
/*
 * Copyright (C) 2003-2006  Rick Richardson
 * Modified by Paul Newall 2010
 * To decode the file for Kodak ESP nnnn AOI printers
Converts the output for the printer into readable text and optionally an image file.
Useful for understanding files from other drivers, or for checking a driver in development.
 * -
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 *
 * Authors: Rick Richardson 
 * and Paul Newall
 */

/* future mods:
fix possible problem with filename length not being checked and maybe longer than the string allocated.  Added 28/8/11
start including support for ESP Cxxx series
*/

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

/* for jbig */
#include <jbig.h>

/* for gzip */
#include <assert.h>
#include "zlib.h"
#define SET_BINARY_MODE(file)
#define CHUNK 16384

/*
 * Global option flags
 */
int	Version=21;
int	Debug = 0;
int	PrintOffset = 0;
int	PrintHexOffset = 0;

int 	Stripe; //counts the stripes
char	*DecFile = NULL;
char	DefaultDecFile[512];
int	DecFileGiven = 0;
int 	sourcecount=0;


int GZIPTokToRaster(FILE *source, FILE *dest,int width,int height,int bytesperpixel)
{
/* converts source file of inflated GZIP data to a raster file dest */
	int i,prevcode=0,prevvalue=0;
	int repeats = 1;
	int RGBbuffer[15000]; //to reorder the rrrgggbbb data into rgbrgbrgb
	
/* get dimensions colour etc */
	int scale=255;
	int reply=0;
	int CODE_BLANKS=0x0001;
	int CODE_STREAM=0x0000;
	int code=0;
	int value=0;
	int pixelcount=0;

// start dest file
	if(bytesperpixel == 3) fprintf(dest, "P6 %d %d %d\n",width,height,scale);
	else fprintf(dest, "P5 %d %d %d\n",width,height,scale);

	while ((reply != EOF) && (pixelcount<width*height))
	{
		//reply = Read4Byte(source,&code,&value);
		reply=fgetc(source); //fprintf(stdout,"%x ",reply);
		value=reply;
		reply=fgetc(source); //fprintf(stdout,"%x ",reply);
		value+=reply<<8;
		reply=fgetc(source); //fprintf(stdout,"%x ",reply);
		code=reply;
		reply=fgetc(source); //fprintf(stdout,"%x ",reply);
		code+=reply<<8;
		sourcecount+=4;
		if (reply == EOF) break;
		if (((code != prevcode) && (value != prevvalue)) || (pixelcount == 0))	
		{
			fprintf(stdout,"x%d\n<%d code %d value %d>",repeats,sourcecount,code,value); 
			repeats=1;
		}
		else ++repeats; 
//fprintf(stdout,"\n<code %d value %d>",code,value); 
		if (code == CODE_BLANKS) 
		{
			for(i=0;i<value*bytesperpixel;++i)
			{
				fputc(255,dest);
			}
			pixelcount+=value;
			if ((code != prevcode) && (value != prevvalue)) fprintf(stdout,"<blanks>");
			
		}
		else if (code == CODE_STREAM)
		{
			if(bytesperpixel == 3)
			{
				for(i=0;(i<value) && (reply!=EOF);++i) //R
				{
					reply=fgetc(source);
					++sourcecount;
					RGBbuffer[i*3+0]=255-reply;
				}
				for(i=0;(i<value) && (reply!=EOF);++i) //G
				{
					reply=fgetc(source);
					++sourcecount;
					RGBbuffer[i*3+1]=255-reply;
				}
				for(i=0;(i<value) && (reply!=EOF);++i) //B
				{
					reply=fgetc(source);
					++sourcecount;
					RGBbuffer[i*3+2]=255-reply;
				}
				for(i=0;(i<value*bytesperpixel);++i) //output
				{
					fputc(RGBbuffer[i],dest);
				}
			}
			else //(bytesperpixel == 1)
			{
				for(i=0;(i<value) && (reply!=EOF);++i)
				{
					reply=fgetc(source);
					++sourcecount;
					fputc(255-reply,dest);
				}
			}

			pixelcount+=value;
			if ((code != prevcode) && (value != prevvalue)) fprintf(stdout,"<coded %d pixels>",value); 
		}
		else fprintf(stdout,"<unknown at %d>",sourcecount);//unknown purpose
		prevcode=code; 
		prevvalue=value;
	}
	fprintf(stdout,"<made %d pixels of %d>\n",pixelcount,width*height); 
	return 0;
}

