File: scanadf-perl

package info (click to toggle)
libimage-sane-perl 0.14-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 328 kB
  • ctags: 81
  • sloc: perl: 2,714; ansic: 5; makefile: 3
file content (1537 lines) | stat: -rwxr-xr-x 47,249 bytes parent folder | download | duplicates (3)
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
#!/usr/bin/perl                      ## no critic (RequireVersionVar)

use warnings;
use strict;
use feature 'switch';
no if $] >= 5.018, warnings => 'experimental::smartmatch';
use Sane;
use Data::Dumper;
use Getopt::Long qw(:config no_ignore_case pass_through);
use File::Basename;
use IO::Handle;
use English qw( -no_match_vars );    # for $PROGRAM_NAME, $EVAL_ERROR
use Readonly;
Readonly my $BUFFER_SIZE     => ( 32 * 1024 );     # default size
Readonly my $SANE_FRAME_TEXT => 10;
Readonly my $SANE_FRAME_JPEG => 11;
Readonly my $SANE_FRAME_G31D => 12;
Readonly my $SANE_FRAME_G32D => 13;
Readonly my $SANE_FRAME_G42D => 14;
Readonly my $START_COLUMN    => 8;
Readonly my $END_COLUMN      => 80;
Readonly my $INDENT          => 4;
Readonly my $BITS_PER_BYTE   => 8;
Readonly my $MM_PER_CM       => 10;
Readonly my $MM_PER_INCH     => 25.4;
Readonly my $_8_BIT          => 8;
Readonly my $MAXVAL_8_BIT    => 2**$_8_BIT - 1;
Readonly my $_16_BIT         => 16;
Readonly my $MAXVAL_16_BIT   => 2**$_16_BIT - 1;

#$Sane::DEBUG = 1;

my ( %options, @window_val_user, @window_option, @window_val, @window, $device,
    $devname, %option_number );
my $num_dev_options  = 0;
my $verbose          = 0;
my $help             = 0;
my $test             = 0;
my $batch_start_at   = 1;
my $batch_increment  = 1;
my $tl_x             = 0;
my $tl_y             = 0;
my $br_x             = 0;
my $br_y             = 0;
my $w_x              = 0;
my $h_y              = 0;
my $resolution_value = 0;
my $prog_name        = basename($PROGRAM_NAME);
my $no_overwrite     = 0;
my $outputfile = 'image-%04d';    # file name(format) to write output to
my $raw        = SANE_FALSE;
my $scanscript;                   # script to run at end of scan
my $startnum = 1;                 # start/end numbers of pages to scan
my $endnum   = -1;                ## no critic (ProhibitMagicNumbers)
my $SPACE    = q{ };
my $EMPTY    = q{};
my $DASH     = q{-};
my @args     = (
    \%options,
    'd|device-name=s' => \$devname,
    'L|list-devices',
    'h|help'         => \$help,
    'v|verbose+'     => \$verbose,
    'N|no-overwrite' => \$no_overwrite,

    'o|output-file:s' => \$outputfile,
    's|start-count=i' => \$startnum,
    'e|end-count=i'   => \$endnum,
    'r|raw'           => \$raw,
);

sub sane_strframe {
    my $frame = shift;
    my %frame = (
        SANE_FRAME_GRAY  => 'gray',
        SANE_FRAME_RGB   => 'RGB',
        SANE_FRAME_RED   => 'red',
        SANE_FRAME_GREEN => 'green',
        SANE_FRAME_BLUE  => 'blue',
        $SANE_FRAME_TEXT => 'text',
        $SANE_FRAME_JPEG => 'jpeg',
        $SANE_FRAME_G31D => 'g31d',
        $SANE_FRAME_G32D => 'g32d',
        $SANE_FRAME_G42D => 'g42d',
    );
    if ( defined $frame{$frame} ) {
        return $frame{$frame};
    }
    else {
        return 'unknown';
    }
}

sub sane_isbasicframe {
    my $frame = shift;
    return
         $frame == SANE_FRAME_GRAY
      || $frame == SANE_FRAME_RGB
      || $frame == SANE_FRAME_RED
      || $frame == SANE_FRAME_GREEN
      || $frame == SANE_FRAME_BLUE;
}

sub printstdout {
    my ($msg) = @_;
    if ( not print $msg) { die "Error writing to STDOUT\n" }
    return;
}

sub printstderr {
    my ($msg) = @_;
    print {*STDERR} $msg;    ## no critic (RequireCheckedSyscalls)
    return;
}

sub sighandler {
    my $signum = shift;

    if ($device) {
        printstderr("$prog_name: stopping scanner...\n");
        $device->cancel;
    }
    return;
}

sub print_unit {
    my ($unit) = @_;

    given ($unit) {
        when (SANE_UNIT_PIXEL) {
            printstdout('pel');
        }
        when (SANE_UNIT_BIT) {
            printstdout('bit');
        }
        when (SANE_UNIT_MM) {
            printstdout('mm');
        }
        when (SANE_UNIT_DPI) {
            printstdout('dpi');
        }
        when (SANE_UNIT_PERCENT) {
            printstdout(q{%});
        }
        when (SANE_UNIT_MICROSECOND) {
            printstdout('us');
        }
    }
    return;
}

sub print_option {
    ( $device, my $opt_num, my $short_name ) = @_;

    my $opt = $device->get_option_descriptor($opt_num);

    if ($short_name) {
        printf '    -%s', $short_name;
    }
    else {
        printf '    --%s', $opt->{name};
    }

    print_option_choices($opt);
    print_current_option_value( $opt, $opt_num );

    if ( $opt->{type} != SANE_TYPE_BUTTON and $opt->{cap} & SANE_CAP_INACTIVE )
    {
        printstdout(' [inactive]');
    }

    printstdout("\n        ");

    if ( $short_name eq 'x' ) {
        printstdout('Width of scan-area.');
    }
    elsif ( $short_name eq 'y' ) {
        printstdout('Height of scan-area.');
    }
    else {
        my $column     = $START_COLUMN;
        my $last_break = 0;
        my $start      = 0;
        for my $pos ( 0 .. length( $opt->{desc} ) - 1 ) {
            ++$column;
            if ( substr( $opt->{desc}, $pos, 1 ) eq $SPACE ) {
                $last_break = $pos;
            }
            if ( $column >= $END_COLUMN - 1 and $last_break ) {
                while ( $start < $last_break ) {
                    printstdout( substr $opt->{desc}, $start++, 1 );
                }
                $start = $last_break + 1;    # skip blank
                printstdout("\n        ");
                $column = $START_COLUMN + $pos - $start;
            }
        }
        while ( $start < length( $opt->{desc} ) ) {
            printstdout( substr $opt->{desc}, $start++, 1 );
        }
    }
    printstdout("\n");
    return;
}

