builddir fix
[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 The \PASCAL\ program that follows defines a standard version
43 @:PASCAL}{\PASCAL@>
44 of \MP\ that is designed to be highly portable so that identical output
45 will be obtainable on a great variety of computers.
46
47 The main purpose of the following program is to explain the algorithms of \MP\
48 as clearly as possible. As a result, the program will not necessarily be very
49 efficient when a particular \PASCAL\ compiler has translated it into a
50 particular machine language. However, the program has been written so that it
51 can be tuned to run efficiently in a wide variety of operating environments
52 by making comparatively few changes. Such flexibility is possible because
53 the documentation that follows is written in the \.{WEB} language, which is
54 at a higher level than \PASCAL; the preprocessing step that converts \.{WEB}
55 to \PASCAL\ is able to introduce most of the necessary refinements.
56 Semi-automatic translation to other languages is also feasible, because the
57 program below does not make extensive use of features that are peculiar to
58 \PASCAL.
59
60 A large piece of software like \MP\ has inherent complexity that cannot
61 be reduced below a certain level of difficulty, although each individual
62 part is fairly simple by itself. The \.{WEB} language is intended to make
63 the algorithms as readable as possible, by reflecting the way the
64 individual program pieces fit together and by providing the
65 cross-references that connect different parts. Detailed comments about
66 what is going on, and about why things were done in certain ways, have
67 been liberally sprinkled throughout the program.  These comments explain
68 features of the implementation, but they rarely attempt to explain the
69 \MP\ language itself, since the reader is supposed to be familiar with
70 {\sl The {\logos METAFONT\/}book} as well as the manual
71 @.WEB@>
72 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
73 {\sl A User's Manual for MetaPost}, Computing Science Technical Report 162,
74 AT\AM T Bell Laboratories.
75
76 @ The present implementation is a preliminary version, but the possibilities
77 for new features are limited by the desire to remain as nearly compatible
78 with \MF\ as possible.
79
80 On the other hand, the \.{WEB} description can be extended without changing
81 the core of the program, and it has been designed so that such
82 extensions are not extremely difficult to make.
83 The |banner| string defined here should be changed whenever \MP\
84 undergoes any modifications, so that it will be clear which version of
85 \MP\ might be the guilty party when a problem arises.
86 @^extensions to \MP@>
87 @^system dependencies@>
88
89 @d banner "This is MetaPost, Version 1.002" /* printed when \MP\ starts */
90 @d metapost_version "1.002"
91 @d mplib_version "0.10"
92 @d version_string " (Cweb version 0.10)"
93
94 @ Different \PASCAL s have slightly different conventions, and the present
95 @:PASCAL H}{\ph@>
96 program is expressed in a version of \PASCAL\ that D. E. Knuth used for \MF.
97 Constructions that apply to
98 this particular compiler, which we shall call \ph, should help the
99 reader see how to make an appropriate interface for other systems
100 if necessary. (\ph\ is Charles Hedrick's modification of a compiler
101 @^Hedrick, Charles Locke@>
102 for the DECsystem-10 that was originally developed at the University of
103 Hamburg; cf.\ {\sl SOFTWARE---Practice \AM\ Experience \bf6} (1976),
104 29--42. The \MP\ program below is intended to be adaptable, without
105 extensive changes, to most other versions of \PASCAL\ and commonly used
106 \PASCAL-to-C translators, so it does not fully
107 @:C@>
108 use the admirable features of \ph. Indeed, a conscious effort has been
109 made here to avoid using several idiosyncratic features of standard
110 \PASCAL\ itself, so that most of the code can be translated mechanically
111 into other high-level languages. For example, the `\&{with}' and `\\{new}'
112 features are not used, nor are pointer types, set types, or enumerated
113 scalar types; there are no `\&{var}' parameters, except in the case of files;
114 there are no tag fields on variant records; there are no |real| variables;
115 no procedures are declared local to other procedures.)
116
117 The portions of this program that involve system-dependent code, where
118 changes might be necessary because of differences between \PASCAL\ compilers
119 and/or differences between
120 operating systems, can be identified by looking at the sections whose
121 numbers are listed under `system dependencies' in the index. Furthermore,
122 the index entries for `dirty \PASCAL' list all places where the restrictions
123 of \PASCAL\ have not been followed perfectly, for one reason or another.
124 @^system dependencies@>
125 @^dirty \PASCAL@>
126
127 @ The program begins with a normal \PASCAL\ program heading, whose
128 components will be filled in later, using the conventions of \.{WEB}.
129 @.WEB@>
130 For example, the portion of the program called `\X\glob:Global
131 variables\X' below will be replaced by a sequence of variable declarations
132 that starts in $\section\glob$ of this documentation. In this way, we are able
133 to define each individual global variable when we are prepared to
134 understand what it means; we do not have to define all of the globals at
135 once.  Cross references in $\section\glob$, where it says ``See also
136 sections \gglob, \dots,'' also make it possible to look at the set of
137 all global variables, if desired.  Similar remarks apply to the other
138 portions of the program heading.
139
140 Actually the heading shown here is not quite normal: The |program| line
141 does not mention any |output| file, because \ph\ would ask the \MP\ user
142 to specify a file name if |output| were specified here.
143 @^system dependencies@>
144
145 @d true 1
146 @d false 0
147  
148 @(mpbasictypes.h@>=
149 typedef int boolean;
150 typedef signed int integer;
151 @<Declare helpers@>;
152
153 @ @(mplib.h@>=
154 #include "mpbasictypes.h"
155 #include "mppstypes.h"
156 typedef struct MP_instance * MP;
157 @<Types in the outer block@>
158 @<Constants in the outer block@>
159 typedef struct MP_options {
160   @<Option variables@>
161 } MP_options;
162 typedef struct MP_instance {
163   @<Global variables@>
164 } MP_instance;
165 @<Exported function headers@>
166
167 @ @c 
168 #include <stdio.h>
169 #include <stdlib.h>
170 #include <string.h>
171 #include <stdarg.h>
172 #include <assert.h>
173 #include <unistd.h> /* for access() */
174 #include <time.h> /* for struct tm \& co */
175 #include "avl.h"
176 #include "mplib.h"
177 #include "mppsout.h"
178 @h
179 @<Declarations@>
180 @<Basic printing procedures@>
181 @<Error handling procedures@>
182
183 @ Here are the functions that set up the \MP\ instance.
184
185 @<Declarations@> =
186 @<Declare |mp_reallocate| functions@>;
187 struct MP_options mp_options (void) {
188   struct MP_options *opt;
189   opt = xmalloc(1,sizeof(MP_options));
190   memset (opt,0,sizeof(MP_options));
191   return *opt;
192
193 MP mp_new (struct MP_options opt) {
194   MP mp;
195   mp = xmalloc(1,sizeof(MP_instance));
196   @<Set |ini_version|@>;
197   @<Allocate or initialize variables@>
198   mp_reallocate_paths(mp,1000);
199   mp_reallocate_fonts(mp,8);
200   mp->term_in = stdin;
201   mp->term_out = stdout;
202   return mp;
203 }
204 void mp_free (MP mp) {
205   int k; /* loop variable */
206   @<Dealloc variables@>
207   xfree(mp);
208 }
209
210 @ @c
211 boolean mp_initialize (MP mp) { /* this procedure gets things started properly */
212   @<Local variables for initialization@>
213   mp->history=fatal_error_stop; /* in case we quit during initialization */
214   t_open_out; /* open the terminal for output */
215   @<Check the ``constant'' values...@>;
216   if ( mp->bad>0 ) {
217     fprintf(stdout,"Ouch---my internal constants have been clobbered!\n"
218                    "---case %i",(int)mp->bad);
219 @.Ouch...clobbered@>
220     return false;
221   }
222   @<Set initial values of key variables@>
223   if (mp->ini_version) {
224     @<Run inimpost commands@>;
225   }
226   @<Initialize the output routines@>;
227   @<Get the first line of input and prepare to start@>;
228   mp_set_job_id(mp,mp->internal[year],mp->internal[month],
229                        mp->internal[day],mp->internal[mp_time]);
230   mp_init_map_file(mp, mp->troff_mode);
231   mp->history=spotless; /* ready to go! */
232   if (mp->troff_mode) {
233     mp->internal[gtroffmode]=unity; 
234     mp->internal[prologues]=unity; 
235   }
236   if ( mp->start_sym>0 ) { /* insert the `\&{everyjob}' symbol */
237     mp->cur_sym=mp->start_sym; mp_back_input(mp);
238   }
239   return true;
240 }
241
242
243 @<Exported function headers@>=
244 extern struct MP_options mp_options (void);
245 extern MP mp_new (struct MP_options opt) ;
246 extern void mp_free (MP mp);
247 extern boolean mp_initialize (MP mp);
248
249
250 @ The overall \MP\ program begins with the heading just shown, after which
251 comes a bunch of procedure declarations and function declarations.
252 Finally we will get to the main program, which begins with the
253 comment `|start_here|'. If you want to skip down to the
254 main program now, you can look up `|start_here|' in the index.
255 But the author suggests that the best way to understand this program
256 is to follow pretty much the order of \MP's components as they appear in the
257 \.{WEB} description you are now reading, since the present ordering is
258 intended to combine the advantages of the ``bottom up'' and ``top down''
259 approaches to the problem of understanding a somewhat complicated system.
260
261 @ Some of the code below is intended to be used only when diagnosing the
262 strange behavior that sometimes occurs when \MP\ is being installed or
263 when system wizards are fooling around with \MP\ without quite knowing
264 what they are doing. Such code will not normally be compiled; it is
265 delimited by the preprocessor test `|#ifdef DEBUG .. #endif|'.
266
267 @ This program has two important variations: (1) There is a long and slow
268 version called \.{INIMP}, which does the extra calculations needed to
269 @.INIMP@>
270 initialize \MP's internal tables; and (2)~there is a shorter and faster
271 production version, which cuts the initialization to a bare minimum.
272
273 Which is which is decided at runtime.
274
275 @ The following parameters can be changed at compile time to extend or
276 reduce \MP's capacity. They may have different values in \.{INIMP} and
277 in production versions of \MP.
278 @.INIMP@>
279 @^system dependencies@>
280
281 @<Constants...@>=
282 #define file_name_size 255 /* file names shouldn't be longer than this */
283 #define bistack_size 1500 /* size of stack for bisection algorithms;
284   should probably be left at this value */
285
286 @ Like the preceding parameters, the following quantities can be changed
287 at compile time to extend or reduce \MP's capacity. But if they are changed,
288 it is necessary to rerun the initialization program \.{INIMP}
289 @.INIMP@>
290 to generate new tables for the production \MP\ program.
291 One can't simply make helter-skelter changes to the following constants,
292 since certain rather complex initialization
293 numbers are computed from them. 
294
295 @ @<Glob...@>=
296 int max_strings; /* maximum number of strings; must not exceed |max_halfword| */
297 int pool_size; /* maximum number of characters in strings, including all
298   error messages and help texts, and the names of all identifiers */
299 int error_line; /* width of context lines on terminal error messages */
300 int half_error_line; /* width of first lines of contexts in terminal
301   error messages; should be between 30 and |error_line-15| */
302 int max_print_line; /* width of longest text lines output; should be at least 60 */
303 int mem_max; /* greatest index in \MP's internal |mem| array;
304   must be strictly less than |max_halfword|;
305   must be equal to |mem_top| in \.{INIMP}, otherwise |>=mem_top| */
306 int mem_top; /* largest index in the |mem| array dumped by \.{INIMP};
307   must not be greater than |mem_max| */
308 int hash_size; /* maximum number of symbolic tokens,
309   must be less than |max_halfword-3*param_size| */
310 int hash_prime; /* a prime number equal to about 85\pct! of |hash_size| */
311 int param_size; /* maximum number of simultaneous macro parameters */
312 int max_in_open; /* maximum number of input files and error insertions that
313   can be going on simultaneously */
314
315 @ @<Option variables@>=
316 int error_line;
317 int half_error_line;
318 int max_print_line;
319 int main_memory;
320 int hash_size; 
321 int hash_prime; 
322 int param_size; 
323 int max_in_open; 
324
325
326 @d set_value(a,b,c) do { a=c; if (b>c) a=b; } while (0)
327
328 @<Allocate or ...@>=
329 mp->max_strings=500;
330 mp->pool_size=10000;
331 set_value(mp->error_line,opt.error_line,79);
332 set_value(mp->half_error_line,opt.half_error_line,50);
333 set_value(mp->max_print_line,opt.max_print_line,79);
334 mp->mem_max=5000;
335 mp->mem_top=5000;
336 if (opt.main_memory>mp->mem_max)
337   mp_reallocate_memory(mp,opt.main_memory);
338 set_value(mp->hash_size,opt.hash_size,9500);
339 set_value(mp->hash_prime,opt.hash_prime,7919);
340 set_value(mp->param_size,opt.param_size,150);
341 set_value(mp->max_in_open,opt.max_in_open,10);
342
343
344 @ In case somebody has inadvertently made bad settings of the ``constants,''
345 \MP\ checks them using a global variable called |bad|.
346
347 This is the first of many sections of \MP\ where global variables are
348 defined.
349
350 @<Glob...@>=
351 integer bad; /* is some ``constant'' wrong? */
352
353 @ Later on we will say `\ignorespaces|if (mem_max>=max_halfword) bad=10;|',
354 or something similar. (We can't do that until |max_halfword| has been defined.)
355
356 @<Check the ``constant'' values for consistency@>=
357 mp->bad=0;
358 if ( (mp->half_error_line<30)||(mp->half_error_line>mp->error_line-15) ) mp->bad=1;
359 if ( mp->max_print_line<60 ) mp->bad=2;
360 if ( mp->mem_top<=1100 ) mp->bad=4;
361 if (mp->hash_prime>mp->hash_size ) mp->bad=5;
362
363 @ Labels are given symbolic names by the following definitions, so that
364 occasional |goto| statements will be meaningful. We insert the label
365 `|exit|:' just before the `\ignorespaces|end|\unskip' of a procedure in
366 which we have used the `|return|' statement defined below; the label
367 `|restart|' is occasionally used at the very beginning of a procedure; and
368 the label `|reswitch|' is occasionally used just prior to a |case|
369 statement in which some cases change the conditions and we wish to branch
370 to the newly applicable case.  Loops that are set up with the |loop|
371 construction defined below are commonly exited by going to `|done|' or to
372 `|found|' or to `|not_found|', and they are sometimes repeated by going to
373 `|continue|'.  If two or more parts of a subroutine start differently but
374 end up the same, the shared code may be gathered together at
375 `|common_ending|'.
376
377 Incidentally, this program never declares a label that isn't actually used,
378 because some fussy \PASCAL\ compilers will complain about redundant labels.
379
380 @d label_exit 10 /* go here to leave a procedure */
381 @d restart 20 /* go here to start a procedure again */
382 @d reswitch 21 /* go here to start a case statement again */
383 @d continue 22 /* go here to resume a loop */
384 @d done 30 /* go here to exit a loop */
385 @d done1 31 /* like |done|, when there is more than one loop */
386 @d done2 32 /* for exiting the second loop in a long block */
387 @d done3 33 /* for exiting the third loop in a very long block */
388 @d done4 34 /* for exiting the fourth loop in an extremely long block */
389 @d done5 35 /* for exiting the fifth loop in an immense block */
390 @d done6 36 /* for exiting the sixth loop in a block */
391 @d found 40 /* go here when you've found it */
392 @d found1 41 /* like |found|, when there's more than one per routine */
393 @d found2 42 /* like |found|, when there's more than two per routine */
394 @d found3 43 /* like |found|, when there's more than three per routine */
395 @d not_found 45 /* go here when you've found nothing */
396 @d common_ending 50 /* go here when you want to merge with another branch */
397
398 @ Here are some macros for common programming idioms.
399
400 @d incr(A)   (A)=(A)+1 /* increase a variable by unity */
401 @d decr(A)   (A)=(A)-1 /* decrease a variable by unity */
402 @d negate(A)   (A)=-(A) /* change the sign of a variable */
403 @d odd(A)   ((A)%2==1)
404 @d chr(A)   (A)
405 @d do_nothing   /* empty statement */
406 @d Return   goto exit /* terminate a procedure call */
407 @f return   nil /* \.{WEB} will henceforth say |return| instead of \\{return} */
408
409 @* \[2] The character set.
410 In order to make \MP\ readily portable to a wide variety of
411 computers, all of its input text is converted to an internal eight-bit
412 code that includes standard ASCII, the ``American Standard Code for
413 Information Interchange.''  This conversion is done immediately when each
414 character is read in. Conversely, characters are converted from ASCII to
415 the user's external representation just before they are output to a
416 text file.
417 @^ASCII code@>
418
419 Such an internal code is relevant to users of \MP\ only with respect to
420 the \&{char} and \&{ASCII} operations, and the comparison of strings.
421
422 @ Characters of text that have been converted to \MP's internal form
423 are said to be of type |ASCII_code|, which is a subrange of the integers.
424
425 @<Types...@>=
426 typedef unsigned char ASCII_code; /* eight-bit numbers */
427
428 @ The original \PASCAL\ compiler was designed in the late 60s, when six-bit
429 character sets were common, so it did not make provision for lowercase
430 letters. Nowadays, of course, we need to deal with both capital and small
431 letters in a convenient way, especially in a program for font design;
432 so the present specification of \MP\ has been written under the assumption
433 that the \PASCAL\ compiler and run-time system permit the use of text files
434 with more than 64 distinguishable characters. More precisely, we assume that
435 the character set contains at least the letters and symbols associated
436 with ASCII codes 040 through 0176; all of these characters are now
437 available on most computer terminals.
438
439 Since we are dealing with more characters than were present in the first
440 \PASCAL\ compilers, we have to decide what to call the associated data
441 type. Some \PASCAL s use the original name |char| for the
442 characters in text files, even though there now are more than 64 such
443 characters, while other \PASCAL s consider |char| to be a 64-element
444 subrange of a larger data type that has some other name.
445
446 In order to accommodate this difference, we shall use the name |text_char|
447 to stand for the data type of the characters that are converted to and
448 from |ASCII_code| when they are input and output. We shall also assume
449 that |text_char| consists of the elements |chr(first_text_char)| through
450 |chr(last_text_char)|, inclusive. The following definitions should be
451 adjusted if necessary.
452 @^system dependencies@>
453
454 @d first_text_char 0 /* ordinal number of the smallest element of |text_char| */
455 @d last_text_char 255 /* ordinal number of the largest element of |text_char| */
456
457 @<Types...@>=
458 typedef unsigned char text_char; /* the data type of characters in text files */
459
460 @ @<Local variables for init...@>=
461 integer i;
462
463 @ The \MP\ processor converts between ASCII code and
464 the user's external character set by means of arrays |xord| and |xchr|
465 that are analogous to \PASCAL's |ord| and |chr| functions.
466
467 @<Glob...@>=
468 ASCII_code xord[256];  /* specifies conversion of input characters */
469 text_char xchr[256];  /* specifies conversion of output characters */
470
471 @ The core system assumes all 8-bit is acceptable.  If it is not,
472 a change file has to alter the below section.
473 @^system dependencies@>
474
475 Additionally, people with extended character sets can
476 assign codes arbitrarily, giving an |xchr| equivalent to whatever
477 characters the users of \MP\ are allowed to have in their input files.
478 Appropriate changes to \MP's |char_class| table should then be made.
479 (Unlike \TeX, each installation of \MP\ has a fixed assignment of category
480 codes, called the |char_class|.) Such changes make portability of programs
481 more difficult, so they should be introduced cautiously if at all.
482 @^character set dependencies@>
483 @^system dependencies@>
484
485 @<Set initial ...@>=
486 for (i=0;i<=0377;i++) { mp->xchr[i]=i; }
487
488 @ The following system-independent code makes the |xord| array contain a
489 suitable inverse to the information in |xchr|. Note that if |xchr[i]=xchr[j]|
490 where |i<j<0177|, the value of |xord[xchr[i]]| will turn out to be
491 |j| or more; hence, standard ASCII code numbers will be used instead of
492 codes below 040 in case there is a coincidence.
493
494 @<Set initial ...@>=
495 for (i=first_text_char;i<=last_text_char;i++) { 
496    mp->xord[chr(i)]=0177;
497 }
498 for (i=0200;i<=0377;i++) { mp->xord[mp->xchr[i]]=i;}
499 for (i=0;i<=0176;i++) {mp->xord[mp->xchr[i]]=i;}
500
501 @* \[3] Input and output.
502 The bane of portability is the fact that different operating systems treat
503 input and output quite differently, perhaps because computer scientists
504 have not given sufficient attention to this problem. People have felt somehow
505 that input and output are not part of ``real'' programming. Well, it is true
506 that some kinds of programming are more fun than others. With existing
507 input/output conventions being so diverse and so messy, the only sources of
508 joy in such parts of the code are the rare occasions when one can find a
509 way to make the program a little less bad than it might have been. We have
510 two choices, either to attack I/O now and get it over with, or to postpone
511 I/O until near the end. Neither prospect is very attractive, so let's
512 get it over with.
513
514 The basic operations we need to do are (1)~inputting and outputting of
515 text, to or from a file or the user's terminal; (2)~inputting and
516 outputting of eight-bit bytes, to or from a file; (3)~instructing the
517 operating system to initiate (``open'') or to terminate (``close'') input or
518 output from a specified file; (4)~testing whether the end of an input
519 file has been reached; (5)~display of bits on the user's screen.
520 The bit-display operation will be discussed in a later section; we shall
521 deal here only with more traditional kinds of I/O.
522
523 @ Finding files happens in a slightly roundabout fashion: the \MP\
524 instance object contains a field that holds a function pointer that finds a
525 file, and returns its name, or NULL. For this, it receives three
526 parameters: the non-qualified name |fname|, the intended |fopen|
527 operation type |fmode|, and the type of the file |ftype|.
528
529 The file types that are passed on in |ftype| can be  used to 
530 differentiate file searches if a library like kpathsea is used,
531 the fopen mode is passed along for the same reason.
532
533 @<Types...@>=
534 typedef unsigned char eight_bits ; /* unsigned one-byte quantity */
535 enum {
536   mp_filetype_program = 1, /* \MP\ language input */
537   mp_filetype_log,  /* the log file */
538   mp_filetype_postscript, /* the postscript output */
539   mp_filetype_text,  /* text files for readfrom and writeto primitives */
540   mp_filetype_memfile, /* memory dumps */
541   mp_filetype_metrics, /* TeX font metric files */
542   mp_filetype_fontmap, /* PostScript font mapping files */
543   mp_filetype_font, /*  PostScript type1 font programs */
544   mp_filetype_encoding, /*  PostScript font encoding files */
545 };
546 typedef char *(*file_finder)(char *, char *, int);
547
548 @ @<Glob...@>=
549 file_finder find_file;
550
551 @ @<Option variables@>=
552 file_finder find_file;
553
554 @ The default function for finding files is |mp_find_file|. It is 
555 pretty stupid: it will only find files in the current directory.
556
557 @c
558 char *mp_find_file (char *fname, char *fmode, int ftype)  {
559   if (fmode[0] != 'r' || access (fname,R_OK) || ftype)  
560      return xstrdup(fname);
561   return NULL;
562 }
563
564 @ This has to be done very early on, so it is best to put it in with
565 the |mp_new| allocations
566
567 @d set_callback_option(A) do { mp->A = mp_##A;
568   if (opt.A!=NULL) mp->A = opt.A;
569 } while (0)
570
571 @<Allocate or initialize ...@>=
572 set_callback_option(find_file);
573
574 @ Because |mp_find_file| is used so early, it has to be in the helpers
575 section.
576
577 @<Declare helpers@>=
578 char *mp_find_file (char *fname, char *fmode, int ftype) ;
579
580 @ The function to open files can now be very short.
581
582 @c
583 FILE *mp_open_file(MP mp, char *fname, char *fmode, int ftype)  {
584   char *s = (mp->find_file)(fname,fmode,ftype);
585   if (s!=NULL) {
586     FILE *f = fopen(s, fmode);
587     xfree(s);
588     return f;   
589   }
590   return NULL;
591 }
592
593 @ This is a legacy interface: (almost) all file names pass through |name_of_file|.
594
595 @<Glob...@>=
596 char name_of_file[file_name_size+1]; /* the name of a system file */
597 int name_length;/* this many characters are actually
598   relevant in |name_of_file| (the rest are blank) */
599 boolean print_found_names; /* configuration parameter */
600
601 @ @<Option variables@>=
602 boolean print_found_names; /* configuration parameter */
603
604 @ If this parameter is true, the terminal and log will report the found
605 file names for input files instead of the requested ones. 
606 It is off by default because it creates an extra filename lookup.
607
608 @<Allocate or initialize ...@>=
609 mp->print_found_names = (opt.print_found_names>0 ? true : false);
610
611 @ \MP's file-opening procedures return |false| if no file identified by
612 |name_of_file| could be opened.
613
614 The |OPEN_FILE| macro takes care of the |print_found_names| parameter.
615 It is not used for opening a mem file for read, because that file name 
616 is never printed.
617
618 @d OPEN_FILE(A) do {
619   if (mp->print_found_names) {
620     char *s = (mp->find_file)(mp->name_of_file,A,ftype);
621     if (s!=NULL) {
622       *f = mp_open_file(mp,mp->name_of_file,A, ftype); 
623       strncpy(mp->name_of_file,s,file_name_size);
624       xfree(s);
625     } else {
626       *f = NULL;
627     }
628   } else {
629     *f = mp_open_file(mp,mp->name_of_file,A, ftype); 
630   }
631 } while (0);
632 return (*f ? true : false)
633
634 @c 
635 boolean mp_a_open_in (MP mp, FILE **f, int ftype) {
636   /* open a text file for input */
637   OPEN_FILE("r");
638 }
639 @#
640 boolean mp_w_open_in (MP mp, FILE **f) {
641   /* open a word file for input */
642   *f = mp_open_file(mp,mp->name_of_file,"rb",mp_filetype_memfile); 
643   return (*f ? true : false);
644 }
645 @#
646 boolean mp_a_open_out (MP mp, FILE **f, int ftype) {
647   /* open a text file for output */
648   OPEN_FILE("w");
649 }
650 @#
651 boolean mp_b_open_out (MP mp, FILE **f, int ftype) {
652   /* open a binary file for output */
653   OPEN_FILE("wb");
654 }
655 @#
656 boolean mp_w_open_out (MP mp, FILE**f) {
657   /* open a word file for output */
658   int ftype = mp_filetype_memfile;
659   OPEN_FILE("wb");
660 }
661
662 @ @<Exported...@>=
663 FILE *mp_open_file(MP mp, char *fname, char *fmode, int ftype);
664
665 @ Binary input and output are done with \PASCAL's ordinary |get| and |put|
666 procedures, so we don't have to make any other special arrangements for
667 binary~I/O. Text output is also easy to do with standard \PASCAL\ routines.
668 The treatment of text input is more difficult, however, because
669 of the necessary translation to |ASCII_code| values.
670 \MP's conventions should be efficient, and they should
671 blend nicely with the user's operating environment.
672
673 @ Input from text files is read one line at a time, using a routine called
674 |input_ln|. This function is defined in terms of global variables called
675 |buffer|, |first|, and |last| that will be described in detail later; for
676 now, it suffices for us to know that |buffer| is an array of |ASCII_code|
677 values, and that |first| and |last| are indices into this array
678 representing the beginning and ending of a line of text.
679
680 @<Glob...@>=
681 size_t buf_size; /* maximum number of characters simultaneously present in
682                     current lines of open files */
683 ASCII_code *buffer; /* lines of characters being read */
684 size_t first; /* the first unused position in |buffer| */
685 size_t last; /* end of the line just input to |buffer| */
686 size_t max_buf_stack; /* largest index used in |buffer| */
687
688 @ @<Allocate or initialize ...@>=
689 mp->buf_size = 200;
690 mp->buffer = xmalloc((mp->buf_size+1),sizeof(ASCII_code));
691
692 @ @<Dealloc variables@>=
693 xfree(mp->buffer);
694
695 @ @c
696 void mp_reallocate_buffer(MP mp, size_t l) {
697   ASCII_code *buffer;
698   if (l>max_halfword) {
699     mp_confusion(mp,"buffer size"); /* can't happen (I hope) */
700   }
701   buffer = xmalloc((l+1),sizeof(ASCII_code));
702   memcpy(buffer,mp->buffer,(mp->buf_size+1));
703   xfree(mp->buffer);
704   mp->buffer = buffer ;
705   mp->buf_size = l;
706 }
707
708 @ The |input_ln| function brings the next line of input from the specified
709 field into available positions of the buffer array and returns the value
710 |true|, unless the file has already been entirely read, in which case it
711 returns |false| and sets |last:=first|.  In general, the |ASCII_code|
712 numbers that represent the next line of the file are input into
713 |buffer[first]|, |buffer[first+1]|, \dots, |buffer[last-1]|; and the
714 global variable |last| is set equal to |first| plus the length of the
715 line. Trailing blanks are removed from the line; thus, either |last=first|
716 (in which case the line was entirely blank) or |buffer[last-1]<>" "|.
717 @^inner loop@>
718
719 An overflow error is given, however, if the normal actions of |input_ln|
720 would make |last>=buf_size|; this is done so that other parts of \MP\
721 can safely look at the contents of |buffer[last+1]| without overstepping
722 the bounds of the |buffer| array. Upon entry to |input_ln|, the condition
723 |first<buf_size| will always hold, so that there is always room for an
724 ``empty'' line.
725
726 The variable |max_buf_stack|, which is used to keep track of how large
727 the |buf_size| parameter must be to accommodate the present job, is
728 also kept up to date by |input_ln|.
729
730 If the |bypass_eoln| parameter is |true|, |input_ln| will do a |get|
731 before looking at the first character of the line; this skips over
732 an |eoln| that was in |f^|. The procedure does not do a |get| when it
733 reaches the end of the line; therefore it can be used to acquire input
734 from the user's terminal as well as from ordinary text files.
735
736 Standard \PASCAL\ says that a file should have |eoln| immediately
737 before |eof|, but \MP\ needs only a weaker restriction: If |eof|
738 occurs in the middle of a line, the system function |eoln| should return
739 a |true| result (even though |f^| will be undefined).
740
741 @c 
742 boolean mp_input_ln (MP mp,FILE *  f, boolean bypass_eoln) {
743   /* inputs the next line or returns |false| */
744   int last_nonblank; /* |last| with trailing blanks removed */
745   int c;
746   if ( bypass_eoln ) {
747     c = fgetc(f);
748     if (c==EOF)
749       return false;
750     if (c!='\n' && c!='\r') {
751       ungetc(c,f);
752     }
753   }
754   /* input the first character of the line into |f^| */
755   mp->last=mp->first; /* cf.\ Matthew 19\thinspace:\thinspace30 */
756   c = fgetc(f);
757   if (c==EOF)
758         return false;
759   last_nonblank=mp->first;
760   while (c!=EOF && c!='\n' && c!='\r') { 
761     if ( mp->last>=mp->max_buf_stack ) { 
762       mp->max_buf_stack=mp->last+1;
763       if ( mp->max_buf_stack==mp->buf_size ) {
764         mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
765       }
766     }
767     mp->buffer[mp->last]=mp->xord[c]; 
768     incr(mp->last);
769     if ( mp->buffer[mp->last-1]!=' ' ) 
770       last_nonblank=mp->last;
771     c = fgetc(f); 
772   } 
773   if (c!=EOF) {
774     ungetc(c,f);
775   }
776   mp->last=last_nonblank; 
777   return true;
778 }
779
780 @ The user's terminal acts essentially like other files of text, except
781 that it is used both for input and for output. When the terminal is
782 considered an input file, the file variable is called |term_in|, and when it
783 is considered an output file the file variable is |term_out|.
784 @^system dependencies@>
785
786 @<Glob...@>=
787 FILE * term_in; /* the terminal as an input file */
788 FILE * term_out; /* the terminal as an output file */
789
790 @ Here is how to open the terminal files. In the default configuration,
791 nothing happens except that the command line (if there is one) is copied
792 to the input buffer.  The variable |command_line| will be filled by the 
793 |main| procedure. The copying can not be done earlier in the program 
794 logic because in the |INI| version, the |buffer| is also used for primitive 
795 initialization.
796
797 @^system dependencies@>
798
799 @d t_open_out  /* open the terminal for text output */
800 @d t_open_in  do { /* open the terminal for text input */
801     if (mp->command_line!=NULL) {
802       mp->last = strlen(mp->command_line);
803       strncpy((char *)mp->buffer,mp->command_line,mp->last);
804       xfree(mp->command_line);
805     }
806 } while (0)
807
808 @<Glob...@>=
809 char *command_line;
810
811 @ @<Option variables@>=
812 char *command_line;
813
814 @ @<Allocate or initialize ...@>=
815 mp->command_line = mp_xstrdup(opt.command_line);
816
817 @ Sometimes it is necessary to synchronize the input/output mixture that
818 happens on the user's terminal, and three system-dependent
819 procedures are used for this
820 purpose. The first of these, |update_terminal|, is called when we want
821 to make sure that everything we have output to the terminal so far has
822 actually left the computer's internal buffers and been sent.
823 The second, |clear_terminal|, is called when we wish to cancel any
824 input that the user may have typed ahead (since we are about to
825 issue an unexpected error message). The third, |wake_up_terminal|,
826 is supposed to revive the terminal if the user has disabled it by
827 some instruction to the operating system.  The following macros show how
828 these operations can be specified in \ph:
829 @^system dependencies@>
830
831 @d update_terminal   fflush(mp->term_out) /* empty the terminal output buffer */
832 @d clear_terminal   do_nothing /* clear the terminal input buffer */
833 @d wake_up_terminal  fflush(mp->term_out) /* cancel the user's cancellation of output */
834
835 @ We need a special routine to read the first line of \MP\ input from
836 the user's terminal. This line is different because it is read before we
837 have opened the transcript file; there is sort of a ``chicken and
838 egg'' problem here. If the user types `\.{input cmr10}' on the first
839 line, or if some macro invoked by that line does such an \.{input},
840 the transcript file will be named `\.{cmr10.log}'; but if no \.{input}
841 commands are performed during the first line of terminal input, the transcript
842 file will acquire its default name `\.{mpout.log}'. (The transcript file
843 will not contain error messages generated by the first line before the
844 first \.{input} command.)
845
846 The first line is even more special if we are lucky enough to have an operating
847 system that treats \MP\ differently from a run-of-the-mill \PASCAL\ object
848 program. It's nice to let the user start running a \MP\ job by typing
849 a command line like `\.{MP cmr10}'; in such a case, \MP\ will operate
850 as if the first line of input were `\.{cmr10}', i.e., the first line will
851 consist of the remainder of the command line, after the part that invoked \MP.
852
853 @ Different systems have different ways to get started. But regardless of
854 what conventions are adopted, the routine that initializes the terminal
855 should satisfy the following specifications:
856
857 \yskip\textindent{1)}It should open file |term_in| for input from the
858   terminal. (The file |term_out| will already be open for output to the
859   terminal.)
860
861 \textindent{2)}If the user has given a command line, this line should be
862   considered the first line of terminal input. Otherwise the
863   user should be prompted with `\.{**}', and the first line of input
864   should be whatever is typed in response.
865
866 \textindent{3)}The first line of input, which might or might not be a
867   command line, should appear in locations |first| to |last-1| of the
868   |buffer| array.
869
870 \textindent{4)}The global variable |loc| should be set so that the
871   character to be read next by \MP\ is in |buffer[loc]|. This
872   character should not be blank, and we should have |loc<last|.
873
874 \yskip\noindent(It may be necessary to prompt the user several times
875 before a non-blank line comes in. The prompt is `\.{**}' instead of the
876 later `\.*' because the meaning is slightly different: `\.{input}' need
877 not be typed immediately after~`\.{**}'.)
878
879 @d loc mp->cur_input.loc_field /* location of first unread character in |buffer| */
880
881 @ The following program does the required initialization
882 without retrieving a possible command line.
883 It should be clear how to modify this routine to deal with command lines,
884 if the system permits them.
885 @^system dependencies@>
886
887 @c 
888 boolean mp_init_terminal (MP mp) { /* gets the terminal input started */
889   t_open_in; 
890   if (mp->last!=0) {
891     loc = mp->first = 0;
892         return true;
893   }
894   while (1) { 
895     wake_up_terminal; fprintf(mp->term_out,"**"); update_terminal;
896 @.**@>
897     if ( ! mp_input_ln(mp, mp->term_in,true) ) { /* this shouldn't happen */
898       fprintf(mp->term_out,"\n! End of file on the terminal... why?");
899 @.End of file on the terminal@>
900       return false;
901     }
902     loc=mp->first;
903     while ( (loc<(int)mp->last)&&(mp->buffer[loc]==' ') ) 
904       incr(loc);
905     if ( loc<(int)mp->last ) { 
906       return true; /* return unless the line was all blank */
907     };
908     fprintf(mp->term_out,"Please type the name of your input file.\n");
909   }
910 }
911
912 @ @<Declarations@>=
913 boolean mp_init_terminal (MP mp) ;
914
915
916 @* \[4] String handling.
917 Symbolic token names and diagnostic messages are variable-length strings
918 of eight-bit characters. Since \PASCAL\ does not have a well-developed string
919 mechanism, \MP\ does all of its string processing by homegrown methods.
920
921 \MP\ uses strings more extensively than \MF\ does, but the necessary
922 operations can still be handled with a fairly simple data structure.
923 The array |str_pool| contains all of the (eight-bit) ASCII codes in all
924 of the strings, and the array |str_start| contains indices of the starting
925 points of each string. Strings are referred to by integer numbers, so that
926 string number |s| comprises the characters |str_pool[j]| for
927 |str_start[s]<=j<str_start[ss]| where |ss=next_str[s]|.  The string pool
928 is allocated sequentially and |str_pool[pool_ptr]| is the next unused
929 location.  The first string number not currently in use is |str_ptr|
930 and |next_str[str_ptr]| begins a list of free string numbers.  String
931 pool entries |str_start[str_ptr]| up to |pool_ptr| are reserved for a
932 string currently being constructed.
933
934 String numbers 0 to 255 are reserved for strings that correspond to single
935 ASCII characters. This is in accordance with the conventions of \.{WEB},
936 @.WEB@>
937 which converts single-character strings into the ASCII code number of the
938 single character involved, while it converts other strings into integers
939 and builds a string pool file. Thus, when the string constant \.{"."} appears
940 in the program below, \.{WEB} converts it into the integer 46, which is the
941 ASCII code for a period, while \.{WEB} will convert a string like \.{"hello"}
942 into some integer greater than~255. String number 46 will presumably be the
943 single character `\..'\thinspace; but some ASCII codes have no standard visible
944 representation, and \MP\ may need to be able to print an arbitrary
945 ASCII character, so the first 256 strings are used to specify exactly what
946 should be printed for each of the 256 possibilities.
947
948 @<Types...@>=
949 typedef int pool_pointer; /* for variables that point into |str_pool| */
950 typedef int str_number; /* for variables that point into |str_start| */
951
952 @ @<Glob...@>=
953 ASCII_code *str_pool; /* the characters */
954 pool_pointer *str_start; /* the starting pointers */
955 str_number *next_str; /* for linking strings in order */
956 pool_pointer pool_ptr; /* first unused position in |str_pool| */
957 str_number str_ptr; /* number of the current string being created */
958 pool_pointer init_pool_ptr; /* the starting value of |pool_ptr| */
959 str_number init_str_use; /* the initial number of strings in use */
960 pool_pointer max_pool_ptr; /* the maximum so far of |pool_ptr| */
961 str_number max_str_ptr; /* the maximum so far of |str_ptr| */
962
963 @ @<Allocate or initialize ...@>=
964 mp->str_pool  = xmalloc ((mp->pool_size +1),sizeof(ASCII_code));
965 mp->str_start = xmalloc ((mp->max_strings+1),sizeof(pool_pointer));
966 mp->next_str  = xmalloc ((mp->max_strings+1),sizeof(str_number));
967
968 @ @<Dealloc variables@>=
969 xfree(mp->str_pool);
970 xfree(mp->str_start);
971 xfree(mp->next_str);
972
973 @ Most printing is done from |char *|s, but sometimes not. Here are
974 functions that convert an internal string into a |char *| for use
975 by the printing routines, and vice versa.
976
977 @d str(A) mp_str(mp,A)
978 @d rts(A) mp_rts(mp,A)
979
980 @<Exported function headers@>=
981 int mp_xstrcmp (const char *a, const char *b);
982 char * mp_str (MP mp, str_number s);
983
984 @ @<Declarations@>=
985 str_number mp_rts (MP mp, char *s);
986 str_number mp_make_string (MP mp);
987
988 @ The attempt to catch interrupted strings that is in |mp_rts|, is not 
989 very good: it does not handle nesting over more than one level.
990
991 @c 
992 int mp_xstrcmp (const char *a, const char *b) {
993         if (a==NULL && b==NULL) 
994           return 0;
995     if (a==NULL)
996       return -1;
997     if (b==NULL)
998       return 1;
999     return strcmp(a,b);
1000 }
1001
1002 @ @c
1003 char * mp_str (MP mp, str_number ss) {
1004   char *s;
1005   int len = length(ss);
1006   s = xmalloc(len+1,sizeof(char));
1007   strncpy(s,(char *)(mp->str_pool+(mp->str_start[ss])),len);
1008   s[len] = 0;
1009   return (char *)s;
1010 }
1011 str_number mp_rts (MP mp, char *s) {
1012   int r; /* the new string */ 
1013   int old; /* a possible string in progress */
1014   int i=0;
1015   if (strlen(s)==0) {
1016     return 256;
1017   } else if (strlen(s)==1) {
1018     return s[0];
1019   } else {
1020    old=0;
1021    str_room((integer)strlen(s));
1022    if (mp->str_start[mp->str_ptr]<mp->pool_ptr)
1023      old = mp_make_string(mp);
1024    while (*s) {
1025      append_char(*s);
1026      s++;
1027    }
1028    r = mp_make_string(mp);
1029    if (old!=0) {
1030       str_room(length(old));
1031       while (i<length(old)) {
1032         append_char((mp->str_start[old]+i));
1033       } 
1034       mp_flush_string(mp,old);
1035     }
1036     return r;
1037   }
1038 }
1039
1040 @ Except for |strs_used_up|, the following string statistics are only
1041 maintained when code between |stat| $\ldots$ |tats| delimiters is not
1042 commented out:
1043
1044 @<Glob...@>=
1045 integer strs_used_up; /* strings in use or unused but not reclaimed */
1046 integer pool_in_use; /* total number of cells of |str_pool| actually in use */
1047 integer strs_in_use; /* total number of strings actually in use */
1048 integer max_pl_used; /* maximum |pool_in_use| so far */
1049 integer max_strs_used; /* maximum |strs_in_use| so far */
1050
1051 @ Several of the elementary string operations are performed using \.{WEB}
1052 macros instead of \PASCAL\ procedures, because many of the
1053 operations are done quite frequently and we want to avoid the
1054 overhead of procedure calls. For example, here is
1055 a simple macro that computes the length of a string.
1056 @.WEB@>
1057
1058 @d str_stop(A) mp->str_start[mp->next_str[(A)]] /* one cell past the end of string
1059   number \# */
1060 @d length(A) (str_stop((A))-mp->str_start[(A)]) /* the number of characters in string \# */
1061
1062 @ The length of the current string is called |cur_length|.  If we decide that
1063 the current string is not needed, |flush_cur_string| resets |pool_ptr| so that
1064 |cur_length| becomes zero.
1065
1066 @d cur_length   (mp->pool_ptr - mp->str_start[mp->str_ptr])
1067 @d flush_cur_string   mp->pool_ptr=mp->str_start[mp->str_ptr]
1068
1069 @ Strings are created by appending character codes to |str_pool|.
1070 The |append_char| macro, defined here, does not check to see if the
1071 value of |pool_ptr| has gotten too high; this test is supposed to be
1072 made before |append_char| is used.
1073
1074 To test if there is room to append |l| more characters to |str_pool|,
1075 we shall write |str_room(l)|, which tries to make sure there is enough room
1076 by compacting the string pool if necessary.  If this does not work,
1077 |do_compaction| aborts \MP\ and gives an apologetic error message.
1078
1079 @d append_char(A)   /* put |ASCII_code| \# at the end of |str_pool| */
1080 { mp->str_pool[mp->pool_ptr]=(A); incr(mp->pool_ptr);
1081 }
1082 @d str_room(A)   /* make sure that the pool hasn't overflowed */
1083   { if ( mp->pool_ptr+(A) > mp->max_pool_ptr ) {
1084     if ( mp->pool_ptr+(A) > mp->pool_size ) mp_do_compaction(mp, (A));
1085     else mp->max_pool_ptr=mp->pool_ptr+(A); }
1086   }
1087
1088 @ The following routine is similar to |str_room(1)| but it uses the
1089 argument |mp->pool_size| to prevent |do_compaction| from aborting when
1090 string space is exhausted.
1091
1092 @<Declare the procedure called |unit_str_room|@>=
1093 void mp_unit_str_room (MP mp);
1094
1095 @ @c
1096 void mp_unit_str_room (MP mp) { 
1097   if ( mp->pool_ptr>=mp->pool_size ) mp_do_compaction(mp, mp->pool_size);
1098   if ( mp->pool_ptr>=mp->max_pool_ptr ) mp->max_pool_ptr=mp->pool_ptr+1;
1099 }
1100
1101 @ \MP's string expressions are implemented in a brute-force way: Every
1102 new string or substring that is needed is simply copied into the string pool.
1103 Space is eventually reclaimed by a procedure called |do_compaction| with
1104 the aid of a simple system system of reference counts.
1105 @^reference counts@>
1106
1107 The number of references to string number |s| will be |str_ref[s]|. The
1108 special value |str_ref[s]=max_str_ref=127| is used to denote an unknown
1109 positive number of references; such strings will never be recycled. If
1110 a string is ever referred to more than 126 times, simultaneously, we
1111 put it in this category. Hence a single byte suffices to store each |str_ref|.
1112
1113 @d max_str_ref 127 /* ``infinite'' number of references */
1114 @d add_str_ref(A) { if ( mp->str_ref[(A)]<max_str_ref ) incr(mp->str_ref[(A)]);
1115   }
1116
1117 @<Glob...@>=
1118 int *str_ref;
1119
1120 @ @<Allocate or initialize ...@>=
1121 mp->str_ref = xmalloc ((mp->max_strings+1),sizeof(int));
1122
1123 @ @<Dealloc variables@>=
1124 xfree(mp->str_ref);
1125
1126 @ Here's what we do when a string reference disappears:
1127
1128 @d delete_str_ref(A)  { 
1129     if ( mp->str_ref[(A)]<max_str_ref ) {
1130        if ( mp->str_ref[(A)]>1 ) decr(mp->str_ref[(A)]); 
1131        else mp_flush_string(mp, (A));
1132     }
1133   }
1134
1135 @<Declare the procedure called |flush_string|@>=
1136 void mp_flush_string (MP mp,str_number s) ;
1137
1138
1139 @ We can't flush the first set of static strings at all, so there 
1140 is no point in trying
1141
1142 @c
1143 void mp_flush_string (MP mp,str_number s) { 
1144   if (length(s)>1) {
1145     mp->pool_in_use=mp->pool_in_use-length(s);
1146     decr(mp->strs_in_use);
1147     if ( mp->next_str[s]!=mp->str_ptr ) {
1148       mp->str_ref[s]=0;
1149     } else { 
1150       mp->str_ptr=s;
1151       decr(mp->strs_used_up);
1152     }
1153     mp->pool_ptr=mp->str_start[mp->str_ptr];
1154   }
1155 }
1156
1157 @ C literals cannot be simply added, they need to be set so they can't
1158 be flushed.
1159
1160 @d intern(A) mp_intern(mp,(A))
1161
1162 @c
1163 str_number mp_intern (MP mp, char *s) {
1164   str_number r ;
1165   r = rts(s);
1166   mp->str_ref[r] = max_str_ref;
1167   return r;
1168 }
1169
1170 @ @<Declarations@>=
1171 str_number mp_intern (MP mp, char *s);
1172
1173
1174 @ Once a sequence of characters has been appended to |str_pool|, it
1175 officially becomes a string when the function |make_string| is called.
1176 This function returns the identification number of the new string as its
1177 value.
1178
1179 When getting the next unused string number from the linked list, we pretend
1180 that
1181 $$ \hbox{|max_str_ptr+1|, |max_str_ptr+2|, $\ldots$, |mp->max_strings|} $$
1182 are linked sequentially even though the |next_str| entries have not been
1183 initialized yet.  We never allow |str_ptr| to reach |mp->max_strings|;
1184 |do_compaction| is responsible for making sure of this.
1185
1186 @<Declarations@>=
1187 @<Declare the procedure called |do_compaction|@>;
1188 @<Declare the procedure called |unit_str_room|@>;
1189 str_number mp_make_string (MP mp);
1190
1191 @ @c 
1192 str_number mp_make_string (MP mp) { /* current string enters the pool */
1193   str_number s; /* the new string */
1194 RESTART: 
1195   s=mp->str_ptr;
1196   mp->str_ptr=mp->next_str[s];
1197   if ( mp->str_ptr>mp->max_str_ptr ) {
1198     if ( mp->str_ptr==mp->max_strings ) { 
1199       mp->str_ptr=s;
1200       mp_do_compaction(mp, 0);
1201       goto RESTART;
1202     } else {
1203 #ifdef DEBUG 
1204       if ( mp->strs_used_up!=mp->max_str_ptr ) mp_confusion(mp, "s");
1205 @:this can't happen s}{\quad \.s@>
1206 #endif
1207       mp->max_str_ptr=mp->str_ptr;
1208       mp->next_str[mp->str_ptr]=mp->max_str_ptr+1;
1209     }
1210   }
1211   mp->str_ref[s]=1;
1212   mp->str_start[mp->str_ptr]=mp->pool_ptr;
1213   incr(mp->strs_used_up);
1214   incr(mp->strs_in_use);
1215   mp->pool_in_use=mp->pool_in_use+length(s);
1216   if ( mp->pool_in_use>mp->max_pl_used ) 
1217     mp->max_pl_used=mp->pool_in_use;
1218   if ( mp->strs_in_use>mp->max_strs_used ) 
1219     mp->max_strs_used=mp->strs_in_use;
1220   return s;
1221 }
1222
1223 @ The most interesting string operation is string pool compaction.  The idea
1224 is to recover unused space in the |str_pool| array by recopying the strings
1225 to close the gaps created when some strings become unused.  All string
1226 numbers~$k$ where |str_ref[k]=0| are to be linked into the list of free string
1227 numbers after |str_ptr|.  If this fails to free enough pool space we issue an
1228 |overflow| error unless |needed=mp->pool_size|.  Calling |do_compaction|
1229 with |needed=mp->pool_size| supresses all overflow tests.
1230
1231 The compaction process starts with |last_fixed_str| because all lower numbered
1232 strings are permanently allocated with |max_str_ref| in their |str_ref| entries.
1233
1234 @<Glob...@>=
1235 str_number last_fixed_str; /* last permanently allocated string */
1236 str_number fixed_str_use; /* number of permanently allocated strings */
1237
1238 @ @<Declare the procedure called |do_compaction|@>=
1239 void mp_do_compaction (MP mp, pool_pointer needed) ;
1240
1241 @ @c
1242 void mp_do_compaction (MP mp, pool_pointer needed) {
1243   str_number str_use; /* a count of strings in use */
1244   str_number r,s,t; /* strings being manipulated */
1245   pool_pointer p,q; /* destination and source for copying string characters */
1246   @<Advance |last_fixed_str| as far as possible and set |str_use|@>;
1247   r=mp->last_fixed_str;
1248   s=mp->next_str[r];
1249   p=mp->str_start[s];
1250   while ( s!=mp->str_ptr ) { 
1251     while ( mp->str_ref[s]==0 ) {
1252       @<Advance |s| and add the old |s| to the list of free string numbers;
1253         then |break| if |s=str_ptr|@>;
1254     }
1255     r=s; s=mp->next_str[s];
1256     incr(str_use);
1257     @<Move string |r| back so that |str_start[r]=p|; make |p| the location
1258      after the end of the string@>;
1259   }
1260   @<Move the current string back so that it starts at |p|@>;
1261   if ( needed<mp->pool_size ) {
1262     @<Make sure that there is room for another string with |needed| characters@>;
1263   }
1264   @<Account for the compaction and make sure the statistics agree with the
1265      global versions@>;
1266   mp->strs_used_up=str_use;
1267 }
1268
1269 @ @<Advance |last_fixed_str| as far as possible and set |str_use|@>=
1270 t=mp->next_str[mp->last_fixed_str];
1271 while ( (mp->str_ref[t]==max_str_ref)&&(t!=mp->str_ptr) ) { 
1272   incr(mp->fixed_str_use);
1273   mp->last_fixed_str=t;
1274   t=mp->next_str[t];
1275 }
1276 str_use=mp->fixed_str_use
1277
1278 @ Because of the way |flush_string| has been written, it should never be
1279 necessary to |break| here.  The extra line of code seems worthwhile to
1280 preserve the generality of |do_compaction|.
1281
1282 @<Advance |s| and add the old |s| to the list of free string numbers;...@>=
1283 {
1284 t=s;
1285 s=mp->next_str[s];
1286 mp->next_str[r]=s;
1287 mp->next_str[t]=mp->next_str[mp->str_ptr];
1288 mp->next_str[mp->str_ptr]=t;
1289 if ( s==mp->str_ptr ) break;
1290 }
1291
1292 @ The string currently starts at |str_start[r]| and ends just before
1293 |str_start[s]|.  We don't change |str_start[s]| because it might be needed
1294 to locate the next string.
1295
1296 @<Move string |r| back so that |str_start[r]=p|; make |p| the location...@>=
1297 q=mp->str_start[r];
1298 mp->str_start[r]=p;
1299 while ( q<mp->str_start[s] ) { 
1300   mp->str_pool[p]=mp->str_pool[q];
1301   incr(p); incr(q);
1302 }
1303
1304 @ Pointers |str_start[str_ptr]| and |pool_ptr| have not been updated.  When
1305 we do this, anything between them should be moved.
1306
1307 @ @<Move the current string back so that it starts at |p|@>=
1308 q=mp->str_start[mp->str_ptr];
1309 mp->str_start[mp->str_ptr]=p;
1310 while ( q<mp->pool_ptr ) { 
1311   mp->str_pool[p]=mp->str_pool[q];
1312   incr(p); incr(q);
1313 }
1314 mp->pool_ptr=p
1315
1316 @ We must remember that |str_ptr| is not allowed to reach |mp->max_strings|.
1317
1318 @<Make sure that there is room for another string with |needed| char...@>=
1319 if ( str_use>=mp->max_strings-1 )
1320   mp_reallocate_strings (mp,str_use);
1321 if ( mp->pool_ptr+needed>mp->max_pool_ptr ) {
1322   mp_reallocate_pool(mp, mp->pool_ptr+needed);
1323   mp->max_pool_ptr=mp->pool_ptr+needed;
1324 }
1325
1326 @ @<Declarations@>=
1327 void mp_reallocate_strings (MP mp, str_number str_use) ;
1328 void mp_reallocate_pool(MP mp, pool_pointer needed) ;
1329
1330 @ @c 
1331 void mp_reallocate_strings (MP mp, str_number str_use) { 
1332   while ( str_use>=mp->max_strings-1 ) {
1333     int l = mp->max_strings + (mp->max_strings>>2);
1334     XREALLOC (mp->str_ref,   (l+1),sizeof(int));
1335     XREALLOC (mp->str_start, (l+1),sizeof(pool_pointer));
1336     XREALLOC (mp->next_str,  (l+1),sizeof(str_number));
1337     mp->max_strings = l;
1338   }
1339 }
1340 void mp_reallocate_pool(MP mp, pool_pointer needed) {
1341   while ( needed>mp->pool_size ) {
1342     int l = mp->pool_size + (mp->pool_size>>2);
1343         XREALLOC (mp->str_pool, (l+1),sizeof(ASCII_code));
1344     mp->pool_size = l;
1345   }
1346 }
1347
1348 @ @<Account for the compaction and make sure the statistics agree with...@>=
1349 if ( (mp->str_start[mp->str_ptr]!=mp->pool_in_use)||(str_use!=mp->strs_in_use) )
1350   mp_confusion(mp, "string");
1351 @:this can't happen string}{\quad string@>
1352 incr(mp->pact_count);
1353 mp->pact_chars=mp->pact_chars+mp->pool_ptr-str_stop(mp->last_fixed_str);
1354 mp->pact_strs=mp->pact_strs+str_use-mp->fixed_str_use;
1355 #ifdef DEBUG
1356 s=mp->str_ptr; t=str_use;
1357 while ( s<=mp->max_str_ptr ){
1358   if ( t>mp->max_str_ptr ) mp_confusion(mp, "\"");
1359   incr(t); s=mp->next_str[s];
1360 };
1361 if ( t<=mp->max_str_ptr ) mp_confusion(mp, "\"");
1362 #endif
1363
1364 @ A few more global variables are needed to keep track of statistics when
1365 |stat| $\ldots$ |tats| blocks are not commented out.
1366
1367 @<Glob...@>=
1368 integer pact_count; /* number of string pool compactions so far */
1369 integer pact_chars; /* total number of characters moved during compactions */
1370 integer pact_strs; /* total number of strings moved during compactions */
1371
1372 @ @<Initialize compaction statistics@>=
1373 mp->pact_count=0;
1374 mp->pact_chars=0;
1375 mp->pact_strs=0;
1376
1377 @ The following subroutine compares string |s| with another string of the
1378 same length that appears in |buffer| starting at position |k|;
1379 the result is |true| if and only if the strings are equal.
1380
1381 @c 
1382 boolean mp_str_eq_buf (MP mp,str_number s, integer k) {
1383   /* test equality of strings */
1384   pool_pointer j; /* running index */
1385   j=mp->str_start[s];
1386   while ( j<str_stop(s) ) { 
1387     if ( mp->str_pool[j++]!=mp->buffer[k++] ) 
1388       return false;
1389   }
1390   return true;
1391 }
1392
1393 @ Here is a similar routine, but it compares two strings in the string pool,
1394 and it does not assume that they have the same length. If the first string
1395 is lexicographically greater than, less than, or equal to the second,
1396 the result is respectively positive, negative, or zero.
1397
1398 @c 
1399 integer mp_str_vs_str (MP mp, str_number s, str_number t) {
1400   /* test equality of strings */
1401   pool_pointer j,k; /* running indices */
1402   integer ls,lt; /* lengths */
1403   integer l; /* length remaining to test */
1404   ls=length(s); lt=length(t);
1405   if ( ls<=lt ) l=ls; else l=lt;
1406   j=mp->str_start[s]; k=mp->str_start[t];
1407   while ( l-->0 ) { 
1408     if ( mp->str_pool[j]!=mp->str_pool[k] ) {
1409        return (mp->str_pool[j]-mp->str_pool[k]); 
1410     }
1411     incr(j); incr(k);
1412   }
1413   return (ls-lt);
1414 }
1415
1416 @ The initial values of |str_pool|, |str_start|, |pool_ptr|,
1417 and |str_ptr| are computed by the \.{INIMP} program, based in part
1418 on the information that \.{WEB} has output while processing \MP.
1419 @.INIMP@>
1420 @^string pool@>
1421
1422 @c 
1423 void mp_get_strings_started (MP mp) { 
1424   /* initializes the string pool,
1425     but returns |false| if something goes wrong */
1426   int k; /* small indices or counters */
1427   str_number g; /* a new string */
1428   mp->pool_ptr=0; mp->str_ptr=0; mp->max_pool_ptr=0; mp->max_str_ptr=0;
1429   mp->str_start[0]=0;
1430   mp->next_str[0]=1;
1431   mp->pool_in_use=0; mp->strs_in_use=0;
1432   mp->max_pl_used=0; mp->max_strs_used=0;
1433   @<Initialize compaction statistics@>;
1434   mp->strs_used_up=0;
1435   @<Make the first 256 strings@>;
1436   g=mp_make_string(mp); /* string 256 == "" */
1437   mp->last_fixed_str=mp->str_ptr-1;
1438   mp->fixed_str_use=mp->str_ptr;
1439   return;
1440 }
1441
1442 @ @<Declarations@>=
1443 void mp_get_strings_started (MP mp);
1444
1445 @ The first 256 strings will consist of a single character only.
1446
1447 @<Make the first 256...@>=
1448 for (k=0;k<=255;k++) { 
1449   append_char(k);
1450   g=mp_make_string(mp); 
1451   mp->str_ref[g]=max_str_ref;
1452 }
1453
1454 @ The first 128 strings will contain 95 standard ASCII characters, and the
1455 other 33 characters will be printed in three-symbol form like `\.{\^\^A}'
1456 unless a system-dependent change is made here. Installations that have
1457 an extended character set, where for example |xchr[032]=@t\.{'^^Z'}@>|,
1458 would like string 032 to be printed as the single character 032 instead
1459 of the three characters 0136, 0136, 0132 (\.{\^\^Z}). On the other hand,
1460 even people with an extended character set will want to represent string
1461 015 by \.{\^\^M}, since 015 is ASCII's ``carriage return'' code; the idea is
1462 to produce visible strings instead of tabs or line-feeds or carriage-returns
1463 or bell-rings or characters that are treated anomalously in text files.
1464
1465 Unprintable characters of codes 128--255 are, similarly, rendered
1466 \.{\^\^80}--\.{\^\^ff}.
1467
1468 The boolean expression defined here should be |true| unless \MP\ internal
1469 code number~|k| corresponds to a non-troublesome visible symbol in the
1470 local character set.
1471 If character |k| cannot be printed, and |k<0200|, then character |k+0100| or
1472 |k-0100| must be printable; moreover, ASCII codes |[060..071, 0141..0146]|
1473 must be printable.
1474 @^character set dependencies@>
1475 @^system dependencies@>
1476
1477 @<Character |k| cannot be printed@>=
1478   (k<' ')||(k>'~')
1479
1480 @* \[5] On-line and off-line printing.
1481 Messages that are sent to a user's terminal and to the transcript-log file
1482 are produced by several `|print|' procedures. These procedures will
1483 direct their output to a variety of places, based on the setting of
1484 the global variable |selector|, which has the following possible
1485 values:
1486
1487 \yskip
1488 \hang |term_and_log|, the normal setting, prints on the terminal and on the
1489   transcript file.
1490
1491 \hang |log_only|, prints only on the transcript file.
1492
1493 \hang |term_only|, prints only on the terminal.
1494
1495 \hang |no_print|, doesn't print at all. This is used only in rare cases
1496   before the transcript file is open.
1497
1498 \hang |ps_file_only| prints only on the \ps\ output file.
1499
1500 \hang |pseudo|, puts output into a cyclic buffer that is used
1501   by the |show_context| routine; when we get to that routine we shall discuss
1502   the reasoning behind this curious mode.
1503
1504 \hang |new_string|, appends the output to the current string in the
1505   string pool.
1506
1507 \hang |>=write_file| prints on one of the files used for the \&{write}
1508 @:write_}{\&{write} primitive@>
1509   command.
1510
1511 \yskip
1512 \noindent The symbolic names `|term_and_log|', etc., have been assigned
1513 numeric codes that satisfy the convenient relations |no_print+1=term_only|,
1514 |no_print+2=log_only|, |term_only+2=log_only+1=term_and_log|.  These
1515 relations are not used when |selector| could be |pseudo|, |new_string|,
1516 or |ps_file_only|.  We need not check for unprintable characters when
1517 |selector<pseudo|.
1518
1519 Four additional global variables, |tally|, |term_offset|, |file_offset|,
1520 and |ps_offset| record the number of characters that have been printed
1521 since they were most recently cleared to zero. We use |tally| to record
1522 the length of (possibly very long) stretches of printing; |term_offset|,
1523 |file_offset|, and |ps_offset|, on the other hand, keep track of how many
1524 characters have appeared so far on the current line that has been output
1525 to the terminal, the transcript file, or the \ps\ output file, respectively.
1526
1527 @d new_string 0 /* printing is deflected to the string pool */
1528 @d ps_file_only 1 /* printing goes to the \ps\ output file */
1529 @d pseudo 2 /* special |selector| setting for |show_context| */
1530 @d no_print 3 /* |selector| setting that makes data disappear */
1531 @d term_only 4 /* printing is destined for the terminal only */
1532 @d log_only 5 /* printing is destined for the transcript file only */
1533 @d term_and_log 6 /* normal |selector| setting */
1534 @d write_file 7 /* first write file selector */
1535
1536 @<Glob...@>=
1537 FILE * log_file; /* transcript of \MP\ session */
1538 FILE * ps_file; /* the generic font output goes here */
1539 unsigned int selector; /* where to print a message */
1540 unsigned char dig[23]; /* digits in a number being output */
1541 integer tally; /* the number of characters recently printed */
1542 unsigned int term_offset;
1543   /* the number of characters on the current terminal line */
1544 unsigned int file_offset;
1545   /* the number of characters on the current file line */
1546 integer ps_offset;
1547   /* the number of characters on the current \ps\ file line */
1548 ASCII_code *trick_buf; /* circular buffer for pseudoprinting */
1549 integer trick_count; /* threshold for pseudoprinting, explained later */
1550 integer first_count; /* another variable for pseudoprinting */
1551
1552 @ @<Allocate or initialize ...@>=
1553 memset(mp->dig,0,23);
1554 mp->trick_buf = xmalloc((mp->error_line+1),sizeof(ASCII_code));
1555
1556 @ @<Dealloc variables@>=
1557 xfree(mp->trick_buf);
1558
1559 @ @<Initialize the output routines@>=
1560 mp->selector=term_only; mp->tally=0; mp->term_offset=0; mp->file_offset=0; mp->ps_offset=0;
1561
1562 @ Macro abbreviations for output to the terminal and to the log file are
1563 defined here for convenience. Some systems need special conventions
1564 for terminal output, and it is possible to adhere to those conventions
1565 by changing |wterm|, |wterm_ln|, and |wterm_cr| here.
1566 @^system dependencies@>
1567
1568 @d wterm(A)    fprintf(mp->term_out,"%s",(A))
1569 @d wterm_chr(A)fprintf(mp->term_out,"%c",(A))
1570 @d wterm_ln(A) fprintf(mp->term_out,"\n%s",(A))
1571 @d wterm_cr    fprintf(mp->term_out,"\n")
1572 @d wlog(A)     fprintf(mp->log_file,"%s",(A))
1573 @d wlog_chr(A) fprintf(mp->log_file,"%c",(A))
1574 @d wlog_ln(A)  fprintf(mp->log_file,"\n%s",(A))
1575 @d wlog_cr     fprintf(mp->log_file, "\n")
1576 @d wps(A)      fprintf(mp->ps_file,"%s",(A))
1577 @d wps_chr(A)  fprintf(mp->ps_file,"%c",(A))
1578 @d wps_ln(A)   fprintf(mp->ps_file,,"\n%s",(A))
1579 @d wps_cr      fprintf(mp->ps_file,"\n")
1580
1581 @ To end a line of text output, we call |print_ln|.  Cases |0..max_write_files|
1582 use an array |wr_file| that will be declared later.
1583
1584 @d mp_print_text(A) mp_print_str(mp,text((A)))
1585
1586 @<Exported...@>=
1587 void mp_print_ln (MP mp);
1588 void mp_print_visible_char (MP mp, ASCII_code s); 
1589 void mp_print_char (MP mp, ASCII_code k);
1590 void mp_print (MP mp, char *s);
1591 void mp_print_str (MP mp, str_number s);
1592 void mp_print_nl (MP mp, char *s);
1593 void mp_print_two (MP mp,scaled x, scaled y) ;
1594 void mp_print_scaled (MP mp,scaled s);
1595
1596 @ @<Basic print...@>=
1597 void mp_print_ln (MP mp) { /* prints an end-of-line */
1598  switch (mp->selector) {
1599   case term_and_log: 
1600     wterm_cr; wlog_cr;
1601     mp->term_offset=0;  mp->file_offset=0;
1602     break;
1603   case log_only: 
1604     wlog_cr; mp->file_offset=0;
1605     break;
1606   case term_only: 
1607     wterm_cr; mp->term_offset=0;
1608     break;
1609   case ps_file_only: 
1610     wps_cr; mp->ps_offset=0;
1611     break;
1612   case no_print:
1613   case pseudo: 
1614   case new_string: 
1615     break;
1616   default: 
1617     fprintf(mp->wr_file[(mp->selector-write_file)],"\n");
1618   }
1619 } /* note that |tally| is not affected */
1620
1621 @ The |print_visible_char| procedure sends one character to the desired
1622 destination, using the |xchr| array to map it into an external character
1623 compatible with |input_ln|.  (It assumes that it is always called with
1624 a visible ASCII character.)  All printing comes through |print_ln| or
1625 |print_char|, which ultimately calls |print_visible_char|, hence these
1626 routines are the ones that limit lines to at most |max_print_line| characters.
1627 But we must make an exception for the \ps\ output file since it is not safe
1628 to cut up lines arbitrarily in \ps.
1629
1630 Procedure |unit_str_room| needs to be declared |forward| here because it calls
1631 |do_compaction| and |do_compaction| can call the error routines.  Actually,
1632 |unit_str_room| avoids |overflow| errors but it can call |confusion|.
1633
1634 @<Basic printing...@>=
1635 void mp_print_visible_char (MP mp, ASCII_code s) { /* prints a single character */
1636   switch (mp->selector) {
1637   case term_and_log: 
1638     wterm_chr(mp->xchr[s]); wlog_chr(mp->xchr[s]);
1639     incr(mp->term_offset); incr(mp->file_offset);
1640     if ( mp->term_offset==(unsigned)mp->max_print_line ) { 
1641        wterm_cr; mp->term_offset=0;
1642     };
1643     if ( mp->file_offset==(unsigned)mp->max_print_line ) { 
1644        wlog_cr; mp->file_offset=0;
1645     };
1646     break;
1647   case log_only: 
1648     wlog_chr(mp->xchr[s]); incr(mp->file_offset);
1649     if ( mp->file_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1650     break;
1651   case term_only: 
1652     wterm_chr(mp->xchr[s]); incr(mp->term_offset);
1653     if ( mp->term_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1654     break;
1655   case ps_file_only: 
1656     if ( s==13 ) {
1657       wps_cr; mp->ps_offset=0;
1658     } else {
1659       wps_chr(mp->xchr[s]); incr(mp->ps_offset);
1660     };
1661     break;
1662   case no_print: 
1663     break;
1664   case pseudo: 
1665     if ( mp->tally<mp->trick_count ) 
1666       mp->trick_buf[mp->tally % mp->error_line]=s;
1667     break;
1668   case new_string: 
1669     if ( mp->pool_ptr>=mp->max_pool_ptr ) { 
1670       mp_unit_str_room(mp);
1671       if ( mp->pool_ptr>=mp->pool_size ) 
1672         goto DONE; /* drop characters if string space is full */
1673     };
1674     append_char(s);
1675     break;
1676   default:
1677     fprintf(mp->wr_file[(mp->selector-write_file)],"%c",mp->xchr[s]);
1678   }
1679 DONE:
1680   incr(mp->tally);
1681 }
1682
1683 @ The |print_char| procedure sends one character to the desired destination.
1684 File names and string expressions might contain |ASCII_code| values that
1685 can't be printed using |print_visible_char|.  These characters will be
1686 printed in three- or four-symbol form like `\.{\^\^A}' or `\.{\^\^e4}'.
1687 (This procedure assumes that it is safe to bypass all checks for unprintable
1688 characters when |selector| is in the range |0..max_write_files-1| or when
1689 |selector=ps_file_only|.  In the former case the user might want to write
1690 unprintable characters, and in the latter case the \ps\ printing routines
1691 check their arguments themselves before calling |print_char| or |print|.)
1692
1693 @d print_lc_hex(A) do { l=(A);
1694     mp_print_visible_char(mp, (l<10 ? l+'0' : l-10+'a'));
1695   } while (0)
1696
1697 @<Basic printing...@>=
1698 void mp_print_char (MP mp, ASCII_code k) { /* prints a single character */
1699   int l; /* small index or counter */
1700   if ( mp->selector<pseudo || mp->selector>=write_file) {
1701     mp_print_visible_char(mp, k);
1702   } else if ( @<Character |k| cannot be printed@> ) { 
1703     mp_print(mp, "^^"); 
1704     if ( k<0100 ) { 
1705       mp_print_visible_char(mp, k+0100); 
1706     } else if ( k<0200 ) { 
1707       mp_print_visible_char(mp, k-0100); 
1708     } else { 
1709       print_lc_hex(k / 16);  
1710       print_lc_hex(k % 16); 
1711     }
1712   } else {
1713     mp_print_visible_char(mp, k);
1714   }
1715 };
1716
1717 @ An entire string is output by calling |print|. Note that if we are outputting
1718 the single standard ASCII character \.c, we could call |print("c")|, since
1719 |"c"=99| is the number of a single-character string, as explained above. But
1720 |print_char("c")| is quicker, so \MP\ goes directly to the |print_char|
1721 routine when it knows that this is safe. (The present implementation
1722 assumes that it is always safe to print a visible ASCII character.)
1723 @^system dependencies@>
1724
1725 @<Basic print...@>=
1726 void mp_do_print (MP mp, char *ss, unsigned int len) { /* prints string |s| */
1727   unsigned int j = 0;
1728   while ( j<len ){ 
1729     mp_print_char(mp, ss[j]); incr(j);
1730   }
1731 }
1732
1733
1734 @<Basic print...@>=
1735 void mp_print (MP mp, char *ss) {
1736   mp_do_print(mp, ss, strlen(ss));
1737 }
1738 void mp_print_str (MP mp, str_number s) {
1739   pool_pointer j; /* current character code position */
1740   if ( (s<0)||(s>mp->max_str_ptr) ) {
1741      mp_do_print(mp,"???",3); /* this can't happen */
1742 @.???@>
1743   }
1744   j=mp->str_start[s];
1745   mp_do_print(mp, (char *)(mp->str_pool+j), (str_stop(s)-j));
1746 }
1747
1748
1749 @ Here is the very first thing that \MP\ prints: a headline that identifies
1750 the version number and base name. The |term_offset| variable is temporarily
1751 incorrect, but the discrepancy is not serious since we assume that the banner
1752 and mem identifier together will occupy at most |max_print_line|
1753 character positions.
1754
1755 @<Initialize the output...@>=
1756 wterm (banner);
1757 wterm (version_string);
1758 if (mp->mem_ident!=NULL) 
1759   mp_print(mp,mp->mem_ident); 
1760 mp_print_ln(mp);
1761 update_terminal;
1762
1763 @ The procedure |print_nl| is like |print|, but it makes sure that the
1764 string appears at the beginning of a new line.
1765
1766 @<Basic print...@>=
1767 void mp_print_nl (MP mp, char *s) { /* prints string |s| at beginning of line */
1768   switch(mp->selector) {
1769   case term_and_log: 
1770     if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_ln(mp);
1771     break;
1772   case log_only: 
1773     if ( mp->file_offset>0 ) mp_print_ln(mp);
1774     break;
1775   case term_only: 
1776     if ( mp->term_offset>0 ) mp_print_ln(mp);
1777     break;
1778   case ps_file_only: 
1779     if ( mp->ps_offset>0 ) mp_print_ln(mp);
1780     break;
1781   case no_print:
1782   case pseudo:
1783   case new_string: 
1784         break;
1785   } /* there are no other cases */
1786   mp_print(mp, s);
1787 }
1788
1789 @ An array of digits in the range |0..9| is printed by |print_the_digs|.
1790
1791 @<Basic print...@>=
1792 void mp_print_the_digs (MP mp, eight_bits k) {
1793   /* prints |dig[k-1]|$\,\ldots\,$|dig[0]| */
1794   while ( k>0 ){ 
1795     decr(k); mp_print_char(mp, '0'+mp->dig[k]);
1796   }
1797 };
1798
1799 @ The following procedure, which prints out the decimal representation of a
1800 given integer |n|, has been written carefully so that it works properly
1801 if |n=0| or if |(-n)| would cause overflow. It does not apply |mod| or |div|
1802 to negative arguments, since such operations are not implemented consistently
1803 by all \PASCAL\ compilers.
1804
1805 @<Basic print...@>=
1806 void mp_print_int (MP mp,integer n) { /* prints an integer in decimal form */
1807   integer m; /* used to negate |n| in possibly dangerous cases */
1808   int k = 0; /* index to current digit; we assume that $|n|<10^{23}$ */
1809   if ( n<0 ) { 
1810     mp_print_char(mp, '-');
1811     if ( n>-100000000 ) {
1812           negate(n);
1813     } else  { 
1814           m=-1-n; n=m / 10; m=(m % 10)+1; k=1;
1815       if ( m<10 ) {
1816         mp->dig[0]=m;
1817       } else { 
1818         mp->dig[0]=0; incr(n);
1819       }
1820     }
1821   }
1822   do {  
1823     mp->dig[k]=n % 10; n=n / 10; incr(k);
1824   } while (n!=0);
1825   mp_print_the_digs(mp, k);
1826 };
1827
1828 @ @<Exported...@>=
1829 void mp_print_int (MP mp,integer n);
1830
1831 @ \MP\ also makes use of a trivial procedure to print two digits. The
1832 following subroutine is usually called with a parameter in the range |0<=n<=99|.
1833
1834 @c 
1835 void mp_print_dd (MP mp,integer n) { /* prints two least significant digits */
1836   n=abs(n) % 100; 
1837   mp_print_char(mp, '0'+(n / 10));
1838   mp_print_char(mp, '0'+(n % 10));
1839 }
1840
1841 @ Here is a procedure that asks the user to type a line of input,
1842 assuming that the |selector| setting is either |term_only| or |term_and_log|.
1843 The input is placed into locations |first| through |last-1| of the
1844 |buffer| array, and echoed on the transcript file if appropriate.
1845
1846 This procedure is never called when |interaction<mp_scroll_mode|.
1847
1848 @d prompt_input(A) do { 
1849     wake_up_terminal; mp_print(mp, (A)); mp_term_input(mp);
1850   } while (0) /* prints a string and gets a line of input */
1851
1852 @c 
1853 void mp_term_input (MP mp) { /* gets a line from the terminal */
1854   size_t k; /* index into |buffer| */
1855   update_terminal; /* Now the user sees the prompt for sure */
1856   if (!mp_input_ln(mp, mp->term_in,true)) 
1857     mp_fatal_error(mp, "End of file on the terminal!");
1858 @.End of file on the terminal@>
1859   mp->term_offset=0; /* the user's line ended with \<\rm return> */
1860   decr(mp->selector); /* prepare to echo the input */
1861   if ( mp->last!=mp->first ) {
1862     for (k=mp->first;k<=mp->last-1;k++) {
1863       mp_print_char(mp, mp->buffer[k]);
1864     }
1865   }
1866   mp_print_ln(mp); 
1867   mp->buffer[mp->last]='%'; 
1868   incr(mp->selector); /* restore previous status */
1869 };
1870
1871 @* \[6] Reporting errors.
1872 When something anomalous is detected, \MP\ typically does something like this:
1873 $$\vbox{\halign{#\hfil\cr
1874 |print_err("Something anomalous has been detected");|\cr
1875 |help3("This is the first line of my offer to help.")|\cr
1876 |("This is the second line. I'm trying to")|\cr
1877 |("explain the best way for you to proceed.");|\cr
1878 |error;|\cr}}$$
1879 A two-line help message would be given using |help2|, etc.; these informal
1880 helps should use simple vocabulary that complements the words used in the
1881 official error message that was printed. (Outside the U.S.A., the help
1882 messages should preferably be translated into the local vernacular. Each
1883 line of help is at most 60 characters long, in the present implementation,
1884 so that |max_print_line| will not be exceeded.)
1885
1886 The |print_err| procedure supplies a `\.!' before the official message,
1887 and makes sure that the terminal is awake if a stop is going to occur.
1888 The |error| procedure supplies a `\..' after the official message, then it
1889 shows the location of the error; and if |interaction=error_stop_mode|,
1890 it also enters into a dialog with the user, during which time the help
1891 message may be printed.
1892 @^system dependencies@>
1893
1894 @ The global variable |interaction| has four settings, representing increasing
1895 amounts of user interaction:
1896
1897 @<Types...@>=
1898 enum { 
1899  mp_unspecified_mode=0, /* extra value for command-line switch */
1900  mp_batch_mode, /* omits all stops and omits terminal output */
1901  mp_nonstop_mode, /* omits all stops */
1902  mp_scroll_mode, /* omits error stops */
1903  mp_error_stop_mode, /* stops at every opportunity to interact */
1904 };
1905
1906 @ @<Glob...@>=
1907 int interaction; /* current level of interaction */
1908
1909 @ @<Option variables@>=
1910 int interaction; /* current level of interaction */
1911
1912 @ Set it here so it can be overwritten by the commandline
1913
1914 @<Allocate or initialize ...@>=
1915 mp->interaction=opt.interaction;
1916 if (mp->interaction==mp_unspecified_mode || mp->interaction>mp_error_stop_mode) 
1917   mp->interaction=mp_error_stop_mode;
1918 if (mp->interaction<mp_unspecified_mode) 
1919   mp->interaction=mp_batch_mode;
1920
1921
1922
1923 @d print_err(A) mp_print_err(mp,(A))
1924
1925 @<Exported...@>=
1926 void mp_print_err(MP mp, char * A);
1927
1928 @ @c
1929 void mp_print_err(MP mp, char * A) { 
1930   if ( mp->interaction==mp_error_stop_mode ) 
1931     wake_up_terminal;
1932   mp_print_nl(mp, "! "); 
1933   mp_print(mp, A);
1934 @.!\relax@>
1935 }
1936
1937
1938 @ \MP\ is careful not to call |error| when the print |selector| setting
1939 might be unusual. The only possible values of |selector| at the time of
1940 error messages are
1941
1942 \yskip\hang|no_print| (when |interaction=mp_batch_mode|
1943   and |log_file| not yet open);
1944
1945 \hang|term_only| (when |interaction>mp_batch_mode| and |log_file| not yet open);
1946
1947 \hang|log_only| (when |interaction=mp_batch_mode| and |log_file| is open);
1948
1949 \hang|term_and_log| (when |interaction>mp_batch_mode| and |log_file| is open).
1950
1951 @<Initialize the print |selector| based on |interaction|@>=
1952 if ( mp->interaction==mp_batch_mode ) mp->selector=no_print; else mp->selector=term_only
1953
1954 @ A global variable |deletions_allowed| is set |false| if the |get_next|
1955 routine is active when |error| is called; this ensures that |get_next|
1956 will never be called recursively.
1957 @^recursion@>
1958
1959 The global variable |history| records the worst level of error that
1960 has been detected. It has four possible values: |spotless|, |warning_issued|,
1961 |error_message_issued|, and |fatal_error_stop|.
1962
1963 Another global variable, |error_count|, is increased by one when an
1964 |error| occurs without an interactive dialog, and it is reset to zero at
1965 the end of every statement.  If |error_count| reaches 100, \MP\ decides
1966 that there is no point in continuing further.
1967
1968 @d spotless 0 /* |history| value when nothing has been amiss yet */
1969 @d warning_issued 1 /* |history| value when |begin_diagnostic| has been called */
1970 @d error_message_issued 2 /* |history| value when |error| has been called */
1971 @d fatal_error_stop 3 /* |history| value when termination was premature */
1972
1973 @<Glob...@>=
1974 boolean deletions_allowed; /* is it safe for |error| to call |get_next|? */
1975 int history; /* has the source input been clean so far? */
1976 int error_count; /* the number of scrolled errors since the last statement ended */
1977
1978 @ The value of |history| is initially |fatal_error_stop|, but it will
1979 be changed to |spotless| if \MP\ survives the initialization process.
1980
1981 @<Allocate or ...@>=
1982 mp->deletions_allowed=true; mp->error_count=0; /* |history| is initialized elsewhere */
1983
1984 @ Since errors can be detected almost anywhere in \MP, we want to declare the
1985 error procedures near the beginning of the program. But the error procedures
1986 in turn use some other procedures, which need to be declared |forward|
1987 before we get to |error| itself.
1988
1989 It is possible for |error| to be called recursively if some error arises
1990 when |get_next| is being used to delete a token, and/or if some fatal error
1991 occurs while \MP\ is trying to fix a non-fatal one. But such recursion
1992 @^recursion@>
1993 is never more than two levels deep.
1994
1995 @<Declarations@>=
1996 void mp_get_next (MP mp);
1997 void mp_term_input (MP mp);
1998 void mp_show_context (MP mp);
1999 void mp_begin_file_reading (MP mp);
2000 void mp_open_log_file (MP mp);
2001 void mp_clear_for_error_prompt (MP mp);
2002 void mp_debug_help (MP mp);
2003 @<Declare the procedure called |flush_string|@>
2004
2005 @ @<Exported...@>=
2006 void mp_normalize_selector (MP mp);
2007
2008 @ Individual lines of help are recorded in the array |help_line|, which
2009 contains entries in positions |0..(help_ptr-1)|. They should be printed
2010 in reverse order, i.e., with |help_line[0]| appearing last.
2011
2012 @d hlp1(A) mp->help_line[0]=(A); }
2013 @d hlp2(A) mp->help_line[1]=(A); hlp1
2014 @d hlp3(A) mp->help_line[2]=(A); hlp2
2015 @d hlp4(A) mp->help_line[3]=(A); hlp3
2016 @d hlp5(A) mp->help_line[4]=(A); hlp4
2017 @d hlp6(A) mp->help_line[5]=(A); hlp5
2018 @d help0 mp->help_ptr=0 /* sometimes there might be no help */
2019 @d help1  { mp->help_ptr=1; hlp1 /* use this with one help line */
2020 @d help2  { mp->help_ptr=2; hlp2 /* use this with two help lines */
2021 @d help3  { mp->help_ptr=3; hlp3 /* use this with three help lines */
2022 @d help4  { mp->help_ptr=4; hlp4 /* use this with four help lines */
2023 @d help5  { mp->help_ptr=5; hlp5 /* use this with five help lines */
2024 @d help6  { mp->help_ptr=6; hlp6 /* use this with six help lines */
2025
2026 @<Glob...@>=
2027 char * help_line[6]; /* helps for the next |error| */
2028 unsigned int help_ptr; /* the number of help lines present */
2029 boolean use_err_help; /* should the |err_help| string be shown? */
2030 str_number err_help; /* a string set up by \&{errhelp} */
2031 str_number filename_template; /* a string set up by \&{filenametemplate} */
2032
2033 @ @<Allocate or ...@>=
2034 mp->help_ptr=0; mp->use_err_help=false; mp->err_help=0; mp->filename_template=0;
2035
2036 @ The |jump_out| procedure just cuts across all active procedure levels and
2037 goes to |end_of_MP|. This is the only nonlocal |goto| statement in the
2038 whole program. It is used when there is no recovery from a particular error.
2039
2040 Some \PASCAL\ compilers do not implement non-local |goto| statements.
2041 @^system dependencies@>
2042 In such cases the body of |jump_out| should simply be
2043 `|close_files_and_terminate|;\thinspace' followed by a call on some system
2044 procedure that quietly terminates the program.
2045
2046 @<Error hand...@>=
2047 void mp_jump_out (MP mp) { 
2048  exit(mp->history);
2049 };
2050
2051 @ Here now is the general |error| routine.
2052
2053 @<Error hand...@>=
2054 void mp_error (MP mp) { /* completes the job of error reporting */
2055   ASCII_code c; /* what the user types */
2056   integer s1,s2,s3; /* used to save global variables when deleting tokens */
2057   pool_pointer j; /* character position being printed */
2058   if ( mp->history<error_message_issued ) mp->history=error_message_issued;
2059   mp_print_char(mp, '.'); mp_show_context(mp);
2060   if ( mp->interaction==mp_error_stop_mode ) {
2061     @<Get user's advice and |return|@>;
2062   }
2063   incr(mp->error_count);
2064   if ( mp->error_count==100 ) { 
2065     mp_print_nl(mp,"(That makes 100 errors; please try again.)");
2066 @.That makes 100 errors...@>
2067     mp->history=fatal_error_stop; mp_jump_out(mp);
2068   }
2069   @<Put help message on the transcript file@>;
2070 }
2071 void mp_warn (MP mp, char *msg) {
2072   int saved_selector = mp->selector;
2073   mp_normalize_selector(mp);
2074   mp_print_nl(mp,"Warning: ");
2075   mp_print(mp,msg);
2076   mp->selector = saved_selector;
2077 }
2078
2079 @ @<Exported...@>=
2080 void mp_error (MP mp);
2081 void mp_warn (MP mp, char *msg);
2082
2083
2084 @ @<Get user's advice...@>=
2085 while (1) { 
2086 CONTINUE:
2087   mp_clear_for_error_prompt(mp); prompt_input("? ");
2088 @.?\relax@>
2089   if ( mp->last==mp->first ) return;
2090   c=mp->buffer[mp->first];
2091   if ( c>='a' ) c=c+'A'-'a'; /* convert to uppercase */
2092   @<Interpret code |c| and |return| if done@>;
2093 }
2094
2095 @ It is desirable to provide an `\.E' option here that gives the user
2096 an easy way to return from \MP\ to the system editor, with the offending
2097 line ready to be edited. But such an extension requires some system
2098 wizardry, so the present implementation simply types out the name of the
2099 file that should be
2100 edited and the relevant line number.
2101 @^system dependencies@>
2102
2103 @<Types...@>=
2104 typedef void (*run_editor_command)(MP, char *, int);
2105
2106 @ @<Glob...@>=
2107 run_editor_command run_editor;
2108
2109 @ @<Option variables@>=
2110 run_editor_command run_editor;
2111
2112 @ @<Allocate or initialize ...@>=
2113 set_callback_option(run_editor);
2114
2115 @ @<Exported function headers@>=
2116 void mp_run_editor (MP mp, char *fname, int fline);
2117
2118 @ @c void mp_run_editor (MP mp, char *fname, int fline) {
2119     mp_print_nl(mp, "You want to edit file ");
2120 @.You want to edit file x@>
2121     mp_print(mp, fname);
2122     mp_print(mp, " at line "); 
2123     mp_print_int(mp, fline);
2124     mp->interaction=mp_scroll_mode; 
2125     mp_jump_out(mp);
2126 }
2127
2128
2129 There is a secret `\.D' option available when the debugging routines haven't
2130 been commented~out.
2131 @^debugging@>
2132
2133 @<Interpret code |c| and |return| if done@>=
2134 switch (c) {
2135 case '0': case '1': case '2': case '3': case '4':
2136 case '5': case '6': case '7': case '8': case '9': 
2137   if ( mp->deletions_allowed ) {
2138     @<Delete |c-"0"| tokens and |continue|@>;
2139   }
2140   break;
2141 #ifdef DEBUG
2142 case 'D': 
2143   mp_debug_help(mp); continue; 
2144   break;
2145 #endif
2146 case 'E': 
2147   if ( mp->file_ptr>0 ){ 
2148     (mp->run_editor)(mp, 
2149                      str(mp->input_stack[mp->file_ptr].name_field), 
2150                      mp_true_line(mp));
2151   }
2152   break;
2153 case 'H': 
2154   @<Print the help information and |continue|@>;
2155   break;
2156 case 'I':
2157   @<Introduce new material from the terminal and |return|@>;
2158   break;
2159 case 'Q': case 'R': case 'S':
2160   @<Change the interaction level and |return|@>;
2161   break;
2162 case 'X':
2163   mp->interaction=mp_scroll_mode; mp_jump_out(mp);
2164   break;
2165 default:
2166   break;
2167 }
2168 @<Print the menu of available options@>
2169
2170 @ @<Print the menu...@>=
2171
2172   mp_print(mp, "Type <return> to proceed, S to scroll future error messages,");
2173 @.Type <return> to proceed...@>
2174   mp_print_nl(mp, "R to run without stopping, Q to run quietly,");
2175   mp_print_nl(mp, "I to insert something, ");
2176   if ( mp->file_ptr>0 ) 
2177     mp_print(mp, "E to edit your file,");
2178   if ( mp->deletions_allowed )
2179     mp_print_nl(mp, "1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
2180   mp_print_nl(mp, "H for help, X to quit.");
2181 }
2182
2183 @ Here the author of \MP\ apologizes for making use of the numerical
2184 relation between |"Q"|, |"R"|, |"S"|, and the desired interaction settings
2185 |mp_batch_mode|, |mp_nonstop_mode|, |mp_scroll_mode|.
2186 @^Knuth, Donald Ervin@>
2187
2188 @<Change the interaction...@>=
2189
2190   mp->error_count=0; mp->interaction=mp_batch_mode+c-'Q';
2191   mp_print(mp, "OK, entering ");
2192   switch (c) {
2193   case 'Q': mp_print(mp, "batchmode"); decr(mp->selector); break;
2194   case 'R': mp_print(mp, "nonstopmode"); break;
2195   case 'S': mp_print(mp, "scrollmode"); break;
2196   } /* there are no other cases */
2197   mp_print(mp, "..."); mp_print_ln(mp); update_terminal; return;
2198 }
2199
2200 @ When the following code is executed, |buffer[(first+1)..(last-1)]| may
2201 contain the material inserted by the user; otherwise another prompt will
2202 be given. In order to understand this part of the program fully, you need
2203 to be familiar with \MP's input stacks.
2204
2205 @<Introduce new material...@>=
2206
2207   mp_begin_file_reading(mp); /* enter a new syntactic level for terminal input */
2208   if ( mp->last>mp->first+1 ) { 
2209     loc=mp->first+1; mp->buffer[mp->first]=' ';
2210   } else { 
2211    prompt_input("insert>"); loc=mp->first;
2212 @.insert>@>
2213   };
2214   mp->first=mp->last+1; mp->cur_input.limit_field=mp->last; return;
2215 }
2216
2217 @ We allow deletion of up to 99 tokens at a time.
2218
2219 @<Delete |c-"0"| tokens...@>=
2220
2221   s1=mp->cur_cmd; s2=mp->cur_mod; s3=mp->cur_sym; mp->OK_to_interrupt=false;
2222   if ( (mp->last>mp->first+1) && (mp->buffer[mp->first+1]>='0')&&(mp->buffer[mp->first+1]<='9') )
2223     c=c*10+mp->buffer[mp->first+1]-'0'*11;
2224   else 
2225     c=c-'0';
2226   while ( c>0 ) { 
2227     mp_get_next(mp); /* one-level recursive call of |error| is possible */
2228     @<Decrease the string reference count, if the current token is a string@>;
2229     decr(c);
2230   };
2231   mp->cur_cmd=s1; mp->cur_mod=s2; mp->cur_sym=s3; mp->OK_to_interrupt=true;
2232   help2("I have just deleted some text, as you asked.")
2233        ("You can now delete more, or insert, or whatever.");
2234   mp_show_context(mp); 
2235   goto CONTINUE;
2236 }
2237
2238 @ @<Print the help info...@>=
2239
2240   if ( mp->use_err_help ) { 
2241     @<Print the string |err_help|, possibly on several lines@>;
2242     mp->use_err_help=false;
2243   } else { 
2244     if ( mp->help_ptr==0 ) {
2245       help2("Sorry, I don't know how to help in this situation.")
2246            ("Maybe you should try asking a human?");
2247      }
2248     do { 
2249       decr(mp->help_ptr); mp_print(mp, mp->help_line[mp->help_ptr]); mp_print_ln(mp);
2250     } while (mp->help_ptr!=0);
2251   };
2252   help4("Sorry, I already gave what help I could...")
2253        ("Maybe you should try asking a human?")
2254        ("An error might have occurred before I noticed any problems.")
2255        ("``If all else fails, read the instructions.''");
2256   goto CONTINUE;
2257 }
2258
2259 @ @<Print the string |err_help|, possibly on several lines@>=
2260 j=mp->str_start[mp->err_help];
2261 while ( j<str_stop(mp->err_help) ) { 
2262   if ( mp->str_pool[j]!='%' ) mp_print_str(mp, mp->str_pool[j]);
2263   else if ( j+1==str_stop(mp->err_help) ) mp_print_ln(mp);
2264   else if ( mp->str_pool[j+1]!='%' ) mp_print_ln(mp);
2265   else  { incr(j); mp_print_char(mp, '%'); };
2266   incr(j);
2267 }
2268
2269 @ @<Put help message on the transcript file@>=
2270 if ( mp->interaction>mp_batch_mode ) decr(mp->selector); /* avoid terminal output */
2271 if ( mp->use_err_help ) { 
2272   mp_print_nl(mp, "");
2273   @<Print the string |err_help|, possibly on several lines@>;
2274 } else { 
2275   while ( mp->help_ptr>0 ){ 
2276     decr(mp->help_ptr); mp_print_nl(mp, mp->help_line[mp->help_ptr]);
2277   };
2278 }
2279 mp_print_ln(mp);
2280 if ( mp->interaction>mp_batch_mode ) incr(mp->selector); /* re-enable terminal output */
2281 mp_print_ln(mp)
2282
2283 @ In anomalous cases, the print selector might be in an unknown state;
2284 the following subroutine is called to fix things just enough to keep
2285 running a bit longer.
2286
2287 @c 
2288 void mp_normalize_selector (MP mp) { 
2289   if ( mp->log_opened ) mp->selector=term_and_log;
2290   else mp->selector=term_only;
2291   if ( mp->job_name==NULL ) mp_open_log_file(mp);
2292   if ( mp->interaction==mp_batch_mode ) decr(mp->selector);
2293 }
2294
2295 @ The following procedure prints \MP's last words before dying.
2296
2297 @d succumb { if ( mp->interaction==mp_error_stop_mode )
2298     mp->interaction=mp_scroll_mode; /* no more interaction */
2299   if ( mp->log_opened ) mp_error(mp);
2300   /* if ( mp->interaction>mp_batch_mode ) mp_debug_help(mp); */
2301   mp->history=fatal_error_stop; mp_jump_out(mp); /* irrecoverable error */
2302   }
2303
2304 @<Error hand...@>=
2305 void mp_fatal_error (MP mp, char *s) { /* prints |s|, and that's it */
2306   mp_normalize_selector(mp);
2307   print_err("Emergency stop"); help1(s); succumb;
2308 @.Emergency stop@>
2309 }
2310
2311 @ @<Exported...@>=
2312 void mp_fatal_error (MP mp, char *s);
2313
2314
2315 @ Here is the most dreaded error message.
2316
2317 @<Error hand...@>=
2318 void mp_overflow (MP mp, char *s, integer n) { /* stop due to finiteness */
2319   mp_normalize_selector(mp);
2320   print_err("MetaPost capacity exceeded, sorry [");
2321 @.MetaPost capacity exceeded ...@>
2322   mp_print(mp, s); mp_print_char(mp, '='); mp_print_int(mp, n); mp_print_char(mp, ']');
2323   help2("If you really absolutely need more capacity,")
2324        ("you can ask a wizard to enlarge me.");
2325   succumb;
2326 }
2327
2328 @ @<Declarations@>=
2329 void mp_overflow (MP mp, char *s, integer n);
2330
2331 @ The program might sometime run completely amok, at which point there is
2332 no choice but to stop. If no previous error has been detected, that's bad
2333 news; a message is printed that is really intended for the \MP\
2334 maintenance person instead of the user (unless the user has been
2335 particularly diabolical).  The index entries for `this can't happen' may
2336 help to pinpoint the problem.
2337 @^dry rot@>
2338
2339 @<Declarations@>=
2340 void mp_confusion (MP mp,char *s);
2341
2342 @ @<Error hand...@>=
2343 void mp_confusion (MP mp,char *s) {
2344   /* consistency check violated; |s| tells where */
2345   mp_normalize_selector(mp);
2346   if ( mp->history<error_message_issued ) { 
2347     print_err("This can't happen ("); mp_print(mp, s); mp_print_char(mp, ')');
2348 @.This can't happen@>
2349     help1("I'm broken. Please show this to someone who can fix can fix");
2350   } else { 
2351     print_err("I can\'t go on meeting you like this");
2352 @.I can't go on...@>
2353     help2("One of your faux pas seems to have wounded me deeply...")
2354          ("in fact, I'm barely conscious. Please fix it and try again.");
2355   }
2356   succumb;
2357 }
2358
2359 @ Users occasionally want to interrupt \MP\ while it's running.
2360 If the \PASCAL\ runtime system allows this, one can implement
2361 a routine that sets the global variable |interrupt| to some nonzero value
2362 when such an interrupt is signaled. Otherwise there is probably at least
2363 a way to make |interrupt| nonzero using the \PASCAL\ debugger.
2364 @^system dependencies@>
2365 @^debugging@>
2366
2367 @d check_interrupt { if ( mp->interrupt!=0 )
2368    mp_pause_for_instructions(mp); }
2369
2370 @<Global...@>=
2371 integer interrupt; /* should \MP\ pause for instructions? */
2372 boolean OK_to_interrupt; /* should interrupts be observed? */
2373
2374 @ @<Allocate or ...@>=
2375 mp->interrupt=0; mp->OK_to_interrupt=true;
2376
2377 @ When an interrupt has been detected, the program goes into its
2378 highest interaction level and lets the user have the full flexibility of
2379 the |error| routine.  \MP\ checks for interrupts only at times when it is
2380 safe to do this.
2381
2382 @c 
2383 void mp_pause_for_instructions (MP mp) { 
2384   if ( mp->OK_to_interrupt ) { 
2385     mp->interaction=mp_error_stop_mode;
2386     if ( (mp->selector==log_only)||(mp->selector==no_print) )
2387       incr(mp->selector);
2388     print_err("Interruption");
2389 @.Interruption@>
2390     help3("You rang?")
2391          ("Try to insert some instructions for me (e.g.,`I show x'),")
2392          ("unless you just want to quit by typing `X'.");
2393     mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
2394     mp->interrupt=0;
2395   }
2396 }
2397
2398 @ Many of \MP's error messages state that a missing token has been
2399 inserted behind the scenes. We can save string space and program space
2400 by putting this common code into a subroutine.
2401
2402 @c 
2403 void mp_missing_err (MP mp, char *s) { 
2404   print_err("Missing `"); mp_print(mp, s); mp_print(mp, "' has been inserted");
2405 @.Missing...inserted@>
2406 }
2407
2408 @* \[7] Arithmetic with scaled numbers.
2409 The principal computations performed by \MP\ are done entirely in terms of
2410 integers less than $2^{31}$ in magnitude; thus, the arithmetic specified in this
2411 program can be carried out in exactly the same way on a wide variety of
2412 computers, including some small ones.
2413 @^small computers@>
2414
2415 But \PASCAL\ does not define the |div|
2416 operation in the case of negative dividends; for example, the result of
2417 |(-2*n-1) div 2| is |-(n+1)| on some computers and |-n| on others.
2418 There are two principal types of arithmetic: ``translation-preserving,''
2419 in which the identity |(a+q*b)div b=(a div b)+q| is valid; and
2420 ``negation-preserving,'' in which |(-a)div b=-(a div b)|. This leads to
2421 two \MP s, which can produce different results, although the differences
2422 should be negligible when the language is being used properly.
2423 The \TeX\ processor has been defined carefully so that both varieties
2424 of arithmetic will produce identical output, but it would be too
2425 inefficient to constrain \MP\ in a similar way.
2426
2427 @d el_gordo   017777777777 /* $2^{31}-1$, the largest value that \MP\ likes */
2428
2429 @ One of \MP's most common operations is the calculation of
2430 $\lfloor{a+b\over2}\rfloor$,
2431 the midpoint of two given integers |a| and~|b|. The only decent way to do
2432 this in \PASCAL\ is to write `|(a+b) div 2|'; but on most machines it is
2433 far more efficient to calculate `|(a+b)| right shifted one bit'.
2434
2435 Therefore the midpoint operation will always be denoted by `|half(a+b)|'
2436 in this program. If \MP\ is being implemented with languages that permit
2437 binary shifting, the |half| macro should be changed to make this operation
2438 as efficient as possible.  Since some languages have shift operators that can
2439 only be trusted to work on positive numbers, there is also a macro |halfp|
2440 that is used only when the quantity being halved is known to be positive
2441 or zero.
2442
2443 @d half(A) ((A)) / 2
2444 @d halfp(A) ((A)) / 2
2445
2446 @ A single computation might use several subroutine calls, and it is
2447 desirable to avoid producing multiple error messages in case of arithmetic
2448 overflow. So the routines below set the global variable |arith_error| to |true|
2449 instead of reporting errors directly to the user.
2450
2451 @<Glob...@>=
2452 boolean arith_error; /* has arithmetic overflow occurred recently? */
2453
2454 @ @<Allocate or ...@>=
2455 mp->arith_error=false;
2456
2457 @ At crucial points the program will say |check_arith|, to test if
2458 an arithmetic error has been detected.
2459
2460 @d check_arith { if ( mp->arith_error ) mp_clear_arith(mp); }
2461
2462 @c 
2463 void mp_clear_arith (MP mp) { 
2464   print_err("Arithmetic overflow");
2465 @.Arithmetic overflow@>
2466   help4("Uh, oh. A little while ago one of the quantities that I was")
2467        ("computing got too large, so I'm afraid your answers will be")
2468        ("somewhat askew. You'll probably have to adopt different")
2469        ("tactics next time. But I shall try to carry on anyway.");
2470   mp_error(mp); 
2471   mp->arith_error=false;
2472 }
2473
2474 @ Addition is not always checked to make sure that it doesn't overflow,
2475 but in places where overflow isn't too unlikely the |slow_add| routine
2476 is used.
2477
2478 @c integer mp_slow_add (MP mp,integer x, integer y) { 
2479   if ( x>=0 )  {
2480     if ( y<=el_gordo-x ) { 
2481       return x+y;
2482     } else  { 
2483       mp->arith_error=true; 
2484           return el_gordo;
2485     }
2486   } else  if ( -y<=el_gordo+x ) {
2487     return x+y;
2488   } else { 
2489     mp->arith_error=true; 
2490         return -el_gordo;
2491   }
2492 }
2493
2494 @ Fixed-point arithmetic is done on {\sl scaled integers\/} that are multiples
2495 of $2^{-16}$. In other words, a binary point is assumed to be sixteen bit
2496 positions from the right end of a binary computer word.
2497
2498 @d quarter_unit   040000 /* $2^{14}$, represents 0.250000 */
2499 @d half_unit   0100000 /* $2^{15}$, represents 0.50000 */
2500 @d three_quarter_unit   0140000 /* $3\cdot2^{14}$, represents 0.75000 */
2501 @d unity   0200000 /* $2^{16}$, represents 1.00000 */
2502 @d two   0400000 /* $2^{17}$, represents 2.00000 */
2503 @d three   0600000 /* $2^{17}+2^{16}$, represents 3.00000 */
2504
2505 @<Types...@>=
2506 typedef integer scaled; /* this type is used for scaled integers */
2507 typedef unsigned char small_number; /* this type is self-explanatory */
2508
2509 @ The following function is used to create a scaled integer from a given decimal
2510 fraction $(.d_0d_1\ldots d_{k-1})$, where |0<=k<=17|. The digit $d_i$ is
2511 given in |dig[i]|, and the calculation produces a correctly rounded result.
2512
2513 @c 
2514 scaled mp_round_decimals (MP mp,small_number k) {
2515   /* converts a decimal fraction */
2516  integer a = 0; /* the accumulator */
2517  while ( k-->0 ) { 
2518     a=(a+mp->dig[k]*two) / 10;
2519   }
2520   return halfp(a+1);
2521 }
2522
2523 @ Conversely, here is a procedure analogous to |print_int|. If the output
2524 of this procedure is subsequently read by \MP\ and converted by the
2525 |round_decimals| routine above, it turns out that the original value will
2526 be reproduced exactly. A decimal point is printed only if the value is
2527 not an integer. If there is more than one way to print the result with
2528 the optimum number of digits following the decimal point, the closest
2529 possible value is given.
2530
2531 The invariant relation in the \&{repeat} loop is that a sequence of
2532 decimal digits yet to be printed will yield the original number if and only if
2533 they form a fraction~$f$ in the range $s-\delta\L10\cdot2^{16}f<s$.
2534 We can stop if and only if $f=0$ satisfies this condition; the loop will
2535 terminate before $s$ can possibly become zero.
2536
2537 @<Basic printing...@>=
2538 void mp_print_scaled (MP mp,scaled s) { /* prints scaled real, rounded to five  digits */
2539   scaled delta; /* amount of allowable inaccuracy */
2540   if ( s<0 ) { 
2541         mp_print_char(mp, '-'); 
2542     negate(s); /* print the sign, if negative */
2543   }
2544   mp_print_int(mp, s / unity); /* print the integer part */
2545   s=10*(s % unity)+5;
2546   if ( s!=5 ) { 
2547     delta=10; 
2548     mp_print_char(mp, '.');
2549     do {  
2550       if ( delta>unity )
2551         s=s+0100000-(delta / 2); /* round the final digit */
2552       mp_print_char(mp, '0'+(s / unity)); 
2553       s=10*(s % unity); 
2554       delta=delta*10;
2555     } while (s>delta);
2556   }
2557 }
2558
2559 @ We often want to print two scaled quantities in parentheses,
2560 separated by a comma.
2561
2562 @<Basic printing...@>=
2563 void mp_print_two (MP mp,scaled x, scaled y) { /* prints `|(x,y)|' */
2564   mp_print_char(mp, '('); 
2565   mp_print_scaled(mp, x); 
2566   mp_print_char(mp, ','); 
2567   mp_print_scaled(mp, y);
2568   mp_print_char(mp, ')');
2569 }
2570
2571 @ The |scaled| quantities in \MP\ programs are generally supposed to be
2572 less than $2^{12}$ in absolute value, so \MP\ does much of its internal
2573 arithmetic with 28~significant bits of precision. A |fraction| denotes
2574 a scaled integer whose binary point is assumed to be 28 bit positions
2575 from the right.
2576
2577 @d fraction_half 01000000000 /* $2^{27}$, represents 0.50000000 */
2578 @d fraction_one 02000000000 /* $2^{28}$, represents 1.00000000 */
2579 @d fraction_two 04000000000 /* $2^{29}$, represents 2.00000000 */
2580 @d fraction_three 06000000000 /* $3\cdot2^{28}$, represents 3.00000000 */
2581 @d fraction_four 010000000000 /* $2^{30}$, represents 4.00000000 */
2582
2583 @<Types...@>=
2584 typedef integer fraction; /* this type is used for scaled fractions */
2585
2586 @ In fact, the two sorts of scaling discussed above aren't quite
2587 sufficient; \MP\ has yet another, used internally to keep track of angles
2588 in units of $2^{-20}$ degrees.
2589
2590 @d forty_five_deg 0264000000 /* $45\cdot2^{20}$, represents $45^\circ$ */
2591 @d ninety_deg 0550000000 /* $90\cdot2^{20}$, represents $90^\circ$ */
2592 @d one_eighty_deg 01320000000 /* $180\cdot2^{20}$, represents $180^\circ$ */
2593 @d three_sixty_deg 02640000000 /* $360\cdot2^{20}$, represents $360^\circ$ */
2594
2595 @<Types...@>=
2596 typedef integer angle; /* this type is used for scaled angles */
2597
2598 @ The |make_fraction| routine produces the |fraction| equivalent of
2599 |p/q|, given integers |p| and~|q|; it computes the integer
2600 $f=\lfloor2^{28}p/q+{1\over2}\rfloor$, when $p$ and $q$ are
2601 positive. If |p| and |q| are both of the same scaled type |t|,
2602 the ``type relation'' |make_fraction(t,t)=fraction| is valid;
2603 and it's also possible to use the subroutine ``backwards,'' using
2604 the relation |make_fraction(t,fraction)=t| between scaled types.
2605
2606 If the result would have magnitude $2^{31}$ or more, |make_fraction|
2607 sets |arith_error:=true|. Most of \MP's internal computations have
2608 been designed to avoid this sort of error.
2609
2610 If this subroutine were programmed in assembly language on a typical
2611 machine, we could simply compute |(@t$2^{28}$@>*p)div q|, since a
2612 double-precision product can often be input to a fixed-point division
2613 instruction. But when we are restricted to \PASCAL\ arithmetic it
2614 is necessary either to resort to multiple-precision maneuvering
2615 or to use a simple but slow iteration. The multiple-precision technique
2616 would be about three times faster than the code adopted here, but it
2617 would be comparatively long and tricky, involving about sixteen
2618 additional multiplications and divisions.
2619
2620 This operation is part of \MP's ``inner loop''; indeed, it will
2621 consume nearly 10\pct! of the running time (exclusive of input and output)
2622 if the code below is left unchanged. A machine-dependent recoding
2623 will therefore make \MP\ run faster. The present implementation
2624 is highly portable, but slow; it avoids multiplication and division
2625 except in the initial stage. System wizards should be careful to
2626 replace it with a routine that is guaranteed to produce identical
2627 results in all cases.
2628 @^system dependencies@>
2629
2630 As noted below, a few more routines should also be replaced by machine-dependent
2631 code, for efficiency. But when a procedure is not part of the ``inner loop,''
2632 such changes aren't advisable; simplicity and robustness are
2633 preferable to trickery, unless the cost is too high.
2634 @^inner loop@>
2635
2636 @<Exported...@>=
2637 fraction mp_make_fraction (MP mp,integer p, integer q);
2638 integer mp_take_scaled (MP mp,integer q, scaled f) ;
2639
2640 @ If FIXPT is not defined, we need these preprocessor values
2641
2642 @d ELGORDO  0x7fffffff
2643 @d TWEXP31  2147483648.0
2644 @d TWEXP28  268435456.0
2645 @d TWEXP16 65536.0
2646 @d TWEXP_16 (1.0/65536.0)
2647 @d TWEXP_28 (1.0/268435456.0)
2648
2649
2650 @c 
2651 fraction mp_make_fraction (MP mp,integer p, integer q) {
2652 #ifdef FIXPT
2653   integer f; /* the fraction bits, with a leading 1 bit */
2654   integer n; /* the integer part of $\vert p/q\vert$ */
2655   integer be_careful; /* disables certain compiler optimizations */
2656   boolean negative = false; /* should the result be negated? */
2657   if ( p<0 ) {
2658     negate(p); negative=true;
2659   }
2660   if ( q<=0 ) { 
2661 #ifdef DEBUG
2662     if ( q==0 ) mp_confusion(mp, '/');
2663 #endif
2664 @:this can't happen /}{\quad \./@>
2665     negate(q); negative = ! negative;
2666   };
2667   n=p / q; p=p % q;
2668   if ( n>=8 ){ 
2669     mp->arith_error=true;
2670     return ( negative ? -el_gordo : el_gordo);
2671   } else { 
2672     n=(n-1)*fraction_one;
2673     @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>;
2674     return (negative ? (-(f+n)) : (f+n));
2675   }
2676 #else /* FIXPT */
2677     register double d;
2678         register integer i;
2679 #ifdef DEBUG
2680         if (q==0) mp_confusion(mp,'/'); 
2681 #endif /* DEBUG */
2682         d = TWEXP28 * (double)p /(double)q;
2683         if ((p^q) >= 0) {
2684                 d += 0.5;
2685                 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
2686                 i = (integer) d;
2687                 if (d==i && ( ((q>0 ? -q : q)&077777)
2688                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2689         } else {
2690                 d -= 0.5;
2691                 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
2692                 i = (integer) d;
2693                 if (d==i && ( ((q>0 ? q : -q)&077777)
2694                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
2695         }
2696         return i;
2697 #endif /* FIXPT */
2698 }
2699
2700 @ The |repeat| loop here preserves the following invariant relations
2701 between |f|, |p|, and~|q|:
2702 (i)~|0<=p<q|; (ii)~$fq+p=2^k(q+p_0)$, where $k$ is an integer and
2703 $p_0$ is the original value of~$p$.
2704
2705 Notice that the computation specifies
2706 |(p-q)+p| instead of |(p+p)-q|, because the latter could overflow.
2707 Let us hope that optimizing compilers do not miss this point; a
2708 special variable |be_careful| is used to emphasize the necessary
2709 order of computation. Optimizing compilers should keep |be_careful|
2710 in a register, not store it in memory.
2711 @^inner loop@>
2712
2713 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>=
2714 {
2715   f=1;
2716   do {  
2717     be_careful=p-q; p=be_careful+p;
2718     if ( p>=0 ) { 
2719       f=f+f+1;
2720     } else  { 
2721       f+=f; p=p+q;
2722     }
2723   } while (f<fraction_one);
2724   be_careful=p-q;
2725   if ( be_careful+p>=0 ) incr(f);
2726 }
2727
2728 @ The dual of |make_fraction| is |take_fraction|, which multiplies a
2729 given integer~|q| by a fraction~|f|. When the operands are positive, it
2730 computes $p=\lfloor qf/2^{28}+{1\over2}\rfloor$, a symmetric function
2731 of |q| and~|f|.
2732
2733 This routine is even more ``inner loopy'' than |make_fraction|;
2734 the present implementation consumes almost 20\pct! of \MP's computation
2735 time during typical jobs, so a machine-language substitute is advisable.
2736 @^inner loop@> @^system dependencies@>
2737
2738 @<Declarations@>=
2739 integer mp_take_fraction (MP mp,integer q, fraction f) ;
2740
2741 @ @c 
2742 #ifdef FIXPT
2743 integer mp_take_fraction (MP mp,integer q, fraction f) {
2744   integer p; /* the fraction so far */
2745   boolean negative; /* should the result be negated? */
2746   integer n; /* additional multiple of $q$ */
2747   integer be_careful; /* disables certain compiler optimizations */
2748   @<Reduce to the case that |f>=0| and |q>0|@>;
2749   if ( f<fraction_one ) { 
2750     n=0;
2751   } else { 
2752     n=f / fraction_one; f=f % fraction_one;
2753     if ( q<=el_gordo / n ) { 
2754       n=n*q ; 
2755     } else { 
2756       mp->arith_error=true; n=el_gordo;
2757     }
2758   }
2759   f=f+fraction_one;
2760   @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>;
2761   be_careful=n-el_gordo;
2762   if ( be_careful+p>0 ){ 
2763     mp->arith_error=true; n=el_gordo-p;
2764   }
2765   if ( negative ) 
2766         return (-(n+p));
2767   else 
2768     return (n+p);
2769 #else /* FIXPT */
2770 integer mp_take_fraction (MP mp,integer p, fraction q) {
2771     register double d;
2772         register integer i;
2773         d = (double)p * (double)q * TWEXP_28;
2774         if ((p^q) >= 0) {
2775                 d += 0.5;
2776                 if (d>=TWEXP31) {
2777                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2778                                 mp->arith_error = true;
2779                         return ELGORDO;
2780                 }
2781                 i = (integer) d;
2782                 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2783         } else {
2784                 d -= 0.5;
2785                 if (d<= -TWEXP31) {
2786                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2787                                 mp->arith_error = true;
2788                         return -ELGORDO;
2789                 }
2790                 i = (integer) d;
2791                 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2792         }
2793         return i;
2794 #endif /* FIXPT */
2795 }
2796
2797 @ @<Reduce to the case that |f>=0| and |q>0|@>=
2798 if ( f>=0 ) {
2799   negative=false;
2800 } else { 
2801   negate( f); negative=true;
2802 }
2803 if ( q<0 ) { 
2804   negate(q); negative=! negative;
2805 }
2806
2807 @ The invariant relations in this case are (i)~$\lfloor(qf+p)/2^k\rfloor
2808 =\lfloor qf_0/2^{28}+{1\over2}\rfloor$, where $k$ is an integer and
2809 $f_0$ is the original value of~$f$; (ii)~$2^k\L f<2^{k+1}$.
2810 @^inner loop@>
2811
2812 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>=
2813 p=fraction_half; /* that's $2^{27}$; the invariants hold now with $k=28$ */
2814 if ( q<fraction_four ) {
2815   do {  
2816     if ( odd(f) ) p=halfp(p+q); else p=halfp(p);
2817     f=halfp(f);
2818   } while (f!=1);
2819 } else  {
2820   do {  
2821     if ( odd(f) ) p=p+halfp(q-p); else p=halfp(p);
2822     f=halfp(f);
2823   } while (f!=1);
2824 }
2825
2826
2827 @ When we want to multiply something by a |scaled| quantity, we use a scheme
2828 analogous to |take_fraction| but with a different scaling.
2829 Given positive operands, |take_scaled|
2830 computes the quantity $p=\lfloor qf/2^{16}+{1\over2}\rfloor$.
2831
2832 Once again it is a good idea to use a machine-language replacement if
2833 possible; otherwise |take_scaled| will use more than 2\pct! of the running time
2834 when the Computer Modern fonts are being generated.
2835 @^inner loop@>
2836
2837 @c 
2838 #ifdef FIXPT
2839 integer mp_take_scaled (MP mp,integer q, scaled f) {
2840   integer p; /* the fraction so far */
2841   boolean negative; /* should the result be negated? */
2842   integer n; /* additional multiple of $q$ */
2843   integer be_careful; /* disables certain compiler optimizations */
2844   @<Reduce to the case that |f>=0| and |q>0|@>;
2845   if ( f<unity ) { 
2846     n=0;
2847   } else  { 
2848     n=f / unity; f=f % unity;
2849     if ( q<=el_gordo / n ) {
2850       n=n*q;
2851     } else  { 
2852       mp->arith_error=true; n=el_gordo;
2853     }
2854   }
2855   f=f+unity;
2856   @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>;
2857   be_careful=n-el_gordo;
2858   if ( be_careful+p>0 ) { 
2859     mp->arith_error=true; n=el_gordo-p;
2860   }
2861   return ( negative ?(-(n+p)) :(n+p));
2862 #else /* FIXPT */
2863 integer mp_take_scaled (MP mp,integer p, scaled q) {
2864     register double d;
2865         register integer i;
2866         d = (double)p * (double)q * TWEXP_16;
2867         if ((p^q) >= 0) {
2868                 d += 0.5;
2869                 if (d>=TWEXP31) {
2870                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2871                                 mp->arith_error = true;
2872                         return ELGORDO;
2873                 }
2874                 i = (integer) d;
2875                 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2876         } else {
2877                 d -= 0.5;
2878                 if (d<= -TWEXP31) {
2879                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2880                                 mp->arith_error = true;
2881                         return -ELGORDO;
2882                 }
2883                 i = (integer) d;
2884                 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2885         }
2886         return i;
2887 #endif /* FIXPT */
2888 }
2889
2890 @ @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>=
2891 p=half_unit; /* that's $2^{15}$; the invariants hold now with $k=16$ */
2892 @^inner loop@>
2893 if ( q<fraction_four ) {
2894   do {  
2895     p = (odd(f) ? halfp(p+q) : halfp(p));
2896     f=halfp(f);
2897   } while (f!=1);
2898 } else {
2899   do {  
2900     p = (odd(f) ? p+halfp(q-p) : halfp(p));
2901     f=halfp(f);
2902   } while (f!=1);
2903 }
2904
2905 @ For completeness, there's also |make_scaled|, which computes a
2906 quotient as a |scaled| number instead of as a |fraction|.
2907 In other words, the result is $\lfloor2^{16}p/q+{1\over2}\rfloor$, if the
2908 operands are positive. \ (This procedure is not used especially often,
2909 so it is not part of \MP's inner loop.)
2910
2911 @c 
2912 scaled mp_make_scaled (MP mp,integer p, integer q) {
2913 #ifdef FIXPT 
2914   integer f; /* the fraction bits, with a leading 1 bit */
2915   integer n; /* the integer part of $\vert p/q\vert$ */
2916   boolean negative; /* should the result be negated? */
2917   integer be_careful; /* disables certain compiler optimizations */
2918   if ( p>=0 ) negative=false;
2919   else  { negate(p); negative=true; };
2920   if ( q<=0 ) { 
2921 #ifdef DEBUG 
2922     if ( q==0 ) mp_confusion(mp, "/");
2923 @:this can't happen /}{\quad \./@>
2924 #endif
2925     negate(q); negative=! negative;
2926   }
2927   n=p / q; p=p % q;
2928   if ( n>=0100000 ) { 
2929     mp->arith_error=true;
2930     return (negative ? (-el_gordo) : el_gordo);
2931   } else  { 
2932     n=(n-1)*unity;
2933     @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>;
2934     return ( negative ? (-(f+n)) :(f+n));
2935   }
2936 #else /* FIXPT */
2937     register double d;
2938         register integer i;
2939 #ifdef DEBUG
2940         if (q==0) mp_confusion(mp,"/"); 
2941 #endif /* DEBUG */
2942         d = TWEXP16 * (double)p /(double)q;
2943         if ((p^q) >= 0) {
2944                 d += 0.5;
2945                 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
2946                 i = (integer) d;
2947                 if (d==i && ( ((q>0 ? -q : q)&077777)
2948                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2949         } else {
2950                 d -= 0.5;
2951                 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
2952                 i = (integer) d;
2953                 if (d==i && ( ((q>0 ? q : -q)&077777)
2954                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
2955         }
2956         return i;
2957 #endif /* FIXPT */
2958 }
2959
2960 @ @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>=
2961 f=1;
2962 do {  
2963   be_careful=p-q; p=be_careful+p;
2964   if ( p>=0 ) f=f+f+1;
2965   else  { f+=f; p=p+q; };
2966 } while (f<unity);
2967 be_careful=p-q;
2968 if ( be_careful+p>=0 ) incr(f)
2969
2970 @ Here is a typical example of how the routines above can be used.
2971 It computes the function
2972 $${1\over3\tau}f(\theta,\phi)=
2973 {\tau^{-1}\bigl(2+\sqrt2\,(\sin\theta-{1\over16}\sin\phi)
2974  (\sin\phi-{1\over16}\sin\theta)(\cos\theta-\cos\phi)\bigr)\over
2975 3\,\bigl(1+{1\over2}(\sqrt5-1)\cos\theta+{1\over2}(3-\sqrt5\,)\cos\phi\bigr)},$$
2976 where $\tau$ is a |scaled| ``tension'' parameter. This is \MP's magic
2977 fudge factor for placing the first control point of a curve that starts
2978 at an angle $\theta$ and ends at an angle $\phi$ from the straight path.
2979 (Actually, if the stated quantity exceeds 4, \MP\ reduces it to~4.)
2980
2981 The trigonometric quantity to be multiplied by $\sqrt2$ is less than $\sqrt2$.
2982 (It's a sum of eight terms whose absolute values can be bounded using
2983 relations such as $\sin\theta\cos\theta\L{1\over2}$.) Thus the numerator
2984 is positive; and since the tension $\tau$ is constrained to be at least
2985 $3\over4$, the numerator is less than $16\over3$. The denominator is
2986 nonnegative and at most~6.  Hence the fixed-point calculations below
2987 are guaranteed to stay within the bounds of a 32-bit computer word.
2988
2989 The angles $\theta$ and $\phi$ are given implicitly in terms of |fraction|
2990 arguments |st|, |ct|, |sf|, and |cf|, representing $\sin\theta$, $\cos\theta$,
2991 $\sin\phi$, and $\cos\phi$, respectively.
2992
2993 @c 
2994 fraction mp_velocity (MP mp,fraction st, fraction ct, fraction sf,
2995                       fraction cf, scaled t) {
2996   integer acc,num,denom; /* registers for intermediate calculations */
2997   acc=mp_take_fraction(mp, st-(sf / 16), sf-(st / 16));
2998   acc=mp_take_fraction(mp, acc,ct-cf);
2999   num=fraction_two+mp_take_fraction(mp, acc,379625062);
3000                    /* $2^{28}\sqrt2\approx379625062.497$ */
3001   denom=fraction_three+mp_take_fraction(mp, ct,497706707)+mp_take_fraction(mp, cf,307599661);
3002                       /* $3\cdot2^{27}\cdot(\sqrt5-1)\approx497706706.78$ and
3003                          $3\cdot2^{27}\cdot(3-\sqrt5\,)\approx307599661.22$ */
3004   if ( t!=unity ) num=mp_make_scaled(mp, num,t);
3005   /* |make_scaled(fraction,scaled)=fraction| */
3006   if ( num / 4>=denom ) 
3007     return fraction_four;
3008   else 
3009     return mp_make_fraction(mp, num, denom);
3010 }
3011
3012 @ The following somewhat different subroutine tests rigorously if $ab$ is
3013 greater than, equal to, or less than~$cd$,
3014 given integers $(a,b,c,d)$. In most cases a quick decision is reached.
3015 The result is $+1$, 0, or~$-1$ in the three respective cases.
3016
3017 @d mp_ab_vs_cd(M,A,B,C,D) mp_do_ab_vs_cd(A,B,C,D)
3018
3019 @c 
3020 integer mp_do_ab_vs_cd (integer a,integer b, integer c, integer d) {
3021   integer q,r; /* temporary registers */
3022   @<Reduce to the case that |a,c>=0|, |b,d>0|@>;
3023   while (1) { 
3024     q = a / d; r = c / b;
3025     if ( q!=r )
3026       return ( q>r ? 1 : -1);
3027     q = a % d; r = c % b;
3028     if ( r==0 )
3029       return (q ? 1 : 0);
3030     if ( q==0 ) return -1;
3031     a=b; b=q; c=d; d=r;
3032   } /* now |a>d>0| and |c>b>0| */
3033 }
3034
3035 @ @<Reduce to the case that |a...@>=
3036 if ( a<0 ) { negate(a); negate(b);  };
3037 if ( c<0 ) { negate(c); negate(d);  };
3038 if ( d<=0 ) { 
3039   if ( b>=0 ) {
3040     if ( (a==0||b==0)&&(c==0||d==0) ) return 0;
3041     else return 1;
3042   }
3043   if ( d==0 )
3044     return ( a==0 ? 0 : -1);
3045   q=a; a=c; c=q; q=-b; b=-d; d=q;
3046 } else if ( b<=0 ) { 
3047   if ( b<0 ) if ( a>0 ) return -1;
3048   return (c==0 ? 0 : -1);
3049 }
3050
3051 @ We conclude this set of elementary routines with some simple rounding
3052 and truncation operations that are coded in a machine-independent fashion.
3053 The routines are slightly complicated because we want them to work
3054 without overflow whenever $-2^{31}\L x<2^{31}$.
3055
3056 @<Declarations@>=
3057 #define mp_floor_scaled(M,i) ((i)&(-65536))
3058 #define mp_round_unscaled(M,i) (((i>>15)+1)>>1)
3059 #define mp_round_fraction(M,i) (((i>>11)+1)>>1)
3060
3061
3062 @* \[8] Algebraic and transcendental functions.
3063 \MP\ computes all of the necessary special functions from scratch, without
3064 relying on |real| arithmetic or system subroutines for sines, cosines, etc.
3065
3066 @ To get the square root of a |scaled| number |x|, we want to calculate
3067 $s=\lfloor 2^8\!\sqrt x +{1\over2}\rfloor$. If $x>0$, this is the unique
3068 integer such that $2^{16}x-s\L s^2<2^{16}x+s$. The following subroutine
3069 determines $s$ by an iterative method that maintains the invariant
3070 relations $x=2^{46-2k}x_0\bmod 2^{30}$, $0<y=\lfloor 2^{16-2k}x_0\rfloor
3071 -s^2+s\L q=2s$, where $x_0$ is the initial value of $x$. The value of~$y$
3072 might, however, be zero at the start of the first iteration.
3073
3074 @<Declarations@>=
3075 scaled mp_square_rt (MP mp,scaled x) ;
3076
3077 @ @c 
3078 scaled mp_square_rt (MP mp,scaled x) {
3079   small_number k; /* iteration control counter */
3080   integer y,q; /* registers for intermediate calculations */
3081   if ( x<=0 ) { 
3082     @<Handle square root of zero or negative argument@>;
3083   } else { 
3084     k=23; q=2;
3085     while ( x<fraction_two ) { /* i.e., |while x<@t$2^{29}$@>|\unskip */
3086       decr(k); x=x+x+x+x;
3087     }
3088     if ( x<fraction_four ) y=0;
3089     else  { x=x-fraction_four; y=1; };
3090     do {  
3091       @<Decrease |k| by 1, maintaining the invariant
3092       relations between |x|, |y|, and~|q|@>;
3093     } while (k!=0);
3094     return (halfp(q));
3095   }
3096 }
3097
3098 @ @<Handle square root of zero...@>=
3099
3100   if ( x<0 ) { 
3101     print_err("Square root of ");
3102 @.Square root...replaced by 0@>
3103     mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3104     help2("Since I don't take square roots of negative numbers,")
3105          ("I'm zeroing this one. Proceed, with fingers crossed.");
3106     mp_error(mp);
3107   };
3108   return 0;
3109 }
3110
3111 @ @<Decrease |k| by 1, maintaining...@>=
3112 x+=x; y+=y;
3113 if ( x>=fraction_four ) { /* note that |fraction_four=@t$2^{30}$@>| */
3114   x=x-fraction_four; incr(y);
3115 };
3116 x+=x; y=y+y-q; q+=q;
3117 if ( x>=fraction_four ) { x=x-fraction_four; incr(y); };
3118 if ( y>q ){ y=y-q; q=q+2; }
3119 else if ( y<=0 )  { q=q-2; y=y+q;  };
3120 decr(k)
3121
3122 @ Pythagorean addition $\psqrt{a^2+b^2}$ is implemented by an elegant
3123 iterative scheme due to Cleve Moler and Donald Morrison [{\sl IBM Journal
3124 @^Moler, Cleve Barry@>
3125 @^Morrison, Donald Ross@>
3126 of Research and Development\/ \bf27} (1983), 577--581]. It modifies |a| and~|b|
3127 in such a way that their Pythagorean sum remains invariant, while the
3128 smaller argument decreases.
3129
3130 @c 
3131 integer mp_pyth_add (MP mp,integer a, integer b) {
3132   fraction r; /* register used to transform |a| and |b| */
3133   boolean big; /* is the result dangerously near $2^{31}$? */
3134   a=abs(a); b=abs(b);
3135   if ( a<b ) { r=b; b=a; a=r; }; /* now |0<=b<=a| */
3136   if ( b>0 ) {
3137     if ( a<fraction_two ) {
3138       big=false;
3139     } else { 
3140       a=a / 4; b=b / 4; big=true;
3141     }; /* we reduced the precision to avoid arithmetic overflow */
3142     @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>;
3143     if ( big ) {
3144       if ( a<fraction_two ) {
3145         a=a+a+a+a;
3146       } else  { 
3147         mp->arith_error=true; a=el_gordo;
3148       };
3149     }
3150   }
3151   return a;
3152 }
3153
3154 @ The key idea here is to reflect the vector $(a,b)$ about the
3155 line through $(a,b/2)$.
3156
3157 @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>=
3158 while (1) {  
3159   r=mp_make_fraction(mp, b,a);
3160   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3161   if ( r==0 ) break;
3162   r=mp_make_fraction(mp, r,fraction_four+r);
3163   a=a+mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3164 }
3165
3166
3167 @ Here is a similar algorithm for $\psqrt{a^2-b^2}$.
3168 It converges slowly when $b$ is near $a$, but otherwise it works fine.
3169
3170 @c 
3171 integer mp_pyth_sub (MP mp,integer a, integer b) {
3172   fraction r; /* register used to transform |a| and |b| */
3173   boolean big; /* is the input dangerously near $2^{31}$? */
3174   a=abs(a); b=abs(b);
3175   if ( a<=b ) {
3176     @<Handle erroneous |pyth_sub| and set |a:=0|@>;
3177   } else { 
3178     if ( a<fraction_four ) {
3179       big=false;
3180     } else  { 
3181       a=halfp(a); b=halfp(b); big=true;
3182     }
3183     @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>;
3184     if ( big ) a=a+a;
3185   }
3186   return a;
3187 }
3188
3189 @ @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>=
3190 while (1) { 
3191   r=mp_make_fraction(mp, b,a);
3192   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3193   if ( r==0 ) break;
3194   r=mp_make_fraction(mp, r,fraction_four-r);
3195   a=a-mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3196 }
3197
3198 @ @<Handle erroneous |pyth_sub| and set |a:=0|@>=
3199
3200   if ( a<b ){ 
3201     print_err("Pythagorean subtraction "); mp_print_scaled(mp, a);
3202     mp_print(mp, "+-+"); mp_print_scaled(mp, b); 
3203     mp_print(mp, " has been replaced by 0");
3204 @.Pythagorean...@>
3205     help2("Since I don't take square roots of negative numbers,")
3206          ("I'm zeroing this one. Proceed, with fingers crossed.");
3207     mp_error(mp);
3208   }
3209   a=0;
3210 }
3211
3212 @ The subroutines for logarithm and exponential involve two tables.
3213 The first is simple: |two_to_the[k]| equals $2^k$. The second involves
3214 a bit more calculation, which the author claims to have done correctly:
3215 |spec_log[k]| is $2^{27}$ times $\ln\bigl(1/(1-2^{-k})\bigr)=
3216 2^{-k}+{1\over2}2^{-2k}+{1\over3}2^{-3k}+\cdots\,$, rounded to the
3217 nearest integer.
3218
3219 @d two_to_the(A) (1<<(A))
3220
3221 @<Constants ...@>=
3222 static const integer spec_log[29] = { 0, /* special logarithms */
3223 93032640, 38612034, 17922280, 8662214, 4261238, 2113709,
3224 1052693, 525315, 262400, 131136, 65552, 32772, 16385,
3225 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 1 };
3226
3227 @ @<Local variables for initialization@>=
3228 integer k; /* all-purpose loop index */
3229
3230
3231 @ Here is the routine that calculates $2^8$ times the natural logarithm
3232 of a |scaled| quantity; it is an integer approximation to $2^{24}\ln(x/2^{16})$,
3233 when |x| is a given positive integer.
3234
3235 The method is based on exercise 1.2.2--25 in {\sl The Art of Computer
3236 Programming\/}: During the main iteration we have $1\L 2^{-30}x<1/(1-2^{1-k})$,
3237 and the logarithm of $2^{30}x$ remains to be added to an accumulator
3238 register called~$y$. Three auxiliary bits of accuracy are retained in~$y$
3239 during the calculation, and sixteen auxiliary bits to extend |y| are
3240 kept in~|z| during the initial argument reduction. (We add
3241 $100\cdot2^{16}=6553600$ to~|z| and subtract 100 from~|y| so that |z| will
3242 not become negative; also, the actual amount subtracted from~|y| is~96,
3243 not~100, because we want to add~4 for rounding before the final division by~8.)
3244
3245 @c 
3246 scaled mp_m_log (MP mp,scaled x) {
3247   integer y,z; /* auxiliary registers */
3248   integer k; /* iteration counter */
3249   if ( x<=0 ) {
3250      @<Handle non-positive logarithm@>;
3251   } else  { 
3252     y=1302456956+4-100; /* $14\times2^{27}\ln2\approx1302456956.421063$ */
3253     z=27595+6553600; /* and $2^{16}\times .421063\approx 27595$ */
3254     while ( x<fraction_four ) {
3255        x+=x; y=y-93032639; z=z-48782;
3256     } /* $2^{27}\ln2\approx 93032639.74436163$ and $2^{16}\times.74436163\approx 48782$ */
3257     y=y+(z / unity); k=2;
3258     while ( x>fraction_four+4 ) {
3259       @<Increase |k| until |x| can be multiplied by a
3260         factor of $2^{-k}$, and adjust $y$ accordingly@>;
3261     }
3262     return (y / 8);
3263   }
3264 }
3265
3266 @ @<Increase |k| until |x| can...@>=
3267
3268   z=((x-1) / two_to_the(k))+1; /* $z=\lceil x/2^k\rceil$ */
3269   while ( x<fraction_four+z ) { z=halfp(z+1); k=k+1; };
3270   y=y+spec_log[k]; x=x-z;
3271 }
3272
3273 @ @<Handle non-positive logarithm@>=
3274
3275   print_err("Logarithm of ");
3276 @.Logarithm...replaced by 0@>
3277   mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3278   help2("Since I don't take logs of non-positive numbers,")
3279        ("I'm zeroing this one. Proceed, with fingers crossed.");
3280   mp_error(mp); 
3281   return 0;
3282 }
3283
3284 @ Conversely, the exponential routine calculates $\exp(x/2^8)$,
3285 when |x| is |scaled|. The result is an integer approximation to
3286 $2^{16}\exp(x/2^{24})$, when |x| is regarded as an integer.
3287
3288 @c 
3289 scaled mp_m_exp (MP mp,scaled x) {
3290   small_number k; /* loop control index */
3291   integer y,z; /* auxiliary registers */
3292   if ( x>174436200 ) {
3293     /* $2^{24}\ln((2^{31}-1)/2^{16})\approx 174436199.51$ */
3294     mp->arith_error=true; 
3295     return el_gordo;
3296   } else if ( x<-197694359 ) {
3297         /* $2^{24}\ln(2^{-1}/2^{16})\approx-197694359.45$ */
3298     return 0;
3299   } else { 
3300     if ( x<=0 ) { 
3301        z=-8*x; y=04000000; /* $y=2^{20}$ */
3302     } else { 
3303       if ( x<=127919879 ) { 
3304         z=1023359037-8*x;
3305         /* $2^{27}\ln((2^{31}-1)/2^{20})\approx 1023359037.125$ */
3306       } else {
3307        z=8*(174436200-x); /* |z| is always nonnegative */
3308       }
3309       y=el_gordo;
3310     };
3311     @<Multiply |y| by $\exp(-z/2^{27})$@>;
3312     if ( x<=127919879 ) 
3313        return ((y+8) / 16);
3314      else 
3315        return y;
3316   }
3317 }
3318
3319 @ The idea here is that subtracting |spec_log[k]| from |z| corresponds
3320 to multiplying |y| by $1-2^{-k}$.
3321
3322 A subtle point (which had to be checked) was that if $x=127919879$, the
3323 value of~|y| will decrease so that |y+8| doesn't overflow. In fact,
3324 $z$ will be 5 in this case, and |y| will decrease by~64 when |k=25|
3325 and by~16 when |k=27|.
3326
3327 @<Multiply |y| by...@>=
3328 k=1;
3329 while ( z>0 ) { 
3330   while ( z>=spec_log[k] ) { 
3331     z-=spec_log[k];
3332     y=y-1-((y-two_to_the(k-1)) / two_to_the(k));
3333   }
3334   incr(k);
3335 }
3336
3337 @ The trigonometric subroutines use an auxiliary table such that
3338 |spec_atan[k]| contains an approximation to the |angle| whose tangent
3339 is~$1/2^k$. $\arctan2^{-k}$ times $2^{20}\cdot180/\pi$ 
3340
3341 @<Constants ...@>=
3342 static const angle spec_atan[27] = { 0, 27855475, 14718068, 7471121, 3750058, 
3343 1876857, 938658, 469357, 234682, 117342, 58671, 29335, 14668, 7334, 3667, 
3344 1833, 917, 458, 229, 115, 57, 29, 14, 7, 4, 2, 1 };
3345
3346 @ Given integers |x| and |y|, not both zero, the |n_arg| function
3347 returns the |angle| whose tangent points in the direction $(x,y)$.
3348 This subroutine first determines the correct octant, then solves the
3349 problem for |0<=y<=x|, then converts the result appropriately to
3350 return an answer in the range |-one_eighty_deg<=@t$\theta$@><=one_eighty_deg|.
3351 (The answer is |+one_eighty_deg| if |y=0| and |x<0|, but an answer of
3352 |-one_eighty_deg| is possible if, for example, |y=-1| and $x=-2^{30}$.)
3353
3354 The octants are represented in a ``Gray code,'' since that turns out
3355 to be computationally simplest.
3356
3357 @d negate_x 1
3358 @d negate_y 2
3359 @d switch_x_and_y 4
3360 @d first_octant 1
3361 @d second_octant (first_octant+switch_x_and_y)
3362 @d third_octant (first_octant+switch_x_and_y+negate_x)
3363 @d fourth_octant (first_octant+negate_x)
3364 @d fifth_octant (first_octant+negate_x+negate_y)
3365 @d sixth_octant (first_octant+switch_x_and_y+negate_x+negate_y)
3366 @d seventh_octant (first_octant+switch_x_and_y+negate_y)
3367 @d eighth_octant (first_octant+negate_y)
3368
3369 @c 
3370 angle mp_n_arg (MP mp,integer x, integer y) {
3371   angle z; /* auxiliary register */
3372   integer t; /* temporary storage */
3373   small_number k; /* loop counter */
3374   int octant; /* octant code */
3375   if ( x>=0 ) {
3376     octant=first_octant;
3377   } else { 
3378     negate(x); octant=first_octant+negate_x;
3379   }
3380   if ( y<0 ) { 
3381     negate(y); octant=octant+negate_y;
3382   }
3383   if ( x<y ) { 
3384     t=y; y=x; x=t; octant=octant+switch_x_and_y;
3385   }
3386   if ( x==0 ) { 
3387     @<Handle undefined arg@>; 
3388   } else { 
3389     @<Set variable |z| to the arg of $(x,y)$@>;
3390     @<Return an appropriate answer based on |z| and |octant|@>;
3391   }
3392 }
3393
3394 @ @<Handle undefined arg@>=
3395
3396   print_err("angle(0,0) is taken as zero");
3397 @.angle(0,0)...zero@>
3398   help2("The `angle' between two identical points is undefined.")
3399        ("I'm zeroing this one. Proceed, with fingers crossed.");
3400   mp_error(mp); 
3401   return 0;
3402 }
3403
3404 @ @<Return an appropriate answer...@>=
3405 switch (octant) {
3406 case first_octant: return z;
3407 case second_octant: return (ninety_deg-z);
3408 case third_octant: return (ninety_deg+z);
3409 case fourth_octant: return (one_eighty_deg-z);
3410 case fifth_octant: return (z-one_eighty_deg);
3411 case sixth_octant: return (-z-ninety_deg);
3412 case seventh_octant: return (z-ninety_deg);
3413 case eighth_octant: return (-z);
3414 }; /* there are no other cases */
3415 return 0
3416
3417 @ At this point we have |x>=y>=0|, and |x>0|. The numbers are scaled up
3418 or down until $2^{28}\L x<2^{29}$, so that accurate fixed-point calculations
3419 will be made.
3420
3421 @<Set variable |z| to the arg...@>=
3422 while ( x>=fraction_two ) { 
3423   x=halfp(x); y=halfp(y);
3424 }
3425 z=0;
3426 if ( y>0 ) { 
3427  while ( x<fraction_one ) { 
3428     x+=x; y+=y; 
3429  };
3430  @<Increase |z| to the arg of $(x,y)$@>;
3431 }
3432
3433 @ During the calculations of this section, variables |x| and~|y|
3434 represent actual coordinates $(x,2^{-k}y)$. We will maintain the
3435 condition |x>=y|, so that the tangent will be at most $2^{-k}$.
3436 If $x<2y$, the tangent is greater than $2^{-k-1}$. The transformation
3437 $(a,b)\mapsto(a+b\tan\phi,b-a\tan\phi)$ replaces $(a,b)$ by
3438 coordinates whose angle has decreased by~$\phi$; in the special case
3439 $a=x$, $b=2^{-k}y$, and $\tan\phi=2^{-k-1}$, this operation reduces
3440 to the particularly simple iteration shown here. [Cf.~John E. Meggitt,
3441 @^Meggitt, John E.@>
3442 {\sl IBM Journal of Research and Development\/ \bf6} (1962), 210--226.]
3443
3444 The initial value of |x| will be multiplied by at most
3445 $(1+{1\over2})(1+{1\over8})(1+{1\over32})\cdots\approx 1.7584$; hence
3446 there is no chance of integer overflow.
3447
3448 @<Increase |z|...@>=
3449 k=0;
3450 do {  
3451   y+=y; incr(k);
3452   if ( y>x ){ 
3453     z=z+spec_atan[k]; t=x; x=x+(y / two_to_the(k+k)); y=y-t;
3454   };
3455 } while (k!=15);
3456 do {  
3457   y+=y; incr(k);
3458   if ( y>x ) { z=z+spec_atan[k]; y=y-x; };
3459 } while (k!=26)
3460
3461 @ Conversely, the |n_sin_cos| routine takes an |angle| and produces the sine
3462 and cosine of that angle. The results of this routine are
3463 stored in global integer variables |n_sin| and |n_cos|.
3464
3465 @<Glob...@>=
3466 fraction n_sin;fraction n_cos; /* results computed by |n_sin_cos| */
3467
3468 @ Given an integer |z| that is $2^{20}$ times an angle $\theta$ in degrees,
3469 the purpose of |n_sin_cos(z)| is to set
3470 |x=@t$r\cos\theta$@>| and |y=@t$r\sin\theta$@>| (approximately),
3471 for some rather large number~|r|. The maximum of |x| and |y|
3472 will be between $2^{28}$ and $2^{30}$, so that there will be hardly
3473 any loss of accuracy. Then |x| and~|y| are divided by~|r|.
3474
3475 @c 
3476 void mp_n_sin_cos (MP mp,angle z) { /* computes a multiple of the sine
3477                                        and cosine */ 
3478   small_number k; /* loop control variable */
3479   int q; /* specifies the quadrant */
3480   fraction r; /* magnitude of |(x,y)| */
3481   integer x,y,t; /* temporary registers */
3482   while ( z<0 ) z=z+three_sixty_deg;
3483   z=z % three_sixty_deg; /* now |0<=z<three_sixty_deg| */
3484   q=z / forty_five_deg; z=z % forty_five_deg;
3485   x=fraction_one; y=x;
3486   if ( ! odd(q) ) z=forty_five_deg-z;
3487   @<Subtract angle |z| from |(x,y)|@>;
3488   @<Convert |(x,y)| to the octant determined by~|q|@>;
3489   r=mp_pyth_add(mp, x,y); 
3490   mp->n_cos=mp_make_fraction(mp, x,r); 
3491   mp->n_sin=mp_make_fraction(mp, y,r);
3492 }
3493
3494 @ In this case the octants are numbered sequentially.
3495
3496 @<Convert |(x,...@>=
3497 switch (q) {
3498 case 0: break;
3499 case 1: t=x; x=y; y=t; break;
3500 case 2: t=x; x=-y; y=t; break;
3501 case 3: negate(x); break;
3502 case 4: negate(x); negate(y); break;
3503 case 5: t=x; x=-y; y=-t; break;
3504 case 6: t=x; x=y; y=-t; break;
3505 case 7: negate(y); break;
3506 } /* there are no other cases */
3507
3508 @ The main iteration of |n_sin_cos| is similar to that of |n_arg| but
3509 applied in reverse. The values of |spec_atan[k]| decrease slowly enough
3510 that this loop is guaranteed to terminate before the (nonexistent) value
3511 |spec_atan[27]| would be required.
3512
3513 @<Subtract angle |z|...@>=
3514 k=1;
3515 while ( z>0 ){ 
3516   if ( z>=spec_atan[k] ) { 
3517     z=z-spec_atan[k]; t=x;
3518     x=t+y / two_to_the(k);
3519     y=y-t / two_to_the(k);
3520   }
3521   incr(k);
3522 }
3523 if ( y<0 ) y=0 /* this precaution may never be needed */
3524
3525 @ And now let's complete our collection of numeric utility routines
3526 by considering random number generation.
3527 \MP\ generates pseudo-random numbers with the additive scheme recommended
3528 in Section 3.6 of {\sl The Art of Computer Programming}; however, the
3529 results are random fractions between 0 and |fraction_one-1|, inclusive.
3530
3531 There's an auxiliary array |randoms| that contains 55 pseudo-random
3532 fractions. Using the recurrence $x_n=(x_{n-55}-x_{n-31})\bmod 2^{28}$,
3533 we generate batches of 55 new $x_n$'s at a time by calling |new_randoms|.
3534 The global variable |j_random| tells which element has most recently
3535 been consumed.
3536 The global variable |sys_random_seed| was introduced in version 0.9,
3537 for the sole reason of stressing the fact that the initial value of the
3538 random seed is system-dependant. The pascal code below will initialize
3539 this variable to |(internal[time] div unity)+internal[day]|, but this is
3540 not good enough on modern fast machines that are capable of running
3541 multiple MetaPost processes within the same second.
3542 @^system dependencies@>
3543
3544 @<Glob...@>=
3545 fraction randoms[55]; /* the last 55 random values generated */
3546 int j_random; /* the number of unused |randoms| */
3547 scaled sys_random_seed; /* the default random seed */
3548
3549 @ @<Types...@>=
3550 typedef scaled (*get_random_seed_command)(MP mp);
3551
3552 @ @<Glob...@>=
3553 get_random_seed_command get_random_seed;
3554
3555 @ @<Option variables@>=
3556 get_random_seed_command get_random_seed;
3557
3558 @ @<Allocate or initialize ...@>=
3559 set_callback_option(get_random_seed);
3560
3561 @ @<Exported function headers@>=
3562 scaled mp_get_random_seed (MP mp);
3563
3564 @ @c 
3565 scaled mp_get_random_seed (MP mp) {
3566   return (mp->internal[mp_time] / unity)+mp->internal[day];
3567 }
3568
3569 @ To consume a random fraction, the program below will say `|next_random|'
3570 and then it will fetch |randoms[j_random]|.
3571
3572 @d next_random { if ( mp->j_random==0 ) mp_new_randoms(mp);
3573   else decr(mp->j_random); }
3574
3575 @c 
3576 void mp_new_randoms (MP mp) {
3577   int k; /* index into |randoms| */
3578   fraction x; /* accumulator */
3579   for (k=0;k<=23;k++) { 
3580    x=mp->randoms[k]-mp->randoms[k+31];
3581     if ( x<0 ) x=x+fraction_one;
3582     mp->randoms[k]=x;
3583   }
3584   for (k=24;k<= 54;k++){ 
3585     x=mp->randoms[k]-mp->randoms[k-24];
3586     if ( x<0 ) x=x+fraction_one;
3587     mp->randoms[k]=x;
3588   }
3589   mp->j_random=54;
3590 }
3591
3592 @ @<Declarations@>=
3593 void mp_init_randoms (MP mp,scaled seed);
3594
3595 @ To initialize the |randoms| table, we call the following routine.
3596
3597 @c 
3598 void mp_init_randoms (MP mp,scaled seed) {
3599   fraction j,jj,k; /* more or less random integers */
3600   int i; /* index into |randoms| */
3601   j=abs(seed);
3602   while ( j>=fraction_one ) j=halfp(j);
3603   k=1;
3604   for (i=0;i<=54;i++ ){ 
3605     jj=k; k=j-k; j=jj;
3606     if ( k<0 ) k=k+fraction_one;
3607     mp->randoms[(i*21)% 55]=j;
3608   }
3609   mp_new_randoms(mp); 
3610   mp_new_randoms(mp); 
3611   mp_new_randoms(mp); /* ``warm up'' the array */
3612 }
3613
3614 @ To produce a uniform random number in the range |0<=u<x| or |0>=u>x|
3615 or |0=u=x|, given a |scaled| value~|x|, we proceed as shown here.
3616
3617 Note that the call of |take_fraction| will produce the values 0 and~|x|
3618 with about half the probability that it will produce any other particular
3619 values between 0 and~|x|, because it rounds its answers.
3620
3621 @c 
3622 scaled mp_unif_rand (MP mp,scaled x) {
3623   scaled y; /* trial value */
3624   next_random; y=mp_take_fraction(mp, abs(x),mp->randoms[mp->j_random]);
3625   if ( y==abs(x) ) return 0;
3626   else if ( x>0 ) return y;
3627   else return (-y);
3628 }
3629
3630 @ Finally, a normal deviate with mean zero and unit standard deviation
3631 can readily be obtained with the ratio method (Algorithm 3.4.1R in
3632 {\sl The Art of Computer Programming\/}).
3633
3634 @c 
3635 scaled mp_norm_rand (MP mp) {
3636   integer x,u,l; /* what the book would call $2^{16}X$, $2^{28}U$, and $-2^{24}\ln U$ */
3637   do { 
3638     do {  
3639       next_random;
3640       x=mp_take_fraction(mp, 112429,mp->randoms[mp->j_random]-fraction_half);
3641       /* $2^{16}\sqrt{8/e}\approx 112428.82793$ */
3642       next_random; u=mp->randoms[mp->j_random];
3643     } while (abs(x)>=u);
3644     x=mp_make_fraction(mp, x,u);
3645     l=139548960-mp_m_log(mp, u); /* $2^{24}\cdot12\ln2\approx139548959.6165$ */
3646   } while (mp_ab_vs_cd(mp, 1024,l,x,x)<0);
3647   return x;
3648 }
3649
3650 @* \[9] Packed data.
3651 In order to make efficient use of storage space, \MP\ bases its major data
3652 structures on a |memory_word|, which contains either a (signed) integer,
3653 possibly scaled, or a small number of fields that are one half or one
3654 quarter of the size used for storing integers.
3655
3656 If |x| is a variable of type |memory_word|, it contains up to four
3657 fields that can be referred to as follows:
3658 $$\vbox{\halign{\hfil#&#\hfil&#\hfil\cr
3659 |x|&.|int|&(an |integer|)\cr
3660 |x|&.|sc|\qquad&(a |scaled| integer)\cr
3661 |x.hh.lh|, |x.hh|&.|rh|&(two halfword fields)\cr
3662 |x.hh.b0|, |x.hh.b1|, |x.hh|&.|rh|&(two quarterword fields, one halfword
3663   field)\cr
3664 |x.qqqq.b0|, |x.qqqq.b1|, |x.qqqq|&.|b2|, |x.qqqq.b3|\hskip-100pt
3665   &\qquad\qquad\qquad(four quarterword fields)\cr}}$$
3666 This is somewhat cumbersome to write, and not very readable either, but
3667 macros will be used to make the notation shorter and more transparent.
3668 The code below gives a formal definition of |memory_word| and
3669 its subsidiary types, using packed variant records. \MP\ makes no
3670 assumptions about the relative positions of the fields within a word.
3671
3672 @d max_quarterword 0x3FFF /* largest allowable value in a |quarterword| */
3673 @d max_halfword 0xFFFFFFF /* largest allowable value in a |halfword| */
3674
3675 @ Here are the inequalities that the quarterword and halfword values
3676 must satisfy (or rather, the inequalities that they mustn't satisfy):
3677
3678 @<Check the ``constant''...@>=
3679 if (mp->ini_version) {
3680   if ( mp->mem_max!=mp->mem_top ) mp->bad=8;
3681 } else {
3682   if ( mp->mem_max<mp->mem_top ) mp->bad=8;
3683 }
3684 if ( max_quarterword<255 ) mp->bad=9;
3685 if ( max_halfword<65535 ) mp->bad=10;
3686 if ( max_quarterword>max_halfword ) mp->bad=11;
3687 if ( mp->mem_max>=max_halfword ) mp->bad=12;
3688 if ( mp->max_strings>max_halfword ) mp->bad=13;
3689
3690 @ The macros |qi| and |qo| are used for input to and output 
3691 from quarterwords. These are legacy macros.
3692 @^system dependencies@>
3693
3694 @d qo(A) (A) /* to read eight bits from a quarterword */
3695 @d qi(A) (A) /* to store eight bits in a quarterword */
3696
3697 @ The reader should study the following definitions closely:
3698 @^system dependencies@>
3699
3700 @d sc cint /* |scaled| data is equivalent to |integer| */
3701
3702 @<Types...@>=
3703 typedef short quarterword; /* 1/4 of a word */
3704 typedef int halfword; /* 1/2 of a word */
3705 typedef union {
3706   struct {
3707     halfword RH, LH;
3708   } v;
3709   struct { /* Make B0,B1 overlap the most significant bytes of LH.  */
3710     halfword junk;
3711     quarterword B0, B1;
3712   } u;
3713 } two_halves;
3714 typedef struct {
3715   struct {
3716     quarterword B2, B3, B0, B1;
3717   } u;
3718 } four_quarters;
3719 typedef union {
3720   two_halves hh;
3721   integer cint;
3722   four_quarters qqqq;
3723 } memory_word;
3724 #define b0 u.B0
3725 #define b1 u.B1
3726 #define b2 u.B2
3727 #define b3 u.B3
3728 #define rh v.RH
3729 #define lh v.LH
3730
3731 @ When debugging, we may want to print a |memory_word| without knowing
3732 what type it is; so we print it in all modes.
3733 @^dirty \PASCAL@>@^debugging@>
3734
3735 @c 
3736 void mp_print_word (MP mp,memory_word w) {
3737   /* prints |w| in all ways */
3738   mp_print_int(mp, w.cint); mp_print_char(mp, ' ');
3739   mp_print_scaled(mp, w.sc); mp_print_char(mp, ' '); 
3740   mp_print_scaled(mp, w.sc / 010000); mp_print_ln(mp);
3741   mp_print_int(mp, w.hh.lh); mp_print_char(mp, '='); 
3742   mp_print_int(mp, w.hh.b0); mp_print_char(mp, ':');
3743   mp_print_int(mp, w.hh.b1); mp_print_char(mp, ';'); 
3744   mp_print_int(mp, w.hh.rh); mp_print_char(mp, ' ');
3745   mp_print_int(mp, w.qqqq.b0); mp_print_char(mp, ':'); 
3746   mp_print_int(mp, w.qqqq.b1); mp_print_char(mp, ':');
3747   mp_print_int(mp, w.qqqq.b2); mp_print_char(mp, ':'); 
3748   mp_print_int(mp, w.qqqq.b3);
3749 }
3750
3751
3752 @* \[10] Dynamic memory allocation.
3753
3754 The \MP\ system does nearly all of its own memory allocation, so that it
3755 can readily be transported into environments that do not have automatic
3756 facilities for strings, garbage collection, etc., and so that it can be in
3757 control of what error messages the user receives. The dynamic storage
3758 requirements of \MP\ are handled by providing a large array |mem| in
3759 which consecutive blocks of words are used as nodes by the \MP\ routines.
3760
3761 Pointer variables are indices into this array, or into another array
3762 called |eqtb| that will be explained later. A pointer variable might
3763 also be a special flag that lies outside the bounds of |mem|, so we
3764 allow pointers to assume any |halfword| value. The minimum memory
3765 index represents a null pointer.
3766
3767 @d null 0 /* the null pointer */
3768
3769 @<Types...@>=
3770 typedef halfword pointer; /* a flag or a location in |mem| or |eqtb| */
3771
3772 @ The |mem| array is divided into two regions that are allocated separately,
3773 but the dividing line between these two regions is not fixed; they grow
3774 together until finding their ``natural'' size in a particular job.
3775 Locations less than or equal to |lo_mem_max| are used for storing
3776 variable-length records consisting of two or more words each. This region
3777 is maintained using an algorithm similar to the one described in exercise
3778 2.5--19 of {\sl The Art of Computer Programming}. However, no size field
3779 appears in the allocated nodes; the program is responsible for knowing the
3780 relevant size when a node is freed. Locations greater than or equal to
3781 |hi_mem_min| are used for storing one-word records; a conventional
3782 \.{AVAIL} stack is used for allocation in this region.
3783
3784 Locations of |mem| between |0| and |mem_top| may be dumped as part
3785 of preloaded format files, by the \.{INIMP} preprocessor.
3786 @.INIMP@>
3787 Production versions of \MP\ may extend the memory at the top end in order to
3788 provide more space; these locations, between |mem_top| and |mem_max|,
3789 are always used for single-word nodes.
3790
3791 The key pointers that govern |mem| allocation have a prescribed order:
3792 $$\hbox{|null=0<lo_mem_max<hi_mem_min<mem_top<=mem_end<=mem_max|.}$$
3793
3794 @<Glob...@>=
3795 memory_word *mem; /* the big dynamic storage area */
3796 pointer lo_mem_max; /* the largest location of variable-size memory in use */
3797 pointer hi_mem_min; /* the smallest location of one-word memory in use */
3798
3799
3800
3801 @d xfree    mp_xfree
3802 @d xrealloc mp_xrealloc
3803 @d xmalloc  mp_xmalloc
3804 @d xstrdup  mp_xstrdup
3805 @d XREALLOC(a,b,c) a = xrealloc(a,b,sizeof(c));
3806
3807 @<Declare helpers@>=
3808 void mp_xfree (void *x);
3809 void *mp_xrealloc (void *p, size_t nmem, size_t size) ;
3810 void *mp_xmalloc (size_t nmem, size_t size) ;
3811 char *mp_xstrdup(const char *s);
3812
3813 @ The |max_size_test| guards against overflow, on the assumption that
3814 |size_t| is at least 31bits wide.
3815
3816 @d max_size_test 0x7FFFFFFF
3817
3818 @c
3819 void mp_xfree (void *x) {
3820   if (x!=NULL) free(x);
3821 }
3822 void  *mp_xrealloc (void *p, size_t nmem, size_t size) {
3823   void *w ; 
3824   if ((max_size_test/size)<nmem) {
3825     fprintf(stderr,"Memory size overflow!\n");
3826     exit(1);
3827   }
3828   w = realloc (p,(nmem*size));
3829   if (w==NULL) {
3830     fprintf(stderr,"Out of memory!\n");
3831     exit(1);
3832   }
3833   return w;
3834 }
3835 void  *mp_xmalloc (size_t nmem, size_t size) {
3836   void *w;
3837   if ((max_size_test/size)<nmem) {
3838     fprintf(stderr,"Memory size overflow!\n");
3839     exit(1);
3840   }
3841   w = malloc (nmem*size);
3842   if (w==NULL) {
3843     fprintf(stderr,"Out of memory!\n");
3844     exit(1);
3845   }
3846   return w;
3847 }
3848 char *mp_xstrdup(const char *s) {
3849   char *w; 
3850   if (s==NULL)
3851     return NULL;
3852   w = strdup(s);
3853   if (w==NULL) {
3854     fprintf(stderr,"Out of memory!\n");
3855     exit(1);
3856   }
3857   return w;
3858 }
3859
3860
3861
3862 @<Allocate or initialize ...@>=
3863 mp->mem = xmalloc ((mp->mem_max+1),sizeof (memory_word));
3864
3865 @ @<Dealloc variables@>=
3866 xfree(mp->mem);
3867
3868 @ Users who wish to study the memory requirements of particular applications can
3869 can use optional special features that keep track of current and
3870 maximum memory usage. When code between the delimiters |stat| $\ldots$
3871 |tats| is not ``commented out,'' \MP\ will run a bit slower but it will
3872 report these statistics when |tracing_stats| is positive.
3873
3874 @<Glob...@>=
3875 integer var_used; integer dyn_used; /* how much memory is in use */
3876
3877 @ Let's consider the one-word memory region first, since it's the
3878 simplest. The pointer variable |mem_end| holds the highest-numbered location
3879 of |mem| that has ever been used. The free locations of |mem| that
3880 occur between |hi_mem_min| and |mem_end|, inclusive, are of type
3881 |two_halves|, and we write |info(p)| and |link(p)| for the |lh|
3882 and |rh| fields of |mem[p]| when it is of this type. The single-word
3883 free locations form a linked list
3884 $$|avail|,\;\hbox{|link(avail)|},\;\hbox{|link(link(avail))|},\;\ldots$$
3885 terminated by |null|.
3886
3887 @d link(A)   mp->mem[(A)].hh.rh /* the |link| field of a memory word */
3888 @d info(A)   mp->mem[(A)].hh.lh /* the |info| field of a memory word */
3889
3890 @<Glob...@>=
3891 pointer avail; /* head of the list of available one-word nodes */
3892 pointer mem_end; /* the last one-word node used in |mem| */
3893
3894 @ If one-word memory is exhausted, it might mean that the user has forgotten
3895 a token like `\&{enddef}' or `\&{endfor}'. We will define some procedures
3896 later that try to help pinpoint the trouble.
3897
3898 @c 
3899 @<Declare the procedure called |show_token_list|@>;
3900 @<Declare the procedure called |runaway|@>
3901
3902 @ The function |get_avail| returns a pointer to a new one-word node whose
3903 |link| field is null. However, \MP\ will halt if there is no more room left.
3904 @^inner loop@>
3905
3906 @c 
3907 pointer mp_get_avail (MP mp) { /* single-word node allocation */
3908   pointer p; /* the new node being got */
3909   p=mp->avail; /* get top location in the |avail| stack */
3910   if ( p!=null ) {
3911     mp->avail=link(mp->avail); /* and pop it off */
3912   } else if ( mp->mem_end<mp->mem_max ) { /* or go into virgin territory */
3913     incr(mp->mem_end); p=mp->mem_end;
3914   } else { 
3915     decr(mp->hi_mem_min); p=mp->hi_mem_min;
3916     if ( mp->hi_mem_min<=mp->lo_mem_max ) { 
3917       mp_runaway(mp); /* if memory is exhausted, display possible runaway text */
3918       mp_overflow(mp, "main memory size",mp->mem_max);
3919       /* quit; all one-word nodes are busy */
3920 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
3921     }
3922   }
3923   link(p)=null; /* provide an oft-desired initialization of the new node */
3924   incr(mp->dyn_used);/* maintain statistics */
3925   return p;
3926 };
3927
3928 @ Conversely, a one-word node is recycled by calling |free_avail|.
3929
3930 @d free_avail(A)  /* single-word node liberation */
3931   { link((A))=mp->avail; mp->avail=(A); decr(mp->dyn_used);  }
3932
3933 @ There's also a |fast_get_avail| routine, which saves the procedure-call
3934 overhead at the expense of extra programming. This macro is used in
3935 the places that would otherwise account for the most calls of |get_avail|.
3936 @^inner loop@>
3937
3938 @d fast_get_avail(A) { 
3939   (A)=mp->avail; /* avoid |get_avail| if possible, to save time */
3940   if ( (A)==null ) { (A)=mp_get_avail(mp); } 
3941   else { mp->avail=link((A)); link((A))=null;  incr(mp->dyn_used); }
3942   }
3943
3944 @ The available-space list that keeps track of the variable-size portion
3945 of |mem| is a nonempty, doubly-linked circular list of empty nodes,
3946 pointed to by the roving pointer |rover|.
3947
3948 Each empty node has size 2 or more; the first word contains the special
3949 value |max_halfword| in its |link| field and the size in its |info| field;
3950 the second word contains the two pointers for double linking.
3951
3952 Each nonempty node also has size 2 or more. Its first word is of type
3953 |two_halves|\kern-1pt, and its |link| field is never equal to |max_halfword|.
3954 Otherwise there is complete flexibility with respect to the contents
3955 of its other fields and its other words.
3956
3957 (We require |mem_max<max_halfword| because terrible things can happen
3958 when |max_halfword| appears in the |link| field of a nonempty node.)
3959
3960 @d empty_flag   max_halfword /* the |link| of an empty variable-size node */
3961 @d is_empty(A)   (link((A))==empty_flag) /* tests for empty node */
3962 @d node_size   info /* the size field in empty variable-size nodes */
3963 @d llink(A)   info((A)+1) /* left link in doubly-linked list of empty nodes */
3964 @d rlink(A)   link((A)+1) /* right link in doubly-linked list of empty nodes */
3965
3966 @<Glob...@>=
3967 pointer rover; /* points to some node in the list of empties */
3968
3969 @ A call to |get_node| with argument |s| returns a pointer to a new node
3970 of size~|s|, which must be 2~or more. The |link| field of the first word
3971 of this new node is set to null. An overflow stop occurs if no suitable
3972 space exists.
3973
3974 If |get_node| is called with $s=2^{30}$, it simply merges adjacent free
3975 areas and returns the value |max_halfword|.
3976
3977 @<Declarations@>=
3978 pointer mp_get_node (MP mp,integer s) ;
3979
3980 @ @c 
3981 pointer mp_get_node (MP mp,integer s) { /* variable-size node allocation */
3982   pointer p; /* the node currently under inspection */
3983   pointer q;  /* the node physically after node |p| */
3984   integer r; /* the newly allocated node, or a candidate for this honor */
3985   integer t,tt; /* temporary registers */
3986 @^inner loop@>
3987  RESTART: 
3988   p=mp->rover; /* start at some free node in the ring */
3989   do {  
3990     @<Try to allocate within node |p| and its physical successors,
3991      and |goto found| if allocation was possible@>;
3992     p=rlink(p); /* move to the next node in the ring */
3993   } while (p!=mp->rover); /* repeat until the whole list has been traversed */
3994   if ( s==010000000000 ) { 
3995     return max_halfword;
3996   };
3997   if ( mp->lo_mem_max+2<mp->hi_mem_min ) {
3998     if ( mp->lo_mem_max+2<=max_halfword ) {
3999       @<Grow more variable-size memory and |goto restart|@>;
4000     }
4001   }
4002   mp_overflow(mp, "main memory size",mp->mem_max);
4003   /* sorry, nothing satisfactory is left */
4004 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
4005 FOUND: 
4006   link(r)=null; /* this node is now nonempty */
4007   mp->var_used=mp->var_used+s; /* maintain usage statistics */
4008   return r;
4009 }
4010
4011 @ The lower part of |mem| grows by 1000 words at a time, unless
4012 we are very close to going under. When it grows, we simply link
4013 a new node into the available-space list. This method of controlled
4014 growth helps to keep the |mem| usage consecutive when \MP\ is
4015 implemented on ``virtual memory'' systems.
4016 @^virtual memory@>
4017
4018 @<Grow more variable-size memory and |goto restart|@>=
4019
4020   if ( mp->hi_mem_min-mp->lo_mem_max>=1998 ) {
4021     t=mp->lo_mem_max+1000;
4022   } else {
4023     t=mp->lo_mem_max+1+(mp->hi_mem_min-mp->lo_mem_max) / 2; 
4024     /* |lo_mem_max+2<=t<hi_mem_min| */
4025   }
4026   if ( t>max_halfword ) t=max_halfword;
4027   p=llink(mp->rover); q=mp->lo_mem_max; rlink(p)=q; llink(mp->rover)=q;
4028   rlink(q)=mp->rover; llink(q)=p; link(q)=empty_flag; node_size(q)=t-mp->lo_mem_max;
4029   mp->lo_mem_max=t; link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4030   mp->rover=q; 
4031   goto RESTART;
4032 }
4033
4034 @ @<Try to allocate...@>=
4035 q=p+node_size(p); /* find the physical successor */
4036 while ( is_empty(q) ) { /* merge node |p| with node |q| */
4037   t=rlink(q); tt=llink(q);
4038 @^inner loop@>
4039   if ( q==mp->rover ) mp->rover=t;
4040   llink(t)=tt; rlink(tt)=t;
4041   q=q+node_size(q);
4042 }
4043 r=q-s;
4044 if ( r>p+1 ) {
4045   @<Allocate from the top of node |p| and |goto found|@>;
4046 }
4047 if ( r==p ) { 
4048   if ( rlink(p)!=p ) {
4049     @<Allocate entire node |p| and |goto found|@>;
4050   }
4051 }
4052 node_size(p)=q-p /* reset the size in case it grew */
4053
4054 @ @<Allocate from the top...@>=
4055
4056   node_size(p)=r-p; /* store the remaining size */
4057   mp->rover=p; /* start searching here next time */
4058   goto FOUND;
4059 }
4060
4061 @ Here we delete node |p| from the ring, and let |rover| rove around.
4062
4063 @<Allocate entire...@>=
4064
4065   mp->rover=rlink(p); t=llink(p);
4066   llink(mp->rover)=t; rlink(t)=mp->rover;
4067   goto FOUND;
4068 }
4069
4070 @ Conversely, when some variable-size node |p| of size |s| is no longer needed,
4071 the operation |free_node(p,s)| will make its words available, by inserting
4072 |p| as a new empty node just before where |rover| now points.
4073
4074 @<Declarations@>=
4075 void mp_free_node (MP mp, pointer p, halfword s) ;
4076
4077 @ @c 
4078 void mp_free_node (MP mp, pointer p, halfword s) { /* variable-size node
4079   liberation */
4080   pointer q; /* |llink(rover)| */
4081   node_size(p)=s; link(p)=empty_flag;
4082 @^inner loop@>
4083   q=llink(mp->rover); llink(p)=q; rlink(p)=mp->rover; /* set both links */
4084   llink(mp->rover)=p; rlink(q)=p; /* insert |p| into the ring */
4085   mp->var_used=mp->var_used-s; /* maintain statistics */
4086 }
4087
4088 @ Just before \.{INIMP} writes out the memory, it sorts the doubly linked
4089 available space list. The list is probably very short at such times, so a
4090 simple insertion sort is used. The smallest available location will be
4091 pointed to by |rover|, the next-smallest by |rlink(rover)|, etc.
4092
4093 @c 
4094 void mp_sort_avail (MP mp) { /* sorts the available variable-size nodes
4095   by location */
4096   pointer p,q,r; /* indices into |mem| */
4097   pointer old_rover; /* initial |rover| setting */
4098   p=mp_get_node(mp, 010000000000); /* merge adjacent free areas */
4099   p=rlink(mp->rover); rlink(mp->rover)=max_halfword; old_rover=mp->rover;
4100   while ( p!=old_rover ) {
4101     @<Sort |p| into the list starting at |rover|
4102      and advance |p| to |rlink(p)|@>;
4103   }
4104   p=mp->rover;
4105   while ( rlink(p)!=max_halfword ) { 
4106     llink(rlink(p))=p; p=rlink(p);
4107   };
4108   rlink(p)=mp->rover; llink(mp->rover)=p;
4109 }
4110
4111 @ The following |while| loop is guaranteed to
4112 terminate, since the list that starts at
4113 |rover| ends with |max_halfword| during the sorting procedure.
4114
4115 @<Sort |p|...@>=
4116 if ( p<mp->rover ) { 
4117   q=p; p=rlink(q); rlink(q)=mp->rover; mp->rover=q;
4118 } else  { 
4119   q=mp->rover;
4120   while ( rlink(q)<p ) q=rlink(q);
4121   r=rlink(p); rlink(p)=rlink(q); rlink(q)=p; p=r;
4122 }
4123
4124 @* \[11] Memory layout.
4125 Some areas of |mem| are dedicated to fixed usage, since static allocation is
4126 more efficient than dynamic allocation when we can get away with it. For
4127 example, locations |0| to |1| are always used to store a
4128 two-word dummy token whose second word is zero.
4129 The following macro definitions accomplish the static allocation by giving
4130 symbolic names to the fixed positions. Static variable-size nodes appear
4131 in locations |0| through |lo_mem_stat_max|, and static single-word nodes
4132 appear in locations |hi_mem_stat_min| through |mem_top|, inclusive.
4133
4134 @d null_dash (2) /* the first two words are reserved for a null value */
4135 @d dep_head (null_dash+3) /* we will define |dash_node_size=3| */
4136 @d zero_val (dep_head+2) /* two words for a permanently zero value */
4137 @d temp_val (zero_val+2) /* two words for a temporary value node */
4138 @d end_attr temp_val /* we use |end_attr+2| only */
4139 @d inf_val (end_attr+2) /* and |inf_val+1| only */
4140 @d test_pen (inf_val+2)
4141   /* nine words for a pen used when testing the turning number */
4142 @d bad_vardef (test_pen+9) /* two words for \&{vardef} error recovery */
4143 @d lo_mem_stat_max (bad_vardef+1)  /* largest statically
4144   allocated word in the variable-size |mem| */
4145 @#
4146 @d sentinel mp->mem_top /* end of sorted lists */
4147 @d temp_head (mp->mem_top-1) /* head of a temporary list of some kind */
4148 @d hold_head (mp->mem_top-2) /* head of a temporary list of another kind */
4149 @d spec_head (mp->mem_top-3) /* head of a list of unprocessed \&{special} items */
4150 @d hi_mem_stat_min (mp->mem_top-3) /* smallest statically allocated word in
4151   the one-word |mem| */
4152
4153 @ The following code gets the dynamic part of |mem| off to a good start,
4154 when \MP\ is initializing itself the slow way.
4155
4156 @<Initialize table entries (done by \.{INIMP} only)@>=
4157 @^data structure assumptions@>
4158 mp->rover=lo_mem_stat_max+1; /* initialize the dynamic memory */
4159 link(mp->rover)=empty_flag;
4160 node_size(mp->rover)=1000; /* which is a 1000-word available node */
4161 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
4162 mp->lo_mem_max=mp->rover+1000; link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4163 for (k=hi_mem_stat_min;k<=(int)mp->mem_top;k++) {
4164   mp->mem[k]=mp->mem[mp->lo_mem_max]; /* clear list heads */
4165 }
4166 mp->avail=null; mp->mem_end=mp->mem_top;
4167 mp->hi_mem_min=hi_mem_stat_min; /* initialize the one-word memory */
4168 mp->var_used=lo_mem_stat_max+1; 
4169 mp->dyn_used=mp->mem_top+1-(hi_mem_stat_min);  /* initialize statistics */
4170 @<Initialize a pen at |test_pen| so that it fits in nine words@>;
4171
4172 @ The procedure |flush_list(p)| frees an entire linked list of one-word
4173 nodes that starts at a given position, until coming to |sentinel| or a
4174 pointer that is not in the one-word region. Another procedure,
4175 |flush_node_list|, frees an entire linked list of one-word and two-word
4176 nodes, until coming to a |null| pointer.
4177 @^inner loop@>
4178
4179 @c 
4180 void mp_flush_list (MP mp,pointer p) { /* makes list of single-word nodes  available */
4181   pointer q,r; /* list traversers */
4182   if ( p>=mp->hi_mem_min ) if ( p!=sentinel ) { 
4183     r=p;
4184     do {  
4185       q=r; r=link(r); 
4186       decr(mp->dyn_used);
4187       if ( r<mp->hi_mem_min ) break;
4188     } while (r!=sentinel);
4189   /* now |q| is the last node on the list */
4190     link(q)=mp->avail; mp->avail=p;
4191   }
4192 }
4193 @#
4194 void mp_flush_node_list (MP mp,pointer p) {
4195   pointer q; /* the node being recycled */
4196   while ( p!=null ){ 
4197     q=p; p=link(p);
4198     if ( q<mp->hi_mem_min ) 
4199       mp_free_node(mp, q,2);
4200     else 
4201       free_avail(q);
4202   }
4203 }
4204
4205 @ If \MP\ is extended improperly, the |mem| array might get screwed up.
4206 For example, some pointers might be wrong, or some ``dead'' nodes might not
4207 have been freed when the last reference to them disappeared. Procedures
4208 |check_mem| and |search_mem| are available to help diagnose such
4209 problems. These procedures make use of two arrays called |free| and
4210 |was_free| that are present only if \MP's debugging routines have
4211 been included. (You may want to decrease the size of |mem| while you
4212 @^debugging@>
4213 are debugging.)
4214
4215 Because |boolean|s are typedef-d as ints, it is better to use
4216 unsigned chars here.
4217
4218 @<Glob...@>=
4219 unsigned char *free; /* free cells */
4220 unsigned char *was_free; /* previously free cells */
4221 pointer was_mem_end; pointer was_lo_max; pointer was_hi_min;
4222   /* previous |mem_end|, |lo_mem_max|,and |hi_mem_min| */
4223 boolean panicking; /* do we want to check memory constantly? */
4224
4225 @ @<Allocate or initialize ...@>=
4226 mp->free = xmalloc ((mp->mem_max+1),sizeof (unsigned char));
4227 mp->was_free = xmalloc ((mp->mem_max+1), sizeof (unsigned char));
4228
4229 @ @<Dealloc variables@>=
4230 xfree(mp->free);
4231 xfree(mp->was_free);
4232
4233 @ @<Allocate or ...@>=
4234 mp->was_mem_end=0; /* indicate that everything was previously free */
4235 mp->was_lo_max=0; mp->was_hi_min=mp->mem_max;
4236 mp->panicking=false;
4237
4238 @ @<Declare |mp_reallocate| functions@>=
4239 void mp_reallocate_memory(MP mp, int l) ;
4240
4241 @ @c
4242 void mp_reallocate_memory(MP mp, int l) {
4243    XREALLOC(mp->free,     (l+1), unsigned char);
4244    XREALLOC(mp->was_free, (l+1), unsigned char);
4245    XREALLOC(mp->mem,      (l+1), memory_word);
4246    mp->mem_max = l;
4247    if (mp->ini_version) 
4248      mp->mem_top = l;
4249 }
4250
4251
4252
4253 @ Procedure |check_mem| makes sure that the available space lists of
4254 |mem| are well formed, and it optionally prints out all locations
4255 that are reserved now but were free the last time this procedure was called.
4256
4257 @c 
4258 void mp_check_mem (MP mp,boolean print_locs ) {
4259   pointer p,q,r; /* current locations of interest in |mem| */
4260   boolean clobbered; /* is something amiss? */
4261   for (p=0;p<=mp->lo_mem_max;p++) {
4262     mp->free[p]=false; /* you can probably do this faster */
4263   }
4264   for (p=mp->hi_mem_min;p<= mp->mem_end;p++) {
4265     mp->free[p]=false; /* ditto */
4266   }
4267   @<Check single-word |avail| list@>;
4268   @<Check variable-size |avail| list@>;
4269   @<Check flags of unavailable nodes@>;
4270   @<Check the list of linear dependencies@>;
4271   if ( print_locs ) {
4272     @<Print newly busy locations@>;
4273   }
4274   for (p=0;p<=mp->lo_mem_max;p++) {
4275     mp->was_free[p]=mp->free[p];
4276   }
4277   for (p=mp->hi_mem_min;p<=mp->mem_end;p++) {
4278     mp->was_free[p]=mp->free[p];
4279   }
4280   /* |was_free:=free| might be faster */
4281   mp->was_mem_end=mp->mem_end; 
4282   mp->was_lo_max=mp->lo_mem_max; 
4283   mp->was_hi_min=mp->hi_mem_min;
4284 }
4285
4286 @ @<Check single-word...@>=
4287 p=mp->avail; q=null; clobbered=false;
4288 while ( p!=null ) { 
4289   if ( (p>mp->mem_end)||(p<mp->hi_mem_min) ) clobbered=true;
4290   else if ( mp->free[p] ) clobbered=true;
4291   if ( clobbered ) { 
4292     mp_print_nl(mp, "AVAIL list clobbered at ");
4293 @.AVAIL list clobbered...@>
4294     mp_print_int(mp, q); break;
4295   }
4296   mp->free[p]=true; q=p; p=link(q);
4297 }
4298
4299 @ @<Check variable-size...@>=
4300 p=mp->rover; q=null; clobbered=false;
4301 do {  
4302   if ( (p>=mp->lo_mem_max)||(p<0) ) clobbered=true;
4303   else if ( (rlink(p)>=mp->lo_mem_max)||(rlink(p)<0) ) clobbered=true;
4304   else if (  !(is_empty(p))||(node_size(p)<2)||
4305    (p+node_size(p)>mp->lo_mem_max)|| (llink(rlink(p))!=p) ) clobbered=true;
4306   if ( clobbered ) { 
4307     mp_print_nl(mp, "Double-AVAIL list clobbered at ");
4308 @.Double-AVAIL list clobbered...@>
4309     mp_print_int(mp, q); break;
4310   }
4311   for (q=p;q<=p+node_size(p)-1;q++) { /* mark all locations free */
4312     if ( mp->free[q] ) { 
4313       mp_print_nl(mp, "Doubly free location at ");
4314 @.Doubly free location...@>
4315       mp_print_int(mp, q); break;
4316     }
4317     mp->free[q]=true;
4318   }
4319   q=p; p=rlink(p);
4320 } while (p!=mp->rover)
4321
4322
4323 @ @<Check flags...@>=
4324 p=0;
4325 while ( p<=mp->lo_mem_max ) { /* node |p| should not be empty */
4326   if ( is_empty(p) ) {
4327     mp_print_nl(mp, "Bad flag at "); mp_print_int(mp, p);
4328 @.Bad flag...@>
4329   }
4330   while ( (p<=mp->lo_mem_max) && ! mp->free[p] ) incr(p);
4331   while ( (p<=mp->lo_mem_max) && mp->free[p] ) incr(p);
4332 }
4333
4334 @ @<Print newly busy...@>=
4335
4336   @<Do intialization required before printing new busy locations@>;
4337   mp_print_nl(mp, "New busy locs:");
4338 @.New busy locs@>
4339   for (p=0;p<= mp->lo_mem_max;p++ ) {
4340     if ( ! mp->free[p] && ((p>mp->was_lo_max) || mp->was_free[p]) ) {
4341       @<Indicate that |p| is a new busy location@>;
4342     }
4343   }
4344   for (p=mp->hi_mem_min;p<=mp->mem_end;p++ ) {
4345     if ( ! mp->free[p] &&
4346         ((p<mp->was_hi_min) || (p>mp->was_mem_end) || mp->was_free[p]) ) {
4347       @<Indicate that |p| is a new busy location@>;
4348     }
4349   }
4350   @<Finish printing new busy locations@>;
4351 }
4352
4353 @ There might be many new busy locations so we are careful to print contiguous
4354 blocks compactly.  During this operation |q| is the last new busy location and
4355 |r| is the start of the block containing |q|.
4356
4357 @<Indicate that |p| is a new busy location@>=
4358
4359   if ( p>q+1 ) { 
4360     if ( q>r ) { 
4361       mp_print(mp, ".."); mp_print_int(mp, q);
4362     }
4363     mp_print_char(mp, ' '); mp_print_int(mp, p);
4364     r=p;
4365   }
4366   q=p;
4367 }
4368
4369 @ @<Do intialization required before printing new busy locations@>=
4370 q=mp->mem_max; r=mp->mem_max
4371
4372 @ @<Finish printing new busy locations@>=
4373 if ( q>r ) { 
4374   mp_print(mp, ".."); mp_print_int(mp, q);
4375 }
4376
4377 @ The |search_mem| procedure attempts to answer the question ``Who points
4378 to node~|p|?'' In doing so, it fetches |link| and |info| fields of |mem|
4379 that might not be of type |two_halves|. Strictly speaking, this is
4380 @^dirty \PASCAL@>
4381 undefined in \PASCAL, and it can lead to ``false drops'' (words that seem to
4382 point to |p| purely by coincidence). But for debugging purposes, we want
4383 to rule out the places that do {\sl not\/} point to |p|, so a few false
4384 drops are tolerable.
4385
4386 @c
4387 void mp_search_mem (MP mp, pointer p) { /* look for pointers to |p| */
4388   integer q; /* current position being searched */
4389   for (q=0;q<=mp->lo_mem_max;q++) { 
4390     if ( link(q)==p ){ 
4391       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4392     }
4393     if ( info(q)==p ) { 
4394       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4395     }
4396   }
4397   for (q=mp->hi_mem_min;q<=mp->mem_end;q++) {
4398     if ( link(q)==p ) {
4399       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4400     }
4401     if ( info(q)==p ) {
4402       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4403     }
4404   }
4405   @<Search |eqtb| for equivalents equal to |p|@>;
4406 }
4407
4408 @* \[12] The command codes.
4409 Before we can go much further, we need to define symbolic names for the internal
4410 code numbers that represent the various commands obeyed by \MP. These codes
4411 are somewhat arbitrary, but not completely so. For example,
4412 some codes have been made adjacent so that |case| statements in the
4413 program need not consider cases that are widely spaced, or so that |case|
4414 statements can be replaced by |if| statements. A command can begin an
4415 expression if and only if its code lies between |min_primary_command| and
4416 |max_primary_command|, inclusive. The first token of a statement that doesn't
4417 begin with an expression has a command code between |min_command| and
4418 |max_statement_command|, inclusive. Anything less than |min_command| is
4419 eliminated during macro expansions, and anything no more than |max_pre_command|
4420 is eliminated when expanding \TeX\ material.  Ranges such as
4421 |min_secondary_command..max_secondary_command| are used when parsing
4422 expressions, but the relative ordering within such a range is generally not
4423 critical.
4424
4425 The ordering of the highest-numbered commands
4426 (|comma<semicolon<end_group<stop|) is crucial for the parsing and
4427 error-recovery methods of this program as is the ordering |if_test<fi_or_else|
4428 for the smallest two commands.  The ordering is also important in the ranges
4429 |numeric_token..plus_or_minus| and |left_brace..ampersand|.
4430
4431 At any rate, here is the list, for future reference.
4432
4433 @d start_tex 1 /* begin \TeX\ material (\&{btex}, \&{verbatimtex}) */
4434 @d etex_marker 2 /* end \TeX\ material (\&{etex}) */
4435 @d mpx_break 3 /* stop reading an \.{MPX} file (\&{mpxbreak}) */
4436 @d max_pre_command mpx_break
4437 @d if_test 4 /* conditional text (\&{if}) */
4438 @d fi_or_else 5 /* delimiters for conditionals (\&{elseif}, \&{else}, \&{fi} */
4439 @d input 6 /* input a source file (\&{input}, \&{endinput}) */
4440 @d iteration 7 /* iterate (\&{for}, \&{forsuffixes}, \&{forever}, \&{endfor}) */
4441 @d repeat_loop 8 /* special command substituted for \&{endfor} */
4442 @d exit_test 9 /* premature exit from a loop (\&{exitif}) */
4443 @d relax 10 /* do nothing (\.{\char`\\}) */
4444 @d scan_tokens 11 /* put a string into the input buffer */
4445 @d expand_after 12 /* look ahead one token */
4446 @d defined_macro 13 /* a macro defined by the user */
4447 @d min_command (defined_macro+1)
4448 @d save_command 14 /* save a list of tokens (\&{save}) */
4449 @d interim_command 15 /* save an internal quantity (\&{interim}) */
4450 @d let_command 16 /* redefine a symbolic token (\&{let}) */
4451 @d new_internal 17 /* define a new internal quantity (\&{newinternal}) */
4452 @d macro_def 18 /* define a macro (\&{def}, \&{vardef}, etc.) */
4453 @d ship_out_command 19 /* output a character (\&{shipout}) */
4454 @d add_to_command 20 /* add to edges (\&{addto}) */
4455 @d bounds_command 21  /* add bounding path to edges (\&{setbounds}, \&{clip}) */
4456 @d tfm_command 22 /* command for font metric info (\&{ligtable}, etc.) */
4457 @d protection_command 23 /* set protection flag (\&{outer}, \&{inner}) */
4458 @d show_command 24 /* diagnostic output (\&{show}, \&{showvariable}, etc.) */
4459 @d mode_command 25 /* set interaction level (\&{batchmode}, etc.) */
4460 @d random_seed 26 /* initialize random number generator (\&{randomseed}) */
4461 @d message_command 27 /* communicate to user (\&{message}, \&{errmessage}) */
4462 @d every_job_command 28 /* designate a starting token (\&{everyjob}) */
4463 @d delimiters 29 /* define a pair of delimiters (\&{delimiters}) */
4464 @d special_command 30 /* output special info (\&{special})
4465                        or font map info (\&{fontmapfile}, \&{fontmapline}) */
4466 @d write_command 31 /* write text to a file (\&{write}) */
4467 @d type_name 32 /* declare a type (\&{numeric}, \&{pair}, etc. */
4468 @d max_statement_command type_name
4469 @d min_primary_command type_name
4470 @d left_delimiter 33 /* the left delimiter of a matching pair */
4471 @d begin_group 34 /* beginning of a group (\&{begingroup}) */
4472 @d nullary 35 /* an operator without arguments (e.g., \&{normaldeviate}) */
4473 @d unary 36 /* an operator with one argument (e.g., \&{sqrt}) */
4474 @d str_op 37 /* convert a suffix to a string (\&{str}) */
4475 @d cycle 38 /* close a cyclic path (\&{cycle}) */
4476 @d primary_binary 39 /* binary operation taking `\&{of}' (e.g., \&{point}) */
4477 @d capsule_token 40 /* a value that has been put into a token list */
4478 @d string_token 41 /* a string constant (e.g., |"hello"|) */
4479 @d internal_quantity 42 /* internal numeric parameter (e.g., \&{pausing}) */
4480 @d min_suffix_token internal_quantity
4481 @d tag_token 43 /* a symbolic token without a primitive meaning */
4482 @d numeric_token 44 /* a numeric constant (e.g., \.{3.14159}) */
4483 @d max_suffix_token numeric_token
4484 @d plus_or_minus 45 /* either `\.+' or `\.-' */
4485 @d max_primary_command plus_or_minus /* should also be |numeric_token+1| */
4486 @d min_tertiary_command plus_or_minus
4487 @d tertiary_secondary_macro 46 /* a macro defined by \&{secondarydef} */
4488 @d tertiary_binary 47 /* an operator at the tertiary level (e.g., `\.{++}') */
4489 @d max_tertiary_command tertiary_binary
4490 @d left_brace 48 /* the operator `\.{\char`\{}' */
4491 @d min_expression_command left_brace
4492 @d path_join 49 /* the operator `\.{..}' */
4493 @d ampersand 50 /* the operator `\.\&' */
4494 @d expression_tertiary_macro 51 /* a macro defined by \&{tertiarydef} */
4495 @d expression_binary 52 /* an operator at the expression level (e.g., `\.<') */
4496 @d equals 53 /* the operator `\.=' */
4497 @d max_expression_command equals
4498 @d and_command 54 /* the operator `\&{and}' */
4499 @d min_secondary_command and_command
4500 @d secondary_primary_macro 55 /* a macro defined by \&{primarydef} */
4501 @d slash 56 /* the operator `\./' */
4502 @d secondary_binary 57 /* an operator at the binary level (e.g., \&{shifted}) */
4503 @d max_secondary_command secondary_binary
4504 @d param_type 58 /* type of parameter (\&{primary}, \&{expr}, \&{suffix}, etc.) */
4505 @d controls 59 /* specify control points explicitly (\&{controls}) */
4506 @d tension 60 /* specify tension between knots (\&{tension}) */
4507 @d at_least 61 /* bounded tension value (\&{atleast}) */
4508 @d curl_command 62 /* specify curl at an end knot (\&{curl}) */
4509 @d macro_special 63 /* special macro operators (\&{quote}, \.{\#\AT!}, etc.) */
4510 @d right_delimiter 64 /* the right delimiter of a matching pair */
4511 @d left_bracket 65 /* the operator `\.[' */
4512 @d right_bracket 66 /* the operator `\.]' */
4513 @d right_brace 67 /* the operator `\.{\char`\}}' */
4514 @d with_option 68 /* option for filling (\&{withpen}, \&{withweight}, etc.) */
4515 @d thing_to_add 69
4516   /* variant of \&{addto} (\&{contour}, \&{doublepath}, \&{also}) */
4517 @d of_token 70 /* the operator `\&{of}' */
4518 @d to_token 71 /* the operator `\&{to}' */
4519 @d step_token 72 /* the operator `\&{step}' */
4520 @d until_token 73 /* the operator `\&{until}' */
4521 @d within_token 74 /* the operator `\&{within}' */
4522 @d lig_kern_token 75
4523   /* the operators `\&{kern}' and `\.{=:}' and `\.{=:\char'174}, etc. */
4524 @d assignment 76 /* the operator `\.{:=}' */
4525 @d skip_to 77 /* the operation `\&{skipto}' */
4526 @d bchar_label 78 /* the operator `\.{\char'174\char'174:}' */
4527 @d double_colon 79 /* the operator `\.{::}' */
4528 @d colon 80 /* the operator `\.:' */
4529 @#
4530 @d comma 81 /* the operator `\.,', must be |colon+1| */
4531 @d end_of_statement (mp->cur_cmd>comma)
4532 @d semicolon 82 /* the operator `\.;', must be |comma+1| */
4533 @d end_group 83 /* end a group (\&{endgroup}), must be |semicolon+1| */
4534 @d stop 84 /* end a job (\&{end}, \&{dump}), must be |end_group+1| */
4535 @d max_command_code stop
4536 @d outer_tag (max_command_code+1) /* protection code added to command code */
4537
4538 @<Types...@>=
4539 typedef int command_code;
4540
4541 @ Variables and capsules in \MP\ have a variety of ``types,''
4542 distinguished by the code numbers defined here. These numbers are also
4543 not completely arbitrary.  Things that get expanded must have types
4544 |>mp_independent|; a type remaining after expansion is numeric if and only if
4545 its code number is at least |numeric_type|; objects containing numeric
4546 parts must have types between |transform_type| and |pair_type|;
4547 all other types must be smaller than |transform_type|; and among the types
4548 that are not unknown or vacuous, the smallest two must be |boolean_type|
4549 and |string_type| in that order.
4550  
4551 @d undefined 0 /* no type has been declared */
4552 @d unknown_tag 1 /* this constant is added to certain type codes below */
4553 @d unknown_types mp_unknown_boolean: case mp_unknown_string:
4554   case mp_unknown_pen: case mp_unknown_picture: case mp_unknown_path
4555
4556 @<Types...@>=
4557 enum {
4558 mp_vacuous=1, /* no expression was present */
4559 mp_boolean_type, /* \&{boolean} with a known value */
4560 mp_unknown_boolean,
4561 mp_string_type, /* \&{string} with a known value */
4562 mp_unknown_string,
4563 mp_pen_type, /* \&{pen} with a known value */
4564 mp_unknown_pen,
4565 mp_path_type, /* \&{path} with a known value */
4566 mp_unknown_path,
4567 mp_picture_type, /* \&{picture} with a known value */
4568 mp_unknown_picture,
4569 mp_transform_type, /* \&{transform} variable or capsule */
4570 mp_color_type, /* \&{color} variable or capsule */
4571 mp_cmykcolor_type, /* \&{cmykcolor} variable or capsule */
4572 mp_pair_type, /* \&{pair} variable or capsule */
4573 mp_numeric_type, /* variable that has been declared \&{numeric} but not used */
4574 mp_known, /* \&{numeric} with a known value */
4575 mp_dependent, /* a linear combination with |fraction| coefficients */
4576 mp_proto_dependent, /* a linear combination with |scaled| coefficients */
4577 mp_independent, /* \&{numeric} with unknown value */
4578 mp_token_list, /* variable name or suffix argument or text argument */
4579 mp_structured, /* variable with subscripts and attributes */
4580 mp_unsuffixed_macro, /* variable defined with \&{vardef} but no \.{\AT!\#} */
4581 mp_suffixed_macro /* variable defined with \&{vardef} and \.{\AT!\#} */
4582 };
4583
4584 @ @<Declarations@>=
4585 void mp_print_type (MP mp,small_number t) ;
4586
4587 @ @<Basic printing procedures@>=
4588 void mp_print_type (MP mp,small_number t) { 
4589   switch (t) {
4590   case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
4591   case mp_boolean_type:mp_print(mp, "boolean"); break;
4592   case mp_unknown_boolean:mp_print(mp, "unknown boolean"); break;
4593   case mp_string_type:mp_print(mp, "string"); break;
4594   case mp_unknown_string:mp_print(mp, "unknown string"); break;
4595   case mp_pen_type:mp_print(mp, "pen"); break;
4596   case mp_unknown_pen:mp_print(mp, "unknown pen"); break;
4597   case mp_path_type:mp_print(mp, "path"); break;
4598   case mp_unknown_path:mp_print(mp, "unknown path"); break;
4599   case mp_picture_type:mp_print(mp, "picture"); break;
4600   case mp_unknown_picture:mp_print(mp, "unknown picture"); break;
4601   case mp_transform_type:mp_print(mp, "transform"); break;
4602   case mp_color_type:mp_print(mp, "color"); break;
4603   case mp_cmykcolor_type:mp_print(mp, "cmykcolor"); break;
4604   case mp_pair_type:mp_print(mp, "pair"); break;
4605   case mp_known:mp_print(mp, "known numeric"); break;
4606   case mp_dependent:mp_print(mp, "dependent"); break;
4607   case mp_proto_dependent:mp_print(mp, "proto-dependent"); break;
4608   case mp_numeric_type:mp_print(mp, "numeric"); break;
4609   case mp_independent:mp_print(mp, "independent"); break;
4610   case mp_token_list:mp_print(mp, "token list"); break;
4611   case mp_structured:mp_print(mp, "mp_structured"); break;
4612   case mp_unsuffixed_macro:mp_print(mp, "unsuffixed macro"); break;
4613   case mp_suffixed_macro:mp_print(mp, "suffixed macro"); break;
4614   default: mp_print(mp, "undefined"); break;
4615   }
4616 }
4617
4618 @ Values inside \MP\ are stored in two-word nodes that have a |name_type|
4619 as well as a |type|. The possibilities for |name_type| are defined
4620 here; they will be explained in more detail later.
4621
4622 @<Types...@>=
4623 enum {
4624  mp_root=0, /* |name_type| at the top level of a variable */
4625  mp_saved_root, /* same, when the variable has been saved */
4626  mp_structured_root, /* |name_type| where a |mp_structured| branch occurs */
4627  mp_subscr, /* |name_type| in a subscript node */
4628  mp_attr, /* |name_type| in an attribute node */
4629  mp_x_part_sector, /* |name_type| in the \&{xpart} of a node */
4630  mp_y_part_sector, /* |name_type| in the \&{ypart} of a node */
4631  mp_xx_part_sector, /* |name_type| in the \&{xxpart} of a node */
4632  mp_xy_part_sector, /* |name_type| in the \&{xypart} of a node */
4633  mp_yx_part_sector, /* |name_type| in the \&{yxpart} of a node */
4634  mp_yy_part_sector, /* |name_type| in the \&{yypart} of a node */
4635  mp_red_part_sector, /* |name_type| in the \&{redpart} of a node */
4636  mp_green_part_sector, /* |name_type| in the \&{greenpart} of a node */
4637  mp_blue_part_sector, /* |name_type| in the \&{bluepart} of a node */
4638  mp_cyan_part_sector, /* |name_type| in the \&{redpart} of a node */
4639  mp_magenta_part_sector, /* |name_type| in the \&{greenpart} of a node */
4640  mp_yellow_part_sector, /* |name_type| in the \&{bluepart} of a node */
4641  mp_black_part_sector, /* |name_type| in the \&{greenpart} of a node */
4642  mp_grey_part_sector, /* |name_type| in the \&{bluepart} of a node */
4643  mp_capsule, /* |name_type| in stashed-away subexpressions */
4644  mp_token  /* |name_type| in a numeric token or string token */
4645 };
4646
4647 @ Primitive operations that produce values have a secondary identification
4648 code in addition to their command code; it's something like genera and species.
4649 For example, `\.*' has the command code |primary_binary|, and its
4650 secondary identification is |times|. The secondary codes start at 30 so that
4651 they don't overlap with the type codes; some type codes (e.g., |mp_string_type|)
4652 are used as operators as well as type identifications.  The relative values
4653 are not critical, except for |true_code..false_code|, |or_op..and_op|,
4654 and |filled_op..bounded_op|.  The restrictions are that
4655 |and_op-false_code=or_op-true_code|, that the ordering of
4656 |x_part...blue_part| must match that of |x_part_sector..mp_blue_part_sector|,
4657 and the ordering of |filled_op..bounded_op| must match that of the code
4658 values they test for.
4659
4660 @d true_code 30 /* operation code for \.{true} */
4661 @d false_code 31 /* operation code for \.{false} */
4662 @d null_picture_code 32 /* operation code for \.{nullpicture} */
4663 @d null_pen_code 33 /* operation code for \.{nullpen} */
4664 @d job_name_op 34 /* operation code for \.{jobname} */
4665 @d read_string_op 35 /* operation code for \.{readstring} */
4666 @d pen_circle 36 /* operation code for \.{pencircle} */
4667 @d normal_deviate 37 /* operation code for \.{normaldeviate} */
4668 @d read_from_op 38 /* operation code for \.{readfrom} */
4669 @d close_from_op 39 /* operation code for \.{closefrom} */
4670 @d odd_op 40 /* operation code for \.{odd} */
4671 @d known_op 41 /* operation code for \.{known} */
4672 @d unknown_op 42 /* operation code for \.{unknown} */
4673 @d not_op 43 /* operation code for \.{not} */
4674 @d decimal 44 /* operation code for \.{decimal} */
4675 @d reverse 45 /* operation code for \.{reverse} */
4676 @d make_path_op 46 /* operation code for \.{makepath} */
4677 @d make_pen_op 47 /* operation code for \.{makepen} */
4678 @d oct_op 48 /* operation code for \.{oct} */
4679 @d hex_op 49 /* operation code for \.{hex} */
4680 @d ASCII_op 50 /* operation code for \.{ASCII} */
4681 @d char_op 51 /* operation code for \.{char} */
4682 @d length_op 52 /* operation code for \.{length} */
4683 @d turning_op 53 /* operation code for \.{turningnumber} */
4684 @d color_model_part 54 /* operation code for \.{colormodel} */
4685 @d x_part 55 /* operation code for \.{xpart} */
4686 @d y_part 56 /* operation code for \.{ypart} */
4687 @d xx_part 57 /* operation code for \.{xxpart} */
4688 @d xy_part 58 /* operation code for \.{xypart} */
4689 @d yx_part 59 /* operation code for \.{yxpart} */
4690 @d yy_part 60 /* operation code for \.{yypart} */
4691 @d red_part 61 /* operation code for \.{redpart} */
4692 @d green_part 62 /* operation code for \.{greenpart} */
4693 @d blue_part 63 /* operation code for \.{bluepart} */
4694 @d cyan_part 64 /* operation code for \.{cyanpart} */
4695 @d magenta_part 65 /* operation code for \.{magentapart} */
4696 @d yellow_part 66 /* operation code for \.{yellowpart} */
4697 @d black_part 67 /* operation code for \.{blackpart} */
4698 @d grey_part 68 /* operation code for \.{greypart} */
4699 @d font_part 69 /* operation code for \.{fontpart} */
4700 @d text_part 70 /* operation code for \.{textpart} */
4701 @d path_part 71 /* operation code for \.{pathpart} */
4702 @d pen_part 72 /* operation code for \.{penpart} */
4703 @d dash_part 73 /* operation code for \.{dashpart} */
4704 @d sqrt_op 74 /* operation code for \.{sqrt} */
4705 @d m_exp_op 75 /* operation code for \.{mexp} */
4706 @d m_log_op 76 /* operation code for \.{mlog} */
4707 @d sin_d_op 77 /* operation code for \.{sind} */
4708 @d cos_d_op 78 /* operation code for \.{cosd} */
4709 @d floor_op 79 /* operation code for \.{floor} */
4710 @d uniform_deviate 80 /* operation code for \.{uniformdeviate} */
4711 @d char_exists_op 81 /* operation code for \.{charexists} */
4712 @d font_size 82 /* operation code for \.{fontsize} */
4713 @d ll_corner_op 83 /* operation code for \.{llcorner} */
4714 @d lr_corner_op 84 /* operation code for \.{lrcorner} */
4715 @d ul_corner_op 85 /* operation code for \.{ulcorner} */
4716 @d ur_corner_op 86 /* operation code for \.{urcorner} */
4717 @d arc_length 87 /* operation code for \.{arclength} */
4718 @d angle_op 88 /* operation code for \.{angle} */
4719 @d cycle_op 89 /* operation code for \.{cycle} */
4720 @d filled_op 90 /* operation code for \.{filled} */
4721 @d stroked_op 91 /* operation code for \.{stroked} */
4722 @d textual_op 92 /* operation code for \.{textual} */
4723 @d clipped_op 93 /* operation code for \.{clipped} */
4724 @d bounded_op 94 /* operation code for \.{bounded} */
4725 @d plus 95 /* operation code for \.+ */
4726 @d minus 96 /* operation code for \.- */
4727 @d times 97 /* operation code for \.* */
4728 @d over 98 /* operation code for \./ */
4729 @d pythag_add 99 /* operation code for \.{++} */
4730 @d pythag_sub 100 /* operation code for \.{+-+} */
4731 @d or_op 101 /* operation code for \.{or} */
4732 @d and_op 102 /* operation code for \.{and} */
4733 @d less_than 103 /* operation code for \.< */
4734 @d less_or_equal 104 /* operation code for \.{<=} */
4735 @d greater_than 105 /* operation code for \.> */
4736 @d greater_or_equal 106 /* operation code for \.{>=} */
4737 @d equal_to 107 /* operation code for \.= */
4738 @d unequal_to 108 /* operation code for \.{<>} */
4739 @d concatenate 109 /* operation code for \.\& */
4740 @d rotated_by 110 /* operation code for \.{rotated} */
4741 @d slanted_by 111 /* operation code for \.{slanted} */
4742 @d scaled_by 112 /* operation code for \.{scaled} */
4743 @d shifted_by 113 /* operation code for \.{shifted} */
4744 @d transformed_by 114 /* operation code for \.{transformed} */
4745 @d x_scaled 115 /* operation code for \.{xscaled} */
4746 @d y_scaled 116 /* operation code for \.{yscaled} */
4747 @d z_scaled 117 /* operation code for \.{zscaled} */
4748 @d in_font 118 /* operation code for \.{infont} */
4749 @d intersect 119 /* operation code for \.{intersectiontimes} */
4750 @d double_dot 120 /* operation code for improper \.{..} */
4751 @d substring_of 121 /* operation code for \.{substring} */
4752 @d min_of substring_of
4753 @d subpath_of 122 /* operation code for \.{subpath} */
4754 @d direction_time_of 123 /* operation code for \.{directiontime} */
4755 @d point_of 124 /* operation code for \.{point} */
4756 @d precontrol_of 125 /* operation code for \.{precontrol} */
4757 @d postcontrol_of 126 /* operation code for \.{postcontrol} */
4758 @d pen_offset_of 127 /* operation code for \.{penoffset} */
4759 @d arc_time_of 128 /* operation code for \.{arctime} */
4760 @d mp_version 129 /* operation code for \.{mpversion} */
4761
4762 @c void mp_print_op (MP mp,quarterword c) { 
4763   if (c<=mp_numeric_type ) {
4764     mp_print_type(mp, c);
4765   } else {
4766     switch (c) {
4767     case true_code:mp_print(mp, "true"); break;
4768     case false_code:mp_print(mp, "false"); break;
4769     case null_picture_code:mp_print(mp, "nullpicture"); break;
4770     case null_pen_code:mp_print(mp, "nullpen"); break;
4771     case job_name_op:mp_print(mp, "jobname"); break;
4772     case read_string_op:mp_print(mp, "readstring"); break;
4773     case pen_circle:mp_print(mp, "pencircle"); break;
4774     case normal_deviate:mp_print(mp, "normaldeviate"); break;
4775     case read_from_op:mp_print(mp, "readfrom"); break;
4776     case close_from_op:mp_print(mp, "closefrom"); break;
4777     case odd_op:mp_print(mp, "odd"); break;
4778     case known_op:mp_print(mp, "known"); break;
4779     case unknown_op:mp_print(mp, "unknown"); break;
4780     case not_op:mp_print(mp, "not"); break;
4781     case decimal:mp_print(mp, "decimal"); break;
4782     case reverse:mp_print(mp, "reverse"); break;
4783     case make_path_op:mp_print(mp, "makepath"); break;
4784     case make_pen_op:mp_print(mp, "makepen"); break;
4785     case oct_op:mp_print(mp, "oct"); break;
4786     case hex_op:mp_print(mp, "hex"); break;
4787     case ASCII_op:mp_print(mp, "ASCII"); break;
4788     case char_op:mp_print(mp, "char"); break;
4789     case length_op:mp_print(mp, "length"); break;
4790     case turning_op:mp_print(mp, "turningnumber"); break;
4791     case x_part:mp_print(mp, "xpart"); break;
4792     case y_part:mp_print(mp, "ypart"); break;
4793     case xx_part:mp_print(mp, "xxpart"); break;
4794     case xy_part:mp_print(mp, "xypart"); break;
4795     case yx_part:mp_print(mp, "yxpart"); break;
4796     case yy_part:mp_print(mp, "yypart"); break;
4797     case red_part:mp_print(mp, "redpart"); break;
4798     case green_part:mp_print(mp, "greenpart"); break;
4799     case blue_part:mp_print(mp, "bluepart"); break;
4800     case cyan_part:mp_print(mp, "cyanpart"); break;
4801     case magenta_part:mp_print(mp, "magentapart"); break;
4802     case yellow_part:mp_print(mp, "yellowpart"); break;
4803     case black_part:mp_print(mp, "blackpart"); break;
4804     case grey_part:mp_print(mp, "greypart"); break;
4805     case color_model_part:mp_print(mp, "colormodel"); break;
4806     case font_part:mp_print(mp, "fontpart"); break;
4807     case text_part:mp_print(mp, "textpart"); break;
4808     case path_part:mp_print(mp, "pathpart"); break;
4809     case pen_part:mp_print(mp, "penpart"); break;
4810     case dash_part:mp_print(mp, "dashpart"); break;
4811     case sqrt_op:mp_print(mp, "sqrt"); break;
4812     case m_exp_op:mp_print(mp, "mexp"); break;
4813     case m_log_op:mp_print(mp, "mlog"); break;
4814     case sin_d_op:mp_print(mp, "sind"); break;
4815     case cos_d_op:mp_print(mp, "cosd"); break;
4816     case floor_op:mp_print(mp, "floor"); break;
4817     case uniform_deviate:mp_print(mp, "uniformdeviate"); break;
4818     case char_exists_op:mp_print(mp, "charexists"); break;
4819     case font_size:mp_print(mp, "fontsize"); break;
4820     case ll_corner_op:mp_print(mp, "llcorner"); break;
4821     case lr_corner_op:mp_print(mp, "lrcorner"); break;
4822     case ul_corner_op:mp_print(mp, "ulcorner"); break;
4823     case ur_corner_op:mp_print(mp, "urcorner"); break;
4824     case arc_length:mp_print(mp, "arclength"); break;
4825     case angle_op:mp_print(mp, "angle"); break;
4826     case cycle_op:mp_print(mp, "cycle"); break;
4827     case filled_op:mp_print(mp, "filled"); break;
4828     case stroked_op:mp_print(mp, "stroked"); break;
4829     case textual_op:mp_print(mp, "textual"); break;
4830     case clipped_op:mp_print(mp, "clipped"); break;
4831     case bounded_op:mp_print(mp, "bounded"); break;
4832     case plus:mp_print_char(mp, '+'); break;
4833     case minus:mp_print_char(mp, '-'); break;
4834     case times:mp_print_char(mp, '*'); break;
4835     case over:mp_print_char(mp, '/'); break;
4836     case pythag_add:mp_print(mp, "++"); break;
4837     case pythag_sub:mp_print(mp, "+-+"); break;
4838     case or_op:mp_print(mp, "or"); break;
4839     case and_op:mp_print(mp, "and"); break;
4840     case less_than:mp_print_char(mp, '<'); break;
4841     case less_or_equal:mp_print(mp, "<="); break;
4842     case greater_than:mp_print_char(mp, '>'); break;
4843     case greater_or_equal:mp_print(mp, ">="); break;
4844     case equal_to:mp_print_char(mp, '='); break;
4845     case unequal_to:mp_print(mp, "<>"); break;
4846     case concatenate:mp_print(mp, "&"); break;
4847     case rotated_by:mp_print(mp, "rotated"); break;
4848     case slanted_by:mp_print(mp, "slanted"); break;
4849     case scaled_by:mp_print(mp, "scaled"); break;
4850     case shifted_by:mp_print(mp, "shifted"); break;
4851     case transformed_by:mp_print(mp, "transformed"); break;
4852     case x_scaled:mp_print(mp, "xscaled"); break;
4853     case y_scaled:mp_print(mp, "yscaled"); break;
4854     case z_scaled:mp_print(mp, "zscaled"); break;
4855     case in_font:mp_print(mp, "infont"); break;
4856     case intersect:mp_print(mp, "intersectiontimes"); break;
4857     case substring_of:mp_print(mp, "substring"); break;
4858     case subpath_of:mp_print(mp, "subpath"); break;
4859     case direction_time_of:mp_print(mp, "directiontime"); break;
4860     case point_of:mp_print(mp, "point"); break;
4861     case precontrol_of:mp_print(mp, "precontrol"); break;
4862     case postcontrol_of:mp_print(mp, "postcontrol"); break;
4863     case pen_offset_of:mp_print(mp, "penoffset"); break;
4864     case arc_time_of:mp_print(mp, "arctime"); break;
4865     case mp_version:mp_print(mp, "mpversion"); break;
4866     default: mp_print(mp, ".."); break;
4867     }
4868   }
4869 }
4870
4871 @ \MP\ also has a bunch of internal parameters that a user might want to
4872 fuss with. Every such parameter has an identifying code number, defined here.
4873
4874 @d tracing_titles 1 /* show titles online when they appear */
4875 @d tracing_equations 2 /* show each variable when it becomes known */
4876 @d tracing_capsules 3 /* show capsules too */
4877 @d tracing_choices 4 /* show the control points chosen for paths */
4878 @d tracing_specs 5 /* show path subdivision prior to filling with polygonal a pen */
4879 @d tracing_commands 6 /* show commands and operations before they are performed */
4880 @d tracing_restores 7 /* show when a variable or internal is restored */
4881 @d tracing_macros 8 /* show macros before they are expanded */
4882 @d tracing_output 9 /* show digitized edges as they are output */
4883 @d tracing_stats 10 /* show memory usage at end of job */
4884 @d tracing_lost_chars 11 /* show characters that aren't \&{infont} */
4885 @d tracing_online 12 /* show long diagnostics on terminal and in the log file */
4886 @d year 13 /* the current year (e.g., 1984) */
4887 @d month 14 /* the current month (e.g, 3 $\equiv$ March) */
4888 @d day 15 /* the current day of the month */
4889 @d mp_time 16 /* the number of minutes past midnight when this job started */
4890 @d char_code 17 /* the number of the next character to be output */
4891 @d char_ext 18 /* the extension code of the next character to be output */
4892 @d char_wd 19 /* the width of the next character to be output */
4893 @d char_ht 20 /* the height of the next character to be output */
4894 @d char_dp 21 /* the depth of the next character to be output */
4895 @d char_ic 22 /* the italic correction of the next character to be output */
4896 @d design_size 23 /* the unit of measure used for |char_wd..char_ic|, in points */
4897 @d pausing 24 /* positive to display lines on the terminal before they are read */
4898 @d showstopping 25 /* positive to stop after each \&{show} command */
4899 @d fontmaking 26 /* positive if font metric output is to be produced */
4900 @d linejoin 27 /* as in \ps: 0 for mitered, 1 for round, 2 for beveled */
4901 @d linecap 28 /* as in \ps: 0 for butt, 1 for round, 2 for square */
4902 @d miterlimit 29 /* controls miter length as in \ps */
4903 @d warning_check 30 /* controls error message when variable value is large */
4904 @d boundary_char 31 /* the right boundary character for ligatures */
4905 @d prologues 32 /* positive to output conforming PostScript using built-in fonts */
4906 @d true_corners 33 /* positive to make \&{llcorner} etc. ignore \&{setbounds} */
4907 @d default_color_model 34 /* the default color model for unspecified items */
4908 @d restore_clip_color 35
4909 @d mpprocset 36 /* wether or not create PostScript command shortcuts */
4910 @d gtroffmode 37 /* whether the user specified |-troff| on the command line */
4911 @d max_given_internal 37
4912
4913 @<Glob...@>=
4914 scaled *internal;  /* the values of internal quantities */
4915 char **int_name;  /* their names */
4916 int int_ptr;  /* the maximum internal quantity defined so far */
4917 int max_internal; /* current maximum number of internal quantities */
4918 boolean troff_mode; 
4919
4920 @ @<Option variables@>=
4921 boolean troff_mode; 
4922
4923 @ @<Allocate or initialize ...@>=
4924 mp->max_internal=2*max_given_internal;
4925 mp->internal = xmalloc ((mp->max_internal+1), sizeof(scaled));
4926 mp->int_name = xmalloc ((mp->max_internal+1), sizeof(char *));
4927 mp->troff_mode=(opt.troff_mode>0 ? true : false);
4928
4929 @ @<Set initial ...@>=
4930 for (k=0;k<= mp->max_internal; k++ ) { 
4931    mp->internal[k]=0; 
4932    mp->int_name[k]=NULL; 
4933 }
4934 mp->int_ptr=max_given_internal;
4935
4936 @ The symbolic names for internal quantities are put into \MP's hash table
4937 by using a routine called |primitive|, which will be defined later. Let us
4938 enter them now, so that we don't have to list all those names again
4939 anywhere else.
4940
4941 @<Put each of \MP's primitives into the hash table@>=
4942 mp_primitive(mp, "tracingtitles",internal_quantity,tracing_titles);
4943 @:tracingtitles_}{\&{tracingtitles} primitive@>
4944 mp_primitive(mp, "tracingequations",internal_quantity,tracing_equations);
4945 @:tracing_equations_}{\&{tracingequations} primitive@>
4946 mp_primitive(mp, "tracingcapsules",internal_quantity,tracing_capsules);
4947 @:tracing_capsules_}{\&{tracingcapsules} primitive@>
4948 mp_primitive(mp, "tracingchoices",internal_quantity,tracing_choices);
4949 @:tracing_choices_}{\&{tracingchoices} primitive@>
4950 mp_primitive(mp, "tracingspecs",internal_quantity,tracing_specs);
4951 @:tracing_specs_}{\&{tracingspecs} primitive@>
4952 mp_primitive(mp, "tracingcommands",internal_quantity,tracing_commands);
4953 @:tracing_commands_}{\&{tracingcommands} primitive@>
4954 mp_primitive(mp, "tracingrestores",internal_quantity,tracing_restores);
4955 @:tracing_restores_}{\&{tracingrestores} primitive@>
4956 mp_primitive(mp, "tracingmacros",internal_quantity,tracing_macros);
4957 @:tracing_macros_}{\&{tracingmacros} primitive@>
4958 mp_primitive(mp, "tracingoutput",internal_quantity,tracing_output);
4959 @:tracing_output_}{\&{tracingoutput} primitive@>
4960 mp_primitive(mp, "tracingstats",internal_quantity,tracing_stats);
4961 @:tracing_stats_}{\&{tracingstats} primitive@>
4962 mp_primitive(mp, "tracinglostchars",internal_quantity,tracing_lost_chars);
4963 @:tracing_lost_chars_}{\&{tracinglostchars} primitive@>
4964 mp_primitive(mp, "tracingonline",internal_quantity,tracing_online);
4965 @:tracing_online_}{\&{tracingonline} primitive@>
4966 mp_primitive(mp, "year",internal_quantity,year);
4967 @:year_}{\&{year} primitive@>
4968 mp_primitive(mp, "month",internal_quantity,month);
4969 @:month_}{\&{month} primitive@>
4970 mp_primitive(mp, "day",internal_quantity,day);
4971 @:day_}{\&{day} primitive@>
4972 mp_primitive(mp, "time",internal_quantity,mp_time);
4973 @:time_}{\&{time} primitive@>
4974 mp_primitive(mp, "charcode",internal_quantity,char_code);
4975 @:char_code_}{\&{charcode} primitive@>
4976 mp_primitive(mp, "charext",internal_quantity,char_ext);
4977 @:char_ext_}{\&{charext} primitive@>
4978 mp_primitive(mp, "charwd",internal_quantity,char_wd);
4979 @:char_wd_}{\&{charwd} primitive@>
4980 mp_primitive(mp, "charht",internal_quantity,char_ht);
4981 @:char_ht_}{\&{charht} primitive@>
4982 mp_primitive(mp, "chardp",internal_quantity,char_dp);
4983 @:char_dp_}{\&{chardp} primitive@>
4984 mp_primitive(mp, "charic",internal_quantity,char_ic);
4985 @:char_ic_}{\&{charic} primitive@>
4986 mp_primitive(mp, "designsize",internal_quantity,design_size);
4987 @:design_size_}{\&{designsize} primitive@>
4988 mp_primitive(mp, "pausing",internal_quantity,pausing);
4989 @:pausing_}{\&{pausing} primitive@>
4990 mp_primitive(mp, "showstopping",internal_quantity,showstopping);
4991 @:showstopping_}{\&{showstopping} primitive@>
4992 mp_primitive(mp, "fontmaking",internal_quantity,fontmaking);
4993 @:fontmaking_}{\&{fontmaking} primitive@>
4994 mp_primitive(mp, "linejoin",internal_quantity,linejoin);
4995 @:linejoin_}{\&{linejoin} primitive@>
4996 mp_primitive(mp, "linecap",internal_quantity,linecap);
4997 @:linecap_}{\&{linecap} primitive@>
4998 mp_primitive(mp, "miterlimit",internal_quantity,miterlimit);
4999 @:miterlimit_}{\&{miterlimit} primitive@>
5000 mp_primitive(mp, "warningcheck",internal_quantity,warning_check);
5001 @:warning_check_}{\&{warningcheck} primitive@>
5002 mp_primitive(mp, "boundarychar",internal_quantity,boundary_char);
5003 @:boundary_char_}{\&{boundarychar} primitive@>
5004 mp_primitive(mp, "prologues",internal_quantity,prologues);
5005 @:prologues_}{\&{prologues} primitive@>
5006 mp_primitive(mp, "truecorners",internal_quantity,true_corners);
5007 @:true_corners_}{\&{truecorners} primitive@>
5008 mp_primitive(mp, "mpprocset",internal_quantity,mpprocset);
5009 @:mpprocset_}{\&{mpprocset} primitive@>
5010 mp_primitive(mp, "troffmode",internal_quantity,gtroffmode);
5011 @:troffmode_}{\&{troffmode} primitive@>
5012 mp_primitive(mp, "defaultcolormodel",internal_quantity,default_color_model);
5013 @:default_color_model_}{\&{defaultcolormodel} primitive@>
5014 mp_primitive(mp, "restoreclipcolor",internal_quantity,restore_clip_color);
5015 @:restore_clip_color_}{\&{restoreclipcolor} primitive@>
5016
5017 @ Colors can be specified in four color models. In the special
5018 case of |no_model|, MetaPost does not output any color operator to
5019 the postscript output.
5020
5021 Note: these values are passed directly on to |with_option|. This only
5022 works because the other possible values passed to |with_option| are
5023 8 and 10 respectively (from |with_pen| and |with_picture|).
5024
5025 There is a first state, that is only used for |gs_colormodel|. It flags
5026 the fact that there has not been any kind of color specification by
5027 the user so far in the game.
5028
5029 @d no_model 1
5030 @d grey_model 3
5031 @d rgb_model 5
5032 @d cmyk_model 7
5033 @d uninitialized_model 9
5034
5035 @<Initialize table entries (done by \.{INIMP} only)@>=
5036 mp->internal[default_color_model]=(rgb_model*unity);
5037 mp->internal[restore_clip_color]=unity;
5038
5039 @ Well, we do have to list the names one more time, for use in symbolic
5040 printouts.
5041
5042 @<Initialize table...@>=
5043 mp->int_name[tracing_titles]=xstrdup("tracingtitles");
5044 mp->int_name[tracing_equations]=xstrdup("tracingequations");
5045 mp->int_name[tracing_capsules]=xstrdup("tracingcapsules");
5046 mp->int_name[tracing_choices]=xstrdup("tracingchoices");
5047 mp->int_name[tracing_specs]=xstrdup("tracingspecs");
5048 mp->int_name[tracing_commands]=xstrdup("tracingcommands");
5049 mp->int_name[tracing_restores]=xstrdup("tracingrestores");
5050 mp->int_name[tracing_macros]=xstrdup("tracingmacros");
5051 mp->int_name[tracing_output]=xstrdup("tracingoutput");
5052 mp->int_name[tracing_stats]=xstrdup("tracingstats");
5053 mp->int_name[tracing_lost_chars]=xstrdup("tracinglostchars");
5054 mp->int_name[tracing_online]=xstrdup("tracingonline");
5055 mp->int_name[year]=xstrdup("year");
5056 mp->int_name[month]=xstrdup("month");
5057 mp->int_name[day]=xstrdup("day");
5058 mp->int_name[mp_time]=xstrdup("time");
5059 mp->int_name[char_code]=xstrdup("charcode");
5060 mp->int_name[char_ext]=xstrdup("charext");
5061 mp->int_name[char_wd]=xstrdup("charwd");
5062 mp->int_name[char_ht]=xstrdup("charht");
5063 mp->int_name[char_dp]=xstrdup("chardp");
5064 mp->int_name[char_ic]=xstrdup("charic");
5065 mp->int_name[design_size]=xstrdup("designsize");
5066 mp->int_name[pausing]=xstrdup("pausing");
5067 mp->int_name[showstopping]=xstrdup("showstopping");
5068 mp->int_name[fontmaking]=xstrdup("fontmaking");
5069 mp->int_name[linejoin]=xstrdup("linejoin");
5070 mp->int_name[linecap]=xstrdup("linecap");
5071 mp->int_name[miterlimit]=xstrdup("miterlimit");
5072 mp->int_name[warning_check]=xstrdup("warningcheck");
5073 mp->int_name[boundary_char]=xstrdup("boundarychar");
5074 mp->int_name[prologues]=xstrdup("prologues");
5075 mp->int_name[true_corners]=xstrdup("truecorners");
5076 mp->int_name[default_color_model]=xstrdup("defaultcolormodel");
5077 mp->int_name[mpprocset]=xstrdup("mpprocset");
5078 mp->int_name[gtroffmode]=xstrdup("troffmode");
5079 mp->int_name[restore_clip_color]=xstrdup("restoreclipcolor");
5080
5081 @ The following procedure, which is called just before \MP\ initializes its
5082 input and output, establishes the initial values of the date and time.
5083 @^system dependencies@>
5084
5085 Note that the values are |scaled| integers. Hence \MP\ can no longer
5086 be used after the year 32767.
5087
5088 @c 
5089 void mp_fix_date_and_time (MP mp) { 
5090   time_t clock = time ((time_t *) 0);
5091   struct tm *tmptr = localtime (&clock);
5092   mp->internal[mp_time]=
5093       (tmptr->tm_hour*60+tmptr->tm_min)*unity; /* minutes since midnight */
5094   mp->internal[day]=(tmptr->tm_mday)*unity; /* fourth day of the month */
5095   mp->internal[month]=(tmptr->tm_mon+1)*unity; /* seventh month of the year */
5096   mp->internal[year]=(tmptr->tm_year+1900)*unity; /* Anno Domini */
5097 }
5098
5099 @ @<Declarations@>=
5100 void mp_fix_date_and_time (MP mp) ;
5101
5102 @ \MP\ is occasionally supposed to print diagnostic information that
5103 goes only into the transcript file, unless |tracing_online| is positive.
5104 Now that we have defined |tracing_online| we can define
5105 two routines that adjust the destination of print commands:
5106
5107 @<Declarations@>=
5108 void mp_begin_diagnostic (MP mp) ;
5109 void mp_end_diagnostic (MP mp,boolean blank_line);
5110 void mp_print_diagnostic (MP mp, char *s, char *t, boolean nuline) ;
5111
5112 @ @<Basic printing...@>=
5113 @<Declare a function called |true_line|@>;
5114 void mp_begin_diagnostic (MP mp) { /* prepare to do some tracing */
5115   mp->old_setting=mp->selector;
5116   if ( mp->selector==ps_file_only ) mp->selector=mp->non_ps_setting;
5117   if ((mp->internal[tracing_online]<=0)&&(mp->selector==term_and_log)){ 
5118     decr(mp->selector);
5119     if ( mp->history==spotless ) mp->history=warning_issued;
5120   }
5121 }
5122 @#
5123 void mp_end_diagnostic (MP mp,boolean blank_line) {
5124   /* restore proper conditions after tracing */
5125   mp_print_nl(mp, "");
5126   if ( blank_line ) mp_print_ln(mp);
5127   mp->selector=mp->old_setting;
5128 }
5129
5130 @ The global variable |non_ps_setting| is initialized when it is time to print
5131 on |ps_file|.
5132
5133 @<Glob...@>=
5134 unsigned int old_setting;
5135 unsigned int non_ps_setting;
5136
5137 @ We will occasionally use |begin_diagnostic| in connection with line-number
5138 printing, as follows. (The parameter |s| is typically |"Path"| or
5139 |"Cycle spec"|, etc.)
5140
5141 @<Basic printing...@>=
5142 void mp_print_diagnostic (MP mp, char *s, char *t, boolean nuline) { 
5143   mp_begin_diagnostic(mp);
5144   if ( nuline ) mp_print_nl(mp, s); else mp_print(mp, s);
5145   mp_print(mp, " at line "); 
5146   mp_print_int(mp, mp_true_line(mp));
5147   mp_print(mp, t); mp_print_char(mp, ':');
5148 }
5149
5150 @ The 256 |ASCII_code| characters are grouped into classes by means of
5151 the |char_class| table. Individual class numbers have no semantic
5152 or syntactic significance, except in a few instances defined here.
5153 There's also |max_class|, which can be used as a basis for additional
5154 class numbers in nonstandard extensions of \MP.
5155
5156 @d digit_class 0 /* the class number of \.{0123456789} */
5157 @d period_class 1 /* the class number of `\..' */
5158 @d space_class 2 /* the class number of spaces and nonstandard characters */
5159 @d percent_class 3 /* the class number of `\.\%' */
5160 @d string_class 4 /* the class number of `\."' */
5161 @d right_paren_class 8 /* the class number of `\.)' */
5162 @d isolated_classes 5: case 6: case 7: case 8 /* characters that make length-one tokens only */
5163 @d letter_class 9 /* letters and the underline character */
5164 @d left_bracket_class 17 /* `\.[' */
5165 @d right_bracket_class 18 /* `\.]' */
5166 @d invalid_class 20 /* bad character in the input */
5167 @d max_class 20 /* the largest class number */
5168
5169 @<Glob...@>=
5170 int char_class[256]; /* the class numbers */
5171
5172 @ If changes are made to accommodate non-ASCII character sets, they should
5173 follow the guidelines in Appendix~C of {\sl The {\logos METAFONT\/}book}.
5174 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
5175 @^system dependencies@>
5176
5177 @<Set initial ...@>=
5178 for (k='0';k<='9';k++) 
5179   mp->char_class[k]=digit_class;
5180 mp->char_class['.']=period_class;
5181 mp->char_class[' ']=space_class;
5182 mp->char_class['%']=percent_class;
5183 mp->char_class['"']=string_class;
5184 mp->char_class[',']=5;
5185 mp->char_class[';']=6;
5186 mp->char_class['(']=7;
5187 mp->char_class[')']=right_paren_class;
5188 for (k='A';k<= 'Z';k++ )
5189   mp->char_class[k]=letter_class;
5190 for (k='a';k<='z';k++) 
5191   mp->char_class[k]=letter_class;
5192 mp->char_class['_']=letter_class;
5193 mp->char_class['<']=10;
5194 mp->char_class['=']=10;
5195 mp->char_class['>']=10;
5196 mp->char_class[':']=10;
5197 mp->char_class['|']=10;
5198 mp->char_class['`']=11;
5199 mp->char_class['\'']=11;
5200 mp->char_class['+']=12;
5201 mp->char_class['-']=12;
5202 mp->char_class['/']=13;
5203 mp->char_class['*']=13;
5204 mp->char_class['\\']=13;
5205 mp->char_class['!']=14;
5206 mp->char_class['?']=14;
5207 mp->char_class['#']=15;
5208 mp->char_class['&']=15;
5209 mp->char_class['@@']=15;
5210 mp->char_class['$']=15;
5211 mp->char_class['^']=16;
5212 mp->char_class['~']=16;
5213 mp->char_class['[']=left_bracket_class;
5214 mp->char_class[']']=right_bracket_class;
5215 mp->char_class['{']=19;
5216 mp->char_class['}']=19;
5217 for (k=0;k<' ';k++)
5218   mp->char_class[k]=invalid_class;
5219 mp->char_class['\t']=space_class;
5220 mp->char_class['\f']=space_class;
5221 for (k=127;k<=255;k++)
5222   mp->char_class[k]=invalid_class;
5223
5224 @* \[13] The hash table.
5225 Symbolic tokens are stored and retrieved by means of a fairly standard hash
5226 table algorithm called the method of ``coalescing lists'' (cf.\ Algorithm 6.4C
5227 in {\sl The Art of Computer Programming\/}). Once a symbolic token enters the
5228 table, it is never removed.
5229
5230 The actual sequence of characters forming a symbolic token is
5231 stored in the |str_pool| array together with all the other strings. An
5232 auxiliary array |hash| consists of items with two halfword fields per
5233 word. The first of these, called |next(p)|, points to the next identifier
5234 belonging to the same coalesced list as the identifier corresponding to~|p|;
5235 and the other, called |text(p)|, points to the |str_start| entry for
5236 |p|'s identifier. If position~|p| of the hash table is empty, we have
5237 |text(p)=0|; if position |p| is either empty or the end of a coalesced
5238 hash list, we have |next(p)=0|.
5239
5240 An auxiliary pointer variable called |hash_used| is maintained in such a
5241 way that all locations |p>=hash_used| are nonempty. The global variable
5242 |st_count| tells how many symbolic tokens have been defined, if statistics
5243 are being kept.
5244
5245 The first 256 locations of |hash| are reserved for symbols of length one.
5246
5247 There's a parallel array called |eqtb| that contains the current equivalent
5248 values of each symbolic token. The entries of this array consist of
5249 two halfwords called |eq_type| (a command code) and |equiv| (a secondary
5250 piece of information that qualifies the |eq_type|).
5251
5252 @d next(A)   mp->hash[(A)].lh /* link for coalesced lists */
5253 @d text(A)   mp->hash[(A)].rh /* string number for symbolic token name */
5254 @d eq_type(A)   mp->eqtb[(A)].lh /* the current ``meaning'' of a symbolic token */
5255 @d equiv(A)   mp->eqtb[(A)].rh /* parametric part of a token's meaning */
5256 @d hash_base 257 /* hashing actually starts here */
5257 @d hash_is_full   (mp->hash_used==hash_base) /* are all positions occupied? */
5258
5259 @<Glob...@>=
5260 pointer hash_used; /* allocation pointer for |hash| */
5261 integer st_count; /* total number of known identifiers */
5262
5263 @ Certain entries in the hash table are ``frozen'' and not redefinable,
5264 since they are used in error recovery.
5265
5266 @d hash_top (hash_base+mp->hash_size) /* the first location of the frozen area */
5267 @d frozen_inaccessible hash_top /* |hash| location to protect the frozen area */
5268 @d frozen_repeat_loop (hash_top+1) /* |hash| location of a loop-repeat token */
5269 @d frozen_right_delimiter (hash_top+2) /* |hash| location of a permanent `\.)' */
5270 @d frozen_left_bracket (hash_top+3) /* |hash| location of a permanent `\.[' */
5271 @d frozen_slash (hash_top+4) /* |hash| location of a permanent `\./' */
5272 @d frozen_colon (hash_top+5) /* |hash| location of a permanent `\.:' */
5273 @d frozen_semicolon (hash_top+6) /* |hash| location of a permanent `\.;' */
5274 @d frozen_end_for (hash_top+7) /* |hash| location of a permanent \&{endfor} */
5275 @d frozen_end_def (hash_top+8) /* |hash| location of a permanent \&{enddef} */
5276 @d frozen_fi (hash_top+9) /* |hash| location of a permanent \&{fi} */
5277 @d frozen_end_group (hash_top+10) /* |hash| location of a permanent `\.{endgroup}' */
5278 @d frozen_etex (hash_top+11) /* |hash| location of a permanent \&{etex} */
5279 @d frozen_mpx_break (hash_top+12) /* |hash| location of a permanent \&{mpxbreak} */
5280 @d frozen_bad_vardef (hash_top+13) /* |hash| location of `\.{a bad variable}' */
5281 @d frozen_undefined (hash_top+14) /* |hash| location that never gets defined */
5282 @d hash_end (hash_top+14) /* the actual size of the |hash| and |eqtb| arrays */
5283
5284 @<Glob...@>=
5285 two_halves *hash; /* the hash table */
5286 two_halves *eqtb; /* the equivalents */
5287
5288 @ @<Allocate or initialize ...@>=
5289 mp->hash = xmalloc((hash_end+1),sizeof(two_halves));
5290 mp->eqtb = xmalloc((hash_end+1),sizeof(two_halves));
5291
5292 @ @<Dealloc variables@>=
5293 xfree(mp->hash);
5294 xfree(mp->eqtb);
5295
5296 @ @<Set init...@>=
5297 next(1)=0; text(1)=0; eq_type(1)=tag_token; equiv(1)=null;
5298 for (k=2;k<=hash_end;k++)  { 
5299   mp->hash[k]=mp->hash[1]; mp->eqtb[k]=mp->eqtb[1];
5300 }
5301
5302 @ @<Initialize table entries...@>=
5303 mp->hash_used=frozen_inaccessible; /* nothing is used */
5304 mp->st_count=0;
5305 text(frozen_bad_vardef)=intern("a bad variable");
5306 text(frozen_etex)=intern("etex");
5307 text(frozen_mpx_break)=intern("mpxbreak");
5308 text(frozen_fi)=intern("fi");
5309 text(frozen_end_group)=intern("endgroup");
5310 text(frozen_end_def)=intern("enddef");
5311 text(frozen_end_for)=intern("endfor");
5312 text(frozen_semicolon)=intern(";");
5313 text(frozen_colon)=intern(":");
5314 text(frozen_slash)=intern("/");
5315 text(frozen_left_bracket)=intern("[");
5316 text(frozen_right_delimiter)=intern(")");
5317 text(frozen_inaccessible)=intern(" INACCESSIBLE");
5318 eq_type(frozen_right_delimiter)=right_delimiter;
5319
5320 @ @<Check the ``constant'' values...@>=
5321 if ( hash_end+mp->max_internal>max_halfword ) mp->bad=17;
5322
5323 @ Here is the subroutine that searches the hash table for an identifier
5324 that matches a given string of length~|l| appearing in |buffer[j..
5325 (j+l-1)]|. If the identifier is not found, it is inserted; hence it
5326 will always be found, and the corresponding hash table address
5327 will be returned.
5328
5329 @c 
5330 pointer mp_id_lookup (MP mp,integer j, integer l) { /* search the hash table */
5331   integer h; /* hash code */
5332   pointer p; /* index in |hash| array */
5333   pointer k; /* index in |buffer| array */
5334   if (l==1) {
5335     @<Treat special case of length 1 and |break|@>;
5336   }
5337   @<Compute the hash code |h|@>;
5338   p=h+hash_base; /* we start searching here; note that |0<=h<hash_prime| */
5339   while (true)  { 
5340         if (text(p)>0 && length(text(p))==l && mp_str_eq_buf(mp, text(p),j)) 
5341       break;
5342     if ( next(p)==0 ) {
5343       @<Insert a new symbolic token after |p|, then
5344         make |p| point to it and |break|@>;
5345     }
5346     p=next(p);
5347   }
5348   return p;
5349 };
5350
5351 @ @<Treat special case of length 1...@>=
5352  p=mp->buffer[j]+1; text(p)=p-1; return p;
5353
5354
5355 @ @<Insert a new symbolic...@>=
5356 {
5357 if ( text(p)>0 ) { 
5358   do {  
5359     if ( hash_is_full )
5360       mp_overflow(mp, "hash size",mp->hash_size);
5361 @:MetaPost capacity exceeded hash size}{\quad hash size@>
5362     decr(mp->hash_used);
5363   } while (text(mp->hash_used)!=0); /* search for an empty location in |hash| */
5364   next(p)=mp->hash_used; 
5365   p=mp->hash_used;
5366 }
5367 str_room(l);
5368 for (k=j;k<=j+l-1;k++) {
5369   append_char(mp->buffer[k]);
5370 }
5371 text(p)=mp_make_string(mp); 
5372 mp->str_ref[text(p)]=max_str_ref;
5373 incr(mp->st_count);
5374 break;
5375 }
5376
5377
5378 @ The value of |hash_prime| should be roughly 85\pct! of |hash_size|, and it
5379 should be a prime number.  The theory of hashing tells us to expect fewer
5380 than two table probes, on the average, when the search is successful.
5381 [See J.~S. Vitter, {\sl Journal of the ACM\/ \bf30} (1983), 231--258.]
5382 @^Vitter, Jeffrey Scott@>
5383
5384 @<Compute the hash code |h|@>=
5385 h=mp->buffer[j];
5386 for (k=j+1;k<=j+l-1;k++){ 
5387   h=h+h+mp->buffer[k];
5388   while ( h>=mp->hash_prime ) h=h-mp->hash_prime;
5389 }
5390
5391 @ @<Search |eqtb| for equivalents equal to |p|@>=
5392 for (q=1;q<=hash_end;q++) { 
5393   if ( equiv(q)==p ) { 
5394     mp_print_nl(mp, "EQUIV("); 
5395     mp_print_int(mp, q); 
5396     mp_print_char(mp, ')');
5397   }
5398 }
5399
5400 @ We need to put \MP's ``primitive'' symbolic tokens into the hash
5401 table, together with their command code (which will be the |eq_type|)
5402 and an operand (which will be the |equiv|). The |primitive| procedure
5403 does this, in a way that no \MP\ user can. The global value |cur_sym|
5404 contains the new |eqtb| pointer after |primitive| has acted.
5405
5406 @c 
5407 void mp_primitive (MP mp, char *ss, halfword c, halfword o) {
5408   pool_pointer k; /* index into |str_pool| */
5409   small_number j; /* index into |buffer| */
5410   small_number l; /* length of the string */
5411   str_number s;
5412   s = intern(ss);
5413   k=mp->str_start[s]; l=str_stop(s)-k;
5414   /* we will move |s| into the (empty) |buffer| */
5415   for (j=0;j<=l-1;j++) {
5416     mp->buffer[j]=mp->str_pool[k+j];
5417   }
5418   mp->cur_sym=mp_id_lookup(mp, 0,l);
5419   if ( s>=256 ) { /* we don't want to have the string twice */
5420     mp_flush_string(mp, text(mp->cur_sym)); text(mp->cur_sym)=s;
5421   };
5422   eq_type(mp->cur_sym)=c; 
5423   equiv(mp->cur_sym)=o;
5424 }
5425
5426
5427 @ Many of \MP's primitives need no |equiv|, since they are identifiable
5428 by their |eq_type| alone. These primitives are loaded into the hash table
5429 as follows:
5430
5431 @<Put each of \MP's primitives into the hash table@>=
5432 mp_primitive(mp, "..",path_join,0);
5433 @:.._}{\.{..} primitive@>
5434 mp_primitive(mp, "[",left_bracket,0); mp->eqtb[frozen_left_bracket]=mp->eqtb[mp->cur_sym];
5435 @:[ }{\.{[} primitive@>
5436 mp_primitive(mp, "]",right_bracket,0);
5437 @:] }{\.{]} primitive@>
5438 mp_primitive(mp, "}",right_brace,0);
5439 @:]]}{\.{\char`\}} primitive@>
5440 mp_primitive(mp, "{",left_brace,0);
5441 @:][}{\.{\char`\{} primitive@>
5442 mp_primitive(mp, ":",colon,0); mp->eqtb[frozen_colon]=mp->eqtb[mp->cur_sym];
5443 @:: }{\.{:} primitive@>
5444 mp_primitive(mp, "::",double_colon,0);
5445 @::: }{\.{::} primitive@>
5446 mp_primitive(mp, "||:",bchar_label,0);
5447 @:::: }{\.{\char'174\char'174:} primitive@>
5448 mp_primitive(mp, ":=",assignment,0);
5449 @::=_}{\.{:=} primitive@>
5450 mp_primitive(mp, ",",comma,0);
5451 @:, }{\., primitive@>
5452 mp_primitive(mp, ";",semicolon,0); mp->eqtb[frozen_semicolon]=mp->eqtb[mp->cur_sym];
5453 @:; }{\.; primitive@>
5454 mp_primitive(mp, "\\",relax,0);
5455 @:]]\\}{\.{\char`\\} primitive@>
5456 @#
5457 mp_primitive(mp, "addto",add_to_command,0);
5458 @:add_to_}{\&{addto} primitive@>
5459 mp_primitive(mp, "atleast",at_least,0);
5460 @:at_least_}{\&{atleast} primitive@>
5461 mp_primitive(mp, "begingroup",begin_group,0); mp->bg_loc=mp->cur_sym;
5462 @:begin_group_}{\&{begingroup} primitive@>
5463 mp_primitive(mp, "controls",controls,0);
5464 @:controls_}{\&{controls} primitive@>
5465 mp_primitive(mp, "curl",curl_command,0);
5466 @:curl_}{\&{curl} primitive@>
5467 mp_primitive(mp, "delimiters",delimiters,0);
5468 @:delimiters_}{\&{delimiters} primitive@>
5469 mp_primitive(mp, "endgroup",end_group,0);
5470  mp->eqtb[frozen_end_group]=mp->eqtb[mp->cur_sym]; mp->eg_loc=mp->cur_sym;
5471 @:endgroup_}{\&{endgroup} primitive@>
5472 mp_primitive(mp, "everyjob",every_job_command,0);
5473 @:every_job_}{\&{everyjob} primitive@>
5474 mp_primitive(mp, "exitif",exit_test,0);
5475 @:exit_if_}{\&{exitif} primitive@>
5476 mp_primitive(mp, "expandafter",expand_after,0);
5477 @:expand_after_}{\&{expandafter} primitive@>
5478 mp_primitive(mp, "interim",interim_command,0);
5479 @:interim_}{\&{interim} primitive@>
5480 mp_primitive(mp, "let",let_command,0);
5481 @:let_}{\&{let} primitive@>
5482 mp_primitive(mp, "newinternal",new_internal,0);
5483 @:new_internal_}{\&{newinternal} primitive@>
5484 mp_primitive(mp, "of",of_token,0);
5485 @:of_}{\&{of} primitive@>
5486 mp_primitive(mp, "randomseed",random_seed,0);
5487 @:random_seed_}{\&{randomseed} primitive@>
5488 mp_primitive(mp, "save",save_command,0);
5489 @:save_}{\&{save} primitive@>
5490 mp_primitive(mp, "scantokens",scan_tokens,0);
5491 @:scan_tokens_}{\&{scantokens} primitive@>
5492 mp_primitive(mp, "shipout",ship_out_command,0);
5493 @:ship_out_}{\&{shipout} primitive@>
5494 mp_primitive(mp, "skipto",skip_to,0);
5495 @:skip_to_}{\&{skipto} primitive@>
5496 mp_primitive(mp, "special",special_command,0);
5497 @:special}{\&{special} primitive@>
5498 mp_primitive(mp, "fontmapfile",special_command,1);
5499 @:fontmapfile}{\&{fontmapfile} primitive@>
5500 mp_primitive(mp, "fontmapline",special_command,2);
5501 @:fontmapline}{\&{fontmapline} primitive@>
5502 mp_primitive(mp, "step",step_token,0);
5503 @:step_}{\&{step} primitive@>
5504 mp_primitive(mp, "str",str_op,0);
5505 @:str_}{\&{str} primitive@>
5506 mp_primitive(mp, "tension",tension,0);
5507 @:tension_}{\&{tension} primitive@>
5508 mp_primitive(mp, "to",to_token,0);
5509 @:to_}{\&{to} primitive@>
5510 mp_primitive(mp, "until",until_token,0);
5511 @:until_}{\&{until} primitive@>
5512 mp_primitive(mp, "within",within_token,0);
5513 @:within_}{\&{within} primitive@>
5514 mp_primitive(mp, "write",write_command,0);
5515 @:write_}{\&{write} primitive@>
5516
5517 @ Each primitive has a corresponding inverse, so that it is possible to
5518 display the cryptic numeric contents of |eqtb| in symbolic form.
5519 Every call of |primitive| in this program is therefore accompanied by some
5520 straightforward code that forms part of the |print_cmd_mod| routine
5521 explained below.
5522
5523 @<Cases of |print_cmd_mod| for symbolic printing of primitives@>=
5524 case add_to_command:mp_print(mp, "addto"); break;
5525 case assignment:mp_print(mp, ":="); break;
5526 case at_least:mp_print(mp, "atleast"); break;
5527 case bchar_label:mp_print(mp, "||:"); break;
5528 case begin_group:mp_print(mp, "begingroup"); break;
5529 case colon:mp_print(mp, ":"); break;
5530 case comma:mp_print(mp, ","); break;
5531 case controls:mp_print(mp, "controls"); break;
5532 case curl_command:mp_print(mp, "curl"); break;
5533 case delimiters:mp_print(mp, "delimiters"); break;
5534 case double_colon:mp_print(mp, "::"); break;
5535 case end_group:mp_print(mp, "endgroup"); break;
5536 case every_job_command:mp_print(mp, "everyjob"); break;
5537 case exit_test:mp_print(mp, "exitif"); break;
5538 case expand_after:mp_print(mp, "expandafter"); break;
5539 case interim_command:mp_print(mp, "interim"); break;
5540 case left_brace:mp_print(mp, "{"); break;
5541 case left_bracket:mp_print(mp, "["); break;
5542 case let_command:mp_print(mp, "let"); break;
5543 case new_internal:mp_print(mp, "newinternal"); break;
5544 case of_token:mp_print(mp, "of"); break;
5545 case path_join:mp_print(mp, ".."); break;
5546 case random_seed:mp_print(mp, "randomseed"); break;
5547 case relax:mp_print_char(mp, '\\'); break;
5548 case right_brace:mp_print(mp, "}"); break;
5549 case right_bracket:mp_print(mp, "]"); break;
5550 case save_command:mp_print(mp, "save"); break;
5551 case scan_tokens:mp_print(mp, "scantokens"); break;
5552 case semicolon:mp_print(mp, ";"); break;
5553 case ship_out_command:mp_print(mp, "shipout"); break;
5554 case skip_to:mp_print(mp, "skipto"); break;
5555 case special_command: if ( m==2 ) mp_print(mp, "fontmapline"); else
5556                  if ( m==1 ) mp_print(mp, "fontmapfile"); else
5557                  mp_print(mp, "special"); break;
5558 case step_token:mp_print(mp, "step"); break;
5559 case str_op:mp_print(mp, "str"); break;
5560 case tension:mp_print(mp, "tension"); break;
5561 case to_token:mp_print(mp, "to"); break;
5562 case until_token:mp_print(mp, "until"); break;
5563 case within_token:mp_print(mp, "within"); break;
5564 case write_command:mp_print(mp, "write"); break;
5565
5566 @ We will deal with the other primitives later, at some point in the program
5567 where their |eq_type| and |equiv| values are more meaningful.  For example,
5568 the primitives for macro definitions will be loaded when we consider the
5569 routines that define macros.
5570 It is easy to find where each particular
5571 primitive was treated by looking in the index at the end; for example, the
5572 section where |"def"| entered |eqtb| is listed under `\&{def} primitive'.
5573
5574 @* \[14] Token lists.
5575 A \MP\ token is either symbolic or numeric or a string, or it denotes
5576 a macro parameter or capsule; so there are five corresponding ways to encode it
5577 @^token@>
5578 internally: (1)~A symbolic token whose hash code is~|p|
5579 is represented by the number |p|, in the |info| field of a single-word
5580 node in~|mem|. (2)~A numeric token whose |scaled| value is~|v| is
5581 represented in a two-word node of~|mem|; the |type| field is |known|,
5582 the |name_type| field is |token|, and the |value| field holds~|v|.
5583 The fact that this token appears in a two-word node rather than a
5584 one-word node is, of course, clear from the node address.
5585 (3)~A string token is also represented in a two-word node; the |type|
5586 field is |mp_string_type|, the |name_type| field is |token|, and the
5587 |value| field holds the corresponding |str_number|.  (4)~Capsules have
5588 |name_type=capsule|, and their |type| and |value| fields represent
5589 arbitrary values (in ways to be explained later).  (5)~Macro parameters
5590 are like symbolic tokens in that they appear in |info| fields of
5591 one-word nodes. The $k$th parameter is represented by |expr_base+k| if it
5592 is of type \&{expr}, or by |suffix_base+k| if it is of type \&{suffix}, or
5593 by |text_base+k| if it is of type \&{text}.  (Here |0<=k<param_size|.)
5594 Actual values of these parameters are kept in a separate stack, as we will
5595 see later.  The constants |expr_base|, |suffix_base|, and |text_base| are,
5596 of course, chosen so that there will be no confusion between symbolic
5597 tokens and parameters of various types.
5598
5599 Note that
5600 the `\\{type}' field of a node has nothing to do with ``type'' in a
5601 printer's sense. It's curious that the same word is used in such different ways.
5602
5603 @d type(A)   mp->mem[(A)].hh.b0 /* identifies what kind of value this is */
5604 @d name_type(A)   mp->mem[(A)].hh.b1 /* a clue to the name of this value */
5605 @d token_node_size 2 /* the number of words in a large token node */
5606 @d value_loc(A) ((A)+1) /* the word that contains the |value| field */
5607 @d value(A) mp->mem[value_loc((A))].cint /* the value stored in a large token node */
5608 @d expr_base (hash_end+1) /* code for the zeroth \&{expr} parameter */
5609 @d suffix_base (expr_base+mp->param_size) /* code for the zeroth \&{suffix} parameter */
5610 @d text_base (suffix_base+mp->param_size) /* code for the zeroth \&{text} parameter */
5611
5612 @<Check the ``constant''...@>=
5613 if ( text_base+mp->param_size>max_halfword ) mp->bad=18;
5614
5615 @ We have set aside a two word node beginning at |null| so that we can have
5616 |value(null)=0|.  We will make use of this coincidence later.
5617
5618 @<Initialize table entries...@>=
5619 link(null)=null; value(null)=0;
5620
5621 @ A numeric token is created by the following trivial routine.
5622
5623 @c 
5624 pointer mp_new_num_tok (MP mp,scaled v) {
5625   pointer p; /* the new node */
5626   p=mp_get_node(mp, token_node_size); value(p)=v;
5627   type(p)=mp_known; name_type(p)=mp_token; 
5628   return p;
5629 }
5630
5631 @ A token list is a singly linked list of nodes in |mem|, where
5632 each node contains a token and a link.  Here's a subroutine that gets rid
5633 of a token list when it is no longer needed.
5634
5635 @<Declarations@>=
5636 void mp_token_recycle (MP mp);
5637
5638
5639 @c void mp_flush_token_list (MP mp,pointer p) {
5640   pointer q; /* the node being recycled */
5641   while ( p!=null ) { 
5642     q=p; p=link(p);
5643     if ( q>=mp->hi_mem_min ) {
5644      free_avail(q);
5645     } else { 
5646       switch (type(q)) {
5647       case mp_vacuous: case mp_boolean_type: case mp_known:
5648         break;
5649       case mp_string_type:
5650         delete_str_ref(value(q));
5651         break;
5652       case unknown_types: case mp_pen_type: case mp_path_type: 
5653       case mp_picture_type: case mp_pair_type: case mp_color_type:
5654       case mp_cmykcolor_type: case mp_transform_type: case mp_dependent:
5655       case mp_proto_dependent: case mp_independent:
5656         mp->g_pointer=q; mp_token_recycle(mp);
5657         break;
5658       default: mp_confusion(mp, "token");
5659 @:this can't happen token}{\quad token@>
5660       }
5661       mp_free_node(mp, q,token_node_size);
5662     }
5663   }
5664 }
5665
5666 @ The procedure |show_token_list|, which prints a symbolic form of
5667 the token list that starts at a given node |p|, illustrates these
5668 conventions. The token list being displayed should not begin with a reference
5669 count. However, the procedure is intended to be fairly robust, so that if the
5670 memory links are awry or if |p| is not really a pointer to a token list,
5671 almost nothing catastrophic can happen.
5672
5673 An additional parameter |q| is also given; this parameter is either null
5674 or it points to a node in the token list where a certain magic computation
5675 takes place that will be explained later. (Basically, |q| is non-null when
5676 we are printing the two-line context information at the time of an error
5677 message; |q| marks the place corresponding to where the second line
5678 should begin.)
5679
5680 The generation will stop, and `\.{\char`\ ETC.}' will be printed, if the length
5681 of printing exceeds a given limit~|l|; the length of printing upon entry is
5682 assumed to be a given amount called |null_tally|. (Note that
5683 |show_token_list| sometimes uses itself recursively to print
5684 variable names within a capsule.)
5685 @^recursion@>
5686
5687 Unusual entries are printed in the form of all-caps tokens
5688 preceded by a space, e.g., `\.{\char`\ BAD}'.
5689
5690 @<Declarations@>=
5691 void mp_print_capsule (MP mp);
5692
5693 @ @<Declare the procedure called |show_token_list|@>=
5694 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5695                          integer null_tally) ;
5696
5697 @ @c
5698 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5699                          integer null_tally) {
5700   small_number class,c; /* the |char_class| of previous and new tokens */
5701   integer r,v; /* temporary registers */
5702   class=percent_class;
5703   mp->tally=null_tally;
5704   while ( (p!=null) && (mp->tally<l) ) { 
5705     if ( p==q ) 
5706       @<Do magic computation@>;
5707     @<Display token |p| and set |c| to its class;
5708       but |return| if there are problems@>;
5709     class=c; p=link(p);
5710   }
5711   if ( p!=null ) 
5712      mp_print(mp, " ETC.");
5713 @.ETC@>
5714   return;
5715 };
5716
5717 @ @<Display token |p| and set |c| to its class...@>=
5718 c=letter_class; /* the default */
5719 if ( (p<0)||(p>mp->mem_end) ) { 
5720   mp_print(mp, " CLOBBERED"); return;
5721 @.CLOBBERED@>
5722 }
5723 if ( p<mp->hi_mem_min ) { 
5724   @<Display two-word token@>;
5725 } else { 
5726   r=info(p);
5727   if ( r>=expr_base ) {
5728      @<Display a parameter token@>;
5729   } else {
5730     if ( r<1 ) {
5731       if ( r==0 ) { 
5732         @<Display a collective subscript@>
5733       } else {
5734         mp_print(mp, " IMPOSSIBLE");
5735 @.IMPOSSIBLE@>
5736       }
5737     } else { 
5738       r=text(r);
5739       if ( (r<0)||(r>mp->max_str_ptr) ) {
5740         mp_print(mp, " NONEXISTENT");
5741 @.NONEXISTENT@>
5742       } else {
5743        @<Print string |r| as a symbolic token
5744         and set |c| to its class@>;
5745       }
5746     }
5747   }
5748 }
5749
5750 @ @<Display two-word token@>=
5751 if ( name_type(p)==mp_token ) {
5752   if ( type(p)==mp_known ) {
5753     @<Display a numeric token@>;
5754   } else if ( type(p)!=mp_string_type ) {
5755     mp_print(mp, " BAD");
5756 @.BAD@>
5757   } else { 
5758     mp_print_char(mp, '"'); mp_print_str(mp, value(p)); mp_print_char(mp, '"');
5759     c=string_class;
5760   }
5761 } else if ((name_type(p)!=mp_capsule)||(type(p)<mp_vacuous)||(type(p)>mp_independent) ) {
5762   mp_print(mp, " BAD");
5763 } else { 
5764   mp->g_pointer=p; mp_print_capsule(mp); c=right_paren_class;
5765 }
5766
5767 @ @<Display a numeric token@>=
5768 if ( class==digit_class ) 
5769   mp_print_char(mp, ' ');
5770 v=value(p);
5771 if ( v<0 ){ 
5772   if ( class==left_bracket_class ) 
5773     mp_print_char(mp, ' ');
5774   mp_print_char(mp, '['); mp_print_scaled(mp, v); mp_print_char(mp, ']');
5775   c=right_bracket_class;
5776 } else { 
5777   mp_print_scaled(mp, v); c=digit_class;
5778 }
5779
5780
5781 @ Strictly speaking, a genuine token will never have |info(p)=0|.
5782 But we will see later (in the |print_variable_name| routine) that
5783 it is convenient to let |info(p)=0| stand for `\.{[]}'.
5784
5785 @<Display a collective subscript@>=
5786 {
5787 if ( class==left_bracket_class ) 
5788   mp_print_char(mp, ' ');
5789 mp_print(mp, "[]"); c=right_bracket_class;
5790 }
5791
5792 @ @<Display a parameter token@>=
5793 {
5794 if ( r<suffix_base ) { 
5795   mp_print(mp, "(EXPR"); r=r-(expr_base);
5796 @.EXPR@>
5797 } else if ( r<text_base ) { 
5798   mp_print(mp, "(SUFFIX"); r=r-(suffix_base);
5799 @.SUFFIX@>
5800 } else { 
5801   mp_print(mp, "(TEXT"); r=r-(text_base);
5802 @.TEXT@>
5803 }
5804 mp_print_int(mp, r); mp_print_char(mp, ')'); c=right_paren_class;
5805 }
5806
5807
5808 @ @<Print string |r| as a symbolic token...@>=
5809
5810 c=mp->char_class[mp->str_pool[mp->str_start[r]]];
5811 if ( c==class ) {
5812   switch (c) {
5813   case letter_class:mp_print_char(mp, '.'); break;
5814   case isolated_classes: break;
5815   default: mp_print_char(mp, ' '); break;
5816   }
5817 }
5818 mp_print_str(mp, r);
5819 }
5820
5821 @ The following procedures have been declared |forward| with no parameters,
5822 because the author dislikes \PASCAL's convention about |forward| procedures
5823 with parameters. It was necessary to do something, because |show_token_list|
5824 is recursive (although the recursion is limited to one level), and because
5825 |flush_token_list| is syntactically (but not semantically) recursive.
5826 @^recursion@>
5827
5828 @<Declare miscellaneous procedures that were declared |forward|@>=
5829 void mp_print_capsule (MP mp) { 
5830   mp_print_char(mp, '('); mp_print_exp(mp, mp->g_pointer,0); mp_print_char(mp, ')');
5831 };
5832 @#
5833 void mp_token_recycle (MP mp) { 
5834   mp_recycle_value(mp, mp->g_pointer);
5835 };
5836
5837 @ @<Glob...@>=
5838 pointer g_pointer; /* (global) parameter to the |forward| procedures */
5839
5840 @ Macro definitions are kept in \MP's memory in the form of token lists
5841 that have a few extra one-word nodes at the beginning.
5842
5843 The first node contains a reference count that is used to tell when the
5844 list is no longer needed. To emphasize the fact that a reference count is
5845 present, we shall refer to the |info| field of this special node as the
5846 |ref_count| field.
5847 @^reference counts@>
5848
5849 The next node or nodes after the reference count serve to describe the
5850 formal parameters. They either contain a code word that specifies all
5851 of the parameters, or they contain zero or more parameter tokens followed
5852 by the code `|general_macro|'.
5853
5854 @d ref_count info
5855   /* reference count preceding a macro definition or picture header */
5856 @d add_mac_ref(A) incr(ref_count((A))) /* make a new reference to a macro list */
5857 @d general_macro 0 /* preface to a macro defined with a parameter list */
5858 @d primary_macro 1 /* preface to a macro with a \&{primary} parameter */
5859 @d secondary_macro 2 /* preface to a macro with a \&{secondary} parameter */
5860 @d tertiary_macro 3 /* preface to a macro with a \&{tertiary} parameter */
5861 @d expr_macro 4 /* preface to a macro with an undelimited \&{expr} parameter */
5862 @d of_macro 5 /* preface to a macro with
5863   undelimited `\&{expr} |x| \&{of}~|y|' parameters */
5864 @d suffix_macro 6 /* preface to a macro with an undelimited \&{suffix} parameter */
5865 @d text_macro 7 /* preface to a macro with an undelimited \&{text} parameter */
5866
5867 @c 
5868 void mp_delete_mac_ref (MP mp,pointer p) {
5869   /* |p| points to the reference count of a macro list that is
5870     losing one reference */
5871   if ( ref_count(p)==null ) mp_flush_token_list(mp, p);
5872   else decr(ref_count(p));
5873 }
5874
5875 @ The following subroutine displays a macro, given a pointer to its
5876 reference count.
5877
5878 @c 
5879 @<Declare the procedure called |print_cmd_mod|@>;
5880 void mp_show_macro (MP mp, pointer p, integer q, integer l) {
5881   pointer r; /* temporary storage */
5882   p=link(p); /* bypass the reference count */
5883   while ( info(p)>text_macro ){ 
5884     r=link(p); link(p)=null;
5885     mp_show_token_list(mp, p,null,l,0); link(p)=r; p=r;
5886     if ( l>0 ) l=l-mp->tally; else return;
5887   } /* control printing of `\.{ETC.}' */
5888 @.ETC@>
5889   mp->tally=0;
5890   switch(info(p)) {
5891   case general_macro:mp_print(mp, "->"); break;
5892 @.->@>
5893   case primary_macro: case secondary_macro: case tertiary_macro:
5894     mp_print_char(mp, '<');
5895     mp_print_cmd_mod(mp, param_type,info(p)); 
5896     mp_print(mp, ">->");
5897     break;
5898   case expr_macro:mp_print(mp, "<expr>->"); break;
5899   case of_macro:mp_print(mp, "<expr>of<primary>->"); break;
5900   case suffix_macro:mp_print(mp, "<suffix>->"); break;
5901   case text_macro:mp_print(mp, "<text>->"); break;
5902   } /* there are no other cases */
5903   mp_show_token_list(mp, link(p),q,l-mp->tally,0);
5904 }
5905
5906 @* \[15] Data structures for variables.
5907 The variables of \MP\ programs can be simple, like `\.x', or they can
5908 combine the structural properties of arrays and records, like `\.{x20a.b}'.
5909 A \MP\ user assigns a type to a variable like \.{x20a.b} by saying, for
5910 example, `\.{boolean} \.{x20a.b}'. It's time for us to study how such
5911 things are represented inside of the computer.
5912
5913 Each variable value occupies two consecutive words, either in a two-word
5914 node called a value node, or as a two-word subfield of a larger node.  One
5915 of those two words is called the |value| field; it is an integer,
5916 containing either a |scaled| numeric value or the representation of some
5917 other type of quantity. (It might also be subdivided into halfwords, in
5918 which case it is referred to by other names instead of |value|.) The other
5919 word is broken into subfields called |type|, |name_type|, and |link|.  The
5920 |type| field is a quarterword that specifies the variable's type, and
5921 |name_type| is a quarterword from which \MP\ can reconstruct the
5922 variable's name (sometimes by using the |link| field as well).  Thus, only
5923 1.25 words are actually devoted to the value itself; the other
5924 three-quarters of a word are overhead, but they aren't wasted because they
5925 allow \MP\ to deal with sparse arrays and to provide meaningful diagnostics.
5926
5927 In this section we shall be concerned only with the structural aspects of
5928 variables, not their values. Later parts of the program will change the
5929 |type| and |value| fields, but we shall treat those fields as black boxes
5930 whose contents should not be touched.
5931
5932 However, if the |type| field is |mp_structured|, there is no |value| field,
5933 and the second word is broken into two pointer fields called |attr_head|
5934 and |subscr_head|. Those fields point to additional nodes that
5935 contain structural information, as we shall see.
5936
5937 @d subscr_head_loc(A)   (A)+1 /* where |value|, |subscr_head| and |attr_head| are */
5938 @d attr_head(A)   info(subscr_head_loc((A))) /* pointer to attribute info */
5939 @d subscr_head(A)   link(subscr_head_loc((A))) /* pointer to subscript info */
5940 @d value_node_size 2 /* the number of words in a value node */
5941
5942 @ An attribute node is three words long. Two of these words contain |type|
5943 and |value| fields as described above, and the third word contains
5944 additional information:  There is an |attr_loc| field, which contains the
5945 hash address of the token that names this attribute; and there's also a
5946 |parent| field, which points to the value node of |mp_structured| type at the
5947 next higher level (i.e., at the level to which this attribute is
5948 subsidiary).  The |name_type| in an attribute node is `|attr|'.  The
5949 |link| field points to the next attribute with the same parent; these are
5950 arranged in increasing order, so that |attr_loc(link(p))>attr_loc(p)|. The
5951 final attribute node links to the constant |end_attr|, whose |attr_loc|
5952 field is greater than any legal hash address. The |attr_head| in the
5953 parent points to a node whose |name_type| is |mp_structured_root|; this
5954 node represents the null attribute, i.e., the variable that is relevant
5955 when no attributes are attached to the parent. The |attr_head| node is either
5956 a value node, a subscript node, or an attribute node, depending on what
5957 the parent would be if it were not structured; but the subscript and
5958 attribute fields are ignored, so it effectively contains only the data of
5959 a value node. The |link| field in this special node points to an attribute
5960 node whose |attr_loc| field is zero; the latter node represents a collective
5961 subscript `\.{[]}' attached to the parent, and its |link| field points to
5962 the first non-special attribute node (or to |end_attr| if there are none).
5963
5964 A subscript node likewise occupies three words, with |type| and |value| fields
5965 plus extra information; its |name_type| is |subscr|. In this case the
5966 third word is called the |subscript| field, which is a |scaled| integer.
5967 The |link| field points to the subscript node with the next larger
5968 subscript, if any; otherwise the |link| points to the attribute node
5969 for collective subscripts at this level. We have seen that the latter node
5970 contains an upward pointer, so that the parent can be deduced.
5971
5972 The |name_type| in a parent-less value node is |root|, and the |link|
5973 is the hash address of the token that names this value.
5974
5975 In other words, variables have a hierarchical structure that includes
5976 enough threads running around so that the program is able to move easily
5977 between siblings, parents, and children. An example should be helpful:
5978 (The reader is advised to draw a picture while reading the following
5979 description, since that will help to firm up the ideas.)
5980 Suppose that `\.x' and `\.{x.a}' and `\.{x[]b}' and `\.{x5}'
5981 and `\.{x20b}' have been mentioned in a user's program, where
5982 \.{x[]b} has been declared to be of \&{boolean} type. Let |h(x)|, |h(a)|,
5983 and |h(b)| be the hash addresses of \.x, \.a, and~\.b. Then
5984 |eq_type(h(x))=name| and |equiv(h(x))=p|, where |p|~is a two-word value
5985 node with |name_type(p)=root| and |link(p)=h(x)|. We have |type(p)=mp_structured|,
5986 |attr_head(p)=q|, and |subscr_head(p)=r|, where |q| points to a value
5987 node and |r| to a subscript node. (Are you still following this? Use
5988 a pencil to draw a diagram.) The lone variable `\.x' is represented by
5989 |type(q)| and |value(q)|; furthermore
5990 |name_type(q)=mp_structured_root| and |link(q)=q1|, where |q1| points
5991 to an attribute node representing `\.{x[]}'. Thus |name_type(q1)=attr|,
5992 |attr_loc(q1)=collective_subscript=0|, |parent(q1)=p|,
5993 |type(q1)=mp_structured|, |attr_head(q1)=qq|, and |subscr_head(q1)=qq1|;
5994 |qq| is a value node with |type(qq)=mp_numeric_type| (assuming that \.{x5} is
5995 numeric, because |qq| represents `\.{x[]}' with no further attributes),
5996 |name_type(qq)=mp_structured_root|, and
5997 |link(qq)=qq1|. (Now pay attention to the next part.) Node |qq1| is
5998 an attribute node representing `\.{x[][]}', which has never yet
5999 occurred; its |type| field is |undefined|, and its |value| field is
6000 undefined. We have |name_type(qq1)=attr|, |attr_loc(qq1)=collective_subscript|,
6001 |parent(qq1)=q1|, and |link(qq1)=qq2|. Since |qq2| represents
6002 `\.{x[]b}', |type(qq2)=mp_unknown_boolean|; also |attr_loc(qq2)=h(b)|,
6003 |parent(qq2)=q1|, |name_type(qq2)=attr|, |link(qq2)=end_attr|.
6004 (Maybe colored lines will help untangle your picture.)
6005  Node |r| is a subscript node with |type| and |value|
6006 representing `\.{x5}'; |name_type(r)=subscr|, |subscript(r)=5.0|,
6007 and |link(r)=r1| is another subscript node. To complete the picture,
6008 see if you can guess what |link(r1)| is; give up? It's~|q1|.
6009 Furthermore |subscript(r1)=20.0|, |name_type(r1)=subscr|,
6010 |type(r1)=mp_structured|, |attr_head(r1)=qqq|, |subscr_head(r1)=qqq1|,
6011 and we finish things off with three more nodes
6012 |qqq|, |qqq1|, and |qqq2| hung onto~|r1|. (Perhaps you should start again
6013 with a larger sheet of paper.) The value of variable \.{x20b}
6014 appears in node~|qqq2|, as you can well imagine.
6015
6016 If the example in the previous paragraph doesn't make things crystal
6017 clear, a glance at some of the simpler subroutines below will reveal how
6018 things work out in practice.
6019
6020 The only really unusual thing about these conventions is the use of
6021 collective subscript attributes. The idea is to avoid repeating a lot of
6022 type information when many elements of an array are identical macros
6023 (for which distinct values need not be stored) or when they don't have
6024 all of the possible attributes. Branches of the structure below collective
6025 subscript attributes do not carry actual values except for macro identifiers;
6026 branches of the structure below subscript nodes do not carry significant
6027 information in their collective subscript attributes.
6028
6029 @d attr_loc_loc(A) ((A)+2) /* where the |attr_loc| and |parent| fields are */
6030 @d attr_loc(A) info(attr_loc_loc((A))) /* hash address of this attribute */
6031 @d parent(A) link(attr_loc_loc((A))) /* pointer to |mp_structured| variable */
6032 @d subscript_loc(A) ((A)+2) /* where the |subscript| field lives */
6033 @d subscript(A) mp->mem[subscript_loc((A))].sc /* subscript of this variable */
6034 @d attr_node_size 3 /* the number of words in an attribute node */
6035 @d subscr_node_size 3 /* the number of words in a subscript node */
6036 @d collective_subscript 0 /* code for the attribute `\.{[]}' */
6037
6038 @<Initialize table...@>=
6039 attr_loc(end_attr)=hash_end+1; parent(end_attr)=null;
6040
6041 @ Variables of type \&{pair} will have values that point to four-word
6042 nodes containing two numeric values. The first of these values has
6043 |name_type=mp_x_part_sector| and the second has |name_type=mp_y_part_sector|;
6044 the |link| in the first points back to the node whose |value| points
6045 to this four-word node.
6046
6047 Variables of type \&{transform} are similar, but in this case their
6048 |value| points to a 12-word node containing six values, identified by
6049 |x_part_sector|, |y_part_sector|, |mp_xx_part_sector|, |mp_xy_part_sector|,
6050 |mp_yx_part_sector|, and |mp_yy_part_sector|.
6051 Finally, variables of type \&{color} have three values in six words
6052 identified by |mp_red_part_sector|, |mp_green_part_sector|, and |mp_blue_part_sector|.
6053
6054 When an entire structured variable is saved, the |root| indication
6055 is temporarily replaced by |saved_root|.
6056
6057 Some variables have no name; they just are used for temporary storage
6058 while expressions are being evaluated. We call them {\sl capsules}.
6059
6060 @d x_part_loc(A) (A) /* where the \&{xpart} is found in a pair or transform node */
6061 @d y_part_loc(A) ((A)+2) /* where the \&{ypart} is found in a pair or transform node */
6062 @d xx_part_loc(A) ((A)+4) /* where the \&{xxpart} is found in a transform node */
6063 @d xy_part_loc(A) ((A)+6) /* where the \&{xypart} is found in a transform node */
6064 @d yx_part_loc(A) ((A)+8) /* where the \&{yxpart} is found in a transform node */
6065 @d yy_part_loc(A) ((A)+10) /* where the \&{yypart} is found in a transform node */
6066 @d red_part_loc(A) (A) /* where the \&{redpart} is found in a color node */
6067 @d green_part_loc(A) ((A)+2) /* where the \&{greenpart} is found in a color node */
6068 @d blue_part_loc(A) ((A)+4) /* where the \&{bluepart} is found in a color node */
6069 @d cyan_part_loc(A) (A) /* where the \&{cyanpart} is found in a color node */
6070 @d magenta_part_loc(A) ((A)+2) /* where the \&{magentapart} is found in a color node */
6071 @d yellow_part_loc(A) ((A)+4) /* where the \&{yellowpart} is found in a color node */
6072 @d black_part_loc(A) ((A)+6) /* where the \&{blackpart} is found in a color node */
6073 @d grey_part_loc(A) (A) /* where the \&{greypart} is found in a color node */
6074 @#
6075 @d pair_node_size 4 /* the number of words in a pair node */
6076 @d transform_node_size 12 /* the number of words in a transform node */
6077 @d color_node_size 6 /* the number of words in a color node */
6078 @d cmykcolor_node_size 8 /* the number of words in a color node */
6079
6080 @<Glob...@>=
6081 small_number big_node_size[mp_pair_type+1];
6082 small_number sector0[mp_pair_type+1];
6083 small_number sector_offset[mp_black_part_sector+1];
6084
6085 @ The |sector0| array gives for each big node type, |name_type| values
6086 for its first subfield; the |sector_offset| array gives for each
6087 |name_type| value, the offset from the first subfield in words;
6088 and the |big_node_size| array gives the size in words for each type of
6089 big node.
6090
6091 @<Set init...@>=
6092 mp->big_node_size[mp_transform_type]=transform_node_size;
6093 mp->big_node_size[mp_pair_type]=pair_node_size;
6094 mp->big_node_size[mp_color_type]=color_node_size;
6095 mp->big_node_size[mp_cmykcolor_type]=cmykcolor_node_size;
6096 mp->sector0[mp_transform_type]=mp_x_part_sector;
6097 mp->sector0[mp_pair_type]=mp_x_part_sector;
6098 mp->sector0[mp_color_type]=mp_red_part_sector;
6099 mp->sector0[mp_cmykcolor_type]=mp_cyan_part_sector;
6100 for (k=mp_x_part_sector;k<= mp_yy_part_sector;k++ ) {
6101   mp->sector_offset[k]=2*(k-mp_x_part_sector);
6102 }
6103 for (k=mp_red_part_sector;k<= mp_blue_part_sector ; k++) {
6104   mp->sector_offset[k]=2*(k-mp_red_part_sector);
6105 }
6106 for (k=mp_cyan_part_sector;k<= mp_black_part_sector;k++ ) {
6107   mp->sector_offset[k]=2*(k-mp_cyan_part_sector);
6108 }
6109
6110 @ If |type(p)=mp_pair_type| or |mp_transform_type| and if |value(p)=null|, the
6111 procedure call |init_big_node(p)| will allocate a pair or transform node
6112 for~|p|.  The individual parts of such nodes are initially of type
6113 |mp_independent|.
6114
6115 @c 
6116 void mp_init_big_node (MP mp,pointer p) {
6117   pointer q; /* the new node */
6118   small_number s; /* its size */
6119   s=mp->big_node_size[type(p)]; q=mp_get_node(mp, s);
6120   do {  
6121     s=s-2; 
6122     @<Make variable |q+s| newly independent@>;
6123     name_type(q+s)=halfp(s)+mp->sector0[type(p)]; 
6124     link(q+s)=null;
6125   } while (s!=0);
6126   link(q)=p; value(p)=q;
6127 }
6128
6129 @ The |id_transform| function creates a capsule for the
6130 identity transformation.
6131
6132 @c 
6133 pointer mp_id_transform (MP mp) {
6134   pointer p,q,r; /* list manipulation registers */
6135   p=mp_get_node(mp, value_node_size); type(p)=mp_transform_type;
6136   name_type(p)=mp_capsule; value(p)=null; mp_init_big_node(mp, p); q=value(p);
6137   r=q+transform_node_size;
6138   do {  
6139     r=r-2;
6140     type(r)=mp_known; value(r)=0;
6141   } while (r!=q);
6142   value(xx_part_loc(q))=unity; 
6143   value(yy_part_loc(q))=unity;
6144   return p;
6145 }
6146
6147 @ Tokens are of type |tag_token| when they first appear, but they point
6148 to |null| until they are first used as the root of a variable.
6149 The following subroutine establishes the root node on such grand occasions.
6150
6151 @c 
6152 void mp_new_root (MP mp,pointer x) {
6153   pointer p; /* the new node */
6154   p=mp_get_node(mp, value_node_size); type(p)=undefined; name_type(p)=mp_root;
6155   link(p)=x; equiv(x)=p;
6156 }
6157
6158 @ These conventions for variable representation are illustrated by the
6159 |print_variable_name| routine, which displays the full name of a
6160 variable given only a pointer to its two-word value packet.
6161
6162 @<Declarations@>=
6163 void mp_print_variable_name (MP mp, pointer p);
6164
6165 @ @c 
6166 void mp_print_variable_name (MP mp, pointer p) {
6167   pointer q; /* a token list that will name the variable's suffix */
6168   pointer r; /* temporary for token list creation */
6169   while ( name_type(p)>=mp_x_part_sector ) {
6170     @<Preface the output with a part specifier; |return| in the
6171       case of a capsule@>;
6172   }
6173   q=null;
6174   while ( name_type(p)>mp_saved_root ) {
6175     @<Ascend one level, pushing a token onto list |q|
6176      and replacing |p| by its parent@>;
6177   }
6178   r=mp_get_avail(mp); info(r)=link(p); link(r)=q;
6179   if ( name_type(p)==mp_saved_root ) mp_print(mp, "(SAVED)");
6180 @.SAVED@>
6181   mp_show_token_list(mp, r,null,el_gordo,mp->tally); 
6182   mp_flush_token_list(mp, r);
6183 }
6184
6185 @ @<Ascend one level, pushing a token onto list |q|...@>=
6186
6187   if ( name_type(p)==mp_subscr ) { 
6188     r=mp_new_num_tok(mp, subscript(p));
6189     do {  
6190       p=link(p);
6191     } while (name_type(p)!=mp_attr);
6192   } else if ( name_type(p)==mp_structured_root ) {
6193     p=link(p); goto FOUND;
6194   } else { 
6195     if ( name_type(p)!=mp_attr ) mp_confusion(mp, "var");
6196 @:this can't happen var}{\quad var@>
6197     r=mp_get_avail(mp); info(r)=attr_loc(p);
6198   }
6199   link(r)=q; q=r;
6200 FOUND:  
6201   p=parent(p);
6202 }
6203
6204 @ @<Preface the output with a part specifier...@>=
6205 { switch (name_type(p)) {
6206   case mp_x_part_sector: mp_print_char(mp, 'x'); break;
6207   case mp_y_part_sector: mp_print_char(mp, 'y'); break;
6208   case mp_xx_part_sector: mp_print(mp, "xx"); break;
6209   case mp_xy_part_sector: mp_print(mp, "xy"); break;
6210   case mp_yx_part_sector: mp_print(mp, "yx"); break;
6211   case mp_yy_part_sector: mp_print(mp, "yy"); break;
6212   case mp_red_part_sector: mp_print(mp, "red"); break;
6213   case mp_green_part_sector: mp_print(mp, "green"); break;
6214   case mp_blue_part_sector: mp_print(mp, "blue"); break;
6215   case mp_cyan_part_sector: mp_print(mp, "cyan"); break;
6216   case mp_magenta_part_sector: mp_print(mp, "magenta"); break;
6217   case mp_yellow_part_sector: mp_print(mp, "yellow"); break;
6218   case mp_black_part_sector: mp_print(mp, "black"); break;
6219   case mp_grey_part_sector: mp_print(mp, "grey"); break;
6220   case mp_capsule: 
6221     mp_print(mp, "%CAPSULE"); mp_print_int(mp, p-null); return;
6222     break;
6223 @.CAPSULE@>
6224   } /* there are no other cases */
6225   mp_print(mp, "part "); 
6226   p=link(p-mp->sector_offset[name_type(p)]);
6227 }
6228
6229 @ The |interesting| function returns |true| if a given variable is not
6230 in a capsule, or if the user wants to trace capsules.
6231
6232 @c 
6233 boolean mp_interesting (MP mp,pointer p) {
6234   small_number t; /* a |name_type| */
6235   if ( mp->internal[tracing_capsules]>0 ) {
6236     return true;
6237   } else { 
6238     t=name_type(p);
6239     if ( t>=mp_x_part_sector ) if ( t!=mp_capsule )
6240       t=name_type(link(p-mp->sector_offset[t]));
6241     return (t!=mp_capsule);
6242   }
6243 }
6244
6245 @ Now here is a subroutine that converts an unstructured type into an
6246 equivalent structured type, by inserting a |mp_structured| node that is
6247 capable of growing. This operation is done only when |name_type(p)=root|,
6248 |subscr|, or |attr|.
6249
6250 The procedure returns a pointer to the new node that has taken node~|p|'s
6251 place in the structure. Node~|p| itself does not move, nor are its
6252 |value| or |type| fields changed in any way.
6253
6254 @c 
6255 pointer mp_new_structure (MP mp,pointer p) {
6256   pointer q,r=0; /* list manipulation registers */
6257   switch (name_type(p)) {
6258   case mp_root: 
6259     q=link(p); r=mp_get_node(mp, value_node_size); equiv(q)=r;
6260     break;
6261   case mp_subscr: 
6262     @<Link a new subscript node |r| in place of node |p|@>;
6263     break;
6264   case mp_attr: 
6265     @<Link a new attribute node |r| in place of node |p|@>;
6266     break;
6267   default: 
6268     mp_confusion(mp, "struct");
6269 @:this can't happen struct}{\quad struct@>
6270     break;
6271   }
6272   link(r)=link(p); type(r)=mp_structured; name_type(r)=name_type(p);
6273   attr_head(r)=p; name_type(p)=mp_structured_root;
6274   q=mp_get_node(mp, attr_node_size); link(p)=q; subscr_head(r)=q;
6275   parent(q)=r; type(q)=undefined; name_type(q)=mp_attr; link(q)=end_attr;
6276   attr_loc(q)=collective_subscript; 
6277   return r;
6278 };
6279
6280 @ @<Link a new subscript node |r| in place of node |p|@>=
6281
6282   q=p;
6283   do {  
6284     q=link(q);
6285   } while (name_type(q)!=mp_attr);
6286   q=parent(q); r=subscr_head_loc(q); /* |link(r)=subscr_head(q)| */
6287   do {  
6288     q=r; r=link(r);
6289   } while (r!=p);
6290   r=mp_get_node(mp, subscr_node_size);
6291   link(q)=r; subscript(r)=subscript(p);
6292 }
6293
6294 @ If the attribute is |collective_subscript|, there are two pointers to
6295 node~|p|, so we must change both of them.
6296
6297 @<Link a new attribute node |r| in place of node |p|@>=
6298
6299   q=parent(p); r=attr_head(q);
6300   do {  
6301     q=r; r=link(r);
6302   } while (r!=p);
6303   r=mp_get_node(mp, attr_node_size); link(q)=r;
6304   mp->mem[attr_loc_loc(r)]=mp->mem[attr_loc_loc(p)]; /* copy |attr_loc| and |parent| */
6305   if ( attr_loc(p)==collective_subscript ) { 
6306     q=subscr_head_loc(parent(p));
6307     while ( link(q)!=p ) q=link(q);
6308     link(q)=r;
6309   }
6310 }
6311
6312 @ The |find_variable| routine is given a pointer~|t| to a nonempty token
6313 list of suffixes; it returns a pointer to the corresponding two-word
6314 value. For example, if |t| points to token \.x followed by a numeric
6315 token containing the value~7, |find_variable| finds where the value of
6316 \.{x7} is stored in memory. This may seem a simple task, and it
6317 usually is, except when \.{x7} has never been referenced before.
6318 Indeed, \.x may never have even been subscripted before; complexities
6319 arise with respect to updating the collective subscript information.
6320
6321 If a macro type is detected anywhere along path~|t|, or if the first
6322 item on |t| isn't a |tag_token|, the value |null| is returned.
6323 Otherwise |p| will be a non-null pointer to a node such that
6324 |undefined<type(p)<mp_structured|.
6325
6326 @d abort_find { return null; }
6327
6328 @c 
6329 pointer mp_find_variable (MP mp,pointer t) {
6330   pointer p,q,r,s; /* nodes in the ``value'' line */
6331   pointer pp,qq,rr,ss; /* nodes in the ``collective'' line */
6332   integer n; /* subscript or attribute */
6333   memory_word save_word; /* temporary storage for a word of |mem| */
6334 @^inner loop@>
6335   p=info(t); t=link(t);
6336   if ( (eq_type(p) % outer_tag) != tag_token ) abort_find;
6337   if ( equiv(p)==null ) mp_new_root(mp, p);
6338   p=equiv(p); pp=p;
6339   while ( t!=null ) { 
6340     @<Make sure that both nodes |p| and |pp| are of |mp_structured| type@>;
6341     if ( t<mp->hi_mem_min ) {
6342       @<Descend one level for the subscript |value(t)|@>
6343     } else {
6344       @<Descend one level for the attribute |info(t)|@>;
6345     }
6346     t=link(t);
6347   }
6348   if ( type(pp)>=mp_structured ) {
6349     if ( type(pp)==mp_structured ) pp=attr_head(pp); else abort_find;
6350   }
6351   if ( type(p)==mp_structured ) p=attr_head(p);
6352   if ( type(p)==undefined ) { 
6353     if ( type(pp)==undefined ) { type(pp)=mp_numeric_type; value(pp)=null; };
6354     type(p)=type(pp); value(p)=null;
6355   };
6356   return p;
6357 }
6358
6359 @ Although |pp| and |p| begin together, they diverge when a subscript occurs;
6360 |pp|~stays in the collective line while |p|~goes through actual subscript
6361 values.
6362
6363 @<Make sure that both nodes |p| and |pp|...@>=
6364 if ( type(pp)!=mp_structured ) { 
6365   if ( type(pp)>mp_structured ) abort_find;
6366   ss=mp_new_structure(mp, pp);
6367   if ( p==pp ) p=ss;
6368   pp=ss;
6369 }; /* now |type(pp)=mp_structured| */
6370 if ( type(p)!=mp_structured ) /* it cannot be |>mp_structured| */
6371   p=mp_new_structure(mp, p) /* now |type(p)=mp_structured| */
6372
6373 @ We want this part of the program to be reasonably fast, in case there are
6374 @^inner loop@>
6375 lots of subscripts at the same level of the data structure. Therefore
6376 we store an ``infinite'' value in the word that appears at the end of the
6377 subscript list, even though that word isn't part of a subscript node.
6378
6379 @<Descend one level for the subscript |value(t)|@>=
6380
6381   n=value(t);
6382   pp=link(attr_head(pp)); /* now |attr_loc(pp)=collective_subscript| */
6383   q=link(attr_head(p)); save_word=mp->mem[subscript_loc(q)];
6384   subscript(q)=el_gordo; s=subscr_head_loc(p); /* |link(s)=subscr_head(p)| */
6385   do {  
6386     r=s; s=link(s);
6387   } while (n>subscript(s));
6388   if ( n==subscript(s) ) {
6389     p=s;
6390   } else { 
6391     p=mp_get_node(mp, subscr_node_size); link(r)=p; link(p)=s;
6392     subscript(p)=n; name_type(p)=mp_subscr; type(p)=undefined;
6393   }
6394   mp->mem[subscript_loc(q)]=save_word;
6395 }
6396
6397 @ @<Descend one level for the attribute |info(t)|@>=
6398
6399   n=info(t);
6400   ss=attr_head(pp);
6401   do {  
6402     rr=ss; ss=link(ss);
6403   } while (n>attr_loc(ss));
6404   if ( n<attr_loc(ss) ) { 
6405     qq=mp_get_node(mp, attr_node_size); link(rr)=qq; link(qq)=ss;
6406     attr_loc(qq)=n; name_type(qq)=mp_attr; type(qq)=undefined;
6407     parent(qq)=pp; ss=qq;
6408   }
6409   if ( p==pp ) { 
6410     p=ss; pp=ss;
6411   } else { 
6412     pp=ss; s=attr_head(p);
6413     do {  
6414       r=s; s=link(s);
6415     } while (n>attr_loc(s));
6416     if ( n==attr_loc(s) ) {
6417       p=s;
6418     } else { 
6419       q=mp_get_node(mp, attr_node_size); link(r)=q; link(q)=s;
6420       attr_loc(q)=n; name_type(q)=mp_attr; type(q)=undefined;
6421       parent(q)=p; p=q;
6422     }
6423   }
6424 }
6425
6426 @ Variables lose their former values when they appear in a type declaration,
6427 or when they are defined to be macros or \&{let} equal to something else.
6428 A subroutine will be defined later that recycles the storage associated
6429 with any particular |type| or |value|; our goal now is to study a higher
6430 level process called |flush_variable|, which selectively frees parts of a
6431 variable structure.
6432
6433 This routine has some complexity because of examples such as
6434 `\hbox{\tt numeric x[]a[]b}'
6435 which recycles all variables of the form \.{x[i]a[j]b} (and no others), while
6436 `\hbox{\tt vardef x[]a[]=...}'
6437 discards all variables of the form \.{x[i]a[j]} followed by an arbitrary
6438 suffix, except for the collective node \.{x[]a[]} itself. The obvious way
6439 to handle such examples is to use recursion; so that's what we~do.
6440 @^recursion@>
6441
6442 Parameter |p| points to the root information of the variable;
6443 parameter |t| points to a list of one-word nodes that represent
6444 suffixes, with |info=collective_subscript| for subscripts.
6445
6446 @<Declarations@>=
6447 @<Declare subroutines for printing expressions@>
6448 @<Declare basic dependency-list subroutines@>
6449 @<Declare the recycling subroutines@>
6450 void mp_flush_cur_exp (MP mp,scaled v) ;
6451 @<Declare the procedure called |flush_below_variable|@>
6452
6453 @ @c 
6454 void mp_flush_variable (MP mp,pointer p, pointer t, boolean discard_suffixes) {
6455   pointer q,r; /* list manipulation */
6456   halfword n; /* attribute to match */
6457   while ( t!=null ) { 
6458     if ( type(p)!=mp_structured ) return;
6459     n=info(t); t=link(t);
6460     if ( n==collective_subscript ) { 
6461       r=subscr_head_loc(p); q=link(r); /* |q=subscr_head(p)| */
6462       while ( name_type(q)==mp_subscr ){ 
6463         mp_flush_variable(mp, q,t,discard_suffixes);
6464         if ( t==null ) {
6465           if ( type(q)==mp_structured ) r=q;
6466           else  { link(r)=link(q); mp_free_node(mp, q,subscr_node_size);   }
6467         } else {
6468           r=q;
6469         }
6470         q=link(r);
6471       }
6472     }
6473     p=attr_head(p);
6474     do {  
6475       r=p; p=link(p);
6476     } while (attr_loc(p)<n);
6477     if ( attr_loc(p)!=n ) return;
6478   }
6479   if ( discard_suffixes ) {
6480     mp_flush_below_variable(mp, p);
6481   } else { 
6482     if ( type(p)==mp_structured ) p=attr_head(p);
6483     mp_recycle_value(mp, p);
6484   }
6485 }
6486
6487 @ The next procedure is simpler; it wipes out everything but |p| itself,
6488 which becomes undefined.
6489
6490 @<Declare the procedure called |flush_below_variable|@>=
6491 void mp_flush_below_variable (MP mp, pointer p);
6492
6493 @ @c
6494 void mp_flush_below_variable (MP mp,pointer p) {
6495    pointer q,r; /* list manipulation registers */
6496   if ( type(p)!=mp_structured ) {
6497     mp_recycle_value(mp, p); /* this sets |type(p)=undefined| */
6498   } else { 
6499     q=subscr_head(p);
6500     while ( name_type(q)==mp_subscr ) { 
6501       mp_flush_below_variable(mp, q); r=q; q=link(q);
6502       mp_free_node(mp, r,subscr_node_size);
6503     }
6504     r=attr_head(p); q=link(r); mp_recycle_value(mp, r);
6505     if ( name_type(p)<=mp_saved_root ) mp_free_node(mp, r,value_node_size);
6506     else mp_free_node(mp, r,subscr_node_size);
6507     /* we assume that |subscr_node_size=attr_node_size| */
6508     do {  
6509       mp_flush_below_variable(mp, q); r=q; q=link(q); mp_free_node(mp, r,attr_node_size);
6510     } while (q!=end_attr);
6511     type(p)=undefined;
6512   }
6513 }
6514
6515 @ Just before assigning a new value to a variable, we will recycle the
6516 old value and make the old value undefined. The |und_type| routine
6517 determines what type of undefined value should be given, based on
6518 the current type before recycling.
6519
6520 @c 
6521 small_number mp_und_type (MP mp,pointer p) { 
6522   switch (type(p)) {
6523   case undefined: case mp_vacuous:
6524     return undefined;
6525   case mp_boolean_type: case mp_unknown_boolean:
6526     return mp_unknown_boolean;
6527   case mp_string_type: case mp_unknown_string:
6528     return mp_unknown_string;
6529   case mp_pen_type: case mp_unknown_pen:
6530     return mp_unknown_pen;
6531   case mp_path_type: case mp_unknown_path:
6532     return mp_unknown_path;
6533   case mp_picture_type: case mp_unknown_picture:
6534     return mp_unknown_picture;
6535   case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
6536   case mp_pair_type: case mp_numeric_type: 
6537     return type(p);
6538   case mp_known: case mp_dependent: case mp_proto_dependent: case mp_independent:
6539     return mp_numeric_type;
6540   } /* there are no other cases */
6541   return 0;
6542 }
6543
6544 @ The |clear_symbol| routine is used when we want to redefine the equivalent
6545 of a symbolic token. It must remove any variable structure or macro
6546 definition that is currently attached to that symbol. If the |saving|
6547 parameter is true, a subsidiary structure is saved instead of destroyed.
6548
6549 @c 
6550 void mp_clear_symbol (MP mp,pointer p, boolean saving) {
6551   pointer q; /* |equiv(p)| */
6552   q=equiv(p);
6553   switch (eq_type(p) % outer_tag)  {
6554   case defined_macro:
6555   case secondary_primary_macro:
6556   case tertiary_secondary_macro:
6557   case expression_tertiary_macro: 
6558     if ( ! saving ) mp_delete_mac_ref(mp, q);
6559     break;
6560   case tag_token:
6561     if ( q!=null ) {
6562       if ( saving ) {
6563         name_type(q)=mp_saved_root;
6564       } else { 
6565         mp_flush_below_variable(mp, q); mp_free_node(mp,q,value_node_size); 
6566       }
6567     }
6568     break;
6569   default:
6570     break;
6571   }
6572   mp->eqtb[p]=mp->eqtb[frozen_undefined];
6573 };
6574
6575 @* \[16] Saving and restoring equivalents.
6576 The nested structure given by \&{begingroup} and \&{endgroup}
6577 allows |eqtb| entries to be saved and restored, so that temporary changes
6578 can be made without difficulty.  When the user requests a current value to
6579 be saved, \MP\ puts that value into its ``save stack.'' An appearance of
6580 \&{endgroup} ultimately causes the old values to be removed from the save
6581 stack and put back in their former places.
6582
6583 The save stack is a linked list containing three kinds of entries,
6584 distinguished by their |info| fields. If |p| points to a saved item,
6585 then
6586
6587 \smallskip\hang
6588 |info(p)=0| stands for a group boundary; each \&{begingroup} contributes
6589 such an item to the save stack and each \&{endgroup} cuts back the stack
6590 until the most recent such entry has been removed.
6591
6592 \smallskip\hang
6593 |info(p)=q|, where |1<=q<=hash_end|, means that |mem[p+1]| holds the former
6594 contents of |eqtb[q]|. Such save stack entries are generated by \&{save}
6595 commands or suitable \&{interim} commands.
6596
6597 \smallskip\hang
6598 |info(p)=hash_end+q|, where |q>0|, means that |value(p)| is a |scaled|
6599 integer to be restored to internal parameter number~|q|. Such entries
6600 are generated by \&{interim} commands.
6601
6602 \smallskip\noindent
6603 The global variable |save_ptr| points to the top item on the save stack.
6604
6605 @d save_node_size 2 /* number of words per non-boundary save-stack node */
6606 @d saved_equiv(A) mp->mem[(A)+1].hh /* where an |eqtb| entry gets saved */
6607 @d save_boundary_item(A) { (A)=mp_get_avail(mp); info((A))=0;
6608   link((A))=mp->save_ptr; mp->save_ptr=(A);
6609   }
6610
6611 @<Glob...@>=
6612 pointer save_ptr; /* the most recently saved item */
6613
6614 @ @<Set init...@>=mp->save_ptr=null;
6615
6616 @ The |save_variable| routine is given a hash address |q|; it salts this
6617 address in the save stack, together with its current equivalent,
6618 then makes token~|q| behave as though it were brand new.
6619
6620 Nothing is stacked when |save_ptr=null|, however; there's no way to remove
6621 things from the stack when the program is not inside a group, so there's
6622 no point in wasting the space.
6623
6624 @c void mp_save_variable (MP mp,pointer q) {
6625   pointer p; /* temporary register */
6626   if ( mp->save_ptr!=null ){ 
6627     p=mp_get_node(mp, save_node_size); info(p)=q; link(p)=mp->save_ptr;
6628     saved_equiv(p)=mp->eqtb[q]; mp->save_ptr=p;
6629   }
6630   mp_clear_symbol(mp, q,(mp->save_ptr!=null));
6631 }
6632
6633 @ Similarly, |save_internal| is given the location |q| of an internal
6634 quantity like |tracing_pens|. It creates a save stack entry of the
6635 third kind.
6636
6637 @c void mp_save_internal (MP mp,halfword q) {
6638   pointer p; /* new item for the save stack */
6639   if ( mp->save_ptr!=null ){ 
6640      p=mp_get_node(mp, save_node_size); info(p)=hash_end+q;
6641     link(p)=mp->save_ptr; value(p)=mp->internal[q]; mp->save_ptr=p;
6642   }
6643 }
6644
6645 @ At the end of a group, the |unsave| routine restores all of the saved
6646 equivalents in reverse order. This routine will be called only when there
6647 is at least one boundary item on the save stack.
6648
6649 @c 
6650 void mp_unsave (MP mp) {
6651   pointer q; /* index to saved item */
6652   pointer p; /* temporary register */
6653   while ( info(mp->save_ptr)!=0 ) {
6654     q=info(mp->save_ptr);
6655     if ( q>hash_end ) {
6656       if ( mp->internal[tracing_restores]>0 ) {
6657         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6658         mp_print(mp, mp->int_name[q-(hash_end)]); mp_print_char(mp, '=');
6659         mp_print_scaled(mp, value(mp->save_ptr)); mp_print_char(mp, '}');
6660         mp_end_diagnostic(mp, false);
6661       }
6662       mp->internal[q-(hash_end)]=value(mp->save_ptr);
6663     } else { 
6664       if ( mp->internal[tracing_restores]>0 ) {
6665         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6666         mp_print_text(q); mp_print_char(mp, '}');
6667         mp_end_diagnostic(mp, false);
6668       }
6669       mp_clear_symbol(mp, q,false);
6670       mp->eqtb[q]=saved_equiv(mp->save_ptr);
6671       if ( eq_type(q) % outer_tag==tag_token ) {
6672         p=equiv(q);
6673         if ( p!=null ) name_type(p)=mp_root;
6674       }
6675     }
6676     p=link(mp->save_ptr); 
6677     mp_free_node(mp, mp->save_ptr,save_node_size); mp->save_ptr=p;
6678   }
6679   p=link(mp->save_ptr); free_avail(mp->save_ptr); mp->save_ptr=p;
6680 }
6681
6682 @* \[17] Data structures for paths.
6683 When a \MP\ user specifies a path, \MP\ will create a list of knots
6684 and control points for the associated cubic spline curves. If the
6685 knots are $z_0$, $z_1$, \dots, $z_n$, there are control points
6686 $z_k^+$ and $z_{k+1}^-$ such that the cubic splines between knots
6687 $z_k$ and $z_{k+1}$ are defined by B\'ezier's formula
6688 @:Bezier}{B\'ezier, Pierre Etienne@>
6689 $$\eqalign{z(t)&=B(z_k,z_k^+,z_{k+1}^-,z_{k+1};t)\cr
6690 &=(1-t)^3z_k+3(1-t)^2tz_k^++3(1-t)t^2z_{k+1}^-+t^3z_{k+1}\cr}$$
6691 for |0<=t<=1|.
6692
6693 There is a 8-word node for each knot $z_k$, containing one word of
6694 control information and six words for the |x| and |y| coordinates of
6695 $z_k^-$ and $z_k$ and~$z_k^+$. The control information appears in the
6696 |left_type| and |right_type| fields, which each occupy a quarter of
6697 the first word in the node; they specify properties of the curve as it
6698 enters and leaves the knot. There's also a halfword |link| field,
6699 which points to the following knot, and a final supplementary word (of
6700 which only a quarter is used).
6701
6702 If the path is a closed contour, knots 0 and |n| are identical;
6703 i.e., the |link| in knot |n-1| points to knot~0. But if the path
6704 is not closed, the |left_type| of knot~0 and the |right_type| of knot~|n|
6705 are equal to |endpoint|. In the latter case the |link| in knot~|n| points
6706 to knot~0, and the control points $z_0^-$ and $z_n^+$ are not used.
6707
6708 @d left_type(A)   mp->mem[(A)].hh.b0 /* characterizes the path entering this knot */
6709 @d right_type(A)   mp->mem[(A)].hh.b1 /* characterizes the path leaving this knot */
6710 @d endpoint 0 /* |left_type| at path beginning and |right_type| at path end */
6711 @d x_coord(A)   mp->mem[(A)+1].sc /* the |x| coordinate of this knot */
6712 @d y_coord(A)   mp->mem[(A)+2].sc /* the |y| coordinate of this knot */
6713 @d left_x(A)   mp->mem[(A)+3].sc /* the |x| coordinate of previous control point */
6714 @d left_y(A)   mp->mem[(A)+4].sc /* the |y| coordinate of previous control point */
6715 @d right_x(A)   mp->mem[(A)+5].sc /* the |x| coordinate of next control point */
6716 @d right_y(A)   mp->mem[(A)+6].sc /* the |y| coordinate of next control point */
6717 @d x_loc(A)   ((A)+1) /* where the |x| coordinate is stored in a knot */
6718 @d y_loc(A)   ((A)+2) /* where the |y| coordinate is stored in a knot */
6719 @d knot_coord(A)   mp->mem[(A)].sc /* |x| or |y| coordinate given |x_loc| or |y_loc| */
6720 @d left_coord(A)   mp->mem[(A)+2].sc
6721   /* coordinate of previous control point given |x_loc| or |y_loc| */
6722 @d right_coord(A)   mp->mem[(A)+4].sc
6723   /* coordinate of next control point given |x_loc| or |y_loc| */
6724 @d knot_node_size 8 /* number of words in a knot node */
6725
6726 @ Before the B\'ezier control points have been calculated, the memory
6727 space they will ultimately occupy is taken up by information that can be
6728 used to compute them. There are four cases:
6729
6730 \yskip
6731 \textindent{$\bullet$} If |right_type=open|, the curve should leave
6732 the knot in the same direction it entered; \MP\ will figure out a
6733 suitable direction.
6734
6735 \yskip
6736 \textindent{$\bullet$} If |right_type=curl|, the curve should leave the
6737 knot in a direction depending on the angle at which it enters the next
6738 knot and on the curl parameter stored in |right_curl|.
6739
6740 \yskip
6741 \textindent{$\bullet$} If |right_type=given|, the curve should leave the
6742 knot in a nonzero direction stored as an |angle| in |right_given|.
6743
6744 \yskip
6745 \textindent{$\bullet$} If |right_type=explicit|, the B\'ezier control
6746 point for leaving this knot has already been computed; it is in the
6747 |right_x| and |right_y| fields.
6748
6749 \yskip\noindent
6750 The rules for |left_type| are similar, but they refer to the curve entering
6751 the knot, and to \\{left} fields instead of \\{right} fields.
6752
6753 Non-|explicit| control points will be chosen based on ``tension'' parameters
6754 in the |left_tension| and |right_tension| fields. The
6755 `\&{atleast}' option is represented by negative tension values.
6756 @:at_least_}{\&{atleast} primitive@>
6757
6758 For example, the \MP\ path specification
6759 $$\.{z0..z1..tension atleast 1..\{curl 2\}z2..z3\{-1,-2\}..tension
6760   3 and 4..p},$$
6761 where \.p is the path `\.{z4..controls z45 and z54..z5}', will be represented
6762 by the six knots
6763 \def\lodash{\hbox to 1.1em{\thinspace\hrulefill\thinspace}}
6764 $$\vbox{\halign{#\hfil&&\qquad#\hfil\cr
6765 |left_type|&\\{left} info&|x_coord,y_coord|&|right_type|&\\{right} info\cr
6766 \noalign{\yskip}
6767 |endpoint|&\lodash$,\,$\lodash&$x_0,y_0$&|curl|&$1.0,1.0$\cr
6768 |open|&\lodash$,1.0$&$x_1,y_1$&|open|&\lodash$,-1.0$\cr
6769 |curl|&$2.0,-1.0$&$x_2,y_2$&|curl|&$2.0,1.0$\cr
6770 |given|&$d,1.0$&$x_3,y_3$&|given|&$d,3.0$\cr
6771 |open|&\lodash$,4.0$&$x_4,y_4$&|explicit|&$x_{45},y_{45}$\cr
6772 |explicit|&$x_{54},y_{54}$&$x_5,y_5$&|endpoint|&\lodash$,\,$\lodash\cr}}$$
6773 Here |d| is the |angle| obtained by calling |n_arg(-unity,-two)|.
6774 Of course, this example is more complicated than anything a normal user
6775 would ever write.
6776
6777 These types must satisfy certain restrictions because of the form of \MP's
6778 path syntax:
6779 (i)~|open| type never appears in the same node together with |endpoint|,
6780 |given|, or |curl|.
6781 (ii)~The |right_type| of a node is |explicit| if and only if the
6782 |left_type| of the following node is |explicit|.
6783 (iii)~|endpoint| types occur only at the ends, as mentioned above.
6784
6785 @d left_curl left_x /* curl information when entering this knot */
6786 @d left_given left_x /* given direction when entering this knot */
6787 @d left_tension left_y /* tension information when entering this knot */
6788 @d right_curl right_x /* curl information when leaving this knot */
6789 @d right_given right_x /* given direction when leaving this knot */
6790 @d right_tension right_y /* tension information when leaving this knot */
6791 @d explicit 1 /* |left_type| or |right_type| when control points are known */
6792 @d given 2 /* |left_type| or |right_type| when a direction is given */
6793 @d curl 3 /* |left_type| or |right_type| when a curl is desired */
6794 @d open 4 /* |left_type| or |right_type| when \MP\ should choose the direction */
6795
6796 @ Knots can be user-supplied, or they can be created by program code,
6797 like the |split_cubic| function, or |copy_path|. The distinction is
6798 needed for the cleanup routine that runs after |split_cubic|, because
6799 it should only delete knots it has previously inserted, and never
6800 anything that was user-supplied. In order to be able to differentiate
6801 one knot from another, we will set |originator(p):=metapost_user| when
6802 it appeared in the actual metapost program, and
6803 |originator(p):=program_code| in all other cases.
6804
6805 @d originator(A)   mp->mem[(A)+7].hh.b0 /* the creator of this knot */
6806 @d program_code 0 /* not created by a user */
6807 @d metapost_user 1 /* created by a user */
6808
6809 @ Here is a routine that prints a given knot list
6810 in symbolic form. It illustrates the conventions discussed above,
6811 and checks for anomalies that might arise while \MP\ is being debugged.
6812
6813 @<Declare subroutines for printing expressions@>=
6814 void mp_pr_path (MP mp,pointer h);
6815
6816 @ @c
6817 void mp_pr_path (MP mp,pointer h) {
6818   pointer p,q; /* for list traversal */
6819   p=h;
6820   do {  
6821     q=link(p);
6822     if ( (p==null)||(q==null) ) { 
6823       mp_print_nl(mp, "???"); return; /* this won't happen */
6824 @.???@>
6825     }
6826     @<Print information for adjacent knots |p| and |q|@>;
6827   DONE1:
6828     p=q;
6829     if ( (p!=h)||(left_type(h)!=endpoint) ) {
6830       @<Print two dots, followed by |given| or |curl| if present@>;
6831     }
6832   } while (p!=h);
6833   if ( left_type(h)!=endpoint ) 
6834     mp_print(mp, "cycle");
6835 }
6836
6837 @ @<Print information for adjacent knots...@>=
6838 mp_print_two(mp, x_coord(p),y_coord(p));
6839 switch (right_type(p)) {
6840 case endpoint: 
6841   if ( left_type(p)==open ) mp_print(mp, "{open?}"); /* can't happen */
6842 @.open?@>
6843   if ( (left_type(q)!=endpoint)||(q!=h) ) q=null; /* force an error */
6844   goto DONE1;
6845   break;
6846 case explicit: 
6847   @<Print control points between |p| and |q|, then |goto done1|@>;
6848   break;
6849 case open: 
6850   @<Print information for a curve that begins |open|@>;
6851   break;
6852 case curl:
6853 case given: 
6854   @<Print information for a curve that begins |curl| or |given|@>;
6855   break;
6856 default:
6857   mp_print(mp, "???"); /* can't happen */
6858 @.???@>
6859   break;
6860 }
6861 if ( left_type(q)<=explicit ) {
6862   mp_print(mp, "..control?"); /* can't happen */
6863 @.control?@>
6864 } else if ( (right_tension(p)!=unity)||(left_tension(q)!=unity) ) {
6865   @<Print tension between |p| and |q|@>;
6866 }
6867
6868 @ Since |n_sin_cos| produces |fraction| results, which we will print as if they
6869 were |scaled|, the magnitude of a |given| direction vector will be~4096.
6870
6871 @<Print two dots...@>=
6872
6873   mp_print_nl(mp, " ..");
6874   if ( left_type(p)==given ) { 
6875     mp_n_sin_cos(mp, left_given(p)); mp_print_char(mp, '{');
6876     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ',');
6877     mp_print_scaled(mp, mp->n_sin); mp_print_char(mp, '}');
6878   } else if ( left_type(p)==curl ){ 
6879     mp_print(mp, "{curl "); 
6880     mp_print_scaled(mp, left_curl(p)); mp_print_char(mp, '}');
6881   }
6882 }
6883
6884 @ @<Print tension between |p| and |q|@>=
6885
6886   mp_print(mp, "..tension ");
6887   if ( right_tension(p)<0 ) mp_print(mp, "atleast");
6888   mp_print_scaled(mp, abs(right_tension(p)));
6889   if ( right_tension(p)!=left_tension(q) ){ 
6890     mp_print(mp, " and ");
6891     if ( left_tension(q)<0 ) mp_print(mp, "atleast");
6892     mp_print_scaled(mp, abs(left_tension(q)));
6893   }
6894 }
6895
6896 @ @<Print control points between |p| and |q|, then |goto done1|@>=
6897
6898   mp_print(mp, "..controls "); 
6899   mp_print_two(mp, right_x(p),right_y(p)); 
6900   mp_print(mp, " and ");
6901   if ( left_type(q)!=explicit ) { 
6902     mp_print(mp, "??"); /* can't happen */
6903 @.??@>
6904   } else {
6905     mp_print_two(mp, left_x(q),left_y(q));
6906   }
6907   goto DONE1;
6908 }
6909
6910 @ @<Print information for a curve that begins |open|@>=
6911 if ( (left_type(p)!=explicit)&&(left_type(p)!=open) ) {
6912   mp_print(mp, "{open?}"); /* can't happen */
6913 @.open?@>
6914 }
6915
6916 @ A curl of 1 is shown explicitly, so that the user sees clearly that
6917 \MP's default curl is present.
6918
6919 The code here uses the fact that |left_curl==left_given| and
6920 |right_curl==right_given|.
6921
6922 @<Print information for a curve that begins |curl|...@>=
6923
6924   if ( left_type(p)==open )  
6925     mp_print(mp, "??"); /* can't happen */
6926 @.??@>
6927   if ( right_type(p)==curl ) { 
6928     mp_print(mp, "{curl "); mp_print_scaled(mp, right_curl(p));
6929   } else { 
6930     mp_n_sin_cos(mp, right_given(p)); mp_print_char(mp, '{');
6931     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ','); 
6932     mp_print_scaled(mp, mp->n_sin);
6933   }
6934   mp_print_char(mp, '}');
6935 }
6936
6937 @ It is convenient to have another version of |pr_path| that prints the path
6938 as a diagnostic message.
6939
6940 @<Declare subroutines for printing expressions@>=
6941 void mp_print_path (MP mp,pointer h, char *s, boolean nuline) { 
6942   mp_print_diagnostic(mp, "Path", s, nuline); mp_print_ln(mp);
6943 @.Path at line...@>
6944   mp_pr_path(mp, h);
6945   mp_end_diagnostic(mp, true);
6946 }
6947
6948 @ If we want to duplicate a knot node, we can say |copy_knot|:
6949
6950 @c 
6951 pointer mp_copy_knot (MP mp,pointer p) {
6952   pointer q; /* the copy */
6953   int k; /* runs through the words of a knot node */
6954   q=mp_get_node(mp, knot_node_size);
6955   for (k=0;k<=knot_node_size-1;k++) {
6956     mp->mem[q+k]=mp->mem[p+k];
6957   }
6958   originator(q)=originator(p);
6959   return q;
6960 }
6961
6962 @ The |copy_path| routine makes a clone of a given path.
6963
6964 @c 
6965 pointer mp_copy_path (MP mp, pointer p) {
6966   pointer q,pp,qq; /* for list manipulation */
6967   q=mp_copy_knot(mp, p);
6968   qq=q; pp=link(p);
6969   while ( pp!=p ) { 
6970     link(qq)=mp_copy_knot(mp, pp);
6971     qq=link(qq);
6972     pp=link(pp);
6973   }
6974   link(qq)=q;
6975   return q;
6976 }
6977
6978 @ Similarly, there's a way to copy the {\sl reverse\/} of a path. This procedure
6979 returns a pointer to the first node of the copy, if the path is a cycle,
6980 but to the final node of a non-cyclic copy. The global
6981 variable |path_tail| will point to the final node of the original path;
6982 this trick makes it easier to implement `\&{doublepath}'.
6983
6984 All node types are assumed to be |endpoint| or |explicit| only.
6985
6986 @c 
6987 pointer mp_htap_ypoc (MP mp,pointer p) {
6988   pointer q,pp,qq,rr; /* for list manipulation */
6989   q=mp_get_node(mp, knot_node_size); /* this will correspond to |p| */
6990   qq=q; pp=p;
6991   while (1) { 
6992     right_type(qq)=left_type(pp); left_type(qq)=right_type(pp);
6993     x_coord(qq)=x_coord(pp); y_coord(qq)=y_coord(pp);
6994     right_x(qq)=left_x(pp); right_y(qq)=left_y(pp);
6995     left_x(qq)=right_x(pp); left_y(qq)=right_y(pp);
6996     originator(qq)=originator(pp);
6997     if ( link(pp)==p ) { 
6998       link(q)=qq; mp->path_tail=pp; return q;
6999     }
7000     rr=mp_get_node(mp, knot_node_size); link(rr)=qq; qq=rr; pp=link(pp);
7001   }
7002 }
7003
7004 @ @<Glob...@>=
7005 pointer path_tail; /* the node that links to the beginning of a path */
7006
7007 @ When a cyclic list of knot nodes is no longer needed, it can be recycled by
7008 calling the following subroutine.
7009
7010 @<Declare the recycling subroutines@>=
7011 void mp_toss_knot_list (MP mp,pointer p) ;
7012
7013 @ @c
7014 void mp_toss_knot_list (MP mp,pointer p) {
7015   pointer q; /* the node being freed */
7016   pointer r; /* the next node */
7017   q=p;
7018   do {  
7019     r=link(q); 
7020     mp_free_node(mp, q,knot_node_size); q=r;
7021   } while (q!=p);
7022 }
7023
7024 @* \[18] Choosing control points.
7025 Now we must actually delve into one of \MP's more difficult routines,
7026 the |make_choices| procedure that chooses angles and control points for
7027 the splines of a curve when the user has not specified them explicitly.
7028 The parameter to |make_choices| points to a list of knots and
7029 path information, as described above.
7030
7031 A path decomposes into independent segments at ``breakpoint'' knots,
7032 which are knots whose left and right angles are both prespecified in
7033 some way (i.e., their |left_type| and |right_type| aren't both open).
7034
7035 @c 
7036 @<Declare the procedure called |solve_choices|@>;
7037 void mp_make_choices (MP mp,pointer knots) {
7038   pointer h; /* the first breakpoint */
7039   pointer p,q; /* consecutive breakpoints being processed */
7040   @<Other local variables for |make_choices|@>;
7041   check_arith; /* make sure that |arith_error=false| */
7042   if ( mp->internal[tracing_choices]>0 )
7043     mp_print_path(mp, knots,", before choices",true);
7044   @<If consecutive knots are equal, join them explicitly@>;
7045   @<Find the first breakpoint, |h|, on the path;
7046     insert an artificial breakpoint if the path is an unbroken cycle@>;
7047   p=h;
7048   do {  
7049     @<Fill in the control points between |p| and the next breakpoint,
7050       then advance |p| to that breakpoint@>;
7051   } while (p!=h);
7052   if ( mp->internal[tracing_choices]>0 )
7053     mp_print_path(mp, knots,", after choices",true);
7054   if ( mp->arith_error ) {
7055     @<Report an unexpected problem during the choice-making@>;
7056   }
7057 }
7058
7059 @ @<Report an unexpected problem during the choice...@>=
7060
7061   print_err("Some number got too big");
7062 @.Some number got too big@>
7063   help2("The path that I just computed is out of range.")
7064        ("So it will probably look funny. Proceed, for a laugh.");
7065   mp_put_get_error(mp); mp->arith_error=false;
7066 }
7067
7068 @ Two knots in a row with the same coordinates will always be joined
7069 by an explicit ``curve'' whose control points are identical with the
7070 knots.
7071
7072 @<If consecutive knots are equal, join them explicitly@>=
7073 p=knots;
7074 do {  
7075   q=link(p);
7076   if ( x_coord(p)==x_coord(q) && y_coord(p)==y_coord(q) && right_type(p)>explicit ) { 
7077     right_type(p)=explicit;
7078     if ( left_type(p)==open ) { 
7079       left_type(p)=curl; left_curl(p)=unity;
7080     }
7081     left_type(q)=explicit;
7082     if ( right_type(q)==open ) { 
7083       right_type(q)=curl; right_curl(q)=unity;
7084     }
7085     right_x(p)=x_coord(p); left_x(q)=x_coord(p);
7086     right_y(p)=y_coord(p); left_y(q)=y_coord(p);
7087   }
7088   p=q;
7089 } while (p!=knots)
7090
7091 @ If there are no breakpoints, it is necessary to compute the direction
7092 angles around an entire cycle. In this case the |left_type| of the first
7093 node is temporarily changed to |end_cycle|.
7094
7095 @d end_cycle (open+1)
7096
7097 @<Find the first breakpoint, |h|, on the path...@>=
7098 h=knots;
7099 while (1) { 
7100   if ( left_type(h)!=open ) break;
7101   if ( right_type(h)!=open ) break;
7102   h=link(h);
7103   if ( h==knots ) { 
7104     left_type(h)=end_cycle; break;
7105   }
7106 }
7107
7108 @ If |right_type(p)<given| and |q=link(p)|, we must have
7109 |right_type(p)=left_type(q)=explicit| or |endpoint|.
7110
7111 @<Fill in the control points between |p| and the next breakpoint...@>=
7112 q=link(p);
7113 if ( right_type(p)>=given ) { 
7114   while ( (left_type(q)==open)&&(right_type(q)==open) ) q=link(q);
7115   @<Fill in the control information between
7116     consecutive breakpoints |p| and |q|@>;
7117 } else if ( right_type(p)==endpoint ) {
7118   @<Give reasonable values for the unused control points between |p| and~|q|@>;
7119 }
7120 p=q
7121
7122 @ This step makes it possible to transform an explicitly computed path without
7123 checking the |left_type| and |right_type| fields.
7124
7125 @<Give reasonable values for the unused control points between |p| and~|q|@>=
7126
7127   right_x(p)=x_coord(p); right_y(p)=y_coord(p);
7128   left_x(q)=x_coord(q); left_y(q)=y_coord(q);
7129 }
7130
7131 @ Before we can go further into the way choices are made, we need to
7132 consider the underlying theory. The basic ideas implemented in |make_choices|
7133 are due to John Hobby, who introduced the notion of ``mock curvature''
7134 @^Hobby, John Douglas@>
7135 at a knot. Angles are chosen so that they preserve mock curvature when
7136 a knot is passed, and this has been found to produce excellent results.
7137
7138 It is convenient to introduce some notations that simplify the necessary
7139 formulas. Let $d_{k,k+1}=\vert z\k-z_k\vert$ be the (nonzero) distance
7140 between knots |k| and |k+1|; and let
7141 $${z\k-z_k\over z_k-z_{k-1}}={d_{k,k+1}\over d_{k-1,k}}e^{i\psi_k}$$
7142 so that a polygonal line from $z_{k-1}$ to $z_k$ to $z\k$ turns left
7143 through an angle of~$\psi_k$. We assume that $\vert\psi_k\vert\L180^\circ$.
7144 The control points for the spline from $z_k$ to $z\k$ will be denoted by
7145 $$\eqalign{z_k^+&=z_k+
7146   \textstyle{1\over3}\rho_k e^{i\theta_k}(z\k-z_k),\cr
7147  z\k^-&=z\k-
7148   \textstyle{1\over3}\sigma\k e^{-i\phi\k}(z\k-z_k),\cr}$$
7149 where $\rho_k$ and $\sigma\k$ are nonnegative ``velocity ratios'' at the
7150 beginning and end of the curve, while $\theta_k$ and $\phi\k$ are the
7151 corresponding ``offset angles.'' These angles satisfy the condition
7152 $$\theta_k+\phi_k+\psi_k=0,\eqno(*)$$
7153 whenever the curve leaves an intermediate knot~|k| in the direction that
7154 it enters.
7155
7156 @ Let $\alpha_k$ and $\beta\k$ be the reciprocals of the ``tension'' of
7157 the curve at its beginning and ending points. This means that
7158 $\rho_k=\alpha_k f(\theta_k,\phi\k)$ and $\sigma\k=\beta\k f(\phi\k,\theta_k)$,
7159 where $f(\theta,\phi)$ is \MP's standard velocity function defined in
7160 the |velocity| subroutine. The cubic spline $B(z_k^{\phantom+},z_k^+,
7161 z\k^-,z\k^{\phantom+};t)$
7162 has curvature
7163 @^curvature@>
7164 $${2\sigma\k\sin(\theta_k+\phi\k)-6\sin\theta_k\over\rho_k^2d_{k,k+1}}
7165 \qquad{\rm and}\qquad
7166 {2\rho_k\sin(\theta_k+\phi\k)-6\sin\phi\k\over\sigma\k^2d_{k,k+1}}$$
7167 at |t=0| and |t=1|, respectively. The mock curvature is the linear
7168 @^mock curvature@>
7169 approximation to this true curvature that arises in the limit for
7170 small $\theta_k$ and~$\phi\k$, if second-order terms are discarded.
7171 The standard velocity function satisfies
7172 $$f(\theta,\phi)=1+O(\theta^2+\theta\phi+\phi^2);$$
7173 hence the mock curvatures are respectively
7174 $${2\beta\k(\theta_k+\phi\k)-6\theta_k\over\alpha_k^2d_{k,k+1}}
7175 \qquad{\rm and}\qquad
7176 {2\alpha_k(\theta_k+\phi\k)-6\phi\k\over\beta\k^2d_{k,k+1}}.\eqno(**)$$
7177
7178 @ The turning angles $\psi_k$ are given, and equation $(*)$ above
7179 determines $\phi_k$ when $\theta_k$ is known, so the task of
7180 angle selection is essentially to choose appropriate values for each
7181 $\theta_k$. When equation~$(*)$ is used to eliminate $\phi$~variables
7182 from $(**)$, we obtain a system of linear equations of the form
7183 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7184 where
7185 $$A_k={\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7186 \qquad B_k={3-\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7187 \qquad C_k={3-\beta\k\over\alpha_k^2d_{k,k+1}},
7188 \qquad D_k={\beta\k\over\alpha_k^2d_{k,k+1}}.$$
7189 The tensions are always $3\over4$ or more, hence each $\alpha$ and~$\beta$
7190 will be at most $4\over3$. It follows that $B_k\G{5\over4}A_k$ and
7191 $C_k\G{5\over4}D_k$; hence the equations are diagonally dominant;
7192 hence they have a unique solution. Moreover, in most cases the tensions
7193 are equal to~1, so that $B_k=2A_k$ and $C_k=2D_k$. This makes the
7194 solution numerically stable, and there is an exponential damping
7195 effect: The data at knot $k\pm j$ affects the angle at knot~$k$ by
7196 a factor of~$O(2^{-j})$.
7197
7198 @ However, we still must consider the angles at the starting and ending
7199 knots of a non-cyclic path. These angles might be given explicitly, or
7200 they might be specified implicitly in terms of an amount of ``curl.''
7201
7202 Let's assume that angles need to be determined for a non-cyclic path
7203 starting at $z_0$ and ending at~$z_n$. Then equations of the form
7204 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta_{k+1}=R_k$$
7205 have been given for $0<k<n$, and it will be convenient to introduce
7206 equations of the same form for $k=0$ and $k=n$, where
7207 $$A_0=B_0=C_n=D_n=0.$$
7208 If $\theta_0$ is supposed to have a given value $E_0$, we simply
7209 define $C_0=0$, $D_0=0$, and $R_0=E_0$. Otherwise a curl
7210 parameter, $\gamma_0$, has been specified at~$z_0$; this means
7211 that the mock curvature at $z_0$ should be $\gamma_0$ times the
7212 mock curvature at $z_1$; i.e.,
7213 $${2\beta_1(\theta_0+\phi_1)-6\theta_0\over\alpha_0^2d_{01}}
7214 =\gamma_0{2\alpha_0(\theta_0+\phi_1)-6\phi_1\over\beta_1^2d_{01}}.$$
7215 This equation simplifies to
7216 $$(\alpha_0\chi_0+3-\beta_1)\theta_0+
7217  \bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\theta_1=
7218  -\bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\psi_1,$$
7219 where $\chi_0=\alpha_0^2\gamma_0/\beta_1^2$; so we can set $C_0=
7220 \chi_0\alpha_0+3-\beta_1$, $D_0=(3-\alpha_0)\chi_0+\beta_1$, $R_0=-D_0\psi_1$.
7221 It can be shown that $C_0>0$ and $C_0B_1-A_1D_0>0$ when $\gamma_0\G0$,
7222 hence the linear equations remain nonsingular.
7223
7224 Similar considerations apply at the right end, when the final angle $\phi_n$
7225 may or may not need to be determined. It is convenient to let $\psi_n=0$,
7226 hence $\theta_n=-\phi_n$. We either have an explicit equation $\theta_n=E_n$,
7227 or we have
7228 $$\bigl((3-\beta_n)\chi_n+\alpha_{n-1}\bigr)\theta_{n-1}+
7229 (\beta_n\chi_n+3-\alpha_{n-1})\theta_n=0,\qquad
7230   \chi_n={\beta_n^2\gamma_n\over\alpha_{n-1}^2}.$$
7231
7232 When |make_choices| chooses angles, it must compute the coefficients of
7233 these linear equations, then solve the equations. To compute the coefficients,
7234 it is necessary to compute arctangents of the given turning angles~$\psi_k$.
7235 When the equations are solved, the chosen directions $\theta_k$ are put
7236 back into the form of control points by essentially computing sines and
7237 cosines.
7238
7239 @ OK, we are ready to make the hard choices of |make_choices|.
7240 Most of the work is relegated to an auxiliary procedure
7241 called |solve_choices|, which has been introduced to keep
7242 |make_choices| from being extremely long.
7243
7244 @<Fill in the control information between...@>=
7245 @<Calculate the turning angles $\psi_k$ and the distances $d_{k,k+1}$;
7246   set $n$ to the length of the path@>;
7247 @<Remove |open| types at the breakpoints@>;
7248 mp_solve_choices(mp, p,q,n)
7249
7250 @ It's convenient to precompute quantities that will be needed several
7251 times later. The values of |delta_x[k]| and |delta_y[k]| will be the
7252 coordinates of $z\k-z_k$, and the magnitude of this vector will be
7253 |delta[k]=@t$d_{k,k+1}$@>|. The path angle $\psi_k$ between $z_k-z_{k-1}$
7254 and $z\k-z_k$ will be stored in |psi[k]|.
7255
7256 @<Glob...@>=
7257 int path_size; /* maximum number of knots between breakpoints of a path */
7258 scaled *delta_x;
7259 scaled *delta_y;
7260 scaled *delta; /* knot differences */
7261 angle  *psi; /* turning angles */
7262
7263 @ @<Allocate or initialize ...@>=
7264 mp->delta_x = NULL;
7265 mp->delta_y = NULL;
7266 mp->delta = NULL;
7267 mp->psi = NULL;
7268
7269 @ @<Dealloc variables@>=
7270 xfree(mp->delta_x);
7271 xfree(mp->delta_y);
7272 xfree(mp->delta);
7273 xfree(mp->psi);
7274
7275 @ @<Other local variables for |make_choices|@>=
7276   int k,n; /* current and final knot numbers */
7277   pointer s,t; /* registers for list traversal */
7278   scaled delx,dely; /* directions where |open| meets |explicit| */
7279   fraction sine,cosine; /* trig functions of various angles */
7280
7281 @ @<Calculate the turning angles...@>=
7282 {
7283 RESTART:
7284   k=0; s=p; n=mp->path_size;
7285   do {  
7286     t=link(s);
7287     mp->delta_x[k]=x_coord(t)-x_coord(s);
7288     mp->delta_y[k]=y_coord(t)-y_coord(s);
7289     mp->delta[k]=mp_pyth_add(mp, mp->delta_x[k],mp->delta_y[k]);
7290     if ( k>0 ) { 
7291       sine=mp_make_fraction(mp, mp->delta_y[k-1],mp->delta[k-1]);
7292       cosine=mp_make_fraction(mp, mp->delta_x[k-1],mp->delta[k-1]);
7293       mp->psi[k]=mp_n_arg(mp, mp_take_fraction(mp, mp->delta_x[k],cosine)+
7294         mp_take_fraction(mp, mp->delta_y[k],sine),
7295         mp_take_fraction(mp, mp->delta_y[k],cosine)-
7296           mp_take_fraction(mp, mp->delta_x[k],sine));
7297     }
7298     incr(k); s=t;
7299     if ( k==mp->path_size ) {
7300       mp_reallocate_paths(mp, mp->path_size+(mp->path_size>>2));
7301       goto RESTART; /* retry, loop size has changed */
7302     }
7303     if ( s==q ) n=k;
7304   } while (! (k>=n)&&(left_type(s)!=end_cycle));
7305   if ( k==n ) mp->psi[n]=0; else mp->psi[k]=mp->psi[1];
7306 }
7307
7308 @ When we get to this point of the code, |right_type(p)| is either
7309 |given| or |curl| or |open|. If it is |open|, we must have
7310 |left_type(p)=end_cycle| or |left_type(p)=explicit|. In the latter
7311 case, the |open| type is converted to |given|; however, if the
7312 velocity coming into this knot is zero, the |open| type is
7313 converted to a |curl|, since we don't know the incoming direction.
7314
7315 Similarly, |left_type(q)| is either |given| or |curl| or |open| or
7316 |end_cycle|. The |open| possibility is reduced either to |given| or to |curl|.
7317
7318 @<Remove |open| types at the breakpoints@>=
7319 if ( left_type(q)==open ) { 
7320   delx=right_x(q)-x_coord(q); dely=right_y(q)-y_coord(q);
7321   if ( (delx==0)&&(dely==0) ) { 
7322     left_type(q)=curl; left_curl(q)=unity;
7323   } else { 
7324     left_type(q)=given; left_given(q)=mp_n_arg(mp, delx,dely);
7325   }
7326 }
7327 if ( (right_type(p)==open)&&(left_type(p)==explicit) ) { 
7328   delx=x_coord(p)-left_x(p); dely=y_coord(p)-left_y(p);
7329   if ( (delx==0)&&(dely==0) ) { 
7330     right_type(p)=curl; right_curl(p)=unity;
7331   } else { 
7332     right_type(p)=given; right_given(p)=mp_n_arg(mp, delx,dely);
7333   }
7334 }
7335
7336 @ Linear equations need to be solved whenever |n>1|; and also when |n=1|
7337 and exactly one of the breakpoints involves a curl. The simplest case occurs
7338 when |n=1| and there is a curl at both breakpoints; then we simply draw
7339 a straight line.
7340
7341 But before coding up the simple cases, we might as well face the general case,
7342 since we must deal with it sooner or later, and since the general case
7343 is likely to give some insight into the way simple cases can be handled best.
7344
7345 When there is no cycle, the linear equations to be solved form a tridiagonal
7346 system, and we can apply the standard technique of Gaussian elimination
7347 to convert that system to a sequence of equations of the form
7348 $$\theta_0+u_0\theta_1=v_0,\quad
7349 \theta_1+u_1\theta_2=v_1,\quad\ldots,\quad
7350 \theta_{n-1}+u_{n-1}\theta_n=v_{n-1},\quad
7351 \theta_n=v_n.$$
7352 It is possible to do this diagonalization while generating the equations.
7353 Once $\theta_n$ is known, it is easy to determine $\theta_{n-1}$, \dots,
7354 $\theta_1$, $\theta_0$; thus, the equations will be solved.
7355
7356 The procedure is slightly more complex when there is a cycle, but the
7357 basic idea will be nearly the same. In the cyclic case the right-hand
7358 sides will be $v_k+w_k\theta_0$ instead of simply $v_k$, and we will start
7359 the process off with $u_0=v_0=0$, $w_0=1$. The final equation will be not
7360 $\theta_n=v_n$ but $\theta_n+u_n\theta_1=v_n+w_n\theta_0$; an appropriate
7361 ending routine will take account of the fact that $\theta_n=\theta_0$ and
7362 eliminate the $w$'s from the system, after which the solution can be
7363 obtained as before.
7364
7365 When $u_k$, $v_k$, and $w_k$ are being computed, the three pointer
7366 variables |r|, |s|,~|t| will point respectively to knots |k-1|, |k|,
7367 and~|k+1|. The $u$'s and $w$'s are scaled by $2^{28}$, i.e., they are
7368 of type |fraction|; the $\theta$'s and $v$'s are of type |angle|.
7369
7370 @<Glob...@>=
7371 angle *theta; /* values of $\theta_k$ */
7372 fraction *uu; /* values of $u_k$ */
7373 angle *vv; /* values of $v_k$ */
7374 fraction *ww; /* values of $w_k$ */
7375
7376 @ @<Allocate or initialize ...@>=
7377 mp->theta = NULL;
7378 mp->uu = NULL;
7379 mp->vv = NULL;
7380 mp->ww = NULL;
7381
7382 @ @<Dealloc variables@>=
7383 xfree(mp->theta);
7384 xfree(mp->uu);
7385 xfree(mp->vv);
7386 xfree(mp->ww);
7387
7388 @ @<Declare |mp_reallocate| functions@>=
7389 void mp_reallocate_paths (MP mp, int l);
7390
7391 @ @c
7392 void mp_reallocate_paths (MP mp, int l) {
7393   XREALLOC (mp->delta_x, (l+1), scaled);
7394   XREALLOC (mp->delta_y, (l+1), scaled);
7395   XREALLOC (mp->delta,   (l+1), scaled);
7396   XREALLOC (mp->psi,     (l+1), angle);
7397   XREALLOC (mp->theta,   (l+1), angle);
7398   XREALLOC (mp->uu,      (l+1), fraction);
7399   XREALLOC (mp->vv,      (l+1), angle);
7400   XREALLOC (mp->ww,      (l+1), fraction);
7401   mp->path_size = l;
7402 }
7403
7404 @ Our immediate problem is to get the ball rolling by setting up the
7405 first equation or by realizing that no equations are needed, and to fit
7406 this initialization into a framework suitable for the overall computation.
7407
7408 @<Declare the procedure called |solve_choices|@>=
7409 @<Declare subroutines needed by |solve_choices|@>;
7410 void mp_solve_choices (MP mp,pointer p, pointer q, halfword n) {
7411   int k; /* current knot number */
7412   pointer r,s,t; /* registers for list traversal */
7413   @<Other local variables for |solve_choices|@>;
7414   k=0; s=p; r=0;
7415   while (1) { 
7416     t=link(s);
7417     if ( k==0 ) {
7418       @<Get the linear equations started; or |return|
7419         with the control points in place, if linear equations
7420         needn't be solved@>
7421     } else  { 
7422       switch (left_type(s)) {
7423       case end_cycle: case open:
7424         @<Set up equation to match mock curvatures
7425           at $z_k$; then |goto found| with $\theta_n$
7426           adjusted to equal $\theta_0$, if a cycle has ended@>;
7427         break;
7428       case curl:
7429         @<Set up equation for a curl at $\theta_n$
7430           and |goto found|@>;
7431         break;
7432       case given:
7433         @<Calculate the given value of $\theta_n$
7434           and |goto found|@>;
7435         break;
7436       } /* there are no other cases */
7437     }
7438     r=s; s=t; incr(k);
7439   }
7440 FOUND:
7441   @<Finish choosing angles and assigning control points@>;
7442 }
7443
7444 @ On the first time through the loop, we have |k=0| and |r| is not yet
7445 defined. The first linear equation, if any, will have $A_0=B_0=0$.
7446
7447 @<Get the linear equations started...@>=
7448 switch (right_type(s)) {
7449 case given: 
7450   if ( left_type(t)==given ) {
7451     @<Reduce to simple case of two givens  and |return|@>
7452   } else {
7453     @<Set up the equation for a given value of $\theta_0$@>;
7454   }
7455   break;
7456 case curl: 
7457   if ( left_type(t)==curl ) {
7458     @<Reduce to simple case of straight line and |return|@>
7459   } else {
7460     @<Set up the equation for a curl at $\theta_0$@>;
7461   }
7462   break;
7463 case open: 
7464   mp->uu[0]=0; mp->vv[0]=0; mp->ww[0]=fraction_one;
7465   /* this begins a cycle */
7466   break;
7467 } /* there are no other cases */
7468
7469 @ The general equation that specifies equality of mock curvature at $z_k$ is
7470 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7471 as derived above. We want to combine this with the already-derived equation
7472 $\theta_{k-1}+u_{k-1}\theta_k=v_{k-1}+w_{k-1}\theta_0$ in order to obtain
7473 a new equation
7474 $\theta_k+u_k\theta\k=v_k+w_k\theta_0$. This can be done by dividing the
7475 equation
7476 $$(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}
7477     -A_kw_{k-1}\theta_0$$
7478 by $B_k-u_{k-1}A_k+C_k$. The trick is to do this carefully with
7479 fixed-point arithmetic, avoiding the chance of overflow while retaining
7480 suitable precision.
7481
7482 The calculations will be performed in several registers that
7483 provide temporary storage for intermediate quantities.
7484
7485 @<Other local variables for |solve_choices|@>=
7486 fraction aa,bb,cc,ff,acc; /* temporary registers */
7487 scaled dd,ee; /* likewise, but |scaled| */
7488 scaled lt,rt; /* tension values */
7489
7490 @ @<Set up equation to match mock curvatures...@>=
7491 { @<Calculate the values $\\{aa}=A_k/B_k$, $\\{bb}=D_k/C_k$,
7492     $\\{dd}=(3-\alpha_{k-1})d_{k,k+1}$, $\\{ee}=(3-\beta\k)d_{k-1,k}$,
7493     and $\\{cc}=(B_k-u_{k-1}A_k)/B_k$@>;
7494   @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>;
7495   mp->uu[k]=mp_take_fraction(mp, ff,bb);
7496   @<Calculate the values of $v_k$ and $w_k$@>;
7497   if ( left_type(s)==end_cycle ) {
7498     @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>;
7499   }
7500 }
7501
7502 @ Since tension values are never less than 3/4, the values |aa| and
7503 |bb| computed here are never more than 4/5.
7504
7505 @<Calculate the values $\\{aa}=...@>=
7506 if ( abs(right_tension(r))==unity) { 
7507   aa=fraction_half; dd=2*mp->delta[k];
7508 } else { 
7509   aa=mp_make_fraction(mp, unity,3*abs(right_tension(r))-unity);
7510   dd=mp_take_fraction(mp, mp->delta[k],
7511     fraction_three-mp_make_fraction(mp, unity,abs(right_tension(r))));
7512 }
7513 if ( abs(left_tension(t))==unity ){ 
7514   bb=fraction_half; ee=2*mp->delta[k-1];
7515 } else { 
7516   bb=mp_make_fraction(mp, unity,3*abs(left_tension(t))-unity);
7517   ee=mp_take_fraction(mp, mp->delta[k-1],
7518     fraction_three-mp_make_fraction(mp, unity,abs(left_tension(t))));
7519 }
7520 cc=fraction_one-mp_take_fraction(mp, mp->uu[k-1],aa)
7521
7522 @ The ratio to be calculated in this step can be written in the form
7523 $$\beta_k^2\cdot\\{ee}\over\beta_k^2\cdot\\{ee}+\alpha_k^2\cdot
7524   \\{cc}\cdot\\{dd},$$
7525 because of the quantities just calculated. The values of |dd| and |ee|
7526 will not be needed after this step has been performed.
7527
7528 @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>=
7529 dd=mp_take_fraction(mp, dd,cc); lt=abs(left_tension(s)); rt=abs(right_tension(s));
7530 if ( lt!=rt ) { /* $\beta_k^{-1}\ne\alpha_k^{-1}$ */
7531   if ( lt<rt ) { 
7532     ff=mp_make_fraction(mp, lt,rt);
7533     ff=mp_take_fraction(mp, ff,ff); /* $\alpha_k^2/\beta_k^2$ */
7534     dd=mp_take_fraction(mp, dd,ff);
7535   } else { 
7536     ff=mp_make_fraction(mp, rt,lt);
7537     ff=mp_take_fraction(mp, ff,ff); /* $\beta_k^2/\alpha_k^2$ */
7538     ee=mp_take_fraction(mp, ee,ff);
7539   }
7540 }
7541 ff=mp_make_fraction(mp, ee,ee+dd)
7542
7543 @ The value of $u_{k-1}$ will be |<=1| except when $k=1$ and the previous
7544 equation was specified by a curl. In that case we must use a special
7545 method of computation to prevent overflow.
7546
7547 Fortunately, the calculations turn out to be even simpler in this ``hard''
7548 case. The curl equation makes $w_0=0$ and $v_0=-u_0\psi_1$, hence
7549 $-B_1\psi_1-A_1v_0=-(B_1-u_0A_1)\psi_1=-\\{cc}\cdot B_1\psi_1$.
7550
7551 @<Calculate the values of $v_k$ and $w_k$@>=
7552 acc=-mp_take_fraction(mp, mp->psi[k+1],mp->uu[k]);
7553 if ( right_type(r)==curl ) { 
7554   mp->ww[k]=0;
7555   mp->vv[k]=acc-mp_take_fraction(mp, mp->psi[1],fraction_one-ff);
7556 } else { 
7557   ff=mp_make_fraction(mp, fraction_one-ff,cc); /* this is
7558     $B_k/(C_k+B_k-u_{k-1}A_k)<5$ */
7559   acc=acc-mp_take_fraction(mp, mp->psi[k],ff);
7560   ff=mp_take_fraction(mp, ff,aa); /* this is $A_k/(C_k+B_k-u_{k-1}A_k)$ */
7561   mp->vv[k]=acc-mp_take_fraction(mp, mp->vv[k-1],ff);
7562   if ( mp->ww[k-1]==0 ) mp->ww[k]=0;
7563   else mp->ww[k]=-mp_take_fraction(mp, mp->ww[k-1],ff);
7564 }
7565
7566 @ When a complete cycle has been traversed, we have $\theta_k+u_k\theta\k=
7567 v_k+w_k\theta_0$, for |1<=k<=n|. We would like to determine the value of
7568 $\theta_n$ and reduce the system to the form $\theta_k+u_k\theta\k=v_k$
7569 for |0<=k<n|, so that the cyclic case can be finished up just as if there
7570 were no cycle.
7571
7572 The idea in the following code is to observe that
7573 $$\eqalign{\theta_n&=v_n+w_n\theta_0-u_n\theta_1=\cdots\cr
7574 &=v_n+w_n\theta_0-u_n\bigl(v_1+w_1\theta_0-u_1(v_2+\cdots
7575   -u_{n-2}(v_{n-1}+w_{n-1}\theta_0-u_{n-1}\theta_0))\bigr),\cr}$$
7576 so we can solve for $\theta_n=\theta_0$.
7577
7578 @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>=
7579
7580 aa=0; bb=fraction_one; /* we have |k=n| */
7581 do {  decr(k);
7582 if ( k==0 ) k=n;
7583   aa=mp->vv[k]-mp_take_fraction(mp, aa,mp->uu[k]);
7584   bb=mp->ww[k]-mp_take_fraction(mp, bb,mp->uu[k]);
7585 } while (k!=n); /* now $\theta_n=\\{aa}+\\{bb}\cdot\theta_n$ */
7586 aa=mp_make_fraction(mp, aa,fraction_one-bb);
7587 mp->theta[n]=aa; mp->vv[0]=aa;
7588 for (k=1;k<=n-1;k++) {
7589   mp->vv[k]=mp->vv[k]+mp_take_fraction(mp, aa,mp->ww[k]);
7590 }
7591 goto FOUND;
7592 }
7593
7594 @ @d reduce_angle(A) if ( abs((A))>one_eighty_deg ) {
7595   if ( (A)>0 ) (A)=(A)-three_sixty_deg; else (A)=(A)+three_sixty_deg; }
7596
7597 @<Calculate the given value of $\theta_n$...@>=
7598
7599   mp->theta[n]=left_given(s)-mp_n_arg(mp, mp->delta_x[n-1],mp->delta_y[n-1]);
7600   reduce_angle(mp->theta[n]);
7601   goto FOUND;
7602 }
7603
7604 @ @<Set up the equation for a given value of $\theta_0$@>=
7605
7606   mp->vv[0]=right_given(s)-mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7607   reduce_angle(mp->vv[0]);
7608   mp->uu[0]=0; mp->ww[0]=0;
7609 }
7610
7611 @ @<Set up the equation for a curl at $\theta_0$@>=
7612 { cc=right_curl(s); lt=abs(left_tension(t)); rt=abs(right_tension(s));
7613   if ( (rt==unity)&&(lt==unity) )
7614     mp->uu[0]=mp_make_fraction(mp, cc+cc+unity,cc+two);
7615   else 
7616     mp->uu[0]=mp_curl_ratio(mp, cc,rt,lt);
7617   mp->vv[0]=-mp_take_fraction(mp, mp->psi[1],mp->uu[0]); mp->ww[0]=0;
7618 }
7619
7620 @ @<Set up equation for a curl at $\theta_n$...@>=
7621 { cc=left_curl(s); lt=abs(left_tension(s)); rt=abs(right_tension(r));
7622   if ( (rt==unity)&&(lt==unity) )
7623     ff=mp_make_fraction(mp, cc+cc+unity,cc+two);
7624   else 
7625     ff=mp_curl_ratio(mp, cc,lt,rt);
7626   mp->theta[n]=-mp_make_fraction(mp, mp_take_fraction(mp, mp->vv[n-1],ff),
7627     fraction_one-mp_take_fraction(mp, ff,mp->uu[n-1]));
7628   goto FOUND;
7629 }
7630
7631 @ The |curl_ratio| subroutine has three arguments, which our previous notation
7632 encourages us to call $\gamma$, $\alpha^{-1}$, and $\beta^{-1}$. It is
7633 a somewhat tedious program to calculate
7634 $${(3-\alpha)\alpha^2\gamma+\beta^3\over
7635   \alpha^3\gamma+(3-\beta)\beta^2},$$
7636 with the result reduced to 4 if it exceeds 4. (This reduction of curl
7637 is necessary only if the curl and tension are both large.)
7638 The values of $\alpha$ and $\beta$ will be at most~4/3.
7639
7640 @<Declare subroutines needed by |solve_choices|@>=
7641 fraction mp_curl_ratio (MP mp,scaled gamma, scaled a_tension, 
7642                         scaled b_tension) {
7643   fraction alpha,beta,num,denom,ff; /* registers */
7644   alpha=mp_make_fraction(mp, unity,a_tension);
7645   beta=mp_make_fraction(mp, unity,b_tension);
7646   if ( alpha<=beta ) {
7647     ff=mp_make_fraction(mp, alpha,beta); ff=mp_take_fraction(mp, ff,ff);
7648     gamma=mp_take_fraction(mp, gamma,ff);
7649     beta=beta / 010000; /* convert |fraction| to |scaled| */
7650     denom=mp_take_fraction(mp, gamma,alpha)+three-beta;
7651     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7652   } else { 
7653     ff=mp_make_fraction(mp, beta,alpha); ff=mp_take_fraction(mp, ff,ff);
7654     beta=mp_take_fraction(mp, beta,ff) / 010000; /* convert |fraction| to |scaled| */
7655     denom=mp_take_fraction(mp, gamma,alpha)+(ff / 1365)-beta;
7656       /* $1365\approx 2^{12}/3$ */
7657     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7658   }
7659   if ( num>=denom+denom+denom+denom ) return fraction_four;
7660   else return mp_make_fraction(mp, num,denom);
7661 }
7662
7663 @ We're in the home stretch now.
7664
7665 @<Finish choosing angles and assigning control points@>=
7666 for (k=n-1;k>=0;k--) {
7667   mp->theta[k]=mp->vv[k]-mp_take_fraction(mp,mp->theta[k+1],mp->uu[k]);
7668 }
7669 s=p; k=0;
7670 do {  
7671   t=link(s);
7672   mp_n_sin_cos(mp, mp->theta[k]); mp->st=mp->n_sin; mp->ct=mp->n_cos;
7673   mp_n_sin_cos(mp, -mp->psi[k+1]-mp->theta[k+1]); mp->sf=mp->n_sin; mp->cf=mp->n_cos;
7674   mp_set_controls(mp, s,t,k);
7675   incr(k); s=t;
7676 } while (k!=n)
7677
7678 @ The |set_controls| routine actually puts the control points into
7679 a pair of consecutive nodes |p| and~|q|. Global variables are used to
7680 record the values of $\sin\theta$, $\cos\theta$, $\sin\phi$, and
7681 $\cos\phi$ needed in this calculation.
7682
7683 @<Glob...@>=
7684 fraction st;
7685 fraction ct;
7686 fraction sf;
7687 fraction cf; /* sines and cosines */
7688
7689 @ @<Declare subroutines needed by |solve_choices|@>=
7690 void mp_set_controls (MP mp,pointer p, pointer q, integer k) {
7691   fraction rr,ss; /* velocities, divided by thrice the tension */
7692   scaled lt,rt; /* tensions */
7693   fraction sine; /* $\sin(\theta+\phi)$ */
7694   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7695   rr=mp_velocity(mp, mp->st,mp->ct,mp->sf,mp->cf,rt);
7696   ss=mp_velocity(mp, mp->sf,mp->cf,mp->st,mp->ct,lt);
7697   if ( (right_tension(p)<0)||(left_tension(q)<0) ) {
7698     @<Decrease the velocities,
7699       if necessary, to stay inside the bounding triangle@>;
7700   }
7701   right_x(p)=x_coord(p)+mp_take_fraction(mp, 
7702                           mp_take_fraction(mp, mp->delta_x[k],mp->ct)-
7703                           mp_take_fraction(mp, mp->delta_y[k],mp->st),rr);
7704   right_y(p)=y_coord(p)+mp_take_fraction(mp, 
7705                           mp_take_fraction(mp, mp->delta_y[k],mp->ct)+
7706                           mp_take_fraction(mp, mp->delta_x[k],mp->st),rr);
7707   left_x(q)=x_coord(q)-mp_take_fraction(mp, 
7708                          mp_take_fraction(mp, mp->delta_x[k],mp->cf)+
7709                          mp_take_fraction(mp, mp->delta_y[k],mp->sf),ss);
7710   left_y(q)=y_coord(q)-mp_take_fraction(mp, 
7711                          mp_take_fraction(mp, mp->delta_y[k],mp->cf)-
7712                          mp_take_fraction(mp, mp->delta_x[k],mp->sf),ss);
7713   right_type(p)=explicit; left_type(q)=explicit;
7714 }
7715
7716 @ The boundedness conditions $\\{rr}\L\sin\phi\,/\sin(\theta+\phi)$ and
7717 $\\{ss}\L\sin\theta\,/\sin(\theta+\phi)$ are to be enforced if $\sin\theta$,
7718 $\sin\phi$, and $\sin(\theta+\phi)$ all have the same sign. Otherwise
7719 there is no ``bounding triangle.''
7720 @:at_least_}{\&{atleast} primitive@>
7721
7722 @<Decrease the velocities, if necessary...@>=
7723 if (((mp->st>=0)&&(mp->sf>=0))||((mp->st<=0)&&(mp->sf<=0)) ) {
7724   sine=mp_take_fraction(mp, abs(mp->st),mp->cf)+
7725                             mp_take_fraction(mp, abs(mp->sf),mp->ct);
7726   if ( sine>0 ) {
7727     sine=mp_take_fraction(mp, sine,fraction_one+unity); /* safety factor */
7728     if ( right_tension(p)<0 )
7729      if ( mp_ab_vs_cd(mp, abs(mp->sf),fraction_one,rr,sine)<0 )
7730       rr=mp_make_fraction(mp, abs(mp->sf),sine);
7731     if ( left_tension(q)<0 )
7732      if ( mp_ab_vs_cd(mp, abs(mp->st),fraction_one,ss,sine)<0 )
7733       ss=mp_make_fraction(mp, abs(mp->st),sine);
7734   }
7735 }
7736
7737 @ Only the simple cases remain to be handled.
7738
7739 @<Reduce to simple case of two givens and |return|@>=
7740
7741   aa=mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7742   mp_n_sin_cos(mp, right_given(p)-aa); mp->ct=mp->n_cos; mp->st=mp->n_sin;
7743   mp_n_sin_cos(mp, left_given(q)-aa); mp->cf=mp->n_cos; mp->sf=-mp->n_sin;
7744   mp_set_controls(mp, p,q,0); return;
7745 }
7746
7747 @ @<Reduce to simple case of straight line and |return|@>=
7748
7749   right_type(p)=explicit; left_type(q)=explicit;
7750   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7751   if ( rt==unity ) {
7752     if ( mp->delta_x[0]>=0 ) right_x(p)=x_coord(p)+((mp->delta_x[0]+1) / 3);
7753     else right_x(p)=x_coord(p)+((mp->delta_x[0]-1) / 3);
7754     if ( mp->delta_y[0]>=0 ) right_y(p)=y_coord(p)+((mp->delta_y[0]+1) / 3);
7755     else right_y(p)=y_coord(p)+((mp->delta_y[0]-1) / 3);
7756   } else { 
7757     ff=mp_make_fraction(mp, unity,3*rt); /* $\alpha/3$ */
7758     right_x(p)=x_coord(p)+mp_take_fraction(mp, mp->delta_x[0],ff);
7759     right_y(p)=y_coord(p)+mp_take_fraction(mp, mp->delta_y[0],ff);
7760   }
7761   if ( lt==unity ) {
7762     if ( mp->delta_x[0]>=0 ) left_x(q)=x_coord(q)-((mp->delta_x[0]+1) / 3);
7763     else left_x(q)=x_coord(q)-((mp->delta_x[0]-1) / 3);
7764     if ( mp->delta_y[0]>=0 ) left_y(q)=y_coord(q)-((mp->delta_y[0]+1) / 3);
7765     else left_y(q)=y_coord(q)-((mp->delta_y[0]-1) / 3);
7766   } else  { 
7767     ff=mp_make_fraction(mp, unity,3*lt); /* $\beta/3$ */
7768     left_x(q)=x_coord(q)-mp_take_fraction(mp, mp->delta_x[0],ff);
7769     left_y(q)=y_coord(q)-mp_take_fraction(mp, mp->delta_y[0],ff);
7770   }
7771   return;
7772 }
7773
7774 @* \[19] Measuring paths.
7775 \MP's \&{llcorner}, \&{lrcorner}, \&{ulcorner}, and \&{urcorner} operators
7776 allow the user to measure the bounding box of anything that can go into a
7777 picture.  It's easy to get rough bounds on the $x$ and $y$ extent of a path
7778 by just finding the bounding box of the knots and the control points. We
7779 need a more accurate version of the bounding box, but we can still use the
7780 easy estimate to save time by focusing on the interesting parts of the path.
7781
7782 @ Computing an accurate bounding box involves a theme that will come up again
7783 and again. Given a Bernshte{\u\i}n polynomial
7784 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
7785 $$B(z_0,z_1,\ldots,z_n;t)=\sum_k{n\choose k}t^k(1-t)^{n-k}z_k,$$
7786 we can conveniently bisect its range as follows:
7787
7788 \smallskip
7789 \textindent{1)} Let $z_k^{(0)}=z_k$, for |0<=k<=n|.
7790
7791 \smallskip
7792 \textindent{2)} Let $z_k^{(j+1)}={1\over2}(z_k^{(j)}+z\k^{(j)})$, for
7793 |0<=k<n-j|, for |0<=j<n|.
7794
7795 \smallskip\noindent
7796 Then
7797 $$B(z_0,z_1,\ldots,z_n;t)=B(z_0^{(0)},z_0^{(1)},\ldots,z_0^{(n)};2t)
7798  =B(z_0^{(n)},z_1^{(n-1)},\ldots,z_n^{(0)};2t-1).$$
7799 This formula gives us the coefficients of polynomials to use over the ranges
7800 $0\L t\L{1\over2}$ and ${1\over2}\L t\L1$.
7801
7802 @ Now here's a subroutine that's handy for all sorts of path computations:
7803 Given a quadratic polynomial $B(a,b,c;t)$, the |crossing_point| function
7804 returns the unique |fraction| value |t| between 0 and~1 at which
7805 $B(a,b,c;t)$ changes from positive to negative, or returns
7806 |t=fraction_one+1| if no such value exists. If |a<0| (so that $B(a,b,c;t)$
7807 is already negative at |t=0|), |crossing_point| returns the value zero.
7808
7809 @d no_crossing {  return (fraction_one+1); }
7810 @d one_crossing { return fraction_one; }
7811 @d zero_crossing { return 0; }
7812 @d mp_crossing_point(M,A,B,C) mp_do_crossing_point(A,B,C)
7813
7814 @c fraction mp_do_crossing_point (integer a, integer b, integer c) {
7815   integer d; /* recursive counter */
7816   integer x,xx,x0,x1,x2; /* temporary registers for bisection */
7817   if ( a<0 ) zero_crossing;
7818   if ( c>=0 ) { 
7819     if ( b>=0 ) {
7820       if ( c>0 ) { no_crossing; }
7821       else if ( (a==0)&&(b==0) ) { no_crossing;} 
7822       else { one_crossing; } 
7823     }
7824     if ( a==0 ) zero_crossing;
7825   } else if ( a==0 ) {
7826     if ( b<=0 ) zero_crossing;
7827   }
7828   @<Use bisection to find the crossing point, if one exists@>;
7829 }
7830
7831 @ The general bisection method is quite simple when $n=2$, hence
7832 |crossing_point| does not take much time. At each stage in the
7833 recursion we have a subinterval defined by |l| and~|j| such that
7834 $B(a,b,c;2^{-l}(j+t))=B(x_0,x_1,x_2;t)$, and we want to ``zero in'' on
7835 the subinterval where $x_0\G0$ and $\min(x_1,x_2)<0$.
7836
7837 It is convenient for purposes of calculation to combine the values
7838 of |l| and~|j| in a single variable $d=2^l+j$, because the operation
7839 of bisection then corresponds simply to doubling $d$ and possibly
7840 adding~1. Furthermore it proves to be convenient to modify
7841 our previous conventions for bisection slightly, maintaining the
7842 variables $X_0=2^lx_0$, $X_1=2^l(x_0-x_1)$, and $X_2=2^l(x_1-x_2)$.
7843 With these variables the conditions $x_0\ge0$ and $\min(x_1,x_2)<0$ are
7844 equivalent to $\max(X_1,X_1+X_2)>X_0\ge0$.
7845
7846 The following code maintains the invariant relations
7847 $0\L|x0|<\max(|x1|,|x1|+|x2|)$,
7848 $\vert|x1|\vert<2^{30}$, $\vert|x2|\vert<2^{30}$;
7849 it has been constructed in such a way that no arithmetic overflow
7850 will occur if the inputs satisfy
7851 $a<2^{30}$, $\vert a-b\vert<2^{30}$, and $\vert b-c\vert<2^{30}$.
7852
7853 @<Use bisection to find the crossing point...@>=
7854 d=1; x0=a; x1=a-b; x2=b-c;
7855 do {  
7856   x=half(x1+x2);
7857   if ( x1-x0>x0 ) { 
7858     x2=x; x0+=x0; d+=d;  
7859   } else { 
7860     xx=x1+x-x0;
7861     if ( xx>x0 ) { 
7862       x2=x; x0+=x0; d+=d;
7863     }  else { 
7864       x0=x0-xx;
7865       if ( x<=x0 ) { if ( x+x2<=x0 ) no_crossing; }
7866       x1=x; d=d+d+1;
7867     }
7868   }
7869 } while (d<fraction_one);
7870 return (d-fraction_one)
7871
7872 @ Here is a routine that computes the $x$ or $y$ coordinate of the point on
7873 a cubic corresponding to the |fraction| value~|t|.
7874
7875 It is convenient to define a \.{WEB} macro |t_of_the_way| such that
7876 |t_of_the_way(a,b)| expands to |a-(a-b)*t|, i.e., to |t[a,b]|.
7877
7878 @d t_of_the_way(A,B) ((A)-mp_take_fraction(mp,(A)-(B),t))
7879
7880 @c scaled mp_eval_cubic (MP mp,pointer p, pointer q, fraction t) {
7881   scaled x1,x2,x3; /* intermediate values */
7882   x1=t_of_the_way(knot_coord(p),right_coord(p));
7883   x2=t_of_the_way(right_coord(p),left_coord(q));
7884   x3=t_of_the_way(left_coord(q),knot_coord(q));
7885   x1=t_of_the_way(x1,x2);
7886   x2=t_of_the_way(x2,x3);
7887   return t_of_the_way(x1,x2);
7888 }
7889
7890 @ The actual bounding box information is stored in global variables.
7891 Since it is convenient to address the $x$ and $y$ information
7892 separately, we define arrays indexed by |x_code..y_code| and use
7893 macros to give them more convenient names.
7894
7895 @<Types...@>=
7896 enum {
7897   mp_x_code=0, /* index for |minx| and |maxx| */
7898   mp_y_code /* index for |miny| and |maxy| */
7899 };
7900
7901
7902 @d minx mp->bbmin[mp_x_code]
7903 @d maxx mp->bbmax[mp_x_code]
7904 @d miny mp->bbmin[mp_y_code]
7905 @d maxy mp->bbmax[mp_y_code]
7906
7907 @<Glob...@>=
7908 scaled bbmin[mp_y_code+1];
7909 scaled bbmax[mp_y_code+1]; 
7910 /* the result of procedures that compute bounding box information */
7911
7912 @ Now we're ready for the key part of the bounding box computation.
7913 The |bound_cubic| procedure updates |bbmin[c]| and |bbmax[c]| based on
7914 $$B(\hbox{|knot_coord(p)|}, \hbox{|right_coord(p)|},
7915     \hbox{|left_coord(q)|}, \hbox{|knot_coord(q)|};t)
7916 $$
7917 for $0<t\le1$.  In other words, the procedure adjusts the bounds to
7918 accommodate |knot_coord(q)| and any extremes over the range $0<t<1$.
7919 The |c| parameter is |x_code| or |y_code|.
7920
7921 @c void mp_bound_cubic (MP mp,pointer p, pointer q, small_number c) {
7922   boolean wavy; /* whether we need to look for extremes */
7923   scaled del1,del2,del3,del,dmax; /* proportional to the control
7924      points of a quadratic derived from a cubic */
7925   fraction t,tt; /* where a quadratic crosses zero */
7926   scaled x; /* a value that |bbmin[c]| and |bbmax[c]| must accommodate */
7927   x=knot_coord(q);
7928   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
7929   @<Check the control points against the bounding box and set |wavy:=true|
7930     if any of them lie outside@>;
7931   if ( wavy ) {
7932     del1=right_coord(p)-knot_coord(p);
7933     del2=left_coord(q)-right_coord(p);
7934     del3=knot_coord(q)-left_coord(q);
7935     @<Scale up |del1|, |del2|, and |del3| for greater accuracy;
7936       also set |del| to the first nonzero element of |(del1,del2,del3)|@>;
7937     if ( del<0 ) {
7938       negate(del1); negate(del2); negate(del3);
7939     };
7940     t=mp_crossing_point(mp, del1,del2,del3);
7941     if ( t<fraction_one ) {
7942       @<Test the extremes of the cubic against the bounding box@>;
7943     }
7944   }
7945 }
7946
7947 @ @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>=
7948 if ( x<mp->bbmin[c] ) mp->bbmin[c]=x;
7949 if ( x>mp->bbmax[c] ) mp->bbmax[c]=x
7950
7951 @ @<Check the control points against the bounding box and set...@>=
7952 wavy=true;
7953 if ( mp->bbmin[c]<=right_coord(p) )
7954   if ( right_coord(p)<=mp->bbmax[c] )
7955     if ( mp->bbmin[c]<=left_coord(q) )
7956       if ( left_coord(q)<=mp->bbmax[c] )
7957         wavy=false
7958
7959 @ If |del1=del2=del3=0|, it's impossible to obey the title of this
7960 section. We just set |del=0| in that case.
7961
7962 @<Scale up |del1|, |del2|, and |del3| for greater accuracy...@>=
7963 if ( del1!=0 ) del=del1;
7964 else if ( del2!=0 ) del=del2;
7965 else del=del3;
7966 if ( del!=0 ) {
7967   dmax=abs(del1);
7968   if ( abs(del2)>dmax ) dmax=abs(del2);
7969   if ( abs(del3)>dmax ) dmax=abs(del3);
7970   while ( dmax<fraction_half ) {
7971     dmax+=dmax; del1+=del1; del2+=del2; del3+=del3;
7972   }
7973 }
7974
7975 @ Since |crossing_point| has tried to choose |t| so that
7976 $B(|del1|,|del2|,|del3|;\tau)$ crosses zero at $\tau=|t|$ with negative
7977 slope, the value of |del2| computed below should not be positive.
7978 But rounding error could make it slightly positive in which case we
7979 must cut it to zero to avoid confusion.
7980
7981 @<Test the extremes of the cubic against the bounding box@>=
7982
7983   x=mp_eval_cubic(mp, p,q,t);
7984   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
7985   del2=t_of_the_way(del2,del3);
7986     /* now |0,del2,del3| represent the derivative on the remaining interval */
7987   if ( del2>0 ) del2=0;
7988   tt=mp_crossing_point(mp, 0,-del2,-del3);
7989   if ( tt<fraction_one ) {
7990     @<Test the second extreme against the bounding box@>;
7991   }
7992 }
7993
7994 @ @<Test the second extreme against the bounding box@>=
7995 {
7996    x=mp_eval_cubic(mp, p,q,t_of_the_way(tt,fraction_one));
7997   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
7998 }
7999
8000 @ Finding the bounding box of a path is basically a matter of applying
8001 |bound_cubic| twice for each pair of adjacent knots.
8002
8003 @c void mp_path_bbox (MP mp,pointer h) {
8004   pointer p,q; /* a pair of adjacent knots */
8005    minx=x_coord(h); miny=y_coord(h);
8006   maxx=minx; maxy=miny;
8007   p=h;
8008   do {  
8009     if ( right_type(p)==endpoint ) return;
8010     q=link(p);
8011     mp_bound_cubic(mp, x_loc(p),x_loc(q),mp_x_code);
8012     mp_bound_cubic(mp, y_loc(p),y_loc(q),mp_y_code);
8013     p=q;
8014   } while (p!=h);
8015 }
8016
8017 @ Another important way to measure a path is to find its arc length.  This
8018 is best done by using the general bisection algorithm to subdivide the path
8019 until obtaining ``well behaved'' subpaths whose arc lengths can be approximated
8020 by simple means.
8021
8022 Since the arc length is the integral with respect to time of the magnitude of
8023 the velocity, it is natural to use Simpson's rule for the approximation.
8024 @^Simpson's rule@>
8025 If $\dot B(t)$ is the spline velocity, Simpson's rule gives
8026 $$ \vb\dot B(0)\vb + 4\vb\dot B({1\over2})\vb + \vb\dot B(1)\vb \over 6 $$
8027 for the arc length of a path of length~1.  For a cubic spline
8028 $B(z_0,z_1,z_2,z_3;t)$, the time derivative $\dot B(t)$ is
8029 $3B(dz_0,dz_1,dz_2;t)$, where $dz_i=z_{i+1}-z_i$.  Hence the arc length
8030 approximation is
8031 $$ {\vb dz_0\vb \over 2} + 2\vb dz_{02}\vb + {\vb dz_2\vb \over 2}, $$
8032 where
8033 $$ dz_{02}={1\over2}\left({dz_0+dz_1\over 2}+{dz_1+dz_2\over 2}\right)$$
8034 is the result of the bisection algorithm.
8035
8036 @ The remaining problem is how to decide when a subpath is ``well behaved.''
8037 This could be done via the theoretical error bound for Simpson's rule,
8038 @^Simpson's rule@>
8039 but this is impractical because it requires an estimate of the fourth
8040 derivative of the quantity being integrated.  It is much easier to just perform
8041 a bisection step and see how much the arc length estimate changes.  Since the
8042 error for Simpson's rule is proportional to the fourth power of the sample
8043 spacing, the remaining error is typically about $1\over16$ of the amount of
8044 the change.  We say ``typically'' because the error has a pseudo-random behavior
8045 that could cause the two estimates to agree when each contain large errors.
8046
8047 To protect against disasters such as undetected cusps, the bisection process
8048 should always continue until all the $dz_i$ vectors belong to a single
8049 $90^\circ$ sector.  This ensures that no point on the spline can have velocity
8050 less than 70\% of the minimum of $\vb dz_0\vb$, $\vb dz_1\vb$ and $\vb dz_2\vb$.
8051 If such a spline happens to produce an erroneous arc length estimate that
8052 is little changed by bisection, the amount of the error is likely to be fairly
8053 small.  We will try to arrange things so that freak accidents of this type do
8054 not destroy the inverse relationship between the \&{arclength} and
8055 \&{arctime} operations.
8056 @:arclength_}{\&{arclength} primitive@>
8057 @:arctime_}{\&{arctime} primitive@>
8058
8059 @ The \&{arclength} and \&{arctime} operations are both based on a recursive
8060 @^recursion@>
8061 function that finds the arc length of a cubic spline given $dz_0$, $dz_1$,
8062 $dz_2$. This |arc_test| routine also takes an arc length goal |a_goal| and
8063 returns the time when the arc length reaches |a_goal| if there is such a time.
8064 Thus the return value is either an arc length less than |a_goal| or, if the
8065 arc length would be at least |a_goal|, it returns a time value decreased by
8066 |two|.  This allows the caller to use the sign of the result to distinguish
8067 between arc lengths and time values.  On certain types of overflow, it is
8068 possible for |a_goal| and the result of |arc_test| both to be |el_gordo|.
8069 Otherwise, the result is always less than |a_goal|.
8070
8071 Rather than halving the control point coordinates on each recursive call to
8072 |arc_test|, it is better to keep them proportional to velocity on the original
8073 curve and halve the results instead.  This means that recursive calls can
8074 potentially use larger error tolerances in their arc length estimates.  How
8075 much larger depends on to what extent the errors behave as though they are
8076 independent of each other.  To save computing time, we use optimistic assumptions
8077 and increase the tolerance by a factor of about $\sqrt2$ for each recursive
8078 call.
8079
8080 In addition to the tolerance parameter, |arc_test| should also have parameters
8081 for ${1\over3}\vb\dot B(0)\vb$, ${2\over3}\vb\dot B({1\over2})\vb$, and
8082 ${1\over3}\vb\dot B(1)\vb$.  These quantities are relatively expensive to compute
8083 and they are needed in different instances of |arc_test|.
8084
8085 @c @t\4@>@<Declare subroutines needed by |arc_test|@>;
8086 scaled mp_arc_test (MP mp, scaled dx0, scaled dy0, scaled dx1, scaled dy1, 
8087                     scaled dx2, scaled dy2, scaled  v0, scaled v02, 
8088                     scaled v2, scaled a_goal, scaled tol) {
8089   boolean simple; /* are the control points confined to a $90^\circ$ sector? */
8090   scaled dx01, dy01, dx12, dy12, dx02, dy02;  /* bisection results */
8091   scaled v002, v022;
8092     /* twice the velocity magnitudes at $t={1\over4}$ and $t={3\over4}$ */
8093   scaled arc; /* best arc length estimate before recursion */
8094   @<Other local variables in |arc_test|@>;
8095   @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,
8096     |dx2|, |dy2|@>;
8097   @<Initialize |v002|, |v022|, and the arc length estimate |arc|; if it overflows
8098     set |arc_test| and |return|@>;
8099   @<Test if the control points are confined to one quadrant or rotating them
8100     $45^\circ$ would put them in one quadrant.  Then set |simple| appropriately@>;
8101   if ( simple && (abs(arc-v02-halfp(v0+v2)) <= tol) ) {
8102     if ( arc < a_goal ) {
8103       return arc;
8104     } else {
8105        @<Estimate when the arc length reaches |a_goal| and set |arc_test| to
8106          that time minus |two|@>;
8107     }
8108   } else {
8109     @<Use one or two recursive calls to compute the |arc_test| function@>;
8110   }
8111 }
8112
8113 @ The |tol| value should by multiplied by $\sqrt 2$ before making recursive
8114 calls, but $1.5$ is an adequate approximation.  It is best to avoid using
8115 |make_fraction| in this inner loop.
8116 @^inner loop@>
8117
8118 @<Use one or two recursive calls to compute the |arc_test| function@>=
8119
8120   @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is as
8121     large as possible@>;
8122   tol = tol + halfp(tol);
8123   a = mp_arc_test(mp, dx0,dy0, dx01,dy01, dx02,dy02, v0, v002, 
8124                   halfp(v02), a_new, tol);
8125   if ( a<0 )  {
8126      return (-halfp(two-a));
8127   } else { 
8128     @<Update |a_new| to reduce |a_new+a_aux| by |a|@>;
8129     b = mp_arc_test(mp, dx02,dy02, dx12,dy12, dx2,dy2,
8130                     halfp(v02), v022, v2, a_new, tol);
8131     if ( b<0 )  
8132       return (-halfp(-b) - half_unit);
8133     else  
8134       return (a + half(b-a));
8135   }
8136 }
8137
8138 @ @<Other local variables in |arc_test|@>=
8139 scaled a,b; /* results of recursive calls */
8140 scaled a_new,a_aux; /* the sum of these gives the |a_goal| */
8141
8142 @ @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is...@>=
8143 a_aux = el_gordo - a_goal;
8144 if ( a_goal > a_aux ) {
8145   a_aux = a_goal - a_aux;
8146   a_new = el_gordo;
8147 } else { 
8148   a_new = a_goal + a_goal;
8149   a_aux = 0;
8150 }
8151
8152 @ There is no need to maintain |a_aux| at this point so we use it as a temporary
8153 to force the additions and subtractions to be done in an order that avoids
8154 overflow.
8155
8156 @<Update |a_new| to reduce |a_new+a_aux| by |a|@>=
8157 if ( a > a_aux ) {
8158   a_aux = a_aux - a;
8159   a_new = a_new + a_aux;
8160 }
8161
8162 @ This code assumes all {\it dx} and {\it dy} variables have magnitude less than
8163 |fraction_four|.  To simplify the rest of the |arc_test| routine, we strengthen
8164 this assumption by requiring the norm of each $({\it dx},{\it dy})$ pair to obey
8165 this bound.  Note that recursive calls will maintain this invariant.
8166
8167 @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,...@>=
8168 dx01 = half(dx0 + dx1);
8169 dx12 = half(dx1 + dx2);
8170 dx02 = half(dx01 + dx12);
8171 dy01 = half(dy0 + dy1);
8172 dy12 = half(dy1 + dy2);
8173 dy02 = half(dy01 + dy12)
8174
8175 @ We should be careful to keep |arc<el_gordo| so that calling |arc_test| with
8176 |a_goal=el_gordo| is guaranteed to yield the arc length.
8177
8178 @<Initialize |v002|, |v022|, and the arc length estimate |arc|;...@>=
8179 v002 = mp_pyth_add(mp, dx01+half(dx0+dx02), dy01+half(dy0+dy02));
8180 v022 = mp_pyth_add(mp, dx12+half(dx02+dx2), dy12+half(dy02+dy2));
8181 tmp = halfp(v02+2);
8182 arc1 = v002 + half(halfp(v0+tmp) - v002);
8183 arc = v022 + half(halfp(v2+tmp) - v022);
8184 if ( (arc < el_gordo-arc1) )  {
8185   arc = arc+arc1;
8186 } else { 
8187   mp->arith_error = true;
8188   if ( a_goal==el_gordo )  return (el_gordo);
8189   else return (-two);
8190 }
8191
8192 @ @<Other local variables in |arc_test|@>=
8193 scaled tmp, tmp2; /* all purpose temporary registers */
8194 scaled arc1; /* arc length estimate for the first half */
8195
8196 @ @<Test if the control points are confined to one quadrant or rotating...@>=
8197 simple = ((dx0>=0) && (dx1>=0) && (dx2>=0)) ||
8198          ((dx0<=0) && (dx1<=0) && (dx2<=0));
8199 if ( simple )
8200   simple = ((dy0>=0) && (dy1>=0) && (dy2>=0)) ||
8201            ((dy0<=0) && (dy1<=0) && (dy2<=0));
8202 if ( ! simple ) {
8203   simple = ((dx0>=dy0) && (dx1>=dy1) && (dx2>=dy2)) ||
8204            ((dx0<=dy0) && (dx1<=dy1) && (dx2<=dy2));
8205   if ( simple ) 
8206     simple = ((-dx0>=dy0) && (-dx1>=dy1) && (-dx2>=dy2)) ||
8207              ((-dx0<=dy0) && (-dx1<=dy1) && (-dx2<=dy2));
8208 }
8209
8210 @ Since Simpson's rule is based on approximating the integrand by a parabola,
8211 @^Simpson's rule@>
8212 it is appropriate to use the same approximation to decide when the integral
8213 reaches the intermediate value |a_goal|.  At this point
8214 $$\eqalign{
8215     {\vb\dot B(0)\vb\over 3} &= \hbox{|v0|}, \qquad
8216     {\vb\dot B({1\over4})\vb\over 3} = {\hbox{|v002|}\over 2}, \qquad
8217     {\vb\dot B({1\over2})\vb\over 3} = {\hbox{|v02|}\over 2}, \cr
8218     {\vb\dot B({3\over4})\vb\over 3} &= {\hbox{|v022|}\over 2}, \qquad
8219     {\vb\dot B(1)\vb\over 3} = \hbox{|v2|} \cr
8220 }
8221 $$
8222 and
8223 $$ {\vb\dot B(t)\vb\over 3} \approx
8224   \cases{B\left(\hbox{|v0|},
8225       \hbox{|v002|}-{1\over 2}\hbox{|v0|}-{1\over 4}\hbox{|v02|},
8226       {1\over 2}\hbox{|v02|}; 2t \right)&
8227     if $t\le{1\over 2}$\cr
8228   B\left({1\over 2}\hbox{|v02|},
8229       \hbox{|v022|}-{1\over 4}\hbox{|v02|}-{1\over 2}\hbox{|v2|},
8230       \hbox{|v2|}; 2t-1 \right)&
8231     if $t\ge{1\over 2}$.\cr}
8232  \eqno (*)
8233 $$
8234 We can integrate $\vb\dot B(t)\vb$ by using
8235 $$\int 3B(a,b,c;\tau)\,dt =
8236   {B(0,a,a+b,a+b+c;\tau) + {\rm constant} \over {d\tau\over dt}}.
8237 $$
8238
8239 This construction allows us to find the time when the arc length reaches
8240 |a_goal| by solving a cubic equation of the form
8241 $$ B(0,a,a+b,a+b+c;\tau) = x, $$
8242 where $\tau$ is $2t$ or $2t+1$, $x$ is |a_goal| or |a_goal-arc1|, and $a$, $b$,
8243 and $c$ are the Bernshte{\u\i}n coefficients from $(*)$ divided by
8244 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
8245 $d\tau\over dt$.  We shall define a function |solve_rising_cubic| that finds
8246 $\tau$ given $a$, $b$, $c$, and $x$.
8247
8248 @<Estimate when the arc length reaches |a_goal| and set |arc_test| to...@>=
8249
8250   tmp = (v02 + 2) / 4;
8251   if ( a_goal<=arc1 ) {
8252     tmp2 = halfp(v0);
8253     return 
8254       (halfp(mp_solve_rising_cubic(mp, tmp2, arc1-tmp2-tmp, tmp, a_goal))- two);
8255   } else { 
8256     tmp2 = halfp(v2);
8257     return ((half_unit - two) +
8258       halfp(mp_solve_rising_cubic(mp, tmp, arc-arc1-tmp-tmp2, tmp2, a_goal-arc1)));
8259   }
8260 }
8261
8262 @ Here is the |solve_rising_cubic| routine that finds the time~$t$ when
8263 $$ B(0, a, a+b, a+b+c; t) = x. $$
8264 This routine is based on |crossing_point| but is simplified by the
8265 assumptions that $B(a,b,c;t)\ge0$ for $0\le t\le1$ and that |0<=x<=a+b+c|.
8266 If rounding error causes this condition to be violated slightly, we just ignore
8267 it and proceed with binary search.  This finds a time when the function value
8268 reaches |x| and the slope is positive.
8269
8270 @<Declare subroutines needed by |arc_test|@>=
8271 scaled mp_solve_rising_cubic (MP mp,scaled a, scaled b,  scaled c, scaled x) {
8272   scaled ab, bc, ac; /* bisection results */
8273   integer t; /* $2^k+q$ where unscaled answer is in $[q2^{-k},(q+1)2^{-k})$ */
8274   integer xx; /* temporary for updating |x| */
8275   if ( (a<0) || (c<0) ) mp_confusion(mp, "rising?");
8276 @:this can't happen rising?}{\quad rising?@>
8277   if ( x<=0 ) {
8278         return 0;
8279   } else if ( x >= a+b+c ) {
8280     return unity;
8281   } else { 
8282     t = 1;
8283     @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than
8284       |el_gordo div 3|@>;
8285     do {  
8286       t+=t;
8287       @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>;
8288       xx = x - a - ab - ac;
8289       if ( xx < -x ) { x+=x; b=ab; c=ac;  }
8290       else { x = x + xx;  a=ac; b=mp->bc; t = t+1; };
8291     } while (t < unity);
8292     return (t - unity);
8293   }
8294 }
8295
8296 @ @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>=
8297 ab = half(a+b);
8298 bc = half(b+c);
8299 ac = half(ab+bc)
8300
8301 @ @d one_third_el_gordo 05252525252 /* upper bound on |a|, |b|, and |c| */
8302
8303 @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than...@>=
8304 while ((a>one_third_el_gordo)||(b>one_third_el_gordo)||(c>one_third_el_gordo)) { 
8305   a = halfp(a);
8306   b = half(b);
8307   c = halfp(c);
8308   x = halfp(x);
8309 }
8310
8311 @ It is convenient to have a simpler interface to |arc_test| that requires no
8312 unnecessary arguments and ensures that each $({\it dx},{\it dy})$ pair has
8313 length less than |fraction_four|.
8314
8315 @d arc_tol   16  /* quit when change in arc length estimate reaches this */
8316
8317 @c scaled mp_do_arc_test (MP mp,scaled dx0, scaled dy0, scaled dx1, 
8318                           scaled dy1, scaled dx2, scaled dy2, scaled a_goal) {
8319   scaled v0,v1,v2; /* length of each $({\it dx},{\it dy})$ pair */
8320   scaled v02; /* twice the norm of the quadratic at $t={1\over2}$ */
8321   v0 = mp_pyth_add(mp, dx0,dy0);
8322   v1 = mp_pyth_add(mp, dx1,dy1);
8323   v2 = mp_pyth_add(mp, dx2,dy2);
8324   if ( (v0>=fraction_four) || (v1>=fraction_four) || (v2>=fraction_four) ) { 
8325     mp->arith_error = true;
8326     if ( a_goal==el_gordo )  return el_gordo;
8327     else return (-two);
8328   } else { 
8329     v02 = mp_pyth_add(mp, dx1+half(dx0+dx2), dy1+half(dy0+dy2));
8330     return (mp_arc_test(mp, dx0,dy0, dx1,dy1, dx2,dy2,
8331                                  v0, v02, v2, a_goal, arc_tol));
8332   }
8333 }
8334
8335 @ Now it is easy to find the arc length of an entire path.
8336
8337 @c scaled mp_get_arc_length (MP mp,pointer h) {
8338   pointer p,q; /* for traversing the path */
8339   scaled a,a_tot; /* current and total arc lengths */
8340   a_tot = 0;
8341   p = h;
8342   while ( right_type(p)!=endpoint ){ 
8343     q = link(p);
8344     a = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8345       left_x(q)-right_x(p), left_y(q)-right_y(p),
8346       x_coord(q)-left_x(q), y_coord(q)-left_y(q), el_gordo);
8347     a_tot = mp_slow_add(mp, a, a_tot);
8348     if ( q==h ) break;  else p=q;
8349   }
8350   check_arith;
8351   return a_tot;
8352 }
8353
8354 @ The inverse operation of finding the time on a path~|h| when the arc length
8355 reaches some value |arc0| can also be accomplished via |do_arc_test|.  Some care
8356 is required to handle very large times or negative times on cyclic paths.  For
8357 non-cyclic paths, |arc0| values that are negative or too large cause
8358 |get_arc_time| to return 0 or the length of path~|h|.
8359
8360 If |arc0| is greater than the arc length of a cyclic path~|h|, the result is a
8361 time value greater than the length of the path.  Since it could be much greater,
8362 we must be prepared to compute the arc length of path~|h| and divide this into
8363 |arc0| to find how many multiples of the length of path~|h| to add.
8364
8365 @c scaled mp_get_arc_time (MP mp,pointer h, scaled  arc0) {
8366   pointer p,q; /* for traversing the path */
8367   scaled t_tot; /* accumulator for the result */
8368   scaled t; /* the result of |do_arc_test| */
8369   scaled arc; /* portion of |arc0| not used up so far */
8370   integer n; /* number of extra times to go around the cycle */
8371   if ( arc0<0 ) {
8372     @<Deal with a negative |arc0| value and |return|@>;
8373   }
8374   if ( arc0==el_gordo ) decr(arc0);
8375   t_tot = 0;
8376   arc = arc0;
8377   p = h;
8378   while ( (right_type(p)!=endpoint) && (arc>0) ) {
8379     q = link(p);
8380     t = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8381       left_x(q)-right_x(p), left_y(q)-right_y(p),
8382       x_coord(q)-left_x(q), y_coord(q)-left_y(q), arc);
8383     @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>;
8384     if ( q==h ) {
8385       @<Update |t_tot| and |arc| to avoid going around the cyclic
8386         path too many times but set |arith_error:=true| and |goto done| on
8387         overflow@>;
8388     }
8389     p = q;
8390   }
8391   check_arith;
8392   return t_tot;
8393 }
8394
8395 @ @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>=
8396 if ( t<0 ) { t_tot = t_tot + t + two;  arc = 0;  }
8397 else { t_tot = t_tot + unity;  arc = arc - t;  }
8398
8399 @ @<Deal with a negative |arc0| value and |return|@>=
8400
8401   if ( left_type(h)==endpoint ) {
8402     t_tot=0;
8403   } else { 
8404     p = mp_htap_ypoc(mp, h);
8405     t_tot = -mp_get_arc_time(mp, p, -arc0);
8406     mp_toss_knot_list(mp, p);
8407   }
8408   check_arith;
8409   return t_tot;
8410 }
8411
8412 @ @<Update |t_tot| and |arc| to avoid going around the cyclic...@>=
8413 if ( arc>0 ) { 
8414   n = arc / (arc0 - arc);
8415   arc = arc - n*(arc0 - arc);
8416   if ( t_tot > el_gordo / (n+1) ) { 
8417     mp->arith_error = true;
8418     t_tot = el_gordo;
8419     break;
8420   }
8421   t_tot = (n + 1)*t_tot;
8422 }
8423
8424 @* \[20] Data structures for pens.
8425 A Pen in \MP\ can be either elliptical or polygonal.  Elliptical pens result
8426 in \ps\ \&{stroke} commands, while anything drawn with a polygonal pen is
8427 @:stroke}{\&{stroke} command@>
8428 converted into an area fill as described in the next part of this program.
8429 The mathematics behind this process is based on simple aspects of the theory
8430 of tracings developed by Leo Guibas, Lyle Ramshaw, and Jorge Stolfi
8431 [``A kinematic framework for computational geometry,'' Proc.\ IEEE Symp.\
8432 Foundations of Computer Science {\bf 24} (1983), 100--111].
8433
8434 Polygonal pens are created from paths via \MP's \&{makepen} primitive.
8435 @:makepen_}{\&{makepen} primitive@>
8436 This path representation is almost sufficient for our purposes except that
8437 a pen path should always be a convex polygon with the vertices in
8438 counter-clockwise order.
8439 Since we will need to scan pen polygons both forward and backward, a pen
8440 should be represented as a doubly linked ring of knot nodes.  There is
8441 room for the extra back pointer because we do not need the
8442 |left_type| or |right_type| fields.  In fact, we don't need the |left_x|,
8443 |left_y|, |right_x|, or |right_y| fields either but we leave these alone
8444 so that certain procedures can operate on both pens and paths.  In particular,
8445 pens can be copied using |copy_path| and recycled using |toss_knot_list|.
8446
8447 @d knil info
8448   /* this replaces the |left_type| and |right_type| fields in a pen knot */
8449
8450 @ The |make_pen| procedure turns a path into a pen by initializing
8451 the |knil| pointers and making sure the knots form a convex polygon.
8452 Thus each cubic in the given path becomes a straight line and the control
8453 points are ignored.  If the path is not cyclic, the ends are connected by a
8454 straight line.
8455
8456 @d copy_pen(A) mp_make_pen(mp, mp_copy_path(mp, (A)),false)
8457
8458 @c @<Declare a function called |convex_hull|@>;
8459 pointer mp_make_pen (MP mp,pointer h, boolean need_hull) {
8460   pointer p,q; /* two consecutive knots */
8461   q=h;
8462   do {  
8463     p=q; q=link(q);
8464     knil(q)=p;
8465   } while (q!=h);
8466   if ( need_hull ){ 
8467     h=mp_convex_hull(mp, h);
8468     @<Make sure |h| isn't confused with an elliptical pen@>;
8469   }
8470   return h;
8471 }
8472
8473 @ The only information required about an elliptical pen is the overall
8474 transformation that has been applied to the original \&{pencircle}.
8475 @:pencircle_}{\&{pencircle} primitive@>
8476 Since it suffices to keep track of how the three points $(0,0)$, $(1,0)$,
8477 and $(0,1)$ are transformed, an elliptical pen can be stored in a single
8478 knot node and transformed as if it were a path.
8479
8480 @d pen_is_elliptical(A) ((A)==link((A)))
8481
8482 @c pointer mp_get_pen_circle (MP mp,scaled diam) {
8483   pointer h; /* the knot node to return */
8484   h=mp_get_node(mp, knot_node_size);
8485   link(h)=h; knil(h)=h;
8486   originator(h)=program_code;
8487   x_coord(h)=0; y_coord(h)=0;
8488   left_x(h)=diam; left_y(h)=0;
8489   right_x(h)=0; right_y(h)=diam;
8490   return h;
8491 }
8492
8493 @ If the polygon being returned by |make_pen| has only one vertex, it will
8494 be interpreted as an elliptical pen.  This is no problem since a degenerate
8495 polygon can equally well be thought of as a degenerate ellipse.  We need only
8496 initialize the |left_x|, |left_y|, |right_x|, and |right_y| fields.
8497
8498 @<Make sure |h| isn't confused with an elliptical pen@>=
8499 if ( pen_is_elliptical( h) ){ 
8500   left_x(h)=x_coord(h); left_y(h)=y_coord(h);
8501   right_x(h)=x_coord(h); right_y(h)=y_coord(h);
8502 }
8503
8504 @ We have to cheat a little here but most operations on pens only use
8505 the first three words in each knot node.
8506 @^data structure assumptions@>
8507
8508 @<Initialize a pen at |test_pen| so that it fits in nine words@>=
8509 x_coord(test_pen)=-half_unit;
8510 y_coord(test_pen)=0;
8511 x_coord(test_pen+3)=half_unit;
8512 y_coord(test_pen+3)=0;
8513 x_coord(test_pen+6)=0;
8514 y_coord(test_pen+6)=unity;
8515 link(test_pen)=test_pen+3;
8516 link(test_pen+3)=test_pen+6;
8517 link(test_pen+6)=test_pen;
8518 knil(test_pen)=test_pen+6;
8519 knil(test_pen+3)=test_pen;
8520 knil(test_pen+6)=test_pen+3
8521
8522 @ Printing a polygonal pen is very much like printing a path
8523
8524 @<Declare subroutines for printing expressions@>=
8525 void mp_pr_pen (MP mp,pointer h) {
8526   pointer p,q; /* for list traversal */
8527   if ( pen_is_elliptical(h) ) {
8528     @<Print the elliptical pen |h|@>;
8529   } else { 
8530     p=h;
8531     do {  
8532       mp_print_two(mp, x_coord(p),y_coord(p));
8533       mp_print_nl(mp, " .. ");
8534       @<Advance |p| making sure the links are OK and |return| if there is
8535         a problem@>;
8536      } while (p!=h);
8537      mp_print(mp, "cycle");
8538   }
8539 }
8540
8541 @ @<Advance |p| making sure the links are OK and |return| if there is...@>=
8542 q=link(p);
8543 if ( (q==null) || (knil(q)!=p) ) { 
8544   mp_print_nl(mp, "???"); return; /* this won't happen */
8545 @.???@>
8546 }
8547 p=q
8548
8549 @ @<Print the elliptical pen |h|@>=
8550
8551 mp_print(mp, "pencircle transformed (");
8552 mp_print_scaled(mp, x_coord(h));
8553 mp_print_char(mp, ',');
8554 mp_print_scaled(mp, y_coord(h));
8555 mp_print_char(mp, ',');
8556 mp_print_scaled(mp, left_x(h)-x_coord(h));
8557 mp_print_char(mp, ',');
8558 mp_print_scaled(mp, right_x(h)-x_coord(h));
8559 mp_print_char(mp, ',');
8560 mp_print_scaled(mp, left_y(h)-y_coord(h));
8561 mp_print_char(mp, ',');
8562 mp_print_scaled(mp, right_y(h)-y_coord(h));
8563 mp_print_char(mp, ')');
8564 }
8565
8566 @ Here us another version of |pr_pen| that prints the pen as a diagnostic
8567 message.
8568
8569 @<Declare subroutines for printing expressions@>=
8570 void mp_print_pen (MP mp,pointer h, char *s, boolean nuline) { 
8571   mp_print_diagnostic(mp, "Pen",s,nuline); mp_print_ln(mp);
8572 @.Pen at line...@>
8573   mp_pr_pen(mp, h);
8574   mp_end_diagnostic(mp, true);
8575 }
8576
8577 @ Making a polygonal pen into a path involves restoring the |left_type| and
8578 |right_type| fields and setting the control points so as to make a polygonal
8579 path.
8580
8581 @c 
8582 void mp_make_path (MP mp,pointer h) {
8583   pointer p; /* for traversing the knot list */
8584   small_number k; /* a loop counter */
8585   @<Other local variables in |make_path|@>;
8586   if ( pen_is_elliptical(h) ) {
8587     @<Make the elliptical pen |h| into a path@>;
8588   } else { 
8589     p=h;
8590     do {  
8591       left_type(p)=explicit;
8592       right_type(p)=explicit;
8593       @<copy the coordinates of knot |p| into its control points@>;
8594        p=link(p);
8595     } while (p!=h);
8596   }
8597 }
8598
8599 @ @<copy the coordinates of knot |p| into its control points@>=
8600 left_x(p)=x_coord(p);
8601 left_y(p)=y_coord(p);
8602 right_x(p)=x_coord(p);
8603 right_y(p)=y_coord(p)
8604
8605 @ We need an eight knot path to get a good approximation to an ellipse.
8606
8607 @<Make the elliptical pen |h| into a path@>=
8608
8609   @<Extract the transformation parameters from the elliptical pen~|h|@>;
8610   p=h;
8611   for (k=0;k<=7;k++ ) { 
8612     @<Initialize |p| as the |k|th knot of a circle of unit diameter,
8613       transforming it appropriately@>;
8614     if ( k==7 ) link(p)=h;  else link(p)=mp_get_node(mp, knot_node_size);
8615     p=link(p);
8616   }
8617 }
8618
8619 @ @<Extract the transformation parameters from the elliptical pen~|h|@>=
8620 center_x=x_coord(h);
8621 center_y=y_coord(h);
8622 width_x=left_x(h)-center_x;
8623 width_y=left_y(h)-center_y;
8624 height_x=right_x(h)-center_x;
8625 height_y=right_y(h)-center_y
8626
8627 @ @<Other local variables in |make_path|@>=
8628 scaled center_x,center_y; /* translation parameters for an elliptical pen */
8629 scaled width_x,width_y; /* the effect of a unit change in $x$ */
8630 scaled height_x,height_y; /* the effect of a unit change in $y$ */
8631 scaled dx,dy; /* the vector from knot |p| to its right control point */
8632 integer kk;
8633   /* |k| advanced $270^\circ$ around the ring (cf. $\sin\theta=\cos(\theta+270)$) */
8634
8635 @ The only tricky thing here are the tables |half_cos| and |d_cos| used to
8636 find the point $k/8$ of the way around the circle and the direction vector
8637 to use there.
8638
8639 @<Initialize |p| as the |k|th knot of a circle of unit diameter,...@>=
8640 kk=(k+6)% 8;
8641 x_coord(p)=center_x+mp_take_fraction(mp, mp->half_cos[k],width_x)
8642            +mp_take_fraction(mp, mp->half_cos[kk],height_x);
8643 y_coord(p)=center_y+mp_take_fraction(mp, mp->half_cos[k],width_y)
8644            +mp_take_fraction(mp, mp->half_cos[kk],height_y);
8645 dx=-mp_take_fraction(mp, mp->d_cos[kk],width_x)
8646    +mp_take_fraction(mp, mp->d_cos[k],height_x);
8647 dy=-mp_take_fraction(mp, mp->d_cos[kk],width_y)
8648    +mp_take_fraction(mp, mp->d_cos[k],height_y);
8649 right_x(p)=x_coord(p)+dx;
8650 right_y(p)=y_coord(p)+dy;
8651 left_x(p)=x_coord(p)-dx;
8652 left_y(p)=y_coord(p)-dy;
8653 left_type(p)=explicit;
8654 right_type(p)=explicit;
8655 originator(p)=program_code
8656
8657 @ @<Glob...@>=
8658 fraction half_cos[8]; /* ${1\over2}\cos(45k)$ */
8659 fraction d_cos[8]; /* a magic constant times $\cos(45k)$ */
8660
8661 @ The magic constant for |d_cos| is the distance between $({1\over2},0)$ and
8662 $({1\over4}\sqrt2,{1\over4}\sqrt2)$ times the result of the |velocity|
8663 function for $\theta=\phi=22.5^\circ$.  This comes out to be
8664 $$ d = {\sqrt{2-\sqrt2}\over 3+3\cos22.5^\circ}
8665   \approx 0.132608244919772.
8666 $$
8667
8668 @<Set init...@>=
8669 mp->half_cos[0]=fraction_half;
8670 mp->half_cos[1]=94906266; /* $2^{26}\sqrt2\approx94906265.62$ */
8671 mp->half_cos[2]=0;
8672 mp->d_cos[0]=35596755; /* $2^{28}d\approx35596754.69$ */
8673 mp->d_cos[1]=25170707; /* $2^{27}\sqrt2\,d\approx25170706.63$ */
8674 mp->d_cos[2]=0;
8675 for (k=3;k<= 4;k++ ) { 
8676   mp->half_cos[k]=-mp->half_cos[4-k];
8677   mp->d_cos[k]=-mp->d_cos[4-k];
8678 }
8679 for (k=5;k<= 7;k++ ) { 
8680   mp->half_cos[k]=mp->half_cos[8-k];
8681   mp->d_cos[k]=mp->d_cos[8-k];
8682 }
8683
8684 @ The |convex_hull| function forces a pen polygon to be convex when it is
8685 returned by |make_pen| and after any subsequent transformation where rounding
8686 error might allow the convexity to be lost.
8687 The convex hull algorithm used here is described by F.~P. Preparata and
8688 M.~I. Shamos [{\sl Computational Geometry}, Springer-Verlag, 1985].
8689
8690 @<Declare a function called |convex_hull|@>=
8691 @<Declare a procedure called |move_knot|@>;
8692 pointer mp_convex_hull (MP mp,pointer h) { /* Make a polygonal pen convex */
8693   pointer l,r; /* the leftmost and rightmost knots */
8694   pointer p,q; /* knots being scanned */
8695   pointer s; /* the starting point for an upcoming scan */
8696   scaled dx,dy; /* a temporary pointer */
8697   if ( pen_is_elliptical(h) ) {
8698      return h;
8699   } else { 
8700     @<Set |l| to the leftmost knot in polygon~|h|@>;
8701     @<Set |r| to the rightmost knot in polygon~|h|@>;
8702     if ( l!=r ) { 
8703       s=link(r);
8704       @<Find any knots on the path from |l| to |r| above the |l|-|r| line and
8705         move them past~|r|@>;
8706       @<Find any knots on the path from |s| to |l| below the |l|-|r| line and
8707         move them past~|l|@>;
8708       @<Sort the path from |l| to |r| by increasing $x$@>;
8709       @<Sort the path from |r| to |l| by decreasing $x$@>;
8710     }
8711     if ( l!=link(l) ) {
8712       @<Do a Gramm scan and remove vertices where there is no left turn@>;
8713     }
8714     return l;
8715   }
8716 }
8717
8718 @ All comparisons are done primarily on $x$ and secondarily on $y$.
8719
8720 @<Set |l| to the leftmost knot in polygon~|h|@>=
8721 l=h;
8722 p=link(h);
8723 while ( p!=h ) { 
8724   if ( x_coord(p)<=x_coord(l) )
8725     if ( (x_coord(p)<x_coord(l)) || (y_coord(p)<y_coord(l)) )
8726       l=p;
8727   p=link(p);
8728 }
8729
8730 @ @<Set |r| to the rightmost knot in polygon~|h|@>=
8731 r=h;
8732 p=link(h);
8733 while ( p!=h ) { 
8734   if ( x_coord(p)>=x_coord(r) )
8735     if ( (x_coord(p)>x_coord(r)) || (y_coord(p)>y_coord(r)) )
8736       r=p;
8737   p=link(p);
8738 }
8739
8740 @ @<Find any knots on the path from |l| to |r| above the |l|-|r| line...@>=
8741 dx=x_coord(r)-x_coord(l);
8742 dy=y_coord(r)-y_coord(l);
8743 p=link(l);
8744 while ( p!=r ) { 
8745   q=link(p);
8746   if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))>0 )
8747     mp_move_knot(mp, p, r);
8748   p=q;
8749 }
8750
8751 @ The |move_knot| procedure removes |p| from a doubly linked list and inserts
8752 it after |q|.
8753
8754 @ @<Declare a procedure called |move_knot|@>=
8755 void mp_move_knot (MP mp,pointer p, pointer q) { 
8756   link(knil(p))=link(p);
8757   knil(link(p))=knil(p);
8758   knil(p)=q;
8759   link(p)=link(q);
8760   link(q)=p;
8761   knil(link(p))=p;
8762 }
8763
8764 @ @<Find any knots on the path from |s| to |l| below the |l|-|r| line...@>=
8765 p=s;
8766 while ( p!=l ) { 
8767   q=link(p);
8768   if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))<0 )
8769     mp_move_knot(mp, p,l);
8770   p=q;
8771 }
8772
8773 @ The list is likely to be in order already so we just do linear insertions.
8774 Secondary comparisons on $y$ ensure that the sort is consistent with the
8775 choice of |l| and |r|.
8776
8777 @<Sort the path from |l| to |r| by increasing $x$@>=
8778 p=link(l);
8779 while ( p!=r ) { 
8780   q=knil(p);
8781   while ( x_coord(q)>x_coord(p) ) q=knil(q);
8782   while ( x_coord(q)==x_coord(p) ) {
8783     if ( y_coord(q)>y_coord(p) ) q=knil(q); else break;
8784   }
8785   if ( q==knil(p) ) p=link(p);
8786   else { p=link(p); mp_move_knot(mp, knil(p),q); };
8787 }
8788
8789 @ @<Sort the path from |r| to |l| by decreasing $x$@>=
8790 p=link(r);
8791 while ( p!=l ){ 
8792   q=knil(p);
8793   while ( x_coord(q)<x_coord(p) ) q=knil(q);
8794   while ( x_coord(q)==x_coord(p) ) {
8795     if ( y_coord(q)<y_coord(p) ) q=knil(q); else break;
8796   }
8797   if ( q==knil(p) ) p=link(p);
8798   else { p=link(p); mp_move_knot(mp, knil(p),q); };
8799 }
8800
8801 @ The condition involving |ab_vs_cd| tests if there is not a left turn
8802 at knot |q|.  There usually will be a left turn so we streamline the case
8803 where the |then| clause is not executed.
8804
8805 @<Do a Gramm scan and remove vertices where there...@>=
8806
8807 p=l; q=link(l);
8808 while (1) { 
8809   dx=x_coord(q)-x_coord(p);
8810   dy=y_coord(q)-y_coord(p);
8811   p=q; q=link(q);
8812   if ( p==l ) break;
8813   if ( p!=r )
8814     if ( mp_ab_vs_cd(mp, dx,y_coord(q)-y_coord(p),dy,x_coord(q)-x_coord(p))<=0 ) {
8815       @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>;
8816     }
8817   }
8818 }
8819
8820 @ @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>=
8821
8822 s=knil(p);
8823 mp_free_node(mp, p,knot_node_size);
8824 link(s)=q; knil(q)=s;
8825 if ( s==l ) p=s;
8826 else { p=knil(s); q=s; };
8827 }
8828
8829 @ The |find_offset| procedure sets global variables |(cur_x,cur_y)| to the
8830 offset associated with the given direction |(x,y)|.  If two different offsets
8831 apply, it chooses one of them.
8832
8833 @c 
8834 void mp_find_offset (MP mp,scaled x, scaled y, pointer h) {
8835   pointer p,q; /* consecutive knots */
8836   scaled wx,wy,hx,hy;
8837   /* the transformation matrix for an elliptical pen */
8838   fraction xx,yy; /* untransformed offset for an elliptical pen */
8839   fraction d; /* a temporary register */
8840   if ( pen_is_elliptical(h) ) {
8841     @<Find the offset for |(x,y)| on the elliptical pen~|h|@>
8842   } else { 
8843     q=h;
8844     do {  
8845       p=q; q=link(q);
8846     } while (! mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)>=0);
8847     do {  
8848       p=q; q=link(q);
8849     } while (! mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)<=0);
8850     mp->cur_x=x_coord(p);
8851     mp->cur_y=y_coord(p);
8852   }
8853 }
8854
8855 @ @<Glob...@>=
8856 scaled cur_x;
8857 scaled cur_y; /* all-purpose return value registers */
8858
8859 @ @<Find the offset for |(x,y)| on the elliptical pen~|h|@>=
8860 if ( (x==0) && (y==0) ) {
8861   mp->cur_x=x_coord(h); mp->cur_y=y_coord(h);  
8862 } else { 
8863   @<Find the non-constant part of the transformation for |h|@>;
8864   while ( (abs(x)<fraction_half) && (abs(y)<fraction_half) ){ 
8865     x+=x; y+=y;  
8866   };
8867   @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the
8868     untransformed version of |(x,y)|@>;
8869   mp->cur_x=x_coord(h)+mp_take_fraction(mp, xx,wx)+mp_take_fraction(mp, yy,hx);
8870   mp->cur_y=y_coord(h)+mp_take_fraction(mp, xx,wy)+mp_take_fraction(mp, yy,hy);
8871 }
8872
8873 @ @<Find the non-constant part of the transformation for |h|@>=
8874 wx=left_x(h)-x_coord(h);
8875 wy=left_y(h)-y_coord(h);
8876 hx=right_x(h)-x_coord(h);
8877 hy=right_y(h)-y_coord(h)
8878
8879 @ @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the...@>=
8880 yy=-(mp_take_fraction(mp, x,hy)+mp_take_fraction(mp, y,-hx));
8881 xx=mp_take_fraction(mp, x,-wy)+mp_take_fraction(mp, y,wx);
8882 d=mp_pyth_add(mp, xx,yy);
8883 if ( d>0 ) { 
8884   xx=half(mp_make_fraction(mp, xx,d));
8885   yy=half(mp_make_fraction(mp, yy,d));
8886 }
8887
8888 @ Finding the bounding box of a pen is easy except if the pen is elliptical.
8889 But we can handle that case by just calling |find_offset| twice.  The answer
8890 is stored in the global variables |minx|, |maxx|, |miny|, and |maxy|.
8891
8892 @c 
8893 void mp_pen_bbox (MP mp,pointer h) {
8894   pointer p; /* for scanning the knot list */
8895   if ( pen_is_elliptical(h) ) {
8896     @<Find the bounding box of an elliptical pen@>;
8897   } else { 
8898     minx=x_coord(h); maxx=minx;
8899     miny=y_coord(h); maxy=miny;
8900     p=link(h);
8901     while ( p!=h ) {
8902       if ( x_coord(p)<minx ) minx=x_coord(p);
8903       if ( y_coord(p)<miny ) miny=y_coord(p);
8904       if ( x_coord(p)>maxx ) maxx=x_coord(p);
8905       if ( y_coord(p)>maxy ) maxy=y_coord(p);
8906       p=link(p);
8907     }
8908   }
8909 }
8910
8911 @ @<Find the bounding box of an elliptical pen@>=
8912
8913 mp_find_offset(mp, 0,fraction_one,h);
8914 maxx=mp->cur_x;
8915 minx=2*x_coord(h)-mp->cur_x;
8916 mp_find_offset(mp, -fraction_one,0,h);
8917 maxy=mp->cur_y;
8918 miny=2*y_coord(h)-mp->cur_y;
8919 }
8920
8921 @* \[21] Edge structures.
8922 Now we come to \MP's internal scheme for representing pictures.
8923 The representation is very different from \MF's edge structures
8924 because \MP\ pictures contain \ps\ graphics objects instead of pixel
8925 images.  However, the basic idea is somewhat similar in that shapes
8926 are represented via their boundaries.
8927
8928 The main purpose of edge structures is to keep track of graphical objects
8929 until it is time to translate them into \ps.  Since \MP\ does not need to
8930 know anything about an edge structure other than how to translate it into
8931 \ps\ and how to find its bounding box, edge structures can be just linked
8932 lists of graphical objects.  \MP\ has no easy way to determine whether
8933 two such objects overlap, but it suffices to draw the first one first and
8934 let the second one overwrite it if necessary.
8935
8936 @ Let's consider the types of graphical objects one at a time.
8937 First of all, a filled contour is represented by a eight-word node.  The first
8938 word contains |type| and |link| fields, and the next six words contain a
8939 pointer to a cyclic path and the value to use for \ps' \&{currentrgbcolor}
8940 parameter.  If a pen is used for filling |pen_p|, |ljoin_val| and |miterlim_val|
8941 give the relevant information.
8942
8943 @d path_p(A) link((A)+1)
8944   /* a pointer to the path that needs filling */
8945 @d pen_p(A) info((A)+1)
8946   /* a pointer to the pen to fill or stroke with */
8947 @d color_model(A) type((A)+2) /*  the color model  */
8948 @d obj_red_loc(A) ((A)+3)  /* the first of three locations for the color */
8949 @d obj_cyan_loc obj_red_loc  /* the first of four locations for the color */
8950 @d obj_grey_loc obj_red_loc  /* the location for the color */
8951 @d red_val(A) mp->mem[(A)+3].sc
8952   /* the red component of the color in the range $0\ldots1$ */
8953 @d cyan_val red_val
8954 @d grey_val red_val
8955 @d green_val(A) mp->mem[(A)+4].sc
8956   /* the green component of the color in the range $0\ldots1$ */
8957 @d magenta_val green_val
8958 @d blue_val(A) mp->mem[(A)+5].sc
8959   /* the blue component of the color in the range $0\ldots1$ */
8960 @d yellow_val blue_val
8961 @d black_val(A) mp->mem[(A)+6].sc
8962   /* the blue component of the color in the range $0\ldots1$ */
8963 @d ljoin_val(A) name_type((A))  /* the value of \&{linejoin} */
8964 @:linejoin_}{\&{linejoin} primitive@>
8965 @d miterlim_val(A) mp->mem[(A)+7].sc  /* the value of \&{miterlimit} */
8966 @:miterlimit_}{\&{miterlimit} primitive@>
8967 @d obj_color_part(A) mp->mem[(A)+3-red_part].sc
8968   /* interpret an object pointer that has been offset by |red_part..blue_part| */
8969 @d pre_script(A) mp->mem[(A)+8].hh.lh
8970 @d post_script(A) mp->mem[(A)+8].hh.rh
8971 @d fill_node_size 9
8972 @d fill_code 1
8973
8974 @c 
8975 pointer mp_new_fill_node (MP mp,pointer p) {
8976   /* make a fill node for cyclic path |p| and color black */
8977   pointer t; /* the new node */
8978   t=mp_get_node(mp, fill_node_size);
8979   type(t)=fill_code;
8980   path_p(t)=p;
8981   pen_p(t)=null; /* |null| means don't use a pen */
8982   red_val(t)=0;
8983   green_val(t)=0;
8984   blue_val(t)=0;
8985   black_val(t)=0;
8986   color_model(t)=uninitialized_model;
8987   pre_script(t)=null;
8988   post_script(t)=null;
8989   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
8990   return t;
8991 }
8992
8993 @ @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>=
8994 if ( mp->internal[linejoin]>unity ) ljoin_val(t)=2;
8995 else if ( mp->internal[linejoin]>0 ) ljoin_val(t)=1;
8996 else ljoin_val(t)=0;
8997 if ( mp->internal[miterlimit]<unity )
8998   miterlim_val(t)=unity;
8999 else
9000   miterlim_val(t)=mp->internal[miterlimit]
9001
9002 @ A stroked path is represented by an eight-word node that is like a filled
9003 contour node except that it contains the current \&{linecap} value, a scale
9004 factor for the dash pattern, and a pointer that is non-null if the stroke
9005 is to be dashed.  The purpose of the scale factor is to allow a picture to
9006 be transformed without touching the picture that |dash_p| points to.
9007
9008 @d dash_p(A) link((A)+9)
9009   /* a pointer to the edge structure that gives the dash pattern */
9010 @d lcap_val(A) type((A)+9)
9011   /* the value of \&{linecap} */
9012 @:linecap_}{\&{linecap} primitive@>
9013 @d dash_scale(A) mp->mem[(A)+10].sc /* dash lengths are scaled by this factor */
9014 @d stroked_node_size 11
9015 @d stroked_code 2
9016
9017 @c 
9018 pointer mp_new_stroked_node (MP mp,pointer p) {
9019   /* make a stroked node for path |p| with |pen_p(p)| temporarily |null| */
9020   pointer t; /* the new node */
9021   t=mp_get_node(mp, stroked_node_size);
9022   type(t)=stroked_code;
9023   path_p(t)=p; pen_p(t)=null;
9024   dash_p(t)=null;
9025   dash_scale(t)=unity;
9026   red_val(t)=0;
9027   green_val(t)=0;
9028   blue_val(t)=0;
9029   black_val(t)=0;
9030   color_model(t)=uninitialized_model;
9031   pre_script(t)=null;
9032   post_script(t)=null;
9033   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9034   if ( mp->internal[linecap]>unity ) lcap_val(t)=2;
9035   else if ( mp->internal[linecap]>0 ) lcap_val(t)=1;
9036   else lcap_val(t)=0;
9037   return t;
9038 }
9039
9040 @ When a dashed line is computed in a transformed coordinate system, the dash
9041 lengths get scaled like the pen shape and we need to compensate for this.  Since
9042 there is no unique scale factor for an arbitrary transformation, we use the
9043 the square root of the determinant.  The properties of the determinant make it
9044 easier to maintain the |dash_scale|.  The computation is fairly straight-forward
9045 except for the initialization of the scale factor |s|.  The factor of 64 is
9046 needed because |square_rt| scales its result by $2^8$ while we need $2^{14}$
9047 to counteract the effect of |take_fraction|.
9048
9049 @<Declare subroutines needed by |print_edges|@>=
9050 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) {
9051   scaled maxabs; /* $max(|a|,|b|,|c|,|d|)$ */
9052   integer s; /* amount by which the result of |square_rt| needs to be scaled */
9053   @<Initialize |maxabs|@>;
9054   s=64;
9055   while ( (maxabs<fraction_one) && (s>1) ){ 
9056     a+=a; b+=b; c+=c; d+=d;
9057     maxabs+=maxabs; s=halfp(s);
9058   }
9059   return s*mp_square_rt(mp, abs(mp_take_fraction(mp, a,d)-mp_take_fraction(mp, b,c)));
9060 }
9061 @#
9062 scaled mp_get_pen_scale (MP mp,pointer p) { 
9063   return mp_sqrt_det(mp, 
9064     left_x(p)-x_coord(p), right_x(p)-x_coord(p),
9065     left_y(p)-y_coord(p), right_y(p)-y_coord(p));
9066 }
9067
9068 @ @<Initialize |maxabs|@>=
9069 maxabs=abs(a);
9070 if ( abs(b)>maxabs ) maxabs=abs(b);
9071 if ( abs(c)>maxabs ) maxabs=abs(c);
9072 if ( abs(d)>maxabs ) maxabs=abs(d)
9073
9074 @ When a picture contains text, this is represented by a fourteen-word node
9075 where the color information and |type| and |link| fields are augmented by
9076 additional fields that describe the text and  how it is transformed.
9077 The |path_p| and |pen_p| pointers are replaced by a number that identifies
9078 the font and a string number that gives the text to be displayed.
9079 The |width|, |height|, and |depth| fields
9080 give the dimensions of the text at its design size, and the remaining six
9081 words give a transformation to be applied to the text.  The |new_text_node|
9082 function initializes everything to default values so that the text comes out
9083 black with its reference point at the origin.
9084
9085 @d text_p(A) link((A)+1)  /* a string pointer for the text to display */
9086 @d font_n(A) info((A)+1)  /* the font number */
9087 @d width_val(A) mp->mem[(A)+7].sc  /* unscaled width of the text */
9088 @d height_val(A) mp->mem[(A)+9].sc  /* unscaled height of the text */
9089 @d depth_val(A) mp->mem[(A)+10].sc  /* unscaled depth of the text */
9090 @d text_tx_loc(A) ((A)+11)
9091   /* the first of six locations for transformation parameters */
9092 @d tx_val(A) mp->mem[(A)+11].sc  /* $x$ shift amount */
9093 @d ty_val(A) mp->mem[(A)+12].sc  /* $y$ shift amount */
9094 @d txx_val(A) mp->mem[(A)+13].sc  /* |txx| transformation parameter */
9095 @d txy_val(A) mp->mem[(A)+14].sc  /* |txy| transformation parameter */
9096 @d tyx_val(A) mp->mem[(A)+15].sc  /* |tyx| transformation parameter */
9097 @d tyy_val(A) mp->mem[(A)+16].sc  /* |tyy| transformation parameter */
9098 @d text_trans_part(A) mp->mem[(A)+11-x_part].sc
9099     /* interpret a text node ponter that has been offset by |x_part..yy_part| */
9100 @d text_node_size 17
9101 @d text_code 3
9102
9103 @c @<Declare text measuring subroutines@>;
9104 pointer mp_new_text_node (MP mp,char *f,str_number s) {
9105   /* make a text node for font |f| and text string |s| */
9106   pointer t; /* the new node */
9107   t=mp_get_node(mp, text_node_size);
9108   type(t)=text_code;
9109   text_p(t)=s;
9110   font_n(t)=mp_find_font(mp, f); /* this identifies the font */
9111   red_val(t)=0;
9112   green_val(t)=0;
9113   blue_val(t)=0;
9114   black_val(t)=0;
9115   color_model(t)=uninitialized_model;
9116   pre_script(t)=null;
9117   post_script(t)=null;
9118   tx_val(t)=0; ty_val(t)=0;
9119   txx_val(t)=unity; txy_val(t)=0;
9120   tyx_val(t)=0; tyy_val(t)=unity;
9121   mp_set_text_box(mp, t); /* this finds the bounding box */
9122   return t;
9123 }
9124
9125 @ The last two types of graphical objects that can occur in an edge structure
9126 are clipping paths and \&{setbounds} paths.  These are slightly more difficult
9127 @:set_bounds_}{\&{setbounds} primitive@>
9128 to implement because we must keep track of exactly what is being clipped or
9129 bounded when pictures get merged together.  For this reason, each clipping or
9130 \&{setbounds} operation is represented by a pair of nodes:  first comes a
9131 two-word node whose |path_p| gives the relevant path, then there is the list
9132 of objects to clip or bound followed by a two-word node whose second word is
9133 unused.
9134
9135 Using at least two words for each graphical object node allows them all to be
9136 allocated and deallocated similarly with a global array |gr_object_size| to
9137 give the size in words for each object type.
9138
9139 @d start_clip_size 2
9140 @d start_bounds_size 2
9141 @d stop_clip_size 2 /* the second word is not used here */
9142 @d stop_bounds_size 2 /* the second word is not used here */
9143 @#
9144 @d stop_type(A) ((A)+2)
9145   /* matching |type| for |start_clip_code| or |start_bounds_code| */
9146 @d has_color(A) (type((A))<mp_start_clip_code)
9147   /* does a graphical object have color fields? */
9148 @d has_pen(A) (type((A))<text_code)
9149   /* does a graphical object have a |pen_p| field? */
9150 @d is_start_or_stop(A) (type((A))>=mp_start_clip_code)
9151 @d is_stop(A) (type((A))>=mp_stop_clip_code)
9152
9153 @<Types...@>=
9154 enum {
9155  mp_start_clip_code=4, /* |type| of a node that starts clipping */
9156  mp_start_bounds_code, /* |type| of a node that gives a \&{setbounds} path */
9157  mp_stop_clip_code, /* |type| of a node that stops clipping */
9158  mp_stop_bounds_code /* |type| of a node that stops \&{setbounds} */
9159 };
9160
9161 @ @c 
9162 pointer mp_new_bounds_node (MP mp,pointer p, small_number  c) {
9163   /* make a node of type |c| where |p| is the clipping or \&{setbounds} path */
9164   pointer t; /* the new node */
9165   t=mp_get_node(mp, mp->gr_object_size[c]);
9166   type(t)=c;
9167   path_p(t)=p;
9168   return t;
9169 };
9170
9171 @ We need an array to keep track of the sizes of graphical objects.
9172
9173 @<Glob...@>=
9174 small_number gr_object_size[mp_stop_bounds_code+1];
9175
9176 @ @<Set init...@>=
9177 mp->gr_object_size[fill_code]=fill_node_size;
9178 mp->gr_object_size[stroked_code]=stroked_node_size;
9179 mp->gr_object_size[text_code]=text_node_size;
9180 mp->gr_object_size[mp_start_clip_code]=start_clip_size;
9181 mp->gr_object_size[mp_stop_clip_code]=stop_clip_size;
9182 mp->gr_object_size[mp_start_bounds_code]=start_bounds_size;
9183 mp->gr_object_size[mp_stop_bounds_code]=stop_bounds_size;
9184
9185 @ All the essential information in an edge structure is encoded as a linked list
9186 of graphical objects as we have just seen, but it is helpful to add some
9187 redundant information.  A single edge structure might be used as a dash pattern
9188 many times, and it would be nice to avoid scanning the same structure
9189 repeatedly.  Thus, an edge structure known to be a suitable dash pattern
9190 has a header that gives a list of dashes in a sorted order designed for rapid
9191 translation into \ps.
9192
9193 Each dash is represented by a three-word node containing the initial and final
9194 $x$~coordinates as well as the usual |link| field.  The |link| fields points to
9195 the dash node with the next higher $x$-coordinates and the final link points
9196 to a special location called |null_dash|.  (There should be no overlap between
9197 dashes).  Since the $y$~coordinate of the dash pattern is needed to determine
9198 the period of repetition, this needs to be stored in the edge header along
9199 with a pointer to the list of dash nodes.
9200
9201 @d start_x(A) mp->mem[(A)+1].sc  /* the starting $x$~coordinate in a dash node */
9202 @d stop_x(A) mp->mem[(A)+2].sc  /* the ending $x$~coordinate in a dash node */
9203 @d dash_node_size 3
9204 @d dash_list link
9205   /* in an edge header this points to the first dash node */
9206 @d dash_y(A) mp->mem[(A)+1].sc  /* $y$ value for the dash list in an edge header */
9207
9208 @ It is also convenient for an edge header to contain the bounding
9209 box information needed by the \&{llcorner} and \&{urcorner} operators
9210 so that this does not have to be recomputed unnecessarily.  This is done by
9211 adding fields for the $x$~and $y$ extremes as well as a pointer that indicates
9212 how far the bounding box computation has gotten.  Thus if the user asks for
9213 the bounding box and then adds some more text to the picture before asking
9214 for more bounding box information, the second computation need only look at
9215 the additional text.
9216
9217 When the bounding box has not been computed, the |bblast| pointer points
9218 to a dummy link at the head of the graphical object list while the |minx_val|
9219 and |miny_val| fields contain |el_gordo| and the |maxx_val| and |maxy_val|
9220 fields contain |-el_gordo|.
9221
9222 Since the bounding box of pictures containing objects of type
9223 |mp_start_bounds_code| depends on the value of \&{truecorners}, the bounding box
9224 @:true_corners_}{\&{truecorners} primitive@>
9225 data might not be valid for all values of this parameter.  Hence, the |bbtype|
9226 field is needed to keep track of this.
9227
9228 @d minx_val(A) mp->mem[(A)+2].sc
9229 @d miny_val(A) mp->mem[(A)+3].sc
9230 @d maxx_val(A) mp->mem[(A)+4].sc
9231 @d maxy_val(A) mp->mem[(A)+5].sc
9232 @d bblast(A) link((A)+6)  /* last item considered in bounding box computation */
9233 @d bbtype(A) info((A)+6)  /* tells how bounding box data depends on \&{truecorners} */
9234 @d dummy_loc(A) ((A)+7)  /* where the object list begins in an edge header */
9235 @d no_bounds 0
9236   /* |bbtype| value when bounding box data is valid for all \&{truecorners} values */
9237 @d bounds_set 1
9238   /* |bbtype| value when bounding box data is for \&{truecorners}${}\le 0$ */
9239 @d bounds_unset 2
9240   /* |bbtype| value when bounding box data is for \&{truecorners}${}>0$ */
9241
9242 @c 
9243 void mp_init_bbox (MP mp,pointer h) {
9244   /* Initialize the bounding box information in edge structure |h| */
9245   bblast(h)=dummy_loc(h);
9246   bbtype(h)=no_bounds;
9247   minx_val(h)=el_gordo;
9248   miny_val(h)=el_gordo;
9249   maxx_val(h)=-el_gordo;
9250   maxy_val(h)=-el_gordo;
9251 }
9252
9253 @ The only other entries in an edge header are a reference count in the first
9254 word and a pointer to the tail of the object list in the last word.
9255
9256 @d obj_tail(A) info((A)+7)  /* points to the last entry in the object list */
9257 @d edge_header_size 8
9258
9259 @c 
9260 void mp_init_edges (MP mp,pointer h) {
9261   /* initialize an edge header to null values */
9262   dash_list(h)=null_dash;
9263   obj_tail(h)=dummy_loc(h);
9264   link(dummy_loc(h))=null;
9265   ref_count(h)=null;
9266   mp_init_bbox(mp, h);
9267 }
9268
9269 @ Here is how edge structures are deleted.  The process can be recursive because
9270 of the need to dereference edge structures that are used as dash patterns.
9271 @^recursion@>
9272
9273 @d add_edge_ref(A) incr(ref_count((A)))
9274 @d delete_edge_ref(A) { if ( ref_count((A))==null ) mp_toss_edges(mp, (A));
9275   else decr(ref_count((A))); }
9276
9277 @<Declare the recycling subroutines@>=
9278 void mp_flush_dash_list (MP mp,pointer h);
9279 pointer mp_toss_gr_object (MP mp,pointer p) ;
9280 void mp_toss_edges (MP mp,pointer h) ;
9281
9282 @ @c void mp_toss_edges (MP mp,pointer h) {
9283   pointer p,q;  /* pointers that scan the list being recycled */
9284   pointer r; /* an edge structure that object |p| refers to */
9285   mp_flush_dash_list(mp, h);
9286   q=link(dummy_loc(h));
9287   while ( (q!=null) ) { 
9288     p=q; q=link(q);
9289     r=mp_toss_gr_object(mp, p);
9290     if ( r!=null ) delete_edge_ref(r);
9291   }
9292   mp_free_node(mp, h,edge_header_size);
9293 }
9294 void mp_flush_dash_list (MP mp,pointer h) {
9295   pointer p,q;  /* pointers that scan the list being recycled */
9296   q=dash_list(h);
9297   while ( q!=null_dash ) { 
9298     p=q; q=link(q);
9299     mp_free_node(mp, p,dash_node_size);
9300   }
9301   dash_list(h)=null_dash;
9302 }
9303 pointer mp_toss_gr_object (MP mp,pointer p) {
9304   /* returns an edge structure that needs to be dereferenced */
9305   pointer e; /* the edge structure to return */
9306   e=null;
9307   @<Prepare to recycle graphical object |p|@>;
9308   mp_free_node(mp, p,mp->gr_object_size[type(p)]);
9309   return e;
9310 }
9311
9312 @ @<Prepare to recycle graphical object |p|@>=
9313 switch (type(p)) {
9314 case fill_code: 
9315   mp_toss_knot_list(mp, path_p(p));
9316   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9317   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9318   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9319   break;
9320 case stroked_code: 
9321   mp_toss_knot_list(mp, path_p(p));
9322   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9323   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9324   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9325   e=dash_p(p);
9326   break;
9327 case text_code: 
9328   delete_str_ref(text_p(p));
9329   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9330   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9331   break;
9332 case mp_start_clip_code:
9333 case mp_start_bounds_code: 
9334   mp_toss_knot_list(mp, path_p(p));
9335   break;
9336 case mp_stop_clip_code:
9337 case mp_stop_bounds_code: 
9338   break;
9339 } /* there are no other cases */
9340
9341 @ If we use |add_edge_ref| to ``copy'' edge structures, the real copying needs
9342 to be done before making a significant change to an edge structure.  Much of
9343 the work is done in a separate routine |copy_objects| that copies a list of
9344 graphical objects into a new edge header.
9345
9346 @c @<Declare a function called |copy_objects|@>;
9347 pointer mp_private_edges (MP mp,pointer h) {
9348   /* make a private copy of the edge structure headed by |h| */
9349   pointer hh;  /* the edge header for the new copy */
9350   pointer p,pp;  /* pointers for copying the dash list */
9351   if ( ref_count(h)==null ) {
9352     return h;
9353   } else { 
9354     decr(ref_count(h));
9355     hh=mp_copy_objects(mp, link(dummy_loc(h)),null);
9356     @<Copy the dash list from |h| to |hh|@>;
9357     @<Copy the bounding box information from |h| to |hh| and make |bblast(hh)|
9358       point into the new object list@>;
9359     return hh;
9360   }
9361 }
9362
9363 @ Here we use the fact that |dash_list(hh)=link(hh)|.
9364 @^data structure assumptions@>
9365
9366 @<Copy the dash list from |h| to |hh|@>=
9367 pp=hh; p=dash_list(h);
9368 while ( (p!=null_dash) ) { 
9369   link(pp)=mp_get_node(mp, dash_node_size);
9370   pp=link(pp);
9371   start_x(pp)=start_x(p);
9372   stop_x(pp)=stop_x(p);
9373   p=link(p);
9374 }
9375 link(pp)=null_dash;
9376 dash_y(hh)=dash_y(h)
9377
9378 @ @<Copy the bounding box information from |h| to |hh|...@>=
9379 minx_val(hh)=minx_val(h);
9380 miny_val(hh)=miny_val(h);
9381 maxx_val(hh)=maxx_val(h);
9382 maxy_val(hh)=maxy_val(h);
9383 bbtype(hh)=bbtype(h);
9384 p=dummy_loc(h); pp=dummy_loc(hh);
9385 while ((p!=bblast(h)) ) { 
9386   if ( p==null ) mp_confusion(mp, "bblast");
9387 @:this can't happen bblast}{\quad bblast@>
9388   p=link(p); pp=link(pp);
9389 }
9390 bblast(hh)=pp
9391
9392 @ Here is the promised routine for copying graphical objects into a new edge
9393 structure.  It starts copying at object~|p| and stops just before object~|q|.
9394 If |q| is null, it copies the entire sublist headed at |p|.  The resulting edge
9395 structure requires further initialization by |init_bbox|.
9396
9397 @<Declare a function called |copy_objects|@>=
9398 pointer mp_copy_objects (MP mp, pointer p, pointer q) {
9399   pointer hh;  /* the new edge header */
9400   pointer pp;  /* the last newly copied object */
9401   small_number k;  /* temporary register */
9402   hh=mp_get_node(mp, edge_header_size);
9403   dash_list(hh)=null_dash;
9404   ref_count(hh)=null;
9405   pp=dummy_loc(hh);
9406   while ( (p!=q) ) {
9407     @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>;
9408   }
9409   obj_tail(hh)=pp;
9410   link(pp)=null;
9411   return hh;
9412 }
9413
9414 @ @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>=
9415 { k=mp->gr_object_size[type(p)];
9416   link(pp)=mp_get_node(mp, k);
9417   pp=link(pp);
9418   while ( (k>0) ) { decr(k); mp->mem[pp+k]=mp->mem[p+k];  };
9419   @<Fix anything in graphical object |pp| that should differ from the
9420     corresponding field in |p|@>;
9421   p=link(p);
9422 }
9423
9424 @ @<Fix anything in graphical object |pp| that should differ from the...@>=
9425 switch (type(p)) {
9426 case mp_start_clip_code:
9427 case mp_start_bounds_code: 
9428   path_p(pp)=mp_copy_path(mp, path_p(p));
9429   break;
9430 case fill_code: 
9431   path_p(pp)=mp_copy_path(mp, path_p(p));
9432   if ( pen_p(p)!=null ) pen_p(pp)=copy_pen(pen_p(p));
9433   break;
9434 case stroked_code: 
9435   path_p(pp)=mp_copy_path(mp, path_p(p));
9436   pen_p(pp)=copy_pen(pen_p(p));
9437   if ( dash_p(p)!=null ) add_edge_ref(dash_p(pp));
9438   break;
9439 case text_code: 
9440   add_str_ref(text_p(pp));
9441   break;
9442 case mp_stop_clip_code:
9443 case mp_stop_bounds_code: 
9444   break;
9445 }  /* there are no other cases */
9446
9447 @ Here is one way to find an acceptable value for the second argument to
9448 |copy_objects|.  Given a non-null graphical object list, |skip_1component|
9449 skips past one picture component, where a ``picture component'' is a single
9450 graphical object, or a start bounds or start clip object and everything up
9451 through the matching stop bounds or stop clip object.  The macro version avoids
9452 procedure call overhead and error handling: |skip_component(p)(e)| advances |p|
9453 unless |p| points to a stop bounds or stop clip node, in which case it executes
9454 |e| instead.
9455
9456 @d skip_component(A)
9457     if ( ! is_start_or_stop((A)) ) (A)=link((A));
9458     else if ( ! is_stop((A)) ) (A)=mp_skip_1component(mp, (A));
9459     else 
9460
9461 @c 
9462 pointer mp_skip_1component (MP mp,pointer p) {
9463   integer lev; /* current nesting level */
9464   lev=0;
9465   do {  
9466    if ( is_start_or_stop(p) ) {
9467      if ( is_stop(p) ) decr(lev);  else incr(lev);
9468    }
9469    p=link(p);
9470   } while (lev!=0);
9471   return p;
9472 }
9473
9474 @ Here is a diagnostic routine for printing an edge structure in symbolic form.
9475
9476 @<Declare subroutines for printing expressions@>=
9477 @<Declare subroutines needed by |print_edges|@>;
9478 void mp_print_edges (MP mp,pointer h, char *s, boolean nuline) {
9479   pointer p;  /* a graphical object to be printed */
9480   pointer hh,pp;  /* temporary pointers */
9481   scaled scf;  /* a scale factor for the dash pattern */
9482   boolean ok_to_dash;  /* |false| for polygonal pen strokes */
9483   mp_print_diagnostic(mp, "Edge structure",s,nuline);
9484   p=dummy_loc(h);
9485   while ( link(p)!=null ) { 
9486     p=link(p);
9487     mp_print_ln(mp);
9488     switch (type(p)) {
9489       @<Cases for printing graphical object node |p|@>;
9490     default: 
9491           mp_print(mp, "[unknown object type!]");
9492           break;
9493     }
9494   }
9495   mp_print_nl(mp, "End edges");
9496   if ( p!=obj_tail(h) ) mp_print(mp, "?");
9497 @.End edges?@>
9498   mp_end_diagnostic(mp, true);
9499 }
9500
9501 @ @<Cases for printing graphical object node |p|@>=
9502 case fill_code: 
9503   mp_print(mp, "Filled contour ");
9504   mp_print_obj_color(mp, p);
9505   mp_print_char(mp, ':'); mp_print_ln(mp);
9506   mp_pr_path(mp, path_p(p)); mp_print_ln(mp);
9507   if ( (pen_p(p)!=null) ) {
9508     @<Print join type for graphical object |p|@>;
9509     mp_print(mp, " with pen"); mp_print_ln(mp);
9510     mp_pr_pen(mp, pen_p(p));
9511   }
9512   break;
9513
9514 @ @<Print join type for graphical object |p|@>=
9515 switch (ljoin_val(p)) {
9516 case 0:
9517   mp_print(mp, "mitered joins limited ");
9518   mp_print_scaled(mp, miterlim_val(p));
9519   break;
9520 case 1:
9521   mp_print(mp, "round joins");
9522   break;
9523 case 2:
9524   mp_print(mp, "beveled joins");
9525   break;
9526 default: 
9527   mp_print(mp, "?? joins");
9528 @.??@>
9529   break;
9530 }
9531
9532 @ For stroked nodes, we need to print |lcap_val(p)| as well.
9533
9534 @<Print join and cap types for stroked node |p|@>=
9535 switch (lcap_val(p)) {
9536 case 0:mp_print(mp, "butt"); break;
9537 case 1:mp_print(mp, "round"); break;
9538 case 2:mp_print(mp, "square"); break;
9539 default: mp_print(mp, "??"); break;
9540 @.??@>
9541 }
9542 mp_print(mp, " ends, ");
9543 @<Print join type for graphical object |p|@>
9544
9545 @ Here is a routine that prints the color of a graphical object if it isn't
9546 black (the default color).
9547
9548 @<Declare subroutines needed by |print_edges|@>=
9549 @<Declare a procedure called |print_compact_node|@>;
9550 void mp_print_obj_color (MP mp,pointer p) { 
9551   if ( color_model(p)==grey_model ) {
9552     if ( grey_val(p)>0 ) { 
9553       mp_print(mp, "greyed ");
9554       mp_print_compact_node(mp, obj_grey_loc(p),1);
9555     };
9556   } else if ( color_model(p)==cmyk_model ) {
9557     if ( (cyan_val(p)>0) || (magenta_val(p)>0) || 
9558          (yellow_val(p)>0) || (black_val(p)>0) ) { 
9559       mp_print(mp, "processcolored ");
9560       mp_print_compact_node(mp, obj_cyan_loc(p),4);
9561     };
9562   } else if ( color_model(p)==rgb_model ) {
9563     if ( (red_val(p)>0) || (green_val(p)>0) || (blue_val(p)>0) ) { 
9564       mp_print(mp, "colored "); 
9565       mp_print_compact_node(mp, obj_red_loc(p),3);
9566     };
9567   }
9568 }
9569
9570 @ We also need a procedure for printing consecutive scaled values as if they
9571 were a known big node.
9572
9573 @<Declare a procedure called |print_compact_node|@>=
9574 void mp_print_compact_node (MP mp,pointer p, small_number k) {
9575   pointer q;  /* last location to print */
9576   q=p+k-1;
9577   mp_print_char(mp, '(');
9578   while ( p<=q ){ 
9579     mp_print_scaled(mp, mp->mem[p].sc);
9580     if ( p<q ) mp_print_char(mp, ',');
9581     incr(p);
9582   }
9583   mp_print_char(mp, ')');
9584 }
9585
9586 @ @<Cases for printing graphical object node |p|@>=
9587 case stroked_code: 
9588   mp_print(mp, "Filled pen stroke ");
9589   mp_print_obj_color(mp, p);
9590   mp_print_char(mp, ':'); mp_print_ln(mp);
9591   mp_pr_path(mp, path_p(p));
9592   if ( dash_p(p)!=null ) { 
9593     mp_print_nl(mp, "dashed (");
9594     @<Finish printing the dash pattern that |p| refers to@>;
9595   }
9596   mp_print_ln(mp);
9597   @<Print join and cap types for stroked node |p|@>;
9598   mp_print(mp, " with pen"); mp_print_ln(mp);
9599   if ( pen_p(p)==null ) mp_print(mp, "???"); /* shouldn't happen */
9600 @.???@>
9601   else mp_pr_pen(mp, pen_p(p));
9602   break;
9603
9604 @ Normally, the  |dash_list| field in an edge header is set to |null_dash|
9605 when it is not known to define a suitable dash pattern.  This is disallowed
9606 here because the |dash_p| field should never point to such an edge header.
9607 Note that memory is allocated for |start_x(null_dash)| and we are free to
9608 give it any convenient value.
9609
9610 @<Finish printing the dash pattern that |p| refers to@>=
9611 ok_to_dash=pen_is_elliptical(pen_p(p));
9612 if ( ! ok_to_dash ) scf=unity; else scf=dash_scale(p);
9613 hh=dash_p(p);
9614 pp=dash_list(hh);
9615 if ( (pp==null_dash) || (dash_y(hh)<0) ) {
9616   mp_print(mp, " ??");
9617 } else { start_x(null_dash)=start_x(pp)+dash_y(hh);
9618   while ( pp!=null_dash ) { 
9619     mp_print(mp, "on ");
9620     mp_print_scaled(mp, mp_take_scaled(mp, stop_x(pp)-start_x(pp),scf));
9621     mp_print(mp, " off ");
9622     mp_print_scaled(mp, mp_take_scaled(mp, start_x(link(pp))-stop_x(pp),scf));
9623     pp = link(pp);
9624     if ( pp!=null_dash ) mp_print_char(mp, ' ');
9625   }
9626   mp_print(mp, ") shifted ");
9627   mp_print_scaled(mp, -mp_take_scaled(mp, mp_dash_offset(mp, hh),scf));
9628   if ( ! ok_to_dash || (dash_y(hh)==0) ) mp_print(mp, " (this will be ignored)");
9629 }
9630
9631 @ @<Declare subroutines needed by |print_edges|@>=
9632 scaled mp_dash_offset (MP mp,pointer h) {
9633   scaled x;  /* the answer */
9634   if ( (dash_list(h)==null_dash) || (dash_y(h)<0) ) mp_confusion(mp, "dash0");
9635 @:this can't happen dash0}{\quad dash0@>
9636   if ( dash_y(h)==0 ) {
9637     x=0; 
9638   } else { 
9639     x=-(start_x(dash_list(h)) % dash_y(h));
9640     if ( x<0 ) x=x+dash_y(h);
9641   }
9642   return x;
9643 }
9644
9645 @ @<Cases for printing graphical object node |p|@>=
9646 case text_code: 
9647   mp_print_char(mp, '"'); mp_print_str(mp,text_p(p));
9648   mp_print(mp, "\" infont \""); mp_print(mp, mp->font_name[font_n(p)]);
9649   mp_print_char(mp, '"'); mp_print_ln(mp);
9650   mp_print_obj_color(mp, p);
9651   mp_print(mp, "transformed ");
9652   mp_print_compact_node(mp, text_tx_loc(p),6);
9653   break;
9654
9655 @ @<Cases for printing graphical object node |p|@>=
9656 case mp_start_clip_code: 
9657   mp_print(mp, "clipping path:");
9658   mp_print_ln(mp);
9659   mp_pr_path(mp, path_p(p));
9660   break;
9661 case mp_stop_clip_code: 
9662   mp_print(mp, "stop clipping");
9663   break;
9664
9665 @ @<Cases for printing graphical object node |p|@>=
9666 case mp_start_bounds_code: 
9667   mp_print(mp, "setbounds path:");
9668   mp_print_ln(mp);
9669   mp_pr_path(mp, path_p(p));
9670   break;
9671 case mp_stop_bounds_code: 
9672   mp_print(mp, "end of setbounds");
9673   break;
9674
9675 @ To initialize the |dash_list| field in an edge header~|h|, we need a
9676 subroutine that scans an edge structure and tries to interpret it as a dash
9677 pattern.  This can only be done when there are no filled regions or clipping
9678 paths and all the pen strokes have the same color.  The first step is to let
9679 $y_0$ be the initial $y$~coordinate of the first pen stroke.  Then we implicitly
9680 project all the pen stroke paths onto the line $y=y_0$ and require that there
9681 be no retracing.  If the resulting paths cover a range of $x$~coordinates of
9682 length $\Delta x$, we set |dash_y(h)| to the length of the dash pattern by
9683 finding the maximum of $\Delta x$ and the absolute value of~$y_0$.
9684
9685 @c @<Declare a procedure called |x_retrace_error|@>;
9686 pointer mp_make_dashes (MP mp,pointer h) { /* returns |h| or |null| */
9687   pointer p;  /* this scans the stroked nodes in the object list */
9688   pointer p0;  /* if not |null| this points to the first stroked node */
9689   pointer pp,qq,rr;  /* pointers into |path_p(p)| */
9690   pointer d,dd;  /* pointers used to create the dash list */
9691   @<Other local variables in |make_dashes|@>;
9692   scaled y0=0;  /* the initial $y$ coordinate */
9693   if ( dash_list(h)!=null_dash ) 
9694         return h;
9695   p0=null;
9696   p=link(dummy_loc(h));
9697   while ( p!=null ) { 
9698     if ( type(p)!=stroked_code ) {
9699       @<Compain that the edge structure contains a node of the wrong type
9700         and |goto not_found|@>;
9701     }
9702     pp=path_p(p);
9703     if ( p0==null ){ p0=p; y0=y_coord(pp);  };
9704     @<Make |d| point to a new dash node created from stroke |p| and path |pp|
9705       or |goto not_found| if there is an error@>;
9706     @<Insert |d| into the dash list and |goto not_found| if there is an error@>;
9707     p=link(p);
9708   }
9709   if ( dash_list(h)==null_dash ) 
9710     goto NOT_FOUND; /* No error message */
9711   @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>;
9712   @<Set |dash_y(h)| and merge the first and last dashes if necessary@>;
9713   return h;
9714 NOT_FOUND: 
9715   @<Flush the dash list, recycle |h| and return |null|@>;
9716 };
9717
9718 @ @<Compain that the edge structure contains a node of the wrong type...@>=
9719
9720 print_err("Picture is too complicated to use as a dash pattern");
9721 help3("When you say `dashed p', picture p should not contain any")
9722   ("text, filled regions, or clipping paths.  This time it did")
9723   ("so I'll just make it a solid line instead.");
9724 mp_put_get_error(mp);
9725 goto NOT_FOUND;
9726 }
9727
9728 @ A similar error occurs when monotonicity fails.
9729
9730 @<Declare a procedure called |x_retrace_error|@>=
9731 void mp_x_retrace_error (MP mp) { 
9732 print_err("Picture is too complicated to use as a dash pattern");
9733 help3("When you say `dashed p', every path in p should be monotone")
9734   ("in x and there must be no overlapping.  This failed")
9735   ("so I'll just make it a solid line instead.");
9736 mp_put_get_error(mp);
9737 }
9738
9739 @ We stash |p| in |info(d)| if |dash_p(p)<>0| so that subsequent processing can
9740 handle the case where the pen stroke |p| is itself dashed.
9741
9742 @<Make |d| point to a new dash node created from stroke |p| and path...@>=
9743 @<Make sure |p| and |p0| are the same color and |goto not_found| if there is
9744   an error@>;
9745 rr=pp;
9746 if ( link(pp)!=pp ) {
9747   do {  
9748     qq=rr; rr=link(rr);
9749     @<Check for retracing between knots |qq| and |rr| and |goto not_found|
9750       if there is a problem@>;
9751   } while (right_type(rr)!=endpoint);
9752 }
9753 d=mp_get_node(mp, dash_node_size);
9754 if ( dash_p(p)==0 ) info(d)=0;  else info(d)=p;
9755 if ( x_coord(pp)<x_coord(rr) ) { 
9756   start_x(d)=x_coord(pp);
9757   stop_x(d)=x_coord(rr);
9758 } else { 
9759   start_x(d)=x_coord(rr);
9760   stop_x(d)=x_coord(pp);
9761 }
9762
9763 @ We also need to check for the case where the segment from |qq| to |rr| is
9764 monotone in $x$ but is reversed relative to the path from |pp| to |qq|.
9765
9766 @<Check for retracing between knots |qq| and |rr| and |goto not_found|...@>=
9767 x0=x_coord(qq);
9768 x1=right_x(qq);
9769 x2=left_x(rr);
9770 x3=x_coord(rr);
9771 if ( (x0>x1) || (x1>x2) || (x2>x3) ) {
9772   if ( (x0<x1) || (x1<x2) || (x2<x3) ) {
9773     if ( mp_ab_vs_cd(mp, x2-x1,x2-x1,x1-x0,x3-x2)>0 ) {
9774       mp_x_retrace_error(mp); goto NOT_FOUND;
9775     }
9776   }
9777 }
9778 if ( (x_coord(pp)>x0) || (x0>x3) ) {
9779   if ( (x_coord(pp)<x0) || (x0<x3) ) {
9780     mp_x_retrace_error(mp); goto NOT_FOUND;
9781   }
9782 }
9783
9784 @ @<Other local variables in |make_dashes|@>=
9785   scaled x0,x1,x2,x3;  /* $x$ coordinates of the segment from |qq| to |rr| */
9786
9787 @ @<Make sure |p| and |p0| are the same color and |goto not_found|...@>=
9788 if ( (red_val(p)!=red_val(p0)) || (black_val(p)!=black_val(p0)) ||
9789   (green_val(p)!=green_val(p0)) || (blue_val(p)!=blue_val(p0)) ) {
9790   print_err("Picture is too complicated to use as a dash pattern");
9791   help3("When you say `dashed p', everything in picture p should")
9792     ("be the same color.  I can\'t handle your color changes")
9793     ("so I'll just make it a solid line instead.");
9794   mp_put_get_error(mp);
9795   goto NOT_FOUND;
9796 }
9797
9798 @ @<Insert |d| into the dash list and |goto not_found| if there is an error@>=
9799 start_x(null_dash)=stop_x(d);
9800 dd=h; /* this makes |link(dd)=dash_list(h)| */
9801 while ( start_x(link(dd))<stop_x(d) )
9802   dd=link(dd);
9803 if ( dd!=h ) {
9804   if ( (stop_x(dd)>start_x(d)) )
9805     { mp_x_retrace_error(mp); goto NOT_FOUND;  };
9806 }
9807 link(d)=link(dd);
9808 link(dd)=d
9809
9810 @ @<Set |dash_y(h)| and merge the first and last dashes if necessary@>=
9811 d=dash_list(h);
9812 while ( (link(d)!=null_dash) )
9813   d=link(d);
9814 dd=dash_list(h);
9815 dash_y(h)=stop_x(d)-start_x(dd);
9816 if ( abs(y0)>dash_y(h) ) {
9817   dash_y(h)=abs(y0);
9818 } else if ( d!=dd ) { 
9819   dash_list(h)=link(dd);
9820   stop_x(d)=stop_x(dd)+dash_y(h);
9821   mp_free_node(mp, dd,dash_node_size);
9822 }
9823
9824 @ We get here when the argument is a null picture or when there is an error.
9825 Recovering from an error involves making |dash_list(h)| empty to indicate
9826 that |h| is not known to be a valid dash pattern.  We also dereference |h|
9827 since it is not being used for the return value.
9828
9829 @<Flush the dash list, recycle |h| and return |null|@>=
9830 mp_flush_dash_list(mp, h);
9831 delete_edge_ref(h);
9832 return null
9833
9834 @ Having carefully saved the dashed stroked nodes in the
9835 corresponding dash nodes, we must be prepared to break up these dashes into
9836 smaller dashes.
9837
9838 @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>=
9839 d=h;  /* now |link(d)=dash_list(h)| */
9840 while ( link(d)!=null_dash ) {
9841   ds=info(link(d));
9842   if ( ds==null ) { 
9843     d=link(d);
9844   } else {
9845     hh=dash_p(ds);
9846     hsf=dash_scale(ds);
9847     if ( (hh==null) ) mp_confusion(mp, "dash1");
9848 @:this can't happen dash0}{\quad dash1@>
9849     if ( dash_y(hh)==0 ) {
9850       d=link(d);
9851     } else { 
9852       if ( dash_list(hh)==null ) mp_confusion(mp, "dash1");
9853 @:this can't happen dash0}{\quad dash1@>
9854       @<Replace |link(d)| by a dashed version as determined by edge header
9855           |hh| and scale factor |ds|@>;
9856     }
9857   }
9858 }
9859
9860 @ @<Other local variables in |make_dashes|@>=
9861 pointer dln;  /* |link(d)| */
9862 pointer hh;  /* an edge header that tells how to break up |dln| */
9863 scaled hsf;  /* the dash pattern from |hh| gets scaled by this */
9864 pointer ds;  /* the stroked node from which |hh| and |hsf| are derived */
9865 scaled xoff;  /* added to $x$ values in |dash_list(hh)| to match |dln| */
9866
9867 @ @<Replace |link(d)| by a dashed version as determined by edge header...@>=
9868 dln=link(d);
9869 dd=dash_list(hh);
9870 xoff=start_x(dln)-mp_take_scaled(mp, hsf,start_x(dd))-
9871         mp_take_scaled(mp, hsf,mp_dash_offset(mp, hh));
9872 start_x(null_dash)=mp_take_scaled(mp, hsf,start_x(dd))
9873                    +mp_take_scaled(mp, hsf,dash_y(hh));
9874 stop_x(null_dash)=start_x(null_dash);
9875 @<Advance |dd| until finding the first dash that overlaps |dln| when
9876   offset by |xoff|@>;
9877 while ( start_x(dln)<=stop_x(dln) ) {
9878   @<If |dd| has `fallen off the end', back up to the beginning and fix |xoff|@>;
9879   @<Insert a dash between |d| and |dln| for the overlap with the offset version
9880     of |dd|@>;
9881   dd=link(dd);
9882   start_x(dln)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
9883 }
9884 link(d)=link(dln);
9885 mp_free_node(mp, dln,dash_node_size)
9886
9887 @ The name of this module is a bit of a lie because we actually just find the
9888 first |dd| where |take_scaled (hsf, stop_x(dd))| is large enough to make an
9889 overlap possible.  It could be that the unoffset version of dash |dln| falls
9890 in the gap between |dd| and its predecessor.
9891
9892 @<Advance |dd| until finding the first dash that overlaps |dln| when...@>=
9893 while ( xoff+mp_take_scaled(mp, hsf,stop_x(dd))<start_x(dln) ) {
9894   dd=link(dd);
9895 }
9896
9897 @ @<If |dd| has `fallen off the end', back up to the beginning and fix...@>=
9898 if ( dd==null_dash ) { 
9899   dd=dash_list(hh);
9900   xoff=xoff+mp_take_scaled(mp, hsf,dash_y(hh));
9901 }
9902
9903 @ At this point we already know that
9904 |start_x(dln)<=xoff+take_scaled(hsf,stop_x(dd))|.
9905
9906 @<Insert a dash between |d| and |dln| for the overlap with the offset...@>=
9907 if ( xoff+mp_take_scaled(mp, hsf,start_x(dd))<=stop_x(dln) ) {
9908   link(d)=mp_get_node(mp, dash_node_size);
9909   d=link(d);
9910   link(d)=dln;
9911   if ( start_x(dln)>xoff+mp_take_scaled(mp, hsf,start_x(dd)))
9912     start_x(d)=start_x(dln);
9913   else 
9914     start_x(d)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
9915   if ( stop_x(dln)<xoff+mp_take_scaled(mp, hsf,stop_x(dd)) ) 
9916     stop_x(d)=stop_x(dln);
9917   else 
9918     stop_x(d)=xoff+mp_take_scaled(mp, hsf,stop_x(dd));
9919 }
9920
9921 @ The next major task is to update the bounding box information in an edge
9922 header~|h|. This is done via a procedure |adjust_bbox| that enlarges an edge
9923 header's bounding box to accommodate the box computed by |path_bbox| or
9924 |pen_bbox|. (This is stored in global variables |minx|, |miny|, |maxx|, and
9925 |maxy|.)
9926
9927 @c void mp_adjust_bbox (MP mp,pointer h) { 
9928   if ( minx<minx_val(h) ) minx_val(h)=minx;
9929   if ( miny<miny_val(h) ) miny_val(h)=miny;
9930   if ( maxx>maxx_val(h) ) maxx_val(h)=maxx;
9931   if ( maxy>maxy_val(h) ) maxy_val(h)=maxy;
9932 }
9933
9934 @ Here is a special routine for updating the bounding box information in
9935 edge header~|h| to account for the squared-off ends of a non-cyclic path~|p|
9936 that is to be stroked with the pen~|pp|.
9937
9938 @c void mp_box_ends (MP mp, pointer p, pointer pp, pointer h) {
9939   pointer q;  /* a knot node adjacent to knot |p| */
9940   fraction dx,dy;  /* a unit vector in the direction out of the path at~|p| */
9941   scaled d;  /* a factor for adjusting the length of |(dx,dy)| */
9942   scaled z;  /* a coordinate being tested against the bounding box */
9943   scaled xx,yy;  /* the extreme pen vertex in the |(dx,dy)| direction */
9944   integer i; /* a loop counter */
9945   if ( right_type(p)!=endpoint ) { 
9946     q=link(p);
9947     while (1) { 
9948       @<Make |(dx,dy)| the final direction for the path segment from
9949         |q| to~|p|; set~|d|@>;
9950       d=mp_pyth_add(mp, dx,dy);
9951       if ( d>0 ) { 
9952          @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>;
9953          for (i=1;i<= 2;i++) { 
9954            @<Use |(dx,dy)| to generate a vertex of the square end cap and
9955              update the bounding box to accommodate it@>;
9956            dx=-dx; dy=-dy; 
9957         }
9958       }
9959       if ( right_type(p)==endpoint ) {
9960          return;
9961       } else {
9962         @<Advance |p| to the end of the path and make |q| the previous knot@>;
9963       } 
9964     }
9965   }
9966 }
9967
9968 @ @<Make |(dx,dy)| the final direction for the path segment from...@>=
9969 if ( q==link(p) ) { 
9970   dx=x_coord(p)-right_x(p);
9971   dy=y_coord(p)-right_y(p);
9972   if ( (dx==0)&&(dy==0) ) {
9973     dx=x_coord(p)-left_x(q);
9974     dy=y_coord(p)-left_y(q);
9975   }
9976 } else { 
9977   dx=x_coord(p)-left_x(p);
9978   dy=y_coord(p)-left_y(p);
9979   if ( (dx==0)&&(dy==0) ) {
9980     dx=x_coord(p)-right_x(q);
9981     dy=y_coord(p)-right_y(q);
9982   }
9983 }
9984 dx=x_coord(p)-x_coord(q);
9985 dy=y_coord(p)-y_coord(q)
9986
9987 @ @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>=
9988 dx=mp_make_fraction(mp, dx,d);
9989 dy=mp_make_fraction(mp, dy,d);
9990 mp_find_offset(mp, -dy,dx,pp);
9991 xx=mp->cur_x; yy=mp->cur_y
9992
9993 @ @<Use |(dx,dy)| to generate a vertex of the square end cap and...@>=
9994 mp_find_offset(mp, dx,dy,pp);
9995 d=mp_take_fraction(mp, xx-mp->cur_x,dx)+mp_take_fraction(mp, yy-mp->cur_y,dy);
9996 if ( ((d<0)&&(i==1)) || ((d>0)&&(i==2))) 
9997   mp_confusion(mp, "box_ends");
9998 @:this can't happen box ends}{\quad\\{box\_ends}@>
9999 z=x_coord(p)+mp->cur_x+mp_take_fraction(mp, d,dx);
10000 if ( z<minx_val(h) ) minx_val(h)=z;
10001 if ( z>maxx_val(h) ) maxx_val(h)=z;
10002 z=y_coord(p)+mp->cur_y+mp_take_fraction(mp, d,dy);
10003 if ( z<miny_val(h) ) miny_val(h)=z;
10004 if ( z>maxy_val(h) ) maxy_val(h)=z
10005
10006 @ @<Advance |p| to the end of the path and make |q| the previous knot@>=
10007 do {  
10008   q=p;
10009   p=link(p);
10010 } while (right_type(p)!=endpoint)
10011
10012 @ The major difficulty in finding the bounding box of an edge structure is the
10013 effect of clipping paths.  We treat them conservatively by only clipping to the
10014 clipping path's bounding box, but this still
10015 requires recursive calls to |set_bbox| in order to find the bounding box of
10016 @^recursion@>
10017 the objects to be clipped.  Such calls are distinguished by the fact that the
10018 boolean parameter |top_level| is false.
10019
10020 @c void mp_set_bbox (MP mp,pointer h, boolean top_level) {
10021   pointer p;  /* a graphical object being considered */
10022   scaled sminx,sminy,smaxx,smaxy;
10023   /* for saving the bounding box during recursive calls */
10024   scaled x0,x1,y0,y1;  /* temporary registers */
10025   integer lev;  /* nesting level for |mp_start_bounds_code| nodes */
10026   @<Wipe out any existing bounding box information if |bbtype(h)| is
10027   incompatible with |internal[true_corners]|@>;
10028   while ( link(bblast(h))!=null ) { 
10029     p=link(bblast(h));
10030     bblast(h)=p;
10031     switch (type(p)) {
10032     case mp_stop_clip_code: 
10033       if ( top_level ) mp_confusion(mp, "bbox");  else return;
10034 @:this can't happen bbox}{\quad bbox@>
10035       break;
10036     @<Other cases for updating the bounding box based on the type of object |p|@>;
10037     } /* all cases are enumerated above */
10038   }
10039   if ( ! top_level ) mp_confusion(mp, "bbox");
10040 }
10041
10042 @ @<Wipe out any existing bounding box information if |bbtype(h)| is...@>=
10043 switch (bbtype(h)) {
10044 case no_bounds: 
10045   break;
10046 case bounds_set: 
10047   if ( mp->internal[true_corners]>0 ) mp_init_bbox(mp, h);
10048   break;
10049 case bounds_unset: 
10050   if ( mp->internal[true_corners]<=0 ) mp_init_bbox(mp, h);
10051   break;
10052 } /* there are no other cases */
10053
10054 @ @<Other cases for updating the bounding box...@>=
10055 case fill_code: 
10056   mp_path_bbox(mp, path_p(p));
10057   if ( pen_p(p)!=null ) { 
10058     x0=minx; y0=miny;
10059     x1=maxx; y1=maxy;
10060     mp_pen_bbox(mp, pen_p(p));
10061     minx=minx+x0;
10062     miny=miny+y0;
10063     maxx=maxx+x1;
10064     maxy=maxy+y1;
10065   }
10066   mp_adjust_bbox(mp, h);
10067   break;
10068
10069 @ @<Other cases for updating the bounding box...@>=
10070 case mp_start_bounds_code: 
10071   if ( mp->internal[true_corners]>0 ) {
10072     bbtype(h)=bounds_unset;
10073   } else { 
10074     bbtype(h)=bounds_set;
10075     mp_path_bbox(mp, path_p(p));
10076     mp_adjust_bbox(mp, h);
10077     @<Scan to the matching |mp_stop_bounds_code| node and update |p| and
10078       |bblast(h)|@>;
10079   }
10080   break;
10081 case mp_stop_bounds_code: 
10082   if ( mp->internal[true_corners]<=0 ) mp_confusion(mp, "bbox2");
10083 @:this can't happen bbox2}{\quad bbox2@>
10084   break;
10085
10086 @ @<Scan to the matching |mp_stop_bounds_code| node and update |p| and...@>=
10087 lev=1;
10088 while ( lev!=0 ) { 
10089   if ( link(p)==null ) mp_confusion(mp, "bbox2");
10090 @:this can't happen bbox2}{\quad bbox2@>
10091   p=link(p);
10092   if ( type(p)==mp_start_bounds_code ) incr(lev);
10093   else if ( type(p)==mp_stop_bounds_code ) decr(lev);
10094 }
10095 bblast(h)=p
10096
10097 @ It saves a lot of grief here to be slightly conservative and not account for
10098 omitted parts of dashed lines.  We also don't worry about the material omitted
10099 when using butt end caps.  The basic computation is for round end caps and
10100 |box_ends| augments it for square end caps.
10101
10102 @<Other cases for updating the bounding box...@>=
10103 case stroked_code: 
10104   mp_path_bbox(mp, path_p(p));
10105   x0=minx; y0=miny;
10106   x1=maxx; y1=maxy;
10107   mp_pen_bbox(mp, pen_p(p));
10108   minx=minx+x0;
10109   miny=miny+y0;
10110   maxx=maxx+x1;
10111   maxy=maxy+y1;
10112   mp_adjust_bbox(mp, h);
10113   if ( (left_type(path_p(p))==endpoint)&&(lcap_val(p)==2) )
10114     mp_box_ends(mp, path_p(p), pen_p(p), h);
10115   break;
10116
10117 @ The height width and depth information stored in a text node determines a
10118 rectangle that needs to be transformed according to the transformation
10119 parameters stored in the text node.
10120
10121 @<Other cases for updating the bounding box...@>=
10122 case text_code: 
10123   x1=mp_take_scaled(mp, txx_val(p),width_val(p));
10124   y0=mp_take_scaled(mp, txy_val(p),-depth_val(p));
10125   y1=mp_take_scaled(mp, txy_val(p),height_val(p));
10126   minx=tx_val(p);
10127   maxx=minx;
10128   if ( y0<y1 ) { minx=minx+y0; maxx=maxx+y1;  }
10129   else         { minx=minx+y1; maxx=maxx+y0;  }
10130   if ( x1<0 ) minx=minx+x1;  else maxx=maxx+x1;
10131   x1=mp_take_scaled(mp, tyx_val(p),width_val(p));
10132   y0=mp_take_scaled(mp, tyy_val(p),-depth_val(p));
10133   y1=mp_take_scaled(mp, tyy_val(p),height_val(p));
10134   miny=ty_val(p);
10135   maxy=miny;
10136   if ( y0<y1 ) { miny=miny+y0; maxy=maxy+y1;  }
10137   else         { miny=miny+y1; maxy=maxy+y0;  }
10138   if ( x1<0 ) miny=miny+x1;  else maxy=maxy+x1;
10139   mp_adjust_bbox(mp, h);
10140   break;
10141
10142 @ This case involves a recursive call that advances |bblast(h)| to the node of
10143 type |mp_stop_clip_code| that matches |p|.
10144
10145 @<Other cases for updating the bounding box...@>=
10146 case mp_start_clip_code: 
10147   mp_path_bbox(mp, path_p(p));
10148   x0=minx; y0=miny;
10149   x1=maxx; y1=maxy;
10150   sminx=minx_val(h); sminy=miny_val(h);
10151   smaxx=maxx_val(h); smaxy=maxy_val(h);
10152   @<Reinitialize the bounding box in header |h| and call |set_bbox| recursively
10153     starting at |link(p)|@>;
10154   @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,
10155     |y0|, |y1|@>;
10156   minx=sminx; miny=sminy;
10157   maxx=smaxx; maxy=smaxy;
10158   mp_adjust_bbox(mp, h);
10159   break;
10160
10161 @ @<Reinitialize the bounding box in header |h| and call |set_bbox|...@>=
10162 minx_val(h)=el_gordo;
10163 miny_val(h)=el_gordo;
10164 maxx_val(h)=-el_gordo;
10165 maxy_val(h)=-el_gordo;
10166 mp_set_bbox(mp, h,false)
10167
10168 @ @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,...@>=
10169 if ( minx_val(h)<x0 ) minx_val(h)=x0;
10170 if ( miny_val(h)<y0 ) miny_val(h)=y0;
10171 if ( maxx_val(h)>x1 ) maxx_val(h)=x1;
10172 if ( maxy_val(h)>y1 ) maxy_val(h)=y1
10173
10174 @* \[22] Finding an envelope.
10175 When \MP\ has a path and a polygonal pen, it needs to express the desired
10176 shape in terms of things \ps\ can understand.  The present task is to compute
10177 a new path that describes the region to be filled.  It is convenient to
10178 define this as a two step process where the first step is determining what
10179 offset to use for each segment of the path.
10180
10181 @ Given a pointer |c| to a cyclic path,
10182 and a pointer~|h| to the first knot of a pen polygon,
10183 the |offset_prep| routine changes the path into cubics that are
10184 associated with particular pen offsets. Thus if the cubic between |p|
10185 and~|q| is associated with the |k|th offset and the cubic between |q| and~|r|
10186 has offset |l| then |info(q)=zero_off+l-k|. (The constant |zero_off| is added
10187 to because |l-k| could be negative.)
10188
10189 After overwriting the type information with offset differences, we no longer
10190 have a true path so we refer to the knot list returned by |offset_prep| as an
10191 ``envelope spec.''
10192 @^envelope spec@>
10193 Since an envelope spec only determines relative changes in pen offsets,
10194 |offset_prep| sets a global variable |spec_offset| to the relative change from
10195 |h| to the first offset.
10196
10197 @d zero_off 16384 /* added to offset changes to make them positive */
10198
10199 @<Glob...@>=
10200 integer spec_offset; /* number of pen edges between |h| and the initial offset */
10201
10202 @ @c @<Declare subroutines needed by |offset_prep|@>;
10203 pointer mp_offset_prep (MP mp,pointer c, pointer h) {
10204   halfword n; /* the number of vertices in the pen polygon */
10205   pointer p,q,r,w, ww; /* for list manipulation */
10206   integer k_needed; /* amount to be added to |info(p)| when it is computed */
10207   pointer w0; /* a pointer to pen offset to use just before |p| */
10208   scaled dxin,dyin; /* the direction into knot |p| */
10209   integer turn_amt; /* change in pen offsets for the current cubic */
10210   @<Other local variables for |offset_prep|@>;
10211   dx0=0; dy0=0;
10212   @<Initialize the pen size~|n|@>;
10213   @<Initialize the incoming direction and pen offset at |c|@>;
10214   p=c; k_needed=0;
10215   do {  
10216     q=link(p);
10217     @<Split the cubic between |p| and |q|, if necessary, into cubics
10218       associated with single offsets, after which |q| should
10219       point to the end of the final such cubic@>;
10220     @<Advance |p| to node |q|, removing any ``dead'' cubics that
10221       might have been introduced by the splitting process@>;
10222   } while (q!=c);
10223   @<Fix the offset change in |info(c)| and set the return value of
10224     |offset_prep|@>;
10225 }
10226
10227 @ We shall want to keep track of where certain knots on the cyclic path
10228 wind up in the envelope spec.  It doesn't suffice just to keep pointers to
10229 knot nodes because some nodes are deleted while removing dead cubics.  Thus
10230 |offset_prep| updates the following pointers
10231
10232 @<Glob...@>=
10233 pointer spec_p1;
10234 pointer spec_p2; /* pointers to distinguished knots */
10235
10236 @ @<Set init...@>=
10237 mp->spec_p1=null; mp->spec_p2=null;
10238
10239 @ @<Initialize the pen size~|n|@>=
10240 n=0; p=h;
10241 do {  
10242   incr(n);
10243   p=link(p);
10244 } while (p!=h)
10245
10246 @ Since the true incoming direction isn't known yet, we just pick a direction
10247 consistent with the pen offset~|h|.  If this is wrong, it can be corrected
10248 later.
10249
10250 @<Initialize the incoming direction and pen offset at |c|@>=
10251 dxin=x_coord(link(h))-x_coord(knil(h));
10252 dyin=y_coord(link(h))-y_coord(knil(h));
10253 if ( (dxin==0)&&(dyin==0) ) {
10254   dxin=y_coord(knil(h))-y_coord(h);
10255   dyin=x_coord(h)-x_coord(knil(h));
10256 }
10257 w0=h
10258
10259 @ We must be careful not to remove the only cubic in a cycle.
10260
10261 But we must also be careful for another reason. If the user-supplied
10262 path starts with a set of degenerate cubics, these should not be removed
10263 because at this point we cannot do so cleanly. The relevant bug is
10264 tracker id 267, bugs 52c, reported by Boguslav.
10265
10266 @<Advance |p| to node |q|, removing any ``dead'' cubics...@>=
10267 do {  r=link(p);
10268 if ( x_coord(p)==right_x(p) ) if ( y_coord(p)==right_y(p) )
10269  if ( x_coord(p)==left_x(r) ) if ( y_coord(p)==left_y(r) )
10270   if ( x_coord(p)==x_coord(r) ) if ( y_coord(p)==y_coord(r) )
10271     if ( r!=p ) if ( ((r!=q) || (originator(r)!=metapost_user)) ) {
10272       @<Remove the cubic following |p| and update the data structures
10273         to merge |r| into |p|@>;
10274 }
10275 p=r;
10276 } while (p!=q)
10277
10278 @ @<Remove the cubic following |p| and update the data structures...@>=
10279 { k_needed=info(p)-zero_off;
10280   if ( r==q ) { 
10281     q=p;
10282   } else { 
10283     info(p)=k_needed+info(r);
10284     k_needed=0;
10285   };
10286   if ( r==c ) { info(p)=info(c); c=p; };
10287   if ( r==mp->spec_p1 ) mp->spec_p1=p;
10288   if ( r==mp->spec_p2 ) mp->spec_p2=p;
10289   r=p; mp_remove_cubic(mp, p);
10290 }
10291
10292 @ Not setting the |info| field of the newly created knot allows the splitting
10293 routine to work for paths.
10294
10295 @<Declare subroutines needed by |offset_prep|@>=
10296 void mp_split_cubic (MP mp,pointer p, fraction t) { /* splits the cubic after |p| */
10297   scaled v; /* an intermediate value */
10298   pointer q,r; /* for list manipulation */
10299   q=link(p); r=mp_get_node(mp, knot_node_size); link(p)=r; link(r)=q;
10300   originator(r)=program_code;
10301   left_type(r)=explicit; right_type(r)=explicit;
10302   v=t_of_the_way(right_x(p),left_x(q));
10303   right_x(p)=t_of_the_way(x_coord(p),right_x(p));
10304   left_x(q)=t_of_the_way(left_x(q),x_coord(q));
10305   left_x(r)=t_of_the_way(right_x(p),v);
10306   right_x(r)=t_of_the_way(v,left_x(q));
10307   x_coord(r)=t_of_the_way(left_x(r),right_x(r));
10308   v=t_of_the_way(right_y(p),left_y(q));
10309   right_y(p)=t_of_the_way(y_coord(p),right_y(p));
10310   left_y(q)=t_of_the_way(left_y(q),y_coord(q));
10311   left_y(r)=t_of_the_way(right_y(p),v);
10312   right_y(r)=t_of_the_way(v,left_y(q));
10313   y_coord(r)=t_of_the_way(left_y(r),right_y(r));
10314 }
10315
10316 @ This does not set |info(p)| or |right_type(p)|.
10317
10318 @<Declare subroutines needed by |offset_prep|@>=
10319 void mp_remove_cubic (MP mp,pointer p) { /* removes the dead cubic following~|p| */
10320   pointer q; /* the node that disappears */
10321   q=link(p); link(p)=link(q);
10322   right_x(p)=right_x(q); right_y(p)=right_y(q);
10323   mp_free_node(mp, q,knot_node_size);
10324 }
10325
10326 @ Let $d\prec d'$ mean that the counter-clockwise angle from $d$ to~$d'$ is
10327 strictly between zero and $180^\circ$.  Then we can define $d\preceq d'$ to
10328 mean that the angle could be zero or $180^\circ$. If $w_k=(u_k,v_k)$ is the
10329 $k$th pen offset, the $k$th pen edge direction is defined by the formula
10330 $$d_k=(u\k-u_k,\,v\k-v_k).$$
10331 When listed by increasing $k$, these directions occur in counter-clockwise
10332 order so that $d_k\preceq d\k$ for all~$k$.
10333 The goal of |offset_prep| is to find an offset index~|k| to associate with
10334 each cubic, such that the direction $d(t)$ of the cubic satisfies
10335 $$d_{k-1}\preceq d(t)\preceq d_k\qquad\hbox{for $0\le t\le 1$.}\eqno(*)$$
10336 We may have to split a cubic into many pieces before each
10337 piece corresponds to a unique offset.
10338
10339 @<Split the cubic between |p| and |q|, if necessary, into cubics...@>=
10340 info(p)=zero_off+k_needed;
10341 k_needed=0;
10342 @<Prepare for derivative computations;
10343   |goto not_found| if the current cubic is dead@>;
10344 @<Find the initial direction |(dx,dy)|@>;
10345 @<Update |info(p)| and find the offset $w_k$ such that
10346   $d_{k-1}\preceq(\\{dx},\\{dy})\prec d_k$; also advance |w0| for
10347   the direction change at |p|@>;
10348 @<Find the final direction |(dxin,dyin)|@>;
10349 @<Decide on the net change in pen offsets and set |turn_amt|@>;
10350 @<Complete the offset splitting process@>;
10351 w0=mp_pen_walk(mp, w0,turn_amt);
10352 NOT_FOUND: do_nothing
10353
10354 @ @<Declare subroutines needed by |offset_prep|@>=
10355 pointer mp_pen_walk (MP mp,pointer w, integer k) {
10356   /* walk |k| steps around a pen from |w| */
10357   while ( k>0 ) { w=link(w); decr(k);  };
10358   while ( k<0 ) { w=knil(w); incr(k);  };
10359   return w;
10360 }
10361
10362 @ The direction of a cubic $B(z_0,z_1,z_2,z_3;t)=\bigl(x(t),y(t)\bigr)$ can be
10363 calculated from the quadratic polynomials
10364 ${1\over3}x'(t)=B(x_1-x_0,x_2-x_1,x_3-x_2;t)$ and
10365 ${1\over3}y'(t)=B(y_1-y_0,y_2-y_1,y_3-y_2;t)$.
10366 Since we may be calculating directions from several cubics
10367 split from the current one, it is desirable to do these calculations
10368 without losing too much precision. ``Scaled up'' values of the
10369 derivatives, which will be less tainted by accumulated errors than
10370 derivatives found from the cubics themselves, are maintained in
10371 local variables |x0|, |x1|, and |x2|, representing $X_0=2^l(x_1-x_0)$,
10372 $X_1=2^l(x_2-x_1)$, and $X_2=2^l(x_3-x_2)$; similarly |y0|, |y1|, and~|y2|
10373 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)$.
10374
10375 @<Other local variables for |offset_prep|@>=
10376 integer x0,x1,x2,y0,y1,y2; /* representatives of derivatives */
10377 integer t0,t1,t2; /* coefficients of polynomial for slope testing */
10378 integer du,dv,dx,dy; /* for directions of the pen and the curve */
10379 integer dx0,dy0; /* initial direction for the first cubic in the curve */
10380 integer mp_max_coef; /* used while scaling */
10381 integer x0a,x1a,x2a,y0a,y1a,y2a; /* intermediate values */
10382 fraction t; /* where the derivative passes through zero */
10383 fraction s; /* a temporary value */
10384
10385 @ @<Prepare for derivative computations...@>=
10386 x0=right_x(p)-x_coord(p);
10387 x2=x_coord(q)-left_x(q);
10388 x1=left_x(q)-right_x(p);
10389 y0=right_y(p)-y_coord(p); y2=y_coord(q)-left_y(q);
10390 y1=left_y(q)-right_y(p);
10391 mp_max_coef=abs(x0);
10392 if ( abs(x1)>mp_max_coef ) mp_max_coef=abs(x1);
10393 if ( abs(x2)>mp_max_coef ) mp_max_coef=abs(x2);
10394 if ( abs(y0)>mp_max_coef ) mp_max_coef=abs(y0);
10395 if ( abs(y1)>mp_max_coef ) mp_max_coef=abs(y1);
10396 if ( abs(y2)>mp_max_coef ) mp_max_coef=abs(y2);
10397 if ( mp_max_coef==0 ) goto NOT_FOUND;
10398 while ( mp_max_coef<fraction_half ) {
10399   mp_max_coef+=mp_max_coef;
10400   x0+=x0; x1+=x1; x2+=x2;
10401   y0+=y0; y1+=y1; y2+=y2;
10402 }
10403
10404 @ Let us first solve a special case of the problem: Suppose we
10405 know an index~$k$ such that either (i)~$d(t)\succeq d_{k-1}$ for all~$t$
10406 and $d(0)\prec d_k$, or (ii)~$d(t)\preceq d_k$ for all~$t$ and
10407 $d(0)\succ d_{k-1}$.
10408 Then, in a sense, we're halfway done, since one of the two relations
10409 in $(*)$ is satisfied, and the other couldn't be satisfied for
10410 any other value of~|k|.
10411
10412 Actually, the conditions can be relaxed somewhat since a relation such as
10413 $d(t)\succeq d_{k-1}$ restricts $d(t)$ to a half plane when all that really
10414 matters is whether $d(t)$ crosses the ray in the $d_{k-1}$ direction from
10415 the origin.  The condition for case~(i) becomes $d_{k-1}\preceq d(0)\prec d_k$
10416 and $d(t)$ never crosses the $d_{k-1}$ ray in the clockwise direction.
10417 Case~(ii) is similar except $d(t)$ cannot cross the $d_k$ ray in the
10418 counterclockwise direction.
10419
10420 The |fin_offset_prep| subroutine solves the stated subproblem.
10421 It has a parameter called |rise| that is |1| in
10422 case~(i), |-1| in case~(ii). Parameters |x0| through |y2| represent
10423 the derivative of the cubic following |p|.
10424 The |w| parameter should point to offset~$w_k$ and |info(p)| should already
10425 be set properly.  The |turn_amt| parameter gives the absolute value of the
10426 overall net change in pen offsets.
10427
10428 @<Declare subroutines needed by |offset_prep|@>=
10429 void mp_fin_offset_prep (MP mp,pointer p, pointer w, integer 
10430   x0,integer x1, integer x2, integer y0, integer y1, integer y2, 
10431   integer rise, integer turn_amt)  {
10432   pointer ww; /* for list manipulation */
10433   scaled du,dv; /* for slope calculation */
10434   integer t0,t1,t2; /* test coefficients */
10435   fraction t; /* place where the derivative passes a critical slope */
10436   fraction s; /* slope or reciprocal slope */
10437   integer v; /* intermediate value for updating |x0..y2| */
10438   pointer q; /* original |link(p)| */
10439   q=link(p);
10440   while (1)  { 
10441     if ( rise>0 ) ww=link(w); /* a pointer to $w\k$ */
10442     else  ww=knil(w); /* a pointer to $w_{k-1}$ */
10443     @<Compute test coefficients |(t0,t1,t2)|
10444       for $d(t)$ versus $d_k$ or $d_{k-1}$@>;
10445     t=mp_crossing_point(mp, t0,t1,t2);
10446     if ( t>=fraction_one ) {
10447       if ( turn_amt>0 ) t=fraction_one;  else return;
10448     }
10449     @<Split the cubic at $t$,
10450       and split off another cubic if the derivative crosses back@>;
10451     w=ww;
10452   }
10453 }
10454
10455 @ We want $B(\\{t0},\\{t1},\\{t2};t)$ to be the dot product of $d(t)$ with a
10456 $-90^\circ$ rotation of the vector from |w| to |ww|.  This makes the resulting
10457 function cross from positive to negative when $d_{k-1}\preceq d(t)\preceq d_k$
10458 begins to fail.
10459
10460 @<Compute test coefficients |(t0,t1,t2)| for $d(t)$ versus...@>=
10461 du=x_coord(ww)-x_coord(w); dv=y_coord(ww)-y_coord(w);
10462 if ( abs(du)>=abs(dv) ) {
10463   s=mp_make_fraction(mp, dv,du);
10464   t0=mp_take_fraction(mp, x0,s)-y0;
10465   t1=mp_take_fraction(mp, x1,s)-y1;
10466   t2=mp_take_fraction(mp, x2,s)-y2;
10467   if ( du<0 ) { negate(t0); negate(t1); negate(t2);  }
10468 } else { 
10469   s=mp_make_fraction(mp, du,dv);
10470   t0=x0-mp_take_fraction(mp, y0,s);
10471   t1=x1-mp_take_fraction(mp, y1,s);
10472   t2=x2-mp_take_fraction(mp, y2,s);
10473   if ( dv<0 ) { negate(t0); negate(t1); negate(t2);  }
10474 }
10475 if ( t0<0 ) t0=0 /* should be positive without rounding error */
10476
10477 @ The curve has crossed $d_k$ or $d_{k-1}$; its initial segment satisfies
10478 $(*)$, and it might cross again, yielding another solution of $(*)$.
10479
10480 @<Split the cubic at $t$, and split off another...@>=
10481
10482 mp_split_cubic(mp, p,t); p=link(p); info(p)=zero_off+rise;
10483 decr(turn_amt);
10484 v=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10485 x0=t_of_the_way(v,x1);
10486 v=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10487 y0=t_of_the_way(v,y1);
10488 if ( turn_amt<0 ) {
10489   t1=t_of_the_way(t1,t2);
10490   if ( t1>0 ) t1=0; /* without rounding error, |t1| would be |<=0| */
10491   t=mp_crossing_point(mp, 0,-t1,-t2);
10492   if ( t>fraction_one ) t=fraction_one;
10493   incr(turn_amt);
10494   if ( (t==fraction_one)&&(link(p)!=q) ) {
10495     info(link(p))=info(link(p))-rise;
10496   } else { 
10497     mp_split_cubic(mp, p,t); info(link(p))=zero_off-rise;
10498     v=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10499     x2=t_of_the_way(x1,v);
10500     v=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10501     y2=t_of_the_way(y1,v);
10502   }
10503 }
10504 }
10505
10506 @ Now we must consider the general problem of |offset_prep|, when
10507 nothing is known about a given cubic. We start by finding its
10508 direction in the vicinity of |t=0|.
10509
10510 If $z'(t)=0$, the given cubic is numerically unstable but |offset_prep|
10511 has not yet introduced any more numerical errors.  Thus we can compute
10512 the true initial direction for the given cubic, even if it is almost
10513 degenerate.
10514
10515 @<Find the initial direction |(dx,dy)|@>=
10516 dx=x0; dy=y0;
10517 if ( dx==0 ) if ( dy==0 ) { 
10518   dx=x1; dy=y1;
10519   if ( dx==0 ) if ( dy==0 ) { 
10520     dx=x2; dy=y2;
10521   }
10522 }
10523 if ( p==c ) { dx0=dx; dy0=dy;  }
10524
10525 @ @<Find the final direction |(dxin,dyin)|@>=
10526 dxin=x2; dyin=y2;
10527 if ( dxin==0 ) if ( dyin==0 ) {
10528   dxin=x1; dyin=y1;
10529   if ( dxin==0 ) if ( dyin==0 ) {
10530     dxin=x0; dyin=y0;
10531   }
10532 }
10533
10534 @ The next step is to bracket the initial direction between consecutive
10535 edges of the pen polygon.  We must be careful to turn clockwise only if
10536 this makes the turn less than $180^\circ$. (A $180^\circ$ turn must be
10537 counter-clockwise in order to make \&{doublepath} envelopes come out
10538 @:double_path_}{\&{doublepath} primitive@>
10539 right.) This code depends on |w0| being the offset for |(dxin,dyin)|.
10540
10541 @<Update |info(p)| and find the offset $w_k$ such that...@>=
10542 turn_amt=mp_get_turn_amt(mp, w0, dx, dy, mp_ab_vs_cd(mp, dy,dxin,dx,dyin)>=0);
10543 w=mp_pen_walk(mp, w0, turn_amt);
10544 w0=w;
10545 info(p)=info(p)+turn_amt
10546
10547 @ Decide how many pen offsets to go away from |w| in order to find the offset
10548 for |(dx,dy)|, going counterclockwise if |ccw| is |true|.  This assumes that
10549 |w| is the offset for some direction $(x',y')$ from which the angle to |(dx,dy)|
10550 in the sense determined by |ccw| is less than or equal to $180^\circ$.
10551
10552 If the pen polygon has only two edges, they could both be parallel
10553 to |(dx,dy)|.  In this case, we must be careful to stop after crossing the first
10554 such edge in order to avoid an infinite loop.
10555
10556 @<Declare subroutines needed by |offset_prep|@>=
10557 integer mp_get_turn_amt (MP mp,pointer w, scaled  dx,
10558                          scaled dy, boolean  ccw) {
10559   pointer ww; /* a neighbor of knot~|w| */
10560   integer s; /* turn amount so far */
10561   integer t; /* |ab_vs_cd| result */
10562   s=0;
10563   if ( ccw ) { 
10564     ww=link(w);
10565     do {  
10566       t=mp_ab_vs_cd(mp, dy,x_coord(ww)-x_coord(w),
10567                         dx,y_coord(ww)-y_coord(w));
10568       if ( t<0 ) break;
10569       incr(s);
10570       w=ww; ww=link(ww);
10571     } while (t>0);
10572   } else { 
10573     ww=knil(w);
10574     while ( mp_ab_vs_cd(mp, dy,x_coord(w)-x_coord(ww),
10575                             dx,y_coord(w)-y_coord(ww))<0 ) { 
10576       decr(s);
10577       w=ww; ww=knil(ww);
10578     }
10579   }
10580   return s;
10581 }
10582
10583 @ When we're all done, the final offset is |w0| and the final curve direction
10584 is |(dxin,dyin)|.  With this knowledge of the incoming direction at |c|, we
10585 can correct |info(c)| which was erroneously based on an incoming offset
10586 of~|h|.
10587
10588 @d fix_by(A) info(c)=info(c)+(A)
10589
10590 @<Fix the offset change in |info(c)| and set the return value of...@>=
10591 mp->spec_offset=info(c)-zero_off;
10592 if ( link(c)==c ) {
10593   info(c)=zero_off+n;
10594 } else { 
10595   fix_by(k_needed);
10596   while ( w0!=h ) { fix_by(1); w0=link(w0);  };
10597   while ( info(c)<=zero_off-n ) fix_by(n);
10598   while ( info(c)>zero_off ) fix_by(-n);
10599   if ( (info(c)!=zero_off)&&(mp_ab_vs_cd(mp, dy0,dxin,dx0,dyin)>=0) ) fix_by(n);
10600 }
10601 return c
10602
10603 @ Finally we want to reduce the general problem to situations that
10604 |fin_offset_prep| can handle. We split the cubic into at most three parts
10605 with respect to $d_{k-1}$, and apply |fin_offset_prep| to each part.
10606
10607 @<Complete the offset splitting process@>=
10608 ww=knil(w);
10609 @<Compute test coeff...@>;
10610 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set
10611   |t:=fraction_one+1|@>;
10612 if ( t>fraction_one ) {
10613   mp_fin_offset_prep(mp, p,w,x0,x1,x2,y0,y1,y2,1,turn_amt);
10614 } else {
10615   mp_split_cubic(mp, p,t); r=link(p);
10616   x1a=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10617   x2a=t_of_the_way(x1a,x1);
10618   y1a=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10619   y2a=t_of_the_way(y1a,y1);
10620   mp_fin_offset_prep(mp, p,w,x0,x1a,x2a,y0,y1a,y2a,1,0); x0=x2a; y0=y2a;
10621   info(r)=zero_off-1;
10622   if ( turn_amt>=0 ) {
10623     t1=t_of_the_way(t1,t2);
10624     if ( t1>0 ) t1=0;
10625     t=mp_crossing_point(mp, 0,-t1,-t2);
10626     if ( t>fraction_one ) t=fraction_one;
10627     @<Split off another rising cubic for |fin_offset_prep|@>;
10628     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,0);
10629   } else {
10630     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,-1-turn_amt);
10631   }
10632 }
10633
10634 @ @<Split off another rising cubic for |fin_offset_prep|@>=
10635 mp_split_cubic(mp, r,t); info(link(r))=zero_off+1;
10636 x1a=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10637 x0a=t_of_the_way(x1,x1a);
10638 y1a=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10639 y0a=t_of_the_way(y1,y1a);
10640 mp_fin_offset_prep(mp, link(r),w,x0a,x1a,x2,y0a,y1a,y2,1,turn_amt);
10641 x2=x0a; y2=y0a
10642
10643 @ At this point, the direction of the incoming pen edge is |(-du,-dv)|.
10644 When the component of $d(t)$ perpendicular to |(-du,-dv)| crosses zero, we
10645 need to decide whether the directions are parallel or antiparallel.  We
10646 can test this by finding the dot product of $d(t)$ and |(-du,-dv)|, but this
10647 should be avoided when the value of |turn_amt| already determines the
10648 answer.  If |t2<0|, there is one crossing and it is antiparallel only if
10649 |turn_amt>=0|.  If |turn_amt<0|, there should always be at least one
10650 crossing and the first crossing cannot be antiparallel.
10651
10652 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set...@>=
10653 t=mp_crossing_point(mp, t0,t1,t2);
10654 if ( turn_amt>=0 ) {
10655   if ( t2<0 ) {
10656     t=fraction_one+1;
10657   } else { 
10658     u0=t_of_the_way(x0,x1);
10659     u1=t_of_the_way(x1,x2);
10660     ss=mp_take_fraction(mp, -du,t_of_the_way(u0,u1));
10661     v0=t_of_the_way(y0,y1);
10662     v1=t_of_the_way(y1,y2);
10663     ss=ss+mp_take_fraction(mp, -dv,t_of_the_way(v0,v1));
10664     if ( ss<0 ) t=fraction_one+1;
10665   }
10666 } else if ( t>fraction_one ) {
10667   t=fraction_one;
10668 }
10669
10670 @ @<Other local variables for |offset_prep|@>=
10671 integer u0,u1,v0,v1; /* intermediate values for $d(t)$ calculation */
10672 integer ss = 0; /* the part of the dot product computed so far */
10673 int d_sign; /* sign of overall change in direction for this cubic */
10674
10675 @ If the cubic almost has a cusp, it is a numerically ill-conditioned
10676 problem to decide which way it loops around but that's OK as long we're
10677 consistent.  To make \&{doublepath} envelopes work properly, reversing
10678 the path should always change the sign of |turn_amt|.
10679
10680 @<Decide on the net change in pen offsets and set |turn_amt|@>=
10681 d_sign=mp_ab_vs_cd(mp, dx,dyin, dxin,dy);
10682 if ( d_sign==0 ) {
10683   if ( dx==0 ) {
10684     if ( dy>0 ) d_sign=1;  else d_sign=-1;
10685   } else if ( dx>0 ) { 
10686     d_sign=1;  
10687   } else { 
10688     d_sign=-1; 
10689   }
10690 }
10691 @<Make |ss| negative if and only if the total change in direction is
10692   more than $180^\circ$@>;
10693 turn_amt=mp_get_turn_amt(mp, w, dxin, dyin, d_sign>0);
10694 if ( ss<0 ) turn_amt=turn_amt-d_sign*n
10695
10696 @ In order to be invariant under path reversal, the result of this computation
10697 should not change when |x0|, |y0|, $\ldots$ are all negated and |(x0,y0)| is
10698 then swapped with |(x2,y2)|.  We make use of the identities
10699 |take_fraction(-a,-b)=take_fraction(a,b)| and
10700 |t_of_the_way(-a,-b)=-(t_of_the_way(a,b))|.
10701
10702 @<Make |ss| negative if and only if the total change in direction is...@>=
10703 t0=half(mp_take_fraction(mp, x0,y2))-half(mp_take_fraction(mp, x2,y0));
10704 t1=half(mp_take_fraction(mp, x1,y0+y2))-half(mp_take_fraction(mp, y1,x0+x2));
10705 if ( t0==0 ) t0=d_sign; /* path reversal always negates |d_sign| */
10706 if ( t0>0 ) {
10707   t=mp_crossing_point(mp, t0,t1,-t0);
10708   u0=t_of_the_way(x0,x1);
10709   u1=t_of_the_way(x1,x2);
10710   v0=t_of_the_way(y0,y1);
10711   v1=t_of_the_way(y1,y2);
10712 } else { 
10713   t=mp_crossing_point(mp, -t0,t1,t0);
10714   u0=t_of_the_way(x2,x1);
10715   u1=t_of_the_way(x1,x0);
10716   v0=t_of_the_way(y2,y1);
10717   v1=t_of_the_way(y1,y0);
10718 }
10719 s=mp_take_fraction(mp, x0+x2,t_of_the_way(u0,u1))+
10720   mp_take_fraction(mp, y0+y2,t_of_the_way(v0,v1))
10721
10722 @ Here's a routine that prints an envelope spec in symbolic form.  It assumes
10723 that the |cur_pen| has not been walked around to the first offset.
10724
10725 @c 
10726 void mp_print_spec (MP mp,pointer cur_spec, pointer cur_pen, char *s) {
10727   pointer p,q; /* list traversal */
10728   pointer w; /* the current pen offset */
10729   mp_print_diagnostic(mp, "Envelope spec",s,true);
10730   p=cur_spec; w=mp_pen_walk(mp, cur_pen,mp->spec_offset);
10731   mp_print_ln(mp);
10732   mp_print_two(mp, x_coord(cur_spec),y_coord(cur_spec));
10733   mp_print(mp, " % beginning with offset ");
10734   mp_print_two(mp, x_coord(w),y_coord(w));
10735   do { 
10736     do {  
10737       q=link(p);
10738       @<Print the cubic between |p| and |q|@>;
10739       p=q;
10740     } while (! ((p==cur_spec) || (info(p)!=zero_off)));
10741     if ( info(p)!=zero_off ) {
10742       @<Update |w| as indicated by |info(p)| and print an explanation@>;
10743     }
10744   } while (p!=cur_spec);
10745   mp_print_nl(mp, " & cycle");
10746   mp_end_diagnostic(mp, true);
10747 }
10748
10749 @ @<Update |w| as indicated by |info(p)| and print an explanation@>=
10750
10751   w=mp_pen_walk(mp, w,info(p)-zero_off);
10752   mp_print(mp, " % ");
10753   if ( info(p)>zero_off ) mp_print(mp, "counter");
10754   mp_print(mp, "clockwise to offset ");
10755   mp_print_two(mp, x_coord(w),y_coord(w));
10756 }
10757
10758 @ @<Print the cubic between |p| and |q|@>=
10759
10760   mp_print_nl(mp, "   ..controls ");
10761   mp_print_two(mp, right_x(p),right_y(p));
10762   mp_print(mp, " and ");
10763   mp_print_two(mp, left_x(q),left_y(q));
10764   mp_print_nl(mp, " ..");
10765   mp_print_two(mp, x_coord(q),y_coord(q));
10766 }
10767
10768 @ Once we have an envelope spec, the remaining task to construct the actual
10769 envelope by offsetting each cubic as determined by the |info| fields in
10770 the knots.  First we use |offset_prep| to convert the |c| into an envelope
10771 spec. Then we add the offsets so that |c| becomes a cyclic path that represents
10772 the envelope.
10773
10774 The |ljoin| and |miterlim| parameters control the treatment of points where the
10775 pen offset changes, and |lcap| controls the endpoints of a \&{doublepath}.
10776 The endpoints are easily located because |c| is given in undoubled form
10777 and then doubled in this procedure.  We use |spec_p1| and |spec_p2| to keep
10778 track of the endpoints and treat them like very sharp corners.
10779 Butt end caps are treated like beveled joins; round end caps are treated like
10780 round joins; and square end caps are achieved by setting |join_type:=3|.
10781
10782 None of these parameters apply to inside joins where the convolution tracing
10783 has retrograde lines.  In such cases we use a simple connect-the-endpoints
10784 approach that is achieved by setting |join_type:=2|.
10785
10786 @c @<Declare a function called |insert_knot|@>;
10787 pointer mp_make_envelope (MP mp,pointer c, pointer h, small_number ljoin,
10788   small_number lcap, scaled miterlim) {
10789   pointer p,q,r,q0; /* for manipulating the path */
10790   int join_type=0; /* codes |0..3| for mitered, round, beveled, or square */
10791   pointer w,w0; /* the pen knot for the current offset */
10792   scaled qx,qy; /* unshifted coordinates of |q| */
10793   halfword k,k0; /* controls pen edge insertion */
10794   @<Other local variables for |make_envelope|@>;
10795   dxin=0; dyin=0; dxout=0; dyout=0;
10796   mp->spec_p1=null; mp->spec_p2=null;
10797   @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>;
10798   @<Use |offset_prep| to compute the envelope spec then walk |h| around to
10799     the initial offset@>;
10800   w=h;
10801   p=c;
10802   do {  
10803     q=link(p); q0=q;
10804     qx=x_coord(q); qy=y_coord(q);
10805     k=info(q);
10806     k0=k; w0=w;
10807     if ( k!=zero_off ) {
10808       @<Set |join_type| to indicate how to handle offset changes at~|q|@>;
10809     }
10810     @<Add offset |w| to the cubic from |p| to |q|@>;
10811     while ( k!=zero_off ) { 
10812       @<Step |w| and move |k| one step closer to |zero_off|@>;
10813       if ( (join_type==1)||(k==zero_off) )
10814          q=mp_insert_knot(mp, q,qx+x_coord(w),qy+y_coord(w));
10815     };
10816     if ( q!=link(p) ) {
10817       @<Set |p=link(p)| and add knots between |p| and |q| as
10818         required by |join_type|@>;
10819     }
10820     p=q;
10821   } while (q0!=c);
10822   return c;
10823 }
10824
10825 @ @<Use |offset_prep| to compute the envelope spec then walk |h| around to...@>=
10826 c=mp_offset_prep(mp, c,h);
10827 if ( mp->internal[tracing_specs]>0 ) 
10828   mp_print_spec(mp, c,h,"");
10829 h=mp_pen_walk(mp, h,mp->spec_offset)
10830
10831 @ Mitered and squared-off joins depend on path directions that are difficult to
10832 compute for degenerate cubics.  The envelope spec computed by |offset_prep| can
10833 have degenerate cubics only if the entire cycle collapses to a single
10834 degenerate cubic.  Setting |join_type:=2| in this case makes the computed
10835 envelope degenerate as well.
10836
10837 @<Set |join_type| to indicate how to handle offset changes at~|q|@>=
10838 if ( k<zero_off ) {
10839   join_type=2;
10840 } else {
10841   if ( (q!=mp->spec_p1)&&(q!=mp->spec_p2) ) join_type=ljoin;
10842   else if ( lcap==2 ) join_type=3;
10843   else join_type=2-lcap;
10844   if ( (join_type==0)||(join_type==3) ) {
10845     @<Set the incoming and outgoing directions at |q|; in case of
10846       degeneracy set |join_type:=2|@>;
10847     if ( join_type==0 ) {
10848       @<If |miterlim| is less than the secant of half the angle at |q|
10849         then set |join_type:=2|@>;
10850     }
10851   }
10852 }
10853
10854 @ @<If |miterlim| is less than the secant of half the angle at |q|...@>=
10855
10856   tmp=mp_take_fraction(mp, miterlim,fraction_half+
10857       half(mp_take_fraction(mp, dxin,dxout)+mp_take_fraction(mp, dyin,dyout)));
10858   if ( tmp<unity )
10859     if ( mp_take_scaled(mp, miterlim,tmp)<unity ) join_type=2;
10860 }
10861
10862 @ @<Other local variables for |make_envelope|@>=
10863 fraction dxin,dyin,dxout,dyout; /* directions at |q| when square or mitered */
10864 scaled tmp; /* a temporary value */
10865
10866 @ The coordinates of |p| have already been shifted unless |p| is the first
10867 knot in which case they get shifted at the very end.
10868
10869 @<Add offset |w| to the cubic from |p| to |q|@>=
10870 right_x(p)=right_x(p)+x_coord(w);
10871 right_y(p)=right_y(p)+y_coord(w);
10872 left_x(q)=left_x(q)+x_coord(w);
10873 left_y(q)=left_y(q)+y_coord(w);
10874 x_coord(q)=x_coord(q)+x_coord(w);
10875 y_coord(q)=y_coord(q)+y_coord(w);
10876 left_type(q)=explicit;
10877 right_type(q)=explicit
10878
10879 @ @<Step |w| and move |k| one step closer to |zero_off|@>=
10880 if ( k>zero_off ){ w=link(w); decr(k);  }
10881 else { w=knil(w); incr(k);  }
10882
10883 @ The cubic from |q| to the new knot at |(x,y)| becomes a line segment and
10884 the |right_x| and |right_y| fields of |r| are set from |q|.  This is done in
10885 case the cubic containing these control points is ``yet to be examined.''
10886
10887 @<Declare a function called |insert_knot|@>=
10888 pointer mp_insert_knot (MP mp,pointer q, scaled x, scaled y) {
10889   /* returns the inserted knot */
10890   pointer r; /* the new knot */
10891   r=mp_get_node(mp, knot_node_size);
10892   link(r)=link(q); link(q)=r;
10893   right_x(r)=right_x(q);
10894   right_y(r)=right_y(q);
10895   x_coord(r)=x;
10896   y_coord(r)=y;
10897   right_x(q)=x_coord(q);
10898   right_y(q)=y_coord(q);
10899   left_x(r)=x_coord(r);
10900   left_y(r)=y_coord(r);
10901   left_type(r)=explicit;
10902   right_type(r)=explicit;
10903   originator(r)=program_code;
10904   return r;
10905 }
10906
10907 @ After setting |p:=link(p)|, either |join_type=1| or |q=link(p)|.
10908
10909 @<Set |p=link(p)| and add knots between |p| and |q| as...@>=
10910
10911   p=link(p);
10912   if ( (join_type==0)||(join_type==3) ) {
10913     if ( join_type==0 ) {
10914       @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>
10915     } else {
10916       @<Make |r| the last of two knots inserted between |p| and |q| to form a
10917         squared join@>;
10918     }
10919     if ( r!=null ) { 
10920       right_x(r)=x_coord(r);
10921       right_y(r)=y_coord(r);
10922     }
10923   }
10924 }
10925
10926 @ For very small angles, adding a knot is unnecessary and would cause numerical
10927 problems, so we just set |r:=null| in that case.
10928
10929 @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>=
10930
10931   det=mp_take_fraction(mp, dyout,dxin)-mp_take_fraction(mp, dxout,dyin);
10932   if ( abs(det)<26844 ) { 
10933      r=null; /* sine $<10^{-4}$ */
10934   } else { 
10935     tmp=mp_take_fraction(mp, x_coord(q)-x_coord(p),dyout)-
10936         mp_take_fraction(mp, y_coord(q)-y_coord(p),dxout);
10937     tmp=mp_make_fraction(mp, tmp,det);
10938     r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
10939       y_coord(p)+mp_take_fraction(mp, tmp,dyin));
10940   }
10941 }
10942
10943 @ @<Other local variables for |make_envelope|@>=
10944 fraction det; /* a determinant used for mitered join calculations */
10945
10946 @ @<Make |r| the last of two knots inserted between |p| and |q| to form a...@>=
10947
10948   ht_x=y_coord(w)-y_coord(w0);
10949   ht_y=x_coord(w0)-x_coord(w);
10950   while ( (abs(ht_x)<fraction_half)&&(abs(ht_y)<fraction_half) ) { 
10951     ht_x+=ht_x; ht_y+=ht_y;
10952   }
10953   @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range dot
10954     product with |(ht_x,ht_y)|@>;
10955   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxin,ht_x)+
10956                                   mp_take_fraction(mp, dyin,ht_y));
10957   r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
10958                          y_coord(p)+mp_take_fraction(mp, tmp,dyin));
10959   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxout,ht_x)+
10960                                   mp_take_fraction(mp, dyout,ht_y));
10961   r=mp_insert_knot(mp, r,x_coord(q)+mp_take_fraction(mp, tmp,dxout),
10962                          y_coord(q)+mp_take_fraction(mp, tmp,dyout));
10963 }
10964
10965 @ @<Other local variables for |make_envelope|@>=
10966 fraction ht_x,ht_y; /* perpendicular to the segment from |p| to |q| */
10967 scaled max_ht; /* maximum height of the pen polygon above the |w0|-|w| line */
10968 halfword kk; /* keeps track of the pen vertices being scanned */
10969 pointer ww; /* the pen vertex being tested */
10970
10971 @ The dot product of the vector from |w0| to |ww| with |(ht_x,ht_y)| ranges
10972 from zero to |max_ht|.
10973
10974 @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range...@>=
10975 max_ht=0;
10976 kk=zero_off;
10977 ww=w;
10978 while (1)  { 
10979   @<Step |ww| and move |kk| one step closer to |k0|@>;
10980   if ( kk==k0 ) break;
10981   tmp=mp_take_fraction(mp, x_coord(ww)-x_coord(w0),ht_x)+
10982       mp_take_fraction(mp, y_coord(ww)-y_coord(w0),ht_y);
10983   if ( tmp>max_ht ) max_ht=tmp;
10984 }
10985
10986
10987 @ @<Step |ww| and move |kk| one step closer to |k0|@>=
10988 if ( kk>k0 ) { ww=link(ww); decr(kk);  }
10989 else { ww=knil(ww); incr(kk);  }
10990
10991 @ @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>=
10992 if ( left_type(c)==endpoint ) { 
10993   mp->spec_p1=mp_htap_ypoc(mp, c);
10994   mp->spec_p2=mp->path_tail;
10995   originator(mp->spec_p1)=program_code;
10996   link(mp->spec_p2)=link(mp->spec_p1);
10997   link(mp->spec_p1)=c;
10998   mp_remove_cubic(mp, mp->spec_p1);
10999   c=mp->spec_p1;
11000   if ( c!=link(c) ) {
11001     originator(mp->spec_p2)=program_code;
11002     mp_remove_cubic(mp, mp->spec_p2);
11003   } else {
11004     @<Make |c| look like a cycle of length one@>;
11005   }
11006 }
11007
11008 @ @<Make |c| look like a cycle of length one@>=
11009
11010   left_type(c)=explicit; right_type(c)=explicit;
11011   left_x(c)=x_coord(c); left_y(c)=y_coord(c);
11012   right_x(c)=x_coord(c); right_y(c)=y_coord(c);
11013 }
11014
11015 @ In degenerate situations we might have to look at the knot preceding~|q|.
11016 That knot is |p| but if |p<>c|, its coordinates have already been offset by |w|.
11017
11018 @<Set the incoming and outgoing directions at |q|; in case of...@>=
11019 dxin=x_coord(q)-left_x(q);
11020 dyin=y_coord(q)-left_y(q);
11021 if ( (dxin==0)&&(dyin==0) ) {
11022   dxin=x_coord(q)-right_x(p);
11023   dyin=y_coord(q)-right_y(p);
11024   if ( (dxin==0)&&(dyin==0) ) {
11025     dxin=x_coord(q)-x_coord(p);
11026     dyin=y_coord(q)-y_coord(p);
11027     if ( p!=c ) { /* the coordinates of |p| have been offset by |w| */
11028       dxin=dxin+x_coord(w);
11029       dyin=dyin+y_coord(w);
11030     }
11031   }
11032 }
11033 tmp=mp_pyth_add(mp, dxin,dyin);
11034 if ( tmp==0 ) {
11035   join_type=2;
11036 } else { 
11037   dxin=mp_make_fraction(mp, dxin,tmp);
11038   dyin=mp_make_fraction(mp, dyin,tmp);
11039   @<Set the outgoing direction at |q|@>;
11040 }
11041
11042 @ If |q=c| then the coordinates of |r| and the control points between |q|
11043 and~|r| have already been offset by |h|.
11044
11045 @<Set the outgoing direction at |q|@>=
11046 dxout=right_x(q)-x_coord(q);
11047 dyout=right_y(q)-y_coord(q);
11048 if ( (dxout==0)&&(dyout==0) ) {
11049   r=link(q);
11050   dxout=left_x(r)-x_coord(q);
11051   dyout=left_y(r)-y_coord(q);
11052   if ( (dxout==0)&&(dyout==0) ) {
11053     dxout=x_coord(r)-x_coord(q);
11054     dyout=y_coord(r)-y_coord(q);
11055   }
11056 }
11057 if ( q==c ) {
11058   dxout=dxout-x_coord(h);
11059   dyout=dyout-y_coord(h);
11060 }
11061 tmp=mp_pyth_add(mp, dxout,dyout);
11062 if ( tmp==0 ) mp_confusion(mp, "degenerate spec");
11063 @:this can't happen degerate spec}{\quad degenerate spec@>
11064 dxout=mp_make_fraction(mp, dxout,tmp);
11065 dyout=mp_make_fraction(mp, dyout,tmp)
11066
11067 @* \[23] Direction and intersection times.
11068 A path of length $n$ is defined parametrically by functions $x(t)$ and
11069 $y(t)$, for |0<=t<=n|; we can regard $t$ as the ``time'' at which the path
11070 reaches the point $\bigl(x(t),y(t)\bigr)$.  In this section of the program
11071 we shall consider operations that determine special times associated with
11072 given paths: the first time that a path travels in a given direction, and
11073 a pair of times at which two paths cross each other.
11074
11075 @ Let's start with the easier task. The function |find_direction_time| is
11076 given a direction |(x,y)| and a path starting at~|h|. If the path never
11077 travels in direction |(x,y)|, the direction time will be~|-1|; otherwise
11078 it will be nonnegative.
11079
11080 Certain anomalous cases can arise: If |(x,y)=(0,0)|, so that the given
11081 direction is undefined, the direction time will be~0. If $\bigl(x'(t),
11082 y'(t)\bigr)=(0,0)$, so that the path direction is undefined, it will be
11083 assumed to match any given direction at time~|t|.
11084
11085 The routine solves this problem in nondegenerate cases by rotating the path
11086 and the given direction so that |(x,y)=(1,0)|; i.e., the main task will be
11087 to find when a given path first travels ``due east.''
11088
11089 @c 
11090 scaled mp_find_direction_time (MP mp,scaled x, scaled y, pointer h) {
11091   scaled max; /* $\max\bigl(\vert x\vert,\vert y\vert\bigr)$ */
11092   pointer p,q; /* for list traversal */
11093   scaled n; /* the direction time at knot |p| */
11094   scaled tt; /* the direction time within a cubic */
11095   @<Other local variables for |find_direction_time|@>;
11096   @<Normalize the given direction for better accuracy;
11097     but |return| with zero result if it's zero@>;
11098   n=0; p=h; phi=0;
11099   while (1) { 
11100     if ( right_type(p)==endpoint ) break;
11101     q=link(p);
11102     @<Rotate the cubic between |p| and |q|; then
11103       |goto found| if the rotated cubic travels due east at some time |tt|;
11104       but |break| if an entire cyclic path has been traversed@>;
11105     p=q; n=n+unity;
11106   }
11107   return (-unity);
11108 FOUND: 
11109   return (n+tt);
11110 }
11111
11112 @ @<Normalize the given direction for better accuracy...@>=
11113 if ( abs(x)<abs(y) ) { 
11114   x=mp_make_fraction(mp, x,abs(y));
11115   if ( y>0 ) y=fraction_one; else y=-fraction_one;
11116 } else if ( x==0 ) { 
11117   return 0;
11118 } else  { 
11119   y=mp_make_fraction(mp, y,abs(x));
11120   if ( x>0 ) x=fraction_one; else x=-fraction_one;
11121 }
11122
11123 @ Since we're interested in the tangent directions, we work with the
11124 derivative $${\textstyle1\over3}B'(x_0,x_1,x_2,x_3;t)=
11125 B(x_1-x_0,x_2-x_1,x_3-x_2;t)$$ instead of
11126 $B(x_0,x_1,x_2,x_3;t)$ itself. The derived coefficients are also scaled up
11127 in order to achieve better accuracy.
11128
11129 The given path may turn abruptly at a knot, and it might pass the critical
11130 tangent direction at such a time. Therefore we remember the direction |phi|
11131 in which the previous rotated cubic was traveling. (The value of |phi| will be
11132 undefined on the first cubic, i.e., when |n=0|.)
11133
11134 @<Rotate the cubic between |p| and |q|; then...@>=
11135 tt=0;
11136 @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples of the control
11137   points of the rotated derivatives@>;
11138 if ( y1==0 ) if ( x1>=0 ) goto FOUND;
11139 if ( n>0 ) { 
11140   @<Exit to |found| if an eastward direction occurs at knot |p|@>;
11141   if ( p==h ) break;
11142   };
11143 if ( (x3!=0)||(y3!=0) ) phi=mp_n_arg(mp, x3,y3);
11144 @<Exit to |found| if the curve whose derivatives are specified by
11145   |x1,x2,x3,y1,y2,y3| travels eastward at some time~|tt|@>
11146
11147 @ @<Other local variables for |find_direction_time|@>=
11148 scaled x1,x2,x3,y1,y2,y3;  /* multiples of rotated derivatives */
11149 angle theta,phi; /* angles of exit and entry at a knot */
11150 fraction t; /* temp storage */
11151
11152 @ @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples...@>=
11153 x1=right_x(p)-x_coord(p); x2=left_x(q)-right_x(p);
11154 x3=x_coord(q)-left_x(q);
11155 y1=right_y(p)-y_coord(p); y2=left_y(q)-right_y(p);
11156 y3=y_coord(q)-left_y(q);
11157 max=abs(x1);
11158 if ( abs(x2)>max ) max=abs(x2);
11159 if ( abs(x3)>max ) max=abs(x3);
11160 if ( abs(y1)>max ) max=abs(y1);
11161 if ( abs(y2)>max ) max=abs(y2);
11162 if ( abs(y3)>max ) max=abs(y3);
11163 if ( max==0 ) goto FOUND;
11164 while ( max<fraction_half ){ 
11165   max+=max; x1+=x1; x2+=x2; x3+=x3;
11166   y1+=y1; y2+=y2; y3+=y3;
11167 }
11168 t=x1; x1=mp_take_fraction(mp, x1,x)+mp_take_fraction(mp, y1,y);
11169 y1=mp_take_fraction(mp, y1,x)-mp_take_fraction(mp, t,y);
11170 t=x2; x2=mp_take_fraction(mp, x2,x)+mp_take_fraction(mp, y2,y);
11171 y2=mp_take_fraction(mp, y2,x)-mp_take_fraction(mp, t,y);
11172 t=x3; x3=mp_take_fraction(mp, x3,x)+mp_take_fraction(mp, y3,y);
11173 y3=mp_take_fraction(mp, y3,x)-mp_take_fraction(mp, t,y)
11174
11175 @ @<Exit to |found| if an eastward direction occurs at knot |p|@>=
11176 theta=mp_n_arg(mp, x1,y1);
11177 if ( theta>=0 ) if ( phi<=0 ) if ( phi>=theta-one_eighty_deg ) goto FOUND;
11178 if ( theta<=0 ) if ( phi>=0 ) if ( phi<=theta+one_eighty_deg ) goto FOUND
11179
11180 @ In this step we want to use the |crossing_point| routine to find the
11181 roots of the quadratic equation $B(y_1,y_2,y_3;t)=0$.
11182 Several complications arise: If the quadratic equation has a double root,
11183 the curve never crosses zero, and |crossing_point| will find nothing;
11184 this case occurs iff $y_1y_3=y_2^2$ and $y_1y_2<0$. If the quadratic
11185 equation has simple roots, or only one root, we may have to negate it
11186 so that $B(y_1,y_2,y_3;t)$ crosses from positive to negative at its first root.
11187 And finally, we need to do special things if $B(y_1,y_2,y_3;t)$ is
11188 identically zero.
11189
11190 @ @<Exit to |found| if the curve whose derivatives are specified by...@>=
11191 if ( x1<0 ) if ( x2<0 ) if ( x3<0 ) goto DONE;
11192 if ( mp_ab_vs_cd(mp, y1,y3,y2,y2)==0 ) {
11193   @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11194     either |goto found| or |goto done|@>;
11195 }
11196 if ( y1<=0 ) {
11197   if ( y1<0 ) { y1=-y1; y2=-y2; y3=-y3; }
11198   else if ( y2>0 ){ y2=-y2; y3=-y3; };
11199 }
11200 @<Check the places where $B(y_1,y_2,y_3;t)=0$ to see if
11201   $B(x_1,x_2,x_3;t)\ge0$@>;
11202 DONE:
11203
11204 @ The quadratic polynomial $B(y_1,y_2,y_3;t)$ begins |>=0| and has at most
11205 two roots, because we know that it isn't identically zero.
11206
11207 It must be admitted that the |crossing_point| routine is not perfectly accurate;
11208 rounding errors might cause it to find a root when $y_1y_3>y_2^2$, or to
11209 miss the roots when $y_1y_3<y_2^2$. The rotation process is itself
11210 subject to rounding errors. Yet this code optimistically tries to
11211 do the right thing.
11212
11213 @d we_found_it { tt=(t+04000) / 010000; goto FOUND; }
11214
11215 @<Check the places where $B(y_1,y_2,y_3;t)=0$...@>=
11216 t=mp_crossing_point(mp, y1,y2,y3);
11217 if ( t>fraction_one ) goto DONE;
11218 y2=t_of_the_way(y2,y3);
11219 x1=t_of_the_way(x1,x2);
11220 x2=t_of_the_way(x2,x3);
11221 x1=t_of_the_way(x1,x2);
11222 if ( x1>=0 ) we_found_it;
11223 if ( y2>0 ) y2=0;
11224 tt=t; t=mp_crossing_point(mp, 0,-y2,-y3);
11225 if ( t>fraction_one ) goto DONE;
11226 x1=t_of_the_way(x1,x2);
11227 x2=t_of_the_way(x2,x3);
11228 if ( t_of_the_way(x1,x2)>=0 ) { 
11229   t=t_of_the_way(tt,fraction_one); we_found_it;
11230 }
11231
11232 @ @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11233     either |goto found| or |goto done|@>=
11234
11235   if ( mp_ab_vs_cd(mp, y1,y2,0,0)<0 ) {
11236     t=mp_make_fraction(mp, y1,y1-y2);
11237     x1=t_of_the_way(x1,x2);
11238     x2=t_of_the_way(x2,x3);
11239     if ( t_of_the_way(x1,x2)>=0 ) we_found_it;
11240   } else if ( y3==0 ) {
11241     if ( y1==0 ) {
11242       @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|@>;
11243     } else if ( x3>=0 ) {
11244       tt=unity; goto FOUND;
11245     }
11246   }
11247   goto DONE;
11248 }
11249
11250 @ At this point we know that the derivative of |y(t)| is identically zero,
11251 and that |x1<0|; but either |x2>=0| or |x3>=0|, so there's some hope of
11252 traveling east.
11253
11254 @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|...@>=
11255
11256   t=mp_crossing_point(mp, -x1,-x2,-x3);
11257   if ( t<=fraction_one ) we_found_it;
11258   if ( mp_ab_vs_cd(mp, x1,x3,x2,x2)<=0 ) { 
11259     t=mp_make_fraction(mp, x1,x1-x2); we_found_it;
11260   }
11261 }
11262
11263 @ The intersection of two cubics can be found by an interesting variant
11264 of the general bisection scheme described in the introduction to
11265 |crossing_point|.\
11266 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)$,
11267 we wish to find a pair of times $(t_1,t_2)$ such that $w(t_1)=z(t_2)$,
11268 if an intersection exists. First we find the smallest rectangle that
11269 encloses the points $\{w_0,w_1,w_2,w_3\}$ and check that it overlaps
11270 the smallest rectangle that encloses
11271 $\{z_0,z_1,z_2,z_3\}$; if not, the cubics certainly don't intersect.
11272 But if the rectangles do overlap, we bisect the intervals, getting
11273 new cubics $w'$ and~$w''$, $z'$~and~$z''$; the intersection routine first
11274 tries for an intersection between $w'$ and~$z'$, then (if unsuccessful)
11275 between $w'$ and~$z''$, then (if still unsuccessful) between $w''$ and~$z'$,
11276 finally (if thrice unsuccessful) between $w''$ and~$z''$. After $l$~successful
11277 levels of bisection we will have determined the intersection times $t_1$
11278 and~$t_2$ to $l$~bits of accuracy.
11279
11280 \def\submin{_{\rm min}} \def\submax{_{\rm max}}
11281 As before, it is better to work with the numbers $W_k=2^l(w_k-w_{k-1})$
11282 and $Z_k=2^l(z_k-z_{k-1})$ rather than the coefficients $w_k$ and $z_k$
11283 themselves. We also need one other quantity, $\Delta=2^l(w_0-z_0)$,
11284 to determine when the enclosing rectangles overlap. Here's why:
11285 The $x$~coordinates of~$w(t)$ are between $u\submin$ and $u\submax$,
11286 and the $x$~coordinates of~$z(t)$ are between $x\submin$ and $x\submax$,
11287 if we write $w_k=(u_k,v_k)$ and $z_k=(x_k,y_k)$ and $u\submin=
11288 \min(u_0,u_1,u_2,u_3)$, etc. These intervals of $x$~coordinates
11289 overlap if and only if $u\submin\L x\submax$ and
11290 $x\submin\L u\submax$. Letting
11291 $$U\submin=\min(0,U_1,U_1+U_2,U_1+U_2+U_3),\;
11292   U\submax=\max(0,U_1,U_1+U_2,U_1+U_2+U_3),$$
11293 we have $u\submin=2^lu_0+U\submin$, etc.; the condition for overlap
11294 reduces to
11295 $$X\submin-U\submax\L 2^l(u_0-x_0)\L X\submax-U\submin.$$
11296 Thus we want to maintain the quantity $2^l(u_0-x_0)$; similarly,
11297 the quantity $2^l(v_0-y_0)$ accounts for the $y$~coordinates. The
11298 coordinates of $\Delta=2^l(w_0-z_0)$ must stay bounded as $l$ increases,
11299 because of the overlap condition; i.e., we know that $X\submin$,
11300 $X\submax$, and their relatives are bounded, hence $X\submax-
11301 U\submin$ and $X\submin-U\submax$ are bounded.
11302
11303 @ Incidentally, if the given cubics intersect more than once, the process
11304 just sketched will not necessarily find the lexicographically smallest pair
11305 $(t_1,t_2)$. The solution actually obtained will be smallest in ``shuffled
11306 order''; i.e., if $t_1=(.a_1a_2\ldots a_{16})_2$ and
11307 $t_2=(.b_1b_2\ldots b_{16})_2$, then we will minimize
11308 $a_1b_1a_2b_2\ldots a_{16}b_{16}$, not
11309 $a_1a_2\ldots a_{16}b_1b_2\ldots b_{16}$.
11310 Shuffled order agrees with lexicographic order if all pairs of solutions
11311 $(t_1,t_2)$ and $(t_1',t_2')$ have the property that $t_1<t_1'$ iff
11312 $t_2<t_2'$; but in general, lexicographic order can be quite different,
11313 and the bisection algorithm would be substantially less efficient if it were
11314 constrained by lexicographic order.
11315
11316 For example, suppose that an overlap has been found for $l=3$ and
11317 $(t_1,t_2)= (.101,.011)$ in binary, but that no overlap is produced by
11318 either of the alternatives $(.1010,.0110)$, $(.1010,.0111)$ at level~4.
11319 Then there is probably an intersection in one of the subintervals
11320 $(.1011,.011x)$; but lexicographic order would require us to explore
11321 $(.1010,.1xxx)$ and $(.1011,.00xx)$ and $(.1011,.010x)$ first. We wouldn't
11322 want to store all of the subdivision data for the second path, so the
11323 subdivisions would have to be regenerated many times. Such inefficiencies
11324 would be associated with every `1' in the binary representation of~$t_1$.
11325
11326 @ The subdivision process introduces rounding errors, hence we need to
11327 make a more liberal test for overlap. It is not hard to show that the
11328 computed values of $U_i$ differ from the truth by at most~$l$, on
11329 level~$l$, hence $U\submin$ and $U\submax$ will be at most $3l$ in error.
11330 If $\beta$ is an upper bound on the absolute error in the computed
11331 components of $\Delta=(|delx|,|dely|)$ on level~$l$, we will replace
11332 the test `$X\submin-U\submax\L|delx|$' by the more liberal test
11333 `$X\submin-U\submax\L|delx|+|tol|$', where $|tol|=6l+\beta$.
11334
11335 More accuracy is obtained if we try the algorithm first with |tol=0|;
11336 the more liberal tolerance is used only if an exact approach fails.
11337 It is convenient to do this double-take by letting `3' in the preceding
11338 paragraph be a parameter, which is first 0, then 3.
11339
11340 @<Glob...@>=
11341 unsigned int tol_step; /* either 0 or 3, usually */
11342
11343 @ We shall use an explicit stack to implement the recursive bisection
11344 method described above. The |bisect_stack| array will contain numerous 5-word
11345 packets like $(U_1,U_2,U_3,U\submin,U\submax)$, as well as 20-word packets
11346 comprising the 5-word packets for $U$, $V$, $X$, and~$Y$.
11347
11348 The following macros define the allocation of stack positions to
11349 the quantities needed for bisection-intersection.
11350
11351 @d stack_1(A) mp->bisect_stack[(A)] /* $U_1$, $V_1$, $X_1$, or $Y_1$ */
11352 @d stack_2(A) mp->bisect_stack[(A)+1] /* $U_2$, $V_2$, $X_2$, or $Y_2$ */
11353 @d stack_3(A) mp->bisect_stack[(A)+2] /* $U_3$, $V_3$, $X_3$, or $Y_3$ */
11354 @d stack_min(A) mp->bisect_stack[(A)+3]
11355   /* $U\submin$, $V\submin$, $X\submin$, or $Y\submin$ */
11356 @d stack_max(A) mp->bisect_stack[(A)+4]
11357   /* $U\submax$, $V\submax$, $X\submax$, or $Y\submax$ */
11358 @d int_packets 20 /* number of words to represent $U_k$, $V_k$, $X_k$, and $Y_k$ */
11359 @#
11360 @d u_packet(A) ((A)-5)
11361 @d v_packet(A) ((A)-10)
11362 @d x_packet(A) ((A)-15)
11363 @d y_packet(A) ((A)-20)
11364 @d l_packets (mp->bisect_ptr-int_packets)
11365 @d r_packets mp->bisect_ptr
11366 @d ul_packet u_packet(l_packets) /* base of $U'_k$ variables */
11367 @d vl_packet v_packet(l_packets) /* base of $V'_k$ variables */
11368 @d xl_packet x_packet(l_packets) /* base of $X'_k$ variables */
11369 @d yl_packet y_packet(l_packets) /* base of $Y'_k$ variables */
11370 @d ur_packet u_packet(r_packets) /* base of $U''_k$ variables */
11371 @d vr_packet v_packet(r_packets) /* base of $V''_k$ variables */
11372 @d xr_packet x_packet(r_packets) /* base of $X''_k$ variables */
11373 @d yr_packet y_packet(r_packets) /* base of $Y''_k$ variables */
11374 @#
11375 @d u1l stack_1(ul_packet) /* $U'_1$ */
11376 @d u2l stack_2(ul_packet) /* $U'_2$ */
11377 @d u3l stack_3(ul_packet) /* $U'_3$ */
11378 @d v1l stack_1(vl_packet) /* $V'_1$ */
11379 @d v2l stack_2(vl_packet) /* $V'_2$ */
11380 @d v3l stack_3(vl_packet) /* $V'_3$ */
11381 @d x1l stack_1(xl_packet) /* $X'_1$ */
11382 @d x2l stack_2(xl_packet) /* $X'_2$ */
11383 @d x3l stack_3(xl_packet) /* $X'_3$ */
11384 @d y1l stack_1(yl_packet) /* $Y'_1$ */
11385 @d y2l stack_2(yl_packet) /* $Y'_2$ */
11386 @d y3l stack_3(yl_packet) /* $Y'_3$ */
11387 @d u1r stack_1(ur_packet) /* $U''_1$ */
11388 @d u2r stack_2(ur_packet) /* $U''_2$ */
11389 @d u3r stack_3(ur_packet) /* $U''_3$ */
11390 @d v1r stack_1(vr_packet) /* $V''_1$ */
11391 @d v2r stack_2(vr_packet) /* $V''_2$ */
11392 @d v3r stack_3(vr_packet) /* $V''_3$ */
11393 @d x1r stack_1(xr_packet) /* $X''_1$ */
11394 @d x2r stack_2(xr_packet) /* $X''_2$ */
11395 @d x3r stack_3(xr_packet) /* $X''_3$ */
11396 @d y1r stack_1(yr_packet) /* $Y''_1$ */
11397 @d y2r stack_2(yr_packet) /* $Y''_2$ */
11398 @d y3r stack_3(yr_packet) /* $Y''_3$ */
11399 @#
11400 @d stack_dx mp->bisect_stack[mp->bisect_ptr] /* stacked value of |delx| */
11401 @d stack_dy mp->bisect_stack[mp->bisect_ptr+1] /* stacked value of |dely| */
11402 @d stack_tol mp->bisect_stack[mp->bisect_ptr+2] /* stacked value of |tol| */
11403 @d stack_uv mp->bisect_stack[mp->bisect_ptr+3] /* stacked value of |uv| */
11404 @d stack_xy mp->bisect_stack[mp->bisect_ptr+4] /* stacked value of |xy| */
11405 @d int_increment (int_packets+int_packets+5) /* number of stack words per level */
11406
11407 @<Glob...@>=
11408 integer *bisect_stack;
11409 unsigned int bisect_ptr;
11410
11411 @ @<Allocate or initialize ...@>=
11412 mp->bisect_stack = xmalloc((bistack_size+1),sizeof(integer));
11413
11414 @ @<Dealloc variables@>=
11415 xfree(mp->bisect_stack);
11416
11417 @ @<Check the ``constant''...@>=
11418 if ( int_packets+17*int_increment>bistack_size ) mp->bad=19;
11419
11420 @ Computation of the min and max is a tedious but fairly fast sequence of
11421 instructions; exactly four comparisons are made in each branch.
11422
11423 @d set_min_max(A) 
11424   if ( stack_1((A))<0 ) {
11425     if ( stack_3((A))>=0 ) {
11426       if ( stack_2((A))<0 ) stack_min((A))=stack_1((A))+stack_2((A));
11427       else stack_min((A))=stack_1((A));
11428       stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11429       if ( stack_max((A))<0 ) stack_max((A))=0;
11430     } else { 
11431       stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11432       if ( stack_min((A))>stack_1((A)) ) stack_min((A))=stack_1((A));
11433       stack_max((A))=stack_1((A))+stack_2((A));
11434       if ( stack_max((A))<0 ) stack_max((A))=0;
11435     }
11436   } else if ( stack_3((A))<=0 ) {
11437     if ( stack_2((A))>0 ) stack_max((A))=stack_1((A))+stack_2((A));
11438     else stack_max((A))=stack_1((A));
11439     stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11440     if ( stack_min((A))>0 ) stack_min((A))=0;
11441   } else  { 
11442     stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11443     if ( stack_max((A))<stack_1((A)) ) stack_max((A))=stack_1((A));
11444     stack_min((A))=stack_1((A))+stack_2((A));
11445     if ( stack_min((A))>0 ) stack_min((A))=0;
11446   }
11447
11448 @ It's convenient to keep the current values of $l$, $t_1$, and $t_2$ in
11449 the integer form $2^l+2^lt_1$ and $2^l+2^lt_2$. The |cubic_intersection|
11450 routine uses global variables |cur_t| and |cur_tt| for this purpose;
11451 after successful completion, |cur_t| and |cur_tt| will contain |unity|
11452 plus the |scaled| values of $t_1$ and~$t_2$.
11453
11454 The values of |cur_t| and |cur_tt| will be set to zero if |cubic_intersection|
11455 finds no intersection. The routine gives up and gives an approximate answer
11456 if it has backtracked
11457 more than 5000 times (otherwise there are cases where several minutes
11458 of fruitless computation would be possible).
11459
11460 @d max_patience 5000
11461
11462 @<Glob...@>=
11463 integer cur_t;integer cur_tt; /* controls and results of |cubic_intersection| */
11464 integer time_to_go; /* this many backtracks before giving up */
11465 integer max_t; /* maximum of $2^{l+1}$ so far achieved */
11466
11467 @ The given cubics $B(w_0,w_1,w_2,w_3;t)$ and
11468 $B(z_0,z_1,z_2,z_3;t)$ are specified in adjacent knot nodes |(p,link(p))|
11469 and |(pp,link(pp))|, respectively.
11470
11471 @c void mp_cubic_intersection (MP mp,pointer p, pointer pp) {
11472   pointer q,qq; /* |link(p)|, |link(pp)| */
11473   mp->time_to_go=max_patience; mp->max_t=2;
11474   @<Initialize for intersections at level zero@>;
11475 CONTINUE:
11476   while (1) { 
11477     if ( mp->delx-mp->tol<=stack_max(x_packet(mp->xy))-stack_min(u_packet(mp->uv)))
11478     if ( mp->delx+mp->tol>=stack_min(x_packet(mp->xy))-stack_max(u_packet(mp->uv)))
11479     if ( mp->dely-mp->tol<=stack_max(y_packet(mp->xy))-stack_min(v_packet(mp->uv)))
11480     if ( mp->dely+mp->tol>=stack_min(y_packet(mp->xy))-stack_max(v_packet(mp->uv))) 
11481     { 
11482       if ( mp->cur_t>=mp->max_t ){ 
11483         if ( mp->max_t==two ) { /* we've done 17 bisections */ 
11484            mp->cur_t=halfp(mp->cur_t+1); mp->cur_tt=halfp(mp->cur_tt+1); return;
11485         }
11486         mp->max_t+=mp->max_t; mp->appr_t=mp->cur_t; mp->appr_tt=mp->cur_tt;
11487       }
11488       @<Subdivide for a new level of intersection@>;
11489       goto CONTINUE;
11490     }
11491     if ( mp->time_to_go>0 ) {
11492       decr(mp->time_to_go);
11493     } else { 
11494       while ( mp->appr_t<unity ) { 
11495         mp->appr_t+=mp->appr_t; mp->appr_tt+=mp->appr_tt;
11496       }
11497       mp->cur_t=mp->appr_t; mp->cur_tt=mp->appr_tt; return;
11498     }
11499     @<Advance to the next pair |(cur_t,cur_tt)|@>;
11500   }
11501 }
11502
11503 @ The following variables are global, although they are used only by
11504 |cubic_intersection|, because it is necessary on some machines to
11505 split |cubic_intersection| up into two procedures.
11506
11507 @<Glob...@>=
11508 integer delx;integer dely; /* the components of $\Delta=2^l(w_0-z_0)$ */
11509 integer tol; /* bound on the uncertainly in the overlap test */
11510 unsigned int uv;
11511 unsigned int xy; /* pointers to the current packets of interest */
11512 integer three_l; /* |tol_step| times the bisection level */
11513 integer appr_t;integer appr_tt; /* best approximations known to the answers */
11514
11515 @ We shall assume that the coordinates are sufficiently non-extreme that
11516 integer overflow will not occur.
11517
11518 @<Initialize for intersections at level zero@>=
11519 q=link(p); qq=link(pp); mp->bisect_ptr=int_packets;
11520 u1r=right_x(p)-x_coord(p); u2r=left_x(q)-right_x(p);
11521 u3r=x_coord(q)-left_x(q); set_min_max(ur_packet);
11522 v1r=right_y(p)-y_coord(p); v2r=left_y(q)-right_y(p);
11523 v3r=y_coord(q)-left_y(q); set_min_max(vr_packet);
11524 x1r=right_x(pp)-x_coord(pp); x2r=left_x(qq)-right_x(pp);
11525 x3r=x_coord(qq)-left_x(qq); set_min_max(xr_packet);
11526 y1r=right_y(pp)-y_coord(pp); y2r=left_y(qq)-right_y(pp);
11527 y3r=y_coord(qq)-left_y(qq); set_min_max(yr_packet);
11528 mp->delx=x_coord(p)-x_coord(pp); mp->dely=y_coord(p)-y_coord(pp);
11529 mp->tol=0; mp->uv=r_packets; mp->xy=r_packets; 
11530 mp->three_l=0; mp->cur_t=1; mp->cur_tt=1
11531
11532 @ @<Subdivide for a new level of intersection@>=
11533 stack_dx=mp->delx; stack_dy=mp->dely; stack_tol=mp->tol; 
11534 stack_uv=mp->uv; stack_xy=mp->xy;
11535 mp->bisect_ptr=mp->bisect_ptr+int_increment;
11536 mp->cur_t+=mp->cur_t; mp->cur_tt+=mp->cur_tt;
11537 u1l=stack_1(u_packet(mp->uv)); u3r=stack_3(u_packet(mp->uv));
11538 u2l=half(u1l+stack_2(u_packet(mp->uv)));
11539 u2r=half(u3r+stack_2(u_packet(mp->uv)));
11540 u3l=half(u2l+u2r); u1r=u3l;
11541 set_min_max(ul_packet); set_min_max(ur_packet);
11542 v1l=stack_1(v_packet(mp->uv)); v3r=stack_3(v_packet(mp->uv));
11543 v2l=half(v1l+stack_2(v_packet(mp->uv)));
11544 v2r=half(v3r+stack_2(v_packet(mp->uv)));
11545 v3l=half(v2l+v2r); v1r=v3l;
11546 set_min_max(vl_packet); set_min_max(vr_packet);
11547 x1l=stack_1(x_packet(mp->xy)); x3r=stack_3(x_packet(mp->xy));
11548 x2l=half(x1l+stack_2(x_packet(mp->xy)));
11549 x2r=half(x3r+stack_2(x_packet(mp->xy)));
11550 x3l=half(x2l+x2r); x1r=x3l;
11551 set_min_max(xl_packet); set_min_max(xr_packet);
11552 y1l=stack_1(y_packet(mp->xy)); y3r=stack_3(y_packet(mp->xy));
11553 y2l=half(y1l+stack_2(y_packet(mp->xy)));
11554 y2r=half(y3r+stack_2(y_packet(mp->xy)));
11555 y3l=half(y2l+y2r); y1r=y3l;
11556 set_min_max(yl_packet); set_min_max(yr_packet);
11557 mp->uv=l_packets; mp->xy=l_packets;
11558 mp->delx+=mp->delx; mp->dely+=mp->dely;
11559 mp->tol=mp->tol-mp->three_l+mp->tol_step; 
11560 mp->tol+=mp->tol; mp->three_l=mp->three_l+mp->tol_step
11561
11562 @ @<Advance to the next pair |(cur_t,cur_tt)|@>=
11563 NOT_FOUND: 
11564 if ( odd(mp->cur_tt) ) {
11565   if ( odd(mp->cur_t) ) {
11566      @<Descend to the previous level and |goto not_found|@>;
11567   } else { 
11568     incr(mp->cur_t);
11569     mp->delx=mp->delx+stack_1(u_packet(mp->uv))+stack_2(u_packet(mp->uv))
11570       +stack_3(u_packet(mp->uv));
11571     mp->dely=mp->dely+stack_1(v_packet(mp->uv))+stack_2(v_packet(mp->uv))
11572       +stack_3(v_packet(mp->uv));
11573     mp->uv=mp->uv+int_packets; /* switch from |l_packet| to |r_packet| */
11574     decr(mp->cur_tt); mp->xy=mp->xy-int_packets; 
11575          /* switch from |r_packet| to |l_packet| */
11576     mp->delx=mp->delx+stack_1(x_packet(mp->xy))+stack_2(x_packet(mp->xy))
11577       +stack_3(x_packet(mp->xy));
11578     mp->dely=mp->dely+stack_1(y_packet(mp->xy))+stack_2(y_packet(mp->xy))
11579       +stack_3(y_packet(mp->xy));
11580   }
11581 } else { 
11582   incr(mp->cur_tt); mp->tol=mp->tol+mp->three_l;
11583   mp->delx=mp->delx-stack_1(x_packet(mp->xy))-stack_2(x_packet(mp->xy))
11584     -stack_3(x_packet(mp->xy));
11585   mp->dely=mp->dely-stack_1(y_packet(mp->xy))-stack_2(y_packet(mp->xy))
11586     -stack_3(y_packet(mp->xy));
11587   mp->xy=mp->xy+int_packets; /* switch from |l_packet| to |r_packet| */
11588 }
11589
11590 @ @<Descend to the previous level...@>=
11591
11592   mp->cur_t=halfp(mp->cur_t); mp->cur_tt=halfp(mp->cur_tt);
11593   if ( mp->cur_t==0 ) return;
11594   mp->bisect_ptr=mp->bisect_ptr-int_increment; 
11595   mp->three_l=mp->three_l-mp->tol_step;
11596   mp->delx=stack_dx; mp->dely=stack_dy; mp->tol=stack_tol; 
11597   mp->uv=stack_uv; mp->xy=stack_xy;
11598   goto NOT_FOUND;
11599 }
11600
11601 @ The |path_intersection| procedure is much simpler.
11602 It invokes |cubic_intersection| in lexicographic order until finding a
11603 pair of cubics that intersect. The final intersection times are placed in
11604 |cur_t| and~|cur_tt|.
11605
11606 @c void mp_path_intersection (MP mp,pointer h, pointer hh) {
11607   pointer p,pp; /* link registers that traverse the given paths */
11608   integer n,nn; /* integer parts of intersection times, minus |unity| */
11609   @<Change one-point paths into dead cycles@>;
11610   mp->tol_step=0;
11611   do {  
11612     n=-unity; p=h;
11613     do {  
11614       if ( right_type(p)!=endpoint ) { 
11615         nn=-unity; pp=hh;
11616         do {  
11617           if ( right_type(pp)!=endpoint )  { 
11618             mp_cubic_intersection(mp, p,pp);
11619             if ( mp->cur_t>0 ) { 
11620               mp->cur_t=mp->cur_t+n; mp->cur_tt=mp->cur_tt+nn; 
11621               return;
11622             }
11623           }
11624           nn=nn+unity; pp=link(pp);
11625         } while (pp!=hh);
11626       }
11627       n=n+unity; p=link(p);
11628     } while (p!=h);
11629     mp->tol_step=mp->tol_step+3;
11630   } while (mp->tol_step<=3);
11631   mp->cur_t=-unity; mp->cur_tt=-unity;
11632 }
11633
11634 @ @<Change one-point paths...@>=
11635 if ( right_type(h)==endpoint ) {
11636   right_x(h)=x_coord(h); left_x(h)=x_coord(h);
11637   right_y(h)=y_coord(h); left_y(h)=y_coord(h); right_type(h)=explicit;
11638 }
11639 if ( right_type(hh)==endpoint ) {
11640   right_x(hh)=x_coord(hh); left_x(hh)=x_coord(hh);
11641   right_y(hh)=y_coord(hh); left_y(hh)=y_coord(hh); right_type(hh)=explicit;
11642 }
11643
11644 @* \[24] Dynamic linear equations.
11645 \MP\ users define variables implicitly by stating equations that should be
11646 satisfied; the computer is supposed to be smart enough to solve those equations.
11647 And indeed, the computer tries valiantly to do so, by distinguishing five
11648 different types of numeric values:
11649
11650 \smallskip\hang
11651 |type(p)=mp_known| is the nice case, when |value(p)| is the |scaled| value
11652 of the variable whose address is~|p|.
11653
11654 \smallskip\hang
11655 |type(p)=mp_dependent| means that |value(p)| is not present, but |dep_list(p)|
11656 points to a {\sl dependency list\/} that expresses the value of variable~|p|
11657 as a |scaled| number plus a sum of independent variables with |fraction|
11658 coefficients.
11659
11660 \smallskip\hang
11661 |type(p)=mp_independent| means that |value(p)=64s+m|, where |s>0| is a ``serial
11662 number'' reflecting the time this variable was first used in an equation;
11663 also |0<=m<64|, and each dependent variable
11664 that refers to this one is actually referring to the future value of
11665 this variable times~$2^m$. (Usually |m=0|, but higher degrees of
11666 scaling are sometimes needed to keep the coefficients in dependency lists
11667 from getting too large. The value of~|m| will always be even.)
11668
11669 \smallskip\hang
11670 |type(p)=mp_numeric_type| means that variable |p| hasn't appeared in an
11671 equation before, but it has been explicitly declared to be numeric.
11672
11673 \smallskip\hang
11674 |type(p)=undefined| means that variable |p| hasn't appeared before.
11675
11676 \smallskip\noindent
11677 We have actually discussed these five types in the reverse order of their
11678 history during a computation: Once |known|, a variable never again
11679 becomes |dependent|; once |dependent|, it almost never again becomes
11680 |mp_independent|; once |mp_independent|, it never again becomes |mp_numeric_type|;
11681 and once |mp_numeric_type|, it never again becomes |undefined| (except
11682 of course when the user specifically decides to scrap the old value
11683 and start again). A backward step may, however, take place: Sometimes
11684 a |dependent| variable becomes |mp_independent| again, when one of the
11685 independent variables it depends on is reverting to |undefined|.
11686
11687
11688 The next patch detects overflow of independent-variable serial
11689 numbers. Diagnosed and patched by Thorsten Dahlheimer.
11690
11691 @d s_scale 64 /* the serial numbers are multiplied by this factor */
11692 @d max_indep_vars 0177777777 /* $2^{25}-1$ */
11693 @d max_serial_no 017777777700 /* |max_indep_vars*s_scale| */
11694 @d new_indep(A)  /* create a new independent variable */
11695   { if ( mp->serial_no==max_serial_no )
11696     mp_fatal_error(mp, "variable instance identifiers exhausted");
11697   type((A))=mp_independent; mp->serial_no=mp->serial_no+s_scale;
11698   value((A))=mp->serial_no;
11699   }
11700
11701 @<Glob...@>=
11702 integer serial_no; /* the most recent serial number, times |s_scale| */
11703
11704 @ @<Make variable |q+s| newly independent@>=new_indep(q+s)
11705
11706 @ But how are dependency lists represented? It's simple: The linear combination
11707 $\alpha_1v_1+\cdots+\alpha_kv_k+\beta$ appears in |k+1| value nodes. If
11708 |q=dep_list(p)| points to this list, and if |k>0|, then |value(q)=
11709 @t$\alpha_1$@>| (which is a |fraction|); |info(q)| points to the location
11710 of $\alpha_1$; and |link(p)| points to the dependency list
11711 $\alpha_2v_2+\cdots+\alpha_kv_k+\beta$. On the other hand if |k=0|,
11712 then |value(q)=@t$\beta$@>| (which is |scaled|) and |info(q)=null|.
11713 The independent variables $v_1$, \dots,~$v_k$ have been sorted so that
11714 they appear in decreasing order of their |value| fields (i.e., of
11715 their serial numbers). \ (It is convenient to use decreasing order,
11716 since |value(null)=0|. If the independent variables were not sorted by
11717 serial number but by some other criterion, such as their location in |mem|,
11718 the equation-solving mechanism would be too system-dependent, because
11719 the ordering can affect the computed results.)
11720
11721 The |link| field in the node that contains the constant term $\beta$ is
11722 called the {\sl final link\/} of the dependency list. \MP\ maintains
11723 a doubly-linked master list of all dependency lists, in terms of a permanently
11724 allocated node
11725 in |mem| called |dep_head|. If there are no dependencies, we have
11726 |link(dep_head)=dep_head| and |prev_dep(dep_head)=dep_head|;
11727 otherwise |link(dep_head)| points to the first dependent variable, say~|p|,
11728 and |prev_dep(p)=dep_head|. We have |type(p)=mp_dependent|, and |dep_list(p)|
11729 points to its dependency list. If the final link of that dependency list
11730 occurs in location~|q|, then |link(q)| points to the next dependent
11731 variable (say~|r|); and we have |prev_dep(r)=q|, etc.
11732
11733 @d dep_list(A) link(value_loc((A)))
11734   /* half of the |value| field in a |dependent| variable */
11735 @d prev_dep(A) info(value_loc((A)))
11736   /* the other half; makes a doubly linked list */
11737 @d dep_node_size 2 /* the number of words per dependency node */
11738
11739 @<Initialize table entries...@>= mp->serial_no=0;
11740 link(dep_head)=dep_head; prev_dep(dep_head)=dep_head;
11741 info(dep_head)=null; dep_list(dep_head)=null;
11742
11743 @ Actually the description above contains a little white lie. There's
11744 another kind of variable called |mp_proto_dependent|, which is
11745 just like a |dependent| one except that the $\alpha$ coefficients
11746 in its dependency list are |scaled| instead of being fractions.
11747 Proto-dependency lists are mixed with dependency lists in the
11748 nodes reachable from |dep_head|.
11749
11750 @ Here is a procedure that prints a dependency list in symbolic form.
11751 The second parameter should be either |dependent| or |mp_proto_dependent|,
11752 to indicate the scaling of the coefficients.
11753
11754 @<Declare subroutines for printing expressions@>=
11755 void mp_print_dependency (MP mp,pointer p, small_number t) {
11756   integer v; /* a coefficient */
11757   pointer pp,q; /* for list manipulation */
11758   pp=p;
11759   while (1) { 
11760     v=abs(value(p)); q=info(p);
11761     if ( q==null ) { /* the constant term */
11762       if ( (v!=0)||(p==pp) ) {
11763          if ( value(p)>0 ) if ( p!=pp ) mp_print_char(mp, '+');
11764          mp_print_scaled(mp, value(p));
11765       }
11766       return;
11767     }
11768     @<Print the coefficient, unless it's $\pm1.0$@>;
11769     if ( type(q)!=mp_independent ) mp_confusion(mp, "dep");
11770 @:this can't happen dep}{\quad dep@>
11771     mp_print_variable_name(mp, q); v=value(q) % s_scale;
11772     while ( v>0 ) { mp_print(mp, "*4"); v=v-2; }
11773     p=link(p);
11774   }
11775 }
11776
11777 @ @<Print the coefficient, unless it's $\pm1.0$@>=
11778 if ( value(p)<0 ) mp_print_char(mp, '-');
11779 else if ( p!=pp ) mp_print_char(mp, '+');
11780 if ( t==mp_dependent ) v=mp_round_fraction(mp, v);
11781 if ( v!=unity ) mp_print_scaled(mp, v)
11782
11783 @ The maximum absolute value of a coefficient in a given dependency list
11784 is returned by the following simple function.
11785
11786 @c fraction mp_max_coef (MP mp,pointer p) {
11787   fraction x; /* the maximum so far */
11788   x=0;
11789   while ( info(p)!=null ) {
11790     if ( abs(value(p))>x ) x=abs(value(p));
11791     p=link(p);
11792   }
11793   return x;
11794 }
11795
11796 @ One of the main operations needed on dependency lists is to add a multiple
11797 of one list to the other; we call this |p_plus_fq|, where |p| and~|q| point
11798 to dependency lists and |f| is a fraction.
11799
11800 If the coefficient of any independent variable becomes |coef_bound| or
11801 more, in absolute value, this procedure changes the type of that variable
11802 to `|independent_needing_fix|', and sets the global variable |fix_needed|
11803 to~|true|. The value of $|coef_bound|=\mu$ is chosen so that
11804 $\mu^2+\mu<8$; this means that the numbers we deal with won't
11805 get too large. (Instead of the ``optimum'' $\mu=(\sqrt{33}-1)/2\approx
11806 2.3723$, the safer value 7/3 is taken as the threshold.)
11807
11808 The changes mentioned in the preceding paragraph are actually done only if
11809 the global variable |watch_coefs| is |true|. But it usually is; in fact,
11810 it is |false| only when \MP\ is making a dependency list that will soon
11811 be equated to zero.
11812
11813 Several procedures that act on dependency lists, including |p_plus_fq|,
11814 set the global variable |dep_final| to the final (constant term) node of
11815 the dependency list that they produce.
11816
11817 @d coef_bound 04525252525 /* |fraction| approximation to 7/3 */
11818 @d independent_needing_fix 0
11819
11820 @<Glob...@>=
11821 boolean fix_needed; /* does at least one |independent| variable need scaling? */
11822 boolean watch_coefs; /* should we scale coefficients that exceed |coef_bound|? */
11823 pointer dep_final; /* location of the constant term and final link */
11824
11825 @ @<Set init...@>=
11826 mp->fix_needed=false; mp->watch_coefs=true;
11827
11828 @ The |p_plus_fq| procedure has a fourth parameter, |t|, that should be
11829 set to |mp_proto_dependent| if |p| is a proto-dependency list. In this
11830 case |f| will be |scaled|, not a |fraction|. Similarly, the fifth parameter~|tt|
11831 should be |mp_proto_dependent| if |q| is a proto-dependency list.
11832
11833 List |q| is unchanged by the operation; but list |p| is totally destroyed.
11834
11835 The final link of the dependency list or proto-dependency list returned
11836 by |p_plus_fq| is the same as the original final link of~|p|. Indeed, the
11837 constant term of the result will be located in the same |mem| location
11838 as the original constant term of~|p|.
11839
11840 Coefficients of the result are assumed to be zero if they are less than
11841 a certain threshold. This compensates for inevitable rounding errors,
11842 and tends to make more variables `|known|'. The threshold is approximately
11843 $10^{-5}$ in the case of normal dependency lists, $10^{-4}$ for
11844 proto-dependencies.
11845
11846 @d fraction_threshold 2685 /* a |fraction| coefficient less than this is zeroed */
11847 @d half_fraction_threshold 1342 /* half of |fraction_threshold| */
11848 @d scaled_threshold 8 /* a |scaled| coefficient less than this is zeroed */
11849 @d half_scaled_threshold 4 /* half of |scaled_threshold| */
11850
11851 @<Declare basic dependency-list subroutines@>=
11852 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
11853                       pointer q, small_number t, small_number tt) ;
11854
11855 @ @c
11856 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
11857                       pointer q, small_number t, small_number tt) {
11858   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
11859   pointer r,s; /* for list manipulation */
11860   integer mp_threshold; /* defines a neighborhood of zero */
11861   integer v; /* temporary register */
11862   if ( t==mp_dependent ) mp_threshold=fraction_threshold;
11863   else mp_threshold=scaled_threshold;
11864   r=temp_head; pp=info(p); qq=info(q);
11865   while (1) {
11866     if ( pp==qq ) {
11867       if ( pp==null ) {
11868        break;
11869       } else {
11870         @<Contribute a term from |p|, plus |f| times the
11871           corresponding term from |q|@>
11872       }
11873     } else if ( value(pp)<value(qq) ) {
11874       @<Contribute a term from |q|, multiplied by~|f|@>
11875     } else { 
11876      link(r)=p; r=p; p=link(p); pp=info(p);
11877     }
11878   }
11879   if ( t==mp_dependent )
11880     value(p)=mp_slow_add(mp, value(p),mp_take_fraction(mp, value(q),f));
11881   else  
11882     value(p)=mp_slow_add(mp, value(p),mp_take_scaled(mp, value(q),f));
11883   link(r)=p; mp->dep_final=p; 
11884   return link(temp_head);
11885 }
11886
11887 @ @<Contribute a term from |p|, plus |f|...@>=
11888
11889   if ( tt==mp_dependent ) v=value(p)+mp_take_fraction(mp, f,value(q));
11890   else v=value(p)+mp_take_scaled(mp, f,value(q));
11891   value(p)=v; s=p; p=link(p);
11892   if ( abs(v)<mp_threshold ) {
11893     mp_free_node(mp, s,dep_node_size);
11894   } else {
11895     if ( (abs(v)>=coef_bound)  && mp->watch_coefs ) { 
11896       type(qq)=independent_needing_fix; mp->fix_needed=true;
11897     }
11898     link(r)=s; r=s;
11899   };
11900   pp=info(p); q=link(q); qq=info(q);
11901 }
11902
11903 @ @<Contribute a term from |q|, multiplied by~|f|@>=
11904
11905   if ( tt==mp_dependent ) v=mp_take_fraction(mp, f,value(q));
11906   else v=mp_take_scaled(mp, f,value(q));
11907   if ( abs(v)>halfp(mp_threshold) ) { 
11908     s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=v;
11909     if ( (abs(v)>=coef_bound) && mp->watch_coefs ) { 
11910       type(qq)=independent_needing_fix; mp->fix_needed=true;
11911     }
11912     link(r)=s; r=s;
11913   }
11914   q=link(q); qq=info(q);
11915 }
11916
11917 @ It is convenient to have another subroutine for the special case
11918 of |p_plus_fq| when |f=1.0|. In this routine lists |p| and |q| are
11919 both of the same type~|t| (either |dependent| or |mp_proto_dependent|).
11920
11921 @c pointer mp_p_plus_q (MP mp,pointer p, pointer q, small_number t) {
11922   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
11923   pointer r,s; /* for list manipulation */
11924   integer mp_threshold; /* defines a neighborhood of zero */
11925   integer v; /* temporary register */
11926   if ( t==mp_dependent ) mp_threshold=fraction_threshold;
11927   else mp_threshold=scaled_threshold;
11928   r=temp_head; pp=info(p); qq=info(q);
11929   while (1) {
11930     if ( pp==qq ) {
11931       if ( pp==null ) {
11932         break;
11933       } else {
11934         @<Contribute a term from |p|, plus the
11935           corresponding term from |q|@>
11936       }
11937     } else if ( value(pp)<value(qq) ) {
11938       s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=value(q);
11939       q=link(q); qq=info(q); link(r)=s; r=s;
11940     } else { 
11941       link(r)=p; r=p; p=link(p); pp=info(p);
11942     }
11943   }
11944   value(p)=mp_slow_add(mp, value(p),value(q));
11945   link(r)=p; mp->dep_final=p; 
11946   return link(temp_head);
11947 }
11948
11949 @ @<Contribute a term from |p|, plus the...@>=
11950
11951   v=value(p)+value(q);
11952   value(p)=v; s=p; p=link(p); pp=info(p);
11953   if ( abs(v)<mp_threshold ) {
11954     mp_free_node(mp, s,dep_node_size);
11955   } else { 
11956     if ( (abs(v)>=coef_bound ) && mp->watch_coefs ) {
11957       type(qq)=independent_needing_fix; mp->fix_needed=true;
11958     }
11959     link(r)=s; r=s;
11960   }
11961   q=link(q); qq=info(q);
11962 }
11963
11964 @ A somewhat simpler routine will multiply a dependency list
11965 by a given constant~|v|. The constant is either a |fraction| less than
11966 |fraction_one|, or it is |scaled|. In the latter case we might be forced to
11967 convert a dependency list to a proto-dependency list.
11968 Parameters |t0| and |t1| are the list types before and after;
11969 they should agree unless |t0=mp_dependent| and |t1=mp_proto_dependent|
11970 and |v_is_scaled=true|.
11971
11972 @c pointer mp_p_times_v (MP mp,pointer p, integer v, small_number t0,
11973                          small_number t1, boolean v_is_scaled) {
11974   pointer r,s; /* for list manipulation */
11975   integer w; /* tentative coefficient */
11976   integer mp_threshold;
11977   boolean scaling_down;
11978   if ( t0!=t1 ) scaling_down=true; else scaling_down=! v_is_scaled;
11979   if ( t1==mp_dependent ) mp_threshold=half_fraction_threshold;
11980   else mp_threshold=half_scaled_threshold;
11981   r=temp_head;
11982   while ( info(p)!=null ) {    
11983     if ( scaling_down ) w=mp_take_fraction(mp, v,value(p));
11984     else w=mp_take_scaled(mp, v,value(p));
11985     if ( abs(w)<=mp_threshold ) { 
11986       s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
11987     } else {
11988       if ( abs(w)>=coef_bound ) { 
11989         mp->fix_needed=true; type(info(p))=independent_needing_fix;
11990       }
11991       link(r)=p; r=p; value(p)=w; p=link(p);
11992     }
11993   }
11994   link(r)=p;
11995   if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
11996   else value(p)=mp_take_fraction(mp, value(p),v);
11997   return link(temp_head);
11998 };
11999
12000 @ Similarly, we sometimes need to divide a dependency list
12001 by a given |scaled| constant.
12002
12003 @<Declare basic dependency-list subroutines@>=
12004 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number 
12005   t0, small_number t1) ;
12006
12007 @ @c
12008 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number 
12009   t0, small_number t1) {
12010   pointer r,s; /* for list manipulation */
12011   integer w; /* tentative coefficient */
12012   integer mp_threshold;
12013   boolean scaling_down;
12014   if ( t0!=t1 ) scaling_down=true; else scaling_down=false;
12015   if ( t1==mp_dependent ) mp_threshold=half_fraction_threshold;
12016   else mp_threshold=half_scaled_threshold;
12017   r=temp_head;
12018   while ( info( p)!=null ) {
12019     if ( scaling_down ) {
12020       if ( abs(v)<02000000 ) w=mp_make_scaled(mp, value(p),v*010000);
12021       else w=mp_make_scaled(mp, mp_round_fraction(mp, value(p)),v);
12022     } else {
12023       w=mp_make_scaled(mp, value(p),v);
12024     }
12025     if ( abs(w)<=mp_threshold ) {
12026       s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
12027     } else { 
12028       if ( abs(w)>=coef_bound ) {
12029          mp->fix_needed=true; type(info(p))=independent_needing_fix;
12030       }
12031       link(r)=p; r=p; value(p)=w; p=link(p);
12032     }
12033   }
12034   link(r)=p; value(p)=mp_make_scaled(mp, value(p),v);
12035   return link(temp_head);
12036 };
12037
12038 @ Here's another utility routine for dependency lists. When an independent
12039 variable becomes dependent, we want to remove it from all existing
12040 dependencies. The |p_with_x_becoming_q| function computes the
12041 dependency list of~|p| after variable~|x| has been replaced by~|q|.
12042
12043 This procedure has basically the same calling conventions as |p_plus_fq|:
12044 List~|q| is unchanged; list~|p| is destroyed; the constant node and the
12045 final link are inherited from~|p|; and the fourth parameter tells whether
12046 or not |p| is |mp_proto_dependent|. However, the global variable |dep_final|
12047 is not altered if |x| does not occur in list~|p|.
12048
12049 @c pointer mp_p_with_x_becoming_q (MP mp,pointer p,
12050            pointer x, pointer q, small_number t) {
12051   pointer r,s; /* for list manipulation */
12052   integer v; /* coefficient of |x| */
12053   integer sx; /* serial number of |x| */
12054   s=p; r=temp_head; sx=value(x);
12055   while ( value(info(s))>sx ) { r=s; s=link(s); };
12056   if ( info(s)!=x ) { 
12057     return p;
12058   } else { 
12059     link(temp_head)=p; link(r)=link(s); v=value(s);
12060     mp_free_node(mp, s,dep_node_size);
12061     return mp_p_plus_fq(mp, link(temp_head),v,q,t,mp_dependent);
12062   }
12063 }
12064
12065 @ Here's a simple procedure that reports an error when a variable
12066 has just received a known value that's out of the required range.
12067
12068 @<Declare basic dependency-list subroutines@>=
12069 void mp_val_too_big (MP mp,scaled x) ;
12070
12071 @ @c void mp_val_too_big (MP mp,scaled x) { 
12072   if ( mp->internal[warning_check]>0 ) { 
12073     print_err("Value is too large ("); mp_print_scaled(mp, x); mp_print_char(mp, ')');
12074 @.Value is too large@>
12075     help4("The equation I just processed has given some variable")
12076       ("a value of 4096 or more. Continue and I'll try to cope")
12077       ("with that big value; but it might be dangerous.")
12078       ("(Set warningcheck:=0 to suppress this message.)");
12079     mp_error(mp);
12080   }
12081 }
12082
12083 @ When a dependent variable becomes known, the following routine
12084 removes its dependency list. Here |p| points to the variable, and
12085 |q| points to the dependency list (which is one node long).
12086
12087 @<Declare basic dependency-list subroutines@>=
12088 void mp_make_known (MP mp,pointer p, pointer q) ;
12089
12090 @ @c void mp_make_known (MP mp,pointer p, pointer q) {
12091   int t; /* the previous type */
12092   prev_dep(link(q))=prev_dep(p);
12093   link(prev_dep(p))=link(q); t=type(p);
12094   type(p)=mp_known; value(p)=value(q); mp_free_node(mp, q,dep_node_size);
12095   if ( abs(value(p))>=fraction_one ) mp_val_too_big(mp, value(p));
12096   if (( mp->internal[tracing_equations]>0) && mp_interesting(mp, p) ) {
12097     mp_begin_diagnostic(mp); mp_print_nl(mp, "#### ");
12098 @:]]]\#\#\#\#_}{\.{\#\#\#\#}@>
12099     mp_print_variable_name(mp, p); 
12100     mp_print_char(mp, '='); mp_print_scaled(mp, value(p));
12101     mp_end_diagnostic(mp, false);
12102   }
12103   if (( mp->cur_exp==p ) && mp->cur_type==t ) {
12104     mp->cur_type=mp_known; mp->cur_exp=value(p);
12105     mp_free_node(mp, p,value_node_size);
12106   }
12107 }
12108
12109 @ The |fix_dependencies| routine is called into action when |fix_needed|
12110 has been triggered. The program keeps a list~|s| of independent variables
12111 whose coefficients must be divided by~4.
12112
12113 In unusual cases, this fixup process might reduce one or more coefficients
12114 to zero, so that a variable will become known more or less by default.
12115
12116 @<Declare basic dependency-list subroutines@>=
12117 void mp_fix_dependencies (MP mp);
12118
12119 @ @c void mp_fix_dependencies (MP mp) {
12120   pointer p,q,r,s,t; /* list manipulation registers */
12121   pointer x; /* an independent variable */
12122   r=link(dep_head); s=null;
12123   while ( r!=dep_head ){ 
12124     t=r;
12125     @<Run through the dependency list for variable |t|, fixing
12126       all nodes, and ending with final link~|q|@>;
12127     r=link(q);
12128     if ( q==dep_list(t) ) mp_make_known(mp, t,q);
12129   }
12130   while ( s!=null ) { 
12131     p=link(s); x=info(s); free_avail(s); s=p;
12132     type(x)=mp_independent; value(x)=value(x)+2;
12133   }
12134   mp->fix_needed=false;
12135 }
12136
12137 @ @d independent_being_fixed 1 /* this variable already appears in |s| */
12138
12139 @<Run through the dependency list for variable |t|...@>=
12140 r=value_loc(t); /* |link(r)=dep_list(t)| */
12141 while (1) { 
12142   q=link(r); x=info(q);
12143   if ( x==null ) break;
12144   if ( type(x)<=independent_being_fixed ) {
12145     if ( type(x)<independent_being_fixed ) {
12146       p=mp_get_avail(mp); link(p)=s; s=p;
12147       info(s)=x; type(x)=independent_being_fixed;
12148     }
12149     value(q)=value(q) / 4;
12150     if ( value(q)==0 ) {
12151       link(r)=link(q); mp_free_node(mp, q,dep_node_size); q=r;
12152     }
12153   }
12154   r=q;
12155 }
12156
12157
12158 @ The |new_dep| routine installs a dependency list~|p| into the value node~|q|,
12159 linking it into the list of all known dependencies. We assume that
12160 |dep_final| points to the final node of list~|p|.
12161
12162 @c void mp_new_dep (MP mp,pointer q, pointer p) {
12163   pointer r; /* what used to be the first dependency */
12164   dep_list(q)=p; prev_dep(q)=dep_head;
12165   r=link(dep_head); link(mp->dep_final)=r; prev_dep(r)=mp->dep_final;
12166   link(dep_head)=q;
12167 }
12168
12169 @ Here is one of the ways a dependency list gets started.
12170 The |const_dependency| routine produces a list that has nothing but
12171 a constant term.
12172
12173 @c pointer mp_const_dependency (MP mp, scaled v) {
12174   mp->dep_final=mp_get_node(mp, dep_node_size);
12175   value(mp->dep_final)=v; info(mp->dep_final)=null;
12176   return mp->dep_final;
12177 }
12178
12179 @ And here's a more interesting way to start a dependency list from scratch:
12180 The parameter to |single_dependency| is the location of an
12181 independent variable~|x|, and the result is the simple dependency list
12182 `|x+0|'.
12183
12184 In the unlikely event that the given independent variable has been doubled so
12185 often that we can't refer to it with a nonzero coefficient,
12186 |single_dependency| returns the simple list `0'.  This case can be
12187 recognized by testing that the returned list pointer is equal to
12188 |dep_final|.
12189
12190 @c pointer mp_single_dependency (MP mp,pointer p) {
12191   pointer q; /* the new dependency list */
12192   integer m; /* the number of doublings */
12193   m=value(p) % s_scale;
12194   if ( m>28 ) {
12195     return mp_const_dependency(mp, 0);
12196   } else { 
12197     q=mp_get_node(mp, dep_node_size);
12198     value(q)=two_to_the(28-m); info(q)=p;
12199     link(q)=mp_const_dependency(mp, 0);
12200     return q;
12201   }
12202 }
12203
12204 @ We sometimes need to make an exact copy of a dependency list.
12205
12206 @c pointer mp_copy_dep_list (MP mp,pointer p) {
12207   pointer q; /* the new dependency list */
12208   q=mp_get_node(mp, dep_node_size); mp->dep_final=q;
12209   while (1) { 
12210     info(mp->dep_final)=info(p); value(mp->dep_final)=value(p);
12211     if ( info(mp->dep_final)==null ) break;
12212     link(mp->dep_final)=mp_get_node(mp, dep_node_size);
12213     mp->dep_final=link(mp->dep_final); p=link(p);
12214   }
12215   return q;
12216 }
12217
12218 @ But how do variables normally become known? Ah, now we get to the heart of the
12219 equation-solving mechanism. The |linear_eq| procedure is given a |dependent|
12220 or |mp_proto_dependent| list,~|p|, in which at least one independent variable
12221 appears. It equates this list to zero, by choosing an independent variable
12222 with the largest coefficient and making it dependent on the others. The
12223 newly dependent variable is eliminated from all current dependencies,
12224 thereby possibly making other dependent variables known.
12225
12226 The given list |p| is, of course, totally destroyed by all this processing.
12227
12228 @c void mp_linear_eq (MP mp, pointer p, small_number t) {
12229   pointer q,r,s; /* for link manipulation */
12230   pointer x; /* the variable that loses its independence */
12231   integer n; /* the number of times |x| had been halved */
12232   integer v; /* the coefficient of |x| in list |p| */
12233   pointer prev_r; /* lags one step behind |r| */
12234   pointer final_node; /* the constant term of the new dependency list */
12235   integer w; /* a tentative coefficient */
12236    @<Find a node |q| in list |p| whose coefficient |v| is largest@>;
12237   x=info(q); n=value(x) % s_scale;
12238   @<Divide list |p| by |-v|, removing node |q|@>;
12239   if ( mp->internal[tracing_equations]>0 ) {
12240     @<Display the new dependency@>;
12241   }
12242   @<Simplify all existing dependencies by substituting for |x|@>;
12243   @<Change variable |x| from |independent| to |dependent| or |known|@>;
12244   if ( mp->fix_needed ) mp_fix_dependencies(mp);
12245 }
12246
12247 @ @<Find a node |q| in list |p| whose coefficient |v| is largest@>=
12248 q=p; r=link(p); v=value(q);
12249 while ( info(r)!=null ) { 
12250   if ( abs(value(r))>abs(v) ) { q=r; v=value(r); };
12251   r=link(r);
12252 }
12253
12254 @ Here we want to change the coefficients from |scaled| to |fraction|,
12255 except in the constant term. In the common case of a trivial equation
12256 like `\.{x=3.14}', we will have |v=-fraction_one|, |q=p|, and |t=mp_dependent|.
12257
12258 @<Divide list |p| by |-v|, removing node |q|@>=
12259 s=temp_head; link(s)=p; r=p;
12260 do { 
12261   if ( r==q ) {
12262     link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12263   } else  { 
12264     w=mp_make_fraction(mp, value(r),v);
12265     if ( abs(w)<=half_fraction_threshold ) {
12266       link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12267     } else { 
12268       value(r)=-w; s=r;
12269     }
12270   }
12271   r=link(s);
12272 } while (info(r)!=null);
12273 if ( t==mp_proto_dependent ) {
12274   value(r)=-mp_make_scaled(mp, value(r),v);
12275 } else if ( v!=-fraction_one ) {
12276   value(r)=-mp_make_fraction(mp, value(r),v);
12277 }
12278 final_node=r; p=link(temp_head)
12279
12280 @ @<Display the new dependency@>=
12281 if ( mp_interesting(mp, x) ) {
12282   mp_begin_diagnostic(mp); mp_print_nl(mp, "## "); 
12283   mp_print_variable_name(mp, x);
12284 @:]]]\#\#_}{\.{\#\#}@>
12285   w=n;
12286   while ( w>0 ) { mp_print(mp, "*4"); w=w-2;  };
12287   mp_print_char(mp, '='); mp_print_dependency(mp, p,mp_dependent); 
12288   mp_end_diagnostic(mp, false);
12289 }
12290
12291 @ @<Simplify all existing dependencies by substituting for |x|@>=
12292 prev_r=dep_head; r=link(dep_head);
12293 while ( r!=dep_head ) {
12294   s=dep_list(r); q=mp_p_with_x_becoming_q(mp, s,x,p,type(r));
12295   if ( info(q)==null ) {
12296     mp_make_known(mp, r,q);
12297   } else { 
12298     dep_list(r)=q;
12299     do {  q=link(q); } while (info(q)!=null);
12300     prev_r=q;
12301   }
12302   r=link(prev_r);
12303 }
12304
12305 @ @<Change variable |x| from |independent| to |dependent| or |known|@>=
12306 if ( n>0 ) @<Divide list |p| by $2^n$@>;
12307 if ( info(p)==null ) {
12308   type(x)=mp_known;
12309   value(x)=value(p);
12310   if ( abs(value(x))>=fraction_one ) mp_val_too_big(mp, value(x));
12311   mp_free_node(mp, p,dep_node_size);
12312   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) {
12313     mp->cur_exp=value(x); mp->cur_type=mp_known;
12314     mp_free_node(mp, x,value_node_size);
12315   }
12316 } else { 
12317   type(x)=mp_dependent; mp->dep_final=final_node; mp_new_dep(mp, x,p);
12318   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) mp->cur_type=mp_dependent;
12319 }
12320
12321 @ @<Divide list |p| by $2^n$@>=
12322
12323   s=temp_head; link(temp_head)=p; r=p;
12324   do {  
12325     if ( n>30 ) w=0;
12326     else w=value(r) / two_to_the(n);
12327     if ( (abs(w)<=half_fraction_threshold)&&(info(r)!=null) ) {
12328       link(s)=link(r);
12329       mp_free_node(mp, r,dep_node_size);
12330     } else { 
12331       value(r)=w; s=r;
12332     }
12333     r=link(s);
12334   } while (info(s)!=null);
12335   p=link(temp_head);
12336 }
12337
12338 @ The |check_mem| procedure, which is used only when \MP\ is being
12339 debugged, makes sure that the current dependency lists are well formed.
12340
12341 @<Check the list of linear dependencies@>=
12342 q=dep_head; p=link(q);
12343 while ( p!=dep_head ) {
12344   if ( prev_dep(p)!=q ) {
12345     mp_print_nl(mp, "Bad PREVDEP at "); mp_print_int(mp, p);
12346 @.Bad PREVDEP...@>
12347   }
12348   p=dep_list(p);
12349   while (1) {
12350     r=info(p); q=p; p=link(q);
12351     if ( r==null ) break;
12352     if ( value(info(p))>=value(r) ) {
12353       mp_print_nl(mp, "Out of order at "); mp_print_int(mp, p);
12354 @.Out of order...@>
12355     }
12356   }
12357 }
12358
12359 @* \[25] Dynamic nonlinear equations.
12360 Variables of numeric type are maintained by the general scheme of
12361 independent, dependent, and known values that we have just studied;
12362 and the components of pair and transform variables are handled in the
12363 same way. But \MP\ also has five other types of values: \&{boolean},
12364 \&{string}, \&{pen}, \&{path}, and \&{picture}; what about them?
12365
12366 Equations are allowed between nonlinear quantities, but only in a
12367 simple form. Two variables that haven't yet been assigned values are
12368 either equal to each other, or they're not.
12369
12370 Before a boolean variable has received a value, its type is |mp_unknown_boolean|;
12371 similarly, there are variables whose type is |mp_unknown_string|, |mp_unknown_pen|,
12372 |mp_unknown_path|, and |mp_unknown_picture|. In such cases the value is either
12373 |null| (which means that no other variables are equivalent to this one), or
12374 it points to another variable of the same undefined type. The pointers in the
12375 latter case form a cycle of nodes, which we shall call a ``ring.''
12376 Rings of undefined variables may include capsules, which arise as
12377 intermediate results within expressions or as \&{expr} parameters to macros.
12378
12379 When one member of a ring receives a value, the same value is given to
12380 all the other members. In the case of paths and pictures, this implies
12381 making separate copies of a potentially large data structure; users should
12382 restrain their enthusiasm for such generality, unless they have lots and
12383 lots of memory space.
12384
12385 @ The following procedure is called when a capsule node is being
12386 added to a ring (e.g., when an unknown variable is mentioned in an expression).
12387
12388 @c pointer mp_new_ring_entry (MP mp,pointer p) {
12389   pointer q; /* the new capsule node */
12390   q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
12391   type(q)=type(p);
12392   if ( value(p)==null ) value(q)=p; else value(q)=value(p);
12393   value(p)=q;
12394   return q;
12395 }
12396
12397 @ Conversely, we might delete a capsule or a variable before it becomes known.
12398 The following procedure simply detaches a quantity from its ring,
12399 without recycling the storage.
12400
12401 @<Declare the recycling subroutines@>=
12402 void mp_ring_delete (MP mp,pointer p) {
12403   pointer q; 
12404   q=value(p);
12405   if ( q!=null ) if ( q!=p ){ 
12406     while ( value(q)!=p ) q=value(q);
12407     value(q)=value(p);
12408   }
12409 }
12410
12411 @ Eventually there might be an equation that assigns values to all of the
12412 variables in a ring. The |nonlinear_eq| subroutine does the necessary
12413 propagation of values.
12414
12415 If the parameter |flush_p| is |true|, node |p| itself needn't receive a
12416 value, it will soon be recycled.
12417
12418 @c void mp_nonlinear_eq (MP mp,integer v, pointer p, boolean flush_p) {
12419   small_number t; /* the type of ring |p| */
12420   pointer q,r; /* link manipulation registers */
12421   t=type(p)-unknown_tag; q=value(p);
12422   if ( flush_p ) type(p)=mp_vacuous; else p=q;
12423   do {  
12424     r=value(q); type(q)=t;
12425     switch (t) {
12426     case mp_boolean_type: value(q)=v; break;
12427     case mp_string_type: value(q)=v; add_str_ref(v); break;
12428     case mp_pen_type: value(q)=copy_pen(v); break;
12429     case mp_path_type: value(q)=mp_copy_path(mp, v); break;
12430     case mp_picture_type: value(q)=v; add_edge_ref(v); break;
12431     } /* there ain't no more cases */
12432     q=r;
12433   } while (q!=p);
12434 }
12435
12436 @ If two members of rings are equated, and if they have the same type,
12437 the |ring_merge| procedure is called on to make them equivalent.
12438
12439 @c void mp_ring_merge (MP mp,pointer p, pointer q) {
12440   pointer r; /* traverses one list */
12441   r=value(p);
12442   while ( r!=p ) {
12443     if ( r==q ) {
12444       @<Exclaim about a redundant equation@>;
12445       return;
12446     };
12447     r=value(r);
12448   }
12449   r=value(p); value(p)=value(q); value(q)=r;
12450 }
12451
12452 @ @<Exclaim about a redundant equation@>=
12453
12454   print_err("Redundant equation");
12455 @.Redundant equation@>
12456   help2("I already knew that this equation was true.")
12457    ("But perhaps no harm has been done; let's continue.");
12458   mp_put_get_error(mp);
12459 }
12460
12461 @* \[26] Introduction to the syntactic routines.
12462 Let's pause a moment now and try to look at the Big Picture.
12463 The \MP\ program consists of three main parts: syntactic routines,
12464 semantic routines, and output routines. The chief purpose of the
12465 syntactic routines is to deliver the user's input to the semantic routines,
12466 while parsing expressions and locating operators and operands. The
12467 semantic routines act as an interpreter responding to these operators,
12468 which may be regarded as commands. And the output routines are
12469 periodically called on to produce compact font descriptions that can be
12470 used for typesetting or for making interim proof drawings. We have
12471 discussed the basic data structures and many of the details of semantic
12472 operations, so we are good and ready to plunge into the part of \MP\ that
12473 actually controls the activities.
12474
12475 Our current goal is to come to grips with the |get_next| procedure,
12476 which is the keystone of \MP's input mechanism. Each call of |get_next|
12477 sets the value of three variables |cur_cmd|, |cur_mod|, and |cur_sym|,
12478 representing the next input token.
12479 $$\vbox{\halign{#\hfil\cr
12480   \hbox{|cur_cmd| denotes a command code from the long list of codes
12481    given earlier;}\cr
12482   \hbox{|cur_mod| denotes a modifier of the command code;}\cr
12483   \hbox{|cur_sym| is the hash address of the symbolic token that was
12484    just scanned,}\cr
12485   \hbox{\qquad or zero in the case of a numeric or string
12486    or capsule token.}\cr}}$$
12487 Underlying this external behavior of |get_next| is all the machinery
12488 necessary to convert from character files to tokens. At a given time we
12489 may be only partially finished with the reading of several files (for
12490 which \&{input} was specified), and partially finished with the expansion
12491 of some user-defined macros and/or some macro parameters, and partially
12492 finished reading some text that the user has inserted online,
12493 and so on. When reading a character file, the characters must be
12494 converted to tokens; comments and blank spaces must
12495 be removed, numeric and string tokens must be evaluated.
12496
12497 To handle these situations, which might all be present simultaneously,
12498 \MP\ uses various stacks that hold information about the incomplete
12499 activities, and there is a finite state control for each level of the
12500 input mechanism. These stacks record the current state of an implicitly
12501 recursive process, but the |get_next| procedure is not recursive.
12502
12503 @<Glob...@>=
12504 eight_bits cur_cmd; /* current command set by |get_next| */
12505 integer cur_mod; /* operand of current command */
12506 halfword cur_sym; /* hash address of current symbol */
12507
12508 @ The |print_cmd_mod| routine prints a symbolic interpretation of a
12509 command code and its modifier.
12510 It consists of a rather tedious sequence of print
12511 commands, and most of it is essentially an inverse to the |primitive|
12512 routine that enters a \MP\ primitive into |hash| and |eqtb|. Therefore almost
12513 all of this procedure appears elsewhere in the program, together with the
12514 corresponding |primitive| calls.
12515
12516 @<Declare the procedure called |print_cmd_mod|@>=
12517 void mp_print_cmd_mod (MP mp,integer c, integer m) { 
12518  switch (c) {
12519   @<Cases of |print_cmd_mod| for symbolic printing of primitives@>
12520   default: mp_print(mp, "[unknown command code!]"); break;
12521   }
12522 }
12523
12524 @ Here is a procedure that displays a given command in braces, in the
12525 user's transcript file.
12526
12527 @d show_cur_cmd_mod mp_show_cmd_mod(mp, mp->cur_cmd,mp->cur_mod)
12528
12529 @c 
12530 void mp_show_cmd_mod (MP mp,integer c, integer m) { 
12531   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
12532   mp_print_cmd_mod(mp, c,m); mp_print_char(mp, '}');
12533   mp_end_diagnostic(mp, false);
12534 }
12535
12536 @* \[27] Input stacks and states.
12537 The state of \MP's input mechanism appears in the input stack, whose
12538 entries are records with five fields, called |index|, |start|, |loc|,
12539 |limit|, and |name|. The top element of this stack is maintained in a
12540 global variable for which no subscripting needs to be done; the other
12541 elements of the stack appear in an array. Hence the stack is declared thus:
12542
12543 @<Types...@>=
12544 typedef struct {
12545   quarterword index_field;
12546   halfword start_field, loc_field, limit_field, name_field;
12547 } in_state_record;
12548
12549 @ @<Glob...@>=
12550 in_state_record *input_stack;
12551 integer input_ptr; /* first unused location of |input_stack| */
12552 integer max_in_stack; /* largest value of |input_ptr| when pushing */
12553 in_state_record cur_input; /* the ``top'' input state */
12554 int stack_size; /* maximum number of simultaneous input sources */
12555
12556 @ @<Allocate or initialize ...@>=
12557 mp->stack_size = 300;
12558 mp->input_stack = xmalloc((mp->stack_size+1),sizeof(in_state_record));
12559
12560 @ @<Dealloc variables@>=
12561 xfree(mp->input_stack);
12562
12563 @ We've already defined the special variable |loc==cur_input.loc_field|
12564 in our discussion of basic input-output routines. The other components of
12565 |cur_input| are defined in the same way:
12566
12567 @d index mp->cur_input.index_field /* reference for buffer information */
12568 @d start mp->cur_input.start_field /* starting position in |buffer| */
12569 @d limit mp->cur_input.limit_field /* end of current line in |buffer| */
12570 @d name mp->cur_input.name_field /* name of the current file */
12571
12572 @ Let's look more closely now at the five control variables
12573 (|index|,~|start|,~|loc|,~|limit|,~|name|),
12574 assuming that \MP\ is reading a line of characters that have been input
12575 from some file or from the user's terminal. There is an array called
12576 |buffer| that acts as a stack of all lines of characters that are
12577 currently being read from files, including all lines on subsidiary
12578 levels of the input stack that are not yet completed. \MP\ will return to
12579 the other lines when it is finished with the present input file.
12580
12581 (Incidentally, on a machine with byte-oriented addressing, it would be
12582 appropriate to combine |buffer| with the |str_pool| array,
12583 letting the buffer entries grow downward from the top of the string pool
12584 and checking that these two tables don't bump into each other.)
12585
12586 The line we are currently working on begins in position |start| of the
12587 buffer; the next character we are about to read is |buffer[loc]|; and
12588 |limit| is the location of the last character present. We always have
12589 |loc<=limit|. For convenience, |buffer[limit]| has been set to |"%"|, so
12590 that the end of a line is easily sensed.
12591
12592 The |name| variable is a string number that designates the name of
12593 the current file, if we are reading an ordinary text file.  Special codes
12594 |is_term..max_spec_src| indicate other sources of input text.
12595
12596 @d is_term 0 /* |name| value when reading from the terminal for normal input */
12597 @d is_read 1 /* |name| value when executing a \&{readstring} or \&{readfrom} */
12598 @d is_scantok 2 /* |name| value when reading text generated by \&{scantokens} */
12599 @d max_spec_src is_scantok
12600
12601 @ Additional information about the current line is available via the
12602 |index| variable, which counts how many lines of characters are present
12603 in the buffer below the current level. We have |index=0| when reading
12604 from the terminal and prompting the user for each line; then if the user types,
12605 e.g., `\.{input figs}', we will have |index=1| while reading
12606 the file \.{figs.mp}. However, it does not follow that |index| is the
12607 same as the input stack pointer, since many of the levels on the input
12608 stack may come from token lists and some |index| values may correspond
12609 to \.{MPX} files that are not currently on the stack.
12610
12611 The global variable |in_open| is equal to the highest |index| value counting
12612 \.{MPX} files but excluding token-list input levels.  Thus, the number of
12613 partially read lines in the buffer is |in_open+1| and we have |in_open>=index|
12614 when we are not reading a token list.
12615
12616 If we are not currently reading from the terminal,
12617 we are reading from the file variable |input_file[index]|. We use
12618 the notation |terminal_input| as a convenient abbreviation for |name=is_term|,
12619 and |cur_file| as an abbreviation for |input_file[index]|.
12620
12621 When \MP\ is not reading from the terminal, the global variable |line| contains
12622 the line number in the current file, for use in error messages. More precisely,
12623 |line| is a macro for |line_stack[index]| and the |line_stack| array gives
12624 the line number for each file in the |input_file| array.
12625
12626 When an \.{MPX} file is opened the file name is stored in the |mpx_name|
12627 array so that the name doesn't get lost when the file is temporarily removed
12628 from the input stack.
12629 Thus when |input_file[k]| is an \.{MPX} file, its name is |mpx_name[k]|
12630 and it contains translated \TeX\ pictures for |input_file[k-1]|.
12631 Since this is not an \.{MPX} file, we have
12632 $$ \hbox{|mpx_name[k-1]<=absent|}. $$
12633 This |name| field is set to |finished| when |input_file[k]| is completely
12634 read.
12635
12636 If more information about the input state is needed, it can be
12637 included in small arrays like those shown here. For example,
12638 the current page or segment number in the input file might be put
12639 into a variable |page|, that is really a macro for the current entry
12640 in `\ignorespaces|page_stack:array[0..max_in_open] of integer|\unskip'
12641 by analogy with |line_stack|.
12642 @^system dependencies@>
12643
12644 @d terminal_input (name==is_term) /* are we reading from the terminal? */
12645 @d cur_file mp->input_file[index] /* the current |FILE *| variable */
12646 @d line mp->line_stack[index] /* current line number in the current source file */
12647 @d in_name mp->iname_stack[index] /* a string used to construct \.{MPX} file names */
12648 @d in_area mp->iarea_stack[index] /* another string for naming \.{MPX} files */
12649 @d absent 1 /* |name_field| value for unused |mpx_in_stack| entries */
12650 @d mpx_reading (mp->mpx_name[index]>absent)
12651   /* when reading a file, is it an \.{MPX} file? */
12652 @d finished 0
12653   /* |name_field| value when the corresponding \.{MPX} file is finished */
12654
12655 @<Glob...@>=
12656 integer in_open; /* the number of lines in the buffer, less one */
12657 unsigned int open_parens; /* the number of open text files */
12658 FILE  * *input_file ;
12659 integer *line_stack ; /* the line number for each file */
12660 char *  *iname_stack; /* used for naming \.{MPX} files */
12661 char *  *iarea_stack; /* used for naming \.{MPX} files */
12662 halfword*mpx_name  ;
12663
12664 @ @<Allocate or ...@>=
12665 mp->input_file  = xmalloc((mp->max_in_open+1),sizeof(FILE *));
12666 mp->line_stack  = xmalloc((mp->max_in_open+1),sizeof(integer));
12667 mp->iname_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12668 mp->iarea_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12669 mp->mpx_name    = xmalloc((mp->max_in_open+1),sizeof(halfword));
12670 {
12671   int k;
12672   for (k=0;k<=mp->max_in_open;k++) {
12673     mp->iname_stack[k] =NULL;
12674     mp->iarea_stack[k] =NULL;
12675   }
12676 }
12677
12678 @ @<Dealloc variables@>=
12679 {
12680   int l;
12681   for (l=0;l<=mp->max_in_open;l++) {
12682     xfree(mp->iname_stack[l]);
12683     xfree(mp->iarea_stack[l]);
12684   }
12685 }
12686 xfree(mp->input_file);
12687 xfree(mp->line_stack);
12688 xfree(mp->iname_stack);
12689 xfree(mp->iarea_stack);
12690 xfree(mp->mpx_name);
12691
12692
12693 @ However, all this discussion about input state really applies only to the
12694 case that we are inputting from a file. There is another important case,
12695 namely when we are currently getting input from a token list. In this case
12696 |index>max_in_open|, and the conventions about the other state variables
12697 are different:
12698
12699 \yskip\hang|loc| is a pointer to the current node in the token list, i.e.,
12700 the node that will be read next. If |loc=null|, the token list has been
12701 fully read.
12702
12703 \yskip\hang|start| points to the first node of the token list; this node
12704 may or may not contain a reference count, depending on the type of token
12705 list involved.
12706
12707 \yskip\hang|token_type|, which takes the place of |index| in the
12708 discussion above, is a code number that explains what kind of token list
12709 is being scanned.
12710
12711 \yskip\hang|name| points to the |eqtb| address of the control sequence
12712 being expanded, if the current token list is a macro not defined by
12713 \&{vardef}. Macros defined by \&{vardef} have |name=null|; their name
12714 can be deduced by looking at their first two parameters.
12715
12716 \yskip\hang|param_start|, which takes the place of |limit|, tells where
12717 the parameters of the current macro or loop text begin in the |param_stack|.
12718
12719 \yskip\noindent The |token_type| can take several values, depending on
12720 where the current token list came from:
12721
12722 \yskip
12723 \indent|forever_text|, if the token list being scanned is the body of
12724 a \&{forever} loop;
12725
12726 \indent|loop_text|, if the token list being scanned is the body of
12727 a \&{for} or \&{forsuffixes} loop;
12728
12729 \indent|parameter|, if a \&{text} or \&{suffix} parameter is being scanned;
12730
12731 \indent|backed_up|, if the token list being scanned has been inserted as
12732 `to be read again'.
12733
12734 \indent|inserted|, if the token list being scanned has been inserted as
12735 part of error recovery;
12736
12737 \indent|macro|, if the expansion of a user-defined symbolic token is being
12738 scanned.
12739
12740 \yskip\noindent
12741 The token list begins with a reference count if and only if |token_type=
12742 macro|.
12743 @^reference counts@>
12744
12745 @d token_type index /* type of current token list */
12746 @d token_state (index>(int)mp->max_in_open) /* are we scanning a token list? */
12747 @d file_state (index<=(int)mp->max_in_open) /* are we scanning a file line? */
12748 @d param_start limit /* base of macro parameters in |param_stack| */
12749 @d forever_text (mp->max_in_open+1) /* |token_type| code for loop texts */
12750 @d loop_text (mp->max_in_open+2) /* |token_type| code for loop texts */
12751 @d parameter (mp->max_in_open+3) /* |token_type| code for parameter texts */
12752 @d backed_up (mp->max_in_open+4) /* |token_type| code for texts to be reread */
12753 @d inserted (mp->max_in_open+5) /* |token_type| code for inserted texts */
12754 @d macro (mp->max_in_open+6) /* |token_type| code for macro replacement texts */
12755
12756 @ The |param_stack| is an auxiliary array used to hold pointers to the token
12757 lists for parameters at the current level and subsidiary levels of input.
12758 This stack grows at a different rate from the others.
12759
12760 @<Glob...@>=
12761 pointer *param_stack;  /* token list pointers for parameters */
12762 integer param_ptr; /* first unused entry in |param_stack| */
12763 integer max_param_stack;  /* largest value of |param_ptr| */
12764
12765 @ @<Allocate or initialize ...@>=
12766 mp->param_stack = xmalloc((mp->param_size+1),sizeof(pointer));
12767
12768 @ @<Dealloc variables@>=
12769 xfree(mp->param_stack);
12770
12771 @ Notice that the |line| isn't valid when |token_state| is true because it
12772 depends on |index|.  If we really need to know the line number for the
12773 topmost file in the index stack we use the following function.  If a page
12774 number or other information is needed, this routine should be modified to
12775 compute it as well.
12776 @^system dependencies@>
12777
12778 @<Declare a function called |true_line|@>=
12779 integer mp_true_line (MP mp) {
12780   int k; /* an index into the input stack */
12781   if ( file_state && (name>max_spec_src) ) {
12782      return line;
12783   } else { 
12784     k=mp->input_ptr;
12785     while ((k>0) &&
12786            ((mp->input_stack[(k-1)].index_field>mp->max_in_open)||
12787             (mp->input_stack[(k-1)].name_field<=max_spec_src))) {
12788       decr(k);
12789     }
12790     return mp->line_stack[(k-1)];
12791   }
12792   return 0; 
12793 }
12794
12795 @ Thus, the ``current input state'' can be very complicated indeed; there
12796 can be many levels and each level can arise in a variety of ways. The
12797 |show_context| procedure, which is used by \MP's error-reporting routine to
12798 print out the current input state on all levels down to the most recent
12799 line of characters from an input file, illustrates most of these conventions.
12800 The global variable |file_ptr| contains the lowest level that was
12801 displayed by this procedure.
12802
12803 @<Glob...@>=
12804 integer file_ptr; /* shallowest level shown by |show_context| */
12805
12806 @ The status at each level is indicated by printing two lines, where the first
12807 line indicates what was read so far and the second line shows what remains
12808 to be read. The context is cropped, if necessary, so that the first line
12809 contains at most |half_error_line| characters, and the second contains
12810 at most |error_line|. Non-current input levels whose |token_type| is
12811 `|backed_up|' are shown only if they have not been fully read.
12812
12813 @c void mp_show_context (MP mp) { /* prints where the scanner is */
12814   int old_setting; /* saved |selector| setting */
12815   @<Local variables for formatting calculations@>
12816   mp->file_ptr=mp->input_ptr; mp->input_stack[mp->file_ptr]=mp->cur_input;
12817   /* store current state */
12818   while (1) { 
12819     mp->cur_input=mp->input_stack[mp->file_ptr]; /* enter into the context */
12820     @<Display the current context@>;
12821     if ( file_state )
12822       if ( (name>max_spec_src) || (mp->file_ptr==0) ) break;
12823     decr(mp->file_ptr);
12824   }
12825   mp->cur_input=mp->input_stack[mp->input_ptr]; /* restore original state */
12826 }
12827
12828 @ @<Display the current context@>=
12829 if ( (mp->file_ptr==mp->input_ptr) || file_state ||
12830    (token_type!=backed_up) || (loc!=null) ) {
12831     /* we omit backed-up token lists that have already been read */
12832   mp->tally=0; /* get ready to count characters */
12833   old_setting=mp->selector;
12834   if ( file_state ) {
12835     @<Print location of current line@>;
12836     @<Pseudoprint the line@>;
12837   } else { 
12838     @<Print type of token list@>;
12839     @<Pseudoprint the token list@>;
12840   }
12841   mp->selector=old_setting; /* stop pseudoprinting */
12842   @<Print two lines using the tricky pseudoprinted information@>;
12843 }
12844
12845 @ This routine should be changed, if necessary, to give the best possible
12846 indication of where the current line resides in the input file.
12847 For example, on some systems it is best to print both a page and line number.
12848 @^system dependencies@>
12849
12850 @<Print location of current line@>=
12851 if ( name>max_spec_src ) {
12852   mp_print_nl(mp, "l."); mp_print_int(mp, mp_true_line(mp));
12853 } else if ( terminal_input ) {
12854   if ( mp->file_ptr==0 ) mp_print_nl(mp, "<*>");
12855   else mp_print_nl(mp, "<insert>");
12856 } else if ( name==is_scantok ) {
12857   mp_print_nl(mp, "<scantokens>");
12858 } else {
12859   mp_print_nl(mp, "<read>");
12860 }
12861 mp_print_char(mp, ' ')
12862
12863 @ Can't use case statement here because the |token_type| is not
12864 a constant expression.
12865
12866 @<Print type of token list@>=
12867 {
12868   if(token_type==forever_text) {
12869     mp_print_nl(mp, "<forever> ");
12870   } else if (token_type==loop_text) {
12871     @<Print the current loop value@>;
12872   } else if (token_type==parameter) {
12873     mp_print_nl(mp, "<argument> "); 
12874   } else if (token_type==backed_up) { 
12875     if ( loc==null ) mp_print_nl(mp, "<recently read> ");
12876     else mp_print_nl(mp, "<to be read again> ");
12877   } else if (token_type==inserted) {
12878     mp_print_nl(mp, "<inserted text> ");
12879   } else if (token_type==macro) {
12880     mp_print_ln(mp);
12881     if ( name!=null ) mp_print_text(name);
12882     else @<Print the name of a \&{vardef}'d macro@>;
12883     mp_print(mp, "->");
12884   } else {
12885     mp_print_nl(mp, "?");/* this should never happen */
12886 @.?\relax@>
12887   }
12888 }
12889
12890 @ The parameter that corresponds to a loop text is either a token list
12891 (in the case of \&{forsuffixes}) or a ``capsule'' (in the case of \&{for}).
12892 We'll discuss capsules later; for now, all we need to know is that
12893 the |link| field in a capsule parameter is |void| and that
12894 |print_exp(p,0)| displays the value of capsule~|p| in abbreviated form.
12895
12896 @d diov (null+1) /* a null pointer different from |null| */
12897
12898 @<Print the current loop value@>=
12899 { mp_print_nl(mp, "<for("); p=mp->param_stack[param_start];
12900   if ( p!=null ) {
12901     if ( link(p)==diov ) mp_print_exp(mp, p,0); /* we're in a \&{for} loop */
12902     else mp_show_token_list(mp, p,null,20,mp->tally);
12903   }
12904   mp_print(mp, ")> ");
12905 }
12906
12907 @ The first two parameters of a macro defined by \&{vardef} will be token
12908 lists representing the macro's prefix and ``at point.'' By putting these
12909 together, we get the macro's full name.
12910
12911 @<Print the name of a \&{vardef}'d macro@>=
12912 { p=mp->param_stack[param_start];
12913   if ( p==null ) {
12914     mp_show_token_list(mp, mp->param_stack[param_start+1],null,20,mp->tally);
12915   } else { 
12916     q=p;
12917     while ( link(q)!=null ) q=link(q);
12918     link(q)=mp->param_stack[param_start+1];
12919     mp_show_token_list(mp, p,null,20,mp->tally);
12920     link(q)=null;
12921   }
12922 }
12923
12924 @ Now it is necessary to explain a little trick. We don't want to store a long
12925 string that corresponds to a token list, because that string might take up
12926 lots of memory; and we are printing during a time when an error message is
12927 being given, so we dare not do anything that might overflow one of \MP's
12928 tables. So `pseudoprinting' is the answer: We enter a mode of printing
12929 that stores characters into a buffer of length |error_line|, where character
12930 $k+1$ is placed into \hbox{|trick_buf[k mod error_line]|} if
12931 |k<trick_count|, otherwise character |k| is dropped. Initially we set
12932 |tally:=0| and |trick_count:=1000000|; then when we reach the
12933 point where transition from line 1 to line 2 should occur, we
12934 set |first_count:=tally| and |trick_count:=@tmax@>(error_line,
12935 tally+1+error_line-half_error_line)|. At the end of the
12936 pseudoprinting, the values of |first_count|, |tally|, and
12937 |trick_count| give us all the information we need to print the two lines,
12938 and all of the necessary text is in |trick_buf|.
12939
12940 Namely, let |l| be the length of the descriptive information that appears
12941 on the first line. The length of the context information gathered for that
12942 line is |k=first_count|, and the length of the context information
12943 gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k<=h|,
12944 where |h=half_error_line|, we print |trick_buf[0..k-1]| after the
12945 descriptive information on line~1, and set |n:=l+k|; here |n| is the
12946 length of line~1. If $l+k>h$, some cropping is necessary, so we set |n:=h|
12947 and print `\.{...}' followed by
12948 $$\hbox{|trick_buf[(l+k-h+3)..k-1]|,}$$
12949 where subscripts of |trick_buf| are circular modulo |error_line|. The
12950 second line consists of |n|~spaces followed by |trick_buf[k..(k+m-1)]|,
12951 unless |n+m>error_line|; in the latter case, further cropping is done.
12952 This is easier to program than to explain.
12953
12954 @<Local variables for formatting...@>=
12955 int i; /* index into |buffer| */
12956 integer l; /* length of descriptive information on line 1 */
12957 integer m; /* context information gathered for line 2 */
12958 int n; /* length of line 1 */
12959 integer p; /* starting or ending place in |trick_buf| */
12960 integer q; /* temporary index */
12961
12962 @ The following code tells the print routines to gather
12963 the desired information.
12964
12965 @d begin_pseudoprint { 
12966   l=mp->tally; mp->tally=0; mp->selector=pseudo;
12967   mp->trick_count=1000000;
12968 }
12969 @d set_trick_count {
12970   mp->first_count=mp->tally;
12971   mp->trick_count=mp->tally+1+mp->error_line-mp->half_error_line;
12972   if ( mp->trick_count<mp->error_line ) mp->trick_count=mp->error_line;
12973 }
12974
12975 @ And the following code uses the information after it has been gathered.
12976
12977 @<Print two lines using the tricky pseudoprinted information@>=
12978 if ( mp->trick_count==1000000 ) set_trick_count;
12979   /* |set_trick_count| must be performed */
12980 if ( mp->tally<mp->trick_count ) m=mp->tally-mp->first_count;
12981 else m=mp->trick_count-mp->first_count; /* context on line 2 */
12982 if ( l+mp->first_count<=mp->half_error_line ) {
12983   p=0; n=l+mp->first_count;
12984 } else  { 
12985   mp_print(mp, "..."); p=l+mp->first_count-mp->half_error_line+3;
12986   n=mp->half_error_line;
12987 }
12988 for (q=p;q<=mp->first_count-1;q++) {
12989   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
12990 }
12991 mp_print_ln(mp);
12992 for (q=1;q<=n;q++) {
12993   mp_print_char(mp, ' '); /* print |n| spaces to begin line~2 */
12994 }
12995 if ( m+n<=mp->error_line ) p=mp->first_count+m; 
12996 else p=mp->first_count+(mp->error_line-n-3);
12997 for (q=mp->first_count;q<=p-1;q++) {
12998   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
12999 }
13000 if ( m+n>mp->error_line ) mp_print(mp, "...")
13001
13002 @ But the trick is distracting us from our current goal, which is to
13003 understand the input state. So let's concentrate on the data structures that
13004 are being pseudoprinted as we finish up the |show_context| procedure.
13005
13006 @<Pseudoprint the line@>=
13007 begin_pseudoprint;
13008 if ( limit>0 ) {
13009   for (i=start;i<=limit-1;i++) {
13010     if ( i==loc ) set_trick_count;
13011     mp_print_str(mp, mp->buffer[i]);
13012   }
13013 }
13014
13015 @ @<Pseudoprint the token list@>=
13016 begin_pseudoprint;
13017 if ( token_type!=macro ) mp_show_token_list(mp, start,loc,100000,0);
13018 else mp_show_macro(mp, start,loc,100000)
13019
13020 @ Here is the missing piece of |show_token_list| that is activated when the
13021 token beginning line~2 is about to be shown:
13022
13023 @<Do magic computation@>=set_trick_count
13024
13025 @* \[28] Maintaining the input stacks.
13026 The following subroutines change the input status in commonly needed ways.
13027
13028 First comes |push_input|, which stores the current state and creates a
13029 new level (having, initially, the same properties as the old).
13030
13031 @d push_input  { /* enter a new input level, save the old */
13032   if ( mp->input_ptr>mp->max_in_stack ) {
13033     mp->max_in_stack=mp->input_ptr;
13034     if ( mp->input_ptr==mp->stack_size ) {
13035       int l = (mp->stack_size+(mp->stack_size>>2));
13036       XREALLOC(mp->input_stack, (l+1), in_state_record);
13037       mp->stack_size = l;
13038     }         
13039   }
13040   mp->input_stack[mp->input_ptr]=mp->cur_input; /* stack the record */
13041   incr(mp->input_ptr);
13042 }
13043
13044 @ And of course what goes up must come down.
13045
13046 @d pop_input { /* leave an input level, re-enter the old */
13047     decr(mp->input_ptr); mp->cur_input=mp->input_stack[mp->input_ptr];
13048   }
13049
13050 @ Here is a procedure that starts a new level of token-list input, given
13051 a token list |p| and its type |t|. If |t=macro|, the calling routine should
13052 set |name|, reset~|loc|, and increase the macro's reference count.
13053
13054 @d back_list(A) mp_begin_token_list(mp, (A),backed_up) /* backs up a simple token list */
13055
13056 @c void mp_begin_token_list (MP mp,pointer p, quarterword t)  { 
13057   push_input; start=p; token_type=t;
13058   param_start=mp->param_ptr; loc=p;
13059 }
13060
13061 @ When a token list has been fully scanned, the following computations
13062 should be done as we leave that level of input.
13063 @^inner loop@>
13064
13065 @c void mp_end_token_list (MP mp) { /* leave a token-list input level */
13066   pointer p; /* temporary register */
13067   if ( token_type>=backed_up ) { /* token list to be deleted */
13068     if ( token_type<=inserted ) { 
13069       mp_flush_token_list(mp, start); goto DONE;
13070     } else {
13071       mp_delete_mac_ref(mp, start); /* update reference count */
13072     }
13073   }
13074   while ( mp->param_ptr>param_start ) { /* parameters must be flushed */
13075     decr(mp->param_ptr);
13076     p=mp->param_stack[mp->param_ptr];
13077     if ( p!=null ) {
13078       if ( link(p)==diov ) { /* it's an \&{expr} parameter */
13079         mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
13080       } else {
13081         mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
13082       }
13083     }
13084   }
13085 DONE: 
13086   pop_input; check_interrupt;
13087 }
13088
13089 @ The contents of |cur_cmd,cur_mod,cur_sym| are placed into an equivalent
13090 token by the |cur_tok| routine.
13091 @^inner loop@>
13092
13093 @c @<Declare the procedure called |make_exp_copy|@>;
13094 pointer mp_cur_tok (MP mp) {
13095   pointer p; /* a new token node */
13096   small_number save_type; /* |cur_type| to be restored */
13097   integer save_exp; /* |cur_exp| to be restored */
13098   if ( mp->cur_sym==0 ) {
13099     if ( mp->cur_cmd==capsule_token ) {
13100       save_type=mp->cur_type; save_exp=mp->cur_exp;
13101       mp_make_exp_copy(mp, mp->cur_mod); p=mp_stash_cur_exp(mp); link(p)=null;
13102       mp->cur_type=save_type; mp->cur_exp=save_exp;
13103     } else { 
13104       p=mp_get_node(mp, token_node_size);
13105       value(p)=mp->cur_mod; name_type(p)=mp_token;
13106       if ( mp->cur_cmd==numeric_token ) type(p)=mp_known;
13107       else type(p)=mp_string_type;
13108     }
13109   } else { 
13110     fast_get_avail(p); info(p)=mp->cur_sym;
13111   }
13112   return p;
13113 }
13114
13115 @ Sometimes \MP\ has read too far and wants to ``unscan'' what it has
13116 seen. The |back_input| procedure takes care of this by putting the token
13117 just scanned back into the input stream, ready to be read again.
13118 If |cur_sym<>0|, the values of |cur_cmd| and |cur_mod| are irrelevant.
13119
13120 @<Declarations@>= 
13121 void mp_back_input (MP mp);
13122
13123 @ @c void mp_back_input (MP mp) {/* undoes one token of input */
13124   pointer p; /* a token list of length one */
13125   p=mp_cur_tok(mp);
13126   while ( token_state &&(loc==null) ) 
13127     mp_end_token_list(mp); /* conserve stack space */
13128   back_list(p);
13129 }
13130
13131 @ The |back_error| routine is used when we want to restore or replace an
13132 offending token just before issuing an error message.  We disable interrupts
13133 during the call of |back_input| so that the help message won't be lost.
13134
13135 @<Declarations@>=
13136 void mp_error (MP mp);
13137 void mp_back_error (MP mp);
13138
13139 @ @c void mp_back_error (MP mp) { /* back up one token and call |error| */
13140   mp->OK_to_interrupt=false; 
13141   mp_back_input(mp); 
13142   mp->OK_to_interrupt=true; mp_error(mp);
13143 }
13144 void mp_ins_error (MP mp) { /* back up one inserted token and call |error| */
13145   mp->OK_to_interrupt=false; 
13146   mp_back_input(mp); token_type=inserted;
13147   mp->OK_to_interrupt=true; mp_error(mp);
13148 }
13149
13150 @ The |begin_file_reading| procedure starts a new level of input for lines
13151 of characters to be read from a file, or as an insertion from the
13152 terminal. It does not take care of opening the file, nor does it set |loc|
13153 or |limit| or |line|.
13154 @^system dependencies@>
13155
13156 @c void mp_begin_file_reading (MP mp) { 
13157   if ( mp->in_open==mp->max_in_open ) 
13158     mp_overflow(mp, "text input levels",mp->max_in_open);
13159 @:MetaPost capacity exceeded text input levels}{\quad text input levels@>
13160   if ( mp->first==mp->buf_size ) 
13161     mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13162   incr(mp->in_open); push_input; index=mp->in_open;
13163   mp->mpx_name[index]=absent;
13164   start=mp->first;
13165   name=is_term; /* |terminal_input| is now |true| */
13166 }
13167
13168 @ Conversely, the variables must be downdated when such a level of input
13169 is finished.  Any associated \.{MPX} file must also be closed and popped
13170 off the file stack.
13171
13172 @c void mp_end_file_reading (MP mp) { 
13173   if ( mp->in_open>index ) {
13174     if ( (mp->mpx_name[mp->in_open]==absent)||(name<=max_spec_src) ) {
13175       mp_confusion(mp, "endinput");
13176 @:this can't happen endinput}{\quad endinput@>
13177     } else { 
13178       fclose(mp->input_file[mp->in_open]); /* close an \.{MPX} file */
13179       delete_str_ref(mp->mpx_name[mp->in_open]);
13180       decr(mp->in_open);
13181     }
13182   }
13183   mp->first=start;
13184   if ( index!=mp->in_open ) mp_confusion(mp, "endinput");
13185   if ( name>max_spec_src ) {
13186     fclose(cur_file);
13187     delete_str_ref(name);
13188     xfree(in_name); in_name=NULL;
13189     xfree(in_area); in_area=NULL;
13190   }
13191   pop_input; decr(mp->in_open);
13192 }
13193
13194 @ Here is a function that tries to resume input from an \.{MPX} file already
13195 associated with the current input file.  It returns |false| if this doesn't
13196 work.
13197
13198 @c boolean mp_begin_mpx_reading (MP mp) { 
13199   if ( mp->in_open!=index+1 ) {
13200      return false;
13201   } else { 
13202     if ( mp->mpx_name[mp->in_open]<=absent ) mp_confusion(mp, "mpx");
13203 @:this can't happen mpx}{\quad mpx@>
13204     if ( mp->first==mp->buf_size ) 
13205       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13206     push_input; index=mp->in_open;
13207     start=mp->first;
13208     name=mp->mpx_name[mp->in_open]; add_str_ref(name);
13209     @<Put an empty line in the input buffer@>;
13210     return true;
13211   }
13212 }
13213
13214 @ This procedure temporarily stops reading an \.{MPX} file.
13215
13216 @c void mp_end_mpx_reading (MP mp) { 
13217   if ( mp->in_open!=index ) mp_confusion(mp, "mpx");
13218 @:this can't happen mpx}{\quad mpx@>
13219   if ( loc<limit ) {
13220     @<Complain that we are not at the end of a line in the \.{MPX} file@>;
13221   }
13222   mp->first=start;
13223   pop_input;
13224 }
13225
13226 @ Here we enforce a restriction that simplifies the input stacks considerably.
13227 This should not inconvenience the user because \.{MPX} files are generated
13228 by an auxiliary program called \.{DVItoMP}.
13229
13230 @ @<Complain that we are not at the end of a line in the \.{MPX} file@>=
13231
13232 print_err("`mpxbreak' must be at the end of a line");
13233 help4("This file contains picture expressions for btex...etex")
13234   ("blocks.  Such files are normally generated automatically")
13235   ("but this one seems to be messed up.  I'm going to ignore")
13236   ("the rest of this line.");
13237 mp_error(mp);
13238 }
13239
13240 @ In order to keep the stack from overflowing during a long sequence of
13241 inserted `\.{show}' commands, the following routine removes completed
13242 error-inserted lines from memory.
13243
13244 @c void mp_clear_for_error_prompt (MP mp) { 
13245   while ( file_state && terminal_input &&
13246     (mp->input_ptr>0)&&(loc==limit) ) mp_end_file_reading(mp);
13247   mp_print_ln(mp); clear_terminal;
13248 }
13249
13250 @ To get \MP's whole input mechanism going, we perform the following
13251 actions.
13252
13253 @<Initialize the input routines@>=
13254 { mp->input_ptr=0; mp->max_in_stack=0;
13255   mp->in_open=0; mp->open_parens=0; mp->max_buf_stack=0;
13256   mp->param_ptr=0; mp->max_param_stack=0;
13257   mp->first=1;
13258   start=1; index=0; line=0; name=is_term;
13259   mp->mpx_name[0]=absent;
13260   mp->force_eof=false;
13261   if ( ! mp_init_terminal(mp) ) exit(EXIT_FAILURE);
13262   limit=mp->last; mp->first=mp->last+1; 
13263   /* |init_terminal| has set |loc| and |last| */
13264 }
13265
13266 @* \[29] Getting the next token.
13267 The heart of \MP's input mechanism is the |get_next| procedure, which
13268 we shall develop in the next few sections of the program. Perhaps we
13269 shouldn't actually call it the ``heart,'' however; it really acts as \MP's
13270 eyes and mouth, reading the source files and gobbling them up. And it also
13271 helps \MP\ to regurgitate stored token lists that are to be processed again.
13272
13273 The main duty of |get_next| is to input one token and to set |cur_cmd|
13274 and |cur_mod| to that token's command code and modifier. Furthermore, if
13275 the input token is a symbolic token, that token's |hash| address
13276 is stored in |cur_sym|; otherwise |cur_sym| is set to zero.
13277
13278 Underlying this simple description is a certain amount of complexity
13279 because of all the cases that need to be handled.
13280 However, the inner loop of |get_next| is reasonably short and fast.
13281
13282 @ Before getting into |get_next|, we need to consider a mechanism by which
13283 \MP\ helps keep errors from propagating too far. Whenever the program goes
13284 into a mode where it keeps calling |get_next| repeatedly until a certain
13285 condition is met, it sets |scanner_status| to some value other than |normal|.
13286 Then if an input file ends, or if an `\&{outer}' symbol appears,
13287 an appropriate error recovery will be possible.
13288
13289 The global variable |warning_info| helps in this error recovery by providing
13290 additional information. For example, |warning_info| might indicate the
13291 name of a macro whose replacement text is being scanned.
13292
13293 @d normal 0 /* |scanner_status| at ``quiet times'' */
13294 @d skipping 1 /* |scanner_status| when false conditional text is being skipped */
13295 @d flushing 2 /* |scanner_status| when junk after a statement is being ignored */
13296 @d absorbing 3 /* |scanner_status| when a \&{text} parameter is being scanned */
13297 @d var_defining 4 /* |scanner_status| when a \&{vardef} is being scanned */
13298 @d op_defining 5 /* |scanner_status| when a macro \&{def} is being scanned */
13299 @d loop_defining 6 /* |scanner_status| when a \&{for} loop is being scanned */
13300 @d tex_flushing 7 /* |scanner_status| when skipping \TeX\ material */
13301
13302 @<Glob...@>=
13303 integer scanner_status; /* are we scanning at high speed? */
13304 integer warning_info; /* if so, what else do we need to know,
13305     in case an error occurs? */
13306
13307 @ @<Initialize the input routines@>=
13308 mp->scanner_status=normal;
13309
13310 @ The following subroutine
13311 is called when an `\&{outer}' symbolic token has been scanned or
13312 when the end of a file has been reached. These two cases are distinguished
13313 by |cur_sym|, which is zero at the end of a file.
13314
13315 @c boolean mp_check_outer_validity (MP mp) {
13316   pointer p; /* points to inserted token list */
13317   if ( mp->scanner_status==normal ) {
13318     return true;
13319   } else if ( mp->scanner_status==tex_flushing ) {
13320     @<Check if the file has ended while flushing \TeX\ material and set the
13321       result value for |check_outer_validity|@>;
13322   } else { 
13323     mp->deletions_allowed=false;
13324     @<Back up an outer symbolic token so that it can be reread@>;
13325     if ( mp->scanner_status>skipping ) {
13326       @<Tell the user what has run away and try to recover@>;
13327     } else { 
13328       print_err("Incomplete if; all text was ignored after line ");
13329 @.Incomplete if...@>
13330       mp_print_int(mp, mp->warning_info);
13331       help3("A forbidden `outer' token occurred in skipped text.")
13332         ("This kind of error happens when you say `if...' and forget")
13333         ("the matching `fi'. I've inserted a `fi'; this might work.");
13334       if ( mp->cur_sym==0 ) 
13335         mp->help_line[2]="The file ended while I was skipping conditional text.";
13336       mp->cur_sym=frozen_fi; mp_ins_error(mp);
13337     }
13338     mp->deletions_allowed=true; 
13339         return false;
13340   }
13341 }
13342
13343 @ @<Check if the file has ended while flushing \TeX\ material and set...@>=
13344 if ( mp->cur_sym!=0 ) { 
13345    return true;
13346 } else { 
13347   mp->deletions_allowed=false;
13348   print_err("TeX mode didn't end; all text was ignored after line ");
13349   mp_print_int(mp, mp->warning_info);
13350   help2("The file ended while I was looking for the `etex' to")
13351     ("finish this TeX material.  I've inserted `etex' now.");
13352   mp->cur_sym = frozen_etex;
13353   mp_ins_error(mp);
13354   mp->deletions_allowed=true;
13355   return false;
13356 }
13357
13358 @ @<Back up an outer symbolic token so that it can be reread@>=
13359 if ( mp->cur_sym!=0 ) {
13360   p=mp_get_avail(mp); info(p)=mp->cur_sym;
13361   back_list(p); /* prepare to read the symbolic token again */
13362 }
13363
13364 @ @<Tell the user what has run away...@>=
13365
13366   mp_runaway(mp); /* print the definition-so-far */
13367   if ( mp->cur_sym==0 ) {
13368     print_err("File ended");
13369 @.File ended while scanning...@>
13370   } else { 
13371     print_err("Forbidden token found");
13372 @.Forbidden token found...@>
13373   }
13374   mp_print(mp, " while scanning ");
13375   help4("I suspect you have forgotten an `enddef',")
13376     ("causing me to read past where you wanted me to stop.")
13377     ("I'll try to recover; but if the error is serious,")
13378     ("you'd better type `E' or `X' now and fix your file.");
13379   switch (mp->scanner_status) {
13380     @<Complete the error message,
13381       and set |cur_sym| to a token that might help recover from the error@>
13382   } /* there are no other cases */
13383   mp_ins_error(mp);
13384 }
13385
13386 @ As we consider various kinds of errors, it is also appropriate to
13387 change the first line of the help message just given; |help_line[3]|
13388 points to the string that might be changed.
13389
13390 @<Complete the error message,...@>=
13391 case flushing: 
13392   mp_print(mp, "to the end of the statement");
13393   mp->help_line[3]="A previous error seems to have propagated,";
13394   mp->cur_sym=frozen_semicolon;
13395   break;
13396 case absorbing: 
13397   mp_print(mp, "a text argument");
13398   mp->help_line[3]="It seems that a right delimiter was left out,";
13399   if ( mp->warning_info==0 ) {
13400     mp->cur_sym=frozen_end_group;
13401   } else { 
13402     mp->cur_sym=frozen_right_delimiter;
13403     equiv(frozen_right_delimiter)=mp->warning_info;
13404   }
13405   break;
13406 case var_defining:
13407 case op_defining: 
13408   mp_print(mp, "the definition of ");
13409   if ( mp->scanner_status==op_defining ) 
13410      mp_print_text(mp->warning_info);
13411   else 
13412      mp_print_variable_name(mp, mp->warning_info);
13413   mp->cur_sym=frozen_end_def;
13414   break;
13415 case loop_defining: 
13416   mp_print(mp, "the text of a "); 
13417   mp_print_text(mp->warning_info);
13418   mp_print(mp, " loop");
13419   mp->help_line[3]="I suspect you have forgotten an `endfor',";
13420   mp->cur_sym=frozen_end_for;
13421   break;
13422
13423 @ The |runaway| procedure displays the first part of the text that occurred
13424 when \MP\ began its special |scanner_status|, if that text has been saved.
13425
13426 @<Declare the procedure called |runaway|@>=
13427 void mp_runaway (MP mp) { 
13428   if ( mp->scanner_status>flushing ) { 
13429      mp_print_nl(mp, "Runaway ");
13430          switch (mp->scanner_status) { 
13431          case absorbing: mp_print(mp, "text?"); break;
13432          case var_defining: 
13433      case op_defining: mp_print(mp,"definition?"); break;
13434      case loop_defining: mp_print(mp, "loop?"); break;
13435      } /* there are no other cases */
13436      mp_print_ln(mp); 
13437      mp_show_token_list(mp, link(hold_head),null,mp->error_line-10,0);
13438   }
13439 }
13440
13441 @ We need to mention a procedure that may be called by |get_next|.
13442
13443 @<Declarations@>= 
13444 void mp_firm_up_the_line (MP mp);
13445
13446 @ And now we're ready to take the plunge into |get_next| itself.
13447 Note that the behavior depends on the |scanner_status| because percent signs
13448 and double quotes need to be passed over when skipping TeX material.
13449
13450 @c 
13451 void mp_get_next (MP mp) {
13452   /* sets |cur_cmd|, |cur_mod|, |cur_sym| to next token */
13453 @^inner loop@>
13454   /*restart*/ /* go here to get the next input token */
13455   /*exit*/ /* go here when the next input token has been got */
13456   /*|common_ending|*/ /* go here to finish getting a symbolic token */
13457   /*found*/ /* go here when the end of a symbolic token has been found */
13458   /*switch*/ /* go here to branch on the class of an input character */
13459   /*|start_numeric_token|,|start_decimal_token|,|fin_numeric_token|,|done|*/
13460     /* go here at crucial stages when scanning a number */
13461   int k; /* an index into |buffer| */
13462   ASCII_code c; /* the current character in the buffer */
13463   ASCII_code class; /* its class number */
13464   integer n,f; /* registers for decimal-to-binary conversion */
13465 RESTART: 
13466   mp->cur_sym=0;
13467   if ( file_state ) {
13468     @<Input from external file; |goto restart| if no input found,
13469     or |return| if a non-symbolic token is found@>;
13470   } else {
13471     @<Input from token list; |goto restart| if end of list or
13472       if a parameter needs to be expanded,
13473       or |return| if a non-symbolic token is found@>;
13474   }
13475 COMMON_ENDING: 
13476   @<Finish getting the symbolic token in |cur_sym|;
13477    |goto restart| if it is illegal@>;
13478 }
13479
13480 @ When a symbolic token is declared to be `\&{outer}', its command code
13481 is increased by |outer_tag|.
13482 @^inner loop@>
13483
13484 @<Finish getting the symbolic token in |cur_sym|...@>=
13485 mp->cur_cmd=eq_type(mp->cur_sym); mp->cur_mod=equiv(mp->cur_sym);
13486 if ( mp->cur_cmd>=outer_tag ) {
13487   if ( mp_check_outer_validity(mp) ) 
13488     mp->cur_cmd=mp->cur_cmd-outer_tag;
13489   else 
13490     goto RESTART;
13491 }
13492
13493 @ A percent sign appears in |buffer[limit]|; this makes it unnecessary
13494 to have a special test for end-of-line.
13495 @^inner loop@>
13496
13497 @<Input from external file;...@>=
13498
13499 SWITCH: 
13500   c=mp->buffer[loc]; incr(loc); class=mp->char_class[c];
13501   switch (class) {
13502   case digit_class: goto START_NUMERIC_TOKEN; break;
13503   case period_class: 
13504     class=mp->char_class[mp->buffer[loc]];
13505     if ( class>period_class ) {
13506       goto SWITCH;
13507     } else if ( class<period_class ) { /* |class=digit_class| */
13508       n=0; goto START_DECIMAL_TOKEN;
13509     }
13510 @:. }{\..\ token@>
13511     break;
13512   case space_class: goto SWITCH; break;
13513   case percent_class: 
13514     if ( mp->scanner_status==tex_flushing ) {
13515       if ( loc<limit ) goto SWITCH;
13516     }
13517     @<Move to next line of file, or |goto restart| if there is no next line@>;
13518     check_interrupt;
13519     goto SWITCH;
13520     break;
13521   case string_class: 
13522     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13523     else @<Get a string token and |return|@>;
13524     break;
13525   case isolated_classes: 
13526     k=loc-1; goto FOUND; break;
13527   case invalid_class: 
13528     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13529     else @<Decry the invalid character and |goto restart|@>;
13530     break;
13531   default: break; /* letters, etc. */
13532   }
13533   k=loc-1;
13534   while ( mp->char_class[mp->buffer[loc]]==class ) incr(loc);
13535   goto FOUND;
13536 START_NUMERIC_TOKEN:
13537   @<Get the integer part |n| of a numeric token;
13538     set |f:=0| and |goto fin_numeric_token| if there is no decimal point@>;
13539 START_DECIMAL_TOKEN:
13540   @<Get the fraction part |f| of a numeric token@>;
13541 FIN_NUMERIC_TOKEN:
13542   @<Pack the numeric and fraction parts of a numeric token
13543     and |return|@>;
13544 FOUND: 
13545   mp->cur_sym=mp_id_lookup(mp, k,loc-k);
13546 }
13547
13548 @ We go to |restart| instead of to |SWITCH|, because |state| might equal
13549 |token_list| after the error has been dealt with
13550 (cf.\ |clear_for_error_prompt|).
13551
13552 @<Decry the invalid...@>=
13553
13554   print_err("Text line contains an invalid character");
13555 @.Text line contains...@>
13556   help2("A funny symbol that I can\'t read has just been input.")
13557     ("Continue, and I'll forget that it ever happened.");
13558   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13559   goto RESTART;
13560 }
13561
13562 @ @<Get a string token and |return|@>=
13563
13564   if ( mp->buffer[loc]=='"' ) {
13565     mp->cur_mod=rts("");
13566   } else { 
13567     k=loc; mp->buffer[limit+1]='"';
13568     do {  
13569      incr(loc);
13570     } while (mp->buffer[loc]!='"');
13571     if ( loc>limit ) {
13572       @<Decry the missing string delimiter and |goto restart|@>;
13573     }
13574     if ( loc==k+1 ) {
13575       mp->cur_mod=mp->buffer[k];
13576     } else { 
13577       str_room(loc-k);
13578       do {  
13579         append_char(mp->buffer[k]); incr(k);
13580       } while (k!=loc);
13581       mp->cur_mod=mp_make_string(mp);
13582     }
13583   }
13584   incr(loc); mp->cur_cmd=string_token; 
13585   return;
13586 }
13587
13588 @ We go to |restart| after this error message, not to |SWITCH|,
13589 because the |clear_for_error_prompt| routine might have reinstated
13590 |token_state| after |error| has finished.
13591
13592 @<Decry the missing string delimiter and |goto restart|@>=
13593
13594   loc=limit; /* the next character to be read on this line will be |"%"| */
13595   print_err("Incomplete string token has been flushed");
13596 @.Incomplete string token...@>
13597   help3("Strings should finish on the same line as they began.")
13598     ("I've deleted the partial string; you might want to")
13599     ("insert another by typing, e.g., `I\"new string\"'.");
13600   mp->deletions_allowed=false; mp_error(mp);
13601   mp->deletions_allowed=true; 
13602   goto RESTART;
13603 }
13604
13605 @ @<Get the integer part |n| of a numeric token...@>=
13606 n=c-'0';
13607 while ( mp->char_class[mp->buffer[loc]]==digit_class ) {
13608   if ( n<32768 ) n=10*n+mp->buffer[loc]-'0';
13609   incr(loc);
13610 }
13611 if ( mp->buffer[loc]=='.' ) 
13612   if ( mp->char_class[mp->buffer[loc+1]]==digit_class ) 
13613     goto DONE;
13614 f=0; 
13615 goto FIN_NUMERIC_TOKEN;
13616 DONE: incr(loc)
13617
13618 @ @<Get the fraction part |f| of a numeric token@>=
13619 k=0;
13620 do { 
13621   if ( k<17 ) { /* digits for |k>=17| cannot affect the result */
13622     mp->dig[k]=mp->buffer[loc]-'0'; incr(k);
13623   }
13624   incr(loc);
13625 } while (mp->char_class[mp->buffer[loc]]==digit_class);
13626 f=mp_round_decimals(mp, k);
13627 if ( f==unity ) {
13628   incr(n); f=0;
13629 }
13630
13631 @ @<Pack the numeric and fraction parts of a numeric token and |return|@>=
13632 if ( n<32768 ) {
13633   @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>;
13634 } else if ( mp->scanner_status!=tex_flushing ) {
13635   print_err("Enormous number has been reduced");
13636 @.Enormous number...@>
13637   help2("I can\'t handle numbers bigger than 32767.99998;")
13638     ("so I've changed your constant to that maximum amount.");
13639   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13640   mp->cur_mod=el_gordo;
13641 }
13642 mp->cur_cmd=numeric_token; return
13643
13644 @ @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>=
13645
13646   mp->cur_mod=n*unity+f;
13647   if ( mp->cur_mod>=fraction_one ) {
13648     if ( (mp->internal[warning_check]>0) &&
13649          (mp->scanner_status!=tex_flushing) ) {
13650       print_err("Number is too large (");
13651       mp_print_scaled(mp, mp->cur_mod);
13652       mp_print_char(mp, ')');
13653       help3("It is at least 4096. Continue and I'll try to cope")
13654       ("with that big value; but it might be dangerous.")
13655       ("(Set warningcheck:=0 to suppress this message.)");
13656       mp_error(mp);
13657     }
13658   }
13659 }
13660
13661 @ Let's consider now what happens when |get_next| is looking at a token list.
13662 @^inner loop@>
13663
13664 @<Input from token list;...@>=
13665 if ( loc>=mp->hi_mem_min ) { /* one-word token */
13666   mp->cur_sym=info(loc); loc=link(loc); /* move to next */
13667   if ( mp->cur_sym>=expr_base ) {
13668     if ( mp->cur_sym>=suffix_base ) {
13669       @<Insert a suffix or text parameter and |goto restart|@>;
13670     } else { 
13671       mp->cur_cmd=capsule_token;
13672       mp->cur_mod=mp->param_stack[param_start+mp->cur_sym-(expr_base)];
13673       mp->cur_sym=0; return;
13674     }
13675   }
13676 } else if ( loc>null ) {
13677   @<Get a stored numeric or string or capsule token and |return|@>
13678 } else { /* we are done with this token list */
13679   mp_end_token_list(mp); goto RESTART; /* resume previous level */
13680 }
13681
13682 @ @<Insert a suffix or text parameter...@>=
13683
13684   if ( mp->cur_sym>=text_base ) mp->cur_sym=mp->cur_sym-mp->param_size;
13685   /* |param_size=text_base-suffix_base| */
13686   mp_begin_token_list(mp,
13687                       mp->param_stack[param_start+mp->cur_sym-(suffix_base)],
13688                       parameter);
13689   goto RESTART;
13690 }
13691
13692 @ @<Get a stored numeric or string or capsule token...@>=
13693
13694   if ( name_type(loc)==mp_token ) {
13695     mp->cur_mod=value(loc);
13696     if ( type(loc)==mp_known ) {
13697       mp->cur_cmd=numeric_token;
13698     } else { 
13699       mp->cur_cmd=string_token; add_str_ref(mp->cur_mod);
13700     }
13701   } else { 
13702     mp->cur_mod=loc; mp->cur_cmd=capsule_token;
13703   };
13704   loc=link(loc); return;
13705 }
13706
13707 @ All of the easy branches of |get_next| have now been taken care of.
13708 There is one more branch.
13709
13710 @<Move to next line of file, or |goto restart|...@>=
13711 if ( name>max_spec_src ) {
13712   @<Read next line of file into |buffer|, or
13713     |goto restart| if the file has ended@>;
13714 } else { 
13715   if ( mp->input_ptr>0 ) {
13716      /* text was inserted during error recovery or by \&{scantokens} */
13717     mp_end_file_reading(mp); goto RESTART; /* resume previous level */
13718   }
13719   if ( mp->selector<log_only || mp->selector>=write_file) mp_open_log_file(mp);
13720   if ( mp->interaction>mp_nonstop_mode ) {
13721     if ( limit==start ) /* previous line was empty */
13722       mp_print_nl(mp, "(Please type a command or say `end')");
13723 @.Please type...@>
13724     mp_print_ln(mp); mp->first=start;
13725     prompt_input("*"); /* input on-line into |buffer| */
13726 @.*\relax@>
13727     limit=mp->last; mp->buffer[limit]='%';
13728     mp->first=limit+1; loc=start;
13729   } else {
13730     mp_fatal_error(mp, "*** (job aborted, no legal end found)");
13731 @.job aborted@>
13732     /* nonstop mode, which is intended for overnight batch processing,
13733     never waits for on-line input */
13734   }
13735 }
13736
13737 @ The global variable |force_eof| is normally |false|; it is set |true|
13738 by an \&{endinput} command.
13739
13740 @<Glob...@>=
13741 boolean force_eof; /* should the next \&{input} be aborted early? */
13742
13743 @ We must decrement |loc| in order to leave the buffer in a valid state
13744 when an error condition causes us to |goto restart| without calling
13745 |end_file_reading|.
13746
13747 @<Read next line of file into |buffer|, or
13748   |goto restart| if the file has ended@>=
13749
13750   incr(line); mp->first=start;
13751   if ( ! mp->force_eof ) {
13752     if ( mp_input_ln(mp, cur_file,true) ) /* not end of file */
13753       mp_firm_up_the_line(mp); /* this sets |limit| */
13754     else 
13755       mp->force_eof=true;
13756   };
13757   if ( mp->force_eof ) {
13758     mp->force_eof=false;
13759     decr(loc);
13760     if ( mpx_reading ) {
13761       @<Complain that the \.{MPX} file ended unexpectly; then set
13762         |cur_sym:=frozen_mpx_break| and |goto comon_ending|@>;
13763     } else { 
13764       mp_print_char(mp, ')'); decr(mp->open_parens);
13765       update_terminal; /* show user that file has been read */
13766       mp_end_file_reading(mp); /* resume previous level */
13767       if ( mp_check_outer_validity(mp) ) goto  RESTART;  
13768       else goto RESTART;
13769     }
13770   }
13771   mp->buffer[limit]='%'; mp->first=limit+1; loc=start; /* ready to read */
13772 }
13773
13774 @ We should never actually come to the end of an \.{MPX} file because such
13775 files should have an \&{mpxbreak} after the translation of the last
13776 \&{btex}$\,\ldots\,$\&{etex} block.
13777
13778 @<Complain that the \.{MPX} file ended unexpectly; then set...@>=
13779
13780   mp->mpx_name[index]=finished;
13781   print_err("mpx file ended unexpectedly");
13782   help4("The file had too few picture expressions for btex...etex")
13783     ("blocks.  Such files are normally generated automatically")
13784     ("but this one got messed up.  You might want to insert a")
13785     ("picture expression now.");
13786   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13787   mp->cur_sym=frozen_mpx_break; goto COMMON_ENDING;
13788 }
13789
13790 @ Sometimes we want to make it look as though we have just read a blank line
13791 without really doing so.
13792
13793 @<Put an empty line in the input buffer@>=
13794 mp->last=mp->first; limit=mp->last; /* simulate |input_ln| and |firm_up_the_line| */
13795 mp->buffer[limit]='%'; mp->first=limit+1; loc=start
13796
13797 @ If the user has set the |pausing| parameter to some positive value,
13798 and if nonstop mode has not been selected, each line of input is displayed
13799 on the terminal and the transcript file, followed by `\.{=>}'.
13800 \MP\ waits for a response. If the response is null (i.e., if nothing is
13801 typed except perhaps a few blank spaces), the original
13802 line is accepted as it stands; otherwise the line typed is
13803 used instead of the line in the file.
13804
13805 @c void mp_firm_up_the_line (MP mp) {
13806   size_t k; /* an index into |buffer| */
13807   limit=mp->last;
13808   if ( mp->internal[pausing]>0 ) if ( mp->interaction>mp_nonstop_mode ) {
13809     wake_up_terminal; mp_print_ln(mp);
13810     if ( start<limit ) {
13811       for (k=(size_t)start;k<=(size_t)(limit-1);k++) {
13812         mp_print_str(mp, mp->buffer[k]);
13813       } 
13814     }
13815     mp->first=limit; prompt_input("=>"); /* wait for user response */
13816 @.=>@>
13817     if ( mp->last>mp->first ) {
13818       for (k=mp->first;k<=mp->last-1;k++) { /* move line down in buffer */
13819         mp->buffer[k+start-mp->first]=mp->buffer[k];
13820       }
13821       limit=start+mp->last-mp->first;
13822     }
13823   }
13824 }
13825
13826 @* \[30] Dealing with \TeX\ material.
13827 The \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}$\,\ldots\,$\&{etex}
13828 features need to be implemented at a low level in the scanning process
13829 so that \MP\ can stay in synch with the a preprocessor that treats
13830 blocks of \TeX\ material as they occur in the input file without trying
13831 to expand \MP\ macros.  Thus we need a special version of |get_next|
13832 that does not expand macros and such but does handle \&{btex},
13833 \&{verbatimtex}, etc.
13834
13835 The special version of |get_next| is called |get_t_next|.  It works by flushing
13836 \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}\allowbreak
13837 $\,\ldots\,$\&{etex} blocks, switching to the \.{MPX} file when it sees
13838 \&{btex}, and switching back when it sees \&{mpxbreak}.
13839
13840 @d btex_code 0
13841 @d verbatim_code 1
13842
13843 @ @<Put each...@>=
13844 mp_primitive(mp, "btex",start_tex,btex_code);
13845 @:btex_}{\&{btex} primitive@>
13846 mp_primitive(mp, "verbatimtex",start_tex,verbatim_code);
13847 @:verbatimtex_}{\&{verbatimtex} primitive@>
13848 mp_primitive(mp, "etex",etex_marker,0); mp->eqtb[frozen_etex]=mp->eqtb[mp->cur_sym];
13849 @:etex_}{\&{etex} primitive@>
13850 mp_primitive(mp, "mpxbreak",mpx_break,0); mp->eqtb[frozen_mpx_break]=mp->eqtb[mp->cur_sym];
13851 @:mpx_break_}{\&{mpxbreak} primitive@>
13852
13853 @ @<Cases of |print_cmd...@>=
13854 case start_tex: if ( m==btex_code ) mp_print(mp, "btex");
13855   else mp_print(mp, "verbatimtex"); break;
13856 case etex_marker: mp_print(mp, "etex"); break;
13857 case mpx_break: mp_print(mp, "mpxbreak"); break;
13858
13859 @ Actually, |get_t_next| is a macro that avoids procedure overhead except
13860 in the unusual case where \&{btex}, \&{verbatimtex}, \&{etex}, or \&{mpxbreak}
13861 is encountered.
13862
13863 @d get_t_next {mp_get_next(mp); if ( mp->cur_cmd<=max_pre_command ) mp_t_next(mp); }
13864
13865 @<Declarations@>=
13866 void mp_start_mpx_input (MP mp);
13867
13868 @ @c 
13869 void mp_t_next (MP mp) {
13870   int old_status; /* saves the |scanner_status| */
13871   integer old_info; /* saves the |warning_info| */
13872   while ( mp->cur_cmd<=max_pre_command ) {
13873     if ( mp->cur_cmd==mpx_break ) {
13874       if ( ! file_state || (mp->mpx_name[index]==absent) ) {
13875         @<Complain about a misplaced \&{mpxbreak}@>;
13876       } else { 
13877         mp_end_mpx_reading(mp); 
13878         goto TEX_FLUSH;
13879       }
13880     } else if ( mp->cur_cmd==start_tex ) {
13881       if ( token_state || (name<=max_spec_src) ) {
13882         @<Complain that we are not reading a file@>;
13883       } else if ( mpx_reading ) {
13884         @<Complain that \.{MPX} files cannot contain \TeX\ material@>;
13885       } else if ( (mp->cur_mod!=verbatim_code)&&
13886                   (mp->mpx_name[index]!=finished) ) {
13887         if ( ! mp_begin_mpx_reading(mp) ) mp_start_mpx_input(mp);
13888       } else {
13889         goto TEX_FLUSH;
13890       }
13891     } else {
13892        @<Complain about a misplaced \&{etex}@>;
13893     }
13894     goto COMMON_ENDING;
13895   TEX_FLUSH: 
13896     @<Flush the \TeX\ material@>;
13897   COMMON_ENDING: 
13898     mp_get_next(mp);
13899   }
13900 }
13901
13902 @ We could be in the middle of an operation such as skipping false conditional
13903 text when \TeX\ material is encountered, so we must be careful to save the
13904 |scanner_status|.
13905
13906 @<Flush the \TeX\ material@>=
13907 old_status=mp->scanner_status;
13908 old_info=mp->warning_info;
13909 mp->scanner_status=tex_flushing;
13910 mp->warning_info=line;
13911 do {  mp_get_next(mp); } while (mp->cur_cmd!=etex_marker);
13912 mp->scanner_status=old_status;
13913 mp->warning_info=old_info
13914
13915 @ @<Complain that \.{MPX} files cannot contain \TeX\ material@>=
13916 { print_err("An mpx file cannot contain btex or verbatimtex blocks");
13917 help4("This file contains picture expressions for btex...etex")
13918   ("blocks.  Such files are normally generated automatically")
13919   ("but this one seems to be messed up.  I'll just keep going")
13920   ("and hope for the best.");
13921 mp_error(mp);
13922 }
13923
13924 @ @<Complain that we are not reading a file@>=
13925 { print_err("You can only use `btex' or `verbatimtex' in a file");
13926 help3("I'll have to ignore this preprocessor command because it")
13927   ("only works when there is a file to preprocess.  You might")
13928   ("want to delete everything up to the next `etex`.");
13929 mp_error(mp);
13930 }
13931
13932 @ @<Complain about a misplaced \&{mpxbreak}@>=
13933 { print_err("Misplaced mpxbreak");
13934 help2("I'll ignore this preprocessor command because it")
13935   ("doesn't belong here");
13936 mp_error(mp);
13937 }
13938
13939 @ @<Complain about a misplaced \&{etex}@>=
13940 { print_err("Extra etex will be ignored");
13941 help1("There is no btex or verbatimtex for this to match");
13942 mp_error(mp);
13943 }
13944
13945 @* \[31] Scanning macro definitions.
13946 \MP\ has a variety of ways to tuck tokens away into token lists for later
13947 use: Macros can be defined with \&{def}, \&{vardef}, \&{primarydef}, etc.;
13948 repeatable code can be defined with \&{for}, \&{forever}, \&{forsuffixes}.
13949 All such operations are handled by the routines in this part of the program.
13950
13951 The modifier part of each command code is zero for the ``ending delimiters''
13952 like \&{enddef} and \&{endfor}.
13953
13954 @d start_def 1 /* command modifier for \&{def} */
13955 @d var_def 2 /* command modifier for \&{vardef} */
13956 @d end_def 0 /* command modifier for \&{enddef} */
13957 @d start_forever 1 /* command modifier for \&{forever} */
13958 @d end_for 0 /* command modifier for \&{endfor} */
13959
13960 @<Put each...@>=
13961 mp_primitive(mp, "def",macro_def,start_def);
13962 @:def_}{\&{def} primitive@>
13963 mp_primitive(mp, "vardef",macro_def,var_def);
13964 @:var_def_}{\&{vardef} primitive@>
13965 mp_primitive(mp, "primarydef",macro_def,secondary_primary_macro);
13966 @:primary_def_}{\&{primarydef} primitive@>
13967 mp_primitive(mp, "secondarydef",macro_def,tertiary_secondary_macro);
13968 @:secondary_def_}{\&{secondarydef} primitive@>
13969 mp_primitive(mp, "tertiarydef",macro_def,expression_tertiary_macro);
13970 @:tertiary_def_}{\&{tertiarydef} primitive@>
13971 mp_primitive(mp, "enddef",macro_def,end_def); mp->eqtb[frozen_end_def]=mp->eqtb[mp->cur_sym];
13972 @:end_def_}{\&{enddef} primitive@>
13973 @#
13974 mp_primitive(mp, "for",iteration,expr_base);
13975 @:for_}{\&{for} primitive@>
13976 mp_primitive(mp, "forsuffixes",iteration,suffix_base);
13977 @:for_suffixes_}{\&{forsuffixes} primitive@>
13978 mp_primitive(mp, "forever",iteration,start_forever);
13979 @:forever_}{\&{forever} primitive@>
13980 mp_primitive(mp, "endfor",iteration,end_for); mp->eqtb[frozen_end_for]=mp->eqtb[mp->cur_sym];
13981 @:end_for_}{\&{endfor} primitive@>
13982
13983 @ @<Cases of |print_cmd...@>=
13984 case macro_def:
13985   if ( m<=var_def ) {
13986     if ( m==start_def ) mp_print(mp, "def");
13987     else if ( m<start_def ) mp_print(mp, "enddef");
13988     else mp_print(mp, "vardef");
13989   } else if ( m==secondary_primary_macro ) { 
13990     mp_print(mp, "primarydef");
13991   } else if ( m==tertiary_secondary_macro ) { 
13992     mp_print(mp, "secondarydef");
13993   } else { 
13994     mp_print(mp, "tertiarydef");
13995   }
13996   break;
13997 case iteration: 
13998   if ( m<=start_forever ) {
13999     if ( m==start_forever ) mp_print(mp, "forever"); 
14000     else mp_print(mp, "endfor");
14001   } else if ( m==expr_base ) {
14002     mp_print(mp, "for"); 
14003   } else { 
14004     mp_print(mp, "forsuffixes");
14005   }
14006   break;
14007
14008 @ Different macro-absorbing operations have different syntaxes, but they
14009 also have a lot in common. There is a list of special symbols that are to
14010 be replaced by parameter tokens; there is a special command code that
14011 ends the definition; the quotation conventions are identical.  Therefore
14012 it makes sense to have most of the work done by a single subroutine. That
14013 subroutine is called |scan_toks|.
14014
14015 The first parameter to |scan_toks| is the command code that will
14016 terminate scanning (either |macro_def|, |loop_repeat|, or |iteration|).
14017
14018 The second parameter, |subst_list|, points to a (possibly empty) list
14019 of two-word nodes whose |info| and |value| fields specify symbol tokens
14020 before and after replacement. The list will be returned to free storage
14021 by |scan_toks|.
14022
14023 The third parameter is simply appended to the token list that is built.
14024 And the final parameter tells how many of the special operations
14025 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#} are to be replaced by suffix parameters.
14026 When such parameters are present, they are called \.{(SUFFIX0)},
14027 \.{(SUFFIX1)}, and \.{(SUFFIX2)}.
14028
14029 @c pointer mp_scan_toks (MP mp,command_code terminator, pointer 
14030   subst_list, pointer tail_end, small_number suffix_count) {
14031   pointer p; /* tail of the token list being built */
14032   pointer q; /* temporary for link management */
14033   integer balance; /* left delimiters minus right delimiters */
14034   p=hold_head; balance=1; link(hold_head)=null;
14035   while (1) { 
14036     get_t_next;
14037     if ( mp->cur_sym>0 ) {
14038       @<Substitute for |cur_sym|, if it's on the |subst_list|@>;
14039       if ( mp->cur_cmd==terminator ) {
14040         @<Adjust the balance; |break| if it's zero@>;
14041       } else if ( mp->cur_cmd==macro_special ) {
14042         @<Handle quoted symbols, \.{\#\AT!}, \.{\AT!}, or \.{\AT!\#}@>;
14043       }
14044     }
14045     link(p)=mp_cur_tok(mp); p=link(p);
14046   }
14047   link(p)=tail_end; mp_flush_node_list(mp, subst_list);
14048   return link(hold_head);
14049 }
14050
14051 @ @<Substitute for |cur_sym|...@>=
14052
14053   q=subst_list;
14054   while ( q!=null ) {
14055     if ( info(q)==mp->cur_sym ) {
14056       mp->cur_sym=value(q); mp->cur_cmd=relax; break;
14057     }
14058     q=link(q);
14059   }
14060 }
14061
14062 @ @<Adjust the balance; |break| if it's zero@>=
14063 if ( mp->cur_mod>0 ) {
14064   incr(balance);
14065 } else { 
14066   decr(balance);
14067   if ( balance==0 )
14068     break;
14069 }
14070
14071 @ Four commands are intended to be used only within macro texts: \&{quote},
14072 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#}. They are variants of a single command
14073 code called |macro_special|.
14074
14075 @d quote 0 /* |macro_special| modifier for \&{quote} */
14076 @d macro_prefix 1 /* |macro_special| modifier for \.{\#\AT!} */
14077 @d macro_at 2 /* |macro_special| modifier for \.{\AT!} */
14078 @d macro_suffix 3 /* |macro_special| modifier for \.{\AT!\#} */
14079
14080 @<Put each...@>=
14081 mp_primitive(mp, "quote",macro_special,quote);
14082 @:quote_}{\&{quote} primitive@>
14083 mp_primitive(mp, "#@@",macro_special,macro_prefix);
14084 @:]]]\#\AT!_}{\.{\#\AT!} primitive@>
14085 mp_primitive(mp, "@@",macro_special,macro_at);
14086 @:]]]\AT!_}{\.{\AT!} primitive@>
14087 mp_primitive(mp, "@@#",macro_special,macro_suffix);
14088 @:]]]\AT!\#_}{\.{\AT!\#} primitive@>
14089
14090 @ @<Cases of |print_cmd...@>=
14091 case macro_special: 
14092   switch (m) {
14093   case macro_prefix: mp_print(mp, "#@@"); break;
14094   case macro_at: mp_print_char(mp, '@@'); break;
14095   case macro_suffix: mp_print(mp, "@@#"); break;
14096   default: mp_print(mp, "quote"); break;
14097   }
14098   break;
14099
14100 @ @<Handle quoted...@>=
14101
14102   if ( mp->cur_mod==quote ) { get_t_next; } 
14103   else if ( mp->cur_mod<=suffix_count ) 
14104     mp->cur_sym=suffix_base-1+mp->cur_mod;
14105 }
14106
14107 @ Here is a routine that's used whenever a token will be redefined. If
14108 the user's token is unredefinable, the `|frozen_inaccessible|' token is
14109 substituted; the latter is redefinable but essentially impossible to use,
14110 hence \MP's tables won't get fouled up.
14111
14112 @c void mp_get_symbol (MP mp) { /* sets |cur_sym| to a safe symbol */
14113 RESTART: 
14114   get_t_next;
14115   if ( (mp->cur_sym==0)||(mp->cur_sym>frozen_inaccessible) ) {
14116     print_err("Missing symbolic token inserted");
14117 @.Missing symbolic token...@>
14118     help3("Sorry: You can\'t redefine a number, string, or expr.")
14119       ("I've inserted an inaccessible symbol so that your")
14120       ("definition will be completed without mixing me up too badly.");
14121     if ( mp->cur_sym>0 )
14122       mp->help_line[2]="Sorry: You can\'t redefine my error-recovery tokens.";
14123     else if ( mp->cur_cmd==string_token ) 
14124       delete_str_ref(mp->cur_mod);
14125     mp->cur_sym=frozen_inaccessible; mp_ins_error(mp); goto RESTART;
14126   }
14127 }
14128
14129 @ Before we actually redefine a symbolic token, we need to clear away its
14130 former value, if it was a variable. The following stronger version of
14131 |get_symbol| does that.
14132
14133 @c void mp_get_clear_symbol (MP mp) { 
14134   mp_get_symbol(mp); mp_clear_symbol(mp, mp->cur_sym,false);
14135 }
14136
14137 @ Here's another little subroutine; it checks that an equals sign
14138 or assignment sign comes along at the proper place in a macro definition.
14139
14140 @c void mp_check_equals (MP mp) { 
14141   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
14142      mp_missing_err(mp, "=");
14143 @.Missing `='@>
14144     help5("The next thing in this `def' should have been `=',")
14145       ("because I've already looked at the definition heading.")
14146       ("But don't worry; I'll pretend that an equals sign")
14147       ("was present. Everything from here to `enddef'")
14148       ("will be the replacement text of this macro.");
14149     mp_back_error(mp);
14150   }
14151 }
14152
14153 @ A \&{primarydef}, \&{secondarydef}, or \&{tertiarydef} is rather easily
14154 handled now that we have |scan_toks|.  In this case there are
14155 two parameters, which will be \.{EXPR0} and \.{EXPR1} (i.e.,
14156 |expr_base| and |expr_base+1|).
14157
14158 @c void mp_make_op_def (MP mp) {
14159   command_code m; /* the type of definition */
14160   pointer p,q,r; /* for list manipulation */
14161   m=mp->cur_mod;
14162   mp_get_symbol(mp); q=mp_get_node(mp, token_node_size);
14163   info(q)=mp->cur_sym; value(q)=expr_base;
14164   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym;
14165   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
14166   info(p)=mp->cur_sym; value(p)=expr_base+1; link(p)=q;
14167   get_t_next; mp_check_equals(mp);
14168   mp->scanner_status=op_defining; q=mp_get_avail(mp); ref_count(q)=null;
14169   r=mp_get_avail(mp); link(q)=r; info(r)=general_macro;
14170   link(r)=mp_scan_toks(mp, macro_def,p,null,0);
14171   mp->scanner_status=normal; eq_type(mp->warning_info)=m;
14172   equiv(mp->warning_info)=q; mp_get_x_next(mp);
14173 }
14174
14175 @ Parameters to macros are introduced by the keywords \&{expr},
14176 \&{suffix}, \&{text}, \&{primary}, \&{secondary}, and \&{tertiary}.
14177
14178 @<Put each...@>=
14179 mp_primitive(mp, "expr",param_type,expr_base);
14180 @:expr_}{\&{expr} primitive@>
14181 mp_primitive(mp, "suffix",param_type,suffix_base);
14182 @:suffix_}{\&{suffix} primitive@>
14183 mp_primitive(mp, "text",param_type,text_base);
14184 @:text_}{\&{text} primitive@>
14185 mp_primitive(mp, "primary",param_type,primary_macro);
14186 @:primary_}{\&{primary} primitive@>
14187 mp_primitive(mp, "secondary",param_type,secondary_macro);
14188 @:secondary_}{\&{secondary} primitive@>
14189 mp_primitive(mp, "tertiary",param_type,tertiary_macro);
14190 @:tertiary_}{\&{tertiary} primitive@>
14191
14192 @ @<Cases of |print_cmd...@>=
14193 case param_type:
14194   if ( m>=expr_base ) {
14195     if ( m==expr_base ) mp_print(mp, "expr");
14196     else if ( m==suffix_base ) mp_print(mp, "suffix");
14197     else mp_print(mp, "text");
14198   } else if ( m<secondary_macro ) {
14199     mp_print(mp, "primary");
14200   } else if ( m==secondary_macro ) {
14201     mp_print(mp, "secondary");
14202   } else {
14203     mp_print(mp, "tertiary");
14204   }
14205   break;
14206
14207 @ Let's turn next to the more complex processing associated with \&{def}
14208 and \&{vardef}. When the following procedure is called, |cur_mod|
14209 should be either |start_def| or |var_def|.
14210
14211 @c @<Declare the procedure called |check_delimiter|@>;
14212 @<Declare the function called |scan_declared_variable|@>;
14213 void mp_scan_def (MP mp) {
14214   int m; /* the type of definition */
14215   int n; /* the number of special suffix parameters */
14216   int k; /* the total number of parameters */
14217   int c; /* the kind of macro we're defining */
14218   pointer r; /* parameter-substitution list */
14219   pointer q; /* tail of the macro token list */
14220   pointer p; /* temporary storage */
14221   halfword base; /* |expr_base|, |suffix_base|, or |text_base| */
14222   pointer l_delim,r_delim; /* matching delimiters */
14223   m=mp->cur_mod; c=general_macro; link(hold_head)=null;
14224   q=mp_get_avail(mp); ref_count(q)=null; r=null;
14225   @<Scan the token or variable to be defined;
14226     set |n|, |scanner_status|, and |warning_info|@>;
14227   k=n;
14228   if ( mp->cur_cmd==left_delimiter ) {
14229     @<Absorb delimited parameters, putting them into lists |q| and |r|@>;
14230   }
14231   if ( mp->cur_cmd==param_type ) {
14232     @<Absorb undelimited parameters, putting them into list |r|@>;
14233   }
14234   mp_check_equals(mp);
14235   p=mp_get_avail(mp); info(p)=c; link(q)=p;
14236   @<Attach the replacement text to the tail of node |p|@>;
14237   mp->scanner_status=normal; mp_get_x_next(mp);
14238 }
14239
14240 @ We don't put `|frozen_end_group|' into the replacement text of
14241 a \&{vardef}, because the user may want to redefine `\.{endgroup}'.
14242
14243 @<Attach the replacement text to the tail of node |p|@>=
14244 if ( m==start_def ) {
14245   link(p)=mp_scan_toks(mp, macro_def,r,null,n);
14246 } else { 
14247   q=mp_get_avail(mp); info(q)=mp->bg_loc; link(p)=q;
14248   p=mp_get_avail(mp); info(p)=mp->eg_loc;
14249   link(q)=mp_scan_toks(mp, macro_def,r,p,n);
14250 }
14251 if ( mp->warning_info==bad_vardef ) 
14252   mp_flush_token_list(mp, value(bad_vardef))
14253
14254 @ @<Glob...@>=
14255 int bg_loc;
14256 int eg_loc; /* hash addresses of `\.{begingroup}' and `\.{endgroup}' */
14257
14258 @ @<Scan the token or variable to be defined;...@>=
14259 if ( m==start_def ) {
14260   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym; get_t_next;
14261   mp->scanner_status=op_defining; n=0;
14262   eq_type(mp->warning_info)=defined_macro; equiv(mp->warning_info)=q;
14263 } else { 
14264   p=mp_scan_declared_variable(mp);
14265   mp_flush_variable(mp, equiv(info(p)),link(p),true);
14266   mp->warning_info=mp_find_variable(mp, p); mp_flush_list(mp, p);
14267   if ( mp->warning_info==null ) @<Change to `\.{a bad variable}'@>;
14268   mp->scanner_status=var_defining; n=2;
14269   if ( mp->cur_cmd==macro_special ) if ( mp->cur_mod==macro_suffix ) {/* \.{\AT!\#} */
14270     n=3; get_t_next;
14271   }
14272   type(mp->warning_info)=mp_unsuffixed_macro-2+n; value(mp->warning_info)=q;
14273 } /* |mp_suffixed_macro=mp_unsuffixed_macro+1| */
14274
14275 @ @<Change to `\.{a bad variable}'@>=
14276
14277   print_err("This variable already starts with a macro");
14278 @.This variable already...@>
14279   help2("After `vardef a' you can\'t say `vardef a.b'.")
14280     ("So I'll have to discard this definition.");
14281   mp_error(mp); mp->warning_info=bad_vardef;
14282 }
14283
14284 @ @<Initialize table entries...@>=
14285 name_type(bad_vardef)=mp_root; link(bad_vardef)=frozen_bad_vardef;
14286 equiv(frozen_bad_vardef)=bad_vardef; eq_type(frozen_bad_vardef)=tag_token;
14287
14288 @ @<Absorb delimited parameters, putting them into lists |q| and |r|@>=
14289 do {  
14290   l_delim=mp->cur_sym; r_delim=mp->cur_mod; get_t_next;
14291   if ( (mp->cur_cmd==param_type)&&(mp->cur_mod>=expr_base) ) {
14292    base=mp->cur_mod;
14293   } else { 
14294     print_err("Missing parameter type; `expr' will be assumed");
14295 @.Missing parameter type@>
14296     help1("You should've had `expr' or `suffix' or `text' here.");
14297     mp_back_error(mp); base=expr_base;
14298   }
14299   @<Absorb parameter tokens for type |base|@>;
14300   mp_check_delimiter(mp, l_delim,r_delim);
14301   get_t_next;
14302 } while (mp->cur_cmd==left_delimiter)
14303
14304 @ @<Absorb parameter tokens for type |base|@>=
14305 do { 
14306   link(q)=mp_get_avail(mp); q=link(q); info(q)=base+k;
14307   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size); 
14308   value(p)=base+k; info(p)=mp->cur_sym;
14309   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14310 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
14311   incr(k); link(p)=r; r=p; get_t_next;
14312 } while (mp->cur_cmd==comma)
14313
14314 @ @<Absorb undelimited parameters, putting them into list |r|@>=
14315
14316   p=mp_get_node(mp, token_node_size);
14317   if ( mp->cur_mod<expr_base ) {
14318     c=mp->cur_mod; value(p)=expr_base+k;
14319   } else { 
14320     value(p)=mp->cur_mod+k;
14321     if ( mp->cur_mod==expr_base ) c=expr_macro;
14322     else if ( mp->cur_mod==suffix_base ) c=suffix_macro;
14323     else c=text_macro;
14324   }
14325   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14326   incr(k); mp_get_symbol(mp); info(p)=mp->cur_sym; link(p)=r; r=p; get_t_next;
14327   if ( c==expr_macro ) if ( mp->cur_cmd==of_token ) {
14328     c=of_macro; p=mp_get_node(mp, token_node_size);
14329     if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14330     value(p)=expr_base+k; mp_get_symbol(mp); info(p)=mp->cur_sym;
14331     link(p)=r; r=p; get_t_next;
14332   }
14333 }
14334
14335 @* \[32] Expanding the next token.
14336 Only a few command codes |<min_command| can possibly be returned by
14337 |get_t_next|; in increasing order, they are
14338 |if_test|, |fi_or_else|, |input|, |iteration|, |repeat_loop|,
14339 |exit_test|, |relax|, |scan_tokens|, |expand_after|, and |defined_macro|.
14340
14341 \MP\ usually gets the next token of input by saying |get_x_next|. This is
14342 like |get_t_next| except that it keeps getting more tokens until
14343 finding |cur_cmd>=min_command|. In other words, |get_x_next| expands
14344 macros and removes conditionals or iterations or input instructions that
14345 might be present.
14346
14347 It follows that |get_x_next| might invoke itself recursively. In fact,
14348 there is massive recursion, since macro expansion can involve the
14349 scanning of arbitrarily complex expressions, which in turn involve
14350 macro expansion and conditionals, etc.
14351 @^recursion@>
14352
14353 Therefore it's necessary to declare a whole bunch of |forward|
14354 procedures at this point, and to insert some other procedures
14355 that will be invoked by |get_x_next|.
14356
14357 @<Declarations@>= 
14358 void mp_scan_primary (MP mp);
14359 void mp_scan_secondary (MP mp);
14360 void mp_scan_tertiary (MP mp);
14361 void mp_scan_expression (MP mp);
14362 void mp_scan_suffix (MP mp);
14363 @<Declare the procedure called |macro_call|@>;
14364 void mp_get_boolean (MP mp);
14365 void mp_pass_text (MP mp);
14366 void mp_conditional (MP mp);
14367 void mp_start_input (MP mp);
14368 void mp_begin_iteration (MP mp);
14369 void mp_resume_iteration (MP mp);
14370 void mp_stop_iteration (MP mp);
14371
14372 @ An auxiliary subroutine called |expand| is used by |get_x_next|
14373 when it has to do exotic expansion commands.
14374
14375 @c void mp_expand (MP mp) {
14376   pointer p; /* for list manipulation */
14377   size_t k; /* something that we hope is |<=buf_size| */
14378   pool_pointer j; /* index into |str_pool| */
14379   if ( mp->internal[tracing_commands]>unity ) 
14380     if ( mp->cur_cmd!=defined_macro )
14381       show_cur_cmd_mod;
14382   switch (mp->cur_cmd)  {
14383   case if_test:
14384     mp_conditional(mp); /* this procedure is discussed in Part 36 below */
14385     break;
14386   case fi_or_else:
14387     @<Terminate the current conditional and skip to \&{fi}@>;
14388     break;
14389   case input:
14390     @<Initiate or terminate input from a file@>;
14391     break;
14392   case iteration:
14393     if ( mp->cur_mod==end_for ) {
14394       @<Scold the user for having an extra \&{endfor}@>;
14395     } else {
14396       mp_begin_iteration(mp); /* this procedure is discussed in Part 37 below */
14397     }
14398     break;
14399   case repeat_loop: 
14400     @<Repeat a loop@>;
14401     break;
14402   case exit_test: 
14403     @<Exit a loop if the proper time has come@>;
14404     break;
14405   case relax: 
14406     break;
14407   case expand_after: 
14408     @<Expand the token after the next token@>;
14409     break;
14410   case scan_tokens: 
14411     @<Put a string into the input buffer@>;
14412     break;
14413   case defined_macro:
14414    mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14415    break;
14416   }; /* there are no other cases */
14417 };
14418
14419 @ @<Scold the user...@>=
14420
14421   print_err("Extra `endfor'");
14422 @.Extra `endfor'@>
14423   help2("I'm not currently working on a for loop,")
14424     ("so I had better not try to end anything.");
14425   mp_error(mp);
14426 }
14427
14428 @ The processing of \&{input} involves the |start_input| subroutine,
14429 which will be declared later; the processing of \&{endinput} is trivial.
14430
14431 @<Put each...@>=
14432 mp_primitive(mp, "input",input,0);
14433 @:input_}{\&{input} primitive@>
14434 mp_primitive(mp, "endinput",input,1);
14435 @:end_input_}{\&{endinput} primitive@>
14436
14437 @ @<Cases of |print_cmd_mod|...@>=
14438 case input: 
14439   if ( m==0 ) mp_print(mp, "input");
14440   else mp_print(mp, "endinput");
14441   break;
14442
14443 @ @<Initiate or terminate input...@>=
14444 if ( mp->cur_mod>0 ) mp->force_eof=true;
14445 else mp_start_input(mp)
14446
14447 @ We'll discuss the complicated parts of loop operations later. For now
14448 it suffices to know that there's a global variable called |loop_ptr|
14449 that will be |null| if no loop is in progress.
14450
14451 @<Repeat a loop@>=
14452 { while ( token_state &&(loc==null) ) 
14453     mp_end_token_list(mp); /* conserve stack space */
14454   if ( mp->loop_ptr==null ) {
14455     print_err("Lost loop");
14456 @.Lost loop@>
14457     help2("I'm confused; after exiting from a loop, I still seem")
14458       ("to want to repeat it. I'll try to forget the problem.");
14459     mp_error(mp);
14460   } else {
14461     mp_resume_iteration(mp); /* this procedure is in Part 37 below */
14462   }
14463 }
14464
14465 @ @<Exit a loop if the proper time has come@>=
14466 { mp_get_boolean(mp);
14467   if ( mp->internal[tracing_commands]>unity ) 
14468     mp_show_cmd_mod(mp, nullary,mp->cur_exp);
14469   if ( mp->cur_exp==true_code ) {
14470     if ( mp->loop_ptr==null ) {
14471       print_err("No loop is in progress");
14472 @.No loop is in progress@>
14473       help1("Why say `exitif' when there's nothing to exit from?");
14474       if ( mp->cur_cmd==semicolon ) mp_error(mp); else mp_back_error(mp);
14475     } else {
14476      @<Exit prematurely from an iteration@>;
14477     }
14478   } else if ( mp->cur_cmd!=semicolon ) {
14479     mp_missing_err(mp, ";");
14480 @.Missing `;'@>
14481     help2("After `exitif <boolean exp>' I expect to see a semicolon.")
14482     ("I shall pretend that one was there."); mp_back_error(mp);
14483   }
14484 }
14485
14486 @ Here we use the fact that |forever_text| is the only |token_type| that
14487 is less than |loop_text|.
14488
14489 @<Exit prematurely...@>=
14490 { p=null;
14491   do {  
14492     if ( file_state ) {
14493       mp_end_file_reading(mp);
14494     } else { 
14495       if ( token_type<=loop_text ) p=start;
14496       mp_end_token_list(mp);
14497     }
14498   } while (p==null);
14499   if ( p!=info(mp->loop_ptr) ) mp_fatal_error(mp, "*** (loop confusion)");
14500 @.loop confusion@>
14501   mp_stop_iteration(mp); /* this procedure is in Part 34 below */
14502 }
14503
14504 @ @<Expand the token after the next token@>=
14505 { get_t_next;
14506   p=mp_cur_tok(mp); get_t_next;
14507   if ( mp->cur_cmd<min_command ) mp_expand(mp); 
14508   else mp_back_input(mp);
14509   back_list(p);
14510 }
14511
14512 @ @<Put a string into the input buffer@>=
14513 { mp_get_x_next(mp); mp_scan_primary(mp);
14514   if ( mp->cur_type!=mp_string_type ) {
14515     mp_disp_err(mp, null,"Not a string");
14516 @.Not a string@>
14517     help2("I'm going to flush this expression, since")
14518        ("scantokens should be followed by a known string.");
14519     mp_put_get_flush_error(mp, 0);
14520   } else { 
14521     mp_back_input(mp);
14522     if ( length(mp->cur_exp)>0 )
14523        @<Pretend we're reading a new one-line file@>;
14524   }
14525 }
14526
14527 @ @<Pretend we're reading a new one-line file@>=
14528 { mp_begin_file_reading(mp); name=is_scantok;
14529   k=mp->first+length(mp->cur_exp);
14530   if ( k>=mp->max_buf_stack ) {
14531     while ( k>=mp->buf_size ) {
14532       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
14533     }
14534     mp->max_buf_stack=k+1;
14535   }
14536   j=mp->str_start[mp->cur_exp]; limit=k;
14537   while ( mp->first<(size_t)limit ) {
14538     mp->buffer[mp->first]=mp->str_pool[j]; incr(j); incr(mp->first);
14539   }
14540   mp->buffer[limit]='%'; mp->first=limit+1; loc=start; 
14541   mp_flush_cur_exp(mp, 0);
14542 }
14543
14544 @ Here finally is |get_x_next|.
14545
14546 The expression scanning routines to be considered later
14547 communicate via the global quantities |cur_type| and |cur_exp|;
14548 we must be very careful to save and restore these quantities while
14549 macros are being expanded.
14550 @^inner loop@>
14551
14552 @<Declarations@>=
14553 void mp_get_x_next (MP mp);
14554
14555 @ @c void mp_get_x_next (MP mp) {
14556   pointer save_exp; /* a capsule to save |cur_type| and |cur_exp| */
14557   get_t_next;
14558   if ( mp->cur_cmd<min_command ) {
14559     save_exp=mp_stash_cur_exp(mp);
14560     do {  
14561       if ( mp->cur_cmd==defined_macro ) 
14562         mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14563       else 
14564         mp_expand(mp);
14565       get_t_next;
14566      } while (mp->cur_cmd<min_command);
14567      mp_unstash_cur_exp(mp, save_exp); /* that restores |cur_type| and |cur_exp| */
14568   }
14569 }
14570
14571 @ Now let's consider the |macro_call| procedure, which is used to start up
14572 all user-defined macros. Since the arguments to a macro might be expressions,
14573 |macro_call| is recursive.
14574 @^recursion@>
14575
14576 The first parameter to |macro_call| points to the reference count of the
14577 token list that defines the macro. The second parameter contains any
14578 arguments that have already been parsed (see below).  The third parameter
14579 points to the symbolic token that names the macro. If the third parameter
14580 is |null|, the macro was defined by \&{vardef}, so its name can be
14581 reconstructed from the prefix and ``at'' arguments found within the
14582 second parameter.
14583
14584 What is this second parameter? It's simply a linked list of one-word items,
14585 whose |info| fields point to the arguments. In other words, if |arg_list=null|,
14586 no arguments have been scanned yet; otherwise |info(arg_list)| points to
14587 the first scanned argument, and |link(arg_list)| points to the list of
14588 further arguments (if any).
14589
14590 Arguments of type \&{expr} are so-called capsules, which we will
14591 discuss later when we concentrate on expressions; they can be
14592 recognized easily because their |link| field is |void|. Arguments of type
14593 \&{suffix} and \&{text} are token lists without reference counts.
14594
14595 @ After argument scanning is complete, the arguments are moved to the
14596 |param_stack|. (They can't be put on that stack any sooner, because
14597 the stack is growing and shrinking in unpredictable ways as more arguments
14598 are being acquired.)  Then the macro body is fed to the scanner; i.e.,
14599 the replacement text of the macro is placed at the top of the \MP's
14600 input stack, so that |get_t_next| will proceed to read it next.
14601
14602 @<Declare the procedure called |macro_call|@>=
14603 @<Declare the procedure called |print_macro_name|@>;
14604 @<Declare the procedure called |print_arg|@>;
14605 @<Declare the procedure called |scan_text_arg|@>;
14606 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14607                     pointer macro_name) ;
14608
14609 @ @c
14610 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14611                     pointer macro_name) {
14612   /* invokes a user-defined control sequence */
14613   pointer r; /* current node in the macro's token list */
14614   pointer p,q; /* for list manipulation */
14615   integer n; /* the number of arguments */
14616   pointer tail = 0; /* tail of the argument list */
14617   pointer l_delim=0,r_delim=0; /* a delimiter pair */
14618   r=link(def_ref); add_mac_ref(def_ref);
14619   if ( arg_list==null ) {
14620     n=0;
14621   } else {
14622    @<Determine the number |n| of arguments already supplied,
14623     and set |tail| to the tail of |arg_list|@>;
14624   }
14625   if ( mp->internal[tracing_macros]>0 ) {
14626     @<Show the text of the macro being expanded, and the existing arguments@>;
14627   }
14628   @<Scan the remaining arguments, if any; set |r| to the first token
14629     of the replacement text@>;
14630   @<Feed the arguments and replacement text to the scanner@>;
14631 }
14632
14633 @ @<Show the text of the macro...@>=
14634 mp_begin_diagnostic(mp); mp_print_ln(mp); 
14635 mp_print_macro_name(mp, arg_list,macro_name);
14636 if ( n==3 ) mp_print(mp, "@@#"); /* indicate a suffixed macro */
14637 mp_show_macro(mp, def_ref,null,100000);
14638 if ( arg_list!=null ) {
14639   n=0; p=arg_list;
14640   do {  
14641     q=info(p);
14642     mp_print_arg(mp, q,n,0);
14643     incr(n); p=link(p);
14644   } while (p!=null);
14645 }
14646 mp_end_diagnostic(mp, false)
14647
14648
14649 @ @<Declare the procedure called |print_macro_name|@>=
14650 void mp_print_macro_name (MP mp,pointer a, pointer n);
14651
14652 @ @c
14653 void mp_print_macro_name (MP mp,pointer a, pointer n) {
14654   pointer p,q; /* they traverse the first part of |a| */
14655   if ( n!=null ) {
14656     mp_print_text(n);
14657   } else  { 
14658     p=info(a);
14659     if ( p==null ) {
14660       mp_print_text(info(info(link(a))));
14661     } else { 
14662       q=p;
14663       while ( link(q)!=null ) q=link(q);
14664       link(q)=info(link(a));
14665       mp_show_token_list(mp, p,null,1000,0);
14666       link(q)=null;
14667     }
14668   }
14669 }
14670
14671 @ @<Declare the procedure called |print_arg|@>=
14672 void mp_print_arg (MP mp,pointer q, integer n, pointer b) ;
14673
14674 @ @c
14675 void mp_print_arg (MP mp,pointer q, integer n, pointer b) {
14676   if ( link(q)==diov ) mp_print_nl(mp, "(EXPR");
14677   else if ( (b<text_base)&&(b!=text_macro) ) mp_print_nl(mp, "(SUFFIX");
14678   else mp_print_nl(mp, "(TEXT");
14679   mp_print_int(mp, n); mp_print(mp, ")<-");
14680   if ( link(q)==diov ) mp_print_exp(mp, q,1);
14681   else mp_show_token_list(mp, q,null,1000,0);
14682 }
14683
14684 @ @<Determine the number |n| of arguments already supplied...@>=
14685 {  
14686   n=1; tail=arg_list;
14687   while ( link(tail)!=null ) { 
14688     incr(n); tail=link(tail);
14689   }
14690 }
14691
14692 @ @<Scan the remaining arguments, if any; set |r|...@>=
14693 mp->cur_cmd=comma+1; /* anything |<>comma| will do */
14694 while ( info(r)>=expr_base ) { 
14695   @<Scan the delimited argument represented by |info(r)|@>;
14696   r=link(r);
14697 };
14698 if ( mp->cur_cmd==comma ) {
14699   print_err("Too many arguments to ");
14700 @.Too many arguments...@>
14701   mp_print_macro_name(mp, arg_list,macro_name); mp_print_char(mp, ';');
14702   mp_print_nl(mp, "  Missing `"); mp_print_text(r_delim);
14703 @.Missing `)'...@>
14704   mp_print(mp, "' has been inserted");
14705   help3("I'm going to assume that the comma I just read was a")
14706    ("right delimiter, and then I'll begin expanding the macro.")
14707    ("You might want to delete some tokens before continuing.");
14708   mp_error(mp);
14709 }
14710 if ( info(r)!=general_macro ) {
14711   @<Scan undelimited argument(s)@>;
14712 }
14713 r=link(r)
14714
14715 @ At this point, the reader will find it advisable to review the explanation
14716 of token list format that was presented earlier, paying special attention to
14717 the conventions that apply only at the beginning of a macro's token list.
14718
14719 On the other hand, the reader will have to take the expression-parsing
14720 aspects of the following program on faith; we will explain |cur_type|
14721 and |cur_exp| later. (Several things in this program depend on each other,
14722 and it's necessary to jump into the circle somewhere.)
14723
14724 @<Scan the delimited argument represented by |info(r)|@>=
14725 if ( mp->cur_cmd!=comma ) {
14726   mp_get_x_next(mp);
14727   if ( mp->cur_cmd!=left_delimiter ) {
14728     print_err("Missing argument to ");
14729 @.Missing argument...@>
14730     mp_print_macro_name(mp, arg_list,macro_name);
14731     help3("That macro has more parameters than you thought.")
14732      ("I'll continue by pretending that each missing argument")
14733      ("is either zero or null.");
14734     if ( info(r)>=suffix_base ) {
14735       mp->cur_exp=null; mp->cur_type=mp_token_list;
14736     } else { 
14737       mp->cur_exp=0; mp->cur_type=mp_known;
14738     }
14739     mp_back_error(mp); mp->cur_cmd=right_delimiter; 
14740     goto FOUND;
14741   }
14742   l_delim=mp->cur_sym; r_delim=mp->cur_mod;
14743 }
14744 @<Scan the argument represented by |info(r)|@>;
14745 if ( mp->cur_cmd!=comma ) 
14746   @<Check that the proper right delimiter was present@>;
14747 FOUND:  
14748 @<Append the current expression to |arg_list|@>
14749
14750 @ @<Check that the proper right delim...@>=
14751 if ( (mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
14752   if ( info(link(r))>=expr_base ) {
14753     mp_missing_err(mp, ",");
14754 @.Missing `,'@>
14755     help3("I've finished reading a macro argument and am about to")
14756       ("read another; the arguments weren't delimited correctly.")
14757        ("You might want to delete some tokens before continuing.");
14758     mp_back_error(mp); mp->cur_cmd=comma;
14759   } else { 
14760     mp_missing_err(mp, str(text(r_delim)));
14761 @.Missing `)'@>
14762     help2("I've gotten to the end of the macro parameter list.")
14763        ("You might want to delete some tokens before continuing.");
14764     mp_back_error(mp);
14765   }
14766 }
14767
14768 @ A \&{suffix} or \&{text} parameter will be have been scanned as
14769 a token list pointed to by |cur_exp|, in which case we will have
14770 |cur_type=token_list|.
14771
14772 @<Append the current expression to |arg_list|@>=
14773
14774   p=mp_get_avail(mp);
14775   if ( mp->cur_type==mp_token_list ) info(p)=mp->cur_exp;
14776   else info(p)=mp_stash_cur_exp(mp);
14777   if ( mp->internal[tracing_macros]>0 ) {
14778     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,info(r)); 
14779     mp_end_diagnostic(mp, false);
14780   }
14781   if ( arg_list==null ) arg_list=p;
14782   else link(tail)=p;
14783   tail=p; incr(n);
14784 }
14785
14786 @ @<Scan the argument represented by |info(r)|@>=
14787 if ( info(r)>=text_base ) {
14788   mp_scan_text_arg(mp, l_delim,r_delim);
14789 } else { 
14790   mp_get_x_next(mp);
14791   if ( info(r)>=suffix_base ) mp_scan_suffix(mp);
14792   else mp_scan_expression(mp);
14793 }
14794
14795 @ The parameters to |scan_text_arg| are either a pair of delimiters
14796 or zero; the latter case is for undelimited text arguments, which
14797 end with the first semicolon or \&{endgroup} or \&{end} that is not
14798 contained in a group.
14799
14800 @<Declare the procedure called |scan_text_arg|@>=
14801 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) ;
14802
14803 @ @c
14804 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) {
14805   integer balance; /* excess of |l_delim| over |r_delim| */
14806   pointer p; /* list tail */
14807   mp->warning_info=l_delim; mp->scanner_status=absorbing;
14808   p=hold_head; balance=1; link(hold_head)=null;
14809   while (1)  { 
14810     get_t_next;
14811     if ( l_delim==0 ) {
14812       @<Adjust the balance for an undelimited argument; |break| if done@>;
14813     } else {
14814           @<Adjust the balance for a delimited argument; |break| if done@>;
14815     }
14816     link(p)=mp_cur_tok(mp); p=link(p);
14817   }
14818   mp->cur_exp=link(hold_head); mp->cur_type=mp_token_list;
14819   mp->scanner_status=normal;
14820 };
14821
14822 @ @<Adjust the balance for a delimited argument...@>=
14823 if ( mp->cur_cmd==right_delimiter ) { 
14824   if ( mp->cur_mod==l_delim ) { 
14825     decr(balance);
14826     if ( balance==0 ) break;
14827   }
14828 } else if ( mp->cur_cmd==left_delimiter ) {
14829   if ( mp->cur_mod==r_delim ) incr(balance);
14830 }
14831
14832 @ @<Adjust the balance for an undelimited...@>=
14833 if ( end_of_statement ) { /* |cur_cmd=semicolon|, |end_group|, or |stop| */
14834   if ( balance==1 ) { break; }
14835   else  { if ( mp->cur_cmd==end_group ) decr(balance); }
14836 } else if ( mp->cur_cmd==begin_group ) { 
14837   incr(balance); 
14838 }
14839
14840 @ @<Scan undelimited argument(s)@>=
14841
14842   if ( info(r)<text_macro ) {
14843     mp_get_x_next(mp);
14844     if ( info(r)!=suffix_macro ) {
14845       if ( (mp->cur_cmd==equals)||(mp->cur_cmd==assignment) ) mp_get_x_next(mp);
14846     }
14847   }
14848   switch (info(r)) {
14849   case primary_macro:mp_scan_primary(mp); break;
14850   case secondary_macro:mp_scan_secondary(mp); break;
14851   case tertiary_macro:mp_scan_tertiary(mp); break;
14852   case expr_macro:mp_scan_expression(mp); break;
14853   case of_macro:
14854     @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>;
14855     break;
14856   case suffix_macro:
14857     @<Scan a suffix with optional delimiters@>;
14858     break;
14859   case text_macro:mp_scan_text_arg(mp, 0,0); break;
14860   } /* there are no other cases */
14861   mp_back_input(mp); 
14862   @<Append the current expression to |arg_list|@>;
14863 }
14864
14865 @ @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>=
14866
14867   mp_scan_expression(mp); p=mp_get_avail(mp); info(p)=mp_stash_cur_exp(mp);
14868   if ( mp->internal[tracing_macros]>0 ) { 
14869     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,0); 
14870     mp_end_diagnostic(mp, false);
14871   }
14872   if ( arg_list==null ) arg_list=p; else link(tail)=p;
14873   tail=p;incr(n);
14874   if ( mp->cur_cmd!=of_token ) {
14875     mp_missing_err(mp, "of"); mp_print(mp, " for ");
14876 @.Missing `of'@>
14877     mp_print_macro_name(mp, arg_list,macro_name);
14878     help1("I've got the first argument; will look now for the other.");
14879     mp_back_error(mp);
14880   }
14881   mp_get_x_next(mp); mp_scan_primary(mp);
14882 }
14883
14884 @ @<Scan a suffix with optional delimiters@>=
14885
14886   if ( mp->cur_cmd!=left_delimiter ) {
14887     l_delim=null;
14888   } else { 
14889     l_delim=mp->cur_sym; r_delim=mp->cur_mod; mp_get_x_next(mp);
14890   };
14891   mp_scan_suffix(mp);
14892   if ( l_delim!=null ) {
14893     if ((mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
14894       mp_missing_err(mp, str(text(r_delim)));
14895 @.Missing `)'@>
14896       help2("I've gotten to the end of the macro parameter list.")
14897          ("You might want to delete some tokens before continuing.");
14898       mp_back_error(mp);
14899     }
14900     mp_get_x_next(mp);
14901   }
14902 }
14903
14904 @ Before we put a new token list on the input stack, it is wise to clean off
14905 all token lists that have recently been depleted. Then a user macro that ends
14906 with a call to itself will not require unbounded stack space.
14907
14908 @<Feed the arguments and replacement text to the scanner@>=
14909 while ( token_state &&(loc==null) ) mp_end_token_list(mp); /* conserve stack space */
14910 if ( mp->param_ptr+n>mp->max_param_stack ) {
14911   mp->max_param_stack=mp->param_ptr+n;
14912   if ( mp->max_param_stack>mp->param_size )
14913     mp_overflow(mp, "parameter stack size",mp->param_size);
14914 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
14915 }
14916 mp_begin_token_list(mp, def_ref,macro); name=macro_name; loc=r;
14917 if ( n>0 ) {
14918   p=arg_list;
14919   do {  
14920    mp->param_stack[mp->param_ptr]=info(p); incr(mp->param_ptr); p=link(p);
14921   } while (p!=null);
14922   mp_flush_list(mp, arg_list);
14923 }
14924
14925 @ It's sometimes necessary to put a single argument onto |param_stack|.
14926 The |stack_argument| subroutine does this.
14927
14928 @c void mp_stack_argument (MP mp,pointer p) { 
14929   if ( mp->param_ptr==mp->max_param_stack ) {
14930     incr(mp->max_param_stack);
14931     if ( mp->max_param_stack>mp->param_size )
14932       mp_overflow(mp, "parameter stack size",mp->param_size);
14933 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
14934   }
14935   mp->param_stack[mp->param_ptr]=p; incr(mp->param_ptr);
14936 }
14937
14938 @* \[33] Conditional processing.
14939 Let's consider now the way \&{if} commands are handled.
14940
14941 Conditions can be inside conditions, and this nesting has a stack
14942 that is independent of other stacks.
14943 Four global variables represent the top of the condition stack:
14944 |cond_ptr| points to pushed-down entries, if~any; |cur_if| tells whether
14945 we are processing \&{if} or \&{elseif}; |if_limit| specifies
14946 the largest code of a |fi_or_else| command that is syntactically legal;
14947 and |if_line| is the line number at which the current conditional began.
14948
14949 If no conditions are currently in progress, the condition stack has the
14950 special state |cond_ptr=null|, |if_limit=normal|, |cur_if=0|, |if_line=0|.
14951 Otherwise |cond_ptr| points to a two-word node; the |type|, |name_type|, and
14952 |link| fields of the first word contain |if_limit|, |cur_if|, and
14953 |cond_ptr| at the next level, and the second word contains the
14954 corresponding |if_line|.
14955
14956 @d if_node_size 2 /* number of words in stack entry for conditionals */
14957 @d if_line_field(A) mp->mem[(A)+1].cint
14958 @d if_code 1 /* code for \&{if} being evaluated */
14959 @d fi_code 2 /* code for \&{fi} */
14960 @d else_code 3 /* code for \&{else} */
14961 @d else_if_code 4 /* code for \&{elseif} */
14962
14963 @<Glob...@>=
14964 pointer cond_ptr; /* top of the condition stack */
14965 integer if_limit; /* upper bound on |fi_or_else| codes */
14966 small_number cur_if; /* type of conditional being worked on */
14967 integer if_line; /* line where that conditional began */
14968
14969 @ @<Set init...@>=
14970 mp->cond_ptr=null; mp->if_limit=normal; mp->cur_if=0; mp->if_line=0;
14971
14972 @ @<Put each...@>=
14973 mp_primitive(mp, "if",if_test,if_code);
14974 @:if_}{\&{if} primitive@>
14975 mp_primitive(mp, "fi",fi_or_else,fi_code); mp->eqtb[frozen_fi]=mp->eqtb[mp->cur_sym];
14976 @:fi_}{\&{fi} primitive@>
14977 mp_primitive(mp, "else",fi_or_else,else_code);
14978 @:else_}{\&{else} primitive@>
14979 mp_primitive(mp, "elseif",fi_or_else,else_if_code);
14980 @:else_if_}{\&{elseif} primitive@>
14981
14982 @ @<Cases of |print_cmd_mod|...@>=
14983 case if_test:
14984 case fi_or_else: 
14985   switch (m) {
14986   case if_code:mp_print(mp, "if"); break;
14987   case fi_code:mp_print(mp, "fi");  break;
14988   case else_code:mp_print(mp, "else"); break;
14989   default: mp_print(mp, "elseif"); break;
14990   }
14991   break;
14992
14993 @ Here is a procedure that ignores text until coming to an \&{elseif},
14994 \&{else}, or \&{fi} at level zero of $\&{if}\ldots\&{fi}$
14995 nesting. After it has acted, |cur_mod| will indicate the token that
14996 was found.
14997
14998 \MP's smallest two command codes are |if_test| and |fi_or_else|; this
14999 makes the skipping process a bit simpler.
15000
15001 @c 
15002 void mp_pass_text (MP mp) {
15003   integer l = 0;
15004   mp->scanner_status=skipping;
15005   mp->warning_info=mp_true_line(mp);
15006   while (1)  { 
15007     get_t_next;
15008     if ( mp->cur_cmd<=fi_or_else ) {
15009       if ( mp->cur_cmd<fi_or_else ) {
15010         incr(l);
15011       } else { 
15012         if ( l==0 ) break;
15013         if ( mp->cur_mod==fi_code ) decr(l);
15014       }
15015     } else {
15016       @<Decrease the string reference count,
15017        if the current token is a string@>;
15018     }
15019   }
15020   mp->scanner_status=normal;
15021 }
15022
15023 @ @<Decrease the string reference count...@>=
15024 if ( mp->cur_cmd==string_token ) { delete_str_ref(mp->cur_mod); }
15025
15026 @ When we begin to process a new \&{if}, we set |if_limit:=if_code|; then
15027 if \&{elseif} or \&{else} or \&{fi} occurs before the current \&{if}
15028 condition has been evaluated, a colon will be inserted.
15029 A construction like `\.{if fi}' would otherwise get \MP\ confused.
15030
15031 @<Push the condition stack@>=
15032 { p=mp_get_node(mp, if_node_size); link(p)=mp->cond_ptr; type(p)=mp->if_limit;
15033   name_type(p)=mp->cur_if; if_line_field(p)=mp->if_line;
15034   mp->cond_ptr=p; mp->if_limit=if_code; mp->if_line=mp_true_line(mp); 
15035   mp->cur_if=if_code;
15036 }
15037
15038 @ @<Pop the condition stack@>=
15039 { p=mp->cond_ptr; mp->if_line=if_line_field(p);
15040   mp->cur_if=name_type(p); mp->if_limit=type(p); mp->cond_ptr=link(p);
15041   mp_free_node(mp, p,if_node_size);
15042 }
15043
15044 @ Here's a procedure that changes the |if_limit| code corresponding to
15045 a given value of |cond_ptr|.
15046
15047 @c void mp_change_if_limit (MP mp,small_number l, pointer p) {
15048   pointer q;
15049   if ( p==mp->cond_ptr ) {
15050     mp->if_limit=l; /* that's the easy case */
15051   } else  { 
15052     q=mp->cond_ptr;
15053     while (1) { 
15054       if ( q==null ) mp_confusion(mp, "if");
15055 @:this can't happen if}{\quad if@>
15056       if ( link(q)==p ) { 
15057         type(q)=l; return;
15058       }
15059       q=link(q);
15060     }
15061   }
15062 }
15063
15064 @ The user is supposed to put colons into the proper parts of conditional
15065 statements. Therefore, \MP\ has to check for their presence.
15066
15067 @c 
15068 void mp_check_colon (MP mp) { 
15069   if ( mp->cur_cmd!=colon ) { 
15070     mp_missing_err(mp, ":");
15071 @.Missing `:'@>
15072     help2("There should've been a colon after the condition.")
15073          ("I shall pretend that one was there.");;
15074     mp_back_error(mp);
15075   }
15076 }
15077
15078 @ A condition is started when the |get_x_next| procedure encounters
15079 an |if_test| command; in that case |get_x_next| calls |conditional|,
15080 which is a recursive procedure.
15081 @^recursion@>
15082
15083 @c void mp_conditional (MP mp) {
15084   pointer save_cond_ptr; /* |cond_ptr| corresponding to this conditional */
15085   int new_if_limit; /* future value of |if_limit| */
15086   pointer p; /* temporary register */
15087   @<Push the condition stack@>; 
15088   save_cond_ptr=mp->cond_ptr;
15089 RESWITCH: 
15090   mp_get_boolean(mp); new_if_limit=else_if_code;
15091   if ( mp->internal[tracing_commands]>unity ) {
15092     @<Display the boolean value of |cur_exp|@>;
15093   }
15094 FOUND: 
15095   mp_check_colon(mp);
15096   if ( mp->cur_exp==true_code ) {
15097     mp_change_if_limit(mp, new_if_limit,save_cond_ptr);
15098     return; /* wait for \&{elseif}, \&{else}, or \&{fi} */
15099   };
15100   @<Skip to \&{elseif} or \&{else} or \&{fi}, then |goto done|@>;
15101 DONE: 
15102   mp->cur_if=mp->cur_mod; mp->if_line=mp_true_line(mp);
15103   if ( mp->cur_mod==fi_code ) {
15104     @<Pop the condition stack@>
15105   } else if ( mp->cur_mod==else_if_code ) {
15106     goto RESWITCH;
15107   } else  { 
15108     mp->cur_exp=true_code; new_if_limit=fi_code; mp_get_x_next(mp); 
15109     goto FOUND;
15110   }
15111 }
15112
15113 @ In a construction like `\&{if} \&{if} \&{true}: $0=1$: \\{foo}
15114 \&{else}: \\{bar} \&{fi}', the first \&{else}
15115 that we come to after learning that the \&{if} is false is not the
15116 \&{else} we're looking for. Hence the following curious logic is needed.
15117
15118 @<Skip to \&{elseif}...@>=
15119 while (1) { 
15120   mp_pass_text(mp);
15121   if ( mp->cond_ptr==save_cond_ptr ) goto DONE;
15122   else if ( mp->cur_mod==fi_code ) @<Pop the condition stack@>;
15123 }
15124
15125
15126 @ @<Display the boolean value...@>=
15127 { mp_begin_diagnostic(mp);
15128   if ( mp->cur_exp==true_code ) mp_print(mp, "{true}");
15129   else mp_print(mp, "{false}");
15130   mp_end_diagnostic(mp, false);
15131 }
15132
15133 @ The processing of conditionals is complete except for the following
15134 code, which is actually part of |get_x_next|. It comes into play when
15135 \&{elseif}, \&{else}, or \&{fi} is scanned.
15136
15137 @<Terminate the current conditional and skip to \&{fi}@>=
15138 if ( mp->cur_mod>mp->if_limit ) {
15139   if ( mp->if_limit==if_code ) { /* condition not yet evaluated */
15140     mp_missing_err(mp, ":");
15141 @.Missing `:'@>
15142     mp_back_input(mp); mp->cur_sym=frozen_colon; mp_ins_error(mp);
15143   } else  { 
15144     print_err("Extra "); mp_print_cmd_mod(mp, fi_or_else,mp->cur_mod);
15145 @.Extra else@>
15146 @.Extra elseif@>
15147 @.Extra fi@>
15148     help1("I'm ignoring this; it doesn't match any if.");
15149     mp_error(mp);
15150   }
15151 } else  { 
15152   while ( mp->cur_mod!=fi_code ) mp_pass_text(mp); /* skip to \&{fi} */
15153   @<Pop the condition stack@>;
15154 }
15155
15156 @* \[34] Iterations.
15157 To bring our treatment of |get_x_next| to a close, we need to consider what
15158 \MP\ does when it sees \&{for}, \&{forsuffixes}, and \&{forever}.
15159
15160 There's a global variable |loop_ptr| that keeps track of the \&{for} loops
15161 that are currently active. If |loop_ptr=null|, no loops are in progress;
15162 otherwise |info(loop_ptr)| points to the iterative text of the current
15163 (innermost) loop, and |link(loop_ptr)| points to the data for any other
15164 loops that enclose the current one.
15165
15166 A loop-control node also has two other fields, called |loop_type| and
15167 |loop_list|, whose contents depend on the type of loop:
15168
15169 \yskip\indent|loop_type(loop_ptr)=null| means that |loop_list(loop_ptr)|
15170 points to a list of one-word nodes whose |info| fields point to the
15171 remaining argument values of a suffix list and expression list.
15172
15173 \yskip\indent|loop_type(loop_ptr)=diov| means that the current loop is
15174 `\&{forever}'.
15175
15176 \yskip\indent|loop_type(loop_ptr)=progression_flag| means that
15177 |p=loop_list(loop_ptr)| points to a ``progression node'' and |value(p)|,
15178 |step_size(p)|, and |final_value(p)| contain the data for an arithmetic
15179 progression.
15180
15181 \yskip\indent|loop_type(loop_ptr)=p>diov| means that |p| points to an edge
15182 header and |loop_list(loop_ptr)| points into the graphical object list for
15183 that edge header.
15184
15185 \yskip\noindent In the case of a progression node, the first word is not used
15186 because the link field of words in the dynamic memory area cannot be arbitrary.
15187
15188 @d loop_list_loc(A) ((A)+1) /* where the |loop_list| field resides */
15189 @d loop_type(A) info(loop_list_loc((A))) /* the type of \&{for} loop */
15190 @d loop_list(A) link(loop_list_loc((A))) /* the remaining list elements */
15191 @d loop_node_size 2 /* the number of words in a loop control node */
15192 @d progression_node_size 4 /* the number of words in a progression node */
15193 @d step_size(A) mp->mem[(A)+2].sc /* the step size in an arithmetic progression */
15194 @d final_value(A) mp->mem[(A)+3].sc /* the final value in an arithmetic progression */
15195 @d progression_flag (null+2)
15196   /* |loop_type| value when |loop_list| points to a progression node */
15197
15198 @<Glob...@>=
15199 pointer loop_ptr; /* top of the loop-control-node stack */
15200
15201 @ @<Set init...@>=
15202 mp->loop_ptr=null;
15203
15204 @ If the expressions that define an arithmetic progression in
15205 a \&{for} loop don't have known numeric values, the |bad_for|
15206 subroutine screams at the user.
15207
15208 @c void mp_bad_for (MP mp, char * s) {
15209   mp_disp_err(mp, null,"Improper "); /* show the bad expression above the message */
15210 @.Improper...replaced by 0@>
15211   mp_print(mp, s); mp_print(mp, " has been replaced by 0");
15212   help4("When you say `for x=a step b until c',")
15213     ("the initial value `a' and the step size `b'")
15214     ("and the final value `c' must have known numeric values.")
15215     ("I'm zeroing this one. Proceed, with fingers crossed.");
15216   mp_put_get_flush_error(mp, 0);
15217 };
15218
15219 @ Here's what \MP\ does when \&{for}, \&{forsuffixes}, or \&{forever}
15220 has just been scanned. (This code requires slight familiarity with
15221 expression-parsing routines that we have not yet discussed; but it seems
15222 to belong in the present part of the program, even though the original author
15223 didn't write it until later. The reader may wish to come back to it.)
15224
15225 @c void mp_begin_iteration (MP mp) {
15226   halfword m; /* |expr_base| (\&{for}) or |suffix_base| (\&{forsuffixes}) */
15227   halfword n; /* hash address of the current symbol */
15228   pointer s; /* the new loop-control node */
15229   pointer p; /* substitution list for |scan_toks| */
15230   pointer q;  /* link manipulation register */
15231   pointer pp; /* a new progression node */
15232   m=mp->cur_mod; n=mp->cur_sym; s=mp_get_node(mp, loop_node_size);
15233   if ( m==start_forever ){ 
15234     loop_type(s)=diov; p=null; mp_get_x_next(mp);
15235   } else { 
15236     mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
15237     info(p)=mp->cur_sym; value(p)=m;
15238     mp_get_x_next(mp);
15239     if ( mp->cur_cmd==within_token ) {
15240       @<Set up a picture iteration@>;
15241     } else { 
15242       @<Check for the |"="| or |":="| in a loop header@>;
15243       @<Scan the values to be used in the loop@>;
15244     }
15245   }
15246   @<Check for the presence of a colon@>;
15247   @<Scan the loop text and put it on the loop control stack@>;
15248   mp_resume_iteration(mp);
15249 }
15250
15251 @ @<Check for the |"="| or |":="| in a loop header@>=
15252 if ( (mp->cur_cmd!=equals)&&(mp->cur_cmd!=assignment) ) { 
15253   mp_missing_err(mp, "=");
15254 @.Missing `='@>
15255   help3("The next thing in this loop should have been `=' or `:='.")
15256     ("But don't worry; I'll pretend that an equals sign")
15257     ("was present, and I'll look for the values next.");
15258   mp_back_error(mp);
15259 }
15260
15261 @ @<Check for the presence of a colon@>=
15262 if ( mp->cur_cmd!=colon ) { 
15263   mp_missing_err(mp, ":");
15264 @.Missing `:'@>
15265   help3("The next thing in this loop should have been a `:'.")
15266     ("So I'll pretend that a colon was present;")
15267     ("everything from here to `endfor' will be iterated.");
15268   mp_back_error(mp);
15269 }
15270
15271 @ We append a special |frozen_repeat_loop| token in place of the
15272 `\&{endfor}' at the end of the loop. This will come through \MP's scanner
15273 at the proper time to cause the loop to be repeated.
15274
15275 (If the user tries some shenanigan like `\&{for} $\ldots$ \&{let} \&{endfor}',
15276 he will be foiled by the |get_symbol| routine, which keeps frozen
15277 tokens unchanged. Furthermore the |frozen_repeat_loop| is an \&{outer}
15278 token, so it won't be lost accidentally.)
15279
15280 @ @<Scan the loop text...@>=
15281 q=mp_get_avail(mp); info(q)=frozen_repeat_loop;
15282 mp->scanner_status=loop_defining; mp->warning_info=n;
15283 info(s)=mp_scan_toks(mp, iteration,p,q,0); mp->scanner_status=normal;
15284 link(s)=mp->loop_ptr; mp->loop_ptr=s
15285
15286 @ @<Initialize table...@>=
15287 eq_type(frozen_repeat_loop)=repeat_loop+outer_tag;
15288 text(frozen_repeat_loop)=intern(" ENDFOR");
15289
15290 @ The loop text is inserted into \MP's scanning apparatus by the
15291 |resume_iteration| routine.
15292
15293 @c void mp_resume_iteration (MP mp) {
15294   pointer p,q; /* link registers */
15295   p=loop_type(mp->loop_ptr);
15296   if ( p==progression_flag ) { 
15297     p=loop_list(mp->loop_ptr); /* now |p| points to a progression node */
15298     mp->cur_exp=value(p);
15299     if ( @<The arithmetic progression has ended@> ) {
15300       mp_stop_iteration(mp);
15301       return;
15302     }
15303     mp->cur_type=mp_known; q=mp_stash_cur_exp(mp); /* make |q| an \&{expr} argument */
15304     value(p)=mp->cur_exp+step_size(p); /* set |value(p)| for the next iteration */
15305   } else if ( p==null ) { 
15306     p=loop_list(mp->loop_ptr);
15307     if ( p==null ) {
15308       mp_stop_iteration(mp);
15309       return;
15310     }
15311     loop_list(mp->loop_ptr)=link(p); q=info(p); free_avail(p);
15312   } else if ( p==diov ) { 
15313     mp_begin_token_list(mp, info(mp->loop_ptr),forever_text); return;
15314   } else {
15315     @<Make |q| a capsule containing the next picture component from
15316       |loop_list(loop_ptr)| or |goto not_found|@>;
15317   }
15318   mp_begin_token_list(mp, info(mp->loop_ptr),loop_text);
15319   mp_stack_argument(mp, q);
15320   if ( mp->internal[tracing_commands]>unity ) {
15321      @<Trace the start of a loop@>;
15322   }
15323   return;
15324 NOT_FOUND:
15325   mp_stop_iteration(mp);
15326 }
15327
15328 @ @<The arithmetic progression has ended@>=
15329 ((step_size(p)>0)&&(mp->cur_exp>final_value(p)))||
15330  ((step_size(p)<0)&&(mp->cur_exp<final_value(p)))
15331
15332 @ @<Trace the start of a loop@>=
15333
15334   mp_begin_diagnostic(mp); mp_print_nl(mp, "{loop value=");
15335 @.loop value=n@>
15336   if ( (q!=null)&&(link(q)==diov) ) mp_print_exp(mp, q,1);
15337   else mp_show_token_list(mp, q,null,50,0);
15338   mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
15339 }
15340
15341 @ @<Make |q| a capsule containing the next picture component from...@>=
15342 { q=loop_list(mp->loop_ptr);
15343   if ( q==null ) goto NOT_FOUND;
15344   skip_component(q) goto NOT_FOUND;
15345   mp->cur_exp=mp_copy_objects(mp, loop_list(mp->loop_ptr),q);
15346   mp_init_bbox(mp, mp->cur_exp);
15347   mp->cur_type=mp_picture_type;
15348   loop_list(mp->loop_ptr)=q;
15349   q=mp_stash_cur_exp(mp);
15350 }
15351
15352 @ A level of loop control disappears when |resume_iteration| has decided
15353 not to resume, or when an \&{exitif} construction has removed the loop text
15354 from the input stack.
15355
15356 @c void mp_stop_iteration (MP mp) {
15357   pointer p,q; /* the usual */
15358   p=loop_type(mp->loop_ptr);
15359   if ( p==progression_flag )  {
15360     mp_free_node(mp, loop_list(mp->loop_ptr),progression_node_size);
15361   } else if ( p==null ){ 
15362     q=loop_list(mp->loop_ptr);
15363     while ( q!=null ) {
15364       p=info(q);
15365       if ( p!=null ) {
15366         if ( link(p)==diov ) { /* it's an \&{expr} parameter */
15367           mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
15368         } else {
15369           mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
15370         }
15371       }
15372       p=q; q=link(q); free_avail(p);
15373     }
15374   } else if ( p>progression_flag ) {
15375     delete_edge_ref(p);
15376   }
15377   p=mp->loop_ptr; mp->loop_ptr=link(p); mp_flush_token_list(mp, info(p));
15378   mp_free_node(mp, p,loop_node_size);
15379 }
15380
15381 @ Now that we know all about loop control, we can finish up
15382 the missing portion of |begin_iteration| and we'll be done.
15383
15384 The following code is performed after the `\.=' has been scanned in
15385 a \&{for} construction (if |m=expr_base|) or a \&{forsuffixes} construction
15386 (if |m=suffix_base|).
15387
15388 @<Scan the values to be used in the loop@>=
15389 loop_type(s)=null; q=loop_list_loc(s); link(q)=null; /* |link(q)=loop_list(s)| */
15390 do {  
15391   mp_get_x_next(mp);
15392   if ( m!=expr_base ) {
15393     mp_scan_suffix(mp);
15394   } else { 
15395     if ( mp->cur_cmd>=colon ) if ( mp->cur_cmd<=comma ) 
15396           goto CONTINUE;
15397     mp_scan_expression(mp);
15398     if ( mp->cur_cmd==step_token ) if ( q==loop_list_loc(s) ) {
15399       @<Prepare for step-until construction and |break|@>;
15400     }
15401     mp->cur_exp=mp_stash_cur_exp(mp);
15402   }
15403   link(q)=mp_get_avail(mp); q=link(q); 
15404   info(q)=mp->cur_exp; mp->cur_type=mp_vacuous;
15405 CONTINUE:
15406   ;
15407 } while (mp->cur_cmd==comma)
15408
15409 @ @<Prepare for step-until construction and |break|@>=
15410
15411   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "initial value");
15412   pp=mp_get_node(mp, progression_node_size); value(pp)=mp->cur_exp;
15413   mp_get_x_next(mp); mp_scan_expression(mp);
15414   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "step size");
15415   step_size(pp)=mp->cur_exp;
15416   if ( mp->cur_cmd!=until_token ) { 
15417     mp_missing_err(mp, "until");
15418 @.Missing `until'@>
15419     help2("I assume you meant to say `until' after `step'.")
15420       ("So I'll look for the final value and colon next.");
15421     mp_back_error(mp);
15422   }
15423   mp_get_x_next(mp); mp_scan_expression(mp);
15424   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "final value");
15425   final_value(pp)=mp->cur_exp; loop_list(s)=pp;
15426   loop_type(s)=progression_flag; 
15427   break;
15428 }
15429
15430 @ The last case is when we have just seen ``\&{within}'', and we need to
15431 parse a picture expression and prepare to iterate over it.
15432
15433 @<Set up a picture iteration@>=
15434 { mp_get_x_next(mp);
15435   mp_scan_expression(mp);
15436   @<Make sure the current expression is a known picture@>;
15437   loop_type(s)=mp->cur_exp; mp->cur_type=mp_vacuous;
15438   q=link(dummy_loc(mp->cur_exp));
15439   if ( q!= null ) 
15440     if ( is_start_or_stop(q) )
15441       if ( mp_skip_1component(mp, q)==null ) q=link(q);
15442   loop_list(s)=q;
15443 }
15444
15445 @ @<Make sure the current expression is a known picture@>=
15446 if ( mp->cur_type!=mp_picture_type ) {
15447   mp_disp_err(mp, null,"Improper iteration spec has been replaced by nullpicture");
15448   help1("When you say `for x in p', p must be a known picture.");
15449   mp_put_get_flush_error(mp, mp_get_node(mp, edge_header_size));
15450   mp_init_edges(mp, mp->cur_exp); mp->cur_type=mp_picture_type;
15451 }
15452
15453 @* \[35] File names.
15454 It's time now to fret about file names.  Besides the fact that different
15455 operating systems treat files in different ways, we must cope with the
15456 fact that completely different naming conventions are used by different
15457 groups of people. The following programs show what is required for one
15458 particular operating system; similar routines for other systems are not
15459 difficult to devise.
15460 @^system dependencies@>
15461
15462 \MP\ assumes that a file name has three parts: the name proper; its
15463 ``extension''; and a ``file area'' where it is found in an external file
15464 system.  The extension of an input file is assumed to be
15465 `\.{.mp}' unless otherwise specified; it is `\.{.log}' on the
15466 transcript file that records each run of \MP; it is `\.{.tfm}' on the font
15467 metric files that describe characters in any fonts created by \MP; it is
15468 `\.{.ps}' or `.{\it nnn}' for some number {\it nnn} on the \ps\ output files;
15469 and it is `\.{.mem}' on the mem files written by \.{INIMP} to initialize \MP.
15470 The file area can be arbitrary on input files, but files are usually
15471 output to the user's current area.  If an input file cannot be
15472 found on the specified area, \MP\ will look for it on a special system
15473 area; this special area is intended for commonly used input files.
15474
15475 Simple uses of \MP\ refer only to file names that have no explicit
15476 extension or area. For example, a person usually says `\.{input} \.{cmr10}'
15477 instead of `\.{input} \.{cmr10.new}'. Simple file
15478 names are best, because they make the \MP\ source files portable;
15479 whenever a file name consists entirely of letters and digits, it should be
15480 treated in the same way by all implementations of \MP. However, users
15481 need the ability to refer to other files in their environment, especially
15482 when responding to error messages concerning unopenable files; therefore
15483 we want to let them use the syntax that appears in their favorite
15484 operating system.
15485
15486 @ \MP\ uses the same conventions that have proved to be satisfactory for
15487 \TeX\ and \MF. In order to isolate the system-dependent aspects of file names,
15488 @^system dependencies@>
15489 the system-independent parts of \MP\ are expressed in terms
15490 of three system-dependent
15491 procedures called |begin_name|, |more_name|, and |end_name|. In
15492 essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
15493 the system-independent driver program does the operations
15494 $$|begin_name|;\,|more_name|(c_1);\,\ldots\,;|more_name|(c_n);
15495 \,|end_name|.$$
15496 These three procedures communicate with each other via global variables.
15497 Afterwards the file name will appear in the string pool as three strings
15498 called |cur_name|\penalty10000\hskip-.05em,
15499 |cur_area|, and |cur_ext|; the latter two are null (i.e.,
15500 |""|), unless they were explicitly specified by the user.
15501
15502 Actually the situation is slightly more complicated, because \MP\ needs
15503 to know when the file name ends. The |more_name| routine is a function
15504 (with side effects) that returns |true| on the calls |more_name|$(c_1)$,
15505 \dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
15506 returns |false|; or, it returns |true| and $c_n$ is the last character
15507 on the current input line. In other words,
15508 |more_name| is supposed to return |true| unless it is sure that the
15509 file name has been completely scanned; and |end_name| is supposed to be able
15510 to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
15511 whether $|more_name|(c_n)$ returned |true| or |false|.
15512
15513 @<Glob...@>=
15514 char * cur_name; /* name of file just scanned */
15515 char * cur_area; /* file area just scanned, or \.{""} */
15516 char * cur_ext; /* file extension just scanned, or \.{""} */
15517
15518 @ It is easier to maintain reference counts if we assign initial values.
15519
15520 @<Set init...@>=
15521 mp->cur_name=xstrdup(""); 
15522 mp->cur_area=xstrdup(""); 
15523 mp->cur_ext=xstrdup("");
15524
15525 @ @<Dealloc variables@>=
15526 xfree(mp->cur_area);
15527 xfree(mp->cur_name);
15528 xfree(mp->cur_ext);
15529
15530 @ The file names we shall deal with for illustrative purposes have the
15531 following structure:  If the name contains `\.>' or `\.:', the file area
15532 consists of all characters up to and including the final such character;
15533 otherwise the file area is null.  If the remaining file name contains
15534 `\..', the file extension consists of all such characters from the first
15535 remaining `\..' to the end, otherwise the file extension is null.
15536 @^system dependencies@>
15537
15538 We can scan such file names easily by using two global variables that keep track
15539 of the occurrences of area and extension delimiters.  Note that these variables
15540 cannot be of type |pool_pointer| because a string pool compaction could occur
15541 while scanning a file name.
15542
15543 @<Glob...@>=
15544 integer area_delimiter;
15545   /* most recent `\.>' or `\.:' relative to |str_start[str_ptr]| */
15546 integer ext_delimiter; /* the relevant `\..', if any */
15547
15548 @ Input files that can't be found in the user's area may appear in standard
15549 system areas called |MP_area| and |MF_area|.  (The latter is used when the file
15550 extension is |".mf"|.)  The standard system area for font metric files
15551 to be read is |MP_font_area|.
15552 This system area name will, of course, vary from place to place.
15553 @^system dependencies@>
15554
15555 @d MP_area "MPinputs:"
15556 @.MPinputs@>
15557 @d MF_area "MFinputs:"
15558 @.MFinputs@>
15559 @d MP_font_area ""
15560 @.TeXfonts@>
15561
15562 @ Here now is the first of the system-dependent routines for file name scanning.
15563 @^system dependencies@>
15564
15565 @<Declare subroutines for parsing file names@>=
15566 void mp_begin_name (MP mp) { 
15567   xfree(mp->cur_name); 
15568   xfree(mp->cur_area); 
15569   xfree(mp->cur_ext);
15570   mp->area_delimiter=-1; 
15571   mp->ext_delimiter=-1;
15572 }
15573
15574 @ And here's the second.
15575 @^system dependencies@>
15576
15577 @<Declare subroutines for parsing file names@>=
15578 boolean mp_more_name (MP mp, ASCII_code c) { 
15579   if (c==' ') {
15580     return false;
15581   } else { 
15582     if ( (c=='>')||(c==':') ) { 
15583       mp->area_delimiter=mp->pool_ptr; 
15584       mp->ext_delimiter=-1;
15585     } else if ( (c=='.')&&(mp->ext_delimiter<0) ) {
15586       mp->ext_delimiter=mp->pool_ptr;
15587     }
15588     str_room(1); append_char(c); /* contribute |c| to the current string */
15589     return true;
15590   }
15591 }
15592
15593 @ The third.
15594 @^system dependencies@>
15595
15596 @d copy_pool_segment(A,B,C) { 
15597       A = xmalloc(C+1,sizeof(char)); 
15598       strncpy(A,(char *)(mp->str_pool+B),C);  
15599       A[C] = 0;}
15600
15601 @<Declare subroutines for parsing file names@>=
15602 void mp_end_name (MP mp) {
15603   pool_pointer s; /* length of area, name, and extension */
15604   unsigned int len;
15605   /* "my/w.mp" */
15606   s = mp->str_start[mp->str_ptr];
15607   if ( mp->area_delimiter<0 ) {
15608     mp->cur_area=xstrdup("");
15609   } else {
15610     len = mp->area_delimiter-s; 
15611     copy_pool_segment(mp->cur_area,s,len);
15612     s += len+1;
15613   }
15614   if ( mp->ext_delimiter<0 ) {
15615     mp->cur_ext=xstrdup("");
15616     len = mp->pool_ptr-s; 
15617   } else {
15618     copy_pool_segment(mp->cur_ext,mp->ext_delimiter,(mp->pool_ptr-mp->ext_delimiter));
15619     len = mp->ext_delimiter-s;
15620   }
15621   copy_pool_segment(mp->cur_name,s,len);
15622   mp->pool_ptr=s; /* don't need this partial string */
15623 }
15624
15625 @ Conversely, here is a routine that takes three strings and prints a file
15626 name that might have produced them. (The routine is system dependent, because
15627 some operating systems put the file area last instead of first.)
15628 @^system dependencies@>
15629
15630 @<Basic printing...@>=
15631 void mp_print_file_name (MP mp, char * n, char * a, char * e) { 
15632   mp_print(mp, a); mp_print(mp, n); mp_print(mp, e);
15633 };
15634
15635 @ Another system-dependent routine is needed to convert three internal
15636 \MP\ strings
15637 to the |name_of_file| value that is used to open files. The present code
15638 allows both lowercase and uppercase letters in the file name.
15639 @^system dependencies@>
15640
15641 @d append_to_name(A) { c=(A); 
15642   if ( k<file_name_size ) {
15643     mp->name_of_file[k]=mp->xchr[c];
15644     incr(k);
15645   }
15646 }
15647
15648 @<Declare subroutines for parsing file names@>=
15649 void mp_pack_file_name (MP mp, char *n, char *a, char *e) {
15650   integer k; /* number of positions filled in |name_of_file| */
15651   ASCII_code c; /* character being packed */
15652   char *j; /* a character  index */
15653   k=0;
15654   assert(n);
15655   if (a!=NULL) {
15656     for (j=a;*j;j++) { append_to_name(*j); }
15657   }
15658   for (j=n;*j;j++) { append_to_name(*j); }
15659   if (e!=NULL) {
15660     for (j=e;*j;j++) { append_to_name(*j); }
15661   }
15662   mp->name_of_file[k]=0;
15663   mp->name_length=k; 
15664 }
15665
15666 @ @<Exported...@>=
15667 void mp_pack_file_name (MP mp, char *n, char *a, char *e) ;
15668
15669 @ A messier routine is also needed, since mem file names must be scanned
15670 before \MP's string mechanism has been initialized. We shall use the
15671 global variable |MP_mem_default| to supply the text for default system areas
15672 and extensions related to mem files.
15673 @^system dependencies@>
15674
15675 @d mem_default_length 9 /* length of the |MP_mem_default| string */
15676 @d mem_ext_length 4 /* length of its `\.{.mem}' part */
15677 @d mem_extension ".mem" /* the extension, as a \.{WEB} constant */
15678
15679 @<Glob...@>=
15680 char *MP_mem_default;
15681 char *mem_name; /* for commandline */
15682
15683 @ @<Option variables@>=
15684 char *mem_name; /* for commandline */
15685
15686 @ @<Allocate or initialize ...@>=
15687 mp->MP_mem_default = xstrdup("plain.mem");
15688 mp->mem_name = mp_xstrdup(opt.mem_name);
15689 @.plain@>
15690 @^system dependencies@>
15691
15692 @ @<Dealloc variables@>=
15693 xfree(mp->MP_mem_default);
15694 xfree(mp->mem_name);
15695
15696 @ @<Check the ``constant'' values for consistency@>=
15697 if ( mem_default_length>file_name_size ) mp->bad=20;
15698
15699 @ Here is the messy routine that was just mentioned. It sets |name_of_file|
15700 from the first |n| characters of |MP_mem_default|, followed by
15701 |buffer[a..b]|, followed by the last |mem_ext_length| characters of
15702 |MP_mem_default|.
15703
15704 We dare not give error messages here, since \MP\ calls this routine before
15705 the |error| routine is ready to roll. Instead, we simply drop excess characters,
15706 since the error will be detected in another way when a strange file name
15707 isn't found.
15708 @^system dependencies@>
15709
15710 @c void mp_pack_buffered_name (MP mp,small_number n, integer a,
15711                                integer b) {
15712   integer k; /* number of positions filled in |name_of_file| */
15713   ASCII_code c; /* character being packed */
15714   integer j; /* index into |buffer| or |MP_mem_default| */
15715   if ( n+b-a+1+mem_ext_length>file_name_size )
15716     b=a+file_name_size-n-1-mem_ext_length;
15717   k=0;
15718   for (j=0;j<n;j++) {
15719     append_to_name(mp->xord[(int)mp->MP_mem_default[j]]);
15720   }
15721   for (j=a;j<=b;j++) {
15722     append_to_name(mp->buffer[j]);
15723   }
15724   for (j=mem_default_length-mem_ext_length;
15725       j<mem_default_length;j++) {
15726     append_to_name(mp->xord[(int)mp->MP_mem_default[j]]);
15727   } 
15728   mp->name_of_file[k]=0;
15729   mp->name_length=k; 
15730 }
15731
15732 @ Here is the only place we use |pack_buffered_name|. This part of the program
15733 becomes active when a ``virgin'' \MP\ is trying to get going, just after
15734 the preliminary initialization, or when the user is substituting another
15735 mem file by typing `\.\&' after the initial `\.{**}' prompt.  The buffer
15736 contains the first line of input in |buffer[loc..(last-1)]|, where
15737 |loc<last| and |buffer[loc]<>" "|.
15738
15739 @<Declarations@>=
15740 boolean mp_open_mem_file (MP mp) ;
15741
15742 @ @c
15743 boolean mp_open_mem_file (MP mp) {
15744   int j; /* the first space after the file name */
15745   if (mp->mem_name!=NULL) {
15746     mp->mem_file = mp_open_file(mp, mp->mem_name, "rb", mp_filetype_memfile);
15747     if ( mp->mem_file ) return true;
15748   }
15749   j=loc;
15750   if ( mp->buffer[loc]=='&' ) {
15751     incr(loc); j=loc; mp->buffer[mp->last]=' ';
15752     while ( mp->buffer[j]!=' ' ) incr(j);
15753     mp_pack_buffered_name(mp, 0,loc,j-1); /* try first without the system file area */
15754     if ( mp_w_open_in(mp, &mp->mem_file) ) goto FOUND;
15755     wake_up_terminal;
15756     wterm_ln("Sorry, I can\'t find that mem file; will try PLAIN.");
15757 @.Sorry, I can't find...@>
15758     update_terminal;
15759   }
15760   /* now pull out all the stops: try for the system \.{plain} file */
15761   mp_pack_buffered_name(mp, mem_default_length-mem_ext_length,0,0);
15762   if ( ! mp_w_open_in(mp, &mp->mem_file) ) {
15763     wake_up_terminal;
15764     wterm_ln("I can\'t find the PLAIN mem file!\n");
15765 @.I can't find PLAIN...@>
15766 @.plain@>
15767     return false;
15768   }
15769 FOUND:
15770   loc=j; return true;
15771 }
15772
15773 @ Operating systems often make it possible to determine the exact name (and
15774 possible version number) of a file that has been opened. The following routine,
15775 which simply makes a \MP\ string from the value of |name_of_file|, should
15776 ideally be changed to deduce the full name of file~|f|, which is the file
15777 most recently opened, if it is possible to do this in a \PASCAL\ program.
15778 @^system dependencies@>
15779
15780 @<Declarations@>=
15781 #define mp_a_make_name_string(A,B)  mp_make_name_string(A)
15782 #define mp_b_make_name_string(A,B)  mp_make_name_string(A)
15783 #define mp_w_make_name_string(A,B)  mp_make_name_string(A)
15784
15785 @ @c 
15786 str_number mp_make_name_string (MP mp) {
15787   int k; /* index into |name_of_file| */
15788   str_room(mp->name_length);
15789   for (k=0;k<mp->name_length;k++) {
15790     append_char(mp->xord[(int)mp->name_of_file[k]]);
15791   }
15792   return mp_make_string(mp);
15793 }
15794
15795 @ Now let's consider the ``driver''
15796 routines by which \MP\ deals with file names
15797 in a system-independent manner.  First comes a procedure that looks for a
15798 file name in the input by taking the information from the input buffer.
15799 (We can't use |get_next|, because the conversion to tokens would
15800 destroy necessary information.)
15801
15802 This procedure doesn't allow semicolons or percent signs to be part of
15803 file names, because of other conventions of \MP.
15804 {\sl The {\logos METAFONT\/}book} doesn't
15805 use semicolons or percents immediately after file names, but some users
15806 no doubt will find it natural to do so; therefore system-dependent
15807 changes to allow such characters in file names should probably
15808 be made with reluctance, and only when an entire file name that
15809 includes special characters is ``quoted'' somehow.
15810 @^system dependencies@>
15811
15812 @c void mp_scan_file_name (MP mp) { 
15813   mp_begin_name(mp);
15814   while ( mp->buffer[loc]==' ' ) incr(loc);
15815   while (1) { 
15816     if ( (mp->buffer[loc]==';')||(mp->buffer[loc]=='%') ) break;
15817     if ( ! mp_more_name(mp, mp->buffer[loc]) ) break;
15818     incr(loc);
15819   }
15820   mp_end_name(mp);
15821 }
15822
15823 @ Here is another version that takes its input from a string.
15824
15825 @<Declare subroutines for parsing file names@>=
15826 void mp_str_scan_file (MP mp,  str_number s) {
15827   pool_pointer p,q; /* current position and stopping point */
15828   mp_begin_name(mp);
15829   p=mp->str_start[s]; q=str_stop(s);
15830   while ( p<q ){ 
15831     if ( ! mp_more_name(mp, mp->str_pool[p]) ) break;
15832     incr(p);
15833   }
15834   mp_end_name(mp);
15835 }
15836
15837 @ And one that reads from a |char*|.
15838
15839 @<Declare subroutines for parsing file names@>=
15840 void mp_ptr_scan_file (MP mp,  char *s) {
15841   char *p, *q; /* current position and stopping point */
15842   mp_begin_name(mp);
15843   p=s; q=p+strlen(s);
15844   while ( p<q ){ 
15845     if ( ! mp_more_name(mp, *p)) break;
15846     p++;
15847   }
15848   mp_end_name(mp);
15849 }
15850
15851
15852 @ The global variable |job_name| contains the file name that was first
15853 \&{input} by the user. This name is extended by `\.{.log}' and `\.{ps}' and
15854 `\.{.mem}' and `\.{.tfm}' in order to make the names of \MP's output files.
15855
15856 @<Glob...@>=
15857 char *job_name; /* principal file name */
15858 boolean log_opened; /* has the transcript file been opened? */
15859 char *log_name; /* full name of the log file */
15860
15861 @ @<Option variables@>=
15862 char *job_name; /* principal file name */
15863
15864 @ Initially |job_name=NULL|; it becomes nonzero as soon as the true name is known.
15865 We have |job_name=NULL| if and only if the `\.{log}' file has not been opened,
15866 except of course for a short time just after |job_name| has become nonzero.
15867
15868 @<Allocate or ...@>=
15869 mp->job_name=mp_xstrdup(opt.job_name); 
15870 mp->log_opened=false;
15871
15872 @ @<Dealloc variables@>=
15873 xfree(mp->job_name);
15874
15875 @ Here is a routine that manufactures the output file names, assuming that
15876 |job_name<>0|. It ignores and changes the current settings of |cur_area|
15877 and |cur_ext|.
15878
15879 @d pack_cur_name mp_pack_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext)
15880
15881 @<Declarations@>=
15882 void mp_pack_job_name (MP mp, char *s) ;
15883
15884 @ @c void mp_pack_job_name (MP mp, char  *s) { /* |s = ".log"|, |".mem"|, |".ps"|, or .\\{nnn} */
15885   xfree(mp->cur_name); mp->cur_name=xstrdup(mp->job_name);
15886   xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
15887   xfree(mp->cur_ext);  mp->cur_ext=xstrdup(s);
15888   pack_cur_name;
15889 }
15890
15891 @ If some trouble arises when \MP\ tries to open a file, the following
15892 routine calls upon the user to supply another file name. Parameter~|s|
15893 is used in the error message to identify the type of file; parameter~|e|
15894 is the default extension if none is given. Upon exit from the routine,
15895 variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
15896 ready for another attempt at file opening.
15897
15898 @<Declarations@>=
15899 void mp_prompt_file_name (MP mp,char * s, char * e) ;
15900
15901 @ @c void mp_prompt_file_name (MP mp,char * s, char * e) {
15902   size_t k; /* index into |buffer| */
15903   char * saved_cur_name;
15904   if ( mp->interaction==mp_scroll_mode ) 
15905         wake_up_terminal;
15906   if (strcmp(s,"input file name")==0) {
15907         print_err("I can\'t find file `");
15908 @.I can't find file x@>
15909   } else {
15910         print_err("I can\'t write on file `");
15911   }
15912 @.I can't write on file x@>
15913   mp_print_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext); 
15914   mp_print(mp, "'.");
15915   if (strcmp(e,"")==0) 
15916         mp_show_context(mp);
15917   mp_print_nl(mp, "Please type another "); mp_print(mp, s);
15918 @.Please type...@>
15919   if ( mp->interaction<mp_scroll_mode )
15920     mp_fatal_error(mp, "*** (job aborted, file error in nonstop mode)");
15921 @.job aborted, file error...@>
15922   saved_cur_name = xstrdup(mp->cur_name);
15923   clear_terminal; prompt_input(": "); @<Scan file name in the buffer@>;
15924   if (strcmp(mp->cur_ext,"")==0) 
15925         mp->cur_ext=e;
15926   if (strlen(mp->cur_name)==0) {
15927     mp->cur_name=saved_cur_name;
15928   } else {
15929     xfree(saved_cur_name);
15930   }
15931   pack_cur_name;
15932 }
15933
15934 @ @<Scan file name in the buffer@>=
15935
15936   mp_begin_name(mp); k=mp->first;
15937   while ( (mp->buffer[k]==' ')&&(k<mp->last) ) incr(k);
15938   while (1) { 
15939     if ( k==mp->last ) break;
15940     if ( ! mp_more_name(mp, mp->buffer[k]) ) break;
15941     incr(k);
15942   }
15943   mp_end_name(mp);
15944 }
15945
15946 @ The |open_log_file| routine is used to open the transcript file and to help
15947 it catch up to what has previously been printed on the terminal.
15948
15949 @c void mp_open_log_file (MP mp) {
15950   int old_setting; /* previous |selector| setting */
15951   int k; /* index into |months| and |buffer| */
15952   int l; /* end of first input line */
15953   integer m; /* the current month */
15954   char *months="JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"; 
15955     /* abbreviations of month names */
15956   old_setting=mp->selector;
15957   if ( mp->job_name==NULL ) {
15958      mp->job_name=xstrdup("mpout");
15959   }
15960   mp_pack_job_name(mp,".log");
15961   while ( ! mp_a_open_out(mp, &mp->log_file, mp_filetype_log) ) {
15962     @<Try to get a different log file name@>;
15963   }
15964   mp->log_name=xstrdup(mp->name_of_file);
15965   mp->selector=log_only; mp->log_opened=true;
15966   @<Print the banner line, including the date and time@>;
15967   mp->input_stack[mp->input_ptr]=mp->cur_input; 
15968     /* make sure bottom level is in memory */
15969   mp_print_nl(mp, "**");
15970 @.**@>
15971   l=mp->input_stack[0].limit_field-1; /* last position of first line */
15972   for (k=0;k<=l;k++) mp_print_str(mp, mp->buffer[k]);
15973   mp_print_ln(mp); /* now the transcript file contains the first line of input */
15974   mp->selector=old_setting+2; /* |log_only| or |term_and_log| */
15975 }
15976
15977 @ @<Dealloc variables@>=
15978 xfree(mp->log_name);
15979
15980 @ Sometimes |open_log_file| is called at awkward moments when \MP\ is
15981 unable to print error messages or even to |show_context|.
15982 The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
15983 routine will not be invoked because |log_opened| will be false.
15984
15985 The normal idea of |mp_batch_mode| is that nothing at all should be written
15986 on the terminal. However, in the unusual case that
15987 no log file could be opened, we make an exception and allow
15988 an explanatory message to be seen.
15989
15990 Incidentally, the program always refers to the log file as a `\.{transcript
15991 file}', because some systems cannot use the extension `\.{.log}' for
15992 this file.
15993
15994 @<Try to get a different log file name@>=
15995 {  
15996   mp->selector=term_only;
15997   mp_prompt_file_name(mp, "transcript file name",".log");
15998 }
15999
16000 @ @<Print the banner...@>=
16001
16002   wlog(banner);
16003   mp_print(mp, mp->mem_ident); mp_print(mp, "  ");
16004   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[day])); 
16005   mp_print_char(mp, ' ');
16006   m=mp_round_unscaled(mp, mp->internal[month]);
16007   for (k=3*m-3;k<3*m;k++) { wlog_chr(months[k]); }
16008   mp_print_char(mp, ' '); 
16009   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[year])); 
16010   mp_print_char(mp, ' ');
16011   m=mp_round_unscaled(mp, mp->internal[mp_time]);
16012   mp_print_dd(mp, m / 60); mp_print_char(mp, ':'); mp_print_dd(mp, m % 60);
16013 }
16014
16015 @ The |try_extension| function tries to open an input file determined by
16016 |cur_name|, |cur_area|, and the argument |ext|.  It returns |false| if it
16017 can't find the file in |cur_area| or the appropriate system area.
16018
16019 @c boolean mp_try_extension (MP mp,char *ext) { 
16020   mp_pack_file_name(mp, mp->cur_name,mp->cur_area, ext);
16021   in_name=xstrdup(mp->cur_name); 
16022   in_area=xstrdup(mp->cur_area);
16023   if ( mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16024     return true;
16025   } else { 
16026     if (strcmp(ext,".mf")==0 ) in_area=xstrdup(MF_area);
16027     else in_area=xstrdup(MP_area);
16028     mp_pack_file_name(mp, mp->cur_name,in_area,ext);
16029     return mp_a_open_in(mp, &cur_file, mp_filetype_program);
16030   }
16031   return false;
16032 }
16033
16034 @ Let's turn now to the procedure that is used to initiate file reading
16035 when an `\.{input}' command is being processed.
16036
16037 @c void mp_start_input (MP mp) { /* \MP\ will \.{input} something */
16038   char *fname = NULL;
16039   @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>;
16040   while (1) { 
16041     mp_begin_file_reading(mp); /* set up |cur_file| and new level of input */
16042     if ( strlen(mp->cur_ext)==0 ) {
16043       if ( mp_try_extension(mp, ".mp") ) break;
16044       else if ( mp_try_extension(mp, "") ) break;
16045       else if ( mp_try_extension(mp, ".mf") ) break;
16046       /* |else do_nothing; | */
16047     } else if ( mp_try_extension(mp, mp->cur_ext) ) {
16048       break;
16049     }
16050     mp_end_file_reading(mp); /* remove the level that didn't work */
16051     mp_prompt_file_name(mp, "input file name","");
16052   }
16053   name=mp_a_make_name_string(mp, cur_file);
16054   fname = xstrdup(mp->name_of_file);
16055   if ( mp->job_name==NULL ) {
16056     mp->job_name=xstrdup(mp->cur_name); 
16057     mp_open_log_file(mp);
16058   } /* |open_log_file| doesn't |show_context|, so |limit|
16059         and |loc| needn't be set to meaningful values yet */
16060   if ( ((int)mp->term_offset+(int)strlen(fname)) > (mp->max_print_line-2)) mp_print_ln(mp);
16061   else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
16062   mp_print_char(mp, '('); incr(mp->open_parens); mp_print(mp, fname); 
16063   xfree(fname);
16064   update_terminal;
16065   @<Flush |name| and replace it with |cur_name| if it won't be needed@>;
16066   @<Read the first line of the new file@>;
16067 }
16068
16069 @ This code should be omitted if |a_make_name_string| returns something other
16070 than just a copy of its argument and the full file name is needed for opening
16071 \.{MPX} files or implementing the switch-to-editor option.
16072 @^system dependencies@>
16073
16074 @<Flush |name| and replace it with |cur_name| if it won't be needed@>=
16075 mp_flush_string(mp, name); name=rts(mp->cur_name); mp->cur_name=NULL
16076
16077 @ Here we have to remember to tell the |input_ln| routine not to
16078 start with a |get|. If the file is empty, it is considered to
16079 contain a single blank line.
16080 @^system dependencies@>
16081
16082 @<Read the first line...@>=
16083
16084   line=1;
16085   (void)mp_input_ln(mp, cur_file,false); 
16086   mp_firm_up_the_line(mp);
16087   mp->buffer[limit]='%'; mp->first=limit+1; loc=start;
16088 }
16089
16090 @ @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>=
16091 while ( token_state &&(loc==null) ) mp_end_token_list(mp);
16092 if ( token_state ) { 
16093   print_err("File names can't appear within macros");
16094 @.File names can't...@>
16095   help3("Sorry...I've converted what follows to tokens,")
16096     ("possibly garbaging the name you gave.")
16097     ("Please delete the tokens and insert the name again.");
16098   mp_error(mp);
16099 }
16100 if ( file_state ) {
16101   mp_scan_file_name(mp);
16102 } else { 
16103    xfree(mp->cur_name); mp->cur_name=xstrdup(""); 
16104    xfree(mp->cur_ext);  mp->cur_ext =xstrdup(""); 
16105    xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
16106 }
16107
16108 @ Sometimes we need to deal with two file names at once.  This procedure
16109 copies the given string into a special array for an old file name.
16110
16111 @c void mp_copy_old_name (MP mp,str_number s) {
16112   integer k; /* number of positions filled in |old_file_name| */
16113   pool_pointer j; /* index into |str_pool| */
16114   k=0;
16115   for (j=mp->str_start[s];j<=str_stop(s)-1;j++) { 
16116     incr(k);
16117     if ( k<=file_name_size ) 
16118       mp->old_file_name[k]=mp->xchr[mp->str_pool[j]];
16119   }
16120   mp->old_file_name[++k] = 0;
16121 }
16122
16123 @ @<Glob...@>=
16124 char old_file_name[file_name_size+1];  /* analogous to |name_of_file| */
16125
16126 @ The following simple routine starts reading the \.{MPX} file associated
16127 with the current input file.
16128
16129 @c void mp_start_mpx_input (MP mp) {
16130   mp_pack_file_name(mp, in_name, in_area, ".mpx");
16131   @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16132     |goto not_found| if there is a problem@>;
16133   mp_begin_file_reading(mp);
16134   if ( ! mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16135     mp_end_file_reading(mp);
16136     goto NOT_FOUND;
16137   }
16138   name=mp_a_make_name_string(mp, cur_file);
16139   mp->mpx_name[index]=name; add_str_ref(name);
16140   @<Read the first line of the new file@>;
16141   return;
16142 NOT_FOUND: 
16143     @<Explain that the \.{MPX} file can't be read and |succumb|@>;
16144 }
16145
16146 @ This should ideally be changed to do whatever is necessary to create the
16147 \.{MPX} file given by |name_of_file| if it does not exist or if it is out
16148 of date.  This requires invoking \.{MPtoTeX} on the |old_file_name| and passing
16149 the results through \TeX\ and \.{DVItoMP}.  (It is possible to use a
16150 completely different typesetting program if suitable postprocessor is
16151 available to perform the function of \.{DVItoMP}.)
16152 @^system dependencies@>
16153
16154 @ @<Types...@>=
16155 typedef boolean (*run_make_mpx_command)(MP mp, char *origname, char *mtxname);
16156
16157 @ @<Glob...@>=
16158 run_make_mpx_command run_make_mpx;
16159
16160 @ @<Option variables@>=
16161 run_make_mpx_command run_make_mpx;
16162
16163 @ @<Allocate or initialize ...@>=
16164 set_callback_option(run_make_mpx);
16165
16166 @ @<Exported function headers@>=
16167 boolean mp_run_make_mpx (MP mp, char *origname, char *mtxname);
16168
16169 @ The default does nothing.
16170 @c 
16171 boolean mp_run_make_mpx (MP mp, char *origname, char *mtxname) {
16172   if (mp && origname && mtxname) /* for -W */
16173     return false;
16174   return false;
16175 }
16176
16177
16178
16179 @ @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16180   |goto not_found| if there is a problem@>=
16181 mp_copy_old_name(mp, name);
16182 if (!(mp->run_make_mpx)(mp, mp->old_file_name, mp->name_of_file))
16183    goto NOT_FOUND
16184
16185 @ @<Explain that the \.{MPX} file can't be read and |succumb|@>=
16186 if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16187 mp_print_nl(mp, ">> ");
16188 mp_print(mp, mp->old_file_name);
16189 mp_print_nl(mp, ">> ");
16190 mp_print(mp, mp->name_of_file);
16191 mp_print_nl(mp, "! Unable to make mpx file");
16192 help4("The two files given above are one of your source files")
16193   ("and an auxiliary file I need to read to find out what your")
16194   ("btex..etex blocks mean. If you don't know why I had trouble,")
16195   ("try running it manually through MPtoTeX, TeX, and DVItoMP");
16196 succumb;
16197
16198 @ The last file-opening commands are for files accessed via the \&{readfrom}
16199 @:read_from_}{\&{readfrom} primitive@>
16200 operator and the \&{write} command.  Such files are stored in separate arrays.
16201 @:write_}{\&{write} primitive@>
16202
16203 @<Types in the outer block@>=
16204 typedef unsigned int readf_index; /* |0..max_read_files| */
16205 typedef unsigned int write_index;  /* |0..max_write_files| */
16206
16207 @ @<Glob...@>=
16208 readf_index max_read_files; /* maximum number of simultaneously open \&{readfrom} files */
16209 FILE ** rd_file; /* \&{readfrom} files */
16210 char ** rd_fname; /* corresponding file name or 0 if file not open */
16211 readf_index read_files; /* number of valid entries in the above arrays */
16212 write_index max_write_files; /* maximum number of simultaneously open \&{write} */
16213 FILE ** wr_file; /* \&{write} files */
16214 char ** wr_fname; /* corresponding file name or 0 if file not open */
16215 write_index write_files; /* number of valid entries in the above arrays */
16216
16217 @ @<Allocate or initialize ...@>=
16218 mp->max_read_files=8;
16219 mp->rd_file = xmalloc((mp->max_read_files+1),sizeof(FILE *));
16220 mp->rd_fname = xmalloc((mp->max_read_files+1),sizeof(char *));
16221 memset(mp->rd_fname, 0, sizeof(char *)*(mp->max_read_files+1));
16222 mp->read_files=0;
16223 mp->max_write_files=8;
16224 mp->wr_file = xmalloc((mp->max_write_files+1),sizeof(FILE *));
16225 mp->wr_fname = xmalloc((mp->max_write_files+1),sizeof(char *));
16226 memset(mp->wr_fname, 0, sizeof(char *)*(mp->max_write_files+1));
16227 mp->write_files=0;
16228
16229
16230 @ This routine starts reading the file named by string~|s| without setting
16231 |loc|, |limit|, or |name|.  It returns |false| if the file is empty or cannot
16232 be opened.  Otherwise it updates |rd_file[n]| and |rd_fname[n]|.
16233
16234 @c boolean mp_start_read_input (MP mp,char *s, readf_index  n) {
16235   mp_ptr_scan_file(mp, s);
16236   pack_cur_name;
16237   mp_begin_file_reading(mp);
16238   if ( ! mp_a_open_in(mp, &mp->rd_file[n], mp_filetype_text) ) 
16239         goto NOT_FOUND;
16240   if ( ! mp_input_ln(mp, mp->rd_file[n], false) ) {
16241     fclose(mp->rd_file[n]); 
16242         goto NOT_FOUND; 
16243   }
16244   mp->rd_fname[n]=xstrdup(mp->name_of_file);
16245   return true;
16246 NOT_FOUND: 
16247   mp_end_file_reading(mp);
16248   return false;
16249 }
16250
16251 @ Open |wr_file[n]| using file name~|s| and update |wr_fname[n]|.
16252
16253 @<Declarations@>=
16254 void mp_open_write_file (MP mp, char *s, readf_index  n) ;
16255
16256 @ @c void mp_open_write_file (MP mp,char *s, readf_index  n) {
16257   mp_ptr_scan_file(mp, s);
16258   pack_cur_name;
16259   while ( ! mp_a_open_out(mp, &mp->wr_file[n], mp_filetype_text) )
16260     mp_prompt_file_name(mp, "file name for write output","");
16261   mp->wr_fname[n]=xstrdup(mp->name_of_file);
16262 }
16263
16264
16265 @* \[36] Introduction to the parsing routines.
16266 We come now to the central nervous system that sparks many of \MP's activities.
16267 By evaluating expressions, from their primary constituents to ever larger
16268 subexpressions, \MP\ builds the structures that ultimately define complete
16269 pictures or fonts of type.
16270
16271 Four mutually recursive subroutines are involved in this process: We call them
16272 $$\hbox{|scan_primary|, |scan_secondary|, |scan_tertiary|,
16273 and |scan_expression|.}$$
16274 @^recursion@>
16275 Each of them is parameterless and begins with the first token to be scanned
16276 already represented in |cur_cmd|, |cur_mod|, and |cur_sym|. After execution,
16277 the value of the primary or secondary or tertiary or expression that was
16278 found will appear in the global variables |cur_type| and |cur_exp|. The
16279 token following the expression will be represented in |cur_cmd|, |cur_mod|,
16280 and |cur_sym|.
16281
16282 Technically speaking, the parsing algorithms are ``LL(1),'' more or less;
16283 backup mechanisms have been added in order to provide reasonable error
16284 recovery.
16285
16286 @<Glob...@>=
16287 small_number cur_type; /* the type of the expression just found */
16288 integer cur_exp; /* the value of the expression just found */
16289
16290 @ @<Set init...@>=
16291 mp->cur_exp=0;
16292
16293 @ Many different kinds of expressions are possible, so it is wise to have
16294 precise descriptions of what |cur_type| and |cur_exp| mean in all cases:
16295
16296 \smallskip\hang
16297 |cur_type=mp_vacuous| means that this expression didn't turn out to have a
16298 value at all, because it arose from a \&{begingroup}$\,\ldots\,$\&{endgroup}
16299 construction in which there was no expression before the \&{endgroup}.
16300 In this case |cur_exp| has some irrelevant value.
16301
16302 \smallskip\hang
16303 |cur_type=mp_boolean_type| means that |cur_exp| is either |true_code|
16304 or |false_code|.
16305
16306 \smallskip\hang
16307 |cur_type=mp_unknown_boolean| means that |cur_exp| points to a capsule
16308 node that is in the ring of variables equivalent
16309 to at least one undefined boolean variable.
16310
16311 \smallskip\hang
16312 |cur_type=mp_string_type| means that |cur_exp| is a string number (i.e., an
16313 integer in the range |0<=cur_exp<str_ptr|). That string's reference count
16314 includes this particular reference.
16315
16316 \smallskip\hang
16317 |cur_type=mp_unknown_string| means that |cur_exp| points to a capsule
16318 node that is in the ring of variables equivalent
16319 to at least one undefined string variable.
16320
16321 \smallskip\hang
16322 |cur_type=mp_pen_type| means that |cur_exp| points to a node in a pen.  Nobody
16323 else points to any of the nodes in this pen.  The pen may be polygonal or
16324 elliptical.
16325
16326 \smallskip\hang
16327 |cur_type=mp_unknown_pen| means that |cur_exp| points to a capsule
16328 node that is in the ring of variables equivalent
16329 to at least one undefined pen variable.
16330
16331 \smallskip\hang
16332 |cur_type=mp_path_type| means that |cur_exp| points to a the first node of
16333 a path; nobody else points to this particular path. The control points of
16334 the path will have been chosen.
16335
16336 \smallskip\hang
16337 |cur_type=mp_unknown_path| means that |cur_exp| points to a capsule
16338 node that is in the ring of variables equivalent
16339 to at least one undefined path variable.
16340
16341 \smallskip\hang
16342 |cur_type=mp_picture_type| means that |cur_exp| points to an edge header node.
16343 There may be other pointers to this particular set of edges.  The header node
16344 contains a reference count that includes this particular reference.
16345
16346 \smallskip\hang
16347 |cur_type=mp_unknown_picture| means that |cur_exp| points to a capsule
16348 node that is in the ring of variables equivalent
16349 to at least one undefined picture variable.
16350
16351 \smallskip\hang
16352 |cur_type=mp_transform_type| means that |cur_exp| points to a |mp_transform_type|
16353 capsule node. The |value| part of this capsule
16354 points to a transform node that contains six numeric values,
16355 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16356
16357 \smallskip\hang
16358 |cur_type=mp_color_type| means that |cur_exp| points to a |color_type|
16359 capsule node. The |value| part of this capsule
16360 points to a color node that contains three numeric values,
16361 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16362
16363 \smallskip\hang
16364 |cur_type=mp_cmykcolor_type| means that |cur_exp| points to a |mp_cmykcolor_type|
16365 capsule node. The |value| part of this capsule
16366 points to a color node that contains four numeric values,
16367 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16368
16369 \smallskip\hang
16370 |cur_type=mp_pair_type| means that |cur_exp| points to a capsule
16371 node whose type is |mp_pair_type|. The |value| part of this capsule
16372 points to a pair node that contains two numeric values,
16373 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16374
16375 \smallskip\hang
16376 |cur_type=mp_known| means that |cur_exp| is a |scaled| value.
16377
16378 \smallskip\hang
16379 |cur_type=mp_dependent| means that |cur_exp| points to a capsule node whose type
16380 is |dependent|. The |dep_list| field in this capsule points to the associated
16381 dependency list.
16382
16383 \smallskip\hang
16384 |cur_type=mp_proto_dependent| means that |cur_exp| points to a |mp_proto_dependent|
16385 capsule node. The |dep_list| field in this capsule
16386 points to the associated dependency list.
16387
16388 \smallskip\hang
16389 |cur_type=independent| means that |cur_exp| points to a capsule node
16390 whose type is |independent|. This somewhat unusual case can arise, for
16391 example, in the expression
16392 `$x+\&{begingroup}\penalty0\,\&{string}\,x; 0\,\&{endgroup}$'.
16393
16394 \smallskip\hang
16395 |cur_type=mp_token_list| means that |cur_exp| points to a linked list of
16396 tokens. This case arises only on the left-hand side of an assignment
16397 (`\.{:=}') operation, under very special circumstances.
16398
16399 \smallskip\noindent
16400 The possible settings of |cur_type| have been listed here in increasing
16401 numerical order. Notice that |cur_type| will never be |mp_numeric_type| or
16402 |suffixed_macro| or |mp_unsuffixed_macro|, although variables of those types
16403 are allowed.  Conversely, \MP\ has no variables of type |mp_vacuous| or
16404 |token_list|.
16405
16406 @ Capsules are two-word nodes that have a similar meaning
16407 to |cur_type| and |cur_exp|. Such nodes have |name_type=capsule|
16408 and |link<=diov|; and their |type| field is one of the possibilities for
16409 |cur_type| listed above.
16410
16411 The |value| field of a capsule is, in most cases, the value that
16412 corresponds to its |type|, as |cur_exp| corresponds to |cur_type|.
16413 However, when |cur_exp| would point to a capsule,
16414 no extra layer of indirection is present; the |value|
16415 field is what would have been called |value(cur_exp)| if it had not been
16416 encapsulated.  Furthermore, if the type is |dependent| or
16417 |mp_proto_dependent|, the |value| field of a capsule is replaced by
16418 |dep_list| and |prev_dep| fields, since dependency lists in capsules are
16419 always part of the general |dep_list| structure.
16420
16421 The |get_x_next| routine is careful not to change the values of |cur_type|
16422 and |cur_exp| when it gets an expanded token. However, |get_x_next| might
16423 call a macro, which might parse an expression, which might execute lots of
16424 commands in a group; hence it's possible that |cur_type| might change
16425 from, say, |mp_unknown_boolean| to |mp_boolean_type|, or from |dependent| to
16426 |known| or |independent|, during the time |get_x_next| is called. The
16427 programs below are careful to stash sensitive intermediate results in
16428 capsules, so that \MP's generality doesn't cause trouble.
16429
16430 Here's a procedure that illustrates these conventions. It takes
16431 the contents of $(|cur_type|\kern-.3pt,|cur_exp|\kern-.3pt)$
16432 and stashes them away in a
16433 capsule. It is not used when |cur_type=mp_token_list|.
16434 After the operation, |cur_type=mp_vacuous|; hence there is no need to
16435 copy path lists or to update reference counts, etc.
16436
16437 The special link |diov| is put on the capsule returned by
16438 |stash_cur_exp|, because this procedure is used to store macro parameters
16439 that must be easily distinguishable from token lists.
16440
16441 @<Declare the stashing/unstashing routines@>=
16442 pointer mp_stash_cur_exp (MP mp) {
16443   pointer p; /* the capsule that will be returned */
16444   switch (mp->cur_type) {
16445   case unknown_types:
16446   case mp_transform_type:
16447   case mp_color_type:
16448   case mp_pair_type:
16449   case mp_dependent:
16450   case mp_proto_dependent:
16451   case mp_independent: 
16452   case mp_cmykcolor_type:
16453     p=mp->cur_exp;
16454     break;
16455   default: 
16456     p=mp_get_node(mp, value_node_size); name_type(p)=mp_capsule;
16457     type(p)=mp->cur_type; value(p)=mp->cur_exp;
16458     break;
16459   }
16460   mp->cur_type=mp_vacuous; link(p)=diov; 
16461   return p;
16462 }
16463
16464 @ The inverse of |stash_cur_exp| is the following procedure, which
16465 deletes an unnecessary capsule and puts its contents into |cur_type|
16466 and |cur_exp|.
16467
16468 The program steps of \MP\ can be divided into two categories: those in
16469 which |cur_type| and |cur_exp| are ``alive'' and those in which they are
16470 ``dead,'' in the sense that |cur_type| and |cur_exp| contain relevant
16471 information or not. It's important not to ignore them when they're alive,
16472 and it's important not to pay attention to them when they're dead.
16473
16474 There's also an intermediate category: If |cur_type=mp_vacuous|, then
16475 |cur_exp| is irrelevant, hence we can proceed without caring if |cur_type|
16476 and |cur_exp| are alive or dead. In such cases we say that |cur_type|
16477 and |cur_exp| are {\sl dormant}. It is permissible to call |get_x_next|
16478 only when they are alive or dormant.
16479
16480 The \\{stash} procedure above assumes that |cur_type| and |cur_exp|
16481 are alive or dormant. The \\{unstash} procedure assumes that they are
16482 dead or dormant; it resuscitates them.
16483
16484 @<Declare the stashing/unstashing...@>=
16485 void mp_unstash_cur_exp (MP mp,pointer p) ;
16486
16487 @ @c
16488 void mp_unstash_cur_exp (MP mp,pointer p) { 
16489   mp->cur_type=type(p);
16490   switch (mp->cur_type) {
16491   case unknown_types:
16492   case mp_transform_type:
16493   case mp_color_type:
16494   case mp_pair_type:
16495   case mp_dependent: 
16496   case mp_proto_dependent:
16497   case mp_independent:
16498   case mp_cmykcolor_type: 
16499     mp->cur_exp=p;
16500     break;
16501   default:
16502     mp->cur_exp=value(p);
16503     mp_free_node(mp, p,value_node_size);
16504     break;
16505   }
16506 }
16507
16508 @ The following procedure prints the values of expressions in an
16509 abbreviated format. If its first parameter |p| is null, the value of
16510 |(cur_type,cur_exp)| is displayed; otherwise |p| should be a capsule
16511 containing the desired value. The second parameter controls the amount of
16512 output. If it is~0, dependency lists will be abbreviated to
16513 `\.{linearform}' unless they consist of a single term.  If it is greater
16514 than~1, complicated structures (pens, pictures, and paths) will be displayed
16515 in full.
16516
16517 @<Declare subroutines for printing expressions@>=
16518 @<Declare the procedure called |print_dp|@>;
16519 @<Declare the stashing/unstashing routines@>;
16520 void mp_print_exp (MP mp,pointer p, small_number verbosity) {
16521   boolean restore_cur_exp; /* should |cur_exp| be restored? */
16522   small_number t; /* the type of the expression */
16523   pointer q; /* a big node being displayed */
16524   integer v=0; /* the value of the expression */
16525   if ( p!=null ) {
16526     restore_cur_exp=false;
16527   } else { 
16528     p=mp_stash_cur_exp(mp); restore_cur_exp=true;
16529   }
16530   t=type(p);
16531   if ( t<mp_dependent ) v=value(p); else if ( t<mp_independent ) v=dep_list(p);
16532   @<Print an abbreviated value of |v| with format depending on |t|@>;
16533   if ( restore_cur_exp ) mp_unstash_cur_exp(mp, p);
16534 }
16535
16536 @ @<Print an abbreviated value of |v| with format depending on |t|@>=
16537 switch (t) {
16538 case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
16539 case mp_boolean_type:
16540   if ( v==true_code ) mp_print(mp, "true"); else mp_print(mp, "false");
16541   break;
16542 case unknown_types: case mp_numeric_type:
16543   @<Display a variable that's been declared but not defined@>;
16544   break;
16545 case mp_string_type:
16546   mp_print_char(mp, '"'); mp_print_str(mp, v); mp_print_char(mp, '"');
16547   break;
16548 case mp_pen_type: case mp_path_type: case mp_picture_type:
16549   @<Display a complex type@>;
16550   break;
16551 case mp_transform_type: case mp_color_type: case mp_pair_type: case mp_cmykcolor_type:
16552   if ( v==null ) mp_print_type(mp, t);
16553   else @<Display a big node@>;
16554   break;
16555 case mp_known:mp_print_scaled(mp, v); break;
16556 case mp_dependent: case mp_proto_dependent:
16557   mp_print_dp(mp, t,v,verbosity);
16558   break;
16559 case mp_independent:mp_print_variable_name(mp, p); break;
16560 default: mp_confusion(mp, "exp"); break;
16561 @:this can't happen exp}{\quad exp@>
16562 }
16563
16564 @ @<Display a big node@>=
16565
16566   mp_print_char(mp, '('); q=v+mp->big_node_size[t];
16567   do {  
16568     if ( type(v)==mp_known ) mp_print_scaled(mp, value(v));
16569     else if ( type(v)==mp_independent ) mp_print_variable_name(mp, v);
16570     else mp_print_dp(mp, type(v),dep_list(v),verbosity);
16571     v=v+2;
16572     if ( v!=q ) mp_print_char(mp, ',');
16573   } while (v!=q);
16574   mp_print_char(mp, ')');
16575 }
16576
16577 @ Values of type \&{picture}, \&{path}, and \&{pen} are displayed verbosely
16578 in the log file only, unless the user has given a positive value to
16579 \\{tracingonline}.
16580
16581 @<Display a complex type@>=
16582 if ( verbosity<=1 ) {
16583   mp_print_type(mp, t);
16584 } else { 
16585   if ( mp->selector==term_and_log )
16586    if ( mp->internal[tracing_online]<=0 ) {
16587     mp->selector=term_only;
16588     mp_print_type(mp, t); mp_print(mp, " (see the transcript file)");
16589     mp->selector=term_and_log;
16590   };
16591   switch (t) {
16592   case mp_pen_type:mp_print_pen(mp, v,"",false); break;
16593   case mp_path_type:mp_print_path(mp, v,"",false); break;
16594   case mp_picture_type:mp_print_edges(mp, v,"",false); break;
16595   } /* there are no other cases */
16596 }
16597
16598 @ @<Declare the procedure called |print_dp|@>=
16599 void mp_print_dp (MP mp,small_number t, pointer p, 
16600                   small_number verbosity)  {
16601   pointer q; /* the node following |p| */
16602   q=link(p);
16603   if ( (info(q)==null) || (verbosity>0) ) mp_print_dependency(mp, p,t);
16604   else mp_print(mp, "linearform");
16605 }
16606
16607 @ The displayed name of a variable in a ring will not be a capsule unless
16608 the ring consists entirely of capsules.
16609
16610 @<Display a variable that's been declared but not defined@>=
16611 { mp_print_type(mp, t);
16612 if ( v!=null )
16613   { mp_print_char(mp, ' ');
16614   while ( (name_type(v)==mp_capsule) && (v!=p) ) v=value(v);
16615   mp_print_variable_name(mp, v);
16616   };
16617 }
16618
16619 @ When errors are detected during parsing, it is often helpful to
16620 display an expression just above the error message, using |exp_err|
16621 or |disp_err| instead of |print_err|.
16622
16623 @d exp_err(A) mp_disp_err(mp, null,(A)) /* displays the current expression */
16624
16625 @<Declare subroutines for printing expressions@>=
16626 void mp_disp_err (MP mp,pointer p, char *s) { 
16627   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16628   mp_print_nl(mp, ">> ");
16629 @.>>@>
16630   mp_print_exp(mp, p,1); /* ``medium verbose'' printing of the expression */
16631   if (strlen(s)) { 
16632     mp_print_nl(mp, "! "); mp_print(mp, s);
16633 @.!\relax@>
16634   }
16635 }
16636
16637 @ If |cur_type| and |cur_exp| contain relevant information that should
16638 be recycled, we will use the following procedure, which changes |cur_type|
16639 to |known| and stores a given value in |cur_exp|. We can think of |cur_type|
16640 and |cur_exp| as either alive or dormant after this has been done,
16641 because |cur_exp| will not contain a pointer value.
16642
16643 @ @c void mp_flush_cur_exp (MP mp,scaled v) { 
16644   switch (mp->cur_type) {
16645   case unknown_types: case mp_transform_type: case mp_color_type: case mp_pair_type:
16646   case mp_dependent: case mp_proto_dependent: case mp_independent: case mp_cmykcolor_type:
16647     mp_recycle_value(mp, mp->cur_exp); 
16648     mp_free_node(mp, mp->cur_exp,value_node_size);
16649     break;
16650   case mp_string_type:
16651     delete_str_ref(mp->cur_exp); break;
16652   case mp_pen_type: case mp_path_type: 
16653     mp_toss_knot_list(mp, mp->cur_exp); break;
16654   case mp_picture_type:
16655     delete_edge_ref(mp->cur_exp); break;
16656   default: 
16657     break;
16658   }
16659   mp->cur_type=mp_known; mp->cur_exp=v;
16660 }
16661
16662 @ There's a much more general procedure that is capable of releasing
16663 the storage associated with any two-word value packet.
16664
16665 @<Declare the recycling subroutines@>=
16666 void mp_recycle_value (MP mp,pointer p) ;
16667
16668 @ @c void mp_recycle_value (MP mp,pointer p) {
16669   small_number t; /* a type code */
16670   integer vv; /* another value */
16671   pointer q,r,s,pp; /* link manipulation registers */
16672   integer v=0; /* a value */
16673   t=type(p);
16674   if ( t<mp_dependent ) v=value(p);
16675   switch (t) {
16676   case undefined: case mp_vacuous: case mp_boolean_type: case mp_known:
16677   case mp_numeric_type:
16678     break;
16679   case unknown_types:
16680     mp_ring_delete(mp, p); break;
16681   case mp_string_type:
16682     delete_str_ref(v); break;
16683   case mp_path_type: case mp_pen_type:
16684     mp_toss_knot_list(mp, v); break;
16685   case mp_picture_type:
16686     delete_edge_ref(v); break;
16687   case mp_cmykcolor_type: case mp_pair_type: case mp_color_type:
16688   case mp_transform_type:
16689     @<Recycle a big node@>; break; 
16690   case mp_dependent: case mp_proto_dependent:
16691     @<Recycle a dependency list@>; break;
16692   case mp_independent:
16693     @<Recycle an independent variable@>; break;
16694   case mp_token_list: case mp_structured:
16695     mp_confusion(mp, "recycle"); break;
16696 @:this can't happen recycle}{\quad recycle@>
16697   case mp_unsuffixed_macro: case mp_suffixed_macro:
16698     mp_delete_mac_ref(mp, value(p)); break;
16699   } /* there are no other cases */
16700   type(p)=undefined;
16701 }
16702
16703 @ @<Recycle a big node@>=
16704 if ( v!=null ){ 
16705   q=v+mp->big_node_size[t];
16706   do {  
16707     q=q-2; mp_recycle_value(mp, q);
16708   } while (q!=v);
16709   mp_free_node(mp, v,mp->big_node_size[t]);
16710 }
16711
16712 @ @<Recycle a dependency list@>=
16713
16714   q=dep_list(p);
16715   while ( info(q)!=null ) q=link(q);
16716   link(prev_dep(p))=link(q);
16717   prev_dep(link(q))=prev_dep(p);
16718   link(q)=null; mp_flush_node_list(mp, dep_list(p));
16719 }
16720
16721 @ When an independent variable disappears, it simply fades away, unless
16722 something depends on it. In the latter case, a dependent variable whose
16723 coefficient of dependence is maximal will take its place.
16724 The relevant algorithm is due to Ignacio~A. Zabala, who implemented it
16725 as part of his Ph.D. thesis (Stanford University, December 1982).
16726 @^Zabala Salelles, Ignacio Andres@>
16727
16728 For example, suppose that variable $x$ is being recycled, and that the
16729 only variables depending on~$x$ are $y=2x+a$ and $z=x+b$. In this case
16730 we want to make $y$ independent and $z=.5y-.5a+b$; no other variables
16731 will depend on~$y$. If $\\{tracingequations}>0$ in this situation,
16732 we will print `\.{\#\#\# -2x=-y+a}'.
16733
16734 There's a slight complication, however: An independent variable $x$
16735 can occur both in dependency lists and in proto-dependency lists.
16736 This makes it necessary to be careful when deciding which coefficient
16737 is maximal.
16738
16739 Furthermore, this complication is not so slight when
16740 a proto-dependent variable is chosen to become independent. For example,
16741 suppose that $y=2x+100a$ is proto-dependent while $z=x+b$ is dependent;
16742 then we must change $z=.5y-50a+b$ to a proto-dependency, because of the
16743 large coefficient `50'.
16744
16745 In order to deal with these complications without wasting too much time,
16746 we shall link together the occurrences of~$x$ among all the linear
16747 dependencies, maintaining separate lists for the dependent and
16748 proto-dependent cases.
16749
16750 @<Recycle an independent variable@>=
16751
16752   mp->max_c[mp_dependent]=0; mp->max_c[mp_proto_dependent]=0;
16753   mp->max_link[mp_dependent]=null; mp->max_link[mp_proto_dependent]=null;
16754   q=link(dep_head);
16755   while ( q!=dep_head ) { 
16756     s=value_loc(q); /* now |link(s)=dep_list(q)| */
16757     while (1) { 
16758       r=link(s);
16759       if ( info(r)==null ) break;;
16760       if ( info(r)!=p ) { 
16761        s=r;
16762       } else  { 
16763         t=type(q); link(s)=link(r); info(r)=q;
16764         if ( abs(value(r))>mp->max_c[t] ) {
16765           @<Record a new maximum coefficient of type |t|@>;
16766         } else { 
16767           link(r)=mp->max_link[t]; mp->max_link[t]=r;
16768         }
16769       }
16770     }   
16771     q=link(r);
16772   }
16773   if ( (mp->max_c[mp_dependent]>0)||(mp->max_c[mp_proto_dependent]>0) ) {
16774     @<Choose a dependent variable to take the place of the disappearing
16775     independent variable, and change all remaining dependencies
16776     accordingly@>;
16777   }
16778 }
16779
16780 @ The code for independency removal makes use of three two-word arrays.
16781
16782 @<Glob...@>=
16783 integer max_c[mp_proto_dependent+1];  /* max coefficient magnitude */
16784 pointer max_ptr[mp_proto_dependent+1]; /* where |p| occurs with |max_c| */
16785 pointer max_link[mp_proto_dependent+1]; /* other occurrences of |p| */
16786
16787 @ @<Record a new maximum coefficient...@>=
16788
16789   if ( mp->max_c[t]>0 ) {
16790     link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
16791   }
16792   mp->max_c[t]=abs(value(r)); mp->max_ptr[t]=r;
16793 }
16794
16795 @ @<Choose a dependent...@>=
16796
16797   if ( (mp->max_c[mp_dependent] / 010000 >= mp->max_c[mp_proto_dependent]) )
16798     t=mp_dependent;
16799   else 
16800     t=mp_proto_dependent;
16801   @<Determine the dependency list |s| to substitute for the independent
16802     variable~|p|@>;
16803   t=mp_dependent+mp_proto_dependent-t; /* complement |t| */
16804   if ( mp->max_c[t]>0 ) { /* we need to pick up an unchosen dependency */ 
16805     link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
16806   }
16807   if ( t!=mp_dependent ) { @<Substitute new dependencies in place of |p|@>; }
16808   else { @<Substitute new proto-dependencies in place of |p|@>;}
16809   mp_flush_node_list(mp, s);
16810   if ( mp->fix_needed ) mp_fix_dependencies(mp);
16811   check_arith;
16812 }
16813
16814 @ Let |s=max_ptr[t]|. At this point we have $|value|(s)=\pm|max_c|[t]$,
16815 and |info(s)| points to the dependent variable~|pp| of type~|t| from
16816 whose dependency list we have removed node~|s|. We must reinsert
16817 node~|s| into the dependency list, with coefficient $-1.0$, and with
16818 |pp| as the new independent variable. Since |pp| will have a larger serial
16819 number than any other variable, we can put node |s| at the head of the
16820 list.
16821
16822 @<Determine the dep...@>=
16823 s=mp->max_ptr[t]; pp=info(s); v=value(s);
16824 if ( t==mp_dependent ) value(s)=-fraction_one; else value(s)=-unity;
16825 r=dep_list(pp); link(s)=r;
16826 while ( info(r)!=null ) r=link(r);
16827 q=link(r); link(r)=null;
16828 prev_dep(q)=prev_dep(pp); link(prev_dep(pp))=q;
16829 new_indep(pp);
16830 if ( mp->cur_exp==pp ) if ( mp->cur_type==t ) mp->cur_type=mp_independent;
16831 if ( mp->internal[tracing_equations]>0 ) { 
16832   @<Show the transformed dependency@>; 
16833 }
16834
16835 @ Now $(-v)$ times the formerly independent variable~|p| is being replaced
16836 by the dependency list~|s|.
16837
16838 @<Show the transformed...@>=
16839 if ( mp_interesting(mp, p) ) {
16840   mp_begin_diagnostic(mp); mp_print_nl(mp, "### ");
16841 @:]]]\#\#\#_}{\.{\#\#\#}@>
16842   if ( v>0 ) mp_print_char(mp, '-');
16843   if ( t==mp_dependent ) vv=mp_round_fraction(mp, mp->max_c[mp_dependent]);
16844   else vv=mp->max_c[mp_proto_dependent];
16845   if ( vv!=unity ) mp_print_scaled(mp, vv);
16846   mp_print_variable_name(mp, p);
16847   while ( value(p) % s_scale>0 ) {
16848     mp_print(mp, "*4"); value(p)=value(p)-2;
16849   }
16850   if ( t==mp_dependent ) mp_print_char(mp, '='); else mp_print(mp, " = ");
16851   mp_print_dependency(mp, s,t);
16852   mp_end_diagnostic(mp, false);
16853 }
16854
16855 @ Finally, there are dependent and proto-dependent variables whose
16856 dependency lists must be brought up to date.
16857
16858 @<Substitute new dependencies...@>=
16859 for (t=mp_dependent;t<=mp_proto_dependent;t++){ 
16860   r=mp->max_link[t];
16861   while ( r!=null ) {
16862     q=info(r);
16863     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
16864      mp_make_fraction(mp, value(r),-v),s,t,mp_dependent);
16865     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
16866     q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
16867   }
16868 }
16869
16870 @ @<Substitute new proto...@>=
16871 for (t=mp_dependent;t<=mp_proto_dependent;t++) {
16872   r=mp->max_link[t];
16873   while ( r!=null ) {
16874     q=info(r);
16875     if ( t==mp_dependent ) { /* for safety's sake, we change |q| to |mp_proto_dependent| */
16876       if ( mp->cur_exp==q ) if ( mp->cur_type==mp_dependent )
16877         mp->cur_type=mp_proto_dependent;
16878       dep_list(q)=mp_p_over_v(mp, dep_list(q),unity,mp_dependent,mp_proto_dependent);
16879       type(q)=mp_proto_dependent; value(r)=mp_round_fraction(mp, value(r));
16880     }
16881     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
16882       mp_make_scaled(mp, value(r),-v),s,mp_proto_dependent,mp_proto_dependent);
16883     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
16884     q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
16885   }
16886 }
16887
16888 @ Here are some routines that provide handy combinations of actions
16889 that are often needed during error recovery. For example,
16890 `|flush_error|' flushes the current expression, replaces it by
16891 a given value, and calls |error|.
16892
16893 Errors often are detected after an extra token has already been scanned.
16894 The `\\{put\_get}' routines put that token back before calling |error|;
16895 then they get it back again. (Or perhaps they get another token, if
16896 the user has changed things.)
16897
16898 @<Declarations@>=
16899 void mp_flush_error (MP mp,scaled v);
16900 void mp_put_get_error (MP mp);
16901 void mp_put_get_flush_error (MP mp,scaled v) ;
16902
16903 @ @c
16904 void mp_flush_error (MP mp,scaled v) { 
16905   mp_error(mp); mp_flush_cur_exp(mp, v); 
16906 }
16907 void mp_put_get_error (MP mp) { 
16908   mp_back_error(mp); mp_get_x_next(mp); 
16909 }
16910 void mp_put_get_flush_error (MP mp,scaled v) { 
16911   mp_put_get_error(mp);
16912   mp_flush_cur_exp(mp, v); 
16913 }
16914
16915 @ A global variable |var_flag| is set to a special command code
16916 just before \MP\ calls |scan_expression|, if the expression should be
16917 treated as a variable when this command code immediately follows. For
16918 example, |var_flag| is set to |assignment| at the beginning of a
16919 statement, because we want to know the {\sl location\/} of a variable at
16920 the left of `\.{:=}', not the {\sl value\/} of that variable.
16921
16922 The |scan_expression| subroutine calls |scan_tertiary|,
16923 which calls |scan_secondary|, which calls |scan_primary|, which sets
16924 |var_flag:=0|. In this way each of the scanning routines ``knows''
16925 when it has been called with a special |var_flag|, but |var_flag| is
16926 usually zero.
16927
16928 A variable preceding a command that equals |var_flag| is converted to a
16929 token list rather than a value. Furthermore, an `\.{=}' sign following an
16930 expression with |var_flag=assignment| is not considered to be a relation
16931 that produces boolean expressions.
16932
16933
16934 @<Glob...@>=
16935 int var_flag; /* command that wants a variable */
16936
16937 @ @<Set init...@>=
16938 mp->var_flag=0;
16939
16940 @* \[37] Parsing primary expressions.
16941 The first parsing routine, |scan_primary|, is also the most complicated one,
16942 since it involves so many different cases. But each case---with one
16943 exception---is fairly simple by itself.
16944
16945 When |scan_primary| begins, the first token of the primary to be scanned
16946 should already appear in |cur_cmd|, |cur_mod|, and |cur_sym|. The values
16947 of |cur_type| and |cur_exp| should be either dead or dormant, as explained
16948 earlier. If |cur_cmd| is not between |min_primary_command| and
16949 |max_primary_command|, inclusive, a syntax error will be signaled.
16950
16951 @<Declare the basic parsing subroutines@>=
16952 void mp_scan_primary (MP mp) {
16953   pointer p,q,r; /* for list manipulation */
16954   quarterword c; /* a primitive operation code */
16955   int my_var_flag; /* initial value of |my_var_flag| */
16956   pointer l_delim,r_delim; /* hash addresses of a delimiter pair */
16957   @<Other local variables for |scan_primary|@>;
16958   my_var_flag=mp->var_flag; mp->var_flag=0;
16959 RESTART:
16960   check_arith;
16961   @<Supply diagnostic information, if requested@>;
16962   switch (mp->cur_cmd) {
16963   case left_delimiter:
16964     @<Scan a delimited primary@>; break;
16965   case begin_group:
16966     @<Scan a grouped primary@>; break;
16967   case string_token:
16968     @<Scan a string constant@>; break;
16969   case numeric_token:
16970     @<Scan a primary that starts with a numeric token@>; break;
16971   case nullary:
16972     @<Scan a nullary operation@>; break;
16973   case unary: case type_name: case cycle: case plus_or_minus:
16974     @<Scan a unary operation@>; break;
16975   case primary_binary:
16976     @<Scan a binary operation with `\&{of}' between its operands@>; break;
16977   case str_op:
16978     @<Convert a suffix to a string@>; break;
16979   case internal_quantity:
16980     @<Scan an internal numeric quantity@>; break;
16981   case capsule_token:
16982     mp_make_exp_copy(mp, mp->cur_mod); break;
16983   case tag_token:
16984     @<Scan a variable primary; |goto restart| if it turns out to be a macro@>; break;
16985   default: 
16986     mp_bad_exp(mp, "A primary"); goto RESTART; break;
16987 @.A primary expression...@>
16988   }
16989   mp_get_x_next(mp); /* the routines |goto done| if they don't want this */
16990 DONE: 
16991   if ( mp->cur_cmd==left_bracket ) {
16992     if ( mp->cur_type>=mp_known ) {
16993       @<Scan a mediation construction@>;
16994     }
16995   }
16996 }
16997
16998
16999
17000 @ Errors at the beginning of expressions are flagged by |bad_exp|.
17001
17002 @c void mp_bad_exp (MP mp,char * s) {
17003   int save_flag;
17004   print_err(s); mp_print(mp, " expression can't begin with `");
17005   mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); 
17006   mp_print_char(mp, '\'');
17007   help4("I'm afraid I need some sort of value in order to continue,")
17008     ("so I've tentatively inserted `0'. You may want to")
17009     ("delete this zero and insert something else;")
17010     ("see Chapter 27 of The METAFONTbook for an example.");
17011 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
17012   mp_back_input(mp); mp->cur_sym=0; mp->cur_cmd=numeric_token; 
17013   mp->cur_mod=0; mp_ins_error(mp);
17014   save_flag=mp->var_flag; mp->var_flag=0; mp_get_x_next(mp);
17015   mp->var_flag=save_flag;
17016 }
17017
17018 @ @<Supply diagnostic information, if requested@>=
17019 #ifdef DEBUG
17020 if ( mp->panicking ) mp_check_mem(mp, false);
17021 #endif
17022 if ( mp->interrupt!=0 ) if ( mp->OK_to_interrupt ) {
17023   mp_back_input(mp); check_interrupt; mp_get_x_next(mp);
17024 }
17025
17026 @ @<Scan a delimited primary@>=
17027
17028   l_delim=mp->cur_sym; r_delim=mp->cur_mod; 
17029   mp_get_x_next(mp); mp_scan_expression(mp);
17030   if ( (mp->cur_cmd==comma) && (mp->cur_type>=mp_known) ) {
17031     @<Scan the rest of a delimited set of numerics@>;
17032   } else {
17033     mp_check_delimiter(mp, l_delim,r_delim);
17034   }
17035 }
17036
17037 @ The |stash_in| subroutine puts the current (numeric) expression into a field
17038 within a ``big node.''
17039
17040 @c void mp_stash_in (MP mp,pointer p) {
17041   pointer q; /* temporary register */
17042   type(p)=mp->cur_type;
17043   if ( mp->cur_type==mp_known ) {
17044     value(p)=mp->cur_exp;
17045   } else { 
17046     if ( mp->cur_type==mp_independent ) {
17047       @<Stash an independent |cur_exp| into a big node@>;
17048     } else { 
17049       mp->mem[value_loc(p)]=mp->mem[value_loc(mp->cur_exp)];
17050       /* |dep_list(p):=dep_list(cur_exp)| and |prev_dep(p):=prev_dep(cur_exp)| */
17051       link(prev_dep(p))=p;
17052     }
17053     mp_free_node(mp, mp->cur_exp,value_node_size);
17054   }
17055   mp->cur_type=mp_vacuous;
17056 }
17057
17058 @ In rare cases the current expression can become |independent|. There
17059 may be many dependency lists pointing to such an independent capsule,
17060 so we can't simply move it into place within a big node. Instead,
17061 we copy it, then recycle it.
17062
17063 @ @<Stash an independent |cur_exp|...@>=
17064
17065   q=mp_single_dependency(mp, mp->cur_exp);
17066   if ( q==mp->dep_final ){ 
17067     type(p)=mp_known; value(p)=0; mp_free_node(mp, q,dep_node_size);
17068   } else { 
17069     type(p)=mp_dependent; mp_new_dep(mp, p,q);
17070   }
17071   mp_recycle_value(mp, mp->cur_exp);
17072 }
17073
17074 @ This code uses the fact that |red_part_loc| and |green_part_loc|
17075 are synonymous with |x_part_loc| and |y_part_loc|.
17076
17077 @<Scan the rest of a delimited set of numerics@>=
17078
17079 p=mp_stash_cur_exp(mp);
17080 mp_get_x_next(mp); mp_scan_expression(mp);
17081 @<Make sure the second part of a pair or color has a numeric type@>;
17082 q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
17083 if ( mp->cur_cmd==comma ) type(q)=mp_color_type;
17084 else type(q)=mp_pair_type;
17085 mp_init_big_node(mp, q); r=value(q);
17086 mp_stash_in(mp, y_part_loc(r));
17087 mp_unstash_cur_exp(mp, p);
17088 mp_stash_in(mp, x_part_loc(r));
17089 if ( mp->cur_cmd==comma ) {
17090   @<Scan the last of a triplet of numerics@>;
17091 }
17092 if ( mp->cur_cmd==comma ) {
17093   type(q)=mp_cmykcolor_type;
17094   mp_init_big_node(mp, q); t=value(q);
17095   mp->mem[cyan_part_loc(t)]=mp->mem[red_part_loc(r)];
17096   value(cyan_part_loc(t))=value(red_part_loc(r));
17097   mp->mem[magenta_part_loc(t)]=mp->mem[green_part_loc(r)];
17098   value(magenta_part_loc(t))=value(green_part_loc(r));
17099   mp->mem[yellow_part_loc(t)]=mp->mem[blue_part_loc(r)];
17100   value(yellow_part_loc(t))=value(blue_part_loc(r));
17101   mp_recycle_value(mp, r);
17102   r=t;
17103   @<Scan the last of a quartet of numerics@>;
17104 }
17105 mp_check_delimiter(mp, l_delim,r_delim);
17106 mp->cur_type=type(q);
17107 mp->cur_exp=q;
17108 }
17109
17110 @ @<Make sure the second part of a pair or color has a numeric type@>=
17111 if ( mp->cur_type<mp_known ) {
17112   exp_err("Nonnumeric ypart has been replaced by 0");
17113 @.Nonnumeric...replaced by 0@>
17114   help4("I've started to scan a pair `(a,b)' or a color `(a,b,c)';")
17115     ("but after finding a nice `a' I found a `b' that isn't")
17116     ("of numeric type. So I've changed that part to zero.")
17117     ("(The b that I didn't like appears above the error message.)");
17118   mp_put_get_flush_error(mp, 0);
17119 }
17120
17121 @ @<Scan the last of a triplet of numerics@>=
17122
17123   mp_get_x_next(mp); mp_scan_expression(mp);
17124   if ( mp->cur_type<mp_known ) {
17125     exp_err("Nonnumeric third part has been replaced by 0");
17126 @.Nonnumeric...replaced by 0@>
17127     help3("I've just scanned a color `(a,b,c)' or cmykcolor(a,b,c,d); but the `c'")
17128       ("isn't of numeric type. So I've changed that part to zero.")
17129       ("(The c that I didn't like appears above the error message.)");
17130     mp_put_get_flush_error(mp, 0);
17131   }
17132   mp_stash_in(mp, blue_part_loc(r));
17133 }
17134
17135 @ @<Scan the last of a quartet of numerics@>=
17136
17137   mp_get_x_next(mp); mp_scan_expression(mp);
17138   if ( mp->cur_type<mp_known ) {
17139     exp_err("Nonnumeric blackpart has been replaced by 0");
17140 @.Nonnumeric...replaced by 0@>
17141     help3("I've just scanned a cmykcolor `(c,m,y,k)'; but the `k' isn't")
17142       ("of numeric type. So I've changed that part to zero.")
17143       ("(The k that I didn't like appears above the error message.)");
17144     mp_put_get_flush_error(mp, 0);
17145   }
17146   mp_stash_in(mp, black_part_loc(r));
17147 }
17148
17149 @ The local variable |group_line| keeps track of the line
17150 where a \&{begingroup} command occurred; this will be useful
17151 in an error message if the group doesn't actually end.
17152
17153 @<Other local variables for |scan_primary|@>=
17154 integer group_line; /* where a group began */
17155
17156 @ @<Scan a grouped primary@>=
17157
17158   group_line=mp_true_line(mp);
17159   if ( mp->internal[tracing_commands]>0 ) show_cur_cmd_mod;
17160   save_boundary_item(p);
17161   do {  
17162     mp_do_statement(mp); /* ends with |cur_cmd>=semicolon| */
17163   } while (! (mp->cur_cmd!=semicolon));
17164   if ( mp->cur_cmd!=end_group ) {
17165     print_err("A group begun on line ");
17166 @.A group...never ended@>
17167     mp_print_int(mp, group_line);
17168     mp_print(mp, " never ended");
17169     help2("I saw a `begingroup' back there that hasn't been matched")
17170          ("by `endgroup'. So I've inserted `endgroup' now.");
17171     mp_back_error(mp); mp->cur_cmd=end_group;
17172   }
17173   mp_unsave(mp); 
17174     /* this might change |cur_type|, if independent variables are recycled */
17175   if ( mp->internal[tracing_commands]>0 ) show_cur_cmd_mod;
17176 }
17177
17178 @ @<Scan a string constant@>=
17179
17180   mp->cur_type=mp_string_type; mp->cur_exp=mp->cur_mod;
17181 }
17182
17183 @ Later we'll come to procedures that perform actual operations like
17184 addition, square root, and so on; our purpose now is to do the parsing.
17185 But we might as well mention those future procedures now, so that the
17186 suspense won't be too bad:
17187
17188 \smallskip
17189 |do_nullary(c)| does primitive operations that have no operands (e.g.,
17190 `\&{true}' or `\&{pencircle}');
17191
17192 \smallskip
17193 |do_unary(c)| applies a primitive operation to the current expression;
17194
17195 \smallskip
17196 |do_binary(p,c)| applies a primitive operation to the capsule~|p|
17197 and the current expression.
17198
17199 @<Scan a nullary operation@>=mp_do_nullary(mp, mp->cur_mod)
17200
17201 @ @<Scan a unary operation@>=
17202
17203   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_primary(mp); 
17204   mp_do_unary(mp, c); goto DONE;
17205 }
17206
17207 @ A numeric token might be a primary by itself, or it might be the
17208 numerator of a fraction composed solely of numeric tokens, or it might
17209 multiply the primary that follows (provided that the primary doesn't begin
17210 with a plus sign or a minus sign). The code here uses the facts that
17211 |max_primary_command=plus_or_minus| and
17212 |max_primary_command-1=numeric_token|. If a fraction is found that is less
17213 than unity, we try to retain higher precision when we use it in scalar
17214 multiplication.
17215
17216 @<Other local variables for |scan_primary|@>=
17217 scaled num,denom; /* for primaries that are fractions, like `1/2' */
17218
17219 @ @<Scan a primary that starts with a numeric token@>=
17220
17221   mp->cur_exp=mp->cur_mod; mp->cur_type=mp_known; mp_get_x_next(mp);
17222   if ( mp->cur_cmd!=slash ) { 
17223     num=0; denom=0;
17224   } else { 
17225     mp_get_x_next(mp);
17226     if ( mp->cur_cmd!=numeric_token ) { 
17227       mp_back_input(mp);
17228       mp->cur_cmd=slash; mp->cur_mod=over; mp->cur_sym=frozen_slash;
17229       goto DONE;
17230     }
17231     num=mp->cur_exp; denom=mp->cur_mod;
17232     if ( denom==0 ) { @<Protest division by zero@>; }
17233     else { mp->cur_exp=mp_make_scaled(mp, num,denom); }
17234     check_arith; mp_get_x_next(mp);
17235   }
17236   if ( mp->cur_cmd>=min_primary_command ) {
17237    if ( mp->cur_cmd<numeric_token ) { /* in particular, |cur_cmd<>plus_or_minus| */
17238      p=mp_stash_cur_exp(mp); mp_scan_primary(mp);
17239      if ( (abs(num)>=abs(denom))||(mp->cur_type<mp_color_type) ) {
17240        mp_do_binary(mp, p,times);
17241      } else {
17242        mp_frac_mult(mp, num,denom);
17243        mp_free_node(mp, p,value_node_size);
17244      }
17245     }
17246   }
17247   goto DONE;
17248 }
17249
17250 @ @<Protest division...@>=
17251
17252   print_err("Division by zero");
17253 @.Division by zero@>
17254   help1("I'll pretend that you meant to divide by 1."); mp_error(mp);
17255 }
17256
17257 @ @<Scan a binary operation with `\&{of}' between its operands@>=
17258
17259   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
17260   if ( mp->cur_cmd!=of_token ) {
17261     mp_missing_err(mp, "of"); mp_print(mp, " for "); 
17262     mp_print_cmd_mod(mp, primary_binary,c);
17263 @.Missing `of'@>
17264     help1("I've got the first argument; will look now for the other.");
17265     mp_back_error(mp);
17266   }
17267   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_primary(mp); 
17268   mp_do_binary(mp, p,c); goto DONE;
17269 }
17270
17271 @ @<Convert a suffix to a string@>=
17272
17273   mp_get_x_next(mp); mp_scan_suffix(mp); 
17274   mp->old_setting=mp->selector; mp->selector=new_string;
17275   mp_show_token_list(mp, mp->cur_exp,null,100000,0); 
17276   mp_flush_token_list(mp, mp->cur_exp);
17277   mp->cur_exp=mp_make_string(mp); mp->selector=mp->old_setting; 
17278   mp->cur_type=mp_string_type;
17279   goto DONE;
17280 }
17281
17282 @ If an internal quantity appears all by itself on the left of an
17283 assignment, we return a token list of length one, containing the address
17284 of the internal quantity plus |hash_end|. (This accords with the conventions
17285 of the save stack, as described earlier.)
17286
17287 @<Scan an internal...@>=
17288
17289   q=mp->cur_mod;
17290   if ( my_var_flag==assignment ) {
17291     mp_get_x_next(mp);
17292     if ( mp->cur_cmd==assignment ) {
17293       mp->cur_exp=mp_get_avail(mp);
17294       info(mp->cur_exp)=q+hash_end; mp->cur_type=mp_token_list; 
17295       goto DONE;
17296     }
17297     mp_back_input(mp);
17298   }
17299   mp->cur_type=mp_known; mp->cur_exp=mp->internal[q];
17300 }
17301
17302 @ The most difficult part of |scan_primary| has been saved for last, since
17303 it was necessary to build up some confidence first. We can now face the task
17304 of scanning a variable.
17305
17306 As we scan a variable, we build a token list containing the relevant
17307 names and subscript values, simultaneously following along in the
17308 ``collective'' structure to see if we are actually dealing with a macro
17309 instead of a value.
17310
17311 The local variables |pre_head| and |post_head| will point to the beginning
17312 of the prefix and suffix lists; |tail| will point to the end of the list
17313 that is currently growing.
17314
17315 Another local variable, |tt|, contains partial information about the
17316 declared type of the variable-so-far. If |tt>=mp_unsuffixed_macro|, the
17317 relation |tt=type(q)| will always hold. If |tt=undefined|, the routine
17318 doesn't bother to update its information about type. And if
17319 |undefined<tt<mp_unsuffixed_macro|, the precise value of |tt| isn't critical.
17320
17321 @ @<Other local variables for |scan_primary|@>=
17322 pointer pre_head,post_head,tail;
17323   /* prefix and suffix list variables */
17324 small_number tt; /* approximation to the type of the variable-so-far */
17325 pointer t; /* a token */
17326 pointer macro_ref = 0; /* reference count for a suffixed macro */
17327
17328 @ @<Scan a variable primary...@>=
17329
17330   fast_get_avail(pre_head); tail=pre_head; post_head=null; tt=mp_vacuous;
17331   while (1) { 
17332     t=mp_cur_tok(mp); link(tail)=t;
17333     if ( tt!=undefined ) {
17334        @<Find the approximate type |tt| and corresponding~|q|@>;
17335       if ( tt>=mp_unsuffixed_macro ) {
17336         @<Either begin an unsuffixed macro call or
17337           prepare for a suffixed one@>;
17338       }
17339     }
17340     mp_get_x_next(mp); tail=t;
17341     if ( mp->cur_cmd==left_bracket ) {
17342       @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>;
17343     }
17344     if ( mp->cur_cmd>max_suffix_token ) break;
17345     if ( mp->cur_cmd<min_suffix_token ) break;
17346   } /* now |cur_cmd| is |internal_quantity|, |tag_token|, or |numeric_token| */
17347   @<Handle unusual cases that masquerade as variables, and |goto restart|
17348     or |goto done| if appropriate;
17349     otherwise make a copy of the variable and |goto done|@>;
17350 }
17351
17352 @ @<Either begin an unsuffixed macro call or...@>=
17353
17354   link(tail)=null;
17355   if ( tt>mp_unsuffixed_macro ) { /* |tt=mp_suffixed_macro| */
17356     post_head=mp_get_avail(mp); tail=post_head; link(tail)=t;
17357     tt=undefined; macro_ref=value(q); add_mac_ref(macro_ref);
17358   } else {
17359     @<Set up unsuffixed macro call and |goto restart|@>;
17360   }
17361 }
17362
17363 @ @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>=
17364
17365   mp_get_x_next(mp); mp_scan_expression(mp);
17366   if ( mp->cur_cmd!=right_bracket ) {
17367     @<Put the left bracket and the expression back to be rescanned@>;
17368   } else { 
17369     if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17370     mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp; mp->cur_sym=0;
17371   }
17372 }
17373
17374 @ The left bracket that we thought was introducing a subscript might have
17375 actually been the left bracket in a mediation construction like `\.{x[a,b]}'.
17376 So we don't issue an error message at this point; but we do want to back up
17377 so as to avoid any embarrassment about our incorrect assumption.
17378
17379 @<Put the left bracket and the expression back to be rescanned@>=
17380
17381   mp_back_input(mp); /* that was the token following the current expression */
17382   mp_back_expr(mp); mp->cur_cmd=left_bracket; 
17383   mp->cur_mod=0; mp->cur_sym=frozen_left_bracket;
17384 }
17385
17386 @ Here's a routine that puts the current expression back to be read again.
17387
17388 @c void mp_back_expr (MP mp) {
17389   pointer p; /* capsule token */
17390   p=mp_stash_cur_exp(mp); link(p)=null; back_list(p);
17391 }
17392
17393 @ Unknown subscripts lead to the following error message.
17394
17395 @c void mp_bad_subscript (MP mp) { 
17396   exp_err("Improper subscript has been replaced by zero");
17397 @.Improper subscript...@>
17398   help3("A bracketed subscript must have a known numeric value;")
17399     ("unfortunately, what I found was the value that appears just")
17400     ("above this error message. So I'll try a zero subscript.");
17401   mp_flush_error(mp, 0);
17402 }
17403
17404 @ Every time we call |get_x_next|, there's a chance that the variable we've
17405 been looking at will disappear. Thus, we cannot safely keep |q| pointing
17406 into the variable structure; we need to start searching from the root each time.
17407
17408 @<Find the approximate type |tt| and corresponding~|q|@>=
17409 @^inner loop@>
17410
17411   p=link(pre_head); q=info(p); tt=undefined;
17412   if ( eq_type(q) % outer_tag==tag_token ) {
17413     q=equiv(q);
17414     if ( q==null ) goto DONE2;
17415     while (1) { 
17416       p=link(p);
17417       if ( p==null ) {
17418         tt=type(q); goto DONE2;
17419       };
17420       if ( type(q)!=mp_structured ) goto DONE2;
17421       q=link(attr_head(q)); /* the |collective_subscript| attribute */
17422       if ( p>=mp->hi_mem_min ) { /* it's not a subscript */
17423         do {  q=link(q); } while (! (attr_loc(q)>=info(p)));
17424         if ( attr_loc(q)>info(p) ) goto DONE2;
17425       }
17426     }
17427   }
17428 DONE2:
17429   ;
17430 }
17431
17432 @ How do things stand now? Well, we have scanned an entire variable name,
17433 including possible subscripts and/or attributes; |cur_cmd|, |cur_mod|, and
17434 |cur_sym| represent the token that follows. If |post_head=null|, a
17435 token list for this variable name starts at |link(pre_head)|, with all
17436 subscripts evaluated. But if |post_head<>null|, the variable turned out
17437 to be a suffixed macro; |pre_head| is the head of the prefix list, while
17438 |post_head| is the head of a token list containing both `\.{\AT!}' and
17439 the suffix.
17440
17441 Our immediate problem is to see if this variable still exists. (Variable
17442 structures can change drastically whenever we call |get_x_next|; users
17443 aren't supposed to do this, but the fact that it is possible means that
17444 we must be cautious.)
17445
17446 The following procedure prints an error message when a variable
17447 unexpectedly disappears. Its help message isn't quite right for
17448 our present purposes, but we'll be able to fix that up.
17449
17450 @c 
17451 void mp_obliterated (MP mp,pointer q) { 
17452   print_err("Variable "); mp_show_token_list(mp, q,null,1000,0);
17453   mp_print(mp, " has been obliterated");
17454 @.Variable...obliterated@>
17455   help5("It seems you did a nasty thing---probably by accident,")
17456     ("but nevertheless you nearly hornswoggled me...")
17457     ("While I was evaluating the right-hand side of this")
17458     ("command, something happened, and the left-hand side")
17459     ("is no longer a variable! So I won't change anything.");
17460 }
17461
17462 @ If the variable does exist, we also need to check
17463 for a few other special cases before deciding that a plain old ordinary
17464 variable has, indeed, been scanned.
17465
17466 @<Handle unusual cases that masquerade as variables...@>=
17467 if ( post_head!=null ) {
17468   @<Set up suffixed macro call and |goto restart|@>;
17469 }
17470 q=link(pre_head); free_avail(pre_head);
17471 if ( mp->cur_cmd==my_var_flag ) { 
17472   mp->cur_type=mp_token_list; mp->cur_exp=q; goto DONE;
17473 }
17474 p=mp_find_variable(mp, q);
17475 if ( p!=null ) {
17476   mp_make_exp_copy(mp, p);
17477 } else { 
17478   mp_obliterated(mp, q);
17479   mp->help_line[2]="While I was evaluating the suffix of this variable,";
17480   mp->help_line[1]="something was redefined, and it's no longer a variable!";
17481   mp->help_line[0]="In order to get back on my feet, I've inserted `0' instead.";
17482   mp_put_get_flush_error(mp, 0);
17483 }
17484 mp_flush_node_list(mp, q); 
17485 goto DONE
17486
17487 @ The only complication associated with macro calling is that the prefix
17488 and ``at'' parameters must be packaged in an appropriate list of lists.
17489
17490 @<Set up unsuffixed macro call and |goto restart|@>=
17491
17492   p=mp_get_avail(mp); info(pre_head)=link(pre_head); link(pre_head)=p;
17493   info(p)=t; mp_macro_call(mp, value(q),pre_head,null);
17494   mp_get_x_next(mp); 
17495   goto RESTART;
17496 }
17497
17498 @ If the ``variable'' that turned out to be a suffixed macro no longer exists,
17499 we don't care, because we have reserved a pointer (|macro_ref|) to its
17500 token list.
17501
17502 @<Set up suffixed macro call and |goto restart|@>=
17503
17504   mp_back_input(mp); p=mp_get_avail(mp); q=link(post_head);
17505   info(pre_head)=link(pre_head); link(pre_head)=post_head;
17506   info(post_head)=q; link(post_head)=p; info(p)=link(q); link(q)=null;
17507   mp_macro_call(mp, macro_ref,pre_head,null); decr(ref_count(macro_ref));
17508   mp_get_x_next(mp); goto RESTART;
17509 }
17510
17511 @ Our remaining job is simply to make a copy of the value that has been
17512 found. Some cases are harder than others, but complexity arises solely
17513 because of the multiplicity of possible cases.
17514
17515 @<Declare the procedure called |make_exp_copy|@>=
17516 @<Declare subroutines needed by |make_exp_copy|@>;
17517 void mp_make_exp_copy (MP mp,pointer p) {
17518   pointer q,r,t; /* registers for list manipulation */
17519 RESTART: 
17520   mp->cur_type=type(p);
17521   switch (mp->cur_type) {
17522   case mp_vacuous: case mp_boolean_type: case mp_known:
17523     mp->cur_exp=value(p); break;
17524   case unknown_types:
17525     mp->cur_exp=mp_new_ring_entry(mp, p);
17526     break;
17527   case mp_string_type: 
17528     mp->cur_exp=value(p); add_str_ref(mp->cur_exp);
17529     break;
17530   case mp_picture_type:
17531     mp->cur_exp=value(p);add_edge_ref(mp->cur_exp);
17532     break;
17533   case mp_pen_type:
17534     mp->cur_exp=copy_pen(value(p));
17535     break; 
17536   case mp_path_type:
17537     mp->cur_exp=mp_copy_path(mp, value(p));
17538     break;
17539   case mp_transform_type: case mp_color_type: 
17540   case mp_cmykcolor_type: case mp_pair_type:
17541     @<Copy the big node |p|@>;
17542     break;
17543   case mp_dependent: case mp_proto_dependent:
17544     mp_encapsulate(mp, mp_copy_dep_list(mp, dep_list(p)));
17545     break;
17546   case mp_numeric_type: 
17547     new_indep(p); goto RESTART;
17548     break;
17549   case mp_independent: 
17550     q=mp_single_dependency(mp, p);
17551     if ( q==mp->dep_final ){ 
17552       mp->cur_type=mp_known; mp->cur_exp=0; mp_free_node(mp, q,value_node_size);
17553     } else { 
17554       mp->cur_type=mp_dependent; mp_encapsulate(mp, q);
17555     }
17556     break;
17557   default: 
17558     mp_confusion(mp, "copy");
17559 @:this can't happen copy}{\quad copy@>
17560     break;
17561   }
17562 }
17563
17564 @ The |encapsulate| subroutine assumes that |dep_final| is the
17565 tail of dependency list~|p|.
17566
17567 @<Declare subroutines needed by |make_exp_copy|@>=
17568 void mp_encapsulate (MP mp,pointer p) { 
17569   mp->cur_exp=mp_get_node(mp, value_node_size); type(mp->cur_exp)=mp->cur_type;
17570   name_type(mp->cur_exp)=mp_capsule; mp_new_dep(mp, mp->cur_exp,p);
17571 }
17572
17573 @ The most tedious case arises when the user refers to a
17574 \&{pair}, \&{color}, or \&{transform} variable; we must copy several fields,
17575 each of which can be |independent|, |dependent|, |mp_proto_dependent|,
17576 or |known|.
17577
17578 @<Copy the big node |p|@>=
17579
17580   if ( value(p)==null ) 
17581     mp_init_big_node(mp, p);
17582   t=mp_get_node(mp, value_node_size); name_type(t)=mp_capsule; type(t)=mp->cur_type;
17583   mp_init_big_node(mp, t);
17584   q=value(p)+mp->big_node_size[mp->cur_type]; 
17585   r=value(t)+mp->big_node_size[mp->cur_type];
17586   do {  
17587     q=q-2; r=r-2; mp_install(mp, r,q);
17588   } while (q!=value(p));
17589   mp->cur_exp=t;
17590 }
17591
17592 @ The |install| procedure copies a numeric field~|q| into field~|r| of
17593 a big node that will be part of a capsule.
17594
17595 @<Declare subroutines needed by |make_exp_copy|@>=
17596 void mp_install (MP mp,pointer r, pointer q) {
17597   pointer p; /* temporary register */
17598   if ( type(q)==mp_known ){ 
17599     value(r)=value(q); type(r)=mp_known;
17600   } else  if ( type(q)==mp_independent ) {
17601     p=mp_single_dependency(mp, q);
17602     if ( p==mp->dep_final ) {
17603       type(r)=mp_known; value(r)=0; mp_free_node(mp, p,value_node_size);
17604     } else  { 
17605       type(r)=mp_dependent; mp_new_dep(mp, r,p);
17606     }
17607   } else {
17608     type(r)=type(q); mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(q)));
17609   }
17610 }
17611
17612 @ Expressions of the form `\.{a[b,c]}' are converted into
17613 `\.{b+a*(c-b)}', without checking the types of \.b~or~\.c,
17614 provided that \.a is numeric.
17615
17616 @<Scan a mediation...@>=
17617
17618   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17619   if ( mp->cur_cmd!=comma ) {
17620     @<Put the left bracket and the expression back...@>;
17621     mp_unstash_cur_exp(mp, p);
17622   } else { 
17623     q=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17624     if ( mp->cur_cmd!=right_bracket ) {
17625       mp_missing_err(mp, "]");
17626 @.Missing `]'@>
17627       help3("I've scanned an expression of the form `a[b,c',")
17628       ("so a right bracket should have come next.")
17629       ("I shall pretend that one was there.");
17630       mp_back_error(mp);
17631     }
17632     r=mp_stash_cur_exp(mp); mp_make_exp_copy(mp, q);
17633     mp_do_binary(mp, r,minus); mp_do_binary(mp, p,times); 
17634     mp_do_binary(mp, q,plus); mp_get_x_next(mp);
17635   }
17636 }
17637
17638 @ Here is a comparatively simple routine that is used to scan the
17639 \&{suffix} parameters of a macro.
17640
17641 @<Declare the basic parsing subroutines@>=
17642 void mp_scan_suffix (MP mp) {
17643   pointer h,t; /* head and tail of the list being built */
17644   pointer p; /* temporary register */
17645   h=mp_get_avail(mp); t=h;
17646   while (1) { 
17647     if ( mp->cur_cmd==left_bracket ) {
17648       @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>;
17649     }
17650     if ( mp->cur_cmd==numeric_token ) {
17651       p=mp_new_num_tok(mp, mp->cur_mod);
17652     } else if ((mp->cur_cmd==tag_token)||(mp->cur_cmd==internal_quantity) ) {
17653        p=mp_get_avail(mp); info(p)=mp->cur_sym;
17654     } else {
17655       break;
17656     }
17657     link(t)=p; t=p; mp_get_x_next(mp);
17658   }
17659   mp->cur_exp=link(h); free_avail(h); mp->cur_type=mp_token_list;
17660 }
17661
17662 @ @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>=
17663
17664   mp_get_x_next(mp); mp_scan_expression(mp);
17665   if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17666   if ( mp->cur_cmd!=right_bracket ) {
17667      mp_missing_err(mp, "]");
17668 @.Missing `]'@>
17669     help3("I've seen a `[' and a subscript value, in a suffix,")
17670       ("so a right bracket should have come next.")
17671       ("I shall pretend that one was there.");
17672     mp_back_error(mp);
17673   }
17674   mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp;
17675 }
17676
17677 @* \[38] Parsing secondary and higher expressions.
17678 After the intricacies of |scan_primary|\kern-1pt,
17679 the |scan_secondary| routine is
17680 refreshingly simple. It's not trivial, but the operations are relatively
17681 straightforward; the main difficulty is, again, that expressions and data
17682 structures might change drastically every time we call |get_x_next|, so a
17683 cautious approach is mandatory. For example, a macro defined by
17684 \&{primarydef} might have disappeared by the time its second argument has
17685 been scanned; we solve this by increasing the reference count of its token
17686 list, so that the macro can be called even after it has been clobbered.
17687
17688 @<Declare the basic parsing subroutines@>=
17689 void mp_scan_secondary (MP mp) {
17690   pointer p; /* for list manipulation */
17691   halfword c,d; /* operation codes or modifiers */
17692   pointer mac_name; /* token defined with \&{primarydef} */
17693 RESTART:
17694   if ((mp->cur_cmd<min_primary_command)||
17695       (mp->cur_cmd>max_primary_command) )
17696     mp_bad_exp(mp, "A secondary");
17697 @.A secondary expression...@>
17698   mp_scan_primary(mp);
17699 CONTINUE: 
17700   if ( mp->cur_cmd<=max_secondary_command )
17701     if ( mp->cur_cmd>=min_secondary_command ) {
17702       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17703       if ( d==secondary_primary_macro ) { 
17704         mac_name=mp->cur_sym; add_mac_ref(c);
17705      }
17706      mp_get_x_next(mp); mp_scan_primary(mp);
17707      if ( d!=secondary_primary_macro ) {
17708        mp_do_binary(mp, p,c);
17709      } else  { 
17710        mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17711        decr(ref_count(c)); mp_get_x_next(mp); 
17712        goto RESTART;
17713     }
17714     goto CONTINUE;
17715   }
17716 }
17717
17718 @ The following procedure calls a macro that has two parameters,
17719 |p| and |cur_exp|.
17720
17721 @c void mp_binary_mac (MP mp,pointer p, pointer c, pointer n) {
17722   pointer q,r; /* nodes in the parameter list */
17723   q=mp_get_avail(mp); r=mp_get_avail(mp); link(q)=r;
17724   info(q)=p; info(r)=mp_stash_cur_exp(mp);
17725   mp_macro_call(mp, c,q,n);
17726 }
17727
17728 @ The next procedure, |scan_tertiary|, is pretty much the same deal.
17729
17730 @<Declare the basic parsing subroutines@>=
17731 void mp_scan_tertiary (MP mp) {
17732   pointer p; /* for list manipulation */
17733   halfword c,d; /* operation codes or modifiers */
17734   pointer mac_name; /* token defined with \&{secondarydef} */
17735 RESTART:
17736   if ((mp->cur_cmd<min_primary_command)||
17737       (mp->cur_cmd>max_primary_command) )
17738     mp_bad_exp(mp, "A tertiary");
17739 @.A tertiary expression...@>
17740   mp_scan_secondary(mp);
17741 CONTINUE: 
17742   if ( mp->cur_cmd<=max_tertiary_command ) {
17743     if ( mp->cur_cmd>=min_tertiary_command ) {
17744       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17745       if ( d==tertiary_secondary_macro ) { 
17746         mac_name=mp->cur_sym; add_mac_ref(c);
17747       };
17748       mp_get_x_next(mp); mp_scan_secondary(mp);
17749       if ( d!=tertiary_secondary_macro ) {
17750         mp_do_binary(mp, p,c);
17751       } else { 
17752         mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17753         decr(ref_count(c)); mp_get_x_next(mp); 
17754         goto RESTART;
17755       }
17756       goto CONTINUE;
17757     }
17758   }
17759 }
17760
17761 @ Finally we reach the deepest level in our quartet of parsing routines.
17762 This one is much like the others; but it has an extra complication from
17763 paths, which materialize here.
17764
17765 @d continue_path 25 /* a label inside of |scan_expression| */
17766 @d finish_path 26 /* another */
17767
17768 @<Declare the basic parsing subroutines@>=
17769 void mp_scan_expression (MP mp) {
17770   pointer p,q,r,pp,qq; /* for list manipulation */
17771   halfword c,d; /* operation codes or modifiers */
17772   int my_var_flag; /* initial value of |var_flag| */
17773   pointer mac_name; /* token defined with \&{tertiarydef} */
17774   boolean cycle_hit; /* did a path expression just end with `\&{cycle}'? */
17775   scaled x,y; /* explicit coordinates or tension at a path join */
17776   int t; /* knot type following a path join */
17777   t=0; y=0; x=0;
17778   my_var_flag=mp->var_flag; mac_name=null;
17779 RESTART:
17780   if ((mp->cur_cmd<min_primary_command)||
17781       (mp->cur_cmd>max_primary_command) )
17782     mp_bad_exp(mp, "An");
17783 @.An expression...@>
17784   mp_scan_tertiary(mp);
17785 CONTINUE: 
17786   if ( mp->cur_cmd<=max_expression_command )
17787     if ( mp->cur_cmd>=min_expression_command ) {
17788       if ( (mp->cur_cmd!=equals)||(my_var_flag!=assignment) ) {
17789         p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17790         if ( d==expression_tertiary_macro ) {
17791           mac_name=mp->cur_sym; add_mac_ref(c);
17792         }
17793         if ( (d<ampersand)||((d==ampersand)&&
17794              ((type(p)==mp_pair_type)||(type(p)==mp_path_type))) ) {
17795           @<Scan a path construction operation;
17796             but |return| if |p| has the wrong type@>;
17797         } else { 
17798           mp_get_x_next(mp); mp_scan_tertiary(mp);
17799           if ( d!=expression_tertiary_macro ) {
17800             mp_do_binary(mp, p,c);
17801           } else  { 
17802             mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17803             decr(ref_count(c)); mp_get_x_next(mp); 
17804             goto RESTART;
17805           }
17806         }
17807         goto CONTINUE;
17808      }
17809   }
17810 }
17811
17812 @ The reader should review the data structure conventions for paths before
17813 hoping to understand the next part of this code.
17814
17815 @<Scan a path construction operation...@>=
17816
17817   cycle_hit=false;
17818   @<Convert the left operand, |p|, into a partial path ending at~|q|;
17819     but |return| if |p| doesn't have a suitable type@>;
17820 CONTINUE_PATH: 
17821   @<Determine the path join parameters;
17822     but |goto finish_path| if there's only a direction specifier@>;
17823   if ( mp->cur_cmd==cycle ) {
17824     @<Get ready to close a cycle@>;
17825   } else { 
17826     mp_scan_tertiary(mp);
17827     @<Convert the right operand, |cur_exp|,
17828       into a partial path from |pp| to~|qq|@>;
17829   }
17830   @<Join the partial paths and reset |p| and |q| to the head and tail
17831     of the result@>;
17832   if ( mp->cur_cmd>=min_expression_command )
17833     if ( mp->cur_cmd<=ampersand ) if ( ! cycle_hit ) goto CONTINUE_PATH;
17834 FINISH_PATH:
17835   @<Choose control points for the path and put the result into |cur_exp|@>;
17836 }
17837
17838 @ @<Convert the left operand, |p|, into a partial path ending at~|q|...@>=
17839
17840   mp_unstash_cur_exp(mp, p);
17841   if ( mp->cur_type==mp_pair_type ) p=mp_new_knot(mp);
17842   else if ( mp->cur_type==mp_path_type ) p=mp->cur_exp;
17843   else return;
17844   q=p;
17845   while ( link(q)!=p ) q=link(q);
17846   if ( left_type(p)!=endpoint ) { /* open up a cycle */
17847     r=mp_copy_knot(mp, p); link(q)=r; q=r;
17848   }
17849   left_type(p)=open; right_type(q)=open;
17850 }
17851
17852 @ A pair of numeric values is changed into a knot node for a one-point path
17853 when \MP\ discovers that the pair is part of a path.
17854
17855 @c@<Declare the procedure called |known_pair|@>;
17856 pointer mp_new_knot (MP mp) { /* convert a pair to a knot with two endpoints */
17857   pointer q; /* the new node */
17858   q=mp_get_node(mp, knot_node_size); left_type(q)=endpoint;
17859   right_type(q)=endpoint; originator(q)=metapost_user; link(q)=q;
17860   mp_known_pair(mp); x_coord(q)=mp->cur_x; y_coord(q)=mp->cur_y;
17861   return q;
17862 }
17863
17864 @ The |known_pair| subroutine sets |cur_x| and |cur_y| to the components
17865 of the current expression, assuming that the current expression is a
17866 pair of known numerics. Unknown components are zeroed, and the
17867 current expression is flushed.
17868
17869 @<Declare the procedure called |known_pair|@>=
17870 void mp_known_pair (MP mp) {
17871   pointer p; /* the pair node */
17872   if ( mp->cur_type!=mp_pair_type ) {
17873     exp_err("Undefined coordinates have been replaced by (0,0)");
17874 @.Undefined coordinates...@>
17875     help5("I need x and y numbers for this part of the path.")
17876       ("The value I found (see above) was no good;")
17877       ("so I'll try to keep going by using zero instead.")
17878       ("(Chapter 27 of The METAFONTbook explains that")
17879 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
17880       ("you might want to type `I ??" "?' now.)");
17881     mp_put_get_flush_error(mp, 0); mp->cur_x=0; mp->cur_y=0;
17882   } else { 
17883     p=value(mp->cur_exp);
17884      @<Make sure that both |x| and |y| parts of |p| are known;
17885        copy them into |cur_x| and |cur_y|@>;
17886     mp_flush_cur_exp(mp, 0);
17887   }
17888 }
17889
17890 @ @<Make sure that both |x| and |y| parts of |p| are known...@>=
17891 if ( type(x_part_loc(p))==mp_known ) {
17892   mp->cur_x=value(x_part_loc(p));
17893 } else { 
17894   mp_disp_err(mp, x_part_loc(p),
17895     "Undefined x coordinate has been replaced by 0");
17896 @.Undefined coordinates...@>
17897   help5("I need a `known' x value for this part of the path.")
17898     ("The value I found (see above) was no good;")
17899     ("so I'll try to keep going by using zero instead.")
17900     ("(Chapter 27 of The METAFONTbook explains that")
17901 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
17902     ("you might want to type `I ??" "?' now.)");
17903   mp_put_get_error(mp); mp_recycle_value(mp, x_part_loc(p)); mp->cur_x=0;
17904 }
17905 if ( type(y_part_loc(p))==mp_known ) {
17906   mp->cur_y=value(y_part_loc(p));
17907 } else { 
17908   mp_disp_err(mp, y_part_loc(p),
17909     "Undefined y coordinate has been replaced by 0");
17910   help5("I need a `known' y value for this part of the path.")
17911     ("The value I found (see above) was no good;")
17912     ("so I'll try to keep going by using zero instead.")
17913     ("(Chapter 27 of The METAFONTbook explains that")
17914     ("you might want to type `I ??" "?' now.)");
17915   mp_put_get_error(mp); mp_recycle_value(mp, y_part_loc(p)); mp->cur_y=0;
17916 }
17917
17918 @ At this point |cur_cmd| is either |ampersand|, |left_brace|, or |path_join|.
17919
17920 @<Determine the path join parameters...@>=
17921 if ( mp->cur_cmd==left_brace ) {
17922   @<Put the pre-join direction information into node |q|@>;
17923 }
17924 d=mp->cur_cmd;
17925 if ( d==path_join ) {
17926   @<Determine the tension and/or control points@>;
17927 } else if ( d!=ampersand ) {
17928   goto FINISH_PATH;
17929 }
17930 mp_get_x_next(mp);
17931 if ( mp->cur_cmd==left_brace ) {
17932   @<Put the post-join direction information into |x| and |t|@>;
17933 } else if ( right_type(q)!=explicit ) {
17934   t=open; x=0;
17935 }
17936
17937 @ The |scan_direction| subroutine looks at the directional information
17938 that is enclosed in braces, and also scans ahead to the following character.
17939 A type code is returned, either |open| (if the direction was $(0,0)$),
17940 or |curl| (if the direction was a curl of known value |cur_exp|), or
17941 |given| (if the direction is given by the |angle| value that now
17942 appears in |cur_exp|).
17943
17944 There's nothing difficult about this subroutine, but the program is rather
17945 lengthy because a variety of potential errors need to be nipped in the bud.
17946
17947 @c small_number mp_scan_direction (MP mp) {
17948   int t; /* the type of information found */
17949   scaled x; /* an |x| coordinate */
17950   mp_get_x_next(mp);
17951   if ( mp->cur_cmd==curl_command ) {
17952      @<Scan a curl specification@>;
17953   } else {
17954     @<Scan a given direction@>;
17955   }
17956   if ( mp->cur_cmd!=right_brace ) {
17957     mp_missing_err(mp, "}");
17958 @.Missing `\char`\}'@>
17959     help3("I've scanned a direction spec for part of a path,")
17960       ("so a right brace should have come next.")
17961       ("I shall pretend that one was there.");
17962     mp_back_error(mp);
17963   }
17964   mp_get_x_next(mp); 
17965   return t;
17966 }
17967
17968 @ @<Scan a curl specification@>=
17969 { mp_get_x_next(mp); mp_scan_expression(mp);
17970 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<0) ){ 
17971   exp_err("Improper curl has been replaced by 1");
17972 @.Improper curl@>
17973   help1("A curl must be a known, nonnegative number.");
17974   mp_put_get_flush_error(mp, unity);
17975 }
17976 t=curl;
17977 }
17978
17979 @ @<Scan a given direction@>=
17980 { mp_scan_expression(mp);
17981   if ( mp->cur_type>mp_pair_type ) {
17982     @<Get given directions separated by commas@>;
17983   } else {
17984     mp_known_pair(mp);
17985   }
17986   if ( (mp->cur_x==0)&&(mp->cur_y==0) )  t=open;
17987   else  { t=given; mp->cur_exp=mp_n_arg(mp, mp->cur_x,mp->cur_y);}
17988 }
17989
17990 @ @<Get given directions separated by commas@>=
17991
17992   if ( mp->cur_type!=mp_known ) {
17993     exp_err("Undefined x coordinate has been replaced by 0");
17994 @.Undefined coordinates...@>
17995     help5("I need a `known' x value for this part of the path.")
17996       ("The value I found (see above) was no good;")
17997       ("so I'll try to keep going by using zero instead.")
17998       ("(Chapter 27 of The METAFONTbook explains that")
17999 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18000       ("you might want to type `I ??" "?' now.)");
18001     mp_put_get_flush_error(mp, 0);
18002   }
18003   x=mp->cur_exp;
18004   if ( mp->cur_cmd!=comma ) {
18005     mp_missing_err(mp, ",");
18006 @.Missing `,'@>
18007     help2("I've got the x coordinate of a path direction;")
18008       ("will look for the y coordinate next.");
18009     mp_back_error(mp);
18010   }
18011   mp_get_x_next(mp); mp_scan_expression(mp);
18012   if ( mp->cur_type!=mp_known ) {
18013      exp_err("Undefined y coordinate has been replaced by 0");
18014     help5("I need a `known' y value for this part of the path.")
18015       ("The value I found (see above) was no good;")
18016       ("so I'll try to keep going by using zero instead.")
18017       ("(Chapter 27 of The METAFONTbook explains that")
18018       ("you might want to type `I ??" "?' now.)");
18019     mp_put_get_flush_error(mp, 0);
18020   }
18021   mp->cur_y=mp->cur_exp; mp->cur_x=x;
18022 }
18023
18024 @ At this point |right_type(q)| is usually |open|, but it may have been
18025 set to some other value by a previous splicing operation. We must maintain
18026 the value of |right_type(q)| in unusual cases such as
18027 `\.{..z1\{z2\}\&\{z3\}z1\{0,0\}..}'.
18028
18029 @<Put the pre-join...@>=
18030
18031   t=mp_scan_direction(mp);
18032   if ( t!=open ) {
18033     right_type(q)=t; right_given(q)=mp->cur_exp;
18034     if ( left_type(q)==open ) {
18035       left_type(q)=t; left_given(q)=mp->cur_exp;
18036     } /* note that |left_given(q)=left_curl(q)| */
18037   }
18038 }
18039
18040 @ Since |left_tension| and |left_y| share the same position in knot nodes,
18041 and since |left_given| is similarly equivalent to |left_x|, we use
18042 |x| and |y| to hold the given direction and tension information when
18043 there are no explicit control points.
18044
18045 @<Put the post-join...@>=
18046
18047   t=mp_scan_direction(mp);
18048   if ( right_type(q)!=explicit ) x=mp->cur_exp;
18049   else t=explicit; /* the direction information is superfluous */
18050 }
18051
18052 @ @<Determine the tension and/or...@>=
18053
18054   mp_get_x_next(mp);
18055   if ( mp->cur_cmd==tension ) {
18056     @<Set explicit tensions@>;
18057   } else if ( mp->cur_cmd==controls ) {
18058     @<Set explicit control points@>;
18059   } else  { 
18060     right_tension(q)=unity; y=unity; mp_back_input(mp); /* default tension */
18061     goto DONE;
18062   };
18063   if ( mp->cur_cmd!=path_join ) {
18064      mp_missing_err(mp, "..");
18065 @.Missing `..'@>
18066     help1("A path join command should end with two dots.");
18067     mp_back_error(mp);
18068   }
18069 DONE:
18070   ;
18071 }
18072
18073 @ @<Set explicit tensions@>=
18074
18075   mp_get_x_next(mp); y=mp->cur_cmd;
18076   if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18077   mp_scan_primary(mp);
18078   @<Make sure that the current expression is a valid tension setting@>;
18079   if ( y==at_least ) negate(mp->cur_exp);
18080   right_tension(q)=mp->cur_exp;
18081   if ( mp->cur_cmd==and_command ) {
18082     mp_get_x_next(mp); y=mp->cur_cmd;
18083     if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18084     mp_scan_primary(mp);
18085     @<Make sure that the current expression is a valid tension setting@>;
18086     if ( y==at_least ) negate(mp->cur_exp);
18087   }
18088   y=mp->cur_exp;
18089 }
18090
18091 @ @d min_tension three_quarter_unit
18092
18093 @<Make sure that the current expression is a valid tension setting@>=
18094 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<min_tension) ) {
18095   exp_err("Improper tension has been set to 1");
18096 @.Improper tension@>
18097   help1("The expression above should have been a number >=3/4.");
18098   mp_put_get_flush_error(mp, unity);
18099 }
18100
18101 @ @<Set explicit control points@>=
18102
18103   right_type(q)=explicit; t=explicit; mp_get_x_next(mp); mp_scan_primary(mp);
18104   mp_known_pair(mp); right_x(q)=mp->cur_x; right_y(q)=mp->cur_y;
18105   if ( mp->cur_cmd!=and_command ) {
18106     x=right_x(q); y=right_y(q);
18107   } else { 
18108     mp_get_x_next(mp); mp_scan_primary(mp);
18109     mp_known_pair(mp); x=mp->cur_x; y=mp->cur_y;
18110   }
18111 }
18112
18113 @ @<Convert the right operand, |cur_exp|, into a partial path...@>=
18114
18115   if ( mp->cur_type!=mp_path_type ) pp=mp_new_knot(mp);
18116   else pp=mp->cur_exp;
18117   qq=pp;
18118   while ( link(qq)!=pp ) qq=link(qq);
18119   if ( left_type(pp)!=endpoint ) { /* open up a cycle */
18120     r=mp_copy_knot(mp, pp); link(qq)=r; qq=r;
18121   }
18122   left_type(pp)=open; right_type(qq)=open;
18123 }
18124
18125 @ If a person tries to define an entire path by saying `\.{(x,y)\&cycle}',
18126 we silently change the specification to `\.{(x,y)..cycle}', since a cycle
18127 shouldn't have length zero.
18128
18129 @<Get ready to close a cycle@>=
18130
18131   cycle_hit=true; mp_get_x_next(mp); pp=p; qq=p;
18132   if ( d==ampersand ) if ( p==q ) {
18133     d=path_join; right_tension(q)=unity; y=unity;
18134   }
18135 }
18136
18137 @ @<Join the partial paths and reset |p| and |q|...@>=
18138
18139 if ( d==ampersand ) {
18140   if ( (x_coord(q)!=x_coord(pp))||(y_coord(q)!=y_coord(pp)) ) {
18141     print_err("Paths don't touch; `&' will be changed to `..'");
18142 @.Paths don't touch@>
18143     help3("When you join paths `p&q', the ending point of p")
18144       ("must be exactly equal to the starting point of q.")
18145       ("So I'm going to pretend that you said `p..q' instead.");
18146     mp_put_get_error(mp); d=path_join; right_tension(q)=unity; y=unity;
18147   }
18148 }
18149 @<Plug an opening in |right_type(pp)|, if possible@>;
18150 if ( d==ampersand ) {
18151   @<Splice independent paths together@>;
18152 } else  { 
18153   @<Plug an opening in |right_type(q)|, if possible@>;
18154   link(q)=pp; left_y(pp)=y;
18155   if ( t!=open ) { left_x(pp)=x; left_type(pp)=t;  };
18156 }
18157 q=qq;
18158 }
18159
18160 @ @<Plug an opening in |right_type(q)|...@>=
18161 if ( right_type(q)==open ) {
18162   if ( (left_type(q)==curl)||(left_type(q)==given) ) {
18163     right_type(q)=left_type(q); right_given(q)=left_given(q);
18164   }
18165 }
18166
18167 @ @<Plug an opening in |right_type(pp)|...@>=
18168 if ( right_type(pp)==open ) {
18169   if ( (t==curl)||(t==given) ) {
18170     right_type(pp)=t; right_given(pp)=x;
18171   }
18172 }
18173
18174 @ @<Splice independent paths together@>=
18175
18176   if ( left_type(q)==open ) if ( right_type(q)==open ) {
18177     left_type(q)=curl; left_curl(q)=unity;
18178   }
18179   if ( right_type(pp)==open ) if ( t==open ) {
18180     right_type(pp)=curl; right_curl(pp)=unity;
18181   }
18182   right_type(q)=right_type(pp); link(q)=link(pp);
18183   right_x(q)=right_x(pp); right_y(q)=right_y(pp);
18184   mp_free_node(mp, pp,knot_node_size);
18185   if ( qq==pp ) qq=q;
18186 }
18187
18188 @ @<Choose control points for the path...@>=
18189 if ( cycle_hit ) { 
18190   if ( d==ampersand ) p=q;
18191 } else  { 
18192   left_type(p)=endpoint;
18193   if ( right_type(p)==open ) { 
18194     right_type(p)=curl; right_curl(p)=unity;
18195   }
18196   right_type(q)=endpoint;
18197   if ( left_type(q)==open ) { 
18198     left_type(q)=curl; left_curl(q)=unity;
18199   }
18200   link(q)=p;
18201 }
18202 mp_make_choices(mp, p);
18203 mp->cur_type=mp_path_type; mp->cur_exp=p
18204
18205 @ Finally, we sometimes need to scan an expression whose value is
18206 supposed to be either |true_code| or |false_code|.
18207
18208 @<Declare the basic parsing subroutines@>=
18209 void mp_get_boolean (MP mp) { 
18210   mp_get_x_next(mp); mp_scan_expression(mp);
18211   if ( mp->cur_type!=mp_boolean_type ) {
18212     exp_err("Undefined condition will be treated as `false'");
18213 @.Undefined condition...@>
18214     help2("The expression shown above should have had a definite")
18215       ("true-or-false value. I'm changing it to `false'.");
18216     mp_put_get_flush_error(mp, false_code); mp->cur_type=mp_boolean_type;
18217   }
18218 }
18219
18220 @* \[39] Doing the operations.
18221 The purpose of parsing is primarily to permit people to avoid piles of
18222 parentheses. But the real work is done after the structure of an expression
18223 has been recognized; that's when new expressions are generated. We
18224 turn now to the guts of \MP, which handles individual operators that
18225 have come through the parsing mechanism.
18226
18227 We'll start with the easy ones that take no operands, then work our way
18228 up to operators with one and ultimately two arguments. In other words,
18229 we will write the three procedures |do_nullary|, |do_unary|, and |do_binary|
18230 that are invoked periodically by the expression scanners.
18231
18232 First let's make sure that all of the primitive operators are in the
18233 hash table. Although |scan_primary| and its relatives made use of the
18234 \\{cmd} code for these operators, the \\{do} routines base everything
18235 on the \\{mod} code. For example, |do_binary| doesn't care whether the
18236 operation it performs is a |primary_binary| or |secondary_binary|, etc.
18237
18238 @<Put each...@>=
18239 mp_primitive(mp, "true",nullary,true_code);
18240 @:true_}{\&{true} primitive@>
18241 mp_primitive(mp, "false",nullary,false_code);
18242 @:false_}{\&{false} primitive@>
18243 mp_primitive(mp, "nullpicture",nullary,null_picture_code);
18244 @:null_picture_}{\&{nullpicture} primitive@>
18245 mp_primitive(mp, "nullpen",nullary,null_pen_code);
18246 @:null_pen_}{\&{nullpen} primitive@>
18247 mp_primitive(mp, "jobname",nullary,job_name_op);
18248 @:job_name_}{\&{jobname} primitive@>
18249 mp_primitive(mp, "readstring",nullary,read_string_op);
18250 @:read_string_}{\&{readstring} primitive@>
18251 mp_primitive(mp, "pencircle",nullary,pen_circle);
18252 @:pen_circle_}{\&{pencircle} primitive@>
18253 mp_primitive(mp, "normaldeviate",nullary,normal_deviate);
18254 @:normal_deviate_}{\&{normaldeviate} primitive@>
18255 mp_primitive(mp, "readfrom",unary,read_from_op);
18256 @:read_from_}{\&{readfrom} primitive@>
18257 mp_primitive(mp, "closefrom",unary,close_from_op);
18258 @:close_from_}{\&{closefrom} primitive@>
18259 mp_primitive(mp, "odd",unary,odd_op);
18260 @:odd_}{\&{odd} primitive@>
18261 mp_primitive(mp, "known",unary,known_op);
18262 @:known_}{\&{known} primitive@>
18263 mp_primitive(mp, "unknown",unary,unknown_op);
18264 @:unknown_}{\&{unknown} primitive@>
18265 mp_primitive(mp, "not",unary,not_op);
18266 @:not_}{\&{not} primitive@>
18267 mp_primitive(mp, "decimal",unary,decimal);
18268 @:decimal_}{\&{decimal} primitive@>
18269 mp_primitive(mp, "reverse",unary,reverse);
18270 @:reverse_}{\&{reverse} primitive@>
18271 mp_primitive(mp, "makepath",unary,make_path_op);
18272 @:make_path_}{\&{makepath} primitive@>
18273 mp_primitive(mp, "makepen",unary,make_pen_op);
18274 @:make_pen_}{\&{makepen} primitive@>
18275 mp_primitive(mp, "oct",unary,oct_op);
18276 @:oct_}{\&{oct} primitive@>
18277 mp_primitive(mp, "hex",unary,hex_op);
18278 @:hex_}{\&{hex} primitive@>
18279 mp_primitive(mp, "ASCII",unary,ASCII_op);
18280 @:ASCII_}{\&{ASCII} primitive@>
18281 mp_primitive(mp, "char",unary,char_op);
18282 @:char_}{\&{char} primitive@>
18283 mp_primitive(mp, "length",unary,length_op);
18284 @:length_}{\&{length} primitive@>
18285 mp_primitive(mp, "turningnumber",unary,turning_op);
18286 @:turning_number_}{\&{turningnumber} primitive@>
18287 mp_primitive(mp, "xpart",unary,x_part);
18288 @:x_part_}{\&{xpart} primitive@>
18289 mp_primitive(mp, "ypart",unary,y_part);
18290 @:y_part_}{\&{ypart} primitive@>
18291 mp_primitive(mp, "xxpart",unary,xx_part);
18292 @:xx_part_}{\&{xxpart} primitive@>
18293 mp_primitive(mp, "xypart",unary,xy_part);
18294 @:xy_part_}{\&{xypart} primitive@>
18295 mp_primitive(mp, "yxpart",unary,yx_part);
18296 @:yx_part_}{\&{yxpart} primitive@>
18297 mp_primitive(mp, "yypart",unary,yy_part);
18298 @:yy_part_}{\&{yypart} primitive@>
18299 mp_primitive(mp, "redpart",unary,red_part);
18300 @:red_part_}{\&{redpart} primitive@>
18301 mp_primitive(mp, "greenpart",unary,green_part);
18302 @:green_part_}{\&{greenpart} primitive@>
18303 mp_primitive(mp, "bluepart",unary,blue_part);
18304 @:blue_part_}{\&{bluepart} primitive@>
18305 mp_primitive(mp, "cyanpart",unary,cyan_part);
18306 @:cyan_part_}{\&{cyanpart} primitive@>
18307 mp_primitive(mp, "magentapart",unary,magenta_part);
18308 @:magenta_part_}{\&{magentapart} primitive@>
18309 mp_primitive(mp, "yellowpart",unary,yellow_part);
18310 @:yellow_part_}{\&{yellowpart} primitive@>
18311 mp_primitive(mp, "blackpart",unary,black_part);
18312 @:black_part_}{\&{blackpart} primitive@>
18313 mp_primitive(mp, "greypart",unary,grey_part);
18314 @:grey_part_}{\&{greypart} primitive@>
18315 mp_primitive(mp, "colormodel",unary,color_model_part);
18316 @:color_model_part_}{\&{colormodel} primitive@>
18317 mp_primitive(mp, "fontpart",unary,font_part);
18318 @:font_part_}{\&{fontpart} primitive@>
18319 mp_primitive(mp, "textpart",unary,text_part);
18320 @:text_part_}{\&{textpart} primitive@>
18321 mp_primitive(mp, "pathpart",unary,path_part);
18322 @:path_part_}{\&{pathpart} primitive@>
18323 mp_primitive(mp, "penpart",unary,pen_part);
18324 @:pen_part_}{\&{penpart} primitive@>
18325 mp_primitive(mp, "dashpart",unary,dash_part);
18326 @:dash_part_}{\&{dashpart} primitive@>
18327 mp_primitive(mp, "sqrt",unary,sqrt_op);
18328 @:sqrt_}{\&{sqrt} primitive@>
18329 mp_primitive(mp, "mexp",unary,m_exp_op);
18330 @:m_exp_}{\&{mexp} primitive@>
18331 mp_primitive(mp, "mlog",unary,m_log_op);
18332 @:m_log_}{\&{mlog} primitive@>
18333 mp_primitive(mp, "sind",unary,sin_d_op);
18334 @:sin_d_}{\&{sind} primitive@>
18335 mp_primitive(mp, "cosd",unary,cos_d_op);
18336 @:cos_d_}{\&{cosd} primitive@>
18337 mp_primitive(mp, "floor",unary,floor_op);
18338 @:floor_}{\&{floor} primitive@>
18339 mp_primitive(mp, "uniformdeviate",unary,uniform_deviate);
18340 @:uniform_deviate_}{\&{uniformdeviate} primitive@>
18341 mp_primitive(mp, "charexists",unary,char_exists_op);
18342 @:char_exists_}{\&{charexists} primitive@>
18343 mp_primitive(mp, "fontsize",unary,font_size);
18344 @:font_size_}{\&{fontsize} primitive@>
18345 mp_primitive(mp, "llcorner",unary,ll_corner_op);
18346 @:ll_corner_}{\&{llcorner} primitive@>
18347 mp_primitive(mp, "lrcorner",unary,lr_corner_op);
18348 @:lr_corner_}{\&{lrcorner} primitive@>
18349 mp_primitive(mp, "ulcorner",unary,ul_corner_op);
18350 @:ul_corner_}{\&{ulcorner} primitive@>
18351 mp_primitive(mp, "urcorner",unary,ur_corner_op);
18352 @:ur_corner_}{\&{urcorner} primitive@>
18353 mp_primitive(mp, "arclength",unary,arc_length);
18354 @:arc_length_}{\&{arclength} primitive@>
18355 mp_primitive(mp, "angle",unary,angle_op);
18356 @:angle_}{\&{angle} primitive@>
18357 mp_primitive(mp, "cycle",cycle,cycle_op);
18358 @:cycle_}{\&{cycle} primitive@>
18359 mp_primitive(mp, "stroked",unary,stroked_op);
18360 @:stroked_}{\&{stroked} primitive@>
18361 mp_primitive(mp, "filled",unary,filled_op);
18362 @:filled_}{\&{filled} primitive@>
18363 mp_primitive(mp, "textual",unary,textual_op);
18364 @:textual_}{\&{textual} primitive@>
18365 mp_primitive(mp, "clipped",unary,clipped_op);
18366 @:clipped_}{\&{clipped} primitive@>
18367 mp_primitive(mp, "bounded",unary,bounded_op);
18368 @:bounded_}{\&{bounded} primitive@>
18369 mp_primitive(mp, "+",plus_or_minus,plus);
18370 @:+ }{\.{+} primitive@>
18371 mp_primitive(mp, "-",plus_or_minus,minus);
18372 @:- }{\.{-} primitive@>
18373 mp_primitive(mp, "*",secondary_binary,times);
18374 @:* }{\.{*} primitive@>
18375 mp_primitive(mp, "/",slash,over); mp->eqtb[frozen_slash]=mp->eqtb[mp->cur_sym];
18376 @:/ }{\.{/} primitive@>
18377 mp_primitive(mp, "++",tertiary_binary,pythag_add);
18378 @:++_}{\.{++} primitive@>
18379 mp_primitive(mp, "+-+",tertiary_binary,pythag_sub);
18380 @:+-+_}{\.{+-+} primitive@>
18381 mp_primitive(mp, "or",tertiary_binary,or_op);
18382 @:or_}{\&{or} primitive@>
18383 mp_primitive(mp, "and",and_command,and_op);
18384 @:and_}{\&{and} primitive@>
18385 mp_primitive(mp, "<",expression_binary,less_than);
18386 @:< }{\.{<} primitive@>
18387 mp_primitive(mp, "<=",expression_binary,less_or_equal);
18388 @:<=_}{\.{<=} primitive@>
18389 mp_primitive(mp, ">",expression_binary,greater_than);
18390 @:> }{\.{>} primitive@>
18391 mp_primitive(mp, ">=",expression_binary,greater_or_equal);
18392 @:>=_}{\.{>=} primitive@>
18393 mp_primitive(mp, "=",equals,equal_to);
18394 @:= }{\.{=} primitive@>
18395 mp_primitive(mp, "<>",expression_binary,unequal_to);
18396 @:<>_}{\.{<>} primitive@>
18397 mp_primitive(mp, "substring",primary_binary,substring_of);
18398 @:substring_}{\&{substring} primitive@>
18399 mp_primitive(mp, "subpath",primary_binary,subpath_of);
18400 @:subpath_}{\&{subpath} primitive@>
18401 mp_primitive(mp, "directiontime",primary_binary,direction_time_of);
18402 @:direction_time_}{\&{directiontime} primitive@>
18403 mp_primitive(mp, "point",primary_binary,point_of);
18404 @:point_}{\&{point} primitive@>
18405 mp_primitive(mp, "precontrol",primary_binary,precontrol_of);
18406 @:precontrol_}{\&{precontrol} primitive@>
18407 mp_primitive(mp, "postcontrol",primary_binary,postcontrol_of);
18408 @:postcontrol_}{\&{postcontrol} primitive@>
18409 mp_primitive(mp, "penoffset",primary_binary,pen_offset_of);
18410 @:pen_offset_}{\&{penoffset} primitive@>
18411 mp_primitive(mp, "arctime",primary_binary,arc_time_of);
18412 @:arc_time_of_}{\&{arctime} primitive@>
18413 mp_primitive(mp, "mpversion",nullary,mp_version);
18414 @:mp_verison_}{\&{mpversion} primitive@>
18415 mp_primitive(mp, "&",ampersand,concatenate);
18416 @:!!!}{\.{\&} primitive@>
18417 mp_primitive(mp, "rotated",secondary_binary,rotated_by);
18418 @:rotated_}{\&{rotated} primitive@>
18419 mp_primitive(mp, "slanted",secondary_binary,slanted_by);
18420 @:slanted_}{\&{slanted} primitive@>
18421 mp_primitive(mp, "scaled",secondary_binary,scaled_by);
18422 @:scaled_}{\&{scaled} primitive@>
18423 mp_primitive(mp, "shifted",secondary_binary,shifted_by);
18424 @:shifted_}{\&{shifted} primitive@>
18425 mp_primitive(mp, "transformed",secondary_binary,transformed_by);
18426 @:transformed_}{\&{transformed} primitive@>
18427 mp_primitive(mp, "xscaled",secondary_binary,x_scaled);
18428 @:x_scaled_}{\&{xscaled} primitive@>
18429 mp_primitive(mp, "yscaled",secondary_binary,y_scaled);
18430 @:y_scaled_}{\&{yscaled} primitive@>
18431 mp_primitive(mp, "zscaled",secondary_binary,z_scaled);
18432 @:z_scaled_}{\&{zscaled} primitive@>
18433 mp_primitive(mp, "infont",secondary_binary,in_font);
18434 @:in_font_}{\&{infont} primitive@>
18435 mp_primitive(mp, "intersectiontimes",tertiary_binary,intersect);
18436 @:intersection_times_}{\&{intersectiontimes} primitive@>
18437
18438 @ @<Cases of |print_cmd...@>=
18439 case nullary:
18440 case unary:
18441 case primary_binary:
18442 case secondary_binary:
18443 case tertiary_binary:
18444 case expression_binary:
18445 case cycle:
18446 case plus_or_minus:
18447 case slash:
18448 case ampersand:
18449 case equals:
18450 case and_command:
18451   mp_print_op(mp, m);
18452   break;
18453
18454 @ OK, let's look at the simplest \\{do} procedure first.
18455
18456 @c @<Declare nullary action procedure@>;
18457 void mp_do_nullary (MP mp,quarterword c) { 
18458   check_arith;
18459   if ( mp->internal[tracing_commands]>two )
18460     mp_show_cmd_mod(mp, nullary,c);
18461   switch (c) {
18462   case true_code: case false_code: 
18463     mp->cur_type=mp_boolean_type; mp->cur_exp=c;
18464     break;
18465   case null_picture_code: 
18466     mp->cur_type=mp_picture_type;
18467     mp->cur_exp=mp_get_node(mp, edge_header_size); 
18468     mp_init_edges(mp, mp->cur_exp);
18469     break;
18470   case null_pen_code: 
18471     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, 0);
18472     break;
18473   case normal_deviate: 
18474     mp->cur_type=mp_known; mp->cur_exp=mp_norm_rand(mp);
18475     break;
18476   case pen_circle: 
18477     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, unity);
18478     break;
18479   case job_name_op:  
18480     if ( mp->job_name==NULL ) mp_open_log_file(mp);
18481     mp->cur_type=mp_string_type; mp->cur_exp=rts(mp->job_name);
18482     break;
18483   case mp_version: 
18484     mp->cur_type=mp_string_type; 
18485     mp->cur_exp=intern(metapost_version) ;
18486     break;
18487   case read_string_op:
18488     @<Read a string from the terminal@>;
18489     break;
18490   } /* there are no other cases */
18491   check_arith;
18492 }
18493
18494 @ @<Read a string...@>=
18495
18496   if ( mp->interaction<=mp_nonstop_mode )
18497     mp_fatal_error(mp, "*** (cannot readstring in nonstop modes)");
18498   mp_begin_file_reading(mp); name=is_read;
18499   limit=start; prompt_input("");
18500   mp_finish_read(mp);
18501 }
18502
18503 @ @<Declare nullary action procedure@>=
18504 void mp_finish_read (MP mp) { /* copy |buffer| line to |cur_exp| */
18505   size_t k;
18506   str_room((int)mp->last-start);
18507   for (k=start;k<=mp->last-1;k++) {
18508    append_char(mp->buffer[k]);
18509   }
18510   mp_end_file_reading(mp); mp->cur_type=mp_string_type; 
18511   mp->cur_exp=mp_make_string(mp);
18512 }
18513
18514 @ Things get a bit more interesting when there's an operand. The
18515 operand to |do_unary| appears in |cur_type| and |cur_exp|.
18516
18517 @c @<Declare unary action procedures@>;
18518 void mp_do_unary (MP mp,quarterword c) {
18519   pointer p,q,r; /* for list manipulation */
18520   integer x; /* a temporary register */
18521   check_arith;
18522   if ( mp->internal[tracing_commands]>two )
18523     @<Trace the current unary operation@>;
18524   switch (c) {
18525   case plus:
18526     if ( mp->cur_type<mp_color_type ) mp_bad_unary(mp, plus);
18527     break;
18528   case minus:
18529     @<Negate the current expression@>;
18530     break;
18531   @<Additional cases of unary operators@>;
18532   } /* there are no other cases */
18533   check_arith;
18534 };
18535
18536 @ The |nice_pair| function returns |true| if both components of a pair
18537 are known.
18538
18539 @<Declare unary action procedures@>=
18540 boolean mp_nice_pair (MP mp,integer p, quarterword t) { 
18541   if ( t==mp_pair_type ) {
18542     p=value(p);
18543     if ( type(x_part_loc(p))==mp_known )
18544       if ( type(y_part_loc(p))==mp_known )
18545         return true;
18546   }
18547   return false;
18548 }
18549
18550 @ The |nice_color_or_pair| function is analogous except that it also accepts
18551 fully known colors.
18552
18553 @<Declare unary action procedures@>=
18554 boolean mp_nice_color_or_pair (MP mp,integer p, quarterword t) {
18555   pointer q,r; /* for scanning the big node */
18556   if ( (t!=mp_pair_type)&&(t!=mp_color_type)&&(t!=mp_cmykcolor_type) ) {
18557     return false;
18558   } else { 
18559     q=value(p);
18560     r=q+mp->big_node_size[type(p)];
18561     do {  
18562       r=r-2;
18563       if ( type(r)!=mp_known )
18564         return false;
18565     } while (r!=q);
18566     return true;
18567   }
18568 }
18569
18570 @ @<Declare unary action...@>=
18571 void mp_print_known_or_unknown_type (MP mp,small_number t, integer v) { 
18572   mp_print_char(mp, '(');
18573   if ( t>mp_known ) mp_print(mp, "unknown numeric");
18574   else { if ( (t==mp_pair_type)||(t==mp_color_type)||(t==mp_cmykcolor_type) )
18575     if ( ! mp_nice_color_or_pair(mp, v,t) ) mp_print(mp, "unknown ");
18576     mp_print_type(mp, t);
18577   }
18578   mp_print_char(mp, ')');
18579 }
18580
18581 @ @<Declare unary action...@>=
18582 void mp_bad_unary (MP mp,quarterword c) { 
18583   exp_err("Not implemented: "); mp_print_op(mp, c);
18584 @.Not implemented...@>
18585   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
18586   help3("I'm afraid I don't know how to apply that operation to that")
18587     ("particular type. Continue, and I'll simply return the")
18588     ("argument (shown above) as the result of the operation.");
18589   mp_put_get_error(mp);
18590 }
18591
18592 @ @<Trace the current unary operation@>=
18593
18594   mp_begin_diagnostic(mp); mp_print_nl(mp, "{"); 
18595   mp_print_op(mp, c); mp_print_char(mp, '(');
18596   mp_print_exp(mp, null,0); /* show the operand, but not verbosely */
18597   mp_print(mp, ")}"); mp_end_diagnostic(mp, false);
18598 }
18599
18600 @ Negation is easy except when the current expression
18601 is of type |independent|, or when it is a pair with one or more
18602 |independent| components.
18603
18604 It is tempting to argue that the negative of an independent variable
18605 is an independent variable, hence we don't have to do anything when
18606 negating it. The fallacy is that other dependent variables pointing
18607 to the current expression must change the sign of their
18608 coefficients if we make no change to the current expression.
18609
18610 Instead, we work around the problem by copying the current expression
18611 and recycling it afterwards (cf.~the |stash_in| routine).
18612
18613 @<Negate the current expression@>=
18614 switch (mp->cur_type) {
18615 case mp_color_type:
18616 case mp_cmykcolor_type:
18617 case mp_pair_type:
18618 case mp_independent: 
18619   q=mp->cur_exp; mp_make_exp_copy(mp, q);
18620   if ( mp->cur_type==mp_dependent ) {
18621     mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18622   } else if ( mp->cur_type<=mp_pair_type ) { /* |mp_color_type| or |mp_pair_type| */
18623     p=value(mp->cur_exp);
18624     r=p+mp->big_node_size[mp->cur_type];
18625     do {  
18626       r=r-2;
18627       if ( type(r)==mp_known ) negate(value(r));
18628       else mp_negate_dep_list(mp, dep_list(r));
18629     } while (r!=p);
18630   } /* if |cur_type=mp_known| then |cur_exp=0| */
18631   mp_recycle_value(mp, q); mp_free_node(mp, q,value_node_size);
18632   break;
18633 case mp_dependent:
18634 case mp_proto_dependent:
18635   mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18636   break;
18637 case mp_known:
18638   negate(mp->cur_exp);
18639   break;
18640 default:
18641   mp_bad_unary(mp, minus);
18642   break;
18643 }
18644
18645 @ @<Declare unary action...@>=
18646 void mp_negate_dep_list (MP mp,pointer p) { 
18647   while (1) { 
18648     negate(value(p));
18649     if ( info(p)==null ) return;
18650     p=link(p);
18651   }
18652 }
18653
18654 @ @<Additional cases of unary operators@>=
18655 case not_op: 
18656   if ( mp->cur_type!=mp_boolean_type ) mp_bad_unary(mp, not_op);
18657   else mp->cur_exp=true_code+false_code-mp->cur_exp;
18658   break;
18659
18660 @ @d three_sixty_units 23592960 /* that's |360*unity| */
18661 @d boolean_reset(A) if ( (A) ) mp->cur_exp=true_code; else mp->cur_exp=false_code
18662
18663 @<Additional cases of unary operators@>=
18664 case sqrt_op:
18665 case m_exp_op:
18666 case m_log_op:
18667 case sin_d_op:
18668 case cos_d_op:
18669 case floor_op:
18670 case  uniform_deviate:
18671 case odd_op:
18672 case char_exists_op:
18673   if ( mp->cur_type!=mp_known ) {
18674     mp_bad_unary(mp, c);
18675   } else {
18676     switch (c) {
18677     case sqrt_op:mp->cur_exp=mp_square_rt(mp, mp->cur_exp);break;
18678     case m_exp_op:mp->cur_exp=mp_m_exp(mp, mp->cur_exp);break;
18679     case m_log_op:mp->cur_exp=mp_m_log(mp, mp->cur_exp);break;
18680     case sin_d_op:
18681     case cos_d_op:
18682       mp_n_sin_cos(mp, (mp->cur_exp % three_sixty_units)*16);
18683       if ( c==sin_d_op ) mp->cur_exp=mp_round_fraction(mp, mp->n_sin);
18684       else mp->cur_exp=mp_round_fraction(mp, mp->n_cos);
18685       break;
18686     case floor_op:mp->cur_exp=mp_floor_scaled(mp, mp->cur_exp);break;
18687     case uniform_deviate:mp->cur_exp=mp_unif_rand(mp, mp->cur_exp);break;
18688     case odd_op: 
18689       boolean_reset(odd(mp_round_unscaled(mp, mp->cur_exp)));
18690       mp->cur_type=mp_boolean_type;
18691       break;
18692     case char_exists_op:
18693       @<Determine if a character has been shipped out@>;
18694       break;
18695     } /* there are no other cases */
18696   }
18697   break;
18698
18699 @ @<Additional cases of unary operators@>=
18700 case angle_op:
18701   if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) ) {
18702     p=value(mp->cur_exp);
18703     x=mp_n_arg(mp, value(x_part_loc(p)),value(y_part_loc(p)));
18704     if ( x>=0 ) mp_flush_cur_exp(mp, (x+8)/ 16);
18705     else mp_flush_cur_exp(mp, -((-x+8)/ 16));
18706   } else {
18707     mp_bad_unary(mp, angle_op);
18708   }
18709   break;
18710
18711 @ If the current expression is a pair, but the context wants it to
18712 be a path, we call |pair_to_path|.
18713
18714 @<Declare unary action...@>=
18715 void mp_pair_to_path (MP mp) { 
18716   mp->cur_exp=mp_new_knot(mp); 
18717   mp->cur_type=mp_path_type;
18718 };
18719
18720 @ @<Additional cases of unary operators@>=
18721 case x_part:
18722 case y_part:
18723   if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_transform_type) )
18724     mp_take_part(mp, c);
18725   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18726   else mp_bad_unary(mp, c);
18727   break;
18728 case xx_part:
18729 case xy_part:
18730 case yx_part:
18731 case yy_part: 
18732   if ( mp->cur_type==mp_transform_type ) mp_take_part(mp, c);
18733   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18734   else mp_bad_unary(mp, c);
18735   break;
18736 case red_part:
18737 case green_part:
18738 case blue_part: 
18739   if ( mp->cur_type==mp_color_type ) mp_take_part(mp, c);
18740   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18741   else mp_bad_unary(mp, c);
18742   break;
18743 case cyan_part:
18744 case magenta_part:
18745 case yellow_part:
18746 case black_part: 
18747   if ( mp->cur_type==mp_cmykcolor_type) mp_take_part(mp, c); 
18748   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18749   else mp_bad_unary(mp, c);
18750   break;
18751 case grey_part: 
18752   if ( mp->cur_type==mp_known ) mp->cur_exp=value(c);
18753   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18754   else mp_bad_unary(mp, c);
18755   break;
18756 case color_model_part: 
18757   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18758   else mp_bad_unary(mp, c);
18759   break;
18760
18761 @ In the following procedure, |cur_exp| points to a capsule, which points to
18762 a big node. We want to delete all but one part of the big node.
18763
18764 @<Declare unary action...@>=
18765 void mp_take_part (MP mp,quarterword c) {
18766   pointer p; /* the big node */
18767   p=value(mp->cur_exp); value(temp_val)=p; type(temp_val)=mp->cur_type;
18768   link(p)=temp_val; mp_free_node(mp, mp->cur_exp,value_node_size);
18769   mp_make_exp_copy(mp, p+mp->sector_offset[c+mp_x_part_sector-x_part]);
18770   mp_recycle_value(mp, temp_val);
18771 }
18772
18773 @ @<Initialize table entries...@>=
18774 name_type(temp_val)=mp_capsule;
18775
18776 @ @<Additional cases of unary operators@>=
18777 case font_part:
18778 case text_part:
18779 case path_part:
18780 case pen_part:
18781 case dash_part:
18782   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18783   else mp_bad_unary(mp, c);
18784   break;
18785
18786 @ @<Declarations@>=
18787 void mp_scale_edges (MP mp);
18788
18789 @ @<Declare unary action...@>=
18790 void mp_take_pict_part (MP mp,quarterword c) {
18791   pointer p; /* first graphical object in |cur_exp| */
18792   p=link(dummy_loc(mp->cur_exp));
18793   if ( p!=null ) {
18794     switch (c) {
18795     case x_part: case y_part: case xx_part:
18796     case xy_part: case yx_part: case yy_part:
18797       if ( type(p)==text_code ) mp_flush_cur_exp(mp, text_trans_part(p+c));
18798       else goto NOT_FOUND;
18799       break;
18800     case red_part: case green_part: case blue_part:
18801       if ( has_color(p) ) mp_flush_cur_exp(mp, obj_color_part(p+c));
18802       else goto NOT_FOUND;
18803       break;
18804     case cyan_part: case magenta_part: case yellow_part:
18805     case black_part:
18806       if ( has_color(p) ) {
18807         if ( color_model(p)==uninitialized_model )
18808           mp_flush_cur_exp(mp, unity);
18809         else
18810           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-cyan_part)));
18811       } else goto NOT_FOUND;
18812       break;
18813     case grey_part:
18814       if ( has_color(p) )
18815           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-grey_part)));
18816       else goto NOT_FOUND;
18817       break;
18818     case color_model_part:
18819       if ( has_color(p) ) {
18820         if ( color_model(p)==uninitialized_model )
18821           mp_flush_cur_exp(mp, mp->internal[default_color_model]);
18822         else
18823           mp_flush_cur_exp(mp, color_model(p)*unity);
18824       } else goto NOT_FOUND;
18825       break;
18826     @<Handle other cases in |take_pict_part| or |goto not_found|@>;
18827     } /* all cases have been enumerated */
18828     return;
18829   };
18830 NOT_FOUND:
18831   @<Convert the current expression to a null value appropriate
18832     for |c|@>;
18833 }
18834
18835 @ @<Handle other cases in |take_pict_part| or |goto not_found|@>=
18836 case text_part: 
18837   if ( type(p)!=text_code ) goto NOT_FOUND;
18838   else { 
18839     mp_flush_cur_exp(mp, text_p(p));
18840     add_str_ref(mp->cur_exp);
18841     mp->cur_type=mp_string_type;
18842     };
18843   break;
18844 case font_part: 
18845   if ( type(p)!=text_code ) goto NOT_FOUND;
18846   else { 
18847     mp_flush_cur_exp(mp, rts(mp->font_name[font_n(p)])); 
18848     add_str_ref(mp->cur_exp);
18849     mp->cur_type=mp_string_type;
18850   };
18851   break;
18852 case path_part:
18853   if ( type(p)==text_code ) goto NOT_FOUND;
18854   else if ( is_stop(p) ) mp_confusion(mp, "pict");
18855 @:this can't happen pict}{\quad pict@>
18856   else { 
18857     mp_flush_cur_exp(mp, mp_copy_path(mp, path_p(p)));
18858     mp->cur_type=mp_path_type;
18859   }
18860   break;
18861 case pen_part: 
18862   if ( ! has_pen(p) ) goto NOT_FOUND;
18863   else {
18864     if ( pen_p(p)==null ) goto NOT_FOUND;
18865     else { mp_flush_cur_exp(mp, copy_pen(pen_p(p)));
18866       mp->cur_type=mp_pen_type;
18867     };
18868   }
18869   break;
18870 case dash_part: 
18871   if ( type(p)!=stroked_code ) goto NOT_FOUND;
18872   else { if ( dash_p(p)==null ) goto NOT_FOUND;
18873     else { add_edge_ref(dash_p(p));
18874     mp->se_sf=dash_scale(p);
18875     mp->se_pic=dash_p(p);
18876     mp_scale_edges(mp);
18877     mp_flush_cur_exp(mp, mp->se_pic);
18878     mp->cur_type=mp_picture_type;
18879     };
18880   }
18881   break;
18882
18883 @ Since |scale_edges| had to be declared |forward|, it had to be declared as a
18884 parameterless procedure even though it really takes two arguments and updates
18885 one of them.  Hence the following globals are needed.
18886
18887 @<Global...@>=
18888 pointer se_pic;  /* edge header used and updated by |scale_edges| */
18889 scaled se_sf;  /* the scale factor argument to |scale_edges| */
18890
18891 @ @<Convert the current expression to a null value appropriate...@>=
18892 switch (c) {
18893 case text_part: case font_part: 
18894   mp_flush_cur_exp(mp, rts(""));
18895   mp->cur_type=mp_string_type;
18896   break;
18897 case path_part: 
18898   mp_flush_cur_exp(mp, mp_get_node(mp, knot_node_size));
18899   left_type(mp->cur_exp)=endpoint;
18900   right_type(mp->cur_exp)=endpoint;
18901   link(mp->cur_exp)=mp->cur_exp;
18902   x_coord(mp->cur_exp)=0;
18903   y_coord(mp->cur_exp)=0;
18904   originator(mp->cur_exp)=metapost_user;
18905   mp->cur_type=mp_path_type;
18906   break;
18907 case pen_part: 
18908   mp_flush_cur_exp(mp, mp_get_pen_circle(mp, 0));
18909   mp->cur_type=mp_pen_type;
18910   break;
18911 case dash_part: 
18912   mp_flush_cur_exp(mp, mp_get_node(mp, edge_header_size));
18913   mp_init_edges(mp, mp->cur_exp);
18914   mp->cur_type=mp_picture_type;
18915   break;
18916 default: 
18917    mp_flush_cur_exp(mp, 0);
18918   break;
18919 }
18920
18921 @ @<Additional cases of unary...@>=
18922 case char_op: 
18923   if ( mp->cur_type!=mp_known ) { 
18924     mp_bad_unary(mp, char_op);
18925   } else { 
18926     mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256; 
18927     mp->cur_type=mp_string_type;
18928     if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
18929   }
18930   break;
18931 case decimal: 
18932   if ( mp->cur_type!=mp_known ) {
18933      mp_bad_unary(mp, decimal);
18934   } else { 
18935     mp->old_setting=mp->selector; mp->selector=new_string;
18936     mp_print_scaled(mp, mp->cur_exp); mp->cur_exp=mp_make_string(mp);
18937     mp->selector=mp->old_setting; mp->cur_type=mp_string_type;
18938   }
18939   break;
18940 case oct_op:
18941 case hex_op:
18942 case ASCII_op: 
18943   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
18944   else mp_str_to_num(mp, c);
18945   break;
18946 case font_size: 
18947   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, font_size);
18948   else @<Find the design size of the font whose name is |cur_exp|@>;
18949   break;
18950
18951 @ @<Declare unary action...@>=
18952 void mp_str_to_num (MP mp,quarterword c) { /* converts a string to a number */
18953   integer n; /* accumulator */
18954   ASCII_code m; /* current character */
18955   pool_pointer k; /* index into |str_pool| */
18956   int b; /* radix of conversion */
18957   boolean bad_char; /* did the string contain an invalid digit? */
18958   if ( c==ASCII_op ) {
18959     if ( length(mp->cur_exp)==0 ) n=-1;
18960     else n=mp->str_pool[mp->str_start[mp->cur_exp]];
18961   } else { 
18962     if ( c==oct_op ) b=8; else b=16;
18963     n=0; bad_char=false;
18964     for (k=mp->str_start[mp->cur_exp];k<=str_stop(mp->cur_exp)-1;k++) {
18965       m=mp->str_pool[k];
18966       if ( (m>='0')&&(m<='9') ) m=m-'0';
18967       else if ( (m>='A')&&(m<='F') ) m=m-'A'+10;
18968       else if ( (m>='a')&&(m<='f') ) m=m-'a'+10;
18969       else  { bad_char=true; m=0; };
18970       if ( m>=b ) { bad_char=true; m=0; };
18971       if ( n<32768 / b ) n=n*b+m; else n=32767;
18972     }
18973     @<Give error messages if |bad_char| or |n>=4096|@>;
18974   }
18975   mp_flush_cur_exp(mp, n*unity);
18976 }
18977
18978 @ @<Give error messages if |bad_char|...@>=
18979 if ( bad_char ) { 
18980   exp_err("String contains illegal digits");
18981 @.String contains illegal digits@>
18982   if ( c==oct_op ) {
18983     help1("I zeroed out characters that weren't in the range 0..7.");
18984   } else  {
18985     help1("I zeroed out characters that weren't hex digits.");
18986   }
18987   mp_put_get_error(mp);
18988 }
18989 if ( (n>4095) ) {
18990   if ( mp->internal[warning_check]>0 ) {
18991     print_err("Number too large ("); 
18992     mp_print_int(mp, n); mp_print_char(mp, ')');
18993 @.Number too large@>
18994     help2("I have trouble with numbers greater than 4095; watch out.")
18995       ("(Set warningcheck:=0 to suppress this message.)");
18996     mp_put_get_error(mp);
18997   }
18998 }
18999
19000 @ The length operation is somewhat unusual in that it applies to a variety
19001 of different types of operands.
19002
19003 @<Additional cases of unary...@>=
19004 case length_op: 
19005   switch (mp->cur_type) {
19006   case mp_string_type: mp_flush_cur_exp(mp, length(mp->cur_exp)*unity); break;
19007   case mp_path_type: mp_flush_cur_exp(mp, mp_path_length(mp)); break;
19008   case mp_known: mp->cur_exp=abs(mp->cur_exp); break;
19009   case mp_picture_type: mp_flush_cur_exp(mp, mp_pict_length(mp)); break;
19010   default: 
19011     if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) )
19012       mp_flush_cur_exp(mp, mp_pyth_add(mp, 
19013         value(x_part_loc(value(mp->cur_exp))),
19014         value(y_part_loc(value(mp->cur_exp)))));
19015     else mp_bad_unary(mp, c);
19016     break;
19017   }
19018   break;
19019
19020 @ @<Declare unary action...@>=
19021 scaled mp_path_length (MP mp) { /* computes the length of the current path */
19022   scaled n; /* the path length so far */
19023   pointer p; /* traverser */
19024   p=mp->cur_exp;
19025   if ( left_type(p)==endpoint ) n=-unity; else n=0;
19026   do {  p=link(p); n=n+unity; } while (p!=mp->cur_exp);
19027   return n;
19028 }
19029
19030 @ @<Declare unary action...@>=
19031 scaled mp_pict_length (MP mp) { 
19032   /* counts interior components in picture |cur_exp| */
19033   scaled n; /* the count so far */
19034   pointer p; /* traverser */
19035   n=0;
19036   p=link(dummy_loc(mp->cur_exp));
19037   if ( p!=null ) {
19038     if ( is_start_or_stop(p) )
19039       if ( mp_skip_1component(mp, p)==null ) p=link(p);
19040     while ( p!=null )  { 
19041       skip_component(p) return n; 
19042       n=n+unity;   
19043     }
19044   }
19045   return n;
19046 }
19047
19048 @ Implement |turningnumber|
19049
19050 @<Additional cases of unary...@>=
19051 case turning_op:
19052   if ( mp->cur_type==mp_pair_type ) mp_flush_cur_exp(mp, 0);
19053   else if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, turning_op);
19054   else if ( left_type(mp->cur_exp)==endpoint )
19055      mp_flush_cur_exp(mp, 0); /* not a cyclic path */
19056   else
19057     mp_flush_cur_exp(mp, mp_turn_cycles_wrapper(mp, mp->cur_exp));
19058   break;
19059
19060 @ The function |an_angle| returns the value of the |angle| primitive, or $0$ if the
19061 argument is |origin|.
19062
19063 @<Declare unary action...@>=
19064 angle mp_an_angle (MP mp,scaled xpar, scaled ypar) {
19065   if ( (! ((xpar==0) && (ypar==0))) )
19066     return mp_n_arg(mp, xpar,ypar);
19067   return 0;
19068 }
19069
19070
19071 @ The actual turning number is (for the moment) computed in a C function
19072 that receives eight integers corresponding to the four controlling points,
19073 and returns a single angle.  Besides those, we have to account for discrete
19074 moves at the actual points.
19075
19076 @d floor(a) (a>=0 ? a : -(int)(-a))
19077 @d bezier_error (720<<20)+1
19078 @d sign(v) ((v)>0 ? 1 : ((v)<0 ? -1 : 0 ))
19079 @d print_roots(a) { if (debuglevel>(65536*2))
19080    fprintf(stdout,"bezier_slope(): %s, i=%f, o=%f, angle=%f\n", (a),in,out,res); }
19081 @d out ((double)(xo>>20))
19082 @d mid ((double)(xm>>20))
19083 @d in  ((double)(xi>>20))
19084 @d divisor (256*256)
19085 @d double2angle(a) (int)floor(a*256.0*256.0*16.0)
19086
19087 @<Declare unary action...@>=
19088 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19089             integer CX,integer CY,integer DX,integer DY, int debuglevel);
19090
19091 @ @c 
19092 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19093             integer CX,integer CY,integer DX,integer DY, int debuglevel) {
19094   double a, b, c;
19095   integer deltax,deltay;
19096   double ax,ay,bx,by,cx,cy,dx,dy;
19097   angle xi = 0, xo = 0, xm = 0;
19098   double res = 0;
19099   ax=AX/divisor;  ay=AY/divisor;
19100   bx=BX/divisor;  by=BY/divisor;
19101   cx=CX/divisor;  cy=CY/divisor;
19102   dx=DX/divisor;  dy=DY/divisor;
19103
19104   deltax = (BX-AX); deltay = (BY-AY);
19105   if (deltax==0 && deltay == 0) { deltax=(CX-AX); deltay=(CY-AY); }
19106   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19107   xi = mp_an_angle(mp,deltax,deltay);
19108
19109   deltax = (CX-BX); deltay = (CY-BY);
19110   xm = mp_an_angle(mp,deltax,deltay);
19111
19112   deltax = (DX-CX); deltay = (DY-CY);
19113   if (deltax==0 && deltay == 0) { deltax=(DX-BX); deltay=(DY-BY); }
19114   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19115   xo = mp_an_angle(mp,deltax,deltay);
19116
19117   a = (bx-ax)*(cy-by) - (cx-bx)*(by-ay); /* a = (bp-ap)x(cp-bp); */
19118   b = (bx-ax)*(dy-cy) - (by-ay)*(dx-cx);; /* b = (bp-ap)x(dp-cp);*/
19119   c = (cx-bx)*(dy-cy) - (dx-cx)*(cy-by); /* c = (cp-bp)x(dp-cp);*/
19120
19121   if (debuglevel>(65536*2)) {
19122     fprintf(stdout,
19123       "bezier_slope(): (%.2f,%.2f),(%.2f,%.2f),(%.2f,%.2f),(%.2f,%.2f)\n",
19124               ax,ay,bx,by,cx,cy,dx,dy);
19125     fprintf(stdout,
19126       "bezier_slope(): a,b,c,b^2,4ac: (%.2f,%.2f,%.2f,%.2f,%.2f)\n",a,b,c,b*b,4*a*c);
19127   }
19128
19129   if ((a==0)&&(c==0)) {
19130     res = (b==0 ?  0 :  (out-in)); 
19131     print_roots("no roots (a)");
19132   } else if ((a==0)||(c==0)) {
19133     if ((sign(b) == sign(a)) || (sign(b) == sign(c))) {
19134       res = out-in; /* ? */
19135       if (res<-180.0) 
19136         res += 360.0;
19137       else if (res>180.0)
19138         res -= 360.0;
19139       print_roots("no roots (b)");
19140     } else {
19141       res = out-in; /* ? */
19142       print_roots("one root (a)");
19143     }
19144   } else if ((sign(a)*sign(c))<0) {
19145     res = out-in; /* ? */
19146       if (res<-180.0) 
19147         res += 360.0;
19148       else if (res>180.0)
19149         res -= 360.0;
19150     print_roots("one root (b)");
19151   } else {
19152     if (sign(a) == sign(b)) {
19153       res = out-in; /* ? */
19154       if (res<-180.0) 
19155         res += 360.0;
19156       else if (res>180.0)
19157         res -= 360.0;
19158       print_roots("no roots (d)");
19159     } else {
19160       if ((b*b) == (4*a*c)) {
19161         res = bezier_error;
19162         print_roots("double root"); /* cusp */
19163       } else if ((b*b) < (4*a*c)) {
19164         res = out-in; /* ? */
19165         if (res<=0.0 &&res>-180.0) 
19166           res += 360.0;
19167         else if (res>=0.0 && res<180.0)
19168           res -= 360.0;
19169         print_roots("no roots (e)");
19170       } else {
19171         res = out-in;
19172         if (res<-180.0) 
19173           res += 360.0;
19174         else if (res>180.0)
19175           res -= 360.0;
19176         print_roots("two roots"); /* two inflections */
19177       }
19178     }
19179   }
19180   return double2angle(res);
19181 }
19182
19183 @
19184 @d p_nextnext link(link(p))
19185 @d p_next link(p)
19186 @d seven_twenty_deg 05500000000 /* $720\cdot2^{20}$, represents $720^\circ$ */
19187
19188 @<Declare unary action...@>=
19189 scaled mp_new_turn_cycles (MP mp,pointer c) {
19190   angle res,ang; /*  the angles of intermediate results  */
19191   scaled turns;  /*  the turn counter  */
19192   pointer p;     /*  for running around the path  */
19193   integer xp,yp;   /*  coordinates of next point  */
19194   integer x,y;   /*  helper coordinates  */
19195   angle in_angle,out_angle;     /*  helper angles */
19196   int old_setting; /* saved |selector| setting */
19197   res=0;
19198   turns= 0;
19199   p=c;
19200   old_setting = mp->selector; mp->selector=term_only;
19201   if ( mp->internal[tracing_commands]>unity ) {
19202     mp_begin_diagnostic(mp);
19203     mp_print_nl(mp, "");
19204     mp_end_diagnostic(mp, false);
19205   }
19206   do { 
19207     xp = x_coord(p_next); yp = y_coord(p_next);
19208     ang  = mp_bezier_slope(mp,x_coord(p), y_coord(p), right_x(p), right_y(p),
19209              left_x(p_next), left_y(p_next), xp, yp, 
19210              mp->internal[tracing_commands]);
19211     if ( ang>seven_twenty_deg ) {
19212       print_err("Strange path");
19213       mp_error(mp);
19214       mp->selector=old_setting;
19215       return 0;
19216     }
19217     res  = res + ang;
19218     if ( res > one_eighty_deg ) {
19219       res = res - three_sixty_deg;
19220       turns = turns + unity;
19221     }
19222     if ( res <= -one_eighty_deg ) {
19223       res = res + three_sixty_deg;
19224       turns = turns - unity;
19225     }
19226     /*  incoming angle at next point  */
19227     x = left_x(p_next);  y = left_y(p_next);
19228     if ( (xp==x)&&(yp==y) ) { x = right_x(p);  y = right_y(p);  };
19229     if ( (xp==x)&&(yp==y) ) { x = x_coord(p);  y = y_coord(p);  };
19230     in_angle = mp_an_angle(mp, xp - x, yp - y);
19231     /*  outgoing angle at next point  */
19232     x = right_x(p_next);  y = right_y(p_next);
19233     if ( (xp==x)&&(yp==y) ) { x = left_x(p_nextnext);  y = left_y(p_nextnext);  };
19234     if ( (xp==x)&&(yp==y) ) { x = x_coord(p_nextnext); y = y_coord(p_nextnext); };
19235     out_angle = mp_an_angle(mp, x - xp, y- yp);
19236     ang  = (out_angle - in_angle);
19237     reduce_angle(ang);
19238     if ( ang!=0 ) {
19239       res  = res + ang;
19240       if ( res >= one_eighty_deg ) {
19241         res = res - three_sixty_deg;
19242         turns = turns + unity;
19243       };
19244       if ( res <= -one_eighty_deg ) {
19245         res = res + three_sixty_deg;
19246         turns = turns - unity;
19247       };
19248     };
19249     p = link(p);
19250   } while (p!=c);
19251   mp->selector=old_setting;
19252   return turns;
19253 }
19254
19255
19256 @ This code is based on Bogus\l{}av Jackowski's
19257 |emergency_turningnumber| macro, with some minor changes by Taco
19258 Hoekwater. The macro code looked more like this:
19259 {\obeylines
19260 vardef turning\_number primary p =
19261 ~~save res, ang, turns;
19262 ~~res := 0;
19263 ~~if length p <= 2:
19264 ~~~~if Angle ((point 0 of p) - (postcontrol 0 of p)) >= 0:  1  else: -1 fi
19265 ~~else:
19266 ~~~~for t = 0 upto length p-1 :
19267 ~~~~~~angc := Angle ((point t+1 of p)  - (point t of p))
19268 ~~~~~~~~- Angle ((point t of p) - (point t-1 of p));
19269 ~~~~~~if angc > 180: angc := angc - 360; fi;
19270 ~~~~~~if angc < -180: angc := angc + 360; fi;
19271 ~~~~~~res  := res + angc;
19272 ~~~~endfor;
19273 ~~res/360
19274 ~~fi
19275 enddef;}
19276 The general idea is to calculate only the sum of the angles of
19277 straight lines between the points, of a path, not worrying about cusps
19278 or self-intersections in the segments at all. If the segment is not
19279 well-behaved, the result is not necesarily correct. But the old code
19280 was not always correct either, and worse, it sometimes failed for
19281 well-behaved paths as well. All known bugs that were triggered by the
19282 original code no longer occur with this code, and it runs roughly 3
19283 times as fast because the algorithm is much simpler.
19284
19285 @ It is possible to overflow the return value of the |turn_cycles|
19286 function when the path is sufficiently long and winding, but I am not
19287 going to bother testing for that. In any case, it would only return
19288 the looped result value, which is not a big problem.
19289
19290 The macro code for the repeat loop was a bit nicer to look
19291 at than the pascal code, because it could use |point -1 of p|. In
19292 pascal, the fastest way to loop around the path is not to look
19293 backward once, but forward twice. These defines help hide the trick.
19294
19295 @d p_to link(link(p))
19296 @d p_here link(p)
19297 @d p_from p
19298
19299 @<Declare unary action...@>=
19300 scaled mp_turn_cycles (MP mp,pointer c) {
19301   angle res,ang; /*  the angles of intermediate results  */
19302   scaled turns;  /*  the turn counter  */
19303   pointer p;     /*  for running around the path  */
19304   res=0;  turns= 0; p=c;
19305   do { 
19306     ang  = mp_an_angle (mp, x_coord(p_to) - x_coord(p_here), 
19307                             y_coord(p_to) - y_coord(p_here))
19308         - mp_an_angle (mp, x_coord(p_here) - x_coord(p_from), 
19309                            y_coord(p_here) - y_coord(p_from));
19310     reduce_angle(ang);
19311     res  = res + ang;
19312     if ( res >= three_sixty_deg )  {
19313       res = res - three_sixty_deg;
19314       turns = turns + unity;
19315     };
19316     if ( res <= -three_sixty_deg ) {
19317       res = res + three_sixty_deg;
19318       turns = turns - unity;
19319     };
19320     p = link(p);
19321   } while (p!=c);
19322   return turns;
19323 }
19324
19325 @ @<Declare unary action...@>=
19326 scaled mp_turn_cycles_wrapper (MP mp,pointer c) {
19327   scaled nval,oval;
19328   scaled saved_t_o; /* tracing\_online saved  */
19329   if ( (link(c)==c)||(link(link(c))==c) ) {
19330     if ( mp_an_angle (mp, x_coord(c) - right_x(c),  y_coord(c) - right_y(c)) > 0 )
19331       return unity;
19332     else
19333       return -unity;
19334   } else {
19335     nval = mp_new_turn_cycles(mp, c);
19336     oval = mp_turn_cycles(mp, c);
19337     if ( nval!=oval ) {
19338       saved_t_o=mp->internal[tracing_online];
19339       mp->internal[tracing_online]=unity;
19340       mp_begin_diagnostic(mp);
19341       mp_print_nl (mp, "Warning: the turningnumber algorithms do not agree."
19342                        " The current computed value is ");
19343       mp_print_scaled(mp, nval);
19344       mp_print(mp, ", but the 'connect-the-dots' algorithm returned ");
19345       mp_print_scaled(mp, oval);
19346       mp_end_diagnostic(mp, false);
19347       mp->internal[tracing_online]=saved_t_o;
19348     }
19349     return nval;
19350   }
19351 }
19352
19353 @ @<Declare unary action...@>=
19354 scaled mp_count_turns (MP mp,pointer c) {
19355   pointer p; /* a knot in envelope spec |c| */
19356   integer t; /* total pen offset changes counted */
19357   t=0; p=c;
19358   do {  
19359     t=t+info(p)-zero_off;
19360     p=link(p);
19361   } while (p!=c);
19362   return ((t / 3)*unity);
19363 }
19364
19365 @ @d type_range(A,B) { 
19366   if ( (mp->cur_type>=(A)) && (mp->cur_type<=(B)) ) 
19367     mp_flush_cur_exp(mp, true_code);
19368   else mp_flush_cur_exp(mp, false_code);
19369   mp->cur_type=mp_boolean_type;
19370   }
19371 @d type_test(A) { 
19372   if ( mp->cur_type==(A) ) mp_flush_cur_exp(mp, true_code);
19373   else mp_flush_cur_exp(mp, false_code);
19374   mp->cur_type=mp_boolean_type;
19375   }
19376
19377 @<Additional cases of unary operators@>=
19378 case mp_boolean_type: 
19379   type_range(mp_boolean_type,mp_unknown_boolean); break;
19380 case mp_string_type: 
19381   type_range(mp_string_type,mp_unknown_string); break;
19382 case mp_pen_type: 
19383   type_range(mp_pen_type,mp_unknown_pen); break;
19384 case mp_path_type: 
19385   type_range(mp_path_type,mp_unknown_path); break;
19386 case mp_picture_type: 
19387   type_range(mp_picture_type,mp_unknown_picture); break;
19388 case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
19389 case mp_pair_type: 
19390   type_test(c); break;
19391 case mp_numeric_type: 
19392   type_range(mp_known,mp_independent); break;
19393 case known_op: case unknown_op: 
19394   mp_test_known(mp, c); break;
19395
19396 @ @<Declare unary action procedures@>=
19397 void mp_test_known (MP mp,quarterword c) {
19398   int b; /* is the current expression known? */
19399   pointer p,q; /* locations in a big node */
19400   b=false_code;
19401   switch (mp->cur_type) {
19402   case mp_vacuous: case mp_boolean_type: case mp_string_type:
19403   case mp_pen_type: case mp_path_type: case mp_picture_type:
19404   case mp_known: 
19405     b=true_code;
19406     break;
19407   case mp_transform_type:
19408   case mp_color_type: case mp_cmykcolor_type: case mp_pair_type: 
19409     p=value(mp->cur_exp);
19410     q=p+mp->big_node_size[mp->cur_type];
19411     do {  
19412       q=q-2;
19413       if ( type(q)!=mp_known ) 
19414        goto DONE;
19415     } while (q!=p);
19416     b=true_code;
19417   DONE:  
19418     break;
19419   default: 
19420     break;
19421   }
19422   if ( c==known_op ) mp_flush_cur_exp(mp, b);
19423   else mp_flush_cur_exp(mp, true_code+false_code-b);
19424   mp->cur_type=mp_boolean_type;
19425 }
19426
19427 @ @<Additional cases of unary operators@>=
19428 case cycle_op: 
19429   if ( mp->cur_type!=mp_path_type ) mp_flush_cur_exp(mp, false_code);
19430   else if ( left_type(mp->cur_exp)!=endpoint ) mp_flush_cur_exp(mp, true_code);
19431   else mp_flush_cur_exp(mp, false_code);
19432   mp->cur_type=mp_boolean_type;
19433   break;
19434
19435 @ @<Additional cases of unary operators@>=
19436 case arc_length: 
19437   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19438   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, arc_length);
19439   else mp_flush_cur_exp(mp, mp_get_arc_length(mp, mp->cur_exp));
19440   break;
19441
19442 @ Here we use the fact that |c-filled_op+fill_code| is the desired graphical
19443 object |type|.
19444 @^data structure assumptions@>
19445
19446 @<Additional cases of unary operators@>=
19447 case filled_op:
19448 case stroked_op:
19449 case textual_op:
19450 case clipped_op:
19451 case bounded_op:
19452   if ( mp->cur_type!=mp_picture_type ) mp_flush_cur_exp(mp, false_code);
19453   else if ( link(dummy_loc(mp->cur_exp))==null ) mp_flush_cur_exp(mp, false_code);
19454   else if ( type(link(dummy_loc(mp->cur_exp)))==c+fill_code-filled_op )
19455     mp_flush_cur_exp(mp, true_code);
19456   else mp_flush_cur_exp(mp, false_code);
19457   mp->cur_type=mp_boolean_type;
19458   break;
19459
19460 @ @<Additional cases of unary operators@>=
19461 case make_pen_op: 
19462   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19463   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, make_pen_op);
19464   else { 
19465     mp->cur_type=mp_pen_type;
19466     mp->cur_exp=mp_make_pen(mp, mp->cur_exp,true);
19467   };
19468   break;
19469 case make_path_op: 
19470   if ( mp->cur_type!=mp_pen_type ) mp_bad_unary(mp, make_path_op);
19471   else  { 
19472     mp->cur_type=mp_path_type;
19473     mp_make_path(mp, mp->cur_exp);
19474   };
19475   break;
19476 case reverse: 
19477   if ( mp->cur_type==mp_path_type ) {
19478     p=mp_htap_ypoc(mp, mp->cur_exp);
19479     if ( right_type(p)==endpoint ) p=link(p);
19480     mp_toss_knot_list(mp, mp->cur_exp); mp->cur_exp=p;
19481   } else if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19482   else mp_bad_unary(mp, reverse);
19483   break;
19484
19485 @ The |pair_value| routine changes the current expression to a
19486 given ordered pair of values.
19487
19488 @<Declare unary action procedures@>=
19489 void mp_pair_value (MP mp,scaled x, scaled y) {
19490   pointer p; /* a pair node */
19491   p=mp_get_node(mp, value_node_size); 
19492   mp_flush_cur_exp(mp, p); mp->cur_type=mp_pair_type;
19493   type(p)=mp_pair_type; name_type(p)=mp_capsule; mp_init_big_node(mp, p);
19494   p=value(p);
19495   type(x_part_loc(p))=mp_known; value(x_part_loc(p))=x;
19496   type(y_part_loc(p))=mp_known; value(y_part_loc(p))=y;
19497 }
19498
19499 @ @<Additional cases of unary operators@>=
19500 case ll_corner_op: 
19501   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ll_corner_op);
19502   else mp_pair_value(mp, minx,miny);
19503   break;
19504 case lr_corner_op: 
19505   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, lr_corner_op);
19506   else mp_pair_value(mp, maxx,miny);
19507   break;
19508 case ul_corner_op: 
19509   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ul_corner_op);
19510   else mp_pair_value(mp, minx,maxy);
19511   break;
19512 case ur_corner_op: 
19513   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ur_corner_op);
19514   else mp_pair_value(mp, maxx,maxy);
19515   break;
19516
19517 @ Here is a function that sets |minx|, |maxx|, |miny|, |maxy| to the bounding
19518 box of the current expression.  The boolean result is |false| if the expression
19519 has the wrong type.
19520
19521 @<Declare unary action procedures@>=
19522 boolean mp_get_cur_bbox (MP mp) { 
19523   switch (mp->cur_type) {
19524   case mp_picture_type: 
19525     mp_set_bbox(mp, mp->cur_exp,true);
19526     if ( minx_val(mp->cur_exp)>maxx_val(mp->cur_exp) ) {
19527       minx=0; maxx=0; miny=0; maxy=0;
19528     } else { 
19529       minx=minx_val(mp->cur_exp);
19530       maxx=maxx_val(mp->cur_exp);
19531       miny=miny_val(mp->cur_exp);
19532       maxy=maxy_val(mp->cur_exp);
19533     }
19534     break;
19535   case mp_path_type: 
19536     mp_path_bbox(mp, mp->cur_exp);
19537     break;
19538   case mp_pen_type: 
19539     mp_pen_bbox(mp, mp->cur_exp);
19540     break;
19541   default: 
19542     return false;
19543   }
19544   return true;
19545 }
19546
19547 @ @<Additional cases of unary operators@>=
19548 case read_from_op:
19549 case close_from_op: 
19550   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19551   else mp_do_read_or_close(mp,c);
19552   break;
19553
19554 @ Here is a routine that interprets |cur_exp| as a file name and tries to read
19555 a line from the file or to close the file.
19556
19557 @d close_file 46 /* go here when closing the file */
19558
19559 @<Declare unary action procedures@>=
19560 void mp_do_read_or_close (MP mp,quarterword c) {
19561   readf_index n,n0; /* indices for searching |rd_fname| */
19562   @<Find the |n| where |rd_fname[n]=cur_exp|; if |cur_exp| must be inserted,
19563     call |start_read_input| and |goto found| or |not_found|@>;
19564   mp_begin_file_reading(mp);
19565   name=is_read;
19566   if ( mp_input_ln(mp, mp->rd_file[n],true) ) 
19567     goto FOUND;
19568   mp_end_file_reading(mp);
19569 NOT_FOUND:
19570   @<Record the end of file and set |cur_exp| to a dummy value@>;
19571   return;
19572 CLOSE_FILE:
19573   mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous; 
19574   return;
19575 FOUND:
19576   mp_flush_cur_exp(mp, 0);
19577   mp_finish_read(mp);
19578 }
19579
19580 @ Free slots in the |rd_file| and |rd_fname| arrays are marked with NULL's in
19581 |rd_fname|.
19582
19583 @<Find the |n| where |rd_fname[n]=cur_exp|...@>=
19584 {   
19585   char *fn;
19586   n=mp->read_files;
19587   n0=mp->read_files;
19588   fn = str(mp->cur_exp);
19589   while (mp_xstrcmp(fn,mp->rd_fname[n])!=0) { 
19590     if ( n>0 ) {
19591       decr(n);
19592     } else if ( c==close_from_op ) {
19593       goto CLOSE_FILE;
19594     } else {
19595       if ( n0==mp->read_files ) {
19596         if ( mp->read_files<mp->max_read_files ) {
19597           incr(mp->read_files);
19598         } else {
19599           FILE **rd_file;
19600           char **rd_fname;
19601               readf_index l,k;
19602           l = mp->max_read_files + (mp->max_read_files>>2);
19603           rd_file = xmalloc((l+1), sizeof(FILE *));
19604           rd_fname = xmalloc((l+1), sizeof(char *));
19605               for (k=0;k<=l;k++) {
19606             if (k<=mp->max_read_files) {
19607                   rd_file[k]=mp->rd_file[k]; 
19608               rd_fname[k]=mp->rd_fname[k];
19609             } else {
19610                   rd_file[k]=0; 
19611               rd_fname[k]=NULL;
19612             }
19613           }
19614               xfree(mp->rd_file); xfree(mp->rd_fname);
19615           mp->max_read_files = l;
19616           mp->rd_file = rd_file;
19617           mp->rd_fname = rd_fname;
19618         }
19619       }
19620       n=n0;
19621       if ( mp_start_read_input(mp,fn,n) ) 
19622         goto FOUND;
19623       else 
19624         goto NOT_FOUND;
19625     }
19626     if ( mp->rd_fname[n]==NULL ) { n0=n; }
19627   } 
19628   if ( c==close_from_op ) { 
19629     fclose(mp->rd_file[n]); 
19630     goto NOT_FOUND; 
19631   }
19632 }
19633
19634 @ @<Record the end of file and set |cur_exp| to a dummy value@>=
19635 xfree(mp->rd_fname[n]);
19636 mp->rd_fname[n]=NULL;
19637 if ( n==mp->read_files-1 ) mp->read_files=n;
19638 if ( c==close_from_op ) 
19639   goto CLOSE_FILE;
19640 mp_flush_cur_exp(mp, mp->eof_line);
19641 mp->cur_type=mp_string_type
19642
19643 @ The string denoting end-of-file is a one-byte string at position zero, by definition
19644
19645 @<Glob...@>=
19646 str_number eof_line;
19647
19648 @ @<Set init...@>=
19649 mp->eof_line=0;
19650
19651 @ Finally, we have the operations that combine a capsule~|p|
19652 with the current expression.
19653
19654 @c @<Declare binary action procedures@>;
19655 void mp_do_binary (MP mp,pointer p, quarterword c) {
19656   pointer q,r,rr; /* for list manipulation */
19657   pointer old_p,old_exp; /* capsules to recycle */
19658   integer v; /* for numeric manipulation */
19659   check_arith;
19660   if ( mp->internal[tracing_commands]>two ) {
19661     @<Trace the current binary operation@>;
19662   }
19663   @<Sidestep |independent| cases in capsule |p|@>;
19664   @<Sidestep |independent| cases in the current expression@>;
19665   switch (c) {
19666   case plus: case minus:
19667     @<Add or subtract the current expression from |p|@>;
19668     break;
19669   @<Additional cases of binary operators@>;
19670   }; /* there are no other cases */
19671   mp_recycle_value(mp, p); 
19672   mp_free_node(mp, p,value_node_size); /* |return| to avoid this */
19673   check_arith; 
19674   @<Recycle any sidestepped |independent| capsules@>;
19675 }
19676
19677 @ @<Declare binary action...@>=
19678 void mp_bad_binary (MP mp,pointer p, quarterword c) { 
19679   mp_disp_err(mp, p,"");
19680   exp_err("Not implemented: ");
19681 @.Not implemented...@>
19682   if ( c>=min_of ) mp_print_op(mp, c);
19683   mp_print_known_or_unknown_type(mp, type(p),p);
19684   if ( c>=min_of ) mp_print(mp, "of"); else mp_print_op(mp, c);
19685   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
19686   help3("I'm afraid I don't know how to apply that operation to that")
19687        ("combination of types. Continue, and I'll return the second")
19688       ("argument (see above) as the result of the operation.");
19689   mp_put_get_error(mp);
19690 }
19691
19692 @ @<Trace the current binary operation@>=
19693
19694   mp_begin_diagnostic(mp); mp_print_nl(mp, "{(");
19695   mp_print_exp(mp,p,0); /* show the operand, but not verbosely */
19696   mp_print_char(mp,')'); mp_print_op(mp,c); mp_print_char(mp,'(');
19697   mp_print_exp(mp,null,0); mp_print(mp,")}"); 
19698   mp_end_diagnostic(mp, false);
19699 }
19700
19701 @ Several of the binary operations are potentially complicated by the
19702 fact that |independent| values can sneak into capsules. For example,
19703 we've seen an instance of this difficulty in the unary operation
19704 of negation. In order to reduce the number of cases that need to be
19705 handled, we first change the two operands (if necessary)
19706 to rid them of |independent| components. The original operands are
19707 put into capsules called |old_p| and |old_exp|, which will be
19708 recycled after the binary operation has been safely carried out.
19709
19710 @<Recycle any sidestepped |independent| capsules@>=
19711 if ( old_p!=null ) { 
19712   mp_recycle_value(mp, old_p); mp_free_node(mp, old_p,value_node_size);
19713 }
19714 if ( old_exp!=null ) {
19715   mp_recycle_value(mp, old_exp); mp_free_node(mp, old_exp,value_node_size);
19716 }
19717
19718 @ A big node is considered to be ``tarnished'' if it contains at least one
19719 independent component. We will define a simple function called `|tarnished|'
19720 that returns |null| if and only if its argument is not tarnished.
19721
19722 @<Sidestep |independent| cases in capsule |p|@>=
19723 switch (type(p)) {
19724 case mp_transform_type:
19725 case mp_color_type:
19726 case mp_cmykcolor_type:
19727 case mp_pair_type: 
19728   old_p=mp_tarnished(mp, p);
19729   break;
19730 case mp_independent: old_p=diov; break;
19731 default: old_p=null; break;
19732 };
19733 if ( old_p!=null ) {
19734   q=mp_stash_cur_exp(mp); old_p=p; mp_make_exp_copy(mp, old_p);
19735   p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
19736 }
19737
19738 @ @<Sidestep |independent| cases in the current expression@>=
19739 switch (mp->cur_type) {
19740 case mp_transform_type:
19741 case mp_color_type:
19742 case mp_cmykcolor_type:
19743 case mp_pair_type: 
19744   old_exp=mp_tarnished(mp, mp->cur_exp);
19745   break;
19746 case mp_independent:old_exp=diov; break;
19747 default: old_exp=null; break;
19748 };
19749 if ( old_exp!=null ) {
19750   old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
19751 }
19752
19753 @ @<Declare binary action...@>=
19754 pointer mp_tarnished (MP mp,pointer p) {
19755   pointer q; /* beginning of the big node */
19756   pointer r; /* current position in the big node */
19757   q=value(p); r=q+mp->big_node_size[type(p)];
19758   do {  
19759    r=r-2;
19760    if ( type(r)==mp_independent ) return diov; 
19761   } while (r!=q);
19762   return null;
19763 }
19764
19765 @ @<Add or subtract the current expression from |p|@>=
19766 if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
19767   mp_bad_binary(mp, p,c);
19768 } else  {
19769   if ((mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
19770     mp_add_or_subtract(mp, p,null,c);
19771   } else {
19772     if ( mp->cur_type!=type(p) )  {
19773       mp_bad_binary(mp, p,c);
19774     } else { 
19775       q=value(p); r=value(mp->cur_exp);
19776       rr=r+mp->big_node_size[mp->cur_type];
19777       while ( r<rr ) { 
19778         mp_add_or_subtract(mp, q,r,c);
19779         q=q+2; r=r+2;
19780       }
19781     }
19782   }
19783 }
19784
19785 @ The first argument to |add_or_subtract| is the location of a value node
19786 in a capsule or pair node that will soon be recycled. The second argument
19787 is either a location within a pair or transform node of |cur_exp|,
19788 or it is null (which means that |cur_exp| itself should be the second
19789 argument).  The third argument is either |plus| or |minus|.
19790
19791 The sum or difference of the numeric quantities will replace the second
19792 operand.  Arithmetic overflow may go undetected; users aren't supposed to
19793 be monkeying around with really big values.
19794
19795 @<Declare binary action...@>=
19796 @<Declare the procedure called |dep_finish|@>;
19797 void mp_add_or_subtract (MP mp,pointer p, pointer q, quarterword c) {
19798   small_number s,t; /* operand types */
19799   pointer r; /* list traverser */
19800   integer v; /* second operand value */
19801   if ( q==null ) { 
19802     t=mp->cur_type;
19803     if ( t<mp_dependent ) v=mp->cur_exp; else v=dep_list(mp->cur_exp);
19804   } else { 
19805     t=type(q);
19806     if ( t<mp_dependent ) v=value(q); else v=dep_list(q);
19807   }
19808   if ( t==mp_known ) {
19809     if ( c==minus ) negate(v);
19810     if ( type(p)==mp_known ) {
19811       v=mp_slow_add(mp, value(p),v);
19812       if ( q==null ) mp->cur_exp=v; else value(q)=v;
19813       return;
19814     }
19815     @<Add a known value to the constant term of |dep_list(p)|@>;
19816   } else  { 
19817     if ( c==minus ) mp_negate_dep_list(mp, v);
19818     @<Add operand |p| to the dependency list |v|@>;
19819   }
19820 }
19821
19822 @ @<Add a known value to the constant term of |dep_list(p)|@>=
19823 r=dep_list(p);
19824 while ( info(r)!=null ) r=link(r);
19825 value(r)=mp_slow_add(mp, value(r),v);
19826 if ( q==null ) {
19827   q=mp_get_node(mp, value_node_size); mp->cur_exp=q; mp->cur_type=type(p);
19828   name_type(q)=mp_capsule;
19829 }
19830 dep_list(q)=dep_list(p); type(q)=type(p);
19831 prev_dep(q)=prev_dep(p); link(prev_dep(p))=q;
19832 type(p)=mp_known; /* this will keep the recycler from collecting non-garbage */
19833
19834 @ We prefer |dependent| lists to |mp_proto_dependent| ones, because it is
19835 nice to retain the extra accuracy of |fraction| coefficients.
19836 But we have to handle both kinds, and mixtures too.
19837
19838 @<Add operand |p| to the dependency list |v|@>=
19839 if ( type(p)==mp_known ) {
19840   @<Add the known |value(p)| to the constant term of |v|@>;
19841 } else { 
19842   s=type(p); r=dep_list(p);
19843   if ( t==mp_dependent ) {
19844     if ( s==mp_dependent ) {
19845       if ( mp_max_coef(mp, r)+mp_max_coef(mp, v)<coef_bound )
19846         v=mp_p_plus_q(mp, v,r,mp_dependent); goto DONE;
19847       } /* |fix_needed| will necessarily be false */
19848       t=mp_proto_dependent; 
19849       v=mp_p_over_v(mp, v,unity,mp_dependent,mp_proto_dependent);
19850     }
19851     if ( s==mp_proto_dependent ) v=mp_p_plus_q(mp, v,r,mp_proto_dependent);
19852     else v=mp_p_plus_fq(mp, v,unity,r,mp_proto_dependent,mp_dependent);
19853  DONE:  
19854     @<Output the answer, |v| (which might have become |known|)@>;
19855   }
19856
19857 @ @<Add the known |value(p)| to the constant term of |v|@>=
19858
19859   while ( info(v)!=null ) v=link(v);
19860   value(v)=mp_slow_add(mp, value(p),value(v));
19861 }
19862
19863 @ @<Output the answer, |v| (which might have become |known|)@>=
19864 if ( q!=null ) mp_dep_finish(mp, v,q,t);
19865 else  { mp->cur_type=t; mp_dep_finish(mp, v,null,t); }
19866
19867 @ Here's the current situation: The dependency list |v| of type |t|
19868 should either be put into the current expression (if |q=null|) or
19869 into location |q| within a pair node (otherwise). The destination (|cur_exp|
19870 or |q|) formerly held a dependency list with the same
19871 final pointer as the list |v|.
19872
19873 @<Declare the procedure called |dep_finish|@>=
19874 void mp_dep_finish (MP mp, pointer v, pointer q, small_number t) {
19875   pointer p; /* the destination */
19876   scaled vv; /* the value, if it is |known| */
19877   if ( q==null ) p=mp->cur_exp; else p=q;
19878   dep_list(p)=v; type(p)=t;
19879   if ( info(v)==null ) { 
19880     vv=value(v);
19881     if ( q==null ) { 
19882       mp_flush_cur_exp(mp, vv);
19883     } else  { 
19884       mp_recycle_value(mp, p); type(q)=mp_known; value(q)=vv; 
19885     }
19886   } else if ( q==null ) {
19887     mp->cur_type=t;
19888   }
19889   if ( mp->fix_needed ) mp_fix_dependencies(mp);
19890 }
19891
19892 @ Let's turn now to the six basic relations of comparison.
19893
19894 @<Additional cases of binary operators@>=
19895 case less_than: case less_or_equal: case greater_than:
19896 case greater_or_equal: case equal_to: case unequal_to:
19897   check_arith; /* at this point |arith_error| should be |false|? */
19898   if ( (mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
19899     mp_add_or_subtract(mp, p,null,minus); /* |cur_exp:=(p)-cur_exp| */
19900   } else if ( mp->cur_type!=type(p) ) {
19901     mp_bad_binary(mp, p,c); goto DONE; 
19902   } else if ( mp->cur_type==mp_string_type ) {
19903     mp_flush_cur_exp(mp, mp_str_vs_str(mp, value(p),mp->cur_exp));
19904   } else if ((mp->cur_type==mp_unknown_string)||
19905            (mp->cur_type==mp_unknown_boolean) ) {
19906     @<Check if unknowns have been equated@>;
19907   } else if ( (mp->cur_type<=mp_pair_type)&&(mp->cur_type>=mp_transform_type)) {
19908     @<Reduce comparison of big nodes to comparison of scalars@>;
19909   } else if ( mp->cur_type==mp_boolean_type ) {
19910     mp_flush_cur_exp(mp, mp->cur_exp-value(p));
19911   } else { 
19912     mp_bad_binary(mp, p,c); goto DONE;
19913   }
19914   @<Compare the current expression with zero@>;
19915 DONE:  
19916   mp->arith_error=false; /* ignore overflow in comparisons */
19917   break;
19918
19919 @ @<Compare the current expression with zero@>=
19920 if ( mp->cur_type!=mp_known ) {
19921   if ( mp->cur_type<mp_known ) {
19922     mp_disp_err(mp, p,"");
19923     help1("The quantities shown above have not been equated.")
19924   } else  {
19925     help2("Oh dear. I can\'t decide if the expression above is positive,")
19926      ("negative, or zero. So this comparison test won't be `true'.");
19927   }
19928   exp_err("Unknown relation will be considered false");
19929 @.Unknown relation...@>
19930   mp_put_get_flush_error(mp, false_code);
19931 } else {
19932   switch (c) {
19933   case less_than: boolean_reset(mp->cur_exp<0); break;
19934   case less_or_equal: boolean_reset(mp->cur_exp<=0); break;
19935   case greater_than: boolean_reset(mp->cur_exp>0); break;
19936   case greater_or_equal: boolean_reset(mp->cur_exp>=0); break;
19937   case equal_to: boolean_reset(mp->cur_exp==0); break;
19938   case unequal_to: boolean_reset(mp->cur_exp!=0); break;
19939   }; /* there are no other cases */
19940 }
19941 mp->cur_type=mp_boolean_type
19942
19943 @ When two unknown strings are in the same ring, we know that they are
19944 equal. Otherwise, we don't know whether they are equal or not, so we
19945 make no change.
19946
19947 @<Check if unknowns have been equated@>=
19948
19949   q=value(mp->cur_exp);
19950   while ( (q!=mp->cur_exp)&&(q!=p) ) q=value(q);
19951   if ( q==p ) mp_flush_cur_exp(mp, 0);
19952 }
19953
19954 @ @<Reduce comparison of big nodes to comparison of scalars@>=
19955
19956   q=value(p); r=value(mp->cur_exp);
19957   rr=r+mp->big_node_size[mp->cur_type]-2;
19958   while (1) { mp_add_or_subtract(mp, q,r,minus);
19959     if ( type(r)!=mp_known ) break;
19960     if ( value(r)!=0 ) break;
19961     if ( r==rr ) break;
19962     q=q+2; r=r+2;
19963   }
19964   mp_take_part(mp, name_type(r)+x_part-mp_x_part_sector);
19965 }
19966
19967 @ Here we use the sneaky fact that |and_op-false_code=or_op-true_code|.
19968
19969 @<Additional cases of binary operators@>=
19970 case and_op:
19971 case or_op: 
19972   if ( (type(p)!=mp_boolean_type)||(mp->cur_type!=mp_boolean_type) )
19973     mp_bad_binary(mp, p,c);
19974   else if ( value(p)==c+false_code-and_op ) mp->cur_exp=value(p);
19975   break;
19976
19977 @ @<Additional cases of binary operators@>=
19978 case times: 
19979   if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
19980    mp_bad_binary(mp, p,times);
19981   } else if ( (mp->cur_type==mp_known)||(type(p)==mp_known) ) {
19982     @<Multiply when at least one operand is known@>;
19983   } else if ( (mp_nice_color_or_pair(mp, p,type(p))&&(mp->cur_type>mp_pair_type))
19984       ||(mp_nice_color_or_pair(mp, mp->cur_exp,mp->cur_type)&&
19985           (type(p)>mp_pair_type)) ) {
19986     mp_hard_times(mp, p); return;
19987   } else {
19988     mp_bad_binary(mp, p,times);
19989   }
19990   break;
19991
19992 @ @<Multiply when at least one operand is known@>=
19993
19994   if ( type(p)==mp_known ) {
19995     v=value(p); mp_free_node(mp, p,value_node_size); 
19996   } else {
19997     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
19998   }
19999   if ( mp->cur_type==mp_known ) {
20000     mp->cur_exp=mp_take_scaled(mp, mp->cur_exp,v);
20001   } else if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_color_type)||
20002               (mp->cur_type==mp_cmykcolor_type) ) {
20003     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20004     do {  
20005        p=p-2; mp_dep_mult(mp, p,v,true);
20006     } while (p!=value(mp->cur_exp));
20007   } else {
20008     mp_dep_mult(mp, null,v,true);
20009   }
20010   return;
20011 }
20012
20013 @ @<Declare binary action...@>=
20014 void mp_dep_mult (MP mp,pointer p, integer v, boolean v_is_scaled) {
20015   pointer q; /* the dependency list being multiplied by |v| */
20016   small_number s,t; /* its type, before and after */
20017   if ( p==null ) {
20018     q=mp->cur_exp;
20019   } else if ( type(p)!=mp_known ) {
20020     q=p;
20021   } else { 
20022     if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
20023     else value(p)=mp_take_fraction(mp, value(p),v);
20024     return;
20025   };
20026   t=type(q); q=dep_list(q); s=t;
20027   if ( t==mp_dependent ) if ( v_is_scaled )
20028     if (mp_ab_vs_cd(mp, mp_max_coef(mp,q),abs(v),coef_bound-1,unity)>=0 ) 
20029       t=mp_proto_dependent;
20030   q=mp_p_times_v(mp, q,v,s,t,v_is_scaled); 
20031   mp_dep_finish(mp, q,p,t);
20032 }
20033
20034 @ Here is a routine that is similar to |times|; but it is invoked only
20035 internally, when |v| is a |fraction| whose magnitude is at most~1,
20036 and when |cur_type>=mp_color_type|.
20037
20038 @c void mp_frac_mult (MP mp,scaled n, scaled d) {
20039   /* multiplies |cur_exp| by |n/d| */
20040   pointer p; /* a pair node */
20041   pointer old_exp; /* a capsule to recycle */
20042   fraction v; /* |n/d| */
20043   if ( mp->internal[tracing_commands]>two ) {
20044     @<Trace the fraction multiplication@>;
20045   }
20046   switch (mp->cur_type) {
20047   case mp_transform_type:
20048   case mp_color_type:
20049   case mp_cmykcolor_type:
20050   case mp_pair_type:
20051    old_exp=mp_tarnished(mp, mp->cur_exp);
20052    break;
20053   case mp_independent: old_exp=diov; break;
20054   default: old_exp=null; break;
20055   }
20056   if ( old_exp!=null ) { 
20057      old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
20058   }
20059   v=mp_make_fraction(mp, n,d);
20060   if ( mp->cur_type==mp_known ) {
20061     mp->cur_exp=mp_take_fraction(mp, mp->cur_exp,v);
20062   } else if ( mp->cur_type<=mp_pair_type ) { 
20063     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20064     do {  
20065       p=p-2;
20066       mp_dep_mult(mp, p,v,false);
20067     } while (p!=value(mp->cur_exp));
20068   } else {
20069     mp_dep_mult(mp, null,v,false);
20070   }
20071   if ( old_exp!=null ) {
20072     mp_recycle_value(mp, old_exp); 
20073     mp_free_node(mp, old_exp,value_node_size);
20074   }
20075 }
20076
20077 @ @<Trace the fraction multiplication@>=
20078
20079   mp_begin_diagnostic(mp); 
20080   mp_print_nl(mp, "{("); mp_print_scaled(mp,n); mp_print_char(mp,'/');
20081   mp_print_scaled(mp,d); mp_print(mp,")*("); mp_print_exp(mp,null,0); 
20082   mp_print(mp,")}");
20083   mp_end_diagnostic(mp, false);
20084 }
20085
20086 @ The |hard_times| routine multiplies a nice color or pair by a dependency list.
20087
20088 @<Declare binary action procedures@>=
20089 void mp_hard_times (MP mp,pointer p) {
20090   pointer q; /* a copy of the dependent variable |p| */
20091   pointer r; /* a component of the big node for the nice color or pair */
20092   scaled v; /* the known value for |r| */
20093   if ( type(p)<=mp_pair_type ) { 
20094      q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p); p=q;
20095   }; /* now |cur_type=mp_pair_type| or |cur_type=mp_color_type| */
20096   r=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20097   while (1) { 
20098     r=r-2;
20099     v=value(r);
20100     type(r)=type(p);
20101     if ( r==value(mp->cur_exp) ) 
20102       break;
20103     mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(p)));
20104     mp_dep_mult(mp, r,v,true);
20105   }
20106   mp->mem[value_loc(r)]=mp->mem[value_loc(p)];
20107   link(prev_dep(p))=r;
20108   mp_free_node(mp, p,value_node_size);
20109   mp_dep_mult(mp, r,v,true);
20110 }
20111
20112 @ @<Additional cases of binary operators@>=
20113 case over: 
20114   if ( (mp->cur_type!=mp_known)||(type(p)<mp_color_type) ) {
20115     mp_bad_binary(mp, p,over);
20116   } else { 
20117     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20118     if ( v==0 ) {
20119       @<Squeal about division by zero@>;
20120     } else { 
20121       if ( mp->cur_type==mp_known ) {
20122         mp->cur_exp=mp_make_scaled(mp, mp->cur_exp,v);
20123       } else if ( mp->cur_type<=mp_pair_type ) { 
20124         p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20125         do {  
20126           p=p-2;  mp_dep_div(mp, p,v);
20127         } while (p!=value(mp->cur_exp));
20128       } else {
20129         mp_dep_div(mp, null,v);
20130       }
20131     }
20132     return;
20133   }
20134   break;
20135
20136 @ @<Declare binary action...@>=
20137 void mp_dep_div (MP mp,pointer p, scaled v) {
20138   pointer q; /* the dependency list being divided by |v| */
20139   small_number s,t; /* its type, before and after */
20140   if ( p==null ) q=mp->cur_exp;
20141   else if ( type(p)!=mp_known ) q=p;
20142   else { value(p)=mp_make_scaled(mp, value(p),v); return; };
20143   t=type(q); q=dep_list(q); s=t;
20144   if ( t==mp_dependent )
20145     if ( mp_ab_vs_cd(mp, mp_max_coef(mp,q),unity,coef_bound-1,abs(v))>=0 ) 
20146       t=mp_proto_dependent;
20147   q=mp_p_over_v(mp, q,v,s,t); 
20148   mp_dep_finish(mp, q,p,t);
20149 }
20150
20151 @ @<Squeal about division by zero@>=
20152
20153   exp_err("Division by zero");
20154 @.Division by zero@>
20155   help2("You're trying to divide the quantity shown above the error")
20156     ("message by zero. I'm going to divide it by one instead.");
20157   mp_put_get_error(mp);
20158 }
20159
20160 @ @<Additional cases of binary operators@>=
20161 case pythag_add:
20162 case pythag_sub: 
20163    if ( (mp->cur_type==mp_known)&&(type(p)==mp_known) ) {
20164      if ( c==pythag_add ) mp->cur_exp=mp_pyth_add(mp, value(p),mp->cur_exp);
20165      else mp->cur_exp=mp_pyth_sub(mp, value(p),mp->cur_exp);
20166    } else mp_bad_binary(mp, p,c);
20167    break;
20168
20169 @ The next few sections of the program deal with affine transformations
20170 of coordinate data.
20171
20172 @<Additional cases of binary operators@>=
20173 case rotated_by: case slanted_by:
20174 case scaled_by: case shifted_by: case transformed_by:
20175 case x_scaled: case y_scaled: case z_scaled:
20176   if ( type(p)==mp_path_type ) { 
20177     path_trans(c,p); return;
20178   } else if ( type(p)==mp_pen_type ) { 
20179     pen_trans(c,p);
20180     mp->cur_exp=mp_convex_hull(mp, mp->cur_exp); 
20181       /* rounding error could destroy convexity */
20182     return;
20183   } else if ( (type(p)==mp_pair_type)||(type(p)==mp_transform_type) ) {
20184     mp_big_trans(mp, p,c);
20185   } else if ( type(p)==mp_picture_type ) {
20186     mp_do_edges_trans(mp, p,c); return;
20187   } else {
20188     mp_bad_binary(mp, p,c);
20189   }
20190   break;
20191
20192 @ Let |c| be one of the eight transform operators. The procedure call
20193 |set_up_trans(c)| first changes |cur_exp| to a transform that corresponds to
20194 |c| and the original value of |cur_exp|. (In particular, |cur_exp| doesn't
20195 change at all if |c=transformed_by|.)
20196
20197 Then, if all components of the resulting transform are |known|, they are
20198 moved to the global variables |txx|, |txy|, |tyx|, |tyy|, |tx|, |ty|;
20199 and |cur_exp| is changed to the known value zero.
20200
20201 @<Declare binary action...@>=
20202 void mp_set_up_trans (MP mp,quarterword c) {
20203   pointer p,q,r; /* list manipulation registers */
20204   if ( (c!=transformed_by)||(mp->cur_type!=mp_transform_type) ) {
20205     @<Put the current transform into |cur_exp|@>;
20206   }
20207   @<If the current transform is entirely known, stash it in global variables;
20208     otherwise |return|@>;
20209 }
20210
20211 @ @<Glob...@>=
20212 scaled txx;
20213 scaled txy;
20214 scaled tyx;
20215 scaled tyy;
20216 scaled tx;
20217 scaled ty; /* current transform coefficients */
20218
20219 @ @<Put the current transform...@>=
20220
20221   p=mp_stash_cur_exp(mp); 
20222   mp->cur_exp=mp_id_transform(mp); 
20223   mp->cur_type=mp_transform_type;
20224   q=value(mp->cur_exp);
20225   switch (c) {
20226   @<For each of the eight cases, change the relevant fields of |cur_exp|
20227     and |goto done|;
20228     but do nothing if capsule |p| doesn't have the appropriate type@>;
20229   }; /* there are no other cases */
20230   mp_disp_err(mp, p,"Improper transformation argument");
20231 @.Improper transformation argument@>
20232   help3("The expression shown above has the wrong type,")
20233        ("so I can\'t transform anything using it.")
20234        ("Proceed, and I'll omit the transformation.");
20235   mp_put_get_error(mp);
20236 DONE: 
20237   mp_recycle_value(mp, p); 
20238   mp_free_node(mp, p,value_node_size);
20239 }
20240
20241 @ @<If the current transform is entirely known, ...@>=
20242 q=value(mp->cur_exp); r=q+transform_node_size;
20243 do {  
20244   r=r-2;
20245   if ( type(r)!=mp_known ) return;
20246 } while (r!=q);
20247 mp->txx=value(xx_part_loc(q));
20248 mp->txy=value(xy_part_loc(q));
20249 mp->tyx=value(yx_part_loc(q));
20250 mp->tyy=value(yy_part_loc(q));
20251 mp->tx=value(x_part_loc(q));
20252 mp->ty=value(y_part_loc(q));
20253 mp_flush_cur_exp(mp, 0)
20254
20255 @ @<For each of the eight cases...@>=
20256 case rotated_by:
20257   if ( type(p)==mp_known )
20258     @<Install sines and cosines, then |goto done|@>;
20259   break;
20260 case slanted_by:
20261   if ( type(p)>mp_pair_type ) { 
20262    mp_install(mp, xy_part_loc(q),p); goto DONE;
20263   };
20264   break;
20265 case scaled_by:
20266   if ( type(p)>mp_pair_type ) { 
20267     mp_install(mp, xx_part_loc(q),p); mp_install(mp, yy_part_loc(q),p); 
20268     goto DONE;
20269   };
20270   break;
20271 case shifted_by:
20272   if ( type(p)==mp_pair_type ) {
20273     r=value(p); mp_install(mp, x_part_loc(q),x_part_loc(r));
20274     mp_install(mp, y_part_loc(q),y_part_loc(r)); goto DONE;
20275   };
20276   break;
20277 case x_scaled:
20278   if ( type(p)>mp_pair_type ) {
20279     mp_install(mp, xx_part_loc(q),p); goto DONE;
20280   };
20281   break;
20282 case y_scaled:
20283   if ( type(p)>mp_pair_type ) {
20284     mp_install(mp, yy_part_loc(q),p); goto DONE;
20285   };
20286   break;
20287 case z_scaled:
20288   if ( type(p)==mp_pair_type )
20289     @<Install a complex multiplier, then |goto done|@>;
20290   break;
20291 case transformed_by:
20292   break;
20293   
20294
20295 @ @<Install sines and cosines, then |goto done|@>=
20296 { mp_n_sin_cos(mp, (value(p) % three_sixty_units)*16);
20297   value(xx_part_loc(q))=mp_round_fraction(mp, mp->n_cos);
20298   value(yx_part_loc(q))=mp_round_fraction(mp, mp->n_sin);
20299   value(xy_part_loc(q))=-value(yx_part_loc(q));
20300   value(yy_part_loc(q))=value(xx_part_loc(q));
20301   goto DONE;
20302 }
20303
20304 @ @<Install a complex multiplier, then |goto done|@>=
20305
20306   r=value(p);
20307   mp_install(mp, xx_part_loc(q),x_part_loc(r));
20308   mp_install(mp, yy_part_loc(q),x_part_loc(r));
20309   mp_install(mp, yx_part_loc(q),y_part_loc(r));
20310   if ( type(y_part_loc(r))==mp_known ) negate(value(y_part_loc(r)));
20311   else mp_negate_dep_list(mp, dep_list(y_part_loc(r)));
20312   mp_install(mp, xy_part_loc(q),y_part_loc(r));
20313   goto DONE;
20314 }
20315
20316 @ Procedure |set_up_known_trans| is like |set_up_trans|, but it
20317 insists that the transformation be entirely known.
20318
20319 @<Declare binary action...@>=
20320 void mp_set_up_known_trans (MP mp,quarterword c) { 
20321   mp_set_up_trans(mp, c);
20322   if ( mp->cur_type!=mp_known ) {
20323     exp_err("Transform components aren't all known");
20324 @.Transform components...@>
20325     help3("I'm unable to apply a partially specified transformation")
20326       ("except to a fully known pair or transform.")
20327       ("Proceed, and I'll omit the transformation.");
20328     mp_put_get_flush_error(mp, 0);
20329     mp->txx=unity; mp->txy=0; mp->tyx=0; mp->tyy=unity; 
20330     mp->tx=0; mp->ty=0;
20331   }
20332 }
20333
20334 @ Here's a procedure that applies the transform |txx..ty| to a pair of
20335 coordinates in locations |p| and~|q|.
20336
20337 @<Declare binary action...@>= 
20338 void mp_trans (MP mp,pointer p, pointer q) {
20339   scaled v; /* the new |x| value */
20340   v=mp_take_scaled(mp, mp->mem[p].sc,mp->txx)+
20341   mp_take_scaled(mp, mp->mem[q].sc,mp->txy)+mp->tx;
20342   mp->mem[q].sc=mp_take_scaled(mp, mp->mem[p].sc,mp->tyx)+
20343   mp_take_scaled(mp, mp->mem[q].sc,mp->tyy)+mp->ty;
20344   mp->mem[p].sc=v;
20345 }
20346
20347 @ The simplest transformation procedure applies a transform to all
20348 coordinates of a path.  The |path_trans(c)(p)| macro applies
20349 a transformation defined by |cur_exp| and the transform operator |c|
20350 to the path~|p|.
20351
20352 @d path_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20353                      mp_unstash_cur_exp(mp, (B)); 
20354                      mp_do_path_trans(mp, mp->cur_exp); }
20355
20356 @<Declare binary action...@>=
20357 void mp_do_path_trans (MP mp,pointer p) {
20358   pointer q; /* list traverser */
20359   q=p;
20360   do { 
20361     if ( left_type(q)!=endpoint ) 
20362       mp_trans(mp, q+3,q+4); /* that's |left_x| and |left_y| */
20363     mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20364     if ( right_type(q)!=endpoint ) 
20365       mp_trans(mp, q+5,q+6); /* that's |right_x| and |right_y| */
20366 @^data structure assumptions@>
20367     q=link(q);
20368   } while (q!=p);
20369 }
20370
20371 @ Transforming a pen is very similar, except that there are no |left_type|
20372 and |right_type| fields.
20373
20374 @d pen_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20375                     mp_unstash_cur_exp(mp, (B)); 
20376                     mp_do_pen_trans(mp, mp->cur_exp); }
20377
20378 @<Declare binary action...@>=
20379 void mp_do_pen_trans (MP mp,pointer p) {
20380   pointer q; /* list traverser */
20381   if ( pen_is_elliptical(p) ) {
20382     mp_trans(mp, p+3,p+4); /* that's |left_x| and |left_y| */
20383     mp_trans(mp, p+5,p+6); /* that's |right_x| and |right_y| */
20384   };
20385   q=p;
20386   do { 
20387     mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20388 @^data structure assumptions@>
20389     q=link(q);
20390   } while (q!=p);
20391 }
20392
20393 @ The next transformation procedure applies to edge structures. It will do
20394 any transformation, but the results may be substandard if the picture contains
20395 text that uses downloaded bitmap fonts.  The binary action procedure is
20396 |do_edges_trans|, but we also need a function that just scales a picture.
20397 That routine is |scale_edges|.  Both it and the underlying routine |edges_trans|
20398 should be thought of as procedures that update an edge structure |h|, except
20399 that they have to return a (possibly new) structure because of the need to call
20400 |private_edges|.
20401
20402 @<Declare binary action...@>=
20403 pointer mp_edges_trans (MP mp, pointer h) {
20404   pointer q; /* the object being transformed */
20405   pointer r,s; /* for list manipulation */
20406   scaled sx,sy; /* saved transformation parameters */
20407   scaled sqdet; /* square root of determinant for |dash_scale| */
20408   integer sgndet; /* sign of the determinant */
20409   scaled v; /* a temporary value */
20410   h=mp_private_edges(mp, h);
20411   sqdet=mp_sqrt_det(mp, mp->txx,mp->txy,mp->tyx,mp->tyy);
20412   sgndet=mp_ab_vs_cd(mp, mp->txx,mp->tyy,mp->txy,mp->tyx);
20413   if ( dash_list(h)!=null_dash ) {
20414     @<Try to transform the dash list of |h|@>;
20415   }
20416   @<Make the bounding box of |h| unknown if it can't be updated properly
20417     without scanning the whole structure@>;  
20418   q=link(dummy_loc(h));
20419   while ( q!=null ) { 
20420     @<Transform graphical object |q|@>;
20421     q=link(q);
20422   }
20423   return h;
20424 }
20425 void mp_do_edges_trans (MP mp,pointer p, quarterword c) { 
20426   mp_set_up_known_trans(mp, c);
20427   value(p)=mp_edges_trans(mp, value(p));
20428   mp_unstash_cur_exp(mp, p);
20429 }
20430 void mp_scale_edges (MP mp) { 
20431   mp->txx=mp->se_sf; mp->tyy=mp->se_sf;
20432   mp->txy=0; mp->tyx=0; mp->tx=0; mp->ty=0;
20433   mp->se_pic=mp_edges_trans(mp, mp->se_pic);
20434 }
20435
20436 @ @<Try to transform the dash list of |h|@>=
20437 if ( (mp->txy!=0)||(mp->tyx!=0)||
20438      (mp->ty!=0)||(abs(mp->txx)!=abs(mp->tyy))) {
20439   mp_flush_dash_list(mp, h);
20440 } else { 
20441   if ( mp->txx<0 ) { @<Reverse the dash list of |h|@>; } 
20442   @<Scale the dash list by |txx| and shift it by |tx|@>;
20443   dash_y(h)=mp_take_scaled(mp, dash_y(h),abs(mp->tyy));
20444 }
20445
20446 @ @<Reverse the dash list of |h|@>=
20447
20448   r=dash_list(h);
20449   dash_list(h)=null_dash;
20450   while ( r!=null_dash ) {
20451     s=r; r=link(r);
20452     v=start_x(s); start_x(s)=stop_x(s); stop_x(s)=v;
20453     link(s)=dash_list(h);
20454     dash_list(h)=s;
20455   }
20456 }
20457
20458 @ @<Scale the dash list by |txx| and shift it by |tx|@>=
20459 r=dash_list(h);
20460 while ( r!=null_dash ) {
20461   start_x(r)=mp_take_scaled(mp, start_x(r),mp->txx)+mp->tx;
20462   stop_x(r)=mp_take_scaled(mp, stop_x(r),mp->txx)+mp->tx;
20463   r=link(r);
20464 }
20465
20466 @ @<Make the bounding box of |h| unknown if it can't be updated properly...@>=
20467 if ( (mp->txx==0)&&(mp->tyy==0) ) {
20468   @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>;
20469 } else if ( (mp->txy!=0)||(mp->tyx!=0) ) {
20470   mp_init_bbox(mp, h);
20471   goto DONE1;
20472 }
20473 if ( minx_val(h)<=maxx_val(h) ) {
20474   @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift by
20475    |(tx,ty)|@>;
20476 }
20477 DONE1:
20478
20479
20480
20481 @ @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>=
20482
20483   v=minx_val(h); minx_val(h)=miny_val(h); miny_val(h)=v;
20484   v=maxx_val(h); maxx_val(h)=maxy_val(h); maxy_val(h)=v;
20485 }
20486
20487 @ The sum ``|txx+txy|'' is whichever of |txx| or |txy| is nonzero.  The other
20488 sum is similar.
20489
20490 @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift...@>=
20491
20492   minx_val(h)=mp_take_scaled(mp, minx_val(h),mp->txx+mp->txy)+mp->tx;
20493   maxx_val(h)=mp_take_scaled(mp, maxx_val(h),mp->txx+mp->txy)+mp->tx;
20494   miny_val(h)=mp_take_scaled(mp, miny_val(h),mp->tyx+mp->tyy)+mp->ty;
20495   maxy_val(h)=mp_take_scaled(mp, maxy_val(h),mp->tyx+mp->tyy)+mp->ty;
20496   if ( mp->txx+mp->txy<0 ) {
20497     v=minx_val(h); minx_val(h)=maxx_val(h); maxx_val(h)=v;
20498   }
20499   if ( mp->tyx+mp->tyy<0 ) {
20500     v=miny_val(h); miny_val(h)=maxy_val(h); maxy_val(h)=v;
20501   }
20502 }
20503
20504 @ Now we ready for the main task of transforming the graphical objects in edge
20505 structure~|h|.
20506
20507 @<Transform graphical object |q|@>=
20508 switch (type(q)) {
20509 case fill_code: case stroked_code: 
20510   mp_do_path_trans(mp, path_p(q));
20511   @<Transform |pen_p(q)|, making sure polygonal pens stay counter-clockwise@>;
20512   break;
20513 case mp_start_clip_code: case mp_start_bounds_code: 
20514   mp_do_path_trans(mp, path_p(q));
20515   break;
20516 case text_code: 
20517   r=text_tx_loc(q);
20518   @<Transform the compact transformation starting at |r|@>;
20519   break;
20520 case mp_stop_clip_code: case mp_stop_bounds_code: 
20521   break;
20522 } /* there are no other cases */
20523
20524 @ Note that the shift parameters |(tx,ty)| apply only to the path being stroked.
20525 The |dash_scale| has to be adjusted  to scale the dash lengths in |dash_p(q)|
20526 since the \ps\ output procedures will try to compensate for the transformation
20527 we are applying to |pen_p(q)|.  Since this compensation is based on the square
20528 root of the determinant, |sqdet| is the appropriate factor.
20529
20530 @<Transform |pen_p(q)|, making sure...@>=
20531 if ( pen_p(q)!=null ) {
20532   sx=mp->tx; sy=mp->ty;
20533   mp->tx=0; mp->ty=0;
20534   mp_do_pen_trans(mp, pen_p(q));
20535   if ( ((type(q)==stroked_code)&&(dash_p(q)!=null)) )
20536     dash_scale(q)=mp_take_scaled(mp, dash_scale(q),sqdet);
20537   if ( ! pen_is_elliptical(pen_p(q)) )
20538     if ( sgndet<0 )
20539       pen_p(q)=mp_make_pen(mp, mp_copy_path(mp, pen_p(q)),true); 
20540          /* this unreverses the pen */
20541   mp->tx=sx; mp->ty=sy;
20542 }
20543
20544 @ This uses the fact that transformations are stored in the order
20545 |(tx,ty,txx,txy,tyx,tyy)|.
20546 @^data structure assumptions@>
20547
20548 @<Transform the compact transformation starting at |r|@>=
20549 mp_trans(mp, r,r+1);
20550 sx=mp->tx; sy=mp->ty;
20551 mp->tx=0; mp->ty=0;
20552 mp_trans(mp, r+2,r+4);
20553 mp_trans(mp, r+3,r+5);
20554 mp->tx=sx; mp->ty=sy
20555
20556 @ The hard cases of transformation occur when big nodes are involved,
20557 and when some of their components are unknown.
20558
20559 @<Declare binary action...@>=
20560 @<Declare subroutines needed by |big_trans|@>;
20561 void mp_big_trans (MP mp,pointer p, quarterword c) {
20562   pointer q,r,pp,qq; /* list manipulation registers */
20563   small_number s; /* size of a big node */
20564   s=mp->big_node_size[type(p)]; q=value(p); r=q+s;
20565   do {  
20566     r=r-2;
20567     if ( type(r)!=mp_known ) {
20568       @<Transform an unknown big node and |return|@>;
20569     }
20570   } while (r!=q);
20571   @<Transform a known big node@>;
20572 }; /* node |p| will now be recycled by |do_binary| */
20573
20574 @ @<Transform an unknown big node and |return|@>=
20575
20576   mp_set_up_known_trans(mp, c); mp_make_exp_copy(mp, p); 
20577   r=value(mp->cur_exp);
20578   if ( mp->cur_type==mp_transform_type ) {
20579     mp_bilin1(mp, yy_part_loc(r),mp->tyy,xy_part_loc(q),mp->tyx,0);
20580     mp_bilin1(mp, yx_part_loc(r),mp->tyy,xx_part_loc(q),mp->tyx,0);
20581     mp_bilin1(mp, xy_part_loc(r),mp->txx,yy_part_loc(q),mp->txy,0);
20582     mp_bilin1(mp, xx_part_loc(r),mp->txx,yx_part_loc(q),mp->txy,0);
20583   }
20584   mp_bilin1(mp, y_part_loc(r),mp->tyy,x_part_loc(q),mp->tyx,mp->ty);
20585   mp_bilin1(mp, x_part_loc(r),mp->txx,y_part_loc(q),mp->txy,mp->tx);
20586   return;
20587 }
20588
20589 @ Let |p| point to a two-word value field inside a big node of |cur_exp|,
20590 and let |q| point to a another value field. The |bilin1| procedure
20591 replaces |p| by $p\cdot t+q\cdot u+\delta$.
20592
20593 @<Declare subroutines needed by |big_trans|@>=
20594 void mp_bilin1 (MP mp, pointer p, scaled t, pointer q, 
20595                 scaled u, scaled delta) {
20596   pointer r; /* list traverser */
20597   if ( t!=unity ) mp_dep_mult(mp, p,t,true);
20598   if ( u!=0 ) {
20599     if ( type(q)==mp_known ) {
20600       delta+=mp_take_scaled(mp, value(q),u);
20601     } else { 
20602       @<Ensure that |type(p)=mp_proto_dependent|@>;
20603       dep_list(p)=mp_p_plus_fq(mp, dep_list(p),u,dep_list(q),
20604                                mp_proto_dependent,type(q));
20605     }
20606   }
20607   if ( type(p)==mp_known ) {
20608     value(p)+=delta;
20609   } else {
20610     r=dep_list(p);
20611     while ( info(r)!=null ) r=link(r);
20612     delta+=value(r);
20613     if ( r!=dep_list(p) ) value(r)=delta;
20614     else { mp_recycle_value(mp, p); type(p)=mp_known; value(p)=delta; };
20615   }
20616   if ( mp->fix_needed ) mp_fix_dependencies(mp);
20617 }
20618
20619 @ @<Ensure that |type(p)=mp_proto_dependent|@>=
20620 if ( type(p)!=mp_proto_dependent ) {
20621   if ( type(p)==mp_known ) 
20622     mp_new_dep(mp, p,mp_const_dependency(mp, value(p)));
20623   else 
20624     dep_list(p)=mp_p_times_v(mp, dep_list(p),unity,mp_dependent,
20625                              mp_proto_dependent,true);
20626   type(p)=mp_proto_dependent;
20627 }
20628
20629 @ @<Transform a known big node@>=
20630 mp_set_up_trans(mp, c);
20631 if ( mp->cur_type==mp_known ) {
20632   @<Transform known by known@>;
20633 } else { 
20634   pp=mp_stash_cur_exp(mp); qq=value(pp);
20635   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20636   if ( mp->cur_type==mp_transform_type ) {
20637     mp_bilin2(mp, yy_part_loc(r),yy_part_loc(qq),
20638       value(xy_part_loc(q)),yx_part_loc(qq),null);
20639     mp_bilin2(mp, yx_part_loc(r),yy_part_loc(qq),
20640       value(xx_part_loc(q)),yx_part_loc(qq),null);
20641     mp_bilin2(mp, xy_part_loc(r),xx_part_loc(qq),
20642       value(yy_part_loc(q)),xy_part_loc(qq),null);
20643     mp_bilin2(mp, xx_part_loc(r),xx_part_loc(qq),
20644       value(yx_part_loc(q)),xy_part_loc(qq),null);
20645   };
20646   mp_bilin2(mp, y_part_loc(r),yy_part_loc(qq),
20647     value(x_part_loc(q)),yx_part_loc(qq),y_part_loc(qq));
20648   mp_bilin2(mp, x_part_loc(r),xx_part_loc(qq),
20649     value(y_part_loc(q)),xy_part_loc(qq),x_part_loc(qq));
20650   mp_recycle_value(mp, pp); mp_free_node(mp, pp,value_node_size);
20651 }
20652
20653 @ Let |p| be a |mp_proto_dependent| value whose dependency list ends
20654 at |dep_final|. The following procedure adds |v| times another
20655 numeric quantity to~|p|.
20656
20657 @<Declare subroutines needed by |big_trans|@>=
20658 void mp_add_mult_dep (MP mp,pointer p, scaled v, pointer r) { 
20659   if ( type(r)==mp_known ) {
20660     value(mp->dep_final)+=mp_take_scaled(mp, value(r),v);
20661   } else  { 
20662     dep_list(p)=mp_p_plus_fq(mp, dep_list(p),v,dep_list(r),
20663                                                          mp_proto_dependent,type(r));
20664     if ( mp->fix_needed ) mp_fix_dependencies(mp);
20665   }
20666 }
20667
20668 @ The |bilin2| procedure is something like |bilin1|, but with known
20669 and unknown quantities reversed. Parameter |p| points to a value field
20670 within the big node for |cur_exp|; and |type(p)=mp_known|. Parameters
20671 |t| and~|u| point to value fields elsewhere; so does parameter~|q|,
20672 unless it is |null| (which stands for zero). Location~|p| will be
20673 replaced by $p\cdot t+v\cdot u+q$.
20674
20675 @<Declare subroutines needed by |big_trans|@>=
20676 void mp_bilin2 (MP mp,pointer p, pointer t, scaled v, 
20677                 pointer u, pointer q) {
20678   scaled vv; /* temporary storage for |value(p)| */
20679   vv=value(p); type(p)=mp_proto_dependent;
20680   mp_new_dep(mp, p,mp_const_dependency(mp, 0)); /* this sets |dep_final| */
20681   if ( vv!=0 ) 
20682     mp_add_mult_dep(mp, p,vv,t); /* |dep_final| doesn't change */
20683   if ( v!=0 ) mp_add_mult_dep(mp, p,v,u);
20684   if ( q!=null ) mp_add_mult_dep(mp, p,unity,q);
20685   if ( dep_list(p)==mp->dep_final ) {
20686     vv=value(mp->dep_final); mp_recycle_value(mp, p);
20687     type(p)=mp_known; value(p)=vv;
20688   }
20689 }
20690
20691 @ @<Transform known by known@>=
20692
20693   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20694   if ( mp->cur_type==mp_transform_type ) {
20695     mp_bilin3(mp, yy_part_loc(r),mp->tyy,value(xy_part_loc(q)),mp->tyx,0);
20696     mp_bilin3(mp, yx_part_loc(r),mp->tyy,value(xx_part_loc(q)),mp->tyx,0);
20697     mp_bilin3(mp, xy_part_loc(r),mp->txx,value(yy_part_loc(q)),mp->txy,0);
20698     mp_bilin3(mp, xx_part_loc(r),mp->txx,value(yx_part_loc(q)),mp->txy,0);
20699   }
20700   mp_bilin3(mp, y_part_loc(r),mp->tyy,value(x_part_loc(q)),mp->tyx,mp->ty);
20701   mp_bilin3(mp, x_part_loc(r),mp->txx,value(y_part_loc(q)),mp->txy,mp->tx);
20702 }
20703
20704 @ Finally, in |bilin3| everything is |known|.
20705
20706 @<Declare subroutines needed by |big_trans|@>=
20707 void mp_bilin3 (MP mp,pointer p, scaled t, 
20708                scaled v, scaled u, scaled delta) { 
20709   if ( t!=unity )
20710     delta+=mp_take_scaled(mp, value(p),t);
20711   else 
20712     delta+=value(p);
20713   if ( u!=0 ) value(p)=delta+mp_take_scaled(mp, v,u);
20714   else value(p)=delta;
20715 }
20716
20717 @ @<Additional cases of binary operators@>=
20718 case concatenate: 
20719   if ( (mp->cur_type==mp_string_type)&&(type(p)==mp_string_type) ) mp_cat(mp, p);
20720   else mp_bad_binary(mp, p,concatenate);
20721   break;
20722 case substring_of: 
20723   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_string_type) )
20724     mp_chop_string(mp, value(p));
20725   else mp_bad_binary(mp, p,substring_of);
20726   break;
20727 case subpath_of: 
20728   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
20729   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_path_type) )
20730     mp_chop_path(mp, value(p));
20731   else mp_bad_binary(mp, p,subpath_of);
20732   break;
20733
20734 @ @<Declare binary action...@>=
20735 void mp_cat (MP mp,pointer p) {
20736   str_number a,b; /* the strings being concatenated */
20737   pool_pointer k; /* index into |str_pool| */
20738   a=value(p); b=mp->cur_exp; str_room(length(a)+length(b));
20739   for (k=mp->str_start[a];k<=str_stop(a)-1;k++) {
20740     append_char(mp->str_pool[k]);
20741   }
20742   for (k=mp->str_start[b];k<=str_stop(b)-1;k++) {
20743     append_char(mp->str_pool[k]);
20744   }
20745   mp->cur_exp=mp_make_string(mp); delete_str_ref(b);
20746 }
20747
20748 @ @<Declare binary action...@>=
20749 void mp_chop_string (MP mp,pointer p) {
20750   integer a, b; /* start and stop points */
20751   integer l; /* length of the original string */
20752   integer k; /* runs from |a| to |b| */
20753   str_number s; /* the original string */
20754   boolean reversed; /* was |a>b|? */
20755   a=mp_round_unscaled(mp, value(x_part_loc(p)));
20756   b=mp_round_unscaled(mp, value(y_part_loc(p)));
20757   if ( a<=b ) reversed=false;
20758   else  { reversed=true; k=a; a=b; b=k; };
20759   s=mp->cur_exp; l=length(s);
20760   if ( a<0 ) { 
20761     a=0;
20762     if ( b<0 ) b=0;
20763   }
20764   if ( b>l ) { 
20765     b=l;
20766     if ( a>l ) a=l;
20767   }
20768   str_room(b-a);
20769   if ( reversed ) {
20770     for (k=mp->str_start[s]+b-1;k>=mp->str_start[s]+a;k--)  {
20771       append_char(mp->str_pool[k]);
20772     }
20773   } else  {
20774     for (k=mp->str_start[s]+a;k<=mp->str_start[s]+b-1;k++)  {
20775       append_char(mp->str_pool[k]);
20776     }
20777   }
20778   mp->cur_exp=mp_make_string(mp); delete_str_ref(s);
20779 }
20780
20781 @ @<Declare binary action...@>=
20782 void mp_chop_path (MP mp,pointer p) {
20783   pointer q; /* a knot in the original path */
20784   pointer pp,qq,rr,ss; /* link variables for copies of path nodes */
20785   scaled a,b,k,l; /* indices for chopping */
20786   boolean reversed; /* was |a>b|? */
20787   l=mp_path_length(mp); a=value(x_part_loc(p)); b=value(y_part_loc(p));
20788   if ( a<=b ) reversed=false;
20789   else  { reversed=true; k=a; a=b; b=k; };
20790   @<Dispense with the cases |a<0| and/or |b>l|@>;
20791   q=mp->cur_exp;
20792   while ( a>=unity ) {
20793     q=link(q); a=a-unity; b=b-unity;
20794   }
20795   if ( b==a ) {
20796     @<Construct a path from |pp| to |qq| of length zero@>; 
20797   } else { 
20798     @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>; 
20799   }
20800   left_type(pp)=endpoint; right_type(qq)=endpoint; link(qq)=pp;
20801   mp_toss_knot_list(mp, mp->cur_exp);
20802   if ( reversed ) {
20803     mp->cur_exp=link(mp_htap_ypoc(mp, pp)); mp_toss_knot_list(mp, pp);
20804   } else {
20805     mp->cur_exp=pp;
20806   }
20807 }
20808
20809 @ @<Dispense with the cases |a<0| and/or |b>l|@>=
20810 if ( a<0 ) {
20811   if ( left_type(mp->cur_exp)==endpoint ) {
20812     a=0; if ( b<0 ) b=0;
20813   } else  {
20814     do {  a=a+l; b=b+l; } while (a<0); /* a cycle always has length |l>0| */
20815   }
20816 }
20817 if ( b>l ) {
20818   if ( left_type(mp->cur_exp)==endpoint ) {
20819     b=l; if ( a>l ) a=l;
20820   } else {
20821     while ( a>=l ) { 
20822       a=a-l; b=b-l;
20823     }
20824   }
20825 }
20826
20827 @ @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>=
20828
20829   pp=mp_copy_knot(mp, q); qq=pp;
20830   do {  
20831     q=link(q); rr=qq; qq=mp_copy_knot(mp, q); link(rr)=qq; b=b-unity;
20832   } while (b>0);
20833   if ( a>0 ) {
20834     ss=pp; pp=link(pp);
20835     mp_split_cubic(mp, ss,a*010000); pp=link(ss);
20836     mp_free_node(mp, ss,knot_node_size);
20837     if ( rr==ss ) {
20838       b=mp_make_scaled(mp, b,unity-a); rr=pp;
20839     }
20840   }
20841   if ( b<0 ) {
20842     mp_split_cubic(mp, rr,(b+unity)*010000);
20843     mp_free_node(mp, qq,knot_node_size);
20844     qq=link(rr);
20845   }
20846 }
20847
20848 @ @<Construct a path from |pp| to |qq| of length zero@>=
20849
20850   if ( a>0 ) { mp_split_cubic(mp, q,a*010000); q=link(q); };
20851   pp=mp_copy_knot(mp, q); qq=pp;
20852 }
20853
20854 @ @<Additional cases of binary operators@>=
20855 case point_of: case precontrol_of: case postcontrol_of: 
20856   if ( mp->cur_type==mp_pair_type )
20857      mp_pair_to_path(mp);
20858   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
20859     mp_find_point(mp, value(p),c);
20860   else 
20861     mp_bad_binary(mp, p,c);
20862   break;
20863 case pen_offset_of: 
20864   if ( (mp->cur_type==mp_pen_type)&& mp_nice_pair(mp, p,type(p)) )
20865     mp_set_up_offset(mp, value(p));
20866   else 
20867     mp_bad_binary(mp, p,pen_offset_of);
20868   break;
20869 case direction_time_of: 
20870   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
20871   if ( (mp->cur_type==mp_path_type)&& mp_nice_pair(mp, p,type(p)) )
20872     mp_set_up_direction_time(mp, value(p));
20873   else 
20874     mp_bad_binary(mp, p,direction_time_of);
20875   break;
20876
20877 @ @<Declare binary action...@>=
20878 void mp_set_up_offset (MP mp,pointer p) { 
20879   mp_find_offset(mp, value(x_part_loc(p)),value(y_part_loc(p)),mp->cur_exp);
20880   mp_pair_value(mp, mp->cur_x,mp->cur_y);
20881 }
20882 void mp_set_up_direction_time (MP mp,pointer p) { 
20883   mp_flush_cur_exp(mp, mp_find_direction_time(mp, value(x_part_loc(p)),
20884   value(y_part_loc(p)),mp->cur_exp));
20885 }
20886
20887 @ @<Declare binary action...@>=
20888 void mp_find_point (MP mp,scaled v, quarterword c) {
20889   pointer p; /* the path */
20890   scaled n; /* its length */
20891   p=mp->cur_exp;
20892   if ( left_type(p)==endpoint ) n=-unity; else n=0;
20893   do {  p=link(p); n=n+unity; } while (p!=mp->cur_exp);
20894   if ( n==0 ) { 
20895     v=0; 
20896   } else if ( v<0 ) {
20897     if ( left_type(p)==endpoint ) v=0;
20898     else v=n-1-((-v-1) % n);
20899   } else if ( v>n ) {
20900     if ( left_type(p)==endpoint ) v=n;
20901     else v=v % n;
20902   }
20903   p=mp->cur_exp;
20904   while ( v>=unity ) { p=link(p); v=v-unity;  };
20905   if ( v!=0 ) {
20906      @<Insert a fractional node by splitting the cubic@>;
20907   }
20908   @<Set the current expression to the desired path coordinates@>;
20909 }
20910
20911 @ @<Insert a fractional node...@>=
20912 { mp_split_cubic(mp, p,v*010000); p=link(p); }
20913
20914 @ @<Set the current expression to the desired path coordinates...@>=
20915 switch (c) {
20916 case point_of: 
20917   mp_pair_value(mp, x_coord(p),y_coord(p));
20918   break;
20919 case precontrol_of: 
20920   if ( left_type(p)==endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
20921   else mp_pair_value(mp, left_x(p),left_y(p));
20922   break;
20923 case postcontrol_of: 
20924   if ( right_type(p)==endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
20925   else mp_pair_value(mp, right_x(p),right_y(p));
20926   break;
20927 } /* there are no other cases */
20928
20929 @ @<Additional cases of binary operators@>=
20930 case arc_time_of: 
20931   if ( mp->cur_type==mp_pair_type )
20932      mp_pair_to_path(mp);
20933   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
20934     mp_flush_cur_exp(mp, mp_get_arc_time(mp, mp->cur_exp,value(p)));
20935   else 
20936     mp_bad_binary(mp, p,c);
20937   break;
20938
20939 @ @<Additional cases of bin...@>=
20940 case intersect: 
20941   if ( type(p)==mp_pair_type ) {
20942     q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p);
20943     mp_pair_to_path(mp); p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
20944   };
20945   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
20946   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_path_type) ) {
20947     mp_path_intersection(mp, value(p),mp->cur_exp);
20948     mp_pair_value(mp, mp->cur_t,mp->cur_tt);
20949   } else {
20950     mp_bad_binary(mp, p,intersect);
20951   }
20952   break;
20953
20954 @ @<Additional cases of bin...@>=
20955 case in_font:
20956   if ( (mp->cur_type!=mp_string_type)||(type(p)!=mp_string_type)) 
20957     mp_bad_binary(mp, p,in_font);
20958   else { mp_do_infont(mp, p); return; }
20959   break;
20960
20961 @ Function |new_text_node| owns the reference count for its second argument
20962 (the text string) but not its first (the font name).
20963
20964 @<Declare binary action...@>=
20965 void mp_do_infont (MP mp,pointer p) {
20966   pointer q;
20967   q=mp_get_node(mp, edge_header_size);
20968   mp_init_edges(mp, q);
20969   link(obj_tail(q))=mp_new_text_node(mp, str(mp->cur_exp),value(p));
20970   obj_tail(q)=link(obj_tail(q));
20971   mp_free_node(mp, p,value_node_size);
20972   mp_flush_cur_exp(mp, q);
20973   mp->cur_type=mp_picture_type;
20974 }
20975
20976 @* \[40] Statements and commands.
20977 The chief executive of \MP\ is the |do_statement| routine, which
20978 contains the master switch that causes all the various pieces of \MP\
20979 to do their things, in the right order.
20980
20981 In a sense, this is the grand climax of the program: It applies all the
20982 tools that we have worked so hard to construct. In another sense, this is
20983 the messiest part of the program: It necessarily refers to other pieces
20984 of code all over the place, so that a person can't fully understand what is
20985 going on without paging back and forth to be reminded of conventions that
20986 are defined elsewhere. We are now at the hub of the web.
20987
20988 The structure of |do_statement| itself is quite simple.  The first token
20989 of the statement is fetched using |get_x_next|.  If it can be the first
20990 token of an expression, we look for an equation, an assignment, or a
20991 title. Otherwise we use a \&{case} construction to branch at high speed to
20992 the appropriate routine for various and sundry other types of commands,
20993 each of which has an ``action procedure'' that does the necessary work.
20994
20995 The program uses the fact that
20996 $$\hbox{|min_primary_command=max_statement_command=type_name|}$$
20997 to interpret a statement that starts with, e.g., `\&{string}',
20998 as a type declaration rather than a boolean expression.
20999
21000 @c void mp_do_statement (MP mp) { /* governs \MP's activities */
21001   mp->cur_type=mp_vacuous; mp_get_x_next(mp);
21002   if ( mp->cur_cmd>max_primary_command ) {
21003     @<Worry about bad statement@>;
21004   } else if ( mp->cur_cmd>max_statement_command ) {
21005     @<Do an equation, assignment, title, or
21006      `$\langle\,$expression$\,\rangle\,$\&{endgroup}'@>;
21007   } else {
21008     @<Do a statement that doesn't begin with an expression@>;
21009   }
21010   if ( mp->cur_cmd<semicolon )
21011     @<Flush unparsable junk that was found after the statement@>;
21012   mp->error_count=0;
21013 }
21014
21015 @ @<Declarations@>=
21016 @<Declare action procedures for use by |do_statement|@>;
21017
21018 @ The only command codes |>max_primary_command| that can be present
21019 at the beginning of a statement are |semicolon| and higher; these
21020 occur when the statement is null.
21021
21022 @<Worry about bad statement@>=
21023
21024   if ( mp->cur_cmd<semicolon ) {
21025     print_err("A statement can't begin with `");
21026 @.A statement can't begin with x@>
21027     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); mp_print_char(mp, '\'');
21028     help5("I was looking for the beginning of a new statement.")
21029       ("If you just proceed without changing anything, I'll ignore")
21030       ("everything up to the next `;'. Please insert a semicolon")
21031       ("now in front of anything that you don't want me to delete.")
21032       ("(See Chapter 27 of The METAFONTbook for an example.)");
21033 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21034     mp_back_error(mp); mp_get_x_next(mp);
21035   }
21036 }
21037
21038 @ The help message printed here says that everything is flushed up to
21039 a semicolon, but actually the commands |end_group| and |stop| will
21040 also terminate a statement.
21041
21042 @<Flush unparsable junk that was found after the statement@>=
21043
21044   print_err("Extra tokens will be flushed");
21045 @.Extra tokens will be flushed@>
21046   help6("I've just read as much of that statement as I could fathom,")
21047        ("so a semicolon should have been next. It's very puzzling...")
21048        ("but I'll try to get myself back together, by ignoring")
21049        ("everything up to the next `;'. Please insert a semicolon")
21050        ("now in front of anything that you don't want me to delete.")
21051        ("(See Chapter 27 of The METAFONTbook for an example.)");
21052 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21053   mp_back_error(mp); mp->scanner_status=flushing;
21054   do {  
21055     get_t_next;
21056     @<Decrease the string reference count...@>;
21057   } while (! end_of_statement); /* |cur_cmd=semicolon|, |end_group|, or |stop| */
21058   mp->scanner_status=normal;
21059 }
21060
21061 @ If |do_statement| ends with |cur_cmd=end_group|, we should have
21062 |cur_type=mp_vacuous| unless the statement was simply an expression;
21063 in the latter case, |cur_type| and |cur_exp| should represent that
21064 expression.
21065
21066 @<Do a statement that doesn't...@>=
21067
21068   if ( mp->internal[tracing_commands]>0 ) 
21069     show_cur_cmd_mod;
21070   switch (mp->cur_cmd ) {
21071   case type_name:mp_do_type_declaration(mp); break;
21072   case macro_def:
21073     if ( mp->cur_mod>var_def ) mp_make_op_def(mp);
21074     else if ( mp->cur_mod>end_def ) mp_scan_def(mp);
21075      break;
21076   @<Cases of |do_statement| that invoke particular commands@>;
21077   } /* there are no other cases */
21078   mp->cur_type=mp_vacuous;
21079 }
21080
21081 @ The most important statements begin with expressions.
21082
21083 @<Do an equation, assignment, title, or...@>=
21084
21085   mp->var_flag=assignment; mp_scan_expression(mp);
21086   if ( mp->cur_cmd<end_group ) {
21087     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21088     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21089     else if ( mp->cur_type==mp_string_type ) {@<Do a title@> ; }
21090     else if ( mp->cur_type!=mp_vacuous ){ 
21091       exp_err("Isolated expression");
21092 @.Isolated expression@>
21093       help3("I couldn't find an `=' or `:=' after the")
21094         ("expression that is shown above this error message,")
21095         ("so I guess I'll just ignore it and carry on.");
21096       mp_put_get_error(mp);
21097     }
21098     mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous;
21099   }
21100 }
21101
21102 @ @<Do a title@>=
21103
21104   if ( mp->internal[tracing_titles]>0 ) {
21105     mp_print_nl(mp, "");  mp_print_str(mp, mp->cur_exp); update_terminal;
21106   }
21107 }
21108
21109 @ Equations and assignments are performed by the pair of mutually recursive
21110 @^recursion@>
21111 routines |do_equation| and |do_assignment|. These routines are called when
21112 |cur_cmd=equals| and when |cur_cmd=assignment|, respectively; the left-hand
21113 side is in |cur_type| and |cur_exp|, while the right-hand side is yet
21114 to be scanned. After the routines are finished, |cur_type| and |cur_exp|
21115 will be equal to the right-hand side (which will normally be equal
21116 to the left-hand side).
21117
21118 @<Declare action procedures for use by |do_statement|@>=
21119 @<Declare the procedure called |try_eq|@>;
21120 @<Declare the procedure called |make_eq|@>;
21121 void mp_do_equation (MP mp) ;
21122
21123 @ @c
21124 void mp_do_equation (MP mp) {
21125   pointer lhs; /* capsule for the left-hand side */
21126   pointer p; /* temporary register */
21127   lhs=mp_stash_cur_exp(mp); mp_get_x_next(mp); 
21128   mp->var_flag=assignment; mp_scan_expression(mp);
21129   if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21130   else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21131   if ( mp->internal[tracing_commands]>two ) 
21132     @<Trace the current equation@>;
21133   if ( mp->cur_type==mp_unknown_path ) if ( type(lhs)==mp_pair_type ) {
21134     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, lhs); lhs=p;
21135   }; /* in this case |make_eq| will change the pair to a path */
21136   mp_make_eq(mp, lhs); /* equate |lhs| to |(cur_type,cur_exp)| */
21137 }
21138
21139 @ And |do_assignment| is similar to |do_expression|:
21140
21141 @<Declarations@>=
21142 void mp_do_assignment (MP mp);
21143
21144 @ @<Declare action procedures for use by |do_statement|@>=
21145 void mp_do_assignment (MP mp) ;
21146
21147 @ @c
21148 void mp_do_assignment (MP mp) {
21149   pointer lhs; /* token list for the left-hand side */
21150   pointer p; /* where the left-hand value is stored */
21151   pointer q; /* temporary capsule for the right-hand value */
21152   if ( mp->cur_type!=mp_token_list ) { 
21153     exp_err("Improper `:=' will be changed to `='");
21154 @.Improper `:='@>
21155     help2("I didn't find a variable name at the left of the `:=',")
21156       ("so I'm going to pretend that you said `=' instead.");
21157     mp_error(mp); mp_do_equation(mp);
21158   } else { 
21159     lhs=mp->cur_exp; mp->cur_type=mp_vacuous;
21160     mp_get_x_next(mp); mp->var_flag=assignment; mp_scan_expression(mp);
21161     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21162     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21163     if ( mp->internal[tracing_commands]>two ) 
21164       @<Trace the current assignment@>;
21165     if ( info(lhs)>hash_end ) {
21166       @<Assign the current expression to an internal variable@>;
21167     } else  {
21168       @<Assign the current expression to the variable |lhs|@>;
21169     }
21170     mp_flush_node_list(mp, lhs);
21171   }
21172 }
21173
21174 @ @<Trace the current equation@>=
21175
21176   mp_begin_diagnostic(mp); mp_print_nl(mp, "{("); mp_print_exp(mp,lhs,0);
21177   mp_print(mp,")=("); mp_print_exp(mp,null,0); 
21178   mp_print(mp,")}"); mp_end_diagnostic(mp, false);
21179 }
21180
21181 @ @<Trace the current assignment@>=
21182
21183   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
21184   if ( info(lhs)>hash_end ) 
21185      mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21186   else 
21187      mp_show_token_list(mp, lhs,null,1000,0);
21188   mp_print(mp, ":="); mp_print_exp(mp, null,0); 
21189   mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
21190 }
21191
21192 @ @<Assign the current expression to an internal variable@>=
21193 if ( mp->cur_type==mp_known )  {
21194   mp->internal[info(lhs)-(hash_end)]=mp->cur_exp;
21195 } else { 
21196   exp_err("Internal quantity `");
21197 @.Internal quantity...@>
21198   mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21199   mp_print(mp, "' must receive a known value");
21200   help2("I can\'t set an internal quantity to anything but a known")
21201     ("numeric value, so I'll have to ignore this assignment.");
21202   mp_put_get_error(mp);
21203 }
21204
21205 @ @<Assign the current expression to the variable |lhs|@>=
21206
21207   p=mp_find_variable(mp, lhs);
21208   if ( p!=null ) {
21209     q=mp_stash_cur_exp(mp); mp->cur_type=mp_und_type(mp, p); 
21210     mp_recycle_value(mp, p);
21211     type(p)=mp->cur_type; value(p)=null; mp_make_exp_copy(mp, p);
21212     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q); mp_make_eq(mp, p);
21213   } else  { 
21214     mp_obliterated(mp, lhs); mp_put_get_error(mp);
21215   }
21216 }
21217
21218
21219 @ And now we get to the nitty-gritty. The |make_eq| procedure is given
21220 a pointer to a capsule that is to be equated to the current expression.
21221
21222 @<Declare the procedure called |make_eq|@>=
21223 void mp_make_eq (MP mp,pointer lhs) ;
21224
21225
21226
21227 @c void mp_make_eq (MP mp,pointer lhs) {
21228   small_number t; /* type of the left-hand side */
21229   pointer p,q; /* pointers inside of big nodes */
21230   integer v=0; /* value of the left-hand side */
21231 RESTART: 
21232   t=type(lhs);
21233   if ( t<=mp_pair_type ) v=value(lhs);
21234   switch (t) {
21235   @<For each type |t|, make an equation and |goto done| unless |cur_type|
21236     is incompatible with~|t|@>;
21237   } /* all cases have been listed */
21238   @<Announce that the equation cannot be performed@>;
21239 DONE:
21240   check_arith; mp_recycle_value(mp, lhs); 
21241   mp_free_node(mp, lhs,value_node_size);
21242 }
21243
21244 @ @<Announce that the equation cannot be performed@>=
21245 mp_disp_err(mp, lhs,""); 
21246 exp_err("Equation cannot be performed (");
21247 @.Equation cannot be performed@>
21248 if ( type(lhs)<=mp_pair_type ) mp_print_type(mp, type(lhs));
21249 else mp_print(mp, "numeric");
21250 mp_print_char(mp, '=');
21251 if ( mp->cur_type<=mp_pair_type ) mp_print_type(mp, mp->cur_type);
21252 else mp_print(mp, "numeric");
21253 mp_print_char(mp, ')');
21254 help2("I'm sorry, but I don't know how to make such things equal.")
21255      ("(See the two expressions just above the error message.)");
21256 mp_put_get_error(mp)
21257
21258 @ @<For each type |t|, make an equation and |goto done| unless...@>=
21259 case mp_boolean_type: case mp_string_type: case mp_pen_type:
21260 case mp_path_type: case mp_picture_type:
21261   if ( mp->cur_type==t+unknown_tag ) { 
21262     mp_nonlinear_eq(mp, v,mp->cur_exp,false); goto DONE;
21263   } else if ( mp->cur_type==t ) {
21264     @<Report redundant or inconsistent equation and |goto done|@>;
21265   }
21266   break;
21267 case unknown_types:
21268   if ( mp->cur_type==t-unknown_tag ) { 
21269     mp_nonlinear_eq(mp, mp->cur_exp,lhs,true); goto DONE;
21270   } else if ( mp->cur_type==t ) { 
21271     mp_ring_merge(mp, lhs,mp->cur_exp); goto DONE;
21272   } else if ( mp->cur_type==mp_pair_type ) {
21273     if ( t==mp_unknown_path ) { 
21274      mp_pair_to_path(mp); goto RESTART;
21275     };
21276   }
21277   break;
21278 case mp_transform_type: case mp_color_type:
21279 case mp_cmykcolor_type: case mp_pair_type:
21280   if ( mp->cur_type==t ) {
21281     @<Do multiple equations and |goto done|@>;
21282   }
21283   break;
21284 case mp_known: case mp_dependent:
21285 case mp_proto_dependent: case mp_independent:
21286   if ( mp->cur_type>=mp_known ) { 
21287     mp_try_eq(mp, lhs,null); goto DONE;
21288   };
21289   break;
21290 case mp_vacuous:
21291   break;
21292
21293 @ @<Report redundant or inconsistent equation and |goto done|@>=
21294
21295   if ( mp->cur_type<=mp_string_type ) {
21296     if ( mp->cur_type==mp_string_type ) {
21297       if ( mp_str_vs_str(mp, v,mp->cur_exp)!=0 ) {
21298         goto NOT_FOUND;
21299       }
21300     } else if ( v!=mp->cur_exp ) {
21301       goto NOT_FOUND;
21302     }
21303     @<Exclaim about a redundant equation@>; goto DONE;
21304   }
21305   print_err("Redundant or inconsistent equation");
21306 @.Redundant or inconsistent equation@>
21307   help2("An equation between already-known quantities can't help.")
21308        ("But don't worry; continue and I'll just ignore it.");
21309   mp_put_get_error(mp); goto DONE;
21310 NOT_FOUND: 
21311   print_err("Inconsistent equation");
21312 @.Inconsistent equation@>
21313   help2("The equation I just read contradicts what was said before.")
21314        ("But don't worry; continue and I'll just ignore it.");
21315   mp_put_get_error(mp); goto DONE;
21316 }
21317
21318 @ @<Do multiple equations and |goto done|@>=
21319
21320   p=v+mp->big_node_size[t]; 
21321   q=value(mp->cur_exp)+mp->big_node_size[t];
21322   do {  
21323     p=p-2; q=q-2; mp_try_eq(mp, p,q);
21324   } while (p!=v);
21325   goto DONE;
21326 }
21327
21328 @ The first argument to |try_eq| is the location of a value node
21329 in a capsule that will soon be recycled. The second argument is
21330 either a location within a pair or transform node pointed to by
21331 |cur_exp|, or it is |null| (which means that |cur_exp| itself
21332 serves as the second argument). The idea is to leave |cur_exp| unchanged,
21333 but to equate the two operands.
21334
21335 @<Declare the procedure called |try_eq|@>=
21336 void mp_try_eq (MP mp,pointer l, pointer r) ;
21337
21338
21339 @c void mp_try_eq (MP mp,pointer l, pointer r) {
21340   pointer p; /* dependency list for right operand minus left operand */
21341   int t; /* the type of list |p| */
21342   pointer q; /* the constant term of |p| is here */
21343   pointer pp; /* dependency list for right operand */
21344   int tt; /* the type of list |pp| */
21345   boolean copied; /* have we copied a list that ought to be recycled? */
21346   @<Remove the left operand from its container, negate it, and
21347     put it into dependency list~|p| with constant term~|q|@>;
21348   @<Add the right operand to list |p|@>;
21349   if ( info(p)==null ) {
21350     @<Deal with redundant or inconsistent equation@>;
21351   } else { 
21352     mp_linear_eq(mp, p,t);
21353     if ( r==null ) if ( mp->cur_type!=mp_known ) {
21354       if ( type(mp->cur_exp)==mp_known ) {
21355         pp=mp->cur_exp; mp->cur_exp=value(mp->cur_exp); mp->cur_type=mp_known;
21356         mp_free_node(mp, pp,value_node_size);
21357       }
21358     }
21359   }
21360 }
21361
21362 @ @<Remove the left operand from its container, negate it, and...@>=
21363 t=type(l);
21364 if ( t==mp_known ) { 
21365   t=mp_dependent; p=mp_const_dependency(mp, -value(l)); q=p;
21366 } else if ( t==mp_independent ) {
21367   t=mp_dependent; p=mp_single_dependency(mp, l); negate(value(p));
21368   q=mp->dep_final;
21369 } else { 
21370   p=dep_list(l); q=p;
21371   while (1) { 
21372     negate(value(q));
21373     if ( info(q)==null ) break;
21374     q=link(q);
21375   }
21376   link(prev_dep(l))=link(q); prev_dep(link(q))=prev_dep(l);
21377   type(l)=mp_known;
21378 }
21379
21380 @ @<Deal with redundant or inconsistent equation@>=
21381
21382   if ( abs(value(p))>64 ) { /* off by .001 or more */
21383     print_err("Inconsistent equation");
21384 @.Inconsistent equation@>
21385     mp_print(mp, " (off by "); mp_print_scaled(mp, value(p)); 
21386     mp_print_char(mp, ')');
21387     help2("The equation I just read contradicts what was said before.")
21388       ("But don't worry; continue and I'll just ignore it.");
21389     mp_put_get_error(mp);
21390   } else if ( r==null ) {
21391     @<Exclaim about a redundant equation@>;
21392   }
21393   mp_free_node(mp, p,dep_node_size);
21394 }
21395
21396 @ @<Add the right operand to list |p|@>=
21397 if ( r==null ) {
21398   if ( mp->cur_type==mp_known ) {
21399     value(q)=value(q)+mp->cur_exp; goto DONE1;
21400   } else { 
21401     tt=mp->cur_type;
21402     if ( tt==mp_independent ) pp=mp_single_dependency(mp, mp->cur_exp);
21403     else pp=dep_list(mp->cur_exp);
21404   } 
21405 } else {
21406   if ( type(r)==mp_known ) {
21407     value(q)=value(q)+value(r); goto DONE1;
21408   } else { 
21409     tt=type(r);
21410     if ( tt==mp_independent ) pp=mp_single_dependency(mp, r);
21411     else pp=dep_list(r);
21412   }
21413 }
21414 if ( tt!=mp_independent ) copied=false;
21415 else  { copied=true; tt=mp_dependent; };
21416 @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>;
21417 if ( copied ) mp_flush_node_list(mp, pp);
21418 DONE1:
21419
21420 @ @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>=
21421 mp->watch_coefs=false;
21422 if ( t==tt ) {
21423   p=mp_p_plus_q(mp, p,pp,t);
21424 } else if ( t==mp_proto_dependent ) {
21425   p=mp_p_plus_fq(mp, p,unity,pp,mp_proto_dependent,mp_dependent);
21426 } else { 
21427   q=p;
21428   while ( info(q)!=null ) {
21429     value(q)=mp_round_fraction(mp, value(q)); q=link(q);
21430   }
21431   t=mp_proto_dependent; p=mp_p_plus_q(mp, p,pp,t);
21432 }
21433 mp->watch_coefs=true;
21434
21435 @ Our next goal is to process type declarations. For this purpose it's
21436 convenient to have a procedure that scans a $\langle\,$declared
21437 variable$\,\rangle$ and returns the corresponding token list. After the
21438 following procedure has acted, the token after the declared variable
21439 will have been scanned, so it will appear in |cur_cmd|, |cur_mod|,
21440 and~|cur_sym|.
21441
21442 @<Declare the function called |scan_declared_variable|@>=
21443 pointer mp_scan_declared_variable (MP mp) {
21444   pointer x; /* hash address of the variable's root */
21445   pointer h,t; /* head and tail of the token list to be returned */
21446   pointer l; /* hash address of left bracket */
21447   mp_get_symbol(mp); x=mp->cur_sym;
21448   if ( mp->cur_cmd!=tag_token ) mp_clear_symbol(mp, x,false);
21449   h=mp_get_avail(mp); info(h)=x; t=h;
21450   while (1) { 
21451     mp_get_x_next(mp);
21452     if ( mp->cur_sym==0 ) break;
21453     if ( mp->cur_cmd!=tag_token ) if ( mp->cur_cmd!=internal_quantity)  {
21454       if ( mp->cur_cmd==left_bracket ) {
21455         @<Descend past a collective subscript@>;
21456       } else {
21457         break;
21458       }
21459     }
21460     link(t)=mp_get_avail(mp); t=link(t); info(t)=mp->cur_sym;
21461   }
21462   if ( eq_type(x)!=tag_token ) mp_clear_symbol(mp, x,false);
21463   if ( equiv(x)==null ) mp_new_root(mp, x);
21464   return h;
21465 }
21466
21467 @ If the subscript isn't collective, we don't accept it as part of the
21468 declared variable.
21469
21470 @<Descend past a collective subscript@>=
21471
21472   l=mp->cur_sym; mp_get_x_next(mp);
21473   if ( mp->cur_cmd!=right_bracket ) {
21474     mp_back_input(mp); mp->cur_sym=l; mp->cur_cmd=left_bracket; break;
21475   } else {
21476     mp->cur_sym=collective_subscript;
21477   }
21478 }
21479
21480 @ Type declarations are introduced by the following primitive operations.
21481
21482 @<Put each...@>=
21483 mp_primitive(mp, "numeric",type_name,mp_numeric_type);
21484 @:numeric_}{\&{numeric} primitive@>
21485 mp_primitive(mp, "string",type_name,mp_string_type);
21486 @:string_}{\&{string} primitive@>
21487 mp_primitive(mp, "boolean",type_name,mp_boolean_type);
21488 @:boolean_}{\&{boolean} primitive@>
21489 mp_primitive(mp, "path",type_name,mp_path_type);
21490 @:path_}{\&{path} primitive@>
21491 mp_primitive(mp, "pen",type_name,mp_pen_type);
21492 @:pen_}{\&{pen} primitive@>
21493 mp_primitive(mp, "picture",type_name,mp_picture_type);
21494 @:picture_}{\&{picture} primitive@>
21495 mp_primitive(mp, "transform",type_name,mp_transform_type);
21496 @:transform_}{\&{transform} primitive@>
21497 mp_primitive(mp, "color",type_name,mp_color_type);
21498 @:color_}{\&{color} primitive@>
21499 mp_primitive(mp, "rgbcolor",type_name,mp_color_type);
21500 @:color_}{\&{rgbcolor} primitive@>
21501 mp_primitive(mp, "cmykcolor",type_name,mp_cmykcolor_type);
21502 @:color_}{\&{cmykcolor} primitive@>
21503 mp_primitive(mp, "pair",type_name,mp_pair_type);
21504 @:pair_}{\&{pair} primitive@>
21505
21506 @ @<Cases of |print_cmd...@>=
21507 case type_name: mp_print_type(mp, m); break;
21508
21509 @ Now we are ready to handle type declarations, assuming that a
21510 |type_name| has just been scanned.
21511
21512 @<Declare action procedures for use by |do_statement|@>=
21513 void mp_do_type_declaration (MP mp) ;
21514
21515 @ @c
21516 void mp_do_type_declaration (MP mp) {
21517   small_number t; /* the type being declared */
21518   pointer p; /* token list for a declared variable */
21519   pointer q; /* value node for the variable */
21520   if ( mp->cur_mod>=mp_transform_type ) 
21521     t=mp->cur_mod;
21522   else 
21523     t=mp->cur_mod+unknown_tag;
21524   do {  
21525     p=mp_scan_declared_variable(mp);
21526     mp_flush_variable(mp, equiv(info(p)),link(p),false);
21527     q=mp_find_variable(mp, p);
21528     if ( q!=null ) { 
21529       type(q)=t; value(q)=null; 
21530     } else  { 
21531       print_err("Declared variable conflicts with previous vardef");
21532 @.Declared variable conflicts...@>
21533       help2("You can't use, e.g., `numeric foo[]' after `vardef foo'.")
21534            ("Proceed, and I'll ignore the illegal redeclaration.");
21535       mp_put_get_error(mp);
21536     }
21537     mp_flush_list(mp, p);
21538     if ( mp->cur_cmd<comma ) {
21539       @<Flush spurious symbols after the declared variable@>;
21540     }
21541   } while (! end_of_statement);
21542 }
21543
21544 @ @<Flush spurious symbols after the declared variable@>=
21545
21546   print_err("Illegal suffix of declared variable will be flushed");
21547 @.Illegal suffix...flushed@>
21548   help5("Variables in declarations must consist entirely of")
21549     ("names and collective subscripts, e.g., `x[]a'.")
21550     ("Are you trying to use a reserved word in a variable name?")
21551     ("I'm going to discard the junk I found here,")
21552     ("up to the next comma or the end of the declaration.");
21553   if ( mp->cur_cmd==numeric_token )
21554     mp->help_line[2]="Explicit subscripts like `x15a' aren't permitted.";
21555   mp_put_get_error(mp); mp->scanner_status=flushing;
21556   do {  
21557     get_t_next;
21558     @<Decrease the string reference count...@>;
21559   } while (mp->cur_cmd<comma); /* either |end_of_statement| or |cur_cmd=comma| */
21560   mp->scanner_status=normal;
21561 }
21562
21563 @ \MP's |main_control| procedure just calls |do_statement| repeatedly
21564 until coming to the end of the user's program.
21565 Each execution of |do_statement| concludes with
21566 |cur_cmd=semicolon|, |end_group|, or |stop|.
21567
21568 @c void mp_main_control (MP mp) { 
21569   do {  
21570     mp_do_statement(mp);
21571     if ( mp->cur_cmd==end_group ) {
21572       print_err("Extra `endgroup'");
21573 @.Extra `endgroup'@>
21574       help2("I'm not currently working on a `begingroup',")
21575         ("so I had better not try to end anything.");
21576       mp_flush_error(mp, 0);
21577     }
21578   } while (mp->cur_cmd!=stop);
21579 }
21580 void mp_run (MP mp) {
21581   mp_main_control(mp); /* come to life */
21582   mp_final_cleanup(mp); /* prepare for death */
21583   mp_close_files_and_terminate(mp);
21584 }
21585 char * mp_mplib_version (MP mp) {
21586   assert(mp);
21587   return mplib_version;
21588 }
21589 char * mp_metapost_version (MP mp) {
21590   assert(mp);
21591   return metapost_version;
21592 }
21593
21594 @ @<Exported function headers@>=
21595 void mp_run (MP mp);
21596 char * mp_mplib_version (MP mp);
21597 char * mp_metapost_version (MP mp);
21598
21599 @ @<Put each...@>=
21600 mp_primitive(mp, "end",stop,0);
21601 @:end_}{\&{end} primitive@>
21602 mp_primitive(mp, "dump",stop,1);
21603 @:dump_}{\&{dump} primitive@>
21604
21605 @ @<Cases of |print_cmd...@>=
21606 case stop:
21607   if ( m==0 ) mp_print(mp, "end");
21608   else mp_print(mp, "dump");
21609   break;
21610
21611 @* \[41] Commands.
21612 Let's turn now to statements that are classified as ``commands'' because
21613 of their imperative nature. We'll begin with simple ones, so that it
21614 will be clear how to hook command processing into the |do_statement| routine;
21615 then we'll tackle the tougher commands.
21616
21617 Here's one of the simplest:
21618
21619 @<Cases of |do_statement|...@>=
21620 case random_seed: mp_do_random_seed(mp);  break;
21621
21622 @ @<Declare action procedures for use by |do_statement|@>=
21623 void mp_do_random_seed (MP mp) ;
21624
21625 @ @c void mp_do_random_seed (MP mp) { 
21626   mp_get_x_next(mp);
21627   if ( mp->cur_cmd!=assignment ) {
21628     mp_missing_err(mp, ":=");
21629 @.Missing `:='@>
21630     help1("Always say `randomseed:=<numeric expression>'.");
21631     mp_back_error(mp);
21632   };
21633   mp_get_x_next(mp); mp_scan_expression(mp);
21634   if ( mp->cur_type!=mp_known ) {
21635     exp_err("Unknown value will be ignored");
21636 @.Unknown value...ignored@>
21637     help2("Your expression was too random for me to handle,")
21638       ("so I won't change the random seed just now.");
21639     mp_put_get_flush_error(mp, 0);
21640   } else {
21641    @<Initialize the random seed to |cur_exp|@>;
21642   }
21643 }
21644
21645 @ @<Initialize the random seed to |cur_exp|@>=
21646
21647   mp_init_randoms(mp, mp->cur_exp);
21648   if ( mp->selector>=log_only && mp->selector<write_file) {
21649     mp->old_setting=mp->selector; mp->selector=log_only;
21650     mp_print_nl(mp, "{randomseed:="); 
21651     mp_print_scaled(mp, mp->cur_exp); 
21652     mp_print_char(mp, '}');
21653     mp_print_nl(mp, ""); mp->selector=mp->old_setting;
21654   }
21655 }
21656
21657 @ And here's another simple one (somewhat different in flavor):
21658
21659 @<Cases of |do_statement|...@>=
21660 case mode_command: 
21661   mp_print_ln(mp); mp->interaction=mp->cur_mod;
21662   @<Initialize the print |selector| based on |interaction|@>;
21663   if ( mp->log_opened ) mp->selector=mp->selector+2;
21664   mp_get_x_next(mp);
21665   break;
21666
21667 @ @<Put each...@>=
21668 mp_primitive(mp, "batchmode",mode_command,mp_batch_mode);
21669 @:mp_batch_mode_}{\&{batchmode} primitive@>
21670 mp_primitive(mp, "nonstopmode",mode_command,mp_nonstop_mode);
21671 @:mp_nonstop_mode_}{\&{nonstopmode} primitive@>
21672 mp_primitive(mp, "scrollmode",mode_command,mp_scroll_mode);
21673 @:mp_scroll_mode_}{\&{scrollmode} primitive@>
21674 mp_primitive(mp, "errorstopmode",mode_command,mp_error_stop_mode);
21675 @:mp_error_stop_mode_}{\&{errorstopmode} primitive@>
21676
21677 @ @<Cases of |print_cmd_mod|...@>=
21678 case mode_command: 
21679   switch (m) {
21680   case mp_batch_mode: mp_print(mp, "batchmode"); break;
21681   case mp_nonstop_mode: mp_print(mp, "nonstopmode"); break;
21682   case mp_scroll_mode: mp_print(mp, "scrollmode"); break;
21683   default: mp_print(mp, "errorstopmode"); break;
21684   }
21685   break;
21686
21687 @ The `\&{inner}' and `\&{outer}' commands are only slightly harder.
21688
21689 @<Cases of |do_statement|...@>=
21690 case protection_command: mp_do_protection(mp); break;
21691
21692 @ @<Put each...@>=
21693 mp_primitive(mp, "inner",protection_command,0);
21694 @:inner_}{\&{inner} primitive@>
21695 mp_primitive(mp, "outer",protection_command,1);
21696 @:outer_}{\&{outer} primitive@>
21697
21698 @ @<Cases of |print_cmd...@>=
21699 case protection_command: 
21700   if ( m==0 ) mp_print(mp, "inner");
21701   else mp_print(mp, "outer");
21702   break;
21703
21704 @ @<Declare action procedures for use by |do_statement|@>=
21705 void mp_do_protection (MP mp) ;
21706
21707 @ @c void mp_do_protection (MP mp) {
21708   int m; /* 0 to unprotect, 1 to protect */
21709   halfword t; /* the |eq_type| before we change it */
21710   m=mp->cur_mod;
21711   do {  
21712     mp_get_symbol(mp); t=eq_type(mp->cur_sym);
21713     if ( m==0 ) { 
21714       if ( t>=outer_tag ) 
21715         eq_type(mp->cur_sym)=t-outer_tag;
21716     } else if ( t<outer_tag ) {
21717       eq_type(mp->cur_sym)=t+outer_tag;
21718     }
21719     mp_get_x_next(mp);
21720   } while (mp->cur_cmd==comma);
21721 }
21722
21723 @ \MP\ never defines the tokens `\.(' and `\.)' to be primitives, but
21724 plain \MP\ begins with the declaration `\&{delimiters} \.{()}'. Such a
21725 declaration assigns the command code |left_delimiter| to `\.{(}' and
21726 |right_delimiter| to `\.{)}'; the |equiv| of each delimiter is the
21727 hash address of its mate.
21728
21729 @<Cases of |do_statement|...@>=
21730 case delimiters: mp_def_delims(mp); break;
21731
21732 @ @<Declare action procedures for use by |do_statement|@>=
21733 void mp_def_delims (MP mp) ;
21734
21735 @ @c void mp_def_delims (MP mp) {
21736   pointer l_delim,r_delim; /* the new delimiter pair */
21737   mp_get_clear_symbol(mp); l_delim=mp->cur_sym;
21738   mp_get_clear_symbol(mp); r_delim=mp->cur_sym;
21739   eq_type(l_delim)=left_delimiter; equiv(l_delim)=r_delim;
21740   eq_type(r_delim)=right_delimiter; equiv(r_delim)=l_delim;
21741   mp_get_x_next(mp);
21742 }
21743
21744 @ Here is a procedure that is called when \MP\ has reached a point
21745 where some right delimiter is mandatory.
21746
21747 @<Declare the procedure called |check_delimiter|@>=
21748 void mp_check_delimiter (MP mp,pointer l_delim, pointer r_delim) {
21749   if ( mp->cur_cmd==right_delimiter ) 
21750     if ( mp->cur_mod==l_delim ) 
21751       return;
21752   if ( mp->cur_sym!=r_delim ) {
21753      mp_missing_err(mp, str(text(r_delim)));
21754 @.Missing `)'@>
21755     help2("I found no right delimiter to match a left one. So I've")
21756       ("put one in, behind the scenes; this may fix the problem.");
21757     mp_back_error(mp);
21758   } else { 
21759     print_err("The token `"); mp_print_text(r_delim);
21760 @.The token...delimiter@>
21761     mp_print(mp, "' is no longer a right delimiter");
21762     help3("Strange: This token has lost its former meaning!")
21763       ("I'll read it as a right delimiter this time;")
21764       ("but watch out, I'll probably miss it later.");
21765     mp_error(mp);
21766   }
21767 }
21768
21769 @ The next four commands save or change the values associated with tokens.
21770
21771 @<Cases of |do_statement|...@>=
21772 case save_command: 
21773   do {  
21774     mp_get_symbol(mp); mp_save_variable(mp, mp->cur_sym); mp_get_x_next(mp);
21775   } while (mp->cur_cmd==comma);
21776   break;
21777 case interim_command: mp_do_interim(mp); break;
21778 case let_command: mp_do_let(mp); break;
21779 case new_internal: mp_do_new_internal(mp); break;
21780
21781 @ @<Declare action procedures for use by |do_statement|@>=
21782 void mp_do_statement (MP mp);
21783 void mp_do_interim (MP mp);
21784
21785 @ @c void mp_do_interim (MP mp) { 
21786   mp_get_x_next(mp);
21787   if ( mp->cur_cmd!=internal_quantity ) {
21788      print_err("The token `");
21789 @.The token...quantity@>
21790     if ( mp->cur_sym==0 ) mp_print(mp, "(%CAPSULE)");
21791     else mp_print_text(mp->cur_sym);
21792     mp_print(mp, "' isn't an internal quantity");
21793     help1("Something like `tracingonline' should follow `interim'.");
21794     mp_back_error(mp);
21795   } else { 
21796     mp_save_internal(mp, mp->cur_mod); mp_back_input(mp);
21797   }
21798   mp_do_statement(mp);
21799 }
21800
21801 @ The following procedure is careful not to undefine the left-hand symbol
21802 too soon, lest commands like `{\tt let x=x}' have a surprising effect.
21803
21804 @<Declare action procedures for use by |do_statement|@>=
21805 void mp_do_let (MP mp) ;
21806
21807 @ @c void mp_do_let (MP mp) {
21808   pointer l; /* hash location of the left-hand symbol */
21809   mp_get_symbol(mp); l=mp->cur_sym; mp_get_x_next(mp);
21810   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
21811      mp_missing_err(mp, "=");
21812 @.Missing `='@>
21813     help3("You should have said `let symbol = something'.")
21814       ("But don't worry; I'll pretend that an equals sign")
21815       ("was present. The next token I read will be `something'.");
21816     mp_back_error(mp);
21817   }
21818   mp_get_symbol(mp);
21819   switch (mp->cur_cmd) {
21820   case defined_macro: case secondary_primary_macro:
21821   case tertiary_secondary_macro: case expression_tertiary_macro: 
21822     add_mac_ref(mp->cur_mod);
21823     break;
21824   default: 
21825     break;
21826   }
21827   mp_clear_symbol(mp, l,false); eq_type(l)=mp->cur_cmd;
21828   if ( mp->cur_cmd==tag_token ) equiv(l)=null;
21829   else equiv(l)=mp->cur_mod;
21830   mp_get_x_next(mp);
21831 }
21832
21833 @ @<Declarations@>=
21834 void mp_grow_internals (MP mp, int l);
21835 void mp_do_new_internal (MP mp) ;
21836
21837 @ @c
21838 void mp_grow_internals (MP mp, int l) {
21839   scaled *internal;
21840   char * *int_name; 
21841   int k;
21842   if ( hash_end+l>max_halfword ) {
21843     mp_confusion(mp, "out of memory space"); /* can't be reached */
21844   }
21845   int_name = xmalloc ((l+1),sizeof(char *));
21846   internal = xmalloc ((l+1),sizeof(scaled));
21847   for (k=0;k<=l; k++ ) { 
21848     if (k<=mp->max_internal) {
21849       internal[k]=mp->internal[k]; 
21850       int_name[k]=mp->int_name[k]; 
21851     } else {
21852       internal[k]=0; 
21853       int_name[k]=NULL; 
21854     }
21855   }
21856   xfree(mp->internal); xfree(mp->int_name);
21857   mp->int_name = int_name;
21858   mp->internal = internal;
21859   mp->max_internal = l;
21860 }
21861
21862
21863 void mp_do_new_internal (MP mp) { 
21864   do {  
21865     if ( mp->int_ptr==mp->max_internal ) {
21866       mp_grow_internals(mp, (mp->max_internal + (mp->max_internal>>2)));
21867     }
21868     mp_get_clear_symbol(mp); incr(mp->int_ptr);
21869     eq_type(mp->cur_sym)=internal_quantity; 
21870     equiv(mp->cur_sym)=mp->int_ptr;
21871     if(mp->int_name[mp->int_ptr]!=NULL)
21872       xfree(mp->int_name[mp->int_ptr]);
21873     mp->int_name[mp->int_ptr]=str(text(mp->cur_sym)); 
21874     mp->internal[mp->int_ptr]=0;
21875     mp_get_x_next(mp);
21876   } while (mp->cur_cmd==comma);
21877 }
21878
21879 @ @<Dealloc variables@>=
21880 for (k=0;k<=mp->max_internal;k++) {
21881    xfree(mp->int_name[k]);
21882 }
21883 xfree(mp->internal); 
21884 xfree(mp->int_name); 
21885
21886
21887 @ The various `\&{show}' commands are distinguished by modifier fields
21888 in the usual way.
21889
21890 @d show_token_code 0 /* show the meaning of a single token */
21891 @d show_stats_code 1 /* show current memory and string usage */
21892 @d show_code 2 /* show a list of expressions */
21893 @d show_var_code 3 /* show a variable and its descendents */
21894 @d show_dependencies_code 4 /* show dependent variables in terms of independents */
21895
21896 @<Put each...@>=
21897 mp_primitive(mp, "showtoken",show_command,show_token_code);
21898 @:show_token_}{\&{showtoken} primitive@>
21899 mp_primitive(mp, "showstats",show_command,show_stats_code);
21900 @:show_stats_}{\&{showstats} primitive@>
21901 mp_primitive(mp, "show",show_command,show_code);
21902 @:show_}{\&{show} primitive@>
21903 mp_primitive(mp, "showvariable",show_command,show_var_code);
21904 @:show_var_}{\&{showvariable} primitive@>
21905 mp_primitive(mp, "showdependencies",show_command,show_dependencies_code);
21906 @:show_dependencies_}{\&{showdependencies} primitive@>
21907
21908 @ @<Cases of |print_cmd...@>=
21909 case show_command: 
21910   switch (m) {
21911   case show_token_code:mp_print(mp, "showtoken"); break;
21912   case show_stats_code:mp_print(mp, "showstats"); break;
21913   case show_code:mp_print(mp, "show"); break;
21914   case show_var_code:mp_print(mp, "showvariable"); break;
21915   default: mp_print(mp, "showdependencies"); break;
21916   }
21917   break;
21918
21919 @ @<Cases of |do_statement|...@>=
21920 case show_command:mp_do_show_whatever(mp); break;
21921
21922 @ The value of |cur_mod| controls the |verbosity| in the |print_exp| routine:
21923 if it's |show_code|, complicated structures are abbreviated, otherwise
21924 they aren't.
21925
21926 @<Declare action procedures for use by |do_statement|@>=
21927 void mp_do_show (MP mp) ;
21928
21929 @ @c void mp_do_show (MP mp) { 
21930   do {  
21931     mp_get_x_next(mp); mp_scan_expression(mp);
21932     mp_print_nl(mp, ">> ");
21933 @.>>@>
21934     mp_print_exp(mp, null,2); mp_flush_cur_exp(mp, 0);
21935   } while (mp->cur_cmd==comma);
21936 }
21937
21938 @ @<Declare action procedures for use by |do_statement|@>=
21939 void mp_disp_token (MP mp) ;
21940
21941 @ @c void mp_disp_token (MP mp) { 
21942   mp_print_nl(mp, "> ");
21943 @.>\relax@>
21944   if ( mp->cur_sym==0 ) {
21945     @<Show a numeric or string or capsule token@>;
21946   } else { 
21947     mp_print_text(mp->cur_sym); mp_print_char(mp, '=');
21948     if ( eq_type(mp->cur_sym)>=outer_tag ) mp_print(mp, "(outer) ");
21949     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod);
21950     if ( mp->cur_cmd==defined_macro ) {
21951       mp_print_ln(mp); mp_show_macro(mp, mp->cur_mod,null,100000);
21952     } /* this avoids recursion between |show_macro| and |print_cmd_mod| */
21953 @^recursion@>
21954   }
21955 }
21956
21957 @ @<Show a numeric or string or capsule token@>=
21958
21959   if ( mp->cur_cmd==numeric_token ) {
21960     mp_print_scaled(mp, mp->cur_mod);
21961   } else if ( mp->cur_cmd==capsule_token ) {
21962     mp->g_pointer=mp->cur_mod; mp_print_capsule(mp);
21963   } else  { 
21964     mp_print_char(mp, '"'); 
21965     mp_print_str(mp, mp->cur_mod); mp_print_char(mp, '"');
21966     delete_str_ref(mp->cur_mod);
21967   }
21968 }
21969
21970 @ The following cases of |print_cmd_mod| might arise in connection
21971 with |disp_token|, although they don't correspond to any
21972 primitive tokens.
21973
21974 @<Cases of |print_cmd_...@>=
21975 case left_delimiter:
21976 case right_delimiter: 
21977   if ( c==left_delimiter ) mp_print(mp, "left");
21978   else mp_print(mp, "right");
21979   mp_print(mp, " delimiter that matches "); 
21980   mp_print_text(m);
21981   break;
21982 case tag_token:
21983   if ( m==null ) mp_print(mp, "tag");
21984    else mp_print(mp, "variable");
21985    break;
21986 case defined_macro: 
21987    mp_print(mp, "macro:");
21988    break;
21989 case secondary_primary_macro:
21990 case tertiary_secondary_macro:
21991 case expression_tertiary_macro:
21992   mp_print_cmd_mod(mp, macro_def,c); 
21993   mp_print(mp, "'d macro:");
21994   mp_print_ln(mp); mp_show_token_list(mp, link(link(m)),null,1000,0);
21995   break;
21996 case repeat_loop:
21997   mp_print(mp, "[repeat the loop]");
21998   break;
21999 case internal_quantity:
22000   mp_print(mp, mp->int_name[m]);
22001   break;
22002
22003 @ @<Declare action procedures for use by |do_statement|@>=
22004 void mp_do_show_token (MP mp) ;
22005
22006 @ @c void mp_do_show_token (MP mp) { 
22007   do {  
22008     get_t_next; mp_disp_token(mp);
22009     mp_get_x_next(mp);
22010   } while (mp->cur_cmd==comma);
22011 }
22012
22013 @ @<Declare action procedures for use by |do_statement|@>=
22014 void mp_do_show_stats (MP mp) ;
22015
22016 @ @c void mp_do_show_stats (MP mp) { 
22017   mp_print_nl(mp, "Memory usage ");
22018 @.Memory usage...@>
22019   mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used);
22020   if ( false )
22021     mp_print(mp, "unknown");
22022   mp_print(mp, " ("); mp_print_int(mp, mp->hi_mem_min-mp->lo_mem_max-1);
22023   mp_print(mp, " still untouched)"); mp_print_ln(mp);
22024   mp_print_nl(mp, "String usage ");
22025   mp_print_int(mp, mp->strs_in_use-mp->init_str_use);
22026   mp_print_char(mp, '&'); mp_print_int(mp, mp->pool_in_use-mp->init_pool_ptr);
22027   if ( false )
22028     mp_print(mp, "unknown");
22029   mp_print(mp, " (");
22030   mp_print_int(mp, mp->max_strings-1-mp->strs_used_up); mp_print_char(mp, '&');
22031   mp_print_int(mp, mp->pool_size-mp->pool_ptr); 
22032   mp_print(mp, " now untouched)"); mp_print_ln(mp);
22033   mp_get_x_next(mp);
22034 }
22035
22036 @ Here's a recursive procedure that gives an abbreviated account
22037 of a variable, for use by |do_show_var|.
22038
22039 @<Declare action procedures for use by |do_statement|@>=
22040 void mp_disp_var (MP mp,pointer p) ;
22041
22042 @ @c void mp_disp_var (MP mp,pointer p) {
22043   pointer q; /* traverses attributes and subscripts */
22044   int n; /* amount of macro text to show */
22045   if ( type(p)==mp_structured )  {
22046     @<Descend the structure@>;
22047   } else if ( type(p)>=mp_unsuffixed_macro ) {
22048     @<Display a variable macro@>;
22049   } else if ( type(p)!=undefined ){ 
22050     mp_print_nl(mp, ""); mp_print_variable_name(mp, p); 
22051     mp_print_char(mp, '=');
22052     mp_print_exp(mp, p,0);
22053   }
22054 }
22055
22056 @ @<Descend the structure@>=
22057
22058   q=attr_head(p);
22059   do {  mp_disp_var(mp, q); q=link(q); } while (q!=end_attr);
22060   q=subscr_head(p);
22061   while ( name_type(q)==mp_subscr ) { 
22062     mp_disp_var(mp, q); q=link(q);
22063   }
22064 }
22065
22066 @ @<Display a variable macro@>=
22067
22068   mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22069   if ( type(p)>mp_unsuffixed_macro ) 
22070     mp_print(mp, "@@#"); /* |suffixed_macro| */
22071   mp_print(mp, "=macro:");
22072   if ( (int)mp->file_offset>=mp->max_print_line-20 ) n=5;
22073   else n=mp->max_print_line-mp->file_offset-15;
22074   mp_show_macro(mp, value(p),null,n);
22075 }
22076
22077 @ @<Declare action procedures for use by |do_statement|@>=
22078 void mp_do_show_var (MP mp) ;
22079
22080 @ @c void mp_do_show_var (MP mp) { 
22081   do {  
22082     get_t_next;
22083     if ( mp->cur_sym>0 ) if ( mp->cur_sym<=hash_end )
22084       if ( mp->cur_cmd==tag_token ) if ( mp->cur_mod!=null ) {
22085       mp_disp_var(mp, mp->cur_mod); goto DONE;
22086     }
22087    mp_disp_token(mp);
22088   DONE:
22089    mp_get_x_next(mp);
22090   } while (mp->cur_cmd==comma);
22091 }
22092
22093 @ @<Declare action procedures for use by |do_statement|@>=
22094 void mp_do_show_dependencies (MP mp) ;
22095
22096 @ @c void mp_do_show_dependencies (MP mp) {
22097   pointer p; /* link that runs through all dependencies */
22098   p=link(dep_head);
22099   while ( p!=dep_head ) {
22100     if ( mp_interesting(mp, p) ) {
22101       mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22102       if ( type(p)==mp_dependent ) mp_print_char(mp, '=');
22103       else mp_print(mp, " = "); /* extra spaces imply proto-dependency */
22104       mp_print_dependency(mp, dep_list(p),type(p));
22105     }
22106     p=dep_list(p);
22107     while ( info(p)!=null ) p=link(p);
22108     p=link(p);
22109   }
22110   mp_get_x_next(mp);
22111 }
22112
22113 @ Finally we are ready for the procedure that governs all of the
22114 show commands.
22115
22116 @<Declare action procedures for use by |do_statement|@>=
22117 void mp_do_show_whatever (MP mp) ;
22118
22119 @ @c void mp_do_show_whatever (MP mp) { 
22120   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
22121   switch (mp->cur_mod) {
22122   case show_token_code:mp_do_show_token(mp); break;
22123   case show_stats_code:mp_do_show_stats(mp); break;
22124   case show_code:mp_do_show(mp); break;
22125   case show_var_code:mp_do_show_var(mp); break;
22126   case show_dependencies_code:mp_do_show_dependencies(mp); break;
22127   } /* there are no other cases */
22128   if ( mp->internal[showstopping]>0 ){ 
22129     print_err("OK");
22130 @.OK@>
22131     if ( mp->interaction<mp_error_stop_mode ) { 
22132       help0; decr(mp->error_count);
22133     } else {
22134       help1("This isn't an error message; I'm just showing something.");
22135     }
22136     if ( mp->cur_cmd==semicolon ) mp_error(mp);
22137      else mp_put_get_error(mp);
22138   }
22139 }
22140
22141 @ The `\&{addto}' command needs the following additional primitives:
22142
22143 @d double_path_code 0 /* command modifier for `\&{doublepath}' */
22144 @d contour_code 1 /* command modifier for `\&{contour}' */
22145 @d also_code 2 /* command modifier for `\&{also}' */
22146
22147 @ Pre and postscripts need two new identifiers:
22148
22149 @d with_pre_script 11
22150 @d with_post_script 13
22151
22152 @<Put each...@>=
22153 mp_primitive(mp, "doublepath",thing_to_add,double_path_code);
22154 @:double_path_}{\&{doublepath} primitive@>
22155 mp_primitive(mp, "contour",thing_to_add,contour_code);
22156 @:contour_}{\&{contour} primitive@>
22157 mp_primitive(mp, "also",thing_to_add,also_code);
22158 @:also_}{\&{also} primitive@>
22159 mp_primitive(mp, "withpen",with_option,mp_pen_type);
22160 @:with_pen_}{\&{withpen} primitive@>
22161 mp_primitive(mp, "dashed",with_option,mp_picture_type);
22162 @:dashed_}{\&{dashed} primitive@>
22163 mp_primitive(mp, "withprescript",with_option,with_pre_script);
22164 @:with_pre_script_}{\&{withprescript} primitive@>
22165 mp_primitive(mp, "withpostscript",with_option,with_post_script);
22166 @:with_post_script_}{\&{withpostscript} primitive@>
22167 mp_primitive(mp, "withoutcolor",with_option,no_model);
22168 @:with_color_}{\&{withoutcolor} primitive@>
22169 mp_primitive(mp, "withgreyscale",with_option,grey_model);
22170 @:with_color_}{\&{withgreyscale} primitive@>
22171 mp_primitive(mp, "withcolor",with_option,uninitialized_model);
22172 @:with_color_}{\&{withcolor} primitive@>
22173 /*  \&{withrgbcolor} is an alias for \&{withcolor} */
22174 mp_primitive(mp, "withrgbcolor",with_option,rgb_model);
22175 @:with_color_}{\&{withrgbcolor} primitive@>
22176 mp_primitive(mp, "withcmykcolor",with_option,cmyk_model);
22177 @:with_color_}{\&{withcmykcolor} primitive@>
22178
22179 @ @<Cases of |print_cmd...@>=
22180 case thing_to_add:
22181   if ( m==contour_code ) mp_print(mp, "contour");
22182   else if ( m==double_path_code ) mp_print(mp, "doublepath");
22183   else mp_print(mp, "also");
22184   break;
22185 case with_option:
22186   if ( m==mp_pen_type ) mp_print(mp, "withpen");
22187   else if ( m==with_pre_script ) mp_print(mp, "withprescript");
22188   else if ( m==with_post_script ) mp_print(mp, "withpostscript");
22189   else if ( m==no_model ) mp_print(mp, "withoutcolor");
22190   else if ( m==rgb_model ) mp_print(mp, "withrgbcolor");
22191   else if ( m==uninitialized_model ) mp_print(mp, "withcolor");
22192   else if ( m==cmyk_model ) mp_print(mp, "withcmykcolor");
22193   else if ( m==grey_model ) mp_print(mp, "withgreyscale");
22194   else mp_print(mp, "dashed");
22195   break;
22196
22197 @ The |scan_with_list| procedure parses a $\langle$with list$\rangle$ and
22198 updates the list of graphical objects starting at |p|.  Each $\langle$with
22199 clause$\rangle$ updates all graphical objects whose |type| is compatible.
22200 Other objects are ignored.
22201
22202 @<Declare action procedures for use by |do_statement|@>=
22203 void mp_scan_with_list (MP mp,pointer p) ;
22204
22205 @ @c void mp_scan_with_list (MP mp,pointer p) {
22206   small_number t; /* |cur_mod| of the |with_option| (should match |cur_type|) */
22207   pointer q; /* for list manipulation */
22208   int old_setting; /* saved |selector| setting */
22209   pointer k; /* for finding the near-last item in a list  */
22210   str_number s; /* for string cleanup after combining  */
22211   pointer cp,pp,dp,ap,bp;
22212     /* objects being updated; |void| initially; |null| to suppress update */
22213   cp=diov; pp=diov; dp=diov; ap=diov; bp=diov;
22214   k=0;
22215   while ( mp->cur_cmd==with_option ){ 
22216     t=mp->cur_mod;
22217     mp_get_x_next(mp);
22218     if ( t!=no_model ) mp_scan_expression(mp);
22219     if (((t==with_pre_script)&&(mp->cur_type!=mp_string_type))||
22220      ((t==with_post_script)&&(mp->cur_type!=mp_string_type))||
22221      ((t==uninitialized_model)&&
22222         ((mp->cur_type!=mp_cmykcolor_type)&&(mp->cur_type!=mp_color_type)
22223           &&(mp->cur_type!=mp_known)&&(mp->cur_type!=mp_boolean_type)))||
22224      ((t==cmyk_model)&&(mp->cur_type!=mp_cmykcolor_type))||
22225      ((t==rgb_model)&&(mp->cur_type!=mp_color_type))||
22226      ((t==grey_model)&&(mp->cur_type!=mp_known))||
22227      ((t==mp_pen_type)&&(mp->cur_type!=t))||
22228      ((t==mp_picture_type)&&(mp->cur_type!=t)) ) {
22229       @<Complain about improper type@>;
22230     } else if ( t==uninitialized_model ) {
22231       if ( cp==diov ) @<Make |cp| a colored object in object list~|p|@>;
22232       if ( cp!=null )
22233         @<Transfer a color from the current expression to object~|cp|@>;
22234       mp_flush_cur_exp(mp, 0);
22235     } else if ( t==rgb_model ) {
22236       if ( cp==diov ) @<Make |cp| a colored object in object list~|p|@>;
22237       if ( cp!=null )
22238         @<Transfer a rgbcolor from the current expression to object~|cp|@>;
22239       mp_flush_cur_exp(mp, 0);
22240     } else if ( t==cmyk_model ) {
22241       if ( cp==diov ) @<Make |cp| a colored object in object list~|p|@>;
22242       if ( cp!=null )
22243         @<Transfer a cmykcolor from the current expression to object~|cp|@>;
22244       mp_flush_cur_exp(mp, 0);
22245     } else if ( t==grey_model ) {
22246       if ( cp==diov ) @<Make |cp| a colored object in object list~|p|@>;
22247       if ( cp!=null )
22248         @<Transfer a greyscale from the current expression to object~|cp|@>;
22249       mp_flush_cur_exp(mp, 0);
22250     } else if ( t==no_model ) {
22251       if ( cp==diov ) @<Make |cp| a colored object in object list~|p|@>;
22252       if ( cp!=null )
22253         @<Transfer a noncolor from the current expression to object~|cp|@>;
22254     } else if ( t==mp_pen_type ) {
22255       if ( pp==diov ) @<Make |pp| an object in list~|p| that needs a pen@>;
22256       if ( pp!=null ) {
22257         if ( pen_p(pp)!=null ) mp_toss_knot_list(mp, pen_p(pp));
22258         pen_p(pp)=mp->cur_exp; mp->cur_type=mp_vacuous;
22259       }
22260     } else if ( t==with_pre_script ) {
22261       if ( ap==diov )
22262         ap=p;
22263       while ( (ap!=null)&&(! has_color(ap)) )
22264          ap=link(ap);
22265       if ( ap!=null ) {
22266         if ( pre_script(ap)!=null ) { /*  build a new,combined string  */
22267           s=pre_script(ap);
22268           old_setting=mp->selector;
22269               mp->selector=new_string;
22270           str_room(length(pre_script(ap))+length(mp->cur_exp)+2);
22271               mp_print_str(mp, mp->cur_exp);
22272           append_char(13);  /* a forced \ps\ newline  */
22273           mp_print_str(mp, pre_script(ap));
22274           pre_script(ap)=mp_make_string(mp);
22275           delete_str_ref(s);
22276           mp->selector=old_setting;
22277         } else {
22278           pre_script(ap)=mp->cur_exp;
22279         }
22280         mp->cur_type=mp_vacuous;
22281       }
22282     } else if ( t==with_post_script ) {
22283       if ( bp==diov )
22284         k=p; 
22285       bp=k;
22286       while ( link(k)!=null ) {
22287         k=link(k);
22288         if ( has_color(k) ) bp=k;
22289       }
22290       if ( bp!=null ) {
22291          if ( post_script(bp)!=null ) {
22292            s=post_script(bp);
22293            old_setting=mp->selector;
22294                mp->selector=new_string;
22295            str_room(length(post_script(bp))+length(mp->cur_exp)+2);
22296            mp_print_str(mp, post_script(bp));
22297            append_char(13); /* a forced \ps\ newline  */
22298            mp_print_str(mp, mp->cur_exp);
22299            post_script(bp)=mp_make_string(mp);
22300            delete_str_ref(s);
22301            mp->selector=old_setting;
22302          } else {
22303            post_script(bp)=mp->cur_exp;
22304          }
22305          mp->cur_type=mp_vacuous;
22306        }
22307     } else { 
22308       if ( dp==diov ) 
22309         @<Make |dp| a stroked node in list~|p|@>;
22310       if ( dp!=null ) {
22311         if ( dash_p(dp)!=null ) delete_edge_ref(dash_p(dp));
22312         dash_p(dp)=mp_make_dashes(mp, mp->cur_exp);
22313         dash_scale(dp)=unity;
22314         mp->cur_type=mp_vacuous;
22315       }
22316     }
22317   }
22318   @<Copy the information from objects |cp|, |pp|, and |dp| into the rest
22319     of the list@>;
22320 };
22321
22322 @ @<Complain about improper type@>=
22323 { exp_err("Improper type");
22324 @.Improper type@>
22325 help2("Next time say `withpen <known pen expression>';")
22326   ("I'll ignore the bad `with' clause and look for another.");
22327 if ( t==with_pre_script )
22328   mp->help_line[1]="Next time say `withprescript <known string expression>';";
22329 else if ( t==with_post_script )
22330   mp->help_line[1]="Next time say `withpostscript <known string expression>';";
22331 else if ( t==mp_picture_type )
22332   mp->help_line[1]="Next time say `dashed <known picture expression>';";
22333 else if ( t==uninitialized_model )
22334   mp->help_line[1]="Next time say `withcolor <known color expression>';";
22335 else if ( t==rgb_model )
22336   mp->help_line[1]="Next time say `withrgbcolor <known color expression>';";
22337 else if ( t==cmyk_model )
22338   mp->help_line[1]="Next time say `withcmykcolor <known cmykcolor expression>';";
22339 else if ( t==grey_model )
22340   mp->help_line[1]="Next time say `withgreyscale <known numeric expression>';";;
22341 mp_put_get_flush_error(mp, 0);
22342 }
22343
22344 @ Forcing the color to be between |0| and |unity| here guarantees that no
22345 picture will ever contain a color outside the legal range for \ps\ graphics.
22346
22347 @<Transfer a color from the current expression to object~|cp|@>=
22348 { if ( mp->cur_type==mp_color_type )
22349    @<Transfer a rgbcolor from the current expression to object~|cp|@>
22350 else if ( mp->cur_type==mp_cmykcolor_type )
22351    @<Transfer a cmykcolor from the current expression to object~|cp|@>
22352 else if ( mp->cur_type==mp_known )
22353    @<Transfer a greyscale from the current expression to object~|cp|@>
22354 else if ( mp->cur_exp==false_code )
22355    @<Transfer a noncolor from the current expression to object~|cp|@>;
22356 }
22357
22358 @ @<Transfer a rgbcolor from the current expression to object~|cp|@>=
22359 { q=value(mp->cur_exp);
22360 cyan_val(cp)=0;
22361 magenta_val(cp)=0;
22362 yellow_val(cp)=0;
22363 black_val(cp)=0;
22364 red_val(cp)=value(red_part_loc(q));
22365 green_val(cp)=value(green_part_loc(q));
22366 blue_val(cp)=value(blue_part_loc(q));
22367 color_model(cp)=rgb_model;
22368 if ( red_val(cp)<0 ) red_val(cp)=0;
22369 if ( green_val(cp)<0 ) green_val(cp)=0;
22370 if ( blue_val(cp)<0 ) blue_val(cp)=0;
22371 if ( red_val(cp)>unity ) red_val(cp)=unity;
22372 if ( green_val(cp)>unity ) green_val(cp)=unity;
22373 if ( blue_val(cp)>unity ) blue_val(cp)=unity;
22374 }
22375
22376 @ @<Transfer a cmykcolor from the current expression to object~|cp|@>=
22377 { q=value(mp->cur_exp);
22378 cyan_val(cp)=value(cyan_part_loc(q));
22379 magenta_val(cp)=value(magenta_part_loc(q));
22380 yellow_val(cp)=value(yellow_part_loc(q));
22381 black_val(cp)=value(black_part_loc(q));
22382 color_model(cp)=cmyk_model;
22383 if ( cyan_val(cp)<0 ) cyan_val(cp)=0;
22384 if ( magenta_val(cp)<0 ) magenta_val(cp)=0;
22385 if ( yellow_val(cp)<0 ) yellow_val(cp)=0;
22386 if ( black_val(cp)<0 ) black_val(cp)=0;
22387 if ( cyan_val(cp)>unity ) cyan_val(cp)=unity;
22388 if ( magenta_val(cp)>unity ) magenta_val(cp)=unity;
22389 if ( yellow_val(cp)>unity ) yellow_val(cp)=unity;
22390 if ( black_val(cp)>unity ) black_val(cp)=unity;
22391 }
22392
22393 @ @<Transfer a greyscale from the current expression to object~|cp|@>=
22394 { q=mp->cur_exp;
22395 cyan_val(cp)=0;
22396 magenta_val(cp)=0;
22397 yellow_val(cp)=0;
22398 black_val(cp)=0;
22399 grey_val(cp)=q;
22400 color_model(cp)=grey_model;
22401 if ( grey_val(cp)<0 ) grey_val(cp)=0;
22402 if ( grey_val(cp)>unity ) grey_val(cp)=unity;
22403 }
22404
22405 @ @<Transfer a noncolor from the current expression to object~|cp|@>=
22406 {
22407 cyan_val(cp)=0;
22408 magenta_val(cp)=0;
22409 yellow_val(cp)=0;
22410 black_val(cp)=0;
22411 grey_val(cp)=0;
22412 color_model(cp)=no_model;
22413 }
22414
22415 @ @<Make |cp| a colored object in object list~|p|@>=
22416 { cp=p;
22417   while ( cp!=null ){ 
22418     if ( has_color(cp) ) break;
22419     cp=link(cp);
22420   }
22421 }
22422
22423 @ @<Make |pp| an object in list~|p| that needs a pen@>=
22424 { pp=p;
22425   while ( pp!=null ) {
22426     if ( has_pen(pp) ) break;
22427     pp=link(pp);
22428   }
22429 }
22430
22431 @ @<Make |dp| a stroked node in list~|p|@>=
22432 { dp=p;
22433   while ( dp!=null ) {
22434     if ( type(dp)==stroked_code ) break;
22435     dp=link(dp);
22436   }
22437 }
22438
22439 @ @<Copy the information from objects |cp|, |pp|, and |dp| into...@>=
22440 @<Copy |cp|'s color into the colored objects linked to~|cp|@>;
22441 if ( pp>diov )
22442   @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>;
22443 if ( dp>diov ) @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>
22444
22445 @ @<Copy |cp|'s color into the colored objects linked to~|cp|@>=
22446 { q=link(cp);
22447   while ( q!=null ) { 
22448     if ( has_color(q) ) {
22449       red_val(q)=red_val(cp);
22450       green_val(q)=green_val(cp);
22451       blue_val(q)=blue_val(cp);
22452       black_val(q)=black_val(cp);
22453       color_model(q)=color_model(cp);
22454     }
22455     q=link(q);
22456   }
22457 }
22458
22459 @ @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>=
22460 { q=link(pp);
22461   while ( q!=null ) {
22462     if ( has_pen(q) ) {
22463       if ( pen_p(q)!=null ) mp_toss_knot_list(mp, pen_p(q));
22464       pen_p(q)=copy_pen(pen_p(pp));
22465     }
22466     q=link(q);
22467   }
22468 }
22469
22470 @ @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>=
22471 { q=link(dp);
22472   while ( q!=null ) {
22473     if ( type(q)==stroked_code ) {
22474       if ( dash_p(q)!=null ) delete_edge_ref(dash_p(q));
22475       dash_p(q)=dash_p(dp);
22476       dash_scale(q)=unity;
22477       if ( dash_p(q)!=null ) add_edge_ref(dash_p(q));
22478     }
22479     q=link(q);
22480   }
22481 }
22482
22483 @ One of the things we need to do when we've parsed an \&{addto} or
22484 similar command is find the header of a supposed \&{picture} variable, given
22485 a token list for that variable.  Since the edge structure is about to be
22486 updated, we use |private_edges| to make sure that this is possible.
22487
22488 @<Declare action procedures for use by |do_statement|@>=
22489 pointer mp_find_edges_var (MP mp, pointer t) ;
22490
22491 @ @c pointer mp_find_edges_var (MP mp, pointer t) {
22492   pointer p;
22493   pointer cur_edges; /* the return value */
22494   p=mp_find_variable(mp, t); cur_edges=null;
22495   if ( p==null ) { 
22496     mp_obliterated(mp, t); mp_put_get_error(mp);
22497   } else if ( type(p)!=mp_picture_type )  { 
22498     print_err("Variable "); mp_show_token_list(mp, t,null,1000,0);
22499 @.Variable x is the wrong type@>
22500     mp_print(mp, " is the wrong type ("); 
22501     mp_print_type(mp, type(p)); mp_print_char(mp, ')');
22502     help2("I was looking for a \"known\" picture variable.")
22503          ("So I'll not change anything just now."); 
22504     mp_put_get_error(mp);
22505   } else { 
22506     value(p)=mp_private_edges(mp, value(p));
22507     cur_edges=value(p);
22508   }
22509   mp_flush_node_list(mp, t);
22510   return cur_edges;
22511 };
22512
22513 @ @<Cases of |do_statement|...@>=
22514 case add_to_command: mp_do_add_to(mp); break;
22515 case bounds_command:mp_do_bounds(mp); break;
22516
22517 @ @<Put each...@>=
22518 mp_primitive(mp, "clip",bounds_command,mp_start_clip_code);
22519 @:clip_}{\&{clip} primitive@>
22520 mp_primitive(mp, "setbounds",bounds_command,mp_start_bounds_code);
22521 @:set_bounds_}{\&{setbounds} primitive@>
22522
22523 @ @<Cases of |print_cmd...@>=
22524 case bounds_command: 
22525   if ( m==mp_start_clip_code ) mp_print(mp, "clip");
22526   else mp_print(mp, "setbounds");
22527   break;
22528
22529 @ The following function parses the beginning of an \&{addto} or \&{clip}
22530 command: it expects a variable name followed by a token with |cur_cmd=sep|
22531 and then an expression.  The function returns the token list for the variable
22532 and stores the command modifier for the separator token in the global variable
22533 |last_add_type|.  We must be careful because this variable might get overwritten
22534 any time we call |get_x_next|.
22535
22536 @<Glob...@>=
22537 quarterword last_add_type;
22538   /* command modifier that identifies the last \&{addto} command */
22539
22540 @ @<Declare action procedures for use by |do_statement|@>=
22541 pointer mp_start_draw_cmd (MP mp,quarterword sep) ;
22542
22543 @ @c pointer mp_start_draw_cmd (MP mp,quarterword sep) {
22544   pointer lhv; /* variable to add to left */
22545   quarterword add_type=0; /* value to be returned in |last_add_type| */
22546   lhv=null;
22547   mp_get_x_next(mp); mp->var_flag=sep; mp_scan_primary(mp);
22548   if ( mp->cur_type!=mp_token_list ) {
22549     @<Abandon edges command because there's no variable@>;
22550   } else  { 
22551     lhv=mp->cur_exp; add_type=mp->cur_mod;
22552     mp->cur_type=mp_vacuous; mp_get_x_next(mp); mp_scan_expression(mp);
22553   }
22554   mp->last_add_type=add_type;
22555   return lhv;
22556 }
22557
22558 @ @<Abandon edges command because there's no variable@>=
22559 { exp_err("Not a suitable variable");
22560 @.Not a suitable variable@>
22561   help4("At this point I needed to see the name of a picture variable.")
22562     ("(Or perhaps you have indeed presented me with one; I might")
22563     ("have missed it, if it wasn't followed by the proper token.)")
22564     ("So I'll not change anything just now.");
22565   mp_put_get_flush_error(mp, 0);
22566 }
22567
22568 @ Here is an example of how to use |start_draw_cmd|.
22569
22570 @<Declare action procedures for use by |do_statement|@>=
22571 void mp_do_bounds (MP mp) ;
22572
22573 @ @c void mp_do_bounds (MP mp) {
22574   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22575   pointer p; /* for list manipulation */
22576   integer m; /* initial value of |cur_mod| */
22577   m=mp->cur_mod;
22578   lhv=mp_start_draw_cmd(mp, to_token);
22579   if ( lhv!=null ) {
22580     lhe=mp_find_edges_var(mp, lhv);
22581     if ( lhe==null ) {
22582       mp_flush_cur_exp(mp, 0);
22583     } else if ( mp->cur_type!=mp_path_type ) {
22584       exp_err("Improper `clip'");
22585 @.Improper `addto'@>
22586       help2("This expression should have specified a known path.")
22587         ("So I'll not change anything just now."); 
22588       mp_put_get_flush_error(mp, 0);
22589     } else if ( left_type(mp->cur_exp)==endpoint ) {
22590       @<Complain about a non-cycle@>;
22591     } else {
22592       @<Make |cur_exp| into a \&{setbounds} or clipping path and add it to |lhe|@>;
22593     }
22594   }
22595 }
22596
22597 @ @<Complain about a non-cycle@>=
22598 { print_err("Not a cycle");
22599 @.Not a cycle@>
22600   help2("That contour should have ended with `..cycle' or `&cycle'.")
22601     ("So I'll not change anything just now."); mp_put_get_error(mp);
22602 }
22603
22604 @ @<Make |cur_exp| into a \&{setbounds} or clipping path and add...@>=
22605 { p=mp_new_bounds_node(mp, mp->cur_exp,m);
22606   link(p)=link(dummy_loc(lhe));
22607   link(dummy_loc(lhe))=p;
22608   if ( obj_tail(lhe)==dummy_loc(lhe) ) obj_tail(lhe)=p;
22609   p=mp_get_node(mp, mp->gr_object_size[stop_type(m)]);
22610   type(p)=stop_type(m);
22611   link(obj_tail(lhe))=p;
22612   obj_tail(lhe)=p;
22613   mp_init_bbox(mp, lhe);
22614 }
22615
22616 @ The |do_add_to| procedure is a little like |do_clip| but there are a lot more
22617 cases to deal with.
22618
22619 @<Declare action procedures for use by |do_statement|@>=
22620 void mp_do_add_to (MP mp) ;
22621
22622 @ @c void mp_do_add_to (MP mp) {
22623   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22624   pointer p; /* the graphical object or list for |scan_with_list| to update */
22625   pointer e; /* an edge structure to be merged */
22626   quarterword add_type; /* |also_code|, |contour_code|, or |double_path_code| */
22627   lhv=mp_start_draw_cmd(mp, thing_to_add); add_type=mp->last_add_type;
22628   if ( lhv!=null ) {
22629     if ( add_type==also_code ) {
22630       @<Make sure the current expression is a suitable picture and set |e| and |p|
22631        appropriately@>;
22632     } else {
22633       @<Create a graphical object |p| based on |add_type| and the current
22634         expression@>;
22635     }
22636     mp_scan_with_list(mp, p);
22637     @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>;
22638   }
22639 }
22640
22641 @ Setting |p:=null| causes the $\langle$with list$\rangle$ to be ignored;
22642 setting |e:=null| prevents anything from being added to |lhe|.
22643
22644 @ @<Make sure the current expression is a suitable picture and set |e|...@>=
22645
22646   p=null; e=null;
22647   if ( mp->cur_type!=mp_picture_type ) {
22648     exp_err("Improper `addto'");
22649 @.Improper `addto'@>
22650     help2("This expression should have specified a known picture.")
22651       ("So I'll not change anything just now."); mp_put_get_flush_error(mp, 0);
22652   } else { 
22653     e=mp_private_edges(mp, mp->cur_exp); mp->cur_type=mp_vacuous;
22654     p=link(dummy_loc(e));
22655   }
22656 }
22657
22658 @ In this case |add_type<>also_code| so setting |p:=null| suppresses future
22659 attempts to add to the edge structure.
22660
22661 @<Create a graphical object |p| based on |add_type| and the current...@>=
22662 { e=null; p=null;
22663   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
22664   if ( mp->cur_type!=mp_path_type ) {
22665     exp_err("Improper `addto'");
22666 @.Improper `addto'@>
22667     help2("This expression should have specified a known path.")
22668       ("So I'll not change anything just now."); 
22669     mp_put_get_flush_error(mp, 0);
22670   } else if ( add_type==contour_code ) {
22671     if ( left_type(mp->cur_exp)==endpoint ) {
22672       @<Complain about a non-cycle@>;
22673     } else { 
22674       p=mp_new_fill_node(mp, mp->cur_exp);
22675       mp->cur_type=mp_vacuous;
22676     }
22677   } else { 
22678     p=mp_new_stroked_node(mp, mp->cur_exp);
22679     mp->cur_type=mp_vacuous;
22680   }
22681 }
22682
22683 @ @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>=
22684 lhe=mp_find_edges_var(mp, lhv);
22685 if ( lhe==null ) {
22686   if ( (e==null)&&(p!=null) ) e=mp_toss_gr_object(mp, p);
22687   if ( e!=null ) delete_edge_ref(e);
22688 } else if ( add_type==also_code ) {
22689   if ( e!=null ) {
22690     @<Merge |e| into |lhe| and delete |e|@>;
22691   } else { 
22692     do_nothing;
22693   }
22694 } else if ( p!=null ) {
22695   link(obj_tail(lhe))=p;
22696   obj_tail(lhe)=p;
22697   if ( add_type==double_path_code )
22698     if ( pen_p(p)==null ) 
22699       pen_p(p)=mp_get_pen_circle(mp, 0);
22700 }
22701
22702 @ @<Merge |e| into |lhe| and delete |e|@>=
22703 { if ( link(dummy_loc(e))!=null ) {
22704     link(obj_tail(lhe))=link(dummy_loc(e));
22705     obj_tail(lhe)=obj_tail(e);
22706     obj_tail(e)=dummy_loc(e);
22707     link(dummy_loc(e))=null;
22708     mp_flush_dash_list(mp, lhe);
22709   }
22710   mp_toss_edges(mp, e);
22711 }
22712
22713 @ @<Cases of |do_statement|...@>=
22714 case ship_out_command: mp_do_ship_out(mp); break;
22715
22716 @ @<Declare action procedures for use by |do_statement|@>=
22717 @<Declare the function called |tfm_check|@>;
22718 @<Declare the \ps\ output procedures@>;
22719 void mp_do_ship_out (MP mp) ;
22720
22721 @ @c void mp_do_ship_out (MP mp) {
22722   integer c; /* the character code */
22723   mp_get_x_next(mp); mp_scan_expression(mp);
22724   if ( mp->cur_type!=mp_picture_type ) {
22725     @<Complain that it's not a known picture@>;
22726   } else { 
22727     c=mp_round_unscaled(mp, mp->internal[char_code]) % 256;
22728     if ( c<0 ) c=c+256;
22729     @<Store the width information for character code~|c|@>;
22730     mp_ship_out(mp, mp->cur_exp);
22731     mp_flush_cur_exp(mp, 0);
22732   }
22733 }
22734
22735 @ @<Complain that it's not a known picture@>=
22736
22737   exp_err("Not a known picture");
22738   help1("I can only output known pictures.");
22739   mp_put_get_flush_error(mp, 0);
22740 }
22741
22742 @ The \&{everyjob} command simply assigns a nonzero value to the global variable
22743 |start_sym|.
22744
22745 @<Cases of |do_statement|...@>=
22746 case every_job_command: 
22747   mp_get_symbol(mp); mp->start_sym=mp->cur_sym; mp_get_x_next(mp);
22748   break;
22749
22750 @ @<Glob...@>=
22751 halfword start_sym; /* a symbolic token to insert at beginning of job */
22752
22753 @ @<Set init...@>=
22754 mp->start_sym=0;
22755
22756 @ Finally, we have only the ``message'' commands remaining.
22757
22758 @d message_code 0
22759 @d err_message_code 1
22760 @d err_help_code 2
22761 @d filename_template_code 3
22762 @d print_with_leading_zeroes(A)  g = mp->pool_ptr;
22763               mp_print_int(mp, (A)); g = mp->pool_ptr-g;
22764               if ( f>g ) {
22765                 mp->pool_ptr = mp->pool_ptr - g;
22766                 while ( f>g ) {
22767                   mp_print_char(mp, '0');
22768                   decr(f);
22769                   };
22770                 mp_print_int(mp, (A));
22771               };
22772               f = 0
22773
22774 @<Put each...@>=
22775 mp_primitive(mp, "message",message_command,message_code);
22776 @:message_}{\&{message} primitive@>
22777 mp_primitive(mp, "errmessage",message_command,err_message_code);
22778 @:err_message_}{\&{errmessage} primitive@>
22779 mp_primitive(mp, "errhelp",message_command,err_help_code);
22780 @:err_help_}{\&{errhelp} primitive@>
22781 mp_primitive(mp, "filenametemplate",message_command,filename_template_code);
22782 @:filename_template_}{\&{filenametemplate} primitive@>
22783
22784 @ @<Cases of |print_cmd...@>=
22785 case message_command: 
22786   if ( m<err_message_code ) mp_print(mp, "message");
22787   else if ( m==err_message_code ) mp_print(mp, "errmessage");
22788   else if ( m==filename_template_code ) mp_print(mp, "filenametemplate");
22789   else mp_print(mp, "errhelp");
22790   break;
22791
22792 @ @<Cases of |do_statement|...@>=
22793 case message_command: mp_do_message(mp); break;
22794
22795 @ @<Declare action procedures for use by |do_statement|@>=
22796 @<Declare a procedure called |no_string_err|@>;
22797 void mp_do_message (MP mp) ;
22798
22799
22800 @c void mp_do_message (MP mp) {
22801   int m; /* the type of message */
22802   m=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
22803   if ( mp->cur_type!=mp_string_type )
22804     mp_no_string_err(mp, "A message should be a known string expression.");
22805   else {
22806     switch (m) {
22807     case message_code: 
22808       mp_print_nl(mp, ""); mp_print_str(mp, mp->cur_exp);
22809       break;
22810     case err_message_code:
22811       @<Print string |cur_exp| as an error message@>;
22812       break;
22813     case err_help_code:
22814       @<Save string |cur_exp| as the |err_help|@>;
22815       break;
22816     case filename_template_code:
22817       @<Save the filename template@>;
22818       break;
22819     } /* there are no other cases */
22820   }
22821   mp_flush_cur_exp(mp, 0);
22822 }
22823
22824 @ @<Declare a procedure called |no_string_err|@>=
22825 void mp_no_string_err (MP mp,char *s) { 
22826    exp_err("Not a string");
22827 @.Not a string@>
22828   help1(s);
22829   mp_put_get_error(mp);
22830 }
22831
22832 @ The global variable |err_help| is zero when the user has most recently
22833 given an empty help string, or if none has ever been given.
22834
22835 @<Save string |cur_exp| as the |err_help|@>=
22836
22837   if ( mp->err_help!=0 ) delete_str_ref(mp->err_help);
22838   if ( length(mp->cur_exp)==0 ) mp->err_help=0;
22839   else  { mp->err_help=mp->cur_exp; add_str_ref(mp->err_help); }
22840 }
22841
22842 @ If \&{errmessage} occurs often in |mp_scroll_mode|, without user-defined
22843 \&{errhelp}, we don't want to give a long help message each time. So we
22844 give a verbose explanation only once.
22845
22846 @<Glob...@>=
22847 boolean long_help_seen; /* has the long \.{\\errmessage} help been used? */
22848
22849 @ @<Set init...@>=mp->long_help_seen=false;
22850
22851 @ @<Print string |cur_exp| as an error message@>=
22852
22853   print_err(""); mp_print_str(mp, mp->cur_exp);
22854   if ( mp->err_help!=0 ) {
22855     mp->use_err_help=true;
22856   } else if ( mp->long_help_seen ) { 
22857     help1("(That was another `errmessage'.)") ; 
22858   } else  { 
22859    if ( mp->interaction<mp_error_stop_mode ) mp->long_help_seen=true;
22860     help4("This error message was generated by an `errmessage'")
22861      ("command, so I can\'t give any explicit help.")
22862      ("Pretend that you're Miss Marple: Examine all clues,")
22863 @^Marple, Jane@>
22864      ("and deduce the truth by inspired guesses.");
22865   }
22866   mp_put_get_error(mp); mp->use_err_help=false;
22867 }
22868
22869 @ @<Cases of |do_statement|...@>=
22870 case write_command: mp_do_write(mp); break;
22871
22872 @ @<Declare action procedures for use by |do_statement|@>=
22873 void mp_do_write (MP mp) ;
22874
22875 @ @c void mp_do_write (MP mp) {
22876   str_number t; /* the line of text to be written */
22877   write_index n,n0; /* for searching |wr_fname| and |wr_file| arrays */
22878   int old_setting; /* for saving |selector| during output */
22879   mp_get_x_next(mp);
22880   mp_scan_expression(mp);
22881   if ( mp->cur_type!=mp_string_type ) {
22882     mp_no_string_err(mp, "The text to be written should be a known string expression");
22883   } else if ( mp->cur_cmd!=to_token ) { 
22884     print_err("Missing `to' clause");
22885     help1("A write command should end with `to <filename>'");
22886     mp_put_get_error(mp);
22887   } else { 
22888     t=mp->cur_exp; mp->cur_type=mp_vacuous;
22889     mp_get_x_next(mp);
22890     mp_scan_expression(mp);
22891     if ( mp->cur_type!=mp_string_type )
22892       mp_no_string_err(mp, "I can\'t write to that file name.  It isn't a known string");
22893     else {
22894       @<Write |t| to the file named by |cur_exp|@>;
22895     }
22896     delete_str_ref(t);
22897   }
22898   mp_flush_cur_exp(mp, 0);
22899 }
22900
22901 @ @<Write |t| to the file named by |cur_exp|@>=
22902
22903   @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if
22904     |cur_exp| must be inserted@>;
22905   if ( mp_str_vs_str(mp, t,mp->eof_line)==0 ) {
22906     @<Record the end of file on |wr_file[n]|@>;
22907   } else { 
22908     old_setting=mp->selector;
22909     mp->selector=n+write_file;
22910     mp_print_str(mp, t); mp_print_ln(mp);
22911     mp->selector = old_setting;
22912   }
22913 }
22914
22915 @ @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if...@>=
22916 {
22917   char *fn = str(mp->cur_exp);
22918   n=mp->write_files;
22919   n0=mp->write_files;
22920   while (mp_xstrcmp(fn,mp->wr_fname[n])!=0) { 
22921     if ( n==0 ) { /* bottom reached */
22922           if ( n0==mp->write_files ) {
22923         if ( mp->write_files<mp->max_write_files ) {
22924           incr(mp->write_files);
22925         } else {
22926           FILE **wr_file;
22927           char **wr_fname;
22928               write_index l,k;
22929           l = mp->max_write_files + (mp->max_write_files>>2);
22930           wr_file = xmalloc((l+1),sizeof(FILE *));
22931           wr_fname = xmalloc((l+1),sizeof(char *));
22932               for (k=0;k<=l;k++) {
22933             if (k<=mp->max_write_files) {
22934                   wr_file[k]=mp->wr_file[k]; 
22935               wr_fname[k]=mp->wr_fname[k];
22936             } else {
22937                   wr_file[k]=0; 
22938               wr_fname[k]=NULL;
22939             }
22940           }
22941               xfree(mp->wr_file); xfree(mp->wr_fname);
22942           mp->max_write_files = l;
22943           mp->wr_file = wr_file;
22944           mp->wr_fname = wr_fname;
22945         }
22946       }
22947       n=n0;
22948       mp_open_write_file(mp, fn ,n);
22949     } else { 
22950       decr(n);
22951           if ( mp->wr_fname[n]==NULL )  n0=n; 
22952     }
22953   }
22954 }
22955
22956 @ @<Record the end of file on |wr_file[n]|@>=
22957 { fclose(mp->wr_file[n]);
22958   xfree(mp->wr_fname[n]);
22959   mp->wr_fname[n]=NULL;
22960   if ( n==mp->write_files-1 ) mp->write_files=n;
22961 }
22962
22963
22964 @* \[42] Writing font metric data.
22965 \TeX\ gets its knowledge about fonts from font metric files, also called
22966 \.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
22967 but other programs know about them too. One of \MP's duties is to
22968 write \.{TFM} files so that the user's fonts can readily be
22969 applied to typesetting.
22970 @:TFM files}{\.{TFM} files@>
22971 @^font metric files@>
22972
22973 The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
22974 Since the number of bytes is always a multiple of~4, we could
22975 also regard the file as a sequence of 32-bit words, but \MP\ uses the
22976 byte interpretation. The format of \.{TFM} files was designed by
22977 Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
22978 @^Ramshaw, Lyle Harold@>
22979 of information in a compact but useful form.
22980
22981 @<Glob...@>=
22982 FILE * tfm_file; /* the font metric output goes here */
22983 char * metric_file_name; /* full name of the font metric file */
22984
22985 @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
22986 integers that give the lengths of the various subsequent portions
22987 of the file. These twelve integers are, in order:
22988 $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
22989 |lf|&length of the entire file, in words;\cr
22990 |lh|&length of the header data, in words;\cr
22991 |bc|&smallest character code in the font;\cr
22992 |ec|&largest character code in the font;\cr
22993 |nw|&number of words in the width table;\cr
22994 |nh|&number of words in the height table;\cr
22995 |nd|&number of words in the depth table;\cr
22996 |ni|&number of words in the italic correction table;\cr
22997 |nl|&number of words in the lig/kern table;\cr
22998 |nk|&number of words in the kern table;\cr
22999 |ne|&number of words in the extensible character table;\cr
23000 |np|&number of font parameter words.\cr}}$$
23001 They are all nonnegative and less than $2^{15}$. We must have |bc-1<=ec<=255|,
23002 |ne<=256|, and
23003 $$\hbox{|lf=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
23004 Note that a font may contain as many as 256 characters (if |bc=0| and |ec=255|),
23005 and as few as 0 characters (if |bc=ec+1|).
23006
23007 Incidentally, when two or more 8-bit bytes are combined to form an integer of
23008 16 or more bits, the most significant bytes appear first in the file.
23009 This is called BigEndian order.
23010 @^BigEndian order@>
23011
23012 @ The rest of the \.{TFM} file may be regarded as a sequence of ten data
23013 arrays.
23014
23015 The most important data type used here is a |fix_word|, which is
23016 a 32-bit representation of a binary fraction. A |fix_word| is a signed
23017 quantity, with the two's complement of the entire word used to represent
23018 negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
23019 binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
23020 the smallest is $-2048$. We will see below, however, that all but two of
23021 the |fix_word| values must lie between $-16$ and $+16$.
23022
23023 @ The first data array is a block of header information, which contains
23024 general facts about the font. The header must contain at least two words,
23025 |header[0]| and |header[1]|, whose meaning is explained below.  Additional
23026 header information of use to other software routines might also be
23027 included, and \MP\ will generate it if the \.{headerbyte} command occurs.
23028 For example, 16 more words of header information are in use at the Xerox
23029 Palo Alto Research Center; the first ten specify the character coding
23030 scheme used (e.g., `\.{XEROX TEXT}' or `\.{TEX MATHSY}'), the next five
23031 give the font family name (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
23032 last gives the ``face byte.''
23033
23034 \yskip\hang|header[0]| is a 32-bit check sum that \MP\ will copy into
23035 the \.{GF} output file. This helps ensure consistency between files,
23036 since \TeX\ records the check sums from the \.{TFM}'s it reads, and these
23037 should match the check sums on actual fonts that are used.  The actual
23038 relation between this check sum and the rest of the \.{TFM} file is not
23039 important; the check sum is simply an identification number with the
23040 property that incompatible fonts almost always have distinct check sums.
23041 @^check sum@>
23042
23043 \yskip\hang|header[1]| is a |fix_word| containing the design size of the
23044 font, in units of \TeX\ points. This number must be at least 1.0; it is
23045 fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
23046 font, i.e., a font that was designed to look best at a 10-point size,
23047 whatever that really means. When a \TeX\ user asks for a font `\.{at}
23048 $\delta$ \.{pt}', the effect is to override the design size and replace it
23049 by $\delta$, and to multiply the $x$ and~$y$ coordinates of the points in
23050 the font image by a factor of $\delta$ divided by the design size.  {\sl
23051 All other dimensions in the\/ \.{TFM} file are |fix_word|\kern-1pt\
23052 numbers in design-size units.} Thus, for example, the value of |param[6]|,
23053 which defines the \.{em} unit, is often the |fix_word| value $2^{20}=1.0$,
23054 since many fonts have a design size equal to one em.  The other dimensions
23055 must be less than 16 design-size units in absolute value; thus,
23056 |header[1]| and |param[1]| are the only |fix_word| entries in the whole
23057 \.{TFM} file whose first byte might be something besides 0 or 255.
23058
23059 @ Next comes the |char_info| array, which contains one |char_info_word|
23060 per character. Each word in this part of the file contains six fields
23061 packed into four bytes as follows.
23062
23063 \yskip\hang first byte: |width_index| (8 bits)\par
23064 \hang second byte: |height_index| (4 bits) times 16, plus |depth_index|
23065   (4~bits)\par
23066 \hang third byte: |italic_index| (6 bits) times 4, plus |tag|
23067   (2~bits)\par
23068 \hang fourth byte: |remainder| (8 bits)\par
23069 \yskip\noindent
23070 The actual width of a character is \\{width}|[width_index]|, in design-size
23071 units; this is a device for compressing information, since many characters
23072 have the same width. Since it is quite common for many characters
23073 to have the same height, depth, or italic correction, the \.{TFM} format
23074 imposes a limit of 16 different heights, 16 different depths, and
23075 64 different italic corrections.
23076
23077 Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
23078 \\{italic}[0]=0$ should always hold, so that an index of zero implies a
23079 value of zero.  The |width_index| should never be zero unless the
23080 character does not exist in the font, since a character is valid if and
23081 only if it lies between |bc| and |ec| and has a nonzero |width_index|.
23082
23083 @ The |tag| field in a |char_info_word| has four values that explain how to
23084 interpret the |remainder| field.
23085
23086 \yskip\hang|tag=0| (|no_tag|) means that |remainder| is unused.\par
23087 \hang|tag=1| (|lig_tag|) means that this character has a ligature/kerning
23088 program starting at location |remainder| in the |lig_kern| array.\par
23089 \hang|tag=2| (|list_tag|) means that this character is part of a chain of
23090 characters of ascending sizes, and not the largest in the chain.  The
23091 |remainder| field gives the character code of the next larger character.\par
23092 \hang|tag=3| (|ext_tag|) means that this character code represents an
23093 extensible character, i.e., a character that is built up of smaller pieces
23094 so that it can be made arbitrarily large. The pieces are specified in
23095 |exten[remainder]|.\par
23096 \yskip\noindent
23097 Characters with |tag=2| and |tag=3| are treated as characters with |tag=0|
23098 unless they are used in special circumstances in math formulas. For example,
23099 \TeX's \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
23100 operation looks for both |list_tag| and |ext_tag|.
23101
23102 @d no_tag 0 /* vanilla character */
23103 @d lig_tag 1 /* character has a ligature/kerning program */
23104 @d list_tag 2 /* character has a successor in a charlist */
23105 @d ext_tag 3 /* character is extensible */
23106
23107 @ The |lig_kern| array contains instructions in a simple programming language
23108 that explains what to do for special letter pairs. Each word in this array is a
23109 |lig_kern_command| of four bytes.
23110
23111 \yskip\hang first byte: |skip_byte|, indicates that this is the final program
23112   step if the byte is 128 or more, otherwise the next step is obtained by
23113   skipping this number of intervening steps.\par
23114 \hang second byte: |next_char|, ``if |next_char| follows the current character,
23115   then perform the operation and stop, otherwise continue.''\par
23116 \hang third byte: |op_byte|, indicates a ligature step if less than~128,
23117   a kern step otherwise.\par
23118 \hang fourth byte: |remainder|.\par
23119 \yskip\noindent
23120 In a kern step, an
23121 additional space equal to |kern[256*(op_byte-128)+remainder]| is inserted
23122 between the current character and |next_char|. This amount is
23123 often negative, so that the characters are brought closer together
23124 by kerning; but it might be positive.
23125
23126 There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
23127 $0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
23128 |remainder| is inserted between the current character and |next_char|;
23129 then the current character is deleted if $b=0$, and |next_char| is
23130 deleted if $c=0$; then we pass over $a$~characters to reach the next
23131 current character (which may have a ligature/kerning program of its own).
23132
23133 If the very first instruction of the |lig_kern| array has |skip_byte=255|,
23134 the |next_char| byte is the so-called right boundary character of this font;
23135 the value of |next_char| need not lie between |bc| and~|ec|.
23136 If the very last instruction of the |lig_kern| array has |skip_byte=255|,
23137 there is a special ligature/kerning program for a left boundary character,
23138 beginning at location |256*op_byte+remainder|.
23139 The interpretation is that \TeX\ puts implicit boundary characters
23140 before and after each consecutive string of characters from the same font.
23141 These implicit characters do not appear in the output, but they can affect
23142 ligatures and kerning.
23143
23144 If the very first instruction of a character's |lig_kern| program has
23145 |skip_byte>128|, the program actually begins in location
23146 |256*op_byte+remainder|. This feature allows access to large |lig_kern|
23147 arrays, because the first instruction must otherwise
23148 appear in a location |<=255|.
23149
23150 Any instruction with |skip_byte>128| in the |lig_kern| array must satisfy
23151 the condition
23152 $$\hbox{|256*op_byte+remainder<nl|.}$$
23153 If such an instruction is encountered during
23154 normal program execution, it denotes an unconditional halt; no ligature
23155 command is performed.
23156
23157 @d stop_flag (128)
23158   /* value indicating `\.{STOP}' in a lig/kern program */
23159 @d kern_flag (128) /* op code for a kern step */
23160 @d skip_byte(A) mp->lig_kern[(A)].b0
23161 @d next_char(A) mp->lig_kern[(A)].b1
23162 @d op_byte(A) mp->lig_kern[(A)].b2
23163 @d rem_byte(A) mp->lig_kern[(A)].b3
23164
23165 @ Extensible characters are specified by an |extensible_recipe|, which
23166 consists of four bytes called |top|, |mid|, |bot|, and |rep| (in this
23167 order). These bytes are the character codes of individual pieces used to
23168 build up a large symbol.  If |top|, |mid|, or |bot| are zero, they are not
23169 present in the built-up result. For example, an extensible vertical line is
23170 like an extensible bracket, except that the top and bottom pieces are missing.
23171
23172 Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
23173 if the piece isn't present. Then the extensible characters have the form
23174 $TR^kMR^kB$ from top to bottom, for some |k>=0|, unless $M$ is absent;
23175 in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
23176 The width of the extensible character is the width of $R$; and the
23177 height-plus-depth is the sum of the individual height-plus-depths of the
23178 components used, since the pieces are butted together in a vertical list.
23179
23180 @d ext_top(A) mp->exten[(A)].b0 /* |top| piece in a recipe */
23181 @d ext_mid(A) mp->exten[(A)].b1 /* |mid| piece in a recipe */
23182 @d ext_bot(A) mp->exten[(A)].b2 /* |bot| piece in a recipe */
23183 @d ext_rep(A) mp->exten[(A)].b3 /* |rep| piece in a recipe */
23184
23185 @ The final portion of a \.{TFM} file is the |param| array, which is another
23186 sequence of |fix_word| values.
23187
23188 \yskip\hang|param[1]=slant| is the amount of italic slant, which is used
23189 to help position accents. For example, |slant=.25| means that when you go
23190 up one unit, you also go .25 units to the right. The |slant| is a pure
23191 number; it is the only |fix_word| other than the design size itself that is
23192 not scaled by the design size.
23193
23194 \hang|param[2]=space| is the normal spacing between words in text.
23195 Note that character 040 in the font need not have anything to do with
23196 blank spaces.
23197
23198 \hang|param[3]=space_stretch| is the amount of glue stretching between words.
23199
23200 \hang|param[4]=space_shrink| is the amount of glue shrinking between words.
23201
23202 \hang|param[5]=x_height| is the size of one ex in the font; it is also
23203 the height of letters for which accents don't have to be raised or lowered.
23204
23205 \hang|param[6]=quad| is the size of one em in the font.
23206
23207 \hang|param[7]=extra_space| is the amount added to |param[2]| at the
23208 ends of sentences.
23209
23210 \yskip\noindent
23211 If fewer than seven parameters are present, \TeX\ sets the missing parameters
23212 to zero.
23213
23214 @d slant_code 1
23215 @d space_code 2
23216 @d space_stretch_code 3
23217 @d space_shrink_code 4
23218 @d x_height_code 5
23219 @d quad_code 6
23220 @d extra_space_code 7
23221
23222 @ So that is what \.{TFM} files hold. One of \MP's duties is to output such
23223 information, and it does this all at once at the end of a job.
23224 In order to prepare for such frenetic activity, it squirrels away the
23225 necessary facts in various arrays as information becomes available.
23226
23227 Character dimensions (\&{charwd}, \&{charht}, \&{chardp}, and \&{charic})
23228 are stored respectively in |tfm_width|, |tfm_height|, |tfm_depth|, and
23229 |tfm_ital_corr|. Other information about a character (e.g., about
23230 its ligatures or successors) is accessible via the |char_tag| and
23231 |char_remainder| arrays. Other information about the font as a whole
23232 is kept in additional arrays called |header_byte|, |lig_kern|,
23233 |kern|, |exten|, and |param|.
23234
23235 @d max_tfm_int 32510
23236 @d undefined_label max_tfm_int /* an undefined local label */
23237
23238 @<Glob...@>=
23239 #define TFM_ITEMS 257
23240 eight_bits bc;
23241 eight_bits ec; /* smallest and largest character codes shipped out */
23242 scaled tfm_width[TFM_ITEMS]; /* \&{charwd} values */
23243 scaled tfm_height[TFM_ITEMS]; /* \&{charht} values */
23244 scaled tfm_depth[TFM_ITEMS]; /* \&{chardp} values */
23245 scaled tfm_ital_corr[TFM_ITEMS]; /* \&{charic} values */
23246 boolean char_exists[TFM_ITEMS]; /* has this code been shipped out? */
23247 int char_tag[TFM_ITEMS]; /* |remainder| category */
23248 int char_remainder[TFM_ITEMS]; /* the |remainder| byte */
23249 char *header_byte; /* bytes of the \.{TFM} header */
23250 int header_last; /* last initialized \.{TFM} header byte */
23251 int header_size; /* size of the \.{TFM} header */
23252 four_quarters *lig_kern; /* the ligature/kern table */
23253 short nl; /* the number of ligature/kern steps so far */
23254 scaled *kern; /* distinct kerning amounts */
23255 short nk; /* the number of distinct kerns so far */
23256 four_quarters exten[TFM_ITEMS]; /* extensible character recipes */
23257 short ne; /* the number of extensible characters so far */
23258 scaled *param; /* \&{fontinfo} parameters */
23259 short np; /* the largest \&{fontinfo} parameter specified so far */
23260 short nw;short nh;short nd;short ni; /* sizes of \.{TFM} subtables */
23261 short skip_table[TFM_ITEMS]; /* local label status */
23262 boolean lk_started; /* has there been a lig/kern step in this command yet? */
23263 integer bchar; /* right boundary character */
23264 short bch_label; /* left boundary starting location */
23265 short ll;short lll; /* registers used for lig/kern processing */
23266 short label_loc[257]; /* lig/kern starting addresses */
23267 eight_bits label_char[257]; /* characters for |label_loc| */
23268 short label_ptr; /* highest position occupied in |label_loc| */
23269
23270 @ @<Allocate or initialize ...@>=
23271 mp->header_last = 0; mp->header_size = 128; /* just for init */
23272 mp->header_byte = xmalloc(mp->header_size, sizeof(char));
23273 mp->lig_kern = NULL; /* allocated when needed */
23274 mp->kern = NULL; /* allocated when needed */ 
23275 mp->param = NULL; /* allocated when needed */
23276
23277 @ @<Dealloc variables@>=
23278 xfree(mp->header_byte);
23279 xfree(mp->lig_kern);
23280 xfree(mp->kern);
23281 xfree(mp->param);
23282
23283 @ @<Set init...@>=
23284 for (k=0;k<= 255;k++ ) {
23285   mp->tfm_width[k]=0; mp->tfm_height[k]=0; mp->tfm_depth[k]=0; mp->tfm_ital_corr[k]=0;
23286   mp->char_exists[k]=false; mp->char_tag[k]=no_tag; mp->char_remainder[k]=0;
23287   mp->skip_table[k]=undefined_label;
23288 };
23289 memset(mp->header_byte,0,mp->header_size);
23290 mp->bc=255; mp->ec=0; mp->nl=0; mp->nk=0; mp->ne=0; mp->np=0;
23291 mp->internal[boundary_char]=-unity;
23292 mp->bch_label=undefined_label;
23293 mp->label_loc[0]=-1; mp->label_ptr=0;
23294
23295 @ @<Declarations@>=
23296 scaled mp_tfm_check (MP mp,small_number m) ;
23297
23298 @ @<Declare the function called |tfm_check|@>=
23299 scaled mp_tfm_check (MP mp,small_number m) {
23300   if ( abs(mp->internal[m])>=fraction_half ) {
23301     print_err("Enormous "); mp_print(mp, mp->int_name[m]);
23302 @.Enormous charwd...@>
23303 @.Enormous chardp...@>
23304 @.Enormous charht...@>
23305 @.Enormous charic...@>
23306 @.Enormous designsize...@>
23307     mp_print(mp, " has been reduced");
23308     help1("Font metric dimensions must be less than 2048pt.");
23309     mp_put_get_error(mp);
23310     if ( mp->internal[m]>0 ) return (fraction_half-1);
23311     else return (1-fraction_half);
23312   } else {
23313     return mp->internal[m];
23314   }
23315 }
23316
23317 @ @<Store the width information for character code~|c|@>=
23318 if ( c<mp->bc ) mp->bc=c;
23319 if ( c>mp->ec ) mp->ec=c;
23320 mp->char_exists[c]=true;
23321 mp->tfm_width[c]=mp_tfm_check(mp, char_wd);
23322 mp->tfm_height[c]=mp_tfm_check(mp, char_ht);
23323 mp->tfm_depth[c]=mp_tfm_check(mp, char_dp);
23324 mp->tfm_ital_corr[c]=mp_tfm_check(mp, char_ic)
23325
23326 @ Now let's consider \MP's special \.{TFM}-oriented commands.
23327
23328 @<Cases of |do_statement|...@>=
23329 case tfm_command: mp_do_tfm_command(mp); break;
23330
23331 @ @d char_list_code 0
23332 @d lig_table_code 1
23333 @d extensible_code 2
23334 @d header_byte_code 3
23335 @d font_dimen_code 4
23336
23337 @<Put each...@>=
23338 mp_primitive(mp, "charlist",tfm_command,char_list_code);
23339 @:char_list_}{\&{charlist} primitive@>
23340 mp_primitive(mp, "ligtable",tfm_command,lig_table_code);
23341 @:lig_table_}{\&{ligtable} primitive@>
23342 mp_primitive(mp, "extensible",tfm_command,extensible_code);
23343 @:extensible_}{\&{extensible} primitive@>
23344 mp_primitive(mp, "headerbyte",tfm_command,header_byte_code);
23345 @:header_byte_}{\&{headerbyte} primitive@>
23346 mp_primitive(mp, "fontdimen",tfm_command,font_dimen_code);
23347 @:font_dimen_}{\&{fontdimen} primitive@>
23348
23349 @ @<Cases of |print_cmd...@>=
23350 case tfm_command: 
23351   switch (m) {
23352   case char_list_code:mp_print(mp, "charlist"); break;
23353   case lig_table_code:mp_print(mp, "ligtable"); break;
23354   case extensible_code:mp_print(mp, "extensible"); break;
23355   case header_byte_code:mp_print(mp, "headerbyte"); break;
23356   default: mp_print(mp, "fontdimen"); break;
23357   }
23358   break;
23359
23360 @ @<Declare action procedures for use by |do_statement|@>=
23361 eight_bits mp_get_code (MP mp) ;
23362
23363 @ @c eight_bits mp_get_code (MP mp) { /* scans a character code value */
23364   integer c; /* the code value found */
23365   mp_get_x_next(mp); mp_scan_expression(mp);
23366   if ( mp->cur_type==mp_known ) { 
23367     c=mp_round_unscaled(mp, mp->cur_exp);
23368     if ( c>=0 ) if ( c<256 ) return c;
23369   } else if ( mp->cur_type==mp_string_type ) {
23370     if ( length(mp->cur_exp)==1 )  { 
23371       c=mp->str_pool[mp->str_start[mp->cur_exp]];
23372       return c;
23373     }
23374   }
23375   exp_err("Invalid code has been replaced by 0");
23376 @.Invalid code...@>
23377   help2("I was looking for a number between 0 and 255, or for a")
23378        ("string of length 1. Didn't find it; will use 0 instead.");
23379   mp_put_get_flush_error(mp, 0); c=0;
23380   return c;
23381 };
23382
23383 @ @<Declare action procedures for use by |do_statement|@>=
23384 void mp_set_tag (MP mp,halfword c, small_number t, halfword r) ;
23385
23386 @ @c void mp_set_tag (MP mp,halfword c, small_number t, halfword r) { 
23387   if ( mp->char_tag[c]==no_tag ) {
23388     mp->char_tag[c]=t; mp->char_remainder[c]=r;
23389     if ( t==lig_tag ){ 
23390       incr(mp->label_ptr); mp->label_loc[mp->label_ptr]=r; 
23391       mp->label_char[mp->label_ptr]=c;
23392     }
23393   } else {
23394     @<Complain about a character tag conflict@>;
23395   }
23396 }
23397
23398 @ @<Complain about a character tag conflict@>=
23399
23400   print_err("Character ");
23401   if ( (c>' ')&&(c<127) ) mp_print_char(mp,c);
23402   else if ( c==256 ) mp_print(mp, "||");
23403   else  { mp_print(mp, "code "); mp_print_int(mp, c); };
23404   mp_print(mp, " is already ");
23405 @.Character c is already...@>
23406   switch (mp->char_tag[c]) {
23407   case lig_tag: mp_print(mp, "in a ligtable"); break;
23408   case list_tag: mp_print(mp, "in a charlist"); break;
23409   case ext_tag: mp_print(mp, "extensible"); break;
23410   } /* there are no other cases */
23411   help2("It's not legal to label a character more than once.")
23412     ("So I'll not change anything just now.");
23413   mp_put_get_error(mp); 
23414 }
23415
23416 @ @<Declare action procedures for use by |do_statement|@>=
23417 void mp_do_tfm_command (MP mp) ;
23418
23419 @ @c void mp_do_tfm_command (MP mp) {
23420   int c,cc; /* character codes */
23421   int k; /* index into the |kern| array */
23422   int j; /* index into |header_byte| or |param| */
23423   switch (mp->cur_mod) {
23424   case char_list_code: 
23425     c=mp_get_code(mp);
23426      /* we will store a list of character successors */
23427     while ( mp->cur_cmd==colon )   { 
23428       cc=mp_get_code(mp); mp_set_tag(mp, c,list_tag,cc); c=cc;
23429     };
23430     break;
23431   case lig_table_code: 
23432     if (mp->lig_kern==NULL) 
23433        mp->lig_kern = xmalloc((max_tfm_int+1),sizeof(four_quarters));
23434     if (mp->kern==NULL) 
23435        mp->kern = xmalloc((max_tfm_int+1),sizeof(scaled));
23436     @<Store a list of ligature/kern steps@>;
23437     break;
23438   case extensible_code: 
23439     @<Define an extensible recipe@>;
23440     break;
23441   case header_byte_code: 
23442   case font_dimen_code: 
23443     c=mp->cur_mod; mp_get_x_next(mp);
23444     mp_scan_expression(mp);
23445     if ( (mp->cur_type!=mp_known)||(mp->cur_exp<half_unit) ) {
23446       exp_err("Improper location");
23447 @.Improper location@>
23448       help2("I was looking for a known, positive number.")
23449        ("For safety's sake I'll ignore the present command.");
23450       mp_put_get_error(mp);
23451     } else  { 
23452       j=mp_round_unscaled(mp, mp->cur_exp);
23453       if ( mp->cur_cmd!=colon ) {
23454         mp_missing_err(mp, ":");
23455 @.Missing `:'@>
23456         help1("A colon should follow a headerbyte or fontinfo location.");
23457         mp_back_error(mp);
23458       }
23459       if ( c==header_byte_code ) { 
23460         @<Store a list of header bytes@>;
23461       } else {     
23462         if (mp->param==NULL) 
23463           mp->param = xmalloc((max_tfm_int+1),sizeof(scaled));
23464         @<Store a list of font dimensions@>;
23465       }
23466     }
23467     break;
23468   } /* there are no other cases */
23469 };
23470
23471 @ @<Store a list of ligature/kern steps@>=
23472
23473   mp->lk_started=false;
23474 CONTINUE: 
23475   mp_get_x_next(mp);
23476   if ((mp->cur_cmd==skip_to)&& mp->lk_started )
23477     @<Process a |skip_to| command and |goto done|@>;
23478   if ( mp->cur_cmd==bchar_label ) { c=256; mp->cur_cmd=colon; }
23479   else { mp_back_input(mp); c=mp_get_code(mp); };
23480   if ((mp->cur_cmd==colon)||(mp->cur_cmd==double_colon)) {
23481     @<Record a label in a lig/kern subprogram and |goto continue|@>;
23482   }
23483   if ( mp->cur_cmd==lig_kern_token ) { 
23484     @<Compile a ligature/kern command@>; 
23485   } else  { 
23486     print_err("Illegal ligtable step");
23487 @.Illegal ligtable step@>
23488     help1("I was looking for `=:' or `kern' here.");
23489     mp_back_error(mp); next_char(mp->nl)=qi(0); 
23490     op_byte(mp->nl)=qi(0); rem_byte(mp->nl)=qi(0);
23491     skip_byte(mp->nl)=stop_flag+1; /* this specifies an unconditional stop */
23492   }
23493   if ( mp->nl==max_tfm_int) mp_fatal_error(mp, "ligtable too large");
23494   incr(mp->nl);
23495   if ( mp->cur_cmd==comma ) goto CONTINUE;
23496   if ( skip_byte(mp->nl-1)<stop_flag ) skip_byte(mp->nl-1)=stop_flag;
23497 }
23498 DONE:
23499
23500 @ @<Put each...@>=
23501 mp_primitive(mp, "=:",lig_kern_token,0);
23502 @:=:_}{\.{=:} primitive@>
23503 mp_primitive(mp, "=:|",lig_kern_token,1);
23504 @:=:/_}{\.{=:\char'174} primitive@>
23505 mp_primitive(mp, "=:|>",lig_kern_token,5);
23506 @:=:/>_}{\.{=:\char'174>} primitive@>
23507 mp_primitive(mp, "|=:",lig_kern_token,2);
23508 @:=:/_}{\.{\char'174=:} primitive@>
23509 mp_primitive(mp, "|=:>",lig_kern_token,6);
23510 @:=:/>_}{\.{\char'174=:>} primitive@>
23511 mp_primitive(mp, "|=:|",lig_kern_token,3);
23512 @:=:/_}{\.{\char'174=:\char'174} primitive@>
23513 mp_primitive(mp, "|=:|>",lig_kern_token,7);
23514 @:=:/>_}{\.{\char'174=:\char'174>} primitive@>
23515 mp_primitive(mp, "|=:|>>",lig_kern_token,11);
23516 @:=:/>_}{\.{\char'174=:\char'174>>} primitive@>
23517 mp_primitive(mp, "kern",lig_kern_token,128);
23518 @:kern_}{\&{kern} primitive@>
23519
23520 @ @<Cases of |print_cmd...@>=
23521 case lig_kern_token: 
23522   switch (m) {
23523   case 0:mp_print(mp, "=:"); break;
23524   case 1:mp_print(mp, "=:|"); break;
23525   case 2:mp_print(mp, "|=:"); break;
23526   case 3:mp_print(mp, "|=:|"); break;
23527   case 5:mp_print(mp, "=:|>"); break;
23528   case 6:mp_print(mp, "|=:>"); break;
23529   case 7:mp_print(mp, "|=:|>"); break;
23530   case 11:mp_print(mp, "|=:|>>"); break;
23531   default: mp_print(mp, "kern"); break;
23532   }
23533   break;
23534
23535 @ Local labels are implemented by maintaining the |skip_table| array,
23536 where |skip_table[c]| is either |undefined_label| or the address of the
23537 most recent lig/kern instruction that skips to local label~|c|. In the
23538 latter case, the |skip_byte| in that instruction will (temporarily)
23539 be zero if there were no prior skips to this label, or it will be the
23540 distance to the prior skip.
23541
23542 We may need to cancel skips that span more than 127 lig/kern steps.
23543
23544 @d cancel_skips(A) mp->ll=(A);
23545   do {  
23546     mp->lll=qo(skip_byte(mp->ll)); 
23547     skip_byte(mp->ll)=stop_flag; mp->ll=mp->ll-mp->lll;
23548   } while (mp->lll!=0)
23549 @d skip_error(A) { print_err("Too far to skip");
23550 @.Too far to skip@>
23551   help1("At most 127 lig/kern steps can separate skipto1 from 1::.");
23552   mp_error(mp); cancel_skips((A));
23553   }
23554
23555 @<Process a |skip_to| command and |goto done|@>=
23556
23557   c=mp_get_code(mp);
23558   if ( mp->nl-mp->skip_table[c]>128 ) { /* |skip_table[c]<<nl<=undefined_label| */
23559     skip_error(mp->skip_table[c]); mp->skip_table[c]=undefined_label;
23560   }
23561   if ( mp->skip_table[c]==undefined_label ) skip_byte(mp->nl-1)=qi(0);
23562   else skip_byte(mp->nl-1)=qi(mp->nl-mp->skip_table[c]-1);
23563   mp->skip_table[c]=mp->nl-1; goto DONE;
23564 }
23565
23566 @ @<Record a label in a lig/kern subprogram and |goto continue|@>=
23567
23568   if ( mp->cur_cmd==colon ) {
23569     if ( c==256 ) mp->bch_label=mp->nl;
23570     else mp_set_tag(mp, c,lig_tag,mp->nl);
23571   } else if ( mp->skip_table[c]<undefined_label ) {
23572     mp->ll=mp->skip_table[c]; mp->skip_table[c]=undefined_label;
23573     do {  
23574       mp->lll=qo(skip_byte(mp->ll));
23575       if ( mp->nl-mp->ll>128 ) {
23576         skip_error(mp->ll); goto CONTINUE;
23577       }
23578       skip_byte(mp->ll)=qi(mp->nl-mp->ll-1); mp->ll=mp->ll-mp->lll;
23579     } while (mp->lll!=0);
23580   }
23581   goto CONTINUE;
23582 }
23583
23584 @ @<Compile a ligature/kern...@>=
23585
23586   next_char(mp->nl)=qi(c); skip_byte(mp->nl)=qi(0);
23587   if ( mp->cur_mod<128 ) { /* ligature op */
23588     op_byte(mp->nl)=qi(mp->cur_mod); rem_byte(mp->nl)=qi(mp_get_code(mp));
23589   } else { 
23590     mp_get_x_next(mp); mp_scan_expression(mp);
23591     if ( mp->cur_type!=mp_known ) {
23592       exp_err("Improper kern");
23593 @.Improper kern@>
23594       help2("The amount of kern should be a known numeric value.")
23595         ("I'm zeroing this one. Proceed, with fingers crossed.");
23596       mp_put_get_flush_error(mp, 0);
23597     }
23598     mp->kern[mp->nk]=mp->cur_exp;
23599     k=0; 
23600     while ( mp->kern[k]!=mp->cur_exp ) incr(k);
23601     if ( k==mp->nk ) {
23602       if ( mp->nk==max_tfm_int ) mp_fatal_error(mp, "too many TFM kerns");
23603       incr(mp->nk);
23604     }
23605     op_byte(mp->nl)=kern_flag+(k / 256);
23606     rem_byte(mp->nl)=qi((k % 256));
23607   }
23608   mp->lk_started=true;
23609 }
23610
23611 @ @d missing_extensible_punctuation(A) 
23612   { mp_missing_err(mp, (A));
23613 @.Missing `\char`\#'@>
23614   help1("I'm processing `extensible c: t,m,b,r'."); mp_back_error(mp);
23615   }
23616
23617 @<Define an extensible recipe@>=
23618
23619   if ( mp->ne==256 ) mp_fatal_error(mp, "too many extensible recipies");
23620   c=mp_get_code(mp); mp_set_tag(mp, c,ext_tag,mp->ne);
23621   if ( mp->cur_cmd!=colon ) missing_extensible_punctuation(":");
23622   ext_top(mp->ne)=qi(mp_get_code(mp));
23623   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23624   ext_mid(mp->ne)=qi(mp_get_code(mp));
23625   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23626   ext_bot(mp->ne)=qi(mp_get_code(mp));
23627   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23628   ext_rep(mp->ne)=qi(mp_get_code(mp));
23629   incr(mp->ne);
23630 }
23631
23632 @ The header could contain ASCII zeroes, so can't use |strdup|.
23633
23634 @<Store a list of header bytes@>=
23635 do {  
23636   if ( j>=mp->header_size ) {
23637     int l = mp->header_size + (mp->header_size >> 2);
23638     char *t = xmalloc(l,sizeof(char));
23639     memset(t,0,l); 
23640     memcpy(t,mp->header_byte,mp->header_size);
23641     xfree (mp->header_byte);
23642     mp->header_byte = t;
23643     mp->header_size = l;
23644   }
23645   mp->header_byte[j]=mp_get_code(mp); 
23646   incr(j); incr(mp->header_last);
23647 } while (mp->cur_cmd==comma)
23648
23649 @ @<Store a list of font dimensions@>=
23650 do {  
23651   if ( j>max_tfm_int ) mp_fatal_error(mp, "too many fontdimens");
23652   while ( j>mp->np ) { incr(mp->np); mp->param[mp->np]=0; };
23653   mp_get_x_next(mp); mp_scan_expression(mp);
23654   if ( mp->cur_type!=mp_known ){ 
23655     exp_err("Improper font parameter");
23656 @.Improper font parameter@>
23657     help1("I'm zeroing this one. Proceed, with fingers crossed.");
23658     mp_put_get_flush_error(mp, 0);
23659   }
23660   mp->param[j]=mp->cur_exp; incr(j);
23661 } while (mp->cur_cmd==comma)
23662
23663 @ OK: We've stored all the data that is needed for the \.{TFM} file.
23664 All that remains is to output it in the correct format.
23665
23666 An interesting problem needs to be solved in this connection, because
23667 the \.{TFM} format allows at most 256~widths, 16~heights, 16~depths,
23668 and 64~italic corrections. If the data has more distinct values than
23669 this, we want to meet the necessary restrictions by perturbing the
23670 given values as little as possible.
23671
23672 \MP\ solves this problem in two steps. First the values of a given
23673 kind (widths, heights, depths, or italic corrections) are sorted;
23674 then the list of sorted values is perturbed, if necessary.
23675
23676 The sorting operation is facilitated by having a special node of
23677 essentially infinite |value| at the end of the current list.
23678
23679 @<Initialize table entries...@>=
23680 value(inf_val)=fraction_four;
23681
23682 @ Straight linear insertion is good enough for sorting, since the lists
23683 are usually not terribly long. As we work on the data, the current list
23684 will start at |link(temp_head)| and end at |inf_val|; the nodes in this
23685 list will be in increasing order of their |value| fields.
23686
23687 Given such a list, the |sort_in| function takes a value and returns a pointer
23688 to where that value can be found in the list. The value is inserted in
23689 the proper place, if necessary.
23690
23691 At the time we need to do these operations, most of \MP's work has been
23692 completed, so we will have plenty of memory to play with. The value nodes
23693 that are allocated for sorting will never be returned to free storage.
23694
23695 @d clear_the_list link(temp_head)=inf_val
23696
23697 @c pointer mp_sort_in (MP mp,scaled v) {
23698   pointer p,q,r; /* list manipulation registers */
23699   p=temp_head;
23700   while (1) { 
23701     q=link(p);
23702     if ( v<=value(q) ) break;
23703     p=q;
23704   }
23705   if ( v<value(q) ) {
23706     r=mp_get_node(mp, value_node_size); value(r)=v; link(r)=q; link(p)=r;
23707   }
23708   return link(p);
23709 }
23710
23711 @ Now we come to the interesting part, where we reduce the list if necessary
23712 until it has the required size. The |min_cover| routine is basic to this
23713 process; it computes the minimum number~|m| such that the values of the
23714 current sorted list can be covered by |m|~intervals of width~|d|. It
23715 also sets the global value |perturbation| to the smallest value $d'>d$
23716 such that the covering found by this algorithm would be different.
23717
23718 In particular, |min_cover(0)| returns the number of distinct values in the
23719 current list and sets |perturbation| to the minimum distance between
23720 adjacent values.
23721
23722 @c integer mp_min_cover (MP mp,scaled d) {
23723   pointer p; /* runs through the current list */
23724   scaled l; /* the least element covered by the current interval */
23725   integer m; /* lower bound on the size of the minimum cover */
23726   m=0; p=link(temp_head); mp->perturbation=el_gordo;
23727   while ( p!=inf_val ){ 
23728     incr(m); l=value(p);
23729     do {  p=link(p); } while (value(p)<=l+d);
23730     if ( value(p)-l<mp->perturbation ) 
23731       mp->perturbation=value(p)-l;
23732   }
23733   return m;
23734 }
23735
23736 @ @<Glob...@>=
23737 scaled perturbation; /* quantity related to \.{TFM} rounding */
23738 integer excess; /* the list is this much too long */
23739
23740 @ The smallest |d| such that a given list can be covered with |m| intervals
23741 is determined by the |threshold| routine, which is sort of an inverse
23742 to |min_cover|. The idea is to increase the interval size rapidly until
23743 finding the range, then to go sequentially until the exact borderline has
23744 been discovered.
23745
23746 @c scaled mp_threshold (MP mp,integer m) {
23747   scaled d; /* lower bound on the smallest interval size */
23748   mp->excess=mp_min_cover(mp, 0)-m;
23749   if ( mp->excess<=0 ) {
23750     return 0;
23751   } else  { 
23752     do {  
23753       d=mp->perturbation;
23754     } while (mp_min_cover(mp, d+d)>m);
23755     while ( mp_min_cover(mp, d)>m ) 
23756       d=mp->perturbation;
23757     return d;
23758   }
23759 }
23760
23761 @ The |skimp| procedure reduces the current list to at most |m| entries,
23762 by changing values if necessary. It also sets |info(p):=k| if |value(p)|
23763 is the |k|th distinct value on the resulting list, and it sets
23764 |perturbation| to the maximum amount by which a |value| field has
23765 been changed. The size of the resulting list is returned as the
23766 value of |skimp|.
23767
23768 @c integer mp_skimp (MP mp,integer m) {
23769   scaled d; /* the size of intervals being coalesced */
23770   pointer p,q,r; /* list manipulation registers */
23771   scaled l; /* the least value in the current interval */
23772   scaled v; /* a compromise value */
23773   d=mp_threshold(mp, m); mp->perturbation=0;
23774   q=temp_head; m=0; p=link(temp_head);
23775   while ( p!=inf_val ) {
23776     incr(m); l=value(p); info(p)=m;
23777     if ( value(link(p))<=l+d ) {
23778       @<Replace an interval of values by its midpoint@>;
23779     }
23780     q=p; p=link(p);
23781   }
23782   return m;
23783 }
23784
23785 @ @<Replace an interval...@>=
23786
23787   do {  
23788     p=link(p); info(p)=m;
23789     decr(mp->excess); if ( mp->excess==0 ) d=0;
23790   } while (value(link(p))<=l+d);
23791   v=l+halfp(value(p)-l);
23792   if ( value(p)-v>mp->perturbation ) 
23793     mp->perturbation=value(p)-v;
23794   r=q;
23795   do {  
23796     r=link(r); value(r)=v;
23797   } while (r!=p);
23798   link(q)=p; /* remove duplicate values from the current list */
23799 }
23800
23801 @ A warning message is issued whenever something is perturbed by
23802 more than 1/16\thinspace pt.
23803
23804 @c void mp_tfm_warning (MP mp,small_number m) { 
23805   mp_print_nl(mp, "(some "); 
23806   mp_print(mp, mp->int_name[m]);
23807 @.some charwds...@>
23808 @.some chardps...@>
23809 @.some charhts...@>
23810 @.some charics...@>
23811   mp_print(mp, " values had to be adjusted by as much as ");
23812   mp_print_scaled(mp, mp->perturbation); mp_print(mp, "pt)");
23813 }
23814
23815 @ Here's an example of how we use these routines.
23816 The width data needs to be perturbed only if there are 256 distinct
23817 widths, but \MP\ must check for this case even though it is
23818 highly unusual.
23819
23820 An integer variable |k| will be defined when we use this code.
23821 The |dimen_head| array will contain pointers to the sorted
23822 lists of dimensions.
23823
23824 @<Massage the \.{TFM} widths@>=
23825 clear_the_list;
23826 for (k=mp->bc;k<=mp->ec;k++)  {
23827   if ( mp->char_exists[k] )
23828     mp->tfm_width[k]=mp_sort_in(mp, mp->tfm_width[k]);
23829 }
23830 mp->nw=mp_skimp(mp, 255)+1; mp->dimen_head[1]=link(temp_head);
23831 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, char_wd)
23832
23833 @ @<Glob...@>=
23834 pointer dimen_head[5]; /* lists of \.{TFM} dimensions */
23835
23836 @ Heights, depths, and italic corrections are different from widths
23837 not only because their list length is more severely restricted, but
23838 also because zero values do not need to be put into the lists.
23839
23840 @<Massage the \.{TFM} heights, depths, and italic corrections@>=
23841 clear_the_list;
23842 for (k=mp->bc;k<=mp->ec;k++) {
23843   if ( mp->char_exists[k] ) {
23844     if ( mp->tfm_height[k]==0 ) mp->tfm_height[k]=zero_val;
23845     else mp->tfm_height[k]=mp_sort_in(mp, mp->tfm_height[k]);
23846   }
23847 }
23848 mp->nh=mp_skimp(mp, 15)+1; mp->dimen_head[2]=link(temp_head);
23849 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, char_ht);
23850 clear_the_list;
23851 for (k=mp->bc;k<=mp->ec;k++) {
23852   if ( mp->char_exists[k] ) {
23853     if ( mp->tfm_depth[k]==0 ) mp->tfm_depth[k]=zero_val;
23854     else mp->tfm_depth[k]=mp_sort_in(mp, mp->tfm_depth[k]);
23855   }
23856 }
23857 mp->nd=mp_skimp(mp, 15)+1; mp->dimen_head[3]=link(temp_head);
23858 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, char_dp);
23859 clear_the_list;
23860 for (k=mp->bc;k<=mp->ec;k++) {
23861   if ( mp->char_exists[k] ) {
23862     if ( mp->tfm_ital_corr[k]==0 ) mp->tfm_ital_corr[k]=zero_val;
23863     else mp->tfm_ital_corr[k]=mp_sort_in(mp, mp->tfm_ital_corr[k]);
23864   }
23865 }
23866 mp->ni=mp_skimp(mp, 63)+1; mp->dimen_head[4]=link(temp_head);
23867 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, char_ic)
23868
23869 @ @<Initialize table entries...@>=
23870 value(zero_val)=0; info(zero_val)=0;
23871
23872 @ Bytes 5--8 of the header are set to the design size, unless the user has
23873 some crazy reason for specifying them differently.
23874
23875 Error messages are not allowed at the time this procedure is called,
23876 so a warning is printed instead.
23877
23878 The value of |max_tfm_dimen| is calculated so that
23879 $$\hbox{|make_scaled(16*max_tfm_dimen,internal[design_size])|}
23880  < \\{three\_bytes}.$$
23881
23882 @d three_bytes 0100000000 /* $2^{24}$ */
23883
23884 @c 
23885 void mp_fix_design_size (MP mp) {
23886   scaled d; /* the design size */
23887   d=mp->internal[design_size];
23888   if ( (d<unity)||(d>=fraction_half) ) {
23889     if ( d!=0 )
23890       mp_print_nl(mp, "(illegal design size has been changed to 128pt)");
23891 @.illegal design size...@>
23892     d=040000000; mp->internal[design_size]=d;
23893   }
23894   if ( mp->header_byte[4]<0 ) if ( mp->header_byte[5]<0 )
23895     if ( mp->header_byte[6]<0 ) if ( mp->header_byte[7]<0 ) {
23896      mp->header_byte[4]=d / 04000000;
23897      mp->header_byte[5]=(d / 4096) % 256;
23898      mp->header_byte[6]=(d / 16) % 256;
23899      mp->header_byte[7]=(d % 16)*16;
23900   };
23901   mp->max_tfm_dimen=16*mp->internal[design_size]-mp->internal[design_size] / 010000000;
23902   if ( mp->max_tfm_dimen>=fraction_half ) mp->max_tfm_dimen=fraction_half-1;
23903 }
23904
23905 @ The |dimen_out| procedure computes a |fix_word| relative to the
23906 design size. If the data was out of range, it is corrected and the
23907 global variable |tfm_changed| is increased by~one.
23908
23909 @c integer mp_dimen_out (MP mp,scaled x) { 
23910   if ( abs(x)>mp->max_tfm_dimen ) {
23911     incr(mp->tfm_changed);
23912     if ( x>0 ) x=three_bytes-1; else x=1-three_bytes;
23913   } else {
23914     x=mp_make_scaled(mp, x*16,mp->internal[design_size]);
23915   }
23916   return x;
23917 }
23918
23919 @ @<Glob...@>=
23920 scaled max_tfm_dimen; /* bound on widths, heights, kerns, etc. */
23921 integer tfm_changed; /* the number of data entries that were out of bounds */
23922
23923 @ If the user has not specified any of the first four header bytes,
23924 the |fix_check_sum| procedure replaces them by a ``check sum'' computed
23925 from the |tfm_width| data relative to the design size.
23926 @^check sum@>
23927
23928 @c void mp_fix_check_sum (MP mp) {
23929   eight_bits k; /* runs through character codes */
23930   eight_bits B1,B2,B3,B4; /* bytes of the check sum */
23931   integer x;  /* hash value used in check sum computation */
23932   if ( mp->header_byte[0]==0 && mp->header_byte[1]==0 &&
23933        mp->header_byte[2]==0 && mp->header_byte[3]==0 ) {
23934     @<Compute a check sum in |(b1,b2,b3,b4)|@>;
23935     mp->header_byte[0]=B1; mp->header_byte[1]=B2;
23936     mp->header_byte[2]=B3; mp->header_byte[3]=B4; 
23937     return;
23938   }
23939 }
23940
23941 @ @<Compute a check sum in |(b1,b2,b3,b4)|@>=
23942 B1=mp->bc; B2=mp->ec; B3=mp->bc; B4=mp->ec; mp->tfm_changed=0;
23943 for (k=mp->bc;k<=mp->ec;k++) { 
23944   if ( mp->char_exists[k] ) {
23945     x=mp_dimen_out(mp, value(mp->tfm_width[k]))+(k+4)*020000000; /* this is positive */
23946     B1=(B1+B1+x) % 255;
23947     B2=(B2+B2+x) % 253;
23948     B3=(B3+B3+x) % 251;
23949     B4=(B4+B4+x) % 247;
23950   }
23951 }
23952
23953 @ Finally we're ready to actually write the \.{TFM} information.
23954 Here are some utility routines for this purpose.
23955
23956 @d tfm_out(A) fputc((A),mp->tfm_file) /* output one byte to |tfm_file| */
23957
23958 @c void mp_tfm_two (MP mp,integer x) { /* output two bytes to |tfm_file| */
23959   tfm_out(x / 256); tfm_out(x % 256);
23960 }
23961 void mp_tfm_four (MP mp,integer x) { /* output four bytes to |tfm_file| */
23962   if ( x>=0 ) tfm_out(x / three_bytes);
23963   else { 
23964     x=x+010000000000; /* use two's complement for negative values */
23965     x=x+010000000000;
23966     tfm_out((x / three_bytes) + 128);
23967   };
23968   x=x % three_bytes; tfm_out(x / unity);
23969   x=x % unity; tfm_out(x / 0400);
23970   tfm_out(x % 0400);
23971 }
23972 void mp_tfm_qqqq (MP mp,four_quarters x) { /* output four quarterwords to |tfm_file| */
23973   tfm_out(qo(x.b0)); tfm_out(qo(x.b1)); 
23974   tfm_out(qo(x.b2)); tfm_out(qo(x.b3));
23975 }
23976
23977 @ @<Finish the \.{TFM} file@>=
23978 if ( mp->job_name==NULL ) mp_open_log_file(mp);
23979 mp_pack_job_name(mp, ".tfm");
23980 while ( ! mp_b_open_out(mp, &mp->tfm_file, mp_filetype_metrics) )
23981   mp_prompt_file_name(mp, "file name for font metrics",".tfm");
23982 mp->metric_file_name=xstrdup(mp->name_of_file);
23983 @<Output the subfile sizes and header bytes@>;
23984 @<Output the character information bytes, then
23985   output the dimensions themselves@>;
23986 @<Output the ligature/kern program@>;
23987 @<Output the extensible character recipes and the font metric parameters@>;
23988   if ( mp->internal[tracing_stats]>0 )
23989   @<Log the subfile sizes of the \.{TFM} file@>;
23990 mp_print_nl(mp, "Font metrics written on "); 
23991 mp_print(mp, mp->metric_file_name); mp_print_char(mp, '.');
23992 @.Font metrics written...@>
23993 fclose(mp->tfm_file)
23994
23995 @ Integer variables |lh|, |k|, and |lk_offset| will be defined when we use
23996 this code.
23997
23998 @<Output the subfile sizes and header bytes@>=
23999 k=mp->header_last;
24000 LH=(k+3) / 4; /* this is the number of header words */
24001 if ( mp->bc>mp->ec ) mp->bc=1; /* if there are no characters, |ec=0| and |bc=1| */
24002 @<Compute the ligature/kern program offset and implant the
24003   left boundary label@>;
24004 mp_tfm_two(mp,6+LH+(mp->ec-mp->bc+1)+mp->nw+mp->nh+mp->nd+mp->ni+mp->nl
24005      +lk_offset+mp->nk+mp->ne+mp->np);
24006   /* this is the total number of file words that will be output */
24007 mp_tfm_two(mp, LH); mp_tfm_two(mp, mp->bc); mp_tfm_two(mp, mp->ec); 
24008 mp_tfm_two(mp, mp->nw); mp_tfm_two(mp, mp->nh);
24009 mp_tfm_two(mp, mp->nd); mp_tfm_two(mp, mp->ni); mp_tfm_two(mp, mp->nl+lk_offset); 
24010 mp_tfm_two(mp, mp->nk); mp_tfm_two(mp, mp->ne);
24011 mp_tfm_two(mp, mp->np);
24012 for (k=0;k< 4*LH;k++)   { 
24013   tfm_out(mp->header_byte[k]);
24014 }
24015
24016 @ @<Output the character information bytes...@>=
24017 for (k=mp->bc;k<=mp->ec;k++) {
24018   if ( ! mp->char_exists[k] ) {
24019     mp_tfm_four(mp, 0);
24020   } else { 
24021     tfm_out(info(mp->tfm_width[k])); /* the width index */
24022     tfm_out((info(mp->tfm_height[k]))*16+info(mp->tfm_depth[k]));
24023     tfm_out((info(mp->tfm_ital_corr[k]))*4+mp->char_tag[k]);
24024     tfm_out(mp->char_remainder[k]);
24025   };
24026 }
24027 mp->tfm_changed=0;
24028 for (k=1;k<=4;k++) { 
24029   mp_tfm_four(mp, 0); p=mp->dimen_head[k];
24030   while ( p!=inf_val ) {
24031     mp_tfm_four(mp, mp_dimen_out(mp, value(p))); p=link(p);
24032   }
24033 }
24034
24035
24036 @ We need to output special instructions at the beginning of the
24037 |lig_kern| array in order to specify the right boundary character
24038 and/or to handle starting addresses that exceed 255. The |label_loc|
24039 and |label_char| arrays have been set up to record all the
24040 starting addresses; we have $-1=|label_loc|[0]<|label_loc|[1]\le\cdots
24041 \le|label_loc|[|label_ptr]|$.
24042
24043 @<Compute the ligature/kern program offset...@>=
24044 mp->bchar=mp_round_unscaled(mp, mp->internal[boundary_char]);
24045 if ((mp->bchar<0)||(mp->bchar>255))
24046   { mp->bchar=-1; mp->lk_started=false; lk_offset=0; }
24047 else { mp->lk_started=true; lk_offset=1; };
24048 @<Find the minimum |lk_offset| and adjust all remainders@>;
24049 if ( mp->bch_label<undefined_label )
24050   { skip_byte(mp->nl)=qi(255); next_char(mp->nl)=qi(0);
24051   op_byte(mp->nl)=qi(((mp->bch_label+lk_offset)/ 256));
24052   rem_byte(mp->nl)=qi(((mp->bch_label+lk_offset)% 256));
24053   incr(mp->nl); /* possibly |nl=lig_table_size+1| */
24054   }
24055
24056 @ @<Find the minimum |lk_offset|...@>=
24057 k=mp->label_ptr; /* pointer to the largest unallocated label */
24058 if ( mp->label_loc[k]+lk_offset>255 ) {
24059   lk_offset=0; mp->lk_started=false; /* location 0 can do double duty */
24060   do {  
24061     mp->char_remainder[mp->label_char[k]]=lk_offset;
24062     while ( mp->label_loc[k-1]==mp->label_loc[k] ) {
24063        decr(k); mp->char_remainder[mp->label_char[k]]=lk_offset;
24064     }
24065     incr(lk_offset); decr(k);
24066   } while (! (lk_offset+mp->label_loc[k]<256));
24067     /* N.B.: |lk_offset=256| satisfies this when |k=0| */
24068 };
24069 if ( lk_offset>0 ) {
24070   while ( k>0 ) {
24071     mp->char_remainder[mp->label_char[k]]
24072      =mp->char_remainder[mp->label_char[k]]+lk_offset;
24073     decr(k);
24074   }
24075 }
24076
24077 @ @<Output the ligature/kern program@>=
24078 for (k=0;k<= 255;k++ ) {
24079   if ( mp->skip_table[k]<undefined_label ) {
24080      mp_print_nl(mp, "(local label "); mp_print_int(mp, k); mp_print(mp, ":: was missing)");
24081 @.local label l:: was missing@>
24082     cancel_skips(mp->skip_table[k]);
24083   }
24084 }
24085 if ( mp->lk_started ) { /* |lk_offset=1| for the special |bchar| */
24086   tfm_out(255); tfm_out(mp->bchar); mp_tfm_two(mp, 0);
24087 } else {
24088   for (k=1;k<=lk_offset;k++) {/* output the redirection specs */
24089     mp->ll=mp->label_loc[mp->label_ptr];
24090     if ( mp->bchar<0 ) { tfm_out(254); tfm_out(0);   }
24091     else { tfm_out(255); tfm_out(mp->bchar);   };
24092     mp_tfm_two(mp, mp->ll+lk_offset);
24093     do {  
24094       decr(mp->label_ptr);
24095     } while (! (mp->label_loc[mp->label_ptr]<mp->ll));
24096   }
24097 }
24098 for (k=0;k<=mp->nl-1;k++) mp_tfm_qqqq(mp, mp->lig_kern[k]);
24099 for (k=0;k<=mp->nk-1;k++) mp_tfm_four(mp, mp_dimen_out(mp, mp->kern[k]))
24100
24101 @ @<Output the extensible character recipes...@>=
24102 for (k=0;k<=mp->ne-1;k++) 
24103   mp_tfm_qqqq(mp, mp->exten[k]);
24104 for (k=1;k<=mp->np;k++) {
24105   if ( k==1 ) {
24106     if ( abs(mp->param[1])<fraction_half ) {
24107       mp_tfm_four(mp, mp->param[1]*16);
24108     } else  { 
24109       incr(mp->tfm_changed);
24110       if ( mp->param[1]>0 ) mp_tfm_four(mp, el_gordo);
24111       else mp_tfm_four(mp, -el_gordo);
24112     }
24113   } else {
24114     mp_tfm_four(mp, mp_dimen_out(mp, mp->param[k]));
24115   }
24116 }
24117 if ( mp->tfm_changed>0 )  { 
24118   if ( mp->tfm_changed==1 ) mp_print_nl(mp, "(a font metric dimension");
24119 @.a font metric dimension...@>
24120   else  { 
24121     mp_print_nl(mp, "("); mp_print_int(mp, mp->tfm_changed);
24122 @.font metric dimensions...@>
24123     mp_print(mp, " font metric dimensions");
24124   }
24125   mp_print(mp, " had to be decreased)");
24126 }
24127
24128 @ @<Log the subfile sizes of the \.{TFM} file@>=
24129
24130   char s[200];
24131   wlog_ln(" ");
24132   if ( mp->bch_label<undefined_label ) decr(mp->nl);
24133   snprintf(s,128,"(You used %iw,%ih,%id,%ii,%il,%ik,%ie,%ip metric file positions)",
24134                  mp->nw, mp->nh, mp->nd, mp->ni, mp->nl, mp->nk, mp->ne,mp->np);
24135   wlog_ln(s);
24136 }
24137
24138 @* \[43] Reading font metric data.
24139
24140 \MP\ isn't a typesetting program but it does need to find the bounding box
24141 of a sequence of typeset characters.  Thus it needs to read \.{TFM} files as
24142 well as write them.
24143
24144 @<Glob...@>=
24145 FILE * tfm_infile;
24146
24147 @ All the width, height, and depth information is stored in an array called
24148 |font_info|.  This array is allocated sequentially and each font is stored
24149 as a series of |char_info| words followed by the width, height, and depth
24150 tables.  Since |font_name| entries are permanent, their |str_ref| values are
24151 set to |max_str_ref|.
24152
24153 @<Types...@>=
24154 typedef unsigned int font_number; /* |0..font_max| */
24155
24156 @ The |font_info| array is indexed via a group directory arrays.
24157 For example, the |char_info| data for character~|c| in font~|f| will be
24158 in |font_info[char_base[f]+c].qqqq|.
24159
24160 @<Glob...@>=
24161 font_number font_max; /* maximum font number for included text fonts */
24162 size_t      font_mem_size; /* number of words for \.{TFM} information for text fonts */
24163 memory_word *font_info; /* height, width, and depth data */
24164 char        **font_enc_name; /* encoding names, if any */
24165 boolean     *font_ps_name_fixed; /* are the postscript names fixed already?  */
24166 int         next_fmem; /* next unused entry in |font_info| */
24167 font_number last_fnum; /* last font number used so far */
24168 scaled      *font_dsize;  /* 16 times the ``design'' size in \ps\ points */
24169 char        **font_name;  /* name as specified in the \&{infont} command */
24170 char        **font_ps_name;  /* PostScript name for use when |internal[prologues]>0| */
24171 font_number last_ps_fnum; /* last valid |font_ps_name| index */
24172 eight_bits  *font_bc;
24173 eight_bits  *font_ec;  /* first and last character code */
24174 int         *char_base;  /* base address for |char_info| */
24175 int         *width_base; /* index for zeroth character width */
24176 int         *height_base; /* index for zeroth character height */
24177 int         *depth_base; /* index for zeroth character depth */
24178 pointer     *font_sizes;
24179
24180 @ @<Allocate or initialize ...@>=
24181 mp->font_mem_size = 10000; 
24182 mp->font_info = xmalloc ((mp->font_mem_size+1),sizeof(memory_word));
24183 memset (mp->font_info,0,sizeof(memory_word)*(mp->font_mem_size+1));
24184 mp->font_enc_name = NULL;
24185 mp->font_ps_name_fixed = NULL;
24186 mp->font_dsize = NULL;
24187 mp->font_name = NULL;
24188 mp->font_ps_name = NULL;
24189 mp->font_bc = NULL;
24190 mp->font_ec = NULL;
24191 mp->last_fnum = null_font;
24192 mp->char_base = NULL;
24193 mp->width_base = NULL;
24194 mp->height_base = NULL;
24195 mp->depth_base = NULL;
24196 mp->font_sizes = null;
24197
24198 @ @<Dealloc variables@>=
24199 xfree(mp->font_info);
24200 xfree(mp->font_enc_name);
24201 xfree(mp->font_ps_name_fixed);
24202 xfree(mp->font_dsize);
24203 xfree(mp->font_name);
24204 xfree(mp->font_ps_name);
24205 xfree(mp->font_bc);
24206 xfree(mp->font_ec);
24207 xfree(mp->char_base);
24208 xfree(mp->width_base);
24209 xfree(mp->height_base);
24210 xfree(mp->depth_base);
24211 xfree(mp->font_sizes);
24212
24213
24214 @c 
24215 void mp_reallocate_fonts (MP mp, font_number l) {
24216   font_number f;
24217   XREALLOC(mp->font_enc_name,      (l+1), char *);
24218   XREALLOC(mp->font_ps_name_fixed, (l+1), boolean);
24219   XREALLOC(mp->font_dsize,         (l+1), scaled);
24220   XREALLOC(mp->font_name,          (l+1), char *);
24221   XREALLOC(mp->font_ps_name,       (l+1), char *);
24222   XREALLOC(mp->font_bc,            (l+1), eight_bits);
24223   XREALLOC(mp->font_ec,            (l+1), eight_bits);
24224   XREALLOC(mp->char_base,          (l+1), int);
24225   XREALLOC(mp->width_base,         (l+1), int);
24226   XREALLOC(mp->height_base,        (l+1), int);
24227   XREALLOC(mp->depth_base,         (l+1), int);
24228   XREALLOC(mp->font_sizes,         (l+1), pointer);
24229   for (f=(mp->last_fnum+1);f<=l;f++) {
24230     mp->font_enc_name[f]=NULL;
24231     mp->font_ps_name_fixed[f] = false;
24232     mp->font_name[f]=NULL;
24233     mp->font_ps_name[f]=NULL;
24234     mp->font_sizes[f]=null;
24235   }
24236   mp->font_max = l;
24237 }
24238
24239 @ @<Declare |mp_reallocate| functions@>=
24240 void mp_reallocate_fonts (MP mp, font_number l);
24241
24242
24243 @ A |null_font| containing no characters is useful for error recovery.  Its
24244 |font_name| entry starts out empty but is reset each time an erroneous font is
24245 found.  This helps to cut down on the number of duplicate error messages without
24246 wasting a lot of space.
24247
24248 @d null_font 0 /* the |font_number| for an empty font */
24249
24250 @<Set initial...@>=
24251 mp->font_dsize[null_font]=0;
24252 mp->font_bc[null_font]=1;
24253 mp->font_ec[null_font]=0;
24254 mp->char_base[null_font]=0;
24255 mp->width_base[null_font]=0;
24256 mp->height_base[null_font]=0;
24257 mp->depth_base[null_font]=0;
24258 mp->next_fmem=0;
24259 mp->last_fnum=null_font;
24260 mp->last_ps_fnum=null_font;
24261 mp->font_name[null_font]="nullfont";
24262 mp->font_ps_name[null_font]="";
24263
24264 @ Each |char_info| word is of type |four_quarters|.  The |b0| field contains
24265 the |width index|; the |b1| field contains the height
24266 index; the |b2| fields contains the depth index, and the |b3| field used only
24267 for temporary storage. (It is used to keep track of which characters occur in
24268 an edge structure that is being shipped out.)
24269 The corresponding words in the width, height, and depth tables are stored as
24270 |scaled| values in units of \ps\ points.
24271
24272 With the macros below, the |char_info| word for character~|c| in font~|f| is
24273 |char_info(f)(c)| and the width is
24274 $$\hbox{|char_width(f)(char_info(f)(c)).sc|.}$$
24275
24276 @d char_info_end(A) (A)].qqqq
24277 @d char_info(A) mp->font_info[mp->char_base[(A)]+char_info_end
24278 @d char_width_end(A) (A).b0].sc
24279 @d char_width(A) mp->font_info[mp->width_base[(A)]+char_width_end
24280 @d char_height_end(A) (A).b1].sc
24281 @d char_height(A) mp->font_info[mp->height_base[(A)]+char_height_end
24282 @d char_depth_end(A) (A).b2].sc
24283 @d char_depth(A) mp->font_info[mp->depth_base[(A)]+char_depth_end
24284 @d ichar_exists(A) ((A).b0>0)
24285
24286 @ The |font_ps_name| for a built-in font should be what PostScript expects.
24287 A preliminary name is obtained here from the \.{TFM} name as given in the
24288 |fname| argument.  This gets updated later from an external table if necessary.
24289
24290 @<Declare text measuring subroutines@>=
24291 @<Declare subroutines for parsing file names@>;
24292 font_number mp_read_font_info (MP mp, char*fname) {
24293   boolean file_opened; /* has |tfm_infile| been opened? */
24294   font_number n; /* the number to return */
24295   halfword lf,tfm_lh,bc,ec,nw,nh,nd; /* subfile size parameters */
24296   size_t whd_size; /* words needed for heights, widths, and depths */
24297   int i,ii; /* |font_info| indices */
24298   int jj; /* counts bytes to be ignored */
24299   scaled z; /* used to compute the design size */
24300   fraction d;
24301   /* height, width, or depth as a fraction of design size times $2^{-8}$ */
24302   eight_bits h_and_d; /* height and depth indices being unpacked */
24303   int tfbyte; /* a byte read from the file */
24304   n=null_font;
24305   @<Open |tfm_infile| for input@>;
24306   @<Read data from |tfm_infile|; if there is no room, say so and |goto done|;
24307     otherwise |goto bad_tfm| or |goto done| as appropriate@>;
24308 BAD_TFM:
24309   @<Complain that the \.{TFM} file is bad@>;
24310 DONE:
24311   if ( file_opened ) fclose(mp->tfm_infile);
24312   if ( n!=null_font ) { 
24313     mp->font_ps_name[n]=fname;
24314     mp->font_name[n]=fname;
24315   }
24316   return n;
24317 }
24318
24319 @ \MP\ doesn't bother to check the entire \.{TFM} file for errors or explain
24320 precisely what is wrong if it does find a problem.  Programs called \.{TFtoPL}
24321 @.TFtoPL@> @.PLtoTF@>
24322 and \.{PLtoTF} can be used to debug \.{TFM} files.
24323
24324 @<Complain that the \.{TFM} file is bad@>=
24325 print_err("Font ");
24326 mp_print(mp, fname);
24327 if ( file_opened ) mp_print(mp, " not usable: TFM file is bad");
24328 else mp_print(mp, " not usable: TFM file not found");
24329 help3("I wasn't able to read the size data for this font so this")
24330   ("`infont' operation won't produce anything. If the font name")
24331   ("is right, you might ask an expert to make a TFM file");
24332 if ( file_opened )
24333   mp->help_line[0]="is right, try asking an expert to fix the TFM file";
24334 mp_error(mp)
24335
24336 @ @<Read data from |tfm_infile|; if there is no room, say so...@>=
24337 @<Read the \.{TFM} size fields@>;
24338 @<Use the size fields to allocate space in |font_info|@>;
24339 @<Read the \.{TFM} header@>;
24340 @<Read the character data and the width, height, and depth tables and
24341   |goto done|@>
24342
24343 @ A bad \.{TFM} file can be shorter than it claims to be.  The code given here
24344 might try to read past the end of the file if this happens.  Changes will be
24345 needed if it causes a system error to refer to |tfm_infile^| or call
24346 |get_tfm_infile| when |eof(tfm_infile)| is true.  For example, the definition
24347 @^system dependencies@>
24348 of |tfget| could be changed to
24349 ``|begin get(tfm_infile); if eof(tfm_infile) then goto bad_tfm; end|.''
24350
24351 @d tfget {tfbyte = fgetc(mp->tfm_infile); }
24352 @d read_two(A) { (A)=tfbyte;
24353   if ( (A)>127 ) goto BAD_TFM;
24354   tfget; (A)=(A)*0400+tfbyte;
24355   }
24356 @d tf_ignore(A) { for (jj=(A);jj>=1;jj--) tfget; }
24357
24358 @<Read the \.{TFM} size fields@>=
24359 tfget; read_two(lf);
24360 tfget; read_two(tfm_lh);
24361 tfget; read_two(bc);
24362 tfget; read_two(ec);
24363 if ( (bc>1+ec)||(ec>255) ) goto BAD_TFM;
24364 tfget; read_two(nw);
24365 tfget; read_two(nh);
24366 tfget; read_two(nd);
24367 whd_size=(ec+1-bc)+nw+nh+nd;
24368 if ( lf<(int)(6+tfm_lh+whd_size) ) goto BAD_TFM;
24369 tf_ignore(10)
24370
24371 @ Offsets are added to |char_base[n]| and |width_base[n]| so that is not
24372 necessary to apply the |so|  and |qo| macros when looking up the width of a
24373 character in the string pool.  In order to ensure nonnegative |char_base|
24374 values when |bc>0|, it may be necessary to reserve a few unused |font_info|
24375 elements.
24376
24377 @<Use the size fields to allocate space in |font_info|@>=
24378 if ( mp->next_fmem<bc) mp->next_fmem=bc;  /* ensure nonnegative |char_base| */
24379 if (mp->last_fnum==mp->font_max)
24380   mp_reallocate_fonts(mp,(mp->font_max+(mp->font_max>>2)));
24381 while (mp->next_fmem+whd_size>=mp->font_mem_size) {
24382   size_t l = mp->font_mem_size+(mp->font_mem_size>>2);
24383   memory_word *font_info;
24384   font_info = xmalloc ((l+1),sizeof(memory_word));
24385   memset (font_info,0,sizeof(memory_word)*(l+1));
24386   memcpy (font_info,mp->font_info,sizeof(memory_word)*(mp->font_mem_size+1));
24387   xfree(mp->font_info);
24388   mp->font_info = font_info;
24389   mp->font_mem_size = l;
24390 }
24391 incr(mp->last_fnum);
24392 n=mp->last_fnum;
24393 mp->font_bc[n]=bc;
24394 mp->font_ec[n]=ec;
24395 mp->char_base[n]=mp->next_fmem-bc;
24396 mp->width_base[n]=mp->next_fmem+ec-bc+1;
24397 mp->height_base[n]=mp->width_base[n]+nw;
24398 mp->depth_base[n]=mp->height_base[n]+nh;
24399 mp->next_fmem=mp->next_fmem+whd_size;
24400
24401
24402 @ @<Read the \.{TFM} header@>=
24403 if ( tfm_lh<2 ) goto BAD_TFM;
24404 tf_ignore(4);
24405 tfget; read_two(z);
24406 tfget; z=z*0400+tfbyte;
24407 tfget; z=z*0400+tfbyte; /* now |z| is 16 times the design size */
24408 mp->font_dsize[n]=mp_take_fraction(mp, z,267432584);
24409   /* times ${72\over72.27}2^{28}$ to convert from \TeX\ points */
24410 tf_ignore(4*(tfm_lh-2))
24411
24412 @ @<Read the character data and the width, height, and depth tables...@>=
24413 ii=mp->width_base[n];
24414 i=mp->char_base[n]+bc;
24415 while ( i<ii ) { 
24416   tfget; mp->font_info[i].qqqq.b0=qi(tfbyte);
24417   tfget; h_and_d=tfbyte;
24418   mp->font_info[i].qqqq.b1=h_and_d / 16;
24419   mp->font_info[i].qqqq.b2=h_and_d % 16;
24420   tfget; tfget;
24421   incr(i);
24422 }
24423 while ( i<mp->next_fmem ) {
24424   @<Read a four byte dimension, scale it by the design size, store it in
24425     |font_info[i]|, and increment |i|@>;
24426 }
24427 if (feof(mp->tfm_infile) ) goto BAD_TFM;
24428 goto DONE
24429
24430 @ The raw dimension read into |d| should have magnitude at most $2^{24}$ when
24431 interpreted as an integer, and this includes a scale factor of $2^{20}$.  Thus
24432 we can multiply it by sixteen and think of it as a |fraction| that has been
24433 divided by sixteen.  This cancels the extra scale factor contained in
24434 |font_dsize[n|.
24435
24436 @<Read a four byte dimension, scale it by the design size, store it in...@>=
24437
24438 tfget; d=tfbyte;
24439 if ( d>=0200 ) d=d-0400;
24440 tfget; d=d*0400+tfbyte;
24441 tfget; d=d*0400+tfbyte;
24442 tfget; d=d*0400+tfbyte;
24443 mp->font_info[i].sc=mp_take_fraction(mp, d*16,mp->font_dsize[n]);
24444 incr(i);
24445 }
24446
24447 @ This function does no longer use the file name parser, because |fname| is
24448 a C string already.
24449 @<Open |tfm_infile| for input@>=
24450 file_opened=false;
24451 mp_ptr_scan_file(mp, fname);
24452 if ( strlen(mp->cur_area)==0 ) mp->cur_area=xstrdup(MP_font_area);
24453 if ( strlen(mp->cur_ext)==0 ) mp->cur_ext=xstrdup(".tfm");
24454 mp->tfm_infile = mp_open_file(mp, fname, "rb",mp_filetype_metrics);
24455 if ( !mp->tfm_infile  ) goto BAD_TFM;
24456 file_opened=true
24457
24458 @ When we have a font name and we don't know whether it has been loaded yet,
24459 we scan the |font_name| array before calling |read_font_info|.
24460
24461 @<Declare text measuring subroutines@>=
24462 font_number mp_find_font (MP mp, char *f) {
24463   font_number n;
24464   for (n=0;n<=mp->last_fnum;n++) {
24465     if (mp_xstrcmp(f,mp->font_name[n])==0 )
24466       return n;
24467   }
24468   return mp_read_font_info(mp, f);
24469 }
24470
24471 @ One simple application of |find_font| is the implementation of the |font_size|
24472 operator that gets the design size for a given font name.
24473
24474 @<Find the design size of the font whose name is |cur_exp|@>=
24475 mp_flush_cur_exp(mp, (mp->font_dsize[mp_find_font(mp, str(mp->cur_exp))]+8) / 16)
24476
24477 @ If we discover that the font doesn't have a requested character, we omit it
24478 from the bounding box computation and expect the \ps\ interpreter to drop it.
24479 This routine issues a warning message if the user has asked for it.
24480
24481 @<Declare text measuring subroutines@>=
24482 void mp_lost_warning (MP mp,font_number f, pool_pointer k) { 
24483   if ( mp->internal[tracing_lost_chars]>0 ) { 
24484     mp_begin_diagnostic(mp);
24485     if ( mp->selector==log_only ) incr(mp->selector);
24486     mp_print_nl(mp, "Missing character: There is no ");
24487 @.Missing character@>
24488     mp_print_str(mp, mp->str_pool[k]); 
24489     mp_print(mp, " in font ");
24490     mp_print(mp, mp->font_name[f]); mp_print_char(mp, '!'); 
24491     mp_end_diagnostic(mp, false);
24492   }
24493 }
24494
24495 @ The whole purpose of saving the height, width, and depth information is to be
24496 able to find the bounding box of an item of text in an edge structure.  The
24497 |set_text_box| procedure takes a text node and adds this information.
24498
24499 @<Declare text measuring subroutines@>=
24500 void mp_set_text_box (MP mp,pointer p) {
24501   font_number f; /* |font_n(p)| */
24502   ASCII_code bc,ec; /* range of valid characters for font |f| */
24503   pool_pointer k,kk; /* current character and character to stop at */
24504   four_quarters cc; /* the |char_info| for the current character */
24505   scaled h,d; /* dimensions of the current character */
24506   width_val(p)=0;
24507   height_val(p)=-el_gordo;
24508   depth_val(p)=-el_gordo;
24509   f=font_n(p);
24510   bc=mp->font_bc[f];
24511   ec=mp->font_ec[f];
24512   kk=str_stop(text_p(p));
24513   k=mp->str_start[text_p(p)];
24514   while ( k<kk ) {
24515     @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>;
24516   }
24517   @<Set the height and depth to zero if the bounding box is empty@>;
24518 }
24519
24520 @ @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>=
24521
24522   if ( (mp->str_pool[k]<bc)||(mp->str_pool[k]>ec) ) {
24523     mp_lost_warning(mp, f,k);
24524   } else { 
24525     cc=char_info(f)(mp->str_pool[k]);
24526     if ( ! ichar_exists(cc) ) {
24527       mp_lost_warning(mp, f,k);
24528     } else { 
24529       width_val(p)=width_val(p)+char_width(f)(cc);
24530       h=char_height(f)(cc);
24531       d=char_depth(f)(cc);
24532       if ( h>height_val(p) ) height_val(p)=h;
24533       if ( d>depth_val(p) ) depth_val(p)=d;
24534     }
24535   }
24536   incr(k);
24537 }
24538
24539 @ Let's hope modern compilers do comparisons correctly when the difference would
24540 overflow.
24541
24542 @<Set the height and depth to zero if the bounding box is empty@>=
24543 if ( height_val(p)<-depth_val(p) ) { 
24544   height_val(p)=0;
24545   depth_val(p)=0;
24546 }
24547
24548 @ The new primitives fontmapfile and fontmapline.
24549
24550 @<Declare action procedures for use by |do_statement|@>=
24551 void mp_do_mapfile (MP mp) ;
24552 void mp_do_mapline (MP mp) ;
24553
24554 @ @c void mp_do_mapfile (MP mp) { 
24555   mp_get_x_next(mp); mp_scan_expression(mp);
24556   if ( mp->cur_type!=mp_string_type ) {
24557     @<Complain about improper map operation@>;
24558   } else {
24559     mp_map_file(mp,mp->cur_exp);
24560   }
24561 }
24562 void mp_do_mapline (MP mp) { 
24563   mp_get_x_next(mp); mp_scan_expression(mp);
24564   if ( mp->cur_type!=mp_string_type ) {
24565      @<Complain about improper map operation@>;
24566   } else { 
24567      mp_map_line(mp,mp->cur_exp);
24568   }
24569 }
24570
24571 @ @<Complain about improper map operation@>=
24572
24573   exp_err("Unsuitable expression");
24574   help1("Only known strings can be map files or map lines.");
24575   mp_put_get_error(mp);
24576 }
24577
24578 @
24579 @<Declare the \ps\ output procedures@>=
24580 void mp_ps_print_cmd (MP mp, char *l, char *s) {
24581   if ( mp->internal[mpprocset]>0 ) { ps_room(strlen(s)); mp_print(mp,s); }
24582   else { ps_room(strlen(l)); mp_print(mp, l); };
24583 }
24584 void mp_print_cmd (MP mp,char *l, char *s) {
24585   if ( mp->internal[mpprocset]>0 ) mp_print(mp, s); 
24586   else mp_print(mp, l);
24587 }
24588
24589 @ To print |scaled| value to PDF output we need some subroutines to ensure
24590 accurary.
24591
24592 @d max_integer   0x7FFFFFFF /* $2^{31}-1$ */
24593
24594 @<Glob...@>=
24595 scaled one_bp; /* scaled value corresponds to 1bp */
24596 scaled one_hundred_bp; /* scaled value corresponds to 100bp */
24597 scaled one_hundred_inch; /* scaled value corresponds to 100in */
24598 integer ten_pow[10]; /* $10^0..10^9$ */
24599 integer scaled_out; /* amount of |scaled| that was taken out in |divide_scaled| */
24600
24601 @ @<Set init...@>=
24602 mp->one_bp = 65782; /* 65781.76 */
24603 mp->one_hundred_bp = 6578176;
24604 mp->one_hundred_inch = 473628672;
24605 mp->ten_pow[0] = 1;
24606 for (i = 1;i<= 9; i++ ) {
24607   mp->ten_pow[i] = 10*mp->ten_pow[i - 1];
24608 }
24609
24610 @ The following function divides |s| by |m|. |dd| is number of decimal digits.
24611
24612 @c scaled mp_divide_scaled (MP mp,scaled s, scaled m, integer  dd) {
24613   scaled q,r;
24614   integer sign,i;
24615   sign = 1;
24616   if ( s < 0 ) { sign = -sign; s = -s; }
24617   if ( m < 0 ) { sign = -sign; m = -m; }
24618   if ( m == 0 )
24619     mp_confusion(mp, "arithmetic: divided by zero");
24620   else if ( m >= (max_integer / 10) )
24621     mp_confusion(mp, "arithmetic: number too big");
24622   q = s / m;
24623   r = s % m;
24624   for (i = 1;i<=dd;i++) {
24625     q = 10*q + (10*r) / m;
24626     r = (10*r) % m;
24627   }
24628   if ( 2*r >= m ) { incr(q); r = r - m; }
24629   mp->scaled_out = sign*(s - (r / mp->ten_pow[dd]));
24630   return (sign*q);
24631 }
24632
24633 @* \[44] Shipping pictures out.
24634 The |ship_out| procedure, to be described below, is given a pointer to
24635 an edge structure. Its mission is to output a file containing the \ps\
24636 description of an edge structure.
24637
24638 @ Each time an edge structure is shipped out we write a new \ps\ output
24639 file named according to the current \&{charcode}.
24640 @:char_code_}{\&{charcode} primitive@>
24641
24642 @<Declare the \ps\ output procedures@>=
24643 void mp_open_output_file (MP mp) ;
24644
24645 @ @c void mp_open_output_file (MP mp) {
24646   integer c; /* \&{charcode} rounded to the nearest integer */
24647   int old_setting; /* previous |selector| setting */
24648   pool_pointer i; /*  indexes into |filename_template|  */
24649   integer cc; /* a temporary integer for template building  */
24650   integer f,g=0; /* field widths */
24651   if ( mp->job_name==NULL ) mp_open_log_file(mp);
24652   c=mp_round_unscaled(mp, mp->internal[char_code]);
24653   if ( mp->filename_template==0 ) {
24654     char *s; /* a file extension derived from |c| */
24655     if ( c<0 ) 
24656       s=xstrdup(".ps");
24657     else 
24658       @<Use |c| to compute the file extension |s|@>;
24659     mp_pack_job_name(mp, s);
24660     xfree(s);
24661     while ( ! mp_a_open_out(mp, &mp->ps_file, mp_filetype_postscript) )
24662       mp_prompt_file_name(mp, "file name for output",s);
24663   } else { /* initializations */
24664     str_number s, n; /* a file extension derived from |c| */
24665     old_setting=mp->selector; 
24666     mp->selector=new_string;
24667     f = 0;
24668     i = mp->str_start[mp->filename_template];
24669     n = rts(""); /* initialize */
24670     while ( i<str_stop(mp->filename_template) ) {
24671        if ( mp->str_pool[i]=='%' ) {
24672       CONTINUE:
24673         incr(i);
24674         if ( i<str_stop(mp->filename_template) ) {
24675           if ( mp->str_pool[i]=='j' ) {
24676             mp_print(mp, mp->job_name);
24677           } else if ( mp->str_pool[i]=='d' ) {
24678              cc= mp_round_unscaled(mp, mp->internal[day]);
24679              print_with_leading_zeroes(cc);
24680           } else if ( mp->str_pool[i]=='m' ) {
24681              cc= mp_round_unscaled(mp, mp->internal[month]);
24682              print_with_leading_zeroes(cc);
24683           } else if ( mp->str_pool[i]=='y' ) {
24684              cc= mp_round_unscaled(mp, mp->internal[year]);
24685              print_with_leading_zeroes(cc);
24686           } else if ( mp->str_pool[i]=='H' ) {
24687              cc= mp_round_unscaled(mp, mp->internal[mp_time]) / 60;
24688              print_with_leading_zeroes(cc);
24689           }  else if ( mp->str_pool[i]=='M' ) {
24690              cc= mp_round_unscaled(mp, mp->internal[mp_time]) % 60;
24691              print_with_leading_zeroes(cc);
24692           } else if ( mp->str_pool[i]=='c' ) {
24693             if ( c<0 ) mp_print(mp, "ps");
24694             else print_with_leading_zeroes(c);
24695           } else if ( (mp->str_pool[i]>='0') && 
24696                       (mp->str_pool[i]<='9') ) {
24697             if ( (f<10)  )
24698               f = (f*10) + mp->str_pool[i]-'0';
24699             goto CONTINUE;
24700           } else {
24701             mp_print_str(mp, mp->str_pool[i]);
24702           }
24703         }
24704       } else {
24705         if ( mp->str_pool[i]=='.' )
24706           if (length(n)==0)
24707             n = mp_make_string(mp);
24708         mp_print_str(mp, mp->str_pool[i]);
24709       };
24710       incr(i);
24711     };
24712     s = mp_make_string(mp);
24713     mp->selector= old_setting;
24714     if (length(n)==0) {
24715        n=s;
24716        s=rts("");
24717     };
24718     mp_pack_file_name(mp, str(n),"",str(s));
24719     while ( ! mp_a_open_out(mp, &mp->ps_file, mp_filetype_postscript) )
24720       mp_prompt_file_name(mp, "file name for output",str(s));
24721     delete_str_ref(n);
24722     delete_str_ref(s);
24723   }
24724   @<Store the true output file name if appropriate@>;
24725   @<Begin the progress report for the output of picture~|c|@>;
24726 }
24727
24728 @ The file extension created here could be up to five characters long in
24729 extreme cases so it may have to be shortened on some systems.
24730 @^system dependencies@>
24731
24732 @<Use |c| to compute the file extension |s|@>=
24733
24734   s = xmalloc(7,1);
24735   snprintf(s,7,".%i",(int)c);
24736 }
24737
24738 @ The user won't want to see all the output file names so we only save the
24739 first and last ones and a count of how many there were.  For this purpose
24740 files are ordered primarily by \&{charcode} and secondarily by order of
24741 creation.
24742 @:char_code_}{\&{charcode} primitive@>
24743
24744 @<Store the true output file name if appropriate@>=
24745 if ((c<mp->first_output_code)&&(mp->first_output_code>=0)) {
24746   mp->first_output_code=c;
24747   xfree(mp->first_file_name);
24748   mp->first_file_name=xstrdup(mp->name_of_file);
24749 }
24750 if ( c>=mp->last_output_code ) {
24751   mp->last_output_code=c;
24752   xfree(mp->last_file_name);
24753   mp->last_file_name=xstrdup(mp->name_of_file);
24754 }
24755
24756 @ @<Glob...@>=
24757 char * first_file_name;
24758 char * last_file_name; /* full file names */
24759 integer first_output_code;integer last_output_code; /* rounded \&{charcode} values */
24760 @:char_code_}{\&{charcode} primitive@>
24761 integer total_shipped; /* total number of |ship_out| operations completed */
24762
24763 @ @<Set init...@>=
24764 mp->first_file_name=xstrdup("");
24765 mp->last_file_name=xstrdup("");
24766 mp->first_output_code=32768;
24767 mp->last_output_code=-32768;
24768 mp->total_shipped=0;
24769
24770 @ @<Dealloc variables@>=
24771 xfree(mp->first_file_name);
24772 xfree(mp->last_file_name);
24773
24774 @ @<Begin the progress report for the output of picture~|c|@>=
24775 if ( (int)mp->term_offset>mp->max_print_line-6 ) mp_print_ln(mp);
24776 else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
24777 mp_print_char(mp, '[');
24778 if ( c>=0 ) mp_print_int(mp, c)
24779
24780 @ @<End progress report@>=
24781 mp_print_char(mp, ']');
24782 update_terminal;
24783 incr(mp->total_shipped)
24784
24785 @ @<Explain what output files were written@>=
24786 if ( mp->total_shipped>0 ) { 
24787   mp_print_nl(mp, "");
24788   mp_print_int(mp, mp->total_shipped);
24789   mp_print(mp, " output file");
24790   if ( mp->total_shipped>1 ) mp_print_char(mp, 's');
24791   mp_print(mp, " written: ");
24792   mp_print(mp, mp->first_file_name);
24793   if ( mp->total_shipped>1 ) {
24794     if ( 31+strlen(mp->first_file_name)+
24795          strlen(mp->last_file_name)> (unsigned)mp->max_print_line) 
24796       mp_print_ln(mp);
24797     mp_print(mp, " .. ");
24798     mp_print(mp, mp->last_file_name);
24799   }
24800 }
24801
24802 @ We often need to print a pair of coordinates.
24803
24804 @d ps_room(A) if ( (mp->ps_offset+(int)(A))>mp->max_print_line ) 
24805   mp_print_ln(mp) /* optional line break */
24806
24807 @<Declare the \ps\ output procedures@>=
24808 void mp_ps_pair_out (MP mp,scaled x, scaled y) { 
24809   ps_room(26);
24810   mp_print_scaled(mp, x); mp_print_char(mp, ' ');
24811   mp_print_scaled(mp, y); mp_print_char(mp, ' ');
24812 }
24813
24814 @ @<Declare the \ps\ output procedures@>=
24815 void mp_ps_print (MP mp,char *s) { 
24816    ps_room(strlen(s));
24817    mp_print(mp, s);
24818 };
24819
24820 @ @<Exported...@>=
24821 void mp_ps_print (MP mp,char *s) ;
24822
24823
24824 @ The most important output procedure is the one that gives the \ps\ version of
24825 a \MP\ path.
24826
24827 @<Declare the \ps\ output procedures@>=
24828 void mp_ps_path_out (MP mp,pointer h) {
24829   pointer p,q; /* for scanning the path */
24830   scaled d; /* a temporary value */
24831   boolean curved; /* |true| unless the cubic is almost straight */
24832   ps_room(40);
24833   if ( mp->need_newpath ) 
24834     mp_print_cmd(mp, "newpath ","n ");
24835   mp->need_newpath=true;
24836   mp_ps_pair_out(mp, x_coord(h),y_coord(h));
24837   mp_print_cmd(mp, "moveto","m");
24838   p=h;
24839   do {  
24840     if ( right_type(p)==endpoint ) { 
24841       if ( p==h ) mp_ps_print_cmd(mp, " 0 0 rlineto"," 0 0 r");
24842       return;
24843     }
24844     q=link(p);
24845     @<Start a new line and print the \ps\ commands for the curve from
24846       |p| to~|q|@>;
24847     p=q;
24848   } while (p!=h);
24849   mp_ps_print_cmd(mp, " closepath"," p");
24850 }
24851
24852 @ @<Glob...@>=
24853 boolean need_newpath;
24854   /* will |ps_path_out| need to issue a \&{newpath} command next time */
24855 @:newpath_}{\&{newpath} command@>
24856
24857 @ @<Start a new line and print the \ps\ commands for the curve from...@>=
24858 curved=true;
24859 @<Set |curved:=false| if the cubic from |p| to |q| is almost straight@>;
24860 mp_print_ln(mp);
24861 if ( curved ){ 
24862   mp_ps_pair_out(mp, right_x(p),right_y(p));
24863   mp_ps_pair_out(mp, left_x(q),left_y(q));
24864   mp_ps_pair_out(mp, x_coord(q),y_coord(q));
24865   mp_ps_print_cmd(mp, "curveto","c");
24866 } else if ( q!=h ){ 
24867   mp_ps_pair_out(mp, x_coord(q),y_coord(q));
24868   mp_ps_print_cmd(mp, "lineto","l");
24869 }
24870
24871 @ Two types of straight lines come up often in \MP\ paths:
24872 cubics with zero initial and final velocity as created by |make_path| or
24873 |make_envelope|, and cubics with control points uniformly spaced on a line
24874 as created by |make_choices|.
24875
24876 @d bend_tolerance 131 /* allow rounding error of $2\cdot10^{-3}$ */
24877
24878 @<Set |curved:=false| if the cubic from |p| to |q| is almost straight@>=
24879 if ( right_x(p)==x_coord(p) )
24880   if ( right_y(p)==y_coord(p) )
24881     if ( left_x(q)==x_coord(q) )
24882       if ( left_y(q)==y_coord(q) ) curved=false;
24883 d=left_x(q)-right_x(p);
24884 if ( abs(right_x(p)-x_coord(p)-d)<=bend_tolerance )
24885   if ( abs(x_coord(q)-left_x(q)-d)<=bend_tolerance )
24886     { d=left_y(q)-right_y(p);
24887     if ( abs(right_y(p)-y_coord(p)-d)<=bend_tolerance )
24888       if ( abs(y_coord(q)-left_y(q)-d)<=bend_tolerance ) curved=false;
24889     }
24890
24891 @ We need to keep track of several parameters from the \ps\ graphics state.
24892 @^graphics state@>
24893 This allows us to be sure that \ps\ has the correct values when they are
24894 needed without wasting time and space setting them unnecessarily.
24895
24896 @d gs_node_size 10
24897 @d gs_red        mp->mem[mp->gs_state+1].sc
24898 @d gs_green      mp->mem[mp->gs_state+2].sc
24899 @d gs_blue       mp->mem[mp->gs_state+3].sc
24900 @d gs_black      mp->mem[mp->gs_state+4].sc
24901    /* color from the last \&{setcmykcolor} or \&{setrgbcolor} or \&{setgray} command */
24902 @d gs_colormodel mp->mem[mp->gs_state+5].qqqq.b0
24903    /* the current colormodel */
24904 @d gs_ljoin      mp->mem[mp->gs_state+5].qqqq.b1
24905 @d gs_lcap       mp->mem[mp->gs_state+5].qqqq.b2
24906    /* values from the last \&{setlinejoin} and \&{setlinecap} commands */
24907 @d gs_adj_wx     mp->mem[mp->gs_state+5].qqqq.b3
24908    /* what resolution-dependent adjustment applies to the width */
24909 @d gs_miterlim   mp->mem[mp->gs_state+6].sc
24910    /* the value from the last \&{setmiterlimit} command */
24911 @d gs_dash_p     mp->mem[mp->gs_state+7].hh.lh
24912    /* edge structure for last \&{setdash} command */
24913 @d gs_previous   mp->mem[mp->gs_state+7].hh.rh
24914    /* backlink to the previous |gs_state| structure */
24915 @d gs_dash_sc    mp->mem[mp->gs_state+8].sc
24916    /* scale factor used with |gs_dash_p| */
24917 @d gs_width      mp->mem[mp->gs_state+9].sc
24918    /* width setting or $-1$ if no \&{setlinewidth} command so far */
24919
24920 @<Glob...@>=
24921 pointer gs_state;
24922
24923 @ @<Set init...@>=
24924 mp->gs_state=null;
24925
24926 @ To avoid making undue assumptions about the initial graphics state, these
24927 parameters are given special values that are guaranteed not to match anything
24928 in the edge structure being shipped out.  On the other hand, the initial color
24929 should be black so that the translation of an all-black picture will have no
24930 \&{setcolor} commands.  (These would be undesirable in a font application.)
24931 Hence we use |c=0| when initializing the graphics state and we use |c<0|
24932 to recover from a situation where we have lost track of the graphics state.
24933
24934 @<Declare the \ps\ output procedures@>=
24935 void mp_unknown_graphics_state (MP mp,scaled c) ;
24936
24937 @ @c void mp_unknown_graphics_state (MP mp,scaled c) {
24938   pointer p; /* to shift graphic states around */
24939   quarterword k; /* a loop index for copying the |gs_state| */
24940   if ( (c==0)||(c==-1) ) {
24941     if ( mp->gs_state==null ) {
24942       mp->gs_state = mp_get_node(mp, gs_node_size);
24943       gs_previous=null;
24944     } else {
24945       while ( gs_previous!=null ) {
24946         p = gs_previous;
24947         mp_free_node(mp, mp->gs_state,gs_node_size);
24948         mp->gs_state=p;
24949       }
24950     }
24951     gs_red=c; gs_green=c; gs_blue=c; gs_black=c;
24952     gs_colormodel=uninitialized_model;
24953     gs_ljoin=3;
24954     gs_lcap=3;
24955     gs_miterlim=0;
24956     gs_dash_p=diov;
24957     gs_dash_sc=0;
24958     gs_width=-1;
24959   } else if ( c==1 ) {
24960     p= mp->gs_state;
24961     mp->gs_state = mp_get_node(mp, gs_node_size);
24962     for (k=1;k<=gs_node_size-1;k++)
24963       mp->mem[mp->gs_state+k]=mp->mem[p+k];
24964     gs_previous = p;
24965   } else if ( c==2 ) {
24966     p = gs_previous;
24967     mp_free_node(mp, mp->gs_state,gs_node_size);
24968     mp->gs_state=p;
24969   }
24970 }
24971
24972 @ When it is time to output a graphical object, |fix_graphics_state| ensures
24973 that \ps's idea of the graphics state agrees with what is stored in the object.
24974
24975 @<Declare the \ps\ output procedures@>=
24976 @<Declare subroutines needed by |fix_graphics_state|@>;
24977 void mp_fix_graphics_state (MP mp, pointer p) ;
24978
24979 @ @c 
24980 void mp_fix_graphics_state (MP mp, pointer p) {
24981   /* get ready to output graphical object |p| */
24982   pointer hh,pp; /* for list manipulation */
24983   scaled wx,wy,ww; /* dimensions of pen bounding box */
24984   boolean adj_wx; /* whether pixel rounding should be based on |wx| or |wy| */
24985   integer tx,ty; /* temporaries for computing |adj_wx| */
24986   scaled scf; /* a scale factor for the dash pattern */
24987   if ( has_color(p) )
24988     @<Make sure \ps\ will use the right color for object~|p|@>;
24989   if ( (type(p)==fill_code)||(type(p)==stroked_code) )
24990     if ( pen_p(p)!=null )
24991       if ( pen_is_elliptical(pen_p(p)) ) {
24992         @<Generate \ps\ code that sets the stroke width to the
24993           appropriate rounded value@>;
24994         @<Make sure \ps\ will use the right dash pattern for |dash_p(p)|@>;
24995         @<Decide whether the line cap parameter matters and set it if necessary@>;
24996         @<Set the other numeric parameters as needed for object~|p|@>;
24997       }
24998   if ( mp->ps_offset>0 ) mp_print_ln(mp);
24999 }
25000
25001 @ @<Decide whether the line cap parameter matters and set it if necessary@>=
25002 if ( type(p)==stroked_code )
25003   if ( (left_type(path_p(p))==endpoint)||(dash_p(p)!=null) )
25004     if ( gs_lcap!=lcap_val(p) ) {
25005       ps_room(13);
25006       mp_print_char(mp, ' ');
25007       mp_print_char(mp, '0'+lcap_val(p)); 
25008       mp_print_cmd(mp, " setlinecap"," lc");
25009       gs_lcap=lcap_val(p);
25010     }
25011
25012 @ @<Set the other numeric parameters as needed for object~|p|@>=
25013 if ( gs_ljoin!=ljoin_val(p) ) {
25014   ps_room(14);
25015   mp_print_char(mp, ' ');
25016   mp_print_char(mp, '0'+ljoin_val(p)); mp_print_cmd(mp, " setlinejoin"," lj");
25017   gs_ljoin=ljoin_val(p);
25018 }
25019 if ( gs_miterlim!=miterlim_val(p) ) {
25020   ps_room(27);
25021   mp_print_char(mp, ' ');
25022   mp_print_scaled(mp, miterlim_val(p)); mp_print_cmd(mp, " setmiterlimit"," ml");
25023   gs_miterlim=miterlim_val(p);
25024 }
25025
25026 @ @<Make sure \ps\ will use the right color for object~|p|@>=
25027 {
25028   if ( (color_model(p)==rgb_model)||
25029      ((color_model(p)==uninitialized_model)&&
25030      ((mp->internal[default_color_model] / unity)==rgb_model)) ) {
25031   if ( (gs_colormodel!=rgb_model)||(gs_red!=red_val(p))||
25032       (gs_green!=green_val(p))||(gs_blue!=blue_val(p)) ) {
25033       gs_red=red_val(p);
25034       gs_green=green_val(p);
25035       gs_blue=blue_val(p);
25036       gs_black= -1;
25037       gs_colormodel=rgb_model;
25038       { ps_room(36);
25039         mp_print_char(mp, ' ');
25040         mp_print_scaled(mp, gs_red); mp_print_char(mp, ' ');
25041         mp_print_scaled(mp, gs_green); mp_print_char(mp, ' ');
25042         mp_print_scaled(mp, gs_blue);
25043         mp_print_cmd(mp, " setrgbcolor", " R");
25044       }
25045     }
25046   } else if ( (color_model(p)==cmyk_model)||
25047      ((color_model(p)==uninitialized_model)&&
25048      ((mp->internal[default_color_model] / unity)==cmyk_model)) ) {
25049    if ( (gs_red!=cyan_val(p))||(gs_green!=magenta_val(p))||
25050       (gs_blue!=yellow_val(p))||(gs_black!=black_val(p))||
25051       (gs_colormodel!=cmyk_model) ) {
25052       if ( color_model(p)==uninitialized_model ) {
25053         gs_red=0;
25054         gs_green=0;
25055         gs_blue=0;
25056         gs_black=unity;
25057       } else {
25058         gs_red=cyan_val(p);
25059         gs_green=magenta_val(p);
25060         gs_blue=yellow_val(p);
25061         gs_black=black_val(p);
25062       }
25063       gs_colormodel=cmyk_model;
25064       { ps_room(45);
25065         mp_print_char(mp, ' ');
25066         mp_print_scaled(mp, gs_red); mp_print_char(mp, ' ');
25067         mp_print_scaled(mp, gs_green); mp_print_char(mp, ' ');
25068         mp_print_scaled(mp, gs_blue); mp_print_char(mp, ' ');
25069         mp_print_scaled(mp, gs_black);
25070         mp_print_cmd(mp, " setcmykcolor"," C");
25071       }
25072     }
25073   } else if ( (color_model(p)==grey_model)||
25074     ((color_model(p)==uninitialized_model)&&
25075      ((mp->internal[default_color_model] / unity)==grey_model)) ) {
25076    if ( (gs_red!=grey_val(p))||(gs_colormodel!=grey_model) ) {
25077       gs_red = grey_val(p);
25078       gs_green= -1;
25079       gs_blue= -1;
25080       gs_black= -1;
25081       gs_colormodel=grey_model;
25082       { ps_room(16);
25083         mp_print_char(mp, ' ');
25084         mp_print_scaled(mp, gs_red);
25085         mp_print_cmd(mp, " setgray"," G");
25086       }
25087     }
25088   }
25089   if ( color_model(p)==no_model )
25090     gs_colormodel=no_model;
25091 }
25092
25093 @ In order to get consistent widths for horizontal and vertical pen strokes, we
25094 want \ps\ to use an integer number of pixels for the \&{setwidth} parameter.
25095 @:setwidth}{\&{setwidth}command@>
25096 We set |gs_width| to the ideal horizontal or vertical stroke width and then
25097 generate \ps\ code that computes the rounded value.  For non-circular pens, the
25098 pen shape will be rescaled so that horizontal or vertical parts of the stroke
25099 have the computed width.
25100
25101 Rounding the width to whole pixels is not likely to improve the appearance of
25102 diagonal or curved strokes, but we do it anyway for consistency.  The
25103 \&{truncate} command generated here tends to make all the strokes a little
25104 @:truncate}{\&{truncate} command@>
25105 thinner, but this is appropriate for \ps's scan-conversion rules.  Even with
25106 truncation, an ideal with of $w$~pixels gets mapped into $\lfloor w\rfloor+1$.
25107 It would be better to have $\lceil w\rceil$ but that is ridiculously expensive
25108 to compute in \ps.
25109
25110 @<Generate \ps\ code that sets the stroke width...@>=
25111 @<Set |wx| and |wy| to the width and height of the bounding box for
25112   |pen_p(p)|@>;
25113 @<Use |pen_p(p)| and |path_p(p)| to decide whether |wx| or |wy| is more
25114   important and set |adj_wx| and |ww| accordingly@>;
25115 if ( (ww!=gs_width) || (adj_wx!=gs_adj_wx) ) {
25116   if ( adj_wx ) {
25117     ps_room(13);
25118     mp_print_char(mp, ' '); mp_print_scaled(mp, ww);
25119     mp_ps_print_cmd(mp, 
25120       " 0 dtransform exch truncate exch idtransform pop setlinewidth"," hlw");
25121   } else {
25122     if ( mp->internal[mpprocset]>0 ) {
25123       ps_room(13);
25124       mp_print_char(mp, ' ');
25125       mp_print_scaled(mp, ww);
25126       mp_ps_print(mp, " vlw");
25127     } else { 
25128       ps_room(15);
25129       mp_print(mp, " 0 "); mp_print_scaled(mp, ww);
25130       mp_ps_print(mp, " dtransform truncate idtransform setlinewidth pop");
25131     }
25132   }
25133   gs_width = ww;
25134   gs_adj_wx = adj_wx;
25135 }
25136
25137 @ @<Set |wx| and |wy| to the width and height of the bounding box for...@>=
25138 pp=pen_p(p);
25139 if ( (right_x(pp)==x_coord(pp)) && (left_y(pp)==y_coord(pp)) ) {
25140   wx = abs(left_x(pp) - x_coord(pp));
25141   wy = abs(right_y(pp) - y_coord(pp));
25142 } else {
25143   wx = mp_pyth_add(mp, left_x(pp)-x_coord(pp), right_x(pp)-x_coord(pp));
25144   wy = mp_pyth_add(mp, left_y(pp)-y_coord(pp), right_y(pp)-y_coord(pp));
25145 }
25146
25147 @ The path is considered ``essentially horizontal'' if its range of
25148 $y$~coordinates is less than the $y$~range |wy| for the pen.  ``Essentially
25149 vertical'' paths are detected similarly.  This code ensures that no component
25150 of the pen transformation is more that |aspect_bound*(ww+1)|.
25151
25152 @d aspect_bound 10 /* ``less important'' of |wx|, |wy| cannot exceed the other by
25153     more than this factor */
25154
25155 @<Use |pen_p(p)| and |path_p(p)| to decide whether |wx| or |wy| is more...@>=
25156 tx=1; ty=1;
25157 if ( mp_coord_rangeOK(mp, path_p(p), y_loc(0), wy) ) tx=aspect_bound;
25158 else if ( mp_coord_rangeOK(mp, path_p(p), x_loc(0), wx) ) ty=aspect_bound;
25159 if ( wy / ty>=wx / tx ) { ww=wy; adj_wx=false; }
25160 else { ww=wx; adj_wx=true;  }
25161
25162 @ This routine quickly tests if path |h| is ``essentially horizontal'' or
25163 ``essentially vertical,'' where |zoff| is |x_loc(0)| or |y_loc(0)| and |dz| is
25164 allowable range for $x$ or~$y$.  We do not need and cannot afford a full
25165 bounding-box computation.
25166
25167 @<Declare subroutines needed by |fix_graphics_state|@>=
25168 boolean mp_coord_rangeOK (MP mp,pointer h, 
25169                           small_number  zoff, scaled dz) {
25170   pointer p; /* for scanning the path form |h| */
25171   scaled zlo,zhi; /* coordinate range so far */
25172   scaled z; /* coordinate currently being tested */
25173   zlo=knot_coord(h+zoff);
25174   zhi=zlo;
25175   p=h;
25176   while ( right_type(p)!=endpoint ) {
25177     z=right_coord(p+zoff);
25178     @<Make |zlo..zhi| include |z| and |return false| if |zhi-zlo>dz|@>;
25179     p=link(p);
25180     z=left_coord(p+zoff);
25181     @<Make |zlo..zhi| include |z| and |return false| if |zhi-zlo>dz|@>;
25182     z=knot_coord(p+zoff);
25183     @<Make |zlo..zhi| include |z| and |return false| if |zhi-zlo>dz|@>;
25184     if ( p==h ) break;
25185   }
25186   return true;
25187 }
25188
25189 @ @<Make |zlo..zhi| include |z| and |return false| if |zhi-zlo>dz|@>=
25190 if ( z<zlo ) zlo=z;
25191 else if ( z>zhi ) zhi=z;
25192 if ( zhi-zlo>dz ) return false
25193
25194 @ Filling with an elliptical pen is implemented via a combination of \&{stroke}
25195 and \&{fill} commands and a nontrivial dash pattern would interfere with this.
25196 @:stroke}{\&{stroke} command@>
25197 @:fill}{\&{fill} command@>
25198 Note that we don't use |delete_edge_ref| because |gs_dash_p| is not counted as
25199 a reference.
25200
25201 @<Make sure \ps\ will use the right dash pattern for |dash_p(p)|@>=
25202 if ( type(p)==fill_code ) {
25203   hh=null;
25204 } else { 
25205   hh=dash_p(p);
25206   scf=mp_get_pen_scale(mp, pen_p(p));
25207   if ( scf==0 ) {
25208     if ( gs_width==0 ) scf=dash_scale(p);  else hh=null;
25209   } else { 
25210     scf=mp_make_scaled(mp, gs_width,scf);
25211     scf=mp_take_scaled(mp, scf,dash_scale(p));
25212   }
25213 }
25214 if ( hh==null ) {
25215   if ( gs_dash_p!=null ) {
25216     mp_ps_print_cmd(mp, " [] 0 setdash"," rd");
25217     gs_dash_p=null;
25218   }
25219 } else if ( (gs_dash_sc!=scf) || ! mp_same_dashes(mp, gs_dash_p,hh) ) {
25220   @<Set the dash pattern from |dash_list(hh)| scaled by |scf|@>;
25221 }
25222
25223 @ Translating a dash list into \ps\ is very similar to printing it symbolically
25224 in |print_edges|.  A dash pattern with |dash_y(hh)=0| has length zero and is
25225 ignored.  The same fate applies in the bizarre case of a dash pattern that
25226 cannot be printed without overflow.
25227
25228 @<Set the dash pattern from |dash_list(hh)| scaled by |scf|@>=
25229 { gs_dash_p=hh;
25230   gs_dash_sc=scf;
25231   if ( (dash_y(hh)==0) || (abs(dash_y(hh)) / unity >= el_gordo / scf)){
25232     mp_ps_print_cmd(mp, " [] 0 setdash"," rd");
25233   } else { 
25234     pp=dash_list(hh);
25235     start_x(null_dash)=start_x(pp)+dash_y(hh);
25236     ps_room(28);
25237     mp_print(mp, " [");
25238     while ( pp!=null_dash ) {
25239       mp_ps_pair_out(mp, mp_take_scaled(mp, stop_x(pp)-start_x(pp),scf),
25240                          mp_take_scaled(mp, start_x(link(pp))-stop_x(pp),scf));
25241       pp=link(pp);
25242     }
25243     ps_room(22);
25244     mp_print(mp, "] ");
25245     mp_print_scaled(mp, mp_take_scaled(mp, mp_dash_offset(mp, hh),scf));
25246     mp_print_cmd(mp, " setdash"," sd");
25247   }
25248 }
25249
25250 @ @<Declare subroutines needed by |fix_graphics_state|@>=
25251 boolean mp_same_dashes (MP mp,pointer h, pointer hh) ;
25252
25253 @ @c
25254 boolean mp_same_dashes (MP mp,pointer h, pointer hh) {
25255   /* do |h| and |hh| represent the same dash pattern? */
25256   pointer p,pp; /* dash nodes being compared */
25257   if ( h==hh ) return true;
25258   else if ( (h<=diov)||(hh<=diov) ) return false;
25259   else if ( dash_y(h)!=dash_y(hh) ) return false;
25260   else { @<Compare |dash_list(h)| and |dash_list(hh)|@>; }
25261   return false; /* can't happen */
25262 }
25263
25264 @ @<Compare |dash_list(h)| and |dash_list(hh)|@>=
25265 { p=dash_list(h);
25266   pp=dash_list(hh);
25267   while ( (p!=null_dash)&&(pp!=null_dash) ) {
25268     if ( (start_x(p)!=start_x(pp))||(stop_x(p)!=stop_x(pp)) ) {
25269       break;
25270     } else { 
25271       p=link(p);
25272       pp=link(pp);
25273     }
25274   }
25275   return (p==pp);
25276 }
25277
25278 @ When stroking a path with an elliptical pen, it is necessary to transform
25279 the coordinate system so that a unit circular pen will have the desired shape.
25280 To keep this transformation local, we enclose it in a
25281 $$\&{gsave}\ldots\&{grestore}$$
25282 block. Any translation component must be applied to the path being stroked
25283 while the rest of the transformation must apply only to the pen.
25284 If |fill_also=true|, the path is to be filled as well as stroked so we must
25285 insert commands to do this after giving the path.
25286
25287 @<Declare the \ps\ output procedures@>=
25288 void mp_stroke_ellipse (MP mp,pointer h, boolean fill_also) ;
25289
25290
25291 @c void mp_stroke_ellipse (MP mp,pointer h, boolean fill_also) {
25292   /* generate an elliptical pen stroke from object |h| */
25293   scaled txx,txy,tyx,tyy; /* transformation parameters */
25294   pointer p; /* the pen to stroke with */
25295   scaled d1,det; /* for tweaking transformation parameters */
25296   integer s; /* also for tweaking transformation paramters */
25297   boolean transformed; /* keeps track of whether gsave/grestore are needed */
25298   transformed=false;
25299   @<Use |pen_p(h)| to set the transformation parameters and give the initial
25300     translation@>;
25301   @<Tweak the transformation parameters so the transformation is nonsingular@>;
25302   mp_ps_path_out(mp, path_p(h));
25303   if ( mp->internal[mpprocset]==0 ) {
25304     if ( fill_also ) mp_print_nl(mp, "gsave fill grestore");
25305     @<Issue \ps\ commands to transform the coordinate system@>;
25306     mp_ps_print(mp, " stroke");
25307     if ( transformed ) mp_ps_print(mp, " grestore");
25308   } else {
25309     if ( fill_also ) mp_print_nl(mp, "B"); else mp_print_ln(mp);
25310     if ( (txy!=0)||(tyx!=0) ) {
25311       mp_print(mp, " [");
25312       mp_ps_pair_out(mp, txx,tyx);
25313       mp_ps_pair_out(mp, txy,tyy);
25314       mp_ps_print(mp, "0 0] t");
25315     } else if ((txx!=unity)||(tyy!=unity) )  {
25316       mp_ps_pair_out(mp,txx,tyy);
25317       mp_print(mp, " s");
25318     };
25319     mp_ps_print(mp, " S");
25320     if ( transformed ) mp_ps_print(mp, " Q");
25321   }
25322   mp_print_ln(mp);
25323 }
25324
25325 @ @<Use |pen_p(h)| to set the transformation parameters and give the...@>=
25326 p=pen_p(h);
25327 txx=left_x(p);
25328 tyx=left_y(p);
25329 txy=right_x(p);
25330 tyy=right_y(p);
25331 if ( (x_coord(p)!=0)||(y_coord(p)!=0) ) {
25332   mp_print_nl(mp, ""); mp_print_cmd(mp, "gsave ","q ");
25333   mp_ps_pair_out(mp, x_coord(p),y_coord(p));
25334   mp_ps_print(mp, "translate ");
25335   txx-=x_coord(p);
25336   tyx-=y_coord(p);
25337   txy-=x_coord(p);
25338   tyy-=y_coord(p);
25339   transformed=true;
25340 } else {
25341   mp_print_nl(mp, "");
25342 }
25343 @<Adjust the transformation to account for |gs_width| and output the
25344   initial \&{gsave} if |transformed| should be |true|@>
25345
25346 @ @<Adjust the transformation to account for |gs_width| and output the...@>=
25347 if ( gs_width!=unity ) {
25348   if ( gs_width==0 ) { 
25349     txx=unity; tyy=unity;
25350   } else { 
25351     txx=mp_make_scaled(mp, txx,gs_width);
25352     txy=mp_make_scaled(mp, txy,gs_width);
25353     tyx=mp_make_scaled(mp, tyx,gs_width);
25354     tyy=mp_make_scaled(mp, tyy,gs_width);
25355   };
25356 }
25357 if ( (txy!=0)||(tyx!=0)||(txx!=unity)||(tyy!=unity) ) {
25358   if ( (! transformed) ){ 
25359     mp_ps_print_cmd(mp, "gsave ","q ");
25360     transformed=true;
25361   }
25362 }
25363
25364 @ @<Issue \ps\ commands to transform the coordinate system@>=
25365 if ( (txy!=0)||(tyx!=0) ){ 
25366   mp_print_ln(mp);
25367   mp_print_char(mp, '[');
25368   mp_ps_pair_out(mp, txx,tyx);
25369   mp_ps_pair_out(mp, txy,tyy);
25370   mp_ps_print(mp, "0 0] concat");
25371 } else if ( (txx!=unity)||(tyy!=unity) ){ 
25372   mp_print_ln(mp);
25373   mp_ps_pair_out(mp, txx,tyy);
25374   mp_print(mp, "scale");
25375 }
25376
25377 @ The \ps\ interpreter will probably abort if it encounters a singular
25378 transformation matrix.  The determinant must be large enough to ensure that
25379 the printed representation will be nonsingular.  Since the printed
25380 representation is always within $2^{-17}$ of the internal |scaled| value, the
25381 total error is at most $4T_{\rm max}2^{-17}$, where $T_{\rm max}$ is a bound on
25382 the magnitudes of |txx/65536|, |txy/65536|, etc.
25383
25384 The |aspect_bound*(gs_width+1)| bound on the components of the pen
25385 transformation allows $T_{\rm max}$ to be at most |2*aspect_bound|.
25386
25387 @<Tweak the transformation parameters so the transformation is nonsingular@>=
25388 det=mp_take_scaled(mp, txx,tyy) - mp_take_scaled(mp, txy,tyx);
25389 d1=4*aspect_bound+1;
25390 if ( abs(det)<d1 ) { 
25391   if ( det>=0 ) { d1=d1-det; s=1;  }
25392   else { d1=-d1-det; s=-1;  };
25393   d1=d1*unity;
25394   if ( abs(txx)+abs(tyy)>=abs(txy)+abs(tyy) ) {
25395     if ( abs(txx)>abs(tyy) ) tyy=tyy+(d1+s*abs(txx)) / txx;
25396     else txx=txx+(d1+s*abs(tyy)) / tyy;
25397   } else {
25398     if ( abs(txy)>abs(tyx) ) tyx=tyx+(d1+s*abs(txy)) / txy;
25399     else txy=txy+(d1+s*abs(tyx)) / tyx;
25400   }
25401 }
25402
25403 @ Here is a simple routine that just fills a cycle.
25404
25405 @<Declare the \ps\ output procedures@>=
25406 void mp_ps_fill_out (MP mp,pointer p) ;
25407
25408 @ @c
25409 void mp_ps_fill_out (MP mp,pointer p) { /* fill cyclic path~|p| */
25410   mp_ps_path_out(mp, p);
25411   mp_ps_print_cmd(mp, " fill"," F");
25412   mp_print_ln(mp);
25413 }
25414
25415 @ Given a cyclic path~|p| and a graphical object~|h|, the |do_outer_envelope|
25416 procedure fills the cycle generated by |make_envelope|.  It need not do
25417 anything unless some region has positive winding number with respect to~|p|,
25418 but it does not seem worthwhile to for test this.
25419
25420 @<Declare the \ps\ output procedures@>=
25421 void mp_do_outer_envelope (MP mp,pointer p, pointer h) ;
25422
25423 @ @c
25424 void mp_do_outer_envelope (MP mp,pointer p, pointer h) {
25425   p=mp_make_envelope(mp, p, pen_p(h), ljoin_val(h), 0, miterlim_val(h));
25426   mp_ps_fill_out(mp, p);
25427   mp_toss_knot_list(mp, p);
25428 }
25429
25430 @ A text node may specify an arbitrary transformation but the usual case
25431 involves only shifting, scaling, and occasionally rotation.  The purpose
25432 of |choose_scale| is to select a scale factor so that the remaining
25433 transformation is as ``nice'' as possible.  The definition of ``nice''
25434 is somewhat arbitrary but shifting and $90^\circ$ rotation are especially
25435 nice because they work out well for bitmap fonts.  The code here selects
25436 a scale factor equal to $1/\sqrt2$ times the Frobenius norm of the
25437 non-shifting part of the transformation matrix.  It is careful to avoid
25438 additions that might cause undetected overflow.
25439
25440 @<Declare the \ps\ output procedures@>=
25441 scaled mp_choose_scale (MP mp,pointer p) ;
25442
25443 @ @c scaled mp_choose_scale (MP mp,pointer p) {
25444   /* |p| should point to a text node */
25445   scaled a,b,c,d,ad,bc; /* temporary values */
25446   a=txx_val(p);
25447   b=txy_val(p);
25448   c=tyx_val(p);
25449   d=tyy_val(p);
25450   if ( (a<0) ) negate(a);
25451   if ( (b<0) ) negate(b);
25452   if ( (c<0) ) negate(c);
25453   if ( (d<0) ) negate(d);
25454   ad=half(a-d);
25455   bc=half(b-c);
25456   return mp_pyth_add(mp, mp_pyth_add(mp, d+ad,ad), mp_pyth_add(mp, c+bc,bc));
25457 }
25458
25459 @ @<Declare the \ps\ output procedures@>=
25460 void mp_ps_string_out (MP mp, char *s) {
25461   char *i; /* current character code position */
25462   ASCII_code k; /* bits to be converted to octal */
25463   mp_print(mp, "(");
25464   i=s;
25465   while (*i) {
25466     if ( mp->ps_offset+5>mp->max_print_line ) {
25467       mp_print_char(mp, '\\');
25468       mp_print_ln(mp);
25469     }
25470     k=*i;
25471     if ( (@<Character |k| is not allowed in PostScript output@>) ) {
25472       mp_print_char(mp, '\\');
25473       mp_print_char(mp, '0'+(k / 64));
25474       mp_print_char(mp, '0'+((k / 8) % 8));
25475       mp_print_char(mp, '0'+(k % 8));
25476     } else { 
25477       if ( (k=='(')||(k==')')||(k=='\\') ) mp_print_char(mp, '\\');
25478       mp_print_char(mp, k);
25479     }
25480     incr(i);
25481   }
25482   mp_print_char(mp, ')');
25483 }
25484
25485
25486 @d mp_is_ps_name(M,A) mp_do_is_ps_name(A)
25487
25488 @<Declare the \ps\ output procedures@>=
25489 boolean mp_do_is_ps_name (char *s) {
25490   char *i; /* current character code position */
25491   ASCII_code k; /* the character being checked */
25492   i=s;
25493   while (*i) {
25494     k=*i;
25495     if ( (k<=' ')||(k>'~') ) return false;
25496     if ( (k=='(')||(k==')')||(k=='<')||(k=='>')||
25497        (k=='{')||(k=='}')||(k=='/')||(k=='%') ) return false;
25498     incr(i);
25499   }
25500   return true;
25501 }
25502
25503 @ @<Exported...@>=
25504 void mp_ps_name_out (MP mp, char *s, boolean lit) ;
25505
25506 @ @c
25507 void mp_ps_name_out (MP mp, char *s, boolean lit) {
25508   ps_room(strlen(s)+2);
25509   mp_print_char(mp, ' ');
25510   if ( mp_is_ps_name(mp, s) ) {
25511     if ( lit ) mp_print_char(mp, '/');
25512       mp_print(mp, s);
25513   } else { 
25514     mp_ps_string_out(mp, s);
25515     if ( ! lit ) mp_ps_print(mp, "cvx ");
25516       mp_ps_print(mp, "cvn");
25517   }
25518 }
25519
25520 @ @<Declare the \ps\ output procedures@>= 
25521 void mp_mark_string_chars (MP mp,font_number f, str_number s) ;
25522
25523 @ @c
25524 void mp_mark_string_chars (MP mp,font_number f, str_number s) {
25525   integer b; /* |char_base[f]| */
25526   ASCII_code bc,ec; /* only characters between these bounds are marked */
25527   pool_pointer k; /* an index into string |s| */
25528   b=mp->char_base[f];
25529   bc=mp->font_bc[f];
25530   ec=mp->font_ec[f];
25531   k=str_stop(s);
25532   while ( k>mp->str_start[s] ){ 
25533     decr(k);
25534     if ( (mp->str_pool[k]>=bc)&&(mp->str_pool[k]<=ec) )
25535       mp->font_info[b+mp->str_pool[k]].qqqq.b3=used;
25536   }
25537 }
25538
25539 @ There may be many sizes of one font and we need to keep track of the
25540 characters used for each size.  This is done by keeping a linked list of
25541 sizes for each font with a counter in each text node giving the appropriate
25542 position in the size list for its font.
25543
25544 @d sc_factor(A) mp->mem[(A)+1].sc /* the scale factor stored in a font size node */
25545 @d font_size_size 2 /* size of a font size node */
25546
25547 @ @<Exported...@>=
25548 boolean mp_has_font_size(MP mp, font_number f );
25549
25550 @ @c 
25551 boolean mp_has_font_size(MP mp, font_number f ) {
25552   return (mp->font_sizes[f]!=null);
25553 }
25554
25555
25556 @ The overflow here is caused by the fact the returned value
25557 has to fit in a |name_type|, which is a quarterword. 
25558
25559 @d fscale_tolerance 65 /* that's $.001\times2^{16}$ */
25560
25561 @<Declare the \ps\ output procedures@>=
25562 quarterword mp_size_index (MP mp, font_number f, scaled s) {
25563   pointer p,q; /* the previous and current font size nodes */
25564   quarterword i; /* the size index for |q| */
25565   q=mp->font_sizes[f];
25566   i=0;
25567   while ( q!=null ) {
25568     if ( abs(s-sc_factor(q))<=fscale_tolerance ) 
25569       return i;
25570     else 
25571       { p=q; q=link(q); incr(i); };
25572     if ( i==max_quarterword )
25573       mp_overflow(mp, "sizes per font",max_quarterword);
25574 @:MetaPost capacity exceeded sizes per font}{\quad sizes per font@>
25575   }
25576   q=mp_get_node(mp, font_size_size);
25577   sc_factor(q)=s;
25578   if ( i==0 ) mp->font_sizes[f]=q;  else link(p)=q;
25579   return i;
25580 }
25581
25582 @ @<Declare the \ps\ output procedures@>=
25583 scaled mp_indexed_size (MP mp,font_number f, quarterword j) {
25584   pointer p; /* a font size node */
25585   quarterword i; /* the size index for |p| */
25586   p=mp->font_sizes[f];
25587   i=0;
25588   if ( p==null ) mp_confusion(mp, "size");
25589   while ( (i!=j) ) { 
25590     incr(i); p=link(p);
25591     if ( p==null ) mp_confusion(mp, "size");
25592   }
25593   return sc_factor(p);
25594 }
25595
25596 @ @<Declare the \ps\ output procedures@>=
25597 void mp_clear_sizes (MP mp) ;
25598
25599 @ @c void mp_clear_sizes (MP mp) {
25600   font_number f;  /* the font whose size list is being cleared */
25601   pointer p;  /* current font size nodes */
25602   for (f=null_font+1;f<=mp->last_fnum;f++) {
25603     while ( mp->font_sizes[f]!=null ) {
25604       p=mp->font_sizes[f];
25605       mp->font_sizes[f]=link(p);
25606       mp_free_node(mp, p,font_size_size);
25607     }
25608   }
25609 }
25610
25611 @ The \&{special} command saves up lines of text to be printed during the next
25612 |ship_out| operation.  The saved items are stored as a list of capsule tokens.
25613
25614 @<Glob...@>=
25615 pointer last_pending; /* the last token in a list of pending specials */
25616
25617 @ @<Set init...@>=
25618 mp->last_pending=spec_head;
25619
25620 @ @<Cases of |do_statement|...@>=
25621 case special_command: 
25622   if ( mp->cur_mod==0 ) mp_do_special(mp); else 
25623   if ( mp->cur_mod==1 ) mp_do_mapfile(mp); else 
25624   mp_do_mapline(mp);
25625   break;
25626
25627 @ @<Declare action procedures for use by |do_statement|@>=
25628 void mp_do_special (MP mp) ;
25629
25630 @ @c void mp_do_special (MP mp) { 
25631   mp_get_x_next(mp); mp_scan_expression(mp);
25632   if ( mp->cur_type!=mp_string_type ) {
25633     @<Complain about improper special operation@>;
25634   } else { 
25635     link(mp->last_pending)=mp_stash_cur_exp(mp);
25636     mp->last_pending=link(mp->last_pending);
25637     link(mp->last_pending)=null;
25638   }
25639 }
25640
25641 @ @<Complain about improper special operation@>=
25642
25643   exp_err("Unsuitable expression");
25644   help1("Only known strings are allowed for output as specials.");
25645   mp_put_get_error(mp);
25646 }
25647
25648 @ @<Print any pending specials@>=
25649 t=link(spec_head);
25650 while ( t!=null ) {
25651   mp_print_str(mp, value(t));
25652   mp_print_ln(mp);
25653   t=link(t);
25654 }
25655 mp_flush_token_list(mp, link(spec_head));
25656 link(spec_head)=null;
25657 mp->last_pending=spec_head
25658
25659 @ We are now ready for the main output procedure.  Note that the |selector|
25660 setting is saved in a global variable so that |begin_diagnostic| can access it.
25661
25662 @<Declare the \ps\ output procedures@>=
25663 void mp_ship_out (MP mp, pointer h) ;
25664
25665 @ @c
25666 void mp_ship_out (MP mp, pointer h) { /* output edge structure |h| */
25667   pointer p; /* the current graphical object */
25668   pointer q; /* something that |p| points to */
25669   integer t; /* a temporary value */
25670   font_number f; /* fonts used in a text node or as loop counters */
25671   font_number ldf;
25672   scaled ds,scf; /* design size and scale factor for a text node */
25673   boolean transformed; /* is the coordinate system being transformed? */
25674   mp_open_output_file(mp);
25675   mp->non_ps_setting=mp->selector; mp->selector=ps_file_only;
25676   if ( (mp->internal[prologues]==two)||(mp->internal[prologues]==three) ) {
25677     @<Print improved initial comment and bounding box for edge structure~|h|@>;
25678     @<Scan all the text nodes and mark the used characters@>;
25679     mp_load_encodings(mp,mp->last_fnum);
25680     @<Update encoding names@>;
25681     @<Print the improved prologue and setup@>;
25682     @<Print any pending specials@>;
25683     mp_unknown_graphics_state(mp, 0);
25684     mp->need_newpath=true;
25685     p=link(dummy_loc(h));
25686     while ( p!=null ) { 
25687       if ( has_color(p) ) {
25688         if ( (pre_script(p))!=null ) {
25689           mp_print_nl (mp, str(pre_script(p))); mp_print_ln(mp);
25690         }
25691       }
25692       mp_fix_graphics_state(mp, p);
25693       switch (type(p)) {
25694       @<Cases for translating graphical object~|p| into \ps@>;
25695       case mp_start_bounds_code:
25696       case mp_stop_bounds_code:
25697             break;
25698       } /* all cases are enumerated */
25699       p=link(p);
25700     }
25701     mp_print_cmd(mp, "showpage","P"); mp_print_ln(mp);
25702     mp_print(mp, "%%EOF"); mp_print_ln(mp);
25703     fclose(mp->ps_file);
25704     mp->selector=mp->non_ps_setting;
25705     if ( mp->internal[prologues]<=0 ) mp_clear_sizes(mp);
25706     @<End progress report@>;
25707   } else {
25708     @<Print the initial comment and give the bounding box for edge structure~|h|@>;
25709     if ( (mp->internal[prologues]>0) && (mp->last_ps_fnum<mp->last_fnum) )
25710       mp_read_psname_table(mp);
25711     mp_print_prologue(mp, (mp->internal[prologues]>>16), (mp->internal[mpprocset]>>16), ldf);
25712     mp_print_nl(mp, "%%Page: 1 1"); mp_print_ln(mp);
25713     @<Print any pending specials@>;
25714     mp_unknown_graphics_state(mp, 0);
25715     mp->need_newpath=true;
25716     p=link(dummy_loc(h));
25717     while ( p!=null ) { 
25718       if ( has_color(p) ) {
25719         if ( (pre_script(p))!=null ) {
25720           mp_print_nl (mp, str(pre_script(p))); mp_print_ln(mp);
25721         }
25722       }
25723       mp_fix_graphics_state(mp, p);
25724       switch (type(p)) {
25725       @<Cases for translating graphical object~|p| into \ps@>;
25726       case mp_start_bounds_code:
25727       case mp_stop_bounds_code: 
25728         break;
25729       } /* all cases are enumerated */
25730       p=link(p);
25731     }
25732     mp_print_cmd(mp, "showpage","P"); mp_print_ln(mp);
25733     mp_print(mp, "%%EOF"); mp_print_ln(mp);
25734     fclose(mp->ps_file);
25735     mp->selector=mp->non_ps_setting;
25736     if ( mp->internal[prologues]<=0 ) mp_clear_sizes(mp);
25737     @<End progress report@>;
25738   }
25739   if ( mp->internal[tracing_output]>0 ) 
25740    mp_print_edges(mp, h," (just shipped out)",true);
25741 }
25742
25743 @ @<Exported...@>=
25744 void mp_apply_mark_string_chars(MP mp, pointer h, int next_size);
25745
25746 @ @c
25747 void mp_apply_mark_string_chars(MP mp, pointer h, int next_size) {
25748   pointer p;
25749   p=link(dummy_loc(h));
25750   while ( p!=null ) {
25751     if ( type(p)==text_code )
25752       if ( font_n(p)!=null_font )
25753         if ( name_type(p)==next_size )
25754           mp_mark_string_chars(mp, font_n(p),text_p(p));
25755     p=link(p);
25756   }
25757 }
25758
25759 @
25760 @<Print the improved prologue and setup@>=
25761 {
25762   mp_print_improved_prologue(mp, (mp->internal[prologues]>>16),(mp->internal[mpprocset]>>16),
25763                             (mp->internal[gtroffmode]>>16), null, h);
25764 }
25765
25766 @
25767 @<Print improved initial comment and bounding box for edge...@>=
25768 mp_print(mp, "%!PS-Adobe-3.0 EPSF-3.0");
25769 mp_print_nl(mp, "%%BoundingBox: ");
25770 mp_set_bbox(mp, h,true);
25771 if ( minx_val(h)>maxx_val(h) ) {
25772   mp_print(mp, "0 0 0 0");
25773 } else { 
25774   mp_ps_pair_out(mp, mp_floor_scaled(mp, minx_val(h)),mp_floor_scaled(mp, miny_val(h)));
25775   mp_ps_pair_out(mp, -mp_floor_scaled(mp, -maxx_val(h)),-mp_floor_scaled(mp, -maxy_val(h)));
25776 };
25777 mp_print_nl(mp, "%%HiResBoundingBox: ");
25778 if ( minx_val(h)>maxx_val(h) ) {
25779   mp_print(mp, "0 0 0 0");
25780 } else {
25781   mp_ps_pair_out(mp, minx_val(h),miny_val(h));
25782   mp_ps_pair_out(mp, maxx_val(h),maxy_val(h));
25783 }
25784 mp_print_nl(mp, "%%Creator: MetaPost ");
25785 mp_print(mp, metapost_version);
25786 mp_print_nl(mp, "%%CreationDate: ");
25787 mp_print_int(mp, mp_round_unscaled(mp, mp->internal[year])); mp_print_char(mp, '.');
25788 mp_print_dd(mp, mp_round_unscaled(mp, mp->internal[month])); mp_print_char(mp, '.');
25789 mp_print_dd(mp, mp_round_unscaled(mp, mp->internal[day])); mp_print_char(mp, ':');
25790 t=mp_round_unscaled(mp, mp->internal[mp_time]);
25791 mp_print_dd(mp, t / 60); mp_print_dd(mp, t % 60);
25792 mp_print_nl(mp, "%%Pages: 1");
25793
25794 @
25795
25796 @ @<Scan all the text nodes and mark the used ...@>=
25797 for (f=null_font+1;f<=mp->last_fnum;f++) {
25798   if ( mp->font_sizes[f]!=null ) {
25799     mp_unmark_font(mp, f);
25800     mp->font_sizes[f]=null;
25801   }
25802   if ( mp->font_enc_name[f]!=NULL )
25803      xfree(mp->font_enc_name[f]);
25804   mp->font_enc_name[f] = NULL;
25805 }
25806 for (f=null_font+1;f<=mp->last_fnum;f++) {
25807   p=link(dummy_loc(h));
25808   while ( p!=null ) {
25809     if ( type(p)==text_code ) {
25810       if ( font_n(p)!=null_font ) {
25811         mp->font_sizes[font_n(p)] = diov;
25812         mp_mark_string_chars(mp, font_n(p),text_p(p));
25813             if ( mp_has_fm_entry(mp,font_n(p),NULL) )
25814           mp->font_ps_name[font_n(p)] = mp_fm_font_name(mp,font_n(p));
25815       }
25816     }
25817     p=link(p);
25818   }
25819 }
25820
25821 @ @<Update encoding names@>=
25822 for (f=null_font+1;f<=mp->last_fnum;f++) {
25823   p=link(dummy_loc(h));
25824   while ( p!=null ) {
25825     if ( type(p)==text_code )
25826       if ( font_n(p)!=null_font )
25827             if ( mp_has_fm_entry(mp,font_n(p),NULL) )
25828           if ( mp->font_enc_name[font_n(p)]==NULL )
25829             mp->font_enc_name[font_n(p)] = mp_fm_encoding_name(mp,font_n(p));
25830     p=link(p);
25831   }
25832 }
25833
25834 @ These special comments described in the {\sl PostScript Language Reference
25835 Manual}, 2nd.~edition are understood by some \ps-reading programs.
25836 We can't normally output ``conforming'' \ps\ because
25837 the structuring conventions don't allow us to say ``Please make sure the
25838 following characters are downloaded and define the \.{fshow} macro to access
25839 them.''
25840
25841 The exact bounding box is written out if |prologues<0|, although this
25842 is not standard \ps, since it allows \TeX\ to calculate the box dimensions
25843 accurately. (Overfull boxes are avoided if an illustration is made to
25844 match a given \.{\char`\\hsize}.)
25845
25846 @<Print the initial comment and give the bounding box for edge...@>=
25847 mp_print(mp, "%!PS");
25848 if ( mp->internal[prologues]>0 ) mp_print(mp, "-Adobe-3.0 EPSF-3.0");
25849 mp_print_nl(mp, "%%BoundingBox: ");
25850 mp_set_bbox(mp, h,true);
25851 if ( minx_val(h)>maxx_val(h) ) mp_print(mp, "0 0 0 0");
25852 else if ( mp->internal[prologues]<0 ) {
25853   mp_ps_pair_out(mp, minx_val(h),miny_val(h));
25854   mp_ps_pair_out(mp, maxx_val(h),maxy_val(h));
25855 } else { 
25856   mp_ps_pair_out(mp, mp_floor_scaled(mp, minx_val(h)),mp_floor_scaled(mp, miny_val(h)));
25857   mp_ps_pair_out(mp, -mp_floor_scaled(mp, -maxx_val(h)),-mp_floor_scaled(mp, -maxy_val(h)));
25858 }
25859 mp_print_nl(mp, "%%HiResBoundingBox: ");
25860 if ( minx_val(h)>maxx_val(h) ) mp_print(mp, "0 0 0 0");
25861 else {
25862   mp_ps_pair_out(mp, minx_val(h),miny_val(h));
25863   mp_ps_pair_out(mp, maxx_val(h),maxy_val(h));
25864 }
25865 mp_print_nl(mp, "%%Creator: MetaPost ");
25866 mp_print(mp, metapost_version);
25867 mp_print_nl(mp, "%%CreationDate: ");
25868 mp_print_int(mp, mp_round_unscaled(mp, mp->internal[year])); mp_print_char(mp, '.');
25869 mp_print_dd(mp, mp_round_unscaled(mp, mp->internal[month])); mp_print_char(mp, '.');
25870 mp_print_dd(mp, mp_round_unscaled(mp, mp->internal[day])); mp_print_char(mp, ':');
25871 t=mp_round_unscaled(mp, mp->internal[mp_time]);
25872 mp_print_dd(mp, t / 60); mp_print_dd(mp, t % 60);
25873 mp_print_nl(mp, "%%Pages: 1");
25874 @<List all the fonts and magnifications for edge structure~|h|@>;
25875 mp_print_ln(mp)
25876
25877 @ @<List all the fonts and magnifications for edge structure~|h|@>=
25878 @<Scan all the text nodes and set the |font_sizes| lists;
25879   if |internal[prologues]<=0| list the sizes selected by |choose_scale|,
25880   apply |unmark_font| to each font encountered, and call |mark_string|
25881   whenever the size index is zero@>;
25882 ldf = mp_print_font_comments (mp, (mp->internal[prologues]>>16), null, h)
25883
25884 @ @<Scan all the text nodes and set the |font_sizes| lists;...@>=
25885 for (f=null_font+1;f<=mp->last_fnum;f++) 
25886   mp->font_sizes[f]=null;
25887 p=link(dummy_loc(h));
25888 while ( p!=null ) {
25889   if ( type(p)==text_code ) {
25890     if ( font_n(p)!=null_font ) {
25891       f=font_n(p);
25892       if ( mp->internal[prologues]>0 ) {
25893         mp->font_sizes[f]=diov;
25894       } else { 
25895         if ( mp->font_sizes[f]==null ) mp_unmark_font(mp, f);
25896         name_type(p)=mp_size_index(mp, f,mp_choose_scale(mp, p));
25897         if ( name_type(p)==0 )
25898           mp_mark_string_chars(mp, f,text_p(p));
25899       }
25900     }
25901   }
25902   p=link(p);
25903 }
25904
25905 @ @<Cases for translating graphical object~|p| into \ps@>=
25906 case mp_start_clip_code: 
25907   mp_print_nl(mp, ""); mp_print_cmd(mp, "gsave ","q ");
25908   mp_ps_path_out(mp, path_p(p));
25909   mp_ps_print_cmd(mp, " clip"," W");
25910   mp_print_ln(mp);
25911   if ( mp->internal[restore_clip_color]>0 )
25912     mp_unknown_graphics_state(mp, 1);
25913   break;
25914 case mp_stop_clip_code: 
25915   mp_print_nl(mp, ""); mp_print_cmd(mp, "grestore","Q");
25916   mp_print_ln(mp);
25917   if ( mp->internal[restore_clip_color]>0 )
25918     mp_unknown_graphics_state(mp, 2);
25919   else
25920     mp_unknown_graphics_state(mp, -1);
25921   break;
25922
25923 @ @<Cases for translating graphical object~|p| into \ps@>=
25924 case fill_code: 
25925   if ( pen_p(p)==null ) mp_ps_fill_out(mp, path_p(p));
25926   else if ( pen_is_elliptical(pen_p(p)) ) mp_stroke_ellipse(mp, p,true);
25927   else { 
25928     mp_do_outer_envelope(mp, mp_copy_path(mp, path_p(p)), p);
25929     mp_do_outer_envelope(mp, mp_htap_ypoc(mp, path_p(p)), p);
25930   }
25931   if ( (post_script(p))!=null ) {
25932     mp_print_nl (mp, str(post_script(p))); mp_print_ln(mp);
25933   };
25934   break;
25935 case stroked_code:
25936   if ( pen_is_elliptical(pen_p(p)) ) mp_stroke_ellipse(mp, p,false);
25937   else { 
25938     q=mp_copy_path(mp, path_p(p));
25939     t=lcap_val(p);
25940     @<Break the cycle and set |t:=1| if path |q| is cyclic@>;
25941     q=mp_make_envelope(mp, q,pen_p(p),ljoin_val(p),t,miterlim_val(p));
25942     mp_ps_fill_out(mp, q);
25943     mp_toss_knot_list(mp, q);
25944   };
25945   if ( (post_script(p))!=null ) {
25946     mp_print_nl (mp, str(post_script(p))); mp_print_ln(mp);
25947   };
25948   break;
25949
25950 @ The envelope of a cyclic path~|q| could be computed by calling
25951 |make_envelope| once for |q| and once for its reversal.  We don't do this
25952 because it would fail color regions that are covered by the pen regardless
25953 of where it is placed on~|q|.
25954
25955 @<Break the cycle and set |t:=1| if path |q| is cyclic@>=
25956 if ( left_type(q)!=endpoint ) { 
25957   left_type(mp_insert_knot(mp, q,x_coord(q),y_coord(q)))=endpoint;
25958   right_type(q)=endpoint;
25959   q=link(q);
25960   t=1;
25961 }
25962
25963 @ @<Cases for translating graphical object~|p| into \ps@>=
25964 case text_code: 
25965   if ( (font_n(p)!=null_font) && (length(text_p(p))>0) ) {
25966     if ( mp->internal[prologues]>0 )
25967       scf=mp_choose_scale(mp, p);
25968     else 
25969       scf=mp_indexed_size(mp, font_n(p), name_type(p));
25970     @<Shift or transform as necessary before outputting text node~|p| at scale
25971       factor~|scf|; set |transformed:=true| if the original transformation must
25972       be restored@>;
25973     mp_ps_string_out(mp, str(text_p(p)));
25974     mp_ps_name_out(mp, mp->font_name[font_n(p)],false);
25975     @<Print the size information and \ps\ commands for text node~|p|@>;
25976     mp_print_ln(mp);
25977   }
25978   if ( (post_script(p))!=null ) {
25979     mp_print_nl (mp, str(post_script(p))); mp_print_ln(mp);
25980   }
25981   break;
25982
25983 @ @<Print the size information and \ps\ commands for text node~|p|@>=
25984 ps_room(18);
25985 mp_print_char(mp, ' ');
25986 ds=(mp->font_dsize[font_n(p)]+8) / 16;
25987 mp_print_scaled(mp, mp_take_scaled(mp, ds,scf));
25988 mp_print(mp, " fshow");
25989 if ( transformed ) 
25990   mp_ps_print_cmd(mp, " grestore"," Q")
25991
25992 @ @<Shift or transform as necessary before outputting text node~|p| at...@>=
25993 transformed=(txx_val(p)!=scf)||(tyy_val(p)!=scf)||
25994             (txy_val(p)!=0)||(tyx_val(p)!=0);
25995 if ( transformed ) {
25996   mp_print_cmd(mp, "gsave [", "q [");
25997   mp_ps_pair_out(mp, mp_make_scaled(mp, txx_val(p),scf),
25998                      mp_make_scaled(mp, tyx_val(p),scf));
25999   mp_ps_pair_out(mp, mp_make_scaled(mp, txy_val(p),scf),
26000                      mp_make_scaled(mp, tyy_val(p),scf));
26001   mp_ps_pair_out(mp, tx_val(p),ty_val(p));
26002   mp_ps_print_cmd(mp, "] concat 0 0 moveto","] t 0 0 m");
26003 } else { 
26004   mp_ps_pair_out(mp, tx_val(p),ty_val(p));
26005   mp_ps_print_cmd(mp, "moveto","m");
26006 }
26007 mp_print_ln(mp)
26008
26009 @ Now that we've finished |ship_out|, let's look at the other commands
26010 by which a user can send things to the \.{GF} file.
26011
26012 @ @<Determine if a character has been shipped out@>=
26013
26014   mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256;
26015   if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
26016   boolean_reset(mp->char_exists[mp->cur_exp]);
26017   mp->cur_type=mp_boolean_type;
26018 }
26019
26020 @ @<Glob...@>=
26021 psout_data ps;
26022
26023 @ @<Allocate or initialize ...@>=
26024 mp_backend_initialize(mp);
26025
26026 @ @<Dealloc...@>=
26027 mp_backend_free(mp);
26028
26029
26030 @* \[45] Dumping and undumping the tables.
26031 After \.{INIMP} has seen a collection of macros, it
26032 can write all the necessary information on an auxiliary file so
26033 that production versions of \MP\ are able to initialize their
26034 memory at high speed. The present section of the program takes
26035 care of such output and input. We shall consider simultaneously
26036 the processes of storing and restoring,
26037 so that the inverse relation between them is clear.
26038 @.INIMP@>
26039
26040 The global variable |mem_ident| is a string that is printed right
26041 after the |banner| line when \MP\ is ready to start. For \.{INIMP} this
26042 string says simply `\.{(INIMP)}'; for other versions of \MP\ it says,
26043 for example, `\.{(mem=plain 90.4.14)}', showing the year,
26044 month, and day that the mem file was created. We have |mem_ident=0|
26045 before \MP's tables are loaded.
26046
26047 @<Glob...@>=
26048 char * mem_ident;
26049
26050 @ @<Set init...@>=
26051 mp->mem_ident=NULL;
26052
26053 @ @<Initialize table entries...@>=
26054 if (mp->ini_version) 
26055   mp->mem_ident=xstrdup(" (INIMP)");
26056
26057 @ @<Declare act...@>=
26058 void mp_store_mem_file (MP mp) ;
26059
26060 @ @c void mp_store_mem_file (MP mp) {
26061   integer k;  /* all-purpose index */
26062   pointer p,q; /* all-purpose pointers */
26063   integer x; /* something to dump */
26064   four_quarters w; /* four ASCII codes */
26065   memory_word WW;
26066   @<Create the |mem_ident|, open the mem file,
26067     and inform the user that dumping has begun@>;
26068   @<Dump constants for consistency check@>;
26069   @<Dump the string pool@>;
26070   @<Dump the dynamic memory@>;
26071   @<Dump the table of equivalents and the hash table@>;
26072   @<Dump a few more things and the closing check word@>;
26073   @<Close the mem file@>;
26074 }
26075
26076 @ Corresponding to the procedure that dumps a mem file, we also have a function
26077 that reads~one~in. The function returns |false| if the dumped mem is
26078 incompatible with the present \MP\ table sizes, etc.
26079
26080 @d off_base 6666 /* go here if the mem file is unacceptable */
26081 @d too_small(A) { wake_up_terminal;
26082   wterm_ln("---! Must increase the "); wterm((A));
26083 @.Must increase the x@>
26084   goto OFF_BASE;
26085   }
26086
26087 @c 
26088 boolean mp_load_mem_file (MP mp) {
26089   integer k; /* all-purpose index */
26090   pointer p,q; /* all-purpose pointers */
26091   integer x; /* something undumped */
26092   str_number s; /* some temporary string */
26093   four_quarters w; /* four ASCII codes */
26094   memory_word WW;
26095   @<Undump constants for consistency check@>;
26096   @<Undump the string pool@>;
26097   @<Undump the dynamic memory@>;
26098   @<Undump the table of equivalents and the hash table@>;
26099   @<Undump a few more things and the closing check word@>;
26100   return true; /* it worked! */
26101 OFF_BASE: 
26102   wake_up_terminal;
26103   wterm_ln("(Fatal mem file error; I'm stymied)\n");
26104 @.Fatal mem file error@>
26105    return false;
26106 }
26107
26108 @ @<Declarations@>=
26109 boolean mp_load_mem_file (MP mp) ;
26110
26111 @ Mem files consist of |memory_word| items, and we use the following
26112 macros to dump words of different types:
26113
26114 @d dump_wd(A)   { WW=(A);      fwrite(&WW,sizeof(WW),1,mp->mem_file); }
26115 @d dump_int(A)  { WW.cint=(A); fwrite(&WW,sizeof(WW),1,mp->mem_file); }
26116 @d dump_hh(A)   { WW.hh=(A);   fwrite(&WW,sizeof(WW),1,mp->mem_file); }
26117 @d dump_qqqq(A) { WW.qqqq=(A); fwrite(&WW,sizeof(WW),1,mp->mem_file); }
26118 @d dump_string(A) { dump_int(strlen(A)+1);
26119                     fwrite(A,strlen(A)+1,1,mp->mem_file); }
26120
26121 @<Glob...@>=
26122 FILE * mem_file; /* for input or output of mem information */
26123
26124 @ The inverse macros are slightly more complicated, since we need to check
26125 the range of the values we are reading in. We say `|undump(a)(b)(x)|' to
26126 read an integer value |x| that is supposed to be in the range |a<=x<=b|.
26127
26128 @d undump_wd(A)   { fread(&WW,sizeof(WW),1,mp->mem_file); (A)=WW; }
26129 @d undump_int(A)  { fread(&WW,sizeof(WW),1,mp->mem_file); (A)=WW.cint; }
26130 @d undump_hh(A)   { fread(&WW,sizeof(WW),1,mp->mem_file); (A)=WW.hh; }
26131 @d undump_qqqq(A) { fread(&WW,sizeof(WW),1,mp->mem_file); (A)=WW.qqqq; }
26132 @d undump_strings(A,B,C) { 
26133    undump_int(x); if ( (x<(A)) || (x>(B)) ) goto OFF_BASE; else (C)=str(x); }
26134 @d undump(A,B,C) { undump_int(x); if ( (x<(A)) || (x>(int)(B)) ) goto OFF_BASE; else (C)=x; }
26135 @d undump_size(A,B,C,D) { undump_int(x);
26136                if (x<(A)) goto OFF_BASE; 
26137                if (x>(B)) { too_small((C)); } else {(D)=x;} }
26138 @d undump_string(A) { integer XX=0; undump_int(XX);
26139                       A = xmalloc(XX,sizeof(char));
26140                       fread(A,XX,1,mp->mem_file); }
26141
26142 @ The next few sections of the program should make it clear how we use the
26143 dump/undump macros.
26144
26145 @<Dump constants for consistency check@>=
26146 dump_int(mp->mem_top);
26147 dump_int(mp->hash_size);
26148 dump_int(mp->hash_prime)
26149 dump_int(mp->param_size);
26150 dump_int(mp->max_in_open);
26151
26152 @ Sections of a \.{WEB} program that are ``commented out'' still contribute
26153 strings to the string pool; therefore \.{INIMP} and \MP\ will have
26154 the same strings. (And it is, of course, a good thing that they do.)
26155 @.WEB@>
26156 @^string pool@>
26157
26158 @<Undump constants for consistency check@>=
26159 undump_int(x); mp->mem_top = x;
26160 undump_int(x); if (mp->hash_size != x) goto OFF_BASE;
26161 undump_int(x); if (mp->hash_prime != x) goto OFF_BASE;
26162 undump_int(x); if (mp->param_size != x) goto OFF_BASE;
26163 undump_int(x); if (mp->max_in_open != x) goto OFF_BASE
26164
26165 @ We do string pool compaction to avoid dumping unused strings.
26166
26167 @d dump_four_ASCII 
26168   w.b0=qi(mp->str_pool[k]); w.b1=qi(mp->str_pool[k+1]);
26169   w.b2=qi(mp->str_pool[k+2]); w.b3=qi(mp->str_pool[k+3]);
26170   dump_qqqq(w)
26171
26172 @<Dump the string pool@>=
26173 mp_do_compaction(mp, mp->pool_size);
26174 dump_int(mp->pool_ptr);
26175 dump_int(mp->max_str_ptr);
26176 dump_int(mp->str_ptr);
26177 k=0;
26178 while ( (mp->next_str[k]==k+1) && (k<=mp->max_str_ptr) ) 
26179   incr(k);
26180 dump_int(k);
26181 while ( k<=mp->max_str_ptr ) { 
26182   dump_int(mp->next_str[k]); incr(k);
26183 }
26184 k=0;
26185 while (1)  { 
26186   dump_int((mp->str_start[k])); 
26187   if ( k==mp->str_ptr ) {
26188     break;
26189   } else { 
26190     k=mp->next_str[k]; 
26191   }
26192 };
26193 k=0;
26194 while (k+4<mp->pool_ptr ) { 
26195   dump_four_ASCII; k=k+4; 
26196 }
26197 k=mp->pool_ptr-4; dump_four_ASCII;
26198 mp_print_ln(mp); mp_print(mp, "at most "); mp_print_int(mp, mp->max_str_ptr);
26199 mp_print(mp, " strings of total length ");
26200 mp_print_int(mp, mp->pool_ptr)
26201
26202 @ @d undump_four_ASCII 
26203   undump_qqqq(w);
26204   mp->str_pool[k]=qo(w.b0); mp->str_pool[k+1]=qo(w.b1);
26205   mp->str_pool[k+2]=qo(w.b2); mp->str_pool[k+3]=qo(w.b3)
26206
26207 @<Undump the string pool@>=
26208 undump_int(mp->pool_ptr);
26209 mp_reallocate_pool(mp, mp->pool_ptr) ;
26210 undump_int(mp->max_str_ptr);
26211 mp_reallocate_strings (mp,mp->max_str_ptr) ;
26212 undump(0,mp->max_str_ptr,mp->str_ptr);
26213 undump(0,mp->max_str_ptr+1,s);
26214 for (k=0;k<=s-1;k++) 
26215   mp->next_str[k]=k+1;
26216 for (k=s;k<=mp->max_str_ptr;k++) 
26217   undump(s+1,mp->max_str_ptr+1,mp->next_str[k]);
26218 mp->fixed_str_use=0;
26219 k=0;
26220 while (1) { 
26221   undump(0,mp->pool_ptr,mp->str_start[k]);
26222   if ( k==mp->str_ptr ) break;
26223   mp->str_ref[k]=max_str_ref;
26224   incr(mp->fixed_str_use);
26225   mp->last_fixed_str=k; k=mp->next_str[k];
26226 }
26227 k=0;
26228 while ( k+4<mp->pool_ptr ) { 
26229   undump_four_ASCII; k=k+4;
26230 }
26231 k=mp->pool_ptr-4; undump_four_ASCII;
26232 mp->init_str_use=mp->fixed_str_use; mp->init_pool_ptr=mp->pool_ptr;
26233 mp->max_pool_ptr=mp->pool_ptr;
26234 mp->strs_used_up=mp->fixed_str_use;
26235 mp->pool_in_use=mp->str_start[mp->str_ptr]; mp->strs_in_use=mp->fixed_str_use;
26236 mp->max_pl_used=mp->pool_in_use; mp->max_strs_used=mp->strs_in_use;
26237 mp->pact_count=0; mp->pact_chars=0; mp->pact_strs=0;
26238
26239 @ By sorting the list of available spaces in the variable-size portion of
26240 |mem|, we are usually able to get by without having to dump very much
26241 of the dynamic memory.
26242
26243 We recompute |var_used| and |dyn_used|, so that \.{INIMP} dumps valid
26244 information even when it has not been gathering statistics.
26245
26246 @<Dump the dynamic memory@>=
26247 mp_sort_avail(mp); mp->var_used=0;
26248 dump_int(mp->lo_mem_max); dump_int(mp->rover);
26249 p=0; q=mp->rover; x=0;
26250 do {  
26251   for (k=p;k<= q+1;k++) 
26252     dump_wd(mp->mem[k]);
26253   x=x+q+2-p; mp->var_used=mp->var_used+q-p;
26254   p=q+node_size(q); q=rlink(q);
26255 } while (q!=mp->rover);
26256 mp->var_used=mp->var_used+mp->lo_mem_max-p; 
26257 mp->dyn_used=mp->mem_end+1-mp->hi_mem_min;
26258 for (k=p;k<= mp->lo_mem_max;k++ ) 
26259   dump_wd(mp->mem[k]);
26260 x=x+mp->lo_mem_max+1-p;
26261 dump_int(mp->hi_mem_min); dump_int(mp->avail);
26262 for (k=mp->hi_mem_min;k<=mp->mem_end;k++ ) 
26263   dump_wd(mp->mem[k]);
26264 x=x+mp->mem_end+1-mp->hi_mem_min;
26265 p=mp->avail;
26266 while ( p!=null ) { 
26267   decr(mp->dyn_used); p=link(p);
26268 }
26269 dump_int(mp->var_used); dump_int(mp->dyn_used);
26270 mp_print_ln(mp); mp_print_int(mp, x);
26271 mp_print(mp, " memory locations dumped; current usage is ");
26272 mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used)
26273
26274 @ @<Undump the dynamic memory@>=
26275 undump(lo_mem_stat_max+1000,hi_mem_stat_min-1,mp->lo_mem_max);
26276 undump(lo_mem_stat_max+1,mp->lo_mem_max,mp->rover);
26277 p=0; q=mp->rover;
26278 do {  
26279   for (k=p;k<= q+1; k++) 
26280     undump_wd(mp->mem[k]);
26281   p=q+node_size(q);
26282   if ( (p>mp->lo_mem_max)||((q>=rlink(q))&&(rlink(q)!=mp->rover)) ) 
26283     goto OFF_BASE;
26284   q=rlink(q);
26285 } while (q!=mp->rover);
26286 for (k=p;k<=mp->lo_mem_max;k++ ) 
26287   undump_wd(mp->mem[k]);
26288 undump(mp->lo_mem_max+1,hi_mem_stat_min,mp->hi_mem_min);
26289 undump(null,mp->mem_top,mp->avail); mp->mem_end=mp->mem_top;
26290 for (k=mp->hi_mem_min;k<= mp->mem_end;k++) 
26291   undump_wd(mp->mem[k]);
26292 undump_int(mp->var_used); undump_int(mp->dyn_used)
26293
26294 @ A different scheme is used to compress the hash table, since its lower region
26295 is usually sparse. When |text(p)<>0| for |p<=hash_used|, we output three
26296 words: |p|, |hash[p]|, and |eqtb[p]|. The hash table is, of course, densely
26297 packed for |p>=hash_used|, so the remaining entries are output in~a~block.
26298
26299 @<Dump the table of equivalents and the hash table@>=
26300 dump_int(mp->hash_used); 
26301 mp->st_count=frozen_inaccessible-1-mp->hash_used;
26302 for (p=1;p<=mp->hash_used;p++) {
26303   if ( text(p)!=0 ) {
26304      dump_int(p); dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]); incr(mp->st_count);
26305   }
26306 }
26307 for (p=mp->hash_used+1;p<=(int)hash_end;p++) {
26308   dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]);
26309 }
26310 dump_int(mp->st_count);
26311 mp_print_ln(mp); mp_print_int(mp, mp->st_count); mp_print(mp, " symbolic tokens")
26312
26313 @ @<Undump the table of equivalents and the hash table@>=
26314 undump(1,frozen_inaccessible,mp->hash_used); 
26315 p=0;
26316 do {  
26317   undump(p+1,mp->hash_used,p); 
26318   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
26319 } while (p!=mp->hash_used);
26320 for (p=mp->hash_used+1;p<=(int)hash_end;p++ )  { 
26321   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
26322 }
26323 undump_int(mp->st_count)
26324
26325 @ We have already printed a lot of statistics, so we set |tracing_stats:=0|
26326 to prevent them appearing again.
26327
26328 @<Dump a few more things and the closing check word@>=
26329 dump_int(mp->max_internal);
26330 dump_int(mp->int_ptr);
26331 for (k=1;k<= mp->int_ptr;k++ ) { 
26332   dump_int(mp->internal[k]); 
26333   dump_string(mp->int_name[k]);
26334 }
26335 dump_int(mp->start_sym); 
26336 dump_int(mp->interaction); 
26337 dump_string(mp->mem_ident);
26338 dump_int(mp->bg_loc); dump_int(mp->eg_loc); dump_int(mp->serial_no); dump_int(69073);
26339 mp->internal[tracing_stats]=0
26340
26341 @ @<Undump a few more things and the closing check word@>=
26342 undump_int(x);
26343 if (x>mp->max_internal) mp_grow_internals(mp,x);
26344 undump_int(mp->int_ptr);
26345 for (k=1;k<= mp->int_ptr;k++) { 
26346   undump_int(mp->internal[k]);
26347   undump_string(mp->int_name[k]);
26348 }
26349 undump(0,frozen_inaccessible,mp->start_sym);
26350 if (mp->interaction==mp_unspecified_mode) {
26351   undump(mp_unspecified_mode,mp_error_stop_mode,mp->interaction);
26352 } else {
26353   undump(mp_unspecified_mode,mp_error_stop_mode,x);
26354 }
26355 undump_string(mp->mem_ident);
26356 undump(1,hash_end,mp->bg_loc);
26357 undump(1,hash_end,mp->eg_loc);
26358 undump_int(mp->serial_no);
26359 undump_int(x); 
26360 if ( (x!=69073)|| feof(mp->mem_file) ) goto OFF_BASE
26361
26362 @ @<Create the |mem_ident|...@>=
26363
26364   xfree(mp->mem_ident);
26365   mp->mem_ident = xmalloc(256,1);
26366   snprintf(mp->mem_ident,256," (mem=%s %i.%i.%i)", 
26367            mp->job_name,
26368            (int)(mp_round_unscaled(mp, mp->internal[year]) % 100),
26369            (int)mp_round_unscaled(mp, mp->internal[month]),
26370            (int)mp_round_unscaled(mp, mp->internal[day]));
26371   mp_pack_job_name(mp, mem_extension);
26372   while (! mp_w_open_out(mp, &mp->mem_file) )
26373     mp_prompt_file_name(mp, "mem file name", mem_extension);
26374   mp_print_nl(mp, "Beginning to dump on file ");
26375 @.Beginning to dump...@>
26376   mp_print(mp, mp->name_of_file); 
26377   mp_print_nl(mp, mp->mem_ident);
26378 }
26379
26380 @ @<Dealloc variables@>=
26381 xfree(mp->mem_ident);
26382
26383 @ @<Close the mem file@>=
26384 fclose(mp->mem_file)
26385
26386 @* \[46] The main program.
26387 This is it: the part of \MP\ that executes all those procedures we have
26388 written.
26389
26390 Well---almost. We haven't put the parsing subroutines into the
26391 program yet; and we'd better leave space for a few more routines that may
26392 have been forgotten.
26393
26394 @c @<Declare the basic parsing subroutines@>;
26395 @<Declare miscellaneous procedures that were declared |forward|@>;
26396 @<Last-minute procedures@>
26397
26398 @ We've noted that there are two versions of \MP. One, called \.{INIMP},
26399 @.INIMP@>
26400 has to be run first; it initializes everything from scratch, without
26401 reading a mem file, and it has the capability of dumping a mem file.
26402 The other one is called `\.{VIRMP}'; it is a ``virgin'' program that needs
26403 @.VIRMP@>
26404 to input a mem file in order to get started. \.{VIRMP} typically has
26405 a bit more memory capacity than \.{INIMP}, because it does not need the
26406 space consumed by the dumping/undumping routines and the numerous calls on
26407 |primitive|, etc.
26408
26409 The \.{VIRMP} program cannot read a mem file instantaneously, of course;
26410 the best implementations therefore allow for production versions of \MP\ that
26411 not only avoid the loading routine for \PASCAL\ object code, they also have
26412 a mem file pre-loaded. 
26413
26414 @<Glob...@>=
26415 boolean ini_version; /* are we iniMP? */
26416
26417 @ @<Option variables@>=
26418 boolean ini_version; /* are we iniMP? */
26419
26420 @ @<Set |ini_version|@>=
26421 mp->ini_version = (opt.ini_version ? true : false);
26422
26423 @ Here we do whatever is needed to complete \MP's job gracefully on the
26424 local operating system. The code here might come into play after a fatal
26425 error; it must therefore consist entirely of ``safe'' operations that
26426 cannot produce error messages. For example, it would be a mistake to call
26427 |str_room| or |make_string| at this time, because a call on |overflow|
26428 might lead to an infinite loop.
26429 @^system dependencies@>
26430
26431 This program doesn't bother to close the input files that may still be open.
26432
26433 @<Last-minute...@>=
26434 void mp_close_files_and_terminate (MP mp) {
26435   integer k; /* all-purpose index */
26436   integer LH; /* the length of the \.{TFM} header, in words */
26437   int lk_offset; /* extra words inserted at beginning of |lig_kern| array */
26438   pointer p; /* runs through a list of \.{TFM} dimensions */
26439   @<Close all open files in the |rd_file| and |wr_file| arrays@>;
26440   if ( mp->internal[tracing_stats]>0 )
26441     @<Output statistics about this job@>;
26442   wake_up_terminal; 
26443   @<Do all the finishing work on the \.{TFM} file@>;
26444   @<Explain what output files were written@>;
26445   if ( mp->log_opened ){ 
26446     wlog_cr;
26447     fclose(mp->log_file); mp->selector=mp->selector-2;
26448     if ( mp->selector==term_only ) {
26449       mp_print_nl(mp, "Transcript written on ");
26450 @.Transcript written...@>
26451       mp_print(mp, mp->log_name); mp_print_char(mp, '.');
26452     }
26453   }
26454   mp_print_ln(mp);
26455 }
26456
26457 @ @<Declarations@>=
26458 void mp_close_files_and_terminate (MP mp) ;
26459
26460 @ @<Close all open files in the |rd_file| and |wr_file| arrays@>=
26461 for (k=0;k<=(int)mp->read_files-1;k++ ) {
26462   if ( mp->rd_fname[k]!=NULL ) fclose(mp->rd_file[k]);
26463 }
26464 for (k=0;k<=(int)mp->write_files-1;k++) {
26465   if ( mp->wr_fname[k]!=NULL ) fclose(mp->wr_file[k]);
26466 }
26467
26468 @ We want to produce a \.{TFM} file if and only if |fontmaking| is positive.
26469
26470 We reclaim all of the variable-size memory at this point, so that
26471 there is no chance of another memory overflow after the memory capacity
26472 has already been exceeded.
26473
26474 @<Do all the finishing work on the \.{TFM} file@>=
26475 if ( mp->internal[fontmaking]>0 ) {
26476   @<Make the dynamic memory into one big available node@>;
26477   @<Massage the \.{TFM} widths@>;
26478   mp_fix_design_size(mp); mp_fix_check_sum(mp);
26479   @<Massage the \.{TFM} heights, depths, and italic corrections@>;
26480   mp->internal[fontmaking]=0; /* avoid loop in case of fatal error */
26481   @<Finish the \.{TFM} file@>;
26482 }
26483
26484 @ @<Make the dynamic memory into one big available node@>=
26485 mp->rover=lo_mem_stat_max+1; link(mp->rover)=empty_flag; mp->lo_mem_max=mp->hi_mem_min-1;
26486 if ( mp->lo_mem_max-mp->rover>max_halfword ) mp->lo_mem_max=max_halfword+mp->rover;
26487 node_size(mp->rover)=mp->lo_mem_max-mp->rover; 
26488 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
26489 link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null
26490
26491 @ The present section goes directly to the log file instead of using
26492 |print| commands, because there's no need for these strings to take
26493 up |str_pool| memory when a non-{\bf stat} version of \MP\ is being used.
26494
26495 @<Output statistics...@>=
26496 if ( mp->log_opened ) { 
26497   char s[128];
26498   wlog_ln(" ");
26499   wlog_ln("Here is how much of MetaPost's memory you used:");
26500 @.Here is how much...@>
26501   snprintf(s,128," %i string%s out of %i",(int)mp->max_strs_used-mp->init_str_use,
26502           (mp->max_strs_used!=mp->init_str_use+1 ? "s" : ""),
26503           (int)(mp->max_strings-1-mp->init_str_use));
26504   wlog_ln(s);
26505   snprintf(s,128," %i string characters out of %i",
26506            (int)mp->max_pl_used-mp->init_pool_ptr,
26507            (int)mp->pool_size-mp->init_pool_ptr);
26508   wlog_ln(s);
26509   snprintf(s,128," %i words of memory out of %i",
26510            (int)mp->lo_mem_max+mp->mem_end-mp->hi_mem_min+2,
26511            (int)mp->mem_end+1);
26512   wlog_ln(s);
26513   snprintf(s,128," %i symbolic tokens out of %i", (int)mp->st_count, (int)mp->hash_size);
26514   wlog_ln(s);
26515   snprintf(s,128," %ii, %in, %ip, %ib stack positions out of %ii, %in, %ip, %ib",
26516            (int)mp->max_in_stack,(int)mp->int_ptr,
26517            (int)mp->max_param_stack,(int)mp->max_buf_stack+1,
26518            (int)mp->stack_size,(int)mp->max_internal,(int)mp->param_size,(int)mp->buf_size);
26519   wlog_ln(s);
26520   snprintf(s,128," %i string compactions (moved %i characters, %i strings)",
26521           (int)mp->pact_count,(int)mp->pact_chars,(int)mp->pact_strs);
26522   wlog_ln(s);
26523 }
26524
26525 @ We get to the |final_cleanup| routine when \&{end} or \&{dump} has
26526 been scanned.
26527
26528 @<Last-minute...@>=
26529 void mp_final_cleanup (MP mp) {
26530   small_number c; /* 0 for \&{end}, 1 for \&{dump} */
26531   c=mp->cur_mod;
26532   if ( mp->job_name==NULL ) mp_open_log_file(mp);
26533   while ( mp->input_ptr>0 ) {
26534     if ( token_state ) mp_end_token_list(mp);
26535     else  mp_end_file_reading(mp);
26536   }
26537   while ( mp->loop_ptr!=null ) mp_stop_iteration(mp);
26538   while ( mp->open_parens>0 ) { 
26539     mp_print(mp, " )"); decr(mp->open_parens);
26540   };
26541   while ( mp->cond_ptr!=null ) {
26542     mp_print_nl(mp, "(end occurred when ");
26543 @.end occurred...@>
26544     mp_print_cmd_mod(mp, fi_or_else,mp->cur_if);
26545     /* `\.{if}' or `\.{elseif}' or `\.{else}' */
26546     if ( mp->if_line!=0 ) {
26547       mp_print(mp, " on line "); mp_print_int(mp, mp->if_line);
26548     }
26549     mp_print(mp, " was incomplete)");
26550     mp->if_line=if_line_field(mp->cond_ptr);
26551     mp->cur_if=name_type(mp->cond_ptr); mp->cond_ptr=link(mp->cond_ptr);
26552   }
26553   if ( mp->history!=spotless )
26554     if ( ((mp->history==warning_issued)||(mp->interaction<mp_error_stop_mode)) )
26555       if ( mp->selector==term_and_log ) {
26556     mp->selector=term_only;
26557     mp_print_nl(mp, "(see the transcript file for additional information)");
26558 @.see the transcript file...@>
26559     mp->selector=term_and_log;
26560   }
26561   if ( c==1 ) {
26562     if (mp->ini_version) {
26563       mp_store_mem_file(mp); return;
26564     }
26565     mp_print_nl(mp, "(dump is performed only by INIMP)"); return;
26566 @.dump...only by INIMP@>
26567   }
26568 }
26569
26570 @ @<Declarations@>=
26571 void mp_final_cleanup (MP mp) ;
26572 void mp_init_prim (MP mp) ;
26573 void mp_init_tab (MP mp) ;
26574
26575 @ @<Last-minute...@>=
26576 void mp_init_prim (MP mp) { /* initialize all the primitives */
26577   @<Put each...@>;
26578 }
26579 @#
26580 void mp_init_tab (MP mp) { /* initialize other tables */
26581   integer k; /* all-purpose index */
26582   @<Initialize table entries (done by \.{INIMP} only)@>;
26583 }
26584
26585
26586 @ When we begin the following code, \MP's tables may still contain garbage;
26587 the strings might not even be present. Thus we must proceed cautiously to get
26588 bootstrapped in.
26589
26590 But when we finish this part of the program, \MP\ is ready to call on the
26591 |main_control| routine to do its work.
26592
26593 @<Get the first line...@>=
26594
26595   @<Initialize the input routines@>;
26596   if ( (mp->mem_ident==NULL)||(mp->buffer[loc]=='&') ) {
26597     if ( mp->mem_ident!=NULL ) mp_initialize(mp); /* erase preloaded mem */
26598     if ( ! mp_open_mem_file(mp) ) return false;
26599     if ( ! mp_load_mem_file(mp) ) {
26600       fclose( mp->mem_file); return false;
26601     }
26602     fclose( mp->mem_file);
26603     while ( (loc<limit)&&(mp->buffer[loc]==' ') ) incr(loc);
26604   }
26605   mp->buffer[limit]='%';
26606   mp_fix_date_and_time(mp);
26607   mp->sys_random_seed = (mp->get_random_seed)(mp);
26608   mp_init_randoms(mp, mp->sys_random_seed);
26609   @<Initialize the print |selector|...@>;
26610   if ( loc<limit ) if ( mp->buffer[loc]!='\\' ) 
26611     mp_start_input(mp); /* \&{input} assumed */
26612 }
26613
26614 @ @<Run inimpost commands@>=
26615 {
26616   mp_get_strings_started(mp);
26617   mp_init_tab(mp); /* initialize the tables */
26618   mp_init_prim(mp); /* call |primitive| for each primitive */
26619   mp->init_str_use=mp->str_ptr; mp->init_pool_ptr=mp->pool_ptr;
26620   mp->max_str_ptr=mp->str_ptr; mp->max_pool_ptr=mp->pool_ptr;
26621   mp_fix_date_and_time(mp);
26622 }
26623
26624
26625 @* \[47] Debugging.
26626 Once \MP\ is working, you should be able to diagnose most errors with
26627 the \.{show} commands and other diagnostic features. But for the initial
26628 stages of debugging, and for the revelation of really deep mysteries, you
26629 can compile \MP\ with a few more aids, including the \PASCAL\ runtime
26630 checks and its debugger. An additional routine called |debug_help|
26631 will also come into play when you type `\.D' after an error message;
26632 |debug_help| also occurs just before a fatal error causes \MP\ to succumb.
26633 @^debugging@>
26634 @^system dependencies@>
26635
26636 The interface to |debug_help| is primitive, but it is good enough when used
26637 with a \PASCAL\ debugger that allows you to set breakpoints and to read
26638 variables and change their values. After getting the prompt `\.{debug \#}', you
26639 type either a negative number (this exits |debug_help|), or zero (this
26640 goes to a location where you can set a breakpoint, thereby entering into
26641 dialog with the \PASCAL\ debugger), or a positive number |m| followed by
26642 an argument |n|. The meaning of |m| and |n| will be clear from the
26643 program below. (If |m=13|, there is an additional argument, |l|.)
26644 @.debug \#@>
26645
26646 @<Last-minute...@>=
26647 void mp_debug_help (MP mp) { /* routine to display various things */
26648   integer k;
26649   int l,m,n;
26650   while (1) { 
26651     wake_up_terminal;
26652     mp_print_nl(mp, "debug # (-1 to exit):"); update_terminal;
26653 @.debug \#@>
26654     m = 0;
26655     fscanf(mp->term_in,"%i",&m);
26656     if ( m<=0 )
26657       return;
26658     n = 0 ;
26659     fscanf(mp->term_in,"%i",&n);
26660     switch (m) {
26661     @<Numbered cases for |debug_help|@>;
26662     default: mp_print(mp, "?"); break;
26663     }
26664   }
26665 }
26666
26667 @ @<Numbered cases...@>=
26668 case 1: mp_print_word(mp, mp->mem[n]); /* display |mem[n]| in all forms */
26669   break;
26670 case 2: mp_print_int(mp, info(n));
26671   break;
26672 case 3: mp_print_int(mp, link(n));
26673   break;
26674 case 4: mp_print_int(mp, eq_type(n)); mp_print_char(mp, ':'); mp_print_int(mp, equiv(n));
26675   break;
26676 case 5: mp_print_variable_name(mp, n);
26677   break;
26678 case 6: mp_print_int(mp, mp->internal[n]);
26679   break;
26680 case 7: mp_do_show_dependencies(mp);
26681   break;
26682 case 9: mp_show_token_list(mp, n,null,100000,0);
26683   break;
26684 case 10: mp_print_str(mp, n);
26685   break;
26686 case 11: mp_check_mem(mp, n>0); /* check wellformedness; print new busy locations if |n>0| */
26687   break;
26688 case 12: mp_search_mem(mp, n); /* look for pointers to |n| */
26689   break;
26690 case 13: l = 0;  fscanf(mp->term_in,"%i",&l); mp_print_cmd_mod(mp, n,l); 
26691   break;
26692 case 14: for (k=0;k<=n;k++) mp_print_str(mp, mp->buffer[k]);
26693   break;
26694 case 15: mp->panicking=! mp->panicking;
26695   break;
26696
26697
26698 @ \MP\ used to have one single routine to print to both `write' files
26699 and the PostScript output. Web2c redefines ``Character |k| cannot be
26700 printed'', and that resulted in some bugs where 8-bit characters were
26701 written to the PostScript file (reported by Wlodek Bzyl).
26702
26703 Also, Hans Hagen requested spaces to be output as "\\040" instead of
26704 a plain space, since that makes it easier to parse the result file
26705 for postprocessing.
26706
26707 @<Character |k| is not allowed in PostScript output@>=
26708   (k<=' ')||(k>'~')
26709
26710 @ Saving the filename template
26711
26712 @<Save the filename template@>=
26713
26714   if ( mp->filename_template!=0 ) delete_str_ref(mp->filename_template);
26715   if ( length(mp->cur_exp)==0 ) mp->filename_template=0;
26716   else { 
26717     mp->filename_template=mp->cur_exp; add_str_ref(mp->filename_template);
26718   }
26719 }
26720
26721 @* \[48] System-dependent changes.
26722 This section should be replaced, if necessary, by any special
26723 modification of the program
26724 that are necessary to make \MP\ work at a particular installation.
26725 It is usually best to design your change file so that all changes to
26726 previous sections preserve the section numbering; then everybody's version
26727 will be consistent with the published program. More extensive changes,
26728 which introduce new sections, can be inserted here; then only the index
26729 itself will get a new section number.
26730 @^system dependencies@>
26731
26732 @* \[49] Index.
26733 Here is where you can find all uses of each identifier in the program,
26734 with underlined entries pointing to where the identifier was defined.
26735 If the identifier is only one letter long, however, you get to see only
26736 the underlined entries. {\sl All references are to section numbers instead of
26737 page numbers.}
26738
26739 This index also lists error messages and other aspects of the program
26740 that you might want to look up some day. For example, the entry
26741 for ``system dependencies'' lists all sections that should receive
26742 special attention from people who are installing \MP\ in a new
26743 operating environment. A list of various things that can't happen appears
26744 under ``this can't happen''.
26745 Approximately 25 sections are listed under ``inner loop''; these account
26746 for more than 60\pct! of \MP's running time, exclusive of input and output.