roentgen b75cab
/* $Id: tiff2ps.c,v 1.49 2011-05-31 17:10:18 bfriesen Exp $ */
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * Copyright (c) 1988-1997 Sam Leffler
roentgen b75cab
 * Copyright (c) 1991-1997 Silicon Graphics, Inc.
roentgen b75cab
 *
roentgen b75cab
 * Permission to use, copy, modify, distribute, and sell this software and 
roentgen b75cab
 * its documentation for any purpose is hereby granted without fee, provided
roentgen b75cab
 * that (i) the above copyright notices and this permission notice appear in
roentgen b75cab
 * all copies of the software and related documentation, and (ii) the names of
roentgen b75cab
 * Sam Leffler and Silicon Graphics may not be used in any advertising or
roentgen b75cab
 * publicity relating to the software without the specific, prior written
roentgen b75cab
 * permission of Sam Leffler and Silicon Graphics.
roentgen b75cab
 * 
roentgen b75cab
 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
roentgen b75cab
 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
roentgen b75cab
 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
roentgen b75cab
 * 
roentgen b75cab
 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
roentgen b75cab
 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
roentgen b75cab
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
roentgen b75cab
 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
roentgen b75cab
 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
roentgen b75cab
 * OF THIS SOFTWARE.
roentgen b75cab
 */
roentgen b75cab
roentgen b75cab
#include "tif_config.h"
roentgen b75cab
roentgen b75cab
#include <stdio.h></stdio.h>
roentgen b75cab
#include <stdlib.h>			/* for atof */</stdlib.h>
roentgen b75cab
#include <math.h></math.h>
roentgen b75cab
#include <time.h></time.h>
roentgen b75cab
#include <string.h></string.h>
roentgen b75cab
roentgen b75cab
#ifdef HAVE_UNISTD_H
roentgen b75cab
# include <unistd.h></unistd.h>
roentgen b75cab
#endif
roentgen b75cab
roentgen b75cab
#ifdef NEED_LIBPORT
roentgen b75cab
# include "libport.h"
roentgen b75cab
#endif
roentgen b75cab
roentgen b75cab
#include "tiffio.h"
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * Revision history
roentgen b75cab
 *
roentgen b75cab
 * 2010-Sep-17
roentgen b75cab
 *    Richard Nolde: Reinstate code from Feb 2009 that never got
roentgen b75cab
 *    accepted into CVS with major modifications to handle -H and -W
roentgen b75cab
 *    options. Replaced original PlaceImage function with several
roentgen b75cab
 *    new functions that make support for multiple output pages
roentgen b75cab
 *    from a single image easier to understand. Added additional
roentgen b75cab
 *    warning messages for incompatible command line options.
roentgen b75cab
 *    Add new command line options to specify PageOrientation
roentgen b75cab
 *    Document Structuring Comment for landscape or portrait
roentgen b75cab
 *    and code to determine the values from ouput width and height
roentgen b75cab
 *    if not specified on the command line.
roentgen b75cab
 *    Add new command line option to specify document creator
roentgen b75cab
 *    as an alterntive to the string "tiff2ps" following model
roentgen b75cab
 *    of patch submitted by Thomas Jarosch for specifiying a
roentgen b75cab
 *    document title which is also supported now.
roentgen b75cab
 *
roentgen b75cab
 * 2009-Feb-11
roentgen b75cab
 *    Richard Nolde: Added support for rotations of 90, 180, 270
roentgen b75cab
 *    and auto using -r <90|180|270|auto>.  Auto picks the best
roentgen b75cab
 *    fit for the image on the specified paper size (eg portrait
roentgen b75cab
 *    or landscape) if -h or -w is specified. Rotation is in
roentgen b75cab
 *    degrees counterclockwise since that is how Postscript does
roentgen b75cab
 *    it. The auto opption rotates the image 90 degrees ccw to
roentgen b75cab
 *    produce landscape if that is a better fit than portait.
roentgen b75cab
 *
roentgen b75cab
 *    Cleaned up code in TIFF2PS and broke into smaller functions
roentgen b75cab
 *    to simplify rotations.
roentgen b75cab
 *
roentgen b75cab
 *    Identified incompatible options and returned errors, eg
roentgen b75cab
 *    -i for imagemask operator is only available for Level2 or
roentgen b75cab
 *    Level3 Postscript in the current implmentation since there
roentgen b75cab
 *    is a difference in the way the operands are called for Level1
roentgen b75cab
 *    and there is no function to provide the Level1 version.
roentgen b75cab
 *    -H was not handled properly if -h and/or -w were specified.
roentgen b75cab
 *    It should only clip the masked images if the scaled image
roentgen b75cab
 *    exceeds the maxPageHeight specified with -H.
roentgen b75cab
 *  
roentgen b75cab
 *    New design allows for all of the following combinations:
roentgen b75cab
 *    Conversion of TIFF to Postscript with optional rotations
roentgen b75cab
 *    of 90, 180, 270, or auto degrees counterclockwise
roentgen b75cab
 *    Conversion of TIFF to Postscript with entire image scaled
roentgen b75cab
 *    to maximum of values spedified with -h or -w while
roentgen b75cab
 *    maintaining aspect ratio. Same rotations apply.
roentgen b75cab
 *    Conversion of TIFF to Postscript with clipping of output
roentgen b75cab
 *    viewport to height specified with -H, producing multiple
roentgen b75cab
 *    pages at this height and original width as needed.
roentgen b75cab
 *    Same rotations apply.
roentgen b75cab
 *    Conversion of TIFF to Postscript with image scaled to 
roentgen b75cab
 *    maximum specified by -h and -w and the resulting scaled
roentgen b75cab
 *    image is presented in an output viewport clipped by -H height.
roentgen b75cab
 *    The same rotations apply.
roentgen b75cab
 *
roentgen b75cab
 *    Added maxPageWidth option using -W flag. MaxPageHeight and
roentgen b75cab
 *    MaxPageWidth are mutually exclusive since the aspect ratio
roentgen b75cab
 *    cannot be maintained if you set both.
roentgen b75cab
 *    Rewrote PlaceImage to allow maxPageHeight and maxPageWidth
roentgen b75cab
 *    options to work with values smaller or larger than the
roentgen b75cab
 *    physical paper size and still preserve the aspect ratio.
roentgen b75cab
 *    This is accomplished by creating multiple pages across
roentgen b75cab
 *    as well as down if need be.
roentgen b75cab
 *
roentgen b75cab
 * 2001-Mar-21
roentgen b75cab
 *    I (Bruce A. Mallett) added this revision history comment ;)
roentgen b75cab
 *
roentgen b75cab
 *    Fixed PS_Lvl2page() code which outputs non-ASCII85 raw
roentgen b75cab
 *    data.  Moved test for when to output a line break to
roentgen b75cab
 *    *after* the output of a character.  This just serves
roentgen b75cab
 *    to fix an eye-nuisance where the first line of raw
roentgen b75cab
 *    data was one character shorter than subsequent lines.
roentgen b75cab
 *
roentgen b75cab
 *    Added an experimental ASCII85 encoder which can be used
roentgen b75cab
 *    only when there is a single buffer of bytes to be encoded.
roentgen b75cab
 *    This version is much faster at encoding a straight-line
roentgen b75cab
 *    buffer of data because it can avoid a lot of the loop
roentgen b75cab
 *    overhead of the byte-by-byte version.  To use this version
roentgen b75cab
 *    you need to define EXP_ASCII85ENCODER (experimental ...).
roentgen b75cab
 *
roentgen b75cab
 *    Added bug fix given by Michael Schmidt to PS_Lvl2page()
roentgen b75cab
 *    in which an end-of-data marker ('>') was not being output
roentgen b75cab
 *    when producing non-ASCII85 encoded PostScript Level 2
roentgen b75cab
 *    data.
roentgen b75cab
 *
roentgen b75cab
 *    Fixed PS_Lvl2colorspace() so that it no longer assumes that
roentgen b75cab
 *    a TIFF having more than 2 planes is a CMYK.  This routine
roentgen b75cab
 *    no longer looks at the samples per pixel but instead looks
roentgen b75cab
 *    at the "photometric" value.  This change allows support of
roentgen b75cab
 *    CMYK TIFFs.
roentgen b75cab
 *
roentgen b75cab
 *    Modified the PostScript L2 imaging loop so as to test if
roentgen b75cab
 *    the input stream is still open before attempting to do a
roentgen b75cab
 *    flushfile on it.  This was done because some RIPs close
roentgen b75cab
 *    the stream after doing the image operation.
roentgen b75cab
 *
roentgen b75cab
 *    Got rid of the realloc() being done inside a loop in the
roentgen b75cab
 *    PSRawDataBW() routine.  The code now walks through the
roentgen b75cab
 *    byte-size array outside the loop to determine the largest
roentgen b75cab
 *    size memory block that will be needed.
roentgen b75cab
 *
roentgen b75cab
 *    Added "-m" switch to ask tiff2ps to, where possible, use the
roentgen b75cab
 *    "imagemask" operator instead of the "image" operator.
roentgen b75cab
 *
roentgen b75cab
 *    Added the "-i #" switch to allow interpolation to be disabled.
roentgen b75cab
 *
roentgen b75cab
 *    Unrolled a loop or two to improve performance.
roentgen b75cab
 */
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * Define EXP_ASCII85ENCODER if you want to use an experimental
roentgen b75cab
 * version of the ASCII85 encoding routine.  The advantage of
roentgen b75cab
 * using this routine is that tiff2ps will convert to ASCII85
roentgen b75cab
 * encoding at between 3 and 4 times the speed as compared to
roentgen b75cab
 * using the old (non-experimental) encoder.  The disadvantage
roentgen b75cab
 * is that you will be using a new (and unproven) encoding
roentgen b75cab
 * routine.  So user beware, you have been warned!
roentgen b75cab
 */
roentgen b75cab
roentgen b75cab
#define	EXP_ASCII85ENCODER
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * NB: this code assumes uint32 works with printf's %l[ud].
roentgen b75cab
 */
roentgen b75cab
#ifndef TRUE
roentgen b75cab
#define	TRUE	1
roentgen b75cab
#define	FALSE	0
roentgen b75cab
#endif
roentgen b75cab
roentgen b75cab
int	ascii85 = FALSE;		/* use ASCII85 encoding */
roentgen b75cab
int	interpolate = TRUE;		/* interpolate level2 image */
roentgen b75cab
int	level2 = FALSE;			/* generate PostScript level 2 */
roentgen b75cab
int	level3 = FALSE;			/* generate PostScript level 3 */
roentgen b75cab
int	printAll = FALSE;		/* print all images in file */
roentgen b75cab
int	generateEPSF = TRUE;		/* generate Encapsulated PostScript */
roentgen b75cab
int	PSduplex = FALSE;		/* enable duplex printing */
roentgen b75cab
int	PStumble = FALSE;		/* enable top edge binding */
roentgen b75cab
int	PSavoiddeadzone = TRUE;		/* enable avoiding printer deadzone */
roentgen b75cab
double	maxPageHeight = 0;		/* maximum height to select from image and print per page */
roentgen b75cab
double	maxPageWidth  = 0;		/* maximum width  to select from image and print per page */
roentgen b75cab
double	splitOverlap = 0;		/* amount for split pages to overlag */
roentgen b75cab
int	rotation = 0;                   /* optional value for rotation angle */
roentgen b75cab
int     auto_rotate = 0;                /* rotate image for best fit on the page */
roentgen b75cab
char	*filename = NULL;		/* input filename */
roentgen b75cab
char    *title = NULL;                  /* optional document title string */
roentgen b75cab
char    *creator = NULL;                /* optional document creator string */
roentgen b75cab
char    pageOrientation[12];            /* set optional PageOrientation DSC to Landscape or Portrait */
roentgen b75cab
int	useImagemask = FALSE;		/* Use imagemask instead of image operator */
roentgen b75cab
uint16	res_unit = 0;			/* Resolution units: 2 - inches, 3 - cm */
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * ASCII85 Encoding Support.
roentgen b75cab
 */
roentgen b75cab
unsigned char ascii85buf[10];
roentgen b75cab
int	ascii85count;
roentgen b75cab
int	ascii85breaklen;
roentgen b75cab
roentgen b75cab
int	TIFF2PS(FILE*, TIFF*, double, double, double, double, int);
roentgen b75cab
void	PSpage(FILE*, TIFF*, uint32, uint32);
roentgen b75cab
void	PSColorContigPreamble(FILE*, uint32, uint32, int);
roentgen b75cab
void	PSColorSeparatePreamble(FILE*, uint32, uint32, int);
roentgen b75cab
void	PSDataColorContig(FILE*, TIFF*, uint32, uint32, int);
roentgen b75cab
void	PSDataColorSeparate(FILE*, TIFF*, uint32, uint32, int);
roentgen b75cab
void	PSDataPalette(FILE*, TIFF*, uint32, uint32);
roentgen b75cab
void	PSDataBW(FILE*, TIFF*, uint32, uint32);
roentgen b75cab
void	PSRawDataBW(FILE*, TIFF*, uint32, uint32);
roentgen b75cab
void	Ascii85Init(void);
roentgen b75cab
void	Ascii85Put(unsigned char code, FILE* fd);
roentgen b75cab
void	Ascii85Flush(FILE* fd);
roentgen b75cab
void    PSHead(FILE*, double, double, double, double);
roentgen b75cab
void	PSTail(FILE*, int);
roentgen b75cab
int     psStart(FILE *, int, int, int *, double *, double, double, double,
roentgen b75cab
                double, double, double, double, double, double, double);
roentgen b75cab
int     psPageSize(FILE *, int, double, double, double, double, double, double);
roentgen b75cab
int     psRotateImage(FILE *, int, double, double, double, double);
roentgen b75cab
int     psMaskImage(FILE *, TIFF *, int, int, int *, double, double,
roentgen b75cab
		    double, double, double, double, double, double, double);
roentgen b75cab
int     psScaleImage(FILE *, double, int, int, double, double, double, double,
roentgen b75cab
                     double, double);
roentgen b75cab
int     get_viewport (double, double, double, double, double *, double *, int);
roentgen b75cab
int     exportMaskedImage(FILE *, double, double, double, double, int, int,
roentgen b75cab
			  double, double, double, int, int);
