fix definition of half() and halfp()
[mplib] / src / texk / web2c / mpdir / lib / mp.w
1 % $Id: mp.web,v 1.8 2005/08/24 10:54:02 taco Exp $
2 % MetaPost, by John Hobby.  Public domain.
3
4 % Much of this program was copied with permission from MF.web Version 1.9
5 % It interprets a language very similar to D.E. Knuth's METAFONT, but with
6 % changes designed to make it more suitable for PostScript output.
7
8 % TeX is a trademark of the American Mathematical Society.
9 % METAFONT is a trademark of Addison-Wesley Publishing Company.
10 % PostScript is a trademark of Adobe Systems Incorporated.
11
12 % Here is TeX material that gets inserted after \input webmac
13 \def\hang{\hangindent 3em\noindent\ignorespaces}
14 \def\textindent#1{\hangindent2.5em\noindent\hbox to2.5em{\hss#1 }\ignorespaces}
15 \def\PASCAL{Pascal}
16 \def\ps{PostScript}
17 \def\ph{\hbox{Pascal-H}}
18 \def\psqrt#1{\sqrt{\mathstrut#1}}
19 \def\k{_{k+1}}
20 \def\pct!{{\char`\%}} % percent sign in ordinary text
21 \font\tenlogo=logo10 % font used for the METAFONT logo
22 \font\logos=logosl10
23 \def\MF{{\tenlogo META}\-{\tenlogo FONT}}
24 \def\MP{{\tenlogo META}\-{\tenlogo POST}}
25 \def\[#1]{#1.} % from pascal web
26 \def\<#1>{$\langle#1\rangle$}
27 \def\section{\mathhexbox278}
28 \let\swap=\leftrightarrow
29 \def\round{\mathop{\rm round}\nolimits}
30 \mathchardef\vb="026A % synonym for `\|'
31
32 \def\(#1){} % this is used to make section names sort themselves better
33 \def\9#1{} % this is used for sort keys in the index via @@:sort key}{entry@@>
34 \def\title{MetaPost}
35 \def\glob{15} % this should be the section number of "<Global...>"
36 \def\gglob{23, 28} % this should be the next two sections of "<Global...>"
37 \pdfoutput=1
38 \pageno=3
39
40 @* \[1] Introduction.
41 This is \MP, a graphics-language processor based on D. E. Knuth's \MF.
42
43 The main purpose of the following program is to explain the algorithms of \MP\
44 as clearly as possible. As a result, the program will not necessarily be very
45 efficient when a particular \PASCAL\ compiler has translated it into a
46 particular machine language. However, the program has been written so that it
47 can be tuned to run efficiently in a wide variety of operating environments
48 by making comparatively few changes. Such flexibility is possible because
49 the documentation that follows is written in the \.{WEB} language, which is
50 at a higher level than \PASCAL; the preprocessing step that converts \.{WEB}
51 to \PASCAL\ is able to introduce most of the necessary refinements.
52 Semi-automatic translation to other languages is also feasible, because the
53 program below does not make extensive use of features that are peculiar to
54 \PASCAL.
55
56 A large piece of software like \MP\ has inherent complexity that cannot
57 be reduced below a certain level of difficulty, although each individual
58 part is fairly simple by itself. The \.{WEB} language is intended to make
59 the algorithms as readable as possible, by reflecting the way the
60 individual program pieces fit together and by providing the
61 cross-references that connect different parts. Detailed comments about
62 what is going on, and about why things were done in certain ways, have
63 been liberally sprinkled throughout the program.  These comments explain
64 features of the implementation, but they rarely attempt to explain the
65 \MP\ language itself, since the reader is supposed to be familiar with
66 {\sl The {\logos METAFONT\/}book} as well as the manual
67 @.WEB@>
68 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
69 {\sl A User's Manual for MetaPost}, Computing Science Technical Report 162,
70 AT\AM T Bell Laboratories.
71
72 @ The present implementation is a preliminary version, but the possibilities
73 for new features are limited by the desire to remain as nearly compatible
74 with \MF\ as possible.
75
76 On the other hand, the \.{WEB} description can be extended without changing
77 the core of the program, and it has been designed so that such
78 extensions are not extremely difficult to make.
79 The |banner| string defined here should be changed whenever \MP\
80 undergoes any modifications, so that it will be clear which version of
81 \MP\ might be the guilty party when a problem arises.
82 @^extensions to \MP@>
83 @^system dependencies@>
84
85 @d banner "This is MetaPost, Version 1.002" /* printed when \MP\ starts */
86 @d metapost_version "1.002"
87 @d mplib_version "0.10"
88 @d version_string " (Cweb version 0.10)"
89
90 @ Different \PASCAL s have slightly different conventions, and the present
91 @:PASCAL H}{\ph@>
92 program is expressed in a version of \PASCAL\ that D. E. Knuth used for \MF.
93 Constructions that apply to
94 this particular compiler, which we shall call \ph, should help the
95 reader see how to make an appropriate interface for other systems
96 if necessary. (\ph\ is Charles Hedrick's modification of a compiler
97 @^Hedrick, Charles Locke@>
98 for the DECsystem-10 that was originally developed at the University of
99 Hamburg; cf.\ {\sl SOFTWARE---Practice \AM\ Experience \bf6} (1976),
100 29--42. The \MP\ program below is intended to be adaptable, without
101 extensive changes, to most other versions of \PASCAL\ and commonly used
102 \PASCAL-to-C translators, so it does not fully
103 @:C@>
104 use the admirable features of \ph. Indeed, a conscious effort has been
105 made here to avoid using several idiosyncratic features of standard
106 \PASCAL\ itself, so that most of the code can be translated mechanically
107 into other high-level languages. For example, the `\&{with}' and `\\{new}'
108 features are not used, nor are pointer types, set types, or enumerated
109 scalar types; there are no `\&{var}' parameters, except in the case of files;
110 there are no tag fields on variant records; there are no |real| variables;
111 no procedures are declared local to other procedures.)
112
113 The portions of this program that involve system-dependent code, where
114 changes might be necessary because of differences between \PASCAL\ compilers
115 and/or differences between
116 operating systems, can be identified by looking at the sections whose
117 numbers are listed under `system dependencies' in the index. Furthermore,
118 the index entries for `dirty \PASCAL' list all places where the restrictions
119 of \PASCAL\ have not been followed perfectly, for one reason or another.
120 @^system dependencies@>
121 @^dirty \PASCAL@>
122
123 @ The program begins with a normal \PASCAL\ program heading, whose
124 components will be filled in later, using the conventions of \.{WEB}.
125 @.WEB@>
126 For example, the portion of the program called `\X\glob:Global
127 variables\X' below will be replaced by a sequence of variable declarations
128 that starts in $\section\glob$ of this documentation. In this way, we are able
129 to define each individual global variable when we are prepared to
130 understand what it means; we do not have to define all of the globals at
131 once.  Cross references in $\section\glob$, where it says ``See also
132 sections \gglob, \dots,'' also make it possible to look at the set of
133 all global variables, if desired.  Similar remarks apply to the other
134 portions of the program heading.
135
136 Actually the heading shown here is not quite normal: The |program| line
137 does not mention any |output| file, because \ph\ would ask the \MP\ user
138 to specify a file name if |output| were specified here.
139 @^system dependencies@>
140
141 @d true 1
142 @d false 0
143  
144 @(mplib.h@>=
145 typedef struct MP_instance * MP;
146 @<Exported types@>
147 typedef struct MP_options {
148   @<Option variables@>
149 } MP_options;
150 @<Exported function headers@>
151
152 @ @(mpmp.h@>=
153 #include <setjmp.h>
154 typedef struct psout_data_struct * psout_data;
155 typedef int boolean;
156 typedef signed int integer;
157 @<Declare helpers@>;
158 @<Types in the outer block@>;
159 @<Constants in the outer block@>
160 #  ifndef LIBAVL_ALLOCATOR
161 #    define LIBAVL_ALLOCATOR
162     struct libavl_allocator {
163         void *(*libavl_malloc) (struct libavl_allocator *, size_t libavl_size);
164         void (*libavl_free) (struct libavl_allocator *, void *libavl_block);
165     };
166 #  endif
167 typedef struct MP_instance {
168   @<Global variables@>
169 } MP_instance;
170 @<Internal library declarations@>
171
172 @ @c 
173 #include <stdio.h>
174 #include <stdlib.h>
175 #include <string.h>
176 #include <stdarg.h>
177 #include <assert.h>
178 #include <unistd.h> /* for access() */
179 #include <time.h> /* for struct tm \& co */
180 #include "mplib.h"
181 #include "mpmp.h" /* internal header */
182 #include "mppsout.h" /* internal header */
183 @h
184 @<Declarations@>
185 @<Basic printing procedures@>
186 @<Error handling procedures@>
187
188 @ Here are the functions that set up the \MP\ instance.
189
190 @<Declarations@> =
191 @<Declare |mp_reallocate| functions@>;
192 struct MP_options *mp_options (void);
193 MP mp_new (struct MP_options *opt);
194
195 @ @c
196 struct MP_options *mp_options (void) {
197   struct MP_options *opt;
198   opt = malloc(sizeof(MP_options));
199   if (opt!=NULL) {
200     memset (opt,0,sizeof(MP_options));
201   }
202   return opt;
203
204 MP mp_new (struct MP_options *opt) {
205   MP mp;
206   mp = xmalloc(1,sizeof(MP_instance));
207   @<Set |ini_version|@>;
208   @<Setup the non-local jump buffer in |mp_new|@>;
209   @<Allocate or initialize variables@>
210   if (opt->main_memory>mp->mem_max)
211     mp_reallocate_memory(mp,opt->main_memory);
212   mp_reallocate_paths(mp,1000);
213   mp_reallocate_fonts(mp,8);
214   mp->term_in = stdin;
215   mp->term_out = stdout;
216   return mp;
217 }
218 void mp_free (MP mp) {
219   int k; /* loop variable */
220   @<Dealloc variables@>
221   xfree(mp);
222 }
223
224 @ @c
225 void mp_do_initialize ( MP mp) {
226   @<Local variables for initialization@>
227   @<Set initial values of key variables@>
228 }
229 int mp_initialize (MP mp) { /* this procedure gets things started properly */
230   mp->history=mp_fatal_error_stop; /* in case we quit during initialization */
231   @<Install and test the non-local jump buffer@>;
232   t_open_out; /* open the terminal for output */
233   @<Check the ``constant'' values...@>;
234   if ( mp->bad>0 ) {
235     fprintf(stdout,"Ouch---my internal constants have been clobbered!\n"
236                    "---case %i",(int)mp->bad);
237 @.Ouch...clobbered@>
238     return mp->history;
239   }
240   mp_do_initialize(mp); /* erase preloaded mem */
241   if (mp->ini_version) {
242     @<Run inimpost commands@>;
243   }
244   @<Initialize the output routines@>;
245   @<Get the first line of input and prepare to start@>;
246   mp_set_job_id(mp);
247   mp_init_map_file(mp, mp->troff_mode);
248   mp->history=mp_spotless; /* ready to go! */
249   if (mp->troff_mode) {
250     mp->internal[mp_gtroffmode]=unity; 
251     mp->internal[mp_prologues]=unity; 
252   }
253   if ( mp->start_sym>0 ) { /* insert the `\&{everyjob}' symbol */
254     mp->cur_sym=mp->start_sym; mp_back_input(mp);
255   }
256   return mp->history;
257 }
258
259
260 @<Exported function headers@>=
261 extern struct MP_options *mp_options (void);
262 extern MP mp_new (struct MP_options *opt) ;
263 extern void mp_free (MP mp);
264 extern int mp_initialize (MP mp);
265
266 @ @<Declarations@>=
267 void mp_do_initialize (MP mp);
268
269
270 @ The overall \MP\ program begins with the heading just shown, after which
271 comes a bunch of procedure declarations and function declarations.
272 Finally we will get to the main program, which begins with the
273 comment `|start_here|'. If you want to skip down to the
274 main program now, you can look up `|start_here|' in the index.
275 But the author suggests that the best way to understand this program
276 is to follow pretty much the order of \MP's components as they appear in the
277 \.{WEB} description you are now reading, since the present ordering is
278 intended to combine the advantages of the ``bottom up'' and ``top down''
279 approaches to the problem of understanding a somewhat complicated system.
280
281 @ Some of the code below is intended to be used only when diagnosing the
282 strange behavior that sometimes occurs when \MP\ is being installed or
283 when system wizards are fooling around with \MP\ without quite knowing
284 what they are doing. Such code will not normally be compiled; it is
285 delimited by the preprocessor test `|#ifdef DEBUG .. #endif|'.
286
287 @ This program has two important variations: (1) There is a long and slow
288 version called \.{INIMP}, which does the extra calculations needed to
289 @.INIMP@>
290 initialize \MP's internal tables; and (2)~there is a shorter and faster
291 production version, which cuts the initialization to a bare minimum.
292
293 Which is which is decided at runtime.
294
295 @ The following parameters can be changed at compile time to extend or
296 reduce \MP's capacity. They may have different values in \.{INIMP} and
297 in production versions of \MP.
298 @.INIMP@>
299 @^system dependencies@>
300
301 @<Constants...@>=
302 #define file_name_size 255 /* file names shouldn't be longer than this */
303 #define bistack_size 1500 /* size of stack for bisection algorithms;
304   should probably be left at this value */
305
306 @ Like the preceding parameters, the following quantities can be changed
307 at compile time to extend or reduce \MP's capacity. But if they are changed,
308 it is necessary to rerun the initialization program \.{INIMP}
309 @.INIMP@>
310 to generate new tables for the production \MP\ program.
311 One can't simply make helter-skelter changes to the following constants,
312 since certain rather complex initialization
313 numbers are computed from them. 
314
315 @ @<Glob...@>=
316 int max_strings; /* maximum number of strings; must not exceed |max_halfword| */
317 int pool_size; /* maximum number of characters in strings, including all
318   error messages and help texts, and the names of all identifiers */
319 int error_line; /* width of context lines on terminal error messages */
320 int half_error_line; /* width of first lines of contexts in terminal
321   error messages; should be between 30 and |error_line-15| */
322 int max_print_line; /* width of longest text lines output; should be at least 60 */
323 int mem_max; /* greatest index in \MP's internal |mem| array;
324   must be strictly less than |max_halfword|;
325   must be equal to |mem_top| in \.{INIMP}, otherwise |>=mem_top| */
326 int mem_top; /* largest index in the |mem| array dumped by \.{INIMP};
327   must not be greater than |mem_max| */
328 int hash_size; /* maximum number of symbolic tokens,
329   must be less than |max_halfword-3*param_size| */
330 int hash_prime; /* a prime number equal to about 85\pct! of |hash_size| */
331 int param_size; /* maximum number of simultaneous macro parameters */
332 int max_in_open; /* maximum number of input files and error insertions that
333   can be going on simultaneously */
334
335 @ @<Option variables@>=
336 int error_line;
337 int half_error_line;
338 int max_print_line;
339 int main_memory;
340 int hash_size; 
341 int hash_prime; 
342 int param_size; 
343 int max_in_open; 
344
345
346 @d set_value(a,b,c) do { a=c; if (b>c) a=b; } while (0)
347
348 @<Allocate or ...@>=
349 mp->max_strings=500;
350 mp->pool_size=10000;
351 set_value(mp->error_line,opt->error_line,79);
352 set_value(mp->half_error_line,opt->half_error_line,50);
353 set_value(mp->max_print_line,opt->max_print_line,79);
354 mp->mem_max=5000;
355 mp->mem_top=5000;
356 set_value(mp->hash_size,opt->hash_size,9500);
357 set_value(mp->hash_prime,opt->hash_prime,7919);
358 set_value(mp->param_size,opt->param_size,150);
359 set_value(mp->max_in_open,opt->max_in_open,10);
360
361
362 @ In case somebody has inadvertently made bad settings of the ``constants,''
363 \MP\ checks them using a global variable called |bad|.
364
365 This is the first of many sections of \MP\ where global variables are
366 defined.
367
368 @<Glob...@>=
369 integer bad; /* is some ``constant'' wrong? */
370
371 @ Later on we will say `\ignorespaces|if (mem_max>=max_halfword) bad=10;|',
372 or something similar. (We can't do that until |max_halfword| has been defined.)
373
374 @<Check the ``constant'' values for consistency@>=
375 mp->bad=0;
376 if ( (mp->half_error_line<30)||(mp->half_error_line>mp->error_line-15) ) mp->bad=1;
377 if ( mp->max_print_line<60 ) mp->bad=2;
378 if ( mp->mem_top<=1100 ) mp->bad=4;
379 if (mp->hash_prime>mp->hash_size ) mp->bad=5;
380
381 @ Labels are given symbolic names by the following definitions, so that
382 occasional |goto| statements will be meaningful. We insert the label
383 `|exit|:' just before the `\ignorespaces|end|\unskip' of a procedure in
384 which we have used the `|return|' statement defined below; the label
385 `|restart|' is occasionally used at the very beginning of a procedure; and
386 the label `|reswitch|' is occasionally used just prior to a |case|
387 statement in which some cases change the conditions and we wish to branch
388 to the newly applicable case.  Loops that are set up with the |loop|
389 construction defined below are commonly exited by going to `|done|' or to
390 `|found|' or to `|not_found|', and they are sometimes repeated by going to
391 `|continue|'.  If two or more parts of a subroutine start differently but
392 end up the same, the shared code may be gathered together at
393 `|common_ending|'.
394
395 Incidentally, this program never declares a label that isn't actually used,
396 because some fussy \PASCAL\ compilers will complain about redundant labels.
397
398 @d label_exit 10 /* go here to leave a procedure */
399 @d restart 20 /* go here to start a procedure again */
400 @d reswitch 21 /* go here to start a case statement again */
401 @d continue 22 /* go here to resume a loop */
402 @d done 30 /* go here to exit a loop */
403 @d done1 31 /* like |done|, when there is more than one loop */
404 @d done2 32 /* for exiting the second loop in a long block */
405 @d done3 33 /* for exiting the third loop in a very long block */
406 @d done4 34 /* for exiting the fourth loop in an extremely long block */
407 @d done5 35 /* for exiting the fifth loop in an immense block */
408 @d done6 36 /* for exiting the sixth loop in a block */
409 @d found 40 /* go here when you've found it */
410 @d found1 41 /* like |found|, when there's more than one per routine */
411 @d found2 42 /* like |found|, when there's more than two per routine */
412 @d found3 43 /* like |found|, when there's more than three per routine */
413 @d not_found 45 /* go here when you've found nothing */
414 @d common_ending 50 /* go here when you want to merge with another branch */
415
416 @ Here are some macros for common programming idioms.
417
418 @d incr(A)   (A)=(A)+1 /* increase a variable by unity */
419 @d decr(A)   (A)=(A)-1 /* decrease a variable by unity */
420 @d negate(A) (A)=-(A) /* change the sign of a variable */
421 @d double(A) (A)=(A)+(A)
422 @d odd(A)   ((A)%2==1)
423 @d chr(A)   (A)
424 @d do_nothing   /* empty statement */
425 @d Return   goto exit /* terminate a procedure call */
426 @f return   nil /* \.{WEB} will henceforth say |return| instead of \\{return} */
427
428 @* \[2] The character set.
429 In order to make \MP\ readily portable to a wide variety of
430 computers, all of its input text is converted to an internal eight-bit
431 code that includes standard ASCII, the ``American Standard Code for
432 Information Interchange.''  This conversion is done immediately when each
433 character is read in. Conversely, characters are converted from ASCII to
434 the user's external representation just before they are output to a
435 text file.
436 @^ASCII code@>
437
438 Such an internal code is relevant to users of \MP\ only with respect to
439 the \&{char} and \&{ASCII} operations, and the comparison of strings.
440
441 @ Characters of text that have been converted to \MP's internal form
442 are said to be of type |ASCII_code|, which is a subrange of the integers.
443
444 @<Types...@>=
445 typedef unsigned char ASCII_code; /* eight-bit numbers */
446
447 @ The original \PASCAL\ compiler was designed in the late 60s, when six-bit
448 character sets were common, so it did not make provision for lowercase
449 letters. Nowadays, of course, we need to deal with both capital and small
450 letters in a convenient way, especially in a program for font design;
451 so the present specification of \MP\ has been written under the assumption
452 that the \PASCAL\ compiler and run-time system permit the use of text files
453 with more than 64 distinguishable characters. More precisely, we assume that
454 the character set contains at least the letters and symbols associated
455 with ASCII codes 040 through 0176; all of these characters are now
456 available on most computer terminals.
457
458 Since we are dealing with more characters than were present in the first
459 \PASCAL\ compilers, we have to decide what to call the associated data
460 type. Some \PASCAL s use the original name |char| for the
461 characters in text files, even though there now are more than 64 such
462 characters, while other \PASCAL s consider |char| to be a 64-element
463 subrange of a larger data type that has some other name.
464
465 In order to accommodate this difference, we shall use the name |text_char|
466 to stand for the data type of the characters that are converted to and
467 from |ASCII_code| when they are input and output. We shall also assume
468 that |text_char| consists of the elements |chr(first_text_char)| through
469 |chr(last_text_char)|, inclusive. The following definitions should be
470 adjusted if necessary.
471 @^system dependencies@>
472
473 @d first_text_char 0 /* ordinal number of the smallest element of |text_char| */
474 @d last_text_char 255 /* ordinal number of the largest element of |text_char| */
475
476 @<Types...@>=
477 typedef unsigned char text_char; /* the data type of characters in text files */
478
479 @ @<Local variables for init...@>=
480 integer i;
481
482 @ The \MP\ processor converts between ASCII code and
483 the user's external character set by means of arrays |xord| and |xchr|
484 that are analogous to \PASCAL's |ord| and |chr| functions.
485
486 @d xchr(A) mp->xchr[(A)]
487 @d xord(A) mp->xord[(A)]
488
489 @<Glob...@>=
490 ASCII_code xord[256];  /* specifies conversion of input characters */
491 text_char xchr[256];  /* specifies conversion of output characters */
492
493 @ The core system assumes all 8-bit is acceptable.  If it is not,
494 a change file has to alter the below section.
495 @^system dependencies@>
496
497 Additionally, people with extended character sets can
498 assign codes arbitrarily, giving an |xchr| equivalent to whatever
499 characters the users of \MP\ are allowed to have in their input files.
500 Appropriate changes to \MP's |char_class| table should then be made.
501 (Unlike \TeX, each installation of \MP\ has a fixed assignment of category
502 codes, called the |char_class|.) Such changes make portability of programs
503 more difficult, so they should be introduced cautiously if at all.
504 @^character set dependencies@>
505 @^system dependencies@>
506
507 @<Set initial ...@>=
508 for (i=0;i<=0377;i++) { xchr(i)=i; }
509
510 @ The following system-independent code makes the |xord| array contain a
511 suitable inverse to the information in |xchr|. Note that if |xchr[i]=xchr[j]|
512 where |i<j<0177|, the value of |xord[xchr[i]]| will turn out to be
513 |j| or more; hence, standard ASCII code numbers will be used instead of
514 codes below 040 in case there is a coincidence.
515
516 @<Set initial ...@>=
517 for (i=first_text_char;i<=last_text_char;i++) { 
518    xord(chr(i))=0177;
519 }
520 for (i=0200;i<=0377;i++) { xord(xchr(i))=i;}
521 for (i=0;i<=0176;i++) { xord(xchr(i))=i;}
522
523 @* \[3] Input and output.
524 The bane of portability is the fact that different operating systems treat
525 input and output quite differently, perhaps because computer scientists
526 have not given sufficient attention to this problem. People have felt somehow
527 that input and output are not part of ``real'' programming. Well, it is true
528 that some kinds of programming are more fun than others. With existing
529 input/output conventions being so diverse and so messy, the only sources of
530 joy in such parts of the code are the rare occasions when one can find a
531 way to make the program a little less bad than it might have been. We have
532 two choices, either to attack I/O now and get it over with, or to postpone
533 I/O until near the end. Neither prospect is very attractive, so let's
534 get it over with.
535
536 The basic operations we need to do are (1)~inputting and outputting of
537 text, to or from a file or the user's terminal; (2)~inputting and
538 outputting of eight-bit bytes, to or from a file; (3)~instructing the
539 operating system to initiate (``open'') or to terminate (``close'') input or
540 output from a specified file; (4)~testing whether the end of an input
541 file has been reached; (5)~display of bits on the user's screen.
542 The bit-display operation will be discussed in a later section; we shall
543 deal here only with more traditional kinds of I/O.
544
545 @ Finding files happens in a slightly roundabout fashion: the \MP\
546 instance object contains a field that holds a function pointer that finds a
547 file, and returns its name, or NULL. For this, it receives three
548 parameters: the non-qualified name |fname|, the intended |fopen|
549 operation type |fmode|, and the type of the file |ftype|.
550
551 The file types that are passed on in |ftype| can be  used to 
552 differentiate file searches if a library like kpathsea is used,
553 the fopen mode is passed along for the same reason.
554
555 @<Types...@>=
556 typedef unsigned char eight_bits ; /* unsigned one-byte quantity */
557
558 @ @<Exported types@>=
559 enum mp_filetype {
560   mp_filetype_program = 1, /* \MP\ language input */
561   mp_filetype_log,  /* the log file */
562   mp_filetype_postscript, /* the postscript output */
563   mp_filetype_text,  /* text files for readfrom and writeto primitives */
564   mp_filetype_memfile, /* memory dumps */
565   mp_filetype_metrics, /* TeX font metric files */
566   mp_filetype_fontmap, /* PostScript font mapping files */
567   mp_filetype_font, /*  PostScript type1 font programs */
568   mp_filetype_encoding, /*  PostScript font encoding files */
569 };
570 typedef char *(*mp_file_finder)(char *, char *, int);
571
572 @ @<Glob...@>=
573 mp_file_finder find_file;
574
575 @ @<Option variables@>=
576 mp_file_finder find_file;
577
578 @ The default function for finding files is |mp_find_file|. It is 
579 pretty stupid: it will only find files in the current directory.
580
581 @c
582 char *mp_find_file (char *fname, char *fmode, int ftype)  {
583   if (fmode[0] != 'r' || access (fname,R_OK) || ftype)  
584      return strdup(fname);
585   return NULL;
586 }
587
588 @ This has to be done very early on, so it is best to put it in with
589 the |mp_new| allocations
590
591 @d set_callback_option(A) do { mp->A = mp_##A;
592   if (opt->A!=NULL) mp->A = opt->A;
593 } while (0)
594
595 @<Allocate or initialize ...@>=
596 set_callback_option(find_file);
597
598 @ Because |mp_find_file| is used so early, it has to be in the helpers
599 section.
600
601 @<Internal ...@>=
602 char *mp_find_file (char *fname, char *fmode, int ftype) ;
603
604 @ The function to open files can now be very short.
605
606 @c
607 FILE *mp_open_file(MP mp, char *fname, char *fmode, int ftype)  {
608   char *s = (mp->find_file)(fname,fmode,ftype);
609   if (s!=NULL) {
610     FILE *f = fopen(s, fmode);
611     xfree(s);
612     return f;   
613   }
614   return NULL;
615 }
616
617 @ This is a legacy interface: (almost) all file names pass through |name_of_file|.
618
619 @<Glob...@>=
620 char name_of_file[file_name_size+1]; /* the name of a system file */
621 int name_length;/* this many characters are actually
622   relevant in |name_of_file| (the rest are blank) */
623 boolean print_found_names; /* configuration parameter */
624
625 @ @<Option variables@>=
626 int print_found_names; /* configuration parameter */
627
628 @ If this parameter is true, the terminal and log will report the found
629 file names for input files instead of the requested ones. 
630 It is off by default because it creates an extra filename lookup.
631
632 @<Allocate or initialize ...@>=
633 mp->print_found_names = (opt->print_found_names>0 ? true : false);
634
635 @ \MP's file-opening procedures return |false| if no file identified by
636 |name_of_file| could be opened.
637
638 The |OPEN_FILE| macro takes care of the |print_found_names| parameter.
639 It is not used for opening a mem file for read, because that file name 
640 is never printed.
641
642 @d OPEN_FILE(A) do {
643   if (mp->print_found_names) {
644     char *s = (mp->find_file)(mp->name_of_file,A,ftype);
645     if (s!=NULL) {
646       *f = mp_open_file(mp,mp->name_of_file,A, ftype); 
647       strncpy(mp->name_of_file,s,file_name_size);
648       xfree(s);
649     } else {
650       *f = NULL;
651     }
652   } else {
653     *f = mp_open_file(mp,mp->name_of_file,A, ftype); 
654   }
655 } while (0);
656 return (*f ? true : false)
657
658 @c 
659 boolean mp_a_open_in (MP mp, FILE **f, int ftype) {
660   /* open a text file for input */
661   OPEN_FILE("r");
662 }
663 @#
664 boolean mp_w_open_in (MP mp, FILE **f) {
665   /* open a word file for input */
666   *f = mp_open_file(mp,mp->name_of_file,"rb",mp_filetype_memfile); 
667   return (*f ? true : false);
668 }
669 @#
670 boolean mp_a_open_out (MP mp, FILE **f, int ftype) {
671   /* open a text file for output */
672   OPEN_FILE("w");
673 }
674 @#
675 boolean mp_b_open_out (MP mp, FILE **f, int ftype) {
676   /* open a binary file for output */
677   OPEN_FILE("wb");
678 }
679 @#
680 boolean mp_w_open_out (MP mp, FILE**f) {
681   /* open a word file for output */
682   int ftype = mp_filetype_memfile;
683   OPEN_FILE("wb");
684 }
685
686 @ @<Internal ...@>=
687 FILE *mp_open_file(MP mp, char *fname, char *fmode, int ftype);
688
689 @ Binary input and output are done with \PASCAL's ordinary |get| and |put|
690 procedures, so we don't have to make any other special arrangements for
691 binary~I/O. Text output is also easy to do with standard \PASCAL\ routines.
692 The treatment of text input is more difficult, however, because
693 of the necessary translation to |ASCII_code| values.
694 \MP's conventions should be efficient, and they should
695 blend nicely with the user's operating environment.
696
697 @ Input from text files is read one line at a time, using a routine called
698 |input_ln|. This function is defined in terms of global variables called
699 |buffer|, |first|, and |last| that will be described in detail later; for
700 now, it suffices for us to know that |buffer| is an array of |ASCII_code|
701 values, and that |first| and |last| are indices into this array
702 representing the beginning and ending of a line of text.
703
704 @<Glob...@>=
705 size_t buf_size; /* maximum number of characters simultaneously present in
706                     current lines of open files */
707 ASCII_code *buffer; /* lines of characters being read */
708 size_t first; /* the first unused position in |buffer| */
709 size_t last; /* end of the line just input to |buffer| */
710 size_t max_buf_stack; /* largest index used in |buffer| */
711
712 @ @<Allocate or initialize ...@>=
713 mp->buf_size = 200;
714 mp->buffer = xmalloc((mp->buf_size+1),sizeof(ASCII_code));
715
716 @ @<Dealloc variables@>=
717 xfree(mp->buffer);
718
719 @ @c
720 void mp_reallocate_buffer(MP mp, size_t l) {
721   ASCII_code *buffer;
722   if (l>max_halfword) {
723     mp_confusion(mp,"buffer size"); /* can't happen (I hope) */
724   }
725   buffer = xmalloc((l+1),sizeof(ASCII_code));
726   memcpy(buffer,mp->buffer,(mp->buf_size+1));
727   xfree(mp->buffer);
728   mp->buffer = buffer ;
729   mp->buf_size = l;
730 }
731
732 @ The |input_ln| function brings the next line of input from the specified
733 field into available positions of the buffer array and returns the value
734 |true|, unless the file has already been entirely read, in which case it
735 returns |false| and sets |last:=first|.  In general, the |ASCII_code|
736 numbers that represent the next line of the file are input into
737 |buffer[first]|, |buffer[first+1]|, \dots, |buffer[last-1]|; and the
738 global variable |last| is set equal to |first| plus the length of the
739 line. Trailing blanks are removed from the line; thus, either |last=first|
740 (in which case the line was entirely blank) or |buffer[last-1]<>" "|.
741 @^inner loop@>
742
743 An overflow error is given, however, if the normal actions of |input_ln|
744 would make |last>=buf_size|; this is done so that other parts of \MP\
745 can safely look at the contents of |buffer[last+1]| without overstepping
746 the bounds of the |buffer| array. Upon entry to |input_ln|, the condition
747 |first<buf_size| will always hold, so that there is always room for an
748 ``empty'' line.
749
750 The variable |max_buf_stack|, which is used to keep track of how large
751 the |buf_size| parameter must be to accommodate the present job, is
752 also kept up to date by |input_ln|.
753
754 If the |bypass_eoln| parameter is |true|, |input_ln| will do a |get|
755 before looking at the first character of the line; this skips over
756 an |eoln| that was in |f^|. The procedure does not do a |get| when it
757 reaches the end of the line; therefore it can be used to acquire input
758 from the user's terminal as well as from ordinary text files.
759
760 Standard \PASCAL\ says that a file should have |eoln| immediately
761 before |eof|, but \MP\ needs only a weaker restriction: If |eof|
762 occurs in the middle of a line, the system function |eoln| should return
763 a |true| result (even though |f^| will be undefined).
764
765 @c 
766 boolean mp_input_ln (MP mp,FILE *  f, boolean bypass_eoln) {
767   /* inputs the next line or returns |false| */
768   int last_nonblank; /* |last| with trailing blanks removed */
769   int c;
770   if ( bypass_eoln ) {
771     c = fgetc(f);
772     if (c==EOF)
773       return false;
774     if (c!='\n' && c!='\r') {
775       ungetc(c,f);
776     }
777   }
778   /* input the first character of the line into |f^| */
779   mp->last=mp->first; /* cf.\ Matthew 19\thinspace:\thinspace30 */
780   c = fgetc(f);
781   if (c==EOF)
782         return false;
783   last_nonblank=mp->first;
784   while (c!=EOF && c!='\n' && c!='\r') { 
785     if ( mp->last>=mp->max_buf_stack ) { 
786       mp->max_buf_stack=mp->last+1;
787       if ( mp->max_buf_stack==mp->buf_size ) {
788         mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
789       }
790     }
791     mp->buffer[mp->last]=xord(c); 
792     incr(mp->last);
793     if ( mp->buffer[mp->last-1]!=' ' ) 
794       last_nonblank=mp->last;
795     c = fgetc(f); 
796   } 
797   if (c!=EOF) {
798     ungetc(c,f);
799   }
800   mp->last=last_nonblank; 
801   return true;
802 }
803
804 @ The user's terminal acts essentially like other files of text, except
805 that it is used both for input and for output. When the terminal is
806 considered an input file, the file variable is called |term_in|, and when it
807 is considered an output file the file variable is |term_out|.
808 @^system dependencies@>
809
810 @<Glob...@>=
811 FILE * term_in; /* the terminal as an input file */
812 FILE * term_out; /* the terminal as an output file */
813
814 @ Here is how to open the terminal files. In the default configuration,
815 nothing happens except that the command line (if there is one) is copied
816 to the input buffer.  The variable |command_line| will be filled by the 
817 |main| procedure. The copying can not be done earlier in the program 
818 logic because in the |INI| version, the |buffer| is also used for primitive 
819 initialization.
820
821 @^system dependencies@>
822
823 @d t_open_out  /* open the terminal for text output */
824 @d t_open_in  do { /* open the terminal for text input */
825     if (mp->command_line!=NULL) {
826       mp->last = strlen(mp->command_line);
827       strncpy((char *)mp->buffer,mp->command_line,mp->last);
828       xfree(mp->command_line);
829     }
830 } while (0)
831
832 @<Glob...@>=
833 char *command_line;
834
835 @ @<Option variables@>=
836 char *command_line;
837
838 @ @<Allocate or initialize ...@>=
839 mp->command_line = opt->command_line;
840
841 @ Sometimes it is necessary to synchronize the input/output mixture that
842 happens on the user's terminal, and three system-dependent
843 procedures are used for this
844 purpose. The first of these, |update_terminal|, is called when we want
845 to make sure that everything we have output to the terminal so far has
846 actually left the computer's internal buffers and been sent.
847 The second, |clear_terminal|, is called when we wish to cancel any
848 input that the user may have typed ahead (since we are about to
849 issue an unexpected error message). The third, |wake_up_terminal|,
850 is supposed to revive the terminal if the user has disabled it by
851 some instruction to the operating system.  The following macros show how
852 these operations can be specified in \ph:
853 @^system dependencies@>
854
855 @d update_terminal   fflush(mp->term_out) /* empty the terminal output buffer */
856 @d clear_terminal   do_nothing /* clear the terminal input buffer */
857 @d wake_up_terminal  fflush(mp->term_out) /* cancel the user's cancellation of output */
858
859 @ We need a special routine to read the first line of \MP\ input from
860 the user's terminal. This line is different because it is read before we
861 have opened the transcript file; there is sort of a ``chicken and
862 egg'' problem here. If the user types `\.{input cmr10}' on the first
863 line, or if some macro invoked by that line does such an \.{input},
864 the transcript file will be named `\.{cmr10.log}'; but if no \.{input}
865 commands are performed during the first line of terminal input, the transcript
866 file will acquire its default name `\.{mpout.log}'. (The transcript file
867 will not contain error messages generated by the first line before the
868 first \.{input} command.)
869
870 The first line is even more special if we are lucky enough to have an operating
871 system that treats \MP\ differently from a run-of-the-mill \PASCAL\ object
872 program. It's nice to let the user start running a \MP\ job by typing
873 a command line like `\.{MP cmr10}'; in such a case, \MP\ will operate
874 as if the first line of input were `\.{cmr10}', i.e., the first line will
875 consist of the remainder of the command line, after the part that invoked \MP.
876
877 @ Different systems have different ways to get started. But regardless of
878 what conventions are adopted, the routine that initializes the terminal
879 should satisfy the following specifications:
880
881 \yskip\textindent{1)}It should open file |term_in| for input from the
882   terminal. (The file |term_out| will already be open for output to the
883   terminal.)
884
885 \textindent{2)}If the user has given a command line, this line should be
886   considered the first line of terminal input. Otherwise the
887   user should be prompted with `\.{**}', and the first line of input
888   should be whatever is typed in response.
889
890 \textindent{3)}The first line of input, which might or might not be a
891   command line, should appear in locations |first| to |last-1| of the
892   |buffer| array.
893
894 \textindent{4)}The global variable |loc| should be set so that the
895   character to be read next by \MP\ is in |buffer[loc]|. This
896   character should not be blank, and we should have |loc<last|.
897
898 \yskip\noindent(It may be necessary to prompt the user several times
899 before a non-blank line comes in. The prompt is `\.{**}' instead of the
900 later `\.*' because the meaning is slightly different: `\.{input}' need
901 not be typed immediately after~`\.{**}'.)
902
903 @d loc mp->cur_input.loc_field /* location of first unread character in |buffer| */
904
905 @ The following program does the required initialization
906 without retrieving a possible command line.
907 It should be clear how to modify this routine to deal with command lines,
908 if the system permits them.
909 @^system dependencies@>
910
911 @c 
912 boolean mp_init_terminal (MP mp) { /* gets the terminal input started */
913   t_open_in; 
914   if (mp->last!=0) {
915     loc = mp->first = 0;
916         return true;
917   }
918   while (1) { 
919     wake_up_terminal; fprintf(mp->term_out,"**"); update_terminal;
920 @.**@>
921     if ( ! mp_input_ln(mp, mp->term_in,true) ) { /* this shouldn't happen */
922       fprintf(mp->term_out,"\n! End of file on the terminal... why?");
923 @.End of file on the terminal@>
924       return false;
925     }
926     loc=mp->first;
927     while ( (loc<(int)mp->last)&&(mp->buffer[loc]==' ') ) 
928       incr(loc);
929     if ( loc<(int)mp->last ) { 
930       return true; /* return unless the line was all blank */
931     };
932     fprintf(mp->term_out,"Please type the name of your input file.\n");
933   }
934 }
935
936 @ @<Declarations@>=
937 boolean mp_init_terminal (MP mp) ;
938
939
940 @* \[4] String handling.
941 Symbolic token names and diagnostic messages are variable-length strings
942 of eight-bit characters. Since \PASCAL\ does not have a well-developed string
943 mechanism, \MP\ does all of its string processing by homegrown methods.
944
945 \MP\ uses strings more extensively than \MF\ does, but the necessary
946 operations can still be handled with a fairly simple data structure.
947 The array |str_pool| contains all of the (eight-bit) ASCII codes in all
948 of the strings, and the array |str_start| contains indices of the starting
949 points of each string. Strings are referred to by integer numbers, so that
950 string number |s| comprises the characters |str_pool[j]| for
951 |str_start[s]<=j<str_start[ss]| where |ss=next_str[s]|.  The string pool
952 is allocated sequentially and |str_pool[pool_ptr]| is the next unused
953 location.  The first string number not currently in use is |str_ptr|
954 and |next_str[str_ptr]| begins a list of free string numbers.  String
955 pool entries |str_start[str_ptr]| up to |pool_ptr| are reserved for a
956 string currently being constructed.
957
958 String numbers 0 to 255 are reserved for strings that correspond to single
959 ASCII characters. This is in accordance with the conventions of \.{WEB},
960 @.WEB@>
961 which converts single-character strings into the ASCII code number of the
962 single character involved, while it converts other strings into integers
963 and builds a string pool file. Thus, when the string constant \.{"."} appears
964 in the program below, \.{WEB} converts it into the integer 46, which is the
965 ASCII code for a period, while \.{WEB} will convert a string like \.{"hello"}
966 into some integer greater than~255. String number 46 will presumably be the
967 single character `\..'\thinspace; but some ASCII codes have no standard visible
968 representation, and \MP\ may need to be able to print an arbitrary
969 ASCII character, so the first 256 strings are used to specify exactly what
970 should be printed for each of the 256 possibilities.
971
972 @<Types...@>=
973 typedef int pool_pointer; /* for variables that point into |str_pool| */
974 typedef int str_number; /* for variables that point into |str_start| */
975
976 @ @<Glob...@>=
977 ASCII_code *str_pool; /* the characters */
978 pool_pointer *str_start; /* the starting pointers */
979 str_number *next_str; /* for linking strings in order */
980 pool_pointer pool_ptr; /* first unused position in |str_pool| */
981 str_number str_ptr; /* number of the current string being created */
982 pool_pointer init_pool_ptr; /* the starting value of |pool_ptr| */
983 str_number init_str_use; /* the initial number of strings in use */
984 pool_pointer max_pool_ptr; /* the maximum so far of |pool_ptr| */
985 str_number max_str_ptr; /* the maximum so far of |str_ptr| */
986
987 @ @<Allocate or initialize ...@>=
988 mp->str_pool  = xmalloc ((mp->pool_size +1),sizeof(ASCII_code));
989 mp->str_start = xmalloc ((mp->max_strings+1),sizeof(pool_pointer));
990 mp->next_str  = xmalloc ((mp->max_strings+1),sizeof(str_number));
991
992 @ @<Dealloc variables@>=
993 xfree(mp->str_pool);
994 xfree(mp->str_start);
995 xfree(mp->next_str);
996
997 @ Most printing is done from |char *|s, but sometimes not. Here are
998 functions that convert an internal string into a |char *| for use
999 by the printing routines, and vice versa.
1000
1001 @d str(A) mp_str(mp,A)
1002 @d rts(A) mp_rts(mp,A)
1003
1004 @<Internal ...@>=
1005 int mp_xstrcmp (const char *a, const char *b);
1006 char * mp_str (MP mp, str_number s);
1007
1008 @ @<Declarations@>=
1009 str_number mp_rts (MP mp, char *s);
1010 str_number mp_make_string (MP mp);
1011
1012 @ The attempt to catch interrupted strings that is in |mp_rts|, is not 
1013 very good: it does not handle nesting over more than one level.
1014
1015 @c 
1016 int mp_xstrcmp (const char *a, const char *b) {
1017         if (a==NULL && b==NULL) 
1018           return 0;
1019     if (a==NULL)
1020       return -1;
1021     if (b==NULL)
1022       return 1;
1023     return strcmp(a,b);
1024 }
1025
1026 @ @c
1027 char * mp_str (MP mp, str_number ss) {
1028   char *s;
1029   int len;
1030   if (ss==mp->str_ptr) {
1031     return NULL;
1032   } else {
1033     len = length(ss);
1034     s = xmalloc(len+1,sizeof(char));
1035     strncpy(s,(char *)(mp->str_pool+(mp->str_start[ss])),len);
1036     s[len] = 0;
1037     return (char *)s;
1038   }
1039 }
1040 str_number mp_rts (MP mp, char *s) {
1041   int r; /* the new string */ 
1042   int old; /* a possible string in progress */
1043   int i=0;
1044   if (strlen(s)==0) {
1045     return 256;
1046   } else if (strlen(s)==1) {
1047     return s[0];
1048   } else {
1049    old=0;
1050    str_room((integer)strlen(s));
1051    if (mp->str_start[mp->str_ptr]<mp->pool_ptr)
1052      old = mp_make_string(mp);
1053    while (*s) {
1054      append_char(*s);
1055      s++;
1056    }
1057    r = mp_make_string(mp);
1058    if (old!=0) {
1059       str_room(length(old));
1060       while (i<length(old)) {
1061         append_char((mp->str_start[old]+i));
1062       } 
1063       mp_flush_string(mp,old);
1064     }
1065     return r;
1066   }
1067 }
1068
1069 @ Except for |strs_used_up|, the following string statistics are only
1070 maintained when code between |stat| $\ldots$ |tats| delimiters is not
1071 commented out:
1072
1073 @<Glob...@>=
1074 integer strs_used_up; /* strings in use or unused but not reclaimed */
1075 integer pool_in_use; /* total number of cells of |str_pool| actually in use */
1076 integer strs_in_use; /* total number of strings actually in use */
1077 integer max_pl_used; /* maximum |pool_in_use| so far */
1078 integer max_strs_used; /* maximum |strs_in_use| so far */
1079
1080 @ Several of the elementary string operations are performed using \.{WEB}
1081 macros instead of \PASCAL\ procedures, because many of the
1082 operations are done quite frequently and we want to avoid the
1083 overhead of procedure calls. For example, here is
1084 a simple macro that computes the length of a string.
1085 @.WEB@>
1086
1087 @d str_stop(A) mp->str_start[mp->next_str[(A)]] /* one cell past the end of string
1088   number \# */
1089 @d length(A) (str_stop((A))-mp->str_start[(A)]) /* the number of characters in string \# */
1090
1091 @ The length of the current string is called |cur_length|.  If we decide that
1092 the current string is not needed, |flush_cur_string| resets |pool_ptr| so that
1093 |cur_length| becomes zero.
1094
1095 @d cur_length   (mp->pool_ptr - mp->str_start[mp->str_ptr])
1096 @d flush_cur_string   mp->pool_ptr=mp->str_start[mp->str_ptr]
1097
1098 @ Strings are created by appending character codes to |str_pool|.
1099 The |append_char| macro, defined here, does not check to see if the
1100 value of |pool_ptr| has gotten too high; this test is supposed to be
1101 made before |append_char| is used.
1102
1103 To test if there is room to append |l| more characters to |str_pool|,
1104 we shall write |str_room(l)|, which tries to make sure there is enough room
1105 by compacting the string pool if necessary.  If this does not work,
1106 |do_compaction| aborts \MP\ and gives an apologetic error message.
1107
1108 @d append_char(A)   /* put |ASCII_code| \# at the end of |str_pool| */
1109 { mp->str_pool[mp->pool_ptr]=(A); incr(mp->pool_ptr);
1110 }
1111 @d str_room(A)   /* make sure that the pool hasn't overflowed */
1112   { if ( mp->pool_ptr+(A) > mp->max_pool_ptr ) {
1113     if ( mp->pool_ptr+(A) > mp->pool_size ) mp_do_compaction(mp, (A));
1114     else mp->max_pool_ptr=mp->pool_ptr+(A); }
1115   }
1116
1117 @ The following routine is similar to |str_room(1)| but it uses the
1118 argument |mp->pool_size| to prevent |do_compaction| from aborting when
1119 string space is exhausted.
1120
1121 @<Declare the procedure called |unit_str_room|@>=
1122 void mp_unit_str_room (MP mp);
1123
1124 @ @c
1125 void mp_unit_str_room (MP mp) { 
1126   if ( mp->pool_ptr>=mp->pool_size ) mp_do_compaction(mp, mp->pool_size);
1127   if ( mp->pool_ptr>=mp->max_pool_ptr ) mp->max_pool_ptr=mp->pool_ptr+1;
1128 }
1129
1130 @ \MP's string expressions are implemented in a brute-force way: Every
1131 new string or substring that is needed is simply copied into the string pool.
1132 Space is eventually reclaimed by a procedure called |do_compaction| with
1133 the aid of a simple system system of reference counts.
1134 @^reference counts@>
1135
1136 The number of references to string number |s| will be |str_ref[s]|. The
1137 special value |str_ref[s]=max_str_ref=127| is used to denote an unknown
1138 positive number of references; such strings will never be recycled. If
1139 a string is ever referred to more than 126 times, simultaneously, we
1140 put it in this category. Hence a single byte suffices to store each |str_ref|.
1141
1142 @d max_str_ref 127 /* ``infinite'' number of references */
1143 @d add_str_ref(A) { if ( mp->str_ref[(A)]<max_str_ref ) incr(mp->str_ref[(A)]);
1144   }
1145
1146 @<Glob...@>=
1147 int *str_ref;
1148
1149 @ @<Allocate or initialize ...@>=
1150 mp->str_ref = xmalloc ((mp->max_strings+1),sizeof(int));
1151
1152 @ @<Dealloc variables@>=
1153 xfree(mp->str_ref);
1154
1155 @ Here's what we do when a string reference disappears:
1156
1157 @d delete_str_ref(A)  { 
1158     if ( mp->str_ref[(A)]<max_str_ref ) {
1159        if ( mp->str_ref[(A)]>1 ) decr(mp->str_ref[(A)]); 
1160        else mp_flush_string(mp, (A));
1161     }
1162   }
1163
1164 @<Declare the procedure called |flush_string|@>=
1165 void mp_flush_string (MP mp,str_number s) ;
1166
1167
1168 @ We can't flush the first set of static strings at all, so there 
1169 is no point in trying
1170
1171 @c
1172 void mp_flush_string (MP mp,str_number s) { 
1173   if (length(s)>1) {
1174     mp->pool_in_use=mp->pool_in_use-length(s);
1175     decr(mp->strs_in_use);
1176     if ( mp->next_str[s]!=mp->str_ptr ) {
1177       mp->str_ref[s]=0;
1178     } else { 
1179       mp->str_ptr=s;
1180       decr(mp->strs_used_up);
1181     }
1182     mp->pool_ptr=mp->str_start[mp->str_ptr];
1183   }
1184 }
1185
1186 @ C literals cannot be simply added, they need to be set so they can't
1187 be flushed.
1188
1189 @d intern(A) mp_intern(mp,(A))
1190
1191 @c
1192 str_number mp_intern (MP mp, char *s) {
1193   str_number r ;
1194   r = rts(s);
1195   mp->str_ref[r] = max_str_ref;
1196   return r;
1197 }
1198
1199 @ @<Declarations@>=
1200 str_number mp_intern (MP mp, char *s);
1201
1202
1203 @ Once a sequence of characters has been appended to |str_pool|, it
1204 officially becomes a string when the function |make_string| is called.
1205 This function returns the identification number of the new string as its
1206 value.
1207
1208 When getting the next unused string number from the linked list, we pretend
1209 that
1210 $$ \hbox{|max_str_ptr+1|, |max_str_ptr+2|, $\ldots$, |mp->max_strings|} $$
1211 are linked sequentially even though the |next_str| entries have not been
1212 initialized yet.  We never allow |str_ptr| to reach |mp->max_strings|;
1213 |do_compaction| is responsible for making sure of this.
1214
1215 @<Declarations@>=
1216 @<Declare the procedure called |do_compaction|@>;
1217 @<Declare the procedure called |unit_str_room|@>;
1218 str_number mp_make_string (MP mp);
1219
1220 @ @c 
1221 str_number mp_make_string (MP mp) { /* current string enters the pool */
1222   str_number s; /* the new string */
1223 RESTART: 
1224   s=mp->str_ptr;
1225   mp->str_ptr=mp->next_str[s];
1226   if ( mp->str_ptr>mp->max_str_ptr ) {
1227     if ( mp->str_ptr==mp->max_strings ) { 
1228       mp->str_ptr=s;
1229       mp_do_compaction(mp, 0);
1230       goto RESTART;
1231     } else {
1232 #ifdef DEBUG 
1233       if ( mp->strs_used_up!=mp->max_str_ptr ) mp_confusion(mp, "s");
1234 @:this can't happen s}{\quad \.s@>
1235 #endif
1236       mp->max_str_ptr=mp->str_ptr;
1237       mp->next_str[mp->str_ptr]=mp->max_str_ptr+1;
1238     }
1239   }
1240   mp->str_ref[s]=1;
1241   mp->str_start[mp->str_ptr]=mp->pool_ptr;
1242   incr(mp->strs_used_up);
1243   incr(mp->strs_in_use);
1244   mp->pool_in_use=mp->pool_in_use+length(s);
1245   if ( mp->pool_in_use>mp->max_pl_used ) 
1246     mp->max_pl_used=mp->pool_in_use;
1247   if ( mp->strs_in_use>mp->max_strs_used ) 
1248     mp->max_strs_used=mp->strs_in_use;
1249   return s;
1250 }
1251
1252 @ The most interesting string operation is string pool compaction.  The idea
1253 is to recover unused space in the |str_pool| array by recopying the strings
1254 to close the gaps created when some strings become unused.  All string
1255 numbers~$k$ where |str_ref[k]=0| are to be linked into the list of free string
1256 numbers after |str_ptr|.  If this fails to free enough pool space we issue an
1257 |overflow| error unless |needed=mp->pool_size|.  Calling |do_compaction|
1258 with |needed=mp->pool_size| supresses all overflow tests.
1259
1260 The compaction process starts with |last_fixed_str| because all lower numbered
1261 strings are permanently allocated with |max_str_ref| in their |str_ref| entries.
1262
1263 @<Glob...@>=
1264 str_number last_fixed_str; /* last permanently allocated string */
1265 str_number fixed_str_use; /* number of permanently allocated strings */
1266
1267 @ @<Declare the procedure called |do_compaction|@>=
1268 void mp_do_compaction (MP mp, pool_pointer needed) ;
1269
1270 @ @c
1271 void mp_do_compaction (MP mp, pool_pointer needed) {
1272   str_number str_use; /* a count of strings in use */
1273   str_number r,s,t; /* strings being manipulated */
1274   pool_pointer p,q; /* destination and source for copying string characters */
1275   @<Advance |last_fixed_str| as far as possible and set |str_use|@>;
1276   r=mp->last_fixed_str;
1277   s=mp->next_str[r];
1278   p=mp->str_start[s];
1279   while ( s!=mp->str_ptr ) { 
1280     while ( mp->str_ref[s]==0 ) {
1281       @<Advance |s| and add the old |s| to the list of free string numbers;
1282         then |break| if |s=str_ptr|@>;
1283     }
1284     r=s; s=mp->next_str[s];
1285     incr(str_use);
1286     @<Move string |r| back so that |str_start[r]=p|; make |p| the location
1287      after the end of the string@>;
1288   }
1289   @<Move the current string back so that it starts at |p|@>;
1290   if ( needed<mp->pool_size ) {
1291     @<Make sure that there is room for another string with |needed| characters@>;
1292   }
1293   @<Account for the compaction and make sure the statistics agree with the
1294      global versions@>;
1295   mp->strs_used_up=str_use;
1296 }
1297
1298 @ @<Advance |last_fixed_str| as far as possible and set |str_use|@>=
1299 t=mp->next_str[mp->last_fixed_str];
1300 while (t!=mp->str_ptr && mp->str_ref[t]==max_str_ref) {
1301   incr(mp->fixed_str_use);
1302   mp->last_fixed_str=t;
1303   t=mp->next_str[t];
1304 }
1305 str_use=mp->fixed_str_use
1306
1307 @ Because of the way |flush_string| has been written, it should never be
1308 necessary to |break| here.  The extra line of code seems worthwhile to
1309 preserve the generality of |do_compaction|.
1310
1311 @<Advance |s| and add the old |s| to the list of free string numbers;...@>=
1312 {
1313 t=s;
1314 s=mp->next_str[s];
1315 mp->next_str[r]=s;
1316 mp->next_str[t]=mp->next_str[mp->str_ptr];
1317 mp->next_str[mp->str_ptr]=t;
1318 if ( s==mp->str_ptr ) break;
1319 }
1320
1321 @ The string currently starts at |str_start[r]| and ends just before
1322 |str_start[s]|.  We don't change |str_start[s]| because it might be needed
1323 to locate the next string.
1324
1325 @<Move string |r| back so that |str_start[r]=p|; make |p| the location...@>=
1326 q=mp->str_start[r];
1327 mp->str_start[r]=p;
1328 while ( q<mp->str_start[s] ) { 
1329   mp->str_pool[p]=mp->str_pool[q];
1330   incr(p); incr(q);
1331 }
1332
1333 @ Pointers |str_start[str_ptr]| and |pool_ptr| have not been updated.  When
1334 we do this, anything between them should be moved.
1335
1336 @ @<Move the current string back so that it starts at |p|@>=
1337 q=mp->str_start[mp->str_ptr];
1338 mp->str_start[mp->str_ptr]=p;
1339 while ( q<mp->pool_ptr ) { 
1340   mp->str_pool[p]=mp->str_pool[q];
1341   incr(p); incr(q);
1342 }
1343 mp->pool_ptr=p
1344
1345 @ We must remember that |str_ptr| is not allowed to reach |mp->max_strings|.
1346
1347 @<Make sure that there is room for another string with |needed| char...@>=
1348 if ( str_use>=mp->max_strings-1 )
1349   mp_reallocate_strings (mp,str_use);
1350 if ( mp->pool_ptr+needed>mp->max_pool_ptr ) {
1351   mp_reallocate_pool(mp, mp->pool_ptr+needed);
1352   mp->max_pool_ptr=mp->pool_ptr+needed;
1353 }
1354
1355 @ @<Declarations@>=
1356 void mp_reallocate_strings (MP mp, str_number str_use) ;
1357 void mp_reallocate_pool(MP mp, pool_pointer needed) ;
1358
1359 @ @c 
1360 void mp_reallocate_strings (MP mp, str_number str_use) { 
1361   while ( str_use>=mp->max_strings-1 ) {
1362     int l = mp->max_strings + (mp->max_strings>>2);
1363     XREALLOC (mp->str_ref,   l, int);
1364     XREALLOC (mp->str_start, l, pool_pointer);
1365     XREALLOC (mp->next_str,  l, str_number);
1366     mp->max_strings = l;
1367   }
1368 }
1369 void mp_reallocate_pool(MP mp, pool_pointer needed) {
1370   while ( needed>mp->pool_size ) {
1371     int l = mp->pool_size + (mp->pool_size>>2);
1372         XREALLOC (mp->str_pool, l, ASCII_code);
1373     mp->pool_size = l;
1374   }
1375 }
1376
1377 @ @<Account for the compaction and make sure the statistics agree with...@>=
1378 if ( (mp->str_start[mp->str_ptr]!=mp->pool_in_use)||(str_use!=mp->strs_in_use) )
1379   mp_confusion(mp, "string");
1380 @:this can't happen string}{\quad string@>
1381 incr(mp->pact_count);
1382 mp->pact_chars=mp->pact_chars+mp->pool_ptr-str_stop(mp->last_fixed_str);
1383 mp->pact_strs=mp->pact_strs+str_use-mp->fixed_str_use;
1384 #ifdef DEBUG
1385 s=mp->str_ptr; t=str_use;
1386 while ( s<=mp->max_str_ptr ){
1387   if ( t>mp->max_str_ptr ) mp_confusion(mp, "\"");
1388   incr(t); s=mp->next_str[s];
1389 };
1390 if ( t<=mp->max_str_ptr ) mp_confusion(mp, "\"");
1391 #endif
1392
1393 @ A few more global variables are needed to keep track of statistics when
1394 |stat| $\ldots$ |tats| blocks are not commented out.
1395
1396 @<Glob...@>=
1397 integer pact_count; /* number of string pool compactions so far */
1398 integer pact_chars; /* total number of characters moved during compactions */
1399 integer pact_strs; /* total number of strings moved during compactions */
1400
1401 @ @<Initialize compaction statistics@>=
1402 mp->pact_count=0;
1403 mp->pact_chars=0;
1404 mp->pact_strs=0;
1405
1406 @ The following subroutine compares string |s| with another string of the
1407 same length that appears in |buffer| starting at position |k|;
1408 the result is |true| if and only if the strings are equal.
1409
1410 @c 
1411 boolean mp_str_eq_buf (MP mp,str_number s, integer k) {
1412   /* test equality of strings */
1413   pool_pointer j; /* running index */
1414   j=mp->str_start[s];
1415   while ( j<str_stop(s) ) { 
1416     if ( mp->str_pool[j++]!=mp->buffer[k++] ) 
1417       return false;
1418   }
1419   return true;
1420 }
1421
1422 @ Here is a similar routine, but it compares two strings in the string pool,
1423 and it does not assume that they have the same length. If the first string
1424 is lexicographically greater than, less than, or equal to the second,
1425 the result is respectively positive, negative, or zero.
1426
1427 @c 
1428 integer mp_str_vs_str (MP mp, str_number s, str_number t) {
1429   /* test equality of strings */
1430   pool_pointer j,k; /* running indices */
1431   integer ls,lt; /* lengths */
1432   integer l; /* length remaining to test */
1433   ls=length(s); lt=length(t);
1434   if ( ls<=lt ) l=ls; else l=lt;
1435   j=mp->str_start[s]; k=mp->str_start[t];
1436   while ( l-->0 ) { 
1437     if ( mp->str_pool[j]!=mp->str_pool[k] ) {
1438        return (mp->str_pool[j]-mp->str_pool[k]); 
1439     }
1440     incr(j); incr(k);
1441   }
1442   return (ls-lt);
1443 }
1444
1445 @ The initial values of |str_pool|, |str_start|, |pool_ptr|,
1446 and |str_ptr| are computed by the \.{INIMP} program, based in part
1447 on the information that \.{WEB} has output while processing \MP.
1448 @.INIMP@>
1449 @^string pool@>
1450
1451 @c 
1452 void mp_get_strings_started (MP mp) { 
1453   /* initializes the string pool,
1454     but returns |false| if something goes wrong */
1455   int k; /* small indices or counters */
1456   str_number g; /* a new string */
1457   mp->pool_ptr=0; mp->str_ptr=0; mp->max_pool_ptr=0; mp->max_str_ptr=0;
1458   mp->str_start[0]=0;
1459   mp->next_str[0]=1;
1460   mp->pool_in_use=0; mp->strs_in_use=0;
1461   mp->max_pl_used=0; mp->max_strs_used=0;
1462   @<Initialize compaction statistics@>;
1463   mp->strs_used_up=0;
1464   @<Make the first 256 strings@>;
1465   g=mp_make_string(mp); /* string 256 == "" */
1466   mp->str_ref[g]=max_str_ref;
1467   mp->last_fixed_str=mp->str_ptr-1;
1468   mp->fixed_str_use=mp->str_ptr;
1469   return;
1470 }
1471
1472 @ @<Declarations@>=
1473 void mp_get_strings_started (MP mp);
1474
1475 @ The first 256 strings will consist of a single character only.
1476
1477 @<Make the first 256...@>=
1478 for (k=0;k<=255;k++) { 
1479   append_char(k);
1480   g=mp_make_string(mp); 
1481   mp->str_ref[g]=max_str_ref;
1482 }
1483
1484 @ The first 128 strings will contain 95 standard ASCII characters, and the
1485 other 33 characters will be printed in three-symbol form like `\.{\^\^A}'
1486 unless a system-dependent change is made here. Installations that have
1487 an extended character set, where for example |xchr[032]=@t\.{'^^Z'}@>|,
1488 would like string 032 to be printed as the single character 032 instead
1489 of the three characters 0136, 0136, 0132 (\.{\^\^Z}). On the other hand,
1490 even people with an extended character set will want to represent string
1491 015 by \.{\^\^M}, since 015 is ASCII's ``carriage return'' code; the idea is
1492 to produce visible strings instead of tabs or line-feeds or carriage-returns
1493 or bell-rings or characters that are treated anomalously in text files.
1494
1495 Unprintable characters of codes 128--255 are, similarly, rendered
1496 \.{\^\^80}--\.{\^\^ff}.
1497
1498 The boolean expression defined here should be |true| unless \MP\ internal
1499 code number~|k| corresponds to a non-troublesome visible symbol in the
1500 local character set.
1501 If character |k| cannot be printed, and |k<0200|, then character |k+0100| or
1502 |k-0100| must be printable; moreover, ASCII codes |[060..071, 0141..0146]|
1503 must be printable.
1504 @^character set dependencies@>
1505 @^system dependencies@>
1506
1507 @<Character |k| cannot be printed@>=
1508   (k<' ')||(k>'~')
1509
1510 @* \[5] On-line and off-line printing.
1511 Messages that are sent to a user's terminal and to the transcript-log file
1512 are produced by several `|print|' procedures. These procedures will
1513 direct their output to a variety of places, based on the setting of
1514 the global variable |selector|, which has the following possible
1515 values:
1516
1517 \yskip
1518 \hang |term_and_log|, the normal setting, prints on the terminal and on the
1519   transcript file.
1520
1521 \hang |log_only|, prints only on the transcript file.
1522
1523 \hang |term_only|, prints only on the terminal.
1524
1525 \hang |no_print|, doesn't print at all. This is used only in rare cases
1526   before the transcript file is open.
1527
1528 \hang |ps_file_only| prints only on the \ps\ output file.
1529
1530 \hang |pseudo|, puts output into a cyclic buffer that is used
1531   by the |show_context| routine; when we get to that routine we shall discuss
1532   the reasoning behind this curious mode.
1533
1534 \hang |new_string|, appends the output to the current string in the
1535   string pool.
1536
1537 \hang |>=write_file| prints on one of the files used for the \&{write}
1538 @:write_}{\&{write} primitive@>
1539   command.
1540
1541 \yskip
1542 \noindent The symbolic names `|term_and_log|', etc., have been assigned
1543 numeric codes that satisfy the convenient relations |no_print+1=term_only|,
1544 |no_print+2=log_only|, |term_only+2=log_only+1=term_and_log|.  These
1545 relations are not used when |selector| could be |pseudo|, |new_string|,
1546 or |ps_file_only|.  We need not check for unprintable characters when
1547 |selector<pseudo|.
1548
1549 Four additional global variables, |tally|, |term_offset|, |file_offset|,
1550 and |ps_offset| record the number of characters that have been printed
1551 since they were most recently cleared to zero. We use |tally| to record
1552 the length of (possibly very long) stretches of printing; |term_offset|,
1553 |file_offset|, and |ps_offset|, on the other hand, keep track of how many
1554 characters have appeared so far on the current line that has been output
1555 to the terminal, the transcript file, or the \ps\ output file, respectively.
1556
1557 @d new_string 0 /* printing is deflected to the string pool */
1558 @d ps_file_only 1 /* printing goes to the \ps\ output file */
1559 @d pseudo 2 /* special |selector| setting for |show_context| */
1560 @d no_print 3 /* |selector| setting that makes data disappear */
1561 @d term_only 4 /* printing is destined for the terminal only */
1562 @d log_only 5 /* printing is destined for the transcript file only */
1563 @d term_and_log 6 /* normal |selector| setting */
1564 @d write_file 7 /* first write file selector */
1565
1566 @<Glob...@>=
1567 FILE * log_file; /* transcript of \MP\ session */
1568 FILE * ps_file; /* the generic font output goes here */
1569 unsigned int selector; /* where to print a message */
1570 unsigned char dig[23]; /* digits in a number being output */
1571 integer tally; /* the number of characters recently printed */
1572 unsigned int term_offset;
1573   /* the number of characters on the current terminal line */
1574 unsigned int file_offset;
1575   /* the number of characters on the current file line */
1576 integer ps_offset;
1577   /* the number of characters on the current \ps\ file line */
1578 ASCII_code *trick_buf; /* circular buffer for pseudoprinting */
1579 integer trick_count; /* threshold for pseudoprinting, explained later */
1580 integer first_count; /* another variable for pseudoprinting */
1581
1582 @ @<Allocate or initialize ...@>=
1583 memset(mp->dig,0,23);
1584 mp->trick_buf = xmalloc((mp->error_line+1),sizeof(ASCII_code));
1585
1586 @ @<Dealloc variables@>=
1587 xfree(mp->trick_buf);
1588
1589 @ @<Initialize the output routines@>=
1590 mp->selector=term_only; mp->tally=0; mp->term_offset=0; mp->file_offset=0; mp->ps_offset=0;
1591
1592 @ Macro abbreviations for output to the terminal and to the log file are
1593 defined here for convenience. Some systems need special conventions
1594 for terminal output, and it is possible to adhere to those conventions
1595 by changing |wterm|, |wterm_ln|, and |wterm_cr| here.
1596 @^system dependencies@>
1597
1598 @d wterm(A)    fprintf(mp->term_out,"%s",(A))
1599 @d wterm_chr(A)fprintf(mp->term_out,"%c",(A))
1600 @d wterm_ln(A) fprintf(mp->term_out,"\n%s",(A))
1601 @d wterm_cr    fprintf(mp->term_out,"\n")
1602 @d wlog(A)     fprintf(mp->log_file,"%s",(A))
1603 @d wlog_chr(A) fprintf(mp->log_file,"%c",(A))
1604 @d wlog_ln(A)  fprintf(mp->log_file,"\n%s",(A))
1605 @d wlog_cr     fprintf(mp->log_file, "\n")
1606 @d wps(A)      fprintf(mp->ps_file,"%s",(A))
1607 @d wps_chr(A)  fprintf(mp->ps_file,"%c",(A))
1608 @d wps_ln(A)   fprintf(mp->ps_file,,"\n%s",(A))
1609 @d wps_cr      fprintf(mp->ps_file,"\n")
1610
1611 @ To end a line of text output, we call |print_ln|.  Cases |0..max_write_files|
1612 use an array |wr_file| that will be declared later.
1613
1614 @d mp_print_text(A) mp_print_str(mp,text((A)))
1615
1616 @<Internal ...@>=
1617 void mp_print_ln (MP mp);
1618 void mp_print_visible_char (MP mp, ASCII_code s); 
1619 void mp_print_char (MP mp, ASCII_code k);
1620 void mp_print (MP mp, char *s);
1621 void mp_print_str (MP mp, str_number s);
1622 void mp_print_nl (MP mp, char *s);
1623 void mp_print_two (MP mp,scaled x, scaled y) ;
1624 void mp_print_scaled (MP mp,scaled s);
1625
1626 @ @<Basic print...@>=
1627 void mp_print_ln (MP mp) { /* prints an end-of-line */
1628  switch (mp->selector) {
1629   case term_and_log: 
1630     wterm_cr; wlog_cr;
1631     mp->term_offset=0;  mp->file_offset=0;
1632     break;
1633   case log_only: 
1634     wlog_cr; mp->file_offset=0;
1635     break;
1636   case term_only: 
1637     wterm_cr; mp->term_offset=0;
1638     break;
1639   case ps_file_only: 
1640     wps_cr; mp->ps_offset=0;
1641     break;
1642   case no_print:
1643   case pseudo: 
1644   case new_string: 
1645     break;
1646   default: 
1647     fprintf(mp->wr_file[(mp->selector-write_file)],"\n");
1648   }
1649 } /* note that |tally| is not affected */
1650
1651 @ The |print_visible_char| procedure sends one character to the desired
1652 destination, using the |xchr| array to map it into an external character
1653 compatible with |input_ln|.  (It assumes that it is always called with
1654 a visible ASCII character.)  All printing comes through |print_ln| or
1655 |print_char|, which ultimately calls |print_visible_char|, hence these
1656 routines are the ones that limit lines to at most |max_print_line| characters.
1657 But we must make an exception for the \ps\ output file since it is not safe
1658 to cut up lines arbitrarily in \ps.
1659
1660 Procedure |unit_str_room| needs to be declared |forward| here because it calls
1661 |do_compaction| and |do_compaction| can call the error routines.  Actually,
1662 |unit_str_room| avoids |overflow| errors but it can call |confusion|.
1663
1664 @<Basic printing...@>=
1665 void mp_print_visible_char (MP mp, ASCII_code s) { /* prints a single character */
1666   switch (mp->selector) {
1667   case term_and_log: 
1668     wterm_chr(xchr(s)); wlog_chr(xchr(s));
1669     incr(mp->term_offset); incr(mp->file_offset);
1670     if ( mp->term_offset==(unsigned)mp->max_print_line ) { 
1671        wterm_cr; mp->term_offset=0;
1672     };
1673     if ( mp->file_offset==(unsigned)mp->max_print_line ) { 
1674        wlog_cr; mp->file_offset=0;
1675     };
1676     break;
1677   case log_only: 
1678     wlog_chr(xchr(s)); incr(mp->file_offset);
1679     if ( mp->file_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1680     break;
1681   case term_only: 
1682     wterm_chr(xchr(s)); incr(mp->term_offset);
1683     if ( mp->term_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1684     break;
1685   case ps_file_only: 
1686     if ( s==13 ) {
1687       wps_cr; mp->ps_offset=0;
1688     } else {
1689       wps_chr(xchr(s)); incr(mp->ps_offset);
1690     };
1691     break;
1692   case no_print: 
1693     break;
1694   case pseudo: 
1695     if ( mp->tally<mp->trick_count ) 
1696       mp->trick_buf[mp->tally % mp->error_line]=s;
1697     break;
1698   case new_string: 
1699     if ( mp->pool_ptr>=mp->max_pool_ptr ) { 
1700       mp_unit_str_room(mp);
1701       if ( mp->pool_ptr>=mp->pool_size ) 
1702         goto DONE; /* drop characters if string space is full */
1703     };
1704     append_char(s);
1705     break;
1706   default:
1707     fprintf(mp->wr_file[(mp->selector-write_file)],"%c",xchr(s));
1708   }
1709 DONE:
1710   incr(mp->tally);
1711 }
1712
1713 @ The |print_char| procedure sends one character to the desired destination.
1714 File names and string expressions might contain |ASCII_code| values that
1715 can't be printed using |print_visible_char|.  These characters will be
1716 printed in three- or four-symbol form like `\.{\^\^A}' or `\.{\^\^e4}'.
1717 (This procedure assumes that it is safe to bypass all checks for unprintable
1718 characters when |selector| is in the range |0..max_write_files-1| or when
1719 |selector=ps_file_only|.  In the former case the user might want to write
1720 unprintable characters, and in the latter case the \ps\ printing routines
1721 check their arguments themselves before calling |print_char| or |print|.)
1722
1723 @d print_lc_hex(A) do { l=(A);
1724     mp_print_visible_char(mp, (l<10 ? l+'0' : l-10+'a'));
1725   } while (0)
1726
1727 @<Basic printing...@>=
1728 void mp_print_char (MP mp, ASCII_code k) { /* prints a single character */
1729   int l; /* small index or counter */
1730   if ( mp->selector<pseudo || mp->selector>=write_file) {
1731     mp_print_visible_char(mp, k);
1732   } else if ( @<Character |k| cannot be printed@> ) { 
1733     mp_print(mp, "^^"); 
1734     if ( k<0100 ) { 
1735       mp_print_visible_char(mp, k+0100); 
1736     } else if ( k<0200 ) { 
1737       mp_print_visible_char(mp, k-0100); 
1738     } else { 
1739       print_lc_hex(k / 16);  
1740       print_lc_hex(k % 16); 
1741     }
1742   } else {
1743     mp_print_visible_char(mp, k);
1744   }
1745 };
1746
1747 @ An entire string is output by calling |print|. Note that if we are outputting
1748 the single standard ASCII character \.c, we could call |print("c")|, since
1749 |"c"=99| is the number of a single-character string, as explained above. But
1750 |print_char("c")| is quicker, so \MP\ goes directly to the |print_char|
1751 routine when it knows that this is safe. (The present implementation
1752 assumes that it is always safe to print a visible ASCII character.)
1753 @^system dependencies@>
1754
1755 @<Basic print...@>=
1756 void mp_do_print (MP mp, char *ss, unsigned int len) { /* prints string |s| */
1757   unsigned int j = 0;
1758   while ( j<len ){ 
1759     mp_print_char(mp, ss[j]); incr(j);
1760   }
1761 }
1762
1763
1764 @<Basic print...@>=
1765 void mp_print (MP mp, char *ss) {
1766   mp_do_print(mp, ss, strlen(ss));
1767 }
1768 void mp_print_str (MP mp, str_number s) {
1769   pool_pointer j; /* current character code position */
1770   if ( (s<0)||(s>mp->max_str_ptr) ) {
1771      mp_do_print(mp,"???",3); /* this can't happen */
1772 @.???@>
1773   }
1774   j=mp->str_start[s];
1775   mp_do_print(mp, (char *)(mp->str_pool+j), (str_stop(s)-j));
1776 }
1777
1778
1779 @ Here is the very first thing that \MP\ prints: a headline that identifies
1780 the version number and base name. The |term_offset| variable is temporarily
1781 incorrect, but the discrepancy is not serious since we assume that the banner
1782 and mem identifier together will occupy at most |max_print_line|
1783 character positions.
1784
1785 @<Initialize the output...@>=
1786 wterm (banner);
1787 wterm (version_string);
1788 if (mp->mem_ident!=NULL) 
1789   mp_print(mp,mp->mem_ident); 
1790 mp_print_ln(mp);
1791 update_terminal;
1792
1793 @ The procedure |print_nl| is like |print|, but it makes sure that the
1794 string appears at the beginning of a new line.
1795
1796 @<Basic print...@>=
1797 void mp_print_nl (MP mp, char *s) { /* prints string |s| at beginning of line */
1798   switch(mp->selector) {
1799   case term_and_log: 
1800     if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_ln(mp);
1801     break;
1802   case log_only: 
1803     if ( mp->file_offset>0 ) mp_print_ln(mp);
1804     break;
1805   case term_only: 
1806     if ( mp->term_offset>0 ) mp_print_ln(mp);
1807     break;
1808   case ps_file_only: 
1809     if ( mp->ps_offset>0 ) mp_print_ln(mp);
1810     break;
1811   case no_print:
1812   case pseudo:
1813   case new_string: 
1814         break;
1815   } /* there are no other cases */
1816   mp_print(mp, s);
1817 }
1818
1819 @ An array of digits in the range |0..9| is printed by |print_the_digs|.
1820
1821 @<Basic print...@>=
1822 void mp_print_the_digs (MP mp, eight_bits k) {
1823   /* prints |dig[k-1]|$\,\ldots\,$|dig[0]| */
1824   while ( k>0 ){ 
1825     decr(k); mp_print_char(mp, '0'+mp->dig[k]);
1826   }
1827 };
1828
1829 @ The following procedure, which prints out the decimal representation of a
1830 given integer |n|, has been written carefully so that it works properly
1831 if |n=0| or if |(-n)| would cause overflow. It does not apply |mod| or |div|
1832 to negative arguments, since such operations are not implemented consistently
1833 by all \PASCAL\ compilers.
1834
1835 @<Basic print...@>=
1836 void mp_print_int (MP mp,integer n) { /* prints an integer in decimal form */
1837   integer m; /* used to negate |n| in possibly dangerous cases */
1838   int k = 0; /* index to current digit; we assume that $|n|<10^{23}$ */
1839   if ( n<0 ) { 
1840     mp_print_char(mp, '-');
1841     if ( n>-100000000 ) {
1842           negate(n);
1843     } else  { 
1844           m=-1-n; n=m / 10; m=(m % 10)+1; k=1;
1845       if ( m<10 ) {
1846         mp->dig[0]=m;
1847       } else { 
1848         mp->dig[0]=0; incr(n);
1849       }
1850     }
1851   }
1852   do {  
1853     mp->dig[k]=n % 10; n=n / 10; incr(k);
1854   } while (n!=0);
1855   mp_print_the_digs(mp, k);
1856 };
1857
1858 @ @<Internal ...@>=
1859 void mp_print_int (MP mp,integer n);
1860
1861 @ \MP\ also makes use of a trivial procedure to print two digits. The
1862 following subroutine is usually called with a parameter in the range |0<=n<=99|.
1863
1864 @c 
1865 void mp_print_dd (MP mp,integer n) { /* prints two least significant digits */
1866   n=abs(n) % 100; 
1867   mp_print_char(mp, '0'+(n / 10));
1868   mp_print_char(mp, '0'+(n % 10));
1869 }
1870
1871
1872 @ @<Internal ...@>=
1873 void mp_print_dd (MP mp,integer n);
1874
1875 @ Here is a procedure that asks the user to type a line of input,
1876 assuming that the |selector| setting is either |term_only| or |term_and_log|.
1877 The input is placed into locations |first| through |last-1| of the
1878 |buffer| array, and echoed on the transcript file if appropriate.
1879
1880 This procedure is never called when |interaction<mp_scroll_mode|.
1881
1882 @d prompt_input(A) do { 
1883     wake_up_terminal; mp_print(mp, (A)); mp_term_input(mp);
1884   } while (0) /* prints a string and gets a line of input */
1885
1886 @c 
1887 void mp_term_input (MP mp) { /* gets a line from the terminal */
1888   size_t k; /* index into |buffer| */
1889   update_terminal; /* Now the user sees the prompt for sure */
1890   if (!mp_input_ln(mp, mp->term_in,true)) 
1891     mp_fatal_error(mp, "End of file on the terminal!");
1892 @.End of file on the terminal@>
1893   mp->term_offset=0; /* the user's line ended with \<\rm return> */
1894   decr(mp->selector); /* prepare to echo the input */
1895   if ( mp->last!=mp->first ) {
1896     for (k=mp->first;k<=mp->last-1;k++) {
1897       mp_print_char(mp, mp->buffer[k]);
1898     }
1899   }
1900   mp_print_ln(mp); 
1901   mp->buffer[mp->last]='%'; 
1902   incr(mp->selector); /* restore previous status */
1903 };
1904
1905 @* \[6] Reporting errors.
1906 When something anomalous is detected, \MP\ typically does something like this:
1907 $$\vbox{\halign{#\hfil\cr
1908 |print_err("Something anomalous has been detected");|\cr
1909 |help3("This is the first line of my offer to help.")|\cr
1910 |("This is the second line. I'm trying to")|\cr
1911 |("explain the best way for you to proceed.");|\cr
1912 |error;|\cr}}$$
1913 A two-line help message would be given using |help2|, etc.; these informal
1914 helps should use simple vocabulary that complements the words used in the
1915 official error message that was printed. (Outside the U.S.A., the help
1916 messages should preferably be translated into the local vernacular. Each
1917 line of help is at most 60 characters long, in the present implementation,
1918 so that |max_print_line| will not be exceeded.)
1919
1920 The |print_err| procedure supplies a `\.!' before the official message,
1921 and makes sure that the terminal is awake if a stop is going to occur.
1922 The |error| procedure supplies a `\..' after the official message, then it
1923 shows the location of the error; and if |interaction=error_stop_mode|,
1924 it also enters into a dialog with the user, during which time the help
1925 message may be printed.
1926 @^system dependencies@>
1927
1928 @ The global variable |interaction| has four settings, representing increasing
1929 amounts of user interaction:
1930
1931 @<Exported types@>=
1932 enum mp_interaction_mode { 
1933  mp_unspecified_mode=0, /* extra value for command-line switch */
1934  mp_batch_mode, /* omits all stops and omits terminal output */
1935  mp_nonstop_mode, /* omits all stops */
1936  mp_scroll_mode, /* omits error stops */
1937  mp_error_stop_mode, /* stops at every opportunity to interact */
1938 };
1939
1940 @ @<Glob...@>=
1941 int interaction; /* current level of interaction */
1942
1943 @ @<Option variables@>=
1944 int interaction; /* current level of interaction */
1945
1946 @ Set it here so it can be overwritten by the commandline
1947
1948 @<Allocate or initialize ...@>=
1949 mp->interaction=opt->interaction;
1950 if (mp->interaction==mp_unspecified_mode || mp->interaction>mp_error_stop_mode) 
1951   mp->interaction=mp_error_stop_mode;
1952 if (mp->interaction<mp_unspecified_mode) 
1953   mp->interaction=mp_batch_mode;
1954
1955
1956
1957 @d print_err(A) mp_print_err(mp,(A))
1958
1959 @<Internal ...@>=
1960 void mp_print_err(MP mp, char * A);
1961
1962 @ @c
1963 void mp_print_err(MP mp, char * A) { 
1964   if ( mp->interaction==mp_error_stop_mode ) 
1965     wake_up_terminal;
1966   mp_print_nl(mp, "! "); 
1967   mp_print(mp, A);
1968 @.!\relax@>
1969 }
1970
1971
1972 @ \MP\ is careful not to call |error| when the print |selector| setting
1973 might be unusual. The only possible values of |selector| at the time of
1974 error messages are
1975
1976 \yskip\hang|no_print| (when |interaction=mp_batch_mode|
1977   and |log_file| not yet open);
1978
1979 \hang|term_only| (when |interaction>mp_batch_mode| and |log_file| not yet open);
1980
1981 \hang|log_only| (when |interaction=mp_batch_mode| and |log_file| is open);
1982
1983 \hang|term_and_log| (when |interaction>mp_batch_mode| and |log_file| is open).
1984
1985 @<Initialize the print |selector| based on |interaction|@>=
1986 if ( mp->interaction==mp_batch_mode ) mp->selector=no_print; else mp->selector=term_only
1987
1988 @ A global variable |deletions_allowed| is set |false| if the |get_next|
1989 routine is active when |error| is called; this ensures that |get_next|
1990 will never be called recursively.
1991 @^recursion@>
1992
1993 The global variable |history| records the worst level of error that
1994 has been detected. It has four possible values: |spotless|, |warning_issued|,
1995 |error_message_issued|, and |fatal_error_stop|.
1996
1997 Another global variable, |error_count|, is increased by one when an
1998 |error| occurs without an interactive dialog, and it is reset to zero at
1999 the end of every statement.  If |error_count| reaches 100, \MP\ decides
2000 that there is no point in continuing further.
2001
2002 @<Types...@>=
2003 enum mp_history_states {
2004   mp_spotless=0, /* |history| value when nothing has been amiss yet */
2005   mp_warning_issued, /* |history| value when |begin_diagnostic| has been called */
2006   mp_error_message_issued, /* |history| value when |error| has been called */
2007   mp_fatal_error_stop, /* |history| value when termination was premature */
2008 };
2009
2010 @ @<Glob...@>=
2011 boolean deletions_allowed; /* is it safe for |error| to call |get_next|? */
2012 int history; /* has the source input been clean so far? */
2013 int error_count; /* the number of scrolled errors since the last statement ended */
2014
2015 @ The value of |history| is initially |fatal_error_stop|, but it will
2016 be changed to |spotless| if \MP\ survives the initialization process.
2017
2018 @<Allocate or ...@>=
2019 mp->deletions_allowed=true; mp->error_count=0; /* |history| is initialized elsewhere */
2020
2021 @ Since errors can be detected almost anywhere in \MP, we want to declare the
2022 error procedures near the beginning of the program. But the error procedures
2023 in turn use some other procedures, which need to be declared |forward|
2024 before we get to |error| itself.
2025
2026 It is possible for |error| to be called recursively if some error arises
2027 when |get_next| is being used to delete a token, and/or if some fatal error
2028 occurs while \MP\ is trying to fix a non-fatal one. But such recursion
2029 @^recursion@>
2030 is never more than two levels deep.
2031
2032 @<Declarations@>=
2033 void mp_get_next (MP mp);
2034 void mp_term_input (MP mp);
2035 void mp_show_context (MP mp);
2036 void mp_begin_file_reading (MP mp);
2037 void mp_open_log_file (MP mp);
2038 void mp_clear_for_error_prompt (MP mp);
2039 void mp_debug_help (MP mp);
2040 @<Declare the procedure called |flush_string|@>
2041
2042 @ @<Internal ...@>=
2043 void mp_normalize_selector (MP mp);
2044
2045 @ Individual lines of help are recorded in the array |help_line|, which
2046 contains entries in positions |0..(help_ptr-1)|. They should be printed
2047 in reverse order, i.e., with |help_line[0]| appearing last.
2048
2049 @d hlp1(A) mp->help_line[0]=(A); }
2050 @d hlp2(A) mp->help_line[1]=(A); hlp1
2051 @d hlp3(A) mp->help_line[2]=(A); hlp2
2052 @d hlp4(A) mp->help_line[3]=(A); hlp3
2053 @d hlp5(A) mp->help_line[4]=(A); hlp4
2054 @d hlp6(A) mp->help_line[5]=(A); hlp5
2055 @d help0 mp->help_ptr=0 /* sometimes there might be no help */
2056 @d help1  { mp->help_ptr=1; hlp1 /* use this with one help line */
2057 @d help2  { mp->help_ptr=2; hlp2 /* use this with two help lines */
2058 @d help3  { mp->help_ptr=3; hlp3 /* use this with three help lines */
2059 @d help4  { mp->help_ptr=4; hlp4 /* use this with four help lines */
2060 @d help5  { mp->help_ptr=5; hlp5 /* use this with five help lines */
2061 @d help6  { mp->help_ptr=6; hlp6 /* use this with six help lines */
2062
2063 @<Glob...@>=
2064 char * help_line[6]; /* helps for the next |error| */
2065 unsigned int help_ptr; /* the number of help lines present */
2066 boolean use_err_help; /* should the |err_help| string be shown? */
2067 str_number err_help; /* a string set up by \&{errhelp} */
2068 str_number filename_template; /* a string set up by \&{filenametemplate} */
2069
2070 @ @<Allocate or ...@>=
2071 mp->help_ptr=0; mp->use_err_help=false; mp->err_help=0; mp->filename_template=0;
2072
2073 @ The |jump_out| procedure just cuts across all active procedure levels and
2074 goes to |end_of_MP|. This is the only nonlocal |goto| statement in the
2075 whole program. It is used when there is no recovery from a particular error.
2076
2077 The program uses a |jump_buf| to handle this, this is initialized at three
2078 spots: the start of |mp_new|, the start of |mp_initialize|, and the start 
2079 of |mp_run|. Those are the only library enty points.
2080
2081 @^system dependencies@>
2082
2083 @<Glob...@>=
2084 jmp_buf jump_buf;
2085
2086 @ @<Install and test the non-local jump buffer@>=
2087 if (setjmp(mp->jump_buf) != 0) return mp->history;
2088
2089 @ @<Setup the non-local jump buffer in |mp_new|@>=
2090 if (setjmp(mp->jump_buf) != 0) return NULL;
2091
2092 @ If |mp->internal| is zero, then a crash occured during initialization,
2093 and it is not safe to run |mp_close_files_and_terminate|.
2094
2095 @<Error hand...@>=
2096 void mp_jump_out (MP mp) { 
2097   if(mp->internal!=NULL)
2098     mp_close_files_and_terminate(mp);
2099   longjmp(mp->jump_buf,1);
2100 }
2101
2102 @ Here now is the general |error| routine.
2103
2104 @<Error hand...@>=
2105 void mp_error (MP mp) { /* completes the job of error reporting */
2106   ASCII_code c; /* what the user types */
2107   integer s1,s2,s3; /* used to save global variables when deleting tokens */
2108   pool_pointer j; /* character position being printed */
2109   if ( mp->history<mp_error_message_issued ) mp->history=mp_error_message_issued;
2110   mp_print_char(mp, '.'); mp_show_context(mp);
2111   if ( mp->interaction==mp_error_stop_mode ) {
2112     @<Get user's advice and |return|@>;
2113   }
2114   incr(mp->error_count);
2115   if ( mp->error_count==100 ) { 
2116     mp_print_nl(mp,"(That makes 100 errors; please try again.)");
2117 @.That makes 100 errors...@>
2118     mp->history=mp_fatal_error_stop; mp_jump_out(mp);
2119   }
2120   @<Put help message on the transcript file@>;
2121 }
2122 void mp_warn (MP mp, char *msg) {
2123   int saved_selector = mp->selector;
2124   mp_normalize_selector(mp);
2125   mp_print_nl(mp,"Warning: ");
2126   mp_print(mp,msg);
2127   mp->selector = saved_selector;
2128 }
2129
2130 @ @<Exported function ...@>=
2131 void mp_error (MP mp);
2132 void mp_warn (MP mp, char *msg);
2133
2134
2135 @ @<Get user's advice...@>=
2136 while (1) { 
2137 CONTINUE:
2138   mp_clear_for_error_prompt(mp); prompt_input("? ");
2139 @.?\relax@>
2140   if ( mp->last==mp->first ) return;
2141   c=mp->buffer[mp->first];
2142   if ( c>='a' ) c=c+'A'-'a'; /* convert to uppercase */
2143   @<Interpret code |c| and |return| if done@>;
2144 }
2145
2146 @ It is desirable to provide an `\.E' option here that gives the user
2147 an easy way to return from \MP\ to the system editor, with the offending
2148 line ready to be edited. But such an extension requires some system
2149 wizardry, so the present implementation simply types out the name of the
2150 file that should be
2151 edited and the relevant line number.
2152 @^system dependencies@>
2153
2154 @<Exported types@>=
2155 typedef void (*mp_run_editor_command)(MP, char *, int);
2156
2157 @ @<Glob...@>=
2158 mp_run_editor_command run_editor;
2159
2160 @ @<Option variables@>=
2161 mp_run_editor_command run_editor;
2162
2163 @ @<Allocate or initialize ...@>=
2164 set_callback_option(run_editor);
2165
2166 @ @<Declarations@>=
2167 void mp_run_editor (MP mp, char *fname, int fline);
2168
2169 @ @c void mp_run_editor (MP mp, char *fname, int fline) {
2170     mp_print_nl(mp, "You want to edit file ");
2171 @.You want to edit file x@>
2172     mp_print(mp, fname);
2173     mp_print(mp, " at line "); 
2174     mp_print_int(mp, fline);
2175     mp->interaction=mp_scroll_mode; 
2176     mp_jump_out(mp);
2177 }
2178
2179
2180 There is a secret `\.D' option available when the debugging routines haven't
2181 been commented~out.
2182 @^debugging@>
2183
2184 @<Interpret code |c| and |return| if done@>=
2185 switch (c) {
2186 case '0': case '1': case '2': case '3': case '4':
2187 case '5': case '6': case '7': case '8': case '9': 
2188   if ( mp->deletions_allowed ) {
2189     @<Delete |c-"0"| tokens and |continue|@>;
2190   }
2191   break;
2192 #ifdef DEBUG
2193 case 'D': 
2194   mp_debug_help(mp); continue; 
2195   break;
2196 #endif
2197 case 'E': 
2198   if ( mp->file_ptr>0 ){ 
2199     (mp->run_editor)(mp, 
2200                      str(mp->input_stack[mp->file_ptr].name_field), 
2201                      mp_true_line(mp));
2202   }
2203   break;
2204 case 'H': 
2205   @<Print the help information and |continue|@>;
2206   break;
2207 case 'I':
2208   @<Introduce new material from the terminal and |return|@>;
2209   break;
2210 case 'Q': case 'R': case 'S':
2211   @<Change the interaction level and |return|@>;
2212   break;
2213 case 'X':
2214   mp->interaction=mp_scroll_mode; mp_jump_out(mp);
2215   break;
2216 default:
2217   break;
2218 }
2219 @<Print the menu of available options@>
2220
2221 @ @<Print the menu...@>=
2222
2223   mp_print(mp, "Type <return> to proceed, S to scroll future error messages,");
2224 @.Type <return> to proceed...@>
2225   mp_print_nl(mp, "R to run without stopping, Q to run quietly,");
2226   mp_print_nl(mp, "I to insert something, ");
2227   if ( mp->file_ptr>0 ) 
2228     mp_print(mp, "E to edit your file,");
2229   if ( mp->deletions_allowed )
2230     mp_print_nl(mp, "1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
2231   mp_print_nl(mp, "H for help, X to quit.");
2232 }
2233
2234 @ Here the author of \MP\ apologizes for making use of the numerical
2235 relation between |"Q"|, |"R"|, |"S"|, and the desired interaction settings
2236 |mp_batch_mode|, |mp_nonstop_mode|, |mp_scroll_mode|.
2237 @^Knuth, Donald Ervin@>
2238
2239 @<Change the interaction...@>=
2240
2241   mp->error_count=0; mp->interaction=mp_batch_mode+c-'Q';
2242   mp_print(mp, "OK, entering ");
2243   switch (c) {
2244   case 'Q': mp_print(mp, "batchmode"); decr(mp->selector); break;
2245   case 'R': mp_print(mp, "nonstopmode"); break;
2246   case 'S': mp_print(mp, "scrollmode"); break;
2247   } /* there are no other cases */
2248   mp_print(mp, "..."); mp_print_ln(mp); update_terminal; return;
2249 }
2250
2251 @ When the following code is executed, |buffer[(first+1)..(last-1)]| may
2252 contain the material inserted by the user; otherwise another prompt will
2253 be given. In order to understand this part of the program fully, you need
2254 to be familiar with \MP's input stacks.
2255
2256 @<Introduce new material...@>=
2257
2258   mp_begin_file_reading(mp); /* enter a new syntactic level for terminal input */
2259   if ( mp->last>mp->first+1 ) { 
2260     loc=mp->first+1; mp->buffer[mp->first]=' ';
2261   } else { 
2262    prompt_input("insert>"); loc=mp->first;
2263 @.insert>@>
2264   };
2265   mp->first=mp->last+1; mp->cur_input.limit_field=mp->last; return;
2266 }
2267
2268 @ We allow deletion of up to 99 tokens at a time.
2269
2270 @<Delete |c-"0"| tokens...@>=
2271
2272   s1=mp->cur_cmd; s2=mp->cur_mod; s3=mp->cur_sym; mp->OK_to_interrupt=false;
2273   if ( (mp->last>mp->first+1) && (mp->buffer[mp->first+1]>='0')&&(mp->buffer[mp->first+1]<='9') )
2274     c=c*10+mp->buffer[mp->first+1]-'0'*11;
2275   else 
2276     c=c-'0';
2277   while ( c>0 ) { 
2278     mp_get_next(mp); /* one-level recursive call of |error| is possible */
2279     @<Decrease the string reference count, if the current token is a string@>;
2280     decr(c);
2281   };
2282   mp->cur_cmd=s1; mp->cur_mod=s2; mp->cur_sym=s3; mp->OK_to_interrupt=true;
2283   help2("I have just deleted some text, as you asked.")
2284        ("You can now delete more, or insert, or whatever.");
2285   mp_show_context(mp); 
2286   goto CONTINUE;
2287 }
2288
2289 @ @<Print the help info...@>=
2290
2291   if ( mp->use_err_help ) { 
2292     @<Print the string |err_help|, possibly on several lines@>;
2293     mp->use_err_help=false;
2294   } else { 
2295     if ( mp->help_ptr==0 ) {
2296       help2("Sorry, I don't know how to help in this situation.")
2297            ("Maybe you should try asking a human?");
2298      }
2299     do { 
2300       decr(mp->help_ptr); mp_print(mp, mp->help_line[mp->help_ptr]); mp_print_ln(mp);
2301     } while (mp->help_ptr!=0);
2302   };
2303   help4("Sorry, I already gave what help I could...")
2304        ("Maybe you should try asking a human?")
2305        ("An error might have occurred before I noticed any problems.")
2306        ("``If all else fails, read the instructions.''");
2307   goto CONTINUE;
2308 }
2309
2310 @ @<Print the string |err_help|, possibly on several lines@>=
2311 j=mp->str_start[mp->err_help];
2312 while ( j<str_stop(mp->err_help) ) { 
2313   if ( mp->str_pool[j]!='%' ) mp_print_str(mp, mp->str_pool[j]);
2314   else if ( j+1==str_stop(mp->err_help) ) mp_print_ln(mp);
2315   else if ( mp->str_pool[j+1]!='%' ) mp_print_ln(mp);
2316   else  { incr(j); mp_print_char(mp, '%'); };
2317   incr(j);
2318 }
2319
2320 @ @<Put help message on the transcript file@>=
2321 if ( mp->interaction>mp_batch_mode ) decr(mp->selector); /* avoid terminal output */
2322 if ( mp->use_err_help ) { 
2323   mp_print_nl(mp, "");
2324   @<Print the string |err_help|, possibly on several lines@>;
2325 } else { 
2326   while ( mp->help_ptr>0 ){ 
2327     decr(mp->help_ptr); mp_print_nl(mp, mp->help_line[mp->help_ptr]);
2328   };
2329 }
2330 mp_print_ln(mp);
2331 if ( mp->interaction>mp_batch_mode ) incr(mp->selector); /* re-enable terminal output */
2332 mp_print_ln(mp)
2333
2334 @ In anomalous cases, the print selector might be in an unknown state;
2335 the following subroutine is called to fix things just enough to keep
2336 running a bit longer.
2337
2338 @c 
2339 void mp_normalize_selector (MP mp) { 
2340   if ( mp->log_opened ) mp->selector=term_and_log;
2341   else mp->selector=term_only;
2342   if ( mp->job_name==NULL ) mp_open_log_file(mp);
2343   if ( mp->interaction==mp_batch_mode ) decr(mp->selector);
2344 }
2345
2346 @ The following procedure prints \MP's last words before dying.
2347
2348 @d succumb { if ( mp->interaction==mp_error_stop_mode )
2349     mp->interaction=mp_scroll_mode; /* no more interaction */
2350   if ( mp->log_opened ) mp_error(mp);
2351   /* if ( mp->interaction>mp_batch_mode ) mp_debug_help(mp); */
2352   mp->history=mp_fatal_error_stop; mp_jump_out(mp); /* irrecoverable error */
2353   }
2354
2355 @<Error hand...@>=
2356 void mp_fatal_error (MP mp, char *s) { /* prints |s|, and that's it */
2357   mp_normalize_selector(mp);
2358   print_err("Emergency stop"); help1(s); succumb;
2359 @.Emergency stop@>
2360 }
2361
2362 @ @<Exported function ...@>=
2363 void mp_fatal_error (MP mp, char *s);
2364
2365
2366 @ Here is the most dreaded error message.
2367
2368 @<Error hand...@>=
2369 void mp_overflow (MP mp, char *s, integer n) { /* stop due to finiteness */
2370   mp_normalize_selector(mp);
2371   print_err("MetaPost capacity exceeded, sorry [");
2372 @.MetaPost capacity exceeded ...@>
2373   mp_print(mp, s); mp_print_char(mp, '='); mp_print_int(mp, n); mp_print_char(mp, ']');
2374   help2("If you really absolutely need more capacity,")
2375        ("you can ask a wizard to enlarge me.");
2376   succumb;
2377 }
2378
2379 @ @<Declarations@>=
2380 void mp_overflow (MP mp, char *s, integer n);
2381
2382 @ The program might sometime run completely amok, at which point there is
2383 no choice but to stop. If no previous error has been detected, that's bad
2384 news; a message is printed that is really intended for the \MP\
2385 maintenance person instead of the user (unless the user has been
2386 particularly diabolical).  The index entries for `this can't happen' may
2387 help to pinpoint the problem.
2388 @^dry rot@>
2389
2390 @<Internal library ...@>=
2391 void mp_confusion (MP mp,char *s);
2392
2393 @ @<Error hand...@>=
2394 void mp_confusion (MP mp,char *s) {
2395   /* consistency check violated; |s| tells where */
2396   mp_normalize_selector(mp);
2397   if ( mp->history<mp_error_message_issued ) { 
2398     print_err("This can't happen ("); mp_print(mp, s); mp_print_char(mp, ')');
2399 @.This can't happen@>
2400     help1("I'm broken. Please show this to someone who can fix can fix");
2401   } else { 
2402     print_err("I can\'t go on meeting you like this");
2403 @.I can't go on...@>
2404     help2("One of your faux pas seems to have wounded me deeply...")
2405          ("in fact, I'm barely conscious. Please fix it and try again.");
2406   }
2407   succumb;
2408 }
2409
2410 @ Users occasionally want to interrupt \MP\ while it's running.
2411 If the \PASCAL\ runtime system allows this, one can implement
2412 a routine that sets the global variable |interrupt| to some nonzero value
2413 when such an interrupt is signaled. Otherwise there is probably at least
2414 a way to make |interrupt| nonzero using the \PASCAL\ debugger.
2415 @^system dependencies@>
2416 @^debugging@>
2417
2418 @d check_interrupt { if ( mp->interrupt!=0 )
2419    mp_pause_for_instructions(mp); }
2420
2421 @<Global...@>=
2422 integer interrupt; /* should \MP\ pause for instructions? */
2423 boolean OK_to_interrupt; /* should interrupts be observed? */
2424
2425 @ @<Allocate or ...@>=
2426 mp->interrupt=0; mp->OK_to_interrupt=true;
2427
2428 @ When an interrupt has been detected, the program goes into its
2429 highest interaction level and lets the user have the full flexibility of
2430 the |error| routine.  \MP\ checks for interrupts only at times when it is
2431 safe to do this.
2432
2433 @c 
2434 void mp_pause_for_instructions (MP mp) { 
2435   if ( mp->OK_to_interrupt ) { 
2436     mp->interaction=mp_error_stop_mode;
2437     if ( (mp->selector==log_only)||(mp->selector==no_print) )
2438       incr(mp->selector);
2439     print_err("Interruption");
2440 @.Interruption@>
2441     help3("You rang?")
2442          ("Try to insert some instructions for me (e.g.,`I show x'),")
2443          ("unless you just want to quit by typing `X'.");
2444     mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
2445     mp->interrupt=0;
2446   }
2447 }
2448
2449 @ Many of \MP's error messages state that a missing token has been
2450 inserted behind the scenes. We can save string space and program space
2451 by putting this common code into a subroutine.
2452
2453 @c 
2454 void mp_missing_err (MP mp, char *s) { 
2455   print_err("Missing `"); mp_print(mp, s); mp_print(mp, "' has been inserted");
2456 @.Missing...inserted@>
2457 }
2458
2459 @* \[7] Arithmetic with scaled numbers.
2460 The principal computations performed by \MP\ are done entirely in terms of
2461 integers less than $2^{31}$ in magnitude; thus, the arithmetic specified in this
2462 program can be carried out in exactly the same way on a wide variety of
2463 computers, including some small ones.
2464 @^small computers@>
2465
2466 But \PASCAL\ does not define the |div|
2467 operation in the case of negative dividends; for example, the result of
2468 |(-2*n-1) div 2| is |-(n+1)| on some computers and |-n| on others.
2469 There are two principal types of arithmetic: ``translation-preserving,''
2470 in which the identity |(a+q*b)div b=(a div b)+q| is valid; and
2471 ``negation-preserving,'' in which |(-a)div b=-(a div b)|. This leads to
2472 two \MP s, which can produce different results, although the differences
2473 should be negligible when the language is being used properly.
2474 The \TeX\ processor has been defined carefully so that both varieties
2475 of arithmetic will produce identical output, but it would be too
2476 inefficient to constrain \MP\ in a similar way.
2477
2478 @d el_gordo   017777777777 /* $2^{31}-1$, the largest value that \MP\ likes */
2479
2480 @ One of \MP's most common operations is the calculation of
2481 $\lfloor{a+b\over2}\rfloor$,
2482 the midpoint of two given integers |a| and~|b|. The only decent way to do
2483 this in \PASCAL\ is to write `|(a+b) div 2|'; but on most machines it is
2484 far more efficient to calculate `|(a+b)| right shifted one bit'.
2485
2486 Therefore the midpoint operation will always be denoted by `|half(a+b)|'
2487 in this program. If \MP\ is being implemented with languages that permit
2488 binary shifting, the |half| macro should be changed to make this operation
2489 as efficient as possible.  Since some languages have shift operators that can
2490 only be trusted to work on positive numbers, there is also a macro |halfp|
2491 that is used only when the quantity being halved is known to be positive
2492 or zero.
2493
2494 @d half(A) ((A) / 2)
2495 @d halfp(A) ((A) / 2)
2496
2497 @ A single computation might use several subroutine calls, and it is
2498 desirable to avoid producing multiple error messages in case of arithmetic
2499 overflow. So the routines below set the global variable |arith_error| to |true|
2500 instead of reporting errors directly to the user.
2501
2502 @<Glob...@>=
2503 boolean arith_error; /* has arithmetic overflow occurred recently? */
2504
2505 @ @<Allocate or ...@>=
2506 mp->arith_error=false;
2507
2508 @ At crucial points the program will say |check_arith|, to test if
2509 an arithmetic error has been detected.
2510
2511 @d check_arith { if ( mp->arith_error ) mp_clear_arith(mp); }
2512
2513 @c 
2514 void mp_clear_arith (MP mp) { 
2515   print_err("Arithmetic overflow");
2516 @.Arithmetic overflow@>
2517   help4("Uh, oh. A little while ago one of the quantities that I was")
2518        ("computing got too large, so I'm afraid your answers will be")
2519        ("somewhat askew. You'll probably have to adopt different")
2520        ("tactics next time. But I shall try to carry on anyway.");
2521   mp_error(mp); 
2522   mp->arith_error=false;
2523 }
2524
2525 @ Addition is not always checked to make sure that it doesn't overflow,
2526 but in places where overflow isn't too unlikely the |slow_add| routine
2527 is used.
2528
2529 @c integer mp_slow_add (MP mp,integer x, integer y) { 
2530   if ( x>=0 )  {
2531     if ( y<=el_gordo-x ) { 
2532       return x+y;
2533     } else  { 
2534       mp->arith_error=true; 
2535           return el_gordo;
2536     }
2537   } else  if ( -y<=el_gordo+x ) {
2538     return x+y;
2539   } else { 
2540     mp->arith_error=true; 
2541         return -el_gordo;
2542   }
2543 }
2544
2545 @ Fixed-point arithmetic is done on {\sl scaled integers\/} that are multiples
2546 of $2^{-16}$. In other words, a binary point is assumed to be sixteen bit
2547 positions from the right end of a binary computer word.
2548
2549 @d quarter_unit   040000 /* $2^{14}$, represents 0.250000 */
2550 @d half_unit   0100000 /* $2^{15}$, represents 0.50000 */
2551 @d three_quarter_unit   0140000 /* $3\cdot2^{14}$, represents 0.75000 */
2552 @d unity   0200000 /* $2^{16}$, represents 1.00000 */
2553 @d two   0400000 /* $2^{17}$, represents 2.00000 */
2554 @d three   0600000 /* $2^{17}+2^{16}$, represents 3.00000 */
2555
2556 @<Types...@>=
2557 typedef integer scaled; /* this type is used for scaled integers */
2558 typedef unsigned char small_number; /* this type is self-explanatory */
2559
2560 @ The following function is used to create a scaled integer from a given decimal
2561 fraction $(.d_0d_1\ldots d_{k-1})$, where |0<=k<=17|. The digit $d_i$ is
2562 given in |dig[i]|, and the calculation produces a correctly rounded result.
2563
2564 @c 
2565 scaled mp_round_decimals (MP mp,small_number k) {
2566   /* converts a decimal fraction */
2567  integer a = 0; /* the accumulator */
2568  while ( k-->0 ) { 
2569     a=(a+mp->dig[k]*two) / 10;
2570   }
2571   return halfp(a+1);
2572 }
2573
2574 @ Conversely, here is a procedure analogous to |print_int|. If the output
2575 of this procedure is subsequently read by \MP\ and converted by the
2576 |round_decimals| routine above, it turns out that the original value will
2577 be reproduced exactly. A decimal point is printed only if the value is
2578 not an integer. If there is more than one way to print the result with
2579 the optimum number of digits following the decimal point, the closest
2580 possible value is given.
2581
2582 The invariant relation in the \&{repeat} loop is that a sequence of
2583 decimal digits yet to be printed will yield the original number if and only if
2584 they form a fraction~$f$ in the range $s-\delta\L10\cdot2^{16}f<s$.
2585 We can stop if and only if $f=0$ satisfies this condition; the loop will
2586 terminate before $s$ can possibly become zero.
2587
2588 @<Basic printing...@>=
2589 void mp_print_scaled (MP mp,scaled s) { /* prints scaled real, rounded to five  digits */
2590   scaled delta; /* amount of allowable inaccuracy */
2591   if ( s<0 ) { 
2592         mp_print_char(mp, '-'); 
2593     negate(s); /* print the sign, if negative */
2594   }
2595   mp_print_int(mp, s / unity); /* print the integer part */
2596   s=10*(s % unity)+5;
2597   if ( s!=5 ) { 
2598     delta=10; 
2599     mp_print_char(mp, '.');
2600     do {  
2601       if ( delta>unity )
2602         s=s+0100000-(delta / 2); /* round the final digit */
2603       mp_print_char(mp, '0'+(s / unity)); 
2604       s=10*(s % unity); 
2605       delta=delta*10;
2606     } while (s>delta);
2607   }
2608 }
2609
2610 @ We often want to print two scaled quantities in parentheses,
2611 separated by a comma.
2612
2613 @<Basic printing...@>=
2614 void mp_print_two (MP mp,scaled x, scaled y) { /* prints `|(x,y)|' */
2615   mp_print_char(mp, '('); 
2616   mp_print_scaled(mp, x); 
2617   mp_print_char(mp, ','); 
2618   mp_print_scaled(mp, y);
2619   mp_print_char(mp, ')');
2620 }
2621
2622 @ The |scaled| quantities in \MP\ programs are generally supposed to be
2623 less than $2^{12}$ in absolute value, so \MP\ does much of its internal
2624 arithmetic with 28~significant bits of precision. A |fraction| denotes
2625 a scaled integer whose binary point is assumed to be 28 bit positions
2626 from the right.
2627
2628 @d fraction_half 01000000000 /* $2^{27}$, represents 0.50000000 */
2629 @d fraction_one 02000000000 /* $2^{28}$, represents 1.00000000 */
2630 @d fraction_two 04000000000 /* $2^{29}$, represents 2.00000000 */
2631 @d fraction_three 06000000000 /* $3\cdot2^{28}$, represents 3.00000000 */
2632 @d fraction_four 010000000000 /* $2^{30}$, represents 4.00000000 */
2633
2634 @<Types...@>=
2635 typedef integer fraction; /* this type is used for scaled fractions */
2636
2637 @ In fact, the two sorts of scaling discussed above aren't quite
2638 sufficient; \MP\ has yet another, used internally to keep track of angles
2639 in units of $2^{-20}$ degrees.
2640
2641 @d forty_five_deg 0264000000 /* $45\cdot2^{20}$, represents $45^\circ$ */
2642 @d ninety_deg 0550000000 /* $90\cdot2^{20}$, represents $90^\circ$ */
2643 @d one_eighty_deg 01320000000 /* $180\cdot2^{20}$, represents $180^\circ$ */
2644 @d three_sixty_deg 02640000000 /* $360\cdot2^{20}$, represents $360^\circ$ */
2645
2646 @<Types...@>=
2647 typedef integer angle; /* this type is used for scaled angles */
2648
2649 @ The |make_fraction| routine produces the |fraction| equivalent of
2650 |p/q|, given integers |p| and~|q|; it computes the integer
2651 $f=\lfloor2^{28}p/q+{1\over2}\rfloor$, when $p$ and $q$ are
2652 positive. If |p| and |q| are both of the same scaled type |t|,
2653 the ``type relation'' |make_fraction(t,t)=fraction| is valid;
2654 and it's also possible to use the subroutine ``backwards,'' using
2655 the relation |make_fraction(t,fraction)=t| between scaled types.
2656
2657 If the result would have magnitude $2^{31}$ or more, |make_fraction|
2658 sets |arith_error:=true|. Most of \MP's internal computations have
2659 been designed to avoid this sort of error.
2660
2661 If this subroutine were programmed in assembly language on a typical
2662 machine, we could simply compute |(@t$2^{28}$@>*p)div q|, since a
2663 double-precision product can often be input to a fixed-point division
2664 instruction. But when we are restricted to \PASCAL\ arithmetic it
2665 is necessary either to resort to multiple-precision maneuvering
2666 or to use a simple but slow iteration. The multiple-precision technique
2667 would be about three times faster than the code adopted here, but it
2668 would be comparatively long and tricky, involving about sixteen
2669 additional multiplications and divisions.
2670
2671 This operation is part of \MP's ``inner loop''; indeed, it will
2672 consume nearly 10\pct! of the running time (exclusive of input and output)
2673 if the code below is left unchanged. A machine-dependent recoding
2674 will therefore make \MP\ run faster. The present implementation
2675 is highly portable, but slow; it avoids multiplication and division
2676 except in the initial stage. System wizards should be careful to
2677 replace it with a routine that is guaranteed to produce identical
2678 results in all cases.
2679 @^system dependencies@>
2680
2681 As noted below, a few more routines should also be replaced by machine-dependent
2682 code, for efficiency. But when a procedure is not part of the ``inner loop,''
2683 such changes aren't advisable; simplicity and robustness are
2684 preferable to trickery, unless the cost is too high.
2685 @^inner loop@>
2686
2687 @<Internal ...@>=
2688 fraction mp_make_fraction (MP mp,integer p, integer q);
2689 integer mp_take_scaled (MP mp,integer q, scaled f) ;
2690
2691 @ If FIXPT is not defined, we need these preprocessor values
2692
2693 @d ELGORDO  0x7fffffff
2694 @d TWEXP31  2147483648.0
2695 @d TWEXP28  268435456.0
2696 @d TWEXP16 65536.0
2697 @d TWEXP_16 (1.0/65536.0)
2698 @d TWEXP_28 (1.0/268435456.0)
2699
2700
2701 @c 
2702 fraction mp_make_fraction (MP mp,integer p, integer q) {
2703 #ifdef FIXPT
2704   integer f; /* the fraction bits, with a leading 1 bit */
2705   integer n; /* the integer part of $\vert p/q\vert$ */
2706   integer be_careful; /* disables certain compiler optimizations */
2707   boolean negative = false; /* should the result be negated? */
2708   if ( p<0 ) {
2709     negate(p); negative=true;
2710   }
2711   if ( q<=0 ) { 
2712 #ifdef DEBUG
2713     if ( q==0 ) mp_confusion(mp, '/');
2714 #endif
2715 @:this can't happen /}{\quad \./@>
2716     negate(q); negative = ! negative;
2717   };
2718   n=p / q; p=p % q;
2719   if ( n>=8 ){ 
2720     mp->arith_error=true;
2721     return ( negative ? -el_gordo : el_gordo);
2722   } else { 
2723     n=(n-1)*fraction_one;
2724     @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>;
2725     return (negative ? (-(f+n)) : (f+n));
2726   }
2727 #else /* FIXPT */
2728     register double d;
2729         register integer i;
2730 #ifdef DEBUG
2731         if (q==0) mp_confusion(mp,'/'); 
2732 #endif /* DEBUG */
2733         d = TWEXP28 * (double)p /(double)q;
2734         if ((p^q) >= 0) {
2735                 d += 0.5;
2736                 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
2737                 i = (integer) d;
2738                 if (d==i && ( ((q>0 ? -q : q)&077777)
2739                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2740         } else {
2741                 d -= 0.5;
2742                 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
2743                 i = (integer) d;
2744                 if (d==i && ( ((q>0 ? q : -q)&077777)
2745                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
2746         }
2747         return i;
2748 #endif /* FIXPT */
2749 }
2750
2751 @ The |repeat| loop here preserves the following invariant relations
2752 between |f|, |p|, and~|q|:
2753 (i)~|0<=p<q|; (ii)~$fq+p=2^k(q+p_0)$, where $k$ is an integer and
2754 $p_0$ is the original value of~$p$.
2755
2756 Notice that the computation specifies
2757 |(p-q)+p| instead of |(p+p)-q|, because the latter could overflow.
2758 Let us hope that optimizing compilers do not miss this point; a
2759 special variable |be_careful| is used to emphasize the necessary
2760 order of computation. Optimizing compilers should keep |be_careful|
2761 in a register, not store it in memory.
2762 @^inner loop@>
2763
2764 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>=
2765 {
2766   f=1;
2767   do {  
2768     be_careful=p-q; p=be_careful+p;
2769     if ( p>=0 ) { 
2770       f=f+f+1;
2771     } else  { 
2772       f+=f; p=p+q;
2773     }
2774   } while (f<fraction_one);
2775   be_careful=p-q;
2776   if ( be_careful+p>=0 ) incr(f);
2777 }
2778
2779 @ The dual of |make_fraction| is |take_fraction|, which multiplies a
2780 given integer~|q| by a fraction~|f|. When the operands are positive, it
2781 computes $p=\lfloor qf/2^{28}+{1\over2}\rfloor$, a symmetric function
2782 of |q| and~|f|.
2783
2784 This routine is even more ``inner loopy'' than |make_fraction|;
2785 the present implementation consumes almost 20\pct! of \MP's computation
2786 time during typical jobs, so a machine-language substitute is advisable.
2787 @^inner loop@> @^system dependencies@>
2788
2789 @<Declarations@>=
2790 integer mp_take_fraction (MP mp,integer q, fraction f) ;
2791
2792 @ @c 
2793 #ifdef FIXPT
2794 integer mp_take_fraction (MP mp,integer q, fraction f) {
2795   integer p; /* the fraction so far */
2796   boolean negative; /* should the result be negated? */
2797   integer n; /* additional multiple of $q$ */
2798   integer be_careful; /* disables certain compiler optimizations */
2799   @<Reduce to the case that |f>=0| and |q>0|@>;
2800   if ( f<fraction_one ) { 
2801     n=0;
2802   } else { 
2803     n=f / fraction_one; f=f % fraction_one;
2804     if ( q<=el_gordo / n ) { 
2805       n=n*q ; 
2806     } else { 
2807       mp->arith_error=true; n=el_gordo;
2808     }
2809   }
2810   f=f+fraction_one;
2811   @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>;
2812   be_careful=n-el_gordo;
2813   if ( be_careful+p>0 ){ 
2814     mp->arith_error=true; n=el_gordo-p;
2815   }
2816   if ( negative ) 
2817         return (-(n+p));
2818   else 
2819     return (n+p);
2820 #else /* FIXPT */
2821 integer mp_take_fraction (MP mp,integer p, fraction q) {
2822     register double d;
2823         register integer i;
2824         d = (double)p * (double)q * TWEXP_28;
2825         if ((p^q) >= 0) {
2826                 d += 0.5;
2827                 if (d>=TWEXP31) {
2828                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2829                                 mp->arith_error = true;
2830                         return ELGORDO;
2831                 }
2832                 i = (integer) d;
2833                 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2834         } else {
2835                 d -= 0.5;
2836                 if (d<= -TWEXP31) {
2837                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2838                                 mp->arith_error = true;
2839                         return -ELGORDO;
2840                 }
2841                 i = (integer) d;
2842                 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2843         }
2844         return i;
2845 #endif /* FIXPT */
2846 }
2847
2848 @ @<Reduce to the case that |f>=0| and |q>0|@>=
2849 if ( f>=0 ) {
2850   negative=false;
2851 } else { 
2852   negate( f); negative=true;
2853 }
2854 if ( q<0 ) { 
2855   negate(q); negative=! negative;
2856 }
2857
2858 @ The invariant relations in this case are (i)~$\lfloor(qf+p)/2^k\rfloor
2859 =\lfloor qf_0/2^{28}+{1\over2}\rfloor$, where $k$ is an integer and
2860 $f_0$ is the original value of~$f$; (ii)~$2^k\L f<2^{k+1}$.
2861 @^inner loop@>
2862
2863 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>=
2864 p=fraction_half; /* that's $2^{27}$; the invariants hold now with $k=28$ */
2865 if ( q<fraction_four ) {
2866   do {  
2867     if ( odd(f) ) p=halfp(p+q); else p=halfp(p);
2868     f=halfp(f);
2869   } while (f!=1);
2870 } else  {
2871   do {  
2872     if ( odd(f) ) p=p+halfp(q-p); else p=halfp(p);
2873     f=halfp(f);
2874   } while (f!=1);
2875 }
2876
2877
2878 @ When we want to multiply something by a |scaled| quantity, we use a scheme
2879 analogous to |take_fraction| but with a different scaling.
2880 Given positive operands, |take_scaled|
2881 computes the quantity $p=\lfloor qf/2^{16}+{1\over2}\rfloor$.
2882
2883 Once again it is a good idea to use a machine-language replacement if
2884 possible; otherwise |take_scaled| will use more than 2\pct! of the running time
2885 when the Computer Modern fonts are being generated.
2886 @^inner loop@>
2887
2888 @c 
2889 #ifdef FIXPT
2890 integer mp_take_scaled (MP mp,integer q, scaled f) {
2891   integer p; /* the fraction so far */
2892   boolean negative; /* should the result be negated? */
2893   integer n; /* additional multiple of $q$ */
2894   integer be_careful; /* disables certain compiler optimizations */
2895   @<Reduce to the case that |f>=0| and |q>0|@>;
2896   if ( f<unity ) { 
2897     n=0;
2898   } else  { 
2899     n=f / unity; f=f % unity;
2900     if ( q<=el_gordo / n ) {
2901       n=n*q;
2902     } else  { 
2903       mp->arith_error=true; n=el_gordo;
2904     }
2905   }
2906   f=f+unity;
2907   @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>;
2908   be_careful=n-el_gordo;
2909   if ( be_careful+p>0 ) { 
2910     mp->arith_error=true; n=el_gordo-p;
2911   }
2912   return ( negative ?(-(n+p)) :(n+p));
2913 #else /* FIXPT */
2914 integer mp_take_scaled (MP mp,integer p, scaled q) {
2915     register double d;
2916         register integer i;
2917         d = (double)p * (double)q * TWEXP_16;
2918         if ((p^q) >= 0) {
2919                 d += 0.5;
2920                 if (d>=TWEXP31) {
2921                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2922                                 mp->arith_error = true;
2923                         return ELGORDO;
2924                 }
2925                 i = (integer) d;
2926                 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2927         } else {
2928                 d -= 0.5;
2929                 if (d<= -TWEXP31) {
2930                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2931                                 mp->arith_error = true;
2932                         return -ELGORDO;
2933                 }
2934                 i = (integer) d;
2935                 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2936         }
2937         return i;
2938 #endif /* FIXPT */
2939 }
2940
2941 @ @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>=
2942 p=half_unit; /* that's $2^{15}$; the invariants hold now with $k=16$ */
2943 @^inner loop@>
2944 if ( q<fraction_four ) {
2945   do {  
2946     p = (odd(f) ? halfp(p+q) : halfp(p));
2947     f=halfp(f);
2948   } while (f!=1);
2949 } else {
2950   do {  
2951     p = (odd(f) ? p+halfp(q-p) : halfp(p));
2952     f=halfp(f);
2953   } while (f!=1);
2954 }
2955
2956 @ For completeness, there's also |make_scaled|, which computes a
2957 quotient as a |scaled| number instead of as a |fraction|.
2958 In other words, the result is $\lfloor2^{16}p/q+{1\over2}\rfloor$, if the
2959 operands are positive. \ (This procedure is not used especially often,
2960 so it is not part of \MP's inner loop.)
2961
2962 @<Internal library ...@>=
2963 scaled mp_make_scaled (MP mp,integer p, integer q) ;
2964
2965 @ @c 
2966 scaled mp_make_scaled (MP mp,integer p, integer q) {
2967 #ifdef FIXPT 
2968   integer f; /* the fraction bits, with a leading 1 bit */
2969   integer n; /* the integer part of $\vert p/q\vert$ */
2970   boolean negative; /* should the result be negated? */
2971   integer be_careful; /* disables certain compiler optimizations */
2972   if ( p>=0 ) negative=false;
2973   else  { negate(p); negative=true; };
2974   if ( q<=0 ) { 
2975 #ifdef DEBUG 
2976     if ( q==0 ) mp_confusion(mp, "/");
2977 @:this can't happen /}{\quad \./@>
2978 #endif
2979     negate(q); negative=! negative;
2980   }
2981   n=p / q; p=p % q;
2982   if ( n>=0100000 ) { 
2983     mp->arith_error=true;
2984     return (negative ? (-el_gordo) : el_gordo);
2985   } else  { 
2986     n=(n-1)*unity;
2987     @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>;
2988     return ( negative ? (-(f+n)) :(f+n));
2989   }
2990 #else /* FIXPT */
2991     register double d;
2992         register integer i;
2993 #ifdef DEBUG
2994         if (q==0) mp_confusion(mp,"/"); 
2995 #endif /* DEBUG */
2996         d = TWEXP16 * (double)p /(double)q;
2997         if ((p^q) >= 0) {
2998                 d += 0.5;
2999                 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
3000                 i = (integer) d;
3001                 if (d==i && ( ((q>0 ? -q : q)&077777)
3002                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
3003         } else {
3004                 d -= 0.5;
3005                 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
3006                 i = (integer) d;
3007                 if (d==i && ( ((q>0 ? q : -q)&077777)
3008                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
3009         }
3010         return i;
3011 #endif /* FIXPT */
3012 }
3013
3014 @ @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>=
3015 f=1;
3016 do {  
3017   be_careful=p-q; p=be_careful+p;
3018   if ( p>=0 ) f=f+f+1;
3019   else  { f+=f; p=p+q; };
3020 } while (f<unity);
3021 be_careful=p-q;
3022 if ( be_careful+p>=0 ) incr(f)
3023
3024 @ Here is a typical example of how the routines above can be used.
3025 It computes the function
3026 $${1\over3\tau}f(\theta,\phi)=
3027 {\tau^{-1}\bigl(2+\sqrt2\,(\sin\theta-{1\over16}\sin\phi)
3028  (\sin\phi-{1\over16}\sin\theta)(\cos\theta-\cos\phi)\bigr)\over
3029 3\,\bigl(1+{1\over2}(\sqrt5-1)\cos\theta+{1\over2}(3-\sqrt5\,)\cos\phi\bigr)},$$
3030 where $\tau$ is a |scaled| ``tension'' parameter. This is \MP's magic
3031 fudge factor for placing the first control point of a curve that starts
3032 at an angle $\theta$ and ends at an angle $\phi$ from the straight path.
3033 (Actually, if the stated quantity exceeds 4, \MP\ reduces it to~4.)
3034
3035 The trigonometric quantity to be multiplied by $\sqrt2$ is less than $\sqrt2$.
3036 (It's a sum of eight terms whose absolute values can be bounded using
3037 relations such as $\sin\theta\cos\theta\L{1\over2}$.) Thus the numerator
3038 is positive; and since the tension $\tau$ is constrained to be at least
3039 $3\over4$, the numerator is less than $16\over3$. The denominator is
3040 nonnegative and at most~6.  Hence the fixed-point calculations below
3041 are guaranteed to stay within the bounds of a 32-bit computer word.
3042
3043 The angles $\theta$ and $\phi$ are given implicitly in terms of |fraction|
3044 arguments |st|, |ct|, |sf|, and |cf|, representing $\sin\theta$, $\cos\theta$,
3045 $\sin\phi$, and $\cos\phi$, respectively.
3046
3047 @c 
3048 fraction mp_velocity (MP mp,fraction st, fraction ct, fraction sf,
3049                       fraction cf, scaled t) {
3050   integer acc,num,denom; /* registers for intermediate calculations */
3051   acc=mp_take_fraction(mp, st-(sf / 16), sf-(st / 16));
3052   acc=mp_take_fraction(mp, acc,ct-cf);
3053   num=fraction_two+mp_take_fraction(mp, acc,379625062);
3054                    /* $2^{28}\sqrt2\approx379625062.497$ */
3055   denom=fraction_three+mp_take_fraction(mp, ct,497706707)+mp_take_fraction(mp, cf,307599661);
3056                       /* $3\cdot2^{27}\cdot(\sqrt5-1)\approx497706706.78$ and
3057                          $3\cdot2^{27}\cdot(3-\sqrt5\,)\approx307599661.22$ */
3058   if ( t!=unity ) num=mp_make_scaled(mp, num,t);
3059   /* |make_scaled(fraction,scaled)=fraction| */
3060   if ( num / 4>=denom ) 
3061     return fraction_four;
3062   else 
3063     return mp_make_fraction(mp, num, denom);
3064 }
3065
3066 @ The following somewhat different subroutine tests rigorously if $ab$ is
3067 greater than, equal to, or less than~$cd$,
3068 given integers $(a,b,c,d)$. In most cases a quick decision is reached.
3069 The result is $+1$, 0, or~$-1$ in the three respective cases.
3070
3071 @d mp_ab_vs_cd(M,A,B,C,D) mp_do_ab_vs_cd(A,B,C,D)
3072
3073 @c 
3074 integer mp_do_ab_vs_cd (integer a,integer b, integer c, integer d) {
3075   integer q,r; /* temporary registers */
3076   @<Reduce to the case that |a,c>=0|, |b,d>0|@>;
3077   while (1) { 
3078     q = a / d; r = c / b;
3079     if ( q!=r )
3080       return ( q>r ? 1 : -1);
3081     q = a % d; r = c % b;
3082     if ( r==0 )
3083       return (q ? 1 : 0);
3084     if ( q==0 ) return -1;
3085     a=b; b=q; c=d; d=r;
3086   } /* now |a>d>0| and |c>b>0| */
3087 }
3088
3089 @ @<Reduce to the case that |a...@>=
3090 if ( a<0 ) { negate(a); negate(b);  };
3091 if ( c<0 ) { negate(c); negate(d);  };
3092 if ( d<=0 ) { 
3093   if ( b>=0 ) {
3094     if ( (a==0||b==0)&&(c==0||d==0) ) return 0;
3095     else return 1;
3096   }
3097   if ( d==0 )
3098     return ( a==0 ? 0 : -1);
3099   q=a; a=c; c=q; q=-b; b=-d; d=q;
3100 } else if ( b<=0 ) { 
3101   if ( b<0 ) if ( a>0 ) return -1;
3102   return (c==0 ? 0 : -1);
3103 }
3104
3105 @ We conclude this set of elementary routines with some simple rounding
3106 and truncation operations.
3107
3108 @<Internal library declarations@>=
3109 #define mp_floor_scaled(M,i) ((i)&(-65536))
3110 #define mp_round_unscaled(M,i) (((i>>15)+1)>>1)
3111 #define mp_round_fraction(M,i) (((i>>11)+1)>>1)
3112
3113
3114 @* \[8] Algebraic and transcendental functions.
3115 \MP\ computes all of the necessary special functions from scratch, without
3116 relying on |real| arithmetic or system subroutines for sines, cosines, etc.
3117
3118 @ To get the square root of a |scaled| number |x|, we want to calculate
3119 $s=\lfloor 2^8\!\sqrt x +{1\over2}\rfloor$. If $x>0$, this is the unique
3120 integer such that $2^{16}x-s\L s^2<2^{16}x+s$. The following subroutine
3121 determines $s$ by an iterative method that maintains the invariant
3122 relations $x=2^{46-2k}x_0\bmod 2^{30}$, $0<y=\lfloor 2^{16-2k}x_0\rfloor
3123 -s^2+s\L q=2s$, where $x_0$ is the initial value of $x$. The value of~$y$
3124 might, however, be zero at the start of the first iteration.
3125
3126 @<Declarations@>=
3127 scaled mp_square_rt (MP mp,scaled x) ;
3128
3129 @ @c 
3130 scaled mp_square_rt (MP mp,scaled x) {
3131   small_number k; /* iteration control counter */
3132   integer y,q; /* registers for intermediate calculations */
3133   if ( x<=0 ) { 
3134     @<Handle square root of zero or negative argument@>;
3135   } else { 
3136     k=23; q=2;
3137     while ( x<fraction_two ) { /* i.e., |while x<@t$2^{29}$@>|\unskip */
3138       decr(k); x=x+x+x+x;
3139     }
3140     if ( x<fraction_four ) y=0;
3141     else  { x=x-fraction_four; y=1; };
3142     do {  
3143       @<Decrease |k| by 1, maintaining the invariant
3144       relations between |x|, |y|, and~|q|@>;
3145     } while (k!=0);
3146     return (halfp(q));
3147   }
3148 }
3149
3150 @ @<Handle square root of zero...@>=
3151
3152   if ( x<0 ) { 
3153     print_err("Square root of ");
3154 @.Square root...replaced by 0@>
3155     mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3156     help2("Since I don't take square roots of negative numbers,")
3157          ("I'm zeroing this one. Proceed, with fingers crossed.");
3158     mp_error(mp);
3159   };
3160   return 0;
3161 }
3162
3163 @ @<Decrease |k| by 1, maintaining...@>=
3164 x+=x; y+=y;
3165 if ( x>=fraction_four ) { /* note that |fraction_four=@t$2^{30}$@>| */
3166   x=x-fraction_four; incr(y);
3167 };
3168 x+=x; y=y+y-q; q+=q;
3169 if ( x>=fraction_four ) { x=x-fraction_four; incr(y); };
3170 if ( y>q ){ y=y-q; q=q+2; }
3171 else if ( y<=0 )  { q=q-2; y=y+q;  };
3172 decr(k)
3173
3174 @ Pythagorean addition $\psqrt{a^2+b^2}$ is implemented by an elegant
3175 iterative scheme due to Cleve Moler and Donald Morrison [{\sl IBM Journal
3176 @^Moler, Cleve Barry@>
3177 @^Morrison, Donald Ross@>
3178 of Research and Development\/ \bf27} (1983), 577--581]. It modifies |a| and~|b|
3179 in such a way that their Pythagorean sum remains invariant, while the
3180 smaller argument decreases.
3181
3182 @<Internal library ...@>=
3183 integer mp_pyth_add (MP mp,integer a, integer b);
3184
3185
3186 @ @c 
3187 integer mp_pyth_add (MP mp,integer a, integer b) {
3188   fraction r; /* register used to transform |a| and |b| */
3189   boolean big; /* is the result dangerously near $2^{31}$? */
3190   a=abs(a); b=abs(b);
3191   if ( a<b ) { r=b; b=a; a=r; }; /* now |0<=b<=a| */
3192   if ( b>0 ) {
3193     if ( a<fraction_two ) {
3194       big=false;
3195     } else { 
3196       a=a / 4; b=b / 4; big=true;
3197     }; /* we reduced the precision to avoid arithmetic overflow */
3198     @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>;
3199     if ( big ) {
3200       if ( a<fraction_two ) {
3201         a=a+a+a+a;
3202       } else  { 
3203         mp->arith_error=true; a=el_gordo;
3204       };
3205     }
3206   }
3207   return a;
3208 }
3209
3210 @ The key idea here is to reflect the vector $(a,b)$ about the
3211 line through $(a,b/2)$.
3212
3213 @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>=
3214 while (1) {  
3215   r=mp_make_fraction(mp, b,a);
3216   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3217   if ( r==0 ) break;
3218   r=mp_make_fraction(mp, r,fraction_four+r);
3219   a=a+mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3220 }
3221
3222
3223 @ Here is a similar algorithm for $\psqrt{a^2-b^2}$.
3224 It converges slowly when $b$ is near $a$, but otherwise it works fine.
3225
3226 @c 
3227 integer mp_pyth_sub (MP mp,integer a, integer b) {
3228   fraction r; /* register used to transform |a| and |b| */
3229   boolean big; /* is the input dangerously near $2^{31}$? */
3230   a=abs(a); b=abs(b);
3231   if ( a<=b ) {
3232     @<Handle erroneous |pyth_sub| and set |a:=0|@>;
3233   } else { 
3234     if ( a<fraction_four ) {
3235       big=false;
3236     } else  { 
3237       a=halfp(a); b=halfp(b); big=true;
3238     }
3239     @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>;
3240     if ( big ) double(a);
3241   }
3242   return a;
3243 }
3244
3245 @ @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>=
3246 while (1) { 
3247   r=mp_make_fraction(mp, b,a);
3248   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3249   if ( r==0 ) break;
3250   r=mp_make_fraction(mp, r,fraction_four-r);
3251   a=a-mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3252 }
3253
3254 @ @<Handle erroneous |pyth_sub| and set |a:=0|@>=
3255
3256   if ( a<b ){ 
3257     print_err("Pythagorean subtraction "); mp_print_scaled(mp, a);
3258     mp_print(mp, "+-+"); mp_print_scaled(mp, b); 
3259     mp_print(mp, " has been replaced by 0");
3260 @.Pythagorean...@>
3261     help2("Since I don't take square roots of negative numbers,")
3262          ("I'm zeroing this one. Proceed, with fingers crossed.");
3263     mp_error(mp);
3264   }
3265   a=0;
3266 }
3267
3268 @ The subroutines for logarithm and exponential involve two tables.
3269 The first is simple: |two_to_the[k]| equals $2^k$. The second involves
3270 a bit more calculation, which the author claims to have done correctly:
3271 |spec_log[k]| is $2^{27}$ times $\ln\bigl(1/(1-2^{-k})\bigr)=
3272 2^{-k}+{1\over2}2^{-2k}+{1\over3}2^{-3k}+\cdots\,$, rounded to the
3273 nearest integer.
3274
3275 @d two_to_the(A) (1<<(A))
3276
3277 @<Constants ...@>=
3278 static const integer spec_log[29] = { 0, /* special logarithms */
3279 93032640, 38612034, 17922280, 8662214, 4261238, 2113709,
3280 1052693, 525315, 262400, 131136, 65552, 32772, 16385,
3281 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 1 };
3282
3283 @ @<Local variables for initialization@>=
3284 integer k; /* all-purpose loop index */
3285
3286
3287 @ Here is the routine that calculates $2^8$ times the natural logarithm
3288 of a |scaled| quantity; it is an integer approximation to $2^{24}\ln(x/2^{16})$,
3289 when |x| is a given positive integer.
3290
3291 The method is based on exercise 1.2.2--25 in {\sl The Art of Computer
3292 Programming\/}: During the main iteration we have $1\L 2^{-30}x<1/(1-2^{1-k})$,
3293 and the logarithm of $2^{30}x$ remains to be added to an accumulator
3294 register called~$y$. Three auxiliary bits of accuracy are retained in~$y$
3295 during the calculation, and sixteen auxiliary bits to extend |y| are
3296 kept in~|z| during the initial argument reduction. (We add
3297 $100\cdot2^{16}=6553600$ to~|z| and subtract 100 from~|y| so that |z| will
3298 not become negative; also, the actual amount subtracted from~|y| is~96,
3299 not~100, because we want to add~4 for rounding before the final division by~8.)
3300
3301 @c 
3302 scaled mp_m_log (MP mp,scaled x) {
3303   integer y,z; /* auxiliary registers */
3304   integer k; /* iteration counter */
3305   if ( x<=0 ) {
3306      @<Handle non-positive logarithm@>;
3307   } else  { 
3308     y=1302456956+4-100; /* $14\times2^{27}\ln2\approx1302456956.421063$ */
3309     z=27595+6553600; /* and $2^{16}\times .421063\approx 27595$ */
3310     while ( x<fraction_four ) {
3311        double(x); y-=93032639; z-=48782;
3312     } /* $2^{27}\ln2\approx 93032639.74436163$ and $2^{16}\times.74436163\approx 48782$ */
3313     y=y+(z / unity); k=2;
3314     while ( x>fraction_four+4 ) {
3315       @<Increase |k| until |x| can be multiplied by a
3316         factor of $2^{-k}$, and adjust $y$ accordingly@>;
3317     }
3318     return (y / 8);
3319   }
3320 }
3321
3322 @ @<Increase |k| until |x| can...@>=
3323
3324   z=((x-1) / two_to_the(k))+1; /* $z=\lceil x/2^k\rceil$ */
3325   while ( x<fraction_four+z ) { z=halfp(z+1); incr(k); };
3326   y+=spec_log[k]; x-=z;
3327 }
3328
3329 @ @<Handle non-positive logarithm@>=
3330
3331   print_err("Logarithm of ");
3332 @.Logarithm...replaced by 0@>
3333   mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3334   help2("Since I don't take logs of non-positive numbers,")
3335        ("I'm zeroing this one. Proceed, with fingers crossed.");
3336   mp_error(mp); 
3337   return 0;
3338 }
3339
3340 @ Conversely, the exponential routine calculates $\exp(x/2^8)$,
3341 when |x| is |scaled|. The result is an integer approximation to
3342 $2^{16}\exp(x/2^{24})$, when |x| is regarded as an integer.
3343
3344 @c 
3345 scaled mp_m_exp (MP mp,scaled x) {
3346   small_number k; /* loop control index */
3347   integer y,z; /* auxiliary registers */
3348   if ( x>174436200 ) {
3349     /* $2^{24}\ln((2^{31}-1)/2^{16})\approx 174436199.51$ */
3350     mp->arith_error=true; 
3351     return el_gordo;
3352   } else if ( x<-197694359 ) {
3353         /* $2^{24}\ln(2^{-1}/2^{16})\approx-197694359.45$ */
3354     return 0;
3355   } else { 
3356     if ( x<=0 ) { 
3357        z=-8*x; y=04000000; /* $y=2^{20}$ */
3358     } else { 
3359       if ( x<=127919879 ) { 
3360         z=1023359037-8*x;
3361         /* $2^{27}\ln((2^{31}-1)/2^{20})\approx 1023359037.125$ */
3362       } else {
3363        z=8*(174436200-x); /* |z| is always nonnegative */
3364       }
3365       y=el_gordo;
3366     };
3367     @<Multiply |y| by $\exp(-z/2^{27})$@>;
3368     if ( x<=127919879 ) 
3369        return ((y+8) / 16);
3370      else 
3371        return y;
3372   }
3373 }
3374
3375 @ The idea here is that subtracting |spec_log[k]| from |z| corresponds
3376 to multiplying |y| by $1-2^{-k}$.
3377
3378 A subtle point (which had to be checked) was that if $x=127919879$, the
3379 value of~|y| will decrease so that |y+8| doesn't overflow. In fact,
3380 $z$ will be 5 in this case, and |y| will decrease by~64 when |k=25|
3381 and by~16 when |k=27|.
3382
3383 @<Multiply |y| by...@>=
3384 k=1;
3385 while ( z>0 ) { 
3386   while ( z>=spec_log[k] ) { 
3387     z-=spec_log[k];
3388     y=y-1-((y-two_to_the(k-1)) / two_to_the(k));
3389   }
3390   incr(k);
3391 }
3392
3393 @ The trigonometric subroutines use an auxiliary table such that
3394 |spec_atan[k]| contains an approximation to the |angle| whose tangent
3395 is~$1/2^k$. $\arctan2^{-k}$ times $2^{20}\cdot180/\pi$ 
3396
3397 @<Constants ...@>=
3398 static const angle spec_atan[27] = { 0, 27855475, 14718068, 7471121, 3750058, 
3399 1876857, 938658, 469357, 234682, 117342, 58671, 29335, 14668, 7334, 3667, 
3400 1833, 917, 458, 229, 115, 57, 29, 14, 7, 4, 2, 1 };
3401
3402 @ Given integers |x| and |y|, not both zero, the |n_arg| function
3403 returns the |angle| whose tangent points in the direction $(x,y)$.
3404 This subroutine first determines the correct octant, then solves the
3405 problem for |0<=y<=x|, then converts the result appropriately to
3406 return an answer in the range |-one_eighty_deg<=@t$\theta$@><=one_eighty_deg|.
3407 (The answer is |+one_eighty_deg| if |y=0| and |x<0|, but an answer of
3408 |-one_eighty_deg| is possible if, for example, |y=-1| and $x=-2^{30}$.)
3409
3410 The octants are represented in a ``Gray code,'' since that turns out
3411 to be computationally simplest.
3412
3413 @d negate_x 1
3414 @d negate_y 2
3415 @d switch_x_and_y 4
3416 @d first_octant 1
3417 @d second_octant (first_octant+switch_x_and_y)
3418 @d third_octant (first_octant+switch_x_and_y+negate_x)
3419 @d fourth_octant (first_octant+negate_x)
3420 @d fifth_octant (first_octant+negate_x+negate_y)
3421 @d sixth_octant (first_octant+switch_x_and_y+negate_x+negate_y)
3422 @d seventh_octant (first_octant+switch_x_and_y+negate_y)
3423 @d eighth_octant (first_octant+negate_y)
3424
3425 @c 
3426 angle mp_n_arg (MP mp,integer x, integer y) {
3427   angle z; /* auxiliary register */
3428   integer t; /* temporary storage */
3429   small_number k; /* loop counter */
3430   int octant; /* octant code */
3431   if ( x>=0 ) {
3432     octant=first_octant;
3433   } else { 
3434     negate(x); octant=first_octant+negate_x;
3435   }
3436   if ( y<0 ) { 
3437     negate(y); octant=octant+negate_y;
3438   }
3439   if ( x<y ) { 
3440     t=y; y=x; x=t; octant=octant+switch_x_and_y;
3441   }
3442   if ( x==0 ) { 
3443     @<Handle undefined arg@>; 
3444   } else { 
3445     @<Set variable |z| to the arg of $(x,y)$@>;
3446     @<Return an appropriate answer based on |z| and |octant|@>;
3447   }
3448 }
3449
3450 @ @<Handle undefined arg@>=
3451
3452   print_err("angle(0,0) is taken as zero");
3453 @.angle(0,0)...zero@>
3454   help2("The `angle' between two identical points is undefined.")
3455        ("I'm zeroing this one. Proceed, with fingers crossed.");
3456   mp_error(mp); 
3457   return 0;
3458 }
3459
3460 @ @<Return an appropriate answer...@>=
3461 switch (octant) {
3462 case first_octant: return z;
3463 case second_octant: return (ninety_deg-z);
3464 case third_octant: return (ninety_deg+z);
3465 case fourth_octant: return (one_eighty_deg-z);
3466 case fifth_octant: return (z-one_eighty_deg);
3467 case sixth_octant: return (-z-ninety_deg);
3468 case seventh_octant: return (z-ninety_deg);
3469 case eighth_octant: return (-z);
3470 }; /* there are no other cases */
3471 return 0
3472
3473 @ At this point we have |x>=y>=0|, and |x>0|. The numbers are scaled up
3474 or down until $2^{28}\L x<2^{29}$, so that accurate fixed-point calculations
3475 will be made.
3476
3477 @<Set variable |z| to the arg...@>=
3478 while ( x>=fraction_two ) { 
3479   x=halfp(x); y=halfp(y);
3480 }
3481 z=0;
3482 if ( y>0 ) { 
3483  while ( x<fraction_one ) { 
3484     x+=x; y+=y; 
3485  };
3486  @<Increase |z| to the arg of $(x,y)$@>;
3487 }
3488
3489 @ During the calculations of this section, variables |x| and~|y|
3490 represent actual coordinates $(x,2^{-k}y)$. We will maintain the
3491 condition |x>=y|, so that the tangent will be at most $2^{-k}$.
3492 If $x<2y$, the tangent is greater than $2^{-k-1}$. The transformation
3493 $(a,b)\mapsto(a+b\tan\phi,b-a\tan\phi)$ replaces $(a,b)$ by
3494 coordinates whose angle has decreased by~$\phi$; in the special case
3495 $a=x$, $b=2^{-k}y$, and $\tan\phi=2^{-k-1}$, this operation reduces
3496 to the particularly simple iteration shown here. [Cf.~John E. Meggitt,
3497 @^Meggitt, John E.@>
3498 {\sl IBM Journal of Research and Development\/ \bf6} (1962), 210--226.]
3499
3500 The initial value of |x| will be multiplied by at most
3501 $(1+{1\over2})(1+{1\over8})(1+{1\over32})\cdots\approx 1.7584$; hence
3502 there is no chance of integer overflow.
3503
3504 @<Increase |z|...@>=
3505 k=0;
3506 do {  
3507   y+=y; incr(k);
3508   if ( y>x ){ 
3509     z=z+spec_atan[k]; t=x; x=x+(y / two_to_the(k+k)); y=y-t;
3510   };
3511 } while (k!=15);
3512 do {  
3513   y+=y; incr(k);
3514   if ( y>x ) { z=z+spec_atan[k]; y=y-x; };
3515 } while (k!=26)
3516
3517 @ Conversely, the |n_sin_cos| routine takes an |angle| and produces the sine
3518 and cosine of that angle. The results of this routine are
3519 stored in global integer variables |n_sin| and |n_cos|.
3520
3521 @<Glob...@>=
3522 fraction n_sin;fraction n_cos; /* results computed by |n_sin_cos| */
3523
3524 @ Given an integer |z| that is $2^{20}$ times an angle $\theta$ in degrees,
3525 the purpose of |n_sin_cos(z)| is to set
3526 |x=@t$r\cos\theta$@>| and |y=@t$r\sin\theta$@>| (approximately),
3527 for some rather large number~|r|. The maximum of |x| and |y|
3528 will be between $2^{28}$ and $2^{30}$, so that there will be hardly
3529 any loss of accuracy. Then |x| and~|y| are divided by~|r|.
3530
3531 @c 
3532 void mp_n_sin_cos (MP mp,angle z) { /* computes a multiple of the sine
3533                                        and cosine */ 
3534   small_number k; /* loop control variable */
3535   int q; /* specifies the quadrant */
3536   fraction r; /* magnitude of |(x,y)| */
3537   integer x,y,t; /* temporary registers */
3538   while ( z<0 ) z=z+three_sixty_deg;
3539   z=z % three_sixty_deg; /* now |0<=z<three_sixty_deg| */
3540   q=z / forty_five_deg; z=z % forty_five_deg;
3541   x=fraction_one; y=x;
3542   if ( ! odd(q) ) z=forty_five_deg-z;
3543   @<Subtract angle |z| from |(x,y)|@>;
3544   @<Convert |(x,y)| to the octant determined by~|q|@>;
3545   r=mp_pyth_add(mp, x,y); 
3546   mp->n_cos=mp_make_fraction(mp, x,r); 
3547   mp->n_sin=mp_make_fraction(mp, y,r);
3548 }
3549
3550 @ In this case the octants are numbered sequentially.
3551
3552 @<Convert |(x,...@>=
3553 switch (q) {
3554 case 0: break;
3555 case 1: t=x; x=y; y=t; break;
3556 case 2: t=x; x=-y; y=t; break;
3557 case 3: negate(x); break;
3558 case 4: negate(x); negate(y); break;
3559 case 5: t=x; x=-y; y=-t; break;
3560 case 6: t=x; x=y; y=-t; break;
3561 case 7: negate(y); break;
3562 } /* there are no other cases */
3563
3564 @ The main iteration of |n_sin_cos| is similar to that of |n_arg| but
3565 applied in reverse. The values of |spec_atan[k]| decrease slowly enough
3566 that this loop is guaranteed to terminate before the (nonexistent) value
3567 |spec_atan[27]| would be required.
3568
3569 @<Subtract angle |z|...@>=
3570 k=1;
3571 while ( z>0 ){ 
3572   if ( z>=spec_atan[k] ) { 
3573     z=z-spec_atan[k]; t=x;
3574     x=t+y / two_to_the(k);
3575     y=y-t / two_to_the(k);
3576   }
3577   incr(k);
3578 }
3579 if ( y<0 ) y=0 /* this precaution may never be needed */
3580
3581 @ And now let's complete our collection of numeric utility routines
3582 by considering random number generation.
3583 \MP\ generates pseudo-random numbers with the additive scheme recommended
3584 in Section 3.6 of {\sl The Art of Computer Programming}; however, the
3585 results are random fractions between 0 and |fraction_one-1|, inclusive.
3586
3587 There's an auxiliary array |randoms| that contains 55 pseudo-random
3588 fractions. Using the recurrence $x_n=(x_{n-55}-x_{n-31})\bmod 2^{28}$,
3589 we generate batches of 55 new $x_n$'s at a time by calling |new_randoms|.
3590 The global variable |j_random| tells which element has most recently
3591 been consumed.
3592 The global variable |sys_random_seed| was introduced in version 0.9,
3593 for the sole reason of stressing the fact that the initial value of the
3594 random seed is system-dependant. The pascal code below will initialize
3595 this variable to |(internal[mp_time] div unity)+internal[mp_day]|, but this 
3596 is not good enough on modern fast machines that are capable of running
3597 multiple MetaPost processes within the same second.
3598 @^system dependencies@>
3599
3600 @<Glob...@>=
3601 fraction randoms[55]; /* the last 55 random values generated */
3602 int j_random; /* the number of unused |randoms| */
3603 scaled sys_random_seed; /* the default random seed */
3604
3605 @ @<Exported types@>=
3606 typedef int (*mp_get_random_seed_command)(MP mp);
3607
3608 @ @<Glob...@>=
3609 mp_get_random_seed_command get_random_seed;
3610
3611 @ @<Option variables@>=
3612 mp_get_random_seed_command get_random_seed;
3613
3614 @ @<Allocate or initialize ...@>=
3615 set_callback_option(get_random_seed);
3616
3617 @ @<Internal library declarations@>=
3618 int mp_get_random_seed (MP mp);
3619
3620 @ @c 
3621 int mp_get_random_seed (MP mp) {
3622   return (mp->internal[mp_time] / unity)+mp->internal[mp_day];
3623 }
3624
3625 @ To consume a random fraction, the program below will say `|next_random|'
3626 and then it will fetch |randoms[j_random]|.
3627
3628 @d next_random { if ( mp->j_random==0 ) mp_new_randoms(mp);
3629   else decr(mp->j_random); }
3630
3631 @c 
3632 void mp_new_randoms (MP mp) {
3633   int k; /* index into |randoms| */
3634   fraction x; /* accumulator */
3635   for (k=0;k<=23;k++) { 
3636    x=mp->randoms[k]-mp->randoms[k+31];
3637     if ( x<0 ) x=x+fraction_one;
3638     mp->randoms[k]=x;
3639   }
3640   for (k=24;k<= 54;k++){ 
3641     x=mp->randoms[k]-mp->randoms[k-24];
3642     if ( x<0 ) x=x+fraction_one;
3643     mp->randoms[k]=x;
3644   }
3645   mp->j_random=54;
3646 }
3647
3648 @ @<Declarations@>=
3649 void mp_init_randoms (MP mp,scaled seed);
3650
3651 @ To initialize the |randoms| table, we call the following routine.
3652
3653 @c 
3654 void mp_init_randoms (MP mp,scaled seed) {
3655   fraction j,jj,k; /* more or less random integers */
3656   int i; /* index into |randoms| */
3657   j=abs(seed);
3658   while ( j>=fraction_one ) j=halfp(j);
3659   k=1;
3660   for (i=0;i<=54;i++ ){ 
3661     jj=k; k=j-k; j=jj;
3662     if ( k<0 ) k=k+fraction_one;
3663     mp->randoms[(i*21)% 55]=j;
3664   }
3665   mp_new_randoms(mp); 
3666   mp_new_randoms(mp); 
3667   mp_new_randoms(mp); /* ``warm up'' the array */
3668 }
3669
3670 @ To produce a uniform random number in the range |0<=u<x| or |0>=u>x|
3671 or |0=u=x|, given a |scaled| value~|x|, we proceed as shown here.
3672
3673 Note that the call of |take_fraction| will produce the values 0 and~|x|
3674 with about half the probability that it will produce any other particular
3675 values between 0 and~|x|, because it rounds its answers.
3676
3677 @c 
3678 scaled mp_unif_rand (MP mp,scaled x) {
3679   scaled y; /* trial value */
3680   next_random; y=mp_take_fraction(mp, abs(x),mp->randoms[mp->j_random]);
3681   if ( y==abs(x) ) return 0;
3682   else if ( x>0 ) return y;
3683   else return (-y);
3684 }
3685
3686 @ Finally, a normal deviate with mean zero and unit standard deviation
3687 can readily be obtained with the ratio method (Algorithm 3.4.1R in
3688 {\sl The Art of Computer Programming\/}).
3689
3690 @c 
3691 scaled mp_norm_rand (MP mp) {
3692   integer x,u,l; /* what the book would call $2^{16}X$, $2^{28}U$, and $-2^{24}\ln U$ */
3693   do { 
3694     do {  
3695       next_random;
3696       x=mp_take_fraction(mp, 112429,mp->randoms[mp->j_random]-fraction_half);
3697       /* $2^{16}\sqrt{8/e}\approx 112428.82793$ */
3698       next_random; u=mp->randoms[mp->j_random];
3699     } while (abs(x)>=u);
3700     x=mp_make_fraction(mp, x,u);
3701     l=139548960-mp_m_log(mp, u); /* $2^{24}\cdot12\ln2\approx139548959.6165$ */
3702   } while (mp_ab_vs_cd(mp, 1024,l,x,x)<0);
3703   return x;
3704 }
3705
3706 @* \[9] Packed data.
3707 In order to make efficient use of storage space, \MP\ bases its major data
3708 structures on a |memory_word|, which contains either a (signed) integer,
3709 possibly scaled, or a small number of fields that are one half or one
3710 quarter of the size used for storing integers.
3711
3712 If |x| is a variable of type |memory_word|, it contains up to four
3713 fields that can be referred to as follows:
3714 $$\vbox{\halign{\hfil#&#\hfil&#\hfil\cr
3715 |x|&.|int|&(an |integer|)\cr
3716 |x|&.|sc|\qquad&(a |scaled| integer)\cr
3717 |x.hh.lh|, |x.hh|&.|rh|&(two halfword fields)\cr
3718 |x.hh.b0|, |x.hh.b1|, |x.hh|&.|rh|&(two quarterword fields, one halfword
3719   field)\cr
3720 |x.qqqq.b0|, |x.qqqq.b1|, |x.qqqq|&.|b2|, |x.qqqq.b3|\hskip-100pt
3721   &\qquad\qquad\qquad(four quarterword fields)\cr}}$$
3722 This is somewhat cumbersome to write, and not very readable either, but
3723 macros will be used to make the notation shorter and more transparent.
3724 The code below gives a formal definition of |memory_word| and
3725 its subsidiary types, using packed variant records. \MP\ makes no
3726 assumptions about the relative positions of the fields within a word.
3727
3728 @d max_quarterword 0x3FFF /* largest allowable value in a |quarterword| */
3729 @d max_halfword 0xFFFFFFF /* largest allowable value in a |halfword| */
3730
3731 @ Here are the inequalities that the quarterword and halfword values
3732 must satisfy (or rather, the inequalities that they mustn't satisfy):
3733
3734 @<Check the ``constant''...@>=
3735 if (mp->ini_version) {
3736   if ( mp->mem_max!=mp->mem_top ) mp->bad=8;
3737 } else {
3738   if ( mp->mem_max<mp->mem_top ) mp->bad=8;
3739 }
3740 if ( max_quarterword<255 ) mp->bad=9;
3741 if ( max_halfword<65535 ) mp->bad=10;
3742 if ( max_quarterword>max_halfword ) mp->bad=11;
3743 if ( mp->mem_max>=max_halfword ) mp->bad=12;
3744 if ( mp->max_strings>max_halfword ) mp->bad=13;
3745
3746 @ The macros |qi| and |qo| are used for input to and output 
3747 from quarterwords. These are legacy macros.
3748 @^system dependencies@>
3749
3750 @d qo(A) (A) /* to read eight bits from a quarterword */
3751 @d qi(A) (A) /* to store eight bits in a quarterword */
3752
3753 @ The reader should study the following definitions closely:
3754 @^system dependencies@>
3755
3756 @d sc cint /* |scaled| data is equivalent to |integer| */
3757
3758 @<Types...@>=
3759 typedef short quarterword; /* 1/4 of a word */
3760 typedef int halfword; /* 1/2 of a word */
3761 typedef union {
3762   struct {
3763     halfword RH, LH;
3764   } v;
3765   struct { /* Make B0,B1 overlap the most significant bytes of LH.  */
3766     halfword junk;
3767     quarterword B0, B1;
3768   } u;
3769 } two_halves;
3770 typedef struct {
3771   struct {
3772     quarterword B2, B3, B0, B1;
3773   } u;
3774 } four_quarters;
3775 typedef union {
3776   two_halves hh;
3777   integer cint;
3778   four_quarters qqqq;
3779 } memory_word;
3780 #define b0 u.B0
3781 #define b1 u.B1
3782 #define b2 u.B2
3783 #define b3 u.B3
3784 #define rh v.RH
3785 #define lh v.LH
3786
3787 @ When debugging, we may want to print a |memory_word| without knowing
3788 what type it is; so we print it in all modes.
3789 @^dirty \PASCAL@>@^debugging@>
3790
3791 @c 
3792 void mp_print_word (MP mp,memory_word w) {
3793   /* prints |w| in all ways */
3794   mp_print_int(mp, w.cint); mp_print_char(mp, ' ');
3795   mp_print_scaled(mp, w.sc); mp_print_char(mp, ' '); 
3796   mp_print_scaled(mp, w.sc / 010000); mp_print_ln(mp);
3797   mp_print_int(mp, w.hh.lh); mp_print_char(mp, '='); 
3798   mp_print_int(mp, w.hh.b0); mp_print_char(mp, ':');
3799   mp_print_int(mp, w.hh.b1); mp_print_char(mp, ';'); 
3800   mp_print_int(mp, w.hh.rh); mp_print_char(mp, ' ');
3801   mp_print_int(mp, w.qqqq.b0); mp_print_char(mp, ':'); 
3802   mp_print_int(mp, w.qqqq.b1); mp_print_char(mp, ':');
3803   mp_print_int(mp, w.qqqq.b2); mp_print_char(mp, ':'); 
3804   mp_print_int(mp, w.qqqq.b3);
3805 }
3806
3807
3808 @* \[10] Dynamic memory allocation.
3809
3810 The \MP\ system does nearly all of its own memory allocation, so that it
3811 can readily be transported into environments that do not have automatic
3812 facilities for strings, garbage collection, etc., and so that it can be in
3813 control of what error messages the user receives. The dynamic storage
3814 requirements of \MP\ are handled by providing a large array |mem| in
3815 which consecutive blocks of words are used as nodes by the \MP\ routines.
3816
3817 Pointer variables are indices into this array, or into another array
3818 called |eqtb| that will be explained later. A pointer variable might
3819 also be a special flag that lies outside the bounds of |mem|, so we
3820 allow pointers to assume any |halfword| value. The minimum memory
3821 index represents a null pointer.
3822
3823 @d null 0 /* the null pointer */
3824 @d mp_void (null+1) /* a null pointer different from |null| */
3825
3826
3827 @<Types...@>=
3828 typedef halfword pointer; /* a flag or a location in |mem| or |eqtb| */
3829
3830 @ The |mem| array is divided into two regions that are allocated separately,
3831 but the dividing line between these two regions is not fixed; they grow
3832 together until finding their ``natural'' size in a particular job.
3833 Locations less than or equal to |lo_mem_max| are used for storing
3834 variable-length records consisting of two or more words each. This region
3835 is maintained using an algorithm similar to the one described in exercise
3836 2.5--19 of {\sl The Art of Computer Programming}. However, no size field
3837 appears in the allocated nodes; the program is responsible for knowing the
3838 relevant size when a node is freed. Locations greater than or equal to
3839 |hi_mem_min| are used for storing one-word records; a conventional
3840 \.{AVAIL} stack is used for allocation in this region.
3841
3842 Locations of |mem| between |0| and |mem_top| may be dumped as part
3843 of preloaded format files, by the \.{INIMP} preprocessor.
3844 @.INIMP@>
3845 Production versions of \MP\ may extend the memory at the top end in order to
3846 provide more space; these locations, between |mem_top| and |mem_max|,
3847 are always used for single-word nodes.
3848
3849 The key pointers that govern |mem| allocation have a prescribed order:
3850 $$\hbox{|null=0<lo_mem_max<hi_mem_min<mem_top<=mem_end<=mem_max|.}$$
3851
3852 @<Glob...@>=
3853 memory_word *mem; /* the big dynamic storage area */
3854 pointer lo_mem_max; /* the largest location of variable-size memory in use */
3855 pointer hi_mem_min; /* the smallest location of one-word memory in use */
3856
3857
3858
3859 @d xfree(A) do { mp_xfree(A); A=NULL; } while (0)
3860 @d xrealloc(P,A,B) mp_xrealloc(mp,P,A,B)
3861 @d xmalloc(A,B)  mp_xmalloc(mp,A,B)
3862 @d xstrdup(A)  mp_xstrdup(mp,A)
3863 @d XREALLOC(a,b,c) a = xrealloc(a,(b+1),sizeof(c));
3864
3865 @<Declare helpers@>=
3866 void mp_xfree (void *x);
3867 void *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) ;
3868 void *mp_xmalloc (MP mp, size_t nmem, size_t size) ;
3869 char *mp_xstrdup(MP mp, const char *s);
3870
3871 @ The |max_size_test| guards against overflow, on the assumption that
3872 |size_t| is at least 31bits wide.
3873
3874 @d max_size_test 0x7FFFFFFF
3875
3876 @c
3877 void mp_xfree (void *x) {
3878   if (x!=NULL) free(x);
3879 }
3880 void  *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) {
3881   void *w ; 
3882   if ((max_size_test/size)<nmem) {
3883     fprintf(stderr,"Memory size overflow!\n");
3884     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3885   }
3886   w = realloc (p,(nmem*size));
3887   if (w==NULL) {
3888     fprintf(stderr,"Out of memory!\n");
3889     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3890   }
3891   return w;
3892 }
3893 void  *mp_xmalloc (MP mp, size_t nmem, size_t size) {
3894   void *w;
3895   if ((max_size_test/size)<nmem) {
3896     fprintf(stderr,"Memory size overflow!\n");
3897     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3898   }
3899   w = malloc (nmem*size);
3900   if (w==NULL) {
3901     fprintf(stderr,"Out of memory!\n");
3902     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3903   }
3904   return w;
3905 }
3906 char *mp_xstrdup(MP mp, const char *s) {
3907   char *w; 
3908   if (s==NULL)
3909     return NULL;
3910   w = strdup(s);
3911   if (w==NULL) {
3912     fprintf(stderr,"Out of memory!\n");
3913     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3914   }
3915   return w;
3916 }
3917
3918
3919
3920 @<Allocate or initialize ...@>=
3921 mp->mem = xmalloc ((mp->mem_max+1),sizeof (memory_word));
3922 memset(mp->mem,0,(mp->mem_max+1)*sizeof (memory_word));
3923
3924 @ @<Dealloc variables@>=
3925 xfree(mp->mem);
3926
3927 @ Users who wish to study the memory requirements of particular applications can
3928 can use optional special features that keep track of current and
3929 maximum memory usage. When code between the delimiters |stat| $\ldots$
3930 |tats| is not ``commented out,'' \MP\ will run a bit slower but it will
3931 report these statistics when |mp_tracing_stats| is positive.
3932
3933 @<Glob...@>=
3934 integer var_used; integer dyn_used; /* how much memory is in use */
3935
3936 @ Let's consider the one-word memory region first, since it's the
3937 simplest. The pointer variable |mem_end| holds the highest-numbered location
3938 of |mem| that has ever been used. The free locations of |mem| that
3939 occur between |hi_mem_min| and |mem_end|, inclusive, are of type
3940 |two_halves|, and we write |info(p)| and |link(p)| for the |lh|
3941 and |rh| fields of |mem[p]| when it is of this type. The single-word
3942 free locations form a linked list
3943 $$|avail|,\;\hbox{|link(avail)|},\;\hbox{|link(link(avail))|},\;\ldots$$
3944 terminated by |null|.
3945
3946 @d link(A)   mp->mem[(A)].hh.rh /* the |link| field of a memory word */
3947 @d info(A)   mp->mem[(A)].hh.lh /* the |info| field of a memory word */
3948
3949 @<Glob...@>=
3950 pointer avail; /* head of the list of available one-word nodes */
3951 pointer mem_end; /* the last one-word node used in |mem| */
3952
3953 @ If one-word memory is exhausted, it might mean that the user has forgotten
3954 a token like `\&{enddef}' or `\&{endfor}'. We will define some procedures
3955 later that try to help pinpoint the trouble.
3956
3957 @c 
3958 @<Declare the procedure called |show_token_list|@>;
3959 @<Declare the procedure called |runaway|@>
3960
3961 @ The function |get_avail| returns a pointer to a new one-word node whose
3962 |link| field is null. However, \MP\ will halt if there is no more room left.
3963 @^inner loop@>
3964
3965 @c 
3966 pointer mp_get_avail (MP mp) { /* single-word node allocation */
3967   pointer p; /* the new node being got */
3968   p=mp->avail; /* get top location in the |avail| stack */
3969   if ( p!=null ) {
3970     mp->avail=link(mp->avail); /* and pop it off */
3971   } else if ( mp->mem_end<mp->mem_max ) { /* or go into virgin territory */
3972     incr(mp->mem_end); p=mp->mem_end;
3973   } else { 
3974     decr(mp->hi_mem_min); p=mp->hi_mem_min;
3975     if ( mp->hi_mem_min<=mp->lo_mem_max ) { 
3976       mp_runaway(mp); /* if memory is exhausted, display possible runaway text */
3977       mp_overflow(mp, "main memory size",mp->mem_max);
3978       /* quit; all one-word nodes are busy */
3979 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
3980     }
3981   }
3982   link(p)=null; /* provide an oft-desired initialization of the new node */
3983   incr(mp->dyn_used);/* maintain statistics */
3984   return p;
3985 };
3986
3987 @ Conversely, a one-word node is recycled by calling |free_avail|.
3988
3989 @d free_avail(A)  /* single-word node liberation */
3990   { link((A))=mp->avail; mp->avail=(A); decr(mp->dyn_used);  }
3991
3992 @ There's also a |fast_get_avail| routine, which saves the procedure-call
3993 overhead at the expense of extra programming. This macro is used in
3994 the places that would otherwise account for the most calls of |get_avail|.
3995 @^inner loop@>
3996
3997 @d fast_get_avail(A) { 
3998   (A)=mp->avail; /* avoid |get_avail| if possible, to save time */
3999   if ( (A)==null ) { (A)=mp_get_avail(mp); } 
4000   else { mp->avail=link((A)); link((A))=null;  incr(mp->dyn_used); }
4001   }
4002
4003 @ The available-space list that keeps track of the variable-size portion
4004 of |mem| is a nonempty, doubly-linked circular list of empty nodes,
4005 pointed to by the roving pointer |rover|.
4006
4007 Each empty node has size 2 or more; the first word contains the special
4008 value |max_halfword| in its |link| field and the size in its |info| field;
4009 the second word contains the two pointers for double linking.
4010
4011 Each nonempty node also has size 2 or more. Its first word is of type
4012 |two_halves|\kern-1pt, and its |link| field is never equal to |max_halfword|.
4013 Otherwise there is complete flexibility with respect to the contents
4014 of its other fields and its other words.
4015
4016 (We require |mem_max<max_halfword| because terrible things can happen
4017 when |max_halfword| appears in the |link| field of a nonempty node.)
4018
4019 @d empty_flag   max_halfword /* the |link| of an empty variable-size node */
4020 @d is_empty(A)   (link((A))==empty_flag) /* tests for empty node */
4021 @d node_size   info /* the size field in empty variable-size nodes */
4022 @d llink(A)   info((A)+1) /* left link in doubly-linked list of empty nodes */
4023 @d rlink(A)   link((A)+1) /* right link in doubly-linked list of empty nodes */
4024
4025 @<Glob...@>=
4026 pointer rover; /* points to some node in the list of empties */
4027
4028 @ A call to |get_node| with argument |s| returns a pointer to a new node
4029 of size~|s|, which must be 2~or more. The |link| field of the first word
4030 of this new node is set to null. An overflow stop occurs if no suitable
4031 space exists.
4032
4033 If |get_node| is called with $s=2^{30}$, it simply merges adjacent free
4034 areas and returns the value |max_halfword|.
4035
4036 @<Declarations@>=
4037 pointer mp_get_node (MP mp,integer s) ;
4038
4039 @ @c 
4040 pointer mp_get_node (MP mp,integer s) { /* variable-size node allocation */
4041   pointer p; /* the node currently under inspection */
4042   pointer q;  /* the node physically after node |p| */
4043   integer r; /* the newly allocated node, or a candidate for this honor */
4044   integer t,tt; /* temporary registers */
4045 @^inner loop@>
4046  RESTART: 
4047   p=mp->rover; /* start at some free node in the ring */
4048   do {  
4049     @<Try to allocate within node |p| and its physical successors,
4050      and |goto found| if allocation was possible@>;
4051     p=rlink(p); /* move to the next node in the ring */
4052   } while (p!=mp->rover); /* repeat until the whole list has been traversed */
4053   if ( s==010000000000 ) { 
4054     return max_halfword;
4055   };
4056   if ( mp->lo_mem_max+2<mp->hi_mem_min ) {
4057     if ( mp->lo_mem_max+2<=max_halfword ) {
4058       @<Grow more variable-size memory and |goto restart|@>;
4059     }
4060   }
4061   mp_overflow(mp, "main memory size",mp->mem_max);
4062   /* sorry, nothing satisfactory is left */
4063 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
4064 FOUND: 
4065   link(r)=null; /* this node is now nonempty */
4066   mp->var_used=mp->var_used+s; /* maintain usage statistics */
4067   return r;
4068 }
4069
4070 @ The lower part of |mem| grows by 1000 words at a time, unless
4071 we are very close to going under. When it grows, we simply link
4072 a new node into the available-space list. This method of controlled
4073 growth helps to keep the |mem| usage consecutive when \MP\ is
4074 implemented on ``virtual memory'' systems.
4075 @^virtual memory@>
4076
4077 @<Grow more variable-size memory and |goto restart|@>=
4078
4079   if ( mp->hi_mem_min-mp->lo_mem_max>=1998 ) {
4080     t=mp->lo_mem_max+1000;
4081   } else {
4082     t=mp->lo_mem_max+1+(mp->hi_mem_min-mp->lo_mem_max) / 2; 
4083     /* |lo_mem_max+2<=t<hi_mem_min| */
4084   }
4085   if ( t>max_halfword ) t=max_halfword;
4086   p=llink(mp->rover); q=mp->lo_mem_max; rlink(p)=q; llink(mp->rover)=q;
4087   rlink(q)=mp->rover; llink(q)=p; link(q)=empty_flag; node_size(q)=t-mp->lo_mem_max;
4088   mp->lo_mem_max=t; link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4089   mp->rover=q; 
4090   goto RESTART;
4091 }
4092
4093 @ @<Try to allocate...@>=
4094 q=p+node_size(p); /* find the physical successor */
4095 while ( is_empty(q) ) { /* merge node |p| with node |q| */
4096   t=rlink(q); tt=llink(q);
4097 @^inner loop@>
4098   if ( q==mp->rover ) mp->rover=t;
4099   llink(t)=tt; rlink(tt)=t;
4100   q=q+node_size(q);
4101 }
4102 r=q-s;
4103 if ( r>p+1 ) {
4104   @<Allocate from the top of node |p| and |goto found|@>;
4105 }
4106 if ( r==p ) { 
4107   if ( rlink(p)!=p ) {
4108     @<Allocate entire node |p| and |goto found|@>;
4109   }
4110 }
4111 node_size(p)=q-p /* reset the size in case it grew */
4112
4113 @ @<Allocate from the top...@>=
4114
4115   node_size(p)=r-p; /* store the remaining size */
4116   mp->rover=p; /* start searching here next time */
4117   goto FOUND;
4118 }
4119
4120 @ Here we delete node |p| from the ring, and let |rover| rove around.
4121
4122 @<Allocate entire...@>=
4123
4124   mp->rover=rlink(p); t=llink(p);
4125   llink(mp->rover)=t; rlink(t)=mp->rover;
4126   goto FOUND;
4127 }
4128
4129 @ Conversely, when some variable-size node |p| of size |s| is no longer needed,
4130 the operation |free_node(p,s)| will make its words available, by inserting
4131 |p| as a new empty node just before where |rover| now points.
4132
4133 @<Declarations@>=
4134 void mp_free_node (MP mp, pointer p, halfword s) ;
4135
4136 @ @c 
4137 void mp_free_node (MP mp, pointer p, halfword s) { /* variable-size node
4138   liberation */
4139   pointer q; /* |llink(rover)| */
4140   node_size(p)=s; link(p)=empty_flag;
4141 @^inner loop@>
4142   q=llink(mp->rover); llink(p)=q; rlink(p)=mp->rover; /* set both links */
4143   llink(mp->rover)=p; rlink(q)=p; /* insert |p| into the ring */
4144   mp->var_used=mp->var_used-s; /* maintain statistics */
4145 }
4146
4147 @ Just before \.{INIMP} writes out the memory, it sorts the doubly linked
4148 available space list. The list is probably very short at such times, so a
4149 simple insertion sort is used. The smallest available location will be
4150 pointed to by |rover|, the next-smallest by |rlink(rover)|, etc.
4151
4152 @c 
4153 void mp_sort_avail (MP mp) { /* sorts the available variable-size nodes
4154   by location */
4155   pointer p,q,r; /* indices into |mem| */
4156   pointer old_rover; /* initial |rover| setting */
4157   p=mp_get_node(mp, 010000000000); /* merge adjacent free areas */
4158   p=rlink(mp->rover); rlink(mp->rover)=max_halfword; old_rover=mp->rover;
4159   while ( p!=old_rover ) {
4160     @<Sort |p| into the list starting at |rover|
4161      and advance |p| to |rlink(p)|@>;
4162   }
4163   p=mp->rover;
4164   while ( rlink(p)!=max_halfword ) { 
4165     llink(rlink(p))=p; p=rlink(p);
4166   };
4167   rlink(p)=mp->rover; llink(mp->rover)=p;
4168 }
4169
4170 @ The following |while| loop is guaranteed to
4171 terminate, since the list that starts at
4172 |rover| ends with |max_halfword| during the sorting procedure.
4173
4174 @<Sort |p|...@>=
4175 if ( p<mp->rover ) { 
4176   q=p; p=rlink(q); rlink(q)=mp->rover; mp->rover=q;
4177 } else  { 
4178   q=mp->rover;
4179   while ( rlink(q)<p ) q=rlink(q);
4180   r=rlink(p); rlink(p)=rlink(q); rlink(q)=p; p=r;
4181 }
4182
4183 @* \[11] Memory layout.
4184 Some areas of |mem| are dedicated to fixed usage, since static allocation is
4185 more efficient than dynamic allocation when we can get away with it. For
4186 example, locations |0| to |1| are always used to store a
4187 two-word dummy token whose second word is zero.
4188 The following macro definitions accomplish the static allocation by giving
4189 symbolic names to the fixed positions. Static variable-size nodes appear
4190 in locations |0| through |lo_mem_stat_max|, and static single-word nodes
4191 appear in locations |hi_mem_stat_min| through |mem_top|, inclusive.
4192
4193 @d null_dash (2) /* the first two words are reserved for a null value */
4194 @d dep_head (null_dash+3) /* we will define |dash_node_size=3| */
4195 @d zero_val (dep_head+2) /* two words for a permanently zero value */
4196 @d temp_val (zero_val+2) /* two words for a temporary value node */
4197 @d end_attr temp_val /* we use |end_attr+2| only */
4198 @d inf_val (end_attr+2) /* and |inf_val+1| only */
4199 @d test_pen (inf_val+2)
4200   /* nine words for a pen used when testing the turning number */
4201 @d bad_vardef (test_pen+9) /* two words for \&{vardef} error recovery */
4202 @d lo_mem_stat_max (bad_vardef+1)  /* largest statically
4203   allocated word in the variable-size |mem| */
4204 @#
4205 @d sentinel mp->mem_top /* end of sorted lists */
4206 @d temp_head (mp->mem_top-1) /* head of a temporary list of some kind */
4207 @d hold_head (mp->mem_top-2) /* head of a temporary list of another kind */
4208 @d spec_head (mp->mem_top-3) /* head of a list of unprocessed \&{special} items */
4209 @d hi_mem_stat_min (mp->mem_top-3) /* smallest statically allocated word in
4210   the one-word |mem| */
4211
4212 @ The following code gets the dynamic part of |mem| off to a good start,
4213 when \MP\ is initializing itself the slow way.
4214
4215 @<Initialize table entries (done by \.{INIMP} only)@>=
4216 @^data structure assumptions@>
4217 mp->rover=lo_mem_stat_max+1; /* initialize the dynamic memory */
4218 link(mp->rover)=empty_flag;
4219 node_size(mp->rover)=1000; /* which is a 1000-word available node */
4220 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
4221 mp->lo_mem_max=mp->rover+1000; link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4222 for (k=hi_mem_stat_min;k<=(int)mp->mem_top;k++) {
4223   mp->mem[k]=mp->mem[mp->lo_mem_max]; /* clear list heads */
4224 }
4225 mp->avail=null; mp->mem_end=mp->mem_top;
4226 mp->hi_mem_min=hi_mem_stat_min; /* initialize the one-word memory */
4227 mp->var_used=lo_mem_stat_max+1; 
4228 mp->dyn_used=mp->mem_top+1-(hi_mem_stat_min);  /* initialize statistics */
4229 @<Initialize a pen at |test_pen| so that it fits in nine words@>;
4230
4231 @ The procedure |flush_list(p)| frees an entire linked list of one-word
4232 nodes that starts at a given position, until coming to |sentinel| or a
4233 pointer that is not in the one-word region. Another procedure,
4234 |flush_node_list|, frees an entire linked list of one-word and two-word
4235 nodes, until coming to a |null| pointer.
4236 @^inner loop@>
4237
4238 @c 
4239 void mp_flush_list (MP mp,pointer p) { /* makes list of single-word nodes  available */
4240   pointer q,r; /* list traversers */
4241   if ( p>=mp->hi_mem_min ) if ( p!=sentinel ) { 
4242     r=p;
4243     do {  
4244       q=r; r=link(r); 
4245       decr(mp->dyn_used);
4246       if ( r<mp->hi_mem_min ) break;
4247     } while (r!=sentinel);
4248   /* now |q| is the last node on the list */
4249     link(q)=mp->avail; mp->avail=p;
4250   }
4251 }
4252 @#
4253 void mp_flush_node_list (MP mp,pointer p) {
4254   pointer q; /* the node being recycled */
4255   while ( p!=null ){ 
4256     q=p; p=link(p);
4257     if ( q<mp->hi_mem_min ) 
4258       mp_free_node(mp, q,2);
4259     else 
4260       free_avail(q);
4261   }
4262 }
4263
4264 @ If \MP\ is extended improperly, the |mem| array might get screwed up.
4265 For example, some pointers might be wrong, or some ``dead'' nodes might not
4266 have been freed when the last reference to them disappeared. Procedures
4267 |check_mem| and |search_mem| are available to help diagnose such
4268 problems. These procedures make use of two arrays called |free| and
4269 |was_free| that are present only if \MP's debugging routines have
4270 been included. (You may want to decrease the size of |mem| while you
4271 @^debugging@>
4272 are debugging.)
4273
4274 Because |boolean|s are typedef-d as ints, it is better to use
4275 unsigned chars here.
4276
4277 @<Glob...@>=
4278 unsigned char *free; /* free cells */
4279 unsigned char *was_free; /* previously free cells */
4280 pointer was_mem_end; pointer was_lo_max; pointer was_hi_min;
4281   /* previous |mem_end|, |lo_mem_max|,and |hi_mem_min| */
4282 boolean panicking; /* do we want to check memory constantly? */
4283
4284 @ @<Allocate or initialize ...@>=
4285 mp->free = xmalloc ((mp->mem_max+1),sizeof (unsigned char));
4286 mp->was_free = xmalloc ((mp->mem_max+1), sizeof (unsigned char));
4287
4288 @ @<Dealloc variables@>=
4289 xfree(mp->free);
4290 xfree(mp->was_free);
4291
4292 @ @<Allocate or ...@>=
4293 mp->was_mem_end=0; /* indicate that everything was previously free */
4294 mp->was_lo_max=0; mp->was_hi_min=mp->mem_max;
4295 mp->panicking=false;
4296
4297 @ @<Declare |mp_reallocate| functions@>=
4298 void mp_reallocate_memory(MP mp, int l) ;
4299
4300 @ @c
4301 void mp_reallocate_memory(MP mp, int l) {
4302    XREALLOC(mp->free,     l, unsigned char);
4303    XREALLOC(mp->was_free, l, unsigned char);
4304    if (mp->mem) {
4305          int newarea = l-mp->mem_max;
4306      XREALLOC(mp->mem,      l, memory_word);
4307      memset (mp->mem+(mp->mem_max+1),0,sizeof(memory_word)*(newarea));
4308    } else {
4309      XREALLOC(mp->mem,      l, memory_word);
4310      memset(mp->mem,0,sizeof(memory_word)*(l+1));
4311    }
4312    mp->mem_max = l;
4313    if (mp->ini_version) 
4314      mp->mem_top = l;
4315 }
4316
4317
4318
4319 @ Procedure |check_mem| makes sure that the available space lists of
4320 |mem| are well formed, and it optionally prints out all locations
4321 that are reserved now but were free the last time this procedure was called.
4322
4323 @c 
4324 void mp_check_mem (MP mp,boolean print_locs ) {
4325   pointer p,q,r; /* current locations of interest in |mem| */
4326   boolean clobbered; /* is something amiss? */
4327   for (p=0;p<=mp->lo_mem_max;p++) {
4328     mp->free[p]=false; /* you can probably do this faster */
4329   }
4330   for (p=mp->hi_mem_min;p<= mp->mem_end;p++) {
4331     mp->free[p]=false; /* ditto */
4332   }
4333   @<Check single-word |avail| list@>;
4334   @<Check variable-size |avail| list@>;
4335   @<Check flags of unavailable nodes@>;
4336   @<Check the list of linear dependencies@>;
4337   if ( print_locs ) {
4338     @<Print newly busy locations@>;
4339   }
4340   memcpy(mp->was_free,mp->free, sizeof(char)*(mp->mem_end+1));
4341   mp->was_mem_end=mp->mem_end; 
4342   mp->was_lo_max=mp->lo_mem_max; 
4343   mp->was_hi_min=mp->hi_mem_min;
4344 }
4345
4346 @ @<Check single-word...@>=
4347 p=mp->avail; q=null; clobbered=false;
4348 while ( p!=null ) { 
4349   if ( (p>mp->mem_end)||(p<mp->hi_mem_min) ) clobbered=true;
4350   else if ( mp->free[p] ) clobbered=true;
4351   if ( clobbered ) { 
4352     mp_print_nl(mp, "AVAIL list clobbered at ");
4353 @.AVAIL list clobbered...@>
4354     mp_print_int(mp, q); break;
4355   }
4356   mp->free[p]=true; q=p; p=link(q);
4357 }
4358
4359 @ @<Check variable-size...@>=
4360 p=mp->rover; q=null; clobbered=false;
4361 do {  
4362   if ( (p>=mp->lo_mem_max)||(p<0) ) clobbered=true;
4363   else if ( (rlink(p)>=mp->lo_mem_max)||(rlink(p)<0) ) clobbered=true;
4364   else if (  !(is_empty(p))||(node_size(p)<2)||
4365    (p+node_size(p)>mp->lo_mem_max)|| (llink(rlink(p))!=p) ) clobbered=true;
4366   if ( clobbered ) { 
4367     mp_print_nl(mp, "Double-AVAIL list clobbered at ");
4368 @.Double-AVAIL list clobbered...@>
4369     mp_print_int(mp, q); break;
4370   }
4371   for (q=p;q<=p+node_size(p)-1;q++) { /* mark all locations free */
4372     if ( mp->free[q] ) { 
4373       mp_print_nl(mp, "Doubly free location at ");
4374 @.Doubly free location...@>
4375       mp_print_int(mp, q); break;
4376     }
4377     mp->free[q]=true;
4378   }
4379   q=p; p=rlink(p);
4380 } while (p!=mp->rover)
4381
4382
4383 @ @<Check flags...@>=
4384 p=0;
4385 while ( p<=mp->lo_mem_max ) { /* node |p| should not be empty */
4386   if ( is_empty(p) ) {
4387     mp_print_nl(mp, "Bad flag at "); mp_print_int(mp, p);
4388 @.Bad flag...@>
4389   }
4390   while ( (p<=mp->lo_mem_max) && ! mp->free[p] ) incr(p);
4391   while ( (p<=mp->lo_mem_max) && mp->free[p] ) incr(p);
4392 }
4393
4394 @ @<Print newly busy...@>=
4395
4396   @<Do intialization required before printing new busy locations@>;
4397   mp_print_nl(mp, "New busy locs:");
4398 @.New busy locs@>
4399   for (p=0;p<= mp->lo_mem_max;p++ ) {
4400     if ( ! mp->free[p] && ((p>mp->was_lo_max) || mp->was_free[p]) ) {
4401       @<Indicate that |p| is a new busy location@>;
4402     }
4403   }
4404   for (p=mp->hi_mem_min;p<=mp->mem_end;p++ ) {
4405     if ( ! mp->free[p] &&
4406         ((p<mp->was_hi_min) || (p>mp->was_mem_end) || mp->was_free[p]) ) {
4407       @<Indicate that |p| is a new busy location@>;
4408     }
4409   }
4410   @<Finish printing new busy locations@>;
4411 }
4412
4413 @ There might be many new busy locations so we are careful to print contiguous
4414 blocks compactly.  During this operation |q| is the last new busy location and
4415 |r| is the start of the block containing |q|.
4416
4417 @<Indicate that |p| is a new busy location@>=
4418
4419   if ( p>q+1 ) { 
4420     if ( q>r ) { 
4421       mp_print(mp, ".."); mp_print_int(mp, q);
4422     }
4423     mp_print_char(mp, ' '); mp_print_int(mp, p);
4424     r=p;
4425   }
4426   q=p;
4427 }
4428
4429 @ @<Do intialization required before printing new busy locations@>=
4430 q=mp->mem_max; r=mp->mem_max
4431
4432 @ @<Finish printing new busy locations@>=
4433 if ( q>r ) { 
4434   mp_print(mp, ".."); mp_print_int(mp, q);
4435 }
4436
4437 @ The |search_mem| procedure attempts to answer the question ``Who points
4438 to node~|p|?'' In doing so, it fetches |link| and |info| fields of |mem|
4439 that might not be of type |two_halves|. Strictly speaking, this is
4440 @^dirty \PASCAL@>
4441 undefined in \PASCAL, and it can lead to ``false drops'' (words that seem to
4442 point to |p| purely by coincidence). But for debugging purposes, we want
4443 to rule out the places that do {\sl not\/} point to |p|, so a few false
4444 drops are tolerable.
4445
4446 @c
4447 void mp_search_mem (MP mp, pointer p) { /* look for pointers to |p| */
4448   integer q; /* current position being searched */
4449   for (q=0;q<=mp->lo_mem_max;q++) { 
4450     if ( link(q)==p ){ 
4451       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4452     }
4453     if ( info(q)==p ) { 
4454       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4455     }
4456   }
4457   for (q=mp->hi_mem_min;q<=mp->mem_end;q++) {
4458     if ( link(q)==p ) {
4459       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4460     }
4461     if ( info(q)==p ) {
4462       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4463     }
4464   }
4465   @<Search |eqtb| for equivalents equal to |p|@>;
4466 }
4467
4468 @* \[12] The command codes.
4469 Before we can go much further, we need to define symbolic names for the internal
4470 code numbers that represent the various commands obeyed by \MP. These codes
4471 are somewhat arbitrary, but not completely so. For example,
4472 some codes have been made adjacent so that |case| statements in the
4473 program need not consider cases that are widely spaced, or so that |case|
4474 statements can be replaced by |if| statements. A command can begin an
4475 expression if and only if its code lies between |min_primary_command| and
4476 |max_primary_command|, inclusive. The first token of a statement that doesn't
4477 begin with an expression has a command code between |min_command| and
4478 |max_statement_command|, inclusive. Anything less than |min_command| is
4479 eliminated during macro expansions, and anything no more than |max_pre_command|
4480 is eliminated when expanding \TeX\ material.  Ranges such as
4481 |min_secondary_command..max_secondary_command| are used when parsing
4482 expressions, but the relative ordering within such a range is generally not
4483 critical.
4484
4485 The ordering of the highest-numbered commands
4486 (|comma<semicolon<end_group<stop|) is crucial for the parsing and
4487 error-recovery methods of this program as is the ordering |if_test<fi_or_else|
4488 for the smallest two commands.  The ordering is also important in the ranges
4489 |numeric_token..plus_or_minus| and |left_brace..ampersand|.
4490
4491 At any rate, here is the list, for future reference.
4492
4493 @d start_tex 1 /* begin \TeX\ material (\&{btex}, \&{verbatimtex}) */
4494 @d etex_marker 2 /* end \TeX\ material (\&{etex}) */
4495 @d mpx_break 3 /* stop reading an \.{MPX} file (\&{mpxbreak}) */
4496 @d max_pre_command mpx_break
4497 @d if_test 4 /* conditional text (\&{if}) */
4498 @d fi_or_else 5 /* delimiters for conditionals (\&{elseif}, \&{else}, \&{fi} */
4499 @d input 6 /* input a source file (\&{input}, \&{endinput}) */
4500 @d iteration 7 /* iterate (\&{for}, \&{forsuffixes}, \&{forever}, \&{endfor}) */
4501 @d repeat_loop 8 /* special command substituted for \&{endfor} */
4502 @d exit_test 9 /* premature exit from a loop (\&{exitif}) */
4503 @d relax 10 /* do nothing (\.{\char`\\}) */
4504 @d scan_tokens 11 /* put a string into the input buffer */
4505 @d expand_after 12 /* look ahead one token */
4506 @d defined_macro 13 /* a macro defined by the user */
4507 @d min_command (defined_macro+1)
4508 @d save_command 14 /* save a list of tokens (\&{save}) */
4509 @d interim_command 15 /* save an internal quantity (\&{interim}) */
4510 @d let_command 16 /* redefine a symbolic token (\&{let}) */
4511 @d new_internal 17 /* define a new internal quantity (\&{newinternal}) */
4512 @d macro_def 18 /* define a macro (\&{def}, \&{vardef}, etc.) */
4513 @d ship_out_command 19 /* output a character (\&{shipout}) */
4514 @d add_to_command 20 /* add to edges (\&{addto}) */
4515 @d bounds_command 21  /* add bounding path to edges (\&{setbounds}, \&{clip}) */
4516 @d tfm_command 22 /* command for font metric info (\&{ligtable}, etc.) */
4517 @d protection_command 23 /* set protection flag (\&{outer}, \&{inner}) */
4518 @d show_command 24 /* diagnostic output (\&{show}, \&{showvariable}, etc.) */
4519 @d mode_command 25 /* set interaction level (\&{batchmode}, etc.) */
4520 @d random_seed 26 /* initialize random number generator (\&{randomseed}) */
4521 @d message_command 27 /* communicate to user (\&{message}, \&{errmessage}) */
4522 @d every_job_command 28 /* designate a starting token (\&{everyjob}) */
4523 @d delimiters 29 /* define a pair of delimiters (\&{delimiters}) */
4524 @d special_command 30 /* output special info (\&{special})
4525                        or font map info (\&{fontmapfile}, \&{fontmapline}) */
4526 @d write_command 31 /* write text to a file (\&{write}) */
4527 @d type_name 32 /* declare a type (\&{numeric}, \&{pair}, etc. */
4528 @d max_statement_command type_name
4529 @d min_primary_command type_name
4530 @d left_delimiter 33 /* the left delimiter of a matching pair */
4531 @d begin_group 34 /* beginning of a group (\&{begingroup}) */
4532 @d nullary 35 /* an operator without arguments (e.g., \&{normaldeviate}) */
4533 @d unary 36 /* an operator with one argument (e.g., \&{sqrt}) */
4534 @d str_op 37 /* convert a suffix to a string (\&{str}) */
4535 @d cycle 38 /* close a cyclic path (\&{cycle}) */
4536 @d primary_binary 39 /* binary operation taking `\&{of}' (e.g., \&{point}) */
4537 @d capsule_token 40 /* a value that has been put into a token list */
4538 @d string_token 41 /* a string constant (e.g., |"hello"|) */
4539 @d internal_quantity 42 /* internal numeric parameter (e.g., \&{pausing}) */
4540 @d min_suffix_token internal_quantity
4541 @d tag_token 43 /* a symbolic token without a primitive meaning */
4542 @d numeric_token 44 /* a numeric constant (e.g., \.{3.14159}) */
4543 @d max_suffix_token numeric_token
4544 @d plus_or_minus 45 /* either `\.+' or `\.-' */
4545 @d max_primary_command plus_or_minus /* should also be |numeric_token+1| */
4546 @d min_tertiary_command plus_or_minus
4547 @d tertiary_secondary_macro 46 /* a macro defined by \&{secondarydef} */
4548 @d tertiary_binary 47 /* an operator at the tertiary level (e.g., `\.{++}') */
4549 @d max_tertiary_command tertiary_binary
4550 @d left_brace 48 /* the operator `\.{\char`\{}' */
4551 @d min_expression_command left_brace
4552 @d path_join 49 /* the operator `\.{..}' */
4553 @d ampersand 50 /* the operator `\.\&' */
4554 @d expression_tertiary_macro 51 /* a macro defined by \&{tertiarydef} */
4555 @d expression_binary 52 /* an operator at the expression level (e.g., `\.<') */
4556 @d equals 53 /* the operator `\.=' */
4557 @d max_expression_command equals
4558 @d and_command 54 /* the operator `\&{and}' */
4559 @d min_secondary_command and_command
4560 @d secondary_primary_macro 55 /* a macro defined by \&{primarydef} */
4561 @d slash 56 /* the operator `\./' */
4562 @d secondary_binary 57 /* an operator at the binary level (e.g., \&{shifted}) */
4563 @d max_secondary_command secondary_binary
4564 @d param_type 58 /* type of parameter (\&{primary}, \&{expr}, \&{suffix}, etc.) */
4565 @d controls 59 /* specify control points explicitly (\&{controls}) */
4566 @d tension 60 /* specify tension between knots (\&{tension}) */
4567 @d at_least 61 /* bounded tension value (\&{atleast}) */
4568 @d curl_command 62 /* specify curl at an end knot (\&{curl}) */
4569 @d macro_special 63 /* special macro operators (\&{quote}, \.{\#\AT!}, etc.) */
4570 @d right_delimiter 64 /* the right delimiter of a matching pair */
4571 @d left_bracket 65 /* the operator `\.[' */
4572 @d right_bracket 66 /* the operator `\.]' */
4573 @d right_brace 67 /* the operator `\.{\char`\}}' */
4574 @d with_option 68 /* option for filling (\&{withpen}, \&{withweight}, etc.) */
4575 @d thing_to_add 69
4576   /* variant of \&{addto} (\&{contour}, \&{doublepath}, \&{also}) */
4577 @d of_token 70 /* the operator `\&{of}' */
4578 @d to_token 71 /* the operator `\&{to}' */
4579 @d step_token 72 /* the operator `\&{step}' */
4580 @d until_token 73 /* the operator `\&{until}' */
4581 @d within_token 74 /* the operator `\&{within}' */
4582 @d lig_kern_token 75
4583   /* the operators `\&{kern}' and `\.{=:}' and `\.{=:\char'174}, etc. */
4584 @d assignment 76 /* the operator `\.{:=}' */
4585 @d skip_to 77 /* the operation `\&{skipto}' */
4586 @d bchar_label 78 /* the operator `\.{\char'174\char'174:}' */
4587 @d double_colon 79 /* the operator `\.{::}' */
4588 @d colon 80 /* the operator `\.:' */
4589 @#
4590 @d comma 81 /* the operator `\.,', must be |colon+1| */
4591 @d end_of_statement (mp->cur_cmd>comma)
4592 @d semicolon 82 /* the operator `\.;', must be |comma+1| */
4593 @d end_group 83 /* end a group (\&{endgroup}), must be |semicolon+1| */
4594 @d stop 84 /* end a job (\&{end}, \&{dump}), must be |end_group+1| */
4595 @d max_command_code stop
4596 @d outer_tag (max_command_code+1) /* protection code added to command code */
4597
4598 @<Types...@>=
4599 typedef int command_code;
4600
4601 @ Variables and capsules in \MP\ have a variety of ``types,''
4602 distinguished by the code numbers defined here. These numbers are also
4603 not completely arbitrary.  Things that get expanded must have types
4604 |>mp_independent|; a type remaining after expansion is numeric if and only if
4605 its code number is at least |numeric_type|; objects containing numeric
4606 parts must have types between |transform_type| and |pair_type|;
4607 all other types must be smaller than |transform_type|; and among the types
4608 that are not unknown or vacuous, the smallest two must be |boolean_type|
4609 and |string_type| in that order.
4610  
4611 @d undefined 0 /* no type has been declared */
4612 @d unknown_tag 1 /* this constant is added to certain type codes below */
4613 @d unknown_types mp_unknown_boolean: case mp_unknown_string:
4614   case mp_unknown_pen: case mp_unknown_picture: case mp_unknown_path
4615
4616 @<Types...@>=
4617 enum mp_variable_type {
4618 mp_vacuous=1, /* no expression was present */
4619 mp_boolean_type, /* \&{boolean} with a known value */
4620 mp_unknown_boolean,
4621 mp_string_type, /* \&{string} with a known value */
4622 mp_unknown_string,
4623 mp_pen_type, /* \&{pen} with a known value */
4624 mp_unknown_pen,
4625 mp_path_type, /* \&{path} with a known value */
4626 mp_unknown_path,
4627 mp_picture_type, /* \&{picture} with a known value */
4628 mp_unknown_picture,
4629 mp_transform_type, /* \&{transform} variable or capsule */
4630 mp_color_type, /* \&{color} variable or capsule */
4631 mp_cmykcolor_type, /* \&{cmykcolor} variable or capsule */
4632 mp_pair_type, /* \&{pair} variable or capsule */
4633 mp_numeric_type, /* variable that has been declared \&{numeric} but not used */
4634 mp_known, /* \&{numeric} with a known value */
4635 mp_dependent, /* a linear combination with |fraction| coefficients */
4636 mp_proto_dependent, /* a linear combination with |scaled| coefficients */
4637 mp_independent, /* \&{numeric} with unknown value */
4638 mp_token_list, /* variable name or suffix argument or text argument */
4639 mp_structured, /* variable with subscripts and attributes */
4640 mp_unsuffixed_macro, /* variable defined with \&{vardef} but no \.{\AT!\#} */
4641 mp_suffixed_macro /* variable defined with \&{vardef} and \.{\AT!\#} */
4642 } ;
4643
4644 @ @<Declarations@>=
4645 void mp_print_type (MP mp,small_number t) ;
4646
4647 @ @<Basic printing procedures@>=
4648 void mp_print_type (MP mp,small_number t) { 
4649   switch (t) {
4650   case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
4651   case mp_boolean_type:mp_print(mp, "boolean"); break;
4652   case mp_unknown_boolean:mp_print(mp, "unknown boolean"); break;
4653   case mp_string_type:mp_print(mp, "string"); break;
4654   case mp_unknown_string:mp_print(mp, "unknown string"); break;
4655   case mp_pen_type:mp_print(mp, "pen"); break;
4656   case mp_unknown_pen:mp_print(mp, "unknown pen"); break;
4657   case mp_path_type:mp_print(mp, "path"); break;
4658   case mp_unknown_path:mp_print(mp, "unknown path"); break;
4659   case mp_picture_type:mp_print(mp, "picture"); break;
4660   case mp_unknown_picture:mp_print(mp, "unknown picture"); break;
4661   case mp_transform_type:mp_print(mp, "transform"); break;
4662   case mp_color_type:mp_print(mp, "color"); break;
4663   case mp_cmykcolor_type:mp_print(mp, "cmykcolor"); break;
4664   case mp_pair_type:mp_print(mp, "pair"); break;
4665   case mp_known:mp_print(mp, "known numeric"); break;
4666   case mp_dependent:mp_print(mp, "dependent"); break;
4667   case mp_proto_dependent:mp_print(mp, "proto-dependent"); break;
4668   case mp_numeric_type:mp_print(mp, "numeric"); break;
4669   case mp_independent:mp_print(mp, "independent"); break;
4670   case mp_token_list:mp_print(mp, "token list"); break;
4671   case mp_structured:mp_print(mp, "mp_structured"); break;
4672   case mp_unsuffixed_macro:mp_print(mp, "unsuffixed macro"); break;
4673   case mp_suffixed_macro:mp_print(mp, "suffixed macro"); break;
4674   default: mp_print(mp, "undefined"); break;
4675   }
4676 }
4677
4678 @ Values inside \MP\ are stored in two-word nodes that have a |name_type|
4679 as well as a |type|. The possibilities for |name_type| are defined
4680 here; they will be explained in more detail later.
4681
4682 @<Types...@>=
4683 enum mp_name_type {
4684  mp_root=0, /* |name_type| at the top level of a variable */
4685  mp_saved_root, /* same, when the variable has been saved */
4686  mp_structured_root, /* |name_type| where a |mp_structured| branch occurs */
4687  mp_subscr, /* |name_type| in a subscript node */
4688  mp_attr, /* |name_type| in an attribute node */
4689  mp_x_part_sector, /* |name_type| in the \&{xpart} of a node */
4690  mp_y_part_sector, /* |name_type| in the \&{ypart} of a node */
4691  mp_xx_part_sector, /* |name_type| in the \&{xxpart} of a node */
4692  mp_xy_part_sector, /* |name_type| in the \&{xypart} of a node */
4693  mp_yx_part_sector, /* |name_type| in the \&{yxpart} of a node */
4694  mp_yy_part_sector, /* |name_type| in the \&{yypart} of a node */
4695  mp_red_part_sector, /* |name_type| in the \&{redpart} of a node */
4696  mp_green_part_sector, /* |name_type| in the \&{greenpart} of a node */
4697  mp_blue_part_sector, /* |name_type| in the \&{bluepart} of a node */
4698  mp_cyan_part_sector, /* |name_type| in the \&{redpart} of a node */
4699  mp_magenta_part_sector, /* |name_type| in the \&{greenpart} of a node */
4700  mp_yellow_part_sector, /* |name_type| in the \&{bluepart} of a node */
4701  mp_black_part_sector, /* |name_type| in the \&{greenpart} of a node */
4702  mp_grey_part_sector, /* |name_type| in the \&{bluepart} of a node */
4703  mp_capsule, /* |name_type| in stashed-away subexpressions */
4704  mp_token  /* |name_type| in a numeric token or string token */
4705 };
4706
4707 @ Primitive operations that produce values have a secondary identification
4708 code in addition to their command code; it's something like genera and species.
4709 For example, `\.*' has the command code |primary_binary|, and its
4710 secondary identification is |times|. The secondary codes start at 30 so that
4711 they don't overlap with the type codes; some type codes (e.g., |mp_string_type|)
4712 are used as operators as well as type identifications.  The relative values
4713 are not critical, except for |true_code..false_code|, |or_op..and_op|,
4714 and |filled_op..bounded_op|.  The restrictions are that
4715 |and_op-false_code=or_op-true_code|, that the ordering of
4716 |x_part...blue_part| must match that of |x_part_sector..mp_blue_part_sector|,
4717 and the ordering of |filled_op..bounded_op| must match that of the code
4718 values they test for.
4719
4720 @d true_code 30 /* operation code for \.{true} */
4721 @d false_code 31 /* operation code for \.{false} */
4722 @d null_picture_code 32 /* operation code for \.{nullpicture} */
4723 @d null_pen_code 33 /* operation code for \.{nullpen} */
4724 @d job_name_op 34 /* operation code for \.{jobname} */
4725 @d read_string_op 35 /* operation code for \.{readstring} */
4726 @d pen_circle 36 /* operation code for \.{pencircle} */
4727 @d normal_deviate 37 /* operation code for \.{normaldeviate} */
4728 @d read_from_op 38 /* operation code for \.{readfrom} */
4729 @d close_from_op 39 /* operation code for \.{closefrom} */
4730 @d odd_op 40 /* operation code for \.{odd} */
4731 @d known_op 41 /* operation code for \.{known} */
4732 @d unknown_op 42 /* operation code for \.{unknown} */
4733 @d not_op 43 /* operation code for \.{not} */
4734 @d decimal 44 /* operation code for \.{decimal} */
4735 @d reverse 45 /* operation code for \.{reverse} */
4736 @d make_path_op 46 /* operation code for \.{makepath} */
4737 @d make_pen_op 47 /* operation code for \.{makepen} */
4738 @d oct_op 48 /* operation code for \.{oct} */
4739 @d hex_op 49 /* operation code for \.{hex} */
4740 @d ASCII_op 50 /* operation code for \.{ASCII} */
4741 @d char_op 51 /* operation code for \.{char} */
4742 @d length_op 52 /* operation code for \.{length} */
4743 @d turning_op 53 /* operation code for \.{turningnumber} */
4744 @d color_model_part 54 /* operation code for \.{colormodel} */
4745 @d x_part 55 /* operation code for \.{xpart} */
4746 @d y_part 56 /* operation code for \.{ypart} */
4747 @d xx_part 57 /* operation code for \.{xxpart} */
4748 @d xy_part 58 /* operation code for \.{xypart} */
4749 @d yx_part 59 /* operation code for \.{yxpart} */
4750 @d yy_part 60 /* operation code for \.{yypart} */
4751 @d red_part 61 /* operation code for \.{redpart} */
4752 @d green_part 62 /* operation code for \.{greenpart} */
4753 @d blue_part 63 /* operation code for \.{bluepart} */
4754 @d cyan_part 64 /* operation code for \.{cyanpart} */
4755 @d magenta_part 65 /* operation code for \.{magentapart} */
4756 @d yellow_part 66 /* operation code for \.{yellowpart} */
4757 @d black_part 67 /* operation code for \.{blackpart} */
4758 @d grey_part 68 /* operation code for \.{greypart} */
4759 @d font_part 69 /* operation code for \.{fontpart} */
4760 @d text_part 70 /* operation code for \.{textpart} */
4761 @d path_part 71 /* operation code for \.{pathpart} */
4762 @d pen_part 72 /* operation code for \.{penpart} */
4763 @d dash_part 73 /* operation code for \.{dashpart} */
4764 @d sqrt_op 74 /* operation code for \.{sqrt} */
4765 @d m_exp_op 75 /* operation code for \.{mexp} */
4766 @d m_log_op 76 /* operation code for \.{mlog} */
4767 @d sin_d_op 77 /* operation code for \.{sind} */
4768 @d cos_d_op 78 /* operation code for \.{cosd} */
4769 @d floor_op 79 /* operation code for \.{floor} */
4770 @d uniform_deviate 80 /* operation code for \.{uniformdeviate} */
4771 @d char_exists_op 81 /* operation code for \.{charexists} */
4772 @d font_size 82 /* operation code for \.{fontsize} */
4773 @d ll_corner_op 83 /* operation code for \.{llcorner} */
4774 @d lr_corner_op 84 /* operation code for \.{lrcorner} */
4775 @d ul_corner_op 85 /* operation code for \.{ulcorner} */
4776 @d ur_corner_op 86 /* operation code for \.{urcorner} */
4777 @d arc_length 87 /* operation code for \.{arclength} */
4778 @d angle_op 88 /* operation code for \.{angle} */
4779 @d cycle_op 89 /* operation code for \.{cycle} */
4780 @d filled_op 90 /* operation code for \.{filled} */
4781 @d stroked_op 91 /* operation code for \.{stroked} */
4782 @d textual_op 92 /* operation code for \.{textual} */
4783 @d clipped_op 93 /* operation code for \.{clipped} */
4784 @d bounded_op 94 /* operation code for \.{bounded} */
4785 @d plus 95 /* operation code for \.+ */
4786 @d minus 96 /* operation code for \.- */
4787 @d times 97 /* operation code for \.* */
4788 @d over 98 /* operation code for \./ */
4789 @d pythag_add 99 /* operation code for \.{++} */
4790 @d pythag_sub 100 /* operation code for \.{+-+} */
4791 @d or_op 101 /* operation code for \.{or} */
4792 @d and_op 102 /* operation code for \.{and} */
4793 @d less_than 103 /* operation code for \.< */
4794 @d less_or_equal 104 /* operation code for \.{<=} */
4795 @d greater_than 105 /* operation code for \.> */
4796 @d greater_or_equal 106 /* operation code for \.{>=} */
4797 @d equal_to 107 /* operation code for \.= */
4798 @d unequal_to 108 /* operation code for \.{<>} */
4799 @d concatenate 109 /* operation code for \.\& */
4800 @d rotated_by 110 /* operation code for \.{rotated} */
4801 @d slanted_by 111 /* operation code for \.{slanted} */
4802 @d scaled_by 112 /* operation code for \.{scaled} */
4803 @d shifted_by 113 /* operation code for \.{shifted} */
4804 @d transformed_by 114 /* operation code for \.{transformed} */
4805 @d x_scaled 115 /* operation code for \.{xscaled} */
4806 @d y_scaled 116 /* operation code for \.{yscaled} */
4807 @d z_scaled 117 /* operation code for \.{zscaled} */
4808 @d in_font 118 /* operation code for \.{infont} */
4809 @d intersect 119 /* operation code for \.{intersectiontimes} */
4810 @d double_dot 120 /* operation code for improper \.{..} */
4811 @d substring_of 121 /* operation code for \.{substring} */
4812 @d min_of substring_of
4813 @d subpath_of 122 /* operation code for \.{subpath} */
4814 @d direction_time_of 123 /* operation code for \.{directiontime} */
4815 @d point_of 124 /* operation code for \.{point} */
4816 @d precontrol_of 125 /* operation code for \.{precontrol} */
4817 @d postcontrol_of 126 /* operation code for \.{postcontrol} */
4818 @d pen_offset_of 127 /* operation code for \.{penoffset} */
4819 @d arc_time_of 128 /* operation code for \.{arctime} */
4820 @d mp_version 129 /* operation code for \.{mpversion} */
4821
4822 @c void mp_print_op (MP mp,quarterword c) { 
4823   if (c<=mp_numeric_type ) {
4824     mp_print_type(mp, c);
4825   } else {
4826     switch (c) {
4827     case true_code:mp_print(mp, "true"); break;
4828     case false_code:mp_print(mp, "false"); break;
4829     case null_picture_code:mp_print(mp, "nullpicture"); break;
4830     case null_pen_code:mp_print(mp, "nullpen"); break;
4831     case job_name_op:mp_print(mp, "jobname"); break;
4832     case read_string_op:mp_print(mp, "readstring"); break;
4833     case pen_circle:mp_print(mp, "pencircle"); break;
4834     case normal_deviate:mp_print(mp, "normaldeviate"); break;
4835     case read_from_op:mp_print(mp, "readfrom"); break;
4836     case close_from_op:mp_print(mp, "closefrom"); break;
4837     case odd_op:mp_print(mp, "odd"); break;
4838     case known_op:mp_print(mp, "known"); break;
4839     case unknown_op:mp_print(mp, "unknown"); break;
4840     case not_op:mp_print(mp, "not"); break;
4841     case decimal:mp_print(mp, "decimal"); break;
4842     case reverse:mp_print(mp, "reverse"); break;
4843     case make_path_op:mp_print(mp, "makepath"); break;
4844     case make_pen_op:mp_print(mp, "makepen"); break;
4845     case oct_op:mp_print(mp, "oct"); break;
4846     case hex_op:mp_print(mp, "hex"); break;
4847     case ASCII_op:mp_print(mp, "ASCII"); break;
4848     case char_op:mp_print(mp, "char"); break;
4849     case length_op:mp_print(mp, "length"); break;
4850     case turning_op:mp_print(mp, "turningnumber"); break;
4851     case x_part:mp_print(mp, "xpart"); break;
4852     case y_part:mp_print(mp, "ypart"); break;
4853     case xx_part:mp_print(mp, "xxpart"); break;
4854     case xy_part:mp_print(mp, "xypart"); break;
4855     case yx_part:mp_print(mp, "yxpart"); break;
4856     case yy_part:mp_print(mp, "yypart"); break;
4857     case red_part:mp_print(mp, "redpart"); break;
4858     case green_part:mp_print(mp, "greenpart"); break;
4859     case blue_part:mp_print(mp, "bluepart"); break;
4860     case cyan_part:mp_print(mp, "cyanpart"); break;
4861     case magenta_part:mp_print(mp, "magentapart"); break;
4862     case yellow_part:mp_print(mp, "yellowpart"); break;
4863     case black_part:mp_print(mp, "blackpart"); break;
4864     case grey_part:mp_print(mp, "greypart"); break;
4865     case color_model_part:mp_print(mp, "colormodel"); break;
4866     case font_part:mp_print(mp, "fontpart"); break;
4867     case text_part:mp_print(mp, "textpart"); break;
4868     case path_part:mp_print(mp, "pathpart"); break;
4869     case pen_part:mp_print(mp, "penpart"); break;
4870     case dash_part:mp_print(mp, "dashpart"); break;
4871     case sqrt_op:mp_print(mp, "sqrt"); break;
4872     case m_exp_op:mp_print(mp, "mexp"); break;
4873     case m_log_op:mp_print(mp, "mlog"); break;
4874     case sin_d_op:mp_print(mp, "sind"); break;
4875     case cos_d_op:mp_print(mp, "cosd"); break;
4876     case floor_op:mp_print(mp, "floor"); break;
4877     case uniform_deviate:mp_print(mp, "uniformdeviate"); break;
4878     case char_exists_op:mp_print(mp, "charexists"); break;
4879     case font_size:mp_print(mp, "fontsize"); break;
4880     case ll_corner_op:mp_print(mp, "llcorner"); break;
4881     case lr_corner_op:mp_print(mp, "lrcorner"); break;
4882     case ul_corner_op:mp_print(mp, "ulcorner"); break;
4883     case ur_corner_op:mp_print(mp, "urcorner"); break;
4884     case arc_length:mp_print(mp, "arclength"); break;
4885     case angle_op:mp_print(mp, "angle"); break;
4886     case cycle_op:mp_print(mp, "cycle"); break;
4887     case filled_op:mp_print(mp, "filled"); break;
4888     case stroked_op:mp_print(mp, "stroked"); break;
4889     case textual_op:mp_print(mp, "textual"); break;
4890     case clipped_op:mp_print(mp, "clipped"); break;
4891     case bounded_op:mp_print(mp, "bounded"); break;
4892     case plus:mp_print_char(mp, '+'); break;
4893     case minus:mp_print_char(mp, '-'); break;
4894     case times:mp_print_char(mp, '*'); break;
4895     case over:mp_print_char(mp, '/'); break;
4896     case pythag_add:mp_print(mp, "++"); break;
4897     case pythag_sub:mp_print(mp, "+-+"); break;
4898     case or_op:mp_print(mp, "or"); break;
4899     case and_op:mp_print(mp, "and"); break;
4900     case less_than:mp_print_char(mp, '<'); break;
4901     case less_or_equal:mp_print(mp, "<="); break;
4902     case greater_than:mp_print_char(mp, '>'); break;
4903     case greater_or_equal:mp_print(mp, ">="); break;
4904     case equal_to:mp_print_char(mp, '='); break;
4905     case unequal_to:mp_print(mp, "<>"); break;
4906     case concatenate:mp_print(mp, "&"); break;
4907     case rotated_by:mp_print(mp, "rotated"); break;
4908     case slanted_by:mp_print(mp, "slanted"); break;
4909     case scaled_by:mp_print(mp, "scaled"); break;
4910     case shifted_by:mp_print(mp, "shifted"); break;
4911     case transformed_by:mp_print(mp, "transformed"); break;
4912     case x_scaled:mp_print(mp, "xscaled"); break;
4913     case y_scaled:mp_print(mp, "yscaled"); break;
4914     case z_scaled:mp_print(mp, "zscaled"); break;
4915     case in_font:mp_print(mp, "infont"); break;
4916     case intersect:mp_print(mp, "intersectiontimes"); break;
4917     case substring_of:mp_print(mp, "substring"); break;
4918     case subpath_of:mp_print(mp, "subpath"); break;
4919     case direction_time_of:mp_print(mp, "directiontime"); break;
4920     case point_of:mp_print(mp, "point"); break;
4921     case precontrol_of:mp_print(mp, "precontrol"); break;
4922     case postcontrol_of:mp_print(mp, "postcontrol"); break;
4923     case pen_offset_of:mp_print(mp, "penoffset"); break;
4924     case arc_time_of:mp_print(mp, "arctime"); break;
4925     case mp_version:mp_print(mp, "mpversion"); break;
4926     default: mp_print(mp, ".."); break;
4927     }
4928   }
4929 }
4930
4931 @ \MP\ also has a bunch of internal parameters that a user might want to
4932 fuss with. Every such parameter has an identifying code number, defined here.
4933
4934 @<Types...@>=
4935 enum mp_given_internal {
4936   mp_tracing_titles=1, /* show titles online when they appear */
4937   mp_tracing_equations, /* show each variable when it becomes known */
4938   mp_tracing_capsules, /* show capsules too */
4939   mp_tracing_choices, /* show the control points chosen for paths */
4940   mp_tracing_specs, /* show path subdivision prior to filling with polygonal a pen */
4941   mp_tracing_commands, /* show commands and operations before they are performed */
4942   mp_tracing_restores, /* show when a variable or internal is restored */
4943   mp_tracing_macros, /* show macros before they are expanded */
4944   mp_tracing_output, /* show digitized edges as they are output */
4945   mp_tracing_stats, /* show memory usage at end of job */
4946   mp_tracing_lost_chars, /* show characters that aren't \&{infont} */
4947   mp_tracing_online, /* show long diagnostics on terminal and in the log file */
4948   mp_year, /* the current year (e.g., 1984) */
4949   mp_month, /* the current month (e.g, 3 $\equiv$ March) */
4950   mp_day, /* the current day of the month */
4951   mp_time, /* the number of minutes past midnight when this job started */
4952   mp_char_code, /* the number of the next character to be output */
4953   mp_char_ext, /* the extension code of the next character to be output */
4954   mp_char_wd, /* the width of the next character to be output */
4955   mp_char_ht, /* the height of the next character to be output */
4956   mp_char_dp, /* the depth of the next character to be output */
4957   mp_char_ic, /* the italic correction of the next character to be output */
4958   mp_design_size, /* the unit of measure used for |mp_char_wd..mp_char_ic|, in points */
4959   mp_pausing, /* positive to display lines on the terminal before they are read */
4960   mp_showstopping, /* positive to stop after each \&{show} command */
4961   mp_fontmaking, /* positive if font metric output is to be produced */
4962   mp_linejoin, /* as in \ps: 0 for mitered, 1 for round, 2 for beveled */
4963   mp_linecap, /* as in \ps: 0 for butt, 1 for round, 2 for square */
4964   mp_miterlimit, /* controls miter length as in \ps */
4965   mp_warning_check, /* controls error message when variable value is large */
4966   mp_boundary_char, /* the right boundary character for ligatures */
4967   mp_prologues, /* positive to output conforming PostScript using built-in fonts */
4968   mp_true_corners, /* positive to make \&{llcorner} etc. ignore \&{setbounds} */
4969   mp_default_color_model, /* the default color model for unspecified items */
4970   mp_restore_clip_color,
4971   mp_procset, /* wether or not create PostScript command shortcuts */
4972   mp_gtroffmode,  /* whether the user specified |-troff| on the command line */
4973 };
4974
4975 @
4976
4977 @d max_given_internal mp_gtroffmode
4978
4979 @<Glob...@>=
4980 scaled *internal;  /* the values of internal quantities */
4981 char **int_name;  /* their names */
4982 int int_ptr;  /* the maximum internal quantity defined so far */
4983 int max_internal; /* current maximum number of internal quantities */
4984 boolean troff_mode; 
4985
4986 @ @<Option variables@>=
4987 int troff_mode; 
4988
4989 @ @<Allocate or initialize ...@>=
4990 mp->max_internal=2*max_given_internal;
4991 mp->internal = xmalloc ((mp->max_internal+1), sizeof(scaled));
4992 mp->int_name = xmalloc ((mp->max_internal+1), sizeof(char *));
4993 mp->troff_mode=(opt->troff_mode>0 ? true : false);
4994
4995 @ @<Exported function ...@>=
4996 int mp_troff_mode(MP mp);
4997
4998 @ @c
4999 int mp_troff_mode(MP mp) { return mp->troff_mode; }
5000
5001 @ @<Set initial ...@>=
5002 for (k=0;k<= mp->max_internal; k++ ) { 
5003    mp->internal[k]=0; 
5004    mp->int_name[k]=NULL; 
5005 }
5006 mp->int_ptr=max_given_internal;
5007
5008 @ The symbolic names for internal quantities are put into \MP's hash table
5009 by using a routine called |primitive|, which will be defined later. Let us
5010 enter them now, so that we don't have to list all those names again
5011 anywhere else.
5012
5013 @<Put each of \MP's primitives into the hash table@>=
5014 mp_primitive(mp, "tracingtitles",internal_quantity,mp_tracing_titles);
5015 @:tracingtitles_}{\&{tracingtitles} primitive@>
5016 mp_primitive(mp, "tracingequations",internal_quantity,mp_tracing_equations);
5017 @:mp_tracing_equations_}{\&{tracingequations} primitive@>
5018 mp_primitive(mp, "tracingcapsules",internal_quantity,mp_tracing_capsules);
5019 @:mp_tracing_capsules_}{\&{tracingcapsules} primitive@>
5020 mp_primitive(mp, "tracingchoices",internal_quantity,mp_tracing_choices);
5021 @:mp_tracing_choices_}{\&{tracingchoices} primitive@>
5022 mp_primitive(mp, "tracingspecs",internal_quantity,mp_tracing_specs);
5023 @:mp_tracing_specs_}{\&{tracingspecs} primitive@>
5024 mp_primitive(mp, "tracingcommands",internal_quantity,mp_tracing_commands);
5025 @:mp_tracing_commands_}{\&{tracingcommands} primitive@>
5026 mp_primitive(mp, "tracingrestores",internal_quantity,mp_tracing_restores);
5027 @:mp_tracing_restores_}{\&{tracingrestores} primitive@>
5028 mp_primitive(mp, "tracingmacros",internal_quantity,mp_tracing_macros);
5029 @:mp_tracing_macros_}{\&{tracingmacros} primitive@>
5030 mp_primitive(mp, "tracingoutput",internal_quantity,mp_tracing_output);
5031 @:mp_tracing_output_}{\&{tracingoutput} primitive@>
5032 mp_primitive(mp, "tracingstats",internal_quantity,mp_tracing_stats);
5033 @:mp_tracing_stats_}{\&{tracingstats} primitive@>
5034 mp_primitive(mp, "tracinglostchars",internal_quantity,mp_tracing_lost_chars);
5035 @:mp_tracing_lost_chars_}{\&{tracinglostchars} primitive@>
5036 mp_primitive(mp, "tracingonline",internal_quantity,mp_tracing_online);
5037 @:mp_tracing_online_}{\&{tracingonline} primitive@>
5038 mp_primitive(mp, "year",internal_quantity,mp_year);
5039 @:mp_year_}{\&{year} primitive@>
5040 mp_primitive(mp, "month",internal_quantity,mp_month);
5041 @:mp_month_}{\&{month} primitive@>
5042 mp_primitive(mp, "day",internal_quantity,mp_day);
5043 @:mp_day_}{\&{day} primitive@>
5044 mp_primitive(mp, "time",internal_quantity,mp_time);
5045 @:time_}{\&{time} primitive@>
5046 mp_primitive(mp, "charcode",internal_quantity,mp_char_code);
5047 @:mp_char_code_}{\&{charcode} primitive@>
5048 mp_primitive(mp, "charext",internal_quantity,mp_char_ext);
5049 @:mp_char_ext_}{\&{charext} primitive@>
5050 mp_primitive(mp, "charwd",internal_quantity,mp_char_wd);
5051 @:mp_char_wd_}{\&{charwd} primitive@>
5052 mp_primitive(mp, "charht",internal_quantity,mp_char_ht);
5053 @:mp_char_ht_}{\&{charht} primitive@>
5054 mp_primitive(mp, "chardp",internal_quantity,mp_char_dp);
5055 @:mp_char_dp_}{\&{chardp} primitive@>
5056 mp_primitive(mp, "charic",internal_quantity,mp_char_ic);
5057 @:mp_char_ic_}{\&{charic} primitive@>
5058 mp_primitive(mp, "designsize",internal_quantity,mp_design_size);
5059 @:mp_design_size_}{\&{designsize} primitive@>
5060 mp_primitive(mp, "pausing",internal_quantity,mp_pausing);
5061 @:mp_pausing_}{\&{pausing} primitive@>
5062 mp_primitive(mp, "showstopping",internal_quantity,mp_showstopping);
5063 @:mp_showstopping_}{\&{showstopping} primitive@>
5064 mp_primitive(mp, "fontmaking",internal_quantity,mp_fontmaking);
5065 @:mp_fontmaking_}{\&{fontmaking} primitive@>
5066 mp_primitive(mp, "linejoin",internal_quantity,mp_linejoin);
5067 @:mp_linejoin_}{\&{linejoin} primitive@>
5068 mp_primitive(mp, "linecap",internal_quantity,mp_linecap);
5069 @:mp_linecap_}{\&{linecap} primitive@>
5070 mp_primitive(mp, "miterlimit",internal_quantity,mp_miterlimit);
5071 @:mp_miterlimit_}{\&{miterlimit} primitive@>
5072 mp_primitive(mp, "warningcheck",internal_quantity,mp_warning_check);
5073 @:mp_warning_check_}{\&{warningcheck} primitive@>
5074 mp_primitive(mp, "boundarychar",internal_quantity,mp_boundary_char);
5075 @:mp_boundary_char_}{\&{boundarychar} primitive@>
5076 mp_primitive(mp, "prologues",internal_quantity,mp_prologues);
5077 @:mp_prologues_}{\&{prologues} primitive@>
5078 mp_primitive(mp, "truecorners",internal_quantity,mp_true_corners);
5079 @:mp_true_corners_}{\&{truecorners} primitive@>
5080 mp_primitive(mp, "mpprocset",internal_quantity,mp_procset);
5081 @:mp_procset_}{\&{mpprocset} primitive@>
5082 mp_primitive(mp, "troffmode",internal_quantity,mp_gtroffmode);
5083 @:troffmode_}{\&{troffmode} primitive@>
5084 mp_primitive(mp, "defaultcolormodel",internal_quantity,mp_default_color_model);
5085 @:mp_default_color_model_}{\&{defaultcolormodel} primitive@>
5086 mp_primitive(mp, "restoreclipcolor",internal_quantity,mp_restore_clip_color);
5087 @:mp_restore_clip_color_}{\&{restoreclipcolor} primitive@>
5088
5089 @ Colors can be specified in four color models. In the special
5090 case of |no_model|, MetaPost does not output any color operator to
5091 the postscript output.
5092
5093 Note: these values are passed directly on to |with_option|. This only
5094 works because the other possible values passed to |with_option| are
5095 8 and 10 respectively (from |with_pen| and |with_picture|).
5096
5097 There is a first state, that is only used for |gs_colormodel|. It flags
5098 the fact that there has not been any kind of color specification by
5099 the user so far in the game.
5100
5101 @<Types...@>=
5102 enum mp_color_model {
5103   mp_no_model=1,
5104   mp_grey_model=3,
5105   mp_rgb_model=5,
5106   mp_cmyk_model=7,
5107   mp_uninitialized_model=9,
5108 };
5109
5110
5111 @ @<Initialize table entries (done by \.{INIMP} only)@>=
5112 mp->internal[mp_default_color_model]=(mp_rgb_model*unity);
5113 mp->internal[mp_restore_clip_color]=unity;
5114
5115 @ Well, we do have to list the names one more time, for use in symbolic
5116 printouts.
5117
5118 @<Initialize table...@>=
5119 mp->int_name[mp_tracing_titles]=xstrdup("tracingtitles");
5120 mp->int_name[mp_tracing_equations]=xstrdup("tracingequations");
5121 mp->int_name[mp_tracing_capsules]=xstrdup("tracingcapsules");
5122 mp->int_name[mp_tracing_choices]=xstrdup("tracingchoices");
5123 mp->int_name[mp_tracing_specs]=xstrdup("tracingspecs");
5124 mp->int_name[mp_tracing_commands]=xstrdup("tracingcommands");
5125 mp->int_name[mp_tracing_restores]=xstrdup("tracingrestores");
5126 mp->int_name[mp_tracing_macros]=xstrdup("tracingmacros");
5127 mp->int_name[mp_tracing_output]=xstrdup("tracingoutput");
5128 mp->int_name[mp_tracing_stats]=xstrdup("tracingstats");
5129 mp->int_name[mp_tracing_lost_chars]=xstrdup("tracinglostchars");
5130 mp->int_name[mp_tracing_online]=xstrdup("tracingonline");
5131 mp->int_name[mp_year]=xstrdup("year");
5132 mp->int_name[mp_month]=xstrdup("month");
5133 mp->int_name[mp_day]=xstrdup("day");
5134 mp->int_name[mp_time]=xstrdup("time");
5135 mp->int_name[mp_char_code]=xstrdup("charcode");
5136 mp->int_name[mp_char_ext]=xstrdup("charext");
5137 mp->int_name[mp_char_wd]=xstrdup("charwd");
5138 mp->int_name[mp_char_ht]=xstrdup("charht");
5139 mp->int_name[mp_char_dp]=xstrdup("chardp");
5140 mp->int_name[mp_char_ic]=xstrdup("charic");
5141 mp->int_name[mp_design_size]=xstrdup("designsize");
5142 mp->int_name[mp_pausing]=xstrdup("pausing");
5143 mp->int_name[mp_showstopping]=xstrdup("showstopping");
5144 mp->int_name[mp_fontmaking]=xstrdup("fontmaking");
5145 mp->int_name[mp_linejoin]=xstrdup("linejoin");
5146 mp->int_name[mp_linecap]=xstrdup("linecap");
5147 mp->int_name[mp_miterlimit]=xstrdup("miterlimit");
5148 mp->int_name[mp_warning_check]=xstrdup("warningcheck");
5149 mp->int_name[mp_boundary_char]=xstrdup("boundarychar");
5150 mp->int_name[mp_prologues]=xstrdup("prologues");
5151 mp->int_name[mp_true_corners]=xstrdup("truecorners");
5152 mp->int_name[mp_default_color_model]=xstrdup("defaultcolormodel");
5153 mp->int_name[mp_procset]=xstrdup("mpprocset");
5154 mp->int_name[mp_gtroffmode]=xstrdup("troffmode");
5155 mp->int_name[mp_restore_clip_color]=xstrdup("restoreclipcolor");
5156
5157 @ The following procedure, which is called just before \MP\ initializes its
5158 input and output, establishes the initial values of the date and time.
5159 @^system dependencies@>
5160
5161 Note that the values are |scaled| integers. Hence \MP\ can no longer
5162 be used after the year 32767.
5163
5164 @c 
5165 void mp_fix_date_and_time (MP mp) { 
5166   time_t clock = time ((time_t *) 0);
5167   struct tm *tmptr = localtime (&clock);
5168   mp->internal[mp_time]=
5169       (tmptr->tm_hour*60+tmptr->tm_min)*unity; /* minutes since midnight */
5170   mp->internal[mp_day]=(tmptr->tm_mday)*unity; /* fourth day of the month */
5171   mp->internal[mp_month]=(tmptr->tm_mon+1)*unity; /* seventh month of the year */
5172   mp->internal[mp_year]=(tmptr->tm_year+1900)*unity; /* Anno Domini */
5173 }
5174
5175 @ @<Declarations@>=
5176 void mp_fix_date_and_time (MP mp) ;
5177
5178 @ \MP\ is occasionally supposed to print diagnostic information that
5179 goes only into the transcript file, unless |mp_tracing_online| is positive.
5180 Now that we have defined |mp_tracing_online| we can define
5181 two routines that adjust the destination of print commands:
5182
5183 @<Declarations@>=
5184 void mp_begin_diagnostic (MP mp) ;
5185 void mp_end_diagnostic (MP mp,boolean blank_line);
5186 void mp_print_diagnostic (MP mp, char *s, char *t, boolean nuline) ;
5187
5188 @ @<Basic printing...@>=
5189 @<Declare a function called |true_line|@>;
5190 void mp_begin_diagnostic (MP mp) { /* prepare to do some tracing */
5191   mp->old_setting=mp->selector;
5192   if ( mp->selector==ps_file_only ) mp->selector=mp->non_ps_setting;
5193   if ((mp->internal[mp_tracing_online]<=0)&&(mp->selector==term_and_log)){ 
5194     decr(mp->selector);
5195     if ( mp->history==mp_spotless ) mp->history=mp_warning_issued;
5196   }
5197 }
5198 @#
5199 void mp_end_diagnostic (MP mp,boolean blank_line) {
5200   /* restore proper conditions after tracing */
5201   mp_print_nl(mp, "");
5202   if ( blank_line ) mp_print_ln(mp);
5203   mp->selector=mp->old_setting;
5204 }
5205
5206 @ The global variable |non_ps_setting| is initialized when it is time to print
5207 on |ps_file|.
5208
5209 @<Glob...@>=
5210 unsigned int old_setting;
5211 unsigned int non_ps_setting;
5212
5213 @ We will occasionally use |begin_diagnostic| in connection with line-number
5214 printing, as follows. (The parameter |s| is typically |"Path"| or
5215 |"Cycle spec"|, etc.)
5216
5217 @<Basic printing...@>=
5218 void mp_print_diagnostic (MP mp, char *s, char *t, boolean nuline) { 
5219   mp_begin_diagnostic(mp);
5220   if ( nuline ) mp_print_nl(mp, s); else mp_print(mp, s);
5221   mp_print(mp, " at line "); 
5222   mp_print_int(mp, mp_true_line(mp));
5223   mp_print(mp, t); mp_print_char(mp, ':');
5224 }
5225
5226 @ The 256 |ASCII_code| characters are grouped into classes by means of
5227 the |char_class| table. Individual class numbers have no semantic
5228 or syntactic significance, except in a few instances defined here.
5229 There's also |max_class|, which can be used as a basis for additional
5230 class numbers in nonstandard extensions of \MP.
5231
5232 @d digit_class 0 /* the class number of \.{0123456789} */
5233 @d period_class 1 /* the class number of `\..' */
5234 @d space_class 2 /* the class number of spaces and nonstandard characters */
5235 @d percent_class 3 /* the class number of `\.\%' */
5236 @d string_class 4 /* the class number of `\."' */
5237 @d right_paren_class 8 /* the class number of `\.)' */
5238 @d isolated_classes 5: case 6: case 7: case 8 /* characters that make length-one tokens only */
5239 @d letter_class 9 /* letters and the underline character */
5240 @d left_bracket_class 17 /* `\.[' */
5241 @d right_bracket_class 18 /* `\.]' */
5242 @d invalid_class 20 /* bad character in the input */
5243 @d max_class 20 /* the largest class number */
5244
5245 @<Glob...@>=
5246 int char_class[256]; /* the class numbers */
5247
5248 @ If changes are made to accommodate non-ASCII character sets, they should
5249 follow the guidelines in Appendix~C of {\sl The {\logos METAFONT\/}book}.
5250 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
5251 @^system dependencies@>
5252
5253 @<Set initial ...@>=
5254 for (k='0';k<='9';k++) 
5255   mp->char_class[k]=digit_class;
5256 mp->char_class['.']=period_class;
5257 mp->char_class[' ']=space_class;
5258 mp->char_class['%']=percent_class;
5259 mp->char_class['"']=string_class;
5260 mp->char_class[',']=5;
5261 mp->char_class[';']=6;
5262 mp->char_class['(']=7;
5263 mp->char_class[')']=right_paren_class;
5264 for (k='A';k<= 'Z';k++ )
5265   mp->char_class[k]=letter_class;
5266 for (k='a';k<='z';k++) 
5267   mp->char_class[k]=letter_class;
5268 mp->char_class['_']=letter_class;
5269 mp->char_class['<']=10;
5270 mp->char_class['=']=10;
5271 mp->char_class['>']=10;
5272 mp->char_class[':']=10;
5273 mp->char_class['|']=10;
5274 mp->char_class['`']=11;
5275 mp->char_class['\'']=11;
5276 mp->char_class['+']=12;
5277 mp->char_class['-']=12;
5278 mp->char_class['/']=13;
5279 mp->char_class['*']=13;
5280 mp->char_class['\\']=13;
5281 mp->char_class['!']=14;
5282 mp->char_class['?']=14;
5283 mp->char_class['#']=15;
5284 mp->char_class['&']=15;
5285 mp->char_class['@@']=15;
5286 mp->char_class['$']=15;
5287 mp->char_class['^']=16;
5288 mp->char_class['~']=16;
5289 mp->char_class['[']=left_bracket_class;
5290 mp->char_class[']']=right_bracket_class;
5291 mp->char_class['{']=19;
5292 mp->char_class['}']=19;
5293 for (k=0;k<' ';k++)
5294   mp->char_class[k]=invalid_class;
5295 mp->char_class['\t']=space_class;
5296 mp->char_class['\f']=space_class;
5297 for (k=127;k<=255;k++)
5298   mp->char_class[k]=invalid_class;
5299
5300 @* \[13] The hash table.
5301 Symbolic tokens are stored and retrieved by means of a fairly standard hash
5302 table algorithm called the method of ``coalescing lists'' (cf.\ Algorithm 6.4C
5303 in {\sl The Art of Computer Programming\/}). Once a symbolic token enters the
5304 table, it is never removed.
5305
5306 The actual sequence of characters forming a symbolic token is
5307 stored in the |str_pool| array together with all the other strings. An
5308 auxiliary array |hash| consists of items with two halfword fields per
5309 word. The first of these, called |next(p)|, points to the next identifier
5310 belonging to the same coalesced list as the identifier corresponding to~|p|;
5311 and the other, called |text(p)|, points to the |str_start| entry for
5312 |p|'s identifier. If position~|p| of the hash table is empty, we have
5313 |text(p)=0|; if position |p| is either empty or the end of a coalesced
5314 hash list, we have |next(p)=0|.
5315
5316 An auxiliary pointer variable called |hash_used| is maintained in such a
5317 way that all locations |p>=hash_used| are nonempty. The global variable
5318 |st_count| tells how many symbolic tokens have been defined, if statistics
5319 are being kept.
5320
5321 The first 256 locations of |hash| are reserved for symbols of length one.
5322
5323 There's a parallel array called |eqtb| that contains the current equivalent
5324 values of each symbolic token. The entries of this array consist of
5325 two halfwords called |eq_type| (a command code) and |equiv| (a secondary
5326 piece of information that qualifies the |eq_type|).
5327
5328 @d next(A)   mp->hash[(A)].lh /* link for coalesced lists */
5329 @d text(A)   mp->hash[(A)].rh /* string number for symbolic token name */
5330 @d eq_type(A)   mp->eqtb[(A)].lh /* the current ``meaning'' of a symbolic token */
5331 @d equiv(A)   mp->eqtb[(A)].rh /* parametric part of a token's meaning */
5332 @d hash_base 257 /* hashing actually starts here */
5333 @d hash_is_full   (mp->hash_used==hash_base) /* are all positions occupied? */
5334
5335 @<Glob...@>=
5336 pointer hash_used; /* allocation pointer for |hash| */
5337 integer st_count; /* total number of known identifiers */
5338
5339 @ Certain entries in the hash table are ``frozen'' and not redefinable,
5340 since they are used in error recovery.
5341
5342 @d hash_top (hash_base+mp->hash_size) /* the first location of the frozen area */
5343 @d frozen_inaccessible hash_top /* |hash| location to protect the frozen area */
5344 @d frozen_repeat_loop (hash_top+1) /* |hash| location of a loop-repeat token */
5345 @d frozen_right_delimiter (hash_top+2) /* |hash| location of a permanent `\.)' */
5346 @d frozen_left_bracket (hash_top+3) /* |hash| location of a permanent `\.[' */
5347 @d frozen_slash (hash_top+4) /* |hash| location of a permanent `\./' */
5348 @d frozen_colon (hash_top+5) /* |hash| location of a permanent `\.:' */
5349 @d frozen_semicolon (hash_top+6) /* |hash| location of a permanent `\.;' */
5350 @d frozen_end_for (hash_top+7) /* |hash| location of a permanent \&{endfor} */
5351 @d frozen_end_def (hash_top+8) /* |hash| location of a permanent \&{enddef} */
5352 @d frozen_fi (hash_top+9) /* |hash| location of a permanent \&{fi} */
5353 @d frozen_end_group (hash_top+10) /* |hash| location of a permanent `\.{endgroup}' */
5354 @d frozen_etex (hash_top+11) /* |hash| location of a permanent \&{etex} */
5355 @d frozen_mpx_break (hash_top+12) /* |hash| location of a permanent \&{mpxbreak} */
5356 @d frozen_bad_vardef (hash_top+13) /* |hash| location of `\.{a bad variable}' */
5357 @d frozen_undefined (hash_top+14) /* |hash| location that never gets defined */
5358 @d hash_end (hash_top+14) /* the actual size of the |hash| and |eqtb| arrays */
5359
5360 @<Glob...@>=
5361 two_halves *hash; /* the hash table */
5362 two_halves *eqtb; /* the equivalents */
5363
5364 @ @<Allocate or initialize ...@>=
5365 mp->hash = xmalloc((hash_end+1),sizeof(two_halves));
5366 mp->eqtb = xmalloc((hash_end+1),sizeof(two_halves));
5367
5368 @ @<Dealloc variables@>=
5369 xfree(mp->hash);
5370 xfree(mp->eqtb);
5371
5372 @ @<Set init...@>=
5373 next(1)=0; text(1)=0; eq_type(1)=tag_token; equiv(1)=null;
5374 for (k=2;k<=hash_end;k++)  { 
5375   mp->hash[k]=mp->hash[1]; mp->eqtb[k]=mp->eqtb[1];
5376 }
5377
5378 @ @<Initialize table entries...@>=
5379 mp->hash_used=frozen_inaccessible; /* nothing is used */
5380 mp->st_count=0;
5381 text(frozen_bad_vardef)=intern("a bad variable");
5382 text(frozen_etex)=intern("etex");
5383 text(frozen_mpx_break)=intern("mpxbreak");
5384 text(frozen_fi)=intern("fi");
5385 text(frozen_end_group)=intern("endgroup");
5386 text(frozen_end_def)=intern("enddef");
5387 text(frozen_end_for)=intern("endfor");
5388 text(frozen_semicolon)=intern(";");
5389 text(frozen_colon)=intern(":");
5390 text(frozen_slash)=intern("/");
5391 text(frozen_left_bracket)=intern("[");
5392 text(frozen_right_delimiter)=intern(")");
5393 text(frozen_inaccessible)=intern(" INACCESSIBLE");
5394 eq_type(frozen_right_delimiter)=right_delimiter;
5395
5396 @ @<Check the ``constant'' values...@>=
5397 if ( hash_end+mp->max_internal>max_halfword ) mp->bad=17;
5398
5399 @ Here is the subroutine that searches the hash table for an identifier
5400 that matches a given string of length~|l| appearing in |buffer[j..
5401 (j+l-1)]|. If the identifier is not found, it is inserted; hence it
5402 will always be found, and the corresponding hash table address
5403 will be returned.
5404
5405 @c 
5406 pointer mp_id_lookup (MP mp,integer j, integer l) { /* search the hash table */
5407   integer h; /* hash code */
5408   pointer p; /* index in |hash| array */
5409   pointer k; /* index in |buffer| array */
5410   if (l==1) {
5411     @<Treat special case of length 1 and |break|@>;
5412   }
5413   @<Compute the hash code |h|@>;
5414   p=h+hash_base; /* we start searching here; note that |0<=h<hash_prime| */
5415   while (true)  { 
5416         if (text(p)>0 && length(text(p))==l && mp_str_eq_buf(mp, text(p),j)) 
5417       break;
5418     if ( next(p)==0 ) {
5419       @<Insert a new symbolic token after |p|, then
5420         make |p| point to it and |break|@>;
5421     }
5422     p=next(p);
5423   }
5424   return p;
5425 };
5426
5427 @ @<Treat special case of length 1...@>=
5428  p=mp->buffer[j]+1; text(p)=p-1; return p;
5429
5430
5431 @ @<Insert a new symbolic...@>=
5432 {
5433 if ( text(p)>0 ) { 
5434   do {  
5435     if ( hash_is_full )
5436       mp_overflow(mp, "hash size",mp->hash_size);
5437 @:MetaPost capacity exceeded hash size}{\quad hash size@>
5438     decr(mp->hash_used);
5439   } while (text(mp->hash_used)!=0); /* search for an empty location in |hash| */
5440   next(p)=mp->hash_used; 
5441   p=mp->hash_used;
5442 }
5443 str_room(l);
5444 for (k=j;k<=j+l-1;k++) {
5445   append_char(mp->buffer[k]);
5446 }
5447 text(p)=mp_make_string(mp); 
5448 mp->str_ref[text(p)]=max_str_ref;
5449 incr(mp->st_count);
5450 break;
5451 }
5452
5453
5454 @ The value of |hash_prime| should be roughly 85\pct! of |hash_size|, and it
5455 should be a prime number.  The theory of hashing tells us to expect fewer
5456 than two table probes, on the average, when the search is successful.
5457 [See J.~S. Vitter, {\sl Journal of the ACM\/ \bf30} (1983), 231--258.]
5458 @^Vitter, Jeffrey Scott@>
5459
5460 @<Compute the hash code |h|@>=
5461 h=mp->buffer[j];
5462 for (k=j+1;k<=j+l-1;k++){ 
5463   h=h+h+mp->buffer[k];
5464   while ( h>=mp->hash_prime ) h=h-mp->hash_prime;
5465 }
5466
5467 @ @<Search |eqtb| for equivalents equal to |p|@>=
5468 for (q=1;q<=hash_end;q++) { 
5469   if ( equiv(q)==p ) { 
5470     mp_print_nl(mp, "EQUIV("); 
5471     mp_print_int(mp, q); 
5472     mp_print_char(mp, ')');
5473   }
5474 }
5475
5476 @ We need to put \MP's ``primitive'' symbolic tokens into the hash
5477 table, together with their command code (which will be the |eq_type|)
5478 and an operand (which will be the |equiv|). The |primitive| procedure
5479 does this, in a way that no \MP\ user can. The global value |cur_sym|
5480 contains the new |eqtb| pointer after |primitive| has acted.
5481
5482 @c 
5483 void mp_primitive (MP mp, char *ss, halfword c, halfword o) {
5484   pool_pointer k; /* index into |str_pool| */
5485   small_number j; /* index into |buffer| */
5486   small_number l; /* length of the string */
5487   str_number s;
5488   s = intern(ss);
5489   k=mp->str_start[s]; l=str_stop(s)-k;
5490   /* we will move |s| into the (empty) |buffer| */
5491   for (j=0;j<=l-1;j++) {
5492     mp->buffer[j]=mp->str_pool[k+j];
5493   }
5494   mp->cur_sym=mp_id_lookup(mp, 0,l);
5495   if ( s>=256 ) { /* we don't want to have the string twice */
5496     mp_flush_string(mp, text(mp->cur_sym)); text(mp->cur_sym)=s;
5497   };
5498   eq_type(mp->cur_sym)=c; 
5499   equiv(mp->cur_sym)=o;
5500 }
5501
5502
5503 @ Many of \MP's primitives need no |equiv|, since they are identifiable
5504 by their |eq_type| alone. These primitives are loaded into the hash table
5505 as follows:
5506
5507 @<Put each of \MP's primitives into the hash table@>=
5508 mp_primitive(mp, "..",path_join,0);
5509 @:.._}{\.{..} primitive@>
5510 mp_primitive(mp, "[",left_bracket,0); mp->eqtb[frozen_left_bracket]=mp->eqtb[mp->cur_sym];
5511 @:[ }{\.{[} primitive@>
5512 mp_primitive(mp, "]",right_bracket,0);
5513 @:] }{\.{]} primitive@>
5514 mp_primitive(mp, "}",right_brace,0);
5515 @:]]}{\.{\char`\}} primitive@>
5516 mp_primitive(mp, "{",left_brace,0);
5517 @:][}{\.{\char`\{} primitive@>
5518 mp_primitive(mp, ":",colon,0); mp->eqtb[frozen_colon]=mp->eqtb[mp->cur_sym];
5519 @:: }{\.{:} primitive@>
5520 mp_primitive(mp, "::",double_colon,0);
5521 @::: }{\.{::} primitive@>
5522 mp_primitive(mp, "||:",bchar_label,0);
5523 @:::: }{\.{\char'174\char'174:} primitive@>
5524 mp_primitive(mp, ":=",assignment,0);
5525 @::=_}{\.{:=} primitive@>
5526 mp_primitive(mp, ",",comma,0);
5527 @:, }{\., primitive@>
5528 mp_primitive(mp, ";",semicolon,0); mp->eqtb[frozen_semicolon]=mp->eqtb[mp->cur_sym];
5529 @:; }{\.; primitive@>
5530 mp_primitive(mp, "\\",relax,0);
5531 @:]]\\}{\.{\char`\\} primitive@>
5532 @#
5533 mp_primitive(mp, "addto",add_to_command,0);
5534 @:add_to_}{\&{addto} primitive@>
5535 mp_primitive(mp, "atleast",at_least,0);
5536 @:at_least_}{\&{atleast} primitive@>
5537 mp_primitive(mp, "begingroup",begin_group,0); mp->bg_loc=mp->cur_sym;
5538 @:begin_group_}{\&{begingroup} primitive@>
5539 mp_primitive(mp, "controls",controls,0);
5540 @:controls_}{\&{controls} primitive@>
5541 mp_primitive(mp, "curl",curl_command,0);
5542 @:curl_}{\&{curl} primitive@>
5543 mp_primitive(mp, "delimiters",delimiters,0);
5544 @:delimiters_}{\&{delimiters} primitive@>
5545 mp_primitive(mp, "endgroup",end_group,0);
5546  mp->eqtb[frozen_end_group]=mp->eqtb[mp->cur_sym]; mp->eg_loc=mp->cur_sym;
5547 @:endgroup_}{\&{endgroup} primitive@>
5548 mp_primitive(mp, "everyjob",every_job_command,0);
5549 @:every_job_}{\&{everyjob} primitive@>
5550 mp_primitive(mp, "exitif",exit_test,0);
5551 @:exit_if_}{\&{exitif} primitive@>
5552 mp_primitive(mp, "expandafter",expand_after,0);
5553 @:expand_after_}{\&{expandafter} primitive@>
5554 mp_primitive(mp, "interim",interim_command,0);
5555 @:interim_}{\&{interim} primitive@>
5556 mp_primitive(mp, "let",let_command,0);
5557 @:let_}{\&{let} primitive@>
5558 mp_primitive(mp, "newinternal",new_internal,0);
5559 @:new_internal_}{\&{newinternal} primitive@>
5560 mp_primitive(mp, "of",of_token,0);
5561 @:of_}{\&{of} primitive@>
5562 mp_primitive(mp, "randomseed",random_seed,0);
5563 @:random_seed_}{\&{randomseed} primitive@>
5564 mp_primitive(mp, "save",save_command,0);
5565 @:save_}{\&{save} primitive@>
5566 mp_primitive(mp, "scantokens",scan_tokens,0);
5567 @:scan_tokens_}{\&{scantokens} primitive@>
5568 mp_primitive(mp, "shipout",ship_out_command,0);
5569 @:ship_out_}{\&{shipout} primitive@>
5570 mp_primitive(mp, "skipto",skip_to,0);
5571 @:skip_to_}{\&{skipto} primitive@>
5572 mp_primitive(mp, "special",special_command,0);
5573 @:special}{\&{special} primitive@>
5574 mp_primitive(mp, "fontmapfile",special_command,1);
5575 @:fontmapfile}{\&{fontmapfile} primitive@>
5576 mp_primitive(mp, "fontmapline",special_command,2);
5577 @:fontmapline}{\&{fontmapline} primitive@>
5578 mp_primitive(mp, "step",step_token,0);
5579 @:step_}{\&{step} primitive@>
5580 mp_primitive(mp, "str",str_op,0);
5581 @:str_}{\&{str} primitive@>
5582 mp_primitive(mp, "tension",tension,0);
5583 @:tension_}{\&{tension} primitive@>
5584 mp_primitive(mp, "to",to_token,0);
5585 @:to_}{\&{to} primitive@>
5586 mp_primitive(mp, "until",until_token,0);
5587 @:until_}{\&{until} primitive@>
5588 mp_primitive(mp, "within",within_token,0);
5589 @:within_}{\&{within} primitive@>
5590 mp_primitive(mp, "write",write_command,0);
5591 @:write_}{\&{write} primitive@>
5592
5593 @ Each primitive has a corresponding inverse, so that it is possible to
5594 display the cryptic numeric contents of |eqtb| in symbolic form.
5595 Every call of |primitive| in this program is therefore accompanied by some
5596 straightforward code that forms part of the |print_cmd_mod| routine
5597 explained below.
5598
5599 @<Cases of |print_cmd_mod| for symbolic printing of primitives@>=
5600 case add_to_command:mp_print(mp, "addto"); break;
5601 case assignment:mp_print(mp, ":="); break;
5602 case at_least:mp_print(mp, "atleast"); break;
5603 case bchar_label:mp_print(mp, "||:"); break;
5604 case begin_group:mp_print(mp, "begingroup"); break;
5605 case colon:mp_print(mp, ":"); break;
5606 case comma:mp_print(mp, ","); break;
5607 case controls:mp_print(mp, "controls"); break;
5608 case curl_command:mp_print(mp, "curl"); break;
5609 case delimiters:mp_print(mp, "delimiters"); break;
5610 case double_colon:mp_print(mp, "::"); break;
5611 case end_group:mp_print(mp, "endgroup"); break;
5612 case every_job_command:mp_print(mp, "everyjob"); break;
5613 case exit_test:mp_print(mp, "exitif"); break;
5614 case expand_after:mp_print(mp, "expandafter"); break;
5615 case interim_command:mp_print(mp, "interim"); break;
5616 case left_brace:mp_print(mp, "{"); break;
5617 case left_bracket:mp_print(mp, "["); break;
5618 case let_command:mp_print(mp, "let"); break;
5619 case new_internal:mp_print(mp, "newinternal"); break;
5620 case of_token:mp_print(mp, "of"); break;
5621 case path_join:mp_print(mp, ".."); break;
5622 case random_seed:mp_print(mp, "randomseed"); break;
5623 case relax:mp_print_char(mp, '\\'); break;
5624 case right_brace:mp_print(mp, "}"); break;
5625 case right_bracket:mp_print(mp, "]"); break;
5626 case save_command:mp_print(mp, "save"); break;
5627 case scan_tokens:mp_print(mp, "scantokens"); break;
5628 case semicolon:mp_print(mp, ";"); break;
5629 case ship_out_command:mp_print(mp, "shipout"); break;
5630 case skip_to:mp_print(mp, "skipto"); break;
5631 case special_command: if ( m==2 ) mp_print(mp, "fontmapline"); else
5632                  if ( m==1 ) mp_print(mp, "fontmapfile"); else
5633                  mp_print(mp, "special"); break;
5634 case step_token:mp_print(mp, "step"); break;
5635 case str_op:mp_print(mp, "str"); break;
5636 case tension:mp_print(mp, "tension"); break;
5637 case to_token:mp_print(mp, "to"); break;
5638 case until_token:mp_print(mp, "until"); break;
5639 case within_token:mp_print(mp, "within"); break;
5640 case write_command:mp_print(mp, "write"); break;
5641
5642 @ We will deal with the other primitives later, at some point in the program
5643 where their |eq_type| and |equiv| values are more meaningful.  For example,
5644 the primitives for macro definitions will be loaded when we consider the
5645 routines that define macros.
5646 It is easy to find where each particular
5647 primitive was treated by looking in the index at the end; for example, the
5648 section where |"def"| entered |eqtb| is listed under `\&{def} primitive'.
5649
5650 @* \[14] Token lists.
5651 A \MP\ token is either symbolic or numeric or a string, or it denotes
5652 a macro parameter or capsule; so there are five corresponding ways to encode it
5653 @^token@>
5654 internally: (1)~A symbolic token whose hash code is~|p|
5655 is represented by the number |p|, in the |info| field of a single-word
5656 node in~|mem|. (2)~A numeric token whose |scaled| value is~|v| is
5657 represented in a two-word node of~|mem|; the |type| field is |known|,
5658 the |name_type| field is |token|, and the |value| field holds~|v|.
5659 The fact that this token appears in a two-word node rather than a
5660 one-word node is, of course, clear from the node address.
5661 (3)~A string token is also represented in a two-word node; the |type|
5662 field is |mp_string_type|, the |name_type| field is |token|, and the
5663 |value| field holds the corresponding |str_number|.  (4)~Capsules have
5664 |name_type=capsule|, and their |type| and |value| fields represent
5665 arbitrary values (in ways to be explained later).  (5)~Macro parameters
5666 are like symbolic tokens in that they appear in |info| fields of
5667 one-word nodes. The $k$th parameter is represented by |expr_base+k| if it
5668 is of type \&{expr}, or by |suffix_base+k| if it is of type \&{suffix}, or
5669 by |text_base+k| if it is of type \&{text}.  (Here |0<=k<param_size|.)
5670 Actual values of these parameters are kept in a separate stack, as we will
5671 see later.  The constants |expr_base|, |suffix_base|, and |text_base| are,
5672 of course, chosen so that there will be no confusion between symbolic
5673 tokens and parameters of various types.
5674
5675 Note that
5676 the `\\{type}' field of a node has nothing to do with ``type'' in a
5677 printer's sense. It's curious that the same word is used in such different ways.
5678
5679 @d type(A)   mp->mem[(A)].hh.b0 /* identifies what kind of value this is */
5680 @d name_type(A)   mp->mem[(A)].hh.b1 /* a clue to the name of this value */
5681 @d token_node_size 2 /* the number of words in a large token node */
5682 @d value_loc(A) ((A)+1) /* the word that contains the |value| field */
5683 @d value(A) mp->mem[value_loc((A))].cint /* the value stored in a large token node */
5684 @d expr_base (hash_end+1) /* code for the zeroth \&{expr} parameter */
5685 @d suffix_base (expr_base+mp->param_size) /* code for the zeroth \&{suffix} parameter */
5686 @d text_base (suffix_base+mp->param_size) /* code for the zeroth \&{text} parameter */
5687
5688 @<Check the ``constant''...@>=
5689 if ( text_base+mp->param_size>max_halfword ) mp->bad=18;
5690
5691 @ We have set aside a two word node beginning at |null| so that we can have
5692 |value(null)=0|.  We will make use of this coincidence later.
5693
5694 @<Initialize table entries...@>=
5695 link(null)=null; value(null)=0;
5696
5697 @ A numeric token is created by the following trivial routine.
5698
5699 @c 
5700 pointer mp_new_num_tok (MP mp,scaled v) {
5701   pointer p; /* the new node */
5702   p=mp_get_node(mp, token_node_size); value(p)=v;
5703   type(p)=mp_known; name_type(p)=mp_token; 
5704   return p;
5705 }
5706
5707 @ A token list is a singly linked list of nodes in |mem|, where
5708 each node contains a token and a link.  Here's a subroutine that gets rid
5709 of a token list when it is no longer needed.
5710
5711 @<Declarations@>=
5712 void mp_token_recycle (MP mp);
5713
5714
5715 @c void mp_flush_token_list (MP mp,pointer p) {
5716   pointer q; /* the node being recycled */
5717   while ( p!=null ) { 
5718     q=p; p=link(p);
5719     if ( q>=mp->hi_mem_min ) {
5720      free_avail(q);
5721     } else { 
5722       switch (type(q)) {
5723       case mp_vacuous: case mp_boolean_type: case mp_known:
5724         break;
5725       case mp_string_type:
5726         delete_str_ref(value(q));
5727         break;
5728       case unknown_types: case mp_pen_type: case mp_path_type: 
5729       case mp_picture_type: case mp_pair_type: case mp_color_type:
5730       case mp_cmykcolor_type: case mp_transform_type: case mp_dependent:
5731       case mp_proto_dependent: case mp_independent:
5732         mp->g_pointer=q; mp_token_recycle(mp);
5733         break;
5734       default: mp_confusion(mp, "token");
5735 @:this can't happen token}{\quad token@>
5736       }
5737       mp_free_node(mp, q,token_node_size);
5738     }
5739   }
5740 }
5741
5742 @ The procedure |show_token_list|, which prints a symbolic form of
5743 the token list that starts at a given node |p|, illustrates these
5744 conventions. The token list being displayed should not begin with a reference
5745 count. However, the procedure is intended to be fairly robust, so that if the
5746 memory links are awry or if |p| is not really a pointer to a token list,
5747 almost nothing catastrophic can happen.
5748
5749 An additional parameter |q| is also given; this parameter is either null
5750 or it points to a node in the token list where a certain magic computation
5751 takes place that will be explained later. (Basically, |q| is non-null when
5752 we are printing the two-line context information at the time of an error
5753 message; |q| marks the place corresponding to where the second line
5754 should begin.)
5755
5756 The generation will stop, and `\.{\char`\ ETC.}' will be printed, if the length
5757 of printing exceeds a given limit~|l|; the length of printing upon entry is
5758 assumed to be a given amount called |null_tally|. (Note that
5759 |show_token_list| sometimes uses itself recursively to print
5760 variable names within a capsule.)
5761 @^recursion@>
5762
5763 Unusual entries are printed in the form of all-caps tokens
5764 preceded by a space, e.g., `\.{\char`\ BAD}'.
5765
5766 @<Declarations@>=
5767 void mp_print_capsule (MP mp);
5768
5769 @ @<Declare the procedure called |show_token_list|@>=
5770 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5771                          integer null_tally) ;
5772
5773 @ @c
5774 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5775                          integer null_tally) {
5776   small_number class,c; /* the |char_class| of previous and new tokens */
5777   integer r,v; /* temporary registers */
5778   class=percent_class;
5779   mp->tally=null_tally;
5780   while ( (p!=null) && (mp->tally<l) ) { 
5781     if ( p==q ) 
5782       @<Do magic computation@>;
5783     @<Display token |p| and set |c| to its class;
5784       but |return| if there are problems@>;
5785     class=c; p=link(p);
5786   }
5787   if ( p!=null ) 
5788      mp_print(mp, " ETC.");
5789 @.ETC@>
5790   return;
5791 };
5792
5793 @ @<Display token |p| and set |c| to its class...@>=
5794 c=letter_class; /* the default */
5795 if ( (p<0)||(p>mp->mem_end) ) { 
5796   mp_print(mp, " CLOBBERED"); return;
5797 @.CLOBBERED@>
5798 }
5799 if ( p<mp->hi_mem_min ) { 
5800   @<Display two-word token@>;
5801 } else { 
5802   r=info(p);
5803   if ( r>=expr_base ) {
5804      @<Display a parameter token@>;
5805   } else {
5806     if ( r<1 ) {
5807       if ( r==0 ) { 
5808         @<Display a collective subscript@>
5809       } else {
5810         mp_print(mp, " IMPOSSIBLE");
5811 @.IMPOSSIBLE@>
5812       }
5813     } else { 
5814       r=text(r);
5815       if ( (r<0)||(r>mp->max_str_ptr) ) {
5816         mp_print(mp, " NONEXISTENT");
5817 @.NONEXISTENT@>
5818       } else {
5819        @<Print string |r| as a symbolic token
5820         and set |c| to its class@>;
5821       }
5822     }
5823   }
5824 }
5825
5826 @ @<Display two-word token@>=
5827 if ( name_type(p)==mp_token ) {
5828   if ( type(p)==mp_known ) {
5829     @<Display a numeric token@>;
5830   } else if ( type(p)!=mp_string_type ) {
5831     mp_print(mp, " BAD");
5832 @.BAD@>
5833   } else { 
5834     mp_print_char(mp, '"'); mp_print_str(mp, value(p)); mp_print_char(mp, '"');
5835     c=string_class;
5836   }
5837 } else if ((name_type(p)!=mp_capsule)||(type(p)<mp_vacuous)||(type(p)>mp_independent) ) {
5838   mp_print(mp, " BAD");
5839 } else { 
5840   mp->g_pointer=p; mp_print_capsule(mp); c=right_paren_class;
5841 }
5842
5843 @ @<Display a numeric token@>=
5844 if ( class==digit_class ) 
5845   mp_print_char(mp, ' ');
5846 v=value(p);
5847 if ( v<0 ){ 
5848   if ( class==left_bracket_class ) 
5849     mp_print_char(mp, ' ');
5850   mp_print_char(mp, '['); mp_print_scaled(mp, v); mp_print_char(mp, ']');
5851   c=right_bracket_class;
5852 } else { 
5853   mp_print_scaled(mp, v); c=digit_class;
5854 }
5855
5856
5857 @ Strictly speaking, a genuine token will never have |info(p)=0|.
5858 But we will see later (in the |print_variable_name| routine) that
5859 it is convenient to let |info(p)=0| stand for `\.{[]}'.
5860
5861 @<Display a collective subscript@>=
5862 {
5863 if ( class==left_bracket_class ) 
5864   mp_print_char(mp, ' ');
5865 mp_print(mp, "[]"); c=right_bracket_class;
5866 }
5867
5868 @ @<Display a parameter token@>=
5869 {
5870 if ( r<suffix_base ) { 
5871   mp_print(mp, "(EXPR"); r=r-(expr_base);
5872 @.EXPR@>
5873 } else if ( r<text_base ) { 
5874   mp_print(mp, "(SUFFIX"); r=r-(suffix_base);
5875 @.SUFFIX@>
5876 } else { 
5877   mp_print(mp, "(TEXT"); r=r-(text_base);
5878 @.TEXT@>
5879 }
5880 mp_print_int(mp, r); mp_print_char(mp, ')'); c=right_paren_class;
5881 }
5882
5883
5884 @ @<Print string |r| as a symbolic token...@>=
5885
5886 c=mp->char_class[mp->str_pool[mp->str_start[r]]];
5887 if ( c==class ) {
5888   switch (c) {
5889   case letter_class:mp_print_char(mp, '.'); break;
5890   case isolated_classes: break;
5891   default: mp_print_char(mp, ' '); break;
5892   }
5893 }
5894 mp_print_str(mp, r);
5895 }
5896
5897 @ The following procedures have been declared |forward| with no parameters,
5898 because the author dislikes \PASCAL's convention about |forward| procedures
5899 with parameters. It was necessary to do something, because |show_token_list|
5900 is recursive (although the recursion is limited to one level), and because
5901 |flush_token_list| is syntactically (but not semantically) recursive.
5902 @^recursion@>
5903
5904 @<Declare miscellaneous procedures that were declared |forward|@>=
5905 void mp_print_capsule (MP mp) { 
5906   mp_print_char(mp, '('); mp_print_exp(mp, mp->g_pointer,0); mp_print_char(mp, ')');
5907 };
5908 @#
5909 void mp_token_recycle (MP mp) { 
5910   mp_recycle_value(mp, mp->g_pointer);
5911 };
5912
5913 @ @<Glob...@>=
5914 pointer g_pointer; /* (global) parameter to the |forward| procedures */
5915
5916 @ Macro definitions are kept in \MP's memory in the form of token lists
5917 that have a few extra one-word nodes at the beginning.
5918
5919 The first node contains a reference count that is used to tell when the
5920 list is no longer needed. To emphasize the fact that a reference count is
5921 present, we shall refer to the |info| field of this special node as the
5922 |ref_count| field.
5923 @^reference counts@>
5924
5925 The next node or nodes after the reference count serve to describe the
5926 formal parameters. They either contain a code word that specifies all
5927 of the parameters, or they contain zero or more parameter tokens followed
5928 by the code `|general_macro|'.
5929
5930 @d ref_count info
5931   /* reference count preceding a macro definition or picture header */
5932 @d add_mac_ref(A) incr(ref_count((A))) /* make a new reference to a macro list */
5933 @d general_macro 0 /* preface to a macro defined with a parameter list */
5934 @d primary_macro 1 /* preface to a macro with a \&{primary} parameter */
5935 @d secondary_macro 2 /* preface to a macro with a \&{secondary} parameter */
5936 @d tertiary_macro 3 /* preface to a macro with a \&{tertiary} parameter */
5937 @d expr_macro 4 /* preface to a macro with an undelimited \&{expr} parameter */
5938 @d of_macro 5 /* preface to a macro with
5939   undelimited `\&{expr} |x| \&{of}~|y|' parameters */
5940 @d suffix_macro 6 /* preface to a macro with an undelimited \&{suffix} parameter */
5941 @d text_macro 7 /* preface to a macro with an undelimited \&{text} parameter */
5942
5943 @c 
5944 void mp_delete_mac_ref (MP mp,pointer p) {
5945   /* |p| points to the reference count of a macro list that is
5946     losing one reference */
5947   if ( ref_count(p)==null ) mp_flush_token_list(mp, p);
5948   else decr(ref_count(p));
5949 }
5950
5951 @ The following subroutine displays a macro, given a pointer to its
5952 reference count.
5953
5954 @c 
5955 @<Declare the procedure called |print_cmd_mod|@>;
5956 void mp_show_macro (MP mp, pointer p, integer q, integer l) {
5957   pointer r; /* temporary storage */
5958   p=link(p); /* bypass the reference count */
5959   while ( info(p)>text_macro ){ 
5960     r=link(p); link(p)=null;
5961     mp_show_token_list(mp, p,null,l,0); link(p)=r; p=r;
5962     if ( l>0 ) l=l-mp->tally; else return;
5963   } /* control printing of `\.{ETC.}' */
5964 @.ETC@>
5965   mp->tally=0;
5966   switch(info(p)) {
5967   case general_macro:mp_print(mp, "->"); break;
5968 @.->@>
5969   case primary_macro: case secondary_macro: case tertiary_macro:
5970     mp_print_char(mp, '<');
5971     mp_print_cmd_mod(mp, param_type,info(p)); 
5972     mp_print(mp, ">->");
5973     break;
5974   case expr_macro:mp_print(mp, "<expr>->"); break;
5975   case of_macro:mp_print(mp, "<expr>of<primary>->"); break;
5976   case suffix_macro:mp_print(mp, "<suffix>->"); break;
5977   case text_macro:mp_print(mp, "<text>->"); break;
5978   } /* there are no other cases */
5979   mp_show_token_list(mp, link(p),q,l-mp->tally,0);
5980 }
5981
5982 @* \[15] Data structures for variables.
5983 The variables of \MP\ programs can be simple, like `\.x', or they can
5984 combine the structural properties of arrays and records, like `\.{x20a.b}'.
5985 A \MP\ user assigns a type to a variable like \.{x20a.b} by saying, for
5986 example, `\.{boolean} \.{x20a.b}'. It's time for us to study how such
5987 things are represented inside of the computer.
5988
5989 Each variable value occupies two consecutive words, either in a two-word
5990 node called a value node, or as a two-word subfield of a larger node.  One
5991 of those two words is called the |value| field; it is an integer,
5992 containing either a |scaled| numeric value or the representation of some
5993 other type of quantity. (It might also be subdivided into halfwords, in
5994 which case it is referred to by other names instead of |value|.) The other
5995 word is broken into subfields called |type|, |name_type|, and |link|.  The
5996 |type| field is a quarterword that specifies the variable's type, and
5997 |name_type| is a quarterword from which \MP\ can reconstruct the
5998 variable's name (sometimes by using the |link| field as well).  Thus, only
5999 1.25 words are actually devoted to the value itself; the other
6000 three-quarters of a word are overhead, but they aren't wasted because they
6001 allow \MP\ to deal with sparse arrays and to provide meaningful diagnostics.
6002
6003 In this section we shall be concerned only with the structural aspects of
6004 variables, not their values. Later parts of the program will change the
6005 |type| and |value| fields, but we shall treat those fields as black boxes
6006 whose contents should not be touched.
6007
6008 However, if the |type| field is |mp_structured|, there is no |value| field,
6009 and the second word is broken into two pointer fields called |attr_head|
6010 and |subscr_head|. Those fields point to additional nodes that
6011 contain structural information, as we shall see.
6012
6013 @d subscr_head_loc(A)   (A)+1 /* where |value|, |subscr_head| and |attr_head| are */
6014 @d attr_head(A)   info(subscr_head_loc((A))) /* pointer to attribute info */
6015 @d subscr_head(A)   link(subscr_head_loc((A))) /* pointer to subscript info */
6016 @d value_node_size 2 /* the number of words in a value node */
6017
6018 @ An attribute node is three words long. Two of these words contain |type|
6019 and |value| fields as described above, and the third word contains
6020 additional information:  There is an |attr_loc| field, which contains the
6021 hash address of the token that names this attribute; and there's also a
6022 |parent| field, which points to the value node of |mp_structured| type at the
6023 next higher level (i.e., at the level to which this attribute is
6024 subsidiary).  The |name_type| in an attribute node is `|attr|'.  The
6025 |link| field points to the next attribute with the same parent; these are
6026 arranged in increasing order, so that |attr_loc(link(p))>attr_loc(p)|. The
6027 final attribute node links to the constant |end_attr|, whose |attr_loc|
6028 field is greater than any legal hash address. The |attr_head| in the
6029 parent points to a node whose |name_type| is |mp_structured_root|; this
6030 node represents the null attribute, i.e., the variable that is relevant
6031 when no attributes are attached to the parent. The |attr_head| node is either
6032 a value node, a subscript node, or an attribute node, depending on what
6033 the parent would be if it were not structured; but the subscript and
6034 attribute fields are ignored, so it effectively contains only the data of
6035 a value node. The |link| field in this special node points to an attribute
6036 node whose |attr_loc| field is zero; the latter node represents a collective
6037 subscript `\.{[]}' attached to the parent, and its |link| field points to
6038 the first non-special attribute node (or to |end_attr| if there are none).
6039
6040 A subscript node likewise occupies three words, with |type| and |value| fields
6041 plus extra information; its |name_type| is |subscr|. In this case the
6042 third word is called the |subscript| field, which is a |scaled| integer.
6043 The |link| field points to the subscript node with the next larger
6044 subscript, if any; otherwise the |link| points to the attribute node
6045 for collective subscripts at this level. We have seen that the latter node
6046 contains an upward pointer, so that the parent can be deduced.
6047
6048 The |name_type| in a parent-less value node is |root|, and the |link|
6049 is the hash address of the token that names this value.
6050
6051 In other words, variables have a hierarchical structure that includes
6052 enough threads running around so that the program is able to move easily
6053 between siblings, parents, and children. An example should be helpful:
6054 (The reader is advised to draw a picture while reading the following
6055 description, since that will help to firm up the ideas.)
6056 Suppose that `\.x' and `\.{x.a}' and `\.{x[]b}' and `\.{x5}'
6057 and `\.{x20b}' have been mentioned in a user's program, where
6058 \.{x[]b} has been declared to be of \&{boolean} type. Let |h(x)|, |h(a)|,
6059 and |h(b)| be the hash addresses of \.x, \.a, and~\.b. Then
6060 |eq_type(h(x))=name| and |equiv(h(x))=p|, where |p|~is a two-word value
6061 node with |name_type(p)=root| and |link(p)=h(x)|. We have |type(p)=mp_structured|,
6062 |attr_head(p)=q|, and |subscr_head(p)=r|, where |q| points to a value
6063 node and |r| to a subscript node. (Are you still following this? Use
6064 a pencil to draw a diagram.) The lone variable `\.x' is represented by
6065 |type(q)| and |value(q)|; furthermore
6066 |name_type(q)=mp_structured_root| and |link(q)=q1|, where |q1| points
6067 to an attribute node representing `\.{x[]}'. Thus |name_type(q1)=attr|,
6068 |attr_loc(q1)=collective_subscript=0|, |parent(q1)=p|,
6069 |type(q1)=mp_structured|, |attr_head(q1)=qq|, and |subscr_head(q1)=qq1|;
6070 |qq| is a value node with |type(qq)=mp_numeric_type| (assuming that \.{x5} is
6071 numeric, because |qq| represents `\.{x[]}' with no further attributes),
6072 |name_type(qq)=mp_structured_root|, and
6073 |link(qq)=qq1|. (Now pay attention to the next part.) Node |qq1| is
6074 an attribute node representing `\.{x[][]}', which has never yet
6075 occurred; its |type| field is |undefined|, and its |value| field is
6076 undefined. We have |name_type(qq1)=attr|, |attr_loc(qq1)=collective_subscript|,
6077 |parent(qq1)=q1|, and |link(qq1)=qq2|. Since |qq2| represents
6078 `\.{x[]b}', |type(qq2)=mp_unknown_boolean|; also |attr_loc(qq2)=h(b)|,
6079 |parent(qq2)=q1|, |name_type(qq2)=attr|, |link(qq2)=end_attr|.
6080 (Maybe colored lines will help untangle your picture.)
6081  Node |r| is a subscript node with |type| and |value|
6082 representing `\.{x5}'; |name_type(r)=subscr|, |subscript(r)=5.0|,
6083 and |link(r)=r1| is another subscript node. To complete the picture,
6084 see if you can guess what |link(r1)| is; give up? It's~|q1|.
6085 Furthermore |subscript(r1)=20.0|, |name_type(r1)=subscr|,
6086 |type(r1)=mp_structured|, |attr_head(r1)=qqq|, |subscr_head(r1)=qqq1|,
6087 and we finish things off with three more nodes
6088 |qqq|, |qqq1|, and |qqq2| hung onto~|r1|. (Perhaps you should start again
6089 with a larger sheet of paper.) The value of variable \.{x20b}
6090 appears in node~|qqq2|, as you can well imagine.
6091
6092 If the example in the previous paragraph doesn't make things crystal
6093 clear, a glance at some of the simpler subroutines below will reveal how
6094 things work out in practice.
6095
6096 The only really unusual thing about these conventions is the use of
6097 collective subscript attributes. The idea is to avoid repeating a lot of
6098 type information when many elements of an array are identical macros
6099 (for which distinct values need not be stored) or when they don't have
6100 all of the possible attributes. Branches of the structure below collective
6101 subscript attributes do not carry actual values except for macro identifiers;
6102 branches of the structure below subscript nodes do not carry significant
6103 information in their collective subscript attributes.
6104
6105 @d attr_loc_loc(A) ((A)+2) /* where the |attr_loc| and |parent| fields are */
6106 @d attr_loc(A) info(attr_loc_loc((A))) /* hash address of this attribute */
6107 @d parent(A) link(attr_loc_loc((A))) /* pointer to |mp_structured| variable */
6108 @d subscript_loc(A) ((A)+2) /* where the |subscript| field lives */
6109 @d subscript(A) mp->mem[subscript_loc((A))].sc /* subscript of this variable */
6110 @d attr_node_size 3 /* the number of words in an attribute node */
6111 @d subscr_node_size 3 /* the number of words in a subscript node */
6112 @d collective_subscript 0 /* code for the attribute `\.{[]}' */
6113
6114 @<Initialize table...@>=
6115 attr_loc(end_attr)=hash_end+1; parent(end_attr)=null;
6116
6117 @ Variables of type \&{pair} will have values that point to four-word
6118 nodes containing two numeric values. The first of these values has
6119 |name_type=mp_x_part_sector| and the second has |name_type=mp_y_part_sector|;
6120 the |link| in the first points back to the node whose |value| points
6121 to this four-word node.
6122
6123 Variables of type \&{transform} are similar, but in this case their
6124 |value| points to a 12-word node containing six values, identified by
6125 |x_part_sector|, |y_part_sector|, |mp_xx_part_sector|, |mp_xy_part_sector|,
6126 |mp_yx_part_sector|, and |mp_yy_part_sector|.
6127 Finally, variables of type \&{color} have three values in six words
6128 identified by |mp_red_part_sector|, |mp_green_part_sector|, and |mp_blue_part_sector|.
6129
6130 When an entire structured variable is saved, the |root| indication
6131 is temporarily replaced by |saved_root|.
6132
6133 Some variables have no name; they just are used for temporary storage
6134 while expressions are being evaluated. We call them {\sl capsules}.
6135
6136 @d x_part_loc(A) (A) /* where the \&{xpart} is found in a pair or transform node */
6137 @d y_part_loc(A) ((A)+2) /* where the \&{ypart} is found in a pair or transform node */
6138 @d xx_part_loc(A) ((A)+4) /* where the \&{xxpart} is found in a transform node */
6139 @d xy_part_loc(A) ((A)+6) /* where the \&{xypart} is found in a transform node */
6140 @d yx_part_loc(A) ((A)+8) /* where the \&{yxpart} is found in a transform node */
6141 @d yy_part_loc(A) ((A)+10) /* where the \&{yypart} is found in a transform node */
6142 @d red_part_loc(A) (A) /* where the \&{redpart} is found in a color node */
6143 @d green_part_loc(A) ((A)+2) /* where the \&{greenpart} is found in a color node */
6144 @d blue_part_loc(A) ((A)+4) /* where the \&{bluepart} is found in a color node */
6145 @d cyan_part_loc(A) (A) /* where the \&{cyanpart} is found in a color node */
6146 @d magenta_part_loc(A) ((A)+2) /* where the \&{magentapart} is found in a color node */
6147 @d yellow_part_loc(A) ((A)+4) /* where the \&{yellowpart} is found in a color node */
6148 @d black_part_loc(A) ((A)+6) /* where the \&{blackpart} is found in a color node */
6149 @d grey_part_loc(A) (A) /* where the \&{greypart} is found in a color node */
6150 @#
6151 @d pair_node_size 4 /* the number of words in a pair node */
6152 @d transform_node_size 12 /* the number of words in a transform node */
6153 @d color_node_size 6 /* the number of words in a color node */
6154 @d cmykcolor_node_size 8 /* the number of words in a color node */
6155
6156 @<Glob...@>=
6157 small_number big_node_size[mp_pair_type+1];
6158 small_number sector0[mp_pair_type+1];
6159 small_number sector_offset[mp_black_part_sector+1];
6160
6161 @ The |sector0| array gives for each big node type, |name_type| values
6162 for its first subfield; the |sector_offset| array gives for each
6163 |name_type| value, the offset from the first subfield in words;
6164 and the |big_node_size| array gives the size in words for each type of
6165 big node.
6166
6167 @<Set init...@>=
6168 mp->big_node_size[mp_transform_type]=transform_node_size;
6169 mp->big_node_size[mp_pair_type]=pair_node_size;
6170 mp->big_node_size[mp_color_type]=color_node_size;
6171 mp->big_node_size[mp_cmykcolor_type]=cmykcolor_node_size;
6172 mp->sector0[mp_transform_type]=mp_x_part_sector;
6173 mp->sector0[mp_pair_type]=mp_x_part_sector;
6174 mp->sector0[mp_color_type]=mp_red_part_sector;
6175 mp->sector0[mp_cmykcolor_type]=mp_cyan_part_sector;
6176 for (k=mp_x_part_sector;k<= mp_yy_part_sector;k++ ) {
6177   mp->sector_offset[k]=2*(k-mp_x_part_sector);
6178 }
6179 for (k=mp_red_part_sector;k<= mp_blue_part_sector ; k++) {
6180   mp->sector_offset[k]=2*(k-mp_red_part_sector);
6181 }
6182 for (k=mp_cyan_part_sector;k<= mp_black_part_sector;k++ ) {
6183   mp->sector_offset[k]=2*(k-mp_cyan_part_sector);
6184 }
6185
6186 @ If |type(p)=mp_pair_type| or |mp_transform_type| and if |value(p)=null|, the
6187 procedure call |init_big_node(p)| will allocate a pair or transform node
6188 for~|p|.  The individual parts of such nodes are initially of type
6189 |mp_independent|.
6190
6191 @c 
6192 void mp_init_big_node (MP mp,pointer p) {
6193   pointer q; /* the new node */
6194   small_number s; /* its size */
6195   s=mp->big_node_size[type(p)]; q=mp_get_node(mp, s);
6196   do {  
6197     s=s-2; 
6198     @<Make variable |q+s| newly independent@>;
6199     name_type(q+s)=halfp(s)+mp->sector0[type(p)]; 
6200     link(q+s)=null;
6201   } while (s!=0);
6202   link(q)=p; value(p)=q;
6203 }
6204
6205 @ The |id_transform| function creates a capsule for the
6206 identity transformation.
6207
6208 @c 
6209 pointer mp_id_transform (MP mp) {
6210   pointer p,q,r; /* list manipulation registers */
6211   p=mp_get_node(mp, value_node_size); type(p)=mp_transform_type;
6212   name_type(p)=mp_capsule; value(p)=null; mp_init_big_node(mp, p); q=value(p);
6213   r=q+transform_node_size;
6214   do {  
6215     r=r-2;
6216     type(r)=mp_known; value(r)=0;
6217   } while (r!=q);
6218   value(xx_part_loc(q))=unity; 
6219   value(yy_part_loc(q))=unity;
6220   return p;
6221 }
6222
6223 @ Tokens are of type |tag_token| when they first appear, but they point
6224 to |null| until they are first used as the root of a variable.
6225 The following subroutine establishes the root node on such grand occasions.
6226
6227 @c 
6228 void mp_new_root (MP mp,pointer x) {
6229   pointer p; /* the new node */
6230   p=mp_get_node(mp, value_node_size); type(p)=undefined; name_type(p)=mp_root;
6231   link(p)=x; equiv(x)=p;
6232 }
6233
6234 @ These conventions for variable representation are illustrated by the
6235 |print_variable_name| routine, which displays the full name of a
6236 variable given only a pointer to its two-word value packet.
6237
6238 @<Declarations@>=
6239 void mp_print_variable_name (MP mp, pointer p);
6240
6241 @ @c 
6242 void mp_print_variable_name (MP mp, pointer p) {
6243   pointer q; /* a token list that will name the variable's suffix */
6244   pointer r; /* temporary for token list creation */
6245   while ( name_type(p)>=mp_x_part_sector ) {
6246     @<Preface the output with a part specifier; |return| in the
6247       case of a capsule@>;
6248   }
6249   q=null;
6250   while ( name_type(p)>mp_saved_root ) {
6251     @<Ascend one level, pushing a token onto list |q|
6252      and replacing |p| by its parent@>;
6253   }
6254   r=mp_get_avail(mp); info(r)=link(p); link(r)=q;
6255   if ( name_type(p)==mp_saved_root ) mp_print(mp, "(SAVED)");
6256 @.SAVED@>
6257   mp_show_token_list(mp, r,null,el_gordo,mp->tally); 
6258   mp_flush_token_list(mp, r);
6259 }
6260
6261 @ @<Ascend one level, pushing a token onto list |q|...@>=
6262
6263   if ( name_type(p)==mp_subscr ) { 
6264     r=mp_new_num_tok(mp, subscript(p));
6265     do {  
6266       p=link(p);
6267     } while (name_type(p)!=mp_attr);
6268   } else if ( name_type(p)==mp_structured_root ) {
6269     p=link(p); goto FOUND;
6270   } else { 
6271     if ( name_type(p)!=mp_attr ) mp_confusion(mp, "var");
6272 @:this can't happen var}{\quad var@>
6273     r=mp_get_avail(mp); info(r)=attr_loc(p);
6274   }
6275   link(r)=q; q=r;
6276 FOUND:  
6277   p=parent(p);
6278 }
6279
6280 @ @<Preface the output with a part specifier...@>=
6281 { switch (name_type(p)) {
6282   case mp_x_part_sector: mp_print_char(mp, 'x'); break;
6283   case mp_y_part_sector: mp_print_char(mp, 'y'); break;
6284   case mp_xx_part_sector: mp_print(mp, "xx"); break;
6285   case mp_xy_part_sector: mp_print(mp, "xy"); break;
6286   case mp_yx_part_sector: mp_print(mp, "yx"); break;
6287   case mp_yy_part_sector: mp_print(mp, "yy"); break;
6288   case mp_red_part_sector: mp_print(mp, "red"); break;
6289   case mp_green_part_sector: mp_print(mp, "green"); break;
6290   case mp_blue_part_sector: mp_print(mp, "blue"); break;
6291   case mp_cyan_part_sector: mp_print(mp, "cyan"); break;
6292   case mp_magenta_part_sector: mp_print(mp, "magenta"); break;
6293   case mp_yellow_part_sector: mp_print(mp, "yellow"); break;
6294   case mp_black_part_sector: mp_print(mp, "black"); break;
6295   case mp_grey_part_sector: mp_print(mp, "grey"); break;
6296   case mp_capsule: 
6297     mp_print(mp, "%CAPSULE"); mp_print_int(mp, p-null); return;
6298     break;
6299 @.CAPSULE@>
6300   } /* there are no other cases */
6301   mp_print(mp, "part "); 
6302   p=link(p-mp->sector_offset[name_type(p)]);
6303 }
6304
6305 @ The |interesting| function returns |true| if a given variable is not
6306 in a capsule, or if the user wants to trace capsules.
6307
6308 @c 
6309 boolean mp_interesting (MP mp,pointer p) {
6310   small_number t; /* a |name_type| */
6311   if ( mp->internal[mp_tracing_capsules]>0 ) {
6312     return true;
6313   } else { 
6314     t=name_type(p);
6315     if ( t>=mp_x_part_sector ) if ( t!=mp_capsule )
6316       t=name_type(link(p-mp->sector_offset[t]));
6317     return (t!=mp_capsule);
6318   }
6319 }
6320
6321 @ Now here is a subroutine that converts an unstructured type into an
6322 equivalent structured type, by inserting a |mp_structured| node that is
6323 capable of growing. This operation is done only when |name_type(p)=root|,
6324 |subscr|, or |attr|.
6325
6326 The procedure returns a pointer to the new node that has taken node~|p|'s
6327 place in the structure. Node~|p| itself does not move, nor are its
6328 |value| or |type| fields changed in any way.
6329
6330 @c 
6331 pointer mp_new_structure (MP mp,pointer p) {
6332   pointer q,r=0; /* list manipulation registers */
6333   switch (name_type(p)) {
6334   case mp_root: 
6335     q=link(p); r=mp_get_node(mp, value_node_size); equiv(q)=r;
6336     break;
6337   case mp_subscr: 
6338     @<Link a new subscript node |r| in place of node |p|@>;
6339     break;
6340   case mp_attr: 
6341     @<Link a new attribute node |r| in place of node |p|@>;
6342     break;
6343   default: 
6344     mp_confusion(mp, "struct");
6345 @:this can't happen struct}{\quad struct@>
6346     break;
6347   }
6348   link(r)=link(p); type(r)=mp_structured; name_type(r)=name_type(p);
6349   attr_head(r)=p; name_type(p)=mp_structured_root;
6350   q=mp_get_node(mp, attr_node_size); link(p)=q; subscr_head(r)=q;
6351   parent(q)=r; type(q)=undefined; name_type(q)=mp_attr; link(q)=end_attr;
6352   attr_loc(q)=collective_subscript; 
6353   return r;
6354 };
6355
6356 @ @<Link a new subscript node |r| in place of node |p|@>=
6357
6358   q=p;
6359   do {  
6360     q=link(q);
6361   } while (name_type(q)!=mp_attr);
6362   q=parent(q); r=subscr_head_loc(q); /* |link(r)=subscr_head(q)| */
6363   do {  
6364     q=r; r=link(r);
6365   } while (r!=p);
6366   r=mp_get_node(mp, subscr_node_size);
6367   link(q)=r; subscript(r)=subscript(p);
6368 }
6369
6370 @ If the attribute is |collective_subscript|, there are two pointers to
6371 node~|p|, so we must change both of them.
6372
6373 @<Link a new attribute node |r| in place of node |p|@>=
6374
6375   q=parent(p); r=attr_head(q);
6376   do {  
6377     q=r; r=link(r);
6378   } while (r!=p);
6379   r=mp_get_node(mp, attr_node_size); link(q)=r;
6380   mp->mem[attr_loc_loc(r)]=mp->mem[attr_loc_loc(p)]; /* copy |attr_loc| and |parent| */
6381   if ( attr_loc(p)==collective_subscript ) { 
6382     q=subscr_head_loc(parent(p));
6383     while ( link(q)!=p ) q=link(q);
6384     link(q)=r;
6385   }
6386 }
6387
6388 @ The |find_variable| routine is given a pointer~|t| to a nonempty token
6389 list of suffixes; it returns a pointer to the corresponding two-word
6390 value. For example, if |t| points to token \.x followed by a numeric
6391 token containing the value~7, |find_variable| finds where the value of
6392 \.{x7} is stored in memory. This may seem a simple task, and it
6393 usually is, except when \.{x7} has never been referenced before.
6394 Indeed, \.x may never have even been subscripted before; complexities
6395 arise with respect to updating the collective subscript information.
6396
6397 If a macro type is detected anywhere along path~|t|, or if the first
6398 item on |t| isn't a |tag_token|, the value |null| is returned.
6399 Otherwise |p| will be a non-null pointer to a node such that
6400 |undefined<type(p)<mp_structured|.
6401
6402 @d abort_find { return null; }
6403
6404 @c 
6405 pointer mp_find_variable (MP mp,pointer t) {
6406   pointer p,q,r,s; /* nodes in the ``value'' line */
6407   pointer pp,qq,rr,ss; /* nodes in the ``collective'' line */
6408   integer n; /* subscript or attribute */
6409   memory_word save_word; /* temporary storage for a word of |mem| */
6410 @^inner loop@>
6411   p=info(t); t=link(t);
6412   if ( (eq_type(p) % outer_tag) != tag_token ) abort_find;
6413   if ( equiv(p)==null ) mp_new_root(mp, p);
6414   p=equiv(p); pp=p;
6415   while ( t!=null ) { 
6416     @<Make sure that both nodes |p| and |pp| are of |mp_structured| type@>;
6417     if ( t<mp->hi_mem_min ) {
6418       @<Descend one level for the subscript |value(t)|@>
6419     } else {
6420       @<Descend one level for the attribute |info(t)|@>;
6421     }
6422     t=link(t);
6423   }
6424   if ( type(pp)>=mp_structured ) {
6425     if ( type(pp)==mp_structured ) pp=attr_head(pp); else abort_find;
6426   }
6427   if ( type(p)==mp_structured ) p=attr_head(p);
6428   if ( type(p)==undefined ) { 
6429     if ( type(pp)==undefined ) { type(pp)=mp_numeric_type; value(pp)=null; };
6430     type(p)=type(pp); value(p)=null;
6431   };
6432   return p;
6433 }
6434
6435 @ Although |pp| and |p| begin together, they diverge when a subscript occurs;
6436 |pp|~stays in the collective line while |p|~goes through actual subscript
6437 values.
6438
6439 @<Make sure that both nodes |p| and |pp|...@>=
6440 if ( type(pp)!=mp_structured ) { 
6441   if ( type(pp)>mp_structured ) abort_find;
6442   ss=mp_new_structure(mp, pp);
6443   if ( p==pp ) p=ss;
6444   pp=ss;
6445 }; /* now |type(pp)=mp_structured| */
6446 if ( type(p)!=mp_structured ) /* it cannot be |>mp_structured| */
6447   p=mp_new_structure(mp, p) /* now |type(p)=mp_structured| */
6448
6449 @ We want this part of the program to be reasonably fast, in case there are
6450 @^inner loop@>
6451 lots of subscripts at the same level of the data structure. Therefore
6452 we store an ``infinite'' value in the word that appears at the end of the
6453 subscript list, even though that word isn't part of a subscript node.
6454
6455 @<Descend one level for the subscript |value(t)|@>=
6456
6457   n=value(t);
6458   pp=link(attr_head(pp)); /* now |attr_loc(pp)=collective_subscript| */
6459   q=link(attr_head(p)); save_word=mp->mem[subscript_loc(q)];
6460   subscript(q)=el_gordo; s=subscr_head_loc(p); /* |link(s)=subscr_head(p)| */
6461   do {  
6462     r=s; s=link(s);
6463   } while (n>subscript(s));
6464   if ( n==subscript(s) ) {
6465     p=s;
6466   } else { 
6467     p=mp_get_node(mp, subscr_node_size); link(r)=p; link(p)=s;
6468     subscript(p)=n; name_type(p)=mp_subscr; type(p)=undefined;
6469   }
6470   mp->mem[subscript_loc(q)]=save_word;
6471 }
6472
6473 @ @<Descend one level for the attribute |info(t)|@>=
6474
6475   n=info(t);
6476   ss=attr_head(pp);
6477   do {  
6478     rr=ss; ss=link(ss);
6479   } while (n>attr_loc(ss));
6480   if ( n<attr_loc(ss) ) { 
6481     qq=mp_get_node(mp, attr_node_size); link(rr)=qq; link(qq)=ss;
6482     attr_loc(qq)=n; name_type(qq)=mp_attr; type(qq)=undefined;
6483     parent(qq)=pp; ss=qq;
6484   }
6485   if ( p==pp ) { 
6486     p=ss; pp=ss;
6487   } else { 
6488     pp=ss; s=attr_head(p);
6489     do {  
6490       r=s; s=link(s);
6491     } while (n>attr_loc(s));
6492     if ( n==attr_loc(s) ) {
6493       p=s;
6494     } else { 
6495       q=mp_get_node(mp, attr_node_size); link(r)=q; link(q)=s;
6496       attr_loc(q)=n; name_type(q)=mp_attr; type(q)=undefined;
6497       parent(q)=p; p=q;
6498     }
6499   }
6500 }
6501
6502 @ Variables lose their former values when they appear in a type declaration,
6503 or when they are defined to be macros or \&{let} equal to something else.
6504 A subroutine will be defined later that recycles the storage associated
6505 with any particular |type| or |value|; our goal now is to study a higher
6506 level process called |flush_variable|, which selectively frees parts of a
6507 variable structure.
6508
6509 This routine has some complexity because of examples such as
6510 `\hbox{\tt numeric x[]a[]b}'
6511 which recycles all variables of the form \.{x[i]a[j]b} (and no others), while
6512 `\hbox{\tt vardef x[]a[]=...}'
6513 discards all variables of the form \.{x[i]a[j]} followed by an arbitrary
6514 suffix, except for the collective node \.{x[]a[]} itself. The obvious way
6515 to handle such examples is to use recursion; so that's what we~do.
6516 @^recursion@>
6517
6518 Parameter |p| points to the root information of the variable;
6519 parameter |t| points to a list of one-word nodes that represent
6520 suffixes, with |info=collective_subscript| for subscripts.
6521
6522 @<Declarations@>=
6523 @<Declare subroutines for printing expressions@>
6524 @<Declare basic dependency-list subroutines@>
6525 @<Declare the recycling subroutines@>
6526 void mp_flush_cur_exp (MP mp,scaled v) ;
6527 @<Declare the procedure called |flush_below_variable|@>
6528
6529 @ @c 
6530 void mp_flush_variable (MP mp,pointer p, pointer t, boolean discard_suffixes) {
6531   pointer q,r; /* list manipulation */
6532   halfword n; /* attribute to match */
6533   while ( t!=null ) { 
6534     if ( type(p)!=mp_structured ) return;
6535     n=info(t); t=link(t);
6536     if ( n==collective_subscript ) { 
6537       r=subscr_head_loc(p); q=link(r); /* |q=subscr_head(p)| */
6538       while ( name_type(q)==mp_subscr ){ 
6539         mp_flush_variable(mp, q,t,discard_suffixes);
6540         if ( t==null ) {
6541           if ( type(q)==mp_structured ) r=q;
6542           else  { link(r)=link(q); mp_free_node(mp, q,subscr_node_size);   }
6543         } else {
6544           r=q;
6545         }
6546         q=link(r);
6547       }
6548     }
6549     p=attr_head(p);
6550     do {  
6551       r=p; p=link(p);
6552     } while (attr_loc(p)<n);
6553     if ( attr_loc(p)!=n ) return;
6554   }
6555   if ( discard_suffixes ) {
6556     mp_flush_below_variable(mp, p);
6557   } else { 
6558     if ( type(p)==mp_structured ) p=attr_head(p);
6559     mp_recycle_value(mp, p);
6560   }
6561 }
6562
6563 @ The next procedure is simpler; it wipes out everything but |p| itself,
6564 which becomes undefined.
6565
6566 @<Declare the procedure called |flush_below_variable|@>=
6567 void mp_flush_below_variable (MP mp, pointer p);
6568
6569 @ @c
6570 void mp_flush_below_variable (MP mp,pointer p) {
6571    pointer q,r; /* list manipulation registers */
6572   if ( type(p)!=mp_structured ) {
6573     mp_recycle_value(mp, p); /* this sets |type(p)=undefined| */
6574   } else { 
6575     q=subscr_head(p);
6576     while ( name_type(q)==mp_subscr ) { 
6577       mp_flush_below_variable(mp, q); r=q; q=link(q);
6578       mp_free_node(mp, r,subscr_node_size);
6579     }
6580     r=attr_head(p); q=link(r); mp_recycle_value(mp, r);
6581     if ( name_type(p)<=mp_saved_root ) mp_free_node(mp, r,value_node_size);
6582     else mp_free_node(mp, r,subscr_node_size);
6583     /* we assume that |subscr_node_size=attr_node_size| */
6584     do {  
6585       mp_flush_below_variable(mp, q); r=q; q=link(q); mp_free_node(mp, r,attr_node_size);
6586     } while (q!=end_attr);
6587     type(p)=undefined;
6588   }
6589 }
6590
6591 @ Just before assigning a new value to a variable, we will recycle the
6592 old value and make the old value undefined. The |und_type| routine
6593 determines what type of undefined value should be given, based on
6594 the current type before recycling.
6595
6596 @c 
6597 small_number mp_und_type (MP mp,pointer p) { 
6598   switch (type(p)) {
6599   case undefined: case mp_vacuous:
6600     return undefined;
6601   case mp_boolean_type: case mp_unknown_boolean:
6602     return mp_unknown_boolean;
6603   case mp_string_type: case mp_unknown_string:
6604     return mp_unknown_string;
6605   case mp_pen_type: case mp_unknown_pen:
6606     return mp_unknown_pen;
6607   case mp_path_type: case mp_unknown_path:
6608     return mp_unknown_path;
6609   case mp_picture_type: case mp_unknown_picture:
6610     return mp_unknown_picture;
6611   case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
6612   case mp_pair_type: case mp_numeric_type: 
6613     return type(p);
6614   case mp_known: case mp_dependent: case mp_proto_dependent: case mp_independent:
6615     return mp_numeric_type;
6616   } /* there are no other cases */
6617   return 0;
6618 }
6619
6620 @ The |clear_symbol| routine is used when we want to redefine the equivalent
6621 of a symbolic token. It must remove any variable structure or macro
6622 definition that is currently attached to that symbol. If the |saving|
6623 parameter is true, a subsidiary structure is saved instead of destroyed.
6624
6625 @c 
6626 void mp_clear_symbol (MP mp,pointer p, boolean saving) {
6627   pointer q; /* |equiv(p)| */
6628   q=equiv(p);
6629   switch (eq_type(p) % outer_tag)  {
6630   case defined_macro:
6631   case secondary_primary_macro:
6632   case tertiary_secondary_macro:
6633   case expression_tertiary_macro: 
6634     if ( ! saving ) mp_delete_mac_ref(mp, q);
6635     break;
6636   case tag_token:
6637     if ( q!=null ) {
6638       if ( saving ) {
6639         name_type(q)=mp_saved_root;
6640       } else { 
6641         mp_flush_below_variable(mp, q); mp_free_node(mp,q,value_node_size); 
6642       }
6643     }
6644     break;
6645   default:
6646     break;
6647   }
6648   mp->eqtb[p]=mp->eqtb[frozen_undefined];
6649 };
6650
6651 @* \[16] Saving and restoring equivalents.
6652 The nested structure given by \&{begingroup} and \&{endgroup}
6653 allows |eqtb| entries to be saved and restored, so that temporary changes
6654 can be made without difficulty.  When the user requests a current value to
6655 be saved, \MP\ puts that value into its ``save stack.'' An appearance of
6656 \&{endgroup} ultimately causes the old values to be removed from the save
6657 stack and put back in their former places.
6658
6659 The save stack is a linked list containing three kinds of entries,
6660 distinguished by their |info| fields. If |p| points to a saved item,
6661 then
6662
6663 \smallskip\hang
6664 |info(p)=0| stands for a group boundary; each \&{begingroup} contributes
6665 such an item to the save stack and each \&{endgroup} cuts back the stack
6666 until the most recent such entry has been removed.
6667
6668 \smallskip\hang
6669 |info(p)=q|, where |1<=q<=hash_end|, means that |mem[p+1]| holds the former
6670 contents of |eqtb[q]|. Such save stack entries are generated by \&{save}
6671 commands or suitable \&{interim} commands.
6672
6673 \smallskip\hang
6674 |info(p)=hash_end+q|, where |q>0|, means that |value(p)| is a |scaled|
6675 integer to be restored to internal parameter number~|q|. Such entries
6676 are generated by \&{interim} commands.
6677
6678 \smallskip\noindent
6679 The global variable |save_ptr| points to the top item on the save stack.
6680
6681 @d save_node_size 2 /* number of words per non-boundary save-stack node */
6682 @d saved_equiv(A) mp->mem[(A)+1].hh /* where an |eqtb| entry gets saved */
6683 @d save_boundary_item(A) { (A)=mp_get_avail(mp); info((A))=0;
6684   link((A))=mp->save_ptr; mp->save_ptr=(A);
6685   }
6686
6687 @<Glob...@>=
6688 pointer save_ptr; /* the most recently saved item */
6689
6690 @ @<Set init...@>=mp->save_ptr=null;
6691
6692 @ The |save_variable| routine is given a hash address |q|; it salts this
6693 address in the save stack, together with its current equivalent,
6694 then makes token~|q| behave as though it were brand new.
6695
6696 Nothing is stacked when |save_ptr=null|, however; there's no way to remove
6697 things from the stack when the program is not inside a group, so there's
6698 no point in wasting the space.
6699
6700 @c void mp_save_variable (MP mp,pointer q) {
6701   pointer p; /* temporary register */
6702   if ( mp->save_ptr!=null ){ 
6703     p=mp_get_node(mp, save_node_size); info(p)=q; link(p)=mp->save_ptr;
6704     saved_equiv(p)=mp->eqtb[q]; mp->save_ptr=p;
6705   }
6706   mp_clear_symbol(mp, q,(mp->save_ptr!=null));
6707 }
6708
6709 @ Similarly, |save_internal| is given the location |q| of an internal
6710 quantity like |mp_tracing_pens|. It creates a save stack entry of the
6711 third kind.
6712
6713 @c void mp_save_internal (MP mp,halfword q) {
6714   pointer p; /* new item for the save stack */
6715   if ( mp->save_ptr!=null ){ 
6716      p=mp_get_node(mp, save_node_size); info(p)=hash_end+q;
6717     link(p)=mp->save_ptr; value(p)=mp->internal[q]; mp->save_ptr=p;
6718   }
6719 }
6720
6721 @ At the end of a group, the |unsave| routine restores all of the saved
6722 equivalents in reverse order. This routine will be called only when there
6723 is at least one boundary item on the save stack.
6724
6725 @c 
6726 void mp_unsave (MP mp) {
6727   pointer q; /* index to saved item */
6728   pointer p; /* temporary register */
6729   while ( info(mp->save_ptr)!=0 ) {
6730     q=info(mp->save_ptr);
6731     if ( q>hash_end ) {
6732       if ( mp->internal[mp_tracing_restores]>0 ) {
6733         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6734         mp_print(mp, mp->int_name[q-(hash_end)]); mp_print_char(mp, '=');
6735         mp_print_scaled(mp, value(mp->save_ptr)); mp_print_char(mp, '}');
6736         mp_end_diagnostic(mp, false);
6737       }
6738       mp->internal[q-(hash_end)]=value(mp->save_ptr);
6739     } else { 
6740       if ( mp->internal[mp_tracing_restores]>0 ) {
6741         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6742         mp_print_text(q); mp_print_char(mp, '}');
6743         mp_end_diagnostic(mp, false);
6744       }
6745       mp_clear_symbol(mp, q,false);
6746       mp->eqtb[q]=saved_equiv(mp->save_ptr);
6747       if ( eq_type(q) % outer_tag==tag_token ) {
6748         p=equiv(q);
6749         if ( p!=null ) name_type(p)=mp_root;
6750       }
6751     }
6752     p=link(mp->save_ptr); 
6753     mp_free_node(mp, mp->save_ptr,save_node_size); mp->save_ptr=p;
6754   }
6755   p=link(mp->save_ptr); free_avail(mp->save_ptr); mp->save_ptr=p;
6756 }
6757
6758 @* \[17] Data structures for paths.
6759 When a \MP\ user specifies a path, \MP\ will create a list of knots
6760 and control points for the associated cubic spline curves. If the
6761 knots are $z_0$, $z_1$, \dots, $z_n$, there are control points
6762 $z_k^+$ and $z_{k+1}^-$ such that the cubic splines between knots
6763 $z_k$ and $z_{k+1}$ are defined by B\'ezier's formula
6764 @:Bezier}{B\'ezier, Pierre Etienne@>
6765 $$\eqalign{z(t)&=B(z_k,z_k^+,z_{k+1}^-,z_{k+1};t)\cr
6766 &=(1-t)^3z_k+3(1-t)^2tz_k^++3(1-t)t^2z_{k+1}^-+t^3z_{k+1}\cr}$$
6767 for |0<=t<=1|.
6768
6769 There is a 8-word node for each knot $z_k$, containing one word of
6770 control information and six words for the |x| and |y| coordinates of
6771 $z_k^-$ and $z_k$ and~$z_k^+$. The control information appears in the
6772 |left_type| and |right_type| fields, which each occupy a quarter of
6773 the first word in the node; they specify properties of the curve as it
6774 enters and leaves the knot. There's also a halfword |link| field,
6775 which points to the following knot, and a final supplementary word (of
6776 which only a quarter is used).
6777
6778 If the path is a closed contour, knots 0 and |n| are identical;
6779 i.e., the |link| in knot |n-1| points to knot~0. But if the path
6780 is not closed, the |left_type| of knot~0 and the |right_type| of knot~|n|
6781 are equal to |endpoint|. In the latter case the |link| in knot~|n| points
6782 to knot~0, and the control points $z_0^-$ and $z_n^+$ are not used.
6783
6784 @d left_type(A)   mp->mem[(A)].hh.b0 /* characterizes the path entering this knot */
6785 @d right_type(A)   mp->mem[(A)].hh.b1 /* characterizes the path leaving this knot */
6786 @d x_coord(A)   mp->mem[(A)+1].sc /* the |x| coordinate of this knot */
6787 @d y_coord(A)   mp->mem[(A)+2].sc /* the |y| coordinate of this knot */
6788 @d left_x(A)   mp->mem[(A)+3].sc /* the |x| coordinate of previous control point */
6789 @d left_y(A)   mp->mem[(A)+4].sc /* the |y| coordinate of previous control point */
6790 @d right_x(A)   mp->mem[(A)+5].sc /* the |x| coordinate of next control point */
6791 @d right_y(A)   mp->mem[(A)+6].sc /* the |y| coordinate of next control point */
6792 @d x_loc(A)   ((A)+1) /* where the |x| coordinate is stored in a knot */
6793 @d y_loc(A)   ((A)+2) /* where the |y| coordinate is stored in a knot */
6794 @d knot_coord(A)   mp->mem[(A)].sc /* |x| or |y| coordinate given |x_loc| or |y_loc| */
6795 @d left_coord(A)   mp->mem[(A)+2].sc
6796   /* coordinate of previous control point given |x_loc| or |y_loc| */
6797 @d right_coord(A)   mp->mem[(A)+4].sc
6798   /* coordinate of next control point given |x_loc| or |y_loc| */
6799 @d knot_node_size 8 /* number of words in a knot node */
6800
6801 @<Types...@>=
6802 enum mp_knot_type {
6803  mp_endpoint=0, /* |left_type| at path beginning and |right_type| at path end */
6804  mp_explicit, /* |left_type| or |right_type| when control points are known */
6805  mp_given, /* |left_type| or |right_type| when a direction is given */
6806  mp_curl, /* |left_type| or |right_type| when a curl is desired */
6807  mp_open, /* |left_type| or |right_type| when \MP\ should choose the direction */
6808  mp_end_cycle
6809 } ;
6810
6811 @ Before the B\'ezier control points have been calculated, the memory
6812 space they will ultimately occupy is taken up by information that can be
6813 used to compute them. There are four cases:
6814
6815 \yskip
6816 \textindent{$\bullet$} If |right_type=mp_open|, the curve should leave
6817 the knot in the same direction it entered; \MP\ will figure out a
6818 suitable direction.
6819
6820 \yskip
6821 \textindent{$\bullet$} If |right_type=mp_curl|, the curve should leave the
6822 knot in a direction depending on the angle at which it enters the next
6823 knot and on the curl parameter stored in |right_curl|.
6824
6825 \yskip
6826 \textindent{$\bullet$} If |right_type=mp_given|, the curve should leave the
6827 knot in a nonzero direction stored as an |angle| in |right_given|.
6828
6829 \yskip
6830 \textindent{$\bullet$} If |right_type=mp_explicit|, the B\'ezier control
6831 point for leaving this knot has already been computed; it is in the
6832 |right_x| and |right_y| fields.
6833
6834 \yskip\noindent
6835 The rules for |left_type| are similar, but they refer to the curve entering
6836 the knot, and to \\{left} fields instead of \\{right} fields.
6837
6838 Non-|explicit| control points will be chosen based on ``tension'' parameters
6839 in the |left_tension| and |right_tension| fields. The
6840 `\&{atleast}' option is represented by negative tension values.
6841 @:at_least_}{\&{atleast} primitive@>
6842
6843 For example, the \MP\ path specification
6844 $$\.{z0..z1..tension atleast 1..\{curl 2\}z2..z3\{-1,-2\}..tension
6845   3 and 4..p},$$
6846 where \.p is the path `\.{z4..controls z45 and z54..z5}', will be represented
6847 by the six knots
6848 \def\lodash{\hbox to 1.1em{\thinspace\hrulefill\thinspace}}
6849 $$\vbox{\halign{#\hfil&&\qquad#\hfil\cr
6850 |left_type|&\\{left} info&|x_coord,y_coord|&|right_type|&\\{right} info\cr
6851 \noalign{\yskip}
6852 |endpoint|&\lodash$,\,$\lodash&$x_0,y_0$&|curl|&$1.0,1.0$\cr
6853 |open|&\lodash$,1.0$&$x_1,y_1$&|open|&\lodash$,-1.0$\cr
6854 |curl|&$2.0,-1.0$&$x_2,y_2$&|curl|&$2.0,1.0$\cr
6855 |given|&$d,1.0$&$x_3,y_3$&|given|&$d,3.0$\cr
6856 |open|&\lodash$,4.0$&$x_4,y_4$&|explicit|&$x_{45},y_{45}$\cr
6857 |explicit|&$x_{54},y_{54}$&$x_5,y_5$&|endpoint|&\lodash$,\,$\lodash\cr}}$$
6858 Here |d| is the |angle| obtained by calling |n_arg(-unity,-two)|.
6859 Of course, this example is more complicated than anything a normal user
6860 would ever write.
6861
6862 These types must satisfy certain restrictions because of the form of \MP's
6863 path syntax:
6864 (i)~|open| type never appears in the same node together with |endpoint|,
6865 |given|, or |curl|.
6866 (ii)~The |right_type| of a node is |explicit| if and only if the
6867 |left_type| of the following node is |explicit|.
6868 (iii)~|endpoint| types occur only at the ends, as mentioned above.
6869
6870 @d left_curl left_x /* curl information when entering this knot */
6871 @d left_given left_x /* given direction when entering this knot */
6872 @d left_tension left_y /* tension information when entering this knot */
6873 @d right_curl right_x /* curl information when leaving this knot */
6874 @d right_given right_x /* given direction when leaving this knot */
6875 @d right_tension right_y /* tension information when leaving this knot */
6876
6877 @ Knots can be user-supplied, or they can be created by program code,
6878 like the |split_cubic| function, or |copy_path|. The distinction is
6879 needed for the cleanup routine that runs after |split_cubic|, because
6880 it should only delete knots it has previously inserted, and never
6881 anything that was user-supplied. In order to be able to differentiate
6882 one knot from another, we will set |originator(p):=mp_metapost_user| when
6883 it appeared in the actual metapost program, and
6884 |originator(p):=mp_program_code| in all other cases.
6885
6886 @d originator(A)   mp->mem[(A)+7].hh.b0 /* the creator of this knot */
6887
6888 @<Types...@>=
6889 enum {
6890   mp_program_code=0, /* not created by a user */
6891   mp_metapost_user, /* created by a user */
6892 };
6893
6894 @ Here is a routine that prints a given knot list
6895 in symbolic form. It illustrates the conventions discussed above,
6896 and checks for anomalies that might arise while \MP\ is being debugged.
6897
6898 @<Declare subroutines for printing expressions@>=
6899 void mp_pr_path (MP mp,pointer h);
6900
6901 @ @c
6902 void mp_pr_path (MP mp,pointer h) {
6903   pointer p,q; /* for list traversal */
6904   p=h;
6905   do {  
6906     q=link(p);
6907     if ( (p==null)||(q==null) ) { 
6908       mp_print_nl(mp, "???"); return; /* this won't happen */
6909 @.???@>
6910     }
6911     @<Print information for adjacent knots |p| and |q|@>;
6912   DONE1:
6913     p=q;
6914     if ( (p!=h)||(left_type(h)!=mp_endpoint) ) {
6915       @<Print two dots, followed by |given| or |curl| if present@>;
6916     }
6917   } while (p!=h);
6918   if ( left_type(h)!=mp_endpoint ) 
6919     mp_print(mp, "cycle");
6920 }
6921
6922 @ @<Print information for adjacent knots...@>=
6923 mp_print_two(mp, x_coord(p),y_coord(p));
6924 switch (right_type(p)) {
6925 case mp_endpoint: 
6926   if ( left_type(p)==mp_open ) mp_print(mp, "{open?}"); /* can't happen */
6927 @.open?@>
6928   if ( (left_type(q)!=mp_endpoint)||(q!=h) ) q=null; /* force an error */
6929   goto DONE1;
6930   break;
6931 case mp_explicit: 
6932   @<Print control points between |p| and |q|, then |goto done1|@>;
6933   break;
6934 case mp_open: 
6935   @<Print information for a curve that begins |open|@>;
6936   break;
6937 case mp_curl:
6938 case mp_given: 
6939   @<Print information for a curve that begins |curl| or |given|@>;
6940   break;
6941 default:
6942   mp_print(mp, "???"); /* can't happen */
6943 @.???@>
6944   break;
6945 }
6946 if ( left_type(q)<=mp_explicit ) {
6947   mp_print(mp, "..control?"); /* can't happen */
6948 @.control?@>
6949 } else if ( (right_tension(p)!=unity)||(left_tension(q)!=unity) ) {
6950   @<Print tension between |p| and |q|@>;
6951 }
6952
6953 @ Since |n_sin_cos| produces |fraction| results, which we will print as if they
6954 were |scaled|, the magnitude of a |given| direction vector will be~4096.
6955
6956 @<Print two dots...@>=
6957
6958   mp_print_nl(mp, " ..");
6959   if ( left_type(p)==mp_given ) { 
6960     mp_n_sin_cos(mp, left_given(p)); mp_print_char(mp, '{');
6961     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ',');
6962     mp_print_scaled(mp, mp->n_sin); mp_print_char(mp, '}');
6963   } else if ( left_type(p)==mp_curl ){ 
6964     mp_print(mp, "{curl "); 
6965     mp_print_scaled(mp, left_curl(p)); mp_print_char(mp, '}');
6966   }
6967 }
6968
6969 @ @<Print tension between |p| and |q|@>=
6970
6971   mp_print(mp, "..tension ");
6972   if ( right_tension(p)<0 ) mp_print(mp, "atleast");
6973   mp_print_scaled(mp, abs(right_tension(p)));
6974   if ( right_tension(p)!=left_tension(q) ){ 
6975     mp_print(mp, " and ");
6976     if ( left_tension(q)<0 ) mp_print(mp, "atleast");
6977     mp_print_scaled(mp, abs(left_tension(q)));
6978   }
6979 }
6980
6981 @ @<Print control points between |p| and |q|, then |goto done1|@>=
6982
6983   mp_print(mp, "..controls "); 
6984   mp_print_two(mp, right_x(p),right_y(p)); 
6985   mp_print(mp, " and ");
6986   if ( left_type(q)!=mp_explicit ) { 
6987     mp_print(mp, "??"); /* can't happen */
6988 @.??@>
6989   } else {
6990     mp_print_two(mp, left_x(q),left_y(q));
6991   }
6992   goto DONE1;
6993 }
6994
6995 @ @<Print information for a curve that begins |open|@>=
6996 if ( (left_type(p)!=mp_explicit)&&(left_type(p)!=mp_open) ) {
6997   mp_print(mp, "{open?}"); /* can't happen */
6998 @.open?@>
6999 }
7000
7001 @ A curl of 1 is shown explicitly, so that the user sees clearly that
7002 \MP's default curl is present.
7003
7004 The code here uses the fact that |left_curl==left_given| and
7005 |right_curl==right_given|.
7006
7007 @<Print information for a curve that begins |curl|...@>=
7008
7009   if ( left_type(p)==mp_open )  
7010     mp_print(mp, "??"); /* can't happen */
7011 @.??@>
7012   if ( right_type(p)==mp_curl ) { 
7013     mp_print(mp, "{curl "); mp_print_scaled(mp, right_curl(p));
7014   } else { 
7015     mp_n_sin_cos(mp, right_given(p)); mp_print_char(mp, '{');
7016     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ','); 
7017     mp_print_scaled(mp, mp->n_sin);
7018   }
7019   mp_print_char(mp, '}');
7020 }
7021
7022 @ It is convenient to have another version of |pr_path| that prints the path
7023 as a diagnostic message.
7024
7025 @<Declare subroutines for printing expressions@>=
7026 void mp_print_path (MP mp,pointer h, char *s, boolean nuline) { 
7027   mp_print_diagnostic(mp, "Path", s, nuline); mp_print_ln(mp);
7028 @.Path at line...@>
7029   mp_pr_path(mp, h);
7030   mp_end_diagnostic(mp, true);
7031 }
7032
7033 @ If we want to duplicate a knot node, we can say |copy_knot|:
7034
7035 @c 
7036 pointer mp_copy_knot (MP mp,pointer p) {
7037   pointer q; /* the copy */
7038   int k; /* runs through the words of a knot node */
7039   q=mp_get_node(mp, knot_node_size);
7040   for (k=0;k<=knot_node_size-1;k++) {
7041     mp->mem[q+k]=mp->mem[p+k];
7042   }
7043   originator(q)=originator(p);
7044   return q;
7045 }
7046
7047 @ The |copy_path| routine makes a clone of a given path.
7048
7049 @c 
7050 pointer mp_copy_path (MP mp, pointer p) {
7051   pointer q,pp,qq; /* for list manipulation */
7052   q=mp_copy_knot(mp, p);
7053   qq=q; pp=link(p);
7054   while ( pp!=p ) { 
7055     link(qq)=mp_copy_knot(mp, pp);
7056     qq=link(qq);
7057     pp=link(pp);
7058   }
7059   link(qq)=q;
7060   return q;
7061 }
7062
7063 @ Similarly, there's a way to copy the {\sl reverse\/} of a path. This procedure
7064 returns a pointer to the first node of the copy, if the path is a cycle,
7065 but to the final node of a non-cyclic copy. The global
7066 variable |path_tail| will point to the final node of the original path;
7067 this trick makes it easier to implement `\&{doublepath}'.
7068
7069 All node types are assumed to be |endpoint| or |explicit| only.
7070
7071 @c 
7072 pointer mp_htap_ypoc (MP mp,pointer p) {
7073   pointer q,pp,qq,rr; /* for list manipulation */
7074   q=mp_get_node(mp, knot_node_size); /* this will correspond to |p| */
7075   qq=q; pp=p;
7076   while (1) { 
7077     right_type(qq)=left_type(pp); left_type(qq)=right_type(pp);
7078     x_coord(qq)=x_coord(pp); y_coord(qq)=y_coord(pp);
7079     right_x(qq)=left_x(pp); right_y(qq)=left_y(pp);
7080     left_x(qq)=right_x(pp); left_y(qq)=right_y(pp);
7081     originator(qq)=originator(pp);
7082     if ( link(pp)==p ) { 
7083       link(q)=qq; mp->path_tail=pp; return q;
7084     }
7085     rr=mp_get_node(mp, knot_node_size); link(rr)=qq; qq=rr; pp=link(pp);
7086   }
7087 }
7088
7089 @ @<Glob...@>=
7090 pointer path_tail; /* the node that links to the beginning of a path */
7091
7092 @ When a cyclic list of knot nodes is no longer needed, it can be recycled by
7093 calling the following subroutine.
7094
7095 @<Declare the recycling subroutines@>=
7096 void mp_toss_knot_list (MP mp,pointer p) ;
7097
7098 @ @c
7099 void mp_toss_knot_list (MP mp,pointer p) {
7100   pointer q; /* the node being freed */
7101   pointer r; /* the next node */
7102   q=p;
7103   do {  
7104     r=link(q); 
7105     mp_free_node(mp, q,knot_node_size); q=r;
7106   } while (q!=p);
7107 }
7108
7109 @* \[18] Choosing control points.
7110 Now we must actually delve into one of \MP's more difficult routines,
7111 the |make_choices| procedure that chooses angles and control points for
7112 the splines of a curve when the user has not specified them explicitly.
7113 The parameter to |make_choices| points to a list of knots and
7114 path information, as described above.
7115
7116 A path decomposes into independent segments at ``breakpoint'' knots,
7117 which are knots whose left and right angles are both prespecified in
7118 some way (i.e., their |left_type| and |right_type| aren't both open).
7119
7120 @c 
7121 @<Declare the procedure called |solve_choices|@>;
7122 void mp_make_choices (MP mp,pointer knots) {
7123   pointer h; /* the first breakpoint */
7124   pointer p,q; /* consecutive breakpoints being processed */
7125   @<Other local variables for |make_choices|@>;
7126   check_arith; /* make sure that |arith_error=false| */
7127   if ( mp->internal[mp_tracing_choices]>0 )
7128     mp_print_path(mp, knots,", before choices",true);
7129   @<If consecutive knots are equal, join them explicitly@>;
7130   @<Find the first breakpoint, |h|, on the path;
7131     insert an artificial breakpoint if the path is an unbroken cycle@>;
7132   p=h;
7133   do {  
7134     @<Fill in the control points between |p| and the next breakpoint,
7135       then advance |p| to that breakpoint@>;
7136   } while (p!=h);
7137   if ( mp->internal[mp_tracing_choices]>0 )
7138     mp_print_path(mp, knots,", after choices",true);
7139   if ( mp->arith_error ) {
7140     @<Report an unexpected problem during the choice-making@>;
7141   }
7142 }
7143
7144 @ @<Report an unexpected problem during the choice...@>=
7145
7146   print_err("Some number got too big");
7147 @.Some number got too big@>
7148   help2("The path that I just computed is out of range.")
7149        ("So it will probably look funny. Proceed, for a laugh.");
7150   mp_put_get_error(mp); mp->arith_error=false;
7151 }
7152
7153 @ Two knots in a row with the same coordinates will always be joined
7154 by an explicit ``curve'' whose control points are identical with the
7155 knots.
7156
7157 @<If consecutive knots are equal, join them explicitly@>=
7158 p=knots;
7159 do {  
7160   q=link(p);
7161   if ( x_coord(p)==x_coord(q) && y_coord(p)==y_coord(q) && right_type(p)>mp_explicit ) { 
7162     right_type(p)=mp_explicit;
7163     if ( left_type(p)==mp_open ) { 
7164       left_type(p)=mp_curl; left_curl(p)=unity;
7165     }
7166     left_type(q)=mp_explicit;
7167     if ( right_type(q)==mp_open ) { 
7168       right_type(q)=mp_curl; right_curl(q)=unity;
7169     }
7170     right_x(p)=x_coord(p); left_x(q)=x_coord(p);
7171     right_y(p)=y_coord(p); left_y(q)=y_coord(p);
7172   }
7173   p=q;
7174 } while (p!=knots)
7175
7176 @ If there are no breakpoints, it is necessary to compute the direction
7177 angles around an entire cycle. In this case the |left_type| of the first
7178 node is temporarily changed to |end_cycle|.
7179
7180 @<Find the first breakpoint, |h|, on the path...@>=
7181 h=knots;
7182 while (1) { 
7183   if ( left_type(h)!=mp_open ) break;
7184   if ( right_type(h)!=mp_open ) break;
7185   h=link(h);
7186   if ( h==knots ) { 
7187     left_type(h)=mp_end_cycle; break;
7188   }
7189 }
7190
7191 @ If |right_type(p)<given| and |q=link(p)|, we must have
7192 |right_type(p)=left_type(q)=mp_explicit| or |endpoint|.
7193
7194 @<Fill in the control points between |p| and the next breakpoint...@>=
7195 q=link(p);
7196 if ( right_type(p)>=mp_given ) { 
7197   while ( (left_type(q)==mp_open)&&(right_type(q)==mp_open) ) q=link(q);
7198   @<Fill in the control information between
7199     consecutive breakpoints |p| and |q|@>;
7200 } else if ( right_type(p)==mp_endpoint ) {
7201   @<Give reasonable values for the unused control points between |p| and~|q|@>;
7202 }
7203 p=q
7204
7205 @ This step makes it possible to transform an explicitly computed path without
7206 checking the |left_type| and |right_type| fields.
7207
7208 @<Give reasonable values for the unused control points between |p| and~|q|@>=
7209
7210   right_x(p)=x_coord(p); right_y(p)=y_coord(p);
7211   left_x(q)=x_coord(q); left_y(q)=y_coord(q);
7212 }
7213
7214 @ Before we can go further into the way choices are made, we need to
7215 consider the underlying theory. The basic ideas implemented in |make_choices|
7216 are due to John Hobby, who introduced the notion of ``mock curvature''
7217 @^Hobby, John Douglas@>
7218 at a knot. Angles are chosen so that they preserve mock curvature when
7219 a knot is passed, and this has been found to produce excellent results.
7220
7221 It is convenient to introduce some notations that simplify the necessary
7222 formulas. Let $d_{k,k+1}=\vert z\k-z_k\vert$ be the (nonzero) distance
7223 between knots |k| and |k+1|; and let
7224 $${z\k-z_k\over z_k-z_{k-1}}={d_{k,k+1}\over d_{k-1,k}}e^{i\psi_k}$$
7225 so that a polygonal line from $z_{k-1}$ to $z_k$ to $z\k$ turns left
7226 through an angle of~$\psi_k$. We assume that $\vert\psi_k\vert\L180^\circ$.
7227 The control points for the spline from $z_k$ to $z\k$ will be denoted by
7228 $$\eqalign{z_k^+&=z_k+
7229   \textstyle{1\over3}\rho_k e^{i\theta_k}(z\k-z_k),\cr
7230  z\k^-&=z\k-
7231   \textstyle{1\over3}\sigma\k e^{-i\phi\k}(z\k-z_k),\cr}$$
7232 where $\rho_k$ and $\sigma\k$ are nonnegative ``velocity ratios'' at the
7233 beginning and end of the curve, while $\theta_k$ and $\phi\k$ are the
7234 corresponding ``offset angles.'' These angles satisfy the condition
7235 $$\theta_k+\phi_k+\psi_k=0,\eqno(*)$$
7236 whenever the curve leaves an intermediate knot~|k| in the direction that
7237 it enters.
7238
7239 @ Let $\alpha_k$ and $\beta\k$ be the reciprocals of the ``tension'' of
7240 the curve at its beginning and ending points. This means that
7241 $\rho_k=\alpha_k f(\theta_k,\phi\k)$ and $\sigma\k=\beta\k f(\phi\k,\theta_k)$,
7242 where $f(\theta,\phi)$ is \MP's standard velocity function defined in
7243 the |velocity| subroutine. The cubic spline $B(z_k^{\phantom+},z_k^+,
7244 z\k^-,z\k^{\phantom+};t)$
7245 has curvature
7246 @^curvature@>
7247 $${2\sigma\k\sin(\theta_k+\phi\k)-6\sin\theta_k\over\rho_k^2d_{k,k+1}}
7248 \qquad{\rm and}\qquad
7249 {2\rho_k\sin(\theta_k+\phi\k)-6\sin\phi\k\over\sigma\k^2d_{k,k+1}}$$
7250 at |t=0| and |t=1|, respectively. The mock curvature is the linear
7251 @^mock curvature@>
7252 approximation to this true curvature that arises in the limit for
7253 small $\theta_k$ and~$\phi\k$, if second-order terms are discarded.
7254 The standard velocity function satisfies
7255 $$f(\theta,\phi)=1+O(\theta^2+\theta\phi+\phi^2);$$
7256 hence the mock curvatures are respectively
7257 $${2\beta\k(\theta_k+\phi\k)-6\theta_k\over\alpha_k^2d_{k,k+1}}
7258 \qquad{\rm and}\qquad
7259 {2\alpha_k(\theta_k+\phi\k)-6\phi\k\over\beta\k^2d_{k,k+1}}.\eqno(**)$$
7260
7261 @ The turning angles $\psi_k$ are given, and equation $(*)$ above
7262 determines $\phi_k$ when $\theta_k$ is known, so the task of
7263 angle selection is essentially to choose appropriate values for each
7264 $\theta_k$. When equation~$(*)$ is used to eliminate $\phi$~variables
7265 from $(**)$, we obtain a system of linear equations of the form
7266 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7267 where
7268 $$A_k={\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7269 \qquad B_k={3-\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7270 \qquad C_k={3-\beta\k\over\alpha_k^2d_{k,k+1}},
7271 \qquad D_k={\beta\k\over\alpha_k^2d_{k,k+1}}.$$
7272 The tensions are always $3\over4$ or more, hence each $\alpha$ and~$\beta$
7273 will be at most $4\over3$. It follows that $B_k\G{5\over4}A_k$ and
7274 $C_k\G{5\over4}D_k$; hence the equations are diagonally dominant;
7275 hence they have a unique solution. Moreover, in most cases the tensions
7276 are equal to~1, so that $B_k=2A_k$ and $C_k=2D_k$. This makes the
7277 solution numerically stable, and there is an exponential damping
7278 effect: The data at knot $k\pm j$ affects the angle at knot~$k$ by
7279 a factor of~$O(2^{-j})$.
7280
7281 @ However, we still must consider the angles at the starting and ending
7282 knots of a non-cyclic path. These angles might be given explicitly, or
7283 they might be specified implicitly in terms of an amount of ``curl.''
7284
7285 Let's assume that angles need to be determined for a non-cyclic path
7286 starting at $z_0$ and ending at~$z_n$. Then equations of the form
7287 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta_{k+1}=R_k$$
7288 have been given for $0<k<n$, and it will be convenient to introduce
7289 equations of the same form for $k=0$ and $k=n$, where
7290 $$A_0=B_0=C_n=D_n=0.$$
7291 If $\theta_0$ is supposed to have a given value $E_0$, we simply
7292 define $C_0=0$, $D_0=0$, and $R_0=E_0$. Otherwise a curl
7293 parameter, $\gamma_0$, has been specified at~$z_0$; this means
7294 that the mock curvature at $z_0$ should be $\gamma_0$ times the
7295 mock curvature at $z_1$; i.e.,
7296 $${2\beta_1(\theta_0+\phi_1)-6\theta_0\over\alpha_0^2d_{01}}
7297 =\gamma_0{2\alpha_0(\theta_0+\phi_1)-6\phi_1\over\beta_1^2d_{01}}.$$
7298 This equation simplifies to
7299 $$(\alpha_0\chi_0+3-\beta_1)\theta_0+
7300  \bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\theta_1=
7301  -\bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\psi_1,$$
7302 where $\chi_0=\alpha_0^2\gamma_0/\beta_1^2$; so we can set $C_0=
7303 \chi_0\alpha_0+3-\beta_1$, $D_0=(3-\alpha_0)\chi_0+\beta_1$, $R_0=-D_0\psi_1$.
7304 It can be shown that $C_0>0$ and $C_0B_1-A_1D_0>0$ when $\gamma_0\G0$,
7305 hence the linear equations remain nonsingular.
7306
7307 Similar considerations apply at the right end, when the final angle $\phi_n$
7308 may or may not need to be determined. It is convenient to let $\psi_n=0$,
7309 hence $\theta_n=-\phi_n$. We either have an explicit equation $\theta_n=E_n$,
7310 or we have
7311 $$\bigl((3-\beta_n)\chi_n+\alpha_{n-1}\bigr)\theta_{n-1}+
7312 (\beta_n\chi_n+3-\alpha_{n-1})\theta_n=0,\qquad
7313   \chi_n={\beta_n^2\gamma_n\over\alpha_{n-1}^2}.$$
7314
7315 When |make_choices| chooses angles, it must compute the coefficients of
7316 these linear equations, then solve the equations. To compute the coefficients,
7317 it is necessary to compute arctangents of the given turning angles~$\psi_k$.
7318 When the equations are solved, the chosen directions $\theta_k$ are put
7319 back into the form of control points by essentially computing sines and
7320 cosines.
7321
7322 @ OK, we are ready to make the hard choices of |make_choices|.
7323 Most of the work is relegated to an auxiliary procedure
7324 called |solve_choices|, which has been introduced to keep
7325 |make_choices| from being extremely long.
7326
7327 @<Fill in the control information between...@>=
7328 @<Calculate the turning angles $\psi_k$ and the distances $d_{k,k+1}$;
7329   set $n$ to the length of the path@>;
7330 @<Remove |open| types at the breakpoints@>;
7331 mp_solve_choices(mp, p,q,n)
7332
7333 @ It's convenient to precompute quantities that will be needed several
7334 times later. The values of |delta_x[k]| and |delta_y[k]| will be the
7335 coordinates of $z\k-z_k$, and the magnitude of this vector will be
7336 |delta[k]=@t$d_{k,k+1}$@>|. The path angle $\psi_k$ between $z_k-z_{k-1}$
7337 and $z\k-z_k$ will be stored in |psi[k]|.
7338
7339 @<Glob...@>=
7340 int path_size; /* maximum number of knots between breakpoints of a path */
7341 scaled *delta_x;
7342 scaled *delta_y;
7343 scaled *delta; /* knot differences */
7344 angle  *psi; /* turning angles */
7345
7346 @ @<Allocate or initialize ...@>=
7347 mp->delta_x = NULL;
7348 mp->delta_y = NULL;
7349 mp->delta = NULL;
7350 mp->psi = NULL;
7351
7352 @ @<Dealloc variables@>=
7353 xfree(mp->delta_x);
7354 xfree(mp->delta_y);
7355 xfree(mp->delta);
7356 xfree(mp->psi);
7357
7358 @ @<Other local variables for |make_choices|@>=
7359   int k,n; /* current and final knot numbers */
7360   pointer s,t; /* registers for list traversal */
7361   scaled delx,dely; /* directions where |open| meets |explicit| */
7362   fraction sine,cosine; /* trig functions of various angles */
7363
7364 @ @<Calculate the turning angles...@>=
7365 {
7366 RESTART:
7367   k=0; s=p; n=mp->path_size;
7368   do {  
7369     t=link(s);
7370     mp->delta_x[k]=x_coord(t)-x_coord(s);
7371     mp->delta_y[k]=y_coord(t)-y_coord(s);
7372     mp->delta[k]=mp_pyth_add(mp, mp->delta_x[k],mp->delta_y[k]);
7373     if ( k>0 ) { 
7374       sine=mp_make_fraction(mp, mp->delta_y[k-1],mp->delta[k-1]);
7375       cosine=mp_make_fraction(mp, mp->delta_x[k-1],mp->delta[k-1]);
7376       mp->psi[k]=mp_n_arg(mp, mp_take_fraction(mp, mp->delta_x[k],cosine)+
7377         mp_take_fraction(mp, mp->delta_y[k],sine),
7378         mp_take_fraction(mp, mp->delta_y[k],cosine)-
7379           mp_take_fraction(mp, mp->delta_x[k],sine));
7380     }
7381     incr(k); s=t;
7382     if ( k==mp->path_size ) {
7383       mp_reallocate_paths(mp, mp->path_size+(mp->path_size>>2));
7384       goto RESTART; /* retry, loop size has changed */
7385     }
7386     if ( s==q ) n=k;
7387   } while (! (k>=n)&&(left_type(s)!=mp_end_cycle));
7388   if ( k==n ) mp->psi[n]=0; else mp->psi[k]=mp->psi[1];
7389 }
7390
7391 @ When we get to this point of the code, |right_type(p)| is either
7392 |given| or |curl| or |open|. If it is |open|, we must have
7393 |left_type(p)=mp_end_cycle| or |left_type(p)=mp_explicit|. In the latter
7394 case, the |open| type is converted to |given|; however, if the
7395 velocity coming into this knot is zero, the |open| type is
7396 converted to a |curl|, since we don't know the incoming direction.
7397
7398 Similarly, |left_type(q)| is either |given| or |curl| or |open| or
7399 |mp_end_cycle|. The |open| possibility is reduced either to |given| or to |curl|.
7400
7401 @<Remove |open| types at the breakpoints@>=
7402 if ( left_type(q)==mp_open ) { 
7403   delx=right_x(q)-x_coord(q); dely=right_y(q)-y_coord(q);
7404   if ( (delx==0)&&(dely==0) ) { 
7405     left_type(q)=mp_curl; left_curl(q)=unity;
7406   } else { 
7407     left_type(q)=mp_given; left_given(q)=mp_n_arg(mp, delx,dely);
7408   }
7409 }
7410 if ( (right_type(p)==mp_open)&&(left_type(p)==mp_explicit) ) { 
7411   delx=x_coord(p)-left_x(p); dely=y_coord(p)-left_y(p);
7412   if ( (delx==0)&&(dely==0) ) { 
7413     right_type(p)=mp_curl; right_curl(p)=unity;
7414   } else { 
7415     right_type(p)=mp_given; right_given(p)=mp_n_arg(mp, delx,dely);
7416   }
7417 }
7418
7419 @ Linear equations need to be solved whenever |n>1|; and also when |n=1|
7420 and exactly one of the breakpoints involves a curl. The simplest case occurs
7421 when |n=1| and there is a curl at both breakpoints; then we simply draw
7422 a straight line.
7423
7424 But before coding up the simple cases, we might as well face the general case,
7425 since we must deal with it sooner or later, and since the general case
7426 is likely to give some insight into the way simple cases can be handled best.
7427
7428 When there is no cycle, the linear equations to be solved form a tridiagonal
7429 system, and we can apply the standard technique of Gaussian elimination
7430 to convert that system to a sequence of equations of the form
7431 $$\theta_0+u_0\theta_1=v_0,\quad
7432 \theta_1+u_1\theta_2=v_1,\quad\ldots,\quad
7433 \theta_{n-1}+u_{n-1}\theta_n=v_{n-1},\quad
7434 \theta_n=v_n.$$
7435 It is possible to do this diagonalization while generating the equations.
7436 Once $\theta_n$ is known, it is easy to determine $\theta_{n-1}$, \dots,
7437 $\theta_1$, $\theta_0$; thus, the equations will be solved.
7438
7439 The procedure is slightly more complex when there is a cycle, but the
7440 basic idea will be nearly the same. In the cyclic case the right-hand
7441 sides will be $v_k+w_k\theta_0$ instead of simply $v_k$, and we will start
7442 the process off with $u_0=v_0=0$, $w_0=1$. The final equation will be not
7443 $\theta_n=v_n$ but $\theta_n+u_n\theta_1=v_n+w_n\theta_0$; an appropriate
7444 ending routine will take account of the fact that $\theta_n=\theta_0$ and
7445 eliminate the $w$'s from the system, after which the solution can be
7446 obtained as before.
7447
7448 When $u_k$, $v_k$, and $w_k$ are being computed, the three pointer
7449 variables |r|, |s|,~|t| will point respectively to knots |k-1|, |k|,
7450 and~|k+1|. The $u$'s and $w$'s are scaled by $2^{28}$, i.e., they are
7451 of type |fraction|; the $\theta$'s and $v$'s are of type |angle|.
7452
7453 @<Glob...@>=
7454 angle *theta; /* values of $\theta_k$ */
7455 fraction *uu; /* values of $u_k$ */
7456 angle *vv; /* values of $v_k$ */
7457 fraction *ww; /* values of $w_k$ */
7458
7459 @ @<Allocate or initialize ...@>=
7460 mp->theta = NULL;
7461 mp->uu = NULL;
7462 mp->vv = NULL;
7463 mp->ww = NULL;
7464
7465 @ @<Dealloc variables@>=
7466 xfree(mp->theta);
7467 xfree(mp->uu);
7468 xfree(mp->vv);
7469 xfree(mp->ww);
7470
7471 @ @<Declare |mp_reallocate| functions@>=
7472 void mp_reallocate_paths (MP mp, int l);
7473
7474 @ @c
7475 void mp_reallocate_paths (MP mp, int l) {
7476   XREALLOC (mp->delta_x, l, scaled);
7477   XREALLOC (mp->delta_y, l, scaled);
7478   XREALLOC (mp->delta,   l, scaled);
7479   XREALLOC (mp->psi,     l, angle);
7480   XREALLOC (mp->theta,   l, angle);
7481   XREALLOC (mp->uu,      l, fraction);
7482   XREALLOC (mp->vv,      l, angle);
7483   XREALLOC (mp->ww,      l, fraction);
7484   mp->path_size = l;
7485 }
7486
7487 @ Our immediate problem is to get the ball rolling by setting up the
7488 first equation or by realizing that no equations are needed, and to fit
7489 this initialization into a framework suitable for the overall computation.
7490
7491 @<Declare the procedure called |solve_choices|@>=
7492 @<Declare subroutines needed by |solve_choices|@>;
7493 void mp_solve_choices (MP mp,pointer p, pointer q, halfword n) {
7494   int k; /* current knot number */
7495   pointer r,s,t; /* registers for list traversal */
7496   @<Other local variables for |solve_choices|@>;
7497   k=0; s=p; r=0;
7498   while (1) { 
7499     t=link(s);
7500     if ( k==0 ) {
7501       @<Get the linear equations started; or |return|
7502         with the control points in place, if linear equations
7503         needn't be solved@>
7504     } else  { 
7505       switch (left_type(s)) {
7506       case mp_end_cycle: case mp_open:
7507         @<Set up equation to match mock curvatures
7508           at $z_k$; then |goto found| with $\theta_n$
7509           adjusted to equal $\theta_0$, if a cycle has ended@>;
7510         break;
7511       case mp_curl:
7512         @<Set up equation for a curl at $\theta_n$
7513           and |goto found|@>;
7514         break;
7515       case mp_given:
7516         @<Calculate the given value of $\theta_n$
7517           and |goto found|@>;
7518         break;
7519       } /* there are no other cases */
7520     }
7521     r=s; s=t; incr(k);
7522   }
7523 FOUND:
7524   @<Finish choosing angles and assigning control points@>;
7525 }
7526
7527 @ On the first time through the loop, we have |k=0| and |r| is not yet
7528 defined. The first linear equation, if any, will have $A_0=B_0=0$.
7529
7530 @<Get the linear equations started...@>=
7531 switch (right_type(s)) {
7532 case mp_given: 
7533   if ( left_type(t)==mp_given ) {
7534     @<Reduce to simple case of two givens  and |return|@>
7535   } else {
7536     @<Set up the equation for a given value of $\theta_0$@>;
7537   }
7538   break;
7539 case mp_curl: 
7540   if ( left_type(t)==mp_curl ) {
7541     @<Reduce to simple case of straight line and |return|@>
7542   } else {
7543     @<Set up the equation for a curl at $\theta_0$@>;
7544   }
7545   break;
7546 case mp_open: 
7547   mp->uu[0]=0; mp->vv[0]=0; mp->ww[0]=fraction_one;
7548   /* this begins a cycle */
7549   break;
7550 } /* there are no other cases */
7551
7552 @ The general equation that specifies equality of mock curvature at $z_k$ is
7553 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7554 as derived above. We want to combine this with the already-derived equation
7555 $\theta_{k-1}+u_{k-1}\theta_k=v_{k-1}+w_{k-1}\theta_0$ in order to obtain
7556 a new equation
7557 $\theta_k+u_k\theta\k=v_k+w_k\theta_0$. This can be done by dividing the
7558 equation
7559 $$(B_k-u_{k-1}A_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k-A_kv_{k-1}
7560     -A_kw_{k-1}\theta_0$$
7561 by $B_k-u_{k-1}A_k+C_k$. The trick is to do this carefully with
7562 fixed-point arithmetic, avoiding the chance of overflow while retaining
7563 suitable precision.
7564
7565 The calculations will be performed in several registers that
7566 provide temporary storage for intermediate quantities.
7567
7568 @<Other local variables for |solve_choices|@>=
7569 fraction aa,bb,cc,ff,acc; /* temporary registers */
7570 scaled dd,ee; /* likewise, but |scaled| */
7571 scaled lt,rt; /* tension values */
7572
7573 @ @<Set up equation to match mock curvatures...@>=
7574 { @<Calculate the values $\\{aa}=A_k/B_k$, $\\{bb}=D_k/C_k$,
7575     $\\{dd}=(3-\alpha_{k-1})d_{k,k+1}$, $\\{ee}=(3-\beta\k)d_{k-1,k}$,
7576     and $\\{cc}=(B_k-u_{k-1}A_k)/B_k$@>;
7577   @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>;
7578   mp->uu[k]=mp_take_fraction(mp, ff,bb);
7579   @<Calculate the values of $v_k$ and $w_k$@>;
7580   if ( left_type(s)==mp_end_cycle ) {
7581     @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>;
7582   }
7583 }
7584
7585 @ Since tension values are never less than 3/4, the values |aa| and
7586 |bb| computed here are never more than 4/5.
7587
7588 @<Calculate the values $\\{aa}=...@>=
7589 if ( abs(right_tension(r))==unity) { 
7590   aa=fraction_half; dd=2*mp->delta[k];
7591 } else { 
7592   aa=mp_make_fraction(mp, unity,3*abs(right_tension(r))-unity);
7593   dd=mp_take_fraction(mp, mp->delta[k],
7594     fraction_three-mp_make_fraction(mp, unity,abs(right_tension(r))));
7595 }
7596 if ( abs(left_tension(t))==unity ){ 
7597   bb=fraction_half; ee=2*mp->delta[k-1];
7598 } else { 
7599   bb=mp_make_fraction(mp, unity,3*abs(left_tension(t))-unity);
7600   ee=mp_take_fraction(mp, mp->delta[k-1],
7601     fraction_three-mp_make_fraction(mp, unity,abs(left_tension(t))));
7602 }
7603 cc=fraction_one-mp_take_fraction(mp, mp->uu[k-1],aa)
7604
7605 @ The ratio to be calculated in this step can be written in the form
7606 $$\beta_k^2\cdot\\{ee}\over\beta_k^2\cdot\\{ee}+\alpha_k^2\cdot
7607   \\{cc}\cdot\\{dd},$$
7608 because of the quantities just calculated. The values of |dd| and |ee|
7609 will not be needed after this step has been performed.
7610
7611 @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>=
7612 dd=mp_take_fraction(mp, dd,cc); lt=abs(left_tension(s)); rt=abs(right_tension(s));
7613 if ( lt!=rt ) { /* $\beta_k^{-1}\ne\alpha_k^{-1}$ */
7614   if ( lt<rt ) { 
7615     ff=mp_make_fraction(mp, lt,rt);
7616     ff=mp_take_fraction(mp, ff,ff); /* $\alpha_k^2/\beta_k^2$ */
7617     dd=mp_take_fraction(mp, dd,ff);
7618   } else { 
7619     ff=mp_make_fraction(mp, rt,lt);
7620     ff=mp_take_fraction(mp, ff,ff); /* $\beta_k^2/\alpha_k^2$ */
7621     ee=mp_take_fraction(mp, ee,ff);
7622   }
7623 }
7624 ff=mp_make_fraction(mp, ee,ee+dd)
7625
7626 @ The value of $u_{k-1}$ will be |<=1| except when $k=1$ and the previous
7627 equation was specified by a curl. In that case we must use a special
7628 method of computation to prevent overflow.
7629
7630 Fortunately, the calculations turn out to be even simpler in this ``hard''
7631 case. The curl equation makes $w_0=0$ and $v_0=-u_0\psi_1$, hence
7632 $-B_1\psi_1-A_1v_0=-(B_1-u_0A_1)\psi_1=-\\{cc}\cdot B_1\psi_1$.
7633
7634 @<Calculate the values of $v_k$ and $w_k$@>=
7635 acc=-mp_take_fraction(mp, mp->psi[k+1],mp->uu[k]);
7636 if ( right_type(r)==mp_curl ) { 
7637   mp->ww[k]=0;
7638   mp->vv[k]=acc-mp_take_fraction(mp, mp->psi[1],fraction_one-ff);
7639 } else { 
7640   ff=mp_make_fraction(mp, fraction_one-ff,cc); /* this is
7641     $B_k/(C_k+B_k-u_{k-1}A_k)<5$ */
7642   acc=acc-mp_take_fraction(mp, mp->psi[k],ff);
7643   ff=mp_take_fraction(mp, ff,aa); /* this is $A_k/(C_k+B_k-u_{k-1}A_k)$ */
7644   mp->vv[k]=acc-mp_take_fraction(mp, mp->vv[k-1],ff);
7645   if ( mp->ww[k-1]==0 ) mp->ww[k]=0;
7646   else mp->ww[k]=-mp_take_fraction(mp, mp->ww[k-1],ff);
7647 }
7648
7649 @ When a complete cycle has been traversed, we have $\theta_k+u_k\theta\k=
7650 v_k+w_k\theta_0$, for |1<=k<=n|. We would like to determine the value of
7651 $\theta_n$ and reduce the system to the form $\theta_k+u_k\theta\k=v_k$
7652 for |0<=k<n|, so that the cyclic case can be finished up just as if there
7653 were no cycle.
7654
7655 The idea in the following code is to observe that
7656 $$\eqalign{\theta_n&=v_n+w_n\theta_0-u_n\theta_1=\cdots\cr
7657 &=v_n+w_n\theta_0-u_n\bigl(v_1+w_1\theta_0-u_1(v_2+\cdots
7658   -u_{n-2}(v_{n-1}+w_{n-1}\theta_0-u_{n-1}\theta_0))\bigr),\cr}$$
7659 so we can solve for $\theta_n=\theta_0$.
7660
7661 @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>=
7662
7663 aa=0; bb=fraction_one; /* we have |k=n| */
7664 do {  decr(k);
7665 if ( k==0 ) k=n;
7666   aa=mp->vv[k]-mp_take_fraction(mp, aa,mp->uu[k]);
7667   bb=mp->ww[k]-mp_take_fraction(mp, bb,mp->uu[k]);
7668 } while (k!=n); /* now $\theta_n=\\{aa}+\\{bb}\cdot\theta_n$ */
7669 aa=mp_make_fraction(mp, aa,fraction_one-bb);
7670 mp->theta[n]=aa; mp->vv[0]=aa;
7671 for (k=1;k<=n-1;k++) {
7672   mp->vv[k]=mp->vv[k]+mp_take_fraction(mp, aa,mp->ww[k]);
7673 }
7674 goto FOUND;
7675 }
7676
7677 @ @d reduce_angle(A) if ( abs((A))>one_eighty_deg ) {
7678   if ( (A)>0 ) (A)=(A)-three_sixty_deg; else (A)=(A)+three_sixty_deg; }
7679
7680 @<Calculate the given value of $\theta_n$...@>=
7681
7682   mp->theta[n]=left_given(s)-mp_n_arg(mp, mp->delta_x[n-1],mp->delta_y[n-1]);
7683   reduce_angle(mp->theta[n]);
7684   goto FOUND;
7685 }
7686
7687 @ @<Set up the equation for a given value of $\theta_0$@>=
7688
7689   mp->vv[0]=right_given(s)-mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7690   reduce_angle(mp->vv[0]);
7691   mp->uu[0]=0; mp->ww[0]=0;
7692 }
7693
7694 @ @<Set up the equation for a curl at $\theta_0$@>=
7695 { cc=right_curl(s); lt=abs(left_tension(t)); rt=abs(right_tension(s));
7696   if ( (rt==unity)&&(lt==unity) )
7697     mp->uu[0]=mp_make_fraction(mp, cc+cc+unity,cc+two);
7698   else 
7699     mp->uu[0]=mp_curl_ratio(mp, cc,rt,lt);
7700   mp->vv[0]=-mp_take_fraction(mp, mp->psi[1],mp->uu[0]); mp->ww[0]=0;
7701 }
7702
7703 @ @<Set up equation for a curl at $\theta_n$...@>=
7704 { cc=left_curl(s); lt=abs(left_tension(s)); rt=abs(right_tension(r));
7705   if ( (rt==unity)&&(lt==unity) )
7706     ff=mp_make_fraction(mp, cc+cc+unity,cc+two);
7707   else 
7708     ff=mp_curl_ratio(mp, cc,lt,rt);
7709   mp->theta[n]=-mp_make_fraction(mp, mp_take_fraction(mp, mp->vv[n-1],ff),
7710     fraction_one-mp_take_fraction(mp, ff,mp->uu[n-1]));
7711   goto FOUND;
7712 }
7713
7714 @ The |curl_ratio| subroutine has three arguments, which our previous notation
7715 encourages us to call $\gamma$, $\alpha^{-1}$, and $\beta^{-1}$. It is
7716 a somewhat tedious program to calculate
7717 $${(3-\alpha)\alpha^2\gamma+\beta^3\over
7718   \alpha^3\gamma+(3-\beta)\beta^2},$$
7719 with the result reduced to 4 if it exceeds 4. (This reduction of curl
7720 is necessary only if the curl and tension are both large.)
7721 The values of $\alpha$ and $\beta$ will be at most~4/3.
7722
7723 @<Declare subroutines needed by |solve_choices|@>=
7724 fraction mp_curl_ratio (MP mp,scaled gamma, scaled a_tension, 
7725                         scaled b_tension) {
7726   fraction alpha,beta,num,denom,ff; /* registers */
7727   alpha=mp_make_fraction(mp, unity,a_tension);
7728   beta=mp_make_fraction(mp, unity,b_tension);
7729   if ( alpha<=beta ) {
7730     ff=mp_make_fraction(mp, alpha,beta); ff=mp_take_fraction(mp, ff,ff);
7731     gamma=mp_take_fraction(mp, gamma,ff);
7732     beta=beta / 010000; /* convert |fraction| to |scaled| */
7733     denom=mp_take_fraction(mp, gamma,alpha)+three-beta;
7734     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7735   } else { 
7736     ff=mp_make_fraction(mp, beta,alpha); ff=mp_take_fraction(mp, ff,ff);
7737     beta=mp_take_fraction(mp, beta,ff) / 010000; /* convert |fraction| to |scaled| */
7738     denom=mp_take_fraction(mp, gamma,alpha)+(ff / 1365)-beta;
7739       /* $1365\approx 2^{12}/3$ */
7740     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7741   }
7742   if ( num>=denom+denom+denom+denom ) return fraction_four;
7743   else return mp_make_fraction(mp, num,denom);
7744 }
7745
7746 @ We're in the home stretch now.
7747
7748 @<Finish choosing angles and assigning control points@>=
7749 for (k=n-1;k>=0;k--) {
7750   mp->theta[k]=mp->vv[k]-mp_take_fraction(mp,mp->theta[k+1],mp->uu[k]);
7751 }
7752 s=p; k=0;
7753 do {  
7754   t=link(s);
7755   mp_n_sin_cos(mp, mp->theta[k]); mp->st=mp->n_sin; mp->ct=mp->n_cos;
7756   mp_n_sin_cos(mp, -mp->psi[k+1]-mp->theta[k+1]); mp->sf=mp->n_sin; mp->cf=mp->n_cos;
7757   mp_set_controls(mp, s,t,k);
7758   incr(k); s=t;
7759 } while (k!=n)
7760
7761 @ The |set_controls| routine actually puts the control points into
7762 a pair of consecutive nodes |p| and~|q|. Global variables are used to
7763 record the values of $\sin\theta$, $\cos\theta$, $\sin\phi$, and
7764 $\cos\phi$ needed in this calculation.
7765
7766 @<Glob...@>=
7767 fraction st;
7768 fraction ct;
7769 fraction sf;
7770 fraction cf; /* sines and cosines */
7771
7772 @ @<Declare subroutines needed by |solve_choices|@>=
7773 void mp_set_controls (MP mp,pointer p, pointer q, integer k) {
7774   fraction rr,ss; /* velocities, divided by thrice the tension */
7775   scaled lt,rt; /* tensions */
7776   fraction sine; /* $\sin(\theta+\phi)$ */
7777   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7778   rr=mp_velocity(mp, mp->st,mp->ct,mp->sf,mp->cf,rt);
7779   ss=mp_velocity(mp, mp->sf,mp->cf,mp->st,mp->ct,lt);
7780   if ( (right_tension(p)<0)||(left_tension(q)<0) ) {
7781     @<Decrease the velocities,
7782       if necessary, to stay inside the bounding triangle@>;
7783   }
7784   right_x(p)=x_coord(p)+mp_take_fraction(mp, 
7785                           mp_take_fraction(mp, mp->delta_x[k],mp->ct)-
7786                           mp_take_fraction(mp, mp->delta_y[k],mp->st),rr);
7787   right_y(p)=y_coord(p)+mp_take_fraction(mp, 
7788                           mp_take_fraction(mp, mp->delta_y[k],mp->ct)+
7789                           mp_take_fraction(mp, mp->delta_x[k],mp->st),rr);
7790   left_x(q)=x_coord(q)-mp_take_fraction(mp, 
7791                          mp_take_fraction(mp, mp->delta_x[k],mp->cf)+
7792                          mp_take_fraction(mp, mp->delta_y[k],mp->sf),ss);
7793   left_y(q)=y_coord(q)-mp_take_fraction(mp, 
7794                          mp_take_fraction(mp, mp->delta_y[k],mp->cf)-
7795                          mp_take_fraction(mp, mp->delta_x[k],mp->sf),ss);
7796   right_type(p)=mp_explicit; left_type(q)=mp_explicit;
7797 }
7798
7799 @ The boundedness conditions $\\{rr}\L\sin\phi\,/\sin(\theta+\phi)$ and
7800 $\\{ss}\L\sin\theta\,/\sin(\theta+\phi)$ are to be enforced if $\sin\theta$,
7801 $\sin\phi$, and $\sin(\theta+\phi)$ all have the same sign. Otherwise
7802 there is no ``bounding triangle.''
7803 @:at_least_}{\&{atleast} primitive@>
7804
7805 @<Decrease the velocities, if necessary...@>=
7806 if (((mp->st>=0)&&(mp->sf>=0))||((mp->st<=0)&&(mp->sf<=0)) ) {
7807   sine=mp_take_fraction(mp, abs(mp->st),mp->cf)+
7808                             mp_take_fraction(mp, abs(mp->sf),mp->ct);
7809   if ( sine>0 ) {
7810     sine=mp_take_fraction(mp, sine,fraction_one+unity); /* safety factor */
7811     if ( right_tension(p)<0 )
7812      if ( mp_ab_vs_cd(mp, abs(mp->sf),fraction_one,rr,sine)<0 )
7813       rr=mp_make_fraction(mp, abs(mp->sf),sine);
7814     if ( left_tension(q)<0 )
7815      if ( mp_ab_vs_cd(mp, abs(mp->st),fraction_one,ss,sine)<0 )
7816       ss=mp_make_fraction(mp, abs(mp->st),sine);
7817   }
7818 }
7819
7820 @ Only the simple cases remain to be handled.
7821
7822 @<Reduce to simple case of two givens and |return|@>=
7823
7824   aa=mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7825   mp_n_sin_cos(mp, right_given(p)-aa); mp->ct=mp->n_cos; mp->st=mp->n_sin;
7826   mp_n_sin_cos(mp, left_given(q)-aa); mp->cf=mp->n_cos; mp->sf=-mp->n_sin;
7827   mp_set_controls(mp, p,q,0); return;
7828 }
7829
7830 @ @<Reduce to simple case of straight line and |return|@>=
7831
7832   right_type(p)=mp_explicit; left_type(q)=mp_explicit;
7833   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7834   if ( rt==unity ) {
7835     if ( mp->delta_x[0]>=0 ) right_x(p)=x_coord(p)+((mp->delta_x[0]+1) / 3);
7836     else right_x(p)=x_coord(p)+((mp->delta_x[0]-1) / 3);
7837     if ( mp->delta_y[0]>=0 ) right_y(p)=y_coord(p)+((mp->delta_y[0]+1) / 3);
7838     else right_y(p)=y_coord(p)+((mp->delta_y[0]-1) / 3);
7839   } else { 
7840     ff=mp_make_fraction(mp, unity,3*rt); /* $\alpha/3$ */
7841     right_x(p)=x_coord(p)+mp_take_fraction(mp, mp->delta_x[0],ff);
7842     right_y(p)=y_coord(p)+mp_take_fraction(mp, mp->delta_y[0],ff);
7843   }
7844   if ( lt==unity ) {
7845     if ( mp->delta_x[0]>=0 ) left_x(q)=x_coord(q)-((mp->delta_x[0]+1) / 3);
7846     else left_x(q)=x_coord(q)-((mp->delta_x[0]-1) / 3);
7847     if ( mp->delta_y[0]>=0 ) left_y(q)=y_coord(q)-((mp->delta_y[0]+1) / 3);
7848     else left_y(q)=y_coord(q)-((mp->delta_y[0]-1) / 3);
7849   } else  { 
7850     ff=mp_make_fraction(mp, unity,3*lt); /* $\beta/3$ */
7851     left_x(q)=x_coord(q)-mp_take_fraction(mp, mp->delta_x[0],ff);
7852     left_y(q)=y_coord(q)-mp_take_fraction(mp, mp->delta_y[0],ff);
7853   }
7854   return;
7855 }
7856
7857 @* \[19] Measuring paths.
7858 \MP's \&{llcorner}, \&{lrcorner}, \&{ulcorner}, and \&{urcorner} operators
7859 allow the user to measure the bounding box of anything that can go into a
7860 picture.  It's easy to get rough bounds on the $x$ and $y$ extent of a path
7861 by just finding the bounding box of the knots and the control points. We
7862 need a more accurate version of the bounding box, but we can still use the
7863 easy estimate to save time by focusing on the interesting parts of the path.
7864
7865 @ Computing an accurate bounding box involves a theme that will come up again
7866 and again. Given a Bernshte{\u\i}n polynomial
7867 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
7868 $$B(z_0,z_1,\ldots,z_n;t)=\sum_k{n\choose k}t^k(1-t)^{n-k}z_k,$$
7869 we can conveniently bisect its range as follows:
7870
7871 \smallskip
7872 \textindent{1)} Let $z_k^{(0)}=z_k$, for |0<=k<=n|.
7873
7874 \smallskip
7875 \textindent{2)} Let $z_k^{(j+1)}={1\over2}(z_k^{(j)}+z\k^{(j)})$, for
7876 |0<=k<n-j|, for |0<=j<n|.
7877
7878 \smallskip\noindent
7879 Then
7880 $$B(z_0,z_1,\ldots,z_n;t)=B(z_0^{(0)},z_0^{(1)},\ldots,z_0^{(n)};2t)
7881  =B(z_0^{(n)},z_1^{(n-1)},\ldots,z_n^{(0)};2t-1).$$
7882 This formula gives us the coefficients of polynomials to use over the ranges
7883 $0\L t\L{1\over2}$ and ${1\over2}\L t\L1$.
7884
7885 @ Now here's a subroutine that's handy for all sorts of path computations:
7886 Given a quadratic polynomial $B(a,b,c;t)$, the |crossing_point| function
7887 returns the unique |fraction| value |t| between 0 and~1 at which
7888 $B(a,b,c;t)$ changes from positive to negative, or returns
7889 |t=fraction_one+1| if no such value exists. If |a<0| (so that $B(a,b,c;t)$
7890 is already negative at |t=0|), |crossing_point| returns the value zero.
7891
7892 @d no_crossing {  return (fraction_one+1); }
7893 @d one_crossing { return fraction_one; }
7894 @d zero_crossing { return 0; }
7895 @d mp_crossing_point(M,A,B,C) mp_do_crossing_point(A,B,C)
7896
7897 @c fraction mp_do_crossing_point (integer a, integer b, integer c) {
7898   integer d; /* recursive counter */
7899   integer x,xx,x0,x1,x2; /* temporary registers for bisection */
7900   if ( a<0 ) zero_crossing;
7901   if ( c>=0 ) { 
7902     if ( b>=0 ) {
7903       if ( c>0 ) { no_crossing; }
7904       else if ( (a==0)&&(b==0) ) { no_crossing;} 
7905       else { one_crossing; } 
7906     }
7907     if ( a==0 ) zero_crossing;
7908   } else if ( a==0 ) {
7909     if ( b<=0 ) zero_crossing;
7910   }
7911   @<Use bisection to find the crossing point, if one exists@>;
7912 }
7913
7914 @ The general bisection method is quite simple when $n=2$, hence
7915 |crossing_point| does not take much time. At each stage in the
7916 recursion we have a subinterval defined by |l| and~|j| such that
7917 $B(a,b,c;2^{-l}(j+t))=B(x_0,x_1,x_2;t)$, and we want to ``zero in'' on
7918 the subinterval where $x_0\G0$ and $\min(x_1,x_2)<0$.
7919
7920 It is convenient for purposes of calculation to combine the values
7921 of |l| and~|j| in a single variable $d=2^l+j$, because the operation
7922 of bisection then corresponds simply to doubling $d$ and possibly
7923 adding~1. Furthermore it proves to be convenient to modify
7924 our previous conventions for bisection slightly, maintaining the
7925 variables $X_0=2^lx_0$, $X_1=2^l(x_0-x_1)$, and $X_2=2^l(x_1-x_2)$.
7926 With these variables the conditions $x_0\ge0$ and $\min(x_1,x_2)<0$ are
7927 equivalent to $\max(X_1,X_1+X_2)>X_0\ge0$.
7928
7929 The following code maintains the invariant relations
7930 $0\L|x0|<\max(|x1|,|x1|+|x2|)$,
7931 $\vert|x1|\vert<2^{30}$, $\vert|x2|\vert<2^{30}$;
7932 it has been constructed in such a way that no arithmetic overflow
7933 will occur if the inputs satisfy
7934 $a<2^{30}$, $\vert a-b\vert<2^{30}$, and $\vert b-c\vert<2^{30}$.
7935
7936 @<Use bisection to find the crossing point...@>=
7937 d=1; x0=a; x1=a-b; x2=b-c;
7938 do {  
7939   x=half(x1+x2);
7940   if ( x1-x0>x0 ) { 
7941     x2=x; x0+=x0; d+=d;  
7942   } else { 
7943     xx=x1+x-x0;
7944     if ( xx>x0 ) { 
7945       x2=x; x0+=x0; d+=d;
7946     }  else { 
7947       x0=x0-xx;
7948       if ( x<=x0 ) { if ( x+x2<=x0 ) no_crossing; }
7949       x1=x; d=d+d+1;
7950     }
7951   }
7952 } while (d<fraction_one);
7953 return (d-fraction_one)
7954
7955 @ Here is a routine that computes the $x$ or $y$ coordinate of the point on
7956 a cubic corresponding to the |fraction| value~|t|.
7957
7958 It is convenient to define a \.{WEB} macro |t_of_the_way| such that
7959 |t_of_the_way(a,b)| expands to |a-(a-b)*t|, i.e., to |t[a,b]|.
7960
7961 @d t_of_the_way(A,B) ((A)-mp_take_fraction(mp,(A)-(B),t))
7962
7963 @c scaled mp_eval_cubic (MP mp,pointer p, pointer q, fraction t) {
7964   scaled x1,x2,x3; /* intermediate values */
7965   x1=t_of_the_way(knot_coord(p),right_coord(p));
7966   x2=t_of_the_way(right_coord(p),left_coord(q));
7967   x3=t_of_the_way(left_coord(q),knot_coord(q));
7968   x1=t_of_the_way(x1,x2);
7969   x2=t_of_the_way(x2,x3);
7970   return t_of_the_way(x1,x2);
7971 }
7972
7973 @ The actual bounding box information is stored in global variables.
7974 Since it is convenient to address the $x$ and $y$ information
7975 separately, we define arrays indexed by |x_code..y_code| and use
7976 macros to give them more convenient names.
7977
7978 @<Types...@>=
7979 enum mp_bb_code  {
7980   mp_x_code=0, /* index for |minx| and |maxx| */
7981   mp_y_code /* index for |miny| and |maxy| */
7982 } ;
7983
7984
7985 @d minx mp->bbmin[mp_x_code]
7986 @d maxx mp->bbmax[mp_x_code]
7987 @d miny mp->bbmin[mp_y_code]
7988 @d maxy mp->bbmax[mp_y_code]
7989
7990 @<Glob...@>=
7991 scaled bbmin[mp_y_code+1];
7992 scaled bbmax[mp_y_code+1]; 
7993 /* the result of procedures that compute bounding box information */
7994
7995 @ Now we're ready for the key part of the bounding box computation.
7996 The |bound_cubic| procedure updates |bbmin[c]| and |bbmax[c]| based on
7997 $$B(\hbox{|knot_coord(p)|}, \hbox{|right_coord(p)|},
7998     \hbox{|left_coord(q)|}, \hbox{|knot_coord(q)|};t)
7999 $$
8000 for $0<t\le1$.  In other words, the procedure adjusts the bounds to
8001 accommodate |knot_coord(q)| and any extremes over the range $0<t<1$.
8002 The |c| parameter is |x_code| or |y_code|.
8003
8004 @c void mp_bound_cubic (MP mp,pointer p, pointer q, small_number c) {
8005   boolean wavy; /* whether we need to look for extremes */
8006   scaled del1,del2,del3,del,dmax; /* proportional to the control
8007      points of a quadratic derived from a cubic */
8008   fraction t,tt; /* where a quadratic crosses zero */
8009   scaled x; /* a value that |bbmin[c]| and |bbmax[c]| must accommodate */
8010   x=knot_coord(q);
8011   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8012   @<Check the control points against the bounding box and set |wavy:=true|
8013     if any of them lie outside@>;
8014   if ( wavy ) {
8015     del1=right_coord(p)-knot_coord(p);
8016     del2=left_coord(q)-right_coord(p);
8017     del3=knot_coord(q)-left_coord(q);
8018     @<Scale up |del1|, |del2|, and |del3| for greater accuracy;
8019       also set |del| to the first nonzero element of |(del1,del2,del3)|@>;
8020     if ( del<0 ) {
8021       negate(del1); negate(del2); negate(del3);
8022     };
8023     t=mp_crossing_point(mp, del1,del2,del3);
8024     if ( t<fraction_one ) {
8025       @<Test the extremes of the cubic against the bounding box@>;
8026     }
8027   }
8028 }
8029
8030 @ @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>=
8031 if ( x<mp->bbmin[c] ) mp->bbmin[c]=x;
8032 if ( x>mp->bbmax[c] ) mp->bbmax[c]=x
8033
8034 @ @<Check the control points against the bounding box and set...@>=
8035 wavy=true;
8036 if ( mp->bbmin[c]<=right_coord(p) )
8037   if ( right_coord(p)<=mp->bbmax[c] )
8038     if ( mp->bbmin[c]<=left_coord(q) )
8039       if ( left_coord(q)<=mp->bbmax[c] )
8040         wavy=false
8041
8042 @ If |del1=del2=del3=0|, it's impossible to obey the title of this
8043 section. We just set |del=0| in that case.
8044
8045 @<Scale up |del1|, |del2|, and |del3| for greater accuracy...@>=
8046 if ( del1!=0 ) del=del1;
8047 else if ( del2!=0 ) del=del2;
8048 else del=del3;
8049 if ( del!=0 ) {
8050   dmax=abs(del1);
8051   if ( abs(del2)>dmax ) dmax=abs(del2);
8052   if ( abs(del3)>dmax ) dmax=abs(del3);
8053   while ( dmax<fraction_half ) {
8054     dmax+=dmax; del1+=del1; del2+=del2; del3+=del3;
8055   }
8056 }
8057
8058 @ Since |crossing_point| has tried to choose |t| so that
8059 $B(|del1|,|del2|,|del3|;\tau)$ crosses zero at $\tau=|t|$ with negative
8060 slope, the value of |del2| computed below should not be positive.
8061 But rounding error could make it slightly positive in which case we
8062 must cut it to zero to avoid confusion.
8063
8064 @<Test the extremes of the cubic against the bounding box@>=
8065
8066   x=mp_eval_cubic(mp, p,q,t);
8067   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8068   del2=t_of_the_way(del2,del3);
8069     /* now |0,del2,del3| represent the derivative on the remaining interval */
8070   if ( del2>0 ) del2=0;
8071   tt=mp_crossing_point(mp, 0,-del2,-del3);
8072   if ( tt<fraction_one ) {
8073     @<Test the second extreme against the bounding box@>;
8074   }
8075 }
8076
8077 @ @<Test the second extreme against the bounding box@>=
8078 {
8079    x=mp_eval_cubic(mp, p,q,t_of_the_way(tt,fraction_one));
8080   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8081 }
8082
8083 @ Finding the bounding box of a path is basically a matter of applying
8084 |bound_cubic| twice for each pair of adjacent knots.
8085
8086 @c void mp_path_bbox (MP mp,pointer h) {
8087   pointer p,q; /* a pair of adjacent knots */
8088    minx=x_coord(h); miny=y_coord(h);
8089   maxx=minx; maxy=miny;
8090   p=h;
8091   do {  
8092     if ( right_type(p)==mp_endpoint ) return;
8093     q=link(p);
8094     mp_bound_cubic(mp, x_loc(p),x_loc(q),mp_x_code);
8095     mp_bound_cubic(mp, y_loc(p),y_loc(q),mp_y_code);
8096     p=q;
8097   } while (p!=h);
8098 }
8099
8100 @ Another important way to measure a path is to find its arc length.  This
8101 is best done by using the general bisection algorithm to subdivide the path
8102 until obtaining ``well behaved'' subpaths whose arc lengths can be approximated
8103 by simple means.
8104
8105 Since the arc length is the integral with respect to time of the magnitude of
8106 the velocity, it is natural to use Simpson's rule for the approximation.
8107 @^Simpson's rule@>
8108 If $\dot B(t)$ is the spline velocity, Simpson's rule gives
8109 $$ \vb\dot B(0)\vb + 4\vb\dot B({1\over2})\vb + \vb\dot B(1)\vb \over 6 $$
8110 for the arc length of a path of length~1.  For a cubic spline
8111 $B(z_0,z_1,z_2,z_3;t)$, the time derivative $\dot B(t)$ is
8112 $3B(dz_0,dz_1,dz_2;t)$, where $dz_i=z_{i+1}-z_i$.  Hence the arc length
8113 approximation is
8114 $$ {\vb dz_0\vb \over 2} + 2\vb dz_{02}\vb + {\vb dz_2\vb \over 2}, $$
8115 where
8116 $$ dz_{02}={1\over2}\left({dz_0+dz_1\over 2}+{dz_1+dz_2\over 2}\right)$$
8117 is the result of the bisection algorithm.
8118
8119 @ The remaining problem is how to decide when a subpath is ``well behaved.''
8120 This could be done via the theoretical error bound for Simpson's rule,
8121 @^Simpson's rule@>
8122 but this is impractical because it requires an estimate of the fourth
8123 derivative of the quantity being integrated.  It is much easier to just perform
8124 a bisection step and see how much the arc length estimate changes.  Since the
8125 error for Simpson's rule is proportional to the fourth power of the sample
8126 spacing, the remaining error is typically about $1\over16$ of the amount of
8127 the change.  We say ``typically'' because the error has a pseudo-random behavior
8128 that could cause the two estimates to agree when each contain large errors.
8129
8130 To protect against disasters such as undetected cusps, the bisection process
8131 should always continue until all the $dz_i$ vectors belong to a single
8132 $90^\circ$ sector.  This ensures that no point on the spline can have velocity
8133 less than 70\% of the minimum of $\vb dz_0\vb$, $\vb dz_1\vb$ and $\vb dz_2\vb$.
8134 If such a spline happens to produce an erroneous arc length estimate that
8135 is little changed by bisection, the amount of the error is likely to be fairly
8136 small.  We will try to arrange things so that freak accidents of this type do
8137 not destroy the inverse relationship between the \&{arclength} and
8138 \&{arctime} operations.
8139 @:arclength_}{\&{arclength} primitive@>
8140 @:arctime_}{\&{arctime} primitive@>
8141
8142 @ The \&{arclength} and \&{arctime} operations are both based on a recursive
8143 @^recursion@>
8144 function that finds the arc length of a cubic spline given $dz_0$, $dz_1$,
8145 $dz_2$. This |arc_test| routine also takes an arc length goal |a_goal| and
8146 returns the time when the arc length reaches |a_goal| if there is such a time.
8147 Thus the return value is either an arc length less than |a_goal| or, if the
8148 arc length would be at least |a_goal|, it returns a time value decreased by
8149 |two|.  This allows the caller to use the sign of the result to distinguish
8150 between arc lengths and time values.  On certain types of overflow, it is
8151 possible for |a_goal| and the result of |arc_test| both to be |el_gordo|.
8152 Otherwise, the result is always less than |a_goal|.
8153
8154 Rather than halving the control point coordinates on each recursive call to
8155 |arc_test|, it is better to keep them proportional to velocity on the original
8156 curve and halve the results instead.  This means that recursive calls can
8157 potentially use larger error tolerances in their arc length estimates.  How
8158 much larger depends on to what extent the errors behave as though they are
8159 independent of each other.  To save computing time, we use optimistic assumptions
8160 and increase the tolerance by a factor of about $\sqrt2$ for each recursive
8161 call.
8162
8163 In addition to the tolerance parameter, |arc_test| should also have parameters
8164 for ${1\over3}\vb\dot B(0)\vb$, ${2\over3}\vb\dot B({1\over2})\vb$, and
8165 ${1\over3}\vb\dot B(1)\vb$.  These quantities are relatively expensive to compute
8166 and they are needed in different instances of |arc_test|.
8167
8168 @c @t\4@>@<Declare subroutines needed by |arc_test|@>;
8169 scaled mp_arc_test (MP mp, scaled dx0, scaled dy0, scaled dx1, scaled dy1, 
8170                     scaled dx2, scaled dy2, scaled  v0, scaled v02, 
8171                     scaled v2, scaled a_goal, scaled tol) {
8172   boolean simple; /* are the control points confined to a $90^\circ$ sector? */
8173   scaled dx01, dy01, dx12, dy12, dx02, dy02;  /* bisection results */
8174   scaled v002, v022;
8175     /* twice the velocity magnitudes at $t={1\over4}$ and $t={3\over4}$ */
8176   scaled arc; /* best arc length estimate before recursion */
8177   @<Other local variables in |arc_test|@>;
8178   @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,
8179     |dx2|, |dy2|@>;
8180   @<Initialize |v002|, |v022|, and the arc length estimate |arc|; if it overflows
8181     set |arc_test| and |return|@>;
8182   @<Test if the control points are confined to one quadrant or rotating them
8183     $45^\circ$ would put them in one quadrant.  Then set |simple| appropriately@>;
8184   if ( simple && (abs(arc-v02-halfp(v0+v2)) <= tol) ) {
8185     if ( arc < a_goal ) {
8186       return arc;
8187     } else {
8188        @<Estimate when the arc length reaches |a_goal| and set |arc_test| to
8189          that time minus |two|@>;
8190     }
8191   } else {
8192     @<Use one or two recursive calls to compute the |arc_test| function@>;
8193   }
8194 }
8195
8196 @ The |tol| value should by multiplied by $\sqrt 2$ before making recursive
8197 calls, but $1.5$ is an adequate approximation.  It is best to avoid using
8198 |make_fraction| in this inner loop.
8199 @^inner loop@>
8200
8201 @<Use one or two recursive calls to compute the |arc_test| function@>=
8202
8203   @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is as
8204     large as possible@>;
8205   tol = tol + halfp(tol);
8206   a = mp_arc_test(mp, dx0,dy0, dx01,dy01, dx02,dy02, v0, v002, 
8207                   halfp(v02), a_new, tol);
8208   if ( a<0 )  {
8209      return (-halfp(two-a));
8210   } else { 
8211     @<Update |a_new| to reduce |a_new+a_aux| by |a|@>;
8212     b = mp_arc_test(mp, dx02,dy02, dx12,dy12, dx2,dy2,
8213                     halfp(v02), v022, v2, a_new, tol);
8214     if ( b<0 )  
8215       return (-halfp(-b) - half_unit);
8216     else  
8217       return (a + half(b-a));
8218   }
8219 }
8220
8221 @ @<Other local variables in |arc_test|@>=
8222 scaled a,b; /* results of recursive calls */
8223 scaled a_new,a_aux; /* the sum of these gives the |a_goal| */
8224
8225 @ @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is...@>=
8226 a_aux = el_gordo - a_goal;
8227 if ( a_goal > a_aux ) {
8228   a_aux = a_goal - a_aux;
8229   a_new = el_gordo;
8230 } else { 
8231   a_new = a_goal + a_goal;
8232   a_aux = 0;
8233 }
8234
8235 @ There is no need to maintain |a_aux| at this point so we use it as a temporary
8236 to force the additions and subtractions to be done in an order that avoids
8237 overflow.
8238
8239 @<Update |a_new| to reduce |a_new+a_aux| by |a|@>=
8240 if ( a > a_aux ) {
8241   a_aux = a_aux - a;
8242   a_new = a_new + a_aux;
8243 }
8244
8245 @ This code assumes all {\it dx} and {\it dy} variables have magnitude less than
8246 |fraction_four|.  To simplify the rest of the |arc_test| routine, we strengthen
8247 this assumption by requiring the norm of each $({\it dx},{\it dy})$ pair to obey
8248 this bound.  Note that recursive calls will maintain this invariant.
8249
8250 @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,...@>=
8251 dx01 = half(dx0 + dx1);
8252 dx12 = half(dx1 + dx2);
8253 dx02 = half(dx01 + dx12);
8254 dy01 = half(dy0 + dy1);
8255 dy12 = half(dy1 + dy2);
8256 dy02 = half(dy01 + dy12)
8257
8258 @ We should be careful to keep |arc<el_gordo| so that calling |arc_test| with
8259 |a_goal=el_gordo| is guaranteed to yield the arc length.
8260
8261 @<Initialize |v002|, |v022|, and the arc length estimate |arc|;...@>=
8262 v002 = mp_pyth_add(mp, dx01+half(dx0+dx02), dy01+half(dy0+dy02));
8263 v022 = mp_pyth_add(mp, dx12+half(dx02+dx2), dy12+half(dy02+dy2));
8264 tmp = halfp(v02+2);
8265 arc1 = v002 + half(halfp(v0+tmp) - v002);
8266 arc = v022 + half(halfp(v2+tmp) - v022);
8267 if ( (arc < el_gordo-arc1) )  {
8268   arc = arc+arc1;
8269 } else { 
8270   mp->arith_error = true;
8271   if ( a_goal==el_gordo )  return (el_gordo);
8272   else return (-two);
8273 }
8274
8275 @ @<Other local variables in |arc_test|@>=
8276 scaled tmp, tmp2; /* all purpose temporary registers */
8277 scaled arc1; /* arc length estimate for the first half */
8278
8279 @ @<Test if the control points are confined to one quadrant or rotating...@>=
8280 simple = ((dx0>=0) && (dx1>=0) && (dx2>=0)) ||
8281          ((dx0<=0) && (dx1<=0) && (dx2<=0));
8282 if ( simple )
8283   simple = ((dy0>=0) && (dy1>=0) && (dy2>=0)) ||
8284            ((dy0<=0) && (dy1<=0) && (dy2<=0));
8285 if ( ! simple ) {
8286   simple = ((dx0>=dy0) && (dx1>=dy1) && (dx2>=dy2)) ||
8287            ((dx0<=dy0) && (dx1<=dy1) && (dx2<=dy2));
8288   if ( simple ) 
8289     simple = ((-dx0>=dy0) && (-dx1>=dy1) && (-dx2>=dy2)) ||
8290              ((-dx0<=dy0) && (-dx1<=dy1) && (-dx2<=dy2));
8291 }
8292
8293 @ Since Simpson's rule is based on approximating the integrand by a parabola,
8294 @^Simpson's rule@>
8295 it is appropriate to use the same approximation to decide when the integral
8296 reaches the intermediate value |a_goal|.  At this point
8297 $$\eqalign{
8298     {\vb\dot B(0)\vb\over 3} &= \hbox{|v0|}, \qquad
8299     {\vb\dot B({1\over4})\vb\over 3} = {\hbox{|v002|}\over 2}, \qquad
8300     {\vb\dot B({1\over2})\vb\over 3} = {\hbox{|v02|}\over 2}, \cr
8301     {\vb\dot B({3\over4})\vb\over 3} &= {\hbox{|v022|}\over 2}, \qquad
8302     {\vb\dot B(1)\vb\over 3} = \hbox{|v2|} \cr
8303 }
8304 $$
8305 and
8306 $$ {\vb\dot B(t)\vb\over 3} \approx
8307   \cases{B\left(\hbox{|v0|},
8308       \hbox{|v002|}-{1\over 2}\hbox{|v0|}-{1\over 4}\hbox{|v02|},
8309       {1\over 2}\hbox{|v02|}; 2t \right)&
8310     if $t\le{1\over 2}$\cr
8311   B\left({1\over 2}\hbox{|v02|},
8312       \hbox{|v022|}-{1\over 4}\hbox{|v02|}-{1\over 2}\hbox{|v2|},
8313       \hbox{|v2|}; 2t-1 \right)&
8314     if $t\ge{1\over 2}$.\cr}
8315  \eqno (*)
8316 $$
8317 We can integrate $\vb\dot B(t)\vb$ by using
8318 $$\int 3B(a,b,c;\tau)\,dt =
8319   {B(0,a,a+b,a+b+c;\tau) + {\rm constant} \over {d\tau\over dt}}.
8320 $$
8321
8322 This construction allows us to find the time when the arc length reaches
8323 |a_goal| by solving a cubic equation of the form
8324 $$ B(0,a,a+b,a+b+c;\tau) = x, $$
8325 where $\tau$ is $2t$ or $2t+1$, $x$ is |a_goal| or |a_goal-arc1|, and $a$, $b$,
8326 and $c$ are the Bernshte{\u\i}n coefficients from $(*)$ divided by
8327 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
8328 $d\tau\over dt$.  We shall define a function |solve_rising_cubic| that finds
8329 $\tau$ given $a$, $b$, $c$, and $x$.
8330
8331 @<Estimate when the arc length reaches |a_goal| and set |arc_test| to...@>=
8332
8333   tmp = (v02 + 2) / 4;
8334   if ( a_goal<=arc1 ) {
8335     tmp2 = halfp(v0);
8336     return 
8337       (halfp(mp_solve_rising_cubic(mp, tmp2, arc1-tmp2-tmp, tmp, a_goal))- two);
8338   } else { 
8339     tmp2 = halfp(v2);
8340     return ((half_unit - two) +
8341       halfp(mp_solve_rising_cubic(mp, tmp, arc-arc1-tmp-tmp2, tmp2, a_goal-arc1)));
8342   }
8343 }
8344
8345 @ Here is the |solve_rising_cubic| routine that finds the time~$t$ when
8346 $$ B(0, a, a+b, a+b+c; t) = x. $$
8347 This routine is based on |crossing_point| but is simplified by the
8348 assumptions that $B(a,b,c;t)\ge0$ for $0\le t\le1$ and that |0<=x<=a+b+c|.
8349 If rounding error causes this condition to be violated slightly, we just ignore
8350 it and proceed with binary search.  This finds a time when the function value
8351 reaches |x| and the slope is positive.
8352
8353 @<Declare subroutines needed by |arc_test|@>=
8354 scaled mp_solve_rising_cubic (MP mp,scaled a, scaled b,  scaled c, scaled x) {
8355   scaled ab, bc, ac; /* bisection results */
8356   integer t; /* $2^k+q$ where unscaled answer is in $[q2^{-k},(q+1)2^{-k})$ */
8357   integer xx; /* temporary for updating |x| */
8358   if ( (a<0) || (c<0) ) mp_confusion(mp, "rising?");
8359 @:this can't happen rising?}{\quad rising?@>
8360   if ( x<=0 ) {
8361         return 0;
8362   } else if ( x >= a+b+c ) {
8363     return unity;
8364   } else { 
8365     t = 1;
8366     @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than
8367       |el_gordo div 3|@>;
8368     do {  
8369       t+=t;
8370       @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>;
8371       xx = x - a - ab - ac;
8372       if ( xx < -x ) { x+=x; b=ab; c=ac;  }
8373       else { x = x + xx;  a=ac; b=mp->bc; t = t+1; };
8374     } while (t < unity);
8375     return (t - unity);
8376   }
8377 }
8378
8379 @ @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>=
8380 ab = half(a+b);
8381 bc = half(b+c);
8382 ac = half(ab+bc)
8383
8384 @ @d one_third_el_gordo 05252525252 /* upper bound on |a|, |b|, and |c| */
8385
8386 @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than...@>=
8387 while ((a>one_third_el_gordo)||(b>one_third_el_gordo)||(c>one_third_el_gordo)) { 
8388   a = halfp(a);
8389   b = half(b);
8390   c = halfp(c);
8391   x = halfp(x);
8392 }
8393
8394 @ It is convenient to have a simpler interface to |arc_test| that requires no
8395 unnecessary arguments and ensures that each $({\it dx},{\it dy})$ pair has
8396 length less than |fraction_four|.
8397
8398 @d arc_tol   16  /* quit when change in arc length estimate reaches this */
8399
8400 @c scaled mp_do_arc_test (MP mp,scaled dx0, scaled dy0, scaled dx1, 
8401                           scaled dy1, scaled dx2, scaled dy2, scaled a_goal) {
8402   scaled v0,v1,v2; /* length of each $({\it dx},{\it dy})$ pair */
8403   scaled v02; /* twice the norm of the quadratic at $t={1\over2}$ */
8404   v0 = mp_pyth_add(mp, dx0,dy0);
8405   v1 = mp_pyth_add(mp, dx1,dy1);
8406   v2 = mp_pyth_add(mp, dx2,dy2);
8407   if ( (v0>=fraction_four) || (v1>=fraction_four) || (v2>=fraction_four) ) { 
8408     mp->arith_error = true;
8409     if ( a_goal==el_gordo )  return el_gordo;
8410     else return (-two);
8411   } else { 
8412     v02 = mp_pyth_add(mp, dx1+half(dx0+dx2), dy1+half(dy0+dy2));
8413     return (mp_arc_test(mp, dx0,dy0, dx1,dy1, dx2,dy2,
8414                                  v0, v02, v2, a_goal, arc_tol));
8415   }
8416 }
8417
8418 @ Now it is easy to find the arc length of an entire path.
8419
8420 @c scaled mp_get_arc_length (MP mp,pointer h) {
8421   pointer p,q; /* for traversing the path */
8422   scaled a,a_tot; /* current and total arc lengths */
8423   a_tot = 0;
8424   p = h;
8425   while ( right_type(p)!=mp_endpoint ){ 
8426     q = link(p);
8427     a = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8428       left_x(q)-right_x(p), left_y(q)-right_y(p),
8429       x_coord(q)-left_x(q), y_coord(q)-left_y(q), el_gordo);
8430     a_tot = mp_slow_add(mp, a, a_tot);
8431     if ( q==h ) break;  else p=q;
8432   }
8433   check_arith;
8434   return a_tot;
8435 }
8436
8437 @ The inverse operation of finding the time on a path~|h| when the arc length
8438 reaches some value |arc0| can also be accomplished via |do_arc_test|.  Some care
8439 is required to handle very large times or negative times on cyclic paths.  For
8440 non-cyclic paths, |arc0| values that are negative or too large cause
8441 |get_arc_time| to return 0 or the length of path~|h|.
8442
8443 If |arc0| is greater than the arc length of a cyclic path~|h|, the result is a
8444 time value greater than the length of the path.  Since it could be much greater,
8445 we must be prepared to compute the arc length of path~|h| and divide this into
8446 |arc0| to find how many multiples of the length of path~|h| to add.
8447
8448 @c scaled mp_get_arc_time (MP mp,pointer h, scaled  arc0) {
8449   pointer p,q; /* for traversing the path */
8450   scaled t_tot; /* accumulator for the result */
8451   scaled t; /* the result of |do_arc_test| */
8452   scaled arc; /* portion of |arc0| not used up so far */
8453   integer n; /* number of extra times to go around the cycle */
8454   if ( arc0<0 ) {
8455     @<Deal with a negative |arc0| value and |return|@>;
8456   }
8457   if ( arc0==el_gordo ) decr(arc0);
8458   t_tot = 0;
8459   arc = arc0;
8460   p = h;
8461   while ( (right_type(p)!=mp_endpoint) && (arc>0) ) {
8462     q = link(p);
8463     t = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8464       left_x(q)-right_x(p), left_y(q)-right_y(p),
8465       x_coord(q)-left_x(q), y_coord(q)-left_y(q), arc);
8466     @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>;
8467     if ( q==h ) {
8468       @<Update |t_tot| and |arc| to avoid going around the cyclic
8469         path too many times but set |arith_error:=true| and |goto done| on
8470         overflow@>;
8471     }
8472     p = q;
8473   }
8474   check_arith;
8475   return t_tot;
8476 }
8477
8478 @ @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>=
8479 if ( t<0 ) { t_tot = t_tot + t + two;  arc = 0;  }
8480 else { t_tot = t_tot + unity;  arc = arc - t;  }
8481
8482 @ @<Deal with a negative |arc0| value and |return|@>=
8483
8484   if ( left_type(h)==mp_endpoint ) {
8485     t_tot=0;
8486   } else { 
8487     p = mp_htap_ypoc(mp, h);
8488     t_tot = -mp_get_arc_time(mp, p, -arc0);
8489     mp_toss_knot_list(mp, p);
8490   }
8491   check_arith;
8492   return t_tot;
8493 }
8494
8495 @ @<Update |t_tot| and |arc| to avoid going around the cyclic...@>=
8496 if ( arc>0 ) { 
8497   n = arc / (arc0 - arc);
8498   arc = arc - n*(arc0 - arc);
8499   if ( t_tot > el_gordo / (n+1) ) { 
8500     mp->arith_error = true;
8501     t_tot = el_gordo;
8502     break;
8503   }
8504   t_tot = (n + 1)*t_tot;
8505 }
8506
8507 @* \[20] Data structures for pens.
8508 A Pen in \MP\ can be either elliptical or polygonal.  Elliptical pens result
8509 in \ps\ \&{stroke} commands, while anything drawn with a polygonal pen is
8510 @:stroke}{\&{stroke} command@>
8511 converted into an area fill as described in the next part of this program.
8512 The mathematics behind this process is based on simple aspects of the theory
8513 of tracings developed by Leo Guibas, Lyle Ramshaw, and Jorge Stolfi
8514 [``A kinematic framework for computational geometry,'' Proc.\ IEEE Symp.\
8515 Foundations of Computer Science {\bf 24} (1983), 100--111].
8516
8517 Polygonal pens are created from paths via \MP's \&{makepen} primitive.
8518 @:makepen_}{\&{makepen} primitive@>
8519 This path representation is almost sufficient for our purposes except that
8520 a pen path should always be a convex polygon with the vertices in
8521 counter-clockwise order.
8522 Since we will need to scan pen polygons both forward and backward, a pen
8523 should be represented as a doubly linked ring of knot nodes.  There is
8524 room for the extra back pointer because we do not need the
8525 |left_type| or |right_type| fields.  In fact, we don't need the |left_x|,
8526 |left_y|, |right_x|, or |right_y| fields either but we leave these alone
8527 so that certain procedures can operate on both pens and paths.  In particular,
8528 pens can be copied using |copy_path| and recycled using |toss_knot_list|.
8529
8530 @d knil info
8531   /* this replaces the |left_type| and |right_type| fields in a pen knot */
8532
8533 @ The |make_pen| procedure turns a path into a pen by initializing
8534 the |knil| pointers and making sure the knots form a convex polygon.
8535 Thus each cubic in the given path becomes a straight line and the control
8536 points are ignored.  If the path is not cyclic, the ends are connected by a
8537 straight line.
8538
8539 @d copy_pen(A) mp_make_pen(mp, mp_copy_path(mp, (A)),false)
8540
8541 @c @<Declare a function called |convex_hull|@>;
8542 pointer mp_make_pen (MP mp,pointer h, boolean need_hull) {
8543   pointer p,q; /* two consecutive knots */
8544   q=h;
8545   do {  
8546     p=q; q=link(q);
8547     knil(q)=p;
8548   } while (q!=h);
8549   if ( need_hull ){ 
8550     h=mp_convex_hull(mp, h);
8551     @<Make sure |h| isn't confused with an elliptical pen@>;
8552   }
8553   return h;
8554 }
8555
8556 @ The only information required about an elliptical pen is the overall
8557 transformation that has been applied to the original \&{pencircle}.
8558 @:pencircle_}{\&{pencircle} primitive@>
8559 Since it suffices to keep track of how the three points $(0,0)$, $(1,0)$,
8560 and $(0,1)$ are transformed, an elliptical pen can be stored in a single
8561 knot node and transformed as if it were a path.
8562
8563 @d pen_is_elliptical(A) ((A)==link((A)))
8564
8565 @c pointer mp_get_pen_circle (MP mp,scaled diam) {
8566   pointer h; /* the knot node to return */
8567   h=mp_get_node(mp, knot_node_size);
8568   link(h)=h; knil(h)=h;
8569   originator(h)=mp_program_code;
8570   x_coord(h)=0; y_coord(h)=0;
8571   left_x(h)=diam; left_y(h)=0;
8572   right_x(h)=0; right_y(h)=diam;
8573   return h;
8574 }
8575
8576 @ If the polygon being returned by |make_pen| has only one vertex, it will
8577 be interpreted as an elliptical pen.  This is no problem since a degenerate
8578 polygon can equally well be thought of as a degenerate ellipse.  We need only
8579 initialize the |left_x|, |left_y|, |right_x|, and |right_y| fields.
8580
8581 @<Make sure |h| isn't confused with an elliptical pen@>=
8582 if ( pen_is_elliptical( h) ){ 
8583   left_x(h)=x_coord(h); left_y(h)=y_coord(h);
8584   right_x(h)=x_coord(h); right_y(h)=y_coord(h);
8585 }
8586
8587 @ We have to cheat a little here but most operations on pens only use
8588 the first three words in each knot node.
8589 @^data structure assumptions@>
8590
8591 @<Initialize a pen at |test_pen| so that it fits in nine words@>=
8592 x_coord(test_pen)=-half_unit;
8593 y_coord(test_pen)=0;
8594 x_coord(test_pen+3)=half_unit;
8595 y_coord(test_pen+3)=0;
8596 x_coord(test_pen+6)=0;
8597 y_coord(test_pen+6)=unity;
8598 link(test_pen)=test_pen+3;
8599 link(test_pen+3)=test_pen+6;
8600 link(test_pen+6)=test_pen;
8601 knil(test_pen)=test_pen+6;
8602 knil(test_pen+3)=test_pen;
8603 knil(test_pen+6)=test_pen+3
8604
8605 @ Printing a polygonal pen is very much like printing a path
8606
8607 @<Declare subroutines for printing expressions@>=
8608 void mp_pr_pen (MP mp,pointer h) {
8609   pointer p,q; /* for list traversal */
8610   if ( pen_is_elliptical(h) ) {
8611     @<Print the elliptical pen |h|@>;
8612   } else { 
8613     p=h;
8614     do {  
8615       mp_print_two(mp, x_coord(p),y_coord(p));
8616       mp_print_nl(mp, " .. ");
8617       @<Advance |p| making sure the links are OK and |return| if there is
8618         a problem@>;
8619      } while (p!=h);
8620      mp_print(mp, "cycle");
8621   }
8622 }
8623
8624 @ @<Advance |p| making sure the links are OK and |return| if there is...@>=
8625 q=link(p);
8626 if ( (q==null) || (knil(q)!=p) ) { 
8627   mp_print_nl(mp, "???"); return; /* this won't happen */
8628 @.???@>
8629 }
8630 p=q
8631
8632 @ @<Print the elliptical pen |h|@>=
8633
8634 mp_print(mp, "pencircle transformed (");
8635 mp_print_scaled(mp, x_coord(h));
8636 mp_print_char(mp, ',');
8637 mp_print_scaled(mp, y_coord(h));
8638 mp_print_char(mp, ',');
8639 mp_print_scaled(mp, left_x(h)-x_coord(h));
8640 mp_print_char(mp, ',');
8641 mp_print_scaled(mp, right_x(h)-x_coord(h));
8642 mp_print_char(mp, ',');
8643 mp_print_scaled(mp, left_y(h)-y_coord(h));
8644 mp_print_char(mp, ',');
8645 mp_print_scaled(mp, right_y(h)-y_coord(h));
8646 mp_print_char(mp, ')');
8647 }
8648
8649 @ Here us another version of |pr_pen| that prints the pen as a diagnostic
8650 message.
8651
8652 @<Declare subroutines for printing expressions@>=
8653 void mp_print_pen (MP mp,pointer h, char *s, boolean nuline) { 
8654   mp_print_diagnostic(mp, "Pen",s,nuline); mp_print_ln(mp);
8655 @.Pen at line...@>
8656   mp_pr_pen(mp, h);
8657   mp_end_diagnostic(mp, true);
8658 }
8659
8660 @ Making a polygonal pen into a path involves restoring the |left_type| and
8661 |right_type| fields and setting the control points so as to make a polygonal
8662 path.
8663
8664 @c 
8665 void mp_make_path (MP mp,pointer h) {
8666   pointer p; /* for traversing the knot list */
8667   small_number k; /* a loop counter */
8668   @<Other local variables in |make_path|@>;
8669   if ( pen_is_elliptical(h) ) {
8670     @<Make the elliptical pen |h| into a path@>;
8671   } else { 
8672     p=h;
8673     do {  
8674       left_type(p)=mp_explicit;
8675       right_type(p)=mp_explicit;
8676       @<copy the coordinates of knot |p| into its control points@>;
8677        p=link(p);
8678     } while (p!=h);
8679   }
8680 }
8681
8682 @ @<copy the coordinates of knot |p| into its control points@>=
8683 left_x(p)=x_coord(p);
8684 left_y(p)=y_coord(p);
8685 right_x(p)=x_coord(p);
8686 right_y(p)=y_coord(p)
8687
8688 @ We need an eight knot path to get a good approximation to an ellipse.
8689
8690 @<Make the elliptical pen |h| into a path@>=
8691
8692   @<Extract the transformation parameters from the elliptical pen~|h|@>;
8693   p=h;
8694   for (k=0;k<=7;k++ ) { 
8695     @<Initialize |p| as the |k|th knot of a circle of unit diameter,
8696       transforming it appropriately@>;
8697     if ( k==7 ) link(p)=h;  else link(p)=mp_get_node(mp, knot_node_size);
8698     p=link(p);
8699   }
8700 }
8701
8702 @ @<Extract the transformation parameters from the elliptical pen~|h|@>=
8703 center_x=x_coord(h);
8704 center_y=y_coord(h);
8705 width_x=left_x(h)-center_x;
8706 width_y=left_y(h)-center_y;
8707 height_x=right_x(h)-center_x;
8708 height_y=right_y(h)-center_y
8709
8710 @ @<Other local variables in |make_path|@>=
8711 scaled center_x,center_y; /* translation parameters for an elliptical pen */
8712 scaled width_x,width_y; /* the effect of a unit change in $x$ */
8713 scaled height_x,height_y; /* the effect of a unit change in $y$ */
8714 scaled dx,dy; /* the vector from knot |p| to its right control point */
8715 integer kk;
8716   /* |k| advanced $270^\circ$ around the ring (cf. $\sin\theta=\cos(\theta+270)$) */
8717
8718 @ The only tricky thing here are the tables |half_cos| and |d_cos| used to
8719 find the point $k/8$ of the way around the circle and the direction vector
8720 to use there.
8721
8722 @<Initialize |p| as the |k|th knot of a circle of unit diameter,...@>=
8723 kk=(k+6)% 8;
8724 x_coord(p)=center_x+mp_take_fraction(mp, mp->half_cos[k],width_x)
8725            +mp_take_fraction(mp, mp->half_cos[kk],height_x);
8726 y_coord(p)=center_y+mp_take_fraction(mp, mp->half_cos[k],width_y)
8727            +mp_take_fraction(mp, mp->half_cos[kk],height_y);
8728 dx=-mp_take_fraction(mp, mp->d_cos[kk],width_x)
8729    +mp_take_fraction(mp, mp->d_cos[k],height_x);
8730 dy=-mp_take_fraction(mp, mp->d_cos[kk],width_y)
8731    +mp_take_fraction(mp, mp->d_cos[k],height_y);
8732 right_x(p)=x_coord(p)+dx;
8733 right_y(p)=y_coord(p)+dy;
8734 left_x(p)=x_coord(p)-dx;
8735 left_y(p)=y_coord(p)-dy;
8736 left_type(p)=mp_explicit;
8737 right_type(p)=mp_explicit;
8738 originator(p)=mp_program_code
8739
8740 @ @<Glob...@>=
8741 fraction half_cos[8]; /* ${1\over2}\cos(45k)$ */
8742 fraction d_cos[8]; /* a magic constant times $\cos(45k)$ */
8743
8744 @ The magic constant for |d_cos| is the distance between $({1\over2},0)$ and
8745 $({1\over4}\sqrt2,{1\over4}\sqrt2)$ times the result of the |velocity|
8746 function for $\theta=\phi=22.5^\circ$.  This comes out to be
8747 $$ d = {\sqrt{2-\sqrt2}\over 3+3\cos22.5^\circ}
8748   \approx 0.132608244919772.
8749 $$
8750
8751 @<Set init...@>=
8752 mp->half_cos[0]=fraction_half;
8753 mp->half_cos[1]=94906266; /* $2^{26}\sqrt2\approx94906265.62$ */
8754 mp->half_cos[2]=0;
8755 mp->d_cos[0]=35596755; /* $2^{28}d\approx35596754.69$ */
8756 mp->d_cos[1]=25170707; /* $2^{27}\sqrt2\,d\approx25170706.63$ */
8757 mp->d_cos[2]=0;
8758 for (k=3;k<= 4;k++ ) { 
8759   mp->half_cos[k]=-mp->half_cos[4-k];
8760   mp->d_cos[k]=-mp->d_cos[4-k];
8761 }
8762 for (k=5;k<= 7;k++ ) { 
8763   mp->half_cos[k]=mp->half_cos[8-k];
8764   mp->d_cos[k]=mp->d_cos[8-k];
8765 }
8766
8767 @ The |convex_hull| function forces a pen polygon to be convex when it is
8768 returned by |make_pen| and after any subsequent transformation where rounding
8769 error might allow the convexity to be lost.
8770 The convex hull algorithm used here is described by F.~P. Preparata and
8771 M.~I. Shamos [{\sl Computational Geometry}, Springer-Verlag, 1985].
8772
8773 @<Declare a function called |convex_hull|@>=
8774 @<Declare a procedure called |move_knot|@>;
8775 pointer mp_convex_hull (MP mp,pointer h) { /* Make a polygonal pen convex */
8776   pointer l,r; /* the leftmost and rightmost knots */
8777   pointer p,q; /* knots being scanned */
8778   pointer s; /* the starting point for an upcoming scan */
8779   scaled dx,dy; /* a temporary pointer */
8780   if ( pen_is_elliptical(h) ) {
8781      return h;
8782   } else { 
8783     @<Set |l| to the leftmost knot in polygon~|h|@>;
8784     @<Set |r| to the rightmost knot in polygon~|h|@>;
8785     if ( l!=r ) { 
8786       s=link(r);
8787       @<Find any knots on the path from |l| to |r| above the |l|-|r| line and
8788         move them past~|r|@>;
8789       @<Find any knots on the path from |s| to |l| below the |l|-|r| line and
8790         move them past~|l|@>;
8791       @<Sort the path from |l| to |r| by increasing $x$@>;
8792       @<Sort the path from |r| to |l| by decreasing $x$@>;
8793     }
8794     if ( l!=link(l) ) {
8795       @<Do a Gramm scan and remove vertices where there is no left turn@>;
8796     }
8797     return l;
8798   }
8799 }
8800
8801 @ All comparisons are done primarily on $x$ and secondarily on $y$.
8802
8803 @<Set |l| to the leftmost knot in polygon~|h|@>=
8804 l=h;
8805 p=link(h);
8806 while ( p!=h ) { 
8807   if ( x_coord(p)<=x_coord(l) )
8808     if ( (x_coord(p)<x_coord(l)) || (y_coord(p)<y_coord(l)) )
8809       l=p;
8810   p=link(p);
8811 }
8812
8813 @ @<Set |r| to the rightmost knot in polygon~|h|@>=
8814 r=h;
8815 p=link(h);
8816 while ( p!=h ) { 
8817   if ( x_coord(p)>=x_coord(r) )
8818     if ( (x_coord(p)>x_coord(r)) || (y_coord(p)>y_coord(r)) )
8819       r=p;
8820   p=link(p);
8821 }
8822
8823 @ @<Find any knots on the path from |l| to |r| above the |l|-|r| line...@>=
8824 dx=x_coord(r)-x_coord(l);
8825 dy=y_coord(r)-y_coord(l);
8826 p=link(l);
8827 while ( p!=r ) { 
8828   q=link(p);
8829   if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))>0 )
8830     mp_move_knot(mp, p, r);
8831   p=q;
8832 }
8833
8834 @ The |move_knot| procedure removes |p| from a doubly linked list and inserts
8835 it after |q|.
8836
8837 @ @<Declare a procedure called |move_knot|@>=
8838 void mp_move_knot (MP mp,pointer p, pointer q) { 
8839   link(knil(p))=link(p);
8840   knil(link(p))=knil(p);
8841   knil(p)=q;
8842   link(p)=link(q);
8843   link(q)=p;
8844   knil(link(p))=p;
8845 }
8846
8847 @ @<Find any knots on the path from |s| to |l| below the |l|-|r| line...@>=
8848 p=s;
8849 while ( p!=l ) { 
8850   q=link(p);
8851   if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))<0 )
8852     mp_move_knot(mp, p,l);
8853   p=q;
8854 }
8855
8856 @ The list is likely to be in order already so we just do linear insertions.
8857 Secondary comparisons on $y$ ensure that the sort is consistent with the
8858 choice of |l| and |r|.
8859
8860 @<Sort the path from |l| to |r| by increasing $x$@>=
8861 p=link(l);
8862 while ( p!=r ) { 
8863   q=knil(p);
8864   while ( x_coord(q)>x_coord(p) ) q=knil(q);
8865   while ( x_coord(q)==x_coord(p) ) {
8866     if ( y_coord(q)>y_coord(p) ) q=knil(q); else break;
8867   }
8868   if ( q==knil(p) ) p=link(p);
8869   else { p=link(p); mp_move_knot(mp, knil(p),q); };
8870 }
8871
8872 @ @<Sort the path from |r| to |l| by decreasing $x$@>=
8873 p=link(r);
8874 while ( p!=l ){ 
8875   q=knil(p);
8876   while ( x_coord(q)<x_coord(p) ) q=knil(q);
8877   while ( x_coord(q)==x_coord(p) ) {
8878     if ( y_coord(q)<y_coord(p) ) q=knil(q); else break;
8879   }
8880   if ( q==knil(p) ) p=link(p);
8881   else { p=link(p); mp_move_knot(mp, knil(p),q); };
8882 }
8883
8884 @ The condition involving |ab_vs_cd| tests if there is not a left turn
8885 at knot |q|.  There usually will be a left turn so we streamline the case
8886 where the |then| clause is not executed.
8887
8888 @<Do a Gramm scan and remove vertices where there...@>=
8889
8890 p=l; q=link(l);
8891 while (1) { 
8892   dx=x_coord(q)-x_coord(p);
8893   dy=y_coord(q)-y_coord(p);
8894   p=q; q=link(q);
8895   if ( p==l ) break;
8896   if ( p!=r )
8897     if ( mp_ab_vs_cd(mp, dx,y_coord(q)-y_coord(p),dy,x_coord(q)-x_coord(p))<=0 ) {
8898       @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>;
8899     }
8900   }
8901 }
8902
8903 @ @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>=
8904
8905 s=knil(p);
8906 mp_free_node(mp, p,knot_node_size);
8907 link(s)=q; knil(q)=s;
8908 if ( s==l ) p=s;
8909 else { p=knil(s); q=s; };
8910 }
8911
8912 @ The |find_offset| procedure sets global variables |(cur_x,cur_y)| to the
8913 offset associated with the given direction |(x,y)|.  If two different offsets
8914 apply, it chooses one of them.
8915
8916 @c 
8917 void mp_find_offset (MP mp,scaled x, scaled y, pointer h) {
8918   pointer p,q; /* consecutive knots */
8919   scaled wx,wy,hx,hy;
8920   /* the transformation matrix for an elliptical pen */
8921   fraction xx,yy; /* untransformed offset for an elliptical pen */
8922   fraction d; /* a temporary register */
8923   if ( pen_is_elliptical(h) ) {
8924     @<Find the offset for |(x,y)| on the elliptical pen~|h|@>
8925   } else { 
8926     q=h;
8927     do {  
8928       p=q; q=link(q);
8929     } while (! mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)>=0);
8930     do {  
8931       p=q; q=link(q);
8932     } while (! mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)<=0);
8933     mp->cur_x=x_coord(p);
8934     mp->cur_y=y_coord(p);
8935   }
8936 }
8937
8938 @ @<Glob...@>=
8939 scaled cur_x;
8940 scaled cur_y; /* all-purpose return value registers */
8941
8942 @ @<Find the offset for |(x,y)| on the elliptical pen~|h|@>=
8943 if ( (x==0) && (y==0) ) {
8944   mp->cur_x=x_coord(h); mp->cur_y=y_coord(h);  
8945 } else { 
8946   @<Find the non-constant part of the transformation for |h|@>;
8947   while ( (abs(x)<fraction_half) && (abs(y)<fraction_half) ){ 
8948     x+=x; y+=y;  
8949   };
8950   @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the
8951     untransformed version of |(x,y)|@>;
8952   mp->cur_x=x_coord(h)+mp_take_fraction(mp, xx,wx)+mp_take_fraction(mp, yy,hx);
8953   mp->cur_y=y_coord(h)+mp_take_fraction(mp, xx,wy)+mp_take_fraction(mp, yy,hy);
8954 }
8955
8956 @ @<Find the non-constant part of the transformation for |h|@>=
8957 wx=left_x(h)-x_coord(h);
8958 wy=left_y(h)-y_coord(h);
8959 hx=right_x(h)-x_coord(h);
8960 hy=right_y(h)-y_coord(h)
8961
8962 @ @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the...@>=
8963 yy=-(mp_take_fraction(mp, x,hy)+mp_take_fraction(mp, y,-hx));
8964 xx=mp_take_fraction(mp, x,-wy)+mp_take_fraction(mp, y,wx);
8965 d=mp_pyth_add(mp, xx,yy);
8966 if ( d>0 ) { 
8967   xx=half(mp_make_fraction(mp, xx,d));
8968   yy=half(mp_make_fraction(mp, yy,d));
8969 }
8970
8971 @ Finding the bounding box of a pen is easy except if the pen is elliptical.
8972 But we can handle that case by just calling |find_offset| twice.  The answer
8973 is stored in the global variables |minx|, |maxx|, |miny|, and |maxy|.
8974
8975 @c 
8976 void mp_pen_bbox (MP mp,pointer h) {
8977   pointer p; /* for scanning the knot list */
8978   if ( pen_is_elliptical(h) ) {
8979     @<Find the bounding box of an elliptical pen@>;
8980   } else { 
8981     minx=x_coord(h); maxx=minx;
8982     miny=y_coord(h); maxy=miny;
8983     p=link(h);
8984     while ( p!=h ) {
8985       if ( x_coord(p)<minx ) minx=x_coord(p);
8986       if ( y_coord(p)<miny ) miny=y_coord(p);
8987       if ( x_coord(p)>maxx ) maxx=x_coord(p);
8988       if ( y_coord(p)>maxy ) maxy=y_coord(p);
8989       p=link(p);
8990     }
8991   }
8992 }
8993
8994 @ @<Find the bounding box of an elliptical pen@>=
8995
8996 mp_find_offset(mp, 0,fraction_one,h);
8997 maxx=mp->cur_x;
8998 minx=2*x_coord(h)-mp->cur_x;
8999 mp_find_offset(mp, -fraction_one,0,h);
9000 maxy=mp->cur_y;
9001 miny=2*y_coord(h)-mp->cur_y;
9002 }
9003
9004 @* \[21] Edge structures.
9005 Now we come to \MP's internal scheme for representing pictures.
9006 The representation is very different from \MF's edge structures
9007 because \MP\ pictures contain \ps\ graphics objects instead of pixel
9008 images.  However, the basic idea is somewhat similar in that shapes
9009 are represented via their boundaries.
9010
9011 The main purpose of edge structures is to keep track of graphical objects
9012 until it is time to translate them into \ps.  Since \MP\ does not need to
9013 know anything about an edge structure other than how to translate it into
9014 \ps\ and how to find its bounding box, edge structures can be just linked
9015 lists of graphical objects.  \MP\ has no easy way to determine whether
9016 two such objects overlap, but it suffices to draw the first one first and
9017 let the second one overwrite it if necessary.
9018
9019 @<Types...@>=
9020 enum mp_graphical_object_code {
9021   @<Graphical object codes@>
9022 };
9023
9024 @ Let's consider the types of graphical objects one at a time.
9025 First of all, a filled contour is represented by a eight-word node.  The first
9026 word contains |type| and |link| fields, and the next six words contain a
9027 pointer to a cyclic path and the value to use for \ps' \&{currentrgbcolor}
9028 parameter.  If a pen is used for filling |pen_p|, |ljoin_val| and |miterlim_val|
9029 give the relevant information.
9030
9031 @d path_p(A) link((A)+1)
9032   /* a pointer to the path that needs filling */
9033 @d pen_p(A) info((A)+1)
9034   /* a pointer to the pen to fill or stroke with */
9035 @d color_model(A) type((A)+2) /*  the color model  */
9036 @d obj_red_loc(A) ((A)+3)  /* the first of three locations for the color */
9037 @d obj_cyan_loc obj_red_loc  /* the first of four locations for the color */
9038 @d obj_grey_loc obj_red_loc  /* the location for the color */
9039 @d red_val(A) mp->mem[(A)+3].sc
9040   /* the red component of the color in the range $0\ldots1$ */
9041 @d cyan_val red_val
9042 @d grey_val red_val
9043 @d green_val(A) mp->mem[(A)+4].sc
9044   /* the green component of the color in the range $0\ldots1$ */
9045 @d magenta_val green_val
9046 @d blue_val(A) mp->mem[(A)+5].sc
9047   /* the blue component of the color in the range $0\ldots1$ */
9048 @d yellow_val blue_val
9049 @d black_val(A) mp->mem[(A)+6].sc
9050   /* the blue component of the color in the range $0\ldots1$ */
9051 @d ljoin_val(A) name_type((A))  /* the value of \&{linejoin} */
9052 @:mp_linejoin_}{\&{linejoin} primitive@>
9053 @d miterlim_val(A) mp->mem[(A)+7].sc  /* the value of \&{miterlimit} */
9054 @:mp_miterlimit_}{\&{miterlimit} primitive@>
9055 @d obj_color_part(A) mp->mem[(A)+3-red_part].sc
9056   /* interpret an object pointer that has been offset by |red_part..blue_part| */
9057 @d pre_script(A) mp->mem[(A)+8].hh.lh
9058 @d post_script(A) mp->mem[(A)+8].hh.rh
9059 @d fill_node_size 9
9060
9061 @ @<Graphical object codes@>=
9062 mp_fill_code=1,
9063
9064 @ @c 
9065 pointer mp_new_fill_node (MP mp,pointer p) {
9066   /* make a fill node for cyclic path |p| and color black */
9067   pointer t; /* the new node */
9068   t=mp_get_node(mp, fill_node_size);
9069   type(t)=mp_fill_code;
9070   path_p(t)=p;
9071   pen_p(t)=null; /* |null| means don't use a pen */
9072   red_val(t)=0;
9073   green_val(t)=0;
9074   blue_val(t)=0;
9075   black_val(t)=0;
9076   color_model(t)=mp_uninitialized_model;
9077   pre_script(t)=null;
9078   post_script(t)=null;
9079   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9080   return t;
9081 }
9082
9083 @ @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>=
9084 if ( mp->internal[mp_linejoin]>unity ) ljoin_val(t)=2;
9085 else if ( mp->internal[mp_linejoin]>0 ) ljoin_val(t)=1;
9086 else ljoin_val(t)=0;
9087 if ( mp->internal[mp_miterlimit]<unity )
9088   miterlim_val(t)=unity;
9089 else
9090   miterlim_val(t)=mp->internal[mp_miterlimit]
9091
9092 @ A stroked path is represented by an eight-word node that is like a filled
9093 contour node except that it contains the current \&{linecap} value, a scale
9094 factor for the dash pattern, and a pointer that is non-null if the stroke
9095 is to be dashed.  The purpose of the scale factor is to allow a picture to
9096 be transformed without touching the picture that |dash_p| points to.
9097
9098 @d dash_p(A) link((A)+9)
9099   /* a pointer to the edge structure that gives the dash pattern */
9100 @d lcap_val(A) type((A)+9)
9101   /* the value of \&{linecap} */
9102 @:mp_linecap_}{\&{linecap} primitive@>
9103 @d dash_scale(A) mp->mem[(A)+10].sc /* dash lengths are scaled by this factor */
9104 @d stroked_node_size 11
9105
9106 @ @<Graphical object codes@>=
9107 mp_stroked_code=2,
9108
9109 @ @c 
9110 pointer mp_new_stroked_node (MP mp,pointer p) {
9111   /* make a stroked node for path |p| with |pen_p(p)| temporarily |null| */
9112   pointer t; /* the new node */
9113   t=mp_get_node(mp, stroked_node_size);
9114   type(t)=mp_stroked_code;
9115   path_p(t)=p; pen_p(t)=null;
9116   dash_p(t)=null;
9117   dash_scale(t)=unity;
9118   red_val(t)=0;
9119   green_val(t)=0;
9120   blue_val(t)=0;
9121   black_val(t)=0;
9122   color_model(t)=mp_uninitialized_model;
9123   pre_script(t)=null;
9124   post_script(t)=null;
9125   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9126   if ( mp->internal[mp_linecap]>unity ) lcap_val(t)=2;
9127   else if ( mp->internal[mp_linecap]>0 ) lcap_val(t)=1;
9128   else lcap_val(t)=0;
9129   return t;
9130 }
9131
9132 @ When a dashed line is computed in a transformed coordinate system, the dash
9133 lengths get scaled like the pen shape and we need to compensate for this.  Since
9134 there is no unique scale factor for an arbitrary transformation, we use the
9135 the square root of the determinant.  The properties of the determinant make it
9136 easier to maintain the |dash_scale|.  The computation is fairly straight-forward
9137 except for the initialization of the scale factor |s|.  The factor of 64 is
9138 needed because |square_rt| scales its result by $2^8$ while we need $2^{14}$
9139 to counteract the effect of |take_fraction|.
9140
9141 @<Declare subroutines needed by |print_edges|@>=
9142 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) {
9143   scaled maxabs; /* $max(|a|,|b|,|c|,|d|)$ */
9144   integer s; /* amount by which the result of |square_rt| needs to be scaled */
9145   @<Initialize |maxabs|@>;
9146   s=64;
9147   while ( (maxabs<fraction_one) && (s>1) ){ 
9148     a+=a; b+=b; c+=c; d+=d;
9149     maxabs+=maxabs; s=halfp(s);
9150   }
9151   return s*mp_square_rt(mp, abs(mp_take_fraction(mp, a,d)-mp_take_fraction(mp, b,c)));
9152 }
9153 @#
9154 scaled mp_get_pen_scale (MP mp,pointer p) { 
9155   return mp_sqrt_det(mp, 
9156     left_x(p)-x_coord(p), right_x(p)-x_coord(p),
9157     left_y(p)-y_coord(p), right_y(p)-y_coord(p));
9158 }
9159
9160 @ @<Internal library ...@>=
9161 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) ;
9162
9163
9164 @ @<Initialize |maxabs|@>=
9165 maxabs=abs(a);
9166 if ( abs(b)>maxabs ) maxabs=abs(b);
9167 if ( abs(c)>maxabs ) maxabs=abs(c);
9168 if ( abs(d)>maxabs ) maxabs=abs(d)
9169
9170 @ When a picture contains text, this is represented by a fourteen-word node
9171 where the color information and |type| and |link| fields are augmented by
9172 additional fields that describe the text and  how it is transformed.
9173 The |path_p| and |pen_p| pointers are replaced by a number that identifies
9174 the font and a string number that gives the text to be displayed.
9175 The |width|, |height|, and |depth| fields
9176 give the dimensions of the text at its design size, and the remaining six
9177 words give a transformation to be applied to the text.  The |new_text_node|
9178 function initializes everything to default values so that the text comes out
9179 black with its reference point at the origin.
9180
9181 @d text_p(A) link((A)+1)  /* a string pointer for the text to display */
9182 @d font_n(A) info((A)+1)  /* the font number */
9183 @d width_val(A) mp->mem[(A)+7].sc  /* unscaled width of the text */
9184 @d height_val(A) mp->mem[(A)+9].sc  /* unscaled height of the text */
9185 @d depth_val(A) mp->mem[(A)+10].sc  /* unscaled depth of the text */
9186 @d text_tx_loc(A) ((A)+11)
9187   /* the first of six locations for transformation parameters */
9188 @d tx_val(A) mp->mem[(A)+11].sc  /* $x$ shift amount */
9189 @d ty_val(A) mp->mem[(A)+12].sc  /* $y$ shift amount */
9190 @d txx_val(A) mp->mem[(A)+13].sc  /* |txx| transformation parameter */
9191 @d txy_val(A) mp->mem[(A)+14].sc  /* |txy| transformation parameter */
9192 @d tyx_val(A) mp->mem[(A)+15].sc  /* |tyx| transformation parameter */
9193 @d tyy_val(A) mp->mem[(A)+16].sc  /* |tyy| transformation parameter */
9194 @d text_trans_part(A) mp->mem[(A)+11-x_part].sc
9195     /* interpret a text node pointer that has been offset by |x_part..yy_part| */
9196 @d text_node_size 17
9197
9198 @ @<Graphical object codes@>=
9199 mp_text_code=3,
9200
9201 @ @c @<Declare text measuring subroutines@>;
9202 pointer mp_new_text_node (MP mp,char *f,str_number s) {
9203   /* make a text node for font |f| and text string |s| */
9204   pointer t; /* the new node */
9205   t=mp_get_node(mp, text_node_size);
9206   type(t)=mp_text_code;
9207   text_p(t)=s;
9208   font_n(t)=mp_find_font(mp, f); /* this identifies the font */
9209   red_val(t)=0;
9210   green_val(t)=0;
9211   blue_val(t)=0;
9212   black_val(t)=0;
9213   color_model(t)=mp_uninitialized_model;
9214   pre_script(t)=null;
9215   post_script(t)=null;
9216   tx_val(t)=0; ty_val(t)=0;
9217   txx_val(t)=unity; txy_val(t)=0;
9218   tyx_val(t)=0; tyy_val(t)=unity;
9219   mp_set_text_box(mp, t); /* this finds the bounding box */
9220   return t;
9221 }
9222
9223 @ The last two types of graphical objects that can occur in an edge structure
9224 are clipping paths and \&{setbounds} paths.  These are slightly more difficult
9225 @:set_bounds_}{\&{setbounds} primitive@>
9226 to implement because we must keep track of exactly what is being clipped or
9227 bounded when pictures get merged together.  For this reason, each clipping or
9228 \&{setbounds} operation is represented by a pair of nodes:  first comes a
9229 two-word node whose |path_p| gives the relevant path, then there is the list
9230 of objects to clip or bound followed by a two-word node whose second word is
9231 unused.
9232
9233 Using at least two words for each graphical object node allows them all to be
9234 allocated and deallocated similarly with a global array |gr_object_size| to
9235 give the size in words for each object type.
9236
9237 @d start_clip_size 2
9238 @d start_bounds_size 2
9239 @d stop_clip_size 2 /* the second word is not used here */
9240 @d stop_bounds_size 2 /* the second word is not used here */
9241 @#
9242 @d stop_type(A) ((A)+2)
9243   /* matching |type| for |start_clip_code| or |start_bounds_code| */
9244 @d has_color(A) (type((A))<mp_start_clip_code)
9245   /* does a graphical object have color fields? */
9246 @d has_pen(A) (type((A))<mp_text_code)
9247   /* does a graphical object have a |pen_p| field? */
9248 @d is_start_or_stop(A) (type((A))>=mp_start_clip_code)
9249 @d is_stop(A) (type((A))>=mp_stop_clip_code)
9250
9251 @ @<Graphical object codes@>=
9252 mp_start_clip_code=4, /* |type| of a node that starts clipping */
9253 mp_start_bounds_code=5, /* |type| of a node that gives a \&{setbounds} path */
9254 mp_stop_clip_code=6, /* |type| of a node that stops clipping */
9255 mp_stop_bounds_code=7, /* |type| of a node that stops \&{setbounds} */
9256
9257
9258 @ @c 
9259 pointer mp_new_bounds_node (MP mp,pointer p, small_number  c) {
9260   /* make a node of type |c| where |p| is the clipping or \&{setbounds} path */
9261   pointer t; /* the new node */
9262   t=mp_get_node(mp, mp->gr_object_size[c]);
9263   type(t)=c;
9264   path_p(t)=p;
9265   return t;
9266 };
9267
9268 @ We need an array to keep track of the sizes of graphical objects.
9269
9270 @<Glob...@>=
9271 small_number gr_object_size[mp_stop_bounds_code+1];
9272
9273 @ @<Set init...@>=
9274 mp->gr_object_size[mp_fill_code]=fill_node_size;
9275 mp->gr_object_size[mp_stroked_code]=stroked_node_size;
9276 mp->gr_object_size[mp_text_code]=text_node_size;
9277 mp->gr_object_size[mp_start_clip_code]=start_clip_size;
9278 mp->gr_object_size[mp_stop_clip_code]=stop_clip_size;
9279 mp->gr_object_size[mp_start_bounds_code]=start_bounds_size;
9280 mp->gr_object_size[mp_stop_bounds_code]=stop_bounds_size;
9281
9282 @ All the essential information in an edge structure is encoded as a linked list
9283 of graphical objects as we have just seen, but it is helpful to add some
9284 redundant information.  A single edge structure might be used as a dash pattern
9285 many times, and it would be nice to avoid scanning the same structure
9286 repeatedly.  Thus, an edge structure known to be a suitable dash pattern
9287 has a header that gives a list of dashes in a sorted order designed for rapid
9288 translation into \ps.
9289
9290 Each dash is represented by a three-word node containing the initial and final
9291 $x$~coordinates as well as the usual |link| field.  The |link| fields points to
9292 the dash node with the next higher $x$-coordinates and the final link points
9293 to a special location called |null_dash|.  (There should be no overlap between
9294 dashes).  Since the $y$~coordinate of the dash pattern is needed to determine
9295 the period of repetition, this needs to be stored in the edge header along
9296 with a pointer to the list of dash nodes.
9297
9298 @d start_x(A) mp->mem[(A)+1].sc  /* the starting $x$~coordinate in a dash node */
9299 @d stop_x(A) mp->mem[(A)+2].sc  /* the ending $x$~coordinate in a dash node */
9300 @d dash_node_size 3
9301 @d dash_list link
9302   /* in an edge header this points to the first dash node */
9303 @d dash_y(A) mp->mem[(A)+1].sc  /* $y$ value for the dash list in an edge header */
9304
9305 @ It is also convenient for an edge header to contain the bounding
9306 box information needed by the \&{llcorner} and \&{urcorner} operators
9307 so that this does not have to be recomputed unnecessarily.  This is done by
9308 adding fields for the $x$~and $y$ extremes as well as a pointer that indicates
9309 how far the bounding box computation has gotten.  Thus if the user asks for
9310 the bounding box and then adds some more text to the picture before asking
9311 for more bounding box information, the second computation need only look at
9312 the additional text.
9313
9314 When the bounding box has not been computed, the |bblast| pointer points
9315 to a dummy link at the head of the graphical object list while the |minx_val|
9316 and |miny_val| fields contain |el_gordo| and the |maxx_val| and |maxy_val|
9317 fields contain |-el_gordo|.
9318
9319 Since the bounding box of pictures containing objects of type
9320 |mp_start_bounds_code| depends on the value of \&{truecorners}, the bounding box
9321 @:mp_true_corners_}{\&{truecorners} primitive@>
9322 data might not be valid for all values of this parameter.  Hence, the |bbtype|
9323 field is needed to keep track of this.
9324
9325 @d minx_val(A) mp->mem[(A)+2].sc
9326 @d miny_val(A) mp->mem[(A)+3].sc
9327 @d maxx_val(A) mp->mem[(A)+4].sc
9328 @d maxy_val(A) mp->mem[(A)+5].sc
9329 @d bblast(A) link((A)+6)  /* last item considered in bounding box computation */
9330 @d bbtype(A) info((A)+6)  /* tells how bounding box data depends on \&{truecorners} */
9331 @d dummy_loc(A) ((A)+7)  /* where the object list begins in an edge header */
9332 @d no_bounds 0
9333   /* |bbtype| value when bounding box data is valid for all \&{truecorners} values */
9334 @d bounds_set 1
9335   /* |bbtype| value when bounding box data is for \&{truecorners}${}\le 0$ */
9336 @d bounds_unset 2
9337   /* |bbtype| value when bounding box data is for \&{truecorners}${}>0$ */
9338
9339 @c 
9340 void mp_init_bbox (MP mp,pointer h) {
9341   /* Initialize the bounding box information in edge structure |h| */
9342   bblast(h)=dummy_loc(h);
9343   bbtype(h)=no_bounds;
9344   minx_val(h)=el_gordo;
9345   miny_val(h)=el_gordo;
9346   maxx_val(h)=-el_gordo;
9347   maxy_val(h)=-el_gordo;
9348 }
9349
9350 @ The only other entries in an edge header are a reference count in the first
9351 word and a pointer to the tail of the object list in the last word.
9352
9353 @d obj_tail(A) info((A)+7)  /* points to the last entry in the object list */
9354 @d edge_header_size 8
9355
9356 @c 
9357 void mp_init_edges (MP mp,pointer h) {
9358   /* initialize an edge header to null values */
9359   dash_list(h)=null_dash;
9360   obj_tail(h)=dummy_loc(h);
9361   link(dummy_loc(h))=null;
9362   ref_count(h)=null;
9363   mp_init_bbox(mp, h);
9364 }
9365
9366 @ Here is how edge structures are deleted.  The process can be recursive because
9367 of the need to dereference edge structures that are used as dash patterns.
9368 @^recursion@>
9369
9370 @d add_edge_ref(A) incr(ref_count((A)))
9371 @d delete_edge_ref(A) { if ( ref_count((A))==null ) mp_toss_edges(mp, (A));
9372   else decr(ref_count((A))); }
9373
9374 @<Declare the recycling subroutines@>=
9375 void mp_flush_dash_list (MP mp,pointer h);
9376 pointer mp_toss_gr_object (MP mp,pointer p) ;
9377 void mp_toss_edges (MP mp,pointer h) ;
9378
9379 @ @c void mp_toss_edges (MP mp,pointer h) {
9380   pointer p,q;  /* pointers that scan the list being recycled */
9381   pointer r; /* an edge structure that object |p| refers to */
9382   mp_flush_dash_list(mp, h);
9383   q=link(dummy_loc(h));
9384   while ( (q!=null) ) { 
9385     p=q; q=link(q);
9386     r=mp_toss_gr_object(mp, p);
9387     if ( r!=null ) delete_edge_ref(r);
9388   }
9389   mp_free_node(mp, h,edge_header_size);
9390 }
9391 void mp_flush_dash_list (MP mp,pointer h) {
9392   pointer p,q;  /* pointers that scan the list being recycled */
9393   q=dash_list(h);
9394   while ( q!=null_dash ) { 
9395     p=q; q=link(q);
9396     mp_free_node(mp, p,dash_node_size);
9397   }
9398   dash_list(h)=null_dash;
9399 }
9400 pointer mp_toss_gr_object (MP mp,pointer p) {
9401   /* returns an edge structure that needs to be dereferenced */
9402   pointer e; /* the edge structure to return */
9403   e=null;
9404   @<Prepare to recycle graphical object |p|@>;
9405   mp_free_node(mp, p,mp->gr_object_size[type(p)]);
9406   return e;
9407 }
9408
9409 @ @<Prepare to recycle graphical object |p|@>=
9410 switch (type(p)) {
9411 case mp_fill_code: 
9412   mp_toss_knot_list(mp, path_p(p));
9413   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9414   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9415   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9416   break;
9417 case mp_stroked_code: 
9418   mp_toss_knot_list(mp, path_p(p));
9419   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9420   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9421   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9422   e=dash_p(p);
9423   break;
9424 case mp_text_code: 
9425   delete_str_ref(text_p(p));
9426   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9427   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9428   break;
9429 case mp_start_clip_code:
9430 case mp_start_bounds_code: 
9431   mp_toss_knot_list(mp, path_p(p));
9432   break;
9433 case mp_stop_clip_code:
9434 case mp_stop_bounds_code: 
9435   break;
9436 } /* there are no other cases */
9437
9438 @ If we use |add_edge_ref| to ``copy'' edge structures, the real copying needs
9439 to be done before making a significant change to an edge structure.  Much of
9440 the work is done in a separate routine |copy_objects| that copies a list of
9441 graphical objects into a new edge header.
9442
9443 @c @<Declare a function called |copy_objects|@>;
9444 pointer mp_private_edges (MP mp,pointer h) {
9445   /* make a private copy of the edge structure headed by |h| */
9446   pointer hh;  /* the edge header for the new copy */
9447   pointer p,pp;  /* pointers for copying the dash list */
9448   if ( ref_count(h)==null ) {
9449     return h;
9450   } else { 
9451     decr(ref_count(h));
9452     hh=mp_copy_objects(mp, link(dummy_loc(h)),null);
9453     @<Copy the dash list from |h| to |hh|@>;
9454     @<Copy the bounding box information from |h| to |hh| and make |bblast(hh)|
9455       point into the new object list@>;
9456     return hh;
9457   }
9458 }
9459
9460 @ Here we use the fact that |dash_list(hh)=link(hh)|.
9461 @^data structure assumptions@>
9462
9463 @<Copy the dash list from |h| to |hh|@>=
9464 pp=hh; p=dash_list(h);
9465 while ( (p!=null_dash) ) { 
9466   link(pp)=mp_get_node(mp, dash_node_size);
9467   pp=link(pp);
9468   start_x(pp)=start_x(p);
9469   stop_x(pp)=stop_x(p);
9470   p=link(p);
9471 }
9472 link(pp)=null_dash;
9473 dash_y(hh)=dash_y(h)
9474
9475 @ @<Copy the bounding box information from |h| to |hh|...@>=
9476 minx_val(hh)=minx_val(h);
9477 miny_val(hh)=miny_val(h);
9478 maxx_val(hh)=maxx_val(h);
9479 maxy_val(hh)=maxy_val(h);
9480 bbtype(hh)=bbtype(h);
9481 p=dummy_loc(h); pp=dummy_loc(hh);
9482 while ((p!=bblast(h)) ) { 
9483   if ( p==null ) mp_confusion(mp, "bblast");
9484 @:this can't happen bblast}{\quad bblast@>
9485   p=link(p); pp=link(pp);
9486 }
9487 bblast(hh)=pp
9488
9489 @ Here is the promised routine for copying graphical objects into a new edge
9490 structure.  It starts copying at object~|p| and stops just before object~|q|.
9491 If |q| is null, it copies the entire sublist headed at |p|.  The resulting edge
9492 structure requires further initialization by |init_bbox|.
9493
9494 @<Declare a function called |copy_objects|@>=
9495 pointer mp_copy_objects (MP mp, pointer p, pointer q) {
9496   pointer hh;  /* the new edge header */
9497   pointer pp;  /* the last newly copied object */
9498   small_number k;  /* temporary register */
9499   hh=mp_get_node(mp, edge_header_size);
9500   dash_list(hh)=null_dash;
9501   ref_count(hh)=null;
9502   pp=dummy_loc(hh);
9503   while ( (p!=q) ) {
9504     @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>;
9505   }
9506   obj_tail(hh)=pp;
9507   link(pp)=null;
9508   return hh;
9509 }
9510
9511 @ @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>=
9512 { k=mp->gr_object_size[type(p)];
9513   link(pp)=mp_get_node(mp, k);
9514   pp=link(pp);
9515   while ( (k>0) ) { decr(k); mp->mem[pp+k]=mp->mem[p+k];  };
9516   @<Fix anything in graphical object |pp| that should differ from the
9517     corresponding field in |p|@>;
9518   p=link(p);
9519 }
9520
9521 @ @<Fix anything in graphical object |pp| that should differ from the...@>=
9522 switch (type(p)) {
9523 case mp_start_clip_code:
9524 case mp_start_bounds_code: 
9525   path_p(pp)=mp_copy_path(mp, path_p(p));
9526   break;
9527 case mp_fill_code: 
9528   path_p(pp)=mp_copy_path(mp, path_p(p));
9529   if ( pen_p(p)!=null ) pen_p(pp)=copy_pen(pen_p(p));
9530   break;
9531 case mp_stroked_code: 
9532   path_p(pp)=mp_copy_path(mp, path_p(p));
9533   pen_p(pp)=copy_pen(pen_p(p));
9534   if ( dash_p(p)!=null ) add_edge_ref(dash_p(pp));
9535   break;
9536 case mp_text_code: 
9537   add_str_ref(text_p(pp));
9538   break;
9539 case mp_stop_clip_code:
9540 case mp_stop_bounds_code: 
9541   break;
9542 }  /* there are no other cases */
9543
9544 @ Here is one way to find an acceptable value for the second argument to
9545 |copy_objects|.  Given a non-null graphical object list, |skip_1component|
9546 skips past one picture component, where a ``picture component'' is a single
9547 graphical object, or a start bounds or start clip object and everything up
9548 through the matching stop bounds or stop clip object.  The macro version avoids
9549 procedure call overhead and error handling: |skip_component(p)(e)| advances |p|
9550 unless |p| points to a stop bounds or stop clip node, in which case it executes
9551 |e| instead.
9552
9553 @d skip_component(A)
9554     if ( ! is_start_or_stop((A)) ) (A)=link((A));
9555     else if ( ! is_stop((A)) ) (A)=mp_skip_1component(mp, (A));
9556     else 
9557
9558 @c 
9559 pointer mp_skip_1component (MP mp,pointer p) {
9560   integer lev; /* current nesting level */
9561   lev=0;
9562   do {  
9563    if ( is_start_or_stop(p) ) {
9564      if ( is_stop(p) ) decr(lev);  else incr(lev);
9565    }
9566    p=link(p);
9567   } while (lev!=0);
9568   return p;
9569 }
9570
9571 @ Here is a diagnostic routine for printing an edge structure in symbolic form.
9572
9573 @<Declare subroutines for printing expressions@>=
9574 @<Declare subroutines needed by |print_edges|@>;
9575 void mp_print_edges (MP mp,pointer h, char *s, boolean nuline) {
9576   pointer p;  /* a graphical object to be printed */
9577   pointer hh,pp;  /* temporary pointers */
9578   scaled scf;  /* a scale factor for the dash pattern */
9579   boolean ok_to_dash;  /* |false| for polygonal pen strokes */
9580   mp_print_diagnostic(mp, "Edge structure",s,nuline);
9581   p=dummy_loc(h);
9582   while ( link(p)!=null ) { 
9583     p=link(p);
9584     mp_print_ln(mp);
9585     switch (type(p)) {
9586       @<Cases for printing graphical object node |p|@>;
9587     default: 
9588           mp_print(mp, "[unknown object type!]");
9589           break;
9590     }
9591   }
9592   mp_print_nl(mp, "End edges");
9593   if ( p!=obj_tail(h) ) mp_print(mp, "?");
9594 @.End edges?@>
9595   mp_end_diagnostic(mp, true);
9596 }
9597
9598 @ @<Cases for printing graphical object node |p|@>=
9599 case mp_fill_code: 
9600   mp_print(mp, "Filled contour ");
9601   mp_print_obj_color(mp, p);
9602   mp_print_char(mp, ':'); mp_print_ln(mp);
9603   mp_pr_path(mp, path_p(p)); mp_print_ln(mp);
9604   if ( (pen_p(p)!=null) ) {
9605     @<Print join type for graphical object |p|@>;
9606     mp_print(mp, " with pen"); mp_print_ln(mp);
9607     mp_pr_pen(mp, pen_p(p));
9608   }
9609   break;
9610
9611 @ @<Print join type for graphical object |p|@>=
9612 switch (ljoin_val(p)) {
9613 case 0:
9614   mp_print(mp, "mitered joins limited ");
9615   mp_print_scaled(mp, miterlim_val(p));
9616   break;
9617 case 1:
9618   mp_print(mp, "round joins");
9619   break;
9620 case 2:
9621   mp_print(mp, "beveled joins");
9622   break;
9623 default: 
9624   mp_print(mp, "?? joins");
9625 @.??@>
9626   break;
9627 }
9628
9629 @ For stroked nodes, we need to print |lcap_val(p)| as well.
9630
9631 @<Print join and cap types for stroked node |p|@>=
9632 switch (lcap_val(p)) {
9633 case 0:mp_print(mp, "butt"); break;
9634 case 1:mp_print(mp, "round"); break;
9635 case 2:mp_print(mp, "square"); break;
9636 default: mp_print(mp, "??"); break;
9637 @.??@>
9638 }
9639 mp_print(mp, " ends, ");
9640 @<Print join type for graphical object |p|@>
9641
9642 @ Here is a routine that prints the color of a graphical object if it isn't
9643 black (the default color).
9644
9645 @<Declare subroutines needed by |print_edges|@>=
9646 @<Declare a procedure called |print_compact_node|@>;
9647 void mp_print_obj_color (MP mp,pointer p) { 
9648   if ( color_model(p)==mp_grey_model ) {
9649     if ( grey_val(p)>0 ) { 
9650       mp_print(mp, "greyed ");
9651       mp_print_compact_node(mp, obj_grey_loc(p),1);
9652     };
9653   } else if ( color_model(p)==mp_cmyk_model ) {
9654     if ( (cyan_val(p)>0) || (magenta_val(p)>0) || 
9655          (yellow_val(p)>0) || (black_val(p)>0) ) { 
9656       mp_print(mp, "processcolored ");
9657       mp_print_compact_node(mp, obj_cyan_loc(p),4);
9658     };
9659   } else if ( color_model(p)==mp_rgb_model ) {
9660     if ( (red_val(p)>0) || (green_val(p)>0) || (blue_val(p)>0) ) { 
9661       mp_print(mp, "colored "); 
9662       mp_print_compact_node(mp, obj_red_loc(p),3);
9663     };
9664   }
9665 }
9666
9667 @ We also need a procedure for printing consecutive scaled values as if they
9668 were a known big node.
9669
9670 @<Declare a procedure called |print_compact_node|@>=
9671 void mp_print_compact_node (MP mp,pointer p, small_number k) {
9672   pointer q;  /* last location to print */
9673   q=p+k-1;
9674   mp_print_char(mp, '(');
9675   while ( p<=q ){ 
9676     mp_print_scaled(mp, mp->mem[p].sc);
9677     if ( p<q ) mp_print_char(mp, ',');
9678     incr(p);
9679   }
9680   mp_print_char(mp, ')');
9681 }
9682
9683 @ @<Cases for printing graphical object node |p|@>=
9684 case mp_stroked_code: 
9685   mp_print(mp, "Filled pen stroke ");
9686   mp_print_obj_color(mp, p);
9687   mp_print_char(mp, ':'); mp_print_ln(mp);
9688   mp_pr_path(mp, path_p(p));
9689   if ( dash_p(p)!=null ) { 
9690     mp_print_nl(mp, "dashed (");
9691     @<Finish printing the dash pattern that |p| refers to@>;
9692   }
9693   mp_print_ln(mp);
9694   @<Print join and cap types for stroked node |p|@>;
9695   mp_print(mp, " with pen"); mp_print_ln(mp);
9696   if ( pen_p(p)==null ) mp_print(mp, "???"); /* shouldn't happen */
9697 @.???@>
9698   else mp_pr_pen(mp, pen_p(p));
9699   break;
9700
9701 @ Normally, the  |dash_list| field in an edge header is set to |null_dash|
9702 when it is not known to define a suitable dash pattern.  This is disallowed
9703 here because the |dash_p| field should never point to such an edge header.
9704 Note that memory is allocated for |start_x(null_dash)| and we are free to
9705 give it any convenient value.
9706
9707 @<Finish printing the dash pattern that |p| refers to@>=
9708 ok_to_dash=pen_is_elliptical(pen_p(p));
9709 if ( ! ok_to_dash ) scf=unity; else scf=dash_scale(p);
9710 hh=dash_p(p);
9711 pp=dash_list(hh);
9712 if ( (pp==null_dash) || (dash_y(hh)<0) ) {
9713   mp_print(mp, " ??");
9714 } else { start_x(null_dash)=start_x(pp)+dash_y(hh);
9715   while ( pp!=null_dash ) { 
9716     mp_print(mp, "on ");
9717     mp_print_scaled(mp, mp_take_scaled(mp, stop_x(pp)-start_x(pp),scf));
9718     mp_print(mp, " off ");
9719     mp_print_scaled(mp, mp_take_scaled(mp, start_x(link(pp))-stop_x(pp),scf));
9720     pp = link(pp);
9721     if ( pp!=null_dash ) mp_print_char(mp, ' ');
9722   }
9723   mp_print(mp, ") shifted ");
9724   mp_print_scaled(mp, -mp_take_scaled(mp, mp_dash_offset(mp, hh),scf));
9725   if ( ! ok_to_dash || (dash_y(hh)==0) ) mp_print(mp, " (this will be ignored)");
9726 }
9727
9728 @ @<Declare subroutines needed by |print_edges|@>=
9729 scaled mp_dash_offset (MP mp,pointer h) {
9730   scaled x;  /* the answer */
9731   if ( (dash_list(h)==null_dash) || (dash_y(h)<0) ) mp_confusion(mp, "dash0");
9732 @:this can't happen dash0}{\quad dash0@>
9733   if ( dash_y(h)==0 ) {
9734     x=0; 
9735   } else { 
9736     x=-(start_x(dash_list(h)) % dash_y(h));
9737     if ( x<0 ) x=x+dash_y(h);
9738   }
9739   return x;
9740 }
9741
9742 @ @<Cases for printing graphical object node |p|@>=
9743 case mp_text_code: 
9744   mp_print_char(mp, '"'); mp_print_str(mp,text_p(p));
9745   mp_print(mp, "\" infont \""); mp_print(mp, mp->font_name[font_n(p)]);
9746   mp_print_char(mp, '"'); mp_print_ln(mp);
9747   mp_print_obj_color(mp, p);
9748   mp_print(mp, "transformed ");
9749   mp_print_compact_node(mp, text_tx_loc(p),6);
9750   break;
9751
9752 @ @<Cases for printing graphical object node |p|@>=
9753 case mp_start_clip_code: 
9754   mp_print(mp, "clipping path:");
9755   mp_print_ln(mp);
9756   mp_pr_path(mp, path_p(p));
9757   break;
9758 case mp_stop_clip_code: 
9759   mp_print(mp, "stop clipping");
9760   break;
9761
9762 @ @<Cases for printing graphical object node |p|@>=
9763 case mp_start_bounds_code: 
9764   mp_print(mp, "setbounds path:");
9765   mp_print_ln(mp);
9766   mp_pr_path(mp, path_p(p));
9767   break;
9768 case mp_stop_bounds_code: 
9769   mp_print(mp, "end of setbounds");
9770   break;
9771
9772 @ To initialize the |dash_list| field in an edge header~|h|, we need a
9773 subroutine that scans an edge structure and tries to interpret it as a dash
9774 pattern.  This can only be done when there are no filled regions or clipping
9775 paths and all the pen strokes have the same color.  The first step is to let
9776 $y_0$ be the initial $y$~coordinate of the first pen stroke.  Then we implicitly
9777 project all the pen stroke paths onto the line $y=y_0$ and require that there
9778 be no retracing.  If the resulting paths cover a range of $x$~coordinates of
9779 length $\Delta x$, we set |dash_y(h)| to the length of the dash pattern by
9780 finding the maximum of $\Delta x$ and the absolute value of~$y_0$.
9781
9782 @c @<Declare a procedure called |x_retrace_error|@>;
9783 pointer mp_make_dashes (MP mp,pointer h) { /* returns |h| or |null| */
9784   pointer p;  /* this scans the stroked nodes in the object list */
9785   pointer p0;  /* if not |null| this points to the first stroked node */
9786   pointer pp,qq,rr;  /* pointers into |path_p(p)| */
9787   pointer d,dd;  /* pointers used to create the dash list */
9788   @<Other local variables in |make_dashes|@>;
9789   scaled y0=0;  /* the initial $y$ coordinate */
9790   if ( dash_list(h)!=null_dash ) 
9791         return h;
9792   p0=null;
9793   p=link(dummy_loc(h));
9794   while ( p!=null ) { 
9795     if ( type(p)!=mp_stroked_code ) {
9796       @<Compain that the edge structure contains a node of the wrong type
9797         and |goto not_found|@>;
9798     }
9799     pp=path_p(p);
9800     if ( p0==null ){ p0=p; y0=y_coord(pp);  };
9801     @<Make |d| point to a new dash node created from stroke |p| and path |pp|
9802       or |goto not_found| if there is an error@>;
9803     @<Insert |d| into the dash list and |goto not_found| if there is an error@>;
9804     p=link(p);
9805   }
9806   if ( dash_list(h)==null_dash ) 
9807     goto NOT_FOUND; /* No error message */
9808   @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>;
9809   @<Set |dash_y(h)| and merge the first and last dashes if necessary@>;
9810   return h;
9811 NOT_FOUND: 
9812   @<Flush the dash list, recycle |h| and return |null|@>;
9813 };
9814
9815 @ @<Compain that the edge structure contains a node of the wrong type...@>=
9816
9817 print_err("Picture is too complicated to use as a dash pattern");
9818 help3("When you say `dashed p', picture p should not contain any")
9819   ("text, filled regions, or clipping paths.  This time it did")
9820   ("so I'll just make it a solid line instead.");
9821 mp_put_get_error(mp);
9822 goto NOT_FOUND;
9823 }
9824
9825 @ A similar error occurs when monotonicity fails.
9826
9827 @<Declare a procedure called |x_retrace_error|@>=
9828 void mp_x_retrace_error (MP mp) { 
9829 print_err("Picture is too complicated to use as a dash pattern");
9830 help3("When you say `dashed p', every path in p should be monotone")
9831   ("in x and there must be no overlapping.  This failed")
9832   ("so I'll just make it a solid line instead.");
9833 mp_put_get_error(mp);
9834 }
9835
9836 @ We stash |p| in |info(d)| if |dash_p(p)<>0| so that subsequent processing can
9837 handle the case where the pen stroke |p| is itself dashed.
9838
9839 @<Make |d| point to a new dash node created from stroke |p| and path...@>=
9840 @<Make sure |p| and |p0| are the same color and |goto not_found| if there is
9841   an error@>;
9842 rr=pp;
9843 if ( link(pp)!=pp ) {
9844   do {  
9845     qq=rr; rr=link(rr);
9846     @<Check for retracing between knots |qq| and |rr| and |goto not_found|
9847       if there is a problem@>;
9848   } while (right_type(rr)!=mp_endpoint);
9849 }
9850 d=mp_get_node(mp, dash_node_size);
9851 if ( dash_p(p)==0 ) info(d)=0;  else info(d)=p;
9852 if ( x_coord(pp)<x_coord(rr) ) { 
9853   start_x(d)=x_coord(pp);
9854   stop_x(d)=x_coord(rr);
9855 } else { 
9856   start_x(d)=x_coord(rr);
9857   stop_x(d)=x_coord(pp);
9858 }
9859
9860 @ We also need to check for the case where the segment from |qq| to |rr| is
9861 monotone in $x$ but is reversed relative to the path from |pp| to |qq|.
9862
9863 @<Check for retracing between knots |qq| and |rr| and |goto not_found|...@>=
9864 x0=x_coord(qq);
9865 x1=right_x(qq);
9866 x2=left_x(rr);
9867 x3=x_coord(rr);
9868 if ( (x0>x1) || (x1>x2) || (x2>x3) ) {
9869   if ( (x0<x1) || (x1<x2) || (x2<x3) ) {
9870     if ( mp_ab_vs_cd(mp, x2-x1,x2-x1,x1-x0,x3-x2)>0 ) {
9871       mp_x_retrace_error(mp); goto NOT_FOUND;
9872     }
9873   }
9874 }
9875 if ( (x_coord(pp)>x0) || (x0>x3) ) {
9876   if ( (x_coord(pp)<x0) || (x0<x3) ) {
9877     mp_x_retrace_error(mp); goto NOT_FOUND;
9878   }
9879 }
9880
9881 @ @<Other local variables in |make_dashes|@>=
9882   scaled x0,x1,x2,x3;  /* $x$ coordinates of the segment from |qq| to |rr| */
9883
9884 @ @<Make sure |p| and |p0| are the same color and |goto not_found|...@>=
9885 if ( (red_val(p)!=red_val(p0)) || (black_val(p)!=black_val(p0)) ||
9886   (green_val(p)!=green_val(p0)) || (blue_val(p)!=blue_val(p0)) ) {
9887   print_err("Picture is too complicated to use as a dash pattern");
9888   help3("When you say `dashed p', everything in picture p should")
9889     ("be the same color.  I can\'t handle your color changes")
9890     ("so I'll just make it a solid line instead.");
9891   mp_put_get_error(mp);
9892   goto NOT_FOUND;
9893 }
9894
9895 @ @<Insert |d| into the dash list and |goto not_found| if there is an error@>=
9896 start_x(null_dash)=stop_x(d);
9897 dd=h; /* this makes |link(dd)=dash_list(h)| */
9898 while ( start_x(link(dd))<stop_x(d) )
9899   dd=link(dd);
9900 if ( dd!=h ) {
9901   if ( (stop_x(dd)>start_x(d)) )
9902     { mp_x_retrace_error(mp); goto NOT_FOUND;  };
9903 }
9904 link(d)=link(dd);
9905 link(dd)=d
9906
9907 @ @<Set |dash_y(h)| and merge the first and last dashes if necessary@>=
9908 d=dash_list(h);
9909 while ( (link(d)!=null_dash) )
9910   d=link(d);
9911 dd=dash_list(h);
9912 dash_y(h)=stop_x(d)-start_x(dd);
9913 if ( abs(y0)>dash_y(h) ) {
9914   dash_y(h)=abs(y0);
9915 } else if ( d!=dd ) { 
9916   dash_list(h)=link(dd);
9917   stop_x(d)=stop_x(dd)+dash_y(h);
9918   mp_free_node(mp, dd,dash_node_size);
9919 }
9920
9921 @ We get here when the argument is a null picture or when there is an error.
9922 Recovering from an error involves making |dash_list(h)| empty to indicate
9923 that |h| is not known to be a valid dash pattern.  We also dereference |h|
9924 since it is not being used for the return value.
9925
9926 @<Flush the dash list, recycle |h| and return |null|@>=
9927 mp_flush_dash_list(mp, h);
9928 delete_edge_ref(h);
9929 return null
9930
9931 @ Having carefully saved the dashed stroked nodes in the
9932 corresponding dash nodes, we must be prepared to break up these dashes into
9933 smaller dashes.
9934
9935 @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>=
9936 d=h;  /* now |link(d)=dash_list(h)| */
9937 while ( link(d)!=null_dash ) {
9938   ds=info(link(d));
9939   if ( ds==null ) { 
9940     d=link(d);
9941   } else {
9942     hh=dash_p(ds);
9943     hsf=dash_scale(ds);
9944     if ( (hh==null) ) mp_confusion(mp, "dash1");
9945 @:this can't happen dash0}{\quad dash1@>
9946     if ( dash_y(hh)==0 ) {
9947       d=link(d);
9948     } else { 
9949       if ( dash_list(hh)==null ) mp_confusion(mp, "dash1");
9950 @:this can't happen dash0}{\quad dash1@>
9951       @<Replace |link(d)| by a dashed version as determined by edge header
9952           |hh| and scale factor |ds|@>;
9953     }
9954   }
9955 }
9956
9957 @ @<Other local variables in |make_dashes|@>=
9958 pointer dln;  /* |link(d)| */
9959 pointer hh;  /* an edge header that tells how to break up |dln| */
9960 scaled hsf;  /* the dash pattern from |hh| gets scaled by this */
9961 pointer ds;  /* the stroked node from which |hh| and |hsf| are derived */
9962 scaled xoff;  /* added to $x$ values in |dash_list(hh)| to match |dln| */
9963
9964 @ @<Replace |link(d)| by a dashed version as determined by edge header...@>=
9965 dln=link(d);
9966 dd=dash_list(hh);
9967 xoff=start_x(dln)-mp_take_scaled(mp, hsf,start_x(dd))-
9968         mp_take_scaled(mp, hsf,mp_dash_offset(mp, hh));
9969 start_x(null_dash)=mp_take_scaled(mp, hsf,start_x(dd))
9970                    +mp_take_scaled(mp, hsf,dash_y(hh));
9971 stop_x(null_dash)=start_x(null_dash);
9972 @<Advance |dd| until finding the first dash that overlaps |dln| when
9973   offset by |xoff|@>;
9974 while ( start_x(dln)<=stop_x(dln) ) {
9975   @<If |dd| has `fallen off the end', back up to the beginning and fix |xoff|@>;
9976   @<Insert a dash between |d| and |dln| for the overlap with the offset version
9977     of |dd|@>;
9978   dd=link(dd);
9979   start_x(dln)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
9980 }
9981 link(d)=link(dln);
9982 mp_free_node(mp, dln,dash_node_size)
9983
9984 @ The name of this module is a bit of a lie because we actually just find the
9985 first |dd| where |take_scaled (hsf, stop_x(dd))| is large enough to make an
9986 overlap possible.  It could be that the unoffset version of dash |dln| falls
9987 in the gap between |dd| and its predecessor.
9988
9989 @<Advance |dd| until finding the first dash that overlaps |dln| when...@>=
9990 while ( xoff+mp_take_scaled(mp, hsf,stop_x(dd))<start_x(dln) ) {
9991   dd=link(dd);
9992 }
9993
9994 @ @<If |dd| has `fallen off the end', back up to the beginning and fix...@>=
9995 if ( dd==null_dash ) { 
9996   dd=dash_list(hh);
9997   xoff=xoff+mp_take_scaled(mp, hsf,dash_y(hh));
9998 }
9999
10000 @ At this point we already know that
10001 |start_x(dln)<=xoff+take_scaled(hsf,stop_x(dd))|.
10002
10003 @<Insert a dash between |d| and |dln| for the overlap with the offset...@>=
10004 if ( xoff+mp_take_scaled(mp, hsf,start_x(dd))<=stop_x(dln) ) {
10005   link(d)=mp_get_node(mp, dash_node_size);
10006   d=link(d);
10007   link(d)=dln;
10008   if ( start_x(dln)>xoff+mp_take_scaled(mp, hsf,start_x(dd)))
10009     start_x(d)=start_x(dln);
10010   else 
10011     start_x(d)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10012   if ( stop_x(dln)<xoff+mp_take_scaled(mp, hsf,stop_x(dd)) ) 
10013     stop_x(d)=stop_x(dln);
10014   else 
10015     stop_x(d)=xoff+mp_take_scaled(mp, hsf,stop_x(dd));
10016 }
10017
10018 @ The next major task is to update the bounding box information in an edge
10019 header~|h|. This is done via a procedure |adjust_bbox| that enlarges an edge
10020 header's bounding box to accommodate the box computed by |path_bbox| or
10021 |pen_bbox|. (This is stored in global variables |minx|, |miny|, |maxx|, and
10022 |maxy|.)
10023
10024 @c void mp_adjust_bbox (MP mp,pointer h) { 
10025   if ( minx<minx_val(h) ) minx_val(h)=minx;
10026   if ( miny<miny_val(h) ) miny_val(h)=miny;
10027   if ( maxx>maxx_val(h) ) maxx_val(h)=maxx;
10028   if ( maxy>maxy_val(h) ) maxy_val(h)=maxy;
10029 }
10030
10031 @ Here is a special routine for updating the bounding box information in
10032 edge header~|h| to account for the squared-off ends of a non-cyclic path~|p|
10033 that is to be stroked with the pen~|pp|.
10034
10035 @c void mp_box_ends (MP mp, pointer p, pointer pp, pointer h) {
10036   pointer q;  /* a knot node adjacent to knot |p| */
10037   fraction dx,dy;  /* a unit vector in the direction out of the path at~|p| */
10038   scaled d;  /* a factor for adjusting the length of |(dx,dy)| */
10039   scaled z;  /* a coordinate being tested against the bounding box */
10040   scaled xx,yy;  /* the extreme pen vertex in the |(dx,dy)| direction */
10041   integer i; /* a loop counter */
10042   if ( right_type(p)!=mp_endpoint ) { 
10043     q=link(p);
10044     while (1) { 
10045       @<Make |(dx,dy)| the final direction for the path segment from
10046         |q| to~|p|; set~|d|@>;
10047       d=mp_pyth_add(mp, dx,dy);
10048       if ( d>0 ) { 
10049          @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>;
10050          for (i=1;i<= 2;i++) { 
10051            @<Use |(dx,dy)| to generate a vertex of the square end cap and
10052              update the bounding box to accommodate it@>;
10053            dx=-dx; dy=-dy; 
10054         }
10055       }
10056       if ( right_type(p)==mp_endpoint ) {
10057          return;
10058       } else {
10059         @<Advance |p| to the end of the path and make |q| the previous knot@>;
10060       } 
10061     }
10062   }
10063 }
10064
10065 @ @<Make |(dx,dy)| the final direction for the path segment from...@>=
10066 if ( q==link(p) ) { 
10067   dx=x_coord(p)-right_x(p);
10068   dy=y_coord(p)-right_y(p);
10069   if ( (dx==0)&&(dy==0) ) {
10070     dx=x_coord(p)-left_x(q);
10071     dy=y_coord(p)-left_y(q);
10072   }
10073 } else { 
10074   dx=x_coord(p)-left_x(p);
10075   dy=y_coord(p)-left_y(p);
10076   if ( (dx==0)&&(dy==0) ) {
10077     dx=x_coord(p)-right_x(q);
10078     dy=y_coord(p)-right_y(q);
10079   }
10080 }
10081 dx=x_coord(p)-x_coord(q);
10082 dy=y_coord(p)-y_coord(q)
10083
10084 @ @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>=
10085 dx=mp_make_fraction(mp, dx,d);
10086 dy=mp_make_fraction(mp, dy,d);
10087 mp_find_offset(mp, -dy,dx,pp);
10088 xx=mp->cur_x; yy=mp->cur_y
10089
10090 @ @<Use |(dx,dy)| to generate a vertex of the square end cap and...@>=
10091 mp_find_offset(mp, dx,dy,pp);
10092 d=mp_take_fraction(mp, xx-mp->cur_x,dx)+mp_take_fraction(mp, yy-mp->cur_y,dy);
10093 if ( ((d<0)&&(i==1)) || ((d>0)&&(i==2))) 
10094   mp_confusion(mp, "box_ends");
10095 @:this can't happen box ends}{\quad\\{box\_ends}@>
10096 z=x_coord(p)+mp->cur_x+mp_take_fraction(mp, d,dx);
10097 if ( z<minx_val(h) ) minx_val(h)=z;
10098 if ( z>maxx_val(h) ) maxx_val(h)=z;
10099 z=y_coord(p)+mp->cur_y+mp_take_fraction(mp, d,dy);
10100 if ( z<miny_val(h) ) miny_val(h)=z;
10101 if ( z>maxy_val(h) ) maxy_val(h)=z
10102
10103 @ @<Advance |p| to the end of the path and make |q| the previous knot@>=
10104 do {  
10105   q=p;
10106   p=link(p);
10107 } while (right_type(p)!=mp_endpoint)
10108
10109 @ The major difficulty in finding the bounding box of an edge structure is the
10110 effect of clipping paths.  We treat them conservatively by only clipping to the
10111 clipping path's bounding box, but this still
10112 requires recursive calls to |set_bbox| in order to find the bounding box of
10113 @^recursion@>
10114 the objects to be clipped.  Such calls are distinguished by the fact that the
10115 boolean parameter |top_level| is false.
10116
10117 @c void mp_set_bbox (MP mp,pointer h, boolean top_level) {
10118   pointer p;  /* a graphical object being considered */
10119   scaled sminx,sminy,smaxx,smaxy;
10120   /* for saving the bounding box during recursive calls */
10121   scaled x0,x1,y0,y1;  /* temporary registers */
10122   integer lev;  /* nesting level for |mp_start_bounds_code| nodes */
10123   @<Wipe out any existing bounding box information if |bbtype(h)| is
10124   incompatible with |internal[mp_true_corners]|@>;
10125   while ( link(bblast(h))!=null ) { 
10126     p=link(bblast(h));
10127     bblast(h)=p;
10128     switch (type(p)) {
10129     case mp_stop_clip_code: 
10130       if ( top_level ) mp_confusion(mp, "bbox");  else return;
10131 @:this can't happen bbox}{\quad bbox@>
10132       break;
10133     @<Other cases for updating the bounding box based on the type of object |p|@>;
10134     } /* all cases are enumerated above */
10135   }
10136   if ( ! top_level ) mp_confusion(mp, "bbox");
10137 }
10138
10139 @ @<Internal library declarations@>=
10140 void mp_set_bbox (MP mp,pointer h, boolean top_level);
10141
10142 @ @<Wipe out any existing bounding box information if |bbtype(h)| is...@>=
10143 switch (bbtype(h)) {
10144 case no_bounds: 
10145   break;
10146 case bounds_set: 
10147   if ( mp->internal[mp_true_corners]>0 ) mp_init_bbox(mp, h);
10148   break;
10149 case bounds_unset: 
10150   if ( mp->internal[mp_true_corners]<=0 ) mp_init_bbox(mp, h);
10151   break;
10152 } /* there are no other cases */
10153
10154 @ @<Other cases for updating the bounding box...@>=
10155 case mp_fill_code: 
10156   mp_path_bbox(mp, path_p(p));
10157   if ( pen_p(p)!=null ) { 
10158     x0=minx; y0=miny;
10159     x1=maxx; y1=maxy;
10160     mp_pen_bbox(mp, pen_p(p));
10161     minx=minx+x0;
10162     miny=miny+y0;
10163     maxx=maxx+x1;
10164     maxy=maxy+y1;
10165   }
10166   mp_adjust_bbox(mp, h);
10167   break;
10168
10169 @ @<Other cases for updating the bounding box...@>=
10170 case mp_start_bounds_code: 
10171   if ( mp->internal[mp_true_corners]>0 ) {
10172     bbtype(h)=bounds_unset;
10173   } else { 
10174     bbtype(h)=bounds_set;
10175     mp_path_bbox(mp, path_p(p));
10176     mp_adjust_bbox(mp, h);
10177     @<Scan to the matching |mp_stop_bounds_code| node and update |p| and
10178       |bblast(h)|@>;
10179   }
10180   break;
10181 case mp_stop_bounds_code: 
10182   if ( mp->internal[mp_true_corners]<=0 ) mp_confusion(mp, "bbox2");
10183 @:this can't happen bbox2}{\quad bbox2@>
10184   break;
10185
10186 @ @<Scan to the matching |mp_stop_bounds_code| node and update |p| and...@>=
10187 lev=1;
10188 while ( lev!=0 ) { 
10189   if ( link(p)==null ) mp_confusion(mp, "bbox2");
10190 @:this can't happen bbox2}{\quad bbox2@>
10191   p=link(p);
10192   if ( type(p)==mp_start_bounds_code ) incr(lev);
10193   else if ( type(p)==mp_stop_bounds_code ) decr(lev);
10194 }
10195 bblast(h)=p
10196
10197 @ It saves a lot of grief here to be slightly conservative and not account for
10198 omitted parts of dashed lines.  We also don't worry about the material omitted
10199 when using butt end caps.  The basic computation is for round end caps and
10200 |box_ends| augments it for square end caps.
10201
10202 @<Other cases for updating the bounding box...@>=
10203 case mp_stroked_code: 
10204   mp_path_bbox(mp, path_p(p));
10205   x0=minx; y0=miny;
10206   x1=maxx; y1=maxy;
10207   mp_pen_bbox(mp, pen_p(p));
10208   minx=minx+x0;
10209   miny=miny+y0;
10210   maxx=maxx+x1;
10211   maxy=maxy+y1;
10212   mp_adjust_bbox(mp, h);
10213   if ( (left_type(path_p(p))==mp_endpoint)&&(lcap_val(p)==2) )
10214     mp_box_ends(mp, path_p(p), pen_p(p), h);
10215   break;
10216
10217 @ The height width and depth information stored in a text node determines a
10218 rectangle that needs to be transformed according to the transformation
10219 parameters stored in the text node.
10220
10221 @<Other cases for updating the bounding box...@>=
10222 case mp_text_code: 
10223   x1=mp_take_scaled(mp, txx_val(p),width_val(p));
10224   y0=mp_take_scaled(mp, txy_val(p),-depth_val(p));
10225   y1=mp_take_scaled(mp, txy_val(p),height_val(p));
10226   minx=tx_val(p);
10227   maxx=minx;
10228   if ( y0<y1 ) { minx=minx+y0; maxx=maxx+y1;  }
10229   else         { minx=minx+y1; maxx=maxx+y0;  }
10230   if ( x1<0 ) minx=minx+x1;  else maxx=maxx+x1;
10231   x1=mp_take_scaled(mp, tyx_val(p),width_val(p));
10232   y0=mp_take_scaled(mp, tyy_val(p),-depth_val(p));
10233   y1=mp_take_scaled(mp, tyy_val(p),height_val(p));
10234   miny=ty_val(p);
10235   maxy=miny;
10236   if ( y0<y1 ) { miny=miny+y0; maxy=maxy+y1;  }
10237   else         { miny=miny+y1; maxy=maxy+y0;  }
10238   if ( x1<0 ) miny=miny+x1;  else maxy=maxy+x1;
10239   mp_adjust_bbox(mp, h);
10240   break;
10241
10242 @ This case involves a recursive call that advances |bblast(h)| to the node of
10243 type |mp_stop_clip_code| that matches |p|.
10244
10245 @<Other cases for updating the bounding box...@>=
10246 case mp_start_clip_code: 
10247   mp_path_bbox(mp, path_p(p));
10248   x0=minx; y0=miny;
10249   x1=maxx; y1=maxy;
10250   sminx=minx_val(h); sminy=miny_val(h);
10251   smaxx=maxx_val(h); smaxy=maxy_val(h);
10252   @<Reinitialize the bounding box in header |h| and call |set_bbox| recursively
10253     starting at |link(p)|@>;
10254   @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,
10255     |y0|, |y1|@>;
10256   minx=sminx; miny=sminy;
10257   maxx=smaxx; maxy=smaxy;
10258   mp_adjust_bbox(mp, h);
10259   break;
10260
10261 @ @<Reinitialize the bounding box in header |h| and call |set_bbox|...@>=
10262 minx_val(h)=el_gordo;
10263 miny_val(h)=el_gordo;
10264 maxx_val(h)=-el_gordo;
10265 maxy_val(h)=-el_gordo;
10266 mp_set_bbox(mp, h,false)
10267
10268 @ @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,...@>=
10269 if ( minx_val(h)<x0 ) minx_val(h)=x0;
10270 if ( miny_val(h)<y0 ) miny_val(h)=y0;
10271 if ( maxx_val(h)>x1 ) maxx_val(h)=x1;
10272 if ( maxy_val(h)>y1 ) maxy_val(h)=y1
10273
10274 @* \[22] Finding an envelope.
10275 When \MP\ has a path and a polygonal pen, it needs to express the desired
10276 shape in terms of things \ps\ can understand.  The present task is to compute
10277 a new path that describes the region to be filled.  It is convenient to
10278 define this as a two step process where the first step is determining what
10279 offset to use for each segment of the path.
10280
10281 @ Given a pointer |c| to a cyclic path,
10282 and a pointer~|h| to the first knot of a pen polygon,
10283 the |offset_prep| routine changes the path into cubics that are
10284 associated with particular pen offsets. Thus if the cubic between |p|
10285 and~|q| is associated with the |k|th offset and the cubic between |q| and~|r|
10286 has offset |l| then |info(q)=zero_off+l-k|. (The constant |zero_off| is added
10287 to because |l-k| could be negative.)
10288
10289 After overwriting the type information with offset differences, we no longer
10290 have a true path so we refer to the knot list returned by |offset_prep| as an
10291 ``envelope spec.''
10292 @^envelope spec@>
10293 Since an envelope spec only determines relative changes in pen offsets,
10294 |offset_prep| sets a global variable |spec_offset| to the relative change from
10295 |h| to the first offset.
10296
10297 @d zero_off 16384 /* added to offset changes to make them positive */
10298
10299 @<Glob...@>=
10300 integer spec_offset; /* number of pen edges between |h| and the initial offset */
10301
10302 @ @c @<Declare subroutines needed by |offset_prep|@>;
10303 pointer mp_offset_prep (MP mp,pointer c, pointer h) {
10304   halfword n; /* the number of vertices in the pen polygon */
10305   pointer p,q,r,w, ww; /* for list manipulation */
10306   integer k_needed; /* amount to be added to |info(p)| when it is computed */
10307   pointer w0; /* a pointer to pen offset to use just before |p| */
10308   scaled dxin,dyin; /* the direction into knot |p| */
10309   integer turn_amt; /* change in pen offsets for the current cubic */
10310   @<Other local variables for |offset_prep|@>;
10311   dx0=0; dy0=0;
10312   @<Initialize the pen size~|n|@>;
10313   @<Initialize the incoming direction and pen offset at |c|@>;
10314   p=c; k_needed=0;
10315   do {  
10316     q=link(p);
10317     @<Split the cubic between |p| and |q|, if necessary, into cubics
10318       associated with single offsets, after which |q| should
10319       point to the end of the final such cubic@>;
10320     @<Advance |p| to node |q|, removing any ``dead'' cubics that
10321       might have been introduced by the splitting process@>;
10322   } while (q!=c);
10323   @<Fix the offset change in |info(c)| and set the return value of
10324     |offset_prep|@>;
10325 }
10326
10327 @ We shall want to keep track of where certain knots on the cyclic path
10328 wind up in the envelope spec.  It doesn't suffice just to keep pointers to
10329 knot nodes because some nodes are deleted while removing dead cubics.  Thus
10330 |offset_prep| updates the following pointers
10331
10332 @<Glob...@>=
10333 pointer spec_p1;
10334 pointer spec_p2; /* pointers to distinguished knots */
10335
10336 @ @<Set init...@>=
10337 mp->spec_p1=null; mp->spec_p2=null;
10338
10339 @ @<Initialize the pen size~|n|@>=
10340 n=0; p=h;
10341 do {  
10342   incr(n);
10343   p=link(p);
10344 } while (p!=h)
10345
10346 @ Since the true incoming direction isn't known yet, we just pick a direction
10347 consistent with the pen offset~|h|.  If this is wrong, it can be corrected
10348 later.
10349
10350 @<Initialize the incoming direction and pen offset at |c|@>=
10351 dxin=x_coord(link(h))-x_coord(knil(h));
10352 dyin=y_coord(link(h))-y_coord(knil(h));
10353 if ( (dxin==0)&&(dyin==0) ) {
10354   dxin=y_coord(knil(h))-y_coord(h);
10355   dyin=x_coord(h)-x_coord(knil(h));
10356 }
10357 w0=h
10358
10359 @ We must be careful not to remove the only cubic in a cycle.
10360
10361 But we must also be careful for another reason. If the user-supplied
10362 path starts with a set of degenerate cubics, these should not be removed
10363 because at this point we cannot do so cleanly. The relevant bug is
10364 tracker id 267, bugs 52c, reported by Boguslav.
10365
10366 @<Advance |p| to node |q|, removing any ``dead'' cubics...@>=
10367 do {  r=link(p);
10368 if ( x_coord(p)==right_x(p) ) if ( y_coord(p)==right_y(p) )
10369  if ( x_coord(p)==left_x(r) ) if ( y_coord(p)==left_y(r) )
10370   if ( x_coord(p)==x_coord(r) ) if ( y_coord(p)==y_coord(r) )
10371     if ( r!=p ) if ( ((r!=q) || (originator(r)!=mp_metapost_user)) ) {
10372       @<Remove the cubic following |p| and update the data structures
10373         to merge |r| into |p|@>;
10374 }
10375 p=r;
10376 } while (p!=q)
10377
10378 @ @<Remove the cubic following |p| and update the data structures...@>=
10379 { k_needed=info(p)-zero_off;
10380   if ( r==q ) { 
10381     q=p;
10382   } else { 
10383     info(p)=k_needed+info(r);
10384     k_needed=0;
10385   };
10386   if ( r==c ) { info(p)=info(c); c=p; };
10387   if ( r==mp->spec_p1 ) mp->spec_p1=p;
10388   if ( r==mp->spec_p2 ) mp->spec_p2=p;
10389   r=p; mp_remove_cubic(mp, p);
10390 }
10391
10392 @ Not setting the |info| field of the newly created knot allows the splitting
10393 routine to work for paths.
10394
10395 @<Declare subroutines needed by |offset_prep|@>=
10396 void mp_split_cubic (MP mp,pointer p, fraction t) { /* splits the cubic after |p| */
10397   scaled v; /* an intermediate value */
10398   pointer q,r; /* for list manipulation */
10399   q=link(p); r=mp_get_node(mp, knot_node_size); link(p)=r; link(r)=q;
10400   originator(r)=mp_program_code;
10401   left_type(r)=mp_explicit; right_type(r)=mp_explicit;
10402   v=t_of_the_way(right_x(p),left_x(q));
10403   right_x(p)=t_of_the_way(x_coord(p),right_x(p));
10404   left_x(q)=t_of_the_way(left_x(q),x_coord(q));
10405   left_x(r)=t_of_the_way(right_x(p),v);
10406   right_x(r)=t_of_the_way(v,left_x(q));
10407   x_coord(r)=t_of_the_way(left_x(r),right_x(r));
10408   v=t_of_the_way(right_y(p),left_y(q));
10409   right_y(p)=t_of_the_way(y_coord(p),right_y(p));
10410   left_y(q)=t_of_the_way(left_y(q),y_coord(q));
10411   left_y(r)=t_of_the_way(right_y(p),v);
10412   right_y(r)=t_of_the_way(v,left_y(q));
10413   y_coord(r)=t_of_the_way(left_y(r),right_y(r));
10414 }
10415
10416 @ This does not set |info(p)| or |right_type(p)|.
10417
10418 @<Declare subroutines needed by |offset_prep|@>=
10419 void mp_remove_cubic (MP mp,pointer p) { /* removes the dead cubic following~|p| */
10420   pointer q; /* the node that disappears */
10421   q=link(p); link(p)=link(q);
10422   right_x(p)=right_x(q); right_y(p)=right_y(q);
10423   mp_free_node(mp, q,knot_node_size);
10424 }
10425
10426 @ Let $d\prec d'$ mean that the counter-clockwise angle from $d$ to~$d'$ is
10427 strictly between zero and $180^\circ$.  Then we can define $d\preceq d'$ to
10428 mean that the angle could be zero or $180^\circ$. If $w_k=(u_k,v_k)$ is the
10429 $k$th pen offset, the $k$th pen edge direction is defined by the formula
10430 $$d_k=(u\k-u_k,\,v\k-v_k).$$
10431 When listed by increasing $k$, these directions occur in counter-clockwise
10432 order so that $d_k\preceq d\k$ for all~$k$.
10433 The goal of |offset_prep| is to find an offset index~|k| to associate with
10434 each cubic, such that the direction $d(t)$ of the cubic satisfies
10435 $$d_{k-1}\preceq d(t)\preceq d_k\qquad\hbox{for $0\le t\le 1$.}\eqno(*)$$
10436 We may have to split a cubic into many pieces before each
10437 piece corresponds to a unique offset.
10438
10439 @<Split the cubic between |p| and |q|, if necessary, into cubics...@>=
10440 info(p)=zero_off+k_needed;
10441 k_needed=0;
10442 @<Prepare for derivative computations;
10443   |goto not_found| if the current cubic is dead@>;
10444 @<Find the initial direction |(dx,dy)|@>;
10445 @<Update |info(p)| and find the offset $w_k$ such that
10446   $d_{k-1}\preceq(\\{dx},\\{dy})\prec d_k$; also advance |w0| for
10447   the direction change at |p|@>;
10448 @<Find the final direction |(dxin,dyin)|@>;
10449 @<Decide on the net change in pen offsets and set |turn_amt|@>;
10450 @<Complete the offset splitting process@>;
10451 w0=mp_pen_walk(mp, w0,turn_amt);
10452 NOT_FOUND: do_nothing
10453
10454 @ @<Declare subroutines needed by |offset_prep|@>=
10455 pointer mp_pen_walk (MP mp,pointer w, integer k) {
10456   /* walk |k| steps around a pen from |w| */
10457   while ( k>0 ) { w=link(w); decr(k);  };
10458   while ( k<0 ) { w=knil(w); incr(k);  };
10459   return w;
10460 }
10461
10462 @ The direction of a cubic $B(z_0,z_1,z_2,z_3;t)=\bigl(x(t),y(t)\bigr)$ can be
10463 calculated from the quadratic polynomials
10464 ${1\over3}x'(t)=B(x_1-x_0,x_2-x_1,x_3-x_2;t)$ and
10465 ${1\over3}y'(t)=B(y_1-y_0,y_2-y_1,y_3-y_2;t)$.
10466 Since we may be calculating directions from several cubics
10467 split from the current one, it is desirable to do these calculations
10468 without losing too much precision. ``Scaled up'' values of the
10469 derivatives, which will be less tainted by accumulated errors than
10470 derivatives found from the cubics themselves, are maintained in
10471 local variables |x0|, |x1|, and |x2|, representing $X_0=2^l(x_1-x_0)$,
10472 $X_1=2^l(x_2-x_1)$, and $X_2=2^l(x_3-x_2)$; similarly |y0|, |y1|, and~|y2|
10473 represent $Y_0=2^l(y_1-y_0)$, $Y_1=2^l(y_2-y_1)$, and $Y_2=2^l(y_3-y_2)$.
10474
10475 @<Other local variables for |offset_prep|@>=
10476 integer x0,x1,x2,y0,y1,y2; /* representatives of derivatives */
10477 integer t0,t1,t2; /* coefficients of polynomial for slope testing */
10478 integer du,dv,dx,dy; /* for directions of the pen and the curve */
10479 integer dx0,dy0; /* initial direction for the first cubic in the curve */
10480 integer mp_max_coef; /* used while scaling */
10481 integer x0a,x1a,x2a,y0a,y1a,y2a; /* intermediate values */
10482 fraction t; /* where the derivative passes through zero */
10483 fraction s; /* a temporary value */
10484
10485 @ @<Prepare for derivative computations...@>=
10486 x0=right_x(p)-x_coord(p);
10487 x2=x_coord(q)-left_x(q);
10488 x1=left_x(q)-right_x(p);
10489 y0=right_y(p)-y_coord(p); y2=y_coord(q)-left_y(q);
10490 y1=left_y(q)-right_y(p);
10491 mp_max_coef=abs(x0);
10492 if ( abs(x1)>mp_max_coef ) mp_max_coef=abs(x1);
10493 if ( abs(x2)>mp_max_coef ) mp_max_coef=abs(x2);
10494 if ( abs(y0)>mp_max_coef ) mp_max_coef=abs(y0);
10495 if ( abs(y1)>mp_max_coef ) mp_max_coef=abs(y1);
10496 if ( abs(y2)>mp_max_coef ) mp_max_coef=abs(y2);
10497 if ( mp_max_coef==0 ) goto NOT_FOUND;
10498 while ( mp_max_coef<fraction_half ) {
10499   mp_max_coef+=mp_max_coef;
10500   x0+=x0; x1+=x1; x2+=x2;
10501   y0+=y0; y1+=y1; y2+=y2;
10502 }
10503
10504 @ Let us first solve a special case of the problem: Suppose we
10505 know an index~$k$ such that either (i)~$d(t)\succeq d_{k-1}$ for all~$t$
10506 and $d(0)\prec d_k$, or (ii)~$d(t)\preceq d_k$ for all~$t$ and
10507 $d(0)\succ d_{k-1}$.
10508 Then, in a sense, we're halfway done, since one of the two relations
10509 in $(*)$ is satisfied, and the other couldn't be satisfied for
10510 any other value of~|k|.
10511
10512 Actually, the conditions can be relaxed somewhat since a relation such as
10513 $d(t)\succeq d_{k-1}$ restricts $d(t)$ to a half plane when all that really
10514 matters is whether $d(t)$ crosses the ray in the $d_{k-1}$ direction from
10515 the origin.  The condition for case~(i) becomes $d_{k-1}\preceq d(0)\prec d_k$
10516 and $d(t)$ never crosses the $d_{k-1}$ ray in the clockwise direction.
10517 Case~(ii) is similar except $d(t)$ cannot cross the $d_k$ ray in the
10518 counterclockwise direction.
10519
10520 The |fin_offset_prep| subroutine solves the stated subproblem.
10521 It has a parameter called |rise| that is |1| in
10522 case~(i), |-1| in case~(ii). Parameters |x0| through |y2| represent
10523 the derivative of the cubic following |p|.
10524 The |w| parameter should point to offset~$w_k$ and |info(p)| should already
10525 be set properly.  The |turn_amt| parameter gives the absolute value of the
10526 overall net change in pen offsets.
10527
10528 @<Declare subroutines needed by |offset_prep|@>=
10529 void mp_fin_offset_prep (MP mp,pointer p, pointer w, integer 
10530   x0,integer x1, integer x2, integer y0, integer y1, integer y2, 
10531   integer rise, integer turn_amt)  {
10532   pointer ww; /* for list manipulation */
10533   scaled du,dv; /* for slope calculation */
10534   integer t0,t1,t2; /* test coefficients */
10535   fraction t; /* place where the derivative passes a critical slope */
10536   fraction s; /* slope or reciprocal slope */
10537   integer v; /* intermediate value for updating |x0..y2| */
10538   pointer q; /* original |link(p)| */
10539   q=link(p);
10540   while (1)  { 
10541     if ( rise>0 ) ww=link(w); /* a pointer to $w\k$ */
10542     else  ww=knil(w); /* a pointer to $w_{k-1}$ */
10543     @<Compute test coefficients |(t0,t1,t2)|
10544       for $d(t)$ versus $d_k$ or $d_{k-1}$@>;
10545     t=mp_crossing_point(mp, t0,t1,t2);
10546     if ( t>=fraction_one ) {
10547       if ( turn_amt>0 ) t=fraction_one;  else return;
10548     }
10549     @<Split the cubic at $t$,
10550       and split off another cubic if the derivative crosses back@>;
10551     w=ww;
10552   }
10553 }
10554
10555 @ We want $B(\\{t0},\\{t1},\\{t2};t)$ to be the dot product of $d(t)$ with a
10556 $-90^\circ$ rotation of the vector from |w| to |ww|.  This makes the resulting
10557 function cross from positive to negative when $d_{k-1}\preceq d(t)\preceq d_k$
10558 begins to fail.
10559
10560 @<Compute test coefficients |(t0,t1,t2)| for $d(t)$ versus...@>=
10561 du=x_coord(ww)-x_coord(w); dv=y_coord(ww)-y_coord(w);
10562 if ( abs(du)>=abs(dv) ) {
10563   s=mp_make_fraction(mp, dv,du);
10564   t0=mp_take_fraction(mp, x0,s)-y0;
10565   t1=mp_take_fraction(mp, x1,s)-y1;
10566   t2=mp_take_fraction(mp, x2,s)-y2;
10567   if ( du<0 ) { negate(t0); negate(t1); negate(t2);  }
10568 } else { 
10569   s=mp_make_fraction(mp, du,dv);
10570   t0=x0-mp_take_fraction(mp, y0,s);
10571   t1=x1-mp_take_fraction(mp, y1,s);
10572   t2=x2-mp_take_fraction(mp, y2,s);
10573   if ( dv<0 ) { negate(t0); negate(t1); negate(t2);  }
10574 }
10575 if ( t0<0 ) t0=0 /* should be positive without rounding error */
10576
10577 @ The curve has crossed $d_k$ or $d_{k-1}$; its initial segment satisfies
10578 $(*)$, and it might cross again, yielding another solution of $(*)$.
10579
10580 @<Split the cubic at $t$, and split off another...@>=
10581
10582 mp_split_cubic(mp, p,t); p=link(p); info(p)=zero_off+rise;
10583 decr(turn_amt);
10584 v=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10585 x0=t_of_the_way(v,x1);
10586 v=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10587 y0=t_of_the_way(v,y1);
10588 if ( turn_amt<0 ) {
10589   t1=t_of_the_way(t1,t2);
10590   if ( t1>0 ) t1=0; /* without rounding error, |t1| would be |<=0| */
10591   t=mp_crossing_point(mp, 0,-t1,-t2);
10592   if ( t>fraction_one ) t=fraction_one;
10593   incr(turn_amt);
10594   if ( (t==fraction_one)&&(link(p)!=q) ) {
10595     info(link(p))=info(link(p))-rise;
10596   } else { 
10597     mp_split_cubic(mp, p,t); info(link(p))=zero_off-rise;
10598     v=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10599     x2=t_of_the_way(x1,v);
10600     v=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10601     y2=t_of_the_way(y1,v);
10602   }
10603 }
10604 }
10605
10606 @ Now we must consider the general problem of |offset_prep|, when
10607 nothing is known about a given cubic. We start by finding its
10608 direction in the vicinity of |t=0|.
10609
10610 If $z'(t)=0$, the given cubic is numerically unstable but |offset_prep|
10611 has not yet introduced any more numerical errors.  Thus we can compute
10612 the true initial direction for the given cubic, even if it is almost
10613 degenerate.
10614
10615 @<Find the initial direction |(dx,dy)|@>=
10616 dx=x0; dy=y0;
10617 if ( dx==0 ) if ( dy==0 ) { 
10618   dx=x1; dy=y1;
10619   if ( dx==0 ) if ( dy==0 ) { 
10620     dx=x2; dy=y2;
10621   }
10622 }
10623 if ( p==c ) { dx0=dx; dy0=dy;  }
10624
10625 @ @<Find the final direction |(dxin,dyin)|@>=
10626 dxin=x2; dyin=y2;
10627 if ( dxin==0 ) if ( dyin==0 ) {
10628   dxin=x1; dyin=y1;
10629   if ( dxin==0 ) if ( dyin==0 ) {
10630     dxin=x0; dyin=y0;
10631   }
10632 }
10633
10634 @ The next step is to bracket the initial direction between consecutive
10635 edges of the pen polygon.  We must be careful to turn clockwise only if
10636 this makes the turn less than $180^\circ$. (A $180^\circ$ turn must be
10637 counter-clockwise in order to make \&{doublepath} envelopes come out
10638 @:double_path_}{\&{doublepath} primitive@>
10639 right.) This code depends on |w0| being the offset for |(dxin,dyin)|.
10640
10641 @<Update |info(p)| and find the offset $w_k$ such that...@>=
10642 turn_amt=mp_get_turn_amt(mp, w0, dx, dy, mp_ab_vs_cd(mp, dy,dxin,dx,dyin)>=0);
10643 w=mp_pen_walk(mp, w0, turn_amt);
10644 w0=w;
10645 info(p)=info(p)+turn_amt
10646
10647 @ Decide how many pen offsets to go away from |w| in order to find the offset
10648 for |(dx,dy)|, going counterclockwise if |ccw| is |true|.  This assumes that
10649 |w| is the offset for some direction $(x',y')$ from which the angle to |(dx,dy)|
10650 in the sense determined by |ccw| is less than or equal to $180^\circ$.
10651
10652 If the pen polygon has only two edges, they could both be parallel
10653 to |(dx,dy)|.  In this case, we must be careful to stop after crossing the first
10654 such edge in order to avoid an infinite loop.
10655
10656 @<Declare subroutines needed by |offset_prep|@>=
10657 integer mp_get_turn_amt (MP mp,pointer w, scaled  dx,
10658                          scaled dy, boolean  ccw) {
10659   pointer ww; /* a neighbor of knot~|w| */
10660   integer s; /* turn amount so far */
10661   integer t; /* |ab_vs_cd| result */
10662   s=0;
10663   if ( ccw ) { 
10664     ww=link(w);
10665     do {  
10666       t=mp_ab_vs_cd(mp, dy,x_coord(ww)-x_coord(w),
10667                         dx,y_coord(ww)-y_coord(w));
10668       if ( t<0 ) break;
10669       incr(s);
10670       w=ww; ww=link(ww);
10671     } while (t>0);
10672   } else { 
10673     ww=knil(w);
10674     while ( mp_ab_vs_cd(mp, dy,x_coord(w)-x_coord(ww),
10675                             dx,y_coord(w)-y_coord(ww))<0 ) { 
10676       decr(s);
10677       w=ww; ww=knil(ww);
10678     }
10679   }
10680   return s;
10681 }
10682
10683 @ When we're all done, the final offset is |w0| and the final curve direction
10684 is |(dxin,dyin)|.  With this knowledge of the incoming direction at |c|, we
10685 can correct |info(c)| which was erroneously based on an incoming offset
10686 of~|h|.
10687
10688 @d fix_by(A) info(c)=info(c)+(A)
10689
10690 @<Fix the offset change in |info(c)| and set the return value of...@>=
10691 mp->spec_offset=info(c)-zero_off;
10692 if ( link(c)==c ) {
10693   info(c)=zero_off+n;
10694 } else { 
10695   fix_by(k_needed);
10696   while ( w0!=h ) { fix_by(1); w0=link(w0);  };
10697   while ( info(c)<=zero_off-n ) fix_by(n);
10698   while ( info(c)>zero_off ) fix_by(-n);
10699   if ( (info(c)!=zero_off)&&(mp_ab_vs_cd(mp, dy0,dxin,dx0,dyin)>=0) ) fix_by(n);
10700 }
10701 return c
10702
10703 @ Finally we want to reduce the general problem to situations that
10704 |fin_offset_prep| can handle. We split the cubic into at most three parts
10705 with respect to $d_{k-1}$, and apply |fin_offset_prep| to each part.
10706
10707 @<Complete the offset splitting process@>=
10708 ww=knil(w);
10709 @<Compute test coeff...@>;
10710 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set
10711   |t:=fraction_one+1|@>;
10712 if ( t>fraction_one ) {
10713   mp_fin_offset_prep(mp, p,w,x0,x1,x2,y0,y1,y2,1,turn_amt);
10714 } else {
10715   mp_split_cubic(mp, p,t); r=link(p);
10716   x1a=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10717   x2a=t_of_the_way(x1a,x1);
10718   y1a=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10719   y2a=t_of_the_way(y1a,y1);
10720   mp_fin_offset_prep(mp, p,w,x0,x1a,x2a,y0,y1a,y2a,1,0); x0=x2a; y0=y2a;
10721   info(r)=zero_off-1;
10722   if ( turn_amt>=0 ) {
10723     t1=t_of_the_way(t1,t2);
10724     if ( t1>0 ) t1=0;
10725     t=mp_crossing_point(mp, 0,-t1,-t2);
10726     if ( t>fraction_one ) t=fraction_one;
10727     @<Split off another rising cubic for |fin_offset_prep|@>;
10728     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,0);
10729   } else {
10730     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,-1-turn_amt);
10731   }
10732 }
10733
10734 @ @<Split off another rising cubic for |fin_offset_prep|@>=
10735 mp_split_cubic(mp, r,t); info(link(r))=zero_off+1;
10736 x1a=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10737 x0a=t_of_the_way(x1,x1a);
10738 y1a=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10739 y0a=t_of_the_way(y1,y1a);
10740 mp_fin_offset_prep(mp, link(r),w,x0a,x1a,x2,y0a,y1a,y2,1,turn_amt);
10741 x2=x0a; y2=y0a
10742
10743 @ At this point, the direction of the incoming pen edge is |(-du,-dv)|.
10744 When the component of $d(t)$ perpendicular to |(-du,-dv)| crosses zero, we
10745 need to decide whether the directions are parallel or antiparallel.  We
10746 can test this by finding the dot product of $d(t)$ and |(-du,-dv)|, but this
10747 should be avoided when the value of |turn_amt| already determines the
10748 answer.  If |t2<0|, there is one crossing and it is antiparallel only if
10749 |turn_amt>=0|.  If |turn_amt<0|, there should always be at least one
10750 crossing and the first crossing cannot be antiparallel.
10751
10752 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set...@>=
10753 t=mp_crossing_point(mp, t0,t1,t2);
10754 if ( turn_amt>=0 ) {
10755   if ( t2<0 ) {
10756     t=fraction_one+1;
10757   } else { 
10758     u0=t_of_the_way(x0,x1);
10759     u1=t_of_the_way(x1,x2);
10760     ss=mp_take_fraction(mp, -du,t_of_the_way(u0,u1));
10761     v0=t_of_the_way(y0,y1);
10762     v1=t_of_the_way(y1,y2);
10763     ss=ss+mp_take_fraction(mp, -dv,t_of_the_way(v0,v1));
10764     if ( ss<0 ) t=fraction_one+1;
10765   }
10766 } else if ( t>fraction_one ) {
10767   t=fraction_one;
10768 }
10769
10770 @ @<Other local variables for |offset_prep|@>=
10771 integer u0,u1,v0,v1; /* intermediate values for $d(t)$ calculation */
10772 integer ss = 0; /* the part of the dot product computed so far */
10773 int d_sign; /* sign of overall change in direction for this cubic */
10774
10775 @ If the cubic almost has a cusp, it is a numerically ill-conditioned
10776 problem to decide which way it loops around but that's OK as long we're
10777 consistent.  To make \&{doublepath} envelopes work properly, reversing
10778 the path should always change the sign of |turn_amt|.
10779
10780 @<Decide on the net change in pen offsets and set |turn_amt|@>=
10781 d_sign=mp_ab_vs_cd(mp, dx,dyin, dxin,dy);
10782 if ( d_sign==0 ) {
10783   if ( dx==0 ) {
10784     if ( dy>0 ) d_sign=1;  else d_sign=-1;
10785   } else if ( dx>0 ) { 
10786     d_sign=1;  
10787   } else { 
10788     d_sign=-1; 
10789   }
10790 }
10791 @<Make |ss| negative if and only if the total change in direction is
10792   more than $180^\circ$@>;
10793 turn_amt=mp_get_turn_amt(mp, w, dxin, dyin, d_sign>0);
10794 if ( ss<0 ) turn_amt=turn_amt-d_sign*n
10795
10796 @ In order to be invariant under path reversal, the result of this computation
10797 should not change when |x0|, |y0|, $\ldots$ are all negated and |(x0,y0)| is
10798 then swapped with |(x2,y2)|.  We make use of the identities
10799 |take_fraction(-a,-b)=take_fraction(a,b)| and
10800 |t_of_the_way(-a,-b)=-(t_of_the_way(a,b))|.
10801
10802 @<Make |ss| negative if and only if the total change in direction is...@>=
10803 t0=half(mp_take_fraction(mp, x0,y2))-half(mp_take_fraction(mp, x2,y0));
10804 t1=half(mp_take_fraction(mp, x1,y0+y2))-half(mp_take_fraction(mp, y1,x0+x2));
10805 if ( t0==0 ) t0=d_sign; /* path reversal always negates |d_sign| */
10806 if ( t0>0 ) {
10807   t=mp_crossing_point(mp, t0,t1,-t0);
10808   u0=t_of_the_way(x0,x1);
10809   u1=t_of_the_way(x1,x2);
10810   v0=t_of_the_way(y0,y1);
10811   v1=t_of_the_way(y1,y2);
10812 } else { 
10813   t=mp_crossing_point(mp, -t0,t1,t0);
10814   u0=t_of_the_way(x2,x1);
10815   u1=t_of_the_way(x1,x0);
10816   v0=t_of_the_way(y2,y1);
10817   v1=t_of_the_way(y1,y0);
10818 }
10819 s=mp_take_fraction(mp, x0+x2,t_of_the_way(u0,u1))+
10820   mp_take_fraction(mp, y0+y2,t_of_the_way(v0,v1))
10821
10822 @ Here's a routine that prints an envelope spec in symbolic form.  It assumes
10823 that the |cur_pen| has not been walked around to the first offset.
10824
10825 @c 
10826 void mp_print_spec (MP mp,pointer cur_spec, pointer cur_pen, char *s) {
10827   pointer p,q; /* list traversal */
10828   pointer w; /* the current pen offset */
10829   mp_print_diagnostic(mp, "Envelope spec",s,true);
10830   p=cur_spec; w=mp_pen_walk(mp, cur_pen,mp->spec_offset);
10831   mp_print_ln(mp);
10832   mp_print_two(mp, x_coord(cur_spec),y_coord(cur_spec));
10833   mp_print(mp, " % beginning with offset ");
10834   mp_print_two(mp, x_coord(w),y_coord(w));
10835   do { 
10836     do {  
10837       q=link(p);
10838       @<Print the cubic between |p| and |q|@>;
10839       p=q;
10840     } while (! ((p==cur_spec) || (info(p)!=zero_off)));
10841     if ( info(p)!=zero_off ) {
10842       @<Update |w| as indicated by |info(p)| and print an explanation@>;
10843     }
10844   } while (p!=cur_spec);
10845   mp_print_nl(mp, " & cycle");
10846   mp_end_diagnostic(mp, true);
10847 }
10848
10849 @ @<Update |w| as indicated by |info(p)| and print an explanation@>=
10850
10851   w=mp_pen_walk(mp, w,info(p)-zero_off);
10852   mp_print(mp, " % ");
10853   if ( info(p)>zero_off ) mp_print(mp, "counter");
10854   mp_print(mp, "clockwise to offset ");
10855   mp_print_two(mp, x_coord(w),y_coord(w));
10856 }
10857
10858 @ @<Print the cubic between |p| and |q|@>=
10859
10860   mp_print_nl(mp, "   ..controls ");
10861   mp_print_two(mp, right_x(p),right_y(p));
10862   mp_print(mp, " and ");
10863   mp_print_two(mp, left_x(q),left_y(q));
10864   mp_print_nl(mp, " ..");
10865   mp_print_two(mp, x_coord(q),y_coord(q));
10866 }
10867
10868 @ Once we have an envelope spec, the remaining task to construct the actual
10869 envelope by offsetting each cubic as determined by the |info| fields in
10870 the knots.  First we use |offset_prep| to convert the |c| into an envelope
10871 spec. Then we add the offsets so that |c| becomes a cyclic path that represents
10872 the envelope.
10873
10874 The |ljoin| and |miterlim| parameters control the treatment of points where the
10875 pen offset changes, and |lcap| controls the endpoints of a \&{doublepath}.
10876 The endpoints are easily located because |c| is given in undoubled form
10877 and then doubled in this procedure.  We use |spec_p1| and |spec_p2| to keep
10878 track of the endpoints and treat them like very sharp corners.
10879 Butt end caps are treated like beveled joins; round end caps are treated like
10880 round joins; and square end caps are achieved by setting |join_type:=3|.
10881
10882 None of these parameters apply to inside joins where the convolution tracing
10883 has retrograde lines.  In such cases we use a simple connect-the-endpoints
10884 approach that is achieved by setting |join_type:=2|.
10885
10886 @c @<Declare a function called |insert_knot|@>;
10887 pointer mp_make_envelope (MP mp,pointer c, pointer h, small_number ljoin,
10888   small_number lcap, scaled miterlim) {
10889   pointer p,q,r,q0; /* for manipulating the path */
10890   int join_type=0; /* codes |0..3| for mitered, round, beveled, or square */
10891   pointer w,w0; /* the pen knot for the current offset */
10892   scaled qx,qy; /* unshifted coordinates of |q| */
10893   halfword k,k0; /* controls pen edge insertion */
10894   @<Other local variables for |make_envelope|@>;
10895   dxin=0; dyin=0; dxout=0; dyout=0;
10896   mp->spec_p1=null; mp->spec_p2=null;
10897   @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>;
10898   @<Use |offset_prep| to compute the envelope spec then walk |h| around to
10899     the initial offset@>;
10900   w=h;
10901   p=c;
10902   do {  
10903     q=link(p); q0=q;
10904     qx=x_coord(q); qy=y_coord(q);
10905     k=info(q);
10906     k0=k; w0=w;
10907     if ( k!=zero_off ) {
10908       @<Set |join_type| to indicate how to handle offset changes at~|q|@>;
10909     }
10910     @<Add offset |w| to the cubic from |p| to |q|@>;
10911     while ( k!=zero_off ) { 
10912       @<Step |w| and move |k| one step closer to |zero_off|@>;
10913       if ( (join_type==1)||(k==zero_off) )
10914          q=mp_insert_knot(mp, q,qx+x_coord(w),qy+y_coord(w));
10915     };
10916     if ( q!=link(p) ) {
10917       @<Set |p=link(p)| and add knots between |p| and |q| as
10918         required by |join_type|@>;
10919     }
10920     p=q;
10921   } while (q0!=c);
10922   return c;
10923 }
10924
10925 @ @<Use |offset_prep| to compute the envelope spec then walk |h| around to...@>=
10926 c=mp_offset_prep(mp, c,h);
10927 if ( mp->internal[mp_tracing_specs]>0 ) 
10928   mp_print_spec(mp, c,h,"");
10929 h=mp_pen_walk(mp, h,mp->spec_offset)
10930
10931 @ Mitered and squared-off joins depend on path directions that are difficult to
10932 compute for degenerate cubics.  The envelope spec computed by |offset_prep| can
10933 have degenerate cubics only if the entire cycle collapses to a single
10934 degenerate cubic.  Setting |join_type:=2| in this case makes the computed
10935 envelope degenerate as well.
10936
10937 @<Set |join_type| to indicate how to handle offset changes at~|q|@>=
10938 if ( k<zero_off ) {
10939   join_type=2;
10940 } else {
10941   if ( (q!=mp->spec_p1)&&(q!=mp->spec_p2) ) join_type=ljoin;
10942   else if ( lcap==2 ) join_type=3;
10943   else join_type=2-lcap;
10944   if ( (join_type==0)||(join_type==3) ) {
10945     @<Set the incoming and outgoing directions at |q|; in case of
10946       degeneracy set |join_type:=2|@>;
10947     if ( join_type==0 ) {
10948       @<If |miterlim| is less than the secant of half the angle at |q|
10949         then set |join_type:=2|@>;
10950     }
10951   }
10952 }
10953
10954 @ @<If |miterlim| is less than the secant of half the angle at |q|...@>=
10955
10956   tmp=mp_take_fraction(mp, miterlim,fraction_half+
10957       half(mp_take_fraction(mp, dxin,dxout)+mp_take_fraction(mp, dyin,dyout)));
10958   if ( tmp<unity )
10959     if ( mp_take_scaled(mp, miterlim,tmp)<unity ) join_type=2;
10960 }
10961
10962 @ @<Other local variables for |make_envelope|@>=
10963 fraction dxin,dyin,dxout,dyout; /* directions at |q| when square or mitered */
10964 scaled tmp; /* a temporary value */
10965
10966 @ The coordinates of |p| have already been shifted unless |p| is the first
10967 knot in which case they get shifted at the very end.
10968
10969 @<Add offset |w| to the cubic from |p| to |q|@>=
10970 right_x(p)=right_x(p)+x_coord(w);
10971 right_y(p)=right_y(p)+y_coord(w);
10972 left_x(q)=left_x(q)+x_coord(w);
10973 left_y(q)=left_y(q)+y_coord(w);
10974 x_coord(q)=x_coord(q)+x_coord(w);
10975 y_coord(q)=y_coord(q)+y_coord(w);
10976 left_type(q)=mp_explicit;
10977 right_type(q)=mp_explicit
10978
10979 @ @<Step |w| and move |k| one step closer to |zero_off|@>=
10980 if ( k>zero_off ){ w=link(w); decr(k);  }
10981 else { w=knil(w); incr(k);  }
10982
10983 @ The cubic from |q| to the new knot at |(x,y)| becomes a line segment and
10984 the |right_x| and |right_y| fields of |r| are set from |q|.  This is done in
10985 case the cubic containing these control points is ``yet to be examined.''
10986
10987 @<Declare a function called |insert_knot|@>=
10988 pointer mp_insert_knot (MP mp,pointer q, scaled x, scaled y) {
10989   /* returns the inserted knot */
10990   pointer r; /* the new knot */
10991   r=mp_get_node(mp, knot_node_size);
10992   link(r)=link(q); link(q)=r;
10993   right_x(r)=right_x(q);
10994   right_y(r)=right_y(q);
10995   x_coord(r)=x;
10996   y_coord(r)=y;
10997   right_x(q)=x_coord(q);
10998   right_y(q)=y_coord(q);
10999   left_x(r)=x_coord(r);
11000   left_y(r)=y_coord(r);
11001   left_type(r)=mp_explicit;
11002   right_type(r)=mp_explicit;
11003   originator(r)=mp_program_code;
11004   return r;
11005 }
11006
11007 @ After setting |p:=link(p)|, either |join_type=1| or |q=link(p)|.
11008
11009 @<Set |p=link(p)| and add knots between |p| and |q| as...@>=
11010
11011   p=link(p);
11012   if ( (join_type==0)||(join_type==3) ) {
11013     if ( join_type==0 ) {
11014       @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>
11015     } else {
11016       @<Make |r| the last of two knots inserted between |p| and |q| to form a
11017         squared join@>;
11018     }
11019     if ( r!=null ) { 
11020       right_x(r)=x_coord(r);
11021       right_y(r)=y_coord(r);
11022     }
11023   }
11024 }
11025
11026 @ For very small angles, adding a knot is unnecessary and would cause numerical
11027 problems, so we just set |r:=null| in that case.
11028
11029 @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>=
11030
11031   det=mp_take_fraction(mp, dyout,dxin)-mp_take_fraction(mp, dxout,dyin);
11032   if ( abs(det)<26844 ) { 
11033      r=null; /* sine $<10^{-4}$ */
11034   } else { 
11035     tmp=mp_take_fraction(mp, x_coord(q)-x_coord(p),dyout)-
11036         mp_take_fraction(mp, y_coord(q)-y_coord(p),dxout);
11037     tmp=mp_make_fraction(mp, tmp,det);
11038     r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11039       y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11040   }
11041 }
11042
11043 @ @<Other local variables for |make_envelope|@>=
11044 fraction det; /* a determinant used for mitered join calculations */
11045
11046 @ @<Make |r| the last of two knots inserted between |p| and |q| to form a...@>=
11047
11048   ht_x=y_coord(w)-y_coord(w0);
11049   ht_y=x_coord(w0)-x_coord(w);
11050   while ( (abs(ht_x)<fraction_half)&&(abs(ht_y)<fraction_half) ) { 
11051     ht_x+=ht_x; ht_y+=ht_y;
11052   }
11053   @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range dot
11054     product with |(ht_x,ht_y)|@>;
11055   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxin,ht_x)+
11056                                   mp_take_fraction(mp, dyin,ht_y));
11057   r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11058                          y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11059   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxout,ht_x)+
11060                                   mp_take_fraction(mp, dyout,ht_y));
11061   r=mp_insert_knot(mp, r,x_coord(q)+mp_take_fraction(mp, tmp,dxout),
11062                          y_coord(q)+mp_take_fraction(mp, tmp,dyout));
11063 }
11064
11065 @ @<Other local variables for |make_envelope|@>=
11066 fraction ht_x,ht_y; /* perpendicular to the segment from |p| to |q| */
11067 scaled max_ht; /* maximum height of the pen polygon above the |w0|-|w| line */
11068 halfword kk; /* keeps track of the pen vertices being scanned */
11069 pointer ww; /* the pen vertex being tested */
11070
11071 @ The dot product of the vector from |w0| to |ww| with |(ht_x,ht_y)| ranges
11072 from zero to |max_ht|.
11073
11074 @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range...@>=
11075 max_ht=0;
11076 kk=zero_off;
11077 ww=w;
11078 while (1)  { 
11079   @<Step |ww| and move |kk| one step closer to |k0|@>;
11080   if ( kk==k0 ) break;
11081   tmp=mp_take_fraction(mp, x_coord(ww)-x_coord(w0),ht_x)+
11082       mp_take_fraction(mp, y_coord(ww)-y_coord(w0),ht_y);
11083   if ( tmp>max_ht ) max_ht=tmp;
11084 }
11085
11086
11087 @ @<Step |ww| and move |kk| one step closer to |k0|@>=
11088 if ( kk>k0 ) { ww=link(ww); decr(kk);  }
11089 else { ww=knil(ww); incr(kk);  }
11090
11091 @ @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>=
11092 if ( left_type(c)==mp_endpoint ) { 
11093   mp->spec_p1=mp_htap_ypoc(mp, c);
11094   mp->spec_p2=mp->path_tail;
11095   originator(mp->spec_p1)=mp_program_code;
11096   link(mp->spec_p2)=link(mp->spec_p1);
11097   link(mp->spec_p1)=c;
11098   mp_remove_cubic(mp, mp->spec_p1);
11099   c=mp->spec_p1;
11100   if ( c!=link(c) ) {
11101     originator(mp->spec_p2)=mp_program_code;
11102     mp_remove_cubic(mp, mp->spec_p2);
11103   } else {
11104     @<Make |c| look like a cycle of length one@>;
11105   }
11106 }
11107
11108 @ @<Make |c| look like a cycle of length one@>=
11109
11110   left_type(c)=mp_explicit; right_type(c)=mp_explicit;
11111   left_x(c)=x_coord(c); left_y(c)=y_coord(c);
11112   right_x(c)=x_coord(c); right_y(c)=y_coord(c);
11113 }
11114
11115 @ In degenerate situations we might have to look at the knot preceding~|q|.
11116 That knot is |p| but if |p<>c|, its coordinates have already been offset by |w|.
11117
11118 @<Set the incoming and outgoing directions at |q|; in case of...@>=
11119 dxin=x_coord(q)-left_x(q);
11120 dyin=y_coord(q)-left_y(q);
11121 if ( (dxin==0)&&(dyin==0) ) {
11122   dxin=x_coord(q)-right_x(p);
11123   dyin=y_coord(q)-right_y(p);
11124   if ( (dxin==0)&&(dyin==0) ) {
11125     dxin=x_coord(q)-x_coord(p);
11126     dyin=y_coord(q)-y_coord(p);
11127     if ( p!=c ) { /* the coordinates of |p| have been offset by |w| */
11128       dxin=dxin+x_coord(w);
11129       dyin=dyin+y_coord(w);
11130     }
11131   }
11132 }
11133 tmp=mp_pyth_add(mp, dxin,dyin);
11134 if ( tmp==0 ) {
11135   join_type=2;
11136 } else { 
11137   dxin=mp_make_fraction(mp, dxin,tmp);
11138   dyin=mp_make_fraction(mp, dyin,tmp);
11139   @<Set the outgoing direction at |q|@>;
11140 }
11141
11142 @ If |q=c| then the coordinates of |r| and the control points between |q|
11143 and~|r| have already been offset by |h|.
11144
11145 @<Set the outgoing direction at |q|@>=
11146 dxout=right_x(q)-x_coord(q);
11147 dyout=right_y(q)-y_coord(q);
11148 if ( (dxout==0)&&(dyout==0) ) {
11149   r=link(q);
11150   dxout=left_x(r)-x_coord(q);
11151   dyout=left_y(r)-y_coord(q);
11152   if ( (dxout==0)&&(dyout==0) ) {
11153     dxout=x_coord(r)-x_coord(q);
11154     dyout=y_coord(r)-y_coord(q);
11155   }
11156 }
11157 if ( q==c ) {
11158   dxout=dxout-x_coord(h);
11159   dyout=dyout-y_coord(h);
11160 }
11161 tmp=mp_pyth_add(mp, dxout,dyout);
11162 if ( tmp==0 ) mp_confusion(mp, "degenerate spec");
11163 @:this can't happen degerate spec}{\quad degenerate spec@>
11164 dxout=mp_make_fraction(mp, dxout,tmp);
11165 dyout=mp_make_fraction(mp, dyout,tmp)
11166
11167 @* \[23] Direction and intersection times.
11168 A path of length $n$ is defined parametrically by functions $x(t)$ and
11169 $y(t)$, for |0<=t<=n|; we can regard $t$ as the ``time'' at which the path
11170 reaches the point $\bigl(x(t),y(t)\bigr)$.  In this section of the program
11171 we shall consider operations that determine special times associated with
11172 given paths: the first time that a path travels in a given direction, and
11173 a pair of times at which two paths cross each other.
11174
11175 @ Let's start with the easier task. The function |find_direction_time| is
11176 given a direction |(x,y)| and a path starting at~|h|. If the path never
11177 travels in direction |(x,y)|, the direction time will be~|-1|; otherwise
11178 it will be nonnegative.
11179
11180 Certain anomalous cases can arise: If |(x,y)=(0,0)|, so that the given
11181 direction is undefined, the direction time will be~0. If $\bigl(x'(t),
11182 y'(t)\bigr)=(0,0)$, so that the path direction is undefined, it will be
11183 assumed to match any given direction at time~|t|.
11184
11185 The routine solves this problem in nondegenerate cases by rotating the path
11186 and the given direction so that |(x,y)=(1,0)|; i.e., the main task will be
11187 to find when a given path first travels ``due east.''
11188
11189 @c 
11190 scaled mp_find_direction_time (MP mp,scaled x, scaled y, pointer h) {
11191   scaled max; /* $\max\bigl(\vert x\vert,\vert y\vert\bigr)$ */
11192   pointer p,q; /* for list traversal */
11193   scaled n; /* the direction time at knot |p| */
11194   scaled tt; /* the direction time within a cubic */
11195   @<Other local variables for |find_direction_time|@>;
11196   @<Normalize the given direction for better accuracy;
11197     but |return| with zero result if it's zero@>;
11198   n=0; p=h; phi=0;
11199   while (1) { 
11200     if ( right_type(p)==mp_endpoint ) break;
11201     q=link(p);
11202     @<Rotate the cubic between |p| and |q|; then
11203       |goto found| if the rotated cubic travels due east at some time |tt|;
11204       but |break| if an entire cyclic path has been traversed@>;
11205     p=q; n=n+unity;
11206   }
11207   return (-unity);
11208 FOUND: 
11209   return (n+tt);
11210 }
11211
11212 @ @<Normalize the given direction for better accuracy...@>=
11213 if ( abs(x)<abs(y) ) { 
11214   x=mp_make_fraction(mp, x,abs(y));
11215   if ( y>0 ) y=fraction_one; else y=-fraction_one;
11216 } else if ( x==0 ) { 
11217   return 0;
11218 } else  { 
11219   y=mp_make_fraction(mp, y,abs(x));
11220   if ( x>0 ) x=fraction_one; else x=-fraction_one;
11221 }
11222
11223 @ Since we're interested in the tangent directions, we work with the
11224 derivative $${\textstyle1\over3}B'(x_0,x_1,x_2,x_3;t)=
11225 B(x_1-x_0,x_2-x_1,x_3-x_2;t)$$ instead of
11226 $B(x_0,x_1,x_2,x_3;t)$ itself. The derived coefficients are also scaled up
11227 in order to achieve better accuracy.
11228
11229 The given path may turn abruptly at a knot, and it might pass the critical
11230 tangent direction at such a time. Therefore we remember the direction |phi|
11231 in which the previous rotated cubic was traveling. (The value of |phi| will be
11232 undefined on the first cubic, i.e., when |n=0|.)
11233
11234 @<Rotate the cubic between |p| and |q|; then...@>=
11235 tt=0;
11236 @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples of the control
11237   points of the rotated derivatives@>;
11238 if ( y1==0 ) if ( x1>=0 ) goto FOUND;
11239 if ( n>0 ) { 
11240   @<Exit to |found| if an eastward direction occurs at knot |p|@>;
11241   if ( p==h ) break;
11242   };
11243 if ( (x3!=0)||(y3!=0) ) phi=mp_n_arg(mp, x3,y3);
11244 @<Exit to |found| if the curve whose derivatives are specified by
11245   |x1,x2,x3,y1,y2,y3| travels eastward at some time~|tt|@>
11246
11247 @ @<Other local variables for |find_direction_time|@>=
11248 scaled x1,x2,x3,y1,y2,y3;  /* multiples of rotated derivatives */
11249 angle theta,phi; /* angles of exit and entry at a knot */
11250 fraction t; /* temp storage */
11251
11252 @ @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples...@>=
11253 x1=right_x(p)-x_coord(p); x2=left_x(q)-right_x(p);
11254 x3=x_coord(q)-left_x(q);
11255 y1=right_y(p)-y_coord(p); y2=left_y(q)-right_y(p);
11256 y3=y_coord(q)-left_y(q);
11257 max=abs(x1);
11258 if ( abs(x2)>max ) max=abs(x2);
11259 if ( abs(x3)>max ) max=abs(x3);
11260 if ( abs(y1)>max ) max=abs(y1);
11261 if ( abs(y2)>max ) max=abs(y2);
11262 if ( abs(y3)>max ) max=abs(y3);
11263 if ( max==0 ) goto FOUND;
11264 while ( max<fraction_half ){ 
11265   max+=max; x1+=x1; x2+=x2; x3+=x3;
11266   y1+=y1; y2+=y2; y3+=y3;
11267 }
11268 t=x1; x1=mp_take_fraction(mp, x1,x)+mp_take_fraction(mp, y1,y);
11269 y1=mp_take_fraction(mp, y1,x)-mp_take_fraction(mp, t,y);
11270 t=x2; x2=mp_take_fraction(mp, x2,x)+mp_take_fraction(mp, y2,y);
11271 y2=mp_take_fraction(mp, y2,x)-mp_take_fraction(mp, t,y);
11272 t=x3; x3=mp_take_fraction(mp, x3,x)+mp_take_fraction(mp, y3,y);
11273 y3=mp_take_fraction(mp, y3,x)-mp_take_fraction(mp, t,y)
11274
11275 @ @<Exit to |found| if an eastward direction occurs at knot |p|@>=
11276 theta=mp_n_arg(mp, x1,y1);
11277 if ( theta>=0 ) if ( phi<=0 ) if ( phi>=theta-one_eighty_deg ) goto FOUND;
11278 if ( theta<=0 ) if ( phi>=0 ) if ( phi<=theta+one_eighty_deg ) goto FOUND
11279
11280 @ In this step we want to use the |crossing_point| routine to find the
11281 roots of the quadratic equation $B(y_1,y_2,y_3;t)=0$.
11282 Several complications arise: If the quadratic equation has a double root,
11283 the curve never crosses zero, and |crossing_point| will find nothing;
11284 this case occurs iff $y_1y_3=y_2^2$ and $y_1y_2<0$. If the quadratic
11285 equation has simple roots, or only one root, we may have to negate it
11286 so that $B(y_1,y_2,y_3;t)$ crosses from positive to negative at its first root.
11287 And finally, we need to do special things if $B(y_1,y_2,y_3;t)$ is
11288 identically zero.
11289
11290 @ @<Exit to |found| if the curve whose derivatives are specified by...@>=
11291 if ( x1<0 ) if ( x2<0 ) if ( x3<0 ) goto DONE;
11292 if ( mp_ab_vs_cd(mp, y1,y3,y2,y2)==0 ) {
11293   @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11294     either |goto found| or |goto done|@>;
11295 }
11296 if ( y1<=0 ) {
11297   if ( y1<0 ) { y1=-y1; y2=-y2; y3=-y3; }
11298   else if ( y2>0 ){ y2=-y2; y3=-y3; };
11299 }
11300 @<Check the places where $B(y_1,y_2,y_3;t)=0$ to see if
11301   $B(x_1,x_2,x_3;t)\ge0$@>;
11302 DONE:
11303
11304 @ The quadratic polynomial $B(y_1,y_2,y_3;t)$ begins |>=0| and has at most
11305 two roots, because we know that it isn't identically zero.
11306
11307 It must be admitted that the |crossing_point| routine is not perfectly accurate;
11308 rounding errors might cause it to find a root when $y_1y_3>y_2^2$, or to
11309 miss the roots when $y_1y_3<y_2^2$. The rotation process is itself
11310 subject to rounding errors. Yet this code optimistically tries to
11311 do the right thing.
11312
11313 @d we_found_it { tt=(t+04000) / 010000; goto FOUND; }
11314
11315 @<Check the places where $B(y_1,y_2,y_3;t)=0$...@>=
11316 t=mp_crossing_point(mp, y1,y2,y3);
11317 if ( t>fraction_one ) goto DONE;
11318 y2=t_of_the_way(y2,y3);
11319 x1=t_of_the_way(x1,x2);
11320 x2=t_of_the_way(x2,x3);
11321 x1=t_of_the_way(x1,x2);
11322 if ( x1>=0 ) we_found_it;
11323 if ( y2>0 ) y2=0;
11324 tt=t; t=mp_crossing_point(mp, 0,-y2,-y3);
11325 if ( t>fraction_one ) goto DONE;
11326 x1=t_of_the_way(x1,x2);
11327 x2=t_of_the_way(x2,x3);
11328 if ( t_of_the_way(x1,x2)>=0 ) { 
11329   t=t_of_the_way(tt,fraction_one); we_found_it;
11330 }
11331
11332 @ @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11333     either |goto found| or |goto done|@>=
11334
11335   if ( mp_ab_vs_cd(mp, y1,y2,0,0)<0 ) {
11336     t=mp_make_fraction(mp, y1,y1-y2);
11337     x1=t_of_the_way(x1,x2);
11338     x2=t_of_the_way(x2,x3);
11339     if ( t_of_the_way(x1,x2)>=0 ) we_found_it;
11340   } else if ( y3==0 ) {
11341     if ( y1==0 ) {
11342       @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|@>;
11343     } else if ( x3>=0 ) {
11344       tt=unity; goto FOUND;
11345     }
11346   }
11347   goto DONE;
11348 }
11349
11350 @ At this point we know that the derivative of |y(t)| is identically zero,
11351 and that |x1<0|; but either |x2>=0| or |x3>=0|, so there's some hope of
11352 traveling east.
11353
11354 @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|...@>=
11355
11356   t=mp_crossing_point(mp, -x1,-x2,-x3);
11357   if ( t<=fraction_one ) we_found_it;
11358   if ( mp_ab_vs_cd(mp, x1,x3,x2,x2)<=0 ) { 
11359     t=mp_make_fraction(mp, x1,x1-x2); we_found_it;
11360   }
11361 }
11362
11363 @ The intersection of two cubics can be found by an interesting variant
11364 of the general bisection scheme described in the introduction to
11365 |crossing_point|.\
11366 Given $w(t)=B(w_0,w_1,w_2,w_3;t)$ and $z(t)=B(z_0,z_1,z_2,z_3;t)$,
11367 we wish to find a pair of times $(t_1,t_2)$ such that $w(t_1)=z(t_2)$,
11368 if an intersection exists. First we find the smallest rectangle that
11369 encloses the points $\{w_0,w_1,w_2,w_3\}$ and check that it overlaps
11370 the smallest rectangle that encloses
11371 $\{z_0,z_1,z_2,z_3\}$; if not, the cubics certainly don't intersect.
11372 But if the rectangles do overlap, we bisect the intervals, getting
11373 new cubics $w'$ and~$w''$, $z'$~and~$z''$; the intersection routine first
11374 tries for an intersection between $w'$ and~$z'$, then (if unsuccessful)
11375 between $w'$ and~$z''$, then (if still unsuccessful) between $w''$ and~$z'$,
11376 finally (if thrice unsuccessful) between $w''$ and~$z''$. After $l$~successful
11377 levels of bisection we will have determined the intersection times $t_1$
11378 and~$t_2$ to $l$~bits of accuracy.
11379
11380 \def\submin{_{\rm min}} \def\submax{_{\rm max}}
11381 As before, it is better to work with the numbers $W_k=2^l(w_k-w_{k-1})$
11382 and $Z_k=2^l(z_k-z_{k-1})$ rather than the coefficients $w_k$ and $z_k$
11383 themselves. We also need one other quantity, $\Delta=2^l(w_0-z_0)$,
11384 to determine when the enclosing rectangles overlap. Here's why:
11385 The $x$~coordinates of~$w(t)$ are between $u\submin$ and $u\submax$,
11386 and the $x$~coordinates of~$z(t)$ are between $x\submin$ and $x\submax$,
11387 if we write $w_k=(u_k,v_k)$ and $z_k=(x_k,y_k)$ and $u\submin=
11388 \min(u_0,u_1,u_2,u_3)$, etc. These intervals of $x$~coordinates
11389 overlap if and only if $u\submin\L x\submax$ and
11390 $x\submin\L u\submax$. Letting
11391 $$U\submin=\min(0,U_1,U_1+U_2,U_1+U_2+U_3),\;
11392   U\submax=\max(0,U_1,U_1+U_2,U_1+U_2+U_3),$$
11393 we have $u\submin=2^lu_0+U\submin$, etc.; the condition for overlap
11394 reduces to
11395 $$X\submin-U\submax\L 2^l(u_0-x_0)\L X\submax-U\submin.$$
11396 Thus we want to maintain the quantity $2^l(u_0-x_0)$; similarly,
11397 the quantity $2^l(v_0-y_0)$ accounts for the $y$~coordinates. The
11398 coordinates of $\Delta=2^l(w_0-z_0)$ must stay bounded as $l$ increases,
11399 because of the overlap condition; i.e., we know that $X\submin$,
11400 $X\submax$, and their relatives are bounded, hence $X\submax-
11401 U\submin$ and $X\submin-U\submax$ are bounded.
11402
11403 @ Incidentally, if the given cubics intersect more than once, the process
11404 just sketched will not necessarily find the lexicographically smallest pair
11405 $(t_1,t_2)$. The solution actually obtained will be smallest in ``shuffled
11406 order''; i.e., if $t_1=(.a_1a_2\ldots a_{16})_2$ and
11407 $t_2=(.b_1b_2\ldots b_{16})_2$, then we will minimize
11408 $a_1b_1a_2b_2\ldots a_{16}b_{16}$, not
11409 $a_1a_2\ldots a_{16}b_1b_2\ldots b_{16}$.
11410 Shuffled order agrees with lexicographic order if all pairs of solutions
11411 $(t_1,t_2)$ and $(t_1',t_2')$ have the property that $t_1<t_1'$ iff
11412 $t_2<t_2'$; but in general, lexicographic order can be quite different,
11413 and the bisection algorithm would be substantially less efficient if it were
11414 constrained by lexicographic order.
11415
11416 For example, suppose that an overlap has been found for $l=3$ and
11417 $(t_1,t_2)= (.101,.011)$ in binary, but that no overlap is produced by
11418 either of the alternatives $(.1010,.0110)$, $(.1010,.0111)$ at level~4.
11419 Then there is probably an intersection in one of the subintervals
11420 $(.1011,.011x)$; but lexicographic order would require us to explore
11421 $(.1010,.1xxx)$ and $(.1011,.00xx)$ and $(.1011,.010x)$ first. We wouldn't
11422 want to store all of the subdivision data for the second path, so the
11423 subdivisions would have to be regenerated many times. Such inefficiencies
11424 would be associated with every `1' in the binary representation of~$t_1$.
11425
11426 @ The subdivision process introduces rounding errors, hence we need to
11427 make a more liberal test for overlap. It is not hard to show that the
11428 computed values of $U_i$ differ from the truth by at most~$l$, on
11429 level~$l$, hence $U\submin$ and $U\submax$ will be at most $3l$ in error.
11430 If $\beta$ is an upper bound on the absolute error in the computed
11431 components of $\Delta=(|delx|,|dely|)$ on level~$l$, we will replace
11432 the test `$X\submin-U\submax\L|delx|$' by the more liberal test
11433 `$X\submin-U\submax\L|delx|+|tol|$', where $|tol|=6l+\beta$.
11434
11435 More accuracy is obtained if we try the algorithm first with |tol=0|;
11436 the more liberal tolerance is used only if an exact approach fails.
11437 It is convenient to do this double-take by letting `3' in the preceding
11438 paragraph be a parameter, which is first 0, then 3.
11439
11440 @<Glob...@>=
11441 unsigned int tol_step; /* either 0 or 3, usually */
11442
11443 @ We shall use an explicit stack to implement the recursive bisection
11444 method described above. The |bisect_stack| array will contain numerous 5-word
11445 packets like $(U_1,U_2,U_3,U\submin,U\submax)$, as well as 20-word packets
11446 comprising the 5-word packets for $U$, $V$, $X$, and~$Y$.
11447
11448 The following macros define the allocation of stack positions to
11449 the quantities needed for bisection-intersection.
11450
11451 @d stack_1(A) mp->bisect_stack[(A)] /* $U_1$, $V_1$, $X_1$, or $Y_1$ */
11452 @d stack_2(A) mp->bisect_stack[(A)+1] /* $U_2$, $V_2$, $X_2$, or $Y_2$ */
11453 @d stack_3(A) mp->bisect_stack[(A)+2] /* $U_3$, $V_3$, $X_3$, or $Y_3$ */
11454 @d stack_min(A) mp->bisect_stack[(A)+3]
11455   /* $U\submin$, $V\submin$, $X\submin$, or $Y\submin$ */
11456 @d stack_max(A) mp->bisect_stack[(A)+4]
11457   /* $U\submax$, $V\submax$, $X\submax$, or $Y\submax$ */
11458 @d int_packets 20 /* number of words to represent $U_k$, $V_k$, $X_k$, and $Y_k$ */
11459 @#
11460 @d u_packet(A) ((A)-5)
11461 @d v_packet(A) ((A)-10)
11462 @d x_packet(A) ((A)-15)
11463 @d y_packet(A) ((A)-20)
11464 @d l_packets (mp->bisect_ptr-int_packets)
11465 @d r_packets mp->bisect_ptr
11466 @d ul_packet u_packet(l_packets) /* base of $U'_k$ variables */
11467 @d vl_packet v_packet(l_packets) /* base of $V'_k$ variables */
11468 @d xl_packet x_packet(l_packets) /* base of $X'_k$ variables */
11469 @d yl_packet y_packet(l_packets) /* base of $Y'_k$ variables */
11470 @d ur_packet u_packet(r_packets) /* base of $U''_k$ variables */
11471 @d vr_packet v_packet(r_packets) /* base of $V''_k$ variables */
11472 @d xr_packet x_packet(r_packets) /* base of $X''_k$ variables */
11473 @d yr_packet y_packet(r_packets) /* base of $Y''_k$ variables */
11474 @#
11475 @d u1l stack_1(ul_packet) /* $U'_1$ */
11476 @d u2l stack_2(ul_packet) /* $U'_2$ */
11477 @d u3l stack_3(ul_packet) /* $U'_3$ */
11478 @d v1l stack_1(vl_packet) /* $V'_1$ */
11479 @d v2l stack_2(vl_packet) /* $V'_2$ */
11480 @d v3l stack_3(vl_packet) /* $V'_3$ */
11481 @d x1l stack_1(xl_packet) /* $X'_1$ */
11482 @d x2l stack_2(xl_packet) /* $X'_2$ */
11483 @d x3l stack_3(xl_packet) /* $X'_3$ */
11484 @d y1l stack_1(yl_packet) /* $Y'_1$ */
11485 @d y2l stack_2(yl_packet) /* $Y'_2$ */
11486 @d y3l stack_3(yl_packet) /* $Y'_3$ */
11487 @d u1r stack_1(ur_packet) /* $U''_1$ */
11488 @d u2r stack_2(ur_packet) /* $U''_2$ */
11489 @d u3r stack_3(ur_packet) /* $U''_3$ */
11490 @d v1r stack_1(vr_packet) /* $V''_1$ */
11491 @d v2r stack_2(vr_packet) /* $V''_2$ */
11492 @d v3r stack_3(vr_packet) /* $V''_3$ */
11493 @d x1r stack_1(xr_packet) /* $X''_1$ */
11494 @d x2r stack_2(xr_packet) /* $X''_2$ */
11495 @d x3r stack_3(xr_packet) /* $X''_3$ */
11496 @d y1r stack_1(yr_packet) /* $Y''_1$ */
11497 @d y2r stack_2(yr_packet) /* $Y''_2$ */
11498 @d y3r stack_3(yr_packet) /* $Y''_3$ */
11499 @#
11500 @d stack_dx mp->bisect_stack[mp->bisect_ptr] /* stacked value of |delx| */
11501 @d stack_dy mp->bisect_stack[mp->bisect_ptr+1] /* stacked value of |dely| */
11502 @d stack_tol mp->bisect_stack[mp->bisect_ptr+2] /* stacked value of |tol| */
11503 @d stack_uv mp->bisect_stack[mp->bisect_ptr+3] /* stacked value of |uv| */
11504 @d stack_xy mp->bisect_stack[mp->bisect_ptr+4] /* stacked value of |xy| */
11505 @d int_increment (int_packets+int_packets+5) /* number of stack words per level */
11506
11507 @<Glob...@>=
11508 integer *bisect_stack;
11509 unsigned int bisect_ptr;
11510
11511 @ @<Allocate or initialize ...@>=
11512 mp->bisect_stack = xmalloc((bistack_size+1),sizeof(integer));
11513
11514 @ @<Dealloc variables@>=
11515 xfree(mp->bisect_stack);
11516
11517 @ @<Check the ``constant''...@>=
11518 if ( int_packets+17*int_increment>bistack_size ) mp->bad=19;
11519
11520 @ Computation of the min and max is a tedious but fairly fast sequence of
11521 instructions; exactly four comparisons are made in each branch.
11522
11523 @d set_min_max(A) 
11524   if ( stack_1((A))<0 ) {
11525     if ( stack_3((A))>=0 ) {
11526       if ( stack_2((A))<0 ) stack_min((A))=stack_1((A))+stack_2((A));
11527       else stack_min((A))=stack_1((A));
11528       stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11529       if ( stack_max((A))<0 ) stack_max((A))=0;
11530     } else { 
11531       stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11532       if ( stack_min((A))>stack_1((A)) ) stack_min((A))=stack_1((A));
11533       stack_max((A))=stack_1((A))+stack_2((A));
11534       if ( stack_max((A))<0 ) stack_max((A))=0;
11535     }
11536   } else if ( stack_3((A))<=0 ) {
11537     if ( stack_2((A))>0 ) stack_max((A))=stack_1((A))+stack_2((A));
11538     else stack_max((A))=stack_1((A));
11539     stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11540     if ( stack_min((A))>0 ) stack_min((A))=0;
11541   } else  { 
11542     stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11543     if ( stack_max((A))<stack_1((A)) ) stack_max((A))=stack_1((A));
11544     stack_min((A))=stack_1((A))+stack_2((A));
11545     if ( stack_min((A))>0 ) stack_min((A))=0;
11546   }
11547
11548 @ It's convenient to keep the current values of $l$, $t_1$, and $t_2$ in
11549 the integer form $2^l+2^lt_1$ and $2^l+2^lt_2$. The |cubic_intersection|
11550 routine uses global variables |cur_t| and |cur_tt| for this purpose;
11551 after successful completion, |cur_t| and |cur_tt| will contain |unity|
11552 plus the |scaled| values of $t_1$ and~$t_2$.
11553
11554 The values of |cur_t| and |cur_tt| will be set to zero if |cubic_intersection|
11555 finds no intersection. The routine gives up and gives an approximate answer
11556 if it has backtracked
11557 more than 5000 times (otherwise there are cases where several minutes
11558 of fruitless computation would be possible).
11559
11560 @d max_patience 5000
11561
11562 @<Glob...@>=
11563 integer cur_t;integer cur_tt; /* controls and results of |cubic_intersection| */
11564 integer time_to_go; /* this many backtracks before giving up */
11565 integer max_t; /* maximum of $2^{l+1}$ so far achieved */
11566
11567 @ The given cubics $B(w_0,w_1,w_2,w_3;t)$ and
11568 $B(z_0,z_1,z_2,z_3;t)$ are specified in adjacent knot nodes |(p,link(p))|
11569 and |(pp,link(pp))|, respectively.
11570
11571 @c void mp_cubic_intersection (MP mp,pointer p, pointer pp) {
11572   pointer q,qq; /* |link(p)|, |link(pp)| */
11573   mp->time_to_go=max_patience; mp->max_t=2;
11574   @<Initialize for intersections at level zero@>;
11575 CONTINUE:
11576   while (1) { 
11577     if ( mp->delx-mp->tol<=stack_max(x_packet(mp->xy))-stack_min(u_packet(mp->uv)))
11578     if ( mp->delx+mp->tol>=stack_min(x_packet(mp->xy))-stack_max(u_packet(mp->uv)))
11579     if ( mp->dely-mp->tol<=stack_max(y_packet(mp->xy))-stack_min(v_packet(mp->uv)))
11580     if ( mp->dely+mp->tol>=stack_min(y_packet(mp->xy))-stack_max(v_packet(mp->uv))) 
11581     { 
11582       if ( mp->cur_t>=mp->max_t ){ 
11583         if ( mp->max_t==two ) { /* we've done 17 bisections */ 
11584            mp->cur_t=halfp(mp->cur_t+1); mp->cur_tt=halfp(mp->cur_tt+1); return;
11585         }
11586         mp->max_t+=mp->max_t; mp->appr_t=mp->cur_t; mp->appr_tt=mp->cur_tt;
11587       }
11588       @<Subdivide for a new level of intersection@>;
11589       goto CONTINUE;
11590     }
11591     if ( mp->time_to_go>0 ) {
11592       decr(mp->time_to_go);
11593     } else { 
11594       while ( mp->appr_t<unity ) { 
11595         mp->appr_t+=mp->appr_t; mp->appr_tt+=mp->appr_tt;
11596       }
11597       mp->cur_t=mp->appr_t; mp->cur_tt=mp->appr_tt; return;
11598     }
11599     @<Advance to the next pair |(cur_t,cur_tt)|@>;
11600   }
11601 }
11602
11603 @ The following variables are global, although they are used only by
11604 |cubic_intersection|, because it is necessary on some machines to
11605 split |cubic_intersection| up into two procedures.
11606
11607 @<Glob...@>=
11608 integer delx;integer dely; /* the components of $\Delta=2^l(w_0-z_0)$ */
11609 integer tol; /* bound on the uncertainly in the overlap test */
11610 unsigned int uv;
11611 unsigned int xy; /* pointers to the current packets of interest */
11612 integer three_l; /* |tol_step| times the bisection level */
11613 integer appr_t;integer appr_tt; /* best approximations known to the answers */
11614
11615 @ We shall assume that the coordinates are sufficiently non-extreme that
11616 integer overflow will not occur.
11617
11618 @<Initialize for intersections at level zero@>=
11619 q=link(p); qq=link(pp); mp->bisect_ptr=int_packets;
11620 u1r=right_x(p)-x_coord(p); u2r=left_x(q)-right_x(p);
11621 u3r=x_coord(q)-left_x(q); set_min_max(ur_packet);
11622 v1r=right_y(p)-y_coord(p); v2r=left_y(q)-right_y(p);
11623 v3r=y_coord(q)-left_y(q); set_min_max(vr_packet);
11624 x1r=right_x(pp)-x_coord(pp); x2r=left_x(qq)-right_x(pp);
11625 x3r=x_coord(qq)-left_x(qq); set_min_max(xr_packet);
11626 y1r=right_y(pp)-y_coord(pp); y2r=left_y(qq)-right_y(pp);
11627 y3r=y_coord(qq)-left_y(qq); set_min_max(yr_packet);
11628 mp->delx=x_coord(p)-x_coord(pp); mp->dely=y_coord(p)-y_coord(pp);
11629 mp->tol=0; mp->uv=r_packets; mp->xy=r_packets; 
11630 mp->three_l=0; mp->cur_t=1; mp->cur_tt=1
11631
11632 @ @<Subdivide for a new level of intersection@>=
11633 stack_dx=mp->delx; stack_dy=mp->dely; stack_tol=mp->tol; 
11634 stack_uv=mp->uv; stack_xy=mp->xy;
11635 mp->bisect_ptr=mp->bisect_ptr+int_increment;
11636 mp->cur_t+=mp->cur_t; mp->cur_tt+=mp->cur_tt;
11637 u1l=stack_1(u_packet(mp->uv)); u3r=stack_3(u_packet(mp->uv));
11638 u2l=half(u1l+stack_2(u_packet(mp->uv)));
11639 u2r=half(u3r+stack_2(u_packet(mp->uv)));
11640 u3l=half(u2l+u2r); u1r=u3l;
11641 set_min_max(ul_packet); set_min_max(ur_packet);
11642 v1l=stack_1(v_packet(mp->uv)); v3r=stack_3(v_packet(mp->uv));
11643 v2l=half(v1l+stack_2(v_packet(mp->uv)));
11644 v2r=half(v3r+stack_2(v_packet(mp->uv)));
11645 v3l=half(v2l+v2r); v1r=v3l;
11646 set_min_max(vl_packet); set_min_max(vr_packet);
11647 x1l=stack_1(x_packet(mp->xy)); x3r=stack_3(x_packet(mp->xy));
11648 x2l=half(x1l+stack_2(x_packet(mp->xy)));
11649 x2r=half(x3r+stack_2(x_packet(mp->xy)));
11650 x3l=half(x2l+x2r); x1r=x3l;
11651 set_min_max(xl_packet); set_min_max(xr_packet);
11652 y1l=stack_1(y_packet(mp->xy)); y3r=stack_3(y_packet(mp->xy));
11653 y2l=half(y1l+stack_2(y_packet(mp->xy)));
11654 y2r=half(y3r+stack_2(y_packet(mp->xy)));
11655 y3l=half(y2l+y2r); y1r=y3l;
11656 set_min_max(yl_packet); set_min_max(yr_packet);
11657 mp->uv=l_packets; mp->xy=l_packets;
11658 mp->delx+=mp->delx; mp->dely+=mp->dely;
11659 mp->tol=mp->tol-mp->three_l+mp->tol_step; 
11660 mp->tol+=mp->tol; mp->three_l=mp->three_l+mp->tol_step
11661
11662 @ @<Advance to the next pair |(cur_t,cur_tt)|@>=
11663 NOT_FOUND: 
11664 if ( odd(mp->cur_tt) ) {
11665   if ( odd(mp->cur_t) ) {
11666      @<Descend to the previous level and |goto not_found|@>;
11667   } else { 
11668     incr(mp->cur_t);
11669     mp->delx=mp->delx+stack_1(u_packet(mp->uv))+stack_2(u_packet(mp->uv))
11670       +stack_3(u_packet(mp->uv));
11671     mp->dely=mp->dely+stack_1(v_packet(mp->uv))+stack_2(v_packet(mp->uv))
11672       +stack_3(v_packet(mp->uv));
11673     mp->uv=mp->uv+int_packets; /* switch from |l_packet| to |r_packet| */
11674     decr(mp->cur_tt); mp->xy=mp->xy-int_packets; 
11675          /* switch from |r_packet| to |l_packet| */
11676     mp->delx=mp->delx+stack_1(x_packet(mp->xy))+stack_2(x_packet(mp->xy))
11677       +stack_3(x_packet(mp->xy));
11678     mp->dely=mp->dely+stack_1(y_packet(mp->xy))+stack_2(y_packet(mp->xy))
11679       +stack_3(y_packet(mp->xy));
11680   }
11681 } else { 
11682   incr(mp->cur_tt); mp->tol=mp->tol+mp->three_l;
11683   mp->delx=mp->delx-stack_1(x_packet(mp->xy))-stack_2(x_packet(mp->xy))
11684     -stack_3(x_packet(mp->xy));
11685   mp->dely=mp->dely-stack_1(y_packet(mp->xy))-stack_2(y_packet(mp->xy))
11686     -stack_3(y_packet(mp->xy));
11687   mp->xy=mp->xy+int_packets; /* switch from |l_packet| to |r_packet| */
11688 }
11689
11690 @ @<Descend to the previous level...@>=
11691
11692   mp->cur_t=halfp(mp->cur_t); mp->cur_tt=halfp(mp->cur_tt);
11693   if ( mp->cur_t==0 ) return;
11694   mp->bisect_ptr=mp->bisect_ptr-int_increment; 
11695   mp->three_l=mp->three_l-mp->tol_step;
11696   mp->delx=stack_dx; mp->dely=stack_dy; mp->tol=stack_tol; 
11697   mp->uv=stack_uv; mp->xy=stack_xy;
11698   goto NOT_FOUND;
11699 }
11700
11701 @ The |path_intersection| procedure is much simpler.
11702 It invokes |cubic_intersection| in lexicographic order until finding a
11703 pair of cubics that intersect. The final intersection times are placed in
11704 |cur_t| and~|cur_tt|.
11705
11706 @c void mp_path_intersection (MP mp,pointer h, pointer hh) {
11707   pointer p,pp; /* link registers that traverse the given paths */
11708   integer n,nn; /* integer parts of intersection times, minus |unity| */
11709   @<Change one-point paths into dead cycles@>;
11710   mp->tol_step=0;
11711   do {  
11712     n=-unity; p=h;
11713     do {  
11714       if ( right_type(p)!=mp_endpoint ) { 
11715         nn=-unity; pp=hh;
11716         do {  
11717           if ( right_type(pp)!=mp_endpoint )  { 
11718             mp_cubic_intersection(mp, p,pp);
11719             if ( mp->cur_t>0 ) { 
11720               mp->cur_t=mp->cur_t+n; mp->cur_tt=mp->cur_tt+nn; 
11721               return;
11722             }
11723           }
11724           nn=nn+unity; pp=link(pp);
11725         } while (pp!=hh);
11726       }
11727       n=n+unity; p=link(p);
11728     } while (p!=h);
11729     mp->tol_step=mp->tol_step+3;
11730   } while (mp->tol_step<=3);
11731   mp->cur_t=-unity; mp->cur_tt=-unity;
11732 }
11733
11734 @ @<Change one-point paths...@>=
11735 if ( right_type(h)==mp_endpoint ) {
11736   right_x(h)=x_coord(h); left_x(h)=x_coord(h);
11737   right_y(h)=y_coord(h); left_y(h)=y_coord(h); right_type(h)=mp_explicit;
11738 }
11739 if ( right_type(hh)==mp_endpoint ) {
11740   right_x(hh)=x_coord(hh); left_x(hh)=x_coord(hh);
11741   right_y(hh)=y_coord(hh); left_y(hh)=y_coord(hh); right_type(hh)=mp_explicit;
11742 }
11743
11744 @* \[24] Dynamic linear equations.
11745 \MP\ users define variables implicitly by stating equations that should be
11746 satisfied; the computer is supposed to be smart enough to solve those equations.
11747 And indeed, the computer tries valiantly to do so, by distinguishing five
11748 different types of numeric values:
11749
11750 \smallskip\hang
11751 |type(p)=mp_known| is the nice case, when |value(p)| is the |scaled| value
11752 of the variable whose address is~|p|.
11753
11754 \smallskip\hang
11755 |type(p)=mp_dependent| means that |value(p)| is not present, but |dep_list(p)|
11756 points to a {\sl dependency list\/} that expresses the value of variable~|p|
11757 as a |scaled| number plus a sum of independent variables with |fraction|
11758 coefficients.
11759
11760 \smallskip\hang
11761 |type(p)=mp_independent| means that |value(p)=64s+m|, where |s>0| is a ``serial
11762 number'' reflecting the time this variable was first used in an equation;
11763 also |0<=m<64|, and each dependent variable
11764 that refers to this one is actually referring to the future value of
11765 this variable times~$2^m$. (Usually |m=0|, but higher degrees of
11766 scaling are sometimes needed to keep the coefficients in dependency lists
11767 from getting too large. The value of~|m| will always be even.)
11768
11769 \smallskip\hang
11770 |type(p)=mp_numeric_type| means that variable |p| hasn't appeared in an
11771 equation before, but it has been explicitly declared to be numeric.
11772
11773 \smallskip\hang
11774 |type(p)=undefined| means that variable |p| hasn't appeared before.
11775
11776 \smallskip\noindent
11777 We have actually discussed these five types in the reverse order of their
11778 history during a computation: Once |known|, a variable never again
11779 becomes |dependent|; once |dependent|, it almost never again becomes
11780 |mp_independent|; once |mp_independent|, it never again becomes |mp_numeric_type|;
11781 and once |mp_numeric_type|, it never again becomes |undefined| (except
11782 of course when the user specifically decides to scrap the old value
11783 and start again). A backward step may, however, take place: Sometimes
11784 a |dependent| variable becomes |mp_independent| again, when one of the
11785 independent variables it depends on is reverting to |undefined|.
11786
11787
11788 The next patch detects overflow of independent-variable serial
11789 numbers. Diagnosed and patched by Thorsten Dahlheimer.
11790
11791 @d s_scale 64 /* the serial numbers are multiplied by this factor */
11792 @d max_indep_vars 0177777777 /* $2^{25}-1$ */
11793 @d max_serial_no 017777777700 /* |max_indep_vars*s_scale| */
11794 @d new_indep(A)  /* create a new independent variable */
11795   { if ( mp->serial_no==max_serial_no )
11796     mp_fatal_error(mp, "variable instance identifiers exhausted");
11797   type((A))=mp_independent; mp->serial_no=mp->serial_no+s_scale;
11798   value((A))=mp->serial_no;
11799   }
11800
11801 @<Glob...@>=
11802 integer serial_no; /* the most recent serial number, times |s_scale| */
11803
11804 @ @<Make variable |q+s| newly independent@>=new_indep(q+s)
11805
11806 @ But how are dependency lists represented? It's simple: The linear combination
11807 $\alpha_1v_1+\cdots+\alpha_kv_k+\beta$ appears in |k+1| value nodes. If
11808 |q=dep_list(p)| points to this list, and if |k>0|, then |value(q)=
11809 @t$\alpha_1$@>| (which is a |fraction|); |info(q)| points to the location
11810 of $\alpha_1$; and |link(p)| points to the dependency list
11811 $\alpha_2v_2+\cdots+\alpha_kv_k+\beta$. On the other hand if |k=0|,
11812 then |value(q)=@t$\beta$@>| (which is |scaled|) and |info(q)=null|.
11813 The independent variables $v_1$, \dots,~$v_k$ have been sorted so that
11814 they appear in decreasing order of their |value| fields (i.e., of
11815 their serial numbers). \ (It is convenient to use decreasing order,
11816 since |value(null)=0|. If the independent variables were not sorted by
11817 serial number but by some other criterion, such as their location in |mem|,
11818 the equation-solving mechanism would be too system-dependent, because
11819 the ordering can affect the computed results.)
11820
11821 The |link| field in the node that contains the constant term $\beta$ is
11822 called the {\sl final link\/} of the dependency list. \MP\ maintains
11823 a doubly-linked master list of all dependency lists, in terms of a permanently
11824 allocated node
11825 in |mem| called |dep_head|. If there are no dependencies, we have
11826 |link(dep_head)=dep_head| and |prev_dep(dep_head)=dep_head|;
11827 otherwise |link(dep_head)| points to the first dependent variable, say~|p|,
11828 and |prev_dep(p)=dep_head|. We have |type(p)=mp_dependent|, and |dep_list(p)|
11829 points to its dependency list. If the final link of that dependency list
11830 occurs in location~|q|, then |link(q)| points to the next dependent
11831 variable (say~|r|); and we have |prev_dep(r)=q|, etc.
11832
11833 @d dep_list(A) link(value_loc((A)))
11834   /* half of the |value| field in a |dependent| variable */
11835 @d prev_dep(A) info(value_loc((A)))
11836   /* the other half; makes a doubly linked list */
11837 @d dep_node_size 2 /* the number of words per dependency node */
11838
11839 @<Initialize table entries...@>= mp->serial_no=0;
11840 link(dep_head)=dep_head; prev_dep(dep_head)=dep_head;
11841 info(dep_head)=null; dep_list(dep_head)=null;
11842
11843 @ Actually the description above contains a little white lie. There's
11844 another kind of variable called |mp_proto_dependent|, which is
11845 just like a |dependent| one except that the $\alpha$ coefficients
11846 in its dependency list are |scaled| instead of being fractions.
11847 Proto-dependency lists are mixed with dependency lists in the
11848 nodes reachable from |dep_head|.
11849
11850 @ Here is a procedure that prints a dependency list in symbolic form.
11851 The second parameter should be either |dependent| or |mp_proto_dependent|,
11852 to indicate the scaling of the coefficients.
11853
11854 @<Declare subroutines for printing expressions@>=
11855 void mp_print_dependency (MP mp,pointer p, small_number t) {
11856   integer v; /* a coefficient */
11857   pointer pp,q; /* for list manipulation */
11858   pp=p;
11859   while (1) { 
11860     v=abs(value(p)); q=info(p);
11861     if ( q==null ) { /* the constant term */
11862       if ( (v!=0)||(p==pp) ) {
11863          if ( value(p)>0 ) if ( p!=pp ) mp_print_char(mp, '+');
11864          mp_print_scaled(mp, value(p));
11865       }
11866       return;
11867     }
11868     @<Print the coefficient, unless it's $\pm1.0$@>;
11869     if ( type(q)!=mp_independent ) mp_confusion(mp, "dep");
11870 @:this can't happen dep}{\quad dep@>
11871     mp_print_variable_name(mp, q); v=value(q) % s_scale;
11872     while ( v>0 ) { mp_print(mp, "*4"); v=v-2; }
11873     p=link(p);
11874   }
11875 }
11876
11877 @ @<Print the coefficient, unless it's $\pm1.0$@>=
11878 if ( value(p)<0 ) mp_print_char(mp, '-');
11879 else if ( p!=pp ) mp_print_char(mp, '+');
11880 if ( t==mp_dependent ) v=mp_round_fraction(mp, v);
11881 if ( v!=unity ) mp_print_scaled(mp, v)
11882
11883 @ The maximum absolute value of a coefficient in a given dependency list
11884 is returned by the following simple function.
11885
11886 @c fraction mp_max_coef (MP mp,pointer p) {
11887   fraction x; /* the maximum so far */
11888   x=0;
11889   while ( info(p)!=null ) {
11890     if ( abs(value(p))>x ) x=abs(value(p));
11891     p=link(p);
11892   }
11893   return x;
11894 }
11895
11896 @ One of the main operations needed on dependency lists is to add a multiple
11897 of one list to the other; we call this |p_plus_fq|, where |p| and~|q| point
11898 to dependency lists and |f| is a fraction.
11899
11900 If the coefficient of any independent variable becomes |coef_bound| or
11901 more, in absolute value, this procedure changes the type of that variable
11902 to `|independent_needing_fix|', and sets the global variable |fix_needed|
11903 to~|true|. The value of $|coef_bound|=\mu$ is chosen so that
11904 $\mu^2+\mu<8$; this means that the numbers we deal with won't
11905 get too large. (Instead of the ``optimum'' $\mu=(\sqrt{33}-1)/2\approx
11906 2.3723$, the safer value 7/3 is taken as the threshold.)
11907
11908 The changes mentioned in the preceding paragraph are actually done only if
11909 the global variable |watch_coefs| is |true|. But it usually is; in fact,
11910 it is |false| only when \MP\ is making a dependency list that will soon
11911 be equated to zero.
11912
11913 Several procedures that act on dependency lists, including |p_plus_fq|,
11914 set the global variable |dep_final| to the final (constant term) node of
11915 the dependency list that they produce.
11916
11917 @d coef_bound 04525252525 /* |fraction| approximation to 7/3 */
11918 @d independent_needing_fix 0
11919
11920 @<Glob...@>=
11921 boolean fix_needed; /* does at least one |independent| variable need scaling? */
11922 boolean watch_coefs; /* should we scale coefficients that exceed |coef_bound|? */
11923 pointer dep_final; /* location of the constant term and final link */
11924
11925 @ @<Set init...@>=
11926 mp->fix_needed=false; mp->watch_coefs=true;
11927
11928 @ The |p_plus_fq| procedure has a fourth parameter, |t|, that should be
11929 set to |mp_proto_dependent| if |p| is a proto-dependency list. In this
11930 case |f| will be |scaled|, not a |fraction|. Similarly, the fifth parameter~|tt|
11931 should be |mp_proto_dependent| if |q| is a proto-dependency list.
11932
11933 List |q| is unchanged by the operation; but list |p| is totally destroyed.
11934
11935 The final link of the dependency list or proto-dependency list returned
11936 by |p_plus_fq| is the same as the original final link of~|p|. Indeed, the
11937 constant term of the result will be located in the same |mem| location
11938 as the original constant term of~|p|.
11939
11940 Coefficients of the result are assumed to be zero if they are less than
11941 a certain threshold. This compensates for inevitable rounding errors,
11942 and tends to make more variables `|known|'. The threshold is approximately
11943 $10^{-5}$ in the case of normal dependency lists, $10^{-4}$ for
11944 proto-dependencies.
11945
11946 @d fraction_threshold 2685 /* a |fraction| coefficient less than this is zeroed */
11947 @d half_fraction_threshold 1342 /* half of |fraction_threshold| */
11948 @d scaled_threshold 8 /* a |scaled| coefficient less than this is zeroed */
11949 @d half_scaled_threshold 4 /* half of |scaled_threshold| */
11950
11951 @<Declare basic dependency-list subroutines@>=
11952 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
11953                       pointer q, small_number t, small_number tt) ;
11954
11955 @ @c
11956 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
11957                       pointer q, small_number t, small_number tt) {
11958   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
11959   pointer r,s; /* for list manipulation */
11960   integer mp_threshold; /* defines a neighborhood of zero */
11961   integer v; /* temporary register */
11962   if ( t==mp_dependent ) mp_threshold=fraction_threshold;
11963   else mp_threshold=scaled_threshold;
11964   r=temp_head; pp=info(p); qq=info(q);
11965   while (1) {
11966     if ( pp==qq ) {
11967       if ( pp==null ) {
11968        break;
11969       } else {
11970         @<Contribute a term from |p|, plus |f| times the
11971           corresponding term from |q|@>
11972       }
11973     } else if ( value(pp)<value(qq) ) {
11974       @<Contribute a term from |q|, multiplied by~|f|@>
11975     } else { 
11976      link(r)=p; r=p; p=link(p); pp=info(p);
11977     }
11978   }
11979   if ( t==mp_dependent )
11980     value(p)=mp_slow_add(mp, value(p),mp_take_fraction(mp, value(q),f));
11981   else  
11982     value(p)=mp_slow_add(mp, value(p),mp_take_scaled(mp, value(q),f));
11983   link(r)=p; mp->dep_final=p; 
11984   return link(temp_head);
11985 }
11986
11987 @ @<Contribute a term from |p|, plus |f|...@>=
11988
11989   if ( tt==mp_dependent ) v=value(p)+mp_take_fraction(mp, f,value(q));
11990   else v=value(p)+mp_take_scaled(mp, f,value(q));
11991   value(p)=v; s=p; p=link(p);
11992   if ( abs(v)<mp_threshold ) {
11993     mp_free_node(mp, s,dep_node_size);
11994   } else {
11995     if ( (abs(v)>=coef_bound)  && mp->watch_coefs ) { 
11996       type(qq)=independent_needing_fix; mp->fix_needed=true;
11997     }
11998     link(r)=s; r=s;
11999   };
12000   pp=info(p); q=link(q); qq=info(q);
12001 }
12002
12003 @ @<Contribute a term from |q|, multiplied by~|f|@>=
12004
12005   if ( tt==mp_dependent ) v=mp_take_fraction(mp, f,value(q));
12006   else v=mp_take_scaled(mp, f,value(q));
12007   if ( abs(v)>halfp(mp_threshold) ) { 
12008     s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=v;
12009     if ( (abs(v)>=coef_bound) && mp->watch_coefs ) { 
12010       type(qq)=independent_needing_fix; mp->fix_needed=true;
12011     }
12012     link(r)=s; r=s;
12013   }
12014   q=link(q); qq=info(q);
12015 }
12016
12017 @ It is convenient to have another subroutine for the special case
12018 of |p_plus_fq| when |f=1.0|. In this routine lists |p| and |q| are
12019 both of the same type~|t| (either |dependent| or |mp_proto_dependent|).
12020
12021 @c pointer mp_p_plus_q (MP mp,pointer p, pointer q, small_number t) {
12022   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
12023   pointer r,s; /* for list manipulation */
12024   integer mp_threshold; /* defines a neighborhood of zero */
12025   integer v; /* temporary register */
12026   if ( t==mp_dependent ) mp_threshold=fraction_threshold;
12027   else mp_threshold=scaled_threshold;
12028   r=temp_head; pp=info(p); qq=info(q);
12029   while (1) {
12030     if ( pp==qq ) {
12031       if ( pp==null ) {
12032         break;
12033       } else {
12034         @<Contribute a term from |p|, plus the
12035           corresponding term from |q|@>
12036       }
12037     } else if ( value(pp)<value(qq) ) {
12038       s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=value(q);
12039       q=link(q); qq=info(q); link(r)=s; r=s;
12040     } else { 
12041       link(r)=p; r=p; p=link(p); pp=info(p);
12042     }
12043   }
12044   value(p)=mp_slow_add(mp, value(p),value(q));
12045   link(r)=p; mp->dep_final=p; 
12046   return link(temp_head);
12047 }
12048
12049 @ @<Contribute a term from |p|, plus the...@>=
12050
12051   v=value(p)+value(q);
12052   value(p)=v; s=p; p=link(p); pp=info(p);
12053   if ( abs(v)<mp_threshold ) {
12054     mp_free_node(mp, s,dep_node_size);
12055   } else { 
12056     if ( (abs(v)>=coef_bound ) && mp->watch_coefs ) {
12057       type(qq)=independent_needing_fix; mp->fix_needed=true;
12058     }
12059     link(r)=s; r=s;
12060   }
12061   q=link(q); qq=info(q);
12062 }
12063
12064 @ A somewhat simpler routine will multiply a dependency list
12065 by a given constant~|v|. The constant is either a |fraction| less than
12066 |fraction_one|, or it is |scaled|. In the latter case we might be forced to
12067 convert a dependency list to a proto-dependency list.
12068 Parameters |t0| and |t1| are the list types before and after;
12069 they should agree unless |t0=mp_dependent| and |t1=mp_proto_dependent|
12070 and |v_is_scaled=true|.
12071
12072 @c pointer mp_p_times_v (MP mp,pointer p, integer v, small_number t0,
12073                          small_number t1, boolean v_is_scaled) {
12074   pointer r,s; /* for list manipulation */
12075   integer w; /* tentative coefficient */
12076   integer mp_threshold;
12077   boolean scaling_down;
12078   if ( t0!=t1 ) scaling_down=true; else scaling_down=! v_is_scaled;
12079   if ( t1==mp_dependent ) mp_threshold=half_fraction_threshold;
12080   else mp_threshold=half_scaled_threshold;
12081   r=temp_head;
12082   while ( info(p)!=null ) {    
12083     if ( scaling_down ) w=mp_take_fraction(mp, v,value(p));
12084     else w=mp_take_scaled(mp, v,value(p));
12085     if ( abs(w)<=mp_threshold ) { 
12086       s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
12087     } else {
12088       if ( abs(w)>=coef_bound ) { 
12089         mp->fix_needed=true; type(info(p))=independent_needing_fix;
12090       }
12091       link(r)=p; r=p; value(p)=w; p=link(p);
12092     }
12093   }
12094   link(r)=p;
12095   if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
12096   else value(p)=mp_take_fraction(mp, value(p),v);
12097   return link(temp_head);
12098 };
12099
12100 @ Similarly, we sometimes need to divide a dependency list
12101 by a given |scaled| constant.
12102
12103 @<Declare basic dependency-list subroutines@>=
12104 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number 
12105   t0, small_number t1) ;
12106
12107 @ @c
12108 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number 
12109   t0, small_number t1) {
12110   pointer r,s; /* for list manipulation */
12111   integer w; /* tentative coefficient */
12112   integer mp_threshold;
12113   boolean scaling_down;
12114   if ( t0!=t1 ) scaling_down=true; else scaling_down=false;
12115   if ( t1==mp_dependent ) mp_threshold=half_fraction_threshold;
12116   else mp_threshold=half_scaled_threshold;
12117   r=temp_head;
12118   while ( info( p)!=null ) {
12119     if ( scaling_down ) {
12120       if ( abs(v)<02000000 ) w=mp_make_scaled(mp, value(p),v*010000);
12121       else w=mp_make_scaled(mp, mp_round_fraction(mp, value(p)),v);
12122     } else {
12123       w=mp_make_scaled(mp, value(p),v);
12124     }
12125     if ( abs(w)<=mp_threshold ) {
12126       s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
12127     } else { 
12128       if ( abs(w)>=coef_bound ) {
12129          mp->fix_needed=true; type(info(p))=independent_needing_fix;
12130       }
12131       link(r)=p; r=p; value(p)=w; p=link(p);
12132     }
12133   }
12134   link(r)=p; value(p)=mp_make_scaled(mp, value(p),v);
12135   return link(temp_head);
12136 };
12137
12138 @ Here's another utility routine for dependency lists. When an independent
12139 variable becomes dependent, we want to remove it from all existing
12140 dependencies. The |p_with_x_becoming_q| function computes the
12141 dependency list of~|p| after variable~|x| has been replaced by~|q|.
12142
12143 This procedure has basically the same calling conventions as |p_plus_fq|:
12144 List~|q| is unchanged; list~|p| is destroyed; the constant node and the
12145 final link are inherited from~|p|; and the fourth parameter tells whether
12146 or not |p| is |mp_proto_dependent|. However, the global variable |dep_final|
12147 is not altered if |x| does not occur in list~|p|.
12148
12149 @c pointer mp_p_with_x_becoming_q (MP mp,pointer p,
12150            pointer x, pointer q, small_number t) {
12151   pointer r,s; /* for list manipulation */
12152   integer v; /* coefficient of |x| */
12153   integer sx; /* serial number of |x| */
12154   s=p; r=temp_head; sx=value(x);
12155   while ( value(info(s))>sx ) { r=s; s=link(s); };
12156   if ( info(s)!=x ) { 
12157     return p;
12158   } else { 
12159     link(temp_head)=p; link(r)=link(s); v=value(s);
12160     mp_free_node(mp, s,dep_node_size);
12161     return mp_p_plus_fq(mp, link(temp_head),v,q,t,mp_dependent);
12162   }
12163 }
12164
12165 @ Here's a simple procedure that reports an error when a variable
12166 has just received a known value that's out of the required range.
12167
12168 @<Declare basic dependency-list subroutines@>=
12169 void mp_val_too_big (MP mp,scaled x) ;
12170
12171 @ @c void mp_val_too_big (MP mp,scaled x) { 
12172   if ( mp->internal[mp_warning_check]>0 ) { 
12173     print_err("Value is too large ("); mp_print_scaled(mp, x); mp_print_char(mp, ')');
12174 @.Value is too large@>
12175     help4("The equation I just processed has given some variable")
12176       ("a value of 4096 or more. Continue and I'll try to cope")
12177       ("with that big value; but it might be dangerous.")
12178       ("(Set warningcheck:=0 to suppress this message.)");
12179     mp_error(mp);
12180   }
12181 }
12182
12183 @ When a dependent variable becomes known, the following routine
12184 removes its dependency list. Here |p| points to the variable, and
12185 |q| points to the dependency list (which is one node long).
12186
12187 @<Declare basic dependency-list subroutines@>=
12188 void mp_make_known (MP mp,pointer p, pointer q) ;
12189
12190 @ @c void mp_make_known (MP mp,pointer p, pointer q) {
12191   int t; /* the previous type */
12192   prev_dep(link(q))=prev_dep(p);
12193   link(prev_dep(p))=link(q); t=type(p);
12194   type(p)=mp_known; value(p)=value(q); mp_free_node(mp, q,dep_node_size);
12195   if ( abs(value(p))>=fraction_one ) mp_val_too_big(mp, value(p));
12196   if (( mp->internal[mp_tracing_equations]>0) && mp_interesting(mp, p) ) {
12197     mp_begin_diagnostic(mp); mp_print_nl(mp, "#### ");
12198 @:]]]\#\#\#\#_}{\.{\#\#\#\#}@>
12199     mp_print_variable_name(mp, p); 
12200     mp_print_char(mp, '='); mp_print_scaled(mp, value(p));
12201     mp_end_diagnostic(mp, false);
12202   }
12203   if (( mp->cur_exp==p ) && mp->cur_type==t ) {
12204     mp->cur_type=mp_known; mp->cur_exp=value(p);
12205     mp_free_node(mp, p,value_node_size);
12206   }
12207 }
12208
12209 @ The |fix_dependencies| routine is called into action when |fix_needed|
12210 has been triggered. The program keeps a list~|s| of independent variables
12211 whose coefficients must be divided by~4.
12212
12213 In unusual cases, this fixup process might reduce one or more coefficients
12214 to zero, so that a variable will become known more or less by default.
12215
12216 @<Declare basic dependency-list subroutines@>=
12217 void mp_fix_dependencies (MP mp);
12218
12219 @ @c void mp_fix_dependencies (MP mp) {
12220   pointer p,q,r,s,t; /* list manipulation registers */
12221   pointer x; /* an independent variable */
12222   r=link(dep_head); s=null;
12223   while ( r!=dep_head ){ 
12224     t=r;
12225     @<Run through the dependency list for variable |t|, fixing
12226       all nodes, and ending with final link~|q|@>;
12227     r=link(q);
12228     if ( q==dep_list(t) ) mp_make_known(mp, t,q);
12229   }
12230   while ( s!=null ) { 
12231     p=link(s); x=info(s); free_avail(s); s=p;
12232     type(x)=mp_independent; value(x)=value(x)+2;
12233   }
12234   mp->fix_needed=false;
12235 }
12236
12237 @ @d independent_being_fixed 1 /* this variable already appears in |s| */
12238
12239 @<Run through the dependency list for variable |t|...@>=
12240 r=value_loc(t); /* |link(r)=dep_list(t)| */
12241 while (1) { 
12242   q=link(r); x=info(q);
12243   if ( x==null ) break;
12244   if ( type(x)<=independent_being_fixed ) {
12245     if ( type(x)<independent_being_fixed ) {
12246       p=mp_get_avail(mp); link(p)=s; s=p;
12247       info(s)=x; type(x)=independent_being_fixed;
12248     }
12249     value(q)=value(q) / 4;
12250     if ( value(q)==0 ) {
12251       link(r)=link(q); mp_free_node(mp, q,dep_node_size); q=r;
12252     }
12253   }
12254   r=q;
12255 }
12256
12257
12258 @ The |new_dep| routine installs a dependency list~|p| into the value node~|q|,
12259 linking it into the list of all known dependencies. We assume that
12260 |dep_final| points to the final node of list~|p|.
12261
12262 @c void mp_new_dep (MP mp,pointer q, pointer p) {
12263   pointer r; /* what used to be the first dependency */
12264   dep_list(q)=p; prev_dep(q)=dep_head;
12265   r=link(dep_head); link(mp->dep_final)=r; prev_dep(r)=mp->dep_final;
12266   link(dep_head)=q;
12267 }
12268
12269 @ Here is one of the ways a dependency list gets started.
12270 The |const_dependency| routine produces a list that has nothing but
12271 a constant term.
12272
12273 @c pointer mp_const_dependency (MP mp, scaled v) {
12274   mp->dep_final=mp_get_node(mp, dep_node_size);
12275   value(mp->dep_final)=v; info(mp->dep_final)=null;
12276   return mp->dep_final;
12277 }
12278
12279 @ And here's a more interesting way to start a dependency list from scratch:
12280 The parameter to |single_dependency| is the location of an
12281 independent variable~|x|, and the result is the simple dependency list
12282 `|x+0|'.
12283
12284 In the unlikely event that the given independent variable has been doubled so
12285 often that we can't refer to it with a nonzero coefficient,
12286 |single_dependency| returns the simple list `0'.  This case can be
12287 recognized by testing that the returned list pointer is equal to
12288 |dep_final|.
12289
12290 @c pointer mp_single_dependency (MP mp,pointer p) {
12291   pointer q; /* the new dependency list */
12292   integer m; /* the number of doublings */
12293   m=value(p) % s_scale;
12294   if ( m>28 ) {
12295     return mp_const_dependency(mp, 0);
12296   } else { 
12297     q=mp_get_node(mp, dep_node_size);
12298     value(q)=two_to_the(28-m); info(q)=p;
12299     link(q)=mp_const_dependency(mp, 0);
12300     return q;
12301   }
12302 }
12303
12304 @ We sometimes need to make an exact copy of a dependency list.
12305
12306 @c pointer mp_copy_dep_list (MP mp,pointer p) {
12307   pointer q; /* the new dependency list */
12308   q=mp_get_node(mp, dep_node_size); mp->dep_final=q;
12309   while (1) { 
12310     info(mp->dep_final)=info(p); value(mp->dep_final)=value(p);
12311     if ( info(mp->dep_final)==null ) break;
12312     link(mp->dep_final)=mp_get_node(mp, dep_node_size);
12313     mp->dep_final=link(mp->dep_final); p=link(p);
12314   }
12315   return q;
12316 }
12317
12318 @ But how do variables normally become known? Ah, now we get to the heart of the
12319 equation-solving mechanism. The |linear_eq| procedure is given a |dependent|
12320 or |mp_proto_dependent| list,~|p|, in which at least one independent variable
12321 appears. It equates this list to zero, by choosing an independent variable
12322 with the largest coefficient and making it dependent on the others. The
12323 newly dependent variable is eliminated from all current dependencies,
12324 thereby possibly making other dependent variables known.
12325
12326 The given list |p| is, of course, totally destroyed by all this processing.
12327
12328 @c void mp_linear_eq (MP mp, pointer p, small_number t) {
12329   pointer q,r,s; /* for link manipulation */
12330   pointer x; /* the variable that loses its independence */
12331   integer n; /* the number of times |x| had been halved */
12332   integer v; /* the coefficient of |x| in list |p| */
12333   pointer prev_r; /* lags one step behind |r| */
12334   pointer final_node; /* the constant term of the new dependency list */
12335   integer w; /* a tentative coefficient */
12336    @<Find a node |q| in list |p| whose coefficient |v| is largest@>;
12337   x=info(q); n=value(x) % s_scale;
12338   @<Divide list |p| by |-v|, removing node |q|@>;
12339   if ( mp->internal[mp_tracing_equations]>0 ) {
12340     @<Display the new dependency@>;
12341   }
12342   @<Simplify all existing dependencies by substituting for |x|@>;
12343   @<Change variable |x| from |independent| to |dependent| or |known|@>;
12344   if ( mp->fix_needed ) mp_fix_dependencies(mp);
12345 }
12346
12347 @ @<Find a node |q| in list |p| whose coefficient |v| is largest@>=
12348 q=p; r=link(p); v=value(q);
12349 while ( info(r)!=null ) { 
12350   if ( abs(value(r))>abs(v) ) { q=r; v=value(r); };
12351   r=link(r);
12352 }
12353
12354 @ Here we want to change the coefficients from |scaled| to |fraction|,
12355 except in the constant term. In the common case of a trivial equation
12356 like `\.{x=3.14}', we will have |v=-fraction_one|, |q=p|, and |t=mp_dependent|.
12357
12358 @<Divide list |p| by |-v|, removing node |q|@>=
12359 s=temp_head; link(s)=p; r=p;
12360 do { 
12361   if ( r==q ) {
12362     link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12363   } else  { 
12364     w=mp_make_fraction(mp, value(r),v);
12365     if ( abs(w)<=half_fraction_threshold ) {
12366       link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12367     } else { 
12368       value(r)=-w; s=r;
12369     }
12370   }
12371   r=link(s);
12372 } while (info(r)!=null);
12373 if ( t==mp_proto_dependent ) {
12374   value(r)=-mp_make_scaled(mp, value(r),v);
12375 } else if ( v!=-fraction_one ) {
12376   value(r)=-mp_make_fraction(mp, value(r),v);
12377 }
12378 final_node=r; p=link(temp_head)
12379
12380 @ @<Display the new dependency@>=
12381 if ( mp_interesting(mp, x) ) {
12382   mp_begin_diagnostic(mp); mp_print_nl(mp, "## "); 
12383   mp_print_variable_name(mp, x);
12384 @:]]]\#\#_}{\.{\#\#}@>
12385   w=n;
12386   while ( w>0 ) { mp_print(mp, "*4"); w=w-2;  };
12387   mp_print_char(mp, '='); mp_print_dependency(mp, p,mp_dependent); 
12388   mp_end_diagnostic(mp, false);
12389 }
12390
12391 @ @<Simplify all existing dependencies by substituting for |x|@>=
12392 prev_r=dep_head; r=link(dep_head);
12393 while ( r!=dep_head ) {
12394   s=dep_list(r); q=mp_p_with_x_becoming_q(mp, s,x,p,type(r));
12395   if ( info(q)==null ) {
12396     mp_make_known(mp, r,q);
12397   } else { 
12398     dep_list(r)=q;
12399     do {  q=link(q); } while (info(q)!=null);
12400     prev_r=q;
12401   }
12402   r=link(prev_r);
12403 }
12404
12405 @ @<Change variable |x| from |independent| to |dependent| or |known|@>=
12406 if ( n>0 ) @<Divide list |p| by $2^n$@>;
12407 if ( info(p)==null ) {
12408   type(x)=mp_known;
12409   value(x)=value(p);
12410   if ( abs(value(x))>=fraction_one ) mp_val_too_big(mp, value(x));
12411   mp_free_node(mp, p,dep_node_size);
12412   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) {
12413     mp->cur_exp=value(x); mp->cur_type=mp_known;
12414     mp_free_node(mp, x,value_node_size);
12415   }
12416 } else { 
12417   type(x)=mp_dependent; mp->dep_final=final_node; mp_new_dep(mp, x,p);
12418   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) mp->cur_type=mp_dependent;
12419 }
12420
12421 @ @<Divide list |p| by $2^n$@>=
12422
12423   s=temp_head; link(temp_head)=p; r=p;
12424   do {  
12425     if ( n>30 ) w=0;
12426     else w=value(r) / two_to_the(n);
12427     if ( (abs(w)<=half_fraction_threshold)&&(info(r)!=null) ) {
12428       link(s)=link(r);
12429       mp_free_node(mp, r,dep_node_size);
12430     } else { 
12431       value(r)=w; s=r;
12432     }
12433     r=link(s);
12434   } while (info(s)!=null);
12435   p=link(temp_head);
12436 }
12437
12438 @ The |check_mem| procedure, which is used only when \MP\ is being
12439 debugged, makes sure that the current dependency lists are well formed.
12440
12441 @<Check the list of linear dependencies@>=
12442 q=dep_head; p=link(q);
12443 while ( p!=dep_head ) {
12444   if ( prev_dep(p)!=q ) {
12445     mp_print_nl(mp, "Bad PREVDEP at "); mp_print_int(mp, p);
12446 @.Bad PREVDEP...@>
12447   }
12448   p=dep_list(p);
12449   while (1) {
12450     r=info(p); q=p; p=link(q);
12451     if ( r==null ) break;
12452     if ( value(info(p))>=value(r) ) {
12453       mp_print_nl(mp, "Out of order at "); mp_print_int(mp, p);
12454 @.Out of order...@>
12455     }
12456   }
12457 }
12458
12459 @* \[25] Dynamic nonlinear equations.
12460 Variables of numeric type are maintained by the general scheme of
12461 independent, dependent, and known values that we have just studied;
12462 and the components of pair and transform variables are handled in the
12463 same way. But \MP\ also has five other types of values: \&{boolean},
12464 \&{string}, \&{pen}, \&{path}, and \&{picture}; what about them?
12465
12466 Equations are allowed between nonlinear quantities, but only in a
12467 simple form. Two variables that haven't yet been assigned values are
12468 either equal to each other, or they're not.
12469
12470 Before a boolean variable has received a value, its type is |mp_unknown_boolean|;
12471 similarly, there are variables whose type is |mp_unknown_string|, |mp_unknown_pen|,
12472 |mp_unknown_path|, and |mp_unknown_picture|. In such cases the value is either
12473 |null| (which means that no other variables are equivalent to this one), or
12474 it points to another variable of the same undefined type. The pointers in the
12475 latter case form a cycle of nodes, which we shall call a ``ring.''
12476 Rings of undefined variables may include capsules, which arise as
12477 intermediate results within expressions or as \&{expr} parameters to macros.
12478
12479 When one member of a ring receives a value, the same value is given to
12480 all the other members. In the case of paths and pictures, this implies
12481 making separate copies of a potentially large data structure; users should
12482 restrain their enthusiasm for such generality, unless they have lots and
12483 lots of memory space.
12484
12485 @ The following procedure is called when a capsule node is being
12486 added to a ring (e.g., when an unknown variable is mentioned in an expression).
12487
12488 @c pointer mp_new_ring_entry (MP mp,pointer p) {
12489   pointer q; /* the new capsule node */
12490   q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
12491   type(q)=type(p);
12492   if ( value(p)==null ) value(q)=p; else value(q)=value(p);
12493   value(p)=q;
12494   return q;
12495 }
12496
12497 @ Conversely, we might delete a capsule or a variable before it becomes known.
12498 The following procedure simply detaches a quantity from its ring,
12499 without recycling the storage.
12500
12501 @<Declare the recycling subroutines@>=
12502 void mp_ring_delete (MP mp,pointer p) {
12503   pointer q; 
12504   q=value(p);
12505   if ( q!=null ) if ( q!=p ){ 
12506     while ( value(q)!=p ) q=value(q);
12507     value(q)=value(p);
12508   }
12509 }
12510
12511 @ Eventually there might be an equation that assigns values to all of the
12512 variables in a ring. The |nonlinear_eq| subroutine does the necessary
12513 propagation of values.
12514
12515 If the parameter |flush_p| is |true|, node |p| itself needn't receive a
12516 value, it will soon be recycled.
12517
12518 @c void mp_nonlinear_eq (MP mp,integer v, pointer p, boolean flush_p) {
12519   small_number t; /* the type of ring |p| */
12520   pointer q,r; /* link manipulation registers */
12521   t=type(p)-unknown_tag; q=value(p);
12522   if ( flush_p ) type(p)=mp_vacuous; else p=q;
12523   do {  
12524     r=value(q); type(q)=t;
12525     switch (t) {
12526     case mp_boolean_type: value(q)=v; break;
12527     case mp_string_type: value(q)=v; add_str_ref(v); break;
12528     case mp_pen_type: value(q)=copy_pen(v); break;
12529     case mp_path_type: value(q)=mp_copy_path(mp, v); break;
12530     case mp_picture_type: value(q)=v; add_edge_ref(v); break;
12531     } /* there ain't no more cases */
12532     q=r;
12533   } while (q!=p);
12534 }
12535
12536 @ If two members of rings are equated, and if they have the same type,
12537 the |ring_merge| procedure is called on to make them equivalent.
12538
12539 @c void mp_ring_merge (MP mp,pointer p, pointer q) {
12540   pointer r; /* traverses one list */
12541   r=value(p);
12542   while ( r!=p ) {
12543     if ( r==q ) {
12544       @<Exclaim about a redundant equation@>;
12545       return;
12546     };
12547     r=value(r);
12548   }
12549   r=value(p); value(p)=value(q); value(q)=r;
12550 }
12551
12552 @ @<Exclaim about a redundant equation@>=
12553
12554   print_err("Redundant equation");
12555 @.Redundant equation@>
12556   help2("I already knew that this equation was true.")
12557    ("But perhaps no harm has been done; let's continue.");
12558   mp_put_get_error(mp);
12559 }
12560
12561 @* \[26] Introduction to the syntactic routines.
12562 Let's pause a moment now and try to look at the Big Picture.
12563 The \MP\ program consists of three main parts: syntactic routines,
12564 semantic routines, and output routines. The chief purpose of the
12565 syntactic routines is to deliver the user's input to the semantic routines,
12566 while parsing expressions and locating operators and operands. The
12567 semantic routines act as an interpreter responding to these operators,
12568 which may be regarded as commands. And the output routines are
12569 periodically called on to produce compact font descriptions that can be
12570 used for typesetting or for making interim proof drawings. We have
12571 discussed the basic data structures and many of the details of semantic
12572 operations, so we are good and ready to plunge into the part of \MP\ that
12573 actually controls the activities.
12574
12575 Our current goal is to come to grips with the |get_next| procedure,
12576 which is the keystone of \MP's input mechanism. Each call of |get_next|
12577 sets the value of three variables |cur_cmd|, |cur_mod|, and |cur_sym|,
12578 representing the next input token.
12579 $$\vbox{\halign{#\hfil\cr
12580   \hbox{|cur_cmd| denotes a command code from the long list of codes
12581    given earlier;}\cr
12582   \hbox{|cur_mod| denotes a modifier of the command code;}\cr
12583   \hbox{|cur_sym| is the hash address of the symbolic token that was
12584    just scanned,}\cr
12585   \hbox{\qquad or zero in the case of a numeric or string
12586    or capsule token.}\cr}}$$
12587 Underlying this external behavior of |get_next| is all the machinery
12588 necessary to convert from character files to tokens. At a given time we
12589 may be only partially finished with the reading of several files (for
12590 which \&{input} was specified), and partially finished with the expansion
12591 of some user-defined macros and/or some macro parameters, and partially
12592 finished reading some text that the user has inserted online,
12593 and so on. When reading a character file, the characters must be
12594 converted to tokens; comments and blank spaces must
12595 be removed, numeric and string tokens must be evaluated.
12596
12597 To handle these situations, which might all be present simultaneously,
12598 \MP\ uses various stacks that hold information about the incomplete
12599 activities, and there is a finite state control for each level of the
12600 input mechanism. These stacks record the current state of an implicitly
12601 recursive process, but the |get_next| procedure is not recursive.
12602
12603 @<Glob...@>=
12604 eight_bits cur_cmd; /* current command set by |get_next| */
12605 integer cur_mod; /* operand of current command */
12606 halfword cur_sym; /* hash address of current symbol */
12607
12608 @ The |print_cmd_mod| routine prints a symbolic interpretation of a
12609 command code and its modifier.
12610 It consists of a rather tedious sequence of print
12611 commands, and most of it is essentially an inverse to the |primitive|
12612 routine that enters a \MP\ primitive into |hash| and |eqtb|. Therefore almost
12613 all of this procedure appears elsewhere in the program, together with the
12614 corresponding |primitive| calls.
12615
12616 @<Declare the procedure called |print_cmd_mod|@>=
12617 void mp_print_cmd_mod (MP mp,integer c, integer m) { 
12618  switch (c) {
12619   @<Cases of |print_cmd_mod| for symbolic printing of primitives@>
12620   default: mp_print(mp, "[unknown command code!]"); break;
12621   }
12622 }
12623
12624 @ Here is a procedure that displays a given command in braces, in the
12625 user's transcript file.
12626
12627 @d show_cur_cmd_mod mp_show_cmd_mod(mp, mp->cur_cmd,mp->cur_mod)
12628
12629 @c 
12630 void mp_show_cmd_mod (MP mp,integer c, integer m) { 
12631   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
12632   mp_print_cmd_mod(mp, c,m); mp_print_char(mp, '}');
12633   mp_end_diagnostic(mp, false);
12634 }
12635
12636 @* \[27] Input stacks and states.
12637 The state of \MP's input mechanism appears in the input stack, whose
12638 entries are records with five fields, called |index|, |start|, |loc|,
12639 |limit|, and |name|. The top element of this stack is maintained in a
12640 global variable for which no subscripting needs to be done; the other
12641 elements of the stack appear in an array. Hence the stack is declared thus:
12642
12643 @<Types...@>=
12644 typedef struct {
12645   quarterword index_field;
12646   halfword start_field, loc_field, limit_field, name_field;
12647 } in_state_record;
12648
12649 @ @<Glob...@>=
12650 in_state_record *input_stack;
12651 integer input_ptr; /* first unused location of |input_stack| */
12652 integer max_in_stack; /* largest value of |input_ptr| when pushing */
12653 in_state_record cur_input; /* the ``top'' input state */
12654 int stack_size; /* maximum number of simultaneous input sources */
12655
12656 @ @<Allocate or initialize ...@>=
12657 mp->stack_size = 300;
12658 mp->input_stack = xmalloc((mp->stack_size+1),sizeof(in_state_record));
12659
12660 @ @<Dealloc variables@>=
12661 xfree(mp->input_stack);
12662
12663 @ We've already defined the special variable |loc==cur_input.loc_field|
12664 in our discussion of basic input-output routines. The other components of
12665 |cur_input| are defined in the same way:
12666
12667 @d index mp->cur_input.index_field /* reference for buffer information */
12668 @d start mp->cur_input.start_field /* starting position in |buffer| */
12669 @d limit mp->cur_input.limit_field /* end of current line in |buffer| */
12670 @d name mp->cur_input.name_field /* name of the current file */
12671
12672 @ Let's look more closely now at the five control variables
12673 (|index|,~|start|,~|loc|,~|limit|,~|name|),
12674 assuming that \MP\ is reading a line of characters that have been input
12675 from some file or from the user's terminal. There is an array called
12676 |buffer| that acts as a stack of all lines of characters that are
12677 currently being read from files, including all lines on subsidiary
12678 levels of the input stack that are not yet completed. \MP\ will return to
12679 the other lines when it is finished with the present input file.
12680
12681 (Incidentally, on a machine with byte-oriented addressing, it would be
12682 appropriate to combine |buffer| with the |str_pool| array,
12683 letting the buffer entries grow downward from the top of the string pool
12684 and checking that these two tables don't bump into each other.)
12685
12686 The line we are currently working on begins in position |start| of the
12687 buffer; the next character we are about to read is |buffer[loc]|; and
12688 |limit| is the location of the last character present. We always have
12689 |loc<=limit|. For convenience, |buffer[limit]| has been set to |"%"|, so
12690 that the end of a line is easily sensed.
12691
12692 The |name| variable is a string number that designates the name of
12693 the current file, if we are reading an ordinary text file.  Special codes
12694 |is_term..max_spec_src| indicate other sources of input text.
12695
12696 @d is_term 0 /* |name| value when reading from the terminal for normal input */
12697 @d is_read 1 /* |name| value when executing a \&{readstring} or \&{readfrom} */
12698 @d is_scantok 2 /* |name| value when reading text generated by \&{scantokens} */
12699 @d max_spec_src is_scantok
12700
12701 @ Additional information about the current line is available via the
12702 |index| variable, which counts how many lines of characters are present
12703 in the buffer below the current level. We have |index=0| when reading
12704 from the terminal and prompting the user for each line; then if the user types,
12705 e.g., `\.{input figs}', we will have |index=1| while reading
12706 the file \.{figs.mp}. However, it does not follow that |index| is the
12707 same as the input stack pointer, since many of the levels on the input
12708 stack may come from token lists and some |index| values may correspond
12709 to \.{MPX} files that are not currently on the stack.
12710
12711 The global variable |in_open| is equal to the highest |index| value counting
12712 \.{MPX} files but excluding token-list input levels.  Thus, the number of
12713 partially read lines in the buffer is |in_open+1| and we have |in_open>=index|
12714 when we are not reading a token list.
12715
12716 If we are not currently reading from the terminal,
12717 we are reading from the file variable |input_file[index]|. We use
12718 the notation |terminal_input| as a convenient abbreviation for |name=is_term|,
12719 and |cur_file| as an abbreviation for |input_file[index]|.
12720
12721 When \MP\ is not reading from the terminal, the global variable |line| contains
12722 the line number in the current file, for use in error messages. More precisely,
12723 |line| is a macro for |line_stack[index]| and the |line_stack| array gives
12724 the line number for each file in the |input_file| array.
12725
12726 When an \.{MPX} file is opened the file name is stored in the |mpx_name|
12727 array so that the name doesn't get lost when the file is temporarily removed
12728 from the input stack.
12729 Thus when |input_file[k]| is an \.{MPX} file, its name is |mpx_name[k]|
12730 and it contains translated \TeX\ pictures for |input_file[k-1]|.
12731 Since this is not an \.{MPX} file, we have
12732 $$ \hbox{|mpx_name[k-1]<=absent|}. $$
12733 This |name| field is set to |finished| when |input_file[k]| is completely
12734 read.
12735
12736 If more information about the input state is needed, it can be
12737 included in small arrays like those shown here. For example,
12738 the current page or segment number in the input file might be put
12739 into a variable |page|, that is really a macro for the current entry
12740 in `\ignorespaces|page_stack:array[0..max_in_open] of integer|\unskip'
12741 by analogy with |line_stack|.
12742 @^system dependencies@>
12743
12744 @d terminal_input (name==is_term) /* are we reading from the terminal? */
12745 @d cur_file mp->input_file[index] /* the current |FILE *| variable */
12746 @d line mp->line_stack[index] /* current line number in the current source file */
12747 @d in_name mp->iname_stack[index] /* a string used to construct \.{MPX} file names */
12748 @d in_area mp->iarea_stack[index] /* another string for naming \.{MPX} files */
12749 @d absent 1 /* |name_field| value for unused |mpx_in_stack| entries */
12750 @d mpx_reading (mp->mpx_name[index]>absent)
12751   /* when reading a file, is it an \.{MPX} file? */
12752 @d finished 0
12753   /* |name_field| value when the corresponding \.{MPX} file is finished */
12754
12755 @<Glob...@>=
12756 integer in_open; /* the number of lines in the buffer, less one */
12757 unsigned int open_parens; /* the number of open text files */
12758 FILE  * *input_file ;
12759 integer *line_stack ; /* the line number for each file */
12760 char *  *iname_stack; /* used for naming \.{MPX} files */
12761 char *  *iarea_stack; /* used for naming \.{MPX} files */
12762 halfword*mpx_name  ;
12763
12764 @ @<Allocate or ...@>=
12765 mp->input_file  = xmalloc((mp->max_in_open+1),sizeof(FILE *));
12766 mp->line_stack  = xmalloc((mp->max_in_open+1),sizeof(integer));
12767 mp->iname_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12768 mp->iarea_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12769 mp->mpx_name    = xmalloc((mp->max_in_open+1),sizeof(halfword));
12770 {
12771   int k;
12772   for (k=0;k<=mp->max_in_open;k++) {
12773     mp->iname_stack[k] =NULL;
12774     mp->iarea_stack[k] =NULL;
12775   }
12776 }
12777
12778 @ @<Dealloc variables@>=
12779 {
12780   int l;
12781   for (l=0;l<=mp->max_in_open;l++) {
12782     xfree(mp->iname_stack[l]);
12783     xfree(mp->iarea_stack[l]);
12784   }
12785 }
12786 xfree(mp->input_file);
12787 xfree(mp->line_stack);
12788 xfree(mp->iname_stack);
12789 xfree(mp->iarea_stack);
12790 xfree(mp->mpx_name);
12791
12792
12793 @ However, all this discussion about input state really applies only to the
12794 case that we are inputting from a file. There is another important case,
12795 namely when we are currently getting input from a token list. In this case
12796 |index>max_in_open|, and the conventions about the other state variables
12797 are different:
12798
12799 \yskip\hang|loc| is a pointer to the current node in the token list, i.e.,
12800 the node that will be read next. If |loc=null|, the token list has been
12801 fully read.
12802
12803 \yskip\hang|start| points to the first node of the token list; this node
12804 may or may not contain a reference count, depending on the type of token
12805 list involved.
12806
12807 \yskip\hang|token_type|, which takes the place of |index| in the
12808 discussion above, is a code number that explains what kind of token list
12809 is being scanned.
12810
12811 \yskip\hang|name| points to the |eqtb| address of the control sequence
12812 being expanded, if the current token list is a macro not defined by
12813 \&{vardef}. Macros defined by \&{vardef} have |name=null|; their name
12814 can be deduced by looking at their first two parameters.
12815
12816 \yskip\hang|param_start|, which takes the place of |limit|, tells where
12817 the parameters of the current macro or loop text begin in the |param_stack|.
12818
12819 \yskip\noindent The |token_type| can take several values, depending on
12820 where the current token list came from:
12821
12822 \yskip
12823 \indent|forever_text|, if the token list being scanned is the body of
12824 a \&{forever} loop;
12825
12826 \indent|loop_text|, if the token list being scanned is the body of
12827 a \&{for} or \&{forsuffixes} loop;
12828
12829 \indent|parameter|, if a \&{text} or \&{suffix} parameter is being scanned;
12830
12831 \indent|backed_up|, if the token list being scanned has been inserted as
12832 `to be read again'.
12833
12834 \indent|inserted|, if the token list being scanned has been inserted as
12835 part of error recovery;
12836
12837 \indent|macro|, if the expansion of a user-defined symbolic token is being
12838 scanned.
12839
12840 \yskip\noindent
12841 The token list begins with a reference count if and only if |token_type=
12842 macro|.
12843 @^reference counts@>
12844
12845 @d token_type index /* type of current token list */
12846 @d token_state (index>(int)mp->max_in_open) /* are we scanning a token list? */
12847 @d file_state (index<=(int)mp->max_in_open) /* are we scanning a file line? */
12848 @d param_start limit /* base of macro parameters in |param_stack| */
12849 @d forever_text (mp->max_in_open+1) /* |token_type| code for loop texts */
12850 @d loop_text (mp->max_in_open+2) /* |token_type| code for loop texts */
12851 @d parameter (mp->max_in_open+3) /* |token_type| code for parameter texts */
12852 @d backed_up (mp->max_in_open+4) /* |token_type| code for texts to be reread */
12853 @d inserted (mp->max_in_open+5) /* |token_type| code for inserted texts */
12854 @d macro (mp->max_in_open+6) /* |token_type| code for macro replacement texts */
12855
12856 @ The |param_stack| is an auxiliary array used to hold pointers to the token
12857 lists for parameters at the current level and subsidiary levels of input.
12858 This stack grows at a different rate from the others.
12859
12860 @<Glob...@>=
12861 pointer *param_stack;  /* token list pointers for parameters */
12862 integer param_ptr; /* first unused entry in |param_stack| */
12863 integer max_param_stack;  /* largest value of |param_ptr| */
12864
12865 @ @<Allocate or initialize ...@>=
12866 mp->param_stack = xmalloc((mp->param_size+1),sizeof(pointer));
12867
12868 @ @<Dealloc variables@>=
12869 xfree(mp->param_stack);
12870
12871 @ Notice that the |line| isn't valid when |token_state| is true because it
12872 depends on |index|.  If we really need to know the line number for the
12873 topmost file in the index stack we use the following function.  If a page
12874 number or other information is needed, this routine should be modified to
12875 compute it as well.
12876 @^system dependencies@>
12877
12878 @<Declare a function called |true_line|@>=
12879 integer mp_true_line (MP mp) {
12880   int k; /* an index into the input stack */
12881   if ( file_state && (name>max_spec_src) ) {
12882      return line;
12883   } else { 
12884     k=mp->input_ptr;
12885     while ((k>0) &&
12886            ((mp->input_stack[(k-1)].index_field>mp->max_in_open)||
12887             (mp->input_stack[(k-1)].name_field<=max_spec_src))) {
12888       decr(k);
12889     }
12890     return mp->line_stack[(k-1)];
12891   }
12892   return 0; 
12893 }
12894
12895 @ Thus, the ``current input state'' can be very complicated indeed; there
12896 can be many levels and each level can arise in a variety of ways. The
12897 |show_context| procedure, which is used by \MP's error-reporting routine to
12898 print out the current input state on all levels down to the most recent
12899 line of characters from an input file, illustrates most of these conventions.
12900 The global variable |file_ptr| contains the lowest level that was
12901 displayed by this procedure.
12902
12903 @<Glob...@>=
12904 integer file_ptr; /* shallowest level shown by |show_context| */
12905
12906 @ The status at each level is indicated by printing two lines, where the first
12907 line indicates what was read so far and the second line shows what remains
12908 to be read. The context is cropped, if necessary, so that the first line
12909 contains at most |half_error_line| characters, and the second contains
12910 at most |error_line|. Non-current input levels whose |token_type| is
12911 `|backed_up|' are shown only if they have not been fully read.
12912
12913 @c void mp_show_context (MP mp) { /* prints where the scanner is */
12914   int old_setting; /* saved |selector| setting */
12915   @<Local variables for formatting calculations@>
12916   mp->file_ptr=mp->input_ptr; mp->input_stack[mp->file_ptr]=mp->cur_input;
12917   /* store current state */
12918   while (1) { 
12919     mp->cur_input=mp->input_stack[mp->file_ptr]; /* enter into the context */
12920     @<Display the current context@>;
12921     if ( file_state )
12922       if ( (name>max_spec_src) || (mp->file_ptr==0) ) break;
12923     decr(mp->file_ptr);
12924   }
12925   mp->cur_input=mp->input_stack[mp->input_ptr]; /* restore original state */
12926 }
12927
12928 @ @<Display the current context@>=
12929 if ( (mp->file_ptr==mp->input_ptr) || file_state ||
12930    (token_type!=backed_up) || (loc!=null) ) {
12931     /* we omit backed-up token lists that have already been read */
12932   mp->tally=0; /* get ready to count characters */
12933   old_setting=mp->selector;
12934   if ( file_state ) {
12935     @<Print location of current line@>;
12936     @<Pseudoprint the line@>;
12937   } else { 
12938     @<Print type of token list@>;
12939     @<Pseudoprint the token list@>;
12940   }
12941   mp->selector=old_setting; /* stop pseudoprinting */
12942   @<Print two lines using the tricky pseudoprinted information@>;
12943 }
12944
12945 @ This routine should be changed, if necessary, to give the best possible
12946 indication of where the current line resides in the input file.
12947 For example, on some systems it is best to print both a page and line number.
12948 @^system dependencies@>
12949
12950 @<Print location of current line@>=
12951 if ( name>max_spec_src ) {
12952   mp_print_nl(mp, "l."); mp_print_int(mp, mp_true_line(mp));
12953 } else if ( terminal_input ) {
12954   if ( mp->file_ptr==0 ) mp_print_nl(mp, "<*>");
12955   else mp_print_nl(mp, "<insert>");
12956 } else if ( name==is_scantok ) {
12957   mp_print_nl(mp, "<scantokens>");
12958 } else {
12959   mp_print_nl(mp, "<read>");
12960 }
12961 mp_print_char(mp, ' ')
12962
12963 @ Can't use case statement here because the |token_type| is not
12964 a constant expression.
12965
12966 @<Print type of token list@>=
12967 {
12968   if(token_type==forever_text) {
12969     mp_print_nl(mp, "<forever> ");
12970   } else if (token_type==loop_text) {
12971     @<Print the current loop value@>;
12972   } else if (token_type==parameter) {
12973     mp_print_nl(mp, "<argument> "); 
12974   } else if (token_type==backed_up) { 
12975     if ( loc==null ) mp_print_nl(mp, "<recently read> ");
12976     else mp_print_nl(mp, "<to be read again> ");
12977   } else if (token_type==inserted) {
12978     mp_print_nl(mp, "<inserted text> ");
12979   } else if (token_type==macro) {
12980     mp_print_ln(mp);
12981     if ( name!=null ) mp_print_text(name);
12982     else @<Print the name of a \&{vardef}'d macro@>;
12983     mp_print(mp, "->");
12984   } else {
12985     mp_print_nl(mp, "?");/* this should never happen */
12986 @.?\relax@>
12987   }
12988 }
12989
12990 @ The parameter that corresponds to a loop text is either a token list
12991 (in the case of \&{forsuffixes}) or a ``capsule'' (in the case of \&{for}).
12992 We'll discuss capsules later; for now, all we need to know is that
12993 the |link| field in a capsule parameter is |void| and that
12994 |print_exp(p,0)| displays the value of capsule~|p| in abbreviated form.
12995
12996 @<Print the current loop value@>=
12997 { mp_print_nl(mp, "<for("); p=mp->param_stack[param_start];
12998   if ( p!=null ) {
12999     if ( link(p)==mp_void ) mp_print_exp(mp, p,0); /* we're in a \&{for} loop */
13000     else mp_show_token_list(mp, p,null,20,mp->tally);
13001   }
13002   mp_print(mp, ")> ");
13003 }
13004
13005 @ The first two parameters of a macro defined by \&{vardef} will be token
13006 lists representing the macro's prefix and ``at point.'' By putting these
13007 together, we get the macro's full name.
13008
13009 @<Print the name of a \&{vardef}'d macro@>=
13010 { p=mp->param_stack[param_start];
13011   if ( p==null ) {
13012     mp_show_token_list(mp, mp->param_stack[param_start+1],null,20,mp->tally);
13013   } else { 
13014     q=p;
13015     while ( link(q)!=null ) q=link(q);
13016     link(q)=mp->param_stack[param_start+1];
13017     mp_show_token_list(mp, p,null,20,mp->tally);
13018     link(q)=null;
13019   }
13020 }
13021
13022 @ Now it is necessary to explain a little trick. We don't want to store a long
13023 string that corresponds to a token list, because that string might take up
13024 lots of memory; and we are printing during a time when an error message is
13025 being given, so we dare not do anything that might overflow one of \MP's
13026 tables. So `pseudoprinting' is the answer: We enter a mode of printing
13027 that stores characters into a buffer of length |error_line|, where character
13028 $k+1$ is placed into \hbox{|trick_buf[k mod error_line]|} if
13029 |k<trick_count|, otherwise character |k| is dropped. Initially we set
13030 |tally:=0| and |trick_count:=1000000|; then when we reach the
13031 point where transition from line 1 to line 2 should occur, we
13032 set |first_count:=tally| and |trick_count:=@tmax@>(error_line,
13033 tally+1+error_line-half_error_line)|. At the end of the
13034 pseudoprinting, the values of |first_count|, |tally|, and
13035 |trick_count| give us all the information we need to print the two lines,
13036 and all of the necessary text is in |trick_buf|.
13037
13038 Namely, let |l| be the length of the descriptive information that appears
13039 on the first line. The length of the context information gathered for that
13040 line is |k=first_count|, and the length of the context information
13041 gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k<=h|,
13042 where |h=half_error_line|, we print |trick_buf[0..k-1]| after the
13043 descriptive information on line~1, and set |n:=l+k|; here |n| is the
13044 length of line~1. If $l+k>h$, some cropping is necessary, so we set |n:=h|
13045 and print `\.{...}' followed by
13046 $$\hbox{|trick_buf[(l+k-h+3)..k-1]|,}$$
13047 where subscripts of |trick_buf| are circular modulo |error_line|. The
13048 second line consists of |n|~spaces followed by |trick_buf[k..(k+m-1)]|,
13049 unless |n+m>error_line|; in the latter case, further cropping is done.
13050 This is easier to program than to explain.
13051
13052 @<Local variables for formatting...@>=
13053 int i; /* index into |buffer| */
13054 integer l; /* length of descriptive information on line 1 */
13055 integer m; /* context information gathered for line 2 */
13056 int n; /* length of line 1 */
13057 integer p; /* starting or ending place in |trick_buf| */
13058 integer q; /* temporary index */
13059
13060 @ The following code tells the print routines to gather
13061 the desired information.
13062
13063 @d begin_pseudoprint { 
13064   l=mp->tally; mp->tally=0; mp->selector=pseudo;
13065   mp->trick_count=1000000;
13066 }
13067 @d set_trick_count {
13068   mp->first_count=mp->tally;
13069   mp->trick_count=mp->tally+1+mp->error_line-mp->half_error_line;
13070   if ( mp->trick_count<mp->error_line ) mp->trick_count=mp->error_line;
13071 }
13072
13073 @ And the following code uses the information after it has been gathered.
13074
13075 @<Print two lines using the tricky pseudoprinted information@>=
13076 if ( mp->trick_count==1000000 ) set_trick_count;
13077   /* |set_trick_count| must be performed */
13078 if ( mp->tally<mp->trick_count ) m=mp->tally-mp->first_count;
13079 else m=mp->trick_count-mp->first_count; /* context on line 2 */
13080 if ( l+mp->first_count<=mp->half_error_line ) {
13081   p=0; n=l+mp->first_count;
13082 } else  { 
13083   mp_print(mp, "..."); p=l+mp->first_count-mp->half_error_line+3;
13084   n=mp->half_error_line;
13085 }
13086 for (q=p;q<=mp->first_count-1;q++) {
13087   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13088 }
13089 mp_print_ln(mp);
13090 for (q=1;q<=n;q++) {
13091   mp_print_char(mp, ' '); /* print |n| spaces to begin line~2 */
13092 }
13093 if ( m+n<=mp->error_line ) p=mp->first_count+m; 
13094 else p=mp->first_count+(mp->error_line-n-3);
13095 for (q=mp->first_count;q<=p-1;q++) {
13096   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13097 }
13098 if ( m+n>mp->error_line ) mp_print(mp, "...")
13099
13100 @ But the trick is distracting us from our current goal, which is to
13101 understand the input state. So let's concentrate on the data structures that
13102 are being pseudoprinted as we finish up the |show_context| procedure.
13103
13104 @<Pseudoprint the line@>=
13105 begin_pseudoprint;
13106 if ( limit>0 ) {
13107   for (i=start;i<=limit-1;i++) {
13108     if ( i==loc ) set_trick_count;
13109     mp_print_str(mp, mp->buffer[i]);
13110   }
13111 }
13112
13113 @ @<Pseudoprint the token list@>=
13114 begin_pseudoprint;
13115 if ( token_type!=macro ) mp_show_token_list(mp, start,loc,100000,0);
13116 else mp_show_macro(mp, start,loc,100000)
13117
13118 @ Here is the missing piece of |show_token_list| that is activated when the
13119 token beginning line~2 is about to be shown:
13120
13121 @<Do magic computation@>=set_trick_count
13122
13123 @* \[28] Maintaining the input stacks.
13124 The following subroutines change the input status in commonly needed ways.
13125
13126 First comes |push_input|, which stores the current state and creates a
13127 new level (having, initially, the same properties as the old).
13128
13129 @d push_input  { /* enter a new input level, save the old */
13130   if ( mp->input_ptr>mp->max_in_stack ) {
13131     mp->max_in_stack=mp->input_ptr;
13132     if ( mp->input_ptr==mp->stack_size ) {
13133       int l = (mp->stack_size+(mp->stack_size>>2));
13134       XREALLOC(mp->input_stack, l, in_state_record);
13135       mp->stack_size = l;
13136     }         
13137   }
13138   mp->input_stack[mp->input_ptr]=mp->cur_input; /* stack the record */
13139   incr(mp->input_ptr);
13140 }
13141
13142 @ And of course what goes up must come down.
13143
13144 @d pop_input { /* leave an input level, re-enter the old */
13145     decr(mp->input_ptr); mp->cur_input=mp->input_stack[mp->input_ptr];
13146   }
13147
13148 @ Here is a procedure that starts a new level of token-list input, given
13149 a token list |p| and its type |t|. If |t=macro|, the calling routine should
13150 set |name|, reset~|loc|, and increase the macro's reference count.
13151
13152 @d back_list(A) mp_begin_token_list(mp, (A),backed_up) /* backs up a simple token list */
13153
13154 @c void mp_begin_token_list (MP mp,pointer p, quarterword t)  { 
13155   push_input; start=p; token_type=t;
13156   param_start=mp->param_ptr; loc=p;
13157 }
13158
13159 @ When a token list has been fully scanned, the following computations
13160 should be done as we leave that level of input.
13161 @^inner loop@>
13162
13163 @c void mp_end_token_list (MP mp) { /* leave a token-list input level */
13164   pointer p; /* temporary register */
13165   if ( token_type>=backed_up ) { /* token list to be deleted */
13166     if ( token_type<=inserted ) { 
13167       mp_flush_token_list(mp, start); goto DONE;
13168     } else {
13169       mp_delete_mac_ref(mp, start); /* update reference count */
13170     }
13171   }
13172   while ( mp->param_ptr>param_start ) { /* parameters must be flushed */
13173     decr(mp->param_ptr);
13174     p=mp->param_stack[mp->param_ptr];
13175     if ( p!=null ) {
13176       if ( link(p)==mp_void ) { /* it's an \&{expr} parameter */
13177         mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
13178       } else {
13179         mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
13180       }
13181     }
13182   }
13183 DONE: 
13184   pop_input; check_interrupt;
13185 }
13186
13187 @ The contents of |cur_cmd,cur_mod,cur_sym| are placed into an equivalent
13188 token by the |cur_tok| routine.
13189 @^inner loop@>
13190
13191 @c @<Declare the procedure called |make_exp_copy|@>;
13192 pointer mp_cur_tok (MP mp) {
13193   pointer p; /* a new token node */
13194   small_number save_type; /* |cur_type| to be restored */
13195   integer save_exp; /* |cur_exp| to be restored */
13196   if ( mp->cur_sym==0 ) {
13197     if ( mp->cur_cmd==capsule_token ) {
13198       save_type=mp->cur_type; save_exp=mp->cur_exp;
13199       mp_make_exp_copy(mp, mp->cur_mod); p=mp_stash_cur_exp(mp); link(p)=null;
13200       mp->cur_type=save_type; mp->cur_exp=save_exp;
13201     } else { 
13202       p=mp_get_node(mp, token_node_size);
13203       value(p)=mp->cur_mod; name_type(p)=mp_token;
13204       if ( mp->cur_cmd==numeric_token ) type(p)=mp_known;
13205       else type(p)=mp_string_type;
13206     }
13207   } else { 
13208     fast_get_avail(p); info(p)=mp->cur_sym;
13209   }
13210   return p;
13211 }
13212
13213 @ Sometimes \MP\ has read too far and wants to ``unscan'' what it has
13214 seen. The |back_input| procedure takes care of this by putting the token
13215 just scanned back into the input stream, ready to be read again.
13216 If |cur_sym<>0|, the values of |cur_cmd| and |cur_mod| are irrelevant.
13217
13218 @<Declarations@>= 
13219 void mp_back_input (MP mp);
13220
13221 @ @c void mp_back_input (MP mp) {/* undoes one token of input */
13222   pointer p; /* a token list of length one */
13223   p=mp_cur_tok(mp);
13224   while ( token_state &&(loc==null) ) 
13225     mp_end_token_list(mp); /* conserve stack space */
13226   back_list(p);
13227 }
13228
13229 @ The |back_error| routine is used when we want to restore or replace an
13230 offending token just before issuing an error message.  We disable interrupts
13231 during the call of |back_input| so that the help message won't be lost.
13232
13233 @<Declarations@>=
13234 void mp_error (MP mp);
13235 void mp_back_error (MP mp);
13236
13237 @ @c void mp_back_error (MP mp) { /* back up one token and call |error| */
13238   mp->OK_to_interrupt=false; 
13239   mp_back_input(mp); 
13240   mp->OK_to_interrupt=true; mp_error(mp);
13241 }
13242 void mp_ins_error (MP mp) { /* back up one inserted token and call |error| */
13243   mp->OK_to_interrupt=false; 
13244   mp_back_input(mp); token_type=inserted;
13245   mp->OK_to_interrupt=true; mp_error(mp);
13246 }
13247
13248 @ The |begin_file_reading| procedure starts a new level of input for lines
13249 of characters to be read from a file, or as an insertion from the
13250 terminal. It does not take care of opening the file, nor does it set |loc|
13251 or |limit| or |line|.
13252 @^system dependencies@>
13253
13254 @c void mp_begin_file_reading (MP mp) { 
13255   if ( mp->in_open==mp->max_in_open ) 
13256     mp_overflow(mp, "text input levels",mp->max_in_open);
13257 @:MetaPost capacity exceeded text input levels}{\quad text input levels@>
13258   if ( mp->first==mp->buf_size ) 
13259     mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13260   incr(mp->in_open); push_input; index=mp->in_open;
13261   mp->mpx_name[index]=absent;
13262   start=mp->first;
13263   name=is_term; /* |terminal_input| is now |true| */
13264 }
13265
13266 @ Conversely, the variables must be downdated when such a level of input
13267 is finished.  Any associated \.{MPX} file must also be closed and popped
13268 off the file stack.
13269
13270 @c void mp_end_file_reading (MP mp) { 
13271   if ( mp->in_open>index ) {
13272     if ( (mp->mpx_name[mp->in_open]==absent)||(name<=max_spec_src) ) {
13273       mp_confusion(mp, "endinput");
13274 @:this can't happen endinput}{\quad endinput@>
13275     } else { 
13276       fclose(mp->input_file[mp->in_open]); /* close an \.{MPX} file */
13277       delete_str_ref(mp->mpx_name[mp->in_open]);
13278       decr(mp->in_open);
13279     }
13280   }
13281   mp->first=start;
13282   if ( index!=mp->in_open ) mp_confusion(mp, "endinput");
13283   if ( name>max_spec_src ) {
13284     fclose(cur_file);
13285     delete_str_ref(name);
13286     xfree(in_name); 
13287     xfree(in_area);
13288   }
13289   pop_input; decr(mp->in_open);
13290 }
13291
13292 @ Here is a function that tries to resume input from an \.{MPX} file already
13293 associated with the current input file.  It returns |false| if this doesn't
13294 work.
13295
13296 @c boolean mp_begin_mpx_reading (MP mp) { 
13297   if ( mp->in_open!=index+1 ) {
13298      return false;
13299   } else { 
13300     if ( mp->mpx_name[mp->in_open]<=absent ) mp_confusion(mp, "mpx");
13301 @:this can't happen mpx}{\quad mpx@>
13302     if ( mp->first==mp->buf_size ) 
13303       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13304     push_input; index=mp->in_open;
13305     start=mp->first;
13306     name=mp->mpx_name[mp->in_open]; add_str_ref(name);
13307     @<Put an empty line in the input buffer@>;
13308     return true;
13309   }
13310 }
13311
13312 @ This procedure temporarily stops reading an \.{MPX} file.
13313
13314 @c void mp_end_mpx_reading (MP mp) { 
13315   if ( mp->in_open!=index ) mp_confusion(mp, "mpx");
13316 @:this can't happen mpx}{\quad mpx@>
13317   if ( loc<limit ) {
13318     @<Complain that we are not at the end of a line in the \.{MPX} file@>;
13319   }
13320   mp->first=start;
13321   pop_input;
13322 }
13323
13324 @ Here we enforce a restriction that simplifies the input stacks considerably.
13325 This should not inconvenience the user because \.{MPX} files are generated
13326 by an auxiliary program called \.{DVItoMP}.
13327
13328 @ @<Complain that we are not at the end of a line in the \.{MPX} file@>=
13329
13330 print_err("`mpxbreak' must be at the end of a line");
13331 help4("This file contains picture expressions for btex...etex")
13332   ("blocks.  Such files are normally generated automatically")
13333   ("but this one seems to be messed up.  I'm going to ignore")
13334   ("the rest of this line.");
13335 mp_error(mp);
13336 }
13337
13338 @ In order to keep the stack from overflowing during a long sequence of
13339 inserted `\.{show}' commands, the following routine removes completed
13340 error-inserted lines from memory.
13341
13342 @c void mp_clear_for_error_prompt (MP mp) { 
13343   while ( file_state && terminal_input &&
13344     (mp->input_ptr>0)&&(loc==limit) ) mp_end_file_reading(mp);
13345   mp_print_ln(mp); clear_terminal;
13346 }
13347
13348 @ To get \MP's whole input mechanism going, we perform the following
13349 actions.
13350
13351 @<Initialize the input routines@>=
13352 { mp->input_ptr=0; mp->max_in_stack=0;
13353   mp->in_open=0; mp->open_parens=0; mp->max_buf_stack=0;
13354   mp->param_ptr=0; mp->max_param_stack=0;
13355   mp->first=1;
13356   start=1; index=0; line=0; name=is_term;
13357   mp->mpx_name[0]=absent;
13358   mp->force_eof=false;
13359   if ( ! mp_init_terminal(mp) ) mp_jump_out(mp);
13360   limit=mp->last; mp->first=mp->last+1; 
13361   /* |init_terminal| has set |loc| and |last| */
13362 }
13363
13364 @* \[29] Getting the next token.
13365 The heart of \MP's input mechanism is the |get_next| procedure, which
13366 we shall develop in the next few sections of the program. Perhaps we
13367 shouldn't actually call it the ``heart,'' however; it really acts as \MP's
13368 eyes and mouth, reading the source files and gobbling them up. And it also
13369 helps \MP\ to regurgitate stored token lists that are to be processed again.
13370
13371 The main duty of |get_next| is to input one token and to set |cur_cmd|
13372 and |cur_mod| to that token's command code and modifier. Furthermore, if
13373 the input token is a symbolic token, that token's |hash| address
13374 is stored in |cur_sym|; otherwise |cur_sym| is set to zero.
13375
13376 Underlying this simple description is a certain amount of complexity
13377 because of all the cases that need to be handled.
13378 However, the inner loop of |get_next| is reasonably short and fast.
13379
13380 @ Before getting into |get_next|, we need to consider a mechanism by which
13381 \MP\ helps keep errors from propagating too far. Whenever the program goes
13382 into a mode where it keeps calling |get_next| repeatedly until a certain
13383 condition is met, it sets |scanner_status| to some value other than |normal|.
13384 Then if an input file ends, or if an `\&{outer}' symbol appears,
13385 an appropriate error recovery will be possible.
13386
13387 The global variable |warning_info| helps in this error recovery by providing
13388 additional information. For example, |warning_info| might indicate the
13389 name of a macro whose replacement text is being scanned.
13390
13391 @d normal 0 /* |scanner_status| at ``quiet times'' */
13392 @d skipping 1 /* |scanner_status| when false conditional text is being skipped */
13393 @d flushing 2 /* |scanner_status| when junk after a statement is being ignored */
13394 @d absorbing 3 /* |scanner_status| when a \&{text} parameter is being scanned */
13395 @d var_defining 4 /* |scanner_status| when a \&{vardef} is being scanned */
13396 @d op_defining 5 /* |scanner_status| when a macro \&{def} is being scanned */
13397 @d loop_defining 6 /* |scanner_status| when a \&{for} loop is being scanned */
13398 @d tex_flushing 7 /* |scanner_status| when skipping \TeX\ material */
13399
13400 @<Glob...@>=
13401 integer scanner_status; /* are we scanning at high speed? */
13402 integer warning_info; /* if so, what else do we need to know,
13403     in case an error occurs? */
13404
13405 @ @<Initialize the input routines@>=
13406 mp->scanner_status=normal;
13407
13408 @ The following subroutine
13409 is called when an `\&{outer}' symbolic token has been scanned or
13410 when the end of a file has been reached. These two cases are distinguished
13411 by |cur_sym|, which is zero at the end of a file.
13412
13413 @c boolean mp_check_outer_validity (MP mp) {
13414   pointer p; /* points to inserted token list */
13415   if ( mp->scanner_status==normal ) {
13416     return true;
13417   } else if ( mp->scanner_status==tex_flushing ) {
13418     @<Check if the file has ended while flushing \TeX\ material and set the
13419       result value for |check_outer_validity|@>;
13420   } else { 
13421     mp->deletions_allowed=false;
13422     @<Back up an outer symbolic token so that it can be reread@>;
13423     if ( mp->scanner_status>skipping ) {
13424       @<Tell the user what has run away and try to recover@>;
13425     } else { 
13426       print_err("Incomplete if; all text was ignored after line ");
13427 @.Incomplete if...@>
13428       mp_print_int(mp, mp->warning_info);
13429       help3("A forbidden `outer' token occurred in skipped text.")
13430         ("This kind of error happens when you say `if...' and forget")
13431         ("the matching `fi'. I've inserted a `fi'; this might work.");
13432       if ( mp->cur_sym==0 ) 
13433         mp->help_line[2]="The file ended while I was skipping conditional text.";
13434       mp->cur_sym=frozen_fi; mp_ins_error(mp);
13435     }
13436     mp->deletions_allowed=true; 
13437         return false;
13438   }
13439 }
13440
13441 @ @<Check if the file has ended while flushing \TeX\ material and set...@>=
13442 if ( mp->cur_sym!=0 ) { 
13443    return true;
13444 } else { 
13445   mp->deletions_allowed=false;
13446   print_err("TeX mode didn't end; all text was ignored after line ");
13447   mp_print_int(mp, mp->warning_info);
13448   help2("The file ended while I was looking for the `etex' to")
13449     ("finish this TeX material.  I've inserted `etex' now.");
13450   mp->cur_sym = frozen_etex;
13451   mp_ins_error(mp);
13452   mp->deletions_allowed=true;
13453   return false;
13454 }
13455
13456 @ @<Back up an outer symbolic token so that it can be reread@>=
13457 if ( mp->cur_sym!=0 ) {
13458   p=mp_get_avail(mp); info(p)=mp->cur_sym;
13459   back_list(p); /* prepare to read the symbolic token again */
13460 }
13461
13462 @ @<Tell the user what has run away...@>=
13463
13464   mp_runaway(mp); /* print the definition-so-far */
13465   if ( mp->cur_sym==0 ) {
13466     print_err("File ended");
13467 @.File ended while scanning...@>
13468   } else { 
13469     print_err("Forbidden token found");
13470 @.Forbidden token found...@>
13471   }
13472   mp_print(mp, " while scanning ");
13473   help4("I suspect you have forgotten an `enddef',")
13474     ("causing me to read past where you wanted me to stop.")
13475     ("I'll try to recover; but if the error is serious,")
13476     ("you'd better type `E' or `X' now and fix your file.");
13477   switch (mp->scanner_status) {
13478     @<Complete the error message,
13479       and set |cur_sym| to a token that might help recover from the error@>
13480   } /* there are no other cases */
13481   mp_ins_error(mp);
13482 }
13483
13484 @ As we consider various kinds of errors, it is also appropriate to
13485 change the first line of the help message just given; |help_line[3]|
13486 points to the string that might be changed.
13487
13488 @<Complete the error message,...@>=
13489 case flushing: 
13490   mp_print(mp, "to the end of the statement");
13491   mp->help_line[3]="A previous error seems to have propagated,";
13492   mp->cur_sym=frozen_semicolon;
13493   break;
13494 case absorbing: 
13495   mp_print(mp, "a text argument");
13496   mp->help_line[3]="It seems that a right delimiter was left out,";
13497   if ( mp->warning_info==0 ) {
13498     mp->cur_sym=frozen_end_group;
13499   } else { 
13500     mp->cur_sym=frozen_right_delimiter;
13501     equiv(frozen_right_delimiter)=mp->warning_info;
13502   }
13503   break;
13504 case var_defining:
13505 case op_defining: 
13506   mp_print(mp, "the definition of ");
13507   if ( mp->scanner_status==op_defining ) 
13508      mp_print_text(mp->warning_info);
13509   else 
13510      mp_print_variable_name(mp, mp->warning_info);
13511   mp->cur_sym=frozen_end_def;
13512   break;
13513 case loop_defining: 
13514   mp_print(mp, "the text of a "); 
13515   mp_print_text(mp->warning_info);
13516   mp_print(mp, " loop");
13517   mp->help_line[3]="I suspect you have forgotten an `endfor',";
13518   mp->cur_sym=frozen_end_for;
13519   break;
13520
13521 @ The |runaway| procedure displays the first part of the text that occurred
13522 when \MP\ began its special |scanner_status|, if that text has been saved.
13523
13524 @<Declare the procedure called |runaway|@>=
13525 void mp_runaway (MP mp) { 
13526   if ( mp->scanner_status>flushing ) { 
13527      mp_print_nl(mp, "Runaway ");
13528          switch (mp->scanner_status) { 
13529          case absorbing: mp_print(mp, "text?"); break;
13530          case var_defining: 
13531      case op_defining: mp_print(mp,"definition?"); break;
13532      case loop_defining: mp_print(mp, "loop?"); break;
13533      } /* there are no other cases */
13534      mp_print_ln(mp); 
13535      mp_show_token_list(mp, link(hold_head),null,mp->error_line-10,0);
13536   }
13537 }
13538
13539 @ We need to mention a procedure that may be called by |get_next|.
13540
13541 @<Declarations@>= 
13542 void mp_firm_up_the_line (MP mp);
13543
13544 @ And now we're ready to take the plunge into |get_next| itself.
13545 Note that the behavior depends on the |scanner_status| because percent signs
13546 and double quotes need to be passed over when skipping TeX material.
13547
13548 @c 
13549 void mp_get_next (MP mp) {
13550   /* sets |cur_cmd|, |cur_mod|, |cur_sym| to next token */
13551 @^inner loop@>
13552   /*restart*/ /* go here to get the next input token */
13553   /*exit*/ /* go here when the next input token has been got */
13554   /*|common_ending|*/ /* go here to finish getting a symbolic token */
13555   /*found*/ /* go here when the end of a symbolic token has been found */
13556   /*switch*/ /* go here to branch on the class of an input character */
13557   /*|start_numeric_token|,|start_decimal_token|,|fin_numeric_token|,|done|*/
13558     /* go here at crucial stages when scanning a number */
13559   int k; /* an index into |buffer| */
13560   ASCII_code c; /* the current character in the buffer */
13561   ASCII_code class; /* its class number */
13562   integer n,f; /* registers for decimal-to-binary conversion */
13563 RESTART: 
13564   mp->cur_sym=0;
13565   if ( file_state ) {
13566     @<Input from external file; |goto restart| if no input found,
13567     or |return| if a non-symbolic token is found@>;
13568   } else {
13569     @<Input from token list; |goto restart| if end of list or
13570       if a parameter needs to be expanded,
13571       or |return| if a non-symbolic token is found@>;
13572   }
13573 COMMON_ENDING: 
13574   @<Finish getting the symbolic token in |cur_sym|;
13575    |goto restart| if it is illegal@>;
13576 }
13577
13578 @ When a symbolic token is declared to be `\&{outer}', its command code
13579 is increased by |outer_tag|.
13580 @^inner loop@>
13581
13582 @<Finish getting the symbolic token in |cur_sym|...@>=
13583 mp->cur_cmd=eq_type(mp->cur_sym); mp->cur_mod=equiv(mp->cur_sym);
13584 if ( mp->cur_cmd>=outer_tag ) {
13585   if ( mp_check_outer_validity(mp) ) 
13586     mp->cur_cmd=mp->cur_cmd-outer_tag;
13587   else 
13588     goto RESTART;
13589 }
13590
13591 @ A percent sign appears in |buffer[limit]|; this makes it unnecessary
13592 to have a special test for end-of-line.
13593 @^inner loop@>
13594
13595 @<Input from external file;...@>=
13596
13597 SWITCH: 
13598   c=mp->buffer[loc]; incr(loc); class=mp->char_class[c];
13599   switch (class) {
13600   case digit_class: goto START_NUMERIC_TOKEN; break;
13601   case period_class: 
13602     class=mp->char_class[mp->buffer[loc]];
13603     if ( class>period_class ) {
13604       goto SWITCH;
13605     } else if ( class<period_class ) { /* |class=digit_class| */
13606       n=0; goto START_DECIMAL_TOKEN;
13607     }
13608 @:. }{\..\ token@>
13609     break;
13610   case space_class: goto SWITCH; break;
13611   case percent_class: 
13612     if ( mp->scanner_status==tex_flushing ) {
13613       if ( loc<limit ) goto SWITCH;
13614     }
13615     @<Move to next line of file, or |goto restart| if there is no next line@>;
13616     check_interrupt;
13617     goto SWITCH;
13618     break;
13619   case string_class: 
13620     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13621     else @<Get a string token and |return|@>;
13622     break;
13623   case isolated_classes: 
13624     k=loc-1; goto FOUND; break;
13625   case invalid_class: 
13626     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13627     else @<Decry the invalid character and |goto restart|@>;
13628     break;
13629   default: break; /* letters, etc. */
13630   }
13631   k=loc-1;
13632   while ( mp->char_class[mp->buffer[loc]]==class ) incr(loc);
13633   goto FOUND;
13634 START_NUMERIC_TOKEN:
13635   @<Get the integer part |n| of a numeric token;
13636     set |f:=0| and |goto fin_numeric_token| if there is no decimal point@>;
13637 START_DECIMAL_TOKEN:
13638   @<Get the fraction part |f| of a numeric token@>;
13639 FIN_NUMERIC_TOKEN:
13640   @<Pack the numeric and fraction parts of a numeric token
13641     and |return|@>;
13642 FOUND: 
13643   mp->cur_sym=mp_id_lookup(mp, k,loc-k);
13644 }
13645
13646 @ We go to |restart| instead of to |SWITCH|, because |state| might equal
13647 |token_list| after the error has been dealt with
13648 (cf.\ |clear_for_error_prompt|).
13649
13650 @<Decry the invalid...@>=
13651
13652   print_err("Text line contains an invalid character");
13653 @.Text line contains...@>
13654   help2("A funny symbol that I can\'t read has just been input.")
13655     ("Continue, and I'll forget that it ever happened.");
13656   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13657   goto RESTART;
13658 }
13659
13660 @ @<Get a string token and |return|@>=
13661
13662   if ( mp->buffer[loc]=='"' ) {
13663     mp->cur_mod=rts("");
13664   } else { 
13665     k=loc; mp->buffer[limit+1]='"';
13666     do {  
13667      incr(loc);
13668     } while (mp->buffer[loc]!='"');
13669     if ( loc>limit ) {
13670       @<Decry the missing string delimiter and |goto restart|@>;
13671     }
13672     if ( loc==k+1 ) {
13673       mp->cur_mod=mp->buffer[k];
13674     } else { 
13675       str_room(loc-k);
13676       do {  
13677         append_char(mp->buffer[k]); incr(k);
13678       } while (k!=loc);
13679       mp->cur_mod=mp_make_string(mp);
13680     }
13681   }
13682   incr(loc); mp->cur_cmd=string_token; 
13683   return;
13684 }
13685
13686 @ We go to |restart| after this error message, not to |SWITCH|,
13687 because the |clear_for_error_prompt| routine might have reinstated
13688 |token_state| after |error| has finished.
13689
13690 @<Decry the missing string delimiter and |goto restart|@>=
13691
13692   loc=limit; /* the next character to be read on this line will be |"%"| */
13693   print_err("Incomplete string token has been flushed");
13694 @.Incomplete string token...@>
13695   help3("Strings should finish on the same line as they began.")
13696     ("I've deleted the partial string; you might want to")
13697     ("insert another by typing, e.g., `I\"new string\"'.");
13698   mp->deletions_allowed=false; mp_error(mp);
13699   mp->deletions_allowed=true; 
13700   goto RESTART;
13701 }
13702
13703 @ @<Get the integer part |n| of a numeric token...@>=
13704 n=c-'0';
13705 while ( mp->char_class[mp->buffer[loc]]==digit_class ) {
13706   if ( n<32768 ) n=10*n+mp->buffer[loc]-'0';
13707   incr(loc);
13708 }
13709 if ( mp->buffer[loc]=='.' ) 
13710   if ( mp->char_class[mp->buffer[loc+1]]==digit_class ) 
13711     goto DONE;
13712 f=0; 
13713 goto FIN_NUMERIC_TOKEN;
13714 DONE: incr(loc)
13715
13716 @ @<Get the fraction part |f| of a numeric token@>=
13717 k=0;
13718 do { 
13719   if ( k<17 ) { /* digits for |k>=17| cannot affect the result */
13720     mp->dig[k]=mp->buffer[loc]-'0'; incr(k);
13721   }
13722   incr(loc);
13723 } while (mp->char_class[mp->buffer[loc]]==digit_class);
13724 f=mp_round_decimals(mp, k);
13725 if ( f==unity ) {
13726   incr(n); f=0;
13727 }
13728
13729 @ @<Pack the numeric and fraction parts of a numeric token and |return|@>=
13730 if ( n<32768 ) {
13731   @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>;
13732 } else if ( mp->scanner_status!=tex_flushing ) {
13733   print_err("Enormous number has been reduced");
13734 @.Enormous number...@>
13735   help2("I can\'t handle numbers bigger than 32767.99998;")
13736     ("so I've changed your constant to that maximum amount.");
13737   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13738   mp->cur_mod=el_gordo;
13739 }
13740 mp->cur_cmd=numeric_token; return
13741
13742 @ @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>=
13743
13744   mp->cur_mod=n*unity+f;
13745   if ( mp->cur_mod>=fraction_one ) {
13746     if ( (mp->internal[mp_warning_check]>0) &&
13747          (mp->scanner_status!=tex_flushing) ) {
13748       print_err("Number is too large (");
13749       mp_print_scaled(mp, mp->cur_mod);
13750       mp_print_char(mp, ')');
13751       help3("It is at least 4096. Continue and I'll try to cope")
13752       ("with that big value; but it might be dangerous.")
13753       ("(Set warningcheck:=0 to suppress this message.)");
13754       mp_error(mp);
13755     }
13756   }
13757 }
13758
13759 @ Let's consider now what happens when |get_next| is looking at a token list.
13760 @^inner loop@>
13761
13762 @<Input from token list;...@>=
13763 if ( loc>=mp->hi_mem_min ) { /* one-word token */
13764   mp->cur_sym=info(loc); loc=link(loc); /* move to next */
13765   if ( mp->cur_sym>=expr_base ) {
13766     if ( mp->cur_sym>=suffix_base ) {
13767       @<Insert a suffix or text parameter and |goto restart|@>;
13768     } else { 
13769       mp->cur_cmd=capsule_token;
13770       mp->cur_mod=mp->param_stack[param_start+mp->cur_sym-(expr_base)];
13771       mp->cur_sym=0; return;
13772     }
13773   }
13774 } else if ( loc>null ) {
13775   @<Get a stored numeric or string or capsule token and |return|@>
13776 } else { /* we are done with this token list */
13777   mp_end_token_list(mp); goto RESTART; /* resume previous level */
13778 }
13779
13780 @ @<Insert a suffix or text parameter...@>=
13781
13782   if ( mp->cur_sym>=text_base ) mp->cur_sym=mp->cur_sym-mp->param_size;
13783   /* |param_size=text_base-suffix_base| */
13784   mp_begin_token_list(mp,
13785                       mp->param_stack[param_start+mp->cur_sym-(suffix_base)],
13786                       parameter);
13787   goto RESTART;
13788 }
13789
13790 @ @<Get a stored numeric or string or capsule token...@>=
13791
13792   if ( name_type(loc)==mp_token ) {
13793     mp->cur_mod=value(loc);
13794     if ( type(loc)==mp_known ) {
13795       mp->cur_cmd=numeric_token;
13796     } else { 
13797       mp->cur_cmd=string_token; add_str_ref(mp->cur_mod);
13798     }
13799   } else { 
13800     mp->cur_mod=loc; mp->cur_cmd=capsule_token;
13801   };
13802   loc=link(loc); return;
13803 }
13804
13805 @ All of the easy branches of |get_next| have now been taken care of.
13806 There is one more branch.
13807
13808 @<Move to next line of file, or |goto restart|...@>=
13809 if ( name>max_spec_src ) {
13810   @<Read next line of file into |buffer|, or
13811     |goto restart| if the file has ended@>;
13812 } else { 
13813   if ( mp->input_ptr>0 ) {
13814      /* text was inserted during error recovery or by \&{scantokens} */
13815     mp_end_file_reading(mp); goto RESTART; /* resume previous level */
13816   }
13817   if ( mp->selector<log_only || mp->selector>=write_file) mp_open_log_file(mp);
13818   if ( mp->interaction>mp_nonstop_mode ) {
13819     if ( limit==start ) /* previous line was empty */
13820       mp_print_nl(mp, "(Please type a command or say `end')");
13821 @.Please type...@>
13822     mp_print_ln(mp); mp->first=start;
13823     prompt_input("*"); /* input on-line into |buffer| */
13824 @.*\relax@>
13825     limit=mp->last; mp->buffer[limit]='%';
13826     mp->first=limit+1; loc=start;
13827   } else {
13828     mp_fatal_error(mp, "*** (job aborted, no legal end found)");
13829 @.job aborted@>
13830     /* nonstop mode, which is intended for overnight batch processing,
13831     never waits for on-line input */
13832   }
13833 }
13834
13835 @ The global variable |force_eof| is normally |false|; it is set |true|
13836 by an \&{endinput} command.
13837
13838 @<Glob...@>=
13839 boolean force_eof; /* should the next \&{input} be aborted early? */
13840
13841 @ We must decrement |loc| in order to leave the buffer in a valid state
13842 when an error condition causes us to |goto restart| without calling
13843 |end_file_reading|.
13844
13845 @<Read next line of file into |buffer|, or
13846   |goto restart| if the file has ended@>=
13847
13848   incr(line); mp->first=start;
13849   if ( ! mp->force_eof ) {
13850     if ( mp_input_ln(mp, cur_file,true) ) /* not end of file */
13851       mp_firm_up_the_line(mp); /* this sets |limit| */
13852     else 
13853       mp->force_eof=true;
13854   };
13855   if ( mp->force_eof ) {
13856     mp->force_eof=false;
13857     decr(loc);
13858     if ( mpx_reading ) {
13859       @<Complain that the \.{MPX} file ended unexpectly; then set
13860         |cur_sym:=frozen_mpx_break| and |goto comon_ending|@>;
13861     } else { 
13862       mp_print_char(mp, ')'); decr(mp->open_parens);
13863       update_terminal; /* show user that file has been read */
13864       mp_end_file_reading(mp); /* resume previous level */
13865       if ( mp_check_outer_validity(mp) ) goto  RESTART;  
13866       else goto RESTART;
13867     }
13868   }
13869   mp->buffer[limit]='%'; mp->first=limit+1; loc=start; /* ready to read */
13870 }
13871
13872 @ We should never actually come to the end of an \.{MPX} file because such
13873 files should have an \&{mpxbreak} after the translation of the last
13874 \&{btex}$\,\ldots\,$\&{etex} block.
13875
13876 @<Complain that the \.{MPX} file ended unexpectly; then set...@>=
13877
13878   mp->mpx_name[index]=finished;
13879   print_err("mpx file ended unexpectedly");
13880   help4("The file had too few picture expressions for btex...etex")
13881     ("blocks.  Such files are normally generated automatically")
13882     ("but this one got messed up.  You might want to insert a")
13883     ("picture expression now.");
13884   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13885   mp->cur_sym=frozen_mpx_break; goto COMMON_ENDING;
13886 }
13887
13888 @ Sometimes we want to make it look as though we have just read a blank line
13889 without really doing so.
13890
13891 @<Put an empty line in the input buffer@>=
13892 mp->last=mp->first; limit=mp->last; /* simulate |input_ln| and |firm_up_the_line| */
13893 mp->buffer[limit]='%'; mp->first=limit+1; loc=start
13894
13895 @ If the user has set the |mp_pausing| parameter to some positive value,
13896 and if nonstop mode has not been selected, each line of input is displayed
13897 on the terminal and the transcript file, followed by `\.{=>}'.
13898 \MP\ waits for a response. If the response is null (i.e., if nothing is
13899 typed except perhaps a few blank spaces), the original
13900 line is accepted as it stands; otherwise the line typed is
13901 used instead of the line in the file.
13902
13903 @c void mp_firm_up_the_line (MP mp) {
13904   size_t k; /* an index into |buffer| */
13905   limit=mp->last;
13906   if ( mp->internal[mp_pausing]>0 ) if ( mp->interaction>mp_nonstop_mode ) {
13907     wake_up_terminal; mp_print_ln(mp);
13908     if ( start<limit ) {
13909       for (k=(size_t)start;k<=(size_t)(limit-1);k++) {
13910         mp_print_str(mp, mp->buffer[k]);
13911       } 
13912     }
13913     mp->first=limit; prompt_input("=>"); /* wait for user response */
13914 @.=>@>
13915     if ( mp->last>mp->first ) {
13916       for (k=mp->first;k<=mp->last-1;k++) { /* move line down in buffer */
13917         mp->buffer[k+start-mp->first]=mp->buffer[k];
13918       }
13919       limit=start+mp->last-mp->first;
13920     }
13921   }
13922 }
13923
13924 @* \[30] Dealing with \TeX\ material.
13925 The \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}$\,\ldots\,$\&{etex}
13926 features need to be implemented at a low level in the scanning process
13927 so that \MP\ can stay in synch with the a preprocessor that treats
13928 blocks of \TeX\ material as they occur in the input file without trying
13929 to expand \MP\ macros.  Thus we need a special version of |get_next|
13930 that does not expand macros and such but does handle \&{btex},
13931 \&{verbatimtex}, etc.
13932
13933 The special version of |get_next| is called |get_t_next|.  It works by flushing
13934 \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}\allowbreak
13935 $\,\ldots\,$\&{etex} blocks, switching to the \.{MPX} file when it sees
13936 \&{btex}, and switching back when it sees \&{mpxbreak}.
13937
13938 @d btex_code 0
13939 @d verbatim_code 1
13940
13941 @ @<Put each...@>=
13942 mp_primitive(mp, "btex",start_tex,btex_code);
13943 @:btex_}{\&{btex} primitive@>
13944 mp_primitive(mp, "verbatimtex",start_tex,verbatim_code);
13945 @:verbatimtex_}{\&{verbatimtex} primitive@>
13946 mp_primitive(mp, "etex",etex_marker,0); mp->eqtb[frozen_etex]=mp->eqtb[mp->cur_sym];
13947 @:etex_}{\&{etex} primitive@>
13948 mp_primitive(mp, "mpxbreak",mpx_break,0); mp->eqtb[frozen_mpx_break]=mp->eqtb[mp->cur_sym];
13949 @:mpx_break_}{\&{mpxbreak} primitive@>
13950
13951 @ @<Cases of |print_cmd...@>=
13952 case start_tex: if ( m==btex_code ) mp_print(mp, "btex");
13953   else mp_print(mp, "verbatimtex"); break;
13954 case etex_marker: mp_print(mp, "etex"); break;
13955 case mpx_break: mp_print(mp, "mpxbreak"); break;
13956
13957 @ Actually, |get_t_next| is a macro that avoids procedure overhead except
13958 in the unusual case where \&{btex}, \&{verbatimtex}, \&{etex}, or \&{mpxbreak}
13959 is encountered.
13960
13961 @d get_t_next {mp_get_next(mp); if ( mp->cur_cmd<=max_pre_command ) mp_t_next(mp); }
13962
13963 @<Declarations@>=
13964 void mp_start_mpx_input (MP mp);
13965
13966 @ @c 
13967 void mp_t_next (MP mp) {
13968   int old_status; /* saves the |scanner_status| */
13969   integer old_info; /* saves the |warning_info| */
13970   while ( mp->cur_cmd<=max_pre_command ) {
13971     if ( mp->cur_cmd==mpx_break ) {
13972       if ( ! file_state || (mp->mpx_name[index]==absent) ) {
13973         @<Complain about a misplaced \&{mpxbreak}@>;
13974       } else { 
13975         mp_end_mpx_reading(mp); 
13976         goto TEX_FLUSH;
13977       }
13978     } else if ( mp->cur_cmd==start_tex ) {
13979       if ( token_state || (name<=max_spec_src) ) {
13980         @<Complain that we are not reading a file@>;
13981       } else if ( mpx_reading ) {
13982         @<Complain that \.{MPX} files cannot contain \TeX\ material@>;
13983       } else if ( (mp->cur_mod!=verbatim_code)&&
13984                   (mp->mpx_name[index]!=finished) ) {
13985         if ( ! mp_begin_mpx_reading(mp) ) mp_start_mpx_input(mp);
13986       } else {
13987         goto TEX_FLUSH;
13988       }
13989     } else {
13990        @<Complain about a misplaced \&{etex}@>;
13991     }
13992     goto COMMON_ENDING;
13993   TEX_FLUSH: 
13994     @<Flush the \TeX\ material@>;
13995   COMMON_ENDING: 
13996     mp_get_next(mp);
13997   }
13998 }
13999
14000 @ We could be in the middle of an operation such as skipping false conditional
14001 text when \TeX\ material is encountered, so we must be careful to save the
14002 |scanner_status|.
14003
14004 @<Flush the \TeX\ material@>=
14005 old_status=mp->scanner_status;
14006 old_info=mp->warning_info;
14007 mp->scanner_status=tex_flushing;
14008 mp->warning_info=line;
14009 do {  mp_get_next(mp); } while (mp->cur_cmd!=etex_marker);
14010 mp->scanner_status=old_status;
14011 mp->warning_info=old_info
14012
14013 @ @<Complain that \.{MPX} files cannot contain \TeX\ material@>=
14014 { print_err("An mpx file cannot contain btex or verbatimtex blocks");
14015 help4("This file contains picture expressions for btex...etex")
14016   ("blocks.  Such files are normally generated automatically")
14017   ("but this one seems to be messed up.  I'll just keep going")
14018   ("and hope for the best.");
14019 mp_error(mp);
14020 }
14021
14022 @ @<Complain that we are not reading a file@>=
14023 { print_err("You can only use `btex' or `verbatimtex' in a file");
14024 help3("I'll have to ignore this preprocessor command because it")
14025   ("only works when there is a file to preprocess.  You might")
14026   ("want to delete everything up to the next `etex`.");
14027 mp_error(mp);
14028 }
14029
14030 @ @<Complain about a misplaced \&{mpxbreak}@>=
14031 { print_err("Misplaced mpxbreak");
14032 help2("I'll ignore this preprocessor command because it")
14033   ("doesn't belong here");
14034 mp_error(mp);
14035 }
14036
14037 @ @<Complain about a misplaced \&{etex}@>=
14038 { print_err("Extra etex will be ignored");
14039 help1("There is no btex or verbatimtex for this to match");
14040 mp_error(mp);
14041 }
14042
14043 @* \[31] Scanning macro definitions.
14044 \MP\ has a variety of ways to tuck tokens away into token lists for later
14045 use: Macros can be defined with \&{def}, \&{vardef}, \&{primarydef}, etc.;
14046 repeatable code can be defined with \&{for}, \&{forever}, \&{forsuffixes}.
14047 All such operations are handled by the routines in this part of the program.
14048
14049 The modifier part of each command code is zero for the ``ending delimiters''
14050 like \&{enddef} and \&{endfor}.
14051
14052 @d start_def 1 /* command modifier for \&{def} */
14053 @d var_def 2 /* command modifier for \&{vardef} */
14054 @d end_def 0 /* command modifier for \&{enddef} */
14055 @d start_forever 1 /* command modifier for \&{forever} */
14056 @d end_for 0 /* command modifier for \&{endfor} */
14057
14058 @<Put each...@>=
14059 mp_primitive(mp, "def",macro_def,start_def);
14060 @:def_}{\&{def} primitive@>
14061 mp_primitive(mp, "vardef",macro_def,var_def);
14062 @:var_def_}{\&{vardef} primitive@>
14063 mp_primitive(mp, "primarydef",macro_def,secondary_primary_macro);
14064 @:primary_def_}{\&{primarydef} primitive@>
14065 mp_primitive(mp, "secondarydef",macro_def,tertiary_secondary_macro);
14066 @:secondary_def_}{\&{secondarydef} primitive@>
14067 mp_primitive(mp, "tertiarydef",macro_def,expression_tertiary_macro);
14068 @:tertiary_def_}{\&{tertiarydef} primitive@>
14069 mp_primitive(mp, "enddef",macro_def,end_def); mp->eqtb[frozen_end_def]=mp->eqtb[mp->cur_sym];
14070 @:end_def_}{\&{enddef} primitive@>
14071 @#
14072 mp_primitive(mp, "for",iteration,expr_base);
14073 @:for_}{\&{for} primitive@>
14074 mp_primitive(mp, "forsuffixes",iteration,suffix_base);
14075 @:for_suffixes_}{\&{forsuffixes} primitive@>
14076 mp_primitive(mp, "forever",iteration,start_forever);
14077 @:forever_}{\&{forever} primitive@>
14078 mp_primitive(mp, "endfor",iteration,end_for); mp->eqtb[frozen_end_for]=mp->eqtb[mp->cur_sym];
14079 @:end_for_}{\&{endfor} primitive@>
14080
14081 @ @<Cases of |print_cmd...@>=
14082 case macro_def:
14083   if ( m<=var_def ) {
14084     if ( m==start_def ) mp_print(mp, "def");
14085     else if ( m<start_def ) mp_print(mp, "enddef");
14086     else mp_print(mp, "vardef");
14087   } else if ( m==secondary_primary_macro ) { 
14088     mp_print(mp, "primarydef");
14089   } else if ( m==tertiary_secondary_macro ) { 
14090     mp_print(mp, "secondarydef");
14091   } else { 
14092     mp_print(mp, "tertiarydef");
14093   }
14094   break;
14095 case iteration: 
14096   if ( m<=start_forever ) {
14097     if ( m==start_forever ) mp_print(mp, "forever"); 
14098     else mp_print(mp, "endfor");
14099   } else if ( m==expr_base ) {
14100     mp_print(mp, "for"); 
14101   } else { 
14102     mp_print(mp, "forsuffixes");
14103   }
14104   break;
14105
14106 @ Different macro-absorbing operations have different syntaxes, but they
14107 also have a lot in common. There is a list of special symbols that are to
14108 be replaced by parameter tokens; there is a special command code that
14109 ends the definition; the quotation conventions are identical.  Therefore
14110 it makes sense to have most of the work done by a single subroutine. That
14111 subroutine is called |scan_toks|.
14112
14113 The first parameter to |scan_toks| is the command code that will
14114 terminate scanning (either |macro_def|, |loop_repeat|, or |iteration|).
14115
14116 The second parameter, |subst_list|, points to a (possibly empty) list
14117 of two-word nodes whose |info| and |value| fields specify symbol tokens
14118 before and after replacement. The list will be returned to free storage
14119 by |scan_toks|.
14120
14121 The third parameter is simply appended to the token list that is built.
14122 And the final parameter tells how many of the special operations
14123 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#} are to be replaced by suffix parameters.
14124 When such parameters are present, they are called \.{(SUFFIX0)},
14125 \.{(SUFFIX1)}, and \.{(SUFFIX2)}.
14126
14127 @c pointer mp_scan_toks (MP mp,command_code terminator, pointer 
14128   subst_list, pointer tail_end, small_number suffix_count) {
14129   pointer p; /* tail of the token list being built */
14130   pointer q; /* temporary for link management */
14131   integer balance; /* left delimiters minus right delimiters */
14132   p=hold_head; balance=1; link(hold_head)=null;
14133   while (1) { 
14134     get_t_next;
14135     if ( mp->cur_sym>0 ) {
14136       @<Substitute for |cur_sym|, if it's on the |subst_list|@>;
14137       if ( mp->cur_cmd==terminator ) {
14138         @<Adjust the balance; |break| if it's zero@>;
14139       } else if ( mp->cur_cmd==macro_special ) {
14140         @<Handle quoted symbols, \.{\#\AT!}, \.{\AT!}, or \.{\AT!\#}@>;
14141       }
14142     }
14143     link(p)=mp_cur_tok(mp); p=link(p);
14144   }
14145   link(p)=tail_end; mp_flush_node_list(mp, subst_list);
14146   return link(hold_head);
14147 }
14148
14149 @ @<Substitute for |cur_sym|...@>=
14150
14151   q=subst_list;
14152   while ( q!=null ) {
14153     if ( info(q)==mp->cur_sym ) {
14154       mp->cur_sym=value(q); mp->cur_cmd=relax; break;
14155     }
14156     q=link(q);
14157   }
14158 }
14159
14160 @ @<Adjust the balance; |break| if it's zero@>=
14161 if ( mp->cur_mod>0 ) {
14162   incr(balance);
14163 } else { 
14164   decr(balance);
14165   if ( balance==0 )
14166     break;
14167 }
14168
14169 @ Four commands are intended to be used only within macro texts: \&{quote},
14170 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#}. They are variants of a single command
14171 code called |macro_special|.
14172
14173 @d quote 0 /* |macro_special| modifier for \&{quote} */
14174 @d macro_prefix 1 /* |macro_special| modifier for \.{\#\AT!} */
14175 @d macro_at 2 /* |macro_special| modifier for \.{\AT!} */
14176 @d macro_suffix 3 /* |macro_special| modifier for \.{\AT!\#} */
14177
14178 @<Put each...@>=
14179 mp_primitive(mp, "quote",macro_special,quote);
14180 @:quote_}{\&{quote} primitive@>
14181 mp_primitive(mp, "#@@",macro_special,macro_prefix);
14182 @:]]]\#\AT!_}{\.{\#\AT!} primitive@>
14183 mp_primitive(mp, "@@",macro_special,macro_at);
14184 @:]]]\AT!_}{\.{\AT!} primitive@>
14185 mp_primitive(mp, "@@#",macro_special,macro_suffix);
14186 @:]]]\AT!\#_}{\.{\AT!\#} primitive@>
14187
14188 @ @<Cases of |print_cmd...@>=
14189 case macro_special: 
14190   switch (m) {
14191   case macro_prefix: mp_print(mp, "#@@"); break;
14192   case macro_at: mp_print_char(mp, '@@'); break;
14193   case macro_suffix: mp_print(mp, "@@#"); break;
14194   default: mp_print(mp, "quote"); break;
14195   }
14196   break;
14197
14198 @ @<Handle quoted...@>=
14199
14200   if ( mp->cur_mod==quote ) { get_t_next; } 
14201   else if ( mp->cur_mod<=suffix_count ) 
14202     mp->cur_sym=suffix_base-1+mp->cur_mod;
14203 }
14204
14205 @ Here is a routine that's used whenever a token will be redefined. If
14206 the user's token is unredefinable, the `|frozen_inaccessible|' token is
14207 substituted; the latter is redefinable but essentially impossible to use,
14208 hence \MP's tables won't get fouled up.
14209
14210 @c void mp_get_symbol (MP mp) { /* sets |cur_sym| to a safe symbol */
14211 RESTART: 
14212   get_t_next;
14213   if ( (mp->cur_sym==0)||(mp->cur_sym>frozen_inaccessible) ) {
14214     print_err("Missing symbolic token inserted");
14215 @.Missing symbolic token...@>
14216     help3("Sorry: You can\'t redefine a number, string, or expr.")
14217       ("I've inserted an inaccessible symbol so that your")
14218       ("definition will be completed without mixing me up too badly.");
14219     if ( mp->cur_sym>0 )
14220       mp->help_line[2]="Sorry: You can\'t redefine my error-recovery tokens.";
14221     else if ( mp->cur_cmd==string_token ) 
14222       delete_str_ref(mp->cur_mod);
14223     mp->cur_sym=frozen_inaccessible; mp_ins_error(mp); goto RESTART;
14224   }
14225 }
14226
14227 @ Before we actually redefine a symbolic token, we need to clear away its
14228 former value, if it was a variable. The following stronger version of
14229 |get_symbol| does that.
14230
14231 @c void mp_get_clear_symbol (MP mp) { 
14232   mp_get_symbol(mp); mp_clear_symbol(mp, mp->cur_sym,false);
14233 }
14234
14235 @ Here's another little subroutine; it checks that an equals sign
14236 or assignment sign comes along at the proper place in a macro definition.
14237
14238 @c void mp_check_equals (MP mp) { 
14239   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
14240      mp_missing_err(mp, "=");
14241 @.Missing `='@>
14242     help5("The next thing in this `def' should have been `=',")
14243       ("because I've already looked at the definition heading.")
14244       ("But don't worry; I'll pretend that an equals sign")
14245       ("was present. Everything from here to `enddef'")
14246       ("will be the replacement text of this macro.");
14247     mp_back_error(mp);
14248   }
14249 }
14250
14251 @ A \&{primarydef}, \&{secondarydef}, or \&{tertiarydef} is rather easily
14252 handled now that we have |scan_toks|.  In this case there are
14253 two parameters, which will be \.{EXPR0} and \.{EXPR1} (i.e.,
14254 |expr_base| and |expr_base+1|).
14255
14256 @c void mp_make_op_def (MP mp) {
14257   command_code m; /* the type of definition */
14258   pointer p,q,r; /* for list manipulation */
14259   m=mp->cur_mod;
14260   mp_get_symbol(mp); q=mp_get_node(mp, token_node_size);
14261   info(q)=mp->cur_sym; value(q)=expr_base;
14262   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym;
14263   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
14264   info(p)=mp->cur_sym; value(p)=expr_base+1; link(p)=q;
14265   get_t_next; mp_check_equals(mp);
14266   mp->scanner_status=op_defining; q=mp_get_avail(mp); ref_count(q)=null;
14267   r=mp_get_avail(mp); link(q)=r; info(r)=general_macro;
14268   link(r)=mp_scan_toks(mp, macro_def,p,null,0);
14269   mp->scanner_status=normal; eq_type(mp->warning_info)=m;
14270   equiv(mp->warning_info)=q; mp_get_x_next(mp);
14271 }
14272
14273 @ Parameters to macros are introduced by the keywords \&{expr},
14274 \&{suffix}, \&{text}, \&{primary}, \&{secondary}, and \&{tertiary}.
14275
14276 @<Put each...@>=
14277 mp_primitive(mp, "expr",param_type,expr_base);
14278 @:expr_}{\&{expr} primitive@>
14279 mp_primitive(mp, "suffix",param_type,suffix_base);
14280 @:suffix_}{\&{suffix} primitive@>
14281 mp_primitive(mp, "text",param_type,text_base);
14282 @:text_}{\&{text} primitive@>
14283 mp_primitive(mp, "primary",param_type,primary_macro);
14284 @:primary_}{\&{primary} primitive@>
14285 mp_primitive(mp, "secondary",param_type,secondary_macro);
14286 @:secondary_}{\&{secondary} primitive@>
14287 mp_primitive(mp, "tertiary",param_type,tertiary_macro);
14288 @:tertiary_}{\&{tertiary} primitive@>
14289
14290 @ @<Cases of |print_cmd...@>=
14291 case param_type:
14292   if ( m>=expr_base ) {
14293     if ( m==expr_base ) mp_print(mp, "expr");
14294     else if ( m==suffix_base ) mp_print(mp, "suffix");
14295     else mp_print(mp, "text");
14296   } else if ( m<secondary_macro ) {
14297     mp_print(mp, "primary");
14298   } else if ( m==secondary_macro ) {
14299     mp_print(mp, "secondary");
14300   } else {
14301     mp_print(mp, "tertiary");
14302   }
14303   break;
14304
14305 @ Let's turn next to the more complex processing associated with \&{def}
14306 and \&{vardef}. When the following procedure is called, |cur_mod|
14307 should be either |start_def| or |var_def|.
14308
14309 @c @<Declare the procedure called |check_delimiter|@>;
14310 @<Declare the function called |scan_declared_variable|@>;
14311 void mp_scan_def (MP mp) {
14312   int m; /* the type of definition */
14313   int n; /* the number of special suffix parameters */
14314   int k; /* the total number of parameters */
14315   int c; /* the kind of macro we're defining */
14316   pointer r; /* parameter-substitution list */
14317   pointer q; /* tail of the macro token list */
14318   pointer p; /* temporary storage */
14319   halfword base; /* |expr_base|, |suffix_base|, or |text_base| */
14320   pointer l_delim,r_delim; /* matching delimiters */
14321   m=mp->cur_mod; c=general_macro; link(hold_head)=null;
14322   q=mp_get_avail(mp); ref_count(q)=null; r=null;
14323   @<Scan the token or variable to be defined;
14324     set |n|, |scanner_status|, and |warning_info|@>;
14325   k=n;
14326   if ( mp->cur_cmd==left_delimiter ) {
14327     @<Absorb delimited parameters, putting them into lists |q| and |r|@>;
14328   }
14329   if ( mp->cur_cmd==param_type ) {
14330     @<Absorb undelimited parameters, putting them into list |r|@>;
14331   }
14332   mp_check_equals(mp);
14333   p=mp_get_avail(mp); info(p)=c; link(q)=p;
14334   @<Attach the replacement text to the tail of node |p|@>;
14335   mp->scanner_status=normal; mp_get_x_next(mp);
14336 }
14337
14338 @ We don't put `|frozen_end_group|' into the replacement text of
14339 a \&{vardef}, because the user may want to redefine `\.{endgroup}'.
14340
14341 @<Attach the replacement text to the tail of node |p|@>=
14342 if ( m==start_def ) {
14343   link(p)=mp_scan_toks(mp, macro_def,r,null,n);
14344 } else { 
14345   q=mp_get_avail(mp); info(q)=mp->bg_loc; link(p)=q;
14346   p=mp_get_avail(mp); info(p)=mp->eg_loc;
14347   link(q)=mp_scan_toks(mp, macro_def,r,p,n);
14348 }
14349 if ( mp->warning_info==bad_vardef ) 
14350   mp_flush_token_list(mp, value(bad_vardef))
14351
14352 @ @<Glob...@>=
14353 int bg_loc;
14354 int eg_loc; /* hash addresses of `\.{begingroup}' and `\.{endgroup}' */
14355
14356 @ @<Scan the token or variable to be defined;...@>=
14357 if ( m==start_def ) {
14358   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym; get_t_next;
14359   mp->scanner_status=op_defining; n=0;
14360   eq_type(mp->warning_info)=defined_macro; equiv(mp->warning_info)=q;
14361 } else { 
14362   p=mp_scan_declared_variable(mp);
14363   mp_flush_variable(mp, equiv(info(p)),link(p),true);
14364   mp->warning_info=mp_find_variable(mp, p); mp_flush_list(mp, p);
14365   if ( mp->warning_info==null ) @<Change to `\.{a bad variable}'@>;
14366   mp->scanner_status=var_defining; n=2;
14367   if ( mp->cur_cmd==macro_special ) if ( mp->cur_mod==macro_suffix ) {/* \.{\AT!\#} */
14368     n=3; get_t_next;
14369   }
14370   type(mp->warning_info)=mp_unsuffixed_macro-2+n; value(mp->warning_info)=q;
14371 } /* |mp_suffixed_macro=mp_unsuffixed_macro+1| */
14372
14373 @ @<Change to `\.{a bad variable}'@>=
14374
14375   print_err("This variable already starts with a macro");
14376 @.This variable already...@>
14377   help2("After `vardef a' you can\'t say `vardef a.b'.")
14378     ("So I'll have to discard this definition.");
14379   mp_error(mp); mp->warning_info=bad_vardef;
14380 }
14381
14382 @ @<Initialize table entries...@>=
14383 name_type(bad_vardef)=mp_root; link(bad_vardef)=frozen_bad_vardef;
14384 equiv(frozen_bad_vardef)=bad_vardef; eq_type(frozen_bad_vardef)=tag_token;
14385
14386 @ @<Absorb delimited parameters, putting them into lists |q| and |r|@>=
14387 do {  
14388   l_delim=mp->cur_sym; r_delim=mp->cur_mod; get_t_next;
14389   if ( (mp->cur_cmd==param_type)&&(mp->cur_mod>=expr_base) ) {
14390    base=mp->cur_mod;
14391   } else { 
14392     print_err("Missing parameter type; `expr' will be assumed");
14393 @.Missing parameter type@>
14394     help1("You should've had `expr' or `suffix' or `text' here.");
14395     mp_back_error(mp); base=expr_base;
14396   }
14397   @<Absorb parameter tokens for type |base|@>;
14398   mp_check_delimiter(mp, l_delim,r_delim);
14399   get_t_next;
14400 } while (mp->cur_cmd==left_delimiter)
14401
14402 @ @<Absorb parameter tokens for type |base|@>=
14403 do { 
14404   link(q)=mp_get_avail(mp); q=link(q); info(q)=base+k;
14405   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size); 
14406   value(p)=base+k; info(p)=mp->cur_sym;
14407   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14408 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
14409   incr(k); link(p)=r; r=p; get_t_next;
14410 } while (mp->cur_cmd==comma)
14411
14412 @ @<Absorb undelimited parameters, putting them into list |r|@>=
14413
14414   p=mp_get_node(mp, token_node_size);
14415   if ( mp->cur_mod<expr_base ) {
14416     c=mp->cur_mod; value(p)=expr_base+k;
14417   } else { 
14418     value(p)=mp->cur_mod+k;
14419     if ( mp->cur_mod==expr_base ) c=expr_macro;
14420     else if ( mp->cur_mod==suffix_base ) c=suffix_macro;
14421     else c=text_macro;
14422   }
14423   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14424   incr(k); mp_get_symbol(mp); info(p)=mp->cur_sym; link(p)=r; r=p; get_t_next;
14425   if ( c==expr_macro ) if ( mp->cur_cmd==of_token ) {
14426     c=of_macro; p=mp_get_node(mp, token_node_size);
14427     if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14428     value(p)=expr_base+k; mp_get_symbol(mp); info(p)=mp->cur_sym;
14429     link(p)=r; r=p; get_t_next;
14430   }
14431 }
14432
14433 @* \[32] Expanding the next token.
14434 Only a few command codes |<min_command| can possibly be returned by
14435 |get_t_next|; in increasing order, they are
14436 |if_test|, |fi_or_else|, |input|, |iteration|, |repeat_loop|,
14437 |exit_test|, |relax|, |scan_tokens|, |expand_after|, and |defined_macro|.
14438
14439 \MP\ usually gets the next token of input by saying |get_x_next|. This is
14440 like |get_t_next| except that it keeps getting more tokens until
14441 finding |cur_cmd>=min_command|. In other words, |get_x_next| expands
14442 macros and removes conditionals or iterations or input instructions that
14443 might be present.
14444
14445 It follows that |get_x_next| might invoke itself recursively. In fact,
14446 there is massive recursion, since macro expansion can involve the
14447 scanning of arbitrarily complex expressions, which in turn involve
14448 macro expansion and conditionals, etc.
14449 @^recursion@>
14450
14451 Therefore it's necessary to declare a whole bunch of |forward|
14452 procedures at this point, and to insert some other procedures
14453 that will be invoked by |get_x_next|.
14454
14455 @<Declarations@>= 
14456 void mp_scan_primary (MP mp);
14457 void mp_scan_secondary (MP mp);
14458 void mp_scan_tertiary (MP mp);
14459 void mp_scan_expression (MP mp);
14460 void mp_scan_suffix (MP mp);
14461 @<Declare the procedure called |macro_call|@>;
14462 void mp_get_boolean (MP mp);
14463 void mp_pass_text (MP mp);
14464 void mp_conditional (MP mp);
14465 void mp_start_input (MP mp);
14466 void mp_begin_iteration (MP mp);
14467 void mp_resume_iteration (MP mp);
14468 void mp_stop_iteration (MP mp);
14469
14470 @ An auxiliary subroutine called |expand| is used by |get_x_next|
14471 when it has to do exotic expansion commands.
14472
14473 @c void mp_expand (MP mp) {
14474   pointer p; /* for list manipulation */
14475   size_t k; /* something that we hope is |<=buf_size| */
14476   pool_pointer j; /* index into |str_pool| */
14477   if ( mp->internal[mp_tracing_commands]>unity ) 
14478     if ( mp->cur_cmd!=defined_macro )
14479       show_cur_cmd_mod;
14480   switch (mp->cur_cmd)  {
14481   case if_test:
14482     mp_conditional(mp); /* this procedure is discussed in Part 36 below */
14483     break;
14484   case fi_or_else:
14485     @<Terminate the current conditional and skip to \&{fi}@>;
14486     break;
14487   case input:
14488     @<Initiate or terminate input from a file@>;
14489     break;
14490   case iteration:
14491     if ( mp->cur_mod==end_for ) {
14492       @<Scold the user for having an extra \&{endfor}@>;
14493     } else {
14494       mp_begin_iteration(mp); /* this procedure is discussed in Part 37 below */
14495     }
14496     break;
14497   case repeat_loop: 
14498     @<Repeat a loop@>;
14499     break;
14500   case exit_test: 
14501     @<Exit a loop if the proper time has come@>;
14502     break;
14503   case relax: 
14504     break;
14505   case expand_after: 
14506     @<Expand the token after the next token@>;
14507     break;
14508   case scan_tokens: 
14509     @<Put a string into the input buffer@>;
14510     break;
14511   case defined_macro:
14512    mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14513    break;
14514   }; /* there are no other cases */
14515 };
14516
14517 @ @<Scold the user...@>=
14518
14519   print_err("Extra `endfor'");
14520 @.Extra `endfor'@>
14521   help2("I'm not currently working on a for loop,")
14522     ("so I had better not try to end anything.");
14523   mp_error(mp);
14524 }
14525
14526 @ The processing of \&{input} involves the |start_input| subroutine,
14527 which will be declared later; the processing of \&{endinput} is trivial.
14528
14529 @<Put each...@>=
14530 mp_primitive(mp, "input",input,0);
14531 @:input_}{\&{input} primitive@>
14532 mp_primitive(mp, "endinput",input,1);
14533 @:end_input_}{\&{endinput} primitive@>
14534
14535 @ @<Cases of |print_cmd_mod|...@>=
14536 case input: 
14537   if ( m==0 ) mp_print(mp, "input");
14538   else mp_print(mp, "endinput");
14539   break;
14540
14541 @ @<Initiate or terminate input...@>=
14542 if ( mp->cur_mod>0 ) mp->force_eof=true;
14543 else mp_start_input(mp)
14544
14545 @ We'll discuss the complicated parts of loop operations later. For now
14546 it suffices to know that there's a global variable called |loop_ptr|
14547 that will be |null| if no loop is in progress.
14548
14549 @<Repeat a loop@>=
14550 { while ( token_state &&(loc==null) ) 
14551     mp_end_token_list(mp); /* conserve stack space */
14552   if ( mp->loop_ptr==null ) {
14553     print_err("Lost loop");
14554 @.Lost loop@>
14555     help2("I'm confused; after exiting from a loop, I still seem")
14556       ("to want to repeat it. I'll try to forget the problem.");
14557     mp_error(mp);
14558   } else {
14559     mp_resume_iteration(mp); /* this procedure is in Part 37 below */
14560   }
14561 }
14562
14563 @ @<Exit a loop if the proper time has come@>=
14564 { mp_get_boolean(mp);
14565   if ( mp->internal[mp_tracing_commands]>unity ) 
14566     mp_show_cmd_mod(mp, nullary,mp->cur_exp);
14567   if ( mp->cur_exp==true_code ) {
14568     if ( mp->loop_ptr==null ) {
14569       print_err("No loop is in progress");
14570 @.No loop is in progress@>
14571       help1("Why say `exitif' when there's nothing to exit from?");
14572       if ( mp->cur_cmd==semicolon ) mp_error(mp); else mp_back_error(mp);
14573     } else {
14574      @<Exit prematurely from an iteration@>;
14575     }
14576   } else if ( mp->cur_cmd!=semicolon ) {
14577     mp_missing_err(mp, ";");
14578 @.Missing `;'@>
14579     help2("After `exitif <boolean exp>' I expect to see a semicolon.")
14580     ("I shall pretend that one was there."); mp_back_error(mp);
14581   }
14582 }
14583
14584 @ Here we use the fact that |forever_text| is the only |token_type| that
14585 is less than |loop_text|.
14586
14587 @<Exit prematurely...@>=
14588 { p=null;
14589   do {  
14590     if ( file_state ) {
14591       mp_end_file_reading(mp);
14592     } else { 
14593       if ( token_type<=loop_text ) p=start;
14594       mp_end_token_list(mp);
14595     }
14596   } while (p==null);
14597   if ( p!=info(mp->loop_ptr) ) mp_fatal_error(mp, "*** (loop confusion)");
14598 @.loop confusion@>
14599   mp_stop_iteration(mp); /* this procedure is in Part 34 below */
14600 }
14601
14602 @ @<Expand the token after the next token@>=
14603 { get_t_next;
14604   p=mp_cur_tok(mp); get_t_next;
14605   if ( mp->cur_cmd<min_command ) mp_expand(mp); 
14606   else mp_back_input(mp);
14607   back_list(p);
14608 }
14609
14610 @ @<Put a string into the input buffer@>=
14611 { mp_get_x_next(mp); mp_scan_primary(mp);
14612   if ( mp->cur_type!=mp_string_type ) {
14613     mp_disp_err(mp, null,"Not a string");
14614 @.Not a string@>
14615     help2("I'm going to flush this expression, since")
14616        ("scantokens should be followed by a known string.");
14617     mp_put_get_flush_error(mp, 0);
14618   } else { 
14619     mp_back_input(mp);
14620     if ( length(mp->cur_exp)>0 )
14621        @<Pretend we're reading a new one-line file@>;
14622   }
14623 }
14624
14625 @ @<Pretend we're reading a new one-line file@>=
14626 { mp_begin_file_reading(mp); name=is_scantok;
14627   k=mp->first+length(mp->cur_exp);
14628   if ( k>=mp->max_buf_stack ) {
14629     while ( k>=mp->buf_size ) {
14630       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
14631     }
14632     mp->max_buf_stack=k+1;
14633   }
14634   j=mp->str_start[mp->cur_exp]; limit=k;
14635   while ( mp->first<(size_t)limit ) {
14636     mp->buffer[mp->first]=mp->str_pool[j]; incr(j); incr(mp->first);
14637   }
14638   mp->buffer[limit]='%'; mp->first=limit+1; loc=start; 
14639   mp_flush_cur_exp(mp, 0);
14640 }
14641
14642 @ Here finally is |get_x_next|.
14643
14644 The expression scanning routines to be considered later
14645 communicate via the global quantities |cur_type| and |cur_exp|;
14646 we must be very careful to save and restore these quantities while
14647 macros are being expanded.
14648 @^inner loop@>
14649
14650 @<Declarations@>=
14651 void mp_get_x_next (MP mp);
14652
14653 @ @c void mp_get_x_next (MP mp) {
14654   pointer save_exp; /* a capsule to save |cur_type| and |cur_exp| */
14655   get_t_next;
14656   if ( mp->cur_cmd<min_command ) {
14657     save_exp=mp_stash_cur_exp(mp);
14658     do {  
14659       if ( mp->cur_cmd==defined_macro ) 
14660         mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14661       else 
14662         mp_expand(mp);
14663       get_t_next;
14664      } while (mp->cur_cmd<min_command);
14665      mp_unstash_cur_exp(mp, save_exp); /* that restores |cur_type| and |cur_exp| */
14666   }
14667 }
14668
14669 @ Now let's consider the |macro_call| procedure, which is used to start up
14670 all user-defined macros. Since the arguments to a macro might be expressions,
14671 |macro_call| is recursive.
14672 @^recursion@>
14673
14674 The first parameter to |macro_call| points to the reference count of the
14675 token list that defines the macro. The second parameter contains any
14676 arguments that have already been parsed (see below).  The third parameter
14677 points to the symbolic token that names the macro. If the third parameter
14678 is |null|, the macro was defined by \&{vardef}, so its name can be
14679 reconstructed from the prefix and ``at'' arguments found within the
14680 second parameter.
14681
14682 What is this second parameter? It's simply a linked list of one-word items,
14683 whose |info| fields point to the arguments. In other words, if |arg_list=null|,
14684 no arguments have been scanned yet; otherwise |info(arg_list)| points to
14685 the first scanned argument, and |link(arg_list)| points to the list of
14686 further arguments (if any).
14687
14688 Arguments of type \&{expr} are so-called capsules, which we will
14689 discuss later when we concentrate on expressions; they can be
14690 recognized easily because their |link| field is |void|. Arguments of type
14691 \&{suffix} and \&{text} are token lists without reference counts.
14692
14693 @ After argument scanning is complete, the arguments are moved to the
14694 |param_stack|. (They can't be put on that stack any sooner, because
14695 the stack is growing and shrinking in unpredictable ways as more arguments
14696 are being acquired.)  Then the macro body is fed to the scanner; i.e.,
14697 the replacement text of the macro is placed at the top of the \MP's
14698 input stack, so that |get_t_next| will proceed to read it next.
14699
14700 @<Declare the procedure called |macro_call|@>=
14701 @<Declare the procedure called |print_macro_name|@>;
14702 @<Declare the procedure called |print_arg|@>;
14703 @<Declare the procedure called |scan_text_arg|@>;
14704 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14705                     pointer macro_name) ;
14706
14707 @ @c
14708 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14709                     pointer macro_name) {
14710   /* invokes a user-defined control sequence */
14711   pointer r; /* current node in the macro's token list */
14712   pointer p,q; /* for list manipulation */
14713   integer n; /* the number of arguments */
14714   pointer tail = 0; /* tail of the argument list */
14715   pointer l_delim=0,r_delim=0; /* a delimiter pair */
14716   r=link(def_ref); add_mac_ref(def_ref);
14717   if ( arg_list==null ) {
14718     n=0;
14719   } else {
14720    @<Determine the number |n| of arguments already supplied,
14721     and set |tail| to the tail of |arg_list|@>;
14722   }
14723   if ( mp->internal[mp_tracing_macros]>0 ) {
14724     @<Show the text of the macro being expanded, and the existing arguments@>;
14725   }
14726   @<Scan the remaining arguments, if any; set |r| to the first token
14727     of the replacement text@>;
14728   @<Feed the arguments and replacement text to the scanner@>;
14729 }
14730
14731 @ @<Show the text of the macro...@>=
14732 mp_begin_diagnostic(mp); mp_print_ln(mp); 
14733 mp_print_macro_name(mp, arg_list,macro_name);
14734 if ( n==3 ) mp_print(mp, "@@#"); /* indicate a suffixed macro */
14735 mp_show_macro(mp, def_ref,null,100000);
14736 if ( arg_list!=null ) {
14737   n=0; p=arg_list;
14738   do {  
14739     q=info(p);
14740     mp_print_arg(mp, q,n,0);
14741     incr(n); p=link(p);
14742   } while (p!=null);
14743 }
14744 mp_end_diagnostic(mp, false)
14745
14746
14747 @ @<Declare the procedure called |print_macro_name|@>=
14748 void mp_print_macro_name (MP mp,pointer a, pointer n);
14749
14750 @ @c
14751 void mp_print_macro_name (MP mp,pointer a, pointer n) {
14752   pointer p,q; /* they traverse the first part of |a| */
14753   if ( n!=null ) {
14754     mp_print_text(n);
14755   } else  { 
14756     p=info(a);
14757     if ( p==null ) {
14758       mp_print_text(info(info(link(a))));
14759     } else { 
14760       q=p;
14761       while ( link(q)!=null ) q=link(q);
14762       link(q)=info(link(a));
14763       mp_show_token_list(mp, p,null,1000,0);
14764       link(q)=null;
14765     }
14766   }
14767 }
14768
14769 @ @<Declare the procedure called |print_arg|@>=
14770 void mp_print_arg (MP mp,pointer q, integer n, pointer b) ;
14771
14772 @ @c
14773 void mp_print_arg (MP mp,pointer q, integer n, pointer b) {
14774   if ( link(q)==mp_void ) mp_print_nl(mp, "(EXPR");
14775   else if ( (b<text_base)&&(b!=text_macro) ) mp_print_nl(mp, "(SUFFIX");
14776   else mp_print_nl(mp, "(TEXT");
14777   mp_print_int(mp, n); mp_print(mp, ")<-");
14778   if ( link(q)==mp_void ) mp_print_exp(mp, q,1);
14779   else mp_show_token_list(mp, q,null,1000,0);
14780 }
14781
14782 @ @<Determine the number |n| of arguments already supplied...@>=
14783 {  
14784   n=1; tail=arg_list;
14785   while ( link(tail)!=null ) { 
14786     incr(n); tail=link(tail);
14787   }
14788 }
14789
14790 @ @<Scan the remaining arguments, if any; set |r|...@>=
14791 mp->cur_cmd=comma+1; /* anything |<>comma| will do */
14792 while ( info(r)>=expr_base ) { 
14793   @<Scan the delimited argument represented by |info(r)|@>;
14794   r=link(r);
14795 };
14796 if ( mp->cur_cmd==comma ) {
14797   print_err("Too many arguments to ");
14798 @.Too many arguments...@>
14799   mp_print_macro_name(mp, arg_list,macro_name); mp_print_char(mp, ';');
14800   mp_print_nl(mp, "  Missing `"); mp_print_text(r_delim);
14801 @.Missing `)'...@>
14802   mp_print(mp, "' has been inserted");
14803   help3("I'm going to assume that the comma I just read was a")
14804    ("right delimiter, and then I'll begin expanding the macro.")
14805    ("You might want to delete some tokens before continuing.");
14806   mp_error(mp);
14807 }
14808 if ( info(r)!=general_macro ) {
14809   @<Scan undelimited argument(s)@>;
14810 }
14811 r=link(r)
14812
14813 @ At this point, the reader will find it advisable to review the explanation
14814 of token list format that was presented earlier, paying special attention to
14815 the conventions that apply only at the beginning of a macro's token list.
14816
14817 On the other hand, the reader will have to take the expression-parsing
14818 aspects of the following program on faith; we will explain |cur_type|
14819 and |cur_exp| later. (Several things in this program depend on each other,
14820 and it's necessary to jump into the circle somewhere.)
14821
14822 @<Scan the delimited argument represented by |info(r)|@>=
14823 if ( mp->cur_cmd!=comma ) {
14824   mp_get_x_next(mp);
14825   if ( mp->cur_cmd!=left_delimiter ) {
14826     print_err("Missing argument to ");
14827 @.Missing argument...@>
14828     mp_print_macro_name(mp, arg_list,macro_name);
14829     help3("That macro has more parameters than you thought.")
14830      ("I'll continue by pretending that each missing argument")
14831      ("is either zero or null.");
14832     if ( info(r)>=suffix_base ) {
14833       mp->cur_exp=null; mp->cur_type=mp_token_list;
14834     } else { 
14835       mp->cur_exp=0; mp->cur_type=mp_known;
14836     }
14837     mp_back_error(mp); mp->cur_cmd=right_delimiter; 
14838     goto FOUND;
14839   }
14840   l_delim=mp->cur_sym; r_delim=mp->cur_mod;
14841 }
14842 @<Scan the argument represented by |info(r)|@>;
14843 if ( mp->cur_cmd!=comma ) 
14844   @<Check that the proper right delimiter was present@>;
14845 FOUND:  
14846 @<Append the current expression to |arg_list|@>
14847
14848 @ @<Check that the proper right delim...@>=
14849 if ( (mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
14850   if ( info(link(r))>=expr_base ) {
14851     mp_missing_err(mp, ",");
14852 @.Missing `,'@>
14853     help3("I've finished reading a macro argument and am about to")
14854       ("read another; the arguments weren't delimited correctly.")
14855        ("You might want to delete some tokens before continuing.");
14856     mp_back_error(mp); mp->cur_cmd=comma;
14857   } else { 
14858     mp_missing_err(mp, str(text(r_delim)));
14859 @.Missing `)'@>
14860     help2("I've gotten to the end of the macro parameter list.")
14861        ("You might want to delete some tokens before continuing.");
14862     mp_back_error(mp);
14863   }
14864 }
14865
14866 @ A \&{suffix} or \&{text} parameter will be have been scanned as
14867 a token list pointed to by |cur_exp|, in which case we will have
14868 |cur_type=token_list|.
14869
14870 @<Append the current expression to |arg_list|@>=
14871
14872   p=mp_get_avail(mp);
14873   if ( mp->cur_type==mp_token_list ) info(p)=mp->cur_exp;
14874   else info(p)=mp_stash_cur_exp(mp);
14875   if ( mp->internal[mp_tracing_macros]>0 ) {
14876     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,info(r)); 
14877     mp_end_diagnostic(mp, false);
14878   }
14879   if ( arg_list==null ) arg_list=p;
14880   else link(tail)=p;
14881   tail=p; incr(n);
14882 }
14883
14884 @ @<Scan the argument represented by |info(r)|@>=
14885 if ( info(r)>=text_base ) {
14886   mp_scan_text_arg(mp, l_delim,r_delim);
14887 } else { 
14888   mp_get_x_next(mp);
14889   if ( info(r)>=suffix_base ) mp_scan_suffix(mp);
14890   else mp_scan_expression(mp);
14891 }
14892
14893 @ The parameters to |scan_text_arg| are either a pair of delimiters
14894 or zero; the latter case is for undelimited text arguments, which
14895 end with the first semicolon or \&{endgroup} or \&{end} that is not
14896 contained in a group.
14897
14898 @<Declare the procedure called |scan_text_arg|@>=
14899 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) ;
14900
14901 @ @c
14902 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) {
14903   integer balance; /* excess of |l_delim| over |r_delim| */
14904   pointer p; /* list tail */
14905   mp->warning_info=l_delim; mp->scanner_status=absorbing;
14906   p=hold_head; balance=1; link(hold_head)=null;
14907   while (1)  { 
14908     get_t_next;
14909     if ( l_delim==0 ) {
14910       @<Adjust the balance for an undelimited argument; |break| if done@>;
14911     } else {
14912           @<Adjust the balance for a delimited argument; |break| if done@>;
14913     }
14914     link(p)=mp_cur_tok(mp); p=link(p);
14915   }
14916   mp->cur_exp=link(hold_head); mp->cur_type=mp_token_list;
14917   mp->scanner_status=normal;
14918 };
14919
14920 @ @<Adjust the balance for a delimited argument...@>=
14921 if ( mp->cur_cmd==right_delimiter ) { 
14922   if ( mp->cur_mod==l_delim ) { 
14923     decr(balance);
14924     if ( balance==0 ) break;
14925   }
14926 } else if ( mp->cur_cmd==left_delimiter ) {
14927   if ( mp->cur_mod==r_delim ) incr(balance);
14928 }
14929
14930 @ @<Adjust the balance for an undelimited...@>=
14931 if ( end_of_statement ) { /* |cur_cmd=semicolon|, |end_group|, or |stop| */
14932   if ( balance==1 ) { break; }
14933   else  { if ( mp->cur_cmd==end_group ) decr(balance); }
14934 } else if ( mp->cur_cmd==begin_group ) { 
14935   incr(balance); 
14936 }
14937
14938 @ @<Scan undelimited argument(s)@>=
14939
14940   if ( info(r)<text_macro ) {
14941     mp_get_x_next(mp);
14942     if ( info(r)!=suffix_macro ) {
14943       if ( (mp->cur_cmd==equals)||(mp->cur_cmd==assignment) ) mp_get_x_next(mp);
14944     }
14945   }
14946   switch (info(r)) {
14947   case primary_macro:mp_scan_primary(mp); break;
14948   case secondary_macro:mp_scan_secondary(mp); break;
14949   case tertiary_macro:mp_scan_tertiary(mp); break;
14950   case expr_macro:mp_scan_expression(mp); break;
14951   case of_macro:
14952     @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>;
14953     break;
14954   case suffix_macro:
14955     @<Scan a suffix with optional delimiters@>;
14956     break;
14957   case text_macro:mp_scan_text_arg(mp, 0,0); break;
14958   } /* there are no other cases */
14959   mp_back_input(mp); 
14960   @<Append the current expression to |arg_list|@>;
14961 }
14962
14963 @ @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>=
14964
14965   mp_scan_expression(mp); p=mp_get_avail(mp); info(p)=mp_stash_cur_exp(mp);
14966   if ( mp->internal[mp_tracing_macros]>0 ) { 
14967     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,0); 
14968     mp_end_diagnostic(mp, false);
14969   }
14970   if ( arg_list==null ) arg_list=p; else link(tail)=p;
14971   tail=p;incr(n);
14972   if ( mp->cur_cmd!=of_token ) {
14973     mp_missing_err(mp, "of"); mp_print(mp, " for ");
14974 @.Missing `of'@>
14975     mp_print_macro_name(mp, arg_list,macro_name);
14976     help1("I've got the first argument; will look now for the other.");
14977     mp_back_error(mp);
14978   }
14979   mp_get_x_next(mp); mp_scan_primary(mp);
14980 }
14981
14982 @ @<Scan a suffix with optional delimiters@>=
14983
14984   if ( mp->cur_cmd!=left_delimiter ) {
14985     l_delim=null;
14986   } else { 
14987     l_delim=mp->cur_sym; r_delim=mp->cur_mod; mp_get_x_next(mp);
14988   };
14989   mp_scan_suffix(mp);
14990   if ( l_delim!=null ) {
14991     if ((mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
14992       mp_missing_err(mp, str(text(r_delim)));
14993 @.Missing `)'@>
14994       help2("I've gotten to the end of the macro parameter list.")
14995          ("You might want to delete some tokens before continuing.");
14996       mp_back_error(mp);
14997     }
14998     mp_get_x_next(mp);
14999   }
15000 }
15001
15002 @ Before we put a new token list on the input stack, it is wise to clean off
15003 all token lists that have recently been depleted. Then a user macro that ends
15004 with a call to itself will not require unbounded stack space.
15005
15006 @<Feed the arguments and replacement text to the scanner@>=
15007 while ( token_state &&(loc==null) ) mp_end_token_list(mp); /* conserve stack space */
15008 if ( mp->param_ptr+n>mp->max_param_stack ) {
15009   mp->max_param_stack=mp->param_ptr+n;
15010   if ( mp->max_param_stack>mp->param_size )
15011     mp_overflow(mp, "parameter stack size",mp->param_size);
15012 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15013 }
15014 mp_begin_token_list(mp, def_ref,macro); name=macro_name; loc=r;
15015 if ( n>0 ) {
15016   p=arg_list;
15017   do {  
15018    mp->param_stack[mp->param_ptr]=info(p); incr(mp->param_ptr); p=link(p);
15019   } while (p!=null);
15020   mp_flush_list(mp, arg_list);
15021 }
15022
15023 @ It's sometimes necessary to put a single argument onto |param_stack|.
15024 The |stack_argument| subroutine does this.
15025
15026 @c void mp_stack_argument (MP mp,pointer p) { 
15027   if ( mp->param_ptr==mp->max_param_stack ) {
15028     incr(mp->max_param_stack);
15029     if ( mp->max_param_stack>mp->param_size )
15030       mp_overflow(mp, "parameter stack size",mp->param_size);
15031 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15032   }
15033   mp->param_stack[mp->param_ptr]=p; incr(mp->param_ptr);
15034 }
15035
15036 @* \[33] Conditional processing.
15037 Let's consider now the way \&{if} commands are handled.
15038
15039 Conditions can be inside conditions, and this nesting has a stack
15040 that is independent of other stacks.
15041 Four global variables represent the top of the condition stack:
15042 |cond_ptr| points to pushed-down entries, if~any; |cur_if| tells whether
15043 we are processing \&{if} or \&{elseif}; |if_limit| specifies
15044 the largest code of a |fi_or_else| command that is syntactically legal;
15045 and |if_line| is the line number at which the current conditional began.
15046
15047 If no conditions are currently in progress, the condition stack has the
15048 special state |cond_ptr=null|, |if_limit=normal|, |cur_if=0|, |if_line=0|.
15049 Otherwise |cond_ptr| points to a two-word node; the |type|, |name_type|, and
15050 |link| fields of the first word contain |if_limit|, |cur_if|, and
15051 |cond_ptr| at the next level, and the second word contains the
15052 corresponding |if_line|.
15053
15054 @d if_node_size 2 /* number of words in stack entry for conditionals */
15055 @d if_line_field(A) mp->mem[(A)+1].cint
15056 @d if_code 1 /* code for \&{if} being evaluated */
15057 @d fi_code 2 /* code for \&{fi} */
15058 @d else_code 3 /* code for \&{else} */
15059 @d else_if_code 4 /* code for \&{elseif} */
15060
15061 @<Glob...@>=
15062 pointer cond_ptr; /* top of the condition stack */
15063 integer if_limit; /* upper bound on |fi_or_else| codes */
15064 small_number cur_if; /* type of conditional being worked on */
15065 integer if_line; /* line where that conditional began */
15066
15067 @ @<Set init...@>=
15068 mp->cond_ptr=null; mp->if_limit=normal; mp->cur_if=0; mp->if_line=0;
15069
15070 @ @<Put each...@>=
15071 mp_primitive(mp, "if",if_test,if_code);
15072 @:if_}{\&{if} primitive@>
15073 mp_primitive(mp, "fi",fi_or_else,fi_code); mp->eqtb[frozen_fi]=mp->eqtb[mp->cur_sym];
15074 @:fi_}{\&{fi} primitive@>
15075 mp_primitive(mp, "else",fi_or_else,else_code);
15076 @:else_}{\&{else} primitive@>
15077 mp_primitive(mp, "elseif",fi_or_else,else_if_code);
15078 @:else_if_}{\&{elseif} primitive@>
15079
15080 @ @<Cases of |print_cmd_mod|...@>=
15081 case if_test:
15082 case fi_or_else: 
15083   switch (m) {
15084   case if_code:mp_print(mp, "if"); break;
15085   case fi_code:mp_print(mp, "fi");  break;
15086   case else_code:mp_print(mp, "else"); break;
15087   default: mp_print(mp, "elseif"); break;
15088   }
15089   break;
15090
15091 @ Here is a procedure that ignores text until coming to an \&{elseif},
15092 \&{else}, or \&{fi} at level zero of $\&{if}\ldots\&{fi}$
15093 nesting. After it has acted, |cur_mod| will indicate the token that
15094 was found.
15095
15096 \MP's smallest two command codes are |if_test| and |fi_or_else|; this
15097 makes the skipping process a bit simpler.
15098
15099 @c 
15100 void mp_pass_text (MP mp) {
15101   integer l = 0;
15102   mp->scanner_status=skipping;
15103   mp->warning_info=mp_true_line(mp);
15104   while (1)  { 
15105     get_t_next;
15106     if ( mp->cur_cmd<=fi_or_else ) {
15107       if ( mp->cur_cmd<fi_or_else ) {
15108         incr(l);
15109       } else { 
15110         if ( l==0 ) break;
15111         if ( mp->cur_mod==fi_code ) decr(l);
15112       }
15113     } else {
15114       @<Decrease the string reference count,
15115        if the current token is a string@>;
15116     }
15117   }
15118   mp->scanner_status=normal;
15119 }
15120
15121 @ @<Decrease the string reference count...@>=
15122 if ( mp->cur_cmd==string_token ) { delete_str_ref(mp->cur_mod); }
15123
15124 @ When we begin to process a new \&{if}, we set |if_limit:=if_code|; then
15125 if \&{elseif} or \&{else} or \&{fi} occurs before the current \&{if}
15126 condition has been evaluated, a colon will be inserted.
15127 A construction like `\.{if fi}' would otherwise get \MP\ confused.
15128
15129 @<Push the condition stack@>=
15130 { p=mp_get_node(mp, if_node_size); link(p)=mp->cond_ptr; type(p)=mp->if_limit;
15131   name_type(p)=mp->cur_if; if_line_field(p)=mp->if_line;
15132   mp->cond_ptr=p; mp->if_limit=if_code; mp->if_line=mp_true_line(mp); 
15133   mp->cur_if=if_code;
15134 }
15135
15136 @ @<Pop the condition stack@>=
15137 { p=mp->cond_ptr; mp->if_line=if_line_field(p);
15138   mp->cur_if=name_type(p); mp->if_limit=type(p); mp->cond_ptr=link(p);
15139   mp_free_node(mp, p,if_node_size);
15140 }
15141
15142 @ Here's a procedure that changes the |if_limit| code corresponding to
15143 a given value of |cond_ptr|.
15144
15145 @c void mp_change_if_limit (MP mp,small_number l, pointer p) {
15146   pointer q;
15147   if ( p==mp->cond_ptr ) {
15148     mp->if_limit=l; /* that's the easy case */
15149   } else  { 
15150     q=mp->cond_ptr;
15151     while (1) { 
15152       if ( q==null ) mp_confusion(mp, "if");
15153 @:this can't happen if}{\quad if@>
15154       if ( link(q)==p ) { 
15155         type(q)=l; return;
15156       }
15157       q=link(q);
15158     }
15159   }
15160 }
15161
15162 @ The user is supposed to put colons into the proper parts of conditional
15163 statements. Therefore, \MP\ has to check for their presence.
15164
15165 @c 
15166 void mp_check_colon (MP mp) { 
15167   if ( mp->cur_cmd!=colon ) { 
15168     mp_missing_err(mp, ":");
15169 @.Missing `:'@>
15170     help2("There should've been a colon after the condition.")
15171          ("I shall pretend that one was there.");;
15172     mp_back_error(mp);
15173   }
15174 }
15175
15176 @ A condition is started when the |get_x_next| procedure encounters
15177 an |if_test| command; in that case |get_x_next| calls |conditional|,
15178 which is a recursive procedure.
15179 @^recursion@>
15180
15181 @c void mp_conditional (MP mp) {
15182   pointer save_cond_ptr; /* |cond_ptr| corresponding to this conditional */
15183   int new_if_limit; /* future value of |if_limit| */
15184   pointer p; /* temporary register */
15185   @<Push the condition stack@>; 
15186   save_cond_ptr=mp->cond_ptr;
15187 RESWITCH: 
15188   mp_get_boolean(mp); new_if_limit=else_if_code;
15189   if ( mp->internal[mp_tracing_commands]>unity ) {
15190     @<Display the boolean value of |cur_exp|@>;
15191   }
15192 FOUND: 
15193   mp_check_colon(mp);
15194   if ( mp->cur_exp==true_code ) {
15195     mp_change_if_limit(mp, new_if_limit,save_cond_ptr);
15196     return; /* wait for \&{elseif}, \&{else}, or \&{fi} */
15197   };
15198   @<Skip to \&{elseif} or \&{else} or \&{fi}, then |goto done|@>;
15199 DONE: 
15200   mp->cur_if=mp->cur_mod; mp->if_line=mp_true_line(mp);
15201   if ( mp->cur_mod==fi_code ) {
15202     @<Pop the condition stack@>
15203   } else if ( mp->cur_mod==else_if_code ) {
15204     goto RESWITCH;
15205   } else  { 
15206     mp->cur_exp=true_code; new_if_limit=fi_code; mp_get_x_next(mp); 
15207     goto FOUND;
15208   }
15209 }
15210
15211 @ In a construction like `\&{if} \&{if} \&{true}: $0=1$: \\{foo}
15212 \&{else}: \\{bar} \&{fi}', the first \&{else}
15213 that we come to after learning that the \&{if} is false is not the
15214 \&{else} we're looking for. Hence the following curious logic is needed.
15215
15216 @<Skip to \&{elseif}...@>=
15217 while (1) { 
15218   mp_pass_text(mp);
15219   if ( mp->cond_ptr==save_cond_ptr ) goto DONE;
15220   else if ( mp->cur_mod==fi_code ) @<Pop the condition stack@>;
15221 }
15222
15223
15224 @ @<Display the boolean value...@>=
15225 { mp_begin_diagnostic(mp);
15226   if ( mp->cur_exp==true_code ) mp_print(mp, "{true}");
15227   else mp_print(mp, "{false}");
15228   mp_end_diagnostic(mp, false);
15229 }
15230
15231 @ The processing of conditionals is complete except for the following
15232 code, which is actually part of |get_x_next|. It comes into play when
15233 \&{elseif}, \&{else}, or \&{fi} is scanned.
15234
15235 @<Terminate the current conditional and skip to \&{fi}@>=
15236 if ( mp->cur_mod>mp->if_limit ) {
15237   if ( mp->if_limit==if_code ) { /* condition not yet evaluated */
15238     mp_missing_err(mp, ":");
15239 @.Missing `:'@>
15240     mp_back_input(mp); mp->cur_sym=frozen_colon; mp_ins_error(mp);
15241   } else  { 
15242     print_err("Extra "); mp_print_cmd_mod(mp, fi_or_else,mp->cur_mod);
15243 @.Extra else@>
15244 @.Extra elseif@>
15245 @.Extra fi@>
15246     help1("I'm ignoring this; it doesn't match any if.");
15247     mp_error(mp);
15248   }
15249 } else  { 
15250   while ( mp->cur_mod!=fi_code ) mp_pass_text(mp); /* skip to \&{fi} */
15251   @<Pop the condition stack@>;
15252 }
15253
15254 @* \[34] Iterations.
15255 To bring our treatment of |get_x_next| to a close, we need to consider what
15256 \MP\ does when it sees \&{for}, \&{forsuffixes}, and \&{forever}.
15257
15258 There's a global variable |loop_ptr| that keeps track of the \&{for} loops
15259 that are currently active. If |loop_ptr=null|, no loops are in progress;
15260 otherwise |info(loop_ptr)| points to the iterative text of the current
15261 (innermost) loop, and |link(loop_ptr)| points to the data for any other
15262 loops that enclose the current one.
15263
15264 A loop-control node also has two other fields, called |loop_type| and
15265 |loop_list|, whose contents depend on the type of loop:
15266
15267 \yskip\indent|loop_type(loop_ptr)=null| means that |loop_list(loop_ptr)|
15268 points to a list of one-word nodes whose |info| fields point to the
15269 remaining argument values of a suffix list and expression list.
15270
15271 \yskip\indent|loop_type(loop_ptr)=mp_void| means that the current loop is
15272 `\&{forever}'.
15273
15274 \yskip\indent|loop_type(loop_ptr)=progression_flag| means that
15275 |p=loop_list(loop_ptr)| points to a ``progression node'' and |value(p)|,
15276 |step_size(p)|, and |final_value(p)| contain the data for an arithmetic
15277 progression.
15278
15279 \yskip\indent|loop_type(loop_ptr)=p>mp_void| means that |p| points to an edge
15280 header and |loop_list(loop_ptr)| points into the graphical object list for
15281 that edge header.
15282
15283 \yskip\noindent In the case of a progression node, the first word is not used
15284 because the link field of words in the dynamic memory area cannot be arbitrary.
15285
15286 @d loop_list_loc(A) ((A)+1) /* where the |loop_list| field resides */
15287 @d loop_type(A) info(loop_list_loc((A))) /* the type of \&{for} loop */
15288 @d loop_list(A) link(loop_list_loc((A))) /* the remaining list elements */
15289 @d loop_node_size 2 /* the number of words in a loop control node */
15290 @d progression_node_size 4 /* the number of words in a progression node */
15291 @d step_size(A) mp->mem[(A)+2].sc /* the step size in an arithmetic progression */
15292 @d final_value(A) mp->mem[(A)+3].sc /* the final value in an arithmetic progression */
15293 @d progression_flag (null+2)
15294   /* |loop_type| value when |loop_list| points to a progression node */
15295
15296 @<Glob...@>=
15297 pointer loop_ptr; /* top of the loop-control-node stack */
15298
15299 @ @<Set init...@>=
15300 mp->loop_ptr=null;
15301
15302 @ If the expressions that define an arithmetic progression in
15303 a \&{for} loop don't have known numeric values, the |bad_for|
15304 subroutine screams at the user.
15305
15306 @c void mp_bad_for (MP mp, char * s) {
15307   mp_disp_err(mp, null,"Improper "); /* show the bad expression above the message */
15308 @.Improper...replaced by 0@>
15309   mp_print(mp, s); mp_print(mp, " has been replaced by 0");
15310   help4("When you say `for x=a step b until c',")
15311     ("the initial value `a' and the step size `b'")
15312     ("and the final value `c' must have known numeric values.")
15313     ("I'm zeroing this one. Proceed, with fingers crossed.");
15314   mp_put_get_flush_error(mp, 0);
15315 };
15316
15317 @ Here's what \MP\ does when \&{for}, \&{forsuffixes}, or \&{forever}
15318 has just been scanned. (This code requires slight familiarity with
15319 expression-parsing routines that we have not yet discussed; but it seems
15320 to belong in the present part of the program, even though the original author
15321 didn't write it until later. The reader may wish to come back to it.)
15322
15323 @c void mp_begin_iteration (MP mp) {
15324   halfword m; /* |expr_base| (\&{for}) or |suffix_base| (\&{forsuffixes}) */
15325   halfword n; /* hash address of the current symbol */
15326   pointer s; /* the new loop-control node */
15327   pointer p; /* substitution list for |scan_toks| */
15328   pointer q;  /* link manipulation register */
15329   pointer pp; /* a new progression node */
15330   m=mp->cur_mod; n=mp->cur_sym; s=mp_get_node(mp, loop_node_size);
15331   if ( m==start_forever ){ 
15332     loop_type(s)=mp_void; p=null; mp_get_x_next(mp);
15333   } else { 
15334     mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
15335     info(p)=mp->cur_sym; value(p)=m;
15336     mp_get_x_next(mp);
15337     if ( mp->cur_cmd==within_token ) {
15338       @<Set up a picture iteration@>;
15339     } else { 
15340       @<Check for the |"="| or |":="| in a loop header@>;
15341       @<Scan the values to be used in the loop@>;
15342     }
15343   }
15344   @<Check for the presence of a colon@>;
15345   @<Scan the loop text and put it on the loop control stack@>;
15346   mp_resume_iteration(mp);
15347 }
15348
15349 @ @<Check for the |"="| or |":="| in a loop header@>=
15350 if ( (mp->cur_cmd!=equals)&&(mp->cur_cmd!=assignment) ) { 
15351   mp_missing_err(mp, "=");
15352 @.Missing `='@>
15353   help3("The next thing in this loop should have been `=' or `:='.")
15354     ("But don't worry; I'll pretend that an equals sign")
15355     ("was present, and I'll look for the values next.");
15356   mp_back_error(mp);
15357 }
15358
15359 @ @<Check for the presence of a colon@>=
15360 if ( mp->cur_cmd!=colon ) { 
15361   mp_missing_err(mp, ":");
15362 @.Missing `:'@>
15363   help3("The next thing in this loop should have been a `:'.")
15364     ("So I'll pretend that a colon was present;")
15365     ("everything from here to `endfor' will be iterated.");
15366   mp_back_error(mp);
15367 }
15368
15369 @ We append a special |frozen_repeat_loop| token in place of the
15370 `\&{endfor}' at the end of the loop. This will come through \MP's scanner
15371 at the proper time to cause the loop to be repeated.
15372
15373 (If the user tries some shenanigan like `\&{for} $\ldots$ \&{let} \&{endfor}',
15374 he will be foiled by the |get_symbol| routine, which keeps frozen
15375 tokens unchanged. Furthermore the |frozen_repeat_loop| is an \&{outer}
15376 token, so it won't be lost accidentally.)
15377
15378 @ @<Scan the loop text...@>=
15379 q=mp_get_avail(mp); info(q)=frozen_repeat_loop;
15380 mp->scanner_status=loop_defining; mp->warning_info=n;
15381 info(s)=mp_scan_toks(mp, iteration,p,q,0); mp->scanner_status=normal;
15382 link(s)=mp->loop_ptr; mp->loop_ptr=s
15383
15384 @ @<Initialize table...@>=
15385 eq_type(frozen_repeat_loop)=repeat_loop+outer_tag;
15386 text(frozen_repeat_loop)=intern(" ENDFOR");
15387
15388 @ The loop text is inserted into \MP's scanning apparatus by the
15389 |resume_iteration| routine.
15390
15391 @c void mp_resume_iteration (MP mp) {
15392   pointer p,q; /* link registers */
15393   p=loop_type(mp->loop_ptr);
15394   if ( p==progression_flag ) { 
15395     p=loop_list(mp->loop_ptr); /* now |p| points to a progression node */
15396     mp->cur_exp=value(p);
15397     if ( @<The arithmetic progression has ended@> ) {
15398       mp_stop_iteration(mp);
15399       return;
15400     }
15401     mp->cur_type=mp_known; q=mp_stash_cur_exp(mp); /* make |q| an \&{expr} argument */
15402     value(p)=mp->cur_exp+step_size(p); /* set |value(p)| for the next iteration */
15403   } else if ( p==null ) { 
15404     p=loop_list(mp->loop_ptr);
15405     if ( p==null ) {
15406       mp_stop_iteration(mp);
15407       return;
15408     }
15409     loop_list(mp->loop_ptr)=link(p); q=info(p); free_avail(p);
15410   } else if ( p==mp_void ) { 
15411     mp_begin_token_list(mp, info(mp->loop_ptr),forever_text); return;
15412   } else {
15413     @<Make |q| a capsule containing the next picture component from
15414       |loop_list(loop_ptr)| or |goto not_found|@>;
15415   }
15416   mp_begin_token_list(mp, info(mp->loop_ptr),loop_text);
15417   mp_stack_argument(mp, q);
15418   if ( mp->internal[mp_tracing_commands]>unity ) {
15419      @<Trace the start of a loop@>;
15420   }
15421   return;
15422 NOT_FOUND:
15423   mp_stop_iteration(mp);
15424 }
15425
15426 @ @<The arithmetic progression has ended@>=
15427 ((step_size(p)>0)&&(mp->cur_exp>final_value(p)))||
15428  ((step_size(p)<0)&&(mp->cur_exp<final_value(p)))
15429
15430 @ @<Trace the start of a loop@>=
15431
15432   mp_begin_diagnostic(mp); mp_print_nl(mp, "{loop value=");
15433 @.loop value=n@>
15434   if ( (q!=null)&&(link(q)==mp_void) ) mp_print_exp(mp, q,1);
15435   else mp_show_token_list(mp, q,null,50,0);
15436   mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
15437 }
15438
15439 @ @<Make |q| a capsule containing the next picture component from...@>=
15440 { q=loop_list(mp->loop_ptr);
15441   if ( q==null ) goto NOT_FOUND;
15442   skip_component(q) goto NOT_FOUND;
15443   mp->cur_exp=mp_copy_objects(mp, loop_list(mp->loop_ptr),q);
15444   mp_init_bbox(mp, mp->cur_exp);
15445   mp->cur_type=mp_picture_type;
15446   loop_list(mp->loop_ptr)=q;
15447   q=mp_stash_cur_exp(mp);
15448 }
15449
15450 @ A level of loop control disappears when |resume_iteration| has decided
15451 not to resume, or when an \&{exitif} construction has removed the loop text
15452 from the input stack.
15453
15454 @c void mp_stop_iteration (MP mp) {
15455   pointer p,q; /* the usual */
15456   p=loop_type(mp->loop_ptr);
15457   if ( p==progression_flag )  {
15458     mp_free_node(mp, loop_list(mp->loop_ptr),progression_node_size);
15459   } else if ( p==null ){ 
15460     q=loop_list(mp->loop_ptr);
15461     while ( q!=null ) {
15462       p=info(q);
15463       if ( p!=null ) {
15464         if ( link(p)==mp_void ) { /* it's an \&{expr} parameter */
15465           mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
15466         } else {
15467           mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
15468         }
15469       }
15470       p=q; q=link(q); free_avail(p);
15471     }
15472   } else if ( p>progression_flag ) {
15473     delete_edge_ref(p);
15474   }
15475   p=mp->loop_ptr; mp->loop_ptr=link(p); mp_flush_token_list(mp, info(p));
15476   mp_free_node(mp, p,loop_node_size);
15477 }
15478
15479 @ Now that we know all about loop control, we can finish up
15480 the missing portion of |begin_iteration| and we'll be done.
15481
15482 The following code is performed after the `\.=' has been scanned in
15483 a \&{for} construction (if |m=expr_base|) or a \&{forsuffixes} construction
15484 (if |m=suffix_base|).
15485
15486 @<Scan the values to be used in the loop@>=
15487 loop_type(s)=null; q=loop_list_loc(s); link(q)=null; /* |link(q)=loop_list(s)| */
15488 do {  
15489   mp_get_x_next(mp);
15490   if ( m!=expr_base ) {
15491     mp_scan_suffix(mp);
15492   } else { 
15493     if ( mp->cur_cmd>=colon ) if ( mp->cur_cmd<=comma ) 
15494           goto CONTINUE;
15495     mp_scan_expression(mp);
15496     if ( mp->cur_cmd==step_token ) if ( q==loop_list_loc(s) ) {
15497       @<Prepare for step-until construction and |break|@>;
15498     }
15499     mp->cur_exp=mp_stash_cur_exp(mp);
15500   }
15501   link(q)=mp_get_avail(mp); q=link(q); 
15502   info(q)=mp->cur_exp; mp->cur_type=mp_vacuous;
15503 CONTINUE:
15504   ;
15505 } while (mp->cur_cmd==comma)
15506
15507 @ @<Prepare for step-until construction and |break|@>=
15508
15509   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "initial value");
15510   pp=mp_get_node(mp, progression_node_size); value(pp)=mp->cur_exp;
15511   mp_get_x_next(mp); mp_scan_expression(mp);
15512   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "step size");
15513   step_size(pp)=mp->cur_exp;
15514   if ( mp->cur_cmd!=until_token ) { 
15515     mp_missing_err(mp, "until");
15516 @.Missing `until'@>
15517     help2("I assume you meant to say `until' after `step'.")
15518       ("So I'll look for the final value and colon next.");
15519     mp_back_error(mp);
15520   }
15521   mp_get_x_next(mp); mp_scan_expression(mp);
15522   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "final value");
15523   final_value(pp)=mp->cur_exp; loop_list(s)=pp;
15524   loop_type(s)=progression_flag; 
15525   break;
15526 }
15527
15528 @ The last case is when we have just seen ``\&{within}'', and we need to
15529 parse a picture expression and prepare to iterate over it.
15530
15531 @<Set up a picture iteration@>=
15532 { mp_get_x_next(mp);
15533   mp_scan_expression(mp);
15534   @<Make sure the current expression is a known picture@>;
15535   loop_type(s)=mp->cur_exp; mp->cur_type=mp_vacuous;
15536   q=link(dummy_loc(mp->cur_exp));
15537   if ( q!= null ) 
15538     if ( is_start_or_stop(q) )
15539       if ( mp_skip_1component(mp, q)==null ) q=link(q);
15540   loop_list(s)=q;
15541 }
15542
15543 @ @<Make sure the current expression is a known picture@>=
15544 if ( mp->cur_type!=mp_picture_type ) {
15545   mp_disp_err(mp, null,"Improper iteration spec has been replaced by nullpicture");
15546   help1("When you say `for x in p', p must be a known picture.");
15547   mp_put_get_flush_error(mp, mp_get_node(mp, edge_header_size));
15548   mp_init_edges(mp, mp->cur_exp); mp->cur_type=mp_picture_type;
15549 }
15550
15551 @* \[35] File names.
15552 It's time now to fret about file names.  Besides the fact that different
15553 operating systems treat files in different ways, we must cope with the
15554 fact that completely different naming conventions are used by different
15555 groups of people. The following programs show what is required for one
15556 particular operating system; similar routines for other systems are not
15557 difficult to devise.
15558 @^system dependencies@>
15559
15560 \MP\ assumes that a file name has three parts: the name proper; its
15561 ``extension''; and a ``file area'' where it is found in an external file
15562 system.  The extension of an input file is assumed to be
15563 `\.{.mp}' unless otherwise specified; it is `\.{.log}' on the
15564 transcript file that records each run of \MP; it is `\.{.tfm}' on the font
15565 metric files that describe characters in any fonts created by \MP; it is
15566 `\.{.ps}' or `.{\it nnn}' for some number {\it nnn} on the \ps\ output files;
15567 and it is `\.{.mem}' on the mem files written by \.{INIMP} to initialize \MP.
15568 The file area can be arbitrary on input files, but files are usually
15569 output to the user's current area.  If an input file cannot be
15570 found on the specified area, \MP\ will look for it on a special system
15571 area; this special area is intended for commonly used input files.
15572
15573 Simple uses of \MP\ refer only to file names that have no explicit
15574 extension or area. For example, a person usually says `\.{input} \.{cmr10}'
15575 instead of `\.{input} \.{cmr10.new}'. Simple file
15576 names are best, because they make the \MP\ source files portable;
15577 whenever a file name consists entirely of letters and digits, it should be
15578 treated in the same way by all implementations of \MP. However, users
15579 need the ability to refer to other files in their environment, especially
15580 when responding to error messages concerning unopenable files; therefore
15581 we want to let them use the syntax that appears in their favorite
15582 operating system.
15583
15584 @ \MP\ uses the same conventions that have proved to be satisfactory for
15585 \TeX\ and \MF. In order to isolate the system-dependent aspects of file names,
15586 @^system dependencies@>
15587 the system-independent parts of \MP\ are expressed in terms
15588 of three system-dependent
15589 procedures called |begin_name|, |more_name|, and |end_name|. In
15590 essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
15591 the system-independent driver program does the operations
15592 $$|begin_name|;\,|more_name|(c_1);\,\ldots\,;|more_name|(c_n);
15593 \,|end_name|.$$
15594 These three procedures communicate with each other via global variables.
15595 Afterwards the file name will appear in the string pool as three strings
15596 called |cur_name|\penalty10000\hskip-.05em,
15597 |cur_area|, and |cur_ext|; the latter two are null (i.e.,
15598 |""|), unless they were explicitly specified by the user.
15599
15600 Actually the situation is slightly more complicated, because \MP\ needs
15601 to know when the file name ends. The |more_name| routine is a function
15602 (with side effects) that returns |true| on the calls |more_name|$(c_1)$,
15603 \dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
15604 returns |false|; or, it returns |true| and $c_n$ is the last character
15605 on the current input line. In other words,
15606 |more_name| is supposed to return |true| unless it is sure that the
15607 file name has been completely scanned; and |end_name| is supposed to be able
15608 to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
15609 whether $|more_name|(c_n)$ returned |true| or |false|.
15610
15611 @<Glob...@>=
15612 char * cur_name; /* name of file just scanned */
15613 char * cur_area; /* file area just scanned, or \.{""} */
15614 char * cur_ext; /* file extension just scanned, or \.{""} */
15615
15616 @ It is easier to maintain reference counts if we assign initial values.
15617
15618 @<Set init...@>=
15619 mp->cur_name=xstrdup(""); 
15620 mp->cur_area=xstrdup(""); 
15621 mp->cur_ext=xstrdup("");
15622
15623 @ @<Dealloc variables@>=
15624 xfree(mp->cur_area);
15625 xfree(mp->cur_name);
15626 xfree(mp->cur_ext);
15627
15628 @ The file names we shall deal with for illustrative purposes have the
15629 following structure:  If the name contains `\.>' or `\.:', the file area
15630 consists of all characters up to and including the final such character;
15631 otherwise the file area is null.  If the remaining file name contains
15632 `\..', the file extension consists of all such characters from the first
15633 remaining `\..' to the end, otherwise the file extension is null.
15634 @^system dependencies@>
15635
15636 We can scan such file names easily by using two global variables that keep track
15637 of the occurrences of area and extension delimiters.  Note that these variables
15638 cannot be of type |pool_pointer| because a string pool compaction could occur
15639 while scanning a file name.
15640
15641 @<Glob...@>=
15642 integer area_delimiter;
15643   /* most recent `\.>' or `\.:' relative to |str_start[str_ptr]| */
15644 integer ext_delimiter; /* the relevant `\..', if any */
15645
15646 @ Input files that can't be found in the user's area may appear in standard
15647 system areas called |MP_area| and |MF_area|.  (The latter is used when the file
15648 extension is |".mf"|.)  The standard system area for font metric files
15649 to be read is |MP_font_area|.
15650 This system area name will, of course, vary from place to place.
15651 @^system dependencies@>
15652
15653 @d MP_area "MPinputs:"
15654 @.MPinputs@>
15655 @d MF_area "MFinputs:"
15656 @.MFinputs@>
15657 @d MP_font_area ""
15658 @.TeXfonts@>
15659
15660 @ Here now is the first of the system-dependent routines for file name scanning.
15661 @^system dependencies@>
15662
15663 @<Declare subroutines for parsing file names@>=
15664 void mp_begin_name (MP mp) { 
15665   xfree(mp->cur_name); 
15666   xfree(mp->cur_area); 
15667   xfree(mp->cur_ext);
15668   mp->area_delimiter=-1; 
15669   mp->ext_delimiter=-1;
15670 }
15671
15672 @ And here's the second.
15673 @^system dependencies@>
15674
15675 @<Declare subroutines for parsing file names@>=
15676 boolean mp_more_name (MP mp, ASCII_code c) { 
15677   if (c==' ') {
15678     return false;
15679   } else { 
15680     if ( (c=='>')||(c==':') ) { 
15681       mp->area_delimiter=mp->pool_ptr; 
15682       mp->ext_delimiter=-1;
15683     } else if ( (c=='.')&&(mp->ext_delimiter<0) ) {
15684       mp->ext_delimiter=mp->pool_ptr;
15685     }
15686     str_room(1); append_char(c); /* contribute |c| to the current string */
15687     return true;
15688   }
15689 }
15690
15691 @ The third.
15692 @^system dependencies@>
15693
15694 @d copy_pool_segment(A,B,C) { 
15695       A = xmalloc(C+1,sizeof(char)); 
15696       strncpy(A,(char *)(mp->str_pool+B),C);  
15697       A[C] = 0;}
15698
15699 @<Declare subroutines for parsing file names@>=
15700 void mp_end_name (MP mp) {
15701   pool_pointer s; /* length of area, name, and extension */
15702   unsigned int len;
15703   /* "my/w.mp" */
15704   s = mp->str_start[mp->str_ptr];
15705   if ( mp->area_delimiter<0 ) {    
15706     mp->cur_area=xstrdup("");
15707   } else {
15708     len = mp->area_delimiter-s; 
15709     copy_pool_segment(mp->cur_area,s,len);
15710     s += len+1;
15711   }
15712   if ( mp->ext_delimiter<0 ) {
15713     mp->cur_ext=xstrdup("");
15714     len = mp->pool_ptr-s; 
15715   } else {
15716     copy_pool_segment(mp->cur_ext,mp->ext_delimiter,(mp->pool_ptr-mp->ext_delimiter));
15717     len = mp->ext_delimiter-s;
15718   }
15719   copy_pool_segment(mp->cur_name,s,len);
15720   mp->pool_ptr=s; /* don't need this partial string */
15721 }
15722
15723 @ Conversely, here is a routine that takes three strings and prints a file
15724 name that might have produced them. (The routine is system dependent, because
15725 some operating systems put the file area last instead of first.)
15726 @^system dependencies@>
15727
15728 @<Basic printing...@>=
15729 void mp_print_file_name (MP mp, char * n, char * a, char * e) { 
15730   mp_print(mp, a); mp_print(mp, n); mp_print(mp, e);
15731 };
15732
15733 @ Another system-dependent routine is needed to convert three internal
15734 \MP\ strings
15735 to the |name_of_file| value that is used to open files. The present code
15736 allows both lowercase and uppercase letters in the file name.
15737 @^system dependencies@>
15738
15739 @d append_to_name(A) { c=(A); 
15740   if ( k<file_name_size ) {
15741     mp->name_of_file[k]=xchr(c);
15742     incr(k);
15743   }
15744 }
15745
15746 @<Declare subroutines for parsing file names@>=
15747 void mp_pack_file_name (MP mp, char *n, char *a, char *e) {
15748   integer k; /* number of positions filled in |name_of_file| */
15749   ASCII_code c; /* character being packed */
15750   char *j; /* a character  index */
15751   k=0;
15752   assert(n);
15753   if (a!=NULL) {
15754     for (j=a;*j;j++) { append_to_name(*j); }
15755   }
15756   for (j=n;*j;j++) { append_to_name(*j); }
15757   if (e!=NULL) {
15758     for (j=e;*j;j++) { append_to_name(*j); }
15759   }
15760   mp->name_of_file[k]=0;
15761   mp->name_length=k; 
15762 }
15763
15764 @ @<Internal library declarations@>=
15765 void mp_pack_file_name (MP mp, char *n, char *a, char *e) ;
15766
15767 @ A messier routine is also needed, since mem file names must be scanned
15768 before \MP's string mechanism has been initialized. We shall use the
15769 global variable |MP_mem_default| to supply the text for default system areas
15770 and extensions related to mem files.
15771 @^system dependencies@>
15772
15773 @d mem_default_length 9 /* length of the |MP_mem_default| string */
15774 @d mem_ext_length 4 /* length of its `\.{.mem}' part */
15775 @d mem_extension ".mem" /* the extension, as a \.{WEB} constant */
15776
15777 @<Glob...@>=
15778 char *MP_mem_default;
15779 char *mem_name; /* for commandline */
15780
15781 @ @<Option variables@>=
15782 char *mem_name; /* for commandline */
15783
15784 @ @<Allocate or initialize ...@>=
15785 mp->MP_mem_default = xstrdup("plain.mem");
15786 mp->mem_name = xstrdup(opt->mem_name);
15787 @.plain@>
15788 @^system dependencies@>
15789
15790 @ @<Dealloc variables@>=
15791 xfree(mp->MP_mem_default);
15792 xfree(mp->mem_name);
15793
15794 @ @<Check the ``constant'' values for consistency@>=
15795 if ( mem_default_length>file_name_size ) mp->bad=20;
15796
15797 @ Here is the messy routine that was just mentioned. It sets |name_of_file|
15798 from the first |n| characters of |MP_mem_default|, followed by
15799 |buffer[a..b-1]|, followed by the last |mem_ext_length| characters of
15800 |MP_mem_default|.
15801
15802 We dare not give error messages here, since \MP\ calls this routine before
15803 the |error| routine is ready to roll. Instead, we simply drop excess characters,
15804 since the error will be detected in another way when a strange file name
15805 isn't found.
15806 @^system dependencies@>
15807
15808 @c void mp_pack_buffered_name (MP mp,small_number n, integer a,
15809                                integer b) {
15810   integer k; /* number of positions filled in |name_of_file| */
15811   ASCII_code c; /* character being packed */
15812   integer j; /* index into |buffer| or |MP_mem_default| */
15813   if ( n+b-a+1+mem_ext_length>file_name_size )
15814     b=a+file_name_size-n-1-mem_ext_length;
15815   k=0;
15816   for (j=0;j<n;j++) {
15817     append_to_name(xord((int)mp->MP_mem_default[j]));
15818   }
15819   for (j=a;j<b;j++) {
15820     append_to_name(mp->buffer[j]);
15821   }
15822   for (j=mem_default_length-mem_ext_length;
15823       j<mem_default_length;j++) {
15824     append_to_name(xord((int)mp->MP_mem_default[j]));
15825   } 
15826   mp->name_of_file[k]=0;
15827   mp->name_length=k; 
15828 }
15829
15830 @ Here is the only place we use |pack_buffered_name|. This part of the program
15831 becomes active when a ``virgin'' \MP\ is trying to get going, just after
15832 the preliminary initialization, or when the user is substituting another
15833 mem file by typing `\.\&' after the initial `\.{**}' prompt.  The buffer
15834 contains the first line of input in |buffer[loc..(last-1)]|, where
15835 |loc<last| and |buffer[loc]<>" "|.
15836
15837 @<Declarations@>=
15838 boolean mp_open_mem_file (MP mp) ;
15839
15840 @ @c
15841 boolean mp_open_mem_file (MP mp) {
15842   int j; /* the first space after the file name */
15843   if (mp->mem_name!=NULL) {
15844     mp->mem_file = mp_open_file(mp, mp->mem_name, "rb", mp_filetype_memfile);
15845     if ( mp->mem_file ) return true;
15846   }
15847   j=loc;
15848   if ( mp->buffer[loc]=='&' ) {
15849     incr(loc); j=loc; mp->buffer[mp->last]=' ';
15850     while ( mp->buffer[j]!=' ' ) incr(j);
15851     mp_pack_buffered_name(mp, 0,loc,j); /* try first without the system file area */
15852     if ( mp_w_open_in(mp, &mp->mem_file) ) goto FOUND;
15853     wake_up_terminal;
15854     wterm_ln("Sorry, I can\'t find that mem file; will try PLAIN.");
15855 @.Sorry, I can't find...@>
15856     update_terminal;
15857   }
15858   /* now pull out all the stops: try for the system \.{plain} file */
15859   mp_pack_buffered_name(mp, mem_default_length-mem_ext_length,0,0);
15860   if ( ! mp_w_open_in(mp, &mp->mem_file) ) {
15861     wake_up_terminal;
15862     wterm_ln("I can\'t find the PLAIN mem file!\n");
15863 @.I can't find PLAIN...@>
15864 @.plain@>
15865     return false;
15866   }
15867 FOUND:
15868   loc=j; return true;
15869 }
15870
15871 @ Operating systems often make it possible to determine the exact name (and
15872 possible version number) of a file that has been opened. The following routine,
15873 which simply makes a \MP\ string from the value of |name_of_file|, should
15874 ideally be changed to deduce the full name of file~|f|, which is the file
15875 most recently opened, if it is possible to do this in a \PASCAL\ program.
15876 @^system dependencies@>
15877
15878 @<Declarations@>=
15879 #define mp_a_make_name_string(A,B)  mp_make_name_string(A)
15880 #define mp_b_make_name_string(A,B)  mp_make_name_string(A)
15881 #define mp_w_make_name_string(A,B)  mp_make_name_string(A)
15882
15883 @ @c 
15884 str_number mp_make_name_string (MP mp) {
15885   int k; /* index into |name_of_file| */
15886   str_room(mp->name_length);
15887   for (k=0;k<mp->name_length;k++) {
15888     append_char(xord((int)mp->name_of_file[k]));
15889   }
15890   return mp_make_string(mp);
15891 }
15892
15893 @ Now let's consider the ``driver''
15894 routines by which \MP\ deals with file names
15895 in a system-independent manner.  First comes a procedure that looks for a
15896 file name in the input by taking the information from the input buffer.
15897 (We can't use |get_next|, because the conversion to tokens would
15898 destroy necessary information.)
15899
15900 This procedure doesn't allow semicolons or percent signs to be part of
15901 file names, because of other conventions of \MP.
15902 {\sl The {\logos METAFONT\/}book} doesn't
15903 use semicolons or percents immediately after file names, but some users
15904 no doubt will find it natural to do so; therefore system-dependent
15905 changes to allow such characters in file names should probably
15906 be made with reluctance, and only when an entire file name that
15907 includes special characters is ``quoted'' somehow.
15908 @^system dependencies@>
15909
15910 @c void mp_scan_file_name (MP mp) { 
15911   mp_begin_name(mp);
15912   while ( mp->buffer[loc]==' ' ) incr(loc);
15913   while (1) { 
15914     if ( (mp->buffer[loc]==';')||(mp->buffer[loc]=='%') ) break;
15915     if ( ! mp_more_name(mp, mp->buffer[loc]) ) break;
15916     incr(loc);
15917   }
15918   mp_end_name(mp);
15919 }
15920
15921 @ Here is another version that takes its input from a string.
15922
15923 @<Declare subroutines for parsing file names@>=
15924 void mp_str_scan_file (MP mp,  str_number s) {
15925   pool_pointer p,q; /* current position and stopping point */
15926   mp_begin_name(mp);
15927   p=mp->str_start[s]; q=str_stop(s);
15928   while ( p<q ){ 
15929     if ( ! mp_more_name(mp, mp->str_pool[p]) ) break;
15930     incr(p);
15931   }
15932   mp_end_name(mp);
15933 }
15934
15935 @ And one that reads from a |char*|.
15936
15937 @<Declare subroutines for parsing file names@>=
15938 void mp_ptr_scan_file (MP mp,  char *s) {
15939   char *p, *q; /* current position and stopping point */
15940   mp_begin_name(mp);
15941   p=s; q=p+strlen(s);
15942   while ( p<q ){ 
15943     if ( ! mp_more_name(mp, *p)) break;
15944     p++;
15945   }
15946   mp_end_name(mp);
15947 }
15948
15949
15950 @ The global variable |job_name| contains the file name that was first
15951 \&{input} by the user. This name is extended by `\.{.log}' and `\.{ps}' and
15952 `\.{.mem}' and `\.{.tfm}' in order to make the names of \MP's output files.
15953
15954 @<Glob...@>=
15955 char *job_name; /* principal file name */
15956 boolean log_opened; /* has the transcript file been opened? */
15957 char *log_name; /* full name of the log file */
15958
15959 @ @<Option variables@>=
15960 char *job_name; /* principal file name */
15961
15962 @ Initially |job_name=NULL|; it becomes nonzero as soon as the true name is known.
15963 We have |job_name=NULL| if and only if the `\.{log}' file has not been opened,
15964 except of course for a short time just after |job_name| has become nonzero.
15965
15966 @<Allocate or ...@>=
15967 mp->job_name=opt->job_name; 
15968 mp->log_opened=false;
15969
15970 @ @<Dealloc variables@>=
15971 xfree(mp->job_name);
15972
15973 @ Here is a routine that manufactures the output file names, assuming that
15974 |job_name<>0|. It ignores and changes the current settings of |cur_area|
15975 and |cur_ext|.
15976
15977 @d pack_cur_name mp_pack_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext)
15978
15979 @<Declarations@>=
15980 void mp_pack_job_name (MP mp, char *s) ;
15981
15982 @ @c void mp_pack_job_name (MP mp, char  *s) { /* |s = ".log"|, |".mem"|, |".ps"|, or .\\{nnn} */
15983   xfree(mp->cur_name); mp->cur_name=xstrdup(mp->job_name);
15984   xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
15985   xfree(mp->cur_ext);  mp->cur_ext=xstrdup(s);
15986   pack_cur_name;
15987 }
15988
15989 @ If some trouble arises when \MP\ tries to open a file, the following
15990 routine calls upon the user to supply another file name. Parameter~|s|
15991 is used in the error message to identify the type of file; parameter~|e|
15992 is the default extension if none is given. Upon exit from the routine,
15993 variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
15994 ready for another attempt at file opening.
15995
15996 @<Declarations@>=
15997 void mp_prompt_file_name (MP mp,char * s, char * e) ;
15998
15999 @ @c void mp_prompt_file_name (MP mp,char * s, char * e) {
16000   size_t k; /* index into |buffer| */
16001   char * saved_cur_name;
16002   if ( mp->interaction==mp_scroll_mode ) 
16003         wake_up_terminal;
16004   if (strcmp(s,"input file name")==0) {
16005         print_err("I can\'t find file `");
16006 @.I can't find file x@>
16007   } else {
16008         print_err("I can\'t write on file `");
16009   }
16010 @.I can't write on file x@>
16011   mp_print_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext); 
16012   mp_print(mp, "'.");
16013   if (strcmp(e,"")==0) 
16014         mp_show_context(mp);
16015   mp_print_nl(mp, "Please type another "); mp_print(mp, s);
16016 @.Please type...@>
16017   if ( mp->interaction<mp_scroll_mode )
16018     mp_fatal_error(mp, "*** (job aborted, file error in nonstop mode)");
16019 @.job aborted, file error...@>
16020   saved_cur_name = xstrdup(mp->cur_name);
16021   clear_terminal; prompt_input(": "); @<Scan file name in the buffer@>;
16022   if (strcmp(mp->cur_ext,"")==0) 
16023         mp->cur_ext=e;
16024   if (strlen(mp->cur_name)==0) {
16025     mp->cur_name=saved_cur_name;
16026   } else {
16027     xfree(saved_cur_name);
16028   }
16029   pack_cur_name;
16030 }
16031
16032 @ @<Scan file name in the buffer@>=
16033
16034   mp_begin_name(mp); k=mp->first;
16035   while ( (mp->buffer[k]==' ')&&(k<mp->last) ) incr(k);
16036   while (1) { 
16037     if ( k==mp->last ) break;
16038     if ( ! mp_more_name(mp, mp->buffer[k]) ) break;
16039     incr(k);
16040   }
16041   mp_end_name(mp);
16042 }
16043
16044 @ The |open_log_file| routine is used to open the transcript file and to help
16045 it catch up to what has previously been printed on the terminal.
16046
16047 @c void mp_open_log_file (MP mp) {
16048   int old_setting; /* previous |selector| setting */
16049   int k; /* index into |months| and |buffer| */
16050   int l; /* end of first input line */
16051   integer m; /* the current month */
16052   char *months="JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"; 
16053     /* abbreviations of month names */
16054   old_setting=mp->selector;
16055   if ( mp->job_name==NULL ) {
16056      mp->job_name=xstrdup("mpout");
16057   }
16058   mp_pack_job_name(mp,".log");
16059   while ( ! mp_a_open_out(mp, &mp->log_file, mp_filetype_log) ) {
16060     @<Try to get a different log file name@>;
16061   }
16062   mp->log_name=xstrdup(mp->name_of_file);
16063   mp->selector=log_only; mp->log_opened=true;
16064   @<Print the banner line, including the date and time@>;
16065   mp->input_stack[mp->input_ptr]=mp->cur_input; 
16066     /* make sure bottom level is in memory */
16067   mp_print_nl(mp, "**");
16068 @.**@>
16069   l=mp->input_stack[0].limit_field-1; /* last position of first line */
16070   for (k=0;k<=l;k++) mp_print_str(mp, mp->buffer[k]);
16071   mp_print_ln(mp); /* now the transcript file contains the first line of input */
16072   mp->selector=old_setting+2; /* |log_only| or |term_and_log| */
16073 }
16074
16075 @ @<Dealloc variables@>=
16076 xfree(mp->log_name);
16077
16078 @ Sometimes |open_log_file| is called at awkward moments when \MP\ is
16079 unable to print error messages or even to |show_context|.
16080 The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
16081 routine will not be invoked because |log_opened| will be false.
16082
16083 The normal idea of |mp_batch_mode| is that nothing at all should be written
16084 on the terminal. However, in the unusual case that
16085 no log file could be opened, we make an exception and allow
16086 an explanatory message to be seen.
16087
16088 Incidentally, the program always refers to the log file as a `\.{transcript
16089 file}', because some systems cannot use the extension `\.{.log}' for
16090 this file.
16091
16092 @<Try to get a different log file name@>=
16093 {  
16094   mp->selector=term_only;
16095   mp_prompt_file_name(mp, "transcript file name",".log");
16096 }
16097
16098 @ @<Print the banner...@>=
16099
16100   wlog(banner);
16101   mp_print(mp, mp->mem_ident); mp_print(mp, "  ");
16102   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_day])); 
16103   mp_print_char(mp, ' ');
16104   m=mp_round_unscaled(mp, mp->internal[mp_month]);
16105   for (k=3*m-3;k<3*m;k++) { wlog_chr(months[k]); }
16106   mp_print_char(mp, ' '); 
16107   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_year])); 
16108   mp_print_char(mp, ' ');
16109   m=mp_round_unscaled(mp, mp->internal[mp_time]);
16110   mp_print_dd(mp, m / 60); mp_print_char(mp, ':'); mp_print_dd(mp, m % 60);
16111 }
16112
16113 @ The |try_extension| function tries to open an input file determined by
16114 |cur_name|, |cur_area|, and the argument |ext|.  It returns |false| if it
16115 can't find the file in |cur_area| or the appropriate system area.
16116
16117 @c boolean mp_try_extension (MP mp,char *ext) { 
16118   mp_pack_file_name(mp, mp->cur_name,mp->cur_area, ext);
16119   in_name=xstrdup(mp->cur_name); 
16120   in_area=xstrdup(mp->cur_area);
16121   if ( mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16122     return true;
16123   } else { 
16124     if (strcmp(ext,".mf")==0 ) in_area=xstrdup(MF_area);
16125     else in_area=xstrdup(MP_area);
16126     mp_pack_file_name(mp, mp->cur_name,in_area,ext);
16127     return mp_a_open_in(mp, &cur_file, mp_filetype_program);
16128   }
16129   return false;
16130 }
16131
16132 @ Let's turn now to the procedure that is used to initiate file reading
16133 when an `\.{input}' command is being processed.
16134
16135 @c void mp_start_input (MP mp) { /* \MP\ will \.{input} something */
16136   char *fname = NULL;
16137   @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>;
16138   while (1) { 
16139     mp_begin_file_reading(mp); /* set up |cur_file| and new level of input */
16140     if ( strlen(mp->cur_ext)==0 ) {
16141       if ( mp_try_extension(mp, ".mp") ) break;
16142       else if ( mp_try_extension(mp, "") ) break;
16143       else if ( mp_try_extension(mp, ".mf") ) break;
16144       /* |else do_nothing; | */
16145     } else if ( mp_try_extension(mp, mp->cur_ext) ) {
16146       break;
16147     }
16148     mp_end_file_reading(mp); /* remove the level that didn't work */
16149     mp_prompt_file_name(mp, "input file name","");
16150   }
16151   name=mp_a_make_name_string(mp, cur_file);
16152   fname = xstrdup(mp->name_of_file);
16153   if ( mp->job_name==NULL ) {
16154     mp->job_name=xstrdup(mp->cur_name); 
16155     mp_open_log_file(mp);
16156   } /* |open_log_file| doesn't |show_context|, so |limit|
16157         and |loc| needn't be set to meaningful values yet */
16158   if ( ((int)mp->term_offset+(int)strlen(fname)) > (mp->max_print_line-2)) mp_print_ln(mp);
16159   else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
16160   mp_print_char(mp, '('); incr(mp->open_parens); mp_print(mp, fname); 
16161   xfree(fname);
16162   update_terminal;
16163   @<Flush |name| and replace it with |cur_name| if it won't be needed@>;
16164   @<Read the first line of the new file@>;
16165 }
16166
16167 @ This code should be omitted if |a_make_name_string| returns something other
16168 than just a copy of its argument and the full file name is needed for opening
16169 \.{MPX} files or implementing the switch-to-editor option.
16170 @^system dependencies@>
16171
16172 @<Flush |name| and replace it with |cur_name| if it won't be needed@>=
16173 mp_flush_string(mp, name); name=rts(mp->cur_name); xfree(mp->cur_name)
16174
16175 @ Here we have to remember to tell the |input_ln| routine not to
16176 start with a |get|. If the file is empty, it is considered to
16177 contain a single blank line.
16178 @^system dependencies@>
16179
16180 @<Read the first line...@>=
16181
16182   line=1;
16183   (void)mp_input_ln(mp, cur_file,false); 
16184   mp_firm_up_the_line(mp);
16185   mp->buffer[limit]='%'; mp->first=limit+1; loc=start;
16186 }
16187
16188 @ @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>=
16189 while ( token_state &&(loc==null) ) mp_end_token_list(mp);
16190 if ( token_state ) { 
16191   print_err("File names can't appear within macros");
16192 @.File names can't...@>
16193   help3("Sorry...I've converted what follows to tokens,")
16194     ("possibly garbaging the name you gave.")
16195     ("Please delete the tokens and insert the name again.");
16196   mp_error(mp);
16197 }
16198 if ( file_state ) {
16199   mp_scan_file_name(mp);
16200 } else { 
16201    xfree(mp->cur_name); mp->cur_name=xstrdup(""); 
16202    xfree(mp->cur_ext);  mp->cur_ext =xstrdup(""); 
16203    xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
16204 }
16205
16206 @ Sometimes we need to deal with two file names at once.  This procedure
16207 copies the given string into a special array for an old file name.
16208
16209 @c void mp_copy_old_name (MP mp,str_number s) {
16210   integer k; /* number of positions filled in |old_file_name| */
16211   pool_pointer j; /* index into |str_pool| */
16212   k=0;
16213   for (j=mp->str_start[s];j<=str_stop(s)-1;j++) { 
16214     incr(k);
16215     if ( k<=file_name_size ) 
16216       mp->old_file_name[k]=xchr(mp->str_pool[j]);
16217   }
16218   mp->old_file_name[++k] = 0;
16219 }
16220
16221 @ @<Glob...@>=
16222 char old_file_name[file_name_size+1];  /* analogous to |name_of_file| */
16223
16224 @ The following simple routine starts reading the \.{MPX} file associated
16225 with the current input file.
16226
16227 @c void mp_start_mpx_input (MP mp) {
16228   mp_pack_file_name(mp, in_name, in_area, ".mpx");
16229   @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16230     |goto not_found| if there is a problem@>;
16231   mp_begin_file_reading(mp);
16232   if ( ! mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16233     mp_end_file_reading(mp);
16234     goto NOT_FOUND;
16235   }
16236   name=mp_a_make_name_string(mp, cur_file);
16237   mp->mpx_name[index]=name; add_str_ref(name);
16238   @<Read the first line of the new file@>;
16239   return;
16240 NOT_FOUND: 
16241     @<Explain that the \.{MPX} file can't be read and |succumb|@>;
16242 }
16243
16244 @ This should ideally be changed to do whatever is necessary to create the
16245 \.{MPX} file given by |name_of_file| if it does not exist or if it is out
16246 of date.  This requires invoking \.{MPtoTeX} on the |old_file_name| and passing
16247 the results through \TeX\ and \.{DVItoMP}.  (It is possible to use a
16248 completely different typesetting program if suitable postprocessor is
16249 available to perform the function of \.{DVItoMP}.)
16250 @^system dependencies@>
16251
16252 @ @<Exported types@>=
16253 typedef int (*mp_run_make_mpx_command)(MP mp, char *origname, char *mtxname);
16254
16255 @ @<Glob...@>=
16256 mp_run_make_mpx_command run_make_mpx;
16257
16258 @ @<Option variables@>=
16259 mp_run_make_mpx_command run_make_mpx;
16260
16261 @ @<Allocate or initialize ...@>=
16262 set_callback_option(run_make_mpx);
16263
16264 @ @<Internal library declarations@>=
16265 int mp_run_make_mpx (MP mp, char *origname, char *mtxname);
16266
16267 @ The default does nothing.
16268 @c 
16269 int mp_run_make_mpx (MP mp, char *origname, char *mtxname) {
16270   if (mp && origname && mtxname) /* for -W */
16271     return false;
16272   return false;
16273 }
16274
16275
16276
16277 @ @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16278   |goto not_found| if there is a problem@>=
16279 mp_copy_old_name(mp, name);
16280 if (!(mp->run_make_mpx)(mp, mp->old_file_name, mp->name_of_file))
16281    goto NOT_FOUND
16282
16283 @ @<Explain that the \.{MPX} file can't be read and |succumb|@>=
16284 if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16285 mp_print_nl(mp, ">> ");
16286 mp_print(mp, mp->old_file_name);
16287 mp_print_nl(mp, ">> ");
16288 mp_print(mp, mp->name_of_file);
16289 mp_print_nl(mp, "! Unable to make mpx file");
16290 help4("The two files given above are one of your source files")
16291   ("and an auxiliary file I need to read to find out what your")
16292   ("btex..etex blocks mean. If you don't know why I had trouble,")
16293   ("try running it manually through MPtoTeX, TeX, and DVItoMP");
16294 succumb;
16295
16296 @ The last file-opening commands are for files accessed via the \&{readfrom}
16297 @:read_from_}{\&{readfrom} primitive@>
16298 operator and the \&{write} command.  Such files are stored in separate arrays.
16299 @:write_}{\&{write} primitive@>
16300
16301 @<Types in the outer block@>=
16302 typedef unsigned int readf_index; /* |0..max_read_files| */
16303 typedef unsigned int write_index;  /* |0..max_write_files| */
16304
16305 @ @<Glob...@>=
16306 readf_index max_read_files; /* maximum number of simultaneously open \&{readfrom} files */
16307 FILE ** rd_file; /* \&{readfrom} files */
16308 char ** rd_fname; /* corresponding file name or 0 if file not open */
16309 readf_index read_files; /* number of valid entries in the above arrays */
16310 write_index max_write_files; /* maximum number of simultaneously open \&{write} */
16311 FILE ** wr_file; /* \&{write} files */
16312 char ** wr_fname; /* corresponding file name or 0 if file not open */
16313 write_index write_files; /* number of valid entries in the above arrays */
16314
16315 @ @<Allocate or initialize ...@>=
16316 mp->max_read_files=8;
16317 mp->rd_file = xmalloc((mp->max_read_files+1),sizeof(FILE *));
16318 mp->rd_fname = xmalloc((mp->max_read_files+1),sizeof(char *));
16319 memset(mp->rd_fname, 0, sizeof(char *)*(mp->max_read_files+1));
16320 mp->read_files=0;
16321 mp->max_write_files=8;
16322 mp->wr_file = xmalloc((mp->max_write_files+1),sizeof(FILE *));
16323 mp->wr_fname = xmalloc((mp->max_write_files+1),sizeof(char *));
16324 memset(mp->wr_fname, 0, sizeof(char *)*(mp->max_write_files+1));
16325 mp->write_files=0;
16326
16327
16328 @ This routine starts reading the file named by string~|s| without setting
16329 |loc|, |limit|, or |name|.  It returns |false| if the file is empty or cannot
16330 be opened.  Otherwise it updates |rd_file[n]| and |rd_fname[n]|.
16331
16332 @c boolean mp_start_read_input (MP mp,char *s, readf_index  n) {
16333   mp_ptr_scan_file(mp, s);
16334   pack_cur_name;
16335   mp_begin_file_reading(mp);
16336   if ( ! mp_a_open_in(mp, &mp->rd_file[n], mp_filetype_text) ) 
16337         goto NOT_FOUND;
16338   if ( ! mp_input_ln(mp, mp->rd_file[n], false) ) {
16339     fclose(mp->rd_file[n]); 
16340         goto NOT_FOUND; 
16341   }
16342   mp->rd_fname[n]=xstrdup(mp->name_of_file);
16343   return true;
16344 NOT_FOUND: 
16345   mp_end_file_reading(mp);
16346   return false;
16347 }
16348
16349 @ Open |wr_file[n]| using file name~|s| and update |wr_fname[n]|.
16350
16351 @<Declarations@>=
16352 void mp_open_write_file (MP mp, char *s, readf_index  n) ;
16353
16354 @ @c void mp_open_write_file (MP mp,char *s, readf_index  n) {
16355   mp_ptr_scan_file(mp, s);
16356   pack_cur_name;
16357   while ( ! mp_a_open_out(mp, &mp->wr_file[n], mp_filetype_text) )
16358     mp_prompt_file_name(mp, "file name for write output","");
16359   mp->wr_fname[n]=xstrdup(mp->name_of_file);
16360 }
16361
16362
16363 @* \[36] Introduction to the parsing routines.
16364 We come now to the central nervous system that sparks many of \MP's activities.
16365 By evaluating expressions, from their primary constituents to ever larger
16366 subexpressions, \MP\ builds the structures that ultimately define complete
16367 pictures or fonts of type.
16368
16369 Four mutually recursive subroutines are involved in this process: We call them
16370 $$\hbox{|scan_primary|, |scan_secondary|, |scan_tertiary|,
16371 and |scan_expression|.}$$
16372 @^recursion@>
16373 Each of them is parameterless and begins with the first token to be scanned
16374 already represented in |cur_cmd|, |cur_mod|, and |cur_sym|. After execution,
16375 the value of the primary or secondary or tertiary or expression that was
16376 found will appear in the global variables |cur_type| and |cur_exp|. The
16377 token following the expression will be represented in |cur_cmd|, |cur_mod|,
16378 and |cur_sym|.
16379
16380 Technically speaking, the parsing algorithms are ``LL(1),'' more or less;
16381 backup mechanisms have been added in order to provide reasonable error
16382 recovery.
16383
16384 @<Glob...@>=
16385 small_number cur_type; /* the type of the expression just found */
16386 integer cur_exp; /* the value of the expression just found */
16387
16388 @ @<Set init...@>=
16389 mp->cur_exp=0;
16390
16391 @ Many different kinds of expressions are possible, so it is wise to have
16392 precise descriptions of what |cur_type| and |cur_exp| mean in all cases:
16393
16394 \smallskip\hang
16395 |cur_type=mp_vacuous| means that this expression didn't turn out to have a
16396 value at all, because it arose from a \&{begingroup}$\,\ldots\,$\&{endgroup}
16397 construction in which there was no expression before the \&{endgroup}.
16398 In this case |cur_exp| has some irrelevant value.
16399
16400 \smallskip\hang
16401 |cur_type=mp_boolean_type| means that |cur_exp| is either |true_code|
16402 or |false_code|.
16403
16404 \smallskip\hang
16405 |cur_type=mp_unknown_boolean| means that |cur_exp| points to a capsule
16406 node that is in the ring of variables equivalent
16407 to at least one undefined boolean variable.
16408
16409 \smallskip\hang
16410 |cur_type=mp_string_type| means that |cur_exp| is a string number (i.e., an
16411 integer in the range |0<=cur_exp<str_ptr|). That string's reference count
16412 includes this particular reference.
16413
16414 \smallskip\hang
16415 |cur_type=mp_unknown_string| means that |cur_exp| points to a capsule
16416 node that is in the ring of variables equivalent
16417 to at least one undefined string variable.
16418
16419 \smallskip\hang
16420 |cur_type=mp_pen_type| means that |cur_exp| points to a node in a pen.  Nobody
16421 else points to any of the nodes in this pen.  The pen may be polygonal or
16422 elliptical.
16423
16424 \smallskip\hang
16425 |cur_type=mp_unknown_pen| means that |cur_exp| points to a capsule
16426 node that is in the ring of variables equivalent
16427 to at least one undefined pen variable.
16428
16429 \smallskip\hang
16430 |cur_type=mp_path_type| means that |cur_exp| points to a the first node of
16431 a path; nobody else points to this particular path. The control points of
16432 the path will have been chosen.
16433
16434 \smallskip\hang
16435 |cur_type=mp_unknown_path| means that |cur_exp| points to a capsule
16436 node that is in the ring of variables equivalent
16437 to at least one undefined path variable.
16438
16439 \smallskip\hang
16440 |cur_type=mp_picture_type| means that |cur_exp| points to an edge header node.
16441 There may be other pointers to this particular set of edges.  The header node
16442 contains a reference count that includes this particular reference.
16443
16444 \smallskip\hang
16445 |cur_type=mp_unknown_picture| means that |cur_exp| points to a capsule
16446 node that is in the ring of variables equivalent
16447 to at least one undefined picture variable.
16448
16449 \smallskip\hang
16450 |cur_type=mp_transform_type| means that |cur_exp| points to a |mp_transform_type|
16451 capsule node. The |value| part of this capsule
16452 points to a transform node that contains six numeric values,
16453 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16454
16455 \smallskip\hang
16456 |cur_type=mp_color_type| means that |cur_exp| points to a |color_type|
16457 capsule node. The |value| part of this capsule
16458 points to a color node that contains three numeric values,
16459 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16460
16461 \smallskip\hang
16462 |cur_type=mp_cmykcolor_type| means that |cur_exp| points to a |mp_cmykcolor_type|
16463 capsule node. The |value| part of this capsule
16464 points to a color node that contains four numeric values,
16465 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16466
16467 \smallskip\hang
16468 |cur_type=mp_pair_type| means that |cur_exp| points to a capsule
16469 node whose type is |mp_pair_type|. The |value| part of this capsule
16470 points to a pair node that contains two numeric values,
16471 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16472
16473 \smallskip\hang
16474 |cur_type=mp_known| means that |cur_exp| is a |scaled| value.
16475
16476 \smallskip\hang
16477 |cur_type=mp_dependent| means that |cur_exp| points to a capsule node whose type
16478 is |dependent|. The |dep_list| field in this capsule points to the associated
16479 dependency list.
16480
16481 \smallskip\hang
16482 |cur_type=mp_proto_dependent| means that |cur_exp| points to a |mp_proto_dependent|
16483 capsule node. The |dep_list| field in this capsule
16484 points to the associated dependency list.
16485
16486 \smallskip\hang
16487 |cur_type=independent| means that |cur_exp| points to a capsule node
16488 whose type is |independent|. This somewhat unusual case can arise, for
16489 example, in the expression
16490 `$x+\&{begingroup}\penalty0\,\&{string}\,x; 0\,\&{endgroup}$'.
16491
16492 \smallskip\hang
16493 |cur_type=mp_token_list| means that |cur_exp| points to a linked list of
16494 tokens. This case arises only on the left-hand side of an assignment
16495 (`\.{:=}') operation, under very special circumstances.
16496
16497 \smallskip\noindent
16498 The possible settings of |cur_type| have been listed here in increasing
16499 numerical order. Notice that |cur_type| will never be |mp_numeric_type| or
16500 |suffixed_macro| or |mp_unsuffixed_macro|, although variables of those types
16501 are allowed.  Conversely, \MP\ has no variables of type |mp_vacuous| or
16502 |token_list|.
16503
16504 @ Capsules are two-word nodes that have a similar meaning
16505 to |cur_type| and |cur_exp|. Such nodes have |name_type=capsule|
16506 and |link<=mp_void|; and their |type| field is one of the possibilities for
16507 |cur_type| listed above.
16508
16509 The |value| field of a capsule is, in most cases, the value that
16510 corresponds to its |type|, as |cur_exp| corresponds to |cur_type|.
16511 However, when |cur_exp| would point to a capsule,
16512 no extra layer of indirection is present; the |value|
16513 field is what would have been called |value(cur_exp)| if it had not been
16514 encapsulated.  Furthermore, if the type is |dependent| or
16515 |mp_proto_dependent|, the |value| field of a capsule is replaced by
16516 |dep_list| and |prev_dep| fields, since dependency lists in capsules are
16517 always part of the general |dep_list| structure.
16518
16519 The |get_x_next| routine is careful not to change the values of |cur_type|
16520 and |cur_exp| when it gets an expanded token. However, |get_x_next| might
16521 call a macro, which might parse an expression, which might execute lots of
16522 commands in a group; hence it's possible that |cur_type| might change
16523 from, say, |mp_unknown_boolean| to |mp_boolean_type|, or from |dependent| to
16524 |known| or |independent|, during the time |get_x_next| is called. The
16525 programs below are careful to stash sensitive intermediate results in
16526 capsules, so that \MP's generality doesn't cause trouble.
16527
16528 Here's a procedure that illustrates these conventions. It takes
16529 the contents of $(|cur_type|\kern-.3pt,|cur_exp|\kern-.3pt)$
16530 and stashes them away in a
16531 capsule. It is not used when |cur_type=mp_token_list|.
16532 After the operation, |cur_type=mp_vacuous|; hence there is no need to
16533 copy path lists or to update reference counts, etc.
16534
16535 The special link |mp_void| is put on the capsule returned by
16536 |stash_cur_exp|, because this procedure is used to store macro parameters
16537 that must be easily distinguishable from token lists.
16538
16539 @<Declare the stashing/unstashing routines@>=
16540 pointer mp_stash_cur_exp (MP mp) {
16541   pointer p; /* the capsule that will be returned */
16542   switch (mp->cur_type) {
16543   case unknown_types:
16544   case mp_transform_type:
16545   case mp_color_type:
16546   case mp_pair_type:
16547   case mp_dependent:
16548   case mp_proto_dependent:
16549   case mp_independent: 
16550   case mp_cmykcolor_type:
16551     p=mp->cur_exp;
16552     break;
16553   default: 
16554     p=mp_get_node(mp, value_node_size); name_type(p)=mp_capsule;
16555     type(p)=mp->cur_type; value(p)=mp->cur_exp;
16556     break;
16557   }
16558   mp->cur_type=mp_vacuous; link(p)=mp_void; 
16559   return p;
16560 }
16561
16562 @ The inverse of |stash_cur_exp| is the following procedure, which
16563 deletes an unnecessary capsule and puts its contents into |cur_type|
16564 and |cur_exp|.
16565
16566 The program steps of \MP\ can be divided into two categories: those in
16567 which |cur_type| and |cur_exp| are ``alive'' and those in which they are
16568 ``dead,'' in the sense that |cur_type| and |cur_exp| contain relevant
16569 information or not. It's important not to ignore them when they're alive,
16570 and it's important not to pay attention to them when they're dead.
16571
16572 There's also an intermediate category: If |cur_type=mp_vacuous|, then
16573 |cur_exp| is irrelevant, hence we can proceed without caring if |cur_type|
16574 and |cur_exp| are alive or dead. In such cases we say that |cur_type|
16575 and |cur_exp| are {\sl dormant}. It is permissible to call |get_x_next|
16576 only when they are alive or dormant.
16577
16578 The \\{stash} procedure above assumes that |cur_type| and |cur_exp|
16579 are alive or dormant. The \\{unstash} procedure assumes that they are
16580 dead or dormant; it resuscitates them.
16581
16582 @<Declare the stashing/unstashing...@>=
16583 void mp_unstash_cur_exp (MP mp,pointer p) ;
16584
16585 @ @c
16586 void mp_unstash_cur_exp (MP mp,pointer p) { 
16587   mp->cur_type=type(p);
16588   switch (mp->cur_type) {
16589   case unknown_types:
16590   case mp_transform_type:
16591   case mp_color_type:
16592   case mp_pair_type:
16593   case mp_dependent: 
16594   case mp_proto_dependent:
16595   case mp_independent:
16596   case mp_cmykcolor_type: 
16597     mp->cur_exp=p;
16598     break;
16599   default:
16600     mp->cur_exp=value(p);
16601     mp_free_node(mp, p,value_node_size);
16602     break;
16603   }
16604 }
16605
16606 @ The following procedure prints the values of expressions in an
16607 abbreviated format. If its first parameter |p| is null, the value of
16608 |(cur_type,cur_exp)| is displayed; otherwise |p| should be a capsule
16609 containing the desired value. The second parameter controls the amount of
16610 output. If it is~0, dependency lists will be abbreviated to
16611 `\.{linearform}' unless they consist of a single term.  If it is greater
16612 than~1, complicated structures (pens, pictures, and paths) will be displayed
16613 in full.
16614
16615 @<Declare subroutines for printing expressions@>=
16616 @<Declare the procedure called |print_dp|@>;
16617 @<Declare the stashing/unstashing routines@>;
16618 void mp_print_exp (MP mp,pointer p, small_number verbosity) {
16619   boolean restore_cur_exp; /* should |cur_exp| be restored? */
16620   small_number t; /* the type of the expression */
16621   pointer q; /* a big node being displayed */
16622   integer v=0; /* the value of the expression */
16623   if ( p!=null ) {
16624     restore_cur_exp=false;
16625   } else { 
16626     p=mp_stash_cur_exp(mp); restore_cur_exp=true;
16627   }
16628   t=type(p);
16629   if ( t<mp_dependent ) v=value(p); else if ( t<mp_independent ) v=dep_list(p);
16630   @<Print an abbreviated value of |v| with format depending on |t|@>;
16631   if ( restore_cur_exp ) mp_unstash_cur_exp(mp, p);
16632 }
16633
16634 @ @<Print an abbreviated value of |v| with format depending on |t|@>=
16635 switch (t) {
16636 case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
16637 case mp_boolean_type:
16638   if ( v==true_code ) mp_print(mp, "true"); else mp_print(mp, "false");
16639   break;
16640 case unknown_types: case mp_numeric_type:
16641   @<Display a variable that's been declared but not defined@>;
16642   break;
16643 case mp_string_type:
16644   mp_print_char(mp, '"'); mp_print_str(mp, v); mp_print_char(mp, '"');
16645   break;
16646 case mp_pen_type: case mp_path_type: case mp_picture_type:
16647   @<Display a complex type@>;
16648   break;
16649 case mp_transform_type: case mp_color_type: case mp_pair_type: case mp_cmykcolor_type:
16650   if ( v==null ) mp_print_type(mp, t);
16651   else @<Display a big node@>;
16652   break;
16653 case mp_known:mp_print_scaled(mp, v); break;
16654 case mp_dependent: case mp_proto_dependent:
16655   mp_print_dp(mp, t,v,verbosity);
16656   break;
16657 case mp_independent:mp_print_variable_name(mp, p); break;
16658 default: mp_confusion(mp, "exp"); break;
16659 @:this can't happen exp}{\quad exp@>
16660 }
16661
16662 @ @<Display a big node@>=
16663
16664   mp_print_char(mp, '('); q=v+mp->big_node_size[t];
16665   do {  
16666     if ( type(v)==mp_known ) mp_print_scaled(mp, value(v));
16667     else if ( type(v)==mp_independent ) mp_print_variable_name(mp, v);
16668     else mp_print_dp(mp, type(v),dep_list(v),verbosity);
16669     v=v+2;
16670     if ( v!=q ) mp_print_char(mp, ',');
16671   } while (v!=q);
16672   mp_print_char(mp, ')');
16673 }
16674
16675 @ Values of type \&{picture}, \&{path}, and \&{pen} are displayed verbosely
16676 in the log file only, unless the user has given a positive value to
16677 \\{tracingonline}.
16678
16679 @<Display a complex type@>=
16680 if ( verbosity<=1 ) {
16681   mp_print_type(mp, t);
16682 } else { 
16683   if ( mp->selector==term_and_log )
16684    if ( mp->internal[mp_tracing_online]<=0 ) {
16685     mp->selector=term_only;
16686     mp_print_type(mp, t); mp_print(mp, " (see the transcript file)");
16687     mp->selector=term_and_log;
16688   };
16689   switch (t) {
16690   case mp_pen_type:mp_print_pen(mp, v,"",false); break;
16691   case mp_path_type:mp_print_path(mp, v,"",false); break;
16692   case mp_picture_type:mp_print_edges(mp, v,"",false); break;
16693   } /* there are no other cases */
16694 }
16695
16696 @ @<Declare the procedure called |print_dp|@>=
16697 void mp_print_dp (MP mp,small_number t, pointer p, 
16698                   small_number verbosity)  {
16699   pointer q; /* the node following |p| */
16700   q=link(p);
16701   if ( (info(q)==null) || (verbosity>0) ) mp_print_dependency(mp, p,t);
16702   else mp_print(mp, "linearform");
16703 }
16704
16705 @ The displayed name of a variable in a ring will not be a capsule unless
16706 the ring consists entirely of capsules.
16707
16708 @<Display a variable that's been declared but not defined@>=
16709 { mp_print_type(mp, t);
16710 if ( v!=null )
16711   { mp_print_char(mp, ' ');
16712   while ( (name_type(v)==mp_capsule) && (v!=p) ) v=value(v);
16713   mp_print_variable_name(mp, v);
16714   };
16715 }
16716
16717 @ When errors are detected during parsing, it is often helpful to
16718 display an expression just above the error message, using |exp_err|
16719 or |disp_err| instead of |print_err|.
16720
16721 @d exp_err(A) mp_disp_err(mp, null,(A)) /* displays the current expression */
16722
16723 @<Declare subroutines for printing expressions@>=
16724 void mp_disp_err (MP mp,pointer p, char *s) { 
16725   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16726   mp_print_nl(mp, ">> ");
16727 @.>>@>
16728   mp_print_exp(mp, p,1); /* ``medium verbose'' printing of the expression */
16729   if (strlen(s)) { 
16730     mp_print_nl(mp, "! "); mp_print(mp, s);
16731 @.!\relax@>
16732   }
16733 }
16734
16735 @ If |cur_type| and |cur_exp| contain relevant information that should
16736 be recycled, we will use the following procedure, which changes |cur_type|
16737 to |known| and stores a given value in |cur_exp|. We can think of |cur_type|
16738 and |cur_exp| as either alive or dormant after this has been done,
16739 because |cur_exp| will not contain a pointer value.
16740
16741 @ @c void mp_flush_cur_exp (MP mp,scaled v) { 
16742   switch (mp->cur_type) {
16743   case unknown_types: case mp_transform_type: case mp_color_type: case mp_pair_type:
16744   case mp_dependent: case mp_proto_dependent: case mp_independent: case mp_cmykcolor_type:
16745     mp_recycle_value(mp, mp->cur_exp); 
16746     mp_free_node(mp, mp->cur_exp,value_node_size);
16747     break;
16748   case mp_string_type:
16749     delete_str_ref(mp->cur_exp); break;
16750   case mp_pen_type: case mp_path_type: 
16751     mp_toss_knot_list(mp, mp->cur_exp); break;
16752   case mp_picture_type:
16753     delete_edge_ref(mp->cur_exp); break;
16754   default: 
16755     break;
16756   }
16757   mp->cur_type=mp_known; mp->cur_exp=v;
16758 }
16759
16760 @ There's a much more general procedure that is capable of releasing
16761 the storage associated with any two-word value packet.
16762
16763 @<Declare the recycling subroutines@>=
16764 void mp_recycle_value (MP mp,pointer p) ;
16765
16766 @ @c void mp_recycle_value (MP mp,pointer p) {
16767   small_number t; /* a type code */
16768   integer vv; /* another value */
16769   pointer q,r,s,pp; /* link manipulation registers */
16770   integer v=0; /* a value */
16771   t=type(p);
16772   if ( t<mp_dependent ) v=value(p);
16773   switch (t) {
16774   case undefined: case mp_vacuous: case mp_boolean_type: case mp_known:
16775   case mp_numeric_type:
16776     break;
16777   case unknown_types:
16778     mp_ring_delete(mp, p); break;
16779   case mp_string_type:
16780     delete_str_ref(v); break;
16781   case mp_path_type: case mp_pen_type:
16782     mp_toss_knot_list(mp, v); break;
16783   case mp_picture_type:
16784     delete_edge_ref(v); break;
16785   case mp_cmykcolor_type: case mp_pair_type: case mp_color_type:
16786   case mp_transform_type:
16787     @<Recycle a big node@>; break; 
16788   case mp_dependent: case mp_proto_dependent:
16789     @<Recycle a dependency list@>; break;
16790   case mp_independent:
16791     @<Recycle an independent variable@>; break;
16792   case mp_token_list: case mp_structured:
16793     mp_confusion(mp, "recycle"); break;
16794 @:this can't happen recycle}{\quad recycle@>
16795   case mp_unsuffixed_macro: case mp_suffixed_macro:
16796     mp_delete_mac_ref(mp, value(p)); break;
16797   } /* there are no other cases */
16798   type(p)=undefined;
16799 }
16800
16801 @ @<Recycle a big node@>=
16802 if ( v!=null ){ 
16803   q=v+mp->big_node_size[t];
16804   do {  
16805     q=q-2; mp_recycle_value(mp, q);
16806   } while (q!=v);
16807   mp_free_node(mp, v,mp->big_node_size[t]);
16808 }
16809
16810 @ @<Recycle a dependency list@>=
16811
16812   q=dep_list(p);
16813   while ( info(q)!=null ) q=link(q);
16814   link(prev_dep(p))=link(q);
16815   prev_dep(link(q))=prev_dep(p);
16816   link(q)=null; mp_flush_node_list(mp, dep_list(p));
16817 }
16818
16819 @ When an independent variable disappears, it simply fades away, unless
16820 something depends on it. In the latter case, a dependent variable whose
16821 coefficient of dependence is maximal will take its place.
16822 The relevant algorithm is due to Ignacio~A. Zabala, who implemented it
16823 as part of his Ph.D. thesis (Stanford University, December 1982).
16824 @^Zabala Salelles, Ignacio Andres@>
16825
16826 For example, suppose that variable $x$ is being recycled, and that the
16827 only variables depending on~$x$ are $y=2x+a$ and $z=x+b$. In this case
16828 we want to make $y$ independent and $z=.5y-.5a+b$; no other variables
16829 will depend on~$y$. If $\\{tracingequations}>0$ in this situation,
16830 we will print `\.{\#\#\# -2x=-y+a}'.
16831
16832 There's a slight complication, however: An independent variable $x$
16833 can occur both in dependency lists and in proto-dependency lists.
16834 This makes it necessary to be careful when deciding which coefficient
16835 is maximal.
16836
16837 Furthermore, this complication is not so slight when
16838 a proto-dependent variable is chosen to become independent. For example,
16839 suppose that $y=2x+100a$ is proto-dependent while $z=x+b$ is dependent;
16840 then we must change $z=.5y-50a+b$ to a proto-dependency, because of the
16841 large coefficient `50'.
16842
16843 In order to deal with these complications without wasting too much time,
16844 we shall link together the occurrences of~$x$ among all the linear
16845 dependencies, maintaining separate lists for the dependent and
16846 proto-dependent cases.
16847
16848 @<Recycle an independent variable@>=
16849
16850   mp->max_c[mp_dependent]=0; mp->max_c[mp_proto_dependent]=0;
16851   mp->max_link[mp_dependent]=null; mp->max_link[mp_proto_dependent]=null;
16852   q=link(dep_head);
16853   while ( q!=dep_head ) { 
16854     s=value_loc(q); /* now |link(s)=dep_list(q)| */
16855     while (1) { 
16856       r=link(s);
16857       if ( info(r)==null ) break;;
16858       if ( info(r)!=p ) { 
16859        s=r;
16860       } else  { 
16861         t=type(q); link(s)=link(r); info(r)=q;
16862         if ( abs(value(r))>mp->max_c[t] ) {
16863           @<Record a new maximum coefficient of type |t|@>;
16864         } else { 
16865           link(r)=mp->max_link[t]; mp->max_link[t]=r;
16866         }
16867       }
16868     }   
16869     q=link(r);
16870   }
16871   if ( (mp->max_c[mp_dependent]>0)||(mp->max_c[mp_proto_dependent]>0) ) {
16872     @<Choose a dependent variable to take the place of the disappearing
16873     independent variable, and change all remaining dependencies
16874     accordingly@>;
16875   }
16876 }
16877
16878 @ The code for independency removal makes use of three two-word arrays.
16879
16880 @<Glob...@>=
16881 integer max_c[mp_proto_dependent+1];  /* max coefficient magnitude */
16882 pointer max_ptr[mp_proto_dependent+1]; /* where |p| occurs with |max_c| */
16883 pointer max_link[mp_proto_dependent+1]; /* other occurrences of |p| */
16884
16885 @ @<Record a new maximum coefficient...@>=
16886
16887   if ( mp->max_c[t]>0 ) {
16888     link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
16889   }
16890   mp->max_c[t]=abs(value(r)); mp->max_ptr[t]=r;
16891 }
16892
16893 @ @<Choose a dependent...@>=
16894
16895   if ( (mp->max_c[mp_dependent] / 010000 >= mp->max_c[mp_proto_dependent]) )
16896     t=mp_dependent;
16897   else 
16898     t=mp_proto_dependent;
16899   @<Determine the dependency list |s| to substitute for the independent
16900     variable~|p|@>;
16901   t=mp_dependent+mp_proto_dependent-t; /* complement |t| */
16902   if ( mp->max_c[t]>0 ) { /* we need to pick up an unchosen dependency */ 
16903     link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
16904   }
16905   if ( t!=mp_dependent ) { @<Substitute new dependencies in place of |p|@>; }
16906   else { @<Substitute new proto-dependencies in place of |p|@>;}
16907   mp_flush_node_list(mp, s);
16908   if ( mp->fix_needed ) mp_fix_dependencies(mp);
16909   check_arith;
16910 }
16911
16912 @ Let |s=max_ptr[t]|. At this point we have $|value|(s)=\pm|max_c|[t]$,
16913 and |info(s)| points to the dependent variable~|pp| of type~|t| from
16914 whose dependency list we have removed node~|s|. We must reinsert
16915 node~|s| into the dependency list, with coefficient $-1.0$, and with
16916 |pp| as the new independent variable. Since |pp| will have a larger serial
16917 number than any other variable, we can put node |s| at the head of the
16918 list.
16919
16920 @<Determine the dep...@>=
16921 s=mp->max_ptr[t]; pp=info(s); v=value(s);
16922 if ( t==mp_dependent ) value(s)=-fraction_one; else value(s)=-unity;
16923 r=dep_list(pp); link(s)=r;
16924 while ( info(r)!=null ) r=link(r);
16925 q=link(r); link(r)=null;
16926 prev_dep(q)=prev_dep(pp); link(prev_dep(pp))=q;
16927 new_indep(pp);
16928 if ( mp->cur_exp==pp ) if ( mp->cur_type==t ) mp->cur_type=mp_independent;
16929 if ( mp->internal[mp_tracing_equations]>0 ) { 
16930   @<Show the transformed dependency@>; 
16931 }
16932
16933 @ Now $(-v)$ times the formerly independent variable~|p| is being replaced
16934 by the dependency list~|s|.
16935
16936 @<Show the transformed...@>=
16937 if ( mp_interesting(mp, p) ) {
16938   mp_begin_diagnostic(mp); mp_print_nl(mp, "### ");
16939 @:]]]\#\#\#_}{\.{\#\#\#}@>
16940   if ( v>0 ) mp_print_char(mp, '-');
16941   if ( t==mp_dependent ) vv=mp_round_fraction(mp, mp->max_c[mp_dependent]);
16942   else vv=mp->max_c[mp_proto_dependent];
16943   if ( vv!=unity ) mp_print_scaled(mp, vv);
16944   mp_print_variable_name(mp, p);
16945   while ( value(p) % s_scale>0 ) {
16946     mp_print(mp, "*4"); value(p)=value(p)-2;
16947   }
16948   if ( t==mp_dependent ) mp_print_char(mp, '='); else mp_print(mp, " = ");
16949   mp_print_dependency(mp, s,t);
16950   mp_end_diagnostic(mp, false);
16951 }
16952
16953 @ Finally, there are dependent and proto-dependent variables whose
16954 dependency lists must be brought up to date.
16955
16956 @<Substitute new dependencies...@>=
16957 for (t=mp_dependent;t<=mp_proto_dependent;t++){ 
16958   r=mp->max_link[t];
16959   while ( r!=null ) {
16960     q=info(r);
16961     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
16962      mp_make_fraction(mp, value(r),-v),s,t,mp_dependent);
16963     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
16964     q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
16965   }
16966 }
16967
16968 @ @<Substitute new proto...@>=
16969 for (t=mp_dependent;t<=mp_proto_dependent;t++) {
16970   r=mp->max_link[t];
16971   while ( r!=null ) {
16972     q=info(r);
16973     if ( t==mp_dependent ) { /* for safety's sake, we change |q| to |mp_proto_dependent| */
16974       if ( mp->cur_exp==q ) if ( mp->cur_type==mp_dependent )
16975         mp->cur_type=mp_proto_dependent;
16976       dep_list(q)=mp_p_over_v(mp, dep_list(q),unity,mp_dependent,mp_proto_dependent);
16977       type(q)=mp_proto_dependent; value(r)=mp_round_fraction(mp, value(r));
16978     }
16979     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
16980       mp_make_scaled(mp, value(r),-v),s,mp_proto_dependent,mp_proto_dependent);
16981     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
16982     q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
16983   }
16984 }
16985
16986 @ Here are some routines that provide handy combinations of actions
16987 that are often needed during error recovery. For example,
16988 `|flush_error|' flushes the current expression, replaces it by
16989 a given value, and calls |error|.
16990
16991 Errors often are detected after an extra token has already been scanned.
16992 The `\\{put\_get}' routines put that token back before calling |error|;
16993 then they get it back again. (Or perhaps they get another token, if
16994 the user has changed things.)
16995
16996 @<Declarations@>=
16997 void mp_flush_error (MP mp,scaled v);
16998 void mp_put_get_error (MP mp);
16999 void mp_put_get_flush_error (MP mp,scaled v) ;
17000
17001 @ @c
17002 void mp_flush_error (MP mp,scaled v) { 
17003   mp_error(mp); mp_flush_cur_exp(mp, v); 
17004 }
17005 void mp_put_get_error (MP mp) { 
17006   mp_back_error(mp); mp_get_x_next(mp); 
17007 }
17008 void mp_put_get_flush_error (MP mp,scaled v) { 
17009   mp_put_get_error(mp);
17010   mp_flush_cur_exp(mp, v); 
17011 }
17012
17013 @ A global variable |var_flag| is set to a special command code
17014 just before \MP\ calls |scan_expression|, if the expression should be
17015 treated as a variable when this command code immediately follows. For
17016 example, |var_flag| is set to |assignment| at the beginning of a
17017 statement, because we want to know the {\sl location\/} of a variable at
17018 the left of `\.{:=}', not the {\sl value\/} of that variable.
17019
17020 The |scan_expression| subroutine calls |scan_tertiary|,
17021 which calls |scan_secondary|, which calls |scan_primary|, which sets
17022 |var_flag:=0|. In this way each of the scanning routines ``knows''
17023 when it has been called with a special |var_flag|, but |var_flag| is
17024 usually zero.
17025
17026 A variable preceding a command that equals |var_flag| is converted to a
17027 token list rather than a value. Furthermore, an `\.{=}' sign following an
17028 expression with |var_flag=assignment| is not considered to be a relation
17029 that produces boolean expressions.
17030
17031
17032 @<Glob...@>=
17033 int var_flag; /* command that wants a variable */
17034
17035 @ @<Set init...@>=
17036 mp->var_flag=0;
17037
17038 @* \[37] Parsing primary expressions.
17039 The first parsing routine, |scan_primary|, is also the most complicated one,
17040 since it involves so many different cases. But each case---with one
17041 exception---is fairly simple by itself.
17042
17043 When |scan_primary| begins, the first token of the primary to be scanned
17044 should already appear in |cur_cmd|, |cur_mod|, and |cur_sym|. The values
17045 of |cur_type| and |cur_exp| should be either dead or dormant, as explained
17046 earlier. If |cur_cmd| is not between |min_primary_command| and
17047 |max_primary_command|, inclusive, a syntax error will be signaled.
17048
17049 @<Declare the basic parsing subroutines@>=
17050 void mp_scan_primary (MP mp) {
17051   pointer p,q,r; /* for list manipulation */
17052   quarterword c; /* a primitive operation code */
17053   int my_var_flag; /* initial value of |my_var_flag| */
17054   pointer l_delim,r_delim; /* hash addresses of a delimiter pair */
17055   @<Other local variables for |scan_primary|@>;
17056   my_var_flag=mp->var_flag; mp->var_flag=0;
17057 RESTART:
17058   check_arith;
17059   @<Supply diagnostic information, if requested@>;
17060   switch (mp->cur_cmd) {
17061   case left_delimiter:
17062     @<Scan a delimited primary@>; break;
17063   case begin_group:
17064     @<Scan a grouped primary@>; break;
17065   case string_token:
17066     @<Scan a string constant@>; break;
17067   case numeric_token:
17068     @<Scan a primary that starts with a numeric token@>; break;
17069   case nullary:
17070     @<Scan a nullary operation@>; break;
17071   case unary: case type_name: case cycle: case plus_or_minus:
17072     @<Scan a unary operation@>; break;
17073   case primary_binary:
17074     @<Scan a binary operation with `\&{of}' between its operands@>; break;
17075   case str_op:
17076     @<Convert a suffix to a string@>; break;
17077   case internal_quantity:
17078     @<Scan an internal numeric quantity@>; break;
17079   case capsule_token:
17080     mp_make_exp_copy(mp, mp->cur_mod); break;
17081   case tag_token:
17082     @<Scan a variable primary; |goto restart| if it turns out to be a macro@>; break;
17083   default: 
17084     mp_bad_exp(mp, "A primary"); goto RESTART; break;
17085 @.A primary expression...@>
17086   }
17087   mp_get_x_next(mp); /* the routines |goto done| if they don't want this */
17088 DONE: 
17089   if ( mp->cur_cmd==left_bracket ) {
17090     if ( mp->cur_type>=mp_known ) {
17091       @<Scan a mediation construction@>;
17092     }
17093   }
17094 }
17095
17096
17097
17098 @ Errors at the beginning of expressions are flagged by |bad_exp|.
17099
17100 @c void mp_bad_exp (MP mp,char * s) {
17101   int save_flag;
17102   print_err(s); mp_print(mp, " expression can't begin with `");
17103   mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); 
17104   mp_print_char(mp, '\'');
17105   help4("I'm afraid I need some sort of value in order to continue,")
17106     ("so I've tentatively inserted `0'. You may want to")
17107     ("delete this zero and insert something else;")
17108     ("see Chapter 27 of The METAFONTbook for an example.");
17109 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
17110   mp_back_input(mp); mp->cur_sym=0; mp->cur_cmd=numeric_token; 
17111   mp->cur_mod=0; mp_ins_error(mp);
17112   save_flag=mp->var_flag; mp->var_flag=0; mp_get_x_next(mp);
17113   mp->var_flag=save_flag;
17114 }
17115
17116 @ @<Supply diagnostic information, if requested@>=
17117 #ifdef DEBUG
17118 if ( mp->panicking ) mp_check_mem(mp, false);
17119 #endif
17120 if ( mp->interrupt!=0 ) if ( mp->OK_to_interrupt ) {
17121   mp_back_input(mp); check_interrupt; mp_get_x_next(mp);
17122 }
17123
17124 @ @<Scan a delimited primary@>=
17125
17126   l_delim=mp->cur_sym; r_delim=mp->cur_mod; 
17127   mp_get_x_next(mp); mp_scan_expression(mp);
17128   if ( (mp->cur_cmd==comma) && (mp->cur_type>=mp_known) ) {
17129     @<Scan the rest of a delimited set of numerics@>;
17130   } else {
17131     mp_check_delimiter(mp, l_delim,r_delim);
17132   }
17133 }
17134
17135 @ The |stash_in| subroutine puts the current (numeric) expression into a field
17136 within a ``big node.''
17137
17138 @c void mp_stash_in (MP mp,pointer p) {
17139   pointer q; /* temporary register */
17140   type(p)=mp->cur_type;
17141   if ( mp->cur_type==mp_known ) {
17142     value(p)=mp->cur_exp;
17143   } else { 
17144     if ( mp->cur_type==mp_independent ) {
17145       @<Stash an independent |cur_exp| into a big node@>;
17146     } else { 
17147       mp->mem[value_loc(p)]=mp->mem[value_loc(mp->cur_exp)];
17148       /* |dep_list(p):=dep_list(cur_exp)| and |prev_dep(p):=prev_dep(cur_exp)| */
17149       link(prev_dep(p))=p;
17150     }
17151     mp_free_node(mp, mp->cur_exp,value_node_size);
17152   }
17153   mp->cur_type=mp_vacuous;
17154 }
17155
17156 @ In rare cases the current expression can become |independent|. There
17157 may be many dependency lists pointing to such an independent capsule,
17158 so we can't simply move it into place within a big node. Instead,
17159 we copy it, then recycle it.
17160
17161 @ @<Stash an independent |cur_exp|...@>=
17162
17163   q=mp_single_dependency(mp, mp->cur_exp);
17164   if ( q==mp->dep_final ){ 
17165     type(p)=mp_known; value(p)=0; mp_free_node(mp, q,dep_node_size);
17166   } else { 
17167     type(p)=mp_dependent; mp_new_dep(mp, p,q);
17168   }
17169   mp_recycle_value(mp, mp->cur_exp);
17170 }
17171
17172 @ This code uses the fact that |red_part_loc| and |green_part_loc|
17173 are synonymous with |x_part_loc| and |y_part_loc|.
17174
17175 @<Scan the rest of a delimited set of numerics@>=
17176
17177 p=mp_stash_cur_exp(mp);
17178 mp_get_x_next(mp); mp_scan_expression(mp);
17179 @<Make sure the second part of a pair or color has a numeric type@>;
17180 q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
17181 if ( mp->cur_cmd==comma ) type(q)=mp_color_type;
17182 else type(q)=mp_pair_type;
17183 mp_init_big_node(mp, q); r=value(q);
17184 mp_stash_in(mp, y_part_loc(r));
17185 mp_unstash_cur_exp(mp, p);
17186 mp_stash_in(mp, x_part_loc(r));
17187 if ( mp->cur_cmd==comma ) {
17188   @<Scan the last of a triplet of numerics@>;
17189 }
17190 if ( mp->cur_cmd==comma ) {
17191   type(q)=mp_cmykcolor_type;
17192   mp_init_big_node(mp, q); t=value(q);
17193   mp->mem[cyan_part_loc(t)]=mp->mem[red_part_loc(r)];
17194   value(cyan_part_loc(t))=value(red_part_loc(r));
17195   mp->mem[magenta_part_loc(t)]=mp->mem[green_part_loc(r)];
17196   value(magenta_part_loc(t))=value(green_part_loc(r));
17197   mp->mem[yellow_part_loc(t)]=mp->mem[blue_part_loc(r)];
17198   value(yellow_part_loc(t))=value(blue_part_loc(r));
17199   mp_recycle_value(mp, r);
17200   r=t;
17201   @<Scan the last of a quartet of numerics@>;
17202 }
17203 mp_check_delimiter(mp, l_delim,r_delim);
17204 mp->cur_type=type(q);
17205 mp->cur_exp=q;
17206 }
17207
17208 @ @<Make sure the second part of a pair or color has a numeric type@>=
17209 if ( mp->cur_type<mp_known ) {
17210   exp_err("Nonnumeric ypart has been replaced by 0");
17211 @.Nonnumeric...replaced by 0@>
17212   help4("I've started to scan a pair `(a,b)' or a color `(a,b,c)';")
17213     ("but after finding a nice `a' I found a `b' that isn't")
17214     ("of numeric type. So I've changed that part to zero.")
17215     ("(The b that I didn't like appears above the error message.)");
17216   mp_put_get_flush_error(mp, 0);
17217 }
17218
17219 @ @<Scan the last of a triplet of numerics@>=
17220
17221   mp_get_x_next(mp); mp_scan_expression(mp);
17222   if ( mp->cur_type<mp_known ) {
17223     exp_err("Nonnumeric third part has been replaced by 0");
17224 @.Nonnumeric...replaced by 0@>
17225     help3("I've just scanned a color `(a,b,c)' or cmykcolor(a,b,c,d); but the `c'")
17226       ("isn't of numeric type. So I've changed that part to zero.")
17227       ("(The c that I didn't like appears above the error message.)");
17228     mp_put_get_flush_error(mp, 0);
17229   }
17230   mp_stash_in(mp, blue_part_loc(r));
17231 }
17232
17233 @ @<Scan the last of a quartet of numerics@>=
17234
17235   mp_get_x_next(mp); mp_scan_expression(mp);
17236   if ( mp->cur_type<mp_known ) {
17237     exp_err("Nonnumeric blackpart has been replaced by 0");
17238 @.Nonnumeric...replaced by 0@>
17239     help3("I've just scanned a cmykcolor `(c,m,y,k)'; but the `k' isn't")
17240       ("of numeric type. So I've changed that part to zero.")
17241       ("(The k that I didn't like appears above the error message.)");
17242     mp_put_get_flush_error(mp, 0);
17243   }
17244   mp_stash_in(mp, black_part_loc(r));
17245 }
17246
17247 @ The local variable |group_line| keeps track of the line
17248 where a \&{begingroup} command occurred; this will be useful
17249 in an error message if the group doesn't actually end.
17250
17251 @<Other local variables for |scan_primary|@>=
17252 integer group_line; /* where a group began */
17253
17254 @ @<Scan a grouped primary@>=
17255
17256   group_line=mp_true_line(mp);
17257   if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17258   save_boundary_item(p);
17259   do {  
17260     mp_do_statement(mp); /* ends with |cur_cmd>=semicolon| */
17261   } while (! (mp->cur_cmd!=semicolon));
17262   if ( mp->cur_cmd!=end_group ) {
17263     print_err("A group begun on line ");
17264 @.A group...never ended@>
17265     mp_print_int(mp, group_line);
17266     mp_print(mp, " never ended");
17267     help2("I saw a `begingroup' back there that hasn't been matched")
17268          ("by `endgroup'. So I've inserted `endgroup' now.");
17269     mp_back_error(mp); mp->cur_cmd=end_group;
17270   }
17271   mp_unsave(mp); 
17272     /* this might change |cur_type|, if independent variables are recycled */
17273   if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17274 }
17275
17276 @ @<Scan a string constant@>=
17277
17278   mp->cur_type=mp_string_type; mp->cur_exp=mp->cur_mod;
17279 }
17280
17281 @ Later we'll come to procedures that perform actual operations like
17282 addition, square root, and so on; our purpose now is to do the parsing.
17283 But we might as well mention those future procedures now, so that the
17284 suspense won't be too bad:
17285
17286 \smallskip
17287 |do_nullary(c)| does primitive operations that have no operands (e.g.,
17288 `\&{true}' or `\&{pencircle}');
17289
17290 \smallskip
17291 |do_unary(c)| applies a primitive operation to the current expression;
17292
17293 \smallskip
17294 |do_binary(p,c)| applies a primitive operation to the capsule~|p|
17295 and the current expression.
17296
17297 @<Scan a nullary operation@>=mp_do_nullary(mp, mp->cur_mod)
17298
17299 @ @<Scan a unary operation@>=
17300
17301   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_primary(mp); 
17302   mp_do_unary(mp, c); goto DONE;
17303 }
17304
17305 @ A numeric token might be a primary by itself, or it might be the
17306 numerator of a fraction composed solely of numeric tokens, or it might
17307 multiply the primary that follows (provided that the primary doesn't begin
17308 with a plus sign or a minus sign). The code here uses the facts that
17309 |max_primary_command=plus_or_minus| and
17310 |max_primary_command-1=numeric_token|. If a fraction is found that is less
17311 than unity, we try to retain higher precision when we use it in scalar
17312 multiplication.
17313
17314 @<Other local variables for |scan_primary|@>=
17315 scaled num,denom; /* for primaries that are fractions, like `1/2' */
17316
17317 @ @<Scan a primary that starts with a numeric token@>=
17318
17319   mp->cur_exp=mp->cur_mod; mp->cur_type=mp_known; mp_get_x_next(mp);
17320   if ( mp->cur_cmd!=slash ) { 
17321     num=0; denom=0;
17322   } else { 
17323     mp_get_x_next(mp);
17324     if ( mp->cur_cmd!=numeric_token ) { 
17325       mp_back_input(mp);
17326       mp->cur_cmd=slash; mp->cur_mod=over; mp->cur_sym=frozen_slash;
17327       goto DONE;
17328     }
17329     num=mp->cur_exp; denom=mp->cur_mod;
17330     if ( denom==0 ) { @<Protest division by zero@>; }
17331     else { mp->cur_exp=mp_make_scaled(mp, num,denom); }
17332     check_arith; mp_get_x_next(mp);
17333   }
17334   if ( mp->cur_cmd>=min_primary_command ) {
17335    if ( mp->cur_cmd<numeric_token ) { /* in particular, |cur_cmd<>plus_or_minus| */
17336      p=mp_stash_cur_exp(mp); mp_scan_primary(mp);
17337      if ( (abs(num)>=abs(denom))||(mp->cur_type<mp_color_type) ) {
17338        mp_do_binary(mp, p,times);
17339      } else {
17340        mp_frac_mult(mp, num,denom);
17341        mp_free_node(mp, p,value_node_size);
17342      }
17343     }
17344   }
17345   goto DONE;
17346 }
17347
17348 @ @<Protest division...@>=
17349
17350   print_err("Division by zero");
17351 @.Division by zero@>
17352   help1("I'll pretend that you meant to divide by 1."); mp_error(mp);
17353 }
17354
17355 @ @<Scan a binary operation with `\&{of}' between its operands@>=
17356
17357   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
17358   if ( mp->cur_cmd!=of_token ) {
17359     mp_missing_err(mp, "of"); mp_print(mp, " for "); 
17360     mp_print_cmd_mod(mp, primary_binary,c);
17361 @.Missing `of'@>
17362     help1("I've got the first argument; will look now for the other.");
17363     mp_back_error(mp);
17364   }
17365   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_primary(mp); 
17366   mp_do_binary(mp, p,c); goto DONE;
17367 }
17368
17369 @ @<Convert a suffix to a string@>=
17370
17371   mp_get_x_next(mp); mp_scan_suffix(mp); 
17372   mp->old_setting=mp->selector; mp->selector=new_string;
17373   mp_show_token_list(mp, mp->cur_exp,null,100000,0); 
17374   mp_flush_token_list(mp, mp->cur_exp);
17375   mp->cur_exp=mp_make_string(mp); mp->selector=mp->old_setting; 
17376   mp->cur_type=mp_string_type;
17377   goto DONE;
17378 }
17379
17380 @ If an internal quantity appears all by itself on the left of an
17381 assignment, we return a token list of length one, containing the address
17382 of the internal quantity plus |hash_end|. (This accords with the conventions
17383 of the save stack, as described earlier.)
17384
17385 @<Scan an internal...@>=
17386
17387   q=mp->cur_mod;
17388   if ( my_var_flag==assignment ) {
17389     mp_get_x_next(mp);
17390     if ( mp->cur_cmd==assignment ) {
17391       mp->cur_exp=mp_get_avail(mp);
17392       info(mp->cur_exp)=q+hash_end; mp->cur_type=mp_token_list; 
17393       goto DONE;
17394     }
17395     mp_back_input(mp);
17396   }
17397   mp->cur_type=mp_known; mp->cur_exp=mp->internal[q];
17398 }
17399
17400 @ The most difficult part of |scan_primary| has been saved for last, since
17401 it was necessary to build up some confidence first. We can now face the task
17402 of scanning a variable.
17403
17404 As we scan a variable, we build a token list containing the relevant
17405 names and subscript values, simultaneously following along in the
17406 ``collective'' structure to see if we are actually dealing with a macro
17407 instead of a value.
17408
17409 The local variables |pre_head| and |post_head| will point to the beginning
17410 of the prefix and suffix lists; |tail| will point to the end of the list
17411 that is currently growing.
17412
17413 Another local variable, |tt|, contains partial information about the
17414 declared type of the variable-so-far. If |tt>=mp_unsuffixed_macro|, the
17415 relation |tt=type(q)| will always hold. If |tt=undefined|, the routine
17416 doesn't bother to update its information about type. And if
17417 |undefined<tt<mp_unsuffixed_macro|, the precise value of |tt| isn't critical.
17418
17419 @ @<Other local variables for |scan_primary|@>=
17420 pointer pre_head,post_head,tail;
17421   /* prefix and suffix list variables */
17422 small_number tt; /* approximation to the type of the variable-so-far */
17423 pointer t; /* a token */
17424 pointer macro_ref = 0; /* reference count for a suffixed macro */
17425
17426 @ @<Scan a variable primary...@>=
17427
17428   fast_get_avail(pre_head); tail=pre_head; post_head=null; tt=mp_vacuous;
17429   while (1) { 
17430     t=mp_cur_tok(mp); link(tail)=t;
17431     if ( tt!=undefined ) {
17432        @<Find the approximate type |tt| and corresponding~|q|@>;
17433       if ( tt>=mp_unsuffixed_macro ) {
17434         @<Either begin an unsuffixed macro call or
17435           prepare for a suffixed one@>;
17436       }
17437     }
17438     mp_get_x_next(mp); tail=t;
17439     if ( mp->cur_cmd==left_bracket ) {
17440       @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>;
17441     }
17442     if ( mp->cur_cmd>max_suffix_token ) break;
17443     if ( mp->cur_cmd<min_suffix_token ) break;
17444   } /* now |cur_cmd| is |internal_quantity|, |tag_token|, or |numeric_token| */
17445   @<Handle unusual cases that masquerade as variables, and |goto restart|
17446     or |goto done| if appropriate;
17447     otherwise make a copy of the variable and |goto done|@>;
17448 }
17449
17450 @ @<Either begin an unsuffixed macro call or...@>=
17451
17452   link(tail)=null;
17453   if ( tt>mp_unsuffixed_macro ) { /* |tt=mp_suffixed_macro| */
17454     post_head=mp_get_avail(mp); tail=post_head; link(tail)=t;
17455     tt=undefined; macro_ref=value(q); add_mac_ref(macro_ref);
17456   } else {
17457     @<Set up unsuffixed macro call and |goto restart|@>;
17458   }
17459 }
17460
17461 @ @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>=
17462
17463   mp_get_x_next(mp); mp_scan_expression(mp);
17464   if ( mp->cur_cmd!=right_bracket ) {
17465     @<Put the left bracket and the expression back to be rescanned@>;
17466   } else { 
17467     if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17468     mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp; mp->cur_sym=0;
17469   }
17470 }
17471
17472 @ The left bracket that we thought was introducing a subscript might have
17473 actually been the left bracket in a mediation construction like `\.{x[a,b]}'.
17474 So we don't issue an error message at this point; but we do want to back up
17475 so as to avoid any embarrassment about our incorrect assumption.
17476
17477 @<Put the left bracket and the expression back to be rescanned@>=
17478
17479   mp_back_input(mp); /* that was the token following the current expression */
17480   mp_back_expr(mp); mp->cur_cmd=left_bracket; 
17481   mp->cur_mod=0; mp->cur_sym=frozen_left_bracket;
17482 }
17483
17484 @ Here's a routine that puts the current expression back to be read again.
17485
17486 @c void mp_back_expr (MP mp) {
17487   pointer p; /* capsule token */
17488   p=mp_stash_cur_exp(mp); link(p)=null; back_list(p);
17489 }
17490
17491 @ Unknown subscripts lead to the following error message.
17492
17493 @c void mp_bad_subscript (MP mp) { 
17494   exp_err("Improper subscript has been replaced by zero");
17495 @.Improper subscript...@>
17496   help3("A bracketed subscript must have a known numeric value;")
17497     ("unfortunately, what I found was the value that appears just")
17498     ("above this error message. So I'll try a zero subscript.");
17499   mp_flush_error(mp, 0);
17500 }
17501
17502 @ Every time we call |get_x_next|, there's a chance that the variable we've
17503 been looking at will disappear. Thus, we cannot safely keep |q| pointing
17504 into the variable structure; we need to start searching from the root each time.
17505
17506 @<Find the approximate type |tt| and corresponding~|q|@>=
17507 @^inner loop@>
17508
17509   p=link(pre_head); q=info(p); tt=undefined;
17510   if ( eq_type(q) % outer_tag==tag_token ) {
17511     q=equiv(q);
17512     if ( q==null ) goto DONE2;
17513     while (1) { 
17514       p=link(p);
17515       if ( p==null ) {
17516         tt=type(q); goto DONE2;
17517       };
17518       if ( type(q)!=mp_structured ) goto DONE2;
17519       q=link(attr_head(q)); /* the |collective_subscript| attribute */
17520       if ( p>=mp->hi_mem_min ) { /* it's not a subscript */
17521         do {  q=link(q); } while (! (attr_loc(q)>=info(p)));
17522         if ( attr_loc(q)>info(p) ) goto DONE2;
17523       }
17524     }
17525   }
17526 DONE2:
17527   ;
17528 }
17529
17530 @ How do things stand now? Well, we have scanned an entire variable name,
17531 including possible subscripts and/or attributes; |cur_cmd|, |cur_mod|, and
17532 |cur_sym| represent the token that follows. If |post_head=null|, a
17533 token list for this variable name starts at |link(pre_head)|, with all
17534 subscripts evaluated. But if |post_head<>null|, the variable turned out
17535 to be a suffixed macro; |pre_head| is the head of the prefix list, while
17536 |post_head| is the head of a token list containing both `\.{\AT!}' and
17537 the suffix.
17538
17539 Our immediate problem is to see if this variable still exists. (Variable
17540 structures can change drastically whenever we call |get_x_next|; users
17541 aren't supposed to do this, but the fact that it is possible means that
17542 we must be cautious.)
17543
17544 The following procedure prints an error message when a variable
17545 unexpectedly disappears. Its help message isn't quite right for
17546 our present purposes, but we'll be able to fix that up.
17547
17548 @c 
17549 void mp_obliterated (MP mp,pointer q) { 
17550   print_err("Variable "); mp_show_token_list(mp, q,null,1000,0);
17551   mp_print(mp, " has been obliterated");
17552 @.Variable...obliterated@>
17553   help5("It seems you did a nasty thing---probably by accident,")
17554     ("but nevertheless you nearly hornswoggled me...")
17555     ("While I was evaluating the right-hand side of this")
17556     ("command, something happened, and the left-hand side")
17557     ("is no longer a variable! So I won't change anything.");
17558 }
17559
17560 @ If the variable does exist, we also need to check
17561 for a few other special cases before deciding that a plain old ordinary
17562 variable has, indeed, been scanned.
17563
17564 @<Handle unusual cases that masquerade as variables...@>=
17565 if ( post_head!=null ) {
17566   @<Set up suffixed macro call and |goto restart|@>;
17567 }
17568 q=link(pre_head); free_avail(pre_head);
17569 if ( mp->cur_cmd==my_var_flag ) { 
17570   mp->cur_type=mp_token_list; mp->cur_exp=q; goto DONE;
17571 }
17572 p=mp_find_variable(mp, q);
17573 if ( p!=null ) {
17574   mp_make_exp_copy(mp, p);
17575 } else { 
17576   mp_obliterated(mp, q);
17577   mp->help_line[2]="While I was evaluating the suffix of this variable,";
17578   mp->help_line[1]="something was redefined, and it's no longer a variable!";
17579   mp->help_line[0]="In order to get back on my feet, I've inserted `0' instead.";
17580   mp_put_get_flush_error(mp, 0);
17581 }
17582 mp_flush_node_list(mp, q); 
17583 goto DONE
17584
17585 @ The only complication associated with macro calling is that the prefix
17586 and ``at'' parameters must be packaged in an appropriate list of lists.
17587
17588 @<Set up unsuffixed macro call and |goto restart|@>=
17589
17590   p=mp_get_avail(mp); info(pre_head)=link(pre_head); link(pre_head)=p;
17591   info(p)=t; mp_macro_call(mp, value(q),pre_head,null);
17592   mp_get_x_next(mp); 
17593   goto RESTART;
17594 }
17595
17596 @ If the ``variable'' that turned out to be a suffixed macro no longer exists,
17597 we don't care, because we have reserved a pointer (|macro_ref|) to its
17598 token list.
17599
17600 @<Set up suffixed macro call and |goto restart|@>=
17601
17602   mp_back_input(mp); p=mp_get_avail(mp); q=link(post_head);
17603   info(pre_head)=link(pre_head); link(pre_head)=post_head;
17604   info(post_head)=q; link(post_head)=p; info(p)=link(q); link(q)=null;
17605   mp_macro_call(mp, macro_ref,pre_head,null); decr(ref_count(macro_ref));
17606   mp_get_x_next(mp); goto RESTART;
17607 }
17608
17609 @ Our remaining job is simply to make a copy of the value that has been
17610 found. Some cases are harder than others, but complexity arises solely
17611 because of the multiplicity of possible cases.
17612
17613 @<Declare the procedure called |make_exp_copy|@>=
17614 @<Declare subroutines needed by |make_exp_copy|@>;
17615 void mp_make_exp_copy (MP mp,pointer p) {
17616   pointer q,r,t; /* registers for list manipulation */
17617 RESTART: 
17618   mp->cur_type=type(p);
17619   switch (mp->cur_type) {
17620   case mp_vacuous: case mp_boolean_type: case mp_known:
17621     mp->cur_exp=value(p); break;
17622   case unknown_types:
17623     mp->cur_exp=mp_new_ring_entry(mp, p);
17624     break;
17625   case mp_string_type: 
17626     mp->cur_exp=value(p); add_str_ref(mp->cur_exp);
17627     break;
17628   case mp_picture_type:
17629     mp->cur_exp=value(p);add_edge_ref(mp->cur_exp);
17630     break;
17631   case mp_pen_type:
17632     mp->cur_exp=copy_pen(value(p));
17633     break; 
17634   case mp_path_type:
17635     mp->cur_exp=mp_copy_path(mp, value(p));
17636     break;
17637   case mp_transform_type: case mp_color_type: 
17638   case mp_cmykcolor_type: case mp_pair_type:
17639     @<Copy the big node |p|@>;
17640     break;
17641   case mp_dependent: case mp_proto_dependent:
17642     mp_encapsulate(mp, mp_copy_dep_list(mp, dep_list(p)));
17643     break;
17644   case mp_numeric_type: 
17645     new_indep(p); goto RESTART;
17646     break;
17647   case mp_independent: 
17648     q=mp_single_dependency(mp, p);
17649     if ( q==mp->dep_final ){ 
17650       mp->cur_type=mp_known; mp->cur_exp=0; mp_free_node(mp, q,value_node_size);
17651     } else { 
17652       mp->cur_type=mp_dependent; mp_encapsulate(mp, q);
17653     }
17654     break;
17655   default: 
17656     mp_confusion(mp, "copy");
17657 @:this can't happen copy}{\quad copy@>
17658     break;
17659   }
17660 }
17661
17662 @ The |encapsulate| subroutine assumes that |dep_final| is the
17663 tail of dependency list~|p|.
17664
17665 @<Declare subroutines needed by |make_exp_copy|@>=
17666 void mp_encapsulate (MP mp,pointer p) { 
17667   mp->cur_exp=mp_get_node(mp, value_node_size); type(mp->cur_exp)=mp->cur_type;
17668   name_type(mp->cur_exp)=mp_capsule; mp_new_dep(mp, mp->cur_exp,p);
17669 }
17670
17671 @ The most tedious case arises when the user refers to a
17672 \&{pair}, \&{color}, or \&{transform} variable; we must copy several fields,
17673 each of which can be |independent|, |dependent|, |mp_proto_dependent|,
17674 or |known|.
17675
17676 @<Copy the big node |p|@>=
17677
17678   if ( value(p)==null ) 
17679     mp_init_big_node(mp, p);
17680   t=mp_get_node(mp, value_node_size); name_type(t)=mp_capsule; type(t)=mp->cur_type;
17681   mp_init_big_node(mp, t);
17682   q=value(p)+mp->big_node_size[mp->cur_type]; 
17683   r=value(t)+mp->big_node_size[mp->cur_type];
17684   do {  
17685     q=q-2; r=r-2; mp_install(mp, r,q);
17686   } while (q!=value(p));
17687   mp->cur_exp=t;
17688 }
17689
17690 @ The |install| procedure copies a numeric field~|q| into field~|r| of
17691 a big node that will be part of a capsule.
17692
17693 @<Declare subroutines needed by |make_exp_copy|@>=
17694 void mp_install (MP mp,pointer r, pointer q) {
17695   pointer p; /* temporary register */
17696   if ( type(q)==mp_known ){ 
17697     value(r)=value(q); type(r)=mp_known;
17698   } else  if ( type(q)==mp_independent ) {
17699     p=mp_single_dependency(mp, q);
17700     if ( p==mp->dep_final ) {
17701       type(r)=mp_known; value(r)=0; mp_free_node(mp, p,value_node_size);
17702     } else  { 
17703       type(r)=mp_dependent; mp_new_dep(mp, r,p);
17704     }
17705   } else {
17706     type(r)=type(q); mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(q)));
17707   }
17708 }
17709
17710 @ Expressions of the form `\.{a[b,c]}' are converted into
17711 `\.{b+a*(c-b)}', without checking the types of \.b~or~\.c,
17712 provided that \.a is numeric.
17713
17714 @<Scan a mediation...@>=
17715
17716   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17717   if ( mp->cur_cmd!=comma ) {
17718     @<Put the left bracket and the expression back...@>;
17719     mp_unstash_cur_exp(mp, p);
17720   } else { 
17721     q=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17722     if ( mp->cur_cmd!=right_bracket ) {
17723       mp_missing_err(mp, "]");
17724 @.Missing `]'@>
17725       help3("I've scanned an expression of the form `a[b,c',")
17726       ("so a right bracket should have come next.")
17727       ("I shall pretend that one was there.");
17728       mp_back_error(mp);
17729     }
17730     r=mp_stash_cur_exp(mp); mp_make_exp_copy(mp, q);
17731     mp_do_binary(mp, r,minus); mp_do_binary(mp, p,times); 
17732     mp_do_binary(mp, q,plus); mp_get_x_next(mp);
17733   }
17734 }
17735
17736 @ Here is a comparatively simple routine that is used to scan the
17737 \&{suffix} parameters of a macro.
17738
17739 @<Declare the basic parsing subroutines@>=
17740 void mp_scan_suffix (MP mp) {
17741   pointer h,t; /* head and tail of the list being built */
17742   pointer p; /* temporary register */
17743   h=mp_get_avail(mp); t=h;
17744   while (1) { 
17745     if ( mp->cur_cmd==left_bracket ) {
17746       @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>;
17747     }
17748     if ( mp->cur_cmd==numeric_token ) {
17749       p=mp_new_num_tok(mp, mp->cur_mod);
17750     } else if ((mp->cur_cmd==tag_token)||(mp->cur_cmd==internal_quantity) ) {
17751        p=mp_get_avail(mp); info(p)=mp->cur_sym;
17752     } else {
17753       break;
17754     }
17755     link(t)=p; t=p; mp_get_x_next(mp);
17756   }
17757   mp->cur_exp=link(h); free_avail(h); mp->cur_type=mp_token_list;
17758 }
17759
17760 @ @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>=
17761
17762   mp_get_x_next(mp); mp_scan_expression(mp);
17763   if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17764   if ( mp->cur_cmd!=right_bracket ) {
17765      mp_missing_err(mp, "]");
17766 @.Missing `]'@>
17767     help3("I've seen a `[' and a subscript value, in a suffix,")
17768       ("so a right bracket should have come next.")
17769       ("I shall pretend that one was there.");
17770     mp_back_error(mp);
17771   }
17772   mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp;
17773 }
17774
17775 @* \[38] Parsing secondary and higher expressions.
17776 After the intricacies of |scan_primary|\kern-1pt,
17777 the |scan_secondary| routine is
17778 refreshingly simple. It's not trivial, but the operations are relatively
17779 straightforward; the main difficulty is, again, that expressions and data
17780 structures might change drastically every time we call |get_x_next|, so a
17781 cautious approach is mandatory. For example, a macro defined by
17782 \&{primarydef} might have disappeared by the time its second argument has
17783 been scanned; we solve this by increasing the reference count of its token
17784 list, so that the macro can be called even after it has been clobbered.
17785
17786 @<Declare the basic parsing subroutines@>=
17787 void mp_scan_secondary (MP mp) {
17788   pointer p; /* for list manipulation */
17789   halfword c,d; /* operation codes or modifiers */
17790   pointer mac_name; /* token defined with \&{primarydef} */
17791 RESTART:
17792   if ((mp->cur_cmd<min_primary_command)||
17793       (mp->cur_cmd>max_primary_command) )
17794     mp_bad_exp(mp, "A secondary");
17795 @.A secondary expression...@>
17796   mp_scan_primary(mp);
17797 CONTINUE: 
17798   if ( mp->cur_cmd<=max_secondary_command )
17799     if ( mp->cur_cmd>=min_secondary_command ) {
17800       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17801       if ( d==secondary_primary_macro ) { 
17802         mac_name=mp->cur_sym; add_mac_ref(c);
17803      }
17804      mp_get_x_next(mp); mp_scan_primary(mp);
17805      if ( d!=secondary_primary_macro ) {
17806        mp_do_binary(mp, p,c);
17807      } else  { 
17808        mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17809        decr(ref_count(c)); mp_get_x_next(mp); 
17810        goto RESTART;
17811     }
17812     goto CONTINUE;
17813   }
17814 }
17815
17816 @ The following procedure calls a macro that has two parameters,
17817 |p| and |cur_exp|.
17818
17819 @c void mp_binary_mac (MP mp,pointer p, pointer c, pointer n) {
17820   pointer q,r; /* nodes in the parameter list */
17821   q=mp_get_avail(mp); r=mp_get_avail(mp); link(q)=r;
17822   info(q)=p; info(r)=mp_stash_cur_exp(mp);
17823   mp_macro_call(mp, c,q,n);
17824 }
17825
17826 @ The next procedure, |scan_tertiary|, is pretty much the same deal.
17827
17828 @<Declare the basic parsing subroutines@>=
17829 void mp_scan_tertiary (MP mp) {
17830   pointer p; /* for list manipulation */
17831   halfword c,d; /* operation codes or modifiers */
17832   pointer mac_name; /* token defined with \&{secondarydef} */
17833 RESTART:
17834   if ((mp->cur_cmd<min_primary_command)||
17835       (mp->cur_cmd>max_primary_command) )
17836     mp_bad_exp(mp, "A tertiary");
17837 @.A tertiary expression...@>
17838   mp_scan_secondary(mp);
17839 CONTINUE: 
17840   if ( mp->cur_cmd<=max_tertiary_command ) {
17841     if ( mp->cur_cmd>=min_tertiary_command ) {
17842       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17843       if ( d==tertiary_secondary_macro ) { 
17844         mac_name=mp->cur_sym; add_mac_ref(c);
17845       };
17846       mp_get_x_next(mp); mp_scan_secondary(mp);
17847       if ( d!=tertiary_secondary_macro ) {
17848         mp_do_binary(mp, p,c);
17849       } else { 
17850         mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17851         decr(ref_count(c)); mp_get_x_next(mp); 
17852         goto RESTART;
17853       }
17854       goto CONTINUE;
17855     }
17856   }
17857 }
17858
17859 @ Finally we reach the deepest level in our quartet of parsing routines.
17860 This one is much like the others; but it has an extra complication from
17861 paths, which materialize here.
17862
17863 @d continue_path 25 /* a label inside of |scan_expression| */
17864 @d finish_path 26 /* another */
17865
17866 @<Declare the basic parsing subroutines@>=
17867 void mp_scan_expression (MP mp) {
17868   pointer p,q,r,pp,qq; /* for list manipulation */
17869   halfword c,d; /* operation codes or modifiers */
17870   int my_var_flag; /* initial value of |var_flag| */
17871   pointer mac_name; /* token defined with \&{tertiarydef} */
17872   boolean cycle_hit; /* did a path expression just end with `\&{cycle}'? */
17873   scaled x,y; /* explicit coordinates or tension at a path join */
17874   int t; /* knot type following a path join */
17875   t=0; y=0; x=0;
17876   my_var_flag=mp->var_flag; mac_name=null;
17877 RESTART:
17878   if ((mp->cur_cmd<min_primary_command)||
17879       (mp->cur_cmd>max_primary_command) )
17880     mp_bad_exp(mp, "An");
17881 @.An expression...@>
17882   mp_scan_tertiary(mp);
17883 CONTINUE: 
17884   if ( mp->cur_cmd<=max_expression_command )
17885     if ( mp->cur_cmd>=min_expression_command ) {
17886       if ( (mp->cur_cmd!=equals)||(my_var_flag!=assignment) ) {
17887         p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17888         if ( d==expression_tertiary_macro ) {
17889           mac_name=mp->cur_sym; add_mac_ref(c);
17890         }
17891         if ( (d<ampersand)||((d==ampersand)&&
17892              ((type(p)==mp_pair_type)||(type(p)==mp_path_type))) ) {
17893           @<Scan a path construction operation;
17894             but |return| if |p| has the wrong type@>;
17895         } else { 
17896           mp_get_x_next(mp); mp_scan_tertiary(mp);
17897           if ( d!=expression_tertiary_macro ) {
17898             mp_do_binary(mp, p,c);
17899           } else  { 
17900             mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17901             decr(ref_count(c)); mp_get_x_next(mp); 
17902             goto RESTART;
17903           }
17904         }
17905         goto CONTINUE;
17906      }
17907   }
17908 }
17909
17910 @ The reader should review the data structure conventions for paths before
17911 hoping to understand the next part of this code.
17912
17913 @<Scan a path construction operation...@>=
17914
17915   cycle_hit=false;
17916   @<Convert the left operand, |p|, into a partial path ending at~|q|;
17917     but |return| if |p| doesn't have a suitable type@>;
17918 CONTINUE_PATH: 
17919   @<Determine the path join parameters;
17920     but |goto finish_path| if there's only a direction specifier@>;
17921   if ( mp->cur_cmd==cycle ) {
17922     @<Get ready to close a cycle@>;
17923   } else { 
17924     mp_scan_tertiary(mp);
17925     @<Convert the right operand, |cur_exp|,
17926       into a partial path from |pp| to~|qq|@>;
17927   }
17928   @<Join the partial paths and reset |p| and |q| to the head and tail
17929     of the result@>;
17930   if ( mp->cur_cmd>=min_expression_command )
17931     if ( mp->cur_cmd<=ampersand ) if ( ! cycle_hit ) goto CONTINUE_PATH;
17932 FINISH_PATH:
17933   @<Choose control points for the path and put the result into |cur_exp|@>;
17934 }
17935
17936 @ @<Convert the left operand, |p|, into a partial path ending at~|q|...@>=
17937
17938   mp_unstash_cur_exp(mp, p);
17939   if ( mp->cur_type==mp_pair_type ) p=mp_new_knot(mp);
17940   else if ( mp->cur_type==mp_path_type ) p=mp->cur_exp;
17941   else return;
17942   q=p;
17943   while ( link(q)!=p ) q=link(q);
17944   if ( left_type(p)!=mp_endpoint ) { /* open up a cycle */
17945     r=mp_copy_knot(mp, p); link(q)=r; q=r;
17946   }
17947   left_type(p)=mp_open; right_type(q)=mp_open;
17948 }
17949
17950 @ A pair of numeric values is changed into a knot node for a one-point path
17951 when \MP\ discovers that the pair is part of a path.
17952
17953 @c@<Declare the procedure called |known_pair|@>;
17954 pointer mp_new_knot (MP mp) { /* convert a pair to a knot with two endpoints */
17955   pointer q; /* the new node */
17956   q=mp_get_node(mp, knot_node_size); left_type(q)=mp_endpoint;
17957   right_type(q)=mp_endpoint; originator(q)=mp_metapost_user; link(q)=q;
17958   mp_known_pair(mp); x_coord(q)=mp->cur_x; y_coord(q)=mp->cur_y;
17959   return q;
17960 }
17961
17962 @ The |known_pair| subroutine sets |cur_x| and |cur_y| to the components
17963 of the current expression, assuming that the current expression is a
17964 pair of known numerics. Unknown components are zeroed, and the
17965 current expression is flushed.
17966
17967 @<Declare the procedure called |known_pair|@>=
17968 void mp_known_pair (MP mp) {
17969   pointer p; /* the pair node */
17970   if ( mp->cur_type!=mp_pair_type ) {
17971     exp_err("Undefined coordinates have been replaced by (0,0)");
17972 @.Undefined coordinates...@>
17973     help5("I need x and y numbers for this part of the path.")
17974       ("The value I found (see above) was no good;")
17975       ("so I'll try to keep going by using zero instead.")
17976       ("(Chapter 27 of The METAFONTbook explains that")
17977 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
17978       ("you might want to type `I ??" "?' now.)");
17979     mp_put_get_flush_error(mp, 0); mp->cur_x=0; mp->cur_y=0;
17980   } else { 
17981     p=value(mp->cur_exp);
17982      @<Make sure that both |x| and |y| parts of |p| are known;
17983        copy them into |cur_x| and |cur_y|@>;
17984     mp_flush_cur_exp(mp, 0);
17985   }
17986 }
17987
17988 @ @<Make sure that both |x| and |y| parts of |p| are known...@>=
17989 if ( type(x_part_loc(p))==mp_known ) {
17990   mp->cur_x=value(x_part_loc(p));
17991 } else { 
17992   mp_disp_err(mp, x_part_loc(p),
17993     "Undefined x coordinate has been replaced by 0");
17994 @.Undefined coordinates...@>
17995   help5("I need a `known' x value for this part of the path.")
17996     ("The value I found (see above) was no good;")
17997     ("so I'll try to keep going by using zero instead.")
17998     ("(Chapter 27 of The METAFONTbook explains that")
17999 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18000     ("you might want to type `I ??" "?' now.)");
18001   mp_put_get_error(mp); mp_recycle_value(mp, x_part_loc(p)); mp->cur_x=0;
18002 }
18003 if ( type(y_part_loc(p))==mp_known ) {
18004   mp->cur_y=value(y_part_loc(p));
18005 } else { 
18006   mp_disp_err(mp, y_part_loc(p),
18007     "Undefined y coordinate has been replaced by 0");
18008   help5("I need a `known' y value for this part of the path.")
18009     ("The value I found (see above) was no good;")
18010     ("so I'll try to keep going by using zero instead.")
18011     ("(Chapter 27 of The METAFONTbook explains that")
18012     ("you might want to type `I ??" "?' now.)");
18013   mp_put_get_error(mp); mp_recycle_value(mp, y_part_loc(p)); mp->cur_y=0;
18014 }
18015
18016 @ At this point |cur_cmd| is either |ampersand|, |left_brace|, or |path_join|.
18017
18018 @<Determine the path join parameters...@>=
18019 if ( mp->cur_cmd==left_brace ) {
18020   @<Put the pre-join direction information into node |q|@>;
18021 }
18022 d=mp->cur_cmd;
18023 if ( d==path_join ) {
18024   @<Determine the tension and/or control points@>;
18025 } else if ( d!=ampersand ) {
18026   goto FINISH_PATH;
18027 }
18028 mp_get_x_next(mp);
18029 if ( mp->cur_cmd==left_brace ) {
18030   @<Put the post-join direction information into |x| and |t|@>;
18031 } else if ( right_type(q)!=mp_explicit ) {
18032   t=mp_open; x=0;
18033 }
18034
18035 @ The |scan_direction| subroutine looks at the directional information
18036 that is enclosed in braces, and also scans ahead to the following character.
18037 A type code is returned, either |open| (if the direction was $(0,0)$),
18038 or |curl| (if the direction was a curl of known value |cur_exp|), or
18039 |given| (if the direction is given by the |angle| value that now
18040 appears in |cur_exp|).
18041
18042 There's nothing difficult about this subroutine, but the program is rather
18043 lengthy because a variety of potential errors need to be nipped in the bud.
18044
18045 @c small_number mp_scan_direction (MP mp) {
18046   int t; /* the type of information found */
18047   scaled x; /* an |x| coordinate */
18048   mp_get_x_next(mp);
18049   if ( mp->cur_cmd==curl_command ) {
18050      @<Scan a curl specification@>;
18051   } else {
18052     @<Scan a given direction@>;
18053   }
18054   if ( mp->cur_cmd!=right_brace ) {
18055     mp_missing_err(mp, "}");
18056 @.Missing `\char`\}'@>
18057     help3("I've scanned a direction spec for part of a path,")
18058       ("so a right brace should have come next.")
18059       ("I shall pretend that one was there.");
18060     mp_back_error(mp);
18061   }
18062   mp_get_x_next(mp); 
18063   return t;
18064 }
18065
18066 @ @<Scan a curl specification@>=
18067 { mp_get_x_next(mp); mp_scan_expression(mp);
18068 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<0) ){ 
18069   exp_err("Improper curl has been replaced by 1");
18070 @.Improper curl@>
18071   help1("A curl must be a known, nonnegative number.");
18072   mp_put_get_flush_error(mp, unity);
18073 }
18074 t=mp_curl;
18075 }
18076
18077 @ @<Scan a given direction@>=
18078 { mp_scan_expression(mp);
18079   if ( mp->cur_type>mp_pair_type ) {
18080     @<Get given directions separated by commas@>;
18081   } else {
18082     mp_known_pair(mp);
18083   }
18084   if ( (mp->cur_x==0)&&(mp->cur_y==0) )  t=mp_open;
18085   else  { t=mp_given; mp->cur_exp=mp_n_arg(mp, mp->cur_x,mp->cur_y);}
18086 }
18087
18088 @ @<Get given directions separated by commas@>=
18089
18090   if ( mp->cur_type!=mp_known ) {
18091     exp_err("Undefined x coordinate has been replaced by 0");
18092 @.Undefined coordinates...@>
18093     help5("I need a `known' x value for this part of the path.")
18094       ("The value I found (see above) was no good;")
18095       ("so I'll try to keep going by using zero instead.")
18096       ("(Chapter 27 of The METAFONTbook explains that")
18097 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18098       ("you might want to type `I ??" "?' now.)");
18099     mp_put_get_flush_error(mp, 0);
18100   }
18101   x=mp->cur_exp;
18102   if ( mp->cur_cmd!=comma ) {
18103     mp_missing_err(mp, ",");
18104 @.Missing `,'@>
18105     help2("I've got the x coordinate of a path direction;")
18106       ("will look for the y coordinate next.");
18107     mp_back_error(mp);
18108   }
18109   mp_get_x_next(mp); mp_scan_expression(mp);
18110   if ( mp->cur_type!=mp_known ) {
18111      exp_err("Undefined y coordinate has been replaced by 0");
18112     help5("I need a `known' y value for this part of the path.")
18113       ("The value I found (see above) was no good;")
18114       ("so I'll try to keep going by using zero instead.")
18115       ("(Chapter 27 of The METAFONTbook explains that")
18116       ("you might want to type `I ??" "?' now.)");
18117     mp_put_get_flush_error(mp, 0);
18118   }
18119   mp->cur_y=mp->cur_exp; mp->cur_x=x;
18120 }
18121
18122 @ At this point |right_type(q)| is usually |open|, but it may have been
18123 set to some other value by a previous splicing operation. We must maintain
18124 the value of |right_type(q)| in unusual cases such as
18125 `\.{..z1\{z2\}\&\{z3\}z1\{0,0\}..}'.
18126
18127 @<Put the pre-join...@>=
18128
18129   t=mp_scan_direction(mp);
18130   if ( t!=mp_open ) {
18131     right_type(q)=t; right_given(q)=mp->cur_exp;
18132     if ( left_type(q)==mp_open ) {
18133       left_type(q)=t; left_given(q)=mp->cur_exp;
18134     } /* note that |left_given(q)=left_curl(q)| */
18135   }
18136 }
18137
18138 @ Since |left_tension| and |left_y| share the same position in knot nodes,
18139 and since |left_given| is similarly equivalent to |left_x|, we use
18140 |x| and |y| to hold the given direction and tension information when
18141 there are no explicit control points.
18142
18143 @<Put the post-join...@>=
18144
18145   t=mp_scan_direction(mp);
18146   if ( right_type(q)!=mp_explicit ) x=mp->cur_exp;
18147   else t=mp_explicit; /* the direction information is superfluous */
18148 }
18149
18150 @ @<Determine the tension and/or...@>=
18151
18152   mp_get_x_next(mp);
18153   if ( mp->cur_cmd==tension ) {
18154     @<Set explicit tensions@>;
18155   } else if ( mp->cur_cmd==controls ) {
18156     @<Set explicit control points@>;
18157   } else  { 
18158     right_tension(q)=unity; y=unity; mp_back_input(mp); /* default tension */
18159     goto DONE;
18160   };
18161   if ( mp->cur_cmd!=path_join ) {
18162      mp_missing_err(mp, "..");
18163 @.Missing `..'@>
18164     help1("A path join command should end with two dots.");
18165     mp_back_error(mp);
18166   }
18167 DONE:
18168   ;
18169 }
18170
18171 @ @<Set explicit tensions@>=
18172
18173   mp_get_x_next(mp); y=mp->cur_cmd;
18174   if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18175   mp_scan_primary(mp);
18176   @<Make sure that the current expression is a valid tension setting@>;
18177   if ( y==at_least ) negate(mp->cur_exp);
18178   right_tension(q)=mp->cur_exp;
18179   if ( mp->cur_cmd==and_command ) {
18180     mp_get_x_next(mp); y=mp->cur_cmd;
18181     if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18182     mp_scan_primary(mp);
18183     @<Make sure that the current expression is a valid tension setting@>;
18184     if ( y==at_least ) negate(mp->cur_exp);
18185   }
18186   y=mp->cur_exp;
18187 }
18188
18189 @ @d min_tension three_quarter_unit
18190
18191 @<Make sure that the current expression is a valid tension setting@>=
18192 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<min_tension) ) {
18193   exp_err("Improper tension has been set to 1");
18194 @.Improper tension@>
18195   help1("The expression above should have been a number >=3/4.");
18196   mp_put_get_flush_error(mp, unity);
18197 }
18198
18199 @ @<Set explicit control points@>=
18200
18201   right_type(q)=mp_explicit; t=mp_explicit; mp_get_x_next(mp); mp_scan_primary(mp);
18202   mp_known_pair(mp); right_x(q)=mp->cur_x; right_y(q)=mp->cur_y;
18203   if ( mp->cur_cmd!=and_command ) {
18204     x=right_x(q); y=right_y(q);
18205   } else { 
18206     mp_get_x_next(mp); mp_scan_primary(mp);
18207     mp_known_pair(mp); x=mp->cur_x; y=mp->cur_y;
18208   }
18209 }
18210
18211 @ @<Convert the right operand, |cur_exp|, into a partial path...@>=
18212
18213   if ( mp->cur_type!=mp_path_type ) pp=mp_new_knot(mp);
18214   else pp=mp->cur_exp;
18215   qq=pp;
18216   while ( link(qq)!=pp ) qq=link(qq);
18217   if ( left_type(pp)!=mp_endpoint ) { /* open up a cycle */
18218     r=mp_copy_knot(mp, pp); link(qq)=r; qq=r;
18219   }
18220   left_type(pp)=mp_open; right_type(qq)=mp_open;
18221 }
18222
18223 @ If a person tries to define an entire path by saying `\.{(x,y)\&cycle}',
18224 we silently change the specification to `\.{(x,y)..cycle}', since a cycle
18225 shouldn't have length zero.
18226
18227 @<Get ready to close a cycle@>=
18228
18229   cycle_hit=true; mp_get_x_next(mp); pp=p; qq=p;
18230   if ( d==ampersand ) if ( p==q ) {
18231     d=path_join; right_tension(q)=unity; y=unity;
18232   }
18233 }
18234
18235 @ @<Join the partial paths and reset |p| and |q|...@>=
18236
18237 if ( d==ampersand ) {
18238   if ( (x_coord(q)!=x_coord(pp))||(y_coord(q)!=y_coord(pp)) ) {
18239     print_err("Paths don't touch; `&' will be changed to `..'");
18240 @.Paths don't touch@>
18241     help3("When you join paths `p&q', the ending point of p")
18242       ("must be exactly equal to the starting point of q.")
18243       ("So I'm going to pretend that you said `p..q' instead.");
18244     mp_put_get_error(mp); d=path_join; right_tension(q)=unity; y=unity;
18245   }
18246 }
18247 @<Plug an opening in |right_type(pp)|, if possible@>;
18248 if ( d==ampersand ) {
18249   @<Splice independent paths together@>;
18250 } else  { 
18251   @<Plug an opening in |right_type(q)|, if possible@>;
18252   link(q)=pp; left_y(pp)=y;
18253   if ( t!=mp_open ) { left_x(pp)=x; left_type(pp)=t;  };
18254 }
18255 q=qq;
18256 }
18257
18258 @ @<Plug an opening in |right_type(q)|...@>=
18259 if ( right_type(q)==mp_open ) {
18260   if ( (left_type(q)==mp_curl)||(left_type(q)==mp_given) ) {
18261     right_type(q)=left_type(q); right_given(q)=left_given(q);
18262   }
18263 }
18264
18265 @ @<Plug an opening in |right_type(pp)|...@>=
18266 if ( right_type(pp)==mp_open ) {
18267   if ( (t==mp_curl)||(t==mp_given) ) {
18268     right_type(pp)=t; right_given(pp)=x;
18269   }
18270 }
18271
18272 @ @<Splice independent paths together@>=
18273
18274   if ( left_type(q)==mp_open ) if ( right_type(q)==mp_open ) {
18275     left_type(q)=mp_curl; left_curl(q)=unity;
18276   }
18277   if ( right_type(pp)==mp_open ) if ( t==mp_open ) {
18278     right_type(pp)=mp_curl; right_curl(pp)=unity;
18279   }
18280   right_type(q)=right_type(pp); link(q)=link(pp);
18281   right_x(q)=right_x(pp); right_y(q)=right_y(pp);
18282   mp_free_node(mp, pp,knot_node_size);
18283   if ( qq==pp ) qq=q;
18284 }
18285
18286 @ @<Choose control points for the path...@>=
18287 if ( cycle_hit ) { 
18288   if ( d==ampersand ) p=q;
18289 } else  { 
18290   left_type(p)=mp_endpoint;
18291   if ( right_type(p)==mp_open ) { 
18292     right_type(p)=mp_curl; right_curl(p)=unity;
18293   }
18294   right_type(q)=mp_endpoint;
18295   if ( left_type(q)==mp_open ) { 
18296     left_type(q)=mp_curl; left_curl(q)=unity;
18297   }
18298   link(q)=p;
18299 }
18300 mp_make_choices(mp, p);
18301 mp->cur_type=mp_path_type; mp->cur_exp=p
18302
18303 @ Finally, we sometimes need to scan an expression whose value is
18304 supposed to be either |true_code| or |false_code|.
18305
18306 @<Declare the basic parsing subroutines@>=
18307 void mp_get_boolean (MP mp) { 
18308   mp_get_x_next(mp); mp_scan_expression(mp);
18309   if ( mp->cur_type!=mp_boolean_type ) {
18310     exp_err("Undefined condition will be treated as `false'");
18311 @.Undefined condition...@>
18312     help2("The expression shown above should have had a definite")
18313       ("true-or-false value. I'm changing it to `false'.");
18314     mp_put_get_flush_error(mp, false_code); mp->cur_type=mp_boolean_type;
18315   }
18316 }
18317
18318 @* \[39] Doing the operations.
18319 The purpose of parsing is primarily to permit people to avoid piles of
18320 parentheses. But the real work is done after the structure of an expression
18321 has been recognized; that's when new expressions are generated. We
18322 turn now to the guts of \MP, which handles individual operators that
18323 have come through the parsing mechanism.
18324
18325 We'll start with the easy ones that take no operands, then work our way
18326 up to operators with one and ultimately two arguments. In other words,
18327 we will write the three procedures |do_nullary|, |do_unary|, and |do_binary|
18328 that are invoked periodically by the expression scanners.
18329
18330 First let's make sure that all of the primitive operators are in the
18331 hash table. Although |scan_primary| and its relatives made use of the
18332 \\{cmd} code for these operators, the \\{do} routines base everything
18333 on the \\{mod} code. For example, |do_binary| doesn't care whether the
18334 operation it performs is a |primary_binary| or |secondary_binary|, etc.
18335
18336 @<Put each...@>=
18337 mp_primitive(mp, "true",nullary,true_code);
18338 @:true_}{\&{true} primitive@>
18339 mp_primitive(mp, "false",nullary,false_code);
18340 @:false_}{\&{false} primitive@>
18341 mp_primitive(mp, "nullpicture",nullary,null_picture_code);
18342 @:null_picture_}{\&{nullpicture} primitive@>
18343 mp_primitive(mp, "nullpen",nullary,null_pen_code);
18344 @:null_pen_}{\&{nullpen} primitive@>
18345 mp_primitive(mp, "jobname",nullary,job_name_op);
18346 @:job_name_}{\&{jobname} primitive@>
18347 mp_primitive(mp, "readstring",nullary,read_string_op);
18348 @:read_string_}{\&{readstring} primitive@>
18349 mp_primitive(mp, "pencircle",nullary,pen_circle);
18350 @:pen_circle_}{\&{pencircle} primitive@>
18351 mp_primitive(mp, "normaldeviate",nullary,normal_deviate);
18352 @:normal_deviate_}{\&{normaldeviate} primitive@>
18353 mp_primitive(mp, "readfrom",unary,read_from_op);
18354 @:read_from_}{\&{readfrom} primitive@>
18355 mp_primitive(mp, "closefrom",unary,close_from_op);
18356 @:close_from_}{\&{closefrom} primitive@>
18357 mp_primitive(mp, "odd",unary,odd_op);
18358 @:odd_}{\&{odd} primitive@>
18359 mp_primitive(mp, "known",unary,known_op);
18360 @:known_}{\&{known} primitive@>
18361 mp_primitive(mp, "unknown",unary,unknown_op);
18362 @:unknown_}{\&{unknown} primitive@>
18363 mp_primitive(mp, "not",unary,not_op);
18364 @:not_}{\&{not} primitive@>
18365 mp_primitive(mp, "decimal",unary,decimal);
18366 @:decimal_}{\&{decimal} primitive@>
18367 mp_primitive(mp, "reverse",unary,reverse);
18368 @:reverse_}{\&{reverse} primitive@>
18369 mp_primitive(mp, "makepath",unary,make_path_op);
18370 @:make_path_}{\&{makepath} primitive@>
18371 mp_primitive(mp, "makepen",unary,make_pen_op);
18372 @:make_pen_}{\&{makepen} primitive@>
18373 mp_primitive(mp, "oct",unary,oct_op);
18374 @:oct_}{\&{oct} primitive@>
18375 mp_primitive(mp, "hex",unary,hex_op);
18376 @:hex_}{\&{hex} primitive@>
18377 mp_primitive(mp, "ASCII",unary,ASCII_op);
18378 @:ASCII_}{\&{ASCII} primitive@>
18379 mp_primitive(mp, "char",unary,char_op);
18380 @:char_}{\&{char} primitive@>
18381 mp_primitive(mp, "length",unary,length_op);
18382 @:length_}{\&{length} primitive@>
18383 mp_primitive(mp, "turningnumber",unary,turning_op);
18384 @:turning_number_}{\&{turningnumber} primitive@>
18385 mp_primitive(mp, "xpart",unary,x_part);
18386 @:x_part_}{\&{xpart} primitive@>
18387 mp_primitive(mp, "ypart",unary,y_part);
18388 @:y_part_}{\&{ypart} primitive@>
18389 mp_primitive(mp, "xxpart",unary,xx_part);
18390 @:xx_part_}{\&{xxpart} primitive@>
18391 mp_primitive(mp, "xypart",unary,xy_part);
18392 @:xy_part_}{\&{xypart} primitive@>
18393 mp_primitive(mp, "yxpart",unary,yx_part);
18394 @:yx_part_}{\&{yxpart} primitive@>
18395 mp_primitive(mp, "yypart",unary,yy_part);
18396 @:yy_part_}{\&{yypart} primitive@>
18397 mp_primitive(mp, "redpart",unary,red_part);
18398 @:red_part_}{\&{redpart} primitive@>
18399 mp_primitive(mp, "greenpart",unary,green_part);
18400 @:green_part_}{\&{greenpart} primitive@>
18401 mp_primitive(mp, "bluepart",unary,blue_part);
18402 @:blue_part_}{\&{bluepart} primitive@>
18403 mp_primitive(mp, "cyanpart",unary,cyan_part);
18404 @:cyan_part_}{\&{cyanpart} primitive@>
18405 mp_primitive(mp, "magentapart",unary,magenta_part);
18406 @:magenta_part_}{\&{magentapart} primitive@>
18407 mp_primitive(mp, "yellowpart",unary,yellow_part);
18408 @:yellow_part_}{\&{yellowpart} primitive@>
18409 mp_primitive(mp, "blackpart",unary,black_part);
18410 @:black_part_}{\&{blackpart} primitive@>
18411 mp_primitive(mp, "greypart",unary,grey_part);
18412 @:grey_part_}{\&{greypart} primitive@>
18413 mp_primitive(mp, "colormodel",unary,color_model_part);
18414 @:color_model_part_}{\&{colormodel} primitive@>
18415 mp_primitive(mp, "fontpart",unary,font_part);
18416 @:font_part_}{\&{fontpart} primitive@>
18417 mp_primitive(mp, "textpart",unary,text_part);
18418 @:text_part_}{\&{textpart} primitive@>
18419 mp_primitive(mp, "pathpart",unary,path_part);
18420 @:path_part_}{\&{pathpart} primitive@>
18421 mp_primitive(mp, "penpart",unary,pen_part);
18422 @:pen_part_}{\&{penpart} primitive@>
18423 mp_primitive(mp, "dashpart",unary,dash_part);
18424 @:dash_part_}{\&{dashpart} primitive@>
18425 mp_primitive(mp, "sqrt",unary,sqrt_op);
18426 @:sqrt_}{\&{sqrt} primitive@>
18427 mp_primitive(mp, "mexp",unary,m_exp_op);
18428 @:m_exp_}{\&{mexp} primitive@>
18429 mp_primitive(mp, "mlog",unary,m_log_op);
18430 @:m_log_}{\&{mlog} primitive@>
18431 mp_primitive(mp, "sind",unary,sin_d_op);
18432 @:sin_d_}{\&{sind} primitive@>
18433 mp_primitive(mp, "cosd",unary,cos_d_op);
18434 @:cos_d_}{\&{cosd} primitive@>
18435 mp_primitive(mp, "floor",unary,floor_op);
18436 @:floor_}{\&{floor} primitive@>
18437 mp_primitive(mp, "uniformdeviate",unary,uniform_deviate);
18438 @:uniform_deviate_}{\&{uniformdeviate} primitive@>
18439 mp_primitive(mp, "charexists",unary,char_exists_op);
18440 @:char_exists_}{\&{charexists} primitive@>
18441 mp_primitive(mp, "fontsize",unary,font_size);
18442 @:font_size_}{\&{fontsize} primitive@>
18443 mp_primitive(mp, "llcorner",unary,ll_corner_op);
18444 @:ll_corner_}{\&{llcorner} primitive@>
18445 mp_primitive(mp, "lrcorner",unary,lr_corner_op);
18446 @:lr_corner_}{\&{lrcorner} primitive@>
18447 mp_primitive(mp, "ulcorner",unary,ul_corner_op);
18448 @:ul_corner_}{\&{ulcorner} primitive@>
18449 mp_primitive(mp, "urcorner",unary,ur_corner_op);
18450 @:ur_corner_}{\&{urcorner} primitive@>
18451 mp_primitive(mp, "arclength",unary,arc_length);
18452 @:arc_length_}{\&{arclength} primitive@>
18453 mp_primitive(mp, "angle",unary,angle_op);
18454 @:angle_}{\&{angle} primitive@>
18455 mp_primitive(mp, "cycle",cycle,cycle_op);
18456 @:cycle_}{\&{cycle} primitive@>
18457 mp_primitive(mp, "stroked",unary,stroked_op);
18458 @:stroked_}{\&{stroked} primitive@>
18459 mp_primitive(mp, "filled",unary,filled_op);
18460 @:filled_}{\&{filled} primitive@>
18461 mp_primitive(mp, "textual",unary,textual_op);
18462 @:textual_}{\&{textual} primitive@>
18463 mp_primitive(mp, "clipped",unary,clipped_op);
18464 @:clipped_}{\&{clipped} primitive@>
18465 mp_primitive(mp, "bounded",unary,bounded_op);
18466 @:bounded_}{\&{bounded} primitive@>
18467 mp_primitive(mp, "+",plus_or_minus,plus);
18468 @:+ }{\.{+} primitive@>
18469 mp_primitive(mp, "-",plus_or_minus,minus);
18470 @:- }{\.{-} primitive@>
18471 mp_primitive(mp, "*",secondary_binary,times);
18472 @:* }{\.{*} primitive@>
18473 mp_primitive(mp, "/",slash,over); mp->eqtb[frozen_slash]=mp->eqtb[mp->cur_sym];
18474 @:/ }{\.{/} primitive@>
18475 mp_primitive(mp, "++",tertiary_binary,pythag_add);
18476 @:++_}{\.{++} primitive@>
18477 mp_primitive(mp, "+-+",tertiary_binary,pythag_sub);
18478 @:+-+_}{\.{+-+} primitive@>
18479 mp_primitive(mp, "or",tertiary_binary,or_op);
18480 @:or_}{\&{or} primitive@>
18481 mp_primitive(mp, "and",and_command,and_op);
18482 @:and_}{\&{and} primitive@>
18483 mp_primitive(mp, "<",expression_binary,less_than);
18484 @:< }{\.{<} primitive@>
18485 mp_primitive(mp, "<=",expression_binary,less_or_equal);
18486 @:<=_}{\.{<=} primitive@>
18487 mp_primitive(mp, ">",expression_binary,greater_than);
18488 @:> }{\.{>} primitive@>
18489 mp_primitive(mp, ">=",expression_binary,greater_or_equal);
18490 @:>=_}{\.{>=} primitive@>
18491 mp_primitive(mp, "=",equals,equal_to);
18492 @:= }{\.{=} primitive@>
18493 mp_primitive(mp, "<>",expression_binary,unequal_to);
18494 @:<>_}{\.{<>} primitive@>
18495 mp_primitive(mp, "substring",primary_binary,substring_of);
18496 @:substring_}{\&{substring} primitive@>
18497 mp_primitive(mp, "subpath",primary_binary,subpath_of);
18498 @:subpath_}{\&{subpath} primitive@>
18499 mp_primitive(mp, "directiontime",primary_binary,direction_time_of);
18500 @:direction_time_}{\&{directiontime} primitive@>
18501 mp_primitive(mp, "point",primary_binary,point_of);
18502 @:point_}{\&{point} primitive@>
18503 mp_primitive(mp, "precontrol",primary_binary,precontrol_of);
18504 @:precontrol_}{\&{precontrol} primitive@>
18505 mp_primitive(mp, "postcontrol",primary_binary,postcontrol_of);
18506 @:postcontrol_}{\&{postcontrol} primitive@>
18507 mp_primitive(mp, "penoffset",primary_binary,pen_offset_of);
18508 @:pen_offset_}{\&{penoffset} primitive@>
18509 mp_primitive(mp, "arctime",primary_binary,arc_time_of);
18510 @:arc_time_of_}{\&{arctime} primitive@>
18511 mp_primitive(mp, "mpversion",nullary,mp_version);
18512 @:mp_verison_}{\&{mpversion} primitive@>
18513 mp_primitive(mp, "&",ampersand,concatenate);
18514 @:!!!}{\.{\&} primitive@>
18515 mp_primitive(mp, "rotated",secondary_binary,rotated_by);
18516 @:rotated_}{\&{rotated} primitive@>
18517 mp_primitive(mp, "slanted",secondary_binary,slanted_by);
18518 @:slanted_}{\&{slanted} primitive@>
18519 mp_primitive(mp, "scaled",secondary_binary,scaled_by);
18520 @:scaled_}{\&{scaled} primitive@>
18521 mp_primitive(mp, "shifted",secondary_binary,shifted_by);
18522 @:shifted_}{\&{shifted} primitive@>
18523 mp_primitive(mp, "transformed",secondary_binary,transformed_by);
18524 @:transformed_}{\&{transformed} primitive@>
18525 mp_primitive(mp, "xscaled",secondary_binary,x_scaled);
18526 @:x_scaled_}{\&{xscaled} primitive@>
18527 mp_primitive(mp, "yscaled",secondary_binary,y_scaled);
18528 @:y_scaled_}{\&{yscaled} primitive@>
18529 mp_primitive(mp, "zscaled",secondary_binary,z_scaled);
18530 @:z_scaled_}{\&{zscaled} primitive@>
18531 mp_primitive(mp, "infont",secondary_binary,in_font);
18532 @:in_font_}{\&{infont} primitive@>
18533 mp_primitive(mp, "intersectiontimes",tertiary_binary,intersect);
18534 @:intersection_times_}{\&{intersectiontimes} primitive@>
18535
18536 @ @<Cases of |print_cmd...@>=
18537 case nullary:
18538 case unary:
18539 case primary_binary:
18540 case secondary_binary:
18541 case tertiary_binary:
18542 case expression_binary:
18543 case cycle:
18544 case plus_or_minus:
18545 case slash:
18546 case ampersand:
18547 case equals:
18548 case and_command:
18549   mp_print_op(mp, m);
18550   break;
18551
18552 @ OK, let's look at the simplest \\{do} procedure first.
18553
18554 @c @<Declare nullary action procedure@>;
18555 void mp_do_nullary (MP mp,quarterword c) { 
18556   check_arith;
18557   if ( mp->internal[mp_tracing_commands]>two )
18558     mp_show_cmd_mod(mp, nullary,c);
18559   switch (c) {
18560   case true_code: case false_code: 
18561     mp->cur_type=mp_boolean_type; mp->cur_exp=c;
18562     break;
18563   case null_picture_code: 
18564     mp->cur_type=mp_picture_type;
18565     mp->cur_exp=mp_get_node(mp, edge_header_size); 
18566     mp_init_edges(mp, mp->cur_exp);
18567     break;
18568   case null_pen_code: 
18569     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, 0);
18570     break;
18571   case normal_deviate: 
18572     mp->cur_type=mp_known; mp->cur_exp=mp_norm_rand(mp);
18573     break;
18574   case pen_circle: 
18575     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, unity);
18576     break;
18577   case job_name_op:  
18578     if ( mp->job_name==NULL ) mp_open_log_file(mp);
18579     mp->cur_type=mp_string_type; mp->cur_exp=rts(mp->job_name);
18580     break;
18581   case mp_version: 
18582     mp->cur_type=mp_string_type; 
18583     mp->cur_exp=intern(metapost_version) ;
18584     break;
18585   case read_string_op:
18586     @<Read a string from the terminal@>;
18587     break;
18588   } /* there are no other cases */
18589   check_arith;
18590 }
18591
18592 @ @<Read a string...@>=
18593
18594   if ( mp->interaction<=mp_nonstop_mode )
18595     mp_fatal_error(mp, "*** (cannot readstring in nonstop modes)");
18596   mp_begin_file_reading(mp); name=is_read;
18597   limit=start; prompt_input("");
18598   mp_finish_read(mp);
18599 }
18600
18601 @ @<Declare nullary action procedure@>=
18602 void mp_finish_read (MP mp) { /* copy |buffer| line to |cur_exp| */
18603   size_t k;
18604   str_room((int)mp->last-start);
18605   for (k=start;k<=mp->last-1;k++) {
18606    append_char(mp->buffer[k]);
18607   }
18608   mp_end_file_reading(mp); mp->cur_type=mp_string_type; 
18609   mp->cur_exp=mp_make_string(mp);
18610 }
18611
18612 @ Things get a bit more interesting when there's an operand. The
18613 operand to |do_unary| appears in |cur_type| and |cur_exp|.
18614
18615 @c @<Declare unary action procedures@>;
18616 void mp_do_unary (MP mp,quarterword c) {
18617   pointer p,q,r; /* for list manipulation */
18618   integer x; /* a temporary register */
18619   check_arith;
18620   if ( mp->internal[mp_tracing_commands]>two )
18621     @<Trace the current unary operation@>;
18622   switch (c) {
18623   case plus:
18624     if ( mp->cur_type<mp_color_type ) mp_bad_unary(mp, plus);
18625     break;
18626   case minus:
18627     @<Negate the current expression@>;
18628     break;
18629   @<Additional cases of unary operators@>;
18630   } /* there are no other cases */
18631   check_arith;
18632 };
18633
18634 @ The |nice_pair| function returns |true| if both components of a pair
18635 are known.
18636
18637 @<Declare unary action procedures@>=
18638 boolean mp_nice_pair (MP mp,integer p, quarterword t) { 
18639   if ( t==mp_pair_type ) {
18640     p=value(p);
18641     if ( type(x_part_loc(p))==mp_known )
18642       if ( type(y_part_loc(p))==mp_known )
18643         return true;
18644   }
18645   return false;
18646 }
18647
18648 @ The |nice_color_or_pair| function is analogous except that it also accepts
18649 fully known colors.
18650
18651 @<Declare unary action procedures@>=
18652 boolean mp_nice_color_or_pair (MP mp,integer p, quarterword t) {
18653   pointer q,r; /* for scanning the big node */
18654   if ( (t!=mp_pair_type)&&(t!=mp_color_type)&&(t!=mp_cmykcolor_type) ) {
18655     return false;
18656   } else { 
18657     q=value(p);
18658     r=q+mp->big_node_size[type(p)];
18659     do {  
18660       r=r-2;
18661       if ( type(r)!=mp_known )
18662         return false;
18663     } while (r!=q);
18664     return true;
18665   }
18666 }
18667
18668 @ @<Declare unary action...@>=
18669 void mp_print_known_or_unknown_type (MP mp,small_number t, integer v) { 
18670   mp_print_char(mp, '(');
18671   if ( t>mp_known ) mp_print(mp, "unknown numeric");
18672   else { if ( (t==mp_pair_type)||(t==mp_color_type)||(t==mp_cmykcolor_type) )
18673     if ( ! mp_nice_color_or_pair(mp, v,t) ) mp_print(mp, "unknown ");
18674     mp_print_type(mp, t);
18675   }
18676   mp_print_char(mp, ')');
18677 }
18678
18679 @ @<Declare unary action...@>=
18680 void mp_bad_unary (MP mp,quarterword c) { 
18681   exp_err("Not implemented: "); mp_print_op(mp, c);
18682 @.Not implemented...@>
18683   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
18684   help3("I'm afraid I don't know how to apply that operation to that")
18685     ("particular type. Continue, and I'll simply return the")
18686     ("argument (shown above) as the result of the operation.");
18687   mp_put_get_error(mp);
18688 }
18689
18690 @ @<Trace the current unary operation@>=
18691
18692   mp_begin_diagnostic(mp); mp_print_nl(mp, "{"); 
18693   mp_print_op(mp, c); mp_print_char(mp, '(');
18694   mp_print_exp(mp, null,0); /* show the operand, but not verbosely */
18695   mp_print(mp, ")}"); mp_end_diagnostic(mp, false);
18696 }
18697
18698 @ Negation is easy except when the current expression
18699 is of type |independent|, or when it is a pair with one or more
18700 |independent| components.
18701
18702 It is tempting to argue that the negative of an independent variable
18703 is an independent variable, hence we don't have to do anything when
18704 negating it. The fallacy is that other dependent variables pointing
18705 to the current expression must change the sign of their
18706 coefficients if we make no change to the current expression.
18707
18708 Instead, we work around the problem by copying the current expression
18709 and recycling it afterwards (cf.~the |stash_in| routine).
18710
18711 @<Negate the current expression@>=
18712 switch (mp->cur_type) {
18713 case mp_color_type:
18714 case mp_cmykcolor_type:
18715 case mp_pair_type:
18716 case mp_independent: 
18717   q=mp->cur_exp; mp_make_exp_copy(mp, q);
18718   if ( mp->cur_type==mp_dependent ) {
18719     mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18720   } else if ( mp->cur_type<=mp_pair_type ) { /* |mp_color_type| or |mp_pair_type| */
18721     p=value(mp->cur_exp);
18722     r=p+mp->big_node_size[mp->cur_type];
18723     do {  
18724       r=r-2;
18725       if ( type(r)==mp_known ) negate(value(r));
18726       else mp_negate_dep_list(mp, dep_list(r));
18727     } while (r!=p);
18728   } /* if |cur_type=mp_known| then |cur_exp=0| */
18729   mp_recycle_value(mp, q); mp_free_node(mp, q,value_node_size);
18730   break;
18731 case mp_dependent:
18732 case mp_proto_dependent:
18733   mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18734   break;
18735 case mp_known:
18736   negate(mp->cur_exp);
18737   break;
18738 default:
18739   mp_bad_unary(mp, minus);
18740   break;
18741 }
18742
18743 @ @<Declare unary action...@>=
18744 void mp_negate_dep_list (MP mp,pointer p) { 
18745   while (1) { 
18746     negate(value(p));
18747     if ( info(p)==null ) return;
18748     p=link(p);
18749   }
18750 }
18751
18752 @ @<Additional cases of unary operators@>=
18753 case not_op: 
18754   if ( mp->cur_type!=mp_boolean_type ) mp_bad_unary(mp, not_op);
18755   else mp->cur_exp=true_code+false_code-mp->cur_exp;
18756   break;
18757
18758 @ @d three_sixty_units 23592960 /* that's |360*unity| */
18759 @d boolean_reset(A) if ( (A) ) mp->cur_exp=true_code; else mp->cur_exp=false_code
18760
18761 @<Additional cases of unary operators@>=
18762 case sqrt_op:
18763 case m_exp_op:
18764 case m_log_op:
18765 case sin_d_op:
18766 case cos_d_op:
18767 case floor_op:
18768 case  uniform_deviate:
18769 case odd_op:
18770 case char_exists_op:
18771   if ( mp->cur_type!=mp_known ) {
18772     mp_bad_unary(mp, c);
18773   } else {
18774     switch (c) {
18775     case sqrt_op:mp->cur_exp=mp_square_rt(mp, mp->cur_exp);break;
18776     case m_exp_op:mp->cur_exp=mp_m_exp(mp, mp->cur_exp);break;
18777     case m_log_op:mp->cur_exp=mp_m_log(mp, mp->cur_exp);break;
18778     case sin_d_op:
18779     case cos_d_op:
18780       mp_n_sin_cos(mp, (mp->cur_exp % three_sixty_units)*16);
18781       if ( c==sin_d_op ) mp->cur_exp=mp_round_fraction(mp, mp->n_sin);
18782       else mp->cur_exp=mp_round_fraction(mp, mp->n_cos);
18783       break;
18784     case floor_op:mp->cur_exp=mp_floor_scaled(mp, mp->cur_exp);break;
18785     case uniform_deviate:mp->cur_exp=mp_unif_rand(mp, mp->cur_exp);break;
18786     case odd_op: 
18787       boolean_reset(odd(mp_round_unscaled(mp, mp->cur_exp)));
18788       mp->cur_type=mp_boolean_type;
18789       break;
18790     case char_exists_op:
18791       @<Determine if a character has been shipped out@>;
18792       break;
18793     } /* there are no other cases */
18794   }
18795   break;
18796
18797 @ @<Additional cases of unary operators@>=
18798 case angle_op:
18799   if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) ) {
18800     p=value(mp->cur_exp);
18801     x=mp_n_arg(mp, value(x_part_loc(p)),value(y_part_loc(p)));
18802     if ( x>=0 ) mp_flush_cur_exp(mp, (x+8)/ 16);
18803     else mp_flush_cur_exp(mp, -((-x+8)/ 16));
18804   } else {
18805     mp_bad_unary(mp, angle_op);
18806   }
18807   break;
18808
18809 @ If the current expression is a pair, but the context wants it to
18810 be a path, we call |pair_to_path|.
18811
18812 @<Declare unary action...@>=
18813 void mp_pair_to_path (MP mp) { 
18814   mp->cur_exp=mp_new_knot(mp); 
18815   mp->cur_type=mp_path_type;
18816 };
18817
18818 @ @<Additional cases of unary operators@>=
18819 case x_part:
18820 case y_part:
18821   if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_transform_type) )
18822     mp_take_part(mp, c);
18823   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18824   else mp_bad_unary(mp, c);
18825   break;
18826 case xx_part:
18827 case xy_part:
18828 case yx_part:
18829 case yy_part: 
18830   if ( mp->cur_type==mp_transform_type ) mp_take_part(mp, c);
18831   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18832   else mp_bad_unary(mp, c);
18833   break;
18834 case red_part:
18835 case green_part:
18836 case blue_part: 
18837   if ( mp->cur_type==mp_color_type ) mp_take_part(mp, c);
18838   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18839   else mp_bad_unary(mp, c);
18840   break;
18841 case cyan_part:
18842 case magenta_part:
18843 case yellow_part:
18844 case black_part: 
18845   if ( mp->cur_type==mp_cmykcolor_type) mp_take_part(mp, c); 
18846   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18847   else mp_bad_unary(mp, c);
18848   break;
18849 case grey_part: 
18850   if ( mp->cur_type==mp_known ) mp->cur_exp=value(c);
18851   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18852   else mp_bad_unary(mp, c);
18853   break;
18854 case color_model_part: 
18855   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18856   else mp_bad_unary(mp, c);
18857   break;
18858
18859 @ In the following procedure, |cur_exp| points to a capsule, which points to
18860 a big node. We want to delete all but one part of the big node.
18861
18862 @<Declare unary action...@>=
18863 void mp_take_part (MP mp,quarterword c) {
18864   pointer p; /* the big node */
18865   p=value(mp->cur_exp); value(temp_val)=p; type(temp_val)=mp->cur_type;
18866   link(p)=temp_val; mp_free_node(mp, mp->cur_exp,value_node_size);
18867   mp_make_exp_copy(mp, p+mp->sector_offset[c+mp_x_part_sector-x_part]);
18868   mp_recycle_value(mp, temp_val);
18869 }
18870
18871 @ @<Initialize table entries...@>=
18872 name_type(temp_val)=mp_capsule;
18873
18874 @ @<Additional cases of unary operators@>=
18875 case font_part:
18876 case text_part:
18877 case path_part:
18878 case pen_part:
18879 case dash_part:
18880   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18881   else mp_bad_unary(mp, c);
18882   break;
18883
18884 @ @<Declarations@>=
18885 void mp_scale_edges (MP mp);
18886
18887 @ @<Declare unary action...@>=
18888 void mp_take_pict_part (MP mp,quarterword c) {
18889   pointer p; /* first graphical object in |cur_exp| */
18890   p=link(dummy_loc(mp->cur_exp));
18891   if ( p!=null ) {
18892     switch (c) {
18893     case x_part: case y_part: case xx_part:
18894     case xy_part: case yx_part: case yy_part:
18895       if ( type(p)==mp_text_code ) mp_flush_cur_exp(mp, text_trans_part(p+c));
18896       else goto NOT_FOUND;
18897       break;
18898     case red_part: case green_part: case blue_part:
18899       if ( has_color(p) ) mp_flush_cur_exp(mp, obj_color_part(p+c));
18900       else goto NOT_FOUND;
18901       break;
18902     case cyan_part: case magenta_part: case yellow_part:
18903     case black_part:
18904       if ( has_color(p) ) {
18905         if ( color_model(p)==mp_uninitialized_model )
18906           mp_flush_cur_exp(mp, unity);
18907         else
18908           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-cyan_part)));
18909       } else goto NOT_FOUND;
18910       break;
18911     case grey_part:
18912       if ( has_color(p) )
18913           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-grey_part)));
18914       else goto NOT_FOUND;
18915       break;
18916     case color_model_part:
18917       if ( has_color(p) ) {
18918         if ( color_model(p)==mp_uninitialized_model )
18919           mp_flush_cur_exp(mp, mp->internal[mp_default_color_model]);
18920         else
18921           mp_flush_cur_exp(mp, color_model(p)*unity);
18922       } else goto NOT_FOUND;
18923       break;
18924     @<Handle other cases in |take_pict_part| or |goto not_found|@>;
18925     } /* all cases have been enumerated */
18926     return;
18927   };
18928 NOT_FOUND:
18929   @<Convert the current expression to a null value appropriate
18930     for |c|@>;
18931 }
18932
18933 @ @<Handle other cases in |take_pict_part| or |goto not_found|@>=
18934 case text_part: 
18935   if ( type(p)!=mp_text_code ) goto NOT_FOUND;
18936   else { 
18937     mp_flush_cur_exp(mp, text_p(p));
18938     add_str_ref(mp->cur_exp);
18939     mp->cur_type=mp_string_type;
18940     };
18941   break;
18942 case font_part: 
18943   if ( type(p)!=mp_text_code ) goto NOT_FOUND;
18944   else { 
18945     mp_flush_cur_exp(mp, rts(mp->font_name[font_n(p)])); 
18946     add_str_ref(mp->cur_exp);
18947     mp->cur_type=mp_string_type;
18948   };
18949   break;
18950 case path_part:
18951   if ( type(p)==mp_text_code ) goto NOT_FOUND;
18952   else if ( is_stop(p) ) mp_confusion(mp, "pict");
18953 @:this can't happen pict}{\quad pict@>
18954   else { 
18955     mp_flush_cur_exp(mp, mp_copy_path(mp, path_p(p)));
18956     mp->cur_type=mp_path_type;
18957   }
18958   break;
18959 case pen_part: 
18960   if ( ! has_pen(p) ) goto NOT_FOUND;
18961   else {
18962     if ( pen_p(p)==null ) goto NOT_FOUND;
18963     else { mp_flush_cur_exp(mp, copy_pen(pen_p(p)));
18964       mp->cur_type=mp_pen_type;
18965     };
18966   }
18967   break;
18968 case dash_part: 
18969   if ( type(p)!=mp_stroked_code ) goto NOT_FOUND;
18970   else { if ( dash_p(p)==null ) goto NOT_FOUND;
18971     else { add_edge_ref(dash_p(p));
18972     mp->se_sf=dash_scale(p);
18973     mp->se_pic=dash_p(p);
18974     mp_scale_edges(mp);
18975     mp_flush_cur_exp(mp, mp->se_pic);
18976     mp->cur_type=mp_picture_type;
18977     };
18978   }
18979   break;
18980
18981 @ Since |scale_edges| had to be declared |forward|, it had to be declared as a
18982 parameterless procedure even though it really takes two arguments and updates
18983 one of them.  Hence the following globals are needed.
18984
18985 @<Global...@>=
18986 pointer se_pic;  /* edge header used and updated by |scale_edges| */
18987 scaled se_sf;  /* the scale factor argument to |scale_edges| */
18988
18989 @ @<Convert the current expression to a null value appropriate...@>=
18990 switch (c) {
18991 case text_part: case font_part: 
18992   mp_flush_cur_exp(mp, rts(""));
18993   mp->cur_type=mp_string_type;
18994   break;
18995 case path_part: 
18996   mp_flush_cur_exp(mp, mp_get_node(mp, knot_node_size));
18997   left_type(mp->cur_exp)=mp_endpoint;
18998   right_type(mp->cur_exp)=mp_endpoint;
18999   link(mp->cur_exp)=mp->cur_exp;
19000   x_coord(mp->cur_exp)=0;
19001   y_coord(mp->cur_exp)=0;
19002   originator(mp->cur_exp)=mp_metapost_user;
19003   mp->cur_type=mp_path_type;
19004   break;
19005 case pen_part: 
19006   mp_flush_cur_exp(mp, mp_get_pen_circle(mp, 0));
19007   mp->cur_type=mp_pen_type;
19008   break;
19009 case dash_part: 
19010   mp_flush_cur_exp(mp, mp_get_node(mp, edge_header_size));
19011   mp_init_edges(mp, mp->cur_exp);
19012   mp->cur_type=mp_picture_type;
19013   break;
19014 default: 
19015    mp_flush_cur_exp(mp, 0);
19016   break;
19017 }
19018
19019 @ @<Additional cases of unary...@>=
19020 case char_op: 
19021   if ( mp->cur_type!=mp_known ) { 
19022     mp_bad_unary(mp, char_op);
19023   } else { 
19024     mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256; 
19025     mp->cur_type=mp_string_type;
19026     if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
19027   }
19028   break;
19029 case decimal: 
19030   if ( mp->cur_type!=mp_known ) {
19031      mp_bad_unary(mp, decimal);
19032   } else { 
19033     mp->old_setting=mp->selector; mp->selector=new_string;
19034     mp_print_scaled(mp, mp->cur_exp); mp->cur_exp=mp_make_string(mp);
19035     mp->selector=mp->old_setting; mp->cur_type=mp_string_type;
19036   }
19037   break;
19038 case oct_op:
19039 case hex_op:
19040 case ASCII_op: 
19041   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19042   else mp_str_to_num(mp, c);
19043   break;
19044 case font_size: 
19045   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, font_size);
19046   else @<Find the design size of the font whose name is |cur_exp|@>;
19047   break;
19048
19049 @ @<Declare unary action...@>=
19050 void mp_str_to_num (MP mp,quarterword c) { /* converts a string to a number */
19051   integer n; /* accumulator */
19052   ASCII_code m; /* current character */
19053   pool_pointer k; /* index into |str_pool| */
19054   int b; /* radix of conversion */
19055   boolean bad_char; /* did the string contain an invalid digit? */
19056   if ( c==ASCII_op ) {
19057     if ( length(mp->cur_exp)==0 ) n=-1;
19058     else n=mp->str_pool[mp->str_start[mp->cur_exp]];
19059   } else { 
19060     if ( c==oct_op ) b=8; else b=16;
19061     n=0; bad_char=false;
19062     for (k=mp->str_start[mp->cur_exp];k<=str_stop(mp->cur_exp)-1;k++) {
19063       m=mp->str_pool[k];
19064       if ( (m>='0')&&(m<='9') ) m=m-'0';
19065       else if ( (m>='A')&&(m<='F') ) m=m-'A'+10;
19066       else if ( (m>='a')&&(m<='f') ) m=m-'a'+10;
19067       else  { bad_char=true; m=0; };
19068       if ( m>=b ) { bad_char=true; m=0; };
19069       if ( n<32768 / b ) n=n*b+m; else n=32767;
19070     }
19071     @<Give error messages if |bad_char| or |n>=4096|@>;
19072   }
19073   mp_flush_cur_exp(mp, n*unity);
19074 }
19075
19076 @ @<Give error messages if |bad_char|...@>=
19077 if ( bad_char ) { 
19078   exp_err("String contains illegal digits");
19079 @.String contains illegal digits@>
19080   if ( c==oct_op ) {
19081     help1("I zeroed out characters that weren't in the range 0..7.");
19082   } else  {
19083     help1("I zeroed out characters that weren't hex digits.");
19084   }
19085   mp_put_get_error(mp);
19086 }
19087 if ( (n>4095) ) {
19088   if ( mp->internal[mp_warning_check]>0 ) {
19089     print_err("Number too large ("); 
19090     mp_print_int(mp, n); mp_print_char(mp, ')');
19091 @.Number too large@>
19092     help2("I have trouble with numbers greater than 4095; watch out.")
19093       ("(Set warningcheck:=0 to suppress this message.)");
19094     mp_put_get_error(mp);
19095   }
19096 }
19097
19098 @ The length operation is somewhat unusual in that it applies to a variety
19099 of different types of operands.
19100
19101 @<Additional cases of unary...@>=
19102 case length_op: 
19103   switch (mp->cur_type) {
19104   case mp_string_type: mp_flush_cur_exp(mp, length(mp->cur_exp)*unity); break;
19105   case mp_path_type: mp_flush_cur_exp(mp, mp_path_length(mp)); break;
19106   case mp_known: mp->cur_exp=abs(mp->cur_exp); break;
19107   case mp_picture_type: mp_flush_cur_exp(mp, mp_pict_length(mp)); break;
19108   default: 
19109     if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) )
19110       mp_flush_cur_exp(mp, mp_pyth_add(mp, 
19111         value(x_part_loc(value(mp->cur_exp))),
19112         value(y_part_loc(value(mp->cur_exp)))));
19113     else mp_bad_unary(mp, c);
19114     break;
19115   }
19116   break;
19117
19118 @ @<Declare unary action...@>=
19119 scaled mp_path_length (MP mp) { /* computes the length of the current path */
19120   scaled n; /* the path length so far */
19121   pointer p; /* traverser */
19122   p=mp->cur_exp;
19123   if ( left_type(p)==mp_endpoint ) n=-unity; else n=0;
19124   do {  p=link(p); n=n+unity; } while (p!=mp->cur_exp);
19125   return n;
19126 }
19127
19128 @ @<Declare unary action...@>=
19129 scaled mp_pict_length (MP mp) { 
19130   /* counts interior components in picture |cur_exp| */
19131   scaled n; /* the count so far */
19132   pointer p; /* traverser */
19133   n=0;
19134   p=link(dummy_loc(mp->cur_exp));
19135   if ( p!=null ) {
19136     if ( is_start_or_stop(p) )
19137       if ( mp_skip_1component(mp, p)==null ) p=link(p);
19138     while ( p!=null )  { 
19139       skip_component(p) return n; 
19140       n=n+unity;   
19141     }
19142   }
19143   return n;
19144 }
19145
19146 @ Implement |turningnumber|
19147
19148 @<Additional cases of unary...@>=
19149 case turning_op:
19150   if ( mp->cur_type==mp_pair_type ) mp_flush_cur_exp(mp, 0);
19151   else if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, turning_op);
19152   else if ( left_type(mp->cur_exp)==mp_endpoint )
19153      mp_flush_cur_exp(mp, 0); /* not a cyclic path */
19154   else
19155     mp_flush_cur_exp(mp, mp_turn_cycles_wrapper(mp, mp->cur_exp));
19156   break;
19157
19158 @ The function |an_angle| returns the value of the |angle| primitive, or $0$ if the
19159 argument is |origin|.
19160
19161 @<Declare unary action...@>=
19162 angle mp_an_angle (MP mp,scaled xpar, scaled ypar) {
19163   if ( (! ((xpar==0) && (ypar==0))) )
19164     return mp_n_arg(mp, xpar,ypar);
19165   return 0;
19166 }
19167
19168
19169 @ The actual turning number is (for the moment) computed in a C function
19170 that receives eight integers corresponding to the four controlling points,
19171 and returns a single angle.  Besides those, we have to account for discrete
19172 moves at the actual points.
19173
19174 @d floor(a) (a>=0 ? a : -(int)(-a))
19175 @d bezier_error (720<<20)+1
19176 @d sign(v) ((v)>0 ? 1 : ((v)<0 ? -1 : 0 ))
19177 @d print_roots(a) { if (debuglevel>(65536*2))
19178    fprintf(stdout,"bezier_slope(): %s, i=%f, o=%f, angle=%f\n", (a),in,out,res); }
19179 @d out ((double)(xo>>20))
19180 @d mid ((double)(xm>>20))
19181 @d in  ((double)(xi>>20))
19182 @d divisor (256*256)
19183 @d double2angle(a) (int)floor(a*256.0*256.0*16.0)
19184
19185 @<Declare unary action...@>=
19186 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19187             integer CX,integer CY,integer DX,integer DY, int debuglevel);
19188
19189 @ @c 
19190 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19191             integer CX,integer CY,integer DX,integer DY, int debuglevel) {
19192   double a, b, c;
19193   integer deltax,deltay;
19194   double ax,ay,bx,by,cx,cy,dx,dy;
19195   angle xi = 0, xo = 0, xm = 0;
19196   double res = 0;
19197   ax=AX/divisor;  ay=AY/divisor;
19198   bx=BX/divisor;  by=BY/divisor;
19199   cx=CX/divisor;  cy=CY/divisor;
19200   dx=DX/divisor;  dy=DY/divisor;
19201
19202   deltax = (BX-AX); deltay = (BY-AY);
19203   if (deltax==0 && deltay == 0) { deltax=(CX-AX); deltay=(CY-AY); }
19204   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19205   xi = mp_an_angle(mp,deltax,deltay);
19206
19207   deltax = (CX-BX); deltay = (CY-BY);
19208   xm = mp_an_angle(mp,deltax,deltay);
19209
19210   deltax = (DX-CX); deltay = (DY-CY);
19211   if (deltax==0 && deltay == 0) { deltax=(DX-BX); deltay=(DY-BY); }
19212   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19213   xo = mp_an_angle(mp,deltax,deltay);
19214
19215   a = (bx-ax)*(cy-by) - (cx-bx)*(by-ay); /* a = (bp-ap)x(cp-bp); */
19216   b = (bx-ax)*(dy-cy) - (by-ay)*(dx-cx);; /* b = (bp-ap)x(dp-cp);*/
19217   c = (cx-bx)*(dy-cy) - (dx-cx)*(cy-by); /* c = (cp-bp)x(dp-cp);*/
19218
19219   if (debuglevel>(65536*2)) {
19220     fprintf(stdout,
19221       "bezier_slope(): (%.2f,%.2f),(%.2f,%.2f),(%.2f,%.2f),(%.2f,%.2f)\n",
19222               ax,ay,bx,by,cx,cy,dx,dy);
19223     fprintf(stdout,
19224       "bezier_slope(): a,b,c,b^2,4ac: (%.2f,%.2f,%.2f,%.2f,%.2f)\n",a,b,c,b*b,4*a*c);
19225   }
19226
19227   if ((a==0)&&(c==0)) {
19228     res = (b==0 ?  0 :  (out-in)); 
19229     print_roots("no roots (a)");
19230   } else if ((a==0)||(c==0)) {
19231     if ((sign(b) == sign(a)) || (sign(b) == sign(c))) {
19232       res = out-in; /* ? */
19233       if (res<-180.0) 
19234         res += 360.0;
19235       else if (res>180.0)
19236         res -= 360.0;
19237       print_roots("no roots (b)");
19238     } else {
19239       res = out-in; /* ? */
19240       print_roots("one root (a)");
19241     }
19242   } else if ((sign(a)*sign(c))<0) {
19243     res = out-in; /* ? */
19244       if (res<-180.0) 
19245         res += 360.0;
19246       else if (res>180.0)
19247         res -= 360.0;
19248     print_roots("one root (b)");
19249   } else {
19250     if (sign(a) == sign(b)) {
19251       res = out-in; /* ? */
19252       if (res<-180.0) 
19253         res += 360.0;
19254       else if (res>180.0)
19255         res -= 360.0;
19256       print_roots("no roots (d)");
19257     } else {
19258       if ((b*b) == (4*a*c)) {
19259         res = bezier_error;
19260         print_roots("double root"); /* cusp */
19261       } else if ((b*b) < (4*a*c)) {
19262         res = out-in; /* ? */
19263         if (res<=0.0 &&res>-180.0) 
19264           res += 360.0;
19265         else if (res>=0.0 && res<180.0)
19266           res -= 360.0;
19267         print_roots("no roots (e)");
19268       } else {
19269         res = out-in;
19270         if (res<-180.0) 
19271           res += 360.0;
19272         else if (res>180.0)
19273           res -= 360.0;
19274         print_roots("two roots"); /* two inflections */
19275       }
19276     }
19277   }
19278   return double2angle(res);
19279 }
19280
19281 @
19282 @d p_nextnext link(link(p))
19283 @d p_next link(p)
19284 @d seven_twenty_deg 05500000000 /* $720\cdot2^{20}$, represents $720^\circ$ */
19285
19286 @<Declare unary action...@>=
19287 scaled mp_new_turn_cycles (MP mp,pointer c) {
19288   angle res,ang; /*  the angles of intermediate results  */
19289   scaled turns;  /*  the turn counter  */
19290   pointer p;     /*  for running around the path  */
19291   integer xp,yp;   /*  coordinates of next point  */
19292   integer x,y;   /*  helper coordinates  */
19293   angle in_angle,out_angle;     /*  helper angles */
19294   int old_setting; /* saved |selector| setting */
19295   res=0;
19296   turns= 0;
19297   p=c;
19298   old_setting = mp->selector; mp->selector=term_only;
19299   if ( mp->internal[mp_tracing_commands]>unity ) {
19300     mp_begin_diagnostic(mp);
19301     mp_print_nl(mp, "");
19302     mp_end_diagnostic(mp, false);
19303   }
19304   do { 
19305     xp = x_coord(p_next); yp = y_coord(p_next);
19306     ang  = mp_bezier_slope(mp,x_coord(p), y_coord(p), right_x(p), right_y(p),
19307              left_x(p_next), left_y(p_next), xp, yp, 
19308              mp->internal[mp_tracing_commands]);
19309     if ( ang>seven_twenty_deg ) {
19310       print_err("Strange path");
19311       mp_error(mp);
19312       mp->selector=old_setting;
19313       return 0;
19314     }
19315     res  = res + ang;
19316     if ( res > one_eighty_deg ) {
19317       res = res - three_sixty_deg;
19318       turns = turns + unity;
19319     }
19320     if ( res <= -one_eighty_deg ) {
19321       res = res + three_sixty_deg;
19322       turns = turns - unity;
19323     }
19324     /*  incoming angle at next point  */
19325     x = left_x(p_next);  y = left_y(p_next);
19326     if ( (xp==x)&&(yp==y) ) { x = right_x(p);  y = right_y(p);  };
19327     if ( (xp==x)&&(yp==y) ) { x = x_coord(p);  y = y_coord(p);  };
19328     in_angle = mp_an_angle(mp, xp - x, yp - y);
19329     /*  outgoing angle at next point  */
19330     x = right_x(p_next);  y = right_y(p_next);
19331     if ( (xp==x)&&(yp==y) ) { x = left_x(p_nextnext);  y = left_y(p_nextnext);  };
19332     if ( (xp==x)&&(yp==y) ) { x = x_coord(p_nextnext); y = y_coord(p_nextnext); };
19333     out_angle = mp_an_angle(mp, x - xp, y- yp);
19334     ang  = (out_angle - in_angle);
19335     reduce_angle(ang);
19336     if ( ang!=0 ) {
19337       res  = res + ang;
19338       if ( res >= one_eighty_deg ) {
19339         res = res - three_sixty_deg;
19340         turns = turns + unity;
19341       };
19342       if ( res <= -one_eighty_deg ) {
19343         res = res + three_sixty_deg;
19344         turns = turns - unity;
19345       };
19346     };
19347     p = link(p);
19348   } while (p!=c);
19349   mp->selector=old_setting;
19350   return turns;
19351 }
19352
19353
19354 @ This code is based on Bogus\l{}av Jackowski's
19355 |emergency_turningnumber| macro, with some minor changes by Taco
19356 Hoekwater. The macro code looked more like this:
19357 {\obeylines
19358 vardef turning\_number primary p =
19359 ~~save res, ang, turns;
19360 ~~res := 0;
19361 ~~if length p <= 2:
19362 ~~~~if Angle ((point 0 of p) - (postcontrol 0 of p)) >= 0:  1  else: -1 fi
19363 ~~else:
19364 ~~~~for t = 0 upto length p-1 :
19365 ~~~~~~angc := Angle ((point t+1 of p)  - (point t of p))
19366 ~~~~~~~~- Angle ((point t of p) - (point t-1 of p));
19367 ~~~~~~if angc > 180: angc := angc - 360; fi;
19368 ~~~~~~if angc < -180: angc := angc + 360; fi;
19369 ~~~~~~res  := res + angc;
19370 ~~~~endfor;
19371 ~~res/360
19372 ~~fi
19373 enddef;}
19374 The general idea is to calculate only the sum of the angles of
19375 straight lines between the points, of a path, not worrying about cusps
19376 or self-intersections in the segments at all. If the segment is not
19377 well-behaved, the result is not necesarily correct. But the old code
19378 was not always correct either, and worse, it sometimes failed for
19379 well-behaved paths as well. All known bugs that were triggered by the
19380 original code no longer occur with this code, and it runs roughly 3
19381 times as fast because the algorithm is much simpler.
19382
19383 @ It is possible to overflow the return value of the |turn_cycles|
19384 function when the path is sufficiently long and winding, but I am not
19385 going to bother testing for that. In any case, it would only return
19386 the looped result value, which is not a big problem.
19387
19388 The macro code for the repeat loop was a bit nicer to look
19389 at than the pascal code, because it could use |point -1 of p|. In
19390 pascal, the fastest way to loop around the path is not to look
19391 backward once, but forward twice. These defines help hide the trick.
19392
19393 @d p_to link(link(p))
19394 @d p_here link(p)
19395 @d p_from p
19396
19397 @<Declare unary action...@>=
19398 scaled mp_turn_cycles (MP mp,pointer c) {
19399   angle res,ang; /*  the angles of intermediate results  */
19400   scaled turns;  /*  the turn counter  */
19401   pointer p;     /*  for running around the path  */
19402   res=0;  turns= 0; p=c;
19403   do { 
19404     ang  = mp_an_angle (mp, x_coord(p_to) - x_coord(p_here), 
19405                             y_coord(p_to) - y_coord(p_here))
19406         - mp_an_angle (mp, x_coord(p_here) - x_coord(p_from), 
19407                            y_coord(p_here) - y_coord(p_from));
19408     reduce_angle(ang);
19409     res  = res + ang;
19410     if ( res >= three_sixty_deg )  {
19411       res = res - three_sixty_deg;
19412       turns = turns + unity;
19413     };
19414     if ( res <= -three_sixty_deg ) {
19415       res = res + three_sixty_deg;
19416       turns = turns - unity;
19417     };
19418     p = link(p);
19419   } while (p!=c);
19420   return turns;
19421 }
19422
19423 @ @<Declare unary action...@>=
19424 scaled mp_turn_cycles_wrapper (MP mp,pointer c) {
19425   scaled nval,oval;
19426   scaled saved_t_o; /* tracing\_online saved  */
19427   if ( (link(c)==c)||(link(link(c))==c) ) {
19428     if ( mp_an_angle (mp, x_coord(c) - right_x(c),  y_coord(c) - right_y(c)) > 0 )
19429       return unity;
19430     else
19431       return -unity;
19432   } else {
19433     nval = mp_new_turn_cycles(mp, c);
19434     oval = mp_turn_cycles(mp, c);
19435     if ( nval!=oval ) {
19436       saved_t_o=mp->internal[mp_tracing_online];
19437       mp->internal[mp_tracing_online]=unity;
19438       mp_begin_diagnostic(mp);
19439       mp_print_nl (mp, "Warning: the turningnumber algorithms do not agree."
19440                        " The current computed value is ");
19441       mp_print_scaled(mp, nval);
19442       mp_print(mp, ", but the 'connect-the-dots' algorithm returned ");
19443       mp_print_scaled(mp, oval);
19444       mp_end_diagnostic(mp, false);
19445       mp->internal[mp_tracing_online]=saved_t_o;
19446     }
19447     return nval;
19448   }
19449 }
19450
19451 @ @<Declare unary action...@>=
19452 scaled mp_count_turns (MP mp,pointer c) {
19453   pointer p; /* a knot in envelope spec |c| */
19454   integer t; /* total pen offset changes counted */
19455   t=0; p=c;
19456   do {  
19457     t=t+info(p)-zero_off;
19458     p=link(p);
19459   } while (p!=c);
19460   return ((t / 3)*unity);
19461 }
19462
19463 @ @d type_range(A,B) { 
19464   if ( (mp->cur_type>=(A)) && (mp->cur_type<=(B)) ) 
19465     mp_flush_cur_exp(mp, true_code);
19466   else mp_flush_cur_exp(mp, false_code);
19467   mp->cur_type=mp_boolean_type;
19468   }
19469 @d type_test(A) { 
19470   if ( mp->cur_type==(A) ) mp_flush_cur_exp(mp, true_code);
19471   else mp_flush_cur_exp(mp, false_code);
19472   mp->cur_type=mp_boolean_type;
19473   }
19474
19475 @<Additional cases of unary operators@>=
19476 case mp_boolean_type: 
19477   type_range(mp_boolean_type,mp_unknown_boolean); break;
19478 case mp_string_type: 
19479   type_range(mp_string_type,mp_unknown_string); break;
19480 case mp_pen_type: 
19481   type_range(mp_pen_type,mp_unknown_pen); break;
19482 case mp_path_type: 
19483   type_range(mp_path_type,mp_unknown_path); break;
19484 case mp_picture_type: 
19485   type_range(mp_picture_type,mp_unknown_picture); break;
19486 case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
19487 case mp_pair_type: 
19488   type_test(c); break;
19489 case mp_numeric_type: 
19490   type_range(mp_known,mp_independent); break;
19491 case known_op: case unknown_op: 
19492   mp_test_known(mp, c); break;
19493
19494 @ @<Declare unary action procedures@>=
19495 void mp_test_known (MP mp,quarterword c) {
19496   int b; /* is the current expression known? */
19497   pointer p,q; /* locations in a big node */
19498   b=false_code;
19499   switch (mp->cur_type) {
19500   case mp_vacuous: case mp_boolean_type: case mp_string_type:
19501   case mp_pen_type: case mp_path_type: case mp_picture_type:
19502   case mp_known: 
19503     b=true_code;
19504     break;
19505   case mp_transform_type:
19506   case mp_color_type: case mp_cmykcolor_type: case mp_pair_type: 
19507     p=value(mp->cur_exp);
19508     q=p+mp->big_node_size[mp->cur_type];
19509     do {  
19510       q=q-2;
19511       if ( type(q)!=mp_known ) 
19512        goto DONE;
19513     } while (q!=p);
19514     b=true_code;
19515   DONE:  
19516     break;
19517   default: 
19518     break;
19519   }
19520   if ( c==known_op ) mp_flush_cur_exp(mp, b);
19521   else mp_flush_cur_exp(mp, true_code+false_code-b);
19522   mp->cur_type=mp_boolean_type;
19523 }
19524
19525 @ @<Additional cases of unary operators@>=
19526 case cycle_op: 
19527   if ( mp->cur_type!=mp_path_type ) mp_flush_cur_exp(mp, false_code);
19528   else if ( left_type(mp->cur_exp)!=mp_endpoint ) mp_flush_cur_exp(mp, true_code);
19529   else mp_flush_cur_exp(mp, false_code);
19530   mp->cur_type=mp_boolean_type;
19531   break;
19532
19533 @ @<Additional cases of unary operators@>=
19534 case arc_length: 
19535   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19536   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, arc_length);
19537   else mp_flush_cur_exp(mp, mp_get_arc_length(mp, mp->cur_exp));
19538   break;
19539
19540 @ Here we use the fact that |c-filled_op+fill_code| is the desired graphical
19541 object |type|.
19542 @^data structure assumptions@>
19543
19544 @<Additional cases of unary operators@>=
19545 case filled_op:
19546 case stroked_op:
19547 case textual_op:
19548 case clipped_op:
19549 case bounded_op:
19550   if ( mp->cur_type!=mp_picture_type ) mp_flush_cur_exp(mp, false_code);
19551   else if ( link(dummy_loc(mp->cur_exp))==null ) mp_flush_cur_exp(mp, false_code);
19552   else if ( type(link(dummy_loc(mp->cur_exp)))==c+mp_fill_code-filled_op )
19553     mp_flush_cur_exp(mp, true_code);
19554   else mp_flush_cur_exp(mp, false_code);
19555   mp->cur_type=mp_boolean_type;
19556   break;
19557
19558 @ @<Additional cases of unary operators@>=
19559 case make_pen_op: 
19560   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19561   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, make_pen_op);
19562   else { 
19563     mp->cur_type=mp_pen_type;
19564     mp->cur_exp=mp_make_pen(mp, mp->cur_exp,true);
19565   };
19566   break;
19567 case make_path_op: 
19568   if ( mp->cur_type!=mp_pen_type ) mp_bad_unary(mp, make_path_op);
19569   else  { 
19570     mp->cur_type=mp_path_type;
19571     mp_make_path(mp, mp->cur_exp);
19572   };
19573   break;
19574 case reverse: 
19575   if ( mp->cur_type==mp_path_type ) {
19576     p=mp_htap_ypoc(mp, mp->cur_exp);
19577     if ( right_type(p)==mp_endpoint ) p=link(p);
19578     mp_toss_knot_list(mp, mp->cur_exp); mp->cur_exp=p;
19579   } else if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19580   else mp_bad_unary(mp, reverse);
19581   break;
19582
19583 @ The |pair_value| routine changes the current expression to a
19584 given ordered pair of values.
19585
19586 @<Declare unary action procedures@>=
19587 void mp_pair_value (MP mp,scaled x, scaled y) {
19588   pointer p; /* a pair node */
19589   p=mp_get_node(mp, value_node_size); 
19590   mp_flush_cur_exp(mp, p); mp->cur_type=mp_pair_type;
19591   type(p)=mp_pair_type; name_type(p)=mp_capsule; mp_init_big_node(mp, p);
19592   p=value(p);
19593   type(x_part_loc(p))=mp_known; value(x_part_loc(p))=x;
19594   type(y_part_loc(p))=mp_known; value(y_part_loc(p))=y;
19595 }
19596
19597 @ @<Additional cases of unary operators@>=
19598 case ll_corner_op: 
19599   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ll_corner_op);
19600   else mp_pair_value(mp, minx,miny);
19601   break;
19602 case lr_corner_op: 
19603   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, lr_corner_op);
19604   else mp_pair_value(mp, maxx,miny);
19605   break;
19606 case ul_corner_op: 
19607   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ul_corner_op);
19608   else mp_pair_value(mp, minx,maxy);
19609   break;
19610 case ur_corner_op: 
19611   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ur_corner_op);
19612   else mp_pair_value(mp, maxx,maxy);
19613   break;
19614
19615 @ Here is a function that sets |minx|, |maxx|, |miny|, |maxy| to the bounding
19616 box of the current expression.  The boolean result is |false| if the expression
19617 has the wrong type.
19618
19619 @<Declare unary action procedures@>=
19620 boolean mp_get_cur_bbox (MP mp) { 
19621   switch (mp->cur_type) {
19622   case mp_picture_type: 
19623     mp_set_bbox(mp, mp->cur_exp,true);
19624     if ( minx_val(mp->cur_exp)>maxx_val(mp->cur_exp) ) {
19625       minx=0; maxx=0; miny=0; maxy=0;
19626     } else { 
19627       minx=minx_val(mp->cur_exp);
19628       maxx=maxx_val(mp->cur_exp);
19629       miny=miny_val(mp->cur_exp);
19630       maxy=maxy_val(mp->cur_exp);
19631     }
19632     break;
19633   case mp_path_type: 
19634     mp_path_bbox(mp, mp->cur_exp);
19635     break;
19636   case mp_pen_type: 
19637     mp_pen_bbox(mp, mp->cur_exp);
19638     break;
19639   default: 
19640     return false;
19641   }
19642   return true;
19643 }
19644
19645 @ @<Additional cases of unary operators@>=
19646 case read_from_op:
19647 case close_from_op: 
19648   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19649   else mp_do_read_or_close(mp,c);
19650   break;
19651
19652 @ Here is a routine that interprets |cur_exp| as a file name and tries to read
19653 a line from the file or to close the file.
19654
19655 @d close_file 46 /* go here when closing the file */
19656
19657 @<Declare unary action procedures@>=
19658 void mp_do_read_or_close (MP mp,quarterword c) {
19659   readf_index n,n0; /* indices for searching |rd_fname| */
19660   @<Find the |n| where |rd_fname[n]=cur_exp|; if |cur_exp| must be inserted,
19661     call |start_read_input| and |goto found| or |not_found|@>;
19662   mp_begin_file_reading(mp);
19663   name=is_read;
19664   if ( mp_input_ln(mp, mp->rd_file[n],true) ) 
19665     goto FOUND;
19666   mp_end_file_reading(mp);
19667 NOT_FOUND:
19668   @<Record the end of file and set |cur_exp| to a dummy value@>;
19669   return;
19670 CLOSE_FILE:
19671   mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous; 
19672   return;
19673 FOUND:
19674   mp_flush_cur_exp(mp, 0);
19675   mp_finish_read(mp);
19676 }
19677
19678 @ Free slots in the |rd_file| and |rd_fname| arrays are marked with NULL's in
19679 |rd_fname|.
19680
19681 @<Find the |n| where |rd_fname[n]=cur_exp|...@>=
19682 {   
19683   char *fn;
19684   n=mp->read_files;
19685   n0=mp->read_files;
19686   fn = str(mp->cur_exp);
19687   while (mp_xstrcmp(fn,mp->rd_fname[n])!=0) { 
19688     if ( n>0 ) {
19689       decr(n);
19690     } else if ( c==close_from_op ) {
19691       goto CLOSE_FILE;
19692     } else {
19693       if ( n0==mp->read_files ) {
19694         if ( mp->read_files<mp->max_read_files ) {
19695           incr(mp->read_files);
19696         } else {
19697           FILE **rd_file;
19698           char **rd_fname;
19699               readf_index l,k;
19700           l = mp->max_read_files + (mp->max_read_files>>2);
19701           rd_file = xmalloc((l+1), sizeof(FILE *));
19702           rd_fname = xmalloc((l+1), sizeof(char *));
19703               for (k=0;k<=l;k++) {
19704             if (k<=mp->max_read_files) {
19705                   rd_file[k]=mp->rd_file[k]; 
19706               rd_fname[k]=mp->rd_fname[k];
19707             } else {
19708               rd_file[k]=0; 
19709               rd_fname[k]=NULL;
19710             }
19711           }
19712               xfree(mp->rd_file); xfree(mp->rd_fname);
19713           mp->max_read_files = l;
19714           mp->rd_file = rd_file;
19715           mp->rd_fname = rd_fname;
19716         }
19717       }
19718       n=n0;
19719       if ( mp_start_read_input(mp,fn,n) ) 
19720         goto FOUND;
19721       else 
19722         goto NOT_FOUND;
19723     }
19724     if ( mp->rd_fname[n]==NULL ) { n0=n; }
19725   } 
19726   if ( c==close_from_op ) { 
19727     fclose(mp->rd_file[n]); 
19728     goto NOT_FOUND; 
19729   }
19730 }
19731
19732 @ @<Record the end of file and set |cur_exp| to a dummy value@>=
19733 xfree(mp->rd_fname[n]);
19734 mp->rd_fname[n]=NULL;
19735 if ( n==mp->read_files-1 ) mp->read_files=n;
19736 if ( c==close_from_op ) 
19737   goto CLOSE_FILE;
19738 mp_flush_cur_exp(mp, mp->eof_line);
19739 mp->cur_type=mp_string_type
19740
19741 @ The string denoting end-of-file is a one-byte string at position zero, by definition
19742
19743 @<Glob...@>=
19744 str_number eof_line;
19745
19746 @ @<Set init...@>=
19747 mp->eof_line=0;
19748
19749 @ Finally, we have the operations that combine a capsule~|p|
19750 with the current expression.
19751
19752 @c @<Declare binary action procedures@>;
19753 void mp_do_binary (MP mp,pointer p, quarterword c) {
19754   pointer q,r,rr; /* for list manipulation */
19755   pointer old_p,old_exp; /* capsules to recycle */
19756   integer v; /* for numeric manipulation */
19757   check_arith;
19758   if ( mp->internal[mp_tracing_commands]>two ) {
19759     @<Trace the current binary operation@>;
19760   }
19761   @<Sidestep |independent| cases in capsule |p|@>;
19762   @<Sidestep |independent| cases in the current expression@>;
19763   switch (c) {
19764   case plus: case minus:
19765     @<Add or subtract the current expression from |p|@>;
19766     break;
19767   @<Additional cases of binary operators@>;
19768   }; /* there are no other cases */
19769   mp_recycle_value(mp, p); 
19770   mp_free_node(mp, p,value_node_size); /* |return| to avoid this */
19771   check_arith; 
19772   @<Recycle any sidestepped |independent| capsules@>;
19773 }
19774
19775 @ @<Declare binary action...@>=
19776 void mp_bad_binary (MP mp,pointer p, quarterword c) { 
19777   mp_disp_err(mp, p,"");
19778   exp_err("Not implemented: ");
19779 @.Not implemented...@>
19780   if ( c>=min_of ) mp_print_op(mp, c);
19781   mp_print_known_or_unknown_type(mp, type(p),p);
19782   if ( c>=min_of ) mp_print(mp, "of"); else mp_print_op(mp, c);
19783   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
19784   help3("I'm afraid I don't know how to apply that operation to that")
19785        ("combination of types. Continue, and I'll return the second")
19786       ("argument (see above) as the result of the operation.");
19787   mp_put_get_error(mp);
19788 }
19789
19790 @ @<Trace the current binary operation@>=
19791
19792   mp_begin_diagnostic(mp); mp_print_nl(mp, "{(");
19793   mp_print_exp(mp,p,0); /* show the operand, but not verbosely */
19794   mp_print_char(mp,')'); mp_print_op(mp,c); mp_print_char(mp,'(');
19795   mp_print_exp(mp,null,0); mp_print(mp,")}"); 
19796   mp_end_diagnostic(mp, false);
19797 }
19798
19799 @ Several of the binary operations are potentially complicated by the
19800 fact that |independent| values can sneak into capsules. For example,
19801 we've seen an instance of this difficulty in the unary operation
19802 of negation. In order to reduce the number of cases that need to be
19803 handled, we first change the two operands (if necessary)
19804 to rid them of |independent| components. The original operands are
19805 put into capsules called |old_p| and |old_exp|, which will be
19806 recycled after the binary operation has been safely carried out.
19807
19808 @<Recycle any sidestepped |independent| capsules@>=
19809 if ( old_p!=null ) { 
19810   mp_recycle_value(mp, old_p); mp_free_node(mp, old_p,value_node_size);
19811 }
19812 if ( old_exp!=null ) {
19813   mp_recycle_value(mp, old_exp); mp_free_node(mp, old_exp,value_node_size);
19814 }
19815
19816 @ A big node is considered to be ``tarnished'' if it contains at least one
19817 independent component. We will define a simple function called `|tarnished|'
19818 that returns |null| if and only if its argument is not tarnished.
19819
19820 @<Sidestep |independent| cases in capsule |p|@>=
19821 switch (type(p)) {
19822 case mp_transform_type:
19823 case mp_color_type:
19824 case mp_cmykcolor_type:
19825 case mp_pair_type: 
19826   old_p=mp_tarnished(mp, p);
19827   break;
19828 case mp_independent: old_p=mp_void; break;
19829 default: old_p=null; break;
19830 };
19831 if ( old_p!=null ) {
19832   q=mp_stash_cur_exp(mp); old_p=p; mp_make_exp_copy(mp, old_p);
19833   p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
19834 }
19835
19836 @ @<Sidestep |independent| cases in the current expression@>=
19837 switch (mp->cur_type) {
19838 case mp_transform_type:
19839 case mp_color_type:
19840 case mp_cmykcolor_type:
19841 case mp_pair_type: 
19842   old_exp=mp_tarnished(mp, mp->cur_exp);
19843   break;
19844 case mp_independent:old_exp=mp_void; break;
19845 default: old_exp=null; break;
19846 };
19847 if ( old_exp!=null ) {
19848   old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
19849 }
19850
19851 @ @<Declare binary action...@>=
19852 pointer mp_tarnished (MP mp,pointer p) {
19853   pointer q; /* beginning of the big node */
19854   pointer r; /* current position in the big node */
19855   q=value(p); r=q+mp->big_node_size[type(p)];
19856   do {  
19857    r=r-2;
19858    if ( type(r)==mp_independent ) return mp_void; 
19859   } while (r!=q);
19860   return null;
19861 }
19862
19863 @ @<Add or subtract the current expression from |p|@>=
19864 if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
19865   mp_bad_binary(mp, p,c);
19866 } else  {
19867   if ((mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
19868     mp_add_or_subtract(mp, p,null,c);
19869   } else {
19870     if ( mp->cur_type!=type(p) )  {
19871       mp_bad_binary(mp, p,c);
19872     } else { 
19873       q=value(p); r=value(mp->cur_exp);
19874       rr=r+mp->big_node_size[mp->cur_type];
19875       while ( r<rr ) { 
19876         mp_add_or_subtract(mp, q,r,c);
19877         q=q+2; r=r+2;
19878       }
19879     }
19880   }
19881 }
19882
19883 @ The first argument to |add_or_subtract| is the location of a value node
19884 in a capsule or pair node that will soon be recycled. The second argument
19885 is either a location within a pair or transform node of |cur_exp|,
19886 or it is null (which means that |cur_exp| itself should be the second
19887 argument).  The third argument is either |plus| or |minus|.
19888
19889 The sum or difference of the numeric quantities will replace the second
19890 operand.  Arithmetic overflow may go undetected; users aren't supposed to
19891 be monkeying around with really big values.
19892
19893 @<Declare binary action...@>=
19894 @<Declare the procedure called |dep_finish|@>;
19895 void mp_add_or_subtract (MP mp,pointer p, pointer q, quarterword c) {
19896   small_number s,t; /* operand types */
19897   pointer r; /* list traverser */
19898   integer v; /* second operand value */
19899   if ( q==null ) { 
19900     t=mp->cur_type;
19901     if ( t<mp_dependent ) v=mp->cur_exp; else v=dep_list(mp->cur_exp);
19902   } else { 
19903     t=type(q);
19904     if ( t<mp_dependent ) v=value(q); else v=dep_list(q);
19905   }
19906   if ( t==mp_known ) {
19907     if ( c==minus ) negate(v);
19908     if ( type(p)==mp_known ) {
19909       v=mp_slow_add(mp, value(p),v);
19910       if ( q==null ) mp->cur_exp=v; else value(q)=v;
19911       return;
19912     }
19913     @<Add a known value to the constant term of |dep_list(p)|@>;
19914   } else  { 
19915     if ( c==minus ) mp_negate_dep_list(mp, v);
19916     @<Add operand |p| to the dependency list |v|@>;
19917   }
19918 }
19919
19920 @ @<Add a known value to the constant term of |dep_list(p)|@>=
19921 r=dep_list(p);
19922 while ( info(r)!=null ) r=link(r);
19923 value(r)=mp_slow_add(mp, value(r),v);
19924 if ( q==null ) {
19925   q=mp_get_node(mp, value_node_size); mp->cur_exp=q; mp->cur_type=type(p);
19926   name_type(q)=mp_capsule;
19927 }
19928 dep_list(q)=dep_list(p); type(q)=type(p);
19929 prev_dep(q)=prev_dep(p); link(prev_dep(p))=q;
19930 type(p)=mp_known; /* this will keep the recycler from collecting non-garbage */
19931
19932 @ We prefer |dependent| lists to |mp_proto_dependent| ones, because it is
19933 nice to retain the extra accuracy of |fraction| coefficients.
19934 But we have to handle both kinds, and mixtures too.
19935
19936 @<Add operand |p| to the dependency list |v|@>=
19937 if ( type(p)==mp_known ) {
19938   @<Add the known |value(p)| to the constant term of |v|@>;
19939 } else { 
19940   s=type(p); r=dep_list(p);
19941   if ( t==mp_dependent ) {
19942     if ( s==mp_dependent ) {
19943       if ( mp_max_coef(mp, r)+mp_max_coef(mp, v)<coef_bound )
19944         v=mp_p_plus_q(mp, v,r,mp_dependent); goto DONE;
19945       } /* |fix_needed| will necessarily be false */
19946       t=mp_proto_dependent; 
19947       v=mp_p_over_v(mp, v,unity,mp_dependent,mp_proto_dependent);
19948     }
19949     if ( s==mp_proto_dependent ) v=mp_p_plus_q(mp, v,r,mp_proto_dependent);
19950     else v=mp_p_plus_fq(mp, v,unity,r,mp_proto_dependent,mp_dependent);
19951  DONE:  
19952     @<Output the answer, |v| (which might have become |known|)@>;
19953   }
19954
19955 @ @<Add the known |value(p)| to the constant term of |v|@>=
19956
19957   while ( info(v)!=null ) v=link(v);
19958   value(v)=mp_slow_add(mp, value(p),value(v));
19959 }
19960
19961 @ @<Output the answer, |v| (which might have become |known|)@>=
19962 if ( q!=null ) mp_dep_finish(mp, v,q,t);
19963 else  { mp->cur_type=t; mp_dep_finish(mp, v,null,t); }
19964
19965 @ Here's the current situation: The dependency list |v| of type |t|
19966 should either be put into the current expression (if |q=null|) or
19967 into location |q| within a pair node (otherwise). The destination (|cur_exp|
19968 or |q|) formerly held a dependency list with the same
19969 final pointer as the list |v|.
19970
19971 @<Declare the procedure called |dep_finish|@>=
19972 void mp_dep_finish (MP mp, pointer v, pointer q, small_number t) {
19973   pointer p; /* the destination */
19974   scaled vv; /* the value, if it is |known| */
19975   if ( q==null ) p=mp->cur_exp; else p=q;
19976   dep_list(p)=v; type(p)=t;
19977   if ( info(v)==null ) { 
19978     vv=value(v);
19979     if ( q==null ) { 
19980       mp_flush_cur_exp(mp, vv);
19981     } else  { 
19982       mp_recycle_value(mp, p); type(q)=mp_known; value(q)=vv; 
19983     }
19984   } else if ( q==null ) {
19985     mp->cur_type=t;
19986   }
19987   if ( mp->fix_needed ) mp_fix_dependencies(mp);
19988 }
19989
19990 @ Let's turn now to the six basic relations of comparison.
19991
19992 @<Additional cases of binary operators@>=
19993 case less_than: case less_or_equal: case greater_than:
19994 case greater_or_equal: case equal_to: case unequal_to:
19995   check_arith; /* at this point |arith_error| should be |false|? */
19996   if ( (mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
19997     mp_add_or_subtract(mp, p,null,minus); /* |cur_exp:=(p)-cur_exp| */
19998   } else if ( mp->cur_type!=type(p) ) {
19999     mp_bad_binary(mp, p,c); goto DONE; 
20000   } else if ( mp->cur_type==mp_string_type ) {
20001     mp_flush_cur_exp(mp, mp_str_vs_str(mp, value(p),mp->cur_exp));
20002   } else if ((mp->cur_type==mp_unknown_string)||
20003            (mp->cur_type==mp_unknown_boolean) ) {
20004     @<Check if unknowns have been equated@>;
20005   } else if ( (mp->cur_type<=mp_pair_type)&&(mp->cur_type>=mp_transform_type)) {
20006     @<Reduce comparison of big nodes to comparison of scalars@>;
20007   } else if ( mp->cur_type==mp_boolean_type ) {
20008     mp_flush_cur_exp(mp, mp->cur_exp-value(p));
20009   } else { 
20010     mp_bad_binary(mp, p,c); goto DONE;
20011   }
20012   @<Compare the current expression with zero@>;
20013 DONE:  
20014   mp->arith_error=false; /* ignore overflow in comparisons */
20015   break;
20016
20017 @ @<Compare the current expression with zero@>=
20018 if ( mp->cur_type!=mp_known ) {
20019   if ( mp->cur_type<mp_known ) {
20020     mp_disp_err(mp, p,"");
20021     help1("The quantities shown above have not been equated.")
20022   } else  {
20023     help2("Oh dear. I can\'t decide if the expression above is positive,")
20024      ("negative, or zero. So this comparison test won't be `true'.");
20025   }
20026   exp_err("Unknown relation will be considered false");
20027 @.Unknown relation...@>
20028   mp_put_get_flush_error(mp, false_code);
20029 } else {
20030   switch (c) {
20031   case less_than: boolean_reset(mp->cur_exp<0); break;
20032   case less_or_equal: boolean_reset(mp->cur_exp<=0); break;
20033   case greater_than: boolean_reset(mp->cur_exp>0); break;
20034   case greater_or_equal: boolean_reset(mp->cur_exp>=0); break;
20035   case equal_to: boolean_reset(mp->cur_exp==0); break;
20036   case unequal_to: boolean_reset(mp->cur_exp!=0); break;
20037   }; /* there are no other cases */
20038 }
20039 mp->cur_type=mp_boolean_type
20040
20041 @ When two unknown strings are in the same ring, we know that they are
20042 equal. Otherwise, we don't know whether they are equal or not, so we
20043 make no change.
20044
20045 @<Check if unknowns have been equated@>=
20046
20047   q=value(mp->cur_exp);
20048   while ( (q!=mp->cur_exp)&&(q!=p) ) q=value(q);
20049   if ( q==p ) mp_flush_cur_exp(mp, 0);
20050 }
20051
20052 @ @<Reduce comparison of big nodes to comparison of scalars@>=
20053
20054   q=value(p); r=value(mp->cur_exp);
20055   rr=r+mp->big_node_size[mp->cur_type]-2;
20056   while (1) { mp_add_or_subtract(mp, q,r,minus);
20057     if ( type(r)!=mp_known ) break;
20058     if ( value(r)!=0 ) break;
20059     if ( r==rr ) break;
20060     q=q+2; r=r+2;
20061   }
20062   mp_take_part(mp, name_type(r)+x_part-mp_x_part_sector);
20063 }
20064
20065 @ Here we use the sneaky fact that |and_op-false_code=or_op-true_code|.
20066
20067 @<Additional cases of binary operators@>=
20068 case and_op:
20069 case or_op: 
20070   if ( (type(p)!=mp_boolean_type)||(mp->cur_type!=mp_boolean_type) )
20071     mp_bad_binary(mp, p,c);
20072   else if ( value(p)==c+false_code-and_op ) mp->cur_exp=value(p);
20073   break;
20074
20075 @ @<Additional cases of binary operators@>=
20076 case times: 
20077   if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
20078    mp_bad_binary(mp, p,times);
20079   } else if ( (mp->cur_type==mp_known)||(type(p)==mp_known) ) {
20080     @<Multiply when at least one operand is known@>;
20081   } else if ( (mp_nice_color_or_pair(mp, p,type(p))&&(mp->cur_type>mp_pair_type))
20082       ||(mp_nice_color_or_pair(mp, mp->cur_exp,mp->cur_type)&&
20083           (type(p)>mp_pair_type)) ) {
20084     mp_hard_times(mp, p); return;
20085   } else {
20086     mp_bad_binary(mp, p,times);
20087   }
20088   break;
20089
20090 @ @<Multiply when at least one operand is known@>=
20091
20092   if ( type(p)==mp_known ) {
20093     v=value(p); mp_free_node(mp, p,value_node_size); 
20094   } else {
20095     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20096   }
20097   if ( mp->cur_type==mp_known ) {
20098     mp->cur_exp=mp_take_scaled(mp, mp->cur_exp,v);
20099   } else if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_color_type)||
20100               (mp->cur_type==mp_cmykcolor_type) ) {
20101     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20102     do {  
20103        p=p-2; mp_dep_mult(mp, p,v,true);
20104     } while (p!=value(mp->cur_exp));
20105   } else {
20106     mp_dep_mult(mp, null,v,true);
20107   }
20108   return;
20109 }
20110
20111 @ @<Declare binary action...@>=
20112 void mp_dep_mult (MP mp,pointer p, integer v, boolean v_is_scaled) {
20113   pointer q; /* the dependency list being multiplied by |v| */
20114   small_number s,t; /* its type, before and after */
20115   if ( p==null ) {
20116     q=mp->cur_exp;
20117   } else if ( type(p)!=mp_known ) {
20118     q=p;
20119   } else { 
20120     if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
20121     else value(p)=mp_take_fraction(mp, value(p),v);
20122     return;
20123   };
20124   t=type(q); q=dep_list(q); s=t;
20125   if ( t==mp_dependent ) if ( v_is_scaled )
20126     if (mp_ab_vs_cd(mp, mp_max_coef(mp,q),abs(v),coef_bound-1,unity)>=0 ) 
20127       t=mp_proto_dependent;
20128   q=mp_p_times_v(mp, q,v,s,t,v_is_scaled); 
20129   mp_dep_finish(mp, q,p,t);
20130 }
20131
20132 @ Here is a routine that is similar to |times|; but it is invoked only
20133 internally, when |v| is a |fraction| whose magnitude is at most~1,
20134 and when |cur_type>=mp_color_type|.
20135
20136 @c void mp_frac_mult (MP mp,scaled n, scaled d) {
20137   /* multiplies |cur_exp| by |n/d| */
20138   pointer p; /* a pair node */
20139   pointer old_exp; /* a capsule to recycle */
20140   fraction v; /* |n/d| */
20141   if ( mp->internal[mp_tracing_commands]>two ) {
20142     @<Trace the fraction multiplication@>;
20143   }
20144   switch (mp->cur_type) {
20145   case mp_transform_type:
20146   case mp_color_type:
20147   case mp_cmykcolor_type:
20148   case mp_pair_type:
20149    old_exp=mp_tarnished(mp, mp->cur_exp);
20150    break;
20151   case mp_independent: old_exp=mp_void; break;
20152   default: old_exp=null; break;
20153   }
20154   if ( old_exp!=null ) { 
20155      old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
20156   }
20157   v=mp_make_fraction(mp, n,d);
20158   if ( mp->cur_type==mp_known ) {
20159     mp->cur_exp=mp_take_fraction(mp, mp->cur_exp,v);
20160   } else if ( mp->cur_type<=mp_pair_type ) { 
20161     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20162     do {  
20163       p=p-2;
20164       mp_dep_mult(mp, p,v,false);
20165     } while (p!=value(mp->cur_exp));
20166   } else {
20167     mp_dep_mult(mp, null,v,false);
20168   }
20169   if ( old_exp!=null ) {
20170     mp_recycle_value(mp, old_exp); 
20171     mp_free_node(mp, old_exp,value_node_size);
20172   }
20173 }
20174
20175 @ @<Trace the fraction multiplication@>=
20176
20177   mp_begin_diagnostic(mp); 
20178   mp_print_nl(mp, "{("); mp_print_scaled(mp,n); mp_print_char(mp,'/');
20179   mp_print_scaled(mp,d); mp_print(mp,")*("); mp_print_exp(mp,null,0); 
20180   mp_print(mp,")}");
20181   mp_end_diagnostic(mp, false);
20182 }
20183
20184 @ The |hard_times| routine multiplies a nice color or pair by a dependency list.
20185
20186 @<Declare binary action procedures@>=
20187 void mp_hard_times (MP mp,pointer p) {
20188   pointer q; /* a copy of the dependent variable |p| */
20189   pointer r; /* a component of the big node for the nice color or pair */
20190   scaled v; /* the known value for |r| */
20191   if ( type(p)<=mp_pair_type ) { 
20192      q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p); p=q;
20193   }; /* now |cur_type=mp_pair_type| or |cur_type=mp_color_type| */
20194   r=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20195   while (1) { 
20196     r=r-2;
20197     v=value(r);
20198     type(r)=type(p);
20199     if ( r==value(mp->cur_exp) ) 
20200       break;
20201     mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(p)));
20202     mp_dep_mult(mp, r,v,true);
20203   }
20204   mp->mem[value_loc(r)]=mp->mem[value_loc(p)];
20205   link(prev_dep(p))=r;
20206   mp_free_node(mp, p,value_node_size);
20207   mp_dep_mult(mp, r,v,true);
20208 }
20209
20210 @ @<Additional cases of binary operators@>=
20211 case over: 
20212   if ( (mp->cur_type!=mp_known)||(type(p)<mp_color_type) ) {
20213     mp_bad_binary(mp, p,over);
20214   } else { 
20215     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20216     if ( v==0 ) {
20217       @<Squeal about division by zero@>;
20218     } else { 
20219       if ( mp->cur_type==mp_known ) {
20220         mp->cur_exp=mp_make_scaled(mp, mp->cur_exp,v);
20221       } else if ( mp->cur_type<=mp_pair_type ) { 
20222         p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20223         do {  
20224           p=p-2;  mp_dep_div(mp, p,v);
20225         } while (p!=value(mp->cur_exp));
20226       } else {
20227         mp_dep_div(mp, null,v);
20228       }
20229     }
20230     return;
20231   }
20232   break;
20233
20234 @ @<Declare binary action...@>=
20235 void mp_dep_div (MP mp,pointer p, scaled v) {
20236   pointer q; /* the dependency list being divided by |v| */
20237   small_number s,t; /* its type, before and after */
20238   if ( p==null ) q=mp->cur_exp;
20239   else if ( type(p)!=mp_known ) q=p;
20240   else { value(p)=mp_make_scaled(mp, value(p),v); return; };
20241   t=type(q); q=dep_list(q); s=t;
20242   if ( t==mp_dependent )
20243     if ( mp_ab_vs_cd(mp, mp_max_coef(mp,q),unity,coef_bound-1,abs(v))>=0 ) 
20244       t=mp_proto_dependent;
20245   q=mp_p_over_v(mp, q,v,s,t); 
20246   mp_dep_finish(mp, q,p,t);
20247 }
20248
20249 @ @<Squeal about division by zero@>=
20250
20251   exp_err("Division by zero");
20252 @.Division by zero@>
20253   help2("You're trying to divide the quantity shown above the error")
20254     ("message by zero. I'm going to divide it by one instead.");
20255   mp_put_get_error(mp);
20256 }
20257
20258 @ @<Additional cases of binary operators@>=
20259 case pythag_add:
20260 case pythag_sub: 
20261    if ( (mp->cur_type==mp_known)&&(type(p)==mp_known) ) {
20262      if ( c==pythag_add ) mp->cur_exp=mp_pyth_add(mp, value(p),mp->cur_exp);
20263      else mp->cur_exp=mp_pyth_sub(mp, value(p),mp->cur_exp);
20264    } else mp_bad_binary(mp, p,c);
20265    break;
20266
20267 @ The next few sections of the program deal with affine transformations
20268 of coordinate data.
20269
20270 @<Additional cases of binary operators@>=
20271 case rotated_by: case slanted_by:
20272 case scaled_by: case shifted_by: case transformed_by:
20273 case x_scaled: case y_scaled: case z_scaled:
20274   if ( type(p)==mp_path_type ) { 
20275     path_trans(c,p); return;
20276   } else if ( type(p)==mp_pen_type ) { 
20277     pen_trans(c,p);
20278     mp->cur_exp=mp_convex_hull(mp, mp->cur_exp); 
20279       /* rounding error could destroy convexity */
20280     return;
20281   } else if ( (type(p)==mp_pair_type)||(type(p)==mp_transform_type) ) {
20282     mp_big_trans(mp, p,c);
20283   } else if ( type(p)==mp_picture_type ) {
20284     mp_do_edges_trans(mp, p,c); return;
20285   } else {
20286     mp_bad_binary(mp, p,c);
20287   }
20288   break;
20289
20290 @ Let |c| be one of the eight transform operators. The procedure call
20291 |set_up_trans(c)| first changes |cur_exp| to a transform that corresponds to
20292 |c| and the original value of |cur_exp|. (In particular, |cur_exp| doesn't
20293 change at all if |c=transformed_by|.)
20294
20295 Then, if all components of the resulting transform are |known|, they are
20296 moved to the global variables |txx|, |txy|, |tyx|, |tyy|, |tx|, |ty|;
20297 and |cur_exp| is changed to the known value zero.
20298
20299 @<Declare binary action...@>=
20300 void mp_set_up_trans (MP mp,quarterword c) {
20301   pointer p,q,r; /* list manipulation registers */
20302   if ( (c!=transformed_by)||(mp->cur_type!=mp_transform_type) ) {
20303     @<Put the current transform into |cur_exp|@>;
20304   }
20305   @<If the current transform is entirely known, stash it in global variables;
20306     otherwise |return|@>;
20307 }
20308
20309 @ @<Glob...@>=
20310 scaled txx;
20311 scaled txy;
20312 scaled tyx;
20313 scaled tyy;
20314 scaled tx;
20315 scaled ty; /* current transform coefficients */
20316
20317 @ @<Put the current transform...@>=
20318
20319   p=mp_stash_cur_exp(mp); 
20320   mp->cur_exp=mp_id_transform(mp); 
20321   mp->cur_type=mp_transform_type;
20322   q=value(mp->cur_exp);
20323   switch (c) {
20324   @<For each of the eight cases, change the relevant fields of |cur_exp|
20325     and |goto done|;
20326     but do nothing if capsule |p| doesn't have the appropriate type@>;
20327   }; /* there are no other cases */
20328   mp_disp_err(mp, p,"Improper transformation argument");
20329 @.Improper transformation argument@>
20330   help3("The expression shown above has the wrong type,")
20331        ("so I can\'t transform anything using it.")
20332        ("Proceed, and I'll omit the transformation.");
20333   mp_put_get_error(mp);
20334 DONE: 
20335   mp_recycle_value(mp, p); 
20336   mp_free_node(mp, p,value_node_size);
20337 }
20338
20339 @ @<If the current transform is entirely known, ...@>=
20340 q=value(mp->cur_exp); r=q+transform_node_size;
20341 do {  
20342   r=r-2;
20343   if ( type(r)!=mp_known ) return;
20344 } while (r!=q);
20345 mp->txx=value(xx_part_loc(q));
20346 mp->txy=value(xy_part_loc(q));
20347 mp->tyx=value(yx_part_loc(q));
20348 mp->tyy=value(yy_part_loc(q));
20349 mp->tx=value(x_part_loc(q));
20350 mp->ty=value(y_part_loc(q));
20351 mp_flush_cur_exp(mp, 0)
20352
20353 @ @<For each of the eight cases...@>=
20354 case rotated_by:
20355   if ( type(p)==mp_known )
20356     @<Install sines and cosines, then |goto done|@>;
20357   break;
20358 case slanted_by:
20359   if ( type(p)>mp_pair_type ) { 
20360    mp_install(mp, xy_part_loc(q),p); goto DONE;
20361   };
20362   break;
20363 case scaled_by:
20364   if ( type(p)>mp_pair_type ) { 
20365     mp_install(mp, xx_part_loc(q),p); mp_install(mp, yy_part_loc(q),p); 
20366     goto DONE;
20367   };
20368   break;
20369 case shifted_by:
20370   if ( type(p)==mp_pair_type ) {
20371     r=value(p); mp_install(mp, x_part_loc(q),x_part_loc(r));
20372     mp_install(mp, y_part_loc(q),y_part_loc(r)); goto DONE;
20373   };
20374   break;
20375 case x_scaled:
20376   if ( type(p)>mp_pair_type ) {
20377     mp_install(mp, xx_part_loc(q),p); goto DONE;
20378   };
20379   break;
20380 case y_scaled:
20381   if ( type(p)>mp_pair_type ) {
20382     mp_install(mp, yy_part_loc(q),p); goto DONE;
20383   };
20384   break;
20385 case z_scaled:
20386   if ( type(p)==mp_pair_type )
20387     @<Install a complex multiplier, then |goto done|@>;
20388   break;
20389 case transformed_by:
20390   break;
20391   
20392
20393 @ @<Install sines and cosines, then |goto done|@>=
20394 { mp_n_sin_cos(mp, (value(p) % three_sixty_units)*16);
20395   value(xx_part_loc(q))=mp_round_fraction(mp, mp->n_cos);
20396   value(yx_part_loc(q))=mp_round_fraction(mp, mp->n_sin);
20397   value(xy_part_loc(q))=-value(yx_part_loc(q));
20398   value(yy_part_loc(q))=value(xx_part_loc(q));
20399   goto DONE;
20400 }
20401
20402 @ @<Install a complex multiplier, then |goto done|@>=
20403
20404   r=value(p);
20405   mp_install(mp, xx_part_loc(q),x_part_loc(r));
20406   mp_install(mp, yy_part_loc(q),x_part_loc(r));
20407   mp_install(mp, yx_part_loc(q),y_part_loc(r));
20408   if ( type(y_part_loc(r))==mp_known ) negate(value(y_part_loc(r)));
20409   else mp_negate_dep_list(mp, dep_list(y_part_loc(r)));
20410   mp_install(mp, xy_part_loc(q),y_part_loc(r));
20411   goto DONE;
20412 }
20413
20414 @ Procedure |set_up_known_trans| is like |set_up_trans|, but it
20415 insists that the transformation be entirely known.
20416
20417 @<Declare binary action...@>=
20418 void mp_set_up_known_trans (MP mp,quarterword c) { 
20419   mp_set_up_trans(mp, c);
20420   if ( mp->cur_type!=mp_known ) {
20421     exp_err("Transform components aren't all known");
20422 @.Transform components...@>
20423     help3("I'm unable to apply a partially specified transformation")
20424       ("except to a fully known pair or transform.")
20425       ("Proceed, and I'll omit the transformation.");
20426     mp_put_get_flush_error(mp, 0);
20427     mp->txx=unity; mp->txy=0; mp->tyx=0; mp->tyy=unity; 
20428     mp->tx=0; mp->ty=0;
20429   }
20430 }
20431
20432 @ Here's a procedure that applies the transform |txx..ty| to a pair of
20433 coordinates in locations |p| and~|q|.
20434
20435 @<Declare binary action...@>= 
20436 void mp_trans (MP mp,pointer p, pointer q) {
20437   scaled v; /* the new |x| value */
20438   v=mp_take_scaled(mp, mp->mem[p].sc,mp->txx)+
20439   mp_take_scaled(mp, mp->mem[q].sc,mp->txy)+mp->tx;
20440   mp->mem[q].sc=mp_take_scaled(mp, mp->mem[p].sc,mp->tyx)+
20441   mp_take_scaled(mp, mp->mem[q].sc,mp->tyy)+mp->ty;
20442   mp->mem[p].sc=v;
20443 }
20444
20445 @ The simplest transformation procedure applies a transform to all
20446 coordinates of a path.  The |path_trans(c)(p)| macro applies
20447 a transformation defined by |cur_exp| and the transform operator |c|
20448 to the path~|p|.
20449
20450 @d path_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20451                      mp_unstash_cur_exp(mp, (B)); 
20452                      mp_do_path_trans(mp, mp->cur_exp); }
20453
20454 @<Declare binary action...@>=
20455 void mp_do_path_trans (MP mp,pointer p) {
20456   pointer q; /* list traverser */
20457   q=p;
20458   do { 
20459     if ( left_type(q)!=mp_endpoint ) 
20460       mp_trans(mp, q+3,q+4); /* that's |left_x| and |left_y| */
20461     mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20462     if ( right_type(q)!=mp_endpoint ) 
20463       mp_trans(mp, q+5,q+6); /* that's |right_x| and |right_y| */
20464 @^data structure assumptions@>
20465     q=link(q);
20466   } while (q!=p);
20467 }
20468
20469 @ Transforming a pen is very similar, except that there are no |left_type|
20470 and |right_type| fields.
20471
20472 @d pen_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20473                     mp_unstash_cur_exp(mp, (B)); 
20474                     mp_do_pen_trans(mp, mp->cur_exp); }
20475
20476 @<Declare binary action...@>=
20477 void mp_do_pen_trans (MP mp,pointer p) {
20478   pointer q; /* list traverser */
20479   if ( pen_is_elliptical(p) ) {
20480     mp_trans(mp, p+3,p+4); /* that's |left_x| and |left_y| */
20481     mp_trans(mp, p+5,p+6); /* that's |right_x| and |right_y| */
20482   };
20483   q=p;
20484   do { 
20485     mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20486 @^data structure assumptions@>
20487     q=link(q);
20488   } while (q!=p);
20489 }
20490
20491 @ The next transformation procedure applies to edge structures. It will do
20492 any transformation, but the results may be substandard if the picture contains
20493 text that uses downloaded bitmap fonts.  The binary action procedure is
20494 |do_edges_trans|, but we also need a function that just scales a picture.
20495 That routine is |scale_edges|.  Both it and the underlying routine |edges_trans|
20496 should be thought of as procedures that update an edge structure |h|, except
20497 that they have to return a (possibly new) structure because of the need to call
20498 |private_edges|.
20499
20500 @<Declare binary action...@>=
20501 pointer mp_edges_trans (MP mp, pointer h) {
20502   pointer q; /* the object being transformed */
20503   pointer r,s; /* for list manipulation */
20504   scaled sx,sy; /* saved transformation parameters */
20505   scaled sqdet; /* square root of determinant for |dash_scale| */
20506   integer sgndet; /* sign of the determinant */
20507   scaled v; /* a temporary value */
20508   h=mp_private_edges(mp, h);
20509   sqdet=mp_sqrt_det(mp, mp->txx,mp->txy,mp->tyx,mp->tyy);
20510   sgndet=mp_ab_vs_cd(mp, mp->txx,mp->tyy,mp->txy,mp->tyx);
20511   if ( dash_list(h)!=null_dash ) {
20512     @<Try to transform the dash list of |h|@>;
20513   }
20514   @<Make the bounding box of |h| unknown if it can't be updated properly
20515     without scanning the whole structure@>;  
20516   q=link(dummy_loc(h));
20517   while ( q!=null ) { 
20518     @<Transform graphical object |q|@>;
20519     q=link(q);
20520   }
20521   return h;
20522 }
20523 void mp_do_edges_trans (MP mp,pointer p, quarterword c) { 
20524   mp_set_up_known_trans(mp, c);
20525   value(p)=mp_edges_trans(mp, value(p));
20526   mp_unstash_cur_exp(mp, p);
20527 }
20528 void mp_scale_edges (MP mp) { 
20529   mp->txx=mp->se_sf; mp->tyy=mp->se_sf;
20530   mp->txy=0; mp->tyx=0; mp->tx=0; mp->ty=0;
20531   mp->se_pic=mp_edges_trans(mp, mp->se_pic);
20532 }
20533
20534 @ @<Try to transform the dash list of |h|@>=
20535 if ( (mp->txy!=0)||(mp->tyx!=0)||
20536      (mp->ty!=0)||(abs(mp->txx)!=abs(mp->tyy))) {
20537   mp_flush_dash_list(mp, h);
20538 } else { 
20539   if ( mp->txx<0 ) { @<Reverse the dash list of |h|@>; } 
20540   @<Scale the dash list by |txx| and shift it by |tx|@>;
20541   dash_y(h)=mp_take_scaled(mp, dash_y(h),abs(mp->tyy));
20542 }
20543
20544 @ @<Reverse the dash list of |h|@>=
20545
20546   r=dash_list(h);
20547   dash_list(h)=null_dash;
20548   while ( r!=null_dash ) {
20549     s=r; r=link(r);
20550     v=start_x(s); start_x(s)=stop_x(s); stop_x(s)=v;
20551     link(s)=dash_list(h);
20552     dash_list(h)=s;
20553   }
20554 }
20555
20556 @ @<Scale the dash list by |txx| and shift it by |tx|@>=
20557 r=dash_list(h);
20558 while ( r!=null_dash ) {
20559   start_x(r)=mp_take_scaled(mp, start_x(r),mp->txx)+mp->tx;
20560   stop_x(r)=mp_take_scaled(mp, stop_x(r),mp->txx)+mp->tx;
20561   r=link(r);
20562 }
20563
20564 @ @<Make the bounding box of |h| unknown if it can't be updated properly...@>=
20565 if ( (mp->txx==0)&&(mp->tyy==0) ) {
20566   @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>;
20567 } else if ( (mp->txy!=0)||(mp->tyx!=0) ) {
20568   mp_init_bbox(mp, h);
20569   goto DONE1;
20570 }
20571 if ( minx_val(h)<=maxx_val(h) ) {
20572   @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift by
20573    |(tx,ty)|@>;
20574 }
20575 DONE1:
20576
20577
20578
20579 @ @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>=
20580
20581   v=minx_val(h); minx_val(h)=miny_val(h); miny_val(h)=v;
20582   v=maxx_val(h); maxx_val(h)=maxy_val(h); maxy_val(h)=v;
20583 }
20584
20585 @ The sum ``|txx+txy|'' is whichever of |txx| or |txy| is nonzero.  The other
20586 sum is similar.
20587
20588 @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift...@>=
20589
20590   minx_val(h)=mp_take_scaled(mp, minx_val(h),mp->txx+mp->txy)+mp->tx;
20591   maxx_val(h)=mp_take_scaled(mp, maxx_val(h),mp->txx+mp->txy)+mp->tx;
20592   miny_val(h)=mp_take_scaled(mp, miny_val(h),mp->tyx+mp->tyy)+mp->ty;
20593   maxy_val(h)=mp_take_scaled(mp, maxy_val(h),mp->tyx+mp->tyy)+mp->ty;
20594   if ( mp->txx+mp->txy<0 ) {
20595     v=minx_val(h); minx_val(h)=maxx_val(h); maxx_val(h)=v;
20596   }
20597   if ( mp->tyx+mp->tyy<0 ) {
20598     v=miny_val(h); miny_val(h)=maxy_val(h); maxy_val(h)=v;
20599   }
20600 }
20601
20602 @ Now we ready for the main task of transforming the graphical objects in edge
20603 structure~|h|.
20604
20605 @<Transform graphical object |q|@>=
20606 switch (type(q)) {
20607 case mp_fill_code: case mp_stroked_code: 
20608   mp_do_path_trans(mp, path_p(q));
20609   @<Transform |pen_p(q)|, making sure polygonal pens stay counter-clockwise@>;
20610   break;
20611 case mp_start_clip_code: case mp_start_bounds_code: 
20612   mp_do_path_trans(mp, path_p(q));
20613   break;
20614 case mp_text_code: 
20615   r=text_tx_loc(q);
20616   @<Transform the compact transformation starting at |r|@>;
20617   break;
20618 case mp_stop_clip_code: case mp_stop_bounds_code: 
20619   break;
20620 } /* there are no other cases */
20621
20622 @ Note that the shift parameters |(tx,ty)| apply only to the path being stroked.
20623 The |dash_scale| has to be adjusted  to scale the dash lengths in |dash_p(q)|
20624 since the \ps\ output procedures will try to compensate for the transformation
20625 we are applying to |pen_p(q)|.  Since this compensation is based on the square
20626 root of the determinant, |sqdet| is the appropriate factor.
20627
20628 @<Transform |pen_p(q)|, making sure...@>=
20629 if ( pen_p(q)!=null ) {
20630   sx=mp->tx; sy=mp->ty;
20631   mp->tx=0; mp->ty=0;
20632   mp_do_pen_trans(mp, pen_p(q));
20633   if ( ((type(q)==mp_stroked_code)&&(dash_p(q)!=null)) )
20634     dash_scale(q)=mp_take_scaled(mp, dash_scale(q),sqdet);
20635   if ( ! pen_is_elliptical(pen_p(q)) )
20636     if ( sgndet<0 )
20637       pen_p(q)=mp_make_pen(mp, mp_copy_path(mp, pen_p(q)),true); 
20638          /* this unreverses the pen */
20639   mp->tx=sx; mp->ty=sy;
20640 }
20641
20642 @ This uses the fact that transformations are stored in the order
20643 |(tx,ty,txx,txy,tyx,tyy)|.
20644 @^data structure assumptions@>
20645
20646 @<Transform the compact transformation starting at |r|@>=
20647 mp_trans(mp, r,r+1);
20648 sx=mp->tx; sy=mp->ty;
20649 mp->tx=0; mp->ty=0;
20650 mp_trans(mp, r+2,r+4);
20651 mp_trans(mp, r+3,r+5);
20652 mp->tx=sx; mp->ty=sy
20653
20654 @ The hard cases of transformation occur when big nodes are involved,
20655 and when some of their components are unknown.
20656
20657 @<Declare binary action...@>=
20658 @<Declare subroutines needed by |big_trans|@>;
20659 void mp_big_trans (MP mp,pointer p, quarterword c) {
20660   pointer q,r,pp,qq; /* list manipulation registers */
20661   small_number s; /* size of a big node */
20662   s=mp->big_node_size[type(p)]; q=value(p); r=q+s;
20663   do {  
20664     r=r-2;
20665     if ( type(r)!=mp_known ) {
20666       @<Transform an unknown big node and |return|@>;
20667     }
20668   } while (r!=q);
20669   @<Transform a known big node@>;
20670 }; /* node |p| will now be recycled by |do_binary| */
20671
20672 @ @<Transform an unknown big node and |return|@>=
20673
20674   mp_set_up_known_trans(mp, c); mp_make_exp_copy(mp, p); 
20675   r=value(mp->cur_exp);
20676   if ( mp->cur_type==mp_transform_type ) {
20677     mp_bilin1(mp, yy_part_loc(r),mp->tyy,xy_part_loc(q),mp->tyx,0);
20678     mp_bilin1(mp, yx_part_loc(r),mp->tyy,xx_part_loc(q),mp->tyx,0);
20679     mp_bilin1(mp, xy_part_loc(r),mp->txx,yy_part_loc(q),mp->txy,0);
20680     mp_bilin1(mp, xx_part_loc(r),mp->txx,yx_part_loc(q),mp->txy,0);
20681   }
20682   mp_bilin1(mp, y_part_loc(r),mp->tyy,x_part_loc(q),mp->tyx,mp->ty);
20683   mp_bilin1(mp, x_part_loc(r),mp->txx,y_part_loc(q),mp->txy,mp->tx);
20684   return;
20685 }
20686
20687 @ Let |p| point to a two-word value field inside a big node of |cur_exp|,
20688 and let |q| point to a another value field. The |bilin1| procedure
20689 replaces |p| by $p\cdot t+q\cdot u+\delta$.
20690
20691 @<Declare subroutines needed by |big_trans|@>=
20692 void mp_bilin1 (MP mp, pointer p, scaled t, pointer q, 
20693                 scaled u, scaled delta) {
20694   pointer r; /* list traverser */
20695   if ( t!=unity ) mp_dep_mult(mp, p,t,true);
20696   if ( u!=0 ) {
20697     if ( type(q)==mp_known ) {
20698       delta+=mp_take_scaled(mp, value(q),u);
20699     } else { 
20700       @<Ensure that |type(p)=mp_proto_dependent|@>;
20701       dep_list(p)=mp_p_plus_fq(mp, dep_list(p),u,dep_list(q),
20702                                mp_proto_dependent,type(q));
20703     }
20704   }
20705   if ( type(p)==mp_known ) {
20706     value(p)+=delta;
20707   } else {
20708     r=dep_list(p);
20709     while ( info(r)!=null ) r=link(r);
20710     delta+=value(r);
20711     if ( r!=dep_list(p) ) value(r)=delta;
20712     else { mp_recycle_value(mp, p); type(p)=mp_known; value(p)=delta; };
20713   }
20714   if ( mp->fix_needed ) mp_fix_dependencies(mp);
20715 }
20716
20717 @ @<Ensure that |type(p)=mp_proto_dependent|@>=
20718 if ( type(p)!=mp_proto_dependent ) {
20719   if ( type(p)==mp_known ) 
20720     mp_new_dep(mp, p,mp_const_dependency(mp, value(p)));
20721   else 
20722     dep_list(p)=mp_p_times_v(mp, dep_list(p),unity,mp_dependent,
20723                              mp_proto_dependent,true);
20724   type(p)=mp_proto_dependent;
20725 }
20726
20727 @ @<Transform a known big node@>=
20728 mp_set_up_trans(mp, c);
20729 if ( mp->cur_type==mp_known ) {
20730   @<Transform known by known@>;
20731 } else { 
20732   pp=mp_stash_cur_exp(mp); qq=value(pp);
20733   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20734   if ( mp->cur_type==mp_transform_type ) {
20735     mp_bilin2(mp, yy_part_loc(r),yy_part_loc(qq),
20736       value(xy_part_loc(q)),yx_part_loc(qq),null);
20737     mp_bilin2(mp, yx_part_loc(r),yy_part_loc(qq),
20738       value(xx_part_loc(q)),yx_part_loc(qq),null);
20739     mp_bilin2(mp, xy_part_loc(r),xx_part_loc(qq),
20740       value(yy_part_loc(q)),xy_part_loc(qq),null);
20741     mp_bilin2(mp, xx_part_loc(r),xx_part_loc(qq),
20742       value(yx_part_loc(q)),xy_part_loc(qq),null);
20743   };
20744   mp_bilin2(mp, y_part_loc(r),yy_part_loc(qq),
20745     value(x_part_loc(q)),yx_part_loc(qq),y_part_loc(qq));
20746   mp_bilin2(mp, x_part_loc(r),xx_part_loc(qq),
20747     value(y_part_loc(q)),xy_part_loc(qq),x_part_loc(qq));
20748   mp_recycle_value(mp, pp); mp_free_node(mp, pp,value_node_size);
20749 }
20750
20751 @ Let |p| be a |mp_proto_dependent| value whose dependency list ends
20752 at |dep_final|. The following procedure adds |v| times another
20753 numeric quantity to~|p|.
20754
20755 @<Declare subroutines needed by |big_trans|@>=
20756 void mp_add_mult_dep (MP mp,pointer p, scaled v, pointer r) { 
20757   if ( type(r)==mp_known ) {
20758     value(mp->dep_final)+=mp_take_scaled(mp, value(r),v);
20759   } else  { 
20760     dep_list(p)=mp_p_plus_fq(mp, dep_list(p),v,dep_list(r),
20761                                                          mp_proto_dependent,type(r));
20762     if ( mp->fix_needed ) mp_fix_dependencies(mp);
20763   }
20764 }
20765
20766 @ The |bilin2| procedure is something like |bilin1|, but with known
20767 and unknown quantities reversed. Parameter |p| points to a value field
20768 within the big node for |cur_exp|; and |type(p)=mp_known|. Parameters
20769 |t| and~|u| point to value fields elsewhere; so does parameter~|q|,
20770 unless it is |null| (which stands for zero). Location~|p| will be
20771 replaced by $p\cdot t+v\cdot u+q$.
20772
20773 @<Declare subroutines needed by |big_trans|@>=
20774 void mp_bilin2 (MP mp,pointer p, pointer t, scaled v, 
20775                 pointer u, pointer q) {
20776   scaled vv; /* temporary storage for |value(p)| */
20777   vv=value(p); type(p)=mp_proto_dependent;
20778   mp_new_dep(mp, p,mp_const_dependency(mp, 0)); /* this sets |dep_final| */
20779   if ( vv!=0 ) 
20780     mp_add_mult_dep(mp, p,vv,t); /* |dep_final| doesn't change */
20781   if ( v!=0 ) mp_add_mult_dep(mp, p,v,u);
20782   if ( q!=null ) mp_add_mult_dep(mp, p,unity,q);
20783   if ( dep_list(p)==mp->dep_final ) {
20784     vv=value(mp->dep_final); mp_recycle_value(mp, p);
20785     type(p)=mp_known; value(p)=vv;
20786   }
20787 }
20788
20789 @ @<Transform known by known@>=
20790
20791   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20792   if ( mp->cur_type==mp_transform_type ) {
20793     mp_bilin3(mp, yy_part_loc(r),mp->tyy,value(xy_part_loc(q)),mp->tyx,0);
20794     mp_bilin3(mp, yx_part_loc(r),mp->tyy,value(xx_part_loc(q)),mp->tyx,0);
20795     mp_bilin3(mp, xy_part_loc(r),mp->txx,value(yy_part_loc(q)),mp->txy,0);
20796     mp_bilin3(mp, xx_part_loc(r),mp->txx,value(yx_part_loc(q)),mp->txy,0);
20797   }
20798   mp_bilin3(mp, y_part_loc(r),mp->tyy,value(x_part_loc(q)),mp->tyx,mp->ty);
20799   mp_bilin3(mp, x_part_loc(r),mp->txx,value(y_part_loc(q)),mp->txy,mp->tx);
20800 }
20801
20802 @ Finally, in |bilin3| everything is |known|.
20803
20804 @<Declare subroutines needed by |big_trans|@>=
20805 void mp_bilin3 (MP mp,pointer p, scaled t, 
20806                scaled v, scaled u, scaled delta) { 
20807   if ( t!=unity )
20808     delta+=mp_take_scaled(mp, value(p),t);
20809   else 
20810     delta+=value(p);
20811   if ( u!=0 ) value(p)=delta+mp_take_scaled(mp, v,u);
20812   else value(p)=delta;
20813 }
20814
20815 @ @<Additional cases of binary operators@>=
20816 case concatenate: 
20817   if ( (mp->cur_type==mp_string_type)&&(type(p)==mp_string_type) ) mp_cat(mp, p);
20818   else mp_bad_binary(mp, p,concatenate);
20819   break;
20820 case substring_of: 
20821   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_string_type) )
20822     mp_chop_string(mp, value(p));
20823   else mp_bad_binary(mp, p,substring_of);
20824   break;
20825 case subpath_of: 
20826   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
20827   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_path_type) )
20828     mp_chop_path(mp, value(p));
20829   else mp_bad_binary(mp, p,subpath_of);
20830   break;
20831
20832 @ @<Declare binary action...@>=
20833 void mp_cat (MP mp,pointer p) {
20834   str_number a,b; /* the strings being concatenated */
20835   pool_pointer k; /* index into |str_pool| */
20836   a=value(p); b=mp->cur_exp; str_room(length(a)+length(b));
20837   for (k=mp->str_start[a];k<=str_stop(a)-1;k++) {
20838     append_char(mp->str_pool[k]);
20839   }
20840   for (k=mp->str_start[b];k<=str_stop(b)-1;k++) {
20841     append_char(mp->str_pool[k]);
20842   }
20843   mp->cur_exp=mp_make_string(mp); delete_str_ref(b);
20844 }
20845
20846 @ @<Declare binary action...@>=
20847 void mp_chop_string (MP mp,pointer p) {
20848   integer a, b; /* start and stop points */
20849   integer l; /* length of the original string */
20850   integer k; /* runs from |a| to |b| */
20851   str_number s; /* the original string */
20852   boolean reversed; /* was |a>b|? */
20853   a=mp_round_unscaled(mp, value(x_part_loc(p)));
20854   b=mp_round_unscaled(mp, value(y_part_loc(p)));
20855   if ( a<=b ) reversed=false;
20856   else  { reversed=true; k=a; a=b; b=k; };
20857   s=mp->cur_exp; l=length(s);
20858   if ( a<0 ) { 
20859     a=0;
20860     if ( b<0 ) b=0;
20861   }
20862   if ( b>l ) { 
20863     b=l;
20864     if ( a>l ) a=l;
20865   }
20866   str_room(b-a);
20867   if ( reversed ) {
20868     for (k=mp->str_start[s]+b-1;k>=mp->str_start[s]+a;k--)  {
20869       append_char(mp->str_pool[k]);
20870     }
20871   } else  {
20872     for (k=mp->str_start[s]+a;k<=mp->str_start[s]+b-1;k++)  {
20873       append_char(mp->str_pool[k]);
20874     }
20875   }
20876   mp->cur_exp=mp_make_string(mp); delete_str_ref(s);
20877 }
20878
20879 @ @<Declare binary action...@>=
20880 void mp_chop_path (MP mp,pointer p) {
20881   pointer q; /* a knot in the original path */
20882   pointer pp,qq,rr,ss; /* link variables for copies of path nodes */
20883   scaled a,b,k,l; /* indices for chopping */
20884   boolean reversed; /* was |a>b|? */
20885   l=mp_path_length(mp); a=value(x_part_loc(p)); b=value(y_part_loc(p));
20886   if ( a<=b ) reversed=false;
20887   else  { reversed=true; k=a; a=b; b=k; };
20888   @<Dispense with the cases |a<0| and/or |b>l|@>;
20889   q=mp->cur_exp;
20890   while ( a>=unity ) {
20891     q=link(q); a=a-unity; b=b-unity;
20892   }
20893   if ( b==a ) {
20894     @<Construct a path from |pp| to |qq| of length zero@>; 
20895   } else { 
20896     @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>; 
20897   }
20898   left_type(pp)=mp_endpoint; right_type(qq)=mp_endpoint; link(qq)=pp;
20899   mp_toss_knot_list(mp, mp->cur_exp);
20900   if ( reversed ) {
20901     mp->cur_exp=link(mp_htap_ypoc(mp, pp)); mp_toss_knot_list(mp, pp);
20902   } else {
20903     mp->cur_exp=pp;
20904   }
20905 }
20906
20907 @ @<Dispense with the cases |a<0| and/or |b>l|@>=
20908 if ( a<0 ) {
20909   if ( left_type(mp->cur_exp)==mp_endpoint ) {
20910     a=0; if ( b<0 ) b=0;
20911   } else  {
20912     do {  a=a+l; b=b+l; } while (a<0); /* a cycle always has length |l>0| */
20913   }
20914 }
20915 if ( b>l ) {
20916   if ( left_type(mp->cur_exp)==mp_endpoint ) {
20917     b=l; if ( a>l ) a=l;
20918   } else {
20919     while ( a>=l ) { 
20920       a=a-l; b=b-l;
20921     }
20922   }
20923 }
20924
20925 @ @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>=
20926
20927   pp=mp_copy_knot(mp, q); qq=pp;
20928   do {  
20929     q=link(q); rr=qq; qq=mp_copy_knot(mp, q); link(rr)=qq; b=b-unity;
20930   } while (b>0);
20931   if ( a>0 ) {
20932     ss=pp; pp=link(pp);
20933     mp_split_cubic(mp, ss,a*010000); pp=link(ss);
20934     mp_free_node(mp, ss,knot_node_size);
20935     if ( rr==ss ) {
20936       b=mp_make_scaled(mp, b,unity-a); rr=pp;
20937     }
20938   }
20939   if ( b<0 ) {
20940     mp_split_cubic(mp, rr,(b+unity)*010000);
20941     mp_free_node(mp, qq,knot_node_size);
20942     qq=link(rr);
20943   }
20944 }
20945
20946 @ @<Construct a path from |pp| to |qq| of length zero@>=
20947
20948   if ( a>0 ) { mp_split_cubic(mp, q,a*010000); q=link(q); };
20949   pp=mp_copy_knot(mp, q); qq=pp;
20950 }
20951
20952 @ @<Additional cases of binary operators@>=
20953 case point_of: case precontrol_of: case postcontrol_of: 
20954   if ( mp->cur_type==mp_pair_type )
20955      mp_pair_to_path(mp);
20956   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
20957     mp_find_point(mp, value(p),c);
20958   else 
20959     mp_bad_binary(mp, p,c);
20960   break;
20961 case pen_offset_of: 
20962   if ( (mp->cur_type==mp_pen_type)&& mp_nice_pair(mp, p,type(p)) )
20963     mp_set_up_offset(mp, value(p));
20964   else 
20965     mp_bad_binary(mp, p,pen_offset_of);
20966   break;
20967 case direction_time_of: 
20968   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
20969   if ( (mp->cur_type==mp_path_type)&& mp_nice_pair(mp, p,type(p)) )
20970     mp_set_up_direction_time(mp, value(p));
20971   else 
20972     mp_bad_binary(mp, p,direction_time_of);
20973   break;
20974
20975 @ @<Declare binary action...@>=
20976 void mp_set_up_offset (MP mp,pointer p) { 
20977   mp_find_offset(mp, value(x_part_loc(p)),value(y_part_loc(p)),mp->cur_exp);
20978   mp_pair_value(mp, mp->cur_x,mp->cur_y);
20979 }
20980 void mp_set_up_direction_time (MP mp,pointer p) { 
20981   mp_flush_cur_exp(mp, mp_find_direction_time(mp, value(x_part_loc(p)),
20982   value(y_part_loc(p)),mp->cur_exp));
20983 }
20984
20985 @ @<Declare binary action...@>=
20986 void mp_find_point (MP mp,scaled v, quarterword c) {
20987   pointer p; /* the path */
20988   scaled n; /* its length */
20989   p=mp->cur_exp;
20990   if ( left_type(p)==mp_endpoint ) n=-unity; else n=0;
20991   do {  p=link(p); n=n+unity; } while (p!=mp->cur_exp);
20992   if ( n==0 ) { 
20993     v=0; 
20994   } else if ( v<0 ) {
20995     if ( left_type(p)==mp_endpoint ) v=0;
20996     else v=n-1-((-v-1) % n);
20997   } else if ( v>n ) {
20998     if ( left_type(p)==mp_endpoint ) v=n;
20999     else v=v % n;
21000   }
21001   p=mp->cur_exp;
21002   while ( v>=unity ) { p=link(p); v=v-unity;  };
21003   if ( v!=0 ) {
21004      @<Insert a fractional node by splitting the cubic@>;
21005   }
21006   @<Set the current expression to the desired path coordinates@>;
21007 }
21008
21009 @ @<Insert a fractional node...@>=
21010 { mp_split_cubic(mp, p,v*010000); p=link(p); }
21011
21012 @ @<Set the current expression to the desired path coordinates...@>=
21013 switch (c) {
21014 case point_of: 
21015   mp_pair_value(mp, x_coord(p),y_coord(p));
21016   break;
21017 case precontrol_of: 
21018   if ( left_type(p)==mp_endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
21019   else mp_pair_value(mp, left_x(p),left_y(p));
21020   break;
21021 case postcontrol_of: 
21022   if ( right_type(p)==mp_endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
21023   else mp_pair_value(mp, right_x(p),right_y(p));
21024   break;
21025 } /* there are no other cases */
21026
21027 @ @<Additional cases of binary operators@>=
21028 case arc_time_of: 
21029   if ( mp->cur_type==mp_pair_type )
21030      mp_pair_to_path(mp);
21031   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
21032     mp_flush_cur_exp(mp, mp_get_arc_time(mp, mp->cur_exp,value(p)));
21033   else 
21034     mp_bad_binary(mp, p,c);
21035   break;
21036
21037 @ @<Additional cases of bin...@>=
21038 case intersect: 
21039   if ( type(p)==mp_pair_type ) {
21040     q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p);
21041     mp_pair_to_path(mp); p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
21042   };
21043   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21044   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_path_type) ) {
21045     mp_path_intersection(mp, value(p),mp->cur_exp);
21046     mp_pair_value(mp, mp->cur_t,mp->cur_tt);
21047   } else {
21048     mp_bad_binary(mp, p,intersect);
21049   }
21050   break;
21051
21052 @ @<Additional cases of bin...@>=
21053 case in_font:
21054   if ( (mp->cur_type!=mp_string_type)||(type(p)!=mp_string_type)) 
21055     mp_bad_binary(mp, p,in_font);
21056   else { mp_do_infont(mp, p); return; }
21057   break;
21058
21059 @ Function |new_text_node| owns the reference count for its second argument
21060 (the text string) but not its first (the font name).
21061
21062 @<Declare binary action...@>=
21063 void mp_do_infont (MP mp,pointer p) {
21064   pointer q;
21065   q=mp_get_node(mp, edge_header_size);
21066   mp_init_edges(mp, q);
21067   link(obj_tail(q))=mp_new_text_node(mp, str(mp->cur_exp),value(p));
21068   obj_tail(q)=link(obj_tail(q));
21069   mp_free_node(mp, p,value_node_size);
21070   mp_flush_cur_exp(mp, q);
21071   mp->cur_type=mp_picture_type;
21072 }
21073
21074 @* \[40] Statements and commands.
21075 The chief executive of \MP\ is the |do_statement| routine, which
21076 contains the master switch that causes all the various pieces of \MP\
21077 to do their things, in the right order.
21078
21079 In a sense, this is the grand climax of the program: It applies all the
21080 tools that we have worked so hard to construct. In another sense, this is
21081 the messiest part of the program: It necessarily refers to other pieces
21082 of code all over the place, so that a person can't fully understand what is
21083 going on without paging back and forth to be reminded of conventions that
21084 are defined elsewhere. We are now at the hub of the web.
21085
21086 The structure of |do_statement| itself is quite simple.  The first token
21087 of the statement is fetched using |get_x_next|.  If it can be the first
21088 token of an expression, we look for an equation, an assignment, or a
21089 title. Otherwise we use a \&{case} construction to branch at high speed to
21090 the appropriate routine for various and sundry other types of commands,
21091 each of which has an ``action procedure'' that does the necessary work.
21092
21093 The program uses the fact that
21094 $$\hbox{|min_primary_command=max_statement_command=type_name|}$$
21095 to interpret a statement that starts with, e.g., `\&{string}',
21096 as a type declaration rather than a boolean expression.
21097
21098 @c void mp_do_statement (MP mp) { /* governs \MP's activities */
21099   mp->cur_type=mp_vacuous; mp_get_x_next(mp);
21100   if ( mp->cur_cmd>max_primary_command ) {
21101     @<Worry about bad statement@>;
21102   } else if ( mp->cur_cmd>max_statement_command ) {
21103     @<Do an equation, assignment, title, or
21104      `$\langle\,$expression$\,\rangle\,$\&{endgroup}'@>;
21105   } else {
21106     @<Do a statement that doesn't begin with an expression@>;
21107   }
21108   if ( mp->cur_cmd<semicolon )
21109     @<Flush unparsable junk that was found after the statement@>;
21110   mp->error_count=0;
21111 }
21112
21113 @ @<Declarations@>=
21114 @<Declare action procedures for use by |do_statement|@>;
21115
21116 @ The only command codes |>max_primary_command| that can be present
21117 at the beginning of a statement are |semicolon| and higher; these
21118 occur when the statement is null.
21119
21120 @<Worry about bad statement@>=
21121
21122   if ( mp->cur_cmd<semicolon ) {
21123     print_err("A statement can't begin with `");
21124 @.A statement can't begin with x@>
21125     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); mp_print_char(mp, '\'');
21126     help5("I was looking for the beginning of a new statement.")
21127       ("If you just proceed without changing anything, I'll ignore")
21128       ("everything up to the next `;'. Please insert a semicolon")
21129       ("now in front of anything that you don't want me to delete.")
21130       ("(See Chapter 27 of The METAFONTbook for an example.)");
21131 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21132     mp_back_error(mp); mp_get_x_next(mp);
21133   }
21134 }
21135
21136 @ The help message printed here says that everything is flushed up to
21137 a semicolon, but actually the commands |end_group| and |stop| will
21138 also terminate a statement.
21139
21140 @<Flush unparsable junk that was found after the statement@>=
21141
21142   print_err("Extra tokens will be flushed");
21143 @.Extra tokens will be flushed@>
21144   help6("I've just read as much of that statement as I could fathom,")
21145        ("so a semicolon should have been next. It's very puzzling...")
21146        ("but I'll try to get myself back together, by ignoring")
21147        ("everything up to the next `;'. Please insert a semicolon")
21148        ("now in front of anything that you don't want me to delete.")
21149        ("(See Chapter 27 of The METAFONTbook for an example.)");
21150 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21151   mp_back_error(mp); mp->scanner_status=flushing;
21152   do {  
21153     get_t_next;
21154     @<Decrease the string reference count...@>;
21155   } while (! end_of_statement); /* |cur_cmd=semicolon|, |end_group|, or |stop| */
21156   mp->scanner_status=normal;
21157 }
21158
21159 @ If |do_statement| ends with |cur_cmd=end_group|, we should have
21160 |cur_type=mp_vacuous| unless the statement was simply an expression;
21161 in the latter case, |cur_type| and |cur_exp| should represent that
21162 expression.
21163
21164 @<Do a statement that doesn't...@>=
21165
21166   if ( mp->internal[mp_tracing_commands]>0 ) 
21167     show_cur_cmd_mod;
21168   switch (mp->cur_cmd ) {
21169   case type_name:mp_do_type_declaration(mp); break;
21170   case macro_def:
21171     if ( mp->cur_mod>var_def ) mp_make_op_def(mp);
21172     else if ( mp->cur_mod>end_def ) mp_scan_def(mp);
21173      break;
21174   @<Cases of |do_statement| that invoke particular commands@>;
21175   } /* there are no other cases */
21176   mp->cur_type=mp_vacuous;
21177 }
21178
21179 @ The most important statements begin with expressions.
21180
21181 @<Do an equation, assignment, title, or...@>=
21182
21183   mp->var_flag=assignment; mp_scan_expression(mp);
21184   if ( mp->cur_cmd<end_group ) {
21185     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21186     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21187     else if ( mp->cur_type==mp_string_type ) {@<Do a title@> ; }
21188     else if ( mp->cur_type!=mp_vacuous ){ 
21189       exp_err("Isolated expression");
21190 @.Isolated expression@>
21191       help3("I couldn't find an `=' or `:=' after the")
21192         ("expression that is shown above this error message,")
21193         ("so I guess I'll just ignore it and carry on.");
21194       mp_put_get_error(mp);
21195     }
21196     mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous;
21197   }
21198 }
21199
21200 @ @<Do a title@>=
21201
21202   if ( mp->internal[mp_tracing_titles]>0 ) {
21203     mp_print_nl(mp, "");  mp_print_str(mp, mp->cur_exp); update_terminal;
21204   }
21205 }
21206
21207 @ Equations and assignments are performed by the pair of mutually recursive
21208 @^recursion@>
21209 routines |do_equation| and |do_assignment|. These routines are called when
21210 |cur_cmd=equals| and when |cur_cmd=assignment|, respectively; the left-hand
21211 side is in |cur_type| and |cur_exp|, while the right-hand side is yet
21212 to be scanned. After the routines are finished, |cur_type| and |cur_exp|
21213 will be equal to the right-hand side (which will normally be equal
21214 to the left-hand side).
21215
21216 @<Declare action procedures for use by |do_statement|@>=
21217 @<Declare the procedure called |try_eq|@>;
21218 @<Declare the procedure called |make_eq|@>;
21219 void mp_do_equation (MP mp) ;
21220
21221 @ @c
21222 void mp_do_equation (MP mp) {
21223   pointer lhs; /* capsule for the left-hand side */
21224   pointer p; /* temporary register */
21225   lhs=mp_stash_cur_exp(mp); mp_get_x_next(mp); 
21226   mp->var_flag=assignment; mp_scan_expression(mp);
21227   if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21228   else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21229   if ( mp->internal[mp_tracing_commands]>two ) 
21230     @<Trace the current equation@>;
21231   if ( mp->cur_type==mp_unknown_path ) if ( type(lhs)==mp_pair_type ) {
21232     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, lhs); lhs=p;
21233   }; /* in this case |make_eq| will change the pair to a path */
21234   mp_make_eq(mp, lhs); /* equate |lhs| to |(cur_type,cur_exp)| */
21235 }
21236
21237 @ And |do_assignment| is similar to |do_expression|:
21238
21239 @<Declarations@>=
21240 void mp_do_assignment (MP mp);
21241
21242 @ @<Declare action procedures for use by |do_statement|@>=
21243 void mp_do_assignment (MP mp) ;
21244
21245 @ @c
21246 void mp_do_assignment (MP mp) {
21247   pointer lhs; /* token list for the left-hand side */
21248   pointer p; /* where the left-hand value is stored */
21249   pointer q; /* temporary capsule for the right-hand value */
21250   if ( mp->cur_type!=mp_token_list ) { 
21251     exp_err("Improper `:=' will be changed to `='");
21252 @.Improper `:='@>
21253     help2("I didn't find a variable name at the left of the `:=',")
21254       ("so I'm going to pretend that you said `=' instead.");
21255     mp_error(mp); mp_do_equation(mp);
21256   } else { 
21257     lhs=mp->cur_exp; mp->cur_type=mp_vacuous;
21258     mp_get_x_next(mp); mp->var_flag=assignment; mp_scan_expression(mp);
21259     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21260     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21261     if ( mp->internal[mp_tracing_commands]>two ) 
21262       @<Trace the current assignment@>;
21263     if ( info(lhs)>hash_end ) {
21264       @<Assign the current expression to an internal variable@>;
21265     } else  {
21266       @<Assign the current expression to the variable |lhs|@>;
21267     }
21268     mp_flush_node_list(mp, lhs);
21269   }
21270 }
21271
21272 @ @<Trace the current equation@>=
21273
21274   mp_begin_diagnostic(mp); mp_print_nl(mp, "{("); mp_print_exp(mp,lhs,0);
21275   mp_print(mp,")=("); mp_print_exp(mp,null,0); 
21276   mp_print(mp,")}"); mp_end_diagnostic(mp, false);
21277 }
21278
21279 @ @<Trace the current assignment@>=
21280
21281   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
21282   if ( info(lhs)>hash_end ) 
21283      mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21284   else 
21285      mp_show_token_list(mp, lhs,null,1000,0);
21286   mp_print(mp, ":="); mp_print_exp(mp, null,0); 
21287   mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
21288 }
21289
21290 @ @<Assign the current expression to an internal variable@>=
21291 if ( mp->cur_type==mp_known )  {
21292   mp->internal[info(lhs)-(hash_end)]=mp->cur_exp;
21293 } else { 
21294   exp_err("Internal quantity `");
21295 @.Internal quantity...@>
21296   mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21297   mp_print(mp, "' must receive a known value");
21298   help2("I can\'t set an internal quantity to anything but a known")
21299     ("numeric value, so I'll have to ignore this assignment.");
21300   mp_put_get_error(mp);
21301 }
21302
21303 @ @<Assign the current expression to the variable |lhs|@>=
21304
21305   p=mp_find_variable(mp, lhs);
21306   if ( p!=null ) {
21307     q=mp_stash_cur_exp(mp); mp->cur_type=mp_und_type(mp, p); 
21308     mp_recycle_value(mp, p);
21309     type(p)=mp->cur_type; value(p)=null; mp_make_exp_copy(mp, p);
21310     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q); mp_make_eq(mp, p);
21311   } else  { 
21312     mp_obliterated(mp, lhs); mp_put_get_error(mp);
21313   }
21314 }
21315
21316
21317 @ And now we get to the nitty-gritty. The |make_eq| procedure is given
21318 a pointer to a capsule that is to be equated to the current expression.
21319
21320 @<Declare the procedure called |make_eq|@>=
21321 void mp_make_eq (MP mp,pointer lhs) ;
21322
21323
21324
21325 @c void mp_make_eq (MP mp,pointer lhs) {
21326   small_number t; /* type of the left-hand side */
21327   pointer p,q; /* pointers inside of big nodes */
21328   integer v=0; /* value of the left-hand side */
21329 RESTART: 
21330   t=type(lhs);
21331   if ( t<=mp_pair_type ) v=value(lhs);
21332   switch (t) {
21333   @<For each type |t|, make an equation and |goto done| unless |cur_type|
21334     is incompatible with~|t|@>;
21335   } /* all cases have been listed */
21336   @<Announce that the equation cannot be performed@>;
21337 DONE:
21338   check_arith; mp_recycle_value(mp, lhs); 
21339   mp_free_node(mp, lhs,value_node_size);
21340 }
21341
21342 @ @<Announce that the equation cannot be performed@>=
21343 mp_disp_err(mp, lhs,""); 
21344 exp_err("Equation cannot be performed (");
21345 @.Equation cannot be performed@>
21346 if ( type(lhs)<=mp_pair_type ) mp_print_type(mp, type(lhs));
21347 else mp_print(mp, "numeric");
21348 mp_print_char(mp, '=');
21349 if ( mp->cur_type<=mp_pair_type ) mp_print_type(mp, mp->cur_type);
21350 else mp_print(mp, "numeric");
21351 mp_print_char(mp, ')');
21352 help2("I'm sorry, but I don't know how to make such things equal.")
21353      ("(See the two expressions just above the error message.)");
21354 mp_put_get_error(mp)
21355
21356 @ @<For each type |t|, make an equation and |goto done| unless...@>=
21357 case mp_boolean_type: case mp_string_type: case mp_pen_type:
21358 case mp_path_type: case mp_picture_type:
21359   if ( mp->cur_type==t+unknown_tag ) { 
21360     mp_nonlinear_eq(mp, v,mp->cur_exp,false); goto DONE;
21361   } else if ( mp->cur_type==t ) {
21362     @<Report redundant or inconsistent equation and |goto done|@>;
21363   }
21364   break;
21365 case unknown_types:
21366   if ( mp->cur_type==t-unknown_tag ) { 
21367     mp_nonlinear_eq(mp, mp->cur_exp,lhs,true); goto DONE;
21368   } else if ( mp->cur_type==t ) { 
21369     mp_ring_merge(mp, lhs,mp->cur_exp); goto DONE;
21370   } else if ( mp->cur_type==mp_pair_type ) {
21371     if ( t==mp_unknown_path ) { 
21372      mp_pair_to_path(mp); goto RESTART;
21373     };
21374   }
21375   break;
21376 case mp_transform_type: case mp_color_type:
21377 case mp_cmykcolor_type: case mp_pair_type:
21378   if ( mp->cur_type==t ) {
21379     @<Do multiple equations and |goto done|@>;
21380   }
21381   break;
21382 case mp_known: case mp_dependent:
21383 case mp_proto_dependent: case mp_independent:
21384   if ( mp->cur_type>=mp_known ) { 
21385     mp_try_eq(mp, lhs,null); goto DONE;
21386   };
21387   break;
21388 case mp_vacuous:
21389   break;
21390
21391 @ @<Report redundant or inconsistent equation and |goto done|@>=
21392
21393   if ( mp->cur_type<=mp_string_type ) {
21394     if ( mp->cur_type==mp_string_type ) {
21395       if ( mp_str_vs_str(mp, v,mp->cur_exp)!=0 ) {
21396         goto NOT_FOUND;
21397       }
21398     } else if ( v!=mp->cur_exp ) {
21399       goto NOT_FOUND;
21400     }
21401     @<Exclaim about a redundant equation@>; goto DONE;
21402   }
21403   print_err("Redundant or inconsistent equation");
21404 @.Redundant or inconsistent equation@>
21405   help2("An equation between already-known quantities can't help.")
21406        ("But don't worry; continue and I'll just ignore it.");
21407   mp_put_get_error(mp); goto DONE;
21408 NOT_FOUND: 
21409   print_err("Inconsistent equation");
21410 @.Inconsistent equation@>
21411   help2("The equation I just read contradicts what was said before.")
21412        ("But don't worry; continue and I'll just ignore it.");
21413   mp_put_get_error(mp); goto DONE;
21414 }
21415
21416 @ @<Do multiple equations and |goto done|@>=
21417
21418   p=v+mp->big_node_size[t]; 
21419   q=value(mp->cur_exp)+mp->big_node_size[t];
21420   do {  
21421     p=p-2; q=q-2; mp_try_eq(mp, p,q);
21422   } while (p!=v);
21423   goto DONE;
21424 }
21425
21426 @ The first argument to |try_eq| is the location of a value node
21427 in a capsule that will soon be recycled. The second argument is
21428 either a location within a pair or transform node pointed to by
21429 |cur_exp|, or it is |null| (which means that |cur_exp| itself
21430 serves as the second argument). The idea is to leave |cur_exp| unchanged,
21431 but to equate the two operands.
21432
21433 @<Declare the procedure called |try_eq|@>=
21434 void mp_try_eq (MP mp,pointer l, pointer r) ;
21435
21436
21437 @c void mp_try_eq (MP mp,pointer l, pointer r) {
21438   pointer p; /* dependency list for right operand minus left operand */
21439   int t; /* the type of list |p| */
21440   pointer q; /* the constant term of |p| is here */
21441   pointer pp; /* dependency list for right operand */
21442   int tt; /* the type of list |pp| */
21443   boolean copied; /* have we copied a list that ought to be recycled? */
21444   @<Remove the left operand from its container, negate it, and
21445     put it into dependency list~|p| with constant term~|q|@>;
21446   @<Add the right operand to list |p|@>;
21447   if ( info(p)==null ) {
21448     @<Deal with redundant or inconsistent equation@>;
21449   } else { 
21450     mp_linear_eq(mp, p,t);
21451     if ( r==null ) if ( mp->cur_type!=mp_known ) {
21452       if ( type(mp->cur_exp)==mp_known ) {
21453         pp=mp->cur_exp; mp->cur_exp=value(mp->cur_exp); mp->cur_type=mp_known;
21454         mp_free_node(mp, pp,value_node_size);
21455       }
21456     }
21457   }
21458 }
21459
21460 @ @<Remove the left operand from its container, negate it, and...@>=
21461 t=type(l);
21462 if ( t==mp_known ) { 
21463   t=mp_dependent; p=mp_const_dependency(mp, -value(l)); q=p;
21464 } else if ( t==mp_independent ) {
21465   t=mp_dependent; p=mp_single_dependency(mp, l); negate(value(p));
21466   q=mp->dep_final;
21467 } else { 
21468   p=dep_list(l); q=p;
21469   while (1) { 
21470     negate(value(q));
21471     if ( info(q)==null ) break;
21472     q=link(q);
21473   }
21474   link(prev_dep(l))=link(q); prev_dep(link(q))=prev_dep(l);
21475   type(l)=mp_known;
21476 }
21477
21478 @ @<Deal with redundant or inconsistent equation@>=
21479
21480   if ( abs(value(p))>64 ) { /* off by .001 or more */
21481     print_err("Inconsistent equation");
21482 @.Inconsistent equation@>
21483     mp_print(mp, " (off by "); mp_print_scaled(mp, value(p)); 
21484     mp_print_char(mp, ')');
21485     help2("The equation I just read contradicts what was said before.")
21486       ("But don't worry; continue and I'll just ignore it.");
21487     mp_put_get_error(mp);
21488   } else if ( r==null ) {
21489     @<Exclaim about a redundant equation@>;
21490   }
21491   mp_free_node(mp, p,dep_node_size);
21492 }
21493
21494 @ @<Add the right operand to list |p|@>=
21495 if ( r==null ) {
21496   if ( mp->cur_type==mp_known ) {
21497     value(q)=value(q)+mp->cur_exp; goto DONE1;
21498   } else { 
21499     tt=mp->cur_type;
21500     if ( tt==mp_independent ) pp=mp_single_dependency(mp, mp->cur_exp);
21501     else pp=dep_list(mp->cur_exp);
21502   } 
21503 } else {
21504   if ( type(r)==mp_known ) {
21505     value(q)=value(q)+value(r); goto DONE1;
21506   } else { 
21507     tt=type(r);
21508     if ( tt==mp_independent ) pp=mp_single_dependency(mp, r);
21509     else pp=dep_list(r);
21510   }
21511 }
21512 if ( tt!=mp_independent ) copied=false;
21513 else  { copied=true; tt=mp_dependent; };
21514 @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>;
21515 if ( copied ) mp_flush_node_list(mp, pp);
21516 DONE1:
21517
21518 @ @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>=
21519 mp->watch_coefs=false;
21520 if ( t==tt ) {
21521   p=mp_p_plus_q(mp, p,pp,t);
21522 } else if ( t==mp_proto_dependent ) {
21523   p=mp_p_plus_fq(mp, p,unity,pp,mp_proto_dependent,mp_dependent);
21524 } else { 
21525   q=p;
21526   while ( info(q)!=null ) {
21527     value(q)=mp_round_fraction(mp, value(q)); q=link(q);
21528   }
21529   t=mp_proto_dependent; p=mp_p_plus_q(mp, p,pp,t);
21530 }
21531 mp->watch_coefs=true;
21532
21533 @ Our next goal is to process type declarations. For this purpose it's
21534 convenient to have a procedure that scans a $\langle\,$declared
21535 variable$\,\rangle$ and returns the corresponding token list. After the
21536 following procedure has acted, the token after the declared variable
21537 will have been scanned, so it will appear in |cur_cmd|, |cur_mod|,
21538 and~|cur_sym|.
21539
21540 @<Declare the function called |scan_declared_variable|@>=
21541 pointer mp_scan_declared_variable (MP mp) {
21542   pointer x; /* hash address of the variable's root */
21543   pointer h,t; /* head and tail of the token list to be returned */
21544   pointer l; /* hash address of left bracket */
21545   mp_get_symbol(mp); x=mp->cur_sym;
21546   if ( mp->cur_cmd!=tag_token ) mp_clear_symbol(mp, x,false);
21547   h=mp_get_avail(mp); info(h)=x; t=h;
21548   while (1) { 
21549     mp_get_x_next(mp);
21550     if ( mp->cur_sym==0 ) break;
21551     if ( mp->cur_cmd!=tag_token ) if ( mp->cur_cmd!=internal_quantity)  {
21552       if ( mp->cur_cmd==left_bracket ) {
21553         @<Descend past a collective subscript@>;
21554       } else {
21555         break;
21556       }
21557     }
21558     link(t)=mp_get_avail(mp); t=link(t); info(t)=mp->cur_sym;
21559   }
21560   if ( eq_type(x)!=tag_token ) mp_clear_symbol(mp, x,false);
21561   if ( equiv(x)==null ) mp_new_root(mp, x);
21562   return h;
21563 }
21564
21565 @ If the subscript isn't collective, we don't accept it as part of the
21566 declared variable.
21567
21568 @<Descend past a collective subscript@>=
21569
21570   l=mp->cur_sym; mp_get_x_next(mp);
21571   if ( mp->cur_cmd!=right_bracket ) {
21572     mp_back_input(mp); mp->cur_sym=l; mp->cur_cmd=left_bracket; break;
21573   } else {
21574     mp->cur_sym=collective_subscript;
21575   }
21576 }
21577
21578 @ Type declarations are introduced by the following primitive operations.
21579
21580 @<Put each...@>=
21581 mp_primitive(mp, "numeric",type_name,mp_numeric_type);
21582 @:numeric_}{\&{numeric} primitive@>
21583 mp_primitive(mp, "string",type_name,mp_string_type);
21584 @:string_}{\&{string} primitive@>
21585 mp_primitive(mp, "boolean",type_name,mp_boolean_type);
21586 @:boolean_}{\&{boolean} primitive@>
21587 mp_primitive(mp, "path",type_name,mp_path_type);
21588 @:path_}{\&{path} primitive@>
21589 mp_primitive(mp, "pen",type_name,mp_pen_type);
21590 @:pen_}{\&{pen} primitive@>
21591 mp_primitive(mp, "picture",type_name,mp_picture_type);
21592 @:picture_}{\&{picture} primitive@>
21593 mp_primitive(mp, "transform",type_name,mp_transform_type);
21594 @:transform_}{\&{transform} primitive@>
21595 mp_primitive(mp, "color",type_name,mp_color_type);
21596 @:color_}{\&{color} primitive@>
21597 mp_primitive(mp, "rgbcolor",type_name,mp_color_type);
21598 @:color_}{\&{rgbcolor} primitive@>
21599 mp_primitive(mp, "cmykcolor",type_name,mp_cmykcolor_type);
21600 @:color_}{\&{cmykcolor} primitive@>
21601 mp_primitive(mp, "pair",type_name,mp_pair_type);
21602 @:pair_}{\&{pair} primitive@>
21603
21604 @ @<Cases of |print_cmd...@>=
21605 case type_name: mp_print_type(mp, m); break;
21606
21607 @ Now we are ready to handle type declarations, assuming that a
21608 |type_name| has just been scanned.
21609
21610 @<Declare action procedures for use by |do_statement|@>=
21611 void mp_do_type_declaration (MP mp) ;
21612
21613 @ @c
21614 void mp_do_type_declaration (MP mp) {
21615   small_number t; /* the type being declared */
21616   pointer p; /* token list for a declared variable */
21617   pointer q; /* value node for the variable */
21618   if ( mp->cur_mod>=mp_transform_type ) 
21619     t=mp->cur_mod;
21620   else 
21621     t=mp->cur_mod+unknown_tag;
21622   do {  
21623     p=mp_scan_declared_variable(mp);
21624     mp_flush_variable(mp, equiv(info(p)),link(p),false);
21625     q=mp_find_variable(mp, p);
21626     if ( q!=null ) { 
21627       type(q)=t; value(q)=null; 
21628     } else  { 
21629       print_err("Declared variable conflicts with previous vardef");
21630 @.Declared variable conflicts...@>
21631       help2("You can't use, e.g., `numeric foo[]' after `vardef foo'.")
21632            ("Proceed, and I'll ignore the illegal redeclaration.");
21633       mp_put_get_error(mp);
21634     }
21635     mp_flush_list(mp, p);
21636     if ( mp->cur_cmd<comma ) {
21637       @<Flush spurious symbols after the declared variable@>;
21638     }
21639   } while (! end_of_statement);
21640 }
21641
21642 @ @<Flush spurious symbols after the declared variable@>=
21643
21644   print_err("Illegal suffix of declared variable will be flushed");
21645 @.Illegal suffix...flushed@>
21646   help5("Variables in declarations must consist entirely of")
21647     ("names and collective subscripts, e.g., `x[]a'.")
21648     ("Are you trying to use a reserved word in a variable name?")
21649     ("I'm going to discard the junk I found here,")
21650     ("up to the next comma or the end of the declaration.");
21651   if ( mp->cur_cmd==numeric_token )
21652     mp->help_line[2]="Explicit subscripts like `x15a' aren't permitted.";
21653   mp_put_get_error(mp); mp->scanner_status=flushing;
21654   do {  
21655     get_t_next;
21656     @<Decrease the string reference count...@>;
21657   } while (mp->cur_cmd<comma); /* either |end_of_statement| or |cur_cmd=comma| */
21658   mp->scanner_status=normal;
21659 }
21660
21661 @ \MP's |main_control| procedure just calls |do_statement| repeatedly
21662 until coming to the end of the user's program.
21663 Each execution of |do_statement| concludes with
21664 |cur_cmd=semicolon|, |end_group|, or |stop|.
21665
21666 @c void mp_main_control (MP mp) { 
21667   do {  
21668     mp_do_statement(mp);
21669     if ( mp->cur_cmd==end_group ) {
21670       print_err("Extra `endgroup'");
21671 @.Extra `endgroup'@>
21672       help2("I'm not currently working on a `begingroup',")
21673         ("so I had better not try to end anything.");
21674       mp_flush_error(mp, 0);
21675     }
21676   } while (mp->cur_cmd!=stop);
21677 }
21678 int mp_run (MP mp) {
21679   @<Install and test the non-local jump buffer@>;
21680   mp_main_control(mp); /* come to life */
21681   mp_final_cleanup(mp); /* prepare for death */
21682   mp_close_files_and_terminate(mp);
21683   return mp->history;
21684 }
21685 char * mp_mplib_version (MP mp) {
21686   assert(mp);
21687   return mplib_version;
21688 }
21689 char * mp_metapost_version (MP mp) {
21690   assert(mp);
21691   return metapost_version;
21692 }
21693
21694 @ @<Exported function headers@>=
21695 int mp_run (MP mp);
21696 char * mp_mplib_version (MP mp);
21697 char * mp_metapost_version (MP mp);
21698
21699 @ @<Put each...@>=
21700 mp_primitive(mp, "end",stop,0);
21701 @:end_}{\&{end} primitive@>
21702 mp_primitive(mp, "dump",stop,1);
21703 @:dump_}{\&{dump} primitive@>
21704
21705 @ @<Cases of |print_cmd...@>=
21706 case stop:
21707   if ( m==0 ) mp_print(mp, "end");
21708   else mp_print(mp, "dump");
21709   break;
21710
21711 @* \[41] Commands.
21712 Let's turn now to statements that are classified as ``commands'' because
21713 of their imperative nature. We'll begin with simple ones, so that it
21714 will be clear how to hook command processing into the |do_statement| routine;
21715 then we'll tackle the tougher commands.
21716
21717 Here's one of the simplest:
21718
21719 @<Cases of |do_statement|...@>=
21720 case random_seed: mp_do_random_seed(mp);  break;
21721
21722 @ @<Declare action procedures for use by |do_statement|@>=
21723 void mp_do_random_seed (MP mp) ;
21724
21725 @ @c void mp_do_random_seed (MP mp) { 
21726   mp_get_x_next(mp);
21727   if ( mp->cur_cmd!=assignment ) {
21728     mp_missing_err(mp, ":=");
21729 @.Missing `:='@>
21730     help1("Always say `randomseed:=<numeric expression>'.");
21731     mp_back_error(mp);
21732   };
21733   mp_get_x_next(mp); mp_scan_expression(mp);
21734   if ( mp->cur_type!=mp_known ) {
21735     exp_err("Unknown value will be ignored");
21736 @.Unknown value...ignored@>
21737     help2("Your expression was too random for me to handle,")
21738       ("so I won't change the random seed just now.");
21739     mp_put_get_flush_error(mp, 0);
21740   } else {
21741    @<Initialize the random seed to |cur_exp|@>;
21742   }
21743 }
21744
21745 @ @<Initialize the random seed to |cur_exp|@>=
21746
21747   mp_init_randoms(mp, mp->cur_exp);
21748   if ( mp->selector>=log_only && mp->selector<write_file) {
21749     mp->old_setting=mp->selector; mp->selector=log_only;
21750     mp_print_nl(mp, "{randomseed:="); 
21751     mp_print_scaled(mp, mp->cur_exp); 
21752     mp_print_char(mp, '}');
21753     mp_print_nl(mp, ""); mp->selector=mp->old_setting;
21754   }
21755 }
21756
21757 @ And here's another simple one (somewhat different in flavor):
21758
21759 @<Cases of |do_statement|...@>=
21760 case mode_command: 
21761   mp_print_ln(mp); mp->interaction=mp->cur_mod;
21762   @<Initialize the print |selector| based on |interaction|@>;
21763   if ( mp->log_opened ) mp->selector=mp->selector+2;
21764   mp_get_x_next(mp);
21765   break;
21766
21767 @ @<Put each...@>=
21768 mp_primitive(mp, "batchmode",mode_command,mp_batch_mode);
21769 @:mp_batch_mode_}{\&{batchmode} primitive@>
21770 mp_primitive(mp, "nonstopmode",mode_command,mp_nonstop_mode);
21771 @:mp_nonstop_mode_}{\&{nonstopmode} primitive@>
21772 mp_primitive(mp, "scrollmode",mode_command,mp_scroll_mode);
21773 @:mp_scroll_mode_}{\&{scrollmode} primitive@>
21774 mp_primitive(mp, "errorstopmode",mode_command,mp_error_stop_mode);
21775 @:mp_error_stop_mode_}{\&{errorstopmode} primitive@>
21776
21777 @ @<Cases of |print_cmd_mod|...@>=
21778 case mode_command: 
21779   switch (m) {
21780   case mp_batch_mode: mp_print(mp, "batchmode"); break;
21781   case mp_nonstop_mode: mp_print(mp, "nonstopmode"); break;
21782   case mp_scroll_mode: mp_print(mp, "scrollmode"); break;
21783   default: mp_print(mp, "errorstopmode"); break;
21784   }
21785   break;
21786
21787 @ The `\&{inner}' and `\&{outer}' commands are only slightly harder.
21788
21789 @<Cases of |do_statement|...@>=
21790 case protection_command: mp_do_protection(mp); break;
21791
21792 @ @<Put each...@>=
21793 mp_primitive(mp, "inner",protection_command,0);
21794 @:inner_}{\&{inner} primitive@>
21795 mp_primitive(mp, "outer",protection_command,1);
21796 @:outer_}{\&{outer} primitive@>
21797
21798 @ @<Cases of |print_cmd...@>=
21799 case protection_command: 
21800   if ( m==0 ) mp_print(mp, "inner");
21801   else mp_print(mp, "outer");
21802   break;
21803
21804 @ @<Declare action procedures for use by |do_statement|@>=
21805 void mp_do_protection (MP mp) ;
21806
21807 @ @c void mp_do_protection (MP mp) {
21808   int m; /* 0 to unprotect, 1 to protect */
21809   halfword t; /* the |eq_type| before we change it */
21810   m=mp->cur_mod;
21811   do {  
21812     mp_get_symbol(mp); t=eq_type(mp->cur_sym);
21813     if ( m==0 ) { 
21814       if ( t>=outer_tag ) 
21815         eq_type(mp->cur_sym)=t-outer_tag;
21816     } else if ( t<outer_tag ) {
21817       eq_type(mp->cur_sym)=t+outer_tag;
21818     }
21819     mp_get_x_next(mp);
21820   } while (mp->cur_cmd==comma);
21821 }
21822
21823 @ \MP\ never defines the tokens `\.(' and `\.)' to be primitives, but
21824 plain \MP\ begins with the declaration `\&{delimiters} \.{()}'. Such a
21825 declaration assigns the command code |left_delimiter| to `\.{(}' and
21826 |right_delimiter| to `\.{)}'; the |equiv| of each delimiter is the
21827 hash address of its mate.
21828
21829 @<Cases of |do_statement|...@>=
21830 case delimiters: mp_def_delims(mp); break;
21831
21832 @ @<Declare action procedures for use by |do_statement|@>=
21833 void mp_def_delims (MP mp) ;
21834
21835 @ @c void mp_def_delims (MP mp) {
21836   pointer l_delim,r_delim; /* the new delimiter pair */
21837   mp_get_clear_symbol(mp); l_delim=mp->cur_sym;
21838   mp_get_clear_symbol(mp); r_delim=mp->cur_sym;
21839   eq_type(l_delim)=left_delimiter; equiv(l_delim)=r_delim;
21840   eq_type(r_delim)=right_delimiter; equiv(r_delim)=l_delim;
21841   mp_get_x_next(mp);
21842 }
21843
21844 @ Here is a procedure that is called when \MP\ has reached a point
21845 where some right delimiter is mandatory.
21846
21847 @<Declare the procedure called |check_delimiter|@>=
21848 void mp_check_delimiter (MP mp,pointer l_delim, pointer r_delim) {
21849   if ( mp->cur_cmd==right_delimiter ) 
21850     if ( mp->cur_mod==l_delim ) 
21851       return;
21852   if ( mp->cur_sym!=r_delim ) {
21853      mp_missing_err(mp, str(text(r_delim)));
21854 @.Missing `)'@>
21855     help2("I found no right delimiter to match a left one. So I've")
21856       ("put one in, behind the scenes; this may fix the problem.");
21857     mp_back_error(mp);
21858   } else { 
21859     print_err("The token `"); mp_print_text(r_delim);
21860 @.The token...delimiter@>
21861     mp_print(mp, "' is no longer a right delimiter");
21862     help3("Strange: This token has lost its former meaning!")
21863       ("I'll read it as a right delimiter this time;")
21864       ("but watch out, I'll probably miss it later.");
21865     mp_error(mp);
21866   }
21867 }
21868
21869 @ The next four commands save or change the values associated with tokens.
21870
21871 @<Cases of |do_statement|...@>=
21872 case save_command: 
21873   do {  
21874     mp_get_symbol(mp); mp_save_variable(mp, mp->cur_sym); mp_get_x_next(mp);
21875   } while (mp->cur_cmd==comma);
21876   break;
21877 case interim_command: mp_do_interim(mp); break;
21878 case let_command: mp_do_let(mp); break;
21879 case new_internal: mp_do_new_internal(mp); break;
21880
21881 @ @<Declare action procedures for use by |do_statement|@>=
21882 void mp_do_statement (MP mp);
21883 void mp_do_interim (MP mp);
21884
21885 @ @c void mp_do_interim (MP mp) { 
21886   mp_get_x_next(mp);
21887   if ( mp->cur_cmd!=internal_quantity ) {
21888      print_err("The token `");
21889 @.The token...quantity@>
21890     if ( mp->cur_sym==0 ) mp_print(mp, "(%CAPSULE)");
21891     else mp_print_text(mp->cur_sym);
21892     mp_print(mp, "' isn't an internal quantity");
21893     help1("Something like `tracingonline' should follow `interim'.");
21894     mp_back_error(mp);
21895   } else { 
21896     mp_save_internal(mp, mp->cur_mod); mp_back_input(mp);
21897   }
21898   mp_do_statement(mp);
21899 }
21900
21901 @ The following procedure is careful not to undefine the left-hand symbol
21902 too soon, lest commands like `{\tt let x=x}' have a surprising effect.
21903
21904 @<Declare action procedures for use by |do_statement|@>=
21905 void mp_do_let (MP mp) ;
21906
21907 @ @c void mp_do_let (MP mp) {
21908   pointer l; /* hash location of the left-hand symbol */
21909   mp_get_symbol(mp); l=mp->cur_sym; mp_get_x_next(mp);
21910   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
21911      mp_missing_err(mp, "=");
21912 @.Missing `='@>
21913     help3("You should have said `let symbol = something'.")
21914       ("But don't worry; I'll pretend that an equals sign")
21915       ("was present. The next token I read will be `something'.");
21916     mp_back_error(mp);
21917   }
21918   mp_get_symbol(mp);
21919   switch (mp->cur_cmd) {
21920   case defined_macro: case secondary_primary_macro:
21921   case tertiary_secondary_macro: case expression_tertiary_macro: 
21922     add_mac_ref(mp->cur_mod);
21923     break;
21924   default: 
21925     break;
21926   }
21927   mp_clear_symbol(mp, l,false); eq_type(l)=mp->cur_cmd;
21928   if ( mp->cur_cmd==tag_token ) equiv(l)=null;
21929   else equiv(l)=mp->cur_mod;
21930   mp_get_x_next(mp);
21931 }
21932
21933 @ @<Declarations@>=
21934 void mp_grow_internals (MP mp, int l);
21935 void mp_do_new_internal (MP mp) ;
21936
21937 @ @c
21938 void mp_grow_internals (MP mp, int l) {
21939   scaled *internal;
21940   char * *int_name; 
21941   int k;
21942   if ( hash_end+l>max_halfword ) {
21943     mp_confusion(mp, "out of memory space"); /* can't be reached */
21944   }
21945   int_name = xmalloc ((l+1),sizeof(char *));
21946   internal = xmalloc ((l+1),sizeof(scaled));
21947   for (k=0;k<=l; k++ ) { 
21948     if (k<=mp->max_internal) {
21949       internal[k]=mp->internal[k]; 
21950       int_name[k]=mp->int_name[k]; 
21951     } else {
21952       internal[k]=0; 
21953       int_name[k]=NULL; 
21954     }
21955   }
21956   xfree(mp->internal); xfree(mp->int_name);
21957   mp->int_name = int_name;
21958   mp->internal = internal;
21959   mp->max_internal = l;
21960 }
21961
21962
21963 void mp_do_new_internal (MP mp) { 
21964   do {  
21965     if ( mp->int_ptr==mp->max_internal ) {
21966       mp_grow_internals(mp, (mp->max_internal + (mp->max_internal>>2)));
21967     }
21968     mp_get_clear_symbol(mp); incr(mp->int_ptr);
21969     eq_type(mp->cur_sym)=internal_quantity; 
21970     equiv(mp->cur_sym)=mp->int_ptr;
21971     if(mp->int_name[mp->int_ptr]!=NULL)
21972       xfree(mp->int_name[mp->int_ptr]);
21973     mp->int_name[mp->int_ptr]=str(text(mp->cur_sym)); 
21974     mp->internal[mp->int_ptr]=0;
21975     mp_get_x_next(mp);
21976   } while (mp->cur_cmd==comma);
21977 }
21978
21979 @ @<Dealloc variables@>=
21980 for (k=0;k<=mp->max_internal;k++) {
21981    xfree(mp->int_name[k]);
21982 }
21983 xfree(mp->internal); 
21984 xfree(mp->int_name); 
21985
21986
21987 @ The various `\&{show}' commands are distinguished by modifier fields
21988 in the usual way.
21989
21990 @d show_token_code 0 /* show the meaning of a single token */
21991 @d show_stats_code 1 /* show current memory and string usage */
21992 @d show_code 2 /* show a list of expressions */
21993 @d show_var_code 3 /* show a variable and its descendents */
21994 @d show_dependencies_code 4 /* show dependent variables in terms of independents */
21995
21996 @<Put each...@>=
21997 mp_primitive(mp, "showtoken",show_command,show_token_code);
21998 @:show_token_}{\&{showtoken} primitive@>
21999 mp_primitive(mp, "showstats",show_command,show_stats_code);
22000 @:show_stats_}{\&{showstats} primitive@>
22001 mp_primitive(mp, "show",show_command,show_code);
22002 @:show_}{\&{show} primitive@>
22003 mp_primitive(mp, "showvariable",show_command,show_var_code);
22004 @:show_var_}{\&{showvariable} primitive@>
22005 mp_primitive(mp, "showdependencies",show_command,show_dependencies_code);
22006 @:show_dependencies_}{\&{showdependencies} primitive@>
22007
22008 @ @<Cases of |print_cmd...@>=
22009 case show_command: 
22010   switch (m) {
22011   case show_token_code:mp_print(mp, "showtoken"); break;
22012   case show_stats_code:mp_print(mp, "showstats"); break;
22013   case show_code:mp_print(mp, "show"); break;
22014   case show_var_code:mp_print(mp, "showvariable"); break;
22015   default: mp_print(mp, "showdependencies"); break;
22016   }
22017   break;
22018
22019 @ @<Cases of |do_statement|...@>=
22020 case show_command:mp_do_show_whatever(mp); break;
22021
22022 @ The value of |cur_mod| controls the |verbosity| in the |print_exp| routine:
22023 if it's |show_code|, complicated structures are abbreviated, otherwise
22024 they aren't.
22025
22026 @<Declare action procedures for use by |do_statement|@>=
22027 void mp_do_show (MP mp) ;
22028
22029 @ @c void mp_do_show (MP mp) { 
22030   do {  
22031     mp_get_x_next(mp); mp_scan_expression(mp);
22032     mp_print_nl(mp, ">> ");
22033 @.>>@>
22034     mp_print_exp(mp, null,2); mp_flush_cur_exp(mp, 0);
22035   } while (mp->cur_cmd==comma);
22036 }
22037
22038 @ @<Declare action procedures for use by |do_statement|@>=
22039 void mp_disp_token (MP mp) ;
22040
22041 @ @c void mp_disp_token (MP mp) { 
22042   mp_print_nl(mp, "> ");
22043 @.>\relax@>
22044   if ( mp->cur_sym==0 ) {
22045     @<Show a numeric or string or capsule token@>;
22046   } else { 
22047     mp_print_text(mp->cur_sym); mp_print_char(mp, '=');
22048     if ( eq_type(mp->cur_sym)>=outer_tag ) mp_print(mp, "(outer) ");
22049     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod);
22050     if ( mp->cur_cmd==defined_macro ) {
22051       mp_print_ln(mp); mp_show_macro(mp, mp->cur_mod,null,100000);
22052     } /* this avoids recursion between |show_macro| and |print_cmd_mod| */
22053 @^recursion@>
22054   }
22055 }
22056
22057 @ @<Show a numeric or string or capsule token@>=
22058
22059   if ( mp->cur_cmd==numeric_token ) {
22060     mp_print_scaled(mp, mp->cur_mod);
22061   } else if ( mp->cur_cmd==capsule_token ) {
22062     mp->g_pointer=mp->cur_mod; mp_print_capsule(mp);
22063   } else  { 
22064     mp_print_char(mp, '"'); 
22065     mp_print_str(mp, mp->cur_mod); mp_print_char(mp, '"');
22066     delete_str_ref(mp->cur_mod);
22067   }
22068 }
22069
22070 @ The following cases of |print_cmd_mod| might arise in connection
22071 with |disp_token|, although they don't correspond to any
22072 primitive tokens.
22073
22074 @<Cases of |print_cmd_...@>=
22075 case left_delimiter:
22076 case right_delimiter: 
22077   if ( c==left_delimiter ) mp_print(mp, "left");
22078   else mp_print(mp, "right");
22079   mp_print(mp, " delimiter that matches "); 
22080   mp_print_text(m);
22081   break;
22082 case tag_token:
22083   if ( m==null ) mp_print(mp, "tag");
22084    else mp_print(mp, "variable");
22085    break;
22086 case defined_macro: 
22087    mp_print(mp, "macro:");
22088    break;
22089 case secondary_primary_macro:
22090 case tertiary_secondary_macro:
22091 case expression_tertiary_macro:
22092   mp_print_cmd_mod(mp, macro_def,c); 
22093   mp_print(mp, "'d macro:");
22094   mp_print_ln(mp); mp_show_token_list(mp, link(link(m)),null,1000,0);
22095   break;
22096 case repeat_loop:
22097   mp_print(mp, "[repeat the loop]");
22098   break;
22099 case internal_quantity:
22100   mp_print(mp, mp->int_name[m]);
22101   break;
22102
22103 @ @<Declare action procedures for use by |do_statement|@>=
22104 void mp_do_show_token (MP mp) ;
22105
22106 @ @c void mp_do_show_token (MP mp) { 
22107   do {  
22108     get_t_next; mp_disp_token(mp);
22109     mp_get_x_next(mp);
22110   } while (mp->cur_cmd==comma);
22111 }
22112
22113 @ @<Declare action procedures for use by |do_statement|@>=
22114 void mp_do_show_stats (MP mp) ;
22115
22116 @ @c void mp_do_show_stats (MP mp) { 
22117   mp_print_nl(mp, "Memory usage ");
22118 @.Memory usage...@>
22119   mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used);
22120   if ( false )
22121     mp_print(mp, "unknown");
22122   mp_print(mp, " ("); mp_print_int(mp, mp->hi_mem_min-mp->lo_mem_max-1);
22123   mp_print(mp, " still untouched)"); mp_print_ln(mp);
22124   mp_print_nl(mp, "String usage ");
22125   mp_print_int(mp, mp->strs_in_use-mp->init_str_use);
22126   mp_print_char(mp, '&'); mp_print_int(mp, mp->pool_in_use-mp->init_pool_ptr);
22127   if ( false )
22128     mp_print(mp, "unknown");
22129   mp_print(mp, " (");
22130   mp_print_int(mp, mp->max_strings-1-mp->strs_used_up); mp_print_char(mp, '&');
22131   mp_print_int(mp, mp->pool_size-mp->pool_ptr); 
22132   mp_print(mp, " now untouched)"); mp_print_ln(mp);
22133   mp_get_x_next(mp);
22134 }
22135
22136 @ Here's a recursive procedure that gives an abbreviated account
22137 of a variable, for use by |do_show_var|.
22138
22139 @<Declare action procedures for use by |do_statement|@>=
22140 void mp_disp_var (MP mp,pointer p) ;
22141
22142 @ @c void mp_disp_var (MP mp,pointer p) {
22143   pointer q; /* traverses attributes and subscripts */
22144   int n; /* amount of macro text to show */
22145   if ( type(p)==mp_structured )  {
22146     @<Descend the structure@>;
22147   } else if ( type(p)>=mp_unsuffixed_macro ) {
22148     @<Display a variable macro@>;
22149   } else if ( type(p)!=undefined ){ 
22150     mp_print_nl(mp, ""); mp_print_variable_name(mp, p); 
22151     mp_print_char(mp, '=');
22152     mp_print_exp(mp, p,0);
22153   }
22154 }
22155
22156 @ @<Descend the structure@>=
22157
22158   q=attr_head(p);
22159   do {  mp_disp_var(mp, q); q=link(q); } while (q!=end_attr);
22160   q=subscr_head(p);
22161   while ( name_type(q)==mp_subscr ) { 
22162     mp_disp_var(mp, q); q=link(q);
22163   }
22164 }
22165
22166 @ @<Display a variable macro@>=
22167
22168   mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22169   if ( type(p)>mp_unsuffixed_macro ) 
22170     mp_print(mp, "@@#"); /* |suffixed_macro| */
22171   mp_print(mp, "=macro:");
22172   if ( (int)mp->file_offset>=mp->max_print_line-20 ) n=5;
22173   else n=mp->max_print_line-mp->file_offset-15;
22174   mp_show_macro(mp, value(p),null,n);
22175 }
22176
22177 @ @<Declare action procedures for use by |do_statement|@>=
22178 void mp_do_show_var (MP mp) ;
22179
22180 @ @c void mp_do_show_var (MP mp) { 
22181   do {  
22182     get_t_next;
22183     if ( mp->cur_sym>0 ) if ( mp->cur_sym<=hash_end )
22184       if ( mp->cur_cmd==tag_token ) if ( mp->cur_mod!=null ) {
22185       mp_disp_var(mp, mp->cur_mod); goto DONE;
22186     }
22187    mp_disp_token(mp);
22188   DONE:
22189    mp_get_x_next(mp);
22190   } while (mp->cur_cmd==comma);
22191 }
22192
22193 @ @<Declare action procedures for use by |do_statement|@>=
22194 void mp_do_show_dependencies (MP mp) ;
22195
22196 @ @c void mp_do_show_dependencies (MP mp) {
22197   pointer p; /* link that runs through all dependencies */
22198   p=link(dep_head);
22199   while ( p!=dep_head ) {
22200     if ( mp_interesting(mp, p) ) {
22201       mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22202       if ( type(p)==mp_dependent ) mp_print_char(mp, '=');
22203       else mp_print(mp, " = "); /* extra spaces imply proto-dependency */
22204       mp_print_dependency(mp, dep_list(p),type(p));
22205     }
22206     p=dep_list(p);
22207     while ( info(p)!=null ) p=link(p);
22208     p=link(p);
22209   }
22210   mp_get_x_next(mp);
22211 }
22212
22213 @ Finally we are ready for the procedure that governs all of the
22214 show commands.
22215
22216 @<Declare action procedures for use by |do_statement|@>=
22217 void mp_do_show_whatever (MP mp) ;
22218
22219 @ @c void mp_do_show_whatever (MP mp) { 
22220   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
22221   switch (mp->cur_mod) {
22222   case show_token_code:mp_do_show_token(mp); break;
22223   case show_stats_code:mp_do_show_stats(mp); break;
22224   case show_code:mp_do_show(mp); break;
22225   case show_var_code:mp_do_show_var(mp); break;
22226   case show_dependencies_code:mp_do_show_dependencies(mp); break;
22227   } /* there are no other cases */
22228   if ( mp->internal[mp_showstopping]>0 ){ 
22229     print_err("OK");
22230 @.OK@>
22231     if ( mp->interaction<mp_error_stop_mode ) { 
22232       help0; decr(mp->error_count);
22233     } else {
22234       help1("This isn't an error message; I'm just showing something.");
22235     }
22236     if ( mp->cur_cmd==semicolon ) mp_error(mp);
22237      else mp_put_get_error(mp);
22238   }
22239 }
22240
22241 @ The `\&{addto}' command needs the following additional primitives:
22242
22243 @d double_path_code 0 /* command modifier for `\&{doublepath}' */
22244 @d contour_code 1 /* command modifier for `\&{contour}' */
22245 @d also_code 2 /* command modifier for `\&{also}' */
22246
22247 @ Pre and postscripts need two new identifiers:
22248
22249 @d with_pre_script 11
22250 @d with_post_script 13
22251
22252 @<Put each...@>=
22253 mp_primitive(mp, "doublepath",thing_to_add,double_path_code);
22254 @:double_path_}{\&{doublepath} primitive@>
22255 mp_primitive(mp, "contour",thing_to_add,contour_code);
22256 @:contour_}{\&{contour} primitive@>
22257 mp_primitive(mp, "also",thing_to_add,also_code);
22258 @:also_}{\&{also} primitive@>
22259 mp_primitive(mp, "withpen",with_option,mp_pen_type);
22260 @:with_pen_}{\&{withpen} primitive@>
22261 mp_primitive(mp, "dashed",with_option,mp_picture_type);
22262 @:dashed_}{\&{dashed} primitive@>
22263 mp_primitive(mp, "withprescript",with_option,with_pre_script);
22264 @:with_pre_script_}{\&{withprescript} primitive@>
22265 mp_primitive(mp, "withpostscript",with_option,with_post_script);
22266 @:with_post_script_}{\&{withpostscript} primitive@>
22267 mp_primitive(mp, "withoutcolor",with_option,mp_no_model);
22268 @:with_color_}{\&{withoutcolor} primitive@>
22269 mp_primitive(mp, "withgreyscale",with_option,mp_grey_model);
22270 @:with_color_}{\&{withgreyscale} primitive@>
22271 mp_primitive(mp, "withcolor",with_option,mp_uninitialized_model);
22272 @:with_color_}{\&{withcolor} primitive@>
22273 /*  \&{withrgbcolor} is an alias for \&{withcolor} */
22274 mp_primitive(mp, "withrgbcolor",with_option,mp_rgb_model);
22275 @:with_color_}{\&{withrgbcolor} primitive@>
22276 mp_primitive(mp, "withcmykcolor",with_option,mp_cmyk_model);
22277 @:with_color_}{\&{withcmykcolor} primitive@>
22278
22279 @ @<Cases of |print_cmd...@>=
22280 case thing_to_add:
22281   if ( m==contour_code ) mp_print(mp, "contour");
22282   else if ( m==double_path_code ) mp_print(mp, "doublepath");
22283   else mp_print(mp, "also");
22284   break;
22285 case with_option:
22286   if ( m==mp_pen_type ) mp_print(mp, "withpen");
22287   else if ( m==with_pre_script ) mp_print(mp, "withprescript");
22288   else if ( m==with_post_script ) mp_print(mp, "withpostscript");
22289   else if ( m==mp_no_model ) mp_print(mp, "withoutcolor");
22290   else if ( m==mp_rgb_model ) mp_print(mp, "withrgbcolor");
22291   else if ( m==mp_uninitialized_model ) mp_print(mp, "withcolor");
22292   else if ( m==mp_cmyk_model ) mp_print(mp, "withcmykcolor");
22293   else if ( m==mp_grey_model ) mp_print(mp, "withgreyscale");
22294   else mp_print(mp, "dashed");
22295   break;
22296
22297 @ The |scan_with_list| procedure parses a $\langle$with list$\rangle$ and
22298 updates the list of graphical objects starting at |p|.  Each $\langle$with
22299 clause$\rangle$ updates all graphical objects whose |type| is compatible.
22300 Other objects are ignored.
22301
22302 @<Declare action procedures for use by |do_statement|@>=
22303 void mp_scan_with_list (MP mp,pointer p) ;
22304
22305 @ @c void mp_scan_with_list (MP mp,pointer p) {
22306   small_number t; /* |cur_mod| of the |with_option| (should match |cur_type|) */
22307   pointer q; /* for list manipulation */
22308   int old_setting; /* saved |selector| setting */
22309   pointer k; /* for finding the near-last item in a list  */
22310   str_number s; /* for string cleanup after combining  */
22311   pointer cp,pp,dp,ap,bp;
22312     /* objects being updated; |void| initially; |null| to suppress update */
22313   cp=mp_void; pp=mp_void; dp=mp_void; ap=mp_void; bp=mp_void;
22314   k=0;
22315   while ( mp->cur_cmd==with_option ){ 
22316     t=mp->cur_mod;
22317     mp_get_x_next(mp);
22318     if ( t!=mp_no_model ) mp_scan_expression(mp);
22319     if (((t==with_pre_script)&&(mp->cur_type!=mp_string_type))||
22320      ((t==with_post_script)&&(mp->cur_type!=mp_string_type))||
22321      ((t==mp_uninitialized_model)&&
22322         ((mp->cur_type!=mp_cmykcolor_type)&&(mp->cur_type!=mp_color_type)
22323           &&(mp->cur_type!=mp_known)&&(mp->cur_type!=mp_boolean_type)))||
22324      ((t==mp_cmyk_model)&&(mp->cur_type!=mp_cmykcolor_type))||
22325      ((t==mp_rgb_model)&&(mp->cur_type!=mp_color_type))||
22326      ((t==mp_grey_model)&&(mp->cur_type!=mp_known))||
22327      ((t==mp_pen_type)&&(mp->cur_type!=t))||
22328      ((t==mp_picture_type)&&(mp->cur_type!=t)) ) {
22329       @<Complain about improper type@>;
22330     } else if ( t==mp_uninitialized_model ) {
22331       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22332       if ( cp!=null )
22333         @<Transfer a color from the current expression to object~|cp|@>;
22334       mp_flush_cur_exp(mp, 0);
22335     } else if ( t==mp_rgb_model ) {
22336       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22337       if ( cp!=null )
22338         @<Transfer a rgbcolor from the current expression to object~|cp|@>;
22339       mp_flush_cur_exp(mp, 0);
22340     } else if ( t==mp_cmyk_model ) {
22341       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22342       if ( cp!=null )
22343         @<Transfer a cmykcolor from the current expression to object~|cp|@>;
22344       mp_flush_cur_exp(mp, 0);
22345     } else if ( t==mp_grey_model ) {
22346       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22347       if ( cp!=null )
22348         @<Transfer a greyscale from the current expression to object~|cp|@>;
22349       mp_flush_cur_exp(mp, 0);
22350     } else if ( t==mp_no_model ) {
22351       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22352       if ( cp!=null )
22353         @<Transfer a noncolor from the current expression to object~|cp|@>;
22354     } else if ( t==mp_pen_type ) {
22355       if ( pp==mp_void ) @<Make |pp| an object in list~|p| that needs a pen@>;
22356       if ( pp!=null ) {
22357         if ( pen_p(pp)!=null ) mp_toss_knot_list(mp, pen_p(pp));
22358         pen_p(pp)=mp->cur_exp; mp->cur_type=mp_vacuous;
22359       }
22360     } else if ( t==with_pre_script ) {
22361       if ( ap==mp_void )
22362         ap=p;
22363       while ( (ap!=null)&&(! has_color(ap)) )
22364          ap=link(ap);
22365       if ( ap!=null ) {
22366         if ( pre_script(ap)!=null ) { /*  build a new,combined string  */
22367           s=pre_script(ap);
22368           old_setting=mp->selector;
22369               mp->selector=new_string;
22370           str_room(length(pre_script(ap))+length(mp->cur_exp)+2);
22371               mp_print_str(mp, mp->cur_exp);
22372           append_char(13);  /* a forced \ps\ newline  */
22373           mp_print_str(mp, pre_script(ap));
22374           pre_script(ap)=mp_make_string(mp);
22375           delete_str_ref(s);
22376           mp->selector=old_setting;
22377         } else {
22378           pre_script(ap)=mp->cur_exp;
22379         }
22380         mp->cur_type=mp_vacuous;
22381       }
22382     } else if ( t==with_post_script ) {
22383       if ( bp==mp_void )
22384         k=p; 
22385       bp=k;
22386       while ( link(k)!=null ) {
22387         k=link(k);
22388         if ( has_color(k) ) bp=k;
22389       }
22390       if ( bp!=null ) {
22391          if ( post_script(bp)!=null ) {
22392            s=post_script(bp);
22393            old_setting=mp->selector;
22394                mp->selector=new_string;
22395            str_room(length(post_script(bp))+length(mp->cur_exp)+2);
22396            mp_print_str(mp, post_script(bp));
22397            append_char(13); /* a forced \ps\ newline  */
22398            mp_print_str(mp, mp->cur_exp);
22399            post_script(bp)=mp_make_string(mp);
22400            delete_str_ref(s);
22401            mp->selector=old_setting;
22402          } else {
22403            post_script(bp)=mp->cur_exp;
22404          }
22405          mp->cur_type=mp_vacuous;
22406        }
22407     } else { 
22408       if ( dp==mp_void ) 
22409         @<Make |dp| a stroked node in list~|p|@>;
22410       if ( dp!=null ) {
22411         if ( dash_p(dp)!=null ) delete_edge_ref(dash_p(dp));
22412         dash_p(dp)=mp_make_dashes(mp, mp->cur_exp);
22413         dash_scale(dp)=unity;
22414         mp->cur_type=mp_vacuous;
22415       }
22416     }
22417   }
22418   @<Copy the information from objects |cp|, |pp|, and |dp| into the rest
22419     of the list@>;
22420 };
22421
22422 @ @<Complain about improper type@>=
22423 { exp_err("Improper type");
22424 @.Improper type@>
22425 help2("Next time say `withpen <known pen expression>';")
22426   ("I'll ignore the bad `with' clause and look for another.");
22427 if ( t==with_pre_script )
22428   mp->help_line[1]="Next time say `withprescript <known string expression>';";
22429 else if ( t==with_post_script )
22430   mp->help_line[1]="Next time say `withpostscript <known string expression>';";
22431 else if ( t==mp_picture_type )
22432   mp->help_line[1]="Next time say `dashed <known picture expression>';";
22433 else if ( t==mp_uninitialized_model )
22434   mp->help_line[1]="Next time say `withcolor <known color expression>';";
22435 else if ( t==mp_rgb_model )
22436   mp->help_line[1]="Next time say `withrgbcolor <known color expression>';";
22437 else if ( t==mp_cmyk_model )
22438   mp->help_line[1]="Next time say `withcmykcolor <known cmykcolor expression>';";
22439 else if ( t==mp_grey_model )
22440   mp->help_line[1]="Next time say `withgreyscale <known numeric expression>';";;
22441 mp_put_get_flush_error(mp, 0);
22442 }
22443
22444 @ Forcing the color to be between |0| and |unity| here guarantees that no
22445 picture will ever contain a color outside the legal range for \ps\ graphics.
22446
22447 @<Transfer a color from the current expression to object~|cp|@>=
22448 { if ( mp->cur_type==mp_color_type )
22449    @<Transfer a rgbcolor from the current expression to object~|cp|@>
22450 else if ( mp->cur_type==mp_cmykcolor_type )
22451    @<Transfer a cmykcolor from the current expression to object~|cp|@>
22452 else if ( mp->cur_type==mp_known )
22453    @<Transfer a greyscale from the current expression to object~|cp|@>
22454 else if ( mp->cur_exp==false_code )
22455    @<Transfer a noncolor from the current expression to object~|cp|@>;
22456 }
22457
22458 @ @<Transfer a rgbcolor from the current expression to object~|cp|@>=
22459 { q=value(mp->cur_exp);
22460 cyan_val(cp)=0;
22461 magenta_val(cp)=0;
22462 yellow_val(cp)=0;
22463 black_val(cp)=0;
22464 red_val(cp)=value(red_part_loc(q));
22465 green_val(cp)=value(green_part_loc(q));
22466 blue_val(cp)=value(blue_part_loc(q));
22467 color_model(cp)=mp_rgb_model;
22468 if ( red_val(cp)<0 ) red_val(cp)=0;
22469 if ( green_val(cp)<0 ) green_val(cp)=0;
22470 if ( blue_val(cp)<0 ) blue_val(cp)=0;
22471 if ( red_val(cp)>unity ) red_val(cp)=unity;
22472 if ( green_val(cp)>unity ) green_val(cp)=unity;
22473 if ( blue_val(cp)>unity ) blue_val(cp)=unity;
22474 }
22475
22476 @ @<Transfer a cmykcolor from the current expression to object~|cp|@>=
22477 { q=value(mp->cur_exp);
22478 cyan_val(cp)=value(cyan_part_loc(q));
22479 magenta_val(cp)=value(magenta_part_loc(q));
22480 yellow_val(cp)=value(yellow_part_loc(q));
22481 black_val(cp)=value(black_part_loc(q));
22482 color_model(cp)=mp_cmyk_model;
22483 if ( cyan_val(cp)<0 ) cyan_val(cp)=0;
22484 if ( magenta_val(cp)<0 ) magenta_val(cp)=0;
22485 if ( yellow_val(cp)<0 ) yellow_val(cp)=0;
22486 if ( black_val(cp)<0 ) black_val(cp)=0;
22487 if ( cyan_val(cp)>unity ) cyan_val(cp)=unity;
22488 if ( magenta_val(cp)>unity ) magenta_val(cp)=unity;
22489 if ( yellow_val(cp)>unity ) yellow_val(cp)=unity;
22490 if ( black_val(cp)>unity ) black_val(cp)=unity;
22491 }
22492
22493 @ @<Transfer a greyscale from the current expression to object~|cp|@>=
22494 { q=mp->cur_exp;
22495 cyan_val(cp)=0;
22496 magenta_val(cp)=0;
22497 yellow_val(cp)=0;
22498 black_val(cp)=0;
22499 grey_val(cp)=q;
22500 color_model(cp)=mp_grey_model;
22501 if ( grey_val(cp)<0 ) grey_val(cp)=0;
22502 if ( grey_val(cp)>unity ) grey_val(cp)=unity;
22503 }
22504
22505 @ @<Transfer a noncolor from the current expression to object~|cp|@>=
22506 {
22507 cyan_val(cp)=0;
22508 magenta_val(cp)=0;
22509 yellow_val(cp)=0;
22510 black_val(cp)=0;
22511 grey_val(cp)=0;
22512 color_model(cp)=mp_no_model;
22513 }
22514
22515 @ @<Make |cp| a colored object in object list~|p|@>=
22516 { cp=p;
22517   while ( cp!=null ){ 
22518     if ( has_color(cp) ) break;
22519     cp=link(cp);
22520   }
22521 }
22522
22523 @ @<Make |pp| an object in list~|p| that needs a pen@>=
22524 { pp=p;
22525   while ( pp!=null ) {
22526     if ( has_pen(pp) ) break;
22527     pp=link(pp);
22528   }
22529 }
22530
22531 @ @<Make |dp| a stroked node in list~|p|@>=
22532 { dp=p;
22533   while ( dp!=null ) {
22534     if ( type(dp)==mp_stroked_code ) break;
22535     dp=link(dp);
22536   }
22537 }
22538
22539 @ @<Copy the information from objects |cp|, |pp|, and |dp| into...@>=
22540 @<Copy |cp|'s color into the colored objects linked to~|cp|@>;
22541 if ( pp>mp_void )
22542   @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>;
22543 if ( dp>mp_void ) @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>
22544
22545 @ @<Copy |cp|'s color into the colored objects linked to~|cp|@>=
22546 { q=link(cp);
22547   while ( q!=null ) { 
22548     if ( has_color(q) ) {
22549       red_val(q)=red_val(cp);
22550       green_val(q)=green_val(cp);
22551       blue_val(q)=blue_val(cp);
22552       black_val(q)=black_val(cp);
22553       color_model(q)=color_model(cp);
22554     }
22555     q=link(q);
22556   }
22557 }
22558
22559 @ @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>=
22560 { q=link(pp);
22561   while ( q!=null ) {
22562     if ( has_pen(q) ) {
22563       if ( pen_p(q)!=null ) mp_toss_knot_list(mp, pen_p(q));
22564       pen_p(q)=copy_pen(pen_p(pp));
22565     }
22566     q=link(q);
22567   }
22568 }
22569
22570 @ @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>=
22571 { q=link(dp);
22572   while ( q!=null ) {
22573     if ( type(q)==mp_stroked_code ) {
22574       if ( dash_p(q)!=null ) delete_edge_ref(dash_p(q));
22575       dash_p(q)=dash_p(dp);
22576       dash_scale(q)=unity;
22577       if ( dash_p(q)!=null ) add_edge_ref(dash_p(q));
22578     }
22579     q=link(q);
22580   }
22581 }
22582
22583 @ One of the things we need to do when we've parsed an \&{addto} or
22584 similar command is find the header of a supposed \&{picture} variable, given
22585 a token list for that variable.  Since the edge structure is about to be
22586 updated, we use |private_edges| to make sure that this is possible.
22587
22588 @<Declare action procedures for use by |do_statement|@>=
22589 pointer mp_find_edges_var (MP mp, pointer t) ;
22590
22591 @ @c pointer mp_find_edges_var (MP mp, pointer t) {
22592   pointer p;
22593   pointer cur_edges; /* the return value */
22594   p=mp_find_variable(mp, t); cur_edges=null;
22595   if ( p==null ) { 
22596     mp_obliterated(mp, t); mp_put_get_error(mp);
22597   } else if ( type(p)!=mp_picture_type )  { 
22598     print_err("Variable "); mp_show_token_list(mp, t,null,1000,0);
22599 @.Variable x is the wrong type@>
22600     mp_print(mp, " is the wrong type ("); 
22601     mp_print_type(mp, type(p)); mp_print_char(mp, ')');
22602     help2("I was looking for a \"known\" picture variable.")
22603          ("So I'll not change anything just now."); 
22604     mp_put_get_error(mp);
22605   } else { 
22606     value(p)=mp_private_edges(mp, value(p));
22607     cur_edges=value(p);
22608   }
22609   mp_flush_node_list(mp, t);
22610   return cur_edges;
22611 };
22612
22613 @ @<Cases of |do_statement|...@>=
22614 case add_to_command: mp_do_add_to(mp); break;
22615 case bounds_command:mp_do_bounds(mp); break;
22616
22617 @ @<Put each...@>=
22618 mp_primitive(mp, "clip",bounds_command,mp_start_clip_code);
22619 @:clip_}{\&{clip} primitive@>
22620 mp_primitive(mp, "setbounds",bounds_command,mp_start_bounds_code);
22621 @:set_bounds_}{\&{setbounds} primitive@>
22622
22623 @ @<Cases of |print_cmd...@>=
22624 case bounds_command: 
22625   if ( m==mp_start_clip_code ) mp_print(mp, "clip");
22626   else mp_print(mp, "setbounds");
22627   break;
22628
22629 @ The following function parses the beginning of an \&{addto} or \&{clip}
22630 command: it expects a variable name followed by a token with |cur_cmd=sep|
22631 and then an expression.  The function returns the token list for the variable
22632 and stores the command modifier for the separator token in the global variable
22633 |last_add_type|.  We must be careful because this variable might get overwritten
22634 any time we call |get_x_next|.
22635
22636 @<Glob...@>=
22637 quarterword last_add_type;
22638   /* command modifier that identifies the last \&{addto} command */
22639
22640 @ @<Declare action procedures for use by |do_statement|@>=
22641 pointer mp_start_draw_cmd (MP mp,quarterword sep) ;
22642
22643 @ @c pointer mp_start_draw_cmd (MP mp,quarterword sep) {
22644   pointer lhv; /* variable to add to left */
22645   quarterword add_type=0; /* value to be returned in |last_add_type| */
22646   lhv=null;
22647   mp_get_x_next(mp); mp->var_flag=sep; mp_scan_primary(mp);
22648   if ( mp->cur_type!=mp_token_list ) {
22649     @<Abandon edges command because there's no variable@>;
22650   } else  { 
22651     lhv=mp->cur_exp; add_type=mp->cur_mod;
22652     mp->cur_type=mp_vacuous; mp_get_x_next(mp); mp_scan_expression(mp);
22653   }
22654   mp->last_add_type=add_type;
22655   return lhv;
22656 }
22657
22658 @ @<Abandon edges command because there's no variable@>=
22659 { exp_err("Not a suitable variable");
22660 @.Not a suitable variable@>
22661   help4("At this point I needed to see the name of a picture variable.")
22662     ("(Or perhaps you have indeed presented me with one; I might")
22663     ("have missed it, if it wasn't followed by the proper token.)")
22664     ("So I'll not change anything just now.");
22665   mp_put_get_flush_error(mp, 0);
22666 }
22667
22668 @ Here is an example of how to use |start_draw_cmd|.
22669
22670 @<Declare action procedures for use by |do_statement|@>=
22671 void mp_do_bounds (MP mp) ;
22672
22673 @ @c void mp_do_bounds (MP mp) {
22674   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22675   pointer p; /* for list manipulation */
22676   integer m; /* initial value of |cur_mod| */
22677   m=mp->cur_mod;
22678   lhv=mp_start_draw_cmd(mp, to_token);
22679   if ( lhv!=null ) {
22680     lhe=mp_find_edges_var(mp, lhv);
22681     if ( lhe==null ) {
22682       mp_flush_cur_exp(mp, 0);
22683     } else if ( mp->cur_type!=mp_path_type ) {
22684       exp_err("Improper `clip'");
22685 @.Improper `addto'@>
22686       help2("This expression should have specified a known path.")
22687         ("So I'll not change anything just now."); 
22688       mp_put_get_flush_error(mp, 0);
22689     } else if ( left_type(mp->cur_exp)==mp_endpoint ) {
22690       @<Complain about a non-cycle@>;
22691     } else {
22692       @<Make |cur_exp| into a \&{setbounds} or clipping path and add it to |lhe|@>;
22693     }
22694   }
22695 }
22696
22697 @ @<Complain about a non-cycle@>=
22698 { print_err("Not a cycle");
22699 @.Not a cycle@>
22700   help2("That contour should have ended with `..cycle' or `&cycle'.")
22701     ("So I'll not change anything just now."); mp_put_get_error(mp);
22702 }
22703
22704 @ @<Make |cur_exp| into a \&{setbounds} or clipping path and add...@>=
22705 { p=mp_new_bounds_node(mp, mp->cur_exp,m);
22706   link(p)=link(dummy_loc(lhe));
22707   link(dummy_loc(lhe))=p;
22708   if ( obj_tail(lhe)==dummy_loc(lhe) ) obj_tail(lhe)=p;
22709   p=mp_get_node(mp, mp->gr_object_size[stop_type(m)]);
22710   type(p)=stop_type(m);
22711   link(obj_tail(lhe))=p;
22712   obj_tail(lhe)=p;
22713   mp_init_bbox(mp, lhe);
22714 }
22715
22716 @ The |do_add_to| procedure is a little like |do_clip| but there are a lot more
22717 cases to deal with.
22718
22719 @<Declare action procedures for use by |do_statement|@>=
22720 void mp_do_add_to (MP mp) ;
22721
22722 @ @c void mp_do_add_to (MP mp) {
22723   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22724   pointer p; /* the graphical object or list for |scan_with_list| to update */
22725   pointer e; /* an edge structure to be merged */
22726   quarterword add_type; /* |also_code|, |contour_code|, or |double_path_code| */
22727   lhv=mp_start_draw_cmd(mp, thing_to_add); add_type=mp->last_add_type;
22728   if ( lhv!=null ) {
22729     if ( add_type==also_code ) {
22730       @<Make sure the current expression is a suitable picture and set |e| and |p|
22731        appropriately@>;
22732     } else {
22733       @<Create a graphical object |p| based on |add_type| and the current
22734         expression@>;
22735     }
22736     mp_scan_with_list(mp, p);
22737     @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>;
22738   }
22739 }
22740
22741 @ Setting |p:=null| causes the $\langle$with list$\rangle$ to be ignored;
22742 setting |e:=null| prevents anything from being added to |lhe|.
22743
22744 @ @<Make sure the current expression is a suitable picture and set |e|...@>=
22745
22746   p=null; e=null;
22747   if ( mp->cur_type!=mp_picture_type ) {
22748     exp_err("Improper `addto'");
22749 @.Improper `addto'@>
22750     help2("This expression should have specified a known picture.")
22751       ("So I'll not change anything just now."); mp_put_get_flush_error(mp, 0);
22752   } else { 
22753     e=mp_private_edges(mp, mp->cur_exp); mp->cur_type=mp_vacuous;
22754     p=link(dummy_loc(e));
22755   }
22756 }
22757
22758 @ In this case |add_type<>also_code| so setting |p:=null| suppresses future
22759 attempts to add to the edge structure.
22760
22761 @<Create a graphical object |p| based on |add_type| and the current...@>=
22762 { e=null; p=null;
22763   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
22764   if ( mp->cur_type!=mp_path_type ) {
22765     exp_err("Improper `addto'");
22766 @.Improper `addto'@>
22767     help2("This expression should have specified a known path.")
22768       ("So I'll not change anything just now."); 
22769     mp_put_get_flush_error(mp, 0);
22770   } else if ( add_type==contour_code ) {
22771     if ( left_type(mp->cur_exp)==mp_endpoint ) {
22772       @<Complain about a non-cycle@>;
22773     } else { 
22774       p=mp_new_fill_node(mp, mp->cur_exp);
22775       mp->cur_type=mp_vacuous;
22776     }
22777   } else { 
22778     p=mp_new_stroked_node(mp, mp->cur_exp);
22779     mp->cur_type=mp_vacuous;
22780   }
22781 }
22782
22783 @ @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>=
22784 lhe=mp_find_edges_var(mp, lhv);
22785 if ( lhe==null ) {
22786   if ( (e==null)&&(p!=null) ) e=mp_toss_gr_object(mp, p);
22787   if ( e!=null ) delete_edge_ref(e);
22788 } else if ( add_type==also_code ) {
22789   if ( e!=null ) {
22790     @<Merge |e| into |lhe| and delete |e|@>;
22791   } else { 
22792     do_nothing;
22793   }
22794 } else if ( p!=null ) {
22795   link(obj_tail(lhe))=p;
22796   obj_tail(lhe)=p;
22797   if ( add_type==double_path_code )
22798     if ( pen_p(p)==null ) 
22799       pen_p(p)=mp_get_pen_circle(mp, 0);
22800 }
22801
22802 @ @<Merge |e| into |lhe| and delete |e|@>=
22803 { if ( link(dummy_loc(e))!=null ) {
22804     link(obj_tail(lhe))=link(dummy_loc(e));
22805     obj_tail(lhe)=obj_tail(e);
22806     obj_tail(e)=dummy_loc(e);
22807     link(dummy_loc(e))=null;
22808     mp_flush_dash_list(mp, lhe);
22809   }
22810   mp_toss_edges(mp, e);
22811 }
22812
22813 @ @<Cases of |do_statement|...@>=
22814 case ship_out_command: mp_do_ship_out(mp); break;
22815
22816 @ @<Declare action procedures for use by |do_statement|@>=
22817 @<Declare the function called |tfm_check|@>;
22818 @<Declare the \ps\ output procedures@>;
22819 void mp_do_ship_out (MP mp) ;
22820
22821 @ @c void mp_do_ship_out (MP mp) {
22822   integer c; /* the character code */
22823   mp_get_x_next(mp); mp_scan_expression(mp);
22824   if ( mp->cur_type!=mp_picture_type ) {
22825     @<Complain that it's not a known picture@>;
22826   } else { 
22827     c=mp_round_unscaled(mp, mp->internal[mp_char_code]) % 256;
22828     if ( c<0 ) c=c+256;
22829     @<Store the width information for character code~|c|@>;
22830     mp_ship_out(mp, mp->cur_exp);
22831     mp_flush_cur_exp(mp, 0);
22832   }
22833 }
22834
22835 @ @<Complain that it's not a known picture@>=
22836
22837   exp_err("Not a known picture");
22838   help1("I can only output known pictures.");
22839   mp_put_get_flush_error(mp, 0);
22840 }
22841
22842 @ The \&{everyjob} command simply assigns a nonzero value to the global variable
22843 |start_sym|.
22844
22845 @<Cases of |do_statement|...@>=
22846 case every_job_command: 
22847   mp_get_symbol(mp); mp->start_sym=mp->cur_sym; mp_get_x_next(mp);
22848   break;
22849
22850 @ @<Glob...@>=
22851 halfword start_sym; /* a symbolic token to insert at beginning of job */
22852
22853 @ @<Set init...@>=
22854 mp->start_sym=0;
22855
22856 @ Finally, we have only the ``message'' commands remaining.
22857
22858 @d message_code 0
22859 @d err_message_code 1
22860 @d err_help_code 2
22861 @d filename_template_code 3
22862 @d print_with_leading_zeroes(A)  g = mp->pool_ptr;
22863               mp_print_int(mp, (A)); g = mp->pool_ptr-g;
22864               if ( f>g ) {
22865                 mp->pool_ptr = mp->pool_ptr - g;
22866                 while ( f>g ) {
22867                   mp_print_char(mp, '0');
22868                   decr(f);
22869                   };
22870                 mp_print_int(mp, (A));
22871               };
22872               f = 0
22873
22874 @<Put each...@>=
22875 mp_primitive(mp, "message",message_command,message_code);
22876 @:message_}{\&{message} primitive@>
22877 mp_primitive(mp, "errmessage",message_command,err_message_code);
22878 @:err_message_}{\&{errmessage} primitive@>
22879 mp_primitive(mp, "errhelp",message_command,err_help_code);
22880 @:err_help_}{\&{errhelp} primitive@>
22881 mp_primitive(mp, "filenametemplate",message_command,filename_template_code);
22882 @:filename_template_}{\&{filenametemplate} primitive@>
22883
22884 @ @<Cases of |print_cmd...@>=
22885 case message_command: 
22886   if ( m<err_message_code ) mp_print(mp, "message");
22887   else if ( m==err_message_code ) mp_print(mp, "errmessage");
22888   else if ( m==filename_template_code ) mp_print(mp, "filenametemplate");
22889   else mp_print(mp, "errhelp");
22890   break;
22891
22892 @ @<Cases of |do_statement|...@>=
22893 case message_command: mp_do_message(mp); break;
22894
22895 @ @<Declare action procedures for use by |do_statement|@>=
22896 @<Declare a procedure called |no_string_err|@>;
22897 void mp_do_message (MP mp) ;
22898
22899
22900 @c void mp_do_message (MP mp) {
22901   int m; /* the type of message */
22902   m=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
22903   if ( mp->cur_type!=mp_string_type )
22904     mp_no_string_err(mp, "A message should be a known string expression.");
22905   else {
22906     switch (m) {
22907     case message_code: 
22908       mp_print_nl(mp, ""); mp_print_str(mp, mp->cur_exp);
22909       break;
22910     case err_message_code:
22911       @<Print string |cur_exp| as an error message@>;
22912       break;
22913     case err_help_code:
22914       @<Save string |cur_exp| as the |err_help|@>;
22915       break;
22916     case filename_template_code:
22917       @<Save the filename template@>;
22918       break;
22919     } /* there are no other cases */
22920   }
22921   mp_flush_cur_exp(mp, 0);
22922 }
22923
22924 @ @<Declare a procedure called |no_string_err|@>=
22925 void mp_no_string_err (MP mp,char *s) { 
22926    exp_err("Not a string");
22927 @.Not a string@>
22928   help1(s);
22929   mp_put_get_error(mp);
22930 }
22931
22932 @ The global variable |err_help| is zero when the user has most recently
22933 given an empty help string, or if none has ever been given.
22934
22935 @<Save string |cur_exp| as the |err_help|@>=
22936
22937   if ( mp->err_help!=0 ) delete_str_ref(mp->err_help);
22938   if ( length(mp->cur_exp)==0 ) mp->err_help=0;
22939   else  { mp->err_help=mp->cur_exp; add_str_ref(mp->err_help); }
22940 }
22941
22942 @ If \&{errmessage} occurs often in |mp_scroll_mode|, without user-defined
22943 \&{errhelp}, we don't want to give a long help message each time. So we
22944 give a verbose explanation only once.
22945
22946 @<Glob...@>=
22947 boolean long_help_seen; /* has the long \.{\\errmessage} help been used? */
22948
22949 @ @<Set init...@>=mp->long_help_seen=false;
22950
22951 @ @<Print string |cur_exp| as an error message@>=
22952
22953   print_err(""); mp_print_str(mp, mp->cur_exp);
22954   if ( mp->err_help!=0 ) {
22955     mp->use_err_help=true;
22956   } else if ( mp->long_help_seen ) { 
22957     help1("(That was another `errmessage'.)") ; 
22958   } else  { 
22959    if ( mp->interaction<mp_error_stop_mode ) mp->long_help_seen=true;
22960     help4("This error message was generated by an `errmessage'")
22961      ("command, so I can\'t give any explicit help.")
22962      ("Pretend that you're Miss Marple: Examine all clues,")
22963 @^Marple, Jane@>
22964      ("and deduce the truth by inspired guesses.");
22965   }
22966   mp_put_get_error(mp); mp->use_err_help=false;
22967 }
22968
22969 @ @<Cases of |do_statement|...@>=
22970 case write_command: mp_do_write(mp); break;
22971
22972 @ @<Declare action procedures for use by |do_statement|@>=
22973 void mp_do_write (MP mp) ;
22974
22975 @ @c void mp_do_write (MP mp) {
22976   str_number t; /* the line of text to be written */
22977   write_index n,n0; /* for searching |wr_fname| and |wr_file| arrays */
22978   int old_setting; /* for saving |selector| during output */
22979   mp_get_x_next(mp);
22980   mp_scan_expression(mp);
22981   if ( mp->cur_type!=mp_string_type ) {
22982     mp_no_string_err(mp, "The text to be written should be a known string expression");
22983   } else if ( mp->cur_cmd!=to_token ) { 
22984     print_err("Missing `to' clause");
22985     help1("A write command should end with `to <filename>'");
22986     mp_put_get_error(mp);
22987   } else { 
22988     t=mp->cur_exp; mp->cur_type=mp_vacuous;
22989     mp_get_x_next(mp);
22990     mp_scan_expression(mp);
22991     if ( mp->cur_type!=mp_string_type )
22992       mp_no_string_err(mp, "I can\'t write to that file name.  It isn't a known string");
22993     else {
22994       @<Write |t| to the file named by |cur_exp|@>;
22995     }
22996     delete_str_ref(t);
22997   }
22998   mp_flush_cur_exp(mp, 0);
22999 }
23000
23001 @ @<Write |t| to the file named by |cur_exp|@>=
23002
23003   @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if
23004     |cur_exp| must be inserted@>;
23005   if ( mp_str_vs_str(mp, t,mp->eof_line)==0 ) {
23006     @<Record the end of file on |wr_file[n]|@>;
23007   } else { 
23008     old_setting=mp->selector;
23009     mp->selector=n+write_file;
23010     mp_print_str(mp, t); mp_print_ln(mp);
23011     mp->selector = old_setting;
23012   }
23013 }
23014
23015 @ @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if...@>=
23016 {
23017   char *fn = str(mp->cur_exp);
23018   n=mp->write_files;
23019   n0=mp->write_files;
23020   while (mp_xstrcmp(fn,mp->wr_fname[n])!=0) { 
23021     if ( n==0 ) { /* bottom reached */
23022           if ( n0==mp->write_files ) {
23023         if ( mp->write_files<mp->max_write_files ) {
23024           incr(mp->write_files);
23025         } else {
23026           FILE **wr_file;
23027           char **wr_fname;
23028               write_index l,k;
23029           l = mp->max_write_files + (mp->max_write_files>>2);
23030           wr_file = xmalloc((l+1),sizeof(FILE *));
23031           wr_fname = xmalloc((l+1),sizeof(char *));
23032               for (k=0;k<=l;k++) {
23033             if (k<=mp->max_write_files) {
23034                   wr_file[k]=mp->wr_file[k]; 
23035               wr_fname[k]=mp->wr_fname[k];
23036             } else {
23037                   wr_file[k]=0; 
23038               wr_fname[k]=NULL;
23039             }
23040           }
23041               xfree(mp->wr_file); xfree(mp->wr_fname);
23042           mp->max_write_files = l;
23043           mp->wr_file = wr_file;
23044           mp->wr_fname = wr_fname;
23045         }
23046       }
23047       n=n0;
23048       mp_open_write_file(mp, fn ,n);
23049     } else { 
23050       decr(n);
23051           if ( mp->wr_fname[n]==NULL )  n0=n; 
23052     }
23053   }
23054 }
23055
23056 @ @<Record the end of file on |wr_file[n]|@>=
23057 { fclose(mp->wr_file[n]);
23058   xfree(mp->wr_fname[n]);
23059   mp->wr_fname[n]=NULL;
23060   if ( n==mp->write_files-1 ) mp->write_files=n;
23061 }
23062
23063
23064 @* \[42] Writing font metric data.
23065 \TeX\ gets its knowledge about fonts from font metric files, also called
23066 \.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
23067 but other programs know about them too. One of \MP's duties is to
23068 write \.{TFM} files so that the user's fonts can readily be
23069 applied to typesetting.
23070 @:TFM files}{\.{TFM} files@>
23071 @^font metric files@>
23072
23073 The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
23074 Since the number of bytes is always a multiple of~4, we could
23075 also regard the file as a sequence of 32-bit words, but \MP\ uses the
23076 byte interpretation. The format of \.{TFM} files was designed by
23077 Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
23078 @^Ramshaw, Lyle Harold@>
23079 of information in a compact but useful form.
23080
23081 @<Glob...@>=
23082 FILE * tfm_file; /* the font metric output goes here */
23083 char * metric_file_name; /* full name of the font metric file */
23084
23085 @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
23086 integers that give the lengths of the various subsequent portions
23087 of the file. These twelve integers are, in order:
23088 $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
23089 |lf|&length of the entire file, in words;\cr
23090 |lh|&length of the header data, in words;\cr
23091 |bc|&smallest character code in the font;\cr
23092 |ec|&largest character code in the font;\cr
23093 |nw|&number of words in the width table;\cr
23094 |nh|&number of words in the height table;\cr
23095 |nd|&number of words in the depth table;\cr
23096 |ni|&number of words in the italic correction table;\cr
23097 |nl|&number of words in the lig/kern table;\cr
23098 |nk|&number of words in the kern table;\cr
23099 |ne|&number of words in the extensible character table;\cr
23100 |np|&number of font parameter words.\cr}}$$
23101 They are all nonnegative and less than $2^{15}$. We must have |bc-1<=ec<=255|,
23102 |ne<=256|, and
23103 $$\hbox{|lf=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
23104 Note that a font may contain as many as 256 characters (if |bc=0| and |ec=255|),
23105 and as few as 0 characters (if |bc=ec+1|).
23106
23107 Incidentally, when two or more 8-bit bytes are combined to form an integer of
23108 16 or more bits, the most significant bytes appear first in the file.
23109 This is called BigEndian order.
23110 @^BigEndian order@>
23111
23112 @ The rest of the \.{TFM} file may be regarded as a sequence of ten data
23113 arrays.
23114
23115 The most important data type used here is a |fix_word|, which is
23116 a 32-bit representation of a binary fraction. A |fix_word| is a signed
23117 quantity, with the two's complement of the entire word used to represent
23118 negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
23119 binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
23120 the smallest is $-2048$. We will see below, however, that all but two of
23121 the |fix_word| values must lie between $-16$ and $+16$.
23122
23123 @ The first data array is a block of header information, which contains
23124 general facts about the font. The header must contain at least two words,
23125 |header[0]| and |header[1]|, whose meaning is explained below.  Additional
23126 header information of use to other software routines might also be
23127 included, and \MP\ will generate it if the \.{headerbyte} command occurs.
23128 For example, 16 more words of header information are in use at the Xerox
23129 Palo Alto Research Center; the first ten specify the character coding
23130 scheme used (e.g., `\.{XEROX TEXT}' or `\.{TEX MATHSY}'), the next five
23131 give the font family name (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
23132 last gives the ``face byte.''
23133
23134 \yskip\hang|header[0]| is a 32-bit check sum that \MP\ will copy into
23135 the \.{GF} output file. This helps ensure consistency between files,
23136 since \TeX\ records the check sums from the \.{TFM}'s it reads, and these
23137 should match the check sums on actual fonts that are used.  The actual
23138 relation between this check sum and the rest of the \.{TFM} file is not
23139 important; the check sum is simply an identification number with the
23140 property that incompatible fonts almost always have distinct check sums.
23141 @^check sum@>
23142
23143 \yskip\hang|header[1]| is a |fix_word| containing the design size of the
23144 font, in units of \TeX\ points. This number must be at least 1.0; it is
23145 fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
23146 font, i.e., a font that was designed to look best at a 10-point size,
23147 whatever that really means. When a \TeX\ user asks for a font `\.{at}
23148 $\delta$ \.{pt}', the effect is to override the design size and replace it
23149 by $\delta$, and to multiply the $x$ and~$y$ coordinates of the points in
23150 the font image by a factor of $\delta$ divided by the design size.  {\sl
23151 All other dimensions in the\/ \.{TFM} file are |fix_word|\kern-1pt\
23152 numbers in design-size units.} Thus, for example, the value of |param[6]|,
23153 which defines the \.{em} unit, is often the |fix_word| value $2^{20}=1.0$,
23154 since many fonts have a design size equal to one em.  The other dimensions
23155 must be less than 16 design-size units in absolute value; thus,
23156 |header[1]| and |param[1]| are the only |fix_word| entries in the whole
23157 \.{TFM} file whose first byte might be something besides 0 or 255.
23158
23159 @ Next comes the |char_info| array, which contains one |char_info_word|
23160 per character. Each word in this part of the file contains six fields
23161 packed into four bytes as follows.
23162
23163 \yskip\hang first byte: |width_index| (8 bits)\par
23164 \hang second byte: |height_index| (4 bits) times 16, plus |depth_index|
23165   (4~bits)\par
23166 \hang third byte: |italic_index| (6 bits) times 4, plus |tag|
23167   (2~bits)\par
23168 \hang fourth byte: |remainder| (8 bits)\par
23169 \yskip\noindent
23170 The actual width of a character is \\{width}|[width_index]|, in design-size
23171 units; this is a device for compressing information, since many characters
23172 have the same width. Since it is quite common for many characters
23173 to have the same height, depth, or italic correction, the \.{TFM} format
23174 imposes a limit of 16 different heights, 16 different depths, and
23175 64 different italic corrections.
23176
23177 Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
23178 \\{italic}[0]=0$ should always hold, so that an index of zero implies a
23179 value of zero.  The |width_index| should never be zero unless the
23180 character does not exist in the font, since a character is valid if and
23181 only if it lies between |bc| and |ec| and has a nonzero |width_index|.
23182
23183 @ The |tag| field in a |char_info_word| has four values that explain how to
23184 interpret the |remainder| field.
23185
23186 \yskip\hang|tag=0| (|no_tag|) means that |remainder| is unused.\par
23187 \hang|tag=1| (|lig_tag|) means that this character has a ligature/kerning
23188 program starting at location |remainder| in the |lig_kern| array.\par
23189 \hang|tag=2| (|list_tag|) means that this character is part of a chain of
23190 characters of ascending sizes, and not the largest in the chain.  The
23191 |remainder| field gives the character code of the next larger character.\par
23192 \hang|tag=3| (|ext_tag|) means that this character code represents an
23193 extensible character, i.e., a character that is built up of smaller pieces
23194 so that it can be made arbitrarily large. The pieces are specified in
23195 |exten[remainder]|.\par
23196 \yskip\noindent
23197 Characters with |tag=2| and |tag=3| are treated as characters with |tag=0|
23198 unless they are used in special circumstances in math formulas. For example,
23199 \TeX's \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
23200 operation looks for both |list_tag| and |ext_tag|.
23201
23202 @d no_tag 0 /* vanilla character */
23203 @d lig_tag 1 /* character has a ligature/kerning program */
23204 @d list_tag 2 /* character has a successor in a charlist */
23205 @d ext_tag 3 /* character is extensible */
23206
23207 @ The |lig_kern| array contains instructions in a simple programming language
23208 that explains what to do for special letter pairs. Each word in this array is a
23209 |lig_kern_command| of four bytes.
23210
23211 \yskip\hang first byte: |skip_byte|, indicates that this is the final program
23212   step if the byte is 128 or more, otherwise the next step is obtained by
23213   skipping this number of intervening steps.\par
23214 \hang second byte: |next_char|, ``if |next_char| follows the current character,
23215   then perform the operation and stop, otherwise continue.''\par
23216 \hang third byte: |op_byte|, indicates a ligature step if less than~128,
23217   a kern step otherwise.\par
23218 \hang fourth byte: |remainder|.\par
23219 \yskip\noindent
23220 In a kern step, an
23221 additional space equal to |kern[256*(op_byte-128)+remainder]| is inserted
23222 between the current character and |next_char|. This amount is
23223 often negative, so that the characters are brought closer together
23224 by kerning; but it might be positive.
23225
23226 There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
23227 $0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
23228 |remainder| is inserted between the current character and |next_char|;
23229 then the current character is deleted if $b=0$, and |next_char| is
23230 deleted if $c=0$; then we pass over $a$~characters to reach the next
23231 current character (which may have a ligature/kerning program of its own).
23232
23233 If the very first instruction of the |lig_kern| array has |skip_byte=255|,
23234 the |next_char| byte is the so-called right boundary character of this font;
23235 the value of |next_char| need not lie between |bc| and~|ec|.
23236 If the very last instruction of the |lig_kern| array has |skip_byte=255|,
23237 there is a special ligature/kerning program for a left boundary character,
23238 beginning at location |256*op_byte+remainder|.
23239 The interpretation is that \TeX\ puts implicit boundary characters
23240 before and after each consecutive string of characters from the same font.
23241 These implicit characters do not appear in the output, but they can affect
23242 ligatures and kerning.
23243
23244 If the very first instruction of a character's |lig_kern| program has
23245 |skip_byte>128|, the program actually begins in location
23246 |256*op_byte+remainder|. This feature allows access to large |lig_kern|
23247 arrays, because the first instruction must otherwise
23248 appear in a location |<=255|.
23249
23250 Any instruction with |skip_byte>128| in the |lig_kern| array must satisfy
23251 the condition
23252 $$\hbox{|256*op_byte+remainder<nl|.}$$
23253 If such an instruction is encountered during
23254 normal program execution, it denotes an unconditional halt; no ligature
23255 command is performed.
23256
23257 @d stop_flag (128)
23258   /* value indicating `\.{STOP}' in a lig/kern program */
23259 @d kern_flag (128) /* op code for a kern step */
23260 @d skip_byte(A) mp->lig_kern[(A)].b0
23261 @d next_char(A) mp->lig_kern[(A)].b1
23262 @d op_byte(A) mp->lig_kern[(A)].b2
23263 @d rem_byte(A) mp->lig_kern[(A)].b3
23264
23265 @ Extensible characters are specified by an |extensible_recipe|, which
23266 consists of four bytes called |top|, |mid|, |bot|, and |rep| (in this
23267 order). These bytes are the character codes of individual pieces used to
23268 build up a large symbol.  If |top|, |mid|, or |bot| are zero, they are not
23269 present in the built-up result. For example, an extensible vertical line is
23270 like an extensible bracket, except that the top and bottom pieces are missing.
23271
23272 Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
23273 if the piece isn't present. Then the extensible characters have the form
23274 $TR^kMR^kB$ from top to bottom, for some |k>=0|, unless $M$ is absent;
23275 in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
23276 The width of the extensible character is the width of $R$; and the
23277 height-plus-depth is the sum of the individual height-plus-depths of the
23278 components used, since the pieces are butted together in a vertical list.
23279
23280 @d ext_top(A) mp->exten[(A)].b0 /* |top| piece in a recipe */
23281 @d ext_mid(A) mp->exten[(A)].b1 /* |mid| piece in a recipe */
23282 @d ext_bot(A) mp->exten[(A)].b2 /* |bot| piece in a recipe */
23283 @d ext_rep(A) mp->exten[(A)].b3 /* |rep| piece in a recipe */
23284
23285 @ The final portion of a \.{TFM} file is the |param| array, which is another
23286 sequence of |fix_word| values.
23287
23288 \yskip\hang|param[1]=slant| is the amount of italic slant, which is used
23289 to help position accents. For example, |slant=.25| means that when you go
23290 up one unit, you also go .25 units to the right. The |slant| is a pure
23291 number; it is the only |fix_word| other than the design size itself that is
23292 not scaled by the design size.
23293
23294 \hang|param[2]=space| is the normal spacing between words in text.
23295 Note that character 040 in the font need not have anything to do with
23296 blank spaces.
23297
23298 \hang|param[3]=space_stretch| is the amount of glue stretching between words.
23299
23300 \hang|param[4]=space_shrink| is the amount of glue shrinking between words.
23301
23302 \hang|param[5]=x_height| is the size of one ex in the font; it is also
23303 the height of letters for which accents don't have to be raised or lowered.
23304
23305 \hang|param[6]=quad| is the size of one em in the font.
23306
23307 \hang|param[7]=extra_space| is the amount added to |param[2]| at the
23308 ends of sentences.
23309
23310 \yskip\noindent
23311 If fewer than seven parameters are present, \TeX\ sets the missing parameters
23312 to zero.
23313
23314 @d slant_code 1
23315 @d space_code 2
23316 @d space_stretch_code 3
23317 @d space_shrink_code 4
23318 @d x_height_code 5
23319 @d quad_code 6
23320 @d extra_space_code 7
23321
23322 @ So that is what \.{TFM} files hold. One of \MP's duties is to output such
23323 information, and it does this all at once at the end of a job.
23324 In order to prepare for such frenetic activity, it squirrels away the
23325 necessary facts in various arrays as information becomes available.
23326
23327 Character dimensions (\&{charwd}, \&{charht}, \&{chardp}, and \&{charic})
23328 are stored respectively in |tfm_width|, |tfm_height|, |tfm_depth|, and
23329 |tfm_ital_corr|. Other information about a character (e.g., about
23330 its ligatures or successors) is accessible via the |char_tag| and
23331 |char_remainder| arrays. Other information about the font as a whole
23332 is kept in additional arrays called |header_byte|, |lig_kern|,
23333 |kern|, |exten|, and |param|.
23334
23335 @d max_tfm_int 32510
23336 @d undefined_label max_tfm_int /* an undefined local label */
23337
23338 @<Glob...@>=
23339 #define TFM_ITEMS 257
23340 eight_bits bc;
23341 eight_bits ec; /* smallest and largest character codes shipped out */
23342 scaled tfm_width[TFM_ITEMS]; /* \&{charwd} values */
23343 scaled tfm_height[TFM_ITEMS]; /* \&{charht} values */
23344 scaled tfm_depth[TFM_ITEMS]; /* \&{chardp} values */
23345 scaled tfm_ital_corr[TFM_ITEMS]; /* \&{charic} values */
23346 boolean char_exists[TFM_ITEMS]; /* has this code been shipped out? */
23347 int char_tag[TFM_ITEMS]; /* |remainder| category */
23348 int char_remainder[TFM_ITEMS]; /* the |remainder| byte */
23349 char *header_byte; /* bytes of the \.{TFM} header */
23350 int header_last; /* last initialized \.{TFM} header byte */
23351 int header_size; /* size of the \.{TFM} header */
23352 four_quarters *lig_kern; /* the ligature/kern table */
23353 short nl; /* the number of ligature/kern steps so far */
23354 scaled *kern; /* distinct kerning amounts */
23355 short nk; /* the number of distinct kerns so far */
23356 four_quarters exten[TFM_ITEMS]; /* extensible character recipes */
23357 short ne; /* the number of extensible characters so far */
23358 scaled *param; /* \&{fontinfo} parameters */
23359 short np; /* the largest \&{fontinfo} parameter specified so far */
23360 short nw;short nh;short nd;short ni; /* sizes of \.{TFM} subtables */
23361 short skip_table[TFM_ITEMS]; /* local label status */
23362 boolean lk_started; /* has there been a lig/kern step in this command yet? */
23363 integer bchar; /* right boundary character */
23364 short bch_label; /* left boundary starting location */
23365 short ll;short lll; /* registers used for lig/kern processing */
23366 short label_loc[257]; /* lig/kern starting addresses */
23367 eight_bits label_char[257]; /* characters for |label_loc| */
23368 short label_ptr; /* highest position occupied in |label_loc| */
23369
23370 @ @<Allocate or initialize ...@>=
23371 mp->header_last = 0; mp->header_size = 128; /* just for init */
23372 mp->header_byte = xmalloc(mp->header_size, sizeof(char));
23373 mp->lig_kern = NULL; /* allocated when needed */
23374 mp->kern = NULL; /* allocated when needed */ 
23375 mp->param = NULL; /* allocated when needed */
23376
23377 @ @<Dealloc variables@>=
23378 xfree(mp->header_byte);
23379 xfree(mp->lig_kern);
23380 xfree(mp->kern);
23381 xfree(mp->param);
23382
23383 @ @<Set init...@>=
23384 for (k=0;k<= 255;k++ ) {
23385   mp->tfm_width[k]=0; mp->tfm_height[k]=0; mp->tfm_depth[k]=0; mp->tfm_ital_corr[k]=0;
23386   mp->char_exists[k]=false; mp->char_tag[k]=no_tag; mp->char_remainder[k]=0;
23387   mp->skip_table[k]=undefined_label;
23388 };
23389 memset(mp->header_byte,0,mp->header_size);
23390 mp->bc=255; mp->ec=0; mp->nl=0; mp->nk=0; mp->ne=0; mp->np=0;
23391 mp->internal[mp_boundary_char]=-unity;
23392 mp->bch_label=undefined_label;
23393 mp->label_loc[0]=-1; mp->label_ptr=0;
23394
23395 @ @<Declarations@>=
23396 scaled mp_tfm_check (MP mp,small_number m) ;
23397
23398 @ @<Declare the function called |tfm_check|@>=
23399 scaled mp_tfm_check (MP mp,small_number m) {
23400   if ( abs(mp->internal[m])>=fraction_half ) {
23401     print_err("Enormous "); mp_print(mp, mp->int_name[m]);
23402 @.Enormous charwd...@>
23403 @.Enormous chardp...@>
23404 @.Enormous charht...@>
23405 @.Enormous charic...@>
23406 @.Enormous designsize...@>
23407     mp_print(mp, " has been reduced");
23408     help1("Font metric dimensions must be less than 2048pt.");
23409     mp_put_get_error(mp);
23410     if ( mp->internal[m]>0 ) return (fraction_half-1);
23411     else return (1-fraction_half);
23412   } else {
23413     return mp->internal[m];
23414   }
23415 }
23416
23417 @ @<Store the width information for character code~|c|@>=
23418 if ( c<mp->bc ) mp->bc=c;
23419 if ( c>mp->ec ) mp->ec=c;
23420 mp->char_exists[c]=true;
23421 mp->tfm_width[c]=mp_tfm_check(mp, mp_char_wd);
23422 mp->tfm_height[c]=mp_tfm_check(mp, mp_char_ht);
23423 mp->tfm_depth[c]=mp_tfm_check(mp, mp_char_dp);
23424 mp->tfm_ital_corr[c]=mp_tfm_check(mp, mp_char_ic)
23425
23426 @ Now let's consider \MP's special \.{TFM}-oriented commands.
23427
23428 @<Cases of |do_statement|...@>=
23429 case tfm_command: mp_do_tfm_command(mp); break;
23430
23431 @ @d char_list_code 0
23432 @d lig_table_code 1
23433 @d extensible_code 2
23434 @d header_byte_code 3
23435 @d font_dimen_code 4
23436
23437 @<Put each...@>=
23438 mp_primitive(mp, "charlist",tfm_command,char_list_code);
23439 @:char_list_}{\&{charlist} primitive@>
23440 mp_primitive(mp, "ligtable",tfm_command,lig_table_code);
23441 @:lig_table_}{\&{ligtable} primitive@>
23442 mp_primitive(mp, "extensible",tfm_command,extensible_code);
23443 @:extensible_}{\&{extensible} primitive@>
23444 mp_primitive(mp, "headerbyte",tfm_command,header_byte_code);
23445 @:header_byte_}{\&{headerbyte} primitive@>
23446 mp_primitive(mp, "fontdimen",tfm_command,font_dimen_code);
23447 @:font_dimen_}{\&{fontdimen} primitive@>
23448
23449 @ @<Cases of |print_cmd...@>=
23450 case tfm_command: 
23451   switch (m) {
23452   case char_list_code:mp_print(mp, "charlist"); break;
23453   case lig_table_code:mp_print(mp, "ligtable"); break;
23454   case extensible_code:mp_print(mp, "extensible"); break;
23455   case header_byte_code:mp_print(mp, "headerbyte"); break;
23456   default: mp_print(mp, "fontdimen"); break;
23457   }
23458   break;
23459
23460 @ @<Declare action procedures for use by |do_statement|@>=
23461 eight_bits mp_get_code (MP mp) ;
23462
23463 @ @c eight_bits mp_get_code (MP mp) { /* scans a character code value */
23464   integer c; /* the code value found */
23465   mp_get_x_next(mp); mp_scan_expression(mp);
23466   if ( mp->cur_type==mp_known ) { 
23467     c=mp_round_unscaled(mp, mp->cur_exp);
23468     if ( c>=0 ) if ( c<256 ) return c;
23469   } else if ( mp->cur_type==mp_string_type ) {
23470     if ( length(mp->cur_exp)==1 )  { 
23471       c=mp->str_pool[mp->str_start[mp->cur_exp]];
23472       return c;
23473     }
23474   }
23475   exp_err("Invalid code has been replaced by 0");
23476 @.Invalid code...@>
23477   help2("I was looking for a number between 0 and 255, or for a")
23478        ("string of length 1. Didn't find it; will use 0 instead.");
23479   mp_put_get_flush_error(mp, 0); c=0;
23480   return c;
23481 };
23482
23483 @ @<Declare action procedures for use by |do_statement|@>=
23484 void mp_set_tag (MP mp,halfword c, small_number t, halfword r) ;
23485
23486 @ @c void mp_set_tag (MP mp,halfword c, small_number t, halfword r) { 
23487   if ( mp->char_tag[c]==no_tag ) {
23488     mp->char_tag[c]=t; mp->char_remainder[c]=r;
23489     if ( t==lig_tag ){ 
23490       incr(mp->label_ptr); mp->label_loc[mp->label_ptr]=r; 
23491       mp->label_char[mp->label_ptr]=c;
23492     }
23493   } else {
23494     @<Complain about a character tag conflict@>;
23495   }
23496 }
23497
23498 @ @<Complain about a character tag conflict@>=
23499
23500   print_err("Character ");
23501   if ( (c>' ')&&(c<127) ) mp_print_char(mp,c);
23502   else if ( c==256 ) mp_print(mp, "||");
23503   else  { mp_print(mp, "code "); mp_print_int(mp, c); };
23504   mp_print(mp, " is already ");
23505 @.Character c is already...@>
23506   switch (mp->char_tag[c]) {
23507   case lig_tag: mp_print(mp, "in a ligtable"); break;
23508   case list_tag: mp_print(mp, "in a charlist"); break;
23509   case ext_tag: mp_print(mp, "extensible"); break;
23510   } /* there are no other cases */
23511   help2("It's not legal to label a character more than once.")
23512     ("So I'll not change anything just now.");
23513   mp_put_get_error(mp); 
23514 }
23515
23516 @ @<Declare action procedures for use by |do_statement|@>=
23517 void mp_do_tfm_command (MP mp) ;
23518
23519 @ @c void mp_do_tfm_command (MP mp) {
23520   int c,cc; /* character codes */
23521   int k; /* index into the |kern| array */
23522   int j; /* index into |header_byte| or |param| */
23523   switch (mp->cur_mod) {
23524   case char_list_code: 
23525     c=mp_get_code(mp);
23526      /* we will store a list of character successors */
23527     while ( mp->cur_cmd==colon )   { 
23528       cc=mp_get_code(mp); mp_set_tag(mp, c,list_tag,cc); c=cc;
23529     };
23530     break;
23531   case lig_table_code: 
23532     if (mp->lig_kern==NULL) 
23533        mp->lig_kern = xmalloc((max_tfm_int+1),sizeof(four_quarters));
23534     if (mp->kern==NULL) 
23535        mp->kern = xmalloc((max_tfm_int+1),sizeof(scaled));
23536     @<Store a list of ligature/kern steps@>;
23537     break;
23538   case extensible_code: 
23539     @<Define an extensible recipe@>;
23540     break;
23541   case header_byte_code: 
23542   case font_dimen_code: 
23543     c=mp->cur_mod; mp_get_x_next(mp);
23544     mp_scan_expression(mp);
23545     if ( (mp->cur_type!=mp_known)||(mp->cur_exp<half_unit) ) {
23546       exp_err("Improper location");
23547 @.Improper location@>
23548       help2("I was looking for a known, positive number.")
23549        ("For safety's sake I'll ignore the present command.");
23550       mp_put_get_error(mp);
23551     } else  { 
23552       j=mp_round_unscaled(mp, mp->cur_exp);
23553       if ( mp->cur_cmd!=colon ) {
23554         mp_missing_err(mp, ":");
23555 @.Missing `:'@>
23556         help1("A colon should follow a headerbyte or fontinfo location.");
23557         mp_back_error(mp);
23558       }
23559       if ( c==header_byte_code ) { 
23560         @<Store a list of header bytes@>;
23561       } else {     
23562         if (mp->param==NULL) 
23563           mp->param = xmalloc((max_tfm_int+1),sizeof(scaled));
23564         @<Store a list of font dimensions@>;
23565       }
23566     }
23567     break;
23568   } /* there are no other cases */
23569 };
23570
23571 @ @<Store a list of ligature/kern steps@>=
23572
23573   mp->lk_started=false;
23574 CONTINUE: 
23575   mp_get_x_next(mp);
23576   if ((mp->cur_cmd==skip_to)&& mp->lk_started )
23577     @<Process a |skip_to| command and |goto done|@>;
23578   if ( mp->cur_cmd==bchar_label ) { c=256; mp->cur_cmd=colon; }
23579   else { mp_back_input(mp); c=mp_get_code(mp); };
23580   if ((mp->cur_cmd==colon)||(mp->cur_cmd==double_colon)) {
23581     @<Record a label in a lig/kern subprogram and |goto continue|@>;
23582   }
23583   if ( mp->cur_cmd==lig_kern_token ) { 
23584     @<Compile a ligature/kern command@>; 
23585   } else  { 
23586     print_err("Illegal ligtable step");
23587 @.Illegal ligtable step@>
23588     help1("I was looking for `=:' or `kern' here.");
23589     mp_back_error(mp); next_char(mp->nl)=qi(0); 
23590     op_byte(mp->nl)=qi(0); rem_byte(mp->nl)=qi(0);
23591     skip_byte(mp->nl)=stop_flag+1; /* this specifies an unconditional stop */
23592   }
23593   if ( mp->nl==max_tfm_int) mp_fatal_error(mp, "ligtable too large");
23594   incr(mp->nl);
23595   if ( mp->cur_cmd==comma ) goto CONTINUE;
23596   if ( skip_byte(mp->nl-1)<stop_flag ) skip_byte(mp->nl-1)=stop_flag;
23597 }
23598 DONE:
23599
23600 @ @<Put each...@>=
23601 mp_primitive(mp, "=:",lig_kern_token,0);
23602 @:=:_}{\.{=:} primitive@>
23603 mp_primitive(mp, "=:|",lig_kern_token,1);
23604 @:=:/_}{\.{=:\char'174} primitive@>
23605 mp_primitive(mp, "=:|>",lig_kern_token,5);
23606 @:=:/>_}{\.{=:\char'174>} primitive@>
23607 mp_primitive(mp, "|=:",lig_kern_token,2);
23608 @:=:/_}{\.{\char'174=:} primitive@>
23609 mp_primitive(mp, "|=:>",lig_kern_token,6);
23610 @:=:/>_}{\.{\char'174=:>} primitive@>
23611 mp_primitive(mp, "|=:|",lig_kern_token,3);
23612 @:=:/_}{\.{\char'174=:\char'174} primitive@>
23613 mp_primitive(mp, "|=:|>",lig_kern_token,7);
23614 @:=:/>_}{\.{\char'174=:\char'174>} primitive@>
23615 mp_primitive(mp, "|=:|>>",lig_kern_token,11);
23616 @:=:/>_}{\.{\char'174=:\char'174>>} primitive@>
23617 mp_primitive(mp, "kern",lig_kern_token,128);
23618 @:kern_}{\&{kern} primitive@>
23619
23620 @ @<Cases of |print_cmd...@>=
23621 case lig_kern_token: 
23622   switch (m) {
23623   case 0:mp_print(mp, "=:"); break;
23624   case 1:mp_print(mp, "=:|"); break;
23625   case 2:mp_print(mp, "|=:"); break;
23626   case 3:mp_print(mp, "|=:|"); break;
23627   case 5:mp_print(mp, "=:|>"); break;
23628   case 6:mp_print(mp, "|=:>"); break;
23629   case 7:mp_print(mp, "|=:|>"); break;
23630   case 11:mp_print(mp, "|=:|>>"); break;
23631   default: mp_print(mp, "kern"); break;
23632   }
23633   break;
23634
23635 @ Local labels are implemented by maintaining the |skip_table| array,
23636 where |skip_table[c]| is either |undefined_label| or the address of the
23637 most recent lig/kern instruction that skips to local label~|c|. In the
23638 latter case, the |skip_byte| in that instruction will (temporarily)
23639 be zero if there were no prior skips to this label, or it will be the
23640 distance to the prior skip.
23641
23642 We may need to cancel skips that span more than 127 lig/kern steps.
23643
23644 @d cancel_skips(A) mp->ll=(A);
23645   do {  
23646     mp->lll=qo(skip_byte(mp->ll)); 
23647     skip_byte(mp->ll)=stop_flag; mp->ll=mp->ll-mp->lll;
23648   } while (mp->lll!=0)
23649 @d skip_error(A) { print_err("Too far to skip");
23650 @.Too far to skip@>
23651   help1("At most 127 lig/kern steps can separate skipto1 from 1::.");
23652   mp_error(mp); cancel_skips((A));
23653   }
23654
23655 @<Process a |skip_to| command and |goto done|@>=
23656
23657   c=mp_get_code(mp);
23658   if ( mp->nl-mp->skip_table[c]>128 ) { /* |skip_table[c]<<nl<=undefined_label| */
23659     skip_error(mp->skip_table[c]); mp->skip_table[c]=undefined_label;
23660   }
23661   if ( mp->skip_table[c]==undefined_label ) skip_byte(mp->nl-1)=qi(0);
23662   else skip_byte(mp->nl-1)=qi(mp->nl-mp->skip_table[c]-1);
23663   mp->skip_table[c]=mp->nl-1; goto DONE;
23664 }
23665
23666 @ @<Record a label in a lig/kern subprogram and |goto continue|@>=
23667
23668   if ( mp->cur_cmd==colon ) {
23669     if ( c==256 ) mp->bch_label=mp->nl;
23670     else mp_set_tag(mp, c,lig_tag,mp->nl);
23671   } else if ( mp->skip_table[c]<undefined_label ) {
23672     mp->ll=mp->skip_table[c]; mp->skip_table[c]=undefined_label;
23673     do {  
23674       mp->lll=qo(skip_byte(mp->ll));
23675       if ( mp->nl-mp->ll>128 ) {
23676         skip_error(mp->ll); goto CONTINUE;
23677       }
23678       skip_byte(mp->ll)=qi(mp->nl-mp->ll-1); mp->ll=mp->ll-mp->lll;
23679     } while (mp->lll!=0);
23680   }
23681   goto CONTINUE;
23682 }
23683
23684 @ @<Compile a ligature/kern...@>=
23685
23686   next_char(mp->nl)=qi(c); skip_byte(mp->nl)=qi(0);
23687   if ( mp->cur_mod<128 ) { /* ligature op */
23688     op_byte(mp->nl)=qi(mp->cur_mod); rem_byte(mp->nl)=qi(mp_get_code(mp));
23689   } else { 
23690     mp_get_x_next(mp); mp_scan_expression(mp);
23691     if ( mp->cur_type!=mp_known ) {
23692       exp_err("Improper kern");
23693 @.Improper kern@>
23694       help2("The amount of kern should be a known numeric value.")
23695         ("I'm zeroing this one. Proceed, with fingers crossed.");
23696       mp_put_get_flush_error(mp, 0);
23697     }
23698     mp->kern[mp->nk]=mp->cur_exp;
23699     k=0; 
23700     while ( mp->kern[k]!=mp->cur_exp ) incr(k);
23701     if ( k==mp->nk ) {
23702       if ( mp->nk==max_tfm_int ) mp_fatal_error(mp, "too many TFM kerns");
23703       incr(mp->nk);
23704     }
23705     op_byte(mp->nl)=kern_flag+(k / 256);
23706     rem_byte(mp->nl)=qi((k % 256));
23707   }
23708   mp->lk_started=true;
23709 }
23710
23711 @ @d missing_extensible_punctuation(A) 
23712   { mp_missing_err(mp, (A));
23713 @.Missing `\char`\#'@>
23714   help1("I'm processing `extensible c: t,m,b,r'."); mp_back_error(mp);
23715   }
23716
23717 @<Define an extensible recipe@>=
23718
23719   if ( mp->ne==256 ) mp_fatal_error(mp, "too many extensible recipies");
23720   c=mp_get_code(mp); mp_set_tag(mp, c,ext_tag,mp->ne);
23721   if ( mp->cur_cmd!=colon ) missing_extensible_punctuation(":");
23722   ext_top(mp->ne)=qi(mp_get_code(mp));
23723   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23724   ext_mid(mp->ne)=qi(mp_get_code(mp));
23725   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23726   ext_bot(mp->ne)=qi(mp_get_code(mp));
23727   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23728   ext_rep(mp->ne)=qi(mp_get_code(mp));
23729   incr(mp->ne);
23730 }
23731
23732 @ The header could contain ASCII zeroes, so can't use |strdup|.
23733
23734 @<Store a list of header bytes@>=
23735 do {  
23736   if ( j>=mp->header_size ) {
23737     int l = mp->header_size + (mp->header_size >> 2);
23738     char *t = xmalloc(l,sizeof(char));
23739     memset(t,0,l); 
23740     memcpy(t,mp->header_byte,mp->header_size);
23741     xfree (mp->header_byte);
23742     mp->header_byte = t;
23743     mp->header_size = l;
23744   }
23745   mp->header_byte[j]=mp_get_code(mp); 
23746   incr(j); incr(mp->header_last);
23747 } while (mp->cur_cmd==comma)
23748
23749 @ @<Store a list of font dimensions@>=
23750 do {  
23751   if ( j>max_tfm_int ) mp_fatal_error(mp, "too many fontdimens");
23752   while ( j>mp->np ) { incr(mp->np); mp->param[mp->np]=0; };
23753   mp_get_x_next(mp); mp_scan_expression(mp);
23754   if ( mp->cur_type!=mp_known ){ 
23755     exp_err("Improper font parameter");
23756 @.Improper font parameter@>
23757     help1("I'm zeroing this one. Proceed, with fingers crossed.");
23758     mp_put_get_flush_error(mp, 0);
23759   }
23760   mp->param[j]=mp->cur_exp; incr(j);
23761 } while (mp->cur_cmd==comma)
23762
23763 @ OK: We've stored all the data that is needed for the \.{TFM} file.
23764 All that remains is to output it in the correct format.
23765
23766 An interesting problem needs to be solved in this connection, because
23767 the \.{TFM} format allows at most 256~widths, 16~heights, 16~depths,
23768 and 64~italic corrections. If the data has more distinct values than
23769 this, we want to meet the necessary restrictions by perturbing the
23770 given values as little as possible.
23771
23772 \MP\ solves this problem in two steps. First the values of a given
23773 kind (widths, heights, depths, or italic corrections) are sorted;
23774 then the list of sorted values is perturbed, if necessary.
23775
23776 The sorting operation is facilitated by having a special node of
23777 essentially infinite |value| at the end of the current list.
23778
23779 @<Initialize table entries...@>=
23780 value(inf_val)=fraction_four;
23781
23782 @ Straight linear insertion is good enough for sorting, since the lists
23783 are usually not terribly long. As we work on the data, the current list
23784 will start at |link(temp_head)| and end at |inf_val|; the nodes in this
23785 list will be in increasing order of their |value| fields.
23786
23787 Given such a list, the |sort_in| function takes a value and returns a pointer
23788 to where that value can be found in the list. The value is inserted in
23789 the proper place, if necessary.
23790
23791 At the time we need to do these operations, most of \MP's work has been
23792 completed, so we will have plenty of memory to play with. The value nodes
23793 that are allocated for sorting will never be returned to free storage.
23794
23795 @d clear_the_list link(temp_head)=inf_val
23796
23797 @c pointer mp_sort_in (MP mp,scaled v) {
23798   pointer p,q,r; /* list manipulation registers */
23799   p=temp_head;
23800   while (1) { 
23801     q=link(p);
23802     if ( v<=value(q) ) break;
23803     p=q;
23804   }
23805   if ( v<value(q) ) {
23806     r=mp_get_node(mp, value_node_size); value(r)=v; link(r)=q; link(p)=r;
23807   }
23808   return link(p);
23809 }
23810
23811 @ Now we come to the interesting part, where we reduce the list if necessary
23812 until it has the required size. The |min_cover| routine is basic to this
23813 process; it computes the minimum number~|m| such that the values of the
23814 current sorted list can be covered by |m|~intervals of width~|d|. It
23815 also sets the global value |perturbation| to the smallest value $d'>d$
23816 such that the covering found by this algorithm would be different.
23817
23818 In particular, |min_cover(0)| returns the number of distinct values in the
23819 current list and sets |perturbation| to the minimum distance between
23820 adjacent values.
23821
23822 @c integer mp_min_cover (MP mp,scaled d) {
23823   pointer p; /* runs through the current list */
23824   scaled l; /* the least element covered by the current interval */
23825   integer m; /* lower bound on the size of the minimum cover */
23826   m=0; p=link(temp_head); mp->perturbation=el_gordo;
23827   while ( p!=inf_val ){ 
23828     incr(m); l=value(p);
23829     do {  p=link(p); } while (value(p)<=l+d);
23830     if ( value(p)-l<mp->perturbation ) 
23831       mp->perturbation=value(p)-l;
23832   }
23833   return m;
23834 }
23835
23836 @ @<Glob...@>=
23837 scaled perturbation; /* quantity related to \.{TFM} rounding */
23838 integer excess; /* the list is this much too long */
23839
23840 @ The smallest |d| such that a given list can be covered with |m| intervals
23841 is determined by the |threshold| routine, which is sort of an inverse
23842 to |min_cover|. The idea is to increase the interval size rapidly until
23843 finding the range, then to go sequentially until the exact borderline has
23844 been discovered.
23845
23846 @c scaled mp_threshold (MP mp,integer m) {
23847   scaled d; /* lower bound on the smallest interval size */
23848   mp->excess=mp_min_cover(mp, 0)-m;
23849   if ( mp->excess<=0 ) {
23850     return 0;
23851   } else  { 
23852     do {  
23853       d=mp->perturbation;
23854     } while (mp_min_cover(mp, d+d)>m);
23855     while ( mp_min_cover(mp, d)>m ) 
23856       d=mp->perturbation;
23857     return d;
23858   }
23859 }
23860
23861 @ The |skimp| procedure reduces the current list to at most |m| entries,
23862 by changing values if necessary. It also sets |info(p):=k| if |value(p)|
23863 is the |k|th distinct value on the resulting list, and it sets
23864 |perturbation| to the maximum amount by which a |value| field has
23865 been changed. The size of the resulting list is returned as the
23866 value of |skimp|.
23867
23868 @c integer mp_skimp (MP mp,integer m) {
23869   scaled d; /* the size of intervals being coalesced */
23870   pointer p,q,r; /* list manipulation registers */
23871   scaled l; /* the least value in the current interval */
23872   scaled v; /* a compromise value */
23873   d=mp_threshold(mp, m); mp->perturbation=0;
23874   q=temp_head; m=0; p=link(temp_head);
23875   while ( p!=inf_val ) {
23876     incr(m); l=value(p); info(p)=m;
23877     if ( value(link(p))<=l+d ) {
23878       @<Replace an interval of values by its midpoint@>;
23879     }
23880     q=p; p=link(p);
23881   }
23882   return m;
23883 }
23884
23885 @ @<Replace an interval...@>=
23886
23887   do {  
23888     p=link(p); info(p)=m;
23889     decr(mp->excess); if ( mp->excess==0 ) d=0;
23890   } while (value(link(p))<=l+d);
23891   v=l+halfp(value(p)-l);
23892   if ( value(p)-v>mp->perturbation ) 
23893     mp->perturbation=value(p)-v;
23894   r=q;
23895   do {  
23896     r=link(r); value(r)=v;
23897   } while (r!=p);
23898   link(q)=p; /* remove duplicate values from the current list */
23899 }
23900
23901 @ A warning message is issued whenever something is perturbed by
23902 more than 1/16\thinspace pt.
23903
23904 @c void mp_tfm_warning (MP mp,small_number m) { 
23905   mp_print_nl(mp, "(some "); 
23906   mp_print(mp, mp->int_name[m]);
23907 @.some charwds...@>
23908 @.some chardps...@>
23909 @.some charhts...@>
23910 @.some charics...@>
23911   mp_print(mp, " values had to be adjusted by as much as ");
23912   mp_print_scaled(mp, mp->perturbation); mp_print(mp, "pt)");
23913 }
23914
23915 @ Here's an example of how we use these routines.
23916 The width data needs to be perturbed only if there are 256 distinct
23917 widths, but \MP\ must check for this case even though it is
23918 highly unusual.
23919
23920 An integer variable |k| will be defined when we use this code.
23921 The |dimen_head| array will contain pointers to the sorted
23922 lists of dimensions.
23923
23924 @<Massage the \.{TFM} widths@>=
23925 clear_the_list;
23926 for (k=mp->bc;k<=mp->ec;k++)  {
23927   if ( mp->char_exists[k] )
23928     mp->tfm_width[k]=mp_sort_in(mp, mp->tfm_width[k]);
23929 }
23930 mp->nw=mp_skimp(mp, 255)+1; mp->dimen_head[1]=link(temp_head);
23931 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_wd)
23932
23933 @ @<Glob...@>=
23934 pointer dimen_head[5]; /* lists of \.{TFM} dimensions */
23935
23936 @ Heights, depths, and italic corrections are different from widths
23937 not only because their list length is more severely restricted, but
23938 also because zero values do not need to be put into the lists.
23939
23940 @<Massage the \.{TFM} heights, depths, and italic corrections@>=
23941 clear_the_list;
23942 for (k=mp->bc;k<=mp->ec;k++) {
23943   if ( mp->char_exists[k] ) {
23944     if ( mp->tfm_height[k]==0 ) mp->tfm_height[k]=zero_val;
23945     else mp->tfm_height[k]=mp_sort_in(mp, mp->tfm_height[k]);
23946   }
23947 }
23948 mp->nh=mp_skimp(mp, 15)+1; mp->dimen_head[2]=link(temp_head);
23949 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ht);
23950 clear_the_list;
23951 for (k=mp->bc;k<=mp->ec;k++) {
23952   if ( mp->char_exists[k] ) {
23953     if ( mp->tfm_depth[k]==0 ) mp->tfm_depth[k]=zero_val;
23954     else mp->tfm_depth[k]=mp_sort_in(mp, mp->tfm_depth[k]);
23955   }
23956 }
23957 mp->nd=mp_skimp(mp, 15)+1; mp->dimen_head[3]=link(temp_head);
23958 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_dp);
23959 clear_the_list;
23960 for (k=mp->bc;k<=mp->ec;k++) {
23961   if ( mp->char_exists[k] ) {
23962     if ( mp->tfm_ital_corr[k]==0 ) mp->tfm_ital_corr[k]=zero_val;
23963     else mp->tfm_ital_corr[k]=mp_sort_in(mp, mp->tfm_ital_corr[k]);
23964   }
23965 }
23966 mp->ni=mp_skimp(mp, 63)+1; mp->dimen_head[4]=link(temp_head);
23967 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ic)
23968
23969 @ @<Initialize table entries...@>=
23970 value(zero_val)=0; info(zero_val)=0;
23971
23972 @ Bytes 5--8 of the header are set to the design size, unless the user has
23973 some crazy reason for specifying them differently.
23974
23975 Error messages are not allowed at the time this procedure is called,
23976 so a warning is printed instead.
23977
23978 The value of |max_tfm_dimen| is calculated so that
23979 $$\hbox{|make_scaled(16*max_tfm_dimen,internal[mp_design_size])|}
23980  < \\{three\_bytes}.$$
23981
23982 @d three_bytes 0100000000 /* $2^{24}$ */
23983
23984 @c 
23985 void mp_fix_design_size (MP mp) {
23986   scaled d; /* the design size */
23987   d=mp->internal[mp_design_size];
23988   if ( (d<unity)||(d>=fraction_half) ) {
23989     if ( d!=0 )
23990       mp_print_nl(mp, "(illegal design size has been changed to 128pt)");
23991 @.illegal design size...@>
23992     d=040000000; mp->internal[mp_design_size]=d;
23993   }
23994   if ( mp->header_byte[4]<0 ) if ( mp->header_byte[5]<0 )
23995     if ( mp->header_byte[6]<0 ) if ( mp->header_byte[7]<0 ) {
23996      mp->header_byte[4]=d / 04000000;
23997      mp->header_byte[5]=(d / 4096) % 256;
23998      mp->header_byte[6]=(d / 16) % 256;
23999      mp->header_byte[7]=(d % 16)*16;
24000   };
24001   mp->max_tfm_dimen=16*mp->internal[mp_design_size]-mp->internal[mp_design_size] / 010000000;
24002   if ( mp->max_tfm_dimen>=fraction_half ) mp->max_tfm_dimen=fraction_half-1;
24003 }
24004
24005 @ The |dimen_out| procedure computes a |fix_word| relative to the
24006 design size. If the data was out of range, it is corrected and the
24007 global variable |tfm_changed| is increased by~one.
24008
24009 @c integer mp_dimen_out (MP mp,scaled x) { 
24010   if ( abs(x)>mp->max_tfm_dimen ) {
24011     incr(mp->tfm_changed);
24012     if ( x>0 ) x=three_bytes-1; else x=1-three_bytes;
24013   } else {
24014     x=mp_make_scaled(mp, x*16,mp->internal[mp_design_size]);
24015   }
24016   return x;
24017 }
24018
24019 @ @<Glob...@>=
24020 scaled max_tfm_dimen; /* bound on widths, heights, kerns, etc. */
24021 integer tfm_changed; /* the number of data entries that were out of bounds */
24022
24023 @ If the user has not specified any of the first four header bytes,
24024 the |fix_check_sum| procedure replaces them by a ``check sum'' computed
24025 from the |tfm_width| data relative to the design size.
24026 @^check sum@>
24027
24028 @c void mp_fix_check_sum (MP mp) {
24029   eight_bits k; /* runs through character codes */
24030   eight_bits B1,B2,B3,B4; /* bytes of the check sum */
24031   integer x;  /* hash value used in check sum computation */
24032   if ( mp->header_byte[0]==0 && mp->header_byte[1]==0 &&
24033        mp->header_byte[2]==0 && mp->header_byte[3]==0 ) {
24034     @<Compute a check sum in |(b1,b2,b3,b4)|@>;
24035     mp->header_byte[0]=B1; mp->header_byte[1]=B2;
24036     mp->header_byte[2]=B3; mp->header_byte[3]=B4; 
24037     return;
24038   }
24039 }
24040
24041 @ @<Compute a check sum in |(b1,b2,b3,b4)|@>=
24042 B1=mp->bc; B2=mp->ec; B3=mp->bc; B4=mp->ec; mp->tfm_changed=0;
24043 for (k=mp->bc;k<=mp->ec;k++) { 
24044   if ( mp->char_exists[k] ) {
24045     x=mp_dimen_out(mp, value(mp->tfm_width[k]))+(k+4)*020000000; /* this is positive */
24046     B1=(B1+B1+x) % 255;
24047     B2=(B2+B2+x) % 253;
24048     B3=(B3+B3+x) % 251;
24049     B4=(B4+B4+x) % 247;
24050   }
24051 }
24052
24053 @ Finally we're ready to actually write the \.{TFM} information.
24054 Here are some utility routines for this purpose.
24055
24056 @d tfm_out(A) fputc((A),mp->tfm_file) /* output one byte to |tfm_file| */
24057
24058 @c void mp_tfm_two (MP mp,integer x) { /* output two bytes to |tfm_file| */
24059   tfm_out(x / 256); tfm_out(x % 256);
24060 }
24061 void mp_tfm_four (MP mp,integer x) { /* output four bytes to |tfm_file| */
24062   if ( x>=0 ) tfm_out(x / three_bytes);
24063   else { 
24064     x=x+010000000000; /* use two's complement for negative values */
24065     x=x+010000000000;
24066     tfm_out((x / three_bytes) + 128);
24067   };
24068   x=x % three_bytes; tfm_out(x / unity);
24069   x=x % unity; tfm_out(x / 0400);
24070   tfm_out(x % 0400);
24071 }
24072 void mp_tfm_qqqq (MP mp,four_quarters x) { /* output four quarterwords to |tfm_file| */
24073   tfm_out(qo(x.b0)); tfm_out(qo(x.b1)); 
24074   tfm_out(qo(x.b2)); tfm_out(qo(x.b3));
24075 }
24076
24077 @ @<Finish the \.{TFM} file@>=
24078 if ( mp->job_name==NULL ) mp_open_log_file(mp);
24079 mp_pack_job_name(mp, ".tfm");
24080 while ( ! mp_b_open_out(mp, &mp->tfm_file, mp_filetype_metrics) )
24081   mp_prompt_file_name(mp, "file name for font metrics",".tfm");
24082 mp->metric_file_name=xstrdup(mp->name_of_file);
24083 @<Output the subfile sizes and header bytes@>;
24084 @<Output the character information bytes, then
24085   output the dimensions themselves@>;
24086 @<Output the ligature/kern program@>;
24087 @<Output the extensible character recipes and the font metric parameters@>;
24088   if ( mp->internal[mp_tracing_stats]>0 )
24089   @<Log the subfile sizes of the \.{TFM} file@>;
24090 mp_print_nl(mp, "Font metrics written on "); 
24091 mp_print(mp, mp->metric_file_name); mp_print_char(mp, '.');
24092 @.Font metrics written...@>
24093 fclose(mp->tfm_file)
24094
24095 @ Integer variables |lh|, |k|, and |lk_offset| will be defined when we use
24096 this code.
24097
24098 @<Output the subfile sizes and header bytes@>=
24099 k=mp->header_last;
24100 LH=(k+3) / 4; /* this is the number of header words */
24101 if ( mp->bc>mp->ec ) mp->bc=1; /* if there are no characters, |ec=0| and |bc=1| */
24102 @<Compute the ligature/kern program offset and implant the
24103   left boundary label@>;
24104 mp_tfm_two(mp,6+LH+(mp->ec-mp->bc+1)+mp->nw+mp->nh+mp->nd+mp->ni+mp->nl
24105      +lk_offset+mp->nk+mp->ne+mp->np);
24106   /* this is the total number of file words that will be output */
24107 mp_tfm_two(mp, LH); mp_tfm_two(mp, mp->bc); mp_tfm_two(mp, mp->ec); 
24108 mp_tfm_two(mp, mp->nw); mp_tfm_two(mp, mp->nh);
24109 mp_tfm_two(mp, mp->nd); mp_tfm_two(mp, mp->ni); mp_tfm_two(mp, mp->nl+lk_offset); 
24110 mp_tfm_two(mp, mp->nk); mp_tfm_two(mp, mp->ne);
24111 mp_tfm_two(mp, mp->np);
24112 for (k=0;k< 4*LH;k++)   { 
24113   tfm_out(mp->header_byte[k]);
24114 }
24115
24116 @ @<Output the character information bytes...@>=
24117 for (k=mp->bc;k<=mp->ec;k++) {
24118   if ( ! mp->char_exists[k] ) {
24119     mp_tfm_four(mp, 0);
24120   } else { 
24121     tfm_out(info(mp->tfm_width[k])); /* the width index */
24122     tfm_out((info(mp->tfm_height[k]))*16+info(mp->tfm_depth[k]));
24123     tfm_out((info(mp->tfm_ital_corr[k]))*4+mp->char_tag[k]);
24124     tfm_out(mp->char_remainder[k]);
24125   };
24126 }
24127 mp->tfm_changed=0;
24128 for (k=1;k<=4;k++) { 
24129   mp_tfm_four(mp, 0); p=mp->dimen_head[k];
24130   while ( p!=inf_val ) {
24131     mp_tfm_four(mp, mp_dimen_out(mp, value(p))); p=link(p);
24132   }
24133 }
24134
24135
24136 @ We need to output special instructions at the beginning of the
24137 |lig_kern| array in order to specify the right boundary character
24138 and/or to handle starting addresses that exceed 255. The |label_loc|
24139 and |label_char| arrays have been set up to record all the
24140 starting addresses; we have $-1=|label_loc|[0]<|label_loc|[1]\le\cdots
24141 \le|label_loc|[|label_ptr]|$.
24142
24143 @<Compute the ligature/kern program offset...@>=
24144 mp->bchar=mp_round_unscaled(mp, mp->internal[mp_boundary_char]);
24145 if ((mp->bchar<0)||(mp->bchar>255))
24146   { mp->bchar=-1; mp->lk_started=false; lk_offset=0; }
24147 else { mp->lk_started=true; lk_offset=1; };
24148 @<Find the minimum |lk_offset| and adjust all remainders@>;
24149 if ( mp->bch_label<undefined_label )
24150   { skip_byte(mp->nl)=qi(255); next_char(mp->nl)=qi(0);
24151   op_byte(mp->nl)=qi(((mp->bch_label+lk_offset)/ 256));
24152   rem_byte(mp->nl)=qi(((mp->bch_label+lk_offset)% 256));
24153   incr(mp->nl); /* possibly |nl=lig_table_size+1| */
24154   }
24155
24156 @ @<Find the minimum |lk_offset|...@>=
24157 k=mp->label_ptr; /* pointer to the largest unallocated label */
24158 if ( mp->label_loc[k]+lk_offset>255 ) {
24159   lk_offset=0; mp->lk_started=false; /* location 0 can do double duty */
24160   do {  
24161     mp->char_remainder[mp->label_char[k]]=lk_offset;
24162     while ( mp->label_loc[k-1]==mp->label_loc[k] ) {
24163        decr(k); mp->char_remainder[mp->label_char[k]]=lk_offset;
24164     }
24165     incr(lk_offset); decr(k);
24166   } while (! (lk_offset+mp->label_loc[k]<256));
24167     /* N.B.: |lk_offset=256| satisfies this when |k=0| */
24168 };
24169 if ( lk_offset>0 ) {
24170   while ( k>0 ) {
24171     mp->char_remainder[mp->label_char[k]]
24172      =mp->char_remainder[mp->label_char[k]]+lk_offset;
24173     decr(k);
24174   }
24175 }
24176
24177 @ @<Output the ligature/kern program@>=
24178 for (k=0;k<= 255;k++ ) {
24179   if ( mp->skip_table[k]<undefined_label ) {
24180      mp_print_nl(mp, "(local label "); mp_print_int(mp, k); mp_print(mp, ":: was missing)");
24181 @.local label l:: was missing@>
24182     cancel_skips(mp->skip_table[k]);
24183   }
24184 }
24185 if ( mp->lk_started ) { /* |lk_offset=1| for the special |bchar| */
24186   tfm_out(255); tfm_out(mp->bchar); mp_tfm_two(mp, 0);
24187 } else {
24188   for (k=1;k<=lk_offset;k++) {/* output the redirection specs */
24189     mp->ll=mp->label_loc[mp->label_ptr];
24190     if ( mp->bchar<0 ) { tfm_out(254); tfm_out(0);   }
24191     else { tfm_out(255); tfm_out(mp->bchar);   };
24192     mp_tfm_two(mp, mp->ll+lk_offset);
24193     do {  
24194       decr(mp->label_ptr);
24195     } while (! (mp->label_loc[mp->label_ptr]<mp->ll));
24196   }
24197 }
24198 for (k=0;k<=mp->nl-1;k++) mp_tfm_qqqq(mp, mp->lig_kern[k]);
24199 for (k=0;k<=mp->nk-1;k++) mp_tfm_four(mp, mp_dimen_out(mp, mp->kern[k]))
24200
24201 @ @<Output the extensible character recipes...@>=
24202 for (k=0;k<=mp->ne-1;k++) 
24203   mp_tfm_qqqq(mp, mp->exten[k]);
24204 for (k=1;k<=mp->np;k++) {
24205   if ( k==1 ) {
24206     if ( abs(mp->param[1])<fraction_half ) {
24207       mp_tfm_four(mp, mp->param[1]*16);
24208     } else  { 
24209       incr(mp->tfm_changed);
24210       if ( mp->param[1]>0 ) mp_tfm_four(mp, el_gordo);
24211       else mp_tfm_four(mp, -el_gordo);
24212     }
24213   } else {
24214     mp_tfm_four(mp, mp_dimen_out(mp, mp->param[k]));
24215   }
24216 }
24217 if ( mp->tfm_changed>0 )  { 
24218   if ( mp->tfm_changed==1 ) mp_print_nl(mp, "(a font metric dimension");
24219 @.a font metric dimension...@>
24220   else  { 
24221     mp_print_nl(mp, "("); mp_print_int(mp, mp->tfm_changed);
24222 @.font metric dimensions...@>
24223     mp_print(mp, " font metric dimensions");
24224   }
24225   mp_print(mp, " had to be decreased)");
24226 }
24227
24228 @ @<Log the subfile sizes of the \.{TFM} file@>=
24229
24230   char s[200];
24231   wlog_ln(" ");
24232   if ( mp->bch_label<undefined_label ) decr(mp->nl);
24233   snprintf(s,128,"(You used %iw,%ih,%id,%ii,%il,%ik,%ie,%ip metric file positions)",
24234                  mp->nw, mp->nh, mp->nd, mp->ni, mp->nl, mp->nk, mp->ne,mp->np);
24235   wlog_ln(s);
24236 }
24237
24238 @* \[43] Reading font metric data.
24239
24240 \MP\ isn't a typesetting program but it does need to find the bounding box
24241 of a sequence of typeset characters.  Thus it needs to read \.{TFM} files as
24242 well as write them.
24243
24244 @<Glob...@>=
24245 FILE * tfm_infile;
24246
24247 @ All the width, height, and depth information is stored in an array called
24248 |font_info|.  This array is allocated sequentially and each font is stored
24249 as a series of |char_info| words followed by the width, height, and depth
24250 tables.  Since |font_name| entries are permanent, their |str_ref| values are
24251 set to |max_str_ref|.
24252
24253 @<Types...@>=
24254 typedef unsigned int font_number; /* |0..font_max| */
24255
24256 @ The |font_info| array is indexed via a group directory arrays.
24257 For example, the |char_info| data for character~|c| in font~|f| will be
24258 in |font_info[char_base[f]+c].qqqq|.
24259
24260 @<Glob...@>=
24261 font_number font_max; /* maximum font number for included text fonts */
24262 size_t      font_mem_size; /* number of words for \.{TFM} information for text fonts */
24263 memory_word *font_info; /* height, width, and depth data */
24264 char        **font_enc_name; /* encoding names, if any */
24265 boolean     *font_ps_name_fixed; /* are the postscript names fixed already?  */
24266 int         next_fmem; /* next unused entry in |font_info| */
24267 font_number last_fnum; /* last font number used so far */
24268 scaled      *font_dsize;  /* 16 times the ``design'' size in \ps\ points */
24269 char        **font_name;  /* name as specified in the \&{infont} command */
24270 char        **font_ps_name;  /* PostScript name for use when |internal[mp_prologues]>0| */
24271 font_number last_ps_fnum; /* last valid |font_ps_name| index */
24272 eight_bits  *font_bc;
24273 eight_bits  *font_ec;  /* first and last character code */
24274 int         *char_base;  /* base address for |char_info| */
24275 int         *width_base; /* index for zeroth character width */
24276 int         *height_base; /* index for zeroth character height */
24277 int         *depth_base; /* index for zeroth character depth */
24278 pointer     *font_sizes;
24279
24280 @ @<Allocate or initialize ...@>=
24281 mp->font_mem_size = 10000; 
24282 mp->font_info = xmalloc ((mp->font_mem_size+1),sizeof(memory_word));
24283 memset (mp->font_info,0,sizeof(memory_word)*(mp->font_mem_size+1));
24284 mp->font_enc_name = NULL;
24285 mp->font_ps_name_fixed = NULL;
24286 mp->font_dsize = NULL;
24287 mp->font_name = NULL;
24288 mp->font_ps_name = NULL;
24289 mp->font_bc = NULL;
24290 mp->font_ec = NULL;
24291 mp->last_fnum = null_font;
24292 mp->char_base = NULL;
24293 mp->width_base = NULL;
24294 mp->height_base = NULL;
24295 mp->depth_base = NULL;
24296 mp->font_sizes = null;
24297
24298 @ @<Dealloc variables@>=
24299 xfree(mp->font_info);
24300 xfree(mp->font_enc_name);
24301 xfree(mp->font_ps_name_fixed);
24302 xfree(mp->font_dsize);
24303 xfree(mp->font_name);
24304 xfree(mp->font_ps_name);
24305 xfree(mp->font_bc);
24306 xfree(mp->font_ec);
24307 xfree(mp->char_base);
24308 xfree(mp->width_base);
24309 xfree(mp->height_base);
24310 xfree(mp->depth_base);
24311 xfree(mp->font_sizes);
24312
24313
24314 @c 
24315 void mp_reallocate_fonts (MP mp, font_number l) {
24316   font_number f;
24317   XREALLOC(mp->font_enc_name,      l, char *);
24318   XREALLOC(mp->font_ps_name_fixed, l, boolean);
24319   XREALLOC(mp->font_dsize,         l, scaled);
24320   XREALLOC(mp->font_name,          l, char *);
24321   XREALLOC(mp->font_ps_name,       l, char *);
24322   XREALLOC(mp->font_bc,            l, eight_bits);
24323   XREALLOC(mp->font_ec,            l, eight_bits);
24324   XREALLOC(mp->char_base,          l, int);
24325   XREALLOC(mp->width_base,         l, int);
24326   XREALLOC(mp->height_base,        l, int);
24327   XREALLOC(mp->depth_base,         l, int);
24328   XREALLOC(mp->font_sizes,         l, pointer);
24329   for (f=(mp->last_fnum+1);f<=l;f++) {
24330     mp->font_enc_name[f]=NULL;
24331     mp->font_ps_name_fixed[f] = false;
24332     mp->font_name[f]=NULL;
24333     mp->font_ps_name[f]=NULL;
24334     mp->font_sizes[f]=null;
24335   }
24336   mp->font_max = l;
24337 }
24338
24339 @ @<Declare |mp_reallocate| functions@>=
24340 void mp_reallocate_fonts (MP mp, font_number l);
24341
24342
24343 @ A |null_font| containing no characters is useful for error recovery.  Its
24344 |font_name| entry starts out empty but is reset each time an erroneous font is
24345 found.  This helps to cut down on the number of duplicate error messages without
24346 wasting a lot of space.
24347
24348 @d null_font 0 /* the |font_number| for an empty font */
24349
24350 @<Set initial...@>=
24351 mp->font_dsize[null_font]=0;
24352 mp->font_bc[null_font]=1;
24353 mp->font_ec[null_font]=0;
24354 mp->char_base[null_font]=0;
24355 mp->width_base[null_font]=0;
24356 mp->height_base[null_font]=0;
24357 mp->depth_base[null_font]=0;
24358 mp->next_fmem=0;
24359 mp->last_fnum=null_font;
24360 mp->last_ps_fnum=null_font;
24361 mp->font_name[null_font]="nullfont";
24362 mp->font_ps_name[null_font]="";
24363
24364 @ Each |char_info| word is of type |four_quarters|.  The |b0| field contains
24365 the |width index|; the |b1| field contains the height
24366 index; the |b2| fields contains the depth index, and the |b3| field used only
24367 for temporary storage. (It is used to keep track of which characters occur in
24368 an edge structure that is being shipped out.)
24369 The corresponding words in the width, height, and depth tables are stored as
24370 |scaled| values in units of \ps\ points.
24371
24372 With the macros below, the |char_info| word for character~|c| in font~|f| is
24373 |char_info(f)(c)| and the width is
24374 $$\hbox{|char_width(f)(char_info(f)(c)).sc|.}$$
24375
24376 @d char_info_end(A) (A)].qqqq
24377 @d char_info(A) mp->font_info[mp->char_base[(A)]+char_info_end
24378 @d char_width_end(A) (A).b0].sc
24379 @d char_width(A) mp->font_info[mp->width_base[(A)]+char_width_end
24380 @d char_height_end(A) (A).b1].sc
24381 @d char_height(A) mp->font_info[mp->height_base[(A)]+char_height_end
24382 @d char_depth_end(A) (A).b2].sc
24383 @d char_depth(A) mp->font_info[mp->depth_base[(A)]+char_depth_end
24384 @d ichar_exists(A) ((A).b0>0)
24385
24386 @ The |font_ps_name| for a built-in font should be what PostScript expects.
24387 A preliminary name is obtained here from the \.{TFM} name as given in the
24388 |fname| argument.  This gets updated later from an external table if necessary.
24389
24390 @<Declare text measuring subroutines@>=
24391 @<Declare subroutines for parsing file names@>;
24392 font_number mp_read_font_info (MP mp, char*fname) {
24393   boolean file_opened; /* has |tfm_infile| been opened? */
24394   font_number n; /* the number to return */
24395   halfword lf,tfm_lh,bc,ec,nw,nh,nd; /* subfile size parameters */
24396   size_t whd_size; /* words needed for heights, widths, and depths */
24397   int i,ii; /* |font_info| indices */
24398   int jj; /* counts bytes to be ignored */
24399   scaled z; /* used to compute the design size */
24400   fraction d;
24401   /* height, width, or depth as a fraction of design size times $2^{-8}$ */
24402   eight_bits h_and_d; /* height and depth indices being unpacked */
24403   int tfbyte; /* a byte read from the file */
24404   n=null_font;
24405   @<Open |tfm_infile| for input@>;
24406   @<Read data from |tfm_infile|; if there is no room, say so and |goto done|;
24407     otherwise |goto bad_tfm| or |goto done| as appropriate@>;
24408 BAD_TFM:
24409   @<Complain that the \.{TFM} file is bad@>;
24410 DONE:
24411   if ( file_opened ) fclose(mp->tfm_infile);
24412   if ( n!=null_font ) { 
24413     mp->font_ps_name[n]=fname;
24414     mp->font_name[n]=fname;
24415   }
24416   return n;
24417 }
24418
24419 @ \MP\ doesn't bother to check the entire \.{TFM} file for errors or explain
24420 precisely what is wrong if it does find a problem.  Programs called \.{TFtoPL}
24421 @.TFtoPL@> @.PLtoTF@>
24422 and \.{PLtoTF} can be used to debug \.{TFM} files.
24423
24424 @<Complain that the \.{TFM} file is bad@>=
24425 print_err("Font ");
24426 mp_print(mp, fname);
24427 if ( file_opened ) mp_print(mp, " not usable: TFM file is bad");
24428 else mp_print(mp, " not usable: TFM file not found");
24429 help3("I wasn't able to read the size data for this font so this")
24430   ("`infont' operation won't produce anything. If the font name")
24431   ("is right, you might ask an expert to make a TFM file");
24432 if ( file_opened )
24433   mp->help_line[0]="is right, try asking an expert to fix the TFM file";
24434 mp_error(mp)
24435
24436 @ @<Read data from |tfm_infile|; if there is no room, say so...@>=
24437 @<Read the \.{TFM} size fields@>;
24438 @<Use the size fields to allocate space in |font_info|@>;
24439 @<Read the \.{TFM} header@>;
24440 @<Read the character data and the width, height, and depth tables and
24441   |goto done|@>
24442
24443 @ A bad \.{TFM} file can be shorter than it claims to be.  The code given here
24444 might try to read past the end of the file if this happens.  Changes will be
24445 needed if it causes a system error to refer to |tfm_infile^| or call
24446 |get_tfm_infile| when |eof(tfm_infile)| is true.  For example, the definition
24447 @^system dependencies@>
24448 of |tfget| could be changed to
24449 ``|begin get(tfm_infile); if eof(tfm_infile) then goto bad_tfm; end|.''
24450
24451 @d tfget {tfbyte = fgetc(mp->tfm_infile); }
24452 @d read_two(A) { (A)=tfbyte;
24453   if ( (A)>127 ) goto BAD_TFM;
24454   tfget; (A)=(A)*0400+tfbyte;
24455   }
24456 @d tf_ignore(A) { for (jj=(A);jj>=1;jj--) tfget; }
24457
24458 @<Read the \.{TFM} size fields@>=
24459 tfget; read_two(lf);
24460 tfget; read_two(tfm_lh);
24461 tfget; read_two(bc);
24462 tfget; read_two(ec);
24463 if ( (bc>1+ec)||(ec>255) ) goto BAD_TFM;
24464 tfget; read_two(nw);
24465 tfget; read_two(nh);
24466 tfget; read_two(nd);
24467 whd_size=(ec+1-bc)+nw+nh+nd;
24468 if ( lf<(int)(6+tfm_lh+whd_size) ) goto BAD_TFM;
24469 tf_ignore(10)
24470
24471 @ Offsets are added to |char_base[n]| and |width_base[n]| so that is not
24472 necessary to apply the |so|  and |qo| macros when looking up the width of a
24473 character in the string pool.  In order to ensure nonnegative |char_base|
24474 values when |bc>0|, it may be necessary to reserve a few unused |font_info|
24475 elements.
24476
24477 @<Use the size fields to allocate space in |font_info|@>=
24478 if ( mp->next_fmem<bc) mp->next_fmem=bc;  /* ensure nonnegative |char_base| */
24479 if (mp->last_fnum==mp->font_max)
24480   mp_reallocate_fonts(mp,(mp->font_max+(mp->font_max>>2)));
24481 while (mp->next_fmem+whd_size>=mp->font_mem_size) {
24482   size_t l = mp->font_mem_size+(mp->font_mem_size>>2);
24483   memory_word *font_info;
24484   font_info = xmalloc ((l+1),sizeof(memory_word));
24485   memset (font_info,0,sizeof(memory_word)*(l+1));
24486   memcpy (font_info,mp->font_info,sizeof(memory_word)*(mp->font_mem_size+1));
24487   xfree(mp->font_info);
24488   mp->font_info = font_info;
24489   mp->font_mem_size = l;
24490 }
24491 incr(mp->last_fnum);
24492 n=mp->last_fnum;
24493 mp->font_bc[n]=bc;
24494 mp->font_ec[n]=ec;
24495 mp->char_base[n]=mp->next_fmem-bc;
24496 mp->width_base[n]=mp->next_fmem+ec-bc+1;
24497 mp->height_base[n]=mp->width_base[n]+nw;
24498 mp->depth_base[n]=mp->height_base[n]+nh;
24499 mp->next_fmem=mp->next_fmem+whd_size;
24500
24501
24502 @ @<Read the \.{TFM} header@>=
24503 if ( tfm_lh<2 ) goto BAD_TFM;
24504 tf_ignore(4);
24505 tfget; read_two(z);
24506 tfget; z=z*0400+tfbyte;
24507 tfget; z=z*0400+tfbyte; /* now |z| is 16 times the design size */
24508 mp->font_dsize[n]=mp_take_fraction(mp, z,267432584);
24509   /* times ${72\over72.27}2^{28}$ to convert from \TeX\ points */
24510 tf_ignore(4*(tfm_lh-2))
24511
24512 @ @<Read the character data and the width, height, and depth tables...@>=
24513 ii=mp->width_base[n];
24514 i=mp->char_base[n]+bc;
24515 while ( i<ii ) { 
24516   tfget; mp->font_info[i].qqqq.b0=qi(tfbyte);
24517   tfget; h_and_d=tfbyte;
24518   mp->font_info[i].qqqq.b1=h_and_d / 16;
24519   mp->font_info[i].qqqq.b2=h_and_d % 16;
24520   tfget; tfget;
24521   incr(i);
24522 }
24523 while ( i<mp->next_fmem ) {
24524   @<Read a four byte dimension, scale it by the design size, store it in
24525     |font_info[i]|, and increment |i|@>;
24526 }
24527 if (feof(mp->tfm_infile) ) goto BAD_TFM;
24528 goto DONE
24529
24530 @ The raw dimension read into |d| should have magnitude at most $2^{24}$ when
24531 interpreted as an integer, and this includes a scale factor of $2^{20}$.  Thus
24532 we can multiply it by sixteen and think of it as a |fraction| that has been
24533 divided by sixteen.  This cancels the extra scale factor contained in
24534 |font_dsize[n|.
24535
24536 @<Read a four byte dimension, scale it by the design size, store it in...@>=
24537
24538 tfget; d=tfbyte;
24539 if ( d>=0200 ) d=d-0400;
24540 tfget; d=d*0400+tfbyte;
24541 tfget; d=d*0400+tfbyte;
24542 tfget; d=d*0400+tfbyte;
24543 mp->font_info[i].sc=mp_take_fraction(mp, d*16,mp->font_dsize[n]);
24544 incr(i);
24545 }
24546
24547 @ This function does no longer use the file name parser, because |fname| is
24548 a C string already.
24549 @<Open |tfm_infile| for input@>=
24550 file_opened=false;
24551 mp_ptr_scan_file(mp, fname);
24552 if ( strlen(mp->cur_area)==0 ) { xfree(mp->cur_area); mp->cur_area=xstrdup(MP_font_area);}
24553 if ( strlen(mp->cur_ext)==0 )  { xfree(mp->cur_ext); mp->cur_ext=xstrdup(".tfm"); }
24554 pack_cur_name;
24555 mp->tfm_infile = mp_open_file(mp, mp->name_of_file, "rb",mp_filetype_metrics);
24556 if ( !mp->tfm_infile  ) goto BAD_TFM;
24557 file_opened=true
24558
24559 @ When we have a font name and we don't know whether it has been loaded yet,
24560 we scan the |font_name| array before calling |read_font_info|.
24561
24562 @<Declare text measuring subroutines@>=
24563 font_number mp_find_font (MP mp, char *f) {
24564   font_number n;
24565   for (n=0;n<=mp->last_fnum;n++) {
24566     if (mp_xstrcmp(f,mp->font_name[n])==0 )
24567       return n;
24568   }
24569   return mp_read_font_info(mp, f);
24570 }
24571
24572 @ One simple application of |find_font| is the implementation of the |font_size|
24573 operator that gets the design size for a given font name.
24574
24575 @<Find the design size of the font whose name is |cur_exp|@>=
24576 mp_flush_cur_exp(mp, (mp->font_dsize[mp_find_font(mp, str(mp->cur_exp))]+8) / 16)
24577
24578 @ If we discover that the font doesn't have a requested character, we omit it
24579 from the bounding box computation and expect the \ps\ interpreter to drop it.
24580 This routine issues a warning message if the user has asked for it.
24581
24582 @<Declare text measuring subroutines@>=
24583 void mp_lost_warning (MP mp,font_number f, pool_pointer k) { 
24584   if ( mp->internal[mp_tracing_lost_chars]>0 ) { 
24585     mp_begin_diagnostic(mp);
24586     if ( mp->selector==log_only ) incr(mp->selector);
24587     mp_print_nl(mp, "Missing character: There is no ");
24588 @.Missing character@>
24589     mp_print_str(mp, mp->str_pool[k]); 
24590     mp_print(mp, " in font ");
24591     mp_print(mp, mp->font_name[f]); mp_print_char(mp, '!'); 
24592     mp_end_diagnostic(mp, false);
24593   }
24594 }
24595
24596 @ The whole purpose of saving the height, width, and depth information is to be
24597 able to find the bounding box of an item of text in an edge structure.  The
24598 |set_text_box| procedure takes a text node and adds this information.
24599
24600 @<Declare text measuring subroutines@>=
24601 void mp_set_text_box (MP mp,pointer p) {
24602   font_number f; /* |font_n(p)| */
24603   ASCII_code bc,ec; /* range of valid characters for font |f| */
24604   pool_pointer k,kk; /* current character and character to stop at */
24605   four_quarters cc; /* the |char_info| for the current character */
24606   scaled h,d; /* dimensions of the current character */
24607   width_val(p)=0;
24608   height_val(p)=-el_gordo;
24609   depth_val(p)=-el_gordo;
24610   f=font_n(p);
24611   bc=mp->font_bc[f];
24612   ec=mp->font_ec[f];
24613   kk=str_stop(text_p(p));
24614   k=mp->str_start[text_p(p)];
24615   while ( k<kk ) {
24616     @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>;
24617   }
24618   @<Set the height and depth to zero if the bounding box is empty@>;
24619 }
24620
24621 @ @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>=
24622
24623   if ( (mp->str_pool[k]<bc)||(mp->str_pool[k]>ec) ) {
24624     mp_lost_warning(mp, f,k);
24625   } else { 
24626     cc=char_info(f)(mp->str_pool[k]);
24627     if ( ! ichar_exists(cc) ) {
24628       mp_lost_warning(mp, f,k);
24629     } else { 
24630       width_val(p)=width_val(p)+char_width(f)(cc);
24631       h=char_height(f)(cc);
24632       d=char_depth(f)(cc);
24633       if ( h>height_val(p) ) height_val(p)=h;
24634       if ( d>depth_val(p) ) depth_val(p)=d;
24635     }
24636   }
24637   incr(k);
24638 }
24639
24640 @ Let's hope modern compilers do comparisons correctly when the difference would
24641 overflow.
24642
24643 @<Set the height and depth to zero if the bounding box is empty@>=
24644 if ( height_val(p)<-depth_val(p) ) { 
24645   height_val(p)=0;
24646   depth_val(p)=0;
24647 }
24648
24649 @ The new primitives fontmapfile and fontmapline.
24650
24651 @<Declare action procedures for use by |do_statement|@>=
24652 void mp_do_mapfile (MP mp) ;
24653 void mp_do_mapline (MP mp) ;
24654
24655 @ @c void mp_do_mapfile (MP mp) { 
24656   mp_get_x_next(mp); mp_scan_expression(mp);
24657   if ( mp->cur_type!=mp_string_type ) {
24658     @<Complain about improper map operation@>;
24659   } else {
24660     mp_map_file(mp,mp->cur_exp);
24661   }
24662 }
24663 void mp_do_mapline (MP mp) { 
24664   mp_get_x_next(mp); mp_scan_expression(mp);
24665   if ( mp->cur_type!=mp_string_type ) {
24666      @<Complain about improper map operation@>;
24667   } else { 
24668      mp_map_line(mp,mp->cur_exp);
24669   }
24670 }
24671
24672 @ @<Complain about improper map operation@>=
24673
24674   exp_err("Unsuitable expression");
24675   help1("Only known strings can be map files or map lines.");
24676   mp_put_get_error(mp);
24677 }
24678
24679 @ This is temporary.
24680
24681 @d ps_room(A) mp_ps_room(mp,A)
24682
24683 @ To print |scaled| value to PDF output we need some subroutines to ensure
24684 accurary.
24685
24686 @d max_integer   0x7FFFFFFF /* $2^{31}-1$ */
24687
24688 @<Glob...@>=
24689 scaled one_bp; /* scaled value corresponds to 1bp */
24690 scaled one_hundred_bp; /* scaled value corresponds to 100bp */
24691 scaled one_hundred_inch; /* scaled value corresponds to 100in */
24692 integer ten_pow[10]; /* $10^0..10^9$ */
24693 integer scaled_out; /* amount of |scaled| that was taken out in |divide_scaled| */
24694
24695 @ @<Set init...@>=
24696 mp->one_bp = 65782; /* 65781.76 */
24697 mp->one_hundred_bp = 6578176;
24698 mp->one_hundred_inch = 473628672;
24699 mp->ten_pow[0] = 1;
24700 for (i = 1;i<= 9; i++ ) {
24701   mp->ten_pow[i] = 10*mp->ten_pow[i - 1];
24702 }
24703
24704 @ The following function divides |s| by |m|. |dd| is number of decimal digits.
24705
24706 @c scaled mp_divide_scaled (MP mp,scaled s, scaled m, integer  dd) {
24707   scaled q,r;
24708   integer sign,i;
24709   sign = 1;
24710   if ( s < 0 ) { sign = -sign; s = -s; }
24711   if ( m < 0 ) { sign = -sign; m = -m; }
24712   if ( m == 0 )
24713     mp_confusion(mp, "arithmetic: divided by zero");
24714   else if ( m >= (max_integer / 10) )
24715     mp_confusion(mp, "arithmetic: number too big");
24716   q = s / m;
24717   r = s % m;
24718   for (i = 1;i<=dd;i++) {
24719     q = 10*q + (10*r) / m;
24720     r = (10*r) % m;
24721   }
24722   if ( 2*r >= m ) { incr(q); r = r - m; }
24723   mp->scaled_out = sign*(s - (r / mp->ten_pow[dd]));
24724   return (sign*q);
24725 }
24726
24727 @* \[44] Shipping pictures out.
24728 The |ship_out| procedure, to be described below, is given a pointer to
24729 an edge structure. Its mission is to output a file containing the \ps\
24730 description of an edge structure.
24731
24732 @ Each time an edge structure is shipped out we write a new \ps\ output
24733 file named according to the current \&{charcode}.
24734 @:char_code_}{\&{charcode} primitive@>
24735
24736 @<Declare the \ps\ output procedures@>=
24737 void mp_open_output_file (MP mp) ;
24738
24739 @ @c void mp_open_output_file (MP mp) {
24740   integer c; /* \&{charcode} rounded to the nearest integer */
24741   int old_setting; /* previous |selector| setting */
24742   pool_pointer i; /*  indexes into |filename_template|  */
24743   integer cc; /* a temporary integer for template building  */
24744   integer f,g=0; /* field widths */
24745   if ( mp->job_name==NULL ) mp_open_log_file(mp);
24746   c=mp_round_unscaled(mp, mp->internal[mp_char_code]);
24747   if ( mp->filename_template==0 ) {
24748     char *s; /* a file extension derived from |c| */
24749     if ( c<0 ) 
24750       s=xstrdup(".ps");
24751     else 
24752       @<Use |c| to compute the file extension |s|@>;
24753     mp_pack_job_name(mp, s);
24754     xfree(s);
24755     while ( ! mp_a_open_out(mp, &mp->ps_file, mp_filetype_postscript) )
24756       mp_prompt_file_name(mp, "file name for output",s);
24757   } else { /* initializations */
24758     str_number s, n; /* a file extension derived from |c| */
24759     old_setting=mp->selector; 
24760     mp->selector=new_string;
24761     f = 0;
24762     i = mp->str_start[mp->filename_template];
24763     n = rts(""); /* initialize */
24764     while ( i<str_stop(mp->filename_template) ) {
24765        if ( mp->str_pool[i]=='%' ) {
24766       CONTINUE:
24767         incr(i);
24768         if ( i<str_stop(mp->filename_template) ) {
24769           if ( mp->str_pool[i]=='j' ) {
24770             mp_print(mp, mp->job_name);
24771           } else if ( mp->str_pool[i]=='d' ) {
24772              cc= mp_round_unscaled(mp, mp->internal[mp_day]);
24773              print_with_leading_zeroes(cc);
24774           } else if ( mp->str_pool[i]=='m' ) {
24775              cc= mp_round_unscaled(mp, mp->internal[mp_month]);
24776              print_with_leading_zeroes(cc);
24777           } else if ( mp->str_pool[i]=='y' ) {
24778              cc= mp_round_unscaled(mp, mp->internal[mp_year]);
24779              print_with_leading_zeroes(cc);
24780           } else if ( mp->str_pool[i]=='H' ) {
24781              cc= mp_round_unscaled(mp, mp->internal[mp_time]) / 60;
24782              print_with_leading_zeroes(cc);
24783           }  else if ( mp->str_pool[i]=='M' ) {
24784              cc= mp_round_unscaled(mp, mp->internal[mp_time]) % 60;
24785              print_with_leading_zeroes(cc);
24786           } else if ( mp->str_pool[i]=='c' ) {
24787             if ( c<0 ) mp_print(mp, "ps");
24788             else print_with_leading_zeroes(c);
24789           } else if ( (mp->str_pool[i]>='0') && 
24790                       (mp->str_pool[i]<='9') ) {
24791             if ( (f<10)  )
24792               f = (f*10) + mp->str_pool[i]-'0';
24793             goto CONTINUE;
24794           } else {
24795             mp_print_str(mp, mp->str_pool[i]);
24796           }
24797         }
24798       } else {
24799         if ( mp->str_pool[i]=='.' )
24800           if (length(n)==0)
24801             n = mp_make_string(mp);
24802         mp_print_str(mp, mp->str_pool[i]);
24803       };
24804       incr(i);
24805     };
24806     s = mp_make_string(mp);
24807     mp->selector= old_setting;
24808     if (length(n)==0) {
24809        n=s;
24810        s=rts("");
24811     };
24812     mp_pack_file_name(mp, str(n),"",str(s));
24813     while ( ! mp_a_open_out(mp, &mp->ps_file, mp_filetype_postscript) )
24814       mp_prompt_file_name(mp, "file name for output",str(s));
24815     delete_str_ref(n);
24816     delete_str_ref(s);
24817   }
24818   @<Store the true output file name if appropriate@>;
24819   @<Begin the progress report for the output of picture~|c|@>;
24820 }
24821
24822 @ The file extension created here could be up to five characters long in
24823 extreme cases so it may have to be shortened on some systems.
24824 @^system dependencies@>
24825
24826 @<Use |c| to compute the file extension |s|@>=
24827
24828   s = xmalloc(7,1);
24829   snprintf(s,7,".%i",(int)c);
24830 }
24831
24832 @ The user won't want to see all the output file names so we only save the
24833 first and last ones and a count of how many there were.  For this purpose
24834 files are ordered primarily by \&{charcode} and secondarily by order of
24835 creation.
24836 @:char_code_}{\&{charcode} primitive@>
24837
24838 @<Store the true output file name if appropriate@>=
24839 if ((c<mp->first_output_code)&&(mp->first_output_code>=0)) {
24840   mp->first_output_code=c;
24841   xfree(mp->first_file_name);
24842   mp->first_file_name=xstrdup(mp->name_of_file);
24843 }
24844 if ( c>=mp->last_output_code ) {
24845   mp->last_output_code=c;
24846   xfree(mp->last_file_name);
24847   mp->last_file_name=xstrdup(mp->name_of_file);
24848 }
24849
24850 @ @<Glob...@>=
24851 char * first_file_name;
24852 char * last_file_name; /* full file names */
24853 integer first_output_code;integer last_output_code; /* rounded \&{charcode} values */
24854 @:char_code_}{\&{charcode} primitive@>
24855 integer total_shipped; /* total number of |ship_out| operations completed */
24856
24857 @ @<Set init...@>=
24858 mp->first_file_name=xstrdup("");
24859 mp->last_file_name=xstrdup("");
24860 mp->first_output_code=32768;
24861 mp->last_output_code=-32768;
24862 mp->total_shipped=0;
24863
24864 @ @<Dealloc variables@>=
24865 xfree(mp->first_file_name);
24866 xfree(mp->last_file_name);
24867
24868 @ @<Begin the progress report for the output of picture~|c|@>=
24869 if ( (int)mp->term_offset>mp->max_print_line-6 ) mp_print_ln(mp);
24870 else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
24871 mp_print_char(mp, '[');
24872 if ( c>=0 ) mp_print_int(mp, c)
24873
24874 @ @<End progress report@>=
24875 mp_print_char(mp, ']');
24876 update_terminal;
24877 incr(mp->total_shipped)
24878
24879 @ @<Explain what output files were written@>=
24880 if ( mp->total_shipped>0 ) { 
24881   mp_print_nl(mp, "");
24882   mp_print_int(mp, mp->total_shipped);
24883   mp_print(mp, " output file");
24884   if ( mp->total_shipped>1 ) mp_print_char(mp, 's');
24885   mp_print(mp, " written: ");
24886   mp_print(mp, mp->first_file_name);
24887   if ( mp->total_shipped>1 ) {
24888     if ( 31+strlen(mp->first_file_name)+
24889          strlen(mp->last_file_name)> (unsigned)mp->max_print_line) 
24890       mp_print_ln(mp);
24891     mp_print(mp, " .. ");
24892     mp_print(mp, mp->last_file_name);
24893   }
24894 }
24895
24896
24897 @ The most important output procedure is the one that gives the \ps\ version of
24898 a \MP\ path.
24899
24900 @<Declare the \ps\ output procedures@>=
24901 void mp_ps_path_out (MP mp,pointer h) {
24902   pointer p,q; /* for scanning the path */
24903   scaled d; /* a temporary value */
24904   boolean curved; /* |true| unless the cubic is almost straight */
24905   ps_room(40);
24906   if ( mp->need_newpath ) 
24907     mp_ps_print_cmd(mp, "newpath ","n ");
24908   mp->need_newpath=true;
24909   mp_ps_pair_out(mp, x_coord(h),y_coord(h));
24910   mp_ps_print_cmd(mp, "moveto","m");
24911   p=h;
24912   do {  
24913     if ( right_type(p)==mp_endpoint ) { 
24914       if ( p==h ) mp_ps_print_cmd(mp, " 0 0 rlineto"," 0 0 r");
24915       return;
24916     }
24917     q=link(p);
24918     @<Start a new line and print the \ps\ commands for the curve from
24919       |p| to~|q|@>;
24920     p=q;
24921   } while (p!=h);
24922   mp_ps_print_cmd(mp, " closepath"," p");
24923 }
24924
24925 @ @<Glob...@>=
24926 boolean need_newpath;
24927   /* will |ps_path_out| need to issue a \&{newpath} command next time */
24928 @:newpath_}{\&{newpath} command@>
24929
24930 @ @<Start a new line and print the \ps\ commands for the curve from...@>=
24931 curved=true;
24932 @<Set |curved:=false| if the cubic from |p| to |q| is almost straight@>;
24933 mp_print_ln(mp);
24934 if ( curved ){ 
24935   mp_ps_pair_out(mp, right_x(p),right_y(p));
24936   mp_ps_pair_out(mp, left_x(q),left_y(q));
24937   mp_ps_pair_out(mp, x_coord(q),y_coord(q));
24938   mp_ps_print_cmd(mp, "curveto","c");
24939 } else if ( q!=h ){ 
24940   mp_ps_pair_out(mp, x_coord(q),y_coord(q));
24941   mp_ps_print_cmd(mp, "lineto","l");
24942 }
24943
24944 @ Two types of straight lines come up often in \MP\ paths:
24945 cubics with zero initial and final velocity as created by |make_path| or
24946 |make_envelope|, and cubics with control points uniformly spaced on a line
24947 as created by |make_choices|.
24948
24949 @d bend_tolerance 131 /* allow rounding error of $2\cdot10^{-3}$ */
24950
24951 @<Set |curved:=false| if the cubic from |p| to |q| is almost straight@>=
24952 if ( right_x(p)==x_coord(p) )
24953   if ( right_y(p)==y_coord(p) )
24954     if ( left_x(q)==x_coord(q) )
24955       if ( left_y(q)==y_coord(q) ) curved=false;
24956 d=left_x(q)-right_x(p);
24957 if ( abs(right_x(p)-x_coord(p)-d)<=bend_tolerance )
24958   if ( abs(x_coord(q)-left_x(q)-d)<=bend_tolerance )
24959     { d=left_y(q)-right_y(p);
24960     if ( abs(right_y(p)-y_coord(p)-d)<=bend_tolerance )
24961       if ( abs(y_coord(q)-left_y(q)-d)<=bend_tolerance ) curved=false;
24962     }
24963
24964 @ We need to keep track of several parameters from the \ps\ graphics state.
24965 @^graphics state@>
24966 This allows us to be sure that \ps\ has the correct values when they are
24967 needed without wasting time and space setting them unnecessarily.
24968
24969 @d gs_node_size 10
24970 @d gs_red        mp->mem[mp->gs_state+1].sc
24971 @d gs_green      mp->mem[mp->gs_state+2].sc
24972 @d gs_blue       mp->mem[mp->gs_state+3].sc
24973 @d gs_black      mp->mem[mp->gs_state+4].sc
24974    /* color from the last \&{setcmykcolor} or \&{setrgbcolor} or \&{setgray} command */
24975 @d gs_colormodel mp->mem[mp->gs_state+5].qqqq.b0
24976    /* the current colormodel */
24977 @d gs_ljoin      mp->mem[mp->gs_state+5].qqqq.b1
24978 @d gs_lcap       mp->mem[mp->gs_state+5].qqqq.b2
24979    /* values from the last \&{setlinejoin} and \&{setlinecap} commands */
24980 @d gs_adj_wx     mp->mem[mp->gs_state+5].qqqq.b3
24981    /* what resolution-dependent adjustment applies to the width */
24982 @d gs_miterlim   mp->mem[mp->gs_state+6].sc
24983    /* the value from the last \&{setmiterlimit} command */
24984 @d gs_dash_p     mp->mem[mp->gs_state+7].hh.lh
24985    /* edge structure for last \&{setdash} command */
24986 @d gs_previous   mp->mem[mp->gs_state+7].hh.rh
24987    /* backlink to the previous |gs_state| structure */
24988 @d gs_dash_sc    mp->mem[mp->gs_state+8].sc
24989    /* scale factor used with |gs_dash_p| */
24990 @d gs_width      mp->mem[mp->gs_state+9].sc
24991    /* width setting or $-1$ if no \&{setlinewidth} command so far */
24992
24993 @<Glob...@>=
24994 pointer gs_state;
24995
24996 @ @<Set init...@>=
24997 mp->gs_state=null;
24998
24999 @ To avoid making undue assumptions about the initial graphics state, these
25000 parameters are given special values that are guaranteed not to match anything
25001 in the edge structure being shipped out.  On the other hand, the initial color
25002 should be black so that the translation of an all-black picture will have no
25003 \&{setcolor} commands.  (These would be undesirable in a font application.)
25004 Hence we use |c=0| when initializing the graphics state and we use |c<0|
25005 to recover from a situation where we have lost track of the graphics state.
25006
25007 @<Declare the \ps\ output procedures@>=
25008 void mp_unknown_graphics_state (MP mp,scaled c) ;
25009
25010 @ @c void mp_unknown_graphics_state (MP mp,scaled c) {
25011   pointer p; /* to shift graphic states around */
25012   quarterword k; /* a loop index for copying the |gs_state| */
25013   if ( (c==0)||(c==-1) ) {
25014     if ( mp->gs_state==null ) {
25015       mp->gs_state = mp_get_node(mp, gs_node_size);
25016       gs_previous=null;
25017     } else {
25018       while ( gs_previous!=null ) {
25019         p = gs_previous;
25020         mp_free_node(mp, mp->gs_state,gs_node_size);
25021         mp->gs_state=p;
25022       }
25023     }
25024     gs_red=c; gs_green=c; gs_blue=c; gs_black=c;
25025     gs_colormodel=mp_uninitialized_model;
25026     gs_ljoin=3;
25027     gs_lcap=3;
25028     gs_miterlim=0;
25029     gs_dash_p=mp_void;
25030     gs_dash_sc=0;
25031     gs_width=-1;
25032   } else if ( c==1 ) {
25033     p= mp->gs_state;
25034     mp->gs_state = mp_get_node(mp, gs_node_size);
25035     for (k=1;k<=gs_node_size-1;k++)
25036       mp->mem[mp->gs_state+k]=mp->mem[p+k];
25037     gs_previous = p;
25038   } else if ( c==2 ) {
25039     p = gs_previous;
25040     mp_free_node(mp, mp->gs_state,gs_node_size);
25041     mp->gs_state=p;
25042   }
25043 }
25044
25045 @ When it is time to output a graphical object, |fix_graphics_state| ensures
25046 that \ps's idea of the graphics state agrees with what is stored in the object.
25047
25048 @<Declare the \ps\ output procedures@>=
25049 @<Declare subroutines needed by |fix_graphics_state|@>;
25050 void mp_fix_graphics_state (MP mp, pointer p) ;
25051
25052 @ @c 
25053 void mp_fix_graphics_state (MP mp, pointer p) {
25054   /* get ready to output graphical object |p| */
25055   pointer hh,pp; /* for list manipulation */
25056   scaled wx,wy,ww; /* dimensions of pen bounding box */
25057   boolean adj_wx; /* whether pixel rounding should be based on |wx| or |wy| */
25058   integer tx,ty; /* temporaries for computing |adj_wx| */
25059   scaled scf; /* a scale factor for the dash pattern */
25060   if ( has_color(p) )
25061     @<Make sure \ps\ will use the right color for object~|p|@>;
25062   if ( (type(p)==mp_fill_code)||(type(p)==mp_stroked_code) )
25063     if ( pen_p(p)!=null )
25064       if ( pen_is_elliptical(pen_p(p)) ) {
25065         @<Generate \ps\ code that sets the stroke width to the
25066           appropriate rounded value@>;
25067         @<Make sure \ps\ will use the right dash pattern for |dash_p(p)|@>;
25068         @<Decide whether the line cap parameter matters and set it if necessary@>;
25069         @<Set the other numeric parameters as needed for object~|p|@>;
25070       }
25071   if ( mp->ps_offset>0 ) mp_print_ln(mp);
25072 }
25073
25074 @ @<Decide whether the line cap parameter matters and set it if necessary@>=
25075 if ( type(p)==mp_stroked_code )
25076   if ( (left_type(path_p(p))==mp_endpoint)||(dash_p(p)!=null) )
25077     if ( gs_lcap!=lcap_val(p) ) {
25078       ps_room(13);
25079       mp_print_char(mp, ' ');
25080       mp_print_char(mp, '0'+lcap_val(p)); 
25081       mp_ps_print_cmd(mp, " setlinecap"," lc");
25082       gs_lcap=lcap_val(p);
25083     }
25084
25085 @ @<Set the other numeric parameters as needed for object~|p|@>=
25086 if ( gs_ljoin!=ljoin_val(p) ) {
25087   ps_room(14);
25088   mp_print_char(mp, ' ');
25089   mp_print_char(mp, '0'+ljoin_val(p)); mp_ps_print_cmd(mp, " setlinejoin"," lj");
25090   gs_ljoin=ljoin_val(p);
25091 }
25092 if ( gs_miterlim!=miterlim_val(p) ) {
25093   ps_room(27);
25094   mp_print_char(mp, ' ');
25095   mp_print_scaled(mp, miterlim_val(p)); mp_ps_print_cmd(mp, " setmiterlimit"," ml");
25096   gs_miterlim=miterlim_val(p);
25097 }
25098
25099 @ @<Make sure \ps\ will use the right color for object~|p|@>=
25100 {
25101   if ( (color_model(p)==mp_rgb_model)||
25102      ((color_model(p)==mp_uninitialized_model)&&
25103      ((mp->internal[mp_default_color_model] / unity)==mp_rgb_model)) ) {
25104   if ( (gs_colormodel!=mp_rgb_model)||(gs_red!=red_val(p))||
25105       (gs_green!=green_val(p))||(gs_blue!=blue_val(p)) ) {
25106       gs_red=red_val(p);
25107       gs_green=green_val(p);
25108       gs_blue=blue_val(p);
25109       gs_black= -1;
25110       gs_colormodel=mp_rgb_model;
25111       { ps_room(36);
25112         mp_print_char(mp, ' ');
25113         mp_print_scaled(mp, gs_red); mp_print_char(mp, ' ');
25114         mp_print_scaled(mp, gs_green); mp_print_char(mp, ' ');
25115         mp_print_scaled(mp, gs_blue);
25116         mp_ps_print_cmd(mp, " setrgbcolor", " R");
25117       }
25118     }
25119   } else if ( (color_model(p)==mp_cmyk_model)||
25120      ((color_model(p)==mp_uninitialized_model)&&
25121      ((mp->internal[mp_default_color_model] / unity)==mp_cmyk_model)) ) {
25122    if ( (gs_red!=cyan_val(p))||(gs_green!=magenta_val(p))||
25123       (gs_blue!=yellow_val(p))||(gs_black!=black_val(p))||
25124       (gs_colormodel!=mp_cmyk_model) ) {
25125       if ( color_model(p)==mp_uninitialized_model ) {
25126         gs_red=0;
25127         gs_green=0;
25128         gs_blue=0;
25129         gs_black=unity;
25130       } else {
25131         gs_red=cyan_val(p);
25132         gs_green=magenta_val(p);
25133         gs_blue=yellow_val(p);
25134         gs_black=black_val(p);
25135       }
25136       gs_colormodel=mp_cmyk_model;
25137       { ps_room(45);
25138         mp_print_char(mp, ' ');
25139         mp_print_scaled(mp, gs_red); mp_print_char(mp, ' ');
25140         mp_print_scaled(mp, gs_green); mp_print_char(mp, ' ');
25141         mp_print_scaled(mp, gs_blue); mp_print_char(mp, ' ');
25142         mp_print_scaled(mp, gs_black);
25143         mp_ps_print_cmd(mp, " setcmykcolor"," C");
25144       }
25145     }
25146   } else if ( (color_model(p)==mp_grey_model)||
25147     ((color_model(p)==mp_uninitialized_model)&&
25148      ((mp->internal[mp_default_color_model] / unity)==mp_grey_model)) ) {
25149    if ( (gs_red!=grey_val(p))||(gs_colormodel!=mp_grey_model) ) {
25150       gs_red = grey_val(p);
25151       gs_green= -1;
25152       gs_blue= -1;
25153       gs_black= -1;
25154       gs_colormodel=mp_grey_model;
25155       { ps_room(16);
25156         mp_print_char(mp, ' ');
25157         mp_print_scaled(mp, gs_red);
25158         mp_ps_print_cmd(mp, " setgray"," G");
25159       }
25160     }
25161   }
25162   if ( color_model(p)==mp_no_model )
25163     gs_colormodel=mp_no_model;
25164 }
25165
25166 @ In order to get consistent widths for horizontal and vertical pen strokes, we
25167 want \ps\ to use an integer number of pixels for the \&{setwidth} parameter.
25168 @:setwidth}{\&{setwidth}command@>
25169 We set |gs_width| to the ideal horizontal or vertical stroke width and then
25170 generate \ps\ code that computes the rounded value.  For non-circular pens, the
25171 pen shape will be rescaled so that horizontal or vertical parts of the stroke
25172 have the computed width.
25173
25174 Rounding the width to whole pixels is not likely to improve the appearance of
25175 diagonal or curved strokes, but we do it anyway for consistency.  The
25176 \&{truncate} command generated here tends to make all the strokes a little
25177 @:truncate}{\&{truncate} command@>
25178 thinner, but this is appropriate for \ps's scan-conversion rules.  Even with
25179 truncation, an ideal with of $w$~pixels gets mapped into $\lfloor w\rfloor+1$.
25180 It would be better to have $\lceil w\rceil$ but that is ridiculously expensive
25181 to compute in \ps.
25182
25183 @<Generate \ps\ code that sets the stroke width...@>=
25184 @<Set |wx| and |wy| to the width and height of the bounding box for
25185   |pen_p(p)|@>;
25186 @<Use |pen_p(p)| and |path_p(p)| to decide whether |wx| or |wy| is more
25187   important and set |adj_wx| and |ww| accordingly@>;
25188 if ( (ww!=gs_width) || (adj_wx!=gs_adj_wx) ) {
25189   if ( adj_wx ) {
25190     ps_room(13);
25191     mp_print_char(mp, ' '); mp_print_scaled(mp, ww);
25192     mp_ps_print_cmd(mp, 
25193       " 0 dtransform exch truncate exch idtransform pop setlinewidth"," hlw");
25194   } else {
25195     if ( mp->internal[mp_procset]>0 ) {
25196       ps_room(13);
25197       mp_print_char(mp, ' ');
25198       mp_print_scaled(mp, ww);
25199       mp_ps_print(mp, " vlw");
25200     } else { 
25201       ps_room(15);
25202       mp_print(mp, " 0 "); mp_print_scaled(mp, ww);
25203       mp_ps_print(mp, " dtransform truncate idtransform setlinewidth pop");
25204     }
25205   }
25206   gs_width = ww;
25207   gs_adj_wx = adj_wx;
25208 }
25209
25210 @ @<Set |wx| and |wy| to the width and height of the bounding box for...@>=
25211 pp=pen_p(p);
25212 if ( (right_x(pp)==x_coord(pp)) && (left_y(pp)==y_coord(pp)) ) {
25213   wx = abs(left_x(pp) - x_coord(pp));
25214   wy = abs(right_y(pp) - y_coord(pp));
25215 } else {
25216   wx = mp_pyth_add(mp, left_x(pp)-x_coord(pp), right_x(pp)-x_coord(pp));
25217   wy = mp_pyth_add(mp, left_y(pp)-y_coord(pp), right_y(pp)-y_coord(pp));
25218 }
25219
25220 @ The path is considered ``essentially horizontal'' if its range of
25221 $y$~coordinates is less than the $y$~range |wy| for the pen.  ``Essentially
25222 vertical'' paths are detected similarly.  This code ensures that no component
25223 of the pen transformation is more that |aspect_bound*(ww+1)|.
25224
25225 @d aspect_bound 10 /* ``less important'' of |wx|, |wy| cannot exceed the other by
25226     more than this factor */
25227
25228 @<Use |pen_p(p)| and |path_p(p)| to decide whether |wx| or |wy| is more...@>=
25229 tx=1; ty=1;
25230 if ( mp_coord_rangeOK(mp, path_p(p), y_loc(0), wy) ) tx=aspect_bound;
25231 else if ( mp_coord_rangeOK(mp, path_p(p), x_loc(0), wx) ) ty=aspect_bound;
25232 if ( wy / ty>=wx / tx ) { ww=wy; adj_wx=false; }
25233 else { ww=wx; adj_wx=true;  }
25234
25235 @ This routine quickly tests if path |h| is ``essentially horizontal'' or
25236 ``essentially vertical,'' where |zoff| is |x_loc(0)| or |y_loc(0)| and |dz| is
25237 allowable range for $x$ or~$y$.  We do not need and cannot afford a full
25238 bounding-box computation.
25239
25240 @<Declare subroutines needed by |fix_graphics_state|@>=
25241 boolean mp_coord_rangeOK (MP mp,pointer h, 
25242                           small_number  zoff, scaled dz) {
25243   pointer p; /* for scanning the path form |h| */
25244   scaled zlo,zhi; /* coordinate range so far */
25245   scaled z; /* coordinate currently being tested */
25246   zlo=knot_coord(h+zoff);
25247   zhi=zlo;
25248   p=h;
25249   while ( right_type(p)!=mp_endpoint ) {
25250     z=right_coord(p+zoff);
25251     @<Make |zlo..zhi| include |z| and |return false| if |zhi-zlo>dz|@>;
25252     p=link(p);
25253     z=left_coord(p+zoff);
25254     @<Make |zlo..zhi| include |z| and |return false| if |zhi-zlo>dz|@>;
25255     z=knot_coord(p+zoff);
25256     @<Make |zlo..zhi| include |z| and |return false| if |zhi-zlo>dz|@>;
25257     if ( p==h ) break;
25258   }
25259   return true;
25260 }
25261
25262 @ @<Make |zlo..zhi| include |z| and |return false| if |zhi-zlo>dz|@>=
25263 if ( z<zlo ) zlo=z;
25264 else if ( z>zhi ) zhi=z;
25265 if ( zhi-zlo>dz ) return false
25266
25267 @ Filling with an elliptical pen is implemented via a combination of \&{stroke}
25268 and \&{fill} commands and a nontrivial dash pattern would interfere with this.
25269 @:stroke}{\&{stroke} command@>
25270 @:fill}{\&{fill} command@>
25271 Note that we don't use |delete_edge_ref| because |gs_dash_p| is not counted as
25272 a reference.
25273
25274 @<Make sure \ps\ will use the right dash pattern for |dash_p(p)|@>=
25275 if ( type(p)==mp_fill_code ) {
25276   hh=null;
25277 } else { 
25278   hh=dash_p(p);
25279   scf=mp_get_pen_scale(mp, pen_p(p));
25280   if ( scf==0 ) {
25281     if ( gs_width==0 ) scf=dash_scale(p);  else hh=null;
25282   } else { 
25283     scf=mp_make_scaled(mp, gs_width,scf);
25284     scf=mp_take_scaled(mp, scf,dash_scale(p));
25285   }
25286 }
25287 if ( hh==null ) {
25288   if ( gs_dash_p!=null ) {
25289     mp_ps_print_cmd(mp, " [] 0 setdash"," rd");
25290     gs_dash_p=null;
25291   }
25292 } else if ( (gs_dash_sc!=scf) || ! mp_same_dashes(mp, gs_dash_p,hh) ) {
25293   @<Set the dash pattern from |dash_list(hh)| scaled by |scf|@>;
25294 }
25295
25296 @ Translating a dash list into \ps\ is very similar to printing it symbolically
25297 in |print_edges|.  A dash pattern with |dash_y(hh)=0| has length zero and is
25298 ignored.  The same fate applies in the bizarre case of a dash pattern that
25299 cannot be printed without overflow.
25300
25301 @<Set the dash pattern from |dash_list(hh)| scaled by |scf|@>=
25302 { gs_dash_p=hh;
25303   gs_dash_sc=scf;
25304   if ( (dash_y(hh)==0) || (abs(dash_y(hh)) / unity >= el_gordo / scf)){
25305     mp_ps_print_cmd(mp, " [] 0 setdash"," rd");
25306   } else { 
25307     pp=dash_list(hh);
25308     start_x(null_dash)=start_x(pp)+dash_y(hh);
25309     ps_room(28);
25310     mp_print(mp, " [");
25311     while ( pp!=null_dash ) {
25312       mp_ps_pair_out(mp, mp_take_scaled(mp, stop_x(pp)-start_x(pp),scf),
25313                          mp_take_scaled(mp, start_x(link(pp))-stop_x(pp),scf));
25314       pp=link(pp);
25315     }
25316     ps_room(22);
25317     mp_print(mp, "] ");
25318     mp_print_scaled(mp, mp_take_scaled(mp, mp_dash_offset(mp, hh),scf));
25319     mp_ps_print_cmd(mp, " setdash"," sd");
25320   }
25321 }
25322
25323 @ @<Declare subroutines needed by |fix_graphics_state|@>=
25324 boolean mp_same_dashes (MP mp,pointer h, pointer hh) ;
25325
25326 @ @c
25327 boolean mp_same_dashes (MP mp,pointer h, pointer hh) {
25328   /* do |h| and |hh| represent the same dash pattern? */
25329   pointer p,pp; /* dash nodes being compared */
25330   if ( h==hh ) return true;
25331   else if ( (h<=mp_void)||(hh<=mp_void) ) return false;
25332   else if ( dash_y(h)!=dash_y(hh) ) return false;
25333   else { @<Compare |dash_list(h)| and |dash_list(hh)|@>; }
25334   return false; /* can't happen */
25335 }
25336
25337 @ @<Compare |dash_list(h)| and |dash_list(hh)|@>=
25338 { p=dash_list(h);
25339   pp=dash_list(hh);
25340   while ( (p!=null_dash)&&(pp!=null_dash) ) {
25341     if ( (start_x(p)!=start_x(pp))||(stop_x(p)!=stop_x(pp)) ) {
25342       break;
25343     } else { 
25344       p=link(p);
25345       pp=link(pp);
25346     }
25347   }
25348   return (p==pp);
25349 }
25350
25351 @ When stroking a path with an elliptical pen, it is necessary to transform
25352 the coordinate system so that a unit circular pen will have the desired shape.
25353 To keep this transformation local, we enclose it in a
25354 $$\&{gsave}\ldots\&{grestore}$$
25355 block. Any translation component must be applied to the path being stroked
25356 while the rest of the transformation must apply only to the pen.
25357 If |fill_also=true|, the path is to be filled as well as stroked so we must
25358 insert commands to do this after giving the path.
25359
25360 @<Declare the \ps\ output procedures@>=
25361 void mp_stroke_ellipse (MP mp,pointer h, boolean fill_also) ;
25362
25363
25364 @c void mp_stroke_ellipse (MP mp,pointer h, boolean fill_also) {
25365   /* generate an elliptical pen stroke from object |h| */
25366   scaled txx,txy,tyx,tyy; /* transformation parameters */
25367   pointer p; /* the pen to stroke with */
25368   scaled d1,det; /* for tweaking transformation parameters */
25369   integer s; /* also for tweaking transformation paramters */
25370   boolean transformed; /* keeps track of whether gsave/grestore are needed */
25371   transformed=false;
25372   @<Use |pen_p(h)| to set the transformation parameters and give the initial
25373     translation@>;
25374   @<Tweak the transformation parameters so the transformation is nonsingular@>;
25375   mp_ps_path_out(mp, path_p(h));
25376   if ( mp->internal[mp_procset]==0 ) {
25377     if ( fill_also ) mp_print_nl(mp, "gsave fill grestore");
25378     @<Issue \ps\ commands to transform the coordinate system@>;
25379     mp_ps_print(mp, " stroke");
25380     if ( transformed ) mp_ps_print(mp, " grestore");
25381   } else {
25382     if ( fill_also ) mp_print_nl(mp, "B"); else mp_print_ln(mp);
25383     if ( (txy!=0)||(tyx!=0) ) {
25384       mp_print(mp, " [");
25385       mp_ps_pair_out(mp, txx,tyx);
25386       mp_ps_pair_out(mp, txy,tyy);
25387       mp_ps_print(mp, "0 0] t");
25388     } else if ((txx!=unity)||(tyy!=unity) )  {
25389       mp_ps_pair_out(mp,txx,tyy);
25390       mp_print(mp, " s");
25391     };
25392     mp_ps_print(mp, " S");
25393     if ( transformed ) mp_ps_print(mp, " Q");
25394   }
25395   mp_print_ln(mp);
25396 }
25397
25398 @ @<Use |pen_p(h)| to set the transformation parameters and give the...@>=
25399 p=pen_p(h);
25400 txx=left_x(p);
25401 tyx=left_y(p);
25402 txy=right_x(p);
25403 tyy=right_y(p);
25404 if ( (x_coord(p)!=0)||(y_coord(p)!=0) ) {
25405   mp_print_nl(mp, ""); mp_ps_print_cmd(mp, "gsave ","q ");
25406   mp_ps_pair_out(mp, x_coord(p),y_coord(p));
25407   mp_ps_print(mp, "translate ");
25408   txx-=x_coord(p);
25409   tyx-=y_coord(p);
25410   txy-=x_coord(p);
25411   tyy-=y_coord(p);
25412   transformed=true;
25413 } else {
25414   mp_print_nl(mp, "");
25415 }
25416 @<Adjust the transformation to account for |gs_width| and output the
25417   initial \&{gsave} if |transformed| should be |true|@>
25418
25419 @ @<Adjust the transformation to account for |gs_width| and output the...@>=
25420 if ( gs_width!=unity ) {
25421   if ( gs_width==0 ) { 
25422     txx=unity; tyy=unity;
25423   } else { 
25424     txx=mp_make_scaled(mp, txx,gs_width);
25425     txy=mp_make_scaled(mp, txy,gs_width);
25426     tyx=mp_make_scaled(mp, tyx,gs_width);
25427     tyy=mp_make_scaled(mp, tyy,gs_width);
25428   };
25429 }
25430 if ( (txy!=0)||(tyx!=0)||(txx!=unity)||(tyy!=unity) ) {
25431   if ( (! transformed) ){ 
25432     mp_ps_print_cmd(mp, "gsave ","q ");
25433     transformed=true;
25434   }
25435 }
25436
25437 @ @<Issue \ps\ commands to transform the coordinate system@>=
25438 if ( (txy!=0)||(tyx!=0) ){ 
25439   mp_print_ln(mp);
25440   mp_print_char(mp, '[');
25441   mp_ps_pair_out(mp, txx,tyx);
25442   mp_ps_pair_out(mp, txy,tyy);
25443   mp_ps_print(mp, "0 0] concat");
25444 } else if ( (txx!=unity)||(tyy!=unity) ){ 
25445   mp_print_ln(mp);
25446   mp_ps_pair_out(mp, txx,tyy);
25447   mp_print(mp, "scale");
25448 }
25449
25450 @ The \ps\ interpreter will probably abort if it encounters a singular
25451 transformation matrix.  The determinant must be large enough to ensure that
25452 the printed representation will be nonsingular.  Since the printed
25453 representation is always within $2^{-17}$ of the internal |scaled| value, the
25454 total error is at most $4T_{\rm max}2^{-17}$, where $T_{\rm max}$ is a bound on
25455 the magnitudes of |txx/65536|, |txy/65536|, etc.
25456
25457 The |aspect_bound*(gs_width+1)| bound on the components of the pen
25458 transformation allows $T_{\rm max}$ to be at most |2*aspect_bound|.
25459
25460 @<Tweak the transformation parameters so the transformation is nonsingular@>=
25461 det=mp_take_scaled(mp, txx,tyy) - mp_take_scaled(mp, txy,tyx);
25462 d1=4*aspect_bound+1;
25463 if ( abs(det)<d1 ) { 
25464   if ( det>=0 ) { d1=d1-det; s=1;  }
25465   else { d1=-d1-det; s=-1;  };
25466   d1=d1*unity;
25467   if ( abs(txx)+abs(tyy)>=abs(txy)+abs(tyy) ) {
25468     if ( abs(txx)>abs(tyy) ) tyy=tyy+(d1+s*abs(txx)) / txx;
25469     else txx=txx+(d1+s*abs(tyy)) / tyy;
25470   } else {
25471     if ( abs(txy)>abs(tyx) ) tyx=tyx+(d1+s*abs(txy)) / txy;
25472     else txy=txy+(d1+s*abs(tyx)) / tyx;
25473   }
25474 }
25475
25476 @ Here is a simple routine that just fills a cycle.
25477
25478 @<Declare the \ps\ output procedures@>=
25479 void mp_ps_fill_out (MP mp,pointer p) ;
25480
25481 @ @c
25482 void mp_ps_fill_out (MP mp,pointer p) { /* fill cyclic path~|p| */
25483   mp_ps_path_out(mp, p);
25484   mp_ps_print_cmd(mp, " fill"," F");
25485   mp_print_ln(mp);
25486 }
25487
25488 @ Given a cyclic path~|p| and a graphical object~|h|, the |do_outer_envelope|
25489 procedure fills the cycle generated by |make_envelope|.  It need not do
25490 anything unless some region has positive winding number with respect to~|p|,
25491 but it does not seem worthwhile to test for this.
25492
25493 @<Declare the \ps\ output procedures@>=
25494 void mp_do_outer_envelope (MP mp,pointer p, pointer h) ;
25495
25496 @ @c
25497 void mp_do_outer_envelope (MP mp,pointer p, pointer h) {
25498   p=mp_make_envelope(mp, p, pen_p(h), ljoin_val(h), 0, miterlim_val(h));
25499   mp_ps_fill_out(mp, p);
25500   mp_toss_knot_list(mp, p);
25501 }
25502
25503 @ A text node may specify an arbitrary transformation but the usual case
25504 involves only shifting, scaling, and occasionally rotation.  The purpose
25505 of |choose_scale| is to select a scale factor so that the remaining
25506 transformation is as ``nice'' as possible.  The definition of ``nice''
25507 is somewhat arbitrary but shifting and $90^\circ$ rotation are especially
25508 nice because they work out well for bitmap fonts.  The code here selects
25509 a scale factor equal to $1/\sqrt2$ times the Frobenius norm of the
25510 non-shifting part of the transformation matrix.  It is careful to avoid
25511 additions that might cause undetected overflow.
25512
25513 @<Declare the \ps\ output procedures@>=
25514 scaled mp_choose_scale (MP mp,pointer p) ;
25515
25516 @ @c scaled mp_choose_scale (MP mp,pointer p) {
25517   /* |p| should point to a text node */
25518   scaled a,b,c,d,ad,bc; /* temporary values */
25519   a=txx_val(p);
25520   b=txy_val(p);
25521   c=tyx_val(p);
25522   d=tyy_val(p);
25523   if ( (a<0) ) negate(a);
25524   if ( (b<0) ) negate(b);
25525   if ( (c<0) ) negate(c);
25526   if ( (d<0) ) negate(d);
25527   ad=half(a-d);
25528   bc=half(b-c);
25529   return mp_pyth_add(mp, mp_pyth_add(mp, d+ad,ad), mp_pyth_add(mp, c+bc,bc));
25530 }
25531
25532 @ There may be many sizes of one font and we need to keep track of the
25533 characters used for each size.  This is done by keeping a linked list of
25534 sizes for each font with a counter in each text node giving the appropriate
25535 position in the size list for its font.
25536
25537 @d sc_factor(A) mp->mem[(A)+1].sc /* the scale factor stored in a font size node */
25538 @d font_size_size 2 /* size of a font size node */
25539
25540 @ @<Internal library declarations@>=
25541 boolean mp_has_font_size(MP mp, font_number f );
25542
25543 @ @c 
25544 boolean mp_has_font_size(MP mp, font_number f ) {
25545   return (mp->font_sizes[f]!=null);
25546 }
25547
25548
25549 @ The potential overflow here is caused by the fact the returned value
25550 has to fit in a |name_type|, which is a quarterword. 
25551
25552 @d fscale_tolerance 65 /* that's $.001\times2^{16}$ */
25553
25554 @<Declare the \ps\ output procedures@>=
25555 quarterword mp_size_index (MP mp, font_number f, scaled s) {
25556   pointer p,q; /* the previous and current font size nodes */
25557   quarterword i; /* the size index for |q| */
25558   q=mp->font_sizes[f];
25559   i=0;
25560   while ( q!=null ) {
25561     if ( abs(s-sc_factor(q))<=fscale_tolerance ) 
25562       return i;
25563     else 
25564       { p=q; q=link(q); incr(i); };
25565     if ( i==max_quarterword )
25566       mp_overflow(mp, "sizes per font",max_quarterword);
25567 @:MetaPost capacity exceeded sizes per font}{\quad sizes per font@>
25568   }
25569   q=mp_get_node(mp, font_size_size);
25570   sc_factor(q)=s;
25571   if ( i==0 ) mp->font_sizes[f]=q;  else link(p)=q;
25572   return i;
25573 }
25574
25575 @ @<Internal library ...@>=
25576 scaled mp_indexed_size (MP mp,font_number f, quarterword j);
25577
25578 @ @c
25579 scaled mp_indexed_size (MP mp,font_number f, quarterword j) {
25580   pointer p; /* a font size node */
25581   quarterword i; /* the size index for |p| */
25582   p=mp->font_sizes[f];
25583   i=0;
25584   if ( p==null ) mp_confusion(mp, "size");
25585   while ( (i!=j) ) { 
25586     incr(i); p=link(p);
25587     if ( p==null ) mp_confusion(mp, "size");
25588   }
25589   return sc_factor(p);
25590 }
25591
25592 @ @<Declare the \ps\ output procedures@>=
25593 void mp_clear_sizes (MP mp) ;
25594
25595 @ @c void mp_clear_sizes (MP mp) {
25596   font_number f;  /* the font whose size list is being cleared */
25597   pointer p;  /* current font size nodes */
25598   for (f=null_font+1;f<=mp->last_fnum;f++) {
25599     while ( mp->font_sizes[f]!=null ) {
25600       p=mp->font_sizes[f];
25601       mp->font_sizes[f]=link(p);
25602       mp_free_node(mp, p,font_size_size);
25603     }
25604   }
25605 }
25606
25607 @ The \&{special} command saves up lines of text to be printed during the next
25608 |ship_out| operation.  The saved items are stored as a list of capsule tokens.
25609
25610 @<Glob...@>=
25611 pointer last_pending; /* the last token in a list of pending specials */
25612
25613 @ @<Set init...@>=
25614 mp->last_pending=spec_head;
25615
25616 @ @<Cases of |do_statement|...@>=
25617 case special_command: 
25618   if ( mp->cur_mod==0 ) mp_do_special(mp); else 
25619   if ( mp->cur_mod==1 ) mp_do_mapfile(mp); else 
25620   mp_do_mapline(mp);
25621   break;
25622
25623 @ @<Declare action procedures for use by |do_statement|@>=
25624 void mp_do_special (MP mp) ;
25625
25626 @ @c void mp_do_special (MP mp) { 
25627   mp_get_x_next(mp); mp_scan_expression(mp);
25628   if ( mp->cur_type!=mp_string_type ) {
25629     @<Complain about improper special operation@>;
25630   } else { 
25631     link(mp->last_pending)=mp_stash_cur_exp(mp);
25632     mp->last_pending=link(mp->last_pending);
25633     link(mp->last_pending)=null;
25634   }
25635 }
25636
25637 @ @<Complain about improper special operation@>=
25638
25639   exp_err("Unsuitable expression");
25640   help1("Only known strings are allowed for output as specials.");
25641   mp_put_get_error(mp);
25642 }
25643
25644 @ @<Print any pending specials@>=
25645 t=link(spec_head);
25646 while ( t!=null ) {
25647   mp_print_str(mp, value(t));
25648   mp_print_ln(mp);
25649   t=link(t);
25650 }
25651 mp_flush_token_list(mp, link(spec_head));
25652 link(spec_head)=null;
25653 mp->last_pending=spec_head
25654
25655 @ We are now ready for the main output procedure.  Note that the |selector|
25656 setting is saved in a global variable so that |begin_diagnostic| can access it.
25657
25658 @<Declare the \ps\ output procedures@>=
25659 void mp_ship_out (MP mp, pointer h) ;
25660
25661 @ @c
25662 void mp_ship_out (MP mp, pointer h) { /* output edge structure |h| */
25663   pointer p; /* the current graphical object */
25664   pointer q; /* something that |p| points to */
25665   integer t; /* a temporary value */
25666   font_number f; /* fonts used in a text node or as loop counters */
25667   scaled ds,scf; /* design size and scale factor for a text node */
25668   boolean transformed; /* is the coordinate system being transformed? */
25669   mp_open_output_file(mp);
25670   mp->non_ps_setting=mp->selector;
25671   mp->selector=ps_file_only;
25672   mp_set_bbox(mp, h, true);
25673   mp_print_initial_comment(mp, h, minx_val(h),miny_val(h),maxx_val(h),maxy_val(h));
25674   if ( (mp->internal[mp_prologues]==two)||(mp->internal[mp_prologues]==three) ) {
25675     @<Scan all the text nodes and mark the used characters@>;
25676     @<Update encoding names@>;
25677     mp_print_improved_prologue(mp, h);
25678   } else {
25679     @<Scan all the text nodes and set the |font_sizes| lists;
25680      if |internal[mp_prologues]<=0| list the sizes selected by |choose_scale|,
25681      apply |unmark_font| to each font encountered, and call |mark_string|
25682      whenever the size index is zero@>;
25683     mp_print_prologue(mp, h);
25684   }
25685   @<Print any pending specials@>;
25686   mp_unknown_graphics_state(mp, 0);
25687   mp->need_newpath=true;
25688   p=link(dummy_loc(h));
25689   while ( p!=null ) { 
25690     if ( has_color(p) ) {
25691       if ( (pre_script(p))!=null ) {
25692         mp_print_nl (mp, str(pre_script(p))); mp_print_ln(mp);
25693       }
25694     }
25695     mp_fix_graphics_state(mp, p);
25696     switch (type(p)) {
25697     @<Cases for translating graphical object~|p| into \ps@>;
25698     case mp_start_bounds_code:
25699     case mp_stop_bounds_code:
25700           break;
25701     } /* all cases are enumerated */
25702     p=link(p);
25703   }
25704   mp_ps_print_cmd(mp, "showpage","P"); mp_print_ln(mp);
25705   mp_print(mp, "%%EOF"); mp_print_ln(mp);
25706   fclose(mp->ps_file);
25707   mp->selector=mp->non_ps_setting;
25708   if ( mp->internal[mp_prologues]<=0 ) mp_clear_sizes(mp);
25709   @<End progress report@>;
25710   if ( mp->internal[mp_tracing_output]>0 ) 
25711    mp_print_edges(mp, h," (just shipped out)",true);
25712 }
25713
25714 @ @<Internal library declarations@>=
25715 void mp_apply_mark_string_chars(MP mp, pointer h, int next_size);
25716
25717 @ @c
25718 void mp_apply_mark_string_chars(MP mp, pointer h, int next_size) {
25719   pointer p;
25720   p=link(dummy_loc(h));
25721   while ( p!=null ) {
25722     if ( type(p)==mp_text_code )
25723       if ( font_n(p)!=null_font )
25724         if ( name_type(p)==next_size )
25725           mp_mark_string_chars(mp, font_n(p),text_p(p));
25726     p=link(p);
25727   }
25728 }
25729
25730 @ @<Scan all the text nodes and mark the used ...@>=
25731 for (f=null_font+1;f<=mp->last_fnum;f++) {
25732   if ( mp->font_sizes[f]!=null ) {
25733     mp_unmark_font(mp, f);
25734     mp->font_sizes[f]=null;
25735   }
25736 }
25737 for (f=null_font+1;f<=mp->last_fnum;f++) {
25738   p=link(dummy_loc(h));
25739   while ( p!=null ) {
25740     if ( type(p)==mp_text_code ) {
25741       if ( font_n(p)!=null_font ) {
25742         mp->font_sizes[font_n(p)] = mp_void;
25743         mp_mark_string_chars(mp, font_n(p),text_p(p));
25744         if ( mp_has_fm_entry(mp,font_n(p),NULL) )
25745           mp->font_ps_name[font_n(p)] = mp_fm_font_name(mp,font_n(p));
25746       }
25747     }
25748     p=link(p);
25749   }
25750 }
25751
25752 @ @<Update encoding names@>=
25753 mp_reload_encodings(mp);
25754 p=link(dummy_loc(h));
25755 while ( p!=null ) {
25756   if ( type(p)==mp_text_code )
25757     if ( font_n(p)!=null_font )
25758       if ( mp_has_fm_entry(mp,font_n(p),NULL) )
25759         if ( mp->font_enc_name[font_n(p)]==NULL )
25760           mp->font_enc_name[font_n(p)] = mp_fm_encoding_name(mp,font_n(p));
25761   p=link(p);
25762 }
25763
25764
25765 @ @<Scan all the text nodes and set the |font_sizes| lists;...@>=
25766 for (f=null_font+1;f<=mp->last_fnum;f++) 
25767   mp->font_sizes[f]=null;
25768 p=link(dummy_loc(h));
25769 while ( p!=null ) {
25770   if ( type(p)==mp_text_code ) {
25771     if ( font_n(p)!=null_font ) {
25772       f=font_n(p);
25773       if ( mp->internal[mp_prologues]>0 ) {
25774         mp->font_sizes[f]=mp_void;
25775       } else { 
25776         if ( mp->font_sizes[f]==null )
25777           mp_unmark_font(mp, f);
25778         name_type(p)=mp_size_index(mp, f,mp_choose_scale(mp, p));
25779         if ( name_type(p)==0 )
25780           mp_mark_string_chars(mp, f,text_p(p));
25781       }
25782     }
25783   }
25784   p=link(p);
25785 }
25786
25787
25788
25789
25790 @ @<Cases for translating graphical object~|p| into \ps@>=
25791 case mp_start_clip_code: 
25792   mp_print_nl(mp, ""); mp_ps_print_cmd(mp, "gsave ","q ");
25793   mp_ps_path_out(mp, path_p(p));
25794   mp_ps_print_cmd(mp, " clip"," W");
25795   mp_print_ln(mp);
25796   if ( mp->internal[mp_restore_clip_color]>0 )
25797     mp_unknown_graphics_state(mp, 1);
25798   break;
25799 case mp_stop_clip_code: 
25800   mp_print_nl(mp, ""); mp_ps_print_cmd(mp, "grestore","Q");
25801   mp_print_ln(mp);
25802   if ( mp->internal[mp_restore_clip_color]>0 )
25803     mp_unknown_graphics_state(mp, 2);
25804   else
25805     mp_unknown_graphics_state(mp, -1);
25806   break;
25807
25808 @ @<Cases for translating graphical object~|p| into \ps@>=
25809 case mp_fill_code: 
25810   if ( pen_p(p)==null ) mp_ps_fill_out(mp, path_p(p));
25811   else if ( pen_is_elliptical(pen_p(p)) ) mp_stroke_ellipse(mp, p,true);
25812   else { 
25813     mp_do_outer_envelope(mp, mp_copy_path(mp, path_p(p)), p);
25814     mp_do_outer_envelope(mp, mp_htap_ypoc(mp, path_p(p)), p);
25815   }
25816   if ( (post_script(p))!=null ) {
25817     mp_print_nl (mp, str(post_script(p))); mp_print_ln(mp);
25818   };
25819   break;
25820 case mp_stroked_code:
25821   if ( pen_is_elliptical(pen_p(p)) ) mp_stroke_ellipse(mp, p,false);
25822   else { 
25823     q=mp_copy_path(mp, path_p(p));
25824     t=lcap_val(p);
25825     @<Break the cycle and set |t:=1| if path |q| is cyclic@>;
25826     q=mp_make_envelope(mp, q,pen_p(p),ljoin_val(p),t,miterlim_val(p));
25827     mp_ps_fill_out(mp, q);
25828     mp_toss_knot_list(mp, q);
25829   };
25830   if ( (post_script(p))!=null ) {
25831     mp_print_nl (mp, str(post_script(p))); mp_print_ln(mp);
25832   };
25833   break;
25834
25835 @ The envelope of a cyclic path~|q| could be computed by calling
25836 |make_envelope| once for |q| and once for its reversal.  We don't do this
25837 because it would fail color regions that are covered by the pen regardless
25838 of where it is placed on~|q|.
25839
25840 @<Break the cycle and set |t:=1| if path |q| is cyclic@>=
25841 if ( left_type(q)!=mp_endpoint ) { 
25842   left_type(mp_insert_knot(mp, q,x_coord(q),y_coord(q)))=mp_endpoint;
25843   right_type(q)=mp_endpoint;
25844   q=link(q);
25845   t=1;
25846 }
25847
25848 @ @<Cases for translating graphical object~|p| into \ps@>=
25849 case mp_text_code: 
25850   if ( (font_n(p)!=null_font) && (length(text_p(p))>0) ) {
25851     if ( mp->internal[mp_prologues]>0 )
25852       scf=mp_choose_scale(mp, p);
25853     else 
25854       scf=mp_indexed_size(mp, font_n(p), name_type(p));
25855     @<Shift or transform as necessary before outputting text node~|p| at scale
25856       factor~|scf|; set |transformed:=true| if the original transformation must
25857       be restored@>;
25858     mp_ps_string_out(mp, str(text_p(p)));
25859     mp_ps_name_out(mp, mp->font_name[font_n(p)],false);
25860     @<Print the size information and \ps\ commands for text node~|p|@>;
25861     mp_print_ln(mp);
25862   }
25863   if ( (post_script(p))!=null ) {
25864     mp_print_nl (mp, str(post_script(p))); mp_print_ln(mp);
25865   }
25866   break;
25867
25868 @ @<Print the size information and \ps\ commands for text node~|p|@>=
25869 ps_room(18);
25870 mp_print_char(mp, ' ');
25871 ds=(mp->font_dsize[font_n(p)]+8) / 16;
25872 mp_print_scaled(mp, mp_take_scaled(mp, ds,scf));
25873 mp_print(mp, " fshow");
25874 if ( transformed ) 
25875   mp_ps_print_cmd(mp, " grestore"," Q")
25876
25877 @ @<Shift or transform as necessary before outputting text node~|p| at...@>=
25878 transformed=(txx_val(p)!=scf)||(tyy_val(p)!=scf)||
25879             (txy_val(p)!=0)||(tyx_val(p)!=0);
25880 if ( transformed ) {
25881   mp_ps_print_cmd(mp, "gsave [", "q [");
25882   mp_ps_pair_out(mp, mp_make_scaled(mp, txx_val(p),scf),
25883                      mp_make_scaled(mp, tyx_val(p),scf));
25884   mp_ps_pair_out(mp, mp_make_scaled(mp, txy_val(p),scf),
25885                      mp_make_scaled(mp, tyy_val(p),scf));
25886   mp_ps_pair_out(mp, tx_val(p),ty_val(p));
25887   mp_ps_print_cmd(mp, "] concat 0 0 moveto","] t 0 0 m");
25888 } else { 
25889   mp_ps_pair_out(mp, tx_val(p),ty_val(p));
25890   mp_ps_print_cmd(mp, "moveto","m");
25891 }
25892 mp_print_ln(mp)
25893
25894 @ Now that we've finished |ship_out|, let's look at the other commands
25895 by which a user can send things to the \.{GF} file.
25896
25897 @ @<Determine if a character has been shipped out@>=
25898
25899   mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256;
25900   if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
25901   boolean_reset(mp->char_exists[mp->cur_exp]);
25902   mp->cur_type=mp_boolean_type;
25903 }
25904
25905 @ @<Glob...@>=
25906 psout_data ps;
25907
25908 @ @<Allocate or initialize ...@>=
25909 mp_backend_initialize(mp);
25910
25911 @ @<Dealloc...@>=
25912 mp_backend_free(mp);
25913
25914
25915 @* \[45] Dumping and undumping the tables.
25916 After \.{INIMP} has seen a collection of macros, it
25917 can write all the necessary information on an auxiliary file so
25918 that production versions of \MP\ are able to initialize their
25919 memory at high speed. The present section of the program takes
25920 care of such output and input. We shall consider simultaneously
25921 the processes of storing and restoring,
25922 so that the inverse relation between them is clear.
25923 @.INIMP@>
25924
25925 The global variable |mem_ident| is a string that is printed right
25926 after the |banner| line when \MP\ is ready to start. For \.{INIMP} this
25927 string says simply `\.{(INIMP)}'; for other versions of \MP\ it says,
25928 for example, `\.{(mem=plain 90.4.14)}', showing the year,
25929 month, and day that the mem file was created. We have |mem_ident=0|
25930 before \MP's tables are loaded.
25931
25932 @<Glob...@>=
25933 char * mem_ident;
25934
25935 @ @<Set init...@>=
25936 mp->mem_ident=NULL;
25937
25938 @ @<Initialize table entries...@>=
25939 mp->mem_ident=xstrdup(" (INIMP)");
25940
25941 @ @<Declare act...@>=
25942 void mp_store_mem_file (MP mp) ;
25943
25944 @ @c void mp_store_mem_file (MP mp) {
25945   integer k;  /* all-purpose index */
25946   pointer p,q; /* all-purpose pointers */
25947   integer x; /* something to dump */
25948   four_quarters w; /* four ASCII codes */
25949   memory_word WW;
25950   @<Create the |mem_ident|, open the mem file,
25951     and inform the user that dumping has begun@>;
25952   @<Dump constants for consistency check@>;
25953   @<Dump the string pool@>;
25954   @<Dump the dynamic memory@>;
25955   @<Dump the table of equivalents and the hash table@>;
25956   @<Dump a few more things and the closing check word@>;
25957   @<Close the mem file@>;
25958 }
25959
25960 @ Corresponding to the procedure that dumps a mem file, we also have a function
25961 that reads~one~in. The function returns |false| if the dumped mem is
25962 incompatible with the present \MP\ table sizes, etc.
25963
25964 @d off_base 6666 /* go here if the mem file is unacceptable */
25965 @d too_small(A) { wake_up_terminal;
25966   wterm_ln("---! Must increase the "); wterm((A));
25967 @.Must increase the x@>
25968   goto OFF_BASE;
25969   }
25970
25971 @c 
25972 boolean mp_load_mem_file (MP mp) {
25973   integer k; /* all-purpose index */
25974   pointer p,q; /* all-purpose pointers */
25975   integer x; /* something undumped */
25976   str_number s; /* some temporary string */
25977   four_quarters w; /* four ASCII codes */
25978   memory_word WW;
25979   @<Undump constants for consistency check@>;
25980   @<Undump the string pool@>;
25981   @<Undump the dynamic memory@>;
25982   @<Undump the table of equivalents and the hash table@>;
25983   @<Undump a few more things and the closing check word@>;
25984   return true; /* it worked! */
25985 OFF_BASE: 
25986   wake_up_terminal;
25987   wterm_ln("(Fatal mem file error; I'm stymied)\n");
25988 @.Fatal mem file error@>
25989    return false;
25990 }
25991
25992 @ @<Declarations@>=
25993 boolean mp_load_mem_file (MP mp) ;
25994
25995 @ Mem files consist of |memory_word| items, and we use the following
25996 macros to dump words of different types:
25997
25998 @d dump_wd(A)   { WW=(A);       fwrite(&WW,sizeof(WW),1,mp->mem_file); }
25999 @d dump_int(A)  { int cint=(A); fwrite(&cint,sizeof(cint),1,mp->mem_file); }
26000 @d dump_hh(A)   { WW.hh=(A);    fwrite(&WW,sizeof(WW),1,mp->mem_file); }
26001 @d dump_qqqq(A) { WW.qqqq=(A);  fwrite(&WW,sizeof(WW),1,mp->mem_file); }
26002 @d dump_string(A) { dump_int(strlen(A)+1);
26003                     fwrite(A,strlen(A)+1,1,mp->mem_file); }
26004
26005 @<Glob...@>=
26006 FILE * mem_file; /* for input or output of mem information */
26007
26008 @ The inverse macros are slightly more complicated, since we need to check
26009 the range of the values we are reading in. We say `|undump(a)(b)(x)|' to
26010 read an integer value |x| that is supposed to be in the range |a<=x<=b|.
26011
26012 @d undump_wd(A)   { fread(&WW,sizeof(WW),1,mp->mem_file); (A)=WW; }
26013 @d undump_int(A)  { int cint; fread(&cint,sizeof(cint),1,mp->mem_file); (A)=cint; }
26014 @d undump_hh(A)   { fread(&WW,sizeof(WW),1,mp->mem_file); (A)=WW.hh; }
26015 @d undump_qqqq(A) { fread(&WW,sizeof(WW),1,mp->mem_file); (A)=WW.qqqq; }
26016 @d undump_strings(A,B,C) { 
26017    undump_int(x); if ( (x<(A)) || (x>(B)) ) goto OFF_BASE; else (C)=str(x); }
26018 @d undump(A,B,C) { undump_int(x); if ( (x<(A)) || (x>(int)(B)) ) goto OFF_BASE; else (C)=x; }
26019 @d undump_size(A,B,C,D) { undump_int(x);
26020                if (x<(A)) goto OFF_BASE; 
26021                if (x>(B)) { too_small((C)); } else {(D)=x;} }
26022 @d undump_string(A) { integer XX=0; undump_int(XX);
26023                       A = xmalloc(XX,sizeof(char));
26024                       fread(A,XX,1,mp->mem_file); }
26025
26026 @ The next few sections of the program should make it clear how we use the
26027 dump/undump macros.
26028
26029 @<Dump constants for consistency check@>=
26030 dump_int(mp->mem_top);
26031 dump_int(mp->hash_size);
26032 dump_int(mp->hash_prime)
26033 dump_int(mp->param_size);
26034 dump_int(mp->max_in_open);
26035
26036 @ Sections of a \.{WEB} program that are ``commented out'' still contribute
26037 strings to the string pool; therefore \.{INIMP} and \MP\ will have
26038 the same strings. (And it is, of course, a good thing that they do.)
26039 @.WEB@>
26040 @^string pool@>
26041
26042 @<Undump constants for consistency check@>=
26043 undump_int(x); mp->mem_top = x;
26044 undump_int(x); if (mp->hash_size != x) goto OFF_BASE;
26045 undump_int(x); if (mp->hash_prime != x) goto OFF_BASE;
26046 undump_int(x); if (mp->param_size != x) goto OFF_BASE;
26047 undump_int(x); if (mp->max_in_open != x) goto OFF_BASE
26048
26049 @ We do string pool compaction to avoid dumping unused strings.
26050
26051 @d dump_four_ASCII 
26052   w.b0=qi(mp->str_pool[k]); w.b1=qi(mp->str_pool[k+1]);
26053   w.b2=qi(mp->str_pool[k+2]); w.b3=qi(mp->str_pool[k+3]);
26054   dump_qqqq(w)
26055
26056 @<Dump the string pool@>=
26057 mp_do_compaction(mp, mp->pool_size);
26058 dump_int(mp->pool_ptr);
26059 dump_int(mp->max_str_ptr);
26060 dump_int(mp->str_ptr);
26061 k=0;
26062 while ( (mp->next_str[k]==k+1) && (k<=mp->max_str_ptr) ) 
26063   incr(k);
26064 dump_int(k);
26065 while ( k<=mp->max_str_ptr ) { 
26066   dump_int(mp->next_str[k]); incr(k);
26067 }
26068 k=0;
26069 while (1)  { 
26070   dump_int(mp->str_start[k]); /* TODO: valgrind warning here */
26071   if ( k==mp->str_ptr ) {
26072     break;
26073   } else { 
26074     k=mp->next_str[k]; 
26075   }
26076 };
26077 k=0;
26078 while (k+4<mp->pool_ptr ) { 
26079   dump_four_ASCII; k=k+4; 
26080 }
26081 k=mp->pool_ptr-4; dump_four_ASCII;
26082 mp_print_ln(mp); mp_print(mp, "at most "); mp_print_int(mp, mp->max_str_ptr);
26083 mp_print(mp, " strings of total length ");
26084 mp_print_int(mp, mp->pool_ptr)
26085
26086 @ @d undump_four_ASCII 
26087   undump_qqqq(w);
26088   mp->str_pool[k]=qo(w.b0); mp->str_pool[k+1]=qo(w.b1);
26089   mp->str_pool[k+2]=qo(w.b2); mp->str_pool[k+3]=qo(w.b3)
26090
26091 @<Undump the string pool@>=
26092 undump_int(mp->pool_ptr);
26093 mp_reallocate_pool(mp, mp->pool_ptr) ;
26094 undump_int(mp->max_str_ptr);
26095 mp_reallocate_strings (mp,mp->max_str_ptr) ;
26096 undump(0,mp->max_str_ptr,mp->str_ptr);
26097 undump(0,mp->max_str_ptr+1,s);
26098 for (k=0;k<=s-1;k++) 
26099   mp->next_str[k]=k+1;
26100 for (k=s;k<=mp->max_str_ptr;k++) 
26101   undump(s+1,mp->max_str_ptr+1,mp->next_str[k]);
26102 mp->fixed_str_use=0;
26103 k=0;
26104 while (1) { 
26105   undump(0,mp->pool_ptr,mp->str_start[k]);
26106   if ( k==mp->str_ptr ) break;
26107   mp->str_ref[k]=max_str_ref;
26108   incr(mp->fixed_str_use);
26109   mp->last_fixed_str=k; k=mp->next_str[k];
26110 }
26111 k=0;
26112 while ( k+4<mp->pool_ptr ) { 
26113   undump_four_ASCII; k=k+4;
26114 }
26115 k=mp->pool_ptr-4; undump_four_ASCII;
26116 mp->init_str_use=mp->fixed_str_use; mp->init_pool_ptr=mp->pool_ptr;
26117 mp->max_pool_ptr=mp->pool_ptr;
26118 mp->strs_used_up=mp->fixed_str_use;
26119 mp->pool_in_use=mp->str_start[mp->str_ptr]; mp->strs_in_use=mp->fixed_str_use;
26120 mp->max_pl_used=mp->pool_in_use; mp->max_strs_used=mp->strs_in_use;
26121 mp->pact_count=0; mp->pact_chars=0; mp->pact_strs=0;
26122
26123 @ By sorting the list of available spaces in the variable-size portion of
26124 |mem|, we are usually able to get by without having to dump very much
26125 of the dynamic memory.
26126
26127 We recompute |var_used| and |dyn_used|, so that \.{INIMP} dumps valid
26128 information even when it has not been gathering statistics.
26129
26130 @<Dump the dynamic memory@>=
26131 mp_sort_avail(mp); mp->var_used=0;
26132 dump_int(mp->lo_mem_max); dump_int(mp->rover);
26133 p=0; q=mp->rover; x=0;
26134 do {  
26135   for (k=p;k<= q+1;k++) 
26136     dump_wd(mp->mem[k]);
26137   x=x+q+2-p; mp->var_used=mp->var_used+q-p;
26138   p=q+node_size(q); q=rlink(q);
26139 } while (q!=mp->rover);
26140 mp->var_used=mp->var_used+mp->lo_mem_max-p; 
26141 mp->dyn_used=mp->mem_end+1-mp->hi_mem_min;
26142 for (k=p;k<= mp->lo_mem_max;k++ ) 
26143   dump_wd(mp->mem[k]);
26144 x=x+mp->lo_mem_max+1-p;
26145 dump_int(mp->hi_mem_min); dump_int(mp->avail);
26146 for (k=mp->hi_mem_min;k<=mp->mem_end;k++ ) 
26147   dump_wd(mp->mem[k]);
26148 x=x+mp->mem_end+1-mp->hi_mem_min;
26149 p=mp->avail;
26150 while ( p!=null ) { 
26151   decr(mp->dyn_used); p=link(p);
26152 }
26153 dump_int(mp->var_used); dump_int(mp->dyn_used);
26154 mp_print_ln(mp); mp_print_int(mp, x);
26155 mp_print(mp, " memory locations dumped; current usage is ");
26156 mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used)
26157
26158 @ @<Undump the dynamic memory@>=
26159 undump(lo_mem_stat_max+1000,hi_mem_stat_min-1,mp->lo_mem_max);
26160 undump(lo_mem_stat_max+1,mp->lo_mem_max,mp->rover);
26161 p=0; q=mp->rover;
26162 do {  
26163   for (k=p;k<= q+1; k++) 
26164     undump_wd(mp->mem[k]);
26165   p=q+node_size(q);
26166   if ( (p>mp->lo_mem_max)||((q>=rlink(q))&&(rlink(q)!=mp->rover)) ) 
26167     goto OFF_BASE;
26168   q=rlink(q);
26169 } while (q!=mp->rover);
26170 for (k=p;k<=mp->lo_mem_max;k++ ) 
26171   undump_wd(mp->mem[k]);
26172 undump(mp->lo_mem_max+1,hi_mem_stat_min,mp->hi_mem_min);
26173 undump(null,mp->mem_top,mp->avail); mp->mem_end=mp->mem_top;
26174 for (k=mp->hi_mem_min;k<= mp->mem_end;k++) 
26175   undump_wd(mp->mem[k]);
26176 undump_int(mp->var_used); undump_int(mp->dyn_used)
26177
26178 @ A different scheme is used to compress the hash table, since its lower region
26179 is usually sparse. When |text(p)<>0| for |p<=hash_used|, we output three
26180 words: |p|, |hash[p]|, and |eqtb[p]|. The hash table is, of course, densely
26181 packed for |p>=hash_used|, so the remaining entries are output in~a~block.
26182
26183 @<Dump the table of equivalents and the hash table@>=
26184 dump_int(mp->hash_used); 
26185 mp->st_count=frozen_inaccessible-1-mp->hash_used;
26186 for (p=1;p<=mp->hash_used;p++) {
26187   if ( text(p)!=0 ) {
26188      dump_int(p); dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]); incr(mp->st_count);
26189   }
26190 }
26191 for (p=mp->hash_used+1;p<=(int)hash_end;p++) {
26192   dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]);
26193 }
26194 dump_int(mp->st_count);
26195 mp_print_ln(mp); mp_print_int(mp, mp->st_count); mp_print(mp, " symbolic tokens")
26196
26197 @ @<Undump the table of equivalents and the hash table@>=
26198 undump(1,frozen_inaccessible,mp->hash_used); 
26199 p=0;
26200 do {  
26201   undump(p+1,mp->hash_used,p); 
26202   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
26203 } while (p!=mp->hash_used);
26204 for (p=mp->hash_used+1;p<=(int)hash_end;p++ )  { 
26205   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
26206 }
26207 undump_int(mp->st_count)
26208
26209 @ We have already printed a lot of statistics, so we set |mp_tracing_stats:=0|
26210 to prevent them appearing again.
26211
26212 @<Dump a few more things and the closing check word@>=
26213 dump_int(mp->max_internal);
26214 dump_int(mp->int_ptr);
26215 for (k=1;k<= mp->int_ptr;k++ ) { 
26216   dump_int(mp->internal[k]); 
26217   dump_string(mp->int_name[k]);
26218 }
26219 dump_int(mp->start_sym); 
26220 dump_int(mp->interaction); 
26221 dump_string(mp->mem_ident);
26222 dump_int(mp->bg_loc); dump_int(mp->eg_loc); dump_int(mp->serial_no); dump_int(69073);
26223 mp->internal[mp_tracing_stats]=0
26224
26225 @ @<Undump a few more things and the closing check word@>=
26226 undump_int(x);
26227 if (x>mp->max_internal) mp_grow_internals(mp,x);
26228 undump_int(mp->int_ptr);
26229 for (k=1;k<= mp->int_ptr;k++) { 
26230   undump_int(mp->internal[k]);
26231   undump_string(mp->int_name[k]);
26232 }
26233 undump(0,frozen_inaccessible,mp->start_sym);
26234 if (mp->interaction==mp_unspecified_mode) {
26235   undump(mp_unspecified_mode,mp_error_stop_mode,mp->interaction);
26236 } else {
26237   undump(mp_unspecified_mode,mp_error_stop_mode,x);
26238 }
26239 undump_string(mp->mem_ident);
26240 undump(1,hash_end,mp->bg_loc);
26241 undump(1,hash_end,mp->eg_loc);
26242 undump_int(mp->serial_no);
26243 undump_int(x); 
26244 if ( (x!=69073)|| feof(mp->mem_file) ) goto OFF_BASE
26245
26246 @ @<Create the |mem_ident|...@>=
26247
26248   xfree(mp->mem_ident);
26249   mp->mem_ident = xmalloc(256,1);
26250   snprintf(mp->mem_ident,256," (mem=%s %i.%i.%i)", 
26251            mp->job_name,
26252            (int)(mp_round_unscaled(mp, mp->internal[mp_year]) % 100),
26253            (int)mp_round_unscaled(mp, mp->internal[mp_month]),
26254            (int)mp_round_unscaled(mp, mp->internal[mp_day]));
26255   mp_pack_job_name(mp, mem_extension);
26256   while (! mp_w_open_out(mp, &mp->mem_file) )
26257     mp_prompt_file_name(mp, "mem file name", mem_extension);
26258   mp_print_nl(mp, "Beginning to dump on file ");
26259 @.Beginning to dump...@>
26260   mp_print(mp, mp->name_of_file); 
26261   mp_print_nl(mp, mp->mem_ident);
26262 }
26263
26264 @ @<Dealloc variables@>=
26265 xfree(mp->mem_ident);
26266
26267 @ @<Close the mem file@>=
26268 fclose(mp->mem_file)
26269
26270 @* \[46] The main program.
26271 This is it: the part of \MP\ that executes all those procedures we have
26272 written.
26273
26274 Well---almost. We haven't put the parsing subroutines into the
26275 program yet; and we'd better leave space for a few more routines that may
26276 have been forgotten.
26277
26278 @c @<Declare the basic parsing subroutines@>;
26279 @<Declare miscellaneous procedures that were declared |forward|@>;
26280 @<Last-minute procedures@>
26281
26282 @ We've noted that there are two versions of \MP. One, called \.{INIMP},
26283 @.INIMP@>
26284 has to be run first; it initializes everything from scratch, without
26285 reading a mem file, and it has the capability of dumping a mem file.
26286 The other one is called `\.{VIRMP}'; it is a ``virgin'' program that needs
26287 @.VIRMP@>
26288 to input a mem file in order to get started. \.{VIRMP} typically has
26289 a bit more memory capacity than \.{INIMP}, because it does not need the
26290 space consumed by the dumping/undumping routines and the numerous calls on
26291 |primitive|, etc.
26292
26293 The \.{VIRMP} program cannot read a mem file instantaneously, of course;
26294 the best implementations therefore allow for production versions of \MP\ that
26295 not only avoid the loading routine for \PASCAL\ object code, they also have
26296 a mem file pre-loaded. 
26297
26298 @<Glob...@>=
26299 boolean ini_version; /* are we iniMP? */
26300
26301 @ @<Option variables@>=
26302 int ini_version; /* are we iniMP? */
26303
26304 @ @<Set |ini_version|@>=
26305 mp->ini_version = (opt->ini_version ? true : false);
26306
26307 @ Here we do whatever is needed to complete \MP's job gracefully on the
26308 local operating system. The code here might come into play after a fatal
26309 error; it must therefore consist entirely of ``safe'' operations that
26310 cannot produce error messages. For example, it would be a mistake to call
26311 |str_room| or |make_string| at this time, because a call on |overflow|
26312 might lead to an infinite loop.
26313 @^system dependencies@>
26314
26315 This program doesn't bother to close the input files that may still be open.
26316
26317 @<Last-minute...@>=
26318 void mp_close_files_and_terminate (MP mp) {
26319   integer k; /* all-purpose index */
26320   integer LH; /* the length of the \.{TFM} header, in words */
26321   int lk_offset; /* extra words inserted at beginning of |lig_kern| array */
26322   pointer p; /* runs through a list of \.{TFM} dimensions */
26323   @<Close all open files in the |rd_file| and |wr_file| arrays@>;
26324   if ( mp->internal[mp_tracing_stats]>0 )
26325     @<Output statistics about this job@>;
26326   wake_up_terminal; 
26327   @<Do all the finishing work on the \.{TFM} file@>;
26328   @<Explain what output files were written@>;
26329   if ( mp->log_opened ){ 
26330     wlog_cr;
26331     fclose(mp->log_file); mp->selector=mp->selector-2;
26332     if ( mp->selector==term_only ) {
26333       mp_print_nl(mp, "Transcript written on ");
26334 @.Transcript written...@>
26335       mp_print(mp, mp->log_name); mp_print_char(mp, '.');
26336     }
26337   }
26338   mp_print_ln(mp);
26339 }
26340
26341 @ @<Declarations@>=
26342 void mp_close_files_and_terminate (MP mp) ;
26343
26344 @ @<Close all open files in the |rd_file| and |wr_file| arrays@>=
26345 if (mp->rd_fname!=NULL) {
26346   for (k=0;k<=(int)mp->read_files-1;k++ ) {
26347     if ( mp->rd_fname[k]!=NULL ) {
26348       fclose(mp->rd_file[k]);
26349    }
26350  }
26351 }
26352 if (mp->wr_fname!=NULL) {
26353   for (k=0;k<=(int)mp->write_files-1;k++) {
26354     if ( mp->wr_fname[k]!=NULL ) {
26355      fclose(mp->wr_file[k]);
26356     }
26357   }
26358 }
26359
26360 @ @<Dealloc ...@>=
26361 for (k=0;k<(int)mp->max_read_files;k++ ) {
26362   if ( mp->rd_fname[k]!=NULL ) {
26363     fclose(mp->rd_file[k]);
26364     mp_xfree(mp->rd_fname[k]); 
26365   }
26366 }
26367 mp_xfree(mp->rd_file);
26368 mp_xfree(mp->rd_fname);
26369 for (k=0;k<(int)mp->max_write_files;k++) {
26370   if ( mp->wr_fname[k]!=NULL ) {
26371     fclose(mp->wr_file[k]);
26372     mp_xfree(mp->wr_fname[k]); 
26373   }
26374 }
26375 mp_xfree(mp->wr_file);
26376 mp_xfree(mp->wr_fname);
26377
26378
26379 @ We want to produce a \.{TFM} file if and only if |mp_fontmaking| is positive.
26380
26381 We reclaim all of the variable-size memory at this point, so that
26382 there is no chance of another memory overflow after the memory capacity
26383 has already been exceeded.
26384
26385 @<Do all the finishing work on the \.{TFM} file@>=
26386 if ( mp->internal[mp_fontmaking]>0 ) {
26387   @<Make the dynamic memory into one big available node@>;
26388   @<Massage the \.{TFM} widths@>;
26389   mp_fix_design_size(mp); mp_fix_check_sum(mp);
26390   @<Massage the \.{TFM} heights, depths, and italic corrections@>;
26391   mp->internal[mp_fontmaking]=0; /* avoid loop in case of fatal error */
26392   @<Finish the \.{TFM} file@>;
26393 }
26394
26395 @ @<Make the dynamic memory into one big available node@>=
26396 mp->rover=lo_mem_stat_max+1; link(mp->rover)=empty_flag; mp->lo_mem_max=mp->hi_mem_min-1;
26397 if ( mp->lo_mem_max-mp->rover>max_halfword ) mp->lo_mem_max=max_halfword+mp->rover;
26398 node_size(mp->rover)=mp->lo_mem_max-mp->rover; 
26399 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
26400 link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null
26401
26402 @ The present section goes directly to the log file instead of using
26403 |print| commands, because there's no need for these strings to take
26404 up |str_pool| memory when a non-{\bf stat} version of \MP\ is being used.
26405
26406 @<Output statistics...@>=
26407 if ( mp->log_opened ) { 
26408   char s[128];
26409   wlog_ln(" ");
26410   wlog_ln("Here is how much of MetaPost's memory you used:");
26411 @.Here is how much...@>
26412   snprintf(s,128," %i string%s out of %i",(int)mp->max_strs_used-mp->init_str_use,
26413           (mp->max_strs_used!=mp->init_str_use+1 ? "s" : ""),
26414           (int)(mp->max_strings-1-mp->init_str_use));
26415   wlog_ln(s);
26416   snprintf(s,128," %i string characters out of %i",
26417            (int)mp->max_pl_used-mp->init_pool_ptr,
26418            (int)mp->pool_size-mp->init_pool_ptr);
26419   wlog_ln(s);
26420   snprintf(s,128," %i words of memory out of %i",
26421            (int)mp->lo_mem_max+mp->mem_end-mp->hi_mem_min+2,
26422            (int)mp->mem_end+1);
26423   wlog_ln(s);
26424   snprintf(s,128," %i symbolic tokens out of %i", (int)mp->st_count, (int)mp->hash_size);
26425   wlog_ln(s);
26426   snprintf(s,128," %ii, %in, %ip, %ib stack positions out of %ii, %in, %ip, %ib",
26427            (int)mp->max_in_stack,(int)mp->int_ptr,
26428            (int)mp->max_param_stack,(int)mp->max_buf_stack+1,
26429            (int)mp->stack_size,(int)mp->max_internal,(int)mp->param_size,(int)mp->buf_size);
26430   wlog_ln(s);
26431   snprintf(s,128," %i string compactions (moved %i characters, %i strings)",
26432           (int)mp->pact_count,(int)mp->pact_chars,(int)mp->pact_strs);
26433   wlog_ln(s);
26434 }
26435
26436 @ We get to the |final_cleanup| routine when \&{end} or \&{dump} has
26437 been scanned.
26438
26439 @<Last-minute...@>=
26440 void mp_final_cleanup (MP mp) {
26441   small_number c; /* 0 for \&{end}, 1 for \&{dump} */
26442   c=mp->cur_mod;
26443   if ( mp->job_name==NULL ) mp_open_log_file(mp);
26444   while ( mp->input_ptr>0 ) {
26445     if ( token_state ) mp_end_token_list(mp);
26446     else  mp_end_file_reading(mp);
26447   }
26448   while ( mp->loop_ptr!=null ) mp_stop_iteration(mp);
26449   while ( mp->open_parens>0 ) { 
26450     mp_print(mp, " )"); decr(mp->open_parens);
26451   };
26452   while ( mp->cond_ptr!=null ) {
26453     mp_print_nl(mp, "(end occurred when ");
26454 @.end occurred...@>
26455     mp_print_cmd_mod(mp, fi_or_else,mp->cur_if);
26456     /* `\.{if}' or `\.{elseif}' or `\.{else}' */
26457     if ( mp->if_line!=0 ) {
26458       mp_print(mp, " on line "); mp_print_int(mp, mp->if_line);
26459     }
26460     mp_print(mp, " was incomplete)");
26461     mp->if_line=if_line_field(mp->cond_ptr);
26462     mp->cur_if=name_type(mp->cond_ptr); mp->cond_ptr=link(mp->cond_ptr);
26463   }
26464   if ( mp->history!=mp_spotless )
26465     if ( ((mp->history==mp_warning_issued)||(mp->interaction<mp_error_stop_mode)) )
26466       if ( mp->selector==term_and_log ) {
26467     mp->selector=term_only;
26468     mp_print_nl(mp, "(see the transcript file for additional information)");
26469 @.see the transcript file...@>
26470     mp->selector=term_and_log;
26471   }
26472   if ( c==1 ) {
26473     if (mp->ini_version) {
26474       mp_store_mem_file(mp); return;
26475     }
26476     mp_print_nl(mp, "(dump is performed only by INIMP)"); return;
26477 @.dump...only by INIMP@>
26478   }
26479 }
26480
26481 @ @<Declarations@>=
26482 void mp_final_cleanup (MP mp) ;
26483 void mp_init_prim (MP mp) ;
26484 void mp_init_tab (MP mp) ;
26485
26486 @ @<Last-minute...@>=
26487 void mp_init_prim (MP mp) { /* initialize all the primitives */
26488   @<Put each...@>;
26489 }
26490 @#
26491 void mp_init_tab (MP mp) { /* initialize other tables */
26492   integer k; /* all-purpose index */
26493   @<Initialize table entries (done by \.{INIMP} only)@>;
26494 }
26495
26496
26497 @ When we begin the following code, \MP's tables may still contain garbage;
26498 the strings might not even be present. Thus we must proceed cautiously to get
26499 bootstrapped in.
26500
26501 But when we finish this part of the program, \MP\ is ready to call on the
26502 |main_control| routine to do its work.
26503
26504 @<Get the first line...@>=
26505
26506   @<Initialize the input routines@>;
26507   if ( (mp->mem_ident==NULL)||(mp->buffer[loc]=='&') ) {
26508     if ( mp->mem_ident!=NULL ) {
26509       mp_do_initialize(mp); /* erase preloaded mem */
26510     }
26511     if ( ! mp_open_mem_file(mp) ) return mp_fatal_error_stop;
26512     if ( ! mp_load_mem_file(mp) ) {
26513       fclose( mp->mem_file); return mp_fatal_error_stop;
26514     }
26515     fclose( mp->mem_file);
26516     while ( (loc<limit)&&(mp->buffer[loc]==' ') ) incr(loc);
26517   }
26518   mp->buffer[limit]='%';
26519   mp_fix_date_and_time(mp);
26520   mp->sys_random_seed = (scaled)(mp->get_random_seed)(mp);
26521   mp_init_randoms(mp, mp->sys_random_seed);
26522   @<Initialize the print |selector|...@>;
26523   if ( loc<limit ) if ( mp->buffer[loc]!='\\' ) 
26524     mp_start_input(mp); /* \&{input} assumed */
26525 }
26526
26527 @ @<Run inimpost commands@>=
26528 {
26529   mp_get_strings_started(mp);
26530   mp_init_tab(mp); /* initialize the tables */
26531   mp_init_prim(mp); /* call |primitive| for each primitive */
26532   mp->init_str_use=mp->str_ptr; mp->init_pool_ptr=mp->pool_ptr;
26533   mp->max_str_ptr=mp->str_ptr; mp->max_pool_ptr=mp->pool_ptr;
26534   mp_fix_date_and_time(mp);
26535 }
26536
26537
26538 @* \[47] Debugging.
26539 Once \MP\ is working, you should be able to diagnose most errors with
26540 the \.{show} commands and other diagnostic features. But for the initial
26541 stages of debugging, and for the revelation of really deep mysteries, you
26542 can compile \MP\ with a few more aids, including the \PASCAL\ runtime
26543 checks and its debugger. An additional routine called |debug_help|
26544 will also come into play when you type `\.D' after an error message;
26545 |debug_help| also occurs just before a fatal error causes \MP\ to succumb.
26546 @^debugging@>
26547 @^system dependencies@>
26548
26549 The interface to |debug_help| is primitive, but it is good enough when used
26550 with a \PASCAL\ debugger that allows you to set breakpoints and to read
26551 variables and change their values. After getting the prompt `\.{debug \#}', you
26552 type either a negative number (this exits |debug_help|), or zero (this
26553 goes to a location where you can set a breakpoint, thereby entering into
26554 dialog with the \PASCAL\ debugger), or a positive number |m| followed by
26555 an argument |n|. The meaning of |m| and |n| will be clear from the
26556 program below. (If |m=13|, there is an additional argument, |l|.)
26557 @.debug \#@>
26558
26559 @<Last-minute...@>=
26560 void mp_debug_help (MP mp) { /* routine to display various things */
26561   integer k;
26562   int l,m,n;
26563   while (1) { 
26564     wake_up_terminal;
26565     mp_print_nl(mp, "debug # (-1 to exit):"); update_terminal;
26566 @.debug \#@>
26567     m = 0;
26568     fscanf(mp->term_in,"%i",&m);
26569     if ( m<=0 )
26570       return;
26571     n = 0 ;
26572     fscanf(mp->term_in,"%i",&n);
26573     switch (m) {
26574     @<Numbered cases for |debug_help|@>;
26575     default: mp_print(mp, "?"); break;
26576     }
26577   }
26578 }
26579
26580 @ @<Numbered cases...@>=
26581 case 1: mp_print_word(mp, mp->mem[n]); /* display |mem[n]| in all forms */
26582   break;
26583 case 2: mp_print_int(mp, info(n));
26584   break;
26585 case 3: mp_print_int(mp, link(n));
26586   break;
26587 case 4: mp_print_int(mp, eq_type(n)); mp_print_char(mp, ':'); mp_print_int(mp, equiv(n));
26588   break;
26589 case 5: mp_print_variable_name(mp, n);
26590   break;
26591 case 6: mp_print_int(mp, mp->internal[n]);
26592   break;
26593 case 7: mp_do_show_dependencies(mp);
26594   break;
26595 case 9: mp_show_token_list(mp, n,null,100000,0);
26596   break;
26597 case 10: mp_print_str(mp, n);
26598   break;
26599 case 11: mp_check_mem(mp, n>0); /* check wellformedness; print new busy locations if |n>0| */
26600   break;
26601 case 12: mp_search_mem(mp, n); /* look for pointers to |n| */
26602   break;
26603 case 13: l = 0;  fscanf(mp->term_in,"%i",&l); mp_print_cmd_mod(mp, n,l); 
26604   break;
26605 case 14: for (k=0;k<=n;k++) mp_print_str(mp, mp->buffer[k]);
26606   break;
26607 case 15: mp->panicking=! mp->panicking;
26608   break;
26609
26610
26611 @ Saving the filename template
26612
26613 @<Save the filename template@>=
26614
26615   if ( mp->filename_template!=0 ) delete_str_ref(mp->filename_template);
26616   if ( length(mp->cur_exp)==0 ) mp->filename_template=0;
26617   else { 
26618     mp->filename_template=mp->cur_exp; add_str_ref(mp->filename_template);
26619   }
26620 }
26621
26622 @* \[48] System-dependent changes.
26623 This section should be replaced, if necessary, by any special
26624 modification of the program
26625 that are necessary to make \MP\ work at a particular installation.
26626 It is usually best to design your change file so that all changes to
26627 previous sections preserve the section numbering; then everybody's version
26628 will be consistent with the published program. More extensive changes,
26629 which introduce new sections, can be inserted here; then only the index
26630 itself will get a new section number.
26631 @^system dependencies@>
26632
26633 @* \[49] Index.
26634 Here is where you can find all uses of each identifier in the program,
26635 with underlined entries pointing to where the identifier was defined.
26636 If the identifier is only one letter long, however, you get to see only
26637 the underlined entries. {\sl All references are to section numbers instead of
26638 page numbers.}
26639
26640 This index also lists error messages and other aspects of the program
26641 that you might want to look up some day. For example, the entry
26642 for ``system dependencies'' lists all sections that should receive
26643 special attention from people who are installing \MP\ in a new
26644 operating environment. A list of various things that can't happen appears
26645 under ``this can't happen''.
26646 Approximately 25 sections are listed under ``inner loop''; these account
26647 for more than 60\pct! of \MP's running time, exclusive of input and output.