/*
 A small example for my hpscan device.

 This will scan an area of 2x2 inches at 300 dpi and output it to 
 a PBM file. The user interface probably needs some polishing. :-)

 As usual, I really have no idea of what I'm doing, I'm just going
 through the motions. If somebody has any documentation on _what_
 to send to the device, please give me a call. (wingel@ctrl-c.liu.se)

 Some of this shamelessly ripped from:

        hpscanpbm
        User-level SCSI HP Scanjet driver
        Written by David Etherton, etherton@netcom.com
        HPUX Port by John Fehr, fehr@ninja.aes.mb.doe.ca
        Copyright 1994, David Etherton
        Released under the terms of the GPL.
        *NO WARRANTY*
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main(void)
{
  FILE *fp;           
  char buf[8192];
  int n;
  int x, y, b;
  char *p;
  
  if ((fp = fopen("/dev/hpscan", "r+")) == NULL)
  {
    perror("open hpscan");
    exit(1);
  }          
 
  /* reset scanner; returns all paramters to defaults */
  fprintf(fp, "\033E");

  /* set resolution, in DPI */
  fprintf(fp, "\033*a%dR", 300);
  fprintf(fp, "\033*a%dS", 300);

   /* set scan extents, in 1/720'ths of an inch */
  fprintf(fp, "\033*a%dX", 0);
  fprintf(fp, "\033*a%dY", 0);
  fprintf(fp, "\033*a%dP", 3400);     /* x */
  fprintf(fp, "\033*a%dQ", 3000);     /* y */

  /* (the original scanjet only allows -1, 0, or 1) */
  fprintf(fp, "\033*a%dL", 0);
  fprintf(fp, "\033*a%dK", 0);
  fflush(fp);

  /* inquire resulting size of image after setting it up */
  fprintf(fp, "\033*s1024E");
  fflush(fp);
  n = fread(buf, 1, 128, fp);
  p = strchr(buf, 'd') + 1;
  x = atoi(p);
  
  fprintf(fp, "\033*s1025E");
  fflush(fp);
  n = fread(buf, 1, 128, fp);
  p = strchr(buf, 'd')  + 1;
  b = atoi(p);

  fprintf(fp, "\033*s1026E");
  fflush(fp);
  n = fread(buf, 1, 128, fp);
  p = strchr(buf, 'd') + 1;
  y = atoi(p);

  fprintf(stderr, "image size: %d x %d\n", x, y);
  fprintf(stderr, "bytes per scanline: %d\n", b);

  /* begin scan! */
  fprintf(fp, "\033*f0S");
  fflush(fp);

  printf("P4\n%d %d\n", x, y);

  while ((n = fread(buf, 1, sizeof(buf), fp)) > 0)
  {
    putc('.', stderr); 
    fflush(stderr);
    fwrite(buf, n, 1, stdout);
  }
  putc('\n', stderr);

  fclose(fp);
  exit(0);
}