/* for gzip
   functions for inflating gzip data are taken directly from 
	zpipe Version 1.4  11 December 2005  Mark Adler */

/* Decompress from file source to file dest until stream ends or EOF.
   inf() returns Z_OK on success, Z_MEM_ERROR if memory could not be
   allocated for processing, Z_DATA_ERROR if the deflate data is
   invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and
   the version of the library linked do not match, or Z_ERRNO if there
   is an error reading or writing the files. */
int inf(FILE *source, FILE *dest)
{
    int ret;
    unsigned have;
    z_stream strm;
    unsigned char in[CHUNK];
    unsigned char out[CHUNK];

    /* allocate inflate state */
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    strm.avail_in = 0;
    strm.next_in = Z_NULL;
    ret = inflateInit(&strm);
    if (ret != Z_OK)
        return ret;

    /* decompress until deflate stream ends or end of file */
    do {
        strm.avail_in = fread(in, 1, CHUNK, source);
        if (ferror(source)) {
            (void)inflateEnd(&strm);
            return Z_ERRNO;
        }
        if (strm.avail_in == 0)
            break;
        strm.next_in = in;

        /* run inflate() on input until output buffer not full */
        do {
            strm.avail_out = CHUNK;
            strm.next_out = out;
            ret = inflate(&strm, Z_NO_FLUSH);
            assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
            switch (ret) {
            case Z_NEED_DICT:
                ret = Z_DATA_ERROR;     /* and fall through */
            case Z_DATA_ERROR:
            case Z_MEM_ERROR:
                (void)inflateEnd(&strm);
                return ret;
            }
            have = CHUNK - strm.avail_out;
            if (fwrite(out, 1, have, dest) != have || ferror(dest)) {
                (void)inflateEnd(&strm);
                return Z_ERRNO;
            }
        } while (strm.avail_out == 0);

        /* done when inflate() says it's done */
    } while (ret != Z_STREAM_END);

    /* clean up and return */
    (void)inflateEnd(&strm);
    return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}

/* report a zlib or i/o error */
void zerr(int ret)
{
    fputs("zpipe: ", stderr);
    switch (ret) {
    case Z_ERRNO:
        if (ferror(stdin))
            fputs("error reading stdin\n", stderr);
        if (ferror(stdout))
            fputs("error writing stdout\n", stderr);
        break;
    case Z_STREAM_ERROR:
        fputs("invalid compression level\n", stderr);
        break;
    case Z_DATA_ERROR:
        fputs("invalid or incomplete deflate data\n", stderr);
        break;
    case Z_MEM_ERROR:
        fputs("out of memory\n", stderr);
        break;
    case Z_VERSION_ERROR:
        fputs("zlib version mismatch!\n", stderr);
    }
}


void
debug(int level, char *fmt, ...)
{
/* Prints the list of variables to stderr using fmt, if Debug>=level */
    va_list ap;

    if (Debug < level)
	return;

    va_start(ap, fmt);
    vfprintf(stderr, fmt, ap);
    va_end(ap);
}

int
error(int fatal, char *fmt, ...)
{
	va_list ap;

	fprintf(stderr, fatal ? "Error: " : "Warning: ");
	if (errno)
	    fprintf(stderr, "%s: ", strerror(errno));
	va_start(ap, fmt);
	vfprintf(stderr, fmt, ap);
	va_end(ap);
	if (fatal > 0)
	    exit(fatal);
	else
	{
	    errno = 0;
	    return (fatal);
	}
}

