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