File: c2esp.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 (1002 lines) | stat: -rw-r--r-- 36,874 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
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
/* 
 *
 *   Kodak ESP 5xxx (OPL?) Control Language filter for the  Common UNIX
 *   Printing System (CUPS)
 *
 *  copyright Paul Newall May 2010 - Jan2012. VERSION 2.4 (c2esp24) 
 *  patch by user awl29 applied to fix problems with non bi-directional printers, smb shared
 *  data chunk size limit applied
 *
 *  Params: job-id user title copies options [file]
 *  options = "noback" disables all calls to the back channel for testing.
 *
 
This filter is based on:
the structure of the rastertohp filter supplied with cups
the JBIG library by Markus Kuhn
 */

#define DEBUGFILES 0 /* DEBUGFILES 1 creates files in /tmp to help debug */
#define TESTING 0 /* TESTING 1 suppresses the output to the printer */
#define MAXJBIGDATACHUNK 65511 /* some printers can't handle more than 65K at a time */

#include <cups/raster.h>
#include <cups/sidechannel.h> //FlushBackChannel, and the side channel functions and constants
#include <fcntl.h> //files
#include <sys/stat.h>
#include <signal.h>
#include <errno.h>
#include "jbig85.h" //the reduced jbig library
#include <cups/driver.h> //has the dither functions
#include <time.h> //time functions used for debugging
#include "c2espcommon.h" //the common library

/*
 * Constants...
 */
char	*Version = "c2esp24";
unsigned char ESC = 255;
int StripeHeightMax = 1280; //the max height of a stripe. (Windows 300x1200 files have 1920)
const float	default_lut[3] = {0.0, 0.7, 1.0}; //default {0.0, 0.5, 1.0}, {0.0, 0.7, 1.0} seems to work OK

/*
 * Globals...
 */
unsigned char	*RasSpace;		/* Output buffer with space before start for previous lines */
unsigned char	*RasForComp;		/* Output buffer */
unsigned char	*CupsLineBuffer;	//buffer for one line of the cups raster
unsigned char	*DitherOutputBuffer;	//buffer for output of the dither
short		*DitherInputBuffer;	//buffer for input to the dither 
unsigned char	*CompStripeBuffer;	//buffer for one compressed stripe
char		KodakPaperSize[50];  	/* String that the printer expects for paper size */
int		CompStripeBufferFree,	//free pointer for buffer
		OutBitsPerPixel,	/* Number of bits per color per pixel for printer*/
		RasForCompWidth,		//width of raster that is compessed and sent to printer
		Duplex,			/* Current duplex mode */
		Page,			/* Current page number */
		Canceled,		/* Has the current job been canceled? */
		DoBack;			/* Enables the back channel comms */ 
int 		SkipStripe; //=1 for each blank stripe that will be skipped
int		MbUsed = 0; //tracks memory use
long		BytesOutCountSingle;//tracks total no of compressed bytes output by jbig library for single stripe system
time_t 		TimeStart; //to record the start of a section
FILE 		*PrintFile = NULL; //file descriptor for debug file
FILE		*JobFile;

time_t		StartTime;
time_t 		KeepAwakeStart;

#if DEBUGFILES == 1
FILE 		*dfp = NULL; //file descriptor for composite raster file
FILE 		*Cyanfp = NULL; //file descriptor for cyan only raster file
FILE 		*Magentafp = NULL; //file descriptor for magenta only raster file
FILE 		*Yellowfp = NULL; //file descriptor for yellow only raster file
FILE 		*Blackfp = NULL; //file descriptor for black only raster file
FILE 		*RawColourFile = NULL; //file descriptor for input to dither
FILE 		*DitheredColourFile = NULL; //file descriptor for output from dither
#endif

struct jbg85_enc_state JbigState;

/* DoOutJob used to enable one call to send to the specified job file and to stdout (if not testing)*/
void DoOutJobNoBack(FILE *OutFile, char *PrintFormat, int I1, int I2)
{
	if (OutFile) fprintf(OutFile, PrintFormat, I1, I2); //to the specified file
#if TESTING == 0
	fprintf(stdout, PrintFormat, I1, I2); //and to the output
#endif
	KeepAwakeStart = time(NULL); // reset timer
}

void
SetupPrinter(cups_page_header2_t *header)
{
//gets the printer ready to start the job
	int  i;
	int StatusLength;

	for(i=0; i<4; ++i)
	{
		if(GoodExchange(JobFile, "LockPrinterWait?", "0002, OK, Locked for printing;", DoBack,  1,  3.0) >= 0) break;
	}
	DoOutJob(JobFile, "Event=StartOfJob;",0,0); //printer command
        
        if (DoBack) {
	StatusLength=abs(GoodExchange(PrintFile, "DeviceStatus?", "0101,DeviceStatus.ImageDevice", DoBack,   1,  1.0));
	DoLog("StatusLength=%d\n",StatusLength,0);
/* you can get unexpected reply if there is an ink low warning then GoodExchange will be -ve */
//aquire ink levels here? DeviceStatus.Printer.InkLevelPercent.Colour=nn%&DeviceStatus.Printer.InkLevelPercent.Black=nn%
//note & used as separator
	if(StatusLength>0)
	{
		DoLog("ColourPercent=%d\n",ColourPercent,0);
		DoLog("BlackPercent=%d\n",BlackPercent,0);
    		fprintf(stderr,"ATTR: marker-levels=%d,%d\n",BlackPercent,ColourPercent); // sets the levels displayed in printer manager
	}
	GoodExchange(PrintFile, "DeviceSettings.System?", "0101,DeviceSettings.System", DoBack,   1,  1.0);
	GoodExchange(PrintFile, "DeviceSettings?", "0101,DeviceSettings.AddressBook", DoBack,   1,  1.0);
        }
        
	DoOutJob(JobFile, KodakPaperSize,0,0);

	if(header->MediaPosition == 0) DoOutJob(JobFile, "MediaInputTrayCheck=Main;",0,0);
	else if(header->MediaPosition == 1) DoOutJob(JobFile, "MediaInputTrayCheck=Photo;",0,0);
	else 
	{
		DoOutJob(JobFile, "MediaInputTrayCheck=Main;",0,0);
		DoLog("Unknown Input Tray no. %d so used main tray", header->MediaPosition, 0);
	}

        if (DoBack) {
	GoodExchange(PrintFile, "MediaTypeStatus?", "MediaTypeStatus=custom-media-type-deviceunavailable", DoBack,  1,  1.0);
	GoodExchange(PrintFile, "MediaDetect?", "0098, OK, Media Detect Started;", DoBack,   1,  1.0);
	//do MediaTypeStatus? until some media is found
#if TESTING == 0
	sleep(5); //typical media detect is 7 seconds
	for(i=0; i<15; ++i) //normal
#endif
#if TESTING == 1
	for(i=0; i<2; ++i) //short for tests
#endif
	{
		DoLog("MediaTypeStatus? try %d\n", i, 0);
		if(GoodExchange(PrintFile, "MediaTypeStatus?", "MediaTypeStatus=custom-media-type-deviceunavailable", DoBack,   2,  2.0) <= 0) break;
	}
}
}


