File: myopldecode.c

package info (click to toggle)
c2esp 24-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 704 kB
  • sloc: ansic: 6,108; makefile: 219; sh: 46; python: 8
file content (939 lines) | stat: -rw-r--r-- 25,165 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939

/*
 * 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,prevvalue;
	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;
	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;
				printf("<decoding GZIP datalen %d>\n", datalen);

				for(i=FirstData;i<=datalen;++i)
				{
					c = getc(fp);
					ch = c;
					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);
}