void
usage(void)
{
    fprintf(stderr,
"Usage:\n"
"	myopldecode [options] < opl-file\n"
"\n"
"	Decode a Kodak Raster Object (opl) stream into human readable form.\n"
"\n"
"	A Kodak Raster Object stream is the printer langauge used by some Kodak\n"
"	printers, such as the ESP 5250.\n"
"\n"
"\n"
"Options:\n"
"       -d basename Basename of .pbm file for saving decompressed planes\n"
"       -o          Print file offsets\n"
"       -h          Print hex file offsets\n"
"       -D lvl      Set Debug level [%d]\n"
    , Debug
    );

    exit(1);
}

void
print_bih(unsigned char bih[20])
{
/* prints the header of a bih */
    unsigned int i, xd, yd, l0;
    char hdr[] = "\n\t\t\t\t";

    if (!PrintOffset && !PrintHexOffset) hdr[strlen(hdr)-1] = 0;

    xd = (bih[4] << 24) | (bih[5] << 16) | (bih[6] << 8) | (bih[7] << 0);
    yd = (bih[8] << 24) | (bih[9] << 16) | (bih[10] << 8) | (bih[11] << 0);
    l0 = (bih[12] << 24) | (bih[13] << 16) | (bih[14] << 8) | (bih[15] << 0);
    for(i=0;i<20;++i)
    {
    	printf("%3x",bih[i]);
    }

    printf("%sDL = %d, D = %d, P = %d, - = %d, XY = %d x %d",
	 hdr, bih[0], bih[1], bih[2], bih[3], xd, yd);

    printf("%sL0 = %d, MX = %d, MY = %d",
	 hdr, l0, bih[16], bih[17]);

    printf("%sOrder   = %d %s%s%s%s%s", hdr, bih[18],
	bih[18] & JBG_HITOLO ? " HITOLO" : "",
	bih[18] & JBG_SEQ ? " SEQ" : "",
	bih[18] & JBG_ILEAVE ? " ILEAVE" : "",
	bih[18] & JBG_SMID ? " SMID" : "",
	bih[18] & 0xf0 ? " other" : "");

    printf("%sOptions = %d %s%s%s%s%s%s%s%s", hdr, bih[19],
	bih[19] & JBG_LRLTWO ? " LRLTWO" : "",
	bih[19] & JBG_VLENGTH ? " VLENGTH" : "",
	bih[19] & JBG_TPDON ? " TPDON" : "",
	bih[19] & JBG_TPBON ? " TPBON" : "",
	bih[19] & JBG_DPON ? " DPON" : "",
	bih[19] & JBG_DPPRIV ? " DPPRIV" : "",
	bih[19] & JBG_DPLAST ? " DPLAST" : "",
	bih[19] & 0x80 ? " other" : "");
    printf("%s%u stripes, %d layers, %d planes",
	hdr,
	((yd >> bih[1]) +  ((((1UL << bih[1]) - 1) & xd) != 0) + l0 - 1) / l0,
	bih[1] - bih[0], bih[2]);
}

void
print_config(unsigned char *c)
{
    char hdr[] = "\n\t\t\t\t";

    if (!PrintOffset && !PrintHexOffset) hdr[strlen(hdr)-1] = 0;

    if (c[1] == 1)
    {
	printf("%sfmt=%d np=%d",
	    hdr, c[0], c[1]);
	printf("%sBLACK:	X=%d, Y=%d, unk=%d, #=%d(%d)",
	    hdr, (c[2]<<8) + c[3], (c[4]<<8) + c[5], c[6], 1 << c[7], c[7]);
    }
    else if (c[1] == 4)
    {
	printf("%sfmt=%d np=%d",
	    hdr, c[0], c[1]);
	printf("%sYEL:	X=%d, Y=%d, unk=%d, #=%d(%d)",
	    hdr, (c[2]<<8) + c[3], (c[4]<<8) + c[5], c[6], 1 << c[7], c[7]);
	printf("%sMAG:	X=%d, Y=%d, unk=%d, #=%d(%d)",
	    hdr, (c[8]<<8) + c[9], (c[10]<<8) + c[11], c[12], 1 << c[13], c[13]);
	printf("%sCYA:	X=%d, Y=%d, unk=%d, #=%d(%d)",
	    hdr, (c[14]<<8) + c[15], (c[16]<<8) + c[17], c[18], 1 << c[19], c[19]);
	printf("%sBLK:	X=%d, Y=%d, unk=%d, #=%d(%d)",
	    hdr, (c[20]<<8) + c[21], (c[22]<<8) + c[23], c[24], 1 << c[25], c[25]);
    }
    else
	error(1, "config image data is not 8 or 26 bytes!\n");
}