roentgen b75cab
roentgen b75cab
#if	defined( EXP_ASCII85ENCODER)
roentgen b75cab
tsize_t Ascii85EncodeBlock( uint8 * ascii85_p, unsigned f_eod, const uint8 * raw_p, tsize_t raw_l );
roentgen b75cab
#endif
roentgen b75cab
roentgen b75cab
static	void usage(int);
roentgen b75cab
roentgen b75cab
int
roentgen b75cab
main(int argc, char* argv[])
roentgen b75cab
{
roentgen b75cab
	int dirnum = -1, c, np = 0;
roentgen b75cab
	int centered = 0;
roentgen b75cab
	double bottommargin = 0;
roentgen b75cab
	double leftmargin = 0;
roentgen b75cab
	double pageWidth = 0;
roentgen b75cab
	double pageHeight = 0;
roentgen b75cab
	uint32 diroff = 0;
roentgen b75cab
	extern char *optarg;
roentgen b75cab
	extern int optind;
roentgen b75cab
	FILE* output = stdout;
roentgen b75cab
roentgen b75cab
        pageOrientation[0] = '\0';
roentgen b75cab
roentgen b75cab
	while ((c = getopt(argc, argv, "b:d:h:H:W:L:i:w:l:o:O:P:C:r:t:acemxyzps1238DT")) != -1)
roentgen b75cab
		switch (c) {
roentgen b75cab
		case 'b':
roentgen b75cab
			bottommargin = atof(optarg);
roentgen b75cab
			break;
roentgen b75cab
		case 'c':
roentgen b75cab
			centered = 1;
roentgen b75cab
			break;
roentgen b75cab
                case 'C':
roentgen b75cab
                        creator = optarg;
roentgen b75cab
                        break;
roentgen b75cab
		case 'd': /* without -a, this only processes one image at this IFD */
roentgen b75cab
			dirnum = atoi(optarg);
roentgen b75cab
			break;
roentgen b75cab
		case 'D':
roentgen b75cab
			PSduplex = TRUE;
roentgen b75cab
			break;
roentgen b75cab
		case 'i':
roentgen b75cab
			interpolate = atoi(optarg) ? TRUE:FALSE;
roentgen b75cab
			break;
roentgen b75cab
		case 'T':
roentgen b75cab
			PStumble = TRUE;
roentgen b75cab
			break;
roentgen b75cab
		case 'e':
roentgen b75cab
                        PSavoiddeadzone = FALSE;
roentgen b75cab
			generateEPSF = TRUE;
roentgen b75cab
			break;
roentgen b75cab
		case 'h':
roentgen b75cab
			pageHeight = atof(optarg);
roentgen b75cab
			break;
roentgen b75cab
		case 'H':
roentgen b75cab
			maxPageHeight = atof(optarg);
roentgen b75cab
			break;
roentgen b75cab
		case 'W':
roentgen b75cab
			maxPageWidth = atof(optarg);
roentgen b75cab
			break;
roentgen b75cab
		case 'L':
roentgen b75cab
			splitOverlap = atof(optarg);
roentgen b75cab
			break;
roentgen b75cab
		case 'm':
roentgen b75cab
			useImagemask = TRUE;
roentgen b75cab
			break;
roentgen b75cab
		case 'o':
roentgen b75cab
		        switch (optarg[0])
roentgen b75cab
                          {
roentgen b75cab
                          case '0':
roentgen b75cab
                          case '1':
roentgen b75cab
                          case '2':
roentgen b75cab
                          case '3':
roentgen b75cab
                          case '4':
roentgen b75cab
                          case '5':
roentgen b75cab
                          case '6':
roentgen b75cab
                          case '7':
roentgen b75cab
                          case '8':
roentgen b75cab
                          case '9': diroff = (uint32) strtoul(optarg, NULL, 0);
roentgen b75cab
			          break;
roentgen b75cab
                          default: TIFFError ("-o", "Offset must be a numeric value.");
roentgen b75cab
			    exit (1);
roentgen b75cab
			  }
roentgen b75cab
			break;
roentgen b75cab
		case 'O':		/* XXX too bad -o is already taken */
roentgen b75cab
			output = fopen(optarg, "w");
roentgen b75cab
			if (output == NULL) {
roentgen b75cab
				fprintf(stderr,
roentgen b75cab
				    "%s: %s: Cannot open output file.\n",
roentgen b75cab
				    argv[0], optarg);
roentgen b75cab
				exit(-2);
roentgen b75cab
			}
roentgen b75cab
			break;
roentgen b75cab
		case 'P':
roentgen b75cab
                        switch (optarg[0])
roentgen b75cab
                          {
roentgen b75cab
                          case 'l':
roentgen b75cab
                          case 'L': strcpy (pageOrientation, "Landscape");
roentgen b75cab
			            break; 
roentgen b75cab
                          case 'p':
roentgen b75cab
                          case 'P': strcpy (pageOrientation, "Portrait");
roentgen b75cab
			            break; 
roentgen b75cab
                          default: TIFFError ("-P", "Page orientation must be Landscape or Portrait");
roentgen b75cab
			           exit (-1);
roentgen b75cab
			  }
roentgen b75cab
			break;
roentgen b75cab
		case 'l':
roentgen b75cab
			leftmargin = atof(optarg);
roentgen b75cab
			break;
roentgen b75cab
		case 'a': /* removed fall through to generate warning below, R Nolde 09-01-2010 */
roentgen b75cab
			printAll = TRUE;
roentgen b75cab
			break;
roentgen b75cab
		case 'p':
roentgen b75cab
			generateEPSF = FALSE;
roentgen b75cab
			break;
roentgen b75cab
		case 'r':
roentgen b75cab
                        if (strcmp (optarg, "auto") == 0)
roentgen b75cab
			  {
roentgen b75cab
                          rotation = 0;
roentgen b75cab
                          auto_rotate = TRUE;
roentgen b75cab
                          }
roentgen b75cab
                        else
roentgen b75cab
			  {
roentgen b75cab
 			  rotation = atoi(optarg);
roentgen b75cab
                          auto_rotate = FALSE;
roentgen b75cab
			  }
roentgen b75cab
                        switch (rotation)
roentgen b75cab
                          {
roentgen b75cab
			  case   0:
roentgen b75cab
                          case  90:
roentgen b75cab
                          case 180:
roentgen b75cab
                          case 270:
roentgen b75cab
			    break;
roentgen b75cab
			  default:
roentgen b75cab
                            fprintf (stderr, "Rotation angle must be 90, 180, 270 (degrees ccw) or auto\n");
roentgen b75cab
			    exit (-1);
roentgen b75cab
			  }
roentgen b75cab
			break;
roentgen b75cab
		case 's':
roentgen b75cab
			printAll = FALSE;
roentgen b75cab
			break;
roentgen b75cab
                case 't':
roentgen b75cab
                        title = optarg;
roentgen b75cab
                        break;
roentgen b75cab
		case 'w':
roentgen b75cab
			pageWidth = atof(optarg);
roentgen b75cab
			break;
roentgen b75cab
		case 'z':
roentgen b75cab
			PSavoiddeadzone = FALSE;
roentgen b75cab
			break;
roentgen b75cab
		case '1':
roentgen b75cab
			level2 = FALSE;
roentgen b75cab
			level3 = FALSE;
roentgen b75cab
			ascii85 = FALSE;
roentgen b75cab
			break;
roentgen b75cab
		case '2':
roentgen b75cab
			level2 = TRUE;
roentgen b75cab
			ascii85 = TRUE;			/* default to yes */
roentgen b75cab
			break;
roentgen b75cab
		case '3':
roentgen b75cab
			level3 = TRUE;
roentgen b75cab
			ascii85 = TRUE;			/* default to yes */
roentgen b75cab
			break;
roentgen b75cab
		case '8':
roentgen b75cab
			ascii85 = FALSE;
roentgen b75cab
			break;
roentgen b75cab
		case 'x':
roentgen b75cab
			res_unit = RESUNIT_CENTIMETER;
roentgen b75cab
			break;
roentgen b75cab
		case 'y':
roentgen b75cab
			res_unit = RESUNIT_INCH;
roentgen b75cab
			break;
roentgen b75cab
		case '?':
roentgen b75cab
			usage(-1);
roentgen b75cab
		}
roentgen b75cab
roentgen b75cab
        if (useImagemask == TRUE)
roentgen b75cab
          {
roentgen b75cab
	  if ((level2 == FALSE) && (level3 == FALSE))
roentgen b75cab
            {
roentgen b75cab
	    TIFFError ("-m "," imagemask operator requres Postscript Level2 or Level3");
roentgen b75cab
	    exit (1);
roentgen b75cab
            }
roentgen b75cab
          }
roentgen b75cab
roentgen b75cab
        if (pageWidth && (maxPageWidth > pageWidth))
roentgen b75cab
	  {
roentgen b75cab
	  TIFFError ("-W", "Max viewport width cannot exceed page width");
roentgen b75cab
	  exit (1);
roentgen b75cab
          }
roentgen b75cab
roentgen b75cab
	if (pageHeight && (maxPageHeight > pageHeight))
roentgen b75cab
	  {
roentgen b75cab
	  TIFFError ("-H", "Max viewport height cannot exceed page height");
roentgen b75cab
	  exit (1);
roentgen b75cab
          }
roentgen b75cab
roentgen b75cab
        /* auto rotate requires a specified page width and height */
roentgen b75cab
        if (auto_rotate == TRUE)
roentgen b75cab
          {
roentgen b75cab
	  if ((pageWidth == 0) || (pageHeight == 0))
roentgen b75cab
	    TIFFWarning ("-r auto", " requires page height and width specified with -h and -w");
roentgen b75cab
roentgen b75cab
          if ((maxPageWidth > 0) || (maxPageHeight > 0))
roentgen b75cab
            {
roentgen b75cab
	    TIFFError ("-r auto", " is incompatible with maximum page width/height specified by -H or -W");
roentgen b75cab
            exit (1);
roentgen b75cab
            }
roentgen b75cab
          }
roentgen b75cab
        if ((maxPageWidth > 0) && (maxPageHeight > 0))
roentgen b75cab
            {
roentgen b75cab
	    TIFFError ("-H and -W", " Use only one of -H or -W to define a viewport");
roentgen b75cab
            exit (1);
roentgen b75cab
            }
roentgen b75cab
roentgen b75cab
        if ((generateEPSF == TRUE) && (printAll == TRUE))
roentgen b75cab
          {
roentgen b75cab
	  TIFFError(" -e and -a", "Warning: Cannot generate Encapsulated Postscript for multiple images");
roentgen b75cab
	  generateEPSF = FALSE;
roentgen b75cab
          }
roentgen b75cab
roentgen b75cab
        if ((generateEPSF == TRUE) && (PSduplex == TRUE))
roentgen b75cab
          {
roentgen b75cab
	  TIFFError(" -e and -D", "Warning: Encapsulated Postscript does not support Duplex option");
roentgen b75cab
	  PSduplex = FALSE;
roentgen b75cab
          }
roentgen b75cab
roentgen b75cab
        if ((generateEPSF == TRUE) && (PStumble == TRUE))
roentgen b75cab
          {
roentgen b75cab
	  TIFFError(" -e and -T", "Warning: Encapsulated Postscript does not support Top Edge Binding option");
roentgen b75cab
	  PStumble = FALSE;
roentgen b75cab
          }
roentgen b75cab
roentgen b75cab
        if ((generateEPSF == TRUE) && (PSavoiddeadzone == TRUE))
roentgen b75cab
	  PSavoiddeadzone = FALSE;
roentgen b75cab
roentgen b75cab
	for (; argc - optind > 0; optind++) {
roentgen b75cab
		TIFF* tif = TIFFOpen(filename = argv[optind], "r");
roentgen b75cab
		if (tif != NULL) {
roentgen b75cab
			if (dirnum != -1
roentgen b75cab
                            && !TIFFSetDirectory(tif, (tdir_t)dirnum))
roentgen b75cab
				return (-1);
roentgen b75cab
			else if (diroff != 0 &&
roentgen b75cab
			    !TIFFSetSubDirectory(tif, diroff))
roentgen b75cab
				return (-1);
roentgen b75cab
			np = TIFF2PS(output, tif, pageWidth, pageHeight,
roentgen b75cab
				     leftmargin, bottommargin, centered);
roentgen b75cab
                        if (np < 0)
roentgen b75cab
                          {
roentgen b75cab
			  TIFFError("Error", "Unable to process %s", filename);
roentgen b75cab
                          }
roentgen b75cab
			TIFFClose(tif);
roentgen b75cab
		}
roentgen b75cab
	}
roentgen b75cab
	if (np)
roentgen b75cab
		PSTail(output, np);
roentgen b75cab
	else
roentgen b75cab
		usage(-1);
roentgen b75cab
	if (output != stdout)
roentgen b75cab
		fclose(output);
roentgen b75cab
	return (0);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
static	uint16 samplesperpixel;
roentgen b75cab
static	uint16 bitspersample;
roentgen b75cab
static	uint16 planarconfiguration;
roentgen b75cab
static	uint16 photometric;
roentgen b75cab
static	uint16 compression;
roentgen b75cab
static	uint16 extrasamples;
roentgen b75cab
static	int alpha;
roentgen b75cab
roentgen b75cab
static int
roentgen b75cab
checkImage(TIFF* tif)
roentgen b75cab
{
roentgen b75cab
	switch (photometric) {
roentgen b75cab
	case PHOTOMETRIC_YCBCR:
roentgen b75cab
		if ((compression == COMPRESSION_JPEG || compression == COMPRESSION_OJPEG)
roentgen b75cab
			&& planarconfiguration == PLANARCONFIG_CONTIG) {
roentgen b75cab
			/* can rely on libjpeg to convert to RGB */
roentgen b75cab
			TIFFSetField(tif, TIFFTAG_JPEGCOLORMODE,
roentgen b75cab
				     JPEGCOLORMODE_RGB);
roentgen b75cab
			photometric = PHOTOMETRIC_RGB;
roentgen b75cab
		} else {
roentgen b75cab
			if (level2 || level3)
roentgen b75cab
				break;
roentgen b75cab
			TIFFError(filename, "Can not handle image with %s",
roentgen b75cab
			    "PhotometricInterpretation=YCbCr");
roentgen b75cab
			return (0);
roentgen b75cab
		}
roentgen b75cab
		/* fall thru... */
roentgen b75cab
	case PHOTOMETRIC_RGB:
roentgen b75cab
		if (alpha && bitspersample != 8) {
roentgen b75cab
			TIFFError(filename,
roentgen b75cab
			    "Can not handle %d-bit/sample RGB image with alpha",
roentgen b75cab
			    bitspersample);
roentgen b75cab
			return (0);
roentgen b75cab
		}
roentgen b75cab
		/* fall thru... */
roentgen b75cab
	case PHOTOMETRIC_SEPARATED:
roentgen b75cab
	case PHOTOMETRIC_PALETTE:
roentgen b75cab
	case PHOTOMETRIC_MINISBLACK:
roentgen b75cab
	case PHOTOMETRIC_MINISWHITE:
roentgen b75cab
		break;
roentgen b75cab
	case PHOTOMETRIC_LOGL:
roentgen b75cab
	case PHOTOMETRIC_LOGLUV:
roentgen b75cab
		if (compression != COMPRESSION_SGILOG &&
roentgen b75cab
		    compression != COMPRESSION_SGILOG24) {
roentgen b75cab
			TIFFError(filename,
roentgen b75cab
		    "Can not handle %s data with compression other than SGILog",
roentgen b75cab
			    (photometric == PHOTOMETRIC_LOGL) ?
roentgen b75cab
				"LogL" : "LogLuv"
roentgen b75cab
			);
roentgen b75cab
			return (0);
roentgen b75cab
		}
roentgen b75cab
		/* rely on library to convert to RGB/greyscale */
roentgen b75cab
		TIFFSetField(tif, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_8BIT);
roentgen b75cab
		photometric = (photometric == PHOTOMETRIC_LOGL) ?
roentgen b75cab
		    PHOTOMETRIC_MINISBLACK : PHOTOMETRIC_RGB;
roentgen b75cab
		bitspersample = 8;
roentgen b75cab
		break;
roentgen b75cab
	case PHOTOMETRIC_CIELAB:
roentgen b75cab
		/* fall thru... */
roentgen b75cab
	default:
roentgen b75cab
		TIFFError(filename,
roentgen b75cab
		    "Can not handle image with PhotometricInterpretation=%d",
roentgen b75cab
		    photometric);
roentgen b75cab
		return (0);
roentgen b75cab
	}
roentgen b75cab
	switch (bitspersample) {
roentgen b75cab
	case 1: case 2:
roentgen b75cab
	case 4: case 8:
roentgen b75cab
	case 16:
roentgen b75cab
		break;
roentgen b75cab
	default:
roentgen b75cab
		TIFFError(filename, "Can not handle %d-bit/sample image",
roentgen b75cab
		    bitspersample);
roentgen b75cab
		return (0);
roentgen b75cab
	}
roentgen b75cab
	if (planarconfiguration == PLANARCONFIG_SEPARATE && extrasamples > 0)
roentgen b75cab
		TIFFWarning(filename, "Ignoring extra samples");
roentgen b75cab
	return (1);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
#define PS_UNIT_SIZE	72.0F
roentgen b75cab
#define	PSUNITS(npix,res)	((npix) * (PS_UNIT_SIZE / (res)))
roentgen b75cab
roentgen b75cab
static	char RGBcolorimage[] = "\
roentgen b75cab
/bwproc {\n\
roentgen b75cab
    rgbproc\n\
roentgen b75cab
    dup length 3 idiv string 0 3 0\n\
roentgen b75cab
    5 -1 roll {\n\
roentgen b75cab
	add 2 1 roll 1 sub dup 0 eq {\n\
roentgen b75cab
	    pop 3 idiv\n\
roentgen b75cab
	    3 -1 roll\n\
roentgen b75cab
	    dup 4 -1 roll\n\
roentgen b75cab
	    dup 3 1 roll\n\
roentgen b75cab
	    5 -1 roll put\n\
roentgen b75cab
	    1 add 3 0\n\
roentgen b75cab
	} { 2 1 roll } ifelse\n\
roentgen b75cab
    } forall\n\
roentgen b75cab
    pop pop pop\n\
roentgen b75cab
} def\n\
roentgen b75cab
/colorimage where {pop} {\n\
roentgen b75cab
    /colorimage {pop pop /rgbproc exch def {bwproc} image} bind def\n\
roentgen b75cab
} ifelse\n\
roentgen b75cab
";
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * Adobe Photoshop requires a comment line of the form:
roentgen b75cab
 *
roentgen b75cab
 * %ImageData: <cols> <rows> <depth>  <main channels=""> <pad channels=""></pad></main></depth></rows></cols>
roentgen b75cab
 *	<block size=""> <1 for binary|2 for hex> "data start"</block>
roentgen b75cab
 *
roentgen b75cab
 * It is claimed to be part of some future revision of the EPS spec.
roentgen b75cab
 */
roentgen b75cab
static void
roentgen b75cab
PhotoshopBanner(FILE* fd, uint32 w, uint32 h, int bs, int nc, char* startline)
roentgen b75cab
{
roentgen b75cab
	fprintf(fd, "%%ImageData: %ld %ld %d %d 0 %d 2 \"",
roentgen b75cab
	    (long) w, (long) h, bitspersample, nc, bs);
roentgen b75cab
	fprintf(fd, startline, nc);
roentgen b75cab
	fprintf(fd, "\"\n");
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
/*   Convert pixel width and height pw, ph, to points pprw, pprh 
roentgen b75cab
 *   using image resolution and resolution units from TIFF tags.
roentgen b75cab
 *   pw : image width in pixels
roentgen b75cab
 *   ph : image height in pixels
roentgen b75cab
 * pprw : image width in PS units (72 dpi)
roentgen b75cab
 * pprh : image height in PS units (72 dpi)
roentgen b75cab
 */
roentgen b75cab
static void
roentgen b75cab
setupPageState(TIFF* tif, uint32* pw, uint32* ph, double* pprw, double* pprh)
roentgen b75cab
{
roentgen b75cab
	float xres = 0.0F, yres = 0.0F;
roentgen b75cab
roentgen b75cab
	TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, pw);
roentgen b75cab
	TIFFGetField(tif, TIFFTAG_IMAGELENGTH, ph);
roentgen b75cab
	if (res_unit == 0)	/* Not specified as command line option */
roentgen b75cab
		if (!TIFFGetFieldDefaulted(tif, TIFFTAG_RESOLUTIONUNIT, &res_unit))
roentgen b75cab
			res_unit = RESUNIT_INCH;
roentgen b75cab
	/*
roentgen b75cab
	 * Calculate printable area.
roentgen b75cab
	 */
roentgen b75cab
	if (!TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres)
roentgen b75cab
            || fabs(xres) < 0.0000001)
roentgen b75cab
		xres = PS_UNIT_SIZE;
roentgen b75cab
	if (!TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres)
roentgen b75cab
            || fabs(yres) < 0.0000001)
roentgen b75cab
		yres = PS_UNIT_SIZE;
roentgen b75cab
	switch (res_unit) {
roentgen b75cab
	case RESUNIT_CENTIMETER:
roentgen b75cab
		xres *= 2.54F, yres *= 2.54F;
roentgen b75cab
		break;
roentgen b75cab
	case RESUNIT_INCH:
roentgen b75cab
		break;
roentgen b75cab
	case RESUNIT_NONE:	/* Subsequent code assumes we have converted to inches! */
roentgen b75cab
		res_unit = RESUNIT_INCH;
roentgen b75cab
		break;
roentgen b75cab
	default:	/* Last ditch guess for unspecified RESUNIT case
roentgen b75cab
			 * check that the resolution is not inches before scaling it.
roentgen b75cab
			 * Moved to end of function with additional check, RJN, 08-31-2010
roentgen b75cab
			 * if (xres != PS_UNIT_SIZE || yres != PS_UNIT_SIZE)
roentgen b75cab
			 * xres *= PS_UNIT_SIZE, yres *= PS_UNIT_SIZE;
roentgen b75cab
			 */
roentgen b75cab
		break;
roentgen b75cab
	}
roentgen b75cab
	/* This is a hack to deal with images that have no meaningful Resolution Size
roentgen b75cab
	 * but may have x and/or y resolutions of 1 pixel per undefined unit.
roentgen b75cab
	 */
roentgen b75cab
	if ((xres > 1.0) && (xres != PS_UNIT_SIZE))
roentgen b75cab
		*pprw = PSUNITS(*pw, xres);
roentgen b75cab
	else
roentgen b75cab
		*pprw = PSUNITS(*pw, PS_UNIT_SIZE);
roentgen b75cab
	if ((yres > 1.0) && (yres != PS_UNIT_SIZE))
roentgen b75cab
		*pprh = PSUNITS(*ph, yres);
roentgen b75cab
	else
roentgen b75cab
		*pprh = PSUNITS(*ph, PS_UNIT_SIZE);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
static int
roentgen b75cab
isCCITTCompression(TIFF* tif)
roentgen b75cab
{
roentgen b75cab
    uint16 compress;
roentgen b75cab
    TIFFGetField(tif, TIFFTAG_COMPRESSION, &compress);
roentgen b75cab
    return (compress == COMPRESSION_CCITTFAX3 ||
roentgen b75cab
	    compress == COMPRESSION_CCITTFAX4 ||
roentgen b75cab
	    compress == COMPRESSION_CCITTRLE ||
roentgen b75cab
	    compress == COMPRESSION_CCITTRLEW);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
static	tsize_t tf_bytesperrow;
roentgen b75cab
static	tsize_t ps_bytesperrow;
roentgen b75cab
static	tsize_t	tf_rowsperstrip;
roentgen b75cab
static	tsize_t	tf_numberstrips;
roentgen b75cab
static	char *hex = "0123456789abcdef";
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * Pagewidth and pageheight are the output size in points,
roentgen b75cab
 * may refer to values specified with -h and -w, or to
roentgen b75cab
 * values read from the image if neither -h nor -w are used.
roentgen b75cab
 * Imagewidth and imageheight are image size in points.
roentgen b75cab
 * Ximages and Yimages are number of pages across and down.
roentgen b75cab
 * Only one of maxPageHeight or maxPageWidth can be used.
roentgen b75cab
 * These are global variables unfortunately.
roentgen b75cab
 */
roentgen b75cab
int get_subimage_count(double pagewidth,  double pageheight,
roentgen b75cab
		       double imagewidth, double imageheight,
roentgen b75cab
		       int *ximages, int *yimages,
roentgen b75cab
		       int rotation, double scale)
roentgen b75cab
{
roentgen b75cab
	int pages = 1;
roentgen b75cab
	double splitheight = 0;  /* Requested Max Height in points */
roentgen b75cab
	double splitwidth  = 0;  /* Requested Max Width in points */
roentgen b75cab
	double overlap     = 0;  /* Repeated edge width in points */
roentgen b75cab
roentgen b75cab
	splitheight = maxPageHeight * PS_UNIT_SIZE;
roentgen b75cab
	splitwidth  = maxPageWidth  * PS_UNIT_SIZE;
roentgen b75cab
	overlap     = splitOverlap  * PS_UNIT_SIZE;
roentgen b75cab
	pagewidth  *= PS_UNIT_SIZE;
roentgen b75cab
	pageheight *= PS_UNIT_SIZE;
roentgen b75cab
roentgen b75cab
	if ((imagewidth < 1.0) || (imageheight < 1.0))
roentgen b75cab
	{
roentgen b75cab
		TIFFError("get_subimage_count", "Invalid image width or height");
roentgen b75cab
		return (0);
roentgen b75cab
	}
roentgen b75cab
roentgen b75cab
  switch (rotation)
roentgen b75cab
    {
roentgen b75cab
    case 0:
roentgen b75cab
    case 180: if (splitheight > 0) /* -H maxPageHeight */
roentgen b75cab
                {
roentgen b75cab
               if (imageheight > splitheight) /* More than one vertical image segment */
roentgen b75cab
                 {
roentgen b75cab
                 if (pagewidth)
roentgen b75cab
                   *ximages = (int)ceil((scale * imagewidth)  / (pagewidth - overlap));
roentgen b75cab
                  else
roentgen b75cab
                   *ximages = 1;
roentgen b75cab
                 *yimages = (int)ceil((scale * imageheight) / (splitheight - overlap)); /* Max vert pages needed */
roentgen b75cab
                 }
roentgen b75cab
                else
roentgen b75cab
                 {
roentgen b75cab
                 if (pagewidth)
roentgen b75cab
                   *ximages = (int)ceil((scale * imagewidth) / (pagewidth - overlap));    /* Max horz pages needed */
roentgen b75cab
                  else
roentgen b75cab
                   *ximages = 1;
roentgen b75cab
                 *yimages = 1;                                                     /* Max vert pages needed */
roentgen b75cab
                 }
roentgen b75cab
               }
roentgen b75cab
              else
roentgen b75cab
               {
roentgen b75cab
                if (splitwidth > 0) /* -W maxPageWidth */
roentgen b75cab
                 {
roentgen b75cab
                 if (imagewidth >splitwidth)
roentgen b75cab
                   {
roentgen b75cab
                   *ximages = (int)ceil((scale * imagewidth)  / (splitwidth - overlap));   /* Max horz pages needed */
roentgen b75cab
                    if (pageheight)
roentgen b75cab
                     *yimages = (int)ceil((scale * imageheight) / (pageheight - overlap)); /* Max vert pages needed */
roentgen b75cab
                    else
roentgen b75cab
                     *yimages = 1;
roentgen b75cab
                   }
roentgen b75cab
                  else
roentgen b75cab
                   {
roentgen b75cab
                   *ximages = 1;                                                     /* Max vert pages needed */
roentgen b75cab
                    if (pageheight)
roentgen b75cab
                     *yimages = (int)ceil((scale * imageheight) / (pageheight - overlap)); /* Max vert pages needed */
roentgen b75cab
                    else
roentgen b75cab
                     *yimages = 1;
roentgen b75cab
                   }
roentgen b75cab
                 }
roentgen b75cab
                else
roentgen b75cab
                 {
roentgen b75cab
                 *ximages = 1;
roentgen b75cab
                 *yimages = 1;
roentgen b75cab
                 }
roentgen b75cab
               }
roentgen b75cab
             break;
roentgen b75cab
    case 90:
roentgen b75cab
    case 270: if (splitheight > 0) /* -H maxPageHeight */
roentgen b75cab
                {
roentgen b75cab
               if (imagewidth > splitheight) /* More than one vertical image segment */
roentgen b75cab
                 {
roentgen b75cab
                 *yimages = (int)ceil((scale * imagewidth) / (splitheight - overlap)); /* Max vert pages needed */
roentgen b75cab
                  if (pagewidth)
roentgen b75cab
                   *ximages = (int)ceil((scale * imageheight) / (pagewidth - overlap));   /* Max horz pages needed */
roentgen b75cab
                  else
roentgen b75cab
                   *ximages = 1;
roentgen b75cab
                 }
roentgen b75cab
                else
roentgen b75cab
                 {
roentgen b75cab
                 *yimages = 1;                                                     /* Max vert pages needed */
roentgen b75cab
                  if (pagewidth)
roentgen b75cab
                   *ximages = (int)ceil((scale * imageheight) / (pagewidth - overlap));    /* Max horz pages needed */
roentgen b75cab
                  else
roentgen b75cab
                   *ximages = 1;
roentgen b75cab
                 }
roentgen b75cab
               }
roentgen b75cab
              else
roentgen b75cab
               {
roentgen b75cab
                if (splitwidth > 0) /* -W maxPageWidth */
roentgen b75cab
                 {
roentgen b75cab
                 if (imageheight > splitwidth)
roentgen b75cab
                   {
roentgen b75cab
                   if (pageheight)
roentgen b75cab
                     *yimages = (int)ceil((scale * imagewidth) / (pageheight - overlap)); /* Max vert pages needed */
roentgen b75cab
                    else
roentgen b75cab
                     *yimages = 1;
roentgen b75cab
                   *ximages = (int)ceil((scale * imageheight)  / (splitwidth - overlap));   /* Max horz pages needed */
roentgen b75cab
                   }
roentgen b75cab
                  else
roentgen b75cab
                   {
roentgen b75cab
                   if (pageheight)
roentgen b75cab
                     *yimages = (int)ceil((scale * imagewidth) / (pageheight - overlap));  /* Max horz pages needed */
roentgen b75cab
                    else
roentgen b75cab
                     *yimages = 1;
roentgen b75cab
                   *ximages = 1;                                                     /* Max vert pages needed */
roentgen b75cab
                   }
roentgen b75cab
                 }
roentgen b75cab
                else
roentgen b75cab
                 {
roentgen b75cab
                 *ximages = 1;
roentgen b75cab
                 *yimages = 1;
roentgen b75cab
                 }
roentgen b75cab
               }
roentgen b75cab
             break;
roentgen b75cab
    default:  *ximages = 1;
roentgen b75cab
             *yimages = 1;
roentgen b75cab
  }
roentgen b75cab
  pages = (*ximages) * (*yimages);
roentgen b75cab
  return (pages);
roentgen b75cab
  }
roentgen b75cab
roentgen b75cab
/* New version of PlaceImage that handles only the translation and rotation
roentgen b75cab
 * for a single output page.
roentgen b75cab
 */
roentgen b75cab
int exportMaskedImage(FILE *fp, double pagewidth, double pageheight,
roentgen b75cab
                     double imagewidth, double imageheight,
roentgen b75cab
                      int row, int column,
roentgen b75cab
                      double left_offset, double bott_offset,
roentgen b75cab
                     double scale, int center, int rotation)
roentgen b75cab
  {
roentgen b75cab
  double xtran = 0.0;
roentgen b75cab
  double ytran = 0.0;
roentgen b75cab
roentgen b75cab
  double xscale = 1.0;
roentgen b75cab
  double yscale = 1.0;
roentgen b75cab
roentgen b75cab
  double splitheight    = 0;  /* Requested Max Height in points */
roentgen b75cab
  double splitwidth     = 0;  /* Requested Max Width in points */
roentgen b75cab
  double overlap        = 0;  /* Repeated edge width in points */
roentgen b75cab
  double subimage_height = 0.0;
roentgen b75cab
roentgen b75cab
  splitheight = maxPageHeight * PS_UNIT_SIZE;
roentgen b75cab
  splitwidth  = maxPageWidth  * PS_UNIT_SIZE;
roentgen b75cab
  overlap     = splitOverlap  * PS_UNIT_SIZE;
roentgen b75cab
  xscale = scale * imagewidth;
roentgen b75cab
  yscale = scale * imageheight;
roentgen b75cab
roentgen b75cab
  if ((xscale < 0.0) || (yscale < 0.0))
roentgen b75cab
    {
roentgen b75cab
    TIFFError("exportMaskedImage", "Invalid parameters.");
roentgen b75cab
    return (-1);
roentgen b75cab
    }
roentgen b75cab
roentgen b75cab
  /* If images are cropped to a vewport with -H or -W, the output pages are shifted to
roentgen b75cab
   * the top of each output page rather than the Postscript default lower edge.
roentgen b75cab
   */
roentgen b75cab
  switch (rotation)
roentgen b75cab
    {
roentgen b75cab
    case 0:
roentgen b75cab
    case 180: if (splitheight > 0) /* -H maxPageHeight */
roentgen b75cab
                {
roentgen b75cab
               if (splitheight < imageheight) /* More than one vertical image segments */
roentgen b75cab
                 {
roentgen b75cab
                 xtran = -1.0 * column * (pagewidth - overlap);
roentgen b75cab
                  subimage_height = imageheight - ((splitheight - overlap) * row);
roentgen b75cab
                 ytran  = pageheight - subimage_height * (pageheight / splitheight);
roentgen b75cab
                  }
roentgen b75cab
                else  /* Only one page in vertical direction */
roentgen b75cab
                 {
roentgen b75cab
                 xtran = -1.0 * column * (pagewidth - overlap);
roentgen b75cab
                  ytran = splitheight - imageheight;
roentgen b75cab
                 }
roentgen b75cab
               }
roentgen b75cab
              else
roentgen b75cab
               {
roentgen b75cab
                if (splitwidth > 0) /* maxPageWidth */
roentgen b75cab
                 {
roentgen b75cab
                 if (splitwidth < imagewidth)
roentgen b75cab
                   {
roentgen b75cab
                   xtran = -1.0  * column * splitwidth;
roentgen b75cab
                   ytran = -1.0 * row * (pageheight - overlap);
roentgen b75cab
                    }
roentgen b75cab
                  else /* Only one page in horizontal direction */
roentgen b75cab
                   {
roentgen b75cab
                    ytran = -1.0 * row * (pageheight - overlap);
roentgen b75cab
                    xtran = 0;
roentgen b75cab
                   }
roentgen b75cab
                 }
roentgen b75cab
                else    /* Simple case, no splitting */
roentgen b75cab
                 {
roentgen b75cab
                 ytran = pageheight - imageheight;
roentgen b75cab
                 xtran = 0;
roentgen b75cab
                  }
roentgen b75cab
                }
roentgen b75cab
              bott_offset += ytran / (center ? 2 : 1);
roentgen b75cab
              left_offset += xtran / (center ? 2 : 1);
roentgen b75cab
              break;
roentgen b75cab
    case  90:
roentgen b75cab
    case 270:  if (splitheight > 0) /* -H maxPageHeight */
roentgen b75cab
                {
roentgen b75cab
               if (splitheight < imagewidth) /* More than one vertical image segments */
roentgen b75cab
                 {
roentgen b75cab
                 xtran = -1.0 * column * (pageheight - overlap);
roentgen b75cab
                 /* Commented code places image at bottom of page instead of top.
roentgen b75cab
                     ytran = -1.0 * row * splitheight;
roentgen b75cab
                   */
roentgen b75cab
                  if (row == 0)
roentgen b75cab
                    ytran = -1.0 * (imagewidth - splitheight);
roentgen b75cab
                  else
roentgen b75cab
                    ytran = -1.0 * (imagewidth - (splitheight - overlap) * (row + 1));
roentgen b75cab
                  }
roentgen b75cab
                else  /* Only one page in vertical direction */
roentgen b75cab
                 {
roentgen b75cab
                  xtran = -1.0 * column * (pageheight - overlap);
roentgen b75cab
                  ytran = splitheight - imagewidth;
roentgen b75cab
                 }
roentgen b75cab
		}
roentgen b75cab
              else
roentgen b75cab
               {
roentgen b75cab
                if (splitwidth > 0) /* maxPageWidth */
roentgen b75cab
                 {
roentgen b75cab
                 if (splitwidth < imageheight)
roentgen b75cab
                   {
roentgen b75cab
                    xtran = -1.0  * column * splitwidth;
roentgen b75cab
                    ytran = -1.0 * row * (pagewidth - overlap);
roentgen b75cab
                    }
roentgen b75cab
                  else /* Only one page in horizontal direction */
roentgen b75cab
                   {
roentgen b75cab
                    ytran = -1.0 * row * (pagewidth - overlap);
roentgen b75cab
                    xtran = 0;
roentgen b75cab
                   }
roentgen b75cab
                 }
roentgen b75cab
                else    /* Simple case, no splitting */
roentgen b75cab
                 {
roentgen b75cab
                 ytran = pageheight - imageheight;
roentgen b75cab
                 xtran = 0; /* pagewidth  - imagewidth; */
roentgen b75cab
                  }
roentgen b75cab
                }
roentgen b75cab
              bott_offset += ytran / (center ? 2 : 1);
roentgen b75cab
              left_offset += xtran / (center ? 2 : 1);
roentgen b75cab
              break;
roentgen b75cab
    default:  xtran = 0;
roentgen b75cab
             ytran = 0;
roentgen b75cab
    }
roentgen b75cab
roentgen b75cab
  switch (rotation)
roentgen b75cab
    {
roentgen b75cab
    case   0: fprintf(fp, "%f %f translate\n", left_offset, bott_offset);
roentgen b75cab
              fprintf(fp, "%f %f scale\n", xscale, yscale);
roentgen b75cab
             break;
roentgen b75cab
    case 180: fprintf(fp, "%f %f translate\n", left_offset, bott_offset);
roentgen b75cab
              fprintf(fp, "%f %f scale\n1 1 translate 180 rotate\n",  xscale, yscale);
roentgen b75cab
              break;
roentgen b75cab
    case  90: fprintf(fp, "%f %f translate\n", left_offset, bott_offset);
roentgen b75cab
              fprintf(fp, "%f %f scale\n1 0 translate 90 rotate\n", yscale, xscale);
roentgen b75cab
              break;
roentgen b75cab
    case 270: fprintf(fp, "%f %f translate\n", left_offset, bott_offset);
roentgen b75cab
              fprintf(fp, "%f %f scale\n0 1 translate 270 rotate\n", yscale, xscale);
roentgen b75cab
              break;
roentgen b75cab
    default:  TIFFError ("exportMaskedImage", "Unsupported rotation angle %d. No rotation", rotation);
roentgen b75cab
             fprintf( fp, "%f %f scale\n", xscale, yscale);
roentgen b75cab
              break;
roentgen b75cab
    }
roentgen b75cab
roentgen b75cab
  return (0);
roentgen b75cab
  }
roentgen b75cab
roentgen b75cab
/* Rotate an image without scaling or clipping */
roentgen b75cab
int  psRotateImage (FILE * fd, int rotation, double pswidth, double psheight,
roentgen b75cab
                    double left_offset, double bottom_offset)
roentgen b75cab
  {
roentgen b75cab
  if ((left_offset != 0.0) || (bottom_offset != 0))
roentgen b75cab
    fprintf (fd, "%f %f translate\n", left_offset, bottom_offset);
roentgen b75cab
roentgen b75cab
  /* Exchange width and height for 90/270 rotations */
roentgen b75cab
  switch (rotation)
roentgen b75cab
    {
roentgen b75cab
    case   0: fprintf (fd, "%f %f scale\n", pswidth, psheight);
roentgen b75cab
              break;
roentgen b75cab
    case  90: fprintf (fd, "%f %f scale\n1 0 translate 90 rotate\n", psheight, pswidth);
roentgen b75cab
              break;
roentgen b75cab
    case 180: fprintf (fd, "%f %f scale\n1 1 translate 180 rotate\n", pswidth, psheight);
roentgen b75cab
              break;
roentgen b75cab
    case 270: fprintf (fd, "%f %f scale\n0 1 translate 270 rotate\n", psheight, pswidth);
roentgen b75cab
              break;
roentgen b75cab
    default:  TIFFError ("psRotateImage", "Unsupported rotation %d.", rotation);
roentgen b75cab
             fprintf( fd, "%f %f scale\n", pswidth, psheight);
roentgen b75cab
              return (1);
roentgen b75cab
    }
roentgen b75cab
  return (0);
roentgen b75cab
  }
roentgen b75cab
roentgen b75cab
/* Scale and rotate an image to a single output page. */
roentgen b75cab
int psScaleImage(FILE * fd, double scale, int rotation, int center,
roentgen b75cab
                 double reqwidth, double reqheight, double pswidth, double psheight,
roentgen b75cab
                 double left_offset, double bottom_offset)
roentgen b75cab
  {
roentgen b75cab
  double hcenter = 0.0, vcenter = 0.0;
roentgen b75cab
roentgen b75cab
  /* Adjust offsets for centering */
roentgen b75cab
  if (center)
roentgen b75cab
    {
roentgen b75cab
    switch (rotation)
roentgen b75cab
      {
roentgen b75cab
      case   90: vcenter = (reqheight - pswidth * scale) / 2;
roentgen b75cab
                hcenter = (reqwidth - psheight * scale) / 2;
roentgen b75cab
                 fprintf (fd, "%f %f translate\n", hcenter, vcenter);
roentgen b75cab
                 fprintf (fd, "%f %f scale\n1 0 translate 90 rotate\n", psheight * scale, pswidth * scale);
roentgen b75cab
                 break;
roentgen b75cab
      case  180: hcenter = (reqwidth - pswidth * scale) / 2;
roentgen b75cab
                vcenter = (reqheight - psheight * scale) / 2;
roentgen b75cab
                 fprintf (fd, "%f %f translate\n", hcenter, vcenter);
roentgen b75cab
                 fprintf (fd, "%f %f scale\n1 1 translate 180 rotate\n", pswidth * scale, psheight * scale);
roentgen b75cab
                 break;
roentgen b75cab
      case  270: vcenter = (reqheight - pswidth * scale) / 2;
roentgen b75cab
                hcenter = (reqwidth - psheight * scale) / 2;
roentgen b75cab
                 fprintf (fd, "%f %f translate\n", hcenter, vcenter);
roentgen b75cab
                 fprintf (fd, "%f %f scale\n0 1 translate 270 rotate\n", psheight * scale, pswidth * scale);
roentgen b75cab
                 break;
roentgen b75cab
      case    0:
roentgen b75cab
      default:   hcenter = (reqwidth - pswidth * scale) / 2;
roentgen b75cab
                vcenter = (reqheight - psheight * scale) / 2;
roentgen b75cab
                 fprintf (fd, "%f %f translate\n", hcenter, vcenter);
roentgen b75cab
                 fprintf (fd, "%f %f scale\n", pswidth * scale, psheight * scale);
roentgen b75cab
                 break;
roentgen b75cab
      }
roentgen b75cab
    }
roentgen b75cab
  else  /* Not centered */
roentgen b75cab
    {
roentgen b75cab
    switch (rotation)
roentgen b75cab
      {
roentgen b75cab
      case 0:   fprintf (fd, "%f %f translate\n", left_offset ? left_offset : 0.0,
roentgen b75cab
                         bottom_offset ? bottom_offset : reqheight - (psheight * scale));
roentgen b75cab
                fprintf (fd, "%f %f scale\n", pswidth * scale, psheight * scale);
roentgen b75cab
                break;
roentgen b75cab
      case 90:  fprintf (fd, "%f %f translate\n", left_offset ? left_offset : 0.0,
roentgen b75cab
                         bottom_offset ? bottom_offset : reqheight - (pswidth * scale));
roentgen b75cab
                fprintf (fd, "%f %f scale\n1 0 translate 90 rotate\n", psheight * scale, pswidth * scale);
roentgen b75cab
                break;
roentgen b75cab
      case 180: fprintf (fd, "%f %f translate\n", left_offset ? left_offset : 0.0,
roentgen b75cab
                         bottom_offset ? bottom_offset : reqheight - (psheight * scale));
roentgen b75cab
                fprintf (fd, "%f %f scale\n1 1 translate 180 rotate\n", pswidth * scale, psheight * scale);
roentgen b75cab
                break;
roentgen b75cab
      case 270: fprintf (fd, "%f %f translate\n", left_offset ? left_offset : 0.0,
roentgen b75cab
                         bottom_offset ? bottom_offset : reqheight - (pswidth * scale));
roentgen b75cab
                fprintf (fd, "%f %f scale\n0 1 translate 270 rotate\n", psheight * scale, pswidth * scale);
roentgen b75cab
                break;
roentgen b75cab
      default:  TIFFError ("psScaleImage", "Unsupported rotation  %d", rotation);
roentgen b75cab
               fprintf (fd, "%f %f scale\n", pswidth * scale, psheight * scale);
roentgen b75cab
                return (1);
roentgen b75cab
      }
roentgen b75cab
    }
roentgen b75cab
roentgen b75cab
  return (0);
roentgen b75cab
  }
roentgen b75cab
roentgen b75cab
/* This controls the visible portion of the page which is displayed.
roentgen b75cab
 * N.B. Setting maxPageHeight no longer sets pageheight if not set explicitly
roentgen b75cab
 */
roentgen b75cab
int psPageSize (FILE * fd, int rotation, double pgwidth, double pgheight,
roentgen b75cab
                double reqwidth, double reqheight, double pswidth, double psheight)
roentgen b75cab
  {
roentgen b75cab
  double xscale = 1.0, yscale = 1.0, scale = 1.0;
roentgen b75cab
  double splitheight;
roentgen b75cab
  double splitwidth;
roentgen b75cab
  double new_width;
roentgen b75cab
  double new_height;
roentgen b75cab
roentgen b75cab
  splitheight = maxPageHeight * PS_UNIT_SIZE;
roentgen b75cab
  splitwidth  = maxPageWidth  * PS_UNIT_SIZE;
roentgen b75cab
roentgen b75cab
  switch (rotation)
roentgen b75cab
    {
roentgen b75cab
    case   0:
roentgen b75cab
    case 180: if ((splitheight > 0) || (splitwidth > 0))
roentgen b75cab
                {
roentgen b75cab
               if (pgwidth != 0 || pgheight != 0)
roentgen b75cab
                  {
roentgen b75cab
                 xscale = reqwidth / (splitwidth ? splitwidth : pswidth);
roentgen b75cab
                 yscale = reqheight / (splitheight ? splitheight : psheight);
roentgen b75cab
                  scale = (xscale < yscale) ? xscale : yscale;
roentgen b75cab
                  }
roentgen b75cab
                new_width = splitwidth ? splitwidth : scale * pswidth;
roentgen b75cab
                new_height = splitheight ? splitheight : scale * psheight;
roentgen b75cab
                if (strlen(pageOrientation))
roentgen b75cab
                  fprintf (fd, "%%%%PageOrientation: %s\n", pageOrientation);
roentgen b75cab
                else
roentgen b75cab
                  fprintf (fd, "%%%%PageOrientation: %s\n", (new_width > new_height) ? "Landscape" : "Portrait");
roentgen b75cab
                fprintf (fd, "%%%%PageBoundingBox: 0 0 %ld %ld\n", (long)new_width, (long)new_height);
roentgen b75cab
                fprintf (fd, "1 dict begin /PageSize [ %f %f ] def currentdict end setpagedevice\n",
roentgen b75cab
                       new_width, new_height);
roentgen b75cab
                }
roentgen b75cab
             else /* No viewport defined with -H or -W */
roentgen b75cab
                {
roentgen b75cab
                if ((pgwidth == 0) && (pgheight == 0)) /* Image not scaled */
roentgen b75cab
                  {
roentgen b75cab
                  if (strlen(pageOrientation))
roentgen b75cab
                    fprintf (fd, "%%%%PageOrientation: %s\n", pageOrientation);
roentgen b75cab
                  else
roentgen b75cab
                    fprintf (fd, "%%%%PageOrientation: %s\n", (pswidth > psheight) ? "Landscape" : "Portrait");
roentgen b75cab
                 fprintf (fd, "%%%%PageBoundingBox: 0 0 %ld %ld\n", (long)pswidth, (long)psheight);
roentgen b75cab
                  fprintf(fd, "1 dict begin /PageSize [ %f %f ] def currentdict end setpagedevice\n",
roentgen b75cab
                          pswidth, psheight);
roentgen b75cab
                  }
roentgen b75cab
               else /* Image scaled */
roentgen b75cab
                  {
roentgen b75cab
                  if (strlen(pageOrientation))
roentgen b75cab
                    fprintf (fd, "%%%%PageOrientation: %s\n", pageOrientation);
roentgen b75cab
                  else
roentgen b75cab
                    fprintf (fd, "%%%%PageOrientation: %s\n", (reqwidth > reqheight) ? "Landscape" : "Portrait");
roentgen b75cab
                 fprintf (fd, "%%%%PageBoundingBox: 0 0 %ld %ld\n", (long)reqwidth, (long)reqheight);
roentgen b75cab
                  fprintf(fd, "1 dict begin /PageSize [ %f %f ] def currentdict end setpagedevice\n",
roentgen b75cab
                           reqwidth, reqheight);
roentgen b75cab
                  }
roentgen b75cab
                }
roentgen b75cab
             break;
roentgen b75cab
    case  90:
roentgen b75cab
    case 270: if ((splitheight > 0) || (splitwidth > 0))
roentgen b75cab
               {
roentgen b75cab
               if (pgwidth != 0 || pgheight != 0)
roentgen b75cab
                  {
roentgen b75cab
                 xscale = reqwidth / (splitwidth ? splitwidth : pswidth);
roentgen b75cab
                 yscale = reqheight / (splitheight ? splitheight : psheight);
roentgen b75cab
                  scale = (xscale < yscale) ? xscale : yscale;
roentgen b75cab
                  }
roentgen b75cab
                new_width = splitwidth ? splitwidth : scale * psheight;
roentgen b75cab
                new_height = splitheight ? splitheight : scale * pswidth;
roentgen b75cab
roentgen b75cab
                if (strlen(pageOrientation))
roentgen b75cab
                  fprintf (fd, "%%%%PageOrientation: %s\n", pageOrientation);
roentgen b75cab
                else
roentgen b75cab
                  fprintf (fd, "%%%%PageOrientation: %s\n", (new_width > new_height) ? "Landscape" : "Portrait");
roentgen b75cab
                fprintf (fd, "%%%%PageBoundingBox: 0 0 %ld %ld\n", (long)new_width, (long)new_height);
roentgen b75cab
                fprintf (fd, "1 dict begin /PageSize [ %f %f ] def currentdict end setpagedevice\n",
roentgen b75cab
                       new_width, new_height);
roentgen b75cab
                }
roentgen b75cab
              else
roentgen b75cab
                {
roentgen b75cab
                if ((pgwidth == 0) && (pgheight == 0)) /* Image not scaled */
roentgen b75cab
                  {
roentgen b75cab
                  if (strlen(pageOrientation))
roentgen b75cab
                    fprintf (fd, "%%%%PageOrientation: %s\n", pageOrientation);
roentgen b75cab
                  else
roentgen b75cab
                    fprintf (fd, "%%%%PageOrientation: %s\n", (psheight > pswidth) ? "Landscape" : "Portrait");
roentgen b75cab
                 fprintf (fd, "%%%%PageBoundingBox: 0 0 %ld %ld\n", (long)psheight, (long)pswidth);
roentgen b75cab
                  fprintf(fd, "1 dict begin /PageSize [ %f %f ] def currentdict end setpagedevice\n",
roentgen b75cab
                         psheight, pswidth);
roentgen b75cab
                  }
roentgen b75cab
               else /* Image scaled */
roentgen b75cab
                  {
roentgen b75cab
                  if (strlen(pageOrientation))
roentgen b75cab
                    fprintf (fd, "%%%%PageOrientation: %s\n", pageOrientation);
roentgen b75cab
                  else
roentgen b75cab
                    fprintf (fd, "%%%%PageOrientation: %s\n", (reqwidth > reqheight) ? "Landscape" : "Portrait");
roentgen b75cab
                 fprintf (fd, "%%%%PageBoundingBox: 0 0 %ld %ld\n", (long)reqwidth, (long)reqheight);
roentgen b75cab
                  fprintf(fd, "1 dict begin /PageSize [ %f %f ] def currentdict end setpagedevice\n",
roentgen b75cab
                          reqwidth, reqheight);
roentgen b75cab
                  }
roentgen b75cab
               }
roentgen b75cab
             break;
roentgen b75cab
    default:  TIFFError ("psPageSize", "Invalid rotation %d", rotation);
roentgen b75cab
      return (1);
roentgen b75cab
    }
roentgen b75cab
  fputs("<<\n  /Policies <<\n    /PageSize 3\n  >>\n>> setpagedevice\n", fd);
roentgen b75cab
roentgen b75cab
  return (0);
roentgen b75cab
  } /* end psPageSize */
roentgen b75cab
roentgen b75cab
/* Mask an image as a series of pages, each only showing a section defined
roentgen b75cab
 * by the maxPageHeight or maxPageWidth options.
roentgen b75cab
 */
roentgen b75cab
int psMaskImage(FILE *fd, TIFF *tif, int rotation, int center,
roentgen b75cab
                int *npages, double pixwidth, double pixheight,
roentgen b75cab
               double left_margin, double bottom_margin,
roentgen b75cab
                double pgwidth, double pgheight,
roentgen b75cab
               double pswidth, double psheight, double scale)
roentgen b75cab
  {
roentgen b75cab
  int i, j;
roentgen b75cab
  int ximages = 1, yimages = 1;
roentgen b75cab
  int pages = *npages;
roentgen b75cab
  double view_width = 0;
roentgen b75cab
  double view_height = 0;
roentgen b75cab
roentgen b75cab
  if (get_viewport (pgwidth, pgheight, pswidth, psheight, &view_width, &view_height, rotation))
roentgen b75cab
    {
roentgen b75cab
    TIFFError ("get_viewport", "Unable to set image viewport");
roentgen b75cab
    return (-1);
roentgen b75cab
    }
roentgen b75cab
roentgen b75cab
  if (get_subimage_count(pgwidth, pgheight, pswidth, psheight,
roentgen b75cab
                        &ximages, &yimages, rotation, scale) < 1)
roentgen b75cab
    {
roentgen b75cab
    TIFFError("get_subimage_count", "Invalid image count: %d columns, %d rows", ximages, yimages);
roentgen b75cab
    return (-1);
roentgen b75cab
    }
roentgen b75cab
roentgen b75cab
  for (i = 0; i < yimages; i++)
roentgen b75cab
    {
roentgen b75cab
    for (j = 0; j < ximages; j++)
roentgen b75cab
       {
roentgen b75cab
       pages++;
roentgen b75cab
       *npages = pages;
roentgen b75cab
       fprintf(fd, "%%%%Page: %d %d\n", pages, pages);
roentgen b75cab
roentgen b75cab
       /* Write out the PageSize info for non EPS files */
roentgen b75cab
       if (!generateEPSF && ( level2 || level3 ))
roentgen b75cab
         {
roentgen b75cab
         if (psPageSize(fd, rotation, pgwidth, pgheight,
roentgen b75cab
                        view_width, view_height, pswidth, psheight))
roentgen b75cab
           return (-1);
roentgen b75cab
        }
roentgen b75cab
       fprintf(fd, "gsave\n");
roentgen b75cab
       fprintf(fd, "100 dict begin\n");
roentgen b75cab
       if (exportMaskedImage(fd, view_width, view_height, pswidth, psheight,
roentgen b75cab
                            i, j, left_margin, bottom_margin,
roentgen b75cab
                            scale, center, rotation))
roentgen b75cab
        {
roentgen b75cab
        TIFFError("exportMaskedImage", "Invalid image parameters.");
roentgen b75cab
        return (-1);
roentgen b75cab
        }
roentgen b75cab
       PSpage(fd, tif, pixwidth, pixheight);
roentgen b75cab
       fprintf(fd, "end\n");
roentgen b75cab
       fprintf(fd, "grestore\n");
roentgen b75cab
       fprintf(fd, "showpage\n");
roentgen b75cab
       }
roentgen b75cab
    }
roentgen b75cab
roentgen b75cab
  return (pages);
roentgen b75cab
  }
roentgen b75cab
roentgen b75cab
/* Compute scale factor and write out file header */
roentgen b75cab
int psStart(FILE *fd, int npages, int auto_rotate, int *rotation, double *scale,
roentgen b75cab
            double ox, double oy, double pgwidth, double pgheight,
roentgen b75cab
           double reqwidth, double reqheight, double pswidth, double psheight,
roentgen b75cab
           double left_offset, double bottom_offset)
roentgen b75cab
  {
roentgen b75cab
  double maxsource = 0.0;    /* Used for auto rotations */
roentgen b75cab
  double maxtarget = 0.0;
roentgen b75cab
  double xscale = 1.0, yscale = 1.0;
roentgen b75cab
  double splitheight;
roentgen b75cab
  double splitwidth;
roentgen b75cab
  double view_width = 0.0, view_height = 0.0;
roentgen b75cab
  double page_width = 0.0, page_height = 0.0;
roentgen b75cab
roentgen b75cab
  /* Splitheight and splitwidth are in inches */
roentgen b75cab
  splitheight = maxPageHeight * PS_UNIT_SIZE;
roentgen b75cab
  splitwidth  = maxPageWidth * PS_UNIT_SIZE;
roentgen b75cab
roentgen b75cab
  page_width = pgwidth * PS_UNIT_SIZE;
roentgen b75cab
  page_height = pgheight * PS_UNIT_SIZE;
roentgen b75cab
roentgen b75cab
  /* If user has specified a page width and height and requested the
roentgen b75cab
   * image to be auto-rotated to fit on that media, we match the
roentgen b75cab
   * longest dimension of the image to the longest dimension of the
roentgen b75cab
   * target media but we have to ignore auto rotate if user specified
roentgen b75cab
   * maxPageHeight since this makes life way too complicated. */
roentgen b75cab
  if (auto_rotate)
roentgen b75cab
    {
roentgen b75cab
    if ((splitheight != 0) || (splitwidth != 0))
roentgen b75cab
      {
roentgen b75cab
      TIFFError ("psStart", "Auto-rotate is incompatible with page splitting ");
roentgen b75cab
      return (1);
roentgen b75cab
      }
roentgen b75cab
roentgen b75cab
    /* Find longest edges in image and output media */
roentgen b75cab
    maxsource = (pswidth >= psheight) ? pswidth : psheight;
roentgen b75cab
    maxtarget = (reqwidth >= reqheight) ? reqwidth : reqheight;
roentgen b75cab
roentgen b75cab
    if (((maxsource == pswidth) && (maxtarget != reqwidth)) ||
roentgen b75cab
        ((maxsource == psheight) && (maxtarget != reqheight)))
roentgen b75cab
      {  /* optimal orientaion does not match input orientation */
roentgen b75cab
      *rotation = 90;
roentgen b75cab
      xscale = (reqwidth - left_offset)/psheight;
roentgen b75cab
      yscale = (reqheight - bottom_offset)/pswidth;
roentgen b75cab
      }
roentgen b75cab
    else /* optimal orientaion matches input orientation */
roentgen b75cab
      {
roentgen b75cab
      xscale = (reqwidth - left_offset)/pswidth;
roentgen b75cab
      yscale = (reqheight - bottom_offset)/psheight;
roentgen b75cab
      }
roentgen b75cab
    *scale = (xscale < yscale) ? xscale : yscale;
roentgen b75cab
roentgen b75cab
    /* Do not scale image beyound original size */
roentgen b75cab
    if (*scale > 1.0)
roentgen b75cab
      *scale = 1.0;
roentgen b75cab
roentgen b75cab
    /* Set the size of the displayed image to requested page size
roentgen b75cab
     * and optimal orientation.
roentgen b75cab
     */
roentgen b75cab
    if (!npages)
roentgen b75cab
      PSHead(fd, reqwidth, reqheight, ox, oy);
roentgen b75cab
roentgen b75cab
    return (0);
roentgen b75cab
    }
roentgen b75cab
roentgen b75cab
  /* N.B. If pgwidth or pgheight are set from maxPageHeight/Width,
roentgen b75cab
   * we have a problem with the tests below under splitheight.
roentgen b75cab
   */
roentgen b75cab
roentgen b75cab
  switch (*rotation)  /* Auto rotate has NOT been specified */
roentgen b75cab
    {
roentgen b75cab
    case   0:
roentgen b75cab
    case 180: if ((splitheight != 0)  || (splitwidth != 0))
roentgen b75cab
                {  /* Viewport clipped to maxPageHeight or maxPageWidth */
roentgen b75cab
                if ((page_width != 0) || (page_height != 0)) /* Image scaled */
roentgen b75cab
                  {
roentgen b75cab
                 xscale = (reqwidth  - left_offset) / (page_width ? page_width : pswidth);
roentgen b75cab
                 yscale = (reqheight - bottom_offset) / (page_height ? page_height : psheight);
roentgen b75cab
                  *scale = (xscale < yscale) ? xscale : yscale;
roentgen b75cab
                  /*
roentgen b75cab
                  if (*scale > 1.0)
roentgen b75cab
                    *scale = 1.0;
roentgen b75cab
                   */
roentgen b75cab
                 }
roentgen b75cab
                else       /* Image clipped but not scaled */
roentgen b75cab
                 *scale = 1.0;
roentgen b75cab
roentgen b75cab
                view_width = splitwidth ? splitwidth : *scale * pswidth;
roentgen b75cab
                view_height = splitheight ? splitheight: *scale * psheight;
roentgen b75cab
               }
roentgen b75cab
              else   /* Viewport not clipped to maxPageHeight or maxPageWidth */
roentgen b75cab
                {
roentgen b75cab
                if ((page_width != 0) || (page_height != 0))
roentgen b75cab
                  {   /* Image scaled  */
roentgen b75cab
                  xscale = (reqwidth - left_offset) / pswidth;
roentgen b75cab
                  yscale = (reqheight - bottom_offset) / psheight;
roentgen b75cab
roentgen b75cab
                  view_width = reqwidth;
roentgen b75cab
                  view_height = reqheight;
roentgen b75cab
                 }
roentgen b75cab
                else
roentgen b75cab
                  {  /* Image not scaled  */
roentgen b75cab
                  xscale = (pswidth - left_offset)/pswidth;
roentgen b75cab
                  yscale = (psheight - bottom_offset)/psheight;
roentgen b75cab
roentgen b75cab
                  view_width = pswidth;
roentgen b75cab
                  view_height = psheight;
roentgen b75cab
                 }
roentgen b75cab
               }
roentgen b75cab
             break;
roentgen b75cab
    case  90:
roentgen b75cab
    case 270: if ((splitheight != 0) || (splitwidth != 0))
roentgen b75cab
                {  /* Viewport clipped to maxPageHeight or maxPageWidth */
roentgen b75cab
                if ((page_width != 0) || (page_height != 0)) /* Image scaled */
roentgen b75cab
                  {
roentgen b75cab
                 xscale = (reqwidth - left_offset)/ psheight;
roentgen b75cab
                 yscale = (reqheight - bottom_offset)/ pswidth;
roentgen b75cab
                  *scale = (xscale < yscale) ? xscale : yscale;
roentgen b75cab
                  /*
roentgen b75cab
                  if (*scale > 1.0)
roentgen b75cab
                    *scale = 1.0;
roentgen b75cab
                 */
roentgen b75cab
                 }
roentgen b75cab
                else  /* Image clipped but not scaled */
roentgen b75cab
                 *scale = 1.0;
roentgen b75cab
                view_width = splitwidth ? splitwidth : *scale * psheight;
roentgen b75cab
                view_height = splitheight ? splitheight : *scale * pswidth;
roentgen b75cab
               }
roentgen b75cab
              else /* Viewport not clipped to maxPageHeight or maxPageWidth */
roentgen b75cab
                {
roentgen b75cab
                if ((page_width != 0) || (page_height != 0)) /* Image scaled */
roentgen b75cab
                  {
roentgen b75cab
                  xscale = (reqwidth - left_offset) / psheight;
roentgen b75cab
                  yscale = (reqheight - bottom_offset) / pswidth;
roentgen b75cab
roentgen b75cab
                 view_width = reqwidth;
roentgen b75cab
                 view_height = reqheight;
roentgen b75cab
                 }
roentgen b75cab
                else
roentgen b75cab
                  {
roentgen b75cab
                  xscale = (pswidth  - left_offset)/ psheight;
roentgen b75cab
                 yscale = (psheight  - bottom_offset)/ pswidth;
roentgen b75cab
roentgen b75cab
                 view_width = psheight;
roentgen b75cab
                 view_height = pswidth;
roentgen b75cab
                  }
roentgen b75cab
                }
roentgen b75cab
              break;
roentgen b75cab
    default:  TIFFError ("psPageSize", "Invalid rotation %d", *rotation);
roentgen b75cab
              return (1);
roentgen b75cab
    }
roentgen b75cab
roentgen b75cab
  if (!npages)
roentgen b75cab
    PSHead(fd, (page_width ? page_width : view_width), (page_height ? page_height : view_height), ox, oy);
roentgen b75cab
roentgen b75cab
  *scale = (xscale < yscale) ? xscale : yscale;
roentgen b75cab
  if (*scale > 1.0)
roentgen b75cab
    *scale = 1.0;
roentgen b75cab
roentgen b75cab
  return (0);
roentgen b75cab
  }
roentgen b75cab
roentgen b75cab
int get_viewport (double pgwidth, double pgheight, double pswidth, double psheight,
roentgen b75cab
                  double *view_width, double *view_height, int rotation)
roentgen b75cab
  {
roentgen b75cab
  /* Only one of maxPageHeight or maxPageWidth can be specified */
roentgen b75cab
  if (maxPageHeight != 0)   /* Clip the viewport to maxPageHeight on each page */
roentgen b75cab
    {
roentgen b75cab
    *view_height = maxPageHeight * PS_UNIT_SIZE;
roentgen b75cab
    /*
roentgen b75cab
     * if (res_unit == RESUNIT_CENTIMETER)
roentgen b75cab
     * *view_height /= 2.54F;
roentgen b75cab
     */
roentgen b75cab
    }
roentgen b75cab
  else
roentgen b75cab
    {
roentgen b75cab
    if (pgheight != 0) /* User has set PageHeight with -h flag */
roentgen b75cab
      {
roentgen b75cab
      *view_height = pgheight * PS_UNIT_SIZE; /* Postscript size for Page Height in inches */
roentgen b75cab
      /* if (res_unit == RESUNIT_CENTIMETER)
roentgen b75cab
       *  *view_height /= 2.54F;
roentgen b75cab
       */
roentgen b75cab
      }
roentgen b75cab
    else /* If no width or height are specified, use the original size from image */
roentgen b75cab
      switch (rotation)
roentgen b75cab
        {
roentgen b75cab
        default:
roentgen b75cab
        case   0:
roentgen b75cab
        case 180: *view_height = psheight;
roentgen b75cab
                 break;
roentgen b75cab
        case  90:
roentgen b75cab
        case 270: *view_height = pswidth;
roentgen b75cab
                 break;
roentgen b75cab
       }
roentgen b75cab
    }
roentgen b75cab
roentgen b75cab
  if (maxPageWidth != 0)   /* Clip the viewport to maxPageWidth on each page */
roentgen b75cab
    {
roentgen b75cab
    *view_width = maxPageWidth * PS_UNIT_SIZE;
roentgen b75cab
    /* if (res_unit == RESUNIT_CENTIMETER)
roentgen b75cab
     *  *view_width /= 2.54F;
roentgen b75cab
     */
roentgen b75cab
    }
roentgen b75cab
  else
roentgen b75cab
    {
roentgen b75cab
    if (pgwidth != 0)  /* User has set PageWidth with -w flag */
roentgen b75cab
      {
roentgen b75cab
      *view_width = pgwidth * PS_UNIT_SIZE; /* Postscript size for Page Width in inches */
roentgen b75cab
      /* if (res_unit == RESUNIT_CENTIMETER)
roentgen b75cab
       * *view_width /= 2.54F;
roentgen b75cab
       */
roentgen b75cab
      }
roentgen b75cab
    else  /* If no width or height are specified, use the original size from image */
roentgen b75cab
      switch (rotation)
roentgen b75cab
        {
roentgen b75cab
        default:
roentgen b75cab
        case   0:
roentgen b75cab
        case 180: *view_width = pswidth;
roentgen b75cab
                 break;
roentgen b75cab
        case  90:
roentgen b75cab
        case 270: *view_width = psheight; /* (*view_height / psheight) * psheight; */
roentgen b75cab
                 break;
roentgen b75cab
       }
roentgen b75cab
    }
roentgen b75cab
roentgen b75cab
  return (0);
roentgen b75cab
  }
roentgen b75cab
roentgen b75cab
/* pgwidth and pgheight specify page width and height in inches from -h and -w flags
roentgen b75cab
 * lm and bm are the LeftMargin and BottomMargin in inches
roentgen b75cab
 * center causes the image to be centered on the page if the paper size is
roentgen b75cab
 * larger than the image size
roentgen b75cab
 * returns the sequence number of the page processed or -1 on error
roentgen b75cab
 */
roentgen b75cab
roentgen b75cab
int TIFF2PS(FILE* fd, TIFF* tif, double pgwidth, double pgheight, double lm, double bm, int center)
roentgen b75cab
  {
roentgen b75cab
  uint32 pixwidth = 0, pixheight = 0;  /* Image width and height in pixels */
roentgen b75cab
  double ox = 0.0, oy = 0.0;  /* Offset from current Postscript origin */
roentgen b75cab
  double pswidth, psheight;   /* Original raw image width and height in points */
roentgen b75cab
  double view_width, view_height; /* Viewport width and height in points */
roentgen b75cab
  double scale = 1.0;
roentgen b75cab
  double left_offset = lm * PS_UNIT_SIZE;
roentgen b75cab
  double bottom_offset = bm * PS_UNIT_SIZE;
roentgen b75cab
  uint32 subfiletype;
roentgen b75cab
  uint16* sampleinfo;
roentgen b75cab
  static int npages = 0;
roentgen b75cab
roentgen b75cab
  if (!TIFFGetField(tif, TIFFTAG_XPOSITION, &ox))
roentgen b75cab
     ox = 0;
roentgen b75cab
  if (!TIFFGetField(tif, TIFFTAG_YPOSITION, &oy))
roentgen b75cab
     oy = 0;
roentgen b75cab
roentgen b75cab
  /* Consolidated all the tag information into one code segment, Richard Nolde */
roentgen b75cab
  do {
roentgen b75cab
     tf_numberstrips = TIFFNumberOfStrips(tif);
roentgen b75cab
     TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &tf_rowsperstrip);
roentgen b75cab
     TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bitspersample);
roentgen b75cab
     TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
roentgen b75cab
     TIFFGetFieldDefaulted(tif, TIFFTAG_PLANARCONFIG, &planarconfiguration);
roentgen b75cab
     TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression);
roentgen b75cab
     TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES, &extrasamples, &sampleinfo);