void
ShutdownPrinter(void)
{
	int i, ret;

	DoOutJob(JobFile, "Event=EndOfJob;",0,0);
	for(i=0; i<20; ++i) /* fast PC might need lots of tries here for printer to finish, how many is reasonable? */
	{
		/* First few tries will be quick so small jobs finish quickly */
		if(i<5) ret=GoodExchange(JobFile, "UnlockPrinter?", "0003, OK, Printer unlocked;", DoBack, 1,  5.0);
		/* Then tries will be slower so long jobs can finish */
		else ret=GoodExchange(JobFile, "UnlockPrinter?", "0003, OK, Printer unlocked;", DoBack, 5,  2.0);
		DoLog("UnlockPrinter? try %d returned %d\n", i, ret);
		if(ret >= 0 || strcmp(BackBuf , "3405, Error, Printer not locked") == 0) break;
		//error string has no terminating ; because it has been tokenised by GoodExchange
	}
}


void
SetupJob(cups_page_header2_t *header) //Prepare the printer for printing.
{
	DoLog("Called SetupJob(*header);\n",0,0);
	DoOutJob(JobFile, "OutputBin=MainSink;",0,0);

	Duplex = header->Duplex;
	if(Duplex == 0) DoOutJob(JobFile, "Sides=OneSided;",0,0);
	else  DoOutJob(JobFile, "Sides=TwoSided;",0,0);
	DoOutJob(JobFile, "MediaType=custom-media-type-autoselection-0-0-0-0;",0,0);
}

void
AllocateBuffers(cups_page_header2_t *header)
{
	int i,   RasForCompSize;

 // Allocate memory for a page of graphics... 
// This printer has a watermark, which appears in the raster tacked onto the RHS of the printing raster.
// I thought it was a watermark, but maybe it's the grey ink? If so there's a possible future improvement of photo print quality by using the grey ink. That would mean dithering to CMYKk.

 	RasForCompSize = RasForCompWidth * StripeHeightMax;
  	if ((RasSpace = malloc(RasForCompSize+RasForCompWidth*2*sizeof(unsigned char))) == NULL) //2 extra lines
  	{
		DoLog("ERROR: Unable to allocate %d bytes for RasSpace!\n",RasForCompSize,0);
    		fputs("ERROR: Unable to allocate memory!\n", stderr);
    		exit(1);
  	}
	else 
	{
		MbUsed = MbUsed + (RasForCompSize+RasForCompWidth*2) * 1E-6;
		RasForComp = RasSpace + (RasForCompWidth*2); //points to the 3rd line, so 2 lines below RasForComp[0] can be used
		// Clear the page, so the watermark (or grey ink) is blank
		for(i=0;i<RasForCompSize-1;++i)  RasForComp[i] = 0;
	}
  	if ((CupsLineBuffer = malloc(header->cupsBytesPerLine)) == NULL) 
  	{
		DoLog("ERROR: Unable to allocate %d bytes for CupsLineBuffer!\n",header->cupsBytesPerLine,0);
    		fputs("ERROR: Unable to allocate memory!\n", stderr);
    		exit(1);
  	}
	else MbUsed = MbUsed + header->cupsBytesPerLine * 1E-6;
  	if ((DitherInputBuffer = malloc(header->cupsWidth*2)) == NULL) 
  	{
		DoLog("ERROR: Unable to allocate %d bytes for DitherInputBuffer!\n",header->cupsWidth*2, 0); //assume a short is 2 bytes
    		fputs("ERROR: Unable to allocate memory!\n", stderr);
    		exit(1);
  	}
 	else MbUsed = MbUsed + header->cupsWidth * 2 * 1E-6;
 	if ((DitherOutputBuffer = malloc(header->cupsWidth)) == NULL) 
  	{
		DoLog("ERROR: Unable to allocate %d bytes for DitherOutputBuffer!\n",header->cupsWidth, 0); 
    		fputs("ERROR: Unable to allocate memory!\n", stderr);
    		exit(1);
  	}
 	else MbUsed = MbUsed + header->cupsWidth * 1E-6;
 	if ((CompStripeBuffer = malloc(RasForCompWidth * StripeHeightMax)) == NULL) 
  	{
		DoLog("ERROR: Unable to allocate %d bytes for CompStripeBuffer!\n",RasForCompWidth * StripeHeightMax, 0); 
    		fputs("ERROR: Unable to allocate memory!\n", stderr);
    		exit(1);
  	}
 	else MbUsed = MbUsed + RasForCompWidth * StripeHeightMax * 1E-6;
	DoLog("Buffers allocated %d Mb\n",MbUsed,0);
}