void
proff(int curOff)
{
    if (PrintOffset)
	printf("%d:	", curOff);
    else if (PrintHexOffset)
	printf("%6x:	", curOff);
}

int
fgetoplsmt(char *smt, int size, int *datalen, FILE *stream)
{
/* opl statement fetcher, will work properly if compressed data contains ; or ? or #
	since it does not read the compressed data.
	Get a string terminated by ; or ? or # from stream
	The string is returned in smt with a null terminator.
	size is the size of smt.
	if the string is followed by an integer delimited by # and =, datalen returns the integer (length of the data)
	smt will not contain any compressed data, you must read that later.
	The function returns 1 if sucessful, 0 if EOF encountered, or size is exceeded.
*/
    	int	c; /* for reading bytes one at a time */
    	char *s = smt; /* s will move along the string */
	int maxdatalen = 100000;

    	*datalen = 0;
    	while (((c = fgetc(stream)) != EOF) && (s-smt < size))
    	{
		*s++ = c;
		if (c == ';' || c == '?' || c == '#')   break;
    	}
	if (c == '#') //expect an int next, terminated by =, that gives the no of bytes in the following data
	{
	    while (((c = fgetc(stream)) != EOF) && (s-smt < size) && (*datalen < maxdatalen))
	    {
		if ((c >= '0') && (c <= '9')) /* c is a digit */
		{
			*s++ = c; /* maybe not add to string ? */
		    *datalen *= 10;
		    *datalen += c - '0';
		}
		else break;
	    }
	}

    	*s++ = 0; /* null termimator for string */
    	if ((c == EOF) || (s-smt >= size)) return (0);
    	else return (1);
}

char *
fgetcomma(char *s, int size, int *datalen, FILE *stream)
{
	//get a string terminated by ; or ? from stream
	//the string is returned in  s
	//size is not used?
	//if the string has an integer delimited by # and =, datalen returns the integer (length of the data)
	//extents might be 10 chars per line, so s should be > 12800 chars
    int	c;
    char *os = s;

    *datalen = 0;
    while ((c = fgetc(stream)) != EOF)
    {
	*s++ = c;
	if (c == ';' || c == '?')
	    break;
	if (c == '#') //expect an int next, terminated by =, that gives the no of bytes in the following JBIG
	{
	    while ((c = fgetc(stream)) != EOF)
	    {
		*s++ = c;
		if (c == '=')
		    break;
		else
		{
		    *datalen *= 10;
		    *datalen += c - '0';
		}
	    }
	    break;
	}
    }
    if (c == EOF)
	return (NULL);
    *s++ = 0;
    return (os);
}