roentgen b75cab
     alpha = (extrasamples == 1 && sampleinfo[0] == EXTRASAMPLE_ASSOCALPHA);
roentgen b75cab
     if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric))
roentgen b75cab
       {
roentgen b75cab
       switch (samplesperpixel - extrasamples)
roentgen b75cab
             {
roentgen b75cab
            case 1: if (isCCITTCompression(tif))
roentgen b75cab
                      photometric = PHOTOMETRIC_MINISWHITE;
roentgen b75cab
                    else
roentgen b75cab
                       photometric = PHOTOMETRIC_MINISBLACK;
roentgen b75cab
                    break;
roentgen b75cab
            case 3: photometric = PHOTOMETRIC_RGB;
roentgen b75cab
                    break;
roentgen b75cab
            case 4: photometric = PHOTOMETRIC_SEPARATED;
roentgen b75cab
                    break;
roentgen b75cab
            }
roentgen b75cab
       }
roentgen b75cab
roentgen b75cab
     /* Read image tags for width and height in pixels pixwidth, pixheight,
roentgen b75cab
      * and convert to points pswidth, psheight
roentgen b75cab
      */
roentgen b75cab
     setupPageState(tif, &pixwidth, &pixheight, &pswidth, &psheight);
roentgen b75cab
     view_width = pswidth;
