summaryrefslogtreecommitdiff
path: root/sys/src/cmd/postscript/postmd
diff options
context:
space:
mode:
authorTaru Karttunen <taruti@taruti.net>2011-03-30 15:46:40 +0300
committerTaru Karttunen <taruti@taruti.net>2011-03-30 15:46:40 +0300
commite5888a1ffdae813d7575f5fb02275c6bb07e5199 (patch)
treed8d51eac403f07814b9e936eed0c9a79195e2450 /sys/src/cmd/postscript/postmd
Import sources from 2011-03-30 iso image
Diffstat (limited to 'sys/src/cmd/postscript/postmd')
-rwxr-xr-xsys/src/cmd/postscript/postmd/README23
-rwxr-xr-xsys/src/cmd/postscript/postmd/mkfile61
-rwxr-xr-xsys/src/cmd/postscript/postmd/postmd.1330
-rwxr-xr-xsys/src/cmd/postscript/postmd/postmd.c1157
-rwxr-xr-xsys/src/cmd/postscript/postmd/postmd.h69
-rwxr-xr-xsys/src/cmd/postscript/postmd/postmd.mk95
-rwxr-xr-xsys/src/cmd/postscript/postmd/postmd.ps177
7 files changed, 1912 insertions, 0 deletions
diff --git a/sys/src/cmd/postscript/postmd/README b/sys/src/cmd/postscript/postmd/README
new file mode 100755
index 000000000..43433c360
--- /dev/null
+++ b/sys/src/cmd/postscript/postmd/README
@@ -0,0 +1,23 @@
+
+A program that displays a matrix as a gray scale image on PostScript
+printers. May be useful if you have a large matrix and want a simple
+way to look for patterns. Expect a 600x600 matrix is an optimistic
+upper limit on a 300 dpi printers using 5 shades of gray and 8.5x11
+inch paper.
+
+Matrix elements are a series of floating point numbers arranged in
+the input file in row major order. By default each matrix is assumed
+to be square and the number of rows (and columns) is set to the square
+root of the number of elements in the input file. White space, including
+newlines, is not used to determine the matrix dimensions. Each matrix
+element is mapped into an integer in the range 0 to 255 (254 by default)
+and PostScript's image operator maps that integer into a gray scale
+appropriate for the printer.
+
+The mapping from floating point matrix elements to integers is controlled
+by an interval list and grayscale map. The default interval list is
+"-1,0,1" which partitions the real line into 7 regions. The default
+grayscale map gets darker as the regions move from left to right along
+the real line. The -i option changes the interval list and the -g option
+modifies the grayscale mapping. Check the man page for more details.
+
diff --git a/sys/src/cmd/postscript/postmd/mkfile b/sys/src/cmd/postscript/postmd/mkfile
new file mode 100755
index 000000000..0b9cf9872
--- /dev/null
+++ b/sys/src/cmd/postscript/postmd/mkfile
@@ -0,0 +1,61 @@
+BUILTINS=
+</$objtype/mkfile
+MAKE=mk
+
+SYSTEM=plan9
+VERSION=3.3.1
+
+ROOT=
+MAN1DIR=$ROOT/tmp
+POSTBIN=$ROOT/sys/lib/postscript/bin
+POSTLIB=$ROOT/sys/lib/postscript/prologues
+
+COMMONDIR=../common
+
+CC=pcc
+LD=pcc
+
+CFLAGS=-c -D$SYSTEM -D_POSIX_SOURCE -I$COMMONDIR -B
+LDFLAGS=
+
+all :V: $O.out
+
+install :V: $POSTBIN/$objtype/postmd $POSTLIB/postmd.ps $MAN1DIR/postmd.1
+
+installall :V:
+ for(objtype in $CPUS) { \
+ $MAKE 'MAKE=$MAKE' \
+ 'SYSTEM=$SYSTEM' 'VERSION=$VERSION' \
+ 'FONTDIR=$FONTDIR' 'HOSTDIR=$HOSTDIR' 'MAN1DIR=$MAN1DIR' \
+ 'POSTBIN=$POSTBIN' 'POSTLIB=$POSTLIB' 'TMACDIR=$TMACDIR' \
+ 'DKHOST=$DKHOST' 'DKSTREAMS=$DKSTREAMS' \
+ 'ROUNDPAGE=$ROUNDPAGE' \
+ 'CC=$CC' 'LD=$LD' 'CFLAGS=$CFLAGS' 'LDFLAGS=$LDFLAGS' \
+ install \
+ }
+
+clean :V:
+ rm -f *.$O
+
+clobber :V: clean
+ rm -f $O.out
+
+$POSTBIN/$objtype/postmd : $O.out
+ cp $prereq $target
+
+$POSTLIB/postmd.ps : postmd.ps
+ cp $prereq $target
+
+$MAN1DIR/postmd.1 : postmd.1
+ cp $prereq $target
+
+$O.out : postmd.$O $COMMONDIR/glob.$O $COMMONDIR/misc.$O $COMMONDIR/request.$O $COMMONDIR/tempnam.$O $COMMONDIR/getopt.$O
+ $LD $LDFLAGS $prereq
+
+postmd.o : postmd.h $COMMONDIR/comments.h $COMMONDIR/ext.h $COMMONDIR/gen.h $COMMONDIR/path.h
+
+%.$O: %.c
+ $CC $CFLAGS $stem.c
+
+common :V:
+ cd $COMMONDIR; $MAKE
diff --git a/sys/src/cmd/postscript/postmd/postmd.1 b/sys/src/cmd/postscript/postmd/postmd.1
new file mode 100755
index 000000000..fb67d969e
--- /dev/null
+++ b/sys/src/cmd/postscript/postmd/postmd.1
@@ -0,0 +1,330 @@
+.ds dQ /usr/lib/postscript
+.TH POSTMD 1 "DWB 3.2"
+.SH NAME
+.B postmd
+\- matrix display program for PostScript printers
+.SH SYNOPSIS
+\*(mBpostmd\f1
+.OP "" options []
+.OP "" files []
+.SH DESCRIPTION
+.B postmd
+reads a series of floating point numbers from
+.IR files ,
+translates them into a PostScript gray scale image,
+and writes the results on the standard output.
+In a typical application the numbers might be
+the elements of a large matrix,
+written in row major order,
+while the printed image could help locate
+patterns in the matrix.
+If no
+.I files
+are specified, or if
+.OP \-
+is one of the input
+.IR files ,
+the standard input is read.
+The following
+.I options
+are understood:
+.TP 0.75i
+.OP \-b num
+Pack the bitmap in the output file using
+.I num
+byte patterns.
+A value of 0 turns off all packing of the output file.
+By default
+.I num
+is 6.
+.TP
+.OP \-c num
+Print
+.I num
+copies of each page.
+By default only one copy is printed.
+.TP
+.OP \-d dimen
+Sets the default matrix dimensions for all input
+.I files
+to
+.IR dimen .
+The
+.I dimen
+string can be given as rows or rows\^\(mu\^columns.
+If columns is omitted it will be set to rows.
+By default
+.B postmd
+assumes each matrix is square and sets the number of rows
+and columns to the square root of the number of elements in
+each input file.
+.TP
+.OP \-g list
+.I list
+is a comma- or space-separated string of integers, each lying between
+0 and 255 inclusive,
+that assigns PostScript gray scales to the regions of the real line
+selected by the
+.OP \-i
+option.
+255 corresponds to white and 0 to black.
+.B postmd
+assigns a default gray scale that omits white (i.e., 255) and gets
+darker as the regions move from left to right along the real line.
+.TP
+.OP \-i list
+.I list
+is a comma- or space-separated string of
+.I N
+floating point numbers that
+partition the real line into
+.RI 2 N +1
+regions.
+The
+.I list
+must be given in increasing numerical order.
+The partitions are used to map floating point numbers read from the input
+.I files
+into gray scale integers that are assigned automatically by
+.B postmd
+or arbitrarily selected using the
+.OP \-g
+option.
+The default interval
+.I list
+is ``\*(mB\-1,0,1\fP'' which partions the real line into 7 regions.
+.TP
+.OP \-m num
+Magnify each logical page by the factor
+.IR num .
+Pages are scaled uniformly about the origin,
+which by default is located at the center of
+each page.
+The default magnification is 1.0.
+.TP
+.OP \-n num
+Print
+.I num
+logical pages on each piece of paper,
+where
+.I num
+can be any positive integer.
+By default
+.I num
+is set to 1.
+.TP
+.OP \-o list
+Print pages whose numbers are given in the comma separated
+.IR list .
+The list contains single numbers
+.I N
+and ranges
+.IR N1\-\|N2 .
+A missing
+.I N1
+means the lowest numbered page, a missing
+.I N2
+means the highest.
+.TP
+.OP \-p mode
+Print
+.I files
+in either \*(mBportrait\fP or \*(mBlandscape\fP
+.IR mode .
+Only the first character of
+.I mode
+is significant.
+The default
+.I mode
+is \*(mBportrait\fP.
+.TP
+.OP \-w window
+.I window
+is a comma- or space-separated list of four positive integers that
+select the upper left and lower right corners of a submatrix from
+each of the input
+.IR files .
+Row and column indices start at 1 in the upper left corner and the
+numbers in the input
+.I files
+are assumed to be written in row major order.
+By default the entire matrix is displayed.
+.TP
+.OP \-x num
+Translate the origin
+.I num
+inches along the positive x axis.
+The default
+coordinate system has the origin fixed at the
+center of the page, with positive
+x to the right and positive y up the page.
+Positive
+.I num
+moves everything right.
+The default offset is 0 inches.
+.TP
+.OP \-y num
+Translate the origin
+.I num
+inches along the positive y axis.
+Positive
+.I num
+moves everything up the page.
+The default offset is 0.
+.TP
+.OP \-E name
+Set the character encoding for text fonts to
+.IR name .
+Requesting
+.I name
+means include file
+.MI \*(dQ/ name .enc \f1.
+A nonexistent encoding file is silently ignored.
+The default selects file
+.MR \*(dQ/Default.enc .
+.TP
+.OP \-L file
+Use
+.I file
+as the PostScript prologue.
+.br
+The default is
+.MR \*(dQ/postmd.ps .
+.PP
+Three options allow insertion of arbitrary PostScript
+at controlled points in the translation process:
+.TP 0.75i
+.OP \-C file
+Copy
+.I file
+to the output file;
+.I file
+must contain legitimate PostScript.
+.TP
+.OP \-P string
+Include
+.I string
+in the output file;
+.I string
+must be legitimate PostScript.
+.TP
+.OP \-R action
+Requests special
+.I action
+(e.g.,
+.MR manualfeed )
+on a per page or global basis.
+The
+.I action
+string can be given as
+.IR request ,
+.IM request : page\f1\|,
+or
+.IM request : page : file\f1\|.
+If
+.I page
+is omitted or given as 0, the request
+applies to all pages.
+If
+.I file
+is omitted, the request
+lookup is done in
+.MR \*(dQ/ps.requests .
+.PP
+Only one matrix is displayed on each logical page,
+and each of the input
+.I files
+must contain complete descriptions of exactly one matrix.
+Matrix elements are floating point numbers arranged in row major order in
+each input file.
+White space, including newlines, is not used to determine matrix
+dimensions.
+By default
+.B postmd
+assumes each matrix is square and sets the number of rows and columns
+to the square root of the number of elements in the input file.
+Supplying default dimensions on the command line using the
+.OP \-d
+option overrides this default behavior, and in that case the
+dimensions apply to all input
+.IR files .
+.PP
+An optional header can be supplied with each input file and is used
+to set the matrix dimensions, the partition of the real line, the gray scale
+map, and a window into the matrix.
+The header consists of keyword/value pairs, each on a separate line.
+It begins on the first line of each input file and ends with the
+first unrecognized string, which should be the first matrix element.
+Values set in the header take precedence, but only apply to the
+current input file.
+Recognized header keywords are
+.MR dimension ,
+.MR interval ,
+.MR grayscale ,
+and
+.MR window .
+The syntax of the value string that follows each keyword parallels what is
+accepted by the
+.OP \-d ,
+.OP \-i ,
+.OP \-g ,
+and
+.OP \-w
+options.
+.SH EXAMPLES
+For example, suppose
+.I file
+initially contains the 1000 numbers
+in a 20\(mu50 matrix.
+Then the command line:
+.EX
+postmd -d20x50 -i"-100 100" -g0,128,254,128,0 \f2file
+.EE
+and prepending the header,
+.EX
+dimension 20x50
+interval -100.0 .100e+3
+grayscale 0 128 254 128 0
+.EE
+to
+.I file
+and typing the command line:
+.EX
+postmd \f2file
+.EE
+produce exactly the same output.
+The interval list partitions the real line into five regions and
+the gray scale list maps numbers less than \-100 or greater than 100
+into 0 (i.e., black), numbers equal to \-100 or 100 into 128
+(i.e., 50 percent
+black), and numbers between \-100 and 100 into 254 (i.e., almost white).
+.SH DIAGNOSTICS
+A 0 exit status is returned if
+.I files
+were successfully processed.
+.SH WARNINGS
+The largest matrix that can be adequately displayed is a function
+of the interval and gray scale lists, the printer resolution,
+and the paper size.
+A 600\(mu600 matrix is an optimistic upper bound for a two element interval
+list (i.e. five regions) using 8.5\(mu11 inch paper on a 300 dpi printer.
+.PP
+Using white (i.e., 255) in a gray scale list is not recommended and will not
+show up in the legend and bar graph that
+.B postmd
+displays below each image.
+.SH FILES
+.MW \*(dQ/postmd.ps
+.br
+.MW \*(dQ/forms.ps
+.br
+.MW \*(dQ/ps.requests
+.SH SEE ALSO
+.BR dpost (1),
+.BR postdaisy (1),
+.BR postdmd (1),
+.BR postio (1),
+.BR postprint (1),
+.BR postreverse (1),
+.BR posttek (1),
+.BR psencoding (1)
diff --git a/sys/src/cmd/postscript/postmd/postmd.c b/sys/src/cmd/postscript/postmd/postmd.c
new file mode 100755
index 000000000..01df4b43d
--- /dev/null
+++ b/sys/src/cmd/postscript/postmd/postmd.c
@@ -0,0 +1,1157 @@
+/*
+ *
+ * postmd - matrix display program for PostScript printers.
+ *
+ * A simple program that can be used to display a matrix as a gray scale image on
+ * a PostScript printer using the image operator. Much of the code was borrowed
+ * from postdmd, the bitmap display program DMD screen dumps. May help if you have
+ * a large matix (of floating point numbers) and want a simple way to look for
+ * patterns.
+ *
+ * Matrix elements are a series of floating point numbers arranged in the input
+ * file in row major order. The actual matrix elements can be preceeded by a simple
+ * header that sets things like the matrix dimensions, interval list, and possibly
+ * a window into the matrix that we'll use for display. The dimension statement is
+ * perhaps the most important. If present it determines the number of rows and
+ * columns in the matrix. For example, either of the following defines a 50x50
+ * matrix,
+ *
+ * dimension 50
+ * dimension 50x50
+ *
+ * If no dimension statement appears in the input file, the matrix is assumed to
+ * be square, and the number of rows (and columns) is set to the square root of
+ * the number of elements in the input file.
+ *
+ * Each matrix element is mapped into an integer in the range 0 to 255 (actually
+ * 254) and PostScript's image operator then maps that number into a gray scale
+ * appropriate for the particular printer. The mapping from the floating point
+ * matrix elements to integers is accomplished using an interval list that can be
+ * set using the -i option. The format of the interval string is,
+ *
+ * num1,num2,num3,...,numn
+ *
+ * where each num is a floating point number. The list must be given in increasing
+ * numerical order. A list of n numbers partitions the real line into 2n+1 regions
+ * given as,
+ *
+ * region1 element < num1
+ * region2 element = num1
+ * region3 element < num2
+ * region4 element = num2
+ * .
+ * .
+ * .
+ * region2n element = numn
+ * region2n+1 element > numn
+ *
+ * Every number in a region is mapped one integer in the range 0 to 254, and that
+ * number, when displayed on a printer using the image operator, prints as a square
+ * filled with a gray shade that reflects the integer that was chosen. 0 maps to
+ * black and 255 maps to white (which by default will not be used).
+ *
+ * The default gray scale gets darker as the region number increases, but can be
+ * changed by supplying a gray scale list with the -g option or in the optional
+ * matrix header. The color map is again a comman or space separated list that
+ * looks like,
+ *
+ * color1,color2, ... ,color2n+1
+ *
+ * where color1 applies to region 1 and color2n+1 applies to region2n+1. Each
+ * number in the list should be an integer between 0 and 255. If less than 2n+1
+ * colors are given default assignments will be used for missing regions.
+ *
+ * The size of the matrix that we can display reasonably well is a function of the
+ * number of elements in the interval list, paper size, and printer resolution.
+ * For example a 300dpi printer using 8.5x11 inch paper gives us an image area of
+ * about 2400x2400 pixels. An interval list of two numbers generates five separate
+ * regions and will therefore need that many different shades of gray. Since we're
+ * not using white we'll need to partion our image area into 4x4 pixel squares,
+ * and that means a 600x600 matrix is about as big as we can go. In practice that's
+ * optimistic, but the argument illustrates some of the limitations.
+ *
+ * A submatrix can be selected to display by windowing into the matrix. The window
+ * list can be given using the -w option or can be set in the optional header that
+ * can preceed each matrix. The list should be a comma or space separated list
+ * that looks like,
+ *
+ * lower-column, lower-row, upper-column, upper-row
+ *
+ * where each element in the list must be a positive integer. Rows and columns in
+ * the input matrix start at 1. The dimension of the displayed window will be from
+ * lower-column to upper-column and from lower-row to upper-row inclusive.
+ *
+ * The encoding produced by the program is essentially identical to what's done
+ * by postdmd. See the comments at the beginning of that program if you need more
+ * details. The prologue also shares much of the same code.
+ *
+ * The PostScript prologue is copied from *prologue before any of the input files
+ * are translated. The program expects that the following PostScript procedures
+ * are defined in that file:
+ *
+ * setup
+ *
+ * mark ... setup -
+ *
+ * Handles special initialization stuff that depends on how this program
+ * was called. Expects to find a mark followed by key/value pairs on the
+ * stack. The def operator is applied to each pair up to the mark, then
+ * the default state is set up.
+ *
+ * pagesetup
+ *
+ * page pagesetup -
+ *
+ * Does whatever is needed to set things up for the next page. Expects
+ * to find the current page number on the stack.
+ *
+ * bitmap
+ *
+ * columns rows bitmap -
+ *
+ * Prints the image that's read as a hex string from standard input. The
+ * image consists of rows lines, each of which includes columns elements.
+ * Eight bits per pixel are used to encode the matrix elements.
+ *
+ * labelmatrix
+ *
+ * matrixname matrixlimits labelmatrix -
+ *
+ * Prints string matrixname just below the lower left corner of the image
+ * and prints string martixlimits near the lower right corner. Outlines
+ * the entire image with a (one pixel wide) box and then draws tick marks
+ * along the top and left sides of the image. One tick mark is printed
+ * for every ten elements.
+ *
+ * legend
+ *
+ * n1 ... nN N c1 m1 ... cM mM total regions legend -
+ *
+ * Prints the legend as a bar graph below the matrix image. n1 ... nN are
+ * strings that represent the interval list. c1 m1 ... cm mM are pairs
+ * that consist of a region's color and the statistics count. Actually
+ * the c's are trivial procedures that just leave a one character string
+ * on the stack when they're executed by image - which is the way the
+ * bar graph is drawn.
+ *
+ * done
+ *
+ * done
+ *
+ * Makes sure the last page is printed. Only needed when we're printing
+ * more than one page on each sheet of paper.
+ *
+ * Many default values, like the magnification and orientation, are defined in
+ * the prologue, which is where they belong. If they're changed (by options), an
+ * appropriate definition is made after the prologue is added to the output file.
+ * The -P option passes arbitrary PostScript through to the output file. Among
+ * other things it can be used to set (or change) values that can't be accessed by
+ * other options.
+ *
+ */
+
+#include <stdio.h>
+#include <signal.h>
+#include <ctype.h>
+#ifdef plan9
+#define isascii(c) ((unsigned char)(c)<=0177)
+#endif
+#include <sys/types.h>
+#include <fcntl.h>
+#include <string.h>
+
+#include "comments.h" /* PostScript file structuring comments */
+#include "gen.h" /* general purpose definitions */
+#include "path.h" /* for the prologue */
+#include "ext.h" /* external variable declarations */
+#include "postmd.h" /* special matrix display definitions */
+
+char *optnames = "a:b:c:d:g:i:m:n:o:p:w:x:y:A:C:E:J:L:P:R:DI";
+
+char *prologue = POSTMD; /* default PostScript prologue */
+char *formfile = FORMFILE; /* stuff for multiple pages per sheet */
+char *temp_dir = TEMPDIR; /* temp directory for copying stdin */
+
+int formsperpage = 1; /* page images on each piece of paper */
+int copies = 1; /* and this many copies of each sheet */
+int bytespp = 6; /* bytes per pattern - on output */
+
+int dostats = ON; /* permanent statistics flag */
+int nxtstat = ON; /* and the one for the next matrix */
+
+char *interval = DFLTILIST; /* string representations of the interval */
+char *colormap = NULL; /* color map */
+char *window = NULL; /* and window lists */
+char *matrixname = "pipe.end"; /* name for the next plot */
+
+Ilist ilist[128]; /* active interval list and color map */
+int next = 0; /* one past the last element in ilist[] */
+int regions; /* an index assigned to the last region */
+int wlist[4]; /* upper left and lower right corners */
+
+int page = 0; /* last page we worked on */
+int printed = 0; /* and the number of pages printed */
+
+int dfltrows = 0; /* default rows */
+int dfltcols = 0; /* and columns - changed by -d option */
+int rows; /* real number of rows */
+int columns; /* and columns in the matrix */
+int patcount = 0; /* will be set to columns * rows */
+
+double element; /* next matrix element */
+
+char *raster = NULL; /* next raster line */
+char *rptr; /* next free byte in raster */
+char *eptr; /* one past the last byte in raster */
+
+FILE *fp_in = stdin; /* read from this file */
+FILE *fp_out = stdout; /* and write stuff here */
+FILE *fp_acct = NULL; /* for accounting data */
+
+/*****************************************************************************/
+
+main(agc, agv)
+
+ int agc;
+ char *agv[];
+
+{
+
+/*
+ *
+ * Bitmap display program for matrices. Only one matrix is allowed per input file,
+ * and each one will be displayed on a page by itself. Input files consist of an
+ * optional header followed by floating point numbers that represent the matrix
+ * elements - in row major order.
+ *
+ */
+
+ argc = agc; /* other routines may want them */
+ argv = agv;
+
+ prog_name = argv[0]; /* really just for error messages */
+
+ init_signals(); /* sets up interrupt handling */
+ header(); /* PostScript header comments */
+ options(); /* handle the command line options */
+ setup(); /* for PostScript */
+ arguments(); /* followed by each input file */
+ done(); /* print the last page etc. */
+ account(); /* job accounting data */
+
+ exit(x_stat); /* not much could be wrong */
+
+} /* End of main */
+
+/*****************************************************************************/
+
+init_signals()
+
+{
+
+/*
+ *
+ * Make sure we handle interrupts.
+ *
+ */
+
+ if ( signal(SIGINT, interrupt) == SIG_IGN ) {
+ signal(SIGINT, SIG_IGN);
+ signal(SIGQUIT, SIG_IGN);
+ signal(SIGHUP, SIG_IGN);
+ } else {
+ signal(SIGHUP, interrupt);
+ signal(SIGQUIT, interrupt);
+ } /* End else */
+
+ signal(SIGTERM, interrupt);
+ signal(SIGFPE, interrupt);
+
+} /* End of init_signals */
+
+/*****************************************************************************/
+
+header()
+
+{
+
+ int ch; /* return value from getopt() */
+ int old_optind = optind; /* for restoring optind - should be 1 */
+
+/*
+ *
+ * Scans the option list looking for things, like the prologue file, that we need
+ * right away but could be changed from the default. Doing things this way is an
+ * attempt to conform to Adobe's latest file structuring conventions. In particular
+ * they now say there should be nothing executed in the prologue, and they have
+ * added two new comments that delimit global initialization calls. Once we know
+ * where things really are we write out the job header, follow it by the prologue,
+ * and then add the ENDPROLOG and BEGINSETUP comments.
+ *
+ */
+
+ while ( (ch = getopt(argc, argv, optnames)) != EOF )
+ if ( ch == 'L' )
+ prologue = optarg;
+ else if ( ch == '?' )
+ error(FATAL, "");
+
+ optind = old_optind; /* get ready for option scanning */
+
+ fprintf(stdout, "%s", CONFORMING);
+ fprintf(stdout, "%s %s\n", VERSION, PROGRAMVERSION);
+ fprintf(stdout, "%s %s\n", DOCUMENTFONTS, ATEND);
+ fprintf(stdout, "%s %s\n", PAGES, ATEND);
+ fprintf(stdout, "%s", ENDCOMMENTS);
+
+ if ( cat(prologue) == FALSE )
+ error(FATAL, "can't read %s", prologue);
+
+ fprintf(stdout, "%s", ENDPROLOG);
+ fprintf(stdout, "%s", BEGINSETUP);
+ fprintf(stdout, "mark\n");
+
+} /* End of header */
+
+/*****************************************************************************/
+
+options()
+
+{
+
+ int ch; /* return value from getopt() */
+
+/*
+ *
+ * Reads and processes the command line options. Added the -P option so arbitrary
+ * PostScript code can be passed through. Expect it could be useful for changing
+ * definitions in the prologue for which options have not been defined.
+ *
+ */
+
+ while ( (ch = getopt(argc, argv, optnames)) != EOF ) {
+ switch ( ch ) {
+ case 'a': /* aspect ratio */
+ fprintf(stdout, "/aspectratio %s def\n", optarg);
+ break;
+
+ case 'b': /* bytes per pattern - on output */
+ bytespp = atoi(optarg);
+ break;
+
+ case 'c': /* copies */
+ copies = atoi(optarg);
+ fprintf(stdout, "/#copies %s store\n", optarg);
+ break;
+
+ case 'd': /* default matrix dimensions */
+ sscanf(optarg, "%dx%d", &dfltrows, &dfltcols);
+ break;
+
+ case 'g': /* set the colormap (ie. grayscale) */
+ colormap = optarg;
+ break;
+
+ case 'i': /* matrix element interval list */
+ interval = optarg;
+ break;
+
+ case 'm': /* magnification */
+ fprintf(stdout, "/magnification %s def\n", optarg);
+ break;
+
+ case 'n': /* forms per page */
+ formsperpage = atoi(optarg);
+ fprintf(stdout, "%s %s\n", FORMSPERPAGE, optarg);
+ fprintf(stdout, "/formsperpage %s def\n", optarg);
+ break;
+
+ case 'o': /* output page list */
+ out_list(optarg);
+ break;
+
+ case 'p': /* landscape or portrait mode */
+ if ( *optarg == 'l' )
+ fprintf(stdout, "/landscape true def\n");
+ else fprintf(stdout, "/landscape false def\n");
+ break;
+
+ case 'w': /* set the window */
+ window = optarg;
+ break;
+
+ case 'x': /* shift things horizontally */
+ fprintf(stdout, "/xoffset %s def\n", optarg);
+ break;
+
+ case 'y': /* and vertically on the page */
+ fprintf(stdout, "/yoffset %s def\n", optarg);
+ break;
+
+ case 'A': /* force job accounting */
+ case 'J':
+ if ( (fp_acct = fopen(optarg, "a")) == NULL )
+ error(FATAL, "can't open accounting file %s", optarg);
+ break;
+
+ case 'C': /* copy file straight to output */
+ if ( cat(optarg) == FALSE )
+ error(FATAL, "can't read %s", optarg);
+ break;
+
+ case 'E': /* text font encoding */
+ fontencoding = optarg;
+ break;
+
+ case 'L': /* PostScript prologue file */
+ prologue = optarg;
+ break;
+
+ case 'P': /* PostScript pass through */
+ fprintf(stdout, "%s\n", optarg);
+ break;
+
+ case 'R': /* special global or page level request */
+ saverequest(optarg);
+ break;
+
+ case 'D': /* debug flag */
+ debug = ON;
+ break;
+
+ case 'I': /* ignore FATAL errors */
+ ignore = ON;
+ break;
+
+ case '?': /* don't understand the option */
+ error(FATAL, "");
+ break;
+
+ default: /* don't know what to do for ch */
+ error(FATAL, "missing case for option %c\n", ch);
+ break;
+ } /* End switch */
+ } /* End while */
+
+ argc -= optind; /* get ready for non-option args */
+ argv += optind;
+
+} /* End of options */
+
+/*****************************************************************************/
+
+setup()
+
+{
+
+/*
+ *
+ * Handles things that must be done after the options are read but before the
+ * input files are processed.
+ *
+ */
+
+ writerequest(0, stdout); /* global requests eg. manual feed */
+ setencoding(fontencoding);
+ fprintf(stdout, "setup\n");
+
+ if ( formsperpage > 1 ) {
+ if ( cat(formfile) == FALSE )
+ error(FATAL, "can't read %s", formfile);
+ fprintf(stdout, "%d setupforms\n", formsperpage);
+ } /* End if */
+
+ fprintf(stdout, "%s", ENDSETUP);
+
+} /* End of setup */
+
+/*****************************************************************************/
+
+arguments()
+
+{
+
+/*
+ *
+ * Makes sure all the non-option command line arguments are processed. If we get
+ * here and there aren't any arguments left, or if '-' is one of the input files
+ * we'll process stdin.
+ *
+ */
+
+ if ( argc < 1 )
+ matrix();
+ else { /* at least one argument is left */
+ while ( argc > 0 ) {
+ matrixname = *argv;
+ if ( strcmp(*argv, "-") == 0 ) {
+ fp_in = stdin;
+ matrixname = "pipe.end";
+ } else if ( (fp_in = fopen(*argv, "r")) == NULL )
+ error(FATAL, "can't open %s", *argv);
+ matrix();
+ if ( fp_in != stdin )
+ fclose(fp_in);
+ argc--;
+ argv++;
+ } /* End while */
+ } /* End else */
+
+} /* End of arguments */
+
+/*****************************************************************************/
+
+done()
+
+{
+
+/*
+ *
+ * Finished with all the input files, so mark the end of the pages, make sure the
+ * last page is printed, and restore the initial environment.
+ *
+ */
+
+ fprintf(stdout, "%s", TRAILER);
+ fprintf(stdout, "done\n");
+ fprintf(stdout, "%s %d\n", PAGES, printed);
+
+ if ( temp_file != NULL )
+ unlink(temp_file);
+
+} /* End of done */
+
+/*****************************************************************************/
+
+account()
+
+{
+
+/*
+ *
+ * Writes an accounting record to *fp_acct provided it's not NULL. Accounting
+ * is requested using the -A or -J options.
+ *
+ */
+
+ if ( fp_acct != NULL )
+ fprintf(fp_acct, " print %d\n copies %d\n", printed, copies);
+
+} /* End of account */
+
+/*****************************************************************************/
+
+matrix()
+
+{
+
+ int count; /* pattern repeats this many times */
+ long total; /* expect this many patterns */
+
+/*
+ *
+ * Reads a matrix from *fp_in, translates it into a PostScript gray scale image,
+ * and writes the result on stdout. For now only one matrix is allowed per input
+ * file. Matrix elements are floating point numbers arranged in row major order
+ * in the input file. In addition each input file may contain an optional header
+ * that defines special things like the dimension of the matrix, a window into
+ * the matrix that will be displayed, and an interval list.
+ *
+ * If we're reading from stdin we first make a copy in a temporary file so we can
+ * can properly position ourselves after we've looked for the header. Originally
+ * wasn't always making a copy of stdin, but I've added a few things to what's
+ * accepted in the header and this simplifies the job. An alternative would be
+ * to always require a header and mark the end of it by some string. Didn't like
+ * that approach much - may fix things up later.
+ *
+ */
+
+ if ( fp_in == stdin ) /* make a copy so we can seek etc. */
+ copystdin();
+
+ rows = dfltrows; /* new dimensions for the next matrix */
+ columns = dfltcols;
+
+ buildilist(interval); /* build the default ilist[] */
+ addcolormap(colormap); /* add the colormap - if not NULL */
+ setwindow(window); /* and setup the initial matrix window */
+ nxtstat = dostats; /* want statistics? */
+ getheader(); /* matrix dimensions at the very least */
+ dimensions(); /* make sure we have the dimensions etc. */
+
+ patcount = 0;
+ total = rows * columns;
+
+ eptr = rptr + (wlist[2] - wlist[0] + 1);
+
+ redirect(++page);
+
+ fprintf(fp_out, "%s %d %d\n", PAGE, page, printed+1);
+ fprintf(fp_out, "/saveobj save def\n");
+ writerequest(printed+1, fp_out);
+ fprintf(fp_out, "%d %d bitmap\n", wlist[2] - wlist[0] + 1, wlist[3] - wlist[1] + 1);
+
+ while ( patcount != total && fscanf(fp_in, "%f", &element) != EOF ) {
+ if ( inwindow() ) *rptr++ = mapfloat(element);
+ if ( ++patcount % columns == 0 )
+ if ( inrange() )
+ putrow();
+ } /* End while */
+
+ if ( total != patcount )
+ error(FATAL, "matrix format error");
+
+ labelmatrix();
+
+ if ( fp_out == stdout ) printed++;
+
+ fprintf(fp_out, "showpage\n");
+ fprintf(fp_out, "saveobj restore\n");
+ fprintf(fp_out, "%s %d %d\n", ENDPAGE, page, printed);
+
+} /* End of matrix */
+
+/*****************************************************************************/
+
+copystdin()
+
+{
+
+ int fd_out; /* for the temporary file */
+ int fd_in; /* for stdin */
+ int buf[512]; /* buffer for reads and writes */
+ int count; /* number of bytes put in buf */
+
+/*
+ *
+ * If we're reading the matrix from stdin and the matrix dimension isn't set by
+ * a dimension statement at the beginning of the file we'll copy stdin to a
+ * temporary file and reset *fp_in so reads come from the temp file. Simplifies
+ * reading the header (if present), but is expensive.
+ *
+ */
+
+ if ( temp_file != NULL ) /* been here already */
+ unlink(temp_file);
+
+ if ( (temp_file = tempnam(temp_dir, "post")) == NULL )
+ error(FATAL, "can't generate temp file name");
+
+ if ( (fd_out = creat(temp_file, 0660)) == -1 )
+ error(FATAL, "can't create %s", temp_file);
+
+ fd_in = fileno(stdin);
+
+ while ( (count = read(fd_in, buf, sizeof(buf))) > 0 )
+ if ( write(fd_out, buf, count) != count )
+ error(FATAL, "error writing to %s", temp_file);
+
+ close(fd_out);
+
+ if ( (fp_in = fopen(temp_file, "r")) == NULL )
+ error(FATAL, "can't open %s", temp_file);
+
+} /* End of copystdin */
+
+/*****************************************************************************/
+
+getheader()
+
+{
+
+ char buf[512]; /* temporary string space */
+ char *cmap = NULL; /* remember header colormap list */
+ long pos; /* for seeking back to first element */
+
+/*
+ *
+ * Looks for the optional header information at the beginning of the input file,
+ * reads it if it's there, and sets *fp_in to be just past the header. That should
+ * be the beginning of the matrix element list. The recognized header keywords are
+ * dimension, interval, colormap (or grayscale), window, name, and statistics. All
+ * are optional, but may be useful in a spooling environment when the user doesn't
+ * doesn't actually run the translator.
+ *
+ * The dimension statement specifies the number of rows and columns. For example
+ * either of the following two lines define a 50 by 50 element matrix,
+ *
+ * dimension 50
+ * dimension 50x50
+ *
+ * The first integer is the number of rows and the second, if given, is the number
+ * of columns. If columns are missing from the dimension statement we assume the
+ * matrix is square.
+ *
+ * interval can be used to redefine the interval list used for mapping floating
+ * point numbers into integers in the range 0 to 254. The string following the
+ * interval keyword has the same format as the -i option. For example to set the
+ * interval list to -1, 0, and 1 you can add the line,
+ *
+ * interval -1,0,1
+ *
+ * The numbers are floats given in increasing order, and separated by commas or
+ * blanks. The last interval list in a header takes precedence.
+ *
+ * colormap can be used to redefine the grayscale list. The string following
+ * the colormap keyword has the same format as the -g option. For example
+ *
+ * colormap 0,50,100,150,200,250
+ * or grayscale 0,50,100,150,200,250
+ *
+ * The window keyword can be used to select a submatrix. The numbers following
+ * window are the upper left and lower right matix coordinates. May not be
+ * implemented yet but shouldn't be difficult. For example
+ *
+ * window 10 10 40 40
+ *
+ * selects the submatrix with corners at (10, 10) and (40, 40). The edges of the
+ * window are included in the display.
+ *
+ * The name keyword can be used to define the title of the display. For example,
+ *
+ * name Plot Of Matrix 1
+ *
+ * prints the string "Plot Of Matrix 1" at the top of the page. Everything up to
+ * the next newline is taken as the name string.
+ *
+ */
+
+ pos = ftell(fp_in);
+
+ while ( fscanf(fp_in, "%s", buf) != EOF ) {
+ if ( strncmp(buf, "dimension", strlen("dimension")) == 0 )
+ fscanf(fp_in, "%dx%d", &rows, &columns);
+ else if ( strncmp(buf, "window", strlen("window")) == 0 ) {
+ fgets(buf, sizeof(buf), fp_in);
+ setwindow(buf);
+ } else if ( strncmp(buf, "name", strlen("name")) == 0 ) {
+ fgets(buf, sizeof(buf), fp_in);
+ matrixname = savestring(buf);
+ } else if ( strncmp(buf, "colormap", strlen("colormap")) == 0 ) {
+ fgets(buf, sizeof(buf), fp_in);
+ cmap = savestring(buf);
+ } else if ( strncmp(buf, "grayscale", strlen("grayscale")) == 0 ) {
+ fgets(buf, sizeof(buf), fp_in);
+ cmap = savestring(buf);
+ } else if ( strncmp(buf, "interval", strlen("interval")) == 0 ) {
+ fgets(buf, sizeof(buf), fp_in);
+ buildilist(buf);
+ } else if ( strncmp(buf, "statistics", strlen("statistics")) == 0 ) {
+ fscanf(fp_in, "%s", buf);
+ if ( strcmp(buf, "on") == 0 || strcmp(buf, "ON") == 0 )
+ nxtstat = ON;
+ else nxtstat = OFF;
+ } else break;
+ pos = ftell(fp_in);
+ } /* End while */
+
+ addcolormap(cmap); /* must happen last */
+ fseek(fp_in, pos, 0); /* back to the start of the matrix */
+
+} /* End of getheader */
+
+/*****************************************************************************/
+
+dimensions()
+
+{
+
+ char buf[100]; /* temporary storage for the elements */
+ long count = 0; /* number of elements in the matrix */
+ long pos; /* matrix elements start here */
+
+/*
+ *
+ * Need to know the dimensions of the matrix before we can go any farther. If
+ * rows and columns are still 0 we'll read the entire input file, starting from
+ * the current position, count the number of elements, take the square root of it,
+ * and use it as the number of rows and columns. Then we seek back to the start
+ * of the real matrix, make sure columns is set, and allocate enough memory for
+ * storing each raster line. After we're certain we've got the number of rows and
+ * columns we check the window coordinates, and if they're not legitimate they're
+ * reset to cover the entire matrix.
+ *
+ */
+
+ if ( rows == 0 ) {
+ pos = ftell(fp_in);
+ while ( fscanf(fp_in, "%s", buf) != EOF )
+ count++;
+ rows = sqrt((double) count);
+ fseek(fp_in, pos, 0);
+ } /* End if */
+
+ if ( columns <= 0 ) columns = rows;
+
+ if ( raster != NULL ) free(raster);
+
+ if ( (rptr = raster = malloc(columns)) == NULL )
+ error(FATAL, "no memory");
+
+ eptr = rptr + columns;
+
+ if ( rows <= 0 || columns <= 0 )
+ error(FATAL, "bad matrix dimensions");
+
+ if ( wlist[0] > wlist[2] || wlist[1] > wlist[3] ) {
+ wlist[0] = wlist[1] = 1;
+ wlist[2] = columns;
+ wlist[3] = rows;
+ } /* End if */
+
+} /* End of dimensions */
+
+/*****************************************************************************/
+
+buildilist(list)
+
+ char *list; /* use this as the interval list */
+
+{
+
+ static char *templist = NULL; /* a working copy of the list */
+ char *ptr; /* next number in *templist */
+ int i; /* loop index - for checking the list */
+
+/*
+ *
+ * Reads string *list and builds up the ilist[] that will be used in the next
+ * matrix. Since strtok() modifies the string it's parsing we make a copy first.
+ * The format of the interval list is described in detail in the comments at the
+ * beginning of this program. Basically consists of a comma or space separated
+ * list of floating point numbers that must be given in increasing numerical order.
+ * The list determines how floating point numbers are mapped into integers in the
+ * range 0 to 254.
+ *
+ */
+
+ if ( templist != NULL ) /* free the space used by the last list */
+ free(templist);
+
+ while ( isascii(*list) && isspace(*list) )
+ list++;
+
+ for ( ptr = list, regions = 3; *ptr != '\0'; ptr++ ) {
+ if ( *ptr == ',' || *ptr == '/' || isspace(*ptr) )
+ regions += 2;
+ while ( isascii(*ptr) && isspace(*ptr) ) ptr++;
+ } /* End for */
+
+ next = 0;
+ templist = savestring(list);
+
+ ptr = strtok(templist, ",/ \t\n");
+ while ( ptr != NULL ) {
+ ilist[next].count = 0;
+ ilist[next++].color = 254 * (regions - 1 - next) / (regions - 1);
+ ilist[next].val = atof(ptr);
+ ilist[next].count = 0;
+ ilist[next++].color = 254 * (regions - 1 - next) / (regions - 1);
+ ptr = strtok(NULL, ",/ \t\n");
+ } /* End while */
+
+ ilist[next].count = 0;
+ ilist[next].color = 254 * (regions - 1 - next) / (regions - 1);
+
+ if ( next == 0 ) /* make sure we have a list */
+ error(FATAL, "missing interval list");
+
+ for ( i = 3; i < next; i += 2 ) /* that's in increasing numerical order */
+ if ( ilist[i].val <= ilist[i-2].val )
+ error(FATAL, "bad interval list");
+
+} /* End of buildilist */
+
+/*****************************************************************************/
+
+addcolormap(list)
+
+ char *list; /* use this color map */
+
+{
+
+ static char *templist = NULL; /* a working copy of the color list */
+ char *ptr; /* next color in *templist */
+ int i = 0; /* assigned to this region in ilist[] */
+
+/*
+ *
+ * Assigns the integers in *list to the color field for the regions defined in
+ * ilist[]. Assumes ilist[] has already been setup.
+ *
+ */
+
+ if ( list != NULL ) {
+ if ( templist != NULL )
+ free(templist);
+ templist = savestring(list);
+
+ ptr = strtok(templist, ",/ \t\n");
+ while ( ptr != NULL ) {
+ ilist[i++].color = atoi(ptr) % 256;
+ ptr = strtok(NULL, ",/ \t\n");
+ } /* End while */
+ } /* End if */
+
+} /* End of addcolormap */
+
+/*****************************************************************************/
+
+setwindow(list)
+
+ char *list; /* corners of window into the matrix */
+
+{
+
+ static char *templist = NULL; /* a working copy of the window list */
+ char *ptr; /* next window coordinate in *templist */
+ int i = 0; /* assigned to this region in wlist[] */
+
+/*
+ *
+ * Sets up an optional window into the matrix.
+ *
+ */
+
+ wlist[0] = wlist[1] = 1;
+ wlist[2] = wlist[3] = 0;
+
+ if ( list != NULL ) {
+ if ( templist != NULL )
+ free(templist);
+ templist = savestring(list);
+
+ ptr = strtok(templist, ",/ \t\n");
+ while ( ptr != NULL ) {
+ wlist[i++] = atoi(ptr);
+ ptr = strtok(NULL, ",/ \t\n");
+ } /* End while */
+ } /* End if */
+
+} /* End of setwindow */
+
+/*****************************************************************************/
+
+inwindow()
+
+{
+
+ int r; /* row of the patcount element */
+ int c; /* column of the patcount element */
+
+/*
+ *
+ * Checks if the patcount element of the matrix is in the window.
+ *
+ */
+
+ r = (patcount/columns) + 1;
+ c = (patcount%columns) + 1;
+
+ return((c >= wlist[0]) && (r >= wlist[1]) && (c <= wlist[2]) && (r <= wlist[3]));
+
+} /* End of inwindow */
+
+/*****************************************************************************/
+
+inrange()
+
+{
+
+/*
+ *
+ * Checks if the current row lies in the window. Used right before we output the
+ * raster lines.
+ *
+ */
+
+ return(((patcount/columns) >= wlist[1]) && ((patcount/columns) <= wlist[3]));
+
+} /* End of inrange */
+
+/*****************************************************************************/
+
+mapfloat(element)
+
+ double element; /* floating point matrix element */
+
+{
+
+ int i; /* loop index */
+
+/*
+ *
+ * Maps element into an integer in the range 0 to 255, and returns the result to
+ * the caller. Mapping is done using the color map that was saved in ilist[]. Also
+ * updates the count field for the region that contains element - not good!
+ *
+ */
+
+ for ( i = 1; i < next && ilist[i].val < element; i += 2 ) ;
+
+ if ( i > next || element < ilist[i].val )
+ i--;
+
+ ilist[i].count++;
+ return(ilist[i].color);
+
+} /* End of mapfloat */
+
+/*****************************************************************************/
+
+putrow()
+
+{
+
+ char *p1, *p2; /* starting and ending columns */
+ int n; /* set to bytes per pattern */
+ int i; /* loop index */
+
+/*
+ *
+ * Takes the scanline that's been saved in *raster, encodes it according to the
+ * value that's been assigned to bytespp, and writes the result to *fp_out. Each
+ * line in the output bitmap is terminated by a 0 on a line by itself.
+ *
+ */
+
+ n = (bytespp <= 0) ? columns : bytespp;
+
+ for ( p1 = raster, p2 = raster + n; p1 < eptr; p1 = p2 )
+ if ( patncmp(p1, n) == TRUE ) {
+ while ( patncmp(p2, n) == TRUE ) p2 += n;
+ p2 += n;
+ fprintf(fp_out, "%d ", n);
+ for ( i = 0; i < n; i++, p1++ )
+ fprintf(fp_out, "%.2X", ((int) *p1) & 0377);
+ fprintf(fp_out, " %d\n", (p2 - p1) / n);
+ } else {
+ while ( p2 < eptr && patncmp(p2, n) == FALSE ) p2 += n;
+ if ( p2 > eptr ) p2 = eptr;
+ fprintf(fp_out, "%d ", p2 - p1);
+ while ( p1 < p2 )
+ fprintf(fp_out, "%.2X", ((int) *p1++) & 0377);
+ fprintf(fp_out, " 0\n");
+ } /* End else */
+
+ fprintf(fp_out, "0\n");
+
+ rptr = raster;
+
+} /* End of putrow */
+
+/*****************************************************************************/
+
+labelmatrix()
+
+{
+
+ int total; /* number of elements in the window */
+ int i; /* loop index */
+
+/*
+ *
+ * Responsible for generating the PostScript calls that label the matrix, generate
+ * the legend, and print the matrix name.
+ *
+ */
+
+ fprintf(fp_out, "(%s) ((%d, %d) to (%d, %d)) labelmatrix\n", matrixname,
+ wlist[0], wlist[1], wlist[2], wlist[3]);
+
+ total = (wlist[2] - wlist[0] + 1) * (wlist[3] - wlist[1] + 1);
+
+ if ( nxtstat == OFF )
+ for ( i = 0; i < regions; i++ )
+ ilist[i].count = 0;
+
+ for ( i = 1; i < next; i += 2 )
+ fprintf(fp_out, "(%g) ", ilist[i].val);
+ fprintf(fp_out, "%d ", (regions - 1) / 2);
+
+ for ( i = regions - 1; i >= 0; i-- )
+ fprintf(fp_out, "{(\\%.3o)} %d ", ilist[i].color, ilist[i].count);
+ fprintf(fp_out, "%d %d legend\n", total, regions);
+
+} /* End of labelmatrix */
+
+/*****************************************************************************/
+
+patncmp(p1, n)
+
+ char *p1; /* first patterns starts here */
+ int n; /* and extends this many bytes */
+
+{
+
+ char *p2; /* address of the second pattern */
+
+/*
+ *
+ * Compares the two n byte patterns *p1 and *(p1+n). FALSE if returned is they're
+ * different or extend past the end of the current raster line.
+ *
+ */
+
+ p2 = p1 + n;
+
+ for ( ; n > 0; n--, p1++, p2++ )
+ if ( p2 >= eptr || *p1 != *p2 )
+ return(FALSE);
+
+ return(TRUE);
+
+} /* End of patncmp */
+
+/*****************************************************************************/
+
+char *savestring(str)
+
+ char *str; /* save this string */
+
+{
+
+ char *ptr = NULL; /* at this address */
+
+/*
+ *
+ * Copies string *str to a permanent place and returns the address to the caller.
+ *
+ */
+
+ if ( str != NULL && *str != '\0' ) {
+ if ( (ptr = malloc(strlen(str) + 1)) == NULL )
+ error(FATAL, "no memory available for string %s", str);
+ strcpy(ptr, str);
+ } /* End if */
+
+ return(ptr);
+
+} /* End of savestring */
+
+/*****************************************************************************/
+
+redirect(pg)
+
+ int pg; /* next page we're printing */
+
+{
+
+ static FILE *fp_null = NULL; /* if output is turned off */
+
+/*
+ *
+ * If we're not supposed to print page pg, fp_out will be directed to /dev/null,
+ * otherwise output goes to stdout.
+ *
+ */
+
+ if ( pg >= 0 && in_olist(pg) == ON )
+ fp_out = stdout;
+ else if ( (fp_out = fp_null) == NULL )
+ fp_out = fp_null = fopen("/dev/null", "w");
+
+} /* End of redirect */
+
+/*****************************************************************************/
+
diff --git a/sys/src/cmd/postscript/postmd/postmd.h b/sys/src/cmd/postscript/postmd/postmd.h
new file mode 100755
index 000000000..715596a1f
--- /dev/null
+++ b/sys/src/cmd/postscript/postmd/postmd.h
@@ -0,0 +1,69 @@
+/*
+ *
+ * An interval list used to map matrix elements into integers in the range 0 to
+ * 254 representing shades of gray on a PostScript printer. The list can be given
+ * using the -i option or can be set in the optional header that can preceed each
+ * matrix. The list should be a comma or space separated list that looks like,
+ *
+ * num1,num2, ... ,numn
+ *
+ * where each num is a floating point number. The list must be given in increasing
+ * numerical order. The n numbers in the list partion the real line into 2n+1
+ * regions given by,
+ *
+ * region1 element < num1
+ * region2 element = num1
+ * region3 element < num2
+ * region4 element = num3
+ * . .
+ * . .
+ * . .
+ * region2n element = numn
+ * region2n+1 element > numn
+ *
+ * Every number in a given region is mapped into an integer in the range 0 to 254
+ * and that number, when displayed on a PostScript printer using the image operator,
+ * prints as a square filled with a gray scale that reflects the integer that was
+ * chosen. 0 maps to black and 255 white (that's why 255 is normally omitted).
+ *
+ * The shades of gray chosen by the program are normally generated automatically,
+ * but can be reassigned using the -g option or by including a grayscale line in
+ * the optional header. The grayscale list is comma or space separated list of
+ * integers between 0 and 255 that's used to map individual regions into arbitray
+ * shade of gray, thus overriding the default choice made in the program. The list
+ * should look like,
+ *
+ * color1,color2, ... ,color2n+1
+ *
+ * where color1 applies to region1 and color2n+1 applies to region2n+1. If less
+ * than 2n+1 numbers are given the default assignments will be used for the missing
+ * regions. Each color must be an integer in the range 0 to 255.
+ *
+ * The default interval list is given below. The default grayscale maps 254 (almost
+ * white) into the first region and 0 (black) into the last.
+ *
+ */
+
+#define DFLTILIST "-1,0,1"
+
+/*
+ *
+ * The active interval list is built from an interval string and stored in an array
+ * whose elements are of type Ilist.
+ *
+ */
+
+typedef struct {
+ double val; /* only valid in kind is ENDPOINT */
+ int color; /* gray scale color */
+ long count; /* statistics for each region */
+} Ilist;
+
+/*
+ *
+ * Non-integer function declarations.
+ *
+ */
+
+char *savestring();
+
diff --git a/sys/src/cmd/postscript/postmd/postmd.mk b/sys/src/cmd/postscript/postmd/postmd.mk
new file mode 100755
index 000000000..ca131c555
--- /dev/null
+++ b/sys/src/cmd/postscript/postmd/postmd.mk
@@ -0,0 +1,95 @@
+MAKE=/bin/make
+MAKEFILE=postmd.mk
+
+SYSTEM=V9
+VERSION=3.3.2
+
+GROUP=bin
+OWNER=bin
+
+MAN1DIR=/tmp
+POSTBIN=/usr/bin/postscript
+POSTLIB=/usr/lib/postscript
+
+COMMONDIR=../common
+
+CFLGS=-O
+LDFLGS=-s
+
+CFLAGS=$(CFLGS) -I$(COMMONDIR)
+LDFLAGS=$(LDFLGS)
+
+HFILES=postmd.h\
+ $(COMMONDIR)/comments.h\
+ $(COMMONDIR)/ext.h\
+ $(COMMONDIR)/gen.h\
+ $(COMMONDIR)/path.h
+
+OFILES=postmd.o\
+ $(COMMONDIR)/glob.o\
+ $(COMMONDIR)/misc.o\
+ $(COMMONDIR)/request.o\
+ $(COMMONDIR)/tempnam.o
+
+all : postmd
+
+install : all
+ @if [ ! -d "$(POSTBIN)" ]; then \
+ mkdir $(POSTBIN); \
+ chmod 755 $(POSTBIN); \
+ chgrp $(GROUP) $(POSTBIN); \
+ chown $(OWNER) $(POSTBIN); \
+ fi
+ @if [ ! -d "$(POSTLIB)" ]; then \
+ mkdir $(POSTLIB); \
+ chmod 755 $(POSTLIB); \
+ chgrp $(GROUP) $(POSTLIB); \
+ chown $(OWNER) $(POSTLIB); \
+ fi
+ cp postmd $(POSTBIN)/postmd
+ @chmod 755 $(POSTBIN)/postmd
+ @chgrp $(GROUP) $(POSTBIN)/postmd
+ @chown $(OWNER) $(POSTBIN)/postmd
+ cp postmd.ps $(POSTLIB)/postmd.ps
+ @chmod 644 $(POSTLIB)/postmd.ps
+ @chgrp $(GROUP) $(POSTLIB)/postmd.ps
+ @chown $(OWNER) $(POSTLIB)/postmd.ps
+ cp postmd.1 $(MAN1DIR)/postmd.1
+ @chmod 644 $(MAN1DIR)/postmd.1
+ @chgrp $(GROUP) $(MAN1DIR)/postmd.1
+ @chown $(OWNER) $(MAN1DIR)/postmd.1
+
+clean :
+ rm -f *.o
+
+clobber : clean
+ rm -f postmd
+
+postmd : $(OFILES)
+ $(CC) $(CFLAGS) $(LDFLAGS) -o postmd $(OFILES) -lm
+
+postmd.o : $(HFILES)
+
+$(COMMONDIR)/glob.o\
+$(COMMONDIR)/misc.o\
+$(COMMONDIR)/request.o\
+$(COMMONDIR)/tempnam.o :
+ @cd $(COMMONDIR); $(MAKE) -f common.mk SYSTEM=$(SYSTEM) `basename $@`
+
+changes :
+ @trap "" 1 2 3 15; \
+ sed \
+ -e "s'^SYSTEM=.*'SYSTEM=$(SYSTEM)'" \
+ -e "s'^VERSION=.*'VERSION=$(VERSION)'" \
+ -e "s'^GROUP=.*'GROUP=$(GROUP)'" \
+ -e "s'^OWNER=.*'OWNER=$(OWNER)'" \
+ -e "s'^MAN1DIR=.*'MAN1DIR=$(MAN1DIR)'" \
+ -e "s'^POSTBIN=.*'POSTBIN=$(POSTBIN)'" \
+ -e "s'^POSTLIB=.*'POSTLIB=$(POSTLIB)'" \
+ $(MAKEFILE) >XXX.mk; \
+ mv XXX.mk $(MAKEFILE); \
+ sed \
+ -e "s'^.ds dQ.*'.ds dQ $(POSTLIB)'" \
+ postmd.1 >XXX.1; \
+ mv XXX.1 postmd.1
+
diff --git a/sys/src/cmd/postscript/postmd/postmd.ps b/sys/src/cmd/postscript/postmd/postmd.ps
new file mode 100755
index 000000000..6a5661e2c
--- /dev/null
+++ b/sys/src/cmd/postscript/postmd/postmd.ps
@@ -0,0 +1,177 @@
+%
+% Version 3.3.2 prologue for matrix display files.
+%
+
+/#copies 1 store
+/aspectratio 1 def
+/font /Helvetica def
+/formsperpage 1 def
+/landscape false def
+/magnification 1 def
+/margin 10 def
+/orientation 0 def
+/rotation 1 def
+/size 9 def
+/statspace 1.6 def
+/ticklength .06 def
+/tickspacing 10 def
+/xoffset 0 def
+/yoffset 0 def
+
+/useclippath true def
+/pagebbox [0 0 612 792] def
+
+/inch {72 mul} bind def
+/min {2 copy gt {exch} if pop} bind def
+
+/show {show} bind def % so later references don't bind
+/stringwidth {stringwidth} bind def
+
+/setup {
+ counttomark 2 idiv {def} repeat pop
+
+ landscape {/orientation 90 orientation add def} if
+
+ pagedimensions
+ height width lt {
+ /statspace statspace height width div mul def
+ /size size height width div mul def
+ /ticklength ticklength height width div mul def
+ } if
+ /height height margin sub statspace inch sub ticklength inch sub size 6 mul sub def
+ /width width margin sub ticklength inch sub def
+ xcenter ycenter translate
+ orientation rotation mul rotate
+ xoffset inch yoffset inch translate
+ 0 height 2 div height width min 2 div sub translate
+ 0 statspace inch 2 div translate
+ magnification dup aspectratio mul scale
+
+ 0 setlinewidth
+} def
+
+/pagedimensions {
+ useclippath {
+ /pagebbox [clippath pathbbox newpath] def
+ } if
+ pagebbox aload pop
+ 4 -1 roll exch 4 1 roll 4 copy
+ landscape {4 2 roll} if
+ sub /width exch def
+ sub /height exch def
+ add 2 div /xcenter exch def
+ add 2 div /ycenter exch def
+ userdict /gotpagebbox true put
+} def
+
+/pagesetup {/page exch def} bind def
+
+/bitmap {
+ /scanlines exch def
+ /scanlength exch def
+
+ /picstr scanlength string def
+
+ gsave
+ height scanlines div width scanlength div min
+ /scaling exch def
+ scaling scaling scale
+
+ scanlength neg 2 div scanlines neg 2 div translate
+ scanlength scanlines scale
+ getbitmap
+ grestore
+} bind def
+
+/getbitmap {
+ scanlength scanlines 8 [scanlength 0 0 scanlines neg 0 scanlines] {
+ 0 {
+ currentfile token pop dup
+ 0 eq {pop pop exit} if
+ /charcount exch def
+ picstr 1 index charcount getinterval
+ /repl exch def
+ currentfile repl readhexstring pop pop
+ charcount add
+ currentfile token pop {
+ picstr 1 index repl putinterval
+ charcount add
+ } repeat
+ } loop
+ picstr
+ } image
+} bind def
+
+/labelmatrix {
+ /matrixlimits exch def
+ /matrixname exch def
+
+ gsave
+ scaling scaling scale
+ font findfont size scaling div scalefont setfont
+ scanlength neg 2 div scanlines 2 div translate
+
+ 0 scanlines size 1.5 mul scaling div add neg moveto
+ matrixname show
+
+ scanlength scanlines size 1.5 mul scaling div add neg moveto
+ matrixlimits stringwidth pop neg 0 rmoveto
+ matrixlimits show
+
+ newpath
+ 0 0 moveto
+ scanlength 0 rlineto
+ 0 scanlines neg rlineto
+ scanlength neg 0 rlineto
+ closepath stroke
+
+ scanlength tickspacing idiv 1 add tickspacing 0 ticks
+ scanlines tickspacing idiv 1 add 0 tickspacing neg ticks
+ grestore
+} bind def
+
+/ticks {
+ /dy exch def
+ /dx exch def
+
+ /tl ticklength inch scaling div def
+ newpath
+ 0 0 moveto
+ {
+ gsave dx 0 eq {tl neg 0} {0 tl} ifelse rlineto stroke grestore
+ dx dy rmoveto
+ } repeat
+} bind def
+
+/legend {
+ /regions exch def
+ /total exch def
+
+ gsave
+ width height min 2 div neg dup size 2 mul sub translate
+ 0 statspace inch neg translate
+
+ gsave
+ regions {
+ gsave
+ total div statspace inch size 2 mul sub mul size 2 mul add
+ width height min regions div exch scale
+ 1 1 8 [1 0 0 1 0 0] 5 -1 roll image
+ grestore
+ width height min regions div 0 translate
+ } repeat
+ grestore
+
+ width height min size 1.5 mul neg translate
+ font findfont size scalefont setfont
+ dup dup add 1 add width height min exch div /interval exch def
+ {
+ interval neg 0 translate
+ interval 2 div neg 0 translate
+ dup stringwidth pop 2 div neg 0 moveto show
+ interval 2 div neg 0 translate
+ } repeat
+ grestore
+} bind def
+
+/done {/lastpage where {pop lastpage} if} def