void
StartPrinterPage(cups_page_header2_t *header)
{
	int  ResX, ResY;

 	//fprintf(stderr, "DEBUG: c2esp: StartPage\n");
	DisplayHeader(header);
	ResX = header->HWResolution[0];
	ResY = header->HWResolution[1];

	DoOutJob(JobFile, KodakPaperSize,0,0);
	DoOutJob(JobFile, "Event=StartOfPage;",0,0);
//	DoOutJob(JobFile, "Origin.Top=5.0mm;Origin.Left=5.0mm;",0,0);
	DoOutJob(JobFile, "Origin.Top=1.0mm;Origin.Left=1.0mm;",0,0);
	if(ResX==300)
	{
		DoOutJob(JobFile, "PrintQuality=0;",0,0);
    		if (OutBitsPerPixel==2)	DoOutJob(JobFile, "PrintSpeed=3;",0,0);
		else 	DoOutJob(JobFile, "PrintSpeed=1;",0,0);
	}
	else if(ResX==600)
	{
		DoOutJob(JobFile, "PrintQuality=4096;",0,0);
    		if (OutBitsPerPixel==2)	DoOutJob(JobFile, "PrintSpeed=3;",0,0); //check print speeds
		else 	DoOutJob(JobFile, "PrintSpeed=1;",0,0);
	}
	else if(ResX==1200)
	{
		DoOutJob(JobFile, "PrintQuality=8192;",0,0);
    		if (OutBitsPerPixel==2)	DoOutJob(JobFile, "PrintSpeed=3;",0,0); //check print speeds
		else 	DoOutJob(JobFile, "PrintSpeed=4;",0,0);
	}
	DoOutJob(JobFile, "Resolution=%dx%d;", ResX, ResY);
	DoOutJob(JobFile, "RasterObject.BitsPerPixel=%d;",OutBitsPerPixel,0);

    	if (header->cupsColorSpace == CUPS_CSPACE_CMYK)
	{
		DoOutJob(JobFile, "RasterObject.Planes=00FFFF,1P0000&FF00FF,1P0000&FFFF00,2P0000&000000,2T0000&000000,1P0000;",0,0); //for colour
		DoLog("CUPS_CSPACE_CMYK (%d)\n",header->cupsColorSpace,0);
	}
	else if	 (header->cupsColorSpace == CUPS_CSPACE_K)
	{
		DoOutJob(JobFile, "RasterObject.Planes=000000,2T0000&000000,1P0000;",0,0); //for mono
		DoLog("CUPS_CSPACE_K  (%d)\n",header->cupsColorSpace,0);
	}
	else	
	{
		DoOutJob(JobFile, "RasterObject.Planes=000000,2T0000&000000,1P0000;",0,0); //for mono
		DoLog("CUPS_CSPACE_??  (%d)\n",header->cupsColorSpace,0);
	}

	DoOutJob(JobFile, "RasterObject.Compression=JBIG;",0,0);
    	DoOutJob(JobFile, "RasterObject.Width=%d;", header->cupsWidth,0);
	DoOutJob(JobFile, "RasterObject.Height=%d;",  header->cupsHeight,0);
}

void
EndPage(void) //Finish a page of graphics.
{
	DoOutJob(JobFile, "Event=EndOfPage;",  0,0);

	/* Free memory... allocated by AllocateBuffers() */
//  	RasForComp not freed because it is inside RasSpace
  	free(RasSpace);
  	free(CupsLineBuffer);
  	free(DitherInputBuffer);
  	free(DitherOutputBuffer);
  	free(CompStripeBuffer);
	MbUsed = 0;
	DoLog("Buffers freed\n",0,0);
}

void
CancelJob(int sig)	/* - Cancel the current job... I - Signal */
{
  (void)sig;
  DoLog("CancelJob: job cancelled by signal\n",0,0);
  Canceled = 1;
}

//look up table to map bit pair 11 to 10, 10 to 01, 01 to 01, 00 to 00
//translates 2 bit per pixel colours to printer data
unsigned char	Map11To10And10To01[256] =
{
0, 1, 1, 2, 4, 5, 5, 6, 4, 5, 5, 6, 8, 9, 9, 10, 
16, 17, 17, 18, 20, 21, 21, 22, 20, 21, 21, 22, 24, 25, 25, 26, 
16, 17, 17, 18, 20, 21, 21, 22, 20, 21, 21, 22, 24, 25, 25, 26, 
32, 33, 33, 34, 36, 37, 37, 38, 36, 37, 37, 38, 40, 41, 41, 42, 
64, 65, 65, 66, 68, 69, 69, 70, 68, 69, 69, 70, 72, 73, 73, 74, 
80, 81, 81, 82, 84, 85, 85, 86, 84, 85, 85, 86, 88, 89, 89, 90, 
80, 81, 81, 82, 84, 85, 85, 86, 84, 85, 85, 86, 88, 89, 89, 90, 
96, 97, 97, 98, 100, 101, 101, 102, 100, 101, 101, 102, 104, 105, 105, 106, 
64, 65, 65, 66, 68, 69, 69, 70, 68, 69, 69, 70, 72, 73, 73, 74, 
80, 81, 81, 82, 84, 85, 85, 86, 84, 85, 85, 86, 88, 89, 89, 90, 
80, 81, 81, 82, 84, 85, 85, 86, 84, 85, 85, 86, 88, 89, 89, 90, 
96, 97, 97, 98, 100, 101, 101, 102, 100, 101, 101, 102, 104, 105, 105, 106, 
128, 129, 129, 130, 132, 133, 133, 134, 132, 133, 133, 134, 136, 137, 137, 138, 
144, 145, 145, 146, 148, 149, 149, 150, 148, 149, 149, 150, 152, 153, 153, 154, 
144, 145, 145, 146, 148, 149, 149, 150, 148, 149, 149, 150, 152, 153, 153, 154, 
160, 161, 161, 162, 164, 165, 165, 166, 164, 165, 165, 166, 168, 169, 169, 170, 
};

void MapDotsInByte(unsigned char *Byte)
{
	*Byte = Map11To10And10To01[*Byte];
}