roentgen b75cab
     view_height = psheight;
roentgen b75cab
roentgen b75cab
     if (get_viewport (pgwidth, pgheight, pswidth, psheight, &view_width, &view_height, rotation))
roentgen b75cab
       {
roentgen b75cab
       TIFFError("get_viewport", "Unable to set image viewport");
roentgen b75cab
       return (1);
roentgen b75cab
       }
roentgen b75cab
roentgen b75cab
     /* Write the Postscript file header with Bounding Box and Page Size definitions */
roentgen b75cab
     if (psStart(fd, npages, auto_rotate, &rotation, &scale, ox, oy,
roentgen b75cab
                pgwidth, pgheight, view_width, view_height, pswidth, psheight,
roentgen b75cab
                 left_offset, bottom_offset))
roentgen b75cab
       return (-1);
roentgen b75cab
roentgen b75cab
     if (checkImage(tif))  /* Aborts if unsupported image parameters */
roentgen b75cab
       {
roentgen b75cab
       tf_bytesperrow = TIFFScanlineSize(tif);
roentgen b75cab
roentgen b75cab
       /* Set viewport clipping and scaling options */
roentgen b75cab
       if ((maxPageHeight) || (maxPageWidth)  || (pgwidth != 0) || (pgheight != 0))
roentgen b75cab
         {
roentgen b75cab
        if ((maxPageHeight) || (maxPageWidth)) /* used -H or -W  option */
roentgen b75cab
           {
roentgen b75cab
          if (psMaskImage(fd, tif, rotation, center, &npages, pixwidth, pixheight,
roentgen b75cab
                          left_offset, bottom_offset, pgwidth, pgheight,
roentgen b75cab
                           pswidth, psheight, scale) < 0)
roentgen b75cab
            return (-1);
roentgen b75cab
          }
roentgen b75cab
         else  /* N.B. Setting maxPageHeight no longer sets pgheight */
roentgen b75cab
           {
roentgen b75cab
           if (pgwidth != 0 || pgheight != 0)
roentgen b75cab
             {
roentgen b75cab
             /* User did not specify a maxium page height or width using -H or -W flag
roentgen b75cab
              * but did use -h or -w flag to scale to a specific size page.
roentgen b75cab
              */
roentgen b75cab
             npages++;
roentgen b75cab
             fprintf(fd, "%%%%Page: %d %d\n", npages, npages);
roentgen b75cab
roentgen b75cab
             if (!generateEPSF && ( level2 || level3 ))
roentgen b75cab
               {
roentgen b75cab
              /* Write out the PageSize info for non EPS files */
roentgen b75cab
              if (psPageSize(fd, rotation, pgwidth, pgheight,
roentgen b75cab
                              view_width, view_height, pswidth, psheight))
roentgen b75cab
                return (-1);
roentgen b75cab
               }
roentgen b75cab
             fprintf(fd, "gsave\n");
roentgen b75cab
             fprintf(fd, "100 dict begin\n");
roentgen b75cab
             if (psScaleImage(fd, scale, rotation, center, view_width, view_height,
roentgen b75cab
                              pswidth, psheight, left_offset, bottom_offset))
roentgen b75cab
              return (-1);
roentgen b75cab
roentgen b75cab
             PSpage(fd, tif, pixwidth, pixheight);
roentgen b75cab
             fprintf(fd, "end\n");
roentgen b75cab
             fprintf(fd, "grestore\n");
roentgen b75cab
             fprintf(fd, "showpage\n");
roentgen b75cab
            }
roentgen b75cab
          }
roentgen b75cab
        }
roentgen b75cab
       else  /* Simple rotation: user did not use -H, -W, -h or -w */
roentgen b75cab
         {
roentgen b75cab
         npages++;
roentgen b75cab
         fprintf(fd, "%%%%Page: %d %d\n", npages, npages);
roentgen b75cab
roentgen b75cab
         if (!generateEPSF && ( level2 || level3 ))
roentgen b75cab
           {
roentgen b75cab
          /* Write out the PageSize info for non EPS files */
roentgen b75cab
          if (psPageSize(fd, rotation, pgwidth, pgheight,
roentgen b75cab
                          view_width, view_height, pswidth, psheight))
roentgen b75cab
           return (-1);
roentgen b75cab
         }
roentgen b75cab
         fprintf(fd, "gsave\n");
roentgen b75cab
         fprintf(fd, "100 dict begin\n");
roentgen b75cab
        if (psRotateImage(fd, rotation, pswidth, psheight, left_offset, bottom_offset))
roentgen b75cab
           return (-1);
roentgen b75cab
roentgen b75cab
         PSpage(fd, tif, pixwidth, pixheight);
roentgen b75cab
         fprintf(fd, "end\n");
roentgen b75cab
         fprintf(fd, "grestore\n");
roentgen b75cab
         fprintf(fd, "showpage\n");
roentgen b75cab
         }
roentgen b75cab
       }
