#ifndef lint
static char *sccsid = "%W% (UKC) %G%";
#endif  lint
/*
 *	Convert Fritzz format pattern files to MG raster format.
 *
 *	Usage: pattoras [file]
 *
 *	To quote Fritzz:
 *	The tiling bitmap can be digitized data, it must be in the form of 
 *	scan lines no longer than 512 bytes followed by newlines.
 *
 *	What he means is that it is a file of ascii characters, where the
 *	pixel values are given by the values of the printable characters
 *	in a line.
 *	It seems to assume that all lines are the same length.
 *	Input lines are guaranteed not to be longer than 512 chars.
 *	You need to take maximum and minimum of input chars to find the range.
 *
 *	Martin Guy, UKC, January 1987
 */

#include <stdio.h>
#include <raster.h>

char *progname;	/* argv[0] for error reporting */

main(argc, argv)
char **argv;
{
	FILE *fp;

	progname = argv[0];

	switch (argc) {
	case 1:
		convert(stdin, "stdin");
		break;
	case 2:
		fp = fopen(argv[1], "r");
		if (fp == NULL) {
			fprintf(stderr, "%s: ", progname);
			perror(argv[1]);
		} else {
			convert(fp, argv[1]);
			fclose(fp);
		}
	}
	exit(0);
}

convert(fp, filename)
FILE *fp;
char *filename;	/* for error reporting */
{
	unsigned char suzie[512][512]; /* ugh, but it's easy */
	pixel_t lb[512];	/* for raster format output */
	pixel_t *linebuf = lb;
	int x, y;		/* for indexing into pattern */
	dimen_t width, height;	/* of image */
	pixel_t	ncolours;	/* in output image */
	unsigned char *line;	/* for quick access to current line in pattern */
	rasfile_t *rf;		/* pointer to output raster file */

	int	k;
	int	big = 0,
		little = 255;
	int	xsue, ysue;
	char	buf[512];
	int	maxx = 0;	/* longest line found */

	/* the following loop was ripped off from fritzz's raytracing program */

	for (ysue = 0;; ysue++) {
		if (fgets (buf, 512, fp) == NULL)
			break;
		xsue = strlen (buf) - 1;/*get rid of EOL tha leaves nasty black dots*/
		if (xsue > maxx) maxx = xsue;
		line = suzie[ysue];
		for (x = 0; x < xsue; x++) {
			k = buf[x];
			line[x] = k;
			if (big < k)
				big = k;
			if (little > k)
				little = k;
		}
	}

	width = maxx; height = ysue; ncolours = big - little + 1;

	rf = rasfpcreate(stdout, width, height, ncolours, 0);

	for (y = 0; y<height; y++) {
		line = suzie[y];
		for (x=0; x<width; x++) {
			/* allow for variable line lengths */
			if (line[x] == 0) linebuf[x] = 0;
			else linebuf[x] = line[x] - little;
		}
		rasputline(linebuf, rf);
	}
	rasclose(rf);
}
