#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <scanner.h>

/*
 *	usage: testscan [lines]
 *
 *	Reads an image (mono only) from the scanner device,
 *	number of lines determined by arg, or, if not given,
 *	two inches.  Writes a pnm (portable bitmap) file to
 *	stdout.  Redirect into a file and use xv/xloadimage
 *	to view it, or the PBM+ utilities to convert it.
 *
 *	(C) 1993 Richard Lyons.
 */

static	char	*scanner = "/dev/scanner";

struct modeinfo_struct info;

int
main(int argc, char **argv)
{
	int fd, lines, bytes, i;
	unsigned char *buf, *p;
	
	if ((fd = open(scanner, O_RDONLY)) < 0) {
		perror(scanner);
		exit(1);
	}
	if (ioctl(fd, HSIOCGMOD, &info) < 0) {
		perror("ioctl");
		exit(2);
	}
	fprintf(stderr, "DPI=%d, BPL=%d\n", info.ydpi, info.bpl);
	lines = (argc == 2) ? atoi(*++argv) : info.ydpi * 2;
	bytes = lines * info.bpl;
	if ((buf = malloc(bytes)) == NULL) {
		fprintf(stderr, "couldn't allocate %d bytes\n", bytes);
		exit(4);
	}
	bytes = read(fd, buf, bytes);
	close(fd);
	if (bytes > 0) {
		for (i = bytes, p = buf; i--; ++p)
			*p ^= 0xFF;
		printf("P4\n%d %d\n", info.bpl * 8, lines);
		fwrite(buf, 1, bytes, stdout);
	}
	return(0);
}