int
jbig_write_file( int pn, int page, struct jbg_dec_state *pstate, FILE *dfp)
//attempts to write image, finished or not
{
		printf("<jbig_write_file starts>\n");
   // size_t	cnt;
    int		rc;
	
	int     h, w, x1, x2, y, wBytes, len;
	unsigned char *image=NULL;

	//h = jbg_dec_getheight(pstate);
	h=pstate->l0 * (Stripe); //band height may not be right with multiple stripes
	w = jbg_dec_getwidth(pstate);
	image = jbg_dec_getimage(pstate, 0); //is the first plane 1 or 0?
	//len = jbg_dec_getsize(pstate);
	wBytes=(w+7)/8;
	len = ((w+7)/8)*h; 
	if (image !=NULL)
	{
	    char        buf[512];
	    sprintf(buf, "%s-p%02d-s%02d.pbm", DecFile, page, Stripe);
		printf("<write_file writing raster to %s...>\n", buf);
	    dfp = fopen(buf, "w");
	    if (dfp)
	    {
		fprintf(dfp, "P4\n%8d %8d\n", w, h);
		rc = fwrite(image, 1, len, dfp);
		fclose(dfp);
	    }
		else return (1);
	//look for zone widths
		printf("<seeking zones>\n");
		for(y=0;y<h;y+=10)
		{
			for(x1=0;image[wBytes*y+x1]==0 && x1<wBytes;++x1);
			for(x2=x1+wBytes/5;image[wBytes*y+x2]==0 && x2<wBytes;++x2);
			printf("%d,",x2-x1);
		}
		printf("\n");

	}
	else   
	{
		debug(0, "Missing image %dx%d!\n", w, h);
		printf("<s.d = %d, s.ii[0] = %d>\n", pstate->d, (int) pstate->ii[0]);		

	}
	jbg_dec_free(pstate);
	return (0);
    
}

int
jbig_zone_widths( int pn, int page, struct jbg_dec_state *pstate, FILE *dfp)
//attempts to detect the colour zone widths 
{
		printf("<jbig_zone_widths starts>");
   // size_t	cnt;
    //int		rc;
	
	int     h, w, x1, x2, y,wBytes;
	unsigned char *image=NULL;

	h=pstate->l0 * (Stripe); //band height may not be right with multiple stripes
	w = jbg_dec_getwidth(pstate);
	image = jbg_dec_getimage(pstate, 0);
	wBytes=(w+7)/8;
	//len = ((w+7)/8)*h; 
	if (image !=NULL)
	{
		printf("<image found - seeking zones>\n");
		for(y=0;y<h;y+=10)
		{
			for(x1=0;image[wBytes*y+x1]==0 && x1<wBytes;++x1);
			for(x2=x1+wBytes/5;image[wBytes*y+x2]==0 && x2<wBytes;++x2);
			printf("%d,",x2-x1);
		}
		printf("\n");
		
	}
	else   
	{
		debug(0, "Missing image! wxh= %dx%d!\n", w, h);
		printf("<s.d = %d, s.ii[0] = %d>\n", pstate->d, (int) pstate->ii[0]);		

	}
	jbg_dec_free(pstate);
	return (0);
}

int
jbig_decode1(unsigned char ch, int pn, int page, struct jbg_dec_state *pstate, FILE *dfp)
//called for every char in the JBIG
{
    size_t	cnt;
    int		rc;
//	printf(".");
    	rc = jbg_dec_in(pstate, &ch, 1, &cnt);
    	if (rc == JBG_EOK || rc == JBG_EOK_INTR) //the image is finished
    	{
		int     h, w, len;
		unsigned char *image=NULL;
		printf("\n<complete image found>\n");

		//debug(0, "JBG_EOK: %d\n", pn);
		h = jbg_dec_getheight(pstate);
		w = jbg_dec_getwidth(pstate);
		image = jbg_dec_getimage(pstate, 0); //is the first plane 1 or 0?
		len = jbg_dec_getsize(pstate);
		if (image !=NULL)
		{
	    		char        buf[512];
	    		sprintf(buf, "%s-%02d-%d.pbm", DecFile, page, pn);
			printf("<\ndecode1 writing raster to %s...>\n", buf);
	    		dfp = fopen(buf, "w");
	    		if (dfp)
	    		{
		    		fprintf(dfp, "P4\n%8d %8d\n", w, h);
				rc = fwrite(image, 1, len, dfp);
				fclose(dfp);
	    		}
		}
		else debug(0, "Missing image %dx%d!\n", h, w);

		++Stripe;
		printf("<Start new stripe no %d>\n",Stripe);
//	jbg_dec_free(pstate);
    	}
	else //its a data byte
	{
		if(rc == JBG_EAGAIN) printf("%3x",ch);
		else printf("<PROBLEM IN DECODING %s>\n", jbg_strerror(rc)); //add some error message 
	}
		return (rc);
}