roentgen b75cab
  if (generateEPSF)
roentgen b75cab
    break;
roentgen b75cab
  TIFFGetFieldDefaulted(tif, TIFFTAG_SUBFILETYPE, &subfiletype);
roentgen b75cab
  } while (((subfiletype & FILETYPE_PAGE) || printAll) && TIFFReadDirectory(tif));
roentgen b75cab
roentgen b75cab
return(npages);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
static char DuplexPreamble[] = "\
roentgen b75cab
%%BeginFeature: *Duplex True\n\
roentgen b75cab
systemdict begin\n\
roentgen b75cab
  /languagelevel where { pop languagelevel } { 1 } ifelse\n\
roentgen b75cab
  2 ge { 1 dict dup /Duplex true put setpagedevice }\n\
roentgen b75cab
  { statusdict /setduplex known { statusdict begin setduplex true end } if\n\
roentgen b75cab
  } ifelse\n\
roentgen b75cab
end\n\
roentgen b75cab
%%EndFeature\n\
roentgen b75cab
";
roentgen b75cab
roentgen b75cab
static char TumblePreamble[] = "\
roentgen b75cab
%%BeginFeature: *Tumble True\n\
roentgen b75cab
systemdict begin\n\
roentgen b75cab
  /languagelevel where { pop languagelevel } { 1 } ifelse\n\
roentgen b75cab
  2 ge { 1 dict dup /Tumble true put setpagedevice }\n\
roentgen b75cab
  { statusdict /settumble known { statusdict begin true settumble end } if\n\
roentgen b75cab
  } ifelse\n\
roentgen b75cab
end\n\
roentgen b75cab
%%EndFeature\n\
roentgen b75cab
";
roentgen b75cab
roentgen b75cab
static char AvoidDeadZonePreamble[] = "\
roentgen b75cab
gsave newpath clippath pathbbox grestore\n\
roentgen b75cab
  4 2 roll 2 copy translate\n\
roentgen b75cab
  exch 3 1 roll sub 3 1 roll sub exch\n\
roentgen b75cab
  currentpagedevice /PageSize get aload pop\n\
roentgen b75cab
  exch 3 1 roll div 3 1 roll div abs exch abs\n\
roentgen b75cab
  2 copy gt { exch } if pop\n\
roentgen b75cab
  dup 1 lt { dup scale } { pop } ifelse\n\