sub print_option_choices {    ## no critic (ProhibitExcessComplexity)
    my ($opt) = @_;
    if ( $opt->{type} == SANE_TYPE_BOOL ) {
        printstdout('[=(');
        if ( $opt->{cap} & SANE_CAP_AUTOMATIC ) { printstdout('auto|') }
        printstdout('yes|no)]');
    }
    elsif ( $opt->{type} != SANE_TYPE_BUTTON ) {
        printstdout($SPACE);
        if ( $opt->{cap} & SANE_CAP_AUTOMATIC ) {
            printstdout('auto|');
        }
        if ( $opt->{constraint_type} == SANE_CONSTRAINT_NONE ) {
            if ( $opt->{type} == SANE_TYPE_INT ) {
                printstdout('<int>');
            }
            elsif ( $opt->{type} == SANE_TYPE_FIXED ) {
                printstdout('<float>');
            }
            elsif ( $opt->{type} == SANE_TYPE_STRING ) {
                printstdout('<string>');
            }
            if ( $opt->{max_values} > 1 ) { printstdout(',...') }
        }
        elsif ( $opt->{constraint_type} == SANE_CONSTRAINT_RANGE ) {
            my $string_format = '%g..%g';
            if ( $opt->{type} == SANE_TYPE_INT ) { $string_format = '%d..%d' }
            if ( $opt->{name} eq SANE_NAME_SCAN_BR_X ) {
                printf $string_format, $opt->{constraint}{min},
                  $opt->{constraint}{max} - $tl_x;
            }
            elsif ( $opt->{name} eq SANE_NAME_SCAN_BR_Y ) {
                printf $string_format, $opt->{constraint}{min},
                  $opt->{constraint}{max} - $tl_y;
            }
            else {
                printf $string_format, $opt->{constraint}{min},
                  $opt->{constraint}{max};
            }
            print_unit( $opt->{unit} );
            if ( $opt->{max_values} > 1 ) { printstdout(',...') }
            if ( $opt->{constraint}{quant} ) {
                printstdout(" (in steps of $opt->{constraint}{quant})");
            }
        }
        elsif ($opt->{constraint_type} == SANE_CONSTRAINT_STRING_LIST
            or $opt->{constraint_type} == SANE_CONSTRAINT_WORD_LIST )
        {
            for my $i ( 0 .. $#{ $opt->{constraint} } ) {
                if ( $i > 0 ) { printstdout(q{|}) }
                my $string_format =
                  $opt->{type} == SANE_TYPE_FIXED ? '%g' : '%s';

                printf $string_format, $opt->{constraint}[$i];
            }
            if ( $opt->{constraint_type} == SANE_CONSTRAINT_WORD_LIST ) {
                print_unit( $opt->{unit} );
                if ( $opt->{max_values} > 1 ) { printstdout(',...') }
            }
        }
    }
    return;
}

sub print_current_option_value {
    my ( $opt, $opt_num ) = @_;
    if ( $opt->{max_values} == 1 ) {

        # print current option value
        if ( !( $opt->{cap} & SANE_CAP_INACTIVE ) ) {
            my $val = $device->get_option($opt_num);
            printstdout(' [');
            if ( $opt->{type} == SANE_TYPE_BOOL ) {
                printstdout( $val ? 'yes' : 'no' );
            }
            elsif ($opt->{type} == SANE_TYPE_INT
                or $opt->{type} == SANE_TYPE_FIXED )
            {
                my $string_format = '%g';
                if ( $opt->{type} == SANE_TYPE_INT ) { $string_format = '%d' }
                given ( $opt->{name} ) {
                    when (SANE_NAME_SCAN_TL_X) {
                        $tl_x = $val;
                        printf $string_format, $tl_x;
                    }
                    when (SANE_NAME_SCAN_TL_Y) {
                        $tl_y = $val;
                        printf $string_format, $tl_y;
                    }
                    when (SANE_NAME_SCAN_BR_X) {
                        $br_x = $val;
                        $w_x  = $br_x - $tl_x;
                        printf $string_format, $w_x;
                    }
                    when (SANE_NAME_SCAN_BR_Y) {
                        $br_y = $val;
                        $h_y  = $br_y - $tl_y;
                        printf $string_format, $h_y;
                    }
                    default {
                        printf $string_format, $val;
                    }
                }
            }
            elsif ( $opt->{type} == SANE_TYPE_STRING ) {
                printstdout($val);
            }
            printstdout(']');
        }
    }
    return;
}

# A scalar has the following syntax:
#
#     V [ U ]
#
#   V is the value of the scalar.  It is either an integer or a
#   floating point number, depending on the option type.
#
#   U is an optional unit.  If not specified, the default unit is used.
#   The following table lists which units are supported depending on
#   what the option's default unit is:
#
#     Option's unit:	Allowed units:
#
#     SANE_UNIT_NONE:
#     SANE_UNIT_PIXEL:	pel
#     SANE_UNIT_BIT:	b (bit), B (byte)
#     SANE_UNIT_MM:	mm (millimeter), cm (centimeter), in or " (inches),
#     SANE_UNIT_DPI:	dpi
#     SANE_UNIT_PERCENT:	%
#     SANE_UNIT_MICROSECOND:	us