void
output_jbig(unsigned char *start, size_t len, void *cbarg)
/* 
start is a pointer to some JBIG data
len is the number of bytes of JBIG data
cbarg is a pointer to an optional output file
(output is also sent to stdout)

uses a fixed global buffer to store one stripe and sends stripe when it becomes complete
 Includes mod by Andreas (awl29) to limit the size of JBIG data chunks which is required for some older models
*/

{
int	i;
int	rc;
int BytesToPrint; 
int CurrentChunkSize; 
unsigned char *CurrentChunkStart; 

 //copy bytes one at a time looking for end of BIE and counting
	for(i=0;i<len;++i)
	{
		CompStripeBuffer[CompStripeBufferFree] = start[i];
		++CompStripeBufferFree;
		++BytesOutCountSingle;

//at end of BIE call output functions
		if(CompStripeBufferFree >= 2 && BytesOutCountSingle > 20) //only if the header is complete
		{
			if(CompStripeBuffer[CompStripeBufferFree-2] == ESC && CompStripeBuffer[CompStripeBufferFree-1] != 0)
			{
			//end of BIE detected
				DoLog("SingleStripe: detected end of BIE at %d bytes, length %d\n",BytesOutCountSingle,CompStripeBufferFree);

			//send the buffer to the printer, in chunks less than MAXJBIGDATACHUNK
				BytesToPrint = CompStripeBufferFree; 
				CurrentChunkSize = 0; 
				CurrentChunkStart = CompStripeBuffer; 
				while (BytesToPrint > 0) { 
					if (BytesToPrint <= MAXJBIGDATACHUNK) { 
						CurrentChunkSize = BytesToPrint; 
					} 
					else { 
						CurrentChunkSize = MAXJBIGDATACHUNK; 
					} 
			//send one chunk of data 
					DoOutJob(cbarg, "RasterObject.Data#%d=", CurrentChunkSize,0); 
					if(cbarg != NULL) rc = fwrite(CurrentChunkStart, 1, CurrentChunkSize, cbarg); 
					DoLog("JBIG data chunk is sent to printer\n",0,0); 
					rc = fwrite(CurrentChunkStart, 1, CurrentChunkSize, stdout); //also to output 
					DoOutJob(cbarg, ";",0,0); //one semi colon after the chunk 
					BytesToPrint -= CurrentChunkSize; 
					CurrentChunkStart += CurrentChunkSize; 
				} 


			//then restart the buffer
				CompStripeBufferFree = 0;
			}
		}
	}
}

time_t KeepAwake(time_t Start, int Interval)
{
// Keeps the printer connection awake by sending DeviceStatus query not sooner than the specified interval in seconds
// Usage:   Start = KeepAwake(Start, Interval);
	if(time(NULL) - Start > Interval)
	{
		DoLog("Keeping printer awake by DeviceStatus?\n",0,0);
		GoodExchange(PrintFile, "DeviceStatus?", "0101,DeviceStatus.ImageDevice", DoBack,   1,  1.0);
		return (time(NULL));
	}
	else return (Start);
}

void OutputLineExtents(unsigned char *buf, int Totalbpl, cups_page_header2_t header, FILE *fp)
{
	int BandLeft, BandRight, BytesLeft, BytesRight, ThisBytePrint, BytesPerCol, Col, Cols, Printbpl;
//BitsPerPixel is in the buffer of printer data, not in the cups raster Use global OutBitsPerPixel
	Printbpl = (header.cupsWidth + 7) / 8;
	if (header.cupsColorSpace == CUPS_CSPACE_CMYK) Cols=4;
	else Cols=1;
	BytesPerCol=Totalbpl/(Cols+1);
	//Search for extents in this row of pixels
	for(BytesLeft=0;BytesLeft<Printbpl;++BytesLeft)
	{
		ThisBytePrint=0;
		for(Col=0;Col<Cols;++Col)
		{
			if(buf[BytesLeft+BytesPerCol*Col]!=0) ThisBytePrint=1;
		}
		if(ThisBytePrint==1) break;
	}
	if(BytesLeft >= Printbpl) BandLeft=0;
	else BandLeft=BytesLeft*8/OutBitsPerPixel;
	//BytesLeft is the offset to the first byte with pixels
	//BandLeft is the pixel offset to the first byte that is not blank

	for(BytesRight=Printbpl*OutBitsPerPixel-1;BytesRight >= 0;--BytesRight)
	{
		ThisBytePrint=0;
		for(Col=0;Col<Cols;++Col)
		{
			if(buf[BytesRight+BytesPerCol*Col]!=0) ThisBytePrint=1;
		}
		if(ThisBytePrint==1) break;
	}
	if(BytesRight < 0) BandRight=0;
	else BandRight=(BytesRight+1)*8/OutBitsPerPixel;
	//BytesRight is the off set to the last byte with pixels
	//BandRight is the pixel offset to the byte after last byte that is not blank
	DoOutJobNoBack(fp,",%d,%d",BandLeft,BandRight);
}

void PrintOneStripe (unsigned char *buf, int Stripe, int StripeHeight, cups_page_header2_t header, FILE *fp)
{
// buf is the stripe buffer with width w and height StripeHeight pixels. PrintW PrintH are the pixel width and height of the print raster
    int	 y, Index;
	DoLog("PrintOneStripe starts SkipStripe = %d\n",SkipStripe,0);
	DoLog("Extent search BitsPerPixel=%d\n",OutBitsPerPixel,0);
	//writes the extents and data for one band for the 5250 printer 
	DoLog("stripe %d of height %d\n",Stripe, StripeHeight);
	fprintf(stderr,"INFO: c2esp: Page %d Stripe %d\n", Page, Stripe);

	//black in bands was stored in SkipStripe
	if(SkipStripe)
	{
		    //there is no print in this band
		DoOutJob(fp, "RasterObject.Extent=skip,%d;", StripeHeight,0);
	   	DoLog("<Stripe %d skipped>\n",Stripe, 0);
	}
	else
	{
		//there is print in this band
		DoOutJob(fp,"RasterObject.BandHeight=%d;",StripeHeight,0);
		DoOutJob(fp,"RasterObject.Extent=true",0,0);
		DoLog("sending the extent data\n",0,0);
		for(y=0;y<StripeHeight;++y) OutputLineExtents(&buf[(y)*RasForCompWidth], RasForCompWidth, header, fp);
		DoOutJob(fp,";",0,0); //extent terminator at end of band

		fprintf(stderr,"DEBUG: c2esp: Compress a stripe\n");
		for(y=0;y < StripeHeight;++y)
		{
			Index = (y)*RasForCompWidth;
			jbg85_enc_lineout(&JbigState, &buf[Index], &buf[Index - RasForCompWidth], &buf[Index - 2 * RasForCompWidth]);
		}

		DoOutJob(fp,"Event=EndOfBand;",0,0);
	} //end of stripe with print
}

