%!
% This is a PostScript program for making an EPS file from a TIFF
%
% Written in BOP s.c., Gda\'nsk, Poland
% e-mail contact: [email protected]
%
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License.
% See: http://www.fsf.org/licenses/gpl.txt
%
% History:
% version 0.30 (28 III 1998)
%
% version 0.35 (30 III 1998)   Header EPSes added, a few buglets removed.
%
% version 0.40 (12-22 IV 1998) Fax-TIFF (CCITT Group III and IV) added,
%                              more tags known, more efficient loops used,
%                              separation in `header' EPSes supported
%                              exact BoundingBox is now optional,
%                              interpolation enabled, interpretation
%                              of parameters improved, a heuristic
%                              work-around applied for TIFFs without
%                              specified resolution.
%
% version 0.50 (28 IV 1998)    BachoTeX '98 release.
%
% version 0.55 (31 VII 1998)   Verbose, imagemask and newer-overwrite
%                              switches added, heuristic implicite
%                              resolution calculation.
% version 0.56 (13 VIII 1998)  Bug in fixing output filter fixed;
%                              some bugs introduced in ver. 0.55 fixed
%                              better formatting of SBC and SOF tables.
%
% version 0.57 (25 VI 1999)    Imagemask colouring enabled.
%
% version 0.58 (30 III 2000)   Usage of ASCII85Encode filter adjusted
%                              to Ghostscript 6.x (see ASCII85Encode).
%
% version 0.59 (10 IV 2000)    `%%Creator:' DSC comment added.
%
% version 0.60 (4 V 2001)      After `BachoTeX 2001' release:
%                              - some minor bugs hunted, and probably many
%                                new introduced ;(
%                              - output filters added:
%                                - LZW with horizontal predictor
%                                - CCITTFax group 3
%                                - CCITTFax group 4 (two-dimensional)
%                                - DCT (JPEG standard)
%                              - resolution can be forced from commandline
%                              - location of image data not defined in TIFF
%                                file is guessed (if it is possible)
%                              - some errors in TIFFs are corrected:
%                                - incompatible RLE is handled
%                                - strips are checked to obtain correct length
%                                - CCITTFax recover of next line is activated
%                              - in header EPSes, a length of TIFF is
%                                checked in order to avoid rendering
%                                a wrong file with the same name
%                              - predictor feature is moved to LZWDecode
%                                parameter, where it was possible
%                              This version is heavily rebuilded, and
%                              intended to be tested intensively.
%
% version 0.61 (19 X 2001)     Command `quit' added at the end of the script.
%
% version 0.62 (28 XI 2001)    Processing of multipage TIFF files added
%                              - option -p#, # - number of page to be
%                              processed.
%
% version 0.63 (29 I 2002)     Processing of very large (wide) TIFF images
%                              implemented (many thanks to Howard Halstead),
%                              slight code optimization, messages changed.
%
% version 0.64 (15 II 2002)    Bugs in the processing of very wide TIFF
%                              images fixed.
%
% version 0.65 (16 IV 2002)    Checking of TIFF length disabled
%                              (on Avantra RIP all files have length -1).
%
% version 0.66 (7 VI 2002)     Generating of Level 1 EPSes.
%
% version 0.67 (25 X 2002)     Work-around bug in reading short values
%                              from IFD (stored as a long value,
%                              procedure `convs').
%
% version 0.68 (7 XI 2002)     A little but noxious bug in processing
%                              of multipage TIFF files fixed.
%
% version 0.69 (30 XI 2002)    `%%HiResBoundingBox:' comment added.
%
% version 0.70 (6 XII 2002)    Licence changed to GPL, package name changed
%                              from tiff2ps to tif2eps;
%                              package submitted to SourceForge.net.
%
% version 0.71 (11 II 2003)    At verbosity level 0, no messages are issued
%                              (even error messages).
%
% version 0.72 (21 II 2003)    Processing of 1- and 2-bit pallete images
%                              added; do there exist 3-bit, 5-bit, 6-bit,
%                              and 7-bit palletes? TIFF 6.0 specification
%                              explicitly allows only 4- and 8-bit palletes.
%
% version 0.73 (5 IV 2003)     Processing of zlib-compressed TIFFs
%                              (compression type 8 and 32946) added,
%                              zero and infinite resolutions are ignored
%                              (72 dpi is assumed).
%
% version 0.74 (24 IV 2003)    Usage message reenabled
%                              (bug introduced in ver. 0.71).
%
% version 0.75 (13 V 2003)     Processing of JPEG-compressed TIFFs
%                              (compression type 7) added;
%                              compression type 6 (TIFF native DCT;
%                              obsolete?) still not supported.
%
% version 0.76 (11 VI 2004)    One more bug in the processing of very
%                              wide TIFF images fixed (in header form).
%
% version 0.77 (10 XII 2004)   Patch for processing TIFFs LZW-packed
%                              by a newer PhotoShop version (>4.x) --
%                              discarding extra byte at the end of strip.
%
% version 0.78 (11 II 2005)    Continuation of the previous fix:
%                              corrected calculation of bytes per strip
%                              in BW pictures.
%
% version 0.79 (1 III 2005)    A bug in -o2 (overwrite if newer) option fixed:
%                              the `created' field of the output file was
%                              compared to the `referenced' field of the
%                              input file. In Ghostscript, `referenced'
%                              field means actually the modification time
%                              (fortunately, although unorthodoxly),
%                              so this field is now used for comparison.
%
% Usage:
%   gs [-dNODISPLAY] [-q] -- tif2eps.ps TIFF_name [EPS_name] [options]
%
% ---
/edef {exch def} def
/TIFFdictput {TIFFdict 3 1 roll exch put} def
/printErr {EPSdict /Verbose get 0 gt {print}{pop} ifelse} def
/printQuit {print (, quitting\n) print flush quit} def
/flushclosefile {dup flushfile closefile} def
/readb {infile read not {(Unexpected EOF, probably damaged TIFF file) printQuit} if} def
/testandsetfileposition {
 dup lengthofinfile gt {
   (Unexpected EOF, probably damaged TIFF file) printQuit
 } if
 setfileposition
} def
/TIFFdict 255 dict def
/IMAGEdict 255 dict def
/EPSdict 255 dict def
%---
% Header of TIFF file
/ReadHeader {
 infile 0 setfileposition
 readb dup 73 eq exch 77 eq % II or MM
 readb dup 73 eq exch 77 eq %
 2 index and exch 3 index and
 4 2 roll pop pop
 2 copy or not
 {(Not a TIFF file) printQuit} if
 {% litle endian (II)
   /reads {readb readb 256 mul add} def
   /readl {readb readb readb readb 256 mul add 256 mul add 256 mul add} def
   /convs {dup type (integertype) eq {655536 mod}
     {dup 65536 div truncate 65536 mul sub cvi} ifelse} def % patch
   /convIIs {dup type (integertype) eq {655536 idiv}
     {65536 div cvi} ifelse} def % patch
 } if
 {% big endian (MM)
   /reads {readb 256 mul readb add} def
   /readl {readb 256 mul readb add 256 mul readb add 256 mul readb add} def
   /convs {dup type (integertype) eq {65536 idiv}
     {65536 div cvi} ifelse} def % patch
   /convIIs {dup type (integertype) eq {65536 mod}
     {dup 65536 div truncate 65536 mul sub cvi} ifelse} def % patch
 } if
 reads 42 ne % magic number
 {(Not a TIFF file) printQuit} if
 /IFDOffset readl def
} def
%---
% Image File Directory (IFD)
/ReadIFDs {
 EPSdict /PageNumber known {
   EPSdict /PageNumber get {
     infile IFDOffset testandsetfileposition
     reads % number of tags in IFD
     12 mul 2 add IFDOffset add
     infile exch testandsetfileposition
     readl dup 0 eq {% pointer to next IFD
       (There are less pages in a TIFF file, then you speciefied) printQuit
     } if
     /IFDOffset edef
   } repeat
 } if
 infile IFDOffset testandsetfileposition
 reads % number of tags in IFD
 {readtag} repeat
 readl % pointer to next IFD
 EPSdict /PageNumber known {pop}{
   0 eq not {
      (More images in a TIFF file, the first one interpreted -- use -p option\n) printCon
   } if
 } ifelse
 flush % show all previous messages
} def
%---
% Interpreting TAGS
/tmpstr 8 string def
/readtag {
 reads % TAG number
 reads % field type
 readl % field count
 readl % offset to value or value
 /returnfileposition infile fileposition def
 3 index dup tmpstr cvs cvn tagsdict exch known {
   tmpstr cvs cvn tagsdict exch get
   exec
 }{
   dup 32768 ge {
     (Private tag \() printCon =string cvs printCon (\), ignored\n) printCon
   }{
     (Unknown tag ) printErr =string cvs printErr (, ignored\n) printErr
   } ifelse
   pop pop pop pop
 } ifelse
 infile returnfileposition setfileposition
} def
%---
% Interpreting TAGS
/PrepareTAGsDictionary {
 % Additional definitions to analyze tags
 /ascii {
   2 ne {(Bad tag type) printQuit} if
 } def
 /short {
   3 eq {convs}{(Bad tag type) printQuit} ifelse
 } def
 /long {
   4 ne {(Bad tag type) printQuit} if
 } def
 /rational {
   5 ne {(Bad tag type) printQuit} if
 } def
 /shortorlong {
   dup 3 eq {
     pop convs
   }{
     4 ne {(Bad tag type) printQuit} if
   } ifelse
 } def
 /toomany {
   1 ne {(Too many values for a tag) printQuit} if
 } def
 /interpreteascii {
   pop % name of field
   pop % value
   pop % count
   ascii
   pop
 } def
 /interpreteshort {
   pop % name of field
   pop % value
   pop % count
   short
   pop
 } def
 /knownnotinterpreted {
   pop pop pop pop pop
 } def
 %---
 % Definitions of TAGs
 /tagsdict 255 dict def
 tagsdict begin
   /254 {
     exch toomany
     exch long
     exch pop
     dup 0 eq exch 2 eq or not
       {(Not the main image -- weird output expected\n) printErr} if
   } def
   /255 {
     exch toomany
     exch short
     exch pop
     dup 1 eq exch 3 eq or not
       {(Not the main image -- weird output expected\n) printErr} if
   } def
   /256 {
     exch toomany
     exch shortorlong
     exch pop
     /Width TIFFdictput
   } def
   /257 {
     exch toomany
     exch shortorlong
     exch pop
     /Length TIFFdictput
   } def
   /258 {
     exch /NOV edef TIFFdict /SamplesPerPixelX NOV put
     exch 3 ne {(Bad tag type) printQuit} if % modified short
     exch pop
     NOV 1 eq {
       convs /BitsPerSample TIFFdictput
     } if
     NOV 2 eq {
       dup dup convs exch convIIs eq {
         convs /BitsPerSample TIFFdictput
       }{
         pop (Samples have not equal numbers of bits, can't process image) printQuit
       } ifelse
     } if
     NOV 2 gt {
       infile exch testandsetfileposition
       NOV {reads} repeat
       true NOV 1 sub {exch 2 index eq and} repeat
       {
         /BitsPerSample TIFFdictput
       }{
         pop (Samples have not equal numbers of bits, can't process image) printQuit
       } ifelse
     } if
   } def
   /259 {
     exch toomany
     exch short
     exch pop
     /Compression TIFFdictput
   } def
   /262 {
     exch toomany
     exch short
     exch pop
     /PhotometricInterpretation TIFFdictput
   } def
   /263 {
     (Tresholding) interpreteshort
   } def
   /264 {
     (CellWidth) knownnotinterpreted
   } def
   /265 {
     (CellHeight) knownnotinterpreted
   } def
   /266 {
     exch toomany
     exch short
     exch pop
     /FillOrder TIFFdictput
   } def
   /269 {
     (DocumentName) interpreteascii
   } def
   /270 {
     (ImageDescription) interpreteascii
   } def
   /271 {
     (Make) interpreteascii
   } def
   /272 {
     (Model) interpreteascii
   } def
   /273 {
     exch /NOV edef TIFFdict /StripsPerImageX NOV put
     exch /LOV edef LOV 3 ne LOV 4 ne and {(Bad tag type) printQuit} if % modified shortlong
     exch pop
     /TOV NOV array def
     LOV 3 eq {
       NOV 1 eq {convs TOV 0 2 index put pop} if
       NOV 2 eq {
         dup convs TOV 0 2 index put pop
             convIIs TOV 1 2 index put pop
       } if
       NOV 2 gt {
         infile exch testandsetfileposition
         0 NOV {dup 1 add exch TOV exch reads put} repeat pop
       } if
     }{
       NOV 1 eq {TOV 0 2 index put pop} if
       NOV 1 gt {
         infile exch testandsetfileposition
         0 NOV {dup 1 add exch TOV exch readl put} repeat pop
       } if
     } ifelse
     TIFFdict /StripOffsets TOV put
   } def
   /274 {
     exch toomany
     exch short
     exch pop
     /Orientation TIFFdictput
   } def
   /277 {
     exch toomany
     exch short
     exch pop
     /SamplesPerPixel TIFFdictput
   } def
   /278 {
     exch toomany
     exch shortorlong
     exch pop
     /RowsPerStrip TIFFdictput
   } def
   /279 {
     exch /NOV edef TIFFdict /StripsPerImageY NOV put
     exch /LOV edef LOV 3 ne LOV 4 ne and {(Bad tag type) printQuit} if % modified shortlong
     exch pop
     /TOV NOV array def
     LOV 3 eq {
       NOV 1 eq {convs TOV 0 2 index put pop} if
       NOV 2 eq {
         dup convs TOV 0 2 index put pop
             convIIs TOV 1 2 index put pop
       } if
       NOV 2 gt {
         infile exch testandsetfileposition
         0 NOV {dup 1 add exch TOV exch reads put} repeat pop
       } if
     }{
       NOV 1 eq {TOV 0 2 index put pop} if
       NOV 1 gt {
         infile exch testandsetfileposition
         0 NOV {dup 1 add exch TOV exch readl put} repeat pop
       } if
     } ifelse
     TIFFdict /StripByteCounts TOV put
   } def
   /280 {
     (MinSampleValue) interpreteshort
   } def
   /281 {
     (MaxSampleValue) interpreteshort
   } def
   /282 {
     exch toomany
     exch rational
     exch pop
     infile exch testandsetfileposition
     TIFFdict /XResolution readl readl
     dup 0 eq  {
       (Bad resolution -- divide by zero, changed to 1.\n) printErr
       pop 1} if
     div put
   } def
   /283 {
     exch toomany
     exch rational
     exch pop
     infile exch testandsetfileposition
     TIFFdict /YResolution readl readl
     dup 0 eq  {
       (Bad resolution -- divide by zero, changed to 1.\n) printErr
       pop 1} if
     div put
   } def
   /284 {
     exch toomany
     exch short
     exch pop
     /PlanarConfiguration TIFFdictput
   } def
   /285 {
     (PageName) interpreteascii
   } def
   /286 {
    (XPosition) knownnotinterpreted
   } def
   /287 {
    (YPosition) knownnotinterpreted
   } def
   /288 {
    (FreeOffsets) knownnotinterpreted
   } def
   /289 {
    (FreeByteCounts) knownnotinterpreted
   } def
   /290 {
    (GrayResponseUnit) knownnotinterpreted
   } def
   /291 {
    (GrayResponseCurve) knownnotinterpreted
   } def
   /292 {
     exch toomany
     exch long
     exch pop
     /T4Options TIFFdictput
   } def
   /293 {
     exch toomany
     exch long
     exch pop
     /T6Options TIFFdictput
   } def
   /296 {
     exch toomany
     exch short
     exch pop
     /ResolutionUnit TIFFdictput
   } def
   /297 {
     exch 2 ne {(Bad number of values for a tag) printQuit} if % modified toomany
     exch 3 ne {(Bad tag type) printQuit} if % modified short
     exch pop
     dup convs /PageNumber TIFFdictput
     convIIs /NumberOfPages TIFFdictput
   } def
   /301 {
    (TransferFunction) knownnotinterpreted
   } def
   /305 {
     (Software) interpreteascii
   } def
   /306 {
     (DateTime) interpreteascii
   } def
   /315 {
     (Artist) interpreteascii
   } def
   /316 {
     (HostComputer) interpreteascii
   } def
   /317 {
     exch toomany
     exch short
     exch pop
     /Predictor TIFFdictput
   } def
   /320 {
     exch /NOV edef
       NOV   6 eq dup {1 /BitsPerSampleX TIFFdictput} if
       NOV  12 eq dup {2 /BitsPerSampleX TIFFdictput} if
       NOV  48 eq dup {4 /BitsPerSampleX TIFFdictput} if
       NOV 768 eq dup {8 /BitsPerSampleX TIFFdictput} if
       or or or not {(Weird pallete mode) printQuit} if
     exch 3 ne {(Bad tag type) printQuit} if % modified short
     exch pop
     /TOV NOV string def
     infile exch testandsetfileposition
     0 NOV {dup 1 add exch TOV exch reads 256 idiv put} repeat pop
     TIFFdict /ColorMap TOV put
   } def
   /322 {
     exch toomany
     exch shortorlong
     exch pop
     /TileWidth TIFFdictput
   } def
   /323 {
     exch toomany
     exch shortorlong
     exch pop
     /TileHeight TIFFdictput
   } def
   /324 {
     exch /NOV edef TIFFdict /TilesPerImageX NOV put
     exch long
     exch pop
     /TOV NOV array def
     % always long data
     NOV 1 eq {TOV 0 2 index put pop} if
     NOV 1 gt {
       infile exch testandsetfileposition
       0 NOV {dup 1 add exch TOV exch readl put} repeat pop
     } if
     TIFFdict /TileOffsets TOV put
   } def
   /325 {
     exch /NOV edef TIFFdict /TilesPerImageY NOV put
     exch /LOV edef LOV 3 ne LOV 4 ne and {(Bad tag type) printQuit} if % modified shortlong
     exch pop
     /TOV NOV array def
     LOV 3 eq {
       NOV 1 eq {convs TOV 0 2 index put pop} if
       NOV 2 eq {
         dup convs TOV 0 2 index put pop
             convIIs TOV 1 2 index put pop
       } if
       NOV 2 gt {
         infile exch testandsetfileposition
         0 NOV {dup 1 add exch TOV exch reads put} repeat pop
       } if
     }{
       NOV 1 eq {TOV 0 2 index put pop} if
       NOV 1 gt {
         infile exch testandsetfileposition
         0 NOV {dup 1 add exch TOV exch readl put} repeat pop
       } if
     } ifelse
     TIFFdict /TileByteCounts TOV put
   } def
   /327 {
     (CleanFaxData) interpreteshort
   } def
   /332 {
     exch toomany
     exch short
     exch pop
     /InkSet TIFFdictput
   } def
   /334 {
     exch toomany
     exch short
     exch pop
     /SamplesPerPixelY TIFFdictput
   } def
   /336 {
    (DotRange) knownnotinterpreted
   } def
   /337 {
     (TargetPrinter) interpreteascii
   } def
   /338 {
     exch /ExtraSamples TIFFdictput
     exch short
     exch pop
     pop
   } def
   /347 {
     /JPEGTableOffset TIFFdictput
     /JPEGTableLength TIFFdictput
     7 ne {(Bad tag type) printQuit} if % Type = UNDEFINED
     pop
   } def
   /33432 {
     (Copyright) interpreteascii
   } def
   /34377 {
     (PhotoShop private field) knownnotinterpreted
   } def
 end
} def
%---
/ProcessImageDict {
 %
 %  required:
 %    /Width
 %    /Length
 %    /PhotometricInterpretation
 %    /XResolution
 %    /YResolution
 %    /Compression
 %    /RowsPerStrip
 %    /StripByteCounts
 %    /StripOffsets
 %
 % other used by program:
 %    /ResolutionUnit
 %    /BitsPerSample
 %    /SamplesPerPixel
 %    /ExtraSamples
 %    /ColorMap
 %    /FillOrder
 %    /Predictor
 %    /Orientation
 %    /PlanarConfiguration
 %    /InkSet
 %    /T4Options
 %    /T6Options
 %    /PageNumber
 %    /NumberOfPages
 %    /TileWidth
 %    /TileHeight
 %    /TileByteCounts
 %    /TileOffsets
 %    /JPEGTableOffset
 %    /JPEGTableLength
 %
 % calculated from others:
 %    /BitsPerSampleX
 %    /SamplesPerPixelX
 %    /SamplesPerPixelY
 %    /StripsPerImageX
 %    /StripsPerImageY
 %    /TilesPerImageX
 %    /TilesPerImageY

 IMAGEdict /ImageType 1 put

 TIFFdict /Width known {
   IMAGEdict /Width TIFFdict /Width get put
 }{
   (Bitmap width not given) printQuit
 } ifelse

 TIFFdict /Length known {
   IMAGEdict /Height TIFFdict /Length get put
 }{
   (Bitmap height not given) printQuit
 } ifelse

 TIFFdict /PhotometricInterpretation known not {
   (Photometric interpretation not given) printQuit
 } if

 TIFFdict /PhotometricInterpretation get 1 le {
   IMAGEdict /ColorSpace [/DeviceGray] put
   TIFFdict /SamplesPerPixel known not {TIFFdict /SamplesPerPixel 1 put} if
   IMAGEdict /ExpectedSamplesPerPixel 1 put
   TIFFdict /BitsPerSample known not {TIFFdict /BitsPerSample 1 put} if
   TIFFdict /PhotometricInterpretation get
   0 eq {IMAGEdict /Decode [1 0] put}{IMAGEdict /Decode [0 1] put} ifelse
 } if

 TIFFdict /PhotometricInterpretation get 2 eq {
   IMAGEdict /ColorSpace [/DeviceRGB] put
   IMAGEdict /ExpectedSamplesPerPixel 3 put
   IMAGEdict /Decode [0 1 0 1 0 1] put
 } if

 TIFFdict /PhotometricInterpretation get 3 eq {
   TIFFdict /BitsPerSample known {
     /ihival 1 TIFFdict /BitsPerSample get bitshift def
   }{
     (Number of colors unknown) printQuit
   } ifelse
   TIFFdict /ColorMap known {
     /icm TIFFdict /ColorMap get def
     icm length 3 div ihival ne {(Bad palette size) printQuit} if
     /ocm icm length string def
     0 1 ihival 1 sub {% interleaving the palette
       dup icm exch get ocm exch 2 index 3 mul exch put
       dup ihival add icm exch get ocm exch 2 index 3 mul 1 add exch put
       dup ihival dup add add icm exch get ocm exch 2 index 3 mul 2 add exch put
       pop
     } for
     TIFFdict /ColorMap ocm put
   }{
     (Palette not given) printQuit
   } ifelse
   TIFFdict /SamplesPerPixel known not {TIFFdict /SamplesPerPixel 1 put} if
   IMAGEdict /HiVal ihival 1 sub put
   IMAGEdict /ExpectedSamplesPerPixel 1 put
   IMAGEdict /ColorSpace [/Indexed
     /DeviceRGB IMAGEdict /HiVal get TIFFdict /ColorMap get] put
   IMAGEdict /Decode [0 IMAGEdict /HiVal get] put
 } if

 TIFFdict /PhotometricInterpretation get 5 eq {
   TIFFdict /InkSet known {
     TIFFdict /InkSet get 1 ne {(Not CMYK separations -- mode not supported) printQuit} if
   } if
   IMAGEdict /ExpectedSamplesPerPixel 4 put
   IMAGEdict /ColorSpace [/DeviceCMYK] put
   IMAGEdict /Decode [0 1 0 1 0 1 0 1] put
 } if

 TIFFdict /PhotometricInterpretation get 6 eq
 TIFFdict /Compression get 7 eq  and {
   IMAGEdict /ColorSpace [/DeviceRGB] put
   IMAGEdict /ExpectedSamplesPerPixel 3 put
   IMAGEdict /Decode [0 1 0 1 0 1] put
 } if

 % none of known PhotometricInterpretation was recognized
 IMAGEdict /ExpectedSamplesPerPixel known not {
   (Photometric interpretation unknown) printQuit
 } if

 TIFFdict /SamplesPerPixel known {
   IMAGEdict /SamplesPerPixel TIFFdict /SamplesPerPixel get put
   TIFFdict /SamplesPerPixel get IMAGEdict /ExpectedSamplesPerPixel get sub
   dup 0 gt {
     IMAGEdict /ExtraSamplesX 2 index put pop
   }{
     0 lt {(Insufficient number of samples per pixel) printQuit} if
   } ifelse
 }{
   (Number of samples per pixel not given) printQuit
 } ifelse

 TIFFdict /SamplesPerPixelX known {
   TIFFdict /SamplesPerPixel get TIFFdict /SamplesPerPixelX get ne
   {%should be
     % (Inconsistent number of samples per pixel) printQuit
     % but I encountered a readable file with inconsisntent
     % number of samples, ie., extra samples are not counted
     % in BitsPerSample
     (Inconsistent number of samples per pixel\n) printErr
   } if
 } if

 TIFFdict /SamplesPerPixelY known {
   TIFFdict /SamplesPerPixel get TIFFdict /SamplesPerPixelY get ne
   {(Inconsistent number of samples per pixel) printQuit} if
 } if

 TIFFdict /BitsPerSample known {
   IMAGEdict /BitsPerComponent TIFFdict /BitsPerSample get put
 }{
   (Number of bits per sample not given) printQuit
 } ifelse

 TIFFdict /BitsPerSampleX known {
   TIFFdict /BitsPerSample get TIFFdict /BitsPerSampleX get ne
   {(Inconsistent number of bits per sample) printQuit} if
 } if

 TIFFdict /Orientation known not {TIFFdict /Orientation 1 put} if
 TIFFdict begin Orientation
   dup 1 eq {IMAGEdict /ImageMatrix [Width 0 0 Length neg 0 Length] put} if
   dup 2 eq {IMAGEdict /ImageMatrix [Width neg 0 0 Length neg Width Length] put} if
   dup 3 eq {IMAGEdict /ImageMatrix [Width neg 0 0 Length Width 0] put} if
   dup 4 eq {IMAGEdict /ImageMatrix [Width 0 0 Length 0 0] put} if
   dup 5 eq {IMAGEdict /ImageMatrix [0 Width neg Length 0 Width] put} if
   dup 6 eq {IMAGEdict /ImageMatrix [0 Width neg Length neg 0 Length Width] put} if
   dup 7 eq {IMAGEdict /ImageMatrix [0 Width Length neg 0 Length 0] put} if
   dup 8 eq {IMAGEdict /ImageMatrix [0 Width Length 0 0 0] put} if
   8 gt {(Strange orientation) printQuit} if
 end

 EPSdict /XResolution known {
   (TIFF resolution overridden\n) printCon
   TIFFdict /XResolution EPSdict /XResolution get put
   TIFFdict /YResolution EPSdict /YResolution get put
   TIFFdict /ResolutionUnit 2 put
 } if

 TIFFdict /ResolutionUnit known {
   TIFFdict /ResolutionUnit get 3 gt
   {(Bad `ResolutionUnit' value) printQuit} if
 }{
   TIFFdict /ResolutionUnit 2 put % default according to specifications is dpi
 } ifelse

 TIFFdict /XResolution known
 TIFFdict /YResolution known or not {
   (Resolution not given -- assuming 72 dpi\n) printCon
   TIFFdict /XResolution 72 put
   TIFFdict /YResolution 72 put
 } if

 % there one of resolution value must be known
 TIFFdict /XResolution known not {
   (XResolution not given -- assuming square pixels\n) printCon
   TIFFdict /XResolution TIFFdict /YResolution get put
 } if
 TIFFdict /YResolution known not {
   (YResolution not given -- assuming square pixels\n) printCon
   TIFFdict /YResolution TIFFdict /XResolution get put
 } if

 TIFFdict /XResolution get 0.01 le dup {
   TIFFdict /XResolution 72 put
 } if
 TIFFdict /YResolution get 0.01 le dup {
   TIFFdict /YResolution 72 put
 } if
 or {
   (Zero resolution given  -- assuming 72 dpi\n) printCon
 } if

 TIFFdict begin
   ResolutionUnit 1 eq {
     Width % assuming physical XResolution 72 ppi
     Length YResolution XResolution div div
   } if
   ResolutionUnit 2 eq {
     Width  XResolution div 72 mul
     Length YResolution div 72 mul
   } if
   ResolutionUnit 3 eq {
     Width  XResolution div 2.54 div 72 mul
     Length YResolution div 2.54 div 72 mul
   } if
   Orientation 4 gt {exch} if
   IMAGEdict /YScale 2 index put pop  IMAGEdict /XScale 2 index put pop
 end

 TIFFdict /RowsPerStrip known {
   IMAGEdict /StripsPerImage TIFFdict /Length get TIFFdict /RowsPerStrip get
   div ceiling cvi put
 }{
   TIFFdict /RowsPerStrip TIFFdict /Length get put
   IMAGEdict /StripsPerImage 1 put
 } ifelse

 TIFFdict /StripsPerImageX known {
   IMAGEdict /StripsPerImage get TIFFdict /StripsPerImageX get ne
   {(Inconsistent number of strips per image) printQuit} if
 } if

 TIFFdict /StripsPerImageY known {
   IMAGEdict /StripsPerImage get TIFFdict /StripsPerImageY get ne
   {(Inconsistent number of strips per image) printQuit} if
 } if

 TIFFdict /Compression known {
   TIFFdict /Compression get
   dup 2 eq {
     IMAGEdict /Decompression {<</EncodedByteAlign true /BlackIs1 true /Columns WOI>> /CCITTFaxDecode filter} put
     IMAGEdict /DecompressionString (    <</EncodedByteAlign true /BlackIs1 true /Columns OWOI>> /CCITTFaxDecode filter\n) put
   } if
   dup 3 eq {
     IMAGEdict /Decompression {<</BlackIs1 true /Columns WOI>> /CCITTFaxDecode filter} put
     IMAGEdict /DecompressionString (    <</BlackIs1 true /Columns OWOI>> /CCITTFaxDecode filter\n) put
   } if
   dup 4 eq {
     IMAGEdict /Decompression {<</K -1 /BlackIs1 true /Columns WOI>> /CCITTFaxDecode filter} put
     IMAGEdict /DecompressionString (    <</K -1 /BlackIs1 true /Columns OWOI>> /CCITTFaxDecode filter\n) put
   } if
   dup 5 eq {
     IMAGEdict /Decompression {/LZWDecode filter LOS () /SubFileDecode filter} put
     IMAGEdict /DecompressionString (    /LZWDecode filter LOS () /SubFileDecode filter\n) put
   } if
   dup 7 eq {
     IMAGEdict /Decompression {/DCTDecode filter} put
     IMAGEdict /DecompressionString (    /DCTDecode filter\n) put
     TIFFdict /PhotometricInterpretation get 2 eq {
       IMAGEdict /Decompression {<</ColorTransform 0>> /DCTDecode filter} put
       IMAGEdict /DecompressionString (    <</ColorTransform 0>> /DCTDecode filter\n) put
     } if
   } if
   dup 8 eq 1 index 32946 eq or {
     IMAGEdict /Decompression {/FlateDecode filter} put
     IMAGEdict /DecompressionString (    /FlateDecode filter\n) put
   } if
   dup 32773 eq {
     IMAGEdict /Decompression {/RunLengthDecode filter} put
     IMAGEdict /DecompressionString (    /RunLengthDecode filter\n) put
   } if
   1 ne IMAGEdict /Decompression known not and {
     (Unknown compression method) printQuit
   } if
 }{
   (Compression method not given) printQuit
 } ifelse

 TIFFdict /T4Options known {
   TIFFdict /Compression get 3 eq {
     TIFFdict /T4Options get
     5 and % we takes care of 0 and 2 bit (bit 1 is not needed)
     % 0 eq is prepared in Compression section
     dup 1 eq {
       IMAGEdict /Decompression {<</K 1 /BlackIs1 true /Columns WOI>> /CCITTFaxDecode filter} put
       IMAGEdict /DecompressionString (    <</K 1 /BlackIs1 true /Columns OWOI>> /CCITTFaxDecode filter\n) put
     } if
     dup 4 eq {
       % I don't know what second bit means. I thought that it is
       % equivalent to: `/EncodedByteAlign true' but it isn't true!
       IMAGEdict /Decompression {<</BlackIs1 true /Columns WOI>> /CCITTFaxDecode filter} put
       IMAGEdict /DecompressionString (    <</BlackIs1 true /Columns OWOI>> /CCITTFaxDecode filter\n) put
     } if
     5 eq {
       IMAGEdict /Decompression {<</K 1 /BlackIs1 true /Columns WOI>> /CCITTFaxDecode filter} put
       IMAGEdict /DecompressionString (    <</K 1 /BlackIs1 true /Columns OWOI>> /CCITTFaxDecode filter\n) put
     } if
   }{
     % probably should be `printQuit', but Ghostscript generetes TIFF with
     % this tag and Modified Huffman run length encoding (compression=2)
     (T4Options given for compression other than CCITT T.4, ignoring\n) printErr
   } ifelse
 } if

 TIFFdict /T6Options known {
   TIFFdict /Compression get 4 eq {
     % bit 0 -- unused
     % bit 1 -- uncompressed mode is always allowed in PostScript
   }{
     (T6Options given for compression other than CCITT T.6, ignoring\n) printErr
   } ifelse
 } if

 TIFFdict /JPEGTableOffset known {
   TIFFdict /Compression get 7 eq {
     IMAGEdict /DCTProc {
       /DCTTMPfile exch def /DCTfirsttime true def
       {DCTfirsttime {
           /DCTfirsttime false def DCTTable
         }{
           DCTTMPfile DCTTMPstr readstring pop
         } ifelse
       }
     } put
   }{
     (JPEGTable given for compression other than 7 (JPEG), ignoring\n) printErr
   } ifelse
 } if

 EPSdict /Recover get {
   TIFFdict /Compression get
   dup 2 eq {
     IMAGEdict /Decompression {<</EncodedByteAlign true /BlackIs1 true /Columns WOI /DamagedRowsBeforeError 10 >> /CCITTFaxDecode filter} put
     IMAGEdict /DecompressionString (    <</EncodedByteAlign true /BlackIs1 true /Columns OWOI /DamagedRowsBeforeError 10 >> /CCITTFaxDecode filter\n) put
   } if
   dup 3 eq {
     IMAGEdict /Decompression {<</BlackIs1 true /Columns WOI /DamagedRowsBeforeError 10 >> /CCITTFaxDecode filter} put
     IMAGEdict /DecompressionString (    <</BlackIs1 true /Columns OWOI /DamagedRowsBeforeError 10 >> /CCITTFaxDecode filter\n) put
     TIFFdict /T4Options known {
       TIFFdict /T4Options get 1 and % we takes care only of 0 bit
       1 eq {
         IMAGEdict /Decompression {<</K 1 /BlackIs1 true /Columns WOI /DamagedRowsBeforeError 10 >> /CCITTFaxDecode filter} put
         IMAGEdict /DecompressionString (    <</K 1 /BlackIs1 true /Columns OWOI /DamagedRowsBeforeError 10 >> /CCITTFaxDecode filter\n) put
       } if
     } if
   } if
   dup 4 eq {
     IMAGEdict /Decompression {<</K -1 /BlackIs1 true /Columns WOI /DamagedRowsBeforeError 10 >> /CCITTFaxDecode filter} put
     IMAGEdict /DecompressionString (    <</K -1 /BlackIs1 true /Columns OWOI /DamagedRowsBeforeError 10 >> /CCITTFaxDecode filter\n) put
   } if
   dup 32773 eq {
     IMAGEdict /Decompression {MyRunLengthDecode} put
     IMAGEdict /DecompressionString (    MyRunLengthDecode\n) put
   } if
 } if

 TIFFdict /FillOrder known {
   TIFFdict /FillOrder get
   dup 2 eq {
     IMAGEdict /FillOrderProc {
       /InFillOrderFile edef
       /FillOrderTmpString 255 string def
       <008040c020a060e0109050d030b070f0088848c828a868e8189858d838b878f8
        048444c424a464e4149454d434b474f40c8c4ccc2cac6cec1c9c5cdc3cbc7cfc
        028242c222a262e2129252d232b272f20a8a4aca2aaa6aea1a9a5ada3aba7afa
        068646c626a666e6169656d636b676f60e8e4ece2eae6eee1e9e5ede3ebe7efe
        018141c121a161e1119151d131b171f1098949c929a969e9199959d939b979f9
        058545c525a565e5159555d535b575f50d8d4dcd2dad6ded1d9d5ddd3dbd7dfd
        038343c323a363e3139353d333b373f30b8b4bcb2bab6beb1b9b5bdb3bbb7bfb
        078747c727a767e7179757d737b777f70f8f4fcf2faf6fef1f9f5fdf3fbf7fff>
        /binv exch def
       {
         InFillOrderFile FillOrderTmpString readstring pop
         dup length 1 sub 0 exch 1 exch {
           FillOrderTmpString exch binv FillOrderTmpString 2 index
           get get put
         } for
       } 0 () /SubFileDecode filter
     } put
   } if
   1 ne IMAGEdict /FillOrderProc known not and {
     (Unknown FillOrder value) printQuit
   } if
 } if

 EPSdict /Recover get {
   IMAGEdict /CheckStripProc {
     /InCheckStripFile edef
     /CheckStripTmpString WOI SPL idiv NOC mul BPS mul 8 div ceiling cvi string def
     /CheckStripBytes LOS RPS idiv
       ACTS NOS 1 sub eq {HOI RPS ACTS mul sub}{RPS} ifelse mul def
     {
       InCheckStripFile CheckStripTmpString readstring pop
       dup length dup CheckStripBytes gt {
         (Recover applied -- some extra bytes was discarded\n) printErr
         pop 0 CheckStripBytes getinterval
       }{
         0 eq CheckStripBytes 0 gt and {
           (Recover applied -- some missing bytes added\n) printErr
           pop CheckStripTmpString dup length CheckStripBytes gt {
             0 CheckStripBytes getinterval
           } if
         } if
       } ifelse
       /CheckStripBytes CheckStripBytes 2 index length sub def
     } 0 () /SubFileDecode filter
   } put
 } if

 TIFFdict /Predictor known {
   TIFFdict /Predictor get
   dup 2 eq {pop
     TIFFdict /Compression get
     dup 5 eq {
       IMAGEdict /Decompression {<</Predictor 2 /Columns WOI /Colors NOC /BitsPerComponent BPS>> /LZWDecode filter LOS () /SubFileDecode filter} put
       IMAGEdict /DecompressionString (    <</Predictor 2 /Columns OWOI /Colors NOC /BitsPerComponent BPS>> /LZWDecode filter LOS () /SubFileDecode filter\n) put
     } if
     dup 8 eq 1 index 32946 eq or {
       IMAGEdict /Decompression {<</Predictor 2 /Columns WOI /Colors NOC /BitsPerComponent BPS>> /FlateDecode filter} put
       IMAGEdict /DecompressionString (    <</Predictor 2 /Columns OWOI /Colors NOC /BitsPerComponent BPS>> /FlateDecode filter\n) put
     } if
     dup 5 ne exch dup 8 ne exch 32946 ne and and {
       IMAGEdict /PredictorProc {
         /InPredictorFile edef
         /PredictorTmpString WOI SPL idiv NOC mul string def
         {
           /LastPix [ NOC {0} repeat ] def /PredictorCount 0 def
           InPredictorFile PredictorTmpString readstring pop
           dup {
             LastPix PredictorCount NOC mod get add 256 mod dup
             LastPix exch PredictorCount NOC mod exch put
             PredictorTmpString PredictorCount 2 index put pop
             /PredictorCount PredictorCount 1 add def
           } forall
         } 0 () /SubFileDecode filter
       } put
     } if
   }{
     1 ne {(Unknown predictor coding) printQuit} if
   } ifelse
 } if

 TIFFdict /ExtraSamples known {
   TIFFdict /ExtraSamples get 0 gt {
     IMAGEdict /ExtraSamplesX known {
       TIFFdict /ExtraSamples get IMAGEdict /ExtraSamplesX get
       ne {(Inconsistent number of extra samples) printQuit} if
     }{
       (Inconsistent number of extra samples) printQuit
     } ifelse
     IMAGEdict /ExtraSamples TIFFdict /ExtraSamples get put
     IMAGEdict /ExtraSamplesProc {
       /InExtraSamplesFile edef
       /NRS NOC IMAGEdict /ExtraSamples get sub def /ONRS NRS def
       /IExtraSamplesString WOI SPL idiv NOC mul string def
       /OExtraSamplesString WOI SPL idiv NRS mul string def
       {
         /IExtraSamplesCount 0 def /OExtraSamplesCount 0 def
         InExtraSamplesFile IExtraSamplesString readstring pop
         length NOC idiv {
           OExtraSamplesString OExtraSamplesCount
           IExtraSamplesString IExtraSamplesCount NRS getinterval
           putinterval
           /OExtraSamplesCount OExtraSamplesCount NRS add def
           /IExtraSamplesCount IExtraSamplesCount NOC add def
         } repeat
         OExtraSamplesString
       } 0 () /SubFileDecode filter
     } put
   } if
 }{
   IMAGEdict /ExtraSamplesX known
   {(Inconsistent number of extra samples) printQuit} if
 } ifelse

 TIFFdict /TileWidth known
 TIFFdict /TileHeight known
 TIFFdict /TileOffsets known
 TIFFdict /TileByteCounts known
 4 copy and and and {
   (Can't process tiled image \(yet\)) printQuit
 } if
 or or or {
   (Can't process tiled image, especially malformed) printQuit
 } if

 TIFFdict /StripOffsets known not {
   IMAGEdict /StripsPerImage get 1 eq {
     (Image location not given -- assume that image begins right after header\n) printErr
     TIFFdict /StripOffsets [ returnfileposition ] put
   }{
     (Image location not given) printQuit
   } ifelse
 } if

 TIFFdict /StripByteCounts known not {
   IMAGEdict /StripsPerImage get 1 eq {
     (Image size not given -- will be guessed\n) printErr
     TIFFdict /Compression get 1 eq {
       TIFFdict /StripByteCounts [ IMAGEdict /Width get
         IMAGEdict /SamplesPerPixel get mul
         IMAGEdict /BitsPerComponent get mul 8 div ceiling cvi
         IMAGEdict /Height get mul ] put
     }{
       TIFFdict /StripByteCounts [ lengthofinfile
         TIFFdict /StripOffsets get 0 get sub ] put
     } ifelse
   }{
     (Image size not given -- can be guessed, but I newer seen such TIFF) printQuit
   } ifelse
 } if

 0 1 IMAGEdict /StripsPerImage get 1 sub {
    dup TIFFdict /StripOffsets get exch get
    exch TIFFdict /StripByteCounts get exch get
    add lengthofinfile gt {(Improper image location) printQuit} if
 } for

 IMAGEdict /StripsPerImage get 1 gt {
   IMAGEdict /MultiStripsProc {
     /InTMPFile edef
     /InTMPString WOI SPL idiv string def
     {
       {
         InTMPFile InTMPString readstring {
           exit
         }{
           ACTS NOS eq {
             exit
           }{
             PrepareNextStrip
             /InTMPFile edef
             dup length 0 eq {pop}{exit} ifelse
           } ifelse
         } ifelse
       } loop
     } 0 () /SubFileDecode filter
   } put
 } if

 /PrepareNextStrip {
   infile SOF ACTS get setfileposition
   infile SBC ACTS get () /SubFileDecode filter
   IMAGEdict /FillOrderProc known {IMAGEdict /FillOrderProc get exec} if
   IMAGEdict /DCTProc known {IMAGEdict /DCTProc get exec} if
   IMAGEdict /Decompression known {IMAGEdict /Decompression get exec} if
   IMAGEdict /CheckStripProc known {IMAGEdict /CheckStripProc get exec} if
   /ACTS ACTS 1 add def
 } def

 /NOS IMAGEdict /StripsPerImage get def
 /RPS TIFFdict /RowsPerStrip get def
 /SOF TIFFdict /StripOffsets get def
 /SBC TIFFdict /StripByteCounts get def
 /NOC IMAGEdict /SamplesPerPixel get def
 /NRS NOC def  % can be changed in ExtraSamplesProc
 /ONRS NRS def % can be changed by separation parameter
 /BPS IMAGEdict /BitsPerComponent get def
 /WOI IMAGEdict /Width get def
 /HOI IMAGEdict /Height get def
 /OWOI WOI def % can be changed by reduction parameter
 /OHOI HOI def % can be changed by reduction parameter
 /LOS WOI NOC mul BPS mul 8 div ceiling cvi RPS mul def % length of strip
 /ACTS 0 def
 /SPL 1 % strings per line (for very wide images)
 WOI NRS mul 65535 gt {
     {1 add
       WOI 1 index mod 0 eq {
         WOI 1 index idiv NRS mul 65535 lt {exit} if
      } if
   } loop
   dup 17 ge {% beautiful Gaussian number
     (Very wide image, may be processed slowly\n) printCon
   } if
 } if def

 IMAGEdict /DCTProc known {
   /DCTTO TIFFdict /JPEGTableOffset get def
   /DCTTL TIFFdict /JPEGTableLength get 2 sub def % without EOI mark
   /DCTTMPstr 4096 string def
   infile DCTTO testandsetfileposition
   /DCTTable infile DCTTL string readstring pop def
   0 1 NOS 1 sub {dup         % and here without SOI mark
     SOF exch 2 copy get 2 add put
     SBC exch 2 copy get 2 sub put
   } for
 } if

 PrepareNextStrip
 IMAGEdict /MultiStripsProc known {IMAGEdict /MultiStripsProc get exec} if
 IMAGEdict /PredictorProc known {IMAGEdict /PredictorProc get exec} if
 IMAGEdict /ExtraSamplesProc known {IMAGEdict /ExtraSamplesProc get exec} if
 IMAGEdict /DataSource 2 index put pop

} def

/Showdict {{exch (\t) print =only (\t) print ==} forall} def
/ShowTIFFDict {% debugging
 EPSdict /Verbose get 2 ge {
   (\n\nTIFF (input) dictionary:\n) print
   TIFFdict Showdict
 } if
} def
/ShowImageDict {% debugging
 EPSdict /Verbose get 2 gt {
   (\n\nImage (inner) dictionary:\n) print
   IMAGEdict Showdict
 } if
} def
/ShowEPSDict {% debugging
 EPSdict /Verbose get 2 gt {
   (\n\nEPS (output) dictionary:\n) print
   EPSdict Showdict
 } if
} def

/ImageImageDict {% for future use
 0 0 translate
 IMAGEdict /XScale get IMAGEdict /YScale get scale
 IMAGEdict /ColorSpace get aload pop setcolorspace
 IMAGEdict image
 showpage
} def

/concatstrings {
 exch dup length 2 index length add string % str2 str1 new
 dup dup 4 2 roll copy        % str2 new new new1
 length 4 -1 roll putinterval
} bind def

/OTmpStr 256 string def
/OWrtStr {oufile exch writestring} def
/writenumber {
 load OTmpStr cvs OWrtStr (\n) OWrtStr
} def
/putnumber {
 (  /) OWrtStr dup OTmpStr cvs OWrtStr ( ) OWrtStr
 load OTmpStr cvs OWrtStr (\n) OWrtStr
} def
/defnumber {
 (  /) OWrtStr dup OTmpStr cvs OWrtStr ( ) OWrtStr
 load OTmpStr cvs OWrtStr ( def\n) OWrtStr
} def
/writematrix {
 ( [ ) OWrtStr load { OTmpStr cvs OWrtStr ( ) OWrtStr} forall (]\n) OWrtStr
} def
/putmatrix {
 (  /) OWrtStr dup OTmpStr cvs OWrtStr writematrix
} def
/defarray {
 (  /) OWrtStr dup OTmpStr cvs OWrtStr ( [ ) OWrtStr
 load /i 0 def {
   OTmpStr cvs OWrtStr
   /i i 1 add def i 8 mod 0 eq {(\n    )}{( )} ifelse OWrtStr
 } forall
 (] def\n) OWrtStr
} def

/writepalettecolorspace {
 ([) OWrtStr ColorSpace {
   dup type dup /stringtype eq {
     pop (<) OWrtStr
     /i 13 def {
       16 OTmpStr cvrs dup length 1 eq {(0) OWrtStr} if OWrtStr
       /i i 1 add def i 33 mod 0 eq { (\n) OWrtStr} if
     } forall
     (>) OWrtStr
   }{
     /nametype eq {(/) OWrtStr} if
     OTmpStr cvs OWrtStr
   } ifelse ( ) OWrtStr
 } forall (]) OWrtStr
} def

/movedictentry {EPSdict exch dup IMAGEdict exch get put} def
/MakeEPSdict {
 /Height           movedictentry
 /Width            movedictentry
 /BitsPerComponent movedictentry
 /ImageMatrix      movedictentry
 /XScale           movedictentry
 /YScale           movedictentry
 /ColorSpace       movedictentry
 /Decode           movedictentry
 EPSdict /ColorSpace get length 1 gt
 EPSdict /PSLevel get 2 lt and {
   (Can't make Level 1 EPS from TIFF width palette colorspace) printQuit
 } if
 EPSdict /PSImagemask get 0 gt
 EPSdict /BitsPerComponent get 1 eq
 EPSdict /Decode get length 2 eq and and {
   EPSdict /PSImagemask get 2 eq {
     EPSdict /Decode 2 copy get aload 3 1 roll exch 3 -1 roll astore put
   } if
   EPSdict /ColorSpace [] put
   EPSdict /ImageOperator (imagemask\n) put
 }{
   EPSdict /ImageOperator (image\n) put
 } ifelse
 EPSdict /Reduction known {
   EPSdict /BitsPerComponent get 8 ne EPSdict /HeaderForm get or {
     EPSdict /Reduction undef
     EPSdict /HeaderForm get {
       (Reduce in header form makes no sense, ignoring `-r'\n) printCon
     }{
       (Can't reduce: sample takes less than byte, ignoring `-r'\n) printErr
     } ifelse
   }{
     EPSdict begin
       /Height Height 1 sub Reduction mul floor 1 add cvi def
       /Width  Width  1 sub Reduction mul floor 1 add cvi def
       TIFFdict /Orientation get % remake ImageMatrix
        dup 1 eq { /ImageMatrix [Width 0 0 Height neg 0 Height] def} if
        dup 2 eq { /ImageMatrix [Width neg 0 0 Height neg Width Height] def} if
        dup 3 eq { /ImageMatrix [Width neg 0 0 Height Width 0] def} if
        dup 4 eq { /ImageMatrix [Width 0 0 Height 0 0] def} if
        dup 5 eq { /ImageMatrix [0 Width neg Height 0 Width] def} if
        dup 6 eq { /ImageMatrix [0 Width neg Height neg 0 Height Width] def} if
        dup 7 eq { /ImageMatrix [0 Width Height neg 0 Height 0] def} if
            8 eq { /ImageMatrix [0 Width Height 0 0 0] def} if
     end
     /OWOI EPSdict /Width get def
     /OHOI EPSdict /Height get def
   } ifelse
 } if
 EPSdict /OutCompression get dup (CT3) eq exch (CT4) eq or
 EPSdict /BitsPerComponent get 1 ne and {
   (CCITTFax compression makes sense only for black-and-white bitmaps, ignoring `-f'\n) printErr
   EPSdict /OutDataComEncode {} put
   EPSdict /OutDataComClose  {} put
   EPSdict /OutDataComSource () put
 } if
 EPSdict /OutCompression get (JPG) eq
 EPSdict /BitsPerComponent get 8 ne and {
   (DCT compression makes sense only for gray, RGB ans CMYK bitmaps, ignoring `-f'\n) printErr
   EPSdict /OutDataComEncode {} put
   EPSdict /OutDataComClose  {} put
   EPSdict /OutDataComSource () put
 } if

 EPSdict /Separation known {
 EPSdict /ColorSpace get 0 get /DeviceCMYK ne {
     (Can't separate: mode other than CMYK, ignoring `-s'\n) printErr
   }{
     EPSdict /ColorSpace [/DeviceGray] put
     EPSdict /Decode [1 0] put
     /ONRS 1 def
   } ifelse
 }if
} def

/WriteDSComments {
 (%!PS-Adobe-3.0 EPSF-3.0\n) OWrtStr
 (%%BoundingBox: 0 0 ) OWrtStr
 ExactBB not {
   XScale ceiling cvi OTmpStr cvs OWrtStr ( ) OWrtStr
   YScale ceiling cvi OTmpStr cvs OWrtStr
   (\n%%HiResBoundingBox: 0 0 ) OWrtStr
 } if
 XScale 1000 mul ceiling 1000 div OTmpStr cvs OWrtStr ( ) OWrtStr
 YScale 1000 mul ceiling 1000 div OTmpStr cvs OWrtStr
 (\n%%Creator: TIF2EPS ver. 0.79 / ) OWrtStr
 product OWrtStr ( ) OWrtStr revision OTmpStr cvs OWrtStr (\n) OWrtStr
} def

/WriteImageParams {
   /OWOI defnumber
   /OHOI defnumber
   /ONRS defnumber
   /BPS defnumber
} def

/WriteImageCommand {
   (0 0 translate\n) OWrtStr
   XScale OTmpStr cvs OWrtStr ( ) OWrtStr YScale OTmpStr cvs OWrtStr ( scale\n) OWrtStr
   ColorSpace length 0 ne {
     ColorSpace length 1 eq {
       (/) OWrtStr ColorSpace 0 get OTmpStr cvs OWrtStr
     }{
       writepalettecolorspace
     } ifelse ( setcolorspace\n) OWrtStr
   } if
   (<<% ImageDictionary\n) OWrtStr
   (  /ImageType 1\n) OWrtStr
   /Width            putnumber
   /Height           putnumber
   /ImageMatrix      putmatrix
   (  /DataSource currentfile ) OWrtStr
   OutDataEncSource OWrtStr OutDataComSource OWrtStr (\n) OWrtStr
   /BitsPerComponent putnumber
   /Decode           putmatrix
   PSInterpolate {
     (  /Interpolate true\n) OWrtStr
   } if
   (>>\n) OWrtStr
   ImageOperator OWrtStr
} def

/WriteImageCommandOne {
   (/picstr OWOI string def\n) OWrtStr
   (0 0 translate\n) OWrtStr
   XScale OTmpStr cvs OWrtStr ( ) OWrtStr YScale OTmpStr cvs OWrtStr ( scale\n) OWrtStr
   ColorSpace length 1 eq Decode 0 get 1 eq and {
     ({1 exch sub} settransfer\n) OWrtStr
   } if
   (OWOI OHOI ) OWrtStr
   ColorSpace length 0 eq {
     Decode 0 get 1 eq {(true\n)}{(false\n)} ifelse
   }{
     (BPS\n)
   } ifelse OWrtStr
   /ImageMatrix writematrix
   ({currentfile picstr readhexstring pop}\n) OWrtStr
   ONRS 1 eq {
     ImageOperator
   }{
     (false ONRS colorimage\n)
   } ifelse OWrtStr
} def

/WriteEPSHeader {
 EPSdict begin
   WriteDSComments
   WriteImageParams
   PSLevel 2 eq {
     WriteImageCommand
   }{
     WriteImageCommandOne
   } ifelse
 end
} def

/definestring {
 /dtmpstr () def {
   /dtmpstr dtmpstr
   currentfile =string readline not
   {(Shouldn't happen -- unexpected end of file) printQuit} if
   (%END) anchorsearch {pop pop pop pop exit} if
   concatstrings (\n) concatstrings def
 } loop
 dtmpstr def
} def

% BEGIN of FillOrder procedure string
/FillOrderProcString definestring
/FillOrderProc {
 /InFillOrderFile exch def
 /FillOrderTmpString 255 string def
 <008040c020a060e0109050d030b070f0088848c828a868e8189858d838b878f8
  048444c424a464e4149454d434b474f40c8c4ccc2cac6cec1c9c5cdc3cbc7cfc
  028242c222a262e2129252d232b272f20a8a4aca2aaa6aea1a9a5ada3aba7afa
  068646c626a666e6169656d636b676f60e8e4ece2eae6eee1e9e5ede3ebe7efe
  018141c121a161e1119151d131b171f1098949c929a969e9199959d939b979f9
  058545c525a565e5159555d535b575f50d8d4dcd2dad6ded1d9d5ddd3dbd7dfd
  038343c323a363e3139353d333b373f30b8b4bcb2bab6beb1b9b5bdb3bbb7bfb
  078747c727a767e7179757d737b777f70f8f4fcf2faf6fef1f9f5fdf3fbf7fff>
 /binv exch def
 {
   InFillOrderFile FillOrderTmpString readstring pop
   dup length 1 sub 0 exch 1 exch {
     FillOrderTmpString exch binv FillOrderTmpString 2 index
     get get put
   } for
 } 0 () /SubFileDecode filter
} def
%END
% BEGIN of DCTProc procedure string
/DCTProcString definestring
/DCTProcInit {
 /DCTTMPstr 4096 string def
 infile DCTTO setfileposition
 /DCTTable infile DCTTL string readstring pop def
} def
/DCTProc {
 /DCTTMPfile exch def /DCTfirsttime true def
 {DCTfirsttime {
     /DCTfirsttime false def DCTTable
   }{
     DCTTMPfile DCTTMPstr readstring pop
   } ifelse
 }
} def
%END
% BEGIN of MultiStrips procedure string
/MultiStripsProcString definestring
% Multi Strips Procedure
/MultiStripsProc {
 /InTMPFile exch def
 /InTMPString OWOI SPL idiv string def
 {
   {
     InTMPFile InTMPString readstring {
       exit
     }{
       ACTS NOS eq {
         exit
       }{
         PrepareNextStrip
         /InTMPFile exch def
         dup length 0 eq {pop}{exit} ifelse
       } ifelse
     } ifelse
   } loop
 } 0 () /SubFileDecode filter
} def
%END
% BEGIN of Predictor procedure string
/PredictorProcString definestring
% Predictor Procedure
/PredictorProc {
 /InPredictorFile exch def
 /PredictorTmpString OWOI SPL idiv NOC mul string def
 {
   /LastPix [ NOC {0} repeat ] def /PredictorCount 0 def
   InPredictorFile PredictorTmpString readstring pop
   dup {
     LastPix PredictorCount NOC mod get add 256 mod dup
     LastPix exch PredictorCount NOC mod exch put
     PredictorTmpString PredictorCount 2 index put pop
     /PredictorCount PredictorCount 1 add def
   } forall
 } 0 () /SubFileDecode filter
} def
%END
% BEGIN of ExtraSamples procedure string
/ExtraSamplesProcString definestring
% Extra Samples Procedure
/ExtraSamplesProc {
 /InExtraSamplesFile exch def
 /IExtraSamplesString OWOI SPL idiv NOC mul string def
 /OExtraSamplesString OWOI SPL idiv NRS mul string def
 {
   /IExtraSamplesCount 0 def /OExtraSamplesCount 0 def
   InExtraSamplesFile IExtraSamplesString readstring pop
   length NOC idiv {
     OExtraSamplesString OExtraSamplesCount
     IExtraSamplesString IExtraSamplesCount NRS getinterval
     putinterval
     /OExtraSamplesCount OExtraSamplesCount NRS add def
     /IExtraSamplesCount IExtraSamplesCount NOC add def
   } repeat
   OExtraSamplesString
 } 0 () /SubFileDecode filter
} def
%END
% BEGIN of Recover string
/RecoverString definestring
% Recover procedures
/CheckStripProc {
 /InCheckStripFile exch def
 /CheckStripTmpString OWOI SPL idiv NOC mul BPS mul 8 div ceiling cvi string def
 /CheckStripBytes CheckStripTmpString length SPL mul
   ACTS NOS 1 sub eq {OHOI RPS ACTS mul sub}{RPS} ifelse mul def
 {
   InCheckStripFile CheckStripTmpString readstring pop
   dup length dup CheckStripBytes gt {
     pop 0 CheckStripBytes getinterval
   }{
     0 eq CheckStripBytes 0 gt and {
           pop CheckStripTmpString dup length CheckStripBytes gt {
         0 CheckStripBytes getinterval
       } if
     } if
   } ifelse
   /CheckStripBytes CheckStripBytes 2 index length sub def
 } 0 () /SubFileDecode filter
} def
/MyRunLengthDecode{
 /MRLETmpString 129 string def
 /RLEFile exch def
 {RLEFile read {
   dup 127 le {
     1 add MRLETmpString exch 0 exch getinterval RLEFile exch readstring pop
     % there should be enough data -- if not decode what is
   }{
     257 exch sub MRLETmpString exch 0 exch getinterval
     RLEFile read {
       0 1 3 index length 1 sub {2 index exch 2 index put} for pop
     }{
       () % in case when count=128 and it meaning is EOD -- according
          % to specification
     } ifelse
   } ifelse
 }{()} ifelse
 } 0 () /SubFileDecode filter
} def
%END
% BEGIN of Separation string
/SeparationProcString definestring
% Separation Procedure
/SeparationProc {
 /TmpSepFile exch def /TmpSepString NRS OWOI mul string def
 {
   TmpSepFile TmpSepString readstring pop 0
   SEP NRS 3 index length 1 sub {
     2 index exch get
     3 copy put pop
     1 add
   } for
   dup 0 ne {0 exch getinterval}{pop pop ()} ifelse
 } 0 () /SubFileDecode filter
} def
%END
% BEGIN of PrepareFile string
/PrepareFileString definestring
 /TIFFDirectory where {
   /TIFFDirectory get
   dup length dup ifn length add string dup dup
   4 -1 roll ifn putinterval
   0 4 -1 roll putinterval
   /ifn exch def
 } if
 ifn status {
   pop pop pop pop
 }{
   (!!!TIFF input ) print ifn print ( not found!!!) print quit
 } ifelse
 /infile ifn (r) file def
%  infile bytesavailable LOT ne
%  infile 4096 LOT 2 copy gt{exch} if pop string readstring pop
%  0 exch {exch 314159265 mod 3 mul add} forall CRC ne or {
%    (!!!TIFF input ) print ifn print ( was changed!!!) print quit
%  } if
 /PrepareNextStrip {
   infile SOF ACTS get setfileposition
   infile SBC ACTS get () /SubFileDecode filter
%END

/PrepareTIFFName {
 /tfn ifn def
 tfn length 1 sub -1 0 {
   dup tfn exch get dup 47 eq exch 92 eq or {
     1 add tfn exch tfn length 1 index sub getinterval /tfn edef exit
   } if
 } for
} def

/writepreparefilteredfile {
 /NOS defnumber
 /SOF defarray
 /SBC defarray
 /RPS defnumber
 /NRS defnumber
 /NOC defnumber
 /SPL defnumber
 /LOS defnumber
 /LOT defnumber
 /CRC defnumber
 (% Procedures for filtering TIFF data\n) OWrtStr
 IMAGEdict /FillOrderProc known    {FillOrderProcString OWrtStr} if
 IMAGEdict /MultiStripsProc known  {MultiStripsProcString OWrtStr} if
 IMAGEdict /DCTProc known          {DCTProcString OWrtStr} if
 IMAGEdict /PredictorProc known    {PredictorProcString OWrtStr} if
 IMAGEdict /ExtraSamplesProc known {ExtraSamplesProcString OWrtStr} if
 EPSdict /Recover get              {RecoverString OWrtStr} if
 EPSdict /Separation known         {SeparationProcString OWrtStr} if
 (% Preparing TIFF data source\n) OWrtStr
 (  /ifn \() OWrtStr tfn OWrtStr (\) def\n) OWrtStr
 PrepareFileString OWrtStr
 IMAGEdict /FillOrderProc known {(  FillOrderProc\n) OWrtStr} if
 IMAGEdict /DCTProc known {(    DCTProc\n) OWrtStr} if
 IMAGEdict /DecompressionString known {
   IMAGEdict /DecompressionString get OWrtStr
 } if
 EPSdict /Recover get {(  CheckStripProc\n) OWrtStr} if
 (    /ACTS ACTS 1 add def\n) OWrtStr
 (  } def\n) OWrtStr % end of PrepareNextStrip procedure
 EPSdict /Separation known {
   (  /SEP ) OWrtStr EPSdict /Separation get OTmpStr cvs OWrtStr
   ( def\n) OWrtStr
 } if
 (  /ACTS 0 def\n) OWrtStr
 IMAGEdict /DCTProc known {
   /DCTTO defnumber
   /DCTTL defnumber
   (DCTProcInit\n) OWrtStr
 } if
 (  PrepareNextStrip\n) OWrtStr
 IMAGEdict /MultiStripsProc known  {(  MultiStripsProc\n) OWrtStr} if
 IMAGEdict /PredictorProc known    {(  PredictorProc\n) OWrtStr} if
 IMAGEdict /ExtraSamplesProc known {(  ExtraSamplesProc\n) OWrtStr} if
 EPSdict   /Separation known       {(  SeparationProc\n) OWrtStr} if
 (  /filteredfile exch def\n) OWrtStr
 (% End of preparing TIFF data source\n) OWrtStr
} def

/WriteHeaderEPS {
 EPSdict begin
   PrepareTIFFName
   WriteDSComments
   (%%DocumentNeededResources: file ) OWrtStr tfn OWrtStr (\n) OWrtStr
   WriteImageParams
   writepreparefilteredfile
   WriteImageCommand
 end
   WriteEPSTrailer
} def

/ticnum 0 def  /tacnum 0 def
/TicTac {
 /ticnum ticnum 1 add def {
   ticnum HOI div tacnum 40 div ge {
     tacnum 10 mod 0 eq {(:)}{(.)} ifelse printCon flush
     /tacnum tacnum 1 add def
   }{exit} ifelse
 } loop % ;-)
} def

/WriteEPSData {
 EPSdict begin
   /ICopyFile IMAGEdict /DataSource get def
   /OCopyFile OutDataEncEncode OutDataComEncode def
   /IOutString WOI SPL idiv NRS mul string def
   EPSdict /Reduction known {
     EPSdict /Separation known {
       /MSEP Separation def
       /get_write_proc {get write} def
     }{
       /MSEP 0 def
       /get_write_proc {NRS getinterval writestring} def
     } ifelse
     /ACTH 0 def /ACTNH 0 def
     HOI {
       ACTH Reduction mul ACTNH ge {
         /ACTW 0 def /ACTNW 0 def
         SPL {
           ICopyFile IOutString readstring pop pop
           /ACTSW MSEP def
           WOI SPL idiv {
             ACTW Reduction mul ACTNW ge {
               OCopyFile IOutString ACTSW get_write_proc
               /ACTNW ACTNW 1 add def
             } if
             /ACTW ACTW 1 add def /ACTSW ACTSW NRS add def
           } repeat
         } repeat
         /ACTNH ACTNH 1 add def
       }{
         SPL {ICopyFile IOutString readstring pop pop} repeat
       } ifelse
       /ACTH ACTH 1 add def
       TicTac
     } repeat
   }{
     EPSdict /Separation known {
       OCopyFile IOutString 2 copy
       HOI {
         SPL {
           ICopyFile IOutString readstring pop pop
           Separation NRS dup WOI SPL idiv mul 1 sub {
             get write 2 copy
           } for
         } repeat
         TicTac
       } repeat pop pop pop pop
     }{
       OCopyFile ICopyFile IOutString
       HOI {
         SPL {
           3 copy readstring pop writestring
         } repeat
           TicTac
       } repeat pop pop pop
     } ifelse
   } ifelse
   OCopyFile flushclosefile OutDataComClose OutDataEncClose
 end
} def

/WriteEPSTrailer {
 (\n%%EOF) OWrtStr
 oufile flushclosefile
} def

/truncext {% (filename.ext) truncext (filename)
 /fnm edef
 fnm length 1 sub -1 0 {
   dup fnm exch get dup 46 eq {
     pop fnm exch 0 exch getinterval /fnm edef exit
   } if
   dup 47 eq {pop exit} if
   92 eq {exit} if
   pop
 } for
 fnm
} def

/CheckFiles {
 EPSdict /InputFilename known {
   EPSdict /InputFilename get /ifn edef
   ifn status {
     pop pop pop pop
   }{
     ifn (.tif) concatstrings status {
       pop pop pop pop /ifn ifn (.tif) concatstrings def
     }{
       (Input file not found) printQuit
     } ifelse
   } ifelse
 }{
   (Input filename unknown) printQuit
 } ifelse
 /infile ifn (r) file def
 /lengthofinfile infile bytesavailable def
 /LOT lengthofinfile def
 infile 4096 LOT 2 copy gt{exch} if pop string readstring pop
 0 exch {exch 314159265 mod 3 mul add} forall /CRC edef
 infile 0 setfileposition

 EPSdict /OutputFilename known {
   EPSdict /OutputFilename get
 }{
   ifn truncext EPSdict /EPSextension get concatstrings
 } ifelse
 /ofn edef

 ifn ofn eq {
   (Input and output filenames must differ) printQuit
 } if
 EPSdict /Overwrite get 1 ne {
   ofn status {
     EPSdict /Overwrite get 0 eq {
       pop pop pop pop
       (Output file exists \(use option `-o' to overwrite\)) printQuit
     }{
       % Using `referenced' (interpreted by Ghostscript as the `modification
       % time', which doesn't comply with the specification of PostScript)
       % instead of `created' (the `creation time') is most preferable
       % for comparison.
       pop 3 1 roll pop pop
       ifn status pop pop 3 1 roll pop pop
       gt {
         (Output file is newer than source \(use option `-o' to overwrite\)) printQuit
       } if
     } ifelse
   } if
 } if

} def

/MyASCII85Encode{
 /InnerASCIIstring 4096 string def
 {pop (%) anchorsearch {pop oufile ( %) writestring} if
   {(\n%) search not {exit} if
    oufile exch writestring pop oufile (\n %) writestring} loop
 oufile exch writestring InnerASCIIstring} /NullEncode filter
 dup /InnerASCIIfile edef /ASCII85Encode filter
} def

/MyASCIIHexEncode{
 /InnerASCIIstring 4096 string def
 {pop (>) search {exch pop exch pop} if
  oufile exch writestring InnerASCIIstring}
 /ASCIIHexEncode filter
} def

/MyRunLengthDecode{
 /MRLETmpString 129 string def
 /RLEFile exch def
 {RLEFile read {
   dup 127 le {
     1 add MRLETmpString exch 0 exch getinterval RLEFile exch readstring pop
     % there should be enough data -- if not decode what is
   }{
     257 exch sub MRLETmpString exch 0 exch getinterval
     RLEFile read {
       0 1 3 index length 1 sub {2 index exch 2 index put} for pop
     }{
       () % in case when count=128 and it meaning is EOD -- according
          % to specification
     } ifelse
   } ifelse
 }{()} ifelse
 } 0 () /SubFileDecode filter
} def

/PrepareOutParams {
 EPSdict /Overwrite get 2 gt {(Odd option -o#\n) printErr} if
 EPSdict /PSLevel get dup 2 eq {pop}{
   1 eq {
     EPSdict /OutCompression get (NON) ne {
       EPSdict /OutCompression (NON) put
     } if
     EPSdict /OutCoding get (HEX) ne {
       EPSdict /OutCoding (HEX) put
     } if
     EPSdict /HeaderForm get {
       EPSdict /HeaderForm false put
     } if
     EPSdict /PSInterpolate get {
       EPSdict /PSInterpolate false put
     } if
   }{
     (Only Level 1 and 2 are supported -- assuming Level 2\n) printErr
     EPSdict /PSLevel 2 put
   } ifelse
 } ifelse
 EPSdict /Verbose get 1 ge {
   /printCon {print} def
 }{
   /printCon {pop} def
 } ifelse
 % Coding
 EPSdict /OutCoding get (A85) eq {
   EPSdict /SpecialASCII85 known {
     EPSdict /OutDataEncEncode /MyASCII85Encode load put
     EPSdict /OutDataEncClose  {InnerASCIIfile flushclosefile} put
   }{
     EPSdict /OutDataEncEncode {oufile /ASCII85Encode filter} put
     EPSdict /OutDataEncClose  {} put
   } ifelse
   EPSdict /OutDataEncSource (/ASCII85Decode filter) put
 } if
 EPSdict /OutCoding get (HEX) eq {
   EPSdict /PSLevel get 1 eq {
     EPSdict /OutDataEncEncode /MyASCIIHexEncode load put
     EPSdict /OutDataEncClose  {} put
     EPSdict /OutDataEncSource () put
   }{
     EPSdict /OutDataEncEncode {oufile /ASCIIHexEncode filter} put
     EPSdict /OutDataEncClose  {} put
     EPSdict /OutDataEncSource (/ASCIIHexDecode filter) put
   } ifelse
 } if
 % Compression
 EPSdict /OutCompression get (RLE) eq {
   EPSdict /OutDataComEncode {dup /COMPRfile edef 0 /RunLengthEncode filter} put
   EPSdict /OutDataComClose  {COMPRfile flushclosefile} put
   EPSdict /OutDataComSource ( /RunLengthDecode filter) put
 } if
 EPSdict /OutCompression get (FLA) eq {
   EPSdict /OutDataComEncode {dup /COMPRfile edef /FlateEncode filter} put
   EPSdict /OutDataComClose  {COMPRfile flushclosefile} put
   EPSdict /OutDataComSource ( /FlateDecode filter) put
 } if
 EPSdict /OutCompression get (LZW) eq {
   EPSdict /OutDataComEncode {dup /COMPRfile edef /LZWEncode filter} put
   EPSdict /OutDataComClose  {COMPRfile flushclosefile} put
   EPSdict /OutDataComSource ( /LZWDecode filter) put
 } if
 EPSdict /OutCompression get (L-P) eq {
   EPSdict /OutDataComEncode {dup /COMPRfile edef <</Predictor 2 /Columns OWOI
     /Colors ONRS /BitsPerSample BPS>> /LZWEncode filter} put
   EPSdict /OutDataComClose  {COMPRfile flushclosefile} put
   EPSdict /OutDataComSource ( <</Predictor 2 /Columns OWOI /Colors ONRS /BitsPerSample BPS>> /LZWDecode filter) put
 } if
 EPSdict /OutCompression get (CT3) eq {
   EPSdict /OutDataComEncode {dup /COMPRfile edef <</K 0 /Columns OWOI>> /CCITTFaxEncode filter} put
   EPSdict /OutDataComClose  {COMPRfile flushclosefile} put
   EPSdict /OutDataComSource ( <</K 0 /Columns OWOI>> /CCITTFaxDecode filter) put
 } if
 EPSdict /OutCompression get (CT4) eq {
   EPSdict /OutDataComEncode {dup /COMPRfile edef <</K -1 /Columns OWOI>> /CCITTFaxEncode filter} put
   EPSdict /OutDataComClose  {COMPRfile flushclosefile} put
   EPSdict /OutDataComSource ( <</K -1 /Columns OWOI>> /CCITTFaxDecode filter) put
 } if
 EPSdict /OutCompression get (JPG) eq {
   EPSdict /OutDataComEncode {dup /COMPRfile edef <</Columns OWOI /Rows OHOI /Colors ONRS>> /DCTEncode filter} put
   EPSdict /OutDataComClose  {COMPRfile flushclosefile} put
   EPSdict /OutDataComSource ( /DCTDecode filter) put
 } if
 EPSdict /OutCompression get (NON) eq {
   EPSdict /OutDataComEncode {} put
   EPSdict /OutDataComClose  {} put
   EPSdict /OutDataComSource () put
 } if
 EPSdict /HeaderForm get {
   EPSdict /OutDataEncSource (pop filteredfile) put
   EPSdict /OutCompression get (NON) ne {
     (For header EPSs compression makes no sense, ignoring `-f'\n) printErr
     EPSdict /OutDataComSource () put
   } if
 } if
} def

/ProcessBooleanFlag {
 mark 3 index dup
 dup (+) eq exch dup (1) eq exch () eq or or {true exch} if
 dup (-) eq exch (0) eq or {false} if
 counttomark 1 eq {
  exch pop EPSdict 3 1 roll put
  pop pop
 }{
   cleartomark pop
   (Odd option ) printErr printErr printErr (\n) printErr
 } ifelse ()
} def
/ProcessIntFlag {
 mark 3 index
 dup dup (-) eq exch (0) eq or {0 exch} if
 dup dup (+) eq exch dup (1) eq exch () eq or or {1 exch} if
 dup (2) eq {2 exch} if
 dup (3) eq {3 exch} if
 (4) eq {4} if
 counttomark 1 eq {
  exch pop EPSdict 3 1 roll put
  pop pop
 }{
   cleartomark pop
   (Odd option ) printErr printErr printErr (\n) printErr
 } ifelse ()
} def

/FixHeaderForm {/HeaderForm ProcessBooleanFlag} def
/FixPSInterpolate {/PSInterpolate ProcessBooleanFlag} def
/FixBB {/ExactBB ProcessBooleanFlag} def
/FixRecover {/Recover ProcessBooleanFlag} def
/FixImagemask {/PSImagemask ProcessIntFlag} def
/FixOverwrite {/Overwrite ProcessIntFlag} def
/FixVerbose {/Verbose ProcessIntFlag} def
/FixLevel {/PSLevel ProcessIntFlag} def
/FixPageN {
 pop {cvi} stopped {
   (Page number must be a number) printQuit
 } if
 dup 0 ge {
   EPSdict /PageNumber 2 index put pop
 }{
   (Negative page number -p) printErr =string cvs printQuit
 } ifelse ()
} def
/FixReduction {
 pop {cvr} stopped {
   (Reduction factor must be a number) printQuit
 } if
 dup dup 1 le exch 0 gt and {
   EPSdict /Reduction 2 index put pop
 }{
   (Improper reduction factor -r) printErr =string cvs printQuit
 } ifelse ()
} def
/FixResolution {
 pop (x) search dup not {pop (X) search} if
 {
   checkresolution EPSdict /XResolution 2 index put pop pop
   checkresolution EPSdict /YResolution 2 index put pop
 }{
   checkresolution EPSdict /XResolution 2 index put
                   EPSdict /YResolution 2 index put pop
 } ifelse ()
} def
/checkresolution {
 {cvr} stopped {(Resolution must be a number) printQuit} if
 dup 1 lt {(Resolution can't be lower than 1 dpi) printQuit} if
} def
/FixSeparation {
 pop
 dup dup (1) eq exch dup (c) eq exch (C) eq or or {EPSdict /Separation 0 put EPSdict /EPSextension (.c) put} if
 dup dup (2) eq exch dup (m) eq exch (M) eq or or {EPSdict /Separation 1 put EPSdict /EPSextension (.m) put} if
 dup dup (3) eq exch dup (y) eq exch (Y) eq or or {EPSdict /Separation 2 put EPSdict /EPSextension (.y) put} if
 dup dup (4) eq exch dup (k) eq exch (K) eq or or {EPSdict /Separation 3 put EPSdict /EPSextension (.k) put} if
 EPSdict /Separation known not {
   (Improper separation -s) printErr printQuit
 }{pop} ifelse ()
} def
/FixFilter {
 pop {
   1 string dup 0 3 index put exch pop
   dup dup (f) eq exch (F) eq or {EPSdict /OutCompression (FLA) put} if
   dup dup (l) eq exch (L) eq or {EPSdict /OutCompression (LZW) put} if
   dup dup (p) eq exch (P) eq or {EPSdict /OutCompression (L-P) put} if
   dup dup (r) eq exch (R) eq or {EPSdict /OutCompression (RLE) put} if
                      dup (3) eq {EPSdict /OutCompression (CT3) put} if
                      dup (4) eq {EPSdict /OutCompression (CT4) put} if
   dup dup (j) eq exch (J) eq or {EPSdict /OutCompression (JPG) put} if
   dup dup (n) eq exch (N) eq or {EPSdict /OutCompression (NON) put} if
   dup dup (h) eq exch (H) eq or {EPSdict /OutCoding (HEX) put} if
                          (8) eq {EPSdict /OutCoding (A85) put} if
 } forall ()
} def
/FixFileNames {
 EPSdict /InputFilename known {
   EPSdict /OutputFilename known {
     (Bad parametr ) printErr printErr (\n) printErr
   }{
     EPSdict /OutputFilename 2 index put pop
   } ifelse
 }{
   EPSdict /InputFilename 2 index put pop
 } ifelse
} def

/SetDefaultParams {
 EPSdict /OutCoding (A85) put
 EPSdict /OutCompression (NON) put
 EPSdict /EPSextension (.eps) put
 EPSdict /HeaderForm false put
 EPSdict /PSInterpolate false put
 EPSdict /ExactBB true put
 EPSdict /Recover false put
 EPSdict /Overwrite 0 put
 EPSdict /Verbose 1 put
 EPSdict /PSImagemask 0 put
 EPSdict /PSLevel 2 put
} def

/ProcessParams {
 SetDefaultParams
 {
   (-f) anchorsearch {FixFilter} if        (-F) anchorsearch {FixFilter} if
   (-r) anchorsearch {FixReduction} if     (-R) anchorsearch {FixReduction} if
   (-d) anchorsearch {FixResolution} if    (-D) anchorsearch {FixResolution} if
   (-s) anchorsearch {FixSeparation} if    (-S) anchorsearch {FixSeparation} if
   (-v) anchorsearch {FixVerbose} if       (-V) anchorsearch {FixVerbose} if
   (-l) anchorsearch {FixLevel} if         (-L) anchorsearch {FixLevel} if
   (-p) anchorsearch {FixPageN} if         (-P) anchorsearch {FixPageN} if
   (-o) anchorsearch {FixOverwrite} if     (-O) anchorsearch {FixOverwrite} if
   (-h) anchorsearch {FixHeaderForm} if    (-H) anchorsearch {FixHeaderForm} if
   (-e) anchorsearch {FixRecover} if       (-E) anchorsearch {FixRecover} if
   (-b) anchorsearch {FixBB} if            (-B) anchorsearch {FixBB} if
   (-i) anchorsearch {FixPSInterpolate} if (-I) anchorsearch {FixPSInterpolate} if
   (-m) anchorsearch {FixImagemask} if     (-M) anchorsearch {FixImagemask} if
   (-) anchorsearch {pop (Unknown option -) printErr printErr (\n) printErr ()} if
   dup () eq {pop}{FixFileNames} ifelse
 } forall
 PrepareOutParams
 CheckFiles
} def

/TIFFtoEPS {
 ProcessParams
 ReadHeader
 PrepareTAGsDictionary
 ReadIFDs
 ShowTIFFDict
 ProcessImageDict
 ShowImageDict
%  ImageImageDict quit
 MakeEPSdict
 ShowEPSDict
 (Converting ) printCon ifn printCon
   EPSdict /HeaderForm get {( into header )}{( into )} ifelse
   printCon ofn printCon (.\n) printCon flush
 /oufile ofn (w) file def
 EPSdict /HeaderForm get {
   WriteHeaderEPS
 }{
   realtime
   WriteEPSHeader
   WriteEPSData
   WriteEPSTrailer
   realtime exch sub 1000 div OTmpStr cvs
   (\nProcessing time ) printCon printCon (s.\n) printCon
 } ifelse
} def

% BEGIN of usage definition
/UsageString definestring

This is tif2eps -- a TIFF to EPS translator (ver. 0.79)

Usage: gs [-dNODISPLAY] [-q] -- tif2eps.ps TIFF_name [EPS_name] [options]
Options:
  -f# -- output filtering, #=[compression][encoding], where
         currently implemented compressions:
           f - Flate, l - LZW, p - LZW with predictor, r - RLE,
           3 - CCITTFax group 3, 4 - CCITTFax group 4 (two-dimensional),
           j - DCT (JPEG standard), n - none, or empty (default is n)
         currently implemented encodings:
           8 - ASCII85, h - HEX, or empty (default is 8)
  -d# -- override resolution (in dpi, X_RESxY_RES form allowed)
  -o# -- overwrite output file: 0 - not (default), 1 - yes, 2 - if older
  -l# -- Postscript Level of output EPS: 1 - Level 1, 2 - Level 2
  -m# -- operator used for monochrome bitmaps: 0 - image (default),
         1 - imagemask, 2 - inversed imagemask
  -p# -- convert # image (page) of multi-page TIFF (0 - first page)
  -r# -- reduction (scaling) factor, 0<#<=1
  -s# -- separation, #=1, 2, 3, 4, or c, m, y, k
  -v# -- verbose level: 0 - off , 1 - basic (default), 2 - elaborate
  -b* -- use exact (non-integer) BoundingBox comment format; otherwise
         HiResBoundingBox is additionally written out (default is +)
  -e* -- recover errors (special RLE filter, CCITTFax recover)
  -h* -- write `header' EPS (which reads and interpretes TIFF)
  -i* -- set `/Interpolate' entry to true in EPS image
  where asterisk denotes a switch:
    on:  + or 1 (or empty)
    off: - or 0 (default if not specified otherwise)
%END of usage definition

% Check for command line arguments.
[ shellarguments { ] dup length 1 ge {
   TIFFtoEPS
 }{
   UsageString print
 } ifelse
}{pop} ifelse
flush quit

%EOF