sub parse_scalar {
    my ( $opt, $str ) = @_;

    my ( $v, $unit );
    if (
        $str =~ qr{^
               (\d*[.]?\d*) # value
               (cm|mm|in|["bB%]|dpi|us)? # optional unit
              }xsm
      )
    {
        $v    = $1;
        $unit = $2;
        if ( not defined $unit ) { $unit = $EMPTY }
    }
    else {
        die
"$prog_name: option --$opt->{name}: bad option value (rest of option: $str)\n";
    }

    if ( $opt->{unit} == SANE_UNIT_BIT ) {
        if ( $unit eq 'B' ) { $v *= $BITS_PER_BYTE }
    }
    elsif ( $opt->{unit} == SANE_UNIT_MM ) {
        if ( $unit eq 'cm' ) {
            $v *= $MM_PER_CM;
        }
        elsif ( $unit eq 'in' ) {
            $v *= $MM_PER_INCH;
        }
    }
    return $v, substr $str, length $v + length $unit, length $str;
}

# A vector has the following syntax:
#
#     [ '[' I ']' ] S { [','|'-'] [ '[' I ']' S }
#
#   The number in brackets (I), if present, determines the index of the
#   vector element to be set next.  If I is not present, the value of
#   last index used plus 1 is used.  The first index value used is 0
#   unless I is present.
#
#   S is a scalar value as defined by parse_scalar().
#
#   If two consecutive value specs are separated by a comma (,) their
#   values are set independently.  If they are separated by a dash (-),
#   they define the endpoints of a line and all vector values between
#   the two endpoints are set according to the value of the
#   interpolated line.  For example, [0]15-[255]15 defines a vector of
#   256 elements whose value is 15.  Similarly, [0]0-[255]255 defines a
#   vector of 256 elements whose value starts at 0 and increases to
#   255.

sub parse_vector {
    my ( $opt, $str ) = @_;

    my $index      = -1;       ## no critic (ProhibitMagicNumbers)
    my $prev_value = 0;
    my $prev_index = 0;
    my $separator  = $EMPTY;
    my ( @vector, $value );
    while ( length $str ) {
        if ( $str =~ /^\[(\d+)(\])?/xsm ) {
            $index = $1;
            if ( $2 ne '\]' ) {
                die
                  "$prog_name: option --$opt->{name}: closing bracket missing "
                  . "(rest of option: $str)\n";
            }
        }
        else {
            ++$index;
        }

        if ( $index < 0 or $index >= length $str ) {
            printstderr(
                sprintf
"$prog_name: option --$opt->{name}: index $index out of range [0..%d]\n",
                length $str
            );
            exit 1;
        }

        # read value
        ( $value, $str ) = parse_scalar( $opt, $str );

        if ( $str ne $EMPTY and $str !~ /^[-,]/xsm ) {
            die
"$prog_name: option --$opt->{name}: illegal separator (rest of option: $str)\n";
        }

        # store value:
        $vector[$index] = $value;
        if ( $separator eq $DASH ) {

            # interpolate
            my $v = $prev_value;
            my $slope = ( $value - $v ) / ( $index - $prev_index );

            for my $i ( $prev_index + 1 .. $index - 1 ) {
                $v += $slope;
                $vector[$i] = $v;
            }
        }

        $prev_index = $index;
        $prev_value = $value;
        $separator  = substr $str, 0, 1;
    }

    if ( $verbose > 2 ) {
        printstderr("$prog_name: value for --$opt->{name} is: ");
        for (@vector) {
            printstderr("$_ ");
        }
        printstderr("\n");
    }

    return @vector;
}

sub fetch_options {
    $device = shift;

    # We got a device, find out how many options it has:
    $num_dev_options = $device->get_option(0);
    if ( $Sane::STATUS != SANE_STATUS_GOOD ) {
        die "$prog_name: unable to determine option count\n";
    }

    for my $i ( 0 .. $num_dev_options - 1 ) {
        my $opt = $device->get_option_descriptor($i);

        next if ( !( $opt->{cap} & SANE_CAP_SOFT_SELECT ) );

        $option_number{ $opt->{name} } = $i;

        update_geometry( $opt, $i );

        if ( $opt->{type} == SANE_TYPE_BOOL ) {
            push @args, "$opt->{name}:s";
        }
        elsif ( $opt->{type} == SANE_TYPE_BUTTON ) {
            push @args, $opt->{name};
        }
        else {
            push @args, "$opt->{name}=s";
        }
    }

    # Initialize width & height options based on backend default
    # values for top-left x/y and bottom-right x/y:
    for my $i ( 0 .. 1 ) {
        if ( $window[$i] and $window[ $i + 2 ] and not $window_val_user[$i] ) {
            my $pos = $device->get_option( $window[ $i + 2 ] );
            if ( defined $pos ) { $window_val[$i] = $window_val[$i] - $pos }
        }
    }
    return;
}

# Keep track of top-left corner options (if they exist at
# all) and replace the bottom-right corner options by a
# width/height option (if they exist at all).
sub update_geometry {
    my ( $opt, $i ) = @_;
    if (    ( $opt->{type} == SANE_TYPE_FIXED || $opt->{type} == SANE_TYPE_INT )
        and ( $opt->{unit} == SANE_UNIT_MM || $opt->{unit} == SANE_UNIT_PIXEL )
      )
    {
        given ( $opt->{name} ) {
            when (SANE_NAME_SCAN_TL_X) {
                $window[2] = $i;
                $opt->{name} = 'l';
            }
            when (SANE_NAME_SCAN_TL_Y) {
                $window[3] = $i;      ## no critic (ProhibitMagicNumbers)
                $opt->{name} = 't';
            }
            when (SANE_NAME_SCAN_BR_X) {
                $window[0]                 = $i;
                $opt->{name}               = 'x';
                $window_option[0]          = $opt;
                $window_option[0]->{title} = 'Scan width';
                $window_option[0]->{desc}  = 'Width of scanning area.';
                if ( !$window_val_user[0] ) {
                    $window_val[0] = $device->get_option($i);
                }
            }
            when (SANE_NAME_SCAN_BR_Y) {
                $window[1]                 = $i;
                $opt->{name}               = 'y';
                $window_option[1]          = $opt;
                $window_option[1]->{title} = 'Scan height';
                $window_option[1]->{desc}  = 'Height of scanning area.';
                if ( !$window_val_user[1] ) {
                    $window_val[1] = $device->get_option($i);
                }
            }
        }
    }
    return;
}

sub set_option {
    ( $device, my $optnum, my $value ) = @_;

    my $opt = $device->get_option_descriptor($optnum);
    if ( $opt and ( $opt->{cap} & SANE_CAP_INACTIVE ) ) {
        if ( $verbose > 0 ) {
            warn
"$prog_name: ignored request to set inactive option $opt->{name}\n";
        }
        return;
    }

    my $info = $device->set_option( $optnum, $value );
    if ( $Sane::STATUS != SANE_STATUS_GOOD ) {
        die
"$prog_name: setting of option --$opt->{name} failed ($Sane::STATUS)\n";
    }

    if ( ( $info & SANE_INFO_INEXACT ) and $opt->{max_values} == 1 ) {
        my $orig = $value;
        $value = $device->get_option($optnum);
        if ( $opt->{type} == SANE_TYPE_INT ) {
            printstderr(
                sprintf
                  "$prog_name: rounded value of $opt->{name} from %d to %d\n",
                $orig, $value
            );
        }
        elsif ( $opt->{type} == SANE_TYPE_FIXED ) {
            printstderr(
                sprintf
                  "$prog_name: rounded value of $opt->{name} from %g to %g\n",
                $orig, $value
            );
        }
    }
    if ( $info & SANE_INFO_RELOAD_OPTIONS ) { fetch_options($device) }
    return;
}

sub process_backend_option {
    ( $device, my $optnum, my $optarg ) = @_;

    my $opt = $device->get_option_descriptor($optnum);

    if ( $opt and ( $opt->{cap} & SANE_CAP_INACTIVE ) ) {
        die "$prog_name: attempted to set inactive option $opt->{name}\n";
    }

    if (    ( $opt->{cap} & SANE_CAP_AUTOMATIC )
        and $optarg
        and $optarg =~ /^auto$/ixsm )
    {
        $device->set_auto($optnum);
        if ( $Sane::STATUS != SANE_STATUS_GOOD ) {
            die
"$prog_name: failed to set option --$opt->{name} to automatic ($Sane::STATUS)\n";
        }
        return;
    }

    my $value;
    given ( $opt->{type} ) {
        when (SANE_TYPE_BOOL) {
            $value = 1;    # no argument means option is set
            if ($optarg) {
                if ( $optarg =~ /^yes$/ixsm ) {
                    $value = 1;
                }
                elsif ( $optarg =~ /^no$/ixsm ) {
                    $value = 0;
                }
                else {
                    die
"$prog_name: option --$opt->{name}: bad option value `$optarg'\n";
                }
            }
        }
        when (
                 $opt->{type} == SANE_TYPE_INT
              or $opt->{type} == SANE_TYPE_FIXED
          )
        {
            my @vector = parse_vector( $opt, $optarg );
            $value = \@vector;
        }
        when (SANE_TYPE_STRING) {
            $value = $optarg;
        }
        when (SANE_TYPE_BUTTON) {
            $value = 0;    # value doesn't matter
        }
        default {
            warn "$prog_name: duh, got unknown option type $opt->{type}\n";
            return;
        }
    }
    set_option( $device, $optnum, $value );
    return;
}

sub write_pnm_header_to_file {
    my ( $fh, $frame_format, $width, $height, $depth ) = @_;

    # The netpbm-package does not define raw image data with maxval > 255.
    # But writing maxval 65535 for 16bit data gives at least a chance
    # to read the image.

    if (   $frame_format == SANE_FRAME_RED
        or $frame_format == SANE_FRAME_GREEN
        or $frame_format == SANE_FRAME_BLUE
        or $frame_format == SANE_FRAME_RGB )
    {
        printf {$fh} "P6\n# SANE data follows\n%d %d\n%d\n", $width, $height,
          ( $depth <= $_8_BIT ) ? $MAXVAL_8_BIT : $MAXVAL_16_BIT;
    }
    elsif ( $frame_format == SANE_FRAME_GRAY ) {
        if ( $depth == 1 ) {
            printf {$fh} "P4\n# SANE data follows\n%d %d\n", $width, $height;
        }
        else {
            printf {$fh} "P5\n# SANE data follows\n%d %d\n%d\n", $width,
              $height,
              ( $depth <= $_8_BIT ) ? $MAXVAL_8_BIT : $MAXVAL_16_BIT;
        }
    }
    return;
}

sub scan_it_raw {
    ( my $fname, $raw, my $script ) = @_;

    my $first_frame = 1, my $offset = 0, my $must_buffer = 0;
    my $min = $MAXVAL_8_BIT, my $max = 0;
    my ( %image, $fp );

    my $parm;
    while ( !$parm->{last_frame} ) {
        log_frame_info( $parm, $fp, $fname, $first_frame );

        my ( $must_buffer, $offset ) =
          initialise_scan( $parm, $first_frame, $fp );

        while (1) {
            my ( $buffer, $len ) = $device->read($BUFFER_SIZE);
            if ( $Sane::STATUS != SANE_STATUS_GOOD ) {
                if ( $verbose && $parm->{depth} == $_8_BIT ) {
                    printstderr(
                        sprintf "$prog_name: min/max graylevel value = %d/%d\n",
                        $min, $max
                    );
                }
                if ( $Sane::STATUS != SANE_STATUS_EOF ) {
                    warn "$prog_name: sane_read: $Sane::STATUS\n";
                    return;
                }
                last;
            }

            $offset =
              buffer_data( $fp, $parm, $buffer, $len, \%image, $offset,
                $must_buffer );

            if ( $verbose && $parm->{depth} == $_8_BIT ) {
                for ( split $EMPTY, $buffer ) {
                    my $c = ord;
                    if ( $c >= $max ) {
                        $max = $c;
                    }
                    elsif ( $c < $min ) {
                        $min = $c;
                    }
                }
            }

        }
        $first_frame = 0;
    }

    if ($must_buffer) { write_buffer( $fp, \%image, $parm ) }

    if ($fp) {
        close $fp or die "Error closing file: $EVAL_ERROR\n";
        undef $fp;
    }

  CLEANUP:
    if ($fp) { close $fp or die "Error closing file: $EVAL_ERROR\n" }
    return;
}

sub log_frame_info {
    my ( $parm, $fp, $fname, $first_frame ) = @_;
    $device->start;
    if ( $Sane::STATUS != SANE_STATUS_GOOD ) {
        if ( $Sane::STATUS != SANE_STATUS_NO_DOCS ) {
            warn "$prog_name: sane_start: $Sane::STATUS\n";
        }
        goto CLEANUP;
    }

    $parm = $device->get_parameters;
    if ( $Sane::STATUS != SANE_STATUS_GOOD ) {
        warn "$prog_name: sane_get_parameters: $Sane::STATUS\n";
        goto CLEANUP;
    }

    if ( not open $fp, '>', $fname )    ## no critic (RequireBriefOpen)
    {
        warn "Error opening output `$fname': $EVAL_ERROR\n";
        $Sane::_status =   ## no critic (ProhibitPackageVars ProtectPrivateVars)
          SANE_STATUS_IO_ERROR;
        goto CLEANUP;
    }

    if ($verbose) {
        if ($first_frame) {
            if ( sane_isbasicframe( $parm->{format} ) ) {
                if ( $parm->{lines} >= 0 ) {
                    printstderr(
                        sprintf
                          "$prog_name: scanning image of size %dx%d pixels at "
                          . "%d bits/pixel\n",
                        $parm->{pixels_per_line},
                        $parm->{lines},
                        $_8_BIT * $parm->{bytes_per_line} /
                          $parm->{pixels_per_line}
                    );
                }
                else {
                    printstderr(
                        sprintf
                          "$prog_name: scanning image %d pixels wide and "
                          . "variable height at %d bits/pixel\n",
                        $parm->{pixels_per_line},
                        $_8_BIT * $parm->{bytes_per_line} /
                          $parm->{pixels_per_line}
                    );
                }
            }
            else {
                printstderr(
                    sprintf "$prog_name: receiving %s frame "
                      . 'bytes/line=%d, '
                      . 'pixels/line=%d, '
                      . 'lines=%d, '
                      . "depth=%d\n",
                    ,
                    sane_strframe( $parm->{format} ),
                    $parm->{bytes_per_line},
                    $parm->{pixels_per_line},
                    $parm->{lines},
                    $parm->{depth}
                );
            }
        }

        printstderr( sprintf "$prog_name: acquiring %s frame\n",
            sane_strframe( $parm->{format} ) );
    }
    return;
}

sub initialise_scan {    ## no critic (ProhibitExcessComplexity)
    my ( $parm, $first_frame, $fp ) = @_;
    my ( $must_buffer, $offset );
    if ($first_frame) {
        if (   $parm->{format} == SANE_FRAME_RED
            or $parm->{format} == SANE_FRAME_GREEN
            or $parm->{format} == SANE_FRAME_BLUE )
        {
            if ( $parm->{depth} != $_8_BIT ) {
                die # FIXME: compare message with SANE source, and give them patch if necessary
"Error: frame format $parm->{format}, but image depth=$parm->{depth} (expected 8)\n";
            }
            $must_buffer = 1;
            $offset      = $parm->{format} - SANE_FRAME_RED;
        }
        elsif ( $parm->{format} == SANE_FRAME_RGB ) {
            if ( $parm->{depth} != $_8_BIT ) {
                die # FIXME: compare message with SANE source, and give them patch if necessary
"Error: frame format $parm->{format}, but image depth=$parm->{depth} (expected 8)\n";
            }
        }
        if (   $parm->{format} == SANE_FRAME_RGB
            or $parm->{format} == SANE_FRAME_GRAY )
        {
            if ( ( $parm->{depth} != 1 ) and ( $parm->{depth} != $_8_BIT ) ) {
                die # FIXME: compare message with SANE source, and give them patch if necessary
"Error: frame format $parm->{format}, but image depth=$parm->{depth} (expected 1 or 8)\n";
            }

            # if we're writing raw, we skip the header and never
            # have to buffer a single frame format.
            if ( $raw == SANE_FALSE ) {
                if ( $parm->{lines} < 0 ) {
                    $must_buffer = 1;
                    $offset      = 0;
                }
                else {
                    write_pnm_header_to_file( $fp, $parm->{format},
                        $parm->{pixels_per_line},
                        $parm->{lines}, $parm->{depth} );
                }
            }
        }
        elsif ($parm->{format} == $SANE_FRAME_TEXT
            or $parm->{format} == $SANE_FRAME_JPEG
            or $parm->{format} == $SANE_FRAME_G31D
            or $parm->{format} == $SANE_FRAME_G32D
            or $parm->{format} == $SANE_FRAME_G42D )
        {
            if ( !$parm->{last_frame} ) {
                $Sane::_status ## no critic (ProhibitPackageVars ProtectPrivateVars)
                  = SANE_STATUS_INVAL;
                printstderr(
                    sprintf "$prog_name: bad %s frame: must be last_frame\n",
                    sane_strframe( $parm->{format} ) );
                goto CLEANUP;
            }
        }

        # write them out without a header; don't buffer
        else {

            # Default action for unknown frametypes; write them out
            # without a header; issue a warning in verbose mode.
            # Since we're not writing a header, there's no need to
            # buffer.
            if ($verbose) {
                warn "$prog_name: unknown frame format $parm->{format}\n";
            }
            if ( !$parm->{last_frame} ) {
                $Sane::_status ## no critic (ProhibitPackageVars ProtectPrivateVars)
                  = SANE_STATUS_INVAL;
                printstderr(
                    sprintf "$prog_name: bad %s frame: must be last_frame\n",
                    sane_strframe( $parm->{format} ) );
                goto CLEANUP;
            }
        }
    }
    else {
        die # FIXME: compare message with SANE source, and give them patch if necessary
"Error: frame format $parm->{format}, but expected SANE_FRAME_RED, SANE_FRAME_GREEN, or SANE_FRAME_BLUE\n"
          if ( $parm->{format} < SANE_FRAME_RED
            or $parm->{format} > SANE_FRAME_BLUE );
        $offset = $parm->{format} - SANE_FRAME_RED;
    }
    return $must_buffer, $offset;
}

sub buffer_data {    ## no critic (ProhibitManyArgs)
    my ( $fp, $parm, $buffer, $len, $image, $offset, $must_buffer ) = @_;
    if ($must_buffer) {

        # We're either scanning a multi-frame image or the
        # scanner doesn't know what the eventual image height
        # will be (common for hand-held scanners).  In either
        # case, we need to buffer all data before we can write
        # the image
        if (   $parm->{format} == SANE_FRAME_RED
            or $parm->{format} == SANE_FRAME_GREEN
            or $parm->{format} == SANE_FRAME_BLUE )
        {
            for my $i ( 0 .. $len - 1 ) {
                $image->{data}
                  [ $offset + 3 * $i ]    ## no critic (ProhibitMagicNumbers)
                  = substr $buffer, $i, 1;
            }
            $offset += 3 * $len;          ## no critic (ProhibitMagicNumbers)
        }
        elsif ($parm->{format} == SANE_FRAME_RGB
            or $parm->{format} == SANE_FRAME_GRAY )
        {
            for my $i ( 0 .. $len - 1 ) {
                $image->{data}[ $offset + $i ] = substr $buffer, $i, 1;
            }
            $offset += $len;
        }
        else {

            # optional frametypes are never buffered
            printstderr(
                sprintf "$prog_name: ERROR: trying to buffer %s frametype\n",
                sane_strframe( $parm->{format} ) );
        }
    }
    else {
        if ( not print {$fp} $buffer ) { die "Error writing to file\n" }
    }
    return $offset;
}

sub write_buffer {
    my ( $fp, $image, $parm ) = @_;
    if ( $parm->{lines} > 0 ) {
        $image->{height} = $parm->{lines};
    }
    else {
        $image->{height} = @{ $image->{data} } / $parm->{pixels_per_line};
        if (   $parm->{format} == SANE_FRAME_RED
            or $parm->{format} == SANE_FRAME_GREEN
            or $parm->{format} == SANE_FRAME_BLUE )
        {
            $image->{height} /= 3;    ## no critic (ProhibitMagicNumbers)
        }
    }
    if ( $raw == SANE_FALSE ) {

        # if we're writing raw, we skip the header
        write_pnm_header_to_file( $fp, $parm->{format},
            $parm->{pixels_per_line},
            $image->{height}, $parm->{depth} );
    }
    for ( @{ $image->{data} } ) {
        if ( not print {$fp} $_ ) { die "Error writing to file\n" }
    }
    return;
}

sub scan_docs {
    my ( $start, $end, $outfmt, $script ) = @_;

    $Sane::_status =    ## no critic (ProhibitPackageVars ProtectPrivateVars)
      SANE_STATUS_GOOD;
    my $scannedpages = 0;

    while ( $end < 0 || $start <= $end ) {

        #!!! buffer overflow; need protection
        my $fname = sprintf $outfmt, $start;

        # does the filename already exist?
        if ( $no_overwrite and -r $fname ) {
            $Sane::_status ## no critic (ProhibitPackageVars ProtectPrivateVars)
              = SANE_STATUS_INVAL;
            warn "Filename $fname already exists; will not overwrite\n";
        }

        # Scan the document
        if ( $Sane::STATUS == SANE_STATUS_GOOD ) {
            scan_it_raw( $fname, $raw, $script );
        }

        # Any scan errors?
        if ( $Sane::STATUS == SANE_STATUS_NO_DOCS ) {

            # out of paper in the hopper; this is our normal exit
            $Sane::_status ## no critic (ProhibitPackageVars ProtectPrivateVars)
              = SANE_STATUS_GOOD;
            last;
        }
        elsif ( $Sane::STATUS == SANE_STATUS_EOF ) {

            # done with this doc
            $Sane::_status ## no critic (ProhibitPackageVars ProtectPrivateVars)
              = SANE_STATUS_GOOD;
            warn "Scanned document $fname\n";
            $scannedpages++;
            $start++;
        }
        else {

            # unexpected error
            warn "$Sane::STATUS\n";
            last;
        }
    }

    warn "Scanned $scannedpages pages\n";

    return;
}

sub process_arguments {

    # re-enable error printing and arg permutation
    Getopt::Long::Configure('no_pass_through');

 # There seems to be a bug in Getopt::Long 2.37 where l is treated as L whilst
 # l is not in @args. Therefore the workaround is to rename l to m for the first
 # scan and back to l for the second.
    for (@ARGV) {
        if ( $_ eq '-m' ) { $_ = '-l' }
        if ( $_ eq '-u' ) { $_ = '-t' }
    }
    my @argv_old = @ARGV;
    exit 1 if ( !GetOptions(@args) );

    # As it isn't possible to get the argument order from Getopt::Long 2.37, do
    # this myself
    for (@argv_old) {
        my $ch;
        if (/--(.*)/xsm) {
            $ch = $1;
            my $i = index $ch, q{=};
            if ( $i > -1 ) {    ## no critic (ProhibitMagicNumbers)
                $ch = substr $ch, 0, $i;
            }
        }
        elsif (/-(.)/xsm) {
            $ch = $1;
        }
        else {
            next;
        }
        if ( defined $options{$ch} ) {
            given ($ch) {
                when ('x') {
                    $window_val_user[0] = 1;
                    ( $window_val[0] ) =
                      parse_vector( $window_option[0], $options{x} );
                }
                when ('y') {
                    $window_val_user[1] = 1;
                    ( $window_val[1] ) =
                      parse_vector( $window_option[1], $options{y} );
                }
                when ('l') {    # tl-x
                    process_backend_option( $device, $window[2], $options{l} );
                }
                when ('t') {    # tl-y
                    process_backend_option(
                        $device, $window[3], ## no critic (ProhibitMagicNumbers)
                        $options{t}
                    );
                }
                default {
                    process_backend_option( $device, $option_number{$ch},
                        $options{$ch} );
                }
            }
        }
    }

    for my $index ( 0 .. 1 ) {
        if ( $window[$index] and defined $window_val[$index] ) {
            my $val = $window_val[$index] - 1;
            if ( $window[ $index + 2 ] ) {
                my $pos = $device->get_option( $window[ $index + 2 ] );
                if ( defined $pos ) { $val = $pos + $window_val[$index] }
            }
            set_option( $device, $window[$index], $val );
        }
    }
    return;
}

sub print_options {
    printf "\nOptions specific to device `%s':\n", $devname;

    for my $i ( 0 .. $num_dev_options - 1 ) {
        my $short_name = $EMPTY;

        my $opt = 0;
        for my $j ( 0 .. $INDENT - 1 ) {
            if ( $i == $window[$j] ) {
                $short_name = substr 'xylt', $j, 1;
                if ( $j < 2 ) { $opt = $window_option[$j] }
            }
        }
        if ( !$opt ) { $opt = $device->get_option_descriptor($i) }

        if ( $opt->{type} == SANE_TYPE_GROUP ) {
            printf "  %s:\n", $opt->{title};
        }

        next if ( !( $opt->{cap} & SANE_CAP_SOFT_SELECT ) );

        print_option( $device, $i, $short_name );
    }
    if ($num_dev_options) { printstdout("\n") }
    return;
}

sub list_device_names {
    printf
"Type ``$prog_name --help -d DEVICE'' to get list of all options for DEVICE.\n\nList of available devices:";
    my @device_list = Sane->get_devices;
    if ( $Sane::STATUS == SANE_STATUS_GOOD ) {
        my $column = $END_COLUMN;

        for (@device_list) {
            if ( $column + length( $_->{name} ) + 1 >= $END_COLUMN ) {
                printf "\n    ";
                $column = $INDENT;
            }
            if ( $column > $INDENT ) {
                printstdout($SPACE);
                $column += 1;
            }
            printstdout( $_->{name} );
            $column += length( $_->{name} );
        }
    }
    printstdout("\n");
    return;
}

# There seems to be a bug in Getopt::Long 2.37 where l is treated as L whilst
# l is not in @args. Therefore the workaround is to rename l to m for the first
# scan and back to l for the second.
for (@ARGV) {
    if ( $_ eq '-l' ) { $_ = '-m' }
    if ( $_ eq '-t' ) { $_ = '-u' }
}

# make a first pass through the options with error printing and argument
# permutation disabled:
GetOptions(@args);

if ( defined $options{L} ) {
    my @device_list = Sane->get_devices;
    if ( $Sane::STATUS != SANE_STATUS_GOOD ) {
        die "$prog_name: sane_get_devices() failed: $Sane::STATUS\n";
    }
    for (@device_list) {
        printf "device `%s' is a %s %s %s\n", $_->{name}, $_->{vendor},
          $_->{model}, $_->{type};
    }
    if ( not @device_list ) {
        printf "\nNo scanners were identified. If you were expecting "
          . "something different,\ncheck that the scanner is plugged "
          . "in, turned on and detected by the\nsane-find-scanner tool "
          . "(if appropriate). Please read the documentation\nwhich came "
          . "with this software (README, FAQ, manpages).\n";
    }
    if ( defined $ENV{'SANE_DEFAULT_DEVICE'} ) {
        printf "default device is `%s'\n", $ENV{'SANE_DEFAULT_DEVICE'};
    }
    exit 0;
}

if ( defined $options{V} ) {
    printf "$prog_name (sane-backends) %s\n", Sane->get_version;
    exit 0;
}

if ($help) {
    print <<"EOS";    ## no critic (RequireCheckedSyscalls)
Usage: $prog_name [OPTION]...

Start image acquisition on a scanner device and write image data to
output files.

   [ -d | --device-name <device> ]   use a given scanner device.
   [ -h | --help ]                   display this help message and exit.
   [ -L | --list-devices ]           show available scanner devices.
   [ -v | --verbose ]                give even more status messages.
   [ -V | --version ]                print version information.
   [ -N | --no-overwrite ]           don't overwrite existing files.

   [ -o | --output-file <name> ]     name of file to write image data
                                     (\%d replacement in output file name).
   [ -S | --scan-script <name> ]     name of script to run after every scan.
   [ --script-wait ]                 wait for scripts to finish before exit
   [ -s | --start-count <num> ]      page count of first scanned image.
   [ -e | --end-count <num> ]        last page number to scan.
   [ -r | --raw ]                    write raw image data to file.
EOS
}

if ( !$devname ) {

    # If no device name was specified explicitly,
    # we open the first device we find (if any):
    my @device_list = Sane->get_devices;
    if ( $Sane::STATUS != SANE_STATUS_GOOD ) {
        die "$prog_name: sane_get_devices() failed: $Sane::STATUS\n";
    }
    if ( not @device_list ) {
        die "$prog_name: no SANE devices found\n";
    }
    $devname = $device_list[0]{name};
}

$device = Sane::Device->open($devname);
if ( $Sane::STATUS != SANE_STATUS_GOOD ) {
    warn "$prog_name: open of device $devname failed: $Sane::STATUS\n";
    if ($help) {
        undef $device;
    }
    else {
        exit 1;
    }
}

if ( defined $device ) {
    fetch_options($device);
    process_arguments();

    if ($help) {
        print_options();
    }
}

if ($help) {
    list_device_names();
    exit 0;
}

local $SIG{HUP}  = \&sighandler;
local $SIG{INT}  = \&sighandler;
local $SIG{PIPE} = \&sighandler;
local $SIG{TERM} = \&sighandler;

scan_docs( $startnum, $endnum, $outputfile, $scanscript );

exit $Sane::STATUS;

## no critic (RequirePodSections)
__END__

=head1 NAME

scanadf - acquire multiple images from a scanner equipped with an ADF

=head1 SYNOPSIS

B<scanadf>
B<[ -d | --device-name>
I<dev ]>
B<[ -h | --help ]>
B<[ -L | --list-devices ]>
B<[ -v | --verbose ]>
B<[ -V | --version ]>
B<[ -o | --output-file>
I<name ]>
B<[ -N | --no-overwrite ]>
B<[ -S | --scan-script>
I<name ]>
B<[ --script-wait ] >
B<[ -s | --start-count>
I<num ]>
B<[ -e | --end-count>
I<num ]>
B<[ -r | --raw ]>
I<[ device-specific-options ]>

=head1 DESCRIPTION

B<scanadf>
is a command-line interface to control image acquisition devices which
are capable of returning a series of images (e.g. a scanner with an
automatic document feeder (ADF)).  The device is controlled via
command-line options.  After command-line processing,
B<scanadf>
normally proceeds to acquire a series of images until the device returns
the
B<SANE_STATUS_NO_DOCS>
status code.  

The images are written to output files, specified by the
B<--output-file>
option.  These files are typically written in one of the PNM (portable aNyMaP) 
formats (PBM for black-and-white images, PGM for grayscale images, 
and PPM for color images).  Several optional frame formats (SANE_FRAME_JPEG, 
SANE_FRAME_G31D, SANE_FRAME_G32D, SANE_FRAME_G42D, and SANE_FRAME_TEXT)
are supported.  In each case, the data is written out to the output file
as-is without a header.  Unrecognized frame formats are handled in
the same way, although a warning message is printed in verbose mode.

Typically, the optional frame formats are used in conjunction with a scan 
script (specified by the 
B<--scanscript>
option) which is invoked for each acquired image.  The script is provided
with a series of environment variables which describe the parameters
and format of the image file.

B<scanadf>
accesses image acquisition devices through the SANE (Scanner Access
Now Easy) interface and can thus support any device for which there
exists a SANE backend (try "apropos sane\-" to get a list of available
backends).

=head1 OPTIONS

The
B<-d>
or
B<--device-name>
options must be followed by a SANE device-name.  A (partial) list of
available devices can be obtained with the
B<--list-devices>
option (see below).  If no device-name is specified explicitly,
B<scanadf>
will attempt to open the first available device.

The
B<-h>
or
B<--help>
options request help information.  The information is printed on
standard output and in this case, no attempt will be made to acquire
an image.

The
B<-L>
or
B<--list-devices>
option requests a (partial) list of devices that are available.  The
list is not complete since some devices may be available, but are not
listed in any of the configuration files (which are typically stored
in directory /etc/sane.d).  This is particularly the case when
accessing scanners through the network.  If a device is not listed in
a configuration file, the only way to access it is by its full device
name.  You may need to consult your system administrator to find out
the names of such devices.

The
B<-v>
or
B<--verbose>
options increase the verbosity of the operation of
B<scanadf.>
The option may be specified repeatedly, each time increasing the verbosity
level.

The
B<-V>
or
B<--version>
option requests that
B<scanadf>
print the program and package name, as well as the version number of
the SANE distribution that it came with.

The
B<-o>
or
B<--output-file>
option specifies a format string used to generate the name of file to 
write the image data to.  You can use %d replacement in the output file
name; this will be replaced with the current page number.  The default
format string is image-%04d.

The
B<-N>
or
B<--no-overwrite>
option prevents
B<scanadf >
from overwriting existing image files. 

The
B<-S>
or
B<--scan-script>
option specifies the name of script to run after each scanned image
is acquired.  The script receives the name of the image output file
as its first and only command line argument.  Additionally the scan
script can reference the following environment variables to get 
information about the parameters of the image.

=over

=item B<SCAN_RES>

- the image resolution (in DPI)

=item B<SCAN_WIDTH>

- the image width (in pixels) 

=item B<SCAN_HEIGHT>

- the image height (in pixels)

=item B<SCAN_DEPTH>

- the image bit-depth (in bits)

=item B<SCAN_FORMAT>

- a string representing the image format (e.g. gray, g42d, text, etc)

=item B<SCAN_FORMAT_ID>

- the numeric image format identifier

=back

If the
B<--script-wait>
option is given, scanadf will wait until all scan-scripts have been finished before
exiting. That will be useful if scanadf is used in conjunction with tools to modify
the scanned images.

The
B<-s>
or
B<--start-count>
option specifies the page number of first scanned image.

The
B<-e>
or
B<--end-count>
option specifies the last page number to scan.  Using this option,
you can request a specific number of pages to be scanned, rather than
scanning until there are no more images available.

The
B<-r>
or
B<--raw>
option specifies that the raw image data be written to the output file
as-is without interpretation.  This disables the writing of the PNM
header for basic frame types.  This feature is usually used in 
conjunction with the
B<--scan-script>
option where the scan script uses the environment variables to
understand the format and parameters of the image and converts
the file to a more useful format.  NOTE: With support for the
optional frame types and the default handling of unrecognized
frametypes, this option becomes less and less useful.

As you might imagine, much of the power of
B<scanadf>
comes from the fact that it can control any SANE backend.  Thus, the
exact set of command-line options depends on the capabilities of the
selected device.  To see the options for a device named
I<dev ,>
invoke
B<scanadf>
via a command-line of the form:

=over

scanadf --help --device
I<dev>

=back

The documentation for the device-specific options printed by
B<--help>
is explained in the manual page for
B<scanimage.>

=head1 FILES

=over

=item I</etc/sane.d>

This directory holds various configuration files.  For details, please
refer to the manual pages listed below.

=back

=head1 "SEE ALSO"

scanimage(1), xscanimage(1), sane(7)

=head1 AUTHOR

Transliterated from the C original by Jeffrey Ratcliffe.

=head1 BUGS

All the bugs of scanadf and much, much more.

This program relies on the backend to return the 
B<SANE_STATUS_NO_DOCS>
status code when the automatic document feeder is out of paper.  Use of
this program with backends that do not support ADFs (e.g. flatbed scanners) 
will likely result in repeated scans of the same document.  In this
case, it is essential to use the start-count and end-count to
control the number of images acquired.

Only a subset of the SANE backends support feeders and return
SANE_STATUS_NO_DOCS appropriately.  Backends which are known to
work at this time are:

=over

=item B<sane-bh>

- Bell+Howell Copiscan II series scanners.

=item B<sane-hp>

- Hewlett Packard scanners.  A patch to the sane-hp backend 
is necessary.  The --scantype=ADF option must be specified (earlier
versions of the backend used the --scan-from-adf option, instead).

=item B<sane-umax>

- UMAX scanners.  Support exists in build 12 and later.
The --source="Automatic Document Feeder" option must be specified.

=back