void SetUpDither(cups_lut_t *Lut[], cups_dither_t *DitherState[], int LineWidth)
{
	int Col;
	for(Col=0;Col<4;++Col)
	{
  		Lut[Col] = cupsLutNew(3, default_lut);
  		DitherState[Col] = cupsDitherNew(LineWidth);
	}
}

unsigned char Dithered4ToPrint(unsigned char *Buffer, int x)
{
	//gets 4 points from Buffer started with x where 00=max colour 255=no colour and maps them into one byte
	//Buffer must be >= 4 chars longer than x
	// (0->10, 2->00, 1->01)
	unsigned char Build=0;
//shifting version
	if (Buffer[x+0]<=2) Build=Build+(Buffer[x+0]<<6);
	if (Buffer[x+1]<=2) Build=Build+(Buffer[x+1]<<4);
	if (Buffer[x+2]<=2) Build=Build+(Buffer[x+2]<<2);
	if (Buffer[x+3]<=2) Build=Build+(Buffer[x+3]);
	return Build;
}

/*
 * 'main()' - Main entry and processing of driver.
 */

int					/* O - Exit status */
main(int  argc,	char *argv[])		/* I - Number of command-line arguments, Command-line arguments */
{
  	int			fd;		/* File descriptor */
 	cups_raster_t		*ras;		/* Raster stream from cups */
  	cups_page_header2_t	header;		/* Page header from cups */
  	int			Stripe, y;		
	int			StripeEnd; //index of last byte in current stripe
	int			StripeHeight; //height of current stripe
	int			CloseError,Col,i,x; 
	int			BlankColour; //boolean to record if the line is blank to save time
#if DEBUGFILES == 1
	char PrintFileName[100]="";
#endif

  	cups_lut_t	*Lut[4];		/* Dither lookup tables */
  	cups_dither_t	*DitherState[4];	/* Dither states */
	int 			BytesPerColour;
	long			RasForCompHeight;
	unsigned char		MinOut, MaxOut; //to check the range of the dithered output
#if DEBUGFILES == 1
	short			MinIn=5000, MaxIn=0; //to check the range of the dithered input
	int 			output;
#endif
	StartTime = time(NULL);
	KeepAwakeStart = time(NULL);

	#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
  	struct sigaction action;		/* Actions for POSIX signals */
	#endif 
 /*
  * Check command-line...
  */
  	if (argc < 6 || argc > 7) //wrong no of arguments
  	{
    		fprintf(stderr, ("Usage: %s job-id user title copies options [file]\n"), "rastertoek");
   		 return (1);
  	}
        
        char data;
        int datalen;
        cups_sc_bidi_t bidi;
        cups_sc_status_t status;
        
        /* Tell cupsSideChannelDoRequest() how big our buffer is... */
        datalen = 1;

        /* Get the bidirectional capabilities, waiting for up to 1 second */
        status = cupsSideChannelDoRequest(CUPS_SC_CMD_GET_BIDI, &data, &datalen, 1.0);

        /* Use the returned value if OK was returned and the length is still 1 */
        if (status == CUPS_SC_STATUS_OK && datalen == 1) {
                bidi = (cups_sc_bidi_t) data;
                DoBack = (bidi == CUPS_SC_BIDI_NOT_SUPPORTED ? 0 : 1);
        } else {
                bidi = CUPS_SC_BIDI_NOT_SUPPORTED;
                DoBack = 0;
        }

#if DEBUGFILES == 1
	chmod("/tmp/c2espjob", S_IRUSR | S_IWUSR | S_IROTH ); //let anyone read it
	remove("/tmp/KodakSendLog"); //to be sure I only see the latest
	SetupLogging("c2esp",DoBack,"/tmp/KodakPrintLog");
#else
	SetupLogging("c2esp",DoBack,"");
#endif

  	setbuf(stderr, NULL);
      	fprintf(stderr, ("DEBUG:  ================ %s ====================================\n"),Version); 
	DoLogString("Starting %s\n",Version);
        
        DoLog("Number of command line parameters: %d\n", argc, 0);
        int argi;
        for (argi = 0; argi < argc; argi++) {
            DoLogString("  param: '%s'\n", argv[argi]);
        }
        DoLogString("End of command-line parameters\n", "");

        DoLogString("Bi-di/backchannel support: %s\n", (bidi == CUPS_SC_BIDI_NOT_SUPPORTED ? "false" : "true"));
        DoLog("DoBack value: %d\n", DoBack, 0);
        
	MarkerSetup();

 /*
  * Open the page stream...
  */
  	if (argc == 7)
  	{
    		if ((fd = open(argv[6], O_RDONLY)) == -1)
    		{
      			fprintf(stderr, ("ERROR: c2esp: Unable to open raster file - %s\n"),
                      	strerror(errno));
      			sleep(1);
      			return (1);
    		}
  	}
  	else    fd = 0;
      	DoLog("opening raster\n",0,0); 
  	ras = cupsRasterOpen(fd, CUPS_RASTER_READ);

 /*
  * Register a signal handler to eject the current page if the
  * job is cancelled.
  */
  	Canceled = 0;
	#ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
  	sigset(SIGTERM, CancelJob);
	#elif defined(HAVE_SIGACTION)
  	memset(&action, 0, sizeof(action));
  	sigemptyset(&action.sa_mask);
  	action.sa_handler = CancelJob;
  	sigaction(SIGTERM, &action, NULL);
	#else
  	signal(SIGTERM, CancelJob);
	#endif /* HAVE_SIGSET */

 /*
  * Initialize the print device...
  */

#if DEBUGFILES == 1
	/* Open the print file */
	strcat(PrintFileName,"/tmp");
	strcat(PrintFileName,"/c2espjob");
	remove(PrintFileName);
	JobFile = fopen(PrintFileName, "w"); 
	if (JobFile != NULL) DoLogString("JobFile %s Opened\n",PrintFileName);
	else DoLogString("JobFile %s failed to open\n",PrintFileName);

	PrintFile = fopen("/tmp/KodakPrintFile", "w");//open the print file
#endif

/* read the first header */
	if(cupsRasterReadHeader2(ras, &header))
	{
		DoLog("First page Header read after %d sec\n", time(NULL)-StartTime,0);
		SetUpDither(Lut, DitherState, header.cupsWidth);

		SetupPrinter(&header);
		DoLog("Printer should be ready now\n",0,0);
  /* 
  * Process pages as needed...
  */
  		Page = 0;
	do //start of loop for each page
  	{
#if DEBUGFILES == 1
//open debug files
	    	remove("/tmp/RasForComp.pbm");
		dfp = fopen("/tmp/RasForComp.pbm", "w");
		if(dfp)	fprintf(dfp, "P4\n%8d %8d\n", RasForCompWidth * 8, (StripeEnd + 1)/RasForCompWidth);

	    	remove("/tmp/RasCyan.pbm");
		remove("/tmp/RasMagenta.pbm");
		remove("/tmp/RasYellow.pbm");
		remove("/tmp/RasBlack.pbm");
		Cyanfp = fopen("/tmp/RasCyan.pbm", "w");
	    	Magentafp = fopen("/tmp/RasMagenta.pbm", "w");
	    	Yellowfp = fopen("/tmp/RasYellow.pbm", "w");
	    	Blackfp = fopen("/tmp/RasBlack.pbm", "w");
		fprintf(Cyanfp, "P4\n%8d %8d\n", BytesPerColour * 8, (StripeEnd + 1)/RasForCompWidth);
		fprintf(Magentafp, "P4\n%8d %8d\n", BytesPerColour * 8, (StripeEnd + 1)/RasForCompWidth);
		fprintf(Yellowfp, "P4\n%8d %8d\n", BytesPerColour * 8, (StripeEnd + 1)/RasForCompWidth);
		fprintf(Blackfp, "P4\n%8d %8d\n", BytesPerColour * 8, (StripeEnd + 1)/RasForCompWidth);
#endif
		DoLog("Header read\n", 0,0);
    		if (Canceled)	break;
		if(header.cupsWidth<=0) break;
    		Page ++;
   		DoLog("PAGE %d COPIES %d\n", Page, header.NumCopies);

   /*
    * Start the page...
    */
		BytesOutCountSingle = 0; //initialise counter
		RasForCompHeight = 0; /* will accumulate the height for one page */
		//StartTime=time(NULL);
		SetPaperSize(KodakPaperSize, header.PageSize[1]); 	
		if(header.cupsBitsPerColor == 1) OutBitsPerPixel = 1; 
		else OutBitsPerPixel = 2;
		BytesPerColour = (((header.cupsWidth * OutBitsPerPixel + 7) / 8) + 31) / 32 * 32; //round each colour up to 32 bytes

		if (header.cupsColorSpace == CUPS_CSPACE_CMYK) //colour
		{
			DoLog("Colour cups raster w = %d h = %d\n", header.cupsWidth, header.cupsHeight);
			DoLog("Colour cups bits per pixel = %d, bits per colour = %d\n", header.cupsBitsPerPixel, header.cupsBitsPerColor);
			DoLog("Colour cups raster bytes per line = %d bits per line = %d\n", header.cupsBytesPerLine, header.cupsBytesPerLine * 8);
			RasForCompWidth = BytesPerColour * 5;

			if(header.cupsBitsPerColor > 2)   //raster is 8 bit for dithering
			{
				fprintf(stderr, "INFO: p%d Colour dithering\n",Page);

#if DEBUGFILES == 1
				//open dither files here
	    			remove("/tmp/RawCyan.pbm");
				RawColourFile = fopen("/tmp/RawCyan.pbm", "w");
	    			if (RawColourFile) 
				{
					fprintf(RawColourFile, "P5\n%8d %8d %8d\n", header.cupsWidth, header.cupsHeight, 255);
					DoLog("Opened RawCyan.pbm\n", 0, 0);
				}
	    			remove("/tmp/DitheredColour.pbm");
				DitheredColourFile = fopen("/tmp/DitheredColour.pbm", "w");
	    			if (DitheredColourFile) 
				{
					fprintf(DitheredColourFile, "P5\n%8d %8d %8d\n", header.cupsWidth, header.cupsHeight, 255);
					DoLog("Opened DitheredColour.pbm\n", 0, 0);
				}
#endif
	    		}
			else fprintf(stderr, "INFO: p%d Colour not dithered\n",Page); //raster is 2 bit

		}
		else if (header.cupsColorSpace == CUPS_CSPACE_K)//monochrome
		{
			//fprintf(stderr, "INFO: p%d Monochrome\n",Page);
			DoLog("Mono cups raster w = %d h = %d\n", header.cupsWidth, header.cupsHeight);
			DoLog("Mono cups raster bytes per line = %d bits per line = %d\n", header.cupsBytesPerLine, header.cupsBytesPerLine * 8);
//			BytesPerColour = (header.cupsBytesPerLine + 31) / 32 * 32; //round each colour up to 32 bytes
			RasForCompWidth = BytesPerColour * 2;
		}
		else DoLog("Unknown cupsColorSpace = %d\n", header.cupsColorSpace, 0);

		AllocateBuffers(&header);
		StripeEnd = -1; //index of the last byte of the stripe
		MinOut=255;MaxOut=0; //initialise

 		if(Page == 1) SetupJob(&header);
		StartPrinterPage( &header);

//prepare for compression JBIG85
		DoLog("initialising Compression\n",0,0);
		jbg85_enc_init(&JbigState, RasForCompWidth * 8, header.cupsHeight, output_jbig, JobFile);
	  	jbg85_enc_options(&JbigState, -1, StripeHeightMax, -1); //default options ie with variable length

   		for (Stripe = 0; Stripe * StripeHeightMax < header.cupsHeight; ++Stripe)  // Loop for each source stripe
   		{
			if(header.cupsHeight > Stripe * StripeHeightMax + StripeHeightMax) StripeHeight = StripeHeightMax;
			else StripeHeight = header.cupsHeight - (Stripe * StripeHeightMax);
			if(Stripe == 1) DoLog("First stripe at %d sec\n", time(NULL)-StartTime, 0);
			
   			for (y = 0; (y < StripeHeightMax) && (y + Stripe * StripeHeightMax < header.cupsHeight); ++y )  // Loop for each line in the stripe
   			{
      				if (Canceled) break;
				KeepAwakeStart = KeepAwake(KeepAwakeStart,10); //Keep the printer connection awake

				if (header.cupsColorSpace == CUPS_CSPACE_CMYK) //colour
				{
					if  (header.cupsBitsPerColor == 8) // do dithering
					{
						if(y == 0) DoLog("Doing dithering in stripe %d\n", Stripe, 0);
					//read a line of colour. The longest line 600dpi 8.5 in = 20400 bytes for 8 bit CMYK values
  						if (!cupsRasterReadPixels(ras, CupsLineBuffer, header.cupsBytesPerLine)) break; 
						//CupsLineBuffer holds the chunky CMYK 8 bit data of a whole line
						if(y == 0) DoLog("Read first line from cups raster\n", Stripe, 0);

						for(Col = 0; Col<4; ++Col)
						{
					//convert the bits in CupsLineBuffer to short ints in DitherInputBuffer for the current colour
					//checking if it's blank as we go
							BlankColour=1; //0 for testing will dither all lines
							for(x=0;x<header.cupsWidth;++x) 
							{
								DitherInputBuffer[x]=CupsLineBuffer[4*x+Col]<<4;
								if(DitherInputBuffer[x]>0) BlankColour=0;
#if DEBUGFILES==1
					//save in file, in the file 255=white 0=black(reverse of printer)
								if(Col == 3) //0=cyan 1=mag 2=yellow 3=black
								{
     									output = 255 - CupsLineBuffer[4*x+Col];
      									if (output < 0) output = 0;
      									if (RawColourFile) fputc(output, RawColourFile);
									if (DitherInputBuffer[x]>MaxIn) MaxIn=DitherInputBuffer[x];
									if (DitherInputBuffer[x]<MinIn) MinIn=DitherInputBuffer[x];
								}
#endif
							}
					//dither the line
							if(BlankColour==0) cupsDitherLine(DitherState[Col], Lut[Col], DitherInputBuffer, 1, DitherOutputBuffer);
// full scale input is 4095. output is the index in the lut.

#if DEBUGFILES==1
					//save in file, in the file 255=white 0=black (reverse of printer)
							for(x=0;x<header.cupsWidth;++x) 
							{
								if(Col == 3) //0=cyan 1=mag 2=yellow 3=black
								{
      									if(!BlankColour) 
									{
									//7 bit shift on the next line to approximate 255/2
										output = 255 - (DitherOutputBuffer[x] << 7);
      										if (output < 0) output = 0;
										if (DitherOutputBuffer[x]>MaxOut) MaxOut=DitherOutputBuffer[x];
										if (DitherOutputBuffer[x]<MinOut) MinOut=DitherOutputBuffer[x];
									}
									else 
									{
										output=255;
										MinOut=0;
									}
      									if (DitheredColourFile) fputc(output, DitheredColourFile);
								}
							}
#endif
					//copy the line as bits into the appropriate position in the printer raster
							for(x=0;x<header.cupsWidth;x=x+4) 
							{
								if(!BlankColour) RasForComp[y * RasForCompWidth + Col * (BytesPerColour)+x/4]=Dithered4ToPrint(DitherOutputBuffer,x);
								else RasForComp[y * RasForCompWidth + Col * (BytesPerColour)+x/4]=0;
							
							}
						} //next Col
					} //end of 8 bits per colour section

					else if (header.cupsBitsPerColor <= 2) //the old version of the ppd non dithered should work for 2 or 1 bit
					{
						for(Col = 0; Col<4; ++Col)
						{
							if (cupsRasterReadPixels(ras, &RasForComp[y * RasForCompWidth + Col * (BytesPerColour)], header.cupsBytesPerLine/4) < 1) break;
						}
					}
					else DoLog("cupsBitsPerColor %d is not handled\n",header.cupsBitsPerColor,0);
					
				}
				else //monochrome
				{
					if (cupsRasterReadPixels(ras, &RasForComp[y * RasForCompWidth], header.cupsBytesPerLine) < 1) break; //read a line
				}

    			} //end of line loop

StripeEnd = StripeHeight * RasForCompWidth - 1; //so do not have to increment in the loop

			//map 2 bit per pixel data of the line to suit the printer and look for printing in the stripe
			SkipStripe = 1;
			for(i=0;i<=StripeEnd;++i) 
			{
				if (header.cupsBitsPerColor==2) RasForComp[i] = Map11To10And10To01[RasForComp[i]]; //map 2 bit
				if(RasForComp[i]!=0) SkipStripe = 0; //look for printing
			}

#if DEBUGFILES == 1
//write the stripe into the raster files
			if(SkipStripe != 1) 
			{
//store the raster for debugging - does not seem to be viewable properly when 600dpi colour
	    			if (dfp) fwrite(&RasForComp[0], 1, StripeEnd, dfp);
//store the CMYK rasters separately
				if(Cyanfp && Magentafp && Yellowfp && Blackfp) 
				{
					for(i=0;i<(StripeEnd + RasForCompWidth + 1);i=i+RasForCompWidth)
					{
					fwrite(&RasForComp[i + 0 * BytesPerColour], 1,  BytesPerColour, Cyanfp);
					fwrite(&RasForComp[i + 1 * BytesPerColour], 1,  BytesPerColour, Magentafp);
					fwrite(&RasForComp[i + 2 * BytesPerColour], 1,  BytesPerColour, Yellowfp);
					fwrite(&RasForComp[i + 3 * BytesPerColour], 1,  BytesPerColour, Blackfp);
					}
				}
				DoLog("Rasters stored at %d sec\n",time(NULL)-StartTime,0);
			}
#endif

			//DoLog("StripeEnd=%d SkipStripe=%d\n",StripeEnd,SkipStripe);
			if(!SkipStripe) RasForCompHeight = RasForCompHeight + StripeHeight;

 			PrintOneStripe(&RasForComp[0], Stripe, StripeHeight, header, JobFile);
//copy the last 2 lines of the stripe, before the first line of RasForComp
			for(i=0;i<RasForCompWidth;++i)
			{
				RasForComp[i - RasForCompWidth] = RasForComp[(StripeHeight-1) * RasForCompWidth + i];
				RasForComp[i - RasForCompWidth * 2] = RasForComp[(StripeHeight-2) * RasForCompWidth + i];
			}
   	
			StripeEnd = -1;
 		} //end of loop for each stripe

		DoLog("Page raster built at %d sec\n",time(NULL)-StartTime,0);
//page is finished
#if DEBUGFILES == 1
//all stripes are now done
		DoLog("Max and min in input colour are %d %d\n",MaxIn,MinIn);
		DoLog("Max and min in dithered colour are %d %d\n",MaxOut,MinOut);

//close the dither files
		if(RawColourFile)
		{
				fclose(RawColourFile);
				sleep(3);
				chmod("/tmp/RawCyan.pbm", S_IRUSR | S_IWUSR | S_IROTH ); //let anyone read it
				DoLog("Closed RawCyan.pbm\n", 0, 0);
		}
		if(DitheredColourFile)
		{
				fclose(DitheredColourFile);
				sleep(3);
				chmod("/tmp/DitheredCyan.pbm", S_IRUSR | S_IWUSR | S_IROTH ); //let anyone read it
				DoLog("Closed DitheredCyan.pbm\n", 0, 0);
		}

//close the debug files
			fclose(dfp);
			sleep(3);
			chmod("/tmp/RasForComp.pbm", S_IRUSR | S_IWUSR | S_IROTH ); //let anyone read it
				fclose(Cyanfp);
				fclose(Magentafp);
				fclose(Yellowfp);
				fclose(Blackfp);
				sleep(3);
				chmod("/tmp/RasCyan.pbm", S_IRUSR | S_IWUSR | S_IROTH ); //let anyone read it
				chmod("/tmp/RasMagenta.pbm", S_IRUSR | S_IWUSR | S_IROTH ); //let anyone read it
				chmod("/tmp/RasYellow.pbm", S_IRUSR | S_IWUSR | S_IROTH ); //let anyone read it
				chmod("/tmp/RasBlack.pbm", S_IRUSR | S_IWUSR | S_IROTH ); //let anyone read it

#endif
		DoLog("Setting jbig height to %d\n", RasForCompHeight, 0);
		jbg85_enc_newlen(&JbigState, RasForCompHeight);

    		EndPage();
   		if (Canceled)    break;
  	}
	while (cupsRasterReadHeader2(ras, &header));

	}
	else DoLog("no headers so nothing to print",0,0);

        if (Page > 0) {
                ShutdownPrinter();
 	}

 /*
  * Close the raster stream... and the debug file
  */
 	cupsRasterClose(ras);
	DoLog("cups raster closed after %d sec\n",time(NULL)-StartTime,0);
  	if (fd != 0)   close(fd);
	if(JobFile != NULL)
	{
		CloseError = fclose(JobFile);
		DoLog("jobfile closed after %d sec with return value %d\n",time(NULL)-StartTime, CloseError);
	}

//free the dither states
  	for(Col = 0; Col < 4 ;++Col)
	{
		cupsDitherDelete(DitherState[Col]);
	  	cupsLutDelete(Lut[Col]);
	}
 /*
  * Termination, send an error message if required...
  */
		DoLog("SingleStripe: Bytes output by JBIG just before terminating = %d\n",BytesOutCountSingle,0);
		DoLog("c2esp terminating after %d sec. Processed %d pages\n",time(NULL)-StartTime,Page);
  	if (Page == 0)
  	{
    		fprintf(stderr, ("ERROR: c2esp: No pages found!\n"));
    		return (1);
  	}
  	else
  	{

		CloseLogging();
#if DEBUGFILES == 1
		if(PrintFile != NULL) 
		{
			fclose(PrintFile);
			// sleep(3); //does this help chmod to work?
		}
		//let anyone read the files How much delay is needed if any?
		chmod("/tmp/c2espjob", S_IRUSR | S_IWUSR | S_IROTH ); //let anyone read it
		chmod("/tmp/KodakPrintLog", S_IRUSR | S_IWUSR | S_IROTH ); //let anyone read it
		chmod("/tmp/KodakPrintFile", S_IRUSR | S_IWUSR | S_IROTH ); //let anyone read it
#endif
		//cups seems to replace this by "Ready to print" so you don't see it
                if (DoBack) {
    		fprintf(stderr, "INFO: c2esp: Ready to print Blk %d Col %d percent\n",BlackPercent, ColourPercent);
                } else {
                        fprintf(stderr, "INFO: c2esp: Ready to print (no bi-di communication)\n");
                }
   		return (0);
  	}
}