make the backend a callback
[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.20"
88 @d version_string " (Cweb version 0.20)"
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   return mp;
215 }
216 void mp_free (MP mp) {
217   int k; /* loop variable */
218   @<Dealloc variables@>
219   xfree(mp);
220 }
221
222 @ @c
223 void mp_do_initialize ( MP mp) {
224   @<Local variables for initialization@>
225   @<Set initial values of key variables@>
226 }
227 int mp_initialize (MP mp) { /* this procedure gets things started properly */
228   mp->history=mp_fatal_error_stop; /* in case we quit during initialization */
229   @<Install and test the non-local jump buffer@>;
230   t_open_out; /* open the terminal for output */
231   @<Check the ``constant'' values...@>;
232   if ( mp->bad>0 ) {
233         char ss[256];
234     snprintf(ss,256,"Ouch---my internal constants have been clobbered!\n"
235                    "---case %i",(int)mp->bad);
236     do_fprintf(mp->err_out,(char *)ss);
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,100);
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_terminal = 0, /* the terminal */
561   mp_filetype_error, /* the terminal */
562   mp_filetype_program , /* \MP\ language input */
563   mp_filetype_log,  /* the log file */
564   mp_filetype_postscript, /* the postscript output */
565   mp_filetype_memfile, /* memory dumps */
566   mp_filetype_metrics, /* TeX font metric files */
567   mp_filetype_fontmap, /* PostScript font mapping files */
568   mp_filetype_font, /*  PostScript type1 font programs */
569   mp_filetype_encoding, /*  PostScript font encoding files */
570   mp_filetype_text,  /* first text file for readfrom and writeto primitives */
571 };
572 typedef char *(*mp_file_finder)(char *, char *, int);
573 typedef void *(*mp_file_opener)(char *, char *, int);
574 typedef char *(*mp_file_reader)(void *, size_t *);
575 typedef void (*mp_binfile_reader)(void *, void **, size_t *);
576 typedef void (*mp_file_closer)(void *);
577 typedef int (*mp_file_eoftest)(void *);
578 typedef void (*mp_file_flush)(void *);
579 typedef void (*mp_file_writer)(void *, char *);
580 typedef void (*mp_binfile_writer)(void *, void *, size_t);
581 #define NOTTESTING 1
582
583 @ @<Glob...@>=
584 mp_file_finder find_file;
585 mp_file_opener open_file;
586 mp_file_reader read_ascii_file;
587 mp_binfile_reader read_binary_file;
588 mp_file_closer close_file;
589 mp_file_eoftest eof_file;
590 mp_file_flush flush_file;
591 mp_file_writer write_ascii_file;
592 mp_binfile_writer write_binary_file;
593
594 @ @<Option variables@>=
595 mp_file_finder find_file;
596 mp_file_opener open_file;
597 mp_file_reader read_ascii_file;
598 mp_binfile_reader read_binary_file;
599 mp_file_closer close_file;
600 mp_file_eoftest eof_file;
601 mp_file_flush flush_file;
602 mp_file_writer write_ascii_file;
603 mp_binfile_writer write_binary_file;
604
605 @ The default function for finding files is |mp_find_file|. It is 
606 pretty stupid: it will only find files in the current directory.
607
608 This function may disappear altogether, it is currently only
609 used for the default font map file.
610
611 @c
612 char *mp_find_file (char *fname, char *fmode, int ftype)  {
613   if (fmode[0] != 'r' || (! access (fname,R_OK)) || ftype) {  
614      return strdup(fname);
615   }
616   return NULL;
617 }
618
619 @ This has to be done very early on, so it is best to put it in with
620 the |mp_new| allocations
621
622 @d set_callback_option(A) do { mp->A = mp_##A;
623   if (opt->A!=NULL) mp->A = opt->A;
624 } while (0)
625
626 @<Allocate or initialize ...@>=
627 set_callback_option(find_file);
628 set_callback_option(open_file);
629 set_callback_option(read_ascii_file);
630 set_callback_option(read_binary_file);
631 set_callback_option(close_file);
632 set_callback_option(eof_file);
633 set_callback_option(flush_file);
634 set_callback_option(write_ascii_file);
635 set_callback_option(write_binary_file);
636
637 @ Because |mp_find_file| is used so early, it has to be in the helpers
638 section.
639
640 @<Internal ...@>=
641 char *mp_find_file (char *fname, char *fmode, int ftype) ;
642 void *mp_open_file (char *fname, char *fmode, int ftype) ;
643 char *mp_read_ascii_file (void *f, size_t *size) ;
644 void mp_read_binary_file (void *f, void **d, size_t *size) ;
645 void mp_close_file (void *f) ;
646 int mp_eof_file (void *f) ;
647 void mp_flush_file (void *f) ;
648 void mp_write_ascii_file (void *f, char *s) ;
649 void mp_write_binary_file (void *f, void *s, size_t t) ;
650
651 @ The function to open files can now be very short.
652
653 @c
654 void *mp_open_file(char *fname, char *fmode, int ftype)  {
655 #if NOTTESTING
656   if (ftype==mp_filetype_terminal) {
657     return (fmode[0] == 'r' ? stdin : stdout);
658   } else if (ftype==mp_filetype_error) {
659     return stderr;
660   } else if (fname != NULL && (fmode[0] != 'r' || (! access (fname,R_OK)))) {
661     return (void *)fopen(fname, fmode);
662   }
663 #endif
664   return NULL;
665 }
666
667 @ This is a legacy interface: (almost) all file names pass through |name_of_file|.
668
669 @<Glob...@>=
670 char name_of_file[file_name_size+1]; /* the name of a system file */
671 int name_length;/* this many characters are actually
672   relevant in |name_of_file| (the rest are blank) */
673 boolean print_found_names; /* configuration parameter */
674
675 @ @<Option variables@>=
676 int print_found_names; /* configuration parameter */
677
678 @ If this parameter is true, the terminal and log will report the found
679 file names for input files instead of the requested ones. 
680 It is off by default because it creates an extra filename lookup.
681
682 @<Allocate or initialize ...@>=
683 mp->print_found_names = (opt->print_found_names>0 ? true : false);
684
685 @ \MP's file-opening procedures return |false| if no file identified by
686 |name_of_file| could be opened.
687
688 The |OPEN_FILE| macro takes care of the |print_found_names| parameter.
689 It is not used for opening a mem file for read, because that file name 
690 is never printed.
691
692 @d OPEN_FILE(A) do {
693   if (mp->print_found_names) {
694     char *s = (mp->find_file)(mp->name_of_file,A,ftype);
695     if (s!=NULL) {
696       *f = (mp->open_file)(mp->name_of_file,A, ftype); 
697       strncpy(mp->name_of_file,s,file_name_size);
698       xfree(s);
699     } else {
700       *f = NULL;
701     }
702   } else {
703     *f = (mp->open_file)(mp->name_of_file,A, ftype); 
704   }
705 } while (0);
706 return (*f ? true : false)
707
708 @c 
709 boolean mp_a_open_in (MP mp, void **f, int ftype) {
710   /* open a text file for input */
711   OPEN_FILE("r");
712 }
713 @#
714 boolean mp_w_open_in (MP mp, void **f) {
715   /* open a word file for input */
716   *f = (mp->open_file)(mp->name_of_file,"rb",mp_filetype_memfile); 
717   return (*f ? true : false);
718 }
719 @#
720 boolean mp_a_open_out (MP mp, void **f, int ftype) {
721   /* open a text file for output */
722   OPEN_FILE("w");
723 }
724 @#
725 boolean mp_b_open_out (MP mp, void **f, int ftype) {
726   /* open a binary file for output */
727   OPEN_FILE("wb");
728 }
729 @#
730 boolean mp_w_open_out (MP mp, void **f) {
731   /* open a word file for output */
732   int ftype = mp_filetype_memfile;
733   OPEN_FILE("wb");
734 }
735
736 @ @c
737 char *mp_read_ascii_file (void *f, size_t *size) {
738   int c;
739   size_t len = 0, lim = 128;
740   char *s = NULL;
741   *size = 0;
742 #if NOTTESTING
743   c = fgetc(f);
744   if (c==EOF)
745     return NULL;
746   s = malloc(lim); 
747   if (s==NULL) return NULL;
748   while (c!=EOF && c!='\n' && c!='\r') { 
749     if (len==lim) {
750       s =realloc(s, (lim+(lim>>2)));
751       if (s==NULL) return NULL;
752       lim+=(lim>>2);
753     }
754         s[len++] = c;
755     c =fgetc(f);
756   }
757   if (c=='\r') {
758     c = fgetc(f);
759     if (c!=EOF && c!='\n')
760        ungetc(c,f);
761   }
762   s[len] = 0;
763   *size = len;
764 #endif
765   return s;
766 }
767
768 @ @c
769 void mp_write_ascii_file (void *f, char *s) {
770 #if NOTTESTING
771   if (f!=NULL) {
772     fputs(s,f);
773   }
774 #endif
775 }
776
777 @ @c
778 void mp_read_binary_file (void *f, void **data, size_t *size) {
779   size_t len = 0;
780 #if NOTTESTING
781   len = fread(*data,1,*size,f);
782 #endif
783   *size = len;
784 }
785
786 @ @c
787 void mp_write_binary_file (void *f, void *s, size_t size) {
788 #if NOTTESTING
789   if (f!=NULL)
790     fwrite(s,size,1,f);
791 #endif
792 }
793
794
795 @ @c
796 void mp_close_file (void *f) {
797 #if NOTTESTING
798   fclose(f);
799 #endif
800 }
801
802 @ @c
803 int mp_eof_file (void *f) {
804 #if NOTTESTING
805   return feof(f);
806 #else
807   return 0;
808 #endif
809 }
810
811 @ @c
812 void mp_flush_file (void *f) {
813 #if NOTTESTING
814   fflush(f);
815 #endif
816 }
817
818 @ Binary input and output are done with \PASCAL's ordinary |get| and |put|
819 procedures, so we don't have to make any other special arrangements for
820 binary~I/O. Text output is also easy to do with standard \PASCAL\ routines.
821 The treatment of text input is more difficult, however, because
822 of the necessary translation to |ASCII_code| values.
823 \MP's conventions should be efficient, and they should
824 blend nicely with the user's operating environment.
825
826 @ Input from text files is read one line at a time, using a routine called
827 |input_ln|. This function is defined in terms of global variables called
828 |buffer|, |first|, and |last| that will be described in detail later; for
829 now, it suffices for us to know that |buffer| is an array of |ASCII_code|
830 values, and that |first| and |last| are indices into this array
831 representing the beginning and ending of a line of text.
832
833 @<Glob...@>=
834 size_t buf_size; /* maximum number of characters simultaneously present in
835                     current lines of open files */
836 ASCII_code *buffer; /* lines of characters being read */
837 size_t first; /* the first unused position in |buffer| */
838 size_t last; /* end of the line just input to |buffer| */
839 size_t max_buf_stack; /* largest index used in |buffer| */
840
841 @ @<Allocate or initialize ...@>=
842 mp->buf_size = 200;
843 mp->buffer = xmalloc((mp->buf_size+1),sizeof(ASCII_code));
844
845 @ @<Dealloc variables@>=
846 xfree(mp->buffer);
847
848 @ @c
849 void mp_reallocate_buffer(MP mp, size_t l) {
850   ASCII_code *buffer;
851   if (l>max_halfword) {
852     mp_confusion(mp,"buffer size"); /* can't happen (I hope) */
853   }
854   buffer = xmalloc((l+1),sizeof(ASCII_code));
855   memcpy(buffer,mp->buffer,(mp->buf_size+1));
856   xfree(mp->buffer);
857   mp->buffer = buffer ;
858   mp->buf_size = l;
859 }
860
861 @ The |input_ln| function brings the next line of input from the specified
862 field into available positions of the buffer array and returns the value
863 |true|, unless the file has already been entirely read, in which case it
864 returns |false| and sets |last:=first|.  In general, the |ASCII_code|
865 numbers that represent the next line of the file are input into
866 |buffer[first]|, |buffer[first+1]|, \dots, |buffer[last-1]|; and the
867 global variable |last| is set equal to |first| plus the length of the
868 line. Trailing blanks are removed from the line; thus, either |last=first|
869 (in which case the line was entirely blank) or |buffer[last-1]<>" "|.
870 @^inner loop@>
871
872 The variable |max_buf_stack|, which is used to keep track of how large
873 the |buf_size| parameter must be to accommodate the present job, is
874 also kept up to date by |input_ln|.
875
876 @c 
877 boolean mp_input_ln (MP mp, void *f ) {
878   /* inputs the next line or returns |false| */
879   char *s;
880   size_t size = 0; 
881   mp->last=mp->first; /* cf.\ Matthew 19\thinspace:\thinspace30 */
882   s = (mp->read_ascii_file)(f, &size);
883   if (s==NULL)
884         return false;
885   if (size>0) {
886     mp->last = mp->first+size;
887     if ( mp->last>=mp->max_buf_stack ) { 
888       mp->max_buf_stack=mp->last+1;
889       while ( mp->max_buf_stack>=mp->buf_size ) {
890         mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
891       }
892     }
893     memcpy((mp->buffer+mp->first),s,size);
894     /* while ( mp->buffer[mp->last]==' ' ) mp->last--; */
895   } 
896   free(s);
897   return true;
898 }
899
900 @ The user's terminal acts essentially like other files of text, except
901 that it is used both for input and for output. When the terminal is
902 considered an input file, the file variable is called |term_in|, and when it
903 is considered an output file the file variable is |term_out|.
904 @^system dependencies@>
905
906 @<Glob...@>=
907 void * term_in; /* the terminal as an input file */
908 void * term_out; /* the terminal as an output file */
909 void * err_out; /* the terminal as an output file */
910
911 @ Here is how to open the terminal files. In the default configuration,
912 nothing happens except that the command line (if there is one) is copied
913 to the input buffer.  The variable |command_line| will be filled by the 
914 |main| procedure. The copying can not be done earlier in the program 
915 logic because in the |INI| version, the |buffer| is also used for primitive 
916 initialization.
917
918 @^system dependencies@>
919
920 @d t_open_out  do {/* open the terminal for text output */
921     mp->term_out = (mp->open_file)("terminal", "w", mp_filetype_terminal);
922     mp->err_out = (mp->open_file)("error", "w", mp_filetype_error);
923 } while (0)
924 @d t_open_in  do { /* open the terminal for text input */
925     mp->term_in = (mp->open_file)("terminal", "r", mp_filetype_terminal);
926     if (mp->command_line!=NULL) {
927       mp->last = strlen(mp->command_line);
928       strncpy((char *)mp->buffer,mp->command_line,mp->last);
929       xfree(mp->command_line);
930     }
931 } while (0)
932
933 @d t_close_out do { /* close the terminal */
934   (mp->close_file)(mp->term_out);
935   (mp->close_file)(mp->err_out);
936 } while (0)
937
938 @d t_close_in do { /* close the terminal */
939   (mp->close_file)(mp->term_in);
940 } while (0)
941
942 @<Glob...@>=
943 char *command_line;
944
945 @ @<Option variables@>=
946 char *command_line;
947
948 @ @<Allocate or initialize ...@>=
949 mp->command_line = xstrdup(opt->command_line);
950
951 @ Sometimes it is necessary to synchronize the input/output mixture that
952 happens on the user's terminal, and three system-dependent
953 procedures are used for this
954 purpose. The first of these, |update_terminal|, is called when we want
955 to make sure that everything we have output to the terminal so far has
956 actually left the computer's internal buffers and been sent.
957 The second, |clear_terminal|, is called when we wish to cancel any
958 input that the user may have typed ahead (since we are about to
959 issue an unexpected error message). The third, |wake_up_terminal|,
960 is supposed to revive the terminal if the user has disabled it by
961 some instruction to the operating system.  The following macros show how
962 these operations can be specified in \ph:
963 @^system dependencies@>
964
965 @d update_terminal   (mp->flush_file)(mp->term_out) /* empty the terminal output buffer */
966 @d clear_terminal   do_nothing /* clear the terminal input buffer */
967 @d wake_up_terminal  (mp->flush_file)(mp->term_out) /* cancel the user's cancellation of output */
968
969 @ We need a special routine to read the first line of \MP\ input from
970 the user's terminal. This line is different because it is read before we
971 have opened the transcript file; there is sort of a ``chicken and
972 egg'' problem here. If the user types `\.{input cmr10}' on the first
973 line, or if some macro invoked by that line does such an \.{input},
974 the transcript file will be named `\.{cmr10.log}'; but if no \.{input}
975 commands are performed during the first line of terminal input, the transcript
976 file will acquire its default name `\.{mpout.log}'. (The transcript file
977 will not contain error messages generated by the first line before the
978 first \.{input} command.)
979
980 The first line is even more special if we are lucky enough to have an operating
981 system that treats \MP\ differently from a run-of-the-mill \PASCAL\ object
982 program. It's nice to let the user start running a \MP\ job by typing
983 a command line like `\.{MP cmr10}'; in such a case, \MP\ will operate
984 as if the first line of input were `\.{cmr10}', i.e., the first line will
985 consist of the remainder of the command line, after the part that invoked \MP.
986
987 @ Different systems have different ways to get started. But regardless of
988 what conventions are adopted, the routine that initializes the terminal
989 should satisfy the following specifications:
990
991 \yskip\textindent{1)}It should open file |term_in| for input from the
992   terminal. (The file |term_out| will already be open for output to the
993   terminal.)
994
995 \textindent{2)}If the user has given a command line, this line should be
996   considered the first line of terminal input. Otherwise the
997   user should be prompted with `\.{**}', and the first line of input
998   should be whatever is typed in response.
999
1000 \textindent{3)}The first line of input, which might or might not be a
1001   command line, should appear in locations |first| to |last-1| of the
1002   |buffer| array.
1003
1004 \textindent{4)}The global variable |loc| should be set so that the
1005   character to be read next by \MP\ is in |buffer[loc]|. This
1006   character should not be blank, and we should have |loc<last|.
1007
1008 \yskip\noindent(It may be necessary to prompt the user several times
1009 before a non-blank line comes in. The prompt is `\.{**}' instead of the
1010 later `\.*' because the meaning is slightly different: `\.{input}' need
1011 not be typed immediately after~`\.{**}'.)
1012
1013 @d loc mp->cur_input.loc_field /* location of first unread character in |buffer| */
1014
1015 @ The following program does the required initialization
1016 without retrieving a possible command line.
1017 It should be clear how to modify this routine to deal with command lines,
1018 if the system permits them.
1019 @^system dependencies@>
1020
1021 @c 
1022 boolean mp_init_terminal (MP mp) { /* gets the terminal input started */
1023   t_open_in; 
1024   if (mp->last!=0) {
1025     loc = mp->first = 0;
1026         return true;
1027   }
1028   while (1) { 
1029     wake_up_terminal; do_fprintf(mp->term_out,"**"); update_terminal;
1030 @.**@>
1031     if ( ! mp_input_ln(mp, mp->term_in ) ) { /* this shouldn't happen */
1032       do_fprintf(mp->term_out,"\n! End of file on the terminal... why?");
1033 @.End of file on the terminal@>
1034       return false;
1035     }
1036     loc=mp->first;
1037     while ( (loc<(int)mp->last)&&(mp->buffer[loc]==' ') ) 
1038       incr(loc);
1039     if ( loc<(int)mp->last ) { 
1040       return true; /* return unless the line was all blank */
1041     };
1042     do_fprintf(mp->term_out,"Please type the name of your input file.\n");
1043   }
1044 }
1045
1046 @ @<Declarations@>=
1047 boolean mp_init_terminal (MP mp) ;
1048
1049
1050 @* \[4] String handling.
1051 Symbolic token names and diagnostic messages are variable-length strings
1052 of eight-bit characters. Since \PASCAL\ does not have a well-developed string
1053 mechanism, \MP\ does all of its string processing by homegrown methods.
1054
1055 \MP\ uses strings more extensively than \MF\ does, but the necessary
1056 operations can still be handled with a fairly simple data structure.
1057 The array |str_pool| contains all of the (eight-bit) ASCII codes in all
1058 of the strings, and the array |str_start| contains indices of the starting
1059 points of each string. Strings are referred to by integer numbers, so that
1060 string number |s| comprises the characters |str_pool[j]| for
1061 |str_start[s]<=j<str_start[ss]| where |ss=next_str[s]|.  The string pool
1062 is allocated sequentially and |str_pool[pool_ptr]| is the next unused
1063 location.  The first string number not currently in use is |str_ptr|
1064 and |next_str[str_ptr]| begins a list of free string numbers.  String
1065 pool entries |str_start[str_ptr]| up to |pool_ptr| are reserved for a
1066 string currently being constructed.
1067
1068 String numbers 0 to 255 are reserved for strings that correspond to single
1069 ASCII characters. This is in accordance with the conventions of \.{WEB},
1070 @.WEB@>
1071 which converts single-character strings into the ASCII code number of the
1072 single character involved, while it converts other strings into integers
1073 and builds a string pool file. Thus, when the string constant \.{"."} appears
1074 in the program below, \.{WEB} converts it into the integer 46, which is the
1075 ASCII code for a period, while \.{WEB} will convert a string like \.{"hello"}
1076 into some integer greater than~255. String number 46 will presumably be the
1077 single character `\..'\thinspace; but some ASCII codes have no standard visible
1078 representation, and \MP\ may need to be able to print an arbitrary
1079 ASCII character, so the first 256 strings are used to specify exactly what
1080 should be printed for each of the 256 possibilities.
1081
1082 @<Types...@>=
1083 typedef int pool_pointer; /* for variables that point into |str_pool| */
1084 typedef int str_number; /* for variables that point into |str_start| */
1085
1086 @ @<Glob...@>=
1087 ASCII_code *str_pool; /* the characters */
1088 pool_pointer *str_start; /* the starting pointers */
1089 str_number *next_str; /* for linking strings in order */
1090 pool_pointer pool_ptr; /* first unused position in |str_pool| */
1091 str_number str_ptr; /* number of the current string being created */
1092 pool_pointer init_pool_ptr; /* the starting value of |pool_ptr| */
1093 str_number init_str_use; /* the initial number of strings in use */
1094 pool_pointer max_pool_ptr; /* the maximum so far of |pool_ptr| */
1095 str_number max_str_ptr; /* the maximum so far of |str_ptr| */
1096
1097 @ @<Allocate or initialize ...@>=
1098 mp->str_pool  = xmalloc ((mp->pool_size +1),sizeof(ASCII_code));
1099 mp->str_start = xmalloc ((mp->max_strings+1),sizeof(pool_pointer));
1100 mp->next_str  = xmalloc ((mp->max_strings+1),sizeof(str_number));
1101
1102 @ @<Dealloc variables@>=
1103 xfree(mp->str_pool);
1104 xfree(mp->str_start);
1105 xfree(mp->next_str);
1106
1107 @ Most printing is done from |char *|s, but sometimes not. Here are
1108 functions that convert an internal string into a |char *| for use
1109 by the printing routines, and vice versa.
1110
1111 @d str(A) mp_str(mp,A)
1112 @d rts(A) mp_rts(mp,A)
1113
1114 @<Internal ...@>=
1115 int mp_xstrcmp (const char *a, const char *b);
1116 char * mp_str (MP mp, str_number s);
1117
1118 @ @<Declarations@>=
1119 str_number mp_rts (MP mp, char *s);
1120 str_number mp_make_string (MP mp);
1121
1122 @ The attempt to catch interrupted strings that is in |mp_rts|, is not 
1123 very good: it does not handle nesting over more than one level.
1124
1125 @c 
1126 int mp_xstrcmp (const char *a, const char *b) {
1127         if (a==NULL && b==NULL) 
1128           return 0;
1129     if (a==NULL)
1130       return -1;
1131     if (b==NULL)
1132       return 1;
1133     return strcmp(a,b);
1134 }
1135
1136 @ @c
1137 char * mp_str (MP mp, str_number ss) {
1138   char *s;
1139   int len;
1140   if (ss==mp->str_ptr) {
1141     return NULL;
1142   } else {
1143     len = length(ss);
1144     s = xmalloc(len+1,sizeof(char));
1145     strncpy(s,(char *)(mp->str_pool+(mp->str_start[ss])),len);
1146     s[len] = 0;
1147     return (char *)s;
1148   }
1149 }
1150 str_number mp_rts (MP mp, char *s) {
1151   int r; /* the new string */ 
1152   int old; /* a possible string in progress */
1153   int i=0;
1154   if (strlen(s)==0) {
1155     return 256;
1156   } else if (strlen(s)==1) {
1157     return s[0];
1158   } else {
1159    old=0;
1160    str_room((integer)strlen(s));
1161    if (mp->str_start[mp->str_ptr]<mp->pool_ptr)
1162      old = mp_make_string(mp);
1163    while (*s) {
1164      append_char(*s);
1165      s++;
1166    }
1167    r = mp_make_string(mp);
1168    if (old!=0) {
1169       str_room(length(old));
1170       while (i<length(old)) {
1171         append_char((mp->str_start[old]+i));
1172       } 
1173       mp_flush_string(mp,old);
1174     }
1175     return r;
1176   }
1177 }
1178
1179 @ Except for |strs_used_up|, the following string statistics are only
1180 maintained when code between |stat| $\ldots$ |tats| delimiters is not
1181 commented out:
1182
1183 @<Glob...@>=
1184 integer strs_used_up; /* strings in use or unused but not reclaimed */
1185 integer pool_in_use; /* total number of cells of |str_pool| actually in use */
1186 integer strs_in_use; /* total number of strings actually in use */
1187 integer max_pl_used; /* maximum |pool_in_use| so far */
1188 integer max_strs_used; /* maximum |strs_in_use| so far */
1189
1190 @ Several of the elementary string operations are performed using \.{WEB}
1191 macros instead of \PASCAL\ procedures, because many of the
1192 operations are done quite frequently and we want to avoid the
1193 overhead of procedure calls. For example, here is
1194 a simple macro that computes the length of a string.
1195 @.WEB@>
1196
1197 @d str_stop(A) mp->str_start[mp->next_str[(A)]] /* one cell past the end of string
1198   number \# */
1199 @d length(A) (str_stop((A))-mp->str_start[(A)]) /* the number of characters in string \# */
1200
1201 @ The length of the current string is called |cur_length|.  If we decide that
1202 the current string is not needed, |flush_cur_string| resets |pool_ptr| so that
1203 |cur_length| becomes zero.
1204
1205 @d cur_length   (mp->pool_ptr - mp->str_start[mp->str_ptr])
1206 @d flush_cur_string   mp->pool_ptr=mp->str_start[mp->str_ptr]
1207
1208 @ Strings are created by appending character codes to |str_pool|.
1209 The |append_char| macro, defined here, does not check to see if the
1210 value of |pool_ptr| has gotten too high; this test is supposed to be
1211 made before |append_char| is used.
1212
1213 To test if there is room to append |l| more characters to |str_pool|,
1214 we shall write |str_room(l)|, which tries to make sure there is enough room
1215 by compacting the string pool if necessary.  If this does not work,
1216 |do_compaction| aborts \MP\ and gives an apologetic error message.
1217
1218 @d append_char(A)   /* put |ASCII_code| \# at the end of |str_pool| */
1219 { mp->str_pool[mp->pool_ptr]=(A); incr(mp->pool_ptr);
1220 }
1221 @d str_room(A)   /* make sure that the pool hasn't overflowed */
1222   { if ( mp->pool_ptr+(A) > mp->max_pool_ptr ) {
1223     if ( mp->pool_ptr+(A) > mp->pool_size ) mp_do_compaction(mp, (A));
1224     else mp->max_pool_ptr=mp->pool_ptr+(A); }
1225   }
1226
1227 @ The following routine is similar to |str_room(1)| but it uses the
1228 argument |mp->pool_size| to prevent |do_compaction| from aborting when
1229 string space is exhausted.
1230
1231 @<Declare the procedure called |unit_str_room|@>=
1232 void mp_unit_str_room (MP mp);
1233
1234 @ @c
1235 void mp_unit_str_room (MP mp) { 
1236   if ( mp->pool_ptr>=mp->pool_size ) mp_do_compaction(mp, mp->pool_size);
1237   if ( mp->pool_ptr>=mp->max_pool_ptr ) mp->max_pool_ptr=mp->pool_ptr+1;
1238 }
1239
1240 @ \MP's string expressions are implemented in a brute-force way: Every
1241 new string or substring that is needed is simply copied into the string pool.
1242 Space is eventually reclaimed by a procedure called |do_compaction| with
1243 the aid of a simple system system of reference counts.
1244 @^reference counts@>
1245
1246 The number of references to string number |s| will be |str_ref[s]|. The
1247 special value |str_ref[s]=max_str_ref=127| is used to denote an unknown
1248 positive number of references; such strings will never be recycled. If
1249 a string is ever referred to more than 126 times, simultaneously, we
1250 put it in this category. Hence a single byte suffices to store each |str_ref|.
1251
1252 @d max_str_ref 127 /* ``infinite'' number of references */
1253 @d add_str_ref(A) { if ( mp->str_ref[(A)]<max_str_ref ) incr(mp->str_ref[(A)]);
1254   }
1255
1256 @<Glob...@>=
1257 int *str_ref;
1258
1259 @ @<Allocate or initialize ...@>=
1260 mp->str_ref = xmalloc ((mp->max_strings+1),sizeof(int));
1261
1262 @ @<Dealloc variables@>=
1263 xfree(mp->str_ref);
1264
1265 @ Here's what we do when a string reference disappears:
1266
1267 @d delete_str_ref(A)  { 
1268     if ( mp->str_ref[(A)]<max_str_ref ) {
1269        if ( mp->str_ref[(A)]>1 ) decr(mp->str_ref[(A)]); 
1270        else mp_flush_string(mp, (A));
1271     }
1272   }
1273
1274 @<Declare the procedure called |flush_string|@>=
1275 void mp_flush_string (MP mp,str_number s) ;
1276
1277
1278 @ We can't flush the first set of static strings at all, so there 
1279 is no point in trying
1280
1281 @c
1282 void mp_flush_string (MP mp,str_number s) { 
1283   if (length(s)>1) {
1284     mp->pool_in_use=mp->pool_in_use-length(s);
1285     decr(mp->strs_in_use);
1286     if ( mp->next_str[s]!=mp->str_ptr ) {
1287       mp->str_ref[s]=0;
1288     } else { 
1289       mp->str_ptr=s;
1290       decr(mp->strs_used_up);
1291     }
1292     mp->pool_ptr=mp->str_start[mp->str_ptr];
1293   }
1294 }
1295
1296 @ C literals cannot be simply added, they need to be set so they can't
1297 be flushed.
1298
1299 @d intern(A) mp_intern(mp,(A))
1300
1301 @c
1302 str_number mp_intern (MP mp, char *s) {
1303   str_number r ;
1304   r = rts(s);
1305   mp->str_ref[r] = max_str_ref;
1306   return r;
1307 }
1308
1309 @ @<Declarations@>=
1310 str_number mp_intern (MP mp, char *s);
1311
1312
1313 @ Once a sequence of characters has been appended to |str_pool|, it
1314 officially becomes a string when the function |make_string| is called.
1315 This function returns the identification number of the new string as its
1316 value.
1317
1318 When getting the next unused string number from the linked list, we pretend
1319 that
1320 $$ \hbox{|max_str_ptr+1|, |max_str_ptr+2|, $\ldots$, |mp->max_strings|} $$
1321 are linked sequentially even though the |next_str| entries have not been
1322 initialized yet.  We never allow |str_ptr| to reach |mp->max_strings|;
1323 |do_compaction| is responsible for making sure of this.
1324
1325 @<Declarations@>=
1326 @<Declare the procedure called |do_compaction|@>;
1327 @<Declare the procedure called |unit_str_room|@>;
1328 str_number mp_make_string (MP mp);
1329
1330 @ @c 
1331 str_number mp_make_string (MP mp) { /* current string enters the pool */
1332   str_number s; /* the new string */
1333 RESTART: 
1334   s=mp->str_ptr;
1335   mp->str_ptr=mp->next_str[s];
1336   if ( mp->str_ptr>mp->max_str_ptr ) {
1337     if ( mp->str_ptr==mp->max_strings ) { 
1338       mp->str_ptr=s;
1339       mp_do_compaction(mp, 0);
1340       goto RESTART;
1341     } else {
1342 #ifdef DEBUG 
1343       if ( mp->strs_used_up!=mp->max_str_ptr ) mp_confusion(mp, "s");
1344 @:this can't happen s}{\quad \.s@>
1345 #endif
1346       mp->max_str_ptr=mp->str_ptr;
1347       mp->next_str[mp->str_ptr]=mp->max_str_ptr+1;
1348     }
1349   }
1350   mp->str_ref[s]=1;
1351   mp->str_start[mp->str_ptr]=mp->pool_ptr;
1352   incr(mp->strs_used_up);
1353   incr(mp->strs_in_use);
1354   mp->pool_in_use=mp->pool_in_use+length(s);
1355   if ( mp->pool_in_use>mp->max_pl_used ) 
1356     mp->max_pl_used=mp->pool_in_use;
1357   if ( mp->strs_in_use>mp->max_strs_used ) 
1358     mp->max_strs_used=mp->strs_in_use;
1359   return s;
1360 }
1361
1362 @ The most interesting string operation is string pool compaction.  The idea
1363 is to recover unused space in the |str_pool| array by recopying the strings
1364 to close the gaps created when some strings become unused.  All string
1365 numbers~$k$ where |str_ref[k]=0| are to be linked into the list of free string
1366 numbers after |str_ptr|.  If this fails to free enough pool space we issue an
1367 |overflow| error unless |needed=mp->pool_size|.  Calling |do_compaction|
1368 with |needed=mp->pool_size| supresses all overflow tests.
1369
1370 The compaction process starts with |last_fixed_str| because all lower numbered
1371 strings are permanently allocated with |max_str_ref| in their |str_ref| entries.
1372
1373 @<Glob...@>=
1374 str_number last_fixed_str; /* last permanently allocated string */
1375 str_number fixed_str_use; /* number of permanently allocated strings */
1376
1377 @ @<Declare the procedure called |do_compaction|@>=
1378 void mp_do_compaction (MP mp, pool_pointer needed) ;
1379
1380 @ @c
1381 void mp_do_compaction (MP mp, pool_pointer needed) {
1382   str_number str_use; /* a count of strings in use */
1383   str_number r,s,t; /* strings being manipulated */
1384   pool_pointer p,q; /* destination and source for copying string characters */
1385   @<Advance |last_fixed_str| as far as possible and set |str_use|@>;
1386   r=mp->last_fixed_str;
1387   s=mp->next_str[r];
1388   p=mp->str_start[s];
1389   while ( s!=mp->str_ptr ) { 
1390     while ( mp->str_ref[s]==0 ) {
1391       @<Advance |s| and add the old |s| to the list of free string numbers;
1392         then |break| if |s=str_ptr|@>;
1393     }
1394     r=s; s=mp->next_str[s];
1395     incr(str_use);
1396     @<Move string |r| back so that |str_start[r]=p|; make |p| the location
1397      after the end of the string@>;
1398   }
1399   @<Move the current string back so that it starts at |p|@>;
1400   if ( needed<mp->pool_size ) {
1401     @<Make sure that there is room for another string with |needed| characters@>;
1402   }
1403   @<Account for the compaction and make sure the statistics agree with the
1404      global versions@>;
1405   mp->strs_used_up=str_use;
1406 }
1407
1408 @ @<Advance |last_fixed_str| as far as possible and set |str_use|@>=
1409 t=mp->next_str[mp->last_fixed_str];
1410 while (t!=mp->str_ptr && mp->str_ref[t]==max_str_ref) {
1411   incr(mp->fixed_str_use);
1412   mp->last_fixed_str=t;
1413   t=mp->next_str[t];
1414 }
1415 str_use=mp->fixed_str_use
1416
1417 @ Because of the way |flush_string| has been written, it should never be
1418 necessary to |break| here.  The extra line of code seems worthwhile to
1419 preserve the generality of |do_compaction|.
1420
1421 @<Advance |s| and add the old |s| to the list of free string numbers;...@>=
1422 {
1423 t=s;
1424 s=mp->next_str[s];
1425 mp->next_str[r]=s;
1426 mp->next_str[t]=mp->next_str[mp->str_ptr];
1427 mp->next_str[mp->str_ptr]=t;
1428 if ( s==mp->str_ptr ) break;
1429 }
1430
1431 @ The string currently starts at |str_start[r]| and ends just before
1432 |str_start[s]|.  We don't change |str_start[s]| because it might be needed
1433 to locate the next string.
1434
1435 @<Move string |r| back so that |str_start[r]=p|; make |p| the location...@>=
1436 q=mp->str_start[r];
1437 mp->str_start[r]=p;
1438 while ( q<mp->str_start[s] ) { 
1439   mp->str_pool[p]=mp->str_pool[q];
1440   incr(p); incr(q);
1441 }
1442
1443 @ Pointers |str_start[str_ptr]| and |pool_ptr| have not been updated.  When
1444 we do this, anything between them should be moved.
1445
1446 @ @<Move the current string back so that it starts at |p|@>=
1447 q=mp->str_start[mp->str_ptr];
1448 mp->str_start[mp->str_ptr]=p;
1449 while ( q<mp->pool_ptr ) { 
1450   mp->str_pool[p]=mp->str_pool[q];
1451   incr(p); incr(q);
1452 }
1453 mp->pool_ptr=p
1454
1455 @ We must remember that |str_ptr| is not allowed to reach |mp->max_strings|.
1456
1457 @<Make sure that there is room for another string with |needed| char...@>=
1458 if ( str_use>=mp->max_strings-1 )
1459   mp_reallocate_strings (mp,str_use);
1460 if ( mp->pool_ptr+needed>mp->max_pool_ptr ) {
1461   mp_reallocate_pool(mp, mp->pool_ptr+needed);
1462   mp->max_pool_ptr=mp->pool_ptr+needed;
1463 }
1464
1465 @ @<Declarations@>=
1466 void mp_reallocate_strings (MP mp, str_number str_use) ;
1467 void mp_reallocate_pool(MP mp, pool_pointer needed) ;
1468
1469 @ @c 
1470 void mp_reallocate_strings (MP mp, str_number str_use) { 
1471   while ( str_use>=mp->max_strings-1 ) {
1472     int l = mp->max_strings + (mp->max_strings>>2);
1473     XREALLOC (mp->str_ref,   l, int);
1474     XREALLOC (mp->str_start, l, pool_pointer);
1475     XREALLOC (mp->next_str,  l, str_number);
1476     mp->max_strings = l;
1477   }
1478 }
1479 void mp_reallocate_pool(MP mp, pool_pointer needed) {
1480   while ( needed>mp->pool_size ) {
1481     int l = mp->pool_size + (mp->pool_size>>2);
1482         XREALLOC (mp->str_pool, l, ASCII_code);
1483     mp->pool_size = l;
1484   }
1485 }
1486
1487 @ @<Account for the compaction and make sure the statistics agree with...@>=
1488 if ( (mp->str_start[mp->str_ptr]!=mp->pool_in_use)||(str_use!=mp->strs_in_use) )
1489   mp_confusion(mp, "string");
1490 @:this can't happen string}{\quad string@>
1491 incr(mp->pact_count);
1492 mp->pact_chars=mp->pact_chars+mp->pool_ptr-str_stop(mp->last_fixed_str);
1493 mp->pact_strs=mp->pact_strs+str_use-mp->fixed_str_use;
1494 #ifdef DEBUG
1495 s=mp->str_ptr; t=str_use;
1496 while ( s<=mp->max_str_ptr ){
1497   if ( t>mp->max_str_ptr ) mp_confusion(mp, "\"");
1498   incr(t); s=mp->next_str[s];
1499 };
1500 if ( t<=mp->max_str_ptr ) mp_confusion(mp, "\"");
1501 #endif
1502
1503 @ A few more global variables are needed to keep track of statistics when
1504 |stat| $\ldots$ |tats| blocks are not commented out.
1505
1506 @<Glob...@>=
1507 integer pact_count; /* number of string pool compactions so far */
1508 integer pact_chars; /* total number of characters moved during compactions */
1509 integer pact_strs; /* total number of strings moved during compactions */
1510
1511 @ @<Initialize compaction statistics@>=
1512 mp->pact_count=0;
1513 mp->pact_chars=0;
1514 mp->pact_strs=0;
1515
1516 @ The following subroutine compares string |s| with another string of the
1517 same length that appears in |buffer| starting at position |k|;
1518 the result is |true| if and only if the strings are equal.
1519
1520 @c 
1521 boolean mp_str_eq_buf (MP mp,str_number s, integer k) {
1522   /* test equality of strings */
1523   pool_pointer j; /* running index */
1524   j=mp->str_start[s];
1525   while ( j<str_stop(s) ) { 
1526     if ( mp->str_pool[j++]!=mp->buffer[k++] ) 
1527       return false;
1528   }
1529   return true;
1530 }
1531
1532 @ Here is a similar routine, but it compares two strings in the string pool,
1533 and it does not assume that they have the same length. If the first string
1534 is lexicographically greater than, less than, or equal to the second,
1535 the result is respectively positive, negative, or zero.
1536
1537 @c 
1538 integer mp_str_vs_str (MP mp, str_number s, str_number t) {
1539   /* test equality of strings */
1540   pool_pointer j,k; /* running indices */
1541   integer ls,lt; /* lengths */
1542   integer l; /* length remaining to test */
1543   ls=length(s); lt=length(t);
1544   if ( ls<=lt ) l=ls; else l=lt;
1545   j=mp->str_start[s]; k=mp->str_start[t];
1546   while ( l-->0 ) { 
1547     if ( mp->str_pool[j]!=mp->str_pool[k] ) {
1548        return (mp->str_pool[j]-mp->str_pool[k]); 
1549     }
1550     incr(j); incr(k);
1551   }
1552   return (ls-lt);
1553 }
1554
1555 @ The initial values of |str_pool|, |str_start|, |pool_ptr|,
1556 and |str_ptr| are computed by the \.{INIMP} program, based in part
1557 on the information that \.{WEB} has output while processing \MP.
1558 @.INIMP@>
1559 @^string pool@>
1560
1561 @c 
1562 void mp_get_strings_started (MP mp) { 
1563   /* initializes the string pool,
1564     but returns |false| if something goes wrong */
1565   int k; /* small indices or counters */
1566   str_number g; /* a new string */
1567   mp->pool_ptr=0; mp->str_ptr=0; mp->max_pool_ptr=0; mp->max_str_ptr=0;
1568   mp->str_start[0]=0;
1569   mp->next_str[0]=1;
1570   mp->pool_in_use=0; mp->strs_in_use=0;
1571   mp->max_pl_used=0; mp->max_strs_used=0;
1572   @<Initialize compaction statistics@>;
1573   mp->strs_used_up=0;
1574   @<Make the first 256 strings@>;
1575   g=mp_make_string(mp); /* string 256 == "" */
1576   mp->str_ref[g]=max_str_ref;
1577   mp->last_fixed_str=mp->str_ptr-1;
1578   mp->fixed_str_use=mp->str_ptr;
1579   return;
1580 }
1581
1582 @ @<Declarations@>=
1583 void mp_get_strings_started (MP mp);
1584
1585 @ The first 256 strings will consist of a single character only.
1586
1587 @<Make the first 256...@>=
1588 for (k=0;k<=255;k++) { 
1589   append_char(k);
1590   g=mp_make_string(mp); 
1591   mp->str_ref[g]=max_str_ref;
1592 }
1593
1594 @ The first 128 strings will contain 95 standard ASCII characters, and the
1595 other 33 characters will be printed in three-symbol form like `\.{\^\^A}'
1596 unless a system-dependent change is made here. Installations that have
1597 an extended character set, where for example |xchr[032]=@t\.{'^^Z'}@>|,
1598 would like string 032 to be printed as the single character 032 instead
1599 of the three characters 0136, 0136, 0132 (\.{\^\^Z}). On the other hand,
1600 even people with an extended character set will want to represent string
1601 015 by \.{\^\^M}, since 015 is ASCII's ``carriage return'' code; the idea is
1602 to produce visible strings instead of tabs or line-feeds or carriage-returns
1603 or bell-rings or characters that are treated anomalously in text files.
1604
1605 Unprintable characters of codes 128--255 are, similarly, rendered
1606 \.{\^\^80}--\.{\^\^ff}.
1607
1608 The boolean expression defined here should be |true| unless \MP\ internal
1609 code number~|k| corresponds to a non-troublesome visible symbol in the
1610 local character set.
1611 If character |k| cannot be printed, and |k<0200|, then character |k+0100| or
1612 |k-0100| must be printable; moreover, ASCII codes |[060..071, 0141..0146]|
1613 must be printable.
1614 @^character set dependencies@>
1615 @^system dependencies@>
1616
1617 @<Character |k| cannot be printed@>=
1618   (k<' ')||(k>'~')
1619
1620 @* \[5] On-line and off-line printing.
1621 Messages that are sent to a user's terminal and to the transcript-log file
1622 are produced by several `|print|' procedures. These procedures will
1623 direct their output to a variety of places, based on the setting of
1624 the global variable |selector|, which has the following possible
1625 values:
1626
1627 \yskip
1628 \hang |term_and_log|, the normal setting, prints on the terminal and on the
1629   transcript file.
1630
1631 \hang |log_only|, prints only on the transcript file.
1632
1633 \hang |term_only|, prints only on the terminal.
1634
1635 \hang |no_print|, doesn't print at all. This is used only in rare cases
1636   before the transcript file is open.
1637
1638 \hang |pseudo|, puts output into a cyclic buffer that is used
1639   by the |show_context| routine; when we get to that routine we shall discuss
1640   the reasoning behind this curious mode.
1641
1642 \hang |new_string|, appends the output to the current string in the
1643   string pool.
1644
1645 \hang |>=write_file| prints on one of the files used for the \&{write}
1646 @:write_}{\&{write} primitive@>
1647   command.
1648
1649 \yskip
1650 \noindent The symbolic names `|term_and_log|', etc., have been assigned
1651 numeric codes that satisfy the convenient relations |no_print+1=term_only|,
1652 |no_print+2=log_only|, |term_only+2=log_only+1=term_and_log|.  These
1653 relations are not used when |selector| could be |pseudo|, or |new_string|.
1654 We need not check for unprintable characters when |selector<pseudo|.
1655
1656 Three additional global variables, |tally|, |term_offset| and |file_offset|
1657 record the number of characters that have been printed
1658 since they were most recently cleared to zero. We use |tally| to record
1659 the length of (possibly very long) stretches of printing; |term_offset|,
1660 and |file_offset|, on the other hand, keep track of how many
1661 characters have appeared so far on the current line that has been output
1662 to the terminal, the transcript file, or the \ps\ output file, respectively.
1663
1664 @d new_string 0 /* printing is deflected to the string pool */
1665 @d pseudo 2 /* special |selector| setting for |show_context| */
1666 @d no_print 3 /* |selector| setting that makes data disappear */
1667 @d term_only 4 /* printing is destined for the terminal only */
1668 @d log_only 5 /* printing is destined for the transcript file only */
1669 @d term_and_log 6 /* normal |selector| setting */
1670 @d write_file 7 /* first write file selector */
1671
1672 @<Glob...@>=
1673 void * log_file; /* transcript of \MP\ session */
1674 void * ps_file; /* the generic font output goes here */
1675 unsigned int selector; /* where to print a message */
1676 unsigned char dig[23]; /* digits in a number being output */
1677 integer tally; /* the number of characters recently printed */
1678 unsigned int term_offset;
1679   /* the number of characters on the current terminal line */
1680 unsigned int file_offset;
1681   /* the number of characters on the current file line */
1682 ASCII_code *trick_buf; /* circular buffer for pseudoprinting */
1683 integer trick_count; /* threshold for pseudoprinting, explained later */
1684 integer first_count; /* another variable for pseudoprinting */
1685
1686 @ @<Allocate or initialize ...@>=
1687 memset(mp->dig,0,23);
1688 mp->trick_buf = xmalloc((mp->error_line+1),sizeof(ASCII_code));
1689
1690 @ @<Dealloc variables@>=
1691 xfree(mp->trick_buf);
1692
1693 @ @<Initialize the output routines@>=
1694 mp->selector=term_only; mp->tally=0; mp->term_offset=0; mp->file_offset=0; 
1695
1696 @ Macro abbreviations for output to the terminal and to the log file are
1697 defined here for convenience. Some systems need special conventions
1698 for terminal output, and it is possible to adhere to those conventions
1699 by changing |wterm|, |wterm_ln|, and |wterm_cr| here.
1700 @^system dependencies@>
1701
1702 @d do_fprintf(f,b) (mp->write_ascii_file)(f,b)
1703 @d wterm(A)     do_fprintf(mp->term_out,(A))
1704 @d wterm_chr(A) { unsigned char ss[2]; ss[0]=(A); ss[1]=0; do_fprintf(mp->term_out,(char *)ss); }
1705 @d wterm_cr     do_fprintf(mp->term_out,"\n")
1706 @d wterm_ln(A)  { wterm_cr; do_fprintf(mp->term_out,(A)); }
1707 @d wlog(A)      do_fprintf(mp->log_file,(A))
1708 @d wlog_chr(A)  { unsigned char ss[2]; ss[0]=(A); ss[1]=0; do_fprintf(mp->log_file,(char *)ss); }
1709 @d wlog_cr      do_fprintf(mp->log_file, "\n")
1710 @d wlog_ln(A)   {wlog_cr; do_fprintf(mp->log_file,(A)); }
1711
1712
1713 @ To end a line of text output, we call |print_ln|.  Cases |0..max_write_files|
1714 use an array |wr_file| that will be declared later.
1715
1716 @d mp_print_text(A) mp_print_str(mp,text((A)))
1717
1718 @<Internal ...@>=
1719 void mp_print_ln (MP mp);
1720 void mp_print_visible_char (MP mp, ASCII_code s); 
1721 void mp_print_char (MP mp, ASCII_code k);
1722 void mp_print (MP mp, char *s);
1723 void mp_print_str (MP mp, str_number s);
1724 void mp_print_nl (MP mp, char *s);
1725 void mp_print_two (MP mp,scaled x, scaled y) ;
1726 void mp_print_scaled (MP mp,scaled s);
1727
1728 @ @<Basic print...@>=
1729 void mp_print_ln (MP mp) { /* prints an end-of-line */
1730  switch (mp->selector) {
1731   case term_and_log: 
1732     wterm_cr; wlog_cr;
1733     mp->term_offset=0;  mp->file_offset=0;
1734     break;
1735   case log_only: 
1736     wlog_cr; mp->file_offset=0;
1737     break;
1738   case term_only: 
1739     wterm_cr; mp->term_offset=0;
1740     break;
1741   case no_print:
1742   case pseudo: 
1743   case new_string: 
1744     break;
1745   default: 
1746     do_fprintf(mp->wr_file[(mp->selector-write_file)],"\n");
1747   }
1748 } /* note that |tally| is not affected */
1749
1750 @ The |print_visible_char| procedure sends one character to the desired
1751 destination, using the |xchr| array to map it into an external character
1752 compatible with |input_ln|.  (It assumes that it is always called with
1753 a visible ASCII character.)  All printing comes through |print_ln| or
1754 |print_char|, which ultimately calls |print_visible_char|, hence these
1755 routines are the ones that limit lines to at most |max_print_line| characters.
1756 But we must make an exception for the \ps\ output file since it is not safe
1757 to cut up lines arbitrarily in \ps.
1758
1759 Procedure |unit_str_room| needs to be declared |forward| here because it calls
1760 |do_compaction| and |do_compaction| can call the error routines.  Actually,
1761 |unit_str_room| avoids |overflow| errors but it can call |confusion|.
1762
1763 @<Basic printing...@>=
1764 void mp_print_visible_char (MP mp, ASCII_code s) { /* prints a single character */
1765   switch (mp->selector) {
1766   case term_and_log: 
1767     wterm_chr(xchr(s)); wlog_chr(xchr(s));
1768     incr(mp->term_offset); incr(mp->file_offset);
1769     if ( mp->term_offset==(unsigned)mp->max_print_line ) { 
1770        wterm_cr; mp->term_offset=0;
1771     };
1772     if ( mp->file_offset==(unsigned)mp->max_print_line ) { 
1773        wlog_cr; mp->file_offset=0;
1774     };
1775     break;
1776   case log_only: 
1777     wlog_chr(xchr(s)); incr(mp->file_offset);
1778     if ( mp->file_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1779     break;
1780   case term_only: 
1781     wterm_chr(xchr(s)); incr(mp->term_offset);
1782     if ( mp->term_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1783     break;
1784   case no_print: 
1785     break;
1786   case pseudo: 
1787     if ( mp->tally<mp->trick_count ) 
1788       mp->trick_buf[mp->tally % mp->error_line]=s;
1789     break;
1790   case new_string: 
1791     if ( mp->pool_ptr>=mp->max_pool_ptr ) { 
1792       mp_unit_str_room(mp);
1793       if ( mp->pool_ptr>=mp->pool_size ) 
1794         goto DONE; /* drop characters if string space is full */
1795     };
1796     append_char(s);
1797     break;
1798   default:
1799     { char ss[2]; ss[0] = xchr(s); ss[1]=0;
1800       do_fprintf(mp->wr_file[(mp->selector-write_file)],(char *)ss);
1801     }
1802   }
1803 DONE:
1804   incr(mp->tally);
1805 }
1806
1807 @ The |print_char| procedure sends one character to the desired destination.
1808 File names and string expressions might contain |ASCII_code| values that
1809 can't be printed using |print_visible_char|.  These characters will be
1810 printed in three- or four-symbol form like `\.{\^\^A}' or `\.{\^\^e4}'.
1811 (This procedure assumes that it is safe to bypass all checks for unprintable
1812 characters when |selector| is in the range |0..max_write_files-1|.
1813 The user might want to write unprintable characters.
1814
1815 @d print_lc_hex(A) do { l=(A);
1816     mp_print_visible_char(mp, (l<10 ? l+'0' : l-10+'a'));
1817   } while (0)
1818
1819 @<Basic printing...@>=
1820 void mp_print_char (MP mp, ASCII_code k) { /* prints a single character */
1821   int l; /* small index or counter */
1822   if ( mp->selector<pseudo || mp->selector>=write_file) {
1823     mp_print_visible_char(mp, k);
1824   } else if ( @<Character |k| cannot be printed@> ) { 
1825     mp_print(mp, "^^"); 
1826     if ( k<0100 ) { 
1827       mp_print_visible_char(mp, k+0100); 
1828     } else if ( k<0200 ) { 
1829       mp_print_visible_char(mp, k-0100); 
1830     } else { 
1831       print_lc_hex(k / 16);  
1832       print_lc_hex(k % 16); 
1833     }
1834   } else {
1835     mp_print_visible_char(mp, k);
1836   }
1837 };
1838
1839 @ An entire string is output by calling |print|. Note that if we are outputting
1840 the single standard ASCII character \.c, we could call |print("c")|, since
1841 |"c"=99| is the number of a single-character string, as explained above. But
1842 |print_char("c")| is quicker, so \MP\ goes directly to the |print_char|
1843 routine when it knows that this is safe. (The present implementation
1844 assumes that it is always safe to print a visible ASCII character.)
1845 @^system dependencies@>
1846
1847 @<Basic print...@>=
1848 void mp_do_print (MP mp, char *ss, unsigned int len) { /* prints string |s| */
1849   unsigned int j = 0;
1850   while ( j<len ){ 
1851     mp_print_char(mp, ss[j]); incr(j);
1852   }
1853 }
1854
1855
1856 @<Basic print...@>=
1857 void mp_print (MP mp, char *ss) {
1858   mp_do_print(mp, ss, strlen(ss));
1859 }
1860 void mp_print_str (MP mp, str_number s) {
1861   pool_pointer j; /* current character code position */
1862   if ( (s<0)||(s>mp->max_str_ptr) ) {
1863      mp_do_print(mp,"???",3); /* this can't happen */
1864 @.???@>
1865   }
1866   j=mp->str_start[s];
1867   mp_do_print(mp, (char *)(mp->str_pool+j), (str_stop(s)-j));
1868 }
1869
1870
1871 @ Here is the very first thing that \MP\ prints: a headline that identifies
1872 the version number and base name. The |term_offset| variable is temporarily
1873 incorrect, but the discrepancy is not serious since we assume that the banner
1874 and mem identifier together will occupy at most |max_print_line|
1875 character positions.
1876
1877 @<Initialize the output...@>=
1878 wterm (banner);
1879 wterm (version_string);
1880 if (mp->mem_ident!=NULL) 
1881   mp_print(mp,mp->mem_ident); 
1882 mp_print_ln(mp);
1883 update_terminal;
1884
1885 @ The procedure |print_nl| is like |print|, but it makes sure that the
1886 string appears at the beginning of a new line.
1887
1888 @<Basic print...@>=
1889 void mp_print_nl (MP mp, char *s) { /* prints string |s| at beginning of line */
1890   switch(mp->selector) {
1891   case term_and_log: 
1892     if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_ln(mp);
1893     break;
1894   case log_only: 
1895     if ( mp->file_offset>0 ) mp_print_ln(mp);
1896     break;
1897   case term_only: 
1898     if ( mp->term_offset>0 ) mp_print_ln(mp);
1899     break;
1900   case no_print:
1901   case pseudo:
1902   case new_string: 
1903         break;
1904   } /* there are no other cases */
1905   mp_print(mp, s);
1906 }
1907
1908 @ An array of digits in the range |0..9| is printed by |print_the_digs|.
1909
1910 @<Basic print...@>=
1911 void mp_print_the_digs (MP mp, eight_bits k) {
1912   /* prints |dig[k-1]|$\,\ldots\,$|dig[0]| */
1913   while ( k>0 ){ 
1914     decr(k); mp_print_char(mp, '0'+mp->dig[k]);
1915   }
1916 };
1917
1918 @ The following procedure, which prints out the decimal representation of a
1919 given integer |n|, has been written carefully so that it works properly
1920 if |n=0| or if |(-n)| would cause overflow. It does not apply |mod| or |div|
1921 to negative arguments, since such operations are not implemented consistently
1922 by all \PASCAL\ compilers.
1923
1924 @<Basic print...@>=
1925 void mp_print_int (MP mp,integer n) { /* prints an integer in decimal form */
1926   integer m; /* used to negate |n| in possibly dangerous cases */
1927   int k = 0; /* index to current digit; we assume that $|n|<10^{23}$ */
1928   if ( n<0 ) { 
1929     mp_print_char(mp, '-');
1930     if ( n>-100000000 ) {
1931           negate(n);
1932     } else  { 
1933           m=-1-n; n=m / 10; m=(m % 10)+1; k=1;
1934       if ( m<10 ) {
1935         mp->dig[0]=m;
1936       } else { 
1937         mp->dig[0]=0; incr(n);
1938       }
1939     }
1940   }
1941   do {  
1942     mp->dig[k]=n % 10; n=n / 10; incr(k);
1943   } while (n!=0);
1944   mp_print_the_digs(mp, k);
1945 };
1946
1947 @ @<Internal ...@>=
1948 void mp_print_int (MP mp,integer n);
1949
1950 @ \MP\ also makes use of a trivial procedure to print two digits. The
1951 following subroutine is usually called with a parameter in the range |0<=n<=99|.
1952
1953 @c 
1954 void mp_print_dd (MP mp,integer n) { /* prints two least significant digits */
1955   n=abs(n) % 100; 
1956   mp_print_char(mp, '0'+(n / 10));
1957   mp_print_char(mp, '0'+(n % 10));
1958 }
1959
1960
1961 @ @<Internal ...@>=
1962 void mp_print_dd (MP mp,integer n);
1963
1964 @ Here is a procedure that asks the user to type a line of input,
1965 assuming that the |selector| setting is either |term_only| or |term_and_log|.
1966 The input is placed into locations |first| through |last-1| of the
1967 |buffer| array, and echoed on the transcript file if appropriate.
1968
1969 This procedure is never called when |interaction<mp_scroll_mode|.
1970
1971 @d prompt_input(A) do { 
1972     wake_up_terminal; mp_print(mp, (A)); mp_term_input(mp);
1973   } while (0) /* prints a string and gets a line of input */
1974
1975 @c 
1976 void mp_term_input (MP mp) { /* gets a line from the terminal */
1977   size_t k; /* index into |buffer| */
1978   update_terminal; /* Now the user sees the prompt for sure */
1979   if (!mp_input_ln(mp, mp->term_in )) 
1980     mp_fatal_error(mp, "End of file on the terminal!");
1981 @.End of file on the terminal@>
1982   mp->term_offset=0; /* the user's line ended with \<\rm return> */
1983   decr(mp->selector); /* prepare to echo the input */
1984   if ( mp->last!=mp->first ) {
1985     for (k=mp->first;k<=mp->last-1;k++) {
1986       mp_print_char(mp, mp->buffer[k]);
1987     }
1988   }
1989   mp_print_ln(mp); 
1990   mp->buffer[mp->last]='%'; 
1991   incr(mp->selector); /* restore previous status */
1992 };
1993
1994 @* \[6] Reporting errors.
1995 When something anomalous is detected, \MP\ typically does something like this:
1996 $$\vbox{\halign{#\hfil\cr
1997 |print_err("Something anomalous has been detected");|\cr
1998 |help3("This is the first line of my offer to help.")|\cr
1999 |("This is the second line. I'm trying to")|\cr
2000 |("explain the best way for you to proceed.");|\cr
2001 |error;|\cr}}$$
2002 A two-line help message would be given using |help2|, etc.; these informal
2003 helps should use simple vocabulary that complements the words used in the
2004 official error message that was printed. (Outside the U.S.A., the help
2005 messages should preferably be translated into the local vernacular. Each
2006 line of help is at most 60 characters long, in the present implementation,
2007 so that |max_print_line| will not be exceeded.)
2008
2009 The |print_err| procedure supplies a `\.!' before the official message,
2010 and makes sure that the terminal is awake if a stop is going to occur.
2011 The |error| procedure supplies a `\..' after the official message, then it
2012 shows the location of the error; and if |interaction=error_stop_mode|,
2013 it also enters into a dialog with the user, during which time the help
2014 message may be printed.
2015 @^system dependencies@>
2016
2017 @ The global variable |interaction| has four settings, representing increasing
2018 amounts of user interaction:
2019
2020 @<Exported types@>=
2021 enum mp_interaction_mode { 
2022  mp_unspecified_mode=0, /* extra value for command-line switch */
2023  mp_batch_mode, /* omits all stops and omits terminal output */
2024  mp_nonstop_mode, /* omits all stops */
2025  mp_scroll_mode, /* omits error stops */
2026  mp_error_stop_mode, /* stops at every opportunity to interact */
2027 };
2028
2029 @ @<Glob...@>=
2030 int interaction; /* current level of interaction */
2031
2032 @ @<Option variables@>=
2033 int interaction; /* current level of interaction */
2034
2035 @ Set it here so it can be overwritten by the commandline
2036
2037 @<Allocate or initialize ...@>=
2038 mp->interaction=opt->interaction;
2039 if (mp->interaction==mp_unspecified_mode || mp->interaction>mp_error_stop_mode) 
2040   mp->interaction=mp_error_stop_mode;
2041 if (mp->interaction<mp_unspecified_mode) 
2042   mp->interaction=mp_batch_mode;
2043
2044
2045
2046 @d print_err(A) mp_print_err(mp,(A))
2047
2048 @<Internal ...@>=
2049 void mp_print_err(MP mp, char * A);
2050
2051 @ @c
2052 void mp_print_err(MP mp, char * A) { 
2053   if ( mp->interaction==mp_error_stop_mode ) 
2054     wake_up_terminal;
2055   mp_print_nl(mp, "! "); 
2056   mp_print(mp, A);
2057 @.!\relax@>
2058 }
2059
2060
2061 @ \MP\ is careful not to call |error| when the print |selector| setting
2062 might be unusual. The only possible values of |selector| at the time of
2063 error messages are
2064
2065 \yskip\hang|no_print| (when |interaction=mp_batch_mode|
2066   and |log_file| not yet open);
2067
2068 \hang|term_only| (when |interaction>mp_batch_mode| and |log_file| not yet open);
2069
2070 \hang|log_only| (when |interaction=mp_batch_mode| and |log_file| is open);
2071
2072 \hang|term_and_log| (when |interaction>mp_batch_mode| and |log_file| is open).
2073
2074 @<Initialize the print |selector| based on |interaction|@>=
2075 if ( mp->interaction==mp_batch_mode ) mp->selector=no_print; else mp->selector=term_only
2076
2077 @ A global variable |deletions_allowed| is set |false| if the |get_next|
2078 routine is active when |error| is called; this ensures that |get_next|
2079 will never be called recursively.
2080 @^recursion@>
2081
2082 The global variable |history| records the worst level of error that
2083 has been detected. It has four possible values: |spotless|, |warning_issued|,
2084 |error_message_issued|, and |fatal_error_stop|.
2085
2086 Another global variable, |error_count|, is increased by one when an
2087 |error| occurs without an interactive dialog, and it is reset to zero at
2088 the end of every statement.  If |error_count| reaches 100, \MP\ decides
2089 that there is no point in continuing further.
2090
2091 @<Types...@>=
2092 enum mp_history_states {
2093   mp_spotless=0, /* |history| value when nothing has been amiss yet */
2094   mp_warning_issued, /* |history| value when |begin_diagnostic| has been called */
2095   mp_error_message_issued, /* |history| value when |error| has been called */
2096   mp_fatal_error_stop, /* |history| value when termination was premature */
2097 };
2098
2099 @ @<Glob...@>=
2100 boolean deletions_allowed; /* is it safe for |error| to call |get_next|? */
2101 int history; /* has the source input been clean so far? */
2102 int error_count; /* the number of scrolled errors since the last statement ended */
2103
2104 @ The value of |history| is initially |fatal_error_stop|, but it will
2105 be changed to |spotless| if \MP\ survives the initialization process.
2106
2107 @<Allocate or ...@>=
2108 mp->deletions_allowed=true; mp->error_count=0; /* |history| is initialized elsewhere */
2109
2110 @ Since errors can be detected almost anywhere in \MP, we want to declare the
2111 error procedures near the beginning of the program. But the error procedures
2112 in turn use some other procedures, which need to be declared |forward|
2113 before we get to |error| itself.
2114
2115 It is possible for |error| to be called recursively if some error arises
2116 when |get_next| is being used to delete a token, and/or if some fatal error
2117 occurs while \MP\ is trying to fix a non-fatal one. But such recursion
2118 @^recursion@>
2119 is never more than two levels deep.
2120
2121 @<Declarations@>=
2122 void mp_get_next (MP mp);
2123 void mp_term_input (MP mp);
2124 void mp_show_context (MP mp);
2125 void mp_begin_file_reading (MP mp);
2126 void mp_open_log_file (MP mp);
2127 void mp_clear_for_error_prompt (MP mp);
2128 void mp_debug_help (MP mp);
2129 @<Declare the procedure called |flush_string|@>
2130
2131 @ @<Internal ...@>=
2132 void mp_normalize_selector (MP mp);
2133
2134 @ Individual lines of help are recorded in the array |help_line|, which
2135 contains entries in positions |0..(help_ptr-1)|. They should be printed
2136 in reverse order, i.e., with |help_line[0]| appearing last.
2137
2138 @d hlp1(A) mp->help_line[0]=(A); }
2139 @d hlp2(A) mp->help_line[1]=(A); hlp1
2140 @d hlp3(A) mp->help_line[2]=(A); hlp2
2141 @d hlp4(A) mp->help_line[3]=(A); hlp3
2142 @d hlp5(A) mp->help_line[4]=(A); hlp4
2143 @d hlp6(A) mp->help_line[5]=(A); hlp5
2144 @d help0 mp->help_ptr=0 /* sometimes there might be no help */
2145 @d help1  { mp->help_ptr=1; hlp1 /* use this with one help line */
2146 @d help2  { mp->help_ptr=2; hlp2 /* use this with two help lines */
2147 @d help3  { mp->help_ptr=3; hlp3 /* use this with three help lines */
2148 @d help4  { mp->help_ptr=4; hlp4 /* use this with four help lines */
2149 @d help5  { mp->help_ptr=5; hlp5 /* use this with five help lines */
2150 @d help6  { mp->help_ptr=6; hlp6 /* use this with six help lines */
2151
2152 @<Glob...@>=
2153 char * help_line[6]; /* helps for the next |error| */
2154 unsigned int help_ptr; /* the number of help lines present */
2155 boolean use_err_help; /* should the |err_help| string be shown? */
2156 str_number err_help; /* a string set up by \&{errhelp} */
2157 str_number filename_template; /* a string set up by \&{filenametemplate} */
2158
2159 @ @<Allocate or ...@>=
2160 mp->help_ptr=0; mp->use_err_help=false; mp->err_help=0; mp->filename_template=0;
2161
2162 @ The |jump_out| procedure just cuts across all active procedure levels and
2163 goes to |end_of_MP|. This is the only nonlocal |goto| statement in the
2164 whole program. It is used when there is no recovery from a particular error.
2165
2166 The program uses a |jump_buf| to handle this, this is initialized at three
2167 spots: the start of |mp_new|, the start of |mp_initialize|, and the start 
2168 of |mp_run|. Those are the only library enty points.
2169
2170 @^system dependencies@>
2171
2172 @<Glob...@>=
2173 jmp_buf jump_buf;
2174
2175 @ @<Install and test the non-local jump buffer@>=
2176 if (setjmp(mp->jump_buf) != 0) return mp->history;
2177
2178 @ @<Setup the non-local jump buffer in |mp_new|@>=
2179 if (setjmp(mp->jump_buf) != 0) return NULL;
2180
2181 @ If |mp->internal| is zero, then a crash occured during initialization,
2182 and it is not safe to run |mp_close_files_and_terminate|.
2183
2184 @<Error hand...@>=
2185 void mp_jump_out (MP mp) { 
2186   if(mp->internal!=NULL)
2187     mp_close_files_and_terminate(mp);
2188   longjmp(mp->jump_buf,1);
2189 }
2190
2191 @ Here now is the general |error| routine.
2192
2193 @<Error hand...@>=
2194 void mp_error (MP mp) { /* completes the job of error reporting */
2195   ASCII_code c; /* what the user types */
2196   integer s1,s2,s3; /* used to save global variables when deleting tokens */
2197   pool_pointer j; /* character position being printed */
2198   if ( mp->history<mp_error_message_issued ) mp->history=mp_error_message_issued;
2199   mp_print_char(mp, '.'); mp_show_context(mp);
2200   if ( mp->interaction==mp_error_stop_mode ) {
2201     @<Get user's advice and |return|@>;
2202   }
2203   incr(mp->error_count);
2204   if ( mp->error_count==100 ) { 
2205     mp_print_nl(mp,"(That makes 100 errors; please try again.)");
2206 @.That makes 100 errors...@>
2207     mp->history=mp_fatal_error_stop; mp_jump_out(mp);
2208   }
2209   @<Put help message on the transcript file@>;
2210 }
2211 void mp_warn (MP mp, char *msg) {
2212   int saved_selector = mp->selector;
2213   mp_normalize_selector(mp);
2214   mp_print_nl(mp,"Warning: ");
2215   mp_print(mp,msg);
2216   mp->selector = saved_selector;
2217 }
2218
2219 @ @<Exported function ...@>=
2220 void mp_error (MP mp);
2221 void mp_warn (MP mp, char *msg);
2222
2223
2224 @ @<Get user's advice...@>=
2225 while (1) { 
2226 CONTINUE:
2227   mp_clear_for_error_prompt(mp); prompt_input("? ");
2228 @.?\relax@>
2229   if ( mp->last==mp->first ) return;
2230   c=mp->buffer[mp->first];
2231   if ( c>='a' ) c=c+'A'-'a'; /* convert to uppercase */
2232   @<Interpret code |c| and |return| if done@>;
2233 }
2234
2235 @ It is desirable to provide an `\.E' option here that gives the user
2236 an easy way to return from \MP\ to the system editor, with the offending
2237 line ready to be edited. But such an extension requires some system
2238 wizardry, so the present implementation simply types out the name of the
2239 file that should be
2240 edited and the relevant line number.
2241 @^system dependencies@>
2242
2243 @<Exported types@>=
2244 typedef void (*mp_run_editor_command)(MP, char *, int);
2245
2246 @ @<Glob...@>=
2247 mp_run_editor_command run_editor;
2248
2249 @ @<Option variables@>=
2250 mp_run_editor_command run_editor;
2251
2252 @ @<Allocate or initialize ...@>=
2253 set_callback_option(run_editor);
2254
2255 @ @<Declarations@>=
2256 void mp_run_editor (MP mp, char *fname, int fline);
2257
2258 @ @c void mp_run_editor (MP mp, char *fname, int fline) {
2259     mp_print_nl(mp, "You want to edit file ");
2260 @.You want to edit file x@>
2261     mp_print(mp, fname);
2262     mp_print(mp, " at line "); 
2263     mp_print_int(mp, fline);
2264     mp->interaction=mp_scroll_mode; 
2265     mp_jump_out(mp);
2266 }
2267
2268
2269 There is a secret `\.D' option available when the debugging routines haven't
2270 been commented~out.
2271 @^debugging@>
2272
2273 @<Interpret code |c| and |return| if done@>=
2274 switch (c) {
2275 case '0': case '1': case '2': case '3': case '4':
2276 case '5': case '6': case '7': case '8': case '9': 
2277   if ( mp->deletions_allowed ) {
2278     @<Delete |c-"0"| tokens and |continue|@>;
2279   }
2280   break;
2281 #ifdef DEBUG
2282 case 'D': 
2283   mp_debug_help(mp); continue; 
2284   break;
2285 #endif
2286 case 'E': 
2287   if ( mp->file_ptr>0 ){ 
2288     (mp->run_editor)(mp, 
2289                      str(mp->input_stack[mp->file_ptr].name_field), 
2290                      mp_true_line(mp));
2291   }
2292   break;
2293 case 'H': 
2294   @<Print the help information and |continue|@>;
2295   break;
2296 case 'I':
2297   @<Introduce new material from the terminal and |return|@>;
2298   break;
2299 case 'Q': case 'R': case 'S':
2300   @<Change the interaction level and |return|@>;
2301   break;
2302 case 'X':
2303   mp->interaction=mp_scroll_mode; mp_jump_out(mp);
2304   break;
2305 default:
2306   break;
2307 }
2308 @<Print the menu of available options@>
2309
2310 @ @<Print the menu...@>=
2311
2312   mp_print(mp, "Type <return> to proceed, S to scroll future error messages,");
2313 @.Type <return> to proceed...@>
2314   mp_print_nl(mp, "R to run without stopping, Q to run quietly,");
2315   mp_print_nl(mp, "I to insert something, ");
2316   if ( mp->file_ptr>0 ) 
2317     mp_print(mp, "E to edit your file,");
2318   if ( mp->deletions_allowed )
2319     mp_print_nl(mp, "1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
2320   mp_print_nl(mp, "H for help, X to quit.");
2321 }
2322
2323 @ Here the author of \MP\ apologizes for making use of the numerical
2324 relation between |"Q"|, |"R"|, |"S"|, and the desired interaction settings
2325 |mp_batch_mode|, |mp_nonstop_mode|, |mp_scroll_mode|.
2326 @^Knuth, Donald Ervin@>
2327
2328 @<Change the interaction...@>=
2329
2330   mp->error_count=0; mp->interaction=mp_batch_mode+c-'Q';
2331   mp_print(mp, "OK, entering ");
2332   switch (c) {
2333   case 'Q': mp_print(mp, "batchmode"); decr(mp->selector); break;
2334   case 'R': mp_print(mp, "nonstopmode"); break;
2335   case 'S': mp_print(mp, "scrollmode"); break;
2336   } /* there are no other cases */
2337   mp_print(mp, "..."); mp_print_ln(mp); update_terminal; return;
2338 }
2339
2340 @ When the following code is executed, |buffer[(first+1)..(last-1)]| may
2341 contain the material inserted by the user; otherwise another prompt will
2342 be given. In order to understand this part of the program fully, you need
2343 to be familiar with \MP's input stacks.
2344
2345 @<Introduce new material...@>=
2346
2347   mp_begin_file_reading(mp); /* enter a new syntactic level for terminal input */
2348   if ( mp->last>mp->first+1 ) { 
2349     loc=mp->first+1; mp->buffer[mp->first]=' ';
2350   } else { 
2351    prompt_input("insert>"); loc=mp->first;
2352 @.insert>@>
2353   };
2354   mp->first=mp->last+1; mp->cur_input.limit_field=mp->last; return;
2355 }
2356
2357 @ We allow deletion of up to 99 tokens at a time.
2358
2359 @<Delete |c-"0"| tokens...@>=
2360
2361   s1=mp->cur_cmd; s2=mp->cur_mod; s3=mp->cur_sym; mp->OK_to_interrupt=false;
2362   if ( (mp->last>mp->first+1) && (mp->buffer[mp->first+1]>='0')&&(mp->buffer[mp->first+1]<='9') )
2363     c=c*10+mp->buffer[mp->first+1]-'0'*11;
2364   else 
2365     c=c-'0';
2366   while ( c>0 ) { 
2367     mp_get_next(mp); /* one-level recursive call of |error| is possible */
2368     @<Decrease the string reference count, if the current token is a string@>;
2369     decr(c);
2370   };
2371   mp->cur_cmd=s1; mp->cur_mod=s2; mp->cur_sym=s3; mp->OK_to_interrupt=true;
2372   help2("I have just deleted some text, as you asked.")
2373        ("You can now delete more, or insert, or whatever.");
2374   mp_show_context(mp); 
2375   goto CONTINUE;
2376 }
2377
2378 @ @<Print the help info...@>=
2379
2380   if ( mp->use_err_help ) { 
2381     @<Print the string |err_help|, possibly on several lines@>;
2382     mp->use_err_help=false;
2383   } else { 
2384     if ( mp->help_ptr==0 ) {
2385       help2("Sorry, I don't know how to help in this situation.")
2386            ("Maybe you should try asking a human?");
2387      }
2388     do { 
2389       decr(mp->help_ptr); mp_print(mp, mp->help_line[mp->help_ptr]); mp_print_ln(mp);
2390     } while (mp->help_ptr!=0);
2391   };
2392   help4("Sorry, I already gave what help I could...")
2393        ("Maybe you should try asking a human?")
2394        ("An error might have occurred before I noticed any problems.")
2395        ("``If all else fails, read the instructions.''");
2396   goto CONTINUE;
2397 }
2398
2399 @ @<Print the string |err_help|, possibly on several lines@>=
2400 j=mp->str_start[mp->err_help];
2401 while ( j<str_stop(mp->err_help) ) { 
2402   if ( mp->str_pool[j]!='%' ) mp_print_str(mp, mp->str_pool[j]);
2403   else if ( j+1==str_stop(mp->err_help) ) mp_print_ln(mp);
2404   else if ( mp->str_pool[j+1]!='%' ) mp_print_ln(mp);
2405   else  { incr(j); mp_print_char(mp, '%'); };
2406   incr(j);
2407 }
2408
2409 @ @<Put help message on the transcript file@>=
2410 if ( mp->interaction>mp_batch_mode ) decr(mp->selector); /* avoid terminal output */
2411 if ( mp->use_err_help ) { 
2412   mp_print_nl(mp, "");
2413   @<Print the string |err_help|, possibly on several lines@>;
2414 } else { 
2415   while ( mp->help_ptr>0 ){ 
2416     decr(mp->help_ptr); mp_print_nl(mp, mp->help_line[mp->help_ptr]);
2417   };
2418 }
2419 mp_print_ln(mp);
2420 if ( mp->interaction>mp_batch_mode ) incr(mp->selector); /* re-enable terminal output */
2421 mp_print_ln(mp)
2422
2423 @ In anomalous cases, the print selector might be in an unknown state;
2424 the following subroutine is called to fix things just enough to keep
2425 running a bit longer.
2426
2427 @c 
2428 void mp_normalize_selector (MP mp) { 
2429   if ( mp->log_opened ) mp->selector=term_and_log;
2430   else mp->selector=term_only;
2431   if ( mp->job_name==NULL ) mp_open_log_file(mp);
2432   if ( mp->interaction==mp_batch_mode ) decr(mp->selector);
2433 }
2434
2435 @ The following procedure prints \MP's last words before dying.
2436
2437 @d succumb { if ( mp->interaction==mp_error_stop_mode )
2438     mp->interaction=mp_scroll_mode; /* no more interaction */
2439   if ( mp->log_opened ) mp_error(mp);
2440   /* if ( mp->interaction>mp_batch_mode ) mp_debug_help(mp); */
2441   mp->history=mp_fatal_error_stop; mp_jump_out(mp); /* irrecoverable error */
2442   }
2443
2444 @<Error hand...@>=
2445 void mp_fatal_error (MP mp, char *s) { /* prints |s|, and that's it */
2446   mp_normalize_selector(mp);
2447   print_err("Emergency stop"); help1(s); succumb;
2448 @.Emergency stop@>
2449 }
2450
2451 @ @<Exported function ...@>=
2452 void mp_fatal_error (MP mp, char *s);
2453
2454
2455 @ Here is the most dreaded error message.
2456
2457 @<Error hand...@>=
2458 void mp_overflow (MP mp, char *s, integer n) { /* stop due to finiteness */
2459   mp_normalize_selector(mp);
2460   print_err("MetaPost capacity exceeded, sorry [");
2461 @.MetaPost capacity exceeded ...@>
2462   mp_print(mp, s); mp_print_char(mp, '='); mp_print_int(mp, n); mp_print_char(mp, ']');
2463   help2("If you really absolutely need more capacity,")
2464        ("you can ask a wizard to enlarge me.");
2465   succumb;
2466 }
2467
2468 @ @<Internal library declarations@>=
2469 void mp_overflow (MP mp, char *s, integer n);
2470
2471 @ The program might sometime run completely amok, at which point there is
2472 no choice but to stop. If no previous error has been detected, that's bad
2473 news; a message is printed that is really intended for the \MP\
2474 maintenance person instead of the user (unless the user has been
2475 particularly diabolical).  The index entries for `this can't happen' may
2476 help to pinpoint the problem.
2477 @^dry rot@>
2478
2479 @<Internal library ...@>=
2480 void mp_confusion (MP mp,char *s);
2481
2482 @ @<Error hand...@>=
2483 void mp_confusion (MP mp,char *s) {
2484   /* consistency check violated; |s| tells where */
2485   mp_normalize_selector(mp);
2486   if ( mp->history<mp_error_message_issued ) { 
2487     print_err("This can't happen ("); mp_print(mp, s); mp_print_char(mp, ')');
2488 @.This can't happen@>
2489     help1("I'm broken. Please show this to someone who can fix can fix");
2490   } else { 
2491     print_err("I can\'t go on meeting you like this");
2492 @.I can't go on...@>
2493     help2("One of your faux pas seems to have wounded me deeply...")
2494          ("in fact, I'm barely conscious. Please fix it and try again.");
2495   }
2496   succumb;
2497 }
2498
2499 @ Users occasionally want to interrupt \MP\ while it's running.
2500 If the \PASCAL\ runtime system allows this, one can implement
2501 a routine that sets the global variable |interrupt| to some nonzero value
2502 when such an interrupt is signaled. Otherwise there is probably at least
2503 a way to make |interrupt| nonzero using the \PASCAL\ debugger.
2504 @^system dependencies@>
2505 @^debugging@>
2506
2507 @d check_interrupt { if ( mp->interrupt!=0 )
2508    mp_pause_for_instructions(mp); }
2509
2510 @<Global...@>=
2511 integer interrupt; /* should \MP\ pause for instructions? */
2512 boolean OK_to_interrupt; /* should interrupts be observed? */
2513
2514 @ @<Allocate or ...@>=
2515 mp->interrupt=0; mp->OK_to_interrupt=true;
2516
2517 @ When an interrupt has been detected, the program goes into its
2518 highest interaction level and lets the user have the full flexibility of
2519 the |error| routine.  \MP\ checks for interrupts only at times when it is
2520 safe to do this.
2521
2522 @c 
2523 void mp_pause_for_instructions (MP mp) { 
2524   if ( mp->OK_to_interrupt ) { 
2525     mp->interaction=mp_error_stop_mode;
2526     if ( (mp->selector==log_only)||(mp->selector==no_print) )
2527       incr(mp->selector);
2528     print_err("Interruption");
2529 @.Interruption@>
2530     help3("You rang?")
2531          ("Try to insert some instructions for me (e.g.,`I show x'),")
2532          ("unless you just want to quit by typing `X'.");
2533     mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
2534     mp->interrupt=0;
2535   }
2536 }
2537
2538 @ Many of \MP's error messages state that a missing token has been
2539 inserted behind the scenes. We can save string space and program space
2540 by putting this common code into a subroutine.
2541
2542 @c 
2543 void mp_missing_err (MP mp, char *s) { 
2544   print_err("Missing `"); mp_print(mp, s); mp_print(mp, "' has been inserted");
2545 @.Missing...inserted@>
2546 }
2547
2548 @* \[7] Arithmetic with scaled numbers.
2549 The principal computations performed by \MP\ are done entirely in terms of
2550 integers less than $2^{31}$ in magnitude; thus, the arithmetic specified in this
2551 program can be carried out in exactly the same way on a wide variety of
2552 computers, including some small ones.
2553 @^small computers@>
2554
2555 But \PASCAL\ does not define the |div|
2556 operation in the case of negative dividends; for example, the result of
2557 |(-2*n-1) div 2| is |-(n+1)| on some computers and |-n| on others.
2558 There are two principal types of arithmetic: ``translation-preserving,''
2559 in which the identity |(a+q*b)div b=(a div b)+q| is valid; and
2560 ``negation-preserving,'' in which |(-a)div b=-(a div b)|. This leads to
2561 two \MP s, which can produce different results, although the differences
2562 should be negligible when the language is being used properly.
2563 The \TeX\ processor has been defined carefully so that both varieties
2564 of arithmetic will produce identical output, but it would be too
2565 inefficient to constrain \MP\ in a similar way.
2566
2567 @d el_gordo   017777777777 /* $2^{31}-1$, the largest value that \MP\ likes */
2568
2569 @ One of \MP's most common operations is the calculation of
2570 $\lfloor{a+b\over2}\rfloor$,
2571 the midpoint of two given integers |a| and~|b|. The only decent way to do
2572 this in \PASCAL\ is to write `|(a+b) div 2|'; but on most machines it is
2573 far more efficient to calculate `|(a+b)| right shifted one bit'.
2574
2575 Therefore the midpoint operation will always be denoted by `|half(a+b)|'
2576 in this program. If \MP\ is being implemented with languages that permit
2577 binary shifting, the |half| macro should be changed to make this operation
2578 as efficient as possible.  Since some languages have shift operators that can
2579 only be trusted to work on positive numbers, there is also a macro |halfp|
2580 that is used only when the quantity being halved is known to be positive
2581 or zero.
2582
2583 @d half(A) ((A) / 2)
2584 @d halfp(A) ((A) / 2)
2585
2586 @ A single computation might use several subroutine calls, and it is
2587 desirable to avoid producing multiple error messages in case of arithmetic
2588 overflow. So the routines below set the global variable |arith_error| to |true|
2589 instead of reporting errors directly to the user.
2590
2591 @<Glob...@>=
2592 boolean arith_error; /* has arithmetic overflow occurred recently? */
2593
2594 @ @<Allocate or ...@>=
2595 mp->arith_error=false;
2596
2597 @ At crucial points the program will say |check_arith|, to test if
2598 an arithmetic error has been detected.
2599
2600 @d check_arith { if ( mp->arith_error ) mp_clear_arith(mp); }
2601
2602 @c 
2603 void mp_clear_arith (MP mp) { 
2604   print_err("Arithmetic overflow");
2605 @.Arithmetic overflow@>
2606   help4("Uh, oh. A little while ago one of the quantities that I was")
2607        ("computing got too large, so I'm afraid your answers will be")
2608        ("somewhat askew. You'll probably have to adopt different")
2609        ("tactics next time. But I shall try to carry on anyway.");
2610   mp_error(mp); 
2611   mp->arith_error=false;
2612 }
2613
2614 @ Addition is not always checked to make sure that it doesn't overflow,
2615 but in places where overflow isn't too unlikely the |slow_add| routine
2616 is used.
2617
2618 @c integer mp_slow_add (MP mp,integer x, integer y) { 
2619   if ( x>=0 )  {
2620     if ( y<=el_gordo-x ) { 
2621       return x+y;
2622     } else  { 
2623       mp->arith_error=true; 
2624           return el_gordo;
2625     }
2626   } else  if ( -y<=el_gordo+x ) {
2627     return x+y;
2628   } else { 
2629     mp->arith_error=true; 
2630         return -el_gordo;
2631   }
2632 }
2633
2634 @ Fixed-point arithmetic is done on {\sl scaled integers\/} that are multiples
2635 of $2^{-16}$. In other words, a binary point is assumed to be sixteen bit
2636 positions from the right end of a binary computer word.
2637
2638 @d quarter_unit   040000 /* $2^{14}$, represents 0.250000 */
2639 @d half_unit   0100000 /* $2^{15}$, represents 0.50000 */
2640 @d three_quarter_unit   0140000 /* $3\cdot2^{14}$, represents 0.75000 */
2641 @d unity   0200000 /* $2^{16}$, represents 1.00000 */
2642 @d two   0400000 /* $2^{17}$, represents 2.00000 */
2643 @d three   0600000 /* $2^{17}+2^{16}$, represents 3.00000 */
2644
2645 @<Types...@>=
2646 typedef integer scaled; /* this type is used for scaled integers */
2647 typedef unsigned char small_number; /* this type is self-explanatory */
2648
2649 @ The following function is used to create a scaled integer from a given decimal
2650 fraction $(.d_0d_1\ldots d_{k-1})$, where |0<=k<=17|. The digit $d_i$ is
2651 given in |dig[i]|, and the calculation produces a correctly rounded result.
2652
2653 @c 
2654 scaled mp_round_decimals (MP mp,small_number k) {
2655   /* converts a decimal fraction */
2656  integer a = 0; /* the accumulator */
2657  while ( k-->0 ) { 
2658     a=(a+mp->dig[k]*two) / 10;
2659   }
2660   return halfp(a+1);
2661 }
2662
2663 @ Conversely, here is a procedure analogous to |print_int|. If the output
2664 of this procedure is subsequently read by \MP\ and converted by the
2665 |round_decimals| routine above, it turns out that the original value will
2666 be reproduced exactly. A decimal point is printed only if the value is
2667 not an integer. If there is more than one way to print the result with
2668 the optimum number of digits following the decimal point, the closest
2669 possible value is given.
2670
2671 The invariant relation in the \&{repeat} loop is that a sequence of
2672 decimal digits yet to be printed will yield the original number if and only if
2673 they form a fraction~$f$ in the range $s-\delta\L10\cdot2^{16}f<s$.
2674 We can stop if and only if $f=0$ satisfies this condition; the loop will
2675 terminate before $s$ can possibly become zero.
2676
2677 @<Basic printing...@>=
2678 void mp_print_scaled (MP mp,scaled s) { /* prints scaled real, rounded to five  digits */
2679   scaled delta; /* amount of allowable inaccuracy */
2680   if ( s<0 ) { 
2681         mp_print_char(mp, '-'); 
2682     negate(s); /* print the sign, if negative */
2683   }
2684   mp_print_int(mp, s / unity); /* print the integer part */
2685   s=10*(s % unity)+5;
2686   if ( s!=5 ) { 
2687     delta=10; 
2688     mp_print_char(mp, '.');
2689     do {  
2690       if ( delta>unity )
2691         s=s+0100000-(delta / 2); /* round the final digit */
2692       mp_print_char(mp, '0'+(s / unity)); 
2693       s=10*(s % unity); 
2694       delta=delta*10;
2695     } while (s>delta);
2696   }
2697 }
2698
2699 @ We often want to print two scaled quantities in parentheses,
2700 separated by a comma.
2701
2702 @<Basic printing...@>=
2703 void mp_print_two (MP mp,scaled x, scaled y) { /* prints `|(x,y)|' */
2704   mp_print_char(mp, '('); 
2705   mp_print_scaled(mp, x); 
2706   mp_print_char(mp, ','); 
2707   mp_print_scaled(mp, y);
2708   mp_print_char(mp, ')');
2709 }
2710
2711 @ The |scaled| quantities in \MP\ programs are generally supposed to be
2712 less than $2^{12}$ in absolute value, so \MP\ does much of its internal
2713 arithmetic with 28~significant bits of precision. A |fraction| denotes
2714 a scaled integer whose binary point is assumed to be 28 bit positions
2715 from the right.
2716
2717 @d fraction_half 01000000000 /* $2^{27}$, represents 0.50000000 */
2718 @d fraction_one 02000000000 /* $2^{28}$, represents 1.00000000 */
2719 @d fraction_two 04000000000 /* $2^{29}$, represents 2.00000000 */
2720 @d fraction_three 06000000000 /* $3\cdot2^{28}$, represents 3.00000000 */
2721 @d fraction_four 010000000000 /* $2^{30}$, represents 4.00000000 */
2722
2723 @<Types...@>=
2724 typedef integer fraction; /* this type is used for scaled fractions */
2725
2726 @ In fact, the two sorts of scaling discussed above aren't quite
2727 sufficient; \MP\ has yet another, used internally to keep track of angles
2728 in units of $2^{-20}$ degrees.
2729
2730 @d forty_five_deg 0264000000 /* $45\cdot2^{20}$, represents $45^\circ$ */
2731 @d ninety_deg 0550000000 /* $90\cdot2^{20}$, represents $90^\circ$ */
2732 @d one_eighty_deg 01320000000 /* $180\cdot2^{20}$, represents $180^\circ$ */
2733 @d three_sixty_deg 02640000000 /* $360\cdot2^{20}$, represents $360^\circ$ */
2734
2735 @<Types...@>=
2736 typedef integer angle; /* this type is used for scaled angles */
2737
2738 @ The |make_fraction| routine produces the |fraction| equivalent of
2739 |p/q|, given integers |p| and~|q|; it computes the integer
2740 $f=\lfloor2^{28}p/q+{1\over2}\rfloor$, when $p$ and $q$ are
2741 positive. If |p| and |q| are both of the same scaled type |t|,
2742 the ``type relation'' |make_fraction(t,t)=fraction| is valid;
2743 and it's also possible to use the subroutine ``backwards,'' using
2744 the relation |make_fraction(t,fraction)=t| between scaled types.
2745
2746 If the result would have magnitude $2^{31}$ or more, |make_fraction|
2747 sets |arith_error:=true|. Most of \MP's internal computations have
2748 been designed to avoid this sort of error.
2749
2750 If this subroutine were programmed in assembly language on a typical
2751 machine, we could simply compute |(@t$2^{28}$@>*p)div q|, since a
2752 double-precision product can often be input to a fixed-point division
2753 instruction. But when we are restricted to \PASCAL\ arithmetic it
2754 is necessary either to resort to multiple-precision maneuvering
2755 or to use a simple but slow iteration. The multiple-precision technique
2756 would be about three times faster than the code adopted here, but it
2757 would be comparatively long and tricky, involving about sixteen
2758 additional multiplications and divisions.
2759
2760 This operation is part of \MP's ``inner loop''; indeed, it will
2761 consume nearly 10\pct! of the running time (exclusive of input and output)
2762 if the code below is left unchanged. A machine-dependent recoding
2763 will therefore make \MP\ run faster. The present implementation
2764 is highly portable, but slow; it avoids multiplication and division
2765 except in the initial stage. System wizards should be careful to
2766 replace it with a routine that is guaranteed to produce identical
2767 results in all cases.
2768 @^system dependencies@>
2769
2770 As noted below, a few more routines should also be replaced by machine-dependent
2771 code, for efficiency. But when a procedure is not part of the ``inner loop,''
2772 such changes aren't advisable; simplicity and robustness are
2773 preferable to trickery, unless the cost is too high.
2774 @^inner loop@>
2775
2776 @<Internal ...@>=
2777 fraction mp_make_fraction (MP mp,integer p, integer q);
2778 integer mp_take_scaled (MP mp,integer q, scaled f) ;
2779
2780 @ If FIXPT is not defined, we need these preprocessor values
2781
2782 @d ELGORDO  0x7fffffff
2783 @d TWEXP31  2147483648.0
2784 @d TWEXP28  268435456.0
2785 @d TWEXP16 65536.0
2786 @d TWEXP_16 (1.0/65536.0)
2787 @d TWEXP_28 (1.0/268435456.0)
2788
2789
2790 @c 
2791 fraction mp_make_fraction (MP mp,integer p, integer q) {
2792 #ifdef FIXPT
2793   integer f; /* the fraction bits, with a leading 1 bit */
2794   integer n; /* the integer part of $\vert p/q\vert$ */
2795   integer be_careful; /* disables certain compiler optimizations */
2796   boolean negative = false; /* should the result be negated? */
2797   if ( p<0 ) {
2798     negate(p); negative=true;
2799   }
2800   if ( q<=0 ) { 
2801 #ifdef DEBUG
2802     if ( q==0 ) mp_confusion(mp, '/');
2803 #endif
2804 @:this can't happen /}{\quad \./@>
2805     negate(q); negative = ! negative;
2806   };
2807   n=p / q; p=p % q;
2808   if ( n>=8 ){ 
2809     mp->arith_error=true;
2810     return ( negative ? -el_gordo : el_gordo);
2811   } else { 
2812     n=(n-1)*fraction_one;
2813     @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>;
2814     return (negative ? (-(f+n)) : (f+n));
2815   }
2816 #else /* FIXPT */
2817     register double d;
2818         register integer i;
2819 #ifdef DEBUG
2820         if (q==0) mp_confusion(mp,'/'); 
2821 #endif /* DEBUG */
2822         d = TWEXP28 * (double)p /(double)q;
2823         if ((p^q) >= 0) {
2824                 d += 0.5;
2825                 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
2826                 i = (integer) d;
2827                 if (d==i && ( ((q>0 ? -q : q)&077777)
2828                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2829         } else {
2830                 d -= 0.5;
2831                 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
2832                 i = (integer) d;
2833                 if (d==i && ( ((q>0 ? q : -q)&077777)
2834                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
2835         }
2836         return i;
2837 #endif /* FIXPT */
2838 }
2839
2840 @ The |repeat| loop here preserves the following invariant relations
2841 between |f|, |p|, and~|q|:
2842 (i)~|0<=p<q|; (ii)~$fq+p=2^k(q+p_0)$, where $k$ is an integer and
2843 $p_0$ is the original value of~$p$.
2844
2845 Notice that the computation specifies
2846 |(p-q)+p| instead of |(p+p)-q|, because the latter could overflow.
2847 Let us hope that optimizing compilers do not miss this point; a
2848 special variable |be_careful| is used to emphasize the necessary
2849 order of computation. Optimizing compilers should keep |be_careful|
2850 in a register, not store it in memory.
2851 @^inner loop@>
2852
2853 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>=
2854 {
2855   f=1;
2856   do {  
2857     be_careful=p-q; p=be_careful+p;
2858     if ( p>=0 ) { 
2859       f=f+f+1;
2860     } else  { 
2861       f+=f; p=p+q;
2862     }
2863   } while (f<fraction_one);
2864   be_careful=p-q;
2865   if ( be_careful+p>=0 ) incr(f);
2866 }
2867
2868 @ The dual of |make_fraction| is |take_fraction|, which multiplies a
2869 given integer~|q| by a fraction~|f|. When the operands are positive, it
2870 computes $p=\lfloor qf/2^{28}+{1\over2}\rfloor$, a symmetric function
2871 of |q| and~|f|.
2872
2873 This routine is even more ``inner loopy'' than |make_fraction|;
2874 the present implementation consumes almost 20\pct! of \MP's computation
2875 time during typical jobs, so a machine-language substitute is advisable.
2876 @^inner loop@> @^system dependencies@>
2877
2878 @<Declarations@>=
2879 integer mp_take_fraction (MP mp,integer q, fraction f) ;
2880
2881 @ @c 
2882 #ifdef FIXPT
2883 integer mp_take_fraction (MP mp,integer q, fraction f) {
2884   integer p; /* the fraction so far */
2885   boolean negative; /* should the result be negated? */
2886   integer n; /* additional multiple of $q$ */
2887   integer be_careful; /* disables certain compiler optimizations */
2888   @<Reduce to the case that |f>=0| and |q>0|@>;
2889   if ( f<fraction_one ) { 
2890     n=0;
2891   } else { 
2892     n=f / fraction_one; f=f % fraction_one;
2893     if ( q<=el_gordo / n ) { 
2894       n=n*q ; 
2895     } else { 
2896       mp->arith_error=true; n=el_gordo;
2897     }
2898   }
2899   f=f+fraction_one;
2900   @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>;
2901   be_careful=n-el_gordo;
2902   if ( be_careful+p>0 ){ 
2903     mp->arith_error=true; n=el_gordo-p;
2904   }
2905   if ( negative ) 
2906         return (-(n+p));
2907   else 
2908     return (n+p);
2909 #else /* FIXPT */
2910 integer mp_take_fraction (MP mp,integer p, fraction q) {
2911     register double d;
2912         register integer i;
2913         d = (double)p * (double)q * TWEXP_28;
2914         if ((p^q) >= 0) {
2915                 d += 0.5;
2916                 if (d>=TWEXP31) {
2917                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2918                                 mp->arith_error = true;
2919                         return ELGORDO;
2920                 }
2921                 i = (integer) d;
2922                 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2923         } else {
2924                 d -= 0.5;
2925                 if (d<= -TWEXP31) {
2926                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2927                                 mp->arith_error = true;
2928                         return -ELGORDO;
2929                 }
2930                 i = (integer) d;
2931                 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2932         }
2933         return i;
2934 #endif /* FIXPT */
2935 }
2936
2937 @ @<Reduce to the case that |f>=0| and |q>0|@>=
2938 if ( f>=0 ) {
2939   negative=false;
2940 } else { 
2941   negate( f); negative=true;
2942 }
2943 if ( q<0 ) { 
2944   negate(q); negative=! negative;
2945 }
2946
2947 @ The invariant relations in this case are (i)~$\lfloor(qf+p)/2^k\rfloor
2948 =\lfloor qf_0/2^{28}+{1\over2}\rfloor$, where $k$ is an integer and
2949 $f_0$ is the original value of~$f$; (ii)~$2^k\L f<2^{k+1}$.
2950 @^inner loop@>
2951
2952 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>=
2953 p=fraction_half; /* that's $2^{27}$; the invariants hold now with $k=28$ */
2954 if ( q<fraction_four ) {
2955   do {  
2956     if ( odd(f) ) p=halfp(p+q); else p=halfp(p);
2957     f=halfp(f);
2958   } while (f!=1);
2959 } else  {
2960   do {  
2961     if ( odd(f) ) p=p+halfp(q-p); else p=halfp(p);
2962     f=halfp(f);
2963   } while (f!=1);
2964 }
2965
2966
2967 @ When we want to multiply something by a |scaled| quantity, we use a scheme
2968 analogous to |take_fraction| but with a different scaling.
2969 Given positive operands, |take_scaled|
2970 computes the quantity $p=\lfloor qf/2^{16}+{1\over2}\rfloor$.
2971
2972 Once again it is a good idea to use a machine-language replacement if
2973 possible; otherwise |take_scaled| will use more than 2\pct! of the running time
2974 when the Computer Modern fonts are being generated.
2975 @^inner loop@>
2976
2977 @c 
2978 #ifdef FIXPT
2979 integer mp_take_scaled (MP mp,integer q, scaled f) {
2980   integer p; /* the fraction so far */
2981   boolean negative; /* should the result be negated? */
2982   integer n; /* additional multiple of $q$ */
2983   integer be_careful; /* disables certain compiler optimizations */
2984   @<Reduce to the case that |f>=0| and |q>0|@>;
2985   if ( f<unity ) { 
2986     n=0;
2987   } else  { 
2988     n=f / unity; f=f % unity;
2989     if ( q<=el_gordo / n ) {
2990       n=n*q;
2991     } else  { 
2992       mp->arith_error=true; n=el_gordo;
2993     }
2994   }
2995   f=f+unity;
2996   @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>;
2997   be_careful=n-el_gordo;
2998   if ( be_careful+p>0 ) { 
2999     mp->arith_error=true; n=el_gordo-p;
3000   }
3001   return ( negative ?(-(n+p)) :(n+p));
3002 #else /* FIXPT */
3003 integer mp_take_scaled (MP mp,integer p, scaled q) {
3004     register double d;
3005         register integer i;
3006         d = (double)p * (double)q * TWEXP_16;
3007         if ((p^q) >= 0) {
3008                 d += 0.5;
3009                 if (d>=TWEXP31) {
3010                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
3011                                 mp->arith_error = true;
3012                         return ELGORDO;
3013                 }
3014                 i = (integer) d;
3015                 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
3016         } else {
3017                 d -= 0.5;
3018                 if (d<= -TWEXP31) {
3019                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
3020                                 mp->arith_error = true;
3021                         return -ELGORDO;
3022                 }
3023                 i = (integer) d;
3024                 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
3025         }
3026         return i;
3027 #endif /* FIXPT */
3028 }
3029
3030 @ @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>=
3031 p=half_unit; /* that's $2^{15}$; the invariants hold now with $k=16$ */
3032 @^inner loop@>
3033 if ( q<fraction_four ) {
3034   do {  
3035     p = (odd(f) ? halfp(p+q) : halfp(p));
3036     f=halfp(f);
3037   } while (f!=1);
3038 } else {
3039   do {  
3040     p = (odd(f) ? p+halfp(q-p) : halfp(p));
3041     f=halfp(f);
3042   } while (f!=1);
3043 }
3044
3045 @ For completeness, there's also |make_scaled|, which computes a
3046 quotient as a |scaled| number instead of as a |fraction|.
3047 In other words, the result is $\lfloor2^{16}p/q+{1\over2}\rfloor$, if the
3048 operands are positive. \ (This procedure is not used especially often,
3049 so it is not part of \MP's inner loop.)
3050
3051 @<Internal library ...@>=
3052 scaled mp_make_scaled (MP mp,integer p, integer q) ;
3053
3054 @ @c 
3055 scaled mp_make_scaled (MP mp,integer p, integer q) {
3056 #ifdef FIXPT 
3057   integer f; /* the fraction bits, with a leading 1 bit */
3058   integer n; /* the integer part of $\vert p/q\vert$ */
3059   boolean negative; /* should the result be negated? */
3060   integer be_careful; /* disables certain compiler optimizations */
3061   if ( p>=0 ) negative=false;
3062   else  { negate(p); negative=true; };
3063   if ( q<=0 ) { 
3064 #ifdef DEBUG 
3065     if ( q==0 ) mp_confusion(mp, "/");
3066 @:this can't happen /}{\quad \./@>
3067 #endif
3068     negate(q); negative=! negative;
3069   }
3070   n=p / q; p=p % q;
3071   if ( n>=0100000 ) { 
3072     mp->arith_error=true;
3073     return (negative ? (-el_gordo) : el_gordo);
3074   } else  { 
3075     n=(n-1)*unity;
3076     @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>;
3077     return ( negative ? (-(f+n)) :(f+n));
3078   }
3079 #else /* FIXPT */
3080     register double d;
3081         register integer i;
3082 #ifdef DEBUG
3083         if (q==0) mp_confusion(mp,"/"); 
3084 #endif /* DEBUG */
3085         d = TWEXP16 * (double)p /(double)q;
3086         if ((p^q) >= 0) {
3087                 d += 0.5;
3088                 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
3089                 i = (integer) d;
3090                 if (d==i && ( ((q>0 ? -q : q)&077777)
3091                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
3092         } else {
3093                 d -= 0.5;
3094                 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
3095                 i = (integer) d;
3096                 if (d==i && ( ((q>0 ? q : -q)&077777)
3097                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
3098         }
3099         return i;
3100 #endif /* FIXPT */
3101 }
3102
3103 @ @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>=
3104 f=1;
3105 do {  
3106   be_careful=p-q; p=be_careful+p;
3107   if ( p>=0 ) f=f+f+1;
3108   else  { f+=f; p=p+q; };
3109 } while (f<unity);
3110 be_careful=p-q;
3111 if ( be_careful+p>=0 ) incr(f)
3112
3113 @ Here is a typical example of how the routines above can be used.
3114 It computes the function
3115 $${1\over3\tau}f(\theta,\phi)=
3116 {\tau^{-1}\bigl(2+\sqrt2\,(\sin\theta-{1\over16}\sin\phi)
3117  (\sin\phi-{1\over16}\sin\theta)(\cos\theta-\cos\phi)\bigr)\over
3118 3\,\bigl(1+{1\over2}(\sqrt5-1)\cos\theta+{1\over2}(3-\sqrt5\,)\cos\phi\bigr)},$$
3119 where $\tau$ is a |scaled| ``tension'' parameter. This is \MP's magic
3120 fudge factor for placing the first control point of a curve that starts
3121 at an angle $\theta$ and ends at an angle $\phi$ from the straight path.
3122 (Actually, if the stated quantity exceeds 4, \MP\ reduces it to~4.)
3123
3124 The trigonometric quantity to be multiplied by $\sqrt2$ is less than $\sqrt2$.
3125 (It's a sum of eight terms whose absolute values can be bounded using
3126 relations such as $\sin\theta\cos\theta\L{1\over2}$.) Thus the numerator
3127 is positive; and since the tension $\tau$ is constrained to be at least
3128 $3\over4$, the numerator is less than $16\over3$. The denominator is
3129 nonnegative and at most~6.  Hence the fixed-point calculations below
3130 are guaranteed to stay within the bounds of a 32-bit computer word.
3131
3132 The angles $\theta$ and $\phi$ are given implicitly in terms of |fraction|
3133 arguments |st|, |ct|, |sf|, and |cf|, representing $\sin\theta$, $\cos\theta$,
3134 $\sin\phi$, and $\cos\phi$, respectively.
3135
3136 @c 
3137 fraction mp_velocity (MP mp,fraction st, fraction ct, fraction sf,
3138                       fraction cf, scaled t) {
3139   integer acc,num,denom; /* registers for intermediate calculations */
3140   acc=mp_take_fraction(mp, st-(sf / 16), sf-(st / 16));
3141   acc=mp_take_fraction(mp, acc,ct-cf);
3142   num=fraction_two+mp_take_fraction(mp, acc,379625062);
3143                    /* $2^{28}\sqrt2\approx379625062.497$ */
3144   denom=fraction_three+mp_take_fraction(mp, ct,497706707)+mp_take_fraction(mp, cf,307599661);
3145                       /* $3\cdot2^{27}\cdot(\sqrt5-1)\approx497706706.78$ and
3146                          $3\cdot2^{27}\cdot(3-\sqrt5\,)\approx307599661.22$ */
3147   if ( t!=unity ) num=mp_make_scaled(mp, num,t);
3148   /* |make_scaled(fraction,scaled)=fraction| */
3149   if ( num / 4>=denom ) 
3150     return fraction_four;
3151   else 
3152     return mp_make_fraction(mp, num, denom);
3153 }
3154
3155 @ The following somewhat different subroutine tests rigorously if $ab$ is
3156 greater than, equal to, or less than~$cd$,
3157 given integers $(a,b,c,d)$. In most cases a quick decision is reached.
3158 The result is $+1$, 0, or~$-1$ in the three respective cases.
3159
3160 @d mp_ab_vs_cd(M,A,B,C,D) mp_do_ab_vs_cd(A,B,C,D)
3161
3162 @c 
3163 integer mp_do_ab_vs_cd (integer a,integer b, integer c, integer d) {
3164   integer q,r; /* temporary registers */
3165   @<Reduce to the case that |a,c>=0|, |b,d>0|@>;
3166   while (1) { 
3167     q = a / d; r = c / b;
3168     if ( q!=r )
3169       return ( q>r ? 1 : -1);
3170     q = a % d; r = c % b;
3171     if ( r==0 )
3172       return (q ? 1 : 0);
3173     if ( q==0 ) return -1;
3174     a=b; b=q; c=d; d=r;
3175   } /* now |a>d>0| and |c>b>0| */
3176 }
3177
3178 @ @<Reduce to the case that |a...@>=
3179 if ( a<0 ) { negate(a); negate(b);  };
3180 if ( c<0 ) { negate(c); negate(d);  };
3181 if ( d<=0 ) { 
3182   if ( b>=0 ) {
3183     if ( (a==0||b==0)&&(c==0||d==0) ) return 0;
3184     else return 1;
3185   }
3186   if ( d==0 )
3187     return ( a==0 ? 0 : -1);
3188   q=a; a=c; c=q; q=-b; b=-d; d=q;
3189 } else if ( b<=0 ) { 
3190   if ( b<0 ) if ( a>0 ) return -1;
3191   return (c==0 ? 0 : -1);
3192 }
3193
3194 @ We conclude this set of elementary routines with some simple rounding
3195 and truncation operations.
3196
3197 @<Internal library declarations@>=
3198 #define mp_floor_scaled(M,i) ((i)&(-65536))
3199 #define mp_round_unscaled(M,i) (((i>>15)+1)>>1)
3200 #define mp_round_fraction(M,i) (((i>>11)+1)>>1)
3201
3202
3203 @* \[8] Algebraic and transcendental functions.
3204 \MP\ computes all of the necessary special functions from scratch, without
3205 relying on |real| arithmetic or system subroutines for sines, cosines, etc.
3206
3207 @ To get the square root of a |scaled| number |x|, we want to calculate
3208 $s=\lfloor 2^8\!\sqrt x +{1\over2}\rfloor$. If $x>0$, this is the unique
3209 integer such that $2^{16}x-s\L s^2<2^{16}x+s$. The following subroutine
3210 determines $s$ by an iterative method that maintains the invariant
3211 relations $x=2^{46-2k}x_0\bmod 2^{30}$, $0<y=\lfloor 2^{16-2k}x_0\rfloor
3212 -s^2+s\L q=2s$, where $x_0$ is the initial value of $x$. The value of~$y$
3213 might, however, be zero at the start of the first iteration.
3214
3215 @<Declarations@>=
3216 scaled mp_square_rt (MP mp,scaled x) ;
3217
3218 @ @c 
3219 scaled mp_square_rt (MP mp,scaled x) {
3220   small_number k; /* iteration control counter */
3221   integer y,q; /* registers for intermediate calculations */
3222   if ( x<=0 ) { 
3223     @<Handle square root of zero or negative argument@>;
3224   } else { 
3225     k=23; q=2;
3226     while ( x<fraction_two ) { /* i.e., |while x<@t$2^{29}$@>|\unskip */
3227       decr(k); x=x+x+x+x;
3228     }
3229     if ( x<fraction_four ) y=0;
3230     else  { x=x-fraction_four; y=1; };
3231     do {  
3232       @<Decrease |k| by 1, maintaining the invariant
3233       relations between |x|, |y|, and~|q|@>;
3234     } while (k!=0);
3235     return (halfp(q));
3236   }
3237 }
3238
3239 @ @<Handle square root of zero...@>=
3240
3241   if ( x<0 ) { 
3242     print_err("Square root of ");
3243 @.Square root...replaced by 0@>
3244     mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3245     help2("Since I don't take square roots of negative numbers,")
3246          ("I'm zeroing this one. Proceed, with fingers crossed.");
3247     mp_error(mp);
3248   };
3249   return 0;
3250 }
3251
3252 @ @<Decrease |k| by 1, maintaining...@>=
3253 x+=x; y+=y;
3254 if ( x>=fraction_four ) { /* note that |fraction_four=@t$2^{30}$@>| */
3255   x=x-fraction_four; incr(y);
3256 };
3257 x+=x; y=y+y-q; q+=q;
3258 if ( x>=fraction_four ) { x=x-fraction_four; incr(y); };
3259 if ( y>q ){ y=y-q; q=q+2; }
3260 else if ( y<=0 )  { q=q-2; y=y+q;  };
3261 decr(k)
3262
3263 @ Pythagorean addition $\psqrt{a^2+b^2}$ is implemented by an elegant
3264 iterative scheme due to Cleve Moler and Donald Morrison [{\sl IBM Journal
3265 @^Moler, Cleve Barry@>
3266 @^Morrison, Donald Ross@>
3267 of Research and Development\/ \bf27} (1983), 577--581]. It modifies |a| and~|b|
3268 in such a way that their Pythagorean sum remains invariant, while the
3269 smaller argument decreases.
3270
3271 @<Internal library ...@>=
3272 integer mp_pyth_add (MP mp,integer a, integer b);
3273
3274
3275 @ @c 
3276 integer mp_pyth_add (MP mp,integer a, integer b) {
3277   fraction r; /* register used to transform |a| and |b| */
3278   boolean big; /* is the result dangerously near $2^{31}$? */
3279   a=abs(a); b=abs(b);
3280   if ( a<b ) { r=b; b=a; a=r; }; /* now |0<=b<=a| */
3281   if ( b>0 ) {
3282     if ( a<fraction_two ) {
3283       big=false;
3284     } else { 
3285       a=a / 4; b=b / 4; big=true;
3286     }; /* we reduced the precision to avoid arithmetic overflow */
3287     @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>;
3288     if ( big ) {
3289       if ( a<fraction_two ) {
3290         a=a+a+a+a;
3291       } else  { 
3292         mp->arith_error=true; a=el_gordo;
3293       };
3294     }
3295   }
3296   return a;
3297 }
3298
3299 @ The key idea here is to reflect the vector $(a,b)$ about the
3300 line through $(a,b/2)$.
3301
3302 @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>=
3303 while (1) {  
3304   r=mp_make_fraction(mp, b,a);
3305   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3306   if ( r==0 ) break;
3307   r=mp_make_fraction(mp, r,fraction_four+r);
3308   a=a+mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3309 }
3310
3311
3312 @ Here is a similar algorithm for $\psqrt{a^2-b^2}$.
3313 It converges slowly when $b$ is near $a$, but otherwise it works fine.
3314
3315 @c 
3316 integer mp_pyth_sub (MP mp,integer a, integer b) {
3317   fraction r; /* register used to transform |a| and |b| */
3318   boolean big; /* is the input dangerously near $2^{31}$? */
3319   a=abs(a); b=abs(b);
3320   if ( a<=b ) {
3321     @<Handle erroneous |pyth_sub| and set |a:=0|@>;
3322   } else { 
3323     if ( a<fraction_four ) {
3324       big=false;
3325     } else  { 
3326       a=halfp(a); b=halfp(b); big=true;
3327     }
3328     @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>;
3329     if ( big ) double(a);
3330   }
3331   return a;
3332 }
3333
3334 @ @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>=
3335 while (1) { 
3336   r=mp_make_fraction(mp, b,a);
3337   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3338   if ( r==0 ) break;
3339   r=mp_make_fraction(mp, r,fraction_four-r);
3340   a=a-mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3341 }
3342
3343 @ @<Handle erroneous |pyth_sub| and set |a:=0|@>=
3344
3345   if ( a<b ){ 
3346     print_err("Pythagorean subtraction "); mp_print_scaled(mp, a);
3347     mp_print(mp, "+-+"); mp_print_scaled(mp, b); 
3348     mp_print(mp, " has been replaced by 0");
3349 @.Pythagorean...@>
3350     help2("Since I don't take square roots of negative numbers,")
3351          ("I'm zeroing this one. Proceed, with fingers crossed.");
3352     mp_error(mp);
3353   }
3354   a=0;
3355 }
3356
3357 @ The subroutines for logarithm and exponential involve two tables.
3358 The first is simple: |two_to_the[k]| equals $2^k$. The second involves
3359 a bit more calculation, which the author claims to have done correctly:
3360 |spec_log[k]| is $2^{27}$ times $\ln\bigl(1/(1-2^{-k})\bigr)=
3361 2^{-k}+{1\over2}2^{-2k}+{1\over3}2^{-3k}+\cdots\,$, rounded to the
3362 nearest integer.
3363
3364 @d two_to_the(A) (1<<(A))
3365
3366 @<Constants ...@>=
3367 static const integer spec_log[29] = { 0, /* special logarithms */
3368 93032640, 38612034, 17922280, 8662214, 4261238, 2113709,
3369 1052693, 525315, 262400, 131136, 65552, 32772, 16385,
3370 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 1 };
3371
3372 @ @<Local variables for initialization@>=
3373 integer k; /* all-purpose loop index */
3374
3375
3376 @ Here is the routine that calculates $2^8$ times the natural logarithm
3377 of a |scaled| quantity; it is an integer approximation to $2^{24}\ln(x/2^{16})$,
3378 when |x| is a given positive integer.
3379
3380 The method is based on exercise 1.2.2--25 in {\sl The Art of Computer
3381 Programming\/}: During the main iteration we have $1\L 2^{-30}x<1/(1-2^{1-k})$,
3382 and the logarithm of $2^{30}x$ remains to be added to an accumulator
3383 register called~$y$. Three auxiliary bits of accuracy are retained in~$y$
3384 during the calculation, and sixteen auxiliary bits to extend |y| are
3385 kept in~|z| during the initial argument reduction. (We add
3386 $100\cdot2^{16}=6553600$ to~|z| and subtract 100 from~|y| so that |z| will
3387 not become negative; also, the actual amount subtracted from~|y| is~96,
3388 not~100, because we want to add~4 for rounding before the final division by~8.)
3389
3390 @c 
3391 scaled mp_m_log (MP mp,scaled x) {
3392   integer y,z; /* auxiliary registers */
3393   integer k; /* iteration counter */
3394   if ( x<=0 ) {
3395      @<Handle non-positive logarithm@>;
3396   } else  { 
3397     y=1302456956+4-100; /* $14\times2^{27}\ln2\approx1302456956.421063$ */
3398     z=27595+6553600; /* and $2^{16}\times .421063\approx 27595$ */
3399     while ( x<fraction_four ) {
3400        double(x); y-=93032639; z-=48782;
3401     } /* $2^{27}\ln2\approx 93032639.74436163$ and $2^{16}\times.74436163\approx 48782$ */
3402     y=y+(z / unity); k=2;
3403     while ( x>fraction_four+4 ) {
3404       @<Increase |k| until |x| can be multiplied by a
3405         factor of $2^{-k}$, and adjust $y$ accordingly@>;
3406     }
3407     return (y / 8);
3408   }
3409 }
3410
3411 @ @<Increase |k| until |x| can...@>=
3412
3413   z=((x-1) / two_to_the(k))+1; /* $z=\lceil x/2^k\rceil$ */
3414   while ( x<fraction_four+z ) { z=halfp(z+1); incr(k); };
3415   y+=spec_log[k]; x-=z;
3416 }
3417
3418 @ @<Handle non-positive logarithm@>=
3419
3420   print_err("Logarithm of ");
3421 @.Logarithm...replaced by 0@>
3422   mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3423   help2("Since I don't take logs of non-positive numbers,")
3424        ("I'm zeroing this one. Proceed, with fingers crossed.");
3425   mp_error(mp); 
3426   return 0;
3427 }
3428
3429 @ Conversely, the exponential routine calculates $\exp(x/2^8)$,
3430 when |x| is |scaled|. The result is an integer approximation to
3431 $2^{16}\exp(x/2^{24})$, when |x| is regarded as an integer.
3432
3433 @c 
3434 scaled mp_m_exp (MP mp,scaled x) {
3435   small_number k; /* loop control index */
3436   integer y,z; /* auxiliary registers */
3437   if ( x>174436200 ) {
3438     /* $2^{24}\ln((2^{31}-1)/2^{16})\approx 174436199.51$ */
3439     mp->arith_error=true; 
3440     return el_gordo;
3441   } else if ( x<-197694359 ) {
3442         /* $2^{24}\ln(2^{-1}/2^{16})\approx-197694359.45$ */
3443     return 0;
3444   } else { 
3445     if ( x<=0 ) { 
3446        z=-8*x; y=04000000; /* $y=2^{20}$ */
3447     } else { 
3448       if ( x<=127919879 ) { 
3449         z=1023359037-8*x;
3450         /* $2^{27}\ln((2^{31}-1)/2^{20})\approx 1023359037.125$ */
3451       } else {
3452        z=8*(174436200-x); /* |z| is always nonnegative */
3453       }
3454       y=el_gordo;
3455     };
3456     @<Multiply |y| by $\exp(-z/2^{27})$@>;
3457     if ( x<=127919879 ) 
3458        return ((y+8) / 16);
3459      else 
3460        return y;
3461   }
3462 }
3463
3464 @ The idea here is that subtracting |spec_log[k]| from |z| corresponds
3465 to multiplying |y| by $1-2^{-k}$.
3466
3467 A subtle point (which had to be checked) was that if $x=127919879$, the
3468 value of~|y| will decrease so that |y+8| doesn't overflow. In fact,
3469 $z$ will be 5 in this case, and |y| will decrease by~64 when |k=25|
3470 and by~16 when |k=27|.
3471
3472 @<Multiply |y| by...@>=
3473 k=1;
3474 while ( z>0 ) { 
3475   while ( z>=spec_log[k] ) { 
3476     z-=spec_log[k];
3477     y=y-1-((y-two_to_the(k-1)) / two_to_the(k));
3478   }
3479   incr(k);
3480 }
3481
3482 @ The trigonometric subroutines use an auxiliary table such that
3483 |spec_atan[k]| contains an approximation to the |angle| whose tangent
3484 is~$1/2^k$. $\arctan2^{-k}$ times $2^{20}\cdot180/\pi$ 
3485
3486 @<Constants ...@>=
3487 static const angle spec_atan[27] = { 0, 27855475, 14718068, 7471121, 3750058, 
3488 1876857, 938658, 469357, 234682, 117342, 58671, 29335, 14668, 7334, 3667, 
3489 1833, 917, 458, 229, 115, 57, 29, 14, 7, 4, 2, 1 };
3490
3491 @ Given integers |x| and |y|, not both zero, the |n_arg| function
3492 returns the |angle| whose tangent points in the direction $(x,y)$.
3493 This subroutine first determines the correct octant, then solves the
3494 problem for |0<=y<=x|, then converts the result appropriately to
3495 return an answer in the range |-one_eighty_deg<=@t$\theta$@><=one_eighty_deg|.
3496 (The answer is |+one_eighty_deg| if |y=0| and |x<0|, but an answer of
3497 |-one_eighty_deg| is possible if, for example, |y=-1| and $x=-2^{30}$.)
3498
3499 The octants are represented in a ``Gray code,'' since that turns out
3500 to be computationally simplest.
3501
3502 @d negate_x 1
3503 @d negate_y 2
3504 @d switch_x_and_y 4
3505 @d first_octant 1
3506 @d second_octant (first_octant+switch_x_and_y)
3507 @d third_octant (first_octant+switch_x_and_y+negate_x)
3508 @d fourth_octant (first_octant+negate_x)
3509 @d fifth_octant (first_octant+negate_x+negate_y)
3510 @d sixth_octant (first_octant+switch_x_and_y+negate_x+negate_y)
3511 @d seventh_octant (first_octant+switch_x_and_y+negate_y)
3512 @d eighth_octant (first_octant+negate_y)
3513
3514 @c 
3515 angle mp_n_arg (MP mp,integer x, integer y) {
3516   angle z; /* auxiliary register */
3517   integer t; /* temporary storage */
3518   small_number k; /* loop counter */
3519   int octant; /* octant code */
3520   if ( x>=0 ) {
3521     octant=first_octant;
3522   } else { 
3523     negate(x); octant=first_octant+negate_x;
3524   }
3525   if ( y<0 ) { 
3526     negate(y); octant=octant+negate_y;
3527   }
3528   if ( x<y ) { 
3529     t=y; y=x; x=t; octant=octant+switch_x_and_y;
3530   }
3531   if ( x==0 ) { 
3532     @<Handle undefined arg@>; 
3533   } else { 
3534     @<Set variable |z| to the arg of $(x,y)$@>;
3535     @<Return an appropriate answer based on |z| and |octant|@>;
3536   }
3537 }
3538
3539 @ @<Handle undefined arg@>=
3540
3541   print_err("angle(0,0) is taken as zero");
3542 @.angle(0,0)...zero@>
3543   help2("The `angle' between two identical points is undefined.")
3544        ("I'm zeroing this one. Proceed, with fingers crossed.");
3545   mp_error(mp); 
3546   return 0;
3547 }
3548
3549 @ @<Return an appropriate answer...@>=
3550 switch (octant) {
3551 case first_octant: return z;
3552 case second_octant: return (ninety_deg-z);
3553 case third_octant: return (ninety_deg+z);
3554 case fourth_octant: return (one_eighty_deg-z);
3555 case fifth_octant: return (z-one_eighty_deg);
3556 case sixth_octant: return (-z-ninety_deg);
3557 case seventh_octant: return (z-ninety_deg);
3558 case eighth_octant: return (-z);
3559 }; /* there are no other cases */
3560 return 0
3561
3562 @ At this point we have |x>=y>=0|, and |x>0|. The numbers are scaled up
3563 or down until $2^{28}\L x<2^{29}$, so that accurate fixed-point calculations
3564 will be made.
3565
3566 @<Set variable |z| to the arg...@>=
3567 while ( x>=fraction_two ) { 
3568   x=halfp(x); y=halfp(y);
3569 }
3570 z=0;
3571 if ( y>0 ) { 
3572  while ( x<fraction_one ) { 
3573     x+=x; y+=y; 
3574  };
3575  @<Increase |z| to the arg of $(x,y)$@>;
3576 }
3577
3578 @ During the calculations of this section, variables |x| and~|y|
3579 represent actual coordinates $(x,2^{-k}y)$. We will maintain the
3580 condition |x>=y|, so that the tangent will be at most $2^{-k}$.
3581 If $x<2y$, the tangent is greater than $2^{-k-1}$. The transformation
3582 $(a,b)\mapsto(a+b\tan\phi,b-a\tan\phi)$ replaces $(a,b)$ by
3583 coordinates whose angle has decreased by~$\phi$; in the special case
3584 $a=x$, $b=2^{-k}y$, and $\tan\phi=2^{-k-1}$, this operation reduces
3585 to the particularly simple iteration shown here. [Cf.~John E. Meggitt,
3586 @^Meggitt, John E.@>
3587 {\sl IBM Journal of Research and Development\/ \bf6} (1962), 210--226.]
3588
3589 The initial value of |x| will be multiplied by at most
3590 $(1+{1\over2})(1+{1\over8})(1+{1\over32})\cdots\approx 1.7584$; hence
3591 there is no chance of integer overflow.
3592
3593 @<Increase |z|...@>=
3594 k=0;
3595 do {  
3596   y+=y; incr(k);
3597   if ( y>x ){ 
3598     z=z+spec_atan[k]; t=x; x=x+(y / two_to_the(k+k)); y=y-t;
3599   };
3600 } while (k!=15);
3601 do {  
3602   y+=y; incr(k);
3603   if ( y>x ) { z=z+spec_atan[k]; y=y-x; };
3604 } while (k!=26)
3605
3606 @ Conversely, the |n_sin_cos| routine takes an |angle| and produces the sine
3607 and cosine of that angle. The results of this routine are
3608 stored in global integer variables |n_sin| and |n_cos|.
3609
3610 @<Glob...@>=
3611 fraction n_sin;fraction n_cos; /* results computed by |n_sin_cos| */
3612
3613 @ Given an integer |z| that is $2^{20}$ times an angle $\theta$ in degrees,
3614 the purpose of |n_sin_cos(z)| is to set
3615 |x=@t$r\cos\theta$@>| and |y=@t$r\sin\theta$@>| (approximately),
3616 for some rather large number~|r|. The maximum of |x| and |y|
3617 will be between $2^{28}$ and $2^{30}$, so that there will be hardly
3618 any loss of accuracy. Then |x| and~|y| are divided by~|r|.
3619
3620 @c 
3621 void mp_n_sin_cos (MP mp,angle z) { /* computes a multiple of the sine
3622                                        and cosine */ 
3623   small_number k; /* loop control variable */
3624   int q; /* specifies the quadrant */
3625   fraction r; /* magnitude of |(x,y)| */
3626   integer x,y,t; /* temporary registers */
3627   while ( z<0 ) z=z+three_sixty_deg;
3628   z=z % three_sixty_deg; /* now |0<=z<three_sixty_deg| */
3629   q=z / forty_five_deg; z=z % forty_five_deg;
3630   x=fraction_one; y=x;
3631   if ( ! odd(q) ) z=forty_five_deg-z;
3632   @<Subtract angle |z| from |(x,y)|@>;
3633   @<Convert |(x,y)| to the octant determined by~|q|@>;
3634   r=mp_pyth_add(mp, x,y); 
3635   mp->n_cos=mp_make_fraction(mp, x,r); 
3636   mp->n_sin=mp_make_fraction(mp, y,r);
3637 }
3638
3639 @ In this case the octants are numbered sequentially.
3640
3641 @<Convert |(x,...@>=
3642 switch (q) {
3643 case 0: break;
3644 case 1: t=x; x=y; y=t; break;
3645 case 2: t=x; x=-y; y=t; break;
3646 case 3: negate(x); break;
3647 case 4: negate(x); negate(y); break;
3648 case 5: t=x; x=-y; y=-t; break;
3649 case 6: t=x; x=y; y=-t; break;
3650 case 7: negate(y); break;
3651 } /* there are no other cases */
3652
3653 @ The main iteration of |n_sin_cos| is similar to that of |n_arg| but
3654 applied in reverse. The values of |spec_atan[k]| decrease slowly enough
3655 that this loop is guaranteed to terminate before the (nonexistent) value
3656 |spec_atan[27]| would be required.
3657
3658 @<Subtract angle |z|...@>=
3659 k=1;
3660 while ( z>0 ){ 
3661   if ( z>=spec_atan[k] ) { 
3662     z=z-spec_atan[k]; t=x;
3663     x=t+y / two_to_the(k);
3664     y=y-t / two_to_the(k);
3665   }
3666   incr(k);
3667 }
3668 if ( y<0 ) y=0 /* this precaution may never be needed */
3669
3670 @ And now let's complete our collection of numeric utility routines
3671 by considering random number generation.
3672 \MP\ generates pseudo-random numbers with the additive scheme recommended
3673 in Section 3.6 of {\sl The Art of Computer Programming}; however, the
3674 results are random fractions between 0 and |fraction_one-1|, inclusive.
3675
3676 There's an auxiliary array |randoms| that contains 55 pseudo-random
3677 fractions. Using the recurrence $x_n=(x_{n-55}-x_{n-31})\bmod 2^{28}$,
3678 we generate batches of 55 new $x_n$'s at a time by calling |new_randoms|.
3679 The global variable |j_random| tells which element has most recently
3680 been consumed.
3681 The global variable |random_seed| was introduced in version 0.9,
3682 for the sole reason of stressing the fact that the initial value of the
3683 random seed is system-dependant. The initialization code below will initialize
3684 this variable to |(internal[mp_time] div unity)+internal[mp_day]|, but this 
3685 is not good enough on modern fast machines that are capable of running
3686 multiple MetaPost processes within the same second.
3687 @^system dependencies@>
3688
3689 @<Glob...@>=
3690 fraction randoms[55]; /* the last 55 random values generated */
3691 int j_random; /* the number of unused |randoms| */
3692 scaled random_seed; /* the default random seed */
3693
3694 @ @<Option variables@>=
3695 int random_seed;
3696
3697 @ @<Allocate or initialize ...@>=
3698 mp->random_seed = (scaled)opt->random_seed;
3699
3700 @ To consume a random fraction, the program below will say `|next_random|'
3701 and then it will fetch |randoms[j_random]|.
3702
3703 @d next_random { if ( mp->j_random==0 ) mp_new_randoms(mp);
3704   else decr(mp->j_random); }
3705
3706 @c 
3707 void mp_new_randoms (MP mp) {
3708   int k; /* index into |randoms| */
3709   fraction x; /* accumulator */
3710   for (k=0;k<=23;k++) { 
3711    x=mp->randoms[k]-mp->randoms[k+31];
3712     if ( x<0 ) x=x+fraction_one;
3713     mp->randoms[k]=x;
3714   }
3715   for (k=24;k<= 54;k++){ 
3716     x=mp->randoms[k]-mp->randoms[k-24];
3717     if ( x<0 ) x=x+fraction_one;
3718     mp->randoms[k]=x;
3719   }
3720   mp->j_random=54;
3721 }
3722
3723 @ @<Declarations@>=
3724 void mp_init_randoms (MP mp,scaled seed);
3725
3726 @ To initialize the |randoms| table, we call the following routine.
3727
3728 @c 
3729 void mp_init_randoms (MP mp,scaled seed) {
3730   fraction j,jj,k; /* more or less random integers */
3731   int i; /* index into |randoms| */
3732   j=abs(seed);
3733   while ( j>=fraction_one ) j=halfp(j);
3734   k=1;
3735   for (i=0;i<=54;i++ ){ 
3736     jj=k; k=j-k; j=jj;
3737     if ( k<0 ) k=k+fraction_one;
3738     mp->randoms[(i*21)% 55]=j;
3739   }
3740   mp_new_randoms(mp); 
3741   mp_new_randoms(mp); 
3742   mp_new_randoms(mp); /* ``warm up'' the array */
3743 }
3744
3745 @ To produce a uniform random number in the range |0<=u<x| or |0>=u>x|
3746 or |0=u=x|, given a |scaled| value~|x|, we proceed as shown here.
3747
3748 Note that the call of |take_fraction| will produce the values 0 and~|x|
3749 with about half the probability that it will produce any other particular
3750 values between 0 and~|x|, because it rounds its answers.
3751
3752 @c 
3753 scaled mp_unif_rand (MP mp,scaled x) {
3754   scaled y; /* trial value */
3755   next_random; y=mp_take_fraction(mp, abs(x),mp->randoms[mp->j_random]);
3756   if ( y==abs(x) ) return 0;
3757   else if ( x>0 ) return y;
3758   else return (-y);
3759 }
3760
3761 @ Finally, a normal deviate with mean zero and unit standard deviation
3762 can readily be obtained with the ratio method (Algorithm 3.4.1R in
3763 {\sl The Art of Computer Programming\/}).
3764
3765 @c 
3766 scaled mp_norm_rand (MP mp) {
3767   integer x,u,l; /* what the book would call $2^{16}X$, $2^{28}U$, and $-2^{24}\ln U$ */
3768   do { 
3769     do {  
3770       next_random;
3771       x=mp_take_fraction(mp, 112429,mp->randoms[mp->j_random]-fraction_half);
3772       /* $2^{16}\sqrt{8/e}\approx 112428.82793$ */
3773       next_random; u=mp->randoms[mp->j_random];
3774     } while (abs(x)>=u);
3775     x=mp_make_fraction(mp, x,u);
3776     l=139548960-mp_m_log(mp, u); /* $2^{24}\cdot12\ln2\approx139548959.6165$ */
3777   } while (mp_ab_vs_cd(mp, 1024,l,x,x)<0);
3778   return x;
3779 }
3780
3781 @* \[9] Packed data.
3782 In order to make efficient use of storage space, \MP\ bases its major data
3783 structures on a |memory_word|, which contains either a (signed) integer,
3784 possibly scaled, or a small number of fields that are one half or one
3785 quarter of the size used for storing integers.
3786
3787 If |x| is a variable of type |memory_word|, it contains up to four
3788 fields that can be referred to as follows:
3789 $$\vbox{\halign{\hfil#&#\hfil&#\hfil\cr
3790 |x|&.|int|&(an |integer|)\cr
3791 |x|&.|sc|\qquad&(a |scaled| integer)\cr
3792 |x.hh.lh|, |x.hh|&.|rh|&(two halfword fields)\cr
3793 |x.hh.b0|, |x.hh.b1|, |x.hh|&.|rh|&(two quarterword fields, one halfword
3794   field)\cr
3795 |x.qqqq.b0|, |x.qqqq.b1|, |x.qqqq|&.|b2|, |x.qqqq.b3|\hskip-100pt
3796   &\qquad\qquad\qquad(four quarterword fields)\cr}}$$
3797 This is somewhat cumbersome to write, and not very readable either, but
3798 macros will be used to make the notation shorter and more transparent.
3799 The code below gives a formal definition of |memory_word| and
3800 its subsidiary types, using packed variant records. \MP\ makes no
3801 assumptions about the relative positions of the fields within a word.
3802
3803 @d max_quarterword 0x3FFF /* largest allowable value in a |quarterword| */
3804 @d max_halfword 0xFFFFFFF /* largest allowable value in a |halfword| */
3805
3806 @ Here are the inequalities that the quarterword and halfword values
3807 must satisfy (or rather, the inequalities that they mustn't satisfy):
3808
3809 @<Check the ``constant''...@>=
3810 if (mp->ini_version) {
3811   if ( mp->mem_max!=mp->mem_top ) mp->bad=8;
3812 } else {
3813   if ( mp->mem_max<mp->mem_top ) mp->bad=8;
3814 }
3815 if ( max_quarterword<255 ) mp->bad=9;
3816 if ( max_halfword<65535 ) mp->bad=10;
3817 if ( max_quarterword>max_halfword ) mp->bad=11;
3818 if ( mp->mem_max>=max_halfword ) mp->bad=12;
3819 if ( mp->max_strings>max_halfword ) mp->bad=13;
3820
3821 @ The macros |qi| and |qo| are used for input to and output 
3822 from quarterwords. These are legacy macros.
3823 @^system dependencies@>
3824
3825 @d qo(A) (A) /* to read eight bits from a quarterword */
3826 @d qi(A) (A) /* to store eight bits in a quarterword */
3827
3828 @ The reader should study the following definitions closely:
3829 @^system dependencies@>
3830
3831 @d sc cint /* |scaled| data is equivalent to |integer| */
3832
3833 @<Types...@>=
3834 typedef short quarterword; /* 1/4 of a word */
3835 typedef int halfword; /* 1/2 of a word */
3836 typedef union {
3837   struct {
3838     halfword RH, LH;
3839   } v;
3840   struct { /* Make B0,B1 overlap the most significant bytes of LH.  */
3841     halfword junk;
3842     quarterword B0, B1;
3843   } u;
3844 } two_halves;
3845 typedef struct {
3846   struct {
3847     quarterword B2, B3, B0, B1;
3848   } u;
3849 } four_quarters;
3850 typedef union {
3851   two_halves hh;
3852   integer cint;
3853   four_quarters qqqq;
3854 } memory_word;
3855 #define b0 u.B0
3856 #define b1 u.B1
3857 #define b2 u.B2
3858 #define b3 u.B3
3859 #define rh v.RH
3860 #define lh v.LH
3861
3862 @ When debugging, we may want to print a |memory_word| without knowing
3863 what type it is; so we print it in all modes.
3864 @^dirty \PASCAL@>@^debugging@>
3865
3866 @c 
3867 void mp_print_word (MP mp,memory_word w) {
3868   /* prints |w| in all ways */
3869   mp_print_int(mp, w.cint); mp_print_char(mp, ' ');
3870   mp_print_scaled(mp, w.sc); mp_print_char(mp, ' '); 
3871   mp_print_scaled(mp, w.sc / 010000); mp_print_ln(mp);
3872   mp_print_int(mp, w.hh.lh); mp_print_char(mp, '='); 
3873   mp_print_int(mp, w.hh.b0); mp_print_char(mp, ':');
3874   mp_print_int(mp, w.hh.b1); mp_print_char(mp, ';'); 
3875   mp_print_int(mp, w.hh.rh); mp_print_char(mp, ' ');
3876   mp_print_int(mp, w.qqqq.b0); mp_print_char(mp, ':'); 
3877   mp_print_int(mp, w.qqqq.b1); mp_print_char(mp, ':');
3878   mp_print_int(mp, w.qqqq.b2); mp_print_char(mp, ':'); 
3879   mp_print_int(mp, w.qqqq.b3);
3880 }
3881
3882
3883 @* \[10] Dynamic memory allocation.
3884
3885 The \MP\ system does nearly all of its own memory allocation, so that it
3886 can readily be transported into environments that do not have automatic
3887 facilities for strings, garbage collection, etc., and so that it can be in
3888 control of what error messages the user receives. The dynamic storage
3889 requirements of \MP\ are handled by providing a large array |mem| in
3890 which consecutive blocks of words are used as nodes by the \MP\ routines.
3891
3892 Pointer variables are indices into this array, or into another array
3893 called |eqtb| that will be explained later. A pointer variable might
3894 also be a special flag that lies outside the bounds of |mem|, so we
3895 allow pointers to assume any |halfword| value. The minimum memory
3896 index represents a null pointer.
3897
3898 @d null 0 /* the null pointer */
3899 @d mp_void (null+1) /* a null pointer different from |null| */
3900
3901
3902 @<Types...@>=
3903 typedef halfword pointer; /* a flag or a location in |mem| or |eqtb| */
3904
3905 @ The |mem| array is divided into two regions that are allocated separately,
3906 but the dividing line between these two regions is not fixed; they grow
3907 together until finding their ``natural'' size in a particular job.
3908 Locations less than or equal to |lo_mem_max| are used for storing
3909 variable-length records consisting of two or more words each. This region
3910 is maintained using an algorithm similar to the one described in exercise
3911 2.5--19 of {\sl The Art of Computer Programming}. However, no size field
3912 appears in the allocated nodes; the program is responsible for knowing the
3913 relevant size when a node is freed. Locations greater than or equal to
3914 |hi_mem_min| are used for storing one-word records; a conventional
3915 \.{AVAIL} stack is used for allocation in this region.
3916
3917 Locations of |mem| between |0| and |mem_top| may be dumped as part
3918 of preloaded format files, by the \.{INIMP} preprocessor.
3919 @.INIMP@>
3920 Production versions of \MP\ may extend the memory at the top end in order to
3921 provide more space; these locations, between |mem_top| and |mem_max|,
3922 are always used for single-word nodes.
3923
3924 The key pointers that govern |mem| allocation have a prescribed order:
3925 $$\hbox{|null=0<lo_mem_max<hi_mem_min<mem_top<=mem_end<=mem_max|.}$$
3926
3927 @<Glob...@>=
3928 memory_word *mem; /* the big dynamic storage area */
3929 pointer lo_mem_max; /* the largest location of variable-size memory in use */
3930 pointer hi_mem_min; /* the smallest location of one-word memory in use */
3931
3932
3933
3934 @d xfree(A) do { mp_xfree(A); A=NULL; } while (0)
3935 @d xrealloc(P,A,B) mp_xrealloc(mp,P,A,B)
3936 @d xmalloc(A,B)  mp_xmalloc(mp,A,B)
3937 @d xstrdup(A)  mp_xstrdup(mp,A)
3938 @d XREALLOC(a,b,c) a = xrealloc(a,(b+1),sizeof(c));
3939
3940 @<Declare helpers@>=
3941 void mp_xfree (void *x);
3942 void *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) ;
3943 void *mp_xmalloc (MP mp, size_t nmem, size_t size) ;
3944 char *mp_xstrdup(MP mp, const char *s);
3945
3946 @ The |max_size_test| guards against overflow, on the assumption that
3947 |size_t| is at least 31bits wide.
3948
3949 @d max_size_test 0x7FFFFFFF
3950
3951 @c
3952 void mp_xfree (void *x) {
3953   if (x!=NULL) free(x);
3954 }
3955 void  *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) {
3956   void *w ; 
3957   if ((max_size_test/size)<nmem) {
3958     do_fprintf(mp->err_out,"Memory size overflow!\n");
3959     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3960   }
3961   w = realloc (p,(nmem*size));
3962   if (w==NULL) {
3963     do_fprintf(mp->err_out,"Out of memory!\n");
3964     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3965   }
3966   return w;
3967 }
3968 void  *mp_xmalloc (MP mp, size_t nmem, size_t size) {
3969   void *w;
3970   if ((max_size_test/size)<nmem) {
3971     do_fprintf(mp->err_out,"Memory size overflow!\n");
3972     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3973   }
3974   w = malloc (nmem*size);
3975   if (w==NULL) {
3976     do_fprintf(mp->err_out,"Out of memory!\n");
3977     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3978   }
3979   return w;
3980 }
3981 char *mp_xstrdup(MP mp, const char *s) {
3982   char *w; 
3983   if (s==NULL)
3984     return NULL;
3985   w = strdup(s);
3986   if (w==NULL) {
3987     do_fprintf(mp->err_out,"Out of memory!\n");
3988     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3989   }
3990   return w;
3991 }
3992
3993
3994
3995 @<Allocate or initialize ...@>=
3996 mp->mem = xmalloc ((mp->mem_max+1),sizeof (memory_word));
3997 memset(mp->mem,0,(mp->mem_max+1)*sizeof (memory_word));
3998
3999 @ @<Dealloc variables@>=
4000 xfree(mp->mem);
4001
4002 @ Users who wish to study the memory requirements of particular applications can
4003 can use optional special features that keep track of current and
4004 maximum memory usage. When code between the delimiters |stat| $\ldots$
4005 |tats| is not ``commented out,'' \MP\ will run a bit slower but it will
4006 report these statistics when |mp_tracing_stats| is positive.
4007
4008 @<Glob...@>=
4009 integer var_used; integer dyn_used; /* how much memory is in use */
4010
4011 @ Let's consider the one-word memory region first, since it's the
4012 simplest. The pointer variable |mem_end| holds the highest-numbered location
4013 of |mem| that has ever been used. The free locations of |mem| that
4014 occur between |hi_mem_min| and |mem_end|, inclusive, are of type
4015 |two_halves|, and we write |info(p)| and |link(p)| for the |lh|
4016 and |rh| fields of |mem[p]| when it is of this type. The single-word
4017 free locations form a linked list
4018 $$|avail|,\;\hbox{|link(avail)|},\;\hbox{|link(link(avail))|},\;\ldots$$
4019 terminated by |null|.
4020
4021 @d link(A)   mp->mem[(A)].hh.rh /* the |link| field of a memory word */
4022 @d info(A)   mp->mem[(A)].hh.lh /* the |info| field of a memory word */
4023
4024 @<Glob...@>=
4025 pointer avail; /* head of the list of available one-word nodes */
4026 pointer mem_end; /* the last one-word node used in |mem| */
4027
4028 @ If one-word memory is exhausted, it might mean that the user has forgotten
4029 a token like `\&{enddef}' or `\&{endfor}'. We will define some procedures
4030 later that try to help pinpoint the trouble.
4031
4032 @c 
4033 @<Declare the procedure called |show_token_list|@>;
4034 @<Declare the procedure called |runaway|@>
4035
4036 @ The function |get_avail| returns a pointer to a new one-word node whose
4037 |link| field is null. However, \MP\ will halt if there is no more room left.
4038 @^inner loop@>
4039
4040 @c 
4041 pointer mp_get_avail (MP mp) { /* single-word node allocation */
4042   pointer p; /* the new node being got */
4043   p=mp->avail; /* get top location in the |avail| stack */
4044   if ( p!=null ) {
4045     mp->avail=link(mp->avail); /* and pop it off */
4046   } else if ( mp->mem_end<mp->mem_max ) { /* or go into virgin territory */
4047     incr(mp->mem_end); p=mp->mem_end;
4048   } else { 
4049     decr(mp->hi_mem_min); p=mp->hi_mem_min;
4050     if ( mp->hi_mem_min<=mp->lo_mem_max ) { 
4051       mp_runaway(mp); /* if memory is exhausted, display possible runaway text */
4052       mp_overflow(mp, "main memory size",mp->mem_max);
4053       /* quit; all one-word nodes are busy */
4054 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
4055     }
4056   }
4057   link(p)=null; /* provide an oft-desired initialization of the new node */
4058   incr(mp->dyn_used);/* maintain statistics */
4059   return p;
4060 };
4061
4062 @ Conversely, a one-word node is recycled by calling |free_avail|.
4063
4064 @d free_avail(A)  /* single-word node liberation */
4065   { link((A))=mp->avail; mp->avail=(A); decr(mp->dyn_used);  }
4066
4067 @ There's also a |fast_get_avail| routine, which saves the procedure-call
4068 overhead at the expense of extra programming. This macro is used in
4069 the places that would otherwise account for the most calls of |get_avail|.
4070 @^inner loop@>
4071
4072 @d fast_get_avail(A) { 
4073   (A)=mp->avail; /* avoid |get_avail| if possible, to save time */
4074   if ( (A)==null ) { (A)=mp_get_avail(mp); } 
4075   else { mp->avail=link((A)); link((A))=null;  incr(mp->dyn_used); }
4076   }
4077
4078 @ The available-space list that keeps track of the variable-size portion
4079 of |mem| is a nonempty, doubly-linked circular list of empty nodes,
4080 pointed to by the roving pointer |rover|.
4081
4082 Each empty node has size 2 or more; the first word contains the special
4083 value |max_halfword| in its |link| field and the size in its |info| field;
4084 the second word contains the two pointers for double linking.
4085
4086 Each nonempty node also has size 2 or more. Its first word is of type
4087 |two_halves|\kern-1pt, and its |link| field is never equal to |max_halfword|.
4088 Otherwise there is complete flexibility with respect to the contents
4089 of its other fields and its other words.
4090
4091 (We require |mem_max<max_halfword| because terrible things can happen
4092 when |max_halfword| appears in the |link| field of a nonempty node.)
4093
4094 @d empty_flag   max_halfword /* the |link| of an empty variable-size node */
4095 @d is_empty(A)   (link((A))==empty_flag) /* tests for empty node */
4096 @d node_size   info /* the size field in empty variable-size nodes */
4097 @d llink(A)   info((A)+1) /* left link in doubly-linked list of empty nodes */
4098 @d rlink(A)   link((A)+1) /* right link in doubly-linked list of empty nodes */
4099
4100 @<Glob...@>=
4101 pointer rover; /* points to some node in the list of empties */
4102
4103 @ A call to |get_node| with argument |s| returns a pointer to a new node
4104 of size~|s|, which must be 2~or more. The |link| field of the first word
4105 of this new node is set to null. An overflow stop occurs if no suitable
4106 space exists.
4107
4108 If |get_node| is called with $s=2^{30}$, it simply merges adjacent free
4109 areas and returns the value |max_halfword|.
4110
4111 @<Internal library declarations@>=
4112 pointer mp_get_node (MP mp,integer s) ;
4113
4114 @ @c 
4115 pointer mp_get_node (MP mp,integer s) { /* variable-size node allocation */
4116   pointer p; /* the node currently under inspection */
4117   pointer q;  /* the node physically after node |p| */
4118   integer r; /* the newly allocated node, or a candidate for this honor */
4119   integer t,tt; /* temporary registers */
4120 @^inner loop@>
4121  RESTART: 
4122   p=mp->rover; /* start at some free node in the ring */
4123   do {  
4124     @<Try to allocate within node |p| and its physical successors,
4125      and |goto found| if allocation was possible@>;
4126     if (rlink(p)==null || rlink(p)==p) {
4127       print_err("Free list garbled");
4128       help3("I found an entry in the list of free nodes that links")
4129        ("badly. I will try to ignore the broken link, but something")
4130        ("is seriously amiss. It is wise to warn the maintainers.")
4131           mp_error(mp);
4132       rlink(p)=mp->rover;
4133     }
4134         p=rlink(p); /* move to the next node in the ring */
4135   } while (p!=mp->rover); /* repeat until the whole list has been traversed */
4136   if ( s==010000000000 ) { 
4137     return max_halfword;
4138   };
4139   if ( mp->lo_mem_max+2<mp->hi_mem_min ) {
4140     if ( mp->lo_mem_max+2<=max_halfword ) {
4141       @<Grow more variable-size memory and |goto restart|@>;
4142     }
4143   }
4144   mp_overflow(mp, "main memory size",mp->mem_max);
4145   /* sorry, nothing satisfactory is left */
4146 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
4147 FOUND: 
4148   link(r)=null; /* this node is now nonempty */
4149   mp->var_used+=s; /* maintain usage statistics */
4150   return r;
4151 }
4152
4153 @ The lower part of |mem| grows by 1000 words at a time, unless
4154 we are very close to going under. When it grows, we simply link
4155 a new node into the available-space list. This method of controlled
4156 growth helps to keep the |mem| usage consecutive when \MP\ is
4157 implemented on ``virtual memory'' systems.
4158 @^virtual memory@>
4159
4160 @<Grow more variable-size memory and |goto restart|@>=
4161
4162   if ( mp->hi_mem_min-mp->lo_mem_max>=1998 ) {
4163     t=mp->lo_mem_max+1000;
4164   } else {
4165     t=mp->lo_mem_max+1+(mp->hi_mem_min-mp->lo_mem_max) / 2; 
4166     /* |lo_mem_max+2<=t<hi_mem_min| */
4167   }
4168   if ( t>max_halfword ) t=max_halfword;
4169   p=llink(mp->rover); q=mp->lo_mem_max; rlink(p)=q; llink(mp->rover)=q;
4170   rlink(q)=mp->rover; llink(q)=p; link(q)=empty_flag; 
4171   node_size(q)=t-mp->lo_mem_max;
4172   mp->lo_mem_max=t; link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4173   mp->rover=q; 
4174   goto RESTART;
4175 }
4176
4177 @ @<Try to allocate...@>=
4178 q=p+node_size(p); /* find the physical successor */
4179 while ( is_empty(q) ) { /* merge node |p| with node |q| */
4180   t=rlink(q); tt=llink(q);
4181 @^inner loop@>
4182   if ( q==mp->rover ) mp->rover=t;
4183   llink(t)=tt; rlink(tt)=t;
4184   q=q+node_size(q);
4185 }
4186 r=q-s;
4187 if ( r>p+1 ) {
4188   @<Allocate from the top of node |p| and |goto found|@>;
4189 }
4190 if ( r==p ) { 
4191   if ( rlink(p)!=p ) {
4192     @<Allocate entire node |p| and |goto found|@>;
4193   }
4194 }
4195 node_size(p)=q-p /* reset the size in case it grew */
4196
4197 @ @<Allocate from the top...@>=
4198
4199   node_size(p)=r-p; /* store the remaining size */
4200   mp->rover=p; /* start searching here next time */
4201   goto FOUND;
4202 }
4203
4204 @ Here we delete node |p| from the ring, and let |rover| rove around.
4205
4206 @<Allocate entire...@>=
4207
4208   mp->rover=rlink(p); t=llink(p);
4209   llink(mp->rover)=t; rlink(t)=mp->rover;
4210   goto FOUND;
4211 }
4212
4213 @ Conversely, when some variable-size node |p| of size |s| is no longer needed,
4214 the operation |free_node(p,s)| will make its words available, by inserting
4215 |p| as a new empty node just before where |rover| now points.
4216
4217 @<Internal library declarations@>=
4218 void mp_free_node (MP mp, pointer p, halfword s) ;
4219
4220 @ @c 
4221 void mp_free_node (MP mp, pointer p, halfword s) { /* variable-size node
4222   liberation */
4223   pointer q; /* |llink(rover)| */
4224   node_size(p)=s; link(p)=empty_flag;
4225 @^inner loop@>
4226   q=llink(mp->rover); llink(p)=q; rlink(p)=mp->rover; /* set both links */
4227   llink(mp->rover)=p; rlink(q)=p; /* insert |p| into the ring */
4228   mp->var_used-=s; /* maintain statistics */
4229 }
4230
4231 @ Just before \.{INIMP} writes out the memory, it sorts the doubly linked
4232 available space list. The list is probably very short at such times, so a
4233 simple insertion sort is used. The smallest available location will be
4234 pointed to by |rover|, the next-smallest by |rlink(rover)|, etc.
4235
4236 @c 
4237 void mp_sort_avail (MP mp) { /* sorts the available variable-size nodes
4238   by location */
4239   pointer p,q,r; /* indices into |mem| */
4240   pointer old_rover; /* initial |rover| setting */
4241   p=mp_get_node(mp, 010000000000); /* merge adjacent free areas */
4242   p=rlink(mp->rover); rlink(mp->rover)=max_halfword; old_rover=mp->rover;
4243   while ( p!=old_rover ) {
4244     @<Sort |p| into the list starting at |rover|
4245      and advance |p| to |rlink(p)|@>;
4246   }
4247   p=mp->rover;
4248   while ( rlink(p)!=max_halfword ) { 
4249     llink(rlink(p))=p; p=rlink(p);
4250   };
4251   rlink(p)=mp->rover; llink(mp->rover)=p;
4252 }
4253
4254 @ The following |while| loop is guaranteed to
4255 terminate, since the list that starts at
4256 |rover| ends with |max_halfword| during the sorting procedure.
4257
4258 @<Sort |p|...@>=
4259 if ( p<mp->rover ) { 
4260   q=p; p=rlink(q); rlink(q)=mp->rover; mp->rover=q;
4261 } else  { 
4262   q=mp->rover;
4263   while ( rlink(q)<p ) q=rlink(q);
4264   r=rlink(p); rlink(p)=rlink(q); rlink(q)=p; p=r;
4265 }
4266
4267 @* \[11] Memory layout.
4268 Some areas of |mem| are dedicated to fixed usage, since static allocation is
4269 more efficient than dynamic allocation when we can get away with it. For
4270 example, locations |0| to |1| are always used to store a
4271 two-word dummy token whose second word is zero.
4272 The following macro definitions accomplish the static allocation by giving
4273 symbolic names to the fixed positions. Static variable-size nodes appear
4274 in locations |0| through |lo_mem_stat_max|, and static single-word nodes
4275 appear in locations |hi_mem_stat_min| through |mem_top|, inclusive.
4276
4277 @d null_dash (2) /* the first two words are reserved for a null value */
4278 @d dep_head (null_dash+3) /* we will define |dash_node_size=3| */
4279 @d zero_val (dep_head+2) /* two words for a permanently zero value */
4280 @d temp_val (zero_val+2) /* two words for a temporary value node */
4281 @d end_attr temp_val /* we use |end_attr+2| only */
4282 @d inf_val (end_attr+2) /* and |inf_val+1| only */
4283 @d test_pen (inf_val+2)
4284   /* nine words for a pen used when testing the turning number */
4285 @d bad_vardef (test_pen+9) /* two words for \&{vardef} error recovery */
4286 @d lo_mem_stat_max (bad_vardef+1)  /* largest statically
4287   allocated word in the variable-size |mem| */
4288 @#
4289 @d sentinel mp->mem_top /* end of sorted lists */
4290 @d temp_head (mp->mem_top-1) /* head of a temporary list of some kind */
4291 @d hold_head (mp->mem_top-2) /* head of a temporary list of another kind */
4292 @d spec_head (mp->mem_top-3) /* head of a list of unprocessed \&{special} items */
4293 @d hi_mem_stat_min (mp->mem_top-3) /* smallest statically allocated word in
4294   the one-word |mem| */
4295
4296 @ The following code gets the dynamic part of |mem| off to a good start,
4297 when \MP\ is initializing itself the slow way.
4298
4299 @<Initialize table entries (done by \.{INIMP} only)@>=
4300 @^data structure assumptions@>
4301 mp->rover=lo_mem_stat_max+1; /* initialize the dynamic memory */
4302 link(mp->rover)=empty_flag;
4303 node_size(mp->rover)=1000; /* which is a 1000-word available node */
4304 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
4305 mp->lo_mem_max=mp->rover+1000; 
4306 link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4307 for (k=hi_mem_stat_min;k<=(int)mp->mem_top;k++) {
4308   mp->mem[k]=mp->mem[mp->lo_mem_max]; /* clear list heads */
4309 }
4310 mp->avail=null; mp->mem_end=mp->mem_top;
4311 mp->hi_mem_min=hi_mem_stat_min; /* initialize the one-word memory */
4312 mp->var_used=lo_mem_stat_max+1; 
4313 mp->dyn_used=mp->mem_top+1-(hi_mem_stat_min);  /* initialize statistics */
4314 @<Initialize a pen at |test_pen| so that it fits in nine words@>;
4315
4316 @ The procedure |flush_list(p)| frees an entire linked list of one-word
4317 nodes that starts at a given position, until coming to |sentinel| or a
4318 pointer that is not in the one-word region. Another procedure,
4319 |flush_node_list|, frees an entire linked list of one-word and two-word
4320 nodes, until coming to a |null| pointer.
4321 @^inner loop@>
4322
4323 @c 
4324 void mp_flush_list (MP mp,pointer p) { /* makes list of single-word nodes  available */
4325   pointer q,r; /* list traversers */
4326   if ( p>=mp->hi_mem_min ) if ( p!=sentinel ) { 
4327     r=p;
4328     do {  
4329       q=r; r=link(r); 
4330       decr(mp->dyn_used);
4331       if ( r<mp->hi_mem_min ) break;
4332     } while (r!=sentinel);
4333   /* now |q| is the last node on the list */
4334     link(q)=mp->avail; mp->avail=p;
4335   }
4336 }
4337 @#
4338 void mp_flush_node_list (MP mp,pointer p) {
4339   pointer q; /* the node being recycled */
4340   while ( p!=null ){ 
4341     q=p; p=link(p);
4342     if ( q<mp->hi_mem_min ) 
4343       mp_free_node(mp, q,2);
4344     else 
4345       free_avail(q);
4346   }
4347 }
4348
4349 @ If \MP\ is extended improperly, the |mem| array might get screwed up.
4350 For example, some pointers might be wrong, or some ``dead'' nodes might not
4351 have been freed when the last reference to them disappeared. Procedures
4352 |check_mem| and |search_mem| are available to help diagnose such
4353 problems. These procedures make use of two arrays called |free| and
4354 |was_free| that are present only if \MP's debugging routines have
4355 been included. (You may want to decrease the size of |mem| while you
4356 @^debugging@>
4357 are debugging.)
4358
4359 Because |boolean|s are typedef-d as ints, it is better to use
4360 unsigned chars here.
4361
4362 @<Glob...@>=
4363 unsigned char *free; /* free cells */
4364 unsigned char *was_free; /* previously free cells */
4365 pointer was_mem_end; pointer was_lo_max; pointer was_hi_min;
4366   /* previous |mem_end|, |lo_mem_max|,and |hi_mem_min| */
4367 boolean panicking; /* do we want to check memory constantly? */
4368
4369 @ @<Allocate or initialize ...@>=
4370 mp->free = xmalloc ((mp->mem_max+1),sizeof (unsigned char));
4371 mp->was_free = xmalloc ((mp->mem_max+1), sizeof (unsigned char));
4372
4373 @ @<Dealloc variables@>=
4374 xfree(mp->free);
4375 xfree(mp->was_free);
4376
4377 @ @<Allocate or ...@>=
4378 mp->was_mem_end=0; /* indicate that everything was previously free */
4379 mp->was_lo_max=0; mp->was_hi_min=mp->mem_max;
4380 mp->panicking=false;
4381
4382 @ @<Declare |mp_reallocate| functions@>=
4383 void mp_reallocate_memory(MP mp, int l) ;
4384
4385 @ @c
4386 void mp_reallocate_memory(MP mp, int l) {
4387    XREALLOC(mp->free,     l, unsigned char);
4388    XREALLOC(mp->was_free, l, unsigned char);
4389    if (mp->mem) {
4390          int newarea = l-mp->mem_max;
4391      XREALLOC(mp->mem,      l, memory_word);
4392      memset (mp->mem+(mp->mem_max+1),0,sizeof(memory_word)*(newarea));
4393    } else {
4394      XREALLOC(mp->mem,      l, memory_word);
4395      memset(mp->mem,0,sizeof(memory_word)*(l+1));
4396    }
4397    mp->mem_max = l;
4398    if (mp->ini_version) 
4399      mp->mem_top = l;
4400 }
4401
4402
4403
4404 @ Procedure |check_mem| makes sure that the available space lists of
4405 |mem| are well formed, and it optionally prints out all locations
4406 that are reserved now but were free the last time this procedure was called.
4407
4408 @c 
4409 void mp_check_mem (MP mp,boolean print_locs ) {
4410   pointer p,q,r; /* current locations of interest in |mem| */
4411   boolean clobbered; /* is something amiss? */
4412   for (p=0;p<=mp->lo_mem_max;p++) {
4413     mp->free[p]=false; /* you can probably do this faster */
4414   }
4415   for (p=mp->hi_mem_min;p<= mp->mem_end;p++) {
4416     mp->free[p]=false; /* ditto */
4417   }
4418   @<Check single-word |avail| list@>;
4419   @<Check variable-size |avail| list@>;
4420   @<Check flags of unavailable nodes@>;
4421   @<Check the list of linear dependencies@>;
4422   if ( print_locs ) {
4423     @<Print newly busy locations@>;
4424   }
4425   memcpy(mp->was_free,mp->free, sizeof(char)*(mp->mem_end+1));
4426   mp->was_mem_end=mp->mem_end; 
4427   mp->was_lo_max=mp->lo_mem_max; 
4428   mp->was_hi_min=mp->hi_mem_min;
4429 }
4430
4431 @ @<Check single-word...@>=
4432 p=mp->avail; q=null; clobbered=false;
4433 while ( p!=null ) { 
4434   if ( (p>mp->mem_end)||(p<mp->hi_mem_min) ) clobbered=true;
4435   else if ( mp->free[p] ) clobbered=true;
4436   if ( clobbered ) { 
4437     mp_print_nl(mp, "AVAIL list clobbered at ");
4438 @.AVAIL list clobbered...@>
4439     mp_print_int(mp, q); break;
4440   }
4441   mp->free[p]=true; q=p; p=link(q);
4442 }
4443
4444 @ @<Check variable-size...@>=
4445 p=mp->rover; q=null; clobbered=false;
4446 do {  
4447   if ( (p>=mp->lo_mem_max)||(p<0) ) clobbered=true;
4448   else if ( (rlink(p)>=mp->lo_mem_max)||(rlink(p)<0) ) clobbered=true;
4449   else if (  !(is_empty(p))||(node_size(p)<2)||
4450    (p+node_size(p)>mp->lo_mem_max)|| (llink(rlink(p))!=p) ) clobbered=true;
4451   if ( clobbered ) { 
4452     mp_print_nl(mp, "Double-AVAIL list clobbered at ");
4453 @.Double-AVAIL list clobbered...@>
4454     mp_print_int(mp, q); break;
4455   }
4456   for (q=p;q<=p+node_size(p)-1;q++) { /* mark all locations free */
4457     if ( mp->free[q] ) { 
4458       mp_print_nl(mp, "Doubly free location at ");
4459 @.Doubly free location...@>
4460       mp_print_int(mp, q); break;
4461     }
4462     mp->free[q]=true;
4463   }
4464   q=p; p=rlink(p);
4465 } while (p!=mp->rover)
4466
4467
4468 @ @<Check flags...@>=
4469 p=0;
4470 while ( p<=mp->lo_mem_max ) { /* node |p| should not be empty */
4471   if ( is_empty(p) ) {
4472     mp_print_nl(mp, "Bad flag at "); mp_print_int(mp, p);
4473 @.Bad flag...@>
4474   }
4475   while ( (p<=mp->lo_mem_max) && ! mp->free[p] ) incr(p);
4476   while ( (p<=mp->lo_mem_max) && mp->free[p] ) incr(p);
4477 }
4478
4479 @ @<Print newly busy...@>=
4480
4481   @<Do intialization required before printing new busy locations@>;
4482   mp_print_nl(mp, "New busy locs:");
4483 @.New busy locs@>
4484   for (p=0;p<= mp->lo_mem_max;p++ ) {
4485     if ( ! mp->free[p] && ((p>mp->was_lo_max) || mp->was_free[p]) ) {
4486       @<Indicate that |p| is a new busy location@>;
4487     }
4488   }
4489   for (p=mp->hi_mem_min;p<=mp->mem_end;p++ ) {
4490     if ( ! mp->free[p] &&
4491         ((p<mp->was_hi_min) || (p>mp->was_mem_end) || mp->was_free[p]) ) {
4492       @<Indicate that |p| is a new busy location@>;
4493     }
4494   }
4495   @<Finish printing new busy locations@>;
4496 }
4497
4498 @ There might be many new busy locations so we are careful to print contiguous
4499 blocks compactly.  During this operation |q| is the last new busy location and
4500 |r| is the start of the block containing |q|.
4501
4502 @<Indicate that |p| is a new busy location@>=
4503
4504   if ( p>q+1 ) { 
4505     if ( q>r ) { 
4506       mp_print(mp, ".."); mp_print_int(mp, q);
4507     }
4508     mp_print_char(mp, ' '); mp_print_int(mp, p);
4509     r=p;
4510   }
4511   q=p;
4512 }
4513
4514 @ @<Do intialization required before printing new busy locations@>=
4515 q=mp->mem_max; r=mp->mem_max
4516
4517 @ @<Finish printing new busy locations@>=
4518 if ( q>r ) { 
4519   mp_print(mp, ".."); mp_print_int(mp, q);
4520 }
4521
4522 @ The |search_mem| procedure attempts to answer the question ``Who points
4523 to node~|p|?'' In doing so, it fetches |link| and |info| fields of |mem|
4524 that might not be of type |two_halves|. Strictly speaking, this is
4525 @^dirty \PASCAL@>
4526 undefined in \PASCAL, and it can lead to ``false drops'' (words that seem to
4527 point to |p| purely by coincidence). But for debugging purposes, we want
4528 to rule out the places that do {\sl not\/} point to |p|, so a few false
4529 drops are tolerable.
4530
4531 @c
4532 void mp_search_mem (MP mp, pointer p) { /* look for pointers to |p| */
4533   integer q; /* current position being searched */
4534   for (q=0;q<=mp->lo_mem_max;q++) { 
4535     if ( link(q)==p ){ 
4536       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4537     }
4538     if ( info(q)==p ) { 
4539       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4540     }
4541   }
4542   for (q=mp->hi_mem_min;q<=mp->mem_end;q++) {
4543     if ( link(q)==p ) {
4544       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4545     }
4546     if ( info(q)==p ) {
4547       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4548     }
4549   }
4550   @<Search |eqtb| for equivalents equal to |p|@>;
4551 }
4552
4553 @* \[12] The command codes.
4554 Before we can go much further, we need to define symbolic names for the internal
4555 code numbers that represent the various commands obeyed by \MP. These codes
4556 are somewhat arbitrary, but not completely so. For example,
4557 some codes have been made adjacent so that |case| statements in the
4558 program need not consider cases that are widely spaced, or so that |case|
4559 statements can be replaced by |if| statements. A command can begin an
4560 expression if and only if its code lies between |min_primary_command| and
4561 |max_primary_command|, inclusive. The first token of a statement that doesn't
4562 begin with an expression has a command code between |min_command| and
4563 |max_statement_command|, inclusive. Anything less than |min_command| is
4564 eliminated during macro expansions, and anything no more than |max_pre_command|
4565 is eliminated when expanding \TeX\ material.  Ranges such as
4566 |min_secondary_command..max_secondary_command| are used when parsing
4567 expressions, but the relative ordering within such a range is generally not
4568 critical.
4569
4570 The ordering of the highest-numbered commands
4571 (|comma<semicolon<end_group<stop|) is crucial for the parsing and
4572 error-recovery methods of this program as is the ordering |if_test<fi_or_else|
4573 for the smallest two commands.  The ordering is also important in the ranges
4574 |numeric_token..plus_or_minus| and |left_brace..ampersand|.
4575
4576 At any rate, here is the list, for future reference.
4577
4578 @d start_tex 1 /* begin \TeX\ material (\&{btex}, \&{verbatimtex}) */
4579 @d etex_marker 2 /* end \TeX\ material (\&{etex}) */
4580 @d mpx_break 3 /* stop reading an \.{MPX} file (\&{mpxbreak}) */
4581 @d max_pre_command mpx_break
4582 @d if_test 4 /* conditional text (\&{if}) */
4583 @d fi_or_else 5 /* delimiters for conditionals (\&{elseif}, \&{else}, \&{fi} */
4584 @d input 6 /* input a source file (\&{input}, \&{endinput}) */
4585 @d iteration 7 /* iterate (\&{for}, \&{forsuffixes}, \&{forever}, \&{endfor}) */
4586 @d repeat_loop 8 /* special command substituted for \&{endfor} */
4587 @d exit_test 9 /* premature exit from a loop (\&{exitif}) */
4588 @d relax 10 /* do nothing (\.{\char`\\}) */
4589 @d scan_tokens 11 /* put a string into the input buffer */
4590 @d expand_after 12 /* look ahead one token */
4591 @d defined_macro 13 /* a macro defined by the user */
4592 @d min_command (defined_macro+1)
4593 @d save_command 14 /* save a list of tokens (\&{save}) */
4594 @d interim_command 15 /* save an internal quantity (\&{interim}) */
4595 @d let_command 16 /* redefine a symbolic token (\&{let}) */
4596 @d new_internal 17 /* define a new internal quantity (\&{newinternal}) */
4597 @d macro_def 18 /* define a macro (\&{def}, \&{vardef}, etc.) */
4598 @d ship_out_command 19 /* output a character (\&{shipout}) */
4599 @d add_to_command 20 /* add to edges (\&{addto}) */
4600 @d bounds_command 21  /* add bounding path to edges (\&{setbounds}, \&{clip}) */
4601 @d tfm_command 22 /* command for font metric info (\&{ligtable}, etc.) */
4602 @d protection_command 23 /* set protection flag (\&{outer}, \&{inner}) */
4603 @d show_command 24 /* diagnostic output (\&{show}, \&{showvariable}, etc.) */
4604 @d mode_command 25 /* set interaction level (\&{batchmode}, etc.) */
4605 @d mp_random_seed 26 /* initialize random number generator (\&{randomseed}) */
4606 @d message_command 27 /* communicate to user (\&{message}, \&{errmessage}) */
4607 @d every_job_command 28 /* designate a starting token (\&{everyjob}) */
4608 @d delimiters 29 /* define a pair of delimiters (\&{delimiters}) */
4609 @d special_command 30 /* output special info (\&{special})
4610                        or font map info (\&{fontmapfile}, \&{fontmapline}) */
4611 @d write_command 31 /* write text to a file (\&{write}) */
4612 @d type_name 32 /* declare a type (\&{numeric}, \&{pair}, etc. */
4613 @d max_statement_command type_name
4614 @d min_primary_command type_name
4615 @d left_delimiter 33 /* the left delimiter of a matching pair */
4616 @d begin_group 34 /* beginning of a group (\&{begingroup}) */
4617 @d nullary 35 /* an operator without arguments (e.g., \&{normaldeviate}) */
4618 @d unary 36 /* an operator with one argument (e.g., \&{sqrt}) */
4619 @d str_op 37 /* convert a suffix to a string (\&{str}) */
4620 @d cycle 38 /* close a cyclic path (\&{cycle}) */
4621 @d primary_binary 39 /* binary operation taking `\&{of}' (e.g., \&{point}) */
4622 @d capsule_token 40 /* a value that has been put into a token list */
4623 @d string_token 41 /* a string constant (e.g., |"hello"|) */
4624 @d internal_quantity 42 /* internal numeric parameter (e.g., \&{pausing}) */
4625 @d min_suffix_token internal_quantity
4626 @d tag_token 43 /* a symbolic token without a primitive meaning */
4627 @d numeric_token 44 /* a numeric constant (e.g., \.{3.14159}) */
4628 @d max_suffix_token numeric_token
4629 @d plus_or_minus 45 /* either `\.+' or `\.-' */
4630 @d max_primary_command plus_or_minus /* should also be |numeric_token+1| */
4631 @d min_tertiary_command plus_or_minus
4632 @d tertiary_secondary_macro 46 /* a macro defined by \&{secondarydef} */
4633 @d tertiary_binary 47 /* an operator at the tertiary level (e.g., `\.{++}') */
4634 @d max_tertiary_command tertiary_binary
4635 @d left_brace 48 /* the operator `\.{\char`\{}' */
4636 @d min_expression_command left_brace
4637 @d path_join 49 /* the operator `\.{..}' */
4638 @d ampersand 50 /* the operator `\.\&' */
4639 @d expression_tertiary_macro 51 /* a macro defined by \&{tertiarydef} */
4640 @d expression_binary 52 /* an operator at the expression level (e.g., `\.<') */
4641 @d equals 53 /* the operator `\.=' */
4642 @d max_expression_command equals
4643 @d and_command 54 /* the operator `\&{and}' */
4644 @d min_secondary_command and_command
4645 @d secondary_primary_macro 55 /* a macro defined by \&{primarydef} */
4646 @d slash 56 /* the operator `\./' */
4647 @d secondary_binary 57 /* an operator at the binary level (e.g., \&{shifted}) */
4648 @d max_secondary_command secondary_binary
4649 @d param_type 58 /* type of parameter (\&{primary}, \&{expr}, \&{suffix}, etc.) */
4650 @d controls 59 /* specify control points explicitly (\&{controls}) */
4651 @d tension 60 /* specify tension between knots (\&{tension}) */
4652 @d at_least 61 /* bounded tension value (\&{atleast}) */
4653 @d curl_command 62 /* specify curl at an end knot (\&{curl}) */
4654 @d macro_special 63 /* special macro operators (\&{quote}, \.{\#\AT!}, etc.) */
4655 @d right_delimiter 64 /* the right delimiter of a matching pair */
4656 @d left_bracket 65 /* the operator `\.[' */
4657 @d right_bracket 66 /* the operator `\.]' */
4658 @d right_brace 67 /* the operator `\.{\char`\}}' */
4659 @d with_option 68 /* option for filling (\&{withpen}, \&{withweight}, etc.) */
4660 @d thing_to_add 69
4661   /* variant of \&{addto} (\&{contour}, \&{doublepath}, \&{also}) */
4662 @d of_token 70 /* the operator `\&{of}' */
4663 @d to_token 71 /* the operator `\&{to}' */
4664 @d step_token 72 /* the operator `\&{step}' */
4665 @d until_token 73 /* the operator `\&{until}' */
4666 @d within_token 74 /* the operator `\&{within}' */
4667 @d lig_kern_token 75
4668   /* the operators `\&{kern}' and `\.{=:}' and `\.{=:\char'174}, etc. */
4669 @d assignment 76 /* the operator `\.{:=}' */
4670 @d skip_to 77 /* the operation `\&{skipto}' */
4671 @d bchar_label 78 /* the operator `\.{\char'174\char'174:}' */
4672 @d double_colon 79 /* the operator `\.{::}' */
4673 @d colon 80 /* the operator `\.:' */
4674 @#
4675 @d comma 81 /* the operator `\.,', must be |colon+1| */
4676 @d end_of_statement (mp->cur_cmd>comma)
4677 @d semicolon 82 /* the operator `\.;', must be |comma+1| */
4678 @d end_group 83 /* end a group (\&{endgroup}), must be |semicolon+1| */
4679 @d stop 84 /* end a job (\&{end}, \&{dump}), must be |end_group+1| */
4680 @d max_command_code stop
4681 @d outer_tag (max_command_code+1) /* protection code added to command code */
4682
4683 @<Types...@>=
4684 typedef int command_code;
4685
4686 @ Variables and capsules in \MP\ have a variety of ``types,''
4687 distinguished by the code numbers defined here. These numbers are also
4688 not completely arbitrary.  Things that get expanded must have types
4689 |>mp_independent|; a type remaining after expansion is numeric if and only if
4690 its code number is at least |numeric_type|; objects containing numeric
4691 parts must have types between |transform_type| and |pair_type|;
4692 all other types must be smaller than |transform_type|; and among the types
4693 that are not unknown or vacuous, the smallest two must be |boolean_type|
4694 and |string_type| in that order.
4695  
4696 @d undefined 0 /* no type has been declared */
4697 @d unknown_tag 1 /* this constant is added to certain type codes below */
4698 @d unknown_types mp_unknown_boolean: case mp_unknown_string:
4699   case mp_unknown_pen: case mp_unknown_picture: case mp_unknown_path
4700
4701 @<Types...@>=
4702 enum mp_variable_type {
4703 mp_vacuous=1, /* no expression was present */
4704 mp_boolean_type, /* \&{boolean} with a known value */
4705 mp_unknown_boolean,
4706 mp_string_type, /* \&{string} with a known value */
4707 mp_unknown_string,
4708 mp_pen_type, /* \&{pen} with a known value */
4709 mp_unknown_pen,
4710 mp_path_type, /* \&{path} with a known value */
4711 mp_unknown_path,
4712 mp_picture_type, /* \&{picture} with a known value */
4713 mp_unknown_picture,
4714 mp_transform_type, /* \&{transform} variable or capsule */
4715 mp_color_type, /* \&{color} variable or capsule */
4716 mp_cmykcolor_type, /* \&{cmykcolor} variable or capsule */
4717 mp_pair_type, /* \&{pair} variable or capsule */
4718 mp_numeric_type, /* variable that has been declared \&{numeric} but not used */
4719 mp_known, /* \&{numeric} with a known value */
4720 mp_dependent, /* a linear combination with |fraction| coefficients */
4721 mp_proto_dependent, /* a linear combination with |scaled| coefficients */
4722 mp_independent, /* \&{numeric} with unknown value */
4723 mp_token_list, /* variable name or suffix argument or text argument */
4724 mp_structured, /* variable with subscripts and attributes */
4725 mp_unsuffixed_macro, /* variable defined with \&{vardef} but no \.{\AT!\#} */
4726 mp_suffixed_macro /* variable defined with \&{vardef} and \.{\AT!\#} */
4727 } ;
4728
4729 @ @<Declarations@>=
4730 void mp_print_type (MP mp,small_number t) ;
4731
4732 @ @<Basic printing procedures@>=
4733 void mp_print_type (MP mp,small_number t) { 
4734   switch (t) {
4735   case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
4736   case mp_boolean_type:mp_print(mp, "boolean"); break;
4737   case mp_unknown_boolean:mp_print(mp, "unknown boolean"); break;
4738   case mp_string_type:mp_print(mp, "string"); break;
4739   case mp_unknown_string:mp_print(mp, "unknown string"); break;
4740   case mp_pen_type:mp_print(mp, "pen"); break;
4741   case mp_unknown_pen:mp_print(mp, "unknown pen"); break;
4742   case mp_path_type:mp_print(mp, "path"); break;
4743   case mp_unknown_path:mp_print(mp, "unknown path"); break;
4744   case mp_picture_type:mp_print(mp, "picture"); break;
4745   case mp_unknown_picture:mp_print(mp, "unknown picture"); break;
4746   case mp_transform_type:mp_print(mp, "transform"); break;
4747   case mp_color_type:mp_print(mp, "color"); break;
4748   case mp_cmykcolor_type:mp_print(mp, "cmykcolor"); break;
4749   case mp_pair_type:mp_print(mp, "pair"); break;
4750   case mp_known:mp_print(mp, "known numeric"); break;
4751   case mp_dependent:mp_print(mp, "dependent"); break;
4752   case mp_proto_dependent:mp_print(mp, "proto-dependent"); break;
4753   case mp_numeric_type:mp_print(mp, "numeric"); break;
4754   case mp_independent:mp_print(mp, "independent"); break;
4755   case mp_token_list:mp_print(mp, "token list"); break;
4756   case mp_structured:mp_print(mp, "mp_structured"); break;
4757   case mp_unsuffixed_macro:mp_print(mp, "unsuffixed macro"); break;
4758   case mp_suffixed_macro:mp_print(mp, "suffixed macro"); break;
4759   default: mp_print(mp, "undefined"); break;
4760   }
4761 }
4762
4763 @ Values inside \MP\ are stored in two-word nodes that have a |name_type|
4764 as well as a |type|. The possibilities for |name_type| are defined
4765 here; they will be explained in more detail later.
4766
4767 @<Types...@>=
4768 enum mp_name_type {
4769  mp_root=0, /* |name_type| at the top level of a variable */
4770  mp_saved_root, /* same, when the variable has been saved */
4771  mp_structured_root, /* |name_type| where a |mp_structured| branch occurs */
4772  mp_subscr, /* |name_type| in a subscript node */
4773  mp_attr, /* |name_type| in an attribute node */
4774  mp_x_part_sector, /* |name_type| in the \&{xpart} of a node */
4775  mp_y_part_sector, /* |name_type| in the \&{ypart} of a node */
4776  mp_xx_part_sector, /* |name_type| in the \&{xxpart} of a node */
4777  mp_xy_part_sector, /* |name_type| in the \&{xypart} of a node */
4778  mp_yx_part_sector, /* |name_type| in the \&{yxpart} of a node */
4779  mp_yy_part_sector, /* |name_type| in the \&{yypart} of a node */
4780  mp_red_part_sector, /* |name_type| in the \&{redpart} of a node */
4781  mp_green_part_sector, /* |name_type| in the \&{greenpart} of a node */
4782  mp_blue_part_sector, /* |name_type| in the \&{bluepart} of a node */
4783  mp_cyan_part_sector, /* |name_type| in the \&{redpart} of a node */
4784  mp_magenta_part_sector, /* |name_type| in the \&{greenpart} of a node */
4785  mp_yellow_part_sector, /* |name_type| in the \&{bluepart} of a node */
4786  mp_black_part_sector, /* |name_type| in the \&{greenpart} of a node */
4787  mp_grey_part_sector, /* |name_type| in the \&{bluepart} of a node */
4788  mp_capsule, /* |name_type| in stashed-away subexpressions */
4789  mp_token  /* |name_type| in a numeric token or string token */
4790 };
4791
4792 @ Primitive operations that produce values have a secondary identification
4793 code in addition to their command code; it's something like genera and species.
4794 For example, `\.*' has the command code |primary_binary|, and its
4795 secondary identification is |times|. The secondary codes start at 30 so that
4796 they don't overlap with the type codes; some type codes (e.g., |mp_string_type|)
4797 are used as operators as well as type identifications.  The relative values
4798 are not critical, except for |true_code..false_code|, |or_op..and_op|,
4799 and |filled_op..bounded_op|.  The restrictions are that
4800 |and_op-false_code=or_op-true_code|, that the ordering of
4801 |x_part...blue_part| must match that of |x_part_sector..mp_blue_part_sector|,
4802 and the ordering of |filled_op..bounded_op| must match that of the code
4803 values they test for.
4804
4805 @d true_code 30 /* operation code for \.{true} */
4806 @d false_code 31 /* operation code for \.{false} */
4807 @d null_picture_code 32 /* operation code for \.{nullpicture} */
4808 @d null_pen_code 33 /* operation code for \.{nullpen} */
4809 @d job_name_op 34 /* operation code for \.{jobname} */
4810 @d read_string_op 35 /* operation code for \.{readstring} */
4811 @d pen_circle 36 /* operation code for \.{pencircle} */
4812 @d normal_deviate 37 /* operation code for \.{normaldeviate} */
4813 @d read_from_op 38 /* operation code for \.{readfrom} */
4814 @d close_from_op 39 /* operation code for \.{closefrom} */
4815 @d odd_op 40 /* operation code for \.{odd} */
4816 @d known_op 41 /* operation code for \.{known} */
4817 @d unknown_op 42 /* operation code for \.{unknown} */
4818 @d not_op 43 /* operation code for \.{not} */
4819 @d decimal 44 /* operation code for \.{decimal} */
4820 @d reverse 45 /* operation code for \.{reverse} */
4821 @d make_path_op 46 /* operation code for \.{makepath} */
4822 @d make_pen_op 47 /* operation code for \.{makepen} */
4823 @d oct_op 48 /* operation code for \.{oct} */
4824 @d hex_op 49 /* operation code for \.{hex} */
4825 @d ASCII_op 50 /* operation code for \.{ASCII} */
4826 @d char_op 51 /* operation code for \.{char} */
4827 @d length_op 52 /* operation code for \.{length} */
4828 @d turning_op 53 /* operation code for \.{turningnumber} */
4829 @d color_model_part 54 /* operation code for \.{colormodel} */
4830 @d x_part 55 /* operation code for \.{xpart} */
4831 @d y_part 56 /* operation code for \.{ypart} */
4832 @d xx_part 57 /* operation code for \.{xxpart} */
4833 @d xy_part 58 /* operation code for \.{xypart} */
4834 @d yx_part 59 /* operation code for \.{yxpart} */
4835 @d yy_part 60 /* operation code for \.{yypart} */
4836 @d red_part 61 /* operation code for \.{redpart} */
4837 @d green_part 62 /* operation code for \.{greenpart} */
4838 @d blue_part 63 /* operation code for \.{bluepart} */
4839 @d cyan_part 64 /* operation code for \.{cyanpart} */
4840 @d magenta_part 65 /* operation code for \.{magentapart} */
4841 @d yellow_part 66 /* operation code for \.{yellowpart} */
4842 @d black_part 67 /* operation code for \.{blackpart} */
4843 @d grey_part 68 /* operation code for \.{greypart} */
4844 @d font_part 69 /* operation code for \.{fontpart} */
4845 @d text_part 70 /* operation code for \.{textpart} */
4846 @d path_part 71 /* operation code for \.{pathpart} */
4847 @d pen_part 72 /* operation code for \.{penpart} */
4848 @d dash_part 73 /* operation code for \.{dashpart} */
4849 @d sqrt_op 74 /* operation code for \.{sqrt} */
4850 @d m_exp_op 75 /* operation code for \.{mexp} */
4851 @d m_log_op 76 /* operation code for \.{mlog} */
4852 @d sin_d_op 77 /* operation code for \.{sind} */
4853 @d cos_d_op 78 /* operation code for \.{cosd} */
4854 @d floor_op 79 /* operation code for \.{floor} */
4855 @d uniform_deviate 80 /* operation code for \.{uniformdeviate} */
4856 @d char_exists_op 81 /* operation code for \.{charexists} */
4857 @d font_size 82 /* operation code for \.{fontsize} */
4858 @d ll_corner_op 83 /* operation code for \.{llcorner} */
4859 @d lr_corner_op 84 /* operation code for \.{lrcorner} */
4860 @d ul_corner_op 85 /* operation code for \.{ulcorner} */
4861 @d ur_corner_op 86 /* operation code for \.{urcorner} */
4862 @d arc_length 87 /* operation code for \.{arclength} */
4863 @d angle_op 88 /* operation code for \.{angle} */
4864 @d cycle_op 89 /* operation code for \.{cycle} */
4865 @d filled_op 90 /* operation code for \.{filled} */
4866 @d stroked_op 91 /* operation code for \.{stroked} */
4867 @d textual_op 92 /* operation code for \.{textual} */
4868 @d clipped_op 93 /* operation code for \.{clipped} */
4869 @d bounded_op 94 /* operation code for \.{bounded} */
4870 @d plus 95 /* operation code for \.+ */
4871 @d minus 96 /* operation code for \.- */
4872 @d times 97 /* operation code for \.* */
4873 @d over 98 /* operation code for \./ */
4874 @d pythag_add 99 /* operation code for \.{++} */
4875 @d pythag_sub 100 /* operation code for \.{+-+} */
4876 @d or_op 101 /* operation code for \.{or} */
4877 @d and_op 102 /* operation code for \.{and} */
4878 @d less_than 103 /* operation code for \.< */
4879 @d less_or_equal 104 /* operation code for \.{<=} */
4880 @d greater_than 105 /* operation code for \.> */
4881 @d greater_or_equal 106 /* operation code for \.{>=} */
4882 @d equal_to 107 /* operation code for \.= */
4883 @d unequal_to 108 /* operation code for \.{<>} */
4884 @d concatenate 109 /* operation code for \.\& */
4885 @d rotated_by 110 /* operation code for \.{rotated} */
4886 @d slanted_by 111 /* operation code for \.{slanted} */
4887 @d scaled_by 112 /* operation code for \.{scaled} */
4888 @d shifted_by 113 /* operation code for \.{shifted} */
4889 @d transformed_by 114 /* operation code for \.{transformed} */
4890 @d x_scaled 115 /* operation code for \.{xscaled} */
4891 @d y_scaled 116 /* operation code for \.{yscaled} */
4892 @d z_scaled 117 /* operation code for \.{zscaled} */
4893 @d in_font 118 /* operation code for \.{infont} */
4894 @d intersect 119 /* operation code for \.{intersectiontimes} */
4895 @d double_dot 120 /* operation code for improper \.{..} */
4896 @d substring_of 121 /* operation code for \.{substring} */
4897 @d min_of substring_of
4898 @d subpath_of 122 /* operation code for \.{subpath} */
4899 @d direction_time_of 123 /* operation code for \.{directiontime} */
4900 @d point_of 124 /* operation code for \.{point} */
4901 @d precontrol_of 125 /* operation code for \.{precontrol} */
4902 @d postcontrol_of 126 /* operation code for \.{postcontrol} */
4903 @d pen_offset_of 127 /* operation code for \.{penoffset} */
4904 @d arc_time_of 128 /* operation code for \.{arctime} */
4905 @d mp_version 129 /* operation code for \.{mpversion} */
4906 @d envelope_of 130 /* operation code for \{.envelope} */
4907
4908 @c void mp_print_op (MP mp,quarterword c) { 
4909   if (c<=mp_numeric_type ) {
4910     mp_print_type(mp, c);
4911   } else {
4912     switch (c) {
4913     case true_code:mp_print(mp, "true"); break;
4914     case false_code:mp_print(mp, "false"); break;
4915     case null_picture_code:mp_print(mp, "nullpicture"); break;
4916     case null_pen_code:mp_print(mp, "nullpen"); break;
4917     case job_name_op:mp_print(mp, "jobname"); break;
4918     case read_string_op:mp_print(mp, "readstring"); break;
4919     case pen_circle:mp_print(mp, "pencircle"); break;
4920     case normal_deviate:mp_print(mp, "normaldeviate"); break;
4921     case read_from_op:mp_print(mp, "readfrom"); break;
4922     case close_from_op:mp_print(mp, "closefrom"); break;
4923     case odd_op:mp_print(mp, "odd"); break;
4924     case known_op:mp_print(mp, "known"); break;
4925     case unknown_op:mp_print(mp, "unknown"); break;
4926     case not_op:mp_print(mp, "not"); break;
4927     case decimal:mp_print(mp, "decimal"); break;
4928     case reverse:mp_print(mp, "reverse"); break;
4929     case make_path_op:mp_print(mp, "makepath"); break;
4930     case make_pen_op:mp_print(mp, "makepen"); break;
4931     case oct_op:mp_print(mp, "oct"); break;
4932     case hex_op:mp_print(mp, "hex"); break;
4933     case ASCII_op:mp_print(mp, "ASCII"); break;
4934     case char_op:mp_print(mp, "char"); break;
4935     case length_op:mp_print(mp, "length"); break;
4936     case turning_op:mp_print(mp, "turningnumber"); break;
4937     case x_part:mp_print(mp, "xpart"); break;
4938     case y_part:mp_print(mp, "ypart"); break;
4939     case xx_part:mp_print(mp, "xxpart"); break;
4940     case xy_part:mp_print(mp, "xypart"); break;
4941     case yx_part:mp_print(mp, "yxpart"); break;
4942     case yy_part:mp_print(mp, "yypart"); break;
4943     case red_part:mp_print(mp, "redpart"); break;
4944     case green_part:mp_print(mp, "greenpart"); break;
4945     case blue_part:mp_print(mp, "bluepart"); break;
4946     case cyan_part:mp_print(mp, "cyanpart"); break;
4947     case magenta_part:mp_print(mp, "magentapart"); break;
4948     case yellow_part:mp_print(mp, "yellowpart"); break;
4949     case black_part:mp_print(mp, "blackpart"); break;
4950     case grey_part:mp_print(mp, "greypart"); break;
4951     case color_model_part:mp_print(mp, "colormodel"); break;
4952     case font_part:mp_print(mp, "fontpart"); break;
4953     case text_part:mp_print(mp, "textpart"); break;
4954     case path_part:mp_print(mp, "pathpart"); break;
4955     case pen_part:mp_print(mp, "penpart"); break;
4956     case dash_part:mp_print(mp, "dashpart"); break;
4957     case sqrt_op:mp_print(mp, "sqrt"); break;
4958     case m_exp_op:mp_print(mp, "mexp"); break;
4959     case m_log_op:mp_print(mp, "mlog"); break;
4960     case sin_d_op:mp_print(mp, "sind"); break;
4961     case cos_d_op:mp_print(mp, "cosd"); break;
4962     case floor_op:mp_print(mp, "floor"); break;
4963     case uniform_deviate:mp_print(mp, "uniformdeviate"); break;
4964     case char_exists_op:mp_print(mp, "charexists"); break;
4965     case font_size:mp_print(mp, "fontsize"); break;
4966     case ll_corner_op:mp_print(mp, "llcorner"); break;
4967     case lr_corner_op:mp_print(mp, "lrcorner"); break;
4968     case ul_corner_op:mp_print(mp, "ulcorner"); break;
4969     case ur_corner_op:mp_print(mp, "urcorner"); break;
4970     case arc_length:mp_print(mp, "arclength"); break;
4971     case angle_op:mp_print(mp, "angle"); break;
4972     case cycle_op:mp_print(mp, "cycle"); break;
4973     case filled_op:mp_print(mp, "filled"); break;
4974     case stroked_op:mp_print(mp, "stroked"); break;
4975     case textual_op:mp_print(mp, "textual"); break;
4976     case clipped_op:mp_print(mp, "clipped"); break;
4977     case bounded_op:mp_print(mp, "bounded"); break;
4978     case plus:mp_print_char(mp, '+'); break;
4979     case minus:mp_print_char(mp, '-'); break;
4980     case times:mp_print_char(mp, '*'); break;
4981     case over:mp_print_char(mp, '/'); break;
4982     case pythag_add:mp_print(mp, "++"); break;
4983     case pythag_sub:mp_print(mp, "+-+"); break;
4984     case or_op:mp_print(mp, "or"); break;
4985     case and_op:mp_print(mp, "and"); break;
4986     case less_than:mp_print_char(mp, '<'); break;
4987     case less_or_equal:mp_print(mp, "<="); break;
4988     case greater_than:mp_print_char(mp, '>'); break;
4989     case greater_or_equal:mp_print(mp, ">="); break;
4990     case equal_to:mp_print_char(mp, '='); break;
4991     case unequal_to:mp_print(mp, "<>"); break;
4992     case concatenate:mp_print(mp, "&"); break;
4993     case rotated_by:mp_print(mp, "rotated"); break;
4994     case slanted_by:mp_print(mp, "slanted"); break;
4995     case scaled_by:mp_print(mp, "scaled"); break;
4996     case shifted_by:mp_print(mp, "shifted"); break;
4997     case transformed_by:mp_print(mp, "transformed"); break;
4998     case x_scaled:mp_print(mp, "xscaled"); break;
4999     case y_scaled:mp_print(mp, "yscaled"); break;
5000     case z_scaled:mp_print(mp, "zscaled"); break;
5001     case in_font:mp_print(mp, "infont"); break;
5002     case intersect:mp_print(mp, "intersectiontimes"); break;
5003     case substring_of:mp_print(mp, "substring"); break;
5004     case subpath_of:mp_print(mp, "subpath"); break;
5005     case direction_time_of:mp_print(mp, "directiontime"); break;
5006     case point_of:mp_print(mp, "point"); break;
5007     case precontrol_of:mp_print(mp, "precontrol"); break;
5008     case postcontrol_of:mp_print(mp, "postcontrol"); break;
5009     case pen_offset_of:mp_print(mp, "penoffset"); break;
5010     case arc_time_of:mp_print(mp, "arctime"); break;
5011     case mp_version:mp_print(mp, "mpversion"); break;
5012     case envelope_of:mp_print(mp, "envelope"); break;
5013     default: mp_print(mp, ".."); break;
5014     }
5015   }
5016 }
5017
5018 @ \MP\ also has a bunch of internal parameters that a user might want to
5019 fuss with. Every such parameter has an identifying code number, defined here.
5020
5021 @<Types...@>=
5022 enum mp_given_internal {
5023   mp_tracing_titles=1, /* show titles online when they appear */
5024   mp_tracing_equations, /* show each variable when it becomes known */
5025   mp_tracing_capsules, /* show capsules too */
5026   mp_tracing_choices, /* show the control points chosen for paths */
5027   mp_tracing_specs, /* show path subdivision prior to filling with polygonal a pen */
5028   mp_tracing_commands, /* show commands and operations before they are performed */
5029   mp_tracing_restores, /* show when a variable or internal is restored */
5030   mp_tracing_macros, /* show macros before they are expanded */
5031   mp_tracing_output, /* show digitized edges as they are output */
5032   mp_tracing_stats, /* show memory usage at end of job */
5033   mp_tracing_lost_chars, /* show characters that aren't \&{infont} */
5034   mp_tracing_online, /* show long diagnostics on terminal and in the log file */
5035   mp_year, /* the current year (e.g., 1984) */
5036   mp_month, /* the current month (e.g, 3 $\equiv$ March) */
5037   mp_day, /* the current day of the month */
5038   mp_time, /* the number of minutes past midnight when this job started */
5039   mp_char_code, /* the number of the next character to be output */
5040   mp_char_ext, /* the extension code of the next character to be output */
5041   mp_char_wd, /* the width of the next character to be output */
5042   mp_char_ht, /* the height of the next character to be output */
5043   mp_char_dp, /* the depth of the next character to be output */
5044   mp_char_ic, /* the italic correction of the next character to be output */
5045   mp_design_size, /* the unit of measure used for |mp_char_wd..mp_char_ic|, in points */
5046   mp_pausing, /* positive to display lines on the terminal before they are read */
5047   mp_showstopping, /* positive to stop after each \&{show} command */
5048   mp_fontmaking, /* positive if font metric output is to be produced */
5049   mp_linejoin, /* as in \ps: 0 for mitered, 1 for round, 2 for beveled */
5050   mp_linecap, /* as in \ps: 0 for butt, 1 for round, 2 for square */
5051   mp_miterlimit, /* controls miter length as in \ps */
5052   mp_warning_check, /* controls error message when variable value is large */
5053   mp_boundary_char, /* the right boundary character for ligatures */
5054   mp_prologues, /* positive to output conforming PostScript using built-in fonts */
5055   mp_true_corners, /* positive to make \&{llcorner} etc. ignore \&{setbounds} */
5056   mp_default_color_model, /* the default color model for unspecified items */
5057   mp_restore_clip_color,
5058   mp_procset, /* wether or not create PostScript command shortcuts */
5059   mp_gtroffmode,  /* whether the user specified |-troff| on the command line */
5060 };
5061
5062 @
5063
5064 @d max_given_internal mp_gtroffmode
5065
5066 @<Glob...@>=
5067 scaled *internal;  /* the values of internal quantities */
5068 char **int_name;  /* their names */
5069 int int_ptr;  /* the maximum internal quantity defined so far */
5070 int max_internal; /* current maximum number of internal quantities */
5071 boolean troff_mode; 
5072
5073 @ @<Option variables@>=
5074 int troff_mode; 
5075
5076 @ @<Allocate or initialize ...@>=
5077 mp->max_internal=2*max_given_internal;
5078 mp->internal = xmalloc ((mp->max_internal+1), sizeof(scaled));
5079 mp->int_name = xmalloc ((mp->max_internal+1), sizeof(char *));
5080 mp->troff_mode=(opt->troff_mode>0 ? true : false);
5081
5082 @ @<Exported function ...@>=
5083 int mp_troff_mode(MP mp);
5084
5085 @ @c
5086 int mp_troff_mode(MP mp) { return mp->troff_mode; }
5087
5088 @ @<Set initial ...@>=
5089 for (k=0;k<= mp->max_internal; k++ ) { 
5090    mp->internal[k]=0; 
5091    mp->int_name[k]=NULL; 
5092 }
5093 mp->int_ptr=max_given_internal;
5094
5095 @ The symbolic names for internal quantities are put into \MP's hash table
5096 by using a routine called |primitive|, which will be defined later. Let us
5097 enter them now, so that we don't have to list all those names again
5098 anywhere else.
5099
5100 @<Put each of \MP's primitives into the hash table@>=
5101 mp_primitive(mp, "tracingtitles",internal_quantity,mp_tracing_titles);
5102 @:tracingtitles_}{\&{tracingtitles} primitive@>
5103 mp_primitive(mp, "tracingequations",internal_quantity,mp_tracing_equations);
5104 @:mp_tracing_equations_}{\&{tracingequations} primitive@>
5105 mp_primitive(mp, "tracingcapsules",internal_quantity,mp_tracing_capsules);
5106 @:mp_tracing_capsules_}{\&{tracingcapsules} primitive@>
5107 mp_primitive(mp, "tracingchoices",internal_quantity,mp_tracing_choices);
5108 @:mp_tracing_choices_}{\&{tracingchoices} primitive@>
5109 mp_primitive(mp, "tracingspecs",internal_quantity,mp_tracing_specs);
5110 @:mp_tracing_specs_}{\&{tracingspecs} primitive@>
5111 mp_primitive(mp, "tracingcommands",internal_quantity,mp_tracing_commands);
5112 @:mp_tracing_commands_}{\&{tracingcommands} primitive@>
5113 mp_primitive(mp, "tracingrestores",internal_quantity,mp_tracing_restores);
5114 @:mp_tracing_restores_}{\&{tracingrestores} primitive@>
5115 mp_primitive(mp, "tracingmacros",internal_quantity,mp_tracing_macros);
5116 @:mp_tracing_macros_}{\&{tracingmacros} primitive@>
5117 mp_primitive(mp, "tracingoutput",internal_quantity,mp_tracing_output);
5118 @:mp_tracing_output_}{\&{tracingoutput} primitive@>
5119 mp_primitive(mp, "tracingstats",internal_quantity,mp_tracing_stats);
5120 @:mp_tracing_stats_}{\&{tracingstats} primitive@>
5121 mp_primitive(mp, "tracinglostchars",internal_quantity,mp_tracing_lost_chars);
5122 @:mp_tracing_lost_chars_}{\&{tracinglostchars} primitive@>
5123 mp_primitive(mp, "tracingonline",internal_quantity,mp_tracing_online);
5124 @:mp_tracing_online_}{\&{tracingonline} primitive@>
5125 mp_primitive(mp, "year",internal_quantity,mp_year);
5126 @:mp_year_}{\&{year} primitive@>
5127 mp_primitive(mp, "month",internal_quantity,mp_month);
5128 @:mp_month_}{\&{month} primitive@>
5129 mp_primitive(mp, "day",internal_quantity,mp_day);
5130 @:mp_day_}{\&{day} primitive@>
5131 mp_primitive(mp, "time",internal_quantity,mp_time);
5132 @:time_}{\&{time} primitive@>
5133 mp_primitive(mp, "charcode",internal_quantity,mp_char_code);
5134 @:mp_char_code_}{\&{charcode} primitive@>
5135 mp_primitive(mp, "charext",internal_quantity,mp_char_ext);
5136 @:mp_char_ext_}{\&{charext} primitive@>
5137 mp_primitive(mp, "charwd",internal_quantity,mp_char_wd);
5138 @:mp_char_wd_}{\&{charwd} primitive@>
5139 mp_primitive(mp, "charht",internal_quantity,mp_char_ht);
5140 @:mp_char_ht_}{\&{charht} primitive@>
5141 mp_primitive(mp, "chardp",internal_quantity,mp_char_dp);
5142 @:mp_char_dp_}{\&{chardp} primitive@>
5143 mp_primitive(mp, "charic",internal_quantity,mp_char_ic);
5144 @:mp_char_ic_}{\&{charic} primitive@>
5145 mp_primitive(mp, "designsize",internal_quantity,mp_design_size);
5146 @:mp_design_size_}{\&{designsize} primitive@>
5147 mp_primitive(mp, "pausing",internal_quantity,mp_pausing);
5148 @:mp_pausing_}{\&{pausing} primitive@>
5149 mp_primitive(mp, "showstopping",internal_quantity,mp_showstopping);
5150 @:mp_showstopping_}{\&{showstopping} primitive@>
5151 mp_primitive(mp, "fontmaking",internal_quantity,mp_fontmaking);
5152 @:mp_fontmaking_}{\&{fontmaking} primitive@>
5153 mp_primitive(mp, "linejoin",internal_quantity,mp_linejoin);
5154 @:mp_linejoin_}{\&{linejoin} primitive@>
5155 mp_primitive(mp, "linecap",internal_quantity,mp_linecap);
5156 @:mp_linecap_}{\&{linecap} primitive@>
5157 mp_primitive(mp, "miterlimit",internal_quantity,mp_miterlimit);
5158 @:mp_miterlimit_}{\&{miterlimit} primitive@>
5159 mp_primitive(mp, "warningcheck",internal_quantity,mp_warning_check);
5160 @:mp_warning_check_}{\&{warningcheck} primitive@>
5161 mp_primitive(mp, "boundarychar",internal_quantity,mp_boundary_char);
5162 @:mp_boundary_char_}{\&{boundarychar} primitive@>
5163 mp_primitive(mp, "prologues",internal_quantity,mp_prologues);
5164 @:mp_prologues_}{\&{prologues} primitive@>
5165 mp_primitive(mp, "truecorners",internal_quantity,mp_true_corners);
5166 @:mp_true_corners_}{\&{truecorners} primitive@>
5167 mp_primitive(mp, "mpprocset",internal_quantity,mp_procset);
5168 @:mp_procset_}{\&{mpprocset} primitive@>
5169 mp_primitive(mp, "troffmode",internal_quantity,mp_gtroffmode);
5170 @:troffmode_}{\&{troffmode} primitive@>
5171 mp_primitive(mp, "defaultcolormodel",internal_quantity,mp_default_color_model);
5172 @:mp_default_color_model_}{\&{defaultcolormodel} primitive@>
5173 mp_primitive(mp, "restoreclipcolor",internal_quantity,mp_restore_clip_color);
5174 @:mp_restore_clip_color_}{\&{restoreclipcolor} primitive@>
5175
5176 @ Colors can be specified in four color models. In the special
5177 case of |no_model|, MetaPost does not output any color operator to
5178 the postscript output.
5179
5180 Note: these values are passed directly on to |with_option|. This only
5181 works because the other possible values passed to |with_option| are
5182 8 and 10 respectively (from |with_pen| and |with_picture|).
5183
5184 There is a first state, that is only used for |gs_colormodel|. It flags
5185 the fact that there has not been any kind of color specification by
5186 the user so far in the game.
5187
5188 @<Types...@>=
5189 enum mp_color_model {
5190   mp_no_model=1,
5191   mp_grey_model=3,
5192   mp_rgb_model=5,
5193   mp_cmyk_model=7,
5194   mp_uninitialized_model=9,
5195 };
5196
5197
5198 @ @<Initialize table entries (done by \.{INIMP} only)@>=
5199 mp->internal[mp_default_color_model]=(mp_rgb_model*unity);
5200 mp->internal[mp_restore_clip_color]=unity;
5201
5202 @ Well, we do have to list the names one more time, for use in symbolic
5203 printouts.
5204
5205 @<Initialize table...@>=
5206 mp->int_name[mp_tracing_titles]=xstrdup("tracingtitles");
5207 mp->int_name[mp_tracing_equations]=xstrdup("tracingequations");
5208 mp->int_name[mp_tracing_capsules]=xstrdup("tracingcapsules");
5209 mp->int_name[mp_tracing_choices]=xstrdup("tracingchoices");
5210 mp->int_name[mp_tracing_specs]=xstrdup("tracingspecs");
5211 mp->int_name[mp_tracing_commands]=xstrdup("tracingcommands");
5212 mp->int_name[mp_tracing_restores]=xstrdup("tracingrestores");
5213 mp->int_name[mp_tracing_macros]=xstrdup("tracingmacros");
5214 mp->int_name[mp_tracing_output]=xstrdup("tracingoutput");
5215 mp->int_name[mp_tracing_stats]=xstrdup("tracingstats");
5216 mp->int_name[mp_tracing_lost_chars]=xstrdup("tracinglostchars");
5217 mp->int_name[mp_tracing_online]=xstrdup("tracingonline");
5218 mp->int_name[mp_year]=xstrdup("year");
5219 mp->int_name[mp_month]=xstrdup("month");
5220 mp->int_name[mp_day]=xstrdup("day");
5221 mp->int_name[mp_time]=xstrdup("time");
5222 mp->int_name[mp_char_code]=xstrdup("charcode");
5223 mp->int_name[mp_char_ext]=xstrdup("charext");
5224 mp->int_name[mp_char_wd]=xstrdup("charwd");
5225 mp->int_name[mp_char_ht]=xstrdup("charht");
5226 mp->int_name[mp_char_dp]=xstrdup("chardp");
5227 mp->int_name[mp_char_ic]=xstrdup("charic");
5228 mp->int_name[mp_design_size]=xstrdup("designsize");
5229 mp->int_name[mp_pausing]=xstrdup("pausing");
5230 mp->int_name[mp_showstopping]=xstrdup("showstopping");
5231 mp->int_name[mp_fontmaking]=xstrdup("fontmaking");
5232 mp->int_name[mp_linejoin]=xstrdup("linejoin");
5233 mp->int_name[mp_linecap]=xstrdup("linecap");
5234 mp->int_name[mp_miterlimit]=xstrdup("miterlimit");
5235 mp->int_name[mp_warning_check]=xstrdup("warningcheck");
5236 mp->int_name[mp_boundary_char]=xstrdup("boundarychar");
5237 mp->int_name[mp_prologues]=xstrdup("prologues");
5238 mp->int_name[mp_true_corners]=xstrdup("truecorners");
5239 mp->int_name[mp_default_color_model]=xstrdup("defaultcolormodel");
5240 mp->int_name[mp_procset]=xstrdup("mpprocset");
5241 mp->int_name[mp_gtroffmode]=xstrdup("troffmode");
5242 mp->int_name[mp_restore_clip_color]=xstrdup("restoreclipcolor");
5243
5244 @ The following procedure, which is called just before \MP\ initializes its
5245 input and output, establishes the initial values of the date and time.
5246 @^system dependencies@>
5247
5248 Note that the values are |scaled| integers. Hence \MP\ can no longer
5249 be used after the year 32767.
5250
5251 @c 
5252 void mp_fix_date_and_time (MP mp) { 
5253   time_t clock = time ((time_t *) 0);
5254   struct tm *tmptr = localtime (&clock);
5255   mp->internal[mp_time]=
5256       (tmptr->tm_hour*60+tmptr->tm_min)*unity; /* minutes since midnight */
5257   mp->internal[mp_day]=(tmptr->tm_mday)*unity; /* fourth day of the month */
5258   mp->internal[mp_month]=(tmptr->tm_mon+1)*unity; /* seventh month of the year */
5259   mp->internal[mp_year]=(tmptr->tm_year+1900)*unity; /* Anno Domini */
5260 }
5261
5262 @ @<Declarations@>=
5263 void mp_fix_date_and_time (MP mp) ;
5264
5265 @ \MP\ is occasionally supposed to print diagnostic information that
5266 goes only into the transcript file, unless |mp_tracing_online| is positive.
5267 Now that we have defined |mp_tracing_online| we can define
5268 two routines that adjust the destination of print commands:
5269
5270 @<Declarations@>=
5271 void mp_begin_diagnostic (MP mp) ;
5272 void mp_end_diagnostic (MP mp,boolean blank_line);
5273 void mp_print_diagnostic (MP mp, char *s, char *t, boolean nuline) ;
5274
5275 @ @<Basic printing...@>=
5276 @<Declare a function called |true_line|@>;
5277 void mp_begin_diagnostic (MP mp) { /* prepare to do some tracing */
5278   mp->old_setting=mp->selector;
5279   if ((mp->internal[mp_tracing_online]<=0)&&(mp->selector==term_and_log)){ 
5280     decr(mp->selector);
5281     if ( mp->history==mp_spotless ) mp->history=mp_warning_issued;
5282   }
5283 }
5284 @#
5285 void mp_end_diagnostic (MP mp,boolean blank_line) {
5286   /* restore proper conditions after tracing */
5287   mp_print_nl(mp, "");
5288   if ( blank_line ) mp_print_ln(mp);
5289   mp->selector=mp->old_setting;
5290 }
5291
5292
5293
5294 @<Glob...@>=
5295 unsigned int old_setting;
5296
5297 @ We will occasionally use |begin_diagnostic| in connection with line-number
5298 printing, as follows. (The parameter |s| is typically |"Path"| or
5299 |"Cycle spec"|, etc.)
5300
5301 @<Basic printing...@>=
5302 void mp_print_diagnostic (MP mp, char *s, char *t, boolean nuline) { 
5303   mp_begin_diagnostic(mp);
5304   if ( nuline ) mp_print_nl(mp, s); else mp_print(mp, s);
5305   mp_print(mp, " at line "); 
5306   mp_print_int(mp, mp_true_line(mp));
5307   mp_print(mp, t); mp_print_char(mp, ':');
5308 }
5309
5310 @ The 256 |ASCII_code| characters are grouped into classes by means of
5311 the |char_class| table. Individual class numbers have no semantic
5312 or syntactic significance, except in a few instances defined here.
5313 There's also |max_class|, which can be used as a basis for additional
5314 class numbers in nonstandard extensions of \MP.
5315
5316 @d digit_class 0 /* the class number of \.{0123456789} */
5317 @d period_class 1 /* the class number of `\..' */
5318 @d space_class 2 /* the class number of spaces and nonstandard characters */
5319 @d percent_class 3 /* the class number of `\.\%' */
5320 @d string_class 4 /* the class number of `\."' */
5321 @d right_paren_class 8 /* the class number of `\.)' */
5322 @d isolated_classes 5: case 6: case 7: case 8 /* characters that make length-one tokens only */
5323 @d letter_class 9 /* letters and the underline character */
5324 @d left_bracket_class 17 /* `\.[' */
5325 @d right_bracket_class 18 /* `\.]' */
5326 @d invalid_class 20 /* bad character in the input */
5327 @d max_class 20 /* the largest class number */
5328
5329 @<Glob...@>=
5330 int char_class[256]; /* the class numbers */
5331
5332 @ If changes are made to accommodate non-ASCII character sets, they should
5333 follow the guidelines in Appendix~C of {\sl The {\logos METAFONT\/}book}.
5334 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
5335 @^system dependencies@>
5336
5337 @<Set initial ...@>=
5338 for (k='0';k<='9';k++) 
5339   mp->char_class[k]=digit_class;
5340 mp->char_class['.']=period_class;
5341 mp->char_class[' ']=space_class;
5342 mp->char_class['%']=percent_class;
5343 mp->char_class['"']=string_class;
5344 mp->char_class[',']=5;
5345 mp->char_class[';']=6;
5346 mp->char_class['(']=7;
5347 mp->char_class[')']=right_paren_class;
5348 for (k='A';k<= 'Z';k++ )
5349   mp->char_class[k]=letter_class;
5350 for (k='a';k<='z';k++) 
5351   mp->char_class[k]=letter_class;
5352 mp->char_class['_']=letter_class;
5353 mp->char_class['<']=10;
5354 mp->char_class['=']=10;
5355 mp->char_class['>']=10;
5356 mp->char_class[':']=10;
5357 mp->char_class['|']=10;
5358 mp->char_class['`']=11;
5359 mp->char_class['\'']=11;
5360 mp->char_class['+']=12;
5361 mp->char_class['-']=12;
5362 mp->char_class['/']=13;
5363 mp->char_class['*']=13;
5364 mp->char_class['\\']=13;
5365 mp->char_class['!']=14;
5366 mp->char_class['?']=14;
5367 mp->char_class['#']=15;
5368 mp->char_class['&']=15;
5369 mp->char_class['@@']=15;
5370 mp->char_class['$']=15;
5371 mp->char_class['^']=16;
5372 mp->char_class['~']=16;
5373 mp->char_class['[']=left_bracket_class;
5374 mp->char_class[']']=right_bracket_class;
5375 mp->char_class['{']=19;
5376 mp->char_class['}']=19;
5377 for (k=0;k<' ';k++)
5378   mp->char_class[k]=invalid_class;
5379 mp->char_class['\t']=space_class;
5380 mp->char_class['\f']=space_class;
5381 for (k=127;k<=255;k++)
5382   mp->char_class[k]=invalid_class;
5383
5384 @* \[13] The hash table.
5385 Symbolic tokens are stored and retrieved by means of a fairly standard hash
5386 table algorithm called the method of ``coalescing lists'' (cf.\ Algorithm 6.4C
5387 in {\sl The Art of Computer Programming\/}). Once a symbolic token enters the
5388 table, it is never removed.
5389
5390 The actual sequence of characters forming a symbolic token is
5391 stored in the |str_pool| array together with all the other strings. An
5392 auxiliary array |hash| consists of items with two halfword fields per
5393 word. The first of these, called |next(p)|, points to the next identifier
5394 belonging to the same coalesced list as the identifier corresponding to~|p|;
5395 and the other, called |text(p)|, points to the |str_start| entry for
5396 |p|'s identifier. If position~|p| of the hash table is empty, we have
5397 |text(p)=0|; if position |p| is either empty or the end of a coalesced
5398 hash list, we have |next(p)=0|.
5399
5400 An auxiliary pointer variable called |hash_used| is maintained in such a
5401 way that all locations |p>=hash_used| are nonempty. The global variable
5402 |st_count| tells how many symbolic tokens have been defined, if statistics
5403 are being kept.
5404
5405 The first 256 locations of |hash| are reserved for symbols of length one.
5406
5407 There's a parallel array called |eqtb| that contains the current equivalent
5408 values of each symbolic token. The entries of this array consist of
5409 two halfwords called |eq_type| (a command code) and |equiv| (a secondary
5410 piece of information that qualifies the |eq_type|).
5411
5412 @d next(A)   mp->hash[(A)].lh /* link for coalesced lists */
5413 @d text(A)   mp->hash[(A)].rh /* string number for symbolic token name */
5414 @d eq_type(A)   mp->eqtb[(A)].lh /* the current ``meaning'' of a symbolic token */
5415 @d equiv(A)   mp->eqtb[(A)].rh /* parametric part of a token's meaning */
5416 @d hash_base 257 /* hashing actually starts here */
5417 @d hash_is_full   (mp->hash_used==hash_base) /* are all positions occupied? */
5418
5419 @<Glob...@>=
5420 pointer hash_used; /* allocation pointer for |hash| */
5421 integer st_count; /* total number of known identifiers */
5422
5423 @ Certain entries in the hash table are ``frozen'' and not redefinable,
5424 since they are used in error recovery.
5425
5426 @d hash_top (hash_base+mp->hash_size) /* the first location of the frozen area */
5427 @d frozen_inaccessible hash_top /* |hash| location to protect the frozen area */
5428 @d frozen_repeat_loop (hash_top+1) /* |hash| location of a loop-repeat token */
5429 @d frozen_right_delimiter (hash_top+2) /* |hash| location of a permanent `\.)' */
5430 @d frozen_left_bracket (hash_top+3) /* |hash| location of a permanent `\.[' */
5431 @d frozen_slash (hash_top+4) /* |hash| location of a permanent `\./' */
5432 @d frozen_colon (hash_top+5) /* |hash| location of a permanent `\.:' */
5433 @d frozen_semicolon (hash_top+6) /* |hash| location of a permanent `\.;' */
5434 @d frozen_end_for (hash_top+7) /* |hash| location of a permanent \&{endfor} */
5435 @d frozen_end_def (hash_top+8) /* |hash| location of a permanent \&{enddef} */
5436 @d frozen_fi (hash_top+9) /* |hash| location of a permanent \&{fi} */
5437 @d frozen_end_group (hash_top+10) /* |hash| location of a permanent `\.{endgroup}' */
5438 @d frozen_etex (hash_top+11) /* |hash| location of a permanent \&{etex} */
5439 @d frozen_mpx_break (hash_top+12) /* |hash| location of a permanent \&{mpxbreak} */
5440 @d frozen_bad_vardef (hash_top+13) /* |hash| location of `\.{a bad variable}' */
5441 @d frozen_undefined (hash_top+14) /* |hash| location that never gets defined */
5442 @d hash_end (hash_top+14) /* the actual size of the |hash| and |eqtb| arrays */
5443
5444 @<Glob...@>=
5445 two_halves *hash; /* the hash table */
5446 two_halves *eqtb; /* the equivalents */
5447
5448 @ @<Allocate or initialize ...@>=
5449 mp->hash = xmalloc((hash_end+1),sizeof(two_halves));
5450 mp->eqtb = xmalloc((hash_end+1),sizeof(two_halves));
5451
5452 @ @<Dealloc variables@>=
5453 xfree(mp->hash);
5454 xfree(mp->eqtb);
5455
5456 @ @<Set init...@>=
5457 next(1)=0; text(1)=0; eq_type(1)=tag_token; equiv(1)=null;
5458 for (k=2;k<=hash_end;k++)  { 
5459   mp->hash[k]=mp->hash[1]; mp->eqtb[k]=mp->eqtb[1];
5460 }
5461
5462 @ @<Initialize table entries...@>=
5463 mp->hash_used=frozen_inaccessible; /* nothing is used */
5464 mp->st_count=0;
5465 text(frozen_bad_vardef)=intern("a bad variable");
5466 text(frozen_etex)=intern("etex");
5467 text(frozen_mpx_break)=intern("mpxbreak");
5468 text(frozen_fi)=intern("fi");
5469 text(frozen_end_group)=intern("endgroup");
5470 text(frozen_end_def)=intern("enddef");
5471 text(frozen_end_for)=intern("endfor");
5472 text(frozen_semicolon)=intern(";");
5473 text(frozen_colon)=intern(":");
5474 text(frozen_slash)=intern("/");
5475 text(frozen_left_bracket)=intern("[");
5476 text(frozen_right_delimiter)=intern(")");
5477 text(frozen_inaccessible)=intern(" INACCESSIBLE");
5478 eq_type(frozen_right_delimiter)=right_delimiter;
5479
5480 @ @<Check the ``constant'' values...@>=
5481 if ( hash_end+mp->max_internal>max_halfword ) mp->bad=17;
5482
5483 @ Here is the subroutine that searches the hash table for an identifier
5484 that matches a given string of length~|l| appearing in |buffer[j..
5485 (j+l-1)]|. If the identifier is not found, it is inserted; hence it
5486 will always be found, and the corresponding hash table address
5487 will be returned.
5488
5489 @c 
5490 pointer mp_id_lookup (MP mp,integer j, integer l) { /* search the hash table */
5491   integer h; /* hash code */
5492   pointer p; /* index in |hash| array */
5493   pointer k; /* index in |buffer| array */
5494   if (l==1) {
5495     @<Treat special case of length 1 and |break|@>;
5496   }
5497   @<Compute the hash code |h|@>;
5498   p=h+hash_base; /* we start searching here; note that |0<=h<hash_prime| */
5499   while (true)  { 
5500         if (text(p)>0 && length(text(p))==l && mp_str_eq_buf(mp, text(p),j)) 
5501       break;
5502     if ( next(p)==0 ) {
5503       @<Insert a new symbolic token after |p|, then
5504         make |p| point to it and |break|@>;
5505     }
5506     p=next(p);
5507   }
5508   return p;
5509 };
5510
5511 @ @<Treat special case of length 1...@>=
5512  p=mp->buffer[j]+1; text(p)=p-1; return p;
5513
5514
5515 @ @<Insert a new symbolic...@>=
5516 {
5517 if ( text(p)>0 ) { 
5518   do {  
5519     if ( hash_is_full )
5520       mp_overflow(mp, "hash size",mp->hash_size);
5521 @:MetaPost capacity exceeded hash size}{\quad hash size@>
5522     decr(mp->hash_used);
5523   } while (text(mp->hash_used)!=0); /* search for an empty location in |hash| */
5524   next(p)=mp->hash_used; 
5525   p=mp->hash_used;
5526 }
5527 str_room(l);
5528 for (k=j;k<=j+l-1;k++) {
5529   append_char(mp->buffer[k]);
5530 }
5531 text(p)=mp_make_string(mp); 
5532 mp->str_ref[text(p)]=max_str_ref;
5533 incr(mp->st_count);
5534 break;
5535 }
5536
5537
5538 @ The value of |hash_prime| should be roughly 85\pct! of |hash_size|, and it
5539 should be a prime number.  The theory of hashing tells us to expect fewer
5540 than two table probes, on the average, when the search is successful.
5541 [See J.~S. Vitter, {\sl Journal of the ACM\/ \bf30} (1983), 231--258.]
5542 @^Vitter, Jeffrey Scott@>
5543
5544 @<Compute the hash code |h|@>=
5545 h=mp->buffer[j];
5546 for (k=j+1;k<=j+l-1;k++){ 
5547   h=h+h+mp->buffer[k];
5548   while ( h>=mp->hash_prime ) h=h-mp->hash_prime;
5549 }
5550
5551 @ @<Search |eqtb| for equivalents equal to |p|@>=
5552 for (q=1;q<=hash_end;q++) { 
5553   if ( equiv(q)==p ) { 
5554     mp_print_nl(mp, "EQUIV("); 
5555     mp_print_int(mp, q); 
5556     mp_print_char(mp, ')');
5557   }
5558 }
5559
5560 @ We need to put \MP's ``primitive'' symbolic tokens into the hash
5561 table, together with their command code (which will be the |eq_type|)
5562 and an operand (which will be the |equiv|). The |primitive| procedure
5563 does this, in a way that no \MP\ user can. The global value |cur_sym|
5564 contains the new |eqtb| pointer after |primitive| has acted.
5565
5566 @c 
5567 void mp_primitive (MP mp, char *ss, halfword c, halfword o) {
5568   pool_pointer k; /* index into |str_pool| */
5569   small_number j; /* index into |buffer| */
5570   small_number l; /* length of the string */
5571   str_number s;
5572   s = intern(ss);
5573   k=mp->str_start[s]; l=str_stop(s)-k;
5574   /* we will move |s| into the (empty) |buffer| */
5575   for (j=0;j<=l-1;j++) {
5576     mp->buffer[j]=mp->str_pool[k+j];
5577   }
5578   mp->cur_sym=mp_id_lookup(mp, 0,l);
5579   if ( s>=256 ) { /* we don't want to have the string twice */
5580     mp_flush_string(mp, text(mp->cur_sym)); text(mp->cur_sym)=s;
5581   };
5582   eq_type(mp->cur_sym)=c; 
5583   equiv(mp->cur_sym)=o;
5584 }
5585
5586
5587 @ Many of \MP's primitives need no |equiv|, since they are identifiable
5588 by their |eq_type| alone. These primitives are loaded into the hash table
5589 as follows:
5590
5591 @<Put each of \MP's primitives into the hash table@>=
5592 mp_primitive(mp, "..",path_join,0);
5593 @:.._}{\.{..} primitive@>
5594 mp_primitive(mp, "[",left_bracket,0); mp->eqtb[frozen_left_bracket]=mp->eqtb[mp->cur_sym];
5595 @:[ }{\.{[} primitive@>
5596 mp_primitive(mp, "]",right_bracket,0);
5597 @:] }{\.{]} primitive@>
5598 mp_primitive(mp, "}",right_brace,0);
5599 @:]]}{\.{\char`\}} primitive@>
5600 mp_primitive(mp, "{",left_brace,0);
5601 @:][}{\.{\char`\{} primitive@>
5602 mp_primitive(mp, ":",colon,0); mp->eqtb[frozen_colon]=mp->eqtb[mp->cur_sym];
5603 @:: }{\.{:} primitive@>
5604 mp_primitive(mp, "::",double_colon,0);
5605 @::: }{\.{::} primitive@>
5606 mp_primitive(mp, "||:",bchar_label,0);
5607 @:::: }{\.{\char'174\char'174:} primitive@>
5608 mp_primitive(mp, ":=",assignment,0);
5609 @::=_}{\.{:=} primitive@>
5610 mp_primitive(mp, ",",comma,0);
5611 @:, }{\., primitive@>
5612 mp_primitive(mp, ";",semicolon,0); mp->eqtb[frozen_semicolon]=mp->eqtb[mp->cur_sym];
5613 @:; }{\.; primitive@>
5614 mp_primitive(mp, "\\",relax,0);
5615 @:]]\\}{\.{\char`\\} primitive@>
5616 @#
5617 mp_primitive(mp, "addto",add_to_command,0);
5618 @:add_to_}{\&{addto} primitive@>
5619 mp_primitive(mp, "atleast",at_least,0);
5620 @:at_least_}{\&{atleast} primitive@>
5621 mp_primitive(mp, "begingroup",begin_group,0); mp->bg_loc=mp->cur_sym;
5622 @:begin_group_}{\&{begingroup} primitive@>
5623 mp_primitive(mp, "controls",controls,0);
5624 @:controls_}{\&{controls} primitive@>
5625 mp_primitive(mp, "curl",curl_command,0);
5626 @:curl_}{\&{curl} primitive@>
5627 mp_primitive(mp, "delimiters",delimiters,0);
5628 @:delimiters_}{\&{delimiters} primitive@>
5629 mp_primitive(mp, "endgroup",end_group,0);
5630  mp->eqtb[frozen_end_group]=mp->eqtb[mp->cur_sym]; mp->eg_loc=mp->cur_sym;
5631 @:endgroup_}{\&{endgroup} primitive@>
5632 mp_primitive(mp, "everyjob",every_job_command,0);
5633 @:every_job_}{\&{everyjob} primitive@>
5634 mp_primitive(mp, "exitif",exit_test,0);
5635 @:exit_if_}{\&{exitif} primitive@>
5636 mp_primitive(mp, "expandafter",expand_after,0);
5637 @:expand_after_}{\&{expandafter} primitive@>
5638 mp_primitive(mp, "interim",interim_command,0);
5639 @:interim_}{\&{interim} primitive@>
5640 mp_primitive(mp, "let",let_command,0);
5641 @:let_}{\&{let} primitive@>
5642 mp_primitive(mp, "newinternal",new_internal,0);
5643 @:new_internal_}{\&{newinternal} primitive@>
5644 mp_primitive(mp, "of",of_token,0);
5645 @:of_}{\&{of} primitive@>
5646 mp_primitive(mp, "randomseed",mp_random_seed,0);
5647 @:mp_random_seed_}{\&{randomseed} primitive@>
5648 mp_primitive(mp, "save",save_command,0);
5649 @:save_}{\&{save} primitive@>
5650 mp_primitive(mp, "scantokens",scan_tokens,0);
5651 @:scan_tokens_}{\&{scantokens} primitive@>
5652 mp_primitive(mp, "shipout",ship_out_command,0);
5653 @:ship_out_}{\&{shipout} primitive@>
5654 mp_primitive(mp, "skipto",skip_to,0);
5655 @:skip_to_}{\&{skipto} primitive@>
5656 mp_primitive(mp, "special",special_command,0);
5657 @:special}{\&{special} primitive@>
5658 mp_primitive(mp, "fontmapfile",special_command,1);
5659 @:fontmapfile}{\&{fontmapfile} primitive@>
5660 mp_primitive(mp, "fontmapline",special_command,2);
5661 @:fontmapline}{\&{fontmapline} primitive@>
5662 mp_primitive(mp, "step",step_token,0);
5663 @:step_}{\&{step} primitive@>
5664 mp_primitive(mp, "str",str_op,0);
5665 @:str_}{\&{str} primitive@>
5666 mp_primitive(mp, "tension",tension,0);
5667 @:tension_}{\&{tension} primitive@>
5668 mp_primitive(mp, "to",to_token,0);
5669 @:to_}{\&{to} primitive@>
5670 mp_primitive(mp, "until",until_token,0);
5671 @:until_}{\&{until} primitive@>
5672 mp_primitive(mp, "within",within_token,0);
5673 @:within_}{\&{within} primitive@>
5674 mp_primitive(mp, "write",write_command,0);
5675 @:write_}{\&{write} primitive@>
5676
5677 @ Each primitive has a corresponding inverse, so that it is possible to
5678 display the cryptic numeric contents of |eqtb| in symbolic form.
5679 Every call of |primitive| in this program is therefore accompanied by some
5680 straightforward code that forms part of the |print_cmd_mod| routine
5681 explained below.
5682
5683 @<Cases of |print_cmd_mod| for symbolic printing of primitives@>=
5684 case add_to_command:mp_print(mp, "addto"); break;
5685 case assignment:mp_print(mp, ":="); break;
5686 case at_least:mp_print(mp, "atleast"); break;
5687 case bchar_label:mp_print(mp, "||:"); break;
5688 case begin_group:mp_print(mp, "begingroup"); break;
5689 case colon:mp_print(mp, ":"); break;
5690 case comma:mp_print(mp, ","); break;
5691 case controls:mp_print(mp, "controls"); break;
5692 case curl_command:mp_print(mp, "curl"); break;
5693 case delimiters:mp_print(mp, "delimiters"); break;
5694 case double_colon:mp_print(mp, "::"); break;
5695 case end_group:mp_print(mp, "endgroup"); break;
5696 case every_job_command:mp_print(mp, "everyjob"); break;
5697 case exit_test:mp_print(mp, "exitif"); break;
5698 case expand_after:mp_print(mp, "expandafter"); break;
5699 case interim_command:mp_print(mp, "interim"); break;
5700 case left_brace:mp_print(mp, "{"); break;
5701 case left_bracket:mp_print(mp, "["); break;
5702 case let_command:mp_print(mp, "let"); break;
5703 case new_internal:mp_print(mp, "newinternal"); break;
5704 case of_token:mp_print(mp, "of"); break;
5705 case path_join:mp_print(mp, ".."); break;
5706 case mp_random_seed:mp_print(mp, "randomseed"); break;
5707 case relax:mp_print_char(mp, '\\'); break;
5708 case right_brace:mp_print(mp, "}"); break;
5709 case right_bracket:mp_print(mp, "]"); break;
5710 case save_command:mp_print(mp, "save"); break;
5711 case scan_tokens:mp_print(mp, "scantokens"); break;
5712 case semicolon:mp_print(mp, ";"); break;
5713 case ship_out_command:mp_print(mp, "shipout"); break;
5714 case skip_to:mp_print(mp, "skipto"); break;
5715 case special_command: if ( m==2 ) mp_print(mp, "fontmapline"); else
5716                  if ( m==1 ) mp_print(mp, "fontmapfile"); else
5717                  mp_print(mp, "special"); break;
5718 case step_token:mp_print(mp, "step"); break;
5719 case str_op:mp_print(mp, "str"); break;
5720 case tension:mp_print(mp, "tension"); break;
5721 case to_token:mp_print(mp, "to"); break;
5722 case until_token:mp_print(mp, "until"); break;
5723 case within_token:mp_print(mp, "within"); break;
5724 case write_command:mp_print(mp, "write"); break;
5725
5726 @ We will deal with the other primitives later, at some point in the program
5727 where their |eq_type| and |equiv| values are more meaningful.  For example,
5728 the primitives for macro definitions will be loaded when we consider the
5729 routines that define macros.
5730 It is easy to find where each particular
5731 primitive was treated by looking in the index at the end; for example, the
5732 section where |"def"| entered |eqtb| is listed under `\&{def} primitive'.
5733
5734 @* \[14] Token lists.
5735 A \MP\ token is either symbolic or numeric or a string, or it denotes
5736 a macro parameter or capsule; so there are five corresponding ways to encode it
5737 @^token@>
5738 internally: (1)~A symbolic token whose hash code is~|p|
5739 is represented by the number |p|, in the |info| field of a single-word
5740 node in~|mem|. (2)~A numeric token whose |scaled| value is~|v| is
5741 represented in a two-word node of~|mem|; the |type| field is |known|,
5742 the |name_type| field is |token|, and the |value| field holds~|v|.
5743 The fact that this token appears in a two-word node rather than a
5744 one-word node is, of course, clear from the node address.
5745 (3)~A string token is also represented in a two-word node; the |type|
5746 field is |mp_string_type|, the |name_type| field is |token|, and the
5747 |value| field holds the corresponding |str_number|.  (4)~Capsules have
5748 |name_type=capsule|, and their |type| and |value| fields represent
5749 arbitrary values (in ways to be explained later).  (5)~Macro parameters
5750 are like symbolic tokens in that they appear in |info| fields of
5751 one-word nodes. The $k$th parameter is represented by |expr_base+k| if it
5752 is of type \&{expr}, or by |suffix_base+k| if it is of type \&{suffix}, or
5753 by |text_base+k| if it is of type \&{text}.  (Here |0<=k<param_size|.)
5754 Actual values of these parameters are kept in a separate stack, as we will
5755 see later.  The constants |expr_base|, |suffix_base|, and |text_base| are,
5756 of course, chosen so that there will be no confusion between symbolic
5757 tokens and parameters of various types.
5758
5759 Note that
5760 the `\\{type}' field of a node has nothing to do with ``type'' in a
5761 printer's sense. It's curious that the same word is used in such different ways.
5762
5763 @d type(A)   mp->mem[(A)].hh.b0 /* identifies what kind of value this is */
5764 @d name_type(A)   mp->mem[(A)].hh.b1 /* a clue to the name of this value */
5765 @d token_node_size 2 /* the number of words in a large token node */
5766 @d value_loc(A) ((A)+1) /* the word that contains the |value| field */
5767 @d value(A) mp->mem[value_loc((A))].cint /* the value stored in a large token node */
5768 @d expr_base (hash_end+1) /* code for the zeroth \&{expr} parameter */
5769 @d suffix_base (expr_base+mp->param_size) /* code for the zeroth \&{suffix} parameter */
5770 @d text_base (suffix_base+mp->param_size) /* code for the zeroth \&{text} parameter */
5771
5772 @<Check the ``constant''...@>=
5773 if ( text_base+mp->param_size>max_halfword ) mp->bad=18;
5774
5775 @ We have set aside a two word node beginning at |null| so that we can have
5776 |value(null)=0|.  We will make use of this coincidence later.
5777
5778 @<Initialize table entries...@>=
5779 link(null)=null; value(null)=0;
5780
5781 @ A numeric token is created by the following trivial routine.
5782
5783 @c 
5784 pointer mp_new_num_tok (MP mp,scaled v) {
5785   pointer p; /* the new node */
5786   p=mp_get_node(mp, token_node_size); value(p)=v;
5787   type(p)=mp_known; name_type(p)=mp_token; 
5788   return p;
5789 }
5790
5791 @ A token list is a singly linked list of nodes in |mem|, where
5792 each node contains a token and a link.  Here's a subroutine that gets rid
5793 of a token list when it is no longer needed.
5794
5795 @<Declarations@>=
5796 void mp_token_recycle (MP mp);
5797
5798
5799 @c void mp_flush_token_list (MP mp,pointer p) {
5800   pointer q; /* the node being recycled */
5801   while ( p!=null ) { 
5802     q=p; p=link(p);
5803     if ( q>=mp->hi_mem_min ) {
5804      free_avail(q);
5805     } else { 
5806       switch (type(q)) {
5807       case mp_vacuous: case mp_boolean_type: case mp_known:
5808         break;
5809       case mp_string_type:
5810         delete_str_ref(value(q));
5811         break;
5812       case unknown_types: case mp_pen_type: case mp_path_type: 
5813       case mp_picture_type: case mp_pair_type: case mp_color_type:
5814       case mp_cmykcolor_type: case mp_transform_type: case mp_dependent:
5815       case mp_proto_dependent: case mp_independent:
5816         mp->g_pointer=q; mp_token_recycle(mp);
5817         break;
5818       default: mp_confusion(mp, "token");
5819 @:this can't happen token}{\quad token@>
5820       }
5821       mp_free_node(mp, q,token_node_size);
5822     }
5823   }
5824 }
5825
5826 @ The procedure |show_token_list|, which prints a symbolic form of
5827 the token list that starts at a given node |p|, illustrates these
5828 conventions. The token list being displayed should not begin with a reference
5829 count. However, the procedure is intended to be fairly robust, so that if the
5830 memory links are awry or if |p| is not really a pointer to a token list,
5831 almost nothing catastrophic can happen.
5832
5833 An additional parameter |q| is also given; this parameter is either null
5834 or it points to a node in the token list where a certain magic computation
5835 takes place that will be explained later. (Basically, |q| is non-null when
5836 we are printing the two-line context information at the time of an error
5837 message; |q| marks the place corresponding to where the second line
5838 should begin.)
5839
5840 The generation will stop, and `\.{\char`\ ETC.}' will be printed, if the length
5841 of printing exceeds a given limit~|l|; the length of printing upon entry is
5842 assumed to be a given amount called |null_tally|. (Note that
5843 |show_token_list| sometimes uses itself recursively to print
5844 variable names within a capsule.)
5845 @^recursion@>
5846
5847 Unusual entries are printed in the form of all-caps tokens
5848 preceded by a space, e.g., `\.{\char`\ BAD}'.
5849
5850 @<Declarations@>=
5851 void mp_print_capsule (MP mp);
5852
5853 @ @<Declare the procedure called |show_token_list|@>=
5854 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5855                          integer null_tally) ;
5856
5857 @ @c
5858 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5859                          integer null_tally) {
5860   small_number class,c; /* the |char_class| of previous and new tokens */
5861   integer r,v; /* temporary registers */
5862   class=percent_class;
5863   mp->tally=null_tally;
5864   while ( (p!=null) && (mp->tally<l) ) { 
5865     if ( p==q ) 
5866       @<Do magic computation@>;
5867     @<Display token |p| and set |c| to its class;
5868       but |return| if there are problems@>;
5869     class=c; p=link(p);
5870   }
5871   if ( p!=null ) 
5872      mp_print(mp, " ETC.");
5873 @.ETC@>
5874   return;
5875 };
5876
5877 @ @<Display token |p| and set |c| to its class...@>=
5878 c=letter_class; /* the default */
5879 if ( (p<0)||(p>mp->mem_end) ) { 
5880   mp_print(mp, " CLOBBERED"); return;
5881 @.CLOBBERED@>
5882 }
5883 if ( p<mp->hi_mem_min ) { 
5884   @<Display two-word token@>;
5885 } else { 
5886   r=info(p);
5887   if ( r>=expr_base ) {
5888      @<Display a parameter token@>;
5889   } else {
5890     if ( r<1 ) {
5891       if ( r==0 ) { 
5892         @<Display a collective subscript@>
5893       } else {
5894         mp_print(mp, " IMPOSSIBLE");
5895 @.IMPOSSIBLE@>
5896       }
5897     } else { 
5898       r=text(r);
5899       if ( (r<0)||(r>mp->max_str_ptr) ) {
5900         mp_print(mp, " NONEXISTENT");
5901 @.NONEXISTENT@>
5902       } else {
5903        @<Print string |r| as a symbolic token
5904         and set |c| to its class@>;
5905       }
5906     }
5907   }
5908 }
5909
5910 @ @<Display two-word token@>=
5911 if ( name_type(p)==mp_token ) {
5912   if ( type(p)==mp_known ) {
5913     @<Display a numeric token@>;
5914   } else if ( type(p)!=mp_string_type ) {
5915     mp_print(mp, " BAD");
5916 @.BAD@>
5917   } else { 
5918     mp_print_char(mp, '"'); mp_print_str(mp, value(p)); mp_print_char(mp, '"');
5919     c=string_class;
5920   }
5921 } else if ((name_type(p)!=mp_capsule)||(type(p)<mp_vacuous)||(type(p)>mp_independent) ) {
5922   mp_print(mp, " BAD");
5923 } else { 
5924   mp->g_pointer=p; mp_print_capsule(mp); c=right_paren_class;
5925 }
5926
5927 @ @<Display a numeric token@>=
5928 if ( class==digit_class ) 
5929   mp_print_char(mp, ' ');
5930 v=value(p);
5931 if ( v<0 ){ 
5932   if ( class==left_bracket_class ) 
5933     mp_print_char(mp, ' ');
5934   mp_print_char(mp, '['); mp_print_scaled(mp, v); mp_print_char(mp, ']');
5935   c=right_bracket_class;
5936 } else { 
5937   mp_print_scaled(mp, v); c=digit_class;
5938 }
5939
5940
5941 @ Strictly speaking, a genuine token will never have |info(p)=0|.
5942 But we will see later (in the |print_variable_name| routine) that
5943 it is convenient to let |info(p)=0| stand for `\.{[]}'.
5944
5945 @<Display a collective subscript@>=
5946 {
5947 if ( class==left_bracket_class ) 
5948   mp_print_char(mp, ' ');
5949 mp_print(mp, "[]"); c=right_bracket_class;
5950 }
5951
5952 @ @<Display a parameter token@>=
5953 {
5954 if ( r<suffix_base ) { 
5955   mp_print(mp, "(EXPR"); r=r-(expr_base);
5956 @.EXPR@>
5957 } else if ( r<text_base ) { 
5958   mp_print(mp, "(SUFFIX"); r=r-(suffix_base);
5959 @.SUFFIX@>
5960 } else { 
5961   mp_print(mp, "(TEXT"); r=r-(text_base);
5962 @.TEXT@>
5963 }
5964 mp_print_int(mp, r); mp_print_char(mp, ')'); c=right_paren_class;
5965 }
5966
5967
5968 @ @<Print string |r| as a symbolic token...@>=
5969
5970 c=mp->char_class[mp->str_pool[mp->str_start[r]]];
5971 if ( c==class ) {
5972   switch (c) {
5973   case letter_class:mp_print_char(mp, '.'); break;
5974   case isolated_classes: break;
5975   default: mp_print_char(mp, ' '); break;
5976   }
5977 }
5978 mp_print_str(mp, r);
5979 }
5980
5981 @ The following procedures have been declared |forward| with no parameters,
5982 because the author dislikes \PASCAL's convention about |forward| procedures
5983 with parameters. It was necessary to do something, because |show_token_list|
5984 is recursive (although the recursion is limited to one level), and because
5985 |flush_token_list| is syntactically (but not semantically) recursive.
5986 @^recursion@>
5987
5988 @<Declare miscellaneous procedures that were declared |forward|@>=
5989 void mp_print_capsule (MP mp) { 
5990   mp_print_char(mp, '('); mp_print_exp(mp, mp->g_pointer,0); mp_print_char(mp, ')');
5991 };
5992 @#
5993 void mp_token_recycle (MP mp) { 
5994   mp_recycle_value(mp, mp->g_pointer);
5995 };
5996
5997 @ @<Glob...@>=
5998 pointer g_pointer; /* (global) parameter to the |forward| procedures */
5999
6000 @ Macro definitions are kept in \MP's memory in the form of token lists
6001 that have a few extra one-word nodes at the beginning.
6002
6003 The first node contains a reference count that is used to tell when the
6004 list is no longer needed. To emphasize the fact that a reference count is
6005 present, we shall refer to the |info| field of this special node as the
6006 |ref_count| field.
6007 @^reference counts@>
6008
6009 The next node or nodes after the reference count serve to describe the
6010 formal parameters. They either contain a code word that specifies all
6011 of the parameters, or they contain zero or more parameter tokens followed
6012 by the code `|general_macro|'.
6013
6014 @d ref_count info
6015   /* reference count preceding a macro definition or picture header */
6016 @d add_mac_ref(A) incr(ref_count((A))) /* make a new reference to a macro list */
6017 @d general_macro 0 /* preface to a macro defined with a parameter list */
6018 @d primary_macro 1 /* preface to a macro with a \&{primary} parameter */
6019 @d secondary_macro 2 /* preface to a macro with a \&{secondary} parameter */
6020 @d tertiary_macro 3 /* preface to a macro with a \&{tertiary} parameter */
6021 @d expr_macro 4 /* preface to a macro with an undelimited \&{expr} parameter */
6022 @d of_macro 5 /* preface to a macro with
6023   undelimited `\&{expr} |x| \&{of}~|y|' parameters */
6024 @d suffix_macro 6 /* preface to a macro with an undelimited \&{suffix} parameter */
6025 @d text_macro 7 /* preface to a macro with an undelimited \&{text} parameter */
6026
6027 @c 
6028 void mp_delete_mac_ref (MP mp,pointer p) {
6029   /* |p| points to the reference count of a macro list that is
6030     losing one reference */
6031   if ( ref_count(p)==null ) mp_flush_token_list(mp, p);
6032   else decr(ref_count(p));
6033 }
6034
6035 @ The following subroutine displays a macro, given a pointer to its
6036 reference count.
6037
6038 @c 
6039 @<Declare the procedure called |print_cmd_mod|@>;
6040 void mp_show_macro (MP mp, pointer p, integer q, integer l) {
6041   pointer r; /* temporary storage */
6042   p=link(p); /* bypass the reference count */
6043   while ( info(p)>text_macro ){ 
6044     r=link(p); link(p)=null;
6045     mp_show_token_list(mp, p,null,l,0); link(p)=r; p=r;
6046     if ( l>0 ) l=l-mp->tally; else return;
6047   } /* control printing of `\.{ETC.}' */
6048 @.ETC@>
6049   mp->tally=0;
6050   switch(info(p)) {
6051   case general_macro:mp_print(mp, "->"); break;
6052 @.->@>
6053   case primary_macro: case secondary_macro: case tertiary_macro:
6054     mp_print_char(mp, '<');
6055     mp_print_cmd_mod(mp, param_type,info(p)); 
6056     mp_print(mp, ">->");
6057     break;
6058   case expr_macro:mp_print(mp, "<expr>->"); break;
6059   case of_macro:mp_print(mp, "<expr>of<primary>->"); break;
6060   case suffix_macro:mp_print(mp, "<suffix>->"); break;
6061   case text_macro:mp_print(mp, "<text>->"); break;
6062   } /* there are no other cases */
6063   mp_show_token_list(mp, link(p),q,l-mp->tally,0);
6064 }
6065
6066 @* \[15] Data structures for variables.
6067 The variables of \MP\ programs can be simple, like `\.x', or they can
6068 combine the structural properties of arrays and records, like `\.{x20a.b}'.
6069 A \MP\ user assigns a type to a variable like \.{x20a.b} by saying, for
6070 example, `\.{boolean} \.{x20a.b}'. It's time for us to study how such
6071 things are represented inside of the computer.
6072
6073 Each variable value occupies two consecutive words, either in a two-word
6074 node called a value node, or as a two-word subfield of a larger node.  One
6075 of those two words is called the |value| field; it is an integer,
6076 containing either a |scaled| numeric value or the representation of some
6077 other type of quantity. (It might also be subdivided into halfwords, in
6078 which case it is referred to by other names instead of |value|.) The other
6079 word is broken into subfields called |type|, |name_type|, and |link|.  The
6080 |type| field is a quarterword that specifies the variable's type, and
6081 |name_type| is a quarterword from which \MP\ can reconstruct the
6082 variable's name (sometimes by using the |link| field as well).  Thus, only
6083 1.25 words are actually devoted to the value itself; the other
6084 three-quarters of a word are overhead, but they aren't wasted because they
6085 allow \MP\ to deal with sparse arrays and to provide meaningful diagnostics.
6086
6087 In this section we shall be concerned only with the structural aspects of
6088 variables, not their values. Later parts of the program will change the
6089 |type| and |value| fields, but we shall treat those fields as black boxes
6090 whose contents should not be touched.
6091
6092 However, if the |type| field is |mp_structured|, there is no |value| field,
6093 and the second word is broken into two pointer fields called |attr_head|
6094 and |subscr_head|. Those fields point to additional nodes that
6095 contain structural information, as we shall see.
6096
6097 @d subscr_head_loc(A)   (A)+1 /* where |value|, |subscr_head| and |attr_head| are */
6098 @d attr_head(A)   info(subscr_head_loc((A))) /* pointer to attribute info */
6099 @d subscr_head(A)   link(subscr_head_loc((A))) /* pointer to subscript info */
6100 @d value_node_size 2 /* the number of words in a value node */
6101
6102 @ An attribute node is three words long. Two of these words contain |type|
6103 and |value| fields as described above, and the third word contains
6104 additional information:  There is an |attr_loc| field, which contains the
6105 hash address of the token that names this attribute; and there's also a
6106 |parent| field, which points to the value node of |mp_structured| type at the
6107 next higher level (i.e., at the level to which this attribute is
6108 subsidiary).  The |name_type| in an attribute node is `|attr|'.  The
6109 |link| field points to the next attribute with the same parent; these are
6110 arranged in increasing order, so that |attr_loc(link(p))>attr_loc(p)|. The
6111 final attribute node links to the constant |end_attr|, whose |attr_loc|
6112 field is greater than any legal hash address. The |attr_head| in the
6113 parent points to a node whose |name_type| is |mp_structured_root|; this
6114 node represents the null attribute, i.e., the variable that is relevant
6115 when no attributes are attached to the parent. The |attr_head| node is either
6116 a value node, a subscript node, or an attribute node, depending on what
6117 the parent would be if it were not structured; but the subscript and
6118 attribute fields are ignored, so it effectively contains only the data of
6119 a value node. The |link| field in this special node points to an attribute
6120 node whose |attr_loc| field is zero; the latter node represents a collective
6121 subscript `\.{[]}' attached to the parent, and its |link| field points to
6122 the first non-special attribute node (or to |end_attr| if there are none).
6123
6124 A subscript node likewise occupies three words, with |type| and |value| fields
6125 plus extra information; its |name_type| is |subscr|. In this case the
6126 third word is called the |subscript| field, which is a |scaled| integer.
6127 The |link| field points to the subscript node with the next larger
6128 subscript, if any; otherwise the |link| points to the attribute node
6129 for collective subscripts at this level. We have seen that the latter node
6130 contains an upward pointer, so that the parent can be deduced.
6131
6132 The |name_type| in a parent-less value node is |root|, and the |link|
6133 is the hash address of the token that names this value.
6134
6135 In other words, variables have a hierarchical structure that includes
6136 enough threads running around so that the program is able to move easily
6137 between siblings, parents, and children. An example should be helpful:
6138 (The reader is advised to draw a picture while reading the following
6139 description, since that will help to firm up the ideas.)
6140 Suppose that `\.x' and `\.{x.a}' and `\.{x[]b}' and `\.{x5}'
6141 and `\.{x20b}' have been mentioned in a user's program, where
6142 \.{x[]b} has been declared to be of \&{boolean} type. Let |h(x)|, |h(a)|,
6143 and |h(b)| be the hash addresses of \.x, \.a, and~\.b. Then
6144 |eq_type(h(x))=name| and |equiv(h(x))=p|, where |p|~is a two-word value
6145 node with |name_type(p)=root| and |link(p)=h(x)|. We have |type(p)=mp_structured|,
6146 |attr_head(p)=q|, and |subscr_head(p)=r|, where |q| points to a value
6147 node and |r| to a subscript node. (Are you still following this? Use
6148 a pencil to draw a diagram.) The lone variable `\.x' is represented by
6149 |type(q)| and |value(q)|; furthermore
6150 |name_type(q)=mp_structured_root| and |link(q)=q1|, where |q1| points
6151 to an attribute node representing `\.{x[]}'. Thus |name_type(q1)=attr|,
6152 |attr_loc(q1)=collective_subscript=0|, |parent(q1)=p|,
6153 |type(q1)=mp_structured|, |attr_head(q1)=qq|, and |subscr_head(q1)=qq1|;
6154 |qq| is a value node with |type(qq)=mp_numeric_type| (assuming that \.{x5} is
6155 numeric, because |qq| represents `\.{x[]}' with no further attributes),
6156 |name_type(qq)=mp_structured_root|, and
6157 |link(qq)=qq1|. (Now pay attention to the next part.) Node |qq1| is
6158 an attribute node representing `\.{x[][]}', which has never yet
6159 occurred; its |type| field is |undefined|, and its |value| field is
6160 undefined. We have |name_type(qq1)=attr|, |attr_loc(qq1)=collective_subscript|,
6161 |parent(qq1)=q1|, and |link(qq1)=qq2|. Since |qq2| represents
6162 `\.{x[]b}', |type(qq2)=mp_unknown_boolean|; also |attr_loc(qq2)=h(b)|,
6163 |parent(qq2)=q1|, |name_type(qq2)=attr|, |link(qq2)=end_attr|.
6164 (Maybe colored lines will help untangle your picture.)
6165  Node |r| is a subscript node with |type| and |value|
6166 representing `\.{x5}'; |name_type(r)=subscr|, |subscript(r)=5.0|,
6167 and |link(r)=r1| is another subscript node. To complete the picture,
6168 see if you can guess what |link(r1)| is; give up? It's~|q1|.
6169 Furthermore |subscript(r1)=20.0|, |name_type(r1)=subscr|,
6170 |type(r1)=mp_structured|, |attr_head(r1)=qqq|, |subscr_head(r1)=qqq1|,
6171 and we finish things off with three more nodes
6172 |qqq|, |qqq1|, and |qqq2| hung onto~|r1|. (Perhaps you should start again
6173 with a larger sheet of paper.) The value of variable \.{x20b}
6174 appears in node~|qqq2|, as you can well imagine.
6175
6176 If the example in the previous paragraph doesn't make things crystal
6177 clear, a glance at some of the simpler subroutines below will reveal how
6178 things work out in practice.
6179
6180 The only really unusual thing about these conventions is the use of
6181 collective subscript attributes. The idea is to avoid repeating a lot of
6182 type information when many elements of an array are identical macros
6183 (for which distinct values need not be stored) or when they don't have
6184 all of the possible attributes. Branches of the structure below collective
6185 subscript attributes do not carry actual values except for macro identifiers;
6186 branches of the structure below subscript nodes do not carry significant
6187 information in their collective subscript attributes.
6188
6189 @d attr_loc_loc(A) ((A)+2) /* where the |attr_loc| and |parent| fields are */
6190 @d attr_loc(A) info(attr_loc_loc((A))) /* hash address of this attribute */
6191 @d parent(A) link(attr_loc_loc((A))) /* pointer to |mp_structured| variable */
6192 @d subscript_loc(A) ((A)+2) /* where the |subscript| field lives */
6193 @d subscript(A) mp->mem[subscript_loc((A))].sc /* subscript of this variable */
6194 @d attr_node_size 3 /* the number of words in an attribute node */
6195 @d subscr_node_size 3 /* the number of words in a subscript node */
6196 @d collective_subscript 0 /* code for the attribute `\.{[]}' */
6197
6198 @<Initialize table...@>=
6199 attr_loc(end_attr)=hash_end+1; parent(end_attr)=null;
6200
6201 @ Variables of type \&{pair} will have values that point to four-word
6202 nodes containing two numeric values. The first of these values has
6203 |name_type=mp_x_part_sector| and the second has |name_type=mp_y_part_sector|;
6204 the |link| in the first points back to the node whose |value| points
6205 to this four-word node.
6206
6207 Variables of type \&{transform} are similar, but in this case their
6208 |value| points to a 12-word node containing six values, identified by
6209 |x_part_sector|, |y_part_sector|, |mp_xx_part_sector|, |mp_xy_part_sector|,
6210 |mp_yx_part_sector|, and |mp_yy_part_sector|.
6211 Finally, variables of type \&{color} have three values in six words
6212 identified by |mp_red_part_sector|, |mp_green_part_sector|, and |mp_blue_part_sector|.
6213
6214 When an entire structured variable is saved, the |root| indication
6215 is temporarily replaced by |saved_root|.
6216
6217 Some variables have no name; they just are used for temporary storage
6218 while expressions are being evaluated. We call them {\sl capsules}.
6219
6220 @d x_part_loc(A) (A) /* where the \&{xpart} is found in a pair or transform node */
6221 @d y_part_loc(A) ((A)+2) /* where the \&{ypart} is found in a pair or transform node */
6222 @d xx_part_loc(A) ((A)+4) /* where the \&{xxpart} is found in a transform node */
6223 @d xy_part_loc(A) ((A)+6) /* where the \&{xypart} is found in a transform node */
6224 @d yx_part_loc(A) ((A)+8) /* where the \&{yxpart} is found in a transform node */
6225 @d yy_part_loc(A) ((A)+10) /* where the \&{yypart} is found in a transform node */
6226 @d red_part_loc(A) (A) /* where the \&{redpart} is found in a color node */
6227 @d green_part_loc(A) ((A)+2) /* where the \&{greenpart} is found in a color node */
6228 @d blue_part_loc(A) ((A)+4) /* where the \&{bluepart} is found in a color node */
6229 @d cyan_part_loc(A) (A) /* where the \&{cyanpart} is found in a color node */
6230 @d magenta_part_loc(A) ((A)+2) /* where the \&{magentapart} is found in a color node */
6231 @d yellow_part_loc(A) ((A)+4) /* where the \&{yellowpart} is found in a color node */
6232 @d black_part_loc(A) ((A)+6) /* where the \&{blackpart} is found in a color node */
6233 @d grey_part_loc(A) (A) /* where the \&{greypart} is found in a color node */
6234 @#
6235 @d pair_node_size 4 /* the number of words in a pair node */
6236 @d transform_node_size 12 /* the number of words in a transform node */
6237 @d color_node_size 6 /* the number of words in a color node */
6238 @d cmykcolor_node_size 8 /* the number of words in a color node */
6239
6240 @<Glob...@>=
6241 small_number big_node_size[mp_pair_type+1];
6242 small_number sector0[mp_pair_type+1];
6243 small_number sector_offset[mp_black_part_sector+1];
6244
6245 @ The |sector0| array gives for each big node type, |name_type| values
6246 for its first subfield; the |sector_offset| array gives for each
6247 |name_type| value, the offset from the first subfield in words;
6248 and the |big_node_size| array gives the size in words for each type of
6249 big node.
6250
6251 @<Set init...@>=
6252 mp->big_node_size[mp_transform_type]=transform_node_size;
6253 mp->big_node_size[mp_pair_type]=pair_node_size;
6254 mp->big_node_size[mp_color_type]=color_node_size;
6255 mp->big_node_size[mp_cmykcolor_type]=cmykcolor_node_size;
6256 mp->sector0[mp_transform_type]=mp_x_part_sector;
6257 mp->sector0[mp_pair_type]=mp_x_part_sector;
6258 mp->sector0[mp_color_type]=mp_red_part_sector;
6259 mp->sector0[mp_cmykcolor_type]=mp_cyan_part_sector;
6260 for (k=mp_x_part_sector;k<= mp_yy_part_sector;k++ ) {
6261   mp->sector_offset[k]=2*(k-mp_x_part_sector);
6262 }
6263 for (k=mp_red_part_sector;k<= mp_blue_part_sector ; k++) {
6264   mp->sector_offset[k]=2*(k-mp_red_part_sector);
6265 }
6266 for (k=mp_cyan_part_sector;k<= mp_black_part_sector;k++ ) {
6267   mp->sector_offset[k]=2*(k-mp_cyan_part_sector);
6268 }
6269
6270 @ If |type(p)=mp_pair_type| or |mp_transform_type| and if |value(p)=null|, the
6271 procedure call |init_big_node(p)| will allocate a pair or transform node
6272 for~|p|.  The individual parts of such nodes are initially of type
6273 |mp_independent|.
6274
6275 @c 
6276 void mp_init_big_node (MP mp,pointer p) {
6277   pointer q; /* the new node */
6278   small_number s; /* its size */
6279   s=mp->big_node_size[type(p)]; q=mp_get_node(mp, s);
6280   do {  
6281     s=s-2; 
6282     @<Make variable |q+s| newly independent@>;
6283     name_type(q+s)=halfp(s)+mp->sector0[type(p)]; 
6284     link(q+s)=null;
6285   } while (s!=0);
6286   link(q)=p; value(p)=q;
6287 }
6288
6289 @ The |id_transform| function creates a capsule for the
6290 identity transformation.
6291
6292 @c 
6293 pointer mp_id_transform (MP mp) {
6294   pointer p,q,r; /* list manipulation registers */
6295   p=mp_get_node(mp, value_node_size); type(p)=mp_transform_type;
6296   name_type(p)=mp_capsule; value(p)=null; mp_init_big_node(mp, p); q=value(p);
6297   r=q+transform_node_size;
6298   do {  
6299     r=r-2;
6300     type(r)=mp_known; value(r)=0;
6301   } while (r!=q);
6302   value(xx_part_loc(q))=unity; 
6303   value(yy_part_loc(q))=unity;
6304   return p;
6305 }
6306
6307 @ Tokens are of type |tag_token| when they first appear, but they point
6308 to |null| until they are first used as the root of a variable.
6309 The following subroutine establishes the root node on such grand occasions.
6310
6311 @c 
6312 void mp_new_root (MP mp,pointer x) {
6313   pointer p; /* the new node */
6314   p=mp_get_node(mp, value_node_size); type(p)=undefined; name_type(p)=mp_root;
6315   link(p)=x; equiv(x)=p;
6316 }
6317
6318 @ These conventions for variable representation are illustrated by the
6319 |print_variable_name| routine, which displays the full name of a
6320 variable given only a pointer to its two-word value packet.
6321
6322 @<Declarations@>=
6323 void mp_print_variable_name (MP mp, pointer p);
6324
6325 @ @c 
6326 void mp_print_variable_name (MP mp, pointer p) {
6327   pointer q; /* a token list that will name the variable's suffix */
6328   pointer r; /* temporary for token list creation */
6329   while ( name_type(p)>=mp_x_part_sector ) {
6330     @<Preface the output with a part specifier; |return| in the
6331       case of a capsule@>;
6332   }
6333   q=null;
6334   while ( name_type(p)>mp_saved_root ) {
6335     @<Ascend one level, pushing a token onto list |q|
6336      and replacing |p| by its parent@>;
6337   }
6338   r=mp_get_avail(mp); info(r)=link(p); link(r)=q;
6339   if ( name_type(p)==mp_saved_root ) mp_print(mp, "(SAVED)");
6340 @.SAVED@>
6341   mp_show_token_list(mp, r,null,el_gordo,mp->tally); 
6342   mp_flush_token_list(mp, r);
6343 }
6344
6345 @ @<Ascend one level, pushing a token onto list |q|...@>=
6346
6347   if ( name_type(p)==mp_subscr ) { 
6348     r=mp_new_num_tok(mp, subscript(p));
6349     do {  
6350       p=link(p);
6351     } while (name_type(p)!=mp_attr);
6352   } else if ( name_type(p)==mp_structured_root ) {
6353     p=link(p); goto FOUND;
6354   } else { 
6355     if ( name_type(p)!=mp_attr ) mp_confusion(mp, "var");
6356 @:this can't happen var}{\quad var@>
6357     r=mp_get_avail(mp); info(r)=attr_loc(p);
6358   }
6359   link(r)=q; q=r;
6360 FOUND:  
6361   p=parent(p);
6362 }
6363
6364 @ @<Preface the output with a part specifier...@>=
6365 { switch (name_type(p)) {
6366   case mp_x_part_sector: mp_print_char(mp, 'x'); break;
6367   case mp_y_part_sector: mp_print_char(mp, 'y'); break;
6368   case mp_xx_part_sector: mp_print(mp, "xx"); break;
6369   case mp_xy_part_sector: mp_print(mp, "xy"); break;
6370   case mp_yx_part_sector: mp_print(mp, "yx"); break;
6371   case mp_yy_part_sector: mp_print(mp, "yy"); break;
6372   case mp_red_part_sector: mp_print(mp, "red"); break;
6373   case mp_green_part_sector: mp_print(mp, "green"); break;
6374   case mp_blue_part_sector: mp_print(mp, "blue"); break;
6375   case mp_cyan_part_sector: mp_print(mp, "cyan"); break;
6376   case mp_magenta_part_sector: mp_print(mp, "magenta"); break;
6377   case mp_yellow_part_sector: mp_print(mp, "yellow"); break;
6378   case mp_black_part_sector: mp_print(mp, "black"); break;
6379   case mp_grey_part_sector: mp_print(mp, "grey"); break;
6380   case mp_capsule: 
6381     mp_print(mp, "%CAPSULE"); mp_print_int(mp, p-null); return;
6382     break;
6383 @.CAPSULE@>
6384   } /* there are no other cases */
6385   mp_print(mp, "part "); 
6386   p=link(p-mp->sector_offset[name_type(p)]);
6387 }
6388
6389 @ The |interesting| function returns |true| if a given variable is not
6390 in a capsule, or if the user wants to trace capsules.
6391
6392 @c 
6393 boolean mp_interesting (MP mp,pointer p) {
6394   small_number t; /* a |name_type| */
6395   if ( mp->internal[mp_tracing_capsules]>0 ) {
6396     return true;
6397   } else { 
6398     t=name_type(p);
6399     if ( t>=mp_x_part_sector ) if ( t!=mp_capsule )
6400       t=name_type(link(p-mp->sector_offset[t]));
6401     return (t!=mp_capsule);
6402   }
6403 }
6404
6405 @ Now here is a subroutine that converts an unstructured type into an
6406 equivalent structured type, by inserting a |mp_structured| node that is
6407 capable of growing. This operation is done only when |name_type(p)=root|,
6408 |subscr|, or |attr|.
6409
6410 The procedure returns a pointer to the new node that has taken node~|p|'s
6411 place in the structure. Node~|p| itself does not move, nor are its
6412 |value| or |type| fields changed in any way.
6413
6414 @c 
6415 pointer mp_new_structure (MP mp,pointer p) {
6416   pointer q,r=0; /* list manipulation registers */
6417   switch (name_type(p)) {
6418   case mp_root: 
6419     q=link(p); r=mp_get_node(mp, value_node_size); equiv(q)=r;
6420     break;
6421   case mp_subscr: 
6422     @<Link a new subscript node |r| in place of node |p|@>;
6423     break;
6424   case mp_attr: 
6425     @<Link a new attribute node |r| in place of node |p|@>;
6426     break;
6427   default: 
6428     mp_confusion(mp, "struct");
6429 @:this can't happen struct}{\quad struct@>
6430     break;
6431   }
6432   link(r)=link(p); type(r)=mp_structured; name_type(r)=name_type(p);
6433   attr_head(r)=p; name_type(p)=mp_structured_root;
6434   q=mp_get_node(mp, attr_node_size); link(p)=q; subscr_head(r)=q;
6435   parent(q)=r; type(q)=undefined; name_type(q)=mp_attr; link(q)=end_attr;
6436   attr_loc(q)=collective_subscript; 
6437   return r;
6438 };
6439
6440 @ @<Link a new subscript node |r| in place of node |p|@>=
6441
6442   q=p;
6443   do {  
6444     q=link(q);
6445   } while (name_type(q)!=mp_attr);
6446   q=parent(q); r=subscr_head_loc(q); /* |link(r)=subscr_head(q)| */
6447   do {  
6448     q=r; r=link(r);
6449   } while (r!=p);
6450   r=mp_get_node(mp, subscr_node_size);
6451   link(q)=r; subscript(r)=subscript(p);
6452 }
6453
6454 @ If the attribute is |collective_subscript|, there are two pointers to
6455 node~|p|, so we must change both of them.
6456
6457 @<Link a new attribute node |r| in place of node |p|@>=
6458
6459   q=parent(p); r=attr_head(q);
6460   do {  
6461     q=r; r=link(r);
6462   } while (r!=p);
6463   r=mp_get_node(mp, attr_node_size); link(q)=r;
6464   mp->mem[attr_loc_loc(r)]=mp->mem[attr_loc_loc(p)]; /* copy |attr_loc| and |parent| */
6465   if ( attr_loc(p)==collective_subscript ) { 
6466     q=subscr_head_loc(parent(p));
6467     while ( link(q)!=p ) q=link(q);
6468     link(q)=r;
6469   }
6470 }
6471
6472 @ The |find_variable| routine is given a pointer~|t| to a nonempty token
6473 list of suffixes; it returns a pointer to the corresponding two-word
6474 value. For example, if |t| points to token \.x followed by a numeric
6475 token containing the value~7, |find_variable| finds where the value of
6476 \.{x7} is stored in memory. This may seem a simple task, and it
6477 usually is, except when \.{x7} has never been referenced before.
6478 Indeed, \.x may never have even been subscripted before; complexities
6479 arise with respect to updating the collective subscript information.
6480
6481 If a macro type is detected anywhere along path~|t|, or if the first
6482 item on |t| isn't a |tag_token|, the value |null| is returned.
6483 Otherwise |p| will be a non-null pointer to a node such that
6484 |undefined<type(p)<mp_structured|.
6485
6486 @d abort_find { return null; }
6487
6488 @c 
6489 pointer mp_find_variable (MP mp,pointer t) {
6490   pointer p,q,r,s; /* nodes in the ``value'' line */
6491   pointer pp,qq,rr,ss; /* nodes in the ``collective'' line */
6492   integer n; /* subscript or attribute */
6493   memory_word save_word; /* temporary storage for a word of |mem| */
6494 @^inner loop@>
6495   p=info(t); t=link(t);
6496   if ( (eq_type(p) % outer_tag) != tag_token ) abort_find;
6497   if ( equiv(p)==null ) mp_new_root(mp, p);
6498   p=equiv(p); pp=p;
6499   while ( t!=null ) { 
6500     @<Make sure that both nodes |p| and |pp| are of |mp_structured| type@>;
6501     if ( t<mp->hi_mem_min ) {
6502       @<Descend one level for the subscript |value(t)|@>
6503     } else {
6504       @<Descend one level for the attribute |info(t)|@>;
6505     }
6506     t=link(t);
6507   }
6508   if ( type(pp)>=mp_structured ) {
6509     if ( type(pp)==mp_structured ) pp=attr_head(pp); else abort_find;
6510   }
6511   if ( type(p)==mp_structured ) p=attr_head(p);
6512   if ( type(p)==undefined ) { 
6513     if ( type(pp)==undefined ) { type(pp)=mp_numeric_type; value(pp)=null; };
6514     type(p)=type(pp); value(p)=null;
6515   };
6516   return p;
6517 }
6518
6519 @ Although |pp| and |p| begin together, they diverge when a subscript occurs;
6520 |pp|~stays in the collective line while |p|~goes through actual subscript
6521 values.
6522
6523 @<Make sure that both nodes |p| and |pp|...@>=
6524 if ( type(pp)!=mp_structured ) { 
6525   if ( type(pp)>mp_structured ) abort_find;
6526   ss=mp_new_structure(mp, pp);
6527   if ( p==pp ) p=ss;
6528   pp=ss;
6529 }; /* now |type(pp)=mp_structured| */
6530 if ( type(p)!=mp_structured ) /* it cannot be |>mp_structured| */
6531   p=mp_new_structure(mp, p) /* now |type(p)=mp_structured| */
6532
6533 @ We want this part of the program to be reasonably fast, in case there are
6534 @^inner loop@>
6535 lots of subscripts at the same level of the data structure. Therefore
6536 we store an ``infinite'' value in the word that appears at the end of the
6537 subscript list, even though that word isn't part of a subscript node.
6538
6539 @<Descend one level for the subscript |value(t)|@>=
6540
6541   n=value(t);
6542   pp=link(attr_head(pp)); /* now |attr_loc(pp)=collective_subscript| */
6543   q=link(attr_head(p)); save_word=mp->mem[subscript_loc(q)];
6544   subscript(q)=el_gordo; s=subscr_head_loc(p); /* |link(s)=subscr_head(p)| */
6545   do {  
6546     r=s; s=link(s);
6547   } while (n>subscript(s));
6548   if ( n==subscript(s) ) {
6549     p=s;
6550   } else { 
6551     p=mp_get_node(mp, subscr_node_size); link(r)=p; link(p)=s;
6552     subscript(p)=n; name_type(p)=mp_subscr; type(p)=undefined;
6553   }
6554   mp->mem[subscript_loc(q)]=save_word;
6555 }
6556
6557 @ @<Descend one level for the attribute |info(t)|@>=
6558
6559   n=info(t);
6560   ss=attr_head(pp);
6561   do {  
6562     rr=ss; ss=link(ss);
6563   } while (n>attr_loc(ss));
6564   if ( n<attr_loc(ss) ) { 
6565     qq=mp_get_node(mp, attr_node_size); link(rr)=qq; link(qq)=ss;
6566     attr_loc(qq)=n; name_type(qq)=mp_attr; type(qq)=undefined;
6567     parent(qq)=pp; ss=qq;
6568   }
6569   if ( p==pp ) { 
6570     p=ss; pp=ss;
6571   } else { 
6572     pp=ss; s=attr_head(p);
6573     do {  
6574       r=s; s=link(s);
6575     } while (n>attr_loc(s));
6576     if ( n==attr_loc(s) ) {
6577       p=s;
6578     } else { 
6579       q=mp_get_node(mp, attr_node_size); link(r)=q; link(q)=s;
6580       attr_loc(q)=n; name_type(q)=mp_attr; type(q)=undefined;
6581       parent(q)=p; p=q;
6582     }
6583   }
6584 }
6585
6586 @ Variables lose their former values when they appear in a type declaration,
6587 or when they are defined to be macros or \&{let} equal to something else.
6588 A subroutine will be defined later that recycles the storage associated
6589 with any particular |type| or |value|; our goal now is to study a higher
6590 level process called |flush_variable|, which selectively frees parts of a
6591 variable structure.
6592
6593 This routine has some complexity because of examples such as
6594 `\hbox{\tt numeric x[]a[]b}'
6595 which recycles all variables of the form \.{x[i]a[j]b} (and no others), while
6596 `\hbox{\tt vardef x[]a[]=...}'
6597 discards all variables of the form \.{x[i]a[j]} followed by an arbitrary
6598 suffix, except for the collective node \.{x[]a[]} itself. The obvious way
6599 to handle such examples is to use recursion; so that's what we~do.
6600 @^recursion@>
6601
6602 Parameter |p| points to the root information of the variable;
6603 parameter |t| points to a list of one-word nodes that represent
6604 suffixes, with |info=collective_subscript| for subscripts.
6605
6606 @<Declarations@>=
6607 @<Declare subroutines for printing expressions@>
6608 @<Declare basic dependency-list subroutines@>
6609 @<Declare the recycling subroutines@>
6610 void mp_flush_cur_exp (MP mp,scaled v) ;
6611 @<Declare the procedure called |flush_below_variable|@>
6612
6613 @ @c 
6614 void mp_flush_variable (MP mp,pointer p, pointer t, boolean discard_suffixes) {
6615   pointer q,r; /* list manipulation */
6616   halfword n; /* attribute to match */
6617   while ( t!=null ) { 
6618     if ( type(p)!=mp_structured ) return;
6619     n=info(t); t=link(t);
6620     if ( n==collective_subscript ) { 
6621       r=subscr_head_loc(p); q=link(r); /* |q=subscr_head(p)| */
6622       while ( name_type(q)==mp_subscr ){ 
6623         mp_flush_variable(mp, q,t,discard_suffixes);
6624         if ( t==null ) {
6625           if ( type(q)==mp_structured ) r=q;
6626           else  { link(r)=link(q); mp_free_node(mp, q,subscr_node_size);   }
6627         } else {
6628           r=q;
6629         }
6630         q=link(r);
6631       }
6632     }
6633     p=attr_head(p);
6634     do {  
6635       r=p; p=link(p);
6636     } while (attr_loc(p)<n);
6637     if ( attr_loc(p)!=n ) return;
6638   }
6639   if ( discard_suffixes ) {
6640     mp_flush_below_variable(mp, p);
6641   } else { 
6642     if ( type(p)==mp_structured ) p=attr_head(p);
6643     mp_recycle_value(mp, p);
6644   }
6645 }
6646
6647 @ The next procedure is simpler; it wipes out everything but |p| itself,
6648 which becomes undefined.
6649
6650 @<Declare the procedure called |flush_below_variable|@>=
6651 void mp_flush_below_variable (MP mp, pointer p);
6652
6653 @ @c
6654 void mp_flush_below_variable (MP mp,pointer p) {
6655    pointer q,r; /* list manipulation registers */
6656   if ( type(p)!=mp_structured ) {
6657     mp_recycle_value(mp, p); /* this sets |type(p)=undefined| */
6658   } else { 
6659     q=subscr_head(p);
6660     while ( name_type(q)==mp_subscr ) { 
6661       mp_flush_below_variable(mp, q); r=q; q=link(q);
6662       mp_free_node(mp, r,subscr_node_size);
6663     }
6664     r=attr_head(p); q=link(r); mp_recycle_value(mp, r);
6665     if ( name_type(p)<=mp_saved_root ) mp_free_node(mp, r,value_node_size);
6666     else mp_free_node(mp, r,subscr_node_size);
6667     /* we assume that |subscr_node_size=attr_node_size| */
6668     do {  
6669       mp_flush_below_variable(mp, q); r=q; q=link(q); mp_free_node(mp, r,attr_node_size);
6670     } while (q!=end_attr);
6671     type(p)=undefined;
6672   }
6673 }
6674
6675 @ Just before assigning a new value to a variable, we will recycle the
6676 old value and make the old value undefined. The |und_type| routine
6677 determines what type of undefined value should be given, based on
6678 the current type before recycling.
6679
6680 @c 
6681 small_number mp_und_type (MP mp,pointer p) { 
6682   switch (type(p)) {
6683   case undefined: case mp_vacuous:
6684     return undefined;
6685   case mp_boolean_type: case mp_unknown_boolean:
6686     return mp_unknown_boolean;
6687   case mp_string_type: case mp_unknown_string:
6688     return mp_unknown_string;
6689   case mp_pen_type: case mp_unknown_pen:
6690     return mp_unknown_pen;
6691   case mp_path_type: case mp_unknown_path:
6692     return mp_unknown_path;
6693   case mp_picture_type: case mp_unknown_picture:
6694     return mp_unknown_picture;
6695   case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
6696   case mp_pair_type: case mp_numeric_type: 
6697     return type(p);
6698   case mp_known: case mp_dependent: case mp_proto_dependent: case mp_independent:
6699     return mp_numeric_type;
6700   } /* there are no other cases */
6701   return 0;
6702 }
6703
6704 @ The |clear_symbol| routine is used when we want to redefine the equivalent
6705 of a symbolic token. It must remove any variable structure or macro
6706 definition that is currently attached to that symbol. If the |saving|
6707 parameter is true, a subsidiary structure is saved instead of destroyed.
6708
6709 @c 
6710 void mp_clear_symbol (MP mp,pointer p, boolean saving) {
6711   pointer q; /* |equiv(p)| */
6712   q=equiv(p);
6713   switch (eq_type(p) % outer_tag)  {
6714   case defined_macro:
6715   case secondary_primary_macro:
6716   case tertiary_secondary_macro:
6717   case expression_tertiary_macro: 
6718     if ( ! saving ) mp_delete_mac_ref(mp, q);
6719     break;
6720   case tag_token:
6721     if ( q!=null ) {
6722       if ( saving ) {
6723         name_type(q)=mp_saved_root;
6724       } else { 
6725         mp_flush_below_variable(mp, q); mp_free_node(mp,q,value_node_size); 
6726       }
6727     }
6728     break;
6729   default:
6730     break;
6731   }
6732   mp->eqtb[p]=mp->eqtb[frozen_undefined];
6733 };
6734
6735 @* \[16] Saving and restoring equivalents.
6736 The nested structure given by \&{begingroup} and \&{endgroup}
6737 allows |eqtb| entries to be saved and restored, so that temporary changes
6738 can be made without difficulty.  When the user requests a current value to
6739 be saved, \MP\ puts that value into its ``save stack.'' An appearance of
6740 \&{endgroup} ultimately causes the old values to be removed from the save
6741 stack and put back in their former places.
6742
6743 The save stack is a linked list containing three kinds of entries,
6744 distinguished by their |info| fields. If |p| points to a saved item,
6745 then
6746
6747 \smallskip\hang
6748 |info(p)=0| stands for a group boundary; each \&{begingroup} contributes
6749 such an item to the save stack and each \&{endgroup} cuts back the stack
6750 until the most recent such entry has been removed.
6751
6752 \smallskip\hang
6753 |info(p)=q|, where |1<=q<=hash_end|, means that |mem[p+1]| holds the former
6754 contents of |eqtb[q]|. Such save stack entries are generated by \&{save}
6755 commands or suitable \&{interim} commands.
6756
6757 \smallskip\hang
6758 |info(p)=hash_end+q|, where |q>0|, means that |value(p)| is a |scaled|
6759 integer to be restored to internal parameter number~|q|. Such entries
6760 are generated by \&{interim} commands.
6761
6762 \smallskip\noindent
6763 The global variable |save_ptr| points to the top item on the save stack.
6764
6765 @d save_node_size 2 /* number of words per non-boundary save-stack node */
6766 @d saved_equiv(A) mp->mem[(A)+1].hh /* where an |eqtb| entry gets saved */
6767 @d save_boundary_item(A) { (A)=mp_get_avail(mp); info((A))=0;
6768   link((A))=mp->save_ptr; mp->save_ptr=(A);
6769   }
6770
6771 @<Glob...@>=
6772 pointer save_ptr; /* the most recently saved item */
6773
6774 @ @<Set init...@>=mp->save_ptr=null;
6775
6776 @ The |save_variable| routine is given a hash address |q|; it salts this
6777 address in the save stack, together with its current equivalent,
6778 then makes token~|q| behave as though it were brand new.
6779
6780 Nothing is stacked when |save_ptr=null|, however; there's no way to remove
6781 things from the stack when the program is not inside a group, so there's
6782 no point in wasting the space.
6783
6784 @c void mp_save_variable (MP mp,pointer q) {
6785   pointer p; /* temporary register */
6786   if ( mp->save_ptr!=null ){ 
6787     p=mp_get_node(mp, save_node_size); info(p)=q; link(p)=mp->save_ptr;
6788     saved_equiv(p)=mp->eqtb[q]; mp->save_ptr=p;
6789   }
6790   mp_clear_symbol(mp, q,(mp->save_ptr!=null));
6791 }
6792
6793 @ Similarly, |save_internal| is given the location |q| of an internal
6794 quantity like |mp_tracing_pens|. It creates a save stack entry of the
6795 third kind.
6796
6797 @c void mp_save_internal (MP mp,halfword q) {
6798   pointer p; /* new item for the save stack */
6799   if ( mp->save_ptr!=null ){ 
6800      p=mp_get_node(mp, save_node_size); info(p)=hash_end+q;
6801     link(p)=mp->save_ptr; value(p)=mp->internal[q]; mp->save_ptr=p;
6802   }
6803 }
6804
6805 @ At the end of a group, the |unsave| routine restores all of the saved
6806 equivalents in reverse order. This routine will be called only when there
6807 is at least one boundary item on the save stack.
6808
6809 @c 
6810 void mp_unsave (MP mp) {
6811   pointer q; /* index to saved item */
6812   pointer p; /* temporary register */
6813   while ( info(mp->save_ptr)!=0 ) {
6814     q=info(mp->save_ptr);
6815     if ( q>hash_end ) {
6816       if ( mp->internal[mp_tracing_restores]>0 ) {
6817         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6818         mp_print(mp, mp->int_name[q-(hash_end)]); mp_print_char(mp, '=');
6819         mp_print_scaled(mp, value(mp->save_ptr)); mp_print_char(mp, '}');
6820         mp_end_diagnostic(mp, false);
6821       }
6822       mp->internal[q-(hash_end)]=value(mp->save_ptr);
6823     } else { 
6824       if ( mp->internal[mp_tracing_restores]>0 ) {
6825         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6826         mp_print_text(q); mp_print_char(mp, '}');
6827         mp_end_diagnostic(mp, false);
6828       }
6829       mp_clear_symbol(mp, q,false);
6830       mp->eqtb[q]=saved_equiv(mp->save_ptr);
6831       if ( eq_type(q) % outer_tag==tag_token ) {
6832         p=equiv(q);
6833         if ( p!=null ) name_type(p)=mp_root;
6834       }
6835     }
6836     p=link(mp->save_ptr); 
6837     mp_free_node(mp, mp->save_ptr,save_node_size); mp->save_ptr=p;
6838   }
6839   p=link(mp->save_ptr); free_avail(mp->save_ptr); mp->save_ptr=p;
6840 }
6841
6842 @* \[17] Data structures for paths.
6843 When a \MP\ user specifies a path, \MP\ will create a list of knots
6844 and control points for the associated cubic spline curves. If the
6845 knots are $z_0$, $z_1$, \dots, $z_n$, there are control points
6846 $z_k^+$ and $z_{k+1}^-$ such that the cubic splines between knots
6847 $z_k$ and $z_{k+1}$ are defined by B\'ezier's formula
6848 @:Bezier}{B\'ezier, Pierre Etienne@>
6849 $$\eqalign{z(t)&=B(z_k,z_k^+,z_{k+1}^-,z_{k+1};t)\cr
6850 &=(1-t)^3z_k+3(1-t)^2tz_k^++3(1-t)t^2z_{k+1}^-+t^3z_{k+1}\cr}$$
6851 for |0<=t<=1|.
6852
6853 There is a 8-word node for each knot $z_k$, containing one word of
6854 control information and six words for the |x| and |y| coordinates of
6855 $z_k^-$ and $z_k$ and~$z_k^+$. The control information appears in the
6856 |left_type| and |right_type| fields, which each occupy a quarter of
6857 the first word in the node; they specify properties of the curve as it
6858 enters and leaves the knot. There's also a halfword |link| field,
6859 which points to the following knot, and a final supplementary word (of
6860 which only a quarter is used).
6861
6862 If the path is a closed contour, knots 0 and |n| are identical;
6863 i.e., the |link| in knot |n-1| points to knot~0. But if the path
6864 is not closed, the |left_type| of knot~0 and the |right_type| of knot~|n|
6865 are equal to |endpoint|. In the latter case the |link| in knot~|n| points
6866 to knot~0, and the control points $z_0^-$ and $z_n^+$ are not used.
6867
6868 @d left_type(A)   mp->mem[(A)].hh.b0 /* characterizes the path entering this knot */
6869 @d right_type(A)   mp->mem[(A)].hh.b1 /* characterizes the path leaving this knot */
6870 @d x_coord(A)   mp->mem[(A)+1].sc /* the |x| coordinate of this knot */
6871 @d y_coord(A)   mp->mem[(A)+2].sc /* the |y| coordinate of this knot */
6872 @d left_x(A)   mp->mem[(A)+3].sc /* the |x| coordinate of previous control point */
6873 @d left_y(A)   mp->mem[(A)+4].sc /* the |y| coordinate of previous control point */
6874 @d right_x(A)   mp->mem[(A)+5].sc /* the |x| coordinate of next control point */
6875 @d right_y(A)   mp->mem[(A)+6].sc /* the |y| coordinate of next control point */
6876 @d x_loc(A)   ((A)+1) /* where the |x| coordinate is stored in a knot */
6877 @d y_loc(A)   ((A)+2) /* where the |y| coordinate is stored in a knot */
6878 @d knot_coord(A)   mp->mem[(A)].sc /* |x| or |y| coordinate given |x_loc| or |y_loc| */
6879 @d left_coord(A)   mp->mem[(A)+2].sc
6880   /* coordinate of previous control point given |x_loc| or |y_loc| */
6881 @d right_coord(A)   mp->mem[(A)+4].sc
6882   /* coordinate of next control point given |x_loc| or |y_loc| */
6883 @d knot_node_size 8 /* number of words in a knot node */
6884
6885 @<Types...@>=
6886 enum mp_knot_type {
6887  mp_endpoint=0, /* |left_type| at path beginning and |right_type| at path end */
6888  mp_explicit, /* |left_type| or |right_type| when control points are known */
6889  mp_given, /* |left_type| or |right_type| when a direction is given */
6890  mp_curl, /* |left_type| or |right_type| when a curl is desired */
6891  mp_open, /* |left_type| or |right_type| when \MP\ should choose the direction */
6892  mp_end_cycle
6893 } ;
6894
6895 @ Before the B\'ezier control points have been calculated, the memory
6896 space they will ultimately occupy is taken up by information that can be
6897 used to compute them. There are four cases:
6898
6899 \yskip
6900 \textindent{$\bullet$} If |right_type=mp_open|, the curve should leave
6901 the knot in the same direction it entered; \MP\ will figure out a
6902 suitable direction.
6903
6904 \yskip
6905 \textindent{$\bullet$} If |right_type=mp_curl|, the curve should leave the
6906 knot in a direction depending on the angle at which it enters the next
6907 knot and on the curl parameter stored in |right_curl|.
6908
6909 \yskip
6910 \textindent{$\bullet$} If |right_type=mp_given|, the curve should leave the
6911 knot in a nonzero direction stored as an |angle| in |right_given|.
6912
6913 \yskip
6914 \textindent{$\bullet$} If |right_type=mp_explicit|, the B\'ezier control
6915 point for leaving this knot has already been computed; it is in the
6916 |right_x| and |right_y| fields.
6917
6918 \yskip\noindent
6919 The rules for |left_type| are similar, but they refer to the curve entering
6920 the knot, and to \\{left} fields instead of \\{right} fields.
6921
6922 Non-|explicit| control points will be chosen based on ``tension'' parameters
6923 in the |left_tension| and |right_tension| fields. The
6924 `\&{atleast}' option is represented by negative tension values.
6925 @:at_least_}{\&{atleast} primitive@>
6926
6927 For example, the \MP\ path specification
6928 $$\.{z0..z1..tension atleast 1..\{curl 2\}z2..z3\{-1,-2\}..tension
6929   3 and 4..p},$$
6930 where \.p is the path `\.{z4..controls z45 and z54..z5}', will be represented
6931 by the six knots
6932 \def\lodash{\hbox to 1.1em{\thinspace\hrulefill\thinspace}}
6933 $$\vbox{\halign{#\hfil&&\qquad#\hfil\cr
6934 |left_type|&\\{left} info&|x_coord,y_coord|&|right_type|&\\{right} info\cr
6935 \noalign{\yskip}
6936 |endpoint|&\lodash$,\,$\lodash&$x_0,y_0$&|curl|&$1.0,1.0$\cr
6937 |open|&\lodash$,1.0$&$x_1,y_1$&|open|&\lodash$,-1.0$\cr
6938 |curl|&$2.0,-1.0$&$x_2,y_2$&|curl|&$2.0,1.0$\cr
6939 |given|&$d,1.0$&$x_3,y_3$&|given|&$d,3.0$\cr
6940 |open|&\lodash$,4.0$&$x_4,y_4$&|explicit|&$x_{45},y_{45}$\cr
6941 |explicit|&$x_{54},y_{54}$&$x_5,y_5$&|endpoint|&\lodash$,\,$\lodash\cr}}$$
6942 Here |d| is the |angle| obtained by calling |n_arg(-unity,-two)|.
6943 Of course, this example is more complicated than anything a normal user
6944 would ever write.
6945
6946 These types must satisfy certain restrictions because of the form of \MP's
6947 path syntax:
6948 (i)~|open| type never appears in the same node together with |endpoint|,
6949 |given|, or |curl|.
6950 (ii)~The |right_type| of a node is |explicit| if and only if the
6951 |left_type| of the following node is |explicit|.
6952 (iii)~|endpoint| types occur only at the ends, as mentioned above.
6953
6954 @d left_curl left_x /* curl information when entering this knot */
6955 @d left_given left_x /* given direction when entering this knot */
6956 @d left_tension left_y /* tension information when entering this knot */
6957 @d right_curl right_x /* curl information when leaving this knot */
6958 @d right_given right_x /* given direction when leaving this knot */
6959 @d right_tension right_y /* tension information when leaving this knot */
6960
6961 @ Knots can be user-supplied, or they can be created by program code,
6962 like the |split_cubic| function, or |copy_path|. The distinction is
6963 needed for the cleanup routine that runs after |split_cubic|, because
6964 it should only delete knots it has previously inserted, and never
6965 anything that was user-supplied. In order to be able to differentiate
6966 one knot from another, we will set |originator(p):=mp_metapost_user| when
6967 it appeared in the actual metapost program, and
6968 |originator(p):=mp_program_code| in all other cases.
6969
6970 @d originator(A)   mp->mem[(A)+7].hh.b0 /* the creator of this knot */
6971
6972 @<Types...@>=
6973 enum {
6974   mp_program_code=0, /* not created by a user */
6975   mp_metapost_user, /* created by a user */
6976 };
6977
6978 @ Here is a routine that prints a given knot list
6979 in symbolic form. It illustrates the conventions discussed above,
6980 and checks for anomalies that might arise while \MP\ is being debugged.
6981
6982 @<Declare subroutines for printing expressions@>=
6983 void mp_pr_path (MP mp,pointer h);
6984
6985 @ @c
6986 void mp_pr_path (MP mp,pointer h) {
6987   pointer p,q; /* for list traversal */
6988   p=h;
6989   do {  
6990     q=link(p);
6991     if ( (p==null)||(q==null) ) { 
6992       mp_print_nl(mp, "???"); return; /* this won't happen */
6993 @.???@>
6994     }
6995     @<Print information for adjacent knots |p| and |q|@>;
6996   DONE1:
6997     p=q;
6998     if ( (p!=h)||(left_type(h)!=mp_endpoint) ) {
6999       @<Print two dots, followed by |given| or |curl| if present@>;
7000     }
7001   } while (p!=h);
7002   if ( left_type(h)!=mp_endpoint ) 
7003     mp_print(mp, "cycle");
7004 }
7005
7006 @ @<Print information for adjacent knots...@>=
7007 mp_print_two(mp, x_coord(p),y_coord(p));
7008 switch (right_type(p)) {
7009 case mp_endpoint: 
7010   if ( left_type(p)==mp_open ) mp_print(mp, "{open?}"); /* can't happen */
7011 @.open?@>
7012   if ( (left_type(q)!=mp_endpoint)||(q!=h) ) q=null; /* force an error */
7013   goto DONE1;
7014   break;
7015 case mp_explicit: 
7016   @<Print control points between |p| and |q|, then |goto done1|@>;
7017   break;
7018 case mp_open: 
7019   @<Print information for a curve that begins |open|@>;
7020   break;
7021 case mp_curl:
7022 case mp_given: 
7023   @<Print information for a curve that begins |curl| or |given|@>;
7024   break;
7025 default:
7026   mp_print(mp, "???"); /* can't happen */
7027 @.???@>
7028   break;
7029 }
7030 if ( left_type(q)<=mp_explicit ) {
7031   mp_print(mp, "..control?"); /* can't happen */
7032 @.control?@>
7033 } else if ( (right_tension(p)!=unity)||(left_tension(q)!=unity) ) {
7034   @<Print tension between |p| and |q|@>;
7035 }
7036
7037 @ Since |n_sin_cos| produces |fraction| results, which we will print as if they
7038 were |scaled|, the magnitude of a |given| direction vector will be~4096.
7039
7040 @<Print two dots...@>=
7041
7042   mp_print_nl(mp, " ..");
7043   if ( left_type(p)==mp_given ) { 
7044     mp_n_sin_cos(mp, left_given(p)); mp_print_char(mp, '{');
7045     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ',');
7046     mp_print_scaled(mp, mp->n_sin); mp_print_char(mp, '}');
7047   } else if ( left_type(p)==mp_curl ){ 
7048     mp_print(mp, "{curl "); 
7049     mp_print_scaled(mp, left_curl(p)); mp_print_char(mp, '}');
7050   }
7051 }
7052
7053 @ @<Print tension between |p| and |q|@>=
7054
7055   mp_print(mp, "..tension ");
7056   if ( right_tension(p)<0 ) mp_print(mp, "atleast");
7057   mp_print_scaled(mp, abs(right_tension(p)));
7058   if ( right_tension(p)!=left_tension(q) ){ 
7059     mp_print(mp, " and ");
7060     if ( left_tension(q)<0 ) mp_print(mp, "atleast");
7061     mp_print_scaled(mp, abs(left_tension(q)));
7062   }
7063 }
7064
7065 @ @<Print control points between |p| and |q|, then |goto done1|@>=
7066
7067   mp_print(mp, "..controls "); 
7068   mp_print_two(mp, right_x(p),right_y(p)); 
7069   mp_print(mp, " and ");
7070   if ( left_type(q)!=mp_explicit ) { 
7071     mp_print(mp, "??"); /* can't happen */
7072 @.??@>
7073   } else {
7074     mp_print_two(mp, left_x(q),left_y(q));
7075   }
7076   goto DONE1;
7077 }
7078
7079 @ @<Print information for a curve that begins |open|@>=
7080 if ( (left_type(p)!=mp_explicit)&&(left_type(p)!=mp_open) ) {
7081   mp_print(mp, "{open?}"); /* can't happen */
7082 @.open?@>
7083 }
7084
7085 @ A curl of 1 is shown explicitly, so that the user sees clearly that
7086 \MP's default curl is present.
7087
7088 The code here uses the fact that |left_curl==left_given| and
7089 |right_curl==right_given|.
7090
7091 @<Print information for a curve that begins |curl|...@>=
7092
7093   if ( left_type(p)==mp_open )  
7094     mp_print(mp, "??"); /* can't happen */
7095 @.??@>
7096   if ( right_type(p)==mp_curl ) { 
7097     mp_print(mp, "{curl "); mp_print_scaled(mp, right_curl(p));
7098   } else { 
7099     mp_n_sin_cos(mp, right_given(p)); mp_print_char(mp, '{');
7100     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ','); 
7101     mp_print_scaled(mp, mp->n_sin);
7102   }
7103   mp_print_char(mp, '}');
7104 }
7105
7106 @ It is convenient to have another version of |pr_path| that prints the path
7107 as a diagnostic message.
7108
7109 @<Declare subroutines for printing expressions@>=
7110 void mp_print_path (MP mp,pointer h, char *s, boolean nuline) { 
7111   mp_print_diagnostic(mp, "Path", s, nuline); mp_print_ln(mp);
7112 @.Path at line...@>
7113   mp_pr_path(mp, h);
7114   mp_end_diagnostic(mp, true);
7115 }
7116
7117 @ If we want to duplicate a knot node, we can say |copy_knot|:
7118
7119 @c 
7120 pointer mp_copy_knot (MP mp,pointer p) {
7121   pointer q; /* the copy */
7122   int k; /* runs through the words of a knot node */
7123   q=mp_get_node(mp, knot_node_size);
7124   for (k=0;k<knot_node_size;k++) {
7125     mp->mem[q+k]=mp->mem[p+k];
7126   }
7127   originator(q)=originator(p);
7128   return q;
7129 }
7130
7131 @ The |copy_path| routine makes a clone of a given path.
7132
7133 @c 
7134 pointer mp_copy_path (MP mp, pointer p) {
7135   pointer q,pp,qq; /* for list manipulation */
7136   q=mp_copy_knot(mp, p);
7137   qq=q; pp=link(p);
7138   while ( pp!=p ) { 
7139     link(qq)=mp_copy_knot(mp, pp);
7140     qq=link(qq);
7141     pp=link(pp);
7142   }
7143   link(qq)=q;
7144   return q;
7145 }
7146
7147
7148 @ Just before |ship_out|, knot lists are exported for printing.
7149
7150 The |gr_XXXX| macros are defined in |mppsout.h|.
7151
7152 @c 
7153 struct mp_knot *mp_export_knot (MP mp,pointer p) {
7154   struct mp_knot *q; /* the copy */
7155   if (p==null)
7156      return NULL;
7157   q = mp_xmalloc(mp, 1, sizeof (struct mp_knot));
7158   memset(q,0,sizeof (struct mp_knot));
7159   gr_left_type(q)  = left_type(p);
7160   gr_right_type(q) = right_type(p);
7161   gr_x_coord(q)    = x_coord(p);
7162   gr_y_coord(q)    = y_coord(p);
7163   gr_left_x(q)     = left_x(p);
7164   gr_left_y(q)     = left_y(p);
7165   gr_right_x(q)    = right_x(p);
7166   gr_right_y(q)    = right_y(p);
7167   gr_originator(q) = originator(p);
7168   return q;
7169 }
7170
7171 @ The |export_knot_list| routine therefore also makes a clone 
7172 of a given path.
7173
7174 @c 
7175 struct mp_knot *mp_export_knot_list (MP mp, pointer p) {
7176   struct mp_knot *q, *qq; /* for list manipulation */
7177   pointer pp; /* for list manipulation */
7178   if (p==null)
7179      return NULL;
7180   q=mp_export_knot(mp, p);
7181   qq=q; pp=link(p);
7182   while ( pp!=p ) { 
7183     gr_next_knot(qq)=mp_export_knot(mp, pp);
7184     qq=gr_next_knot(qq);
7185     pp=link(pp);
7186   }
7187   gr_next_knot(qq)=q;
7188   return q;
7189 }
7190
7191
7192 @ Similarly, there's a way to copy the {\sl reverse\/} of a path. This procedure
7193 returns a pointer to the first node of the copy, if the path is a cycle,
7194 but to the final node of a non-cyclic copy. The global
7195 variable |path_tail| will point to the final node of the original path;
7196 this trick makes it easier to implement `\&{doublepath}'.
7197
7198 All node types are assumed to be |endpoint| or |explicit| only.
7199
7200 @c 
7201 pointer mp_htap_ypoc (MP mp,pointer p) {
7202   pointer q,pp,qq,rr; /* for list manipulation */
7203   q=mp_get_node(mp, knot_node_size); /* this will correspond to |p| */
7204   qq=q; pp=p;
7205   while (1) { 
7206     right_type(qq)=left_type(pp); left_type(qq)=right_type(pp);
7207     x_coord(qq)=x_coord(pp); y_coord(qq)=y_coord(pp);
7208     right_x(qq)=left_x(pp); right_y(qq)=left_y(pp);
7209     left_x(qq)=right_x(pp); left_y(qq)=right_y(pp);
7210     originator(qq)=originator(pp);
7211     if ( link(pp)==p ) { 
7212       link(q)=qq; mp->path_tail=pp; return q;
7213     }
7214     rr=mp_get_node(mp, knot_node_size); link(rr)=qq; qq=rr; pp=link(pp);
7215   }
7216 }
7217
7218 @ @<Glob...@>=
7219 pointer path_tail; /* the node that links to the beginning of a path */
7220
7221 @ When a cyclic list of knot nodes is no longer needed, it can be recycled by
7222 calling the following subroutine.
7223
7224 @<Declare the recycling subroutines@>=
7225 void mp_toss_knot_list (MP mp,pointer p) ;
7226
7227 @ @c
7228 void mp_toss_knot_list (MP mp,pointer p) {
7229   pointer q; /* the node being freed */
7230   pointer r; /* the next node */
7231   q=p;
7232   do {  
7233     r=link(q); 
7234     mp_free_node(mp, q,knot_node_size); q=r;
7235   } while (q!=p);
7236 }
7237
7238 @* \[18] Choosing control points.
7239 Now we must actually delve into one of \MP's more difficult routines,
7240 the |make_choices| procedure that chooses angles and control points for
7241 the splines of a curve when the user has not specified them explicitly.
7242 The parameter to |make_choices| points to a list of knots and
7243 path information, as described above.
7244
7245 A path decomposes into independent segments at ``breakpoint'' knots,
7246 which are knots whose left and right angles are both prespecified in
7247 some way (i.e., their |left_type| and |right_type| aren't both open).
7248
7249 @c 
7250 @<Declare the procedure called |solve_choices|@>;
7251 void mp_make_choices (MP mp,pointer knots) {
7252   pointer h; /* the first breakpoint */
7253   pointer p,q; /* consecutive breakpoints being processed */
7254   @<Other local variables for |make_choices|@>;
7255   check_arith; /* make sure that |arith_error=false| */
7256   if ( mp->internal[mp_tracing_choices]>0 )
7257     mp_print_path(mp, knots,", before choices",true);
7258   @<If consecutive knots are equal, join them explicitly@>;
7259   @<Find the first breakpoint, |h|, on the path;
7260     insert an artificial breakpoint if the path is an unbroken cycle@>;
7261   p=h;
7262   do {  
7263     @<Fill in the control points between |p| and the next breakpoint,
7264       then advance |p| to that breakpoint@>;
7265   } while (p!=h);
7266   if ( mp->internal[mp_tracing_choices]>0 )
7267     mp_print_path(mp, knots,", after choices",true);
7268   if ( mp->arith_error ) {
7269     @<Report an unexpected problem during the choice-making@>;
7270   }
7271 }
7272
7273 @ @<Report an unexpected problem during the choice...@>=
7274
7275   print_err("Some number got too big");
7276 @.Some number got too big@>
7277   help2("The path that I just computed is out of range.")
7278        ("So it will probably look funny. Proceed, for a laugh.");
7279   mp_put_get_error(mp); mp->arith_error=false;
7280 }
7281
7282 @ Two knots in a row with the same coordinates will always be joined
7283 by an explicit ``curve'' whose control points are identical with the
7284 knots.
7285
7286 @<If consecutive knots are equal, join them explicitly@>=
7287 p=knots;
7288 do {  
7289   q=link(p);
7290   if ( x_coord(p)==x_coord(q) && y_coord(p)==y_coord(q) && right_type(p)>mp_explicit ) { 
7291     right_type(p)=mp_explicit;
7292     if ( left_type(p)==mp_open ) { 
7293       left_type(p)=mp_curl; left_curl(p)=unity;
7294     }
7295     left_type(q)=mp_explicit;
7296     if ( right_type(q)==mp_open ) { 
7297       right_type(q)=mp_curl; right_curl(q)=unity;
7298     }
7299     right_x(p)=x_coord(p); left_x(q)=x_coord(p);
7300     right_y(p)=y_coord(p); left_y(q)=y_coord(p);
7301   }
7302   p=q;
7303 } while (p!=knots)
7304
7305 @ If there are no breakpoints, it is necessary to compute the direction
7306 angles around an entire cycle. In this case the |left_type| of the first
7307 node is temporarily changed to |end_cycle|.
7308
7309 @<Find the first breakpoint, |h|, on the path...@>=
7310 h=knots;
7311 while (1) { 
7312   if ( left_type(h)!=mp_open ) break;
7313   if ( right_type(h)!=mp_open ) break;
7314   h=link(h);
7315   if ( h==knots ) { 
7316     left_type(h)=mp_end_cycle; break;
7317   }
7318 }
7319
7320 @ If |right_type(p)<given| and |q=link(p)|, we must have
7321 |right_type(p)=left_type(q)=mp_explicit| or |endpoint|.
7322
7323 @<Fill in the control points between |p| and the next breakpoint...@>=
7324 q=link(p);
7325 if ( right_type(p)>=mp_given ) { 
7326   while ( (left_type(q)==mp_open)&&(right_type(q)==mp_open) ) q=link(q);
7327   @<Fill in the control information between
7328     consecutive breakpoints |p| and |q|@>;
7329 } else if ( right_type(p)==mp_endpoint ) {
7330   @<Give reasonable values for the unused control points between |p| and~|q|@>;
7331 }
7332 p=q
7333
7334 @ This step makes it possible to transform an explicitly computed path without
7335 checking the |left_type| and |right_type| fields.
7336
7337 @<Give reasonable values for the unused control points between |p| and~|q|@>=
7338
7339   right_x(p)=x_coord(p); right_y(p)=y_coord(p);
7340   left_x(q)=x_coord(q); left_y(q)=y_coord(q);
7341 }
7342
7343 @ Before we can go further into the way choices are made, we need to
7344 consider the underlying theory. The basic ideas implemented in |make_choices|
7345 are due to John Hobby, who introduced the notion of ``mock curvature''
7346 @^Hobby, John Douglas@>
7347 at a knot. Angles are chosen so that they preserve mock curvature when
7348 a knot is passed, and this has been found to produce excellent results.
7349
7350 It is convenient to introduce some notations that simplify the necessary
7351 formulas. Let $d_{k,k+1}=\vert z\k-z_k\vert$ be the (nonzero) distance
7352 between knots |k| and |k+1|; and let
7353 $${z\k-z_k\over z_k-z_{k-1}}={d_{k,k+1}\over d_{k-1,k}}e^{i\psi_k}$$
7354 so that a polygonal line from $z_{k-1}$ to $z_k$ to $z\k$ turns left
7355 through an angle of~$\psi_k$. We assume that $\vert\psi_k\vert\L180^\circ$.
7356 The control points for the spline from $z_k$ to $z\k$ will be denoted by
7357 $$\eqalign{z_k^+&=z_k+
7358   \textstyle{1\over3}\rho_k e^{i\theta_k}(z\k-z_k),\cr
7359  z\k^-&=z\k-
7360   \textstyle{1\over3}\sigma\k e^{-i\phi\k}(z\k-z_k),\cr}$$
7361 where $\rho_k$ and $\sigma\k$ are nonnegative ``velocity ratios'' at the
7362 beginning and end of the curve, while $\theta_k$ and $\phi\k$ are the
7363 corresponding ``offset angles.'' These angles satisfy the condition
7364 $$\theta_k+\phi_k+\psi_k=0,\eqno(*)$$
7365 whenever the curve leaves an intermediate knot~|k| in the direction that
7366 it enters.
7367
7368 @ Let $\alpha_k$ and $\beta\k$ be the reciprocals of the ``tension'' of
7369 the curve at its beginning and ending points. This means that
7370 $\rho_k=\alpha_k f(\theta_k,\phi\k)$ and $\sigma\k=\beta\k f(\phi\k,\theta_k)$,
7371 where $f(\theta,\phi)$ is \MP's standard velocity function defined in
7372 the |velocity| subroutine. The cubic spline $B(z_k^{\phantom+},z_k^+,
7373 z\k^-,z\k^{\phantom+};t)$
7374 has curvature
7375 @^curvature@>
7376 $${2\sigma\k\sin(\theta_k+\phi\k)-6\sin\theta_k\over\rho_k^2d_{k,k+1}}
7377 \qquad{\rm and}\qquad
7378 {2\rho_k\sin(\theta_k+\phi\k)-6\sin\phi\k\over\sigma\k^2d_{k,k+1}}$$
7379 at |t=0| and |t=1|, respectively. The mock curvature is the linear
7380 @^mock curvature@>
7381 approximation to this true curvature that arises in the limit for
7382 small $\theta_k$ and~$\phi\k$, if second-order terms are discarded.
7383 The standard velocity function satisfies
7384 $$f(\theta,\phi)=1+O(\theta^2+\theta\phi+\phi^2);$$
7385 hence the mock curvatures are respectively
7386 $${2\beta\k(\theta_k+\phi\k)-6\theta_k\over\alpha_k^2d_{k,k+1}}
7387 \qquad{\rm and}\qquad
7388 {2\alpha_k(\theta_k+\phi\k)-6\phi\k\over\beta\k^2d_{k,k+1}}.\eqno(**)$$
7389
7390 @ The turning angles $\psi_k$ are given, and equation $(*)$ above
7391 determines $\phi_k$ when $\theta_k$ is known, so the task of
7392 angle selection is essentially to choose appropriate values for each
7393 $\theta_k$. When equation~$(*)$ is used to eliminate $\phi$~variables
7394 from $(**)$, we obtain a system of linear equations of the form
7395 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7396 where
7397 $$A_k={\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7398 \qquad B_k={3-\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7399 \qquad C_k={3-\beta\k\over\alpha_k^2d_{k,k+1}},
7400 \qquad D_k={\beta\k\over\alpha_k^2d_{k,k+1}}.$$
7401 The tensions are always $3\over4$ or more, hence each $\alpha$ and~$\beta$
7402 will be at most $4\over3$. It follows that $B_k\G{5\over4}A_k$ and
7403 $C_k\G{5\over4}D_k$; hence the equations are diagonally dominant;
7404 hence they have a unique solution. Moreover, in most cases the tensions
7405 are equal to~1, so that $B_k=2A_k$ and $C_k=2D_k$. This makes the
7406 solution numerically stable, and there is an exponential damping
7407 effect: The data at knot $k\pm j$ affects the angle at knot~$k$ by
7408 a factor of~$O(2^{-j})$.
7409
7410 @ However, we still must consider the angles at the starting and ending
7411 knots of a non-cyclic path. These angles might be given explicitly, or
7412 they might be specified implicitly in terms of an amount of ``curl.''
7413
7414 Let's assume that angles need to be determined for a non-cyclic path
7415 starting at $z_0$ and ending at~$z_n$. Then equations of the form
7416 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta_{k+1}=R_k$$
7417 have been given for $0<k<n$, and it will be convenient to introduce
7418 equations of the same form for $k=0$ and $k=n$, where
7419 $$A_0=B_0=C_n=D_n=0.$$
7420 If $\theta_0$ is supposed to have a given value $E_0$, we simply
7421 define $C_0=0$, $D_0=0$, and $R_0=E_0$. Otherwise a curl
7422 parameter, $\gamma_0$, has been specified at~$z_0$; this means
7423 that the mock curvature at $z_0$ should be $\gamma_0$ times the
7424 mock curvature at $z_1$; i.e.,
7425 $${2\beta_1(\theta_0+\phi_1)-6\theta_0\over\alpha_0^2d_{01}}
7426 =\gamma_0{2\alpha_0(\theta_0+\phi_1)-6\phi_1\over\beta_1^2d_{01}}.$$
7427 This equation simplifies to
7428 $$(\alpha_0\chi_0+3-\beta_1)\theta_0+
7429  \bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\theta_1=
7430  -\bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\psi_1,$$
7431 where $\chi_0=\alpha_0^2\gamma_0/\beta_1^2$; so we can set $C_0=
7432 \chi_0\alpha_0+3-\beta_1$, $D_0=(3-\alpha_0)\chi_0+\beta_1$, $R_0=-D_0\psi_1$.
7433 It can be shown that $C_0>0$ and $C_0B_1-A_1D_0>0$ when $\gamma_0\G0$,
7434 hence the linear equations remain nonsingular.
7435
7436 Similar considerations apply at the right end, when the final angle $\phi_n$
7437 may or may not need to be determined. It is convenient to let $\psi_n=0$,
7438 hence $\theta_n=-\phi_n$. We either have an explicit equation $\theta_n=E_n$,
7439 or we have
7440 $$\bigl((3-\beta_n)\chi_n+\alpha_{n-1}\bigr)\theta_{n-1}+
7441 (\beta_n\chi_n+3-\alpha_{n-1})\theta_n=0,\qquad
7442   \chi_n={\beta_n^2\gamma_n\over\alpha_{n-1}^2}.$$
7443
7444 When |make_choices| chooses angles, it must compute the coefficients of
7445 these linear equations, then solve the equations. To compute the coefficients,
7446 it is necessary to compute arctangents of the given turning angles~$\psi_k$.
7447 When the equations are solved, the chosen directions $\theta_k$ are put
7448 back into the form of control points by essentially computing sines and
7449 cosines.
7450
7451 @ OK, we are ready to make the hard choices of |make_choices|.
7452 Most of the work is relegated to an auxiliary procedure
7453 called |solve_choices|, which has been introduced to keep
7454 |make_choices| from being extremely long.
7455
7456 @<Fill in the control information between...@>=
7457 @<Calculate the turning angles $\psi_k$ and the distances $d_{k,k+1}$;
7458   set $n$ to the length of the path@>;
7459 @<Remove |open| types at the breakpoints@>;
7460 mp_solve_choices(mp, p,q,n)
7461
7462 @ It's convenient to precompute quantities that will be needed several
7463 times later. The values of |delta_x[k]| and |delta_y[k]| will be the
7464 coordinates of $z\k-z_k$, and the magnitude of this vector will be
7465 |delta[k]=@t$d_{k,k+1}$@>|. The path angle $\psi_k$ between $z_k-z_{k-1}$
7466 and $z\k-z_k$ will be stored in |psi[k]|.
7467
7468 @<Glob...@>=
7469 int path_size; /* maximum number of knots between breakpoints of a path */
7470 scaled *delta_x;
7471 scaled *delta_y;
7472 scaled *delta; /* knot differences */
7473 angle  *psi; /* turning angles */
7474
7475 @ @<Allocate or initialize ...@>=
7476 mp->delta_x = NULL;
7477 mp->delta_y = NULL;
7478 mp->delta = NULL;
7479 mp->psi = NULL;
7480
7481 @ @<Dealloc variables@>=
7482 xfree(mp->delta_x);
7483 xfree(mp->delta_y);
7484 xfree(mp->delta);
7485 xfree(mp->psi);
7486
7487 @ @<Other local variables for |make_choices|@>=
7488   int k,n; /* current and final knot numbers */
7489   pointer s,t; /* registers for list traversal */
7490   scaled delx,dely; /* directions where |open| meets |explicit| */
7491   fraction sine,cosine; /* trig functions of various angles */
7492
7493 @ @<Calculate the turning angles...@>=
7494 {
7495 RESTART:
7496   k=0; s=p; n=mp->path_size;
7497   do {  
7498     t=link(s);
7499     mp->delta_x[k]=x_coord(t)-x_coord(s);
7500     mp->delta_y[k]=y_coord(t)-y_coord(s);
7501     mp->delta[k]=mp_pyth_add(mp, mp->delta_x[k],mp->delta_y[k]);
7502     if ( k>0 ) { 
7503       sine=mp_make_fraction(mp, mp->delta_y[k-1],mp->delta[k-1]);
7504       cosine=mp_make_fraction(mp, mp->delta_x[k-1],mp->delta[k-1]);
7505       mp->psi[k]=mp_n_arg(mp, mp_take_fraction(mp, mp->delta_x[k],cosine)+
7506         mp_take_fraction(mp, mp->delta_y[k],sine),
7507         mp_take_fraction(mp, mp->delta_y[k],cosine)-
7508           mp_take_fraction(mp, mp->delta_x[k],sine));
7509     }
7510     incr(k); s=t;
7511     if ( k==mp->path_size ) {
7512       mp_reallocate_paths(mp, mp->path_size+(mp->path_size>>2));
7513       goto RESTART; /* retry, loop size has changed */
7514     }
7515     if ( s==q ) n=k;
7516   } while (!((k>=n)&&(left_type(s)!=mp_end_cycle)));
7517   if ( k==n ) mp->psi[n]=0; else mp->psi[k]=mp->psi[1];
7518 }
7519
7520 @ When we get to this point of the code, |right_type(p)| is either
7521 |given| or |curl| or |open|. If it is |open|, we must have
7522 |left_type(p)=mp_end_cycle| or |left_type(p)=mp_explicit|. In the latter
7523 case, the |open| type is converted to |given|; however, if the
7524 velocity coming into this knot is zero, the |open| type is
7525 converted to a |curl|, since we don't know the incoming direction.
7526
7527 Similarly, |left_type(q)| is either |given| or |curl| or |open| or
7528 |mp_end_cycle|. The |open| possibility is reduced either to |given| or to |curl|.
7529
7530 @<Remove |open| types at the breakpoints@>=
7531 if ( left_type(q)==mp_open ) { 
7532   delx=right_x(q)-x_coord(q); dely=right_y(q)-y_coord(q);
7533   if ( (delx==0)&&(dely==0) ) { 
7534     left_type(q)=mp_curl; left_curl(q)=unity;
7535   } else { 
7536     left_type(q)=mp_given; left_given(q)=mp_n_arg(mp, delx,dely);
7537   }
7538 }
7539 if ( (right_type(p)==mp_open)&&(left_type(p)==mp_explicit) ) { 
7540   delx=x_coord(p)-left_x(p); dely=y_coord(p)-left_y(p);
7541   if ( (delx==0)&&(dely==0) ) { 
7542     right_type(p)=mp_curl; right_curl(p)=unity;
7543   } else { 
7544     right_type(p)=mp_given; right_given(p)=mp_n_arg(mp, delx,dely);
7545   }
7546 }
7547
7548 @ Linear equations need to be solved whenever |n>1|; and also when |n=1|
7549 and exactly one of the breakpoints involves a curl. The simplest case occurs
7550 when |n=1| and there is a curl at both breakpoints; then we simply draw
7551 a straight line.
7552
7553 But before coding up the simple cases, we might as well face the general case,
7554 since we must deal with it sooner or later, and since the general case
7555 is likely to give some insight into the way simple cases can be handled best.
7556
7557 When there is no cycle, the linear equations to be solved form a tridiagonal
7558 system, and we can apply the standard technique of Gaussian elimination
7559 to convert that system to a sequence of equations of the form
7560 $$\theta_0+u_0\theta_1=v_0,\quad
7561 \theta_1+u_1\theta_2=v_1,\quad\ldots,\quad
7562 \theta_{n-1}+u_{n-1}\theta_n=v_{n-1},\quad
7563 \theta_n=v_n.$$
7564 It is possible to do this diagonalization while generating the equations.
7565 Once $\theta_n$ is known, it is easy to determine $\theta_{n-1}$, \dots,
7566 $\theta_1$, $\theta_0$; thus, the equations will be solved.
7567
7568 The procedure is slightly more complex when there is a cycle, but the
7569 basic idea will be nearly the same. In the cyclic case the right-hand
7570 sides will be $v_k+w_k\theta_0$ instead of simply $v_k$, and we will start
7571 the process off with $u_0=v_0=0$, $w_0=1$. The final equation will be not
7572 $\theta_n=v_n$ but $\theta_n+u_n\theta_1=v_n+w_n\theta_0$; an appropriate
7573 ending routine will take account of the fact that $\theta_n=\theta_0$ and
7574 eliminate the $w$'s from the system, after which the solution can be
7575 obtained as before.
7576
7577 When $u_k$, $v_k$, and $w_k$ are being computed, the three pointer
7578 variables |r|, |s|,~|t| will point respectively to knots |k-1|, |k|,
7579 and~|k+1|. The $u$'s and $w$'s are scaled by $2^{28}$, i.e., they are
7580 of type |fraction|; the $\theta$'s and $v$'s are of type |angle|.
7581
7582 @<Glob...@>=
7583 angle *theta; /* values of $\theta_k$ */
7584 fraction *uu; /* values of $u_k$ */
7585 angle *vv; /* values of $v_k$ */
7586 fraction *ww; /* values of $w_k$ */
7587
7588 @ @<Allocate or initialize ...@>=
7589 mp->theta = NULL;
7590 mp->uu = NULL;
7591 mp->vv = NULL;
7592 mp->ww = NULL;
7593
7594 @ @<Dealloc variables@>=
7595 xfree(mp->theta);
7596 xfree(mp->uu);
7597 xfree(mp->vv);
7598 xfree(mp->ww);
7599
7600 @ @<Declare |mp_reallocate| functions@>=
7601 void mp_reallocate_paths (MP mp, int l);
7602
7603 @ @c
7604 void mp_reallocate_paths (MP mp, int l) {
7605   XREALLOC (mp->delta_x, l, scaled);
7606   XREALLOC (mp->delta_y, l, scaled);
7607   XREALLOC (mp->delta,   l, scaled);
7608   XREALLOC (mp->psi,     l, angle);
7609   XREALLOC (mp->theta,   l, angle);
7610   XREALLOC (mp->uu,      l, fraction);
7611   XREALLOC (mp->vv,      l, angle);
7612   XREALLOC (mp->ww,      l, fraction);
7613   mp->path_size = l;
7614 }
7615
7616 @ Our immediate problem is to get the ball rolling by setting up the
7617 first equation or by realizing that no equations are needed, and to fit
7618 this initialization into a framework suitable for the overall computation.
7619
7620 @<Declare the procedure called |solve_choices|@>=
7621 @<Declare subroutines needed by |solve_choices|@>;
7622 void mp_solve_choices (MP mp,pointer p, pointer q, halfword n) {
7623   int k; /* current knot number */
7624   pointer r,s,t; /* registers for list traversal */
7625   @<Other local variables for |solve_choices|@>;
7626   k=0; s=p; r=0;
7627   while (1) { 
7628     t=link(s);
7629     if ( k==0 ) {
7630       @<Get the linear equations started; or |return|
7631         with the control points in place, if linear equations
7632         needn't be solved@>
7633     } else  { 
7634       switch (left_type(s)) {
7635       case mp_end_cycle: case mp_open:
7636         @<Set up equation to match mock curvatures
7637           at $z_k$; then |goto found| with $\theta_n$
7638           adjusted to equal $\theta_0$, if a cycle has ended@>;
7639         break;
7640       case mp_curl:
7641         @<Set up equation for a curl at $\theta_n$
7642           and |goto found|@>;
7643         break;
7644       case mp_given:
7645         @<Calculate the given value of $\theta_n$
7646           and |goto found|@>;
7647         break;
7648       } /* there are no other cases */
7649     }
7650     r=s; s=t; incr(k);
7651   }
7652 FOUND:
7653   @<Finish choosing angles and assigning control points@>;
7654 }
7655
7656 @ On the first time through the loop, we have |k=0| and |r| is not yet
7657 defined. The first linear equation, if any, will have $A_0=B_0=0$.
7658
7659 @<Get the linear equations started...@>=
7660 switch (right_type(s)) {
7661 case mp_given: 
7662   if ( left_type(t)==mp_given ) {
7663     @<Reduce to simple case of two givens  and |return|@>
7664   } else {
7665     @<Set up the equation for a given value of $\theta_0$@>;
7666   }
7667   break;
7668 case mp_curl: 
7669   if ( left_type(t)==mp_curl ) {
7670     @<Reduce to simple case of straight line and |return|@>
7671   } else {
7672     @<Set up the equation for a curl at $\theta_0$@>;
7673   }
7674   break;
7675 case mp_open: 
7676   mp->uu[0]=0; mp->vv[0]=0; mp->ww[0]=fraction_one;
7677   /* this begins a cycle */
7678   break;
7679 } /* there are no other cases */
7680
7681 @ The general equation that specifies equality of mock curvature at $z_k$ is
7682 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7683 as derived above. We want to combine this with the already-derived equation
7684 $\theta_{k-1}+u_{k-1}\theta_k=v_{k-1}+w_{k-1}\theta_0$ in order to obtain
7685 a new equation
7686 $\theta_k+u_k\theta\k=v_k+w_k\theta_0$. This can be done by dividing the
7687 equation
7688 $$(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}
7689     -A_kw_{k-1}\theta_0$$
7690 by $B_k-u_{k-1}A_k+C_k$. The trick is to do this carefully with
7691 fixed-point arithmetic, avoiding the chance of overflow while retaining
7692 suitable precision.
7693
7694 The calculations will be performed in several registers that
7695 provide temporary storage for intermediate quantities.
7696
7697 @<Other local variables for |solve_choices|@>=
7698 fraction aa,bb,cc,ff,acc; /* temporary registers */
7699 scaled dd,ee; /* likewise, but |scaled| */
7700 scaled lt,rt; /* tension values */
7701
7702 @ @<Set up equation to match mock curvatures...@>=
7703 { @<Calculate the values $\\{aa}=A_k/B_k$, $\\{bb}=D_k/C_k$,
7704     $\\{dd}=(3-\alpha_{k-1})d_{k,k+1}$, $\\{ee}=(3-\beta\k)d_{k-1,k}$,
7705     and $\\{cc}=(B_k-u_{k-1}A_k)/B_k$@>;
7706   @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>;
7707   mp->uu[k]=mp_take_fraction(mp, ff,bb);
7708   @<Calculate the values of $v_k$ and $w_k$@>;
7709   if ( left_type(s)==mp_end_cycle ) {
7710     @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>;
7711   }
7712 }
7713
7714 @ Since tension values are never less than 3/4, the values |aa| and
7715 |bb| computed here are never more than 4/5.
7716
7717 @<Calculate the values $\\{aa}=...@>=
7718 if ( abs(right_tension(r))==unity) { 
7719   aa=fraction_half; dd=2*mp->delta[k];
7720 } else { 
7721   aa=mp_make_fraction(mp, unity,3*abs(right_tension(r))-unity);
7722   dd=mp_take_fraction(mp, mp->delta[k],
7723     fraction_three-mp_make_fraction(mp, unity,abs(right_tension(r))));
7724 }
7725 if ( abs(left_tension(t))==unity ){ 
7726   bb=fraction_half; ee=2*mp->delta[k-1];
7727 } else { 
7728   bb=mp_make_fraction(mp, unity,3*abs(left_tension(t))-unity);
7729   ee=mp_take_fraction(mp, mp->delta[k-1],
7730     fraction_three-mp_make_fraction(mp, unity,abs(left_tension(t))));
7731 }
7732 cc=fraction_one-mp_take_fraction(mp, mp->uu[k-1],aa)
7733
7734 @ The ratio to be calculated in this step can be written in the form
7735 $$\beta_k^2\cdot\\{ee}\over\beta_k^2\cdot\\{ee}+\alpha_k^2\cdot
7736   \\{cc}\cdot\\{dd},$$
7737 because of the quantities just calculated. The values of |dd| and |ee|
7738 will not be needed after this step has been performed.
7739
7740 @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>=
7741 dd=mp_take_fraction(mp, dd,cc); lt=abs(left_tension(s)); rt=abs(right_tension(s));
7742 if ( lt!=rt ) { /* $\beta_k^{-1}\ne\alpha_k^{-1}$ */
7743   if ( lt<rt ) { 
7744     ff=mp_make_fraction(mp, lt,rt);
7745     ff=mp_take_fraction(mp, ff,ff); /* $\alpha_k^2/\beta_k^2$ */
7746     dd=mp_take_fraction(mp, dd,ff);
7747   } else { 
7748     ff=mp_make_fraction(mp, rt,lt);
7749     ff=mp_take_fraction(mp, ff,ff); /* $\beta_k^2/\alpha_k^2$ */
7750     ee=mp_take_fraction(mp, ee,ff);
7751   }
7752 }
7753 ff=mp_make_fraction(mp, ee,ee+dd)
7754
7755 @ The value of $u_{k-1}$ will be |<=1| except when $k=1$ and the previous
7756 equation was specified by a curl. In that case we must use a special
7757 method of computation to prevent overflow.
7758
7759 Fortunately, the calculations turn out to be even simpler in this ``hard''
7760 case. The curl equation makes $w_0=0$ and $v_0=-u_0\psi_1$, hence
7761 $-B_1\psi_1-A_1v_0=-(B_1-u_0A_1)\psi_1=-\\{cc}\cdot B_1\psi_1$.
7762
7763 @<Calculate the values of $v_k$ and $w_k$@>=
7764 acc=-mp_take_fraction(mp, mp->psi[k+1],mp->uu[k]);
7765 if ( right_type(r)==mp_curl ) { 
7766   mp->ww[k]=0;
7767   mp->vv[k]=acc-mp_take_fraction(mp, mp->psi[1],fraction_one-ff);
7768 } else { 
7769   ff=mp_make_fraction(mp, fraction_one-ff,cc); /* this is
7770     $B_k/(C_k+B_k-u_{k-1}A_k)<5$ */
7771   acc=acc-mp_take_fraction(mp, mp->psi[k],ff);
7772   ff=mp_take_fraction(mp, ff,aa); /* this is $A_k/(C_k+B_k-u_{k-1}A_k)$ */
7773   mp->vv[k]=acc-mp_take_fraction(mp, mp->vv[k-1],ff);
7774   if ( mp->ww[k-1]==0 ) mp->ww[k]=0;
7775   else mp->ww[k]=-mp_take_fraction(mp, mp->ww[k-1],ff);
7776 }
7777
7778 @ When a complete cycle has been traversed, we have $\theta_k+u_k\theta\k=
7779 v_k+w_k\theta_0$, for |1<=k<=n|. We would like to determine the value of
7780 $\theta_n$ and reduce the system to the form $\theta_k+u_k\theta\k=v_k$
7781 for |0<=k<n|, so that the cyclic case can be finished up just as if there
7782 were no cycle.
7783
7784 The idea in the following code is to observe that
7785 $$\eqalign{\theta_n&=v_n+w_n\theta_0-u_n\theta_1=\cdots\cr
7786 &=v_n+w_n\theta_0-u_n\bigl(v_1+w_1\theta_0-u_1(v_2+\cdots
7787   -u_{n-2}(v_{n-1}+w_{n-1}\theta_0-u_{n-1}\theta_0))\bigr),\cr}$$
7788 so we can solve for $\theta_n=\theta_0$.
7789
7790 @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>=
7791
7792 aa=0; bb=fraction_one; /* we have |k=n| */
7793 do {  decr(k);
7794 if ( k==0 ) k=n;
7795   aa=mp->vv[k]-mp_take_fraction(mp, aa,mp->uu[k]);
7796   bb=mp->ww[k]-mp_take_fraction(mp, bb,mp->uu[k]);
7797 } while (k!=n); /* now $\theta_n=\\{aa}+\\{bb}\cdot\theta_n$ */
7798 aa=mp_make_fraction(mp, aa,fraction_one-bb);
7799 mp->theta[n]=aa; mp->vv[0]=aa;
7800 for (k=1;k<=n-1;k++) {
7801   mp->vv[k]=mp->vv[k]+mp_take_fraction(mp, aa,mp->ww[k]);
7802 }
7803 goto FOUND;
7804 }
7805
7806 @ @d reduce_angle(A) if ( abs((A))>one_eighty_deg ) {
7807   if ( (A)>0 ) (A)=(A)-three_sixty_deg; else (A)=(A)+three_sixty_deg; }
7808
7809 @<Calculate the given value of $\theta_n$...@>=
7810
7811   mp->theta[n]=left_given(s)-mp_n_arg(mp, mp->delta_x[n-1],mp->delta_y[n-1]);
7812   reduce_angle(mp->theta[n]);
7813   goto FOUND;
7814 }
7815
7816 @ @<Set up the equation for a given value of $\theta_0$@>=
7817
7818   mp->vv[0]=right_given(s)-mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7819   reduce_angle(mp->vv[0]);
7820   mp->uu[0]=0; mp->ww[0]=0;
7821 }
7822
7823 @ @<Set up the equation for a curl at $\theta_0$@>=
7824 { cc=right_curl(s); lt=abs(left_tension(t)); rt=abs(right_tension(s));
7825   if ( (rt==unity)&&(lt==unity) )
7826     mp->uu[0]=mp_make_fraction(mp, cc+cc+unity,cc+two);
7827   else 
7828     mp->uu[0]=mp_curl_ratio(mp, cc,rt,lt);
7829   mp->vv[0]=-mp_take_fraction(mp, mp->psi[1],mp->uu[0]); mp->ww[0]=0;
7830 }
7831
7832 @ @<Set up equation for a curl at $\theta_n$...@>=
7833 { cc=left_curl(s); lt=abs(left_tension(s)); rt=abs(right_tension(r));
7834   if ( (rt==unity)&&(lt==unity) )
7835     ff=mp_make_fraction(mp, cc+cc+unity,cc+two);
7836   else 
7837     ff=mp_curl_ratio(mp, cc,lt,rt);
7838   mp->theta[n]=-mp_make_fraction(mp, mp_take_fraction(mp, mp->vv[n-1],ff),
7839     fraction_one-mp_take_fraction(mp, ff,mp->uu[n-1]));
7840   goto FOUND;
7841 }
7842
7843 @ The |curl_ratio| subroutine has three arguments, which our previous notation
7844 encourages us to call $\gamma$, $\alpha^{-1}$, and $\beta^{-1}$. It is
7845 a somewhat tedious program to calculate
7846 $${(3-\alpha)\alpha^2\gamma+\beta^3\over
7847   \alpha^3\gamma+(3-\beta)\beta^2},$$
7848 with the result reduced to 4 if it exceeds 4. (This reduction of curl
7849 is necessary only if the curl and tension are both large.)
7850 The values of $\alpha$ and $\beta$ will be at most~4/3.
7851
7852 @<Declare subroutines needed by |solve_choices|@>=
7853 fraction mp_curl_ratio (MP mp,scaled gamma, scaled a_tension, 
7854                         scaled b_tension) {
7855   fraction alpha,beta,num,denom,ff; /* registers */
7856   alpha=mp_make_fraction(mp, unity,a_tension);
7857   beta=mp_make_fraction(mp, unity,b_tension);
7858   if ( alpha<=beta ) {
7859     ff=mp_make_fraction(mp, alpha,beta); ff=mp_take_fraction(mp, ff,ff);
7860     gamma=mp_take_fraction(mp, gamma,ff);
7861     beta=beta / 010000; /* convert |fraction| to |scaled| */
7862     denom=mp_take_fraction(mp, gamma,alpha)+three-beta;
7863     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7864   } else { 
7865     ff=mp_make_fraction(mp, beta,alpha); ff=mp_take_fraction(mp, ff,ff);
7866     beta=mp_take_fraction(mp, beta,ff) / 010000; /* convert |fraction| to |scaled| */
7867     denom=mp_take_fraction(mp, gamma,alpha)+(ff / 1365)-beta;
7868       /* $1365\approx 2^{12}/3$ */
7869     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7870   }
7871   if ( num>=denom+denom+denom+denom ) return fraction_four;
7872   else return mp_make_fraction(mp, num,denom);
7873 }
7874
7875 @ We're in the home stretch now.
7876
7877 @<Finish choosing angles and assigning control points@>=
7878 for (k=n-1;k>=0;k--) {
7879   mp->theta[k]=mp->vv[k]-mp_take_fraction(mp,mp->theta[k+1],mp->uu[k]);
7880 }
7881 s=p; k=0;
7882 do {  
7883   t=link(s);
7884   mp_n_sin_cos(mp, mp->theta[k]); mp->st=mp->n_sin; mp->ct=mp->n_cos;
7885   mp_n_sin_cos(mp, -mp->psi[k+1]-mp->theta[k+1]); mp->sf=mp->n_sin; mp->cf=mp->n_cos;
7886   mp_set_controls(mp, s,t,k);
7887   incr(k); s=t;
7888 } while (k!=n)
7889
7890 @ The |set_controls| routine actually puts the control points into
7891 a pair of consecutive nodes |p| and~|q|. Global variables are used to
7892 record the values of $\sin\theta$, $\cos\theta$, $\sin\phi$, and
7893 $\cos\phi$ needed in this calculation.
7894
7895 @<Glob...@>=
7896 fraction st;
7897 fraction ct;
7898 fraction sf;
7899 fraction cf; /* sines and cosines */
7900
7901 @ @<Declare subroutines needed by |solve_choices|@>=
7902 void mp_set_controls (MP mp,pointer p, pointer q, integer k) {
7903   fraction rr,ss; /* velocities, divided by thrice the tension */
7904   scaled lt,rt; /* tensions */
7905   fraction sine; /* $\sin(\theta+\phi)$ */
7906   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7907   rr=mp_velocity(mp, mp->st,mp->ct,mp->sf,mp->cf,rt);
7908   ss=mp_velocity(mp, mp->sf,mp->cf,mp->st,mp->ct,lt);
7909   if ( (right_tension(p)<0)||(left_tension(q)<0) ) {
7910     @<Decrease the velocities,
7911       if necessary, to stay inside the bounding triangle@>;
7912   }
7913   right_x(p)=x_coord(p)+mp_take_fraction(mp, 
7914                           mp_take_fraction(mp, mp->delta_x[k],mp->ct)-
7915                           mp_take_fraction(mp, mp->delta_y[k],mp->st),rr);
7916   right_y(p)=y_coord(p)+mp_take_fraction(mp, 
7917                           mp_take_fraction(mp, mp->delta_y[k],mp->ct)+
7918                           mp_take_fraction(mp, mp->delta_x[k],mp->st),rr);
7919   left_x(q)=x_coord(q)-mp_take_fraction(mp, 
7920                          mp_take_fraction(mp, mp->delta_x[k],mp->cf)+
7921                          mp_take_fraction(mp, mp->delta_y[k],mp->sf),ss);
7922   left_y(q)=y_coord(q)-mp_take_fraction(mp, 
7923                          mp_take_fraction(mp, mp->delta_y[k],mp->cf)-
7924                          mp_take_fraction(mp, mp->delta_x[k],mp->sf),ss);
7925   right_type(p)=mp_explicit; left_type(q)=mp_explicit;
7926 }
7927
7928 @ The boundedness conditions $\\{rr}\L\sin\phi\,/\sin(\theta+\phi)$ and
7929 $\\{ss}\L\sin\theta\,/\sin(\theta+\phi)$ are to be enforced if $\sin\theta$,
7930 $\sin\phi$, and $\sin(\theta+\phi)$ all have the same sign. Otherwise
7931 there is no ``bounding triangle.''
7932 @:at_least_}{\&{atleast} primitive@>
7933
7934 @<Decrease the velocities, if necessary...@>=
7935 if (((mp->st>=0)&&(mp->sf>=0))||((mp->st<=0)&&(mp->sf<=0)) ) {
7936   sine=mp_take_fraction(mp, abs(mp->st),mp->cf)+
7937                             mp_take_fraction(mp, abs(mp->sf),mp->ct);
7938   if ( sine>0 ) {
7939     sine=mp_take_fraction(mp, sine,fraction_one+unity); /* safety factor */
7940     if ( right_tension(p)<0 )
7941      if ( mp_ab_vs_cd(mp, abs(mp->sf),fraction_one,rr,sine)<0 )
7942       rr=mp_make_fraction(mp, abs(mp->sf),sine);
7943     if ( left_tension(q)<0 )
7944      if ( mp_ab_vs_cd(mp, abs(mp->st),fraction_one,ss,sine)<0 )
7945       ss=mp_make_fraction(mp, abs(mp->st),sine);
7946   }
7947 }
7948
7949 @ Only the simple cases remain to be handled.
7950
7951 @<Reduce to simple case of two givens and |return|@>=
7952
7953   aa=mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7954   mp_n_sin_cos(mp, right_given(p)-aa); mp->ct=mp->n_cos; mp->st=mp->n_sin;
7955   mp_n_sin_cos(mp, left_given(q)-aa); mp->cf=mp->n_cos; mp->sf=-mp->n_sin;
7956   mp_set_controls(mp, p,q,0); return;
7957 }
7958
7959 @ @<Reduce to simple case of straight line and |return|@>=
7960
7961   right_type(p)=mp_explicit; left_type(q)=mp_explicit;
7962   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7963   if ( rt==unity ) {
7964     if ( mp->delta_x[0]>=0 ) right_x(p)=x_coord(p)+((mp->delta_x[0]+1) / 3);
7965     else right_x(p)=x_coord(p)+((mp->delta_x[0]-1) / 3);
7966     if ( mp->delta_y[0]>=0 ) right_y(p)=y_coord(p)+((mp->delta_y[0]+1) / 3);
7967     else right_y(p)=y_coord(p)+((mp->delta_y[0]-1) / 3);
7968   } else { 
7969     ff=mp_make_fraction(mp, unity,3*rt); /* $\alpha/3$ */
7970     right_x(p)=x_coord(p)+mp_take_fraction(mp, mp->delta_x[0],ff);
7971     right_y(p)=y_coord(p)+mp_take_fraction(mp, mp->delta_y[0],ff);
7972   }
7973   if ( lt==unity ) {
7974     if ( mp->delta_x[0]>=0 ) left_x(q)=x_coord(q)-((mp->delta_x[0]+1) / 3);
7975     else left_x(q)=x_coord(q)-((mp->delta_x[0]-1) / 3);
7976     if ( mp->delta_y[0]>=0 ) left_y(q)=y_coord(q)-((mp->delta_y[0]+1) / 3);
7977     else left_y(q)=y_coord(q)-((mp->delta_y[0]-1) / 3);
7978   } else  { 
7979     ff=mp_make_fraction(mp, unity,3*lt); /* $\beta/3$ */
7980     left_x(q)=x_coord(q)-mp_take_fraction(mp, mp->delta_x[0],ff);
7981     left_y(q)=y_coord(q)-mp_take_fraction(mp, mp->delta_y[0],ff);
7982   }
7983   return;
7984 }
7985
7986 @* \[19] Measuring paths.
7987 \MP's \&{llcorner}, \&{lrcorner}, \&{ulcorner}, and \&{urcorner} operators
7988 allow the user to measure the bounding box of anything that can go into a
7989 picture.  It's easy to get rough bounds on the $x$ and $y$ extent of a path
7990 by just finding the bounding box of the knots and the control points. We
7991 need a more accurate version of the bounding box, but we can still use the
7992 easy estimate to save time by focusing on the interesting parts of the path.
7993
7994 @ Computing an accurate bounding box involves a theme that will come up again
7995 and again. Given a Bernshte{\u\i}n polynomial
7996 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
7997 $$B(z_0,z_1,\ldots,z_n;t)=\sum_k{n\choose k}t^k(1-t)^{n-k}z_k,$$
7998 we can conveniently bisect its range as follows:
7999
8000 \smallskip
8001 \textindent{1)} Let $z_k^{(0)}=z_k$, for |0<=k<=n|.
8002
8003 \smallskip
8004 \textindent{2)} Let $z_k^{(j+1)}={1\over2}(z_k^{(j)}+z\k^{(j)})$, for
8005 |0<=k<n-j|, for |0<=j<n|.
8006
8007 \smallskip\noindent
8008 Then
8009 $$B(z_0,z_1,\ldots,z_n;t)=B(z_0^{(0)},z_0^{(1)},\ldots,z_0^{(n)};2t)
8010  =B(z_0^{(n)},z_1^{(n-1)},\ldots,z_n^{(0)};2t-1).$$
8011 This formula gives us the coefficients of polynomials to use over the ranges
8012 $0\L t\L{1\over2}$ and ${1\over2}\L t\L1$.
8013
8014 @ Now here's a subroutine that's handy for all sorts of path computations:
8015 Given a quadratic polynomial $B(a,b,c;t)$, the |crossing_point| function
8016 returns the unique |fraction| value |t| between 0 and~1 at which
8017 $B(a,b,c;t)$ changes from positive to negative, or returns
8018 |t=fraction_one+1| if no such value exists. If |a<0| (so that $B(a,b,c;t)$
8019 is already negative at |t=0|), |crossing_point| returns the value zero.
8020
8021 @d no_crossing {  return (fraction_one+1); }
8022 @d one_crossing { return fraction_one; }
8023 @d zero_crossing { return 0; }
8024 @d mp_crossing_point(M,A,B,C) mp_do_crossing_point(A,B,C)
8025
8026 @c fraction mp_do_crossing_point (integer a, integer b, integer c) {
8027   integer d; /* recursive counter */
8028   integer x,xx,x0,x1,x2; /* temporary registers for bisection */
8029   if ( a<0 ) zero_crossing;
8030   if ( c>=0 ) { 
8031     if ( b>=0 ) {
8032       if ( c>0 ) { no_crossing; }
8033       else if ( (a==0)&&(b==0) ) { no_crossing;} 
8034       else { one_crossing; } 
8035     }
8036     if ( a==0 ) zero_crossing;
8037   } else if ( a==0 ) {
8038     if ( b<=0 ) zero_crossing;
8039   }
8040   @<Use bisection to find the crossing point, if one exists@>;
8041 }
8042
8043 @ The general bisection method is quite simple when $n=2$, hence
8044 |crossing_point| does not take much time. At each stage in the
8045 recursion we have a subinterval defined by |l| and~|j| such that
8046 $B(a,b,c;2^{-l}(j+t))=B(x_0,x_1,x_2;t)$, and we want to ``zero in'' on
8047 the subinterval where $x_0\G0$ and $\min(x_1,x_2)<0$.
8048
8049 It is convenient for purposes of calculation to combine the values
8050 of |l| and~|j| in a single variable $d=2^l+j$, because the operation
8051 of bisection then corresponds simply to doubling $d$ and possibly
8052 adding~1. Furthermore it proves to be convenient to modify
8053 our previous conventions for bisection slightly, maintaining the
8054 variables $X_0=2^lx_0$, $X_1=2^l(x_0-x_1)$, and $X_2=2^l(x_1-x_2)$.
8055 With these variables the conditions $x_0\ge0$ and $\min(x_1,x_2)<0$ are
8056 equivalent to $\max(X_1,X_1+X_2)>X_0\ge0$.
8057
8058 The following code maintains the invariant relations
8059 $0\L|x0|<\max(|x1|,|x1|+|x2|)$,
8060 $\vert|x1|\vert<2^{30}$, $\vert|x2|\vert<2^{30}$;
8061 it has been constructed in such a way that no arithmetic overflow
8062 will occur if the inputs satisfy
8063 $a<2^{30}$, $\vert a-b\vert<2^{30}$, and $\vert b-c\vert<2^{30}$.
8064
8065 @<Use bisection to find the crossing point...@>=
8066 d=1; x0=a; x1=a-b; x2=b-c;
8067 do {  
8068   x=half(x1+x2);
8069   if ( x1-x0>x0 ) { 
8070     x2=x; x0+=x0; d+=d;  
8071   } else { 
8072     xx=x1+x-x0;
8073     if ( xx>x0 ) { 
8074       x2=x; x0+=x0; d+=d;
8075     }  else { 
8076       x0=x0-xx;
8077       if ( x<=x0 ) { if ( x+x2<=x0 ) no_crossing; }
8078       x1=x; d=d+d+1;
8079     }
8080   }
8081 } while (d<fraction_one);
8082 return (d-fraction_one)
8083
8084 @ Here is a routine that computes the $x$ or $y$ coordinate of the point on
8085 a cubic corresponding to the |fraction| value~|t|.
8086
8087 It is convenient to define a \.{WEB} macro |t_of_the_way| such that
8088 |t_of_the_way(a,b)| expands to |a-(a-b)*t|, i.e., to |t[a,b]|.
8089
8090 @d t_of_the_way(A,B) ((A)-mp_take_fraction(mp,((A)-(B)),t))
8091
8092 @c scaled mp_eval_cubic (MP mp,pointer p, pointer q, fraction t) {
8093   scaled x1,x2,x3; /* intermediate values */
8094   x1=t_of_the_way(knot_coord(p),right_coord(p));
8095   x2=t_of_the_way(right_coord(p),left_coord(q));
8096   x3=t_of_the_way(left_coord(q),knot_coord(q));
8097   x1=t_of_the_way(x1,x2);
8098   x2=t_of_the_way(x2,x3);
8099   return t_of_the_way(x1,x2);
8100 }
8101
8102 @ The actual bounding box information is stored in global variables.
8103 Since it is convenient to address the $x$ and $y$ information
8104 separately, we define arrays indexed by |x_code..y_code| and use
8105 macros to give them more convenient names.
8106
8107 @<Types...@>=
8108 enum mp_bb_code  {
8109   mp_x_code=0, /* index for |minx| and |maxx| */
8110   mp_y_code /* index for |miny| and |maxy| */
8111 } ;
8112
8113
8114 @d minx mp->bbmin[mp_x_code]
8115 @d maxx mp->bbmax[mp_x_code]
8116 @d miny mp->bbmin[mp_y_code]
8117 @d maxy mp->bbmax[mp_y_code]
8118
8119 @<Glob...@>=
8120 scaled bbmin[mp_y_code+1];
8121 scaled bbmax[mp_y_code+1]; 
8122 /* the result of procedures that compute bounding box information */
8123
8124 @ Now we're ready for the key part of the bounding box computation.
8125 The |bound_cubic| procedure updates |bbmin[c]| and |bbmax[c]| based on
8126 $$B(\hbox{|knot_coord(p)|}, \hbox{|right_coord(p)|},
8127     \hbox{|left_coord(q)|}, \hbox{|knot_coord(q)|};t)
8128 $$
8129 for $0<t\le1$.  In other words, the procedure adjusts the bounds to
8130 accommodate |knot_coord(q)| and any extremes over the range $0<t<1$.
8131 The |c| parameter is |x_code| or |y_code|.
8132
8133 @c void mp_bound_cubic (MP mp,pointer p, pointer q, small_number c) {
8134   boolean wavy; /* whether we need to look for extremes */
8135   scaled del1,del2,del3,del,dmax; /* proportional to the control
8136      points of a quadratic derived from a cubic */
8137   fraction t,tt; /* where a quadratic crosses zero */
8138   scaled x; /* a value that |bbmin[c]| and |bbmax[c]| must accommodate */
8139   x=knot_coord(q);
8140   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8141   @<Check the control points against the bounding box and set |wavy:=true|
8142     if any of them lie outside@>;
8143   if ( wavy ) {
8144     del1=right_coord(p)-knot_coord(p);
8145     del2=left_coord(q)-right_coord(p);
8146     del3=knot_coord(q)-left_coord(q);
8147     @<Scale up |del1|, |del2|, and |del3| for greater accuracy;
8148       also set |del| to the first nonzero element of |(del1,del2,del3)|@>;
8149     if ( del<0 ) {
8150       negate(del1); negate(del2); negate(del3);
8151     };
8152     t=mp_crossing_point(mp, del1,del2,del3);
8153     if ( t<fraction_one ) {
8154       @<Test the extremes of the cubic against the bounding box@>;
8155     }
8156   }
8157 }
8158
8159 @ @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>=
8160 if ( x<mp->bbmin[c] ) mp->bbmin[c]=x;
8161 if ( x>mp->bbmax[c] ) mp->bbmax[c]=x
8162
8163 @ @<Check the control points against the bounding box and set...@>=
8164 wavy=true;
8165 if ( mp->bbmin[c]<=right_coord(p) )
8166   if ( right_coord(p)<=mp->bbmax[c] )
8167     if ( mp->bbmin[c]<=left_coord(q) )
8168       if ( left_coord(q)<=mp->bbmax[c] )
8169         wavy=false
8170
8171 @ If |del1=del2=del3=0|, it's impossible to obey the title of this
8172 section. We just set |del=0| in that case.
8173
8174 @<Scale up |del1|, |del2|, and |del3| for greater accuracy...@>=
8175 if ( del1!=0 ) del=del1;
8176 else if ( del2!=0 ) del=del2;
8177 else del=del3;
8178 if ( del!=0 ) {
8179   dmax=abs(del1);
8180   if ( abs(del2)>dmax ) dmax=abs(del2);
8181   if ( abs(del3)>dmax ) dmax=abs(del3);
8182   while ( dmax<fraction_half ) {
8183     dmax+=dmax; del1+=del1; del2+=del2; del3+=del3;
8184   }
8185 }
8186
8187 @ Since |crossing_point| has tried to choose |t| so that
8188 $B(|del1|,|del2|,|del3|;\tau)$ crosses zero at $\tau=|t|$ with negative
8189 slope, the value of |del2| computed below should not be positive.
8190 But rounding error could make it slightly positive in which case we
8191 must cut it to zero to avoid confusion.
8192
8193 @<Test the extremes of the cubic against the bounding box@>=
8194
8195   x=mp_eval_cubic(mp, p,q,t);
8196   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8197   del2=t_of_the_way(del2,del3);
8198     /* now |0,del2,del3| represent the derivative on the remaining interval */
8199   if ( del2>0 ) del2=0;
8200   tt=mp_crossing_point(mp, 0,-del2,-del3);
8201   if ( tt<fraction_one ) {
8202     @<Test the second extreme against the bounding box@>;
8203   }
8204 }
8205
8206 @ @<Test the second extreme against the bounding box@>=
8207 {
8208    x=mp_eval_cubic(mp, p,q,t_of_the_way(tt,fraction_one));
8209   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8210 }
8211
8212 @ Finding the bounding box of a path is basically a matter of applying
8213 |bound_cubic| twice for each pair of adjacent knots.
8214
8215 @c void mp_path_bbox (MP mp,pointer h) {
8216   pointer p,q; /* a pair of adjacent knots */
8217    minx=x_coord(h); miny=y_coord(h);
8218   maxx=minx; maxy=miny;
8219   p=h;
8220   do {  
8221     if ( right_type(p)==mp_endpoint ) return;
8222     q=link(p);
8223     mp_bound_cubic(mp, x_loc(p),x_loc(q),mp_x_code);
8224     mp_bound_cubic(mp, y_loc(p),y_loc(q),mp_y_code);
8225     p=q;
8226   } while (p!=h);
8227 }
8228
8229 @ Another important way to measure a path is to find its arc length.  This
8230 is best done by using the general bisection algorithm to subdivide the path
8231 until obtaining ``well behaved'' subpaths whose arc lengths can be approximated
8232 by simple means.
8233
8234 Since the arc length is the integral with respect to time of the magnitude of
8235 the velocity, it is natural to use Simpson's rule for the approximation.
8236 @^Simpson's rule@>
8237 If $\dot B(t)$ is the spline velocity, Simpson's rule gives
8238 $$ \vb\dot B(0)\vb + 4\vb\dot B({1\over2})\vb + \vb\dot B(1)\vb \over 6 $$
8239 for the arc length of a path of length~1.  For a cubic spline
8240 $B(z_0,z_1,z_2,z_3;t)$, the time derivative $\dot B(t)$ is
8241 $3B(dz_0,dz_1,dz_2;t)$, where $dz_i=z_{i+1}-z_i$.  Hence the arc length
8242 approximation is
8243 $$ {\vb dz_0\vb \over 2} + 2\vb dz_{02}\vb + {\vb dz_2\vb \over 2}, $$
8244 where
8245 $$ dz_{02}={1\over2}\left({dz_0+dz_1\over 2}+{dz_1+dz_2\over 2}\right)$$
8246 is the result of the bisection algorithm.
8247
8248 @ The remaining problem is how to decide when a subpath is ``well behaved.''
8249 This could be done via the theoretical error bound for Simpson's rule,
8250 @^Simpson's rule@>
8251 but this is impractical because it requires an estimate of the fourth
8252 derivative of the quantity being integrated.  It is much easier to just perform
8253 a bisection step and see how much the arc length estimate changes.  Since the
8254 error for Simpson's rule is proportional to the fourth power of the sample
8255 spacing, the remaining error is typically about $1\over16$ of the amount of
8256 the change.  We say ``typically'' because the error has a pseudo-random behavior
8257 that could cause the two estimates to agree when each contain large errors.
8258
8259 To protect against disasters such as undetected cusps, the bisection process
8260 should always continue until all the $dz_i$ vectors belong to a single
8261 $90^\circ$ sector.  This ensures that no point on the spline can have velocity
8262 less than 70\% of the minimum of $\vb dz_0\vb$, $\vb dz_1\vb$ and $\vb dz_2\vb$.
8263 If such a spline happens to produce an erroneous arc length estimate that
8264 is little changed by bisection, the amount of the error is likely to be fairly
8265 small.  We will try to arrange things so that freak accidents of this type do
8266 not destroy the inverse relationship between the \&{arclength} and
8267 \&{arctime} operations.
8268 @:arclength_}{\&{arclength} primitive@>
8269 @:arctime_}{\&{arctime} primitive@>
8270
8271 @ The \&{arclength} and \&{arctime} operations are both based on a recursive
8272 @^recursion@>
8273 function that finds the arc length of a cubic spline given $dz_0$, $dz_1$,
8274 $dz_2$. This |arc_test| routine also takes an arc length goal |a_goal| and
8275 returns the time when the arc length reaches |a_goal| if there is such a time.
8276 Thus the return value is either an arc length less than |a_goal| or, if the
8277 arc length would be at least |a_goal|, it returns a time value decreased by
8278 |two|.  This allows the caller to use the sign of the result to distinguish
8279 between arc lengths and time values.  On certain types of overflow, it is
8280 possible for |a_goal| and the result of |arc_test| both to be |el_gordo|.
8281 Otherwise, the result is always less than |a_goal|.
8282
8283 Rather than halving the control point coordinates on each recursive call to
8284 |arc_test|, it is better to keep them proportional to velocity on the original
8285 curve and halve the results instead.  This means that recursive calls can
8286 potentially use larger error tolerances in their arc length estimates.  How
8287 much larger depends on to what extent the errors behave as though they are
8288 independent of each other.  To save computing time, we use optimistic assumptions
8289 and increase the tolerance by a factor of about $\sqrt2$ for each recursive
8290 call.
8291
8292 In addition to the tolerance parameter, |arc_test| should also have parameters
8293 for ${1\over3}\vb\dot B(0)\vb$, ${2\over3}\vb\dot B({1\over2})\vb$, and
8294 ${1\over3}\vb\dot B(1)\vb$.  These quantities are relatively expensive to compute
8295 and they are needed in different instances of |arc_test|.
8296
8297 @c @t\4@>@<Declare subroutines needed by |arc_test|@>;
8298 scaled mp_arc_test (MP mp, scaled dx0, scaled dy0, scaled dx1, scaled dy1, 
8299                     scaled dx2, scaled dy2, scaled  v0, scaled v02, 
8300                     scaled v2, scaled a_goal, scaled tol) {
8301   boolean simple; /* are the control points confined to a $90^\circ$ sector? */
8302   scaled dx01, dy01, dx12, dy12, dx02, dy02;  /* bisection results */
8303   scaled v002, v022;
8304     /* twice the velocity magnitudes at $t={1\over4}$ and $t={3\over4}$ */
8305   scaled arc; /* best arc length estimate before recursion */
8306   @<Other local variables in |arc_test|@>;
8307   @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,
8308     |dx2|, |dy2|@>;
8309   @<Initialize |v002|, |v022|, and the arc length estimate |arc|; if it overflows
8310     set |arc_test| and |return|@>;
8311   @<Test if the control points are confined to one quadrant or rotating them
8312     $45^\circ$ would put them in one quadrant.  Then set |simple| appropriately@>;
8313   if ( simple && (abs(arc-v02-halfp(v0+v2)) <= tol) ) {
8314     if ( arc < a_goal ) {
8315       return arc;
8316     } else {
8317        @<Estimate when the arc length reaches |a_goal| and set |arc_test| to
8318          that time minus |two|@>;
8319     }
8320   } else {
8321     @<Use one or two recursive calls to compute the |arc_test| function@>;
8322   }
8323 }
8324
8325 @ The |tol| value should by multiplied by $\sqrt 2$ before making recursive
8326 calls, but $1.5$ is an adequate approximation.  It is best to avoid using
8327 |make_fraction| in this inner loop.
8328 @^inner loop@>
8329
8330 @<Use one or two recursive calls to compute the |arc_test| function@>=
8331
8332   @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is as
8333     large as possible@>;
8334   tol = tol + halfp(tol);
8335   a = mp_arc_test(mp, dx0,dy0, dx01,dy01, dx02,dy02, v0, v002, 
8336                   halfp(v02), a_new, tol);
8337   if ( a<0 )  {
8338      return (-halfp(two-a));
8339   } else { 
8340     @<Update |a_new| to reduce |a_new+a_aux| by |a|@>;
8341     b = mp_arc_test(mp, dx02,dy02, dx12,dy12, dx2,dy2,
8342                     halfp(v02), v022, v2, a_new, tol);
8343     if ( b<0 )  
8344       return (-halfp(-b) - half_unit);
8345     else  
8346       return (a + half(b-a));
8347   }
8348 }
8349
8350 @ @<Other local variables in |arc_test|@>=
8351 scaled a,b; /* results of recursive calls */
8352 scaled a_new,a_aux; /* the sum of these gives the |a_goal| */
8353
8354 @ @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is...@>=
8355 a_aux = el_gordo - a_goal;
8356 if ( a_goal > a_aux ) {
8357   a_aux = a_goal - a_aux;
8358   a_new = el_gordo;
8359 } else { 
8360   a_new = a_goal + a_goal;
8361   a_aux = 0;
8362 }
8363
8364 @ There is no need to maintain |a_aux| at this point so we use it as a temporary
8365 to force the additions and subtractions to be done in an order that avoids
8366 overflow.
8367
8368 @<Update |a_new| to reduce |a_new+a_aux| by |a|@>=
8369 if ( a > a_aux ) {
8370   a_aux = a_aux - a;
8371   a_new = a_new + a_aux;
8372 }
8373
8374 @ This code assumes all {\it dx} and {\it dy} variables have magnitude less than
8375 |fraction_four|.  To simplify the rest of the |arc_test| routine, we strengthen
8376 this assumption by requiring the norm of each $({\it dx},{\it dy})$ pair to obey
8377 this bound.  Note that recursive calls will maintain this invariant.
8378
8379 @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,...@>=
8380 dx01 = half(dx0 + dx1);
8381 dx12 = half(dx1 + dx2);
8382 dx02 = half(dx01 + dx12);
8383 dy01 = half(dy0 + dy1);
8384 dy12 = half(dy1 + dy2);
8385 dy02 = half(dy01 + dy12)
8386
8387 @ We should be careful to keep |arc<el_gordo| so that calling |arc_test| with
8388 |a_goal=el_gordo| is guaranteed to yield the arc length.
8389
8390 @<Initialize |v002|, |v022|, and the arc length estimate |arc|;...@>=
8391 v002 = mp_pyth_add(mp, dx01+half(dx0+dx02), dy01+half(dy0+dy02));
8392 v022 = mp_pyth_add(mp, dx12+half(dx02+dx2), dy12+half(dy02+dy2));
8393 tmp = halfp(v02+2);
8394 arc1 = v002 + half(halfp(v0+tmp) - v002);
8395 arc = v022 + half(halfp(v2+tmp) - v022);
8396 if ( (arc < el_gordo-arc1) )  {
8397   arc = arc+arc1;
8398 } else { 
8399   mp->arith_error = true;
8400   if ( a_goal==el_gordo )  return (el_gordo);
8401   else return (-two);
8402 }
8403
8404 @ @<Other local variables in |arc_test|@>=
8405 scaled tmp, tmp2; /* all purpose temporary registers */
8406 scaled arc1; /* arc length estimate for the first half */
8407
8408 @ @<Test if the control points are confined to one quadrant or rotating...@>=
8409 simple = ((dx0>=0) && (dx1>=0) && (dx2>=0)) ||
8410          ((dx0<=0) && (dx1<=0) && (dx2<=0));
8411 if ( simple )
8412   simple = ((dy0>=0) && (dy1>=0) && (dy2>=0)) ||
8413            ((dy0<=0) && (dy1<=0) && (dy2<=0));
8414 if ( ! simple ) {
8415   simple = ((dx0>=dy0) && (dx1>=dy1) && (dx2>=dy2)) ||
8416            ((dx0<=dy0) && (dx1<=dy1) && (dx2<=dy2));
8417   if ( simple ) 
8418     simple = ((-dx0>=dy0) && (-dx1>=dy1) && (-dx2>=dy2)) ||
8419              ((-dx0<=dy0) && (-dx1<=dy1) && (-dx2<=dy2));
8420 }
8421
8422 @ Since Simpson's rule is based on approximating the integrand by a parabola,
8423 @^Simpson's rule@>
8424 it is appropriate to use the same approximation to decide when the integral
8425 reaches the intermediate value |a_goal|.  At this point
8426 $$\eqalign{
8427     {\vb\dot B(0)\vb\over 3} &= \hbox{|v0|}, \qquad
8428     {\vb\dot B({1\over4})\vb\over 3} = {\hbox{|v002|}\over 2}, \qquad
8429     {\vb\dot B({1\over2})\vb\over 3} = {\hbox{|v02|}\over 2}, \cr
8430     {\vb\dot B({3\over4})\vb\over 3} &= {\hbox{|v022|}\over 2}, \qquad
8431     {\vb\dot B(1)\vb\over 3} = \hbox{|v2|} \cr
8432 }
8433 $$
8434 and
8435 $$ {\vb\dot B(t)\vb\over 3} \approx
8436   \cases{B\left(\hbox{|v0|},
8437       \hbox{|v002|}-{1\over 2}\hbox{|v0|}-{1\over 4}\hbox{|v02|},
8438       {1\over 2}\hbox{|v02|}; 2t \right)&
8439     if $t\le{1\over 2}$\cr
8440   B\left({1\over 2}\hbox{|v02|},
8441       \hbox{|v022|}-{1\over 4}\hbox{|v02|}-{1\over 2}\hbox{|v2|},
8442       \hbox{|v2|}; 2t-1 \right)&
8443     if $t\ge{1\over 2}$.\cr}
8444  \eqno (*)
8445 $$
8446 We can integrate $\vb\dot B(t)\vb$ by using
8447 $$\int 3B(a,b,c;\tau)\,dt =
8448   {B(0,a,a+b,a+b+c;\tau) + {\rm constant} \over {d\tau\over dt}}.
8449 $$
8450
8451 This construction allows us to find the time when the arc length reaches
8452 |a_goal| by solving a cubic equation of the form
8453 $$ B(0,a,a+b,a+b+c;\tau) = x, $$
8454 where $\tau$ is $2t$ or $2t+1$, $x$ is |a_goal| or |a_goal-arc1|, and $a$, $b$,
8455 and $c$ are the Bernshte{\u\i}n coefficients from $(*)$ divided by
8456 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
8457 $d\tau\over dt$.  We shall define a function |solve_rising_cubic| that finds
8458 $\tau$ given $a$, $b$, $c$, and $x$.
8459
8460 @<Estimate when the arc length reaches |a_goal| and set |arc_test| to...@>=
8461
8462   tmp = (v02 + 2) / 4;
8463   if ( a_goal<=arc1 ) {
8464     tmp2 = halfp(v0);
8465     return 
8466       (halfp(mp_solve_rising_cubic(mp, tmp2, arc1-tmp2-tmp, tmp, a_goal))- two);
8467   } else { 
8468     tmp2 = halfp(v2);
8469     return ((half_unit - two) +
8470       halfp(mp_solve_rising_cubic(mp, tmp, arc-arc1-tmp-tmp2, tmp2, a_goal-arc1)));
8471   }
8472 }
8473
8474 @ Here is the |solve_rising_cubic| routine that finds the time~$t$ when
8475 $$ B(0, a, a+b, a+b+c; t) = x. $$
8476 This routine is based on |crossing_point| but is simplified by the
8477 assumptions that $B(a,b,c;t)\ge0$ for $0\le t\le1$ and that |0<=x<=a+b+c|.
8478 If rounding error causes this condition to be violated slightly, we just ignore
8479 it and proceed with binary search.  This finds a time when the function value
8480 reaches |x| and the slope is positive.
8481
8482 @<Declare subroutines needed by |arc_test|@>=
8483 scaled mp_solve_rising_cubic (MP mp,scaled a, scaled b,  scaled c, scaled x) {
8484   scaled ab, bc, ac; /* bisection results */
8485   integer t; /* $2^k+q$ where unscaled answer is in $[q2^{-k},(q+1)2^{-k})$ */
8486   integer xx; /* temporary for updating |x| */
8487   if ( (a<0) || (c<0) ) mp_confusion(mp, "rising?");
8488 @:this can't happen rising?}{\quad rising?@>
8489   if ( x<=0 ) {
8490         return 0;
8491   } else if ( x >= a+b+c ) {
8492     return unity;
8493   } else { 
8494     t = 1;
8495     @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than
8496       |el_gordo div 3|@>;
8497     do {  
8498       t+=t;
8499       @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>;
8500       xx = x - a - ab - ac;
8501       if ( xx < -x ) { x+=x; b=ab; c=ac;  }
8502       else { x = x + xx;  a=ac; b=mp->bc; t = t+1; };
8503     } while (t < unity);
8504     return (t - unity);
8505   }
8506 }
8507
8508 @ @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>=
8509 ab = half(a+b);
8510 bc = half(b+c);
8511 ac = half(ab+bc)
8512
8513 @ @d one_third_el_gordo 05252525252 /* upper bound on |a|, |b|, and |c| */
8514
8515 @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than...@>=
8516 while ((a>one_third_el_gordo)||(b>one_third_el_gordo)||(c>one_third_el_gordo)) { 
8517   a = halfp(a);
8518   b = half(b);
8519   c = halfp(c);
8520   x = halfp(x);
8521 }
8522
8523 @ It is convenient to have a simpler interface to |arc_test| that requires no
8524 unnecessary arguments and ensures that each $({\it dx},{\it dy})$ pair has
8525 length less than |fraction_four|.
8526
8527 @d arc_tol   16  /* quit when change in arc length estimate reaches this */
8528
8529 @c scaled mp_do_arc_test (MP mp,scaled dx0, scaled dy0, scaled dx1, 
8530                           scaled dy1, scaled dx2, scaled dy2, scaled a_goal) {
8531   scaled v0,v1,v2; /* length of each $({\it dx},{\it dy})$ pair */
8532   scaled v02; /* twice the norm of the quadratic at $t={1\over2}$ */
8533   v0 = mp_pyth_add(mp, dx0,dy0);
8534   v1 = mp_pyth_add(mp, dx1,dy1);
8535   v2 = mp_pyth_add(mp, dx2,dy2);
8536   if ( (v0>=fraction_four) || (v1>=fraction_four) || (v2>=fraction_four) ) { 
8537     mp->arith_error = true;
8538     if ( a_goal==el_gordo )  return el_gordo;
8539     else return (-two);
8540   } else { 
8541     v02 = mp_pyth_add(mp, dx1+half(dx0+dx2), dy1+half(dy0+dy2));
8542     return (mp_arc_test(mp, dx0,dy0, dx1,dy1, dx2,dy2,
8543                                  v0, v02, v2, a_goal, arc_tol));
8544   }
8545 }
8546
8547 @ Now it is easy to find the arc length of an entire path.
8548
8549 @c scaled mp_get_arc_length (MP mp,pointer h) {
8550   pointer p,q; /* for traversing the path */
8551   scaled a,a_tot; /* current and total arc lengths */
8552   a_tot = 0;
8553   p = h;
8554   while ( right_type(p)!=mp_endpoint ){ 
8555     q = link(p);
8556     a = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8557       left_x(q)-right_x(p), left_y(q)-right_y(p),
8558       x_coord(q)-left_x(q), y_coord(q)-left_y(q), el_gordo);
8559     a_tot = mp_slow_add(mp, a, a_tot);
8560     if ( q==h ) break;  else p=q;
8561   }
8562   check_arith;
8563   return a_tot;
8564 }
8565
8566 @ The inverse operation of finding the time on a path~|h| when the arc length
8567 reaches some value |arc0| can also be accomplished via |do_arc_test|.  Some care
8568 is required to handle very large times or negative times on cyclic paths.  For
8569 non-cyclic paths, |arc0| values that are negative or too large cause
8570 |get_arc_time| to return 0 or the length of path~|h|.
8571
8572 If |arc0| is greater than the arc length of a cyclic path~|h|, the result is a
8573 time value greater than the length of the path.  Since it could be much greater,
8574 we must be prepared to compute the arc length of path~|h| and divide this into
8575 |arc0| to find how many multiples of the length of path~|h| to add.
8576
8577 @c scaled mp_get_arc_time (MP mp,pointer h, scaled  arc0) {
8578   pointer p,q; /* for traversing the path */
8579   scaled t_tot; /* accumulator for the result */
8580   scaled t; /* the result of |do_arc_test| */
8581   scaled arc; /* portion of |arc0| not used up so far */
8582   integer n; /* number of extra times to go around the cycle */
8583   if ( arc0<0 ) {
8584     @<Deal with a negative |arc0| value and |return|@>;
8585   }
8586   if ( arc0==el_gordo ) decr(arc0);
8587   t_tot = 0;
8588   arc = arc0;
8589   p = h;
8590   while ( (right_type(p)!=mp_endpoint) && (arc>0) ) {
8591     q = link(p);
8592     t = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8593       left_x(q)-right_x(p), left_y(q)-right_y(p),
8594       x_coord(q)-left_x(q), y_coord(q)-left_y(q), arc);
8595     @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>;
8596     if ( q==h ) {
8597       @<Update |t_tot| and |arc| to avoid going around the cyclic
8598         path too many times but set |arith_error:=true| and |goto done| on
8599         overflow@>;
8600     }
8601     p = q;
8602   }
8603   check_arith;
8604   return t_tot;
8605 }
8606
8607 @ @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>=
8608 if ( t<0 ) { t_tot = t_tot + t + two;  arc = 0;  }
8609 else { t_tot = t_tot + unity;  arc = arc - t;  }
8610
8611 @ @<Deal with a negative |arc0| value and |return|@>=
8612
8613   if ( left_type(h)==mp_endpoint ) {
8614     t_tot=0;
8615   } else { 
8616     p = mp_htap_ypoc(mp, h);
8617     t_tot = -mp_get_arc_time(mp, p, -arc0);
8618     mp_toss_knot_list(mp, p);
8619   }
8620   check_arith;
8621   return t_tot;
8622 }
8623
8624 @ @<Update |t_tot| and |arc| to avoid going around the cyclic...@>=
8625 if ( arc>0 ) { 
8626   n = arc / (arc0 - arc);
8627   arc = arc - n*(arc0 - arc);
8628   if ( t_tot > el_gordo / (n+1) ) { 
8629     mp->arith_error = true;
8630     t_tot = el_gordo;
8631     break;
8632   }
8633   t_tot = (n + 1)*t_tot;
8634 }
8635
8636 @* \[20] Data structures for pens.
8637 A Pen in \MP\ can be either elliptical or polygonal.  Elliptical pens result
8638 in \ps\ \&{stroke} commands, while anything drawn with a polygonal pen is
8639 @:stroke}{\&{stroke} command@>
8640 converted into an area fill as described in the next part of this program.
8641 The mathematics behind this process is based on simple aspects of the theory
8642 of tracings developed by Leo Guibas, Lyle Ramshaw, and Jorge Stolfi
8643 [``A kinematic framework for computational geometry,'' Proc.\ IEEE Symp.\
8644 Foundations of Computer Science {\bf 24} (1983), 100--111].
8645
8646 Polygonal pens are created from paths via \MP's \&{makepen} primitive.
8647 @:makepen_}{\&{makepen} primitive@>
8648 This path representation is almost sufficient for our purposes except that
8649 a pen path should always be a convex polygon with the vertices in
8650 counter-clockwise order.
8651 Since we will need to scan pen polygons both forward and backward, a pen
8652 should be represented as a doubly linked ring of knot nodes.  There is
8653 room for the extra back pointer because we do not need the
8654 |left_type| or |right_type| fields.  In fact, we don't need the |left_x|,
8655 |left_y|, |right_x|, or |right_y| fields either but we leave these alone
8656 so that certain procedures can operate on both pens and paths.  In particular,
8657 pens can be copied using |copy_path| and recycled using |toss_knot_list|.
8658
8659 @d knil info
8660   /* this replaces the |left_type| and |right_type| fields in a pen knot */
8661
8662 @ The |make_pen| procedure turns a path into a pen by initializing
8663 the |knil| pointers and making sure the knots form a convex polygon.
8664 Thus each cubic in the given path becomes a straight line and the control
8665 points are ignored.  If the path is not cyclic, the ends are connected by a
8666 straight line.
8667
8668 @d copy_pen(A) mp_make_pen(mp, mp_copy_path(mp, (A)),false)
8669
8670 @c @<Declare a function called |convex_hull|@>;
8671 pointer mp_make_pen (MP mp,pointer h, boolean need_hull) {
8672   pointer p,q; /* two consecutive knots */
8673   q=h;
8674   do {  
8675     p=q; q=link(q);
8676     knil(q)=p;
8677   } while (q!=h);
8678   if ( need_hull ){ 
8679     h=mp_convex_hull(mp, h);
8680     @<Make sure |h| isn't confused with an elliptical pen@>;
8681   }
8682   return h;
8683 }
8684
8685 @ The only information required about an elliptical pen is the overall
8686 transformation that has been applied to the original \&{pencircle}.
8687 @:pencircle_}{\&{pencircle} primitive@>
8688 Since it suffices to keep track of how the three points $(0,0)$, $(1,0)$,
8689 and $(0,1)$ are transformed, an elliptical pen can be stored in a single
8690 knot node and transformed as if it were a path.
8691
8692 @d pen_is_elliptical(A) ((A)==link((A)))
8693
8694 @c pointer mp_get_pen_circle (MP mp,scaled diam) {
8695   pointer h; /* the knot node to return */
8696   h=mp_get_node(mp, knot_node_size);
8697   link(h)=h; knil(h)=h;
8698   originator(h)=mp_program_code;
8699   x_coord(h)=0; y_coord(h)=0;
8700   left_x(h)=diam; left_y(h)=0;
8701   right_x(h)=0; right_y(h)=diam;
8702   return h;
8703 }
8704
8705 @ If the polygon being returned by |make_pen| has only one vertex, it will
8706 be interpreted as an elliptical pen.  This is no problem since a degenerate
8707 polygon can equally well be thought of as a degenerate ellipse.  We need only
8708 initialize the |left_x|, |left_y|, |right_x|, and |right_y| fields.
8709
8710 @<Make sure |h| isn't confused with an elliptical pen@>=
8711 if ( pen_is_elliptical( h) ){ 
8712   left_x(h)=x_coord(h); left_y(h)=y_coord(h);
8713   right_x(h)=x_coord(h); right_y(h)=y_coord(h);
8714 }
8715
8716 @ We have to cheat a little here but most operations on pens only use
8717 the first three words in each knot node.
8718 @^data structure assumptions@>
8719
8720 @<Initialize a pen at |test_pen| so that it fits in nine words@>=
8721 x_coord(test_pen)=-half_unit;
8722 y_coord(test_pen)=0;
8723 x_coord(test_pen+3)=half_unit;
8724 y_coord(test_pen+3)=0;
8725 x_coord(test_pen+6)=0;
8726 y_coord(test_pen+6)=unity;
8727 link(test_pen)=test_pen+3;
8728 link(test_pen+3)=test_pen+6;
8729 link(test_pen+6)=test_pen;
8730 knil(test_pen)=test_pen+6;
8731 knil(test_pen+3)=test_pen;
8732 knil(test_pen+6)=test_pen+3
8733
8734 @ Printing a polygonal pen is very much like printing a path
8735
8736 @<Declare subroutines for printing expressions@>=
8737 void mp_pr_pen (MP mp,pointer h) {
8738   pointer p,q; /* for list traversal */
8739   if ( pen_is_elliptical(h) ) {
8740     @<Print the elliptical pen |h|@>;
8741   } else { 
8742     p=h;
8743     do {  
8744       mp_print_two(mp, x_coord(p),y_coord(p));
8745       mp_print_nl(mp, " .. ");
8746       @<Advance |p| making sure the links are OK and |return| if there is
8747         a problem@>;
8748      } while (p!=h);
8749      mp_print(mp, "cycle");
8750   }
8751 }
8752
8753 @ @<Advance |p| making sure the links are OK and |return| if there is...@>=
8754 q=link(p);
8755 if ( (q==null) || (knil(q)!=p) ) { 
8756   mp_print_nl(mp, "???"); return; /* this won't happen */
8757 @.???@>
8758 }
8759 p=q
8760
8761 @ @<Print the elliptical pen |h|@>=
8762
8763 mp_print(mp, "pencircle transformed (");
8764 mp_print_scaled(mp, x_coord(h));
8765 mp_print_char(mp, ',');
8766 mp_print_scaled(mp, y_coord(h));
8767 mp_print_char(mp, ',');
8768 mp_print_scaled(mp, left_x(h)-x_coord(h));
8769 mp_print_char(mp, ',');
8770 mp_print_scaled(mp, right_x(h)-x_coord(h));
8771 mp_print_char(mp, ',');
8772 mp_print_scaled(mp, left_y(h)-y_coord(h));
8773 mp_print_char(mp, ',');
8774 mp_print_scaled(mp, right_y(h)-y_coord(h));
8775 mp_print_char(mp, ')');
8776 }
8777
8778 @ Here us another version of |pr_pen| that prints the pen as a diagnostic
8779 message.
8780
8781 @<Declare subroutines for printing expressions@>=
8782 void mp_print_pen (MP mp,pointer h, char *s, boolean nuline) { 
8783   mp_print_diagnostic(mp, "Pen",s,nuline); mp_print_ln(mp);
8784 @.Pen at line...@>
8785   mp_pr_pen(mp, h);
8786   mp_end_diagnostic(mp, true);
8787 }
8788
8789 @ Making a polygonal pen into a path involves restoring the |left_type| and
8790 |right_type| fields and setting the control points so as to make a polygonal
8791 path.
8792
8793 @c 
8794 void mp_make_path (MP mp,pointer h) {
8795   pointer p; /* for traversing the knot list */
8796   small_number k; /* a loop counter */
8797   @<Other local variables in |make_path|@>;
8798   if ( pen_is_elliptical(h) ) {
8799     @<Make the elliptical pen |h| into a path@>;
8800   } else { 
8801     p=h;
8802     do {  
8803       left_type(p)=mp_explicit;
8804       right_type(p)=mp_explicit;
8805       @<copy the coordinates of knot |p| into its control points@>;
8806        p=link(p);
8807     } while (p!=h);
8808   }
8809 }
8810
8811 @ @<copy the coordinates of knot |p| into its control points@>=
8812 left_x(p)=x_coord(p);
8813 left_y(p)=y_coord(p);
8814 right_x(p)=x_coord(p);
8815 right_y(p)=y_coord(p)
8816
8817 @ We need an eight knot path to get a good approximation to an ellipse.
8818
8819 @<Make the elliptical pen |h| into a path@>=
8820
8821   @<Extract the transformation parameters from the elliptical pen~|h|@>;
8822   p=h;
8823   for (k=0;k<=7;k++ ) { 
8824     @<Initialize |p| as the |k|th knot of a circle of unit diameter,
8825       transforming it appropriately@>;
8826     if ( k==7 ) link(p)=h;  else link(p)=mp_get_node(mp, knot_node_size);
8827     p=link(p);
8828   }
8829 }
8830
8831 @ @<Extract the transformation parameters from the elliptical pen~|h|@>=
8832 center_x=x_coord(h);
8833 center_y=y_coord(h);
8834 width_x=left_x(h)-center_x;
8835 width_y=left_y(h)-center_y;
8836 height_x=right_x(h)-center_x;
8837 height_y=right_y(h)-center_y
8838
8839 @ @<Other local variables in |make_path|@>=
8840 scaled center_x,center_y; /* translation parameters for an elliptical pen */
8841 scaled width_x,width_y; /* the effect of a unit change in $x$ */
8842 scaled height_x,height_y; /* the effect of a unit change in $y$ */
8843 scaled dx,dy; /* the vector from knot |p| to its right control point */
8844 integer kk;
8845   /* |k| advanced $270^\circ$ around the ring (cf. $\sin\theta=\cos(\theta+270)$) */
8846
8847 @ The only tricky thing here are the tables |half_cos| and |d_cos| used to
8848 find the point $k/8$ of the way around the circle and the direction vector
8849 to use there.
8850
8851 @<Initialize |p| as the |k|th knot of a circle of unit diameter,...@>=
8852 kk=(k+6)% 8;
8853 x_coord(p)=center_x+mp_take_fraction(mp, mp->half_cos[k],width_x)
8854            +mp_take_fraction(mp, mp->half_cos[kk],height_x);
8855 y_coord(p)=center_y+mp_take_fraction(mp, mp->half_cos[k],width_y)
8856            +mp_take_fraction(mp, mp->half_cos[kk],height_y);
8857 dx=-mp_take_fraction(mp, mp->d_cos[kk],width_x)
8858    +mp_take_fraction(mp, mp->d_cos[k],height_x);
8859 dy=-mp_take_fraction(mp, mp->d_cos[kk],width_y)
8860    +mp_take_fraction(mp, mp->d_cos[k],height_y);
8861 right_x(p)=x_coord(p)+dx;
8862 right_y(p)=y_coord(p)+dy;
8863 left_x(p)=x_coord(p)-dx;
8864 left_y(p)=y_coord(p)-dy;
8865 left_type(p)=mp_explicit;
8866 right_type(p)=mp_explicit;
8867 originator(p)=mp_program_code
8868
8869 @ @<Glob...@>=
8870 fraction half_cos[8]; /* ${1\over2}\cos(45k)$ */
8871 fraction d_cos[8]; /* a magic constant times $\cos(45k)$ */
8872
8873 @ The magic constant for |d_cos| is the distance between $({1\over2},0)$ and
8874 $({1\over4}\sqrt2,{1\over4}\sqrt2)$ times the result of the |velocity|
8875 function for $\theta=\phi=22.5^\circ$.  This comes out to be
8876 $$ d = {\sqrt{2-\sqrt2}\over 3+3\cos22.5^\circ}
8877   \approx 0.132608244919772.
8878 $$
8879
8880 @<Set init...@>=
8881 mp->half_cos[0]=fraction_half;
8882 mp->half_cos[1]=94906266; /* $2^{26}\sqrt2\approx94906265.62$ */
8883 mp->half_cos[2]=0;
8884 mp->d_cos[0]=35596755; /* $2^{28}d\approx35596754.69$ */
8885 mp->d_cos[1]=25170707; /* $2^{27}\sqrt2\,d\approx25170706.63$ */
8886 mp->d_cos[2]=0;
8887 for (k=3;k<= 4;k++ ) { 
8888   mp->half_cos[k]=-mp->half_cos[4-k];
8889   mp->d_cos[k]=-mp->d_cos[4-k];
8890 }
8891 for (k=5;k<= 7;k++ ) { 
8892   mp->half_cos[k]=mp->half_cos[8-k];
8893   mp->d_cos[k]=mp->d_cos[8-k];
8894 }
8895
8896 @ The |convex_hull| function forces a pen polygon to be convex when it is
8897 returned by |make_pen| and after any subsequent transformation where rounding
8898 error might allow the convexity to be lost.
8899 The convex hull algorithm used here is described by F.~P. Preparata and
8900 M.~I. Shamos [{\sl Computational Geometry}, Springer-Verlag, 1985].
8901
8902 @<Declare a function called |convex_hull|@>=
8903 @<Declare a procedure called |move_knot|@>;
8904 pointer mp_convex_hull (MP mp,pointer h) { /* Make a polygonal pen convex */
8905   pointer l,r; /* the leftmost and rightmost knots */
8906   pointer p,q; /* knots being scanned */
8907   pointer s; /* the starting point for an upcoming scan */
8908   scaled dx,dy; /* a temporary pointer */
8909   if ( pen_is_elliptical(h) ) {
8910      return h;
8911   } else { 
8912     @<Set |l| to the leftmost knot in polygon~|h|@>;
8913     @<Set |r| to the rightmost knot in polygon~|h|@>;
8914     if ( l!=r ) { 
8915       s=link(r);
8916       @<Find any knots on the path from |l| to |r| above the |l|-|r| line and
8917         move them past~|r|@>;
8918       @<Find any knots on the path from |s| to |l| below the |l|-|r| line and
8919         move them past~|l|@>;
8920       @<Sort the path from |l| to |r| by increasing $x$@>;
8921       @<Sort the path from |r| to |l| by decreasing $x$@>;
8922     }
8923     if ( l!=link(l) ) {
8924       @<Do a Gramm scan and remove vertices where there is no left turn@>;
8925     }
8926     return l;
8927   }
8928 }
8929
8930 @ All comparisons are done primarily on $x$ and secondarily on $y$.
8931
8932 @<Set |l| to the leftmost knot in polygon~|h|@>=
8933 l=h;
8934 p=link(h);
8935 while ( p!=h ) { 
8936   if ( x_coord(p)<=x_coord(l) )
8937     if ( (x_coord(p)<x_coord(l)) || (y_coord(p)<y_coord(l)) )
8938       l=p;
8939   p=link(p);
8940 }
8941
8942 @ @<Set |r| to the rightmost knot in polygon~|h|@>=
8943 r=h;
8944 p=link(h);
8945 while ( p!=h ) { 
8946   if ( x_coord(p)>=x_coord(r) )
8947     if ( (x_coord(p)>x_coord(r)) || (y_coord(p)>y_coord(r)) )
8948       r=p;
8949   p=link(p);
8950 }
8951
8952 @ @<Find any knots on the path from |l| to |r| above the |l|-|r| line...@>=
8953 dx=x_coord(r)-x_coord(l);
8954 dy=y_coord(r)-y_coord(l);
8955 p=link(l);
8956 while ( p!=r ) { 
8957   q=link(p);
8958   if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))>0 )
8959     mp_move_knot(mp, p, r);
8960   p=q;
8961 }
8962
8963 @ The |move_knot| procedure removes |p| from a doubly linked list and inserts
8964 it after |q|.
8965
8966 @ @<Declare a procedure called |move_knot|@>=
8967 void mp_move_knot (MP mp,pointer p, pointer q) { 
8968   link(knil(p))=link(p);
8969   knil(link(p))=knil(p);
8970   knil(p)=q;
8971   link(p)=link(q);
8972   link(q)=p;
8973   knil(link(p))=p;
8974 }
8975
8976 @ @<Find any knots on the path from |s| to |l| below the |l|-|r| line...@>=
8977 p=s;
8978 while ( p!=l ) { 
8979   q=link(p);
8980   if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))<0 )
8981     mp_move_knot(mp, p,l);
8982   p=q;
8983 }
8984
8985 @ The list is likely to be in order already so we just do linear insertions.
8986 Secondary comparisons on $y$ ensure that the sort is consistent with the
8987 choice of |l| and |r|.
8988
8989 @<Sort the path from |l| to |r| by increasing $x$@>=
8990 p=link(l);
8991 while ( p!=r ) { 
8992   q=knil(p);
8993   while ( x_coord(q)>x_coord(p) ) q=knil(q);
8994   while ( x_coord(q)==x_coord(p) ) {
8995     if ( y_coord(q)>y_coord(p) ) q=knil(q); else break;
8996   }
8997   if ( q==knil(p) ) p=link(p);
8998   else { p=link(p); mp_move_knot(mp, knil(p),q); };
8999 }
9000
9001 @ @<Sort the path from |r| to |l| by decreasing $x$@>=
9002 p=link(r);
9003 while ( p!=l ){ 
9004   q=knil(p);
9005   while ( x_coord(q)<x_coord(p) ) q=knil(q);
9006   while ( x_coord(q)==x_coord(p) ) {
9007     if ( y_coord(q)<y_coord(p) ) q=knil(q); else break;
9008   }
9009   if ( q==knil(p) ) p=link(p);
9010   else { p=link(p); mp_move_knot(mp, knil(p),q); };
9011 }
9012
9013 @ The condition involving |ab_vs_cd| tests if there is not a left turn
9014 at knot |q|.  There usually will be a left turn so we streamline the case
9015 where the |then| clause is not executed.
9016
9017 @<Do a Gramm scan and remove vertices where there...@>=
9018
9019 p=l; q=link(l);
9020 while (1) { 
9021   dx=x_coord(q)-x_coord(p);
9022   dy=y_coord(q)-y_coord(p);
9023   p=q; q=link(q);
9024   if ( p==l ) break;
9025   if ( p!=r )
9026     if ( mp_ab_vs_cd(mp, dx,y_coord(q)-y_coord(p),dy,x_coord(q)-x_coord(p))<=0 ) {
9027       @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>;
9028     }
9029   }
9030 }
9031
9032 @ @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>=
9033
9034 s=knil(p);
9035 mp_free_node(mp, p,knot_node_size);
9036 link(s)=q; knil(q)=s;
9037 if ( s==l ) p=s;
9038 else { p=knil(s); q=s; };
9039 }
9040
9041 @ The |find_offset| procedure sets global variables |(cur_x,cur_y)| to the
9042 offset associated with the given direction |(x,y)|.  If two different offsets
9043 apply, it chooses one of them.
9044
9045 @c 
9046 void mp_find_offset (MP mp,scaled x, scaled y, pointer h) {
9047   pointer p,q; /* consecutive knots */
9048   scaled wx,wy,hx,hy;
9049   /* the transformation matrix for an elliptical pen */
9050   fraction xx,yy; /* untransformed offset for an elliptical pen */
9051   fraction d; /* a temporary register */
9052   if ( pen_is_elliptical(h) ) {
9053     @<Find the offset for |(x,y)| on the elliptical pen~|h|@>
9054   } else { 
9055     q=h;
9056     do {  
9057       p=q; q=link(q);
9058     } while (!(mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)>=0));
9059     do {  
9060       p=q; q=link(q);
9061     } while (!(mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)<=0));
9062     mp->cur_x=x_coord(p);
9063     mp->cur_y=y_coord(p);
9064   }
9065 }
9066
9067 @ @<Glob...@>=
9068 scaled cur_x;
9069 scaled cur_y; /* all-purpose return value registers */
9070
9071 @ @<Find the offset for |(x,y)| on the elliptical pen~|h|@>=
9072 if ( (x==0) && (y==0) ) {
9073   mp->cur_x=x_coord(h); mp->cur_y=y_coord(h);  
9074 } else { 
9075   @<Find the non-constant part of the transformation for |h|@>;
9076   while ( (abs(x)<fraction_half) && (abs(y)<fraction_half) ){ 
9077     x+=x; y+=y;  
9078   };
9079   @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the
9080     untransformed version of |(x,y)|@>;
9081   mp->cur_x=x_coord(h)+mp_take_fraction(mp, xx,wx)+mp_take_fraction(mp, yy,hx);
9082   mp->cur_y=y_coord(h)+mp_take_fraction(mp, xx,wy)+mp_take_fraction(mp, yy,hy);
9083 }
9084
9085 @ @<Find the non-constant part of the transformation for |h|@>=
9086 wx=left_x(h)-x_coord(h);
9087 wy=left_y(h)-y_coord(h);
9088 hx=right_x(h)-x_coord(h);
9089 hy=right_y(h)-y_coord(h)
9090
9091 @ @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the...@>=
9092 yy=-(mp_take_fraction(mp, x,hy)+mp_take_fraction(mp, y,-hx));
9093 xx=mp_take_fraction(mp, x,-wy)+mp_take_fraction(mp, y,wx);
9094 d=mp_pyth_add(mp, xx,yy);
9095 if ( d>0 ) { 
9096   xx=half(mp_make_fraction(mp, xx,d));
9097   yy=half(mp_make_fraction(mp, yy,d));
9098 }
9099
9100 @ Finding the bounding box of a pen is easy except if the pen is elliptical.
9101 But we can handle that case by just calling |find_offset| twice.  The answer
9102 is stored in the global variables |minx|, |maxx|, |miny|, and |maxy|.
9103
9104 @c 
9105 void mp_pen_bbox (MP mp,pointer h) {
9106   pointer p; /* for scanning the knot list */
9107   if ( pen_is_elliptical(h) ) {
9108     @<Find the bounding box of an elliptical pen@>;
9109   } else { 
9110     minx=x_coord(h); maxx=minx;
9111     miny=y_coord(h); maxy=miny;
9112     p=link(h);
9113     while ( p!=h ) {
9114       if ( x_coord(p)<minx ) minx=x_coord(p);
9115       if ( y_coord(p)<miny ) miny=y_coord(p);
9116       if ( x_coord(p)>maxx ) maxx=x_coord(p);
9117       if ( y_coord(p)>maxy ) maxy=y_coord(p);
9118       p=link(p);
9119     }
9120   }
9121 }
9122
9123 @ @<Find the bounding box of an elliptical pen@>=
9124
9125 mp_find_offset(mp, 0,fraction_one,h);
9126 maxx=mp->cur_x;
9127 minx=2*x_coord(h)-mp->cur_x;
9128 mp_find_offset(mp, -fraction_one,0,h);
9129 maxy=mp->cur_y;
9130 miny=2*y_coord(h)-mp->cur_y;
9131 }
9132
9133 @* \[21] Edge structures.
9134 Now we come to \MP's internal scheme for representing pictures.
9135 The representation is very different from \MF's edge structures
9136 because \MP\ pictures contain \ps\ graphics objects instead of pixel
9137 images.  However, the basic idea is somewhat similar in that shapes
9138 are represented via their boundaries.
9139
9140 The main purpose of edge structures is to keep track of graphical objects
9141 until it is time to translate them into \ps.  Since \MP\ does not need to
9142 know anything about an edge structure other than how to translate it into
9143 \ps\ and how to find its bounding box, edge structures can be just linked
9144 lists of graphical objects.  \MP\ has no easy way to determine whether
9145 two such objects overlap, but it suffices to draw the first one first and
9146 let the second one overwrite it if necessary.
9147
9148 @<Types...@>=
9149 enum mp_graphical_object_code {
9150   @<Graphical object codes@>
9151 };
9152
9153 @ Let's consider the types of graphical objects one at a time.
9154 First of all, a filled contour is represented by a eight-word node.  The first
9155 word contains |type| and |link| fields, and the next six words contain a
9156 pointer to a cyclic path and the value to use for \ps' \&{currentrgbcolor}
9157 parameter.  If a pen is used for filling |pen_p|, |ljoin_val| and |miterlim_val|
9158 give the relevant information.
9159
9160 @d path_p(A) link((A)+1)
9161   /* a pointer to the path that needs filling */
9162 @d pen_p(A) info((A)+1)
9163   /* a pointer to the pen to fill or stroke with */
9164 @d color_model(A) type((A)+2) /*  the color model  */
9165 @d obj_red_loc(A) ((A)+3)  /* the first of three locations for the color */
9166 @d obj_cyan_loc obj_red_loc  /* the first of four locations for the color */
9167 @d obj_grey_loc obj_red_loc  /* the location for the color */
9168 @d red_val(A) mp->mem[(A)+3].sc
9169   /* the red component of the color in the range $0\ldots1$ */
9170 @d cyan_val red_val
9171 @d grey_val red_val
9172 @d green_val(A) mp->mem[(A)+4].sc
9173   /* the green component of the color in the range $0\ldots1$ */
9174 @d magenta_val green_val
9175 @d blue_val(A) mp->mem[(A)+5].sc
9176   /* the blue component of the color in the range $0\ldots1$ */
9177 @d yellow_val blue_val
9178 @d black_val(A) mp->mem[(A)+6].sc
9179   /* the blue component of the color in the range $0\ldots1$ */
9180 @d ljoin_val(A) name_type((A))  /* the value of \&{linejoin} */
9181 @:mp_linejoin_}{\&{linejoin} primitive@>
9182 @d miterlim_val(A) mp->mem[(A)+7].sc  /* the value of \&{miterlimit} */
9183 @:mp_miterlimit_}{\&{miterlimit} primitive@>
9184 @d obj_color_part(A) mp->mem[(A)+3-red_part].sc
9185   /* interpret an object pointer that has been offset by |red_part..blue_part| */
9186 @d pre_script(A) mp->mem[(A)+8].hh.lh
9187 @d post_script(A) mp->mem[(A)+8].hh.rh
9188 @d fill_node_size 9
9189
9190 @ @<Graphical object codes@>=
9191 mp_fill_code=1,
9192
9193 @ @c 
9194 pointer mp_new_fill_node (MP mp,pointer p) {
9195   /* make a fill node for cyclic path |p| and color black */
9196   pointer t; /* the new node */
9197   t=mp_get_node(mp, fill_node_size);
9198   type(t)=mp_fill_code;
9199   path_p(t)=p;
9200   pen_p(t)=null; /* |null| means don't use a pen */
9201   red_val(t)=0;
9202   green_val(t)=0;
9203   blue_val(t)=0;
9204   black_val(t)=0;
9205   color_model(t)=mp_uninitialized_model;
9206   pre_script(t)=null;
9207   post_script(t)=null;
9208   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9209   return t;
9210 }
9211
9212 @ @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>=
9213 if ( mp->internal[mp_linejoin]>unity ) ljoin_val(t)=2;
9214 else if ( mp->internal[mp_linejoin]>0 ) ljoin_val(t)=1;
9215 else ljoin_val(t)=0;
9216 if ( mp->internal[mp_miterlimit]<unity )
9217   miterlim_val(t)=unity;
9218 else
9219   miterlim_val(t)=mp->internal[mp_miterlimit]
9220
9221 @ A stroked path is represented by an eight-word node that is like a filled
9222 contour node except that it contains the current \&{linecap} value, a scale
9223 factor for the dash pattern, and a pointer that is non-null if the stroke
9224 is to be dashed.  The purpose of the scale factor is to allow a picture to
9225 be transformed without touching the picture that |dash_p| points to.
9226
9227 @d dash_p(A) link((A)+9)
9228   /* a pointer to the edge structure that gives the dash pattern */
9229 @d lcap_val(A) type((A)+9)
9230   /* the value of \&{linecap} */
9231 @:mp_linecap_}{\&{linecap} primitive@>
9232 @d dash_scale(A) mp->mem[(A)+10].sc /* dash lengths are scaled by this factor */
9233 @d stroked_node_size 11
9234
9235 @ @<Graphical object codes@>=
9236 mp_stroked_code=2,
9237
9238 @ @c 
9239 pointer mp_new_stroked_node (MP mp,pointer p) {
9240   /* make a stroked node for path |p| with |pen_p(p)| temporarily |null| */
9241   pointer t; /* the new node */
9242   t=mp_get_node(mp, stroked_node_size);
9243   type(t)=mp_stroked_code;
9244   path_p(t)=p; pen_p(t)=null;
9245   dash_p(t)=null;
9246   dash_scale(t)=unity;
9247   red_val(t)=0;
9248   green_val(t)=0;
9249   blue_val(t)=0;
9250   black_val(t)=0;
9251   color_model(t)=mp_uninitialized_model;
9252   pre_script(t)=null;
9253   post_script(t)=null;
9254   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9255   if ( mp->internal[mp_linecap]>unity ) lcap_val(t)=2;
9256   else if ( mp->internal[mp_linecap]>0 ) lcap_val(t)=1;
9257   else lcap_val(t)=0;
9258   return t;
9259 }
9260
9261 @ When a dashed line is computed in a transformed coordinate system, the dash
9262 lengths get scaled like the pen shape and we need to compensate for this.  Since
9263 there is no unique scale factor for an arbitrary transformation, we use the
9264 the square root of the determinant.  The properties of the determinant make it
9265 easier to maintain the |dash_scale|.  The computation is fairly straight-forward
9266 except for the initialization of the scale factor |s|.  The factor of 64 is
9267 needed because |square_rt| scales its result by $2^8$ while we need $2^{14}$
9268 to counteract the effect of |take_fraction|.
9269
9270 @<Declare subroutines needed by |print_edges|@>=
9271 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) {
9272   scaled maxabs; /* $max(|a|,|b|,|c|,|d|)$ */
9273   integer s; /* amount by which the result of |square_rt| needs to be scaled */
9274   @<Initialize |maxabs|@>;
9275   s=64;
9276   while ( (maxabs<fraction_one) && (s>1) ){ 
9277     a+=a; b+=b; c+=c; d+=d;
9278     maxabs+=maxabs; s=halfp(s);
9279   }
9280   return s*mp_square_rt(mp, abs(mp_take_fraction(mp, a,d)-mp_take_fraction(mp, b,c)));
9281 }
9282 @#
9283 scaled mp_get_pen_scale (MP mp,pointer p) { 
9284   return mp_sqrt_det(mp, 
9285     left_x(p)-x_coord(p), right_x(p)-x_coord(p),
9286     left_y(p)-y_coord(p), right_y(p)-y_coord(p));
9287 }
9288
9289 @ @<Internal library ...@>=
9290 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) ;
9291
9292
9293 @ @<Initialize |maxabs|@>=
9294 maxabs=abs(a);
9295 if ( abs(b)>maxabs ) maxabs=abs(b);
9296 if ( abs(c)>maxabs ) maxabs=abs(c);
9297 if ( abs(d)>maxabs ) maxabs=abs(d)
9298
9299 @ When a picture contains text, this is represented by a fourteen-word node
9300 where the color information and |type| and |link| fields are augmented by
9301 additional fields that describe the text and  how it is transformed.
9302 The |path_p| and |pen_p| pointers are replaced by a number that identifies
9303 the font and a string number that gives the text to be displayed.
9304 The |width|, |height|, and |depth| fields
9305 give the dimensions of the text at its design size, and the remaining six
9306 words give a transformation to be applied to the text.  The |new_text_node|
9307 function initializes everything to default values so that the text comes out
9308 black with its reference point at the origin.
9309
9310 @d text_p(A) link((A)+1)  /* a string pointer for the text to display */
9311 @d font_n(A) info((A)+1)  /* the font number */
9312 @d width_val(A) mp->mem[(A)+7].sc  /* unscaled width of the text */
9313 @d height_val(A) mp->mem[(A)+9].sc  /* unscaled height of the text */
9314 @d depth_val(A) mp->mem[(A)+10].sc  /* unscaled depth of the text */
9315 @d text_tx_loc(A) ((A)+11)
9316   /* the first of six locations for transformation parameters */
9317 @d tx_val(A) mp->mem[(A)+11].sc  /* $x$ shift amount */
9318 @d ty_val(A) mp->mem[(A)+12].sc  /* $y$ shift amount */
9319 @d txx_val(A) mp->mem[(A)+13].sc  /* |txx| transformation parameter */
9320 @d txy_val(A) mp->mem[(A)+14].sc  /* |txy| transformation parameter */
9321 @d tyx_val(A) mp->mem[(A)+15].sc  /* |tyx| transformation parameter */
9322 @d tyy_val(A) mp->mem[(A)+16].sc  /* |tyy| transformation parameter */
9323 @d text_trans_part(A) mp->mem[(A)+11-x_part].sc
9324     /* interpret a text node pointer that has been offset by |x_part..yy_part| */
9325 @d text_node_size 17
9326
9327 @ @<Graphical object codes@>=
9328 mp_text_code=3,
9329
9330 @ @c @<Declare text measuring subroutines@>;
9331 pointer mp_new_text_node (MP mp,char *f,str_number s) {
9332   /* make a text node for font |f| and text string |s| */
9333   pointer t; /* the new node */
9334   t=mp_get_node(mp, text_node_size);
9335   type(t)=mp_text_code;
9336   text_p(t)=s;
9337   font_n(t)=mp_find_font(mp, f); /* this identifies the font */
9338   red_val(t)=0;
9339   green_val(t)=0;
9340   blue_val(t)=0;
9341   black_val(t)=0;
9342   color_model(t)=mp_uninitialized_model;
9343   pre_script(t)=null;
9344   post_script(t)=null;
9345   tx_val(t)=0; ty_val(t)=0;
9346   txx_val(t)=unity; txy_val(t)=0;
9347   tyx_val(t)=0; tyy_val(t)=unity;
9348   mp_set_text_box(mp, t); /* this finds the bounding box */
9349   return t;
9350 }
9351
9352 @ The last two types of graphical objects that can occur in an edge structure
9353 are clipping paths and \&{setbounds} paths.  These are slightly more difficult
9354 @:set_bounds_}{\&{setbounds} primitive@>
9355 to implement because we must keep track of exactly what is being clipped or
9356 bounded when pictures get merged together.  For this reason, each clipping or
9357 \&{setbounds} operation is represented by a pair of nodes:  first comes a
9358 two-word node whose |path_p| gives the relevant path, then there is the list
9359 of objects to clip or bound followed by a two-word node whose second word is
9360 unused.
9361
9362 Using at least two words for each graphical object node allows them all to be
9363 allocated and deallocated similarly with a global array |gr_object_size| to
9364 give the size in words for each object type.
9365
9366 @d start_clip_size 2
9367 @d start_bounds_size 2
9368 @d stop_clip_size 2 /* the second word is not used here */
9369 @d stop_bounds_size 2 /* the second word is not used here */
9370 @#
9371 @d stop_type(A) ((A)+2)
9372   /* matching |type| for |start_clip_code| or |start_bounds_code| */
9373 @d has_color(A) (type((A))<mp_start_clip_code)
9374   /* does a graphical object have color fields? */
9375 @d has_pen(A) (type((A))<mp_text_code)
9376   /* does a graphical object have a |pen_p| field? */
9377 @d is_start_or_stop(A) (type((A))>=mp_start_clip_code)
9378 @d is_stop(A) (type((A))>=mp_stop_clip_code)
9379
9380 @ @<Graphical object codes@>=
9381 mp_start_clip_code=4, /* |type| of a node that starts clipping */
9382 mp_start_bounds_code=5, /* |type| of a node that gives a \&{setbounds} path */
9383 mp_stop_clip_code=6, /* |type| of a node that stops clipping */
9384 mp_stop_bounds_code=7, /* |type| of a node that stops \&{setbounds} */
9385
9386 @ @c 
9387 pointer mp_new_bounds_node (MP mp,pointer p, small_number  c) {
9388   /* make a node of type |c| where |p| is the clipping or \&{setbounds} path */
9389   pointer t; /* the new node */
9390   t=mp_get_node(mp, mp->gr_object_size[c]);
9391   type(t)=c;
9392   path_p(t)=p;
9393   return t;
9394 };
9395
9396 @ We need an array to keep track of the sizes of graphical objects.
9397
9398 @<Glob...@>=
9399 small_number gr_object_size[mp_stop_bounds_code+1];
9400
9401 @ @<Set init...@>=
9402 mp->gr_object_size[mp_fill_code]=fill_node_size;
9403 mp->gr_object_size[mp_stroked_code]=stroked_node_size;
9404 mp->gr_object_size[mp_text_code]=text_node_size;
9405 mp->gr_object_size[mp_start_clip_code]=start_clip_size;
9406 mp->gr_object_size[mp_stop_clip_code]=stop_clip_size;
9407 mp->gr_object_size[mp_start_bounds_code]=start_bounds_size;
9408 mp->gr_object_size[mp_stop_bounds_code]=stop_bounds_size;
9409
9410 @ All the essential information in an edge structure is encoded as a linked list
9411 of graphical objects as we have just seen, but it is helpful to add some
9412 redundant information.  A single edge structure might be used as a dash pattern
9413 many times, and it would be nice to avoid scanning the same structure
9414 repeatedly.  Thus, an edge structure known to be a suitable dash pattern
9415 has a header that gives a list of dashes in a sorted order designed for rapid
9416 translation into \ps.
9417
9418 Each dash is represented by a three-word node containing the initial and final
9419 $x$~coordinates as well as the usual |link| field.  The |link| fields points to
9420 the dash node with the next higher $x$-coordinates and the final link points
9421 to a special location called |null_dash|.  (There should be no overlap between
9422 dashes).  Since the $y$~coordinate of the dash pattern is needed to determine
9423 the period of repetition, this needs to be stored in the edge header along
9424 with a pointer to the list of dash nodes.
9425
9426 @d start_x(A) mp->mem[(A)+1].sc  /* the starting $x$~coordinate in a dash node */
9427 @d stop_x(A) mp->mem[(A)+2].sc  /* the ending $x$~coordinate in a dash node */
9428 @d dash_node_size 3
9429 @d dash_list link
9430   /* in an edge header this points to the first dash node */
9431 @d dash_y(A) mp->mem[(A)+1].sc  /* $y$ value for the dash list in an edge header */
9432
9433 @ It is also convenient for an edge header to contain the bounding
9434 box information needed by the \&{llcorner} and \&{urcorner} operators
9435 so that this does not have to be recomputed unnecessarily.  This is done by
9436 adding fields for the $x$~and $y$ extremes as well as a pointer that indicates
9437 how far the bounding box computation has gotten.  Thus if the user asks for
9438 the bounding box and then adds some more text to the picture before asking
9439 for more bounding box information, the second computation need only look at
9440 the additional text.
9441
9442 When the bounding box has not been computed, the |bblast| pointer points
9443 to a dummy link at the head of the graphical object list while the |minx_val|
9444 and |miny_val| fields contain |el_gordo| and the |maxx_val| and |maxy_val|
9445 fields contain |-el_gordo|.
9446
9447 Since the bounding box of pictures containing objects of type
9448 |mp_start_bounds_code| depends on the value of \&{truecorners}, the bounding box
9449 @:mp_true_corners_}{\&{truecorners} primitive@>
9450 data might not be valid for all values of this parameter.  Hence, the |bbtype|
9451 field is needed to keep track of this.
9452
9453 @d minx_val(A) mp->mem[(A)+2].sc
9454 @d miny_val(A) mp->mem[(A)+3].sc
9455 @d maxx_val(A) mp->mem[(A)+4].sc
9456 @d maxy_val(A) mp->mem[(A)+5].sc
9457 @d bblast(A) link((A)+6)  /* last item considered in bounding box computation */
9458 @d bbtype(A) info((A)+6)  /* tells how bounding box data depends on \&{truecorners} */
9459 @d dummy_loc(A) ((A)+7)  /* where the object list begins in an edge header */
9460 @d no_bounds 0
9461   /* |bbtype| value when bounding box data is valid for all \&{truecorners} values */
9462 @d bounds_set 1
9463   /* |bbtype| value when bounding box data is for \&{truecorners}${}\le 0$ */
9464 @d bounds_unset 2
9465   /* |bbtype| value when bounding box data is for \&{truecorners}${}>0$ */
9466
9467 @c 
9468 void mp_init_bbox (MP mp,pointer h) {
9469   /* Initialize the bounding box information in edge structure |h| */
9470   bblast(h)=dummy_loc(h);
9471   bbtype(h)=no_bounds;
9472   minx_val(h)=el_gordo;
9473   miny_val(h)=el_gordo;
9474   maxx_val(h)=-el_gordo;
9475   maxy_val(h)=-el_gordo;
9476 }
9477
9478 @ The only other entries in an edge header are a reference count in the first
9479 word and a pointer to the tail of the object list in the last word.
9480
9481 @d obj_tail(A) info((A)+7)  /* points to the last entry in the object list */
9482 @d edge_header_size 8
9483
9484 @c 
9485 void mp_init_edges (MP mp,pointer h) {
9486   /* initialize an edge header to null values */
9487   dash_list(h)=null_dash;
9488   obj_tail(h)=dummy_loc(h);
9489   link(dummy_loc(h))=null;
9490   ref_count(h)=null;
9491   mp_init_bbox(mp, h);
9492 }
9493
9494 @ Here is how edge structures are deleted.  The process can be recursive because
9495 of the need to dereference edge structures that are used as dash patterns.
9496 @^recursion@>
9497
9498 @d add_edge_ref(A) incr(ref_count(A))
9499 @d delete_edge_ref(A) { 
9500    if ( ref_count((A))==null ) 
9501      mp_toss_edges(mp, A);
9502    else 
9503      decr(ref_count(A)); 
9504    }
9505
9506 @<Declare the recycling subroutines@>=
9507 void mp_flush_dash_list (MP mp,pointer h);
9508 pointer mp_toss_gr_object (MP mp,pointer p) ;
9509 void mp_toss_edges (MP mp,pointer h) ;
9510
9511 @ @c void mp_toss_edges (MP mp,pointer h) {
9512   pointer p,q;  /* pointers that scan the list being recycled */
9513   pointer r; /* an edge structure that object |p| refers to */
9514   mp_flush_dash_list(mp, h);
9515   q=link(dummy_loc(h));
9516   while ( (q!=null) ) { 
9517     p=q; q=link(q);
9518     r=mp_toss_gr_object(mp, p);
9519     if ( r!=null ) delete_edge_ref(r);
9520   }
9521   mp_free_node(mp, h,edge_header_size);
9522 }
9523 void mp_flush_dash_list (MP mp,pointer h) {
9524   pointer p,q;  /* pointers that scan the list being recycled */
9525   q=dash_list(h);
9526   while ( q!=null_dash ) { 
9527     p=q; q=link(q);
9528     mp_free_node(mp, p,dash_node_size);
9529   }
9530   dash_list(h)=null_dash;
9531 }
9532 pointer mp_toss_gr_object (MP mp,pointer p) {
9533   /* returns an edge structure that needs to be dereferenced */
9534   pointer e; /* the edge structure to return */
9535   e=null;
9536   @<Prepare to recycle graphical object |p|@>;
9537   mp_free_node(mp, p,mp->gr_object_size[type(p)]);
9538   return e;
9539 }
9540
9541 @ @<Prepare to recycle graphical object |p|@>=
9542 switch (type(p)) {
9543 case mp_fill_code: 
9544   mp_toss_knot_list(mp, path_p(p));
9545   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9546   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9547   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9548   break;
9549 case mp_stroked_code: 
9550   mp_toss_knot_list(mp, path_p(p));
9551   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9552   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9553   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9554   e=dash_p(p);
9555   break;
9556 case mp_text_code: 
9557   delete_str_ref(text_p(p));
9558   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9559   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9560   break;
9561 case mp_start_clip_code:
9562 case mp_start_bounds_code: 
9563   mp_toss_knot_list(mp, path_p(p));
9564   break;
9565 case mp_stop_clip_code:
9566 case mp_stop_bounds_code: 
9567   break;
9568 } /* there are no other cases */
9569
9570 @ If we use |add_edge_ref| to ``copy'' edge structures, the real copying needs
9571 to be done before making a significant change to an edge structure.  Much of
9572 the work is done in a separate routine |copy_objects| that copies a list of
9573 graphical objects into a new edge header.
9574
9575 @c @<Declare a function called |copy_objects|@>;
9576 pointer mp_private_edges (MP mp,pointer h) {
9577   /* make a private copy of the edge structure headed by |h| */
9578   pointer hh;  /* the edge header for the new copy */
9579   pointer p,pp;  /* pointers for copying the dash list */
9580   if ( ref_count(h)==null ) {
9581     return h;
9582   } else { 
9583     decr(ref_count(h));
9584     hh=mp_copy_objects(mp, link(dummy_loc(h)),null);
9585     @<Copy the dash list from |h| to |hh|@>;
9586     @<Copy the bounding box information from |h| to |hh| and make |bblast(hh)|
9587       point into the new object list@>;
9588     return hh;
9589   }
9590 }
9591
9592 @ Here we use the fact that |dash_list(hh)=link(hh)|.
9593 @^data structure assumptions@>
9594
9595 @<Copy the dash list from |h| to |hh|@>=
9596 pp=hh; p=dash_list(h);
9597 while ( (p!=null_dash) ) { 
9598   link(pp)=mp_get_node(mp, dash_node_size);
9599   pp=link(pp);
9600   start_x(pp)=start_x(p);
9601   stop_x(pp)=stop_x(p);
9602   p=link(p);
9603 }
9604 link(pp)=null_dash;
9605 dash_y(hh)=dash_y(h)
9606
9607
9608 @ |h| is an edge structure
9609
9610 @d gr_start_x(A)    (A)->start_x_field
9611 @d gr_stop_x(A)     (A)->stop_x_field
9612 @d gr_dash_link(A)  (A)->next_field
9613
9614 @d gr_dash_list(A)  (A)->list_field
9615 @d gr_dash_y(A)     (A)->y_field
9616
9617 @c
9618 struct mp_dash_list *mp_export_dashes (MP mp, pointer h) {
9619   struct mp_dash_list *dl;
9620   struct mp_dash_item *dh, *di;
9621   pointer p;
9622   if (h==null ||  dash_list(h)==null_dash) 
9623         return NULL;
9624   p = dash_list(h);
9625   dl = mp_xmalloc(mp,1,sizeof(struct mp_dash_list));
9626   gr_dash_list(dl) = NULL;
9627   gr_dash_y(dl) = dash_y(h);
9628   dh = NULL;
9629   while (p != null_dash) { 
9630     di=mp_xmalloc(mp,1,sizeof(struct mp_dash_item));
9631     gr_dash_link(di) = NULL;
9632     gr_start_x(di) = start_x(p);
9633     gr_stop_x(di) = stop_x(p);
9634     if (dh==NULL) {
9635       gr_dash_list(dl) = di;
9636     } else {
9637       gr_dash_link(dh) = di;
9638     }
9639     dh = di;
9640     p=link(p);
9641   }
9642   return dl;
9643 }
9644
9645
9646 @ @<Copy the bounding box information from |h| to |hh|...@>=
9647 minx_val(hh)=minx_val(h);
9648 miny_val(hh)=miny_val(h);
9649 maxx_val(hh)=maxx_val(h);
9650 maxy_val(hh)=maxy_val(h);
9651 bbtype(hh)=bbtype(h);
9652 p=dummy_loc(h); pp=dummy_loc(hh);
9653 while ((p!=bblast(h)) ) { 
9654   if ( p==null ) mp_confusion(mp, "bblast");
9655 @:this can't happen bblast}{\quad bblast@>
9656   p=link(p); pp=link(pp);
9657 }
9658 bblast(hh)=pp
9659
9660 @ Here is the promised routine for copying graphical objects into a new edge
9661 structure.  It starts copying at object~|p| and stops just before object~|q|.
9662 If |q| is null, it copies the entire sublist headed at |p|.  The resulting edge
9663 structure requires further initialization by |init_bbox|.
9664
9665 @<Declare a function called |copy_objects|@>=
9666 pointer mp_copy_objects (MP mp, pointer p, pointer q) {
9667   pointer hh;  /* the new edge header */
9668   pointer pp;  /* the last newly copied object */
9669   small_number k;  /* temporary register */
9670   hh=mp_get_node(mp, edge_header_size);
9671   dash_list(hh)=null_dash;
9672   ref_count(hh)=null;
9673   pp=dummy_loc(hh);
9674   while ( (p!=q) ) {
9675     @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>;
9676   }
9677   obj_tail(hh)=pp;
9678   link(pp)=null;
9679   return hh;
9680 }
9681
9682 @ @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>=
9683 { k=mp->gr_object_size[type(p)];
9684   link(pp)=mp_get_node(mp, k);
9685   pp=link(pp);
9686   while ( (k>0) ) { decr(k); mp->mem[pp+k]=mp->mem[p+k];  };
9687   @<Fix anything in graphical object |pp| that should differ from the
9688     corresponding field in |p|@>;
9689   p=link(p);
9690 }
9691
9692 @ @<Fix anything in graphical object |pp| that should differ from the...@>=
9693 switch (type(p)) {
9694 case mp_start_clip_code:
9695 case mp_start_bounds_code: 
9696   path_p(pp)=mp_copy_path(mp, path_p(p));
9697   break;
9698 case mp_fill_code: 
9699   path_p(pp)=mp_copy_path(mp, path_p(p));
9700   if ( pen_p(p)!=null ) pen_p(pp)=copy_pen(pen_p(p));
9701   break;
9702 case mp_stroked_code: 
9703   path_p(pp)=mp_copy_path(mp, path_p(p));
9704   pen_p(pp)=copy_pen(pen_p(p));
9705   if ( dash_p(p)!=null ) add_edge_ref(dash_p(pp));
9706   break;
9707 case mp_text_code: 
9708   add_str_ref(text_p(pp));
9709   break;
9710 case mp_stop_clip_code:
9711 case mp_stop_bounds_code: 
9712   break;
9713 }  /* there are no other cases */
9714
9715 @ Here is one way to find an acceptable value for the second argument to
9716 |copy_objects|.  Given a non-null graphical object list, |skip_1component|
9717 skips past one picture component, where a ``picture component'' is a single
9718 graphical object, or a start bounds or start clip object and everything up
9719 through the matching stop bounds or stop clip object.  The macro version avoids
9720 procedure call overhead and error handling: |skip_component(p)(e)| advances |p|
9721 unless |p| points to a stop bounds or stop clip node, in which case it executes
9722 |e| instead.
9723
9724 @d skip_component(A)
9725     if ( ! is_start_or_stop((A)) ) (A)=link((A));
9726     else if ( ! is_stop((A)) ) (A)=mp_skip_1component(mp, (A));
9727     else 
9728
9729 @c 
9730 pointer mp_skip_1component (MP mp,pointer p) {
9731   integer lev; /* current nesting level */
9732   lev=0;
9733   do {  
9734    if ( is_start_or_stop(p) ) {
9735      if ( is_stop(p) ) decr(lev);  else incr(lev);
9736    }
9737    p=link(p);
9738   } while (lev!=0);
9739   return p;
9740 }
9741
9742 @ Here is a diagnostic routine for printing an edge structure in symbolic form.
9743
9744 @<Declare subroutines for printing expressions@>=
9745 @<Declare subroutines needed by |print_edges|@>;
9746 void mp_print_edges (MP mp,pointer h, char *s, boolean nuline) {
9747   pointer p;  /* a graphical object to be printed */
9748   pointer hh,pp;  /* temporary pointers */
9749   scaled scf;  /* a scale factor for the dash pattern */
9750   boolean ok_to_dash;  /* |false| for polygonal pen strokes */
9751   mp_print_diagnostic(mp, "Edge structure",s,nuline);
9752   p=dummy_loc(h);
9753   while ( link(p)!=null ) { 
9754     p=link(p);
9755     mp_print_ln(mp);
9756     switch (type(p)) {
9757       @<Cases for printing graphical object node |p|@>;
9758     default: 
9759           mp_print(mp, "[unknown object type!]");
9760           break;
9761     }
9762   }
9763   mp_print_nl(mp, "End edges");
9764   if ( p!=obj_tail(h) ) mp_print(mp, "?");
9765 @.End edges?@>
9766   mp_end_diagnostic(mp, true);
9767 }
9768
9769 @ @<Cases for printing graphical object node |p|@>=
9770 case mp_fill_code: 
9771   mp_print(mp, "Filled contour ");
9772   mp_print_obj_color(mp, p);
9773   mp_print_char(mp, ':'); mp_print_ln(mp);
9774   mp_pr_path(mp, path_p(p)); mp_print_ln(mp);
9775   if ( (pen_p(p)!=null) ) {
9776     @<Print join type for graphical object |p|@>;
9777     mp_print(mp, " with pen"); mp_print_ln(mp);
9778     mp_pr_pen(mp, pen_p(p));
9779   }
9780   break;
9781
9782 @ @<Print join type for graphical object |p|@>=
9783 switch (ljoin_val(p)) {
9784 case 0:
9785   mp_print(mp, "mitered joins limited ");
9786   mp_print_scaled(mp, miterlim_val(p));
9787   break;
9788 case 1:
9789   mp_print(mp, "round joins");
9790   break;
9791 case 2:
9792   mp_print(mp, "beveled joins");
9793   break;
9794 default: 
9795   mp_print(mp, "?? joins");
9796 @.??@>
9797   break;
9798 }
9799
9800 @ For stroked nodes, we need to print |lcap_val(p)| as well.
9801
9802 @<Print join and cap types for stroked node |p|@>=
9803 switch (lcap_val(p)) {
9804 case 0:mp_print(mp, "butt"); break;
9805 case 1:mp_print(mp, "round"); break;
9806 case 2:mp_print(mp, "square"); break;
9807 default: mp_print(mp, "??"); break;
9808 @.??@>
9809 }
9810 mp_print(mp, " ends, ");
9811 @<Print join type for graphical object |p|@>
9812
9813 @ Here is a routine that prints the color of a graphical object if it isn't
9814 black (the default color).
9815
9816 @<Declare subroutines needed by |print_edges|@>=
9817 @<Declare a procedure called |print_compact_node|@>;
9818 void mp_print_obj_color (MP mp,pointer p) { 
9819   if ( color_model(p)==mp_grey_model ) {
9820     if ( grey_val(p)>0 ) { 
9821       mp_print(mp, "greyed ");
9822       mp_print_compact_node(mp, obj_grey_loc(p),1);
9823     };
9824   } else if ( color_model(p)==mp_cmyk_model ) {
9825     if ( (cyan_val(p)>0) || (magenta_val(p)>0) || 
9826          (yellow_val(p)>0) || (black_val(p)>0) ) { 
9827       mp_print(mp, "processcolored ");
9828       mp_print_compact_node(mp, obj_cyan_loc(p),4);
9829     };
9830   } else if ( color_model(p)==mp_rgb_model ) {
9831     if ( (red_val(p)>0) || (green_val(p)>0) || (blue_val(p)>0) ) { 
9832       mp_print(mp, "colored "); 
9833       mp_print_compact_node(mp, obj_red_loc(p),3);
9834     };
9835   }
9836 }
9837
9838 @ We also need a procedure for printing consecutive scaled values as if they
9839 were a known big node.
9840
9841 @<Declare a procedure called |print_compact_node|@>=
9842 void mp_print_compact_node (MP mp,pointer p, small_number k) {
9843   pointer q;  /* last location to print */
9844   q=p+k-1;
9845   mp_print_char(mp, '(');
9846   while ( p<=q ){ 
9847     mp_print_scaled(mp, mp->mem[p].sc);
9848     if ( p<q ) mp_print_char(mp, ',');
9849     incr(p);
9850   }
9851   mp_print_char(mp, ')');
9852 }
9853
9854 @ @<Cases for printing graphical object node |p|@>=
9855 case mp_stroked_code: 
9856   mp_print(mp, "Filled pen stroke ");
9857   mp_print_obj_color(mp, p);
9858   mp_print_char(mp, ':'); mp_print_ln(mp);
9859   mp_pr_path(mp, path_p(p));
9860   if ( dash_p(p)!=null ) { 
9861     mp_print_nl(mp, "dashed (");
9862     @<Finish printing the dash pattern that |p| refers to@>;
9863   }
9864   mp_print_ln(mp);
9865   @<Print join and cap types for stroked node |p|@>;
9866   mp_print(mp, " with pen"); mp_print_ln(mp);
9867   if ( pen_p(p)==null ) mp_print(mp, "???"); /* shouldn't happen */
9868 @.???@>
9869   else mp_pr_pen(mp, pen_p(p));
9870   break;
9871
9872 @ Normally, the  |dash_list| field in an edge header is set to |null_dash|
9873 when it is not known to define a suitable dash pattern.  This is disallowed
9874 here because the |dash_p| field should never point to such an edge header.
9875 Note that memory is allocated for |start_x(null_dash)| and we are free to
9876 give it any convenient value.
9877
9878 @<Finish printing the dash pattern that |p| refers to@>=
9879 ok_to_dash=pen_is_elliptical(pen_p(p));
9880 if ( ! ok_to_dash ) scf=unity; else scf=dash_scale(p);
9881 hh=dash_p(p);
9882 pp=dash_list(hh);
9883 if ( (pp==null_dash) || (dash_y(hh)<0) ) {
9884   mp_print(mp, " ??");
9885 } else { start_x(null_dash)=start_x(pp)+dash_y(hh);
9886   while ( pp!=null_dash ) { 
9887     mp_print(mp, "on ");
9888     mp_print_scaled(mp, mp_take_scaled(mp, stop_x(pp)-start_x(pp),scf));
9889     mp_print(mp, " off ");
9890     mp_print_scaled(mp, mp_take_scaled(mp, start_x(link(pp))-stop_x(pp),scf));
9891     pp = link(pp);
9892     if ( pp!=null_dash ) mp_print_char(mp, ' ');
9893   }
9894   mp_print(mp, ") shifted ");
9895   mp_print_scaled(mp, -mp_take_scaled(mp, mp_dash_offset(mp, hh),scf));
9896   if ( ! ok_to_dash || (dash_y(hh)==0) ) mp_print(mp, " (this will be ignored)");
9897 }
9898
9899 @ @<Declare subroutines needed by |print_edges|@>=
9900 scaled mp_dash_offset (MP mp,pointer h) {
9901   scaled x;  /* the answer */
9902   if (dash_list(h)==null_dash || dash_y(h)<0) mp_confusion(mp, "dash0");
9903 @:this can't happen dash0}{\quad dash0@>
9904   if ( dash_y(h)==0 ) {
9905     x=0; 
9906   } else { 
9907     x=-(start_x(dash_list(h)) % dash_y(h));
9908     if ( x<0 ) x=x+dash_y(h);
9909   }
9910   return x;
9911 }
9912
9913 @ @<Cases for printing graphical object node |p|@>=
9914 case mp_text_code: 
9915   mp_print_char(mp, '"'); mp_print_str(mp,text_p(p));
9916   mp_print(mp, "\" infont \""); mp_print(mp, mp->font_name[font_n(p)]);
9917   mp_print_char(mp, '"'); mp_print_ln(mp);
9918   mp_print_obj_color(mp, p);
9919   mp_print(mp, "transformed ");
9920   mp_print_compact_node(mp, text_tx_loc(p),6);
9921   break;
9922
9923 @ @<Cases for printing graphical object node |p|@>=
9924 case mp_start_clip_code: 
9925   mp_print(mp, "clipping path:");
9926   mp_print_ln(mp);
9927   mp_pr_path(mp, path_p(p));
9928   break;
9929 case mp_stop_clip_code: 
9930   mp_print(mp, "stop clipping");
9931   break;
9932
9933 @ @<Cases for printing graphical object node |p|@>=
9934 case mp_start_bounds_code: 
9935   mp_print(mp, "setbounds path:");
9936   mp_print_ln(mp);
9937   mp_pr_path(mp, path_p(p));
9938   break;
9939 case mp_stop_bounds_code: 
9940   mp_print(mp, "end of setbounds");
9941   break;
9942
9943 @ To initialize the |dash_list| field in an edge header~|h|, we need a
9944 subroutine that scans an edge structure and tries to interpret it as a dash
9945 pattern.  This can only be done when there are no filled regions or clipping
9946 paths and all the pen strokes have the same color.  The first step is to let
9947 $y_0$ be the initial $y$~coordinate of the first pen stroke.  Then we implicitly
9948 project all the pen stroke paths onto the line $y=y_0$ and require that there
9949 be no retracing.  If the resulting paths cover a range of $x$~coordinates of
9950 length $\Delta x$, we set |dash_y(h)| to the length of the dash pattern by
9951 finding the maximum of $\Delta x$ and the absolute value of~$y_0$.
9952
9953 @c @<Declare a procedure called |x_retrace_error|@>;
9954 pointer mp_make_dashes (MP mp,pointer h) { /* returns |h| or |null| */
9955   pointer p;  /* this scans the stroked nodes in the object list */
9956   pointer p0;  /* if not |null| this points to the first stroked node */
9957   pointer pp,qq,rr;  /* pointers into |path_p(p)| */
9958   pointer d,dd;  /* pointers used to create the dash list */
9959   @<Other local variables in |make_dashes|@>;
9960   scaled y0=0;  /* the initial $y$ coordinate */
9961   if ( dash_list(h)!=null_dash ) 
9962         return h;
9963   p0=null;
9964   p=link(dummy_loc(h));
9965   while ( p!=null ) { 
9966     if ( type(p)!=mp_stroked_code ) {
9967       @<Compain that the edge structure contains a node of the wrong type
9968         and |goto not_found|@>;
9969     }
9970     pp=path_p(p);
9971     if ( p0==null ){ p0=p; y0=y_coord(pp);  };
9972     @<Make |d| point to a new dash node created from stroke |p| and path |pp|
9973       or |goto not_found| if there is an error@>;
9974     @<Insert |d| into the dash list and |goto not_found| if there is an error@>;
9975     p=link(p);
9976   }
9977   if ( dash_list(h)==null_dash ) 
9978     goto NOT_FOUND; /* No error message */
9979   @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>;
9980   @<Set |dash_y(h)| and merge the first and last dashes if necessary@>;
9981   return h;
9982 NOT_FOUND: 
9983   @<Flush the dash list, recycle |h| and return |null|@>;
9984 };
9985
9986 @ @<Compain that the edge structure contains a node of the wrong type...@>=
9987
9988 print_err("Picture is too complicated to use as a dash pattern");
9989 help3("When you say `dashed p', picture p should not contain any")
9990   ("text, filled regions, or clipping paths.  This time it did")
9991   ("so I'll just make it a solid line instead.");
9992 mp_put_get_error(mp);
9993 goto NOT_FOUND;
9994 }
9995
9996 @ A similar error occurs when monotonicity fails.
9997
9998 @<Declare a procedure called |x_retrace_error|@>=
9999 void mp_x_retrace_error (MP mp) { 
10000 print_err("Picture is too complicated to use as a dash pattern");
10001 help3("When you say `dashed p', every path in p should be monotone")
10002   ("in x and there must be no overlapping.  This failed")
10003   ("so I'll just make it a solid line instead.");
10004 mp_put_get_error(mp);
10005 }
10006
10007 @ We stash |p| in |info(d)| if |dash_p(p)<>0| so that subsequent processing can
10008 handle the case where the pen stroke |p| is itself dashed.
10009
10010 @<Make |d| point to a new dash node created from stroke |p| and path...@>=
10011 @<Make sure |p| and |p0| are the same color and |goto not_found| if there is
10012   an error@>;
10013 rr=pp;
10014 if ( link(pp)!=pp ) {
10015   do {  
10016     qq=rr; rr=link(rr);
10017     @<Check for retracing between knots |qq| and |rr| and |goto not_found|
10018       if there is a problem@>;
10019   } while (right_type(rr)!=mp_endpoint);
10020 }
10021 d=mp_get_node(mp, dash_node_size);
10022 if ( dash_p(p)==0 ) info(d)=0;  else info(d)=p;
10023 if ( x_coord(pp)<x_coord(rr) ) { 
10024   start_x(d)=x_coord(pp);
10025   stop_x(d)=x_coord(rr);
10026 } else { 
10027   start_x(d)=x_coord(rr);
10028   stop_x(d)=x_coord(pp);
10029 }
10030
10031 @ We also need to check for the case where the segment from |qq| to |rr| is
10032 monotone in $x$ but is reversed relative to the path from |pp| to |qq|.
10033
10034 @<Check for retracing between knots |qq| and |rr| and |goto not_found|...@>=
10035 x0=x_coord(qq);
10036 x1=right_x(qq);
10037 x2=left_x(rr);
10038 x3=x_coord(rr);
10039 if ( (x0>x1) || (x1>x2) || (x2>x3) ) {
10040   if ( (x0<x1) || (x1<x2) || (x2<x3) ) {
10041     if ( mp_ab_vs_cd(mp, x2-x1,x2-x1,x1-x0,x3-x2)>0 ) {
10042       mp_x_retrace_error(mp); goto NOT_FOUND;
10043     }
10044   }
10045 }
10046 if ( (x_coord(pp)>x0) || (x0>x3) ) {
10047   if ( (x_coord(pp)<x0) || (x0<x3) ) {
10048     mp_x_retrace_error(mp); goto NOT_FOUND;
10049   }
10050 }
10051
10052 @ @<Other local variables in |make_dashes|@>=
10053   scaled x0,x1,x2,x3;  /* $x$ coordinates of the segment from |qq| to |rr| */
10054
10055 @ @<Make sure |p| and |p0| are the same color and |goto not_found|...@>=
10056 if ( (red_val(p)!=red_val(p0)) || (black_val(p)!=black_val(p0)) ||
10057   (green_val(p)!=green_val(p0)) || (blue_val(p)!=blue_val(p0)) ) {
10058   print_err("Picture is too complicated to use as a dash pattern");
10059   help3("When you say `dashed p', everything in picture p should")
10060     ("be the same color.  I can\'t handle your color changes")
10061     ("so I'll just make it a solid line instead.");
10062   mp_put_get_error(mp);
10063   goto NOT_FOUND;
10064 }
10065
10066 @ @<Insert |d| into the dash list and |goto not_found| if there is an error@>=
10067 start_x(null_dash)=stop_x(d);
10068 dd=h; /* this makes |link(dd)=dash_list(h)| */
10069 while ( start_x(link(dd))<stop_x(d) )
10070   dd=link(dd);
10071 if ( dd!=h ) {
10072   if ( (stop_x(dd)>start_x(d)) )
10073     { mp_x_retrace_error(mp); goto NOT_FOUND;  };
10074 }
10075 link(d)=link(dd);
10076 link(dd)=d
10077
10078 @ @<Set |dash_y(h)| and merge the first and last dashes if necessary@>=
10079 d=dash_list(h);
10080 while ( (link(d)!=null_dash) )
10081   d=link(d);
10082 dd=dash_list(h);
10083 dash_y(h)=stop_x(d)-start_x(dd);
10084 if ( abs(y0)>dash_y(h) ) {
10085   dash_y(h)=abs(y0);
10086 } else if ( d!=dd ) { 
10087   dash_list(h)=link(dd);
10088   stop_x(d)=stop_x(dd)+dash_y(h);
10089   mp_free_node(mp, dd,dash_node_size);
10090 }
10091
10092 @ We get here when the argument is a null picture or when there is an error.
10093 Recovering from an error involves making |dash_list(h)| empty to indicate
10094 that |h| is not known to be a valid dash pattern.  We also dereference |h|
10095 since it is not being used for the return value.
10096
10097 @<Flush the dash list, recycle |h| and return |null|@>=
10098 mp_flush_dash_list(mp, h);
10099 delete_edge_ref(h);
10100 return null
10101
10102 @ Having carefully saved the dashed stroked nodes in the
10103 corresponding dash nodes, we must be prepared to break up these dashes into
10104 smaller dashes.
10105
10106 @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>=
10107 d=h;  /* now |link(d)=dash_list(h)| */
10108 while ( link(d)!=null_dash ) {
10109   ds=info(link(d));
10110   if ( ds==null ) { 
10111     d=link(d);
10112   } else {
10113     hh=dash_p(ds);
10114     hsf=dash_scale(ds);
10115     if ( (hh==null) ) mp_confusion(mp, "dash1");
10116 @:this can't happen dash0}{\quad dash1@>
10117     if ( dash_y(hh)==0 ) {
10118       d=link(d);
10119     } else { 
10120       if ( dash_list(hh)==null ) mp_confusion(mp, "dash1");
10121 @:this can't happen dash0}{\quad dash1@>
10122       @<Replace |link(d)| by a dashed version as determined by edge header
10123           |hh| and scale factor |ds|@>;
10124     }
10125   }
10126 }
10127
10128 @ @<Other local variables in |make_dashes|@>=
10129 pointer dln;  /* |link(d)| */
10130 pointer hh;  /* an edge header that tells how to break up |dln| */
10131 scaled hsf;  /* the dash pattern from |hh| gets scaled by this */
10132 pointer ds;  /* the stroked node from which |hh| and |hsf| are derived */
10133 scaled xoff;  /* added to $x$ values in |dash_list(hh)| to match |dln| */
10134
10135 @ @<Replace |link(d)| by a dashed version as determined by edge header...@>=
10136 dln=link(d);
10137 dd=dash_list(hh);
10138 xoff=start_x(dln)-mp_take_scaled(mp, hsf,start_x(dd))-
10139         mp_take_scaled(mp, hsf,mp_dash_offset(mp, hh));
10140 start_x(null_dash)=mp_take_scaled(mp, hsf,start_x(dd))
10141                    +mp_take_scaled(mp, hsf,dash_y(hh));
10142 stop_x(null_dash)=start_x(null_dash);
10143 @<Advance |dd| until finding the first dash that overlaps |dln| when
10144   offset by |xoff|@>;
10145 while ( start_x(dln)<=stop_x(dln) ) {
10146   @<If |dd| has `fallen off the end', back up to the beginning and fix |xoff|@>;
10147   @<Insert a dash between |d| and |dln| for the overlap with the offset version
10148     of |dd|@>;
10149   dd=link(dd);
10150   start_x(dln)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10151 }
10152 link(d)=link(dln);
10153 mp_free_node(mp, dln,dash_node_size)
10154
10155 @ The name of this module is a bit of a lie because we actually just find the
10156 first |dd| where |take_scaled (hsf, stop_x(dd))| is large enough to make an
10157 overlap possible.  It could be that the unoffset version of dash |dln| falls
10158 in the gap between |dd| and its predecessor.
10159
10160 @<Advance |dd| until finding the first dash that overlaps |dln| when...@>=
10161 while ( xoff+mp_take_scaled(mp, hsf,stop_x(dd))<start_x(dln) ) {
10162   dd=link(dd);
10163 }
10164
10165 @ @<If |dd| has `fallen off the end', back up to the beginning and fix...@>=
10166 if ( dd==null_dash ) { 
10167   dd=dash_list(hh);
10168   xoff=xoff+mp_take_scaled(mp, hsf,dash_y(hh));
10169 }
10170
10171 @ At this point we already know that
10172 |start_x(dln)<=xoff+take_scaled(hsf,stop_x(dd))|.
10173
10174 @<Insert a dash between |d| and |dln| for the overlap with the offset...@>=
10175 if ( (xoff+mp_take_scaled(mp, hsf,start_x(dd)))<=stop_x(dln) ) {
10176   link(d)=mp_get_node(mp, dash_node_size);
10177   d=link(d);
10178   link(d)=dln;
10179   if ( start_x(dln)>(xoff+mp_take_scaled(mp, hsf,start_x(dd))))
10180     start_x(d)=start_x(dln);
10181   else 
10182     start_x(d)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10183   if ( stop_x(dln)<(xoff+mp_take_scaled(mp, hsf,stop_x(dd)))) 
10184     stop_x(d)=stop_x(dln);
10185   else 
10186     stop_x(d)=xoff+mp_take_scaled(mp, hsf,stop_x(dd));
10187 }
10188
10189 @ The next major task is to update the bounding box information in an edge
10190 header~|h|. This is done via a procedure |adjust_bbox| that enlarges an edge
10191 header's bounding box to accommodate the box computed by |path_bbox| or
10192 |pen_bbox|. (This is stored in global variables |minx|, |miny|, |maxx|, and
10193 |maxy|.)
10194
10195 @c void mp_adjust_bbox (MP mp,pointer h) { 
10196   if ( minx<minx_val(h) ) minx_val(h)=minx;
10197   if ( miny<miny_val(h) ) miny_val(h)=miny;
10198   if ( maxx>maxx_val(h) ) maxx_val(h)=maxx;
10199   if ( maxy>maxy_val(h) ) maxy_val(h)=maxy;
10200 }
10201
10202 @ Here is a special routine for updating the bounding box information in
10203 edge header~|h| to account for the squared-off ends of a non-cyclic path~|p|
10204 that is to be stroked with the pen~|pp|.
10205
10206 @c void mp_box_ends (MP mp, pointer p, pointer pp, pointer h) {
10207   pointer q;  /* a knot node adjacent to knot |p| */
10208   fraction dx,dy;  /* a unit vector in the direction out of the path at~|p| */
10209   scaled d;  /* a factor for adjusting the length of |(dx,dy)| */
10210   scaled z;  /* a coordinate being tested against the bounding box */
10211   scaled xx,yy;  /* the extreme pen vertex in the |(dx,dy)| direction */
10212   integer i; /* a loop counter */
10213   if ( right_type(p)!=mp_endpoint ) { 
10214     q=link(p);
10215     while (1) { 
10216       @<Make |(dx,dy)| the final direction for the path segment from
10217         |q| to~|p|; set~|d|@>;
10218       d=mp_pyth_add(mp, dx,dy);
10219       if ( d>0 ) { 
10220          @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>;
10221          for (i=1;i<= 2;i++) { 
10222            @<Use |(dx,dy)| to generate a vertex of the square end cap and
10223              update the bounding box to accommodate it@>;
10224            dx=-dx; dy=-dy; 
10225         }
10226       }
10227       if ( right_type(p)==mp_endpoint ) {
10228          return;
10229       } else {
10230         @<Advance |p| to the end of the path and make |q| the previous knot@>;
10231       } 
10232     }
10233   }
10234 }
10235
10236 @ @<Make |(dx,dy)| the final direction for the path segment from...@>=
10237 if ( q==link(p) ) { 
10238   dx=x_coord(p)-right_x(p);
10239   dy=y_coord(p)-right_y(p);
10240   if ( (dx==0)&&(dy==0) ) {
10241     dx=x_coord(p)-left_x(q);
10242     dy=y_coord(p)-left_y(q);
10243   }
10244 } else { 
10245   dx=x_coord(p)-left_x(p);
10246   dy=y_coord(p)-left_y(p);
10247   if ( (dx==0)&&(dy==0) ) {
10248     dx=x_coord(p)-right_x(q);
10249     dy=y_coord(p)-right_y(q);
10250   }
10251 }
10252 dx=x_coord(p)-x_coord(q);
10253 dy=y_coord(p)-y_coord(q)
10254
10255 @ @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>=
10256 dx=mp_make_fraction(mp, dx,d);
10257 dy=mp_make_fraction(mp, dy,d);
10258 mp_find_offset(mp, -dy,dx,pp);
10259 xx=mp->cur_x; yy=mp->cur_y
10260
10261 @ @<Use |(dx,dy)| to generate a vertex of the square end cap and...@>=
10262 mp_find_offset(mp, dx,dy,pp);
10263 d=mp_take_fraction(mp, xx-mp->cur_x,dx)+mp_take_fraction(mp, yy-mp->cur_y,dy);
10264 if ( ((d<0)&&(i==1)) || ((d>0)&&(i==2))) 
10265   mp_confusion(mp, "box_ends");
10266 @:this can't happen box ends}{\quad\\{box\_ends}@>
10267 z=x_coord(p)+mp->cur_x+mp_take_fraction(mp, d,dx);
10268 if ( z<minx_val(h) ) minx_val(h)=z;
10269 if ( z>maxx_val(h) ) maxx_val(h)=z;
10270 z=y_coord(p)+mp->cur_y+mp_take_fraction(mp, d,dy);
10271 if ( z<miny_val(h) ) miny_val(h)=z;
10272 if ( z>maxy_val(h) ) maxy_val(h)=z
10273
10274 @ @<Advance |p| to the end of the path and make |q| the previous knot@>=
10275 do {  
10276   q=p;
10277   p=link(p);
10278 } while (right_type(p)!=mp_endpoint)
10279
10280 @ The major difficulty in finding the bounding box of an edge structure is the
10281 effect of clipping paths.  We treat them conservatively by only clipping to the
10282 clipping path's bounding box, but this still
10283 requires recursive calls to |set_bbox| in order to find the bounding box of
10284 @^recursion@>
10285 the objects to be clipped.  Such calls are distinguished by the fact that the
10286 boolean parameter |top_level| is false.
10287
10288 @c void mp_set_bbox (MP mp,pointer h, boolean top_level) {
10289   pointer p;  /* a graphical object being considered */
10290   scaled sminx,sminy,smaxx,smaxy;
10291   /* for saving the bounding box during recursive calls */
10292   scaled x0,x1,y0,y1;  /* temporary registers */
10293   integer lev;  /* nesting level for |mp_start_bounds_code| nodes */
10294   @<Wipe out any existing bounding box information if |bbtype(h)| is
10295   incompatible with |internal[mp_true_corners]|@>;
10296   while ( link(bblast(h))!=null ) { 
10297     p=link(bblast(h));
10298     bblast(h)=p;
10299     switch (type(p)) {
10300     case mp_stop_clip_code: 
10301       if ( top_level ) mp_confusion(mp, "bbox");  else return;
10302 @:this can't happen bbox}{\quad bbox@>
10303       break;
10304     @<Other cases for updating the bounding box based on the type of object |p|@>;
10305     } /* all cases are enumerated above */
10306   }
10307   if ( ! top_level ) mp_confusion(mp, "bbox");
10308 }
10309
10310 @ @<Internal library declarations@>=
10311 void mp_set_bbox (MP mp,pointer h, boolean top_level);
10312
10313 @ @<Wipe out any existing bounding box information if |bbtype(h)| is...@>=
10314 switch (bbtype(h)) {
10315 case no_bounds: 
10316   break;
10317 case bounds_set: 
10318   if ( mp->internal[mp_true_corners]>0 ) mp_init_bbox(mp, h);
10319   break;
10320 case bounds_unset: 
10321   if ( mp->internal[mp_true_corners]<=0 ) mp_init_bbox(mp, h);
10322   break;
10323 } /* there are no other cases */
10324
10325 @ @<Other cases for updating the bounding box...@>=
10326 case mp_fill_code: 
10327   mp_path_bbox(mp, path_p(p));
10328   if ( pen_p(p)!=null ) { 
10329     x0=minx; y0=miny;
10330     x1=maxx; y1=maxy;
10331     mp_pen_bbox(mp, pen_p(p));
10332     minx=minx+x0;
10333     miny=miny+y0;
10334     maxx=maxx+x1;
10335     maxy=maxy+y1;
10336   }
10337   mp_adjust_bbox(mp, h);
10338   break;
10339
10340 @ @<Other cases for updating the bounding box...@>=
10341 case mp_start_bounds_code: 
10342   if ( mp->internal[mp_true_corners]>0 ) {
10343     bbtype(h)=bounds_unset;
10344   } else { 
10345     bbtype(h)=bounds_set;
10346     mp_path_bbox(mp, path_p(p));
10347     mp_adjust_bbox(mp, h);
10348     @<Scan to the matching |mp_stop_bounds_code| node and update |p| and
10349       |bblast(h)|@>;
10350   }
10351   break;
10352 case mp_stop_bounds_code: 
10353   if ( mp->internal[mp_true_corners]<=0 ) mp_confusion(mp, "bbox2");
10354 @:this can't happen bbox2}{\quad bbox2@>
10355   break;
10356
10357 @ @<Scan to the matching |mp_stop_bounds_code| node and update |p| and...@>=
10358 lev=1;
10359 while ( lev!=0 ) { 
10360   if ( link(p)==null ) mp_confusion(mp, "bbox2");
10361 @:this can't happen bbox2}{\quad bbox2@>
10362   p=link(p);
10363   if ( type(p)==mp_start_bounds_code ) incr(lev);
10364   else if ( type(p)==mp_stop_bounds_code ) decr(lev);
10365 }
10366 bblast(h)=p
10367
10368 @ It saves a lot of grief here to be slightly conservative and not account for
10369 omitted parts of dashed lines.  We also don't worry about the material omitted
10370 when using butt end caps.  The basic computation is for round end caps and
10371 |box_ends| augments it for square end caps.
10372
10373 @<Other cases for updating the bounding box...@>=
10374 case mp_stroked_code: 
10375   mp_path_bbox(mp, path_p(p));
10376   x0=minx; y0=miny;
10377   x1=maxx; y1=maxy;
10378   mp_pen_bbox(mp, pen_p(p));
10379   minx=minx+x0;
10380   miny=miny+y0;
10381   maxx=maxx+x1;
10382   maxy=maxy+y1;
10383   mp_adjust_bbox(mp, h);
10384   if ( (left_type(path_p(p))==mp_endpoint)&&(lcap_val(p)==2) )
10385     mp_box_ends(mp, path_p(p), pen_p(p), h);
10386   break;
10387
10388 @ The height width and depth information stored in a text node determines a
10389 rectangle that needs to be transformed according to the transformation
10390 parameters stored in the text node.
10391
10392 @<Other cases for updating the bounding box...@>=
10393 case mp_text_code: 
10394   x1=mp_take_scaled(mp, txx_val(p),width_val(p));
10395   y0=mp_take_scaled(mp, txy_val(p),-depth_val(p));
10396   y1=mp_take_scaled(mp, txy_val(p),height_val(p));
10397   minx=tx_val(p);
10398   maxx=minx;
10399   if ( y0<y1 ) { minx=minx+y0; maxx=maxx+y1;  }
10400   else         { minx=minx+y1; maxx=maxx+y0;  }
10401   if ( x1<0 ) minx=minx+x1;  else maxx=maxx+x1;
10402   x1=mp_take_scaled(mp, tyx_val(p),width_val(p));
10403   y0=mp_take_scaled(mp, tyy_val(p),-depth_val(p));
10404   y1=mp_take_scaled(mp, tyy_val(p),height_val(p));
10405   miny=ty_val(p);
10406   maxy=miny;
10407   if ( y0<y1 ) { miny=miny+y0; maxy=maxy+y1;  }
10408   else         { miny=miny+y1; maxy=maxy+y0;  }
10409   if ( x1<0 ) miny=miny+x1;  else maxy=maxy+x1;
10410   mp_adjust_bbox(mp, h);
10411   break;
10412
10413 @ This case involves a recursive call that advances |bblast(h)| to the node of
10414 type |mp_stop_clip_code| that matches |p|.
10415
10416 @<Other cases for updating the bounding box...@>=
10417 case mp_start_clip_code: 
10418   mp_path_bbox(mp, path_p(p));
10419   x0=minx; y0=miny;
10420   x1=maxx; y1=maxy;
10421   sminx=minx_val(h); sminy=miny_val(h);
10422   smaxx=maxx_val(h); smaxy=maxy_val(h);
10423   @<Reinitialize the bounding box in header |h| and call |set_bbox| recursively
10424     starting at |link(p)|@>;
10425   @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,
10426     |y0|, |y1|@>;
10427   minx=sminx; miny=sminy;
10428   maxx=smaxx; maxy=smaxy;
10429   mp_adjust_bbox(mp, h);
10430   break;
10431
10432 @ @<Reinitialize the bounding box in header |h| and call |set_bbox|...@>=
10433 minx_val(h)=el_gordo;
10434 miny_val(h)=el_gordo;
10435 maxx_val(h)=-el_gordo;
10436 maxy_val(h)=-el_gordo;
10437 mp_set_bbox(mp, h,false)
10438
10439 @ @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,...@>=
10440 if ( minx_val(h)<x0 ) minx_val(h)=x0;
10441 if ( miny_val(h)<y0 ) miny_val(h)=y0;
10442 if ( maxx_val(h)>x1 ) maxx_val(h)=x1;
10443 if ( maxy_val(h)>y1 ) maxy_val(h)=y1
10444
10445 @* \[22] Finding an envelope.
10446 When \MP\ has a path and a polygonal pen, it needs to express the desired
10447 shape in terms of things \ps\ can understand.  The present task is to compute
10448 a new path that describes the region to be filled.  It is convenient to
10449 define this as a two step process where the first step is determining what
10450 offset to use for each segment of the path.
10451
10452 @ Given a pointer |c| to a cyclic path,
10453 and a pointer~|h| to the first knot of a pen polygon,
10454 the |offset_prep| routine changes the path into cubics that are
10455 associated with particular pen offsets. Thus if the cubic between |p|
10456 and~|q| is associated with the |k|th offset and the cubic between |q| and~|r|
10457 has offset |l| then |info(q)=zero_off+l-k|. (The constant |zero_off| is added
10458 to because |l-k| could be negative.)
10459
10460 After overwriting the type information with offset differences, we no longer
10461 have a true path so we refer to the knot list returned by |offset_prep| as an
10462 ``envelope spec.''
10463 @^envelope spec@>
10464 Since an envelope spec only determines relative changes in pen offsets,
10465 |offset_prep| sets a global variable |spec_offset| to the relative change from
10466 |h| to the first offset.
10467
10468 @d zero_off 16384 /* added to offset changes to make them positive */
10469
10470 @<Glob...@>=
10471 integer spec_offset; /* number of pen edges between |h| and the initial offset */
10472
10473 @ @c @<Declare subroutines needed by |offset_prep|@>;
10474 pointer mp_offset_prep (MP mp,pointer c, pointer h) {
10475   halfword n; /* the number of vertices in the pen polygon */
10476   pointer p,q,q0,r,w, ww; /* for list manipulation */
10477   integer k_needed; /* amount to be added to |info(p)| when it is computed */
10478   pointer w0; /* a pointer to pen offset to use just before |p| */
10479   scaled dxin,dyin; /* the direction into knot |p| */
10480   integer turn_amt; /* change in pen offsets for the current cubic */
10481   @<Other local variables for |offset_prep|@>;
10482   dx0=0; dy0=0;
10483   @<Initialize the pen size~|n|@>;
10484   @<Initialize the incoming direction and pen offset at |c|@>;
10485   p=c; k_needed=0;
10486   do {  
10487     q=link(p);
10488     @<Split the cubic between |p| and |q|, if necessary, into cubics
10489       associated with single offsets, after which |q| should
10490       point to the end of the final such cubic@>;
10491   NOT_FOUND:
10492     @<Advance |p| to node |q|, removing any ``dead'' cubics that
10493       might have been introduced by the splitting process@>;
10494   } while (q!=c);
10495   @<Fix the offset change in |info(c)| and set |c| to the return value of
10496     |offset_prep|@>;
10497   return c;
10498 }
10499
10500 @ We shall want to keep track of where certain knots on the cyclic path
10501 wind up in the envelope spec.  It doesn't suffice just to keep pointers to
10502 knot nodes because some nodes are deleted while removing dead cubics.  Thus
10503 |offset_prep| updates the following pointers
10504
10505 @<Glob...@>=
10506 pointer spec_p1;
10507 pointer spec_p2; /* pointers to distinguished knots */
10508
10509 @ @<Set init...@>=
10510 mp->spec_p1=null; mp->spec_p2=null;
10511
10512 @ @<Initialize the pen size~|n|@>=
10513 n=0; p=h;
10514 do {  
10515   incr(n);
10516   p=link(p);
10517 } while (p!=h)
10518
10519 @ Since the true incoming direction isn't known yet, we just pick a direction
10520 consistent with the pen offset~|h|.  If this is wrong, it can be corrected
10521 later.
10522
10523 @<Initialize the incoming direction and pen offset at |c|@>=
10524 dxin=x_coord(link(h))-x_coord(knil(h));
10525 dyin=y_coord(link(h))-y_coord(knil(h));
10526 if ( (dxin==0)&&(dyin==0) ) {
10527   dxin=y_coord(knil(h))-y_coord(h);
10528   dyin=x_coord(h)-x_coord(knil(h));
10529 }
10530 w0=h
10531
10532 @ We must be careful not to remove the only cubic in a cycle.
10533
10534 But we must also be careful for another reason. If the user-supplied
10535 path starts with a set of degenerate cubics, the target node |q| can
10536 be collapsed to the initial node |p| which might be the same as the
10537 initial node |c| of the curve. This would cause the |offset_prep| routine
10538 to bail out too early, causing distress later on. (See for example
10539 the testcase reported by Bogus\l{}aw Jackowski in tracker id 267, case 52c
10540 on Sarovar.)
10541
10542 @<Advance |p| to node |q|, removing any ``dead'' cubics...@>=
10543 q0=q;
10544 do { 
10545   r=link(p);
10546   if ( x_coord(p)==right_x(p) && y_coord(p)==right_y(p) &&
10547        x_coord(p)==left_x(r)  && y_coord(p)==left_y(r) &&
10548        x_coord(p)==x_coord(r) && y_coord(p)==y_coord(r) &&
10549        r!=p ) {
10550       @<Remove the cubic following |p| and update the data structures
10551         to merge |r| into |p|@>;
10552   }
10553   p=r;
10554 } while (p!=q);
10555 /* Check if we removed too much */
10556 if(q!=q0)
10557   q = link(q)
10558
10559 @ @<Remove the cubic following |p| and update the data structures...@>=
10560 { k_needed=info(p)-zero_off;
10561   if ( r==q ) { 
10562     q=p;
10563   } else { 
10564     info(p)=k_needed+info(r);
10565     k_needed=0;
10566   };
10567   if ( r==c ) { info(p)=info(c); c=p; };
10568   if ( r==mp->spec_p1 ) mp->spec_p1=p;
10569   if ( r==mp->spec_p2 ) mp->spec_p2=p;
10570   r=p; mp_remove_cubic(mp, p);
10571 }
10572
10573 @ Not setting the |info| field of the newly created knot allows the splitting
10574 routine to work for paths.
10575
10576 @<Declare subroutines needed by |offset_prep|@>=
10577 void mp_split_cubic (MP mp,pointer p, fraction t) { /* splits the cubic after |p| */
10578   scaled v; /* an intermediate value */
10579   pointer q,r; /* for list manipulation */
10580   q=link(p); r=mp_get_node(mp, knot_node_size); link(p)=r; link(r)=q;
10581   originator(r)=mp_program_code;
10582   left_type(r)=mp_explicit; right_type(r)=mp_explicit;
10583   v=t_of_the_way(right_x(p),left_x(q));
10584   right_x(p)=t_of_the_way(x_coord(p),right_x(p));
10585   left_x(q)=t_of_the_way(left_x(q),x_coord(q));
10586   left_x(r)=t_of_the_way(right_x(p),v);
10587   right_x(r)=t_of_the_way(v,left_x(q));
10588   x_coord(r)=t_of_the_way(left_x(r),right_x(r));
10589   v=t_of_the_way(right_y(p),left_y(q));
10590   right_y(p)=t_of_the_way(y_coord(p),right_y(p));
10591   left_y(q)=t_of_the_way(left_y(q),y_coord(q));
10592   left_y(r)=t_of_the_way(right_y(p),v);
10593   right_y(r)=t_of_the_way(v,left_y(q));
10594   y_coord(r)=t_of_the_way(left_y(r),right_y(r));
10595 }
10596
10597 @ This does not set |info(p)| or |right_type(p)|.
10598
10599 @<Declare subroutines needed by |offset_prep|@>=
10600 void mp_remove_cubic (MP mp,pointer p) { /* removes the dead cubic following~|p| */
10601   pointer q; /* the node that disappears */
10602   q=link(p); link(p)=link(q);
10603   right_x(p)=right_x(q); right_y(p)=right_y(q);
10604   mp_free_node(mp, q,knot_node_size);
10605 }
10606
10607 @ Let $d\prec d'$ mean that the counter-clockwise angle from $d$ to~$d'$ is
10608 strictly between zero and $180^\circ$.  Then we can define $d\preceq d'$ to
10609 mean that the angle could be zero or $180^\circ$. If $w_k=(u_k,v_k)$ is the
10610 $k$th pen offset, the $k$th pen edge direction is defined by the formula
10611 $$d_k=(u\k-u_k,\,v\k-v_k).$$
10612 When listed by increasing $k$, these directions occur in counter-clockwise
10613 order so that $d_k\preceq d\k$ for all~$k$.
10614 The goal of |offset_prep| is to find an offset index~|k| to associate with
10615 each cubic, such that the direction $d(t)$ of the cubic satisfies
10616 $$d_{k-1}\preceq d(t)\preceq d_k\qquad\hbox{for $0\le t\le 1$.}\eqno(*)$$
10617 We may have to split a cubic into many pieces before each
10618 piece corresponds to a unique offset.
10619
10620 @<Split the cubic between |p| and |q|, if necessary, into cubics...@>=
10621 info(p)=zero_off+k_needed;
10622 k_needed=0;
10623 @<Prepare for derivative computations;
10624   |goto not_found| if the current cubic is dead@>;
10625 @<Find the initial direction |(dx,dy)|@>;
10626 @<Update |info(p)| and find the offset $w_k$ such that
10627   $d_{k-1}\preceq(\\{dx},\\{dy})\prec d_k$; also advance |w0| for
10628   the direction change at |p|@>;
10629 @<Find the final direction |(dxin,dyin)|@>;
10630 @<Decide on the net change in pen offsets and set |turn_amt|@>;
10631 @<Complete the offset splitting process@>;
10632 w0=mp_pen_walk(mp, w0,turn_amt)
10633
10634 @ @<Declare subroutines needed by |offset_prep|@>=
10635 pointer mp_pen_walk (MP mp,pointer w, integer k) {
10636   /* walk |k| steps around a pen from |w| */
10637   while ( k>0 ) { w=link(w); decr(k);  };
10638   while ( k<0 ) { w=knil(w); incr(k);  };
10639   return w;
10640 }
10641
10642 @ The direction of a cubic $B(z_0,z_1,z_2,z_3;t)=\bigl(x(t),y(t)\bigr)$ can be
10643 calculated from the quadratic polynomials
10644 ${1\over3}x'(t)=B(x_1-x_0,x_2-x_1,x_3-x_2;t)$ and
10645 ${1\over3}y'(t)=B(y_1-y_0,y_2-y_1,y_3-y_2;t)$.
10646 Since we may be calculating directions from several cubics
10647 split from the current one, it is desirable to do these calculations
10648 without losing too much precision. ``Scaled up'' values of the
10649 derivatives, which will be less tainted by accumulated errors than
10650 derivatives found from the cubics themselves, are maintained in
10651 local variables |x0|, |x1|, and |x2|, representing $X_0=2^l(x_1-x_0)$,
10652 $X_1=2^l(x_2-x_1)$, and $X_2=2^l(x_3-x_2)$; similarly |y0|, |y1|, and~|y2|
10653 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)$.
10654
10655 @<Other local variables for |offset_prep|@>=
10656 integer x0,x1,x2,y0,y1,y2; /* representatives of derivatives */
10657 integer t0,t1,t2; /* coefficients of polynomial for slope testing */
10658 integer du,dv,dx,dy; /* for directions of the pen and the curve */
10659 integer dx0,dy0; /* initial direction for the first cubic in the curve */
10660 integer max_coef; /* used while scaling */
10661 integer x0a,x1a,x2a,y0a,y1a,y2a; /* intermediate values */
10662 fraction t; /* where the derivative passes through zero */
10663 fraction s; /* a temporary value */
10664
10665 @ @<Prepare for derivative computations...@>=
10666 x0=right_x(p)-x_coord(p);
10667 x2=x_coord(q)-left_x(q);
10668 x1=left_x(q)-right_x(p);
10669 y0=right_y(p)-y_coord(p); y2=y_coord(q)-left_y(q);
10670 y1=left_y(q)-right_y(p);
10671 max_coef=abs(x0);
10672 if ( abs(x1)>max_coef ) max_coef=abs(x1);
10673 if ( abs(x2)>max_coef ) max_coef=abs(x2);
10674 if ( abs(y0)>max_coef ) max_coef=abs(y0);
10675 if ( abs(y1)>max_coef ) max_coef=abs(y1);
10676 if ( abs(y2)>max_coef ) max_coef=abs(y2);
10677 if ( max_coef==0 ) goto NOT_FOUND;
10678 while ( max_coef<fraction_half ) {
10679   double(max_coef);
10680   double(x0); double(x1); double(x2);
10681   double(y0); double(y1); double(y2);
10682 }
10683
10684 @ Let us first solve a special case of the problem: Suppose we
10685 know an index~$k$ such that either (i)~$d(t)\succeq d_{k-1}$ for all~$t$
10686 and $d(0)\prec d_k$, or (ii)~$d(t)\preceq d_k$ for all~$t$ and
10687 $d(0)\succ d_{k-1}$.
10688 Then, in a sense, we're halfway done, since one of the two relations
10689 in $(*)$ is satisfied, and the other couldn't be satisfied for
10690 any other value of~|k|.
10691
10692 Actually, the conditions can be relaxed somewhat since a relation such as
10693 $d(t)\succeq d_{k-1}$ restricts $d(t)$ to a half plane when all that really
10694 matters is whether $d(t)$ crosses the ray in the $d_{k-1}$ direction from
10695 the origin.  The condition for case~(i) becomes $d_{k-1}\preceq d(0)\prec d_k$
10696 and $d(t)$ never crosses the $d_{k-1}$ ray in the clockwise direction.
10697 Case~(ii) is similar except $d(t)$ cannot cross the $d_k$ ray in the
10698 counterclockwise direction.
10699
10700 The |fin_offset_prep| subroutine solves the stated subproblem.
10701 It has a parameter called |rise| that is |1| in
10702 case~(i), |-1| in case~(ii). Parameters |x0| through |y2| represent
10703 the derivative of the cubic following |p|.
10704 The |w| parameter should point to offset~$w_k$ and |info(p)| should already
10705 be set properly.  The |turn_amt| parameter gives the absolute value of the
10706 overall net change in pen offsets.
10707
10708 @<Declare subroutines needed by |offset_prep|@>=
10709 void mp_fin_offset_prep (MP mp,pointer p, pointer w, integer 
10710   x0,integer x1, integer x2, integer y0, integer y1, integer y2, 
10711   integer rise, integer turn_amt)  {
10712   pointer ww; /* for list manipulation */
10713   scaled du,dv; /* for slope calculation */
10714   integer t0,t1,t2; /* test coefficients */
10715   fraction t; /* place where the derivative passes a critical slope */
10716   fraction s; /* slope or reciprocal slope */
10717   integer v; /* intermediate value for updating |x0..y2| */
10718   pointer q; /* original |link(p)| */
10719   q=link(p);
10720   while (1)  { 
10721     if ( rise>0 ) ww=link(w); /* a pointer to $w\k$ */
10722     else  ww=knil(w); /* a pointer to $w_{k-1}$ */
10723     @<Compute test coefficients |(t0,t1,t2)|
10724       for $d(t)$ versus $d_k$ or $d_{k-1}$@>;
10725     t=mp_crossing_point(mp, t0,t1,t2);
10726     if ( t>=fraction_one ) {
10727       if ( turn_amt>0 ) t=fraction_one;  else return;
10728     }
10729     @<Split the cubic at $t$,
10730       and split off another cubic if the derivative crosses back@>;
10731     w=ww;
10732   }
10733 }
10734
10735 @ We want $B(\\{t0},\\{t1},\\{t2};t)$ to be the dot product of $d(t)$ with a
10736 $-90^\circ$ rotation of the vector from |w| to |ww|.  This makes the resulting
10737 function cross from positive to negative when $d_{k-1}\preceq d(t)\preceq d_k$
10738 begins to fail.
10739
10740 @<Compute test coefficients |(t0,t1,t2)| for $d(t)$ versus...@>=
10741 du=x_coord(ww)-x_coord(w); dv=y_coord(ww)-y_coord(w);
10742 if ( abs(du)>=abs(dv) ) {
10743   s=mp_make_fraction(mp, dv,du);
10744   t0=mp_take_fraction(mp, x0,s)-y0;
10745   t1=mp_take_fraction(mp, x1,s)-y1;
10746   t2=mp_take_fraction(mp, x2,s)-y2;
10747   if ( du<0 ) { negate(t0); negate(t1); negate(t2);  }
10748 } else { 
10749   s=mp_make_fraction(mp, du,dv);
10750   t0=x0-mp_take_fraction(mp, y0,s);
10751   t1=x1-mp_take_fraction(mp, y1,s);
10752   t2=x2-mp_take_fraction(mp, y2,s);
10753   if ( dv<0 ) { negate(t0); negate(t1); negate(t2);  }
10754 }
10755 if ( t0<0 ) t0=0 /* should be positive without rounding error */
10756
10757 @ The curve has crossed $d_k$ or $d_{k-1}$; its initial segment satisfies
10758 $(*)$, and it might cross again, yielding another solution of $(*)$.
10759
10760 @<Split the cubic at $t$, and split off another...@>=
10761
10762 mp_split_cubic(mp, p,t); p=link(p); info(p)=zero_off+rise;
10763 decr(turn_amt);
10764 v=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10765 x0=t_of_the_way(v,x1);
10766 v=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10767 y0=t_of_the_way(v,y1);
10768 if ( turn_amt<0 ) {
10769   t1=t_of_the_way(t1,t2);
10770   if ( t1>0 ) t1=0; /* without rounding error, |t1| would be |<=0| */
10771   t=mp_crossing_point(mp, 0,-t1,-t2);
10772   if ( t>fraction_one ) t=fraction_one;
10773   incr(turn_amt);
10774   if ( (t==fraction_one)&&(link(p)!=q) ) {
10775     info(link(p))=info(link(p))-rise;
10776   } else { 
10777     mp_split_cubic(mp, p,t); info(link(p))=zero_off-rise;
10778     v=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10779     x2=t_of_the_way(x1,v);
10780     v=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10781     y2=t_of_the_way(y1,v);
10782   }
10783 }
10784 }
10785
10786 @ Now we must consider the general problem of |offset_prep|, when
10787 nothing is known about a given cubic. We start by finding its
10788 direction in the vicinity of |t=0|.
10789
10790 If $z'(t)=0$, the given cubic is numerically unstable but |offset_prep|
10791 has not yet introduced any more numerical errors.  Thus we can compute
10792 the true initial direction for the given cubic, even if it is almost
10793 degenerate.
10794
10795 @<Find the initial direction |(dx,dy)|@>=
10796 dx=x0; dy=y0;
10797 if ( dx==0 && dy==0 ) { 
10798   dx=x1; dy=y1;
10799   if ( dx==0 && dy==0 ) { 
10800     dx=x2; dy=y2;
10801   }
10802 }
10803 if ( p==c ) { dx0=dx; dy0=dy;  }
10804
10805 @ @<Find the final direction |(dxin,dyin)|@>=
10806 dxin=x2; dyin=y2;
10807 if ( dxin==0 && dyin==0 ) {
10808   dxin=x1; dyin=y1;
10809   if ( dxin==0 && dyin==0 ) {
10810     dxin=x0; dyin=y0;
10811   }
10812 }
10813
10814 @ The next step is to bracket the initial direction between consecutive
10815 edges of the pen polygon.  We must be careful to turn clockwise only if
10816 this makes the turn less than $180^\circ$. (A $180^\circ$ turn must be
10817 counter-clockwise in order to make \&{doublepath} envelopes come out
10818 @:double_path_}{\&{doublepath} primitive@>
10819 right.) This code depends on |w0| being the offset for |(dxin,dyin)|.
10820
10821 @<Update |info(p)| and find the offset $w_k$ such that...@>=
10822 turn_amt=mp_get_turn_amt(mp,w0,dx,dy,(mp_ab_vs_cd(mp, dy,dxin,dx,dyin)>=0));
10823 w=mp_pen_walk(mp, w0, turn_amt);
10824 w0=w;
10825 info(p)=info(p)+turn_amt
10826
10827 @ Decide how many pen offsets to go away from |w| in order to find the offset
10828 for |(dx,dy)|, going counterclockwise if |ccw| is |true|.  This assumes that
10829 |w| is the offset for some direction $(x',y')$ from which the angle to |(dx,dy)|
10830 in the sense determined by |ccw| is less than or equal to $180^\circ$.
10831
10832 If the pen polygon has only two edges, they could both be parallel
10833 to |(dx,dy)|.  In this case, we must be careful to stop after crossing the first
10834 such edge in order to avoid an infinite loop.
10835
10836 @<Declare subroutines needed by |offset_prep|@>=
10837 integer mp_get_turn_amt (MP mp,pointer w, scaled  dx,
10838                          scaled dy, boolean  ccw) {
10839   pointer ww; /* a neighbor of knot~|w| */
10840   integer s; /* turn amount so far */
10841   integer t; /* |ab_vs_cd| result */
10842   s=0;
10843   if ( ccw ) { 
10844     ww=link(w);
10845     do {  
10846       t=mp_ab_vs_cd(mp, dy,(x_coord(ww)-x_coord(w)),
10847                         dx,(y_coord(ww)-y_coord(w)));
10848       if ( t<0 ) break;
10849       incr(s);
10850       w=ww; ww=link(ww);
10851     } while (t>0);
10852   } else { 
10853     ww=knil(w);
10854     while ( mp_ab_vs_cd(mp, dy,(x_coord(w)-x_coord(ww)),
10855                             dx,(y_coord(w)-y_coord(ww))) < 0) { 
10856       decr(s);
10857       w=ww; ww=knil(ww);
10858     }
10859   }
10860   return s;
10861 }
10862
10863 @ When we're all done, the final offset is |w0| and the final curve direction
10864 is |(dxin,dyin)|.  With this knowledge of the incoming direction at |c|, we
10865 can correct |info(c)| which was erroneously based on an incoming offset
10866 of~|h|.
10867
10868 @d fix_by(A) info(c)=info(c)+(A)
10869
10870 @<Fix the offset change in |info(c)| and set |c| to the return value of...@>=
10871 mp->spec_offset=info(c)-zero_off;
10872 if ( link(c)==c ) {
10873   info(c)=zero_off+n;
10874 } else { 
10875   fix_by(k_needed);
10876   while ( w0!=h ) { fix_by(1); w0=link(w0);  };
10877   while ( info(c)<=zero_off-n ) fix_by(n);
10878   while ( info(c)>zero_off ) fix_by(-n);
10879   if ( (info(c)!=zero_off)&&(mp_ab_vs_cd(mp, dy0,dxin,dx0,dyin)>=0) ) fix_by(n);
10880 }
10881 return c
10882
10883 @ Finally we want to reduce the general problem to situations that
10884 |fin_offset_prep| can handle. We split the cubic into at most three parts
10885 with respect to $d_{k-1}$, and apply |fin_offset_prep| to each part.
10886
10887 @<Complete the offset splitting process@>=
10888 ww=knil(w);
10889 @<Compute test coeff...@>;
10890 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set
10891   |t:=fraction_one+1|@>;
10892 if ( t>fraction_one ) {
10893   mp_fin_offset_prep(mp, p,w,x0,x1,x2,y0,y1,y2,1,turn_amt);
10894 } else {
10895   mp_split_cubic(mp, p,t); r=link(p);
10896   x1a=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10897   x2a=t_of_the_way(x1a,x1);
10898   y1a=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10899   y2a=t_of_the_way(y1a,y1);
10900   mp_fin_offset_prep(mp, p,w,x0,x1a,x2a,y0,y1a,y2a,1,0); x0=x2a; y0=y2a;
10901   info(r)=zero_off-1;
10902   if ( turn_amt>=0 ) {
10903     t1=t_of_the_way(t1,t2);
10904     if ( t1>0 ) t1=0;
10905     t=mp_crossing_point(mp, 0,-t1,-t2);
10906     if ( t>fraction_one ) t=fraction_one;
10907     @<Split off another rising cubic for |fin_offset_prep|@>;
10908     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,0);
10909   } else {
10910     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,(-1-turn_amt));
10911   }
10912 }
10913
10914 @ @<Split off another rising cubic for |fin_offset_prep|@>=
10915 mp_split_cubic(mp, r,t); info(link(r))=zero_off+1;
10916 x1a=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10917 x0a=t_of_the_way(x1,x1a);
10918 y1a=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10919 y0a=t_of_the_way(y1,y1a);
10920 mp_fin_offset_prep(mp, link(r),w,x0a,x1a,x2,y0a,y1a,y2,1,turn_amt);
10921 x2=x0a; y2=y0a
10922
10923 @ At this point, the direction of the incoming pen edge is |(-du,-dv)|.
10924 When the component of $d(t)$ perpendicular to |(-du,-dv)| crosses zero, we
10925 need to decide whether the directions are parallel or antiparallel.  We
10926 can test this by finding the dot product of $d(t)$ and |(-du,-dv)|, but this
10927 should be avoided when the value of |turn_amt| already determines the
10928 answer.  If |t2<0|, there is one crossing and it is antiparallel only if
10929 |turn_amt>=0|.  If |turn_amt<0|, there should always be at least one
10930 crossing and the first crossing cannot be antiparallel.
10931
10932 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set...@>=
10933 t=mp_crossing_point(mp, t0,t1,t2);
10934 if ( turn_amt>=0 ) {
10935   if ( t2<0 ) {
10936     t=fraction_one+1;
10937   } else { 
10938     u0=t_of_the_way(x0,x1);
10939     u1=t_of_the_way(x1,x2);
10940     ss=mp_take_fraction(mp, -du,t_of_the_way(u0,u1));
10941     v0=t_of_the_way(y0,y1);
10942     v1=t_of_the_way(y1,y2);
10943     ss=ss+mp_take_fraction(mp, -dv,t_of_the_way(v0,v1));
10944     if ( ss<0 ) t=fraction_one+1;
10945   }
10946 } else if ( t>fraction_one ) {
10947   t=fraction_one;
10948 }
10949
10950 @ @<Other local variables for |offset_prep|@>=
10951 integer u0,u1,v0,v1; /* intermediate values for $d(t)$ calculation */
10952 integer ss = 0; /* the part of the dot product computed so far */
10953 int d_sign; /* sign of overall change in direction for this cubic */
10954
10955 @ If the cubic almost has a cusp, it is a numerically ill-conditioned
10956 problem to decide which way it loops around but that's OK as long we're
10957 consistent.  To make \&{doublepath} envelopes work properly, reversing
10958 the path should always change the sign of |turn_amt|.
10959
10960 @<Decide on the net change in pen offsets and set |turn_amt|@>=
10961 d_sign=mp_ab_vs_cd(mp, dx,dyin, dxin,dy);
10962 if ( d_sign==0 ) {
10963   @<Check rotation direction based on node position@>
10964 }
10965 if ( d_sign==0 ) {
10966   if ( dx==0 ) {
10967     if ( dy>0 ) d_sign=1;  else d_sign=-1;
10968   } else {
10969     if ( dx>0 ) d_sign=1;  else d_sign=-1; 
10970   }
10971 }
10972 @<Make |ss| negative if and only if the total change in direction is
10973   more than $180^\circ$@>;
10974 turn_amt=mp_get_turn_amt(mp, w, dxin, dyin, (d_sign>0));
10975 if ( ss<0 ) turn_amt=turn_amt-d_sign*n
10976
10977 @ We check rotation direction by looking at the vector connecting the current
10978 node with the next. If its angle with incoming and outgoing tangents has the
10979 same sign, we pick this as |d_sign|, since it means we have a flex, not a cusp.
10980 Otherwise we proceed to the cusp code.
10981
10982 @<Check rotation direction based on node position@>=
10983 u0=x_coord(q)-x_coord(p);
10984 u1=y_coord(q)-y_coord(p);
10985 d_sign = half(mp_ab_vs_cd(mp, dx, u1, u0, dy)+
10986   mp_ab_vs_cd(mp, u0, dyin, dxin, u1));
10987
10988 @ In order to be invariant under path reversal, the result of this computation
10989 should not change when |x0|, |y0|, $\ldots$ are all negated and |(x0,y0)| is
10990 then swapped with |(x2,y2)|.  We make use of the identities
10991 |take_fraction(-a,-b)=take_fraction(a,b)| and
10992 |t_of_the_way(-a,-b)=-(t_of_the_way(a,b))|.
10993
10994 @<Make |ss| negative if and only if the total change in direction is...@>=
10995 t0=half(mp_take_fraction(mp, x0,y2))-half(mp_take_fraction(mp, x2,y0));
10996 t1=half(mp_take_fraction(mp, x1,(y0+y2)))-half(mp_take_fraction(mp, y1,(x0+x2)));
10997 if ( t0==0 ) t0=d_sign; /* path reversal always negates |d_sign| */
10998 if ( t0>0 ) {
10999   t=mp_crossing_point(mp, t0,t1,-t0);
11000   u0=t_of_the_way(x0,x1);
11001   u1=t_of_the_way(x1,x2);
11002   v0=t_of_the_way(y0,y1);
11003   v1=t_of_the_way(y1,y2);
11004 } else { 
11005   t=mp_crossing_point(mp, -t0,t1,t0);
11006   u0=t_of_the_way(x2,x1);
11007   u1=t_of_the_way(x1,x0);
11008   v0=t_of_the_way(y2,y1);
11009   v1=t_of_the_way(y1,y0);
11010 }
11011 ss=mp_take_fraction(mp, (x0+x2),t_of_the_way(u0,u1))+
11012    mp_take_fraction(mp, (y0+y2),t_of_the_way(v0,v1))
11013
11014 @ Here's a routine that prints an envelope spec in symbolic form.  It assumes
11015 that the |cur_pen| has not been walked around to the first offset.
11016
11017 @c 
11018 void mp_print_spec (MP mp,pointer cur_spec, pointer cur_pen, char *s) {
11019   pointer p,q; /* list traversal */
11020   pointer w; /* the current pen offset */
11021   mp_print_diagnostic(mp, "Envelope spec",s,true);
11022   p=cur_spec; w=mp_pen_walk(mp, cur_pen,mp->spec_offset);
11023   mp_print_ln(mp);
11024   mp_print_two(mp, x_coord(cur_spec),y_coord(cur_spec));
11025   mp_print(mp, " % beginning with offset ");
11026   mp_print_two(mp, x_coord(w),y_coord(w));
11027   do { 
11028     while (1) {  
11029       q=link(p);
11030       @<Print the cubic between |p| and |q|@>;
11031       p=q;
11032           if ((p==cur_spec) || (info(p)!=zero_off)) 
11033         break;
11034     }
11035     if ( info(p)!=zero_off ) {
11036       @<Update |w| as indicated by |info(p)| and print an explanation@>;
11037     }
11038   } while (p!=cur_spec);
11039   mp_print_nl(mp, " & cycle");
11040   mp_end_diagnostic(mp, true);
11041 }
11042
11043 @ @<Update |w| as indicated by |info(p)| and print an explanation@>=
11044
11045   w=mp_pen_walk(mp, w, (info(p)-zero_off));
11046   mp_print(mp, " % ");
11047   if ( info(p)>zero_off ) mp_print(mp, "counter");
11048   mp_print(mp, "clockwise to offset ");
11049   mp_print_two(mp, x_coord(w),y_coord(w));
11050 }
11051
11052 @ @<Print the cubic between |p| and |q|@>=
11053
11054   mp_print_nl(mp, "   ..controls ");
11055   mp_print_two(mp, right_x(p),right_y(p));
11056   mp_print(mp, " and ");
11057   mp_print_two(mp, left_x(q),left_y(q));
11058   mp_print_nl(mp, " ..");
11059   mp_print_two(mp, x_coord(q),y_coord(q));
11060 }
11061
11062 @ Once we have an envelope spec, the remaining task to construct the actual
11063 envelope by offsetting each cubic as determined by the |info| fields in
11064 the knots.  First we use |offset_prep| to convert the |c| into an envelope
11065 spec. Then we add the offsets so that |c| becomes a cyclic path that represents
11066 the envelope.
11067
11068 The |ljoin| and |miterlim| parameters control the treatment of points where the
11069 pen offset changes, and |lcap| controls the endpoints of a \&{doublepath}.
11070 The endpoints are easily located because |c| is given in undoubled form
11071 and then doubled in this procedure.  We use |spec_p1| and |spec_p2| to keep
11072 track of the endpoints and treat them like very sharp corners.
11073 Butt end caps are treated like beveled joins; round end caps are treated like
11074 round joins; and square end caps are achieved by setting |join_type:=3|.
11075
11076 None of these parameters apply to inside joins where the convolution tracing
11077 has retrograde lines.  In such cases we use a simple connect-the-endpoints
11078 approach that is achieved by setting |join_type:=2|.
11079
11080 @c @<Declare a function called |insert_knot|@>;
11081 pointer mp_make_envelope (MP mp,pointer c, pointer h, small_number ljoin,
11082   small_number lcap, scaled miterlim) {
11083   pointer p,q,r,q0; /* for manipulating the path */
11084   int join_type=0; /* codes |0..3| for mitered, round, beveled, or square */
11085   pointer w,w0; /* the pen knot for the current offset */
11086   scaled qx,qy; /* unshifted coordinates of |q| */
11087   halfword k,k0; /* controls pen edge insertion */
11088   @<Other local variables for |make_envelope|@>;
11089   dxin=0; dyin=0; dxout=0; dyout=0;
11090   mp->spec_p1=null; mp->spec_p2=null;
11091   @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>;
11092   @<Use |offset_prep| to compute the envelope spec then walk |h| around to
11093     the initial offset@>;
11094   w=h;
11095   p=c;
11096   do {  
11097     q=link(p); q0=q;
11098     qx=x_coord(q); qy=y_coord(q);
11099     k=info(q);
11100     k0=k; w0=w;
11101     if ( k!=zero_off ) {
11102       @<Set |join_type| to indicate how to handle offset changes at~|q|@>;
11103     }
11104     @<Add offset |w| to the cubic from |p| to |q|@>;
11105     while ( k!=zero_off ) { 
11106       @<Step |w| and move |k| one step closer to |zero_off|@>;
11107       if ( (join_type==1)||(k==zero_off) )
11108          q=mp_insert_knot(mp, q,qx+x_coord(w),qy+y_coord(w));
11109     };
11110     if ( q!=link(p) ) {
11111       @<Set |p=link(p)| and add knots between |p| and |q| as
11112         required by |join_type|@>;
11113     }
11114     p=q;
11115   } while (q0!=c);
11116   return c;
11117 }
11118
11119 @ @<Use |offset_prep| to compute the envelope spec then walk |h| around to...@>=
11120 c=mp_offset_prep(mp, c,h);
11121 if ( mp->internal[mp_tracing_specs]>0 ) 
11122   mp_print_spec(mp, c,h,"");
11123 h=mp_pen_walk(mp, h,mp->spec_offset)
11124
11125 @ Mitered and squared-off joins depend on path directions that are difficult to
11126 compute for degenerate cubics.  The envelope spec computed by |offset_prep| can
11127 have degenerate cubics only if the entire cycle collapses to a single
11128 degenerate cubic.  Setting |join_type:=2| in this case makes the computed
11129 envelope degenerate as well.
11130
11131 @<Set |join_type| to indicate how to handle offset changes at~|q|@>=
11132 if ( k<zero_off ) {
11133   join_type=2;
11134 } else {
11135   if ( (q!=mp->spec_p1)&&(q!=mp->spec_p2) ) join_type=ljoin;
11136   else if ( lcap==2 ) join_type=3;
11137   else join_type=2-lcap;
11138   if ( (join_type==0)||(join_type==3) ) {
11139     @<Set the incoming and outgoing directions at |q|; in case of
11140       degeneracy set |join_type:=2|@>;
11141     if ( join_type==0 ) {
11142       @<If |miterlim| is less than the secant of half the angle at |q|
11143         then set |join_type:=2|@>;
11144     }
11145   }
11146 }
11147
11148 @ @<If |miterlim| is less than the secant of half the angle at |q|...@>=
11149
11150   tmp=mp_take_fraction(mp, miterlim,fraction_half+
11151       half(mp_take_fraction(mp, dxin,dxout)+mp_take_fraction(mp, dyin,dyout)));
11152   if ( tmp<unity )
11153     if ( mp_take_scaled(mp, miterlim,tmp)<unity ) join_type=2;
11154 }
11155
11156 @ @<Other local variables for |make_envelope|@>=
11157 fraction dxin,dyin,dxout,dyout; /* directions at |q| when square or mitered */
11158 scaled tmp; /* a temporary value */
11159
11160 @ The coordinates of |p| have already been shifted unless |p| is the first
11161 knot in which case they get shifted at the very end.
11162
11163 @<Add offset |w| to the cubic from |p| to |q|@>=
11164 right_x(p)=right_x(p)+x_coord(w);
11165 right_y(p)=right_y(p)+y_coord(w);
11166 left_x(q)=left_x(q)+x_coord(w);
11167 left_y(q)=left_y(q)+y_coord(w);
11168 x_coord(q)=x_coord(q)+x_coord(w);
11169 y_coord(q)=y_coord(q)+y_coord(w);
11170 left_type(q)=mp_explicit;
11171 right_type(q)=mp_explicit
11172
11173 @ @<Step |w| and move |k| one step closer to |zero_off|@>=
11174 if ( k>zero_off ){ w=link(w); decr(k);  }
11175 else { w=knil(w); incr(k);  }
11176
11177 @ The cubic from |q| to the new knot at |(x,y)| becomes a line segment and
11178 the |right_x| and |right_y| fields of |r| are set from |q|.  This is done in
11179 case the cubic containing these control points is ``yet to be examined.''
11180
11181 @<Declare a function called |insert_knot|@>=
11182 pointer mp_insert_knot (MP mp,pointer q, scaled x, scaled y) {
11183   /* returns the inserted knot */
11184   pointer r; /* the new knot */
11185   r=mp_get_node(mp, knot_node_size);
11186   link(r)=link(q); link(q)=r;
11187   right_x(r)=right_x(q);
11188   right_y(r)=right_y(q);
11189   x_coord(r)=x;
11190   y_coord(r)=y;
11191   right_x(q)=x_coord(q);
11192   right_y(q)=y_coord(q);
11193   left_x(r)=x_coord(r);
11194   left_y(r)=y_coord(r);
11195   left_type(r)=mp_explicit;
11196   right_type(r)=mp_explicit;
11197   originator(r)=mp_program_code;
11198   return r;
11199 }
11200
11201 @ After setting |p:=link(p)|, either |join_type=1| or |q=link(p)|.
11202
11203 @<Set |p=link(p)| and add knots between |p| and |q| as...@>=
11204
11205   p=link(p);
11206   if ( (join_type==0)||(join_type==3) ) {
11207     if ( join_type==0 ) {
11208       @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>
11209     } else {
11210       @<Make |r| the last of two knots inserted between |p| and |q| to form a
11211         squared join@>;
11212     }
11213     if ( r!=null ) { 
11214       right_x(r)=x_coord(r);
11215       right_y(r)=y_coord(r);
11216     }
11217   }
11218 }
11219
11220 @ For very small angles, adding a knot is unnecessary and would cause numerical
11221 problems, so we just set |r:=null| in that case.
11222
11223 @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>=
11224
11225   det=mp_take_fraction(mp, dyout,dxin)-mp_take_fraction(mp, dxout,dyin);
11226   if ( abs(det)<26844 ) { 
11227      r=null; /* sine $<10^{-4}$ */
11228   } else { 
11229     tmp=mp_take_fraction(mp, x_coord(q)-x_coord(p),dyout)-
11230         mp_take_fraction(mp, y_coord(q)-y_coord(p),dxout);
11231     tmp=mp_make_fraction(mp, tmp,det);
11232     r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11233       y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11234   }
11235 }
11236
11237 @ @<Other local variables for |make_envelope|@>=
11238 fraction det; /* a determinant used for mitered join calculations */
11239
11240 @ @<Make |r| the last of two knots inserted between |p| and |q| to form a...@>=
11241
11242   ht_x=y_coord(w)-y_coord(w0);
11243   ht_y=x_coord(w0)-x_coord(w);
11244   while ( (abs(ht_x)<fraction_half)&&(abs(ht_y)<fraction_half) ) { 
11245     ht_x+=ht_x; ht_y+=ht_y;
11246   }
11247   @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range dot
11248     product with |(ht_x,ht_y)|@>;
11249   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxin,ht_x)+
11250                                   mp_take_fraction(mp, dyin,ht_y));
11251   r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11252                          y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11253   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxout,ht_x)+
11254                                   mp_take_fraction(mp, dyout,ht_y));
11255   r=mp_insert_knot(mp, r,x_coord(q)+mp_take_fraction(mp, tmp,dxout),
11256                          y_coord(q)+mp_take_fraction(mp, tmp,dyout));
11257 }
11258
11259 @ @<Other local variables for |make_envelope|@>=
11260 fraction ht_x,ht_y; /* perpendicular to the segment from |p| to |q| */
11261 scaled max_ht; /* maximum height of the pen polygon above the |w0|-|w| line */
11262 halfword kk; /* keeps track of the pen vertices being scanned */
11263 pointer ww; /* the pen vertex being tested */
11264
11265 @ The dot product of the vector from |w0| to |ww| with |(ht_x,ht_y)| ranges
11266 from zero to |max_ht|.
11267
11268 @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range...@>=
11269 max_ht=0;
11270 kk=zero_off;
11271 ww=w;
11272 while (1)  { 
11273   @<Step |ww| and move |kk| one step closer to |k0|@>;
11274   if ( kk==k0 ) break;
11275   tmp=mp_take_fraction(mp, (x_coord(ww)-x_coord(w0)),ht_x)+
11276       mp_take_fraction(mp, (y_coord(ww)-y_coord(w0)),ht_y);
11277   if ( tmp>max_ht ) max_ht=tmp;
11278 }
11279
11280
11281 @ @<Step |ww| and move |kk| one step closer to |k0|@>=
11282 if ( kk>k0 ) { ww=link(ww); decr(kk);  }
11283 else { ww=knil(ww); incr(kk);  }
11284
11285 @ @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>=
11286 if ( left_type(c)==mp_endpoint ) { 
11287   mp->spec_p1=mp_htap_ypoc(mp, c);
11288   mp->spec_p2=mp->path_tail;
11289   originator(mp->spec_p1)=mp_program_code;
11290   link(mp->spec_p2)=link(mp->spec_p1);
11291   link(mp->spec_p1)=c;
11292   mp_remove_cubic(mp, mp->spec_p1);
11293   c=mp->spec_p1;
11294   if ( c!=link(c) ) {
11295     originator(mp->spec_p2)=mp_program_code;
11296     mp_remove_cubic(mp, mp->spec_p2);
11297   } else {
11298     @<Make |c| look like a cycle of length one@>;
11299   }
11300 }
11301
11302 @ @<Make |c| look like a cycle of length one@>=
11303
11304   left_type(c)=mp_explicit; right_type(c)=mp_explicit;
11305   left_x(c)=x_coord(c); left_y(c)=y_coord(c);
11306   right_x(c)=x_coord(c); right_y(c)=y_coord(c);
11307 }
11308
11309 @ In degenerate situations we might have to look at the knot preceding~|q|.
11310 That knot is |p| but if |p<>c|, its coordinates have already been offset by |w|.
11311
11312 @<Set the incoming and outgoing directions at |q|; in case of...@>=
11313 dxin=x_coord(q)-left_x(q);
11314 dyin=y_coord(q)-left_y(q);
11315 if ( (dxin==0)&&(dyin==0) ) {
11316   dxin=x_coord(q)-right_x(p);
11317   dyin=y_coord(q)-right_y(p);
11318   if ( (dxin==0)&&(dyin==0) ) {
11319     dxin=x_coord(q)-x_coord(p);
11320     dyin=y_coord(q)-y_coord(p);
11321     if ( p!=c ) { /* the coordinates of |p| have been offset by |w| */
11322       dxin=dxin+x_coord(w);
11323       dyin=dyin+y_coord(w);
11324     }
11325   }
11326 }
11327 tmp=mp_pyth_add(mp, dxin,dyin);
11328 if ( tmp==0 ) {
11329   join_type=2;
11330 } else { 
11331   dxin=mp_make_fraction(mp, dxin,tmp);
11332   dyin=mp_make_fraction(mp, dyin,tmp);
11333   @<Set the outgoing direction at |q|@>;
11334 }
11335
11336 @ If |q=c| then the coordinates of |r| and the control points between |q|
11337 and~|r| have already been offset by |h|.
11338
11339 @<Set the outgoing direction at |q|@>=
11340 dxout=right_x(q)-x_coord(q);
11341 dyout=right_y(q)-y_coord(q);
11342 if ( (dxout==0)&&(dyout==0) ) {
11343   r=link(q);
11344   dxout=left_x(r)-x_coord(q);
11345   dyout=left_y(r)-y_coord(q);
11346   if ( (dxout==0)&&(dyout==0) ) {
11347     dxout=x_coord(r)-x_coord(q);
11348     dyout=y_coord(r)-y_coord(q);
11349   }
11350 }
11351 if ( q==c ) {
11352   dxout=dxout-x_coord(h);
11353   dyout=dyout-y_coord(h);
11354 }
11355 tmp=mp_pyth_add(mp, dxout,dyout);
11356 if ( tmp==0 ) mp_confusion(mp, "degenerate spec");
11357 @:this can't happen degerate spec}{\quad degenerate spec@>
11358 dxout=mp_make_fraction(mp, dxout,tmp);
11359 dyout=mp_make_fraction(mp, dyout,tmp)
11360
11361 @* \[23] Direction and intersection times.
11362 A path of length $n$ is defined parametrically by functions $x(t)$ and
11363 $y(t)$, for |0<=t<=n|; we can regard $t$ as the ``time'' at which the path
11364 reaches the point $\bigl(x(t),y(t)\bigr)$.  In this section of the program
11365 we shall consider operations that determine special times associated with
11366 given paths: the first time that a path travels in a given direction, and
11367 a pair of times at which two paths cross each other.
11368
11369 @ Let's start with the easier task. The function |find_direction_time| is
11370 given a direction |(x,y)| and a path starting at~|h|. If the path never
11371 travels in direction |(x,y)|, the direction time will be~|-1|; otherwise
11372 it will be nonnegative.
11373
11374 Certain anomalous cases can arise: If |(x,y)=(0,0)|, so that the given
11375 direction is undefined, the direction time will be~0. If $\bigl(x'(t),
11376 y'(t)\bigr)=(0,0)$, so that the path direction is undefined, it will be
11377 assumed to match any given direction at time~|t|.
11378
11379 The routine solves this problem in nondegenerate cases by rotating the path
11380 and the given direction so that |(x,y)=(1,0)|; i.e., the main task will be
11381 to find when a given path first travels ``due east.''
11382
11383 @c 
11384 scaled mp_find_direction_time (MP mp,scaled x, scaled y, pointer h) {
11385   scaled max; /* $\max\bigl(\vert x\vert,\vert y\vert\bigr)$ */
11386   pointer p,q; /* for list traversal */
11387   scaled n; /* the direction time at knot |p| */
11388   scaled tt; /* the direction time within a cubic */
11389   @<Other local variables for |find_direction_time|@>;
11390   @<Normalize the given direction for better accuracy;
11391     but |return| with zero result if it's zero@>;
11392   n=0; p=h; phi=0;
11393   while (1) { 
11394     if ( right_type(p)==mp_endpoint ) break;
11395     q=link(p);
11396     @<Rotate the cubic between |p| and |q|; then
11397       |goto found| if the rotated cubic travels due east at some time |tt|;
11398       but |break| if an entire cyclic path has been traversed@>;
11399     p=q; n=n+unity;
11400   }
11401   return (-unity);
11402 FOUND: 
11403   return (n+tt);
11404 }
11405
11406 @ @<Normalize the given direction for better accuracy...@>=
11407 if ( abs(x)<abs(y) ) { 
11408   x=mp_make_fraction(mp, x,abs(y));
11409   if ( y>0 ) y=fraction_one; else y=-fraction_one;
11410 } else if ( x==0 ) { 
11411   return 0;
11412 } else  { 
11413   y=mp_make_fraction(mp, y,abs(x));
11414   if ( x>0 ) x=fraction_one; else x=-fraction_one;
11415 }
11416
11417 @ Since we're interested in the tangent directions, we work with the
11418 derivative $${\textstyle1\over3}B'(x_0,x_1,x_2,x_3;t)=
11419 B(x_1-x_0,x_2-x_1,x_3-x_2;t)$$ instead of
11420 $B(x_0,x_1,x_2,x_3;t)$ itself. The derived coefficients are also scaled up
11421 in order to achieve better accuracy.
11422
11423 The given path may turn abruptly at a knot, and it might pass the critical
11424 tangent direction at such a time. Therefore we remember the direction |phi|
11425 in which the previous rotated cubic was traveling. (The value of |phi| will be
11426 undefined on the first cubic, i.e., when |n=0|.)
11427
11428 @<Rotate the cubic between |p| and |q|; then...@>=
11429 tt=0;
11430 @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples of the control
11431   points of the rotated derivatives@>;
11432 if ( y1==0 ) if ( x1>=0 ) goto FOUND;
11433 if ( n>0 ) { 
11434   @<Exit to |found| if an eastward direction occurs at knot |p|@>;
11435   if ( p==h ) break;
11436   };
11437 if ( (x3!=0)||(y3!=0) ) phi=mp_n_arg(mp, x3,y3);
11438 @<Exit to |found| if the curve whose derivatives are specified by
11439   |x1,x2,x3,y1,y2,y3| travels eastward at some time~|tt|@>
11440
11441 @ @<Other local variables for |find_direction_time|@>=
11442 scaled x1,x2,x3,y1,y2,y3;  /* multiples of rotated derivatives */
11443 angle theta,phi; /* angles of exit and entry at a knot */
11444 fraction t; /* temp storage */
11445
11446 @ @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples...@>=
11447 x1=right_x(p)-x_coord(p); x2=left_x(q)-right_x(p);
11448 x3=x_coord(q)-left_x(q);
11449 y1=right_y(p)-y_coord(p); y2=left_y(q)-right_y(p);
11450 y3=y_coord(q)-left_y(q);
11451 max=abs(x1);
11452 if ( abs(x2)>max ) max=abs(x2);
11453 if ( abs(x3)>max ) max=abs(x3);
11454 if ( abs(y1)>max ) max=abs(y1);
11455 if ( abs(y2)>max ) max=abs(y2);
11456 if ( abs(y3)>max ) max=abs(y3);
11457 if ( max==0 ) goto FOUND;
11458 while ( max<fraction_half ){ 
11459   max+=max; x1+=x1; x2+=x2; x3+=x3;
11460   y1+=y1; y2+=y2; y3+=y3;
11461 }
11462 t=x1; x1=mp_take_fraction(mp, x1,x)+mp_take_fraction(mp, y1,y);
11463 y1=mp_take_fraction(mp, y1,x)-mp_take_fraction(mp, t,y);
11464 t=x2; x2=mp_take_fraction(mp, x2,x)+mp_take_fraction(mp, y2,y);
11465 y2=mp_take_fraction(mp, y2,x)-mp_take_fraction(mp, t,y);
11466 t=x3; x3=mp_take_fraction(mp, x3,x)+mp_take_fraction(mp, y3,y);
11467 y3=mp_take_fraction(mp, y3,x)-mp_take_fraction(mp, t,y)
11468
11469 @ @<Exit to |found| if an eastward direction occurs at knot |p|@>=
11470 theta=mp_n_arg(mp, x1,y1);
11471 if ( theta>=0 ) if ( phi<=0 ) if ( phi>=theta-one_eighty_deg ) goto FOUND;
11472 if ( theta<=0 ) if ( phi>=0 ) if ( phi<=theta+one_eighty_deg ) goto FOUND
11473
11474 @ In this step we want to use the |crossing_point| routine to find the
11475 roots of the quadratic equation $B(y_1,y_2,y_3;t)=0$.
11476 Several complications arise: If the quadratic equation has a double root,
11477 the curve never crosses zero, and |crossing_point| will find nothing;
11478 this case occurs iff $y_1y_3=y_2^2$ and $y_1y_2<0$. If the quadratic
11479 equation has simple roots, or only one root, we may have to negate it
11480 so that $B(y_1,y_2,y_3;t)$ crosses from positive to negative at its first root.
11481 And finally, we need to do special things if $B(y_1,y_2,y_3;t)$ is
11482 identically zero.
11483
11484 @ @<Exit to |found| if the curve whose derivatives are specified by...@>=
11485 if ( x1<0 ) if ( x2<0 ) if ( x3<0 ) goto DONE;
11486 if ( mp_ab_vs_cd(mp, y1,y3,y2,y2)==0 ) {
11487   @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11488     either |goto found| or |goto done|@>;
11489 }
11490 if ( y1<=0 ) {
11491   if ( y1<0 ) { y1=-y1; y2=-y2; y3=-y3; }
11492   else if ( y2>0 ){ y2=-y2; y3=-y3; };
11493 }
11494 @<Check the places where $B(y_1,y_2,y_3;t)=0$ to see if
11495   $B(x_1,x_2,x_3;t)\ge0$@>;
11496 DONE:
11497
11498 @ The quadratic polynomial $B(y_1,y_2,y_3;t)$ begins |>=0| and has at most
11499 two roots, because we know that it isn't identically zero.
11500
11501 It must be admitted that the |crossing_point| routine is not perfectly accurate;
11502 rounding errors might cause it to find a root when $y_1y_3>y_2^2$, or to
11503 miss the roots when $y_1y_3<y_2^2$. The rotation process is itself
11504 subject to rounding errors. Yet this code optimistically tries to
11505 do the right thing.
11506
11507 @d we_found_it { tt=(t+04000) / 010000; goto FOUND; }
11508
11509 @<Check the places where $B(y_1,y_2,y_3;t)=0$...@>=
11510 t=mp_crossing_point(mp, y1,y2,y3);
11511 if ( t>fraction_one ) goto DONE;
11512 y2=t_of_the_way(y2,y3);
11513 x1=t_of_the_way(x1,x2);
11514 x2=t_of_the_way(x2,x3);
11515 x1=t_of_the_way(x1,x2);
11516 if ( x1>=0 ) we_found_it;
11517 if ( y2>0 ) y2=0;
11518 tt=t; t=mp_crossing_point(mp, 0,-y2,-y3);
11519 if ( t>fraction_one ) goto DONE;
11520 x1=t_of_the_way(x1,x2);
11521 x2=t_of_the_way(x2,x3);
11522 if ( t_of_the_way(x1,x2)>=0 ) { 
11523   t=t_of_the_way(tt,fraction_one); we_found_it;
11524 }
11525
11526 @ @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11527     either |goto found| or |goto done|@>=
11528
11529   if ( mp_ab_vs_cd(mp, y1,y2,0,0)<0 ) {
11530     t=mp_make_fraction(mp, y1,y1-y2);
11531     x1=t_of_the_way(x1,x2);
11532     x2=t_of_the_way(x2,x3);
11533     if ( t_of_the_way(x1,x2)>=0 ) we_found_it;
11534   } else if ( y3==0 ) {
11535     if ( y1==0 ) {
11536       @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|@>;
11537     } else if ( x3>=0 ) {
11538       tt=unity; goto FOUND;
11539     }
11540   }
11541   goto DONE;
11542 }
11543
11544 @ At this point we know that the derivative of |y(t)| is identically zero,
11545 and that |x1<0|; but either |x2>=0| or |x3>=0|, so there's some hope of
11546 traveling east.
11547
11548 @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|...@>=
11549
11550   t=mp_crossing_point(mp, -x1,-x2,-x3);
11551   if ( t<=fraction_one ) we_found_it;
11552   if ( mp_ab_vs_cd(mp, x1,x3,x2,x2)<=0 ) { 
11553     t=mp_make_fraction(mp, x1,x1-x2); we_found_it;
11554   }
11555 }
11556
11557 @ The intersection of two cubics can be found by an interesting variant
11558 of the general bisection scheme described in the introduction to
11559 |crossing_point|.\
11560 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)$,
11561 we wish to find a pair of times $(t_1,t_2)$ such that $w(t_1)=z(t_2)$,
11562 if an intersection exists. First we find the smallest rectangle that
11563 encloses the points $\{w_0,w_1,w_2,w_3\}$ and check that it overlaps
11564 the smallest rectangle that encloses
11565 $\{z_0,z_1,z_2,z_3\}$; if not, the cubics certainly don't intersect.
11566 But if the rectangles do overlap, we bisect the intervals, getting
11567 new cubics $w'$ and~$w''$, $z'$~and~$z''$; the intersection routine first
11568 tries for an intersection between $w'$ and~$z'$, then (if unsuccessful)
11569 between $w'$ and~$z''$, then (if still unsuccessful) between $w''$ and~$z'$,
11570 finally (if thrice unsuccessful) between $w''$ and~$z''$. After $l$~successful
11571 levels of bisection we will have determined the intersection times $t_1$
11572 and~$t_2$ to $l$~bits of accuracy.
11573
11574 \def\submin{_{\rm min}} \def\submax{_{\rm max}}
11575 As before, it is better to work with the numbers $W_k=2^l(w_k-w_{k-1})$
11576 and $Z_k=2^l(z_k-z_{k-1})$ rather than the coefficients $w_k$ and $z_k$
11577 themselves. We also need one other quantity, $\Delta=2^l(w_0-z_0)$,
11578 to determine when the enclosing rectangles overlap. Here's why:
11579 The $x$~coordinates of~$w(t)$ are between $u\submin$ and $u\submax$,
11580 and the $x$~coordinates of~$z(t)$ are between $x\submin$ and $x\submax$,
11581 if we write $w_k=(u_k,v_k)$ and $z_k=(x_k,y_k)$ and $u\submin=
11582 \min(u_0,u_1,u_2,u_3)$, etc. These intervals of $x$~coordinates
11583 overlap if and only if $u\submin\L x\submax$ and
11584 $x\submin\L u\submax$. Letting
11585 $$U\submin=\min(0,U_1,U_1+U_2,U_1+U_2+U_3),\;
11586   U\submax=\max(0,U_1,U_1+U_2,U_1+U_2+U_3),$$
11587 we have $u\submin=2^lu_0+U\submin$, etc.; the condition for overlap
11588 reduces to
11589 $$X\submin-U\submax\L 2^l(u_0-x_0)\L X\submax-U\submin.$$
11590 Thus we want to maintain the quantity $2^l(u_0-x_0)$; similarly,
11591 the quantity $2^l(v_0-y_0)$ accounts for the $y$~coordinates. The
11592 coordinates of $\Delta=2^l(w_0-z_0)$ must stay bounded as $l$ increases,
11593 because of the overlap condition; i.e., we know that $X\submin$,
11594 $X\submax$, and their relatives are bounded, hence $X\submax-
11595 U\submin$ and $X\submin-U\submax$ are bounded.
11596
11597 @ Incidentally, if the given cubics intersect more than once, the process
11598 just sketched will not necessarily find the lexicographically smallest pair
11599 $(t_1,t_2)$. The solution actually obtained will be smallest in ``shuffled
11600 order''; i.e., if $t_1=(.a_1a_2\ldots a_{16})_2$ and
11601 $t_2=(.b_1b_2\ldots b_{16})_2$, then we will minimize
11602 $a_1b_1a_2b_2\ldots a_{16}b_{16}$, not
11603 $a_1a_2\ldots a_{16}b_1b_2\ldots b_{16}$.
11604 Shuffled order agrees with lexicographic order if all pairs of solutions
11605 $(t_1,t_2)$ and $(t_1',t_2')$ have the property that $t_1<t_1'$ iff
11606 $t_2<t_2'$; but in general, lexicographic order can be quite different,
11607 and the bisection algorithm would be substantially less efficient if it were
11608 constrained by lexicographic order.
11609
11610 For example, suppose that an overlap has been found for $l=3$ and
11611 $(t_1,t_2)= (.101,.011)$ in binary, but that no overlap is produced by
11612 either of the alternatives $(.1010,.0110)$, $(.1010,.0111)$ at level~4.
11613 Then there is probably an intersection in one of the subintervals
11614 $(.1011,.011x)$; but lexicographic order would require us to explore
11615 $(.1010,.1xxx)$ and $(.1011,.00xx)$ and $(.1011,.010x)$ first. We wouldn't
11616 want to store all of the subdivision data for the second path, so the
11617 subdivisions would have to be regenerated many times. Such inefficiencies
11618 would be associated with every `1' in the binary representation of~$t_1$.
11619
11620 @ The subdivision process introduces rounding errors, hence we need to
11621 make a more liberal test for overlap. It is not hard to show that the
11622 computed values of $U_i$ differ from the truth by at most~$l$, on
11623 level~$l$, hence $U\submin$ and $U\submax$ will be at most $3l$ in error.
11624 If $\beta$ is an upper bound on the absolute error in the computed
11625 components of $\Delta=(|delx|,|dely|)$ on level~$l$, we will replace
11626 the test `$X\submin-U\submax\L|delx|$' by the more liberal test
11627 `$X\submin-U\submax\L|delx|+|tol|$', where $|tol|=6l+\beta$.
11628
11629 More accuracy is obtained if we try the algorithm first with |tol=0|;
11630 the more liberal tolerance is used only if an exact approach fails.
11631 It is convenient to do this double-take by letting `3' in the preceding
11632 paragraph be a parameter, which is first 0, then 3.
11633
11634 @<Glob...@>=
11635 unsigned int tol_step; /* either 0 or 3, usually */
11636
11637 @ We shall use an explicit stack to implement the recursive bisection
11638 method described above. The |bisect_stack| array will contain numerous 5-word
11639 packets like $(U_1,U_2,U_3,U\submin,U\submax)$, as well as 20-word packets
11640 comprising the 5-word packets for $U$, $V$, $X$, and~$Y$.
11641
11642 The following macros define the allocation of stack positions to
11643 the quantities needed for bisection-intersection.
11644
11645 @d stack_1(A) mp->bisect_stack[(A)] /* $U_1$, $V_1$, $X_1$, or $Y_1$ */
11646 @d stack_2(A) mp->bisect_stack[(A)+1] /* $U_2$, $V_2$, $X_2$, or $Y_2$ */
11647 @d stack_3(A) mp->bisect_stack[(A)+2] /* $U_3$, $V_3$, $X_3$, or $Y_3$ */
11648 @d stack_min(A) mp->bisect_stack[(A)+3]
11649   /* $U\submin$, $V\submin$, $X\submin$, or $Y\submin$ */
11650 @d stack_max(A) mp->bisect_stack[(A)+4]
11651   /* $U\submax$, $V\submax$, $X\submax$, or $Y\submax$ */
11652 @d int_packets 20 /* number of words to represent $U_k$, $V_k$, $X_k$, and $Y_k$ */
11653 @#
11654 @d u_packet(A) ((A)-5)
11655 @d v_packet(A) ((A)-10)
11656 @d x_packet(A) ((A)-15)
11657 @d y_packet(A) ((A)-20)
11658 @d l_packets (mp->bisect_ptr-int_packets)
11659 @d r_packets mp->bisect_ptr
11660 @d ul_packet u_packet(l_packets) /* base of $U'_k$ variables */
11661 @d vl_packet v_packet(l_packets) /* base of $V'_k$ variables */
11662 @d xl_packet x_packet(l_packets) /* base of $X'_k$ variables */
11663 @d yl_packet y_packet(l_packets) /* base of $Y'_k$ variables */
11664 @d ur_packet u_packet(r_packets) /* base of $U''_k$ variables */
11665 @d vr_packet v_packet(r_packets) /* base of $V''_k$ variables */
11666 @d xr_packet x_packet(r_packets) /* base of $X''_k$ variables */
11667 @d yr_packet y_packet(r_packets) /* base of $Y''_k$ variables */
11668 @#
11669 @d u1l stack_1(ul_packet) /* $U'_1$ */
11670 @d u2l stack_2(ul_packet) /* $U'_2$ */
11671 @d u3l stack_3(ul_packet) /* $U'_3$ */
11672 @d v1l stack_1(vl_packet) /* $V'_1$ */
11673 @d v2l stack_2(vl_packet) /* $V'_2$ */
11674 @d v3l stack_3(vl_packet) /* $V'_3$ */
11675 @d x1l stack_1(xl_packet) /* $X'_1$ */
11676 @d x2l stack_2(xl_packet) /* $X'_2$ */
11677 @d x3l stack_3(xl_packet) /* $X'_3$ */
11678 @d y1l stack_1(yl_packet) /* $Y'_1$ */
11679 @d y2l stack_2(yl_packet) /* $Y'_2$ */
11680 @d y3l stack_3(yl_packet) /* $Y'_3$ */
11681 @d u1r stack_1(ur_packet) /* $U''_1$ */
11682 @d u2r stack_2(ur_packet) /* $U''_2$ */
11683 @d u3r stack_3(ur_packet) /* $U''_3$ */
11684 @d v1r stack_1(vr_packet) /* $V''_1$ */
11685 @d v2r stack_2(vr_packet) /* $V''_2$ */
11686 @d v3r stack_3(vr_packet) /* $V''_3$ */
11687 @d x1r stack_1(xr_packet) /* $X''_1$ */
11688 @d x2r stack_2(xr_packet) /* $X''_2$ */
11689 @d x3r stack_3(xr_packet) /* $X''_3$ */
11690 @d y1r stack_1(yr_packet) /* $Y''_1$ */
11691 @d y2r stack_2(yr_packet) /* $Y''_2$ */
11692 @d y3r stack_3(yr_packet) /* $Y''_3$ */
11693 @#
11694 @d stack_dx mp->bisect_stack[mp->bisect_ptr] /* stacked value of |delx| */
11695 @d stack_dy mp->bisect_stack[mp->bisect_ptr+1] /* stacked value of |dely| */
11696 @d stack_tol mp->bisect_stack[mp->bisect_ptr+2] /* stacked value of |tol| */
11697 @d stack_uv mp->bisect_stack[mp->bisect_ptr+3] /* stacked value of |uv| */
11698 @d stack_xy mp->bisect_stack[mp->bisect_ptr+4] /* stacked value of |xy| */
11699 @d int_increment (int_packets+int_packets+5) /* number of stack words per level */
11700
11701 @<Glob...@>=
11702 integer *bisect_stack;
11703 unsigned int bisect_ptr;
11704
11705 @ @<Allocate or initialize ...@>=
11706 mp->bisect_stack = xmalloc((bistack_size+1),sizeof(integer));
11707
11708 @ @<Dealloc variables@>=
11709 xfree(mp->bisect_stack);
11710
11711 @ @<Check the ``constant''...@>=
11712 if ( int_packets+17*int_increment>bistack_size ) mp->bad=19;
11713
11714 @ Computation of the min and max is a tedious but fairly fast sequence of
11715 instructions; exactly four comparisons are made in each branch.
11716
11717 @d set_min_max(A) 
11718   if ( stack_1((A))<0 ) {
11719     if ( stack_3((A))>=0 ) {
11720       if ( stack_2((A))<0 ) stack_min((A))=stack_1((A))+stack_2((A));
11721       else stack_min((A))=stack_1((A));
11722       stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11723       if ( stack_max((A))<0 ) stack_max((A))=0;
11724     } else { 
11725       stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11726       if ( stack_min((A))>stack_1((A)) ) stack_min((A))=stack_1((A));
11727       stack_max((A))=stack_1((A))+stack_2((A));
11728       if ( stack_max((A))<0 ) stack_max((A))=0;
11729     }
11730   } else if ( stack_3((A))<=0 ) {
11731     if ( stack_2((A))>0 ) stack_max((A))=stack_1((A))+stack_2((A));
11732     else stack_max((A))=stack_1((A));
11733     stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11734     if ( stack_min((A))>0 ) stack_min((A))=0;
11735   } else  { 
11736     stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11737     if ( stack_max((A))<stack_1((A)) ) stack_max((A))=stack_1((A));
11738     stack_min((A))=stack_1((A))+stack_2((A));
11739     if ( stack_min((A))>0 ) stack_min((A))=0;
11740   }
11741
11742 @ It's convenient to keep the current values of $l$, $t_1$, and $t_2$ in
11743 the integer form $2^l+2^lt_1$ and $2^l+2^lt_2$. The |cubic_intersection|
11744 routine uses global variables |cur_t| and |cur_tt| for this purpose;
11745 after successful completion, |cur_t| and |cur_tt| will contain |unity|
11746 plus the |scaled| values of $t_1$ and~$t_2$.
11747
11748 The values of |cur_t| and |cur_tt| will be set to zero if |cubic_intersection|
11749 finds no intersection. The routine gives up and gives an approximate answer
11750 if it has backtracked
11751 more than 5000 times (otherwise there are cases where several minutes
11752 of fruitless computation would be possible).
11753
11754 @d max_patience 5000
11755
11756 @<Glob...@>=
11757 integer cur_t;integer cur_tt; /* controls and results of |cubic_intersection| */
11758 integer time_to_go; /* this many backtracks before giving up */
11759 integer max_t; /* maximum of $2^{l+1}$ so far achieved */
11760
11761 @ The given cubics $B(w_0,w_1,w_2,w_3;t)$ and
11762 $B(z_0,z_1,z_2,z_3;t)$ are specified in adjacent knot nodes |(p,link(p))|
11763 and |(pp,link(pp))|, respectively.
11764
11765 @c void mp_cubic_intersection (MP mp,pointer p, pointer pp) {
11766   pointer q,qq; /* |link(p)|, |link(pp)| */
11767   mp->time_to_go=max_patience; mp->max_t=2;
11768   @<Initialize for intersections at level zero@>;
11769 CONTINUE:
11770   while (1) { 
11771     if ( mp->delx-mp->tol<=stack_max(x_packet(mp->xy))-stack_min(u_packet(mp->uv)))
11772     if ( mp->delx+mp->tol>=stack_min(x_packet(mp->xy))-stack_max(u_packet(mp->uv)))
11773     if ( mp->dely-mp->tol<=stack_max(y_packet(mp->xy))-stack_min(v_packet(mp->uv)))
11774     if ( mp->dely+mp->tol>=stack_min(y_packet(mp->xy))-stack_max(v_packet(mp->uv))) 
11775     { 
11776       if ( mp->cur_t>=mp->max_t ){ 
11777         if ( mp->max_t==two ) { /* we've done 17 bisections */ 
11778            mp->cur_t=halfp(mp->cur_t+1); mp->cur_tt=halfp(mp->cur_tt+1); return;
11779         }
11780         mp->max_t+=mp->max_t; mp->appr_t=mp->cur_t; mp->appr_tt=mp->cur_tt;
11781       }
11782       @<Subdivide for a new level of intersection@>;
11783       goto CONTINUE;
11784     }
11785     if ( mp->time_to_go>0 ) {
11786       decr(mp->time_to_go);
11787     } else { 
11788       while ( mp->appr_t<unity ) { 
11789         mp->appr_t+=mp->appr_t; mp->appr_tt+=mp->appr_tt;
11790       }
11791       mp->cur_t=mp->appr_t; mp->cur_tt=mp->appr_tt; return;
11792     }
11793     @<Advance to the next pair |(cur_t,cur_tt)|@>;
11794   }
11795 }
11796
11797 @ The following variables are global, although they are used only by
11798 |cubic_intersection|, because it is necessary on some machines to
11799 split |cubic_intersection| up into two procedures.
11800
11801 @<Glob...@>=
11802 integer delx;integer dely; /* the components of $\Delta=2^l(w_0-z_0)$ */
11803 integer tol; /* bound on the uncertainly in the overlap test */
11804 unsigned int uv;
11805 unsigned int xy; /* pointers to the current packets of interest */
11806 integer three_l; /* |tol_step| times the bisection level */
11807 integer appr_t;integer appr_tt; /* best approximations known to the answers */
11808
11809 @ We shall assume that the coordinates are sufficiently non-extreme that
11810 integer overflow will not occur.
11811
11812 @<Initialize for intersections at level zero@>=
11813 q=link(p); qq=link(pp); mp->bisect_ptr=int_packets;
11814 u1r=right_x(p)-x_coord(p); u2r=left_x(q)-right_x(p);
11815 u3r=x_coord(q)-left_x(q); set_min_max(ur_packet);
11816 v1r=right_y(p)-y_coord(p); v2r=left_y(q)-right_y(p);
11817 v3r=y_coord(q)-left_y(q); set_min_max(vr_packet);
11818 x1r=right_x(pp)-x_coord(pp); x2r=left_x(qq)-right_x(pp);
11819 x3r=x_coord(qq)-left_x(qq); set_min_max(xr_packet);
11820 y1r=right_y(pp)-y_coord(pp); y2r=left_y(qq)-right_y(pp);
11821 y3r=y_coord(qq)-left_y(qq); set_min_max(yr_packet);
11822 mp->delx=x_coord(p)-x_coord(pp); mp->dely=y_coord(p)-y_coord(pp);
11823 mp->tol=0; mp->uv=r_packets; mp->xy=r_packets; 
11824 mp->three_l=0; mp->cur_t=1; mp->cur_tt=1
11825
11826 @ @<Subdivide for a new level of intersection@>=
11827 stack_dx=mp->delx; stack_dy=mp->dely; stack_tol=mp->tol; 
11828 stack_uv=mp->uv; stack_xy=mp->xy;
11829 mp->bisect_ptr=mp->bisect_ptr+int_increment;
11830 mp->cur_t+=mp->cur_t; mp->cur_tt+=mp->cur_tt;
11831 u1l=stack_1(u_packet(mp->uv)); u3r=stack_3(u_packet(mp->uv));
11832 u2l=half(u1l+stack_2(u_packet(mp->uv)));
11833 u2r=half(u3r+stack_2(u_packet(mp->uv)));
11834 u3l=half(u2l+u2r); u1r=u3l;
11835 set_min_max(ul_packet); set_min_max(ur_packet);
11836 v1l=stack_1(v_packet(mp->uv)); v3r=stack_3(v_packet(mp->uv));
11837 v2l=half(v1l+stack_2(v_packet(mp->uv)));
11838 v2r=half(v3r+stack_2(v_packet(mp->uv)));
11839 v3l=half(v2l+v2r); v1r=v3l;
11840 set_min_max(vl_packet); set_min_max(vr_packet);
11841 x1l=stack_1(x_packet(mp->xy)); x3r=stack_3(x_packet(mp->xy));
11842 x2l=half(x1l+stack_2(x_packet(mp->xy)));
11843 x2r=half(x3r+stack_2(x_packet(mp->xy)));
11844 x3l=half(x2l+x2r); x1r=x3l;
11845 set_min_max(xl_packet); set_min_max(xr_packet);
11846 y1l=stack_1(y_packet(mp->xy)); y3r=stack_3(y_packet(mp->xy));
11847 y2l=half(y1l+stack_2(y_packet(mp->xy)));
11848 y2r=half(y3r+stack_2(y_packet(mp->xy)));
11849 y3l=half(y2l+y2r); y1r=y3l;
11850 set_min_max(yl_packet); set_min_max(yr_packet);
11851 mp->uv=l_packets; mp->xy=l_packets;
11852 mp->delx+=mp->delx; mp->dely+=mp->dely;
11853 mp->tol=mp->tol-mp->three_l+mp->tol_step; 
11854 mp->tol+=mp->tol; mp->three_l=mp->three_l+mp->tol_step
11855
11856 @ @<Advance to the next pair |(cur_t,cur_tt)|@>=
11857 NOT_FOUND: 
11858 if ( odd(mp->cur_tt) ) {
11859   if ( odd(mp->cur_t) ) {
11860      @<Descend to the previous level and |goto not_found|@>;
11861   } else { 
11862     incr(mp->cur_t);
11863     mp->delx=mp->delx+stack_1(u_packet(mp->uv))+stack_2(u_packet(mp->uv))
11864       +stack_3(u_packet(mp->uv));
11865     mp->dely=mp->dely+stack_1(v_packet(mp->uv))+stack_2(v_packet(mp->uv))
11866       +stack_3(v_packet(mp->uv));
11867     mp->uv=mp->uv+int_packets; /* switch from |l_packet| to |r_packet| */
11868     decr(mp->cur_tt); mp->xy=mp->xy-int_packets; 
11869          /* switch from |r_packet| to |l_packet| */
11870     mp->delx=mp->delx+stack_1(x_packet(mp->xy))+stack_2(x_packet(mp->xy))
11871       +stack_3(x_packet(mp->xy));
11872     mp->dely=mp->dely+stack_1(y_packet(mp->xy))+stack_2(y_packet(mp->xy))
11873       +stack_3(y_packet(mp->xy));
11874   }
11875 } else { 
11876   incr(mp->cur_tt); mp->tol=mp->tol+mp->three_l;
11877   mp->delx=mp->delx-stack_1(x_packet(mp->xy))-stack_2(x_packet(mp->xy))
11878     -stack_3(x_packet(mp->xy));
11879   mp->dely=mp->dely-stack_1(y_packet(mp->xy))-stack_2(y_packet(mp->xy))
11880     -stack_3(y_packet(mp->xy));
11881   mp->xy=mp->xy+int_packets; /* switch from |l_packet| to |r_packet| */
11882 }
11883
11884 @ @<Descend to the previous level...@>=
11885
11886   mp->cur_t=halfp(mp->cur_t); mp->cur_tt=halfp(mp->cur_tt);
11887   if ( mp->cur_t==0 ) return;
11888   mp->bisect_ptr=mp->bisect_ptr-int_increment; 
11889   mp->three_l=mp->three_l-mp->tol_step;
11890   mp->delx=stack_dx; mp->dely=stack_dy; mp->tol=stack_tol; 
11891   mp->uv=stack_uv; mp->xy=stack_xy;
11892   goto NOT_FOUND;
11893 }
11894
11895 @ The |path_intersection| procedure is much simpler.
11896 It invokes |cubic_intersection| in lexicographic order until finding a
11897 pair of cubics that intersect. The final intersection times are placed in
11898 |cur_t| and~|cur_tt|.
11899
11900 @c void mp_path_intersection (MP mp,pointer h, pointer hh) {
11901   pointer p,pp; /* link registers that traverse the given paths */
11902   integer n,nn; /* integer parts of intersection times, minus |unity| */
11903   @<Change one-point paths into dead cycles@>;
11904   mp->tol_step=0;
11905   do {  
11906     n=-unity; p=h;
11907     do {  
11908       if ( right_type(p)!=mp_endpoint ) { 
11909         nn=-unity; pp=hh;
11910         do {  
11911           if ( right_type(pp)!=mp_endpoint )  { 
11912             mp_cubic_intersection(mp, p,pp);
11913             if ( mp->cur_t>0 ) { 
11914               mp->cur_t=mp->cur_t+n; mp->cur_tt=mp->cur_tt+nn; 
11915               return;
11916             }
11917           }
11918           nn=nn+unity; pp=link(pp);
11919         } while (pp!=hh);
11920       }
11921       n=n+unity; p=link(p);
11922     } while (p!=h);
11923     mp->tol_step=mp->tol_step+3;
11924   } while (mp->tol_step<=3);
11925   mp->cur_t=-unity; mp->cur_tt=-unity;
11926 }
11927
11928 @ @<Change one-point paths...@>=
11929 if ( right_type(h)==mp_endpoint ) {
11930   right_x(h)=x_coord(h); left_x(h)=x_coord(h);
11931   right_y(h)=y_coord(h); left_y(h)=y_coord(h); right_type(h)=mp_explicit;
11932 }
11933 if ( right_type(hh)==mp_endpoint ) {
11934   right_x(hh)=x_coord(hh); left_x(hh)=x_coord(hh);
11935   right_y(hh)=y_coord(hh); left_y(hh)=y_coord(hh); right_type(hh)=mp_explicit;
11936 }
11937
11938 @* \[24] Dynamic linear equations.
11939 \MP\ users define variables implicitly by stating equations that should be
11940 satisfied; the computer is supposed to be smart enough to solve those equations.
11941 And indeed, the computer tries valiantly to do so, by distinguishing five
11942 different types of numeric values:
11943
11944 \smallskip\hang
11945 |type(p)=mp_known| is the nice case, when |value(p)| is the |scaled| value
11946 of the variable whose address is~|p|.
11947
11948 \smallskip\hang
11949 |type(p)=mp_dependent| means that |value(p)| is not present, but |dep_list(p)|
11950 points to a {\sl dependency list\/} that expresses the value of variable~|p|
11951 as a |scaled| number plus a sum of independent variables with |fraction|
11952 coefficients.
11953
11954 \smallskip\hang
11955 |type(p)=mp_independent| means that |value(p)=64s+m|, where |s>0| is a ``serial
11956 number'' reflecting the time this variable was first used in an equation;
11957 also |0<=m<64|, and each dependent variable
11958 that refers to this one is actually referring to the future value of
11959 this variable times~$2^m$. (Usually |m=0|, but higher degrees of
11960 scaling are sometimes needed to keep the coefficients in dependency lists
11961 from getting too large. The value of~|m| will always be even.)
11962
11963 \smallskip\hang
11964 |type(p)=mp_numeric_type| means that variable |p| hasn't appeared in an
11965 equation before, but it has been explicitly declared to be numeric.
11966
11967 \smallskip\hang
11968 |type(p)=undefined| means that variable |p| hasn't appeared before.
11969
11970 \smallskip\noindent
11971 We have actually discussed these five types in the reverse order of their
11972 history during a computation: Once |known|, a variable never again
11973 becomes |dependent|; once |dependent|, it almost never again becomes
11974 |mp_independent|; once |mp_independent|, it never again becomes |mp_numeric_type|;
11975 and once |mp_numeric_type|, it never again becomes |undefined| (except
11976 of course when the user specifically decides to scrap the old value
11977 and start again). A backward step may, however, take place: Sometimes
11978 a |dependent| variable becomes |mp_independent| again, when one of the
11979 independent variables it depends on is reverting to |undefined|.
11980
11981
11982 The next patch detects overflow of independent-variable serial
11983 numbers. Diagnosed and patched by Thorsten Dahlheimer.
11984
11985 @d s_scale 64 /* the serial numbers are multiplied by this factor */
11986 @d max_indep_vars 0177777777 /* $2^{25}-1$ */
11987 @d max_serial_no 017777777700 /* |max_indep_vars*s_scale| */
11988 @d new_indep(A)  /* create a new independent variable */
11989   { if ( mp->serial_no==max_serial_no )
11990     mp_fatal_error(mp, "variable instance identifiers exhausted");
11991   type((A))=mp_independent; mp->serial_no=mp->serial_no+s_scale;
11992   value((A))=mp->serial_no;
11993   }
11994
11995 @<Glob...@>=
11996 integer serial_no; /* the most recent serial number, times |s_scale| */
11997
11998 @ @<Make variable |q+s| newly independent@>=new_indep(q+s)
11999
12000 @ But how are dependency lists represented? It's simple: The linear combination
12001 $\alpha_1v_1+\cdots+\alpha_kv_k+\beta$ appears in |k+1| value nodes. If
12002 |q=dep_list(p)| points to this list, and if |k>0|, then |value(q)=
12003 @t$\alpha_1$@>| (which is a |fraction|); |info(q)| points to the location
12004 of $\alpha_1$; and |link(p)| points to the dependency list
12005 $\alpha_2v_2+\cdots+\alpha_kv_k+\beta$. On the other hand if |k=0|,
12006 then |value(q)=@t$\beta$@>| (which is |scaled|) and |info(q)=null|.
12007 The independent variables $v_1$, \dots,~$v_k$ have been sorted so that
12008 they appear in decreasing order of their |value| fields (i.e., of
12009 their serial numbers). \ (It is convenient to use decreasing order,
12010 since |value(null)=0|. If the independent variables were not sorted by
12011 serial number but by some other criterion, such as their location in |mem|,
12012 the equation-solving mechanism would be too system-dependent, because
12013 the ordering can affect the computed results.)
12014
12015 The |link| field in the node that contains the constant term $\beta$ is
12016 called the {\sl final link\/} of the dependency list. \MP\ maintains
12017 a doubly-linked master list of all dependency lists, in terms of a permanently
12018 allocated node
12019 in |mem| called |dep_head|. If there are no dependencies, we have
12020 |link(dep_head)=dep_head| and |prev_dep(dep_head)=dep_head|;
12021 otherwise |link(dep_head)| points to the first dependent variable, say~|p|,
12022 and |prev_dep(p)=dep_head|. We have |type(p)=mp_dependent|, and |dep_list(p)|
12023 points to its dependency list. If the final link of that dependency list
12024 occurs in location~|q|, then |link(q)| points to the next dependent
12025 variable (say~|r|); and we have |prev_dep(r)=q|, etc.
12026
12027 @d dep_list(A) link(value_loc((A)))
12028   /* half of the |value| field in a |dependent| variable */
12029 @d prev_dep(A) info(value_loc((A)))
12030   /* the other half; makes a doubly linked list */
12031 @d dep_node_size 2 /* the number of words per dependency node */
12032
12033 @<Initialize table entries...@>= mp->serial_no=0;
12034 link(dep_head)=dep_head; prev_dep(dep_head)=dep_head;
12035 info(dep_head)=null; dep_list(dep_head)=null;
12036
12037 @ Actually the description above contains a little white lie. There's
12038 another kind of variable called |mp_proto_dependent|, which is
12039 just like a |dependent| one except that the $\alpha$ coefficients
12040 in its dependency list are |scaled| instead of being fractions.
12041 Proto-dependency lists are mixed with dependency lists in the
12042 nodes reachable from |dep_head|.
12043
12044 @ Here is a procedure that prints a dependency list in symbolic form.
12045 The second parameter should be either |dependent| or |mp_proto_dependent|,
12046 to indicate the scaling of the coefficients.
12047
12048 @<Declare subroutines for printing expressions@>=
12049 void mp_print_dependency (MP mp,pointer p, small_number t) {
12050   integer v; /* a coefficient */
12051   pointer pp,q; /* for list manipulation */
12052   pp=p;
12053   while (1) { 
12054     v=abs(value(p)); q=info(p);
12055     if ( q==null ) { /* the constant term */
12056       if ( (v!=0)||(p==pp) ) {
12057          if ( value(p)>0 ) if ( p!=pp ) mp_print_char(mp, '+');
12058          mp_print_scaled(mp, value(p));
12059       }
12060       return;
12061     }
12062     @<Print the coefficient, unless it's $\pm1.0$@>;
12063     if ( type(q)!=mp_independent ) mp_confusion(mp, "dep");
12064 @:this can't happen dep}{\quad dep@>
12065     mp_print_variable_name(mp, q); v=value(q) % s_scale;
12066     while ( v>0 ) { mp_print(mp, "*4"); v=v-2; }
12067     p=link(p);
12068   }
12069 }
12070
12071 @ @<Print the coefficient, unless it's $\pm1.0$@>=
12072 if ( value(p)<0 ) mp_print_char(mp, '-');
12073 else if ( p!=pp ) mp_print_char(mp, '+');
12074 if ( t==mp_dependent ) v=mp_round_fraction(mp, v);
12075 if ( v!=unity ) mp_print_scaled(mp, v)
12076
12077 @ The maximum absolute value of a coefficient in a given dependency list
12078 is returned by the following simple function.
12079
12080 @c fraction mp_max_coef (MP mp,pointer p) {
12081   fraction x; /* the maximum so far */
12082   x=0;
12083   while ( info(p)!=null ) {
12084     if ( abs(value(p))>x ) x=abs(value(p));
12085     p=link(p);
12086   }
12087   return x;
12088 }
12089
12090 @ One of the main operations needed on dependency lists is to add a multiple
12091 of one list to the other; we call this |p_plus_fq|, where |p| and~|q| point
12092 to dependency lists and |f| is a fraction.
12093
12094 If the coefficient of any independent variable becomes |coef_bound| or
12095 more, in absolute value, this procedure changes the type of that variable
12096 to `|independent_needing_fix|', and sets the global variable |fix_needed|
12097 to~|true|. The value of $|coef_bound|=\mu$ is chosen so that
12098 $\mu^2+\mu<8$; this means that the numbers we deal with won't
12099 get too large. (Instead of the ``optimum'' $\mu=(\sqrt{33}-1)/2\approx
12100 2.3723$, the safer value 7/3 is taken as the threshold.)
12101
12102 The changes mentioned in the preceding paragraph are actually done only if
12103 the global variable |watch_coefs| is |true|. But it usually is; in fact,
12104 it is |false| only when \MP\ is making a dependency list that will soon
12105 be equated to zero.
12106
12107 Several procedures that act on dependency lists, including |p_plus_fq|,
12108 set the global variable |dep_final| to the final (constant term) node of
12109 the dependency list that they produce.
12110
12111 @d coef_bound 04525252525 /* |fraction| approximation to 7/3 */
12112 @d independent_needing_fix 0
12113
12114 @<Glob...@>=
12115 boolean fix_needed; /* does at least one |independent| variable need scaling? */
12116 boolean watch_coefs; /* should we scale coefficients that exceed |coef_bound|? */
12117 pointer dep_final; /* location of the constant term and final link */
12118
12119 @ @<Set init...@>=
12120 mp->fix_needed=false; mp->watch_coefs=true;
12121
12122 @ The |p_plus_fq| procedure has a fourth parameter, |t|, that should be
12123 set to |mp_proto_dependent| if |p| is a proto-dependency list. In this
12124 case |f| will be |scaled|, not a |fraction|. Similarly, the fifth parameter~|tt|
12125 should be |mp_proto_dependent| if |q| is a proto-dependency list.
12126
12127 List |q| is unchanged by the operation; but list |p| is totally destroyed.
12128
12129 The final link of the dependency list or proto-dependency list returned
12130 by |p_plus_fq| is the same as the original final link of~|p|. Indeed, the
12131 constant term of the result will be located in the same |mem| location
12132 as the original constant term of~|p|.
12133
12134 Coefficients of the result are assumed to be zero if they are less than
12135 a certain threshold. This compensates for inevitable rounding errors,
12136 and tends to make more variables `|known|'. The threshold is approximately
12137 $10^{-5}$ in the case of normal dependency lists, $10^{-4}$ for
12138 proto-dependencies.
12139
12140 @d fraction_threshold 2685 /* a |fraction| coefficient less than this is zeroed */
12141 @d half_fraction_threshold 1342 /* half of |fraction_threshold| */
12142 @d scaled_threshold 8 /* a |scaled| coefficient less than this is zeroed */
12143 @d half_scaled_threshold 4 /* half of |scaled_threshold| */
12144
12145 @<Declare basic dependency-list subroutines@>=
12146 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
12147                       pointer q, small_number t, small_number tt) ;
12148
12149 @ @c
12150 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
12151                       pointer q, small_number t, small_number tt) {
12152   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
12153   pointer r,s; /* for list manipulation */
12154   integer mp_threshold; /* defines a neighborhood of zero */
12155   integer v; /* temporary register */
12156   if ( t==mp_dependent ) mp_threshold=fraction_threshold;
12157   else mp_threshold=scaled_threshold;
12158   r=temp_head; pp=info(p); qq=info(q);
12159   while (1) {
12160     if ( pp==qq ) {
12161       if ( pp==null ) {
12162        break;
12163       } else {
12164         @<Contribute a term from |p|, plus |f| times the
12165           corresponding term from |q|@>
12166       }
12167     } else if ( value(pp)<value(qq) ) {
12168       @<Contribute a term from |q|, multiplied by~|f|@>
12169     } else { 
12170      link(r)=p; r=p; p=link(p); pp=info(p);
12171     }
12172   }
12173   if ( t==mp_dependent )
12174     value(p)=mp_slow_add(mp, value(p),mp_take_fraction(mp, value(q),f));
12175   else  
12176     value(p)=mp_slow_add(mp, value(p),mp_take_scaled(mp, value(q),f));
12177   link(r)=p; mp->dep_final=p; 
12178   return link(temp_head);
12179 }
12180
12181 @ @<Contribute a term from |p|, plus |f|...@>=
12182
12183   if ( tt==mp_dependent ) v=value(p)+mp_take_fraction(mp, f,value(q));
12184   else v=value(p)+mp_take_scaled(mp, f,value(q));
12185   value(p)=v; s=p; p=link(p);
12186   if ( abs(v)<mp_threshold ) {
12187     mp_free_node(mp, s,dep_node_size);
12188   } else {
12189     if ( (abs(v)>=coef_bound)  && mp->watch_coefs ) { 
12190       type(qq)=independent_needing_fix; mp->fix_needed=true;
12191     }
12192     link(r)=s; r=s;
12193   };
12194   pp=info(p); q=link(q); qq=info(q);
12195 }
12196
12197 @ @<Contribute a term from |q|, multiplied by~|f|@>=
12198
12199   if ( tt==mp_dependent ) v=mp_take_fraction(mp, f,value(q));
12200   else v=mp_take_scaled(mp, f,value(q));
12201   if ( abs(v)>halfp(mp_threshold) ) { 
12202     s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=v;
12203     if ( (abs(v)>=coef_bound) && mp->watch_coefs ) { 
12204       type(qq)=independent_needing_fix; mp->fix_needed=true;
12205     }
12206     link(r)=s; r=s;
12207   }
12208   q=link(q); qq=info(q);
12209 }
12210
12211 @ It is convenient to have another subroutine for the special case
12212 of |p_plus_fq| when |f=1.0|. In this routine lists |p| and |q| are
12213 both of the same type~|t| (either |dependent| or |mp_proto_dependent|).
12214
12215 @c pointer mp_p_plus_q (MP mp,pointer p, pointer q, small_number t) {
12216   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
12217   pointer r,s; /* for list manipulation */
12218   integer mp_threshold; /* defines a neighborhood of zero */
12219   integer v; /* temporary register */
12220   if ( t==mp_dependent ) mp_threshold=fraction_threshold;
12221   else mp_threshold=scaled_threshold;
12222   r=temp_head; pp=info(p); qq=info(q);
12223   while (1) {
12224     if ( pp==qq ) {
12225       if ( pp==null ) {
12226         break;
12227       } else {
12228         @<Contribute a term from |p|, plus the
12229           corresponding term from |q|@>
12230       }
12231     } else if ( value(pp)<value(qq) ) {
12232       s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=value(q);
12233       q=link(q); qq=info(q); link(r)=s; r=s;
12234     } else { 
12235       link(r)=p; r=p; p=link(p); pp=info(p);
12236     }
12237   }
12238   value(p)=mp_slow_add(mp, value(p),value(q));
12239   link(r)=p; mp->dep_final=p; 
12240   return link(temp_head);
12241 }
12242
12243 @ @<Contribute a term from |p|, plus the...@>=
12244
12245   v=value(p)+value(q);
12246   value(p)=v; s=p; p=link(p); pp=info(p);
12247   if ( abs(v)<mp_threshold ) {
12248     mp_free_node(mp, s,dep_node_size);
12249   } else { 
12250     if ( (abs(v)>=coef_bound ) && mp->watch_coefs ) {
12251       type(qq)=independent_needing_fix; mp->fix_needed=true;
12252     }
12253     link(r)=s; r=s;
12254   }
12255   q=link(q); qq=info(q);
12256 }
12257
12258 @ A somewhat simpler routine will multiply a dependency list
12259 by a given constant~|v|. The constant is either a |fraction| less than
12260 |fraction_one|, or it is |scaled|. In the latter case we might be forced to
12261 convert a dependency list to a proto-dependency list.
12262 Parameters |t0| and |t1| are the list types before and after;
12263 they should agree unless |t0=mp_dependent| and |t1=mp_proto_dependent|
12264 and |v_is_scaled=true|.
12265
12266 @c pointer mp_p_times_v (MP mp,pointer p, integer v, small_number t0,
12267                          small_number t1, boolean v_is_scaled) {
12268   pointer r,s; /* for list manipulation */
12269   integer w; /* tentative coefficient */
12270   integer mp_threshold;
12271   boolean scaling_down;
12272   if ( t0!=t1 ) scaling_down=true; else scaling_down=! v_is_scaled;
12273   if ( t1==mp_dependent ) mp_threshold=half_fraction_threshold;
12274   else mp_threshold=half_scaled_threshold;
12275   r=temp_head;
12276   while ( info(p)!=null ) {    
12277     if ( scaling_down ) w=mp_take_fraction(mp, v,value(p));
12278     else w=mp_take_scaled(mp, v,value(p));
12279     if ( abs(w)<=mp_threshold ) { 
12280       s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
12281     } else {
12282       if ( abs(w)>=coef_bound ) { 
12283         mp->fix_needed=true; type(info(p))=independent_needing_fix;
12284       }
12285       link(r)=p; r=p; value(p)=w; p=link(p);
12286     }
12287   }
12288   link(r)=p;
12289   if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
12290   else value(p)=mp_take_fraction(mp, value(p),v);
12291   return link(temp_head);
12292 };
12293
12294 @ Similarly, we sometimes need to divide a dependency list
12295 by a given |scaled| constant.
12296
12297 @<Declare basic dependency-list subroutines@>=
12298 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number 
12299   t0, small_number t1) ;
12300
12301 @ @c
12302 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number 
12303   t0, small_number t1) {
12304   pointer r,s; /* for list manipulation */
12305   integer w; /* tentative coefficient */
12306   integer mp_threshold;
12307   boolean scaling_down;
12308   if ( t0!=t1 ) scaling_down=true; else scaling_down=false;
12309   if ( t1==mp_dependent ) mp_threshold=half_fraction_threshold;
12310   else mp_threshold=half_scaled_threshold;
12311   r=temp_head;
12312   while ( info( p)!=null ) {
12313     if ( scaling_down ) {
12314       if ( abs(v)<02000000 ) w=mp_make_scaled(mp, value(p),v*010000);
12315       else w=mp_make_scaled(mp, mp_round_fraction(mp, value(p)),v);
12316     } else {
12317       w=mp_make_scaled(mp, value(p),v);
12318     }
12319     if ( abs(w)<=mp_threshold ) {
12320       s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
12321     } else { 
12322       if ( abs(w)>=coef_bound ) {
12323          mp->fix_needed=true; type(info(p))=independent_needing_fix;
12324       }
12325       link(r)=p; r=p; value(p)=w; p=link(p);
12326     }
12327   }
12328   link(r)=p; value(p)=mp_make_scaled(mp, value(p),v);
12329   return link(temp_head);
12330 };
12331
12332 @ Here's another utility routine for dependency lists. When an independent
12333 variable becomes dependent, we want to remove it from all existing
12334 dependencies. The |p_with_x_becoming_q| function computes the
12335 dependency list of~|p| after variable~|x| has been replaced by~|q|.
12336
12337 This procedure has basically the same calling conventions as |p_plus_fq|:
12338 List~|q| is unchanged; list~|p| is destroyed; the constant node and the
12339 final link are inherited from~|p|; and the fourth parameter tells whether
12340 or not |p| is |mp_proto_dependent|. However, the global variable |dep_final|
12341 is not altered if |x| does not occur in list~|p|.
12342
12343 @c pointer mp_p_with_x_becoming_q (MP mp,pointer p,
12344            pointer x, pointer q, small_number t) {
12345   pointer r,s; /* for list manipulation */
12346   integer v; /* coefficient of |x| */
12347   integer sx; /* serial number of |x| */
12348   s=p; r=temp_head; sx=value(x);
12349   while ( value(info(s))>sx ) { r=s; s=link(s); };
12350   if ( info(s)!=x ) { 
12351     return p;
12352   } else { 
12353     link(temp_head)=p; link(r)=link(s); v=value(s);
12354     mp_free_node(mp, s,dep_node_size);
12355     return mp_p_plus_fq(mp, link(temp_head),v,q,t,mp_dependent);
12356   }
12357 }
12358
12359 @ Here's a simple procedure that reports an error when a variable
12360 has just received a known value that's out of the required range.
12361
12362 @<Declare basic dependency-list subroutines@>=
12363 void mp_val_too_big (MP mp,scaled x) ;
12364
12365 @ @c void mp_val_too_big (MP mp,scaled x) { 
12366   if ( mp->internal[mp_warning_check]>0 ) { 
12367     print_err("Value is too large ("); mp_print_scaled(mp, x); mp_print_char(mp, ')');
12368 @.Value is too large@>
12369     help4("The equation I just processed has given some variable")
12370       ("a value of 4096 or more. Continue and I'll try to cope")
12371       ("with that big value; but it might be dangerous.")
12372       ("(Set warningcheck:=0 to suppress this message.)");
12373     mp_error(mp);
12374   }
12375 }
12376
12377 @ When a dependent variable becomes known, the following routine
12378 removes its dependency list. Here |p| points to the variable, and
12379 |q| points to the dependency list (which is one node long).
12380
12381 @<Declare basic dependency-list subroutines@>=
12382 void mp_make_known (MP mp,pointer p, pointer q) ;
12383
12384 @ @c void mp_make_known (MP mp,pointer p, pointer q) {
12385   int t; /* the previous type */
12386   prev_dep(link(q))=prev_dep(p);
12387   link(prev_dep(p))=link(q); t=type(p);
12388   type(p)=mp_known; value(p)=value(q); mp_free_node(mp, q,dep_node_size);
12389   if ( abs(value(p))>=fraction_one ) mp_val_too_big(mp, value(p));
12390   if (( mp->internal[mp_tracing_equations]>0) && mp_interesting(mp, p) ) {
12391     mp_begin_diagnostic(mp); mp_print_nl(mp, "#### ");
12392 @:]]]\#\#\#\#_}{\.{\#\#\#\#}@>
12393     mp_print_variable_name(mp, p); 
12394     mp_print_char(mp, '='); mp_print_scaled(mp, value(p));
12395     mp_end_diagnostic(mp, false);
12396   }
12397   if (( mp->cur_exp==p ) && mp->cur_type==t ) {
12398     mp->cur_type=mp_known; mp->cur_exp=value(p);
12399     mp_free_node(mp, p,value_node_size);
12400   }
12401 }
12402
12403 @ The |fix_dependencies| routine is called into action when |fix_needed|
12404 has been triggered. The program keeps a list~|s| of independent variables
12405 whose coefficients must be divided by~4.
12406
12407 In unusual cases, this fixup process might reduce one or more coefficients
12408 to zero, so that a variable will become known more or less by default.
12409
12410 @<Declare basic dependency-list subroutines@>=
12411 void mp_fix_dependencies (MP mp);
12412
12413 @ @c void mp_fix_dependencies (MP mp) {
12414   pointer p,q,r,s,t; /* list manipulation registers */
12415   pointer x; /* an independent variable */
12416   r=link(dep_head); s=null;
12417   while ( r!=dep_head ){ 
12418     t=r;
12419     @<Run through the dependency list for variable |t|, fixing
12420       all nodes, and ending with final link~|q|@>;
12421     r=link(q);
12422     if ( q==dep_list(t) ) mp_make_known(mp, t,q);
12423   }
12424   while ( s!=null ) { 
12425     p=link(s); x=info(s); free_avail(s); s=p;
12426     type(x)=mp_independent; value(x)=value(x)+2;
12427   }
12428   mp->fix_needed=false;
12429 }
12430
12431 @ @d independent_being_fixed 1 /* this variable already appears in |s| */
12432
12433 @<Run through the dependency list for variable |t|...@>=
12434 r=value_loc(t); /* |link(r)=dep_list(t)| */
12435 while (1) { 
12436   q=link(r); x=info(q);
12437   if ( x==null ) break;
12438   if ( type(x)<=independent_being_fixed ) {
12439     if ( type(x)<independent_being_fixed ) {
12440       p=mp_get_avail(mp); link(p)=s; s=p;
12441       info(s)=x; type(x)=independent_being_fixed;
12442     }
12443     value(q)=value(q) / 4;
12444     if ( value(q)==0 ) {
12445       link(r)=link(q); mp_free_node(mp, q,dep_node_size); q=r;
12446     }
12447   }
12448   r=q;
12449 }
12450
12451
12452 @ The |new_dep| routine installs a dependency list~|p| into the value node~|q|,
12453 linking it into the list of all known dependencies. We assume that
12454 |dep_final| points to the final node of list~|p|.
12455
12456 @c void mp_new_dep (MP mp,pointer q, pointer p) {
12457   pointer r; /* what used to be the first dependency */
12458   dep_list(q)=p; prev_dep(q)=dep_head;
12459   r=link(dep_head); link(mp->dep_final)=r; prev_dep(r)=mp->dep_final;
12460   link(dep_head)=q;
12461 }
12462
12463 @ Here is one of the ways a dependency list gets started.
12464 The |const_dependency| routine produces a list that has nothing but
12465 a constant term.
12466
12467 @c pointer mp_const_dependency (MP mp, scaled v) {
12468   mp->dep_final=mp_get_node(mp, dep_node_size);
12469   value(mp->dep_final)=v; info(mp->dep_final)=null;
12470   return mp->dep_final;
12471 }
12472
12473 @ And here's a more interesting way to start a dependency list from scratch:
12474 The parameter to |single_dependency| is the location of an
12475 independent variable~|x|, and the result is the simple dependency list
12476 `|x+0|'.
12477
12478 In the unlikely event that the given independent variable has been doubled so
12479 often that we can't refer to it with a nonzero coefficient,
12480 |single_dependency| returns the simple list `0'.  This case can be
12481 recognized by testing that the returned list pointer is equal to
12482 |dep_final|.
12483
12484 @c pointer mp_single_dependency (MP mp,pointer p) {
12485   pointer q; /* the new dependency list */
12486   integer m; /* the number of doublings */
12487   m=value(p) % s_scale;
12488   if ( m>28 ) {
12489     return mp_const_dependency(mp, 0);
12490   } else { 
12491     q=mp_get_node(mp, dep_node_size);
12492     value(q)=two_to_the(28-m); info(q)=p;
12493     link(q)=mp_const_dependency(mp, 0);
12494     return q;
12495   }
12496 }
12497
12498 @ We sometimes need to make an exact copy of a dependency list.
12499
12500 @c pointer mp_copy_dep_list (MP mp,pointer p) {
12501   pointer q; /* the new dependency list */
12502   q=mp_get_node(mp, dep_node_size); mp->dep_final=q;
12503   while (1) { 
12504     info(mp->dep_final)=info(p); value(mp->dep_final)=value(p);
12505     if ( info(mp->dep_final)==null ) break;
12506     link(mp->dep_final)=mp_get_node(mp, dep_node_size);
12507     mp->dep_final=link(mp->dep_final); p=link(p);
12508   }
12509   return q;
12510 }
12511
12512 @ But how do variables normally become known? Ah, now we get to the heart of the
12513 equation-solving mechanism. The |linear_eq| procedure is given a |dependent|
12514 or |mp_proto_dependent| list,~|p|, in which at least one independent variable
12515 appears. It equates this list to zero, by choosing an independent variable
12516 with the largest coefficient and making it dependent on the others. The
12517 newly dependent variable is eliminated from all current dependencies,
12518 thereby possibly making other dependent variables known.
12519
12520 The given list |p| is, of course, totally destroyed by all this processing.
12521
12522 @c void mp_linear_eq (MP mp, pointer p, small_number t) {
12523   pointer q,r,s; /* for link manipulation */
12524   pointer x; /* the variable that loses its independence */
12525   integer n; /* the number of times |x| had been halved */
12526   integer v; /* the coefficient of |x| in list |p| */
12527   pointer prev_r; /* lags one step behind |r| */
12528   pointer final_node; /* the constant term of the new dependency list */
12529   integer w; /* a tentative coefficient */
12530    @<Find a node |q| in list |p| whose coefficient |v| is largest@>;
12531   x=info(q); n=value(x) % s_scale;
12532   @<Divide list |p| by |-v|, removing node |q|@>;
12533   if ( mp->internal[mp_tracing_equations]>0 ) {
12534     @<Display the new dependency@>;
12535   }
12536   @<Simplify all existing dependencies by substituting for |x|@>;
12537   @<Change variable |x| from |independent| to |dependent| or |known|@>;
12538   if ( mp->fix_needed ) mp_fix_dependencies(mp);
12539 }
12540
12541 @ @<Find a node |q| in list |p| whose coefficient |v| is largest@>=
12542 q=p; r=link(p); v=value(q);
12543 while ( info(r)!=null ) { 
12544   if ( abs(value(r))>abs(v) ) { q=r; v=value(r); };
12545   r=link(r);
12546 }
12547
12548 @ Here we want to change the coefficients from |scaled| to |fraction|,
12549 except in the constant term. In the common case of a trivial equation
12550 like `\.{x=3.14}', we will have |v=-fraction_one|, |q=p|, and |t=mp_dependent|.
12551
12552 @<Divide list |p| by |-v|, removing node |q|@>=
12553 s=temp_head; link(s)=p; r=p;
12554 do { 
12555   if ( r==q ) {
12556     link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12557   } else  { 
12558     w=mp_make_fraction(mp, value(r),v);
12559     if ( abs(w)<=half_fraction_threshold ) {
12560       link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12561     } else { 
12562       value(r)=-w; s=r;
12563     }
12564   }
12565   r=link(s);
12566 } while (info(r)!=null);
12567 if ( t==mp_proto_dependent ) {
12568   value(r)=-mp_make_scaled(mp, value(r),v);
12569 } else if ( v!=-fraction_one ) {
12570   value(r)=-mp_make_fraction(mp, value(r),v);
12571 }
12572 final_node=r; p=link(temp_head)
12573
12574 @ @<Display the new dependency@>=
12575 if ( mp_interesting(mp, x) ) {
12576   mp_begin_diagnostic(mp); mp_print_nl(mp, "## "); 
12577   mp_print_variable_name(mp, x);
12578 @:]]]\#\#_}{\.{\#\#}@>
12579   w=n;
12580   while ( w>0 ) { mp_print(mp, "*4"); w=w-2;  };
12581   mp_print_char(mp, '='); mp_print_dependency(mp, p,mp_dependent); 
12582   mp_end_diagnostic(mp, false);
12583 }
12584
12585 @ @<Simplify all existing dependencies by substituting for |x|@>=
12586 prev_r=dep_head; r=link(dep_head);
12587 while ( r!=dep_head ) {
12588   s=dep_list(r); q=mp_p_with_x_becoming_q(mp, s,x,p,type(r));
12589   if ( info(q)==null ) {
12590     mp_make_known(mp, r,q);
12591   } else { 
12592     dep_list(r)=q;
12593     do {  q=link(q); } while (info(q)!=null);
12594     prev_r=q;
12595   }
12596   r=link(prev_r);
12597 }
12598
12599 @ @<Change variable |x| from |independent| to |dependent| or |known|@>=
12600 if ( n>0 ) @<Divide list |p| by $2^n$@>;
12601 if ( info(p)==null ) {
12602   type(x)=mp_known;
12603   value(x)=value(p);
12604   if ( abs(value(x))>=fraction_one ) mp_val_too_big(mp, value(x));
12605   mp_free_node(mp, p,dep_node_size);
12606   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) {
12607     mp->cur_exp=value(x); mp->cur_type=mp_known;
12608     mp_free_node(mp, x,value_node_size);
12609   }
12610 } else { 
12611   type(x)=mp_dependent; mp->dep_final=final_node; mp_new_dep(mp, x,p);
12612   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) mp->cur_type=mp_dependent;
12613 }
12614
12615 @ @<Divide list |p| by $2^n$@>=
12616
12617   s=temp_head; link(temp_head)=p; r=p;
12618   do {  
12619     if ( n>30 ) w=0;
12620     else w=value(r) / two_to_the(n);
12621     if ( (abs(w)<=half_fraction_threshold)&&(info(r)!=null) ) {
12622       link(s)=link(r);
12623       mp_free_node(mp, r,dep_node_size);
12624     } else { 
12625       value(r)=w; s=r;
12626     }
12627     r=link(s);
12628   } while (info(s)!=null);
12629   p=link(temp_head);
12630 }
12631
12632 @ The |check_mem| procedure, which is used only when \MP\ is being
12633 debugged, makes sure that the current dependency lists are well formed.
12634
12635 @<Check the list of linear dependencies@>=
12636 q=dep_head; p=link(q);
12637 while ( p!=dep_head ) {
12638   if ( prev_dep(p)!=q ) {
12639     mp_print_nl(mp, "Bad PREVDEP at "); mp_print_int(mp, p);
12640 @.Bad PREVDEP...@>
12641   }
12642   p=dep_list(p);
12643   while (1) {
12644     r=info(p); q=p; p=link(q);
12645     if ( r==null ) break;
12646     if ( value(info(p))>=value(r) ) {
12647       mp_print_nl(mp, "Out of order at "); mp_print_int(mp, p);
12648 @.Out of order...@>
12649     }
12650   }
12651 }
12652
12653 @* \[25] Dynamic nonlinear equations.
12654 Variables of numeric type are maintained by the general scheme of
12655 independent, dependent, and known values that we have just studied;
12656 and the components of pair and transform variables are handled in the
12657 same way. But \MP\ also has five other types of values: \&{boolean},
12658 \&{string}, \&{pen}, \&{path}, and \&{picture}; what about them?
12659
12660 Equations are allowed between nonlinear quantities, but only in a
12661 simple form. Two variables that haven't yet been assigned values are
12662 either equal to each other, or they're not.
12663
12664 Before a boolean variable has received a value, its type is |mp_unknown_boolean|;
12665 similarly, there are variables whose type is |mp_unknown_string|, |mp_unknown_pen|,
12666 |mp_unknown_path|, and |mp_unknown_picture|. In such cases the value is either
12667 |null| (which means that no other variables are equivalent to this one), or
12668 it points to another variable of the same undefined type. The pointers in the
12669 latter case form a cycle of nodes, which we shall call a ``ring.''
12670 Rings of undefined variables may include capsules, which arise as
12671 intermediate results within expressions or as \&{expr} parameters to macros.
12672
12673 When one member of a ring receives a value, the same value is given to
12674 all the other members. In the case of paths and pictures, this implies
12675 making separate copies of a potentially large data structure; users should
12676 restrain their enthusiasm for such generality, unless they have lots and
12677 lots of memory space.
12678
12679 @ The following procedure is called when a capsule node is being
12680 added to a ring (e.g., when an unknown variable is mentioned in an expression).
12681
12682 @c pointer mp_new_ring_entry (MP mp,pointer p) {
12683   pointer q; /* the new capsule node */
12684   q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
12685   type(q)=type(p);
12686   if ( value(p)==null ) value(q)=p; else value(q)=value(p);
12687   value(p)=q;
12688   return q;
12689 }
12690
12691 @ Conversely, we might delete a capsule or a variable before it becomes known.
12692 The following procedure simply detaches a quantity from its ring,
12693 without recycling the storage.
12694
12695 @<Declare the recycling subroutines@>=
12696 void mp_ring_delete (MP mp,pointer p) {
12697   pointer q; 
12698   q=value(p);
12699   if ( q!=null ) if ( q!=p ){ 
12700     while ( value(q)!=p ) q=value(q);
12701     value(q)=value(p);
12702   }
12703 }
12704
12705 @ Eventually there might be an equation that assigns values to all of the
12706 variables in a ring. The |nonlinear_eq| subroutine does the necessary
12707 propagation of values.
12708
12709 If the parameter |flush_p| is |true|, node |p| itself needn't receive a
12710 value, it will soon be recycled.
12711
12712 @c void mp_nonlinear_eq (MP mp,integer v, pointer p, boolean flush_p) {
12713   small_number t; /* the type of ring |p| */
12714   pointer q,r; /* link manipulation registers */
12715   t=type(p)-unknown_tag; q=value(p);
12716   if ( flush_p ) type(p)=mp_vacuous; else p=q;
12717   do {  
12718     r=value(q); type(q)=t;
12719     switch (t) {
12720     case mp_boolean_type: value(q)=v; break;
12721     case mp_string_type: value(q)=v; add_str_ref(v); break;
12722     case mp_pen_type: value(q)=copy_pen(v); break;
12723     case mp_path_type: value(q)=mp_copy_path(mp, v); break;
12724     case mp_picture_type: value(q)=v; add_edge_ref(v); break;
12725     } /* there ain't no more cases */
12726     q=r;
12727   } while (q!=p);
12728 }
12729
12730 @ If two members of rings are equated, and if they have the same type,
12731 the |ring_merge| procedure is called on to make them equivalent.
12732
12733 @c void mp_ring_merge (MP mp,pointer p, pointer q) {
12734   pointer r; /* traverses one list */
12735   r=value(p);
12736   while ( r!=p ) {
12737     if ( r==q ) {
12738       @<Exclaim about a redundant equation@>;
12739       return;
12740     };
12741     r=value(r);
12742   }
12743   r=value(p); value(p)=value(q); value(q)=r;
12744 }
12745
12746 @ @<Exclaim about a redundant equation@>=
12747
12748   print_err("Redundant equation");
12749 @.Redundant equation@>
12750   help2("I already knew that this equation was true.")
12751    ("But perhaps no harm has been done; let's continue.");
12752   mp_put_get_error(mp);
12753 }
12754
12755 @* \[26] Introduction to the syntactic routines.
12756 Let's pause a moment now and try to look at the Big Picture.
12757 The \MP\ program consists of three main parts: syntactic routines,
12758 semantic routines, and output routines. The chief purpose of the
12759 syntactic routines is to deliver the user's input to the semantic routines,
12760 while parsing expressions and locating operators and operands. The
12761 semantic routines act as an interpreter responding to these operators,
12762 which may be regarded as commands. And the output routines are
12763 periodically called on to produce compact font descriptions that can be
12764 used for typesetting or for making interim proof drawings. We have
12765 discussed the basic data structures and many of the details of semantic
12766 operations, so we are good and ready to plunge into the part of \MP\ that
12767 actually controls the activities.
12768
12769 Our current goal is to come to grips with the |get_next| procedure,
12770 which is the keystone of \MP's input mechanism. Each call of |get_next|
12771 sets the value of three variables |cur_cmd|, |cur_mod|, and |cur_sym|,
12772 representing the next input token.
12773 $$\vbox{\halign{#\hfil\cr
12774   \hbox{|cur_cmd| denotes a command code from the long list of codes
12775    given earlier;}\cr
12776   \hbox{|cur_mod| denotes a modifier of the command code;}\cr
12777   \hbox{|cur_sym| is the hash address of the symbolic token that was
12778    just scanned,}\cr
12779   \hbox{\qquad or zero in the case of a numeric or string
12780    or capsule token.}\cr}}$$
12781 Underlying this external behavior of |get_next| is all the machinery
12782 necessary to convert from character files to tokens. At a given time we
12783 may be only partially finished with the reading of several files (for
12784 which \&{input} was specified), and partially finished with the expansion
12785 of some user-defined macros and/or some macro parameters, and partially
12786 finished reading some text that the user has inserted online,
12787 and so on. When reading a character file, the characters must be
12788 converted to tokens; comments and blank spaces must
12789 be removed, numeric and string tokens must be evaluated.
12790
12791 To handle these situations, which might all be present simultaneously,
12792 \MP\ uses various stacks that hold information about the incomplete
12793 activities, and there is a finite state control for each level of the
12794 input mechanism. These stacks record the current state of an implicitly
12795 recursive process, but the |get_next| procedure is not recursive.
12796
12797 @<Glob...@>=
12798 eight_bits cur_cmd; /* current command set by |get_next| */
12799 integer cur_mod; /* operand of current command */
12800 halfword cur_sym; /* hash address of current symbol */
12801
12802 @ The |print_cmd_mod| routine prints a symbolic interpretation of a
12803 command code and its modifier.
12804 It consists of a rather tedious sequence of print
12805 commands, and most of it is essentially an inverse to the |primitive|
12806 routine that enters a \MP\ primitive into |hash| and |eqtb|. Therefore almost
12807 all of this procedure appears elsewhere in the program, together with the
12808 corresponding |primitive| calls.
12809
12810 @<Declare the procedure called |print_cmd_mod|@>=
12811 void mp_print_cmd_mod (MP mp,integer c, integer m) { 
12812  switch (c) {
12813   @<Cases of |print_cmd_mod| for symbolic printing of primitives@>
12814   default: mp_print(mp, "[unknown command code!]"); break;
12815   }
12816 }
12817
12818 @ Here is a procedure that displays a given command in braces, in the
12819 user's transcript file.
12820
12821 @d show_cur_cmd_mod mp_show_cmd_mod(mp, mp->cur_cmd,mp->cur_mod)
12822
12823 @c 
12824 void mp_show_cmd_mod (MP mp,integer c, integer m) { 
12825   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
12826   mp_print_cmd_mod(mp, c,m); mp_print_char(mp, '}');
12827   mp_end_diagnostic(mp, false);
12828 }
12829
12830 @* \[27] Input stacks and states.
12831 The state of \MP's input mechanism appears in the input stack, whose
12832 entries are records with five fields, called |index|, |start|, |loc|,
12833 |limit|, and |name|. The top element of this stack is maintained in a
12834 global variable for which no subscripting needs to be done; the other
12835 elements of the stack appear in an array. Hence the stack is declared thus:
12836
12837 @<Types...@>=
12838 typedef struct {
12839   quarterword index_field;
12840   halfword start_field, loc_field, limit_field, name_field;
12841 } in_state_record;
12842
12843 @ @<Glob...@>=
12844 in_state_record *input_stack;
12845 integer input_ptr; /* first unused location of |input_stack| */
12846 integer max_in_stack; /* largest value of |input_ptr| when pushing */
12847 in_state_record cur_input; /* the ``top'' input state */
12848 int stack_size; /* maximum number of simultaneous input sources */
12849
12850 @ @<Allocate or initialize ...@>=
12851 mp->stack_size = 300;
12852 mp->input_stack = xmalloc((mp->stack_size+1),sizeof(in_state_record));
12853
12854 @ @<Dealloc variables@>=
12855 xfree(mp->input_stack);
12856
12857 @ We've already defined the special variable |loc==cur_input.loc_field|
12858 in our discussion of basic input-output routines. The other components of
12859 |cur_input| are defined in the same way:
12860
12861 @d index mp->cur_input.index_field /* reference for buffer information */
12862 @d start mp->cur_input.start_field /* starting position in |buffer| */
12863 @d limit mp->cur_input.limit_field /* end of current line in |buffer| */
12864 @d name mp->cur_input.name_field /* name of the current file */
12865
12866 @ Let's look more closely now at the five control variables
12867 (|index|,~|start|,~|loc|,~|limit|,~|name|),
12868 assuming that \MP\ is reading a line of characters that have been input
12869 from some file or from the user's terminal. There is an array called
12870 |buffer| that acts as a stack of all lines of characters that are
12871 currently being read from files, including all lines on subsidiary
12872 levels of the input stack that are not yet completed. \MP\ will return to
12873 the other lines when it is finished with the present input file.
12874
12875 (Incidentally, on a machine with byte-oriented addressing, it would be
12876 appropriate to combine |buffer| with the |str_pool| array,
12877 letting the buffer entries grow downward from the top of the string pool
12878 and checking that these two tables don't bump into each other.)
12879
12880 The line we are currently working on begins in position |start| of the
12881 buffer; the next character we are about to read is |buffer[loc]|; and
12882 |limit| is the location of the last character present. We always have
12883 |loc<=limit|. For convenience, |buffer[limit]| has been set to |"%"|, so
12884 that the end of a line is easily sensed.
12885
12886 The |name| variable is a string number that designates the name of
12887 the current file, if we are reading an ordinary text file.  Special codes
12888 |is_term..max_spec_src| indicate other sources of input text.
12889
12890 @d is_term 0 /* |name| value when reading from the terminal for normal input */
12891 @d is_read 1 /* |name| value when executing a \&{readstring} or \&{readfrom} */
12892 @d is_scantok 2 /* |name| value when reading text generated by \&{scantokens} */
12893 @d max_spec_src is_scantok
12894
12895 @ Additional information about the current line is available via the
12896 |index| variable, which counts how many lines of characters are present
12897 in the buffer below the current level. We have |index=0| when reading
12898 from the terminal and prompting the user for each line; then if the user types,
12899 e.g., `\.{input figs}', we will have |index=1| while reading
12900 the file \.{figs.mp}. However, it does not follow that |index| is the
12901 same as the input stack pointer, since many of the levels on the input
12902 stack may come from token lists and some |index| values may correspond
12903 to \.{MPX} files that are not currently on the stack.
12904
12905 The global variable |in_open| is equal to the highest |index| value counting
12906 \.{MPX} files but excluding token-list input levels.  Thus, the number of
12907 partially read lines in the buffer is |in_open+1| and we have |in_open>=index|
12908 when we are not reading a token list.
12909
12910 If we are not currently reading from the terminal,
12911 we are reading from the file variable |input_file[index]|. We use
12912 the notation |terminal_input| as a convenient abbreviation for |name=is_term|,
12913 and |cur_file| as an abbreviation for |input_file[index]|.
12914
12915 When \MP\ is not reading from the terminal, the global variable |line| contains
12916 the line number in the current file, for use in error messages. More precisely,
12917 |line| is a macro for |line_stack[index]| and the |line_stack| array gives
12918 the line number for each file in the |input_file| array.
12919
12920 When an \.{MPX} file is opened the file name is stored in the |mpx_name|
12921 array so that the name doesn't get lost when the file is temporarily removed
12922 from the input stack.
12923 Thus when |input_file[k]| is an \.{MPX} file, its name is |mpx_name[k]|
12924 and it contains translated \TeX\ pictures for |input_file[k-1]|.
12925 Since this is not an \.{MPX} file, we have
12926 $$ \hbox{|mpx_name[k-1]<=absent|}. $$
12927 This |name| field is set to |finished| when |input_file[k]| is completely
12928 read.
12929
12930 If more information about the input state is needed, it can be
12931 included in small arrays like those shown here. For example,
12932 the current page or segment number in the input file might be put
12933 into a variable |page|, that is really a macro for the current entry
12934 in `\ignorespaces|page_stack:array[0..max_in_open] of integer|\unskip'
12935 by analogy with |line_stack|.
12936 @^system dependencies@>
12937
12938 @d terminal_input (name==is_term) /* are we reading from the terminal? */
12939 @d cur_file mp->input_file[index] /* the current |void *| variable */
12940 @d line mp->line_stack[index] /* current line number in the current source file */
12941 @d in_name mp->iname_stack[index] /* a string used to construct \.{MPX} file names */
12942 @d in_area mp->iarea_stack[index] /* another string for naming \.{MPX} files */
12943 @d absent 1 /* |name_field| value for unused |mpx_in_stack| entries */
12944 @d mpx_reading (mp->mpx_name[index]>absent)
12945   /* when reading a file, is it an \.{MPX} file? */
12946 @d finished 0
12947   /* |name_field| value when the corresponding \.{MPX} file is finished */
12948
12949 @<Glob...@>=
12950 integer in_open; /* the number of lines in the buffer, less one */
12951 unsigned int open_parens; /* the number of open text files */
12952 void  * *input_file ;
12953 integer *line_stack ; /* the line number for each file */
12954 char *  *iname_stack; /* used for naming \.{MPX} files */
12955 char *  *iarea_stack; /* used for naming \.{MPX} files */
12956 halfword*mpx_name  ;
12957
12958 @ @<Allocate or ...@>=
12959 mp->input_file  = xmalloc((mp->max_in_open+1),sizeof(void *));
12960 mp->line_stack  = xmalloc((mp->max_in_open+1),sizeof(integer));
12961 mp->iname_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12962 mp->iarea_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12963 mp->mpx_name    = xmalloc((mp->max_in_open+1),sizeof(halfword));
12964 {
12965   int k;
12966   for (k=0;k<=mp->max_in_open;k++) {
12967     mp->iname_stack[k] =NULL;
12968     mp->iarea_stack[k] =NULL;
12969   }
12970 }
12971
12972 @ @<Dealloc variables@>=
12973 {
12974   int l;
12975   for (l=0;l<=mp->max_in_open;l++) {
12976     xfree(mp->iname_stack[l]);
12977     xfree(mp->iarea_stack[l]);
12978   }
12979 }
12980 xfree(mp->input_file);
12981 xfree(mp->line_stack);
12982 xfree(mp->iname_stack);
12983 xfree(mp->iarea_stack);
12984 xfree(mp->mpx_name);
12985
12986
12987 @ However, all this discussion about input state really applies only to the
12988 case that we are inputting from a file. There is another important case,
12989 namely when we are currently getting input from a token list. In this case
12990 |index>max_in_open|, and the conventions about the other state variables
12991 are different:
12992
12993 \yskip\hang|loc| is a pointer to the current node in the token list, i.e.,
12994 the node that will be read next. If |loc=null|, the token list has been
12995 fully read.
12996
12997 \yskip\hang|start| points to the first node of the token list; this node
12998 may or may not contain a reference count, depending on the type of token
12999 list involved.
13000
13001 \yskip\hang|token_type|, which takes the place of |index| in the
13002 discussion above, is a code number that explains what kind of token list
13003 is being scanned.
13004
13005 \yskip\hang|name| points to the |eqtb| address of the control sequence
13006 being expanded, if the current token list is a macro not defined by
13007 \&{vardef}. Macros defined by \&{vardef} have |name=null|; their name
13008 can be deduced by looking at their first two parameters.
13009
13010 \yskip\hang|param_start|, which takes the place of |limit|, tells where
13011 the parameters of the current macro or loop text begin in the |param_stack|.
13012
13013 \yskip\noindent The |token_type| can take several values, depending on
13014 where the current token list came from:
13015
13016 \yskip
13017 \indent|forever_text|, if the token list being scanned is the body of
13018 a \&{forever} loop;
13019
13020 \indent|loop_text|, if the token list being scanned is the body of
13021 a \&{for} or \&{forsuffixes} loop;
13022
13023 \indent|parameter|, if a \&{text} or \&{suffix} parameter is being scanned;
13024
13025 \indent|backed_up|, if the token list being scanned has been inserted as
13026 `to be read again'.
13027
13028 \indent|inserted|, if the token list being scanned has been inserted as
13029 part of error recovery;
13030
13031 \indent|macro|, if the expansion of a user-defined symbolic token is being
13032 scanned.
13033
13034 \yskip\noindent
13035 The token list begins with a reference count if and only if |token_type=
13036 macro|.
13037 @^reference counts@>
13038
13039 @d token_type index /* type of current token list */
13040 @d token_state (index>(int)mp->max_in_open) /* are we scanning a token list? */
13041 @d file_state (index<=(int)mp->max_in_open) /* are we scanning a file line? */
13042 @d param_start limit /* base of macro parameters in |param_stack| */
13043 @d forever_text (mp->max_in_open+1) /* |token_type| code for loop texts */
13044 @d loop_text (mp->max_in_open+2) /* |token_type| code for loop texts */
13045 @d parameter (mp->max_in_open+3) /* |token_type| code for parameter texts */
13046 @d backed_up (mp->max_in_open+4) /* |token_type| code for texts to be reread */
13047 @d inserted (mp->max_in_open+5) /* |token_type| code for inserted texts */
13048 @d macro (mp->max_in_open+6) /* |token_type| code for macro replacement texts */
13049
13050 @ The |param_stack| is an auxiliary array used to hold pointers to the token
13051 lists for parameters at the current level and subsidiary levels of input.
13052 This stack grows at a different rate from the others.
13053
13054 @<Glob...@>=
13055 pointer *param_stack;  /* token list pointers for parameters */
13056 integer param_ptr; /* first unused entry in |param_stack| */
13057 integer max_param_stack;  /* largest value of |param_ptr| */
13058
13059 @ @<Allocate or initialize ...@>=
13060 mp->param_stack = xmalloc((mp->param_size+1),sizeof(pointer));
13061
13062 @ @<Dealloc variables@>=
13063 xfree(mp->param_stack);
13064
13065 @ Notice that the |line| isn't valid when |token_state| is true because it
13066 depends on |index|.  If we really need to know the line number for the
13067 topmost file in the index stack we use the following function.  If a page
13068 number or other information is needed, this routine should be modified to
13069 compute it as well.
13070 @^system dependencies@>
13071
13072 @<Declare a function called |true_line|@>=
13073 integer mp_true_line (MP mp) {
13074   int k; /* an index into the input stack */
13075   if ( file_state && (name>max_spec_src) ) {
13076      return line;
13077   } else { 
13078     k=mp->input_ptr;
13079     while ((k>0) &&
13080            ((mp->input_stack[(k-1)].index_field>mp->max_in_open)||
13081             (mp->input_stack[(k-1)].name_field<=max_spec_src))) {
13082       decr(k);
13083     }
13084     return mp->line_stack[(k-1)];
13085   }
13086   return 0; 
13087 }
13088
13089 @ Thus, the ``current input state'' can be very complicated indeed; there
13090 can be many levels and each level can arise in a variety of ways. The
13091 |show_context| procedure, which is used by \MP's error-reporting routine to
13092 print out the current input state on all levels down to the most recent
13093 line of characters from an input file, illustrates most of these conventions.
13094 The global variable |file_ptr| contains the lowest level that was
13095 displayed by this procedure.
13096
13097 @<Glob...@>=
13098 integer file_ptr; /* shallowest level shown by |show_context| */
13099
13100 @ The status at each level is indicated by printing two lines, where the first
13101 line indicates what was read so far and the second line shows what remains
13102 to be read. The context is cropped, if necessary, so that the first line
13103 contains at most |half_error_line| characters, and the second contains
13104 at most |error_line|. Non-current input levels whose |token_type| is
13105 `|backed_up|' are shown only if they have not been fully read.
13106
13107 @c void mp_show_context (MP mp) { /* prints where the scanner is */
13108   int old_setting; /* saved |selector| setting */
13109   @<Local variables for formatting calculations@>
13110   mp->file_ptr=mp->input_ptr; mp->input_stack[mp->file_ptr]=mp->cur_input;
13111   /* store current state */
13112   while (1) { 
13113     mp->cur_input=mp->input_stack[mp->file_ptr]; /* enter into the context */
13114     @<Display the current context@>;
13115     if ( file_state )
13116       if ( (name>max_spec_src) || (mp->file_ptr==0) ) break;
13117     decr(mp->file_ptr);
13118   }
13119   mp->cur_input=mp->input_stack[mp->input_ptr]; /* restore original state */
13120 }
13121
13122 @ @<Display the current context@>=
13123 if ( (mp->file_ptr==mp->input_ptr) || file_state ||
13124    (token_type!=backed_up) || (loc!=null) ) {
13125     /* we omit backed-up token lists that have already been read */
13126   mp->tally=0; /* get ready to count characters */
13127   old_setting=mp->selector;
13128   if ( file_state ) {
13129     @<Print location of current line@>;
13130     @<Pseudoprint the line@>;
13131   } else { 
13132     @<Print type of token list@>;
13133     @<Pseudoprint the token list@>;
13134   }
13135   mp->selector=old_setting; /* stop pseudoprinting */
13136   @<Print two lines using the tricky pseudoprinted information@>;
13137 }
13138
13139 @ This routine should be changed, if necessary, to give the best possible
13140 indication of where the current line resides in the input file.
13141 For example, on some systems it is best to print both a page and line number.
13142 @^system dependencies@>
13143
13144 @<Print location of current line@>=
13145 if ( name>max_spec_src ) {
13146   mp_print_nl(mp, "l."); mp_print_int(mp, mp_true_line(mp));
13147 } else if ( terminal_input ) {
13148   if ( mp->file_ptr==0 ) mp_print_nl(mp, "<*>");
13149   else mp_print_nl(mp, "<insert>");
13150 } else if ( name==is_scantok ) {
13151   mp_print_nl(mp, "<scantokens>");
13152 } else {
13153   mp_print_nl(mp, "<read>");
13154 }
13155 mp_print_char(mp, ' ')
13156
13157 @ Can't use case statement here because the |token_type| is not
13158 a constant expression.
13159
13160 @<Print type of token list@>=
13161 {
13162   if(token_type==forever_text) {
13163     mp_print_nl(mp, "<forever> ");
13164   } else if (token_type==loop_text) {
13165     @<Print the current loop value@>;
13166   } else if (token_type==parameter) {
13167     mp_print_nl(mp, "<argument> "); 
13168   } else if (token_type==backed_up) { 
13169     if ( loc==null ) mp_print_nl(mp, "<recently read> ");
13170     else mp_print_nl(mp, "<to be read again> ");
13171   } else if (token_type==inserted) {
13172     mp_print_nl(mp, "<inserted text> ");
13173   } else if (token_type==macro) {
13174     mp_print_ln(mp);
13175     if ( name!=null ) mp_print_text(name);
13176     else @<Print the name of a \&{vardef}'d macro@>;
13177     mp_print(mp, "->");
13178   } else {
13179     mp_print_nl(mp, "?");/* this should never happen */
13180 @.?\relax@>
13181   }
13182 }
13183
13184 @ The parameter that corresponds to a loop text is either a token list
13185 (in the case of \&{forsuffixes}) or a ``capsule'' (in the case of \&{for}).
13186 We'll discuss capsules later; for now, all we need to know is that
13187 the |link| field in a capsule parameter is |void| and that
13188 |print_exp(p,0)| displays the value of capsule~|p| in abbreviated form.
13189
13190 @<Print the current loop value@>=
13191 { mp_print_nl(mp, "<for("); p=mp->param_stack[param_start];
13192   if ( p!=null ) {
13193     if ( link(p)==mp_void ) mp_print_exp(mp, p,0); /* we're in a \&{for} loop */
13194     else mp_show_token_list(mp, p,null,20,mp->tally);
13195   }
13196   mp_print(mp, ")> ");
13197 }
13198
13199 @ The first two parameters of a macro defined by \&{vardef} will be token
13200 lists representing the macro's prefix and ``at point.'' By putting these
13201 together, we get the macro's full name.
13202
13203 @<Print the name of a \&{vardef}'d macro@>=
13204 { p=mp->param_stack[param_start];
13205   if ( p==null ) {
13206     mp_show_token_list(mp, mp->param_stack[param_start+1],null,20,mp->tally);
13207   } else { 
13208     q=p;
13209     while ( link(q)!=null ) q=link(q);
13210     link(q)=mp->param_stack[param_start+1];
13211     mp_show_token_list(mp, p,null,20,mp->tally);
13212     link(q)=null;
13213   }
13214 }
13215
13216 @ Now it is necessary to explain a little trick. We don't want to store a long
13217 string that corresponds to a token list, because that string might take up
13218 lots of memory; and we are printing during a time when an error message is
13219 being given, so we dare not do anything that might overflow one of \MP's
13220 tables. So `pseudoprinting' is the answer: We enter a mode of printing
13221 that stores characters into a buffer of length |error_line|, where character
13222 $k+1$ is placed into \hbox{|trick_buf[k mod error_line]|} if
13223 |k<trick_count|, otherwise character |k| is dropped. Initially we set
13224 |tally:=0| and |trick_count:=1000000|; then when we reach the
13225 point where transition from line 1 to line 2 should occur, we
13226 set |first_count:=tally| and |trick_count:=@tmax@>(error_line,
13227 tally+1+error_line-half_error_line)|. At the end of the
13228 pseudoprinting, the values of |first_count|, |tally|, and
13229 |trick_count| give us all the information we need to print the two lines,
13230 and all of the necessary text is in |trick_buf|.
13231
13232 Namely, let |l| be the length of the descriptive information that appears
13233 on the first line. The length of the context information gathered for that
13234 line is |k=first_count|, and the length of the context information
13235 gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k<=h|,
13236 where |h=half_error_line|, we print |trick_buf[0..k-1]| after the
13237 descriptive information on line~1, and set |n:=l+k|; here |n| is the
13238 length of line~1. If $l+k>h$, some cropping is necessary, so we set |n:=h|
13239 and print `\.{...}' followed by
13240 $$\hbox{|trick_buf[(l+k-h+3)..k-1]|,}$$
13241 where subscripts of |trick_buf| are circular modulo |error_line|. The
13242 second line consists of |n|~spaces followed by |trick_buf[k..(k+m-1)]|,
13243 unless |n+m>error_line|; in the latter case, further cropping is done.
13244 This is easier to program than to explain.
13245
13246 @<Local variables for formatting...@>=
13247 int i; /* index into |buffer| */
13248 integer l; /* length of descriptive information on line 1 */
13249 integer m; /* context information gathered for line 2 */
13250 int n; /* length of line 1 */
13251 integer p; /* starting or ending place in |trick_buf| */
13252 integer q; /* temporary index */
13253
13254 @ The following code tells the print routines to gather
13255 the desired information.
13256
13257 @d begin_pseudoprint { 
13258   l=mp->tally; mp->tally=0; mp->selector=pseudo;
13259   mp->trick_count=1000000;
13260 }
13261 @d set_trick_count {
13262   mp->first_count=mp->tally;
13263   mp->trick_count=mp->tally+1+mp->error_line-mp->half_error_line;
13264   if ( mp->trick_count<mp->error_line ) mp->trick_count=mp->error_line;
13265 }
13266
13267 @ And the following code uses the information after it has been gathered.
13268
13269 @<Print two lines using the tricky pseudoprinted information@>=
13270 if ( mp->trick_count==1000000 ) set_trick_count;
13271   /* |set_trick_count| must be performed */
13272 if ( mp->tally<mp->trick_count ) m=mp->tally-mp->first_count;
13273 else m=mp->trick_count-mp->first_count; /* context on line 2 */
13274 if ( l+mp->first_count<=mp->half_error_line ) {
13275   p=0; n=l+mp->first_count;
13276 } else  { 
13277   mp_print(mp, "..."); p=l+mp->first_count-mp->half_error_line+3;
13278   n=mp->half_error_line;
13279 }
13280 for (q=p;q<=mp->first_count-1;q++) {
13281   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13282 }
13283 mp_print_ln(mp);
13284 for (q=1;q<=n;q++) {
13285   mp_print_char(mp, ' '); /* print |n| spaces to begin line~2 */
13286 }
13287 if ( m+n<=mp->error_line ) p=mp->first_count+m; 
13288 else p=mp->first_count+(mp->error_line-n-3);
13289 for (q=mp->first_count;q<=p-1;q++) {
13290   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13291 }
13292 if ( m+n>mp->error_line ) mp_print(mp, "...")
13293
13294 @ But the trick is distracting us from our current goal, which is to
13295 understand the input state. So let's concentrate on the data structures that
13296 are being pseudoprinted as we finish up the |show_context| procedure.
13297
13298 @<Pseudoprint the line@>=
13299 begin_pseudoprint;
13300 if ( limit>0 ) {
13301   for (i=start;i<=limit-1;i++) {
13302     if ( i==loc ) set_trick_count;
13303     mp_print_str(mp, mp->buffer[i]);
13304   }
13305 }
13306
13307 @ @<Pseudoprint the token list@>=
13308 begin_pseudoprint;
13309 if ( token_type!=macro ) mp_show_token_list(mp, start,loc,100000,0);
13310 else mp_show_macro(mp, start,loc,100000)
13311
13312 @ Here is the missing piece of |show_token_list| that is activated when the
13313 token beginning line~2 is about to be shown:
13314
13315 @<Do magic computation@>=set_trick_count
13316
13317 @* \[28] Maintaining the input stacks.
13318 The following subroutines change the input status in commonly needed ways.
13319
13320 First comes |push_input|, which stores the current state and creates a
13321 new level (having, initially, the same properties as the old).
13322
13323 @d push_input  { /* enter a new input level, save the old */
13324   if ( mp->input_ptr>mp->max_in_stack ) {
13325     mp->max_in_stack=mp->input_ptr;
13326     if ( mp->input_ptr==mp->stack_size ) {
13327       int l = (mp->stack_size+(mp->stack_size>>2));
13328       XREALLOC(mp->input_stack, l, in_state_record);
13329       mp->stack_size = l;
13330     }         
13331   }
13332   mp->input_stack[mp->input_ptr]=mp->cur_input; /* stack the record */
13333   incr(mp->input_ptr);
13334 }
13335
13336 @ And of course what goes up must come down.
13337
13338 @d pop_input { /* leave an input level, re-enter the old */
13339     decr(mp->input_ptr); mp->cur_input=mp->input_stack[mp->input_ptr];
13340   }
13341
13342 @ Here is a procedure that starts a new level of token-list input, given
13343 a token list |p| and its type |t|. If |t=macro|, the calling routine should
13344 set |name|, reset~|loc|, and increase the macro's reference count.
13345
13346 @d back_list(A) mp_begin_token_list(mp, (A),backed_up) /* backs up a simple token list */
13347
13348 @c void mp_begin_token_list (MP mp,pointer p, quarterword t)  { 
13349   push_input; start=p; token_type=t;
13350   param_start=mp->param_ptr; loc=p;
13351 }
13352
13353 @ When a token list has been fully scanned, the following computations
13354 should be done as we leave that level of input.
13355 @^inner loop@>
13356
13357 @c void mp_end_token_list (MP mp) { /* leave a token-list input level */
13358   pointer p; /* temporary register */
13359   if ( token_type>=backed_up ) { /* token list to be deleted */
13360     if ( token_type<=inserted ) { 
13361       mp_flush_token_list(mp, start); goto DONE;
13362     } else {
13363       mp_delete_mac_ref(mp, start); /* update reference count */
13364     }
13365   }
13366   while ( mp->param_ptr>param_start ) { /* parameters must be flushed */
13367     decr(mp->param_ptr);
13368     p=mp->param_stack[mp->param_ptr];
13369     if ( p!=null ) {
13370       if ( link(p)==mp_void ) { /* it's an \&{expr} parameter */
13371         mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
13372       } else {
13373         mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
13374       }
13375     }
13376   }
13377 DONE: 
13378   pop_input; check_interrupt;
13379 }
13380
13381 @ The contents of |cur_cmd,cur_mod,cur_sym| are placed into an equivalent
13382 token by the |cur_tok| routine.
13383 @^inner loop@>
13384
13385 @c @<Declare the procedure called |make_exp_copy|@>;
13386 pointer mp_cur_tok (MP mp) {
13387   pointer p; /* a new token node */
13388   small_number save_type; /* |cur_type| to be restored */
13389   integer save_exp; /* |cur_exp| to be restored */
13390   if ( mp->cur_sym==0 ) {
13391     if ( mp->cur_cmd==capsule_token ) {
13392       save_type=mp->cur_type; save_exp=mp->cur_exp;
13393       mp_make_exp_copy(mp, mp->cur_mod); p=mp_stash_cur_exp(mp); link(p)=null;
13394       mp->cur_type=save_type; mp->cur_exp=save_exp;
13395     } else { 
13396       p=mp_get_node(mp, token_node_size);
13397       value(p)=mp->cur_mod; name_type(p)=mp_token;
13398       if ( mp->cur_cmd==numeric_token ) type(p)=mp_known;
13399       else type(p)=mp_string_type;
13400     }
13401   } else { 
13402     fast_get_avail(p); info(p)=mp->cur_sym;
13403   }
13404   return p;
13405 }
13406
13407 @ Sometimes \MP\ has read too far and wants to ``unscan'' what it has
13408 seen. The |back_input| procedure takes care of this by putting the token
13409 just scanned back into the input stream, ready to be read again.
13410 If |cur_sym<>0|, the values of |cur_cmd| and |cur_mod| are irrelevant.
13411
13412 @<Declarations@>= 
13413 void mp_back_input (MP mp);
13414
13415 @ @c void mp_back_input (MP mp) {/* undoes one token of input */
13416   pointer p; /* a token list of length one */
13417   p=mp_cur_tok(mp);
13418   while ( token_state &&(loc==null) ) 
13419     mp_end_token_list(mp); /* conserve stack space */
13420   back_list(p);
13421 }
13422
13423 @ The |back_error| routine is used when we want to restore or replace an
13424 offending token just before issuing an error message.  We disable interrupts
13425 during the call of |back_input| so that the help message won't be lost.
13426
13427 @<Declarations@>=
13428 void mp_error (MP mp);
13429 void mp_back_error (MP mp);
13430
13431 @ @c void mp_back_error (MP mp) { /* back up one token and call |error| */
13432   mp->OK_to_interrupt=false; 
13433   mp_back_input(mp); 
13434   mp->OK_to_interrupt=true; mp_error(mp);
13435 }
13436 void mp_ins_error (MP mp) { /* back up one inserted token and call |error| */
13437   mp->OK_to_interrupt=false; 
13438   mp_back_input(mp); token_type=inserted;
13439   mp->OK_to_interrupt=true; mp_error(mp);
13440 }
13441
13442 @ The |begin_file_reading| procedure starts a new level of input for lines
13443 of characters to be read from a file, or as an insertion from the
13444 terminal. It does not take care of opening the file, nor does it set |loc|
13445 or |limit| or |line|.
13446 @^system dependencies@>
13447
13448 @c void mp_begin_file_reading (MP mp) { 
13449   if ( mp->in_open==mp->max_in_open ) 
13450     mp_overflow(mp, "text input levels",mp->max_in_open);
13451 @:MetaPost capacity exceeded text input levels}{\quad text input levels@>
13452   if ( mp->first==mp->buf_size ) 
13453     mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13454   incr(mp->in_open); push_input; index=mp->in_open;
13455   mp->mpx_name[index]=absent;
13456   start=mp->first;
13457   name=is_term; /* |terminal_input| is now |true| */
13458 }
13459
13460 @ Conversely, the variables must be downdated when such a level of input
13461 is finished.  Any associated \.{MPX} file must also be closed and popped
13462 off the file stack.
13463
13464 @c void mp_end_file_reading (MP mp) { 
13465   if ( mp->in_open>index ) {
13466     if ( (mp->mpx_name[mp->in_open]==absent)||(name<=max_spec_src) ) {
13467       mp_confusion(mp, "endinput");
13468 @:this can't happen endinput}{\quad endinput@>
13469     } else { 
13470       (mp->close_file)(mp->input_file[mp->in_open]); /* close an \.{MPX} file */
13471       delete_str_ref(mp->mpx_name[mp->in_open]);
13472       decr(mp->in_open);
13473     }
13474   }
13475   mp->first=start;
13476   if ( index!=mp->in_open ) mp_confusion(mp, "endinput");
13477   if ( name>max_spec_src ) {
13478     (mp->close_file)(cur_file);
13479     delete_str_ref(name);
13480     xfree(in_name); 
13481     xfree(in_area);
13482   }
13483   pop_input; decr(mp->in_open);
13484 }
13485
13486 @ Here is a function that tries to resume input from an \.{MPX} file already
13487 associated with the current input file.  It returns |false| if this doesn't
13488 work.
13489
13490 @c boolean mp_begin_mpx_reading (MP mp) { 
13491   if ( mp->in_open!=index+1 ) {
13492      return false;
13493   } else { 
13494     if ( mp->mpx_name[mp->in_open]<=absent ) mp_confusion(mp, "mpx");
13495 @:this can't happen mpx}{\quad mpx@>
13496     if ( mp->first==mp->buf_size ) 
13497       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13498     push_input; index=mp->in_open;
13499     start=mp->first;
13500     name=mp->mpx_name[mp->in_open]; add_str_ref(name);
13501     @<Put an empty line in the input buffer@>;
13502     return true;
13503   }
13504 }
13505
13506 @ This procedure temporarily stops reading an \.{MPX} file.
13507
13508 @c void mp_end_mpx_reading (MP mp) { 
13509   if ( mp->in_open!=index ) mp_confusion(mp, "mpx");
13510 @:this can't happen mpx}{\quad mpx@>
13511   if ( loc<limit ) {
13512     @<Complain that we are not at the end of a line in the \.{MPX} file@>;
13513   }
13514   mp->first=start;
13515   pop_input;
13516 }
13517
13518 @ Here we enforce a restriction that simplifies the input stacks considerably.
13519 This should not inconvenience the user because \.{MPX} files are generated
13520 by an auxiliary program called \.{DVItoMP}.
13521
13522 @ @<Complain that we are not at the end of a line in the \.{MPX} file@>=
13523
13524 print_err("`mpxbreak' must be at the end of a line");
13525 help4("This file contains picture expressions for btex...etex")
13526   ("blocks.  Such files are normally generated automatically")
13527   ("but this one seems to be messed up.  I'm going to ignore")
13528   ("the rest of this line.");
13529 mp_error(mp);
13530 }
13531
13532 @ In order to keep the stack from overflowing during a long sequence of
13533 inserted `\.{show}' commands, the following routine removes completed
13534 error-inserted lines from memory.
13535
13536 @c void mp_clear_for_error_prompt (MP mp) { 
13537   while ( file_state && terminal_input &&
13538     (mp->input_ptr>0)&&(loc==limit) ) mp_end_file_reading(mp);
13539   mp_print_ln(mp); clear_terminal;
13540 }
13541
13542 @ To get \MP's whole input mechanism going, we perform the following
13543 actions.
13544
13545 @<Initialize the input routines@>=
13546 { mp->input_ptr=0; mp->max_in_stack=0;
13547   mp->in_open=0; mp->open_parens=0; mp->max_buf_stack=0;
13548   mp->param_ptr=0; mp->max_param_stack=0;
13549   mp->first=1;
13550   start=1; index=0; line=0; name=is_term;
13551   mp->mpx_name[0]=absent;
13552   mp->force_eof=false;
13553   if ( ! mp_init_terminal(mp) ) mp_jump_out(mp);
13554   limit=mp->last; mp->first=mp->last+1; 
13555   /* |init_terminal| has set |loc| and |last| */
13556 }
13557
13558 @* \[29] Getting the next token.
13559 The heart of \MP's input mechanism is the |get_next| procedure, which
13560 we shall develop in the next few sections of the program. Perhaps we
13561 shouldn't actually call it the ``heart,'' however; it really acts as \MP's
13562 eyes and mouth, reading the source files and gobbling them up. And it also
13563 helps \MP\ to regurgitate stored token lists that are to be processed again.
13564
13565 The main duty of |get_next| is to input one token and to set |cur_cmd|
13566 and |cur_mod| to that token's command code and modifier. Furthermore, if
13567 the input token is a symbolic token, that token's |hash| address
13568 is stored in |cur_sym|; otherwise |cur_sym| is set to zero.
13569
13570 Underlying this simple description is a certain amount of complexity
13571 because of all the cases that need to be handled.
13572 However, the inner loop of |get_next| is reasonably short and fast.
13573
13574 @ Before getting into |get_next|, we need to consider a mechanism by which
13575 \MP\ helps keep errors from propagating too far. Whenever the program goes
13576 into a mode where it keeps calling |get_next| repeatedly until a certain
13577 condition is met, it sets |scanner_status| to some value other than |normal|.
13578 Then if an input file ends, or if an `\&{outer}' symbol appears,
13579 an appropriate error recovery will be possible.
13580
13581 The global variable |warning_info| helps in this error recovery by providing
13582 additional information. For example, |warning_info| might indicate the
13583 name of a macro whose replacement text is being scanned.
13584
13585 @d normal 0 /* |scanner_status| at ``quiet times'' */
13586 @d skipping 1 /* |scanner_status| when false conditional text is being skipped */
13587 @d flushing 2 /* |scanner_status| when junk after a statement is being ignored */
13588 @d absorbing 3 /* |scanner_status| when a \&{text} parameter is being scanned */
13589 @d var_defining 4 /* |scanner_status| when a \&{vardef} is being scanned */
13590 @d op_defining 5 /* |scanner_status| when a macro \&{def} is being scanned */
13591 @d loop_defining 6 /* |scanner_status| when a \&{for} loop is being scanned */
13592 @d tex_flushing 7 /* |scanner_status| when skipping \TeX\ material */
13593
13594 @<Glob...@>=
13595 integer scanner_status; /* are we scanning at high speed? */
13596 integer warning_info; /* if so, what else do we need to know,
13597     in case an error occurs? */
13598
13599 @ @<Initialize the input routines@>=
13600 mp->scanner_status=normal;
13601
13602 @ The following subroutine
13603 is called when an `\&{outer}' symbolic token has been scanned or
13604 when the end of a file has been reached. These two cases are distinguished
13605 by |cur_sym|, which is zero at the end of a file.
13606
13607 @c boolean mp_check_outer_validity (MP mp) {
13608   pointer p; /* points to inserted token list */
13609   if ( mp->scanner_status==normal ) {
13610     return true;
13611   } else if ( mp->scanner_status==tex_flushing ) {
13612     @<Check if the file has ended while flushing \TeX\ material and set the
13613       result value for |check_outer_validity|@>;
13614   } else { 
13615     mp->deletions_allowed=false;
13616     @<Back up an outer symbolic token so that it can be reread@>;
13617     if ( mp->scanner_status>skipping ) {
13618       @<Tell the user what has run away and try to recover@>;
13619     } else { 
13620       print_err("Incomplete if; all text was ignored after line ");
13621 @.Incomplete if...@>
13622       mp_print_int(mp, mp->warning_info);
13623       help3("A forbidden `outer' token occurred in skipped text.")
13624         ("This kind of error happens when you say `if...' and forget")
13625         ("the matching `fi'. I've inserted a `fi'; this might work.");
13626       if ( mp->cur_sym==0 ) 
13627         mp->help_line[2]="The file ended while I was skipping conditional text.";
13628       mp->cur_sym=frozen_fi; mp_ins_error(mp);
13629     }
13630     mp->deletions_allowed=true; 
13631         return false;
13632   }
13633 }
13634
13635 @ @<Check if the file has ended while flushing \TeX\ material and set...@>=
13636 if ( mp->cur_sym!=0 ) { 
13637    return true;
13638 } else { 
13639   mp->deletions_allowed=false;
13640   print_err("TeX mode didn't end; all text was ignored after line ");
13641   mp_print_int(mp, mp->warning_info);
13642   help2("The file ended while I was looking for the `etex' to")
13643     ("finish this TeX material.  I've inserted `etex' now.");
13644   mp->cur_sym = frozen_etex;
13645   mp_ins_error(mp);
13646   mp->deletions_allowed=true;
13647   return false;
13648 }
13649
13650 @ @<Back up an outer symbolic token so that it can be reread@>=
13651 if ( mp->cur_sym!=0 ) {
13652   p=mp_get_avail(mp); info(p)=mp->cur_sym;
13653   back_list(p); /* prepare to read the symbolic token again */
13654 }
13655
13656 @ @<Tell the user what has run away...@>=
13657
13658   mp_runaway(mp); /* print the definition-so-far */
13659   if ( mp->cur_sym==0 ) {
13660     print_err("File ended");
13661 @.File ended while scanning...@>
13662   } else { 
13663     print_err("Forbidden token found");
13664 @.Forbidden token found...@>
13665   }
13666   mp_print(mp, " while scanning ");
13667   help4("I suspect you have forgotten an `enddef',")
13668     ("causing me to read past where you wanted me to stop.")
13669     ("I'll try to recover; but if the error is serious,")
13670     ("you'd better type `E' or `X' now and fix your file.");
13671   switch (mp->scanner_status) {
13672     @<Complete the error message,
13673       and set |cur_sym| to a token that might help recover from the error@>
13674   } /* there are no other cases */
13675   mp_ins_error(mp);
13676 }
13677
13678 @ As we consider various kinds of errors, it is also appropriate to
13679 change the first line of the help message just given; |help_line[3]|
13680 points to the string that might be changed.
13681
13682 @<Complete the error message,...@>=
13683 case flushing: 
13684   mp_print(mp, "to the end of the statement");
13685   mp->help_line[3]="A previous error seems to have propagated,";
13686   mp->cur_sym=frozen_semicolon;
13687   break;
13688 case absorbing: 
13689   mp_print(mp, "a text argument");
13690   mp->help_line[3]="It seems that a right delimiter was left out,";
13691   if ( mp->warning_info==0 ) {
13692     mp->cur_sym=frozen_end_group;
13693   } else { 
13694     mp->cur_sym=frozen_right_delimiter;
13695     equiv(frozen_right_delimiter)=mp->warning_info;
13696   }
13697   break;
13698 case var_defining:
13699 case op_defining: 
13700   mp_print(mp, "the definition of ");
13701   if ( mp->scanner_status==op_defining ) 
13702      mp_print_text(mp->warning_info);
13703   else 
13704      mp_print_variable_name(mp, mp->warning_info);
13705   mp->cur_sym=frozen_end_def;
13706   break;
13707 case loop_defining: 
13708   mp_print(mp, "the text of a "); 
13709   mp_print_text(mp->warning_info);
13710   mp_print(mp, " loop");
13711   mp->help_line[3]="I suspect you have forgotten an `endfor',";
13712   mp->cur_sym=frozen_end_for;
13713   break;
13714
13715 @ The |runaway| procedure displays the first part of the text that occurred
13716 when \MP\ began its special |scanner_status|, if that text has been saved.
13717
13718 @<Declare the procedure called |runaway|@>=
13719 void mp_runaway (MP mp) { 
13720   if ( mp->scanner_status>flushing ) { 
13721      mp_print_nl(mp, "Runaway ");
13722          switch (mp->scanner_status) { 
13723          case absorbing: mp_print(mp, "text?"); break;
13724          case var_defining: 
13725      case op_defining: mp_print(mp,"definition?"); break;
13726      case loop_defining: mp_print(mp, "loop?"); break;
13727      } /* there are no other cases */
13728      mp_print_ln(mp); 
13729      mp_show_token_list(mp, link(hold_head),null,mp->error_line-10,0);
13730   }
13731 }
13732
13733 @ We need to mention a procedure that may be called by |get_next|.
13734
13735 @<Declarations@>= 
13736 void mp_firm_up_the_line (MP mp);
13737
13738 @ And now we're ready to take the plunge into |get_next| itself.
13739 Note that the behavior depends on the |scanner_status| because percent signs
13740 and double quotes need to be passed over when skipping TeX material.
13741
13742 @c 
13743 void mp_get_next (MP mp) {
13744   /* sets |cur_cmd|, |cur_mod|, |cur_sym| to next token */
13745 @^inner loop@>
13746   /*restart*/ /* go here to get the next input token */
13747   /*exit*/ /* go here when the next input token has been got */
13748   /*|common_ending|*/ /* go here to finish getting a symbolic token */
13749   /*found*/ /* go here when the end of a symbolic token has been found */
13750   /*switch*/ /* go here to branch on the class of an input character */
13751   /*|start_numeric_token|,|start_decimal_token|,|fin_numeric_token|,|done|*/
13752     /* go here at crucial stages when scanning a number */
13753   int k; /* an index into |buffer| */
13754   ASCII_code c; /* the current character in the buffer */
13755   ASCII_code class; /* its class number */
13756   integer n,f; /* registers for decimal-to-binary conversion */
13757 RESTART: 
13758   mp->cur_sym=0;
13759   if ( file_state ) {
13760     @<Input from external file; |goto restart| if no input found,
13761     or |return| if a non-symbolic token is found@>;
13762   } else {
13763     @<Input from token list; |goto restart| if end of list or
13764       if a parameter needs to be expanded,
13765       or |return| if a non-symbolic token is found@>;
13766   }
13767 COMMON_ENDING: 
13768   @<Finish getting the symbolic token in |cur_sym|;
13769    |goto restart| if it is illegal@>;
13770 }
13771
13772 @ When a symbolic token is declared to be `\&{outer}', its command code
13773 is increased by |outer_tag|.
13774 @^inner loop@>
13775
13776 @<Finish getting the symbolic token in |cur_sym|...@>=
13777 mp->cur_cmd=eq_type(mp->cur_sym); mp->cur_mod=equiv(mp->cur_sym);
13778 if ( mp->cur_cmd>=outer_tag ) {
13779   if ( mp_check_outer_validity(mp) ) 
13780     mp->cur_cmd=mp->cur_cmd-outer_tag;
13781   else 
13782     goto RESTART;
13783 }
13784
13785 @ A percent sign appears in |buffer[limit]|; this makes it unnecessary
13786 to have a special test for end-of-line.
13787 @^inner loop@>
13788
13789 @<Input from external file;...@>=
13790
13791 SWITCH: 
13792   c=mp->buffer[loc]; incr(loc); class=mp->char_class[c];
13793   switch (class) {
13794   case digit_class: goto START_NUMERIC_TOKEN; break;
13795   case period_class: 
13796     class=mp->char_class[mp->buffer[loc]];
13797     if ( class>period_class ) {
13798       goto SWITCH;
13799     } else if ( class<period_class ) { /* |class=digit_class| */
13800       n=0; goto START_DECIMAL_TOKEN;
13801     }
13802 @:. }{\..\ token@>
13803     break;
13804   case space_class: goto SWITCH; break;
13805   case percent_class: 
13806     if ( mp->scanner_status==tex_flushing ) {
13807       if ( loc<limit ) goto SWITCH;
13808     }
13809     @<Move to next line of file, or |goto restart| if there is no next line@>;
13810     check_interrupt;
13811     goto SWITCH;
13812     break;
13813   case string_class: 
13814     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13815     else @<Get a string token and |return|@>;
13816     break;
13817   case isolated_classes: 
13818     k=loc-1; goto FOUND; break;
13819   case invalid_class: 
13820     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13821     else @<Decry the invalid character and |goto restart|@>;
13822     break;
13823   default: break; /* letters, etc. */
13824   }
13825   k=loc-1;
13826   while ( mp->char_class[mp->buffer[loc]]==class ) incr(loc);
13827   goto FOUND;
13828 START_NUMERIC_TOKEN:
13829   @<Get the integer part |n| of a numeric token;
13830     set |f:=0| and |goto fin_numeric_token| if there is no decimal point@>;
13831 START_DECIMAL_TOKEN:
13832   @<Get the fraction part |f| of a numeric token@>;
13833 FIN_NUMERIC_TOKEN:
13834   @<Pack the numeric and fraction parts of a numeric token
13835     and |return|@>;
13836 FOUND: 
13837   mp->cur_sym=mp_id_lookup(mp, k,loc-k);
13838 }
13839
13840 @ We go to |restart| instead of to |SWITCH|, because |state| might equal
13841 |token_list| after the error has been dealt with
13842 (cf.\ |clear_for_error_prompt|).
13843
13844 @<Decry the invalid...@>=
13845
13846   print_err("Text line contains an invalid character");
13847 @.Text line contains...@>
13848   help2("A funny symbol that I can\'t read has just been input.")
13849     ("Continue, and I'll forget that it ever happened.");
13850   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13851   goto RESTART;
13852 }
13853
13854 @ @<Get a string token and |return|@>=
13855
13856   if ( mp->buffer[loc]=='"' ) {
13857     mp->cur_mod=rts("");
13858   } else { 
13859     k=loc; mp->buffer[limit+1]='"';
13860     do {  
13861      incr(loc);
13862     } while (mp->buffer[loc]!='"');
13863     if ( loc>limit ) {
13864       @<Decry the missing string delimiter and |goto restart|@>;
13865     }
13866     if ( loc==k+1 ) {
13867       mp->cur_mod=mp->buffer[k];
13868     } else { 
13869       str_room(loc-k);
13870       do {  
13871         append_char(mp->buffer[k]); incr(k);
13872       } while (k!=loc);
13873       mp->cur_mod=mp_make_string(mp);
13874     }
13875   }
13876   incr(loc); mp->cur_cmd=string_token; 
13877   return;
13878 }
13879
13880 @ We go to |restart| after this error message, not to |SWITCH|,
13881 because the |clear_for_error_prompt| routine might have reinstated
13882 |token_state| after |error| has finished.
13883
13884 @<Decry the missing string delimiter and |goto restart|@>=
13885
13886   loc=limit; /* the next character to be read on this line will be |"%"| */
13887   print_err("Incomplete string token has been flushed");
13888 @.Incomplete string token...@>
13889   help3("Strings should finish on the same line as they began.")
13890     ("I've deleted the partial string; you might want to")
13891     ("insert another by typing, e.g., `I\"new string\"'.");
13892   mp->deletions_allowed=false; mp_error(mp);
13893   mp->deletions_allowed=true; 
13894   goto RESTART;
13895 }
13896
13897 @ @<Get the integer part |n| of a numeric token...@>=
13898 n=c-'0';
13899 while ( mp->char_class[mp->buffer[loc]]==digit_class ) {
13900   if ( n<32768 ) n=10*n+mp->buffer[loc]-'0';
13901   incr(loc);
13902 }
13903 if ( mp->buffer[loc]=='.' ) 
13904   if ( mp->char_class[mp->buffer[loc+1]]==digit_class ) 
13905     goto DONE;
13906 f=0; 
13907 goto FIN_NUMERIC_TOKEN;
13908 DONE: incr(loc)
13909
13910 @ @<Get the fraction part |f| of a numeric token@>=
13911 k=0;
13912 do { 
13913   if ( k<17 ) { /* digits for |k>=17| cannot affect the result */
13914     mp->dig[k]=mp->buffer[loc]-'0'; incr(k);
13915   }
13916   incr(loc);
13917 } while (mp->char_class[mp->buffer[loc]]==digit_class);
13918 f=mp_round_decimals(mp, k);
13919 if ( f==unity ) {
13920   incr(n); f=0;
13921 }
13922
13923 @ @<Pack the numeric and fraction parts of a numeric token and |return|@>=
13924 if ( n<32768 ) {
13925   @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>;
13926 } else if ( mp->scanner_status!=tex_flushing ) {
13927   print_err("Enormous number has been reduced");
13928 @.Enormous number...@>
13929   help2("I can\'t handle numbers bigger than 32767.99998;")
13930     ("so I've changed your constant to that maximum amount.");
13931   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13932   mp->cur_mod=el_gordo;
13933 }
13934 mp->cur_cmd=numeric_token; return
13935
13936 @ @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>=
13937
13938   mp->cur_mod=n*unity+f;
13939   if ( mp->cur_mod>=fraction_one ) {
13940     if ( (mp->internal[mp_warning_check]>0) &&
13941          (mp->scanner_status!=tex_flushing) ) {
13942       print_err("Number is too large (");
13943       mp_print_scaled(mp, mp->cur_mod);
13944       mp_print_char(mp, ')');
13945       help3("It is at least 4096. Continue and I'll try to cope")
13946       ("with that big value; but it might be dangerous.")
13947       ("(Set warningcheck:=0 to suppress this message.)");
13948       mp_error(mp);
13949     }
13950   }
13951 }
13952
13953 @ Let's consider now what happens when |get_next| is looking at a token list.
13954 @^inner loop@>
13955
13956 @<Input from token list;...@>=
13957 if ( loc>=mp->hi_mem_min ) { /* one-word token */
13958   mp->cur_sym=info(loc); loc=link(loc); /* move to next */
13959   if ( mp->cur_sym>=expr_base ) {
13960     if ( mp->cur_sym>=suffix_base ) {
13961       @<Insert a suffix or text parameter and |goto restart|@>;
13962     } else { 
13963       mp->cur_cmd=capsule_token;
13964       mp->cur_mod=mp->param_stack[param_start+mp->cur_sym-(expr_base)];
13965       mp->cur_sym=0; return;
13966     }
13967   }
13968 } else if ( loc>null ) {
13969   @<Get a stored numeric or string or capsule token and |return|@>
13970 } else { /* we are done with this token list */
13971   mp_end_token_list(mp); goto RESTART; /* resume previous level */
13972 }
13973
13974 @ @<Insert a suffix or text parameter...@>=
13975
13976   if ( mp->cur_sym>=text_base ) mp->cur_sym=mp->cur_sym-mp->param_size;
13977   /* |param_size=text_base-suffix_base| */
13978   mp_begin_token_list(mp,
13979                       mp->param_stack[param_start+mp->cur_sym-(suffix_base)],
13980                       parameter);
13981   goto RESTART;
13982 }
13983
13984 @ @<Get a stored numeric or string or capsule token...@>=
13985
13986   if ( name_type(loc)==mp_token ) {
13987     mp->cur_mod=value(loc);
13988     if ( type(loc)==mp_known ) {
13989       mp->cur_cmd=numeric_token;
13990     } else { 
13991       mp->cur_cmd=string_token; add_str_ref(mp->cur_mod);
13992     }
13993   } else { 
13994     mp->cur_mod=loc; mp->cur_cmd=capsule_token;
13995   };
13996   loc=link(loc); return;
13997 }
13998
13999 @ All of the easy branches of |get_next| have now been taken care of.
14000 There is one more branch.
14001
14002 @<Move to next line of file, or |goto restart|...@>=
14003 if ( name>max_spec_src ) {
14004   @<Read next line of file into |buffer|, or
14005     |goto restart| if the file has ended@>;
14006 } else { 
14007   if ( mp->input_ptr>0 ) {
14008      /* text was inserted during error recovery or by \&{scantokens} */
14009     mp_end_file_reading(mp); goto RESTART; /* resume previous level */
14010   }
14011   if ( mp->selector<log_only || mp->selector>=write_file) mp_open_log_file(mp);
14012   if ( mp->interaction>mp_nonstop_mode ) {
14013     if ( limit==start ) /* previous line was empty */
14014       mp_print_nl(mp, "(Please type a command or say `end')");
14015 @.Please type...@>
14016     mp_print_ln(mp); mp->first=start;
14017     prompt_input("*"); /* input on-line into |buffer| */
14018 @.*\relax@>
14019     limit=mp->last; mp->buffer[limit]='%';
14020     mp->first=limit+1; loc=start;
14021   } else {
14022     mp_fatal_error(mp, "*** (job aborted, no legal end found)");
14023 @.job aborted@>
14024     /* nonstop mode, which is intended for overnight batch processing,
14025     never waits for on-line input */
14026   }
14027 }
14028
14029 @ The global variable |force_eof| is normally |false|; it is set |true|
14030 by an \&{endinput} command.
14031
14032 @<Glob...@>=
14033 boolean force_eof; /* should the next \&{input} be aborted early? */
14034
14035 @ We must decrement |loc| in order to leave the buffer in a valid state
14036 when an error condition causes us to |goto restart| without calling
14037 |end_file_reading|.
14038
14039 @<Read next line of file into |buffer|, or
14040   |goto restart| if the file has ended@>=
14041
14042   incr(line); mp->first=start;
14043   if ( ! mp->force_eof ) {
14044     if ( mp_input_ln(mp, cur_file ) ) /* not end of file */
14045       mp_firm_up_the_line(mp); /* this sets |limit| */
14046     else 
14047       mp->force_eof=true;
14048   };
14049   if ( mp->force_eof ) {
14050     mp->force_eof=false;
14051     decr(loc);
14052     if ( mpx_reading ) {
14053       @<Complain that the \.{MPX} file ended unexpectly; then set
14054         |cur_sym:=frozen_mpx_break| and |goto comon_ending|@>;
14055     } else { 
14056       mp_print_char(mp, ')'); decr(mp->open_parens);
14057       update_terminal; /* show user that file has been read */
14058       mp_end_file_reading(mp); /* resume previous level */
14059       if ( mp_check_outer_validity(mp) ) goto  RESTART;  
14060       else goto RESTART;
14061     }
14062   }
14063   mp->buffer[limit]='%'; mp->first=limit+1; loc=start; /* ready to read */
14064 }
14065
14066 @ We should never actually come to the end of an \.{MPX} file because such
14067 files should have an \&{mpxbreak} after the translation of the last
14068 \&{btex}$\,\ldots\,$\&{etex} block.
14069
14070 @<Complain that the \.{MPX} file ended unexpectly; then set...@>=
14071
14072   mp->mpx_name[index]=finished;
14073   print_err("mpx file ended unexpectedly");
14074   help4("The file had too few picture expressions for btex...etex")
14075     ("blocks.  Such files are normally generated automatically")
14076     ("but this one got messed up.  You might want to insert a")
14077     ("picture expression now.");
14078   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
14079   mp->cur_sym=frozen_mpx_break; goto COMMON_ENDING;
14080 }
14081
14082 @ Sometimes we want to make it look as though we have just read a blank line
14083 without really doing so.
14084
14085 @<Put an empty line in the input buffer@>=
14086 mp->last=mp->first; limit=mp->last; /* simulate |input_ln| and |firm_up_the_line| */
14087 mp->buffer[limit]='%'; mp->first=limit+1; loc=start
14088
14089 @ If the user has set the |mp_pausing| parameter to some positive value,
14090 and if nonstop mode has not been selected, each line of input is displayed
14091 on the terminal and the transcript file, followed by `\.{=>}'.
14092 \MP\ waits for a response. If the response is null (i.e., if nothing is
14093 typed except perhaps a few blank spaces), the original
14094 line is accepted as it stands; otherwise the line typed is
14095 used instead of the line in the file.
14096
14097 @c void mp_firm_up_the_line (MP mp) {
14098   size_t k; /* an index into |buffer| */
14099   limit=mp->last;
14100   if ( mp->internal[mp_pausing]>0) if ( mp->interaction>mp_nonstop_mode ) {
14101     wake_up_terminal; mp_print_ln(mp);
14102     if ( start<limit ) {
14103       for (k=(size_t)start;k<=(size_t)(limit-1);k++) {
14104         mp_print_str(mp, mp->buffer[k]);
14105       } 
14106     }
14107     mp->first=limit; prompt_input("=>"); /* wait for user response */
14108 @.=>@>
14109     if ( mp->last>mp->first ) {
14110       for (k=mp->first;k<=mp->last-1;k++) { /* move line down in buffer */
14111         mp->buffer[k+start-mp->first]=mp->buffer[k];
14112       }
14113       limit=start+mp->last-mp->first;
14114     }
14115   }
14116 }
14117
14118 @* \[30] Dealing with \TeX\ material.
14119 The \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}$\,\ldots\,$\&{etex}
14120 features need to be implemented at a low level in the scanning process
14121 so that \MP\ can stay in synch with the a preprocessor that treats
14122 blocks of \TeX\ material as they occur in the input file without trying
14123 to expand \MP\ macros.  Thus we need a special version of |get_next|
14124 that does not expand macros and such but does handle \&{btex},
14125 \&{verbatimtex}, etc.
14126
14127 The special version of |get_next| is called |get_t_next|.  It works by flushing
14128 \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}\allowbreak
14129 $\,\ldots\,$\&{etex} blocks, switching to the \.{MPX} file when it sees
14130 \&{btex}, and switching back when it sees \&{mpxbreak}.
14131
14132 @d btex_code 0
14133 @d verbatim_code 1
14134
14135 @ @<Put each...@>=
14136 mp_primitive(mp, "btex",start_tex,btex_code);
14137 @:btex_}{\&{btex} primitive@>
14138 mp_primitive(mp, "verbatimtex",start_tex,verbatim_code);
14139 @:verbatimtex_}{\&{verbatimtex} primitive@>
14140 mp_primitive(mp, "etex",etex_marker,0); mp->eqtb[frozen_etex]=mp->eqtb[mp->cur_sym];
14141 @:etex_}{\&{etex} primitive@>
14142 mp_primitive(mp, "mpxbreak",mpx_break,0); mp->eqtb[frozen_mpx_break]=mp->eqtb[mp->cur_sym];
14143 @:mpx_break_}{\&{mpxbreak} primitive@>
14144
14145 @ @<Cases of |print_cmd...@>=
14146 case start_tex: if ( m==btex_code ) mp_print(mp, "btex");
14147   else mp_print(mp, "verbatimtex"); break;
14148 case etex_marker: mp_print(mp, "etex"); break;
14149 case mpx_break: mp_print(mp, "mpxbreak"); break;
14150
14151 @ Actually, |get_t_next| is a macro that avoids procedure overhead except
14152 in the unusual case where \&{btex}, \&{verbatimtex}, \&{etex}, or \&{mpxbreak}
14153 is encountered.
14154
14155 @d get_t_next {mp_get_next(mp); if ( mp->cur_cmd<=max_pre_command ) mp_t_next(mp); }
14156
14157 @<Declarations@>=
14158 void mp_start_mpx_input (MP mp);
14159
14160 @ @c 
14161 void mp_t_next (MP mp) {
14162   int old_status; /* saves the |scanner_status| */
14163   integer old_info; /* saves the |warning_info| */
14164   while ( mp->cur_cmd<=max_pre_command ) {
14165     if ( mp->cur_cmd==mpx_break ) {
14166       if ( ! file_state || (mp->mpx_name[index]==absent) ) {
14167         @<Complain about a misplaced \&{mpxbreak}@>;
14168       } else { 
14169         mp_end_mpx_reading(mp); 
14170         goto TEX_FLUSH;
14171       }
14172     } else if ( mp->cur_cmd==start_tex ) {
14173       if ( token_state || (name<=max_spec_src) ) {
14174         @<Complain that we are not reading a file@>;
14175       } else if ( mpx_reading ) {
14176         @<Complain that \.{MPX} files cannot contain \TeX\ material@>;
14177       } else if ( (mp->cur_mod!=verbatim_code)&&
14178                   (mp->mpx_name[index]!=finished) ) {
14179         if ( ! mp_begin_mpx_reading(mp) ) mp_start_mpx_input(mp);
14180       } else {
14181         goto TEX_FLUSH;
14182       }
14183     } else {
14184        @<Complain about a misplaced \&{etex}@>;
14185     }
14186     goto COMMON_ENDING;
14187   TEX_FLUSH: 
14188     @<Flush the \TeX\ material@>;
14189   COMMON_ENDING: 
14190     mp_get_next(mp);
14191   }
14192 }
14193
14194 @ We could be in the middle of an operation such as skipping false conditional
14195 text when \TeX\ material is encountered, so we must be careful to save the
14196 |scanner_status|.
14197
14198 @<Flush the \TeX\ material@>=
14199 old_status=mp->scanner_status;
14200 old_info=mp->warning_info;
14201 mp->scanner_status=tex_flushing;
14202 mp->warning_info=line;
14203 do {  mp_get_next(mp); } while (mp->cur_cmd!=etex_marker);
14204 mp->scanner_status=old_status;
14205 mp->warning_info=old_info
14206
14207 @ @<Complain that \.{MPX} files cannot contain \TeX\ material@>=
14208 { print_err("An mpx file cannot contain btex or verbatimtex blocks");
14209 help4("This file contains picture expressions for btex...etex")
14210   ("blocks.  Such files are normally generated automatically")
14211   ("but this one seems to be messed up.  I'll just keep going")
14212   ("and hope for the best.");
14213 mp_error(mp);
14214 }
14215
14216 @ @<Complain that we are not reading a file@>=
14217 { print_err("You can only use `btex' or `verbatimtex' in a file");
14218 help3("I'll have to ignore this preprocessor command because it")
14219   ("only works when there is a file to preprocess.  You might")
14220   ("want to delete everything up to the next `etex`.");
14221 mp_error(mp);
14222 }
14223
14224 @ @<Complain about a misplaced \&{mpxbreak}@>=
14225 { print_err("Misplaced mpxbreak");
14226 help2("I'll ignore this preprocessor command because it")
14227   ("doesn't belong here");
14228 mp_error(mp);
14229 }
14230
14231 @ @<Complain about a misplaced \&{etex}@>=
14232 { print_err("Extra etex will be ignored");
14233 help1("There is no btex or verbatimtex for this to match");
14234 mp_error(mp);
14235 }
14236
14237 @* \[31] Scanning macro definitions.
14238 \MP\ has a variety of ways to tuck tokens away into token lists for later
14239 use: Macros can be defined with \&{def}, \&{vardef}, \&{primarydef}, etc.;
14240 repeatable code can be defined with \&{for}, \&{forever}, \&{forsuffixes}.
14241 All such operations are handled by the routines in this part of the program.
14242
14243 The modifier part of each command code is zero for the ``ending delimiters''
14244 like \&{enddef} and \&{endfor}.
14245
14246 @d start_def 1 /* command modifier for \&{def} */
14247 @d var_def 2 /* command modifier for \&{vardef} */
14248 @d end_def 0 /* command modifier for \&{enddef} */
14249 @d start_forever 1 /* command modifier for \&{forever} */
14250 @d end_for 0 /* command modifier for \&{endfor} */
14251
14252 @<Put each...@>=
14253 mp_primitive(mp, "def",macro_def,start_def);
14254 @:def_}{\&{def} primitive@>
14255 mp_primitive(mp, "vardef",macro_def,var_def);
14256 @:var_def_}{\&{vardef} primitive@>
14257 mp_primitive(mp, "primarydef",macro_def,secondary_primary_macro);
14258 @:primary_def_}{\&{primarydef} primitive@>
14259 mp_primitive(mp, "secondarydef",macro_def,tertiary_secondary_macro);
14260 @:secondary_def_}{\&{secondarydef} primitive@>
14261 mp_primitive(mp, "tertiarydef",macro_def,expression_tertiary_macro);
14262 @:tertiary_def_}{\&{tertiarydef} primitive@>
14263 mp_primitive(mp, "enddef",macro_def,end_def); mp->eqtb[frozen_end_def]=mp->eqtb[mp->cur_sym];
14264 @:end_def_}{\&{enddef} primitive@>
14265 @#
14266 mp_primitive(mp, "for",iteration,expr_base);
14267 @:for_}{\&{for} primitive@>
14268 mp_primitive(mp, "forsuffixes",iteration,suffix_base);
14269 @:for_suffixes_}{\&{forsuffixes} primitive@>
14270 mp_primitive(mp, "forever",iteration,start_forever);
14271 @:forever_}{\&{forever} primitive@>
14272 mp_primitive(mp, "endfor",iteration,end_for); mp->eqtb[frozen_end_for]=mp->eqtb[mp->cur_sym];
14273 @:end_for_}{\&{endfor} primitive@>
14274
14275 @ @<Cases of |print_cmd...@>=
14276 case macro_def:
14277   if ( m<=var_def ) {
14278     if ( m==start_def ) mp_print(mp, "def");
14279     else if ( m<start_def ) mp_print(mp, "enddef");
14280     else mp_print(mp, "vardef");
14281   } else if ( m==secondary_primary_macro ) { 
14282     mp_print(mp, "primarydef");
14283   } else if ( m==tertiary_secondary_macro ) { 
14284     mp_print(mp, "secondarydef");
14285   } else { 
14286     mp_print(mp, "tertiarydef");
14287   }
14288   break;
14289 case iteration: 
14290   if ( m<=start_forever ) {
14291     if ( m==start_forever ) mp_print(mp, "forever"); 
14292     else mp_print(mp, "endfor");
14293   } else if ( m==expr_base ) {
14294     mp_print(mp, "for"); 
14295   } else { 
14296     mp_print(mp, "forsuffixes");
14297   }
14298   break;
14299
14300 @ Different macro-absorbing operations have different syntaxes, but they
14301 also have a lot in common. There is a list of special symbols that are to
14302 be replaced by parameter tokens; there is a special command code that
14303 ends the definition; the quotation conventions are identical.  Therefore
14304 it makes sense to have most of the work done by a single subroutine. That
14305 subroutine is called |scan_toks|.
14306
14307 The first parameter to |scan_toks| is the command code that will
14308 terminate scanning (either |macro_def|, |loop_repeat|, or |iteration|).
14309
14310 The second parameter, |subst_list|, points to a (possibly empty) list
14311 of two-word nodes whose |info| and |value| fields specify symbol tokens
14312 before and after replacement. The list will be returned to free storage
14313 by |scan_toks|.
14314
14315 The third parameter is simply appended to the token list that is built.
14316 And the final parameter tells how many of the special operations
14317 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#} are to be replaced by suffix parameters.
14318 When such parameters are present, they are called \.{(SUFFIX0)},
14319 \.{(SUFFIX1)}, and \.{(SUFFIX2)}.
14320
14321 @c pointer mp_scan_toks (MP mp,command_code terminator, pointer 
14322   subst_list, pointer tail_end, small_number suffix_count) {
14323   pointer p; /* tail of the token list being built */
14324   pointer q; /* temporary for link management */
14325   integer balance; /* left delimiters minus right delimiters */
14326   p=hold_head; balance=1; link(hold_head)=null;
14327   while (1) { 
14328     get_t_next;
14329     if ( mp->cur_sym>0 ) {
14330       @<Substitute for |cur_sym|, if it's on the |subst_list|@>;
14331       if ( mp->cur_cmd==terminator ) {
14332         @<Adjust the balance; |break| if it's zero@>;
14333       } else if ( mp->cur_cmd==macro_special ) {
14334         @<Handle quoted symbols, \.{\#\AT!}, \.{\AT!}, or \.{\AT!\#}@>;
14335       }
14336     }
14337     link(p)=mp_cur_tok(mp); p=link(p);
14338   }
14339   link(p)=tail_end; mp_flush_node_list(mp, subst_list);
14340   return link(hold_head);
14341 }
14342
14343 @ @<Substitute for |cur_sym|...@>=
14344
14345   q=subst_list;
14346   while ( q!=null ) {
14347     if ( info(q)==mp->cur_sym ) {
14348       mp->cur_sym=value(q); mp->cur_cmd=relax; break;
14349     }
14350     q=link(q);
14351   }
14352 }
14353
14354 @ @<Adjust the balance; |break| if it's zero@>=
14355 if ( mp->cur_mod>0 ) {
14356   incr(balance);
14357 } else { 
14358   decr(balance);
14359   if ( balance==0 )
14360     break;
14361 }
14362
14363 @ Four commands are intended to be used only within macro texts: \&{quote},
14364 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#}. They are variants of a single command
14365 code called |macro_special|.
14366
14367 @d quote 0 /* |macro_special| modifier for \&{quote} */
14368 @d macro_prefix 1 /* |macro_special| modifier for \.{\#\AT!} */
14369 @d macro_at 2 /* |macro_special| modifier for \.{\AT!} */
14370 @d macro_suffix 3 /* |macro_special| modifier for \.{\AT!\#} */
14371
14372 @<Put each...@>=
14373 mp_primitive(mp, "quote",macro_special,quote);
14374 @:quote_}{\&{quote} primitive@>
14375 mp_primitive(mp, "#@@",macro_special,macro_prefix);
14376 @:]]]\#\AT!_}{\.{\#\AT!} primitive@>
14377 mp_primitive(mp, "@@",macro_special,macro_at);
14378 @:]]]\AT!_}{\.{\AT!} primitive@>
14379 mp_primitive(mp, "@@#",macro_special,macro_suffix);
14380 @:]]]\AT!\#_}{\.{\AT!\#} primitive@>
14381
14382 @ @<Cases of |print_cmd...@>=
14383 case macro_special: 
14384   switch (m) {
14385   case macro_prefix: mp_print(mp, "#@@"); break;
14386   case macro_at: mp_print_char(mp, '@@'); break;
14387   case macro_suffix: mp_print(mp, "@@#"); break;
14388   default: mp_print(mp, "quote"); break;
14389   }
14390   break;
14391
14392 @ @<Handle quoted...@>=
14393
14394   if ( mp->cur_mod==quote ) { get_t_next; } 
14395   else if ( mp->cur_mod<=suffix_count ) 
14396     mp->cur_sym=suffix_base-1+mp->cur_mod;
14397 }
14398
14399 @ Here is a routine that's used whenever a token will be redefined. If
14400 the user's token is unredefinable, the `|frozen_inaccessible|' token is
14401 substituted; the latter is redefinable but essentially impossible to use,
14402 hence \MP's tables won't get fouled up.
14403
14404 @c void mp_get_symbol (MP mp) { /* sets |cur_sym| to a safe symbol */
14405 RESTART: 
14406   get_t_next;
14407   if ( (mp->cur_sym==0)||(mp->cur_sym>frozen_inaccessible) ) {
14408     print_err("Missing symbolic token inserted");
14409 @.Missing symbolic token...@>
14410     help3("Sorry: You can\'t redefine a number, string, or expr.")
14411       ("I've inserted an inaccessible symbol so that your")
14412       ("definition will be completed without mixing me up too badly.");
14413     if ( mp->cur_sym>0 )
14414       mp->help_line[2]="Sorry: You can\'t redefine my error-recovery tokens.";
14415     else if ( mp->cur_cmd==string_token ) 
14416       delete_str_ref(mp->cur_mod);
14417     mp->cur_sym=frozen_inaccessible; mp_ins_error(mp); goto RESTART;
14418   }
14419 }
14420
14421 @ Before we actually redefine a symbolic token, we need to clear away its
14422 former value, if it was a variable. The following stronger version of
14423 |get_symbol| does that.
14424
14425 @c void mp_get_clear_symbol (MP mp) { 
14426   mp_get_symbol(mp); mp_clear_symbol(mp, mp->cur_sym,false);
14427 }
14428
14429 @ Here's another little subroutine; it checks that an equals sign
14430 or assignment sign comes along at the proper place in a macro definition.
14431
14432 @c void mp_check_equals (MP mp) { 
14433   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
14434      mp_missing_err(mp, "=");
14435 @.Missing `='@>
14436     help5("The next thing in this `def' should have been `=',")
14437       ("because I've already looked at the definition heading.")
14438       ("But don't worry; I'll pretend that an equals sign")
14439       ("was present. Everything from here to `enddef'")
14440       ("will be the replacement text of this macro.");
14441     mp_back_error(mp);
14442   }
14443 }
14444
14445 @ A \&{primarydef}, \&{secondarydef}, or \&{tertiarydef} is rather easily
14446 handled now that we have |scan_toks|.  In this case there are
14447 two parameters, which will be \.{EXPR0} and \.{EXPR1} (i.e.,
14448 |expr_base| and |expr_base+1|).
14449
14450 @c void mp_make_op_def (MP mp) {
14451   command_code m; /* the type of definition */
14452   pointer p,q,r; /* for list manipulation */
14453   m=mp->cur_mod;
14454   mp_get_symbol(mp); q=mp_get_node(mp, token_node_size);
14455   info(q)=mp->cur_sym; value(q)=expr_base;
14456   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym;
14457   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
14458   info(p)=mp->cur_sym; value(p)=expr_base+1; link(p)=q;
14459   get_t_next; mp_check_equals(mp);
14460   mp->scanner_status=op_defining; q=mp_get_avail(mp); ref_count(q)=null;
14461   r=mp_get_avail(mp); link(q)=r; info(r)=general_macro;
14462   link(r)=mp_scan_toks(mp, macro_def,p,null,0);
14463   mp->scanner_status=normal; eq_type(mp->warning_info)=m;
14464   equiv(mp->warning_info)=q; mp_get_x_next(mp);
14465 }
14466
14467 @ Parameters to macros are introduced by the keywords \&{expr},
14468 \&{suffix}, \&{text}, \&{primary}, \&{secondary}, and \&{tertiary}.
14469
14470 @<Put each...@>=
14471 mp_primitive(mp, "expr",param_type,expr_base);
14472 @:expr_}{\&{expr} primitive@>
14473 mp_primitive(mp, "suffix",param_type,suffix_base);
14474 @:suffix_}{\&{suffix} primitive@>
14475 mp_primitive(mp, "text",param_type,text_base);
14476 @:text_}{\&{text} primitive@>
14477 mp_primitive(mp, "primary",param_type,primary_macro);
14478 @:primary_}{\&{primary} primitive@>
14479 mp_primitive(mp, "secondary",param_type,secondary_macro);
14480 @:secondary_}{\&{secondary} primitive@>
14481 mp_primitive(mp, "tertiary",param_type,tertiary_macro);
14482 @:tertiary_}{\&{tertiary} primitive@>
14483
14484 @ @<Cases of |print_cmd...@>=
14485 case param_type:
14486   if ( m>=expr_base ) {
14487     if ( m==expr_base ) mp_print(mp, "expr");
14488     else if ( m==suffix_base ) mp_print(mp, "suffix");
14489     else mp_print(mp, "text");
14490   } else if ( m<secondary_macro ) {
14491     mp_print(mp, "primary");
14492   } else if ( m==secondary_macro ) {
14493     mp_print(mp, "secondary");
14494   } else {
14495     mp_print(mp, "tertiary");
14496   }
14497   break;
14498
14499 @ Let's turn next to the more complex processing associated with \&{def}
14500 and \&{vardef}. When the following procedure is called, |cur_mod|
14501 should be either |start_def| or |var_def|.
14502
14503 @c @<Declare the procedure called |check_delimiter|@>;
14504 @<Declare the function called |scan_declared_variable|@>;
14505 void mp_scan_def (MP mp) {
14506   int m; /* the type of definition */
14507   int n; /* the number of special suffix parameters */
14508   int k; /* the total number of parameters */
14509   int c; /* the kind of macro we're defining */
14510   pointer r; /* parameter-substitution list */
14511   pointer q; /* tail of the macro token list */
14512   pointer p; /* temporary storage */
14513   halfword base; /* |expr_base|, |suffix_base|, or |text_base| */
14514   pointer l_delim,r_delim; /* matching delimiters */
14515   m=mp->cur_mod; c=general_macro; link(hold_head)=null;
14516   q=mp_get_avail(mp); ref_count(q)=null; r=null;
14517   @<Scan the token or variable to be defined;
14518     set |n|, |scanner_status|, and |warning_info|@>;
14519   k=n;
14520   if ( mp->cur_cmd==left_delimiter ) {
14521     @<Absorb delimited parameters, putting them into lists |q| and |r|@>;
14522   }
14523   if ( mp->cur_cmd==param_type ) {
14524     @<Absorb undelimited parameters, putting them into list |r|@>;
14525   }
14526   mp_check_equals(mp);
14527   p=mp_get_avail(mp); info(p)=c; link(q)=p;
14528   @<Attach the replacement text to the tail of node |p|@>;
14529   mp->scanner_status=normal; mp_get_x_next(mp);
14530 }
14531
14532 @ We don't put `|frozen_end_group|' into the replacement text of
14533 a \&{vardef}, because the user may want to redefine `\.{endgroup}'.
14534
14535 @<Attach the replacement text to the tail of node |p|@>=
14536 if ( m==start_def ) {
14537   link(p)=mp_scan_toks(mp, macro_def,r,null,n);
14538 } else { 
14539   q=mp_get_avail(mp); info(q)=mp->bg_loc; link(p)=q;
14540   p=mp_get_avail(mp); info(p)=mp->eg_loc;
14541   link(q)=mp_scan_toks(mp, macro_def,r,p,n);
14542 }
14543 if ( mp->warning_info==bad_vardef ) 
14544   mp_flush_token_list(mp, value(bad_vardef))
14545
14546 @ @<Glob...@>=
14547 int bg_loc;
14548 int eg_loc; /* hash addresses of `\.{begingroup}' and `\.{endgroup}' */
14549
14550 @ @<Scan the token or variable to be defined;...@>=
14551 if ( m==start_def ) {
14552   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym; get_t_next;
14553   mp->scanner_status=op_defining; n=0;
14554   eq_type(mp->warning_info)=defined_macro; equiv(mp->warning_info)=q;
14555 } else { 
14556   p=mp_scan_declared_variable(mp);
14557   mp_flush_variable(mp, equiv(info(p)),link(p),true);
14558   mp->warning_info=mp_find_variable(mp, p); mp_flush_list(mp, p);
14559   if ( mp->warning_info==null ) @<Change to `\.{a bad variable}'@>;
14560   mp->scanner_status=var_defining; n=2;
14561   if ( mp->cur_cmd==macro_special ) if ( mp->cur_mod==macro_suffix ) {/* \.{\AT!\#} */
14562     n=3; get_t_next;
14563   }
14564   type(mp->warning_info)=mp_unsuffixed_macro-2+n; value(mp->warning_info)=q;
14565 } /* |mp_suffixed_macro=mp_unsuffixed_macro+1| */
14566
14567 @ @<Change to `\.{a bad variable}'@>=
14568
14569   print_err("This variable already starts with a macro");
14570 @.This variable already...@>
14571   help2("After `vardef a' you can\'t say `vardef a.b'.")
14572     ("So I'll have to discard this definition.");
14573   mp_error(mp); mp->warning_info=bad_vardef;
14574 }
14575
14576 @ @<Initialize table entries...@>=
14577 name_type(bad_vardef)=mp_root; link(bad_vardef)=frozen_bad_vardef;
14578 equiv(frozen_bad_vardef)=bad_vardef; eq_type(frozen_bad_vardef)=tag_token;
14579
14580 @ @<Absorb delimited parameters, putting them into lists |q| and |r|@>=
14581 do {  
14582   l_delim=mp->cur_sym; r_delim=mp->cur_mod; get_t_next;
14583   if ( (mp->cur_cmd==param_type)&&(mp->cur_mod>=expr_base) ) {
14584    base=mp->cur_mod;
14585   } else { 
14586     print_err("Missing parameter type; `expr' will be assumed");
14587 @.Missing parameter type@>
14588     help1("You should've had `expr' or `suffix' or `text' here.");
14589     mp_back_error(mp); base=expr_base;
14590   }
14591   @<Absorb parameter tokens for type |base|@>;
14592   mp_check_delimiter(mp, l_delim,r_delim);
14593   get_t_next;
14594 } while (mp->cur_cmd==left_delimiter)
14595
14596 @ @<Absorb parameter tokens for type |base|@>=
14597 do { 
14598   link(q)=mp_get_avail(mp); q=link(q); info(q)=base+k;
14599   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size); 
14600   value(p)=base+k; info(p)=mp->cur_sym;
14601   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14602 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
14603   incr(k); link(p)=r; r=p; get_t_next;
14604 } while (mp->cur_cmd==comma)
14605
14606 @ @<Absorb undelimited parameters, putting them into list |r|@>=
14607
14608   p=mp_get_node(mp, token_node_size);
14609   if ( mp->cur_mod<expr_base ) {
14610     c=mp->cur_mod; value(p)=expr_base+k;
14611   } else { 
14612     value(p)=mp->cur_mod+k;
14613     if ( mp->cur_mod==expr_base ) c=expr_macro;
14614     else if ( mp->cur_mod==suffix_base ) c=suffix_macro;
14615     else c=text_macro;
14616   }
14617   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14618   incr(k); mp_get_symbol(mp); info(p)=mp->cur_sym; link(p)=r; r=p; get_t_next;
14619   if ( c==expr_macro ) if ( mp->cur_cmd==of_token ) {
14620     c=of_macro; p=mp_get_node(mp, token_node_size);
14621     if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14622     value(p)=expr_base+k; mp_get_symbol(mp); info(p)=mp->cur_sym;
14623     link(p)=r; r=p; get_t_next;
14624   }
14625 }
14626
14627 @* \[32] Expanding the next token.
14628 Only a few command codes |<min_command| can possibly be returned by
14629 |get_t_next|; in increasing order, they are
14630 |if_test|, |fi_or_else|, |input|, |iteration|, |repeat_loop|,
14631 |exit_test|, |relax|, |scan_tokens|, |expand_after|, and |defined_macro|.
14632
14633 \MP\ usually gets the next token of input by saying |get_x_next|. This is
14634 like |get_t_next| except that it keeps getting more tokens until
14635 finding |cur_cmd>=min_command|. In other words, |get_x_next| expands
14636 macros and removes conditionals or iterations or input instructions that
14637 might be present.
14638
14639 It follows that |get_x_next| might invoke itself recursively. In fact,
14640 there is massive recursion, since macro expansion can involve the
14641 scanning of arbitrarily complex expressions, which in turn involve
14642 macro expansion and conditionals, etc.
14643 @^recursion@>
14644
14645 Therefore it's necessary to declare a whole bunch of |forward|
14646 procedures at this point, and to insert some other procedures
14647 that will be invoked by |get_x_next|.
14648
14649 @<Declarations@>= 
14650 void mp_scan_primary (MP mp);
14651 void mp_scan_secondary (MP mp);
14652 void mp_scan_tertiary (MP mp);
14653 void mp_scan_expression (MP mp);
14654 void mp_scan_suffix (MP mp);
14655 @<Declare the procedure called |macro_call|@>;
14656 void mp_get_boolean (MP mp);
14657 void mp_pass_text (MP mp);
14658 void mp_conditional (MP mp);
14659 void mp_start_input (MP mp);
14660 void mp_begin_iteration (MP mp);
14661 void mp_resume_iteration (MP mp);
14662 void mp_stop_iteration (MP mp);
14663
14664 @ An auxiliary subroutine called |expand| is used by |get_x_next|
14665 when it has to do exotic expansion commands.
14666
14667 @c void mp_expand (MP mp) {
14668   pointer p; /* for list manipulation */
14669   size_t k; /* something that we hope is |<=buf_size| */
14670   pool_pointer j; /* index into |str_pool| */
14671   if ( mp->internal[mp_tracing_commands]>unity ) 
14672     if ( mp->cur_cmd!=defined_macro )
14673       show_cur_cmd_mod;
14674   switch (mp->cur_cmd)  {
14675   case if_test:
14676     mp_conditional(mp); /* this procedure is discussed in Part 36 below */
14677     break;
14678   case fi_or_else:
14679     @<Terminate the current conditional and skip to \&{fi}@>;
14680     break;
14681   case input:
14682     @<Initiate or terminate input from a file@>;
14683     break;
14684   case iteration:
14685     if ( mp->cur_mod==end_for ) {
14686       @<Scold the user for having an extra \&{endfor}@>;
14687     } else {
14688       mp_begin_iteration(mp); /* this procedure is discussed in Part 37 below */
14689     }
14690     break;
14691   case repeat_loop: 
14692     @<Repeat a loop@>;
14693     break;
14694   case exit_test: 
14695     @<Exit a loop if the proper time has come@>;
14696     break;
14697   case relax: 
14698     break;
14699   case expand_after: 
14700     @<Expand the token after the next token@>;
14701     break;
14702   case scan_tokens: 
14703     @<Put a string into the input buffer@>;
14704     break;
14705   case defined_macro:
14706    mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14707    break;
14708   }; /* there are no other cases */
14709 };
14710
14711 @ @<Scold the user...@>=
14712
14713   print_err("Extra `endfor'");
14714 @.Extra `endfor'@>
14715   help2("I'm not currently working on a for loop,")
14716     ("so I had better not try to end anything.");
14717   mp_error(mp);
14718 }
14719
14720 @ The processing of \&{input} involves the |start_input| subroutine,
14721 which will be declared later; the processing of \&{endinput} is trivial.
14722
14723 @<Put each...@>=
14724 mp_primitive(mp, "input",input,0);
14725 @:input_}{\&{input} primitive@>
14726 mp_primitive(mp, "endinput",input,1);
14727 @:end_input_}{\&{endinput} primitive@>
14728
14729 @ @<Cases of |print_cmd_mod|...@>=
14730 case input: 
14731   if ( m==0 ) mp_print(mp, "input");
14732   else mp_print(mp, "endinput");
14733   break;
14734
14735 @ @<Initiate or terminate input...@>=
14736 if ( mp->cur_mod>0 ) mp->force_eof=true;
14737 else mp_start_input(mp)
14738
14739 @ We'll discuss the complicated parts of loop operations later. For now
14740 it suffices to know that there's a global variable called |loop_ptr|
14741 that will be |null| if no loop is in progress.
14742
14743 @<Repeat a loop@>=
14744 { while ( token_state &&(loc==null) ) 
14745     mp_end_token_list(mp); /* conserve stack space */
14746   if ( mp->loop_ptr==null ) {
14747     print_err("Lost loop");
14748 @.Lost loop@>
14749     help2("I'm confused; after exiting from a loop, I still seem")
14750       ("to want to repeat it. I'll try to forget the problem.");
14751     mp_error(mp);
14752   } else {
14753     mp_resume_iteration(mp); /* this procedure is in Part 37 below */
14754   }
14755 }
14756
14757 @ @<Exit a loop if the proper time has come@>=
14758 { mp_get_boolean(mp);
14759   if ( mp->internal[mp_tracing_commands]>unity ) 
14760     mp_show_cmd_mod(mp, nullary,mp->cur_exp);
14761   if ( mp->cur_exp==true_code ) {
14762     if ( mp->loop_ptr==null ) {
14763       print_err("No loop is in progress");
14764 @.No loop is in progress@>
14765       help1("Why say `exitif' when there's nothing to exit from?");
14766       if ( mp->cur_cmd==semicolon ) mp_error(mp); else mp_back_error(mp);
14767     } else {
14768      @<Exit prematurely from an iteration@>;
14769     }
14770   } else if ( mp->cur_cmd!=semicolon ) {
14771     mp_missing_err(mp, ";");
14772 @.Missing `;'@>
14773     help2("After `exitif <boolean exp>' I expect to see a semicolon.")
14774     ("I shall pretend that one was there."); mp_back_error(mp);
14775   }
14776 }
14777
14778 @ Here we use the fact that |forever_text| is the only |token_type| that
14779 is less than |loop_text|.
14780
14781 @<Exit prematurely...@>=
14782 { p=null;
14783   do {  
14784     if ( file_state ) {
14785       mp_end_file_reading(mp);
14786     } else { 
14787       if ( token_type<=loop_text ) p=start;
14788       mp_end_token_list(mp);
14789     }
14790   } while (p==null);
14791   if ( p!=info(mp->loop_ptr) ) mp_fatal_error(mp, "*** (loop confusion)");
14792 @.loop confusion@>
14793   mp_stop_iteration(mp); /* this procedure is in Part 34 below */
14794 }
14795
14796 @ @<Expand the token after the next token@>=
14797 { get_t_next;
14798   p=mp_cur_tok(mp); get_t_next;
14799   if ( mp->cur_cmd<min_command ) mp_expand(mp); 
14800   else mp_back_input(mp);
14801   back_list(p);
14802 }
14803
14804 @ @<Put a string into the input buffer@>=
14805 { mp_get_x_next(mp); mp_scan_primary(mp);
14806   if ( mp->cur_type!=mp_string_type ) {
14807     mp_disp_err(mp, null,"Not a string");
14808 @.Not a string@>
14809     help2("I'm going to flush this expression, since")
14810        ("scantokens should be followed by a known string.");
14811     mp_put_get_flush_error(mp, 0);
14812   } else { 
14813     mp_back_input(mp);
14814     if ( length(mp->cur_exp)>0 )
14815        @<Pretend we're reading a new one-line file@>;
14816   }
14817 }
14818
14819 @ @<Pretend we're reading a new one-line file@>=
14820 { mp_begin_file_reading(mp); name=is_scantok;
14821   k=mp->first+length(mp->cur_exp);
14822   if ( k>=mp->max_buf_stack ) {
14823     while ( k>=mp->buf_size ) {
14824       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
14825     }
14826     mp->max_buf_stack=k+1;
14827   }
14828   j=mp->str_start[mp->cur_exp]; limit=k;
14829   while ( mp->first<(size_t)limit ) {
14830     mp->buffer[mp->first]=mp->str_pool[j]; incr(j); incr(mp->first);
14831   }
14832   mp->buffer[limit]='%'; mp->first=limit+1; loc=start; 
14833   mp_flush_cur_exp(mp, 0);
14834 }
14835
14836 @ Here finally is |get_x_next|.
14837
14838 The expression scanning routines to be considered later
14839 communicate via the global quantities |cur_type| and |cur_exp|;
14840 we must be very careful to save and restore these quantities while
14841 macros are being expanded.
14842 @^inner loop@>
14843
14844 @<Declarations@>=
14845 void mp_get_x_next (MP mp);
14846
14847 @ @c void mp_get_x_next (MP mp) {
14848   pointer save_exp; /* a capsule to save |cur_type| and |cur_exp| */
14849   get_t_next;
14850   if ( mp->cur_cmd<min_command ) {
14851     save_exp=mp_stash_cur_exp(mp);
14852     do {  
14853       if ( mp->cur_cmd==defined_macro ) 
14854         mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14855       else 
14856         mp_expand(mp);
14857       get_t_next;
14858      } while (mp->cur_cmd<min_command);
14859      mp_unstash_cur_exp(mp, save_exp); /* that restores |cur_type| and |cur_exp| */
14860   }
14861 }
14862
14863 @ Now let's consider the |macro_call| procedure, which is used to start up
14864 all user-defined macros. Since the arguments to a macro might be expressions,
14865 |macro_call| is recursive.
14866 @^recursion@>
14867
14868 The first parameter to |macro_call| points to the reference count of the
14869 token list that defines the macro. The second parameter contains any
14870 arguments that have already been parsed (see below).  The third parameter
14871 points to the symbolic token that names the macro. If the third parameter
14872 is |null|, the macro was defined by \&{vardef}, so its name can be
14873 reconstructed from the prefix and ``at'' arguments found within the
14874 second parameter.
14875
14876 What is this second parameter? It's simply a linked list of one-word items,
14877 whose |info| fields point to the arguments. In other words, if |arg_list=null|,
14878 no arguments have been scanned yet; otherwise |info(arg_list)| points to
14879 the first scanned argument, and |link(arg_list)| points to the list of
14880 further arguments (if any).
14881
14882 Arguments of type \&{expr} are so-called capsules, which we will
14883 discuss later when we concentrate on expressions; they can be
14884 recognized easily because their |link| field is |void|. Arguments of type
14885 \&{suffix} and \&{text} are token lists without reference counts.
14886
14887 @ After argument scanning is complete, the arguments are moved to the
14888 |param_stack|. (They can't be put on that stack any sooner, because
14889 the stack is growing and shrinking in unpredictable ways as more arguments
14890 are being acquired.)  Then the macro body is fed to the scanner; i.e.,
14891 the replacement text of the macro is placed at the top of the \MP's
14892 input stack, so that |get_t_next| will proceed to read it next.
14893
14894 @<Declare the procedure called |macro_call|@>=
14895 @<Declare the procedure called |print_macro_name|@>;
14896 @<Declare the procedure called |print_arg|@>;
14897 @<Declare the procedure called |scan_text_arg|@>;
14898 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14899                     pointer macro_name) ;
14900
14901 @ @c
14902 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14903                     pointer macro_name) {
14904   /* invokes a user-defined control sequence */
14905   pointer r; /* current node in the macro's token list */
14906   pointer p,q; /* for list manipulation */
14907   integer n; /* the number of arguments */
14908   pointer tail = 0; /* tail of the argument list */
14909   pointer l_delim=0,r_delim=0; /* a delimiter pair */
14910   r=link(def_ref); add_mac_ref(def_ref);
14911   if ( arg_list==null ) {
14912     n=0;
14913   } else {
14914    @<Determine the number |n| of arguments already supplied,
14915     and set |tail| to the tail of |arg_list|@>;
14916   }
14917   if ( mp->internal[mp_tracing_macros]>0 ) {
14918     @<Show the text of the macro being expanded, and the existing arguments@>;
14919   }
14920   @<Scan the remaining arguments, if any; set |r| to the first token
14921     of the replacement text@>;
14922   @<Feed the arguments and replacement text to the scanner@>;
14923 }
14924
14925 @ @<Show the text of the macro...@>=
14926 mp_begin_diagnostic(mp); mp_print_ln(mp); 
14927 mp_print_macro_name(mp, arg_list,macro_name);
14928 if ( n==3 ) mp_print(mp, "@@#"); /* indicate a suffixed macro */
14929 mp_show_macro(mp, def_ref,null,100000);
14930 if ( arg_list!=null ) {
14931   n=0; p=arg_list;
14932   do {  
14933     q=info(p);
14934     mp_print_arg(mp, q,n,0);
14935     incr(n); p=link(p);
14936   } while (p!=null);
14937 }
14938 mp_end_diagnostic(mp, false)
14939
14940
14941 @ @<Declare the procedure called |print_macro_name|@>=
14942 void mp_print_macro_name (MP mp,pointer a, pointer n);
14943
14944 @ @c
14945 void mp_print_macro_name (MP mp,pointer a, pointer n) {
14946   pointer p,q; /* they traverse the first part of |a| */
14947   if ( n!=null ) {
14948     mp_print_text(n);
14949   } else  { 
14950     p=info(a);
14951     if ( p==null ) {
14952       mp_print_text(info(info(link(a))));
14953     } else { 
14954       q=p;
14955       while ( link(q)!=null ) q=link(q);
14956       link(q)=info(link(a));
14957       mp_show_token_list(mp, p,null,1000,0);
14958       link(q)=null;
14959     }
14960   }
14961 }
14962
14963 @ @<Declare the procedure called |print_arg|@>=
14964 void mp_print_arg (MP mp,pointer q, integer n, pointer b) ;
14965
14966 @ @c
14967 void mp_print_arg (MP mp,pointer q, integer n, pointer b) {
14968   if ( link(q)==mp_void ) mp_print_nl(mp, "(EXPR");
14969   else if ( (b<text_base)&&(b!=text_macro) ) mp_print_nl(mp, "(SUFFIX");
14970   else mp_print_nl(mp, "(TEXT");
14971   mp_print_int(mp, n); mp_print(mp, ")<-");
14972   if ( link(q)==mp_void ) mp_print_exp(mp, q,1);
14973   else mp_show_token_list(mp, q,null,1000,0);
14974 }
14975
14976 @ @<Determine the number |n| of arguments already supplied...@>=
14977 {  
14978   n=1; tail=arg_list;
14979   while ( link(tail)!=null ) { 
14980     incr(n); tail=link(tail);
14981   }
14982 }
14983
14984 @ @<Scan the remaining arguments, if any; set |r|...@>=
14985 mp->cur_cmd=comma+1; /* anything |<>comma| will do */
14986 while ( info(r)>=expr_base ) { 
14987   @<Scan the delimited argument represented by |info(r)|@>;
14988   r=link(r);
14989 };
14990 if ( mp->cur_cmd==comma ) {
14991   print_err("Too many arguments to ");
14992 @.Too many arguments...@>
14993   mp_print_macro_name(mp, arg_list,macro_name); mp_print_char(mp, ';');
14994   mp_print_nl(mp, "  Missing `"); mp_print_text(r_delim);
14995 @.Missing `)'...@>
14996   mp_print(mp, "' has been inserted");
14997   help3("I'm going to assume that the comma I just read was a")
14998    ("right delimiter, and then I'll begin expanding the macro.")
14999    ("You might want to delete some tokens before continuing.");
15000   mp_error(mp);
15001 }
15002 if ( info(r)!=general_macro ) {
15003   @<Scan undelimited argument(s)@>;
15004 }
15005 r=link(r)
15006
15007 @ At this point, the reader will find it advisable to review the explanation
15008 of token list format that was presented earlier, paying special attention to
15009 the conventions that apply only at the beginning of a macro's token list.
15010
15011 On the other hand, the reader will have to take the expression-parsing
15012 aspects of the following program on faith; we will explain |cur_type|
15013 and |cur_exp| later. (Several things in this program depend on each other,
15014 and it's necessary to jump into the circle somewhere.)
15015
15016 @<Scan the delimited argument represented by |info(r)|@>=
15017 if ( mp->cur_cmd!=comma ) {
15018   mp_get_x_next(mp);
15019   if ( mp->cur_cmd!=left_delimiter ) {
15020     print_err("Missing argument to ");
15021 @.Missing argument...@>
15022     mp_print_macro_name(mp, arg_list,macro_name);
15023     help3("That macro has more parameters than you thought.")
15024      ("I'll continue by pretending that each missing argument")
15025      ("is either zero or null.");
15026     if ( info(r)>=suffix_base ) {
15027       mp->cur_exp=null; mp->cur_type=mp_token_list;
15028     } else { 
15029       mp->cur_exp=0; mp->cur_type=mp_known;
15030     }
15031     mp_back_error(mp); mp->cur_cmd=right_delimiter; 
15032     goto FOUND;
15033   }
15034   l_delim=mp->cur_sym; r_delim=mp->cur_mod;
15035 }
15036 @<Scan the argument represented by |info(r)|@>;
15037 if ( mp->cur_cmd!=comma ) 
15038   @<Check that the proper right delimiter was present@>;
15039 FOUND:  
15040 @<Append the current expression to |arg_list|@>
15041
15042 @ @<Check that the proper right delim...@>=
15043 if ( (mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
15044   if ( info(link(r))>=expr_base ) {
15045     mp_missing_err(mp, ",");
15046 @.Missing `,'@>
15047     help3("I've finished reading a macro argument and am about to")
15048       ("read another; the arguments weren't delimited correctly.")
15049        ("You might want to delete some tokens before continuing.");
15050     mp_back_error(mp); mp->cur_cmd=comma;
15051   } else { 
15052     mp_missing_err(mp, str(text(r_delim)));
15053 @.Missing `)'@>
15054     help2("I've gotten to the end of the macro parameter list.")
15055        ("You might want to delete some tokens before continuing.");
15056     mp_back_error(mp);
15057   }
15058 }
15059
15060 @ A \&{suffix} or \&{text} parameter will be have been scanned as
15061 a token list pointed to by |cur_exp|, in which case we will have
15062 |cur_type=token_list|.
15063
15064 @<Append the current expression to |arg_list|@>=
15065
15066   p=mp_get_avail(mp);
15067   if ( mp->cur_type==mp_token_list ) info(p)=mp->cur_exp;
15068   else info(p)=mp_stash_cur_exp(mp);
15069   if ( mp->internal[mp_tracing_macros]>0 ) {
15070     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,info(r)); 
15071     mp_end_diagnostic(mp, false);
15072   }
15073   if ( arg_list==null ) arg_list=p;
15074   else link(tail)=p;
15075   tail=p; incr(n);
15076 }
15077
15078 @ @<Scan the argument represented by |info(r)|@>=
15079 if ( info(r)>=text_base ) {
15080   mp_scan_text_arg(mp, l_delim,r_delim);
15081 } else { 
15082   mp_get_x_next(mp);
15083   if ( info(r)>=suffix_base ) mp_scan_suffix(mp);
15084   else mp_scan_expression(mp);
15085 }
15086
15087 @ The parameters to |scan_text_arg| are either a pair of delimiters
15088 or zero; the latter case is for undelimited text arguments, which
15089 end with the first semicolon or \&{endgroup} or \&{end} that is not
15090 contained in a group.
15091
15092 @<Declare the procedure called |scan_text_arg|@>=
15093 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) ;
15094
15095 @ @c
15096 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) {
15097   integer balance; /* excess of |l_delim| over |r_delim| */
15098   pointer p; /* list tail */
15099   mp->warning_info=l_delim; mp->scanner_status=absorbing;
15100   p=hold_head; balance=1; link(hold_head)=null;
15101   while (1)  { 
15102     get_t_next;
15103     if ( l_delim==0 ) {
15104       @<Adjust the balance for an undelimited argument; |break| if done@>;
15105     } else {
15106           @<Adjust the balance for a delimited argument; |break| if done@>;
15107     }
15108     link(p)=mp_cur_tok(mp); p=link(p);
15109   }
15110   mp->cur_exp=link(hold_head); mp->cur_type=mp_token_list;
15111   mp->scanner_status=normal;
15112 };
15113
15114 @ @<Adjust the balance for a delimited argument...@>=
15115 if ( mp->cur_cmd==right_delimiter ) { 
15116   if ( mp->cur_mod==l_delim ) { 
15117     decr(balance);
15118     if ( balance==0 ) break;
15119   }
15120 } else if ( mp->cur_cmd==left_delimiter ) {
15121   if ( mp->cur_mod==r_delim ) incr(balance);
15122 }
15123
15124 @ @<Adjust the balance for an undelimited...@>=
15125 if ( end_of_statement ) { /* |cur_cmd=semicolon|, |end_group|, or |stop| */
15126   if ( balance==1 ) { break; }
15127   else  { if ( mp->cur_cmd==end_group ) decr(balance); }
15128 } else if ( mp->cur_cmd==begin_group ) { 
15129   incr(balance); 
15130 }
15131
15132 @ @<Scan undelimited argument(s)@>=
15133
15134   if ( info(r)<text_macro ) {
15135     mp_get_x_next(mp);
15136     if ( info(r)!=suffix_macro ) {
15137       if ( (mp->cur_cmd==equals)||(mp->cur_cmd==assignment) ) mp_get_x_next(mp);
15138     }
15139   }
15140   switch (info(r)) {
15141   case primary_macro:mp_scan_primary(mp); break;
15142   case secondary_macro:mp_scan_secondary(mp); break;
15143   case tertiary_macro:mp_scan_tertiary(mp); break;
15144   case expr_macro:mp_scan_expression(mp); break;
15145   case of_macro:
15146     @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>;
15147     break;
15148   case suffix_macro:
15149     @<Scan a suffix with optional delimiters@>;
15150     break;
15151   case text_macro:mp_scan_text_arg(mp, 0,0); break;
15152   } /* there are no other cases */
15153   mp_back_input(mp); 
15154   @<Append the current expression to |arg_list|@>;
15155 }
15156
15157 @ @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>=
15158
15159   mp_scan_expression(mp); p=mp_get_avail(mp); info(p)=mp_stash_cur_exp(mp);
15160   if ( mp->internal[mp_tracing_macros]>0 ) { 
15161     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,0); 
15162     mp_end_diagnostic(mp, false);
15163   }
15164   if ( arg_list==null ) arg_list=p; else link(tail)=p;
15165   tail=p;incr(n);
15166   if ( mp->cur_cmd!=of_token ) {
15167     mp_missing_err(mp, "of"); mp_print(mp, " for ");
15168 @.Missing `of'@>
15169     mp_print_macro_name(mp, arg_list,macro_name);
15170     help1("I've got the first argument; will look now for the other.");
15171     mp_back_error(mp);
15172   }
15173   mp_get_x_next(mp); mp_scan_primary(mp);
15174 }
15175
15176 @ @<Scan a suffix with optional delimiters@>=
15177
15178   if ( mp->cur_cmd!=left_delimiter ) {
15179     l_delim=null;
15180   } else { 
15181     l_delim=mp->cur_sym; r_delim=mp->cur_mod; mp_get_x_next(mp);
15182   };
15183   mp_scan_suffix(mp);
15184   if ( l_delim!=null ) {
15185     if ((mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
15186       mp_missing_err(mp, str(text(r_delim)));
15187 @.Missing `)'@>
15188       help2("I've gotten to the end of the macro parameter list.")
15189          ("You might want to delete some tokens before continuing.");
15190       mp_back_error(mp);
15191     }
15192     mp_get_x_next(mp);
15193   }
15194 }
15195
15196 @ Before we put a new token list on the input stack, it is wise to clean off
15197 all token lists that have recently been depleted. Then a user macro that ends
15198 with a call to itself will not require unbounded stack space.
15199
15200 @<Feed the arguments and replacement text to the scanner@>=
15201 while ( token_state &&(loc==null) ) mp_end_token_list(mp); /* conserve stack space */
15202 if ( mp->param_ptr+n>mp->max_param_stack ) {
15203   mp->max_param_stack=mp->param_ptr+n;
15204   if ( mp->max_param_stack>mp->param_size )
15205     mp_overflow(mp, "parameter stack size",mp->param_size);
15206 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15207 }
15208 mp_begin_token_list(mp, def_ref,macro); name=macro_name; loc=r;
15209 if ( n>0 ) {
15210   p=arg_list;
15211   do {  
15212    mp->param_stack[mp->param_ptr]=info(p); incr(mp->param_ptr); p=link(p);
15213   } while (p!=null);
15214   mp_flush_list(mp, arg_list);
15215 }
15216
15217 @ It's sometimes necessary to put a single argument onto |param_stack|.
15218 The |stack_argument| subroutine does this.
15219
15220 @c void mp_stack_argument (MP mp,pointer p) { 
15221   if ( mp->param_ptr==mp->max_param_stack ) {
15222     incr(mp->max_param_stack);
15223     if ( mp->max_param_stack>mp->param_size )
15224       mp_overflow(mp, "parameter stack size",mp->param_size);
15225 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15226   }
15227   mp->param_stack[mp->param_ptr]=p; incr(mp->param_ptr);
15228 }
15229
15230 @* \[33] Conditional processing.
15231 Let's consider now the way \&{if} commands are handled.
15232
15233 Conditions can be inside conditions, and this nesting has a stack
15234 that is independent of other stacks.
15235 Four global variables represent the top of the condition stack:
15236 |cond_ptr| points to pushed-down entries, if~any; |cur_if| tells whether
15237 we are processing \&{if} or \&{elseif}; |if_limit| specifies
15238 the largest code of a |fi_or_else| command that is syntactically legal;
15239 and |if_line| is the line number at which the current conditional began.
15240
15241 If no conditions are currently in progress, the condition stack has the
15242 special state |cond_ptr=null|, |if_limit=normal|, |cur_if=0|, |if_line=0|.
15243 Otherwise |cond_ptr| points to a two-word node; the |type|, |name_type|, and
15244 |link| fields of the first word contain |if_limit|, |cur_if|, and
15245 |cond_ptr| at the next level, and the second word contains the
15246 corresponding |if_line|.
15247
15248 @d if_node_size 2 /* number of words in stack entry for conditionals */
15249 @d if_line_field(A) mp->mem[(A)+1].cint
15250 @d if_code 1 /* code for \&{if} being evaluated */
15251 @d fi_code 2 /* code for \&{fi} */
15252 @d else_code 3 /* code for \&{else} */
15253 @d else_if_code 4 /* code for \&{elseif} */
15254
15255 @<Glob...@>=
15256 pointer cond_ptr; /* top of the condition stack */
15257 integer if_limit; /* upper bound on |fi_or_else| codes */
15258 small_number cur_if; /* type of conditional being worked on */
15259 integer if_line; /* line where that conditional began */
15260
15261 @ @<Set init...@>=
15262 mp->cond_ptr=null; mp->if_limit=normal; mp->cur_if=0; mp->if_line=0;
15263
15264 @ @<Put each...@>=
15265 mp_primitive(mp, "if",if_test,if_code);
15266 @:if_}{\&{if} primitive@>
15267 mp_primitive(mp, "fi",fi_or_else,fi_code); mp->eqtb[frozen_fi]=mp->eqtb[mp->cur_sym];
15268 @:fi_}{\&{fi} primitive@>
15269 mp_primitive(mp, "else",fi_or_else,else_code);
15270 @:else_}{\&{else} primitive@>
15271 mp_primitive(mp, "elseif",fi_or_else,else_if_code);
15272 @:else_if_}{\&{elseif} primitive@>
15273
15274 @ @<Cases of |print_cmd_mod|...@>=
15275 case if_test:
15276 case fi_or_else: 
15277   switch (m) {
15278   case if_code:mp_print(mp, "if"); break;
15279   case fi_code:mp_print(mp, "fi");  break;
15280   case else_code:mp_print(mp, "else"); break;
15281   default: mp_print(mp, "elseif"); break;
15282   }
15283   break;
15284
15285 @ Here is a procedure that ignores text until coming to an \&{elseif},
15286 \&{else}, or \&{fi} at level zero of $\&{if}\ldots\&{fi}$
15287 nesting. After it has acted, |cur_mod| will indicate the token that
15288 was found.
15289
15290 \MP's smallest two command codes are |if_test| and |fi_or_else|; this
15291 makes the skipping process a bit simpler.
15292
15293 @c 
15294 void mp_pass_text (MP mp) {
15295   integer l = 0;
15296   mp->scanner_status=skipping;
15297   mp->warning_info=mp_true_line(mp);
15298   while (1)  { 
15299     get_t_next;
15300     if ( mp->cur_cmd<=fi_or_else ) {
15301       if ( mp->cur_cmd<fi_or_else ) {
15302         incr(l);
15303       } else { 
15304         if ( l==0 ) break;
15305         if ( mp->cur_mod==fi_code ) decr(l);
15306       }
15307     } else {
15308       @<Decrease the string reference count,
15309        if the current token is a string@>;
15310     }
15311   }
15312   mp->scanner_status=normal;
15313 }
15314
15315 @ @<Decrease the string reference count...@>=
15316 if ( mp->cur_cmd==string_token ) { delete_str_ref(mp->cur_mod); }
15317
15318 @ When we begin to process a new \&{if}, we set |if_limit:=if_code|; then
15319 if \&{elseif} or \&{else} or \&{fi} occurs before the current \&{if}
15320 condition has been evaluated, a colon will be inserted.
15321 A construction like `\.{if fi}' would otherwise get \MP\ confused.
15322
15323 @<Push the condition stack@>=
15324 { p=mp_get_node(mp, if_node_size); link(p)=mp->cond_ptr; type(p)=mp->if_limit;
15325   name_type(p)=mp->cur_if; if_line_field(p)=mp->if_line;
15326   mp->cond_ptr=p; mp->if_limit=if_code; mp->if_line=mp_true_line(mp); 
15327   mp->cur_if=if_code;
15328 }
15329
15330 @ @<Pop the condition stack@>=
15331 { p=mp->cond_ptr; mp->if_line=if_line_field(p);
15332   mp->cur_if=name_type(p); mp->if_limit=type(p); mp->cond_ptr=link(p);
15333   mp_free_node(mp, p,if_node_size);
15334 }
15335
15336 @ Here's a procedure that changes the |if_limit| code corresponding to
15337 a given value of |cond_ptr|.
15338
15339 @c void mp_change_if_limit (MP mp,small_number l, pointer p) {
15340   pointer q;
15341   if ( p==mp->cond_ptr ) {
15342     mp->if_limit=l; /* that's the easy case */
15343   } else  { 
15344     q=mp->cond_ptr;
15345     while (1) { 
15346       if ( q==null ) mp_confusion(mp, "if");
15347 @:this can't happen if}{\quad if@>
15348       if ( link(q)==p ) { 
15349         type(q)=l; return;
15350       }
15351       q=link(q);
15352     }
15353   }
15354 }
15355
15356 @ The user is supposed to put colons into the proper parts of conditional
15357 statements. Therefore, \MP\ has to check for their presence.
15358
15359 @c 
15360 void mp_check_colon (MP mp) { 
15361   if ( mp->cur_cmd!=colon ) { 
15362     mp_missing_err(mp, ":");
15363 @.Missing `:'@>
15364     help2("There should've been a colon after the condition.")
15365          ("I shall pretend that one was there.");;
15366     mp_back_error(mp);
15367   }
15368 }
15369
15370 @ A condition is started when the |get_x_next| procedure encounters
15371 an |if_test| command; in that case |get_x_next| calls |conditional|,
15372 which is a recursive procedure.
15373 @^recursion@>
15374
15375 @c void mp_conditional (MP mp) {
15376   pointer save_cond_ptr; /* |cond_ptr| corresponding to this conditional */
15377   int new_if_limit; /* future value of |if_limit| */
15378   pointer p; /* temporary register */
15379   @<Push the condition stack@>; 
15380   save_cond_ptr=mp->cond_ptr;
15381 RESWITCH: 
15382   mp_get_boolean(mp); new_if_limit=else_if_code;
15383   if ( mp->internal[mp_tracing_commands]>unity ) {
15384     @<Display the boolean value of |cur_exp|@>;
15385   }
15386 FOUND: 
15387   mp_check_colon(mp);
15388   if ( mp->cur_exp==true_code ) {
15389     mp_change_if_limit(mp, new_if_limit,save_cond_ptr);
15390     return; /* wait for \&{elseif}, \&{else}, or \&{fi} */
15391   };
15392   @<Skip to \&{elseif} or \&{else} or \&{fi}, then |goto done|@>;
15393 DONE: 
15394   mp->cur_if=mp->cur_mod; mp->if_line=mp_true_line(mp);
15395   if ( mp->cur_mod==fi_code ) {
15396     @<Pop the condition stack@>
15397   } else if ( mp->cur_mod==else_if_code ) {
15398     goto RESWITCH;
15399   } else  { 
15400     mp->cur_exp=true_code; new_if_limit=fi_code; mp_get_x_next(mp); 
15401     goto FOUND;
15402   }
15403 }
15404
15405 @ In a construction like `\&{if} \&{if} \&{true}: $0=1$: \\{foo}
15406 \&{else}: \\{bar} \&{fi}', the first \&{else}
15407 that we come to after learning that the \&{if} is false is not the
15408 \&{else} we're looking for. Hence the following curious logic is needed.
15409
15410 @<Skip to \&{elseif}...@>=
15411 while (1) { 
15412   mp_pass_text(mp);
15413   if ( mp->cond_ptr==save_cond_ptr ) goto DONE;
15414   else if ( mp->cur_mod==fi_code ) @<Pop the condition stack@>;
15415 }
15416
15417
15418 @ @<Display the boolean value...@>=
15419 { mp_begin_diagnostic(mp);
15420   if ( mp->cur_exp==true_code ) mp_print(mp, "{true}");
15421   else mp_print(mp, "{false}");
15422   mp_end_diagnostic(mp, false);
15423 }
15424
15425 @ The processing of conditionals is complete except for the following
15426 code, which is actually part of |get_x_next|. It comes into play when
15427 \&{elseif}, \&{else}, or \&{fi} is scanned.
15428
15429 @<Terminate the current conditional and skip to \&{fi}@>=
15430 if ( mp->cur_mod>mp->if_limit ) {
15431   if ( mp->if_limit==if_code ) { /* condition not yet evaluated */
15432     mp_missing_err(mp, ":");
15433 @.Missing `:'@>
15434     mp_back_input(mp); mp->cur_sym=frozen_colon; mp_ins_error(mp);
15435   } else  { 
15436     print_err("Extra "); mp_print_cmd_mod(mp, fi_or_else,mp->cur_mod);
15437 @.Extra else@>
15438 @.Extra elseif@>
15439 @.Extra fi@>
15440     help1("I'm ignoring this; it doesn't match any if.");
15441     mp_error(mp);
15442   }
15443 } else  { 
15444   while ( mp->cur_mod!=fi_code ) mp_pass_text(mp); /* skip to \&{fi} */
15445   @<Pop the condition stack@>;
15446 }
15447
15448 @* \[34] Iterations.
15449 To bring our treatment of |get_x_next| to a close, we need to consider what
15450 \MP\ does when it sees \&{for}, \&{forsuffixes}, and \&{forever}.
15451
15452 There's a global variable |loop_ptr| that keeps track of the \&{for} loops
15453 that are currently active. If |loop_ptr=null|, no loops are in progress;
15454 otherwise |info(loop_ptr)| points to the iterative text of the current
15455 (innermost) loop, and |link(loop_ptr)| points to the data for any other
15456 loops that enclose the current one.
15457
15458 A loop-control node also has two other fields, called |loop_type| and
15459 |loop_list|, whose contents depend on the type of loop:
15460
15461 \yskip\indent|loop_type(loop_ptr)=null| means that |loop_list(loop_ptr)|
15462 points to a list of one-word nodes whose |info| fields point to the
15463 remaining argument values of a suffix list and expression list.
15464
15465 \yskip\indent|loop_type(loop_ptr)=mp_void| means that the current loop is
15466 `\&{forever}'.
15467
15468 \yskip\indent|loop_type(loop_ptr)=progression_flag| means that
15469 |p=loop_list(loop_ptr)| points to a ``progression node'' and |value(p)|,
15470 |step_size(p)|, and |final_value(p)| contain the data for an arithmetic
15471 progression.
15472
15473 \yskip\indent|loop_type(loop_ptr)=p>mp_void| means that |p| points to an edge
15474 header and |loop_list(loop_ptr)| points into the graphical object list for
15475 that edge header.
15476
15477 \yskip\noindent In the case of a progression node, the first word is not used
15478 because the link field of words in the dynamic memory area cannot be arbitrary.
15479
15480 @d loop_list_loc(A) ((A)+1) /* where the |loop_list| field resides */
15481 @d loop_type(A) info(loop_list_loc((A))) /* the type of \&{for} loop */
15482 @d loop_list(A) link(loop_list_loc((A))) /* the remaining list elements */
15483 @d loop_node_size 2 /* the number of words in a loop control node */
15484 @d progression_node_size 4 /* the number of words in a progression node */
15485 @d step_size(A) mp->mem[(A)+2].sc /* the step size in an arithmetic progression */
15486 @d final_value(A) mp->mem[(A)+3].sc /* the final value in an arithmetic progression */
15487 @d progression_flag (null+2)
15488   /* |loop_type| value when |loop_list| points to a progression node */
15489
15490 @<Glob...@>=
15491 pointer loop_ptr; /* top of the loop-control-node stack */
15492
15493 @ @<Set init...@>=
15494 mp->loop_ptr=null;
15495
15496 @ If the expressions that define an arithmetic progression in
15497 a \&{for} loop don't have known numeric values, the |bad_for|
15498 subroutine screams at the user.
15499
15500 @c void mp_bad_for (MP mp, char * s) {
15501   mp_disp_err(mp, null,"Improper "); /* show the bad expression above the message */
15502 @.Improper...replaced by 0@>
15503   mp_print(mp, s); mp_print(mp, " has been replaced by 0");
15504   help4("When you say `for x=a step b until c',")
15505     ("the initial value `a' and the step size `b'")
15506     ("and the final value `c' must have known numeric values.")
15507     ("I'm zeroing this one. Proceed, with fingers crossed.");
15508   mp_put_get_flush_error(mp, 0);
15509 };
15510
15511 @ Here's what \MP\ does when \&{for}, \&{forsuffixes}, or \&{forever}
15512 has just been scanned. (This code requires slight familiarity with
15513 expression-parsing routines that we have not yet discussed; but it seems
15514 to belong in the present part of the program, even though the original author
15515 didn't write it until later. The reader may wish to come back to it.)
15516
15517 @c void mp_begin_iteration (MP mp) {
15518   halfword m; /* |expr_base| (\&{for}) or |suffix_base| (\&{forsuffixes}) */
15519   halfword n; /* hash address of the current symbol */
15520   pointer s; /* the new loop-control node */
15521   pointer p; /* substitution list for |scan_toks| */
15522   pointer q;  /* link manipulation register */
15523   pointer pp; /* a new progression node */
15524   m=mp->cur_mod; n=mp->cur_sym; s=mp_get_node(mp, loop_node_size);
15525   if ( m==start_forever ){ 
15526     loop_type(s)=mp_void; p=null; mp_get_x_next(mp);
15527   } else { 
15528     mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
15529     info(p)=mp->cur_sym; value(p)=m;
15530     mp_get_x_next(mp);
15531     if ( mp->cur_cmd==within_token ) {
15532       @<Set up a picture iteration@>;
15533     } else { 
15534       @<Check for the |"="| or |":="| in a loop header@>;
15535       @<Scan the values to be used in the loop@>;
15536     }
15537   }
15538   @<Check for the presence of a colon@>;
15539   @<Scan the loop text and put it on the loop control stack@>;
15540   mp_resume_iteration(mp);
15541 }
15542
15543 @ @<Check for the |"="| or |":="| in a loop header@>=
15544 if ( (mp->cur_cmd!=equals)&&(mp->cur_cmd!=assignment) ) { 
15545   mp_missing_err(mp, "=");
15546 @.Missing `='@>
15547   help3("The next thing in this loop should have been `=' or `:='.")
15548     ("But don't worry; I'll pretend that an equals sign")
15549     ("was present, and I'll look for the values next.");
15550   mp_back_error(mp);
15551 }
15552
15553 @ @<Check for the presence of a colon@>=
15554 if ( mp->cur_cmd!=colon ) { 
15555   mp_missing_err(mp, ":");
15556 @.Missing `:'@>
15557   help3("The next thing in this loop should have been a `:'.")
15558     ("So I'll pretend that a colon was present;")
15559     ("everything from here to `endfor' will be iterated.");
15560   mp_back_error(mp);
15561 }
15562
15563 @ We append a special |frozen_repeat_loop| token in place of the
15564 `\&{endfor}' at the end of the loop. This will come through \MP's scanner
15565 at the proper time to cause the loop to be repeated.
15566
15567 (If the user tries some shenanigan like `\&{for} $\ldots$ \&{let} \&{endfor}',
15568 he will be foiled by the |get_symbol| routine, which keeps frozen
15569 tokens unchanged. Furthermore the |frozen_repeat_loop| is an \&{outer}
15570 token, so it won't be lost accidentally.)
15571
15572 @ @<Scan the loop text...@>=
15573 q=mp_get_avail(mp); info(q)=frozen_repeat_loop;
15574 mp->scanner_status=loop_defining; mp->warning_info=n;
15575 info(s)=mp_scan_toks(mp, iteration,p,q,0); mp->scanner_status=normal;
15576 link(s)=mp->loop_ptr; mp->loop_ptr=s
15577
15578 @ @<Initialize table...@>=
15579 eq_type(frozen_repeat_loop)=repeat_loop+outer_tag;
15580 text(frozen_repeat_loop)=intern(" ENDFOR");
15581
15582 @ The loop text is inserted into \MP's scanning apparatus by the
15583 |resume_iteration| routine.
15584
15585 @c void mp_resume_iteration (MP mp) {
15586   pointer p,q; /* link registers */
15587   p=loop_type(mp->loop_ptr);
15588   if ( p==progression_flag ) { 
15589     p=loop_list(mp->loop_ptr); /* now |p| points to a progression node */
15590     mp->cur_exp=value(p);
15591     if ( @<The arithmetic progression has ended@> ) {
15592       mp_stop_iteration(mp);
15593       return;
15594     }
15595     mp->cur_type=mp_known; q=mp_stash_cur_exp(mp); /* make |q| an \&{expr} argument */
15596     value(p)=mp->cur_exp+step_size(p); /* set |value(p)| for the next iteration */
15597   } else if ( p==null ) { 
15598     p=loop_list(mp->loop_ptr);
15599     if ( p==null ) {
15600       mp_stop_iteration(mp);
15601       return;
15602     }
15603     loop_list(mp->loop_ptr)=link(p); q=info(p); free_avail(p);
15604   } else if ( p==mp_void ) { 
15605     mp_begin_token_list(mp, info(mp->loop_ptr),forever_text); return;
15606   } else {
15607     @<Make |q| a capsule containing the next picture component from
15608       |loop_list(loop_ptr)| or |goto not_found|@>;
15609   }
15610   mp_begin_token_list(mp, info(mp->loop_ptr),loop_text);
15611   mp_stack_argument(mp, q);
15612   if ( mp->internal[mp_tracing_commands]>unity ) {
15613      @<Trace the start of a loop@>;
15614   }
15615   return;
15616 NOT_FOUND:
15617   mp_stop_iteration(mp);
15618 }
15619
15620 @ @<The arithmetic progression has ended@>=
15621 ((step_size(p)>0)&&(mp->cur_exp>final_value(p)))||
15622  ((step_size(p)<0)&&(mp->cur_exp<final_value(p)))
15623
15624 @ @<Trace the start of a loop@>=
15625
15626   mp_begin_diagnostic(mp); mp_print_nl(mp, "{loop value=");
15627 @.loop value=n@>
15628   if ( (q!=null)&&(link(q)==mp_void) ) mp_print_exp(mp, q,1);
15629   else mp_show_token_list(mp, q,null,50,0);
15630   mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
15631 }
15632
15633 @ @<Make |q| a capsule containing the next picture component from...@>=
15634 { q=loop_list(mp->loop_ptr);
15635   if ( q==null ) goto NOT_FOUND;
15636   skip_component(q) goto NOT_FOUND;
15637   mp->cur_exp=mp_copy_objects(mp, loop_list(mp->loop_ptr),q);
15638   mp_init_bbox(mp, mp->cur_exp);
15639   mp->cur_type=mp_picture_type;
15640   loop_list(mp->loop_ptr)=q;
15641   q=mp_stash_cur_exp(mp);
15642 }
15643
15644 @ A level of loop control disappears when |resume_iteration| has decided
15645 not to resume, or when an \&{exitif} construction has removed the loop text
15646 from the input stack.
15647
15648 @c void mp_stop_iteration (MP mp) {
15649   pointer p,q; /* the usual */
15650   p=loop_type(mp->loop_ptr);
15651   if ( p==progression_flag )  {
15652     mp_free_node(mp, loop_list(mp->loop_ptr),progression_node_size);
15653   } else if ( p==null ){ 
15654     q=loop_list(mp->loop_ptr);
15655     while ( q!=null ) {
15656       p=info(q);
15657       if ( p!=null ) {
15658         if ( link(p)==mp_void ) { /* it's an \&{expr} parameter */
15659           mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
15660         } else {
15661           mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
15662         }
15663       }
15664       p=q; q=link(q); free_avail(p);
15665     }
15666   } else if ( p>progression_flag ) {
15667     delete_edge_ref(p);
15668   }
15669   p=mp->loop_ptr; mp->loop_ptr=link(p); mp_flush_token_list(mp, info(p));
15670   mp_free_node(mp, p,loop_node_size);
15671 }
15672
15673 @ Now that we know all about loop control, we can finish up
15674 the missing portion of |begin_iteration| and we'll be done.
15675
15676 The following code is performed after the `\.=' has been scanned in
15677 a \&{for} construction (if |m=expr_base|) or a \&{forsuffixes} construction
15678 (if |m=suffix_base|).
15679
15680 @<Scan the values to be used in the loop@>=
15681 loop_type(s)=null; q=loop_list_loc(s); link(q)=null; /* |link(q)=loop_list(s)| */
15682 do {  
15683   mp_get_x_next(mp);
15684   if ( m!=expr_base ) {
15685     mp_scan_suffix(mp);
15686   } else { 
15687     if ( mp->cur_cmd>=colon ) if ( mp->cur_cmd<=comma ) 
15688           goto CONTINUE;
15689     mp_scan_expression(mp);
15690     if ( mp->cur_cmd==step_token ) if ( q==loop_list_loc(s) ) {
15691       @<Prepare for step-until construction and |break|@>;
15692     }
15693     mp->cur_exp=mp_stash_cur_exp(mp);
15694   }
15695   link(q)=mp_get_avail(mp); q=link(q); 
15696   info(q)=mp->cur_exp; mp->cur_type=mp_vacuous;
15697 CONTINUE:
15698   ;
15699 } while (mp->cur_cmd==comma)
15700
15701 @ @<Prepare for step-until construction and |break|@>=
15702
15703   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "initial value");
15704   pp=mp_get_node(mp, progression_node_size); value(pp)=mp->cur_exp;
15705   mp_get_x_next(mp); mp_scan_expression(mp);
15706   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "step size");
15707   step_size(pp)=mp->cur_exp;
15708   if ( mp->cur_cmd!=until_token ) { 
15709     mp_missing_err(mp, "until");
15710 @.Missing `until'@>
15711     help2("I assume you meant to say `until' after `step'.")
15712       ("So I'll look for the final value and colon next.");
15713     mp_back_error(mp);
15714   }
15715   mp_get_x_next(mp); mp_scan_expression(mp);
15716   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "final value");
15717   final_value(pp)=mp->cur_exp; loop_list(s)=pp;
15718   loop_type(s)=progression_flag; 
15719   break;
15720 }
15721
15722 @ The last case is when we have just seen ``\&{within}'', and we need to
15723 parse a picture expression and prepare to iterate over it.
15724
15725 @<Set up a picture iteration@>=
15726 { mp_get_x_next(mp);
15727   mp_scan_expression(mp);
15728   @<Make sure the current expression is a known picture@>;
15729   loop_type(s)=mp->cur_exp; mp->cur_type=mp_vacuous;
15730   q=link(dummy_loc(mp->cur_exp));
15731   if ( q!= null ) 
15732     if ( is_start_or_stop(q) )
15733       if ( mp_skip_1component(mp, q)==null ) q=link(q);
15734   loop_list(s)=q;
15735 }
15736
15737 @ @<Make sure the current expression is a known picture@>=
15738 if ( mp->cur_type!=mp_picture_type ) {
15739   mp_disp_err(mp, null,"Improper iteration spec has been replaced by nullpicture");
15740   help1("When you say `for x in p', p must be a known picture.");
15741   mp_put_get_flush_error(mp, mp_get_node(mp, edge_header_size));
15742   mp_init_edges(mp, mp->cur_exp); mp->cur_type=mp_picture_type;
15743 }
15744
15745 @* \[35] File names.
15746 It's time now to fret about file names.  Besides the fact that different
15747 operating systems treat files in different ways, we must cope with the
15748 fact that completely different naming conventions are used by different
15749 groups of people. The following programs show what is required for one
15750 particular operating system; similar routines for other systems are not
15751 difficult to devise.
15752 @^system dependencies@>
15753
15754 \MP\ assumes that a file name has three parts: the name proper; its
15755 ``extension''; and a ``file area'' where it is found in an external file
15756 system.  The extension of an input file is assumed to be
15757 `\.{.mp}' unless otherwise specified; it is `\.{.log}' on the
15758 transcript file that records each run of \MP; it is `\.{.tfm}' on the font
15759 metric files that describe characters in any fonts created by \MP; it is
15760 `\.{.ps}' or `.{\it nnn}' for some number {\it nnn} on the \ps\ output files;
15761 and it is `\.{.mem}' on the mem files written by \.{INIMP} to initialize \MP.
15762 The file area can be arbitrary on input files, but files are usually
15763 output to the user's current area.  If an input file cannot be
15764 found on the specified area, \MP\ will look for it on a special system
15765 area; this special area is intended for commonly used input files.
15766
15767 Simple uses of \MP\ refer only to file names that have no explicit
15768 extension or area. For example, a person usually says `\.{input} \.{cmr10}'
15769 instead of `\.{input} \.{cmr10.new}'. Simple file
15770 names are best, because they make the \MP\ source files portable;
15771 whenever a file name consists entirely of letters and digits, it should be
15772 treated in the same way by all implementations of \MP. However, users
15773 need the ability to refer to other files in their environment, especially
15774 when responding to error messages concerning unopenable files; therefore
15775 we want to let them use the syntax that appears in their favorite
15776 operating system.
15777
15778 @ \MP\ uses the same conventions that have proved to be satisfactory for
15779 \TeX\ and \MF. In order to isolate the system-dependent aspects of file names,
15780 @^system dependencies@>
15781 the system-independent parts of \MP\ are expressed in terms
15782 of three system-dependent
15783 procedures called |begin_name|, |more_name|, and |end_name|. In
15784 essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
15785 the system-independent driver program does the operations
15786 $$|begin_name|;\,|more_name|(c_1);\,\ldots\,;|more_name|(c_n);
15787 \,|end_name|.$$
15788 These three procedures communicate with each other via global variables.
15789 Afterwards the file name will appear in the string pool as three strings
15790 called |cur_name|\penalty10000\hskip-.05em,
15791 |cur_area|, and |cur_ext|; the latter two are null (i.e.,
15792 |""|), unless they were explicitly specified by the user.
15793
15794 Actually the situation is slightly more complicated, because \MP\ needs
15795 to know when the file name ends. The |more_name| routine is a function
15796 (with side effects) that returns |true| on the calls |more_name|$(c_1)$,
15797 \dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
15798 returns |false|; or, it returns |true| and $c_n$ is the last character
15799 on the current input line. In other words,
15800 |more_name| is supposed to return |true| unless it is sure that the
15801 file name has been completely scanned; and |end_name| is supposed to be able
15802 to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
15803 whether $|more_name|(c_n)$ returned |true| or |false|.
15804
15805 @<Glob...@>=
15806 char * cur_name; /* name of file just scanned */
15807 char * cur_area; /* file area just scanned, or \.{""} */
15808 char * cur_ext; /* file extension just scanned, or \.{""} */
15809
15810 @ It is easier to maintain reference counts if we assign initial values.
15811
15812 @<Set init...@>=
15813 mp->cur_name=xstrdup(""); 
15814 mp->cur_area=xstrdup(""); 
15815 mp->cur_ext=xstrdup("");
15816
15817 @ @<Dealloc variables@>=
15818 xfree(mp->cur_area);
15819 xfree(mp->cur_name);
15820 xfree(mp->cur_ext);
15821
15822 @ The file names we shall deal with for illustrative purposes have the
15823 following structure:  If the name contains `\.>' or `\.:', the file area
15824 consists of all characters up to and including the final such character;
15825 otherwise the file area is null.  If the remaining file name contains
15826 `\..', the file extension consists of all such characters from the first
15827 remaining `\..' to the end, otherwise the file extension is null.
15828 @^system dependencies@>
15829
15830 We can scan such file names easily by using two global variables that keep track
15831 of the occurrences of area and extension delimiters.  Note that these variables
15832 cannot be of type |pool_pointer| because a string pool compaction could occur
15833 while scanning a file name.
15834
15835 @<Glob...@>=
15836 integer area_delimiter;
15837   /* most recent `\.>' or `\.:' relative to |str_start[str_ptr]| */
15838 integer ext_delimiter; /* the relevant `\..', if any */
15839
15840 @ Input files that can't be found in the user's area may appear in standard
15841 system areas called |MP_area| and |MF_area|.  (The latter is used when the file
15842 extension is |".mf"|.)  The standard system area for font metric files
15843 to be read is |MP_font_area|.
15844 This system area name will, of course, vary from place to place.
15845 @^system dependencies@>
15846
15847 @d MP_area "MPinputs:"
15848 @.MPinputs@>
15849 @d MF_area "MFinputs:"
15850 @.MFinputs@>
15851 @d MP_font_area ""
15852 @.TeXfonts@>
15853
15854 @ Here now is the first of the system-dependent routines for file name scanning.
15855 @^system dependencies@>
15856
15857 @<Declare subroutines for parsing file names@>=
15858 void mp_begin_name (MP mp) { 
15859   xfree(mp->cur_name); 
15860   xfree(mp->cur_area); 
15861   xfree(mp->cur_ext);
15862   mp->area_delimiter=-1; 
15863   mp->ext_delimiter=-1;
15864 }
15865
15866 @ And here's the second.
15867 @^system dependencies@>
15868
15869 @<Declare subroutines for parsing file names@>=
15870 boolean mp_more_name (MP mp, ASCII_code c) { 
15871   if (c==' ') {
15872     return false;
15873   } else { 
15874     if ( (c=='>')||(c==':') ) { 
15875       mp->area_delimiter=mp->pool_ptr; 
15876       mp->ext_delimiter=-1;
15877     } else if ( (c=='.')&&(mp->ext_delimiter<0) ) {
15878       mp->ext_delimiter=mp->pool_ptr;
15879     }
15880     str_room(1); append_char(c); /* contribute |c| to the current string */
15881     return true;
15882   }
15883 }
15884
15885 @ The third.
15886 @^system dependencies@>
15887
15888 @d copy_pool_segment(A,B,C) { 
15889       A = xmalloc(C+1,sizeof(char)); 
15890       strncpy(A,(char *)(mp->str_pool+B),C);  
15891       A[C] = 0;}
15892
15893 @<Declare subroutines for parsing file names@>=
15894 void mp_end_name (MP mp) {
15895   pool_pointer s; /* length of area, name, and extension */
15896   unsigned int len;
15897   /* "my/w.mp" */
15898   s = mp->str_start[mp->str_ptr];
15899   if ( mp->area_delimiter<0 ) {    
15900     mp->cur_area=xstrdup("");
15901   } else {
15902     len = mp->area_delimiter-s; 
15903     copy_pool_segment(mp->cur_area,s,len);
15904     s += len+1;
15905   }
15906   if ( mp->ext_delimiter<0 ) {
15907     mp->cur_ext=xstrdup("");
15908     len = mp->pool_ptr-s; 
15909   } else {
15910     copy_pool_segment(mp->cur_ext,mp->ext_delimiter,(mp->pool_ptr-mp->ext_delimiter));
15911     len = mp->ext_delimiter-s;
15912   }
15913   copy_pool_segment(mp->cur_name,s,len);
15914   mp->pool_ptr=s; /* don't need this partial string */
15915 }
15916
15917 @ Conversely, here is a routine that takes three strings and prints a file
15918 name that might have produced them. (The routine is system dependent, because
15919 some operating systems put the file area last instead of first.)
15920 @^system dependencies@>
15921
15922 @<Basic printing...@>=
15923 void mp_print_file_name (MP mp, char * n, char * a, char * e) { 
15924   mp_print(mp, a); mp_print(mp, n); mp_print(mp, e);
15925 };
15926
15927 @ Another system-dependent routine is needed to convert three internal
15928 \MP\ strings
15929 to the |name_of_file| value that is used to open files. The present code
15930 allows both lowercase and uppercase letters in the file name.
15931 @^system dependencies@>
15932
15933 @d append_to_name(A) { c=(A); 
15934   if ( k<file_name_size ) {
15935     mp->name_of_file[k]=xchr(c);
15936     incr(k);
15937   }
15938 }
15939
15940 @<Declare subroutines for parsing file names@>=
15941 void mp_pack_file_name (MP mp, char *n, char *a, char *e) {
15942   integer k; /* number of positions filled in |name_of_file| */
15943   ASCII_code c; /* character being packed */
15944   char *j; /* a character  index */
15945   k=0;
15946   assert(n);
15947   if (a!=NULL) {
15948     for (j=a;*j;j++) { append_to_name(*j); }
15949   }
15950   for (j=n;*j;j++) { append_to_name(*j); }
15951   if (e!=NULL) {
15952     for (j=e;*j;j++) { append_to_name(*j); }
15953   }
15954   mp->name_of_file[k]=0;
15955   mp->name_length=k; 
15956 }
15957
15958 @ @<Internal library declarations@>=
15959 void mp_pack_file_name (MP mp, char *n, char *a, char *e) ;
15960
15961 @ A messier routine is also needed, since mem file names must be scanned
15962 before \MP's string mechanism has been initialized. We shall use the
15963 global variable |MP_mem_default| to supply the text for default system areas
15964 and extensions related to mem files.
15965 @^system dependencies@>
15966
15967 @d mem_default_length 9 /* length of the |MP_mem_default| string */
15968 @d mem_ext_length 4 /* length of its `\.{.mem}' part */
15969 @d mem_extension ".mem" /* the extension, as a \.{WEB} constant */
15970
15971 @<Glob...@>=
15972 char *MP_mem_default;
15973 char *mem_name; /* for commandline */
15974
15975 @ @<Option variables@>=
15976 char *mem_name; /* for commandline */
15977
15978 @ @<Allocate or initialize ...@>=
15979 mp->MP_mem_default = xstrdup("plain.mem");
15980 mp->mem_name = xstrdup(opt->mem_name);
15981 @.plain@>
15982 @^system dependencies@>
15983
15984 @ @<Dealloc variables@>=
15985 xfree(mp->MP_mem_default);
15986 xfree(mp->mem_name);
15987
15988 @ @<Check the ``constant'' values for consistency@>=
15989 if ( mem_default_length>file_name_size ) mp->bad=20;
15990
15991 @ Here is the messy routine that was just mentioned. It sets |name_of_file|
15992 from the first |n| characters of |MP_mem_default|, followed by
15993 |buffer[a..b-1]|, followed by the last |mem_ext_length| characters of
15994 |MP_mem_default|.
15995
15996 We dare not give error messages here, since \MP\ calls this routine before
15997 the |error| routine is ready to roll. Instead, we simply drop excess characters,
15998 since the error will be detected in another way when a strange file name
15999 isn't found.
16000 @^system dependencies@>
16001
16002 @c void mp_pack_buffered_name (MP mp,small_number n, integer a,
16003                                integer b) {
16004   integer k; /* number of positions filled in |name_of_file| */
16005   ASCII_code c; /* character being packed */
16006   integer j; /* index into |buffer| or |MP_mem_default| */
16007   if ( n+b-a+1+mem_ext_length>file_name_size )
16008     b=a+file_name_size-n-1-mem_ext_length;
16009   k=0;
16010   for (j=0;j<n;j++) {
16011     append_to_name(xord((int)mp->MP_mem_default[j]));
16012   }
16013   for (j=a;j<b;j++) {
16014     append_to_name(mp->buffer[j]);
16015   }
16016   for (j=mem_default_length-mem_ext_length;
16017       j<mem_default_length;j++) {
16018     append_to_name(xord((int)mp->MP_mem_default[j]));
16019   } 
16020   mp->name_of_file[k]=0;
16021   mp->name_length=k; 
16022 }
16023
16024 @ Here is the only place we use |pack_buffered_name|. This part of the program
16025 becomes active when a ``virgin'' \MP\ is trying to get going, just after
16026 the preliminary initialization, or when the user is substituting another
16027 mem file by typing `\.\&' after the initial `\.{**}' prompt.  The buffer
16028 contains the first line of input in |buffer[loc..(last-1)]|, where
16029 |loc<last| and |buffer[loc]<>" "|.
16030
16031 @<Declarations@>=
16032 boolean mp_open_mem_file (MP mp) ;
16033
16034 @ @c
16035 boolean mp_open_mem_file (MP mp) {
16036   int j; /* the first space after the file name */
16037   if (mp->mem_name!=NULL) {
16038     mp->mem_file = (mp->open_file)(mp->mem_name, "rb", mp_filetype_memfile);
16039     if ( mp->mem_file ) return true;
16040   }
16041   j=loc;
16042   if ( mp->buffer[loc]=='&' ) {
16043     incr(loc); j=loc; mp->buffer[mp->last]=' ';
16044     while ( mp->buffer[j]!=' ' ) incr(j);
16045     mp_pack_buffered_name(mp, 0,loc,j); /* try first without the system file area */
16046     if ( mp_w_open_in(mp, &mp->mem_file) ) goto FOUND;
16047     wake_up_terminal;
16048     wterm_ln("Sorry, I can\'t find that mem file; will try PLAIN.");
16049 @.Sorry, I can't find...@>
16050     update_terminal;
16051   }
16052   /* now pull out all the stops: try for the system \.{plain} file */
16053   mp_pack_buffered_name(mp, mem_default_length-mem_ext_length,0,0);
16054   if ( ! mp_w_open_in(mp, &mp->mem_file) ) {
16055     wake_up_terminal;
16056     wterm_ln("I can\'t find the PLAIN mem file!\n");
16057 @.I can't find PLAIN...@>
16058 @.plain@>
16059     return false;
16060   }
16061 FOUND:
16062   loc=j; return true;
16063 }
16064
16065 @ Operating systems often make it possible to determine the exact name (and
16066 possible version number) of a file that has been opened. The following routine,
16067 which simply makes a \MP\ string from the value of |name_of_file|, should
16068 ideally be changed to deduce the full name of file~|f|, which is the file
16069 most recently opened, if it is possible to do this in a \PASCAL\ program.
16070 @^system dependencies@>
16071
16072 @<Declarations@>=
16073 #define mp_a_make_name_string(A,B)  mp_make_name_string(A)
16074 #define mp_b_make_name_string(A,B)  mp_make_name_string(A)
16075 #define mp_w_make_name_string(A,B)  mp_make_name_string(A)
16076
16077 @ @c 
16078 str_number mp_make_name_string (MP mp) {
16079   int k; /* index into |name_of_file| */
16080   str_room(mp->name_length);
16081   for (k=0;k<mp->name_length;k++) {
16082     append_char(xord((int)mp->name_of_file[k]));
16083   }
16084   return mp_make_string(mp);
16085 }
16086
16087 @ Now let's consider the ``driver''
16088 routines by which \MP\ deals with file names
16089 in a system-independent manner.  First comes a procedure that looks for a
16090 file name in the input by taking the information from the input buffer.
16091 (We can't use |get_next|, because the conversion to tokens would
16092 destroy necessary information.)
16093
16094 This procedure doesn't allow semicolons or percent signs to be part of
16095 file names, because of other conventions of \MP.
16096 {\sl The {\logos METAFONT\/}book} doesn't
16097 use semicolons or percents immediately after file names, but some users
16098 no doubt will find it natural to do so; therefore system-dependent
16099 changes to allow such characters in file names should probably
16100 be made with reluctance, and only when an entire file name that
16101 includes special characters is ``quoted'' somehow.
16102 @^system dependencies@>
16103
16104 @c void mp_scan_file_name (MP mp) { 
16105   mp_begin_name(mp);
16106   while ( mp->buffer[loc]==' ' ) incr(loc);
16107   while (1) { 
16108     if ( (mp->buffer[loc]==';')||(mp->buffer[loc]=='%') ) break;
16109     if ( ! mp_more_name(mp, mp->buffer[loc]) ) break;
16110     incr(loc);
16111   }
16112   mp_end_name(mp);
16113 }
16114
16115 @ Here is another version that takes its input from a string.
16116
16117 @<Declare subroutines for parsing file names@>=
16118 void mp_str_scan_file (MP mp,  str_number s) {
16119   pool_pointer p,q; /* current position and stopping point */
16120   mp_begin_name(mp);
16121   p=mp->str_start[s]; q=str_stop(s);
16122   while ( p<q ){ 
16123     if ( ! mp_more_name(mp, mp->str_pool[p]) ) break;
16124     incr(p);
16125   }
16126   mp_end_name(mp);
16127 }
16128
16129 @ And one that reads from a |char*|.
16130
16131 @<Declare subroutines for parsing file names@>=
16132 void mp_ptr_scan_file (MP mp,  char *s) {
16133   char *p, *q; /* current position and stopping point */
16134   mp_begin_name(mp);
16135   p=s; q=p+strlen(s);
16136   while ( p<q ){ 
16137     if ( ! mp_more_name(mp, *p)) break;
16138     p++;
16139   }
16140   mp_end_name(mp);
16141 }
16142
16143
16144 @ The global variable |job_name| contains the file name that was first
16145 \&{input} by the user. This name is extended by `\.{.log}' and `\.{ps}' and
16146 `\.{.mem}' and `\.{.tfm}' in order to make the names of \MP's output files.
16147
16148 @<Glob...@>=
16149 char *job_name; /* principal file name */
16150 boolean log_opened; /* has the transcript file been opened? */
16151 char *log_name; /* full name of the log file */
16152
16153 @ @<Option variables@>=
16154 char *job_name; /* principal file name */
16155
16156 @ Initially |job_name=NULL|; it becomes nonzero as soon as the true name is known.
16157 We have |job_name=NULL| if and only if the `\.{log}' file has not been opened,
16158 except of course for a short time just after |job_name| has become nonzero.
16159
16160 @<Allocate or ...@>=
16161 mp->job_name=opt->job_name; 
16162 mp->log_opened=false;
16163
16164 @ @<Dealloc variables@>=
16165 xfree(mp->job_name);
16166
16167 @ Here is a routine that manufactures the output file names, assuming that
16168 |job_name<>0|. It ignores and changes the current settings of |cur_area|
16169 and |cur_ext|.
16170
16171 @d pack_cur_name mp_pack_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext)
16172
16173 @<Declarations@>=
16174 void mp_pack_job_name (MP mp, char *s) ;
16175
16176 @ @c void mp_pack_job_name (MP mp, char  *s) { /* |s = ".log"|, |".mem"|, |".ps"|, or .\\{nnn} */
16177   xfree(mp->cur_name); mp->cur_name=xstrdup(mp->job_name);
16178   xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
16179   xfree(mp->cur_ext);  mp->cur_ext=xstrdup(s);
16180   pack_cur_name;
16181 }
16182
16183 @ If some trouble arises when \MP\ tries to open a file, the following
16184 routine calls upon the user to supply another file name. Parameter~|s|
16185 is used in the error message to identify the type of file; parameter~|e|
16186 is the default extension if none is given. Upon exit from the routine,
16187 variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
16188 ready for another attempt at file opening.
16189
16190 @<Declarations@>=
16191 void mp_prompt_file_name (MP mp,char * s, char * e) ;
16192
16193 @ @c void mp_prompt_file_name (MP mp,char * s, char * e) {
16194   size_t k; /* index into |buffer| */
16195   char * saved_cur_name;
16196   if ( mp->interaction==mp_scroll_mode ) 
16197         wake_up_terminal;
16198   if (strcmp(s,"input file name")==0) {
16199         print_err("I can\'t find file `");
16200 @.I can't find file x@>
16201   } else {
16202         print_err("I can\'t write on file `");
16203   }
16204 @.I can't write on file x@>
16205   mp_print_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext); 
16206   mp_print(mp, "'.");
16207   if (strcmp(e,"")==0) 
16208         mp_show_context(mp);
16209   mp_print_nl(mp, "Please type another "); mp_print(mp, s);
16210 @.Please type...@>
16211   if ( mp->interaction<mp_scroll_mode )
16212     mp_fatal_error(mp, "*** (job aborted, file error in nonstop mode)");
16213 @.job aborted, file error...@>
16214   saved_cur_name = xstrdup(mp->cur_name);
16215   clear_terminal; prompt_input(": "); @<Scan file name in the buffer@>;
16216   if (strcmp(mp->cur_ext,"")==0) 
16217         mp->cur_ext=e;
16218   if (strlen(mp->cur_name)==0) {
16219     mp->cur_name=saved_cur_name;
16220   } else {
16221     xfree(saved_cur_name);
16222   }
16223   pack_cur_name;
16224 }
16225
16226 @ @<Scan file name in the buffer@>=
16227
16228   mp_begin_name(mp); k=mp->first;
16229   while ( (mp->buffer[k]==' ')&&(k<mp->last) ) incr(k);
16230   while (1) { 
16231     if ( k==mp->last ) break;
16232     if ( ! mp_more_name(mp, mp->buffer[k]) ) break;
16233     incr(k);
16234   }
16235   mp_end_name(mp);
16236 }
16237
16238 @ The |open_log_file| routine is used to open the transcript file and to help
16239 it catch up to what has previously been printed on the terminal.
16240
16241 @c void mp_open_log_file (MP mp) {
16242   int old_setting; /* previous |selector| setting */
16243   int k; /* index into |months| and |buffer| */
16244   int l; /* end of first input line */
16245   integer m; /* the current month */
16246   char *months="JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"; 
16247     /* abbreviations of month names */
16248   old_setting=mp->selector;
16249   if ( mp->job_name==NULL ) {
16250      mp->job_name=xstrdup("mpout");
16251   }
16252   mp_pack_job_name(mp,".log");
16253   while ( ! mp_a_open_out(mp, &mp->log_file, mp_filetype_log) ) {
16254     @<Try to get a different log file name@>;
16255   }
16256   mp->log_name=xstrdup(mp->name_of_file);
16257   mp->selector=log_only; mp->log_opened=true;
16258   @<Print the banner line, including the date and time@>;
16259   mp->input_stack[mp->input_ptr]=mp->cur_input; 
16260     /* make sure bottom level is in memory */
16261   mp_print_nl(mp, "**");
16262 @.**@>
16263   l=mp->input_stack[0].limit_field-1; /* last position of first line */
16264   for (k=0;k<=l;k++) mp_print_str(mp, mp->buffer[k]);
16265   mp_print_ln(mp); /* now the transcript file contains the first line of input */
16266   mp->selector=old_setting+2; /* |log_only| or |term_and_log| */
16267 }
16268
16269 @ @<Dealloc variables@>=
16270 xfree(mp->log_name);
16271
16272 @ Sometimes |open_log_file| is called at awkward moments when \MP\ is
16273 unable to print error messages or even to |show_context|.
16274 The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
16275 routine will not be invoked because |log_opened| will be false.
16276
16277 The normal idea of |mp_batch_mode| is that nothing at all should be written
16278 on the terminal. However, in the unusual case that
16279 no log file could be opened, we make an exception and allow
16280 an explanatory message to be seen.
16281
16282 Incidentally, the program always refers to the log file as a `\.{transcript
16283 file}', because some systems cannot use the extension `\.{.log}' for
16284 this file.
16285
16286 @<Try to get a different log file name@>=
16287 {  
16288   mp->selector=term_only;
16289   mp_prompt_file_name(mp, "transcript file name",".log");
16290 }
16291
16292 @ @<Print the banner...@>=
16293
16294   wlog(banner);
16295   mp_print(mp, mp->mem_ident); mp_print(mp, "  ");
16296   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_day])); 
16297   mp_print_char(mp, ' ');
16298   m=mp_round_unscaled(mp, mp->internal[mp_month]);
16299   for (k=3*m-3;k<3*m;k++) { wlog_chr(months[k]); }
16300   mp_print_char(mp, ' '); 
16301   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_year])); 
16302   mp_print_char(mp, ' ');
16303   m=mp_round_unscaled(mp, mp->internal[mp_time]);
16304   mp_print_dd(mp, m / 60); mp_print_char(mp, ':'); mp_print_dd(mp, m % 60);
16305 }
16306
16307 @ The |try_extension| function tries to open an input file determined by
16308 |cur_name|, |cur_area|, and the argument |ext|.  It returns |false| if it
16309 can't find the file in |cur_area| or the appropriate system area.
16310
16311 @c boolean mp_try_extension (MP mp,char *ext) { 
16312   mp_pack_file_name(mp, mp->cur_name,mp->cur_area, ext);
16313   in_name=xstrdup(mp->cur_name); 
16314   in_area=xstrdup(mp->cur_area);
16315   if ( mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16316     return true;
16317   } else { 
16318     if (strcmp(ext,".mf")==0 ) in_area=xstrdup(MF_area);
16319     else in_area=xstrdup(MP_area);
16320     mp_pack_file_name(mp, mp->cur_name,in_area,ext);
16321     return mp_a_open_in(mp, &cur_file, mp_filetype_program);
16322   }
16323   return false;
16324 }
16325
16326 @ Let's turn now to the procedure that is used to initiate file reading
16327 when an `\.{input}' command is being processed.
16328
16329 @c void mp_start_input (MP mp) { /* \MP\ will \.{input} something */
16330   char *fname = NULL;
16331   @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>;
16332   while (1) { 
16333     mp_begin_file_reading(mp); /* set up |cur_file| and new level of input */
16334     if ( strlen(mp->cur_ext)==0 ) {
16335       if ( mp_try_extension(mp, ".mp") ) break;
16336       else if ( mp_try_extension(mp, "") ) break;
16337       else if ( mp_try_extension(mp, ".mf") ) break;
16338       /* |else do_nothing; | */
16339     } else if ( mp_try_extension(mp, mp->cur_ext) ) {
16340       break;
16341     }
16342     mp_end_file_reading(mp); /* remove the level that didn't work */
16343     mp_prompt_file_name(mp, "input file name","");
16344   }
16345   name=mp_a_make_name_string(mp, cur_file);
16346   fname = xstrdup(mp->name_of_file);
16347   if ( mp->job_name==NULL ) {
16348     mp->job_name=xstrdup(mp->cur_name); 
16349     mp_open_log_file(mp);
16350   } /* |open_log_file| doesn't |show_context|, so |limit|
16351         and |loc| needn't be set to meaningful values yet */
16352   if ( ((int)mp->term_offset+(int)strlen(fname)) > (mp->max_print_line-2)) mp_print_ln(mp);
16353   else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
16354   mp_print_char(mp, '('); incr(mp->open_parens); mp_print(mp, fname); 
16355   xfree(fname);
16356   update_terminal;
16357   @<Flush |name| and replace it with |cur_name| if it won't be needed@>;
16358   @<Read the first line of the new file@>;
16359 }
16360
16361 @ This code should be omitted if |a_make_name_string| returns something other
16362 than just a copy of its argument and the full file name is needed for opening
16363 \.{MPX} files or implementing the switch-to-editor option.
16364 @^system dependencies@>
16365
16366 @<Flush |name| and replace it with |cur_name| if it won't be needed@>=
16367 mp_flush_string(mp, name); name=rts(mp->cur_name); xfree(mp->cur_name)
16368
16369 @ If the file is empty, it is considered to contain a single blank line,
16370 so there is no need to test the return value.
16371
16372 @<Read the first line...@>=
16373
16374   line=1;
16375   (void)mp_input_ln(mp, cur_file ); 
16376   mp_firm_up_the_line(mp);
16377   mp->buffer[limit]='%'; mp->first=limit+1; loc=start;
16378 }
16379
16380 @ @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>=
16381 while ( token_state &&(loc==null) ) mp_end_token_list(mp);
16382 if ( token_state ) { 
16383   print_err("File names can't appear within macros");
16384 @.File names can't...@>
16385   help3("Sorry...I've converted what follows to tokens,")
16386     ("possibly garbaging the name you gave.")
16387     ("Please delete the tokens and insert the name again.");
16388   mp_error(mp);
16389 }
16390 if ( file_state ) {
16391   mp_scan_file_name(mp);
16392 } else { 
16393    xfree(mp->cur_name); mp->cur_name=xstrdup(""); 
16394    xfree(mp->cur_ext);  mp->cur_ext =xstrdup(""); 
16395    xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
16396 }
16397
16398 @ Sometimes we need to deal with two file names at once.  This procedure
16399 copies the given string into a special array for an old file name.
16400
16401 @c void mp_copy_old_name (MP mp,str_number s) {
16402   integer k; /* number of positions filled in |old_file_name| */
16403   pool_pointer j; /* index into |str_pool| */
16404   k=0;
16405   for (j=mp->str_start[s];j<=str_stop(s)-1;j++) { 
16406     incr(k);
16407     if ( k<=file_name_size ) 
16408       mp->old_file_name[k]=xchr(mp->str_pool[j]);
16409   }
16410   mp->old_file_name[++k] = 0;
16411 }
16412
16413 @ @<Glob...@>=
16414 char old_file_name[file_name_size+1];  /* analogous to |name_of_file| */
16415
16416 @ The following simple routine starts reading the \.{MPX} file associated
16417 with the current input file.
16418
16419 @c void mp_start_mpx_input (MP mp) {
16420   mp_pack_file_name(mp, in_name, in_area, ".mpx");
16421   @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16422     |goto not_found| if there is a problem@>;
16423   mp_begin_file_reading(mp);
16424   if ( ! mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16425     mp_end_file_reading(mp);
16426     goto NOT_FOUND;
16427   }
16428   name=mp_a_make_name_string(mp, cur_file);
16429   mp->mpx_name[index]=name; add_str_ref(name);
16430   @<Read the first line of the new file@>;
16431   return;
16432 NOT_FOUND: 
16433     @<Explain that the \.{MPX} file can't be read and |succumb|@>;
16434 }
16435
16436 @ This should ideally be changed to do whatever is necessary to create the
16437 \.{MPX} file given by |name_of_file| if it does not exist or if it is out
16438 of date.  This requires invoking \.{MPtoTeX} on the |old_file_name| and passing
16439 the results through \TeX\ and \.{DVItoMP}.  (It is possible to use a
16440 completely different typesetting program if suitable postprocessor is
16441 available to perform the function of \.{DVItoMP}.)
16442 @^system dependencies@>
16443
16444 @ @<Exported types@>=
16445 typedef int (*mp_run_make_mpx_command)(MP mp, char *origname, char *mtxname);
16446
16447 @ @<Glob...@>=
16448 mp_run_make_mpx_command run_make_mpx;
16449
16450 @ @<Option variables@>=
16451 mp_run_make_mpx_command run_make_mpx;
16452
16453 @ @<Allocate or initialize ...@>=
16454 set_callback_option(run_make_mpx);
16455
16456 @ @<Internal library declarations@>=
16457 int mp_run_make_mpx (MP mp, char *origname, char *mtxname);
16458
16459 @ The default does nothing.
16460 @c 
16461 int mp_run_make_mpx (MP mp, char *origname, char *mtxname) {
16462   if (mp && origname && mtxname) /* for -W */
16463     return false;
16464   return false;
16465 }
16466
16467
16468
16469 @ @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16470   |goto not_found| if there is a problem@>=
16471 mp_copy_old_name(mp, name);
16472 if (!(mp->run_make_mpx)(mp, mp->old_file_name, mp->name_of_file))
16473    goto NOT_FOUND
16474
16475 @ @<Explain that the \.{MPX} file can't be read and |succumb|@>=
16476 if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16477 mp_print_nl(mp, ">> ");
16478 mp_print(mp, mp->old_file_name);
16479 mp_print_nl(mp, ">> ");
16480 mp_print(mp, mp->name_of_file);
16481 mp_print_nl(mp, "! Unable to make mpx file");
16482 help4("The two files given above are one of your source files")
16483   ("and an auxiliary file I need to read to find out what your")
16484   ("btex..etex blocks mean. If you don't know why I had trouble,")
16485   ("try running it manually through MPtoTeX, TeX, and DVItoMP");
16486 succumb;
16487
16488 @ The last file-opening commands are for files accessed via the \&{readfrom}
16489 @:read_from_}{\&{readfrom} primitive@>
16490 operator and the \&{write} command.  Such files are stored in separate arrays.
16491 @:write_}{\&{write} primitive@>
16492
16493 @<Types in the outer block@>=
16494 typedef unsigned int readf_index; /* |0..max_read_files| */
16495 typedef unsigned int write_index;  /* |0..max_write_files| */
16496
16497 @ @<Glob...@>=
16498 readf_index max_read_files; /* maximum number of simultaneously open \&{readfrom} files */
16499 void ** rd_file; /* \&{readfrom} files */
16500 char ** rd_fname; /* corresponding file name or 0 if file not open */
16501 readf_index read_files; /* number of valid entries in the above arrays */
16502 write_index max_write_files; /* maximum number of simultaneously open \&{write} */
16503 void ** wr_file; /* \&{write} files */
16504 char ** wr_fname; /* corresponding file name or 0 if file not open */
16505 write_index write_files; /* number of valid entries in the above arrays */
16506
16507 @ @<Allocate or initialize ...@>=
16508 mp->max_read_files=8;
16509 mp->rd_file = xmalloc((mp->max_read_files+1),sizeof(void *));
16510 mp->rd_fname = xmalloc((mp->max_read_files+1),sizeof(char *));
16511 memset(mp->rd_fname, 0, sizeof(char *)*(mp->max_read_files+1));
16512 mp->read_files=0;
16513 mp->max_write_files=8;
16514 mp->wr_file = xmalloc((mp->max_write_files+1),sizeof(void *));
16515 mp->wr_fname = xmalloc((mp->max_write_files+1),sizeof(char *));
16516 memset(mp->wr_fname, 0, sizeof(char *)*(mp->max_write_files+1));
16517 mp->write_files=0;
16518
16519
16520 @ This routine starts reading the file named by string~|s| without setting
16521 |loc|, |limit|, or |name|.  It returns |false| if the file is empty or cannot
16522 be opened.  Otherwise it updates |rd_file[n]| and |rd_fname[n]|.
16523
16524 @c boolean mp_start_read_input (MP mp,char *s, readf_index  n) {
16525   mp_ptr_scan_file(mp, s);
16526   pack_cur_name;
16527   mp_begin_file_reading(mp);
16528   if ( ! mp_a_open_in(mp, &mp->rd_file[n], (mp_filetype_text+n)) ) 
16529         goto NOT_FOUND;
16530   if ( ! mp_input_ln(mp, mp->rd_file[n] ) ) {
16531     (mp->close_file)(mp->rd_file[n]); 
16532         goto NOT_FOUND; 
16533   }
16534   mp->rd_fname[n]=xstrdup(mp->name_of_file);
16535   return true;
16536 NOT_FOUND: 
16537   mp_end_file_reading(mp);
16538   return false;
16539 }
16540
16541 @ Open |wr_file[n]| using file name~|s| and update |wr_fname[n]|.
16542
16543 @<Declarations@>=
16544 void mp_open_write_file (MP mp, char *s, readf_index  n) ;
16545
16546 @ @c void mp_open_write_file (MP mp,char *s, readf_index  n) {
16547   mp_ptr_scan_file(mp, s);
16548   pack_cur_name;
16549   while ( ! mp_a_open_out(mp, &mp->wr_file[n], (mp_filetype_text+n)) )
16550     mp_prompt_file_name(mp, "file name for write output","");
16551   mp->wr_fname[n]=xstrdup(mp->name_of_file);
16552 }
16553
16554
16555 @* \[36] Introduction to the parsing routines.
16556 We come now to the central nervous system that sparks many of \MP's activities.
16557 By evaluating expressions, from their primary constituents to ever larger
16558 subexpressions, \MP\ builds the structures that ultimately define complete
16559 pictures or fonts of type.
16560
16561 Four mutually recursive subroutines are involved in this process: We call them
16562 $$\hbox{|scan_primary|, |scan_secondary|, |scan_tertiary|,
16563 and |scan_expression|.}$$
16564 @^recursion@>
16565 Each of them is parameterless and begins with the first token to be scanned
16566 already represented in |cur_cmd|, |cur_mod|, and |cur_sym|. After execution,
16567 the value of the primary or secondary or tertiary or expression that was
16568 found will appear in the global variables |cur_type| and |cur_exp|. The
16569 token following the expression will be represented in |cur_cmd|, |cur_mod|,
16570 and |cur_sym|.
16571
16572 Technically speaking, the parsing algorithms are ``LL(1),'' more or less;
16573 backup mechanisms have been added in order to provide reasonable error
16574 recovery.
16575
16576 @<Glob...@>=
16577 small_number cur_type; /* the type of the expression just found */
16578 integer cur_exp; /* the value of the expression just found */
16579
16580 @ @<Set init...@>=
16581 mp->cur_exp=0;
16582
16583 @ Many different kinds of expressions are possible, so it is wise to have
16584 precise descriptions of what |cur_type| and |cur_exp| mean in all cases:
16585
16586 \smallskip\hang
16587 |cur_type=mp_vacuous| means that this expression didn't turn out to have a
16588 value at all, because it arose from a \&{begingroup}$\,\ldots\,$\&{endgroup}
16589 construction in which there was no expression before the \&{endgroup}.
16590 In this case |cur_exp| has some irrelevant value.
16591
16592 \smallskip\hang
16593 |cur_type=mp_boolean_type| means that |cur_exp| is either |true_code|
16594 or |false_code|.
16595
16596 \smallskip\hang
16597 |cur_type=mp_unknown_boolean| means that |cur_exp| points to a capsule
16598 node that is in the ring of variables equivalent
16599 to at least one undefined boolean variable.
16600
16601 \smallskip\hang
16602 |cur_type=mp_string_type| means that |cur_exp| is a string number (i.e., an
16603 integer in the range |0<=cur_exp<str_ptr|). That string's reference count
16604 includes this particular reference.
16605
16606 \smallskip\hang
16607 |cur_type=mp_unknown_string| means that |cur_exp| points to a capsule
16608 node that is in the ring of variables equivalent
16609 to at least one undefined string variable.
16610
16611 \smallskip\hang
16612 |cur_type=mp_pen_type| means that |cur_exp| points to a node in a pen.  Nobody
16613 else points to any of the nodes in this pen.  The pen may be polygonal or
16614 elliptical.
16615
16616 \smallskip\hang
16617 |cur_type=mp_unknown_pen| means that |cur_exp| points to a capsule
16618 node that is in the ring of variables equivalent
16619 to at least one undefined pen variable.
16620
16621 \smallskip\hang
16622 |cur_type=mp_path_type| means that |cur_exp| points to a the first node of
16623 a path; nobody else points to this particular path. The control points of
16624 the path will have been chosen.
16625
16626 \smallskip\hang
16627 |cur_type=mp_unknown_path| means that |cur_exp| points to a capsule
16628 node that is in the ring of variables equivalent
16629 to at least one undefined path variable.
16630
16631 \smallskip\hang
16632 |cur_type=mp_picture_type| means that |cur_exp| points to an edge header node.
16633 There may be other pointers to this particular set of edges.  The header node
16634 contains a reference count that includes this particular reference.
16635
16636 \smallskip\hang
16637 |cur_type=mp_unknown_picture| means that |cur_exp| points to a capsule
16638 node that is in the ring of variables equivalent
16639 to at least one undefined picture variable.
16640
16641 \smallskip\hang
16642 |cur_type=mp_transform_type| means that |cur_exp| points to a |mp_transform_type|
16643 capsule node. The |value| part of this capsule
16644 points to a transform node that contains six numeric values,
16645 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16646
16647 \smallskip\hang
16648 |cur_type=mp_color_type| means that |cur_exp| points to a |color_type|
16649 capsule node. The |value| part of this capsule
16650 points to a color node that contains three numeric values,
16651 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16652
16653 \smallskip\hang
16654 |cur_type=mp_cmykcolor_type| means that |cur_exp| points to a |mp_cmykcolor_type|
16655 capsule node. The |value| part of this capsule
16656 points to a color node that contains four numeric values,
16657 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16658
16659 \smallskip\hang
16660 |cur_type=mp_pair_type| means that |cur_exp| points to a capsule
16661 node whose type is |mp_pair_type|. The |value| part of this capsule
16662 points to a pair node that contains two numeric values,
16663 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16664
16665 \smallskip\hang
16666 |cur_type=mp_known| means that |cur_exp| is a |scaled| value.
16667
16668 \smallskip\hang
16669 |cur_type=mp_dependent| means that |cur_exp| points to a capsule node whose type
16670 is |dependent|. The |dep_list| field in this capsule points to the associated
16671 dependency list.
16672
16673 \smallskip\hang
16674 |cur_type=mp_proto_dependent| means that |cur_exp| points to a |mp_proto_dependent|
16675 capsule node. The |dep_list| field in this capsule
16676 points to the associated dependency list.
16677
16678 \smallskip\hang
16679 |cur_type=independent| means that |cur_exp| points to a capsule node
16680 whose type is |independent|. This somewhat unusual case can arise, for
16681 example, in the expression
16682 `$x+\&{begingroup}\penalty0\,\&{string}\,x; 0\,\&{endgroup}$'.
16683
16684 \smallskip\hang
16685 |cur_type=mp_token_list| means that |cur_exp| points to a linked list of
16686 tokens. This case arises only on the left-hand side of an assignment
16687 (`\.{:=}') operation, under very special circumstances.
16688
16689 \smallskip\noindent
16690 The possible settings of |cur_type| have been listed here in increasing
16691 numerical order. Notice that |cur_type| will never be |mp_numeric_type| or
16692 |suffixed_macro| or |mp_unsuffixed_macro|, although variables of those types
16693 are allowed.  Conversely, \MP\ has no variables of type |mp_vacuous| or
16694 |token_list|.
16695
16696 @ Capsules are two-word nodes that have a similar meaning
16697 to |cur_type| and |cur_exp|. Such nodes have |name_type=capsule|
16698 and |link<=mp_void|; and their |type| field is one of the possibilities for
16699 |cur_type| listed above.
16700
16701 The |value| field of a capsule is, in most cases, the value that
16702 corresponds to its |type|, as |cur_exp| corresponds to |cur_type|.
16703 However, when |cur_exp| would point to a capsule,
16704 no extra layer of indirection is present; the |value|
16705 field is what would have been called |value(cur_exp)| if it had not been
16706 encapsulated.  Furthermore, if the type is |dependent| or
16707 |mp_proto_dependent|, the |value| field of a capsule is replaced by
16708 |dep_list| and |prev_dep| fields, since dependency lists in capsules are
16709 always part of the general |dep_list| structure.
16710
16711 The |get_x_next| routine is careful not to change the values of |cur_type|
16712 and |cur_exp| when it gets an expanded token. However, |get_x_next| might
16713 call a macro, which might parse an expression, which might execute lots of
16714 commands in a group; hence it's possible that |cur_type| might change
16715 from, say, |mp_unknown_boolean| to |mp_boolean_type|, or from |dependent| to
16716 |known| or |independent|, during the time |get_x_next| is called. The
16717 programs below are careful to stash sensitive intermediate results in
16718 capsules, so that \MP's generality doesn't cause trouble.
16719
16720 Here's a procedure that illustrates these conventions. It takes
16721 the contents of $(|cur_type|\kern-.3pt,|cur_exp|\kern-.3pt)$
16722 and stashes them away in a
16723 capsule. It is not used when |cur_type=mp_token_list|.
16724 After the operation, |cur_type=mp_vacuous|; hence there is no need to
16725 copy path lists or to update reference counts, etc.
16726
16727 The special link |mp_void| is put on the capsule returned by
16728 |stash_cur_exp|, because this procedure is used to store macro parameters
16729 that must be easily distinguishable from token lists.
16730
16731 @<Declare the stashing/unstashing routines@>=
16732 pointer mp_stash_cur_exp (MP mp) {
16733   pointer p; /* the capsule that will be returned */
16734   switch (mp->cur_type) {
16735   case unknown_types:
16736   case mp_transform_type:
16737   case mp_color_type:
16738   case mp_pair_type:
16739   case mp_dependent:
16740   case mp_proto_dependent:
16741   case mp_independent: 
16742   case mp_cmykcolor_type:
16743     p=mp->cur_exp;
16744     break;
16745   default: 
16746     p=mp_get_node(mp, value_node_size); name_type(p)=mp_capsule;
16747     type(p)=mp->cur_type; value(p)=mp->cur_exp;
16748     break;
16749   }
16750   mp->cur_type=mp_vacuous; link(p)=mp_void; 
16751   return p;
16752 }
16753
16754 @ The inverse of |stash_cur_exp| is the following procedure, which
16755 deletes an unnecessary capsule and puts its contents into |cur_type|
16756 and |cur_exp|.
16757
16758 The program steps of \MP\ can be divided into two categories: those in
16759 which |cur_type| and |cur_exp| are ``alive'' and those in which they are
16760 ``dead,'' in the sense that |cur_type| and |cur_exp| contain relevant
16761 information or not. It's important not to ignore them when they're alive,
16762 and it's important not to pay attention to them when they're dead.
16763
16764 There's also an intermediate category: If |cur_type=mp_vacuous|, then
16765 |cur_exp| is irrelevant, hence we can proceed without caring if |cur_type|
16766 and |cur_exp| are alive or dead. In such cases we say that |cur_type|
16767 and |cur_exp| are {\sl dormant}. It is permissible to call |get_x_next|
16768 only when they are alive or dormant.
16769
16770 The \\{stash} procedure above assumes that |cur_type| and |cur_exp|
16771 are alive or dormant. The \\{unstash} procedure assumes that they are
16772 dead or dormant; it resuscitates them.
16773
16774 @<Declare the stashing/unstashing...@>=
16775 void mp_unstash_cur_exp (MP mp,pointer p) ;
16776
16777 @ @c
16778 void mp_unstash_cur_exp (MP mp,pointer p) { 
16779   mp->cur_type=type(p);
16780   switch (mp->cur_type) {
16781   case unknown_types:
16782   case mp_transform_type:
16783   case mp_color_type:
16784   case mp_pair_type:
16785   case mp_dependent: 
16786   case mp_proto_dependent:
16787   case mp_independent:
16788   case mp_cmykcolor_type: 
16789     mp->cur_exp=p;
16790     break;
16791   default:
16792     mp->cur_exp=value(p);
16793     mp_free_node(mp, p,value_node_size);
16794     break;
16795   }
16796 }
16797
16798 @ The following procedure prints the values of expressions in an
16799 abbreviated format. If its first parameter |p| is null, the value of
16800 |(cur_type,cur_exp)| is displayed; otherwise |p| should be a capsule
16801 containing the desired value. The second parameter controls the amount of
16802 output. If it is~0, dependency lists will be abbreviated to
16803 `\.{linearform}' unless they consist of a single term.  If it is greater
16804 than~1, complicated structures (pens, pictures, and paths) will be displayed
16805 in full.
16806
16807 @<Declare subroutines for printing expressions@>=
16808 @<Declare the procedure called |print_dp|@>;
16809 @<Declare the stashing/unstashing routines@>;
16810 void mp_print_exp (MP mp,pointer p, small_number verbosity) {
16811   boolean restore_cur_exp; /* should |cur_exp| be restored? */
16812   small_number t; /* the type of the expression */
16813   pointer q; /* a big node being displayed */
16814   integer v=0; /* the value of the expression */
16815   if ( p!=null ) {
16816     restore_cur_exp=false;
16817   } else { 
16818     p=mp_stash_cur_exp(mp); restore_cur_exp=true;
16819   }
16820   t=type(p);
16821   if ( t<mp_dependent ) v=value(p); else if ( t<mp_independent ) v=dep_list(p);
16822   @<Print an abbreviated value of |v| with format depending on |t|@>;
16823   if ( restore_cur_exp ) mp_unstash_cur_exp(mp, p);
16824 }
16825
16826 @ @<Print an abbreviated value of |v| with format depending on |t|@>=
16827 switch (t) {
16828 case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
16829 case mp_boolean_type:
16830   if ( v==true_code ) mp_print(mp, "true"); else mp_print(mp, "false");
16831   break;
16832 case unknown_types: case mp_numeric_type:
16833   @<Display a variable that's been declared but not defined@>;
16834   break;
16835 case mp_string_type:
16836   mp_print_char(mp, '"'); mp_print_str(mp, v); mp_print_char(mp, '"');
16837   break;
16838 case mp_pen_type: case mp_path_type: case mp_picture_type:
16839   @<Display a complex type@>;
16840   break;
16841 case mp_transform_type: case mp_color_type: case mp_pair_type: case mp_cmykcolor_type:
16842   if ( v==null ) mp_print_type(mp, t);
16843   else @<Display a big node@>;
16844   break;
16845 case mp_known:mp_print_scaled(mp, v); break;
16846 case mp_dependent: case mp_proto_dependent:
16847   mp_print_dp(mp, t,v,verbosity);
16848   break;
16849 case mp_independent:mp_print_variable_name(mp, p); break;
16850 default: mp_confusion(mp, "exp"); break;
16851 @:this can't happen exp}{\quad exp@>
16852 }
16853
16854 @ @<Display a big node@>=
16855
16856   mp_print_char(mp, '('); q=v+mp->big_node_size[t];
16857   do {  
16858     if ( type(v)==mp_known ) mp_print_scaled(mp, value(v));
16859     else if ( type(v)==mp_independent ) mp_print_variable_name(mp, v);
16860     else mp_print_dp(mp, type(v),dep_list(v),verbosity);
16861     v=v+2;
16862     if ( v!=q ) mp_print_char(mp, ',');
16863   } while (v!=q);
16864   mp_print_char(mp, ')');
16865 }
16866
16867 @ Values of type \&{picture}, \&{path}, and \&{pen} are displayed verbosely
16868 in the log file only, unless the user has given a positive value to
16869 \\{tracingonline}.
16870
16871 @<Display a complex type@>=
16872 if ( verbosity<=1 ) {
16873   mp_print_type(mp, t);
16874 } else { 
16875   if ( mp->selector==term_and_log )
16876    if ( mp->internal[mp_tracing_online]<=0 ) {
16877     mp->selector=term_only;
16878     mp_print_type(mp, t); mp_print(mp, " (see the transcript file)");
16879     mp->selector=term_and_log;
16880   };
16881   switch (t) {
16882   case mp_pen_type:mp_print_pen(mp, v,"",false); break;
16883   case mp_path_type:mp_print_path(mp, v,"",false); break;
16884   case mp_picture_type:mp_print_edges(mp, v,"",false); break;
16885   } /* there are no other cases */
16886 }
16887
16888 @ @<Declare the procedure called |print_dp|@>=
16889 void mp_print_dp (MP mp,small_number t, pointer p, 
16890                   small_number verbosity)  {
16891   pointer q; /* the node following |p| */
16892   q=link(p);
16893   if ( (info(q)==null) || (verbosity>0) ) mp_print_dependency(mp, p,t);
16894   else mp_print(mp, "linearform");
16895 }
16896
16897 @ The displayed name of a variable in a ring will not be a capsule unless
16898 the ring consists entirely of capsules.
16899
16900 @<Display a variable that's been declared but not defined@>=
16901 { mp_print_type(mp, t);
16902 if ( v!=null )
16903   { mp_print_char(mp, ' ');
16904   while ( (name_type(v)==mp_capsule) && (v!=p) ) v=value(v);
16905   mp_print_variable_name(mp, v);
16906   };
16907 }
16908
16909 @ When errors are detected during parsing, it is often helpful to
16910 display an expression just above the error message, using |exp_err|
16911 or |disp_err| instead of |print_err|.
16912
16913 @d exp_err(A) mp_disp_err(mp, null,(A)) /* displays the current expression */
16914
16915 @<Declare subroutines for printing expressions@>=
16916 void mp_disp_err (MP mp,pointer p, char *s) { 
16917   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16918   mp_print_nl(mp, ">> ");
16919 @.>>@>
16920   mp_print_exp(mp, p,1); /* ``medium verbose'' printing of the expression */
16921   if (strlen(s)) { 
16922     mp_print_nl(mp, "! "); mp_print(mp, s);
16923 @.!\relax@>
16924   }
16925 }
16926
16927 @ If |cur_type| and |cur_exp| contain relevant information that should
16928 be recycled, we will use the following procedure, which changes |cur_type|
16929 to |known| and stores a given value in |cur_exp|. We can think of |cur_type|
16930 and |cur_exp| as either alive or dormant after this has been done,
16931 because |cur_exp| will not contain a pointer value.
16932
16933 @ @c void mp_flush_cur_exp (MP mp,scaled v) { 
16934   switch (mp->cur_type) {
16935   case unknown_types: case mp_transform_type: case mp_color_type: case mp_pair_type:
16936   case mp_dependent: case mp_proto_dependent: case mp_independent: case mp_cmykcolor_type:
16937     mp_recycle_value(mp, mp->cur_exp); 
16938     mp_free_node(mp, mp->cur_exp,value_node_size);
16939     break;
16940   case mp_string_type:
16941     delete_str_ref(mp->cur_exp); break;
16942   case mp_pen_type: case mp_path_type: 
16943     mp_toss_knot_list(mp, mp->cur_exp); break;
16944   case mp_picture_type:
16945     delete_edge_ref(mp->cur_exp); break;
16946   default: 
16947     break;
16948   }
16949   mp->cur_type=mp_known; mp->cur_exp=v;
16950 }
16951
16952 @ There's a much more general procedure that is capable of releasing
16953 the storage associated with any two-word value packet.
16954
16955 @<Declare the recycling subroutines@>=
16956 void mp_recycle_value (MP mp,pointer p) ;
16957
16958 @ @c void mp_recycle_value (MP mp,pointer p) {
16959   small_number t; /* a type code */
16960   integer vv; /* another value */
16961   pointer q,r,s,pp; /* link manipulation registers */
16962   integer v=0; /* a value */
16963   t=type(p);
16964   if ( t<mp_dependent ) v=value(p);
16965   switch (t) {
16966   case undefined: case mp_vacuous: case mp_boolean_type: case mp_known:
16967   case mp_numeric_type:
16968     break;
16969   case unknown_types:
16970     mp_ring_delete(mp, p); break;
16971   case mp_string_type:
16972     delete_str_ref(v); break;
16973   case mp_path_type: case mp_pen_type:
16974     mp_toss_knot_list(mp, v); break;
16975   case mp_picture_type:
16976     delete_edge_ref(v); break;
16977   case mp_cmykcolor_type: case mp_pair_type: case mp_color_type:
16978   case mp_transform_type:
16979     @<Recycle a big node@>; break; 
16980   case mp_dependent: case mp_proto_dependent:
16981     @<Recycle a dependency list@>; break;
16982   case mp_independent:
16983     @<Recycle an independent variable@>; break;
16984   case mp_token_list: case mp_structured:
16985     mp_confusion(mp, "recycle"); break;
16986 @:this can't happen recycle}{\quad recycle@>
16987   case mp_unsuffixed_macro: case mp_suffixed_macro:
16988     mp_delete_mac_ref(mp, value(p)); break;
16989   } /* there are no other cases */
16990   type(p)=undefined;
16991 }
16992
16993 @ @<Recycle a big node@>=
16994 if ( v!=null ){ 
16995   q=v+mp->big_node_size[t];
16996   do {  
16997     q=q-2; mp_recycle_value(mp, q);
16998   } while (q!=v);
16999   mp_free_node(mp, v,mp->big_node_size[t]);
17000 }
17001
17002 @ @<Recycle a dependency list@>=
17003
17004   q=dep_list(p);
17005   while ( info(q)!=null ) q=link(q);
17006   link(prev_dep(p))=link(q);
17007   prev_dep(link(q))=prev_dep(p);
17008   link(q)=null; mp_flush_node_list(mp, dep_list(p));
17009 }
17010
17011 @ When an independent variable disappears, it simply fades away, unless
17012 something depends on it. In the latter case, a dependent variable whose
17013 coefficient of dependence is maximal will take its place.
17014 The relevant algorithm is due to Ignacio~A. Zabala, who implemented it
17015 as part of his Ph.D. thesis (Stanford University, December 1982).
17016 @^Zabala Salelles, Ignacio Andres@>
17017
17018 For example, suppose that variable $x$ is being recycled, and that the
17019 only variables depending on~$x$ are $y=2x+a$ and $z=x+b$. In this case
17020 we want to make $y$ independent and $z=.5y-.5a+b$; no other variables
17021 will depend on~$y$. If $\\{tracingequations}>0$ in this situation,
17022 we will print `\.{\#\#\# -2x=-y+a}'.
17023
17024 There's a slight complication, however: An independent variable $x$
17025 can occur both in dependency lists and in proto-dependency lists.
17026 This makes it necessary to be careful when deciding which coefficient
17027 is maximal.
17028
17029 Furthermore, this complication is not so slight when
17030 a proto-dependent variable is chosen to become independent. For example,
17031 suppose that $y=2x+100a$ is proto-dependent while $z=x+b$ is dependent;
17032 then we must change $z=.5y-50a+b$ to a proto-dependency, because of the
17033 large coefficient `50'.
17034
17035 In order to deal with these complications without wasting too much time,
17036 we shall link together the occurrences of~$x$ among all the linear
17037 dependencies, maintaining separate lists for the dependent and
17038 proto-dependent cases.
17039
17040 @<Recycle an independent variable@>=
17041
17042   mp->max_c[mp_dependent]=0; mp->max_c[mp_proto_dependent]=0;
17043   mp->max_link[mp_dependent]=null; mp->max_link[mp_proto_dependent]=null;
17044   q=link(dep_head);
17045   while ( q!=dep_head ) { 
17046     s=value_loc(q); /* now |link(s)=dep_list(q)| */
17047     while (1) { 
17048       r=link(s);
17049       if ( info(r)==null ) break;;
17050       if ( info(r)!=p ) { 
17051        s=r;
17052       } else  { 
17053         t=type(q); link(s)=link(r); info(r)=q;
17054         if ( abs(value(r))>mp->max_c[t] ) {
17055           @<Record a new maximum coefficient of type |t|@>;
17056         } else { 
17057           link(r)=mp->max_link[t]; mp->max_link[t]=r;
17058         }
17059       }
17060     }   
17061     q=link(r);
17062   }
17063   if ( (mp->max_c[mp_dependent]>0)||(mp->max_c[mp_proto_dependent]>0) ) {
17064     @<Choose a dependent variable to take the place of the disappearing
17065     independent variable, and change all remaining dependencies
17066     accordingly@>;
17067   }
17068 }
17069
17070 @ The code for independency removal makes use of three two-word arrays.
17071
17072 @<Glob...@>=
17073 integer max_c[mp_proto_dependent+1];  /* max coefficient magnitude */
17074 pointer max_ptr[mp_proto_dependent+1]; /* where |p| occurs with |max_c| */
17075 pointer max_link[mp_proto_dependent+1]; /* other occurrences of |p| */
17076
17077 @ @<Record a new maximum coefficient...@>=
17078
17079   if ( mp->max_c[t]>0 ) {
17080     link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
17081   }
17082   mp->max_c[t]=abs(value(r)); mp->max_ptr[t]=r;
17083 }
17084
17085 @ @<Choose a dependent...@>=
17086
17087   if ( (mp->max_c[mp_dependent] / 010000 >= mp->max_c[mp_proto_dependent]) )
17088     t=mp_dependent;
17089   else 
17090     t=mp_proto_dependent;
17091   @<Determine the dependency list |s| to substitute for the independent
17092     variable~|p|@>;
17093   t=mp_dependent+mp_proto_dependent-t; /* complement |t| */
17094   if ( mp->max_c[t]>0 ) { /* we need to pick up an unchosen dependency */ 
17095     link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
17096   }
17097   if ( t!=mp_dependent ) { @<Substitute new dependencies in place of |p|@>; }
17098   else { @<Substitute new proto-dependencies in place of |p|@>;}
17099   mp_flush_node_list(mp, s);
17100   if ( mp->fix_needed ) mp_fix_dependencies(mp);
17101   check_arith;
17102 }
17103
17104 @ Let |s=max_ptr[t]|. At this point we have $|value|(s)=\pm|max_c|[t]$,
17105 and |info(s)| points to the dependent variable~|pp| of type~|t| from
17106 whose dependency list we have removed node~|s|. We must reinsert
17107 node~|s| into the dependency list, with coefficient $-1.0$, and with
17108 |pp| as the new independent variable. Since |pp| will have a larger serial
17109 number than any other variable, we can put node |s| at the head of the
17110 list.
17111
17112 @<Determine the dep...@>=
17113 s=mp->max_ptr[t]; pp=info(s); v=value(s);
17114 if ( t==mp_dependent ) value(s)=-fraction_one; else value(s)=-unity;
17115 r=dep_list(pp); link(s)=r;
17116 while ( info(r)!=null ) r=link(r);
17117 q=link(r); link(r)=null;
17118 prev_dep(q)=prev_dep(pp); link(prev_dep(pp))=q;
17119 new_indep(pp);
17120 if ( mp->cur_exp==pp ) if ( mp->cur_type==t ) mp->cur_type=mp_independent;
17121 if ( mp->internal[mp_tracing_equations]>0 ) { 
17122   @<Show the transformed dependency@>; 
17123 }
17124
17125 @ Now $(-v)$ times the formerly independent variable~|p| is being replaced
17126 by the dependency list~|s|.
17127
17128 @<Show the transformed...@>=
17129 if ( mp_interesting(mp, p) ) {
17130   mp_begin_diagnostic(mp); mp_print_nl(mp, "### ");
17131 @:]]]\#\#\#_}{\.{\#\#\#}@>
17132   if ( v>0 ) mp_print_char(mp, '-');
17133   if ( t==mp_dependent ) vv=mp_round_fraction(mp, mp->max_c[mp_dependent]);
17134   else vv=mp->max_c[mp_proto_dependent];
17135   if ( vv!=unity ) mp_print_scaled(mp, vv);
17136   mp_print_variable_name(mp, p);
17137   while ( value(p) % s_scale>0 ) {
17138     mp_print(mp, "*4"); value(p)=value(p)-2;
17139   }
17140   if ( t==mp_dependent ) mp_print_char(mp, '='); else mp_print(mp, " = ");
17141   mp_print_dependency(mp, s,t);
17142   mp_end_diagnostic(mp, false);
17143 }
17144
17145 @ Finally, there are dependent and proto-dependent variables whose
17146 dependency lists must be brought up to date.
17147
17148 @<Substitute new dependencies...@>=
17149 for (t=mp_dependent;t<=mp_proto_dependent;t++){ 
17150   r=mp->max_link[t];
17151   while ( r!=null ) {
17152     q=info(r);
17153     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
17154      mp_make_fraction(mp, value(r),-v),s,t,mp_dependent);
17155     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
17156     q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
17157   }
17158 }
17159
17160 @ @<Substitute new proto...@>=
17161 for (t=mp_dependent;t<=mp_proto_dependent;t++) {
17162   r=mp->max_link[t];
17163   while ( r!=null ) {
17164     q=info(r);
17165     if ( t==mp_dependent ) { /* for safety's sake, we change |q| to |mp_proto_dependent| */
17166       if ( mp->cur_exp==q ) if ( mp->cur_type==mp_dependent )
17167         mp->cur_type=mp_proto_dependent;
17168       dep_list(q)=mp_p_over_v(mp, dep_list(q),unity,mp_dependent,mp_proto_dependent);
17169       type(q)=mp_proto_dependent; value(r)=mp_round_fraction(mp, value(r));
17170     }
17171     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
17172       mp_make_scaled(mp, value(r),-v),s,mp_proto_dependent,mp_proto_dependent);
17173     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
17174     q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
17175   }
17176 }
17177
17178 @ Here are some routines that provide handy combinations of actions
17179 that are often needed during error recovery. For example,
17180 `|flush_error|' flushes the current expression, replaces it by
17181 a given value, and calls |error|.
17182
17183 Errors often are detected after an extra token has already been scanned.
17184 The `\\{put\_get}' routines put that token back before calling |error|;
17185 then they get it back again. (Or perhaps they get another token, if
17186 the user has changed things.)
17187
17188 @<Declarations@>=
17189 void mp_flush_error (MP mp,scaled v);
17190 void mp_put_get_error (MP mp);
17191 void mp_put_get_flush_error (MP mp,scaled v) ;
17192
17193 @ @c
17194 void mp_flush_error (MP mp,scaled v) { 
17195   mp_error(mp); mp_flush_cur_exp(mp, v); 
17196 }
17197 void mp_put_get_error (MP mp) { 
17198   mp_back_error(mp); mp_get_x_next(mp); 
17199 }
17200 void mp_put_get_flush_error (MP mp,scaled v) { 
17201   mp_put_get_error(mp);
17202   mp_flush_cur_exp(mp, v); 
17203 }
17204
17205 @ A global variable |var_flag| is set to a special command code
17206 just before \MP\ calls |scan_expression|, if the expression should be
17207 treated as a variable when this command code immediately follows. For
17208 example, |var_flag| is set to |assignment| at the beginning of a
17209 statement, because we want to know the {\sl location\/} of a variable at
17210 the left of `\.{:=}', not the {\sl value\/} of that variable.
17211
17212 The |scan_expression| subroutine calls |scan_tertiary|,
17213 which calls |scan_secondary|, which calls |scan_primary|, which sets
17214 |var_flag:=0|. In this way each of the scanning routines ``knows''
17215 when it has been called with a special |var_flag|, but |var_flag| is
17216 usually zero.
17217
17218 A variable preceding a command that equals |var_flag| is converted to a
17219 token list rather than a value. Furthermore, an `\.{=}' sign following an
17220 expression with |var_flag=assignment| is not considered to be a relation
17221 that produces boolean expressions.
17222
17223
17224 @<Glob...@>=
17225 int var_flag; /* command that wants a variable */
17226
17227 @ @<Set init...@>=
17228 mp->var_flag=0;
17229
17230 @* \[37] Parsing primary expressions.
17231 The first parsing routine, |scan_primary|, is also the most complicated one,
17232 since it involves so many different cases. But each case---with one
17233 exception---is fairly simple by itself.
17234
17235 When |scan_primary| begins, the first token of the primary to be scanned
17236 should already appear in |cur_cmd|, |cur_mod|, and |cur_sym|. The values
17237 of |cur_type| and |cur_exp| should be either dead or dormant, as explained
17238 earlier. If |cur_cmd| is not between |min_primary_command| and
17239 |max_primary_command|, inclusive, a syntax error will be signaled.
17240
17241 @<Declare the basic parsing subroutines@>=
17242 void mp_scan_primary (MP mp) {
17243   pointer p,q,r; /* for list manipulation */
17244   quarterword c; /* a primitive operation code */
17245   int my_var_flag; /* initial value of |my_var_flag| */
17246   pointer l_delim,r_delim; /* hash addresses of a delimiter pair */
17247   @<Other local variables for |scan_primary|@>;
17248   my_var_flag=mp->var_flag; mp->var_flag=0;
17249 RESTART:
17250   check_arith;
17251   @<Supply diagnostic information, if requested@>;
17252   switch (mp->cur_cmd) {
17253   case left_delimiter:
17254     @<Scan a delimited primary@>; break;
17255   case begin_group:
17256     @<Scan a grouped primary@>; break;
17257   case string_token:
17258     @<Scan a string constant@>; break;
17259   case numeric_token:
17260     @<Scan a primary that starts with a numeric token@>; break;
17261   case nullary:
17262     @<Scan a nullary operation@>; break;
17263   case unary: case type_name: case cycle: case plus_or_minus:
17264     @<Scan a unary operation@>; break;
17265   case primary_binary:
17266     @<Scan a binary operation with `\&{of}' between its operands@>; break;
17267   case str_op:
17268     @<Convert a suffix to a string@>; break;
17269   case internal_quantity:
17270     @<Scan an internal numeric quantity@>; break;
17271   case capsule_token:
17272     mp_make_exp_copy(mp, mp->cur_mod); break;
17273   case tag_token:
17274     @<Scan a variable primary; |goto restart| if it turns out to be a macro@>; break;
17275   default: 
17276     mp_bad_exp(mp, "A primary"); goto RESTART; break;
17277 @.A primary expression...@>
17278   }
17279   mp_get_x_next(mp); /* the routines |goto done| if they don't want this */
17280 DONE: 
17281   if ( mp->cur_cmd==left_bracket ) {
17282     if ( mp->cur_type>=mp_known ) {
17283       @<Scan a mediation construction@>;
17284     }
17285   }
17286 }
17287
17288
17289
17290 @ Errors at the beginning of expressions are flagged by |bad_exp|.
17291
17292 @c void mp_bad_exp (MP mp,char * s) {
17293   int save_flag;
17294   print_err(s); mp_print(mp, " expression can't begin with `");
17295   mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); 
17296   mp_print_char(mp, '\'');
17297   help4("I'm afraid I need some sort of value in order to continue,")
17298     ("so I've tentatively inserted `0'. You may want to")
17299     ("delete this zero and insert something else;")
17300     ("see Chapter 27 of The METAFONTbook for an example.");
17301 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
17302   mp_back_input(mp); mp->cur_sym=0; mp->cur_cmd=numeric_token; 
17303   mp->cur_mod=0; mp_ins_error(mp);
17304   save_flag=mp->var_flag; mp->var_flag=0; mp_get_x_next(mp);
17305   mp->var_flag=save_flag;
17306 }
17307
17308 @ @<Supply diagnostic information, if requested@>=
17309 #ifdef DEBUG
17310 if ( mp->panicking ) mp_check_mem(mp, false);
17311 #endif
17312 if ( mp->interrupt!=0 ) if ( mp->OK_to_interrupt ) {
17313   mp_back_input(mp); check_interrupt; mp_get_x_next(mp);
17314 }
17315
17316 @ @<Scan a delimited primary@>=
17317
17318   l_delim=mp->cur_sym; r_delim=mp->cur_mod; 
17319   mp_get_x_next(mp); mp_scan_expression(mp);
17320   if ( (mp->cur_cmd==comma) && (mp->cur_type>=mp_known) ) {
17321     @<Scan the rest of a delimited set of numerics@>;
17322   } else {
17323     mp_check_delimiter(mp, l_delim,r_delim);
17324   }
17325 }
17326
17327 @ The |stash_in| subroutine puts the current (numeric) expression into a field
17328 within a ``big node.''
17329
17330 @c void mp_stash_in (MP mp,pointer p) {
17331   pointer q; /* temporary register */
17332   type(p)=mp->cur_type;
17333   if ( mp->cur_type==mp_known ) {
17334     value(p)=mp->cur_exp;
17335   } else { 
17336     if ( mp->cur_type==mp_independent ) {
17337       @<Stash an independent |cur_exp| into a big node@>;
17338     } else { 
17339       mp->mem[value_loc(p)]=mp->mem[value_loc(mp->cur_exp)];
17340       /* |dep_list(p):=dep_list(cur_exp)| and |prev_dep(p):=prev_dep(cur_exp)| */
17341       link(prev_dep(p))=p;
17342     }
17343     mp_free_node(mp, mp->cur_exp,value_node_size);
17344   }
17345   mp->cur_type=mp_vacuous;
17346 }
17347
17348 @ In rare cases the current expression can become |independent|. There
17349 may be many dependency lists pointing to such an independent capsule,
17350 so we can't simply move it into place within a big node. Instead,
17351 we copy it, then recycle it.
17352
17353 @ @<Stash an independent |cur_exp|...@>=
17354
17355   q=mp_single_dependency(mp, mp->cur_exp);
17356   if ( q==mp->dep_final ){ 
17357     type(p)=mp_known; value(p)=0; mp_free_node(mp, q,dep_node_size);
17358   } else { 
17359     type(p)=mp_dependent; mp_new_dep(mp, p,q);
17360   }
17361   mp_recycle_value(mp, mp->cur_exp);
17362 }
17363
17364 @ This code uses the fact that |red_part_loc| and |green_part_loc|
17365 are synonymous with |x_part_loc| and |y_part_loc|.
17366
17367 @<Scan the rest of a delimited set of numerics@>=
17368
17369 p=mp_stash_cur_exp(mp);
17370 mp_get_x_next(mp); mp_scan_expression(mp);
17371 @<Make sure the second part of a pair or color has a numeric type@>;
17372 q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
17373 if ( mp->cur_cmd==comma ) type(q)=mp_color_type;
17374 else type(q)=mp_pair_type;
17375 mp_init_big_node(mp, q); r=value(q);
17376 mp_stash_in(mp, y_part_loc(r));
17377 mp_unstash_cur_exp(mp, p);
17378 mp_stash_in(mp, x_part_loc(r));
17379 if ( mp->cur_cmd==comma ) {
17380   @<Scan the last of a triplet of numerics@>;
17381 }
17382 if ( mp->cur_cmd==comma ) {
17383   type(q)=mp_cmykcolor_type;
17384   mp_init_big_node(mp, q); t=value(q);
17385   mp->mem[cyan_part_loc(t)]=mp->mem[red_part_loc(r)];
17386   value(cyan_part_loc(t))=value(red_part_loc(r));
17387   mp->mem[magenta_part_loc(t)]=mp->mem[green_part_loc(r)];
17388   value(magenta_part_loc(t))=value(green_part_loc(r));
17389   mp->mem[yellow_part_loc(t)]=mp->mem[blue_part_loc(r)];
17390   value(yellow_part_loc(t))=value(blue_part_loc(r));
17391   mp_recycle_value(mp, r);
17392   r=t;
17393   @<Scan the last of a quartet of numerics@>;
17394 }
17395 mp_check_delimiter(mp, l_delim,r_delim);
17396 mp->cur_type=type(q);
17397 mp->cur_exp=q;
17398 }
17399
17400 @ @<Make sure the second part of a pair or color has a numeric type@>=
17401 if ( mp->cur_type<mp_known ) {
17402   exp_err("Nonnumeric ypart has been replaced by 0");
17403 @.Nonnumeric...replaced by 0@>
17404   help4("I've started to scan a pair `(a,b)' or a color `(a,b,c)';")
17405     ("but after finding a nice `a' I found a `b' that isn't")
17406     ("of numeric type. So I've changed that part to zero.")
17407     ("(The b that I didn't like appears above the error message.)");
17408   mp_put_get_flush_error(mp, 0);
17409 }
17410
17411 @ @<Scan the last of a triplet of numerics@>=
17412
17413   mp_get_x_next(mp); mp_scan_expression(mp);
17414   if ( mp->cur_type<mp_known ) {
17415     exp_err("Nonnumeric third part has been replaced by 0");
17416 @.Nonnumeric...replaced by 0@>
17417     help3("I've just scanned a color `(a,b,c)' or cmykcolor(a,b,c,d); but the `c'")
17418       ("isn't of numeric type. So I've changed that part to zero.")
17419       ("(The c that I didn't like appears above the error message.)");
17420     mp_put_get_flush_error(mp, 0);
17421   }
17422   mp_stash_in(mp, blue_part_loc(r));
17423 }
17424
17425 @ @<Scan the last of a quartet of numerics@>=
17426
17427   mp_get_x_next(mp); mp_scan_expression(mp);
17428   if ( mp->cur_type<mp_known ) {
17429     exp_err("Nonnumeric blackpart has been replaced by 0");
17430 @.Nonnumeric...replaced by 0@>
17431     help3("I've just scanned a cmykcolor `(c,m,y,k)'; but the `k' isn't")
17432       ("of numeric type. So I've changed that part to zero.")
17433       ("(The k that I didn't like appears above the error message.)");
17434     mp_put_get_flush_error(mp, 0);
17435   }
17436   mp_stash_in(mp, black_part_loc(r));
17437 }
17438
17439 @ The local variable |group_line| keeps track of the line
17440 where a \&{begingroup} command occurred; this will be useful
17441 in an error message if the group doesn't actually end.
17442
17443 @<Other local variables for |scan_primary|@>=
17444 integer group_line; /* where a group began */
17445
17446 @ @<Scan a grouped primary@>=
17447
17448   group_line=mp_true_line(mp);
17449   if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17450   save_boundary_item(p);
17451   do {  
17452     mp_do_statement(mp); /* ends with |cur_cmd>=semicolon| */
17453   } while (! (mp->cur_cmd!=semicolon));
17454   if ( mp->cur_cmd!=end_group ) {
17455     print_err("A group begun on line ");
17456 @.A group...never ended@>
17457     mp_print_int(mp, group_line);
17458     mp_print(mp, " never ended");
17459     help2("I saw a `begingroup' back there that hasn't been matched")
17460          ("by `endgroup'. So I've inserted `endgroup' now.");
17461     mp_back_error(mp); mp->cur_cmd=end_group;
17462   }
17463   mp_unsave(mp); 
17464     /* this might change |cur_type|, if independent variables are recycled */
17465   if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17466 }
17467
17468 @ @<Scan a string constant@>=
17469
17470   mp->cur_type=mp_string_type; mp->cur_exp=mp->cur_mod;
17471 }
17472
17473 @ Later we'll come to procedures that perform actual operations like
17474 addition, square root, and so on; our purpose now is to do the parsing.
17475 But we might as well mention those future procedures now, so that the
17476 suspense won't be too bad:
17477
17478 \smallskip
17479 |do_nullary(c)| does primitive operations that have no operands (e.g.,
17480 `\&{true}' or `\&{pencircle}');
17481
17482 \smallskip
17483 |do_unary(c)| applies a primitive operation to the current expression;
17484
17485 \smallskip
17486 |do_binary(p,c)| applies a primitive operation to the capsule~|p|
17487 and the current expression.
17488
17489 @<Scan a nullary operation@>=mp_do_nullary(mp, mp->cur_mod)
17490
17491 @ @<Scan a unary operation@>=
17492
17493   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_primary(mp); 
17494   mp_do_unary(mp, c); goto DONE;
17495 }
17496
17497 @ A numeric token might be a primary by itself, or it might be the
17498 numerator of a fraction composed solely of numeric tokens, or it might
17499 multiply the primary that follows (provided that the primary doesn't begin
17500 with a plus sign or a minus sign). The code here uses the facts that
17501 |max_primary_command=plus_or_minus| and
17502 |max_primary_command-1=numeric_token|. If a fraction is found that is less
17503 than unity, we try to retain higher precision when we use it in scalar
17504 multiplication.
17505
17506 @<Other local variables for |scan_primary|@>=
17507 scaled num,denom; /* for primaries that are fractions, like `1/2' */
17508
17509 @ @<Scan a primary that starts with a numeric token@>=
17510
17511   mp->cur_exp=mp->cur_mod; mp->cur_type=mp_known; mp_get_x_next(mp);
17512   if ( mp->cur_cmd!=slash ) { 
17513     num=0; denom=0;
17514   } else { 
17515     mp_get_x_next(mp);
17516     if ( mp->cur_cmd!=numeric_token ) { 
17517       mp_back_input(mp);
17518       mp->cur_cmd=slash; mp->cur_mod=over; mp->cur_sym=frozen_slash;
17519       goto DONE;
17520     }
17521     num=mp->cur_exp; denom=mp->cur_mod;
17522     if ( denom==0 ) { @<Protest division by zero@>; }
17523     else { mp->cur_exp=mp_make_scaled(mp, num,denom); }
17524     check_arith; mp_get_x_next(mp);
17525   }
17526   if ( mp->cur_cmd>=min_primary_command ) {
17527    if ( mp->cur_cmd<numeric_token ) { /* in particular, |cur_cmd<>plus_or_minus| */
17528      p=mp_stash_cur_exp(mp); mp_scan_primary(mp);
17529      if ( (abs(num)>=abs(denom))||(mp->cur_type<mp_color_type) ) {
17530        mp_do_binary(mp, p,times);
17531      } else {
17532        mp_frac_mult(mp, num,denom);
17533        mp_free_node(mp, p,value_node_size);
17534      }
17535     }
17536   }
17537   goto DONE;
17538 }
17539
17540 @ @<Protest division...@>=
17541
17542   print_err("Division by zero");
17543 @.Division by zero@>
17544   help1("I'll pretend that you meant to divide by 1."); mp_error(mp);
17545 }
17546
17547 @ @<Scan a binary operation with `\&{of}' between its operands@>=
17548
17549   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
17550   if ( mp->cur_cmd!=of_token ) {
17551     mp_missing_err(mp, "of"); mp_print(mp, " for "); 
17552     mp_print_cmd_mod(mp, primary_binary,c);
17553 @.Missing `of'@>
17554     help1("I've got the first argument; will look now for the other.");
17555     mp_back_error(mp);
17556   }
17557   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_primary(mp); 
17558   mp_do_binary(mp, p,c); goto DONE;
17559 }
17560
17561 @ @<Convert a suffix to a string@>=
17562
17563   mp_get_x_next(mp); mp_scan_suffix(mp); 
17564   mp->old_setting=mp->selector; mp->selector=new_string;
17565   mp_show_token_list(mp, mp->cur_exp,null,100000,0); 
17566   mp_flush_token_list(mp, mp->cur_exp);
17567   mp->cur_exp=mp_make_string(mp); mp->selector=mp->old_setting; 
17568   mp->cur_type=mp_string_type;
17569   goto DONE;
17570 }
17571
17572 @ If an internal quantity appears all by itself on the left of an
17573 assignment, we return a token list of length one, containing the address
17574 of the internal quantity plus |hash_end|. (This accords with the conventions
17575 of the save stack, as described earlier.)
17576
17577 @<Scan an internal...@>=
17578
17579   q=mp->cur_mod;
17580   if ( my_var_flag==assignment ) {
17581     mp_get_x_next(mp);
17582     if ( mp->cur_cmd==assignment ) {
17583       mp->cur_exp=mp_get_avail(mp);
17584       info(mp->cur_exp)=q+hash_end; mp->cur_type=mp_token_list; 
17585       goto DONE;
17586     }
17587     mp_back_input(mp);
17588   }
17589   mp->cur_type=mp_known; mp->cur_exp=mp->internal[q];
17590 }
17591
17592 @ The most difficult part of |scan_primary| has been saved for last, since
17593 it was necessary to build up some confidence first. We can now face the task
17594 of scanning a variable.
17595
17596 As we scan a variable, we build a token list containing the relevant
17597 names and subscript values, simultaneously following along in the
17598 ``collective'' structure to see if we are actually dealing with a macro
17599 instead of a value.
17600
17601 The local variables |pre_head| and |post_head| will point to the beginning
17602 of the prefix and suffix lists; |tail| will point to the end of the list
17603 that is currently growing.
17604
17605 Another local variable, |tt|, contains partial information about the
17606 declared type of the variable-so-far. If |tt>=mp_unsuffixed_macro|, the
17607 relation |tt=type(q)| will always hold. If |tt=undefined|, the routine
17608 doesn't bother to update its information about type. And if
17609 |undefined<tt<mp_unsuffixed_macro|, the precise value of |tt| isn't critical.
17610
17611 @ @<Other local variables for |scan_primary|@>=
17612 pointer pre_head,post_head,tail;
17613   /* prefix and suffix list variables */
17614 small_number tt; /* approximation to the type of the variable-so-far */
17615 pointer t; /* a token */
17616 pointer macro_ref = 0; /* reference count for a suffixed macro */
17617
17618 @ @<Scan a variable primary...@>=
17619
17620   fast_get_avail(pre_head); tail=pre_head; post_head=null; tt=mp_vacuous;
17621   while (1) { 
17622     t=mp_cur_tok(mp); link(tail)=t;
17623     if ( tt!=undefined ) {
17624        @<Find the approximate type |tt| and corresponding~|q|@>;
17625       if ( tt>=mp_unsuffixed_macro ) {
17626         @<Either begin an unsuffixed macro call or
17627           prepare for a suffixed one@>;
17628       }
17629     }
17630     mp_get_x_next(mp); tail=t;
17631     if ( mp->cur_cmd==left_bracket ) {
17632       @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>;
17633     }
17634     if ( mp->cur_cmd>max_suffix_token ) break;
17635     if ( mp->cur_cmd<min_suffix_token ) break;
17636   } /* now |cur_cmd| is |internal_quantity|, |tag_token|, or |numeric_token| */
17637   @<Handle unusual cases that masquerade as variables, and |goto restart|
17638     or |goto done| if appropriate;
17639     otherwise make a copy of the variable and |goto done|@>;
17640 }
17641
17642 @ @<Either begin an unsuffixed macro call or...@>=
17643
17644   link(tail)=null;
17645   if ( tt>mp_unsuffixed_macro ) { /* |tt=mp_suffixed_macro| */
17646     post_head=mp_get_avail(mp); tail=post_head; link(tail)=t;
17647     tt=undefined; macro_ref=value(q); add_mac_ref(macro_ref);
17648   } else {
17649     @<Set up unsuffixed macro call and |goto restart|@>;
17650   }
17651 }
17652
17653 @ @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>=
17654
17655   mp_get_x_next(mp); mp_scan_expression(mp);
17656   if ( mp->cur_cmd!=right_bracket ) {
17657     @<Put the left bracket and the expression back to be rescanned@>;
17658   } else { 
17659     if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17660     mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp; mp->cur_sym=0;
17661   }
17662 }
17663
17664 @ The left bracket that we thought was introducing a subscript might have
17665 actually been the left bracket in a mediation construction like `\.{x[a,b]}'.
17666 So we don't issue an error message at this point; but we do want to back up
17667 so as to avoid any embarrassment about our incorrect assumption.
17668
17669 @<Put the left bracket and the expression back to be rescanned@>=
17670
17671   mp_back_input(mp); /* that was the token following the current expression */
17672   mp_back_expr(mp); mp->cur_cmd=left_bracket; 
17673   mp->cur_mod=0; mp->cur_sym=frozen_left_bracket;
17674 }
17675
17676 @ Here's a routine that puts the current expression back to be read again.
17677
17678 @c void mp_back_expr (MP mp) {
17679   pointer p; /* capsule token */
17680   p=mp_stash_cur_exp(mp); link(p)=null; back_list(p);
17681 }
17682
17683 @ Unknown subscripts lead to the following error message.
17684
17685 @c void mp_bad_subscript (MP mp) { 
17686   exp_err("Improper subscript has been replaced by zero");
17687 @.Improper subscript...@>
17688   help3("A bracketed subscript must have a known numeric value;")
17689     ("unfortunately, what I found was the value that appears just")
17690     ("above this error message. So I'll try a zero subscript.");
17691   mp_flush_error(mp, 0);
17692 }
17693
17694 @ Every time we call |get_x_next|, there's a chance that the variable we've
17695 been looking at will disappear. Thus, we cannot safely keep |q| pointing
17696 into the variable structure; we need to start searching from the root each time.
17697
17698 @<Find the approximate type |tt| and corresponding~|q|@>=
17699 @^inner loop@>
17700
17701   p=link(pre_head); q=info(p); tt=undefined;
17702   if ( eq_type(q) % outer_tag==tag_token ) {
17703     q=equiv(q);
17704     if ( q==null ) goto DONE2;
17705     while (1) { 
17706       p=link(p);
17707       if ( p==null ) {
17708         tt=type(q); goto DONE2;
17709       };
17710       if ( type(q)!=mp_structured ) goto DONE2;
17711       q=link(attr_head(q)); /* the |collective_subscript| attribute */
17712       if ( p>=mp->hi_mem_min ) { /* it's not a subscript */
17713         do {  q=link(q); } while (! (attr_loc(q)>=info(p)));
17714         if ( attr_loc(q)>info(p) ) goto DONE2;
17715       }
17716     }
17717   }
17718 DONE2:
17719   ;
17720 }
17721
17722 @ How do things stand now? Well, we have scanned an entire variable name,
17723 including possible subscripts and/or attributes; |cur_cmd|, |cur_mod|, and
17724 |cur_sym| represent the token that follows. If |post_head=null|, a
17725 token list for this variable name starts at |link(pre_head)|, with all
17726 subscripts evaluated. But if |post_head<>null|, the variable turned out
17727 to be a suffixed macro; |pre_head| is the head of the prefix list, while
17728 |post_head| is the head of a token list containing both `\.{\AT!}' and
17729 the suffix.
17730
17731 Our immediate problem is to see if this variable still exists. (Variable
17732 structures can change drastically whenever we call |get_x_next|; users
17733 aren't supposed to do this, but the fact that it is possible means that
17734 we must be cautious.)
17735
17736 The following procedure prints an error message when a variable
17737 unexpectedly disappears. Its help message isn't quite right for
17738 our present purposes, but we'll be able to fix that up.
17739
17740 @c 
17741 void mp_obliterated (MP mp,pointer q) { 
17742   print_err("Variable "); mp_show_token_list(mp, q,null,1000,0);
17743   mp_print(mp, " has been obliterated");
17744 @.Variable...obliterated@>
17745   help5("It seems you did a nasty thing---probably by accident,")
17746     ("but nevertheless you nearly hornswoggled me...")
17747     ("While I was evaluating the right-hand side of this")
17748     ("command, something happened, and the left-hand side")
17749     ("is no longer a variable! So I won't change anything.");
17750 }
17751
17752 @ If the variable does exist, we also need to check
17753 for a few other special cases before deciding that a plain old ordinary
17754 variable has, indeed, been scanned.
17755
17756 @<Handle unusual cases that masquerade as variables...@>=
17757 if ( post_head!=null ) {
17758   @<Set up suffixed macro call and |goto restart|@>;
17759 }
17760 q=link(pre_head); free_avail(pre_head);
17761 if ( mp->cur_cmd==my_var_flag ) { 
17762   mp->cur_type=mp_token_list; mp->cur_exp=q; goto DONE;
17763 }
17764 p=mp_find_variable(mp, q);
17765 if ( p!=null ) {
17766   mp_make_exp_copy(mp, p);
17767 } else { 
17768   mp_obliterated(mp, q);
17769   mp->help_line[2]="While I was evaluating the suffix of this variable,";
17770   mp->help_line[1]="something was redefined, and it's no longer a variable!";
17771   mp->help_line[0]="In order to get back on my feet, I've inserted `0' instead.";
17772   mp_put_get_flush_error(mp, 0);
17773 }
17774 mp_flush_node_list(mp, q); 
17775 goto DONE
17776
17777 @ The only complication associated with macro calling is that the prefix
17778 and ``at'' parameters must be packaged in an appropriate list of lists.
17779
17780 @<Set up unsuffixed macro call and |goto restart|@>=
17781
17782   p=mp_get_avail(mp); info(pre_head)=link(pre_head); link(pre_head)=p;
17783   info(p)=t; mp_macro_call(mp, value(q),pre_head,null);
17784   mp_get_x_next(mp); 
17785   goto RESTART;
17786 }
17787
17788 @ If the ``variable'' that turned out to be a suffixed macro no longer exists,
17789 we don't care, because we have reserved a pointer (|macro_ref|) to its
17790 token list.
17791
17792 @<Set up suffixed macro call and |goto restart|@>=
17793
17794   mp_back_input(mp); p=mp_get_avail(mp); q=link(post_head);
17795   info(pre_head)=link(pre_head); link(pre_head)=post_head;
17796   info(post_head)=q; link(post_head)=p; info(p)=link(q); link(q)=null;
17797   mp_macro_call(mp, macro_ref,pre_head,null); decr(ref_count(macro_ref));
17798   mp_get_x_next(mp); goto RESTART;
17799 }
17800
17801 @ Our remaining job is simply to make a copy of the value that has been
17802 found. Some cases are harder than others, but complexity arises solely
17803 because of the multiplicity of possible cases.
17804
17805 @<Declare the procedure called |make_exp_copy|@>=
17806 @<Declare subroutines needed by |make_exp_copy|@>;
17807 void mp_make_exp_copy (MP mp,pointer p) {
17808   pointer q,r,t; /* registers for list manipulation */
17809 RESTART: 
17810   mp->cur_type=type(p);
17811   switch (mp->cur_type) {
17812   case mp_vacuous: case mp_boolean_type: case mp_known:
17813     mp->cur_exp=value(p); break;
17814   case unknown_types:
17815     mp->cur_exp=mp_new_ring_entry(mp, p);
17816     break;
17817   case mp_string_type: 
17818     mp->cur_exp=value(p); add_str_ref(mp->cur_exp);
17819     break;
17820   case mp_picture_type:
17821     mp->cur_exp=value(p);add_edge_ref(mp->cur_exp);
17822     break;
17823   case mp_pen_type:
17824     mp->cur_exp=copy_pen(value(p));
17825     break; 
17826   case mp_path_type:
17827     mp->cur_exp=mp_copy_path(mp, value(p));
17828     break;
17829   case mp_transform_type: case mp_color_type: 
17830   case mp_cmykcolor_type: case mp_pair_type:
17831     @<Copy the big node |p|@>;
17832     break;
17833   case mp_dependent: case mp_proto_dependent:
17834     mp_encapsulate(mp, mp_copy_dep_list(mp, dep_list(p)));
17835     break;
17836   case mp_numeric_type: 
17837     new_indep(p); goto RESTART;
17838     break;
17839   case mp_independent: 
17840     q=mp_single_dependency(mp, p);
17841     if ( q==mp->dep_final ){ 
17842       mp->cur_type=mp_known; mp->cur_exp=0; mp_free_node(mp, q,value_node_size);
17843     } else { 
17844       mp->cur_type=mp_dependent; mp_encapsulate(mp, q);
17845     }
17846     break;
17847   default: 
17848     mp_confusion(mp, "copy");
17849 @:this can't happen copy}{\quad copy@>
17850     break;
17851   }
17852 }
17853
17854 @ The |encapsulate| subroutine assumes that |dep_final| is the
17855 tail of dependency list~|p|.
17856
17857 @<Declare subroutines needed by |make_exp_copy|@>=
17858 void mp_encapsulate (MP mp,pointer p) { 
17859   mp->cur_exp=mp_get_node(mp, value_node_size); type(mp->cur_exp)=mp->cur_type;
17860   name_type(mp->cur_exp)=mp_capsule; mp_new_dep(mp, mp->cur_exp,p);
17861 }
17862
17863 @ The most tedious case arises when the user refers to a
17864 \&{pair}, \&{color}, or \&{transform} variable; we must copy several fields,
17865 each of which can be |independent|, |dependent|, |mp_proto_dependent|,
17866 or |known|.
17867
17868 @<Copy the big node |p|@>=
17869
17870   if ( value(p)==null ) 
17871     mp_init_big_node(mp, p);
17872   t=mp_get_node(mp, value_node_size); name_type(t)=mp_capsule; type(t)=mp->cur_type;
17873   mp_init_big_node(mp, t);
17874   q=value(p)+mp->big_node_size[mp->cur_type]; 
17875   r=value(t)+mp->big_node_size[mp->cur_type];
17876   do {  
17877     q=q-2; r=r-2; mp_install(mp, r,q);
17878   } while (q!=value(p));
17879   mp->cur_exp=t;
17880 }
17881
17882 @ The |install| procedure copies a numeric field~|q| into field~|r| of
17883 a big node that will be part of a capsule.
17884
17885 @<Declare subroutines needed by |make_exp_copy|@>=
17886 void mp_install (MP mp,pointer r, pointer q) {
17887   pointer p; /* temporary register */
17888   if ( type(q)==mp_known ){ 
17889     value(r)=value(q); type(r)=mp_known;
17890   } else  if ( type(q)==mp_independent ) {
17891     p=mp_single_dependency(mp, q);
17892     if ( p==mp->dep_final ) {
17893       type(r)=mp_known; value(r)=0; mp_free_node(mp, p,value_node_size);
17894     } else  { 
17895       type(r)=mp_dependent; mp_new_dep(mp, r,p);
17896     }
17897   } else {
17898     type(r)=type(q); mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(q)));
17899   }
17900 }
17901
17902 @ Expressions of the form `\.{a[b,c]}' are converted into
17903 `\.{b+a*(c-b)}', without checking the types of \.b~or~\.c,
17904 provided that \.a is numeric.
17905
17906 @<Scan a mediation...@>=
17907
17908   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17909   if ( mp->cur_cmd!=comma ) {
17910     @<Put the left bracket and the expression back...@>;
17911     mp_unstash_cur_exp(mp, p);
17912   } else { 
17913     q=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17914     if ( mp->cur_cmd!=right_bracket ) {
17915       mp_missing_err(mp, "]");
17916 @.Missing `]'@>
17917       help3("I've scanned an expression of the form `a[b,c',")
17918       ("so a right bracket should have come next.")
17919       ("I shall pretend that one was there.");
17920       mp_back_error(mp);
17921     }
17922     r=mp_stash_cur_exp(mp); mp_make_exp_copy(mp, q);
17923     mp_do_binary(mp, r,minus); mp_do_binary(mp, p,times); 
17924     mp_do_binary(mp, q,plus); mp_get_x_next(mp);
17925   }
17926 }
17927
17928 @ Here is a comparatively simple routine that is used to scan the
17929 \&{suffix} parameters of a macro.
17930
17931 @<Declare the basic parsing subroutines@>=
17932 void mp_scan_suffix (MP mp) {
17933   pointer h,t; /* head and tail of the list being built */
17934   pointer p; /* temporary register */
17935   h=mp_get_avail(mp); t=h;
17936   while (1) { 
17937     if ( mp->cur_cmd==left_bracket ) {
17938       @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>;
17939     }
17940     if ( mp->cur_cmd==numeric_token ) {
17941       p=mp_new_num_tok(mp, mp->cur_mod);
17942     } else if ((mp->cur_cmd==tag_token)||(mp->cur_cmd==internal_quantity) ) {
17943        p=mp_get_avail(mp); info(p)=mp->cur_sym;
17944     } else {
17945       break;
17946     }
17947     link(t)=p; t=p; mp_get_x_next(mp);
17948   }
17949   mp->cur_exp=link(h); free_avail(h); mp->cur_type=mp_token_list;
17950 }
17951
17952 @ @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>=
17953
17954   mp_get_x_next(mp); mp_scan_expression(mp);
17955   if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17956   if ( mp->cur_cmd!=right_bracket ) {
17957      mp_missing_err(mp, "]");
17958 @.Missing `]'@>
17959     help3("I've seen a `[' and a subscript value, in a suffix,")
17960       ("so a right bracket should have come next.")
17961       ("I shall pretend that one was there.");
17962     mp_back_error(mp);
17963   }
17964   mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp;
17965 }
17966
17967 @* \[38] Parsing secondary and higher expressions.
17968 After the intricacies of |scan_primary|\kern-1pt,
17969 the |scan_secondary| routine is
17970 refreshingly simple. It's not trivial, but the operations are relatively
17971 straightforward; the main difficulty is, again, that expressions and data
17972 structures might change drastically every time we call |get_x_next|, so a
17973 cautious approach is mandatory. For example, a macro defined by
17974 \&{primarydef} might have disappeared by the time its second argument has
17975 been scanned; we solve this by increasing the reference count of its token
17976 list, so that the macro can be called even after it has been clobbered.
17977
17978 @<Declare the basic parsing subroutines@>=
17979 void mp_scan_secondary (MP mp) {
17980   pointer p; /* for list manipulation */
17981   halfword c,d; /* operation codes or modifiers */
17982   pointer mac_name; /* token defined with \&{primarydef} */
17983 RESTART:
17984   if ((mp->cur_cmd<min_primary_command)||
17985       (mp->cur_cmd>max_primary_command) )
17986     mp_bad_exp(mp, "A secondary");
17987 @.A secondary expression...@>
17988   mp_scan_primary(mp);
17989 CONTINUE: 
17990   if ( mp->cur_cmd<=max_secondary_command )
17991     if ( mp->cur_cmd>=min_secondary_command ) {
17992       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17993       if ( d==secondary_primary_macro ) { 
17994         mac_name=mp->cur_sym; add_mac_ref(c);
17995      }
17996      mp_get_x_next(mp); mp_scan_primary(mp);
17997      if ( d!=secondary_primary_macro ) {
17998        mp_do_binary(mp, p,c);
17999      } else  { 
18000        mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
18001        decr(ref_count(c)); mp_get_x_next(mp); 
18002        goto RESTART;
18003     }
18004     goto CONTINUE;
18005   }
18006 }
18007
18008 @ The following procedure calls a macro that has two parameters,
18009 |p| and |cur_exp|.
18010
18011 @c void mp_binary_mac (MP mp,pointer p, pointer c, pointer n) {
18012   pointer q,r; /* nodes in the parameter list */
18013   q=mp_get_avail(mp); r=mp_get_avail(mp); link(q)=r;
18014   info(q)=p; info(r)=mp_stash_cur_exp(mp);
18015   mp_macro_call(mp, c,q,n);
18016 }
18017
18018 @ The next procedure, |scan_tertiary|, is pretty much the same deal.
18019
18020 @<Declare the basic parsing subroutines@>=
18021 void mp_scan_tertiary (MP mp) {
18022   pointer p; /* for list manipulation */
18023   halfword c,d; /* operation codes or modifiers */
18024   pointer mac_name; /* token defined with \&{secondarydef} */
18025 RESTART:
18026   if ((mp->cur_cmd<min_primary_command)||
18027       (mp->cur_cmd>max_primary_command) )
18028     mp_bad_exp(mp, "A tertiary");
18029 @.A tertiary expression...@>
18030   mp_scan_secondary(mp);
18031 CONTINUE: 
18032   if ( mp->cur_cmd<=max_tertiary_command ) {
18033     if ( mp->cur_cmd>=min_tertiary_command ) {
18034       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
18035       if ( d==tertiary_secondary_macro ) { 
18036         mac_name=mp->cur_sym; add_mac_ref(c);
18037       };
18038       mp_get_x_next(mp); mp_scan_secondary(mp);
18039       if ( d!=tertiary_secondary_macro ) {
18040         mp_do_binary(mp, p,c);
18041       } else { 
18042         mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
18043         decr(ref_count(c)); mp_get_x_next(mp); 
18044         goto RESTART;
18045       }
18046       goto CONTINUE;
18047     }
18048   }
18049 }
18050
18051 @ Finally we reach the deepest level in our quartet of parsing routines.
18052 This one is much like the others; but it has an extra complication from
18053 paths, which materialize here.
18054
18055 @d continue_path 25 /* a label inside of |scan_expression| */
18056 @d finish_path 26 /* another */
18057
18058 @<Declare the basic parsing subroutines@>=
18059 void mp_scan_expression (MP mp) {
18060   pointer p,q,r,pp,qq; /* for list manipulation */
18061   halfword c,d; /* operation codes or modifiers */
18062   int my_var_flag; /* initial value of |var_flag| */
18063   pointer mac_name; /* token defined with \&{tertiarydef} */
18064   boolean cycle_hit; /* did a path expression just end with `\&{cycle}'? */
18065   scaled x,y; /* explicit coordinates or tension at a path join */
18066   int t; /* knot type following a path join */
18067   t=0; y=0; x=0;
18068   my_var_flag=mp->var_flag; mac_name=null;
18069 RESTART:
18070   if ((mp->cur_cmd<min_primary_command)||
18071       (mp->cur_cmd>max_primary_command) )
18072     mp_bad_exp(mp, "An");
18073 @.An expression...@>
18074   mp_scan_tertiary(mp);
18075 CONTINUE: 
18076   if ( mp->cur_cmd<=max_expression_command )
18077     if ( mp->cur_cmd>=min_expression_command ) {
18078       if ( (mp->cur_cmd!=equals)||(my_var_flag!=assignment) ) {
18079         p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
18080         if ( d==expression_tertiary_macro ) {
18081           mac_name=mp->cur_sym; add_mac_ref(c);
18082         }
18083         if ( (d<ampersand)||((d==ampersand)&&
18084              ((type(p)==mp_pair_type)||(type(p)==mp_path_type))) ) {
18085           @<Scan a path construction operation;
18086             but |return| if |p| has the wrong type@>;
18087         } else { 
18088           mp_get_x_next(mp); mp_scan_tertiary(mp);
18089           if ( d!=expression_tertiary_macro ) {
18090             mp_do_binary(mp, p,c);
18091           } else  { 
18092             mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
18093             decr(ref_count(c)); mp_get_x_next(mp); 
18094             goto RESTART;
18095           }
18096         }
18097         goto CONTINUE;
18098      }
18099   }
18100 }
18101
18102 @ The reader should review the data structure conventions for paths before
18103 hoping to understand the next part of this code.
18104
18105 @<Scan a path construction operation...@>=
18106
18107   cycle_hit=false;
18108   @<Convert the left operand, |p|, into a partial path ending at~|q|;
18109     but |return| if |p| doesn't have a suitable type@>;
18110 CONTINUE_PATH: 
18111   @<Determine the path join parameters;
18112     but |goto finish_path| if there's only a direction specifier@>;
18113   if ( mp->cur_cmd==cycle ) {
18114     @<Get ready to close a cycle@>;
18115   } else { 
18116     mp_scan_tertiary(mp);
18117     @<Convert the right operand, |cur_exp|,
18118       into a partial path from |pp| to~|qq|@>;
18119   }
18120   @<Join the partial paths and reset |p| and |q| to the head and tail
18121     of the result@>;
18122   if ( mp->cur_cmd>=min_expression_command )
18123     if ( mp->cur_cmd<=ampersand ) if ( ! cycle_hit ) goto CONTINUE_PATH;
18124 FINISH_PATH:
18125   @<Choose control points for the path and put the result into |cur_exp|@>;
18126 }
18127
18128 @ @<Convert the left operand, |p|, into a partial path ending at~|q|...@>=
18129
18130   mp_unstash_cur_exp(mp, p);
18131   if ( mp->cur_type==mp_pair_type ) p=mp_new_knot(mp);
18132   else if ( mp->cur_type==mp_path_type ) p=mp->cur_exp;
18133   else return;
18134   q=p;
18135   while ( link(q)!=p ) q=link(q);
18136   if ( left_type(p)!=mp_endpoint ) { /* open up a cycle */
18137     r=mp_copy_knot(mp, p); link(q)=r; q=r;
18138   }
18139   left_type(p)=mp_open; right_type(q)=mp_open;
18140 }
18141
18142 @ A pair of numeric values is changed into a knot node for a one-point path
18143 when \MP\ discovers that the pair is part of a path.
18144
18145 @c@<Declare the procedure called |known_pair|@>;
18146 pointer mp_new_knot (MP mp) { /* convert a pair to a knot with two endpoints */
18147   pointer q; /* the new node */
18148   q=mp_get_node(mp, knot_node_size); left_type(q)=mp_endpoint;
18149   right_type(q)=mp_endpoint; originator(q)=mp_metapost_user; link(q)=q;
18150   mp_known_pair(mp); x_coord(q)=mp->cur_x; y_coord(q)=mp->cur_y;
18151   return q;
18152 }
18153
18154 @ The |known_pair| subroutine sets |cur_x| and |cur_y| to the components
18155 of the current expression, assuming that the current expression is a
18156 pair of known numerics. Unknown components are zeroed, and the
18157 current expression is flushed.
18158
18159 @<Declare the procedure called |known_pair|@>=
18160 void mp_known_pair (MP mp) {
18161   pointer p; /* the pair node */
18162   if ( mp->cur_type!=mp_pair_type ) {
18163     exp_err("Undefined coordinates have been replaced by (0,0)");
18164 @.Undefined coordinates...@>
18165     help5("I need x and y numbers for this part of the path.")
18166       ("The value I found (see above) was no good;")
18167       ("so I'll try to keep going by using zero instead.")
18168       ("(Chapter 27 of The METAFONTbook explains that")
18169 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18170       ("you might want to type `I ??" "?' now.)");
18171     mp_put_get_flush_error(mp, 0); mp->cur_x=0; mp->cur_y=0;
18172   } else { 
18173     p=value(mp->cur_exp);
18174      @<Make sure that both |x| and |y| parts of |p| are known;
18175        copy them into |cur_x| and |cur_y|@>;
18176     mp_flush_cur_exp(mp, 0);
18177   }
18178 }
18179
18180 @ @<Make sure that both |x| and |y| parts of |p| are known...@>=
18181 if ( type(x_part_loc(p))==mp_known ) {
18182   mp->cur_x=value(x_part_loc(p));
18183 } else { 
18184   mp_disp_err(mp, x_part_loc(p),
18185     "Undefined x coordinate has been replaced by 0");
18186 @.Undefined coordinates...@>
18187   help5("I need a `known' x value for this part of the path.")
18188     ("The value I found (see above) was no good;")
18189     ("so I'll try to keep going by using zero instead.")
18190     ("(Chapter 27 of The METAFONTbook explains that")
18191 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18192     ("you might want to type `I ??" "?' now.)");
18193   mp_put_get_error(mp); mp_recycle_value(mp, x_part_loc(p)); mp->cur_x=0;
18194 }
18195 if ( type(y_part_loc(p))==mp_known ) {
18196   mp->cur_y=value(y_part_loc(p));
18197 } else { 
18198   mp_disp_err(mp, y_part_loc(p),
18199     "Undefined y coordinate has been replaced by 0");
18200   help5("I need a `known' y value for this part of the path.")
18201     ("The value I found (see above) was no good;")
18202     ("so I'll try to keep going by using zero instead.")
18203     ("(Chapter 27 of The METAFONTbook explains that")
18204     ("you might want to type `I ??" "?' now.)");
18205   mp_put_get_error(mp); mp_recycle_value(mp, y_part_loc(p)); mp->cur_y=0;
18206 }
18207
18208 @ At this point |cur_cmd| is either |ampersand|, |left_brace|, or |path_join|.
18209
18210 @<Determine the path join parameters...@>=
18211 if ( mp->cur_cmd==left_brace ) {
18212   @<Put the pre-join direction information into node |q|@>;
18213 }
18214 d=mp->cur_cmd;
18215 if ( d==path_join ) {
18216   @<Determine the tension and/or control points@>;
18217 } else if ( d!=ampersand ) {
18218   goto FINISH_PATH;
18219 }
18220 mp_get_x_next(mp);
18221 if ( mp->cur_cmd==left_brace ) {
18222   @<Put the post-join direction information into |x| and |t|@>;
18223 } else if ( right_type(q)!=mp_explicit ) {
18224   t=mp_open; x=0;
18225 }
18226
18227 @ The |scan_direction| subroutine looks at the directional information
18228 that is enclosed in braces, and also scans ahead to the following character.
18229 A type code is returned, either |open| (if the direction was $(0,0)$),
18230 or |curl| (if the direction was a curl of known value |cur_exp|), or
18231 |given| (if the direction is given by the |angle| value that now
18232 appears in |cur_exp|).
18233
18234 There's nothing difficult about this subroutine, but the program is rather
18235 lengthy because a variety of potential errors need to be nipped in the bud.
18236
18237 @c small_number mp_scan_direction (MP mp) {
18238   int t; /* the type of information found */
18239   scaled x; /* an |x| coordinate */
18240   mp_get_x_next(mp);
18241   if ( mp->cur_cmd==curl_command ) {
18242      @<Scan a curl specification@>;
18243   } else {
18244     @<Scan a given direction@>;
18245   }
18246   if ( mp->cur_cmd!=right_brace ) {
18247     mp_missing_err(mp, "}");
18248 @.Missing `\char`\}'@>
18249     help3("I've scanned a direction spec for part of a path,")
18250       ("so a right brace should have come next.")
18251       ("I shall pretend that one was there.");
18252     mp_back_error(mp);
18253   }
18254   mp_get_x_next(mp); 
18255   return t;
18256 }
18257
18258 @ @<Scan a curl specification@>=
18259 { mp_get_x_next(mp); mp_scan_expression(mp);
18260 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<0) ){ 
18261   exp_err("Improper curl has been replaced by 1");
18262 @.Improper curl@>
18263   help1("A curl must be a known, nonnegative number.");
18264   mp_put_get_flush_error(mp, unity);
18265 }
18266 t=mp_curl;
18267 }
18268
18269 @ @<Scan a given direction@>=
18270 { mp_scan_expression(mp);
18271   if ( mp->cur_type>mp_pair_type ) {
18272     @<Get given directions separated by commas@>;
18273   } else {
18274     mp_known_pair(mp);
18275   }
18276   if ( (mp->cur_x==0)&&(mp->cur_y==0) )  t=mp_open;
18277   else  { t=mp_given; mp->cur_exp=mp_n_arg(mp, mp->cur_x,mp->cur_y);}
18278 }
18279
18280 @ @<Get given directions separated by commas@>=
18281
18282   if ( mp->cur_type!=mp_known ) {
18283     exp_err("Undefined x coordinate has been replaced by 0");
18284 @.Undefined coordinates...@>
18285     help5("I need a `known' x value for this part of the path.")
18286       ("The value I found (see above) was no good;")
18287       ("so I'll try to keep going by using zero instead.")
18288       ("(Chapter 27 of The METAFONTbook explains that")
18289 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18290       ("you might want to type `I ??" "?' now.)");
18291     mp_put_get_flush_error(mp, 0);
18292   }
18293   x=mp->cur_exp;
18294   if ( mp->cur_cmd!=comma ) {
18295     mp_missing_err(mp, ",");
18296 @.Missing `,'@>
18297     help2("I've got the x coordinate of a path direction;")
18298       ("will look for the y coordinate next.");
18299     mp_back_error(mp);
18300   }
18301   mp_get_x_next(mp); mp_scan_expression(mp);
18302   if ( mp->cur_type!=mp_known ) {
18303      exp_err("Undefined y coordinate has been replaced by 0");
18304     help5("I need a `known' y value for this part of the path.")
18305       ("The value I found (see above) was no good;")
18306       ("so I'll try to keep going by using zero instead.")
18307       ("(Chapter 27 of The METAFONTbook explains that")
18308       ("you might want to type `I ??" "?' now.)");
18309     mp_put_get_flush_error(mp, 0);
18310   }
18311   mp->cur_y=mp->cur_exp; mp->cur_x=x;
18312 }
18313
18314 @ At this point |right_type(q)| is usually |open|, but it may have been
18315 set to some other value by a previous splicing operation. We must maintain
18316 the value of |right_type(q)| in unusual cases such as
18317 `\.{..z1\{z2\}\&\{z3\}z1\{0,0\}..}'.
18318
18319 @<Put the pre-join...@>=
18320
18321   t=mp_scan_direction(mp);
18322   if ( t!=mp_open ) {
18323     right_type(q)=t; right_given(q)=mp->cur_exp;
18324     if ( left_type(q)==mp_open ) {
18325       left_type(q)=t; left_given(q)=mp->cur_exp;
18326     } /* note that |left_given(q)=left_curl(q)| */
18327   }
18328 }
18329
18330 @ Since |left_tension| and |left_y| share the same position in knot nodes,
18331 and since |left_given| is similarly equivalent to |left_x|, we use
18332 |x| and |y| to hold the given direction and tension information when
18333 there are no explicit control points.
18334
18335 @<Put the post-join...@>=
18336
18337   t=mp_scan_direction(mp);
18338   if ( right_type(q)!=mp_explicit ) x=mp->cur_exp;
18339   else t=mp_explicit; /* the direction information is superfluous */
18340 }
18341
18342 @ @<Determine the tension and/or...@>=
18343
18344   mp_get_x_next(mp);
18345   if ( mp->cur_cmd==tension ) {
18346     @<Set explicit tensions@>;
18347   } else if ( mp->cur_cmd==controls ) {
18348     @<Set explicit control points@>;
18349   } else  { 
18350     right_tension(q)=unity; y=unity; mp_back_input(mp); /* default tension */
18351     goto DONE;
18352   };
18353   if ( mp->cur_cmd!=path_join ) {
18354      mp_missing_err(mp, "..");
18355 @.Missing `..'@>
18356     help1("A path join command should end with two dots.");
18357     mp_back_error(mp);
18358   }
18359 DONE:
18360   ;
18361 }
18362
18363 @ @<Set explicit tensions@>=
18364
18365   mp_get_x_next(mp); y=mp->cur_cmd;
18366   if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18367   mp_scan_primary(mp);
18368   @<Make sure that the current expression is a valid tension setting@>;
18369   if ( y==at_least ) negate(mp->cur_exp);
18370   right_tension(q)=mp->cur_exp;
18371   if ( mp->cur_cmd==and_command ) {
18372     mp_get_x_next(mp); y=mp->cur_cmd;
18373     if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18374     mp_scan_primary(mp);
18375     @<Make sure that the current expression is a valid tension setting@>;
18376     if ( y==at_least ) negate(mp->cur_exp);
18377   }
18378   y=mp->cur_exp;
18379 }
18380
18381 @ @d min_tension three_quarter_unit
18382
18383 @<Make sure that the current expression is a valid tension setting@>=
18384 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<min_tension) ) {
18385   exp_err("Improper tension has been set to 1");
18386 @.Improper tension@>
18387   help1("The expression above should have been a number >=3/4.");
18388   mp_put_get_flush_error(mp, unity);
18389 }
18390
18391 @ @<Set explicit control points@>=
18392
18393   right_type(q)=mp_explicit; t=mp_explicit; mp_get_x_next(mp); mp_scan_primary(mp);
18394   mp_known_pair(mp); right_x(q)=mp->cur_x; right_y(q)=mp->cur_y;
18395   if ( mp->cur_cmd!=and_command ) {
18396     x=right_x(q); y=right_y(q);
18397   } else { 
18398     mp_get_x_next(mp); mp_scan_primary(mp);
18399     mp_known_pair(mp); x=mp->cur_x; y=mp->cur_y;
18400   }
18401 }
18402
18403 @ @<Convert the right operand, |cur_exp|, into a partial path...@>=
18404
18405   if ( mp->cur_type!=mp_path_type ) pp=mp_new_knot(mp);
18406   else pp=mp->cur_exp;
18407   qq=pp;
18408   while ( link(qq)!=pp ) qq=link(qq);
18409   if ( left_type(pp)!=mp_endpoint ) { /* open up a cycle */
18410     r=mp_copy_knot(mp, pp); link(qq)=r; qq=r;
18411   }
18412   left_type(pp)=mp_open; right_type(qq)=mp_open;
18413 }
18414
18415 @ If a person tries to define an entire path by saying `\.{(x,y)\&cycle}',
18416 we silently change the specification to `\.{(x,y)..cycle}', since a cycle
18417 shouldn't have length zero.
18418
18419 @<Get ready to close a cycle@>=
18420
18421   cycle_hit=true; mp_get_x_next(mp); pp=p; qq=p;
18422   if ( d==ampersand ) if ( p==q ) {
18423     d=path_join; right_tension(q)=unity; y=unity;
18424   }
18425 }
18426
18427 @ @<Join the partial paths and reset |p| and |q|...@>=
18428
18429 if ( d==ampersand ) {
18430   if ( (x_coord(q)!=x_coord(pp))||(y_coord(q)!=y_coord(pp)) ) {
18431     print_err("Paths don't touch; `&' will be changed to `..'");
18432 @.Paths don't touch@>
18433     help3("When you join paths `p&q', the ending point of p")
18434       ("must be exactly equal to the starting point of q.")
18435       ("So I'm going to pretend that you said `p..q' instead.");
18436     mp_put_get_error(mp); d=path_join; right_tension(q)=unity; y=unity;
18437   }
18438 }
18439 @<Plug an opening in |right_type(pp)|, if possible@>;
18440 if ( d==ampersand ) {
18441   @<Splice independent paths together@>;
18442 } else  { 
18443   @<Plug an opening in |right_type(q)|, if possible@>;
18444   link(q)=pp; left_y(pp)=y;
18445   if ( t!=mp_open ) { left_x(pp)=x; left_type(pp)=t;  };
18446 }
18447 q=qq;
18448 }
18449
18450 @ @<Plug an opening in |right_type(q)|...@>=
18451 if ( right_type(q)==mp_open ) {
18452   if ( (left_type(q)==mp_curl)||(left_type(q)==mp_given) ) {
18453     right_type(q)=left_type(q); right_given(q)=left_given(q);
18454   }
18455 }
18456
18457 @ @<Plug an opening in |right_type(pp)|...@>=
18458 if ( right_type(pp)==mp_open ) {
18459   if ( (t==mp_curl)||(t==mp_given) ) {
18460     right_type(pp)=t; right_given(pp)=x;
18461   }
18462 }
18463
18464 @ @<Splice independent paths together@>=
18465
18466   if ( left_type(q)==mp_open ) if ( right_type(q)==mp_open ) {
18467     left_type(q)=mp_curl; left_curl(q)=unity;
18468   }
18469   if ( right_type(pp)==mp_open ) if ( t==mp_open ) {
18470     right_type(pp)=mp_curl; right_curl(pp)=unity;
18471   }
18472   right_type(q)=right_type(pp); link(q)=link(pp);
18473   right_x(q)=right_x(pp); right_y(q)=right_y(pp);
18474   mp_free_node(mp, pp,knot_node_size);
18475   if ( qq==pp ) qq=q;
18476 }
18477
18478 @ @<Choose control points for the path...@>=
18479 if ( cycle_hit ) { 
18480   if ( d==ampersand ) p=q;
18481 } else  { 
18482   left_type(p)=mp_endpoint;
18483   if ( right_type(p)==mp_open ) { 
18484     right_type(p)=mp_curl; right_curl(p)=unity;
18485   }
18486   right_type(q)=mp_endpoint;
18487   if ( left_type(q)==mp_open ) { 
18488     left_type(q)=mp_curl; left_curl(q)=unity;
18489   }
18490   link(q)=p;
18491 }
18492 mp_make_choices(mp, p);
18493 mp->cur_type=mp_path_type; mp->cur_exp=p
18494
18495 @ Finally, we sometimes need to scan an expression whose value is
18496 supposed to be either |true_code| or |false_code|.
18497
18498 @<Declare the basic parsing subroutines@>=
18499 void mp_get_boolean (MP mp) { 
18500   mp_get_x_next(mp); mp_scan_expression(mp);
18501   if ( mp->cur_type!=mp_boolean_type ) {
18502     exp_err("Undefined condition will be treated as `false'");
18503 @.Undefined condition...@>
18504     help2("The expression shown above should have had a definite")
18505       ("true-or-false value. I'm changing it to `false'.");
18506     mp_put_get_flush_error(mp, false_code); mp->cur_type=mp_boolean_type;
18507   }
18508 }
18509
18510 @* \[39] Doing the operations.
18511 The purpose of parsing is primarily to permit people to avoid piles of
18512 parentheses. But the real work is done after the structure of an expression
18513 has been recognized; that's when new expressions are generated. We
18514 turn now to the guts of \MP, which handles individual operators that
18515 have come through the parsing mechanism.
18516
18517 We'll start with the easy ones that take no operands, then work our way
18518 up to operators with one and ultimately two arguments. In other words,
18519 we will write the three procedures |do_nullary|, |do_unary|, and |do_binary|
18520 that are invoked periodically by the expression scanners.
18521
18522 First let's make sure that all of the primitive operators are in the
18523 hash table. Although |scan_primary| and its relatives made use of the
18524 \\{cmd} code for these operators, the \\{do} routines base everything
18525 on the \\{mod} code. For example, |do_binary| doesn't care whether the
18526 operation it performs is a |primary_binary| or |secondary_binary|, etc.
18527
18528 @<Put each...@>=
18529 mp_primitive(mp, "true",nullary,true_code);
18530 @:true_}{\&{true} primitive@>
18531 mp_primitive(mp, "false",nullary,false_code);
18532 @:false_}{\&{false} primitive@>
18533 mp_primitive(mp, "nullpicture",nullary,null_picture_code);
18534 @:null_picture_}{\&{nullpicture} primitive@>
18535 mp_primitive(mp, "nullpen",nullary,null_pen_code);
18536 @:null_pen_}{\&{nullpen} primitive@>
18537 mp_primitive(mp, "jobname",nullary,job_name_op);
18538 @:job_name_}{\&{jobname} primitive@>
18539 mp_primitive(mp, "readstring",nullary,read_string_op);
18540 @:read_string_}{\&{readstring} primitive@>
18541 mp_primitive(mp, "pencircle",nullary,pen_circle);
18542 @:pen_circle_}{\&{pencircle} primitive@>
18543 mp_primitive(mp, "normaldeviate",nullary,normal_deviate);
18544 @:normal_deviate_}{\&{normaldeviate} primitive@>
18545 mp_primitive(mp, "readfrom",unary,read_from_op);
18546 @:read_from_}{\&{readfrom} primitive@>
18547 mp_primitive(mp, "closefrom",unary,close_from_op);
18548 @:close_from_}{\&{closefrom} primitive@>
18549 mp_primitive(mp, "odd",unary,odd_op);
18550 @:odd_}{\&{odd} primitive@>
18551 mp_primitive(mp, "known",unary,known_op);
18552 @:known_}{\&{known} primitive@>
18553 mp_primitive(mp, "unknown",unary,unknown_op);
18554 @:unknown_}{\&{unknown} primitive@>
18555 mp_primitive(mp, "not",unary,not_op);
18556 @:not_}{\&{not} primitive@>
18557 mp_primitive(mp, "decimal",unary,decimal);
18558 @:decimal_}{\&{decimal} primitive@>
18559 mp_primitive(mp, "reverse",unary,reverse);
18560 @:reverse_}{\&{reverse} primitive@>
18561 mp_primitive(mp, "makepath",unary,make_path_op);
18562 @:make_path_}{\&{makepath} primitive@>
18563 mp_primitive(mp, "makepen",unary,make_pen_op);
18564 @:make_pen_}{\&{makepen} primitive@>
18565 mp_primitive(mp, "oct",unary,oct_op);
18566 @:oct_}{\&{oct} primitive@>
18567 mp_primitive(mp, "hex",unary,hex_op);
18568 @:hex_}{\&{hex} primitive@>
18569 mp_primitive(mp, "ASCII",unary,ASCII_op);
18570 @:ASCII_}{\&{ASCII} primitive@>
18571 mp_primitive(mp, "char",unary,char_op);
18572 @:char_}{\&{char} primitive@>
18573 mp_primitive(mp, "length",unary,length_op);
18574 @:length_}{\&{length} primitive@>
18575 mp_primitive(mp, "turningnumber",unary,turning_op);
18576 @:turning_number_}{\&{turningnumber} primitive@>
18577 mp_primitive(mp, "xpart",unary,x_part);
18578 @:x_part_}{\&{xpart} primitive@>
18579 mp_primitive(mp, "ypart",unary,y_part);
18580 @:y_part_}{\&{ypart} primitive@>
18581 mp_primitive(mp, "xxpart",unary,xx_part);
18582 @:xx_part_}{\&{xxpart} primitive@>
18583 mp_primitive(mp, "xypart",unary,xy_part);
18584 @:xy_part_}{\&{xypart} primitive@>
18585 mp_primitive(mp, "yxpart",unary,yx_part);
18586 @:yx_part_}{\&{yxpart} primitive@>
18587 mp_primitive(mp, "yypart",unary,yy_part);
18588 @:yy_part_}{\&{yypart} primitive@>
18589 mp_primitive(mp, "redpart",unary,red_part);
18590 @:red_part_}{\&{redpart} primitive@>
18591 mp_primitive(mp, "greenpart",unary,green_part);
18592 @:green_part_}{\&{greenpart} primitive@>
18593 mp_primitive(mp, "bluepart",unary,blue_part);
18594 @:blue_part_}{\&{bluepart} primitive@>
18595 mp_primitive(mp, "cyanpart",unary,cyan_part);
18596 @:cyan_part_}{\&{cyanpart} primitive@>
18597 mp_primitive(mp, "magentapart",unary,magenta_part);
18598 @:magenta_part_}{\&{magentapart} primitive@>
18599 mp_primitive(mp, "yellowpart",unary,yellow_part);
18600 @:yellow_part_}{\&{yellowpart} primitive@>
18601 mp_primitive(mp, "blackpart",unary,black_part);
18602 @:black_part_}{\&{blackpart} primitive@>
18603 mp_primitive(mp, "greypart",unary,grey_part);
18604 @:grey_part_}{\&{greypart} primitive@>
18605 mp_primitive(mp, "colormodel",unary,color_model_part);
18606 @:color_model_part_}{\&{colormodel} primitive@>
18607 mp_primitive(mp, "fontpart",unary,font_part);
18608 @:font_part_}{\&{fontpart} primitive@>
18609 mp_primitive(mp, "textpart",unary,text_part);
18610 @:text_part_}{\&{textpart} primitive@>
18611 mp_primitive(mp, "pathpart",unary,path_part);
18612 @:path_part_}{\&{pathpart} primitive@>
18613 mp_primitive(mp, "penpart",unary,pen_part);
18614 @:pen_part_}{\&{penpart} primitive@>
18615 mp_primitive(mp, "dashpart",unary,dash_part);
18616 @:dash_part_}{\&{dashpart} primitive@>
18617 mp_primitive(mp, "sqrt",unary,sqrt_op);
18618 @:sqrt_}{\&{sqrt} primitive@>
18619 mp_primitive(mp, "mexp",unary,m_exp_op);
18620 @:m_exp_}{\&{mexp} primitive@>
18621 mp_primitive(mp, "mlog",unary,m_log_op);
18622 @:m_log_}{\&{mlog} primitive@>
18623 mp_primitive(mp, "sind",unary,sin_d_op);
18624 @:sin_d_}{\&{sind} primitive@>
18625 mp_primitive(mp, "cosd",unary,cos_d_op);
18626 @:cos_d_}{\&{cosd} primitive@>
18627 mp_primitive(mp, "floor",unary,floor_op);
18628 @:floor_}{\&{floor} primitive@>
18629 mp_primitive(mp, "uniformdeviate",unary,uniform_deviate);
18630 @:uniform_deviate_}{\&{uniformdeviate} primitive@>
18631 mp_primitive(mp, "charexists",unary,char_exists_op);
18632 @:char_exists_}{\&{charexists} primitive@>
18633 mp_primitive(mp, "fontsize",unary,font_size);
18634 @:font_size_}{\&{fontsize} primitive@>
18635 mp_primitive(mp, "llcorner",unary,ll_corner_op);
18636 @:ll_corner_}{\&{llcorner} primitive@>
18637 mp_primitive(mp, "lrcorner",unary,lr_corner_op);
18638 @:lr_corner_}{\&{lrcorner} primitive@>
18639 mp_primitive(mp, "ulcorner",unary,ul_corner_op);
18640 @:ul_corner_}{\&{ulcorner} primitive@>
18641 mp_primitive(mp, "urcorner",unary,ur_corner_op);
18642 @:ur_corner_}{\&{urcorner} primitive@>
18643 mp_primitive(mp, "arclength",unary,arc_length);
18644 @:arc_length_}{\&{arclength} primitive@>
18645 mp_primitive(mp, "angle",unary,angle_op);
18646 @:angle_}{\&{angle} primitive@>
18647 mp_primitive(mp, "cycle",cycle,cycle_op);
18648 @:cycle_}{\&{cycle} primitive@>
18649 mp_primitive(mp, "stroked",unary,stroked_op);
18650 @:stroked_}{\&{stroked} primitive@>
18651 mp_primitive(mp, "filled",unary,filled_op);
18652 @:filled_}{\&{filled} primitive@>
18653 mp_primitive(mp, "textual",unary,textual_op);
18654 @:textual_}{\&{textual} primitive@>
18655 mp_primitive(mp, "clipped",unary,clipped_op);
18656 @:clipped_}{\&{clipped} primitive@>
18657 mp_primitive(mp, "bounded",unary,bounded_op);
18658 @:bounded_}{\&{bounded} primitive@>
18659 mp_primitive(mp, "+",plus_or_minus,plus);
18660 @:+ }{\.{+} primitive@>
18661 mp_primitive(mp, "-",plus_or_minus,minus);
18662 @:- }{\.{-} primitive@>
18663 mp_primitive(mp, "*",secondary_binary,times);
18664 @:* }{\.{*} primitive@>
18665 mp_primitive(mp, "/",slash,over); mp->eqtb[frozen_slash]=mp->eqtb[mp->cur_sym];
18666 @:/ }{\.{/} primitive@>
18667 mp_primitive(mp, "++",tertiary_binary,pythag_add);
18668 @:++_}{\.{++} primitive@>
18669 mp_primitive(mp, "+-+",tertiary_binary,pythag_sub);
18670 @:+-+_}{\.{+-+} primitive@>
18671 mp_primitive(mp, "or",tertiary_binary,or_op);
18672 @:or_}{\&{or} primitive@>
18673 mp_primitive(mp, "and",and_command,and_op);
18674 @:and_}{\&{and} primitive@>
18675 mp_primitive(mp, "<",expression_binary,less_than);
18676 @:< }{\.{<} primitive@>
18677 mp_primitive(mp, "<=",expression_binary,less_or_equal);
18678 @:<=_}{\.{<=} primitive@>
18679 mp_primitive(mp, ">",expression_binary,greater_than);
18680 @:> }{\.{>} primitive@>
18681 mp_primitive(mp, ">=",expression_binary,greater_or_equal);
18682 @:>=_}{\.{>=} primitive@>
18683 mp_primitive(mp, "=",equals,equal_to);
18684 @:= }{\.{=} primitive@>
18685 mp_primitive(mp, "<>",expression_binary,unequal_to);
18686 @:<>_}{\.{<>} primitive@>
18687 mp_primitive(mp, "substring",primary_binary,substring_of);
18688 @:substring_}{\&{substring} primitive@>
18689 mp_primitive(mp, "subpath",primary_binary,subpath_of);
18690 @:subpath_}{\&{subpath} primitive@>
18691 mp_primitive(mp, "directiontime",primary_binary,direction_time_of);
18692 @:direction_time_}{\&{directiontime} primitive@>
18693 mp_primitive(mp, "point",primary_binary,point_of);
18694 @:point_}{\&{point} primitive@>
18695 mp_primitive(mp, "precontrol",primary_binary,precontrol_of);
18696 @:precontrol_}{\&{precontrol} primitive@>
18697 mp_primitive(mp, "postcontrol",primary_binary,postcontrol_of);
18698 @:postcontrol_}{\&{postcontrol} primitive@>
18699 mp_primitive(mp, "penoffset",primary_binary,pen_offset_of);
18700 @:pen_offset_}{\&{penoffset} primitive@>
18701 mp_primitive(mp, "arctime",primary_binary,arc_time_of);
18702 @:arc_time_of_}{\&{arctime} primitive@>
18703 mp_primitive(mp, "mpversion",nullary,mp_version);
18704 @:mp_verison_}{\&{mpversion} primitive@>
18705 mp_primitive(mp, "&",ampersand,concatenate);
18706 @:!!!}{\.{\&} primitive@>
18707 mp_primitive(mp, "rotated",secondary_binary,rotated_by);
18708 @:rotated_}{\&{rotated} primitive@>
18709 mp_primitive(mp, "slanted",secondary_binary,slanted_by);
18710 @:slanted_}{\&{slanted} primitive@>
18711 mp_primitive(mp, "scaled",secondary_binary,scaled_by);
18712 @:scaled_}{\&{scaled} primitive@>
18713 mp_primitive(mp, "shifted",secondary_binary,shifted_by);
18714 @:shifted_}{\&{shifted} primitive@>
18715 mp_primitive(mp, "transformed",secondary_binary,transformed_by);
18716 @:transformed_}{\&{transformed} primitive@>
18717 mp_primitive(mp, "xscaled",secondary_binary,x_scaled);
18718 @:x_scaled_}{\&{xscaled} primitive@>
18719 mp_primitive(mp, "yscaled",secondary_binary,y_scaled);
18720 @:y_scaled_}{\&{yscaled} primitive@>
18721 mp_primitive(mp, "zscaled",secondary_binary,z_scaled);
18722 @:z_scaled_}{\&{zscaled} primitive@>
18723 mp_primitive(mp, "infont",secondary_binary,in_font);
18724 @:in_font_}{\&{infont} primitive@>
18725 mp_primitive(mp, "intersectiontimes",tertiary_binary,intersect);
18726 @:intersection_times_}{\&{intersectiontimes} primitive@>
18727 mp_primitive(mp, "envelope",primary_binary,envelope_of);
18728 @:envelope_}{\&{envelope} primitive@>
18729
18730 @ @<Cases of |print_cmd...@>=
18731 case nullary:
18732 case unary:
18733 case primary_binary:
18734 case secondary_binary:
18735 case tertiary_binary:
18736 case expression_binary:
18737 case cycle:
18738 case plus_or_minus:
18739 case slash:
18740 case ampersand:
18741 case equals:
18742 case and_command:
18743   mp_print_op(mp, m);
18744   break;
18745
18746 @ OK, let's look at the simplest \\{do} procedure first.
18747
18748 @c @<Declare nullary action procedure@>;
18749 void mp_do_nullary (MP mp,quarterword c) { 
18750   check_arith;
18751   if ( mp->internal[mp_tracing_commands]>two )
18752     mp_show_cmd_mod(mp, nullary,c);
18753   switch (c) {
18754   case true_code: case false_code: 
18755     mp->cur_type=mp_boolean_type; mp->cur_exp=c;
18756     break;
18757   case null_picture_code: 
18758     mp->cur_type=mp_picture_type;
18759     mp->cur_exp=mp_get_node(mp, edge_header_size); 
18760     mp_init_edges(mp, mp->cur_exp);
18761     break;
18762   case null_pen_code: 
18763     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, 0);
18764     break;
18765   case normal_deviate: 
18766     mp->cur_type=mp_known; mp->cur_exp=mp_norm_rand(mp);
18767     break;
18768   case pen_circle: 
18769     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, unity);
18770     break;
18771   case job_name_op:  
18772     if ( mp->job_name==NULL ) mp_open_log_file(mp);
18773     mp->cur_type=mp_string_type; mp->cur_exp=rts(mp->job_name);
18774     break;
18775   case mp_version: 
18776     mp->cur_type=mp_string_type; 
18777     mp->cur_exp=intern(metapost_version) ;
18778     break;
18779   case read_string_op:
18780     @<Read a string from the terminal@>;
18781     break;
18782   } /* there are no other cases */
18783   check_arith;
18784 }
18785
18786 @ @<Read a string...@>=
18787
18788   if ( mp->interaction<=mp_nonstop_mode )
18789     mp_fatal_error(mp, "*** (cannot readstring in nonstop modes)");
18790   mp_begin_file_reading(mp); name=is_read;
18791   limit=start; prompt_input("");
18792   mp_finish_read(mp);
18793 }
18794
18795 @ @<Declare nullary action procedure@>=
18796 void mp_finish_read (MP mp) { /* copy |buffer| line to |cur_exp| */
18797   size_t k;
18798   str_room((int)mp->last-start);
18799   for (k=start;k<=mp->last-1;k++) {
18800    append_char(mp->buffer[k]);
18801   }
18802   mp_end_file_reading(mp); mp->cur_type=mp_string_type; 
18803   mp->cur_exp=mp_make_string(mp);
18804 }
18805
18806 @ Things get a bit more interesting when there's an operand. The
18807 operand to |do_unary| appears in |cur_type| and |cur_exp|.
18808
18809 @c @<Declare unary action procedures@>;
18810 void mp_do_unary (MP mp,quarterword c) {
18811   pointer p,q,r; /* for list manipulation */
18812   integer x; /* a temporary register */
18813   check_arith;
18814   if ( mp->internal[mp_tracing_commands]>two )
18815     @<Trace the current unary operation@>;
18816   switch (c) {
18817   case plus:
18818     if ( mp->cur_type<mp_color_type ) mp_bad_unary(mp, plus);
18819     break;
18820   case minus:
18821     @<Negate the current expression@>;
18822     break;
18823   @<Additional cases of unary operators@>;
18824   } /* there are no other cases */
18825   check_arith;
18826 };
18827
18828 @ The |nice_pair| function returns |true| if both components of a pair
18829 are known.
18830
18831 @<Declare unary action procedures@>=
18832 boolean mp_nice_pair (MP mp,integer p, quarterword t) { 
18833   if ( t==mp_pair_type ) {
18834     p=value(p);
18835     if ( type(x_part_loc(p))==mp_known )
18836       if ( type(y_part_loc(p))==mp_known )
18837         return true;
18838   }
18839   return false;
18840 }
18841
18842 @ The |nice_color_or_pair| function is analogous except that it also accepts
18843 fully known colors.
18844
18845 @<Declare unary action procedures@>=
18846 boolean mp_nice_color_or_pair (MP mp,integer p, quarterword t) {
18847   pointer q,r; /* for scanning the big node */
18848   if ( (t!=mp_pair_type)&&(t!=mp_color_type)&&(t!=mp_cmykcolor_type) ) {
18849     return false;
18850   } else { 
18851     q=value(p);
18852     r=q+mp->big_node_size[type(p)];
18853     do {  
18854       r=r-2;
18855       if ( type(r)!=mp_known )
18856         return false;
18857     } while (r!=q);
18858     return true;
18859   }
18860 }
18861
18862 @ @<Declare unary action...@>=
18863 void mp_print_known_or_unknown_type (MP mp,small_number t, integer v) { 
18864   mp_print_char(mp, '(');
18865   if ( t>mp_known ) mp_print(mp, "unknown numeric");
18866   else { if ( (t==mp_pair_type)||(t==mp_color_type)||(t==mp_cmykcolor_type) )
18867     if ( ! mp_nice_color_or_pair(mp, v,t) ) mp_print(mp, "unknown ");
18868     mp_print_type(mp, t);
18869   }
18870   mp_print_char(mp, ')');
18871 }
18872
18873 @ @<Declare unary action...@>=
18874 void mp_bad_unary (MP mp,quarterword c) { 
18875   exp_err("Not implemented: "); mp_print_op(mp, c);
18876 @.Not implemented...@>
18877   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
18878   help3("I'm afraid I don't know how to apply that operation to that")
18879     ("particular type. Continue, and I'll simply return the")
18880     ("argument (shown above) as the result of the operation.");
18881   mp_put_get_error(mp);
18882 }
18883
18884 @ @<Trace the current unary operation@>=
18885
18886   mp_begin_diagnostic(mp); mp_print_nl(mp, "{"); 
18887   mp_print_op(mp, c); mp_print_char(mp, '(');
18888   mp_print_exp(mp, null,0); /* show the operand, but not verbosely */
18889   mp_print(mp, ")}"); mp_end_diagnostic(mp, false);
18890 }
18891
18892 @ Negation is easy except when the current expression
18893 is of type |independent|, or when it is a pair with one or more
18894 |independent| components.
18895
18896 It is tempting to argue that the negative of an independent variable
18897 is an independent variable, hence we don't have to do anything when
18898 negating it. The fallacy is that other dependent variables pointing
18899 to the current expression must change the sign of their
18900 coefficients if we make no change to the current expression.
18901
18902 Instead, we work around the problem by copying the current expression
18903 and recycling it afterwards (cf.~the |stash_in| routine).
18904
18905 @<Negate the current expression@>=
18906 switch (mp->cur_type) {
18907 case mp_color_type:
18908 case mp_cmykcolor_type:
18909 case mp_pair_type:
18910 case mp_independent: 
18911   q=mp->cur_exp; mp_make_exp_copy(mp, q);
18912   if ( mp->cur_type==mp_dependent ) {
18913     mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18914   } else if ( mp->cur_type<=mp_pair_type ) { /* |mp_color_type| or |mp_pair_type| */
18915     p=value(mp->cur_exp);
18916     r=p+mp->big_node_size[mp->cur_type];
18917     do {  
18918       r=r-2;
18919       if ( type(r)==mp_known ) negate(value(r));
18920       else mp_negate_dep_list(mp, dep_list(r));
18921     } while (r!=p);
18922   } /* if |cur_type=mp_known| then |cur_exp=0| */
18923   mp_recycle_value(mp, q); mp_free_node(mp, q,value_node_size);
18924   break;
18925 case mp_dependent:
18926 case mp_proto_dependent:
18927   mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18928   break;
18929 case mp_known:
18930   negate(mp->cur_exp);
18931   break;
18932 default:
18933   mp_bad_unary(mp, minus);
18934   break;
18935 }
18936
18937 @ @<Declare unary action...@>=
18938 void mp_negate_dep_list (MP mp,pointer p) { 
18939   while (1) { 
18940     negate(value(p));
18941     if ( info(p)==null ) return;
18942     p=link(p);
18943   }
18944 }
18945
18946 @ @<Additional cases of unary operators@>=
18947 case not_op: 
18948   if ( mp->cur_type!=mp_boolean_type ) mp_bad_unary(mp, not_op);
18949   else mp->cur_exp=true_code+false_code-mp->cur_exp;
18950   break;
18951
18952 @ @d three_sixty_units 23592960 /* that's |360*unity| */
18953 @d boolean_reset(A) if ( (A) ) mp->cur_exp=true_code; else mp->cur_exp=false_code
18954
18955 @<Additional cases of unary operators@>=
18956 case sqrt_op:
18957 case m_exp_op:
18958 case m_log_op:
18959 case sin_d_op:
18960 case cos_d_op:
18961 case floor_op:
18962 case  uniform_deviate:
18963 case odd_op:
18964 case char_exists_op:
18965   if ( mp->cur_type!=mp_known ) {
18966     mp_bad_unary(mp, c);
18967   } else {
18968     switch (c) {
18969     case sqrt_op:mp->cur_exp=mp_square_rt(mp, mp->cur_exp);break;
18970     case m_exp_op:mp->cur_exp=mp_m_exp(mp, mp->cur_exp);break;
18971     case m_log_op:mp->cur_exp=mp_m_log(mp, mp->cur_exp);break;
18972     case sin_d_op:
18973     case cos_d_op:
18974       mp_n_sin_cos(mp, (mp->cur_exp % three_sixty_units)*16);
18975       if ( c==sin_d_op ) mp->cur_exp=mp_round_fraction(mp, mp->n_sin);
18976       else mp->cur_exp=mp_round_fraction(mp, mp->n_cos);
18977       break;
18978     case floor_op:mp->cur_exp=mp_floor_scaled(mp, mp->cur_exp);break;
18979     case uniform_deviate:mp->cur_exp=mp_unif_rand(mp, mp->cur_exp);break;
18980     case odd_op: 
18981       boolean_reset(odd(mp_round_unscaled(mp, mp->cur_exp)));
18982       mp->cur_type=mp_boolean_type;
18983       break;
18984     case char_exists_op:
18985       @<Determine if a character has been shipped out@>;
18986       break;
18987     } /* there are no other cases */
18988   }
18989   break;
18990
18991 @ @<Additional cases of unary operators@>=
18992 case angle_op:
18993   if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) ) {
18994     p=value(mp->cur_exp);
18995     x=mp_n_arg(mp, value(x_part_loc(p)),value(y_part_loc(p)));
18996     if ( x>=0 ) mp_flush_cur_exp(mp, (x+8)/ 16);
18997     else mp_flush_cur_exp(mp, -((-x+8)/ 16));
18998   } else {
18999     mp_bad_unary(mp, angle_op);
19000   }
19001   break;
19002
19003 @ If the current expression is a pair, but the context wants it to
19004 be a path, we call |pair_to_path|.
19005
19006 @<Declare unary action...@>=
19007 void mp_pair_to_path (MP mp) { 
19008   mp->cur_exp=mp_new_knot(mp); 
19009   mp->cur_type=mp_path_type;
19010 };
19011
19012 @ @<Additional cases of unary operators@>=
19013 case x_part:
19014 case y_part:
19015   if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_transform_type) )
19016     mp_take_part(mp, c);
19017   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
19018   else mp_bad_unary(mp, c);
19019   break;
19020 case xx_part:
19021 case xy_part:
19022 case yx_part:
19023 case yy_part: 
19024   if ( mp->cur_type==mp_transform_type ) mp_take_part(mp, c);
19025   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
19026   else mp_bad_unary(mp, c);
19027   break;
19028 case red_part:
19029 case green_part:
19030 case blue_part: 
19031   if ( mp->cur_type==mp_color_type ) mp_take_part(mp, c);
19032   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
19033   else mp_bad_unary(mp, c);
19034   break;
19035 case cyan_part:
19036 case magenta_part:
19037 case yellow_part:
19038 case black_part: 
19039   if ( mp->cur_type==mp_cmykcolor_type) mp_take_part(mp, c); 
19040   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
19041   else mp_bad_unary(mp, c);
19042   break;
19043 case grey_part: 
19044   if ( mp->cur_type==mp_known ) mp->cur_exp=value(c);
19045   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
19046   else mp_bad_unary(mp, c);
19047   break;
19048 case color_model_part: 
19049   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
19050   else mp_bad_unary(mp, c);
19051   break;
19052
19053 @ In the following procedure, |cur_exp| points to a capsule, which points to
19054 a big node. We want to delete all but one part of the big node.
19055
19056 @<Declare unary action...@>=
19057 void mp_take_part (MP mp,quarterword c) {
19058   pointer p; /* the big node */
19059   p=value(mp->cur_exp); value(temp_val)=p; type(temp_val)=mp->cur_type;
19060   link(p)=temp_val; mp_free_node(mp, mp->cur_exp,value_node_size);
19061   mp_make_exp_copy(mp, p+mp->sector_offset[c+mp_x_part_sector-x_part]);
19062   mp_recycle_value(mp, temp_val);
19063 }
19064
19065 @ @<Initialize table entries...@>=
19066 name_type(temp_val)=mp_capsule;
19067
19068 @ @<Additional cases of unary operators@>=
19069 case font_part:
19070 case text_part:
19071 case path_part:
19072 case pen_part:
19073 case dash_part:
19074   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
19075   else mp_bad_unary(mp, c);
19076   break;
19077
19078 @ @<Declarations@>=
19079 void mp_scale_edges (MP mp);
19080
19081 @ @<Declare unary action...@>=
19082 void mp_take_pict_part (MP mp,quarterword c) {
19083   pointer p; /* first graphical object in |cur_exp| */
19084   p=link(dummy_loc(mp->cur_exp));
19085   if ( p!=null ) {
19086     switch (c) {
19087     case x_part: case y_part: case xx_part:
19088     case xy_part: case yx_part: case yy_part:
19089       if ( type(p)==mp_text_code ) mp_flush_cur_exp(mp, text_trans_part(p+c));
19090       else goto NOT_FOUND;
19091       break;
19092     case red_part: case green_part: case blue_part:
19093       if ( has_color(p) ) mp_flush_cur_exp(mp, obj_color_part(p+c));
19094       else goto NOT_FOUND;
19095       break;
19096     case cyan_part: case magenta_part: case yellow_part:
19097     case black_part:
19098       if ( has_color(p) ) {
19099         if ( color_model(p)==mp_uninitialized_model )
19100           mp_flush_cur_exp(mp, unity);
19101         else
19102           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-cyan_part)));
19103       } else goto NOT_FOUND;
19104       break;
19105     case grey_part:
19106       if ( has_color(p) )
19107           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-grey_part)));
19108       else goto NOT_FOUND;
19109       break;
19110     case color_model_part:
19111       if ( has_color(p) ) {
19112         if ( color_model(p)==mp_uninitialized_model )
19113           mp_flush_cur_exp(mp, mp->internal[mp_default_color_model]);
19114         else
19115           mp_flush_cur_exp(mp, color_model(p)*unity);
19116       } else goto NOT_FOUND;
19117       break;
19118     @<Handle other cases in |take_pict_part| or |goto not_found|@>;
19119     } /* all cases have been enumerated */
19120     return;
19121   };
19122 NOT_FOUND:
19123   @<Convert the current expression to a null value appropriate
19124     for |c|@>;
19125 }
19126
19127 @ @<Handle other cases in |take_pict_part| or |goto not_found|@>=
19128 case text_part: 
19129   if ( type(p)!=mp_text_code ) goto NOT_FOUND;
19130   else { 
19131     mp_flush_cur_exp(mp, text_p(p));
19132     add_str_ref(mp->cur_exp);
19133     mp->cur_type=mp_string_type;
19134     };
19135   break;
19136 case font_part: 
19137   if ( type(p)!=mp_text_code ) goto NOT_FOUND;
19138   else { 
19139     mp_flush_cur_exp(mp, rts(mp->font_name[font_n(p)])); 
19140     add_str_ref(mp->cur_exp);
19141     mp->cur_type=mp_string_type;
19142   };
19143   break;
19144 case path_part:
19145   if ( type(p)==mp_text_code ) goto NOT_FOUND;
19146   else if ( is_stop(p) ) mp_confusion(mp, "pict");
19147 @:this can't happen pict}{\quad pict@>
19148   else { 
19149     mp_flush_cur_exp(mp, mp_copy_path(mp, path_p(p)));
19150     mp->cur_type=mp_path_type;
19151   }
19152   break;
19153 case pen_part: 
19154   if ( ! has_pen(p) ) goto NOT_FOUND;
19155   else {
19156     if ( pen_p(p)==null ) goto NOT_FOUND;
19157     else { mp_flush_cur_exp(mp, copy_pen(pen_p(p)));
19158       mp->cur_type=mp_pen_type;
19159     };
19160   }
19161   break;
19162 case dash_part: 
19163   if ( type(p)!=mp_stroked_code ) goto NOT_FOUND;
19164   else { if ( dash_p(p)==null ) goto NOT_FOUND;
19165     else { add_edge_ref(dash_p(p));
19166     mp->se_sf=dash_scale(p);
19167     mp->se_pic=dash_p(p);
19168     mp_scale_edges(mp);
19169     mp_flush_cur_exp(mp, mp->se_pic);
19170     mp->cur_type=mp_picture_type;
19171     };
19172   }
19173   break;
19174
19175 @ Since |scale_edges| had to be declared |forward|, it had to be declared as a
19176 parameterless procedure even though it really takes two arguments and updates
19177 one of them.  Hence the following globals are needed.
19178
19179 @<Global...@>=
19180 pointer se_pic;  /* edge header used and updated by |scale_edges| */
19181 scaled se_sf;  /* the scale factor argument to |scale_edges| */
19182
19183 @ @<Convert the current expression to a null value appropriate...@>=
19184 switch (c) {
19185 case text_part: case font_part: 
19186   mp_flush_cur_exp(mp, rts(""));
19187   mp->cur_type=mp_string_type;
19188   break;
19189 case path_part: 
19190   mp_flush_cur_exp(mp, mp_get_node(mp, knot_node_size));
19191   left_type(mp->cur_exp)=mp_endpoint;
19192   right_type(mp->cur_exp)=mp_endpoint;
19193   link(mp->cur_exp)=mp->cur_exp;
19194   x_coord(mp->cur_exp)=0;
19195   y_coord(mp->cur_exp)=0;
19196   originator(mp->cur_exp)=mp_metapost_user;
19197   mp->cur_type=mp_path_type;
19198   break;
19199 case pen_part: 
19200   mp_flush_cur_exp(mp, mp_get_pen_circle(mp, 0));
19201   mp->cur_type=mp_pen_type;
19202   break;
19203 case dash_part: 
19204   mp_flush_cur_exp(mp, mp_get_node(mp, edge_header_size));
19205   mp_init_edges(mp, mp->cur_exp);
19206   mp->cur_type=mp_picture_type;
19207   break;
19208 default: 
19209    mp_flush_cur_exp(mp, 0);
19210   break;
19211 }
19212
19213 @ @<Additional cases of unary...@>=
19214 case char_op: 
19215   if ( mp->cur_type!=mp_known ) { 
19216     mp_bad_unary(mp, char_op);
19217   } else { 
19218     mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256; 
19219     mp->cur_type=mp_string_type;
19220     if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
19221   }
19222   break;
19223 case decimal: 
19224   if ( mp->cur_type!=mp_known ) {
19225      mp_bad_unary(mp, decimal);
19226   } else { 
19227     mp->old_setting=mp->selector; mp->selector=new_string;
19228     mp_print_scaled(mp, mp->cur_exp); mp->cur_exp=mp_make_string(mp);
19229     mp->selector=mp->old_setting; mp->cur_type=mp_string_type;
19230   }
19231   break;
19232 case oct_op:
19233 case hex_op:
19234 case ASCII_op: 
19235   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19236   else mp_str_to_num(mp, c);
19237   break;
19238 case font_size: 
19239   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, font_size);
19240   else @<Find the design size of the font whose name is |cur_exp|@>;
19241   break;
19242
19243 @ @<Declare unary action...@>=
19244 void mp_str_to_num (MP mp,quarterword c) { /* converts a string to a number */
19245   integer n; /* accumulator */
19246   ASCII_code m; /* current character */
19247   pool_pointer k; /* index into |str_pool| */
19248   int b; /* radix of conversion */
19249   boolean bad_char; /* did the string contain an invalid digit? */
19250   if ( c==ASCII_op ) {
19251     if ( length(mp->cur_exp)==0 ) n=-1;
19252     else n=mp->str_pool[mp->str_start[mp->cur_exp]];
19253   } else { 
19254     if ( c==oct_op ) b=8; else b=16;
19255     n=0; bad_char=false;
19256     for (k=mp->str_start[mp->cur_exp];k<=str_stop(mp->cur_exp)-1;k++) {
19257       m=mp->str_pool[k];
19258       if ( (m>='0')&&(m<='9') ) m=m-'0';
19259       else if ( (m>='A')&&(m<='F') ) m=m-'A'+10;
19260       else if ( (m>='a')&&(m<='f') ) m=m-'a'+10;
19261       else  { bad_char=true; m=0; };
19262       if ( m>=b ) { bad_char=true; m=0; };
19263       if ( n<32768 / b ) n=n*b+m; else n=32767;
19264     }
19265     @<Give error messages if |bad_char| or |n>=4096|@>;
19266   }
19267   mp_flush_cur_exp(mp, n*unity);
19268 }
19269
19270 @ @<Give error messages if |bad_char|...@>=
19271 if ( bad_char ) { 
19272   exp_err("String contains illegal digits");
19273 @.String contains illegal digits@>
19274   if ( c==oct_op ) {
19275     help1("I zeroed out characters that weren't in the range 0..7.");
19276   } else  {
19277     help1("I zeroed out characters that weren't hex digits.");
19278   }
19279   mp_put_get_error(mp);
19280 }
19281 if ( (n>4095) ) {
19282   if ( mp->internal[mp_warning_check]>0 ) {
19283     print_err("Number too large ("); 
19284     mp_print_int(mp, n); mp_print_char(mp, ')');
19285 @.Number too large@>
19286     help2("I have trouble with numbers greater than 4095; watch out.")
19287       ("(Set warningcheck:=0 to suppress this message.)");
19288     mp_put_get_error(mp);
19289   }
19290 }
19291
19292 @ The length operation is somewhat unusual in that it applies to a variety
19293 of different types of operands.
19294
19295 @<Additional cases of unary...@>=
19296 case length_op: 
19297   switch (mp->cur_type) {
19298   case mp_string_type: mp_flush_cur_exp(mp, length(mp->cur_exp)*unity); break;
19299   case mp_path_type: mp_flush_cur_exp(mp, mp_path_length(mp)); break;
19300   case mp_known: mp->cur_exp=abs(mp->cur_exp); break;
19301   case mp_picture_type: mp_flush_cur_exp(mp, mp_pict_length(mp)); break;
19302   default: 
19303     if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) )
19304       mp_flush_cur_exp(mp, mp_pyth_add(mp, 
19305         value(x_part_loc(value(mp->cur_exp))),
19306         value(y_part_loc(value(mp->cur_exp)))));
19307     else mp_bad_unary(mp, c);
19308     break;
19309   }
19310   break;
19311
19312 @ @<Declare unary action...@>=
19313 scaled mp_path_length (MP mp) { /* computes the length of the current path */
19314   scaled n; /* the path length so far */
19315   pointer p; /* traverser */
19316   p=mp->cur_exp;
19317   if ( left_type(p)==mp_endpoint ) n=-unity; else n=0;
19318   do {  p=link(p); n=n+unity; } while (p!=mp->cur_exp);
19319   return n;
19320 }
19321
19322 @ @<Declare unary action...@>=
19323 scaled mp_pict_length (MP mp) { 
19324   /* counts interior components in picture |cur_exp| */
19325   scaled n; /* the count so far */
19326   pointer p; /* traverser */
19327   n=0;
19328   p=link(dummy_loc(mp->cur_exp));
19329   if ( p!=null ) {
19330     if ( is_start_or_stop(p) )
19331       if ( mp_skip_1component(mp, p)==null ) p=link(p);
19332     while ( p!=null )  { 
19333       skip_component(p) return n; 
19334       n=n+unity;   
19335     }
19336   }
19337   return n;
19338 }
19339
19340 @ Implement |turningnumber|
19341
19342 @<Additional cases of unary...@>=
19343 case turning_op:
19344   if ( mp->cur_type==mp_pair_type ) mp_flush_cur_exp(mp, 0);
19345   else if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, turning_op);
19346   else if ( left_type(mp->cur_exp)==mp_endpoint )
19347      mp_flush_cur_exp(mp, 0); /* not a cyclic path */
19348   else
19349     mp_flush_cur_exp(mp, mp_turn_cycles_wrapper(mp, mp->cur_exp));
19350   break;
19351
19352 @ The function |an_angle| returns the value of the |angle| primitive, or $0$ if the
19353 argument is |origin|.
19354
19355 @<Declare unary action...@>=
19356 angle mp_an_angle (MP mp,scaled xpar, scaled ypar) {
19357   if ( (! ((xpar==0) && (ypar==0))) )
19358     return mp_n_arg(mp, xpar,ypar);
19359   return 0;
19360 }
19361
19362
19363 @ The actual turning number is (for the moment) computed in a C function
19364 that receives eight integers corresponding to the four controlling points,
19365 and returns a single angle.  Besides those, we have to account for discrete
19366 moves at the actual points.
19367
19368 @d floor(a) (a>=0 ? a : -(int)(-a))
19369 @d bezier_error (720<<20)+1
19370 @d sign(v) ((v)>0 ? 1 : ((v)<0 ? -1 : 0 ))
19371 @d print_roots(a) 
19372 @d out ((double)(xo>>20))
19373 @d mid ((double)(xm>>20))
19374 @d in  ((double)(xi>>20))
19375 @d divisor (256*256)
19376 @d double2angle(a) (int)floor(a*256.0*256.0*16.0)
19377
19378 @<Declare unary action...@>=
19379 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19380             integer CX,integer CY,integer DX,integer DY);
19381
19382 @ @c 
19383 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19384             integer CX,integer CY,integer DX,integer DY) {
19385   double a, b, c;
19386   integer deltax,deltay;
19387   double ax,ay,bx,by,cx,cy,dx,dy;
19388   angle xi = 0, xo = 0, xm = 0;
19389   double res = 0;
19390   ax=AX/divisor;  ay=AY/divisor;
19391   bx=BX/divisor;  by=BY/divisor;
19392   cx=CX/divisor;  cy=CY/divisor;
19393   dx=DX/divisor;  dy=DY/divisor;
19394
19395   deltax = (BX-AX); deltay = (BY-AY);
19396   if (deltax==0 && deltay == 0) { deltax=(CX-AX); deltay=(CY-AY); }
19397   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19398   xi = mp_an_angle(mp,deltax,deltay);
19399
19400   deltax = (CX-BX); deltay = (CY-BY);
19401   xm = mp_an_angle(mp,deltax,deltay);
19402
19403   deltax = (DX-CX); deltay = (DY-CY);
19404   if (deltax==0 && deltay == 0) { deltax=(DX-BX); deltay=(DY-BY); }
19405   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19406   xo = mp_an_angle(mp,deltax,deltay);
19407
19408   a = (bx-ax)*(cy-by) - (cx-bx)*(by-ay); /* a = (bp-ap)x(cp-bp); */
19409   b = (bx-ax)*(dy-cy) - (by-ay)*(dx-cx);; /* b = (bp-ap)x(dp-cp);*/
19410   c = (cx-bx)*(dy-cy) - (dx-cx)*(cy-by); /* c = (cp-bp)x(dp-cp);*/
19411
19412   if ((a==0)&&(c==0)) {
19413     res = (b==0 ?  0 :  (out-in)); 
19414     print_roots("no roots (a)");
19415   } else if ((a==0)||(c==0)) {
19416     if ((sign(b) == sign(a)) || (sign(b) == sign(c))) {
19417       res = out-in; /* ? */
19418       if (res<-180.0) 
19419         res += 360.0;
19420       else if (res>180.0)
19421         res -= 360.0;
19422       print_roots("no roots (b)");
19423     } else {
19424       res = out-in; /* ? */
19425       print_roots("one root (a)");
19426     }
19427   } else if ((sign(a)*sign(c))<0) {
19428     res = out-in; /* ? */
19429       if (res<-180.0) 
19430         res += 360.0;
19431       else if (res>180.0)
19432         res -= 360.0;
19433     print_roots("one root (b)");
19434   } else {
19435     if (sign(a) == sign(b)) {
19436       res = out-in; /* ? */
19437       if (res<-180.0) 
19438         res += 360.0;
19439       else if (res>180.0)
19440         res -= 360.0;
19441       print_roots("no roots (d)");
19442     } else {
19443       if ((b*b) == (4*a*c)) {
19444         res = bezier_error;
19445         print_roots("double root"); /* cusp */
19446       } else if ((b*b) < (4*a*c)) {
19447         res = out-in; /* ? */
19448         if (res<=0.0 &&res>-180.0) 
19449           res += 360.0;
19450         else if (res>=0.0 && res<180.0)
19451           res -= 360.0;
19452         print_roots("no roots (e)");
19453       } else {
19454         res = out-in;
19455         if (res<-180.0) 
19456           res += 360.0;
19457         else if (res>180.0)
19458           res -= 360.0;
19459         print_roots("two roots"); /* two inflections */
19460       }
19461     }
19462   }
19463   return double2angle(res);
19464 }
19465
19466 @
19467 @d p_nextnext link(link(p))
19468 @d p_next link(p)
19469 @d seven_twenty_deg 05500000000 /* $720\cdot2^{20}$, represents $720^\circ$ */
19470
19471 @<Declare unary action...@>=
19472 scaled mp_new_turn_cycles (MP mp,pointer c) {
19473   angle res,ang; /*  the angles of intermediate results  */
19474   scaled turns;  /*  the turn counter  */
19475   pointer p;     /*  for running around the path  */
19476   integer xp,yp;   /*  coordinates of next point  */
19477   integer x,y;   /*  helper coordinates  */
19478   angle in_angle,out_angle;     /*  helper angles */
19479   int old_setting; /* saved |selector| setting */
19480   res=0;
19481   turns= 0;
19482   p=c;
19483   old_setting = mp->selector; mp->selector=term_only;
19484   if ( mp->internal[mp_tracing_commands]>unity ) {
19485     mp_begin_diagnostic(mp);
19486     mp_print_nl(mp, "");
19487     mp_end_diagnostic(mp, false);
19488   }
19489   do { 
19490     xp = x_coord(p_next); yp = y_coord(p_next);
19491     ang  = mp_bezier_slope(mp,x_coord(p), y_coord(p), right_x(p), right_y(p),
19492              left_x(p_next), left_y(p_next), xp, yp);
19493     if ( ang>seven_twenty_deg ) {
19494       print_err("Strange path");
19495       mp_error(mp);
19496       mp->selector=old_setting;
19497       return 0;
19498     }
19499     res  = res + ang;
19500     if ( res > one_eighty_deg ) {
19501       res = res - three_sixty_deg;
19502       turns = turns + unity;
19503     }
19504     if ( res <= -one_eighty_deg ) {
19505       res = res + three_sixty_deg;
19506       turns = turns - unity;
19507     }
19508     /*  incoming angle at next point  */
19509     x = left_x(p_next);  y = left_y(p_next);
19510     if ( (xp==x)&&(yp==y) ) { x = right_x(p);  y = right_y(p);  };
19511     if ( (xp==x)&&(yp==y) ) { x = x_coord(p);  y = y_coord(p);  };
19512     in_angle = mp_an_angle(mp, xp - x, yp - y);
19513     /*  outgoing angle at next point  */
19514     x = right_x(p_next);  y = right_y(p_next);
19515     if ( (xp==x)&&(yp==y) ) { x = left_x(p_nextnext);  y = left_y(p_nextnext);  };
19516     if ( (xp==x)&&(yp==y) ) { x = x_coord(p_nextnext); y = y_coord(p_nextnext); };
19517     out_angle = mp_an_angle(mp, x - xp, y- yp);
19518     ang  = (out_angle - in_angle);
19519     reduce_angle(ang);
19520     if ( ang!=0 ) {
19521       res  = res + ang;
19522       if ( res >= one_eighty_deg ) {
19523         res = res - three_sixty_deg;
19524         turns = turns + unity;
19525       };
19526       if ( res <= -one_eighty_deg ) {
19527         res = res + three_sixty_deg;
19528         turns = turns - unity;
19529       };
19530     };
19531     p = link(p);
19532   } while (p!=c);
19533   mp->selector=old_setting;
19534   return turns;
19535 }
19536
19537
19538 @ This code is based on Bogus\l{}av Jackowski's
19539 |emergency_turningnumber| macro, with some minor changes by Taco
19540 Hoekwater. The macro code looked more like this:
19541 {\obeylines
19542 vardef turning\_number primary p =
19543 ~~save res, ang, turns;
19544 ~~res := 0;
19545 ~~if length p <= 2:
19546 ~~~~if Angle ((point 0 of p) - (postcontrol 0 of p)) >= 0:  1  else: -1 fi
19547 ~~else:
19548 ~~~~for t = 0 upto length p-1 :
19549 ~~~~~~angc := Angle ((point t+1 of p)  - (point t of p))
19550 ~~~~~~~~- Angle ((point t of p) - (point t-1 of p));
19551 ~~~~~~if angc > 180: angc := angc - 360; fi;
19552 ~~~~~~if angc < -180: angc := angc + 360; fi;
19553 ~~~~~~res  := res + angc;
19554 ~~~~endfor;
19555 ~~res/360
19556 ~~fi
19557 enddef;}
19558 The general idea is to calculate only the sum of the angles of
19559 straight lines between the points, of a path, not worrying about cusps
19560 or self-intersections in the segments at all. If the segment is not
19561 well-behaved, the result is not necesarily correct. But the old code
19562 was not always correct either, and worse, it sometimes failed for
19563 well-behaved paths as well. All known bugs that were triggered by the
19564 original code no longer occur with this code, and it runs roughly 3
19565 times as fast because the algorithm is much simpler.
19566
19567 @ It is possible to overflow the return value of the |turn_cycles|
19568 function when the path is sufficiently long and winding, but I am not
19569 going to bother testing for that. In any case, it would only return
19570 the looped result value, which is not a big problem.
19571
19572 The macro code for the repeat loop was a bit nicer to look
19573 at than the pascal code, because it could use |point -1 of p|. In
19574 pascal, the fastest way to loop around the path is not to look
19575 backward once, but forward twice. These defines help hide the trick.
19576
19577 @d p_to link(link(p))
19578 @d p_here link(p)
19579 @d p_from p
19580
19581 @<Declare unary action...@>=
19582 scaled mp_turn_cycles (MP mp,pointer c) {
19583   angle res,ang; /*  the angles of intermediate results  */
19584   scaled turns;  /*  the turn counter  */
19585   pointer p;     /*  for running around the path  */
19586   res=0;  turns= 0; p=c;
19587   do { 
19588     ang  = mp_an_angle (mp, x_coord(p_to) - x_coord(p_here), 
19589                             y_coord(p_to) - y_coord(p_here))
19590         - mp_an_angle (mp, x_coord(p_here) - x_coord(p_from), 
19591                            y_coord(p_here) - y_coord(p_from));
19592     reduce_angle(ang);
19593     res  = res + ang;
19594     if ( res >= three_sixty_deg )  {
19595       res = res - three_sixty_deg;
19596       turns = turns + unity;
19597     };
19598     if ( res <= -three_sixty_deg ) {
19599       res = res + three_sixty_deg;
19600       turns = turns - unity;
19601     };
19602     p = link(p);
19603   } while (p!=c);
19604   return turns;
19605 }
19606
19607 @ @<Declare unary action...@>=
19608 scaled mp_turn_cycles_wrapper (MP mp,pointer c) {
19609   scaled nval,oval;
19610   scaled saved_t_o; /* tracing\_online saved  */
19611   if ( (link(c)==c)||(link(link(c))==c) ) {
19612     if ( mp_an_angle (mp, x_coord(c) - right_x(c),  y_coord(c) - right_y(c)) > 0 )
19613       return unity;
19614     else
19615       return -unity;
19616   } else {
19617     nval = mp_new_turn_cycles(mp, c);
19618     oval = mp_turn_cycles(mp, c);
19619     if ( nval!=oval ) {
19620       saved_t_o=mp->internal[mp_tracing_online];
19621       mp->internal[mp_tracing_online]=unity;
19622       mp_begin_diagnostic(mp);
19623       mp_print_nl (mp, "Warning: the turningnumber algorithms do not agree."
19624                        " The current computed value is ");
19625       mp_print_scaled(mp, nval);
19626       mp_print(mp, ", but the 'connect-the-dots' algorithm returned ");
19627       mp_print_scaled(mp, oval);
19628       mp_end_diagnostic(mp, false);
19629       mp->internal[mp_tracing_online]=saved_t_o;
19630     }
19631     return nval;
19632   }
19633 }
19634
19635 @ @<Declare unary action...@>=
19636 scaled mp_count_turns (MP mp,pointer c) {
19637   pointer p; /* a knot in envelope spec |c| */
19638   integer t; /* total pen offset changes counted */
19639   t=0; p=c;
19640   do {  
19641     t=t+info(p)-zero_off;
19642     p=link(p);
19643   } while (p!=c);
19644   return ((t / 3)*unity);
19645 }
19646
19647 @ @d type_range(A,B) { 
19648   if ( (mp->cur_type>=(A)) && (mp->cur_type<=(B)) ) 
19649     mp_flush_cur_exp(mp, true_code);
19650   else mp_flush_cur_exp(mp, false_code);
19651   mp->cur_type=mp_boolean_type;
19652   }
19653 @d type_test(A) { 
19654   if ( mp->cur_type==(A) ) mp_flush_cur_exp(mp, true_code);
19655   else mp_flush_cur_exp(mp, false_code);
19656   mp->cur_type=mp_boolean_type;
19657   }
19658
19659 @<Additional cases of unary operators@>=
19660 case mp_boolean_type: 
19661   type_range(mp_boolean_type,mp_unknown_boolean); break;
19662 case mp_string_type: 
19663   type_range(mp_string_type,mp_unknown_string); break;
19664 case mp_pen_type: 
19665   type_range(mp_pen_type,mp_unknown_pen); break;
19666 case mp_path_type: 
19667   type_range(mp_path_type,mp_unknown_path); break;
19668 case mp_picture_type: 
19669   type_range(mp_picture_type,mp_unknown_picture); break;
19670 case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
19671 case mp_pair_type: 
19672   type_test(c); break;
19673 case mp_numeric_type: 
19674   type_range(mp_known,mp_independent); break;
19675 case known_op: case unknown_op: 
19676   mp_test_known(mp, c); break;
19677
19678 @ @<Declare unary action procedures@>=
19679 void mp_test_known (MP mp,quarterword c) {
19680   int b; /* is the current expression known? */
19681   pointer p,q; /* locations in a big node */
19682   b=false_code;
19683   switch (mp->cur_type) {
19684   case mp_vacuous: case mp_boolean_type: case mp_string_type:
19685   case mp_pen_type: case mp_path_type: case mp_picture_type:
19686   case mp_known: 
19687     b=true_code;
19688     break;
19689   case mp_transform_type:
19690   case mp_color_type: case mp_cmykcolor_type: case mp_pair_type: 
19691     p=value(mp->cur_exp);
19692     q=p+mp->big_node_size[mp->cur_type];
19693     do {  
19694       q=q-2;
19695       if ( type(q)!=mp_known ) 
19696        goto DONE;
19697     } while (q!=p);
19698     b=true_code;
19699   DONE:  
19700     break;
19701   default: 
19702     break;
19703   }
19704   if ( c==known_op ) mp_flush_cur_exp(mp, b);
19705   else mp_flush_cur_exp(mp, true_code+false_code-b);
19706   mp->cur_type=mp_boolean_type;
19707 }
19708
19709 @ @<Additional cases of unary operators@>=
19710 case cycle_op: 
19711   if ( mp->cur_type!=mp_path_type ) mp_flush_cur_exp(mp, false_code);
19712   else if ( left_type(mp->cur_exp)!=mp_endpoint ) mp_flush_cur_exp(mp, true_code);
19713   else mp_flush_cur_exp(mp, false_code);
19714   mp->cur_type=mp_boolean_type;
19715   break;
19716
19717 @ @<Additional cases of unary operators@>=
19718 case arc_length: 
19719   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19720   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, arc_length);
19721   else mp_flush_cur_exp(mp, mp_get_arc_length(mp, mp->cur_exp));
19722   break;
19723
19724 @ Here we use the fact that |c-filled_op+fill_code| is the desired graphical
19725 object |type|.
19726 @^data structure assumptions@>
19727
19728 @<Additional cases of unary operators@>=
19729 case filled_op:
19730 case stroked_op:
19731 case textual_op:
19732 case clipped_op:
19733 case bounded_op:
19734   if ( mp->cur_type!=mp_picture_type ) mp_flush_cur_exp(mp, false_code);
19735   else if ( link(dummy_loc(mp->cur_exp))==null ) mp_flush_cur_exp(mp, false_code);
19736   else if ( type(link(dummy_loc(mp->cur_exp)))==c+mp_fill_code-filled_op )
19737     mp_flush_cur_exp(mp, true_code);
19738   else mp_flush_cur_exp(mp, false_code);
19739   mp->cur_type=mp_boolean_type;
19740   break;
19741
19742 @ @<Additional cases of unary operators@>=
19743 case make_pen_op: 
19744   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19745   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, make_pen_op);
19746   else { 
19747     mp->cur_type=mp_pen_type;
19748     mp->cur_exp=mp_make_pen(mp, mp->cur_exp,true);
19749   };
19750   break;
19751 case make_path_op: 
19752   if ( mp->cur_type!=mp_pen_type ) mp_bad_unary(mp, make_path_op);
19753   else  { 
19754     mp->cur_type=mp_path_type;
19755     mp_make_path(mp, mp->cur_exp);
19756   };
19757   break;
19758 case reverse: 
19759   if ( mp->cur_type==mp_path_type ) {
19760     p=mp_htap_ypoc(mp, mp->cur_exp);
19761     if ( right_type(p)==mp_endpoint ) p=link(p);
19762     mp_toss_knot_list(mp, mp->cur_exp); mp->cur_exp=p;
19763   } else if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19764   else mp_bad_unary(mp, reverse);
19765   break;
19766
19767 @ The |pair_value| routine changes the current expression to a
19768 given ordered pair of values.
19769
19770 @<Declare unary action procedures@>=
19771 void mp_pair_value (MP mp,scaled x, scaled y) {
19772   pointer p; /* a pair node */
19773   p=mp_get_node(mp, value_node_size); 
19774   mp_flush_cur_exp(mp, p); mp->cur_type=mp_pair_type;
19775   type(p)=mp_pair_type; name_type(p)=mp_capsule; mp_init_big_node(mp, p);
19776   p=value(p);
19777   type(x_part_loc(p))=mp_known; value(x_part_loc(p))=x;
19778   type(y_part_loc(p))=mp_known; value(y_part_loc(p))=y;
19779 }
19780
19781 @ @<Additional cases of unary operators@>=
19782 case ll_corner_op: 
19783   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ll_corner_op);
19784   else mp_pair_value(mp, minx,miny);
19785   break;
19786 case lr_corner_op: 
19787   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, lr_corner_op);
19788   else mp_pair_value(mp, maxx,miny);
19789   break;
19790 case ul_corner_op: 
19791   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ul_corner_op);
19792   else mp_pair_value(mp, minx,maxy);
19793   break;
19794 case ur_corner_op: 
19795   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ur_corner_op);
19796   else mp_pair_value(mp, maxx,maxy);
19797   break;
19798
19799 @ Here is a function that sets |minx|, |maxx|, |miny|, |maxy| to the bounding
19800 box of the current expression.  The boolean result is |false| if the expression
19801 has the wrong type.
19802
19803 @<Declare unary action procedures@>=
19804 boolean mp_get_cur_bbox (MP mp) { 
19805   switch (mp->cur_type) {
19806   case mp_picture_type: 
19807     mp_set_bbox(mp, mp->cur_exp,true);
19808     if ( minx_val(mp->cur_exp)>maxx_val(mp->cur_exp) ) {
19809       minx=0; maxx=0; miny=0; maxy=0;
19810     } else { 
19811       minx=minx_val(mp->cur_exp);
19812       maxx=maxx_val(mp->cur_exp);
19813       miny=miny_val(mp->cur_exp);
19814       maxy=maxy_val(mp->cur_exp);
19815     }
19816     break;
19817   case mp_path_type: 
19818     mp_path_bbox(mp, mp->cur_exp);
19819     break;
19820   case mp_pen_type: 
19821     mp_pen_bbox(mp, mp->cur_exp);
19822     break;
19823   default: 
19824     return false;
19825   }
19826   return true;
19827 }
19828
19829 @ @<Additional cases of unary operators@>=
19830 case read_from_op:
19831 case close_from_op: 
19832   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19833   else mp_do_read_or_close(mp,c);
19834   break;
19835
19836 @ Here is a routine that interprets |cur_exp| as a file name and tries to read
19837 a line from the file or to close the file.
19838
19839 @<Declare unary action procedures@>=
19840 void mp_do_read_or_close (MP mp,quarterword c) {
19841   readf_index n,n0; /* indices for searching |rd_fname| */
19842   @<Find the |n| where |rd_fname[n]=cur_exp|; if |cur_exp| must be inserted,
19843     call |start_read_input| and |goto found| or |not_found|@>;
19844   mp_begin_file_reading(mp);
19845   name=is_read;
19846   if ( mp_input_ln(mp, mp->rd_file[n] ) ) 
19847     goto FOUND;
19848   mp_end_file_reading(mp);
19849 NOT_FOUND:
19850   @<Record the end of file and set |cur_exp| to a dummy value@>;
19851   return;
19852 CLOSE_FILE:
19853   mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous; 
19854   return;
19855 FOUND:
19856   mp_flush_cur_exp(mp, 0);
19857   mp_finish_read(mp);
19858 }
19859
19860 @ Free slots in the |rd_file| and |rd_fname| arrays are marked with NULL's in
19861 |rd_fname|.
19862
19863 @<Find the |n| where |rd_fname[n]=cur_exp|...@>=
19864 {   
19865   char *fn;
19866   n=mp->read_files;
19867   n0=mp->read_files;
19868   fn = str(mp->cur_exp);
19869   while (mp_xstrcmp(fn,mp->rd_fname[n])!=0) { 
19870     if ( n>0 ) {
19871       decr(n);
19872     } else if ( c==close_from_op ) {
19873       goto CLOSE_FILE;
19874     } else {
19875       if ( n0==mp->read_files ) {
19876         if ( mp->read_files<mp->max_read_files ) {
19877           incr(mp->read_files);
19878         } else {
19879           void **rd_file;
19880           char **rd_fname;
19881               readf_index l,k;
19882           l = mp->max_read_files + (mp->max_read_files>>2);
19883           rd_file = xmalloc((l+1), sizeof(void *));
19884           rd_fname = xmalloc((l+1), sizeof(char *));
19885               for (k=0;k<=l;k++) {
19886             if (k<=mp->max_read_files) {
19887                   rd_file[k]=mp->rd_file[k]; 
19888               rd_fname[k]=mp->rd_fname[k];
19889             } else {
19890               rd_file[k]=0; 
19891               rd_fname[k]=NULL;
19892             }
19893           }
19894               xfree(mp->rd_file); xfree(mp->rd_fname);
19895           mp->max_read_files = l;
19896           mp->rd_file = rd_file;
19897           mp->rd_fname = rd_fname;
19898         }
19899       }
19900       n=n0;
19901       if ( mp_start_read_input(mp,fn,n) ) 
19902         goto FOUND;
19903       else 
19904         goto NOT_FOUND;
19905     }
19906     if ( mp->rd_fname[n]==NULL ) { n0=n; }
19907   } 
19908   if ( c==close_from_op ) { 
19909     (mp->close_file)(mp->rd_file[n]); 
19910     goto NOT_FOUND; 
19911   }
19912 }
19913
19914 @ @<Record the end of file and set |cur_exp| to a dummy value@>=
19915 xfree(mp->rd_fname[n]);
19916 mp->rd_fname[n]=NULL;
19917 if ( n==mp->read_files-1 ) mp->read_files=n;
19918 if ( c==close_from_op ) 
19919   goto CLOSE_FILE;
19920 mp_flush_cur_exp(mp, mp->eof_line);
19921 mp->cur_type=mp_string_type
19922
19923 @ The string denoting end-of-file is a one-byte string at position zero, by definition
19924
19925 @<Glob...@>=
19926 str_number eof_line;
19927
19928 @ @<Set init...@>=
19929 mp->eof_line=0;
19930
19931 @ Finally, we have the operations that combine a capsule~|p|
19932 with the current expression.
19933
19934 @c @<Declare binary action procedures@>;
19935 void mp_do_binary (MP mp,pointer p, quarterword c) {
19936   pointer q,r,rr; /* for list manipulation */
19937   pointer old_p,old_exp; /* capsules to recycle */
19938   integer v; /* for numeric manipulation */
19939   check_arith;
19940   if ( mp->internal[mp_tracing_commands]>two ) {
19941     @<Trace the current binary operation@>;
19942   }
19943   @<Sidestep |independent| cases in capsule |p|@>;
19944   @<Sidestep |independent| cases in the current expression@>;
19945   switch (c) {
19946   case plus: case minus:
19947     @<Add or subtract the current expression from |p|@>;
19948     break;
19949   @<Additional cases of binary operators@>;
19950   }; /* there are no other cases */
19951   mp_recycle_value(mp, p); 
19952   mp_free_node(mp, p,value_node_size); /* |return| to avoid this */
19953   check_arith; 
19954   @<Recycle any sidestepped |independent| capsules@>;
19955 }
19956
19957 @ @<Declare binary action...@>=
19958 void mp_bad_binary (MP mp,pointer p, quarterword c) { 
19959   mp_disp_err(mp, p,"");
19960   exp_err("Not implemented: ");
19961 @.Not implemented...@>
19962   if ( c>=min_of ) mp_print_op(mp, c);
19963   mp_print_known_or_unknown_type(mp, type(p),p);
19964   if ( c>=min_of ) mp_print(mp, "of"); else mp_print_op(mp, c);
19965   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
19966   help3("I'm afraid I don't know how to apply that operation to that")
19967        ("combination of types. Continue, and I'll return the second")
19968       ("argument (see above) as the result of the operation.");
19969   mp_put_get_error(mp);
19970 }
19971 void mp_bad_envelope_pen (MP mp) {
19972   mp_disp_err(mp, null,"");
19973   exp_err("Not implemented: envelope(elliptical pen)of(path)");
19974 @.Not implemented...@>
19975   help3("I'm afraid I don't know how to apply that operation to that")
19976        ("combination of types. Continue, and I'll return the second")
19977       ("argument (see above) as the result of the operation.");
19978   mp_put_get_error(mp);
19979 }
19980
19981 @ @<Trace the current binary operation@>=
19982
19983   mp_begin_diagnostic(mp); mp_print_nl(mp, "{(");
19984   mp_print_exp(mp,p,0); /* show the operand, but not verbosely */
19985   mp_print_char(mp,')'); mp_print_op(mp,c); mp_print_char(mp,'(');
19986   mp_print_exp(mp,null,0); mp_print(mp,")}"); 
19987   mp_end_diagnostic(mp, false);
19988 }
19989
19990 @ Several of the binary operations are potentially complicated by the
19991 fact that |independent| values can sneak into capsules. For example,
19992 we've seen an instance of this difficulty in the unary operation
19993 of negation. In order to reduce the number of cases that need to be
19994 handled, we first change the two operands (if necessary)
19995 to rid them of |independent| components. The original operands are
19996 put into capsules called |old_p| and |old_exp|, which will be
19997 recycled after the binary operation has been safely carried out.
19998
19999 @<Recycle any sidestepped |independent| capsules@>=
20000 if ( old_p!=null ) { 
20001   mp_recycle_value(mp, old_p); mp_free_node(mp, old_p,value_node_size);
20002 }
20003 if ( old_exp!=null ) {
20004   mp_recycle_value(mp, old_exp); mp_free_node(mp, old_exp,value_node_size);
20005 }
20006
20007 @ A big node is considered to be ``tarnished'' if it contains at least one
20008 independent component. We will define a simple function called `|tarnished|'
20009 that returns |null| if and only if its argument is not tarnished.
20010
20011 @<Sidestep |independent| cases in capsule |p|@>=
20012 switch (type(p)) {
20013 case mp_transform_type:
20014 case mp_color_type:
20015 case mp_cmykcolor_type:
20016 case mp_pair_type: 
20017   old_p=mp_tarnished(mp, p);
20018   break;
20019 case mp_independent: old_p=mp_void; break;
20020 default: old_p=null; break;
20021 };
20022 if ( old_p!=null ) {
20023   q=mp_stash_cur_exp(mp); old_p=p; mp_make_exp_copy(mp, old_p);
20024   p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
20025 }
20026
20027 @ @<Sidestep |independent| cases in the current expression@>=
20028 switch (mp->cur_type) {
20029 case mp_transform_type:
20030 case mp_color_type:
20031 case mp_cmykcolor_type:
20032 case mp_pair_type: 
20033   old_exp=mp_tarnished(mp, mp->cur_exp);
20034   break;
20035 case mp_independent:old_exp=mp_void; break;
20036 default: old_exp=null; break;
20037 };
20038 if ( old_exp!=null ) {
20039   old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
20040 }
20041
20042 @ @<Declare binary action...@>=
20043 pointer mp_tarnished (MP mp,pointer p) {
20044   pointer q; /* beginning of the big node */
20045   pointer r; /* current position in the big node */
20046   q=value(p); r=q+mp->big_node_size[type(p)];
20047   do {  
20048    r=r-2;
20049    if ( type(r)==mp_independent ) return mp_void; 
20050   } while (r!=q);
20051   return null;
20052 }
20053
20054 @ @<Add or subtract the current expression from |p|@>=
20055 if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
20056   mp_bad_binary(mp, p,c);
20057 } else  {
20058   if ((mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
20059     mp_add_or_subtract(mp, p,null,c);
20060   } else {
20061     if ( mp->cur_type!=type(p) )  {
20062       mp_bad_binary(mp, p,c);
20063     } else { 
20064       q=value(p); r=value(mp->cur_exp);
20065       rr=r+mp->big_node_size[mp->cur_type];
20066       while ( r<rr ) { 
20067         mp_add_or_subtract(mp, q,r,c);
20068         q=q+2; r=r+2;
20069       }
20070     }
20071   }
20072 }
20073
20074 @ The first argument to |add_or_subtract| is the location of a value node
20075 in a capsule or pair node that will soon be recycled. The second argument
20076 is either a location within a pair or transform node of |cur_exp|,
20077 or it is null (which means that |cur_exp| itself should be the second
20078 argument).  The third argument is either |plus| or |minus|.
20079
20080 The sum or difference of the numeric quantities will replace the second
20081 operand.  Arithmetic overflow may go undetected; users aren't supposed to
20082 be monkeying around with really big values.
20083
20084 @<Declare binary action...@>=
20085 @<Declare the procedure called |dep_finish|@>;
20086 void mp_add_or_subtract (MP mp,pointer p, pointer q, quarterword c) {
20087   small_number s,t; /* operand types */
20088   pointer r; /* list traverser */
20089   integer v; /* second operand value */
20090   if ( q==null ) { 
20091     t=mp->cur_type;
20092     if ( t<mp_dependent ) v=mp->cur_exp; else v=dep_list(mp->cur_exp);
20093   } else { 
20094     t=type(q);
20095     if ( t<mp_dependent ) v=value(q); else v=dep_list(q);
20096   }
20097   if ( t==mp_known ) {
20098     if ( c==minus ) negate(v);
20099     if ( type(p)==mp_known ) {
20100       v=mp_slow_add(mp, value(p),v);
20101       if ( q==null ) mp->cur_exp=v; else value(q)=v;
20102       return;
20103     }
20104     @<Add a known value to the constant term of |dep_list(p)|@>;
20105   } else  { 
20106     if ( c==minus ) mp_negate_dep_list(mp, v);
20107     @<Add operand |p| to the dependency list |v|@>;
20108   }
20109 }
20110
20111 @ @<Add a known value to the constant term of |dep_list(p)|@>=
20112 r=dep_list(p);
20113 while ( info(r)!=null ) r=link(r);
20114 value(r)=mp_slow_add(mp, value(r),v);
20115 if ( q==null ) {
20116   q=mp_get_node(mp, value_node_size); mp->cur_exp=q; mp->cur_type=type(p);
20117   name_type(q)=mp_capsule;
20118 }
20119 dep_list(q)=dep_list(p); type(q)=type(p);
20120 prev_dep(q)=prev_dep(p); link(prev_dep(p))=q;
20121 type(p)=mp_known; /* this will keep the recycler from collecting non-garbage */
20122
20123 @ We prefer |dependent| lists to |mp_proto_dependent| ones, because it is
20124 nice to retain the extra accuracy of |fraction| coefficients.
20125 But we have to handle both kinds, and mixtures too.
20126
20127 @<Add operand |p| to the dependency list |v|@>=
20128 if ( type(p)==mp_known ) {
20129   @<Add the known |value(p)| to the constant term of |v|@>;
20130 } else { 
20131   s=type(p); r=dep_list(p);
20132   if ( t==mp_dependent ) {
20133     if ( s==mp_dependent ) {
20134       if ( mp_max_coef(mp, r)+mp_max_coef(mp, v)<coef_bound )
20135         v=mp_p_plus_q(mp, v,r,mp_dependent); goto DONE;
20136       } /* |fix_needed| will necessarily be false */
20137       t=mp_proto_dependent; 
20138       v=mp_p_over_v(mp, v,unity,mp_dependent,mp_proto_dependent);
20139     }
20140     if ( s==mp_proto_dependent ) v=mp_p_plus_q(mp, v,r,mp_proto_dependent);
20141     else v=mp_p_plus_fq(mp, v,unity,r,mp_proto_dependent,mp_dependent);
20142  DONE:  
20143     @<Output the answer, |v| (which might have become |known|)@>;
20144   }
20145
20146 @ @<Add the known |value(p)| to the constant term of |v|@>=
20147
20148   while ( info(v)!=null ) v=link(v);
20149   value(v)=mp_slow_add(mp, value(p),value(v));
20150 }
20151
20152 @ @<Output the answer, |v| (which might have become |known|)@>=
20153 if ( q!=null ) mp_dep_finish(mp, v,q,t);
20154 else  { mp->cur_type=t; mp_dep_finish(mp, v,null,t); }
20155
20156 @ Here's the current situation: The dependency list |v| of type |t|
20157 should either be put into the current expression (if |q=null|) or
20158 into location |q| within a pair node (otherwise). The destination (|cur_exp|
20159 or |q|) formerly held a dependency list with the same
20160 final pointer as the list |v|.
20161
20162 @<Declare the procedure called |dep_finish|@>=
20163 void mp_dep_finish (MP mp, pointer v, pointer q, small_number t) {
20164   pointer p; /* the destination */
20165   scaled vv; /* the value, if it is |known| */
20166   if ( q==null ) p=mp->cur_exp; else p=q;
20167   dep_list(p)=v; type(p)=t;
20168   if ( info(v)==null ) { 
20169     vv=value(v);
20170     if ( q==null ) { 
20171       mp_flush_cur_exp(mp, vv);
20172     } else  { 
20173       mp_recycle_value(mp, p); type(q)=mp_known; value(q)=vv; 
20174     }
20175   } else if ( q==null ) {
20176     mp->cur_type=t;
20177   }
20178   if ( mp->fix_needed ) mp_fix_dependencies(mp);
20179 }
20180
20181 @ Let's turn now to the six basic relations of comparison.
20182
20183 @<Additional cases of binary operators@>=
20184 case less_than: case less_or_equal: case greater_than:
20185 case greater_or_equal: case equal_to: case unequal_to:
20186   check_arith; /* at this point |arith_error| should be |false|? */
20187   if ( (mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
20188     mp_add_or_subtract(mp, p,null,minus); /* |cur_exp:=(p)-cur_exp| */
20189   } else if ( mp->cur_type!=type(p) ) {
20190     mp_bad_binary(mp, p,c); goto DONE; 
20191   } else if ( mp->cur_type==mp_string_type ) {
20192     mp_flush_cur_exp(mp, mp_str_vs_str(mp, value(p),mp->cur_exp));
20193   } else if ((mp->cur_type==mp_unknown_string)||
20194            (mp->cur_type==mp_unknown_boolean) ) {
20195     @<Check if unknowns have been equated@>;
20196   } else if ( (mp->cur_type<=mp_pair_type)&&(mp->cur_type>=mp_transform_type)) {
20197     @<Reduce comparison of big nodes to comparison of scalars@>;
20198   } else if ( mp->cur_type==mp_boolean_type ) {
20199     mp_flush_cur_exp(mp, mp->cur_exp-value(p));
20200   } else { 
20201     mp_bad_binary(mp, p,c); goto DONE;
20202   }
20203   @<Compare the current expression with zero@>;
20204 DONE:  
20205   mp->arith_error=false; /* ignore overflow in comparisons */
20206   break;
20207
20208 @ @<Compare the current expression with zero@>=
20209 if ( mp->cur_type!=mp_known ) {
20210   if ( mp->cur_type<mp_known ) {
20211     mp_disp_err(mp, p,"");
20212     help1("The quantities shown above have not been equated.")
20213   } else  {
20214     help2("Oh dear. I can\'t decide if the expression above is positive,")
20215      ("negative, or zero. So this comparison test won't be `true'.");
20216   }
20217   exp_err("Unknown relation will be considered false");
20218 @.Unknown relation...@>
20219   mp_put_get_flush_error(mp, false_code);
20220 } else {
20221   switch (c) {
20222   case less_than: boolean_reset(mp->cur_exp<0); break;
20223   case less_or_equal: boolean_reset(mp->cur_exp<=0); break;
20224   case greater_than: boolean_reset(mp->cur_exp>0); break;
20225   case greater_or_equal: boolean_reset(mp->cur_exp>=0); break;
20226   case equal_to: boolean_reset(mp->cur_exp==0); break;
20227   case unequal_to: boolean_reset(mp->cur_exp!=0); break;
20228   }; /* there are no other cases */
20229 }
20230 mp->cur_type=mp_boolean_type
20231
20232 @ When two unknown strings are in the same ring, we know that they are
20233 equal. Otherwise, we don't know whether they are equal or not, so we
20234 make no change.
20235
20236 @<Check if unknowns have been equated@>=
20237
20238   q=value(mp->cur_exp);
20239   while ( (q!=mp->cur_exp)&&(q!=p) ) q=value(q);
20240   if ( q==p ) mp_flush_cur_exp(mp, 0);
20241 }
20242
20243 @ @<Reduce comparison of big nodes to comparison of scalars@>=
20244
20245   q=value(p); r=value(mp->cur_exp);
20246   rr=r+mp->big_node_size[mp->cur_type]-2;
20247   while (1) { mp_add_or_subtract(mp, q,r,minus);
20248     if ( type(r)!=mp_known ) break;
20249     if ( value(r)!=0 ) break;
20250     if ( r==rr ) break;
20251     q=q+2; r=r+2;
20252   }
20253   mp_take_part(mp, name_type(r)+x_part-mp_x_part_sector);
20254 }
20255
20256 @ Here we use the sneaky fact that |and_op-false_code=or_op-true_code|.
20257
20258 @<Additional cases of binary operators@>=
20259 case and_op:
20260 case or_op: 
20261   if ( (type(p)!=mp_boolean_type)||(mp->cur_type!=mp_boolean_type) )
20262     mp_bad_binary(mp, p,c);
20263   else if ( value(p)==c+false_code-and_op ) mp->cur_exp=value(p);
20264   break;
20265
20266 @ @<Additional cases of binary operators@>=
20267 case times: 
20268   if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
20269    mp_bad_binary(mp, p,times);
20270   } else if ( (mp->cur_type==mp_known)||(type(p)==mp_known) ) {
20271     @<Multiply when at least one operand is known@>;
20272   } else if ( (mp_nice_color_or_pair(mp, p,type(p))&&(mp->cur_type>mp_pair_type))
20273       ||(mp_nice_color_or_pair(mp, mp->cur_exp,mp->cur_type)&&
20274           (type(p)>mp_pair_type)) ) {
20275     mp_hard_times(mp, p); return;
20276   } else {
20277     mp_bad_binary(mp, p,times);
20278   }
20279   break;
20280
20281 @ @<Multiply when at least one operand is known@>=
20282
20283   if ( type(p)==mp_known ) {
20284     v=value(p); mp_free_node(mp, p,value_node_size); 
20285   } else {
20286     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20287   }
20288   if ( mp->cur_type==mp_known ) {
20289     mp->cur_exp=mp_take_scaled(mp, mp->cur_exp,v);
20290   } else if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_color_type)||
20291               (mp->cur_type==mp_cmykcolor_type) ) {
20292     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20293     do {  
20294        p=p-2; mp_dep_mult(mp, p,v,true);
20295     } while (p!=value(mp->cur_exp));
20296   } else {
20297     mp_dep_mult(mp, null,v,true);
20298   }
20299   return;
20300 }
20301
20302 @ @<Declare binary action...@>=
20303 void mp_dep_mult (MP mp,pointer p, integer v, boolean v_is_scaled) {
20304   pointer q; /* the dependency list being multiplied by |v| */
20305   small_number s,t; /* its type, before and after */
20306   if ( p==null ) {
20307     q=mp->cur_exp;
20308   } else if ( type(p)!=mp_known ) {
20309     q=p;
20310   } else { 
20311     if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
20312     else value(p)=mp_take_fraction(mp, value(p),v);
20313     return;
20314   };
20315   t=type(q); q=dep_list(q); s=t;
20316   if ( t==mp_dependent ) if ( v_is_scaled )
20317     if (mp_ab_vs_cd(mp, mp_max_coef(mp,q),abs(v),coef_bound-1,unity)>=0 ) 
20318       t=mp_proto_dependent;
20319   q=mp_p_times_v(mp, q,v,s,t,v_is_scaled); 
20320   mp_dep_finish(mp, q,p,t);
20321 }
20322
20323 @ Here is a routine that is similar to |times|; but it is invoked only
20324 internally, when |v| is a |fraction| whose magnitude is at most~1,
20325 and when |cur_type>=mp_color_type|.
20326
20327 @c void mp_frac_mult (MP mp,scaled n, scaled d) {
20328   /* multiplies |cur_exp| by |n/d| */
20329   pointer p; /* a pair node */
20330   pointer old_exp; /* a capsule to recycle */
20331   fraction v; /* |n/d| */
20332   if ( mp->internal[mp_tracing_commands]>two ) {
20333     @<Trace the fraction multiplication@>;
20334   }
20335   switch (mp->cur_type) {
20336   case mp_transform_type:
20337   case mp_color_type:
20338   case mp_cmykcolor_type:
20339   case mp_pair_type:
20340    old_exp=mp_tarnished(mp, mp->cur_exp);
20341    break;
20342   case mp_independent: old_exp=mp_void; break;
20343   default: old_exp=null; break;
20344   }
20345   if ( old_exp!=null ) { 
20346      old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
20347   }
20348   v=mp_make_fraction(mp, n,d);
20349   if ( mp->cur_type==mp_known ) {
20350     mp->cur_exp=mp_take_fraction(mp, mp->cur_exp,v);
20351   } else if ( mp->cur_type<=mp_pair_type ) { 
20352     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20353     do {  
20354       p=p-2;
20355       mp_dep_mult(mp, p,v,false);
20356     } while (p!=value(mp->cur_exp));
20357   } else {
20358     mp_dep_mult(mp, null,v,false);
20359   }
20360   if ( old_exp!=null ) {
20361     mp_recycle_value(mp, old_exp); 
20362     mp_free_node(mp, old_exp,value_node_size);
20363   }
20364 }
20365
20366 @ @<Trace the fraction multiplication@>=
20367
20368   mp_begin_diagnostic(mp); 
20369   mp_print_nl(mp, "{("); mp_print_scaled(mp,n); mp_print_char(mp,'/');
20370   mp_print_scaled(mp,d); mp_print(mp,")*("); mp_print_exp(mp,null,0); 
20371   mp_print(mp,")}");
20372   mp_end_diagnostic(mp, false);
20373 }
20374
20375 @ The |hard_times| routine multiplies a nice color or pair by a dependency list.
20376
20377 @<Declare binary action procedures@>=
20378 void mp_hard_times (MP mp,pointer p) {
20379   pointer q; /* a copy of the dependent variable |p| */
20380   pointer r; /* a component of the big node for the nice color or pair */
20381   scaled v; /* the known value for |r| */
20382   if ( type(p)<=mp_pair_type ) { 
20383      q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p); p=q;
20384   }; /* now |cur_type=mp_pair_type| or |cur_type=mp_color_type| */
20385   r=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20386   while (1) { 
20387     r=r-2;
20388     v=value(r);
20389     type(r)=type(p);
20390     if ( r==value(mp->cur_exp) ) 
20391       break;
20392     mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(p)));
20393     mp_dep_mult(mp, r,v,true);
20394   }
20395   mp->mem[value_loc(r)]=mp->mem[value_loc(p)];
20396   link(prev_dep(p))=r;
20397   mp_free_node(mp, p,value_node_size);
20398   mp_dep_mult(mp, r,v,true);
20399 }
20400
20401 @ @<Additional cases of binary operators@>=
20402 case over: 
20403   if ( (mp->cur_type!=mp_known)||(type(p)<mp_color_type) ) {
20404     mp_bad_binary(mp, p,over);
20405   } else { 
20406     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20407     if ( v==0 ) {
20408       @<Squeal about division by zero@>;
20409     } else { 
20410       if ( mp->cur_type==mp_known ) {
20411         mp->cur_exp=mp_make_scaled(mp, mp->cur_exp,v);
20412       } else if ( mp->cur_type<=mp_pair_type ) { 
20413         p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20414         do {  
20415           p=p-2;  mp_dep_div(mp, p,v);
20416         } while (p!=value(mp->cur_exp));
20417       } else {
20418         mp_dep_div(mp, null,v);
20419       }
20420     }
20421     return;
20422   }
20423   break;
20424
20425 @ @<Declare binary action...@>=
20426 void mp_dep_div (MP mp,pointer p, scaled v) {
20427   pointer q; /* the dependency list being divided by |v| */
20428   small_number s,t; /* its type, before and after */
20429   if ( p==null ) q=mp->cur_exp;
20430   else if ( type(p)!=mp_known ) q=p;
20431   else { value(p)=mp_make_scaled(mp, value(p),v); return; };
20432   t=type(q); q=dep_list(q); s=t;
20433   if ( t==mp_dependent )
20434     if ( mp_ab_vs_cd(mp, mp_max_coef(mp,q),unity,coef_bound-1,abs(v))>=0 ) 
20435       t=mp_proto_dependent;
20436   q=mp_p_over_v(mp, q,v,s,t); 
20437   mp_dep_finish(mp, q,p,t);
20438 }
20439
20440 @ @<Squeal about division by zero@>=
20441
20442   exp_err("Division by zero");
20443 @.Division by zero@>
20444   help2("You're trying to divide the quantity shown above the error")
20445     ("message by zero. I'm going to divide it by one instead.");
20446   mp_put_get_error(mp);
20447 }
20448
20449 @ @<Additional cases of binary operators@>=
20450 case pythag_add:
20451 case pythag_sub: 
20452    if ( (mp->cur_type==mp_known)&&(type(p)==mp_known) ) {
20453      if ( c==pythag_add ) mp->cur_exp=mp_pyth_add(mp, value(p),mp->cur_exp);
20454      else mp->cur_exp=mp_pyth_sub(mp, value(p),mp->cur_exp);
20455    } else mp_bad_binary(mp, p,c);
20456    break;
20457
20458 @ The next few sections of the program deal with affine transformations
20459 of coordinate data.
20460
20461 @<Additional cases of binary operators@>=
20462 case rotated_by: case slanted_by:
20463 case scaled_by: case shifted_by: case transformed_by:
20464 case x_scaled: case y_scaled: case z_scaled:
20465   if ( type(p)==mp_path_type ) { 
20466     path_trans(c,p); return;
20467   } else if ( type(p)==mp_pen_type ) { 
20468     pen_trans(c,p);
20469     mp->cur_exp=mp_convex_hull(mp, mp->cur_exp); 
20470       /* rounding error could destroy convexity */
20471     return;
20472   } else if ( (type(p)==mp_pair_type)||(type(p)==mp_transform_type) ) {
20473     mp_big_trans(mp, p,c);
20474   } else if ( type(p)==mp_picture_type ) {
20475     mp_do_edges_trans(mp, p,c); return;
20476   } else {
20477     mp_bad_binary(mp, p,c);
20478   }
20479   break;
20480
20481 @ Let |c| be one of the eight transform operators. The procedure call
20482 |set_up_trans(c)| first changes |cur_exp| to a transform that corresponds to
20483 |c| and the original value of |cur_exp|. (In particular, |cur_exp| doesn't
20484 change at all if |c=transformed_by|.)
20485
20486 Then, if all components of the resulting transform are |known|, they are
20487 moved to the global variables |txx|, |txy|, |tyx|, |tyy|, |tx|, |ty|;
20488 and |cur_exp| is changed to the known value zero.
20489
20490 @<Declare binary action...@>=
20491 void mp_set_up_trans (MP mp,quarterword c) {
20492   pointer p,q,r; /* list manipulation registers */
20493   if ( (c!=transformed_by)||(mp->cur_type!=mp_transform_type) ) {
20494     @<Put the current transform into |cur_exp|@>;
20495   }
20496   @<If the current transform is entirely known, stash it in global variables;
20497     otherwise |return|@>;
20498 }
20499
20500 @ @<Glob...@>=
20501 scaled txx;
20502 scaled txy;
20503 scaled tyx;
20504 scaled tyy;
20505 scaled tx;
20506 scaled ty; /* current transform coefficients */
20507
20508 @ @<Put the current transform...@>=
20509
20510   p=mp_stash_cur_exp(mp); 
20511   mp->cur_exp=mp_id_transform(mp); 
20512   mp->cur_type=mp_transform_type;
20513   q=value(mp->cur_exp);
20514   switch (c) {
20515   @<For each of the eight cases, change the relevant fields of |cur_exp|
20516     and |goto done|;
20517     but do nothing if capsule |p| doesn't have the appropriate type@>;
20518   }; /* there are no other cases */
20519   mp_disp_err(mp, p,"Improper transformation argument");
20520 @.Improper transformation argument@>
20521   help3("The expression shown above has the wrong type,")
20522        ("so I can\'t transform anything using it.")
20523        ("Proceed, and I'll omit the transformation.");
20524   mp_put_get_error(mp);
20525 DONE: 
20526   mp_recycle_value(mp, p); 
20527   mp_free_node(mp, p,value_node_size);
20528 }
20529
20530 @ @<If the current transform is entirely known, ...@>=
20531 q=value(mp->cur_exp); r=q+transform_node_size;
20532 do {  
20533   r=r-2;
20534   if ( type(r)!=mp_known ) return;
20535 } while (r!=q);
20536 mp->txx=value(xx_part_loc(q));
20537 mp->txy=value(xy_part_loc(q));
20538 mp->tyx=value(yx_part_loc(q));
20539 mp->tyy=value(yy_part_loc(q));
20540 mp->tx=value(x_part_loc(q));
20541 mp->ty=value(y_part_loc(q));
20542 mp_flush_cur_exp(mp, 0)
20543
20544 @ @<For each of the eight cases...@>=
20545 case rotated_by:
20546   if ( type(p)==mp_known )
20547     @<Install sines and cosines, then |goto done|@>;
20548   break;
20549 case slanted_by:
20550   if ( type(p)>mp_pair_type ) { 
20551    mp_install(mp, xy_part_loc(q),p); goto DONE;
20552   };
20553   break;
20554 case scaled_by:
20555   if ( type(p)>mp_pair_type ) { 
20556     mp_install(mp, xx_part_loc(q),p); mp_install(mp, yy_part_loc(q),p); 
20557     goto DONE;
20558   };
20559   break;
20560 case shifted_by:
20561   if ( type(p)==mp_pair_type ) {
20562     r=value(p); mp_install(mp, x_part_loc(q),x_part_loc(r));
20563     mp_install(mp, y_part_loc(q),y_part_loc(r)); goto DONE;
20564   };
20565   break;
20566 case x_scaled:
20567   if ( type(p)>mp_pair_type ) {
20568     mp_install(mp, xx_part_loc(q),p); goto DONE;
20569   };
20570   break;
20571 case y_scaled:
20572   if ( type(p)>mp_pair_type ) {
20573     mp_install(mp, yy_part_loc(q),p); goto DONE;
20574   };
20575   break;
20576 case z_scaled:
20577   if ( type(p)==mp_pair_type )
20578     @<Install a complex multiplier, then |goto done|@>;
20579   break;
20580 case transformed_by:
20581   break;
20582   
20583
20584 @ @<Install sines and cosines, then |goto done|@>=
20585 { mp_n_sin_cos(mp, (value(p) % three_sixty_units)*16);
20586   value(xx_part_loc(q))=mp_round_fraction(mp, mp->n_cos);
20587   value(yx_part_loc(q))=mp_round_fraction(mp, mp->n_sin);
20588   value(xy_part_loc(q))=-value(yx_part_loc(q));
20589   value(yy_part_loc(q))=value(xx_part_loc(q));
20590   goto DONE;
20591 }
20592
20593 @ @<Install a complex multiplier, then |goto done|@>=
20594
20595   r=value(p);
20596   mp_install(mp, xx_part_loc(q),x_part_loc(r));
20597   mp_install(mp, yy_part_loc(q),x_part_loc(r));
20598   mp_install(mp, yx_part_loc(q),y_part_loc(r));
20599   if ( type(y_part_loc(r))==mp_known ) negate(value(y_part_loc(r)));
20600   else mp_negate_dep_list(mp, dep_list(y_part_loc(r)));
20601   mp_install(mp, xy_part_loc(q),y_part_loc(r));
20602   goto DONE;
20603 }
20604
20605 @ Procedure |set_up_known_trans| is like |set_up_trans|, but it
20606 insists that the transformation be entirely known.
20607
20608 @<Declare binary action...@>=
20609 void mp_set_up_known_trans (MP mp,quarterword c) { 
20610   mp_set_up_trans(mp, c);
20611   if ( mp->cur_type!=mp_known ) {
20612     exp_err("Transform components aren't all known");
20613 @.Transform components...@>
20614     help3("I'm unable to apply a partially specified transformation")
20615       ("except to a fully known pair or transform.")
20616       ("Proceed, and I'll omit the transformation.");
20617     mp_put_get_flush_error(mp, 0);
20618     mp->txx=unity; mp->txy=0; mp->tyx=0; mp->tyy=unity; 
20619     mp->tx=0; mp->ty=0;
20620   }
20621 }
20622
20623 @ Here's a procedure that applies the transform |txx..ty| to a pair of
20624 coordinates in locations |p| and~|q|.
20625
20626 @<Declare binary action...@>= 
20627 void mp_trans (MP mp,pointer p, pointer q) {
20628   scaled v; /* the new |x| value */
20629   v=mp_take_scaled(mp, mp->mem[p].sc,mp->txx)+
20630   mp_take_scaled(mp, mp->mem[q].sc,mp->txy)+mp->tx;
20631   mp->mem[q].sc=mp_take_scaled(mp, mp->mem[p].sc,mp->tyx)+
20632   mp_take_scaled(mp, mp->mem[q].sc,mp->tyy)+mp->ty;
20633   mp->mem[p].sc=v;
20634 }
20635
20636 @ The simplest transformation procedure applies a transform to all
20637 coordinates of a path.  The |path_trans(c)(p)| macro applies
20638 a transformation defined by |cur_exp| and the transform operator |c|
20639 to the path~|p|.
20640
20641 @d path_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20642                      mp_unstash_cur_exp(mp, (B)); 
20643                      mp_do_path_trans(mp, mp->cur_exp); }
20644
20645 @<Declare binary action...@>=
20646 void mp_do_path_trans (MP mp,pointer p) {
20647   pointer q; /* list traverser */
20648   q=p;
20649   do { 
20650     if ( left_type(q)!=mp_endpoint ) 
20651       mp_trans(mp, q+3,q+4); /* that's |left_x| and |left_y| */
20652     mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20653     if ( right_type(q)!=mp_endpoint ) 
20654       mp_trans(mp, q+5,q+6); /* that's |right_x| and |right_y| */
20655 @^data structure assumptions@>
20656     q=link(q);
20657   } while (q!=p);
20658 }
20659
20660 @ Transforming a pen is very similar, except that there are no |left_type|
20661 and |right_type| fields.
20662
20663 @d pen_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20664                     mp_unstash_cur_exp(mp, (B)); 
20665                     mp_do_pen_trans(mp, mp->cur_exp); }
20666
20667 @<Declare binary action...@>=
20668 void mp_do_pen_trans (MP mp,pointer p) {
20669   pointer q; /* list traverser */
20670   if ( pen_is_elliptical(p) ) {
20671     mp_trans(mp, p+3,p+4); /* that's |left_x| and |left_y| */
20672     mp_trans(mp, p+5,p+6); /* that's |right_x| and |right_y| */
20673   };
20674   q=p;
20675   do { 
20676     mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20677 @^data structure assumptions@>
20678     q=link(q);
20679   } while (q!=p);
20680 }
20681
20682 @ The next transformation procedure applies to edge structures. It will do
20683 any transformation, but the results may be substandard if the picture contains
20684 text that uses downloaded bitmap fonts.  The binary action procedure is
20685 |do_edges_trans|, but we also need a function that just scales a picture.
20686 That routine is |scale_edges|.  Both it and the underlying routine |edges_trans|
20687 should be thought of as procedures that update an edge structure |h|, except
20688 that they have to return a (possibly new) structure because of the need to call
20689 |private_edges|.
20690
20691 @<Declare binary action...@>=
20692 pointer mp_edges_trans (MP mp, pointer h) {
20693   pointer q; /* the object being transformed */
20694   pointer r,s; /* for list manipulation */
20695   scaled sx,sy; /* saved transformation parameters */
20696   scaled sqdet; /* square root of determinant for |dash_scale| */
20697   integer sgndet; /* sign of the determinant */
20698   scaled v; /* a temporary value */
20699   h=mp_private_edges(mp, h);
20700   sqdet=mp_sqrt_det(mp, mp->txx,mp->txy,mp->tyx,mp->tyy);
20701   sgndet=mp_ab_vs_cd(mp, mp->txx,mp->tyy,mp->txy,mp->tyx);
20702   if ( dash_list(h)!=null_dash ) {
20703     @<Try to transform the dash list of |h|@>;
20704   }
20705   @<Make the bounding box of |h| unknown if it can't be updated properly
20706     without scanning the whole structure@>;  
20707   q=link(dummy_loc(h));
20708   while ( q!=null ) { 
20709     @<Transform graphical object |q|@>;
20710     q=link(q);
20711   }
20712   return h;
20713 }
20714 void mp_do_edges_trans (MP mp,pointer p, quarterword c) { 
20715   mp_set_up_known_trans(mp, c);
20716   value(p)=mp_edges_trans(mp, value(p));
20717   mp_unstash_cur_exp(mp, p);
20718 }
20719 void mp_scale_edges (MP mp) { 
20720   mp->txx=mp->se_sf; mp->tyy=mp->se_sf;
20721   mp->txy=0; mp->tyx=0; mp->tx=0; mp->ty=0;
20722   mp->se_pic=mp_edges_trans(mp, mp->se_pic);
20723 }
20724
20725 @ @<Try to transform the dash list of |h|@>=
20726 if ( (mp->txy!=0)||(mp->tyx!=0)||
20727      (mp->ty!=0)||(abs(mp->txx)!=abs(mp->tyy))) {
20728   mp_flush_dash_list(mp, h);
20729 } else { 
20730   if ( mp->txx<0 ) { @<Reverse the dash list of |h|@>; } 
20731   @<Scale the dash list by |txx| and shift it by |tx|@>;
20732   dash_y(h)=mp_take_scaled(mp, dash_y(h),abs(mp->tyy));
20733 }
20734
20735 @ @<Reverse the dash list of |h|@>=
20736
20737   r=dash_list(h);
20738   dash_list(h)=null_dash;
20739   while ( r!=null_dash ) {
20740     s=r; r=link(r);
20741     v=start_x(s); start_x(s)=stop_x(s); stop_x(s)=v;
20742     link(s)=dash_list(h);
20743     dash_list(h)=s;
20744   }
20745 }
20746
20747 @ @<Scale the dash list by |txx| and shift it by |tx|@>=
20748 r=dash_list(h);
20749 while ( r!=null_dash ) {
20750   start_x(r)=mp_take_scaled(mp, start_x(r),mp->txx)+mp->tx;
20751   stop_x(r)=mp_take_scaled(mp, stop_x(r),mp->txx)+mp->tx;
20752   r=link(r);
20753 }
20754
20755 @ @<Make the bounding box of |h| unknown if it can't be updated properly...@>=
20756 if ( (mp->txx==0)&&(mp->tyy==0) ) {
20757   @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>;
20758 } else if ( (mp->txy!=0)||(mp->tyx!=0) ) {
20759   mp_init_bbox(mp, h);
20760   goto DONE1;
20761 }
20762 if ( minx_val(h)<=maxx_val(h) ) {
20763   @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift by
20764    |(tx,ty)|@>;
20765 }
20766 DONE1:
20767
20768
20769
20770 @ @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>=
20771
20772   v=minx_val(h); minx_val(h)=miny_val(h); miny_val(h)=v;
20773   v=maxx_val(h); maxx_val(h)=maxy_val(h); maxy_val(h)=v;
20774 }
20775
20776 @ The sum ``|txx+txy|'' is whichever of |txx| or |txy| is nonzero.  The other
20777 sum is similar.
20778
20779 @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift...@>=
20780
20781   minx_val(h)=mp_take_scaled(mp, minx_val(h),mp->txx+mp->txy)+mp->tx;
20782   maxx_val(h)=mp_take_scaled(mp, maxx_val(h),mp->txx+mp->txy)+mp->tx;
20783   miny_val(h)=mp_take_scaled(mp, miny_val(h),mp->tyx+mp->tyy)+mp->ty;
20784   maxy_val(h)=mp_take_scaled(mp, maxy_val(h),mp->tyx+mp->tyy)+mp->ty;
20785   if ( mp->txx+mp->txy<0 ) {
20786     v=minx_val(h); minx_val(h)=maxx_val(h); maxx_val(h)=v;
20787   }
20788   if ( mp->tyx+mp->tyy<0 ) {
20789     v=miny_val(h); miny_val(h)=maxy_val(h); maxy_val(h)=v;
20790   }
20791 }
20792
20793 @ Now we ready for the main task of transforming the graphical objects in edge
20794 structure~|h|.
20795
20796 @<Transform graphical object |q|@>=
20797 switch (type(q)) {
20798 case mp_fill_code: case mp_stroked_code: 
20799   mp_do_path_trans(mp, path_p(q));
20800   @<Transform |pen_p(q)|, making sure polygonal pens stay counter-clockwise@>;
20801   break;
20802 case mp_start_clip_code: case mp_start_bounds_code: 
20803   mp_do_path_trans(mp, path_p(q));
20804   break;
20805 case mp_text_code: 
20806   r=text_tx_loc(q);
20807   @<Transform the compact transformation starting at |r|@>;
20808   break;
20809 case mp_stop_clip_code: case mp_stop_bounds_code: 
20810   break;
20811 } /* there are no other cases */
20812
20813 @ Note that the shift parameters |(tx,ty)| apply only to the path being stroked.
20814 The |dash_scale| has to be adjusted  to scale the dash lengths in |dash_p(q)|
20815 since the \ps\ output procedures will try to compensate for the transformation
20816 we are applying to |pen_p(q)|.  Since this compensation is based on the square
20817 root of the determinant, |sqdet| is the appropriate factor.
20818
20819 @<Transform |pen_p(q)|, making sure...@>=
20820 if ( pen_p(q)!=null ) {
20821   sx=mp->tx; sy=mp->ty;
20822   mp->tx=0; mp->ty=0;
20823   mp_do_pen_trans(mp, pen_p(q));
20824   if ( ((type(q)==mp_stroked_code)&&(dash_p(q)!=null)) )
20825     dash_scale(q)=mp_take_scaled(mp, dash_scale(q),sqdet);
20826   if ( ! pen_is_elliptical(pen_p(q)) )
20827     if ( sgndet<0 )
20828       pen_p(q)=mp_make_pen(mp, mp_copy_path(mp, pen_p(q)),true); 
20829          /* this unreverses the pen */
20830   mp->tx=sx; mp->ty=sy;
20831 }
20832
20833 @ This uses the fact that transformations are stored in the order
20834 |(tx,ty,txx,txy,tyx,tyy)|.
20835 @^data structure assumptions@>
20836
20837 @<Transform the compact transformation starting at |r|@>=
20838 mp_trans(mp, r,r+1);
20839 sx=mp->tx; sy=mp->ty;
20840 mp->tx=0; mp->ty=0;
20841 mp_trans(mp, r+2,r+4);
20842 mp_trans(mp, r+3,r+5);
20843 mp->tx=sx; mp->ty=sy
20844
20845 @ The hard cases of transformation occur when big nodes are involved,
20846 and when some of their components are unknown.
20847
20848 @<Declare binary action...@>=
20849 @<Declare subroutines needed by |big_trans|@>;
20850 void mp_big_trans (MP mp,pointer p, quarterword c) {
20851   pointer q,r,pp,qq; /* list manipulation registers */
20852   small_number s; /* size of a big node */
20853   s=mp->big_node_size[type(p)]; q=value(p); r=q+s;
20854   do {  
20855     r=r-2;
20856     if ( type(r)!=mp_known ) {
20857       @<Transform an unknown big node and |return|@>;
20858     }
20859   } while (r!=q);
20860   @<Transform a known big node@>;
20861 }; /* node |p| will now be recycled by |do_binary| */
20862
20863 @ @<Transform an unknown big node and |return|@>=
20864
20865   mp_set_up_known_trans(mp, c); mp_make_exp_copy(mp, p); 
20866   r=value(mp->cur_exp);
20867   if ( mp->cur_type==mp_transform_type ) {
20868     mp_bilin1(mp, yy_part_loc(r),mp->tyy,xy_part_loc(q),mp->tyx,0);
20869     mp_bilin1(mp, yx_part_loc(r),mp->tyy,xx_part_loc(q),mp->tyx,0);
20870     mp_bilin1(mp, xy_part_loc(r),mp->txx,yy_part_loc(q),mp->txy,0);
20871     mp_bilin1(mp, xx_part_loc(r),mp->txx,yx_part_loc(q),mp->txy,0);
20872   }
20873   mp_bilin1(mp, y_part_loc(r),mp->tyy,x_part_loc(q),mp->tyx,mp->ty);
20874   mp_bilin1(mp, x_part_loc(r),mp->txx,y_part_loc(q),mp->txy,mp->tx);
20875   return;
20876 }
20877
20878 @ Let |p| point to a two-word value field inside a big node of |cur_exp|,
20879 and let |q| point to a another value field. The |bilin1| procedure
20880 replaces |p| by $p\cdot t+q\cdot u+\delta$.
20881
20882 @<Declare subroutines needed by |big_trans|@>=
20883 void mp_bilin1 (MP mp, pointer p, scaled t, pointer q, 
20884                 scaled u, scaled delta) {
20885   pointer r; /* list traverser */
20886   if ( t!=unity ) mp_dep_mult(mp, p,t,true);
20887   if ( u!=0 ) {
20888     if ( type(q)==mp_known ) {
20889       delta+=mp_take_scaled(mp, value(q),u);
20890     } else { 
20891       @<Ensure that |type(p)=mp_proto_dependent|@>;
20892       dep_list(p)=mp_p_plus_fq(mp, dep_list(p),u,dep_list(q),
20893                                mp_proto_dependent,type(q));
20894     }
20895   }
20896   if ( type(p)==mp_known ) {
20897     value(p)+=delta;
20898   } else {
20899     r=dep_list(p);
20900     while ( info(r)!=null ) r=link(r);
20901     delta+=value(r);
20902     if ( r!=dep_list(p) ) value(r)=delta;
20903     else { mp_recycle_value(mp, p); type(p)=mp_known; value(p)=delta; };
20904   }
20905   if ( mp->fix_needed ) mp_fix_dependencies(mp);
20906 }
20907
20908 @ @<Ensure that |type(p)=mp_proto_dependent|@>=
20909 if ( type(p)!=mp_proto_dependent ) {
20910   if ( type(p)==mp_known ) 
20911     mp_new_dep(mp, p,mp_const_dependency(mp, value(p)));
20912   else 
20913     dep_list(p)=mp_p_times_v(mp, dep_list(p),unity,mp_dependent,
20914                              mp_proto_dependent,true);
20915   type(p)=mp_proto_dependent;
20916 }
20917
20918 @ @<Transform a known big node@>=
20919 mp_set_up_trans(mp, c);
20920 if ( mp->cur_type==mp_known ) {
20921   @<Transform known by known@>;
20922 } else { 
20923   pp=mp_stash_cur_exp(mp); qq=value(pp);
20924   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20925   if ( mp->cur_type==mp_transform_type ) {
20926     mp_bilin2(mp, yy_part_loc(r),yy_part_loc(qq),
20927       value(xy_part_loc(q)),yx_part_loc(qq),null);
20928     mp_bilin2(mp, yx_part_loc(r),yy_part_loc(qq),
20929       value(xx_part_loc(q)),yx_part_loc(qq),null);
20930     mp_bilin2(mp, xy_part_loc(r),xx_part_loc(qq),
20931       value(yy_part_loc(q)),xy_part_loc(qq),null);
20932     mp_bilin2(mp, xx_part_loc(r),xx_part_loc(qq),
20933       value(yx_part_loc(q)),xy_part_loc(qq),null);
20934   };
20935   mp_bilin2(mp, y_part_loc(r),yy_part_loc(qq),
20936     value(x_part_loc(q)),yx_part_loc(qq),y_part_loc(qq));
20937   mp_bilin2(mp, x_part_loc(r),xx_part_loc(qq),
20938     value(y_part_loc(q)),xy_part_loc(qq),x_part_loc(qq));
20939   mp_recycle_value(mp, pp); mp_free_node(mp, pp,value_node_size);
20940 }
20941
20942 @ Let |p| be a |mp_proto_dependent| value whose dependency list ends
20943 at |dep_final|. The following procedure adds |v| times another
20944 numeric quantity to~|p|.
20945
20946 @<Declare subroutines needed by |big_trans|@>=
20947 void mp_add_mult_dep (MP mp,pointer p, scaled v, pointer r) { 
20948   if ( type(r)==mp_known ) {
20949     value(mp->dep_final)+=mp_take_scaled(mp, value(r),v);
20950   } else  { 
20951     dep_list(p)=mp_p_plus_fq(mp, dep_list(p),v,dep_list(r),
20952                                                          mp_proto_dependent,type(r));
20953     if ( mp->fix_needed ) mp_fix_dependencies(mp);
20954   }
20955 }
20956
20957 @ The |bilin2| procedure is something like |bilin1|, but with known
20958 and unknown quantities reversed. Parameter |p| points to a value field
20959 within the big node for |cur_exp|; and |type(p)=mp_known|. Parameters
20960 |t| and~|u| point to value fields elsewhere; so does parameter~|q|,
20961 unless it is |null| (which stands for zero). Location~|p| will be
20962 replaced by $p\cdot t+v\cdot u+q$.
20963
20964 @<Declare subroutines needed by |big_trans|@>=
20965 void mp_bilin2 (MP mp,pointer p, pointer t, scaled v, 
20966                 pointer u, pointer q) {
20967   scaled vv; /* temporary storage for |value(p)| */
20968   vv=value(p); type(p)=mp_proto_dependent;
20969   mp_new_dep(mp, p,mp_const_dependency(mp, 0)); /* this sets |dep_final| */
20970   if ( vv!=0 ) 
20971     mp_add_mult_dep(mp, p,vv,t); /* |dep_final| doesn't change */
20972   if ( v!=0 ) mp_add_mult_dep(mp, p,v,u);
20973   if ( q!=null ) mp_add_mult_dep(mp, p,unity,q);
20974   if ( dep_list(p)==mp->dep_final ) {
20975     vv=value(mp->dep_final); mp_recycle_value(mp, p);
20976     type(p)=mp_known; value(p)=vv;
20977   }
20978 }
20979
20980 @ @<Transform known by known@>=
20981
20982   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20983   if ( mp->cur_type==mp_transform_type ) {
20984     mp_bilin3(mp, yy_part_loc(r),mp->tyy,value(xy_part_loc(q)),mp->tyx,0);
20985     mp_bilin3(mp, yx_part_loc(r),mp->tyy,value(xx_part_loc(q)),mp->tyx,0);
20986     mp_bilin3(mp, xy_part_loc(r),mp->txx,value(yy_part_loc(q)),mp->txy,0);
20987     mp_bilin3(mp, xx_part_loc(r),mp->txx,value(yx_part_loc(q)),mp->txy,0);
20988   }
20989   mp_bilin3(mp, y_part_loc(r),mp->tyy,value(x_part_loc(q)),mp->tyx,mp->ty);
20990   mp_bilin3(mp, x_part_loc(r),mp->txx,value(y_part_loc(q)),mp->txy,mp->tx);
20991 }
20992
20993 @ Finally, in |bilin3| everything is |known|.
20994
20995 @<Declare subroutines needed by |big_trans|@>=
20996 void mp_bilin3 (MP mp,pointer p, scaled t, 
20997                scaled v, scaled u, scaled delta) { 
20998   if ( t!=unity )
20999     delta+=mp_take_scaled(mp, value(p),t);
21000   else 
21001     delta+=value(p);
21002   if ( u!=0 ) value(p)=delta+mp_take_scaled(mp, v,u);
21003   else value(p)=delta;
21004 }
21005
21006 @ @<Additional cases of binary operators@>=
21007 case concatenate: 
21008   if ( (mp->cur_type==mp_string_type)&&(type(p)==mp_string_type) ) mp_cat(mp, p);
21009   else mp_bad_binary(mp, p,concatenate);
21010   break;
21011 case substring_of: 
21012   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_string_type) )
21013     mp_chop_string(mp, value(p));
21014   else mp_bad_binary(mp, p,substring_of);
21015   break;
21016 case subpath_of: 
21017   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21018   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_path_type) )
21019     mp_chop_path(mp, value(p));
21020   else mp_bad_binary(mp, p,subpath_of);
21021   break;
21022
21023 @ @<Declare binary action...@>=
21024 void mp_cat (MP mp,pointer p) {
21025   str_number a,b; /* the strings being concatenated */
21026   pool_pointer k; /* index into |str_pool| */
21027   a=value(p); b=mp->cur_exp; str_room(length(a)+length(b));
21028   for (k=mp->str_start[a];k<=str_stop(a)-1;k++) {
21029     append_char(mp->str_pool[k]);
21030   }
21031   for (k=mp->str_start[b];k<=str_stop(b)-1;k++) {
21032     append_char(mp->str_pool[k]);
21033   }
21034   mp->cur_exp=mp_make_string(mp); delete_str_ref(b);
21035 }
21036
21037 @ @<Declare binary action...@>=
21038 void mp_chop_string (MP mp,pointer p) {
21039   integer a, b; /* start and stop points */
21040   integer l; /* length of the original string */
21041   integer k; /* runs from |a| to |b| */
21042   str_number s; /* the original string */
21043   boolean reversed; /* was |a>b|? */
21044   a=mp_round_unscaled(mp, value(x_part_loc(p)));
21045   b=mp_round_unscaled(mp, value(y_part_loc(p)));
21046   if ( a<=b ) reversed=false;
21047   else  { reversed=true; k=a; a=b; b=k; };
21048   s=mp->cur_exp; l=length(s);
21049   if ( a<0 ) { 
21050     a=0;
21051     if ( b<0 ) b=0;
21052   }
21053   if ( b>l ) { 
21054     b=l;
21055     if ( a>l ) a=l;
21056   }
21057   str_room(b-a);
21058   if ( reversed ) {
21059     for (k=mp->str_start[s]+b-1;k>=mp->str_start[s]+a;k--)  {
21060       append_char(mp->str_pool[k]);
21061     }
21062   } else  {
21063     for (k=mp->str_start[s]+a;k<=mp->str_start[s]+b-1;k++)  {
21064       append_char(mp->str_pool[k]);
21065     }
21066   }
21067   mp->cur_exp=mp_make_string(mp); delete_str_ref(s);
21068 }
21069
21070 @ @<Declare binary action...@>=
21071 void mp_chop_path (MP mp,pointer p) {
21072   pointer q; /* a knot in the original path */
21073   pointer pp,qq,rr,ss; /* link variables for copies of path nodes */
21074   scaled a,b,k,l; /* indices for chopping */
21075   boolean reversed; /* was |a>b|? */
21076   l=mp_path_length(mp); a=value(x_part_loc(p)); b=value(y_part_loc(p));
21077   if ( a<=b ) reversed=false;
21078   else  { reversed=true; k=a; a=b; b=k; };
21079   @<Dispense with the cases |a<0| and/or |b>l|@>;
21080   q=mp->cur_exp;
21081   while ( a>=unity ) {
21082     q=link(q); a=a-unity; b=b-unity;
21083   }
21084   if ( b==a ) {
21085     @<Construct a path from |pp| to |qq| of length zero@>; 
21086   } else { 
21087     @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>; 
21088   }
21089   left_type(pp)=mp_endpoint; right_type(qq)=mp_endpoint; link(qq)=pp;
21090   mp_toss_knot_list(mp, mp->cur_exp);
21091   if ( reversed ) {
21092     mp->cur_exp=link(mp_htap_ypoc(mp, pp)); mp_toss_knot_list(mp, pp);
21093   } else {
21094     mp->cur_exp=pp;
21095   }
21096 }
21097
21098 @ @<Dispense with the cases |a<0| and/or |b>l|@>=
21099 if ( a<0 ) {
21100   if ( left_type(mp->cur_exp)==mp_endpoint ) {
21101     a=0; if ( b<0 ) b=0;
21102   } else  {
21103     do {  a=a+l; b=b+l; } while (a<0); /* a cycle always has length |l>0| */
21104   }
21105 }
21106 if ( b>l ) {
21107   if ( left_type(mp->cur_exp)==mp_endpoint ) {
21108     b=l; if ( a>l ) a=l;
21109   } else {
21110     while ( a>=l ) { 
21111       a=a-l; b=b-l;
21112     }
21113   }
21114 }
21115
21116 @ @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>=
21117
21118   pp=mp_copy_knot(mp, q); qq=pp;
21119   do {  
21120     q=link(q); rr=qq; qq=mp_copy_knot(mp, q); link(rr)=qq; b=b-unity;
21121   } while (b>0);
21122   if ( a>0 ) {
21123     ss=pp; pp=link(pp);
21124     mp_split_cubic(mp, ss,a*010000); pp=link(ss);
21125     mp_free_node(mp, ss,knot_node_size);
21126     if ( rr==ss ) {
21127       b=mp_make_scaled(mp, b,unity-a); rr=pp;
21128     }
21129   }
21130   if ( b<0 ) {
21131     mp_split_cubic(mp, rr,(b+unity)*010000);
21132     mp_free_node(mp, qq,knot_node_size);
21133     qq=link(rr);
21134   }
21135 }
21136
21137 @ @<Construct a path from |pp| to |qq| of length zero@>=
21138
21139   if ( a>0 ) { mp_split_cubic(mp, q,a*010000); q=link(q); };
21140   pp=mp_copy_knot(mp, q); qq=pp;
21141 }
21142
21143 @ @<Additional cases of binary operators@>=
21144 case point_of: case precontrol_of: case postcontrol_of: 
21145   if ( mp->cur_type==mp_pair_type )
21146      mp_pair_to_path(mp);
21147   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
21148     mp_find_point(mp, value(p),c);
21149   else 
21150     mp_bad_binary(mp, p,c);
21151   break;
21152 case pen_offset_of: 
21153   if ( (mp->cur_type==mp_pen_type)&& mp_nice_pair(mp, p,type(p)) )
21154     mp_set_up_offset(mp, value(p));
21155   else 
21156     mp_bad_binary(mp, p,pen_offset_of);
21157   break;
21158 case direction_time_of: 
21159   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21160   if ( (mp->cur_type==mp_path_type)&& mp_nice_pair(mp, p,type(p)) )
21161     mp_set_up_direction_time(mp, value(p));
21162   else 
21163     mp_bad_binary(mp, p,direction_time_of);
21164   break;
21165 case envelope_of:
21166   if ( (type(p) != mp_pen_type) || (mp->cur_type != mp_path_type) )
21167     mp_bad_binary(mp, p,envelope_of);
21168   else
21169     mp_set_up_envelope(mp, p);
21170   break;
21171
21172 @ @<Declare binary action...@>=
21173 void mp_set_up_offset (MP mp,pointer p) { 
21174   mp_find_offset(mp, value(x_part_loc(p)),value(y_part_loc(p)),mp->cur_exp);
21175   mp_pair_value(mp, mp->cur_x,mp->cur_y);
21176 }
21177 void mp_set_up_direction_time (MP mp,pointer p) { 
21178   mp_flush_cur_exp(mp, mp_find_direction_time(mp, value(x_part_loc(p)),
21179   value(y_part_loc(p)),mp->cur_exp));
21180 }
21181 void mp_set_up_envelope (MP mp,pointer p) {
21182   pointer q = mp_copy_path(mp, mp->cur_exp); /* the original path */
21183   /* TODO: accept elliptical pens for straight paths */
21184   if (pen_is_elliptical(value(p))) {
21185     mp_bad_envelope_pen(mp);
21186     mp->cur_exp = q;
21187     mp->cur_type = mp_path_type;
21188     return;
21189   }
21190   small_number ljoin, lcap;
21191   scaled miterlim;
21192   if ( mp->internal[mp_linejoin]>unity ) ljoin=2;
21193   else if ( mp->internal[mp_linejoin]>0 ) ljoin=1;
21194   else ljoin=0;
21195   if ( mp->internal[mp_linecap]>unity ) lcap=2;
21196   else if ( mp->internal[mp_linecap]>0 ) lcap=1;
21197   else lcap=0;
21198   if ( mp->internal[mp_miterlimit]<unity )
21199     miterlim=unity;
21200   else
21201     miterlim=mp->internal[mp_miterlimit];
21202   mp->cur_exp = mp_make_envelope(mp, q, value(p), ljoin,lcap,miterlim);
21203   mp->cur_type = mp_path_type;
21204 }
21205
21206 @ @<Declare binary action...@>=
21207 void mp_find_point (MP mp,scaled v, quarterword c) {
21208   pointer p; /* the path */
21209   scaled n; /* its length */
21210   p=mp->cur_exp;
21211   if ( left_type(p)==mp_endpoint ) n=-unity; else n=0;
21212   do {  p=link(p); n=n+unity; } while (p!=mp->cur_exp);
21213   if ( n==0 ) { 
21214     v=0; 
21215   } else if ( v<0 ) {
21216     if ( left_type(p)==mp_endpoint ) v=0;
21217     else v=n-1-((-v-1) % n);
21218   } else if ( v>n ) {
21219     if ( left_type(p)==mp_endpoint ) v=n;
21220     else v=v % n;
21221   }
21222   p=mp->cur_exp;
21223   while ( v>=unity ) { p=link(p); v=v-unity;  };
21224   if ( v!=0 ) {
21225      @<Insert a fractional node by splitting the cubic@>;
21226   }
21227   @<Set the current expression to the desired path coordinates@>;
21228 }
21229
21230 @ @<Insert a fractional node...@>=
21231 { mp_split_cubic(mp, p,v*010000); p=link(p); }
21232
21233 @ @<Set the current expression to the desired path coordinates...@>=
21234 switch (c) {
21235 case point_of: 
21236   mp_pair_value(mp, x_coord(p),y_coord(p));
21237   break;
21238 case precontrol_of: 
21239   if ( left_type(p)==mp_endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
21240   else mp_pair_value(mp, left_x(p),left_y(p));
21241   break;
21242 case postcontrol_of: 
21243   if ( right_type(p)==mp_endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
21244   else mp_pair_value(mp, right_x(p),right_y(p));
21245   break;
21246 } /* there are no other cases */
21247
21248 @ @<Additional cases of binary operators@>=
21249 case arc_time_of: 
21250   if ( mp->cur_type==mp_pair_type )
21251      mp_pair_to_path(mp);
21252   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
21253     mp_flush_cur_exp(mp, mp_get_arc_time(mp, mp->cur_exp,value(p)));
21254   else 
21255     mp_bad_binary(mp, p,c);
21256   break;
21257
21258 @ @<Additional cases of bin...@>=
21259 case intersect: 
21260   if ( type(p)==mp_pair_type ) {
21261     q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p);
21262     mp_pair_to_path(mp); p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
21263   };
21264   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21265   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_path_type) ) {
21266     mp_path_intersection(mp, value(p),mp->cur_exp);
21267     mp_pair_value(mp, mp->cur_t,mp->cur_tt);
21268   } else {
21269     mp_bad_binary(mp, p,intersect);
21270   }
21271   break;
21272
21273 @ @<Additional cases of bin...@>=
21274 case in_font:
21275   if ( (mp->cur_type!=mp_string_type)||(type(p)!=mp_string_type)) 
21276     mp_bad_binary(mp, p,in_font);
21277   else { mp_do_infont(mp, p); return; }
21278   break;
21279
21280 @ Function |new_text_node| owns the reference count for its second argument
21281 (the text string) but not its first (the font name).
21282
21283 @<Declare binary action...@>=
21284 void mp_do_infont (MP mp,pointer p) {
21285   pointer q;
21286   q=mp_get_node(mp, edge_header_size);
21287   mp_init_edges(mp, q);
21288   link(obj_tail(q))=mp_new_text_node(mp,str(mp->cur_exp),value(p));
21289   obj_tail(q)=link(obj_tail(q));
21290   mp_free_node(mp, p,value_node_size);
21291   mp_flush_cur_exp(mp, q);
21292   mp->cur_type=mp_picture_type;
21293 }
21294
21295 @* \[40] Statements and commands.
21296 The chief executive of \MP\ is the |do_statement| routine, which
21297 contains the master switch that causes all the various pieces of \MP\
21298 to do their things, in the right order.
21299
21300 In a sense, this is the grand climax of the program: It applies all the
21301 tools that we have worked so hard to construct. In another sense, this is
21302 the messiest part of the program: It necessarily refers to other pieces
21303 of code all over the place, so that a person can't fully understand what is
21304 going on without paging back and forth to be reminded of conventions that
21305 are defined elsewhere. We are now at the hub of the web.
21306
21307 The structure of |do_statement| itself is quite simple.  The first token
21308 of the statement is fetched using |get_x_next|.  If it can be the first
21309 token of an expression, we look for an equation, an assignment, or a
21310 title. Otherwise we use a \&{case} construction to branch at high speed to
21311 the appropriate routine for various and sundry other types of commands,
21312 each of which has an ``action procedure'' that does the necessary work.
21313
21314 The program uses the fact that
21315 $$\hbox{|min_primary_command=max_statement_command=type_name|}$$
21316 to interpret a statement that starts with, e.g., `\&{string}',
21317 as a type declaration rather than a boolean expression.
21318
21319 @c void mp_do_statement (MP mp) { /* governs \MP's activities */
21320   mp->cur_type=mp_vacuous; mp_get_x_next(mp);
21321   if ( mp->cur_cmd>max_primary_command ) {
21322     @<Worry about bad statement@>;
21323   } else if ( mp->cur_cmd>max_statement_command ) {
21324     @<Do an equation, assignment, title, or
21325      `$\langle\,$expression$\,\rangle\,$\&{endgroup}'@>;
21326   } else {
21327     @<Do a statement that doesn't begin with an expression@>;
21328   }
21329   if ( mp->cur_cmd<semicolon )
21330     @<Flush unparsable junk that was found after the statement@>;
21331   mp->error_count=0;
21332 }
21333
21334 @ @<Declarations@>=
21335 @<Declare action procedures for use by |do_statement|@>;
21336
21337 @ The only command codes |>max_primary_command| that can be present
21338 at the beginning of a statement are |semicolon| and higher; these
21339 occur when the statement is null.
21340
21341 @<Worry about bad statement@>=
21342
21343   if ( mp->cur_cmd<semicolon ) {
21344     print_err("A statement can't begin with `");
21345 @.A statement can't begin with x@>
21346     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); mp_print_char(mp, '\'');
21347     help5("I was looking for the beginning of a new statement.")
21348       ("If you just proceed without changing anything, I'll ignore")
21349       ("everything up to the next `;'. Please insert a semicolon")
21350       ("now in front of anything that you don't want me to delete.")
21351       ("(See Chapter 27 of The METAFONTbook for an example.)");
21352 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21353     mp_back_error(mp); mp_get_x_next(mp);
21354   }
21355 }
21356
21357 @ The help message printed here says that everything is flushed up to
21358 a semicolon, but actually the commands |end_group| and |stop| will
21359 also terminate a statement.
21360
21361 @<Flush unparsable junk that was found after the statement@>=
21362
21363   print_err("Extra tokens will be flushed");
21364 @.Extra tokens will be flushed@>
21365   help6("I've just read as much of that statement as I could fathom,")
21366        ("so a semicolon should have been next. It's very puzzling...")
21367        ("but I'll try to get myself back together, by ignoring")
21368        ("everything up to the next `;'. Please insert a semicolon")
21369        ("now in front of anything that you don't want me to delete.")
21370        ("(See Chapter 27 of The METAFONTbook for an example.)");
21371 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21372   mp_back_error(mp); mp->scanner_status=flushing;
21373   do {  
21374     get_t_next;
21375     @<Decrease the string reference count...@>;
21376   } while (! end_of_statement); /* |cur_cmd=semicolon|, |end_group|, or |stop| */
21377   mp->scanner_status=normal;
21378 }
21379
21380 @ If |do_statement| ends with |cur_cmd=end_group|, we should have
21381 |cur_type=mp_vacuous| unless the statement was simply an expression;
21382 in the latter case, |cur_type| and |cur_exp| should represent that
21383 expression.
21384
21385 @<Do a statement that doesn't...@>=
21386
21387   if ( mp->internal[mp_tracing_commands]>0 ) 
21388     show_cur_cmd_mod;
21389   switch (mp->cur_cmd ) {
21390   case type_name:mp_do_type_declaration(mp); break;
21391   case macro_def:
21392     if ( mp->cur_mod>var_def ) mp_make_op_def(mp);
21393     else if ( mp->cur_mod>end_def ) mp_scan_def(mp);
21394      break;
21395   @<Cases of |do_statement| that invoke particular commands@>;
21396   } /* there are no other cases */
21397   mp->cur_type=mp_vacuous;
21398 }
21399
21400 @ The most important statements begin with expressions.
21401
21402 @<Do an equation, assignment, title, or...@>=
21403
21404   mp->var_flag=assignment; mp_scan_expression(mp);
21405   if ( mp->cur_cmd<end_group ) {
21406     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21407     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21408     else if ( mp->cur_type==mp_string_type ) {@<Do a title@> ; }
21409     else if ( mp->cur_type!=mp_vacuous ){ 
21410       exp_err("Isolated expression");
21411 @.Isolated expression@>
21412       help3("I couldn't find an `=' or `:=' after the")
21413         ("expression that is shown above this error message,")
21414         ("so I guess I'll just ignore it and carry on.");
21415       mp_put_get_error(mp);
21416     }
21417     mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous;
21418   }
21419 }
21420
21421 @ @<Do a title@>=
21422
21423   if ( mp->internal[mp_tracing_titles]>0 ) {
21424     mp_print_nl(mp, "");  mp_print_str(mp, mp->cur_exp); update_terminal;
21425   }
21426 }
21427
21428 @ Equations and assignments are performed by the pair of mutually recursive
21429 @^recursion@>
21430 routines |do_equation| and |do_assignment|. These routines are called when
21431 |cur_cmd=equals| and when |cur_cmd=assignment|, respectively; the left-hand
21432 side is in |cur_type| and |cur_exp|, while the right-hand side is yet
21433 to be scanned. After the routines are finished, |cur_type| and |cur_exp|
21434 will be equal to the right-hand side (which will normally be equal
21435 to the left-hand side).
21436
21437 @<Declare action procedures for use by |do_statement|@>=
21438 @<Declare the procedure called |try_eq|@>;
21439 @<Declare the procedure called |make_eq|@>;
21440 void mp_do_equation (MP mp) ;
21441
21442 @ @c
21443 void mp_do_equation (MP mp) {
21444   pointer lhs; /* capsule for the left-hand side */
21445   pointer p; /* temporary register */
21446   lhs=mp_stash_cur_exp(mp); mp_get_x_next(mp); 
21447   mp->var_flag=assignment; mp_scan_expression(mp);
21448   if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21449   else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21450   if ( mp->internal[mp_tracing_commands]>two ) 
21451     @<Trace the current equation@>;
21452   if ( mp->cur_type==mp_unknown_path ) if ( type(lhs)==mp_pair_type ) {
21453     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, lhs); lhs=p;
21454   }; /* in this case |make_eq| will change the pair to a path */
21455   mp_make_eq(mp, lhs); /* equate |lhs| to |(cur_type,cur_exp)| */
21456 }
21457
21458 @ And |do_assignment| is similar to |do_expression|:
21459
21460 @<Declarations@>=
21461 void mp_do_assignment (MP mp);
21462
21463 @ @<Declare action procedures for use by |do_statement|@>=
21464 void mp_do_assignment (MP mp) ;
21465
21466 @ @c
21467 void mp_do_assignment (MP mp) {
21468   pointer lhs; /* token list for the left-hand side */
21469   pointer p; /* where the left-hand value is stored */
21470   pointer q; /* temporary capsule for the right-hand value */
21471   if ( mp->cur_type!=mp_token_list ) { 
21472     exp_err("Improper `:=' will be changed to `='");
21473 @.Improper `:='@>
21474     help2("I didn't find a variable name at the left of the `:=',")
21475       ("so I'm going to pretend that you said `=' instead.");
21476     mp_error(mp); mp_do_equation(mp);
21477   } else { 
21478     lhs=mp->cur_exp; mp->cur_type=mp_vacuous;
21479     mp_get_x_next(mp); mp->var_flag=assignment; mp_scan_expression(mp);
21480     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21481     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21482     if ( mp->internal[mp_tracing_commands]>two ) 
21483       @<Trace the current assignment@>;
21484     if ( info(lhs)>hash_end ) {
21485       @<Assign the current expression to an internal variable@>;
21486     } else  {
21487       @<Assign the current expression to the variable |lhs|@>;
21488     }
21489     mp_flush_node_list(mp, lhs);
21490   }
21491 }
21492
21493 @ @<Trace the current equation@>=
21494
21495   mp_begin_diagnostic(mp); mp_print_nl(mp, "{("); mp_print_exp(mp,lhs,0);
21496   mp_print(mp,")=("); mp_print_exp(mp,null,0); 
21497   mp_print(mp,")}"); mp_end_diagnostic(mp, false);
21498 }
21499
21500 @ @<Trace the current assignment@>=
21501
21502   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
21503   if ( info(lhs)>hash_end ) 
21504      mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21505   else 
21506      mp_show_token_list(mp, lhs,null,1000,0);
21507   mp_print(mp, ":="); mp_print_exp(mp, null,0); 
21508   mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
21509 }
21510
21511 @ @<Assign the current expression to an internal variable@>=
21512 if ( mp->cur_type==mp_known )  {
21513   mp->internal[info(lhs)-(hash_end)]=mp->cur_exp;
21514 } else { 
21515   exp_err("Internal quantity `");
21516 @.Internal quantity...@>
21517   mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21518   mp_print(mp, "' must receive a known value");
21519   help2("I can\'t set an internal quantity to anything but a known")
21520     ("numeric value, so I'll have to ignore this assignment.");
21521   mp_put_get_error(mp);
21522 }
21523
21524 @ @<Assign the current expression to the variable |lhs|@>=
21525
21526   p=mp_find_variable(mp, lhs);
21527   if ( p!=null ) {
21528     q=mp_stash_cur_exp(mp); mp->cur_type=mp_und_type(mp, p); 
21529     mp_recycle_value(mp, p);
21530     type(p)=mp->cur_type; value(p)=null; mp_make_exp_copy(mp, p);
21531     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q); mp_make_eq(mp, p);
21532   } else  { 
21533     mp_obliterated(mp, lhs); mp_put_get_error(mp);
21534   }
21535 }
21536
21537
21538 @ And now we get to the nitty-gritty. The |make_eq| procedure is given
21539 a pointer to a capsule that is to be equated to the current expression.
21540
21541 @<Declare the procedure called |make_eq|@>=
21542 void mp_make_eq (MP mp,pointer lhs) ;
21543
21544
21545
21546 @c void mp_make_eq (MP mp,pointer lhs) {
21547   small_number t; /* type of the left-hand side */
21548   pointer p,q; /* pointers inside of big nodes */
21549   integer v=0; /* value of the left-hand side */
21550 RESTART: 
21551   t=type(lhs);
21552   if ( t<=mp_pair_type ) v=value(lhs);
21553   switch (t) {
21554   @<For each type |t|, make an equation and |goto done| unless |cur_type|
21555     is incompatible with~|t|@>;
21556   } /* all cases have been listed */
21557   @<Announce that the equation cannot be performed@>;
21558 DONE:
21559   check_arith; mp_recycle_value(mp, lhs); 
21560   mp_free_node(mp, lhs,value_node_size);
21561 }
21562
21563 @ @<Announce that the equation cannot be performed@>=
21564 mp_disp_err(mp, lhs,""); 
21565 exp_err("Equation cannot be performed (");
21566 @.Equation cannot be performed@>
21567 if ( type(lhs)<=mp_pair_type ) mp_print_type(mp, type(lhs));
21568 else mp_print(mp, "numeric");
21569 mp_print_char(mp, '=');
21570 if ( mp->cur_type<=mp_pair_type ) mp_print_type(mp, mp->cur_type);
21571 else mp_print(mp, "numeric");
21572 mp_print_char(mp, ')');
21573 help2("I'm sorry, but I don't know how to make such things equal.")
21574      ("(See the two expressions just above the error message.)");
21575 mp_put_get_error(mp)
21576
21577 @ @<For each type |t|, make an equation and |goto done| unless...@>=
21578 case mp_boolean_type: case mp_string_type: case mp_pen_type:
21579 case mp_path_type: case mp_picture_type:
21580   if ( mp->cur_type==t+unknown_tag ) { 
21581     mp_nonlinear_eq(mp, v,mp->cur_exp,false); goto DONE;
21582   } else if ( mp->cur_type==t ) {
21583     @<Report redundant or inconsistent equation and |goto done|@>;
21584   }
21585   break;
21586 case unknown_types:
21587   if ( mp->cur_type==t-unknown_tag ) { 
21588     mp_nonlinear_eq(mp, mp->cur_exp,lhs,true); goto DONE;
21589   } else if ( mp->cur_type==t ) { 
21590     mp_ring_merge(mp, lhs,mp->cur_exp); goto DONE;
21591   } else if ( mp->cur_type==mp_pair_type ) {
21592     if ( t==mp_unknown_path ) { 
21593      mp_pair_to_path(mp); goto RESTART;
21594     };
21595   }
21596   break;
21597 case mp_transform_type: case mp_color_type:
21598 case mp_cmykcolor_type: case mp_pair_type:
21599   if ( mp->cur_type==t ) {
21600     @<Do multiple equations and |goto done|@>;
21601   }
21602   break;
21603 case mp_known: case mp_dependent:
21604 case mp_proto_dependent: case mp_independent:
21605   if ( mp->cur_type>=mp_known ) { 
21606     mp_try_eq(mp, lhs,null); goto DONE;
21607   };
21608   break;
21609 case mp_vacuous:
21610   break;
21611
21612 @ @<Report redundant or inconsistent equation and |goto done|@>=
21613
21614   if ( mp->cur_type<=mp_string_type ) {
21615     if ( mp->cur_type==mp_string_type ) {
21616       if ( mp_str_vs_str(mp, v,mp->cur_exp)!=0 ) {
21617         goto NOT_FOUND;
21618       }
21619     } else if ( v!=mp->cur_exp ) {
21620       goto NOT_FOUND;
21621     }
21622     @<Exclaim about a redundant equation@>; goto DONE;
21623   }
21624   print_err("Redundant or inconsistent equation");
21625 @.Redundant or inconsistent equation@>
21626   help2("An equation between already-known quantities can't help.")
21627        ("But don't worry; continue and I'll just ignore it.");
21628   mp_put_get_error(mp); goto DONE;
21629 NOT_FOUND: 
21630   print_err("Inconsistent equation");
21631 @.Inconsistent equation@>
21632   help2("The equation I just read contradicts what was said before.")
21633        ("But don't worry; continue and I'll just ignore it.");
21634   mp_put_get_error(mp); goto DONE;
21635 }
21636
21637 @ @<Do multiple equations and |goto done|@>=
21638
21639   p=v+mp->big_node_size[t]; 
21640   q=value(mp->cur_exp)+mp->big_node_size[t];
21641   do {  
21642     p=p-2; q=q-2; mp_try_eq(mp, p,q);
21643   } while (p!=v);
21644   goto DONE;
21645 }
21646
21647 @ The first argument to |try_eq| is the location of a value node
21648 in a capsule that will soon be recycled. The second argument is
21649 either a location within a pair or transform node pointed to by
21650 |cur_exp|, or it is |null| (which means that |cur_exp| itself
21651 serves as the second argument). The idea is to leave |cur_exp| unchanged,
21652 but to equate the two operands.
21653
21654 @<Declare the procedure called |try_eq|@>=
21655 void mp_try_eq (MP mp,pointer l, pointer r) ;
21656
21657
21658 @c void mp_try_eq (MP mp,pointer l, pointer r) {
21659   pointer p; /* dependency list for right operand minus left operand */
21660   int t; /* the type of list |p| */
21661   pointer q; /* the constant term of |p| is here */
21662   pointer pp; /* dependency list for right operand */
21663   int tt; /* the type of list |pp| */
21664   boolean copied; /* have we copied a list that ought to be recycled? */
21665   @<Remove the left operand from its container, negate it, and
21666     put it into dependency list~|p| with constant term~|q|@>;
21667   @<Add the right operand to list |p|@>;
21668   if ( info(p)==null ) {
21669     @<Deal with redundant or inconsistent equation@>;
21670   } else { 
21671     mp_linear_eq(mp, p,t);
21672     if ( r==null ) if ( mp->cur_type!=mp_known ) {
21673       if ( type(mp->cur_exp)==mp_known ) {
21674         pp=mp->cur_exp; mp->cur_exp=value(mp->cur_exp); mp->cur_type=mp_known;
21675         mp_free_node(mp, pp,value_node_size);
21676       }
21677     }
21678   }
21679 }
21680
21681 @ @<Remove the left operand from its container, negate it, and...@>=
21682 t=type(l);
21683 if ( t==mp_known ) { 
21684   t=mp_dependent; p=mp_const_dependency(mp, -value(l)); q=p;
21685 } else if ( t==mp_independent ) {
21686   t=mp_dependent; p=mp_single_dependency(mp, l); negate(value(p));
21687   q=mp->dep_final;
21688 } else { 
21689   p=dep_list(l); q=p;
21690   while (1) { 
21691     negate(value(q));
21692     if ( info(q)==null ) break;
21693     q=link(q);
21694   }
21695   link(prev_dep(l))=link(q); prev_dep(link(q))=prev_dep(l);
21696   type(l)=mp_known;
21697 }
21698
21699 @ @<Deal with redundant or inconsistent equation@>=
21700
21701   if ( abs(value(p))>64 ) { /* off by .001 or more */
21702     print_err("Inconsistent equation");
21703 @.Inconsistent equation@>
21704     mp_print(mp, " (off by "); mp_print_scaled(mp, value(p)); 
21705     mp_print_char(mp, ')');
21706     help2("The equation I just read contradicts what was said before.")
21707       ("But don't worry; continue and I'll just ignore it.");
21708     mp_put_get_error(mp);
21709   } else if ( r==null ) {
21710     @<Exclaim about a redundant equation@>;
21711   }
21712   mp_free_node(mp, p,dep_node_size);
21713 }
21714
21715 @ @<Add the right operand to list |p|@>=
21716 if ( r==null ) {
21717   if ( mp->cur_type==mp_known ) {
21718     value(q)=value(q)+mp->cur_exp; goto DONE1;
21719   } else { 
21720     tt=mp->cur_type;
21721     if ( tt==mp_independent ) pp=mp_single_dependency(mp, mp->cur_exp);
21722     else pp=dep_list(mp->cur_exp);
21723   } 
21724 } else {
21725   if ( type(r)==mp_known ) {
21726     value(q)=value(q)+value(r); goto DONE1;
21727   } else { 
21728     tt=type(r);
21729     if ( tt==mp_independent ) pp=mp_single_dependency(mp, r);
21730     else pp=dep_list(r);
21731   }
21732 }
21733 if ( tt!=mp_independent ) copied=false;
21734 else  { copied=true; tt=mp_dependent; };
21735 @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>;
21736 if ( copied ) mp_flush_node_list(mp, pp);
21737 DONE1:
21738
21739 @ @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>=
21740 mp->watch_coefs=false;
21741 if ( t==tt ) {
21742   p=mp_p_plus_q(mp, p,pp,t);
21743 } else if ( t==mp_proto_dependent ) {
21744   p=mp_p_plus_fq(mp, p,unity,pp,mp_proto_dependent,mp_dependent);
21745 } else { 
21746   q=p;
21747   while ( info(q)!=null ) {
21748     value(q)=mp_round_fraction(mp, value(q)); q=link(q);
21749   }
21750   t=mp_proto_dependent; p=mp_p_plus_q(mp, p,pp,t);
21751 }
21752 mp->watch_coefs=true;
21753
21754 @ Our next goal is to process type declarations. For this purpose it's
21755 convenient to have a procedure that scans a $\langle\,$declared
21756 variable$\,\rangle$ and returns the corresponding token list. After the
21757 following procedure has acted, the token after the declared variable
21758 will have been scanned, so it will appear in |cur_cmd|, |cur_mod|,
21759 and~|cur_sym|.
21760
21761 @<Declare the function called |scan_declared_variable|@>=
21762 pointer mp_scan_declared_variable (MP mp) {
21763   pointer x; /* hash address of the variable's root */
21764   pointer h,t; /* head and tail of the token list to be returned */
21765   pointer l; /* hash address of left bracket */
21766   mp_get_symbol(mp); x=mp->cur_sym;
21767   if ( mp->cur_cmd!=tag_token ) mp_clear_symbol(mp, x,false);
21768   h=mp_get_avail(mp); info(h)=x; t=h;
21769   while (1) { 
21770     mp_get_x_next(mp);
21771     if ( mp->cur_sym==0 ) break;
21772     if ( mp->cur_cmd!=tag_token ) if ( mp->cur_cmd!=internal_quantity)  {
21773       if ( mp->cur_cmd==left_bracket ) {
21774         @<Descend past a collective subscript@>;
21775       } else {
21776         break;
21777       }
21778     }
21779     link(t)=mp_get_avail(mp); t=link(t); info(t)=mp->cur_sym;
21780   }
21781   if ( eq_type(x)!=tag_token ) mp_clear_symbol(mp, x,false);
21782   if ( equiv(x)==null ) mp_new_root(mp, x);
21783   return h;
21784 }
21785
21786 @ If the subscript isn't collective, we don't accept it as part of the
21787 declared variable.
21788
21789 @<Descend past a collective subscript@>=
21790
21791   l=mp->cur_sym; mp_get_x_next(mp);
21792   if ( mp->cur_cmd!=right_bracket ) {
21793     mp_back_input(mp); mp->cur_sym=l; mp->cur_cmd=left_bracket; break;
21794   } else {
21795     mp->cur_sym=collective_subscript;
21796   }
21797 }
21798
21799 @ Type declarations are introduced by the following primitive operations.
21800
21801 @<Put each...@>=
21802 mp_primitive(mp, "numeric",type_name,mp_numeric_type);
21803 @:numeric_}{\&{numeric} primitive@>
21804 mp_primitive(mp, "string",type_name,mp_string_type);
21805 @:string_}{\&{string} primitive@>
21806 mp_primitive(mp, "boolean",type_name,mp_boolean_type);
21807 @:boolean_}{\&{boolean} primitive@>
21808 mp_primitive(mp, "path",type_name,mp_path_type);
21809 @:path_}{\&{path} primitive@>
21810 mp_primitive(mp, "pen",type_name,mp_pen_type);
21811 @:pen_}{\&{pen} primitive@>
21812 mp_primitive(mp, "picture",type_name,mp_picture_type);
21813 @:picture_}{\&{picture} primitive@>
21814 mp_primitive(mp, "transform",type_name,mp_transform_type);
21815 @:transform_}{\&{transform} primitive@>
21816 mp_primitive(mp, "color",type_name,mp_color_type);
21817 @:color_}{\&{color} primitive@>
21818 mp_primitive(mp, "rgbcolor",type_name,mp_color_type);
21819 @:color_}{\&{rgbcolor} primitive@>
21820 mp_primitive(mp, "cmykcolor",type_name,mp_cmykcolor_type);
21821 @:color_}{\&{cmykcolor} primitive@>
21822 mp_primitive(mp, "pair",type_name,mp_pair_type);
21823 @:pair_}{\&{pair} primitive@>
21824
21825 @ @<Cases of |print_cmd...@>=
21826 case type_name: mp_print_type(mp, m); break;
21827
21828 @ Now we are ready to handle type declarations, assuming that a
21829 |type_name| has just been scanned.
21830
21831 @<Declare action procedures for use by |do_statement|@>=
21832 void mp_do_type_declaration (MP mp) ;
21833
21834 @ @c
21835 void mp_do_type_declaration (MP mp) {
21836   small_number t; /* the type being declared */
21837   pointer p; /* token list for a declared variable */
21838   pointer q; /* value node for the variable */
21839   if ( mp->cur_mod>=mp_transform_type ) 
21840     t=mp->cur_mod;
21841   else 
21842     t=mp->cur_mod+unknown_tag;
21843   do {  
21844     p=mp_scan_declared_variable(mp);
21845     mp_flush_variable(mp, equiv(info(p)),link(p),false);
21846     q=mp_find_variable(mp, p);
21847     if ( q!=null ) { 
21848       type(q)=t; value(q)=null; 
21849     } else  { 
21850       print_err("Declared variable conflicts with previous vardef");
21851 @.Declared variable conflicts...@>
21852       help2("You can't use, e.g., `numeric foo[]' after `vardef foo'.")
21853            ("Proceed, and I'll ignore the illegal redeclaration.");
21854       mp_put_get_error(mp);
21855     }
21856     mp_flush_list(mp, p);
21857     if ( mp->cur_cmd<comma ) {
21858       @<Flush spurious symbols after the declared variable@>;
21859     }
21860   } while (! end_of_statement);
21861 }
21862
21863 @ @<Flush spurious symbols after the declared variable@>=
21864
21865   print_err("Illegal suffix of declared variable will be flushed");
21866 @.Illegal suffix...flushed@>
21867   help5("Variables in declarations must consist entirely of")
21868     ("names and collective subscripts, e.g., `x[]a'.")
21869     ("Are you trying to use a reserved word in a variable name?")
21870     ("I'm going to discard the junk I found here,")
21871     ("up to the next comma or the end of the declaration.");
21872   if ( mp->cur_cmd==numeric_token )
21873     mp->help_line[2]="Explicit subscripts like `x15a' aren't permitted.";
21874   mp_put_get_error(mp); mp->scanner_status=flushing;
21875   do {  
21876     get_t_next;
21877     @<Decrease the string reference count...@>;
21878   } while (mp->cur_cmd<comma); /* either |end_of_statement| or |cur_cmd=comma| */
21879   mp->scanner_status=normal;
21880 }
21881
21882 @ \MP's |main_control| procedure just calls |do_statement| repeatedly
21883 until coming to the end of the user's program.
21884 Each execution of |do_statement| concludes with
21885 |cur_cmd=semicolon|, |end_group|, or |stop|.
21886
21887 @c void mp_main_control (MP mp) { 
21888   do {  
21889     mp_do_statement(mp);
21890     if ( mp->cur_cmd==end_group ) {
21891       print_err("Extra `endgroup'");
21892 @.Extra `endgroup'@>
21893       help2("I'm not currently working on a `begingroup',")
21894         ("so I had better not try to end anything.");
21895       mp_flush_error(mp, 0);
21896     }
21897   } while (mp->cur_cmd!=stop);
21898 }
21899 int mp_run (MP mp) {
21900   @<Install and test the non-local jump buffer@>;
21901   mp_main_control(mp); /* come to life */
21902   mp_final_cleanup(mp); /* prepare for death */
21903   mp_close_files_and_terminate(mp);
21904   return mp->history;
21905 }
21906 char * mp_mplib_version (MP mp) {
21907   assert(mp);
21908   return mplib_version;
21909 }
21910 char * mp_metapost_version (MP mp) {
21911   assert(mp);
21912   return metapost_version;
21913 }
21914
21915 @ @<Exported function headers@>=
21916 int mp_run (MP mp);
21917 char * mp_mplib_version (MP mp);
21918 char * mp_metapost_version (MP mp);
21919
21920 @ @<Put each...@>=
21921 mp_primitive(mp, "end",stop,0);
21922 @:end_}{\&{end} primitive@>
21923 mp_primitive(mp, "dump",stop,1);
21924 @:dump_}{\&{dump} primitive@>
21925
21926 @ @<Cases of |print_cmd...@>=
21927 case stop:
21928   if ( m==0 ) mp_print(mp, "end");
21929   else mp_print(mp, "dump");
21930   break;
21931
21932 @* \[41] Commands.
21933 Let's turn now to statements that are classified as ``commands'' because
21934 of their imperative nature. We'll begin with simple ones, so that it
21935 will be clear how to hook command processing into the |do_statement| routine;
21936 then we'll tackle the tougher commands.
21937
21938 Here's one of the simplest:
21939
21940 @<Cases of |do_statement|...@>=
21941 case mp_random_seed: mp_do_random_seed(mp);  break;
21942
21943 @ @<Declare action procedures for use by |do_statement|@>=
21944 void mp_do_random_seed (MP mp) ;
21945
21946 @ @c void mp_do_random_seed (MP mp) { 
21947   mp_get_x_next(mp);
21948   if ( mp->cur_cmd!=assignment ) {
21949     mp_missing_err(mp, ":=");
21950 @.Missing `:='@>
21951     help1("Always say `randomseed:=<numeric expression>'.");
21952     mp_back_error(mp);
21953   };
21954   mp_get_x_next(mp); mp_scan_expression(mp);
21955   if ( mp->cur_type!=mp_known ) {
21956     exp_err("Unknown value will be ignored");
21957 @.Unknown value...ignored@>
21958     help2("Your expression was too random for me to handle,")
21959       ("so I won't change the random seed just now.");
21960     mp_put_get_flush_error(mp, 0);
21961   } else {
21962    @<Initialize the random seed to |cur_exp|@>;
21963   }
21964 }
21965
21966 @ @<Initialize the random seed to |cur_exp|@>=
21967
21968   mp_init_randoms(mp, mp->cur_exp);
21969   if ( mp->selector>=log_only && mp->selector<write_file) {
21970     mp->old_setting=mp->selector; mp->selector=log_only;
21971     mp_print_nl(mp, "{randomseed:="); 
21972     mp_print_scaled(mp, mp->cur_exp); 
21973     mp_print_char(mp, '}');
21974     mp_print_nl(mp, ""); mp->selector=mp->old_setting;
21975   }
21976 }
21977
21978 @ And here's another simple one (somewhat different in flavor):
21979
21980 @<Cases of |do_statement|...@>=
21981 case mode_command: 
21982   mp_print_ln(mp); mp->interaction=mp->cur_mod;
21983   @<Initialize the print |selector| based on |interaction|@>;
21984   if ( mp->log_opened ) mp->selector=mp->selector+2;
21985   mp_get_x_next(mp);
21986   break;
21987
21988 @ @<Put each...@>=
21989 mp_primitive(mp, "batchmode",mode_command,mp_batch_mode);
21990 @:mp_batch_mode_}{\&{batchmode} primitive@>
21991 mp_primitive(mp, "nonstopmode",mode_command,mp_nonstop_mode);
21992 @:mp_nonstop_mode_}{\&{nonstopmode} primitive@>
21993 mp_primitive(mp, "scrollmode",mode_command,mp_scroll_mode);
21994 @:mp_scroll_mode_}{\&{scrollmode} primitive@>
21995 mp_primitive(mp, "errorstopmode",mode_command,mp_error_stop_mode);
21996 @:mp_error_stop_mode_}{\&{errorstopmode} primitive@>
21997
21998 @ @<Cases of |print_cmd_mod|...@>=
21999 case mode_command: 
22000   switch (m) {
22001   case mp_batch_mode: mp_print(mp, "batchmode"); break;
22002   case mp_nonstop_mode: mp_print(mp, "nonstopmode"); break;
22003   case mp_scroll_mode: mp_print(mp, "scrollmode"); break;
22004   default: mp_print(mp, "errorstopmode"); break;
22005   }
22006   break;
22007
22008 @ The `\&{inner}' and `\&{outer}' commands are only slightly harder.
22009
22010 @<Cases of |do_statement|...@>=
22011 case protection_command: mp_do_protection(mp); break;
22012
22013 @ @<Put each...@>=
22014 mp_primitive(mp, "inner",protection_command,0);
22015 @:inner_}{\&{inner} primitive@>
22016 mp_primitive(mp, "outer",protection_command,1);
22017 @:outer_}{\&{outer} primitive@>
22018
22019 @ @<Cases of |print_cmd...@>=
22020 case protection_command: 
22021   if ( m==0 ) mp_print(mp, "inner");
22022   else mp_print(mp, "outer");
22023   break;
22024
22025 @ @<Declare action procedures for use by |do_statement|@>=
22026 void mp_do_protection (MP mp) ;
22027
22028 @ @c void mp_do_protection (MP mp) {
22029   int m; /* 0 to unprotect, 1 to protect */
22030   halfword t; /* the |eq_type| before we change it */
22031   m=mp->cur_mod;
22032   do {  
22033     mp_get_symbol(mp); t=eq_type(mp->cur_sym);
22034     if ( m==0 ) { 
22035       if ( t>=outer_tag ) 
22036         eq_type(mp->cur_sym)=t-outer_tag;
22037     } else if ( t<outer_tag ) {
22038       eq_type(mp->cur_sym)=t+outer_tag;
22039     }
22040     mp_get_x_next(mp);
22041   } while (mp->cur_cmd==comma);
22042 }
22043
22044 @ \MP\ never defines the tokens `\.(' and `\.)' to be primitives, but
22045 plain \MP\ begins with the declaration `\&{delimiters} \.{()}'. Such a
22046 declaration assigns the command code |left_delimiter| to `\.{(}' and
22047 |right_delimiter| to `\.{)}'; the |equiv| of each delimiter is the
22048 hash address of its mate.
22049
22050 @<Cases of |do_statement|...@>=
22051 case delimiters: mp_def_delims(mp); break;
22052
22053 @ @<Declare action procedures for use by |do_statement|@>=
22054 void mp_def_delims (MP mp) ;
22055
22056 @ @c void mp_def_delims (MP mp) {
22057   pointer l_delim,r_delim; /* the new delimiter pair */
22058   mp_get_clear_symbol(mp); l_delim=mp->cur_sym;
22059   mp_get_clear_symbol(mp); r_delim=mp->cur_sym;
22060   eq_type(l_delim)=left_delimiter; equiv(l_delim)=r_delim;
22061   eq_type(r_delim)=right_delimiter; equiv(r_delim)=l_delim;
22062   mp_get_x_next(mp);
22063 }
22064
22065 @ Here is a procedure that is called when \MP\ has reached a point
22066 where some right delimiter is mandatory.
22067
22068 @<Declare the procedure called |check_delimiter|@>=
22069 void mp_check_delimiter (MP mp,pointer l_delim, pointer r_delim) {
22070   if ( mp->cur_cmd==right_delimiter ) 
22071     if ( mp->cur_mod==l_delim ) 
22072       return;
22073   if ( mp->cur_sym!=r_delim ) {
22074      mp_missing_err(mp, str(text(r_delim)));
22075 @.Missing `)'@>
22076     help2("I found no right delimiter to match a left one. So I've")
22077       ("put one in, behind the scenes; this may fix the problem.");
22078     mp_back_error(mp);
22079   } else { 
22080     print_err("The token `"); mp_print_text(r_delim);
22081 @.The token...delimiter@>
22082     mp_print(mp, "' is no longer a right delimiter");
22083     help3("Strange: This token has lost its former meaning!")
22084       ("I'll read it as a right delimiter this time;")
22085       ("but watch out, I'll probably miss it later.");
22086     mp_error(mp);
22087   }
22088 }
22089
22090 @ The next four commands save or change the values associated with tokens.
22091
22092 @<Cases of |do_statement|...@>=
22093 case save_command: 
22094   do {  
22095     mp_get_symbol(mp); mp_save_variable(mp, mp->cur_sym); mp_get_x_next(mp);
22096   } while (mp->cur_cmd==comma);
22097   break;
22098 case interim_command: mp_do_interim(mp); break;
22099 case let_command: mp_do_let(mp); break;
22100 case new_internal: mp_do_new_internal(mp); break;
22101
22102 @ @<Declare action procedures for use by |do_statement|@>=
22103 void mp_do_statement (MP mp);
22104 void mp_do_interim (MP mp);
22105
22106 @ @c void mp_do_interim (MP mp) { 
22107   mp_get_x_next(mp);
22108   if ( mp->cur_cmd!=internal_quantity ) {
22109      print_err("The token `");
22110 @.The token...quantity@>
22111     if ( mp->cur_sym==0 ) mp_print(mp, "(%CAPSULE)");
22112     else mp_print_text(mp->cur_sym);
22113     mp_print(mp, "' isn't an internal quantity");
22114     help1("Something like `tracingonline' should follow `interim'.");
22115     mp_back_error(mp);
22116   } else { 
22117     mp_save_internal(mp, mp->cur_mod); mp_back_input(mp);
22118   }
22119   mp_do_statement(mp);
22120 }
22121
22122 @ The following procedure is careful not to undefine the left-hand symbol
22123 too soon, lest commands like `{\tt let x=x}' have a surprising effect.
22124
22125 @<Declare action procedures for use by |do_statement|@>=
22126 void mp_do_let (MP mp) ;
22127
22128 @ @c void mp_do_let (MP mp) {
22129   pointer l; /* hash location of the left-hand symbol */
22130   mp_get_symbol(mp); l=mp->cur_sym; mp_get_x_next(mp);
22131   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
22132      mp_missing_err(mp, "=");
22133 @.Missing `='@>
22134     help3("You should have said `let symbol = something'.")
22135       ("But don't worry; I'll pretend that an equals sign")
22136       ("was present. The next token I read will be `something'.");
22137     mp_back_error(mp);
22138   }
22139   mp_get_symbol(mp);
22140   switch (mp->cur_cmd) {
22141   case defined_macro: case secondary_primary_macro:
22142   case tertiary_secondary_macro: case expression_tertiary_macro: 
22143     add_mac_ref(mp->cur_mod);
22144     break;
22145   default: 
22146     break;
22147   }
22148   mp_clear_symbol(mp, l,false); eq_type(l)=mp->cur_cmd;
22149   if ( mp->cur_cmd==tag_token ) equiv(l)=null;
22150   else equiv(l)=mp->cur_mod;
22151   mp_get_x_next(mp);
22152 }
22153
22154 @ @<Declarations@>=
22155 void mp_grow_internals (MP mp, int l);
22156 void mp_do_new_internal (MP mp) ;
22157
22158 @ @c
22159 void mp_grow_internals (MP mp, int l) {
22160   scaled *internal;
22161   char * *int_name; 
22162   int k;
22163   if ( hash_end+l>max_halfword ) {
22164     mp_confusion(mp, "out of memory space"); /* can't be reached */
22165   }
22166   int_name = xmalloc ((l+1),sizeof(char *));
22167   internal = xmalloc ((l+1),sizeof(scaled));
22168   for (k=0;k<=l; k++ ) { 
22169     if (k<=mp->max_internal) {
22170       internal[k]=mp->internal[k]; 
22171       int_name[k]=mp->int_name[k]; 
22172     } else {
22173       internal[k]=0; 
22174       int_name[k]=NULL; 
22175     }
22176   }
22177   xfree(mp->internal); xfree(mp->int_name);
22178   mp->int_name = int_name;
22179   mp->internal = internal;
22180   mp->max_internal = l;
22181 }
22182
22183
22184 void mp_do_new_internal (MP mp) { 
22185   do {  
22186     if ( mp->int_ptr==mp->max_internal ) {
22187       mp_grow_internals(mp, (mp->max_internal + (mp->max_internal>>2)));
22188     }
22189     mp_get_clear_symbol(mp); incr(mp->int_ptr);
22190     eq_type(mp->cur_sym)=internal_quantity; 
22191     equiv(mp->cur_sym)=mp->int_ptr;
22192     if(mp->int_name[mp->int_ptr]!=NULL)
22193       xfree(mp->int_name[mp->int_ptr]);
22194     mp->int_name[mp->int_ptr]=str(text(mp->cur_sym)); 
22195     mp->internal[mp->int_ptr]=0;
22196     mp_get_x_next(mp);
22197   } while (mp->cur_cmd==comma);
22198 }
22199
22200 @ @<Dealloc variables@>=
22201 for (k=0;k<=mp->max_internal;k++) {
22202    xfree(mp->int_name[k]);
22203 }
22204 xfree(mp->internal); 
22205 xfree(mp->int_name); 
22206
22207
22208 @ The various `\&{show}' commands are distinguished by modifier fields
22209 in the usual way.
22210
22211 @d show_token_code 0 /* show the meaning of a single token */
22212 @d show_stats_code 1 /* show current memory and string usage */
22213 @d show_code 2 /* show a list of expressions */
22214 @d show_var_code 3 /* show a variable and its descendents */
22215 @d show_dependencies_code 4 /* show dependent variables in terms of independents */
22216
22217 @<Put each...@>=
22218 mp_primitive(mp, "showtoken",show_command,show_token_code);
22219 @:show_token_}{\&{showtoken} primitive@>
22220 mp_primitive(mp, "showstats",show_command,show_stats_code);
22221 @:show_stats_}{\&{showstats} primitive@>
22222 mp_primitive(mp, "show",show_command,show_code);
22223 @:show_}{\&{show} primitive@>
22224 mp_primitive(mp, "showvariable",show_command,show_var_code);
22225 @:show_var_}{\&{showvariable} primitive@>
22226 mp_primitive(mp, "showdependencies",show_command,show_dependencies_code);
22227 @:show_dependencies_}{\&{showdependencies} primitive@>
22228
22229 @ @<Cases of |print_cmd...@>=
22230 case show_command: 
22231   switch (m) {
22232   case show_token_code:mp_print(mp, "showtoken"); break;
22233   case show_stats_code:mp_print(mp, "showstats"); break;
22234   case show_code:mp_print(mp, "show"); break;
22235   case show_var_code:mp_print(mp, "showvariable"); break;
22236   default: mp_print(mp, "showdependencies"); break;
22237   }
22238   break;
22239
22240 @ @<Cases of |do_statement|...@>=
22241 case show_command:mp_do_show_whatever(mp); break;
22242
22243 @ The value of |cur_mod| controls the |verbosity| in the |print_exp| routine:
22244 if it's |show_code|, complicated structures are abbreviated, otherwise
22245 they aren't.
22246
22247 @<Declare action procedures for use by |do_statement|@>=
22248 void mp_do_show (MP mp) ;
22249
22250 @ @c void mp_do_show (MP mp) { 
22251   do {  
22252     mp_get_x_next(mp); mp_scan_expression(mp);
22253     mp_print_nl(mp, ">> ");
22254 @.>>@>
22255     mp_print_exp(mp, null,2); mp_flush_cur_exp(mp, 0);
22256   } while (mp->cur_cmd==comma);
22257 }
22258
22259 @ @<Declare action procedures for use by |do_statement|@>=
22260 void mp_disp_token (MP mp) ;
22261
22262 @ @c void mp_disp_token (MP mp) { 
22263   mp_print_nl(mp, "> ");
22264 @.>\relax@>
22265   if ( mp->cur_sym==0 ) {
22266     @<Show a numeric or string or capsule token@>;
22267   } else { 
22268     mp_print_text(mp->cur_sym); mp_print_char(mp, '=');
22269     if ( eq_type(mp->cur_sym)>=outer_tag ) mp_print(mp, "(outer) ");
22270     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod);
22271     if ( mp->cur_cmd==defined_macro ) {
22272       mp_print_ln(mp); mp_show_macro(mp, mp->cur_mod,null,100000);
22273     } /* this avoids recursion between |show_macro| and |print_cmd_mod| */
22274 @^recursion@>
22275   }
22276 }
22277
22278 @ @<Show a numeric or string or capsule token@>=
22279
22280   if ( mp->cur_cmd==numeric_token ) {
22281     mp_print_scaled(mp, mp->cur_mod);
22282   } else if ( mp->cur_cmd==capsule_token ) {
22283     mp->g_pointer=mp->cur_mod; mp_print_capsule(mp);
22284   } else  { 
22285     mp_print_char(mp, '"'); 
22286     mp_print_str(mp, mp->cur_mod); mp_print_char(mp, '"');
22287     delete_str_ref(mp->cur_mod);
22288   }
22289 }
22290
22291 @ The following cases of |print_cmd_mod| might arise in connection
22292 with |disp_token|, although they don't correspond to any
22293 primitive tokens.
22294
22295 @<Cases of |print_cmd_...@>=
22296 case left_delimiter:
22297 case right_delimiter: 
22298   if ( c==left_delimiter ) mp_print(mp, "left");
22299   else mp_print(mp, "right");
22300   mp_print(mp, " delimiter that matches "); 
22301   mp_print_text(m);
22302   break;
22303 case tag_token:
22304   if ( m==null ) mp_print(mp, "tag");
22305    else mp_print(mp, "variable");
22306    break;
22307 case defined_macro: 
22308    mp_print(mp, "macro:");
22309    break;
22310 case secondary_primary_macro:
22311 case tertiary_secondary_macro:
22312 case expression_tertiary_macro:
22313   mp_print_cmd_mod(mp, macro_def,c); 
22314   mp_print(mp, "'d macro:");
22315   mp_print_ln(mp); mp_show_token_list(mp, link(link(m)),null,1000,0);
22316   break;
22317 case repeat_loop:
22318   mp_print(mp, "[repeat the loop]");
22319   break;
22320 case internal_quantity:
22321   mp_print(mp, mp->int_name[m]);
22322   break;
22323
22324 @ @<Declare action procedures for use by |do_statement|@>=
22325 void mp_do_show_token (MP mp) ;
22326
22327 @ @c void mp_do_show_token (MP mp) { 
22328   do {  
22329     get_t_next; mp_disp_token(mp);
22330     mp_get_x_next(mp);
22331   } while (mp->cur_cmd==comma);
22332 }
22333
22334 @ @<Declare action procedures for use by |do_statement|@>=
22335 void mp_do_show_stats (MP mp) ;
22336
22337 @ @c void mp_do_show_stats (MP mp) { 
22338   mp_print_nl(mp, "Memory usage ");
22339 @.Memory usage...@>
22340   mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used);
22341   if ( false )
22342     mp_print(mp, "unknown");
22343   mp_print(mp, " ("); mp_print_int(mp, mp->hi_mem_min-mp->lo_mem_max-1);
22344   mp_print(mp, " still untouched)"); mp_print_ln(mp);
22345   mp_print_nl(mp, "String usage ");
22346   mp_print_int(mp, mp->strs_in_use-mp->init_str_use);
22347   mp_print_char(mp, '&'); mp_print_int(mp, mp->pool_in_use-mp->init_pool_ptr);
22348   if ( false )
22349     mp_print(mp, "unknown");
22350   mp_print(mp, " (");
22351   mp_print_int(mp, mp->max_strings-1-mp->strs_used_up); mp_print_char(mp, '&');
22352   mp_print_int(mp, mp->pool_size-mp->pool_ptr); 
22353   mp_print(mp, " now untouched)"); mp_print_ln(mp);
22354   mp_get_x_next(mp);
22355 }
22356
22357 @ Here's a recursive procedure that gives an abbreviated account
22358 of a variable, for use by |do_show_var|.
22359
22360 @<Declare action procedures for use by |do_statement|@>=
22361 void mp_disp_var (MP mp,pointer p) ;
22362
22363 @ @c void mp_disp_var (MP mp,pointer p) {
22364   pointer q; /* traverses attributes and subscripts */
22365   int n; /* amount of macro text to show */
22366   if ( type(p)==mp_structured )  {
22367     @<Descend the structure@>;
22368   } else if ( type(p)>=mp_unsuffixed_macro ) {
22369     @<Display a variable macro@>;
22370   } else if ( type(p)!=undefined ){ 
22371     mp_print_nl(mp, ""); mp_print_variable_name(mp, p); 
22372     mp_print_char(mp, '=');
22373     mp_print_exp(mp, p,0);
22374   }
22375 }
22376
22377 @ @<Descend the structure@>=
22378
22379   q=attr_head(p);
22380   do {  mp_disp_var(mp, q); q=link(q); } while (q!=end_attr);
22381   q=subscr_head(p);
22382   while ( name_type(q)==mp_subscr ) { 
22383     mp_disp_var(mp, q); q=link(q);
22384   }
22385 }
22386
22387 @ @<Display a variable macro@>=
22388
22389   mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22390   if ( type(p)>mp_unsuffixed_macro ) 
22391     mp_print(mp, "@@#"); /* |suffixed_macro| */
22392   mp_print(mp, "=macro:");
22393   if ( (int)mp->file_offset>=mp->max_print_line-20 ) n=5;
22394   else n=mp->max_print_line-mp->file_offset-15;
22395   mp_show_macro(mp, value(p),null,n);
22396 }
22397
22398 @ @<Declare action procedures for use by |do_statement|@>=
22399 void mp_do_show_var (MP mp) ;
22400
22401 @ @c void mp_do_show_var (MP mp) { 
22402   do {  
22403     get_t_next;
22404     if ( mp->cur_sym>0 ) if ( mp->cur_sym<=hash_end )
22405       if ( mp->cur_cmd==tag_token ) if ( mp->cur_mod!=null ) {
22406       mp_disp_var(mp, mp->cur_mod); goto DONE;
22407     }
22408    mp_disp_token(mp);
22409   DONE:
22410    mp_get_x_next(mp);
22411   } while (mp->cur_cmd==comma);
22412 }
22413
22414 @ @<Declare action procedures for use by |do_statement|@>=
22415 void mp_do_show_dependencies (MP mp) ;
22416
22417 @ @c void mp_do_show_dependencies (MP mp) {
22418   pointer p; /* link that runs through all dependencies */
22419   p=link(dep_head);
22420   while ( p!=dep_head ) {
22421     if ( mp_interesting(mp, p) ) {
22422       mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22423       if ( type(p)==mp_dependent ) mp_print_char(mp, '=');
22424       else mp_print(mp, " = "); /* extra spaces imply proto-dependency */
22425       mp_print_dependency(mp, dep_list(p),type(p));
22426     }
22427     p=dep_list(p);
22428     while ( info(p)!=null ) p=link(p);
22429     p=link(p);
22430   }
22431   mp_get_x_next(mp);
22432 }
22433
22434 @ Finally we are ready for the procedure that governs all of the
22435 show commands.
22436
22437 @<Declare action procedures for use by |do_statement|@>=
22438 void mp_do_show_whatever (MP mp) ;
22439
22440 @ @c void mp_do_show_whatever (MP mp) { 
22441   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
22442   switch (mp->cur_mod) {
22443   case show_token_code:mp_do_show_token(mp); break;
22444   case show_stats_code:mp_do_show_stats(mp); break;
22445   case show_code:mp_do_show(mp); break;
22446   case show_var_code:mp_do_show_var(mp); break;
22447   case show_dependencies_code:mp_do_show_dependencies(mp); break;
22448   } /* there are no other cases */
22449   if ( mp->internal[mp_showstopping]>0 ){ 
22450     print_err("OK");
22451 @.OK@>
22452     if ( mp->interaction<mp_error_stop_mode ) { 
22453       help0; decr(mp->error_count);
22454     } else {
22455       help1("This isn't an error message; I'm just showing something.");
22456     }
22457     if ( mp->cur_cmd==semicolon ) mp_error(mp);
22458      else mp_put_get_error(mp);
22459   }
22460 }
22461
22462 @ The `\&{addto}' command needs the following additional primitives:
22463
22464 @d double_path_code 0 /* command modifier for `\&{doublepath}' */
22465 @d contour_code 1 /* command modifier for `\&{contour}' */
22466 @d also_code 2 /* command modifier for `\&{also}' */
22467
22468 @ Pre and postscripts need two new identifiers:
22469
22470 @d with_pre_script 11
22471 @d with_post_script 13
22472
22473 @<Put each...@>=
22474 mp_primitive(mp, "doublepath",thing_to_add,double_path_code);
22475 @:double_path_}{\&{doublepath} primitive@>
22476 mp_primitive(mp, "contour",thing_to_add,contour_code);
22477 @:contour_}{\&{contour} primitive@>
22478 mp_primitive(mp, "also",thing_to_add,also_code);
22479 @:also_}{\&{also} primitive@>
22480 mp_primitive(mp, "withpen",with_option,mp_pen_type);
22481 @:with_pen_}{\&{withpen} primitive@>
22482 mp_primitive(mp, "dashed",with_option,mp_picture_type);
22483 @:dashed_}{\&{dashed} primitive@>
22484 mp_primitive(mp, "withprescript",with_option,with_pre_script);
22485 @:with_pre_script_}{\&{withprescript} primitive@>
22486 mp_primitive(mp, "withpostscript",with_option,with_post_script);
22487 @:with_post_script_}{\&{withpostscript} primitive@>
22488 mp_primitive(mp, "withoutcolor",with_option,mp_no_model);
22489 @:with_color_}{\&{withoutcolor} primitive@>
22490 mp_primitive(mp, "withgreyscale",with_option,mp_grey_model);
22491 @:with_color_}{\&{withgreyscale} primitive@>
22492 mp_primitive(mp, "withcolor",with_option,mp_uninitialized_model);
22493 @:with_color_}{\&{withcolor} primitive@>
22494 /*  \&{withrgbcolor} is an alias for \&{withcolor} */
22495 mp_primitive(mp, "withrgbcolor",with_option,mp_rgb_model);
22496 @:with_color_}{\&{withrgbcolor} primitive@>
22497 mp_primitive(mp, "withcmykcolor",with_option,mp_cmyk_model);
22498 @:with_color_}{\&{withcmykcolor} primitive@>
22499
22500 @ @<Cases of |print_cmd...@>=
22501 case thing_to_add:
22502   if ( m==contour_code ) mp_print(mp, "contour");
22503   else if ( m==double_path_code ) mp_print(mp, "doublepath");
22504   else mp_print(mp, "also");
22505   break;
22506 case with_option:
22507   if ( m==mp_pen_type ) mp_print(mp, "withpen");
22508   else if ( m==with_pre_script ) mp_print(mp, "withprescript");
22509   else if ( m==with_post_script ) mp_print(mp, "withpostscript");
22510   else if ( m==mp_no_model ) mp_print(mp, "withoutcolor");
22511   else if ( m==mp_rgb_model ) mp_print(mp, "withrgbcolor");
22512   else if ( m==mp_uninitialized_model ) mp_print(mp, "withcolor");
22513   else if ( m==mp_cmyk_model ) mp_print(mp, "withcmykcolor");
22514   else if ( m==mp_grey_model ) mp_print(mp, "withgreyscale");
22515   else mp_print(mp, "dashed");
22516   break;
22517
22518 @ The |scan_with_list| procedure parses a $\langle$with list$\rangle$ and
22519 updates the list of graphical objects starting at |p|.  Each $\langle$with
22520 clause$\rangle$ updates all graphical objects whose |type| is compatible.
22521 Other objects are ignored.
22522
22523 @<Declare action procedures for use by |do_statement|@>=
22524 void mp_scan_with_list (MP mp,pointer p) ;
22525
22526 @ @c void mp_scan_with_list (MP mp,pointer p) {
22527   small_number t; /* |cur_mod| of the |with_option| (should match |cur_type|) */
22528   pointer q; /* for list manipulation */
22529   int old_setting; /* saved |selector| setting */
22530   pointer k; /* for finding the near-last item in a list  */
22531   str_number s; /* for string cleanup after combining  */
22532   pointer cp,pp,dp,ap,bp;
22533     /* objects being updated; |void| initially; |null| to suppress update */
22534   cp=mp_void; pp=mp_void; dp=mp_void; ap=mp_void; bp=mp_void;
22535   k=0;
22536   while ( mp->cur_cmd==with_option ){ 
22537     t=mp->cur_mod;
22538     mp_get_x_next(mp);
22539     if ( t!=mp_no_model ) mp_scan_expression(mp);
22540     if (((t==with_pre_script)&&(mp->cur_type!=mp_string_type))||
22541      ((t==with_post_script)&&(mp->cur_type!=mp_string_type))||
22542      ((t==mp_uninitialized_model)&&
22543         ((mp->cur_type!=mp_cmykcolor_type)&&(mp->cur_type!=mp_color_type)
22544           &&(mp->cur_type!=mp_known)&&(mp->cur_type!=mp_boolean_type)))||
22545      ((t==mp_cmyk_model)&&(mp->cur_type!=mp_cmykcolor_type))||
22546      ((t==mp_rgb_model)&&(mp->cur_type!=mp_color_type))||
22547      ((t==mp_grey_model)&&(mp->cur_type!=mp_known))||
22548      ((t==mp_pen_type)&&(mp->cur_type!=t))||
22549      ((t==mp_picture_type)&&(mp->cur_type!=t)) ) {
22550       @<Complain about improper type@>;
22551     } else if ( t==mp_uninitialized_model ) {
22552       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22553       if ( cp!=null )
22554         @<Transfer a color from the current expression to object~|cp|@>;
22555       mp_flush_cur_exp(mp, 0);
22556     } else if ( t==mp_rgb_model ) {
22557       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22558       if ( cp!=null )
22559         @<Transfer a rgbcolor from the current expression to object~|cp|@>;
22560       mp_flush_cur_exp(mp, 0);
22561     } else if ( t==mp_cmyk_model ) {
22562       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22563       if ( cp!=null )
22564         @<Transfer a cmykcolor from the current expression to object~|cp|@>;
22565       mp_flush_cur_exp(mp, 0);
22566     } else if ( t==mp_grey_model ) {
22567       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22568       if ( cp!=null )
22569         @<Transfer a greyscale from the current expression to object~|cp|@>;
22570       mp_flush_cur_exp(mp, 0);
22571     } else if ( t==mp_no_model ) {
22572       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22573       if ( cp!=null )
22574         @<Transfer a noncolor from the current expression to object~|cp|@>;
22575     } else if ( t==mp_pen_type ) {
22576       if ( pp==mp_void ) @<Make |pp| an object in list~|p| that needs a pen@>;
22577       if ( pp!=null ) {
22578         if ( pen_p(pp)!=null ) mp_toss_knot_list(mp, pen_p(pp));
22579         pen_p(pp)=mp->cur_exp; mp->cur_type=mp_vacuous;
22580       }
22581     } else if ( t==with_pre_script ) {
22582       if ( ap==mp_void )
22583         ap=p;
22584       while ( (ap!=null)&&(! has_color(ap)) )
22585          ap=link(ap);
22586       if ( ap!=null ) {
22587         if ( pre_script(ap)!=null ) { /*  build a new,combined string  */
22588           s=pre_script(ap);
22589           old_setting=mp->selector;
22590               mp->selector=new_string;
22591           str_room(length(pre_script(ap))+length(mp->cur_exp)+2);
22592               mp_print_str(mp, mp->cur_exp);
22593           append_char(13);  /* a forced \ps\ newline  */
22594           mp_print_str(mp, pre_script(ap));
22595           pre_script(ap)=mp_make_string(mp);
22596           delete_str_ref(s);
22597           mp->selector=old_setting;
22598         } else {
22599           pre_script(ap)=mp->cur_exp;
22600         }
22601         mp->cur_type=mp_vacuous;
22602       }
22603     } else if ( t==with_post_script ) {
22604       if ( bp==mp_void )
22605         k=p; 
22606       bp=k;
22607       while ( link(k)!=null ) {
22608         k=link(k);
22609         if ( has_color(k) ) bp=k;
22610       }
22611       if ( bp!=null ) {
22612          if ( post_script(bp)!=null ) {
22613            s=post_script(bp);
22614            old_setting=mp->selector;
22615                mp->selector=new_string;
22616            str_room(length(post_script(bp))+length(mp->cur_exp)+2);
22617            mp_print_str(mp, post_script(bp));
22618            append_char(13); /* a forced \ps\ newline  */
22619            mp_print_str(mp, mp->cur_exp);
22620            post_script(bp)=mp_make_string(mp);
22621            delete_str_ref(s);
22622            mp->selector=old_setting;
22623          } else {
22624            post_script(bp)=mp->cur_exp;
22625          }
22626          mp->cur_type=mp_vacuous;
22627        }
22628     } else { 
22629       if ( dp==mp_void ) {
22630         @<Make |dp| a stroked node in list~|p|@>;
22631       }
22632       if ( dp!=null ) {
22633         if ( dash_p(dp)!=null ) delete_edge_ref(dash_p(dp));
22634         dash_p(dp)=mp_make_dashes(mp, mp->cur_exp);
22635         dash_scale(dp)=unity;
22636         mp->cur_type=mp_vacuous;
22637       }
22638     }
22639   }
22640   @<Copy the information from objects |cp|, |pp|, and |dp| into the rest
22641     of the list@>;
22642 };
22643
22644 @ @<Complain about improper type@>=
22645 { exp_err("Improper type");
22646 @.Improper type@>
22647 help2("Next time say `withpen <known pen expression>';")
22648   ("I'll ignore the bad `with' clause and look for another.");
22649 if ( t==with_pre_script )
22650   mp->help_line[1]="Next time say `withprescript <known string expression>';";
22651 else if ( t==with_post_script )
22652   mp->help_line[1]="Next time say `withpostscript <known string expression>';";
22653 else if ( t==mp_picture_type )
22654   mp->help_line[1]="Next time say `dashed <known picture expression>';";
22655 else if ( t==mp_uninitialized_model )
22656   mp->help_line[1]="Next time say `withcolor <known color expression>';";
22657 else if ( t==mp_rgb_model )
22658   mp->help_line[1]="Next time say `withrgbcolor <known color expression>';";
22659 else if ( t==mp_cmyk_model )
22660   mp->help_line[1]="Next time say `withcmykcolor <known cmykcolor expression>';";
22661 else if ( t==mp_grey_model )
22662   mp->help_line[1]="Next time say `withgreyscale <known numeric expression>';";;
22663 mp_put_get_flush_error(mp, 0);
22664 }
22665
22666 @ Forcing the color to be between |0| and |unity| here guarantees that no
22667 picture will ever contain a color outside the legal range for \ps\ graphics.
22668
22669 @<Transfer a color from the current expression to object~|cp|@>=
22670 { if ( mp->cur_type==mp_color_type )
22671    @<Transfer a rgbcolor from the current expression to object~|cp|@>
22672 else if ( mp->cur_type==mp_cmykcolor_type )
22673    @<Transfer a cmykcolor from the current expression to object~|cp|@>
22674 else if ( mp->cur_type==mp_known )
22675    @<Transfer a greyscale from the current expression to object~|cp|@>
22676 else if ( mp->cur_exp==false_code )
22677    @<Transfer a noncolor from the current expression to object~|cp|@>;
22678 }
22679
22680 @ @<Transfer a rgbcolor from the current expression to object~|cp|@>=
22681 { q=value(mp->cur_exp);
22682 cyan_val(cp)=0;
22683 magenta_val(cp)=0;
22684 yellow_val(cp)=0;
22685 black_val(cp)=0;
22686 red_val(cp)=value(red_part_loc(q));
22687 green_val(cp)=value(green_part_loc(q));
22688 blue_val(cp)=value(blue_part_loc(q));
22689 color_model(cp)=mp_rgb_model;
22690 if ( red_val(cp)<0 ) red_val(cp)=0;
22691 if ( green_val(cp)<0 ) green_val(cp)=0;
22692 if ( blue_val(cp)<0 ) blue_val(cp)=0;
22693 if ( red_val(cp)>unity ) red_val(cp)=unity;
22694 if ( green_val(cp)>unity ) green_val(cp)=unity;
22695 if ( blue_val(cp)>unity ) blue_val(cp)=unity;
22696 }
22697
22698 @ @<Transfer a cmykcolor from the current expression to object~|cp|@>=
22699 { q=value(mp->cur_exp);
22700 cyan_val(cp)=value(cyan_part_loc(q));
22701 magenta_val(cp)=value(magenta_part_loc(q));
22702 yellow_val(cp)=value(yellow_part_loc(q));
22703 black_val(cp)=value(black_part_loc(q));
22704 color_model(cp)=mp_cmyk_model;
22705 if ( cyan_val(cp)<0 ) cyan_val(cp)=0;
22706 if ( magenta_val(cp)<0 ) magenta_val(cp)=0;
22707 if ( yellow_val(cp)<0 ) yellow_val(cp)=0;
22708 if ( black_val(cp)<0 ) black_val(cp)=0;
22709 if ( cyan_val(cp)>unity ) cyan_val(cp)=unity;
22710 if ( magenta_val(cp)>unity ) magenta_val(cp)=unity;
22711 if ( yellow_val(cp)>unity ) yellow_val(cp)=unity;
22712 if ( black_val(cp)>unity ) black_val(cp)=unity;
22713 }
22714
22715 @ @<Transfer a greyscale from the current expression to object~|cp|@>=
22716 { q=mp->cur_exp;
22717 cyan_val(cp)=0;
22718 magenta_val(cp)=0;
22719 yellow_val(cp)=0;
22720 black_val(cp)=0;
22721 grey_val(cp)=q;
22722 color_model(cp)=mp_grey_model;
22723 if ( grey_val(cp)<0 ) grey_val(cp)=0;
22724 if ( grey_val(cp)>unity ) grey_val(cp)=unity;
22725 }
22726
22727 @ @<Transfer a noncolor from the current expression to object~|cp|@>=
22728 {
22729 cyan_val(cp)=0;
22730 magenta_val(cp)=0;
22731 yellow_val(cp)=0;
22732 black_val(cp)=0;
22733 grey_val(cp)=0;
22734 color_model(cp)=mp_no_model;
22735 }
22736
22737 @ @<Make |cp| a colored object in object list~|p|@>=
22738 { cp=p;
22739   while ( cp!=null ){ 
22740     if ( has_color(cp) ) break;
22741     cp=link(cp);
22742   }
22743 }
22744
22745 @ @<Make |pp| an object in list~|p| that needs a pen@>=
22746 { pp=p;
22747   while ( pp!=null ) {
22748     if ( has_pen(pp) ) break;
22749     pp=link(pp);
22750   }
22751 }
22752
22753 @ @<Make |dp| a stroked node in list~|p|@>=
22754 { dp=p;
22755   while ( dp!=null ) {
22756     if ( type(dp)==mp_stroked_code ) break;
22757     dp=link(dp);
22758   }
22759 }
22760
22761 @ @<Copy the information from objects |cp|, |pp|, and |dp| into...@>=
22762 @<Copy |cp|'s color into the colored objects linked to~|cp|@>;
22763 if ( pp>mp_void ) {
22764   @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>;
22765 }
22766 if ( dp>mp_void ) {
22767   @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>;
22768 }
22769
22770
22771 @ @<Copy |cp|'s color into the colored objects linked to~|cp|@>=
22772 { q=link(cp);
22773   while ( q!=null ) { 
22774     if ( has_color(q) ) {
22775       red_val(q)=red_val(cp);
22776       green_val(q)=green_val(cp);
22777       blue_val(q)=blue_val(cp);
22778       black_val(q)=black_val(cp);
22779       color_model(q)=color_model(cp);
22780     }
22781     q=link(q);
22782   }
22783 }
22784
22785 @ @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>=
22786 { q=link(pp);
22787   while ( q!=null ) {
22788     if ( has_pen(q) ) {
22789       if ( pen_p(q)!=null ) mp_toss_knot_list(mp, pen_p(q));
22790       pen_p(q)=copy_pen(pen_p(pp));
22791     }
22792     q=link(q);
22793   }
22794 }
22795
22796 @ @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>=
22797 { q=link(dp);
22798   while ( q!=null ) {
22799     if ( type(q)==mp_stroked_code ) {
22800       if ( dash_p(q)!=null ) delete_edge_ref(dash_p(q));
22801       dash_p(q)=dash_p(dp);
22802       dash_scale(q)=unity;
22803       if ( dash_p(q)!=null ) add_edge_ref(dash_p(q));
22804     }
22805     q=link(q);
22806   }
22807 }
22808
22809 @ One of the things we need to do when we've parsed an \&{addto} or
22810 similar command is find the header of a supposed \&{picture} variable, given
22811 a token list for that variable.  Since the edge structure is about to be
22812 updated, we use |private_edges| to make sure that this is possible.
22813
22814 @<Declare action procedures for use by |do_statement|@>=
22815 pointer mp_find_edges_var (MP mp, pointer t) ;
22816
22817 @ @c pointer mp_find_edges_var (MP mp, pointer t) {
22818   pointer p;
22819   pointer cur_edges; /* the return value */
22820   p=mp_find_variable(mp, t); cur_edges=null;
22821   if ( p==null ) { 
22822     mp_obliterated(mp, t); mp_put_get_error(mp);
22823   } else if ( type(p)!=mp_picture_type )  { 
22824     print_err("Variable "); mp_show_token_list(mp, t,null,1000,0);
22825 @.Variable x is the wrong type@>
22826     mp_print(mp, " is the wrong type ("); 
22827     mp_print_type(mp, type(p)); mp_print_char(mp, ')');
22828     help2("I was looking for a \"known\" picture variable.")
22829          ("So I'll not change anything just now."); 
22830     mp_put_get_error(mp);
22831   } else { 
22832     value(p)=mp_private_edges(mp, value(p));
22833     cur_edges=value(p);
22834   }
22835   mp_flush_node_list(mp, t);
22836   return cur_edges;
22837 };
22838
22839 @ @<Cases of |do_statement|...@>=
22840 case add_to_command: mp_do_add_to(mp); break;
22841 case bounds_command:mp_do_bounds(mp); break;
22842
22843 @ @<Put each...@>=
22844 mp_primitive(mp, "clip",bounds_command,mp_start_clip_code);
22845 @:clip_}{\&{clip} primitive@>
22846 mp_primitive(mp, "setbounds",bounds_command,mp_start_bounds_code);
22847 @:set_bounds_}{\&{setbounds} primitive@>
22848
22849 @ @<Cases of |print_cmd...@>=
22850 case bounds_command: 
22851   if ( m==mp_start_clip_code ) mp_print(mp, "clip");
22852   else mp_print(mp, "setbounds");
22853   break;
22854
22855 @ The following function parses the beginning of an \&{addto} or \&{clip}
22856 command: it expects a variable name followed by a token with |cur_cmd=sep|
22857 and then an expression.  The function returns the token list for the variable
22858 and stores the command modifier for the separator token in the global variable
22859 |last_add_type|.  We must be careful because this variable might get overwritten
22860 any time we call |get_x_next|.
22861
22862 @<Glob...@>=
22863 quarterword last_add_type;
22864   /* command modifier that identifies the last \&{addto} command */
22865
22866 @ @<Declare action procedures for use by |do_statement|@>=
22867 pointer mp_start_draw_cmd (MP mp,quarterword sep) ;
22868
22869 @ @c pointer mp_start_draw_cmd (MP mp,quarterword sep) {
22870   pointer lhv; /* variable to add to left */
22871   quarterword add_type=0; /* value to be returned in |last_add_type| */
22872   lhv=null;
22873   mp_get_x_next(mp); mp->var_flag=sep; mp_scan_primary(mp);
22874   if ( mp->cur_type!=mp_token_list ) {
22875     @<Abandon edges command because there's no variable@>;
22876   } else  { 
22877     lhv=mp->cur_exp; add_type=mp->cur_mod;
22878     mp->cur_type=mp_vacuous; mp_get_x_next(mp); mp_scan_expression(mp);
22879   }
22880   mp->last_add_type=add_type;
22881   return lhv;
22882 }
22883
22884 @ @<Abandon edges command because there's no variable@>=
22885 { exp_err("Not a suitable variable");
22886 @.Not a suitable variable@>
22887   help4("At this point I needed to see the name of a picture variable.")
22888     ("(Or perhaps you have indeed presented me with one; I might")
22889     ("have missed it, if it wasn't followed by the proper token.)")
22890     ("So I'll not change anything just now.");
22891   mp_put_get_flush_error(mp, 0);
22892 }
22893
22894 @ Here is an example of how to use |start_draw_cmd|.
22895
22896 @<Declare action procedures for use by |do_statement|@>=
22897 void mp_do_bounds (MP mp) ;
22898
22899 @ @c void mp_do_bounds (MP mp) {
22900   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22901   pointer p; /* for list manipulation */
22902   integer m; /* initial value of |cur_mod| */
22903   m=mp->cur_mod;
22904   lhv=mp_start_draw_cmd(mp, to_token);
22905   if ( lhv!=null ) {
22906     lhe=mp_find_edges_var(mp, lhv);
22907     if ( lhe==null ) {
22908       mp_flush_cur_exp(mp, 0);
22909     } else if ( mp->cur_type!=mp_path_type ) {
22910       exp_err("Improper `clip'");
22911 @.Improper `addto'@>
22912       help2("This expression should have specified a known path.")
22913         ("So I'll not change anything just now."); 
22914       mp_put_get_flush_error(mp, 0);
22915     } else if ( left_type(mp->cur_exp)==mp_endpoint ) {
22916       @<Complain about a non-cycle@>;
22917     } else {
22918       @<Make |cur_exp| into a \&{setbounds} or clipping path and add it to |lhe|@>;
22919     }
22920   }
22921 }
22922
22923 @ @<Complain about a non-cycle@>=
22924 { print_err("Not a cycle");
22925 @.Not a cycle@>
22926   help2("That contour should have ended with `..cycle' or `&cycle'.")
22927     ("So I'll not change anything just now."); mp_put_get_error(mp);
22928 }
22929
22930 @ @<Make |cur_exp| into a \&{setbounds} or clipping path and add...@>=
22931 { p=mp_new_bounds_node(mp, mp->cur_exp,m);
22932   link(p)=link(dummy_loc(lhe));
22933   link(dummy_loc(lhe))=p;
22934   if ( obj_tail(lhe)==dummy_loc(lhe) ) obj_tail(lhe)=p;
22935   p=mp_get_node(mp, mp->gr_object_size[stop_type(m)]);
22936   type(p)=stop_type(m);
22937   link(obj_tail(lhe))=p;
22938   obj_tail(lhe)=p;
22939   mp_init_bbox(mp, lhe);
22940 }
22941
22942 @ The |do_add_to| procedure is a little like |do_clip| but there are a lot more
22943 cases to deal with.
22944
22945 @<Declare action procedures for use by |do_statement|@>=
22946 void mp_do_add_to (MP mp) ;
22947
22948 @ @c void mp_do_add_to (MP mp) {
22949   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22950   pointer p; /* the graphical object or list for |scan_with_list| to update */
22951   pointer e; /* an edge structure to be merged */
22952   quarterword add_type; /* |also_code|, |contour_code|, or |double_path_code| */
22953   lhv=mp_start_draw_cmd(mp, thing_to_add); add_type=mp->last_add_type;
22954   if ( lhv!=null ) {
22955     if ( add_type==also_code ) {
22956       @<Make sure the current expression is a suitable picture and set |e| and |p|
22957        appropriately@>;
22958     } else {
22959       @<Create a graphical object |p| based on |add_type| and the current
22960         expression@>;
22961     }
22962     mp_scan_with_list(mp, p);
22963     @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>;
22964   }
22965 }
22966
22967 @ Setting |p:=null| causes the $\langle$with list$\rangle$ to be ignored;
22968 setting |e:=null| prevents anything from being added to |lhe|.
22969
22970 @ @<Make sure the current expression is a suitable picture and set |e|...@>=
22971
22972   p=null; e=null;
22973   if ( mp->cur_type!=mp_picture_type ) {
22974     exp_err("Improper `addto'");
22975 @.Improper `addto'@>
22976     help2("This expression should have specified a known picture.")
22977       ("So I'll not change anything just now."); mp_put_get_flush_error(mp, 0);
22978   } else { 
22979     e=mp_private_edges(mp, mp->cur_exp); mp->cur_type=mp_vacuous;
22980     p=link(dummy_loc(e));
22981   }
22982 }
22983
22984 @ In this case |add_type<>also_code| so setting |p:=null| suppresses future
22985 attempts to add to the edge structure.
22986
22987 @<Create a graphical object |p| based on |add_type| and the current...@>=
22988 { e=null; p=null;
22989   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
22990   if ( mp->cur_type!=mp_path_type ) {
22991     exp_err("Improper `addto'");
22992 @.Improper `addto'@>
22993     help2("This expression should have specified a known path.")
22994       ("So I'll not change anything just now."); 
22995     mp_put_get_flush_error(mp, 0);
22996   } else if ( add_type==contour_code ) {
22997     if ( left_type(mp->cur_exp)==mp_endpoint ) {
22998       @<Complain about a non-cycle@>;
22999     } else { 
23000       p=mp_new_fill_node(mp, mp->cur_exp);
23001       mp->cur_type=mp_vacuous;
23002     }
23003   } else { 
23004     p=mp_new_stroked_node(mp, mp->cur_exp);
23005     mp->cur_type=mp_vacuous;
23006   }
23007 }
23008
23009 @ @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>=
23010 lhe=mp_find_edges_var(mp, lhv);
23011 if ( lhe==null ) {
23012   if ( (e==null)&&(p!=null) ) e=mp_toss_gr_object(mp, p);
23013   if ( e!=null ) delete_edge_ref(e);
23014 } else if ( add_type==also_code ) {
23015   if ( e!=null ) {
23016     @<Merge |e| into |lhe| and delete |e|@>;
23017   } else { 
23018     do_nothing;
23019   }
23020 } else if ( p!=null ) {
23021   link(obj_tail(lhe))=p;
23022   obj_tail(lhe)=p;
23023   if ( add_type==double_path_code )
23024     if ( pen_p(p)==null ) 
23025       pen_p(p)=mp_get_pen_circle(mp, 0);
23026 }
23027
23028 @ @<Merge |e| into |lhe| and delete |e|@>=
23029 { if ( link(dummy_loc(e))!=null ) {
23030     link(obj_tail(lhe))=link(dummy_loc(e));
23031     obj_tail(lhe)=obj_tail(e);
23032     obj_tail(e)=dummy_loc(e);
23033     link(dummy_loc(e))=null;
23034     mp_flush_dash_list(mp, lhe);
23035   }
23036   mp_toss_edges(mp, e);
23037 }
23038
23039 @ @<Cases of |do_statement|...@>=
23040 case ship_out_command: mp_do_ship_out(mp); break;
23041
23042 @ @<Declare action procedures for use by |do_statement|@>=
23043 @<Declare the function called |tfm_check|@>;
23044 @<Declare the \ps\ output procedures@>;
23045 void mp_do_ship_out (MP mp) ;
23046
23047 @ @c void mp_do_ship_out (MP mp) {
23048   integer c; /* the character code */
23049   mp_get_x_next(mp); mp_scan_expression(mp);
23050   if ( mp->cur_type!=mp_picture_type ) {
23051     @<Complain that it's not a known picture@>;
23052   } else { 
23053     c=mp_round_unscaled(mp, mp->internal[mp_char_code]) % 256;
23054     if ( c<0 ) c=c+256;
23055     @<Store the width information for character code~|c|@>;
23056     mp_ship_out(mp, mp->cur_exp);
23057     mp_flush_cur_exp(mp, 0);
23058   }
23059 }
23060
23061 @ @<Complain that it's not a known picture@>=
23062
23063   exp_err("Not a known picture");
23064   help1("I can only output known pictures.");
23065   mp_put_get_flush_error(mp, 0);
23066 }
23067
23068 @ The \&{everyjob} command simply assigns a nonzero value to the global variable
23069 |start_sym|.
23070
23071 @<Cases of |do_statement|...@>=
23072 case every_job_command: 
23073   mp_get_symbol(mp); mp->start_sym=mp->cur_sym; mp_get_x_next(mp);
23074   break;
23075
23076 @ @<Glob...@>=
23077 halfword start_sym; /* a symbolic token to insert at beginning of job */
23078
23079 @ @<Set init...@>=
23080 mp->start_sym=0;
23081
23082 @ Finally, we have only the ``message'' commands remaining.
23083
23084 @d message_code 0
23085 @d err_message_code 1
23086 @d err_help_code 2
23087 @d filename_template_code 3
23088 @d print_with_leading_zeroes(A)  g = mp->pool_ptr;
23089               mp_print_int(mp, (A)); g = mp->pool_ptr-g;
23090               if ( f>g ) {
23091                 mp->pool_ptr = mp->pool_ptr - g;
23092                 while ( f>g ) {
23093                   mp_print_char(mp, '0');
23094                   decr(f);
23095                   };
23096                 mp_print_int(mp, (A));
23097               };
23098               f = 0
23099
23100 @<Put each...@>=
23101 mp_primitive(mp, "message",message_command,message_code);
23102 @:message_}{\&{message} primitive@>
23103 mp_primitive(mp, "errmessage",message_command,err_message_code);
23104 @:err_message_}{\&{errmessage} primitive@>
23105 mp_primitive(mp, "errhelp",message_command,err_help_code);
23106 @:err_help_}{\&{errhelp} primitive@>
23107 mp_primitive(mp, "filenametemplate",message_command,filename_template_code);
23108 @:filename_template_}{\&{filenametemplate} primitive@>
23109
23110 @ @<Cases of |print_cmd...@>=
23111 case message_command: 
23112   if ( m<err_message_code ) mp_print(mp, "message");
23113   else if ( m==err_message_code ) mp_print(mp, "errmessage");
23114   else if ( m==filename_template_code ) mp_print(mp, "filenametemplate");
23115   else mp_print(mp, "errhelp");
23116   break;
23117
23118 @ @<Cases of |do_statement|...@>=
23119 case message_command: mp_do_message(mp); break;
23120
23121 @ @<Declare action procedures for use by |do_statement|@>=
23122 @<Declare a procedure called |no_string_err|@>;
23123 void mp_do_message (MP mp) ;
23124
23125
23126 @c void mp_do_message (MP mp) {
23127   int m; /* the type of message */
23128   m=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
23129   if ( mp->cur_type!=mp_string_type )
23130     mp_no_string_err(mp, "A message should be a known string expression.");
23131   else {
23132     switch (m) {
23133     case message_code: 
23134       mp_print_nl(mp, ""); mp_print_str(mp, mp->cur_exp);
23135       break;
23136     case err_message_code:
23137       @<Print string |cur_exp| as an error message@>;
23138       break;
23139     case err_help_code:
23140       @<Save string |cur_exp| as the |err_help|@>;
23141       break;
23142     case filename_template_code:
23143       @<Save the filename template@>;
23144       break;
23145     } /* there are no other cases */
23146   }
23147   mp_flush_cur_exp(mp, 0);
23148 }
23149
23150 @ @<Declare a procedure called |no_string_err|@>=
23151 void mp_no_string_err (MP mp,char *s) { 
23152    exp_err("Not a string");
23153 @.Not a string@>
23154   help1(s);
23155   mp_put_get_error(mp);
23156 }
23157
23158 @ The global variable |err_help| is zero when the user has most recently
23159 given an empty help string, or if none has ever been given.
23160
23161 @<Save string |cur_exp| as the |err_help|@>=
23162
23163   if ( mp->err_help!=0 ) delete_str_ref(mp->err_help);
23164   if ( length(mp->cur_exp)==0 ) mp->err_help=0;
23165   else  { mp->err_help=mp->cur_exp; add_str_ref(mp->err_help); }
23166 }
23167
23168 @ If \&{errmessage} occurs often in |mp_scroll_mode|, without user-defined
23169 \&{errhelp}, we don't want to give a long help message each time. So we
23170 give a verbose explanation only once.
23171
23172 @<Glob...@>=
23173 boolean long_help_seen; /* has the long \.{\\errmessage} help been used? */
23174
23175 @ @<Set init...@>=mp->long_help_seen=false;
23176
23177 @ @<Print string |cur_exp| as an error message@>=
23178
23179   print_err(""); mp_print_str(mp, mp->cur_exp);
23180   if ( mp->err_help!=0 ) {
23181     mp->use_err_help=true;
23182   } else if ( mp->long_help_seen ) { 
23183     help1("(That was another `errmessage'.)") ; 
23184   } else  { 
23185    if ( mp->interaction<mp_error_stop_mode ) mp->long_help_seen=true;
23186     help4("This error message was generated by an `errmessage'")
23187      ("command, so I can\'t give any explicit help.")
23188      ("Pretend that you're Miss Marple: Examine all clues,")
23189 @^Marple, Jane@>
23190      ("and deduce the truth by inspired guesses.");
23191   }
23192   mp_put_get_error(mp); mp->use_err_help=false;
23193 }
23194
23195 @ @<Cases of |do_statement|...@>=
23196 case write_command: mp_do_write(mp); break;
23197
23198 @ @<Declare action procedures for use by |do_statement|@>=
23199 void mp_do_write (MP mp) ;
23200
23201 @ @c void mp_do_write (MP mp) {
23202   str_number t; /* the line of text to be written */
23203   write_index n,n0; /* for searching |wr_fname| and |wr_file| arrays */
23204   int old_setting; /* for saving |selector| during output */
23205   mp_get_x_next(mp);
23206   mp_scan_expression(mp);
23207   if ( mp->cur_type!=mp_string_type ) {
23208     mp_no_string_err(mp, "The text to be written should be a known string expression");
23209   } else if ( mp->cur_cmd!=to_token ) { 
23210     print_err("Missing `to' clause");
23211     help1("A write command should end with `to <filename>'");
23212     mp_put_get_error(mp);
23213   } else { 
23214     t=mp->cur_exp; mp->cur_type=mp_vacuous;
23215     mp_get_x_next(mp);
23216     mp_scan_expression(mp);
23217     if ( mp->cur_type!=mp_string_type )
23218       mp_no_string_err(mp, "I can\'t write to that file name.  It isn't a known string");
23219     else {
23220       @<Write |t| to the file named by |cur_exp|@>;
23221     }
23222     delete_str_ref(t);
23223   }
23224   mp_flush_cur_exp(mp, 0);
23225 }
23226
23227 @ @<Write |t| to the file named by |cur_exp|@>=
23228
23229   @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if
23230     |cur_exp| must be inserted@>;
23231   if ( mp_str_vs_str(mp, t,mp->eof_line)==0 ) {
23232     @<Record the end of file on |wr_file[n]|@>;
23233   } else { 
23234     old_setting=mp->selector;
23235     mp->selector=n+write_file;
23236     mp_print_str(mp, t); mp_print_ln(mp);
23237     mp->selector = old_setting;
23238   }
23239 }
23240
23241 @ @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if...@>=
23242 {
23243   char *fn = str(mp->cur_exp);
23244   n=mp->write_files;
23245   n0=mp->write_files;
23246   while (mp_xstrcmp(fn,mp->wr_fname[n])!=0) { 
23247     if ( n==0 ) { /* bottom reached */
23248           if ( n0==mp->write_files ) {
23249         if ( mp->write_files<mp->max_write_files ) {
23250           incr(mp->write_files);
23251         } else {
23252           void **wr_file;
23253           char **wr_fname;
23254               write_index l,k;
23255           l = mp->max_write_files + (mp->max_write_files>>2);
23256           wr_file = xmalloc((l+1),sizeof(void *));
23257           wr_fname = xmalloc((l+1),sizeof(char *));
23258               for (k=0;k<=l;k++) {
23259             if (k<=mp->max_write_files) {
23260                   wr_file[k]=mp->wr_file[k]; 
23261               wr_fname[k]=mp->wr_fname[k];
23262             } else {
23263                   wr_file[k]=0; 
23264               wr_fname[k]=NULL;
23265             }
23266           }
23267               xfree(mp->wr_file); xfree(mp->wr_fname);
23268           mp->max_write_files = l;
23269           mp->wr_file = wr_file;
23270           mp->wr_fname = wr_fname;
23271         }
23272       }
23273       n=n0;
23274       mp_open_write_file(mp, fn ,n);
23275     } else { 
23276       decr(n);
23277           if ( mp->wr_fname[n]==NULL )  n0=n; 
23278     }
23279   }
23280 }
23281
23282 @ @<Record the end of file on |wr_file[n]|@>=
23283 { (mp->close_file)(mp->wr_file[n]);
23284   xfree(mp->wr_fname[n]);
23285   mp->wr_fname[n]=NULL;
23286   if ( n==mp->write_files-1 ) mp->write_files=n;
23287 }
23288
23289
23290 @* \[42] Writing font metric data.
23291 \TeX\ gets its knowledge about fonts from font metric files, also called
23292 \.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
23293 but other programs know about them too. One of \MP's duties is to
23294 write \.{TFM} files so that the user's fonts can readily be
23295 applied to typesetting.
23296 @:TFM files}{\.{TFM} files@>
23297 @^font metric files@>
23298
23299 The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
23300 Since the number of bytes is always a multiple of~4, we could
23301 also regard the file as a sequence of 32-bit words, but \MP\ uses the
23302 byte interpretation. The format of \.{TFM} files was designed by
23303 Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
23304 @^Ramshaw, Lyle Harold@>
23305 of information in a compact but useful form.
23306
23307 @<Glob...@>=
23308 void * tfm_file; /* the font metric output goes here */
23309 char * metric_file_name; /* full name of the font metric file */
23310
23311 @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
23312 integers that give the lengths of the various subsequent portions
23313 of the file. These twelve integers are, in order:
23314 $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
23315 |lf|&length of the entire file, in words;\cr
23316 |lh|&length of the header data, in words;\cr
23317 |bc|&smallest character code in the font;\cr
23318 |ec|&largest character code in the font;\cr
23319 |nw|&number of words in the width table;\cr
23320 |nh|&number of words in the height table;\cr
23321 |nd|&number of words in the depth table;\cr
23322 |ni|&number of words in the italic correction table;\cr
23323 |nl|&number of words in the lig/kern table;\cr
23324 |nk|&number of words in the kern table;\cr
23325 |ne|&number of words in the extensible character table;\cr
23326 |np|&number of font parameter words.\cr}}$$
23327 They are all nonnegative and less than $2^{15}$. We must have |bc-1<=ec<=255|,
23328 |ne<=256|, and
23329 $$\hbox{|lf=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
23330 Note that a font may contain as many as 256 characters (if |bc=0| and |ec=255|),
23331 and as few as 0 characters (if |bc=ec+1|).
23332
23333 Incidentally, when two or more 8-bit bytes are combined to form an integer of
23334 16 or more bits, the most significant bytes appear first in the file.
23335 This is called BigEndian order.
23336 @^BigEndian order@>
23337
23338 @ The rest of the \.{TFM} file may be regarded as a sequence of ten data
23339 arrays.
23340
23341 The most important data type used here is a |fix_word|, which is
23342 a 32-bit representation of a binary fraction. A |fix_word| is a signed
23343 quantity, with the two's complement of the entire word used to represent
23344 negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
23345 binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
23346 the smallest is $-2048$. We will see below, however, that all but two of
23347 the |fix_word| values must lie between $-16$ and $+16$.
23348
23349 @ The first data array is a block of header information, which contains
23350 general facts about the font. The header must contain at least two words,
23351 |header[0]| and |header[1]|, whose meaning is explained below.  Additional
23352 header information of use to other software routines might also be
23353 included, and \MP\ will generate it if the \.{headerbyte} command occurs.
23354 For example, 16 more words of header information are in use at the Xerox
23355 Palo Alto Research Center; the first ten specify the character coding
23356 scheme used (e.g., `\.{XEROX TEXT}' or `\.{TEX MATHSY}'), the next five
23357 give the font family name (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
23358 last gives the ``face byte.''
23359
23360 \yskip\hang|header[0]| is a 32-bit check sum that \MP\ will copy into
23361 the \.{GF} output file. This helps ensure consistency between files,
23362 since \TeX\ records the check sums from the \.{TFM}'s it reads, and these
23363 should match the check sums on actual fonts that are used.  The actual
23364 relation between this check sum and the rest of the \.{TFM} file is not
23365 important; the check sum is simply an identification number with the
23366 property that incompatible fonts almost always have distinct check sums.
23367 @^check sum@>
23368
23369 \yskip\hang|header[1]| is a |fix_word| containing the design size of the
23370 font, in units of \TeX\ points. This number must be at least 1.0; it is
23371 fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
23372 font, i.e., a font that was designed to look best at a 10-point size,
23373 whatever that really means. When a \TeX\ user asks for a font `\.{at}
23374 $\delta$ \.{pt}', the effect is to override the design size and replace it
23375 by $\delta$, and to multiply the $x$ and~$y$ coordinates of the points in
23376 the font image by a factor of $\delta$ divided by the design size.  {\sl
23377 All other dimensions in the\/ \.{TFM} file are |fix_word|\kern-1pt\
23378 numbers in design-size units.} Thus, for example, the value of |param[6]|,
23379 which defines the \.{em} unit, is often the |fix_word| value $2^{20}=1.0$,
23380 since many fonts have a design size equal to one em.  The other dimensions
23381 must be less than 16 design-size units in absolute value; thus,
23382 |header[1]| and |param[1]| are the only |fix_word| entries in the whole
23383 \.{TFM} file whose first byte might be something besides 0 or 255.
23384
23385 @ Next comes the |char_info| array, which contains one |char_info_word|
23386 per character. Each word in this part of the file contains six fields
23387 packed into four bytes as follows.
23388
23389 \yskip\hang first byte: |width_index| (8 bits)\par
23390 \hang second byte: |height_index| (4 bits) times 16, plus |depth_index|
23391   (4~bits)\par
23392 \hang third byte: |italic_index| (6 bits) times 4, plus |tag|
23393   (2~bits)\par
23394 \hang fourth byte: |remainder| (8 bits)\par
23395 \yskip\noindent
23396 The actual width of a character is \\{width}|[width_index]|, in design-size
23397 units; this is a device for compressing information, since many characters
23398 have the same width. Since it is quite common for many characters
23399 to have the same height, depth, or italic correction, the \.{TFM} format
23400 imposes a limit of 16 different heights, 16 different depths, and
23401 64 different italic corrections.
23402
23403 Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
23404 \\{italic}[0]=0$ should always hold, so that an index of zero implies a
23405 value of zero.  The |width_index| should never be zero unless the
23406 character does not exist in the font, since a character is valid if and
23407 only if it lies between |bc| and |ec| and has a nonzero |width_index|.
23408
23409 @ The |tag| field in a |char_info_word| has four values that explain how to
23410 interpret the |remainder| field.
23411
23412 \yskip\hang|tag=0| (|no_tag|) means that |remainder| is unused.\par
23413 \hang|tag=1| (|lig_tag|) means that this character has a ligature/kerning
23414 program starting at location |remainder| in the |lig_kern| array.\par
23415 \hang|tag=2| (|list_tag|) means that this character is part of a chain of
23416 characters of ascending sizes, and not the largest in the chain.  The
23417 |remainder| field gives the character code of the next larger character.\par
23418 \hang|tag=3| (|ext_tag|) means that this character code represents an
23419 extensible character, i.e., a character that is built up of smaller pieces
23420 so that it can be made arbitrarily large. The pieces are specified in
23421 |exten[remainder]|.\par
23422 \yskip\noindent
23423 Characters with |tag=2| and |tag=3| are treated as characters with |tag=0|
23424 unless they are used in special circumstances in math formulas. For example,
23425 \TeX's \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
23426 operation looks for both |list_tag| and |ext_tag|.
23427
23428 @d no_tag 0 /* vanilla character */
23429 @d lig_tag 1 /* character has a ligature/kerning program */
23430 @d list_tag 2 /* character has a successor in a charlist */
23431 @d ext_tag 3 /* character is extensible */
23432
23433 @ The |lig_kern| array contains instructions in a simple programming language
23434 that explains what to do for special letter pairs. Each word in this array is a
23435 |lig_kern_command| of four bytes.
23436
23437 \yskip\hang first byte: |skip_byte|, indicates that this is the final program
23438   step if the byte is 128 or more, otherwise the next step is obtained by
23439   skipping this number of intervening steps.\par
23440 \hang second byte: |next_char|, ``if |next_char| follows the current character,
23441   then perform the operation and stop, otherwise continue.''\par
23442 \hang third byte: |op_byte|, indicates a ligature step if less than~128,
23443   a kern step otherwise.\par
23444 \hang fourth byte: |remainder|.\par
23445 \yskip\noindent
23446 In a kern step, an
23447 additional space equal to |kern[256*(op_byte-128)+remainder]| is inserted
23448 between the current character and |next_char|. This amount is
23449 often negative, so that the characters are brought closer together
23450 by kerning; but it might be positive.
23451
23452 There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
23453 $0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
23454 |remainder| is inserted between the current character and |next_char|;
23455 then the current character is deleted if $b=0$, and |next_char| is
23456 deleted if $c=0$; then we pass over $a$~characters to reach the next
23457 current character (which may have a ligature/kerning program of its own).
23458
23459 If the very first instruction of the |lig_kern| array has |skip_byte=255|,
23460 the |next_char| byte is the so-called right boundary character of this font;
23461 the value of |next_char| need not lie between |bc| and~|ec|.
23462 If the very last instruction of the |lig_kern| array has |skip_byte=255|,
23463 there is a special ligature/kerning program for a left boundary character,
23464 beginning at location |256*op_byte+remainder|.
23465 The interpretation is that \TeX\ puts implicit boundary characters
23466 before and after each consecutive string of characters from the same font.
23467 These implicit characters do not appear in the output, but they can affect
23468 ligatures and kerning.
23469
23470 If the very first instruction of a character's |lig_kern| program has
23471 |skip_byte>128|, the program actually begins in location
23472 |256*op_byte+remainder|. This feature allows access to large |lig_kern|
23473 arrays, because the first instruction must otherwise
23474 appear in a location |<=255|.
23475
23476 Any instruction with |skip_byte>128| in the |lig_kern| array must satisfy
23477 the condition
23478 $$\hbox{|256*op_byte+remainder<nl|.}$$
23479 If such an instruction is encountered during
23480 normal program execution, it denotes an unconditional halt; no ligature
23481 command is performed.
23482
23483 @d stop_flag (128)
23484   /* value indicating `\.{STOP}' in a lig/kern program */
23485 @d kern_flag (128) /* op code for a kern step */
23486 @d skip_byte(A) mp->lig_kern[(A)].b0
23487 @d next_char(A) mp->lig_kern[(A)].b1
23488 @d op_byte(A) mp->lig_kern[(A)].b2
23489 @d rem_byte(A) mp->lig_kern[(A)].b3
23490
23491 @ Extensible characters are specified by an |extensible_recipe|, which
23492 consists of four bytes called |top|, |mid|, |bot|, and |rep| (in this
23493 order). These bytes are the character codes of individual pieces used to
23494 build up a large symbol.  If |top|, |mid|, or |bot| are zero, they are not
23495 present in the built-up result. For example, an extensible vertical line is
23496 like an extensible bracket, except that the top and bottom pieces are missing.
23497
23498 Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
23499 if the piece isn't present. Then the extensible characters have the form
23500 $TR^kMR^kB$ from top to bottom, for some |k>=0|, unless $M$ is absent;
23501 in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
23502 The width of the extensible character is the width of $R$; and the
23503 height-plus-depth is the sum of the individual height-plus-depths of the
23504 components used, since the pieces are butted together in a vertical list.
23505
23506 @d ext_top(A) mp->exten[(A)].b0 /* |top| piece in a recipe */
23507 @d ext_mid(A) mp->exten[(A)].b1 /* |mid| piece in a recipe */
23508 @d ext_bot(A) mp->exten[(A)].b2 /* |bot| piece in a recipe */
23509 @d ext_rep(A) mp->exten[(A)].b3 /* |rep| piece in a recipe */
23510
23511 @ The final portion of a \.{TFM} file is the |param| array, which is another
23512 sequence of |fix_word| values.
23513
23514 \yskip\hang|param[1]=slant| is the amount of italic slant, which is used
23515 to help position accents. For example, |slant=.25| means that when you go
23516 up one unit, you also go .25 units to the right. The |slant| is a pure
23517 number; it is the only |fix_word| other than the design size itself that is
23518 not scaled by the design size.
23519
23520 \hang|param[2]=space| is the normal spacing between words in text.
23521 Note that character 040 in the font need not have anything to do with
23522 blank spaces.
23523
23524 \hang|param[3]=space_stretch| is the amount of glue stretching between words.
23525
23526 \hang|param[4]=space_shrink| is the amount of glue shrinking between words.
23527
23528 \hang|param[5]=x_height| is the size of one ex in the font; it is also
23529 the height of letters for which accents don't have to be raised or lowered.
23530
23531 \hang|param[6]=quad| is the size of one em in the font.
23532
23533 \hang|param[7]=extra_space| is the amount added to |param[2]| at the
23534 ends of sentences.
23535
23536 \yskip\noindent
23537 If fewer than seven parameters are present, \TeX\ sets the missing parameters
23538 to zero.
23539
23540 @d slant_code 1
23541 @d space_code 2
23542 @d space_stretch_code 3
23543 @d space_shrink_code 4
23544 @d x_height_code 5
23545 @d quad_code 6
23546 @d extra_space_code 7
23547
23548 @ So that is what \.{TFM} files hold. One of \MP's duties is to output such
23549 information, and it does this all at once at the end of a job.
23550 In order to prepare for such frenetic activity, it squirrels away the
23551 necessary facts in various arrays as information becomes available.
23552
23553 Character dimensions (\&{charwd}, \&{charht}, \&{chardp}, and \&{charic})
23554 are stored respectively in |tfm_width|, |tfm_height|, |tfm_depth|, and
23555 |tfm_ital_corr|. Other information about a character (e.g., about
23556 its ligatures or successors) is accessible via the |char_tag| and
23557 |char_remainder| arrays. Other information about the font as a whole
23558 is kept in additional arrays called |header_byte|, |lig_kern|,
23559 |kern|, |exten|, and |param|.
23560
23561 @d max_tfm_int 32510
23562 @d undefined_label max_tfm_int /* an undefined local label */
23563
23564 @<Glob...@>=
23565 #define TFM_ITEMS 257
23566 eight_bits bc;
23567 eight_bits ec; /* smallest and largest character codes shipped out */
23568 scaled tfm_width[TFM_ITEMS]; /* \&{charwd} values */
23569 scaled tfm_height[TFM_ITEMS]; /* \&{charht} values */
23570 scaled tfm_depth[TFM_ITEMS]; /* \&{chardp} values */
23571 scaled tfm_ital_corr[TFM_ITEMS]; /* \&{charic} values */
23572 boolean char_exists[TFM_ITEMS]; /* has this code been shipped out? */
23573 int char_tag[TFM_ITEMS]; /* |remainder| category */
23574 int char_remainder[TFM_ITEMS]; /* the |remainder| byte */
23575 char *header_byte; /* bytes of the \.{TFM} header */
23576 int header_last; /* last initialized \.{TFM} header byte */
23577 int header_size; /* size of the \.{TFM} header */
23578 four_quarters *lig_kern; /* the ligature/kern table */
23579 short nl; /* the number of ligature/kern steps so far */
23580 scaled *kern; /* distinct kerning amounts */
23581 short nk; /* the number of distinct kerns so far */
23582 four_quarters exten[TFM_ITEMS]; /* extensible character recipes */
23583 short ne; /* the number of extensible characters so far */
23584 scaled *param; /* \&{fontinfo} parameters */
23585 short np; /* the largest \&{fontinfo} parameter specified so far */
23586 short nw;short nh;short nd;short ni; /* sizes of \.{TFM} subtables */
23587 short skip_table[TFM_ITEMS]; /* local label status */
23588 boolean lk_started; /* has there been a lig/kern step in this command yet? */
23589 integer bchar; /* right boundary character */
23590 short bch_label; /* left boundary starting location */
23591 short ll;short lll; /* registers used for lig/kern processing */
23592 short label_loc[257]; /* lig/kern starting addresses */
23593 eight_bits label_char[257]; /* characters for |label_loc| */
23594 short label_ptr; /* highest position occupied in |label_loc| */
23595
23596 @ @<Allocate or initialize ...@>=
23597 mp->header_last = 0; mp->header_size = 128; /* just for init */
23598 mp->header_byte = xmalloc(mp->header_size, sizeof(char));
23599 mp->lig_kern = NULL; /* allocated when needed */
23600 mp->kern = NULL; /* allocated when needed */ 
23601 mp->param = NULL; /* allocated when needed */
23602
23603 @ @<Dealloc variables@>=
23604 xfree(mp->header_byte);
23605 xfree(mp->lig_kern);
23606 xfree(mp->kern);
23607 xfree(mp->param);
23608
23609 @ @<Set init...@>=
23610 for (k=0;k<= 255;k++ ) {
23611   mp->tfm_width[k]=0; mp->tfm_height[k]=0; mp->tfm_depth[k]=0; mp->tfm_ital_corr[k]=0;
23612   mp->char_exists[k]=false; mp->char_tag[k]=no_tag; mp->char_remainder[k]=0;
23613   mp->skip_table[k]=undefined_label;
23614 };
23615 memset(mp->header_byte,0,mp->header_size);
23616 mp->bc=255; mp->ec=0; mp->nl=0; mp->nk=0; mp->ne=0; mp->np=0;
23617 mp->internal[mp_boundary_char]=-unity;
23618 mp->bch_label=undefined_label;
23619 mp->label_loc[0]=-1; mp->label_ptr=0;
23620
23621 @ @<Declarations@>=
23622 scaled mp_tfm_check (MP mp,small_number m) ;
23623
23624 @ @<Declare the function called |tfm_check|@>=
23625 scaled mp_tfm_check (MP mp,small_number m) {
23626   if ( abs(mp->internal[m])>=fraction_half ) {
23627     print_err("Enormous "); mp_print(mp, mp->int_name[m]);
23628 @.Enormous charwd...@>
23629 @.Enormous chardp...@>
23630 @.Enormous charht...@>
23631 @.Enormous charic...@>
23632 @.Enormous designsize...@>
23633     mp_print(mp, " has been reduced");
23634     help1("Font metric dimensions must be less than 2048pt.");
23635     mp_put_get_error(mp);
23636     if ( mp->internal[m]>0 ) return (fraction_half-1);
23637     else return (1-fraction_half);
23638   } else {
23639     return mp->internal[m];
23640   }
23641 }
23642
23643 @ @<Store the width information for character code~|c|@>=
23644 if ( c<mp->bc ) mp->bc=c;
23645 if ( c>mp->ec ) mp->ec=c;
23646 mp->char_exists[c]=true;
23647 mp->tfm_width[c]=mp_tfm_check(mp, mp_char_wd);
23648 mp->tfm_height[c]=mp_tfm_check(mp, mp_char_ht);
23649 mp->tfm_depth[c]=mp_tfm_check(mp, mp_char_dp);
23650 mp->tfm_ital_corr[c]=mp_tfm_check(mp, mp_char_ic)
23651
23652 @ Now let's consider \MP's special \.{TFM}-oriented commands.
23653
23654 @<Cases of |do_statement|...@>=
23655 case tfm_command: mp_do_tfm_command(mp); break;
23656
23657 @ @d char_list_code 0
23658 @d lig_table_code 1
23659 @d extensible_code 2
23660 @d header_byte_code 3
23661 @d font_dimen_code 4
23662
23663 @<Put each...@>=
23664 mp_primitive(mp, "charlist",tfm_command,char_list_code);
23665 @:char_list_}{\&{charlist} primitive@>
23666 mp_primitive(mp, "ligtable",tfm_command,lig_table_code);
23667 @:lig_table_}{\&{ligtable} primitive@>
23668 mp_primitive(mp, "extensible",tfm_command,extensible_code);
23669 @:extensible_}{\&{extensible} primitive@>
23670 mp_primitive(mp, "headerbyte",tfm_command,header_byte_code);
23671 @:header_byte_}{\&{headerbyte} primitive@>
23672 mp_primitive(mp, "fontdimen",tfm_command,font_dimen_code);
23673 @:font_dimen_}{\&{fontdimen} primitive@>
23674
23675 @ @<Cases of |print_cmd...@>=
23676 case tfm_command: 
23677   switch (m) {
23678   case char_list_code:mp_print(mp, "charlist"); break;
23679   case lig_table_code:mp_print(mp, "ligtable"); break;
23680   case extensible_code:mp_print(mp, "extensible"); break;
23681   case header_byte_code:mp_print(mp, "headerbyte"); break;
23682   default: mp_print(mp, "fontdimen"); break;
23683   }
23684   break;
23685
23686 @ @<Declare action procedures for use by |do_statement|@>=
23687 eight_bits mp_get_code (MP mp) ;
23688
23689 @ @c eight_bits mp_get_code (MP mp) { /* scans a character code value */
23690   integer c; /* the code value found */
23691   mp_get_x_next(mp); mp_scan_expression(mp);
23692   if ( mp->cur_type==mp_known ) { 
23693     c=mp_round_unscaled(mp, mp->cur_exp);
23694     if ( c>=0 ) if ( c<256 ) return c;
23695   } else if ( mp->cur_type==mp_string_type ) {
23696     if ( length(mp->cur_exp)==1 )  { 
23697       c=mp->str_pool[mp->str_start[mp->cur_exp]];
23698       return c;
23699     }
23700   }
23701   exp_err("Invalid code has been replaced by 0");
23702 @.Invalid code...@>
23703   help2("I was looking for a number between 0 and 255, or for a")
23704        ("string of length 1. Didn't find it; will use 0 instead.");
23705   mp_put_get_flush_error(mp, 0); c=0;
23706   return c;
23707 };
23708
23709 @ @<Declare action procedures for use by |do_statement|@>=
23710 void mp_set_tag (MP mp,halfword c, small_number t, halfword r) ;
23711
23712 @ @c void mp_set_tag (MP mp,halfword c, small_number t, halfword r) { 
23713   if ( mp->char_tag[c]==no_tag ) {
23714     mp->char_tag[c]=t; mp->char_remainder[c]=r;
23715     if ( t==lig_tag ){ 
23716       incr(mp->label_ptr); mp->label_loc[mp->label_ptr]=r; 
23717       mp->label_char[mp->label_ptr]=c;
23718     }
23719   } else {
23720     @<Complain about a character tag conflict@>;
23721   }
23722 }
23723
23724 @ @<Complain about a character tag conflict@>=
23725
23726   print_err("Character ");
23727   if ( (c>' ')&&(c<127) ) mp_print_char(mp,c);
23728   else if ( c==256 ) mp_print(mp, "||");
23729   else  { mp_print(mp, "code "); mp_print_int(mp, c); };
23730   mp_print(mp, " is already ");
23731 @.Character c is already...@>
23732   switch (mp->char_tag[c]) {
23733   case lig_tag: mp_print(mp, "in a ligtable"); break;
23734   case list_tag: mp_print(mp, "in a charlist"); break;
23735   case ext_tag: mp_print(mp, "extensible"); break;
23736   } /* there are no other cases */
23737   help2("It's not legal to label a character more than once.")
23738     ("So I'll not change anything just now.");
23739   mp_put_get_error(mp); 
23740 }
23741
23742 @ @<Declare action procedures for use by |do_statement|@>=
23743 void mp_do_tfm_command (MP mp) ;
23744
23745 @ @c void mp_do_tfm_command (MP mp) {
23746   int c,cc; /* character codes */
23747   int k; /* index into the |kern| array */
23748   int j; /* index into |header_byte| or |param| */
23749   switch (mp->cur_mod) {
23750   case char_list_code: 
23751     c=mp_get_code(mp);
23752      /* we will store a list of character successors */
23753     while ( mp->cur_cmd==colon )   { 
23754       cc=mp_get_code(mp); mp_set_tag(mp, c,list_tag,cc); c=cc;
23755     };
23756     break;
23757   case lig_table_code: 
23758     if (mp->lig_kern==NULL) 
23759        mp->lig_kern = xmalloc((max_tfm_int+1),sizeof(four_quarters));
23760     if (mp->kern==NULL) 
23761        mp->kern = xmalloc((max_tfm_int+1),sizeof(scaled));
23762     @<Store a list of ligature/kern steps@>;
23763     break;
23764   case extensible_code: 
23765     @<Define an extensible recipe@>;
23766     break;
23767   case header_byte_code: 
23768   case font_dimen_code: 
23769     c=mp->cur_mod; mp_get_x_next(mp);
23770     mp_scan_expression(mp);
23771     if ( (mp->cur_type!=mp_known)||(mp->cur_exp<half_unit) ) {
23772       exp_err("Improper location");
23773 @.Improper location@>
23774       help2("I was looking for a known, positive number.")
23775        ("For safety's sake I'll ignore the present command.");
23776       mp_put_get_error(mp);
23777     } else  { 
23778       j=mp_round_unscaled(mp, mp->cur_exp);
23779       if ( mp->cur_cmd!=colon ) {
23780         mp_missing_err(mp, ":");
23781 @.Missing `:'@>
23782         help1("A colon should follow a headerbyte or fontinfo location.");
23783         mp_back_error(mp);
23784       }
23785       if ( c==header_byte_code ) { 
23786         @<Store a list of header bytes@>;
23787       } else {     
23788         if (mp->param==NULL) 
23789           mp->param = xmalloc((max_tfm_int+1),sizeof(scaled));
23790         @<Store a list of font dimensions@>;
23791       }
23792     }
23793     break;
23794   } /* there are no other cases */
23795 };
23796
23797 @ @<Store a list of ligature/kern steps@>=
23798
23799   mp->lk_started=false;
23800 CONTINUE: 
23801   mp_get_x_next(mp);
23802   if ((mp->cur_cmd==skip_to)&& mp->lk_started )
23803     @<Process a |skip_to| command and |goto done|@>;
23804   if ( mp->cur_cmd==bchar_label ) { c=256; mp->cur_cmd=colon; }
23805   else { mp_back_input(mp); c=mp_get_code(mp); };
23806   if ((mp->cur_cmd==colon)||(mp->cur_cmd==double_colon)) {
23807     @<Record a label in a lig/kern subprogram and |goto continue|@>;
23808   }
23809   if ( mp->cur_cmd==lig_kern_token ) { 
23810     @<Compile a ligature/kern command@>; 
23811   } else  { 
23812     print_err("Illegal ligtable step");
23813 @.Illegal ligtable step@>
23814     help1("I was looking for `=:' or `kern' here.");
23815     mp_back_error(mp); next_char(mp->nl)=qi(0); 
23816     op_byte(mp->nl)=qi(0); rem_byte(mp->nl)=qi(0);
23817     skip_byte(mp->nl)=stop_flag+1; /* this specifies an unconditional stop */
23818   }
23819   if ( mp->nl==max_tfm_int) mp_fatal_error(mp, "ligtable too large");
23820   incr(mp->nl);
23821   if ( mp->cur_cmd==comma ) goto CONTINUE;
23822   if ( skip_byte(mp->nl-1)<stop_flag ) skip_byte(mp->nl-1)=stop_flag;
23823 }
23824 DONE:
23825
23826 @ @<Put each...@>=
23827 mp_primitive(mp, "=:",lig_kern_token,0);
23828 @:=:_}{\.{=:} primitive@>
23829 mp_primitive(mp, "=:|",lig_kern_token,1);
23830 @:=:/_}{\.{=:\char'174} primitive@>
23831 mp_primitive(mp, "=:|>",lig_kern_token,5);
23832 @:=:/>_}{\.{=:\char'174>} primitive@>
23833 mp_primitive(mp, "|=:",lig_kern_token,2);
23834 @:=:/_}{\.{\char'174=:} primitive@>
23835 mp_primitive(mp, "|=:>",lig_kern_token,6);
23836 @:=:/>_}{\.{\char'174=:>} primitive@>
23837 mp_primitive(mp, "|=:|",lig_kern_token,3);
23838 @:=:/_}{\.{\char'174=:\char'174} primitive@>
23839 mp_primitive(mp, "|=:|>",lig_kern_token,7);
23840 @:=:/>_}{\.{\char'174=:\char'174>} primitive@>
23841 mp_primitive(mp, "|=:|>>",lig_kern_token,11);
23842 @:=:/>_}{\.{\char'174=:\char'174>>} primitive@>
23843 mp_primitive(mp, "kern",lig_kern_token,128);
23844 @:kern_}{\&{kern} primitive@>
23845
23846 @ @<Cases of |print_cmd...@>=
23847 case lig_kern_token: 
23848   switch (m) {
23849   case 0:mp_print(mp, "=:"); break;
23850   case 1:mp_print(mp, "=:|"); break;
23851   case 2:mp_print(mp, "|=:"); break;
23852   case 3:mp_print(mp, "|=:|"); break;
23853   case 5:mp_print(mp, "=:|>"); break;
23854   case 6:mp_print(mp, "|=:>"); break;
23855   case 7:mp_print(mp, "|=:|>"); break;
23856   case 11:mp_print(mp, "|=:|>>"); break;
23857   default: mp_print(mp, "kern"); break;
23858   }
23859   break;
23860
23861 @ Local labels are implemented by maintaining the |skip_table| array,
23862 where |skip_table[c]| is either |undefined_label| or the address of the
23863 most recent lig/kern instruction that skips to local label~|c|. In the
23864 latter case, the |skip_byte| in that instruction will (temporarily)
23865 be zero if there were no prior skips to this label, or it will be the
23866 distance to the prior skip.
23867
23868 We may need to cancel skips that span more than 127 lig/kern steps.
23869
23870 @d cancel_skips(A) mp->ll=(A);
23871   do {  
23872     mp->lll=qo(skip_byte(mp->ll)); 
23873     skip_byte(mp->ll)=stop_flag; mp->ll=mp->ll-mp->lll;
23874   } while (mp->lll!=0)
23875 @d skip_error(A) { print_err("Too far to skip");
23876 @.Too far to skip@>
23877   help1("At most 127 lig/kern steps can separate skipto1 from 1::.");
23878   mp_error(mp); cancel_skips((A));
23879   }
23880
23881 @<Process a |skip_to| command and |goto done|@>=
23882
23883   c=mp_get_code(mp);
23884   if ( mp->nl-mp->skip_table[c]>128 ) { /* |skip_table[c]<<nl<=undefined_label| */
23885     skip_error(mp->skip_table[c]); mp->skip_table[c]=undefined_label;
23886   }
23887   if ( mp->skip_table[c]==undefined_label ) skip_byte(mp->nl-1)=qi(0);
23888   else skip_byte(mp->nl-1)=qi(mp->nl-mp->skip_table[c]-1);
23889   mp->skip_table[c]=mp->nl-1; goto DONE;
23890 }
23891
23892 @ @<Record a label in a lig/kern subprogram and |goto continue|@>=
23893
23894   if ( mp->cur_cmd==colon ) {
23895     if ( c==256 ) mp->bch_label=mp->nl;
23896     else mp_set_tag(mp, c,lig_tag,mp->nl);
23897   } else if ( mp->skip_table[c]<undefined_label ) {
23898     mp->ll=mp->skip_table[c]; mp->skip_table[c]=undefined_label;
23899     do {  
23900       mp->lll=qo(skip_byte(mp->ll));
23901       if ( mp->nl-mp->ll>128 ) {
23902         skip_error(mp->ll); goto CONTINUE;
23903       }
23904       skip_byte(mp->ll)=qi(mp->nl-mp->ll-1); mp->ll=mp->ll-mp->lll;
23905     } while (mp->lll!=0);
23906   }
23907   goto CONTINUE;
23908 }
23909
23910 @ @<Compile a ligature/kern...@>=
23911
23912   next_char(mp->nl)=qi(c); skip_byte(mp->nl)=qi(0);
23913   if ( mp->cur_mod<128 ) { /* ligature op */
23914     op_byte(mp->nl)=qi(mp->cur_mod); rem_byte(mp->nl)=qi(mp_get_code(mp));
23915   } else { 
23916     mp_get_x_next(mp); mp_scan_expression(mp);
23917     if ( mp->cur_type!=mp_known ) {
23918       exp_err("Improper kern");
23919 @.Improper kern@>
23920       help2("The amount of kern should be a known numeric value.")
23921         ("I'm zeroing this one. Proceed, with fingers crossed.");
23922       mp_put_get_flush_error(mp, 0);
23923     }
23924     mp->kern[mp->nk]=mp->cur_exp;
23925     k=0; 
23926     while ( mp->kern[k]!=mp->cur_exp ) incr(k);
23927     if ( k==mp->nk ) {
23928       if ( mp->nk==max_tfm_int ) mp_fatal_error(mp, "too many TFM kerns");
23929       incr(mp->nk);
23930     }
23931     op_byte(mp->nl)=kern_flag+(k / 256);
23932     rem_byte(mp->nl)=qi((k % 256));
23933   }
23934   mp->lk_started=true;
23935 }
23936
23937 @ @d missing_extensible_punctuation(A) 
23938   { mp_missing_err(mp, (A));
23939 @.Missing `\char`\#'@>
23940   help1("I'm processing `extensible c: t,m,b,r'."); mp_back_error(mp);
23941   }
23942
23943 @<Define an extensible recipe@>=
23944
23945   if ( mp->ne==256 ) mp_fatal_error(mp, "too many extensible recipies");
23946   c=mp_get_code(mp); mp_set_tag(mp, c,ext_tag,mp->ne);
23947   if ( mp->cur_cmd!=colon ) missing_extensible_punctuation(":");
23948   ext_top(mp->ne)=qi(mp_get_code(mp));
23949   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23950   ext_mid(mp->ne)=qi(mp_get_code(mp));
23951   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23952   ext_bot(mp->ne)=qi(mp_get_code(mp));
23953   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23954   ext_rep(mp->ne)=qi(mp_get_code(mp));
23955   incr(mp->ne);
23956 }
23957
23958 @ The header could contain ASCII zeroes, so can't use |strdup|.
23959
23960 @<Store a list of header bytes@>=
23961 do {  
23962   if ( j>=mp->header_size ) {
23963     int l = mp->header_size + (mp->header_size >> 2);
23964     char *t = xmalloc(l,sizeof(char));
23965     memset(t,0,l); 
23966     memcpy(t,mp->header_byte,mp->header_size);
23967     xfree (mp->header_byte);
23968     mp->header_byte = t;
23969     mp->header_size = l;
23970   }
23971   mp->header_byte[j]=mp_get_code(mp); 
23972   incr(j); incr(mp->header_last);
23973 } while (mp->cur_cmd==comma)
23974
23975 @ @<Store a list of font dimensions@>=
23976 do {  
23977   if ( j>max_tfm_int ) mp_fatal_error(mp, "too many fontdimens");
23978   while ( j>mp->np ) { incr(mp->np); mp->param[mp->np]=0; };
23979   mp_get_x_next(mp); mp_scan_expression(mp);
23980   if ( mp->cur_type!=mp_known ){ 
23981     exp_err("Improper font parameter");
23982 @.Improper font parameter@>
23983     help1("I'm zeroing this one. Proceed, with fingers crossed.");
23984     mp_put_get_flush_error(mp, 0);
23985   }
23986   mp->param[j]=mp->cur_exp; incr(j);
23987 } while (mp->cur_cmd==comma)
23988
23989 @ OK: We've stored all the data that is needed for the \.{TFM} file.
23990 All that remains is to output it in the correct format.
23991
23992 An interesting problem needs to be solved in this connection, because
23993 the \.{TFM} format allows at most 256~widths, 16~heights, 16~depths,
23994 and 64~italic corrections. If the data has more distinct values than
23995 this, we want to meet the necessary restrictions by perturbing the
23996 given values as little as possible.
23997
23998 \MP\ solves this problem in two steps. First the values of a given
23999 kind (widths, heights, depths, or italic corrections) are sorted;
24000 then the list of sorted values is perturbed, if necessary.
24001
24002 The sorting operation is facilitated by having a special node of
24003 essentially infinite |value| at the end of the current list.
24004
24005 @<Initialize table entries...@>=
24006 value(inf_val)=fraction_four;
24007
24008 @ Straight linear insertion is good enough for sorting, since the lists
24009 are usually not terribly long. As we work on the data, the current list
24010 will start at |link(temp_head)| and end at |inf_val|; the nodes in this
24011 list will be in increasing order of their |value| fields.
24012
24013 Given such a list, the |sort_in| function takes a value and returns a pointer
24014 to where that value can be found in the list. The value is inserted in
24015 the proper place, if necessary.
24016
24017 At the time we need to do these operations, most of \MP's work has been
24018 completed, so we will have plenty of memory to play with. The value nodes
24019 that are allocated for sorting will never be returned to free storage.
24020
24021 @d clear_the_list link(temp_head)=inf_val
24022
24023 @c pointer mp_sort_in (MP mp,scaled v) {
24024   pointer p,q,r; /* list manipulation registers */
24025   p=temp_head;
24026   while (1) { 
24027     q=link(p);
24028     if ( v<=value(q) ) break;
24029     p=q;
24030   }
24031   if ( v<value(q) ) {
24032     r=mp_get_node(mp, value_node_size); value(r)=v; link(r)=q; link(p)=r;
24033   }
24034   return link(p);
24035 }
24036
24037 @ Now we come to the interesting part, where we reduce the list if necessary
24038 until it has the required size. The |min_cover| routine is basic to this
24039 process; it computes the minimum number~|m| such that the values of the
24040 current sorted list can be covered by |m|~intervals of width~|d|. It
24041 also sets the global value |perturbation| to the smallest value $d'>d$
24042 such that the covering found by this algorithm would be different.
24043
24044 In particular, |min_cover(0)| returns the number of distinct values in the
24045 current list and sets |perturbation| to the minimum distance between
24046 adjacent values.
24047
24048 @c integer mp_min_cover (MP mp,scaled d) {
24049   pointer p; /* runs through the current list */
24050   scaled l; /* the least element covered by the current interval */
24051   integer m; /* lower bound on the size of the minimum cover */
24052   m=0; p=link(temp_head); mp->perturbation=el_gordo;
24053   while ( p!=inf_val ){ 
24054     incr(m); l=value(p);
24055     do {  p=link(p); } while (value(p)<=l+d);
24056     if ( value(p)-l<mp->perturbation ) 
24057       mp->perturbation=value(p)-l;
24058   }
24059   return m;
24060 }
24061
24062 @ @<Glob...@>=
24063 scaled perturbation; /* quantity related to \.{TFM} rounding */
24064 integer excess; /* the list is this much too long */
24065
24066 @ The smallest |d| such that a given list can be covered with |m| intervals
24067 is determined by the |threshold| routine, which is sort of an inverse
24068 to |min_cover|. The idea is to increase the interval size rapidly until
24069 finding the range, then to go sequentially until the exact borderline has
24070 been discovered.
24071
24072 @c scaled mp_threshold (MP mp,integer m) {
24073   scaled d; /* lower bound on the smallest interval size */
24074   mp->excess=mp_min_cover(mp, 0)-m;
24075   if ( mp->excess<=0 ) {
24076     return 0;
24077   } else  { 
24078     do {  
24079       d=mp->perturbation;
24080     } while (mp_min_cover(mp, d+d)>m);
24081     while ( mp_min_cover(mp, d)>m ) 
24082       d=mp->perturbation;
24083     return d;
24084   }
24085 }
24086
24087 @ The |skimp| procedure reduces the current list to at most |m| entries,
24088 by changing values if necessary. It also sets |info(p):=k| if |value(p)|
24089 is the |k|th distinct value on the resulting list, and it sets
24090 |perturbation| to the maximum amount by which a |value| field has
24091 been changed. The size of the resulting list is returned as the
24092 value of |skimp|.
24093
24094 @c integer mp_skimp (MP mp,integer m) {
24095   scaled d; /* the size of intervals being coalesced */
24096   pointer p,q,r; /* list manipulation registers */
24097   scaled l; /* the least value in the current interval */
24098   scaled v; /* a compromise value */
24099   d=mp_threshold(mp, m); mp->perturbation=0;
24100   q=temp_head; m=0; p=link(temp_head);
24101   while ( p!=inf_val ) {
24102     incr(m); l=value(p); info(p)=m;
24103     if ( value(link(p))<=l+d ) {
24104       @<Replace an interval of values by its midpoint@>;
24105     }
24106     q=p; p=link(p);
24107   }
24108   return m;
24109 }
24110
24111 @ @<Replace an interval...@>=
24112
24113   do {  
24114     p=link(p); info(p)=m;
24115     decr(mp->excess); if ( mp->excess==0 ) d=0;
24116   } while (value(link(p))<=l+d);
24117   v=l+halfp(value(p)-l);
24118   if ( value(p)-v>mp->perturbation ) 
24119     mp->perturbation=value(p)-v;
24120   r=q;
24121   do {  
24122     r=link(r); value(r)=v;
24123   } while (r!=p);
24124   link(q)=p; /* remove duplicate values from the current list */
24125 }
24126
24127 @ A warning message is issued whenever something is perturbed by
24128 more than 1/16\thinspace pt.
24129
24130 @c void mp_tfm_warning (MP mp,small_number m) { 
24131   mp_print_nl(mp, "(some "); 
24132   mp_print(mp, mp->int_name[m]);
24133 @.some charwds...@>
24134 @.some chardps...@>
24135 @.some charhts...@>
24136 @.some charics...@>
24137   mp_print(mp, " values had to be adjusted by as much as ");
24138   mp_print_scaled(mp, mp->perturbation); mp_print(mp, "pt)");
24139 }
24140
24141 @ Here's an example of how we use these routines.
24142 The width data needs to be perturbed only if there are 256 distinct
24143 widths, but \MP\ must check for this case even though it is
24144 highly unusual.
24145
24146 An integer variable |k| will be defined when we use this code.
24147 The |dimen_head| array will contain pointers to the sorted
24148 lists of dimensions.
24149
24150 @<Massage the \.{TFM} widths@>=
24151 clear_the_list;
24152 for (k=mp->bc;k<=mp->ec;k++)  {
24153   if ( mp->char_exists[k] )
24154     mp->tfm_width[k]=mp_sort_in(mp, mp->tfm_width[k]);
24155 }
24156 mp->nw=mp_skimp(mp, 255)+1; mp->dimen_head[1]=link(temp_head);
24157 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_wd)
24158
24159 @ @<Glob...@>=
24160 pointer dimen_head[5]; /* lists of \.{TFM} dimensions */
24161
24162 @ Heights, depths, and italic corrections are different from widths
24163 not only because their list length is more severely restricted, but
24164 also because zero values do not need to be put into the lists.
24165
24166 @<Massage the \.{TFM} heights, depths, and italic corrections@>=
24167 clear_the_list;
24168 for (k=mp->bc;k<=mp->ec;k++) {
24169   if ( mp->char_exists[k] ) {
24170     if ( mp->tfm_height[k]==0 ) mp->tfm_height[k]=zero_val;
24171     else mp->tfm_height[k]=mp_sort_in(mp, mp->tfm_height[k]);
24172   }
24173 }
24174 mp->nh=mp_skimp(mp, 15)+1; mp->dimen_head[2]=link(temp_head);
24175 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ht);
24176 clear_the_list;
24177 for (k=mp->bc;k<=mp->ec;k++) {
24178   if ( mp->char_exists[k] ) {
24179     if ( mp->tfm_depth[k]==0 ) mp->tfm_depth[k]=zero_val;
24180     else mp->tfm_depth[k]=mp_sort_in(mp, mp->tfm_depth[k]);
24181   }
24182 }
24183 mp->nd=mp_skimp(mp, 15)+1; mp->dimen_head[3]=link(temp_head);
24184 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_dp);
24185 clear_the_list;
24186 for (k=mp->bc;k<=mp->ec;k++) {
24187   if ( mp->char_exists[k] ) {
24188     if ( mp->tfm_ital_corr[k]==0 ) mp->tfm_ital_corr[k]=zero_val;
24189     else mp->tfm_ital_corr[k]=mp_sort_in(mp, mp->tfm_ital_corr[k]);
24190   }
24191 }
24192 mp->ni=mp_skimp(mp, 63)+1; mp->dimen_head[4]=link(temp_head);
24193 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ic)
24194
24195 @ @<Initialize table entries...@>=
24196 value(zero_val)=0; info(zero_val)=0;
24197
24198 @ Bytes 5--8 of the header are set to the design size, unless the user has
24199 some crazy reason for specifying them differently.
24200
24201 Error messages are not allowed at the time this procedure is called,
24202 so a warning is printed instead.
24203
24204 The value of |max_tfm_dimen| is calculated so that
24205 $$\hbox{|make_scaled(16*max_tfm_dimen,internal[mp_design_size])|}
24206  < \\{three\_bytes}.$$
24207
24208 @d three_bytes 0100000000 /* $2^{24}$ */
24209
24210 @c 
24211 void mp_fix_design_size (MP mp) {
24212   scaled d; /* the design size */
24213   d=mp->internal[mp_design_size];
24214   if ( (d<unity)||(d>=fraction_half) ) {
24215     if ( d!=0 )
24216       mp_print_nl(mp, "(illegal design size has been changed to 128pt)");
24217 @.illegal design size...@>
24218     d=040000000; mp->internal[mp_design_size]=d;
24219   }
24220   if ( mp->header_byte[4]<0 ) if ( mp->header_byte[5]<0 )
24221     if ( mp->header_byte[6]<0 ) if ( mp->header_byte[7]<0 ) {
24222      mp->header_byte[4]=d / 04000000;
24223      mp->header_byte[5]=(d / 4096) % 256;
24224      mp->header_byte[6]=(d / 16) % 256;
24225      mp->header_byte[7]=(d % 16)*16;
24226   };
24227   mp->max_tfm_dimen=16*mp->internal[mp_design_size]-mp->internal[mp_design_size] / 010000000;
24228   if ( mp->max_tfm_dimen>=fraction_half ) mp->max_tfm_dimen=fraction_half-1;
24229 }
24230
24231 @ The |dimen_out| procedure computes a |fix_word| relative to the
24232 design size. If the data was out of range, it is corrected and the
24233 global variable |tfm_changed| is increased by~one.
24234
24235 @c integer mp_dimen_out (MP mp,scaled x) { 
24236   if ( abs(x)>mp->max_tfm_dimen ) {
24237     incr(mp->tfm_changed);
24238     if ( x>0 ) x=three_bytes-1; else x=1-three_bytes;
24239   } else {
24240     x=mp_make_scaled(mp, x*16,mp->internal[mp_design_size]);
24241   }
24242   return x;
24243 }
24244
24245 @ @<Glob...@>=
24246 scaled max_tfm_dimen; /* bound on widths, heights, kerns, etc. */
24247 integer tfm_changed; /* the number of data entries that were out of bounds */
24248
24249 @ If the user has not specified any of the first four header bytes,
24250 the |fix_check_sum| procedure replaces them by a ``check sum'' computed
24251 from the |tfm_width| data relative to the design size.
24252 @^check sum@>
24253
24254 @c void mp_fix_check_sum (MP mp) {
24255   eight_bits k; /* runs through character codes */
24256   eight_bits B1,B2,B3,B4; /* bytes of the check sum */
24257   integer x;  /* hash value used in check sum computation */
24258   if ( mp->header_byte[0]==0 && mp->header_byte[1]==0 &&
24259        mp->header_byte[2]==0 && mp->header_byte[3]==0 ) {
24260     @<Compute a check sum in |(b1,b2,b3,b4)|@>;
24261     mp->header_byte[0]=B1; mp->header_byte[1]=B2;
24262     mp->header_byte[2]=B3; mp->header_byte[3]=B4; 
24263     return;
24264   }
24265 }
24266
24267 @ @<Compute a check sum in |(b1,b2,b3,b4)|@>=
24268 B1=mp->bc; B2=mp->ec; B3=mp->bc; B4=mp->ec; mp->tfm_changed=0;
24269 for (k=mp->bc;k<=mp->ec;k++) { 
24270   if ( mp->char_exists[k] ) {
24271     x=mp_dimen_out(mp, value(mp->tfm_width[k]))+(k+4)*020000000; /* this is positive */
24272     B1=(B1+B1+x) % 255;
24273     B2=(B2+B2+x) % 253;
24274     B3=(B3+B3+x) % 251;
24275     B4=(B4+B4+x) % 247;
24276   }
24277 }
24278
24279 @ Finally we're ready to actually write the \.{TFM} information.
24280 Here are some utility routines for this purpose.
24281
24282 @d tfm_out(A) do { /* output one byte to |tfm_file| */
24283   unsigned char s=(A); 
24284   (mp->write_binary_file)(mp->tfm_file,(void *)&s,1); 
24285   } while (0)
24286
24287 @c void mp_tfm_two (MP mp,integer x) { /* output two bytes to |tfm_file| */
24288   tfm_out(x / 256); tfm_out(x % 256);
24289 }
24290 void mp_tfm_four (MP mp,integer x) { /* output four bytes to |tfm_file| */
24291   if ( x>=0 ) tfm_out(x / three_bytes);
24292   else { 
24293     x=x+010000000000; /* use two's complement for negative values */
24294     x=x+010000000000;
24295     tfm_out((x / three_bytes) + 128);
24296   };
24297   x=x % three_bytes; tfm_out(x / unity);
24298   x=x % unity; tfm_out(x / 0400);
24299   tfm_out(x % 0400);
24300 }
24301 void mp_tfm_qqqq (MP mp,four_quarters x) { /* output four quarterwords to |tfm_file| */
24302   tfm_out(qo(x.b0)); tfm_out(qo(x.b1)); 
24303   tfm_out(qo(x.b2)); tfm_out(qo(x.b3));
24304 }
24305
24306 @ @<Finish the \.{TFM} file@>=
24307 if ( mp->job_name==NULL ) mp_open_log_file(mp);
24308 mp_pack_job_name(mp, ".tfm");
24309 while ( ! mp_b_open_out(mp, &mp->tfm_file, mp_filetype_metrics) )
24310   mp_prompt_file_name(mp, "file name for font metrics",".tfm");
24311 mp->metric_file_name=xstrdup(mp->name_of_file);
24312 @<Output the subfile sizes and header bytes@>;
24313 @<Output the character information bytes, then
24314   output the dimensions themselves@>;
24315 @<Output the ligature/kern program@>;
24316 @<Output the extensible character recipes and the font metric parameters@>;
24317   if ( mp->internal[mp_tracing_stats]>0 )
24318   @<Log the subfile sizes of the \.{TFM} file@>;
24319 mp_print_nl(mp, "Font metrics written on "); 
24320 mp_print(mp, mp->metric_file_name); mp_print_char(mp, '.');
24321 @.Font metrics written...@>
24322 (mp->close_file)(mp->tfm_file)
24323
24324 @ Integer variables |lh|, |k|, and |lk_offset| will be defined when we use
24325 this code.
24326
24327 @<Output the subfile sizes and header bytes@>=
24328 k=mp->header_last;
24329 LH=(k+3) / 4; /* this is the number of header words */
24330 if ( mp->bc>mp->ec ) mp->bc=1; /* if there are no characters, |ec=0| and |bc=1| */
24331 @<Compute the ligature/kern program offset and implant the
24332   left boundary label@>;
24333 mp_tfm_two(mp,6+LH+(mp->ec-mp->bc+1)+mp->nw+mp->nh+mp->nd+mp->ni+mp->nl
24334      +lk_offset+mp->nk+mp->ne+mp->np);
24335   /* this is the total number of file words that will be output */
24336 mp_tfm_two(mp, LH); mp_tfm_two(mp, mp->bc); mp_tfm_two(mp, mp->ec); 
24337 mp_tfm_two(mp, mp->nw); mp_tfm_two(mp, mp->nh);
24338 mp_tfm_two(mp, mp->nd); mp_tfm_two(mp, mp->ni); mp_tfm_two(mp, mp->nl+lk_offset); 
24339 mp_tfm_two(mp, mp->nk); mp_tfm_two(mp, mp->ne);
24340 mp_tfm_two(mp, mp->np);
24341 for (k=0;k< 4*LH;k++)   { 
24342   tfm_out(mp->header_byte[k]);
24343 }
24344
24345 @ @<Output the character information bytes...@>=
24346 for (k=mp->bc;k<=mp->ec;k++) {
24347   if ( ! mp->char_exists[k] ) {
24348     mp_tfm_four(mp, 0);
24349   } else { 
24350     tfm_out(info(mp->tfm_width[k])); /* the width index */
24351     tfm_out((info(mp->tfm_height[k]))*16+info(mp->tfm_depth[k]));
24352     tfm_out((info(mp->tfm_ital_corr[k]))*4+mp->char_tag[k]);
24353     tfm_out(mp->char_remainder[k]);
24354   };
24355 }
24356 mp->tfm_changed=0;
24357 for (k=1;k<=4;k++) { 
24358   mp_tfm_four(mp, 0); p=mp->dimen_head[k];
24359   while ( p!=inf_val ) {
24360     mp_tfm_four(mp, mp_dimen_out(mp, value(p))); p=link(p);
24361   }
24362 }
24363
24364
24365 @ We need to output special instructions at the beginning of the
24366 |lig_kern| array in order to specify the right boundary character
24367 and/or to handle starting addresses that exceed 255. The |label_loc|
24368 and |label_char| arrays have been set up to record all the
24369 starting addresses; we have $-1=|label_loc|[0]<|label_loc|[1]\le\cdots
24370 \le|label_loc|[|label_ptr]|$.
24371
24372 @<Compute the ligature/kern program offset...@>=
24373 mp->bchar=mp_round_unscaled(mp, mp->internal[mp_boundary_char]);
24374 if ((mp->bchar<0)||(mp->bchar>255))
24375   { mp->bchar=-1; mp->lk_started=false; lk_offset=0; }
24376 else { mp->lk_started=true; lk_offset=1; };
24377 @<Find the minimum |lk_offset| and adjust all remainders@>;
24378 if ( mp->bch_label<undefined_label )
24379   { skip_byte(mp->nl)=qi(255); next_char(mp->nl)=qi(0);
24380   op_byte(mp->nl)=qi(((mp->bch_label+lk_offset)/ 256));
24381   rem_byte(mp->nl)=qi(((mp->bch_label+lk_offset)% 256));
24382   incr(mp->nl); /* possibly |nl=lig_table_size+1| */
24383   }
24384
24385 @ @<Find the minimum |lk_offset|...@>=
24386 k=mp->label_ptr; /* pointer to the largest unallocated label */
24387 if ( mp->label_loc[k]+lk_offset>255 ) {
24388   lk_offset=0; mp->lk_started=false; /* location 0 can do double duty */
24389   do {  
24390     mp->char_remainder[mp->label_char[k]]=lk_offset;
24391     while ( mp->label_loc[k-1]==mp->label_loc[k] ) {
24392        decr(k); mp->char_remainder[mp->label_char[k]]=lk_offset;
24393     }
24394     incr(lk_offset); decr(k);
24395   } while (! (lk_offset+mp->label_loc[k]<256));
24396     /* N.B.: |lk_offset=256| satisfies this when |k=0| */
24397 };
24398 if ( lk_offset>0 ) {
24399   while ( k>0 ) {
24400     mp->char_remainder[mp->label_char[k]]
24401      =mp->char_remainder[mp->label_char[k]]+lk_offset;
24402     decr(k);
24403   }
24404 }
24405
24406 @ @<Output the ligature/kern program@>=
24407 for (k=0;k<= 255;k++ ) {
24408   if ( mp->skip_table[k]<undefined_label ) {
24409      mp_print_nl(mp, "(local label "); mp_print_int(mp, k); mp_print(mp, ":: was missing)");
24410 @.local label l:: was missing@>
24411     cancel_skips(mp->skip_table[k]);
24412   }
24413 }
24414 if ( mp->lk_started ) { /* |lk_offset=1| for the special |bchar| */
24415   tfm_out(255); tfm_out(mp->bchar); mp_tfm_two(mp, 0);
24416 } else {
24417   for (k=1;k<=lk_offset;k++) {/* output the redirection specs */
24418     mp->ll=mp->label_loc[mp->label_ptr];
24419     if ( mp->bchar<0 ) { tfm_out(254); tfm_out(0);   }
24420     else { tfm_out(255); tfm_out(mp->bchar);   };
24421     mp_tfm_two(mp, mp->ll+lk_offset);
24422     do {  
24423       decr(mp->label_ptr);
24424     } while (! (mp->label_loc[mp->label_ptr]<mp->ll));
24425   }
24426 }
24427 for (k=0;k<=mp->nl-1;k++) mp_tfm_qqqq(mp, mp->lig_kern[k]);
24428 for (k=0;k<=mp->nk-1;k++) mp_tfm_four(mp, mp_dimen_out(mp, mp->kern[k]))
24429
24430 @ @<Output the extensible character recipes...@>=
24431 for (k=0;k<=mp->ne-1;k++) 
24432   mp_tfm_qqqq(mp, mp->exten[k]);
24433 for (k=1;k<=mp->np;k++) {
24434   if ( k==1 ) {
24435     if ( abs(mp->param[1])<fraction_half ) {
24436       mp_tfm_four(mp, mp->param[1]*16);
24437     } else  { 
24438       incr(mp->tfm_changed);
24439       if ( mp->param[1]>0 ) mp_tfm_four(mp, el_gordo);
24440       else mp_tfm_four(mp, -el_gordo);
24441     }
24442   } else {
24443     mp_tfm_four(mp, mp_dimen_out(mp, mp->param[k]));
24444   }
24445 }
24446 if ( mp->tfm_changed>0 )  { 
24447   if ( mp->tfm_changed==1 ) mp_print_nl(mp, "(a font metric dimension");
24448 @.a font metric dimension...@>
24449   else  { 
24450     mp_print_nl(mp, "("); mp_print_int(mp, mp->tfm_changed);
24451 @.font metric dimensions...@>
24452     mp_print(mp, " font metric dimensions");
24453   }
24454   mp_print(mp, " had to be decreased)");
24455 }
24456
24457 @ @<Log the subfile sizes of the \.{TFM} file@>=
24458
24459   char s[200];
24460   wlog_ln(" ");
24461   if ( mp->bch_label<undefined_label ) decr(mp->nl);
24462   snprintf(s,128,"(You used %iw,%ih,%id,%ii,%il,%ik,%ie,%ip metric file positions)",
24463                  mp->nw, mp->nh, mp->nd, mp->ni, mp->nl, mp->nk, mp->ne,mp->np);
24464   wlog_ln(s);
24465 }
24466
24467 @* \[43] Reading font metric data.
24468
24469 \MP\ isn't a typesetting program but it does need to find the bounding box
24470 of a sequence of typeset characters.  Thus it needs to read \.{TFM} files as
24471 well as write them.
24472
24473 @<Glob...@>=
24474 void * tfm_infile;
24475
24476 @ All the width, height, and depth information is stored in an array called
24477 |font_info|.  This array is allocated sequentially and each font is stored
24478 as a series of |char_info| words followed by the width, height, and depth
24479 tables.  Since |font_name| entries are permanent, their |str_ref| values are
24480 set to |max_str_ref|.
24481
24482 @<Types...@>=
24483 typedef unsigned int font_number; /* |0..font_max| */
24484
24485 @ The |font_info| array is indexed via a group directory arrays.
24486 For example, the |char_info| data for character~|c| in font~|f| will be
24487 in |font_info[char_base[f]+c].qqqq|.
24488
24489 @<Glob...@>=
24490 font_number font_max; /* maximum font number for included text fonts */
24491 size_t      font_mem_size; /* number of words for \.{TFM} information for text fonts */
24492 memory_word *font_info; /* height, width, and depth data */
24493 char        **font_enc_name; /* encoding names, if any */
24494 boolean     *font_ps_name_fixed; /* are the postscript names fixed already?  */
24495 int         next_fmem; /* next unused entry in |font_info| */
24496 font_number last_fnum; /* last font number used so far */
24497 scaled      *font_dsize;  /* 16 times the ``design'' size in \ps\ points */
24498 char        **font_name;  /* name as specified in the \&{infont} command */
24499 char        **font_ps_name;  /* PostScript name for use when |internal[mp_prologues]>0| */
24500 font_number last_ps_fnum; /* last valid |font_ps_name| index */
24501 eight_bits  *font_bc;
24502 eight_bits  *font_ec;  /* first and last character code */
24503 int         *char_base;  /* base address for |char_info| */
24504 int         *width_base; /* index for zeroth character width */
24505 int         *height_base; /* index for zeroth character height */
24506 int         *depth_base; /* index for zeroth character depth */
24507 pointer     *font_sizes;
24508
24509 @ @<Allocate or initialize ...@>=
24510 mp->font_mem_size = 10000; 
24511 mp->font_info = xmalloc ((mp->font_mem_size+1),sizeof(memory_word));
24512 memset (mp->font_info,0,sizeof(memory_word)*(mp->font_mem_size+1));
24513 mp->font_enc_name = NULL;
24514 mp->font_ps_name_fixed = NULL;
24515 mp->font_dsize = NULL;
24516 mp->font_name = NULL;
24517 mp->font_ps_name = NULL;
24518 mp->font_bc = NULL;
24519 mp->font_ec = NULL;
24520 mp->last_fnum = null_font;
24521 mp->char_base = NULL;
24522 mp->width_base = NULL;
24523 mp->height_base = NULL;
24524 mp->depth_base = NULL;
24525 mp->font_sizes = null;
24526
24527 @ @<Dealloc variables@>=
24528 for (k=1;k<=(int)mp->last_fnum;k++) {
24529   xfree(mp->font_enc_name[k]);
24530   xfree(mp->font_name[k]);
24531   xfree(mp->font_ps_name[k]);
24532 }
24533 xfree(mp->font_info);
24534 xfree(mp->font_enc_name);
24535 xfree(mp->font_ps_name_fixed);
24536 xfree(mp->font_dsize);
24537 xfree(mp->font_name);
24538 xfree(mp->font_ps_name);
24539 xfree(mp->font_bc);
24540 xfree(mp->font_ec);
24541 xfree(mp->char_base);
24542 xfree(mp->width_base);
24543 xfree(mp->height_base);
24544 xfree(mp->depth_base);
24545 xfree(mp->font_sizes);
24546
24547
24548 @c 
24549 void mp_reallocate_fonts (MP mp, font_number l) {
24550   font_number f;
24551   XREALLOC(mp->font_enc_name,      l, char *);
24552   XREALLOC(mp->font_ps_name_fixed, l, boolean);
24553   XREALLOC(mp->font_dsize,         l, scaled);
24554   XREALLOC(mp->font_name,          l, char *);
24555   XREALLOC(mp->font_ps_name,       l, char *);
24556   XREALLOC(mp->font_bc,            l, eight_bits);
24557   XREALLOC(mp->font_ec,            l, eight_bits);
24558   XREALLOC(mp->char_base,          l, int);
24559   XREALLOC(mp->width_base,         l, int);
24560   XREALLOC(mp->height_base,        l, int);
24561   XREALLOC(mp->depth_base,         l, int);
24562   XREALLOC(mp->font_sizes,         l, pointer);
24563   for (f=(mp->last_fnum+1);f<=l;f++) {
24564     mp->font_enc_name[f]=NULL;
24565     mp->font_ps_name_fixed[f] = false;
24566     mp->font_name[f]=NULL;
24567     mp->font_ps_name[f]=NULL;
24568     mp->font_sizes[f]=null;
24569   }
24570   mp->font_max = l;
24571 }
24572
24573 @ @<Declare |mp_reallocate| functions@>=
24574 void mp_reallocate_fonts (MP mp, font_number l);
24575
24576
24577 @ A |null_font| containing no characters is useful for error recovery.  Its
24578 |font_name| entry starts out empty but is reset each time an erroneous font is
24579 found.  This helps to cut down on the number of duplicate error messages without
24580 wasting a lot of space.
24581
24582 @d null_font 0 /* the |font_number| for an empty font */
24583
24584 @<Set initial...@>=
24585 mp->font_dsize[null_font]=0;
24586 mp->font_bc[null_font]=1;
24587 mp->font_ec[null_font]=0;
24588 mp->char_base[null_font]=0;
24589 mp->width_base[null_font]=0;
24590 mp->height_base[null_font]=0;
24591 mp->depth_base[null_font]=0;
24592 mp->next_fmem=0;
24593 mp->last_fnum=null_font;
24594 mp->last_ps_fnum=null_font;
24595 mp->font_name[null_font]="nullfont";
24596 mp->font_ps_name[null_font]="";
24597 mp->font_ps_name_fixed[null_font] = false;
24598 mp->font_enc_name[null_font]=NULL;
24599 mp->font_sizes[null_font]=null;
24600
24601 @ Each |char_info| word is of type |four_quarters|.  The |b0| field contains
24602 the |width index|; the |b1| field contains the height
24603 index; the |b2| fields contains the depth index, and the |b3| field used only
24604 for temporary storage. (It is used to keep track of which characters occur in
24605 an edge structure that is being shipped out.)
24606 The corresponding words in the width, height, and depth tables are stored as
24607 |scaled| values in units of \ps\ points.
24608
24609 With the macros below, the |char_info| word for character~|c| in font~|f| is
24610 |char_info(f)(c)| and the width is
24611 $$\hbox{|char_width(f)(char_info(f)(c)).sc|.}$$
24612
24613 @d char_info_end(A) (A)].qqqq
24614 @d char_info(A) mp->font_info[mp->char_base[(A)]+char_info_end
24615 @d char_width_end(A) (A).b0].sc
24616 @d char_width(A) mp->font_info[mp->width_base[(A)]+char_width_end
24617 @d char_height_end(A) (A).b1].sc
24618 @d char_height(A) mp->font_info[mp->height_base[(A)]+char_height_end
24619 @d char_depth_end(A) (A).b2].sc
24620 @d char_depth(A) mp->font_info[mp->depth_base[(A)]+char_depth_end
24621 @d ichar_exists(A) ((A).b0>0)
24622
24623 @ The |font_ps_name| for a built-in font should be what PostScript expects.
24624 A preliminary name is obtained here from the \.{TFM} name as given in the
24625 |fname| argument.  This gets updated later from an external table if necessary.
24626
24627 @<Declare text measuring subroutines@>=
24628 @<Declare subroutines for parsing file names@>;
24629 font_number mp_read_font_info (MP mp, char *fname) {
24630   boolean file_opened; /* has |tfm_infile| been opened? */
24631   font_number n; /* the number to return */
24632   halfword lf,tfm_lh,bc,ec,nw,nh,nd; /* subfile size parameters */
24633   size_t whd_size; /* words needed for heights, widths, and depths */
24634   int i,ii; /* |font_info| indices */
24635   int jj; /* counts bytes to be ignored */
24636   scaled z; /* used to compute the design size */
24637   fraction d;
24638   /* height, width, or depth as a fraction of design size times $2^{-8}$ */
24639   eight_bits h_and_d; /* height and depth indices being unpacked */
24640   unsigned char tfbyte; /* a byte read from the file */
24641   n=null_font;
24642   @<Open |tfm_infile| for input@>;
24643   @<Read data from |tfm_infile|; if there is no room, say so and |goto done|;
24644     otherwise |goto bad_tfm| or |goto done| as appropriate@>;
24645 BAD_TFM:
24646   @<Complain that the \.{TFM} file is bad@>;
24647 DONE:
24648   if ( file_opened ) (mp->close_file)(mp->tfm_infile);
24649   if ( n!=null_font ) { 
24650     mp->font_ps_name[n]=mp_xstrdup(mp,fname);
24651     mp->font_name[n]=mp_xstrdup(mp,fname);
24652   }
24653   return n;
24654 }
24655
24656 @ \MP\ doesn't bother to check the entire \.{TFM} file for errors or explain
24657 precisely what is wrong if it does find a problem.  Programs called \.{TFtoPL}
24658 @.TFtoPL@> @.PLtoTF@>
24659 and \.{PLtoTF} can be used to debug \.{TFM} files.
24660
24661 @<Complain that the \.{TFM} file is bad@>=
24662 print_err("Font ");
24663 mp_print(mp, fname);
24664 if ( file_opened ) mp_print(mp, " not usable: TFM file is bad");
24665 else mp_print(mp, " not usable: TFM file not found");
24666 help3("I wasn't able to read the size data for this font so this")
24667   ("`infont' operation won't produce anything. If the font name")
24668   ("is right, you might ask an expert to make a TFM file");
24669 if ( file_opened )
24670   mp->help_line[0]="is right, try asking an expert to fix the TFM file";
24671 mp_error(mp)
24672
24673 @ @<Read data from |tfm_infile|; if there is no room, say so...@>=
24674 @<Read the \.{TFM} size fields@>;
24675 @<Use the size fields to allocate space in |font_info|@>;
24676 @<Read the \.{TFM} header@>;
24677 @<Read the character data and the width, height, and depth tables and
24678   |goto done|@>
24679
24680 @ A bad \.{TFM} file can be shorter than it claims to be.  The code given here
24681 might try to read past the end of the file if this happens.  Changes will be
24682 needed if it causes a system error to refer to |tfm_infile^| or call
24683 |get_tfm_infile| when |eof(tfm_infile)| is true.  For example, the definition
24684 @^system dependencies@>
24685 of |tfget| could be changed to
24686 ``|begin get(tfm_infile); if eof(tfm_infile) then goto bad_tfm; end|.''
24687
24688 @d tfget do { 
24689   size_t wanted=1; 
24690   void *tfbyte_ptr = &tfbyte;
24691   (mp->read_binary_file)(mp->tfm_infile,&tfbyte_ptr,&wanted); 
24692   if (wanted==0) goto BAD_TFM; 
24693 } while (0)
24694 @d read_two(A) { (A)=tfbyte;
24695   if ( (A)>127 ) goto BAD_TFM;
24696   tfget; (A)=(A)*0400+tfbyte;
24697 }
24698 @d tf_ignore(A) { for (jj=(A);jj>=1;jj--) tfget; }
24699
24700 @<Read the \.{TFM} size fields@>=
24701 tfget; read_two(lf);
24702 tfget; read_two(tfm_lh);
24703 tfget; read_two(bc);
24704 tfget; read_two(ec);
24705 if ( (bc>1+ec)||(ec>255) ) goto BAD_TFM;
24706 tfget; read_two(nw);
24707 tfget; read_two(nh);
24708 tfget; read_two(nd);
24709 whd_size=(ec+1-bc)+nw+nh+nd;
24710 if ( lf<(int)(6+tfm_lh+whd_size) ) goto BAD_TFM;
24711 tf_ignore(10)
24712
24713 @ Offsets are added to |char_base[n]| and |width_base[n]| so that is not
24714 necessary to apply the |so|  and |qo| macros when looking up the width of a
24715 character in the string pool.  In order to ensure nonnegative |char_base|
24716 values when |bc>0|, it may be necessary to reserve a few unused |font_info|
24717 elements.
24718
24719 @<Use the size fields to allocate space in |font_info|@>=
24720 if ( mp->next_fmem<bc) mp->next_fmem=bc;  /* ensure nonnegative |char_base| */
24721 if (mp->last_fnum==mp->font_max)
24722   mp_reallocate_fonts(mp,(mp->font_max+(mp->font_max>>2)));
24723 while (mp->next_fmem+whd_size>=mp->font_mem_size) {
24724   size_t l = mp->font_mem_size+(mp->font_mem_size>>2);
24725   memory_word *font_info;
24726   font_info = xmalloc ((l+1),sizeof(memory_word));
24727   memset (font_info,0,sizeof(memory_word)*(l+1));
24728   memcpy (font_info,mp->font_info,sizeof(memory_word)*(mp->font_mem_size+1));
24729   xfree(mp->font_info);
24730   mp->font_info = font_info;
24731   mp->font_mem_size = l;
24732 }
24733 incr(mp->last_fnum);
24734 n=mp->last_fnum;
24735 mp->font_bc[n]=bc;
24736 mp->font_ec[n]=ec;
24737 mp->char_base[n]=mp->next_fmem-bc;
24738 mp->width_base[n]=mp->next_fmem+ec-bc+1;
24739 mp->height_base[n]=mp->width_base[n]+nw;
24740 mp->depth_base[n]=mp->height_base[n]+nh;
24741 mp->next_fmem=mp->next_fmem+whd_size;
24742
24743
24744 @ @<Read the \.{TFM} header@>=
24745 if ( tfm_lh<2 ) goto BAD_TFM;
24746 tf_ignore(4);
24747 tfget; read_two(z);
24748 tfget; z=z*0400+tfbyte;
24749 tfget; z=z*0400+tfbyte; /* now |z| is 16 times the design size */
24750 mp->font_dsize[n]=mp_take_fraction(mp, z,267432584);
24751   /* times ${72\over72.27}2^{28}$ to convert from \TeX\ points */
24752 tf_ignore(4*(tfm_lh-2))
24753
24754 @ @<Read the character data and the width, height, and depth tables...@>=
24755 ii=mp->width_base[n];
24756 i=mp->char_base[n]+bc;
24757 while ( i<ii ) { 
24758   tfget; mp->font_info[i].qqqq.b0=qi(tfbyte);
24759   tfget; h_and_d=tfbyte;
24760   mp->font_info[i].qqqq.b1=h_and_d / 16;
24761   mp->font_info[i].qqqq.b2=h_and_d % 16;
24762   tfget; tfget;
24763   incr(i);
24764 }
24765 while ( i<mp->next_fmem ) {
24766   @<Read a four byte dimension, scale it by the design size, store it in
24767     |font_info[i]|, and increment |i|@>;
24768 }
24769 goto DONE
24770
24771 @ The raw dimension read into |d| should have magnitude at most $2^{24}$ when
24772 interpreted as an integer, and this includes a scale factor of $2^{20}$.  Thus
24773 we can multiply it by sixteen and think of it as a |fraction| that has been
24774 divided by sixteen.  This cancels the extra scale factor contained in
24775 |font_dsize[n|.
24776
24777 @<Read a four byte dimension, scale it by the design size, store it in...@>=
24778
24779 tfget; d=tfbyte;
24780 if ( d>=0200 ) d=d-0400;
24781 tfget; d=d*0400+tfbyte;
24782 tfget; d=d*0400+tfbyte;
24783 tfget; d=d*0400+tfbyte;
24784 mp->font_info[i].sc=mp_take_fraction(mp, d*16,mp->font_dsize[n]);
24785 incr(i);
24786 }
24787
24788 @ This function does no longer use the file name parser, because |fname| is
24789 a C string already.
24790 @<Open |tfm_infile| for input@>=
24791 file_opened=false;
24792 mp_ptr_scan_file(mp, fname);
24793 if ( strlen(mp->cur_area)==0 ) { xfree(mp->cur_area); mp->cur_area=xstrdup(MP_font_area);}
24794 if ( strlen(mp->cur_ext)==0 )  { xfree(mp->cur_ext); mp->cur_ext=xstrdup(".tfm"); }
24795 pack_cur_name;
24796 mp->tfm_infile = (mp->open_file)( mp->name_of_file, "rb",mp_filetype_metrics);
24797 if ( !mp->tfm_infile  ) goto BAD_TFM;
24798 file_opened=true
24799
24800 @ When we have a font name and we don't know whether it has been loaded yet,
24801 we scan the |font_name| array before calling |read_font_info|.
24802
24803 @<Declare text measuring subroutines@>=
24804 font_number mp_find_font (MP mp, char *f) {
24805   font_number n;
24806   for (n=0;n<=mp->last_fnum;n++) {
24807     if (mp_xstrcmp(f,mp->font_name[n])==0 ) {
24808       mp_xfree(f);
24809       return n;
24810     }
24811   }
24812   n = mp_read_font_info(mp, f);
24813   mp_xfree(f);
24814   return n;
24815 }
24816
24817 @ One simple application of |find_font| is the implementation of the |font_size|
24818 operator that gets the design size for a given font name.
24819
24820 @<Find the design size of the font whose name is |cur_exp|@>=
24821 mp_flush_cur_exp(mp, (mp->font_dsize[mp_find_font(mp, str(mp->cur_exp))]+8) / 16)
24822
24823 @ If we discover that the font doesn't have a requested character, we omit it
24824 from the bounding box computation and expect the \ps\ interpreter to drop it.
24825 This routine issues a warning message if the user has asked for it.
24826
24827 @<Declare text measuring subroutines@>=
24828 void mp_lost_warning (MP mp,font_number f, pool_pointer k) { 
24829   if ( mp->internal[mp_tracing_lost_chars]>0 ) { 
24830     mp_begin_diagnostic(mp);
24831     if ( mp->selector==log_only ) incr(mp->selector);
24832     mp_print_nl(mp, "Missing character: There is no ");
24833 @.Missing character@>
24834     mp_print_str(mp, mp->str_pool[k]); 
24835     mp_print(mp, " in font ");
24836     mp_print(mp, mp->font_name[f]); mp_print_char(mp, '!'); 
24837     mp_end_diagnostic(mp, false);
24838   }
24839 }
24840
24841 @ The whole purpose of saving the height, width, and depth information is to be
24842 able to find the bounding box of an item of text in an edge structure.  The
24843 |set_text_box| procedure takes a text node and adds this information.
24844
24845 @<Declare text measuring subroutines@>=
24846 void mp_set_text_box (MP mp,pointer p) {
24847   font_number f; /* |font_n(p)| */
24848   ASCII_code bc,ec; /* range of valid characters for font |f| */
24849   pool_pointer k,kk; /* current character and character to stop at */
24850   four_quarters cc; /* the |char_info| for the current character */
24851   scaled h,d; /* dimensions of the current character */
24852   width_val(p)=0;
24853   height_val(p)=-el_gordo;
24854   depth_val(p)=-el_gordo;
24855   f=font_n(p);
24856   bc=mp->font_bc[f];
24857   ec=mp->font_ec[f];
24858   kk=str_stop(text_p(p));
24859   k=mp->str_start[text_p(p)];
24860   while ( k<kk ) {
24861     @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>;
24862   }
24863   @<Set the height and depth to zero if the bounding box is empty@>;
24864 }
24865
24866 @ @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>=
24867
24868   if ( (mp->str_pool[k]<bc)||(mp->str_pool[k]>ec) ) {
24869     mp_lost_warning(mp, f,k);
24870   } else { 
24871     cc=char_info(f)(mp->str_pool[k]);
24872     if ( ! ichar_exists(cc) ) {
24873       mp_lost_warning(mp, f,k);
24874     } else { 
24875       width_val(p)=width_val(p)+char_width(f)(cc);
24876       h=char_height(f)(cc);
24877       d=char_depth(f)(cc);
24878       if ( h>height_val(p) ) height_val(p)=h;
24879       if ( d>depth_val(p) ) depth_val(p)=d;
24880     }
24881   }
24882   incr(k);
24883 }
24884
24885 @ Let's hope modern compilers do comparisons correctly when the difference would
24886 overflow.
24887
24888 @<Set the height and depth to zero if the bounding box is empty@>=
24889 if ( height_val(p)<-depth_val(p) ) { 
24890   height_val(p)=0;
24891   depth_val(p)=0;
24892 }
24893
24894 @ The new primitives fontmapfile and fontmapline.
24895
24896 @<Declare action procedures for use by |do_statement|@>=
24897 void mp_do_mapfile (MP mp) ;
24898 void mp_do_mapline (MP mp) ;
24899
24900 @ @c void mp_do_mapfile (MP mp) { 
24901   mp_get_x_next(mp); mp_scan_expression(mp);
24902   if ( mp->cur_type!=mp_string_type ) {
24903     @<Complain about improper map operation@>;
24904   } else {
24905     mp_map_file(mp,mp->cur_exp);
24906   }
24907 }
24908 void mp_do_mapline (MP mp) { 
24909   mp_get_x_next(mp); mp_scan_expression(mp);
24910   if ( mp->cur_type!=mp_string_type ) {
24911      @<Complain about improper map operation@>;
24912   } else { 
24913      mp_map_line(mp,mp->cur_exp);
24914   }
24915 }
24916
24917 @ @<Complain about improper map operation@>=
24918
24919   exp_err("Unsuitable expression");
24920   help1("Only known strings can be map files or map lines.");
24921   mp_put_get_error(mp);
24922 }
24923
24924 @ To print |scaled| value to PDF output we need some subroutines to ensure
24925 accurary.
24926
24927 @d max_integer   0x7FFFFFFF /* $2^{31}-1$ */
24928
24929 @<Glob...@>=
24930 scaled one_bp; /* scaled value corresponds to 1bp */
24931 scaled one_hundred_bp; /* scaled value corresponds to 100bp */
24932 scaled one_hundred_inch; /* scaled value corresponds to 100in */
24933 integer ten_pow[10]; /* $10^0..10^9$ */
24934 integer scaled_out; /* amount of |scaled| that was taken out in |divide_scaled| */
24935
24936 @ @<Set init...@>=
24937 mp->one_bp = 65782; /* 65781.76 */
24938 mp->one_hundred_bp = 6578176;
24939 mp->one_hundred_inch = 473628672;
24940 mp->ten_pow[0] = 1;
24941 for (i = 1;i<= 9; i++ ) {
24942   mp->ten_pow[i] = 10*mp->ten_pow[i - 1];
24943 }
24944
24945 @ The following function divides |s| by |m|. |dd| is number of decimal digits.
24946
24947 @c scaled mp_divide_scaled (MP mp,scaled s, scaled m, integer  dd) {
24948   scaled q,r;
24949   integer sign,i;
24950   sign = 1;
24951   if ( s < 0 ) { sign = -sign; s = -s; }
24952   if ( m < 0 ) { sign = -sign; m = -m; }
24953   if ( m == 0 )
24954     mp_confusion(mp, "arithmetic: divided by zero");
24955   else if ( m >= (max_integer / 10) )
24956     mp_confusion(mp, "arithmetic: number too big");
24957   q = s / m;
24958   r = s % m;
24959   for (i = 1;i<=dd;i++) {
24960     q = 10*q + (10*r) / m;
24961     r = (10*r) % m;
24962   }
24963   if ( 2*r >= m ) { incr(q); r = r - m; }
24964   mp->scaled_out = sign*(s - (r / mp->ten_pow[dd]));
24965   return (sign*q);
24966 }
24967
24968 @* \[44] Shipping pictures out.
24969 The |ship_out| procedure, to be described below, is given a pointer to
24970 an edge structure. Its mission is to output a file containing the \ps\
24971 description of an edge structure.
24972
24973 @ Each time an edge structure is shipped out we write a new \ps\ output
24974 file named according to the current \&{charcode}.
24975 @:char_code_}{\&{charcode} primitive@>
24976
24977 This is the only backend function that remains in the main |mpost.w| file. 
24978 There are just too many variable accesses needed for status reporting 
24979 etcetera to make it worthwile to move the code to |psout.w|.
24980
24981 @<Internal library declarations@>=
24982 void mp_open_output_file (MP mp) ;
24983
24984 @ @c void mp_open_output_file (MP mp) {
24985   integer c; /* \&{charcode} rounded to the nearest integer */
24986   int old_setting; /* previous |selector| setting */
24987   pool_pointer i; /*  indexes into |filename_template|  */
24988   integer cc; /* a temporary integer for template building  */
24989   integer f,g=0; /* field widths */
24990   if ( mp->job_name==NULL ) mp_open_log_file(mp);
24991   c=mp_round_unscaled(mp, mp->internal[mp_char_code]);
24992   if ( mp->filename_template==0 ) {
24993     char *s; /* a file extension derived from |c| */
24994     if ( c<0 ) 
24995       s=xstrdup(".ps");
24996     else 
24997       @<Use |c| to compute the file extension |s|@>;
24998     mp_pack_job_name(mp, s);
24999     xfree(s);
25000     while ( ! mp_a_open_out(mp, (void *)&mp->ps_file, mp_filetype_postscript) )
25001       mp_prompt_file_name(mp, "file name for output",s);
25002   } else { /* initializations */
25003     str_number s, n; /* a file extension derived from |c| */
25004     old_setting=mp->selector; 
25005     mp->selector=new_string;
25006     f = 0;
25007     i = mp->str_start[mp->filename_template];
25008     n = rts(""); /* initialize */
25009     while ( i<str_stop(mp->filename_template) ) {
25010        if ( mp->str_pool[i]=='%' ) {
25011       CONTINUE:
25012         incr(i);
25013         if ( i<str_stop(mp->filename_template) ) {
25014           if ( mp->str_pool[i]=='j' ) {
25015             mp_print(mp, mp->job_name);
25016           } else if ( mp->str_pool[i]=='d' ) {
25017              cc= mp_round_unscaled(mp, mp->internal[mp_day]);
25018              print_with_leading_zeroes(cc);
25019           } else if ( mp->str_pool[i]=='m' ) {
25020              cc= mp_round_unscaled(mp, mp->internal[mp_month]);
25021              print_with_leading_zeroes(cc);
25022           } else if ( mp->str_pool[i]=='y' ) {
25023              cc= mp_round_unscaled(mp, mp->internal[mp_year]);
25024              print_with_leading_zeroes(cc);
25025           } else if ( mp->str_pool[i]=='H' ) {
25026              cc= mp_round_unscaled(mp, mp->internal[mp_time]) / 60;
25027              print_with_leading_zeroes(cc);
25028           }  else if ( mp->str_pool[i]=='M' ) {
25029              cc= mp_round_unscaled(mp, mp->internal[mp_time]) % 60;
25030              print_with_leading_zeroes(cc);
25031           } else if ( mp->str_pool[i]=='c' ) {
25032             if ( c<0 ) mp_print(mp, "ps");
25033             else print_with_leading_zeroes(c);
25034           } else if ( (mp->str_pool[i]>='0') && 
25035                       (mp->str_pool[i]<='9') ) {
25036             if ( (f<10)  )
25037               f = (f*10) + mp->str_pool[i]-'0';
25038             goto CONTINUE;
25039           } else {
25040             mp_print_str(mp, mp->str_pool[i]);
25041           }
25042         }
25043       } else {
25044         if ( mp->str_pool[i]=='.' )
25045           if (length(n)==0)
25046             n = mp_make_string(mp);
25047         mp_print_str(mp, mp->str_pool[i]);
25048       };
25049       incr(i);
25050     };
25051     s = mp_make_string(mp);
25052     mp->selector= old_setting;
25053     if (length(n)==0) {
25054        n=s;
25055        s=rts("");
25056     };
25057     mp_pack_file_name(mp, str(n),"",str(s));
25058     while ( ! mp_a_open_out(mp, (void *)&mp->ps_file, mp_filetype_postscript) )
25059       mp_prompt_file_name(mp, "file name for output",str(s));
25060     delete_str_ref(n);
25061     delete_str_ref(s);
25062   }
25063   @<Store the true output file name if appropriate@>;
25064   @<Begin the progress report for the output of picture~|c|@>;
25065 }
25066
25067 @ The file extension created here could be up to five characters long in
25068 extreme cases so it may have to be shortened on some systems.
25069 @^system dependencies@>
25070
25071 @<Use |c| to compute the file extension |s|@>=
25072
25073   s = xmalloc(7,1);
25074   snprintf(s,7,".%i",(int)c);
25075 }
25076
25077 @ The user won't want to see all the output file names so we only save the
25078 first and last ones and a count of how many there were.  For this purpose
25079 files are ordered primarily by \&{charcode} and secondarily by order of
25080 creation.
25081 @:char_code_}{\&{charcode} primitive@>
25082
25083 @<Store the true output file name if appropriate@>=
25084 if ((c<mp->first_output_code)&&(mp->first_output_code>=0)) {
25085   mp->first_output_code=c;
25086   xfree(mp->first_file_name);
25087   mp->first_file_name=xstrdup(mp->name_of_file);
25088 }
25089 if ( c>=mp->last_output_code ) {
25090   mp->last_output_code=c;
25091   xfree(mp->last_file_name);
25092   mp->last_file_name=xstrdup(mp->name_of_file);
25093 }
25094
25095 @ @<Glob...@>=
25096 char * first_file_name;
25097 char * last_file_name; /* full file names */
25098 integer first_output_code;integer last_output_code; /* rounded \&{charcode} values */
25099 @:char_code_}{\&{charcode} primitive@>
25100 integer total_shipped; /* total number of |ship_out| operations completed */
25101
25102 @ @<Set init...@>=
25103 mp->first_file_name=xstrdup("");
25104 mp->last_file_name=xstrdup("");
25105 mp->first_output_code=32768;
25106 mp->last_output_code=-32768;
25107 mp->total_shipped=0;
25108
25109 @ @<Dealloc variables@>=
25110 xfree(mp->first_file_name);
25111 xfree(mp->last_file_name);
25112
25113 @ @<Begin the progress report for the output of picture~|c|@>=
25114 if ( (int)mp->term_offset>mp->max_print_line-6 ) mp_print_ln(mp);
25115 else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
25116 mp_print_char(mp, '[');
25117 if ( c>=0 ) mp_print_int(mp, c)
25118
25119 @ @<End progress report@>=
25120 mp_print_char(mp, ']');
25121 update_terminal;
25122 incr(mp->total_shipped)
25123
25124 @ @<Explain what output files were written@>=
25125 if ( mp->total_shipped>0 ) { 
25126   mp_print_nl(mp, "");
25127   mp_print_int(mp, mp->total_shipped);
25128   mp_print(mp, " output file");
25129   if ( mp->total_shipped>1 ) mp_print_char(mp, 's');
25130   mp_print(mp, " written: ");
25131   mp_print(mp, mp->first_file_name);
25132   if ( mp->total_shipped>1 ) {
25133     if ( 31+strlen(mp->first_file_name)+
25134          strlen(mp->last_file_name)> (unsigned)mp->max_print_line) 
25135       mp_print_ln(mp);
25136     mp_print(mp, " .. ");
25137     mp_print(mp, mp->last_file_name);
25138   }
25139 }
25140
25141 @ @<Internal library declarations@>=
25142 boolean mp_has_font_size(MP mp, font_number f );
25143
25144 @ @c 
25145 boolean mp_has_font_size(MP mp, font_number f ) {
25146   return (mp->font_sizes[f]!=null);
25147 }
25148
25149 @ The \&{special} command saves up lines of text to be printed during the next
25150 |ship_out| operation.  The saved items are stored as a list of capsule tokens.
25151
25152 @<Glob...@>=
25153 pointer last_pending; /* the last token in a list of pending specials */
25154
25155 @ @<Set init...@>=
25156 mp->last_pending=spec_head;
25157
25158 @ @<Cases of |do_statement|...@>=
25159 case special_command: 
25160   if ( mp->cur_mod==0 ) mp_do_special(mp); else 
25161   if ( mp->cur_mod==1 ) mp_do_mapfile(mp); else 
25162   mp_do_mapline(mp);
25163   break;
25164
25165 @ @<Declare action procedures for use by |do_statement|@>=
25166 void mp_do_special (MP mp) ;
25167
25168 @ @c void mp_do_special (MP mp) { 
25169   mp_get_x_next(mp); mp_scan_expression(mp);
25170   if ( mp->cur_type!=mp_string_type ) {
25171     @<Complain about improper special operation@>;
25172   } else { 
25173     link(mp->last_pending)=mp_stash_cur_exp(mp);
25174     mp->last_pending=link(mp->last_pending);
25175     link(mp->last_pending)=null;
25176   }
25177 }
25178
25179 @ @<Complain about improper special operation@>=
25180
25181   exp_err("Unsuitable expression");
25182   help1("Only known strings are allowed for output as specials.");
25183   mp_put_get_error(mp);
25184 }
25185
25186 @ On the export side, we need an extra object type for special strings.
25187
25188 @<Graphical object codes@>=
25189 mp_special_code=8, 
25190
25191 @ @<Export pending specials@>=
25192 p=link(spec_head);
25193 while ( p!=null ) {
25194   hq = mp_new_graphic_object(mp,mp_special_code);
25195   gr_pre_script(hq)  = str(value(p));
25196   if (hh->body==NULL) hh->body=hq; else gr_link(hp) = hq;
25197   hp = hq;
25198   p=link(p);
25199 }
25200 mp_flush_token_list(mp, link(spec_head));
25201 link(spec_head)=null;
25202 mp->last_pending=spec_head
25203
25204 @ We are now ready for the main output procedure.  Note that the |selector|
25205 setting is saved in a global variable so that |begin_diagnostic| can access it.
25206
25207 @<Declare the \ps\ output procedures@>=
25208 void mp_ship_out (MP mp, pointer h) ;
25209
25210 @ Once again, the |gr_XXXX| macros are defined in |mppsout.h|
25211
25212 @c
25213 struct mp_edge_object *mp_gr_export(MP mp, pointer h) {
25214   pointer p; /* the current graphical object */
25215   integer t; /* a temporary value */
25216   struct mp_edge_object *hh; /* the first graphical object */
25217   struct mp_graphic_object *hp; /* the current graphical object */
25218   struct mp_graphic_object *hq; /* something |hp| points to  */
25219   mp_set_bbox(mp, h, true);
25220   hh = mp_xmalloc(mp,1,sizeof(struct mp_edge_object));
25221   hh->body = NULL;
25222   hh->_minx = minx_val(h);
25223   hh->_miny = miny_val(h);
25224   hh->_maxx = maxx_val(h);
25225   hh->_maxy = maxy_val(h);
25226   @<Export pending specials@>;
25227   p=link(dummy_loc(h));
25228   while ( p!=null ) { 
25229     hq = mp_new_graphic_object(mp,type(p));
25230     switch (type(p)) {
25231     case mp_fill_code:
25232       gr_pen_p(hq)        = mp_export_knot_list(mp,pen_p(p));
25233       if ((pen_p(p)==null) || pen_is_elliptical(pen_p(p)))  {
25234           gr_path_p(hq)       = mp_export_knot_list(mp,path_p(p));
25235       } else {
25236         pointer pc, pp;
25237         pc = mp_copy_path(mp, path_p(p));
25238         pp = mp_make_envelope(mp, pc, pen_p(p),ljoin_val(p),0,miterlim_val(p));
25239         gr_path_p(hq)       = mp_export_knot_list(mp,pp);
25240         mp_toss_knot_list(mp, pp);
25241         pc = mp_htap_ypoc(mp, path_p(p));
25242         pp = mp_make_envelope(mp, pc, pen_p(p),ljoin_val(p),0,miterlim_val(p));
25243         gr_htap_p(hq)       = mp_export_knot_list(mp,pp);
25244         mp_toss_knot_list(mp, pp);
25245       }
25246       @<Export object color@>;
25247       @<Export object scripts@>;
25248       gr_ljoin_val(hq)    = ljoin_val(p);
25249       gr_miterlim_val(hq) = miterlim_val(p);
25250       break;
25251     case mp_stroked_code:
25252       gr_pen_p(hq)        = mp_export_knot_list(mp,pen_p(p));
25253       if (pen_is_elliptical(pen_p(p)))  {
25254               gr_path_p(hq)       = mp_export_knot_list(mp,path_p(p));
25255       } else {
25256         pointer pc;
25257         pc=mp_copy_path(mp, path_p(p));
25258         t=lcap_val(p);
25259         if ( left_type(pc)!=mp_endpoint ) { 
25260           left_type(mp_insert_knot(mp, pc,x_coord(pc),y_coord(pc)))=mp_endpoint;
25261           right_type(pc)=mp_endpoint;
25262           pc=link(pc);
25263           t=1;
25264         }
25265         pc=mp_make_envelope(mp,pc,pen_p(p),ljoin_val(p),t,miterlim_val(p));
25266         gr_path_p(hq)       = mp_export_knot_list(mp,pc);
25267         mp_toss_knot_list(mp, pc);
25268       }
25269       @<Export object color@>;
25270       @<Export object scripts@>;
25271       gr_ljoin_val(hq)    = ljoin_val(p);
25272       gr_miterlim_val(hq) = miterlim_val(p);
25273       gr_lcap_val(hq)     = lcap_val(p);
25274       gr_dash_scale(hq)   = dash_scale(p);
25275       gr_dash_p(hq)       = mp_export_dashes(mp,dash_p(p));
25276       break;
25277     case mp_text_code:
25278       gr_text_p(hq)       = str(text_p(p));
25279       gr_font_n(hq)       = font_n(p);
25280       @<Export object color@>;
25281       @<Export object scripts@>;
25282       gr_width_val(hq)    = width_val(p);
25283       gr_height_val(hq)   = height_val(p);
25284       gr_depth_val(hq)    = depth_val(p);
25285       gr_tx_val(hq)       = tx_val(p);
25286       gr_ty_val(hq)       = ty_val(p);
25287       gr_txx_val(hq)      = txx_val(p);
25288       gr_txy_val(hq)      = txy_val(p);
25289       gr_tyx_val(hq)      = tyx_val(p);
25290       gr_tyy_val(hq)      = tyy_val(p);
25291       break;
25292     case mp_start_clip_code: 
25293     case mp_start_bounds_code:
25294       gr_path_p(hq) = mp_export_knot_list(mp,path_p(p));
25295       break;
25296     case mp_stop_clip_code: 
25297     case mp_stop_bounds_code:
25298       /* nothing to do here */
25299       break;
25300     } 
25301     if (hh->body==NULL) hh->body=hq; else  gr_link(hp) = hq;
25302     hp = hq;
25303     p=link(p);
25304   }
25305   return hh;
25306 }
25307
25308 @ @<Exported function ...@>=
25309 struct mp_edge_object *mp_gr_export(MP mp, int h);
25310 extern void mp_gr_ship_out (MP mp, struct mp_edge_object *hh) ;
25311
25312 @ This function is now nearly trivial.
25313
25314 @c
25315 void mp_ship_out (MP mp, pointer h) { /* output edge structure |h| */
25316   (mp->shipout_backend) (mp, h);
25317   @<End progress report@>;
25318   if ( mp->internal[mp_tracing_output]>0 ) 
25319    mp_print_edges(mp, h," (just shipped out)",true);
25320 }
25321
25322 @ @<Declarations@>=
25323 void mp_shipout_backend (MP mp, pointer h);
25324
25325 @ @c
25326 void mp_shipout_backend (MP mp, pointer h) {
25327   struct mp_edge_object *hh; /* the first graphical object */
25328   hh = mp_gr_export(mp,h);
25329   mp_gr_ship_out (mp, hh);
25330   mp_xfree(hh);
25331 }
25332
25333 @ @<Exported types@>=
25334 typedef void (*mp_backend_writer)(MP, int);
25335
25336 @ @<Glob...@>=
25337 mp_backend_writer shipout_backend;
25338
25339 @ @<Option variables@>=
25340 mp_backend_writer shipout_backend;
25341
25342 @ @<Allocate or initialize ...@>=
25343 set_callback_option(shipout_backend);
25344
25345
25346
25347 @ Once again, the |gr_XXXX| macros are defined in |mppsout.h|
25348
25349 @<Export object color@>=
25350 gr_color_model(hq)  = color_model(p);
25351 gr_cyan_val(hq)     = cyan_val(p);
25352 gr_magenta_val(hq)  = magenta_val(p);
25353 gr_yellow_val(hq)   = yellow_val(p);
25354 gr_black_val(hq)    = black_val(p);
25355 gr_red_val(hq)      = red_val(p);
25356 gr_green_val(hq)    = green_val(p);
25357 gr_blue_val(hq)     = blue_val(p);
25358 gr_grey_val(hq)     = grey_val(p)
25359
25360
25361 @ @<Export object scripts@>=
25362 if (pre_script(p)!=null)
25363   gr_pre_script(hq)   = str(pre_script(p));
25364 if (post_script(p)!=null)
25365   gr_post_script(hq)  = str(post_script(p));
25366
25367 @ Now that we've finished |ship_out|, let's look at the other commands
25368 by which a user can send things to the \.{GF} file.
25369
25370 @ @<Determine if a character has been shipped out@>=
25371
25372   mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256;
25373   if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
25374   boolean_reset(mp->char_exists[mp->cur_exp]);
25375   mp->cur_type=mp_boolean_type;
25376 }
25377
25378 @ @<Glob...@>=
25379 psout_data ps;
25380
25381 @ @<Allocate or initialize ...@>=
25382 mp_backend_initialize(mp);
25383
25384 @ @<Dealloc...@>=
25385 mp_backend_free(mp);
25386
25387
25388 @* \[45] Dumping and undumping the tables.
25389 After \.{INIMP} has seen a collection of macros, it
25390 can write all the necessary information on an auxiliary file so
25391 that production versions of \MP\ are able to initialize their
25392 memory at high speed. The present section of the program takes
25393 care of such output and input. We shall consider simultaneously
25394 the processes of storing and restoring,
25395 so that the inverse relation between them is clear.
25396 @.INIMP@>
25397
25398 The global variable |mem_ident| is a string that is printed right
25399 after the |banner| line when \MP\ is ready to start. For \.{INIMP} this
25400 string says simply `\.{(INIMP)}'; for other versions of \MP\ it says,
25401 for example, `\.{(mem=plain 90.4.14)}', showing the year,
25402 month, and day that the mem file was created. We have |mem_ident=0|
25403 before \MP's tables are loaded.
25404
25405 @<Glob...@>=
25406 char * mem_ident;
25407
25408 @ @<Set init...@>=
25409 mp->mem_ident=NULL;
25410
25411 @ @<Initialize table entries...@>=
25412 mp->mem_ident=xstrdup(" (INIMP)");
25413
25414 @ @<Declare act...@>=
25415 void mp_store_mem_file (MP mp) ;
25416
25417 @ @c void mp_store_mem_file (MP mp) {
25418   integer k;  /* all-purpose index */
25419   pointer p,q; /* all-purpose pointers */
25420   integer x; /* something to dump */
25421   four_quarters w; /* four ASCII codes */
25422   memory_word WW;
25423   @<Create the |mem_ident|, open the mem file,
25424     and inform the user that dumping has begun@>;
25425   @<Dump constants for consistency check@>;
25426   @<Dump the string pool@>;
25427   @<Dump the dynamic memory@>;
25428   @<Dump the table of equivalents and the hash table@>;
25429   @<Dump a few more things and the closing check word@>;
25430   @<Close the mem file@>;
25431 }
25432
25433 @ Corresponding to the procedure that dumps a mem file, we also have a function
25434 that reads~one~in. The function returns |false| if the dumped mem is
25435 incompatible with the present \MP\ table sizes, etc.
25436
25437 @d off_base 6666 /* go here if the mem file is unacceptable */
25438 @d too_small(A) { wake_up_terminal;
25439   wterm_ln("---! Must increase the "); wterm((A));
25440 @.Must increase the x@>
25441   goto OFF_BASE;
25442   }
25443
25444 @c 
25445 boolean mp_load_mem_file (MP mp) {
25446   integer k; /* all-purpose index */
25447   pointer p,q; /* all-purpose pointers */
25448   integer x; /* something undumped */
25449   str_number s; /* some temporary string */
25450   four_quarters w; /* four ASCII codes */
25451   memory_word WW;
25452   @<Undump constants for consistency check@>;
25453   @<Undump the string pool@>;
25454   @<Undump the dynamic memory@>;
25455   @<Undump the table of equivalents and the hash table@>;
25456   @<Undump a few more things and the closing check word@>;
25457   return true; /* it worked! */
25458 OFF_BASE: 
25459   wake_up_terminal;
25460   wterm_ln("(Fatal mem file error; I'm stymied)\n");
25461 @.Fatal mem file error@>
25462    return false;
25463 }
25464
25465 @ @<Declarations@>=
25466 boolean mp_load_mem_file (MP mp) ;
25467
25468 @ Mem files consist of |memory_word| items, and we use the following
25469 macros to dump words of different types:
25470
25471 @d dump_wd(A)   { WW=(A);       (mp->write_binary_file)(mp->mem_file,&WW,sizeof(WW)); }
25472 @d dump_int(A)  { int cint=(A); (mp->write_binary_file)(mp->mem_file,&cint,sizeof(cint)); }
25473 @d dump_hh(A)   { WW.hh=(A);    (mp->write_binary_file)(mp->mem_file,&WW,sizeof(WW)); }
25474 @d dump_qqqq(A) { WW.qqqq=(A);  (mp->write_binary_file)(mp->mem_file,&WW,sizeof(WW)); }
25475 @d dump_string(A) { dump_int(strlen(A)+1);
25476                     (mp->write_binary_file)(mp->mem_file,A,strlen(A)+1); }
25477
25478 @<Glob...@>=
25479 void * mem_file; /* for input or output of mem information */
25480
25481 @ The inverse macros are slightly more complicated, since we need to check
25482 the range of the values we are reading in. We say `|undump(a)(b)(x)|' to
25483 read an integer value |x| that is supposed to be in the range |a<=x<=b|.
25484
25485 @d mgeti(A) do {
25486   size_t wanted = sizeof(A);
25487   void *A_ptr = &A;
25488   (mp->read_binary_file)(mp->mem_file,&A_ptr,&wanted);
25489   if (wanted!=sizeof(A)) goto OFF_BASE;
25490 } while (0)
25491
25492 @d mgetw(A) do {
25493   size_t wanted = sizeof(A);
25494   void *A_ptr = &A;
25495   (mp->read_binary_file)(mp->mem_file,&A_ptr,&wanted);
25496   if (wanted!=sizeof(A)) goto OFF_BASE;
25497 } while (0)
25498
25499 @d undump_wd(A)   { mgetw(WW); A=WW; }
25500 @d undump_int(A)  { int cint; mgeti(cint); A=cint; }
25501 @d undump_hh(A)   { mgetw(WW); A=WW.hh; }
25502 @d undump_qqqq(A) { mgetw(WW); A=WW.qqqq; }
25503 @d undump_strings(A,B,C) { 
25504    undump_int(x); if ( (x<(A)) || (x>(B)) ) goto OFF_BASE; else C=str(x); }
25505 @d undump(A,B,C) { undump_int(x); if ( (x<(A)) || (x>(int)(B)) ) goto OFF_BASE; else C=x; }
25506 @d undump_size(A,B,C,D) { undump_int(x);
25507                           if (x<(A)) goto OFF_BASE; 
25508                           if (x>(B)) { too_small((C)); } else { D=x;} }
25509 @d undump_string(A) do { 
25510   size_t wanted; 
25511   integer XX=0; 
25512   undump_int(XX);
25513   wanted = XX;
25514   A = xmalloc(XX,sizeof(char));
25515   (mp->read_binary_file)(mp->mem_file,(void **)&A,&wanted);
25516   if (wanted!=(size_t)XX) goto OFF_BASE;
25517 } while (0)
25518
25519 @ The next few sections of the program should make it clear how we use the
25520 dump/undump macros.
25521
25522 @<Dump constants for consistency check@>=
25523 dump_int(mp->mem_top);
25524 dump_int(mp->hash_size);
25525 dump_int(mp->hash_prime)
25526 dump_int(mp->param_size);
25527 dump_int(mp->max_in_open);
25528
25529 @ Sections of a \.{WEB} program that are ``commented out'' still contribute
25530 strings to the string pool; therefore \.{INIMP} and \MP\ will have
25531 the same strings. (And it is, of course, a good thing that they do.)
25532 @.WEB@>
25533 @^string pool@>
25534
25535 @<Undump constants for consistency check@>=
25536 undump_int(x); mp->mem_top = x;
25537 undump_int(x); if (mp->hash_size != x) goto OFF_BASE;
25538 undump_int(x); if (mp->hash_prime != x) goto OFF_BASE;
25539 undump_int(x); if (mp->param_size != x) goto OFF_BASE;
25540 undump_int(x); if (mp->max_in_open != x) goto OFF_BASE
25541
25542 @ We do string pool compaction to avoid dumping unused strings.
25543
25544 @d dump_four_ASCII 
25545   w.b0=qi(mp->str_pool[k]); w.b1=qi(mp->str_pool[k+1]);
25546   w.b2=qi(mp->str_pool[k+2]); w.b3=qi(mp->str_pool[k+3]);
25547   dump_qqqq(w)
25548
25549 @<Dump the string pool@>=
25550 mp_do_compaction(mp, mp->pool_size);
25551 dump_int(mp->pool_ptr);
25552 dump_int(mp->max_str_ptr);
25553 dump_int(mp->str_ptr);
25554 k=0;
25555 while ( (mp->next_str[k]==k+1) && (k<=mp->max_str_ptr) ) 
25556   incr(k);
25557 dump_int(k);
25558 while ( k<=mp->max_str_ptr ) { 
25559   dump_int(mp->next_str[k]); incr(k);
25560 }
25561 k=0;
25562 while (1)  { 
25563   dump_int(mp->str_start[k]); /* TODO: valgrind warning here */
25564   if ( k==mp->str_ptr ) {
25565     break;
25566   } else { 
25567     k=mp->next_str[k]; 
25568   }
25569 };
25570 k=0;
25571 while (k+4<mp->pool_ptr ) { 
25572   dump_four_ASCII; k=k+4; 
25573 }
25574 k=mp->pool_ptr-4; dump_four_ASCII;
25575 mp_print_ln(mp); mp_print(mp, "at most "); mp_print_int(mp, mp->max_str_ptr);
25576 mp_print(mp, " strings of total length ");
25577 mp_print_int(mp, mp->pool_ptr)
25578
25579 @ @d undump_four_ASCII 
25580   undump_qqqq(w);
25581   mp->str_pool[k]=qo(w.b0); mp->str_pool[k+1]=qo(w.b1);
25582   mp->str_pool[k+2]=qo(w.b2); mp->str_pool[k+3]=qo(w.b3)
25583
25584 @<Undump the string pool@>=
25585 undump_int(mp->pool_ptr);
25586 mp_reallocate_pool(mp, mp->pool_ptr) ;
25587 undump_int(mp->max_str_ptr);
25588 mp_reallocate_strings (mp,mp->max_str_ptr) ;
25589 undump(0,mp->max_str_ptr,mp->str_ptr);
25590 undump(0,mp->max_str_ptr+1,s);
25591 for (k=0;k<=s-1;k++) 
25592   mp->next_str[k]=k+1;
25593 for (k=s;k<=mp->max_str_ptr;k++) 
25594   undump(s+1,mp->max_str_ptr+1,mp->next_str[k]);
25595 mp->fixed_str_use=0;
25596 k=0;
25597 while (1) { 
25598   undump(0,mp->pool_ptr,mp->str_start[k]);
25599   if ( k==mp->str_ptr ) break;
25600   mp->str_ref[k]=max_str_ref;
25601   incr(mp->fixed_str_use);
25602   mp->last_fixed_str=k; k=mp->next_str[k];
25603 }
25604 k=0;
25605 while ( k+4<mp->pool_ptr ) { 
25606   undump_four_ASCII; k=k+4;
25607 }
25608 k=mp->pool_ptr-4; undump_four_ASCII;
25609 mp->init_str_use=mp->fixed_str_use; mp->init_pool_ptr=mp->pool_ptr;
25610 mp->max_pool_ptr=mp->pool_ptr;
25611 mp->strs_used_up=mp->fixed_str_use;
25612 mp->pool_in_use=mp->str_start[mp->str_ptr]; mp->strs_in_use=mp->fixed_str_use;
25613 mp->max_pl_used=mp->pool_in_use; mp->max_strs_used=mp->strs_in_use;
25614 mp->pact_count=0; mp->pact_chars=0; mp->pact_strs=0;
25615
25616 @ By sorting the list of available spaces in the variable-size portion of
25617 |mem|, we are usually able to get by without having to dump very much
25618 of the dynamic memory.
25619
25620 We recompute |var_used| and |dyn_used|, so that \.{INIMP} dumps valid
25621 information even when it has not been gathering statistics.
25622
25623 @<Dump the dynamic memory@>=
25624 mp_sort_avail(mp); mp->var_used=0;
25625 dump_int(mp->lo_mem_max); dump_int(mp->rover);
25626 p=0; q=mp->rover; x=0;
25627 do {  
25628   for (k=p;k<= q+1;k++) 
25629     dump_wd(mp->mem[k]);
25630   x=x+q+2-p; mp->var_used=mp->var_used+q-p;
25631   p=q+node_size(q); q=rlink(q);
25632 } while (q!=mp->rover);
25633 mp->var_used=mp->var_used+mp->lo_mem_max-p; 
25634 mp->dyn_used=mp->mem_end+1-mp->hi_mem_min;
25635 for (k=p;k<= mp->lo_mem_max;k++ ) 
25636   dump_wd(mp->mem[k]);
25637 x=x+mp->lo_mem_max+1-p;
25638 dump_int(mp->hi_mem_min); dump_int(mp->avail);
25639 for (k=mp->hi_mem_min;k<=mp->mem_end;k++ ) 
25640   dump_wd(mp->mem[k]);
25641 x=x+mp->mem_end+1-mp->hi_mem_min;
25642 p=mp->avail;
25643 while ( p!=null ) { 
25644   decr(mp->dyn_used); p=link(p);
25645 }
25646 dump_int(mp->var_used); dump_int(mp->dyn_used);
25647 mp_print_ln(mp); mp_print_int(mp, x);
25648 mp_print(mp, " memory locations dumped; current usage is ");
25649 mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used)
25650
25651 @ @<Undump the dynamic memory@>=
25652 undump(lo_mem_stat_max+1000,hi_mem_stat_min-1,mp->lo_mem_max);
25653 undump(lo_mem_stat_max+1,mp->lo_mem_max,mp->rover);
25654 p=0; q=mp->rover;
25655 do {  
25656   for (k=p;k<= q+1; k++) 
25657     undump_wd(mp->mem[k]);
25658   p=q+node_size(q);
25659   if ( (p>mp->lo_mem_max)||((q>=rlink(q))&&(rlink(q)!=mp->rover)) ) 
25660     goto OFF_BASE;
25661   q=rlink(q);
25662 } while (q!=mp->rover);
25663 for (k=p;k<=mp->lo_mem_max;k++ ) 
25664   undump_wd(mp->mem[k]);
25665 undump(mp->lo_mem_max+1,hi_mem_stat_min,mp->hi_mem_min);
25666 undump(null,mp->mem_top,mp->avail); mp->mem_end=mp->mem_top;
25667 for (k=mp->hi_mem_min;k<= mp->mem_end;k++) 
25668   undump_wd(mp->mem[k]);
25669 undump_int(mp->var_used); undump_int(mp->dyn_used)
25670
25671 @ A different scheme is used to compress the hash table, since its lower region
25672 is usually sparse. When |text(p)<>0| for |p<=hash_used|, we output three
25673 words: |p|, |hash[p]|, and |eqtb[p]|. The hash table is, of course, densely
25674 packed for |p>=hash_used|, so the remaining entries are output in~a~block.
25675
25676 @<Dump the table of equivalents and the hash table@>=
25677 dump_int(mp->hash_used); 
25678 mp->st_count=frozen_inaccessible-1-mp->hash_used;
25679 for (p=1;p<=mp->hash_used;p++) {
25680   if ( text(p)!=0 ) {
25681      dump_int(p); dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]); incr(mp->st_count);
25682   }
25683 }
25684 for (p=mp->hash_used+1;p<=(int)hash_end;p++) {
25685   dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]);
25686 }
25687 dump_int(mp->st_count);
25688 mp_print_ln(mp); mp_print_int(mp, mp->st_count); mp_print(mp, " symbolic tokens")
25689
25690 @ @<Undump the table of equivalents and the hash table@>=
25691 undump(1,frozen_inaccessible,mp->hash_used); 
25692 p=0;
25693 do {  
25694   undump(p+1,mp->hash_used,p); 
25695   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
25696 } while (p!=mp->hash_used);
25697 for (p=mp->hash_used+1;p<=(int)hash_end;p++ )  { 
25698   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
25699 }
25700 undump_int(mp->st_count)
25701
25702 @ We have already printed a lot of statistics, so we set |mp_tracing_stats:=0|
25703 to prevent them appearing again.
25704
25705 @<Dump a few more things and the closing check word@>=
25706 dump_int(mp->max_internal);
25707 dump_int(mp->int_ptr);
25708 for (k=1;k<= mp->int_ptr;k++ ) { 
25709   dump_int(mp->internal[k]); 
25710   dump_string(mp->int_name[k]);
25711 }
25712 dump_int(mp->start_sym); 
25713 dump_int(mp->interaction); 
25714 dump_string(mp->mem_ident);
25715 dump_int(mp->bg_loc); dump_int(mp->eg_loc); dump_int(mp->serial_no); dump_int(69073);
25716 mp->internal[mp_tracing_stats]=0
25717
25718 @ @<Undump a few more things and the closing check word@>=
25719 undump_int(x);
25720 if (x>mp->max_internal) mp_grow_internals(mp,x);
25721 undump_int(mp->int_ptr);
25722 for (k=1;k<= mp->int_ptr;k++) { 
25723   undump_int(mp->internal[k]);
25724   undump_string(mp->int_name[k]);
25725 }
25726 undump(0,frozen_inaccessible,mp->start_sym);
25727 if (mp->interaction==mp_unspecified_mode) {
25728   undump(mp_unspecified_mode,mp_error_stop_mode,mp->interaction);
25729 } else {
25730   undump(mp_unspecified_mode,mp_error_stop_mode,x);
25731 }
25732 undump_string(mp->mem_ident);
25733 undump(1,hash_end,mp->bg_loc);
25734 undump(1,hash_end,mp->eg_loc);
25735 undump_int(mp->serial_no);
25736 undump_int(x); 
25737 if (x!=69073) goto OFF_BASE
25738
25739 @ @<Create the |mem_ident|...@>=
25740
25741   xfree(mp->mem_ident);
25742   mp->mem_ident = xmalloc(256,1);
25743   snprintf(mp->mem_ident,256," (mem=%s %i.%i.%i)", 
25744            mp->job_name,
25745            (int)(mp_round_unscaled(mp, mp->internal[mp_year]) % 100),
25746            (int)mp_round_unscaled(mp, mp->internal[mp_month]),
25747            (int)mp_round_unscaled(mp, mp->internal[mp_day]));
25748   mp_pack_job_name(mp, mem_extension);
25749   while (! mp_w_open_out(mp, &mp->mem_file) )
25750     mp_prompt_file_name(mp, "mem file name", mem_extension);
25751   mp_print_nl(mp, "Beginning to dump on file ");
25752 @.Beginning to dump...@>
25753   mp_print(mp, mp->name_of_file); 
25754   mp_print_nl(mp, mp->mem_ident);
25755 }
25756
25757 @ @<Dealloc variables@>=
25758 xfree(mp->mem_ident);
25759
25760 @ @<Close the mem file@>=
25761 (mp->close_file)(mp->mem_file)
25762
25763 @* \[46] The main program.
25764 This is it: the part of \MP\ that executes all those procedures we have
25765 written.
25766
25767 Well---almost. We haven't put the parsing subroutines into the
25768 program yet; and we'd better leave space for a few more routines that may
25769 have been forgotten.
25770
25771 @c @<Declare the basic parsing subroutines@>;
25772 @<Declare miscellaneous procedures that were declared |forward|@>;
25773 @<Last-minute procedures@>
25774
25775 @ We've noted that there are two versions of \MP. One, called \.{INIMP},
25776 @.INIMP@>
25777 has to be run first; it initializes everything from scratch, without
25778 reading a mem file, and it has the capability of dumping a mem file.
25779 The other one is called `\.{VIRMP}'; it is a ``virgin'' program that needs
25780 @.VIRMP@>
25781 to input a mem file in order to get started. \.{VIRMP} typically has
25782 a bit more memory capacity than \.{INIMP}, because it does not need the
25783 space consumed by the dumping/undumping routines and the numerous calls on
25784 |primitive|, etc.
25785
25786 The \.{VIRMP} program cannot read a mem file instantaneously, of course;
25787 the best implementations therefore allow for production versions of \MP\ that
25788 not only avoid the loading routine for \PASCAL\ object code, they also have
25789 a mem file pre-loaded. 
25790
25791 @<Glob...@>=
25792 boolean ini_version; /* are we iniMP? */
25793
25794 @ @<Option variables@>=
25795 int ini_version; /* are we iniMP? */
25796
25797 @ @<Set |ini_version|@>=
25798 mp->ini_version = (opt->ini_version ? true : false);
25799
25800 @ Here we do whatever is needed to complete \MP's job gracefully on the
25801 local operating system. The code here might come into play after a fatal
25802 error; it must therefore consist entirely of ``safe'' operations that
25803 cannot produce error messages. For example, it would be a mistake to call
25804 |str_room| or |make_string| at this time, because a call on |overflow|
25805 might lead to an infinite loop.
25806 @^system dependencies@>
25807
25808 This program doesn't bother to close the input files that may still be open.
25809
25810 @<Last-minute...@>=
25811 void mp_close_files_and_terminate (MP mp) {
25812   integer k; /* all-purpose index */
25813   integer LH; /* the length of the \.{TFM} header, in words */
25814   int lk_offset; /* extra words inserted at beginning of |lig_kern| array */
25815   pointer p; /* runs through a list of \.{TFM} dimensions */
25816   @<Close all open files in the |rd_file| and |wr_file| arrays@>;
25817   if ( mp->internal[mp_tracing_stats]>0 )
25818     @<Output statistics about this job@>;
25819   wake_up_terminal; 
25820   @<Do all the finishing work on the \.{TFM} file@>;
25821   @<Explain what output files were written@>;
25822   if ( mp->log_opened ){ 
25823     wlog_cr;
25824     (mp->close_file)(mp->log_file); 
25825     mp->selector=mp->selector-2;
25826     if ( mp->selector==term_only ) {
25827       mp_print_nl(mp, "Transcript written on ");
25828 @.Transcript written...@>
25829       mp_print(mp, mp->log_name); mp_print_char(mp, '.');
25830     }
25831   }
25832   mp_print_ln(mp);
25833   t_close_out;
25834   t_close_in;
25835 }
25836
25837 @ @<Declarations@>=
25838 void mp_close_files_and_terminate (MP mp) ;
25839
25840 @ @<Close all open files in the |rd_file| and |wr_file| arrays@>=
25841 if (mp->rd_fname!=NULL) {
25842   for (k=0;k<=(int)mp->read_files-1;k++ ) {
25843     if ( mp->rd_fname[k]!=NULL ) {
25844       (mp->close_file)(mp->rd_file[k]);
25845    }
25846  }
25847 }
25848 if (mp->wr_fname!=NULL) {
25849   for (k=0;k<=(int)mp->write_files-1;k++) {
25850     if ( mp->wr_fname[k]!=NULL ) {
25851      (mp->close_file)(mp->wr_file[k]);
25852     }
25853   }
25854 }
25855
25856 @ @<Dealloc ...@>=
25857 for (k=0;k<(int)mp->max_read_files;k++ ) {
25858   if ( mp->rd_fname[k]!=NULL ) {
25859     (mp->close_file)(mp->rd_file[k]);
25860     mp_xfree(mp->rd_fname[k]); 
25861   }
25862 }
25863 mp_xfree(mp->rd_file);
25864 mp_xfree(mp->rd_fname);
25865 for (k=0;k<(int)mp->max_write_files;k++) {
25866   if ( mp->wr_fname[k]!=NULL ) {
25867     (mp->close_file)(mp->wr_file[k]);
25868     mp_xfree(mp->wr_fname[k]); 
25869   }
25870 }
25871 mp_xfree(mp->wr_file);
25872 mp_xfree(mp->wr_fname);
25873
25874
25875 @ We want to produce a \.{TFM} file if and only if |mp_fontmaking| is positive.
25876
25877 We reclaim all of the variable-size memory at this point, so that
25878 there is no chance of another memory overflow after the memory capacity
25879 has already been exceeded.
25880
25881 @<Do all the finishing work on the \.{TFM} file@>=
25882 if ( mp->internal[mp_fontmaking]>0 ) {
25883   @<Make the dynamic memory into one big available node@>;
25884   @<Massage the \.{TFM} widths@>;
25885   mp_fix_design_size(mp); mp_fix_check_sum(mp);
25886   @<Massage the \.{TFM} heights, depths, and italic corrections@>;
25887   mp->internal[mp_fontmaking]=0; /* avoid loop in case of fatal error */
25888   @<Finish the \.{TFM} file@>;
25889 }
25890
25891 @ @<Make the dynamic memory into one big available node@>=
25892 mp->rover=lo_mem_stat_max+1; link(mp->rover)=empty_flag; mp->lo_mem_max=mp->hi_mem_min-1;
25893 if ( mp->lo_mem_max-mp->rover>max_halfword ) mp->lo_mem_max=max_halfword+mp->rover;
25894 node_size(mp->rover)=mp->lo_mem_max-mp->rover; 
25895 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
25896 link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null
25897
25898 @ The present section goes directly to the log file instead of using
25899 |print| commands, because there's no need for these strings to take
25900 up |str_pool| memory when a non-{\bf stat} version of \MP\ is being used.
25901
25902 @<Output statistics...@>=
25903 if ( mp->log_opened ) { 
25904   char s[128];
25905   wlog_ln(" ");
25906   wlog_ln("Here is how much of MetaPost's memory you used:");
25907 @.Here is how much...@>
25908   snprintf(s,128," %i string%s out of %i",(int)mp->max_strs_used-mp->init_str_use,
25909           (mp->max_strs_used!=mp->init_str_use+1 ? "s" : ""),
25910           (int)(mp->max_strings-1-mp->init_str_use));
25911   wlog_ln(s);
25912   snprintf(s,128," %i string characters out of %i",
25913            (int)mp->max_pl_used-mp->init_pool_ptr,
25914            (int)mp->pool_size-mp->init_pool_ptr);
25915   wlog_ln(s);
25916   snprintf(s,128," %i words of memory out of %i",
25917            (int)mp->lo_mem_max+mp->mem_end-mp->hi_mem_min+2,
25918            (int)mp->mem_end+1);
25919   wlog_ln(s);
25920   snprintf(s,128," %i symbolic tokens out of %i", (int)mp->st_count, (int)mp->hash_size);
25921   wlog_ln(s);
25922   snprintf(s,128," %ii, %in, %ip, %ib stack positions out of %ii, %in, %ip, %ib",
25923            (int)mp->max_in_stack,(int)mp->int_ptr,
25924            (int)mp->max_param_stack,(int)mp->max_buf_stack+1,
25925            (int)mp->stack_size,(int)mp->max_internal,(int)mp->param_size,(int)mp->buf_size);
25926   wlog_ln(s);
25927   snprintf(s,128," %i string compactions (moved %i characters, %i strings)",
25928           (int)mp->pact_count,(int)mp->pact_chars,(int)mp->pact_strs);
25929   wlog_ln(s);
25930 }
25931
25932 @ We get to the |final_cleanup| routine when \&{end} or \&{dump} has
25933 been scanned.
25934
25935 @<Last-minute...@>=
25936 void mp_final_cleanup (MP mp) {
25937   small_number c; /* 0 for \&{end}, 1 for \&{dump} */
25938   c=mp->cur_mod;
25939   if ( mp->job_name==NULL ) mp_open_log_file(mp);
25940   while ( mp->input_ptr>0 ) {
25941     if ( token_state ) mp_end_token_list(mp);
25942     else  mp_end_file_reading(mp);
25943   }
25944   while ( mp->loop_ptr!=null ) mp_stop_iteration(mp);
25945   while ( mp->open_parens>0 ) { 
25946     mp_print(mp, " )"); decr(mp->open_parens);
25947   };
25948   while ( mp->cond_ptr!=null ) {
25949     mp_print_nl(mp, "(end occurred when ");
25950 @.end occurred...@>
25951     mp_print_cmd_mod(mp, fi_or_else,mp->cur_if);
25952     /* `\.{if}' or `\.{elseif}' or `\.{else}' */
25953     if ( mp->if_line!=0 ) {
25954       mp_print(mp, " on line "); mp_print_int(mp, mp->if_line);
25955     }
25956     mp_print(mp, " was incomplete)");
25957     mp->if_line=if_line_field(mp->cond_ptr);
25958     mp->cur_if=name_type(mp->cond_ptr); mp->cond_ptr=link(mp->cond_ptr);
25959   }
25960   if ( mp->history!=mp_spotless )
25961     if ( ((mp->history==mp_warning_issued)||(mp->interaction<mp_error_stop_mode)) )
25962       if ( mp->selector==term_and_log ) {
25963     mp->selector=term_only;
25964     mp_print_nl(mp, "(see the transcript file for additional information)");
25965 @.see the transcript file...@>
25966     mp->selector=term_and_log;
25967   }
25968   if ( c==1 ) {
25969     if (mp->ini_version) {
25970       mp_store_mem_file(mp); return;
25971     }
25972     mp_print_nl(mp, "(dump is performed only by INIMP)"); return;
25973 @.dump...only by INIMP@>
25974   }
25975 }
25976
25977 @ @<Declarations@>=
25978 void mp_final_cleanup (MP mp) ;
25979 void mp_init_prim (MP mp) ;
25980 void mp_init_tab (MP mp) ;
25981
25982 @ @<Last-minute...@>=
25983 void mp_init_prim (MP mp) { /* initialize all the primitives */
25984   @<Put each...@>;
25985 }
25986 @#
25987 void mp_init_tab (MP mp) { /* initialize other tables */
25988   integer k; /* all-purpose index */
25989   @<Initialize table entries (done by \.{INIMP} only)@>;
25990 }
25991
25992
25993 @ When we begin the following code, \MP's tables may still contain garbage;
25994 the strings might not even be present. Thus we must proceed cautiously to get
25995 bootstrapped in.
25996
25997 But when we finish this part of the program, \MP\ is ready to call on the
25998 |main_control| routine to do its work.
25999
26000 @<Get the first line...@>=
26001
26002   @<Initialize the input routines@>;
26003   if ( (mp->mem_ident==NULL)||(mp->buffer[loc]=='&') ) {
26004     if ( mp->mem_ident!=NULL ) {
26005       mp_do_initialize(mp); /* erase preloaded mem */
26006     }
26007     if ( ! mp_open_mem_file(mp) ) return mp_fatal_error_stop;
26008     if ( ! mp_load_mem_file(mp) ) {
26009       (mp->close_file)(mp->mem_file); 
26010       return mp_fatal_error_stop;
26011     }
26012     (mp->close_file)( mp->mem_file);
26013     while ( (loc<limit)&&(mp->buffer[loc]==' ') ) incr(loc);
26014   }
26015   mp->buffer[limit]='%';
26016   mp_fix_date_and_time(mp);
26017   if (mp->random_seed==0)
26018     mp->random_seed = (mp->internal[mp_time] / unity)+mp->internal[mp_day];
26019   mp_init_randoms(mp, mp->random_seed);
26020   @<Initialize the print |selector|...@>;
26021   if ( loc<limit ) if ( mp->buffer[loc]!='\\' ) 
26022     mp_start_input(mp); /* \&{input} assumed */
26023 }
26024
26025 @ @<Run inimpost commands@>=
26026 {
26027   mp_get_strings_started(mp);
26028   mp_init_tab(mp); /* initialize the tables */
26029   mp_init_prim(mp); /* call |primitive| for each primitive */
26030   mp->init_str_use=mp->str_ptr; mp->init_pool_ptr=mp->pool_ptr;
26031   mp->max_str_ptr=mp->str_ptr; mp->max_pool_ptr=mp->pool_ptr;
26032   mp_fix_date_and_time(mp);
26033 }
26034
26035
26036 @* \[47] Debugging.
26037 Once \MP\ is working, you should be able to diagnose most errors with
26038 the \.{show} commands and other diagnostic features. But for the initial
26039 stages of debugging, and for the revelation of really deep mysteries, you
26040 can compile \MP\ with a few more aids, including the \PASCAL\ runtime
26041 checks and its debugger. An additional routine called |debug_help|
26042 will also come into play when you type `\.D' after an error message;
26043 |debug_help| also occurs just before a fatal error causes \MP\ to succumb.
26044 @^debugging@>
26045 @^system dependencies@>
26046
26047 The interface to |debug_help| is primitive, but it is good enough when used
26048 with a \PASCAL\ debugger that allows you to set breakpoints and to read
26049 variables and change their values. After getting the prompt `\.{debug \#}', you
26050 type either a negative number (this exits |debug_help|), or zero (this
26051 goes to a location where you can set a breakpoint, thereby entering into
26052 dialog with the \PASCAL\ debugger), or a positive number |m| followed by
26053 an argument |n|. The meaning of |m| and |n| will be clear from the
26054 program below. (If |m=13|, there is an additional argument, |l|.)
26055 @.debug \#@>
26056
26057 @<Last-minute...@>=
26058 void mp_debug_help (MP mp) { /* routine to display various things */
26059   integer k;
26060   int l,m,n;
26061   char *aline;
26062   size_t len;
26063   while (1) { 
26064     wake_up_terminal;
26065     mp_print_nl(mp, "debug # (-1 to exit):"); update_terminal;
26066 @.debug \#@>
26067     m = 0;
26068     aline = (mp->read_ascii_file)(mp->term_in, &len);
26069     if (len) { sscanf(aline,"%i",&m); xfree(aline); }
26070     if ( m<=0 )
26071       return;
26072     n = 0 ;
26073     aline = (mp->read_ascii_file)(mp->term_in, &len);
26074     if (len) { sscanf(aline,"%i",&n); xfree(aline); }
26075     switch (m) {
26076     @<Numbered cases for |debug_help|@>;
26077     default: mp_print(mp, "?"); break;
26078     }
26079   }
26080 }
26081
26082 @ @<Numbered cases...@>=
26083 case 1: mp_print_word(mp, mp->mem[n]); /* display |mem[n]| in all forms */
26084   break;
26085 case 2: mp_print_int(mp, info(n));
26086   break;
26087 case 3: mp_print_int(mp, link(n));
26088   break;
26089 case 4: mp_print_int(mp, eq_type(n)); mp_print_char(mp, ':'); mp_print_int(mp, equiv(n));
26090   break;
26091 case 5: mp_print_variable_name(mp, n);
26092   break;
26093 case 6: mp_print_int(mp, mp->internal[n]);
26094   break;
26095 case 7: mp_do_show_dependencies(mp);
26096   break;
26097 case 9: mp_show_token_list(mp, n,null,100000,0);
26098   break;
26099 case 10: mp_print_str(mp, n);
26100   break;
26101 case 11: mp_check_mem(mp, n>0); /* check wellformedness; print new busy locations if |n>0| */
26102   break;
26103 case 12: mp_search_mem(mp, n); /* look for pointers to |n| */
26104   break;
26105 case 13: 
26106   l = 0;  
26107   aline = (mp->read_ascii_file)(mp->term_in, &len);
26108   if (len) { sscanf(aline,"%i",&l); xfree(aline); }
26109   mp_print_cmd_mod(mp, n,l); 
26110   break;
26111 case 14: for (k=0;k<=n;k++) mp_print_str(mp, mp->buffer[k]);
26112   break;
26113 case 15: mp->panicking=! mp->panicking;
26114   break;
26115
26116
26117 @ Saving the filename template
26118
26119 @<Save the filename template@>=
26120
26121   if ( mp->filename_template!=0 ) delete_str_ref(mp->filename_template);
26122   if ( length(mp->cur_exp)==0 ) mp->filename_template=0;
26123   else { 
26124     mp->filename_template=mp->cur_exp; add_str_ref(mp->filename_template);
26125   }
26126 }
26127
26128 @* \[48] System-dependent changes.
26129 This section should be replaced, if necessary, by any special
26130 modification of the program
26131 that are necessary to make \MP\ work at a particular installation.
26132 It is usually best to design your change file so that all changes to
26133 previous sections preserve the section numbering; then everybody's version
26134 will be consistent with the published program. More extensive changes,
26135 which introduce new sections, can be inserted here; then only the index
26136 itself will get a new section number.
26137 @^system dependencies@>
26138
26139 @* \[49] Index.
26140 Here is where you can find all uses of each identifier in the program,
26141 with underlined entries pointing to where the identifier was defined.
26142 If the identifier is only one letter long, however, you get to see only
26143 the underlined entries. {\sl All references are to section numbers instead of
26144 page numbers.}
26145
26146 This index also lists error messages and other aspects of the program
26147 that you might want to look up some day. For example, the entry
26148 for ``system dependencies'' lists all sections that should receive
26149 special attention from people who are installing \MP\ in a new
26150 operating environment. A list of various things that can't happen appears
26151 under ``this can't happen''.
26152 Approximately 25 sections are listed under ``inner loop''; these account
26153 for more than 60\pct! of \MP's running time, exclusive of input and output.