#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <vga.h>
#include <scanner.h>

#define MIN(a, b)	((a)<(b)?(a):(b))

main()
{
  int n, fd, r, sl, m, ht, wd, mag = 1;
  struct m105_modeinfo_struct mi;
  unsigned char line[1280], mask;
  unsigned char buf[207];

  if ((fd = open("/dev/scan", O_RDONLY)) < 0) {
    perror("open");
    exit(1);
  }
  if ((ioctl(fd, HSIOCGMOD, &mi)) < 0) {
    perror("ioctl");
    close(fd);
    exit(2);
  }
  printf("Scanner set to %d dpi (%d bytes per scanline)\n", mi.dpi, mi.bpl);

  vga_init();
  if ((r = vga_getdefaultmode()) < 0) {
    fprintf(stderr, "GSVGAMODE environment variable contains no valid mode." \
	    "Please change this.\n");
    close(fd);
    exit(3);
  }
  vga_setmode(r);
  if (vga_getcolors() != 256) {
    fprintf(stderr, "Please select a 256 color mode\n");
    vga_setmode(TEXT);
    close(fd);
    exit(4);
  }
  wd = vga_getxdim();
  ht = vga_getydim();
  vga_setpalette(0, 0, 0, 0);
  vga_setpalette(1, 63, 63, 63);
  for (n = 0; n < sizeof(line); n++)
    line[n] = 0;

  while (1)
    for (sl = 0; sl < ht;) {
      if ((r = read(fd, &buf, mi.bpl)) < 0) {
	vga_setmode(TEXT);
	perror("read");
	close(fd);
	exit(1);
      } else if (r > 0) {
	for (n = 0; n < (MIN(wd >> 3, mi.bpl)); n++) {
	  mask = 0x80;
	  for (r = 0; r < 8; r++) {
	    line[((n << 3) + r)] = ((buf[n] & mask) != 0);
	    mask >>= 1;
	  }
	}
	vga_drawscanline(sl++, line);
      }
    }
}
