xref: /libtiff-4.0.7/tools/tiff2ps.c (revision bfbc7176)
1 /* $Id: tiff2ps.c,v 1.44 2010-03-10 18:56:50 bfriesen Exp $ */
2 
3 /*
4  * Copyright (c) 1988-1997 Sam Leffler
5  * Copyright (c) 1991-1997 Silicon Graphics, Inc.
6  *
7  * Permission to use, copy, modify, distribute, and sell this software and
8  * its documentation for any purpose is hereby granted without fee, provided
9  * that (i) the above copyright notices and this permission notice appear in
10  * all copies of the software and related documentation, and (ii) the names of
11  * Sam Leffler and Silicon Graphics may not be used in any advertising or
12  * publicity relating to the software without the specific, prior written
13  * permission of Sam Leffler and Silicon Graphics.
14  *
15  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
16  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
17  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
18  *
19  * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
20  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
21  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
22  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
23  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
24  * OF THIS SOFTWARE.
25  */
26 
27 #include "tif_config.h"
28 
29 #include <stdio.h>
30 #include <stdlib.h>			/* for atof */
31 #include <math.h>
32 #include <time.h>
33 #include <string.h>
34 
35 #ifdef HAVE_UNISTD_H
36 # include <unistd.h>
37 #endif
38 
39 #ifdef NEED_LIBPORT
40 # include "libport.h"
41 #endif
42 
43 #include "tiffio.h"
44 
45 /*
46  * Revision history
47  *
48  * 2005-June-3
49  *    Richard Nolde: Added support for rotations of 90, 180, 270
50  *    and auto using -r <90|180|270|auto>.  Auto picks the best
51  *    fit for the image on the specified paper size (eg portrait
52  *    or landscape) if -h or -w is specified. Rotation is in
53  *    degrees counterclockwise since that is how Postscript does
54  *    it.  Auto rotates 90 degrees ccw to produce landscape.
55  *
56  *    Added maxPageWidth option using -W flag. MaxPageHeight and
57  *    MaxPageWidth are mutually exclusive since the aspect ratio
58  *    cannot be maintained if you set both.
59  *    Rewrote PlaceImage to allow maxPageHeight and maxPageWidth
60  *    options to work with values smaller or larger than the
61  *    physical paper size and still preserve the aspect ratio.
62  *    This is accomplished by creating multiple pages across
63  *    as well as down if need be.
64  *
65  * 2001-Mar-21
66  *    I (Bruce A. Mallett) added this revision history comment ;)
67  *
68  *    Fixed PS_Lvl2page() code which outputs non-ASCII85 raw
69  *    data.  Moved test for when to output a line break to
70  *    *after* the output of a character.  This just serves
71  *    to fix an eye-nuisance where the first line of raw
72  *    data was one character shorter than subsequent lines.
73  *
74  *    Added an experimental ASCII85 encoder which can be used
75  *    only when there is a single buffer of bytes to be encoded.
76  *    This version is much faster at encoding a straight-line
77  *    buffer of data because it can avoid alot of the loop
78  *    overhead of the byte-by-bye version.  To use this version
79  *    you need to define EXP_ASCII85ENCODER (experimental ...).
80  *
81  *    Added bug fix given by Michael Schmidt to PS_Lvl2page()
82  *    in which an end-of-data marker ('>') was not being output
83  *    when producing non-ASCII85 encoded PostScript Level 2
84  *    data.
85  *
86  *    Fixed PS_Lvl2colorspace() so that it no longer assumes that
87  *    a TIFF having more than 2 planes is a CMYK.  This routine
88  *    no longer looks at the samples per pixel but instead looks
89  *    at the "photometric" value.  This change allows support of
90  *    CMYK TIFFs.
91  *
92  *    Modified the PostScript L2 imaging loop so as to test if
93  *    the input stream is still open before attempting to do a
94  *    flushfile on it.  This was done because some RIPs close
95  *    the stream after doing the image operation.
96  *
97  *    Got rid of the realloc() being done inside a loop in the
98  *    PSRawDataBW() routine.  The code now walks through the
99  *    byte-size array outside the loop to determine the largest
100  *    size memory block that will be needed.
101  *
102  *    Added "-m" switch to ask tiff2ps to, where possible, use the
103  *    "imagemask" operator instead of the "image" operator.
104  *
105  *    Added the "-i #" switch to allow interpolation to be disabled.
106  *
107  *    Unrolled a loop or two to improve performance.
108  */
109 
110 /*
111  * Define EXP_ASCII85ENCODER if you want to use an experimental
112  * version of the ASCII85 encoding routine.  The advantage of
113  * using this routine is that tiff2ps will convert to ASCII85
114  * encoding at between 3 and 4 times the speed as compared to
115  * using the old (non-experimental) encoder.  The disadvantage
116  * is that you will be using a new (and unproven) encoding
117  * routine.  So user beware, you have been warned!
118  */
119 
120 #define	EXP_ASCII85ENCODER
121 
122 /*
123  * NB: this code assumes uint32 works with printf's %l[ud].
124  */
125 #ifndef TRUE
126 #define	TRUE	1
127 #define	FALSE	0
128 #endif
129 
130 #define HORIZONTAL 1
131 #define VERTICAL   2
132 
133 int	ascii85 = FALSE;		/* use ASCII85 encoding */
134 int	interpolate = TRUE;		/* interpolate level2 image */
135 int	level2 = FALSE;			/* generate PostScript level 2 */
136 int	level3 = FALSE;			/* generate PostScript level 3 */
137 int	printAll = FALSE;		/* print all images in file */
138 int	generateEPSF = TRUE;		/* generate Encapsulated PostScript */
139 int	PSduplex = FALSE;		/* enable duplex printing */
140 int	PStumble = FALSE;		/* enable top edge binding */
141 int	PSavoiddeadzone = TRUE;		/* enable avoiding printer deadzone */
142 double	maxPageHeight = 0;		/* maximum height to select from image and print per page */
143 double	maxPageWidth  = 0;		/* maximum width  to select from image and print per page */
144 double	splitOverlap = 0;		/* amount for split pages to overlag */
145 int	rotate = FALSE;			/* rotate image by angle 90, 180, 270 degrees */
146 int	rotation = 0;                   /* optional value for rotation angle */
147 char	*filename;			/* input filename */
148 int	useImagemask = FALSE;		/* Use imagemask instead of image operator */
149 uint16	res_unit = 0;			/* Resolution units: 2 - inches, 3 - cm */
150 
151 /*
152  * ASCII85 Encoding Support.
153  */
154 unsigned char ascii85buf[10];
155 int	ascii85count;
156 int	ascii85breaklen;
157 
158 int	TIFF2PS(FILE*, TIFF*, double, double, double, double, int);
159 void	PSpage(FILE*, TIFF*, uint32, uint32);
160 void	PSColorContigPreamble(FILE*, uint32, uint32, int);
161 void	PSColorSeparatePreamble(FILE*, uint32, uint32, int);
162 void	PSDataColorContig(FILE*, TIFF*, uint32, uint32, int);
163 void	PSDataColorSeparate(FILE*, TIFF*, uint32, uint32, int);
164 void	PSDataPalette(FILE*, TIFF*, uint32, uint32);
165 void	PSDataBW(FILE*, TIFF*, uint32, uint32);
166 void	PSRawDataBW(FILE*, TIFF*, uint32, uint32);
167 void	Ascii85Init(void);
168 void	Ascii85Put(unsigned char code, FILE* fd);
169 void	Ascii85Flush(FILE* fd);
170 void    PSHead(FILE*, TIFF*, uint32, uint32, double, double, double, double);
171 void	PSTail(FILE*, int);
172 
173 #if	defined( EXP_ASCII85ENCODER)
174 tsize_t Ascii85EncodeBlock( uint8 * ascii85_p, unsigned f_eod, const uint8 * raw_p, tsize_t raw_l );
175 #endif
176 
177 static	void usage(int);
178 
179 int
180 main(int argc, char* argv[])
181 {
182 	int dirnum = -1, c, np = 0;
183 	int centered = 0;
184 	double bottommargin = 0;
185 	double leftmargin = 0;
186 	double pageWidth = 0;
187 	double pageHeight = 0;
188 	uint32 diroff = 0;
189 	extern char *optarg;
190 	extern int optind;
191 	FILE* output = stdout;
192 
193 	while ((c = getopt(argc, argv, "b:d:h:H:W:L:i:w:l:o:O:r:acelmxyzps1238DT")) != -1)
194 		switch (c) {
195 		case 'b':
196 			bottommargin = atof(optarg);
197 			break;
198 		case 'c':
199 			centered = 1;
200 			break;
201 		case 'd':
202 			dirnum = atoi(optarg);
203 			break;
204 		case 'D':
205 			PSduplex = TRUE;
206 			break;
207 		case 'i':
208 			interpolate = atoi(optarg) ? TRUE:FALSE;
209 			break;
210 		case 'T':
211 			PStumble = TRUE;
212 			break;
213 		case 'e':
214 			PSavoiddeadzone = FALSE;
215 			generateEPSF = TRUE;
216 			break;
217 		case 'h':
218 			pageHeight = atof(optarg);
219 			break;
220 		case 'H':
221 			maxPageHeight = atof(optarg);
222 			if (pageHeight==0) pageHeight = maxPageHeight;
223 			break;
224 		case 'W':
225 			maxPageWidth = atof(optarg);
226 			if (pageWidth==0) pageWidth = maxPageWidth;
227 			break;
228 		case 'L':
229 			splitOverlap = atof(optarg);
230 			break;
231 		case 'm':
232 			useImagemask = TRUE;
233 			break;
234 		case 'o':
235 			diroff = (uint32) strtoul(optarg, NULL, 0);
236 			break;
237 		case 'O':		/* XXX too bad -o is already taken */
238 			output = fopen(optarg, "w");
239 			if (output == NULL) {
240 				fprintf(stderr,
241 				    "%s: %s: Cannot open output file.\n",
242 				    argv[0], optarg);
243 				exit(-2);
244 			}
245 			break;
246 		case 'l':
247 			leftmargin = atof(optarg);
248 			break;
249 		case 'a':
250 			printAll = TRUE;
251 			/* fall thru... */
252 		case 'p':
253 			generateEPSF = FALSE;
254 			break;
255 		case 'r':
256 			rotate = TRUE;
257                         if (strcmp (optarg, "auto") == 0)
258                           rotation = 0;
259                         else
260  			  rotation = atoi(optarg);
261                         switch (rotation)
262                           {
263 			  case   0:
264                           case  90:
265                           case 180:
266                           case 270:
267 			    break;
268 			  default:
269                             fprintf (stderr, "Rotation angle must be 90, 180, 270 (degrees ccw) or auto\n");
270 			    exit (-2);
271 			  }
272 			break;
273 		case 's':
274 			printAll = FALSE;
275 			break;
276 		case 'w':
277 			pageWidth = atof(optarg);
278 			break;
279 		case 'z':
280 			PSavoiddeadzone = FALSE;
281 			break;
282 		case '1':
283 			level2 = FALSE;
284 			level3 = FALSE;
285 			ascii85 = FALSE;
286 			break;
287 		case '2':
288 			level2 = TRUE;
289 			ascii85 = TRUE;			/* default to yes */
290 			break;
291 		case '3':
292 			level3 = TRUE;
293 			ascii85 = TRUE;			/* default to yes */
294 			break;
295 		case '8':
296 			ascii85 = FALSE;
297 			break;
298 		case 'x':
299 			res_unit = RESUNIT_CENTIMETER;
300 			break;
301 		case 'y':
302 			res_unit = RESUNIT_INCH;
303 			break;
304 		case '?':
305 			usage(-1);
306 		}
307 	for (; argc - optind > 0; optind++) {
308 		TIFF* tif = TIFFOpen(filename = argv[optind], "r");
309 		if (tif != NULL) {
310 			if (dirnum != -1
311                             && !TIFFSetDirectory(tif, (tdir_t)dirnum))
312 				return (-1);
313 			else if (diroff != 0 &&
314 			    !TIFFSetSubDirectory(tif, diroff))
315 				return (-1);
316 			np = TIFF2PS(output, tif, pageWidth, pageHeight,
317 				leftmargin, bottommargin, centered);
318 			TIFFClose(tif);
319 		}
320 	}
321 	if (np)
322 		PSTail(output, np);
323 	else
324 		usage(-1);
325 	if (output != stdout)
326 		fclose(output);
327 	return (0);
328 }
329 
330 static	uint16 samplesperpixel;
331 static	uint16 bitspersample;
332 static	uint16 planarconfiguration;
333 static	uint16 photometric;
334 static	uint16 compression;
335 static	uint16 extrasamples;
336 static	int alpha;
337 
338 static int
339 checkImage(TIFF* tif)
340 {
341 	switch (photometric) {
342 	case PHOTOMETRIC_YCBCR:
343 		if ((compression == COMPRESSION_JPEG || compression == COMPRESSION_OJPEG)
344 			&& planarconfiguration == PLANARCONFIG_CONTIG) {
345 			/* can rely on libjpeg to convert to RGB */
346 			TIFFSetField(tif, TIFFTAG_JPEGCOLORMODE,
347 				     JPEGCOLORMODE_RGB);
348 			photometric = PHOTOMETRIC_RGB;
349 		} else {
350 			if (level2 || level3)
351 				break;
352 			TIFFError(filename, "Can not handle image with %s",
353 			    "PhotometricInterpretation=YCbCr");
354 			return (0);
355 		}
356 		/* fall thru... */
357 	case PHOTOMETRIC_RGB:
358 		if (alpha && bitspersample != 8) {
359 			TIFFError(filename,
360 			    "Can not handle %d-bit/sample RGB image with alpha",
361 			    bitspersample);
362 			return (0);
363 		}
364 		/* fall thru... */
365 	case PHOTOMETRIC_SEPARATED:
366 	case PHOTOMETRIC_PALETTE:
367 	case PHOTOMETRIC_MINISBLACK:
368 	case PHOTOMETRIC_MINISWHITE:
369 		break;
370 	case PHOTOMETRIC_LOGL:
371 	case PHOTOMETRIC_LOGLUV:
372 		if (compression != COMPRESSION_SGILOG &&
373 		    compression != COMPRESSION_SGILOG24) {
374 			TIFFError(filename,
375 		    "Can not handle %s data with compression other than SGILog",
376 			    (photometric == PHOTOMETRIC_LOGL) ?
377 				"LogL" : "LogLuv"
378 			);
379 			return (0);
380 		}
381 		/* rely on library to convert to RGB/greyscale */
382 		TIFFSetField(tif, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_8BIT);
383 		photometric = (photometric == PHOTOMETRIC_LOGL) ?
384 		    PHOTOMETRIC_MINISBLACK : PHOTOMETRIC_RGB;
385 		bitspersample = 8;
386 		break;
387 	case PHOTOMETRIC_CIELAB:
388 		/* fall thru... */
389 	default:
390 		TIFFError(filename,
391 		    "Can not handle image with PhotometricInterpretation=%d",
392 		    photometric);
393 		return (0);
394 	}
395 	switch (bitspersample) {
396 	case 1: case 2:
397 	case 4: case 8:
398 	case 16:
399 		break;
400 	default:
401 		TIFFError(filename, "Can not handle %d-bit/sample image",
402 		    bitspersample);
403 		return (0);
404 	}
405 	if (planarconfiguration == PLANARCONFIG_SEPARATE && extrasamples > 0)
406 		TIFFWarning(filename, "Ignoring extra samples");
407 	return (1);
408 }
409 
410 #define PS_UNIT_SIZE	72.0F
411 #define	PSUNITS(npix,res)	((npix) * (PS_UNIT_SIZE / (res)))
412 
413 static	char RGBcolorimage[] = "\
414 /bwproc {\n\
415     rgbproc\n\
416     dup length 3 idiv string 0 3 0\n\
417     5 -1 roll {\n\
418 	add 2 1 roll 1 sub dup 0 eq {\n\
419 	    pop 3 idiv\n\
420 	    3 -1 roll\n\
421 	    dup 4 -1 roll\n\
422 	    dup 3 1 roll\n\
423 	    5 -1 roll put\n\
424 	    1 add 3 0\n\
425 	} { 2 1 roll } ifelse\n\
426     } forall\n\
427     pop pop pop\n\
428 } def\n\
429 /colorimage where {pop} {\n\
430     /colorimage {pop pop /rgbproc exch def {bwproc} image} bind def\n\
431 } ifelse\n\
432 ";
433 
434 /*
435  * Adobe Photoshop requires a comment line of the form:
436  *
437  * %ImageData: <cols> <rows> <depth>  <main channels> <pad channels>
438  *	<block size> <1 for binary|2 for hex> "data start"
439  *
440  * It is claimed to be part of some future revision of the EPS spec.
441  */
442 static void
443 PhotoshopBanner(FILE* fd, uint32 w, uint32 h, int bs, int nc, char* startline)
444 {
445 	fprintf(fd, "%%ImageData: %ld %ld %d %d 0 %d 2 \"",
446 	    (long) w, (long) h, bitspersample, nc, bs);
447 	fprintf(fd, startline, nc);
448 	fprintf(fd, "\"\n");
449 }
450 
451 /*
452  *   pw : image width in pixels
453  *   ph : image height in pixels
454  * pprw : image width in PS units (72 dpi)
455  * pprh : image height in PS units (72 dpi)
456  */
457 static void
458 setupPageState(TIFF* tif, uint32* pw, uint32* ph, double* pprw, double* pprh)
459 {
460 	float xres = 0.0F, yres = 0.0F;
461 
462 	TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, pw);
463 	TIFFGetField(tif, TIFFTAG_IMAGELENGTH, ph);
464 	if (res_unit == 0)
465 		TIFFGetFieldDefaulted(tif, TIFFTAG_RESOLUTIONUNIT, &res_unit);
466 	/*
467 	 * Calculate printable area.
468 	 */
469 	if (!TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres)
470             || fabs(xres) < 0.0000001)
471 		xres = PS_UNIT_SIZE;
472 	if (!TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres)
473             || fabs(yres) < 0.0000001)
474 		yres = PS_UNIT_SIZE;
475 	switch (res_unit) {
476 	case RESUNIT_CENTIMETER:
477 		xres *= 2.54F, yres *= 2.54F;
478 		break;
479 	case RESUNIT_INCH:
480 		break;
481 	case RESUNIT_NONE:
482 	default:
483 		/*
484 		 * check that the resolution is not inches before scaling it
485 		 */
486 		if (xres != PS_UNIT_SIZE || yres != PS_UNIT_SIZE)
487 		xres *= PS_UNIT_SIZE, yres *= PS_UNIT_SIZE;
488 		break;
489 	}
490 	*pprh = PSUNITS(*ph, yres);
491 	*pprw = PSUNITS(*pw, xres);
492 }
493 
494 static int
495 isCCITTCompression(TIFF* tif)
496 {
497     uint16 compress;
498     TIFFGetField(tif, TIFFTAG_COMPRESSION, &compress);
499     return (compress == COMPRESSION_CCITTFAX3 ||
500 	    compress == COMPRESSION_CCITTFAX4 ||
501 	    compress == COMPRESSION_CCITTRLE ||
502 	    compress == COMPRESSION_CCITTRLEW);
503 }
504 
505 static	tsize_t tf_bytesperrow;
506 static	tsize_t ps_bytesperrow;
507 static	tsize_t	tf_rowsperstrip;
508 static	tsize_t	tf_numberstrips;
509 static	char *hex = "0123456789abcdef";
510 
511 /*
512  * imagewidth & imageheight are 1/72 inches
513  * pagewidth & pageheight are inches
514  */
515 int
516 PlaceImage(TIFF *tif, FILE *fp, int *npages, uint32 w, uint32 h,
517            double pagewidth, double pageheight,
518 	   double imagewidth, double imageheight,
519            int splitpage, double lm, double bm, int cnt)
520 {
521         int    i       = 0;
522         int    ximages = 0;
523         int    splitaxis = 0;
524 	double xtran = 0;
525 	double ytran = 0;
526 	double xscale = 1;
527 	double yscale = 1;
528 	double left_margin    = 0;
529 	double bottom_margin  = 0;
530 	double left_offset    = lm * PS_UNIT_SIZE;
531 	double bottom_offset  = bm * PS_UNIT_SIZE;
532 	double splitwidth     = 0;
533 	double splitheight    = 0;
534 	double subimageheight = 0;
535 	double subimagewidth  = 0;
536 	double overlap        = 0;
537 	double overlapspace   = 0;
538 
539 	pagewidth *= PS_UNIT_SIZE;
540 	pageheight *= PS_UNIT_SIZE;
541 
542 	splitheight = maxPageHeight * PS_UNIT_SIZE;
543 	splitwidth  = maxPageWidth  * PS_UNIT_SIZE;
544 	overlap     = splitOverlap  * PS_UNIT_SIZE;
545         /* These have to be mutually exclusive to maintain the aspect ratio */
546         if (splitheight != 0)
547           splitaxis = VERTICAL;
548         else {
549            if (splitwidth != 0)
550              splitaxis = HORIZONTAL;
551            else {
552              fprintf (stderr, "You must specify either a maximum page height or width\n");
553              return (0);
554            }
555         }
556 
557         if (splitaxis == VERTICAL) {
558   	  if (imageheight <= splitheight) {
559 	    /* Simple case, no splitting or scaling for image height */
560 	    yscale = imageheight;
561 	    ytran = pageheight - imageheight;
562 	  } else { /* imageheight > splitheight */
563 	      subimageheight = imageheight - ((splitheight - overlap) * splitpage);
564 
565               yscale = imageheight * (pageheight / splitheight);
566 	      ytran  = pageheight - subimageheight * (pageheight / splitheight);
567 
568               if (subimageheight > splitheight) {
569 	        splitpage++;
570 	      } else {
571 		  splitpage = 0;
572 	          }
573 	  }
574 	  bottom_offset += ytran / (cnt?2:1);
575           left_margin = left_offset / (cnt ? 2 : 1);
576 	  /*
577            * WIDTH: We can't rescale height based on width so we need to make multiple
578            *   pages from each horizontal segment if the image is wider than pagewidth
579            */
580 
581           ximages = (int) ceil (imagewidth / pagewidth);
582           overlapspace = (ximages - 1) * overlap;
583           if (((imagewidth + overlapspace) * (pageheight / splitheight)) > (ximages * pagewidth)) {
584             ximages++;
585             overlapspace += overlap;
586 	  }
587           xscale = (imagewidth + overlapspace) * (pageheight / splitheight);
588 	  if (imagewidth <= pagewidth) {
589             left_offset = left_margin;
590             bottom_offset = bottom_margin;
591 	    fprintf(fp, "%f %f translate\n", left_offset, bottom_offset);
592 	    fprintf(fp, "%f %f scale\n", xscale, yscale);
593 	  } else {
594             for (i = 0; i < ximages; i++) {
595               xtran = i * (pagewidth - ((i > 0) ? overlap : 0));
596 	      left_offset = -xtran + left_margin;
597 
598  	      fprintf(fp, "%f %f translate\n", left_offset, bottom_offset);
599 	      fprintf(fp, "%f %f scale\n", xscale, yscale);
600 
601               if ( i < (ximages - 1)) {
602   	        PSpage(fp, tif, w, h);
603 	        fprintf(fp, "end\n");
604 	        fprintf(fp, "grestore\n");
605 	        fprintf(fp, "showpage\n");
606  	        (*npages)++;
607 	        fprintf(fp, "%%%%Page: %d %d\n", (*npages), (*npages));
608 	        fprintf(fp, "gsave\n");
609 	        fprintf(fp, "100 dict begin\n");
610 	        }
611 	    }
612 	  }
613         } else {  /* splitaxis is HORIZONTAL */
614           ximages = (int) ceil (imagewidth / splitwidth);
615           overlapspace = (ximages - 1) * overlap;
616           if (((imagewidth + overlapspace) * (pagewidth / splitwidth)) > (ximages * pagewidth)) {
617             ximages++;
618             overlapspace += overlap;
619 	  }
620   	  if (ximages == 1) {
621 	    /* Simple case, no splitting or scaling for image width */
622 	    xscale = imagewidth;
623 	    xtran = 0;
624             splitpage = 0;
625 	  } else {
626 	      subimagewidth  = imagewidth  - ((splitwidth - overlap) * splitpage);
627 
628               xscale = imagewidth * (pagewidth / splitwidth);
629 	      xtran  = imagewidth - (subimagewidth * (pagewidth / splitwidth));
630 
631               splitheight = pageheight;
632 	      subimageheight = imageheight - ((splitheight - overlap) * splitpage);
633               yscale = (imageheight + overlapspace);
634 	      ytran  = pageheight - subimageheight  + (overlapspace * (pagewidth / splitwidth));
635 
636               if (subimageheight > splitheight) {
637 	        splitpage++;
638 	      } else {
639 		  splitpage = 0;
640 	          }
641 	  }
642           bottom_margin = bottom_offset / (cnt ? 2 : 1);
643  	  bottom_offset = bottom_margin + ytran;
644           left_margin = left_offset / (cnt ? 2 : 1);
645 	  if (imagewidth <= pagewidth) {
646             left_offset = left_margin;
647             bottom_offset = bottom_margin;
648 	    fprintf(fp, "%f %f translate\n", left_offset, bottom_offset);
649 	    fprintf(fp, "%f %f scale\n", xscale, yscale);
650 	  } else {
651               for (i = 0; i < ximages; i++) {
652                 xtran = i * (pagewidth - ((i > 0) ? overlap : 0));
653 	        left_offset = left_margin - xtran;
654  	        fprintf(fp, "%f %f translate\n", left_offset, bottom_offset);
655 	        fprintf(fp, "%f %f scale\n", xscale, yscale);
656                 if ( i < (ximages - 1)) {
657   	          PSpage(fp, tif, w, h);
658 	          fprintf(fp, "end\n");
659 	          fprintf(fp, "grestore\n");
660 	          fprintf(fp, "showpage\n");
661  	          (*npages)++;
662 	          fprintf(fp, "%%%%Page: %d %d\n", (*npages), (*npages));
663 	          fprintf(fp, "gsave\n");
664 	          fprintf(fp, "100 dict begin\n");
665 	        }
666 	      }
667 	  }
668 	}
669 
670 	if (rotate)
671 	    {
672 	    if (rotation == 180 )
673               {
674     	      fprintf(fp, "%f %f translate\n", left_offset, bottom_offset);
675 	      fprintf(fp, "%f %f scale\n", xscale, yscale);
676               }
677             else
678               {
679     	      fprintf(fp, "%f %f translate\n", bottom_offset, left_offset);
680 	      fprintf(fp, "%f %f scale\n", yscale, xscale);
681               }
682 	    fprintf (fp, "1 1 translate %d rotate\n", rotation);
683             }
684 
685 	return splitpage;
686 }
687 
688 /* returns the sequence number of the page processed */
689 int
690 TIFF2PS(FILE* fd, TIFF* tif,
691 	double pw, double ph, double lm, double bm, int cnt)
692 {
693 	uint32 w = 0, h = 0;
694 	float  ox, oy;
695         double maxsource, maxtarget;    /* Used for auto rotations */
696         double hcenter, vcenter;        /* Used for centering */
697         double prw, prh;    /* Original Image width and height in Postscript points */
698 	double psw, psh;    /* Scaled image width and height in Postscript points */
699 	double xscale = 1.0, yscale = 1.0, scale = 1.0;
700 	double left_offset = lm * PS_UNIT_SIZE;
701 	double bottom_offset = bm * PS_UNIT_SIZE;
702 	uint32 subfiletype;
703 	uint16* sampleinfo;
704 	static int npages = 0;
705 	int split;
706 
707 	if (!TIFFGetField(tif, TIFFTAG_XPOSITION, &ox))
708 		ox = 0;
709 	if (!TIFFGetField(tif, TIFFTAG_YPOSITION, &oy))
710 		oy = 0;
711 	do {
712 		tf_numberstrips = TIFFNumberOfStrips(tif);
713 		TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP,
714 		    &tf_rowsperstrip);
715 		setupPageState(tif, &w, &h, &prw, &prh);
716                 if (pw != 0) {
717                     psw = pw * PS_UNIT_SIZE;
718 		    if (res_unit == RESUNIT_CENTIMETER)
719 			psw *= 2.54F;
720 		}
721                 else
722                   psw = prw;
723 
724                 if (ph != 0) {
725                     psh = ph * PS_UNIT_SIZE;
726  		    if (res_unit == RESUNIT_CENTIMETER)
727 			psh *= 2.54F;
728 		}
729                 else
730                   psh = prh;
731 
732                 /* auto rotate for best fit */
733                 if (rotate && rotation == 0) {
734                   maxsource = (prw >= prh) ? prw : prh;
735                   maxtarget = (psw >= psh) ? psw : psh;
736                   if (((maxsource == prw) && (maxtarget != psw)) ||
737                       ((maxsource == prh) && (maxtarget != psh))) {
738 		    rotation = 90;
739 		  }
740 		}
741 
742                 /* scaling depends on rotation and new page size */
743                 switch (rotation) {
744                   case   0:
745                   case 180:
746                     xscale = (psw - left_offset)/prw;
747                     yscale = (psh - bottom_offset)/prh;
748 		    if (!npages)
749 		      PSHead(fd, tif, w, h, psw, psh, ox, oy);
750                     break;
751 		  case  90:
752                   case 270:
753                     xscale = (psw - bottom_offset) /prh;
754                     yscale = (psh - left_offset) /prw;
755 		    if (!npages)
756 		      PSHead(fd, tif, w, h, psh, psw, oy, ox);
757                     break;
758 		}
759 		TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE,
760 		    &bitspersample);
761 		TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL,
762 		    &samplesperpixel);
763 		TIFFGetFieldDefaulted(tif, TIFFTAG_PLANARCONFIG,
764 		    &planarconfiguration);
765 		TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression);
766 		TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES,
767 		    &extrasamples, &sampleinfo);
768 		alpha = (extrasamples == 1 &&
769 			 sampleinfo[0] == EXTRASAMPLE_ASSOCALPHA);
770 		if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric)) {
771 			switch (samplesperpixel - extrasamples) {
772 			case 1:
773 				if (isCCITTCompression(tif))
774 					photometric = PHOTOMETRIC_MINISWHITE;
775 				else
776 					photometric = PHOTOMETRIC_MINISBLACK;
777 				break;
778 			case 3:
779 				photometric = PHOTOMETRIC_RGB;
780 				break;
781 			case 4:
782 				photometric = PHOTOMETRIC_SEPARATED;
783 				break;
784 			}
785 		}
786 		if (checkImage(tif)) {
787 			tf_bytesperrow = TIFFScanlineSize(tif);
788 			npages++;
789 			fprintf(fd, "%%%%Page: %d %d\n", npages, npages);
790 			if (!generateEPSF && ( level2 || level3 )) {
791 				fprintf(fd,
792 	"1 dict begin /PageSize [ %f %f ] def currentdict end setpagedevice\n",
793 					psw, psh);
794 				fputs(
795 	"<<\n  /Policies <<\n    /PageSize 3\n  >>\n>> setpagedevice\n",
796 				      fd);
797 			}
798 			fprintf(fd, "gsave\n");
799 			fprintf(fd, "100 dict begin\n");
800                         /* N.B. Setting maxPageHeight also sets ph if not set explicitly */
801 			if (pw != 0 || ph != 0) {
802 				if (maxPageHeight || maxPageWidth)  { /* used -H or -W options */
803 				  split = PlaceImage(tif,fd,&npages,w,h,pw,ph,prw,prh,
804 				     0,lm,bm,cnt);
805 					while( split ) {
806 					    PSpage(fd, tif, w, h);
807 					    fprintf(fd, "end\n");
808 					    fprintf(fd, "grestore\n");
809 					    fprintf(fd, "showpage\n");
810 					    npages++;
811 					    fprintf(fd, "%%%%Page: %d %d\n",
812 						    npages, npages);
813 					    fprintf(fd, "gsave\n");
814 					    fprintf(fd, "100 dict begin\n");
815 					    split = PlaceImage(tif,fd,&npages,w,h,pw,ph,prw,prh,
816 						split,lm,bm,cnt);
817 					}
818 				}
819                                 else {
820 				    /* NB: maintain image aspect ratio */
821                                     scale = (xscale < yscale) ? xscale : yscale;
822 				    if (scale > 1.0)
823 				       	scale = 1.0;
824 
825                                     /* Adjust offsets for centering */
826 				    if (cnt) {
827                                       switch (rotation) {
828 					case   90:
829                                         case  270:
830 					    hcenter = (psw - prh * scale) / 2;
831 					    vcenter = (psh - prw * scale) / 2;
832                                             break;
833 					case    0:
834                                         case  180:
835 					default:
836 					    hcenter = (psw - prw * scale) / 2;
837 					    vcenter = (psh - prh * scale) / 2;
838                                             break;
839 				      }
840 				    }
841 				  else
842                                       hcenter = 0.0, vcenter = 0.0;
843                                   if (cnt)
844   				     fprintf (fd, "%f %f translate\n", hcenter, vcenter);
845                                   switch (rotation) {
846  				    case 0:
847 				        fprintf (fd, "%f %f scale\n", prw * scale, prh * scale);
848                                         break;
849  			       	    case 90:
850 					fprintf (fd, "%f %f scale\n1 0 translate 90 rotate\n", prh * scale, prw * scale);
851                                         break;
852                                     case 180:
853 					fprintf (fd, "%f %f scale\n1 1 translate 180 rotate\n", prw * scale, prh * scale);
854 					break;
855 				    case 270:
856 					fprintf (fd, "%f %f scale\n0 1 translate 270 rotate\n", prh * scale, prw * scale);
857 				        break;
858 			            default:
859 			                fprintf (stderr, "Unsupported angle. No rotation\n");
860 					fprintf (fd, "%f %f scale\n", prw * scale, prh * scale);
861                                         break;
862 				  }
863 				}
864 			} else {
865 			    if (rotate)
866                               {
867 			      /* Width and height have already been enchanged for 90/270 rotations */
868 			      switch (rotation) {
869 			         case   0:
870 			             fprintf (fd, "%f %f scale\n", prw, prh);
871 				 case  90:
872 				     fprintf (fd, "%f %f scale\n1 0 translate 90 rotate\n", prw, prh);
873                                      break;
874                                  case 180:
875 			             fprintf (fd, "%f %f scale\n1 1 translate 180 rotate\n", prw, prh);
876                                      break;
877 			         case 270:
878 				     fprintf (fd, "%f %f scale\n0 1 translate 270 rotate\n", prw, prh);
879                                      break;
880 			         default:
881 			             fprintf (stderr, "Unsupported angle. No rotation\n");
882 			             fprintf( fd, "%f %f scale\n", prw, prh);
883                                      break;
884 			         }
885 			      }
886                             else
887 			      {
888 			      /* fprintf (stderr, "No rotation\n"); */
889 			      fprintf (fd, "%f %f scale\n", prw, prh);
890 			      }
891 			}
892 			PSpage(fd, tif, w, h);
893 			fprintf(fd, "end\n");
894 			fprintf(fd, "grestore\n");
895 			fprintf(fd, "showpage\n");
896 		}
897 		if (generateEPSF)
898 			break;
899 		TIFFGetFieldDefaulted(tif, TIFFTAG_SUBFILETYPE, &subfiletype);
900 	} while (((subfiletype & FILETYPE_PAGE) || printAll) &&
901 	    TIFFReadDirectory(tif));
902 
903 	return(npages);
904 }
905 
906 static char DuplexPreamble[] = "\
907 %%BeginFeature: *Duplex True\n\
908 systemdict begin\n\
909   /languagelevel where { pop languagelevel } { 1 } ifelse\n\
910   2 ge { 1 dict dup /Duplex true put setpagedevice }\n\
911   { statusdict /setduplex known { statusdict begin setduplex true end } if\n\
912   } ifelse\n\
913 end\n\
914 %%EndFeature\n\
915 ";
916 
917 static char TumblePreamble[] = "\
918 %%BeginFeature: *Tumble True\n\
919 systemdict begin\n\
920   /languagelevel where { pop languagelevel } { 1 } ifelse\n\
921   2 ge { 1 dict dup /Tumble true put setpagedevice }\n\
922   { statusdict /settumble known { statusdict begin true settumble end } if\n\
923   } ifelse\n\
924 end\n\
925 %%EndFeature\n\
926 ";
927 
928 static char AvoidDeadZonePreamble[] = "\
929 gsave newpath clippath pathbbox grestore\n\
930   4 2 roll 2 copy translate\n\
931   exch 3 1 roll sub 3 1 roll sub exch\n\
932   currentpagedevice /PageSize get aload pop\n\
933   exch 3 1 roll div 3 1 roll div abs exch abs\n\
934   2 copy gt { exch } if pop\n\
935   dup 1 lt { dup scale } { pop } ifelse\n\
936 ";
937 
938 void
939 PSHead(FILE *fd, TIFF *tif, uint32 w, uint32 h,
940        double pw, double ph, double ox, double oy)
941 {
942 	time_t t;
943 
944 	(void) tif; (void) w; (void) h;
945 	t = time(0);
946 	fprintf(fd, "%%!PS-Adobe-3.0%s\n", generateEPSF ? " EPSF-3.0" : "");
947 	fprintf(fd, "%%%%Creator: tiff2ps\n");
948 	fprintf(fd, "%%%%Title: %s\n", filename);
949 	fprintf(fd, "%%%%CreationDate: %s", ctime(&t));
950 	fprintf(fd, "%%%%DocumentData: Clean7Bit\n");
951 	fprintf(fd, "%%%%Origin: %ld %ld\n", (long) ox, (long) oy);
952 	/* NB: should use PageBoundingBox */
953         if (rotate && (rotation == 90 || rotation == 270))
954  	  fprintf(fd, "%%%%BoundingBox: 0 0 %ld %ld\n",
955 	    (long) ceil(ph), (long) ceil(pw));
956         else
957           fprintf(fd, "%%%%BoundingBox: 0 0 %ld %ld\n",
958 	    (long) ceil(pw), (long) ceil(ph));
959 
960 	fprintf(fd, "%%%%LanguageLevel: %d\n", (level3 ? 3 : (level2 ? 2 : 1)));
961 	fprintf(fd, "%%%%Pages: (atend)\n");
962 	fprintf(fd, "%%%%EndComments\n");
963 	fprintf(fd, "%%%%BeginSetup\n");
964 	if (PSduplex)
965 		fprintf(fd, "%s", DuplexPreamble);
966 	if (PStumble)
967 		fprintf(fd, "%s", TumblePreamble);
968 	if (PSavoiddeadzone && (level2 || level3))
969 		fprintf(fd, "%s", AvoidDeadZonePreamble);
970 	fprintf(fd, "%%%%EndSetup\n");
971 }
972 
973 void
974 PSTail(FILE *fd, int npages)
975 {
976 	fprintf(fd, "%%%%Trailer\n");
977 	fprintf(fd, "%%%%Pages: %d\n", npages);
978 	fprintf(fd, "%%%%EOF\n");
979 }
980 
981 static int
982 checkcmap(TIFF* tif, int n, uint16* r, uint16* g, uint16* b)
983 {
984 	(void) tif;
985 	while (n-- > 0)
986 		if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256)
987 			return (16);
988 	TIFFWarning(filename, "Assuming 8-bit colormap");
989 	return (8);
990 }
991 
992 static void
993 PS_Lvl2colorspace(FILE* fd, TIFF* tif)
994 {
995 	uint16 *rmap, *gmap, *bmap;
996 	int i, num_colors;
997 	const char * colorspace_p;
998 
999 	switch ( photometric )
1000 	{
1001 	case PHOTOMETRIC_SEPARATED:
1002 		colorspace_p = "CMYK";
1003 		break;
1004 
1005 	case PHOTOMETRIC_RGB:
1006 		colorspace_p = "RGB";
1007 		break;
1008 
1009 	default:
1010 		colorspace_p = "Gray";
1011 	}
1012 
1013 	/*
1014 	 * Set up PostScript Level 2 colorspace according to
1015 	 * section 4.8 in the PostScript refenence manual.
1016 	 */
1017 	fputs("% PostScript Level 2 only.\n", fd);
1018 	if (photometric != PHOTOMETRIC_PALETTE) {
1019 		if (photometric == PHOTOMETRIC_YCBCR) {
1020 		    /* MORE CODE HERE */
1021 		}
1022 		fprintf(fd, "/Device%s setcolorspace\n", colorspace_p );
1023 		return;
1024 	}
1025 
1026 	/*
1027 	 * Set up an indexed/palette colorspace
1028 	 */
1029 	num_colors = (1 << bitspersample);
1030 	if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) {
1031 		TIFFError(filename,
1032 			"Palette image w/o \"Colormap\" tag");
1033 		return;
1034 	}
1035 	if (checkcmap(tif, num_colors, rmap, gmap, bmap) == 16) {
1036 		/*
1037 		 * Convert colormap to 8-bits values.
1038 		 */
1039 #define	CVT(x)		(((x) * 255) / ((1L<<16)-1))
1040 		for (i = 0; i < num_colors; i++) {
1041 			rmap[i] = CVT(rmap[i]);
1042 			gmap[i] = CVT(gmap[i]);
1043 			bmap[i] = CVT(bmap[i]);
1044 		}
1045 #undef CVT
1046 	}
1047 	fprintf(fd, "[ /Indexed /DeviceRGB %d", num_colors - 1);
1048 	if (ascii85) {
1049 		Ascii85Init();
1050 		fputs("\n<~", fd);
1051 		ascii85breaklen -= 2;
1052 	} else
1053 		fputs(" <", fd);
1054 	for (i = 0; i < num_colors; i++) {
1055 		if (ascii85) {
1056 			Ascii85Put((unsigned char)rmap[i], fd);
1057 			Ascii85Put((unsigned char)gmap[i], fd);
1058 			Ascii85Put((unsigned char)bmap[i], fd);
1059 		} else {
1060 			fputs((i % 8) ? " " : "\n  ", fd);
1061 			fprintf(fd, "%02x%02x%02x",
1062 			    rmap[i], gmap[i], bmap[i]);
1063 		}
1064 	}
1065 	if (ascii85)
1066 		Ascii85Flush(fd);
1067 	else
1068 		fputs(">\n", fd);
1069 	fputs("] setcolorspace\n", fd);
1070 }
1071 
1072 static int
1073 PS_Lvl2ImageDict(FILE* fd, TIFF* tif, uint32 w, uint32 h)
1074 {
1075 	int use_rawdata;
1076 	uint32 tile_width, tile_height;
1077 	uint16 predictor, minsamplevalue, maxsamplevalue;
1078 	int repeat_count;
1079 	char im_h[64], im_x[64], im_y[64];
1080 	char * imageOp = "image";
1081 
1082 	if ( useImagemask && (bitspersample == 1) )
1083 		imageOp = "imagemask";
1084 
1085 	(void)strcpy(im_x, "0");
1086 	(void)sprintf(im_y, "%lu", (long) h);
1087 	(void)sprintf(im_h, "%lu", (long) h);
1088 	tile_width = w;
1089 	tile_height = h;
1090 	if (TIFFIsTiled(tif)) {
1091 		repeat_count = TIFFNumberOfTiles(tif);
1092 		TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tile_width);
1093 		TIFFGetField(tif, TIFFTAG_TILELENGTH, &tile_height);
1094 		if (tile_width > w || tile_height > h ||
1095 		    (w % tile_width) != 0 || (h % tile_height != 0)) {
1096 			/*
1097 			 * The tiles does not fit image width and height.
1098 			 * Set up a clip rectangle for the image unit square.
1099 			 */
1100 			fputs("0 0 1 1 rectclip\n", fd);
1101 		}
1102 		if (tile_width < w) {
1103 			fputs("/im_x 0 def\n", fd);
1104 			(void)strcpy(im_x, "im_x neg");
1105 		}
1106 		if (tile_height < h) {
1107 			fputs("/im_y 0 def\n", fd);
1108 			(void)sprintf(im_y, "%lu im_y sub", (unsigned long) h);
1109 		}
1110 	} else {
1111 		repeat_count = tf_numberstrips;
1112 		tile_height = tf_rowsperstrip;
1113 		if (tile_height > h)
1114 			tile_height = h;
1115 		if (repeat_count > 1) {
1116 			fputs("/im_y 0 def\n", fd);
1117 			fprintf(fd, "/im_h %lu def\n",
1118 			    (unsigned long) tile_height);
1119 			(void)strcpy(im_h, "im_h");
1120 			(void)sprintf(im_y, "%lu im_y sub", (unsigned long) h);
1121 		}
1122 	}
1123 
1124 	/*
1125 	 * Output start of exec block
1126 	 */
1127 	fputs("{ % exec\n", fd);
1128 
1129 	if (repeat_count > 1)
1130 		fprintf(fd, "%d { %% repeat\n", repeat_count);
1131 
1132 	/*
1133 	 * Output filter options and image dictionary.
1134 	 */
1135 	if (ascii85)
1136 		fputs(" /im_stream currentfile /ASCII85Decode filter def\n",
1137 		    fd);
1138 	fputs(" <<\n", fd);
1139 	fputs("  /ImageType 1\n", fd);
1140 	fprintf(fd, "  /Width %lu\n", (unsigned long) tile_width);
1141 	/*
1142 	 * Workaround for some software that may crash when last strip
1143 	 * of image contains fewer number of scanlines than specified
1144 	 * by the `/Height' variable. So for stripped images with multiple
1145 	 * strips we will set `/Height' as `im_h', because one is
1146 	 * recalculated for each strip - including the (smaller) final strip.
1147 	 * For tiled images and images with only one strip `/Height' will
1148 	 * contain number of scanlines in tile (or image height in case of
1149 	 * one-stripped image).
1150 	 */
1151 	if (TIFFIsTiled(tif) || tf_numberstrips == 1)
1152 		fprintf(fd, "  /Height %lu\n", (unsigned long) tile_height);
1153 	else
1154 		fprintf(fd, "  /Height im_h\n");
1155 
1156 	if (planarconfiguration == PLANARCONFIG_SEPARATE && samplesperpixel > 1)
1157 		fputs("  /MultipleDataSources true\n", fd);
1158 	fprintf(fd, "  /ImageMatrix [ %lu 0 0 %ld %s %s ]\n",
1159 	    (unsigned long) w, - (long)h, im_x, im_y);
1160 	fprintf(fd, "  /BitsPerComponent %d\n", bitspersample);
1161 	fprintf(fd, "  /Interpolate %s\n", interpolate ? "true" : "false");
1162 
1163 	switch (samplesperpixel - extrasamples) {
1164 	case 1:
1165 		switch (photometric) {
1166 		case PHOTOMETRIC_MINISBLACK:
1167 			fputs("  /Decode [0 1]\n", fd);
1168 			break;
1169 		case PHOTOMETRIC_MINISWHITE:
1170 			switch (compression) {
1171 			case COMPRESSION_CCITTRLE:
1172 			case COMPRESSION_CCITTRLEW:
1173 			case COMPRESSION_CCITTFAX3:
1174 			case COMPRESSION_CCITTFAX4:
1175 				/*
1176 				 * Manage inverting with /Blackis1 flag
1177 				 * since there migth be uncompressed parts
1178 				 */
1179 				fputs("  /Decode [0 1]\n", fd);
1180 				break;
1181 			default:
1182 				/*
1183 				 * ERROR...
1184 				 */
1185 				fputs("  /Decode [1 0]\n", fd);
1186 				break;
1187 			}
1188 			break;
1189 		case PHOTOMETRIC_PALETTE:
1190 			TIFFGetFieldDefaulted(tif, TIFFTAG_MINSAMPLEVALUE,
1191 			    &minsamplevalue);
1192 			TIFFGetFieldDefaulted(tif, TIFFTAG_MAXSAMPLEVALUE,
1193 			    &maxsamplevalue);
1194 			fprintf(fd, "  /Decode [%u %u]\n",
1195 				    minsamplevalue, maxsamplevalue);
1196 			break;
1197 		default:
1198 			/*
1199 			 * ERROR ?
1200 			 */
1201 			fputs("  /Decode [0 1]\n", fd);
1202 			break;
1203 		}
1204 		break;
1205 	case 3:
1206 		switch (photometric) {
1207 		case PHOTOMETRIC_RGB:
1208 			fputs("  /Decode [0 1 0 1 0 1]\n", fd);
1209 			break;
1210 		case PHOTOMETRIC_MINISWHITE:
1211 		case PHOTOMETRIC_MINISBLACK:
1212 		default:
1213 			/*
1214 			 * ERROR??
1215 			 */
1216 			fputs("  /Decode [0 1 0 1 0 1]\n", fd);
1217 			break;
1218 		}
1219 		break;
1220 	case 4:
1221 		/*
1222 		 * ERROR??
1223 		 */
1224 		fputs("  /Decode [0 1 0 1 0 1 0 1]\n", fd);
1225 		break;
1226 	}
1227 	fputs("  /DataSource", fd);
1228 	if (planarconfiguration == PLANARCONFIG_SEPARATE &&
1229 	    samplesperpixel > 1)
1230 		fputs(" [", fd);
1231 	if (ascii85)
1232 		fputs(" im_stream", fd);
1233 	else
1234 		fputs(" currentfile /ASCIIHexDecode filter", fd);
1235 
1236 	use_rawdata = TRUE;
1237 	switch (compression) {
1238 	case COMPRESSION_NONE:		/* 1: uncompressed */
1239 		break;
1240 	case COMPRESSION_CCITTRLE:	/* 2: CCITT modified Huffman RLE */
1241 	case COMPRESSION_CCITTRLEW:	/* 32771: #1 w/ word alignment */
1242 	case COMPRESSION_CCITTFAX3:	/* 3: CCITT Group 3 fax encoding */
1243 	case COMPRESSION_CCITTFAX4:	/* 4: CCITT Group 4 fax encoding */
1244 		fputs("\n\t<<\n", fd);
1245 		if (compression == COMPRESSION_CCITTFAX3) {
1246 			uint32 g3_options;
1247 
1248 			fputs("\t /EndOfLine true\n", fd);
1249 			fputs("\t /EndOfBlock false\n", fd);
1250 			if (!TIFFGetField(tif, TIFFTAG_GROUP3OPTIONS,
1251 					    &g3_options))
1252 				g3_options = 0;
1253 			if (g3_options & GROUP3OPT_2DENCODING)
1254 				fprintf(fd, "\t /K %s\n", im_h);
1255 			if (g3_options & GROUP3OPT_UNCOMPRESSED)
1256 				fputs("\t /Uncompressed true\n", fd);
1257 			if (g3_options & GROUP3OPT_FILLBITS)
1258 				fputs("\t /EncodedByteAlign true\n", fd);
1259 		}
1260 		if (compression == COMPRESSION_CCITTFAX4) {
1261 			uint32 g4_options;
1262 
1263 			fputs("\t /K -1\n", fd);
1264 			TIFFGetFieldDefaulted(tif, TIFFTAG_GROUP4OPTIONS,
1265 					       &g4_options);
1266 			if (g4_options & GROUP4OPT_UNCOMPRESSED)
1267 				fputs("\t /Uncompressed true\n", fd);
1268 		}
1269 		if (!(tile_width == w && w == 1728U))
1270 			fprintf(fd, "\t /Columns %lu\n",
1271 			    (unsigned long) tile_width);
1272 		fprintf(fd, "\t /Rows %s\n", im_h);
1273 		if (compression == COMPRESSION_CCITTRLE ||
1274 		    compression == COMPRESSION_CCITTRLEW) {
1275 			fputs("\t /EncodedByteAlign true\n", fd);
1276 			fputs("\t /EndOfBlock false\n", fd);
1277 		}
1278 		if (photometric == PHOTOMETRIC_MINISBLACK)
1279 			fputs("\t /BlackIs1 true\n", fd);
1280 		fprintf(fd, "\t>> /CCITTFaxDecode filter");
1281 		break;
1282 	case COMPRESSION_LZW:	/* 5: Lempel-Ziv & Welch */
1283 		TIFFGetFieldDefaulted(tif, TIFFTAG_PREDICTOR, &predictor);
1284 		if (predictor == 2) {
1285 			fputs("\n\t<<\n", fd);
1286 			fprintf(fd, "\t /Predictor %u\n", predictor);
1287 			fprintf(fd, "\t /Columns %lu\n",
1288 			    (unsigned long) tile_width);
1289 			fprintf(fd, "\t /Colors %u\n", samplesperpixel);
1290 			fprintf(fd, "\t /BitsPerComponent %u\n",
1291 			    bitspersample);
1292 			fputs("\t>>", fd);
1293 		}
1294 		fputs(" /LZWDecode filter", fd);
1295 		break;
1296 	case COMPRESSION_DEFLATE:	/* 5: ZIP */
1297 	case COMPRESSION_ADOBE_DEFLATE:
1298 		if ( level3 ) {
1299 			 TIFFGetFieldDefaulted(tif, TIFFTAG_PREDICTOR, &predictor);
1300 			 if (predictor > 1) {
1301 				fprintf(fd, "\t %% PostScript Level 3 only.");
1302 				fputs("\n\t<<\n", fd);
1303 				fprintf(fd, "\t /Predictor %u\n", predictor);
1304 				fprintf(fd, "\t /Columns %lu\n",
1305 					(unsigned long) tile_width);
1306 				fprintf(fd, "\t /Colors %u\n", samplesperpixel);
1307 					fprintf(fd, "\t /BitsPerComponent %u\n",
1308 					bitspersample);
1309 				fputs("\t>>", fd);
1310 			 }
1311 			 fputs(" /FlateDecode filter", fd);
1312 		} else {
1313 			use_rawdata = FALSE ;
1314 		}
1315 		break;
1316 	case COMPRESSION_PACKBITS:	/* 32773: Macintosh RLE */
1317 		fputs(" /RunLengthDecode filter", fd);
1318 		use_rawdata = TRUE;
1319 	    break;
1320 	case COMPRESSION_OJPEG:		/* 6: !6.0 JPEG */
1321 	case COMPRESSION_JPEG:		/* 7: %JPEG DCT compression */
1322 #ifdef notdef
1323 		/*
1324 		 * Code not tested yet
1325 		 */
1326 		fputs(" /DCTDecode filter", fd);
1327 		use_rawdata = TRUE;
1328 #else
1329 		use_rawdata = FALSE;
1330 #endif
1331 		break;
1332 	case COMPRESSION_NEXT:		/* 32766: NeXT 2-bit RLE */
1333 	case COMPRESSION_THUNDERSCAN:	/* 32809: ThunderScan RLE */
1334 	case COMPRESSION_PIXARFILM:	/* 32908: Pixar companded 10bit LZW */
1335 	case COMPRESSION_JBIG:		/* 34661: ISO JBIG */
1336 		use_rawdata = FALSE;
1337 		break;
1338 	case COMPRESSION_SGILOG:	/* 34676: SGI LogL or LogLuv */
1339 	case COMPRESSION_SGILOG24:	/* 34677: SGI 24-bit LogLuv */
1340 		use_rawdata = FALSE;
1341 		break;
1342 	default:
1343 		/*
1344 		 * ERROR...
1345 		 */
1346 		use_rawdata = FALSE;
1347 		break;
1348 	}
1349 	if (planarconfiguration == PLANARCONFIG_SEPARATE &&
1350 	    samplesperpixel > 1) {
1351 		uint16 i;
1352 
1353 		/*
1354 		 * NOTE: This code does not work yet...
1355 		 */
1356 		for (i = 1; i < samplesperpixel; i++)
1357 			fputs(" dup", fd);
1358 		fputs(" ]", fd);
1359 	}
1360 
1361 	fprintf( fd, "\n >> %s\n", imageOp );
1362 	if (ascii85)
1363 		fputs(" im_stream status { im_stream flushfile } if\n", fd);
1364 	if (repeat_count > 1) {
1365 		if (tile_width < w) {
1366 			fprintf(fd, " /im_x im_x %lu add def\n",
1367 			    (unsigned long) tile_width);
1368 			if (tile_height < h) {
1369 				fprintf(fd, " im_x %lu ge {\n",
1370 				    (unsigned long) w);
1371 				fputs("  /im_x 0 def\n", fd);
1372 				fprintf(fd, " /im_y im_y %lu add def\n",
1373 				    (unsigned long) tile_height);
1374 				fputs(" } if\n", fd);
1375 			}
1376 		}
1377 		if (tile_height < h) {
1378 			if (tile_width >= w) {
1379 				fprintf(fd, " /im_y im_y %lu add def\n",
1380 				    (unsigned long) tile_height);
1381 				if (!TIFFIsTiled(tif)) {
1382 					fprintf(fd, " /im_h %lu im_y sub",
1383 					    (unsigned long) h);
1384 					fprintf(fd, " dup %lu gt { pop",
1385 					    (unsigned long) tile_height);
1386 					fprintf(fd, " %lu } if def\n",
1387 					    (unsigned long) tile_height);
1388 				}
1389 			}
1390 		}
1391 		fputs("} repeat\n", fd);
1392 	}
1393 	/*
1394 	 * End of exec function
1395 	 */
1396 	fputs("}\n", fd);
1397 
1398 	return(use_rawdata);
1399 }
1400 
1401 /* Flip the byte order of buffers with 16 bit samples */
1402 static void
1403 PS_FlipBytes(unsigned char* buf, tsize_t count)
1404 {
1405 	int i;
1406 	unsigned char temp;
1407 
1408 	if (count <= 0 || bitspersample <= 8) {
1409 		return;
1410 	}
1411 
1412 	count--;
1413 
1414 	for (i = 0; i < count; i += 2) {
1415 		temp = buf[i];
1416 		buf[i] = buf[i + 1];
1417 		buf[i + 1] = temp;
1418 	}
1419 }
1420 
1421 #define MAXLINE		36
1422 
1423 int
1424 PS_Lvl2page(FILE* fd, TIFF* tif, uint32 w, uint32 h)
1425 {
1426 	uint16 fillorder;
1427 	int use_rawdata, tiled_image, breaklen = MAXLINE;
1428 	uint32 chunk_no, num_chunks;
1429         uint64 *bc;
1430 	unsigned char *buf_data, *cp;
1431 	tsize_t chunk_size, byte_count;
1432 
1433 #if defined( EXP_ASCII85ENCODER )
1434 	tsize_t			ascii85_l;	/* Length, in bytes, of ascii85_p[] data */
1435 	uint8		*	ascii85_p = 0;	/* Holds ASCII85 encoded data */
1436 #endif
1437 
1438 	PS_Lvl2colorspace(fd, tif);
1439 	use_rawdata = PS_Lvl2ImageDict(fd, tif, w, h);
1440 
1441 /* See http://bugzilla.remotesensing.org/show_bug.cgi?id=80 */
1442 #ifdef ENABLE_BROKEN_BEGINENDDATA
1443 	fputs("%%BeginData:\n", fd);
1444 #endif
1445 	fputs("exec\n", fd);
1446 
1447 	tiled_image = TIFFIsTiled(tif);
1448 	if (tiled_image) {
1449 		num_chunks = TIFFNumberOfTiles(tif);
1450 		TIFFGetField(tif, TIFFTAG_TILEBYTECOUNTS, &bc);
1451 	} else {
1452 		num_chunks = TIFFNumberOfStrips(tif);
1453 		TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &bc);
1454 	}
1455 
1456 	if (use_rawdata) {
1457 		chunk_size = (tsize_t) bc[0];
1458 		for (chunk_no = 1; chunk_no < num_chunks; chunk_no++)
1459 			if ((tsize_t) bc[chunk_no] > chunk_size)
1460 				chunk_size = (tsize_t) bc[chunk_no];
1461 	} else {
1462 		if (tiled_image)
1463 			chunk_size = TIFFTileSize(tif);
1464 		else
1465 			chunk_size = TIFFStripSize(tif);
1466 	}
1467 	buf_data = (unsigned char *)_TIFFmalloc(chunk_size);
1468 	if (!buf_data) {
1469 		TIFFError(filename, "Can't alloc %lu bytes for %s.",
1470 			(unsigned long) chunk_size, tiled_image ? "tiles" : "strips");
1471 		return(FALSE);
1472 	}
1473 
1474 #if defined( EXP_ASCII85ENCODER )
1475 	if ( ascii85 ) {
1476 	    /*
1477 	     * Allocate a buffer to hold the ASCII85 encoded data.  Note
1478 	     * that it is allocated with sufficient room to hold the
1479 	     * encoded data (5*chunk_size/4) plus the EOD marker (+8)
1480 	     * and formatting line breaks.  The line breaks are more
1481 	     * than taken care of by using 6*chunk_size/4 rather than
1482 	     * 5*chunk_size/4.
1483 	     */
1484 
1485 	    ascii85_p = _TIFFmalloc( (chunk_size+(chunk_size/2)) + 8 );
1486 
1487 	    if ( !ascii85_p ) {
1488 		_TIFFfree( buf_data );
1489 
1490 		TIFFError( filename, "Cannot allocate ASCII85 encoding buffer." );
1491 		return ( FALSE );
1492 	    }
1493 	}
1494 #endif
1495 
1496 	TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &fillorder);
1497 	for (chunk_no = 0; chunk_no < num_chunks; chunk_no++) {
1498 		if (ascii85)
1499 			Ascii85Init();
1500 		else
1501 			breaklen = MAXLINE;
1502 		if (use_rawdata) {
1503 			if (tiled_image)
1504 				byte_count = TIFFReadRawTile(tif, chunk_no,
1505 						  buf_data, chunk_size);
1506 			else
1507 				byte_count = TIFFReadRawStrip(tif, chunk_no,
1508 						  buf_data, chunk_size);
1509 			if (fillorder == FILLORDER_LSB2MSB)
1510 			    TIFFReverseBits(buf_data, byte_count);
1511 		} else {
1512 			if (tiled_image)
1513 				byte_count = TIFFReadEncodedTile(tif,
1514 						chunk_no, buf_data,
1515 						chunk_size);
1516 			else
1517 				byte_count = TIFFReadEncodedStrip(tif,
1518 						chunk_no, buf_data,
1519 						chunk_size);
1520 		}
1521 		if (byte_count < 0) {
1522 			TIFFError(filename, "Can't read %s %d.",
1523 				tiled_image ? "tile" : "strip", chunk_no);
1524 			if (ascii85)
1525 				Ascii85Put('\0', fd);
1526 		}
1527 		/*
1528 		 * for 16 bits, the two bytes must be most significant
1529 		 * byte first
1530 		 */
1531 		if (bitspersample == 16 && !TIFFIsBigEndian(tif)) {
1532 			PS_FlipBytes(buf_data, byte_count);
1533 		}
1534 		/*
1535 		 * For images with alpha, matte against a white background;
1536 		 * i.e. Cback * (1 - Aimage) where Cback = 1. We will fill the
1537 		 * lower part of the buffer with the modified values.
1538 		 *
1539 		 * XXX: needs better solution
1540 		 */
1541 		if (alpha) {
1542 			int adjust, i, j = 0;
1543 			int ncomps = samplesperpixel - extrasamples;
1544 			for (i = 0; i < byte_count; i+=samplesperpixel) {
1545 				adjust = 255 - buf_data[i + ncomps];
1546 				switch (ncomps) {
1547 					case 1:
1548 						buf_data[j++] = buf_data[i] + adjust;
1549 						break;
1550 					case 2:
1551 						buf_data[j++] = buf_data[i] + adjust;
1552 						buf_data[j++] = buf_data[i+1] + adjust;
1553 						break;
1554 					case 3:
1555 						buf_data[j++] = buf_data[i] + adjust;
1556 						buf_data[j++] = buf_data[i+1] + adjust;
1557 						buf_data[j++] = buf_data[i+2] + adjust;
1558 						break;
1559 				}
1560 			}
1561 			byte_count -= j;
1562 		}
1563 
1564 		if (ascii85) {
1565 #if defined( EXP_ASCII85ENCODER )
1566 			ascii85_l = Ascii85EncodeBlock(ascii85_p, 1, buf_data, byte_count );
1567 
1568 			if ( ascii85_l > 0 )
1569 				fwrite( ascii85_p, ascii85_l, 1, fd );
1570 #else
1571 			for (cp = buf_data; byte_count > 0; byte_count--)
1572 				Ascii85Put(*cp++, fd);
1573 #endif
1574 		}
1575 		else
1576 		{
1577 			for (cp = buf_data; byte_count > 0; byte_count--) {
1578 				putc(hex[((*cp)>>4)&0xf], fd);
1579 				putc(hex[(*cp)&0xf], fd);
1580 				cp++;
1581 
1582 				if (--breaklen <= 0) {
1583 					putc('\n', fd);
1584 					breaklen = MAXLINE;
1585 				}
1586 			}
1587 		}
1588 
1589 		if ( !ascii85 ) {
1590 			if ( level2 || level3 )
1591 				putc( '>', fd );
1592 			putc('\n', fd);
1593 		}
1594 #if !defined( EXP_ASCII85ENCODER )
1595 		else
1596 			Ascii85Flush(fd);
1597 #endif
1598 	}
1599 
1600 #if defined( EXP_ASCII85ENCODER )
1601 	if ( ascii85_p )
1602 	    _TIFFfree( ascii85_p );
1603 #endif
1604 
1605 	_TIFFfree(buf_data);
1606 #ifdef ENABLE_BROKEN_BEGINENDDATA
1607 	fputs("%%EndData\n", fd);
1608 #endif
1609 	return(TRUE);
1610 }
1611 
1612 void
1613 PSpage(FILE* fd, TIFF* tif, uint32 w, uint32 h)
1614 {
1615 	char	*	imageOp = "image";
1616 
1617 	if ( useImagemask && (bitspersample == 1) )
1618 		imageOp = "imagemask";
1619 
1620 	if ((level2 || level3) && PS_Lvl2page(fd, tif, w, h))
1621 		return;
1622 	ps_bytesperrow = tf_bytesperrow - (extrasamples * bitspersample / 8)*w;
1623 	switch (photometric) {
1624 	case PHOTOMETRIC_RGB:
1625 		if (planarconfiguration == PLANARCONFIG_CONTIG) {
1626 			fprintf(fd, "%s", RGBcolorimage);
1627 			PSColorContigPreamble(fd, w, h, 3);
1628 			PSDataColorContig(fd, tif, w, h, 3);
1629 		} else {
1630 			PSColorSeparatePreamble(fd, w, h, 3);
1631 			PSDataColorSeparate(fd, tif, w, h, 3);
1632 		}
1633 		break;
1634 	case PHOTOMETRIC_SEPARATED:
1635 		/* XXX should emit CMYKcolorimage */
1636 		if (planarconfiguration == PLANARCONFIG_CONTIG) {
1637 			PSColorContigPreamble(fd, w, h, 4);
1638 			PSDataColorContig(fd, tif, w, h, 4);
1639 		} else {
1640 			PSColorSeparatePreamble(fd, w, h, 4);
1641 			PSDataColorSeparate(fd, tif, w, h, 4);
1642 		}
1643 		break;
1644 	case PHOTOMETRIC_PALETTE:
1645 		fprintf(fd, "%s", RGBcolorimage);
1646 		PhotoshopBanner(fd, w, h, 1, 3, "false 3 colorimage");
1647 		fprintf(fd, "/scanLine %ld string def\n",
1648 		    (long) ps_bytesperrow * 3L);
1649 		fprintf(fd, "%lu %lu 8\n",
1650 		    (unsigned long) w, (unsigned long) h);
1651 		fprintf(fd, "[%lu 0 0 -%lu 0 %lu]\n",
1652 		    (unsigned long) w, (unsigned long) h, (unsigned long) h);
1653 		fprintf(fd, "{currentfile scanLine readhexstring pop} bind\n");
1654 		fprintf(fd, "false 3 colorimage\n");
1655 		PSDataPalette(fd, tif, w, h);
1656 		break;
1657 	case PHOTOMETRIC_MINISBLACK:
1658 	case PHOTOMETRIC_MINISWHITE:
1659 		PhotoshopBanner(fd, w, h, 1, 1, imageOp);
1660 		fprintf(fd, "/scanLine %ld string def\n",
1661 		    (long) ps_bytesperrow);
1662 		fprintf(fd, "%lu %lu %d\n",
1663 		    (unsigned long) w, (unsigned long) h, bitspersample);
1664 		fprintf(fd, "[%lu 0 0 -%lu 0 %lu]\n",
1665 		    (unsigned long) w, (unsigned long) h, (unsigned long) h);
1666 		fprintf(fd,
1667 		    "{currentfile scanLine readhexstring pop} bind\n");
1668 		fprintf(fd, "%s\n", imageOp);
1669 		PSDataBW(fd, tif, w, h);
1670 		break;
1671 	}
1672 	putc('\n', fd);
1673 }
1674 
1675 void
1676 PSColorContigPreamble(FILE* fd, uint32 w, uint32 h, int nc)
1677 {
1678 	ps_bytesperrow = nc * (tf_bytesperrow / samplesperpixel);
1679 	PhotoshopBanner(fd, w, h, 1, nc, "false %d colorimage");
1680 	fprintf(fd, "/line %ld string def\n", (long) ps_bytesperrow);
1681 	fprintf(fd, "%lu %lu %d\n",
1682 	    (unsigned long) w, (unsigned long) h, bitspersample);
1683 	fprintf(fd, "[%lu 0 0 -%lu 0 %lu]\n",
1684 	    (unsigned long) w, (unsigned long) h, (unsigned long) h);
1685 	fprintf(fd, "{currentfile line readhexstring pop} bind\n");
1686 	fprintf(fd, "false %d colorimage\n", nc);
1687 }
1688 
1689 void
1690 PSColorSeparatePreamble(FILE* fd, uint32 w, uint32 h, int nc)
1691 {
1692 	int i;
1693 
1694 	PhotoshopBanner(fd, w, h, ps_bytesperrow, nc, "true %d colorimage");
1695 	for (i = 0; i < nc; i++)
1696 		fprintf(fd, "/line%d %ld string def\n",
1697 		    i, (long) ps_bytesperrow);
1698 	fprintf(fd, "%lu %lu %d\n",
1699 	    (unsigned long) w, (unsigned long) h, bitspersample);
1700 	fprintf(fd, "[%lu 0 0 -%lu 0 %lu] \n",
1701 	    (unsigned long) w, (unsigned long) h, (unsigned long) h);
1702 	for (i = 0; i < nc; i++)
1703 		fprintf(fd, "{currentfile line%d readhexstring pop}bind\n", i);
1704 	fprintf(fd, "true %d colorimage\n", nc);
1705 }
1706 
1707 #define	DOBREAK(len, howmany, fd) \
1708 	if (((len) -= (howmany)) <= 0) {	\
1709 		putc('\n', fd);			\
1710 		(len) = MAXLINE-(howmany);	\
1711 	}
1712 #define	PUTHEX(c,fd)	putc(hex[((c)>>4)&0xf],fd); putc(hex[(c)&0xf],fd)
1713 
1714 void
1715 PSDataColorContig(FILE* fd, TIFF* tif, uint32 w, uint32 h, int nc)
1716 {
1717 	uint32 row;
1718 	int breaklen = MAXLINE, es = samplesperpixel - nc;
1719 	tsize_t cc;
1720 	unsigned char *tf_buf;
1721 	unsigned char *cp, c;
1722 
1723 	(void) w;
1724 	tf_buf = (unsigned char *) _TIFFmalloc(tf_bytesperrow);
1725 	if (tf_buf == NULL) {
1726 		TIFFError(filename, "No space for scanline buffer");
1727 		return;
1728 	}
1729 	for (row = 0; row < h; row++) {
1730 		if (TIFFReadScanline(tif, tf_buf, row, 0) < 0)
1731 			break;
1732 		cp = tf_buf;
1733 		/*
1734 		 * for 16 bits, the two bytes must be most significant
1735 		 * byte first
1736 		 */
1737 		if (bitspersample == 16 && !HOST_BIGENDIAN) {
1738 			PS_FlipBytes(cp, tf_bytesperrow);
1739 		}
1740 		if (alpha) {
1741 			int adjust;
1742 			cc = 0;
1743 			for (; cc < tf_bytesperrow; cc += samplesperpixel) {
1744 				DOBREAK(breaklen, nc, fd);
1745 				/*
1746 				 * For images with alpha, matte against
1747 				 * a white background; i.e.
1748 				 *    Cback * (1 - Aimage)
1749 				 * where Cback = 1.
1750 				 */
1751 				adjust = 255 - cp[nc];
1752 				switch (nc) {
1753 				case 4: c = *cp++ + adjust; PUTHEX(c,fd);
1754 				case 3: c = *cp++ + adjust; PUTHEX(c,fd);
1755 				case 2: c = *cp++ + adjust; PUTHEX(c,fd);
1756 				case 1: c = *cp++ + adjust; PUTHEX(c,fd);
1757 				}
1758 				cp += es;
1759 			}
1760 		} else {
1761 			cc = 0;
1762 			for (; cc < tf_bytesperrow; cc += samplesperpixel) {
1763 				DOBREAK(breaklen, nc, fd);
1764 				switch (nc) {
1765 				case 4: c = *cp++; PUTHEX(c,fd);
1766 				case 3: c = *cp++; PUTHEX(c,fd);
1767 				case 2: c = *cp++; PUTHEX(c,fd);
1768 				case 1: c = *cp++; PUTHEX(c,fd);
1769 				}
1770 				cp += es;
1771 			}
1772 		}
1773 	}
1774 	_TIFFfree((char *) tf_buf);
1775 }
1776 
1777 void
1778 PSDataColorSeparate(FILE* fd, TIFF* tif, uint32 w, uint32 h, int nc)
1779 {
1780 	uint32 row;
1781 	int breaklen = MAXLINE;
1782 	tsize_t cc;
1783 	tsample_t s, maxs;
1784 	unsigned char *tf_buf;
1785 	unsigned char *cp, c;
1786 
1787 	(void) w;
1788 	tf_buf = (unsigned char *) _TIFFmalloc(tf_bytesperrow);
1789 	if (tf_buf == NULL) {
1790 		TIFFError(filename, "No space for scanline buffer");
1791 		return;
1792 	}
1793 	maxs = (samplesperpixel > nc ? nc : samplesperpixel);
1794 	for (row = 0; row < h; row++) {
1795 		for (s = 0; s < maxs; s++) {
1796 			if (TIFFReadScanline(tif, tf_buf, row, s) < 0)
1797 				break;
1798 			for (cp = tf_buf, cc = 0; cc < tf_bytesperrow; cc++) {
1799 				DOBREAK(breaklen, 1, fd);
1800 				c = *cp++;
1801 				PUTHEX(c,fd);
1802 			}
1803 		}
1804 	}
1805 	_TIFFfree((char *) tf_buf);
1806 }
1807 
1808 #define	PUTRGBHEX(c,fd) \
1809 	PUTHEX(rmap[c],fd); PUTHEX(gmap[c],fd); PUTHEX(bmap[c],fd)
1810 
1811 void
1812 PSDataPalette(FILE* fd, TIFF* tif, uint32 w, uint32 h)
1813 {
1814 	uint16 *rmap, *gmap, *bmap;
1815 	uint32 row;
1816 	int breaklen = MAXLINE, nc;
1817 	tsize_t cc;
1818 	unsigned char *tf_buf;
1819 	unsigned char *cp, c;
1820 
1821 	(void) w;
1822 	if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) {
1823 		TIFFError(filename, "Palette image w/o \"Colormap\" tag");
1824 		return;
1825 	}
1826 	switch (bitspersample) {
1827 	case 8:	case 4: case 2: case 1:
1828 		break;
1829 	default:
1830 		TIFFError(filename, "Depth %d not supported", bitspersample);
1831 		return;
1832 	}
1833 	nc = 3 * (8 / bitspersample);
1834 	tf_buf = (unsigned char *) _TIFFmalloc(tf_bytesperrow);
1835 	if (tf_buf == NULL) {
1836 		TIFFError(filename, "No space for scanline buffer");
1837 		return;
1838 	}
1839 	if (checkcmap(tif, 1<<bitspersample, rmap, gmap, bmap) == 16) {
1840 		int i;
1841 #define	CVT(x)		((unsigned short) (((x) * 255) / ((1U<<16)-1)))
1842 		for (i = (1<<bitspersample)-1; i >= 0; i--) {
1843 			rmap[i] = CVT(rmap[i]);
1844 			gmap[i] = CVT(gmap[i]);
1845 			bmap[i] = CVT(bmap[i]);
1846 		}
1847 #undef CVT
1848 	}
1849 	for (row = 0; row < h; row++) {
1850 		if (TIFFReadScanline(tif, tf_buf, row, 0) < 0)
1851 			break;
1852 		for (cp = tf_buf, cc = 0; cc < tf_bytesperrow; cc++) {
1853 			DOBREAK(breaklen, nc, fd);
1854 			switch (bitspersample) {
1855 			case 8:
1856 				c = *cp++; PUTRGBHEX(c, fd);
1857 				break;
1858 			case 4:
1859 				c = *cp++; PUTRGBHEX(c&0xf, fd);
1860 				c >>= 4;   PUTRGBHEX(c, fd);
1861 				break;
1862 			case 2:
1863 				c = *cp++; PUTRGBHEX(c&0x3, fd);
1864 				c >>= 2;   PUTRGBHEX(c&0x3, fd);
1865 				c >>= 2;   PUTRGBHEX(c&0x3, fd);
1866 				c >>= 2;   PUTRGBHEX(c, fd);
1867 				break;
1868 			case 1:
1869 				c = *cp++; PUTRGBHEX(c&0x1, fd);
1870 				c >>= 1;   PUTRGBHEX(c&0x1, fd);
1871 				c >>= 1;   PUTRGBHEX(c&0x1, fd);
1872 				c >>= 1;   PUTRGBHEX(c&0x1, fd);
1873 				c >>= 1;   PUTRGBHEX(c&0x1, fd);
1874 				c >>= 1;   PUTRGBHEX(c&0x1, fd);
1875 				c >>= 1;   PUTRGBHEX(c&0x1, fd);
1876 				c >>= 1;   PUTRGBHEX(c, fd);
1877 				break;
1878 			}
1879 		}
1880 	}
1881 	_TIFFfree((char *) tf_buf);
1882 }
1883 
1884 void
1885 PSDataBW(FILE* fd, TIFF* tif, uint32 w, uint32 h)
1886 {
1887 	int breaklen = MAXLINE;
1888 	unsigned char* tf_buf;
1889 	unsigned char* cp;
1890 	tsize_t stripsize = TIFFStripSize(tif);
1891 	tstrip_t s;
1892 
1893 #if defined( EXP_ASCII85ENCODER )
1894 	tsize_t	ascii85_l;		/* Length, in bytes, of ascii85_p[] data */
1895 	uint8	*ascii85_p = 0;		/* Holds ASCII85 encoded data */
1896 #endif
1897 
1898 	(void) w; (void) h;
1899 	tf_buf = (unsigned char *) _TIFFmalloc(stripsize);
1900         memset(tf_buf, 0, stripsize);
1901 	if (tf_buf == NULL) {
1902 		TIFFError(filename, "No space for scanline buffer");
1903 		return;
1904 	}
1905 
1906 #if defined( EXP_ASCII85ENCODER )
1907 	if ( ascii85 ) {
1908 	    /*
1909 	     * Allocate a buffer to hold the ASCII85 encoded data.  Note
1910 	     * that it is allocated with sufficient room to hold the
1911 	     * encoded data (5*stripsize/4) plus the EOD marker (+8)
1912 	     * and formatting line breaks.  The line breaks are more
1913 	     * than taken care of by using 6*stripsize/4 rather than
1914 	     * 5*stripsize/4.
1915 	     */
1916 
1917 	    ascii85_p = _TIFFmalloc( (stripsize+(stripsize/2)) + 8 );
1918 
1919 	    if ( !ascii85_p ) {
1920 		_TIFFfree( tf_buf );
1921 
1922 		TIFFError( filename, "Cannot allocate ASCII85 encoding buffer." );
1923 		return;
1924 	    }
1925 	}
1926 #endif
1927 
1928 	if (ascii85)
1929 		Ascii85Init();
1930 
1931 	for (s = 0; s < TIFFNumberOfStrips(tif); s++) {
1932 		tmsize_t cc = TIFFReadEncodedStrip(tif, s, tf_buf, stripsize);
1933 		if (cc < 0) {
1934 			TIFFError(filename, "Can't read strip");
1935 			break;
1936 		}
1937 		cp = tf_buf;
1938 		if (photometric == PHOTOMETRIC_MINISWHITE) {
1939 			for (cp += cc; --cp >= tf_buf;)
1940 				*cp = ~*cp;
1941 			cp++;
1942 		}
1943 		/*
1944 		 * for 16 bits, the two bytes must be most significant
1945 		 * byte first
1946 		 */
1947 		if (bitspersample == 16 && !HOST_BIGENDIAN) {
1948 			PS_FlipBytes(cp, cc);
1949 		}
1950 		if (ascii85) {
1951 #if defined( EXP_ASCII85ENCODER )
1952 			if (alpha) {
1953 				int adjust, i;
1954 				for (i = 0; i < cc; i+=2) {
1955 					adjust = 255 - cp[i + 1];
1956 				    cp[i / 2] = cp[i] + adjust;
1957 				}
1958 				cc /= 2;
1959 			}
1960 
1961 			ascii85_l = Ascii85EncodeBlock( ascii85_p, 1, cp, cc );
1962 
1963 			if ( ascii85_l > 0 )
1964 			    fwrite( ascii85_p, ascii85_l, 1, fd );
1965 #else
1966 			while (cc-- > 0)
1967 				Ascii85Put(*cp++, fd);
1968 #endif /* EXP_ASCII85_ENCODER */
1969 		} else {
1970 			unsigned char c;
1971 
1972 			if (alpha) {
1973 				int adjust;
1974 				while (cc-- > 0) {
1975 					DOBREAK(breaklen, 1, fd);
1976 					/*
1977 					 * For images with alpha, matte against
1978 					 * a white background; i.e.
1979 					 *    Cback * (1 - Aimage)
1980 					 * where Cback = 1.
1981 					 */
1982 					adjust = 255 - cp[1];
1983 					c = *cp++ + adjust; PUTHEX(c,fd);
1984 					cp++, cc--;
1985 				}
1986 			} else {
1987 				while (cc-- > 0) {
1988 					c = *cp++;
1989 					DOBREAK(breaklen, 1, fd);
1990 					PUTHEX(c, fd);
1991 				}
1992 			}
1993 		}
1994 	}
1995 
1996 	if ( !ascii85 )
1997 	{
1998 	    if ( level2 || level3)
1999 		fputs(">\n", fd);
2000 	}
2001 #if !defined( EXP_ASCII85ENCODER )
2002 	else
2003 	    Ascii85Flush(fd);
2004 #else
2005 	if ( ascii85_p )
2006 	    _TIFFfree( ascii85_p );
2007 #endif
2008 
2009 	_TIFFfree(tf_buf);
2010 }
2011 
2012 void
2013 PSRawDataBW(FILE* fd, TIFF* tif, uint32 w, uint32 h)
2014 {
2015 	uint64 *bc;
2016 	uint32 bufsize;
2017 	int breaklen = MAXLINE;
2018 	tmsize_t cc;
2019 	uint16 fillorder;
2020 	unsigned char *tf_buf;
2021 	unsigned char *cp, c;
2022 	tstrip_t s;
2023 
2024 #if defined( EXP_ASCII85ENCODER )
2025 	tsize_t 		ascii85_l;		/* Length, in bytes, of ascii85_p[] data */
2026 	uint8		*	ascii85_p = 0;		/* Holds ASCII85 encoded data */
2027 #endif
2028 
2029 	(void) w; (void) h;
2030 	TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &fillorder);
2031 	TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &bc);
2032 
2033 	/*
2034 	 * Find largest strip:
2035 	 */
2036 
2037 	bufsize = (uint32) bc[0];
2038 
2039 	for ( s = 0; ++s < (tstrip_t)tf_numberstrips; ) {
2040 		if ( bc[s] > bufsize )
2041 			bufsize = (uint32) bc[s];
2042 	}
2043 
2044 	tf_buf = (unsigned char*) _TIFFmalloc(bufsize);
2045 	if (tf_buf == NULL) {
2046 		TIFFError(filename, "No space for strip buffer");
2047 		return;
2048 	}
2049 
2050 #if defined( EXP_ASCII85ENCODER )
2051 	if ( ascii85 ) {
2052 	    /*
2053 	     * Allocate a buffer to hold the ASCII85 encoded data.  Note
2054 	     * that it is allocated with sufficient room to hold the
2055 	     * encoded data (5*bufsize/4) plus the EOD marker (+8)
2056 	     * and formatting line breaks.  The line breaks are more
2057 	     * than taken care of by using 6*bufsize/4 rather than
2058 	     * 5*bufsize/4.
2059 	     */
2060 
2061 	    ascii85_p = _TIFFmalloc( (bufsize+(bufsize/2)) + 8 );
2062 
2063 	    if ( !ascii85_p ) {
2064 		_TIFFfree( tf_buf );
2065 
2066 		TIFFError( filename, "Cannot allocate ASCII85 encoding buffer." );
2067 		return;
2068 	    }
2069 	}
2070 #endif
2071 
2072 	for (s = 0; s < (tstrip_t) tf_numberstrips; s++) {
2073 		cc = TIFFReadRawStrip(tif, s, tf_buf, (tmsize_t) bc[s]);
2074 		if (cc < 0) {
2075 			TIFFError(filename, "Can't read strip");
2076 			break;
2077 		}
2078 		if (fillorder == FILLORDER_LSB2MSB)
2079 			TIFFReverseBits(tf_buf, cc);
2080 		if (!ascii85) {
2081 			for (cp = tf_buf; cc > 0; cc--) {
2082 				DOBREAK(breaklen, 1, fd);
2083 				c = *cp++;
2084 				PUTHEX(c, fd);
2085 			}
2086 			fputs(">\n", fd);
2087 			breaklen = MAXLINE;
2088 		} else {
2089 			Ascii85Init();
2090 #if defined( EXP_ASCII85ENCODER )
2091 			ascii85_l = Ascii85EncodeBlock( ascii85_p, 1, tf_buf, cc );
2092 
2093 			if ( ascii85_l > 0 )
2094 				fwrite( ascii85_p, ascii85_l, 1, fd );
2095 #else
2096 			for (cp = tf_buf; cc > 0; cc--)
2097 				Ascii85Put(*cp++, fd);
2098 			Ascii85Flush(fd);
2099 #endif	/* EXP_ASCII85ENCODER */
2100 		}
2101 	}
2102 	_TIFFfree((char *) tf_buf);
2103 
2104 #if defined( EXP_ASCII85ENCODER )
2105 	if ( ascii85_p )
2106 		_TIFFfree( ascii85_p );
2107 #endif
2108 }
2109 
2110 void
2111 Ascii85Init(void)
2112 {
2113 	ascii85breaklen = 2*MAXLINE;
2114 	ascii85count = 0;
2115 }
2116 
2117 static char*
2118 Ascii85Encode(unsigned char* raw)
2119 {
2120 	static char encoded[6];
2121 	uint32 word;
2122 
2123 	word = (((raw[0]<<8)+raw[1])<<16) + (raw[2]<<8) + raw[3];
2124 	if (word != 0L) {
2125 		uint32 q;
2126 		uint16 w1;
2127 
2128 		q = word / (85L*85*85*85);	/* actually only a byte */
2129 		encoded[0] = (char) (q + '!');
2130 
2131 		word -= q * (85L*85*85*85); q = word / (85L*85*85);
2132 		encoded[1] = (char) (q + '!');
2133 
2134 		word -= q * (85L*85*85); q = word / (85*85);
2135 		encoded[2] = (char) (q + '!');
2136 
2137 		w1 = (uint16) (word - q*(85L*85));
2138 		encoded[3] = (char) ((w1 / 85) + '!');
2139 		encoded[4] = (char) ((w1 % 85) + '!');
2140 		encoded[5] = '\0';
2141 	} else
2142 		encoded[0] = 'z', encoded[1] = '\0';
2143 	return (encoded);
2144 }
2145 
2146 void
2147 Ascii85Put(unsigned char code, FILE* fd)
2148 {
2149 	ascii85buf[ascii85count++] = code;
2150 	if (ascii85count >= 4) {
2151 		unsigned char* p;
2152 		int n;
2153 
2154 		for (n = ascii85count, p = ascii85buf; n >= 4; n -= 4, p += 4) {
2155 			char* cp;
2156 			for (cp = Ascii85Encode(p); *cp; cp++) {
2157 				putc(*cp, fd);
2158 				if (--ascii85breaklen == 0) {
2159 					putc('\n', fd);
2160 					ascii85breaklen = 2*MAXLINE;
2161 				}
2162 			}
2163 		}
2164 		_TIFFmemcpy(ascii85buf, p, n);
2165 		ascii85count = n;
2166 	}
2167 }
2168 
2169 void
2170 Ascii85Flush(FILE* fd)
2171 {
2172 	if (ascii85count > 0) {
2173 		char* res;
2174 		_TIFFmemset(&ascii85buf[ascii85count], 0, 3);
2175 		res = Ascii85Encode(ascii85buf);
2176 		fwrite(res[0] == 'z' ? "!!!!" : res, ascii85count + 1, 1, fd);
2177 	}
2178 	fputs("~>\n", fd);
2179 }
2180 #if	defined( EXP_ASCII85ENCODER)
2181 
2182 #define A85BREAKCNTR    ascii85breaklen
2183 #define A85BREAKLEN     (2*MAXLINE)
2184 
2185 /*****************************************************************************
2186 *
2187 * Name:         Ascii85EncodeBlock( ascii85_p, f_eod, raw_p, raw_l )
2188 *
2189 * Description:  This routine will encode the raw data in the buffer described
2190 *               by raw_p and raw_l into ASCII85 format and store the encoding
2191 *               in the buffer given by ascii85_p.
2192 *
2193 * Parameters:   ascii85_p   -   A buffer supplied by the caller which will
2194 *                               contain the encoded ASCII85 data.
2195 *               f_eod       -   Flag: Nz means to end the encoded buffer with
2196 *                               an End-Of-Data marker.
2197 *               raw_p       -   Pointer to the buffer of data to be encoded
2198 *               raw_l       -   Number of bytes in raw_p[] to be encoded
2199 *
2200 * Returns:      (int)   <   0   Error, see errno
2201 *                       >=  0   Number of bytes written to ascii85_p[].
2202 *
2203 * Notes:        An external variable given by A85BREAKCNTR is used to
2204 *               determine when to insert newline characters into the
2205 *               encoded data.  As each byte is placed into ascii85_p this
2206 *               external is decremented.  If the variable is decrement to
2207 *               or past zero then a newline is inserted into ascii85_p
2208 *               and the A85BREAKCNTR is then reset to A85BREAKLEN.
2209 *                   Note:  for efficiency reasons the A85BREAKCNTR variable
2210 *                          is not actually checked on *every* character
2211 *                          placed into ascii85_p but often only for every
2212 *                          5 characters.
2213 *
2214 *               THE CALLER IS RESPONSIBLE FOR ENSURING THAT ASCII85_P[] IS
2215 *               SUFFICIENTLY LARGE TO THE ENCODED DATA!
2216 *                   You will need at least 5 * (raw_l/4) bytes plus space for
2217 *                   newline characters and space for an EOD marker (if
2218 *                   requested).  A safe calculation is to use 6*(raw_l/4) + 8
2219 *                   to size ascii85_p.
2220 *
2221 *****************************************************************************/
2222 
2223 tsize_t Ascii85EncodeBlock( uint8 * ascii85_p, unsigned f_eod, const uint8 * raw_p, tsize_t raw_l )
2224 
2225 {
2226     char                        ascii85[5];     /* Encoded 5 tuple */
2227     tsize_t                     ascii85_l;      /* Number of bytes written to ascii85_p[] */
2228     int                         rc;             /* Return code */
2229     uint32                      val32;          /* Unencoded 4 tuple */
2230 
2231     ascii85_l = 0;                              /* Nothing written yet */
2232 
2233     if ( raw_p )
2234     {
2235         --raw_p;                                /* Prepare for pre-increment fetches */
2236 
2237         for ( ; raw_l > 3; raw_l -= 4 )
2238         {
2239             val32  = *(++raw_p) << 24;
2240             val32 += *(++raw_p) << 16;
2241             val32 += *(++raw_p) <<  8;
2242             val32 += *(++raw_p);
2243 
2244             if ( val32 == 0 )                   /* Special case */
2245             {
2246                 ascii85_p[ascii85_l] = 'z';
2247                 rc = 1;
2248             }
2249 
2250             else
2251             {
2252                 ascii85[4] = (char) ((val32 % 85) + 33);
2253                 val32 /= 85;
2254 
2255                 ascii85[3] = (char) ((val32 % 85) + 33);
2256                 val32 /= 85;
2257 
2258                 ascii85[2] = (char) ((val32 % 85) + 33);
2259                 val32 /= 85;
2260 
2261                 ascii85[1] = (char) ((val32 % 85) + 33);
2262                 ascii85[0] = (char) ((val32 / 85) + 33);
2263 
2264                 _TIFFmemcpy( &ascii85_p[ascii85_l], ascii85, sizeof(ascii85) );
2265                 rc = sizeof(ascii85);
2266             }
2267 
2268             ascii85_l += rc;
2269 
2270             if ( (A85BREAKCNTR -= rc) <= 0 )
2271             {
2272                 ascii85_p[ascii85_l] = '\n';
2273                 ++ascii85_l;
2274                 A85BREAKCNTR = A85BREAKLEN;
2275             }
2276         }
2277 
2278         /*
2279          * Output any straggler bytes:
2280          */
2281 
2282         if ( raw_l > 0 )
2283         {
2284             tsize_t         len;                /* Output this many bytes */
2285 
2286             len = raw_l + 1;
2287             val32 = *++raw_p << 24;             /* Prime the pump */
2288 
2289             if ( --raw_l > 0 )  val32 += *(++raw_p) << 16;
2290             if ( --raw_l > 0 )  val32 += *(++raw_p) <<  8;
2291 
2292             val32 /= 85;
2293 
2294             ascii85[3] = (char) ((val32 % 85) + 33);
2295             val32 /= 85;
2296 
2297             ascii85[2] = (char) ((val32 % 85) + 33);
2298             val32 /= 85;
2299 
2300             ascii85[1] = (char) ((val32 % 85) + 33);
2301             ascii85[0] = (char) ((val32 / 85) + 33);
2302 
2303             _TIFFmemcpy( &ascii85_p[ascii85_l], ascii85, len );
2304             ascii85_l += len;
2305         }
2306     }
2307 
2308     /*
2309      * If requested add an ASCII85 End Of Data marker:
2310      */
2311 
2312     if ( f_eod )
2313     {
2314         ascii85_p[ascii85_l++] = '~';
2315         ascii85_p[ascii85_l++] = '>';
2316         ascii85_p[ascii85_l++] = '\n';
2317     }
2318 
2319     return ( ascii85_l );
2320 
2321 }   /* Ascii85EncodeBlock() */
2322 
2323 #endif	/* EXP_ASCII85ENCODER */
2324 
2325 
2326 char* stuff[] = {
2327 "usage: tiff2ps [options] input.tif ...",
2328 "where options are:",
2329 " -1            generate PostScript Level 1 (default)",
2330 " -2            generate PostScript Level 2",
2331 " -3            generate PostScript Level 3",
2332 " -8            disable use of ASCII85 encoding with PostScript Level 2/3",
2333 " -a            convert all directories in file (default is first)",
2334 " -b #          set the bottom margin to # inches",
2335 " -c            center image (-b and -l still add to this)",
2336 " -d #          convert directory number #",
2337 " -D            enable duplex printing (two pages per sheet of paper)",
2338 " -e            generate Encapsulated PostScript (EPS) (implies -z)",
2339 " -h #          assume printed page height is # inches (default 11)",
2340 " -w #          assume printed page width is # inches (default 8.5)",
2341 " -H #          split image if height is more than # inches",
2342 " -W #          split image if width is more than # inches",
2343 " -L #          overLap split images by # inches",
2344 " -i #          enable/disable (Nz/0) pixel interpolation (default: enable)",
2345 " -l #          set the left margin to # inches",
2346 " -m            use \"imagemask\" operator instead of \"image\"",
2347 " -o #          convert directory at file offset #",
2348 " -O file       write PostScript to file instead of standard output",
2349 " -p            generate regular PostScript",
2350 " -r # or auto  rotate by 90, 180, 270 degrees or auto",
2351 " -s            generate PostScript for a single image",
2352 " -T            print pages for top edge binding",
2353 " -x            override resolution units as centimeters",
2354 " -y            override resolution units as inches",
2355 " -z            enable printing in the deadzone (only for PostScript Level 2/3)",
2356 NULL
2357 };
2358 
2359 static void
2360 usage(int code)
2361 {
2362 	char buf[BUFSIZ];
2363 	int i;
2364 
2365 	setbuf(stderr, buf);
2366         fprintf(stderr, "%s\n\n", TIFFGetVersion());
2367 	for (i = 0; stuff[i] != NULL; i++)
2368 		fprintf(stderr, "%s\n", stuff[i]);
2369 	exit(code);
2370 }
2371 
2372 /* vim: set ts=8 sts=8 sw=8 noet: */
2373 /*
2374  * Local Variables:
2375  * mode: c
2376  * c-basic-offset: 8
2377  * fill-column: 78
2378  * End:
2379  */
2380