roentgen b75cab
";
roentgen b75cab
roentgen b75cab
void
roentgen b75cab
PSHead(FILE *fd, double pagewidth, double pageheight, double xoff, double yoff)
roentgen b75cab
{
roentgen b75cab
	time_t t;
roentgen b75cab
roentgen b75cab
	t = time(0);
roentgen b75cab
	fprintf(fd, "%%!PS-Adobe-3.0%s\n", generateEPSF ? " EPSF-3.0" : "");
roentgen b75cab
	fprintf(fd, "%%%%Creator: %s\n", creator ? creator : "tiff2ps");
roentgen b75cab
        fprintf(fd, "%%%%Title: %s\n", title ? title : filename);
roentgen b75cab
	fprintf(fd, "%%%%CreationDate: %s", ctime(&t));
roentgen b75cab
	fprintf(fd, "%%%%DocumentData: Clean7Bit\n");
roentgen b75cab
	/* NB: should use PageBoundingBox for each page instead of BoundingBox *
roentgen b75cab
         * PageBoundingBox DSC added in PSPageSize function, R Nolde 09-01-2010
roentgen b75cab
         */
roentgen b75cab
	fprintf(fd, "%%%%Origin: %ld %ld\n", (long) xoff, (long) yoff);
roentgen b75cab
        fprintf(fd, "%%%%BoundingBox: 0 0 %ld %ld\n",
roentgen b75cab
	       (long) ceil(pagewidth), (long) ceil(pageheight));
roentgen b75cab
roentgen b75cab
	fprintf(fd, "%%%%LanguageLevel: %d\n", (level3 ? 3 : (level2 ? 2 : 1)));
roentgen b75cab
        if (generateEPSF == TRUE)
roentgen b75cab
	  fprintf(fd, "%%%%Pages: 1 1\n");
roentgen b75cab
        else
roentgen b75cab
	  fprintf(fd, "%%%%Pages: (atend)\n");
roentgen b75cab
	fprintf(fd, "%%%%EndComments\n");
roentgen b75cab
        if (generateEPSF == FALSE)
roentgen b75cab
          {
roentgen b75cab
  	  fprintf(fd, "%%%%BeginSetup\n");
roentgen b75cab
	  if (PSduplex)
roentgen b75cab
		fprintf(fd, "%s", DuplexPreamble);
roentgen b75cab
	  if (PStumble)
roentgen b75cab
		fprintf(fd, "%s", TumblePreamble);
roentgen b75cab
	  if (PSavoiddeadzone && (level2 || level3))
roentgen b75cab
		fprintf(fd, "%s", AvoidDeadZonePreamble);
roentgen b75cab
	  fprintf(fd, "%%%%EndSetup\n");
roentgen b75cab
	  }
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
void
roentgen b75cab
PSTail(FILE *fd, int npages)
roentgen b75cab
{
roentgen b75cab
	fprintf(fd, "%%%%Trailer\n");
roentgen b75cab
        if (generateEPSF == FALSE)
roentgen b75cab
	  fprintf(fd, "%%%%Pages: %d\n", npages);
roentgen b75cab
	fprintf(fd, "%%%%EOF\n");
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
static int
roentgen b75cab
checkcmap(TIFF* tif, int n, uint16* r, uint16* g, uint16* b)
roentgen b75cab
{
roentgen b75cab
	(void) tif;
roentgen b75cab
	while (n-- > 0)
roentgen b75cab
		if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256)
roentgen b75cab
			return (16);
roentgen b75cab
	TIFFWarning(filename, "Assuming 8-bit colormap");
roentgen b75cab
	return (8);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
static void
roentgen b75cab
PS_Lvl2colorspace(FILE* fd, TIFF* tif)
roentgen b75cab
{
roentgen b75cab
	uint16 *rmap, *gmap, *bmap;
roentgen b75cab
	int i, num_colors;
roentgen b75cab
	const char * colorspace_p;
roentgen b75cab
roentgen b75cab
	switch ( photometric )
roentgen b75cab
	{
roentgen b75cab
	case PHOTOMETRIC_SEPARATED:
roentgen b75cab
		colorspace_p = "CMYK";
roentgen b75cab
		break;
roentgen b75cab
roentgen b75cab
	case PHOTOMETRIC_RGB:
roentgen b75cab
		colorspace_p = "RGB";
roentgen b75cab
		break;
roentgen b75cab
roentgen b75cab
	default:
roentgen b75cab
		colorspace_p = "Gray";
roentgen b75cab
	}
roentgen b75cab
roentgen b75cab
	/*
roentgen b75cab
	 * Set up PostScript Level 2 colorspace according to
roentgen b75cab
	 * section 4.8 in the PostScript refenence manual.
roentgen b75cab
	 */
roentgen b75cab
	fputs("% PostScript Level 2 only.\n", fd);
roentgen b75cab
	if (photometric != PHOTOMETRIC_PALETTE) {
roentgen b75cab
		if (photometric == PHOTOMETRIC_YCBCR) {
roentgen b75cab
		    /* MORE CODE HERE */
roentgen b75cab
		}
roentgen b75cab
		fprintf(fd, "/Device%s setcolorspace\n", colorspace_p );
roentgen b75cab
		return;
roentgen b75cab
	}
roentgen b75cab
roentgen b75cab
	/*
roentgen b75cab
	 * Set up an indexed/palette colorspace
roentgen b75cab
	 */
roentgen b75cab
	num_colors = (1 << bitspersample);
roentgen b75cab
	if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) {
roentgen b75cab
		TIFFError(filename,
roentgen b75cab
			"Palette image w/o \"Colormap\" tag");
roentgen b75cab
		return;
roentgen b75cab
	}
roentgen b75cab
	if (checkcmap(tif, num_colors, rmap, gmap, bmap) == 16) {
roentgen b75cab
		/*
roentgen b75cab
		 * Convert colormap to 8-bits values.
roentgen b75cab
		 */
roentgen b75cab
#define	CVT(x)		(((x) * 255) / ((1L<<16)-1))
roentgen b75cab
		for (i = 0; i < num_colors; i++) {
roentgen b75cab
			rmap[i] = CVT(rmap[i]);
roentgen b75cab
			gmap[i] = CVT(gmap[i]);
roentgen b75cab
			bmap[i] = CVT(bmap[i]);
roentgen b75cab
		}
roentgen b75cab
#undef CVT
roentgen b75cab
	}
roentgen b75cab
	fprintf(fd, "[ /Indexed /DeviceRGB %d", num_colors - 1);
roentgen b75cab
	if (ascii85) {
roentgen b75cab
		Ascii85Init();
roentgen b75cab
		fputs("\n<~", fd);
roentgen b75cab
		ascii85breaklen -= 2;
roentgen b75cab
	} else
roentgen b75cab
		fputs(" <", fd);
roentgen b75cab
	for (i = 0; i < num_colors; i++) {
roentgen b75cab
		if (ascii85) {
roentgen b75cab
			Ascii85Put((unsigned char)rmap[i], fd);
roentgen b75cab
			Ascii85Put((unsigned char)gmap[i], fd);
roentgen b75cab
			Ascii85Put((unsigned char)bmap[i], fd);
roentgen b75cab
		} else {
roentgen b75cab
			fputs((i % 8) ? " " : "\n  ", fd);
roentgen b75cab
			fprintf(fd, "%02x%02x%02x",
roentgen b75cab
			    rmap[i], gmap[i], bmap[i]);
roentgen b75cab
		}
roentgen b75cab
	}
roentgen b75cab
	if (ascii85)
roentgen b75cab
		Ascii85Flush(fd);
roentgen b75cab
	else
roentgen b75cab
		fputs(">\n", fd);
roentgen b75cab
	fputs("] setcolorspace\n", fd);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
static int
roentgen b75cab
PS_Lvl2ImageDict(FILE* fd, TIFF* tif, uint32 w, uint32 h)
roentgen b75cab
{
roentgen b75cab
	int use_rawdata;
roentgen b75cab
	uint32 tile_width, tile_height;
roentgen b75cab
	uint16 predictor, minsamplevalue, maxsamplevalue;
roentgen b75cab
	int repeat_count;
roentgen b75cab
	char im_h[64], im_x[64], im_y[64];
roentgen b75cab
	char * imageOp = "image";
roentgen b75cab
roentgen b75cab
	if ( useImagemask && (bitspersample == 1) )
roentgen b75cab
		imageOp = "imagemask";
roentgen b75cab
roentgen b75cab
	(void)strcpy(im_x, "0");
roentgen b75cab
	(void)sprintf(im_y, "%lu", (long) h);
roentgen b75cab
	(void)sprintf(im_h, "%lu", (long) h);
roentgen b75cab
	tile_width = w;
roentgen b75cab
	tile_height = h;
roentgen b75cab
	if (TIFFIsTiled(tif)) {
roentgen b75cab
		repeat_count = TIFFNumberOfTiles(tif);
roentgen b75cab
		TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tile_width);
roentgen b75cab
		TIFFGetField(tif, TIFFTAG_TILELENGTH, &tile_height);
roentgen b75cab
		if (tile_width > w || tile_height > h ||
roentgen b75cab
		    (w % tile_width) != 0 || (h % tile_height != 0)) {
roentgen b75cab
			/*
roentgen b75cab
			 * The tiles does not fit image width and height.
roentgen b75cab
			 * Set up a clip rectangle for the image unit square.
roentgen b75cab
			 */
roentgen b75cab
			fputs("0 0 1 1 rectclip\n", fd);
roentgen b75cab
		}
roentgen b75cab
		if (tile_width < w) {
roentgen b75cab
			fputs("/im_x 0 def\n", fd);
roentgen b75cab
			(void)strcpy(im_x, "im_x neg");
roentgen b75cab
		}
roentgen b75cab
		if (tile_height < h) {
roentgen b75cab
			fputs("/im_y 0 def\n", fd);
roentgen b75cab
			(void)sprintf(im_y, "%lu im_y sub", (unsigned long) h);
roentgen b75cab
		}
roentgen b75cab
	} else {
roentgen b75cab
		repeat_count = tf_numberstrips;
roentgen b75cab
		tile_height = tf_rowsperstrip;
roentgen b75cab
		if (tile_height > h)
roentgen b75cab
			tile_height = h;
roentgen b75cab
		if (repeat_count > 1) {
roentgen b75cab
			fputs("/im_y 0 def\n", fd);
roentgen b75cab
			fprintf(fd, "/im_h %lu def\n",
roentgen b75cab
			    (unsigned long) tile_height);
roentgen b75cab
			(void)strcpy(im_h, "im_h");
roentgen b75cab
			(void)sprintf(im_y, "%lu im_y sub", (unsigned long) h);
roentgen b75cab
		}
roentgen b75cab
	}
roentgen b75cab
roentgen b75cab
	/*
roentgen b75cab
	 * Output start of exec block
roentgen b75cab
	 */
roentgen b75cab
	fputs("{ % exec\n", fd);
roentgen b75cab
roentgen b75cab
	if (repeat_count > 1)
roentgen b75cab
		fprintf(fd, "%d { %% repeat\n", repeat_count);
roentgen b75cab
roentgen b75cab
	/*
roentgen b75cab
	 * Output filter options and image dictionary.
roentgen b75cab
	 */
roentgen b75cab
	if (ascii85)
roentgen b75cab
		fputs(" /im_stream currentfile /ASCII85Decode filter def\n",
roentgen b75cab
		    fd);
roentgen b75cab
	fputs(" <<\n", fd);
roentgen b75cab
	fputs("  /ImageType 1\n", fd);
roentgen b75cab
	fprintf(fd, "  /Width %lu\n", (unsigned long) tile_width);
roentgen b75cab
	/*
roentgen b75cab
	 * Workaround for some software that may crash when last strip
roentgen b75cab
	 * of image contains fewer number of scanlines than specified
roentgen b75cab
	 * by the `/Height' variable. So for stripped images with multiple
roentgen b75cab
	 * strips we will set `/Height' as `im_h', because one is 
roentgen b75cab
	 * recalculated for each strip - including the (smaller) final strip.
roentgen b75cab
	 * For tiled images and images with only one strip `/Height' will
roentgen b75cab
	 * contain number of scanlines in tile (or image height in case of
roentgen b75cab
	 * one-stripped image).
roentgen b75cab
	 */
roentgen b75cab
	if (TIFFIsTiled(tif) || tf_numberstrips == 1)
roentgen b75cab
		fprintf(fd, "  /Height %lu\n", (unsigned long) tile_height);
roentgen b75cab
	else
roentgen b75cab
		fprintf(fd, "  /Height im_h\n");
roentgen b75cab
	
roentgen b75cab
	if (planarconfiguration == PLANARCONFIG_SEPARATE && samplesperpixel > 1)
roentgen b75cab
		fputs("  /MultipleDataSources true\n", fd);
roentgen b75cab
	fprintf(fd, "  /ImageMatrix [ %lu 0 0 %ld %s %s ]\n",
roentgen b75cab
	    (unsigned long) w, - (long)h, im_x, im_y);
roentgen b75cab
	fprintf(fd, "  /BitsPerComponent %d\n", bitspersample);
roentgen b75cab
	fprintf(fd, "  /Interpolate %s\n", interpolate ? "true" : "false");
roentgen b75cab
roentgen b75cab
	switch (samplesperpixel - extrasamples) {
roentgen b75cab
	case 1:
roentgen b75cab
		switch (photometric) {
roentgen b75cab
		case PHOTOMETRIC_MINISBLACK:
roentgen b75cab
			fputs("  /Decode [0 1]\n", fd);
roentgen b75cab
			break;
roentgen b75cab
		case PHOTOMETRIC_MINISWHITE:
roentgen b75cab
			switch (compression) {
roentgen b75cab
			case COMPRESSION_CCITTRLE:
roentgen b75cab
			case COMPRESSION_CCITTRLEW:
roentgen b75cab
			case COMPRESSION_CCITTFAX3:
roentgen b75cab
			case COMPRESSION_CCITTFAX4:
roentgen b75cab
				/*
roentgen b75cab
				 * Manage inverting with /Blackis1 flag
roentgen b75cab
				 * since there migth be uncompressed parts
roentgen b75cab
				 */
roentgen b75cab
				fputs("  /Decode [0 1]\n", fd);
roentgen b75cab
				break;
roentgen b75cab
			default:
roentgen b75cab
				/*
roentgen b75cab
				 * ERROR...
roentgen b75cab
				 */
roentgen b75cab
				fputs("  /Decode [1 0]\n", fd);
roentgen b75cab
				break;
roentgen b75cab
			}
roentgen b75cab
			break;
roentgen b75cab
		case PHOTOMETRIC_PALETTE:
roentgen b75cab
			TIFFGetFieldDefaulted(tif, TIFFTAG_MINSAMPLEVALUE,
roentgen b75cab
			    &minsamplevalue);
roentgen b75cab
			TIFFGetFieldDefaulted(tif, TIFFTAG_MAXSAMPLEVALUE,
roentgen b75cab
			    &maxsamplevalue);
roentgen b75cab
			fprintf(fd, "  /Decode [%u %u]\n",
roentgen b75cab
				    minsamplevalue, maxsamplevalue);
roentgen b75cab
			break;
roentgen b75cab
		default:
roentgen b75cab
			/*
roentgen b75cab
			 * ERROR ?
roentgen b75cab
			 */
roentgen b75cab
			fputs("  /Decode [0 1]\n", fd);
roentgen b75cab
			break;
roentgen b75cab
		}
roentgen b75cab
		break;
roentgen b75cab
	case 3:
roentgen b75cab
		switch (photometric) {
roentgen b75cab
		case PHOTOMETRIC_RGB:
roentgen b75cab
			fputs("  /Decode [0 1 0 1 0 1]\n", fd);
roentgen b75cab
			break;
roentgen b75cab
		case PHOTOMETRIC_MINISWHITE:
roentgen b75cab
		case PHOTOMETRIC_MINISBLACK:
roentgen b75cab
		default:
roentgen b75cab
			/*
roentgen b75cab
			 * ERROR??
roentgen b75cab
			 */
roentgen b75cab
			fputs("  /Decode [0 1 0 1 0 1]\n", fd);
roentgen b75cab
			break;
roentgen b75cab
		}
roentgen b75cab
		break;
roentgen b75cab
	case 4:
roentgen b75cab
		/*
roentgen b75cab
		 * ERROR??
roentgen b75cab
		 */
roentgen b75cab
		fputs("  /Decode [0 1 0 1 0 1 0 1]\n", fd);
roentgen b75cab
		break;
roentgen b75cab
	}
roentgen b75cab
	fputs("  /DataSource", fd);
roentgen b75cab
	if (planarconfiguration == PLANARCONFIG_SEPARATE &&
roentgen b75cab
	    samplesperpixel > 1)
roentgen b75cab
		fputs(" [", fd);
roentgen b75cab
	if (ascii85)
roentgen b75cab
		fputs(" im_stream", fd);
roentgen b75cab
	else
roentgen b75cab
		fputs(" currentfile /ASCIIHexDecode filter", fd);
roentgen b75cab
roentgen b75cab
	use_rawdata = TRUE;
roentgen b75cab
	switch (compression) {
roentgen b75cab
	case COMPRESSION_NONE:		/* 1: uncompressed */
roentgen b75cab
		break;
roentgen b75cab
	case COMPRESSION_CCITTRLE:	/* 2: CCITT modified Huffman RLE */
roentgen b75cab
	case COMPRESSION_CCITTRLEW:	/* 32771: #1 w/ word alignment */
roentgen b75cab
	case COMPRESSION_CCITTFAX3:	/* 3: CCITT Group 3 fax encoding */
roentgen b75cab
	case COMPRESSION_CCITTFAX4:	/* 4: CCITT Group 4 fax encoding */
roentgen b75cab
		fputs("\n\t<<\n", fd);
roentgen b75cab
		if (compression == COMPRESSION_CCITTFAX3) {
roentgen b75cab
			uint32 g3_options;
roentgen b75cab
roentgen b75cab
			fputs("\t /EndOfLine true\n", fd);
roentgen b75cab
			fputs("\t /EndOfBlock false\n", fd);
roentgen b75cab
			if (!TIFFGetField(tif, TIFFTAG_GROUP3OPTIONS,
roentgen b75cab
					    &g3_options))
roentgen b75cab
				g3_options = 0;
roentgen b75cab
			if (g3_options & GROUP3OPT_2DENCODING)
roentgen b75cab
				fprintf(fd, "\t /K %s\n", im_h);
roentgen b75cab
			if (g3_options & GROUP3OPT_UNCOMPRESSED)
roentgen b75cab
				fputs("\t /Uncompressed true\n", fd);
roentgen b75cab
			if (g3_options & GROUP3OPT_FILLBITS)
roentgen b75cab
				fputs("\t /EncodedByteAlign true\n", fd);
roentgen b75cab
		}
roentgen b75cab
		if (compression == COMPRESSION_CCITTFAX4) {
roentgen b75cab
			uint32 g4_options;
roentgen b75cab
roentgen b75cab
			fputs("\t /K -1\n", fd);
roentgen b75cab
			TIFFGetFieldDefaulted(tif, TIFFTAG_GROUP4OPTIONS,
roentgen b75cab
					       &g4_options);
roentgen b75cab
			if (g4_options & GROUP4OPT_UNCOMPRESSED)
roentgen b75cab
				fputs("\t /Uncompressed true\n", fd);
roentgen b75cab
		}
roentgen b75cab
		if (!(tile_width == w && w == 1728U))
roentgen b75cab
			fprintf(fd, "\t /Columns %lu\n",
roentgen b75cab
			    (unsigned long) tile_width);
roentgen b75cab
		fprintf(fd, "\t /Rows %s\n", im_h);
roentgen b75cab
		if (compression == COMPRESSION_CCITTRLE ||
roentgen b75cab
		    compression == COMPRESSION_CCITTRLEW) {
roentgen b75cab
			fputs("\t /EncodedByteAlign true\n", fd);
roentgen b75cab
			fputs("\t /EndOfBlock false\n", fd);
roentgen b75cab
		}
roentgen b75cab
		if (photometric == PHOTOMETRIC_MINISBLACK)
roentgen b75cab
			fputs("\t /BlackIs1 true\n", fd);
roentgen b75cab
		fprintf(fd, "\t>> /CCITTFaxDecode filter");
roentgen b75cab
		break;
roentgen b75cab
	case COMPRESSION_LZW:	/* 5: Lempel-Ziv & Welch */
roentgen b75cab
		TIFFGetFieldDefaulted(tif, TIFFTAG_PREDICTOR, &predictor);
roentgen b75cab
		if (predictor == 2) {
roentgen b75cab
			fputs("\n\t<<\n", fd);
roentgen b75cab
			fprintf(fd, "\t /Predictor %u\n", predictor);
roentgen b75cab
			fprintf(fd, "\t /Columns %lu\n",
roentgen b75cab
			    (unsigned long) tile_width);
roentgen b75cab
			fprintf(fd, "\t /Colors %u\n", samplesperpixel);
roentgen b75cab
			fprintf(fd, "\t /BitsPerComponent %u\n",
roentgen b75cab
			    bitspersample);
roentgen b75cab
			fputs("\t>>", fd);
roentgen b75cab
		}
roentgen b75cab
		fputs(" /LZWDecode filter", fd);
roentgen b75cab
		break;
roentgen b75cab
	case COMPRESSION_DEFLATE:	/* 5: ZIP */
roentgen b75cab
	case COMPRESSION_ADOBE_DEFLATE:
roentgen b75cab
		if ( level3 ) {
roentgen b75cab
			 TIFFGetFieldDefaulted(tif, TIFFTAG_PREDICTOR, &predictor);
roentgen b75cab
			 if (predictor > 1) {
roentgen b75cab
				fprintf(fd, "\t %% PostScript Level 3 only.");
roentgen b75cab
				fputs("\n\t<<\n", fd);
roentgen b75cab
				fprintf(fd, "\t /Predictor %u\n", predictor);
roentgen b75cab
				fprintf(fd, "\t /Columns %lu\n",
roentgen b75cab
					(unsigned long) tile_width);
roentgen b75cab
				fprintf(fd, "\t /Colors %u\n", samplesperpixel);
roentgen b75cab
					fprintf(fd, "\t /BitsPerComponent %u\n",
roentgen b75cab
					bitspersample);
roentgen b75cab
				fputs("\t>>", fd);
roentgen b75cab
			 }
roentgen b75cab
			 fputs(" /FlateDecode filter", fd);
roentgen b75cab
		} else {
roentgen b75cab
			use_rawdata = FALSE ;
roentgen b75cab
		}
roentgen b75cab
		break;
roentgen b75cab
	case COMPRESSION_PACKBITS:	/* 32773: Macintosh RLE */
roentgen b75cab
		fputs(" /RunLengthDecode filter", fd);
roentgen b75cab
		use_rawdata = TRUE;
roentgen b75cab
	    break;
roentgen b75cab
	case COMPRESSION_OJPEG:		/* 6: !6.0 JPEG */
roentgen b75cab
	case COMPRESSION_JPEG:		/* 7: %JPEG DCT compression */
roentgen b75cab
#ifdef notdef
roentgen b75cab
		/*
roentgen b75cab
		 * Code not tested yet
roentgen b75cab
		 */
roentgen b75cab
		fputs(" /DCTDecode filter", fd);
roentgen b75cab
		use_rawdata = TRUE;
roentgen b75cab
#else
roentgen b75cab
		use_rawdata = FALSE;
roentgen b75cab
#endif
roentgen b75cab
		break;
roentgen b75cab
	case COMPRESSION_NEXT:		/* 32766: NeXT 2-bit RLE */
roentgen b75cab
	case COMPRESSION_THUNDERSCAN:	/* 32809: ThunderScan RLE */
roentgen b75cab
	case COMPRESSION_PIXARFILM:	/* 32908: Pixar companded 10bit LZW */
roentgen b75cab
	case COMPRESSION_JBIG:		/* 34661: ISO JBIG */
roentgen b75cab
		use_rawdata = FALSE;
roentgen b75cab
		break;
roentgen b75cab
	case COMPRESSION_SGILOG:	/* 34676: SGI LogL or LogLuv */
roentgen b75cab
	case COMPRESSION_SGILOG24:	/* 34677: SGI 24-bit LogLuv */
roentgen b75cab
		use_rawdata = FALSE;
roentgen b75cab
		break;
roentgen b75cab
	default:
roentgen b75cab
		/*
roentgen b75cab
		 * ERROR...
roentgen b75cab
		 */
roentgen b75cab
		use_rawdata = FALSE;
roentgen b75cab
		break;
roentgen b75cab
	}
roentgen b75cab
	if (planarconfiguration == PLANARCONFIG_SEPARATE &&
roentgen b75cab
	    samplesperpixel > 1) {
roentgen b75cab
		uint16 i;
roentgen b75cab
roentgen b75cab
		/*
roentgen b75cab
		 * NOTE: This code does not work yet...
roentgen b75cab
		 */
roentgen b75cab
		for (i = 1; i < samplesperpixel; i++)
roentgen b75cab
			fputs(" dup", fd);
roentgen b75cab
		fputs(" ]", fd);
roentgen b75cab
	}
roentgen b75cab
roentgen b75cab
	fprintf( fd, "\n >> %s\n", imageOp );
roentgen b75cab
	if (ascii85)
roentgen b75cab
		fputs(" im_stream status { im_stream flushfile } if\n", fd);
roentgen b75cab
	if (repeat_count > 1) {
roentgen b75cab
		if (tile_width < w) {
roentgen b75cab
			fprintf(fd, " /im_x im_x %lu add def\n",
roentgen b75cab
			    (unsigned long) tile_width);
roentgen b75cab
			if (tile_height < h) {
roentgen b75cab
				fprintf(fd, " im_x %lu ge {\n",
roentgen b75cab
				    (unsigned long) w);
roentgen b75cab
				fputs("  /im_x 0 def\n", fd);
roentgen b75cab
				fprintf(fd, " /im_y im_y %lu add def\n",
roentgen b75cab
				    (unsigned long) tile_height);
roentgen b75cab
				fputs(" } if\n", fd);
roentgen b75cab
			}
roentgen b75cab
		}
roentgen b75cab
		if (tile_height < h) {
roentgen b75cab
			if (tile_width >= w) {
roentgen b75cab
				fprintf(fd, " /im_y im_y %lu add def\n",
roentgen b75cab
				    (unsigned long) tile_height);
roentgen b75cab
				if (!TIFFIsTiled(tif)) {
roentgen b75cab
					fprintf(fd, " /im_h %lu im_y sub",
roentgen b75cab
					    (unsigned long) h);
roentgen b75cab
					fprintf(fd, " dup %lu gt { pop",
roentgen b75cab
					    (unsigned long) tile_height);
roentgen b75cab
					fprintf(fd, " %lu } if def\n",
roentgen b75cab
					    (unsigned long) tile_height);
roentgen b75cab
				}
roentgen b75cab
			}
roentgen b75cab
		}
roentgen b75cab
		fputs("} repeat\n", fd);
roentgen b75cab
	}
roentgen b75cab
	/*
roentgen b75cab
	 * End of exec function
roentgen b75cab
	 */
roentgen b75cab
	fputs("}\n", fd);
roentgen b75cab
roentgen b75cab
	return(use_rawdata);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
/* Flip the byte order of buffers with 16 bit samples */
roentgen b75cab
static void
roentgen b75cab
PS_FlipBytes(unsigned char* buf, tsize_t count)
roentgen b75cab
{
roentgen b75cab
	int i;
roentgen b75cab
	unsigned char temp;
roentgen b75cab
roentgen b75cab
	if (count <= 0 || bitspersample <= 8) {
roentgen b75cab
		return;
roentgen b75cab
	}
roentgen b75cab
roentgen b75cab
	count--;
roentgen b75cab
roentgen b75cab
	for (i = 0; i < count; i += 2) {
roentgen b75cab
		temp = buf[i];
roentgen b75cab
		buf[i] = buf[i + 1];
roentgen b75cab
		buf[i + 1] = temp;
roentgen b75cab
	}
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
#define MAXLINE		36
roentgen b75cab
roentgen b75cab
int
roentgen b75cab
PS_Lvl2page(FILE* fd, TIFF* tif, uint32 w, uint32 h)
roentgen b75cab
{
roentgen b75cab
	uint16 fillorder;
roentgen b75cab
	int use_rawdata, tiled_image, breaklen = MAXLINE;
roentgen b75cab
	uint32 chunk_no, num_chunks;
roentgen b75cab
        uint64 *bc;
roentgen b75cab
	unsigned char *buf_data, *cp;
roentgen b75cab
	tsize_t chunk_size, byte_count;
roentgen b75cab
roentgen b75cab
#if defined( EXP_ASCII85ENCODER )
roentgen b75cab
	tsize_t			ascii85_l;	/* Length, in bytes, of ascii85_p[] data */
roentgen b75cab
	uint8		*	ascii85_p = 0;	/* Holds ASCII85 encoded data */
roentgen b75cab
#endif
roentgen b75cab
roentgen b75cab
	PS_Lvl2colorspace(fd, tif);
roentgen b75cab
	use_rawdata = PS_Lvl2ImageDict(fd, tif, w, h);
roentgen b75cab
roentgen b75cab
/* See http://bugzilla.remotesensing.org/show_bug.cgi?id=80 */
roentgen b75cab
#ifdef ENABLE_BROKEN_BEGINENDDATA
roentgen b75cab
	fputs("%%BeginData:\n", fd);
roentgen b75cab
#endif
roentgen b75cab
	fputs("exec\n", fd);
roentgen b75cab
roentgen b75cab
	tiled_image = TIFFIsTiled(tif);
roentgen b75cab
	if (tiled_image) {
roentgen b75cab
		num_chunks = TIFFNumberOfTiles(tif);
roentgen b75cab
		TIFFGetField(tif, TIFFTAG_TILEBYTECOUNTS, &bc);
roentgen b75cab
	} else {
roentgen b75cab
		num_chunks = TIFFNumberOfStrips(tif);
roentgen b75cab
		TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &bc);
roentgen b75cab
	}
roentgen b75cab
roentgen b75cab
	if (use_rawdata) {
roentgen b75cab
		chunk_size = (tsize_t) bc[0];
roentgen b75cab
		for (chunk_no = 1; chunk_no < num_chunks; chunk_no++)
roentgen b75cab
			if ((tsize_t) bc[chunk_no] > chunk_size)
roentgen b75cab
				chunk_size = (tsize_t) bc[chunk_no];
roentgen b75cab
	} else {
roentgen b75cab
		if (tiled_image)
roentgen b75cab
			chunk_size = TIFFTileSize(tif);
roentgen b75cab
		else
roentgen b75cab
			chunk_size = TIFFStripSize(tif);
roentgen b75cab
	}
roentgen b75cab
	buf_data = (unsigned char *)_TIFFmalloc(chunk_size);
roentgen b75cab
	if (!buf_data) {
roentgen b75cab
		TIFFError(filename, "Can't alloc %lu bytes for %s.",
roentgen b75cab
			(unsigned long) chunk_size, tiled_image ? "tiles" : "strips");
roentgen b75cab
		return(FALSE);
roentgen b75cab
	}
roentgen b75cab
roentgen b75cab
#if defined( EXP_ASCII85ENCODER )
roentgen b75cab
	if ( ascii85 ) {
roentgen b75cab
	    /*
roentgen b75cab
	     * Allocate a buffer to hold the ASCII85 encoded data.  Note
roentgen b75cab
	     * that it is allocated with sufficient room to hold the
roentgen b75cab
	     * encoded data (5*chunk_size/4) plus the EOD marker (+8)
roentgen b75cab
	     * and formatting line breaks.  The line breaks are more
roentgen b75cab
	     * than taken care of by using 6*chunk_size/4 rather than
roentgen b75cab
	     * 5*chunk_size/4.
roentgen b75cab
	     */
roentgen b75cab
roentgen b75cab
	    ascii85_p = _TIFFmalloc( (chunk_size+(chunk_size/2)) + 8 );
roentgen b75cab
roentgen b75cab
	    if ( !ascii85_p ) {
roentgen b75cab
		_TIFFfree( buf_data );
roentgen b75cab
roentgen b75cab
		TIFFError( filename, "Cannot allocate ASCII85 encoding buffer." );
roentgen b75cab
		return ( FALSE );
roentgen b75cab
	    }
roentgen b75cab
	}
roentgen b75cab
#endif
roentgen b75cab
roentgen b75cab
	TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &fillorder);
roentgen b75cab
	for (chunk_no = 0; chunk_no < num_chunks; chunk_no++) {
roentgen b75cab
		if (ascii85)
roentgen b75cab
			Ascii85Init();
roentgen b75cab
		else
roentgen b75cab
			breaklen = MAXLINE;
roentgen b75cab
		if (use_rawdata) {
roentgen b75cab
			if (tiled_image)
roentgen b75cab
				byte_count = TIFFReadRawTile(tif, chunk_no,
roentgen b75cab
						  buf_data, chunk_size);
roentgen b75cab
			else
roentgen b75cab
				byte_count = TIFFReadRawStrip(tif, chunk_no,
roentgen b75cab
						  buf_data, chunk_size);
roentgen b75cab
			if (fillorder == FILLORDER_LSB2MSB)
roentgen b75cab
			    TIFFReverseBits(buf_data, byte_count);
roentgen b75cab
		} else {
roentgen b75cab
			if (tiled_image)
roentgen b75cab
				byte_count = TIFFReadEncodedTile(tif,
roentgen b75cab
						chunk_no, buf_data,
roentgen b75cab
						chunk_size);
roentgen b75cab
			else
roentgen b75cab
				byte_count = TIFFReadEncodedStrip(tif,
roentgen b75cab
						chunk_no, buf_data,
roentgen b75cab
						chunk_size);
roentgen b75cab
		}
roentgen b75cab
		if (byte_count < 0) {
roentgen b75cab
			TIFFError(filename, "Can't read %s %d.",
roentgen b75cab
				tiled_image ? "tile" : "strip", chunk_no);
roentgen b75cab
			if (ascii85)
roentgen b75cab
				Ascii85Put('\0', fd);
roentgen b75cab
		}
roentgen b75cab
		/*
roentgen b75cab
		 * for 16 bits, the two bytes must be most significant
roentgen b75cab
		 * byte first
roentgen b75cab
		 */
roentgen b75cab
		if (bitspersample == 16 && !TIFFIsBigEndian(tif)) {
roentgen b75cab
			PS_FlipBytes(buf_data, byte_count);
roentgen b75cab
		}
roentgen b75cab
		/*
roentgen b75cab
		 * For images with alpha, matte against a white background;
roentgen b75cab
		 * i.e. Cback * (1 - Aimage) where Cback = 1. We will fill the
roentgen b75cab
		 * lower part of the buffer with the modified values.
roentgen b75cab
		 *
roentgen b75cab
		 * XXX: needs better solution
roentgen b75cab
		 */
roentgen b75cab
		if (alpha) {
roentgen b75cab
			int adjust, i, j = 0;
roentgen b75cab
			int ncomps = samplesperpixel - extrasamples;
roentgen b75cab
			for (i = 0; i < byte_count; i+=samplesperpixel) {
roentgen b75cab
				adjust = 255 - buf_data[i + ncomps];
roentgen b75cab
				switch (ncomps) {
roentgen b75cab
					case 1:
roentgen b75cab
						buf_data[j++] = buf_data[i] + adjust;
roentgen b75cab
						break;
roentgen b75cab
					case 2:
roentgen b75cab
						buf_data[j++] = buf_data[i] + adjust;
roentgen b75cab
						buf_data[j++] = buf_data[i+1] + adjust;
roentgen b75cab
						break;
roentgen b75cab
					case 3:
roentgen b75cab
						buf_data[j++] = buf_data[i] + adjust;
roentgen b75cab
						buf_data[j++] = buf_data[i+1] + adjust;
roentgen b75cab
						buf_data[j++] = buf_data[i+2] + adjust;
roentgen b75cab
						break;
roentgen b75cab
				}
roentgen b75cab
			}
roentgen b75cab
			byte_count -= j;
roentgen b75cab
		}
roentgen b75cab
roentgen b75cab
		if (ascii85) {
roentgen b75cab
#if defined( EXP_ASCII85ENCODER )
roentgen b75cab
			ascii85_l = Ascii85EncodeBlock(ascii85_p, 1, buf_data, byte_count );
roentgen b75cab
roentgen b75cab
			if ( ascii85_l > 0 )
roentgen b75cab
				fwrite( ascii85_p, ascii85_l, 1, fd );
roentgen b75cab
#else
roentgen b75cab
			for (cp = buf_data; byte_count > 0; byte_count--)
roentgen b75cab
				Ascii85Put(*cp++, fd);
roentgen b75cab
#endif
roentgen b75cab
		}
roentgen b75cab
		else
roentgen b75cab
		{
roentgen b75cab
			for (cp = buf_data; byte_count > 0; byte_count--) {
roentgen b75cab
				putc(hex[((*cp)>>4)&0xf], fd);
roentgen b75cab
				putc(hex[(*cp)&0xf], fd);
roentgen b75cab
				cp++;
roentgen b75cab
roentgen b75cab
				if (--breaklen <= 0) {
roentgen b75cab
					putc('\n', fd);
roentgen b75cab
					breaklen = MAXLINE;
roentgen b75cab
				}
roentgen b75cab
			}
roentgen b75cab
		}
roentgen b75cab
roentgen b75cab
		if ( !ascii85 ) {
roentgen b75cab
			if ( level2 || level3 )
roentgen b75cab
				putc( '>', fd );
roentgen b75cab
			putc('\n', fd);
roentgen b75cab
		}
roentgen b75cab
#if !defined( EXP_ASCII85ENCODER )
roentgen b75cab
		else
roentgen b75cab
			Ascii85Flush(fd);
roentgen b75cab
#endif
roentgen b75cab
	}
roentgen b75cab
roentgen b75cab
#if defined( EXP_ASCII85ENCODER )
roentgen b75cab
	if ( ascii85_p )
roentgen b75cab
	    _TIFFfree( ascii85_p );
roentgen b75cab
#endif
roentgen b75cab
       
roentgen b75cab
	_TIFFfree(buf_data);
roentgen b75cab
#ifdef ENABLE_BROKEN_BEGINENDDATA
roentgen b75cab
	fputs("%%EndData\n", fd);
roentgen b75cab
#endif
roentgen b75cab
	return(TRUE);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
void
roentgen b75cab
PSpage(FILE* fd, TIFF* tif, uint32 w, uint32 h)
roentgen b75cab
{
roentgen b75cab
	char	*	imageOp = "image";
roentgen b75cab
roentgen b75cab
	if ( useImagemask && (bitspersample == 1) )
roentgen b75cab
		imageOp = "imagemask";
roentgen b75cab
roentgen b75cab
	if ((level2 || level3) && PS_Lvl2page(fd, tif, w, h))
roentgen b75cab
		return;
roentgen b75cab
	ps_bytesperrow = tf_bytesperrow - (extrasamples * bitspersample / 8)*w;
roentgen b75cab
	switch (photometric) {
roentgen b75cab
	case PHOTOMETRIC_RGB:
roentgen b75cab
		if (planarconfiguration == PLANARCONFIG_CONTIG) {
roentgen b75cab
			fprintf(fd, "%s", RGBcolorimage);
roentgen b75cab
			PSColorContigPreamble(fd, w, h, 3);
roentgen b75cab
			PSDataColorContig(fd, tif, w, h, 3);
roentgen b75cab
		} else {
roentgen b75cab
			PSColorSeparatePreamble(fd, w, h, 3);
roentgen b75cab
			PSDataColorSeparate(fd, tif, w, h, 3);
roentgen b75cab
		}
roentgen b75cab
		break;
roentgen b75cab
	case PHOTOMETRIC_SEPARATED:
roentgen b75cab
		/* XXX should emit CMYKcolorimage */
roentgen b75cab
		if (planarconfiguration == PLANARCONFIG_CONTIG) {
roentgen b75cab
			PSColorContigPreamble(fd, w, h, 4);
roentgen b75cab
			PSDataColorContig(fd, tif, w, h, 4);
roentgen b75cab
		} else {
roentgen b75cab
			PSColorSeparatePreamble(fd, w, h, 4);
roentgen b75cab
			PSDataColorSeparate(fd, tif, w, h, 4);
roentgen b75cab
		}
roentgen b75cab
		break;
roentgen b75cab
	case PHOTOMETRIC_PALETTE:
roentgen b75cab
		fprintf(fd, "%s", RGBcolorimage);
roentgen b75cab
		PhotoshopBanner(fd, w, h, 1, 3, "false 3 colorimage");
roentgen b75cab
		fprintf(fd, "/scanLine %ld string def\n",
roentgen b75cab
		    (long) ps_bytesperrow * 3L);
roentgen b75cab
		fprintf(fd, "%lu %lu 8\n",
roentgen b75cab
		    (unsigned long) w, (unsigned long) h);
roentgen b75cab
		fprintf(fd, "[%lu 0 0 -%lu 0 %lu]\n",
roentgen b75cab
		    (unsigned long) w, (unsigned long) h, (unsigned long) h);
roentgen b75cab
		fprintf(fd, "{currentfile scanLine readhexstring pop} bind\n");
roentgen b75cab
		fprintf(fd, "false 3 colorimage\n");
roentgen b75cab
		PSDataPalette(fd, tif, w, h);
roentgen b75cab
		break;
roentgen b75cab
	case PHOTOMETRIC_MINISBLACK:
roentgen b75cab
	case PHOTOMETRIC_MINISWHITE:
roentgen b75cab
		PhotoshopBanner(fd, w, h, 1, 1, imageOp);
roentgen b75cab
		fprintf(fd, "/scanLine %ld string def\n",
roentgen b75cab
		    (long) ps_bytesperrow);
roentgen b75cab
		fprintf(fd, "%lu %lu %d\n",
roentgen b75cab
		    (unsigned long) w, (unsigned long) h, bitspersample);
roentgen b75cab
		fprintf(fd, "[%lu 0 0 -%lu 0 %lu]\n",
roentgen b75cab
		    (unsigned long) w, (unsigned long) h, (unsigned long) h);
roentgen b75cab
		fprintf(fd,
roentgen b75cab
		    "{currentfile scanLine readhexstring pop} bind\n");
roentgen b75cab
		fprintf(fd, "%s\n", imageOp);
roentgen b75cab
		PSDataBW(fd, tif, w, h);
roentgen b75cab
		break;
roentgen b75cab
	}
roentgen b75cab
	putc('\n', fd);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
void
roentgen b75cab
PSColorContigPreamble(FILE* fd, uint32 w, uint32 h, int nc)
roentgen b75cab
{
roentgen b75cab
	ps_bytesperrow = nc * (tf_bytesperrow / samplesperpixel);
roentgen b75cab
	PhotoshopBanner(fd, w, h, 1, nc, "false %d colorimage");
roentgen b75cab
	fprintf(fd, "/line %ld string def\n", (long) ps_bytesperrow);
roentgen b75cab
	fprintf(fd, "%lu %lu %d\n",
roentgen b75cab
	    (unsigned long) w, (unsigned long) h, bitspersample);
roentgen b75cab
	fprintf(fd, "[%lu 0 0 -%lu 0 %lu]\n",
roentgen b75cab
	    (unsigned long) w, (unsigned long) h, (unsigned long) h);
roentgen b75cab
	fprintf(fd, "{currentfile line readhexstring pop} bind\n");
roentgen b75cab
	fprintf(fd, "false %d colorimage\n", nc);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
void
roentgen b75cab
PSColorSeparatePreamble(FILE* fd, uint32 w, uint32 h, int nc)
roentgen b75cab
{
roentgen b75cab
	int i;
roentgen b75cab
roentgen b75cab
	PhotoshopBanner(fd, w, h, ps_bytesperrow, nc, "true %d colorimage");
roentgen b75cab
	for (i = 0; i < nc; i++)
roentgen b75cab
		fprintf(fd, "/line%d %ld string def\n",
roentgen b75cab
		    i, (long) ps_bytesperrow);
roentgen b75cab
	fprintf(fd, "%lu %lu %d\n",
roentgen b75cab
	    (unsigned long) w, (unsigned long) h, bitspersample);
roentgen b75cab
	fprintf(fd, "[%lu 0 0 -%lu 0 %lu] \n",
roentgen b75cab
	    (unsigned long) w, (unsigned long) h, (unsigned long) h);
roentgen b75cab
	for (i = 0; i < nc; i++)
roentgen b75cab
		fprintf(fd, "{currentfile line%d readhexstring pop}bind\n", i);
roentgen b75cab
	fprintf(fd, "true %d colorimage\n", nc);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
#define	DOBREAK(len, howmany, fd) \
roentgen b75cab
	if (((len) -= (howmany)) <= 0) {	\
roentgen b75cab
		putc('\n', fd);			\
roentgen b75cab
		(len) = MAXLINE-(howmany);	\
roentgen b75cab
	}
roentgen b75cab
#define	PUTHEX(c,fd)	putc(hex[((c)>>4)&0xf],fd); putc(hex[(c)&0xf],fd)
roentgen b75cab
roentgen b75cab
void
roentgen b75cab
PSDataColorContig(FILE* fd, TIFF* tif, uint32 w, uint32 h, int nc)
roentgen b75cab
{
roentgen b75cab
	uint32 row;
roentgen b75cab
	int breaklen = MAXLINE, es = samplesperpixel - nc;
roentgen b75cab
	tsize_t cc;
roentgen b75cab
	unsigned char *tf_buf;
roentgen b75cab
	unsigned char *cp, c;
roentgen b75cab
roentgen b75cab
	(void) w;
roentgen b75cab
	tf_buf = (unsigned char *) _TIFFmalloc(tf_bytesperrow);
roentgen b75cab
	if (tf_buf == NULL) {
roentgen b75cab
		TIFFError(filename, "No space for scanline buffer");
roentgen b75cab
		return;
roentgen b75cab
	}
roentgen b75cab
	for (row = 0; row < h; row++) {
roentgen b75cab
		if (TIFFReadScanline(tif, tf_buf, row, 0) < 0)
roentgen b75cab
			break;
roentgen b75cab
		cp = tf_buf;
roentgen b75cab
		/*
roentgen b75cab
		 * for 16 bits, the two bytes must be most significant
roentgen b75cab
		 * byte first
roentgen b75cab
		 */
roentgen b75cab
		if (bitspersample == 16 && !HOST_BIGENDIAN) {
roentgen b75cab
			PS_FlipBytes(cp, tf_bytesperrow);
roentgen b75cab
		}
roentgen b75cab
		if (alpha) {
roentgen b75cab
			int adjust;
roentgen b75cab
			cc = 0;
roentgen b75cab
			for (; cc < tf_bytesperrow; cc += samplesperpixel) {
roentgen b75cab
				DOBREAK(breaklen, nc, fd);
roentgen b75cab
				/*
roentgen b75cab
				 * For images with alpha, matte against
roentgen b75cab
				 * a white background; i.e.
roentgen b75cab
				 *    Cback * (1 - Aimage)
roentgen b75cab
				 * where Cback = 1.
roentgen b75cab
				 */
roentgen b75cab
				adjust = 255 - cp[nc];
roentgen b75cab
				switch (nc) {
roentgen b75cab
				case 4: c = *cp++ + adjust; PUTHEX(c,fd);
roentgen b75cab
				case 3: c = *cp++ + adjust; PUTHEX(c,fd);
roentgen b75cab
				case 2: c = *cp++ + adjust; PUTHEX(c,fd);
roentgen b75cab
				case 1: c = *cp++ + adjust; PUTHEX(c,fd);
roentgen b75cab
				}
roentgen b75cab
				cp += es;
roentgen b75cab
			}
roentgen b75cab
		} else {
roentgen b75cab
			cc = 0;
roentgen b75cab
			for (; cc < tf_bytesperrow; cc += samplesperpixel) {
roentgen b75cab
				DOBREAK(breaklen, nc, fd);
roentgen b75cab
				switch (nc) {
roentgen b75cab
				case 4: c = *cp++; PUTHEX(c,fd);
roentgen b75cab
				case 3: c = *cp++; PUTHEX(c,fd);
roentgen b75cab
				case 2: c = *cp++; PUTHEX(c,fd);
roentgen b75cab
				case 1: c = *cp++; PUTHEX(c,fd);
roentgen b75cab
				}
roentgen b75cab
				cp += es;
roentgen b75cab
			}
roentgen b75cab
		}
roentgen b75cab
	}
roentgen b75cab
	_TIFFfree((char *) tf_buf);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
void
roentgen b75cab
PSDataColorSeparate(FILE* fd, TIFF* tif, uint32 w, uint32 h, int nc)
roentgen b75cab
{
roentgen b75cab
	uint32 row;
roentgen b75cab
	int breaklen = MAXLINE;
roentgen b75cab
	tsize_t cc;
roentgen b75cab
	tsample_t s, maxs;
roentgen b75cab
	unsigned char *tf_buf;
roentgen b75cab
	unsigned char *cp, c;
roentgen b75cab
roentgen b75cab
	(void) w;
roentgen b75cab
	tf_buf = (unsigned char *) _TIFFmalloc(tf_bytesperrow);
roentgen b75cab
	if (tf_buf == NULL) {
roentgen b75cab
		TIFFError(filename, "No space for scanline buffer");
roentgen b75cab
		return;
roentgen b75cab
	}
roentgen b75cab
	maxs = (samplesperpixel > nc ? nc : samplesperpixel);
roentgen b75cab
	for (row = 0; row < h; row++) {
roentgen b75cab
		for (s = 0; s < maxs; s++) {
roentgen b75cab
			if (TIFFReadScanline(tif, tf_buf, row, s) < 0)
roentgen b75cab
				break;
roentgen b75cab
			for (cp = tf_buf, cc = 0; cc < tf_bytesperrow; cc++) {
roentgen b75cab
				DOBREAK(breaklen, 1, fd);
roentgen b75cab
				c = *cp++;
roentgen b75cab
				PUTHEX(c,fd);
roentgen b75cab
			}
roentgen b75cab
		}
roentgen b75cab
	}
roentgen b75cab
	_TIFFfree((char *) tf_buf);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
#define	PUTRGBHEX(c,fd) \
roentgen b75cab
	PUTHEX(rmap[c],fd); PUTHEX(gmap[c],fd); PUTHEX(bmap[c],fd)
roentgen b75cab
roentgen b75cab
void
roentgen b75cab
PSDataPalette(FILE* fd, TIFF* tif, uint32 w, uint32 h)
roentgen b75cab
{
roentgen b75cab
	uint16 *rmap, *gmap, *bmap;
roentgen b75cab
	uint32 row;
roentgen b75cab
	int breaklen = MAXLINE, nc;
roentgen b75cab
	tsize_t cc;
roentgen b75cab
	unsigned char *tf_buf;
roentgen b75cab
	unsigned char *cp, c;
roentgen b75cab
roentgen b75cab
	(void) w;
roentgen b75cab
	if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) {
roentgen b75cab
		TIFFError(filename, "Palette image w/o \"Colormap\" tag");
roentgen b75cab
		return;
roentgen b75cab
	}
roentgen b75cab
	switch (bitspersample) {
roentgen b75cab
	case 8:	case 4: case 2: case 1:
roentgen b75cab
		break;
roentgen b75cab
	default:
roentgen b75cab
		TIFFError(filename, "Depth %d not supported", bitspersample);
roentgen b75cab
		return;
roentgen b75cab
	}
roentgen b75cab
	nc = 3 * (8 / bitspersample);
roentgen b75cab
	tf_buf = (unsigned char *) _TIFFmalloc(tf_bytesperrow);
roentgen b75cab
	if (tf_buf == NULL) {
roentgen b75cab
		TIFFError(filename, "No space for scanline buffer");
roentgen b75cab
		return;
roentgen b75cab
	}
roentgen b75cab
	if (checkcmap(tif, 1<
roentgen b75cab
		int i;
roentgen b75cab
#define	CVT(x)		((unsigned short) (((x) * 255) / ((1U<<16)-1)))
roentgen b75cab
		for (i = (1<<bitspersample)-1; i="">= 0; i--) {</bitspersample)-1;>
roentgen b75cab
			rmap[i] = CVT(rmap[i]);
roentgen b75cab
			gmap[i] = CVT(gmap[i]);
roentgen b75cab
			bmap[i] = CVT(bmap[i]);
roentgen b75cab
		}
roentgen b75cab
#undef CVT
roentgen b75cab
	}
roentgen b75cab
	for (row = 0; row < h; row++) {
roentgen b75cab
		if (TIFFReadScanline(tif, tf_buf, row, 0) < 0)
roentgen b75cab
			break;
roentgen b75cab
		for (cp = tf_buf, cc = 0; cc < tf_bytesperrow; cc++) {
roentgen b75cab
			DOBREAK(breaklen, nc, fd);
roentgen b75cab
			switch (bitspersample) {
roentgen b75cab
			case 8:
roentgen b75cab
				c = *cp++; PUTRGBHEX(c, fd);
roentgen b75cab
				break;
roentgen b75cab
			case 4:
roentgen b75cab
				c = *cp++; PUTRGBHEX(c&0xf, fd);
roentgen b75cab
				c >>= 4;   PUTRGBHEX(c, fd);
roentgen b75cab
				break;
roentgen b75cab
			case 2:
roentgen b75cab
				c = *cp++; PUTRGBHEX(c&0x3, fd);
roentgen b75cab
				c >>= 2;   PUTRGBHEX(c&0x3, fd);
roentgen b75cab
				c >>= 2;   PUTRGBHEX(c&0x3, fd);
roentgen b75cab
				c >>= 2;   PUTRGBHEX(c, fd);
roentgen b75cab
				break;
roentgen b75cab
			case 1:
roentgen b75cab
				c = *cp++; PUTRGBHEX(c&0x1, fd);
roentgen b75cab
				c >>= 1;   PUTRGBHEX(c&0x1, fd);
roentgen b75cab
				c >>= 1;   PUTRGBHEX(c&0x1, fd);
roentgen b75cab
				c >>= 1;   PUTRGBHEX(c&0x1, fd);
roentgen b75cab
				c >>= 1;   PUTRGBHEX(c&0x1, fd);
roentgen b75cab
				c >>= 1;   PUTRGBHEX(c&0x1, fd);
roentgen b75cab
				c >>= 1;   PUTRGBHEX(c&0x1, fd);
roentgen b75cab
				c >>= 1;   PUTRGBHEX(c, fd);
roentgen b75cab
				break;
roentgen b75cab
			}
roentgen b75cab
		}
roentgen b75cab
	}
roentgen b75cab
	_TIFFfree((char *) tf_buf);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
void
roentgen b75cab
PSDataBW(FILE* fd, TIFF* tif, uint32 w, uint32 h)
roentgen b75cab
{
roentgen b75cab
	int breaklen = MAXLINE;
roentgen b75cab
	unsigned char* tf_buf;
roentgen b75cab
	unsigned char* cp;
roentgen b75cab
	tsize_t stripsize = TIFFStripSize(tif);
roentgen b75cab
	tstrip_t s;
roentgen b75cab
roentgen b75cab
#if defined( EXP_ASCII85ENCODER )
roentgen b75cab
	tsize_t	ascii85_l;		/* Length, in bytes, of ascii85_p[] data */
roentgen b75cab
	uint8	*ascii85_p = 0;		/* Holds ASCII85 encoded data */
roentgen b75cab
#endif
roentgen b75cab
roentgen b75cab
	(void) w; (void) h;
roentgen b75cab
	tf_buf = (unsigned char *) _TIFFmalloc(stripsize);
roentgen b75cab
	if (tf_buf == NULL) {
roentgen b75cab
		TIFFError(filename, "No space for scanline buffer");
roentgen b75cab
		return;
roentgen b75cab
	}
roentgen b75cab
roentgen b75cab
	// FIXME
roentgen b75cab
	memset(tf_buf, 0, stripsize);
roentgen b75cab
roentgen b75cab
#if defined( EXP_ASCII85ENCODER )
roentgen b75cab
	if ( ascii85 ) {
roentgen b75cab
	    /*
roentgen b75cab
	     * Allocate a buffer to hold the ASCII85 encoded data.  Note
roentgen b75cab
	     * that it is allocated with sufficient room to hold the
roentgen b75cab
	     * encoded data (5*stripsize/4) plus the EOD marker (+8)
roentgen b75cab
	     * and formatting line breaks.  The line breaks are more
roentgen b75cab
	     * than taken care of by using 6*stripsize/4 rather than
roentgen b75cab
	     * 5*stripsize/4.
roentgen b75cab
	     */
roentgen b75cab
roentgen b75cab
	    ascii85_p = _TIFFmalloc( (stripsize+(stripsize/2)) + 8 );
roentgen b75cab
roentgen b75cab
	    if ( !ascii85_p ) {
roentgen b75cab
		_TIFFfree( tf_buf );
roentgen b75cab
roentgen b75cab
		TIFFError( filename, "Cannot allocate ASCII85 encoding buffer." );
roentgen b75cab
		return;
roentgen b75cab
	    }
roentgen b75cab
	}
roentgen b75cab
#endif
roentgen b75cab
roentgen b75cab
	if (ascii85)
roentgen b75cab
		Ascii85Init();
roentgen b75cab
roentgen b75cab
	for (s = 0; s < TIFFNumberOfStrips(tif); s++) {
roentgen b75cab
		tmsize_t cc = TIFFReadEncodedStrip(tif, s, tf_buf, stripsize);
roentgen b75cab
		if (cc < 0) {
roentgen b75cab
			TIFFError(filename, "Can't read strip");
roentgen b75cab
			break;
roentgen b75cab
		}
roentgen b75cab
		cp = tf_buf;
roentgen b75cab
		if (photometric == PHOTOMETRIC_MINISWHITE) {
roentgen b75cab
			for (cp += cc; --cp >= tf_buf;)
roentgen b75cab
				*cp = ~*cp;
roentgen b75cab
			cp++;
roentgen b75cab
		}
roentgen b75cab
		/*
roentgen b75cab
		 * for 16 bits, the two bytes must be most significant
roentgen b75cab
		 * byte first
roentgen b75cab
		 */
roentgen b75cab
		if (bitspersample == 16 && !HOST_BIGENDIAN) {
roentgen b75cab
			PS_FlipBytes(cp, cc);
roentgen b75cab
		}
roentgen b75cab
		if (ascii85) {
roentgen b75cab
#if defined( EXP_ASCII85ENCODER )
roentgen b75cab
			if (alpha) {
roentgen b75cab
				int adjust, i;
roentgen b75cab
				for (i = 0; i < cc; i+=2) {
roentgen b75cab
					adjust = 255 - cp[i + 1];
roentgen b75cab
				    cp[i / 2] = cp[i] + adjust;
roentgen b75cab
				}
roentgen b75cab
				cc /= 2;
roentgen b75cab
			}
roentgen b75cab
roentgen b75cab
			ascii85_l = Ascii85EncodeBlock( ascii85_p, 1, cp, cc );
roentgen b75cab
roentgen b75cab
			if ( ascii85_l > 0 )
roentgen b75cab
			    fwrite( ascii85_p, ascii85_l, 1, fd );
roentgen b75cab
#else
roentgen b75cab
			while (cc-- > 0)
roentgen b75cab
				Ascii85Put(*cp++, fd);
roentgen b75cab
#endif /* EXP_ASCII85_ENCODER */
roentgen b75cab
		} else {
roentgen b75cab
			unsigned char c;
roentgen b75cab
roentgen b75cab
			if (alpha) {
roentgen b75cab
				int adjust;
roentgen b75cab
				while (cc-- > 0) {
roentgen b75cab
					DOBREAK(breaklen, 1, fd);
roentgen b75cab
					/*
roentgen b75cab
					 * For images with alpha, matte against
roentgen b75cab
					 * a white background; i.e.
roentgen b75cab
					 *    Cback * (1 - Aimage)
roentgen b75cab
					 * where Cback = 1.
roentgen b75cab
					 */
roentgen b75cab
					adjust = 255 - cp[1];
roentgen b75cab
					c = *cp++ + adjust; PUTHEX(c,fd);
roentgen b75cab
					cp++, cc--;
roentgen b75cab
				}
roentgen b75cab
			} else {
roentgen b75cab
				while (cc-- > 0) {
roentgen b75cab
					c = *cp++;
roentgen b75cab
					DOBREAK(breaklen, 1, fd);
roentgen b75cab
					PUTHEX(c, fd);
roentgen b75cab
				}
roentgen b75cab
			}
roentgen b75cab
		}
roentgen b75cab
	}
roentgen b75cab
roentgen b75cab
	if ( !ascii85 )
roentgen b75cab
	{
roentgen b75cab
	    if ( level2 || level3)
roentgen b75cab
		fputs(">\n", fd);
roentgen b75cab
	}
roentgen b75cab
#if !defined( EXP_ASCII85ENCODER )
roentgen b75cab
	else
roentgen b75cab
	    Ascii85Flush(fd);
roentgen b75cab
#else
roentgen b75cab
	if ( ascii85_p )
roentgen b75cab
	    _TIFFfree( ascii85_p );
roentgen b75cab
#endif
roentgen b75cab
roentgen b75cab
	_TIFFfree(tf_buf);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
void
roentgen b75cab
PSRawDataBW(FILE* fd, TIFF* tif, uint32 w, uint32 h)
roentgen b75cab
{
roentgen b75cab
	uint64 *bc;
roentgen b75cab
	uint32 bufsize;
roentgen b75cab
	int breaklen = MAXLINE;
roentgen b75cab
	tmsize_t cc;
roentgen b75cab
	uint16 fillorder;
roentgen b75cab
	unsigned char *tf_buf;
roentgen b75cab
	unsigned char *cp, c;
roentgen b75cab
	tstrip_t s;
roentgen b75cab
roentgen b75cab
#if defined( EXP_ASCII85ENCODER )
roentgen b75cab
	tsize_t 		ascii85_l;		/* Length, in bytes, of ascii85_p[] data */
roentgen b75cab
	uint8		*	ascii85_p = 0;		/* Holds ASCII85 encoded data */
roentgen b75cab
#endif
roentgen b75cab
roentgen b75cab
	(void) w; (void) h;
roentgen b75cab
	TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &fillorder);
roentgen b75cab
	TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &bc);
roentgen b75cab
roentgen b75cab
	/*
roentgen b75cab
	 * Find largest strip:
roentgen b75cab
	 */
roentgen b75cab
roentgen b75cab
	bufsize = (uint32) bc[0];
roentgen b75cab
roentgen b75cab
	for ( s = 0; ++s < (tstrip_t)tf_numberstrips; ) {
roentgen b75cab
		if ( bc[s] > bufsize )
roentgen b75cab
			bufsize = (uint32) bc[s];
roentgen b75cab
	}
roentgen b75cab
roentgen b75cab
	tf_buf = (unsigned char*) _TIFFmalloc(bufsize);
roentgen b75cab
	if (tf_buf == NULL) {
roentgen b75cab
		TIFFError(filename, "No space for strip buffer");
roentgen b75cab
		return;
roentgen b75cab
	}
roentgen b75cab
roentgen b75cab
#if defined( EXP_ASCII85ENCODER )
roentgen b75cab
	if ( ascii85 ) {
roentgen b75cab
	    /*
roentgen b75cab
	     * Allocate a buffer to hold the ASCII85 encoded data.  Note
roentgen b75cab
	     * that it is allocated with sufficient room to hold the
roentgen b75cab
	     * encoded data (5*bufsize/4) plus the EOD marker (+8)
roentgen b75cab
	     * and formatting line breaks.  The line breaks are more
roentgen b75cab
	     * than taken care of by using 6*bufsize/4 rather than
roentgen b75cab
	     * 5*bufsize/4.
roentgen b75cab
	     */
roentgen b75cab
roentgen b75cab
	    ascii85_p = _TIFFmalloc( (bufsize+(bufsize/2)) + 8 );
roentgen b75cab
roentgen b75cab
	    if ( !ascii85_p ) {
roentgen b75cab
		_TIFFfree( tf_buf );
roentgen b75cab
roentgen b75cab
		TIFFError( filename, "Cannot allocate ASCII85 encoding buffer." );
roentgen b75cab
		return;
roentgen b75cab
	    }
roentgen b75cab
	}
roentgen b75cab
#endif
roentgen b75cab
roentgen b75cab
	for (s = 0; s < (tstrip_t) tf_numberstrips; s++) {
roentgen b75cab
		cc = TIFFReadRawStrip(tif, s, tf_buf, (tmsize_t) bc[s]);
roentgen b75cab
		if (cc < 0) {
roentgen b75cab
			TIFFError(filename, "Can't read strip");
roentgen b75cab
			break;
roentgen b75cab
		}
roentgen b75cab
		if (fillorder == FILLORDER_LSB2MSB)
roentgen b75cab
			TIFFReverseBits(tf_buf, cc);
roentgen b75cab
		if (!ascii85) {
roentgen b75cab
			for (cp = tf_buf; cc > 0; cc--) {
roentgen b75cab
				DOBREAK(breaklen, 1, fd);
roentgen b75cab
				c = *cp++;
roentgen b75cab
				PUTHEX(c, fd);
roentgen b75cab
			}
roentgen b75cab
			fputs(">\n", fd);
roentgen b75cab
			breaklen = MAXLINE;
roentgen b75cab
		} else {
roentgen b75cab
			Ascii85Init();
roentgen b75cab
#if defined( EXP_ASCII85ENCODER )
roentgen b75cab
			ascii85_l = Ascii85EncodeBlock( ascii85_p, 1, tf_buf, cc );
roentgen b75cab
roentgen b75cab
			if ( ascii85_l > 0 )
roentgen b75cab
				fwrite( ascii85_p, ascii85_l, 1, fd );
roentgen b75cab
#else
roentgen b75cab
			for (cp = tf_buf; cc > 0; cc--)
roentgen b75cab
				Ascii85Put(*cp++, fd);
roentgen b75cab
			Ascii85Flush(fd);
roentgen b75cab
#endif	/* EXP_ASCII85ENCODER */
roentgen b75cab
		}
roentgen b75cab
	}
roentgen b75cab
	_TIFFfree((char *) tf_buf);
roentgen b75cab
roentgen b75cab
#if defined( EXP_ASCII85ENCODER )
roentgen b75cab
	if ( ascii85_p )
roentgen b75cab
		_TIFFfree( ascii85_p );
roentgen b75cab
#endif
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
void
roentgen b75cab
Ascii85Init(void)
roentgen b75cab
{
roentgen b75cab
	ascii85breaklen = 2*MAXLINE;
roentgen b75cab
	ascii85count = 0;
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
static char*
roentgen b75cab
Ascii85Encode(unsigned char* raw)
roentgen b75cab
{
roentgen b75cab
	static char encoded[6];
roentgen b75cab
	uint32 word;
roentgen b75cab
roentgen b75cab
	word = (((raw[0]<<8)+raw[1])<<16) + (raw[2]<<8) + raw[3];
roentgen b75cab
	if (word != 0L) {
roentgen b75cab
		uint32 q;
roentgen b75cab
		uint16 w1;
roentgen b75cab
roentgen b75cab
		q = word / (85L*85*85*85);	/* actually only a byte */
roentgen b75cab
		encoded[0] = (char) (q + '!');
roentgen b75cab
roentgen b75cab
		word -= q * (85L*85*85*85); q = word / (85L*85*85);
roentgen b75cab
		encoded[1] = (char) (q + '!');
roentgen b75cab
roentgen b75cab
		word -= q * (85L*85*85); q = word / (85*85);
roentgen b75cab
		encoded[2] = (char) (q + '!');
roentgen b75cab
roentgen b75cab
		w1 = (uint16) (word - q*(85L*85));
roentgen b75cab
		encoded[3] = (char) ((w1 / 85) + '!');
roentgen b75cab
		encoded[4] = (char) ((w1 % 85) + '!');
roentgen b75cab
		encoded[5] = '\0';
roentgen b75cab
	} else
roentgen b75cab
		encoded[0] = 'z', encoded[1] = '\0';
roentgen b75cab
	return (encoded);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
void
roentgen b75cab
Ascii85Put(unsigned char code, FILE* fd)
roentgen b75cab
{
roentgen b75cab
	ascii85buf[ascii85count++] = code;
roentgen b75cab
	if (ascii85count >= 4) {
roentgen b75cab
		unsigned char* p;
roentgen b75cab
		int n;
roentgen b75cab
roentgen b75cab
		for (n = ascii85count, p = ascii85buf; n >= 4; n -= 4, p += 4) {
roentgen b75cab
			char* cp;
roentgen b75cab
			for (cp = Ascii85Encode(p); *cp; cp++) {
roentgen b75cab
				putc(*cp, fd);
roentgen b75cab
				if (--ascii85breaklen == 0) {
roentgen b75cab
					putc('\n', fd);
roentgen b75cab
					ascii85breaklen = 2*MAXLINE;
roentgen b75cab
				}
roentgen b75cab
			}
roentgen b75cab
		}
roentgen b75cab
		_TIFFmemcpy(ascii85buf, p, n);
roentgen b75cab
		ascii85count = n;
roentgen b75cab
	}
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
void
roentgen b75cab
Ascii85Flush(FILE* fd)
roentgen b75cab
{
roentgen b75cab
	if (ascii85count > 0) {
roentgen b75cab
		char* res;
roentgen b75cab
		_TIFFmemset(&ascii85buf[ascii85count], 0, 3);
roentgen b75cab
		res = Ascii85Encode(ascii85buf);
roentgen b75cab
		fwrite(res[0] == 'z' ? "!!!!" : res, ascii85count + 1, 1, fd);
roentgen b75cab
	}
roentgen b75cab
	fputs("~>\n", fd);
roentgen b75cab
}
roentgen b75cab
#if	defined( EXP_ASCII85ENCODER)
roentgen b75cab

roentgen b75cab
#define A85BREAKCNTR    ascii85breaklen
roentgen b75cab
#define A85BREAKLEN     (2*MAXLINE)
roentgen b75cab
roentgen b75cab
/*****************************************************************************
roentgen b75cab
*
roentgen b75cab
* Name:         Ascii85EncodeBlock( ascii85_p, f_eod, raw_p, raw_l )
roentgen b75cab
*
roentgen b75cab
* Description:  This routine will encode the raw data in the buffer described
roentgen b75cab
*               by raw_p and raw_l into ASCII85 format and store the encoding
roentgen b75cab
*               in the buffer given by ascii85_p.
roentgen b75cab
*
roentgen b75cab
* Parameters:   ascii85_p   -   A buffer supplied by the caller which will
roentgen b75cab
*                               contain the encoded ASCII85 data.
roentgen b75cab
*               f_eod       -   Flag: Nz means to end the encoded buffer with
roentgen b75cab
*                               an End-Of-Data marker.
roentgen b75cab
*               raw_p       -   Pointer to the buffer of data to be encoded
roentgen b75cab
*               raw_l       -   Number of bytes in raw_p[] to be encoded
roentgen b75cab
*
roentgen b75cab
* Returns:      (int)   <   0   Error, see errno
roentgen b75cab
*                       >=  0   Number of bytes written to ascii85_p[].
roentgen b75cab
*
roentgen b75cab
* Notes:        An external variable given by A85BREAKCNTR is used to
roentgen b75cab
*               determine when to insert newline characters into the
roentgen b75cab
*               encoded data.  As each byte is placed into ascii85_p this
roentgen b75cab
*               external is decremented.  If the variable is decrement to
roentgen b75cab
*               or past zero then a newline is inserted into ascii85_p
roentgen b75cab
*               and the A85BREAKCNTR is then reset to A85BREAKLEN.
roentgen b75cab
*                   Note:  for efficiency reasons the A85BREAKCNTR variable
roentgen b75cab
*                          is not actually checked on *every* character
roentgen b75cab
*                          placed into ascii85_p but often only for every
roentgen b75cab
*                          5 characters.
roentgen b75cab
*
roentgen b75cab
*               THE CALLER IS RESPONSIBLE FOR ENSURING THAT ASCII85_P[] IS
roentgen b75cab
*               SUFFICIENTLY LARGE TO THE ENCODED DATA!
roentgen b75cab
*                   You will need at least 5 * (raw_l/4) bytes plus space for
roentgen b75cab
*                   newline characters and space for an EOD marker (if
roentgen b75cab
*                   requested).  A safe calculation is to use 6*(raw_l/4) + 8
roentgen b75cab
*                   to size ascii85_p.
roentgen b75cab
*
roentgen b75cab
*****************************************************************************/
roentgen b75cab
roentgen b75cab
tsize_t Ascii85EncodeBlock( uint8 * ascii85_p, unsigned f_eod, const uint8 * raw_p, tsize_t raw_l )
roentgen b75cab
roentgen b75cab
{
roentgen b75cab
    char                        ascii85[5];     /* Encoded 5 tuple */
roentgen b75cab
    tsize_t                     ascii85_l;      /* Number of bytes written to ascii85_p[] */
roentgen b75cab
    int                         rc;             /* Return code */
roentgen b75cab
    uint32                      val32;          /* Unencoded 4 tuple */
roentgen b75cab
roentgen b75cab
    ascii85_l = 0;                              /* Nothing written yet */
roentgen b75cab
roentgen b75cab
    if ( raw_p )
roentgen b75cab
    {
roentgen b75cab
        --raw_p;                                /* Prepare for pre-increment fetches */
roentgen b75cab
roentgen b75cab
        for ( ; raw_l > 3; raw_l -= 4 )
roentgen b75cab
        {
roentgen b75cab
            val32  = *(++raw_p) << 24;
roentgen b75cab
            val32 += *(++raw_p) << 16;
roentgen b75cab
            val32 += *(++raw_p) <<  8;
roentgen b75cab
            val32 += *(++raw_p);
roentgen b75cab
    
roentgen b75cab
            if ( val32 == 0 )                   /* Special case */
roentgen b75cab
            {
roentgen b75cab
                ascii85_p[ascii85_l] = 'z';
roentgen b75cab
                rc = 1;
roentgen b75cab
            }
roentgen b75cab
    
roentgen b75cab
            else
roentgen b75cab
            {
roentgen b75cab
                ascii85[4] = (char) ((val32 % 85) + 33);
roentgen b75cab
                val32 /= 85;
roentgen b75cab
    
roentgen b75cab
                ascii85[3] = (char) ((val32 % 85) + 33);
roentgen b75cab
                val32 /= 85;
roentgen b75cab
    
roentgen b75cab
                ascii85[2] = (char) ((val32 % 85) + 33);
roentgen b75cab
                val32 /= 85;
roentgen b75cab
    
roentgen b75cab
                ascii85[1] = (char) ((val32 % 85) + 33);
roentgen b75cab
                ascii85[0] = (char) ((val32 / 85) + 33);
roentgen b75cab
roentgen b75cab
                _TIFFmemcpy( &ascii85_p[ascii85_l], ascii85, sizeof(ascii85) );
roentgen b75cab
                rc = sizeof(ascii85);
roentgen b75cab
            }
roentgen b75cab
    
roentgen b75cab
            ascii85_l += rc;
roentgen b75cab
    
roentgen b75cab
            if ( (A85BREAKCNTR -= rc) <= 0 )
roentgen b75cab
            {
roentgen b75cab
                ascii85_p[ascii85_l] = '\n';
roentgen b75cab
                ++ascii85_l;
roentgen b75cab
                A85BREAKCNTR = A85BREAKLEN;
roentgen b75cab
            }
roentgen b75cab
        }
roentgen b75cab
    
roentgen b75cab
        /*
roentgen b75cab
         * Output any straggler bytes:
roentgen b75cab
         */
roentgen b75cab
    
roentgen b75cab
        if ( raw_l > 0 )
roentgen b75cab
        {
roentgen b75cab
            tsize_t         len;                /* Output this many bytes */
roentgen b75cab
    
roentgen b75cab
            len = raw_l + 1;
roentgen b75cab
            val32 = *++raw_p << 24;             /* Prime the pump */
roentgen b75cab
    
roentgen b75cab
            if ( --raw_l > 0 )  val32 += *(++raw_p) << 16;
roentgen b75cab
            if ( --raw_l > 0 )  val32 += *(++raw_p) <<  8;
roentgen b75cab
    
roentgen b75cab
            val32 /= 85;
roentgen b75cab
    
roentgen b75cab
            ascii85[3] = (char) ((val32 % 85) + 33);
roentgen b75cab
            val32 /= 85;
roentgen b75cab
    
roentgen b75cab
            ascii85[2] = (char) ((val32 % 85) + 33);
roentgen b75cab
            val32 /= 85;
roentgen b75cab
    
roentgen b75cab
            ascii85[1] = (char) ((val32 % 85) + 33);
roentgen b75cab
            ascii85[0] = (char) ((val32 / 85) + 33);
roentgen b75cab
    
roentgen b75cab
            _TIFFmemcpy( &ascii85_p[ascii85_l], ascii85, len );
roentgen b75cab
            ascii85_l += len;
roentgen b75cab
        }
roentgen b75cab
    }
roentgen b75cab
roentgen b75cab
    /*
roentgen b75cab
     * If requested add an ASCII85 End Of Data marker:
roentgen b75cab
     */
roentgen b75cab
roentgen b75cab
    if ( f_eod )
roentgen b75cab
    {
roentgen b75cab
        ascii85_p[ascii85_l++] = '~';
roentgen b75cab
        ascii85_p[ascii85_l++] = '>';
roentgen b75cab
        ascii85_p[ascii85_l++] = '\n';
roentgen b75cab
    }
roentgen b75cab
roentgen b75cab
    return ( ascii85_l );
roentgen b75cab
roentgen b75cab
}   /* Ascii85EncodeBlock() */
roentgen b75cab
roentgen b75cab
#endif	/* EXP_ASCII85ENCODER */
roentgen b75cab
roentgen b75cab
roentgen b75cab
char* stuff[] = {
roentgen b75cab
"usage: tiff2ps [options] input.tif ...",
roentgen b75cab
"where options are:",
roentgen b75cab
" -1            generate PostScript Level 1 (default)",
roentgen b75cab
" -2            generate PostScript Level 2",
roentgen b75cab
" -3            generate PostScript Level 3",
roentgen b75cab
" -8            disable use of ASCII85 encoding with PostScript Level 2/3",
roentgen b75cab
" -a            convert all directories in file (default is first), Not EPS",
roentgen b75cab
" -b #          set the bottom margin to # inches",
roentgen b75cab
" -c            center image (-b and -l still add to this)",
roentgen b75cab
" -d #          set initial directory to # counting from zero",
roentgen b75cab
" -D            enable duplex printing (two pages per sheet of paper)",
roentgen b75cab
" -e            generate Encapsulated PostScript (EPS) (implies -z)",
roentgen b75cab
" -h #          set printed page height to # inches (no default)",
roentgen b75cab
" -w #          set printed page width to # inches (no default)",
roentgen b75cab
" -H #          split image if height is more than # inches",
roentgen b75cab
" -P L or P     set optional PageOrientation DSC comment to Landscape or Portrait",
roentgen b75cab
" -W #          split image if width is more than # inches",
roentgen b75cab
" -L #          overLap split images by # inches",
roentgen b75cab
" -i #          enable/disable (Nz/0) pixel interpolation (default: enable)",
roentgen b75cab
" -l #          set the left margin to # inches",
roentgen b75cab
" -m            use \"imagemask\" operator instead of \"image\"",
roentgen b75cab
" -o #          convert directory at file offset # bytes",
roentgen b75cab
" -O file       write PostScript to file instead of standard output",
roentgen b75cab
" -p            generate regular PostScript",
roentgen b75cab
" -r # or auto  rotate by 90, 180, 270 degrees or auto",
roentgen b75cab
" -s            generate PostScript for a single image",
roentgen b75cab
" -t name       set postscript document title. Otherwise the filename is used",
roentgen b75cab
" -T            print pages for top edge binding",
roentgen b75cab
" -x            override resolution units as centimeters",
roentgen b75cab
" -y            override resolution units as inches",
roentgen b75cab
" -z            enable printing in the deadzone (only for PostScript Level 2/3)",
roentgen b75cab
NULL
roentgen b75cab
};
roentgen b75cab
roentgen b75cab
static void
roentgen b75cab
usage(int code)
roentgen b75cab
{
roentgen b75cab
	char buf[BUFSIZ];
roentgen b75cab
	int i;
roentgen b75cab
roentgen b75cab
	setbuf(stderr, buf);
roentgen b75cab
        fprintf(stderr, "%s\n\n", TIFFGetVersion());
roentgen b75cab
	for (i = 0; stuff[i] != NULL; i++)
roentgen b75cab
		fprintf(stderr, "%s\n", stuff[i]);
roentgen b75cab
	exit(code);
roentgen b75cab
}
roentgen b75cab