#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <scanner.h>

struct scanner_info *scanners[] = { SCANNERS NULL };
struct scanner_info *scanner;

#ifdef HAVE_PNG
#define NAME	"out.png"
#include "png.c"
#else
#define NAME	"out.pgm"
int generate_img(char *name, char *img, int width, int height)
{
	FILE *f;

	f = fopen(name, "w");
	fprintf(f, "P5\n%d %d %d\n", width, height, 255);
	fwrite(img, width, height, f);

	fclose(f);

	return 0;
}
#endif

void sigint_proc(int);

int main (void)
{
	int ret;
	int x, y;
	char *img;
	int i = 0;
	char name[80];

	signal(SIGINT, sigint_proc);

	scanner = scanners[0];
	if (scanner == NULL)
	{
		return 1;
	}

	printf("\n\nConsole scanner demo. Copyright (C) 1998-2008 Neurotechnology\n\n");

	scanner->timeout = 2000;
	ret = scanner->init();
	printf("scanner %s version: %X, dpi: %d, initialization: %d(%s)\n",
		scanner->name, scanner->version, scanner->dpi,
		ret, (ret == 0) ? "success" : "failed");
	if (ret != 0)
	{
		return 1;
	}

	while (1)
	{
		i ++;
		img = (char *)scanner->read(&x, &y);
		if (img)
		{
			sprintf(name, "%04d_"NAME, i);
			generate_img(name, img, x, y);
			printf("scanner image scanned OK\n");
		}
		else
		{
			printf("scanner image scanned FAILED\n");
		}
	}

	return 0;
}

void sigint_proc(int sig)
{
	scanner->close();
	exit(0);
}