void
decode(FILE *fp)
{
    int		bitsperpixel,h,w,c,i;
    int		rc=0;
	int	FirstData; //the position of the first data byte in compressed data. In JBIG data the first stripe has a 20 bytes header, and FirstData=21.
    FILE	*dfp = NULL;
    FILE	*ifp = NULL;
    FILE	*rfp = NULL;
    int		pageNum = 1;
    int		curOff = 0;
    struct jbg_dec_state	s[5];
    unsigned char	bih[20];
    int			bihlen = 0;
    int         	pn = 1;//was 0 but I took out the ++pn
    int			totSize = 0;
	char		buf[15000];
    	int		datalen; //size of image , size of BIE
	char 		cmpmethod[20];
	char 		colourspace[20];
	char        zname[512]; //for compressed filename
	char        iname[512]; //for inflated filename
	char        rname[512]; //for inflated filename

    Stripe = 0;
	while (fgetcomma(buf, sizeof(buf), &datalen, fp)) 	//get a string in buf terminated by ; or ? and return datalen
	{
		proff(curOff); curOff += strlen(buf);
		if (strncmp(buf, "RasterObject.Data", 17) == 0)  
		{
			printf("RasterObject.Data#%d=\n", datalen);
	    		curOff += datalen + 1;
	    		totSize += datalen;
			if (strncmp(cmpmethod, "JBIG", 4) == 0) 
			{
				/* Handle JBIG data */
				printf("<JBIG data>");
				printf("<Stripe %d>\n",Stripe);
		// In Kodak jbig files the header is the first 20 bytes in the data of the first stripe.
				if(Stripe == 0)
				{
					rc = fread(bih, bihlen = sizeof(bih), 1, fp);
					print_bih(bih);
					printf("\n");
		//		getc(fp); //is this for the ; at the end of the header?
					if (DecFileGiven)
					{
					//initialize the JBIG decode
						size_t      cnt;
						jbg_dec_init(&s[pn]);
						rc = jbg_dec_in(&s[pn], bih, bihlen, &cnt);
						if (rc == JBG_EIMPL) error(1, "JBIG uses unimpl feature\n");
						h = jbg_dec_getheight(&s[pn]);
						w = jbg_dec_getwidth(&s[pn]);
						printf("<initialised decode and read header, image is %dx%d>\n",w,h);
					}
				}
		//in kodak jbig files there's data following the header
				if (datalen > 20 && Stripe == 0) FirstData = 21;
				else FirstData = 1;
				unsigned char ch;
//jbg_dec_maxsize(&s[pn], s[pn].xd, s[pn].l0); //set the size to the size of one stripe
				printf("<decoding JBIG stripe start %d datalen %d>\n",FirstData, datalen);
				h = jbg_dec_getheight(&s[pn]);
				w = jbg_dec_getwidth(&s[pn]);

				for(i=FirstData;i<=datalen;++i)
				{
					c = getc(fp);
					ch = c;
					if(i==FirstData) 
					{
						printf("<First byte has been read>\n");
						printf("<DecFile=%s ch=%d pn=%d pageNum=%d >\n",DecFile,ch,pn,pageNum);
					}
					if (DecFileGiven)  jbig_decode1(ch, pn, pageNum, &s[pn], dfp);
		 		}

				c = getc(fp); //for the ; at the end of the data?
				if(c == ';') 
				{
					printf("<Data has been read, terminated OK>\n");
				}
				else printf("<Data has been read, but unexpected terminator>\n");

				//jbig_write_file(pn, pageNum, &s[pn], dfp);
				++Stripe;
				printf("<Start new stripe no %d>\n",Stripe);

			} // end of handle JBIG

/* GZIP section */
			else if (strncmp(cmpmethod, "GZIPTok", 7) == 0) 
			{
				printf("<GZIP data>\n");

				if(Stripe == 0)
				{
					if (DecFileGiven)
					{
					//initialize the GZIP decode

					/* for now just write to a file */
	    					sprintf(zname, "%s-p%02d.z", DecFile, pageNum);
	    					sprintf(iname, "%s-p%02d.out", DecFile, pageNum);
						printf("<writing gzip file to %s...>\n", zname);
	    					dfp = fopen(zname, "w");
					}
				}
				FirstData = 1;
				//unsigned char ch; //ch may not be needed 17/12/13
				printf("<decoding GZIP datalen %d>\n", datalen);

				for(i=FirstData;i<=datalen;++i)
				{
					c = getc(fp);
					//ch = c; //ch may not be needed 17/12/13
					if(i==FirstData) 
					{
						printf("<First byte has been read>\n");
						printf("<DecFile=%s pn=%d pageNum=%d >\n",DecFile,pn,pageNum);
					}
//printf("<Byte %d>\n",i);
					/* for now just write to a file */
					if (DecFileGiven && dfp)  rc = putc(c,dfp);

		 		}
	    			if (dfp) fclose(dfp);

				c = getc(fp); //for the ; at the end of the data?
				if(c == ';') 
				{
					printf("<Data has been read, terminated OK>\n");
					/*inflate the file */
					printf("<inflating gzip %s to %s>\n", zname,iname);
	    				dfp = fopen(zname, "r");
	    				ifp = fopen(iname, "w");
					if (dfp && ifp)
					{
						rc = inf(dfp, ifp);
	    					fclose(dfp);
	    					fclose(ifp);
					}
					else printf("<could not open gzip data file or inflated data file>");
					if (rc == Z_OK)
					{
						printf("<inflation OK>\n");
						/* check we can decode this type */
						if(bitsperpixel==8)
//						if((bitsperpixel==8) && (strncmp(colourspace, "Mono;", 5) == 0))
						{

	    					ifp = fopen(iname, "r");

						if(strncmp(colourspace, "Mono;", 5) == 0) 
						{
	    						sprintf(rname, "%s-p%02d.pgm", DecFile, pageNum);
	    						rfp = fopen(rname, "w");
							GZIPTokToRaster(ifp,rfp,w,h,1);
							printf("<rasterizing inflated gzip %s to %s>\n", iname,rname);
						}
						else 
						{
	    						sprintf(rname, "%s-p%02d.ppm", DecFile, pageNum);
	    						rfp = fopen(rname, "w");
							GZIPTokToRaster(ifp,rfp,w,h,3);
							printf("<rasterizing inflated gzip %s to %s>\n", iname,rname);
						}

	    					if (ifp) fclose(ifp);
	    					if (rfp) fclose(rfp);
						}
						else
						{
						printf("<cannot rasterize gzip bpp=%d colour=%s>\n", bitsperpixel, colourspace);
						}
					}
					else printf("<inflation failed>\n");
				}
				else printf("<Data has been read, but unexpected terminator>\n");
				++Stripe;
				printf("<Start new stripe no %d>\n",Stripe);


			} //end of handle GZIP
			else 
			{
				//unknown compression method
				printf("<unknown comp method =%s>\n",cmpmethod);
			}
		} //end of compressed data
	else 
	{
		printf("%s\n", buf);

	if (strncmp(buf, "LockPrinter", 11) == 0) {
	}
	else if (strncmp(buf, "Event=StartOfJob", 16) == 0) {
	}
	else if (strncmp(buf, "DeviceStatus", 12) == 0) {
	}
	else if (strncmp(buf, "DeviceSettings.System", 21) == 0) {
	}
	else if (strncmp(buf, "DeviceSettings", 14) == 0) {
	}
	else if (strncmp(buf, "DeviceStatus", 11) == 0) {
	}
	else if (strncmp(buf, "Event=EndOfPage", 15) == 0) {
	    Stripe = 0;
	    ++pageNum;
	}
	else if (strncmp(buf, "RasterObject.BitsPerPixel", 25) == 0) {
	    sscanf(buf+26, "%d", &bitsperpixel);
	    debug(1, "bitsperpixel=%d\n", bitsperpixel);
	}
	else if (strncmp(buf, "RasterObject.Planes", 19) == 0) {
	    int pl;
	    sscanf(buf+20, "%x", &pl);
	    debug(1, "planes=%x\n", pl);
	}
	else if (strncmp(buf, "RasterObject.Compression", 24) == 0) {
	    sscanf(buf+25, "%s", cmpmethod);
	    debug(1, "compression=%s\n", cmpmethod);
		printf("<comp method =%s>\n",cmpmethod);
	}
	else if (strncmp(buf, "RasterObject.Colorspace", 23) == 0) {
	    sscanf(buf+24, "%s", colourspace);
	    debug(1, "colourspace=%s\n", colourspace);
		printf("<colourspace =%s>\n",colourspace);
	}
	else if (strncmp(buf, "RasterObject.Width", 18) == 0) {
	   // int w;
	    sscanf(buf+19, "%d", &w);
	    debug(1, "width=%d\n", w);
	}
	else if (strncmp(buf, "RasterObject.Height", 19) == 0) {
	    //int h;
	    sscanf(buf+20, "%d", &h);
	    debug(1, "height=%d\n", h);
	}
	else if (strncmp(buf, "RasterObject.Extent=true", 19) == 0) {
	    int Commas = 0;
		for(i=0;i<sizeof(buf) && buf[i] != 0;++i) 
		{ 
			if(buf[i] == ',') 
			{
				++Commas;
				//printf("X");
			}
		}
		printf("<Extents = %d, Height = %d>\n",(Commas)/2,h);
		} //end of non data items
	}
    } //end of while there are statements
//try to identify the width of the colour zones
//jbig_zone_widths(pn, pageNum, &s[pn], dfp);
//try to write the file
	if (strncmp(cmpmethod, "JBIG", 4) == 0) 
	{
		jbig_write_file(pn, pageNum-1, &s[pn], dfp);
		jbg_dec_free(&s[pn]);
	}
	else if (strncmp(cmpmethod, "GZIPTok", 7) == 0) 
	{
/* write file and close the decompression */

	}
} //end of function decode

