postmd.c 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157
  1. /*
  2. *
  3. * postmd - matrix display program for PostScript printers.
  4. *
  5. * A simple program that can be used to display a matrix as a gray scale image on
  6. * a PostScript printer using the image operator. Much of the code was borrowed
  7. * from postdmd, the bitmap display program DMD screen dumps. May help if you have
  8. * a large matix (of floating point numbers) and want a simple way to look for
  9. * patterns.
  10. *
  11. * Matrix elements are a series of floating point numbers arranged in the input
  12. * file in row major order. The actual matrix elements can be preceeded by a simple
  13. * header that sets things like the matrix dimensions, interval list, and possibly
  14. * a window into the matrix that we'll use for display. The dimension statement is
  15. * perhaps the most important. If present it determines the number of rows and
  16. * columns in the matrix. For example, either of the following defines a 50x50
  17. * matrix,
  18. *
  19. * dimension 50
  20. * dimension 50x50
  21. *
  22. * If no dimension statement appears in the input file, the matrix is assumed to
  23. * be square, and the number of rows (and columns) is set to the square root of
  24. * the number of elements in the input file.
  25. *
  26. * Each matrix element is mapped into an integer in the range 0 to 255 (actually
  27. * 254) and PostScript's image operator then maps that number into a gray scale
  28. * appropriate for the particular printer. The mapping from the floating point
  29. * matrix elements to integers is accomplished using an interval list that can be
  30. * set using the -i option. The format of the interval string is,
  31. *
  32. * num1,num2,num3,...,numn
  33. *
  34. * where each num is a floating point number. The list must be given in increasing
  35. * numerical order. A list of n numbers partitions the real line into 2n+1 regions
  36. * given as,
  37. *
  38. * region1 element < num1
  39. * region2 element = num1
  40. * region3 element < num2
  41. * region4 element = num2
  42. * .
  43. * .
  44. * .
  45. * region2n element = numn
  46. * region2n+1 element > numn
  47. *
  48. * Every number in a region is mapped one integer in the range 0 to 254, and that
  49. * number, when displayed on a printer using the image operator, prints as a square
  50. * filled with a gray shade that reflects the integer that was chosen. 0 maps to
  51. * black and 255 maps to white (which by default will not be used).
  52. *
  53. * The default gray scale gets darker as the region number increases, but can be
  54. * changed by supplying a gray scale list with the -g option or in the optional
  55. * matrix header. The color map is again a comman or space separated list that
  56. * looks like,
  57. *
  58. * color1,color2, ... ,color2n+1
  59. *
  60. * where color1 applies to region 1 and color2n+1 applies to region2n+1. Each
  61. * number in the list should be an integer between 0 and 255. If less than 2n+1
  62. * colors are given default assignments will be used for missing regions.
  63. *
  64. * The size of the matrix that we can display reasonably well is a function of the
  65. * number of elements in the interval list, paper size, and printer resolution.
  66. * For example a 300dpi printer using 8.5x11 inch paper gives us an image area of
  67. * about 2400x2400 pixels. An interval list of two numbers generates five separate
  68. * regions and will therefore need that many different shades of gray. Since we're
  69. * not using white we'll need to partion our image area into 4x4 pixel squares,
  70. * and that means a 600x600 matrix is about as big as we can go. In practice that's
  71. * optimistic, but the argument illustrates some of the limitations.
  72. *
  73. * A submatrix can be selected to display by windowing into the matrix. The window
  74. * list can be given using the -w option or can be set in the optional header that
  75. * can preceed each matrix. The list should be a comma or space separated list
  76. * that looks like,
  77. *
  78. * lower-column, lower-row, upper-column, upper-row
  79. *
  80. * where each element in the list must be a positive integer. Rows and columns in
  81. * the input matrix start at 1. The dimension of the displayed window will be from
  82. * lower-column to upper-column and from lower-row to upper-row inclusive.
  83. *
  84. * The encoding produced by the program is essentially identical to what's done
  85. * by postdmd. See the comments at the beginning of that program if you need more
  86. * details. The prologue also shares much of the same code.
  87. *
  88. * The PostScript prologue is copied from *prologue before any of the input files
  89. * are translated. The program expects that the following PostScript procedures
  90. * are defined in that file:
  91. *
  92. * setup
  93. *
  94. * mark ... setup -
  95. *
  96. * Handles special initialization stuff that depends on how this program
  97. * was called. Expects to find a mark followed by key/value pairs on the
  98. * stack. The def operator is applied to each pair up to the mark, then
  99. * the default state is set up.
  100. *
  101. * pagesetup
  102. *
  103. * page pagesetup -
  104. *
  105. * Does whatever is needed to set things up for the next page. Expects
  106. * to find the current page number on the stack.
  107. *
  108. * bitmap
  109. *
  110. * columns rows bitmap -
  111. *
  112. * Prints the image that's read as a hex string from standard input. The
  113. * image consists of rows lines, each of which includes columns elements.
  114. * Eight bits per pixel are used to encode the matrix elements.
  115. *
  116. * labelmatrix
  117. *
  118. * matrixname matrixlimits labelmatrix -
  119. *
  120. * Prints string matrixname just below the lower left corner of the image
  121. * and prints string martixlimits near the lower right corner. Outlines
  122. * the entire image with a (one pixel wide) box and then draws tick marks
  123. * along the top and left sides of the image. One tick mark is printed
  124. * for every ten elements.
  125. *
  126. * legend
  127. *
  128. * n1 ... nN N c1 m1 ... cM mM total regions legend -
  129. *
  130. * Prints the legend as a bar graph below the matrix image. n1 ... nN are
  131. * strings that represent the interval list. c1 m1 ... cm mM are pairs
  132. * that consist of a region's color and the statistics count. Actually
  133. * the c's are trivial procedures that just leave a one character string
  134. * on the stack when they're executed by image - which is the way the
  135. * bar graph is drawn.
  136. *
  137. * done
  138. *
  139. * done
  140. *
  141. * Makes sure the last page is printed. Only needed when we're printing
  142. * more than one page on each sheet of paper.
  143. *
  144. * Many default values, like the magnification and orientation, are defined in
  145. * the prologue, which is where they belong. If they're changed (by options), an
  146. * appropriate definition is made after the prologue is added to the output file.
  147. * The -P option passes arbitrary PostScript through to the output file. Among
  148. * other things it can be used to set (or change) values that can't be accessed by
  149. * other options.
  150. *
  151. */
  152. #include <stdio.h>
  153. #include <signal.h>
  154. #include <ctype.h>
  155. #ifdef plan9
  156. #define isascii(c) ((unsigned char)(c)<=0177)
  157. #endif
  158. #include <sys/types.h>
  159. #include <fcntl.h>
  160. #include <string.h>
  161. #include "comments.h" /* PostScript file structuring comments */
  162. #include "gen.h" /* general purpose definitions */
  163. #include "path.h" /* for the prologue */
  164. #include "ext.h" /* external variable declarations */
  165. #include "postmd.h" /* special matrix display definitions */
  166. char *optnames = "a:b:c:d:g:i:m:n:o:p:w:x:y:A:C:E:J:L:P:R:DI";
  167. char *prologue = POSTMD; /* default PostScript prologue */
  168. char *formfile = FORMFILE; /* stuff for multiple pages per sheet */
  169. char *temp_dir = TEMPDIR; /* temp directory for copying stdin */
  170. int formsperpage = 1; /* page images on each piece of paper */
  171. int copies = 1; /* and this many copies of each sheet */
  172. int bytespp = 6; /* bytes per pattern - on output */
  173. int dostats = ON; /* permanent statistics flag */
  174. int nxtstat = ON; /* and the one for the next matrix */
  175. char *interval = DFLTILIST; /* string representations of the interval */
  176. char *colormap = NULL; /* color map */
  177. char *window = NULL; /* and window lists */
  178. char *matrixname = "pipe.end"; /* name for the next plot */
  179. Ilist ilist[128]; /* active interval list and color map */
  180. int next = 0; /* one past the last element in ilist[] */
  181. int regions; /* an index assigned to the last region */
  182. int wlist[4]; /* upper left and lower right corners */
  183. int page = 0; /* last page we worked on */
  184. int printed = 0; /* and the number of pages printed */
  185. int dfltrows = 0; /* default rows */
  186. int dfltcols = 0; /* and columns - changed by -d option */
  187. int rows; /* real number of rows */
  188. int columns; /* and columns in the matrix */
  189. int patcount = 0; /* will be set to columns * rows */
  190. double element; /* next matrix element */
  191. char *raster = NULL; /* next raster line */
  192. char *rptr; /* next free byte in raster */
  193. char *eptr; /* one past the last byte in raster */
  194. FILE *fp_in = stdin; /* read from this file */
  195. FILE *fp_out = stdout; /* and write stuff here */
  196. FILE *fp_acct = NULL; /* for accounting data */
  197. /*****************************************************************************/
  198. main(agc, agv)
  199. int agc;
  200. char *agv[];
  201. {
  202. /*
  203. *
  204. * Bitmap display program for matrices. Only one matrix is allowed per input file,
  205. * and each one will be displayed on a page by itself. Input files consist of an
  206. * optional header followed by floating point numbers that represent the matrix
  207. * elements - in row major order.
  208. *
  209. */
  210. argc = agc; /* other routines may want them */
  211. argv = agv;
  212. prog_name = argv[0]; /* really just for error messages */
  213. init_signals(); /* sets up interrupt handling */
  214. header(); /* PostScript header comments */
  215. options(); /* handle the command line options */
  216. setup(); /* for PostScript */
  217. arguments(); /* followed by each input file */
  218. done(); /* print the last page etc. */
  219. account(); /* job accounting data */
  220. exit(x_stat); /* not much could be wrong */
  221. } /* End of main */
  222. /*****************************************************************************/
  223. init_signals()
  224. {
  225. /*
  226. *
  227. * Make sure we handle interrupts.
  228. *
  229. */
  230. if ( signal(SIGINT, interrupt) == SIG_IGN ) {
  231. signal(SIGINT, SIG_IGN);
  232. signal(SIGQUIT, SIG_IGN);
  233. signal(SIGHUP, SIG_IGN);
  234. } else {
  235. signal(SIGHUP, interrupt);
  236. signal(SIGQUIT, interrupt);
  237. } /* End else */
  238. signal(SIGTERM, interrupt);
  239. signal(SIGFPE, interrupt);
  240. } /* End of init_signals */
  241. /*****************************************************************************/
  242. header()
  243. {
  244. int ch; /* return value from getopt() */
  245. int old_optind = optind; /* for restoring optind - should be 1 */
  246. /*
  247. *
  248. * Scans the option list looking for things, like the prologue file, that we need
  249. * right away but could be changed from the default. Doing things this way is an
  250. * attempt to conform to Adobe's latest file structuring conventions. In particular
  251. * they now say there should be nothing executed in the prologue, and they have
  252. * added two new comments that delimit global initialization calls. Once we know
  253. * where things really are we write out the job header, follow it by the prologue,
  254. * and then add the ENDPROLOG and BEGINSETUP comments.
  255. *
  256. */
  257. while ( (ch = getopt(argc, argv, optnames)) != EOF )
  258. if ( ch == 'L' )
  259. prologue = optarg;
  260. else if ( ch == '?' )
  261. error(FATAL, "");
  262. optind = old_optind; /* get ready for option scanning */
  263. fprintf(stdout, "%s", CONFORMING);
  264. fprintf(stdout, "%s %s\n", VERSION, PROGRAMVERSION);
  265. fprintf(stdout, "%s %s\n", DOCUMENTFONTS, ATEND);
  266. fprintf(stdout, "%s %s\n", PAGES, ATEND);
  267. fprintf(stdout, "%s", ENDCOMMENTS);
  268. if ( cat(prologue) == FALSE )
  269. error(FATAL, "can't read %s", prologue);
  270. fprintf(stdout, "%s", ENDPROLOG);
  271. fprintf(stdout, "%s", BEGINSETUP);
  272. fprintf(stdout, "mark\n");
  273. } /* End of header */
  274. /*****************************************************************************/
  275. options()
  276. {
  277. int ch; /* return value from getopt() */
  278. /*
  279. *
  280. * Reads and processes the command line options. Added the -P option so arbitrary
  281. * PostScript code can be passed through. Expect it could be useful for changing
  282. * definitions in the prologue for which options have not been defined.
  283. *
  284. */
  285. while ( (ch = getopt(argc, argv, optnames)) != EOF ) {
  286. switch ( ch ) {
  287. case 'a': /* aspect ratio */
  288. fprintf(stdout, "/aspectratio %s def\n", optarg);
  289. break;
  290. case 'b': /* bytes per pattern - on output */
  291. bytespp = atoi(optarg);
  292. break;
  293. case 'c': /* copies */
  294. copies = atoi(optarg);
  295. fprintf(stdout, "/#copies %s store\n", optarg);
  296. break;
  297. case 'd': /* default matrix dimensions */
  298. sscanf(optarg, "%dx%d", &dfltrows, &dfltcols);
  299. break;
  300. case 'g': /* set the colormap (ie. grayscale) */
  301. colormap = optarg;
  302. break;
  303. case 'i': /* matrix element interval list */
  304. interval = optarg;
  305. break;
  306. case 'm': /* magnification */
  307. fprintf(stdout, "/magnification %s def\n", optarg);
  308. break;
  309. case 'n': /* forms per page */
  310. formsperpage = atoi(optarg);
  311. fprintf(stdout, "%s %s\n", FORMSPERPAGE, optarg);
  312. fprintf(stdout, "/formsperpage %s def\n", optarg);
  313. break;
  314. case 'o': /* output page list */
  315. out_list(optarg);
  316. break;
  317. case 'p': /* landscape or portrait mode */
  318. if ( *optarg == 'l' )
  319. fprintf(stdout, "/landscape true def\n");
  320. else fprintf(stdout, "/landscape false def\n");
  321. break;
  322. case 'w': /* set the window */
  323. window = optarg;
  324. break;
  325. case 'x': /* shift things horizontally */
  326. fprintf(stdout, "/xoffset %s def\n", optarg);
  327. break;
  328. case 'y': /* and vertically on the page */
  329. fprintf(stdout, "/yoffset %s def\n", optarg);
  330. break;
  331. case 'A': /* force job accounting */
  332. case 'J':
  333. if ( (fp_acct = fopen(optarg, "a")) == NULL )
  334. error(FATAL, "can't open accounting file %s", optarg);
  335. break;
  336. case 'C': /* copy file straight to output */
  337. if ( cat(optarg) == FALSE )
  338. error(FATAL, "can't read %s", optarg);
  339. break;
  340. case 'E': /* text font encoding */
  341. fontencoding = optarg;
  342. break;
  343. case 'L': /* PostScript prologue file */
  344. prologue = optarg;
  345. break;
  346. case 'P': /* PostScript pass through */
  347. fprintf(stdout, "%s\n", optarg);
  348. break;
  349. case 'R': /* special global or page level request */
  350. saverequest(optarg);
  351. break;
  352. case 'D': /* debug flag */
  353. debug = ON;
  354. break;
  355. case 'I': /* ignore FATAL errors */
  356. ignore = ON;
  357. break;
  358. case '?': /* don't understand the option */
  359. error(FATAL, "");
  360. break;
  361. default: /* don't know what to do for ch */
  362. error(FATAL, "missing case for option %c\n", ch);
  363. break;
  364. } /* End switch */
  365. } /* End while */
  366. argc -= optind; /* get ready for non-option args */
  367. argv += optind;
  368. } /* End of options */
  369. /*****************************************************************************/
  370. setup()
  371. {
  372. /*
  373. *
  374. * Handles things that must be done after the options are read but before the
  375. * input files are processed.
  376. *
  377. */
  378. writerequest(0, stdout); /* global requests eg. manual feed */
  379. setencoding(fontencoding);
  380. fprintf(stdout, "setup\n");
  381. if ( formsperpage > 1 ) {
  382. if ( cat(formfile) == FALSE )
  383. error(FATAL, "can't read %s", formfile);
  384. fprintf(stdout, "%d setupforms\n", formsperpage);
  385. } /* End if */
  386. fprintf(stdout, "%s", ENDSETUP);
  387. } /* End of setup */
  388. /*****************************************************************************/
  389. arguments()
  390. {
  391. /*
  392. *
  393. * Makes sure all the non-option command line arguments are processed. If we get
  394. * here and there aren't any arguments left, or if '-' is one of the input files
  395. * we'll process stdin.
  396. *
  397. */
  398. if ( argc < 1 )
  399. matrix();
  400. else { /* at least one argument is left */
  401. while ( argc > 0 ) {
  402. matrixname = *argv;
  403. if ( strcmp(*argv, "-") == 0 ) {
  404. fp_in = stdin;
  405. matrixname = "pipe.end";
  406. } else if ( (fp_in = fopen(*argv, "r")) == NULL )
  407. error(FATAL, "can't open %s", *argv);
  408. matrix();
  409. if ( fp_in != stdin )
  410. fclose(fp_in);
  411. argc--;
  412. argv++;
  413. } /* End while */
  414. } /* End else */
  415. } /* End of arguments */
  416. /*****************************************************************************/
  417. done()
  418. {
  419. /*
  420. *
  421. * Finished with all the input files, so mark the end of the pages, make sure the
  422. * last page is printed, and restore the initial environment.
  423. *
  424. */
  425. fprintf(stdout, "%s", TRAILER);
  426. fprintf(stdout, "done\n");
  427. fprintf(stdout, "%s %d\n", PAGES, printed);
  428. if ( temp_file != NULL )
  429. unlink(temp_file);
  430. } /* End of done */
  431. /*****************************************************************************/
  432. account()
  433. {
  434. /*
  435. *
  436. * Writes an accounting record to *fp_acct provided it's not NULL. Accounting
  437. * is requested using the -A or -J options.
  438. *
  439. */
  440. if ( fp_acct != NULL )
  441. fprintf(fp_acct, " print %d\n copies %d\n", printed, copies);
  442. } /* End of account */
  443. /*****************************************************************************/
  444. matrix()
  445. {
  446. int count; /* pattern repeats this many times */
  447. long total; /* expect this many patterns */
  448. /*
  449. *
  450. * Reads a matrix from *fp_in, translates it into a PostScript gray scale image,
  451. * and writes the result on stdout. For now only one matrix is allowed per input
  452. * file. Matrix elements are floating point numbers arranged in row major order
  453. * in the input file. In addition each input file may contain an optional header
  454. * that defines special things like the dimension of the matrix, a window into
  455. * the matrix that will be displayed, and an interval list.
  456. *
  457. * If we're reading from stdin we first make a copy in a temporary file so we can
  458. * can properly position ourselves after we've looked for the header. Originally
  459. * wasn't always making a copy of stdin, but I've added a few things to what's
  460. * accepted in the header and this simplifies the job. An alternative would be
  461. * to always require a header and mark the end of it by some string. Didn't like
  462. * that approach much - may fix things up later.
  463. *
  464. */
  465. if ( fp_in == stdin ) /* make a copy so we can seek etc. */
  466. copystdin();
  467. rows = dfltrows; /* new dimensions for the next matrix */
  468. columns = dfltcols;
  469. buildilist(interval); /* build the default ilist[] */
  470. addcolormap(colormap); /* add the colormap - if not NULL */
  471. setwindow(window); /* and setup the initial matrix window */
  472. nxtstat = dostats; /* want statistics? */
  473. getheader(); /* matrix dimensions at the very least */
  474. dimensions(); /* make sure we have the dimensions etc. */
  475. patcount = 0;
  476. total = rows * columns;
  477. eptr = rptr + (wlist[2] - wlist[0] + 1);
  478. redirect(++page);
  479. fprintf(fp_out, "%s %d %d\n", PAGE, page, printed+1);
  480. fprintf(fp_out, "/saveobj save def\n");
  481. writerequest(printed+1, fp_out);
  482. fprintf(fp_out, "%d %d bitmap\n", wlist[2] - wlist[0] + 1, wlist[3] - wlist[1] + 1);
  483. while ( patcount != total && fscanf(fp_in, "%f", &element) != EOF ) {
  484. if ( inwindow() ) *rptr++ = mapfloat(element);
  485. if ( ++patcount % columns == 0 )
  486. if ( inrange() )
  487. putrow();
  488. } /* End while */
  489. if ( total != patcount )
  490. error(FATAL, "matrix format error");
  491. labelmatrix();
  492. if ( fp_out == stdout ) printed++;
  493. fprintf(fp_out, "showpage\n");
  494. fprintf(fp_out, "saveobj restore\n");
  495. fprintf(fp_out, "%s %d %d\n", ENDPAGE, page, printed);
  496. } /* End of matrix */
  497. /*****************************************************************************/
  498. copystdin()
  499. {
  500. int fd_out; /* for the temporary file */
  501. int fd_in; /* for stdin */
  502. int buf[512]; /* buffer for reads and writes */
  503. int count; /* number of bytes put in buf */
  504. /*
  505. *
  506. * If we're reading the matrix from stdin and the matrix dimension isn't set by
  507. * a dimension statement at the beginning of the file we'll copy stdin to a
  508. * temporary file and reset *fp_in so reads come from the temp file. Simplifies
  509. * reading the header (if present), but is expensive.
  510. *
  511. */
  512. if ( temp_file != NULL ) /* been here already */
  513. unlink(temp_file);
  514. if ( (temp_file = tempnam(temp_dir, "post")) == NULL )
  515. error(FATAL, "can't generate temp file name");
  516. if ( (fd_out = creat(temp_file, 0660)) == -1 )
  517. error(FATAL, "can't create %s", temp_file);
  518. fd_in = fileno(stdin);
  519. while ( (count = read(fd_in, buf, sizeof(buf))) > 0 )
  520. if ( write(fd_out, buf, count) != count )
  521. error(FATAL, "error writing to %s", temp_file);
  522. close(fd_out);
  523. if ( (fp_in = fopen(temp_file, "r")) == NULL )
  524. error(FATAL, "can't open %s", temp_file);
  525. } /* End of copystdin */
  526. /*****************************************************************************/
  527. getheader()
  528. {
  529. char buf[512]; /* temporary string space */
  530. char *cmap = NULL; /* remember header colormap list */
  531. long pos; /* for seeking back to first element */
  532. /*
  533. *
  534. * Looks for the optional header information at the beginning of the input file,
  535. * reads it if it's there, and sets *fp_in to be just past the header. That should
  536. * be the beginning of the matrix element list. The recognized header keywords are
  537. * dimension, interval, colormap (or grayscale), window, name, and statistics. All
  538. * are optional, but may be useful in a spooling environment when the user doesn't
  539. * doesn't actually run the translator.
  540. *
  541. * The dimension statement specifies the number of rows and columns. For example
  542. * either of the following two lines define a 50 by 50 element matrix,
  543. *
  544. * dimension 50
  545. * dimension 50x50
  546. *
  547. * The first integer is the number of rows and the second, if given, is the number
  548. * of columns. If columns are missing from the dimension statement we assume the
  549. * matrix is square.
  550. *
  551. * interval can be used to redefine the interval list used for mapping floating
  552. * point numbers into integers in the range 0 to 254. The string following the
  553. * interval keyword has the same format as the -i option. For example to set the
  554. * interval list to -1, 0, and 1 you can add the line,
  555. *
  556. * interval -1,0,1
  557. *
  558. * The numbers are floats given in increasing order, and separated by commas or
  559. * blanks. The last interval list in a header takes precedence.
  560. *
  561. * colormap can be used to redefine the grayscale list. The string following
  562. * the colormap keyword has the same format as the -g option. For example
  563. *
  564. * colormap 0,50,100,150,200,250
  565. * or grayscale 0,50,100,150,200,250
  566. *
  567. * The window keyword can be used to select a submatrix. The numbers following
  568. * window are the upper left and lower right matix coordinates. May not be
  569. * implemented yet but shouldn't be difficult. For example
  570. *
  571. * window 10 10 40 40
  572. *
  573. * selects the submatrix with corners at (10, 10) and (40, 40). The edges of the
  574. * window are included in the display.
  575. *
  576. * The name keyword can be used to define the title of the display. For example,
  577. *
  578. * name Plot Of Matrix 1
  579. *
  580. * prints the string "Plot Of Matrix 1" at the top of the page. Everything up to
  581. * the next newline is taken as the name string.
  582. *
  583. */
  584. pos = ftell(fp_in);
  585. while ( fscanf(fp_in, "%s", buf) != EOF ) {
  586. if ( strncmp(buf, "dimension", strlen("dimension")) == 0 )
  587. fscanf(fp_in, "%dx%d", &rows, &columns);
  588. else if ( strncmp(buf, "window", strlen("window")) == 0 ) {
  589. fgets(buf, sizeof(buf), fp_in);
  590. setwindow(buf);
  591. } else if ( strncmp(buf, "name", strlen("name")) == 0 ) {
  592. fgets(buf, sizeof(buf), fp_in);
  593. matrixname = savestring(buf);
  594. } else if ( strncmp(buf, "colormap", strlen("colormap")) == 0 ) {
  595. fgets(buf, sizeof(buf), fp_in);
  596. cmap = savestring(buf);
  597. } else if ( strncmp(buf, "grayscale", strlen("grayscale")) == 0 ) {
  598. fgets(buf, sizeof(buf), fp_in);
  599. cmap = savestring(buf);
  600. } else if ( strncmp(buf, "interval", strlen("interval")) == 0 ) {
  601. fgets(buf, sizeof(buf), fp_in);
  602. buildilist(buf);
  603. } else if ( strncmp(buf, "statistics", strlen("statistics")) == 0 ) {
  604. fscanf(fp_in, "%s", buf);
  605. if ( strcmp(buf, "on") == 0 || strcmp(buf, "ON") == 0 )
  606. nxtstat = ON;
  607. else nxtstat = OFF;
  608. } else break;
  609. pos = ftell(fp_in);
  610. } /* End while */
  611. addcolormap(cmap); /* must happen last */
  612. fseek(fp_in, pos, 0); /* back to the start of the matrix */
  613. } /* End of getheader */
  614. /*****************************************************************************/
  615. dimensions()
  616. {
  617. char buf[100]; /* temporary storage for the elements */
  618. long count = 0; /* number of elements in the matrix */
  619. long pos; /* matrix elements start here */
  620. /*
  621. *
  622. * Need to know the dimensions of the matrix before we can go any farther. If
  623. * rows and columns are still 0 we'll read the entire input file, starting from
  624. * the current position, count the number of elements, take the square root of it,
  625. * and use it as the number of rows and columns. Then we seek back to the start
  626. * of the real matrix, make sure columns is set, and allocate enough memory for
  627. * storing each raster line. After we're certain we've got the number of rows and
  628. * columns we check the window coordinates, and if they're not legitimate they're
  629. * reset to cover the entire matrix.
  630. *
  631. */
  632. if ( rows == 0 ) {
  633. pos = ftell(fp_in);
  634. while ( fscanf(fp_in, "%s", buf) != EOF )
  635. count++;
  636. rows = sqrt((double) count);
  637. fseek(fp_in, pos, 0);
  638. } /* End if */
  639. if ( columns <= 0 ) columns = rows;
  640. if ( raster != NULL ) free(raster);
  641. if ( (rptr = raster = malloc(columns)) == NULL )
  642. error(FATAL, "no memory");
  643. eptr = rptr + columns;
  644. if ( rows <= 0 || columns <= 0 )
  645. error(FATAL, "bad matrix dimensions");
  646. if ( wlist[0] > wlist[2] || wlist[1] > wlist[3] ) {
  647. wlist[0] = wlist[1] = 1;
  648. wlist[2] = columns;
  649. wlist[3] = rows;
  650. } /* End if */
  651. } /* End of dimensions */
  652. /*****************************************************************************/
  653. buildilist(list)
  654. char *list; /* use this as the interval list */
  655. {
  656. static char *templist = NULL; /* a working copy of the list */
  657. char *ptr; /* next number in *templist */
  658. int i; /* loop index - for checking the list */
  659. /*
  660. *
  661. * Reads string *list and builds up the ilist[] that will be used in the next
  662. * matrix. Since strtok() modifies the string it's parsing we make a copy first.
  663. * The format of the interval list is described in detail in the comments at the
  664. * beginning of this program. Basically consists of a comma or space separated
  665. * list of floating point numbers that must be given in increasing numerical order.
  666. * The list determines how floating point numbers are mapped into integers in the
  667. * range 0 to 254.
  668. *
  669. */
  670. if ( templist != NULL ) /* free the space used by the last list */
  671. free(templist);
  672. while ( isascii(*list) && isspace(*list) )
  673. list++;
  674. for ( ptr = list, regions = 3; *ptr != '\0'; ptr++ ) {
  675. if ( *ptr == ',' || *ptr == '/' || isspace(*ptr) )
  676. regions += 2;
  677. while ( isascii(*ptr) && isspace(*ptr) ) ptr++;
  678. } /* End for */
  679. next = 0;
  680. templist = savestring(list);
  681. ptr = strtok(templist, ",/ \t\n");
  682. while ( ptr != NULL ) {
  683. ilist[next].count = 0;
  684. ilist[next++].color = 254 * (regions - 1 - next) / (regions - 1);
  685. ilist[next].val = atof(ptr);
  686. ilist[next].count = 0;
  687. ilist[next++].color = 254 * (regions - 1 - next) / (regions - 1);
  688. ptr = strtok(NULL, ",/ \t\n");
  689. } /* End while */
  690. ilist[next].count = 0;
  691. ilist[next].color = 254 * (regions - 1 - next) / (regions - 1);
  692. if ( next == 0 ) /* make sure we have a list */
  693. error(FATAL, "missing interval list");
  694. for ( i = 3; i < next; i += 2 ) /* that's in increasing numerical order */
  695. if ( ilist[i].val <= ilist[i-2].val )
  696. error(FATAL, "bad interval list");
  697. } /* End of buildilist */
  698. /*****************************************************************************/
  699. addcolormap(list)
  700. char *list; /* use this color map */
  701. {
  702. static char *templist = NULL; /* a working copy of the color list */
  703. char *ptr; /* next color in *templist */
  704. int i = 0; /* assigned to this region in ilist[] */
  705. /*
  706. *
  707. * Assigns the integers in *list to the color field for the regions defined in
  708. * ilist[]. Assumes ilist[] has already been setup.
  709. *
  710. */
  711. if ( list != NULL ) {
  712. if ( templist != NULL )
  713. free(templist);
  714. templist = savestring(list);
  715. ptr = strtok(templist, ",/ \t\n");
  716. while ( ptr != NULL ) {
  717. ilist[i++].color = atoi(ptr) % 256;
  718. ptr = strtok(NULL, ",/ \t\n");
  719. } /* End while */
  720. } /* End if */
  721. } /* End of addcolormap */
  722. /*****************************************************************************/
  723. setwindow(list)
  724. char *list; /* corners of window into the matrix */
  725. {
  726. static char *templist = NULL; /* a working copy of the window list */
  727. char *ptr; /* next window coordinate in *templist */
  728. int i = 0; /* assigned to this region in wlist[] */
  729. /*
  730. *
  731. * Sets up an optional window into the matrix.
  732. *
  733. */
  734. wlist[0] = wlist[1] = 1;
  735. wlist[2] = wlist[3] = 0;
  736. if ( list != NULL ) {
  737. if ( templist != NULL )
  738. free(templist);
  739. templist = savestring(list);
  740. ptr = strtok(templist, ",/ \t\n");
  741. while ( ptr != NULL ) {
  742. wlist[i++] = atoi(ptr);
  743. ptr = strtok(NULL, ",/ \t\n");
  744. } /* End while */
  745. } /* End if */
  746. } /* End of setwindow */
  747. /*****************************************************************************/
  748. inwindow()
  749. {
  750. int r; /* row of the patcount element */
  751. int c; /* column of the patcount element */
  752. /*
  753. *
  754. * Checks if the patcount element of the matrix is in the window.
  755. *
  756. */
  757. r = (patcount/columns) + 1;
  758. c = (patcount%columns) + 1;
  759. return((c >= wlist[0]) && (r >= wlist[1]) && (c <= wlist[2]) && (r <= wlist[3]));
  760. } /* End of inwindow */
  761. /*****************************************************************************/
  762. inrange()
  763. {
  764. /*
  765. *
  766. * Checks if the current row lies in the window. Used right before we output the
  767. * raster lines.
  768. *
  769. */
  770. return(((patcount/columns) >= wlist[1]) && ((patcount/columns) <= wlist[3]));
  771. } /* End of inrange */
  772. /*****************************************************************************/
  773. mapfloat(element)
  774. double element; /* floating point matrix element */
  775. {
  776. int i; /* loop index */
  777. /*
  778. *
  779. * Maps element into an integer in the range 0 to 255, and returns the result to
  780. * the caller. Mapping is done using the color map that was saved in ilist[]. Also
  781. * updates the count field for the region that contains element - not good!
  782. *
  783. */
  784. for ( i = 1; i < next && ilist[i].val < element; i += 2 ) ;
  785. if ( i > next || element < ilist[i].val )
  786. i--;
  787. ilist[i].count++;
  788. return(ilist[i].color);
  789. } /* End of mapfloat */
  790. /*****************************************************************************/
  791. putrow()
  792. {
  793. char *p1, *p2; /* starting and ending columns */
  794. int n; /* set to bytes per pattern */
  795. int i; /* loop index */
  796. /*
  797. *
  798. * Takes the scanline that's been saved in *raster, encodes it according to the
  799. * value that's been assigned to bytespp, and writes the result to *fp_out. Each
  800. * line in the output bitmap is terminated by a 0 on a line by itself.
  801. *
  802. */
  803. n = (bytespp <= 0) ? columns : bytespp;
  804. for ( p1 = raster, p2 = raster + n; p1 < eptr; p1 = p2 )
  805. if ( patncmp(p1, n) == TRUE ) {
  806. while ( patncmp(p2, n) == TRUE ) p2 += n;
  807. p2 += n;
  808. fprintf(fp_out, "%d ", n);
  809. for ( i = 0; i < n; i++, p1++ )
  810. fprintf(fp_out, "%.2X", ((int) *p1) & 0377);
  811. fprintf(fp_out, " %d\n", (p2 - p1) / n);
  812. } else {
  813. while ( p2 < eptr && patncmp(p2, n) == FALSE ) p2 += n;
  814. if ( p2 > eptr ) p2 = eptr;
  815. fprintf(fp_out, "%d ", p2 - p1);
  816. while ( p1 < p2 )
  817. fprintf(fp_out, "%.2X", ((int) *p1++) & 0377);
  818. fprintf(fp_out, " 0\n");
  819. } /* End else */
  820. fprintf(fp_out, "0\n");
  821. rptr = raster;
  822. } /* End of putrow */
  823. /*****************************************************************************/
  824. labelmatrix()
  825. {
  826. int total; /* number of elements in the window */
  827. int i; /* loop index */
  828. /*
  829. *
  830. * Responsible for generating the PostScript calls that label the matrix, generate
  831. * the legend, and print the matrix name.
  832. *
  833. */
  834. fprintf(fp_out, "(%s) ((%d, %d) to (%d, %d)) labelmatrix\n", matrixname,
  835. wlist[0], wlist[1], wlist[2], wlist[3]);
  836. total = (wlist[2] - wlist[0] + 1) * (wlist[3] - wlist[1] + 1);
  837. if ( nxtstat == OFF )
  838. for ( i = 0; i < regions; i++ )
  839. ilist[i].count = 0;
  840. for ( i = 1; i < next; i += 2 )
  841. fprintf(fp_out, "(%g) ", ilist[i].val);
  842. fprintf(fp_out, "%d ", (regions - 1) / 2);
  843. for ( i = regions - 1; i >= 0; i-- )
  844. fprintf(fp_out, "{(\\%.3o)} %d ", ilist[i].color, ilist[i].count);
  845. fprintf(fp_out, "%d %d legend\n", total, regions);
  846. } /* End of labelmatrix */
  847. /*****************************************************************************/
  848. patncmp(p1, n)
  849. char *p1; /* first patterns starts here */
  850. int n; /* and extends this many bytes */
  851. {
  852. char *p2; /* address of the second pattern */
  853. /*
  854. *
  855. * Compares the two n byte patterns *p1 and *(p1+n). FALSE if returned is they're
  856. * different or extend past the end of the current raster line.
  857. *
  858. */
  859. p2 = p1 + n;
  860. for ( ; n > 0; n--, p1++, p2++ )
  861. if ( p2 >= eptr || *p1 != *p2 )
  862. return(FALSE);
  863. return(TRUE);
  864. } /* End of patncmp */
  865. /*****************************************************************************/
  866. char *savestring(str)
  867. char *str; /* save this string */
  868. {
  869. char *ptr = NULL; /* at this address */
  870. /*
  871. *
  872. * Copies string *str to a permanent place and returns the address to the caller.
  873. *
  874. */
  875. if ( str != NULL && *str != '\0' ) {
  876. if ( (ptr = malloc(strlen(str) + 1)) == NULL )
  877. error(FATAL, "no memory available for string %s", str);
  878. strcpy(ptr, str);
  879. } /* End if */
  880. return(ptr);
  881. } /* End of savestring */
  882. /*****************************************************************************/
  883. redirect(pg)
  884. int pg; /* next page we're printing */
  885. {
  886. static FILE *fp_null = NULL; /* if output is turned off */
  887. /*
  888. *
  889. * If we're not supposed to print page pg, fp_out will be directed to /dev/null,
  890. * otherwise output goes to stdout.
  891. *
  892. */
  893. if ( pg >= 0 && in_olist(pg) == ON )
  894. fp_out = stdout;
  895. else if ( (fp_out = fp_null) == NULL )
  896. fp_out = fp_null = fopen("/dev/null", "w");
  897. } /* End of redirect */
  898. /*****************************************************************************/