int
main(int argc, char *argv[])
{
	extern int	optind;
	extern char	*optarg;
	int		c;

	printf("myopldecode version %d\n\n",Version);
	sprintf(DefaultDecFile,"myopldecode");
	DecFile = DefaultDecFile;
	DecFileGiven =1;

	while ( (c = getopt(argc, argv, "d:hoD:?h")) != EOF)
		switch (c)
		{
		case 'd': DecFile = optarg; 
		printf("<will write raster to %s....>\n", DecFile);
		DecFileGiven =1;
		break;
		case 'o': PrintOffset = 1; break;
		case 'h': PrintHexOffset = 1; break;
		case 'D': Debug = atoi(optarg); break;
		default: usage(); exit(1);
		}

	argc -= optind;
	argv += optind;

        if (argc > 0)
        {
            FILE        *fp;

            fp = fopen(argv[0], "r");
            if (!fp)
                error(1, "file '%s' doesn't exist\n", argv[0]);
            for (;;)
            {
                decode(fp);
                c = getc(fp); ungetc(c, fp);
                if (feof(fp))
                    break;
            }
            fclose(fp);
        }
        else
        {
	    for(;;)
	    {
		decode(stdin);
		printf("Returned from decode\n");
		c = getc(stdin); ungetc(c, stdin);
		if (feof(stdin))
		    break;
	    }
	}
	printf("\n");

	exit(0);
}
