remove a few tokens for ctangle (and fix a reallocation bug while at it)
[mplib] / src / texk / web2c / mpdir / lib / mp.w
1 % $Id: mp.web,v 1.8 2005/08/24 10:54:02 taco Exp $
2 % MetaPost, by John Hobby.  Public domain.
3
4 % Much of this program was copied with permission from MF.web Version 1.9
5 % It interprets a language very similar to D.E. Knuth's METAFONT, but with
6 % changes designed to make it more suitable for PostScript output.
7
8 % TeX is a trademark of the American Mathematical Society.
9 % METAFONT is a trademark of Addison-Wesley Publishing Company.
10 % PostScript is a trademark of Adobe Systems Incorporated.
11
12 % Here is TeX material that gets inserted after \input webmac
13 \def\hang{\hangindent 3em\noindent\ignorespaces}
14 \def\textindent#1{\hangindent2.5em\noindent\hbox to2.5em{\hss#1 }\ignorespaces}
15 \def\PASCAL{Pascal}
16 \def\ps{PostScript}
17 \def\ph{\hbox{Pascal-H}}
18 \def\psqrt#1{\sqrt{\mathstrut#1}}
19 \def\k{_{k+1}}
20 \def\pct!{{\char`\%}} % percent sign in ordinary text
21 \font\tenlogo=logo10 % font used for the METAFONT logo
22 \font\logos=logosl10
23 \def\MF{{\tenlogo META}\-{\tenlogo FONT}}
24 \def\MP{{\tenlogo META}\-{\tenlogo POST}}
25 \def\[#1]{#1.} % from pascal web
26 \def\<#1>{$\langle#1\rangle$}
27 \def\section{\mathhexbox278}
28 \let\swap=\leftrightarrow
29 \def\round{\mathop{\rm round}\nolimits}
30 \mathchardef\vb="026A % synonym for `\|'
31
32 \def\(#1){} % this is used to make section names sort themselves better
33 \def\9#1{} % this is used for sort keys in the index via @@:sort key}{entry@@>
34 \def\title{MetaPost}
35 \def\glob{15} % this should be the section number of "<Global...>"
36 \def\gglob{23, 28} % this should be the next two sections of "<Global...>"
37 \pdfoutput=1
38 \pageno=3
39
40 @* \[1] Introduction.
41 This is \MP, a graphics-language processor based on D. E. Knuth's \MF.
42
43 The main purpose of the following program is to explain the algorithms of \MP\
44 as clearly as possible. As a result, the program will not necessarily be very
45 efficient when a particular \PASCAL\ compiler has translated it into a
46 particular machine language. However, the program has been written so that it
47 can be tuned to run efficiently in a wide variety of operating environments
48 by making comparatively few changes. Such flexibility is possible because
49 the documentation that follows is written in the \.{WEB} language, which is
50 at a higher level than \PASCAL; the preprocessing step that converts \.{WEB}
51 to \PASCAL\ is able to introduce most of the necessary refinements.
52 Semi-automatic translation to other languages is also feasible, because the
53 program below does not make extensive use of features that are peculiar to
54 \PASCAL.
55
56 A large piece of software like \MP\ has inherent complexity that cannot
57 be reduced below a certain level of difficulty, although each individual
58 part is fairly simple by itself. The \.{WEB} language is intended to make
59 the algorithms as readable as possible, by reflecting the way the
60 individual program pieces fit together and by providing the
61 cross-references that connect different parts. Detailed comments about
62 what is going on, and about why things were done in certain ways, have
63 been liberally sprinkled throughout the program.  These comments explain
64 features of the implementation, but they rarely attempt to explain the
65 \MP\ language itself, since the reader is supposed to be familiar with
66 {\sl The {\logos METAFONT\/}book} as well as the manual
67 @.WEB@>
68 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
69 {\sl A User's Manual for MetaPost}, Computing Science Technical Report 162,
70 AT\AM T Bell Laboratories.
71
72 @ The present implementation is a preliminary version, but the possibilities
73 for new features are limited by the desire to remain as nearly compatible
74 with \MF\ as possible.
75
76 On the other hand, the \.{WEB} description can be extended without changing
77 the core of the program, and it has been designed so that such
78 extensions are not extremely difficult to make.
79 The |banner| string defined here should be changed whenever \MP\
80 undergoes any modifications, so that it will be clear which version of
81 \MP\ might be the guilty party when a problem arises.
82 @^extensions to \MP@>
83 @^system dependencies@>
84
85 @d banner "This is MetaPost, Version 1.002" /* printed when \MP\ starts */
86 @d metapost_version "1.002"
87 @d mplib_version "0.10"
88 @d version_string " (Cweb version 0.10)"
89
90 @ Different \PASCAL s have slightly different conventions, and the present
91 @:PASCAL H}{\ph@>
92 program is expressed in a version of \PASCAL\ that D. E. Knuth used for \MF.
93 Constructions that apply to
94 this particular compiler, which we shall call \ph, should help the
95 reader see how to make an appropriate interface for other systems
96 if necessary. (\ph\ is Charles Hedrick's modification of a compiler
97 @^Hedrick, Charles Locke@>
98 for the DECsystem-10 that was originally developed at the University of
99 Hamburg; cf.\ {\sl SOFTWARE---Practice \AM\ Experience \bf6} (1976),
100 29--42. The \MP\ program below is intended to be adaptable, without
101 extensive changes, to most other versions of \PASCAL\ and commonly used
102 \PASCAL-to-C translators, so it does not fully
103 @:C@>
104 use the admirable features of \ph. Indeed, a conscious effort has been
105 made here to avoid using several idiosyncratic features of standard
106 \PASCAL\ itself, so that most of the code can be translated mechanically
107 into other high-level languages. For example, the `\&{with}' and `\\{new}'
108 features are not used, nor are pointer types, set types, or enumerated
109 scalar types; there are no `\&{var}' parameters, except in the case of files;
110 there are no tag fields on variant records; there are no |real| variables;
111 no procedures are declared local to other procedures.)
112
113 The portions of this program that involve system-dependent code, where
114 changes might be necessary because of differences between \PASCAL\ compilers
115 and/or differences between
116 operating systems, can be identified by looking at the sections whose
117 numbers are listed under `system dependencies' in the index. Furthermore,
118 the index entries for `dirty \PASCAL' list all places where the restrictions
119 of \PASCAL\ have not been followed perfectly, for one reason or another.
120 @^system dependencies@>
121 @^dirty \PASCAL@>
122
123 @ The program begins with a normal \PASCAL\ program heading, whose
124 components will be filled in later, using the conventions of \.{WEB}.
125 @.WEB@>
126 For example, the portion of the program called `\X\glob:Global
127 variables\X' below will be replaced by a sequence of variable declarations
128 that starts in $\section\glob$ of this documentation. In this way, we are able
129 to define each individual global variable when we are prepared to
130 understand what it means; we do not have to define all of the globals at
131 once.  Cross references in $\section\glob$, where it says ``See also
132 sections \gglob, \dots,'' also make it possible to look at the set of
133 all global variables, if desired.  Similar remarks apply to the other
134 portions of the program heading.
135
136 Actually the heading shown here is not quite normal: The |program| line
137 does not mention any |output| file, because \ph\ would ask the \MP\ user
138 to specify a file name if |output| were specified here.
139 @^system dependencies@>
140
141 @d true 1
142 @d false 0
143  
144 @(mplib.h@>=
145 #  ifndef LIBAVL_ALLOCATOR
146 #    define LIBAVL_ALLOCATOR
147     struct libavl_allocator {
148         void *(*libavl_malloc) (struct libavl_allocator *, size_t libavl_size);
149         void (*libavl_free) (struct libavl_allocator *, void *libavl_block);
150     };
151 #  endif
152 typedef struct psout_data_struct * psout_data;
153 typedef struct MP_instance * MP;
154 typedef int boolean;
155 typedef signed int integer;
156 @<Types in the outer block@>
157 typedef struct MP_options {
158   @<Option variables@>
159 } MP_options;
160 @<Declare helpers@>;
161 @<Exported function headers@>
162
163 @ @(mpmp.h@>=
164 @<Constants in the outer block@>
165 typedef struct MP_instance {
166   @<Global variables@>
167 } MP_instance;
168
169 @ @c 
170 #include <stdio.h>
171 #include <stdlib.h>
172 #include <string.h>
173 #include <stdarg.h>
174 #include <assert.h>
175 #include <unistd.h> /* for access() */
176 #include <time.h> /* for struct tm \& co */
177 #include "mplib.h"
178 #include "mpmp.h" /* internal header */
179 #include "mppsout.h" /* internal header */
180 @h
181 @<Declarations@>
182 @<Basic printing procedures@>
183 @<Error handling procedures@>
184
185 @ Here are the functions that set up the \MP\ instance.
186
187 @<Declarations@> =
188 @<Declare |mp_reallocate| functions@>;
189 struct MP_options mp_options (void) {
190   struct MP_options *opt;
191   opt = xmalloc(1,sizeof(MP_options));
192   memset (opt,0,sizeof(MP_options));
193   return *opt;
194
195 MP mp_new (struct MP_options opt) {
196   MP mp;
197   mp = xmalloc(1,sizeof(MP_instance));
198   @<Set |ini_version|@>;
199   @<Allocate or initialize variables@>
200   mp_reallocate_paths(mp,1000);
201   mp_reallocate_fonts(mp,8);
202   mp->term_in = stdin;
203   mp->term_out = stdout;
204   return mp;
205 }
206 void mp_free (MP mp) {
207   int k; /* loop variable */
208   @<Dealloc variables@>
209   xfree(mp);
210 }
211
212 @ @c
213 boolean mp_initialize (MP mp) { /* this procedure gets things started properly */
214   @<Local variables for initialization@>
215   mp->history=fatal_error_stop; /* in case we quit during initialization */
216   t_open_out; /* open the terminal for output */
217   @<Check the ``constant'' values...@>;
218   if ( mp->bad>0 ) {
219     fprintf(stdout,"Ouch---my internal constants have been clobbered!\n"
220                    "---case %i",(int)mp->bad);
221 @.Ouch...clobbered@>
222     return false;
223   }
224   @<Set initial values of key variables@>
225   if (mp->ini_version) {
226     @<Run inimpost commands@>;
227   }
228   @<Initialize the output routines@>;
229   @<Get the first line of input and prepare to start@>;
230   mp_set_job_id(mp,mp->internal[year],mp->internal[month],
231                        mp->internal[day],mp->internal[mp_time]);
232   mp_init_map_file(mp, mp->troff_mode);
233   mp->history=spotless; /* ready to go! */
234   if (mp->troff_mode) {
235     mp->internal[gtroffmode]=unity; 
236     mp->internal[prologues]=unity; 
237   }
238   if ( mp->start_sym>0 ) { /* insert the `\&{everyjob}' symbol */
239     mp->cur_sym=mp->start_sym; mp_back_input(mp);
240   }
241   return true;
242 }
243
244
245 @<Exported function headers@>=
246 extern struct MP_options mp_options (void);
247 extern MP mp_new (struct MP_options opt) ;
248 extern void mp_free (MP mp);
249 extern boolean mp_initialize (MP mp);
250
251
252 @ The overall \MP\ program begins with the heading just shown, after which
253 comes a bunch of procedure declarations and function declarations.
254 Finally we will get to the main program, which begins with the
255 comment `|start_here|'. If you want to skip down to the
256 main program now, you can look up `|start_here|' in the index.
257 But the author suggests that the best way to understand this program
258 is to follow pretty much the order of \MP's components as they appear in the
259 \.{WEB} description you are now reading, since the present ordering is
260 intended to combine the advantages of the ``bottom up'' and ``top down''
261 approaches to the problem of understanding a somewhat complicated system.
262
263 @ Some of the code below is intended to be used only when diagnosing the
264 strange behavior that sometimes occurs when \MP\ is being installed or
265 when system wizards are fooling around with \MP\ without quite knowing
266 what they are doing. Such code will not normally be compiled; it is
267 delimited by the preprocessor test `|#ifdef DEBUG .. #endif|'.
268
269 @ This program has two important variations: (1) There is a long and slow
270 version called \.{INIMP}, which does the extra calculations needed to
271 @.INIMP@>
272 initialize \MP's internal tables; and (2)~there is a shorter and faster
273 production version, which cuts the initialization to a bare minimum.
274
275 Which is which is decided at runtime.
276
277 @ The following parameters can be changed at compile time to extend or
278 reduce \MP's capacity. They may have different values in \.{INIMP} and
279 in production versions of \MP.
280 @.INIMP@>
281 @^system dependencies@>
282
283 @<Constants...@>=
284 #define file_name_size 255 /* file names shouldn't be longer than this */
285 #define bistack_size 1500 /* size of stack for bisection algorithms;
286   should probably be left at this value */
287
288 @ Like the preceding parameters, the following quantities can be changed
289 at compile time to extend or reduce \MP's capacity. But if they are changed,
290 it is necessary to rerun the initialization program \.{INIMP}
291 @.INIMP@>
292 to generate new tables for the production \MP\ program.
293 One can't simply make helter-skelter changes to the following constants,
294 since certain rather complex initialization
295 numbers are computed from them. 
296
297 @ @<Glob...@>=
298 int max_strings; /* maximum number of strings; must not exceed |max_halfword| */
299 int pool_size; /* maximum number of characters in strings, including all
300   error messages and help texts, and the names of all identifiers */
301 int error_line; /* width of context lines on terminal error messages */
302 int half_error_line; /* width of first lines of contexts in terminal
303   error messages; should be between 30 and |error_line-15| */
304 int max_print_line; /* width of longest text lines output; should be at least 60 */
305 int mem_max; /* greatest index in \MP's internal |mem| array;
306   must be strictly less than |max_halfword|;
307   must be equal to |mem_top| in \.{INIMP}, otherwise |>=mem_top| */
308 int mem_top; /* largest index in the |mem| array dumped by \.{INIMP};
309   must not be greater than |mem_max| */
310 int hash_size; /* maximum number of symbolic tokens,
311   must be less than |max_halfword-3*param_size| */
312 int hash_prime; /* a prime number equal to about 85\pct! of |hash_size| */
313 int param_size; /* maximum number of simultaneous macro parameters */
314 int max_in_open; /* maximum number of input files and error insertions that
315   can be going on simultaneously */
316
317 @ @<Option variables@>=
318 int error_line;
319 int half_error_line;
320 int max_print_line;
321 int main_memory;
322 int hash_size; 
323 int hash_prime; 
324 int param_size; 
325 int max_in_open; 
326
327
328 @d set_value(a,b,c) do { a=c; if (b>c) a=b; } while (0)
329
330 @<Allocate or ...@>=
331 mp->max_strings=500;
332 mp->pool_size=10000;
333 set_value(mp->error_line,opt.error_line,79);
334 set_value(mp->half_error_line,opt.half_error_line,50);
335 set_value(mp->max_print_line,opt.max_print_line,79);
336 mp->mem_max=5000;
337 mp->mem_top=5000;
338 if (opt.main_memory>mp->mem_max)
339   mp_reallocate_memory(mp,opt.main_memory);
340 set_value(mp->hash_size,opt.hash_size,9500);
341 set_value(mp->hash_prime,opt.hash_prime,7919);
342 set_value(mp->param_size,opt.param_size,150);
343 set_value(mp->max_in_open,opt.max_in_open,10);
344
345
346 @ In case somebody has inadvertently made bad settings of the ``constants,''
347 \MP\ checks them using a global variable called |bad|.
348
349 This is the first of many sections of \MP\ where global variables are
350 defined.
351
352 @<Glob...@>=
353 integer bad; /* is some ``constant'' wrong? */
354
355 @ Later on we will say `\ignorespaces|if (mem_max>=max_halfword) bad=10;|',
356 or something similar. (We can't do that until |max_halfword| has been defined.)
357
358 @<Check the ``constant'' values for consistency@>=
359 mp->bad=0;
360 if ( (mp->half_error_line<30)||(mp->half_error_line>mp->error_line-15) ) mp->bad=1;
361 if ( mp->max_print_line<60 ) mp->bad=2;
362 if ( mp->mem_top<=1100 ) mp->bad=4;
363 if (mp->hash_prime>mp->hash_size ) mp->bad=5;
364
365 @ Labels are given symbolic names by the following definitions, so that
366 occasional |goto| statements will be meaningful. We insert the label
367 `|exit|:' just before the `\ignorespaces|end|\unskip' of a procedure in
368 which we have used the `|return|' statement defined below; the label
369 `|restart|' is occasionally used at the very beginning of a procedure; and
370 the label `|reswitch|' is occasionally used just prior to a |case|
371 statement in which some cases change the conditions and we wish to branch
372 to the newly applicable case.  Loops that are set up with the |loop|
373 construction defined below are commonly exited by going to `|done|' or to
374 `|found|' or to `|not_found|', and they are sometimes repeated by going to
375 `|continue|'.  If two or more parts of a subroutine start differently but
376 end up the same, the shared code may be gathered together at
377 `|common_ending|'.
378
379 Incidentally, this program never declares a label that isn't actually used,
380 because some fussy \PASCAL\ compilers will complain about redundant labels.
381
382 @d label_exit 10 /* go here to leave a procedure */
383 @d restart 20 /* go here to start a procedure again */
384 @d reswitch 21 /* go here to start a case statement again */
385 @d continue 22 /* go here to resume a loop */
386 @d done 30 /* go here to exit a loop */
387 @d done1 31 /* like |done|, when there is more than one loop */
388 @d done2 32 /* for exiting the second loop in a long block */
389 @d done3 33 /* for exiting the third loop in a very long block */
390 @d done4 34 /* for exiting the fourth loop in an extremely long block */
391 @d done5 35 /* for exiting the fifth loop in an immense block */
392 @d done6 36 /* for exiting the sixth loop in a block */
393 @d found 40 /* go here when you've found it */
394 @d found1 41 /* like |found|, when there's more than one per routine */
395 @d found2 42 /* like |found|, when there's more than two per routine */
396 @d found3 43 /* like |found|, when there's more than three per routine */
397 @d not_found 45 /* go here when you've found nothing */
398 @d common_ending 50 /* go here when you want to merge with another branch */
399
400 @ Here are some macros for common programming idioms.
401
402 @d incr(A)   (A)=(A)+1 /* increase a variable by unity */
403 @d decr(A)   (A)=(A)-1 /* decrease a variable by unity */
404 @d negate(A)   (A)=-(A) /* change the sign of a variable */
405 @d odd(A)   ((A)%2==1)
406 @d chr(A)   (A)
407 @d do_nothing   /* empty statement */
408 @d Return   goto exit /* terminate a procedure call */
409 @f return   nil /* \.{WEB} will henceforth say |return| instead of \\{return} */
410
411 @* \[2] The character set.
412 In order to make \MP\ readily portable to a wide variety of
413 computers, all of its input text is converted to an internal eight-bit
414 code that includes standard ASCII, the ``American Standard Code for
415 Information Interchange.''  This conversion is done immediately when each
416 character is read in. Conversely, characters are converted from ASCII to
417 the user's external representation just before they are output to a
418 text file.
419 @^ASCII code@>
420
421 Such an internal code is relevant to users of \MP\ only with respect to
422 the \&{char} and \&{ASCII} operations, and the comparison of strings.
423
424 @ Characters of text that have been converted to \MP's internal form
425 are said to be of type |ASCII_code|, which is a subrange of the integers.
426
427 @<Types...@>=
428 typedef unsigned char ASCII_code; /* eight-bit numbers */
429
430 @ The original \PASCAL\ compiler was designed in the late 60s, when six-bit
431 character sets were common, so it did not make provision for lowercase
432 letters. Nowadays, of course, we need to deal with both capital and small
433 letters in a convenient way, especially in a program for font design;
434 so the present specification of \MP\ has been written under the assumption
435 that the \PASCAL\ compiler and run-time system permit the use of text files
436 with more than 64 distinguishable characters. More precisely, we assume that
437 the character set contains at least the letters and symbols associated
438 with ASCII codes 040 through 0176; all of these characters are now
439 available on most computer terminals.
440
441 Since we are dealing with more characters than were present in the first
442 \PASCAL\ compilers, we have to decide what to call the associated data
443 type. Some \PASCAL s use the original name |char| for the
444 characters in text files, even though there now are more than 64 such
445 characters, while other \PASCAL s consider |char| to be a 64-element
446 subrange of a larger data type that has some other name.
447
448 In order to accommodate this difference, we shall use the name |text_char|
449 to stand for the data type of the characters that are converted to and
450 from |ASCII_code| when they are input and output. We shall also assume
451 that |text_char| consists of the elements |chr(first_text_char)| through
452 |chr(last_text_char)|, inclusive. The following definitions should be
453 adjusted if necessary.
454 @^system dependencies@>
455
456 @d first_text_char 0 /* ordinal number of the smallest element of |text_char| */
457 @d last_text_char 255 /* ordinal number of the largest element of |text_char| */
458
459 @<Types...@>=
460 typedef unsigned char text_char; /* the data type of characters in text files */
461
462 @ @<Local variables for init...@>=
463 integer i;
464
465 @ The \MP\ processor converts between ASCII code and
466 the user's external character set by means of arrays |xord| and |xchr|
467 that are analogous to \PASCAL's |ord| and |chr| functions.
468
469 @d xchr(A) mp->xchr[(A)]
470 @d xord(A) mp->xord[(A)]
471
472 @<Glob...@>=
473 ASCII_code xord[256];  /* specifies conversion of input characters */
474 text_char xchr[256];  /* specifies conversion of output characters */
475
476 @ The core system assumes all 8-bit is acceptable.  If it is not,
477 a change file has to alter the below section.
478 @^system dependencies@>
479
480 Additionally, people with extended character sets can
481 assign codes arbitrarily, giving an |xchr| equivalent to whatever
482 characters the users of \MP\ are allowed to have in their input files.
483 Appropriate changes to \MP's |char_class| table should then be made.
484 (Unlike \TeX, each installation of \MP\ has a fixed assignment of category
485 codes, called the |char_class|.) Such changes make portability of programs
486 more difficult, so they should be introduced cautiously if at all.
487 @^character set dependencies@>
488 @^system dependencies@>
489
490 @<Set initial ...@>=
491 for (i=0;i<=0377;i++) { xchr(i)=i; }
492
493 @ The following system-independent code makes the |xord| array contain a
494 suitable inverse to the information in |xchr|. Note that if |xchr[i]=xchr[j]|
495 where |i<j<0177|, the value of |xord[xchr[i]]| will turn out to be
496 |j| or more; hence, standard ASCII code numbers will be used instead of
497 codes below 040 in case there is a coincidence.
498
499 @<Set initial ...@>=
500 for (i=first_text_char;i<=last_text_char;i++) { 
501    xord(chr(i))=0177;
502 }
503 for (i=0200;i<=0377;i++) { xord(xchr(i))=i;}
504 for (i=0;i<=0176;i++) { xord(xchr(i))=i;}
505
506 @* \[3] Input and output.
507 The bane of portability is the fact that different operating systems treat
508 input and output quite differently, perhaps because computer scientists
509 have not given sufficient attention to this problem. People have felt somehow
510 that input and output are not part of ``real'' programming. Well, it is true
511 that some kinds of programming are more fun than others. With existing
512 input/output conventions being so diverse and so messy, the only sources of
513 joy in such parts of the code are the rare occasions when one can find a
514 way to make the program a little less bad than it might have been. We have
515 two choices, either to attack I/O now and get it over with, or to postpone
516 I/O until near the end. Neither prospect is very attractive, so let's
517 get it over with.
518
519 The basic operations we need to do are (1)~inputting and outputting of
520 text, to or from a file or the user's terminal; (2)~inputting and
521 outputting of eight-bit bytes, to or from a file; (3)~instructing the
522 operating system to initiate (``open'') or to terminate (``close'') input or
523 output from a specified file; (4)~testing whether the end of an input
524 file has been reached; (5)~display of bits on the user's screen.
525 The bit-display operation will be discussed in a later section; we shall
526 deal here only with more traditional kinds of I/O.
527
528 @ Finding files happens in a slightly roundabout fashion: the \MP\
529 instance object contains a field that holds a function pointer that finds a
530 file, and returns its name, or NULL. For this, it receives three
531 parameters: the non-qualified name |fname|, the intended |fopen|
532 operation type |fmode|, and the type of the file |ftype|.
533
534 The file types that are passed on in |ftype| can be  used to 
535 differentiate file searches if a library like kpathsea is used,
536 the fopen mode is passed along for the same reason.
537
538 @<Types...@>=
539 typedef unsigned char eight_bits ; /* unsigned one-byte quantity */
540 enum {
541   mp_filetype_program = 1, /* \MP\ language input */
542   mp_filetype_log,  /* the log file */
543   mp_filetype_postscript, /* the postscript output */
544   mp_filetype_text,  /* text files for readfrom and writeto primitives */
545   mp_filetype_memfile, /* memory dumps */
546   mp_filetype_metrics, /* TeX font metric files */
547   mp_filetype_fontmap, /* PostScript font mapping files */
548   mp_filetype_font, /*  PostScript type1 font programs */
549   mp_filetype_encoding, /*  PostScript font encoding files */
550 };
551 typedef char *(*file_finder)(char *, char *, int);
552
553 @ @<Glob...@>=
554 file_finder find_file;
555
556 @ @<Option variables@>=
557 file_finder find_file;
558
559 @ The default function for finding files is |mp_find_file|. It is 
560 pretty stupid: it will only find files in the current directory.
561
562 @c
563 char *mp_find_file (char *fname, char *fmode, int ftype)  {
564   if (fmode[0] != 'r' || access (fname,R_OK) || ftype)  
565      return xstrdup(fname);
566   return NULL;
567 }
568
569 @ This has to be done very early on, so it is best to put it in with
570 the |mp_new| allocations
571
572 @d set_callback_option(A) do { mp->A = mp_##A;
573   if (opt.A!=NULL) mp->A = opt.A;
574 } while (0)
575
576 @<Allocate or initialize ...@>=
577 set_callback_option(find_file);
578
579 @ Because |mp_find_file| is used so early, it has to be in the helpers
580 section.
581
582 @<Declare helpers@>=
583 char *mp_find_file (char *fname, char *fmode, int ftype) ;
584
585 @ The function to open files can now be very short.
586
587 @c
588 FILE *mp_open_file(MP mp, char *fname, char *fmode, int ftype)  {
589   char *s = (mp->find_file)(fname,fmode,ftype);
590   if (s!=NULL) {
591     FILE *f = fopen(s, fmode);
592     xfree(s);
593     return f;   
594   }
595   return NULL;
596 }
597
598 @ This is a legacy interface: (almost) all file names pass through |name_of_file|.
599
600 @<Glob...@>=
601 char name_of_file[file_name_size+1]; /* the name of a system file */
602 int name_length;/* this many characters are actually
603   relevant in |name_of_file| (the rest are blank) */
604 boolean print_found_names; /* configuration parameter */
605
606 @ @<Option variables@>=
607 boolean print_found_names; /* configuration parameter */
608
609 @ If this parameter is true, the terminal and log will report the found
610 file names for input files instead of the requested ones. 
611 It is off by default because it creates an extra filename lookup.
612
613 @<Allocate or initialize ...@>=
614 mp->print_found_names = (opt.print_found_names>0 ? true : false);
615
616 @ \MP's file-opening procedures return |false| if no file identified by
617 |name_of_file| could be opened.
618
619 The |OPEN_FILE| macro takes care of the |print_found_names| parameter.
620 It is not used for opening a mem file for read, because that file name 
621 is never printed.
622
623 @d OPEN_FILE(A) do {
624   if (mp->print_found_names) {
625     char *s = (mp->find_file)(mp->name_of_file,A,ftype);
626     if (s!=NULL) {
627       *f = mp_open_file(mp,mp->name_of_file,A, ftype); 
628       strncpy(mp->name_of_file,s,file_name_size);
629       xfree(s);
630     } else {
631       *f = NULL;
632     }
633   } else {
634     *f = mp_open_file(mp,mp->name_of_file,A, ftype); 
635   }
636 } while (0);
637 return (*f ? true : false)
638
639 @c 
640 boolean mp_a_open_in (MP mp, FILE **f, int ftype) {
641   /* open a text file for input */
642   OPEN_FILE("r");
643 }
644 @#
645 boolean mp_w_open_in (MP mp, FILE **f) {
646   /* open a word file for input */
647   *f = mp_open_file(mp,mp->name_of_file,"rb",mp_filetype_memfile); 
648   return (*f ? true : false);
649 }
650 @#
651 boolean mp_a_open_out (MP mp, FILE **f, int ftype) {
652   /* open a text file for output */
653   OPEN_FILE("w");
654 }
655 @#
656 boolean mp_b_open_out (MP mp, FILE **f, int ftype) {
657   /* open a binary file for output */
658   OPEN_FILE("wb");
659 }
660 @#
661 boolean mp_w_open_out (MP mp, FILE**f) {
662   /* open a word file for output */
663   int ftype = mp_filetype_memfile;
664   OPEN_FILE("wb");
665 }
666
667 @ @<Exported...@>=
668 FILE *mp_open_file(MP mp, char *fname, char *fmode, int ftype);
669
670 @ Binary input and output are done with \PASCAL's ordinary |get| and |put|
671 procedures, so we don't have to make any other special arrangements for
672 binary~I/O. Text output is also easy to do with standard \PASCAL\ routines.
673 The treatment of text input is more difficult, however, because
674 of the necessary translation to |ASCII_code| values.
675 \MP's conventions should be efficient, and they should
676 blend nicely with the user's operating environment.
677
678 @ Input from text files is read one line at a time, using a routine called
679 |input_ln|. This function is defined in terms of global variables called
680 |buffer|, |first|, and |last| that will be described in detail later; for
681 now, it suffices for us to know that |buffer| is an array of |ASCII_code|
682 values, and that |first| and |last| are indices into this array
683 representing the beginning and ending of a line of text.
684
685 @<Glob...@>=
686 size_t buf_size; /* maximum number of characters simultaneously present in
687                     current lines of open files */
688 ASCII_code *buffer; /* lines of characters being read */
689 size_t first; /* the first unused position in |buffer| */
690 size_t last; /* end of the line just input to |buffer| */
691 size_t max_buf_stack; /* largest index used in |buffer| */
692
693 @ @<Allocate or initialize ...@>=
694 mp->buf_size = 200;
695 mp->buffer = xmalloc((mp->buf_size+1),sizeof(ASCII_code));
696
697 @ @<Dealloc variables@>=
698 xfree(mp->buffer);
699
700 @ @c
701 void mp_reallocate_buffer(MP mp, size_t l) {
702   ASCII_code *buffer;
703   if (l>max_halfword) {
704     mp_confusion(mp,"buffer size"); /* can't happen (I hope) */
705   }
706   buffer = xmalloc((l+1),sizeof(ASCII_code));
707   memcpy(buffer,mp->buffer,(mp->buf_size+1));
708   xfree(mp->buffer);
709   mp->buffer = buffer ;
710   mp->buf_size = l;
711 }
712
713 @ The |input_ln| function brings the next line of input from the specified
714 field into available positions of the buffer array and returns the value
715 |true|, unless the file has already been entirely read, in which case it
716 returns |false| and sets |last:=first|.  In general, the |ASCII_code|
717 numbers that represent the next line of the file are input into
718 |buffer[first]|, |buffer[first+1]|, \dots, |buffer[last-1]|; and the
719 global variable |last| is set equal to |first| plus the length of the
720 line. Trailing blanks are removed from the line; thus, either |last=first|
721 (in which case the line was entirely blank) or |buffer[last-1]<>" "|.
722 @^inner loop@>
723
724 An overflow error is given, however, if the normal actions of |input_ln|
725 would make |last>=buf_size|; this is done so that other parts of \MP\
726 can safely look at the contents of |buffer[last+1]| without overstepping
727 the bounds of the |buffer| array. Upon entry to |input_ln|, the condition
728 |first<buf_size| will always hold, so that there is always room for an
729 ``empty'' line.
730
731 The variable |max_buf_stack|, which is used to keep track of how large
732 the |buf_size| parameter must be to accommodate the present job, is
733 also kept up to date by |input_ln|.
734
735 If the |bypass_eoln| parameter is |true|, |input_ln| will do a |get|
736 before looking at the first character of the line; this skips over
737 an |eoln| that was in |f^|. The procedure does not do a |get| when it
738 reaches the end of the line; therefore it can be used to acquire input
739 from the user's terminal as well as from ordinary text files.
740
741 Standard \PASCAL\ says that a file should have |eoln| immediately
742 before |eof|, but \MP\ needs only a weaker restriction: If |eof|
743 occurs in the middle of a line, the system function |eoln| should return
744 a |true| result (even though |f^| will be undefined).
745
746 @c 
747 boolean mp_input_ln (MP mp,FILE *  f, boolean bypass_eoln) {
748   /* inputs the next line or returns |false| */
749   int last_nonblank; /* |last| with trailing blanks removed */
750   int c;
751   if ( bypass_eoln ) {
752     c = fgetc(f);
753     if (c==EOF)
754       return false;
755     if (c!='\n' && c!='\r') {
756       ungetc(c,f);
757     }
758   }
759   /* input the first character of the line into |f^| */
760   mp->last=mp->first; /* cf.\ Matthew 19\thinspace:\thinspace30 */
761   c = fgetc(f);
762   if (c==EOF)
763         return false;
764   last_nonblank=mp->first;
765   while (c!=EOF && c!='\n' && c!='\r') { 
766     if ( mp->last>=mp->max_buf_stack ) { 
767       mp->max_buf_stack=mp->last+1;
768       if ( mp->max_buf_stack==mp->buf_size ) {
769         mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
770       }
771     }
772     mp->buffer[mp->last]=xord(c); 
773     incr(mp->last);
774     if ( mp->buffer[mp->last-1]!=' ' ) 
775       last_nonblank=mp->last;
776     c = fgetc(f); 
777   } 
778   if (c!=EOF) {
779     ungetc(c,f);
780   }
781   mp->last=last_nonblank; 
782   return true;
783 }
784
785 @ The user's terminal acts essentially like other files of text, except
786 that it is used both for input and for output. When the terminal is
787 considered an input file, the file variable is called |term_in|, and when it
788 is considered an output file the file variable is |term_out|.
789 @^system dependencies@>
790
791 @<Glob...@>=
792 FILE * term_in; /* the terminal as an input file */
793 FILE * term_out; /* the terminal as an output file */
794
795 @ Here is how to open the terminal files. In the default configuration,
796 nothing happens except that the command line (if there is one) is copied
797 to the input buffer.  The variable |command_line| will be filled by the 
798 |main| procedure. The copying can not be done earlier in the program 
799 logic because in the |INI| version, the |buffer| is also used for primitive 
800 initialization.
801
802 @^system dependencies@>
803
804 @d t_open_out  /* open the terminal for text output */
805 @d t_open_in  do { /* open the terminal for text input */
806     if (mp->command_line!=NULL) {
807       mp->last = strlen(mp->command_line);
808       strncpy((char *)mp->buffer,mp->command_line,mp->last);
809       xfree(mp->command_line);
810     }
811 } while (0)
812
813 @<Glob...@>=
814 char *command_line;
815
816 @ @<Option variables@>=
817 char *command_line;
818
819 @ @<Allocate or initialize ...@>=
820 mp->command_line = mp_xstrdup(opt.command_line);
821
822 @ Sometimes it is necessary to synchronize the input/output mixture that
823 happens on the user's terminal, and three system-dependent
824 procedures are used for this
825 purpose. The first of these, |update_terminal|, is called when we want
826 to make sure that everything we have output to the terminal so far has
827 actually left the computer's internal buffers and been sent.
828 The second, |clear_terminal|, is called when we wish to cancel any
829 input that the user may have typed ahead (since we are about to
830 issue an unexpected error message). The third, |wake_up_terminal|,
831 is supposed to revive the terminal if the user has disabled it by
832 some instruction to the operating system.  The following macros show how
833 these operations can be specified in \ph:
834 @^system dependencies@>
835
836 @d update_terminal   fflush(mp->term_out) /* empty the terminal output buffer */
837 @d clear_terminal   do_nothing /* clear the terminal input buffer */
838 @d wake_up_terminal  fflush(mp->term_out) /* cancel the user's cancellation of output */
839
840 @ We need a special routine to read the first line of \MP\ input from
841 the user's terminal. This line is different because it is read before we
842 have opened the transcript file; there is sort of a ``chicken and
843 egg'' problem here. If the user types `\.{input cmr10}' on the first
844 line, or if some macro invoked by that line does such an \.{input},
845 the transcript file will be named `\.{cmr10.log}'; but if no \.{input}
846 commands are performed during the first line of terminal input, the transcript
847 file will acquire its default name `\.{mpout.log}'. (The transcript file
848 will not contain error messages generated by the first line before the
849 first \.{input} command.)
850
851 The first line is even more special if we are lucky enough to have an operating
852 system that treats \MP\ differently from a run-of-the-mill \PASCAL\ object
853 program. It's nice to let the user start running a \MP\ job by typing
854 a command line like `\.{MP cmr10}'; in such a case, \MP\ will operate
855 as if the first line of input were `\.{cmr10}', i.e., the first line will
856 consist of the remainder of the command line, after the part that invoked \MP.
857
858 @ Different systems have different ways to get started. But regardless of
859 what conventions are adopted, the routine that initializes the terminal
860 should satisfy the following specifications:
861
862 \yskip\textindent{1)}It should open file |term_in| for input from the
863   terminal. (The file |term_out| will already be open for output to the
864   terminal.)
865
866 \textindent{2)}If the user has given a command line, this line should be
867   considered the first line of terminal input. Otherwise the
868   user should be prompted with `\.{**}', and the first line of input
869   should be whatever is typed in response.
870
871 \textindent{3)}The first line of input, which might or might not be a
872   command line, should appear in locations |first| to |last-1| of the
873   |buffer| array.
874
875 \textindent{4)}The global variable |loc| should be set so that the
876   character to be read next by \MP\ is in |buffer[loc]|. This
877   character should not be blank, and we should have |loc<last|.
878
879 \yskip\noindent(It may be necessary to prompt the user several times
880 before a non-blank line comes in. The prompt is `\.{**}' instead of the
881 later `\.*' because the meaning is slightly different: `\.{input}' need
882 not be typed immediately after~`\.{**}'.)
883
884 @d loc mp->cur_input.loc_field /* location of first unread character in |buffer| */
885
886 @ The following program does the required initialization
887 without retrieving a possible command line.
888 It should be clear how to modify this routine to deal with command lines,
889 if the system permits them.
890 @^system dependencies@>
891
892 @c 
893 boolean mp_init_terminal (MP mp) { /* gets the terminal input started */
894   t_open_in; 
895   if (mp->last!=0) {
896     loc = mp->first = 0;
897         return true;
898   }
899   while (1) { 
900     wake_up_terminal; fprintf(mp->term_out,"**"); update_terminal;
901 @.**@>
902     if ( ! mp_input_ln(mp, mp->term_in,true) ) { /* this shouldn't happen */
903       fprintf(mp->term_out,"\n! End of file on the terminal... why?");
904 @.End of file on the terminal@>
905       return false;
906     }
907     loc=mp->first;
908     while ( (loc<(int)mp->last)&&(mp->buffer[loc]==' ') ) 
909       incr(loc);
910     if ( loc<(int)mp->last ) { 
911       return true; /* return unless the line was all blank */
912     };
913     fprintf(mp->term_out,"Please type the name of your input file.\n");
914   }
915 }
916
917 @ @<Declarations@>=
918 boolean mp_init_terminal (MP mp) ;
919
920
921 @* \[4] String handling.
922 Symbolic token names and diagnostic messages are variable-length strings
923 of eight-bit characters. Since \PASCAL\ does not have a well-developed string
924 mechanism, \MP\ does all of its string processing by homegrown methods.
925
926 \MP\ uses strings more extensively than \MF\ does, but the necessary
927 operations can still be handled with a fairly simple data structure.
928 The array |str_pool| contains all of the (eight-bit) ASCII codes in all
929 of the strings, and the array |str_start| contains indices of the starting
930 points of each string. Strings are referred to by integer numbers, so that
931 string number |s| comprises the characters |str_pool[j]| for
932 |str_start[s]<=j<str_start[ss]| where |ss=next_str[s]|.  The string pool
933 is allocated sequentially and |str_pool[pool_ptr]| is the next unused
934 location.  The first string number not currently in use is |str_ptr|
935 and |next_str[str_ptr]| begins a list of free string numbers.  String
936 pool entries |str_start[str_ptr]| up to |pool_ptr| are reserved for a
937 string currently being constructed.
938
939 String numbers 0 to 255 are reserved for strings that correspond to single
940 ASCII characters. This is in accordance with the conventions of \.{WEB},
941 @.WEB@>
942 which converts single-character strings into the ASCII code number of the
943 single character involved, while it converts other strings into integers
944 and builds a string pool file. Thus, when the string constant \.{"."} appears
945 in the program below, \.{WEB} converts it into the integer 46, which is the
946 ASCII code for a period, while \.{WEB} will convert a string like \.{"hello"}
947 into some integer greater than~255. String number 46 will presumably be the
948 single character `\..'\thinspace; but some ASCII codes have no standard visible
949 representation, and \MP\ may need to be able to print an arbitrary
950 ASCII character, so the first 256 strings are used to specify exactly what
951 should be printed for each of the 256 possibilities.
952
953 @<Types...@>=
954 typedef int pool_pointer; /* for variables that point into |str_pool| */
955 typedef int str_number; /* for variables that point into |str_start| */
956
957 @ @<Glob...@>=
958 ASCII_code *str_pool; /* the characters */
959 pool_pointer *str_start; /* the starting pointers */
960 str_number *next_str; /* for linking strings in order */
961 pool_pointer pool_ptr; /* first unused position in |str_pool| */
962 str_number str_ptr; /* number of the current string being created */
963 pool_pointer init_pool_ptr; /* the starting value of |pool_ptr| */
964 str_number init_str_use; /* the initial number of strings in use */
965 pool_pointer max_pool_ptr; /* the maximum so far of |pool_ptr| */
966 str_number max_str_ptr; /* the maximum so far of |str_ptr| */
967
968 @ @<Allocate or initialize ...@>=
969 mp->str_pool  = xmalloc ((mp->pool_size +1),sizeof(ASCII_code));
970 mp->str_start = xmalloc ((mp->max_strings+1),sizeof(pool_pointer));
971 mp->next_str  = xmalloc ((mp->max_strings+1),sizeof(str_number));
972
973 @ @<Dealloc variables@>=
974 xfree(mp->str_pool);
975 xfree(mp->str_start);
976 xfree(mp->next_str);
977
978 @ Most printing is done from |char *|s, but sometimes not. Here are
979 functions that convert an internal string into a |char *| for use
980 by the printing routines, and vice versa.
981
982 @d str(A) mp_str(mp,A)
983 @d rts(A) mp_rts(mp,A)
984
985 @<Exported function headers@>=
986 int mp_xstrcmp (const char *a, const char *b);
987 char * mp_str (MP mp, str_number s);
988
989 @ @<Declarations@>=
990 str_number mp_rts (MP mp, char *s);
991 str_number mp_make_string (MP mp);
992
993 @ The attempt to catch interrupted strings that is in |mp_rts|, is not 
994 very good: it does not handle nesting over more than one level.
995
996 @c 
997 int mp_xstrcmp (const char *a, const char *b) {
998         if (a==NULL && b==NULL) 
999           return 0;
1000     if (a==NULL)
1001       return -1;
1002     if (b==NULL)
1003       return 1;
1004     return strcmp(a,b);
1005 }
1006
1007 @ @c
1008 char * mp_str (MP mp, str_number ss) {
1009   char *s;
1010   int len = length(ss);
1011   s = xmalloc(len+1,sizeof(char));
1012   strncpy(s,(char *)(mp->str_pool+(mp->str_start[ss])),len);
1013   s[len] = 0;
1014   return (char *)s;
1015 }
1016 str_number mp_rts (MP mp, char *s) {
1017   int r; /* the new string */ 
1018   int old; /* a possible string in progress */
1019   int i=0;
1020   if (strlen(s)==0) {
1021     return 256;
1022   } else if (strlen(s)==1) {
1023     return s[0];
1024   } else {
1025    old=0;
1026    str_room((integer)strlen(s));
1027    if (mp->str_start[mp->str_ptr]<mp->pool_ptr)
1028      old = mp_make_string(mp);
1029    while (*s) {
1030      append_char(*s);
1031      s++;
1032    }
1033    r = mp_make_string(mp);
1034    if (old!=0) {
1035       str_room(length(old));
1036       while (i<length(old)) {
1037         append_char((mp->str_start[old]+i));
1038       } 
1039       mp_flush_string(mp,old);
1040     }
1041     return r;
1042   }
1043 }
1044
1045 @ Except for |strs_used_up|, the following string statistics are only
1046 maintained when code between |stat| $\ldots$ |tats| delimiters is not
1047 commented out:
1048
1049 @<Glob...@>=
1050 integer strs_used_up; /* strings in use or unused but not reclaimed */
1051 integer pool_in_use; /* total number of cells of |str_pool| actually in use */
1052 integer strs_in_use; /* total number of strings actually in use */
1053 integer max_pl_used; /* maximum |pool_in_use| so far */
1054 integer max_strs_used; /* maximum |strs_in_use| so far */
1055
1056 @ Several of the elementary string operations are performed using \.{WEB}
1057 macros instead of \PASCAL\ procedures, because many of the
1058 operations are done quite frequently and we want to avoid the
1059 overhead of procedure calls. For example, here is
1060 a simple macro that computes the length of a string.
1061 @.WEB@>
1062
1063 @d str_stop(A) mp->str_start[mp->next_str[(A)]] /* one cell past the end of string
1064   number \# */
1065 @d length(A) (str_stop((A))-mp->str_start[(A)]) /* the number of characters in string \# */
1066
1067 @ The length of the current string is called |cur_length|.  If we decide that
1068 the current string is not needed, |flush_cur_string| resets |pool_ptr| so that
1069 |cur_length| becomes zero.
1070
1071 @d cur_length   (mp->pool_ptr - mp->str_start[mp->str_ptr])
1072 @d flush_cur_string   mp->pool_ptr=mp->str_start[mp->str_ptr]
1073
1074 @ Strings are created by appending character codes to |str_pool|.
1075 The |append_char| macro, defined here, does not check to see if the
1076 value of |pool_ptr| has gotten too high; this test is supposed to be
1077 made before |append_char| is used.
1078
1079 To test if there is room to append |l| more characters to |str_pool|,
1080 we shall write |str_room(l)|, which tries to make sure there is enough room
1081 by compacting the string pool if necessary.  If this does not work,
1082 |do_compaction| aborts \MP\ and gives an apologetic error message.
1083
1084 @d append_char(A)   /* put |ASCII_code| \# at the end of |str_pool| */
1085 { mp->str_pool[mp->pool_ptr]=(A); incr(mp->pool_ptr);
1086 }
1087 @d str_room(A)   /* make sure that the pool hasn't overflowed */
1088   { if ( mp->pool_ptr+(A) > mp->max_pool_ptr ) {
1089     if ( mp->pool_ptr+(A) > mp->pool_size ) mp_do_compaction(mp, (A));
1090     else mp->max_pool_ptr=mp->pool_ptr+(A); }
1091   }
1092
1093 @ The following routine is similar to |str_room(1)| but it uses the
1094 argument |mp->pool_size| to prevent |do_compaction| from aborting when
1095 string space is exhausted.
1096
1097 @<Declare the procedure called |unit_str_room|@>=
1098 void mp_unit_str_room (MP mp);
1099
1100 @ @c
1101 void mp_unit_str_room (MP mp) { 
1102   if ( mp->pool_ptr>=mp->pool_size ) mp_do_compaction(mp, mp->pool_size);
1103   if ( mp->pool_ptr>=mp->max_pool_ptr ) mp->max_pool_ptr=mp->pool_ptr+1;
1104 }
1105
1106 @ \MP's string expressions are implemented in a brute-force way: Every
1107 new string or substring that is needed is simply copied into the string pool.
1108 Space is eventually reclaimed by a procedure called |do_compaction| with
1109 the aid of a simple system system of reference counts.
1110 @^reference counts@>
1111
1112 The number of references to string number |s| will be |str_ref[s]|. The
1113 special value |str_ref[s]=max_str_ref=127| is used to denote an unknown
1114 positive number of references; such strings will never be recycled. If
1115 a string is ever referred to more than 126 times, simultaneously, we
1116 put it in this category. Hence a single byte suffices to store each |str_ref|.
1117
1118 @d max_str_ref 127 /* ``infinite'' number of references */
1119 @d add_str_ref(A) { if ( mp->str_ref[(A)]<max_str_ref ) incr(mp->str_ref[(A)]);
1120   }
1121
1122 @<Glob...@>=
1123 int *str_ref;
1124
1125 @ @<Allocate or initialize ...@>=
1126 mp->str_ref = xmalloc ((mp->max_strings+1),sizeof(int));
1127
1128 @ @<Dealloc variables@>=
1129 xfree(mp->str_ref);
1130
1131 @ Here's what we do when a string reference disappears:
1132
1133 @d delete_str_ref(A)  { 
1134     if ( mp->str_ref[(A)]<max_str_ref ) {
1135        if ( mp->str_ref[(A)]>1 ) decr(mp->str_ref[(A)]); 
1136        else mp_flush_string(mp, (A));
1137     }
1138   }
1139
1140 @<Declare the procedure called |flush_string|@>=
1141 void mp_flush_string (MP mp,str_number s) ;
1142
1143
1144 @ We can't flush the first set of static strings at all, so there 
1145 is no point in trying
1146
1147 @c
1148 void mp_flush_string (MP mp,str_number s) { 
1149   if (length(s)>1) {
1150     mp->pool_in_use=mp->pool_in_use-length(s);
1151     decr(mp->strs_in_use);
1152     if ( mp->next_str[s]!=mp->str_ptr ) {
1153       mp->str_ref[s]=0;
1154     } else { 
1155       mp->str_ptr=s;
1156       decr(mp->strs_used_up);
1157     }
1158     mp->pool_ptr=mp->str_start[mp->str_ptr];
1159   }
1160 }
1161
1162 @ C literals cannot be simply added, they need to be set so they can't
1163 be flushed.
1164
1165 @d intern(A) mp_intern(mp,(A))
1166
1167 @c
1168 str_number mp_intern (MP mp, char *s) {
1169   str_number r ;
1170   r = rts(s);
1171   mp->str_ref[r] = max_str_ref;
1172   return r;
1173 }
1174
1175 @ @<Declarations@>=
1176 str_number mp_intern (MP mp, char *s);
1177
1178
1179 @ Once a sequence of characters has been appended to |str_pool|, it
1180 officially becomes a string when the function |make_string| is called.
1181 This function returns the identification number of the new string as its
1182 value.
1183
1184 When getting the next unused string number from the linked list, we pretend
1185 that
1186 $$ \hbox{|max_str_ptr+1|, |max_str_ptr+2|, $\ldots$, |mp->max_strings|} $$
1187 are linked sequentially even though the |next_str| entries have not been
1188 initialized yet.  We never allow |str_ptr| to reach |mp->max_strings|;
1189 |do_compaction| is responsible for making sure of this.
1190
1191 @<Declarations@>=
1192 @<Declare the procedure called |do_compaction|@>;
1193 @<Declare the procedure called |unit_str_room|@>;
1194 str_number mp_make_string (MP mp);
1195
1196 @ @c 
1197 str_number mp_make_string (MP mp) { /* current string enters the pool */
1198   str_number s; /* the new string */
1199 RESTART: 
1200   s=mp->str_ptr;
1201   mp->str_ptr=mp->next_str[s];
1202   if ( mp->str_ptr>mp->max_str_ptr ) {
1203     if ( mp->str_ptr==mp->max_strings ) { 
1204       mp->str_ptr=s;
1205       mp_do_compaction(mp, 0);
1206       goto RESTART;
1207     } else {
1208 #ifdef DEBUG 
1209       if ( mp->strs_used_up!=mp->max_str_ptr ) mp_confusion(mp, "s");
1210 @:this can't happen s}{\quad \.s@>
1211 #endif
1212       mp->max_str_ptr=mp->str_ptr;
1213       mp->next_str[mp->str_ptr]=mp->max_str_ptr+1;
1214     }
1215   }
1216   mp->str_ref[s]=1;
1217   mp->str_start[mp->str_ptr]=mp->pool_ptr;
1218   incr(mp->strs_used_up);
1219   incr(mp->strs_in_use);
1220   mp->pool_in_use=mp->pool_in_use+length(s);
1221   if ( mp->pool_in_use>mp->max_pl_used ) 
1222     mp->max_pl_used=mp->pool_in_use;
1223   if ( mp->strs_in_use>mp->max_strs_used ) 
1224     mp->max_strs_used=mp->strs_in_use;
1225   return s;
1226 }
1227
1228 @ The most interesting string operation is string pool compaction.  The idea
1229 is to recover unused space in the |str_pool| array by recopying the strings
1230 to close the gaps created when some strings become unused.  All string
1231 numbers~$k$ where |str_ref[k]=0| are to be linked into the list of free string
1232 numbers after |str_ptr|.  If this fails to free enough pool space we issue an
1233 |overflow| error unless |needed=mp->pool_size|.  Calling |do_compaction|
1234 with |needed=mp->pool_size| supresses all overflow tests.
1235
1236 The compaction process starts with |last_fixed_str| because all lower numbered
1237 strings are permanently allocated with |max_str_ref| in their |str_ref| entries.
1238
1239 @<Glob...@>=
1240 str_number last_fixed_str; /* last permanently allocated string */
1241 str_number fixed_str_use; /* number of permanently allocated strings */
1242
1243 @ @<Declare the procedure called |do_compaction|@>=
1244 void mp_do_compaction (MP mp, pool_pointer needed) ;
1245
1246 @ @c
1247 void mp_do_compaction (MP mp, pool_pointer needed) {
1248   str_number str_use; /* a count of strings in use */
1249   str_number r,s,t; /* strings being manipulated */
1250   pool_pointer p,q; /* destination and source for copying string characters */
1251   @<Advance |last_fixed_str| as far as possible and set |str_use|@>;
1252   r=mp->last_fixed_str;
1253   s=mp->next_str[r];
1254   p=mp->str_start[s];
1255   while ( s!=mp->str_ptr ) { 
1256     while ( mp->str_ref[s]==0 ) {
1257       @<Advance |s| and add the old |s| to the list of free string numbers;
1258         then |break| if |s=str_ptr|@>;
1259     }
1260     r=s; s=mp->next_str[s];
1261     incr(str_use);
1262     @<Move string |r| back so that |str_start[r]=p|; make |p| the location
1263      after the end of the string@>;
1264   }
1265   @<Move the current string back so that it starts at |p|@>;
1266   if ( needed<mp->pool_size ) {
1267     @<Make sure that there is room for another string with |needed| characters@>;
1268   }
1269   @<Account for the compaction and make sure the statistics agree with the
1270      global versions@>;
1271   mp->strs_used_up=str_use;
1272 }
1273
1274 @ @<Advance |last_fixed_str| as far as possible and set |str_use|@>=
1275 t=mp->next_str[mp->last_fixed_str];
1276 while ( (mp->str_ref[t]==max_str_ref)&&(t!=mp->str_ptr) ) { 
1277   incr(mp->fixed_str_use);
1278   mp->last_fixed_str=t;
1279   t=mp->next_str[t];
1280 }
1281 str_use=mp->fixed_str_use
1282
1283 @ Because of the way |flush_string| has been written, it should never be
1284 necessary to |break| here.  The extra line of code seems worthwhile to
1285 preserve the generality of |do_compaction|.
1286
1287 @<Advance |s| and add the old |s| to the list of free string numbers;...@>=
1288 {
1289 t=s;
1290 s=mp->next_str[s];
1291 mp->next_str[r]=s;
1292 mp->next_str[t]=mp->next_str[mp->str_ptr];
1293 mp->next_str[mp->str_ptr]=t;
1294 if ( s==mp->str_ptr ) break;
1295 }
1296
1297 @ The string currently starts at |str_start[r]| and ends just before
1298 |str_start[s]|.  We don't change |str_start[s]| because it might be needed
1299 to locate the next string.
1300
1301 @<Move string |r| back so that |str_start[r]=p|; make |p| the location...@>=
1302 q=mp->str_start[r];
1303 mp->str_start[r]=p;
1304 while ( q<mp->str_start[s] ) { 
1305   mp->str_pool[p]=mp->str_pool[q];
1306   incr(p); incr(q);
1307 }
1308
1309 @ Pointers |str_start[str_ptr]| and |pool_ptr| have not been updated.  When
1310 we do this, anything between them should be moved.
1311
1312 @ @<Move the current string back so that it starts at |p|@>=
1313 q=mp->str_start[mp->str_ptr];
1314 mp->str_start[mp->str_ptr]=p;
1315 while ( q<mp->pool_ptr ) { 
1316   mp->str_pool[p]=mp->str_pool[q];
1317   incr(p); incr(q);
1318 }
1319 mp->pool_ptr=p
1320
1321 @ We must remember that |str_ptr| is not allowed to reach |mp->max_strings|.
1322
1323 @<Make sure that there is room for another string with |needed| char...@>=
1324 if ( str_use>=mp->max_strings-1 )
1325   mp_reallocate_strings (mp,str_use);
1326 if ( mp->pool_ptr+needed>mp->max_pool_ptr ) {
1327   mp_reallocate_pool(mp, mp->pool_ptr+needed);
1328   mp->max_pool_ptr=mp->pool_ptr+needed;
1329 }
1330
1331 @ @<Declarations@>=
1332 void mp_reallocate_strings (MP mp, str_number str_use) ;
1333 void mp_reallocate_pool(MP mp, pool_pointer needed) ;
1334
1335 @ @c 
1336 void mp_reallocate_strings (MP mp, str_number str_use) { 
1337   while ( str_use>=mp->max_strings-1 ) {
1338     int l = mp->max_strings + (mp->max_strings>>2);
1339     XREALLOC (mp->str_ref,   l, int);
1340     XREALLOC (mp->str_start, l, pool_pointer);
1341     XREALLOC (mp->next_str,  l, str_number);
1342     mp->max_strings = l;
1343   }
1344 }
1345 void mp_reallocate_pool(MP mp, pool_pointer needed) {
1346   while ( needed>mp->pool_size ) {
1347     int l = mp->pool_size + (mp->pool_size>>2);
1348         XREALLOC (mp->str_pool, l, ASCII_code);
1349     mp->pool_size = l;
1350   }
1351 }
1352
1353 @ @<Account for the compaction and make sure the statistics agree with...@>=
1354 if ( (mp->str_start[mp->str_ptr]!=mp->pool_in_use)||(str_use!=mp->strs_in_use) )
1355   mp_confusion(mp, "string");
1356 @:this can't happen string}{\quad string@>
1357 incr(mp->pact_count);
1358 mp->pact_chars=mp->pact_chars+mp->pool_ptr-str_stop(mp->last_fixed_str);
1359 mp->pact_strs=mp->pact_strs+str_use-mp->fixed_str_use;
1360 #ifdef DEBUG
1361 s=mp->str_ptr; t=str_use;
1362 while ( s<=mp->max_str_ptr ){
1363   if ( t>mp->max_str_ptr ) mp_confusion(mp, "\"");
1364   incr(t); s=mp->next_str[s];
1365 };
1366 if ( t<=mp->max_str_ptr ) mp_confusion(mp, "\"");
1367 #endif
1368
1369 @ A few more global variables are needed to keep track of statistics when
1370 |stat| $\ldots$ |tats| blocks are not commented out.
1371
1372 @<Glob...@>=
1373 integer pact_count; /* number of string pool compactions so far */
1374 integer pact_chars; /* total number of characters moved during compactions */
1375 integer pact_strs; /* total number of strings moved during compactions */
1376
1377 @ @<Initialize compaction statistics@>=
1378 mp->pact_count=0;
1379 mp->pact_chars=0;
1380 mp->pact_strs=0;
1381
1382 @ The following subroutine compares string |s| with another string of the
1383 same length that appears in |buffer| starting at position |k|;
1384 the result is |true| if and only if the strings are equal.
1385
1386 @c 
1387 boolean mp_str_eq_buf (MP mp,str_number s, integer k) {
1388   /* test equality of strings */
1389   pool_pointer j; /* running index */
1390   j=mp->str_start[s];
1391   while ( j<str_stop(s) ) { 
1392     if ( mp->str_pool[j++]!=mp->buffer[k++] ) 
1393       return false;
1394   }
1395   return true;
1396 }
1397
1398 @ Here is a similar routine, but it compares two strings in the string pool,
1399 and it does not assume that they have the same length. If the first string
1400 is lexicographically greater than, less than, or equal to the second,
1401 the result is respectively positive, negative, or zero.
1402
1403 @c 
1404 integer mp_str_vs_str (MP mp, str_number s, str_number t) {
1405   /* test equality of strings */
1406   pool_pointer j,k; /* running indices */
1407   integer ls,lt; /* lengths */
1408   integer l; /* length remaining to test */
1409   ls=length(s); lt=length(t);
1410   if ( ls<=lt ) l=ls; else l=lt;
1411   j=mp->str_start[s]; k=mp->str_start[t];
1412   while ( l-->0 ) { 
1413     if ( mp->str_pool[j]!=mp->str_pool[k] ) {
1414        return (mp->str_pool[j]-mp->str_pool[k]); 
1415     }
1416     incr(j); incr(k);
1417   }
1418   return (ls-lt);
1419 }
1420
1421 @ The initial values of |str_pool|, |str_start|, |pool_ptr|,
1422 and |str_ptr| are computed by the \.{INIMP} program, based in part
1423 on the information that \.{WEB} has output while processing \MP.
1424 @.INIMP@>
1425 @^string pool@>
1426
1427 @c 
1428 void mp_get_strings_started (MP mp) { 
1429   /* initializes the string pool,
1430     but returns |false| if something goes wrong */
1431   int k; /* small indices or counters */
1432   str_number g; /* a new string */
1433   mp->pool_ptr=0; mp->str_ptr=0; mp->max_pool_ptr=0; mp->max_str_ptr=0;
1434   mp->str_start[0]=0;
1435   mp->next_str[0]=1;
1436   mp->pool_in_use=0; mp->strs_in_use=0;
1437   mp->max_pl_used=0; mp->max_strs_used=0;
1438   @<Initialize compaction statistics@>;
1439   mp->strs_used_up=0;
1440   @<Make the first 256 strings@>;
1441   g=mp_make_string(mp); /* string 256 == "" */
1442   mp->last_fixed_str=mp->str_ptr-1;
1443   mp->fixed_str_use=mp->str_ptr;
1444   return;
1445 }
1446
1447 @ @<Declarations@>=
1448 void mp_get_strings_started (MP mp);
1449
1450 @ The first 256 strings will consist of a single character only.
1451
1452 @<Make the first 256...@>=
1453 for (k=0;k<=255;k++) { 
1454   append_char(k);
1455   g=mp_make_string(mp); 
1456   mp->str_ref[g]=max_str_ref;
1457 }
1458
1459 @ The first 128 strings will contain 95 standard ASCII characters, and the
1460 other 33 characters will be printed in three-symbol form like `\.{\^\^A}'
1461 unless a system-dependent change is made here. Installations that have
1462 an extended character set, where for example |xchr[032]=@t\.{'^^Z'}@>|,
1463 would like string 032 to be printed as the single character 032 instead
1464 of the three characters 0136, 0136, 0132 (\.{\^\^Z}). On the other hand,
1465 even people with an extended character set will want to represent string
1466 015 by \.{\^\^M}, since 015 is ASCII's ``carriage return'' code; the idea is
1467 to produce visible strings instead of tabs or line-feeds or carriage-returns
1468 or bell-rings or characters that are treated anomalously in text files.
1469
1470 Unprintable characters of codes 128--255 are, similarly, rendered
1471 \.{\^\^80}--\.{\^\^ff}.
1472
1473 The boolean expression defined here should be |true| unless \MP\ internal
1474 code number~|k| corresponds to a non-troublesome visible symbol in the
1475 local character set.
1476 If character |k| cannot be printed, and |k<0200|, then character |k+0100| or
1477 |k-0100| must be printable; moreover, ASCII codes |[060..071, 0141..0146]|
1478 must be printable.
1479 @^character set dependencies@>
1480 @^system dependencies@>
1481
1482 @<Character |k| cannot be printed@>=
1483   (k<' ')||(k>'~')
1484
1485 @* \[5] On-line and off-line printing.
1486 Messages that are sent to a user's terminal and to the transcript-log file
1487 are produced by several `|print|' procedures. These procedures will
1488 direct their output to a variety of places, based on the setting of
1489 the global variable |selector|, which has the following possible
1490 values:
1491
1492 \yskip
1493 \hang |term_and_log|, the normal setting, prints on the terminal and on the
1494   transcript file.
1495
1496 \hang |log_only|, prints only on the transcript file.
1497
1498 \hang |term_only|, prints only on the terminal.
1499
1500 \hang |no_print|, doesn't print at all. This is used only in rare cases
1501   before the transcript file is open.
1502
1503 \hang |ps_file_only| prints only on the \ps\ output file.
1504
1505 \hang |pseudo|, puts output into a cyclic buffer that is used
1506   by the |show_context| routine; when we get to that routine we shall discuss
1507   the reasoning behind this curious mode.
1508
1509 \hang |new_string|, appends the output to the current string in the
1510   string pool.
1511
1512 \hang |>=write_file| prints on one of the files used for the \&{write}
1513 @:write_}{\&{write} primitive@>
1514   command.
1515
1516 \yskip
1517 \noindent The symbolic names `|term_and_log|', etc., have been assigned
1518 numeric codes that satisfy the convenient relations |no_print+1=term_only|,
1519 |no_print+2=log_only|, |term_only+2=log_only+1=term_and_log|.  These
1520 relations are not used when |selector| could be |pseudo|, |new_string|,
1521 or |ps_file_only|.  We need not check for unprintable characters when
1522 |selector<pseudo|.
1523
1524 Four additional global variables, |tally|, |term_offset|, |file_offset|,
1525 and |ps_offset| record the number of characters that have been printed
1526 since they were most recently cleared to zero. We use |tally| to record
1527 the length of (possibly very long) stretches of printing; |term_offset|,
1528 |file_offset|, and |ps_offset|, on the other hand, keep track of how many
1529 characters have appeared so far on the current line that has been output
1530 to the terminal, the transcript file, or the \ps\ output file, respectively.
1531
1532 @d new_string 0 /* printing is deflected to the string pool */
1533 @d ps_file_only 1 /* printing goes to the \ps\ output file */
1534 @d pseudo 2 /* special |selector| setting for |show_context| */
1535 @d no_print 3 /* |selector| setting that makes data disappear */
1536 @d term_only 4 /* printing is destined for the terminal only */
1537 @d log_only 5 /* printing is destined for the transcript file only */
1538 @d term_and_log 6 /* normal |selector| setting */
1539 @d write_file 7 /* first write file selector */
1540
1541 @<Glob...@>=
1542 FILE * log_file; /* transcript of \MP\ session */
1543 FILE * ps_file; /* the generic font output goes here */
1544 unsigned int selector; /* where to print a message */
1545 unsigned char dig[23]; /* digits in a number being output */
1546 integer tally; /* the number of characters recently printed */
1547 unsigned int term_offset;
1548   /* the number of characters on the current terminal line */
1549 unsigned int file_offset;
1550   /* the number of characters on the current file line */
1551 integer ps_offset;
1552   /* the number of characters on the current \ps\ file line */
1553 ASCII_code *trick_buf; /* circular buffer for pseudoprinting */
1554 integer trick_count; /* threshold for pseudoprinting, explained later */
1555 integer first_count; /* another variable for pseudoprinting */
1556
1557 @ @<Allocate or initialize ...@>=
1558 memset(mp->dig,0,23);
1559 mp->trick_buf = xmalloc((mp->error_line+1),sizeof(ASCII_code));
1560
1561 @ @<Dealloc variables@>=
1562 xfree(mp->trick_buf);
1563
1564 @ @<Initialize the output routines@>=
1565 mp->selector=term_only; mp->tally=0; mp->term_offset=0; mp->file_offset=0; mp->ps_offset=0;
1566
1567 @ Macro abbreviations for output to the terminal and to the log file are
1568 defined here for convenience. Some systems need special conventions
1569 for terminal output, and it is possible to adhere to those conventions
1570 by changing |wterm|, |wterm_ln|, and |wterm_cr| here.
1571 @^system dependencies@>
1572
1573 @d wterm(A)    fprintf(mp->term_out,"%s",(A))
1574 @d wterm_chr(A)fprintf(mp->term_out,"%c",(A))
1575 @d wterm_ln(A) fprintf(mp->term_out,"\n%s",(A))
1576 @d wterm_cr    fprintf(mp->term_out,"\n")
1577 @d wlog(A)     fprintf(mp->log_file,"%s",(A))
1578 @d wlog_chr(A) fprintf(mp->log_file,"%c",(A))
1579 @d wlog_ln(A)  fprintf(mp->log_file,"\n%s",(A))
1580 @d wlog_cr     fprintf(mp->log_file, "\n")
1581 @d wps(A)      fprintf(mp->ps_file,"%s",(A))
1582 @d wps_chr(A)  fprintf(mp->ps_file,"%c",(A))
1583 @d wps_ln(A)   fprintf(mp->ps_file,,"\n%s",(A))
1584 @d wps_cr      fprintf(mp->ps_file,"\n")
1585
1586 @ To end a line of text output, we call |print_ln|.  Cases |0..max_write_files|
1587 use an array |wr_file| that will be declared later.
1588
1589 @d mp_print_text(A) mp_print_str(mp,text((A)))
1590
1591 @<Exported...@>=
1592 void mp_print_ln (MP mp);
1593 void mp_print_visible_char (MP mp, ASCII_code s); 
1594 void mp_print_char (MP mp, ASCII_code k);
1595 void mp_print (MP mp, char *s);
1596 void mp_print_str (MP mp, str_number s);
1597 void mp_print_nl (MP mp, char *s);
1598 void mp_print_two (MP mp,scaled x, scaled y) ;
1599 void mp_print_scaled (MP mp,scaled s);
1600
1601 @ @<Basic print...@>=
1602 void mp_print_ln (MP mp) { /* prints an end-of-line */
1603  switch (mp->selector) {
1604   case term_and_log: 
1605     wterm_cr; wlog_cr;
1606     mp->term_offset=0;  mp->file_offset=0;
1607     break;
1608   case log_only: 
1609     wlog_cr; mp->file_offset=0;
1610     break;
1611   case term_only: 
1612     wterm_cr; mp->term_offset=0;
1613     break;
1614   case ps_file_only: 
1615     wps_cr; mp->ps_offset=0;
1616     break;
1617   case no_print:
1618   case pseudo: 
1619   case new_string: 
1620     break;
1621   default: 
1622     fprintf(mp->wr_file[(mp->selector-write_file)],"\n");
1623   }
1624 } /* note that |tally| is not affected */
1625
1626 @ The |print_visible_char| procedure sends one character to the desired
1627 destination, using the |xchr| array to map it into an external character
1628 compatible with |input_ln|.  (It assumes that it is always called with
1629 a visible ASCII character.)  All printing comes through |print_ln| or
1630 |print_char|, which ultimately calls |print_visible_char|, hence these
1631 routines are the ones that limit lines to at most |max_print_line| characters.
1632 But we must make an exception for the \ps\ output file since it is not safe
1633 to cut up lines arbitrarily in \ps.
1634
1635 Procedure |unit_str_room| needs to be declared |forward| here because it calls
1636 |do_compaction| and |do_compaction| can call the error routines.  Actually,
1637 |unit_str_room| avoids |overflow| errors but it can call |confusion|.
1638
1639 @<Basic printing...@>=
1640 void mp_print_visible_char (MP mp, ASCII_code s) { /* prints a single character */
1641   switch (mp->selector) {
1642   case term_and_log: 
1643     wterm_chr(xchr(s)); wlog_chr(xchr(s));
1644     incr(mp->term_offset); incr(mp->file_offset);
1645     if ( mp->term_offset==(unsigned)mp->max_print_line ) { 
1646        wterm_cr; mp->term_offset=0;
1647     };
1648     if ( mp->file_offset==(unsigned)mp->max_print_line ) { 
1649        wlog_cr; mp->file_offset=0;
1650     };
1651     break;
1652   case log_only: 
1653     wlog_chr(xchr(s)); incr(mp->file_offset);
1654     if ( mp->file_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1655     break;
1656   case term_only: 
1657     wterm_chr(xchr(s)); incr(mp->term_offset);
1658     if ( mp->term_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1659     break;
1660   case ps_file_only: 
1661     if ( s==13 ) {
1662       wps_cr; mp->ps_offset=0;
1663     } else {
1664       wps_chr(xchr(s)); incr(mp->ps_offset);
1665     };
1666     break;
1667   case no_print: 
1668     break;
1669   case pseudo: 
1670     if ( mp->tally<mp->trick_count ) 
1671       mp->trick_buf[mp->tally % mp->error_line]=s;
1672     break;
1673   case new_string: 
1674     if ( mp->pool_ptr>=mp->max_pool_ptr ) { 
1675       mp_unit_str_room(mp);
1676       if ( mp->pool_ptr>=mp->pool_size ) 
1677         goto DONE; /* drop characters if string space is full */
1678     };
1679     append_char(s);
1680     break;
1681   default:
1682     fprintf(mp->wr_file[(mp->selector-write_file)],"%c",xchr(s));
1683   }
1684 DONE:
1685   incr(mp->tally);
1686 }
1687
1688 @ The |print_char| procedure sends one character to the desired destination.
1689 File names and string expressions might contain |ASCII_code| values that
1690 can't be printed using |print_visible_char|.  These characters will be
1691 printed in three- or four-symbol form like `\.{\^\^A}' or `\.{\^\^e4}'.
1692 (This procedure assumes that it is safe to bypass all checks for unprintable
1693 characters when |selector| is in the range |0..max_write_files-1| or when
1694 |selector=ps_file_only|.  In the former case the user might want to write
1695 unprintable characters, and in the latter case the \ps\ printing routines
1696 check their arguments themselves before calling |print_char| or |print|.)
1697
1698 @d print_lc_hex(A) do { l=(A);
1699     mp_print_visible_char(mp, (l<10 ? l+'0' : l-10+'a'));
1700   } while (0)
1701
1702 @<Basic printing...@>=
1703 void mp_print_char (MP mp, ASCII_code k) { /* prints a single character */
1704   int l; /* small index or counter */
1705   if ( mp->selector<pseudo || mp->selector>=write_file) {
1706     mp_print_visible_char(mp, k);
1707   } else if ( @<Character |k| cannot be printed@> ) { 
1708     mp_print(mp, "^^"); 
1709     if ( k<0100 ) { 
1710       mp_print_visible_char(mp, k+0100); 
1711     } else if ( k<0200 ) { 
1712       mp_print_visible_char(mp, k-0100); 
1713     } else { 
1714       print_lc_hex(k / 16);  
1715       print_lc_hex(k % 16); 
1716     }
1717   } else {
1718     mp_print_visible_char(mp, k);
1719   }
1720 };
1721
1722 @ An entire string is output by calling |print|. Note that if we are outputting
1723 the single standard ASCII character \.c, we could call |print("c")|, since
1724 |"c"=99| is the number of a single-character string, as explained above. But
1725 |print_char("c")| is quicker, so \MP\ goes directly to the |print_char|
1726 routine when it knows that this is safe. (The present implementation
1727 assumes that it is always safe to print a visible ASCII character.)
1728 @^system dependencies@>
1729
1730 @<Basic print...@>=
1731 void mp_do_print (MP mp, char *ss, unsigned int len) { /* prints string |s| */
1732   unsigned int j = 0;
1733   while ( j<len ){ 
1734     mp_print_char(mp, ss[j]); incr(j);
1735   }
1736 }
1737
1738
1739 @<Basic print...@>=
1740 void mp_print (MP mp, char *ss) {
1741   mp_do_print(mp, ss, strlen(ss));
1742 }
1743 void mp_print_str (MP mp, str_number s) {
1744   pool_pointer j; /* current character code position */
1745   if ( (s<0)||(s>mp->max_str_ptr) ) {
1746      mp_do_print(mp,"???",3); /* this can't happen */
1747 @.???@>
1748   }
1749   j=mp->str_start[s];
1750   mp_do_print(mp, (char *)(mp->str_pool+j), (str_stop(s)-j));
1751 }
1752
1753
1754 @ Here is the very first thing that \MP\ prints: a headline that identifies
1755 the version number and base name. The |term_offset| variable is temporarily
1756 incorrect, but the discrepancy is not serious since we assume that the banner
1757 and mem identifier together will occupy at most |max_print_line|
1758 character positions.
1759
1760 @<Initialize the output...@>=
1761 wterm (banner);
1762 wterm (version_string);
1763 if (mp->mem_ident!=NULL) 
1764   mp_print(mp,mp->mem_ident); 
1765 mp_print_ln(mp);
1766 update_terminal;
1767
1768 @ The procedure |print_nl| is like |print|, but it makes sure that the
1769 string appears at the beginning of a new line.
1770
1771 @<Basic print...@>=
1772 void mp_print_nl (MP mp, char *s) { /* prints string |s| at beginning of line */
1773   switch(mp->selector) {
1774   case term_and_log: 
1775     if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_ln(mp);
1776     break;
1777   case log_only: 
1778     if ( mp->file_offset>0 ) mp_print_ln(mp);
1779     break;
1780   case term_only: 
1781     if ( mp->term_offset>0 ) mp_print_ln(mp);
1782     break;
1783   case ps_file_only: 
1784     if ( mp->ps_offset>0 ) mp_print_ln(mp);
1785     break;
1786   case no_print:
1787   case pseudo:
1788   case new_string: 
1789         break;
1790   } /* there are no other cases */
1791   mp_print(mp, s);
1792 }
1793
1794 @ An array of digits in the range |0..9| is printed by |print_the_digs|.
1795
1796 @<Basic print...@>=
1797 void mp_print_the_digs (MP mp, eight_bits k) {
1798   /* prints |dig[k-1]|$\,\ldots\,$|dig[0]| */
1799   while ( k>0 ){ 
1800     decr(k); mp_print_char(mp, '0'+mp->dig[k]);
1801   }
1802 };
1803
1804 @ The following procedure, which prints out the decimal representation of a
1805 given integer |n|, has been written carefully so that it works properly
1806 if |n=0| or if |(-n)| would cause overflow. It does not apply |mod| or |div|
1807 to negative arguments, since such operations are not implemented consistently
1808 by all \PASCAL\ compilers.
1809
1810 @<Basic print...@>=
1811 void mp_print_int (MP mp,integer n) { /* prints an integer in decimal form */
1812   integer m; /* used to negate |n| in possibly dangerous cases */
1813   int k = 0; /* index to current digit; we assume that $|n|<10^{23}$ */
1814   if ( n<0 ) { 
1815     mp_print_char(mp, '-');
1816     if ( n>-100000000 ) {
1817           negate(n);
1818     } else  { 
1819           m=-1-n; n=m / 10; m=(m % 10)+1; k=1;
1820       if ( m<10 ) {
1821         mp->dig[0]=m;
1822       } else { 
1823         mp->dig[0]=0; incr(n);
1824       }
1825     }
1826   }
1827   do {  
1828     mp->dig[k]=n % 10; n=n / 10; incr(k);
1829   } while (n!=0);
1830   mp_print_the_digs(mp, k);
1831 };
1832
1833 @ @<Exported...@>=
1834 void mp_print_int (MP mp,integer n);
1835
1836 @ \MP\ also makes use of a trivial procedure to print two digits. The
1837 following subroutine is usually called with a parameter in the range |0<=n<=99|.
1838
1839 @c 
1840 void mp_print_dd (MP mp,integer n) { /* prints two least significant digits */
1841   n=abs(n) % 100; 
1842   mp_print_char(mp, '0'+(n / 10));
1843   mp_print_char(mp, '0'+(n % 10));
1844 }
1845
1846 @ Here is a procedure that asks the user to type a line of input,
1847 assuming that the |selector| setting is either |term_only| or |term_and_log|.
1848 The input is placed into locations |first| through |last-1| of the
1849 |buffer| array, and echoed on the transcript file if appropriate.
1850
1851 This procedure is never called when |interaction<mp_scroll_mode|.
1852
1853 @d prompt_input(A) do { 
1854     wake_up_terminal; mp_print(mp, (A)); mp_term_input(mp);
1855   } while (0) /* prints a string and gets a line of input */
1856
1857 @c 
1858 void mp_term_input (MP mp) { /* gets a line from the terminal */
1859   size_t k; /* index into |buffer| */
1860   update_terminal; /* Now the user sees the prompt for sure */
1861   if (!mp_input_ln(mp, mp->term_in,true)) 
1862     mp_fatal_error(mp, "End of file on the terminal!");
1863 @.End of file on the terminal@>
1864   mp->term_offset=0; /* the user's line ended with \<\rm return> */
1865   decr(mp->selector); /* prepare to echo the input */
1866   if ( mp->last!=mp->first ) {
1867     for (k=mp->first;k<=mp->last-1;k++) {
1868       mp_print_char(mp, mp->buffer[k]);
1869     }
1870   }
1871   mp_print_ln(mp); 
1872   mp->buffer[mp->last]='%'; 
1873   incr(mp->selector); /* restore previous status */
1874 };
1875
1876 @* \[6] Reporting errors.
1877 When something anomalous is detected, \MP\ typically does something like this:
1878 $$\vbox{\halign{#\hfil\cr
1879 |print_err("Something anomalous has been detected");|\cr
1880 |help3("This is the first line of my offer to help.")|\cr
1881 |("This is the second line. I'm trying to")|\cr
1882 |("explain the best way for you to proceed.");|\cr
1883 |error;|\cr}}$$
1884 A two-line help message would be given using |help2|, etc.; these informal
1885 helps should use simple vocabulary that complements the words used in the
1886 official error message that was printed. (Outside the U.S.A., the help
1887 messages should preferably be translated into the local vernacular. Each
1888 line of help is at most 60 characters long, in the present implementation,
1889 so that |max_print_line| will not be exceeded.)
1890
1891 The |print_err| procedure supplies a `\.!' before the official message,
1892 and makes sure that the terminal is awake if a stop is going to occur.
1893 The |error| procedure supplies a `\..' after the official message, then it
1894 shows the location of the error; and if |interaction=error_stop_mode|,
1895 it also enters into a dialog with the user, during which time the help
1896 message may be printed.
1897 @^system dependencies@>
1898
1899 @ The global variable |interaction| has four settings, representing increasing
1900 amounts of user interaction:
1901
1902 @<Types...@>=
1903 enum { 
1904  mp_unspecified_mode=0, /* extra value for command-line switch */
1905  mp_batch_mode, /* omits all stops and omits terminal output */
1906  mp_nonstop_mode, /* omits all stops */
1907  mp_scroll_mode, /* omits error stops */
1908  mp_error_stop_mode, /* stops at every opportunity to interact */
1909 };
1910
1911 @ @<Glob...@>=
1912 int interaction; /* current level of interaction */
1913
1914 @ @<Option variables@>=
1915 int interaction; /* current level of interaction */
1916
1917 @ Set it here so it can be overwritten by the commandline
1918
1919 @<Allocate or initialize ...@>=
1920 mp->interaction=opt.interaction;
1921 if (mp->interaction==mp_unspecified_mode || mp->interaction>mp_error_stop_mode) 
1922   mp->interaction=mp_error_stop_mode;
1923 if (mp->interaction<mp_unspecified_mode) 
1924   mp->interaction=mp_batch_mode;
1925
1926
1927
1928 @d print_err(A) mp_print_err(mp,(A))
1929
1930 @<Exported...@>=
1931 void mp_print_err(MP mp, char * A);
1932
1933 @ @c
1934 void mp_print_err(MP mp, char * A) { 
1935   if ( mp->interaction==mp_error_stop_mode ) 
1936     wake_up_terminal;
1937   mp_print_nl(mp, "! "); 
1938   mp_print(mp, A);
1939 @.!\relax@>
1940 }
1941
1942
1943 @ \MP\ is careful not to call |error| when the print |selector| setting
1944 might be unusual. The only possible values of |selector| at the time of
1945 error messages are
1946
1947 \yskip\hang|no_print| (when |interaction=mp_batch_mode|
1948   and |log_file| not yet open);
1949
1950 \hang|term_only| (when |interaction>mp_batch_mode| and |log_file| not yet open);
1951
1952 \hang|log_only| (when |interaction=mp_batch_mode| and |log_file| is open);
1953
1954 \hang|term_and_log| (when |interaction>mp_batch_mode| and |log_file| is open).
1955
1956 @<Initialize the print |selector| based on |interaction|@>=
1957 if ( mp->interaction==mp_batch_mode ) mp->selector=no_print; else mp->selector=term_only
1958
1959 @ A global variable |deletions_allowed| is set |false| if the |get_next|
1960 routine is active when |error| is called; this ensures that |get_next|
1961 will never be called recursively.
1962 @^recursion@>
1963
1964 The global variable |history| records the worst level of error that
1965 has been detected. It has four possible values: |spotless|, |warning_issued|,
1966 |error_message_issued|, and |fatal_error_stop|.
1967
1968 Another global variable, |error_count|, is increased by one when an
1969 |error| occurs without an interactive dialog, and it is reset to zero at
1970 the end of every statement.  If |error_count| reaches 100, \MP\ decides
1971 that there is no point in continuing further.
1972
1973 @d spotless 0 /* |history| value when nothing has been amiss yet */
1974 @d warning_issued 1 /* |history| value when |begin_diagnostic| has been called */
1975 @d error_message_issued 2 /* |history| value when |error| has been called */
1976 @d fatal_error_stop 3 /* |history| value when termination was premature */
1977
1978 @<Glob...@>=
1979 boolean deletions_allowed; /* is it safe for |error| to call |get_next|? */
1980 int history; /* has the source input been clean so far? */
1981 int error_count; /* the number of scrolled errors since the last statement ended */
1982
1983 @ The value of |history| is initially |fatal_error_stop|, but it will
1984 be changed to |spotless| if \MP\ survives the initialization process.
1985
1986 @<Allocate or ...@>=
1987 mp->deletions_allowed=true; mp->error_count=0; /* |history| is initialized elsewhere */
1988
1989 @ Since errors can be detected almost anywhere in \MP, we want to declare the
1990 error procedures near the beginning of the program. But the error procedures
1991 in turn use some other procedures, which need to be declared |forward|
1992 before we get to |error| itself.
1993
1994 It is possible for |error| to be called recursively if some error arises
1995 when |get_next| is being used to delete a token, and/or if some fatal error
1996 occurs while \MP\ is trying to fix a non-fatal one. But such recursion
1997 @^recursion@>
1998 is never more than two levels deep.
1999
2000 @<Declarations@>=
2001 void mp_get_next (MP mp);
2002 void mp_term_input (MP mp);
2003 void mp_show_context (MP mp);
2004 void mp_begin_file_reading (MP mp);
2005 void mp_open_log_file (MP mp);
2006 void mp_clear_for_error_prompt (MP mp);
2007 void mp_debug_help (MP mp);
2008 @<Declare the procedure called |flush_string|@>
2009
2010 @ @<Exported...@>=
2011 void mp_normalize_selector (MP mp);
2012
2013 @ Individual lines of help are recorded in the array |help_line|, which
2014 contains entries in positions |0..(help_ptr-1)|. They should be printed
2015 in reverse order, i.e., with |help_line[0]| appearing last.
2016
2017 @d hlp1(A) mp->help_line[0]=(A); }
2018 @d hlp2(A) mp->help_line[1]=(A); hlp1
2019 @d hlp3(A) mp->help_line[2]=(A); hlp2
2020 @d hlp4(A) mp->help_line[3]=(A); hlp3
2021 @d hlp5(A) mp->help_line[4]=(A); hlp4
2022 @d hlp6(A) mp->help_line[5]=(A); hlp5
2023 @d help0 mp->help_ptr=0 /* sometimes there might be no help */
2024 @d help1  { mp->help_ptr=1; hlp1 /* use this with one help line */
2025 @d help2  { mp->help_ptr=2; hlp2 /* use this with two help lines */
2026 @d help3  { mp->help_ptr=3; hlp3 /* use this with three help lines */
2027 @d help4  { mp->help_ptr=4; hlp4 /* use this with four help lines */
2028 @d help5  { mp->help_ptr=5; hlp5 /* use this with five help lines */
2029 @d help6  { mp->help_ptr=6; hlp6 /* use this with six help lines */
2030
2031 @<Glob...@>=
2032 char * help_line[6]; /* helps for the next |error| */
2033 unsigned int help_ptr; /* the number of help lines present */
2034 boolean use_err_help; /* should the |err_help| string be shown? */
2035 str_number err_help; /* a string set up by \&{errhelp} */
2036 str_number filename_template; /* a string set up by \&{filenametemplate} */
2037
2038 @ @<Allocate or ...@>=
2039 mp->help_ptr=0; mp->use_err_help=false; mp->err_help=0; mp->filename_template=0;
2040
2041 @ The |jump_out| procedure just cuts across all active procedure levels and
2042 goes to |end_of_MP|. This is the only nonlocal |goto| statement in the
2043 whole program. It is used when there is no recovery from a particular error.
2044
2045 Some \PASCAL\ compilers do not implement non-local |goto| statements.
2046 @^system dependencies@>
2047 In such cases the body of |jump_out| should simply be
2048 `|close_files_and_terminate|;\thinspace' followed by a call on some system
2049 procedure that quietly terminates the program.
2050
2051 @<Error hand...@>=
2052 void mp_jump_out (MP mp) { 
2053  exit(mp->history);
2054 };
2055
2056 @ Here now is the general |error| routine.
2057
2058 @<Error hand...@>=
2059 void mp_error (MP mp) { /* completes the job of error reporting */
2060   ASCII_code c; /* what the user types */
2061   integer s1,s2,s3; /* used to save global variables when deleting tokens */
2062   pool_pointer j; /* character position being printed */
2063   if ( mp->history<error_message_issued ) mp->history=error_message_issued;
2064   mp_print_char(mp, '.'); mp_show_context(mp);
2065   if ( mp->interaction==mp_error_stop_mode ) {
2066     @<Get user's advice and |return|@>;
2067   }
2068   incr(mp->error_count);
2069   if ( mp->error_count==100 ) { 
2070     mp_print_nl(mp,"(That makes 100 errors; please try again.)");
2071 @.That makes 100 errors...@>
2072     mp->history=fatal_error_stop; mp_jump_out(mp);
2073   }
2074   @<Put help message on the transcript file@>;
2075 }
2076 void mp_warn (MP mp, char *msg) {
2077   int saved_selector = mp->selector;
2078   mp_normalize_selector(mp);
2079   mp_print_nl(mp,"Warning: ");
2080   mp_print(mp,msg);
2081   mp->selector = saved_selector;
2082 }
2083
2084 @ @<Exported...@>=
2085 void mp_error (MP mp);
2086 void mp_warn (MP mp, char *msg);
2087
2088
2089 @ @<Get user's advice...@>=
2090 while (1) { 
2091 CONTINUE:
2092   mp_clear_for_error_prompt(mp); prompt_input("? ");
2093 @.?\relax@>
2094   if ( mp->last==mp->first ) return;
2095   c=mp->buffer[mp->first];
2096   if ( c>='a' ) c=c+'A'-'a'; /* convert to uppercase */
2097   @<Interpret code |c| and |return| if done@>;
2098 }
2099
2100 @ It is desirable to provide an `\.E' option here that gives the user
2101 an easy way to return from \MP\ to the system editor, with the offending
2102 line ready to be edited. But such an extension requires some system
2103 wizardry, so the present implementation simply types out the name of the
2104 file that should be
2105 edited and the relevant line number.
2106 @^system dependencies@>
2107
2108 @<Types...@>=
2109 typedef void (*run_editor_command)(MP, char *, int);
2110
2111 @ @<Glob...@>=
2112 run_editor_command run_editor;
2113
2114 @ @<Option variables@>=
2115 run_editor_command run_editor;
2116
2117 @ @<Allocate or initialize ...@>=
2118 set_callback_option(run_editor);
2119
2120 @ @<Exported function headers@>=
2121 void mp_run_editor (MP mp, char *fname, int fline);
2122
2123 @ @c void mp_run_editor (MP mp, char *fname, int fline) {
2124     mp_print_nl(mp, "You want to edit file ");
2125 @.You want to edit file x@>
2126     mp_print(mp, fname);
2127     mp_print(mp, " at line "); 
2128     mp_print_int(mp, fline);
2129     mp->interaction=mp_scroll_mode; 
2130     mp_jump_out(mp);
2131 }
2132
2133
2134 There is a secret `\.D' option available when the debugging routines haven't
2135 been commented~out.
2136 @^debugging@>
2137
2138 @<Interpret code |c| and |return| if done@>=
2139 switch (c) {
2140 case '0': case '1': case '2': case '3': case '4':
2141 case '5': case '6': case '7': case '8': case '9': 
2142   if ( mp->deletions_allowed ) {
2143     @<Delete |c-"0"| tokens and |continue|@>;
2144   }
2145   break;
2146 #ifdef DEBUG
2147 case 'D': 
2148   mp_debug_help(mp); continue; 
2149   break;
2150 #endif
2151 case 'E': 
2152   if ( mp->file_ptr>0 ){ 
2153     (mp->run_editor)(mp, 
2154                      str(mp->input_stack[mp->file_ptr].name_field), 
2155                      mp_true_line(mp));
2156   }
2157   break;
2158 case 'H': 
2159   @<Print the help information and |continue|@>;
2160   break;
2161 case 'I':
2162   @<Introduce new material from the terminal and |return|@>;
2163   break;
2164 case 'Q': case 'R': case 'S':
2165   @<Change the interaction level and |return|@>;
2166   break;
2167 case 'X':
2168   mp->interaction=mp_scroll_mode; mp_jump_out(mp);
2169   break;
2170 default:
2171   break;
2172 }
2173 @<Print the menu of available options@>
2174
2175 @ @<Print the menu...@>=
2176
2177   mp_print(mp, "Type <return> to proceed, S to scroll future error messages,");
2178 @.Type <return> to proceed...@>
2179   mp_print_nl(mp, "R to run without stopping, Q to run quietly,");
2180   mp_print_nl(mp, "I to insert something, ");
2181   if ( mp->file_ptr>0 ) 
2182     mp_print(mp, "E to edit your file,");
2183   if ( mp->deletions_allowed )
2184     mp_print_nl(mp, "1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
2185   mp_print_nl(mp, "H for help, X to quit.");
2186 }
2187
2188 @ Here the author of \MP\ apologizes for making use of the numerical
2189 relation between |"Q"|, |"R"|, |"S"|, and the desired interaction settings
2190 |mp_batch_mode|, |mp_nonstop_mode|, |mp_scroll_mode|.
2191 @^Knuth, Donald Ervin@>
2192
2193 @<Change the interaction...@>=
2194
2195   mp->error_count=0; mp->interaction=mp_batch_mode+c-'Q';
2196   mp_print(mp, "OK, entering ");
2197   switch (c) {
2198   case 'Q': mp_print(mp, "batchmode"); decr(mp->selector); break;
2199   case 'R': mp_print(mp, "nonstopmode"); break;
2200   case 'S': mp_print(mp, "scrollmode"); break;
2201   } /* there are no other cases */
2202   mp_print(mp, "..."); mp_print_ln(mp); update_terminal; return;
2203 }
2204
2205 @ When the following code is executed, |buffer[(first+1)..(last-1)]| may
2206 contain the material inserted by the user; otherwise another prompt will
2207 be given. In order to understand this part of the program fully, you need
2208 to be familiar with \MP's input stacks.
2209
2210 @<Introduce new material...@>=
2211
2212   mp_begin_file_reading(mp); /* enter a new syntactic level for terminal input */
2213   if ( mp->last>mp->first+1 ) { 
2214     loc=mp->first+1; mp->buffer[mp->first]=' ';
2215   } else { 
2216    prompt_input("insert>"); loc=mp->first;
2217 @.insert>@>
2218   };
2219   mp->first=mp->last+1; mp->cur_input.limit_field=mp->last; return;
2220 }
2221
2222 @ We allow deletion of up to 99 tokens at a time.
2223
2224 @<Delete |c-"0"| tokens...@>=
2225
2226   s1=mp->cur_cmd; s2=mp->cur_mod; s3=mp->cur_sym; mp->OK_to_interrupt=false;
2227   if ( (mp->last>mp->first+1) && (mp->buffer[mp->first+1]>='0')&&(mp->buffer[mp->first+1]<='9') )
2228     c=c*10+mp->buffer[mp->first+1]-'0'*11;
2229   else 
2230     c=c-'0';
2231   while ( c>0 ) { 
2232     mp_get_next(mp); /* one-level recursive call of |error| is possible */
2233     @<Decrease the string reference count, if the current token is a string@>;
2234     decr(c);
2235   };
2236   mp->cur_cmd=s1; mp->cur_mod=s2; mp->cur_sym=s3; mp->OK_to_interrupt=true;
2237   help2("I have just deleted some text, as you asked.")
2238        ("You can now delete more, or insert, or whatever.");
2239   mp_show_context(mp); 
2240   goto CONTINUE;
2241 }
2242
2243 @ @<Print the help info...@>=
2244
2245   if ( mp->use_err_help ) { 
2246     @<Print the string |err_help|, possibly on several lines@>;
2247     mp->use_err_help=false;
2248   } else { 
2249     if ( mp->help_ptr==0 ) {
2250       help2("Sorry, I don't know how to help in this situation.")
2251            ("Maybe you should try asking a human?");
2252      }
2253     do { 
2254       decr(mp->help_ptr); mp_print(mp, mp->help_line[mp->help_ptr]); mp_print_ln(mp);
2255     } while (mp->help_ptr!=0);
2256   };
2257   help4("Sorry, I already gave what help I could...")
2258        ("Maybe you should try asking a human?")
2259        ("An error might have occurred before I noticed any problems.")
2260        ("``If all else fails, read the instructions.''");
2261   goto CONTINUE;
2262 }
2263
2264 @ @<Print the string |err_help|, possibly on several lines@>=
2265 j=mp->str_start[mp->err_help];
2266 while ( j<str_stop(mp->err_help) ) { 
2267   if ( mp->str_pool[j]!='%' ) mp_print_str(mp, mp->str_pool[j]);
2268   else if ( j+1==str_stop(mp->err_help) ) mp_print_ln(mp);
2269   else if ( mp->str_pool[j+1]!='%' ) mp_print_ln(mp);
2270   else  { incr(j); mp_print_char(mp, '%'); };
2271   incr(j);
2272 }
2273
2274 @ @<Put help message on the transcript file@>=
2275 if ( mp->interaction>mp_batch_mode ) decr(mp->selector); /* avoid terminal output */
2276 if ( mp->use_err_help ) { 
2277   mp_print_nl(mp, "");
2278   @<Print the string |err_help|, possibly on several lines@>;
2279 } else { 
2280   while ( mp->help_ptr>0 ){ 
2281     decr(mp->help_ptr); mp_print_nl(mp, mp->help_line[mp->help_ptr]);
2282   };
2283 }
2284 mp_print_ln(mp);
2285 if ( mp->interaction>mp_batch_mode ) incr(mp->selector); /* re-enable terminal output */
2286 mp_print_ln(mp)
2287
2288 @ In anomalous cases, the print selector might be in an unknown state;
2289 the following subroutine is called to fix things just enough to keep
2290 running a bit longer.
2291
2292 @c 
2293 void mp_normalize_selector (MP mp) { 
2294   if ( mp->log_opened ) mp->selector=term_and_log;
2295   else mp->selector=term_only;
2296   if ( mp->job_name==NULL ) mp_open_log_file(mp);
2297   if ( mp->interaction==mp_batch_mode ) decr(mp->selector);
2298 }
2299
2300 @ The following procedure prints \MP's last words before dying.
2301
2302 @d succumb { if ( mp->interaction==mp_error_stop_mode )
2303     mp->interaction=mp_scroll_mode; /* no more interaction */
2304   if ( mp->log_opened ) mp_error(mp);
2305   /* if ( mp->interaction>mp_batch_mode ) mp_debug_help(mp); */
2306   mp->history=fatal_error_stop; mp_jump_out(mp); /* irrecoverable error */
2307   }
2308
2309 @<Error hand...@>=
2310 void mp_fatal_error (MP mp, char *s) { /* prints |s|, and that's it */
2311   mp_normalize_selector(mp);
2312   print_err("Emergency stop"); help1(s); succumb;
2313 @.Emergency stop@>
2314 }
2315
2316 @ @<Exported...@>=
2317 void mp_fatal_error (MP mp, char *s);
2318
2319
2320 @ Here is the most dreaded error message.
2321
2322 @<Error hand...@>=
2323 void mp_overflow (MP mp, char *s, integer n) { /* stop due to finiteness */
2324   mp_normalize_selector(mp);
2325   print_err("MetaPost capacity exceeded, sorry [");
2326 @.MetaPost capacity exceeded ...@>
2327   mp_print(mp, s); mp_print_char(mp, '='); mp_print_int(mp, n); mp_print_char(mp, ']');
2328   help2("If you really absolutely need more capacity,")
2329        ("you can ask a wizard to enlarge me.");
2330   succumb;
2331 }
2332
2333 @ @<Declarations@>=
2334 void mp_overflow (MP mp, char *s, integer n);
2335
2336 @ The program might sometime run completely amok, at which point there is
2337 no choice but to stop. If no previous error has been detected, that's bad
2338 news; a message is printed that is really intended for the \MP\
2339 maintenance person instead of the user (unless the user has been
2340 particularly diabolical).  The index entries for `this can't happen' may
2341 help to pinpoint the problem.
2342 @^dry rot@>
2343
2344 @<Declarations@>=
2345 void mp_confusion (MP mp,char *s);
2346
2347 @ @<Error hand...@>=
2348 void mp_confusion (MP mp,char *s) {
2349   /* consistency check violated; |s| tells where */
2350   mp_normalize_selector(mp);
2351   if ( mp->history<error_message_issued ) { 
2352     print_err("This can't happen ("); mp_print(mp, s); mp_print_char(mp, ')');
2353 @.This can't happen@>
2354     help1("I'm broken. Please show this to someone who can fix can fix");
2355   } else { 
2356     print_err("I can\'t go on meeting you like this");
2357 @.I can't go on...@>
2358     help2("One of your faux pas seems to have wounded me deeply...")
2359          ("in fact, I'm barely conscious. Please fix it and try again.");
2360   }
2361   succumb;
2362 }
2363
2364 @ Users occasionally want to interrupt \MP\ while it's running.
2365 If the \PASCAL\ runtime system allows this, one can implement
2366 a routine that sets the global variable |interrupt| to some nonzero value
2367 when such an interrupt is signaled. Otherwise there is probably at least
2368 a way to make |interrupt| nonzero using the \PASCAL\ debugger.
2369 @^system dependencies@>
2370 @^debugging@>
2371
2372 @d check_interrupt { if ( mp->interrupt!=0 )
2373    mp_pause_for_instructions(mp); }
2374
2375 @<Global...@>=
2376 integer interrupt; /* should \MP\ pause for instructions? */
2377 boolean OK_to_interrupt; /* should interrupts be observed? */
2378
2379 @ @<Allocate or ...@>=
2380 mp->interrupt=0; mp->OK_to_interrupt=true;
2381
2382 @ When an interrupt has been detected, the program goes into its
2383 highest interaction level and lets the user have the full flexibility of
2384 the |error| routine.  \MP\ checks for interrupts only at times when it is
2385 safe to do this.
2386
2387 @c 
2388 void mp_pause_for_instructions (MP mp) { 
2389   if ( mp->OK_to_interrupt ) { 
2390     mp->interaction=mp_error_stop_mode;
2391     if ( (mp->selector==log_only)||(mp->selector==no_print) )
2392       incr(mp->selector);
2393     print_err("Interruption");
2394 @.Interruption@>
2395     help3("You rang?")
2396          ("Try to insert some instructions for me (e.g.,`I show x'),")
2397          ("unless you just want to quit by typing `X'.");
2398     mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
2399     mp->interrupt=0;
2400   }
2401 }
2402
2403 @ Many of \MP's error messages state that a missing token has been
2404 inserted behind the scenes. We can save string space and program space
2405 by putting this common code into a subroutine.
2406
2407 @c 
2408 void mp_missing_err (MP mp, char *s) { 
2409   print_err("Missing `"); mp_print(mp, s); mp_print(mp, "' has been inserted");
2410 @.Missing...inserted@>
2411 }
2412
2413 @* \[7] Arithmetic with scaled numbers.
2414 The principal computations performed by \MP\ are done entirely in terms of
2415 integers less than $2^{31}$ in magnitude; thus, the arithmetic specified in this
2416 program can be carried out in exactly the same way on a wide variety of
2417 computers, including some small ones.
2418 @^small computers@>
2419
2420 But \PASCAL\ does not define the |div|
2421 operation in the case of negative dividends; for example, the result of
2422 |(-2*n-1) div 2| is |-(n+1)| on some computers and |-n| on others.
2423 There are two principal types of arithmetic: ``translation-preserving,''
2424 in which the identity |(a+q*b)div b=(a div b)+q| is valid; and
2425 ``negation-preserving,'' in which |(-a)div b=-(a div b)|. This leads to
2426 two \MP s, which can produce different results, although the differences
2427 should be negligible when the language is being used properly.
2428 The \TeX\ processor has been defined carefully so that both varieties
2429 of arithmetic will produce identical output, but it would be too
2430 inefficient to constrain \MP\ in a similar way.
2431
2432 @d el_gordo   017777777777 /* $2^{31}-1$, the largest value that \MP\ likes */
2433
2434 @ One of \MP's most common operations is the calculation of
2435 $\lfloor{a+b\over2}\rfloor$,
2436 the midpoint of two given integers |a| and~|b|. The only decent way to do
2437 this in \PASCAL\ is to write `|(a+b) div 2|'; but on most machines it is
2438 far more efficient to calculate `|(a+b)| right shifted one bit'.
2439
2440 Therefore the midpoint operation will always be denoted by `|half(a+b)|'
2441 in this program. If \MP\ is being implemented with languages that permit
2442 binary shifting, the |half| macro should be changed to make this operation
2443 as efficient as possible.  Since some languages have shift operators that can
2444 only be trusted to work on positive numbers, there is also a macro |halfp|
2445 that is used only when the quantity being halved is known to be positive
2446 or zero.
2447
2448 @d half(A) ((A)) / 2
2449 @d halfp(A) ((A)) / 2
2450
2451 @ A single computation might use several subroutine calls, and it is
2452 desirable to avoid producing multiple error messages in case of arithmetic
2453 overflow. So the routines below set the global variable |arith_error| to |true|
2454 instead of reporting errors directly to the user.
2455
2456 @<Glob...@>=
2457 boolean arith_error; /* has arithmetic overflow occurred recently? */
2458
2459 @ @<Allocate or ...@>=
2460 mp->arith_error=false;
2461
2462 @ At crucial points the program will say |check_arith|, to test if
2463 an arithmetic error has been detected.
2464
2465 @d check_arith { if ( mp->arith_error ) mp_clear_arith(mp); }
2466
2467 @c 
2468 void mp_clear_arith (MP mp) { 
2469   print_err("Arithmetic overflow");
2470 @.Arithmetic overflow@>
2471   help4("Uh, oh. A little while ago one of the quantities that I was")
2472        ("computing got too large, so I'm afraid your answers will be")
2473        ("somewhat askew. You'll probably have to adopt different")
2474        ("tactics next time. But I shall try to carry on anyway.");
2475   mp_error(mp); 
2476   mp->arith_error=false;
2477 }
2478
2479 @ Addition is not always checked to make sure that it doesn't overflow,
2480 but in places where overflow isn't too unlikely the |slow_add| routine
2481 is used.
2482
2483 @c integer mp_slow_add (MP mp,integer x, integer y) { 
2484   if ( x>=0 )  {
2485     if ( y<=el_gordo-x ) { 
2486       return x+y;
2487     } else  { 
2488       mp->arith_error=true; 
2489           return el_gordo;
2490     }
2491   } else  if ( -y<=el_gordo+x ) {
2492     return x+y;
2493   } else { 
2494     mp->arith_error=true; 
2495         return -el_gordo;
2496   }
2497 }
2498
2499 @ Fixed-point arithmetic is done on {\sl scaled integers\/} that are multiples
2500 of $2^{-16}$. In other words, a binary point is assumed to be sixteen bit
2501 positions from the right end of a binary computer word.
2502
2503 @d quarter_unit   040000 /* $2^{14}$, represents 0.250000 */
2504 @d half_unit   0100000 /* $2^{15}$, represents 0.50000 */
2505 @d three_quarter_unit   0140000 /* $3\cdot2^{14}$, represents 0.75000 */
2506 @d unity   0200000 /* $2^{16}$, represents 1.00000 */
2507 @d two   0400000 /* $2^{17}$, represents 2.00000 */
2508 @d three   0600000 /* $2^{17}+2^{16}$, represents 3.00000 */
2509
2510 @<Types...@>=
2511 typedef integer scaled; /* this type is used for scaled integers */
2512 typedef unsigned char small_number; /* this type is self-explanatory */
2513
2514 @ The following function is used to create a scaled integer from a given decimal
2515 fraction $(.d_0d_1\ldots d_{k-1})$, where |0<=k<=17|. The digit $d_i$ is
2516 given in |dig[i]|, and the calculation produces a correctly rounded result.
2517
2518 @c 
2519 scaled mp_round_decimals (MP mp,small_number k) {
2520   /* converts a decimal fraction */
2521  integer a = 0; /* the accumulator */
2522  while ( k-->0 ) { 
2523     a=(a+mp->dig[k]*two) / 10;
2524   }
2525   return halfp(a+1);
2526 }
2527
2528 @ Conversely, here is a procedure analogous to |print_int|. If the output
2529 of this procedure is subsequently read by \MP\ and converted by the
2530 |round_decimals| routine above, it turns out that the original value will
2531 be reproduced exactly. A decimal point is printed only if the value is
2532 not an integer. If there is more than one way to print the result with
2533 the optimum number of digits following the decimal point, the closest
2534 possible value is given.
2535
2536 The invariant relation in the \&{repeat} loop is that a sequence of
2537 decimal digits yet to be printed will yield the original number if and only if
2538 they form a fraction~$f$ in the range $s-\delta\L10\cdot2^{16}f<s$.
2539 We can stop if and only if $f=0$ satisfies this condition; the loop will
2540 terminate before $s$ can possibly become zero.
2541
2542 @<Basic printing...@>=
2543 void mp_print_scaled (MP mp,scaled s) { /* prints scaled real, rounded to five  digits */
2544   scaled delta; /* amount of allowable inaccuracy */
2545   if ( s<0 ) { 
2546         mp_print_char(mp, '-'); 
2547     negate(s); /* print the sign, if negative */
2548   }
2549   mp_print_int(mp, s / unity); /* print the integer part */
2550   s=10*(s % unity)+5;
2551   if ( s!=5 ) { 
2552     delta=10; 
2553     mp_print_char(mp, '.');
2554     do {  
2555       if ( delta>unity )
2556         s=s+0100000-(delta / 2); /* round the final digit */
2557       mp_print_char(mp, '0'+(s / unity)); 
2558       s=10*(s % unity); 
2559       delta=delta*10;
2560     } while (s>delta);
2561   }
2562 }
2563
2564 @ We often want to print two scaled quantities in parentheses,
2565 separated by a comma.
2566
2567 @<Basic printing...@>=
2568 void mp_print_two (MP mp,scaled x, scaled y) { /* prints `|(x,y)|' */
2569   mp_print_char(mp, '('); 
2570   mp_print_scaled(mp, x); 
2571   mp_print_char(mp, ','); 
2572   mp_print_scaled(mp, y);
2573   mp_print_char(mp, ')');
2574 }
2575
2576 @ The |scaled| quantities in \MP\ programs are generally supposed to be
2577 less than $2^{12}$ in absolute value, so \MP\ does much of its internal
2578 arithmetic with 28~significant bits of precision. A |fraction| denotes
2579 a scaled integer whose binary point is assumed to be 28 bit positions
2580 from the right.
2581
2582 @d fraction_half 01000000000 /* $2^{27}$, represents 0.50000000 */
2583 @d fraction_one 02000000000 /* $2^{28}$, represents 1.00000000 */
2584 @d fraction_two 04000000000 /* $2^{29}$, represents 2.00000000 */
2585 @d fraction_three 06000000000 /* $3\cdot2^{28}$, represents 3.00000000 */
2586 @d fraction_four 010000000000 /* $2^{30}$, represents 4.00000000 */
2587
2588 @<Types...@>=
2589 typedef integer fraction; /* this type is used for scaled fractions */
2590
2591 @ In fact, the two sorts of scaling discussed above aren't quite
2592 sufficient; \MP\ has yet another, used internally to keep track of angles
2593 in units of $2^{-20}$ degrees.
2594
2595 @d forty_five_deg 0264000000 /* $45\cdot2^{20}$, represents $45^\circ$ */
2596 @d ninety_deg 0550000000 /* $90\cdot2^{20}$, represents $90^\circ$ */
2597 @d one_eighty_deg 01320000000 /* $180\cdot2^{20}$, represents $180^\circ$ */
2598 @d three_sixty_deg 02640000000 /* $360\cdot2^{20}$, represents $360^\circ$ */
2599
2600 @<Types...@>=
2601 typedef integer angle; /* this type is used for scaled angles */
2602
2603 @ The |make_fraction| routine produces the |fraction| equivalent of
2604 |p/q|, given integers |p| and~|q|; it computes the integer
2605 $f=\lfloor2^{28}p/q+{1\over2}\rfloor$, when $p$ and $q$ are
2606 positive. If |p| and |q| are both of the same scaled type |t|,
2607 the ``type relation'' |make_fraction(t,t)=fraction| is valid;
2608 and it's also possible to use the subroutine ``backwards,'' using
2609 the relation |make_fraction(t,fraction)=t| between scaled types.
2610
2611 If the result would have magnitude $2^{31}$ or more, |make_fraction|
2612 sets |arith_error:=true|. Most of \MP's internal computations have
2613 been designed to avoid this sort of error.
2614
2615 If this subroutine were programmed in assembly language on a typical
2616 machine, we could simply compute |(@t$2^{28}$@>*p)div q|, since a
2617 double-precision product can often be input to a fixed-point division
2618 instruction. But when we are restricted to \PASCAL\ arithmetic it
2619 is necessary either to resort to multiple-precision maneuvering
2620 or to use a simple but slow iteration. The multiple-precision technique
2621 would be about three times faster than the code adopted here, but it
2622 would be comparatively long and tricky, involving about sixteen
2623 additional multiplications and divisions.
2624
2625 This operation is part of \MP's ``inner loop''; indeed, it will
2626 consume nearly 10\pct! of the running time (exclusive of input and output)
2627 if the code below is left unchanged. A machine-dependent recoding
2628 will therefore make \MP\ run faster. The present implementation
2629 is highly portable, but slow; it avoids multiplication and division
2630 except in the initial stage. System wizards should be careful to
2631 replace it with a routine that is guaranteed to produce identical
2632 results in all cases.
2633 @^system dependencies@>
2634
2635 As noted below, a few more routines should also be replaced by machine-dependent
2636 code, for efficiency. But when a procedure is not part of the ``inner loop,''
2637 such changes aren't advisable; simplicity and robustness are
2638 preferable to trickery, unless the cost is too high.
2639 @^inner loop@>
2640
2641 @<Exported...@>=
2642 fraction mp_make_fraction (MP mp,integer p, integer q);
2643 integer mp_take_scaled (MP mp,integer q, scaled f) ;
2644
2645 @ If FIXPT is not defined, we need these preprocessor values
2646
2647 @d ELGORDO  0x7fffffff
2648 @d TWEXP31  2147483648.0
2649 @d TWEXP28  268435456.0
2650 @d TWEXP16 65536.0
2651 @d TWEXP_16 (1.0/65536.0)
2652 @d TWEXP_28 (1.0/268435456.0)
2653
2654
2655 @c 
2656 fraction mp_make_fraction (MP mp,integer p, integer q) {
2657 #ifdef FIXPT
2658   integer f; /* the fraction bits, with a leading 1 bit */
2659   integer n; /* the integer part of $\vert p/q\vert$ */
2660   integer be_careful; /* disables certain compiler optimizations */
2661   boolean negative = false; /* should the result be negated? */
2662   if ( p<0 ) {
2663     negate(p); negative=true;
2664   }
2665   if ( q<=0 ) { 
2666 #ifdef DEBUG
2667     if ( q==0 ) mp_confusion(mp, '/');
2668 #endif
2669 @:this can't happen /}{\quad \./@>
2670     negate(q); negative = ! negative;
2671   };
2672   n=p / q; p=p % q;
2673   if ( n>=8 ){ 
2674     mp->arith_error=true;
2675     return ( negative ? -el_gordo : el_gordo);
2676   } else { 
2677     n=(n-1)*fraction_one;
2678     @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>;
2679     return (negative ? (-(f+n)) : (f+n));
2680   }
2681 #else /* FIXPT */
2682     register double d;
2683         register integer i;
2684 #ifdef DEBUG
2685         if (q==0) mp_confusion(mp,'/'); 
2686 #endif /* DEBUG */
2687         d = TWEXP28 * (double)p /(double)q;
2688         if ((p^q) >= 0) {
2689                 d += 0.5;
2690                 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
2691                 i = (integer) d;
2692                 if (d==i && ( ((q>0 ? -q : q)&077777)
2693                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2694         } else {
2695                 d -= 0.5;
2696                 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
2697                 i = (integer) d;
2698                 if (d==i && ( ((q>0 ? q : -q)&077777)
2699                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
2700         }
2701         return i;
2702 #endif /* FIXPT */
2703 }
2704
2705 @ The |repeat| loop here preserves the following invariant relations
2706 between |f|, |p|, and~|q|:
2707 (i)~|0<=p<q|; (ii)~$fq+p=2^k(q+p_0)$, where $k$ is an integer and
2708 $p_0$ is the original value of~$p$.
2709
2710 Notice that the computation specifies
2711 |(p-q)+p| instead of |(p+p)-q|, because the latter could overflow.
2712 Let us hope that optimizing compilers do not miss this point; a
2713 special variable |be_careful| is used to emphasize the necessary
2714 order of computation. Optimizing compilers should keep |be_careful|
2715 in a register, not store it in memory.
2716 @^inner loop@>
2717
2718 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>=
2719 {
2720   f=1;
2721   do {  
2722     be_careful=p-q; p=be_careful+p;
2723     if ( p>=0 ) { 
2724       f=f+f+1;
2725     } else  { 
2726       f+=f; p=p+q;
2727     }
2728   } while (f<fraction_one);
2729   be_careful=p-q;
2730   if ( be_careful+p>=0 ) incr(f);
2731 }
2732
2733 @ The dual of |make_fraction| is |take_fraction|, which multiplies a
2734 given integer~|q| by a fraction~|f|. When the operands are positive, it
2735 computes $p=\lfloor qf/2^{28}+{1\over2}\rfloor$, a symmetric function
2736 of |q| and~|f|.
2737
2738 This routine is even more ``inner loopy'' than |make_fraction|;
2739 the present implementation consumes almost 20\pct! of \MP's computation
2740 time during typical jobs, so a machine-language substitute is advisable.
2741 @^inner loop@> @^system dependencies@>
2742
2743 @<Declarations@>=
2744 integer mp_take_fraction (MP mp,integer q, fraction f) ;
2745
2746 @ @c 
2747 #ifdef FIXPT
2748 integer mp_take_fraction (MP mp,integer q, fraction f) {
2749   integer p; /* the fraction so far */
2750   boolean negative; /* should the result be negated? */
2751   integer n; /* additional multiple of $q$ */
2752   integer be_careful; /* disables certain compiler optimizations */
2753   @<Reduce to the case that |f>=0| and |q>0|@>;
2754   if ( f<fraction_one ) { 
2755     n=0;
2756   } else { 
2757     n=f / fraction_one; f=f % fraction_one;
2758     if ( q<=el_gordo / n ) { 
2759       n=n*q ; 
2760     } else { 
2761       mp->arith_error=true; n=el_gordo;
2762     }
2763   }
2764   f=f+fraction_one;
2765   @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>;
2766   be_careful=n-el_gordo;
2767   if ( be_careful+p>0 ){ 
2768     mp->arith_error=true; n=el_gordo-p;
2769   }
2770   if ( negative ) 
2771         return (-(n+p));
2772   else 
2773     return (n+p);
2774 #else /* FIXPT */
2775 integer mp_take_fraction (MP mp,integer p, fraction q) {
2776     register double d;
2777         register integer i;
2778         d = (double)p * (double)q * TWEXP_28;
2779         if ((p^q) >= 0) {
2780                 d += 0.5;
2781                 if (d>=TWEXP31) {
2782                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2783                                 mp->arith_error = true;
2784                         return ELGORDO;
2785                 }
2786                 i = (integer) d;
2787                 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2788         } else {
2789                 d -= 0.5;
2790                 if (d<= -TWEXP31) {
2791                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2792                                 mp->arith_error = true;
2793                         return -ELGORDO;
2794                 }
2795                 i = (integer) d;
2796                 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2797         }
2798         return i;
2799 #endif /* FIXPT */
2800 }
2801
2802 @ @<Reduce to the case that |f>=0| and |q>0|@>=
2803 if ( f>=0 ) {
2804   negative=false;
2805 } else { 
2806   negate( f); negative=true;
2807 }
2808 if ( q<0 ) { 
2809   negate(q); negative=! negative;
2810 }
2811
2812 @ The invariant relations in this case are (i)~$\lfloor(qf+p)/2^k\rfloor
2813 =\lfloor qf_0/2^{28}+{1\over2}\rfloor$, where $k$ is an integer and
2814 $f_0$ is the original value of~$f$; (ii)~$2^k\L f<2^{k+1}$.
2815 @^inner loop@>
2816
2817 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>=
2818 p=fraction_half; /* that's $2^{27}$; the invariants hold now with $k=28$ */
2819 if ( q<fraction_four ) {
2820   do {  
2821     if ( odd(f) ) p=halfp(p+q); else p=halfp(p);
2822     f=halfp(f);
2823   } while (f!=1);
2824 } else  {
2825   do {  
2826     if ( odd(f) ) p=p+halfp(q-p); else p=halfp(p);
2827     f=halfp(f);
2828   } while (f!=1);
2829 }
2830
2831
2832 @ When we want to multiply something by a |scaled| quantity, we use a scheme
2833 analogous to |take_fraction| but with a different scaling.
2834 Given positive operands, |take_scaled|
2835 computes the quantity $p=\lfloor qf/2^{16}+{1\over2}\rfloor$.
2836
2837 Once again it is a good idea to use a machine-language replacement if
2838 possible; otherwise |take_scaled| will use more than 2\pct! of the running time
2839 when the Computer Modern fonts are being generated.
2840 @^inner loop@>
2841
2842 @c 
2843 #ifdef FIXPT
2844 integer mp_take_scaled (MP mp,integer q, scaled f) {
2845   integer p; /* the fraction so far */
2846   boolean negative; /* should the result be negated? */
2847   integer n; /* additional multiple of $q$ */
2848   integer be_careful; /* disables certain compiler optimizations */
2849   @<Reduce to the case that |f>=0| and |q>0|@>;
2850   if ( f<unity ) { 
2851     n=0;
2852   } else  { 
2853     n=f / unity; f=f % unity;
2854     if ( q<=el_gordo / n ) {
2855       n=n*q;
2856     } else  { 
2857       mp->arith_error=true; n=el_gordo;
2858     }
2859   }
2860   f=f+unity;
2861   @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>;
2862   be_careful=n-el_gordo;
2863   if ( be_careful+p>0 ) { 
2864     mp->arith_error=true; n=el_gordo-p;
2865   }
2866   return ( negative ?(-(n+p)) :(n+p));
2867 #else /* FIXPT */
2868 integer mp_take_scaled (MP mp,integer p, scaled q) {
2869     register double d;
2870         register integer i;
2871         d = (double)p * (double)q * TWEXP_16;
2872         if ((p^q) >= 0) {
2873                 d += 0.5;
2874                 if (d>=TWEXP31) {
2875                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2876                                 mp->arith_error = true;
2877                         return ELGORDO;
2878                 }
2879                 i = (integer) d;
2880                 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2881         } else {
2882                 d -= 0.5;
2883                 if (d<= -TWEXP31) {
2884                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2885                                 mp->arith_error = true;
2886                         return -ELGORDO;
2887                 }
2888                 i = (integer) d;
2889                 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2890         }
2891         return i;
2892 #endif /* FIXPT */
2893 }
2894
2895 @ @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>=
2896 p=half_unit; /* that's $2^{15}$; the invariants hold now with $k=16$ */
2897 @^inner loop@>
2898 if ( q<fraction_four ) {
2899   do {  
2900     p = (odd(f) ? halfp(p+q) : halfp(p));
2901     f=halfp(f);
2902   } while (f!=1);
2903 } else {
2904   do {  
2905     p = (odd(f) ? p+halfp(q-p) : halfp(p));
2906     f=halfp(f);
2907   } while (f!=1);
2908 }
2909
2910 @ For completeness, there's also |make_scaled|, which computes a
2911 quotient as a |scaled| number instead of as a |fraction|.
2912 In other words, the result is $\lfloor2^{16}p/q+{1\over2}\rfloor$, if the
2913 operands are positive. \ (This procedure is not used especially often,
2914 so it is not part of \MP's inner loop.)
2915
2916 @c 
2917 scaled mp_make_scaled (MP mp,integer p, integer q) {
2918 #ifdef FIXPT 
2919   integer f; /* the fraction bits, with a leading 1 bit */
2920   integer n; /* the integer part of $\vert p/q\vert$ */
2921   boolean negative; /* should the result be negated? */
2922   integer be_careful; /* disables certain compiler optimizations */
2923   if ( p>=0 ) negative=false;
2924   else  { negate(p); negative=true; };
2925   if ( q<=0 ) { 
2926 #ifdef DEBUG 
2927     if ( q==0 ) mp_confusion(mp, "/");
2928 @:this can't happen /}{\quad \./@>
2929 #endif
2930     negate(q); negative=! negative;
2931   }
2932   n=p / q; p=p % q;
2933   if ( n>=0100000 ) { 
2934     mp->arith_error=true;
2935     return (negative ? (-el_gordo) : el_gordo);
2936   } else  { 
2937     n=(n-1)*unity;
2938     @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>;
2939     return ( negative ? (-(f+n)) :(f+n));
2940   }
2941 #else /* FIXPT */
2942     register double d;
2943         register integer i;
2944 #ifdef DEBUG
2945         if (q==0) mp_confusion(mp,"/"); 
2946 #endif /* DEBUG */
2947         d = TWEXP16 * (double)p /(double)q;
2948         if ((p^q) >= 0) {
2949                 d += 0.5;
2950                 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
2951                 i = (integer) d;
2952                 if (d==i && ( ((q>0 ? -q : q)&077777)
2953                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2954         } else {
2955                 d -= 0.5;
2956                 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
2957                 i = (integer) d;
2958                 if (d==i && ( ((q>0 ? q : -q)&077777)
2959                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
2960         }
2961         return i;
2962 #endif /* FIXPT */
2963 }
2964
2965 @ @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>=
2966 f=1;
2967 do {  
2968   be_careful=p-q; p=be_careful+p;
2969   if ( p>=0 ) f=f+f+1;
2970   else  { f+=f; p=p+q; };
2971 } while (f<unity);
2972 be_careful=p-q;
2973 if ( be_careful+p>=0 ) incr(f)
2974
2975 @ Here is a typical example of how the routines above can be used.
2976 It computes the function
2977 $${1\over3\tau}f(\theta,\phi)=
2978 {\tau^{-1}\bigl(2+\sqrt2\,(\sin\theta-{1\over16}\sin\phi)
2979  (\sin\phi-{1\over16}\sin\theta)(\cos\theta-\cos\phi)\bigr)\over
2980 3\,\bigl(1+{1\over2}(\sqrt5-1)\cos\theta+{1\over2}(3-\sqrt5\,)\cos\phi\bigr)},$$
2981 where $\tau$ is a |scaled| ``tension'' parameter. This is \MP's magic
2982 fudge factor for placing the first control point of a curve that starts
2983 at an angle $\theta$ and ends at an angle $\phi$ from the straight path.
2984 (Actually, if the stated quantity exceeds 4, \MP\ reduces it to~4.)
2985
2986 The trigonometric quantity to be multiplied by $\sqrt2$ is less than $\sqrt2$.
2987 (It's a sum of eight terms whose absolute values can be bounded using
2988 relations such as $\sin\theta\cos\theta\L{1\over2}$.) Thus the numerator
2989 is positive; and since the tension $\tau$ is constrained to be at least
2990 $3\over4$, the numerator is less than $16\over3$. The denominator is
2991 nonnegative and at most~6.  Hence the fixed-point calculations below
2992 are guaranteed to stay within the bounds of a 32-bit computer word.
2993
2994 The angles $\theta$ and $\phi$ are given implicitly in terms of |fraction|
2995 arguments |st|, |ct|, |sf|, and |cf|, representing $\sin\theta$, $\cos\theta$,
2996 $\sin\phi$, and $\cos\phi$, respectively.
2997
2998 @c 
2999 fraction mp_velocity (MP mp,fraction st, fraction ct, fraction sf,
3000                       fraction cf, scaled t) {
3001   integer acc,num,denom; /* registers for intermediate calculations */
3002   acc=mp_take_fraction(mp, st-(sf / 16), sf-(st / 16));
3003   acc=mp_take_fraction(mp, acc,ct-cf);
3004   num=fraction_two+mp_take_fraction(mp, acc,379625062);
3005                    /* $2^{28}\sqrt2\approx379625062.497$ */
3006   denom=fraction_three+mp_take_fraction(mp, ct,497706707)+mp_take_fraction(mp, cf,307599661);
3007                       /* $3\cdot2^{27}\cdot(\sqrt5-1)\approx497706706.78$ and
3008                          $3\cdot2^{27}\cdot(3-\sqrt5\,)\approx307599661.22$ */
3009   if ( t!=unity ) num=mp_make_scaled(mp, num,t);
3010   /* |make_scaled(fraction,scaled)=fraction| */
3011   if ( num / 4>=denom ) 
3012     return fraction_four;
3013   else 
3014     return mp_make_fraction(mp, num, denom);
3015 }
3016
3017 @ The following somewhat different subroutine tests rigorously if $ab$ is
3018 greater than, equal to, or less than~$cd$,
3019 given integers $(a,b,c,d)$. In most cases a quick decision is reached.
3020 The result is $+1$, 0, or~$-1$ in the three respective cases.
3021
3022 @d mp_ab_vs_cd(M,A,B,C,D) mp_do_ab_vs_cd(A,B,C,D)
3023
3024 @c 
3025 integer mp_do_ab_vs_cd (integer a,integer b, integer c, integer d) {
3026   integer q,r; /* temporary registers */
3027   @<Reduce to the case that |a,c>=0|, |b,d>0|@>;
3028   while (1) { 
3029     q = a / d; r = c / b;
3030     if ( q!=r )
3031       return ( q>r ? 1 : -1);
3032     q = a % d; r = c % b;
3033     if ( r==0 )
3034       return (q ? 1 : 0);
3035     if ( q==0 ) return -1;
3036     a=b; b=q; c=d; d=r;
3037   } /* now |a>d>0| and |c>b>0| */
3038 }
3039
3040 @ @<Reduce to the case that |a...@>=
3041 if ( a<0 ) { negate(a); negate(b);  };
3042 if ( c<0 ) { negate(c); negate(d);  };
3043 if ( d<=0 ) { 
3044   if ( b>=0 ) {
3045     if ( (a==0||b==0)&&(c==0||d==0) ) return 0;
3046     else return 1;
3047   }
3048   if ( d==0 )
3049     return ( a==0 ? 0 : -1);
3050   q=a; a=c; c=q; q=-b; b=-d; d=q;
3051 } else if ( b<=0 ) { 
3052   if ( b<0 ) if ( a>0 ) return -1;
3053   return (c==0 ? 0 : -1);
3054 }
3055
3056 @ We conclude this set of elementary routines with some simple rounding
3057 and truncation operations that are coded in a machine-independent fashion.
3058 The routines are slightly complicated because we want them to work
3059 without overflow whenever $-2^{31}\L x<2^{31}$.
3060
3061 @<Declarations@>=
3062 #define mp_floor_scaled(M,i) ((i)&(-65536))
3063 #define mp_round_unscaled(M,i) (((i>>15)+1)>>1)
3064 #define mp_round_fraction(M,i) (((i>>11)+1)>>1)
3065
3066
3067 @* \[8] Algebraic and transcendental functions.
3068 \MP\ computes all of the necessary special functions from scratch, without
3069 relying on |real| arithmetic or system subroutines for sines, cosines, etc.
3070
3071 @ To get the square root of a |scaled| number |x|, we want to calculate
3072 $s=\lfloor 2^8\!\sqrt x +{1\over2}\rfloor$. If $x>0$, this is the unique
3073 integer such that $2^{16}x-s\L s^2<2^{16}x+s$. The following subroutine
3074 determines $s$ by an iterative method that maintains the invariant
3075 relations $x=2^{46-2k}x_0\bmod 2^{30}$, $0<y=\lfloor 2^{16-2k}x_0\rfloor
3076 -s^2+s\L q=2s$, where $x_0$ is the initial value of $x$. The value of~$y$
3077 might, however, be zero at the start of the first iteration.
3078
3079 @<Declarations@>=
3080 scaled mp_square_rt (MP mp,scaled x) ;
3081
3082 @ @c 
3083 scaled mp_square_rt (MP mp,scaled x) {
3084   small_number k; /* iteration control counter */
3085   integer y,q; /* registers for intermediate calculations */
3086   if ( x<=0 ) { 
3087     @<Handle square root of zero or negative argument@>;
3088   } else { 
3089     k=23; q=2;
3090     while ( x<fraction_two ) { /* i.e., |while x<@t$2^{29}$@>|\unskip */
3091       decr(k); x=x+x+x+x;
3092     }
3093     if ( x<fraction_four ) y=0;
3094     else  { x=x-fraction_four; y=1; };
3095     do {  
3096       @<Decrease |k| by 1, maintaining the invariant
3097       relations between |x|, |y|, and~|q|@>;
3098     } while (k!=0);
3099     return (halfp(q));
3100   }
3101 }
3102
3103 @ @<Handle square root of zero...@>=
3104
3105   if ( x<0 ) { 
3106     print_err("Square root of ");
3107 @.Square root...replaced by 0@>
3108     mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3109     help2("Since I don't take square roots of negative numbers,")
3110          ("I'm zeroing this one. Proceed, with fingers crossed.");
3111     mp_error(mp);
3112   };
3113   return 0;
3114 }
3115
3116 @ @<Decrease |k| by 1, maintaining...@>=
3117 x+=x; y+=y;
3118 if ( x>=fraction_four ) { /* note that |fraction_four=@t$2^{30}$@>| */
3119   x=x-fraction_four; incr(y);
3120 };
3121 x+=x; y=y+y-q; q+=q;
3122 if ( x>=fraction_four ) { x=x-fraction_four; incr(y); };
3123 if ( y>q ){ y=y-q; q=q+2; }
3124 else if ( y<=0 )  { q=q-2; y=y+q;  };
3125 decr(k)
3126
3127 @ Pythagorean addition $\psqrt{a^2+b^2}$ is implemented by an elegant
3128 iterative scheme due to Cleve Moler and Donald Morrison [{\sl IBM Journal
3129 @^Moler, Cleve Barry@>
3130 @^Morrison, Donald Ross@>
3131 of Research and Development\/ \bf27} (1983), 577--581]. It modifies |a| and~|b|
3132 in such a way that their Pythagorean sum remains invariant, while the
3133 smaller argument decreases.
3134
3135 @c 
3136 integer mp_pyth_add (MP mp,integer a, integer b) {
3137   fraction r; /* register used to transform |a| and |b| */
3138   boolean big; /* is the result dangerously near $2^{31}$? */
3139   a=abs(a); b=abs(b);
3140   if ( a<b ) { r=b; b=a; a=r; }; /* now |0<=b<=a| */
3141   if ( b>0 ) {
3142     if ( a<fraction_two ) {
3143       big=false;
3144     } else { 
3145       a=a / 4; b=b / 4; big=true;
3146     }; /* we reduced the precision to avoid arithmetic overflow */
3147     @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>;
3148     if ( big ) {
3149       if ( a<fraction_two ) {
3150         a=a+a+a+a;
3151       } else  { 
3152         mp->arith_error=true; a=el_gordo;
3153       };
3154     }
3155   }
3156   return a;
3157 }
3158
3159 @ The key idea here is to reflect the vector $(a,b)$ about the
3160 line through $(a,b/2)$.
3161
3162 @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>=
3163 while (1) {  
3164   r=mp_make_fraction(mp, b,a);
3165   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3166   if ( r==0 ) break;
3167   r=mp_make_fraction(mp, r,fraction_four+r);
3168   a=a+mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3169 }
3170
3171
3172 @ Here is a similar algorithm for $\psqrt{a^2-b^2}$.
3173 It converges slowly when $b$ is near $a$, but otherwise it works fine.
3174
3175 @c 
3176 integer mp_pyth_sub (MP mp,integer a, integer b) {
3177   fraction r; /* register used to transform |a| and |b| */
3178   boolean big; /* is the input dangerously near $2^{31}$? */
3179   a=abs(a); b=abs(b);
3180   if ( a<=b ) {
3181     @<Handle erroneous |pyth_sub| and set |a:=0|@>;
3182   } else { 
3183     if ( a<fraction_four ) {
3184       big=false;
3185     } else  { 
3186       a=halfp(a); b=halfp(b); big=true;
3187     }
3188     @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>;
3189     if ( big ) a=a+a;
3190   }
3191   return a;
3192 }
3193
3194 @ @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>=
3195 while (1) { 
3196   r=mp_make_fraction(mp, b,a);
3197   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3198   if ( r==0 ) break;
3199   r=mp_make_fraction(mp, r,fraction_four-r);
3200   a=a-mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3201 }
3202
3203 @ @<Handle erroneous |pyth_sub| and set |a:=0|@>=
3204
3205   if ( a<b ){ 
3206     print_err("Pythagorean subtraction "); mp_print_scaled(mp, a);
3207     mp_print(mp, "+-+"); mp_print_scaled(mp, b); 
3208     mp_print(mp, " has been replaced by 0");
3209 @.Pythagorean...@>
3210     help2("Since I don't take square roots of negative numbers,")
3211          ("I'm zeroing this one. Proceed, with fingers crossed.");
3212     mp_error(mp);
3213   }
3214   a=0;
3215 }
3216
3217 @ The subroutines for logarithm and exponential involve two tables.
3218 The first is simple: |two_to_the[k]| equals $2^k$. The second involves
3219 a bit more calculation, which the author claims to have done correctly:
3220 |spec_log[k]| is $2^{27}$ times $\ln\bigl(1/(1-2^{-k})\bigr)=
3221 2^{-k}+{1\over2}2^{-2k}+{1\over3}2^{-3k}+\cdots\,$, rounded to the
3222 nearest integer.
3223
3224 @d two_to_the(A) (1<<(A))
3225
3226 @<Constants ...@>=
3227 static const integer spec_log[29] = { 0, /* special logarithms */
3228 93032640, 38612034, 17922280, 8662214, 4261238, 2113709,
3229 1052693, 525315, 262400, 131136, 65552, 32772, 16385,
3230 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 1 };
3231
3232 @ @<Local variables for initialization@>=
3233 integer k; /* all-purpose loop index */
3234
3235
3236 @ Here is the routine that calculates $2^8$ times the natural logarithm
3237 of a |scaled| quantity; it is an integer approximation to $2^{24}\ln(x/2^{16})$,
3238 when |x| is a given positive integer.
3239
3240 The method is based on exercise 1.2.2--25 in {\sl The Art of Computer
3241 Programming\/}: During the main iteration we have $1\L 2^{-30}x<1/(1-2^{1-k})$,
3242 and the logarithm of $2^{30}x$ remains to be added to an accumulator
3243 register called~$y$. Three auxiliary bits of accuracy are retained in~$y$
3244 during the calculation, and sixteen auxiliary bits to extend |y| are
3245 kept in~|z| during the initial argument reduction. (We add
3246 $100\cdot2^{16}=6553600$ to~|z| and subtract 100 from~|y| so that |z| will
3247 not become negative; also, the actual amount subtracted from~|y| is~96,
3248 not~100, because we want to add~4 for rounding before the final division by~8.)
3249
3250 @c 
3251 scaled mp_m_log (MP mp,scaled x) {
3252   integer y,z; /* auxiliary registers */
3253   integer k; /* iteration counter */
3254   if ( x<=0 ) {
3255      @<Handle non-positive logarithm@>;
3256   } else  { 
3257     y=1302456956+4-100; /* $14\times2^{27}\ln2\approx1302456956.421063$ */
3258     z=27595+6553600; /* and $2^{16}\times .421063\approx 27595$ */
3259     while ( x<fraction_four ) {
3260        x+=x; y=y-93032639; z=z-48782;
3261     } /* $2^{27}\ln2\approx 93032639.74436163$ and $2^{16}\times.74436163\approx 48782$ */
3262     y=y+(z / unity); k=2;
3263     while ( x>fraction_four+4 ) {
3264       @<Increase |k| until |x| can be multiplied by a
3265         factor of $2^{-k}$, and adjust $y$ accordingly@>;
3266     }
3267     return (y / 8);
3268   }
3269 }
3270
3271 @ @<Increase |k| until |x| can...@>=
3272
3273   z=((x-1) / two_to_the(k))+1; /* $z=\lceil x/2^k\rceil$ */
3274   while ( x<fraction_four+z ) { z=halfp(z+1); k=k+1; };
3275   y=y+spec_log[k]; x=x-z;
3276 }
3277
3278 @ @<Handle non-positive logarithm@>=
3279
3280   print_err("Logarithm of ");
3281 @.Logarithm...replaced by 0@>
3282   mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3283   help2("Since I don't take logs of non-positive numbers,")
3284        ("I'm zeroing this one. Proceed, with fingers crossed.");
3285   mp_error(mp); 
3286   return 0;
3287 }
3288
3289 @ Conversely, the exponential routine calculates $\exp(x/2^8)$,
3290 when |x| is |scaled|. The result is an integer approximation to
3291 $2^{16}\exp(x/2^{24})$, when |x| is regarded as an integer.
3292
3293 @c 
3294 scaled mp_m_exp (MP mp,scaled x) {
3295   small_number k; /* loop control index */
3296   integer y,z; /* auxiliary registers */
3297   if ( x>174436200 ) {
3298     /* $2^{24}\ln((2^{31}-1)/2^{16})\approx 174436199.51$ */
3299     mp->arith_error=true; 
3300     return el_gordo;
3301   } else if ( x<-197694359 ) {
3302         /* $2^{24}\ln(2^{-1}/2^{16})\approx-197694359.45$ */
3303     return 0;
3304   } else { 
3305     if ( x<=0 ) { 
3306        z=-8*x; y=04000000; /* $y=2^{20}$ */
3307     } else { 
3308       if ( x<=127919879 ) { 
3309         z=1023359037-8*x;
3310         /* $2^{27}\ln((2^{31}-1)/2^{20})\approx 1023359037.125$ */
3311       } else {
3312        z=8*(174436200-x); /* |z| is always nonnegative */
3313       }
3314       y=el_gordo;
3315     };
3316     @<Multiply |y| by $\exp(-z/2^{27})$@>;
3317     if ( x<=127919879 ) 
3318        return ((y+8) / 16);
3319      else 
3320        return y;
3321   }
3322 }
3323
3324 @ The idea here is that subtracting |spec_log[k]| from |z| corresponds
3325 to multiplying |y| by $1-2^{-k}$.
3326
3327 A subtle point (which had to be checked) was that if $x=127919879$, the
3328 value of~|y| will decrease so that |y+8| doesn't overflow. In fact,
3329 $z$ will be 5 in this case, and |y| will decrease by~64 when |k=25|
3330 and by~16 when |k=27|.
3331
3332 @<Multiply |y| by...@>=
3333 k=1;
3334 while ( z>0 ) { 
3335   while ( z>=spec_log[k] ) { 
3336     z-=spec_log[k];
3337     y=y-1-((y-two_to_the(k-1)) / two_to_the(k));
3338   }
3339   incr(k);
3340 }
3341
3342 @ The trigonometric subroutines use an auxiliary table such that
3343 |spec_atan[k]| contains an approximation to the |angle| whose tangent
3344 is~$1/2^k$. $\arctan2^{-k}$ times $2^{20}\cdot180/\pi$ 
3345
3346 @<Constants ...@>=
3347 static const angle spec_atan[27] = { 0, 27855475, 14718068, 7471121, 3750058, 
3348 1876857, 938658, 469357, 234682, 117342, 58671, 29335, 14668, 7334, 3667, 
3349 1833, 917, 458, 229, 115, 57, 29, 14, 7, 4, 2, 1 };
3350
3351 @ Given integers |x| and |y|, not both zero, the |n_arg| function
3352 returns the |angle| whose tangent points in the direction $(x,y)$.
3353 This subroutine first determines the correct octant, then solves the
3354 problem for |0<=y<=x|, then converts the result appropriately to
3355 return an answer in the range |-one_eighty_deg<=@t$\theta$@><=one_eighty_deg|.
3356 (The answer is |+one_eighty_deg| if |y=0| and |x<0|, but an answer of
3357 |-one_eighty_deg| is possible if, for example, |y=-1| and $x=-2^{30}$.)
3358
3359 The octants are represented in a ``Gray code,'' since that turns out
3360 to be computationally simplest.
3361
3362 @d negate_x 1
3363 @d negate_y 2
3364 @d switch_x_and_y 4
3365 @d first_octant 1
3366 @d second_octant (first_octant+switch_x_and_y)
3367 @d third_octant (first_octant+switch_x_and_y+negate_x)
3368 @d fourth_octant (first_octant+negate_x)
3369 @d fifth_octant (first_octant+negate_x+negate_y)
3370 @d sixth_octant (first_octant+switch_x_and_y+negate_x+negate_y)
3371 @d seventh_octant (first_octant+switch_x_and_y+negate_y)
3372 @d eighth_octant (first_octant+negate_y)
3373
3374 @c 
3375 angle mp_n_arg (MP mp,integer x, integer y) {
3376   angle z; /* auxiliary register */
3377   integer t; /* temporary storage */
3378   small_number k; /* loop counter */
3379   int octant; /* octant code */
3380   if ( x>=0 ) {
3381     octant=first_octant;
3382   } else { 
3383     negate(x); octant=first_octant+negate_x;
3384   }
3385   if ( y<0 ) { 
3386     negate(y); octant=octant+negate_y;
3387   }
3388   if ( x<y ) { 
3389     t=y; y=x; x=t; octant=octant+switch_x_and_y;
3390   }
3391   if ( x==0 ) { 
3392     @<Handle undefined arg@>; 
3393   } else { 
3394     @<Set variable |z| to the arg of $(x,y)$@>;
3395     @<Return an appropriate answer based on |z| and |octant|@>;
3396   }
3397 }
3398
3399 @ @<Handle undefined arg@>=
3400
3401   print_err("angle(0,0) is taken as zero");
3402 @.angle(0,0)...zero@>
3403   help2("The `angle' between two identical points is undefined.")
3404        ("I'm zeroing this one. Proceed, with fingers crossed.");
3405   mp_error(mp); 
3406   return 0;
3407 }
3408
3409 @ @<Return an appropriate answer...@>=
3410 switch (octant) {
3411 case first_octant: return z;
3412 case second_octant: return (ninety_deg-z);
3413 case third_octant: return (ninety_deg+z);
3414 case fourth_octant: return (one_eighty_deg-z);
3415 case fifth_octant: return (z-one_eighty_deg);
3416 case sixth_octant: return (-z-ninety_deg);
3417 case seventh_octant: return (z-ninety_deg);
3418 case eighth_octant: return (-z);
3419 }; /* there are no other cases */
3420 return 0
3421
3422 @ At this point we have |x>=y>=0|, and |x>0|. The numbers are scaled up
3423 or down until $2^{28}\L x<2^{29}$, so that accurate fixed-point calculations
3424 will be made.
3425
3426 @<Set variable |z| to the arg...@>=
3427 while ( x>=fraction_two ) { 
3428   x=halfp(x); y=halfp(y);
3429 }
3430 z=0;
3431 if ( y>0 ) { 
3432  while ( x<fraction_one ) { 
3433     x+=x; y+=y; 
3434  };
3435  @<Increase |z| to the arg of $(x,y)$@>;
3436 }
3437
3438 @ During the calculations of this section, variables |x| and~|y|
3439 represent actual coordinates $(x,2^{-k}y)$. We will maintain the
3440 condition |x>=y|, so that the tangent will be at most $2^{-k}$.
3441 If $x<2y$, the tangent is greater than $2^{-k-1}$. The transformation
3442 $(a,b)\mapsto(a+b\tan\phi,b-a\tan\phi)$ replaces $(a,b)$ by
3443 coordinates whose angle has decreased by~$\phi$; in the special case
3444 $a=x$, $b=2^{-k}y$, and $\tan\phi=2^{-k-1}$, this operation reduces
3445 to the particularly simple iteration shown here. [Cf.~John E. Meggitt,
3446 @^Meggitt, John E.@>
3447 {\sl IBM Journal of Research and Development\/ \bf6} (1962), 210--226.]
3448
3449 The initial value of |x| will be multiplied by at most
3450 $(1+{1\over2})(1+{1\over8})(1+{1\over32})\cdots\approx 1.7584$; hence
3451 there is no chance of integer overflow.
3452
3453 @<Increase |z|...@>=
3454 k=0;
3455 do {  
3456   y+=y; incr(k);
3457   if ( y>x ){ 
3458     z=z+spec_atan[k]; t=x; x=x+(y / two_to_the(k+k)); y=y-t;
3459   };
3460 } while (k!=15);
3461 do {  
3462   y+=y; incr(k);
3463   if ( y>x ) { z=z+spec_atan[k]; y=y-x; };
3464 } while (k!=26)
3465
3466 @ Conversely, the |n_sin_cos| routine takes an |angle| and produces the sine
3467 and cosine of that angle. The results of this routine are
3468 stored in global integer variables |n_sin| and |n_cos|.
3469
3470 @<Glob...@>=
3471 fraction n_sin;fraction n_cos; /* results computed by |n_sin_cos| */
3472
3473 @ Given an integer |z| that is $2^{20}$ times an angle $\theta$ in degrees,
3474 the purpose of |n_sin_cos(z)| is to set
3475 |x=@t$r\cos\theta$@>| and |y=@t$r\sin\theta$@>| (approximately),
3476 for some rather large number~|r|. The maximum of |x| and |y|
3477 will be between $2^{28}$ and $2^{30}$, so that there will be hardly
3478 any loss of accuracy. Then |x| and~|y| are divided by~|r|.
3479
3480 @c 
3481 void mp_n_sin_cos (MP mp,angle z) { /* computes a multiple of the sine
3482                                        and cosine */ 
3483   small_number k; /* loop control variable */
3484   int q; /* specifies the quadrant */
3485   fraction r; /* magnitude of |(x,y)| */
3486   integer x,y,t; /* temporary registers */
3487   while ( z<0 ) z=z+three_sixty_deg;
3488   z=z % three_sixty_deg; /* now |0<=z<three_sixty_deg| */
3489   q=z / forty_five_deg; z=z % forty_five_deg;
3490   x=fraction_one; y=x;
3491   if ( ! odd(q) ) z=forty_five_deg-z;
3492   @<Subtract angle |z| from |(x,y)|@>;
3493   @<Convert |(x,y)| to the octant determined by~|q|@>;
3494   r=mp_pyth_add(mp, x,y); 
3495   mp->n_cos=mp_make_fraction(mp, x,r); 
3496   mp->n_sin=mp_make_fraction(mp, y,r);
3497 }
3498
3499 @ In this case the octants are numbered sequentially.
3500
3501 @<Convert |(x,...@>=
3502 switch (q) {
3503 case 0: break;
3504 case 1: t=x; x=y; y=t; break;
3505 case 2: t=x; x=-y; y=t; break;
3506 case 3: negate(x); break;
3507 case 4: negate(x); negate(y); break;
3508 case 5: t=x; x=-y; y=-t; break;
3509 case 6: t=x; x=y; y=-t; break;
3510 case 7: negate(y); break;
3511 } /* there are no other cases */
3512
3513 @ The main iteration of |n_sin_cos| is similar to that of |n_arg| but
3514 applied in reverse. The values of |spec_atan[k]| decrease slowly enough
3515 that this loop is guaranteed to terminate before the (nonexistent) value
3516 |spec_atan[27]| would be required.
3517
3518 @<Subtract angle |z|...@>=
3519 k=1;
3520 while ( z>0 ){ 
3521   if ( z>=spec_atan[k] ) { 
3522     z=z-spec_atan[k]; t=x;
3523     x=t+y / two_to_the(k);
3524     y=y-t / two_to_the(k);
3525   }
3526   incr(k);
3527 }
3528 if ( y<0 ) y=0 /* this precaution may never be needed */
3529
3530 @ And now let's complete our collection of numeric utility routines
3531 by considering random number generation.
3532 \MP\ generates pseudo-random numbers with the additive scheme recommended
3533 in Section 3.6 of {\sl The Art of Computer Programming}; however, the
3534 results are random fractions between 0 and |fraction_one-1|, inclusive.
3535
3536 There's an auxiliary array |randoms| that contains 55 pseudo-random
3537 fractions. Using the recurrence $x_n=(x_{n-55}-x_{n-31})\bmod 2^{28}$,
3538 we generate batches of 55 new $x_n$'s at a time by calling |new_randoms|.
3539 The global variable |j_random| tells which element has most recently
3540 been consumed.
3541 The global variable |sys_random_seed| was introduced in version 0.9,
3542 for the sole reason of stressing the fact that the initial value of the
3543 random seed is system-dependant. The pascal code below will initialize
3544 this variable to |(internal[time] div unity)+internal[day]|, but this is
3545 not good enough on modern fast machines that are capable of running
3546 multiple MetaPost processes within the same second.
3547 @^system dependencies@>
3548
3549 @<Glob...@>=
3550 fraction randoms[55]; /* the last 55 random values generated */
3551 int j_random; /* the number of unused |randoms| */
3552 scaled sys_random_seed; /* the default random seed */
3553
3554 @ @<Types...@>=
3555 typedef scaled (*get_random_seed_command)(MP mp);
3556
3557 @ @<Glob...@>=
3558 get_random_seed_command get_random_seed;
3559
3560 @ @<Option variables@>=
3561 get_random_seed_command get_random_seed;
3562
3563 @ @<Allocate or initialize ...@>=
3564 set_callback_option(get_random_seed);
3565
3566 @ @<Exported function headers@>=
3567 scaled mp_get_random_seed (MP mp);
3568
3569 @ @c 
3570 scaled mp_get_random_seed (MP mp) {
3571   return (mp->internal[mp_time] / unity)+mp->internal[day];
3572 }
3573
3574 @ To consume a random fraction, the program below will say `|next_random|'
3575 and then it will fetch |randoms[j_random]|.
3576
3577 @d next_random { if ( mp->j_random==0 ) mp_new_randoms(mp);
3578   else decr(mp->j_random); }
3579
3580 @c 
3581 void mp_new_randoms (MP mp) {
3582   int k; /* index into |randoms| */
3583   fraction x; /* accumulator */
3584   for (k=0;k<=23;k++) { 
3585    x=mp->randoms[k]-mp->randoms[k+31];
3586     if ( x<0 ) x=x+fraction_one;
3587     mp->randoms[k]=x;
3588   }
3589   for (k=24;k<= 54;k++){ 
3590     x=mp->randoms[k]-mp->randoms[k-24];
3591     if ( x<0 ) x=x+fraction_one;
3592     mp->randoms[k]=x;
3593   }
3594   mp->j_random=54;
3595 }
3596
3597 @ @<Declarations@>=
3598 void mp_init_randoms (MP mp,scaled seed);
3599
3600 @ To initialize the |randoms| table, we call the following routine.
3601
3602 @c 
3603 void mp_init_randoms (MP mp,scaled seed) {
3604   fraction j,jj,k; /* more or less random integers */
3605   int i; /* index into |randoms| */
3606   j=abs(seed);
3607   while ( j>=fraction_one ) j=halfp(j);
3608   k=1;
3609   for (i=0;i<=54;i++ ){ 
3610     jj=k; k=j-k; j=jj;
3611     if ( k<0 ) k=k+fraction_one;
3612     mp->randoms[(i*21)% 55]=j;
3613   }
3614   mp_new_randoms(mp); 
3615   mp_new_randoms(mp); 
3616   mp_new_randoms(mp); /* ``warm up'' the array */
3617 }
3618
3619 @ To produce a uniform random number in the range |0<=u<x| or |0>=u>x|
3620 or |0=u=x|, given a |scaled| value~|x|, we proceed as shown here.
3621
3622 Note that the call of |take_fraction| will produce the values 0 and~|x|
3623 with about half the probability that it will produce any other particular
3624 values between 0 and~|x|, because it rounds its answers.
3625
3626 @c 
3627 scaled mp_unif_rand (MP mp,scaled x) {
3628   scaled y; /* trial value */
3629   next_random; y=mp_take_fraction(mp, abs(x),mp->randoms[mp->j_random]);
3630   if ( y==abs(x) ) return 0;
3631   else if ( x>0 ) return y;
3632   else return (-y);
3633 }
3634
3635 @ Finally, a normal deviate with mean zero and unit standard deviation
3636 can readily be obtained with the ratio method (Algorithm 3.4.1R in
3637 {\sl The Art of Computer Programming\/}).
3638
3639 @c 
3640 scaled mp_norm_rand (MP mp) {
3641   integer x,u,l; /* what the book would call $2^{16}X$, $2^{28}U$, and $-2^{24}\ln U$ */
3642   do { 
3643     do {  
3644       next_random;
3645       x=mp_take_fraction(mp, 112429,mp->randoms[mp->j_random]-fraction_half);
3646       /* $2^{16}\sqrt{8/e}\approx 112428.82793$ */
3647       next_random; u=mp->randoms[mp->j_random];
3648     } while (abs(x)>=u);
3649     x=mp_make_fraction(mp, x,u);
3650     l=139548960-mp_m_log(mp, u); /* $2^{24}\cdot12\ln2\approx139548959.6165$ */
3651   } while (mp_ab_vs_cd(mp, 1024,l,x,x)<0);
3652   return x;
3653 }
3654
3655 @* \[9] Packed data.
3656 In order to make efficient use of storage space, \MP\ bases its major data
3657 structures on a |memory_word|, which contains either a (signed) integer,
3658 possibly scaled, or a small number of fields that are one half or one
3659 quarter of the size used for storing integers.
3660
3661 If |x| is a variable of type |memory_word|, it contains up to four
3662 fields that can be referred to as follows:
3663 $$\vbox{\halign{\hfil#&#\hfil&#\hfil\cr
3664 |x|&.|int|&(an |integer|)\cr
3665 |x|&.|sc|\qquad&(a |scaled| integer)\cr
3666 |x.hh.lh|, |x.hh|&.|rh|&(two halfword fields)\cr
3667 |x.hh.b0|, |x.hh.b1|, |x.hh|&.|rh|&(two quarterword fields, one halfword
3668   field)\cr
3669 |x.qqqq.b0|, |x.qqqq.b1|, |x.qqqq|&.|b2|, |x.qqqq.b3|\hskip-100pt
3670   &\qquad\qquad\qquad(four quarterword fields)\cr}}$$
3671 This is somewhat cumbersome to write, and not very readable either, but
3672 macros will be used to make the notation shorter and more transparent.
3673 The code below gives a formal definition of |memory_word| and
3674 its subsidiary types, using packed variant records. \MP\ makes no
3675 assumptions about the relative positions of the fields within a word.
3676
3677 @d max_quarterword 0x3FFF /* largest allowable value in a |quarterword| */
3678 @d max_halfword 0xFFFFFFF /* largest allowable value in a |halfword| */
3679
3680 @ Here are the inequalities that the quarterword and halfword values
3681 must satisfy (or rather, the inequalities that they mustn't satisfy):
3682
3683 @<Check the ``constant''...@>=
3684 if (mp->ini_version) {
3685   if ( mp->mem_max!=mp->mem_top ) mp->bad=8;
3686 } else {
3687   if ( mp->mem_max<mp->mem_top ) mp->bad=8;
3688 }
3689 if ( max_quarterword<255 ) mp->bad=9;
3690 if ( max_halfword<65535 ) mp->bad=10;
3691 if ( max_quarterword>max_halfword ) mp->bad=11;
3692 if ( mp->mem_max>=max_halfword ) mp->bad=12;
3693 if ( mp->max_strings>max_halfword ) mp->bad=13;
3694
3695 @ The macros |qi| and |qo| are used for input to and output 
3696 from quarterwords. These are legacy macros.
3697 @^system dependencies@>
3698
3699 @d qo(A) (A) /* to read eight bits from a quarterword */
3700 @d qi(A) (A) /* to store eight bits in a quarterword */
3701
3702 @ The reader should study the following definitions closely:
3703 @^system dependencies@>
3704
3705 @d sc cint /* |scaled| data is equivalent to |integer| */
3706
3707 @<Types...@>=
3708 typedef short quarterword; /* 1/4 of a word */
3709 typedef int halfword; /* 1/2 of a word */
3710 typedef union {
3711   struct {
3712     halfword RH, LH;
3713   } v;
3714   struct { /* Make B0,B1 overlap the most significant bytes of LH.  */
3715     halfword junk;
3716     quarterword B0, B1;
3717   } u;
3718 } two_halves;
3719 typedef struct {
3720   struct {
3721     quarterword B2, B3, B0, B1;
3722   } u;
3723 } four_quarters;
3724 typedef union {
3725   two_halves hh;
3726   integer cint;
3727   four_quarters qqqq;
3728 } memory_word;
3729 #define b0 u.B0
3730 #define b1 u.B1
3731 #define b2 u.B2
3732 #define b3 u.B3
3733 #define rh v.RH
3734 #define lh v.LH
3735
3736 @ When debugging, we may want to print a |memory_word| without knowing
3737 what type it is; so we print it in all modes.
3738 @^dirty \PASCAL@>@^debugging@>
3739
3740 @c 
3741 void mp_print_word (MP mp,memory_word w) {
3742   /* prints |w| in all ways */
3743   mp_print_int(mp, w.cint); mp_print_char(mp, ' ');
3744   mp_print_scaled(mp, w.sc); mp_print_char(mp, ' '); 
3745   mp_print_scaled(mp, w.sc / 010000); mp_print_ln(mp);
3746   mp_print_int(mp, w.hh.lh); mp_print_char(mp, '='); 
3747   mp_print_int(mp, w.hh.b0); mp_print_char(mp, ':');
3748   mp_print_int(mp, w.hh.b1); mp_print_char(mp, ';'); 
3749   mp_print_int(mp, w.hh.rh); mp_print_char(mp, ' ');
3750   mp_print_int(mp, w.qqqq.b0); mp_print_char(mp, ':'); 
3751   mp_print_int(mp, w.qqqq.b1); mp_print_char(mp, ':');
3752   mp_print_int(mp, w.qqqq.b2); mp_print_char(mp, ':'); 
3753   mp_print_int(mp, w.qqqq.b3);
3754 }
3755
3756
3757 @* \[10] Dynamic memory allocation.
3758
3759 The \MP\ system does nearly all of its own memory allocation, so that it
3760 can readily be transported into environments that do not have automatic
3761 facilities for strings, garbage collection, etc., and so that it can be in
3762 control of what error messages the user receives. The dynamic storage
3763 requirements of \MP\ are handled by providing a large array |mem| in
3764 which consecutive blocks of words are used as nodes by the \MP\ routines.
3765
3766 Pointer variables are indices into this array, or into another array
3767 called |eqtb| that will be explained later. A pointer variable might
3768 also be a special flag that lies outside the bounds of |mem|, so we
3769 allow pointers to assume any |halfword| value. The minimum memory
3770 index represents a null pointer.
3771
3772 @d null 0 /* the null pointer */
3773
3774 @<Types...@>=
3775 typedef halfword pointer; /* a flag or a location in |mem| or |eqtb| */
3776
3777 @ The |mem| array is divided into two regions that are allocated separately,
3778 but the dividing line between these two regions is not fixed; they grow
3779 together until finding their ``natural'' size in a particular job.
3780 Locations less than or equal to |lo_mem_max| are used for storing
3781 variable-length records consisting of two or more words each. This region
3782 is maintained using an algorithm similar to the one described in exercise
3783 2.5--19 of {\sl The Art of Computer Programming}. However, no size field
3784 appears in the allocated nodes; the program is responsible for knowing the
3785 relevant size when a node is freed. Locations greater than or equal to
3786 |hi_mem_min| are used for storing one-word records; a conventional
3787 \.{AVAIL} stack is used for allocation in this region.
3788
3789 Locations of |mem| between |0| and |mem_top| may be dumped as part
3790 of preloaded format files, by the \.{INIMP} preprocessor.
3791 @.INIMP@>
3792 Production versions of \MP\ may extend the memory at the top end in order to
3793 provide more space; these locations, between |mem_top| and |mem_max|,
3794 are always used for single-word nodes.
3795
3796 The key pointers that govern |mem| allocation have a prescribed order:
3797 $$\hbox{|null=0<lo_mem_max<hi_mem_min<mem_top<=mem_end<=mem_max|.}$$
3798
3799 @<Glob...@>=
3800 memory_word *mem; /* the big dynamic storage area */
3801 pointer lo_mem_max; /* the largest location of variable-size memory in use */
3802 pointer hi_mem_min; /* the smallest location of one-word memory in use */
3803
3804
3805
3806 @d xfree    mp_xfree
3807 @d xrealloc mp_xrealloc
3808 @d xmalloc  mp_xmalloc
3809 @d xstrdup  mp_xstrdup
3810 @d XREALLOC(a,b,c) a = xrealloc(a,(b+1),sizeof(c));
3811
3812 @<Declare helpers@>=
3813 void mp_xfree (void *x);
3814 void *mp_xrealloc (void *p, size_t nmem, size_t size) ;
3815 void *mp_xmalloc (size_t nmem, size_t size) ;
3816 char *mp_xstrdup(const char *s);
3817
3818 @ The |max_size_test| guards against overflow, on the assumption that
3819 |size_t| is at least 31bits wide.
3820
3821 @d max_size_test 0x7FFFFFFF
3822
3823 @c
3824 void mp_xfree (void *x) {
3825   if (x!=NULL) free(x);
3826 }
3827 void  *mp_xrealloc (void *p, size_t nmem, size_t size) {
3828   void *w ; 
3829   if ((max_size_test/size)<nmem) {
3830     fprintf(stderr,"Memory size overflow!\n");
3831     exit(1);
3832   }
3833   w = realloc (p,(nmem*size));
3834   if (w==NULL) {
3835     fprintf(stderr,"Out of memory!\n");
3836     exit(1);
3837   }
3838   return w;
3839 }
3840 void  *mp_xmalloc (size_t nmem, size_t size) {
3841   void *w;
3842   if ((max_size_test/size)<nmem) {
3843     fprintf(stderr,"Memory size overflow!\n");
3844     exit(1);
3845   }
3846   w = malloc (nmem*size);
3847   if (w==NULL) {
3848     fprintf(stderr,"Out of memory!\n");
3849     exit(1);
3850   }
3851   return w;
3852 }
3853 char *mp_xstrdup(const char *s) {
3854   char *w; 
3855   if (s==NULL)
3856     return NULL;
3857   w = strdup(s);
3858   if (w==NULL) {
3859     fprintf(stderr,"Out of memory!\n");
3860     exit(1);
3861   }
3862   return w;
3863 }
3864
3865
3866
3867 @<Allocate or initialize ...@>=
3868 mp->mem = xmalloc ((mp->mem_max+1),sizeof (memory_word));
3869
3870 @ @<Dealloc variables@>=
3871 xfree(mp->mem);
3872
3873 @ Users who wish to study the memory requirements of particular applications can
3874 can use optional special features that keep track of current and
3875 maximum memory usage. When code between the delimiters |stat| $\ldots$
3876 |tats| is not ``commented out,'' \MP\ will run a bit slower but it will
3877 report these statistics when |tracing_stats| is positive.
3878
3879 @<Glob...@>=
3880 integer var_used; integer dyn_used; /* how much memory is in use */
3881
3882 @ Let's consider the one-word memory region first, since it's the
3883 simplest. The pointer variable |mem_end| holds the highest-numbered location
3884 of |mem| that has ever been used. The free locations of |mem| that
3885 occur between |hi_mem_min| and |mem_end|, inclusive, are of type
3886 |two_halves|, and we write |info(p)| and |link(p)| for the |lh|
3887 and |rh| fields of |mem[p]| when it is of this type. The single-word
3888 free locations form a linked list
3889 $$|avail|,\;\hbox{|link(avail)|},\;\hbox{|link(link(avail))|},\;\ldots$$
3890 terminated by |null|.
3891
3892 @d link(A)   mp->mem[(A)].hh.rh /* the |link| field of a memory word */
3893 @d info(A)   mp->mem[(A)].hh.lh /* the |info| field of a memory word */
3894
3895 @<Glob...@>=
3896 pointer avail; /* head of the list of available one-word nodes */
3897 pointer mem_end; /* the last one-word node used in |mem| */
3898
3899 @ If one-word memory is exhausted, it might mean that the user has forgotten
3900 a token like `\&{enddef}' or `\&{endfor}'. We will define some procedures
3901 later that try to help pinpoint the trouble.
3902
3903 @c 
3904 @<Declare the procedure called |show_token_list|@>;
3905 @<Declare the procedure called |runaway|@>
3906
3907 @ The function |get_avail| returns a pointer to a new one-word node whose
3908 |link| field is null. However, \MP\ will halt if there is no more room left.
3909 @^inner loop@>
3910
3911 @c 
3912 pointer mp_get_avail (MP mp) { /* single-word node allocation */
3913   pointer p; /* the new node being got */
3914   p=mp->avail; /* get top location in the |avail| stack */
3915   if ( p!=null ) {
3916     mp->avail=link(mp->avail); /* and pop it off */
3917   } else if ( mp->mem_end<mp->mem_max ) { /* or go into virgin territory */
3918     incr(mp->mem_end); p=mp->mem_end;
3919   } else { 
3920     decr(mp->hi_mem_min); p=mp->hi_mem_min;
3921     if ( mp->hi_mem_min<=mp->lo_mem_max ) { 
3922       mp_runaway(mp); /* if memory is exhausted, display possible runaway text */
3923       mp_overflow(mp, "main memory size",mp->mem_max);
3924       /* quit; all one-word nodes are busy */
3925 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
3926     }
3927   }
3928   link(p)=null; /* provide an oft-desired initialization of the new node */
3929   incr(mp->dyn_used);/* maintain statistics */
3930   return p;
3931 };
3932
3933 @ Conversely, a one-word node is recycled by calling |free_avail|.
3934
3935 @d free_avail(A)  /* single-word node liberation */
3936   { link((A))=mp->avail; mp->avail=(A); decr(mp->dyn_used);  }
3937
3938 @ There's also a |fast_get_avail| routine, which saves the procedure-call
3939 overhead at the expense of extra programming. This macro is used in
3940 the places that would otherwise account for the most calls of |get_avail|.
3941 @^inner loop@>
3942
3943 @d fast_get_avail(A) { 
3944   (A)=mp->avail; /* avoid |get_avail| if possible, to save time */
3945   if ( (A)==null ) { (A)=mp_get_avail(mp); } 
3946   else { mp->avail=link((A)); link((A))=null;  incr(mp->dyn_used); }
3947   }
3948
3949 @ The available-space list that keeps track of the variable-size portion
3950 of |mem| is a nonempty, doubly-linked circular list of empty nodes,
3951 pointed to by the roving pointer |rover|.
3952
3953 Each empty node has size 2 or more; the first word contains the special
3954 value |max_halfword| in its |link| field and the size in its |info| field;
3955 the second word contains the two pointers for double linking.
3956
3957 Each nonempty node also has size 2 or more. Its first word is of type
3958 |two_halves|\kern-1pt, and its |link| field is never equal to |max_halfword|.
3959 Otherwise there is complete flexibility with respect to the contents
3960 of its other fields and its other words.
3961
3962 (We require |mem_max<max_halfword| because terrible things can happen
3963 when |max_halfword| appears in the |link| field of a nonempty node.)
3964
3965 @d empty_flag   max_halfword /* the |link| of an empty variable-size node */
3966 @d is_empty(A)   (link((A))==empty_flag) /* tests for empty node */
3967 @d node_size   info /* the size field in empty variable-size nodes */
3968 @d llink(A)   info((A)+1) /* left link in doubly-linked list of empty nodes */
3969 @d rlink(A)   link((A)+1) /* right link in doubly-linked list of empty nodes */
3970
3971 @<Glob...@>=
3972 pointer rover; /* points to some node in the list of empties */
3973
3974 @ A call to |get_node| with argument |s| returns a pointer to a new node
3975 of size~|s|, which must be 2~or more. The |link| field of the first word
3976 of this new node is set to null. An overflow stop occurs if no suitable
3977 space exists.
3978
3979 If |get_node| is called with $s=2^{30}$, it simply merges adjacent free
3980 areas and returns the value |max_halfword|.
3981
3982 @<Declarations@>=
3983 pointer mp_get_node (MP mp,integer s) ;
3984
3985 @ @c 
3986 pointer mp_get_node (MP mp,integer s) { /* variable-size node allocation */
3987   pointer p; /* the node currently under inspection */
3988   pointer q;  /* the node physically after node |p| */
3989   integer r; /* the newly allocated node, or a candidate for this honor */
3990   integer t,tt; /* temporary registers */
3991 @^inner loop@>
3992  RESTART: 
3993   p=mp->rover; /* start at some free node in the ring */
3994   do {  
3995     @<Try to allocate within node |p| and its physical successors,
3996      and |goto found| if allocation was possible@>;
3997     p=rlink(p); /* move to the next node in the ring */
3998   } while (p!=mp->rover); /* repeat until the whole list has been traversed */
3999   if ( s==010000000000 ) { 
4000     return max_halfword;
4001   };
4002   if ( mp->lo_mem_max+2<mp->hi_mem_min ) {
4003     if ( mp->lo_mem_max+2<=max_halfword ) {
4004       @<Grow more variable-size memory and |goto restart|@>;
4005     }
4006   }
4007   mp_overflow(mp, "main memory size",mp->mem_max);
4008   /* sorry, nothing satisfactory is left */
4009 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
4010 FOUND: 
4011   link(r)=null; /* this node is now nonempty */
4012   mp->var_used=mp->var_used+s; /* maintain usage statistics */
4013   return r;
4014 }
4015
4016 @ The lower part of |mem| grows by 1000 words at a time, unless
4017 we are very close to going under. When it grows, we simply link
4018 a new node into the available-space list. This method of controlled
4019 growth helps to keep the |mem| usage consecutive when \MP\ is
4020 implemented on ``virtual memory'' systems.
4021 @^virtual memory@>
4022
4023 @<Grow more variable-size memory and |goto restart|@>=
4024
4025   if ( mp->hi_mem_min-mp->lo_mem_max>=1998 ) {
4026     t=mp->lo_mem_max+1000;
4027   } else {
4028     t=mp->lo_mem_max+1+(mp->hi_mem_min-mp->lo_mem_max) / 2; 
4029     /* |lo_mem_max+2<=t<hi_mem_min| */
4030   }
4031   if ( t>max_halfword ) t=max_halfword;
4032   p=llink(mp->rover); q=mp->lo_mem_max; rlink(p)=q; llink(mp->rover)=q;
4033   rlink(q)=mp->rover; llink(q)=p; link(q)=empty_flag; node_size(q)=t-mp->lo_mem_max;
4034   mp->lo_mem_max=t; link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4035   mp->rover=q; 
4036   goto RESTART;
4037 }
4038
4039 @ @<Try to allocate...@>=
4040 q=p+node_size(p); /* find the physical successor */
4041 while ( is_empty(q) ) { /* merge node |p| with node |q| */
4042   t=rlink(q); tt=llink(q);
4043 @^inner loop@>
4044   if ( q==mp->rover ) mp->rover=t;
4045   llink(t)=tt; rlink(tt)=t;
4046   q=q+node_size(q);
4047 }
4048 r=q-s;
4049 if ( r>p+1 ) {
4050   @<Allocate from the top of node |p| and |goto found|@>;
4051 }
4052 if ( r==p ) { 
4053   if ( rlink(p)!=p ) {
4054     @<Allocate entire node |p| and |goto found|@>;
4055   }
4056 }
4057 node_size(p)=q-p /* reset the size in case it grew */
4058
4059 @ @<Allocate from the top...@>=
4060
4061   node_size(p)=r-p; /* store the remaining size */
4062   mp->rover=p; /* start searching here next time */
4063   goto FOUND;
4064 }
4065
4066 @ Here we delete node |p| from the ring, and let |rover| rove around.
4067
4068 @<Allocate entire...@>=
4069
4070   mp->rover=rlink(p); t=llink(p);
4071   llink(mp->rover)=t; rlink(t)=mp->rover;
4072   goto FOUND;
4073 }
4074
4075 @ Conversely, when some variable-size node |p| of size |s| is no longer needed,
4076 the operation |free_node(p,s)| will make its words available, by inserting
4077 |p| as a new empty node just before where |rover| now points.
4078
4079 @<Declarations@>=
4080 void mp_free_node (MP mp, pointer p, halfword s) ;
4081
4082 @ @c 
4083 void mp_free_node (MP mp, pointer p, halfword s) { /* variable-size node
4084   liberation */
4085   pointer q; /* |llink(rover)| */
4086   node_size(p)=s; link(p)=empty_flag;
4087 @^inner loop@>
4088   q=llink(mp->rover); llink(p)=q; rlink(p)=mp->rover; /* set both links */
4089   llink(mp->rover)=p; rlink(q)=p; /* insert |p| into the ring */
4090   mp->var_used=mp->var_used-s; /* maintain statistics */
4091 }
4092
4093 @ Just before \.{INIMP} writes out the memory, it sorts the doubly linked
4094 available space list. The list is probably very short at such times, so a
4095 simple insertion sort is used. The smallest available location will be
4096 pointed to by |rover|, the next-smallest by |rlink(rover)|, etc.
4097
4098 @c 
4099 void mp_sort_avail (MP mp) { /* sorts the available variable-size nodes
4100   by location */
4101   pointer p,q,r; /* indices into |mem| */
4102   pointer old_rover; /* initial |rover| setting */
4103   p=mp_get_node(mp, 010000000000); /* merge adjacent free areas */
4104   p=rlink(mp->rover); rlink(mp->rover)=max_halfword; old_rover=mp->rover;
4105   while ( p!=old_rover ) {
4106     @<Sort |p| into the list starting at |rover|
4107      and advance |p| to |rlink(p)|@>;
4108   }
4109   p=mp->rover;
4110   while ( rlink(p)!=max_halfword ) { 
4111     llink(rlink(p))=p; p=rlink(p);
4112   };
4113   rlink(p)=mp->rover; llink(mp->rover)=p;
4114 }
4115
4116 @ The following |while| loop is guaranteed to
4117 terminate, since the list that starts at
4118 |rover| ends with |max_halfword| during the sorting procedure.
4119
4120 @<Sort |p|...@>=
4121 if ( p<mp->rover ) { 
4122   q=p; p=rlink(q); rlink(q)=mp->rover; mp->rover=q;
4123 } else  { 
4124   q=mp->rover;
4125   while ( rlink(q)<p ) q=rlink(q);
4126   r=rlink(p); rlink(p)=rlink(q); rlink(q)=p; p=r;
4127 }
4128
4129 @* \[11] Memory layout.
4130 Some areas of |mem| are dedicated to fixed usage, since static allocation is
4131 more efficient than dynamic allocation when we can get away with it. For
4132 example, locations |0| to |1| are always used to store a
4133 two-word dummy token whose second word is zero.
4134 The following macro definitions accomplish the static allocation by giving
4135 symbolic names to the fixed positions. Static variable-size nodes appear
4136 in locations |0| through |lo_mem_stat_max|, and static single-word nodes
4137 appear in locations |hi_mem_stat_min| through |mem_top|, inclusive.
4138
4139 @d null_dash (2) /* the first two words are reserved for a null value */
4140 @d dep_head (null_dash+3) /* we will define |dash_node_size=3| */
4141 @d zero_val (dep_head+2) /* two words for a permanently zero value */
4142 @d temp_val (zero_val+2) /* two words for a temporary value node */
4143 @d end_attr temp_val /* we use |end_attr+2| only */
4144 @d inf_val (end_attr+2) /* and |inf_val+1| only */
4145 @d test_pen (inf_val+2)
4146   /* nine words for a pen used when testing the turning number */
4147 @d bad_vardef (test_pen+9) /* two words for \&{vardef} error recovery */
4148 @d lo_mem_stat_max (bad_vardef+1)  /* largest statically
4149   allocated word in the variable-size |mem| */
4150 @#
4151 @d sentinel mp->mem_top /* end of sorted lists */
4152 @d temp_head (mp->mem_top-1) /* head of a temporary list of some kind */
4153 @d hold_head (mp->mem_top-2) /* head of a temporary list of another kind */
4154 @d spec_head (mp->mem_top-3) /* head of a list of unprocessed \&{special} items */
4155 @d hi_mem_stat_min (mp->mem_top-3) /* smallest statically allocated word in
4156   the one-word |mem| */
4157
4158 @ The following code gets the dynamic part of |mem| off to a good start,
4159 when \MP\ is initializing itself the slow way.
4160
4161 @<Initialize table entries (done by \.{INIMP} only)@>=
4162 @^data structure assumptions@>
4163 mp->rover=lo_mem_stat_max+1; /* initialize the dynamic memory */
4164 link(mp->rover)=empty_flag;
4165 node_size(mp->rover)=1000; /* which is a 1000-word available node */
4166 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
4167 mp->lo_mem_max=mp->rover+1000; link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4168 for (k=hi_mem_stat_min;k<=(int)mp->mem_top;k++) {
4169   mp->mem[k]=mp->mem[mp->lo_mem_max]; /* clear list heads */
4170 }
4171 mp->avail=null; mp->mem_end=mp->mem_top;
4172 mp->hi_mem_min=hi_mem_stat_min; /* initialize the one-word memory */
4173 mp->var_used=lo_mem_stat_max+1; 
4174 mp->dyn_used=mp->mem_top+1-(hi_mem_stat_min);  /* initialize statistics */
4175 @<Initialize a pen at |test_pen| so that it fits in nine words@>;
4176
4177 @ The procedure |flush_list(p)| frees an entire linked list of one-word
4178 nodes that starts at a given position, until coming to |sentinel| or a
4179 pointer that is not in the one-word region. Another procedure,
4180 |flush_node_list|, frees an entire linked list of one-word and two-word
4181 nodes, until coming to a |null| pointer.
4182 @^inner loop@>
4183
4184 @c 
4185 void mp_flush_list (MP mp,pointer p) { /* makes list of single-word nodes  available */
4186   pointer q,r; /* list traversers */
4187   if ( p>=mp->hi_mem_min ) if ( p!=sentinel ) { 
4188     r=p;
4189     do {  
4190       q=r; r=link(r); 
4191       decr(mp->dyn_used);
4192       if ( r<mp->hi_mem_min ) break;
4193     } while (r!=sentinel);
4194   /* now |q| is the last node on the list */
4195     link(q)=mp->avail; mp->avail=p;
4196   }
4197 }
4198 @#
4199 void mp_flush_node_list (MP mp,pointer p) {
4200   pointer q; /* the node being recycled */
4201   while ( p!=null ){ 
4202     q=p; p=link(p);
4203     if ( q<mp->hi_mem_min ) 
4204       mp_free_node(mp, q,2);
4205     else 
4206       free_avail(q);
4207   }
4208 }
4209
4210 @ If \MP\ is extended improperly, the |mem| array might get screwed up.
4211 For example, some pointers might be wrong, or some ``dead'' nodes might not
4212 have been freed when the last reference to them disappeared. Procedures
4213 |check_mem| and |search_mem| are available to help diagnose such
4214 problems. These procedures make use of two arrays called |free| and
4215 |was_free| that are present only if \MP's debugging routines have
4216 been included. (You may want to decrease the size of |mem| while you
4217 @^debugging@>
4218 are debugging.)
4219
4220 Because |boolean|s are typedef-d as ints, it is better to use
4221 unsigned chars here.
4222
4223 @<Glob...@>=
4224 unsigned char *free; /* free cells */
4225 unsigned char *was_free; /* previously free cells */
4226 pointer was_mem_end; pointer was_lo_max; pointer was_hi_min;
4227   /* previous |mem_end|, |lo_mem_max|,and |hi_mem_min| */
4228 boolean panicking; /* do we want to check memory constantly? */
4229
4230 @ @<Allocate or initialize ...@>=
4231 mp->free = xmalloc ((mp->mem_max+1),sizeof (unsigned char));
4232 mp->was_free = xmalloc ((mp->mem_max+1), sizeof (unsigned char));
4233
4234 @ @<Dealloc variables@>=
4235 xfree(mp->free);
4236 xfree(mp->was_free);
4237
4238 @ @<Allocate or ...@>=
4239 mp->was_mem_end=0; /* indicate that everything was previously free */
4240 mp->was_lo_max=0; mp->was_hi_min=mp->mem_max;
4241 mp->panicking=false;
4242
4243 @ @<Declare |mp_reallocate| functions@>=
4244 void mp_reallocate_memory(MP mp, int l) ;
4245
4246 @ @c
4247 void mp_reallocate_memory(MP mp, int l) {
4248    XREALLOC(mp->free,     l, unsigned char);
4249    XREALLOC(mp->was_free, l, unsigned char);
4250    XREALLOC(mp->mem,      l, memory_word);
4251    mp->mem_max = l;
4252    if (mp->ini_version) 
4253      mp->mem_top = l;
4254 }
4255
4256
4257
4258 @ Procedure |check_mem| makes sure that the available space lists of
4259 |mem| are well formed, and it optionally prints out all locations
4260 that are reserved now but were free the last time this procedure was called.
4261
4262 @c 
4263 void mp_check_mem (MP mp,boolean print_locs ) {
4264   pointer p,q,r; /* current locations of interest in |mem| */
4265   boolean clobbered; /* is something amiss? */
4266   for (p=0;p<=mp->lo_mem_max;p++) {
4267     mp->free[p]=false; /* you can probably do this faster */
4268   }
4269   for (p=mp->hi_mem_min;p<= mp->mem_end;p++) {
4270     mp->free[p]=false; /* ditto */
4271   }
4272   @<Check single-word |avail| list@>;
4273   @<Check variable-size |avail| list@>;
4274   @<Check flags of unavailable nodes@>;
4275   @<Check the list of linear dependencies@>;
4276   if ( print_locs ) {
4277     @<Print newly busy locations@>;
4278   }
4279   for (p=0;p<=mp->lo_mem_max;p++) {
4280     mp->was_free[p]=mp->free[p];
4281   }
4282   for (p=mp->hi_mem_min;p<=mp->mem_end;p++) {
4283     mp->was_free[p]=mp->free[p];
4284   }
4285   /* |was_free:=free| might be faster */
4286   mp->was_mem_end=mp->mem_end; 
4287   mp->was_lo_max=mp->lo_mem_max; 
4288   mp->was_hi_min=mp->hi_mem_min;
4289 }
4290
4291 @ @<Check single-word...@>=
4292 p=mp->avail; q=null; clobbered=false;
4293 while ( p!=null ) { 
4294   if ( (p>mp->mem_end)||(p<mp->hi_mem_min) ) clobbered=true;
4295   else if ( mp->free[p] ) clobbered=true;
4296   if ( clobbered ) { 
4297     mp_print_nl(mp, "AVAIL list clobbered at ");
4298 @.AVAIL list clobbered...@>
4299     mp_print_int(mp, q); break;
4300   }
4301   mp->free[p]=true; q=p; p=link(q);
4302 }
4303
4304 @ @<Check variable-size...@>=
4305 p=mp->rover; q=null; clobbered=false;
4306 do {  
4307   if ( (p>=mp->lo_mem_max)||(p<0) ) clobbered=true;
4308   else if ( (rlink(p)>=mp->lo_mem_max)||(rlink(p)<0) ) clobbered=true;
4309   else if (  !(is_empty(p))||(node_size(p)<2)||
4310    (p+node_size(p)>mp->lo_mem_max)|| (llink(rlink(p))!=p) ) clobbered=true;
4311   if ( clobbered ) { 
4312     mp_print_nl(mp, "Double-AVAIL list clobbered at ");
4313 @.Double-AVAIL list clobbered...@>
4314     mp_print_int(mp, q); break;
4315   }
4316   for (q=p;q<=p+node_size(p)-1;q++) { /* mark all locations free */
4317     if ( mp->free[q] ) { 
4318       mp_print_nl(mp, "Doubly free location at ");
4319 @.Doubly free location...@>
4320       mp_print_int(mp, q); break;
4321     }
4322     mp->free[q]=true;
4323   }
4324   q=p; p=rlink(p);
4325 } while (p!=mp->rover)
4326
4327
4328 @ @<Check flags...@>=
4329 p=0;
4330 while ( p<=mp->lo_mem_max ) { /* node |p| should not be empty */
4331   if ( is_empty(p) ) {
4332     mp_print_nl(mp, "Bad flag at "); mp_print_int(mp, p);
4333 @.Bad flag...@>
4334   }
4335   while ( (p<=mp->lo_mem_max) && ! mp->free[p] ) incr(p);
4336   while ( (p<=mp->lo_mem_max) && mp->free[p] ) incr(p);
4337 }
4338
4339 @ @<Print newly busy...@>=
4340
4341   @<Do intialization required before printing new busy locations@>;
4342   mp_print_nl(mp, "New busy locs:");
4343 @.New busy locs@>
4344   for (p=0;p<= mp->lo_mem_max;p++ ) {
4345     if ( ! mp->free[p] && ((p>mp->was_lo_max) || mp->was_free[p]) ) {
4346       @<Indicate that |p| is a new busy location@>;
4347     }
4348   }
4349   for (p=mp->hi_mem_min;p<=mp->mem_end;p++ ) {
4350     if ( ! mp->free[p] &&
4351         ((p<mp->was_hi_min) || (p>mp->was_mem_end) || mp->was_free[p]) ) {
4352       @<Indicate that |p| is a new busy location@>;
4353     }
4354   }
4355   @<Finish printing new busy locations@>;
4356 }
4357
4358 @ There might be many new busy locations so we are careful to print contiguous
4359 blocks compactly.  During this operation |q| is the last new busy location and
4360 |r| is the start of the block containing |q|.
4361
4362 @<Indicate that |p| is a new busy location@>=
4363
4364   if ( p>q+1 ) { 
4365     if ( q>r ) { 
4366       mp_print(mp, ".."); mp_print_int(mp, q);
4367     }
4368     mp_print_char(mp, ' '); mp_print_int(mp, p);
4369     r=p;
4370   }
4371   q=p;
4372 }
4373
4374 @ @<Do intialization required before printing new busy locations@>=
4375 q=mp->mem_max; r=mp->mem_max
4376
4377 @ @<Finish printing new busy locations@>=
4378 if ( q>r ) { 
4379   mp_print(mp, ".."); mp_print_int(mp, q);
4380 }
4381
4382 @ The |search_mem| procedure attempts to answer the question ``Who points
4383 to node~|p|?'' In doing so, it fetches |link| and |info| fields of |mem|
4384 that might not be of type |two_halves|. Strictly speaking, this is
4385 @^dirty \PASCAL@>
4386 undefined in \PASCAL, and it can lead to ``false drops'' (words that seem to
4387 point to |p| purely by coincidence). But for debugging purposes, we want
4388 to rule out the places that do {\sl not\/} point to |p|, so a few false
4389 drops are tolerable.
4390
4391 @c
4392 void mp_search_mem (MP mp, pointer p) { /* look for pointers to |p| */
4393   integer q; /* current position being searched */
4394   for (q=0;q<=mp->lo_mem_max;q++) { 
4395     if ( link(q)==p ){ 
4396       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4397     }
4398     if ( info(q)==p ) { 
4399       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4400     }
4401   }
4402   for (q=mp->hi_mem_min;q<=mp->mem_end;q++) {
4403     if ( link(q)==p ) {
4404       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4405     }
4406     if ( info(q)==p ) {
4407       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4408     }
4409   }
4410   @<Search |eqtb| for equivalents equal to |p|@>;
4411 }
4412
4413 @* \[12] The command codes.
4414 Before we can go much further, we need to define symbolic names for the internal
4415 code numbers that represent the various commands obeyed by \MP. These codes
4416 are somewhat arbitrary, but not completely so. For example,
4417 some codes have been made adjacent so that |case| statements in the
4418 program need not consider cases that are widely spaced, or so that |case|
4419 statements can be replaced by |if| statements. A command can begin an
4420 expression if and only if its code lies between |min_primary_command| and
4421 |max_primary_command|, inclusive. The first token of a statement that doesn't
4422 begin with an expression has a command code between |min_command| and
4423 |max_statement_command|, inclusive. Anything less than |min_command| is
4424 eliminated during macro expansions, and anything no more than |max_pre_command|
4425 is eliminated when expanding \TeX\ material.  Ranges such as
4426 |min_secondary_command..max_secondary_command| are used when parsing
4427 expressions, but the relative ordering within such a range is generally not
4428 critical.
4429
4430 The ordering of the highest-numbered commands
4431 (|comma<semicolon<end_group<stop|) is crucial for the parsing and
4432 error-recovery methods of this program as is the ordering |if_test<fi_or_else|
4433 for the smallest two commands.  The ordering is also important in the ranges
4434 |numeric_token..plus_or_minus| and |left_brace..ampersand|.
4435
4436 At any rate, here is the list, for future reference.
4437
4438 @d start_tex 1 /* begin \TeX\ material (\&{btex}, \&{verbatimtex}) */
4439 @d etex_marker 2 /* end \TeX\ material (\&{etex}) */
4440 @d mpx_break 3 /* stop reading an \.{MPX} file (\&{mpxbreak}) */
4441 @d max_pre_command mpx_break
4442 @d if_test 4 /* conditional text (\&{if}) */
4443 @d fi_or_else 5 /* delimiters for conditionals (\&{elseif}, \&{else}, \&{fi} */
4444 @d input 6 /* input a source file (\&{input}, \&{endinput}) */
4445 @d iteration 7 /* iterate (\&{for}, \&{forsuffixes}, \&{forever}, \&{endfor}) */
4446 @d repeat_loop 8 /* special command substituted for \&{endfor} */
4447 @d exit_test 9 /* premature exit from a loop (\&{exitif}) */
4448 @d relax 10 /* do nothing (\.{\char`\\}) */
4449 @d scan_tokens 11 /* put a string into the input buffer */
4450 @d expand_after 12 /* look ahead one token */
4451 @d defined_macro 13 /* a macro defined by the user */
4452 @d min_command (defined_macro+1)
4453 @d save_command 14 /* save a list of tokens (\&{save}) */
4454 @d interim_command 15 /* save an internal quantity (\&{interim}) */
4455 @d let_command 16 /* redefine a symbolic token (\&{let}) */
4456 @d new_internal 17 /* define a new internal quantity (\&{newinternal}) */
4457 @d macro_def 18 /* define a macro (\&{def}, \&{vardef}, etc.) */
4458 @d ship_out_command 19 /* output a character (\&{shipout}) */
4459 @d add_to_command 20 /* add to edges (\&{addto}) */
4460 @d bounds_command 21  /* add bounding path to edges (\&{setbounds}, \&{clip}) */
4461 @d tfm_command 22 /* command for font metric info (\&{ligtable}, etc.) */
4462 @d protection_command 23 /* set protection flag (\&{outer}, \&{inner}) */
4463 @d show_command 24 /* diagnostic output (\&{show}, \&{showvariable}, etc.) */
4464 @d mode_command 25 /* set interaction level (\&{batchmode}, etc.) */
4465 @d random_seed 26 /* initialize random number generator (\&{randomseed}) */
4466 @d message_command 27 /* communicate to user (\&{message}, \&{errmessage}) */
4467 @d every_job_command 28 /* designate a starting token (\&{everyjob}) */
4468 @d delimiters 29 /* define a pair of delimiters (\&{delimiters}) */
4469 @d special_command 30 /* output special info (\&{special})
4470                        or font map info (\&{fontmapfile}, \&{fontmapline}) */
4471 @d write_command 31 /* write text to a file (\&{write}) */
4472 @d type_name 32 /* declare a type (\&{numeric}, \&{pair}, etc. */
4473 @d max_statement_command type_name
4474 @d min_primary_command type_name
4475 @d left_delimiter 33 /* the left delimiter of a matching pair */
4476 @d begin_group 34 /* beginning of a group (\&{begingroup}) */
4477 @d nullary 35 /* an operator without arguments (e.g., \&{normaldeviate}) */
4478 @d unary 36 /* an operator with one argument (e.g., \&{sqrt}) */
4479 @d str_op 37 /* convert a suffix to a string (\&{str}) */
4480 @d cycle 38 /* close a cyclic path (\&{cycle}) */
4481 @d primary_binary 39 /* binary operation taking `\&{of}' (e.g., \&{point}) */
4482 @d capsule_token 40 /* a value that has been put into a token list */
4483 @d string_token 41 /* a string constant (e.g., |"hello"|) */
4484 @d internal_quantity 42 /* internal numeric parameter (e.g., \&{pausing}) */
4485 @d min_suffix_token internal_quantity
4486 @d tag_token 43 /* a symbolic token without a primitive meaning */
4487 @d numeric_token 44 /* a numeric constant (e.g., \.{3.14159}) */
4488 @d max_suffix_token numeric_token
4489 @d plus_or_minus 45 /* either `\.+' or `\.-' */
4490 @d max_primary_command plus_or_minus /* should also be |numeric_token+1| */
4491 @d min_tertiary_command plus_or_minus
4492 @d tertiary_secondary_macro 46 /* a macro defined by \&{secondarydef} */
4493 @d tertiary_binary 47 /* an operator at the tertiary level (e.g., `\.{++}') */
4494 @d max_tertiary_command tertiary_binary
4495 @d left_brace 48 /* the operator `\.{\char`\{}' */
4496 @d min_expression_command left_brace
4497 @d path_join 49 /* the operator `\.{..}' */
4498 @d ampersand 50 /* the operator `\.\&' */
4499 @d expression_tertiary_macro 51 /* a macro defined by \&{tertiarydef} */
4500 @d expression_binary 52 /* an operator at the expression level (e.g., `\.<') */
4501 @d equals 53 /* the operator `\.=' */
4502 @d max_expression_command equals
4503 @d and_command 54 /* the operator `\&{and}' */
4504 @d min_secondary_command and_command
4505 @d secondary_primary_macro 55 /* a macro defined by \&{primarydef} */
4506 @d slash 56 /* the operator `\./' */
4507 @d secondary_binary 57 /* an operator at the binary level (e.g., \&{shifted}) */
4508 @d max_secondary_command secondary_binary
4509 @d param_type 58 /* type of parameter (\&{primary}, \&{expr}, \&{suffix}, etc.) */
4510 @d controls 59 /* specify control points explicitly (\&{controls}) */
4511 @d tension 60 /* specify tension between knots (\&{tension}) */
4512 @d at_least 61 /* bounded tension value (\&{atleast}) */
4513 @d curl_command 62 /* specify curl at an end knot (\&{curl}) */
4514 @d macro_special 63 /* special macro operators (\&{quote}, \.{\#\AT!}, etc.) */
4515 @d right_delimiter 64 /* the right delimiter of a matching pair */
4516 @d left_bracket 65 /* the operator `\.[' */
4517 @d right_bracket 66 /* the operator `\.]' */
4518 @d right_brace 67 /* the operator `\.{\char`\}}' */
4519 @d with_option 68 /* option for filling (\&{withpen}, \&{withweight}, etc.) */
4520 @d thing_to_add 69
4521   /* variant of \&{addto} (\&{contour}, \&{doublepath}, \&{also}) */
4522 @d of_token 70 /* the operator `\&{of}' */
4523 @d to_token 71 /* the operator `\&{to}' */
4524 @d step_token 72 /* the operator `\&{step}' */
4525 @d until_token 73 /* the operator `\&{until}' */
4526 @d within_token 74 /* the operator `\&{within}' */
4527 @d lig_kern_token 75
4528   /* the operators `\&{kern}' and `\.{=:}' and `\.{=:\char'174}, etc. */
4529 @d assignment 76 /* the operator `\.{:=}' */
4530 @d skip_to 77 /* the operation `\&{skipto}' */
4531 @d bchar_label 78 /* the operator `\.{\char'174\char'174:}' */
4532 @d double_colon 79 /* the operator `\.{::}' */
4533 @d colon 80 /* the operator `\.:' */
4534 @#
4535 @d comma 81 /* the operator `\.,', must be |colon+1| */
4536 @d end_of_statement (mp->cur_cmd>comma)
4537 @d semicolon 82 /* the operator `\.;', must be |comma+1| */
4538 @d end_group 83 /* end a group (\&{endgroup}), must be |semicolon+1| */
4539 @d stop 84 /* end a job (\&{end}, \&{dump}), must be |end_group+1| */
4540 @d max_command_code stop
4541 @d outer_tag (max_command_code+1) /* protection code added to command code */
4542
4543 @<Types...@>=
4544 typedef int command_code;
4545
4546 @ Variables and capsules in \MP\ have a variety of ``types,''
4547 distinguished by the code numbers defined here. These numbers are also
4548 not completely arbitrary.  Things that get expanded must have types
4549 |>mp_independent|; a type remaining after expansion is numeric if and only if
4550 its code number is at least |numeric_type|; objects containing numeric
4551 parts must have types between |transform_type| and |pair_type|;
4552 all other types must be smaller than |transform_type|; and among the types
4553 that are not unknown or vacuous, the smallest two must be |boolean_type|
4554 and |string_type| in that order.
4555  
4556 @d undefined 0 /* no type has been declared */
4557 @d unknown_tag 1 /* this constant is added to certain type codes below */
4558 @d unknown_types mp_unknown_boolean: case mp_unknown_string:
4559   case mp_unknown_pen: case mp_unknown_picture: case mp_unknown_path
4560
4561 @<Types...@>=
4562 enum {
4563 mp_vacuous=1, /* no expression was present */
4564 mp_boolean_type, /* \&{boolean} with a known value */
4565 mp_unknown_boolean,
4566 mp_string_type, /* \&{string} with a known value */
4567 mp_unknown_string,
4568 mp_pen_type, /* \&{pen} with a known value */
4569 mp_unknown_pen,
4570 mp_path_type, /* \&{path} with a known value */
4571 mp_unknown_path,
4572 mp_picture_type, /* \&{picture} with a known value */
4573 mp_unknown_picture,
4574 mp_transform_type, /* \&{transform} variable or capsule */
4575 mp_color_type, /* \&{color} variable or capsule */
4576 mp_cmykcolor_type, /* \&{cmykcolor} variable or capsule */
4577 mp_pair_type, /* \&{pair} variable or capsule */
4578 mp_numeric_type, /* variable that has been declared \&{numeric} but not used */
4579 mp_known, /* \&{numeric} with a known value */
4580 mp_dependent, /* a linear combination with |fraction| coefficients */
4581 mp_proto_dependent, /* a linear combination with |scaled| coefficients */
4582 mp_independent, /* \&{numeric} with unknown value */
4583 mp_token_list, /* variable name or suffix argument or text argument */
4584 mp_structured, /* variable with subscripts and attributes */
4585 mp_unsuffixed_macro, /* variable defined with \&{vardef} but no \.{\AT!\#} */
4586 mp_suffixed_macro /* variable defined with \&{vardef} and \.{\AT!\#} */
4587 };
4588
4589 @ @<Declarations@>=
4590 void mp_print_type (MP mp,small_number t) ;
4591
4592 @ @<Basic printing procedures@>=
4593 void mp_print_type (MP mp,small_number t) { 
4594   switch (t) {
4595   case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
4596   case mp_boolean_type:mp_print(mp, "boolean"); break;
4597   case mp_unknown_boolean:mp_print(mp, "unknown boolean"); break;
4598   case mp_string_type:mp_print(mp, "string"); break;
4599   case mp_unknown_string:mp_print(mp, "unknown string"); break;
4600   case mp_pen_type:mp_print(mp, "pen"); break;
4601   case mp_unknown_pen:mp_print(mp, "unknown pen"); break;
4602   case mp_path_type:mp_print(mp, "path"); break;
4603   case mp_unknown_path:mp_print(mp, "unknown path"); break;
4604   case mp_picture_type:mp_print(mp, "picture"); break;
4605   case mp_unknown_picture:mp_print(mp, "unknown picture"); break;
4606   case mp_transform_type:mp_print(mp, "transform"); break;
4607   case mp_color_type:mp_print(mp, "color"); break;
4608   case mp_cmykcolor_type:mp_print(mp, "cmykcolor"); break;
4609   case mp_pair_type:mp_print(mp, "pair"); break;
4610   case mp_known:mp_print(mp, "known numeric"); break;
4611   case mp_dependent:mp_print(mp, "dependent"); break;
4612   case mp_proto_dependent:mp_print(mp, "proto-dependent"); break;
4613   case mp_numeric_type:mp_print(mp, "numeric"); break;
4614   case mp_independent:mp_print(mp, "independent"); break;
4615   case mp_token_list:mp_print(mp, "token list"); break;
4616   case mp_structured:mp_print(mp, "mp_structured"); break;
4617   case mp_unsuffixed_macro:mp_print(mp, "unsuffixed macro"); break;
4618   case mp_suffixed_macro:mp_print(mp, "suffixed macro"); break;
4619   default: mp_print(mp, "undefined"); break;
4620   }
4621 }
4622
4623 @ Values inside \MP\ are stored in two-word nodes that have a |name_type|
4624 as well as a |type|. The possibilities for |name_type| are defined
4625 here; they will be explained in more detail later.
4626
4627 @<Types...@>=
4628 enum {
4629  mp_root=0, /* |name_type| at the top level of a variable */
4630  mp_saved_root, /* same, when the variable has been saved */
4631  mp_structured_root, /* |name_type| where a |mp_structured| branch occurs */
4632  mp_subscr, /* |name_type| in a subscript node */
4633  mp_attr, /* |name_type| in an attribute node */
4634  mp_x_part_sector, /* |name_type| in the \&{xpart} of a node */
4635  mp_y_part_sector, /* |name_type| in the \&{ypart} of a node */
4636  mp_xx_part_sector, /* |name_type| in the \&{xxpart} of a node */
4637  mp_xy_part_sector, /* |name_type| in the \&{xypart} of a node */
4638  mp_yx_part_sector, /* |name_type| in the \&{yxpart} of a node */
4639  mp_yy_part_sector, /* |name_type| in the \&{yypart} of a node */
4640  mp_red_part_sector, /* |name_type| in the \&{redpart} of a node */
4641  mp_green_part_sector, /* |name_type| in the \&{greenpart} of a node */
4642  mp_blue_part_sector, /* |name_type| in the \&{bluepart} of a node */
4643  mp_cyan_part_sector, /* |name_type| in the \&{redpart} of a node */
4644  mp_magenta_part_sector, /* |name_type| in the \&{greenpart} of a node */
4645  mp_yellow_part_sector, /* |name_type| in the \&{bluepart} of a node */
4646  mp_black_part_sector, /* |name_type| in the \&{greenpart} of a node */
4647  mp_grey_part_sector, /* |name_type| in the \&{bluepart} of a node */
4648  mp_capsule, /* |name_type| in stashed-away subexpressions */
4649  mp_token  /* |name_type| in a numeric token or string token */
4650 };
4651
4652 @ Primitive operations that produce values have a secondary identification
4653 code in addition to their command code; it's something like genera and species.
4654 For example, `\.*' has the command code |primary_binary|, and its
4655 secondary identification is |times|. The secondary codes start at 30 so that
4656 they don't overlap with the type codes; some type codes (e.g., |mp_string_type|)
4657 are used as operators as well as type identifications.  The relative values
4658 are not critical, except for |true_code..false_code|, |or_op..and_op|,
4659 and |filled_op..bounded_op|.  The restrictions are that
4660 |and_op-false_code=or_op-true_code|, that the ordering of
4661 |x_part...blue_part| must match that of |x_part_sector..mp_blue_part_sector|,
4662 and the ordering of |filled_op..bounded_op| must match that of the code
4663 values they test for.
4664
4665 @d true_code 30 /* operation code for \.{true} */
4666 @d false_code 31 /* operation code for \.{false} */
4667 @d null_picture_code 32 /* operation code for \.{nullpicture} */
4668 @d null_pen_code 33 /* operation code for \.{nullpen} */
4669 @d job_name_op 34 /* operation code for \.{jobname} */
4670 @d read_string_op 35 /* operation code for \.{readstring} */
4671 @d pen_circle 36 /* operation code for \.{pencircle} */
4672 @d normal_deviate 37 /* operation code for \.{normaldeviate} */
4673 @d read_from_op 38 /* operation code for \.{readfrom} */
4674 @d close_from_op 39 /* operation code for \.{closefrom} */
4675 @d odd_op 40 /* operation code for \.{odd} */
4676 @d known_op 41 /* operation code for \.{known} */
4677 @d unknown_op 42 /* operation code for \.{unknown} */
4678 @d not_op 43 /* operation code for \.{not} */
4679 @d decimal 44 /* operation code for \.{decimal} */
4680 @d reverse 45 /* operation code for \.{reverse} */
4681 @d make_path_op 46 /* operation code for \.{makepath} */
4682 @d make_pen_op 47 /* operation code for \.{makepen} */
4683 @d oct_op 48 /* operation code for \.{oct} */
4684 @d hex_op 49 /* operation code for \.{hex} */
4685 @d ASCII_op 50 /* operation code for \.{ASCII} */
4686 @d char_op 51 /* operation code for \.{char} */
4687 @d length_op 52 /* operation code for \.{length} */
4688 @d turning_op 53 /* operation code for \.{turningnumber} */
4689 @d color_model_part 54 /* operation code for \.{colormodel} */
4690 @d x_part 55 /* operation code for \.{xpart} */
4691 @d y_part 56 /* operation code for \.{ypart} */
4692 @d xx_part 57 /* operation code for \.{xxpart} */
4693 @d xy_part 58 /* operation code for \.{xypart} */
4694 @d yx_part 59 /* operation code for \.{yxpart} */
4695 @d yy_part 60 /* operation code for \.{yypart} */
4696 @d red_part 61 /* operation code for \.{redpart} */
4697 @d green_part 62 /* operation code for \.{greenpart} */
4698 @d blue_part 63 /* operation code for \.{bluepart} */
4699 @d cyan_part 64 /* operation code for \.{cyanpart} */
4700 @d magenta_part 65 /* operation code for \.{magentapart} */
4701 @d yellow_part 66 /* operation code for \.{yellowpart} */
4702 @d black_part 67 /* operation code for \.{blackpart} */
4703 @d grey_part 68 /* operation code for \.{greypart} */
4704 @d font_part 69 /* operation code for \.{fontpart} */
4705 @d text_part 70 /* operation code for \.{textpart} */
4706 @d path_part 71 /* operation code for \.{pathpart} */
4707 @d pen_part 72 /* operation code for \.{penpart} */
4708 @d dash_part 73 /* operation code for \.{dashpart} */
4709 @d sqrt_op 74 /* operation code for \.{sqrt} */
4710 @d m_exp_op 75 /* operation code for \.{mexp} */
4711 @d m_log_op 76 /* operation code for \.{mlog} */
4712 @d sin_d_op 77 /* operation code for \.{sind} */
4713 @d cos_d_op 78 /* operation code for \.{cosd} */
4714 @d floor_op 79 /* operation code for \.{floor} */
4715 @d uniform_deviate 80 /* operation code for \.{uniformdeviate} */
4716 @d char_exists_op 81 /* operation code for \.{charexists} */
4717 @d font_size 82 /* operation code for \.{fontsize} */
4718 @d ll_corner_op 83 /* operation code for \.{llcorner} */
4719 @d lr_corner_op 84 /* operation code for \.{lrcorner} */
4720 @d ul_corner_op 85 /* operation code for \.{ulcorner} */
4721 @d ur_corner_op 86 /* operation code for \.{urcorner} */
4722 @d arc_length 87 /* operation code for \.{arclength} */
4723 @d angle_op 88 /* operation code for \.{angle} */
4724 @d cycle_op 89 /* operation code for \.{cycle} */
4725 @d filled_op 90 /* operation code for \.{filled} */
4726 @d stroked_op 91 /* operation code for \.{stroked} */
4727 @d textual_op 92 /* operation code for \.{textual} */
4728 @d clipped_op 93 /* operation code for \.{clipped} */
4729 @d bounded_op 94 /* operation code for \.{bounded} */
4730 @d plus 95 /* operation code for \.+ */
4731 @d minus 96 /* operation code for \.- */
4732 @d times 97 /* operation code for \.* */
4733 @d over 98 /* operation code for \./ */
4734 @d pythag_add 99 /* operation code for \.{++} */
4735 @d pythag_sub 100 /* operation code for \.{+-+} */
4736 @d or_op 101 /* operation code for \.{or} */
4737 @d and_op 102 /* operation code for \.{and} */
4738 @d less_than 103 /* operation code for \.< */
4739 @d less_or_equal 104 /* operation code for \.{<=} */
4740 @d greater_than 105 /* operation code for \.> */
4741 @d greater_or_equal 106 /* operation code for \.{>=} */
4742 @d equal_to 107 /* operation code for \.= */
4743 @d unequal_to 108 /* operation code for \.{<>} */
4744 @d concatenate 109 /* operation code for \.\& */
4745 @d rotated_by 110 /* operation code for \.{rotated} */
4746 @d slanted_by 111 /* operation code for \.{slanted} */
4747 @d scaled_by 112 /* operation code for \.{scaled} */
4748 @d shifted_by 113 /* operation code for \.{shifted} */
4749 @d transformed_by 114 /* operation code for \.{transformed} */
4750 @d x_scaled 115 /* operation code for \.{xscaled} */
4751 @d y_scaled 116 /* operation code for \.{yscaled} */
4752 @d z_scaled 117 /* operation code for \.{zscaled} */
4753 @d in_font 118 /* operation code for \.{infont} */
4754 @d intersect 119 /* operation code for \.{intersectiontimes} */
4755 @d double_dot 120 /* operation code for improper \.{..} */
4756 @d substring_of 121 /* operation code for \.{substring} */
4757 @d min_of substring_of
4758 @d subpath_of 122 /* operation code for \.{subpath} */
4759 @d direction_time_of 123 /* operation code for \.{directiontime} */
4760 @d point_of 124 /* operation code for \.{point} */
4761 @d precontrol_of 125 /* operation code for \.{precontrol} */
4762 @d postcontrol_of 126 /* operation code for \.{postcontrol} */
4763 @d pen_offset_of 127 /* operation code for \.{penoffset} */
4764 @d arc_time_of 128 /* operation code for \.{arctime} */
4765 @d mp_version 129 /* operation code for \.{mpversion} */
4766
4767 @c void mp_print_op (MP mp,quarterword c) { 
4768   if (c<=mp_numeric_type ) {
4769     mp_print_type(mp, c);
4770   } else {
4771     switch (c) {
4772     case true_code:mp_print(mp, "true"); break;
4773     case false_code:mp_print(mp, "false"); break;
4774     case null_picture_code:mp_print(mp, "nullpicture"); break;
4775     case null_pen_code:mp_print(mp, "nullpen"); break;
4776     case job_name_op:mp_print(mp, "jobname"); break;
4777     case read_string_op:mp_print(mp, "readstring"); break;
4778     case pen_circle:mp_print(mp, "pencircle"); break;
4779     case normal_deviate:mp_print(mp, "normaldeviate"); break;
4780     case read_from_op:mp_print(mp, "readfrom"); break;
4781     case close_from_op:mp_print(mp, "closefrom"); break;
4782     case odd_op:mp_print(mp, "odd"); break;
4783     case known_op:mp_print(mp, "known"); break;
4784     case unknown_op:mp_print(mp, "unknown"); break;
4785     case not_op:mp_print(mp, "not"); break;
4786     case decimal:mp_print(mp, "decimal"); break;
4787     case reverse:mp_print(mp, "reverse"); break;
4788     case make_path_op:mp_print(mp, "makepath"); break;
4789     case make_pen_op:mp_print(mp, "makepen"); break;
4790     case oct_op:mp_print(mp, "oct"); break;
4791     case hex_op:mp_print(mp, "hex"); break;
4792     case ASCII_op:mp_print(mp, "ASCII"); break;
4793     case char_op:mp_print(mp, "char"); break;
4794     case length_op:mp_print(mp, "length"); break;
4795     case turning_op:mp_print(mp, "turningnumber"); break;
4796     case x_part:mp_print(mp, "xpart"); break;
4797     case y_part:mp_print(mp, "ypart"); break;
4798     case xx_part:mp_print(mp, "xxpart"); break;
4799     case xy_part:mp_print(mp, "xypart"); break;
4800     case yx_part:mp_print(mp, "yxpart"); break;
4801     case yy_part:mp_print(mp, "yypart"); break;
4802     case red_part:mp_print(mp, "redpart"); break;
4803     case green_part:mp_print(mp, "greenpart"); break;
4804     case blue_part:mp_print(mp, "bluepart"); break;
4805     case cyan_part:mp_print(mp, "cyanpart"); break;
4806     case magenta_part:mp_print(mp, "magentapart"); break;
4807     case yellow_part:mp_print(mp, "yellowpart"); break;
4808     case black_part:mp_print(mp, "blackpart"); break;
4809     case grey_part:mp_print(mp, "greypart"); break;
4810     case color_model_part:mp_print(mp, "colormodel"); break;
4811     case font_part:mp_print(mp, "fontpart"); break;
4812     case text_part:mp_print(mp, "textpart"); break;
4813     case path_part:mp_print(mp, "pathpart"); break;
4814     case pen_part:mp_print(mp, "penpart"); break;
4815     case dash_part:mp_print(mp, "dashpart"); break;
4816     case sqrt_op:mp_print(mp, "sqrt"); break;
4817     case m_exp_op:mp_print(mp, "mexp"); break;
4818     case m_log_op:mp_print(mp, "mlog"); break;
4819     case sin_d_op:mp_print(mp, "sind"); break;
4820     case cos_d_op:mp_print(mp, "cosd"); break;
4821     case floor_op:mp_print(mp, "floor"); break;
4822     case uniform_deviate:mp_print(mp, "uniformdeviate"); break;
4823     case char_exists_op:mp_print(mp, "charexists"); break;
4824     case font_size:mp_print(mp, "fontsize"); break;
4825     case ll_corner_op:mp_print(mp, "llcorner"); break;
4826     case lr_corner_op:mp_print(mp, "lrcorner"); break;
4827     case ul_corner_op:mp_print(mp, "ulcorner"); break;
4828     case ur_corner_op:mp_print(mp, "urcorner"); break;
4829     case arc_length:mp_print(mp, "arclength"); break;
4830     case angle_op:mp_print(mp, "angle"); break;
4831     case cycle_op:mp_print(mp, "cycle"); break;
4832     case filled_op:mp_print(mp, "filled"); break;
4833     case stroked_op:mp_print(mp, "stroked"); break;
4834     case textual_op:mp_print(mp, "textual"); break;
4835     case clipped_op:mp_print(mp, "clipped"); break;
4836     case bounded_op:mp_print(mp, "bounded"); break;
4837     case plus:mp_print_char(mp, '+'); break;
4838     case minus:mp_print_char(mp, '-'); break;
4839     case times:mp_print_char(mp, '*'); break;
4840     case over:mp_print_char(mp, '/'); break;
4841     case pythag_add:mp_print(mp, "++"); break;
4842     case pythag_sub:mp_print(mp, "+-+"); break;
4843     case or_op:mp_print(mp, "or"); break;
4844     case and_op:mp_print(mp, "and"); break;
4845     case less_than:mp_print_char(mp, '<'); break;
4846     case less_or_equal:mp_print(mp, "<="); break;
4847     case greater_than:mp_print_char(mp, '>'); break;
4848     case greater_or_equal:mp_print(mp, ">="); break;
4849     case equal_to:mp_print_char(mp, '='); break;
4850     case unequal_to:mp_print(mp, "<>"); break;
4851     case concatenate:mp_print(mp, "&"); break;
4852     case rotated_by:mp_print(mp, "rotated"); break;
4853     case slanted_by:mp_print(mp, "slanted"); break;
4854     case scaled_by:mp_print(mp, "scaled"); break;
4855     case shifted_by:mp_print(mp, "shifted"); break;
4856     case transformed_by:mp_print(mp, "transformed"); break;
4857     case x_scaled:mp_print(mp, "xscaled"); break;
4858     case y_scaled:mp_print(mp, "yscaled"); break;
4859     case z_scaled:mp_print(mp, "zscaled"); break;
4860     case in_font:mp_print(mp, "infont"); break;
4861     case intersect:mp_print(mp, "intersectiontimes"); break;
4862     case substring_of:mp_print(mp, "substring"); break;
4863     case subpath_of:mp_print(mp, "subpath"); break;
4864     case direction_time_of:mp_print(mp, "directiontime"); break;
4865     case point_of:mp_print(mp, "point"); break;
4866     case precontrol_of:mp_print(mp, "precontrol"); break;
4867     case postcontrol_of:mp_print(mp, "postcontrol"); break;
4868     case pen_offset_of:mp_print(mp, "penoffset"); break;
4869     case arc_time_of:mp_print(mp, "arctime"); break;
4870     case mp_version:mp_print(mp, "mpversion"); break;
4871     default: mp_print(mp, ".."); break;
4872     }
4873   }
4874 }
4875
4876 @ \MP\ also has a bunch of internal parameters that a user might want to
4877 fuss with. Every such parameter has an identifying code number, defined here.
4878
4879 @d tracing_titles 1 /* show titles online when they appear */
4880 @d tracing_equations 2 /* show each variable when it becomes known */
4881 @d tracing_capsules 3 /* show capsules too */
4882 @d tracing_choices 4 /* show the control points chosen for paths */
4883 @d tracing_specs 5 /* show path subdivision prior to filling with polygonal a pen */
4884 @d tracing_commands 6 /* show commands and operations before they are performed */
4885 @d tracing_restores 7 /* show when a variable or internal is restored */
4886 @d tracing_macros 8 /* show macros before they are expanded */
4887 @d tracing_output 9 /* show digitized edges as they are output */
4888 @d tracing_stats 10 /* show memory usage at end of job */
4889 @d tracing_lost_chars 11 /* show characters that aren't \&{infont} */
4890 @d tracing_online 12 /* show long diagnostics on terminal and in the log file */
4891 @d year 13 /* the current year (e.g., 1984) */
4892 @d month 14 /* the current month (e.g, 3 $\equiv$ March) */
4893 @d day 15 /* the current day of the month */
4894 @d mp_time 16 /* the number of minutes past midnight when this job started */
4895 @d char_code 17 /* the number of the next character to be output */
4896 @d char_ext 18 /* the extension code of the next character to be output */
4897 @d char_wd 19 /* the width of the next character to be output */
4898 @d char_ht 20 /* the height of the next character to be output */
4899 @d char_dp 21 /* the depth of the next character to be output */
4900 @d char_ic 22 /* the italic correction of the next character to be output */
4901 @d design_size 23 /* the unit of measure used for |char_wd..char_ic|, in points */
4902 @d pausing 24 /* positive to display lines on the terminal before they are read */
4903 @d showstopping 25 /* positive to stop after each \&{show} command */
4904 @d fontmaking 26 /* positive if font metric output is to be produced */
4905 @d linejoin 27 /* as in \ps: 0 for mitered, 1 for round, 2 for beveled */
4906 @d linecap 28 /* as in \ps: 0 for butt, 1 for round, 2 for square */
4907 @d miterlimit 29 /* controls miter length as in \ps */
4908 @d warning_check 30 /* controls error message when variable value is large */
4909 @d boundary_char 31 /* the right boundary character for ligatures */
4910 @d prologues 32 /* positive to output conforming PostScript using built-in fonts */
4911 @d true_corners 33 /* positive to make \&{llcorner} etc. ignore \&{setbounds} */
4912 @d default_color_model 34 /* the default color model for unspecified items */
4913 @d restore_clip_color 35
4914 @d mpprocset 36 /* wether or not create PostScript command shortcuts */
4915 @d gtroffmode 37 /* whether the user specified |-troff| on the command line */
4916 @d max_given_internal 37
4917
4918 @<Glob...@>=
4919 scaled *internal;  /* the values of internal quantities */
4920 char **int_name;  /* their names */
4921 int int_ptr;  /* the maximum internal quantity defined so far */
4922 int max_internal; /* current maximum number of internal quantities */
4923 boolean troff_mode; 
4924
4925 @ @<Option variables@>=
4926 boolean troff_mode; 
4927
4928 @ @<Allocate or initialize ...@>=
4929 mp->max_internal=2*max_given_internal;
4930 mp->internal = xmalloc ((mp->max_internal+1), sizeof(scaled));
4931 mp->int_name = xmalloc ((mp->max_internal+1), sizeof(char *));
4932 mp->troff_mode=(opt.troff_mode>0 ? true : false);
4933
4934 @ @<Exported ...@>=
4935 int mp_troff_mode(MP mp);
4936
4937 @ @c
4938 int mp_troff_mode(MP mp) { return mp->troff_mode; }
4939
4940 @ @<Set initial ...@>=
4941 for (k=0;k<= mp->max_internal; k++ ) { 
4942    mp->internal[k]=0; 
4943    mp->int_name[k]=NULL; 
4944 }
4945 mp->int_ptr=max_given_internal;
4946
4947 @ The symbolic names for internal quantities are put into \MP's hash table
4948 by using a routine called |primitive|, which will be defined later. Let us
4949 enter them now, so that we don't have to list all those names again
4950 anywhere else.
4951
4952 @<Put each of \MP's primitives into the hash table@>=
4953 mp_primitive(mp, "tracingtitles",internal_quantity,tracing_titles);
4954 @:tracingtitles_}{\&{tracingtitles} primitive@>
4955 mp_primitive(mp, "tracingequations",internal_quantity,tracing_equations);
4956 @:tracing_equations_}{\&{tracingequations} primitive@>
4957 mp_primitive(mp, "tracingcapsules",internal_quantity,tracing_capsules);
4958 @:tracing_capsules_}{\&{tracingcapsules} primitive@>
4959 mp_primitive(mp, "tracingchoices",internal_quantity,tracing_choices);
4960 @:tracing_choices_}{\&{tracingchoices} primitive@>
4961 mp_primitive(mp, "tracingspecs",internal_quantity,tracing_specs);
4962 @:tracing_specs_}{\&{tracingspecs} primitive@>
4963 mp_primitive(mp, "tracingcommands",internal_quantity,tracing_commands);
4964 @:tracing_commands_}{\&{tracingcommands} primitive@>
4965 mp_primitive(mp, "tracingrestores",internal_quantity,tracing_restores);
4966 @:tracing_restores_}{\&{tracingrestores} primitive@>
4967 mp_primitive(mp, "tracingmacros",internal_quantity,tracing_macros);
4968 @:tracing_macros_}{\&{tracingmacros} primitive@>
4969 mp_primitive(mp, "tracingoutput",internal_quantity,tracing_output);
4970 @:tracing_output_}{\&{tracingoutput} primitive@>
4971 mp_primitive(mp, "tracingstats",internal_quantity,tracing_stats);
4972 @:tracing_stats_}{\&{tracingstats} primitive@>
4973 mp_primitive(mp, "tracinglostchars",internal_quantity,tracing_lost_chars);
4974 @:tracing_lost_chars_}{\&{tracinglostchars} primitive@>
4975 mp_primitive(mp, "tracingonline",internal_quantity,tracing_online);
4976 @:tracing_online_}{\&{tracingonline} primitive@>
4977 mp_primitive(mp, "year",internal_quantity,year);
4978 @:year_}{\&{year} primitive@>
4979 mp_primitive(mp, "month",internal_quantity,month);
4980 @:month_}{\&{month} primitive@>
4981 mp_primitive(mp, "day",internal_quantity,day);
4982 @:day_}{\&{day} primitive@>
4983 mp_primitive(mp, "time",internal_quantity,mp_time);
4984 @:time_}{\&{time} primitive@>
4985 mp_primitive(mp, "charcode",internal_quantity,char_code);
4986 @:char_code_}{\&{charcode} primitive@>
4987 mp_primitive(mp, "charext",internal_quantity,char_ext);
4988 @:char_ext_}{\&{charext} primitive@>
4989 mp_primitive(mp, "charwd",internal_quantity,char_wd);
4990 @:char_wd_}{\&{charwd} primitive@>
4991 mp_primitive(mp, "charht",internal_quantity,char_ht);
4992 @:char_ht_}{\&{charht} primitive@>
4993 mp_primitive(mp, "chardp",internal_quantity,char_dp);
4994 @:char_dp_}{\&{chardp} primitive@>
4995 mp_primitive(mp, "charic",internal_quantity,char_ic);
4996 @:char_ic_}{\&{charic} primitive@>
4997 mp_primitive(mp, "designsize",internal_quantity,design_size);
4998 @:design_size_}{\&{designsize} primitive@>
4999 mp_primitive(mp, "pausing",internal_quantity,pausing);
5000 @:pausing_}{\&{pausing} primitive@>
5001 mp_primitive(mp, "showstopping",internal_quantity,showstopping);
5002 @:showstopping_}{\&{showstopping} primitive@>
5003 mp_primitive(mp, "fontmaking",internal_quantity,fontmaking);
5004 @:fontmaking_}{\&{fontmaking} primitive@>
5005 mp_primitive(mp, "linejoin",internal_quantity,linejoin);
5006 @:linejoin_}{\&{linejoin} primitive@>
5007 mp_primitive(mp, "linecap",internal_quantity,linecap);
5008 @:linecap_}{\&{linecap} primitive@>
5009 mp_primitive(mp, "miterlimit",internal_quantity,miterlimit);
5010 @:miterlimit_}{\&{miterlimit} primitive@>
5011 mp_primitive(mp, "warningcheck",internal_quantity,warning_check);
5012 @:warning_check_}{\&{warningcheck} primitive@>
5013 mp_primitive(mp, "boundarychar",internal_quantity,boundary_char);
5014 @:boundary_char_}{\&{boundarychar} primitive@>
5015 mp_primitive(mp, "prologues",internal_quantity,prologues);
5016 @:prologues_}{\&{prologues} primitive@>
5017 mp_primitive(mp, "truecorners",internal_quantity,true_corners);
5018 @:true_corners_}{\&{truecorners} primitive@>
5019 mp_primitive(mp, "mpprocset",internal_quantity,mpprocset);
5020 @:mpprocset_}{\&{mpprocset} primitive@>
5021 mp_primitive(mp, "troffmode",internal_quantity,gtroffmode);
5022 @:troffmode_}{\&{troffmode} primitive@>
5023 mp_primitive(mp, "defaultcolormodel",internal_quantity,default_color_model);
5024 @:default_color_model_}{\&{defaultcolormodel} primitive@>
5025 mp_primitive(mp, "restoreclipcolor",internal_quantity,restore_clip_color);
5026 @:restore_clip_color_}{\&{restoreclipcolor} primitive@>
5027
5028 @ Colors can be specified in four color models. In the special
5029 case of |no_model|, MetaPost does not output any color operator to
5030 the postscript output.
5031
5032 Note: these values are passed directly on to |with_option|. This only
5033 works because the other possible values passed to |with_option| are
5034 8 and 10 respectively (from |with_pen| and |with_picture|).
5035
5036 There is a first state, that is only used for |gs_colormodel|. It flags
5037 the fact that there has not been any kind of color specification by
5038 the user so far in the game.
5039
5040 @d no_model 1
5041 @d grey_model 3
5042 @d rgb_model 5
5043 @d cmyk_model 7
5044 @d uninitialized_model 9
5045
5046 @<Initialize table entries (done by \.{INIMP} only)@>=
5047 mp->internal[default_color_model]=(rgb_model*unity);
5048 mp->internal[restore_clip_color]=unity;
5049
5050 @ Well, we do have to list the names one more time, for use in symbolic
5051 printouts.
5052
5053 @<Initialize table...@>=
5054 mp->int_name[tracing_titles]=xstrdup("tracingtitles");
5055 mp->int_name[tracing_equations]=xstrdup("tracingequations");
5056 mp->int_name[tracing_capsules]=xstrdup("tracingcapsules");
5057 mp->int_name[tracing_choices]=xstrdup("tracingchoices");
5058 mp->int_name[tracing_specs]=xstrdup("tracingspecs");
5059 mp->int_name[tracing_commands]=xstrdup("tracingcommands");
5060 mp->int_name[tracing_restores]=xstrdup("tracingrestores");
5061 mp->int_name[tracing_macros]=xstrdup("tracingmacros");
5062 mp->int_name[tracing_output]=xstrdup("tracingoutput");
5063 mp->int_name[tracing_stats]=xstrdup("tracingstats");
5064 mp->int_name[tracing_lost_chars]=xstrdup("tracinglostchars");
5065 mp->int_name[tracing_online]=xstrdup("tracingonline");
5066 mp->int_name[year]=xstrdup("year");
5067 mp->int_name[month]=xstrdup("month");
5068 mp->int_name[day]=xstrdup("day");
5069 mp->int_name[mp_time]=xstrdup("time");
5070 mp->int_name[char_code]=xstrdup("charcode");
5071 mp->int_name[char_ext]=xstrdup("charext");
5072 mp->int_name[char_wd]=xstrdup("charwd");
5073 mp->int_name[char_ht]=xstrdup("charht");
5074 mp->int_name[char_dp]=xstrdup("chardp");
5075 mp->int_name[char_ic]=xstrdup("charic");
5076 mp->int_name[design_size]=xstrdup("designsize");
5077 mp->int_name[pausing]=xstrdup("pausing");
5078 mp->int_name[showstopping]=xstrdup("showstopping");
5079 mp->int_name[fontmaking]=xstrdup("fontmaking");
5080 mp->int_name[linejoin]=xstrdup("linejoin");
5081 mp->int_name[linecap]=xstrdup("linecap");
5082 mp->int_name[miterlimit]=xstrdup("miterlimit");
5083 mp->int_name[warning_check]=xstrdup("warningcheck");
5084 mp->int_name[boundary_char]=xstrdup("boundarychar");
5085 mp->int_name[prologues]=xstrdup("prologues");
5086 mp->int_name[true_corners]=xstrdup("truecorners");
5087 mp->int_name[default_color_model]=xstrdup("defaultcolormodel");
5088 mp->int_name[mpprocset]=xstrdup("mpprocset");
5089 mp->int_name[gtroffmode]=xstrdup("troffmode");
5090 mp->int_name[restore_clip_color]=xstrdup("restoreclipcolor");
5091
5092 @ The following procedure, which is called just before \MP\ initializes its
5093 input and output, establishes the initial values of the date and time.
5094 @^system dependencies@>
5095
5096 Note that the values are |scaled| integers. Hence \MP\ can no longer
5097 be used after the year 32767.
5098
5099 @c 
5100 void mp_fix_date_and_time (MP mp) { 
5101   time_t clock = time ((time_t *) 0);
5102   struct tm *tmptr = localtime (&clock);
5103   mp->internal[mp_time]=
5104       (tmptr->tm_hour*60+tmptr->tm_min)*unity; /* minutes since midnight */
5105   mp->internal[day]=(tmptr->tm_mday)*unity; /* fourth day of the month */
5106   mp->internal[month]=(tmptr->tm_mon+1)*unity; /* seventh month of the year */
5107   mp->internal[year]=(tmptr->tm_year+1900)*unity; /* Anno Domini */
5108 }
5109
5110 @ @<Declarations@>=
5111 void mp_fix_date_and_time (MP mp) ;
5112
5113 @ \MP\ is occasionally supposed to print diagnostic information that
5114 goes only into the transcript file, unless |tracing_online| is positive.
5115 Now that we have defined |tracing_online| we can define
5116 two routines that adjust the destination of print commands:
5117
5118 @<Declarations@>=
5119 void mp_begin_diagnostic (MP mp) ;
5120 void mp_end_diagnostic (MP mp,boolean blank_line);
5121 void mp_print_diagnostic (MP mp, char *s, char *t, boolean nuline) ;
5122
5123 @ @<Basic printing...@>=
5124 @<Declare a function called |true_line|@>;
5125 void mp_begin_diagnostic (MP mp) { /* prepare to do some tracing */
5126   mp->old_setting=mp->selector;
5127   if ( mp->selector==ps_file_only ) mp->selector=mp->non_ps_setting;
5128   if ((mp->internal[tracing_online]<=0)&&(mp->selector==term_and_log)){ 
5129     decr(mp->selector);
5130     if ( mp->history==spotless ) mp->history=warning_issued;
5131   }
5132 }
5133 @#
5134 void mp_end_diagnostic (MP mp,boolean blank_line) {
5135   /* restore proper conditions after tracing */
5136   mp_print_nl(mp, "");
5137   if ( blank_line ) mp_print_ln(mp);
5138   mp->selector=mp->old_setting;
5139 }
5140
5141 @ The global variable |non_ps_setting| is initialized when it is time to print
5142 on |ps_file|.
5143
5144 @<Glob...@>=
5145 unsigned int old_setting;
5146 unsigned int non_ps_setting;
5147
5148 @ We will occasionally use |begin_diagnostic| in connection with line-number
5149 printing, as follows. (The parameter |s| is typically |"Path"| or
5150 |"Cycle spec"|, etc.)
5151
5152 @<Basic printing...@>=
5153 void mp_print_diagnostic (MP mp, char *s, char *t, boolean nuline) { 
5154   mp_begin_diagnostic(mp);
5155   if ( nuline ) mp_print_nl(mp, s); else mp_print(mp, s);
5156   mp_print(mp, " at line "); 
5157   mp_print_int(mp, mp_true_line(mp));
5158   mp_print(mp, t); mp_print_char(mp, ':');
5159 }
5160
5161 @ The 256 |ASCII_code| characters are grouped into classes by means of
5162 the |char_class| table. Individual class numbers have no semantic
5163 or syntactic significance, except in a few instances defined here.
5164 There's also |max_class|, which can be used as a basis for additional
5165 class numbers in nonstandard extensions of \MP.
5166
5167 @d digit_class 0 /* the class number of \.{0123456789} */
5168 @d period_class 1 /* the class number of `\..' */
5169 @d space_class 2 /* the class number of spaces and nonstandard characters */
5170 @d percent_class 3 /* the class number of `\.\%' */
5171 @d string_class 4 /* the class number of `\."' */
5172 @d right_paren_class 8 /* the class number of `\.)' */
5173 @d isolated_classes 5: case 6: case 7: case 8 /* characters that make length-one tokens only */
5174 @d letter_class 9 /* letters and the underline character */
5175 @d left_bracket_class 17 /* `\.[' */
5176 @d right_bracket_class 18 /* `\.]' */
5177 @d invalid_class 20 /* bad character in the input */
5178 @d max_class 20 /* the largest class number */
5179
5180 @<Glob...@>=
5181 int char_class[256]; /* the class numbers */
5182
5183 @ If changes are made to accommodate non-ASCII character sets, they should
5184 follow the guidelines in Appendix~C of {\sl The {\logos METAFONT\/}book}.
5185 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
5186 @^system dependencies@>
5187
5188 @<Set initial ...@>=
5189 for (k='0';k<='9';k++) 
5190   mp->char_class[k]=digit_class;
5191 mp->char_class['.']=period_class;
5192 mp->char_class[' ']=space_class;
5193 mp->char_class['%']=percent_class;
5194 mp->char_class['"']=string_class;
5195 mp->char_class[',']=5;
5196 mp->char_class[';']=6;
5197 mp->char_class['(']=7;
5198 mp->char_class[')']=right_paren_class;
5199 for (k='A';k<= 'Z';k++ )
5200   mp->char_class[k]=letter_class;
5201 for (k='a';k<='z';k++) 
5202   mp->char_class[k]=letter_class;
5203 mp->char_class['_']=letter_class;
5204 mp->char_class['<']=10;
5205 mp->char_class['=']=10;
5206 mp->char_class['>']=10;
5207 mp->char_class[':']=10;
5208 mp->char_class['|']=10;
5209 mp->char_class['`']=11;
5210 mp->char_class['\'']=11;
5211 mp->char_class['+']=12;
5212 mp->char_class['-']=12;
5213 mp->char_class['/']=13;
5214 mp->char_class['*']=13;
5215 mp->char_class['\\']=13;
5216 mp->char_class['!']=14;
5217 mp->char_class['?']=14;
5218 mp->char_class['#']=15;
5219 mp->char_class['&']=15;
5220 mp->char_class['@@']=15;
5221 mp->char_class['$']=15;
5222 mp->char_class['^']=16;
5223 mp->char_class['~']=16;
5224 mp->char_class['[']=left_bracket_class;
5225 mp->char_class[']']=right_bracket_class;
5226 mp->char_class['{']=19;
5227 mp->char_class['}']=19;
5228 for (k=0;k<' ';k++)
5229   mp->char_class[k]=invalid_class;
5230 mp->char_class['\t']=space_class;
5231 mp->char_class['\f']=space_class;
5232 for (k=127;k<=255;k++)
5233   mp->char_class[k]=invalid_class;
5234
5235 @* \[13] The hash table.
5236 Symbolic tokens are stored and retrieved by means of a fairly standard hash
5237 table algorithm called the method of ``coalescing lists'' (cf.\ Algorithm 6.4C
5238 in {\sl The Art of Computer Programming\/}). Once a symbolic token enters the
5239 table, it is never removed.
5240
5241 The actual sequence of characters forming a symbolic token is
5242 stored in the |str_pool| array together with all the other strings. An
5243 auxiliary array |hash| consists of items with two halfword fields per
5244 word. The first of these, called |next(p)|, points to the next identifier
5245 belonging to the same coalesced list as the identifier corresponding to~|p|;
5246 and the other, called |text(p)|, points to the |str_start| entry for
5247 |p|'s identifier. If position~|p| of the hash table is empty, we have
5248 |text(p)=0|; if position |p| is either empty or the end of a coalesced
5249 hash list, we have |next(p)=0|.
5250
5251 An auxiliary pointer variable called |hash_used| is maintained in such a
5252 way that all locations |p>=hash_used| are nonempty. The global variable
5253 |st_count| tells how many symbolic tokens have been defined, if statistics
5254 are being kept.
5255
5256 The first 256 locations of |hash| are reserved for symbols of length one.
5257
5258 There's a parallel array called |eqtb| that contains the current equivalent
5259 values of each symbolic token. The entries of this array consist of
5260 two halfwords called |eq_type| (a command code) and |equiv| (a secondary
5261 piece of information that qualifies the |eq_type|).
5262
5263 @d next(A)   mp->hash[(A)].lh /* link for coalesced lists */
5264 @d text(A)   mp->hash[(A)].rh /* string number for symbolic token name */
5265 @d eq_type(A)   mp->eqtb[(A)].lh /* the current ``meaning'' of a symbolic token */
5266 @d equiv(A)   mp->eqtb[(A)].rh /* parametric part of a token's meaning */
5267 @d hash_base 257 /* hashing actually starts here */
5268 @d hash_is_full   (mp->hash_used==hash_base) /* are all positions occupied? */
5269
5270 @<Glob...@>=
5271 pointer hash_used; /* allocation pointer for |hash| */
5272 integer st_count; /* total number of known identifiers */
5273
5274 @ Certain entries in the hash table are ``frozen'' and not redefinable,
5275 since they are used in error recovery.
5276
5277 @d hash_top (hash_base+mp->hash_size) /* the first location of the frozen area */
5278 @d frozen_inaccessible hash_top /* |hash| location to protect the frozen area */
5279 @d frozen_repeat_loop (hash_top+1) /* |hash| location of a loop-repeat token */
5280 @d frozen_right_delimiter (hash_top+2) /* |hash| location of a permanent `\.)' */
5281 @d frozen_left_bracket (hash_top+3) /* |hash| location of a permanent `\.[' */
5282 @d frozen_slash (hash_top+4) /* |hash| location of a permanent `\./' */
5283 @d frozen_colon (hash_top+5) /* |hash| location of a permanent `\.:' */
5284 @d frozen_semicolon (hash_top+6) /* |hash| location of a permanent `\.;' */
5285 @d frozen_end_for (hash_top+7) /* |hash| location of a permanent \&{endfor} */
5286 @d frozen_end_def (hash_top+8) /* |hash| location of a permanent \&{enddef} */
5287 @d frozen_fi (hash_top+9) /* |hash| location of a permanent \&{fi} */
5288 @d frozen_end_group (hash_top+10) /* |hash| location of a permanent `\.{endgroup}' */
5289 @d frozen_etex (hash_top+11) /* |hash| location of a permanent \&{etex} */
5290 @d frozen_mpx_break (hash_top+12) /* |hash| location of a permanent \&{mpxbreak} */
5291 @d frozen_bad_vardef (hash_top+13) /* |hash| location of `\.{a bad variable}' */
5292 @d frozen_undefined (hash_top+14) /* |hash| location that never gets defined */
5293 @d hash_end (hash_top+14) /* the actual size of the |hash| and |eqtb| arrays */
5294
5295 @<Glob...@>=
5296 two_halves *hash; /* the hash table */
5297 two_halves *eqtb; /* the equivalents */
5298
5299 @ @<Allocate or initialize ...@>=
5300 mp->hash = xmalloc((hash_end+1),sizeof(two_halves));
5301 mp->eqtb = xmalloc((hash_end+1),sizeof(two_halves));
5302
5303 @ @<Dealloc variables@>=
5304 xfree(mp->hash);
5305 xfree(mp->eqtb);
5306
5307 @ @<Set init...@>=
5308 next(1)=0; text(1)=0; eq_type(1)=tag_token; equiv(1)=null;
5309 for (k=2;k<=hash_end;k++)  { 
5310   mp->hash[k]=mp->hash[1]; mp->eqtb[k]=mp->eqtb[1];
5311 }
5312
5313 @ @<Initialize table entries...@>=
5314 mp->hash_used=frozen_inaccessible; /* nothing is used */
5315 mp->st_count=0;
5316 text(frozen_bad_vardef)=intern("a bad variable");
5317 text(frozen_etex)=intern("etex");
5318 text(frozen_mpx_break)=intern("mpxbreak");
5319 text(frozen_fi)=intern("fi");
5320 text(frozen_end_group)=intern("endgroup");
5321 text(frozen_end_def)=intern("enddef");
5322 text(frozen_end_for)=intern("endfor");
5323 text(frozen_semicolon)=intern(";");
5324 text(frozen_colon)=intern(":");
5325 text(frozen_slash)=intern("/");
5326 text(frozen_left_bracket)=intern("[");
5327 text(frozen_right_delimiter)=intern(")");
5328 text(frozen_inaccessible)=intern(" INACCESSIBLE");
5329 eq_type(frozen_right_delimiter)=right_delimiter;
5330
5331 @ @<Check the ``constant'' values...@>=
5332 if ( hash_end+mp->max_internal>max_halfword ) mp->bad=17;
5333
5334 @ Here is the subroutine that searches the hash table for an identifier
5335 that matches a given string of length~|l| appearing in |buffer[j..
5336 (j+l-1)]|. If the identifier is not found, it is inserted; hence it
5337 will always be found, and the corresponding hash table address
5338 will be returned.
5339
5340 @c 
5341 pointer mp_id_lookup (MP mp,integer j, integer l) { /* search the hash table */
5342   integer h; /* hash code */
5343   pointer p; /* index in |hash| array */
5344   pointer k; /* index in |buffer| array */
5345   if (l==1) {
5346     @<Treat special case of length 1 and |break|@>;
5347   }
5348   @<Compute the hash code |h|@>;
5349   p=h+hash_base; /* we start searching here; note that |0<=h<hash_prime| */
5350   while (true)  { 
5351         if (text(p)>0 && length(text(p))==l && mp_str_eq_buf(mp, text(p),j)) 
5352       break;
5353     if ( next(p)==0 ) {
5354       @<Insert a new symbolic token after |p|, then
5355         make |p| point to it and |break|@>;
5356     }
5357     p=next(p);
5358   }
5359   return p;
5360 };
5361
5362 @ @<Treat special case of length 1...@>=
5363  p=mp->buffer[j]+1; text(p)=p-1; return p;
5364
5365
5366 @ @<Insert a new symbolic...@>=
5367 {
5368 if ( text(p)>0 ) { 
5369   do {  
5370     if ( hash_is_full )
5371       mp_overflow(mp, "hash size",mp->hash_size);
5372 @:MetaPost capacity exceeded hash size}{\quad hash size@>
5373     decr(mp->hash_used);
5374   } while (text(mp->hash_used)!=0); /* search for an empty location in |hash| */
5375   next(p)=mp->hash_used; 
5376   p=mp->hash_used;
5377 }
5378 str_room(l);
5379 for (k=j;k<=j+l-1;k++) {
5380   append_char(mp->buffer[k]);
5381 }
5382 text(p)=mp_make_string(mp); 
5383 mp->str_ref[text(p)]=max_str_ref;
5384 incr(mp->st_count);
5385 break;
5386 }
5387
5388
5389 @ The value of |hash_prime| should be roughly 85\pct! of |hash_size|, and it
5390 should be a prime number.  The theory of hashing tells us to expect fewer
5391 than two table probes, on the average, when the search is successful.
5392 [See J.~S. Vitter, {\sl Journal of the ACM\/ \bf30} (1983), 231--258.]
5393 @^Vitter, Jeffrey Scott@>
5394
5395 @<Compute the hash code |h|@>=
5396 h=mp->buffer[j];
5397 for (k=j+1;k<=j+l-1;k++){ 
5398   h=h+h+mp->buffer[k];
5399   while ( h>=mp->hash_prime ) h=h-mp->hash_prime;
5400 }
5401
5402 @ @<Search |eqtb| for equivalents equal to |p|@>=
5403 for (q=1;q<=hash_end;q++) { 
5404   if ( equiv(q)==p ) { 
5405     mp_print_nl(mp, "EQUIV("); 
5406     mp_print_int(mp, q); 
5407     mp_print_char(mp, ')');
5408   }
5409 }
5410
5411 @ We need to put \MP's ``primitive'' symbolic tokens into the hash
5412 table, together with their command code (which will be the |eq_type|)
5413 and an operand (which will be the |equiv|). The |primitive| procedure
5414 does this, in a way that no \MP\ user can. The global value |cur_sym|
5415 contains the new |eqtb| pointer after |primitive| has acted.
5416
5417 @c 
5418 void mp_primitive (MP mp, char *ss, halfword c, halfword o) {
5419   pool_pointer k; /* index into |str_pool| */
5420   small_number j; /* index into |buffer| */
5421   small_number l; /* length of the string */
5422   str_number s;
5423   s = intern(ss);
5424   k=mp->str_start[s]; l=str_stop(s)-k;
5425   /* we will move |s| into the (empty) |buffer| */
5426   for (j=0;j<=l-1;j++) {
5427     mp->buffer[j]=mp->str_pool[k+j];
5428   }
5429   mp->cur_sym=mp_id_lookup(mp, 0,l);
5430   if ( s>=256 ) { /* we don't want to have the string twice */
5431     mp_flush_string(mp, text(mp->cur_sym)); text(mp->cur_sym)=s;
5432   };
5433   eq_type(mp->cur_sym)=c; 
5434   equiv(mp->cur_sym)=o;
5435 }
5436
5437
5438 @ Many of \MP's primitives need no |equiv|, since they are identifiable
5439 by their |eq_type| alone. These primitives are loaded into the hash table
5440 as follows:
5441
5442 @<Put each of \MP's primitives into the hash table@>=
5443 mp_primitive(mp, "..",path_join,0);
5444 @:.._}{\.{..} primitive@>
5445 mp_primitive(mp, "[",left_bracket,0); mp->eqtb[frozen_left_bracket]=mp->eqtb[mp->cur_sym];
5446 @:[ }{\.{[} primitive@>
5447 mp_primitive(mp, "]",right_bracket,0);
5448 @:] }{\.{]} primitive@>
5449 mp_primitive(mp, "}",right_brace,0);
5450 @:]]}{\.{\char`\}} primitive@>
5451 mp_primitive(mp, "{",left_brace,0);
5452 @:][}{\.{\char`\{} primitive@>
5453 mp_primitive(mp, ":",colon,0); mp->eqtb[frozen_colon]=mp->eqtb[mp->cur_sym];
5454 @:: }{\.{:} primitive@>
5455 mp_primitive(mp, "::",double_colon,0);
5456 @::: }{\.{::} primitive@>
5457 mp_primitive(mp, "||:",bchar_label,0);
5458 @:::: }{\.{\char'174\char'174:} primitive@>
5459 mp_primitive(mp, ":=",assignment,0);
5460 @::=_}{\.{:=} primitive@>
5461 mp_primitive(mp, ",",comma,0);
5462 @:, }{\., primitive@>
5463 mp_primitive(mp, ";",semicolon,0); mp->eqtb[frozen_semicolon]=mp->eqtb[mp->cur_sym];
5464 @:; }{\.; primitive@>
5465 mp_primitive(mp, "\\",relax,0);
5466 @:]]\\}{\.{\char`\\} primitive@>
5467 @#
5468 mp_primitive(mp, "addto",add_to_command,0);
5469 @:add_to_}{\&{addto} primitive@>
5470 mp_primitive(mp, "atleast",at_least,0);
5471 @:at_least_}{\&{atleast} primitive@>
5472 mp_primitive(mp, "begingroup",begin_group,0); mp->bg_loc=mp->cur_sym;
5473 @:begin_group_}{\&{begingroup} primitive@>
5474 mp_primitive(mp, "controls",controls,0);
5475 @:controls_}{\&{controls} primitive@>
5476 mp_primitive(mp, "curl",curl_command,0);
5477 @:curl_}{\&{curl} primitive@>
5478 mp_primitive(mp, "delimiters",delimiters,0);
5479 @:delimiters_}{\&{delimiters} primitive@>
5480 mp_primitive(mp, "endgroup",end_group,0);
5481  mp->eqtb[frozen_end_group]=mp->eqtb[mp->cur_sym]; mp->eg_loc=mp->cur_sym;
5482 @:endgroup_}{\&{endgroup} primitive@>
5483 mp_primitive(mp, "everyjob",every_job_command,0);
5484 @:every_job_}{\&{everyjob} primitive@>
5485 mp_primitive(mp, "exitif",exit_test,0);
5486 @:exit_if_}{\&{exitif} primitive@>
5487 mp_primitive(mp, "expandafter",expand_after,0);
5488 @:expand_after_}{\&{expandafter} primitive@>
5489 mp_primitive(mp, "interim",interim_command,0);
5490 @:interim_}{\&{interim} primitive@>
5491 mp_primitive(mp, "let",let_command,0);
5492 @:let_}{\&{let} primitive@>
5493 mp_primitive(mp, "newinternal",new_internal,0);
5494 @:new_internal_}{\&{newinternal} primitive@>
5495 mp_primitive(mp, "of",of_token,0);
5496 @:of_}{\&{of} primitive@>
5497 mp_primitive(mp, "randomseed",random_seed,0);
5498 @:random_seed_}{\&{randomseed} primitive@>
5499 mp_primitive(mp, "save",save_command,0);
5500 @:save_}{\&{save} primitive@>
5501 mp_primitive(mp, "scantokens",scan_tokens,0);
5502 @:scan_tokens_}{\&{scantokens} primitive@>
5503 mp_primitive(mp, "shipout",ship_out_command,0);
5504 @:ship_out_}{\&{shipout} primitive@>
5505 mp_primitive(mp, "skipto",skip_to,0);
5506 @:skip_to_}{\&{skipto} primitive@>
5507 mp_primitive(mp, "special",special_command,0);
5508 @:special}{\&{special} primitive@>
5509 mp_primitive(mp, "fontmapfile",special_command,1);
5510 @:fontmapfile}{\&{fontmapfile} primitive@>
5511 mp_primitive(mp, "fontmapline",special_command,2);
5512 @:fontmapline}{\&{fontmapline} primitive@>
5513 mp_primitive(mp, "step",step_token,0);
5514 @:step_}{\&{step} primitive@>
5515 mp_primitive(mp, "str",str_op,0);
5516 @:str_}{\&{str} primitive@>
5517 mp_primitive(mp, "tension",tension,0);
5518 @:tension_}{\&{tension} primitive@>
5519 mp_primitive(mp, "to",to_token,0);
5520 @:to_}{\&{to} primitive@>
5521 mp_primitive(mp, "until",until_token,0);
5522 @:until_}{\&{until} primitive@>
5523 mp_primitive(mp, "within",within_token,0);
5524 @:within_}{\&{within} primitive@>
5525 mp_primitive(mp, "write",write_command,0);
5526 @:write_}{\&{write} primitive@>
5527
5528 @ Each primitive has a corresponding inverse, so that it is possible to
5529 display the cryptic numeric contents of |eqtb| in symbolic form.
5530 Every call of |primitive| in this program is therefore accompanied by some
5531 straightforward code that forms part of the |print_cmd_mod| routine
5532 explained below.
5533
5534 @<Cases of |print_cmd_mod| for symbolic printing of primitives@>=
5535 case add_to_command:mp_print(mp, "addto"); break;
5536 case assignment:mp_print(mp, ":="); break;
5537 case at_least:mp_print(mp, "atleast"); break;
5538 case bchar_label:mp_print(mp, "||:"); break;
5539 case begin_group:mp_print(mp, "begingroup"); break;
5540 case colon:mp_print(mp, ":"); break;
5541 case comma:mp_print(mp, ","); break;
5542 case controls:mp_print(mp, "controls"); break;
5543 case curl_command:mp_print(mp, "curl"); break;
5544 case delimiters:mp_print(mp, "delimiters"); break;
5545 case double_colon:mp_print(mp, "::"); break;
5546 case end_group:mp_print(mp, "endgroup"); break;
5547 case every_job_command:mp_print(mp, "everyjob"); break;
5548 case exit_test:mp_print(mp, "exitif"); break;
5549 case expand_after:mp_print(mp, "expandafter"); break;
5550 case interim_command:mp_print(mp, "interim"); break;
5551 case left_brace:mp_print(mp, "{"); break;
5552 case left_bracket:mp_print(mp, "["); break;
5553 case let_command:mp_print(mp, "let"); break;
5554 case new_internal:mp_print(mp, "newinternal"); break;
5555 case of_token:mp_print(mp, "of"); break;
5556 case path_join:mp_print(mp, ".."); break;
5557 case random_seed:mp_print(mp, "randomseed"); break;
5558 case relax:mp_print_char(mp, '\\'); break;
5559 case right_brace:mp_print(mp, "}"); break;
5560 case right_bracket:mp_print(mp, "]"); break;
5561 case save_command:mp_print(mp, "save"); break;
5562 case scan_tokens:mp_print(mp, "scantokens"); break;
5563 case semicolon:mp_print(mp, ";"); break;
5564 case ship_out_command:mp_print(mp, "shipout"); break;
5565 case skip_to:mp_print(mp, "skipto"); break;
5566 case special_command: if ( m==2 ) mp_print(mp, "fontmapline"); else
5567                  if ( m==1 ) mp_print(mp, "fontmapfile"); else
5568                  mp_print(mp, "special"); break;
5569 case step_token:mp_print(mp, "step"); break;
5570 case str_op:mp_print(mp, "str"); break;
5571 case tension:mp_print(mp, "tension"); break;
5572 case to_token:mp_print(mp, "to"); break;
5573 case until_token:mp_print(mp, "until"); break;
5574 case within_token:mp_print(mp, "within"); break;
5575 case write_command:mp_print(mp, "write"); break;
5576
5577 @ We will deal with the other primitives later, at some point in the program
5578 where their |eq_type| and |equiv| values are more meaningful.  For example,
5579 the primitives for macro definitions will be loaded when we consider the
5580 routines that define macros.
5581 It is easy to find where each particular
5582 primitive was treated by looking in the index at the end; for example, the
5583 section where |"def"| entered |eqtb| is listed under `\&{def} primitive'.
5584
5585 @* \[14] Token lists.
5586 A \MP\ token is either symbolic or numeric or a string, or it denotes
5587 a macro parameter or capsule; so there are five corresponding ways to encode it
5588 @^token@>
5589 internally: (1)~A symbolic token whose hash code is~|p|
5590 is represented by the number |p|, in the |info| field of a single-word
5591 node in~|mem|. (2)~A numeric token whose |scaled| value is~|v| is
5592 represented in a two-word node of~|mem|; the |type| field is |known|,
5593 the |name_type| field is |token|, and the |value| field holds~|v|.
5594 The fact that this token appears in a two-word node rather than a
5595 one-word node is, of course, clear from the node address.
5596 (3)~A string token is also represented in a two-word node; the |type|
5597 field is |mp_string_type|, the |name_type| field is |token|, and the
5598 |value| field holds the corresponding |str_number|.  (4)~Capsules have
5599 |name_type=capsule|, and their |type| and |value| fields represent
5600 arbitrary values (in ways to be explained later).  (5)~Macro parameters
5601 are like symbolic tokens in that they appear in |info| fields of
5602 one-word nodes. The $k$th parameter is represented by |expr_base+k| if it
5603 is of type \&{expr}, or by |suffix_base+k| if it is of type \&{suffix}, or
5604 by |text_base+k| if it is of type \&{text}.  (Here |0<=k<param_size|.)
5605 Actual values of these parameters are kept in a separate stack, as we will
5606 see later.  The constants |expr_base|, |suffix_base|, and |text_base| are,
5607 of course, chosen so that there will be no confusion between symbolic
5608 tokens and parameters of various types.
5609
5610 Note that
5611 the `\\{type}' field of a node has nothing to do with ``type'' in a
5612 printer's sense. It's curious that the same word is used in such different ways.
5613
5614 @d type(A)   mp->mem[(A)].hh.b0 /* identifies what kind of value this is */
5615 @d name_type(A)   mp->mem[(A)].hh.b1 /* a clue to the name of this value */
5616 @d token_node_size 2 /* the number of words in a large token node */
5617 @d value_loc(A) ((A)+1) /* the word that contains the |value| field */
5618 @d value(A) mp->mem[value_loc((A))].cint /* the value stored in a large token node */
5619 @d expr_base (hash_end+1) /* code for the zeroth \&{expr} parameter */
5620 @d suffix_base (expr_base+mp->param_size) /* code for the zeroth \&{suffix} parameter */
5621 @d text_base (suffix_base+mp->param_size) /* code for the zeroth \&{text} parameter */
5622
5623 @<Check the ``constant''...@>=
5624 if ( text_base+mp->param_size>max_halfword ) mp->bad=18;
5625
5626 @ We have set aside a two word node beginning at |null| so that we can have
5627 |value(null)=0|.  We will make use of this coincidence later.
5628
5629 @<Initialize table entries...@>=
5630 link(null)=null; value(null)=0;
5631
5632 @ A numeric token is created by the following trivial routine.
5633
5634 @c 
5635 pointer mp_new_num_tok (MP mp,scaled v) {
5636   pointer p; /* the new node */
5637   p=mp_get_node(mp, token_node_size); value(p)=v;
5638   type(p)=mp_known; name_type(p)=mp_token; 
5639   return p;
5640 }
5641
5642 @ A token list is a singly linked list of nodes in |mem|, where
5643 each node contains a token and a link.  Here's a subroutine that gets rid
5644 of a token list when it is no longer needed.
5645
5646 @<Declarations@>=
5647 void mp_token_recycle (MP mp);
5648
5649
5650 @c void mp_flush_token_list (MP mp,pointer p) {
5651   pointer q; /* the node being recycled */
5652   while ( p!=null ) { 
5653     q=p; p=link(p);
5654     if ( q>=mp->hi_mem_min ) {
5655      free_avail(q);
5656     } else { 
5657       switch (type(q)) {
5658       case mp_vacuous: case mp_boolean_type: case mp_known:
5659         break;
5660       case mp_string_type:
5661         delete_str_ref(value(q));
5662         break;
5663       case unknown_types: case mp_pen_type: case mp_path_type: 
5664       case mp_picture_type: case mp_pair_type: case mp_color_type:
5665       case mp_cmykcolor_type: case mp_transform_type: case mp_dependent:
5666       case mp_proto_dependent: case mp_independent:
5667         mp->g_pointer=q; mp_token_recycle(mp);
5668         break;
5669       default: mp_confusion(mp, "token");
5670 @:this can't happen token}{\quad token@>
5671       }
5672       mp_free_node(mp, q,token_node_size);
5673     }
5674   }
5675 }
5676
5677 @ The procedure |show_token_list|, which prints a symbolic form of
5678 the token list that starts at a given node |p|, illustrates these
5679 conventions. The token list being displayed should not begin with a reference
5680 count. However, the procedure is intended to be fairly robust, so that if the
5681 memory links are awry or if |p| is not really a pointer to a token list,
5682 almost nothing catastrophic can happen.
5683
5684 An additional parameter |q| is also given; this parameter is either null
5685 or it points to a node in the token list where a certain magic computation
5686 takes place that will be explained later. (Basically, |q| is non-null when
5687 we are printing the two-line context information at the time of an error
5688 message; |q| marks the place corresponding to where the second line
5689 should begin.)
5690
5691 The generation will stop, and `\.{\char`\ ETC.}' will be printed, if the length
5692 of printing exceeds a given limit~|l|; the length of printing upon entry is
5693 assumed to be a given amount called |null_tally|. (Note that
5694 |show_token_list| sometimes uses itself recursively to print
5695 variable names within a capsule.)
5696 @^recursion@>
5697
5698 Unusual entries are printed in the form of all-caps tokens
5699 preceded by a space, e.g., `\.{\char`\ BAD}'.
5700
5701 @<Declarations@>=
5702 void mp_print_capsule (MP mp);
5703
5704 @ @<Declare the procedure called |show_token_list|@>=
5705 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5706                          integer null_tally) ;
5707
5708 @ @c
5709 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5710                          integer null_tally) {
5711   small_number class,c; /* the |char_class| of previous and new tokens */
5712   integer r,v; /* temporary registers */
5713   class=percent_class;
5714   mp->tally=null_tally;
5715   while ( (p!=null) && (mp->tally<l) ) { 
5716     if ( p==q ) 
5717       @<Do magic computation@>;
5718     @<Display token |p| and set |c| to its class;
5719       but |return| if there are problems@>;
5720     class=c; p=link(p);
5721   }
5722   if ( p!=null ) 
5723      mp_print(mp, " ETC.");
5724 @.ETC@>
5725   return;
5726 };
5727
5728 @ @<Display token |p| and set |c| to its class...@>=
5729 c=letter_class; /* the default */
5730 if ( (p<0)||(p>mp->mem_end) ) { 
5731   mp_print(mp, " CLOBBERED"); return;
5732 @.CLOBBERED@>
5733 }
5734 if ( p<mp->hi_mem_min ) { 
5735   @<Display two-word token@>;
5736 } else { 
5737   r=info(p);
5738   if ( r>=expr_base ) {
5739      @<Display a parameter token@>;
5740   } else {
5741     if ( r<1 ) {
5742       if ( r==0 ) { 
5743         @<Display a collective subscript@>
5744       } else {
5745         mp_print(mp, " IMPOSSIBLE");
5746 @.IMPOSSIBLE@>
5747       }
5748     } else { 
5749       r=text(r);
5750       if ( (r<0)||(r>mp->max_str_ptr) ) {
5751         mp_print(mp, " NONEXISTENT");
5752 @.NONEXISTENT@>
5753       } else {
5754        @<Print string |r| as a symbolic token
5755         and set |c| to its class@>;
5756       }
5757     }
5758   }
5759 }
5760
5761 @ @<Display two-word token@>=
5762 if ( name_type(p)==mp_token ) {
5763   if ( type(p)==mp_known ) {
5764     @<Display a numeric token@>;
5765   } else if ( type(p)!=mp_string_type ) {
5766     mp_print(mp, " BAD");
5767 @.BAD@>
5768   } else { 
5769     mp_print_char(mp, '"'); mp_print_str(mp, value(p)); mp_print_char(mp, '"');
5770     c=string_class;
5771   }
5772 } else if ((name_type(p)!=mp_capsule)||(type(p)<mp_vacuous)||(type(p)>mp_independent) ) {
5773   mp_print(mp, " BAD");
5774 } else { 
5775   mp->g_pointer=p; mp_print_capsule(mp); c=right_paren_class;
5776 }
5777
5778 @ @<Display a numeric token@>=
5779 if ( class==digit_class ) 
5780   mp_print_char(mp, ' ');
5781 v=value(p);
5782 if ( v<0 ){ 
5783   if ( class==left_bracket_class ) 
5784     mp_print_char(mp, ' ');
5785   mp_print_char(mp, '['); mp_print_scaled(mp, v); mp_print_char(mp, ']');
5786   c=right_bracket_class;
5787 } else { 
5788   mp_print_scaled(mp, v); c=digit_class;
5789 }
5790
5791
5792 @ Strictly speaking, a genuine token will never have |info(p)=0|.
5793 But we will see later (in the |print_variable_name| routine) that
5794 it is convenient to let |info(p)=0| stand for `\.{[]}'.
5795
5796 @<Display a collective subscript@>=
5797 {
5798 if ( class==left_bracket_class ) 
5799   mp_print_char(mp, ' ');
5800 mp_print(mp, "[]"); c=right_bracket_class;
5801 }
5802
5803 @ @<Display a parameter token@>=
5804 {
5805 if ( r<suffix_base ) { 
5806   mp_print(mp, "(EXPR"); r=r-(expr_base);
5807 @.EXPR@>
5808 } else if ( r<text_base ) { 
5809   mp_print(mp, "(SUFFIX"); r=r-(suffix_base);
5810 @.SUFFIX@>
5811 } else { 
5812   mp_print(mp, "(TEXT"); r=r-(text_base);
5813 @.TEXT@>
5814 }
5815 mp_print_int(mp, r); mp_print_char(mp, ')'); c=right_paren_class;
5816 }
5817
5818
5819 @ @<Print string |r| as a symbolic token...@>=
5820
5821 c=mp->char_class[mp->str_pool[mp->str_start[r]]];
5822 if ( c==class ) {
5823   switch (c) {
5824   case letter_class:mp_print_char(mp, '.'); break;
5825   case isolated_classes: break;
5826   default: mp_print_char(mp, ' '); break;
5827   }
5828 }
5829 mp_print_str(mp, r);
5830 }
5831
5832 @ The following procedures have been declared |forward| with no parameters,
5833 because the author dislikes \PASCAL's convention about |forward| procedures
5834 with parameters. It was necessary to do something, because |show_token_list|
5835 is recursive (although the recursion is limited to one level), and because
5836 |flush_token_list| is syntactically (but not semantically) recursive.
5837 @^recursion@>
5838
5839 @<Declare miscellaneous procedures that were declared |forward|@>=
5840 void mp_print_capsule (MP mp) { 
5841   mp_print_char(mp, '('); mp_print_exp(mp, mp->g_pointer,0); mp_print_char(mp, ')');
5842 };
5843 @#
5844 void mp_token_recycle (MP mp) { 
5845   mp_recycle_value(mp, mp->g_pointer);
5846 };
5847
5848 @ @<Glob...@>=
5849 pointer g_pointer; /* (global) parameter to the |forward| procedures */
5850
5851 @ Macro definitions are kept in \MP's memory in the form of token lists
5852 that have a few extra one-word nodes at the beginning.
5853
5854 The first node contains a reference count that is used to tell when the
5855 list is no longer needed. To emphasize the fact that a reference count is
5856 present, we shall refer to the |info| field of this special node as the
5857 |ref_count| field.
5858 @^reference counts@>
5859
5860 The next node or nodes after the reference count serve to describe the
5861 formal parameters. They either contain a code word that specifies all
5862 of the parameters, or they contain zero or more parameter tokens followed
5863 by the code `|general_macro|'.
5864
5865 @d ref_count info
5866   /* reference count preceding a macro definition or picture header */
5867 @d add_mac_ref(A) incr(ref_count((A))) /* make a new reference to a macro list */
5868 @d general_macro 0 /* preface to a macro defined with a parameter list */
5869 @d primary_macro 1 /* preface to a macro with a \&{primary} parameter */
5870 @d secondary_macro 2 /* preface to a macro with a \&{secondary} parameter */
5871 @d tertiary_macro 3 /* preface to a macro with a \&{tertiary} parameter */
5872 @d expr_macro 4 /* preface to a macro with an undelimited \&{expr} parameter */
5873 @d of_macro 5 /* preface to a macro with
5874   undelimited `\&{expr} |x| \&{of}~|y|' parameters */
5875 @d suffix_macro 6 /* preface to a macro with an undelimited \&{suffix} parameter */
5876 @d text_macro 7 /* preface to a macro with an undelimited \&{text} parameter */
5877
5878 @c 
5879 void mp_delete_mac_ref (MP mp,pointer p) {
5880   /* |p| points to the reference count of a macro list that is
5881     losing one reference */
5882   if ( ref_count(p)==null ) mp_flush_token_list(mp, p);
5883   else decr(ref_count(p));
5884 }
5885
5886 @ The following subroutine displays a macro, given a pointer to its
5887 reference count.
5888
5889 @c 
5890 @<Declare the procedure called |print_cmd_mod|@>;
5891 void mp_show_macro (MP mp, pointer p, integer q, integer l) {
5892   pointer r; /* temporary storage */
5893   p=link(p); /* bypass the reference count */
5894   while ( info(p)>text_macro ){ 
5895     r=link(p); link(p)=null;
5896     mp_show_token_list(mp, p,null,l,0); link(p)=r; p=r;
5897     if ( l>0 ) l=l-mp->tally; else return;
5898   } /* control printing of `\.{ETC.}' */
5899 @.ETC@>
5900   mp->tally=0;
5901   switch(info(p)) {
5902   case general_macro:mp_print(mp, "->"); break;
5903 @.->@>
5904   case primary_macro: case secondary_macro: case tertiary_macro:
5905     mp_print_char(mp, '<');
5906     mp_print_cmd_mod(mp, param_type,info(p)); 
5907     mp_print(mp, ">->");
5908     break;
5909   case expr_macro:mp_print(mp, "<expr>->"); break;
5910   case of_macro:mp_print(mp, "<expr>of<primary>->"); break;
5911   case suffix_macro:mp_print(mp, "<suffix>->"); break;
5912   case text_macro:mp_print(mp, "<text>->"); break;
5913   } /* there are no other cases */
5914   mp_show_token_list(mp, link(p),q,l-mp->tally,0);
5915 }
5916
5917 @* \[15] Data structures for variables.
5918 The variables of \MP\ programs can be simple, like `\.x', or they can
5919 combine the structural properties of arrays and records, like `\.{x20a.b}'.
5920 A \MP\ user assigns a type to a variable like \.{x20a.b} by saying, for
5921 example, `\.{boolean} \.{x20a.b}'. It's time for us to study how such
5922 things are represented inside of the computer.
5923
5924 Each variable value occupies two consecutive words, either in a two-word
5925 node called a value node, or as a two-word subfield of a larger node.  One
5926 of those two words is called the |value| field; it is an integer,
5927 containing either a |scaled| numeric value or the representation of some
5928 other type of quantity. (It might also be subdivided into halfwords, in
5929 which case it is referred to by other names instead of |value|.) The other
5930 word is broken into subfields called |type|, |name_type|, and |link|.  The
5931 |type| field is a quarterword that specifies the variable's type, and
5932 |name_type| is a quarterword from which \MP\ can reconstruct the
5933 variable's name (sometimes by using the |link| field as well).  Thus, only
5934 1.25 words are actually devoted to the value itself; the other
5935 three-quarters of a word are overhead, but they aren't wasted because they
5936 allow \MP\ to deal with sparse arrays and to provide meaningful diagnostics.
5937
5938 In this section we shall be concerned only with the structural aspects of
5939 variables, not their values. Later parts of the program will change the
5940 |type| and |value| fields, but we shall treat those fields as black boxes
5941 whose contents should not be touched.
5942
5943 However, if the |type| field is |mp_structured|, there is no |value| field,
5944 and the second word is broken into two pointer fields called |attr_head|
5945 and |subscr_head|. Those fields point to additional nodes that
5946 contain structural information, as we shall see.
5947
5948 @d subscr_head_loc(A)   (A)+1 /* where |value|, |subscr_head| and |attr_head| are */
5949 @d attr_head(A)   info(subscr_head_loc((A))) /* pointer to attribute info */
5950 @d subscr_head(A)   link(subscr_head_loc((A))) /* pointer to subscript info */
5951 @d value_node_size 2 /* the number of words in a value node */
5952
5953 @ An attribute node is three words long. Two of these words contain |type|
5954 and |value| fields as described above, and the third word contains
5955 additional information:  There is an |attr_loc| field, which contains the
5956 hash address of the token that names this attribute; and there's also a
5957 |parent| field, which points to the value node of |mp_structured| type at the
5958 next higher level (i.e., at the level to which this attribute is
5959 subsidiary).  The |name_type| in an attribute node is `|attr|'.  The
5960 |link| field points to the next attribute with the same parent; these are
5961 arranged in increasing order, so that |attr_loc(link(p))>attr_loc(p)|. The
5962 final attribute node links to the constant |end_attr|, whose |attr_loc|
5963 field is greater than any legal hash address. The |attr_head| in the
5964 parent points to a node whose |name_type| is |mp_structured_root|; this
5965 node represents the null attribute, i.e., the variable that is relevant
5966 when no attributes are attached to the parent. The |attr_head| node is either
5967 a value node, a subscript node, or an attribute node, depending on what
5968 the parent would be if it were not structured; but the subscript and
5969 attribute fields are ignored, so it effectively contains only the data of
5970 a value node. The |link| field in this special node points to an attribute
5971 node whose |attr_loc| field is zero; the latter node represents a collective
5972 subscript `\.{[]}' attached to the parent, and its |link| field points to
5973 the first non-special attribute node (or to |end_attr| if there are none).
5974
5975 A subscript node likewise occupies three words, with |type| and |value| fields
5976 plus extra information; its |name_type| is |subscr|. In this case the
5977 third word is called the |subscript| field, which is a |scaled| integer.
5978 The |link| field points to the subscript node with the next larger
5979 subscript, if any; otherwise the |link| points to the attribute node
5980 for collective subscripts at this level. We have seen that the latter node
5981 contains an upward pointer, so that the parent can be deduced.
5982
5983 The |name_type| in a parent-less value node is |root|, and the |link|
5984 is the hash address of the token that names this value.
5985
5986 In other words, variables have a hierarchical structure that includes
5987 enough threads running around so that the program is able to move easily
5988 between siblings, parents, and children. An example should be helpful:
5989 (The reader is advised to draw a picture while reading the following
5990 description, since that will help to firm up the ideas.)
5991 Suppose that `\.x' and `\.{x.a}' and `\.{x[]b}' and `\.{x5}'
5992 and `\.{x20b}' have been mentioned in a user's program, where
5993 \.{x[]b} has been declared to be of \&{boolean} type. Let |h(x)|, |h(a)|,
5994 and |h(b)| be the hash addresses of \.x, \.a, and~\.b. Then
5995 |eq_type(h(x))=name| and |equiv(h(x))=p|, where |p|~is a two-word value
5996 node with |name_type(p)=root| and |link(p)=h(x)|. We have |type(p)=mp_structured|,
5997 |attr_head(p)=q|, and |subscr_head(p)=r|, where |q| points to a value
5998 node and |r| to a subscript node. (Are you still following this? Use
5999 a pencil to draw a diagram.) The lone variable `\.x' is represented by
6000 |type(q)| and |value(q)|; furthermore
6001 |name_type(q)=mp_structured_root| and |link(q)=q1|, where |q1| points
6002 to an attribute node representing `\.{x[]}'. Thus |name_type(q1)=attr|,
6003 |attr_loc(q1)=collective_subscript=0|, |parent(q1)=p|,
6004 |type(q1)=mp_structured|, |attr_head(q1)=qq|, and |subscr_head(q1)=qq1|;
6005 |qq| is a value node with |type(qq)=mp_numeric_type| (assuming that \.{x5} is
6006 numeric, because |qq| represents `\.{x[]}' with no further attributes),
6007 |name_type(qq)=mp_structured_root|, and
6008 |link(qq)=qq1|. (Now pay attention to the next part.) Node |qq1| is
6009 an attribute node representing `\.{x[][]}', which has never yet
6010 occurred; its |type| field is |undefined|, and its |value| field is
6011 undefined. We have |name_type(qq1)=attr|, |attr_loc(qq1)=collective_subscript|,
6012 |parent(qq1)=q1|, and |link(qq1)=qq2|. Since |qq2| represents
6013 `\.{x[]b}', |type(qq2)=mp_unknown_boolean|; also |attr_loc(qq2)=h(b)|,
6014 |parent(qq2)=q1|, |name_type(qq2)=attr|, |link(qq2)=end_attr|.
6015 (Maybe colored lines will help untangle your picture.)
6016  Node |r| is a subscript node with |type| and |value|
6017 representing `\.{x5}'; |name_type(r)=subscr|, |subscript(r)=5.0|,
6018 and |link(r)=r1| is another subscript node. To complete the picture,
6019 see if you can guess what |link(r1)| is; give up? It's~|q1|.
6020 Furthermore |subscript(r1)=20.0|, |name_type(r1)=subscr|,
6021 |type(r1)=mp_structured|, |attr_head(r1)=qqq|, |subscr_head(r1)=qqq1|,
6022 and we finish things off with three more nodes
6023 |qqq|, |qqq1|, and |qqq2| hung onto~|r1|. (Perhaps you should start again
6024 with a larger sheet of paper.) The value of variable \.{x20b}
6025 appears in node~|qqq2|, as you can well imagine.
6026
6027 If the example in the previous paragraph doesn't make things crystal
6028 clear, a glance at some of the simpler subroutines below will reveal how
6029 things work out in practice.
6030
6031 The only really unusual thing about these conventions is the use of
6032 collective subscript attributes. The idea is to avoid repeating a lot of
6033 type information when many elements of an array are identical macros
6034 (for which distinct values need not be stored) or when they don't have
6035 all of the possible attributes. Branches of the structure below collective
6036 subscript attributes do not carry actual values except for macro identifiers;
6037 branches of the structure below subscript nodes do not carry significant
6038 information in their collective subscript attributes.
6039
6040 @d attr_loc_loc(A) ((A)+2) /* where the |attr_loc| and |parent| fields are */
6041 @d attr_loc(A) info(attr_loc_loc((A))) /* hash address of this attribute */
6042 @d parent(A) link(attr_loc_loc((A))) /* pointer to |mp_structured| variable */
6043 @d subscript_loc(A) ((A)+2) /* where the |subscript| field lives */
6044 @d subscript(A) mp->mem[subscript_loc((A))].sc /* subscript of this variable */
6045 @d attr_node_size 3 /* the number of words in an attribute node */
6046 @d subscr_node_size 3 /* the number of words in a subscript node */
6047 @d collective_subscript 0 /* code for the attribute `\.{[]}' */
6048
6049 @<Initialize table...@>=
6050 attr_loc(end_attr)=hash_end+1; parent(end_attr)=null;
6051
6052 @ Variables of type \&{pair} will have values that point to four-word
6053 nodes containing two numeric values. The first of these values has
6054 |name_type=mp_x_part_sector| and the second has |name_type=mp_y_part_sector|;
6055 the |link| in the first points back to the node whose |value| points
6056 to this four-word node.
6057
6058 Variables of type \&{transform} are similar, but in this case their
6059 |value| points to a 12-word node containing six values, identified by
6060 |x_part_sector|, |y_part_sector|, |mp_xx_part_sector|, |mp_xy_part_sector|,
6061 |mp_yx_part_sector|, and |mp_yy_part_sector|.
6062 Finally, variables of type \&{color} have three values in six words
6063 identified by |mp_red_part_sector|, |mp_green_part_sector|, and |mp_blue_part_sector|.
6064
6065 When an entire structured variable is saved, the |root| indication
6066 is temporarily replaced by |saved_root|.
6067
6068 Some variables have no name; they just are used for temporary storage
6069 while expressions are being evaluated. We call them {\sl capsules}.
6070
6071 @d x_part_loc(A) (A) /* where the \&{xpart} is found in a pair or transform node */
6072 @d y_part_loc(A) ((A)+2) /* where the \&{ypart} is found in a pair or transform node */
6073 @d xx_part_loc(A) ((A)+4) /* where the \&{xxpart} is found in a transform node */
6074 @d xy_part_loc(A) ((A)+6) /* where the \&{xypart} is found in a transform node */
6075 @d yx_part_loc(A) ((A)+8) /* where the \&{yxpart} is found in a transform node */
6076 @d yy_part_loc(A) ((A)+10) /* where the \&{yypart} is found in a transform node */
6077 @d red_part_loc(A) (A) /* where the \&{redpart} is found in a color node */
6078 @d green_part_loc(A) ((A)+2) /* where the \&{greenpart} is found in a color node */
6079 @d blue_part_loc(A) ((A)+4) /* where the \&{bluepart} is found in a color node */
6080 @d cyan_part_loc(A) (A) /* where the \&{cyanpart} is found in a color node */
6081 @d magenta_part_loc(A) ((A)+2) /* where the \&{magentapart} is found in a color node */
6082 @d yellow_part_loc(A) ((A)+4) /* where the \&{yellowpart} is found in a color node */
6083 @d black_part_loc(A) ((A)+6) /* where the \&{blackpart} is found in a color node */
6084 @d grey_part_loc(A) (A) /* where the \&{greypart} is found in a color node */
6085 @#
6086 @d pair_node_size 4 /* the number of words in a pair node */
6087 @d transform_node_size 12 /* the number of words in a transform node */
6088 @d color_node_size 6 /* the number of words in a color node */
6089 @d cmykcolor_node_size 8 /* the number of words in a color node */
6090
6091 @<Glob...@>=
6092 small_number big_node_size[mp_pair_type+1];
6093 small_number sector0[mp_pair_type+1];
6094 small_number sector_offset[mp_black_part_sector+1];
6095
6096 @ The |sector0| array gives for each big node type, |name_type| values
6097 for its first subfield; the |sector_offset| array gives for each
6098 |name_type| value, the offset from the first subfield in words;
6099 and the |big_node_size| array gives the size in words for each type of
6100 big node.
6101
6102 @<Set init...@>=
6103 mp->big_node_size[mp_transform_type]=transform_node_size;
6104 mp->big_node_size[mp_pair_type]=pair_node_size;
6105 mp->big_node_size[mp_color_type]=color_node_size;
6106 mp->big_node_size[mp_cmykcolor_type]=cmykcolor_node_size;
6107 mp->sector0[mp_transform_type]=mp_x_part_sector;
6108 mp->sector0[mp_pair_type]=mp_x_part_sector;
6109 mp->sector0[mp_color_type]=mp_red_part_sector;
6110 mp->sector0[mp_cmykcolor_type]=mp_cyan_part_sector;
6111 for (k=mp_x_part_sector;k<= mp_yy_part_sector;k++ ) {
6112   mp->sector_offset[k]=2*(k-mp_x_part_sector);
6113 }
6114 for (k=mp_red_part_sector;k<= mp_blue_part_sector ; k++) {
6115   mp->sector_offset[k]=2*(k-mp_red_part_sector);
6116 }
6117 for (k=mp_cyan_part_sector;k<= mp_black_part_sector;k++ ) {
6118   mp->sector_offset[k]=2*(k-mp_cyan_part_sector);
6119 }
6120
6121 @ If |type(p)=mp_pair_type| or |mp_transform_type| and if |value(p)=null|, the
6122 procedure call |init_big_node(p)| will allocate a pair or transform node
6123 for~|p|.  The individual parts of such nodes are initially of type
6124 |mp_independent|.
6125
6126 @c 
6127 void mp_init_big_node (MP mp,pointer p) {
6128   pointer q; /* the new node */
6129   small_number s; /* its size */
6130   s=mp->big_node_size[type(p)]; q=mp_get_node(mp, s);
6131   do {  
6132     s=s-2; 
6133     @<Make variable |q+s| newly independent@>;
6134     name_type(q+s)=halfp(s)+mp->sector0[type(p)]; 
6135     link(q+s)=null;
6136   } while (s!=0);
6137   link(q)=p; value(p)=q;
6138 }
6139
6140 @ The |id_transform| function creates a capsule for the
6141 identity transformation.
6142
6143 @c 
6144 pointer mp_id_transform (MP mp) {
6145   pointer p,q,r; /* list manipulation registers */
6146   p=mp_get_node(mp, value_node_size); type(p)=mp_transform_type;
6147   name_type(p)=mp_capsule; value(p)=null; mp_init_big_node(mp, p); q=value(p);
6148   r=q+transform_node_size;
6149   do {  
6150     r=r-2;
6151     type(r)=mp_known; value(r)=0;
6152   } while (r!=q);
6153   value(xx_part_loc(q))=unity; 
6154   value(yy_part_loc(q))=unity;
6155   return p;
6156 }
6157
6158 @ Tokens are of type |tag_token| when they first appear, but they point
6159 to |null| until they are first used as the root of a variable.
6160 The following subroutine establishes the root node on such grand occasions.
6161
6162 @c 
6163 void mp_new_root (MP mp,pointer x) {
6164   pointer p; /* the new node */
6165   p=mp_get_node(mp, value_node_size); type(p)=undefined; name_type(p)=mp_root;
6166   link(p)=x; equiv(x)=p;
6167 }
6168
6169 @ These conventions for variable representation are illustrated by the
6170 |print_variable_name| routine, which displays the full name of a
6171 variable given only a pointer to its two-word value packet.
6172
6173 @<Declarations@>=
6174 void mp_print_variable_name (MP mp, pointer p);
6175
6176 @ @c 
6177 void mp_print_variable_name (MP mp, pointer p) {
6178   pointer q; /* a token list that will name the variable's suffix */
6179   pointer r; /* temporary for token list creation */
6180   while ( name_type(p)>=mp_x_part_sector ) {
6181     @<Preface the output with a part specifier; |return| in the
6182       case of a capsule@>;
6183   }
6184   q=null;
6185   while ( name_type(p)>mp_saved_root ) {
6186     @<Ascend one level, pushing a token onto list |q|
6187      and replacing |p| by its parent@>;
6188   }
6189   r=mp_get_avail(mp); info(r)=link(p); link(r)=q;
6190   if ( name_type(p)==mp_saved_root ) mp_print(mp, "(SAVED)");
6191 @.SAVED@>
6192   mp_show_token_list(mp, r,null,el_gordo,mp->tally); 
6193   mp_flush_token_list(mp, r);
6194 }
6195
6196 @ @<Ascend one level, pushing a token onto list |q|...@>=
6197
6198   if ( name_type(p)==mp_subscr ) { 
6199     r=mp_new_num_tok(mp, subscript(p));
6200     do {  
6201       p=link(p);
6202     } while (name_type(p)!=mp_attr);
6203   } else if ( name_type(p)==mp_structured_root ) {
6204     p=link(p); goto FOUND;
6205   } else { 
6206     if ( name_type(p)!=mp_attr ) mp_confusion(mp, "var");
6207 @:this can't happen var}{\quad var@>
6208     r=mp_get_avail(mp); info(r)=attr_loc(p);
6209   }
6210   link(r)=q; q=r;
6211 FOUND:  
6212   p=parent(p);
6213 }
6214
6215 @ @<Preface the output with a part specifier...@>=
6216 { switch (name_type(p)) {
6217   case mp_x_part_sector: mp_print_char(mp, 'x'); break;
6218   case mp_y_part_sector: mp_print_char(mp, 'y'); break;
6219   case mp_xx_part_sector: mp_print(mp, "xx"); break;
6220   case mp_xy_part_sector: mp_print(mp, "xy"); break;
6221   case mp_yx_part_sector: mp_print(mp, "yx"); break;
6222   case mp_yy_part_sector: mp_print(mp, "yy"); break;
6223   case mp_red_part_sector: mp_print(mp, "red"); break;
6224   case mp_green_part_sector: mp_print(mp, "green"); break;
6225   case mp_blue_part_sector: mp_print(mp, "blue"); break;
6226   case mp_cyan_part_sector: mp_print(mp, "cyan"); break;
6227   case mp_magenta_part_sector: mp_print(mp, "magenta"); break;
6228   case mp_yellow_part_sector: mp_print(mp, "yellow"); break;
6229   case mp_black_part_sector: mp_print(mp, "black"); break;
6230   case mp_grey_part_sector: mp_print(mp, "grey"); break;
6231   case mp_capsule: 
6232     mp_print(mp, "%CAPSULE"); mp_print_int(mp, p-null); return;
6233     break;
6234 @.CAPSULE@>
6235   } /* there are no other cases */
6236   mp_print(mp, "part "); 
6237   p=link(p-mp->sector_offset[name_type(p)]);
6238 }
6239
6240 @ The |interesting| function returns |true| if a given variable is not
6241 in a capsule, or if the user wants to trace capsules.
6242
6243 @c 
6244 boolean mp_interesting (MP mp,pointer p) {
6245   small_number t; /* a |name_type| */
6246   if ( mp->internal[tracing_capsules]>0 ) {
6247     return true;
6248   } else { 
6249     t=name_type(p);
6250     if ( t>=mp_x_part_sector ) if ( t!=mp_capsule )
6251       t=name_type(link(p-mp->sector_offset[t]));
6252     return (t!=mp_capsule);
6253   }
6254 }
6255
6256 @ Now here is a subroutine that converts an unstructured type into an
6257 equivalent structured type, by inserting a |mp_structured| node that is
6258 capable of growing. This operation is done only when |name_type(p)=root|,
6259 |subscr|, or |attr|.
6260
6261 The procedure returns a pointer to the new node that has taken node~|p|'s
6262 place in the structure. Node~|p| itself does not move, nor are its
6263 |value| or |type| fields changed in any way.
6264
6265 @c 
6266 pointer mp_new_structure (MP mp,pointer p) {
6267   pointer q,r=0; /* list manipulation registers */
6268   switch (name_type(p)) {
6269   case mp_root: 
6270     q=link(p); r=mp_get_node(mp, value_node_size); equiv(q)=r;
6271     break;
6272   case mp_subscr: 
6273     @<Link a new subscript node |r| in place of node |p|@>;
6274     break;
6275   case mp_attr: 
6276     @<Link a new attribute node |r| in place of node |p|@>;
6277     break;
6278   default: 
6279     mp_confusion(mp, "struct");
6280 @:this can't happen struct}{\quad struct@>
6281     break;
6282   }
6283   link(r)=link(p); type(r)=mp_structured; name_type(r)=name_type(p);
6284   attr_head(r)=p; name_type(p)=mp_structured_root;
6285   q=mp_get_node(mp, attr_node_size); link(p)=q; subscr_head(r)=q;
6286   parent(q)=r; type(q)=undefined; name_type(q)=mp_attr; link(q)=end_attr;
6287   attr_loc(q)=collective_subscript; 
6288   return r;
6289 };
6290
6291 @ @<Link a new subscript node |r| in place of node |p|@>=
6292
6293   q=p;
6294   do {  
6295     q=link(q);
6296   } while (name_type(q)!=mp_attr);
6297   q=parent(q); r=subscr_head_loc(q); /* |link(r)=subscr_head(q)| */
6298   do {  
6299     q=r; r=link(r);
6300   } while (r!=p);
6301   r=mp_get_node(mp, subscr_node_size);
6302   link(q)=r; subscript(r)=subscript(p);
6303 }
6304
6305 @ If the attribute is |collective_subscript|, there are two pointers to
6306 node~|p|, so we must change both of them.
6307
6308 @<Link a new attribute node |r| in place of node |p|@>=
6309
6310   q=parent(p); r=attr_head(q);
6311   do {  
6312     q=r; r=link(r);
6313   } while (r!=p);
6314   r=mp_get_node(mp, attr_node_size); link(q)=r;
6315   mp->mem[attr_loc_loc(r)]=mp->mem[attr_loc_loc(p)]; /* copy |attr_loc| and |parent| */
6316   if ( attr_loc(p)==collective_subscript ) { 
6317     q=subscr_head_loc(parent(p));
6318     while ( link(q)!=p ) q=link(q);
6319     link(q)=r;
6320   }
6321 }
6322
6323 @ The |find_variable| routine is given a pointer~|t| to a nonempty token
6324 list of suffixes; it returns a pointer to the corresponding two-word
6325 value. For example, if |t| points to token \.x followed by a numeric
6326 token containing the value~7, |find_variable| finds where the value of
6327 \.{x7} is stored in memory. This may seem a simple task, and it
6328 usually is, except when \.{x7} has never been referenced before.
6329 Indeed, \.x may never have even been subscripted before; complexities
6330 arise with respect to updating the collective subscript information.
6331
6332 If a macro type is detected anywhere along path~|t|, or if the first
6333 item on |t| isn't a |tag_token|, the value |null| is returned.
6334 Otherwise |p| will be a non-null pointer to a node such that
6335 |undefined<type(p)<mp_structured|.
6336
6337 @d abort_find { return null; }
6338
6339 @c 
6340 pointer mp_find_variable (MP mp,pointer t) {
6341   pointer p,q,r,s; /* nodes in the ``value'' line */
6342   pointer pp,qq,rr,ss; /* nodes in the ``collective'' line */
6343   integer n; /* subscript or attribute */
6344   memory_word save_word; /* temporary storage for a word of |mem| */
6345 @^inner loop@>
6346   p=info(t); t=link(t);
6347   if ( (eq_type(p) % outer_tag) != tag_token ) abort_find;
6348   if ( equiv(p)==null ) mp_new_root(mp, p);
6349   p=equiv(p); pp=p;
6350   while ( t!=null ) { 
6351     @<Make sure that both nodes |p| and |pp| are of |mp_structured| type@>;
6352     if ( t<mp->hi_mem_min ) {
6353       @<Descend one level for the subscript |value(t)|@>
6354     } else {
6355       @<Descend one level for the attribute |info(t)|@>;
6356     }
6357     t=link(t);
6358   }
6359   if ( type(pp)>=mp_structured ) {
6360     if ( type(pp)==mp_structured ) pp=attr_head(pp); else abort_find;
6361   }
6362   if ( type(p)==mp_structured ) p=attr_head(p);
6363   if ( type(p)==undefined ) { 
6364     if ( type(pp)==undefined ) { type(pp)=mp_numeric_type; value(pp)=null; };
6365     type(p)=type(pp); value(p)=null;
6366   };
6367   return p;
6368 }
6369
6370 @ Although |pp| and |p| begin together, they diverge when a subscript occurs;
6371 |pp|~stays in the collective line while |p|~goes through actual subscript
6372 values.
6373
6374 @<Make sure that both nodes |p| and |pp|...@>=
6375 if ( type(pp)!=mp_structured ) { 
6376   if ( type(pp)>mp_structured ) abort_find;
6377   ss=mp_new_structure(mp, pp);
6378   if ( p==pp ) p=ss;
6379   pp=ss;
6380 }; /* now |type(pp)=mp_structured| */
6381 if ( type(p)!=mp_structured ) /* it cannot be |>mp_structured| */
6382   p=mp_new_structure(mp, p) /* now |type(p)=mp_structured| */
6383
6384 @ We want this part of the program to be reasonably fast, in case there are
6385 @^inner loop@>
6386 lots of subscripts at the same level of the data structure. Therefore
6387 we store an ``infinite'' value in the word that appears at the end of the
6388 subscript list, even though that word isn't part of a subscript node.
6389
6390 @<Descend one level for the subscript |value(t)|@>=
6391
6392   n=value(t);
6393   pp=link(attr_head(pp)); /* now |attr_loc(pp)=collective_subscript| */
6394   q=link(attr_head(p)); save_word=mp->mem[subscript_loc(q)];
6395   subscript(q)=el_gordo; s=subscr_head_loc(p); /* |link(s)=subscr_head(p)| */
6396   do {  
6397     r=s; s=link(s);
6398   } while (n>subscript(s));
6399   if ( n==subscript(s) ) {
6400     p=s;
6401   } else { 
6402     p=mp_get_node(mp, subscr_node_size); link(r)=p; link(p)=s;
6403     subscript(p)=n; name_type(p)=mp_subscr; type(p)=undefined;
6404   }
6405   mp->mem[subscript_loc(q)]=save_word;
6406 }
6407
6408 @ @<Descend one level for the attribute |info(t)|@>=
6409
6410   n=info(t);
6411   ss=attr_head(pp);
6412   do {  
6413     rr=ss; ss=link(ss);
6414   } while (n>attr_loc(ss));
6415   if ( n<attr_loc(ss) ) { 
6416     qq=mp_get_node(mp, attr_node_size); link(rr)=qq; link(qq)=ss;
6417     attr_loc(qq)=n; name_type(qq)=mp_attr; type(qq)=undefined;
6418     parent(qq)=pp; ss=qq;
6419   }
6420   if ( p==pp ) { 
6421     p=ss; pp=ss;
6422   } else { 
6423     pp=ss; s=attr_head(p);
6424     do {  
6425       r=s; s=link(s);
6426     } while (n>attr_loc(s));
6427     if ( n==attr_loc(s) ) {
6428       p=s;
6429     } else { 
6430       q=mp_get_node(mp, attr_node_size); link(r)=q; link(q)=s;
6431       attr_loc(q)=n; name_type(q)=mp_attr; type(q)=undefined;
6432       parent(q)=p; p=q;
6433     }
6434   }
6435 }
6436
6437 @ Variables lose their former values when they appear in a type declaration,
6438 or when they are defined to be macros or \&{let} equal to something else.
6439 A subroutine will be defined later that recycles the storage associated
6440 with any particular |type| or |value|; our goal now is to study a higher
6441 level process called |flush_variable|, which selectively frees parts of a
6442 variable structure.
6443
6444 This routine has some complexity because of examples such as
6445 `\hbox{\tt numeric x[]a[]b}'
6446 which recycles all variables of the form \.{x[i]a[j]b} (and no others), while
6447 `\hbox{\tt vardef x[]a[]=...}'
6448 discards all variables of the form \.{x[i]a[j]} followed by an arbitrary
6449 suffix, except for the collective node \.{x[]a[]} itself. The obvious way
6450 to handle such examples is to use recursion; so that's what we~do.
6451 @^recursion@>
6452
6453 Parameter |p| points to the root information of the variable;
6454 parameter |t| points to a list of one-word nodes that represent
6455 suffixes, with |info=collective_subscript| for subscripts.
6456
6457 @<Declarations@>=
6458 @<Declare subroutines for printing expressions@>
6459 @<Declare basic dependency-list subroutines@>
6460 @<Declare the recycling subroutines@>
6461 void mp_flush_cur_exp (MP mp,scaled v) ;
6462 @<Declare the procedure called |flush_below_variable|@>
6463
6464 @ @c 
6465 void mp_flush_variable (MP mp,pointer p, pointer t, boolean discard_suffixes) {
6466   pointer q,r; /* list manipulation */
6467   halfword n; /* attribute to match */
6468   while ( t!=null ) { 
6469     if ( type(p)!=mp_structured ) return;
6470     n=info(t); t=link(t);
6471     if ( n==collective_subscript ) { 
6472       r=subscr_head_loc(p); q=link(r); /* |q=subscr_head(p)| */
6473       while ( name_type(q)==mp_subscr ){ 
6474         mp_flush_variable(mp, q,t,discard_suffixes);
6475         if ( t==null ) {
6476           if ( type(q)==mp_structured ) r=q;
6477           else  { link(r)=link(q); mp_free_node(mp, q,subscr_node_size);   }
6478         } else {
6479           r=q;
6480         }
6481         q=link(r);
6482       }
6483     }
6484     p=attr_head(p);
6485     do {  
6486       r=p; p=link(p);
6487     } while (attr_loc(p)<n);
6488     if ( attr_loc(p)!=n ) return;
6489   }
6490   if ( discard_suffixes ) {
6491     mp_flush_below_variable(mp, p);
6492   } else { 
6493     if ( type(p)==mp_structured ) p=attr_head(p);
6494     mp_recycle_value(mp, p);
6495   }
6496 }
6497
6498 @ The next procedure is simpler; it wipes out everything but |p| itself,
6499 which becomes undefined.
6500
6501 @<Declare the procedure called |flush_below_variable|@>=
6502 void mp_flush_below_variable (MP mp, pointer p);
6503
6504 @ @c
6505 void mp_flush_below_variable (MP mp,pointer p) {
6506    pointer q,r; /* list manipulation registers */
6507   if ( type(p)!=mp_structured ) {
6508     mp_recycle_value(mp, p); /* this sets |type(p)=undefined| */
6509   } else { 
6510     q=subscr_head(p);
6511     while ( name_type(q)==mp_subscr ) { 
6512       mp_flush_below_variable(mp, q); r=q; q=link(q);
6513       mp_free_node(mp, r,subscr_node_size);
6514     }
6515     r=attr_head(p); q=link(r); mp_recycle_value(mp, r);
6516     if ( name_type(p)<=mp_saved_root ) mp_free_node(mp, r,value_node_size);
6517     else mp_free_node(mp, r,subscr_node_size);
6518     /* we assume that |subscr_node_size=attr_node_size| */
6519     do {  
6520       mp_flush_below_variable(mp, q); r=q; q=link(q); mp_free_node(mp, r,attr_node_size);
6521     } while (q!=end_attr);
6522     type(p)=undefined;
6523   }
6524 }
6525
6526 @ Just before assigning a new value to a variable, we will recycle the
6527 old value and make the old value undefined. The |und_type| routine
6528 determines what type of undefined value should be given, based on
6529 the current type before recycling.
6530
6531 @c 
6532 small_number mp_und_type (MP mp,pointer p) { 
6533   switch (type(p)) {
6534   case undefined: case mp_vacuous:
6535     return undefined;
6536   case mp_boolean_type: case mp_unknown_boolean:
6537     return mp_unknown_boolean;
6538   case mp_string_type: case mp_unknown_string:
6539     return mp_unknown_string;
6540   case mp_pen_type: case mp_unknown_pen:
6541     return mp_unknown_pen;
6542   case mp_path_type: case mp_unknown_path:
6543     return mp_unknown_path;
6544   case mp_picture_type: case mp_unknown_picture:
6545     return mp_unknown_picture;
6546   case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
6547   case mp_pair_type: case mp_numeric_type: 
6548     return type(p);
6549   case mp_known: case mp_dependent: case mp_proto_dependent: case mp_independent:
6550     return mp_numeric_type;
6551   } /* there are no other cases */
6552   return 0;
6553 }
6554
6555 @ The |clear_symbol| routine is used when we want to redefine the equivalent
6556 of a symbolic token. It must remove any variable structure or macro
6557 definition that is currently attached to that symbol. If the |saving|
6558 parameter is true, a subsidiary structure is saved instead of destroyed.
6559
6560 @c 
6561 void mp_clear_symbol (MP mp,pointer p, boolean saving) {
6562   pointer q; /* |equiv(p)| */
6563   q=equiv(p);
6564   switch (eq_type(p) % outer_tag)  {
6565   case defined_macro:
6566   case secondary_primary_macro:
6567   case tertiary_secondary_macro:
6568   case expression_tertiary_macro: 
6569     if ( ! saving ) mp_delete_mac_ref(mp, q);
6570     break;
6571   case tag_token:
6572     if ( q!=null ) {
6573       if ( saving ) {
6574         name_type(q)=mp_saved_root;
6575       } else { 
6576         mp_flush_below_variable(mp, q); mp_free_node(mp,q,value_node_size); 
6577       }
6578     }
6579     break;
6580   default:
6581     break;
6582   }
6583   mp->eqtb[p]=mp->eqtb[frozen_undefined];
6584 };
6585
6586 @* \[16] Saving and restoring equivalents.
6587 The nested structure given by \&{begingroup} and \&{endgroup}
6588 allows |eqtb| entries to be saved and restored, so that temporary changes
6589 can be made without difficulty.  When the user requests a current value to
6590 be saved, \MP\ puts that value into its ``save stack.'' An appearance of
6591 \&{endgroup} ultimately causes the old values to be removed from the save
6592 stack and put back in their former places.
6593
6594 The save stack is a linked list containing three kinds of entries,
6595 distinguished by their |info| fields. If |p| points to a saved item,
6596 then
6597
6598 \smallskip\hang
6599 |info(p)=0| stands for a group boundary; each \&{begingroup} contributes
6600 such an item to the save stack and each \&{endgroup} cuts back the stack
6601 until the most recent such entry has been removed.
6602
6603 \smallskip\hang
6604 |info(p)=q|, where |1<=q<=hash_end|, means that |mem[p+1]| holds the former
6605 contents of |eqtb[q]|. Such save stack entries are generated by \&{save}
6606 commands or suitable \&{interim} commands.
6607
6608 \smallskip\hang
6609 |info(p)=hash_end+q|, where |q>0|, means that |value(p)| is a |scaled|
6610 integer to be restored to internal parameter number~|q|. Such entries
6611 are generated by \&{interim} commands.
6612
6613 \smallskip\noindent
6614 The global variable |save_ptr| points to the top item on the save stack.
6615
6616 @d save_node_size 2 /* number of words per non-boundary save-stack node */
6617 @d saved_equiv(A) mp->mem[(A)+1].hh /* where an |eqtb| entry gets saved */
6618 @d save_boundary_item(A) { (A)=mp_get_avail(mp); info((A))=0;
6619   link((A))=mp->save_ptr; mp->save_ptr=(A);
6620   }
6621
6622 @<Glob...@>=
6623 pointer save_ptr; /* the most recently saved item */
6624
6625 @ @<Set init...@>=mp->save_ptr=null;
6626
6627 @ The |save_variable| routine is given a hash address |q|; it salts this
6628 address in the save stack, together with its current equivalent,
6629 then makes token~|q| behave as though it were brand new.
6630
6631 Nothing is stacked when |save_ptr=null|, however; there's no way to remove
6632 things from the stack when the program is not inside a group, so there's
6633 no point in wasting the space.
6634
6635 @c void mp_save_variable (MP mp,pointer q) {
6636   pointer p; /* temporary register */
6637   if ( mp->save_ptr!=null ){ 
6638     p=mp_get_node(mp, save_node_size); info(p)=q; link(p)=mp->save_ptr;
6639     saved_equiv(p)=mp->eqtb[q]; mp->save_ptr=p;
6640   }
6641   mp_clear_symbol(mp, q,(mp->save_ptr!=null));
6642 }
6643
6644 @ Similarly, |save_internal| is given the location |q| of an internal
6645 quantity like |tracing_pens|. It creates a save stack entry of the
6646 third kind.
6647
6648 @c void mp_save_internal (MP mp,halfword q) {
6649   pointer p; /* new item for the save stack */
6650   if ( mp->save_ptr!=null ){ 
6651      p=mp_get_node(mp, save_node_size); info(p)=hash_end+q;
6652     link(p)=mp->save_ptr; value(p)=mp->internal[q]; mp->save_ptr=p;
6653   }
6654 }
6655
6656 @ At the end of a group, the |unsave| routine restores all of the saved
6657 equivalents in reverse order. This routine will be called only when there
6658 is at least one boundary item on the save stack.
6659
6660 @c 
6661 void mp_unsave (MP mp) {
6662   pointer q; /* index to saved item */
6663   pointer p; /* temporary register */
6664   while ( info(mp->save_ptr)!=0 ) {
6665     q=info(mp->save_ptr);
6666     if ( q>hash_end ) {
6667       if ( mp->internal[tracing_restores]>0 ) {
6668         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6669         mp_print(mp, mp->int_name[q-(hash_end)]); mp_print_char(mp, '=');
6670         mp_print_scaled(mp, value(mp->save_ptr)); mp_print_char(mp, '}');
6671         mp_end_diagnostic(mp, false);
6672       }
6673       mp->internal[q-(hash_end)]=value(mp->save_ptr);
6674     } else { 
6675       if ( mp->internal[tracing_restores]>0 ) {
6676         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6677         mp_print_text(q); mp_print_char(mp, '}');
6678         mp_end_diagnostic(mp, false);
6679       }
6680       mp_clear_symbol(mp, q,false);
6681       mp->eqtb[q]=saved_equiv(mp->save_ptr);
6682       if ( eq_type(q) % outer_tag==tag_token ) {
6683         p=equiv(q);
6684         if ( p!=null ) name_type(p)=mp_root;
6685       }
6686     }
6687     p=link(mp->save_ptr); 
6688     mp_free_node(mp, mp->save_ptr,save_node_size); mp->save_ptr=p;
6689   }
6690   p=link(mp->save_ptr); free_avail(mp->save_ptr); mp->save_ptr=p;
6691 }
6692
6693 @* \[17] Data structures for paths.
6694 When a \MP\ user specifies a path, \MP\ will create a list of knots
6695 and control points for the associated cubic spline curves. If the
6696 knots are $z_0$, $z_1$, \dots, $z_n$, there are control points
6697 $z_k^+$ and $z_{k+1}^-$ such that the cubic splines between knots
6698 $z_k$ and $z_{k+1}$ are defined by B\'ezier's formula
6699 @:Bezier}{B\'ezier, Pierre Etienne@>
6700 $$\eqalign{z(t)&=B(z_k,z_k^+,z_{k+1}^-,z_{k+1};t)\cr
6701 &=(1-t)^3z_k+3(1-t)^2tz_k^++3(1-t)t^2z_{k+1}^-+t^3z_{k+1}\cr}$$
6702 for |0<=t<=1|.
6703
6704 There is a 8-word node for each knot $z_k$, containing one word of
6705 control information and six words for the |x| and |y| coordinates of
6706 $z_k^-$ and $z_k$ and~$z_k^+$. The control information appears in the
6707 |left_type| and |right_type| fields, which each occupy a quarter of
6708 the first word in the node; they specify properties of the curve as it
6709 enters and leaves the knot. There's also a halfword |link| field,
6710 which points to the following knot, and a final supplementary word (of
6711 which only a quarter is used).
6712
6713 If the path is a closed contour, knots 0 and |n| are identical;
6714 i.e., the |link| in knot |n-1| points to knot~0. But if the path
6715 is not closed, the |left_type| of knot~0 and the |right_type| of knot~|n|
6716 are equal to |endpoint|. In the latter case the |link| in knot~|n| points
6717 to knot~0, and the control points $z_0^-$ and $z_n^+$ are not used.
6718
6719 @d left_type(A)   mp->mem[(A)].hh.b0 /* characterizes the path entering this knot */
6720 @d right_type(A)   mp->mem[(A)].hh.b1 /* characterizes the path leaving this knot */
6721 @d endpoint 0 /* |left_type| at path beginning and |right_type| at path end */
6722 @d x_coord(A)   mp->mem[(A)+1].sc /* the |x| coordinate of this knot */
6723 @d y_coord(A)   mp->mem[(A)+2].sc /* the |y| coordinate of this knot */
6724 @d left_x(A)   mp->mem[(A)+3].sc /* the |x| coordinate of previous control point */
6725 @d left_y(A)   mp->mem[(A)+4].sc /* the |y| coordinate of previous control point */
6726 @d right_x(A)   mp->mem[(A)+5].sc /* the |x| coordinate of next control point */
6727 @d right_y(A)   mp->mem[(A)+6].sc /* the |y| coordinate of next control point */
6728 @d x_loc(A)   ((A)+1) /* where the |x| coordinate is stored in a knot */
6729 @d y_loc(A)   ((A)+2) /* where the |y| coordinate is stored in a knot */
6730 @d knot_coord(A)   mp->mem[(A)].sc /* |x| or |y| coordinate given |x_loc| or |y_loc| */
6731 @d left_coord(A)   mp->mem[(A)+2].sc
6732   /* coordinate of previous control point given |x_loc| or |y_loc| */
6733 @d right_coord(A)   mp->mem[(A)+4].sc
6734   /* coordinate of next control point given |x_loc| or |y_loc| */
6735 @d knot_node_size 8 /* number of words in a knot node */
6736
6737 @ Before the B\'ezier control points have been calculated, the memory
6738 space they will ultimately occupy is taken up by information that can be
6739 used to compute them. There are four cases:
6740
6741 \yskip
6742 \textindent{$\bullet$} If |right_type=open|, the curve should leave
6743 the knot in the same direction it entered; \MP\ will figure out a
6744 suitable direction.
6745
6746 \yskip
6747 \textindent{$\bullet$} If |right_type=curl|, the curve should leave the
6748 knot in a direction depending on the angle at which it enters the next
6749 knot and on the curl parameter stored in |right_curl|.
6750
6751 \yskip
6752 \textindent{$\bullet$} If |right_type=given|, the curve should leave the
6753 knot in a nonzero direction stored as an |angle| in |right_given|.
6754
6755 \yskip
6756 \textindent{$\bullet$} If |right_type=explicit|, the B\'ezier control
6757 point for leaving this knot has already been computed; it is in the
6758 |right_x| and |right_y| fields.
6759
6760 \yskip\noindent
6761 The rules for |left_type| are similar, but they refer to the curve entering
6762 the knot, and to \\{left} fields instead of \\{right} fields.
6763
6764 Non-|explicit| control points will be chosen based on ``tension'' parameters
6765 in the |left_tension| and |right_tension| fields. The
6766 `\&{atleast}' option is represented by negative tension values.
6767 @:at_least_}{\&{atleast} primitive@>
6768
6769 For example, the \MP\ path specification
6770 $$\.{z0..z1..tension atleast 1..\{curl 2\}z2..z3\{-1,-2\}..tension
6771   3 and 4..p},$$
6772 where \.p is the path `\.{z4..controls z45 and z54..z5}', will be represented
6773 by the six knots
6774 \def\lodash{\hbox to 1.1em{\thinspace\hrulefill\thinspace}}
6775 $$\vbox{\halign{#\hfil&&\qquad#\hfil\cr
6776 |left_type|&\\{left} info&|x_coord,y_coord|&|right_type|&\\{right} info\cr
6777 \noalign{\yskip}
6778 |endpoint|&\lodash$,\,$\lodash&$x_0,y_0$&|curl|&$1.0,1.0$\cr
6779 |open|&\lodash$,1.0$&$x_1,y_1$&|open|&\lodash$,-1.0$\cr
6780 |curl|&$2.0,-1.0$&$x_2,y_2$&|curl|&$2.0,1.0$\cr
6781 |given|&$d,1.0$&$x_3,y_3$&|given|&$d,3.0$\cr
6782 |open|&\lodash$,4.0$&$x_4,y_4$&|explicit|&$x_{45},y_{45}$\cr
6783 |explicit|&$x_{54},y_{54}$&$x_5,y_5$&|endpoint|&\lodash$,\,$\lodash\cr}}$$
6784 Here |d| is the |angle| obtained by calling |n_arg(-unity,-two)|.
6785 Of course, this example is more complicated than anything a normal user
6786 would ever write.
6787
6788 These types must satisfy certain restrictions because of the form of \MP's
6789 path syntax:
6790 (i)~|open| type never appears in the same node together with |endpoint|,
6791 |given|, or |curl|.
6792 (ii)~The |right_type| of a node is |explicit| if and only if the
6793 |left_type| of the following node is |explicit|.
6794 (iii)~|endpoint| types occur only at the ends, as mentioned above.
6795
6796 @d left_curl left_x /* curl information when entering this knot */
6797 @d left_given left_x /* given direction when entering this knot */
6798 @d left_tension left_y /* tension information when entering this knot */
6799 @d right_curl right_x /* curl information when leaving this knot */
6800 @d right_given right_x /* given direction when leaving this knot */
6801 @d right_tension right_y /* tension information when leaving this knot */
6802 @d explicit 1 /* |left_type| or |right_type| when control points are known */
6803 @d given 2 /* |left_type| or |right_type| when a direction is given */
6804 @d curl 3 /* |left_type| or |right_type| when a curl is desired */
6805 @d open 4 /* |left_type| or |right_type| when \MP\ should choose the direction */
6806
6807 @ Knots can be user-supplied, or they can be created by program code,
6808 like the |split_cubic| function, or |copy_path|. The distinction is
6809 needed for the cleanup routine that runs after |split_cubic|, because
6810 it should only delete knots it has previously inserted, and never
6811 anything that was user-supplied. In order to be able to differentiate
6812 one knot from another, we will set |originator(p):=metapost_user| when
6813 it appeared in the actual metapost program, and
6814 |originator(p):=program_code| in all other cases.
6815
6816 @d originator(A)   mp->mem[(A)+7].hh.b0 /* the creator of this knot */
6817 @d program_code 0 /* not created by a user */
6818 @d metapost_user 1 /* created by a user */
6819
6820 @ Here is a routine that prints a given knot list
6821 in symbolic form. It illustrates the conventions discussed above,
6822 and checks for anomalies that might arise while \MP\ is being debugged.
6823
6824 @<Declare subroutines for printing expressions@>=
6825 void mp_pr_path (MP mp,pointer h);
6826
6827 @ @c
6828 void mp_pr_path (MP mp,pointer h) {
6829   pointer p,q; /* for list traversal */
6830   p=h;
6831   do {  
6832     q=link(p);
6833     if ( (p==null)||(q==null) ) { 
6834       mp_print_nl(mp, "???"); return; /* this won't happen */
6835 @.???@>
6836     }
6837     @<Print information for adjacent knots |p| and |q|@>;
6838   DONE1:
6839     p=q;
6840     if ( (p!=h)||(left_type(h)!=endpoint) ) {
6841       @<Print two dots, followed by |given| or |curl| if present@>;
6842     }
6843   } while (p!=h);
6844   if ( left_type(h)!=endpoint ) 
6845     mp_print(mp, "cycle");
6846 }
6847
6848 @ @<Print information for adjacent knots...@>=
6849 mp_print_two(mp, x_coord(p),y_coord(p));
6850 switch (right_type(p)) {
6851 case endpoint: 
6852   if ( left_type(p)==open ) mp_print(mp, "{open?}"); /* can't happen */
6853 @.open?@>
6854   if ( (left_type(q)!=endpoint)||(q!=h) ) q=null; /* force an error */
6855   goto DONE1;
6856   break;
6857 case explicit: 
6858   @<Print control points between |p| and |q|, then |goto done1|@>;
6859   break;
6860 case open: 
6861   @<Print information for a curve that begins |open|@>;
6862   break;
6863 case curl:
6864 case given: 
6865   @<Print information for a curve that begins |curl| or |given|@>;
6866   break;
6867 default:
6868   mp_print(mp, "???"); /* can't happen */
6869 @.???@>
6870   break;
6871 }
6872 if ( left_type(q)<=explicit ) {
6873   mp_print(mp, "..control?"); /* can't happen */
6874 @.control?@>
6875 } else if ( (right_tension(p)!=unity)||(left_tension(q)!=unity) ) {
6876   @<Print tension between |p| and |q|@>;
6877 }
6878
6879 @ Since |n_sin_cos| produces |fraction| results, which we will print as if they
6880 were |scaled|, the magnitude of a |given| direction vector will be~4096.
6881
6882 @<Print two dots...@>=
6883
6884   mp_print_nl(mp, " ..");
6885   if ( left_type(p)==given ) { 
6886     mp_n_sin_cos(mp, left_given(p)); mp_print_char(mp, '{');
6887     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ',');
6888     mp_print_scaled(mp, mp->n_sin); mp_print_char(mp, '}');
6889   } else if ( left_type(p)==curl ){ 
6890     mp_print(mp, "{curl "); 
6891     mp_print_scaled(mp, left_curl(p)); mp_print_char(mp, '}');
6892   }
6893 }
6894
6895 @ @<Print tension between |p| and |q|@>=
6896
6897   mp_print(mp, "..tension ");
6898   if ( right_tension(p)<0 ) mp_print(mp, "atleast");
6899   mp_print_scaled(mp, abs(right_tension(p)));
6900   if ( right_tension(p)!=left_tension(q) ){ 
6901     mp_print(mp, " and ");
6902     if ( left_tension(q)<0 ) mp_print(mp, "atleast");
6903     mp_print_scaled(mp, abs(left_tension(q)));
6904   }
6905 }
6906
6907 @ @<Print control points between |p| and |q|, then |goto done1|@>=
6908
6909   mp_print(mp, "..controls "); 
6910   mp_print_two(mp, right_x(p),right_y(p)); 
6911   mp_print(mp, " and ");
6912   if ( left_type(q)!=explicit ) { 
6913     mp_print(mp, "??"); /* can't happen */
6914 @.??@>
6915   } else {
6916     mp_print_two(mp, left_x(q),left_y(q));
6917   }
6918   goto DONE1;
6919 }
6920
6921 @ @<Print information for a curve that begins |open|@>=
6922 if ( (left_type(p)!=explicit)&&(left_type(p)!=open) ) {
6923   mp_print(mp, "{open?}"); /* can't happen */
6924 @.open?@>
6925 }
6926
6927 @ A curl of 1 is shown explicitly, so that the user sees clearly that
6928 \MP's default curl is present.
6929
6930 The code here uses the fact that |left_curl==left_given| and
6931 |right_curl==right_given|.
6932
6933 @<Print information for a curve that begins |curl|...@>=
6934
6935   if ( left_type(p)==open )  
6936     mp_print(mp, "??"); /* can't happen */
6937 @.??@>
6938   if ( right_type(p)==curl ) { 
6939     mp_print(mp, "{curl "); mp_print_scaled(mp, right_curl(p));
6940   } else { 
6941     mp_n_sin_cos(mp, right_given(p)); mp_print_char(mp, '{');
6942     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ','); 
6943     mp_print_scaled(mp, mp->n_sin);
6944   }
6945   mp_print_char(mp, '}');
6946 }
6947
6948 @ It is convenient to have another version of |pr_path| that prints the path
6949 as a diagnostic message.
6950
6951 @<Declare subroutines for printing expressions@>=
6952 void mp_print_path (MP mp,pointer h, char *s, boolean nuline) { 
6953   mp_print_diagnostic(mp, "Path", s, nuline); mp_print_ln(mp);
6954 @.Path at line...@>
6955   mp_pr_path(mp, h);
6956   mp_end_diagnostic(mp, true);
6957 }
6958
6959 @ If we want to duplicate a knot node, we can say |copy_knot|:
6960
6961 @c 
6962 pointer mp_copy_knot (MP mp,pointer p) {
6963   pointer q; /* the copy */
6964   int k; /* runs through the words of a knot node */
6965   q=mp_get_node(mp, knot_node_size);
6966   for (k=0;k<=knot_node_size-1;k++) {
6967     mp->mem[q+k]=mp->mem[p+k];
6968   }
6969   originator(q)=originator(p);
6970   return q;
6971 }
6972
6973 @ The |copy_path| routine makes a clone of a given path.
6974
6975 @c 
6976 pointer mp_copy_path (MP mp, pointer p) {
6977   pointer q,pp,qq; /* for list manipulation */
6978   q=mp_copy_knot(mp, p);
6979   qq=q; pp=link(p);
6980   while ( pp!=p ) { 
6981     link(qq)=mp_copy_knot(mp, pp);
6982     qq=link(qq);
6983     pp=link(pp);
6984   }
6985   link(qq)=q;
6986   return q;
6987 }
6988
6989 @ Similarly, there's a way to copy the {\sl reverse\/} of a path. This procedure
6990 returns a pointer to the first node of the copy, if the path is a cycle,
6991 but to the final node of a non-cyclic copy. The global
6992 variable |path_tail| will point to the final node of the original path;
6993 this trick makes it easier to implement `\&{doublepath}'.
6994
6995 All node types are assumed to be |endpoint| or |explicit| only.
6996
6997 @c 
6998 pointer mp_htap_ypoc (MP mp,pointer p) {
6999   pointer q,pp,qq,rr; /* for list manipulation */
7000   q=mp_get_node(mp, knot_node_size); /* this will correspond to |p| */
7001   qq=q; pp=p;
7002   while (1) { 
7003     right_type(qq)=left_type(pp); left_type(qq)=right_type(pp);
7004     x_coord(qq)=x_coord(pp); y_coord(qq)=y_coord(pp);
7005     right_x(qq)=left_x(pp); right_y(qq)=left_y(pp);
7006     left_x(qq)=right_x(pp); left_y(qq)=right_y(pp);
7007     originator(qq)=originator(pp);
7008     if ( link(pp)==p ) { 
7009       link(q)=qq; mp->path_tail=pp; return q;
7010     }
7011     rr=mp_get_node(mp, knot_node_size); link(rr)=qq; qq=rr; pp=link(pp);
7012   }
7013 }
7014
7015 @ @<Glob...@>=
7016 pointer path_tail; /* the node that links to the beginning of a path */
7017
7018 @ When a cyclic list of knot nodes is no longer needed, it can be recycled by
7019 calling the following subroutine.
7020
7021 @<Declare the recycling subroutines@>=
7022 void mp_toss_knot_list (MP mp,pointer p) ;
7023
7024 @ @c
7025 void mp_toss_knot_list (MP mp,pointer p) {
7026   pointer q; /* the node being freed */
7027   pointer r; /* the next node */
7028   q=p;
7029   do {  
7030     r=link(q); 
7031     mp_free_node(mp, q,knot_node_size); q=r;
7032   } while (q!=p);
7033 }
7034
7035 @* \[18] Choosing control points.
7036 Now we must actually delve into one of \MP's more difficult routines,
7037 the |make_choices| procedure that chooses angles and control points for
7038 the splines of a curve when the user has not specified them explicitly.
7039 The parameter to |make_choices| points to a list of knots and
7040 path information, as described above.
7041
7042 A path decomposes into independent segments at ``breakpoint'' knots,
7043 which are knots whose left and right angles are both prespecified in
7044 some way (i.e., their |left_type| and |right_type| aren't both open).
7045
7046 @c 
7047 @<Declare the procedure called |solve_choices|@>;
7048 void mp_make_choices (MP mp,pointer knots) {
7049   pointer h; /* the first breakpoint */
7050   pointer p,q; /* consecutive breakpoints being processed */
7051   @<Other local variables for |make_choices|@>;
7052   check_arith; /* make sure that |arith_error=false| */
7053   if ( mp->internal[tracing_choices]>0 )
7054     mp_print_path(mp, knots,", before choices",true);
7055   @<If consecutive knots are equal, join them explicitly@>;
7056   @<Find the first breakpoint, |h|, on the path;
7057     insert an artificial breakpoint if the path is an unbroken cycle@>;
7058   p=h;
7059   do {  
7060     @<Fill in the control points between |p| and the next breakpoint,
7061       then advance |p| to that breakpoint@>;
7062   } while (p!=h);
7063   if ( mp->internal[tracing_choices]>0 )
7064     mp_print_path(mp, knots,", after choices",true);
7065   if ( mp->arith_error ) {
7066     @<Report an unexpected problem during the choice-making@>;
7067   }
7068 }
7069
7070 @ @<Report an unexpected problem during the choice...@>=
7071
7072   print_err("Some number got too big");
7073 @.Some number got too big@>
7074   help2("The path that I just computed is out of range.")
7075        ("So it will probably look funny. Proceed, for a laugh.");
7076   mp_put_get_error(mp); mp->arith_error=false;
7077 }
7078
7079 @ Two knots in a row with the same coordinates will always be joined
7080 by an explicit ``curve'' whose control points are identical with the
7081 knots.
7082
7083 @<If consecutive knots are equal, join them explicitly@>=
7084 p=knots;
7085 do {  
7086   q=link(p);
7087   if ( x_coord(p)==x_coord(q) && y_coord(p)==y_coord(q) && right_type(p)>explicit ) { 
7088     right_type(p)=explicit;
7089     if ( left_type(p)==open ) { 
7090       left_type(p)=curl; left_curl(p)=unity;
7091     }
7092     left_type(q)=explicit;
7093     if ( right_type(q)==open ) { 
7094       right_type(q)=curl; right_curl(q)=unity;
7095     }
7096     right_x(p)=x_coord(p); left_x(q)=x_coord(p);
7097     right_y(p)=y_coord(p); left_y(q)=y_coord(p);
7098   }
7099   p=q;
7100 } while (p!=knots)
7101
7102 @ If there are no breakpoints, it is necessary to compute the direction
7103 angles around an entire cycle. In this case the |left_type| of the first
7104 node is temporarily changed to |end_cycle|.
7105
7106 @d end_cycle (open+1)
7107
7108 @<Find the first breakpoint, |h|, on the path...@>=
7109 h=knots;
7110 while (1) { 
7111   if ( left_type(h)!=open ) break;
7112   if ( right_type(h)!=open ) break;
7113   h=link(h);
7114   if ( h==knots ) { 
7115     left_type(h)=end_cycle; break;
7116   }
7117 }
7118
7119 @ If |right_type(p)<given| and |q=link(p)|, we must have
7120 |right_type(p)=left_type(q)=explicit| or |endpoint|.
7121
7122 @<Fill in the control points between |p| and the next breakpoint...@>=
7123 q=link(p);
7124 if ( right_type(p)>=given ) { 
7125   while ( (left_type(q)==open)&&(right_type(q)==open) ) q=link(q);
7126   @<Fill in the control information between
7127     consecutive breakpoints |p| and |q|@>;
7128 } else if ( right_type(p)==endpoint ) {
7129   @<Give reasonable values for the unused control points between |p| and~|q|@>;
7130 }
7131 p=q
7132
7133 @ This step makes it possible to transform an explicitly computed path without
7134 checking the |left_type| and |right_type| fields.
7135
7136 @<Give reasonable values for the unused control points between |p| and~|q|@>=
7137
7138   right_x(p)=x_coord(p); right_y(p)=y_coord(p);
7139   left_x(q)=x_coord(q); left_y(q)=y_coord(q);
7140 }
7141
7142 @ Before we can go further into the way choices are made, we need to
7143 consider the underlying theory. The basic ideas implemented in |make_choices|
7144 are due to John Hobby, who introduced the notion of ``mock curvature''
7145 @^Hobby, John Douglas@>
7146 at a knot. Angles are chosen so that they preserve mock curvature when
7147 a knot is passed, and this has been found to produce excellent results.
7148
7149 It is convenient to introduce some notations that simplify the necessary
7150 formulas. Let $d_{k,k+1}=\vert z\k-z_k\vert$ be the (nonzero) distance
7151 between knots |k| and |k+1|; and let
7152 $${z\k-z_k\over z_k-z_{k-1}}={d_{k,k+1}\over d_{k-1,k}}e^{i\psi_k}$$
7153 so that a polygonal line from $z_{k-1}$ to $z_k$ to $z\k$ turns left
7154 through an angle of~$\psi_k$. We assume that $\vert\psi_k\vert\L180^\circ$.
7155 The control points for the spline from $z_k$ to $z\k$ will be denoted by
7156 $$\eqalign{z_k^+&=z_k+
7157   \textstyle{1\over3}\rho_k e^{i\theta_k}(z\k-z_k),\cr
7158  z\k^-&=z\k-
7159   \textstyle{1\over3}\sigma\k e^{-i\phi\k}(z\k-z_k),\cr}$$
7160 where $\rho_k$ and $\sigma\k$ are nonnegative ``velocity ratios'' at the
7161 beginning and end of the curve, while $\theta_k$ and $\phi\k$ are the
7162 corresponding ``offset angles.'' These angles satisfy the condition
7163 $$\theta_k+\phi_k+\psi_k=0,\eqno(*)$$
7164 whenever the curve leaves an intermediate knot~|k| in the direction that
7165 it enters.
7166
7167 @ Let $\alpha_k$ and $\beta\k$ be the reciprocals of the ``tension'' of
7168 the curve at its beginning and ending points. This means that
7169 $\rho_k=\alpha_k f(\theta_k,\phi\k)$ and $\sigma\k=\beta\k f(\phi\k,\theta_k)$,
7170 where $f(\theta,\phi)$ is \MP's standard velocity function defined in
7171 the |velocity| subroutine. The cubic spline $B(z_k^{\phantom+},z_k^+,
7172 z\k^-,z\k^{\phantom+};t)$
7173 has curvature
7174 @^curvature@>
7175 $${2\sigma\k\sin(\theta_k+\phi\k)-6\sin\theta_k\over\rho_k^2d_{k,k+1}}
7176 \qquad{\rm and}\qquad
7177 {2\rho_k\sin(\theta_k+\phi\k)-6\sin\phi\k\over\sigma\k^2d_{k,k+1}}$$
7178 at |t=0| and |t=1|, respectively. The mock curvature is the linear
7179 @^mock curvature@>
7180 approximation to this true curvature that arises in the limit for
7181 small $\theta_k$ and~$\phi\k$, if second-order terms are discarded.
7182 The standard velocity function satisfies
7183 $$f(\theta,\phi)=1+O(\theta^2+\theta\phi+\phi^2);$$
7184 hence the mock curvatures are respectively
7185 $${2\beta\k(\theta_k+\phi\k)-6\theta_k\over\alpha_k^2d_{k,k+1}}
7186 \qquad{\rm and}\qquad
7187 {2\alpha_k(\theta_k+\phi\k)-6\phi\k\over\beta\k^2d_{k,k+1}}.\eqno(**)$$
7188
7189 @ The turning angles $\psi_k$ are given, and equation $(*)$ above
7190 determines $\phi_k$ when $\theta_k$ is known, so the task of
7191 angle selection is essentially to choose appropriate values for each
7192 $\theta_k$. When equation~$(*)$ is used to eliminate $\phi$~variables
7193 from $(**)$, we obtain a system of linear equations of the form
7194 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7195 where
7196 $$A_k={\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7197 \qquad B_k={3-\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7198 \qquad C_k={3-\beta\k\over\alpha_k^2d_{k,k+1}},
7199 \qquad D_k={\beta\k\over\alpha_k^2d_{k,k+1}}.$$
7200 The tensions are always $3\over4$ or more, hence each $\alpha$ and~$\beta$
7201 will be at most $4\over3$. It follows that $B_k\G{5\over4}A_k$ and
7202 $C_k\G{5\over4}D_k$; hence the equations are diagonally dominant;
7203 hence they have a unique solution. Moreover, in most cases the tensions
7204 are equal to~1, so that $B_k=2A_k$ and $C_k=2D_k$. This makes the
7205 solution numerically stable, and there is an exponential damping
7206 effect: The data at knot $k\pm j$ affects the angle at knot~$k$ by
7207 a factor of~$O(2^{-j})$.
7208
7209 @ However, we still must consider the angles at the starting and ending
7210 knots of a non-cyclic path. These angles might be given explicitly, or
7211 they might be specified implicitly in terms of an amount of ``curl.''
7212
7213 Let's assume that angles need to be determined for a non-cyclic path
7214 starting at $z_0$ and ending at~$z_n$. Then equations of the form
7215 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta_{k+1}=R_k$$
7216 have been given for $0<k<n$, and it will be convenient to introduce
7217 equations of the same form for $k=0$ and $k=n$, where
7218 $$A_0=B_0=C_n=D_n=0.$$
7219 If $\theta_0$ is supposed to have a given value $E_0$, we simply
7220 define $C_0=0$, $D_0=0$, and $R_0=E_0$. Otherwise a curl
7221 parameter, $\gamma_0$, has been specified at~$z_0$; this means
7222 that the mock curvature at $z_0$ should be $\gamma_0$ times the
7223 mock curvature at $z_1$; i.e.,
7224 $${2\beta_1(\theta_0+\phi_1)-6\theta_0\over\alpha_0^2d_{01}}
7225 =\gamma_0{2\alpha_0(\theta_0+\phi_1)-6\phi_1\over\beta_1^2d_{01}}.$$
7226 This equation simplifies to
7227 $$(\alpha_0\chi_0+3-\beta_1)\theta_0+
7228  \bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\theta_1=
7229  -\bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\psi_1,$$
7230 where $\chi_0=\alpha_0^2\gamma_0/\beta_1^2$; so we can set $C_0=
7231 \chi_0\alpha_0+3-\beta_1$, $D_0=(3-\alpha_0)\chi_0+\beta_1$, $R_0=-D_0\psi_1$.
7232 It can be shown that $C_0>0$ and $C_0B_1-A_1D_0>0$ when $\gamma_0\G0$,
7233 hence the linear equations remain nonsingular.
7234
7235 Similar considerations apply at the right end, when the final angle $\phi_n$
7236 may or may not need to be determined. It is convenient to let $\psi_n=0$,
7237 hence $\theta_n=-\phi_n$. We either have an explicit equation $\theta_n=E_n$,
7238 or we have
7239 $$\bigl((3-\beta_n)\chi_n+\alpha_{n-1}\bigr)\theta_{n-1}+
7240 (\beta_n\chi_n+3-\alpha_{n-1})\theta_n=0,\qquad
7241   \chi_n={\beta_n^2\gamma_n\over\alpha_{n-1}^2}.$$
7242
7243 When |make_choices| chooses angles, it must compute the coefficients of
7244 these linear equations, then solve the equations. To compute the coefficients,
7245 it is necessary to compute arctangents of the given turning angles~$\psi_k$.
7246 When the equations are solved, the chosen directions $\theta_k$ are put
7247 back into the form of control points by essentially computing sines and
7248 cosines.
7249
7250 @ OK, we are ready to make the hard choices of |make_choices|.
7251 Most of the work is relegated to an auxiliary procedure
7252 called |solve_choices|, which has been introduced to keep
7253 |make_choices| from being extremely long.
7254
7255 @<Fill in the control information between...@>=
7256 @<Calculate the turning angles $\psi_k$ and the distances $d_{k,k+1}$;
7257   set $n$ to the length of the path@>;
7258 @<Remove |open| types at the breakpoints@>;
7259 mp_solve_choices(mp, p,q,n)
7260
7261 @ It's convenient to precompute quantities that will be needed several
7262 times later. The values of |delta_x[k]| and |delta_y[k]| will be the
7263 coordinates of $z\k-z_k$, and the magnitude of this vector will be
7264 |delta[k]=@t$d_{k,k+1}$@>|. The path angle $\psi_k$ between $z_k-z_{k-1}$
7265 and $z\k-z_k$ will be stored in |psi[k]|.
7266
7267 @<Glob...@>=
7268 int path_size; /* maximum number of knots between breakpoints of a path */
7269 scaled *delta_x;
7270 scaled *delta_y;
7271 scaled *delta; /* knot differences */
7272 angle  *psi; /* turning angles */
7273
7274 @ @<Allocate or initialize ...@>=
7275 mp->delta_x = NULL;
7276 mp->delta_y = NULL;
7277 mp->delta = NULL;
7278 mp->psi = NULL;
7279
7280 @ @<Dealloc variables@>=
7281 xfree(mp->delta_x);
7282 xfree(mp->delta_y);
7283 xfree(mp->delta);
7284 xfree(mp->psi);
7285
7286 @ @<Other local variables for |make_choices|@>=
7287   int k,n; /* current and final knot numbers */
7288   pointer s,t; /* registers for list traversal */
7289   scaled delx,dely; /* directions where |open| meets |explicit| */
7290   fraction sine,cosine; /* trig functions of various angles */
7291
7292 @ @<Calculate the turning angles...@>=
7293 {
7294 RESTART:
7295   k=0; s=p; n=mp->path_size;
7296   do {  
7297     t=link(s);
7298     mp->delta_x[k]=x_coord(t)-x_coord(s);
7299     mp->delta_y[k]=y_coord(t)-y_coord(s);
7300     mp->delta[k]=mp_pyth_add(mp, mp->delta_x[k],mp->delta_y[k]);
7301     if ( k>0 ) { 
7302       sine=mp_make_fraction(mp, mp->delta_y[k-1],mp->delta[k-1]);
7303       cosine=mp_make_fraction(mp, mp->delta_x[k-1],mp->delta[k-1]);
7304       mp->psi[k]=mp_n_arg(mp, mp_take_fraction(mp, mp->delta_x[k],cosine)+
7305         mp_take_fraction(mp, mp->delta_y[k],sine),
7306         mp_take_fraction(mp, mp->delta_y[k],cosine)-
7307           mp_take_fraction(mp, mp->delta_x[k],sine));
7308     }
7309     incr(k); s=t;
7310     if ( k==mp->path_size ) {
7311       mp_reallocate_paths(mp, mp->path_size+(mp->path_size>>2));
7312       goto RESTART; /* retry, loop size has changed */
7313     }
7314     if ( s==q ) n=k;
7315   } while (! (k>=n)&&(left_type(s)!=end_cycle));
7316   if ( k==n ) mp->psi[n]=0; else mp->psi[k]=mp->psi[1];
7317 }
7318
7319 @ When we get to this point of the code, |right_type(p)| is either
7320 |given| or |curl| or |open|. If it is |open|, we must have
7321 |left_type(p)=end_cycle| or |left_type(p)=explicit|. In the latter
7322 case, the |open| type is converted to |given|; however, if the
7323 velocity coming into this knot is zero, the |open| type is
7324 converted to a |curl|, since we don't know the incoming direction.
7325
7326 Similarly, |left_type(q)| is either |given| or |curl| or |open| or
7327 |end_cycle|. The |open| possibility is reduced either to |given| or to |curl|.
7328
7329 @<Remove |open| types at the breakpoints@>=
7330 if ( left_type(q)==open ) { 
7331   delx=right_x(q)-x_coord(q); dely=right_y(q)-y_coord(q);
7332   if ( (delx==0)&&(dely==0) ) { 
7333     left_type(q)=curl; left_curl(q)=unity;
7334   } else { 
7335     left_type(q)=given; left_given(q)=mp_n_arg(mp, delx,dely);
7336   }
7337 }
7338 if ( (right_type(p)==open)&&(left_type(p)==explicit) ) { 
7339   delx=x_coord(p)-left_x(p); dely=y_coord(p)-left_y(p);
7340   if ( (delx==0)&&(dely==0) ) { 
7341     right_type(p)=curl; right_curl(p)=unity;
7342   } else { 
7343     right_type(p)=given; right_given(p)=mp_n_arg(mp, delx,dely);
7344   }
7345 }
7346
7347 @ Linear equations need to be solved whenever |n>1|; and also when |n=1|
7348 and exactly one of the breakpoints involves a curl. The simplest case occurs
7349 when |n=1| and there is a curl at both breakpoints; then we simply draw
7350 a straight line.
7351
7352 But before coding up the simple cases, we might as well face the general case,
7353 since we must deal with it sooner or later, and since the general case
7354 is likely to give some insight into the way simple cases can be handled best.
7355
7356 When there is no cycle, the linear equations to be solved form a tridiagonal
7357 system, and we can apply the standard technique of Gaussian elimination
7358 to convert that system to a sequence of equations of the form
7359 $$\theta_0+u_0\theta_1=v_0,\quad
7360 \theta_1+u_1\theta_2=v_1,\quad\ldots,\quad
7361 \theta_{n-1}+u_{n-1}\theta_n=v_{n-1},\quad
7362 \theta_n=v_n.$$
7363 It is possible to do this diagonalization while generating the equations.
7364 Once $\theta_n$ is known, it is easy to determine $\theta_{n-1}$, \dots,
7365 $\theta_1$, $\theta_0$; thus, the equations will be solved.
7366
7367 The procedure is slightly more complex when there is a cycle, but the
7368 basic idea will be nearly the same. In the cyclic case the right-hand
7369 sides will be $v_k+w_k\theta_0$ instead of simply $v_k$, and we will start
7370 the process off with $u_0=v_0=0$, $w_0=1$. The final equation will be not
7371 $\theta_n=v_n$ but $\theta_n+u_n\theta_1=v_n+w_n\theta_0$; an appropriate
7372 ending routine will take account of the fact that $\theta_n=\theta_0$ and
7373 eliminate the $w$'s from the system, after which the solution can be
7374 obtained as before.
7375
7376 When $u_k$, $v_k$, and $w_k$ are being computed, the three pointer
7377 variables |r|, |s|,~|t| will point respectively to knots |k-1|, |k|,
7378 and~|k+1|. The $u$'s and $w$'s are scaled by $2^{28}$, i.e., they are
7379 of type |fraction|; the $\theta$'s and $v$'s are of type |angle|.
7380
7381 @<Glob...@>=
7382 angle *theta; /* values of $\theta_k$ */
7383 fraction *uu; /* values of $u_k$ */
7384 angle *vv; /* values of $v_k$ */
7385 fraction *ww; /* values of $w_k$ */
7386
7387 @ @<Allocate or initialize ...@>=
7388 mp->theta = NULL;
7389 mp->uu = NULL;
7390 mp->vv = NULL;
7391 mp->ww = NULL;
7392
7393 @ @<Dealloc variables@>=
7394 xfree(mp->theta);
7395 xfree(mp->uu);
7396 xfree(mp->vv);
7397 xfree(mp->ww);
7398
7399 @ @<Declare |mp_reallocate| functions@>=
7400 void mp_reallocate_paths (MP mp, int l);
7401
7402 @ @c
7403 void mp_reallocate_paths (MP mp, int l) {
7404   XREALLOC (mp->delta_x, l, scaled);
7405   XREALLOC (mp->delta_y, l, scaled);
7406   XREALLOC (mp->delta,   l, scaled);
7407   XREALLOC (mp->psi,     l, angle);
7408   XREALLOC (mp->theta,   l, angle);
7409   XREALLOC (mp->uu,      l, fraction);
7410   XREALLOC (mp->vv,      l, angle);
7411   XREALLOC (mp->ww,      l, fraction);
7412   mp->path_size = l;
7413 }
7414
7415 @ Our immediate problem is to get the ball rolling by setting up the
7416 first equation or by realizing that no equations are needed, and to fit
7417 this initialization into a framework suitable for the overall computation.
7418
7419 @<Declare the procedure called |solve_choices|@>=
7420 @<Declare subroutines needed by |solve_choices|@>;
7421 void mp_solve_choices (MP mp,pointer p, pointer q, halfword n) {
7422   int k; /* current knot number */
7423   pointer r,s,t; /* registers for list traversal */
7424   @<Other local variables for |solve_choices|@>;
7425   k=0; s=p; r=0;
7426   while (1) { 
7427     t=link(s);
7428     if ( k==0 ) {
7429       @<Get the linear equations started; or |return|
7430         with the control points in place, if linear equations
7431         needn't be solved@>
7432     } else  { 
7433       switch (left_type(s)) {
7434       case end_cycle: case open:
7435         @<Set up equation to match mock curvatures
7436           at $z_k$; then |goto found| with $\theta_n$
7437           adjusted to equal $\theta_0$, if a cycle has ended@>;
7438         break;
7439       case curl:
7440         @<Set up equation for a curl at $\theta_n$
7441           and |goto found|@>;
7442         break;
7443       case given:
7444         @<Calculate the given value of $\theta_n$
7445           and |goto found|@>;
7446         break;
7447       } /* there are no other cases */
7448     }
7449     r=s; s=t; incr(k);
7450   }
7451 FOUND:
7452   @<Finish choosing angles and assigning control points@>;
7453 }
7454
7455 @ On the first time through the loop, we have |k=0| and |r| is not yet
7456 defined. The first linear equation, if any, will have $A_0=B_0=0$.
7457
7458 @<Get the linear equations started...@>=
7459 switch (right_type(s)) {
7460 case given: 
7461   if ( left_type(t)==given ) {
7462     @<Reduce to simple case of two givens  and |return|@>
7463   } else {
7464     @<Set up the equation for a given value of $\theta_0$@>;
7465   }
7466   break;
7467 case curl: 
7468   if ( left_type(t)==curl ) {
7469     @<Reduce to simple case of straight line and |return|@>
7470   } else {
7471     @<Set up the equation for a curl at $\theta_0$@>;
7472   }
7473   break;
7474 case open: 
7475   mp->uu[0]=0; mp->vv[0]=0; mp->ww[0]=fraction_one;
7476   /* this begins a cycle */
7477   break;
7478 } /* there are no other cases */
7479
7480 @ The general equation that specifies equality of mock curvature at $z_k$ is
7481 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7482 as derived above. We want to combine this with the already-derived equation
7483 $\theta_{k-1}+u_{k-1}\theta_k=v_{k-1}+w_{k-1}\theta_0$ in order to obtain
7484 a new equation
7485 $\theta_k+u_k\theta\k=v_k+w_k\theta_0$. This can be done by dividing the
7486 equation
7487 $$(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}
7488     -A_kw_{k-1}\theta_0$$
7489 by $B_k-u_{k-1}A_k+C_k$. The trick is to do this carefully with
7490 fixed-point arithmetic, avoiding the chance of overflow while retaining
7491 suitable precision.
7492
7493 The calculations will be performed in several registers that
7494 provide temporary storage for intermediate quantities.
7495
7496 @<Other local variables for |solve_choices|@>=
7497 fraction aa,bb,cc,ff,acc; /* temporary registers */
7498 scaled dd,ee; /* likewise, but |scaled| */
7499 scaled lt,rt; /* tension values */
7500
7501 @ @<Set up equation to match mock curvatures...@>=
7502 { @<Calculate the values $\\{aa}=A_k/B_k$, $\\{bb}=D_k/C_k$,
7503     $\\{dd}=(3-\alpha_{k-1})d_{k,k+1}$, $\\{ee}=(3-\beta\k)d_{k-1,k}$,
7504     and $\\{cc}=(B_k-u_{k-1}A_k)/B_k$@>;
7505   @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>;
7506   mp->uu[k]=mp_take_fraction(mp, ff,bb);
7507   @<Calculate the values of $v_k$ and $w_k$@>;
7508   if ( left_type(s)==end_cycle ) {
7509     @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>;
7510   }
7511 }
7512
7513 @ Since tension values are never less than 3/4, the values |aa| and
7514 |bb| computed here are never more than 4/5.
7515
7516 @<Calculate the values $\\{aa}=...@>=
7517 if ( abs(right_tension(r))==unity) { 
7518   aa=fraction_half; dd=2*mp->delta[k];
7519 } else { 
7520   aa=mp_make_fraction(mp, unity,3*abs(right_tension(r))-unity);
7521   dd=mp_take_fraction(mp, mp->delta[k],
7522     fraction_three-mp_make_fraction(mp, unity,abs(right_tension(r))));
7523 }
7524 if ( abs(left_tension(t))==unity ){ 
7525   bb=fraction_half; ee=2*mp->delta[k-1];
7526 } else { 
7527   bb=mp_make_fraction(mp, unity,3*abs(left_tension(t))-unity);
7528   ee=mp_take_fraction(mp, mp->delta[k-1],
7529     fraction_three-mp_make_fraction(mp, unity,abs(left_tension(t))));
7530 }
7531 cc=fraction_one-mp_take_fraction(mp, mp->uu[k-1],aa)
7532
7533 @ The ratio to be calculated in this step can be written in the form
7534 $$\beta_k^2\cdot\\{ee}\over\beta_k^2\cdot\\{ee}+\alpha_k^2\cdot
7535   \\{cc}\cdot\\{dd},$$
7536 because of the quantities just calculated. The values of |dd| and |ee|
7537 will not be needed after this step has been performed.
7538
7539 @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>=
7540 dd=mp_take_fraction(mp, dd,cc); lt=abs(left_tension(s)); rt=abs(right_tension(s));
7541 if ( lt!=rt ) { /* $\beta_k^{-1}\ne\alpha_k^{-1}$ */
7542   if ( lt<rt ) { 
7543     ff=mp_make_fraction(mp, lt,rt);
7544     ff=mp_take_fraction(mp, ff,ff); /* $\alpha_k^2/\beta_k^2$ */
7545     dd=mp_take_fraction(mp, dd,ff);
7546   } else { 
7547     ff=mp_make_fraction(mp, rt,lt);
7548     ff=mp_take_fraction(mp, ff,ff); /* $\beta_k^2/\alpha_k^2$ */
7549     ee=mp_take_fraction(mp, ee,ff);
7550   }
7551 }
7552 ff=mp_make_fraction(mp, ee,ee+dd)
7553
7554 @ The value of $u_{k-1}$ will be |<=1| except when $k=1$ and the previous
7555 equation was specified by a curl. In that case we must use a special
7556 method of computation to prevent overflow.
7557
7558 Fortunately, the calculations turn out to be even simpler in this ``hard''
7559 case. The curl equation makes $w_0=0$ and $v_0=-u_0\psi_1$, hence
7560 $-B_1\psi_1-A_1v_0=-(B_1-u_0A_1)\psi_1=-\\{cc}\cdot B_1\psi_1$.
7561
7562 @<Calculate the values of $v_k$ and $w_k$@>=
7563 acc=-mp_take_fraction(mp, mp->psi[k+1],mp->uu[k]);
7564 if ( right_type(r)==curl ) { 
7565   mp->ww[k]=0;
7566   mp->vv[k]=acc-mp_take_fraction(mp, mp->psi[1],fraction_one-ff);
7567 } else { 
7568   ff=mp_make_fraction(mp, fraction_one-ff,cc); /* this is
7569     $B_k/(C_k+B_k-u_{k-1}A_k)<5$ */
7570   acc=acc-mp_take_fraction(mp, mp->psi[k],ff);
7571   ff=mp_take_fraction(mp, ff,aa); /* this is $A_k/(C_k+B_k-u_{k-1}A_k)$ */
7572   mp->vv[k]=acc-mp_take_fraction(mp, mp->vv[k-1],ff);
7573   if ( mp->ww[k-1]==0 ) mp->ww[k]=0;
7574   else mp->ww[k]=-mp_take_fraction(mp, mp->ww[k-1],ff);
7575 }
7576
7577 @ When a complete cycle has been traversed, we have $\theta_k+u_k\theta\k=
7578 v_k+w_k\theta_0$, for |1<=k<=n|. We would like to determine the value of
7579 $\theta_n$ and reduce the system to the form $\theta_k+u_k\theta\k=v_k$
7580 for |0<=k<n|, so that the cyclic case can be finished up just as if there
7581 were no cycle.
7582
7583 The idea in the following code is to observe that
7584 $$\eqalign{\theta_n&=v_n+w_n\theta_0-u_n\theta_1=\cdots\cr
7585 &=v_n+w_n\theta_0-u_n\bigl(v_1+w_1\theta_0-u_1(v_2+\cdots
7586   -u_{n-2}(v_{n-1}+w_{n-1}\theta_0-u_{n-1}\theta_0))\bigr),\cr}$$
7587 so we can solve for $\theta_n=\theta_0$.
7588
7589 @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>=
7590
7591 aa=0; bb=fraction_one; /* we have |k=n| */
7592 do {  decr(k);
7593 if ( k==0 ) k=n;
7594   aa=mp->vv[k]-mp_take_fraction(mp, aa,mp->uu[k]);
7595   bb=mp->ww[k]-mp_take_fraction(mp, bb,mp->uu[k]);
7596 } while (k!=n); /* now $\theta_n=\\{aa}+\\{bb}\cdot\theta_n$ */
7597 aa=mp_make_fraction(mp, aa,fraction_one-bb);
7598 mp->theta[n]=aa; mp->vv[0]=aa;
7599 for (k=1;k<=n-1;k++) {
7600   mp->vv[k]=mp->vv[k]+mp_take_fraction(mp, aa,mp->ww[k]);
7601 }
7602 goto FOUND;
7603 }
7604
7605 @ @d reduce_angle(A) if ( abs((A))>one_eighty_deg ) {
7606   if ( (A)>0 ) (A)=(A)-three_sixty_deg; else (A)=(A)+three_sixty_deg; }
7607
7608 @<Calculate the given value of $\theta_n$...@>=
7609
7610   mp->theta[n]=left_given(s)-mp_n_arg(mp, mp->delta_x[n-1],mp->delta_y[n-1]);
7611   reduce_angle(mp->theta[n]);
7612   goto FOUND;
7613 }
7614
7615 @ @<Set up the equation for a given value of $\theta_0$@>=
7616
7617   mp->vv[0]=right_given(s)-mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7618   reduce_angle(mp->vv[0]);
7619   mp->uu[0]=0; mp->ww[0]=0;
7620 }
7621
7622 @ @<Set up the equation for a curl at $\theta_0$@>=
7623 { cc=right_curl(s); lt=abs(left_tension(t)); rt=abs(right_tension(s));
7624   if ( (rt==unity)&&(lt==unity) )
7625     mp->uu[0]=mp_make_fraction(mp, cc+cc+unity,cc+two);
7626   else 
7627     mp->uu[0]=mp_curl_ratio(mp, cc,rt,lt);
7628   mp->vv[0]=-mp_take_fraction(mp, mp->psi[1],mp->uu[0]); mp->ww[0]=0;
7629 }
7630
7631 @ @<Set up equation for a curl at $\theta_n$...@>=
7632 { cc=left_curl(s); lt=abs(left_tension(s)); rt=abs(right_tension(r));
7633   if ( (rt==unity)&&(lt==unity) )
7634     ff=mp_make_fraction(mp, cc+cc+unity,cc+two);
7635   else 
7636     ff=mp_curl_ratio(mp, cc,lt,rt);
7637   mp->theta[n]=-mp_make_fraction(mp, mp_take_fraction(mp, mp->vv[n-1],ff),
7638     fraction_one-mp_take_fraction(mp, ff,mp->uu[n-1]));
7639   goto FOUND;
7640 }
7641
7642 @ The |curl_ratio| subroutine has three arguments, which our previous notation
7643 encourages us to call $\gamma$, $\alpha^{-1}$, and $\beta^{-1}$. It is
7644 a somewhat tedious program to calculate
7645 $${(3-\alpha)\alpha^2\gamma+\beta^3\over
7646   \alpha^3\gamma+(3-\beta)\beta^2},$$
7647 with the result reduced to 4 if it exceeds 4. (This reduction of curl
7648 is necessary only if the curl and tension are both large.)
7649 The values of $\alpha$ and $\beta$ will be at most~4/3.
7650
7651 @<Declare subroutines needed by |solve_choices|@>=
7652 fraction mp_curl_ratio (MP mp,scaled gamma, scaled a_tension, 
7653                         scaled b_tension) {
7654   fraction alpha,beta,num,denom,ff; /* registers */
7655   alpha=mp_make_fraction(mp, unity,a_tension);
7656   beta=mp_make_fraction(mp, unity,b_tension);
7657   if ( alpha<=beta ) {
7658     ff=mp_make_fraction(mp, alpha,beta); ff=mp_take_fraction(mp, ff,ff);
7659     gamma=mp_take_fraction(mp, gamma,ff);
7660     beta=beta / 010000; /* convert |fraction| to |scaled| */
7661     denom=mp_take_fraction(mp, gamma,alpha)+three-beta;
7662     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7663   } else { 
7664     ff=mp_make_fraction(mp, beta,alpha); ff=mp_take_fraction(mp, ff,ff);
7665     beta=mp_take_fraction(mp, beta,ff) / 010000; /* convert |fraction| to |scaled| */
7666     denom=mp_take_fraction(mp, gamma,alpha)+(ff / 1365)-beta;
7667       /* $1365\approx 2^{12}/3$ */
7668     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7669   }
7670   if ( num>=denom+denom+denom+denom ) return fraction_four;
7671   else return mp_make_fraction(mp, num,denom);
7672 }
7673
7674 @ We're in the home stretch now.
7675
7676 @<Finish choosing angles and assigning control points@>=
7677 for (k=n-1;k>=0;k--) {
7678   mp->theta[k]=mp->vv[k]-mp_take_fraction(mp,mp->theta[k+1],mp->uu[k]);
7679 }
7680 s=p; k=0;
7681 do {  
7682   t=link(s);
7683   mp_n_sin_cos(mp, mp->theta[k]); mp->st=mp->n_sin; mp->ct=mp->n_cos;
7684   mp_n_sin_cos(mp, -mp->psi[k+1]-mp->theta[k+1]); mp->sf=mp->n_sin; mp->cf=mp->n_cos;
7685   mp_set_controls(mp, s,t,k);
7686   incr(k); s=t;
7687 } while (k!=n)
7688
7689 @ The |set_controls| routine actually puts the control points into
7690 a pair of consecutive nodes |p| and~|q|. Global variables are used to
7691 record the values of $\sin\theta$, $\cos\theta$, $\sin\phi$, and
7692 $\cos\phi$ needed in this calculation.
7693
7694 @<Glob...@>=
7695 fraction st;
7696 fraction ct;
7697 fraction sf;
7698 fraction cf; /* sines and cosines */
7699
7700 @ @<Declare subroutines needed by |solve_choices|@>=
7701 void mp_set_controls (MP mp,pointer p, pointer q, integer k) {
7702   fraction rr,ss; /* velocities, divided by thrice the tension */
7703   scaled lt,rt; /* tensions */
7704   fraction sine; /* $\sin(\theta+\phi)$ */
7705   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7706   rr=mp_velocity(mp, mp->st,mp->ct,mp->sf,mp->cf,rt);
7707   ss=mp_velocity(mp, mp->sf,mp->cf,mp->st,mp->ct,lt);
7708   if ( (right_tension(p)<0)||(left_tension(q)<0) ) {
7709     @<Decrease the velocities,
7710       if necessary, to stay inside the bounding triangle@>;
7711   }
7712   right_x(p)=x_coord(p)+mp_take_fraction(mp, 
7713                           mp_take_fraction(mp, mp->delta_x[k],mp->ct)-
7714                           mp_take_fraction(mp, mp->delta_y[k],mp->st),rr);
7715   right_y(p)=y_coord(p)+mp_take_fraction(mp, 
7716                           mp_take_fraction(mp, mp->delta_y[k],mp->ct)+
7717                           mp_take_fraction(mp, mp->delta_x[k],mp->st),rr);
7718   left_x(q)=x_coord(q)-mp_take_fraction(mp, 
7719                          mp_take_fraction(mp, mp->delta_x[k],mp->cf)+
7720                          mp_take_fraction(mp, mp->delta_y[k],mp->sf),ss);
7721   left_y(q)=y_coord(q)-mp_take_fraction(mp, 
7722                          mp_take_fraction(mp, mp->delta_y[k],mp->cf)-
7723                          mp_take_fraction(mp, mp->delta_x[k],mp->sf),ss);
7724   right_type(p)=explicit; left_type(q)=explicit;
7725 }
7726
7727 @ The boundedness conditions $\\{rr}\L\sin\phi\,/\sin(\theta+\phi)$ and
7728 $\\{ss}\L\sin\theta\,/\sin(\theta+\phi)$ are to be enforced if $\sin\theta$,
7729 $\sin\phi$, and $\sin(\theta+\phi)$ all have the same sign. Otherwise
7730 there is no ``bounding triangle.''
7731 @:at_least_}{\&{atleast} primitive@>
7732
7733 @<Decrease the velocities, if necessary...@>=
7734 if (((mp->st>=0)&&(mp->sf>=0))||((mp->st<=0)&&(mp->sf<=0)) ) {
7735   sine=mp_take_fraction(mp, abs(mp->st),mp->cf)+
7736                             mp_take_fraction(mp, abs(mp->sf),mp->ct);
7737   if ( sine>0 ) {
7738     sine=mp_take_fraction(mp, sine,fraction_one+unity); /* safety factor */
7739     if ( right_tension(p)<0 )
7740      if ( mp_ab_vs_cd(mp, abs(mp->sf),fraction_one,rr,sine)<0 )
7741       rr=mp_make_fraction(mp, abs(mp->sf),sine);
7742     if ( left_tension(q)<0 )
7743      if ( mp_ab_vs_cd(mp, abs(mp->st),fraction_one,ss,sine)<0 )
7744       ss=mp_make_fraction(mp, abs(mp->st),sine);
7745   }
7746 }
7747
7748 @ Only the simple cases remain to be handled.
7749
7750 @<Reduce to simple case of two givens and |return|@>=
7751
7752   aa=mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7753   mp_n_sin_cos(mp, right_given(p)-aa); mp->ct=mp->n_cos; mp->st=mp->n_sin;
7754   mp_n_sin_cos(mp, left_given(q)-aa); mp->cf=mp->n_cos; mp->sf=-mp->n_sin;
7755   mp_set_controls(mp, p,q,0); return;
7756 }
7757
7758 @ @<Reduce to simple case of straight line and |return|@>=
7759
7760   right_type(p)=explicit; left_type(q)=explicit;
7761   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7762   if ( rt==unity ) {
7763     if ( mp->delta_x[0]>=0 ) right_x(p)=x_coord(p)+((mp->delta_x[0]+1) / 3);
7764     else right_x(p)=x_coord(p)+((mp->delta_x[0]-1) / 3);
7765     if ( mp->delta_y[0]>=0 ) right_y(p)=y_coord(p)+((mp->delta_y[0]+1) / 3);
7766     else right_y(p)=y_coord(p)+((mp->delta_y[0]-1) / 3);
7767   } else { 
7768     ff=mp_make_fraction(mp, unity,3*rt); /* $\alpha/3$ */
7769     right_x(p)=x_coord(p)+mp_take_fraction(mp, mp->delta_x[0],ff);
7770     right_y(p)=y_coord(p)+mp_take_fraction(mp, mp->delta_y[0],ff);
7771   }
7772   if ( lt==unity ) {
7773     if ( mp->delta_x[0]>=0 ) left_x(q)=x_coord(q)-((mp->delta_x[0]+1) / 3);
7774     else left_x(q)=x_coord(q)-((mp->delta_x[0]-1) / 3);
7775     if ( mp->delta_y[0]>=0 ) left_y(q)=y_coord(q)-((mp->delta_y[0]+1) / 3);
7776     else left_y(q)=y_coord(q)-((mp->delta_y[0]-1) / 3);
7777   } else  { 
7778     ff=mp_make_fraction(mp, unity,3*lt); /* $\beta/3$ */
7779     left_x(q)=x_coord(q)-mp_take_fraction(mp, mp->delta_x[0],ff);
7780     left_y(q)=y_coord(q)-mp_take_fraction(mp, mp->delta_y[0],ff);
7781   }
7782   return;
7783 }
7784
7785 @* \[19] Measuring paths.
7786 \MP's \&{llcorner}, \&{lrcorner}, \&{ulcorner}, and \&{urcorner} operators
7787 allow the user to measure the bounding box of anything that can go into a
7788 picture.  It's easy to get rough bounds on the $x$ and $y$ extent of a path
7789 by just finding the bounding box of the knots and the control points. We
7790 need a more accurate version of the bounding box, but we can still use the
7791 easy estimate to save time by focusing on the interesting parts of the path.
7792
7793 @ Computing an accurate bounding box involves a theme that will come up again
7794 and again. Given a Bernshte{\u\i}n polynomial
7795 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
7796 $$B(z_0,z_1,\ldots,z_n;t)=\sum_k{n\choose k}t^k(1-t)^{n-k}z_k,$$
7797 we can conveniently bisect its range as follows:
7798
7799 \smallskip
7800 \textindent{1)} Let $z_k^{(0)}=z_k$, for |0<=k<=n|.
7801
7802 \smallskip
7803 \textindent{2)} Let $z_k^{(j+1)}={1\over2}(z_k^{(j)}+z\k^{(j)})$, for
7804 |0<=k<n-j|, for |0<=j<n|.
7805
7806 \smallskip\noindent
7807 Then
7808 $$B(z_0,z_1,\ldots,z_n;t)=B(z_0^{(0)},z_0^{(1)},\ldots,z_0^{(n)};2t)
7809  =B(z_0^{(n)},z_1^{(n-1)},\ldots,z_n^{(0)};2t-1).$$
7810 This formula gives us the coefficients of polynomials to use over the ranges
7811 $0\L t\L{1\over2}$ and ${1\over2}\L t\L1$.
7812
7813 @ Now here's a subroutine that's handy for all sorts of path computations:
7814 Given a quadratic polynomial $B(a,b,c;t)$, the |crossing_point| function
7815 returns the unique |fraction| value |t| between 0 and~1 at which
7816 $B(a,b,c;t)$ changes from positive to negative, or returns
7817 |t=fraction_one+1| if no such value exists. If |a<0| (so that $B(a,b,c;t)$
7818 is already negative at |t=0|), |crossing_point| returns the value zero.
7819
7820 @d no_crossing {  return (fraction_one+1); }
7821 @d one_crossing { return fraction_one; }
7822 @d zero_crossing { return 0; }
7823 @d mp_crossing_point(M,A,B,C) mp_do_crossing_point(A,B,C)
7824
7825 @c fraction mp_do_crossing_point (integer a, integer b, integer c) {
7826   integer d; /* recursive counter */
7827   integer x,xx,x0,x1,x2; /* temporary registers for bisection */
7828   if ( a<0 ) zero_crossing;
7829   if ( c>=0 ) { 
7830     if ( b>=0 ) {
7831       if ( c>0 ) { no_crossing; }
7832       else if ( (a==0)&&(b==0) ) { no_crossing;} 
7833       else { one_crossing; } 
7834     }
7835     if ( a==0 ) zero_crossing;
7836   } else if ( a==0 ) {
7837     if ( b<=0 ) zero_crossing;
7838   }
7839   @<Use bisection to find the crossing point, if one exists@>;
7840 }
7841
7842 @ The general bisection method is quite simple when $n=2$, hence
7843 |crossing_point| does not take much time. At each stage in the
7844 recursion we have a subinterval defined by |l| and~|j| such that
7845 $B(a,b,c;2^{-l}(j+t))=B(x_0,x_1,x_2;t)$, and we want to ``zero in'' on
7846 the subinterval where $x_0\G0$ and $\min(x_1,x_2)<0$.
7847
7848 It is convenient for purposes of calculation to combine the values
7849 of |l| and~|j| in a single variable $d=2^l+j$, because the operation
7850 of bisection then corresponds simply to doubling $d$ and possibly
7851 adding~1. Furthermore it proves to be convenient to modify
7852 our previous conventions for bisection slightly, maintaining the
7853 variables $X_0=2^lx_0$, $X_1=2^l(x_0-x_1)$, and $X_2=2^l(x_1-x_2)$.
7854 With these variables the conditions $x_0\ge0$ and $\min(x_1,x_2)<0$ are
7855 equivalent to $\max(X_1,X_1+X_2)>X_0\ge0$.
7856
7857 The following code maintains the invariant relations
7858 $0\L|x0|<\max(|x1|,|x1|+|x2|)$,
7859 $\vert|x1|\vert<2^{30}$, $\vert|x2|\vert<2^{30}$;
7860 it has been constructed in such a way that no arithmetic overflow
7861 will occur if the inputs satisfy
7862 $a<2^{30}$, $\vert a-b\vert<2^{30}$, and $\vert b-c\vert<2^{30}$.
7863
7864 @<Use bisection to find the crossing point...@>=
7865 d=1; x0=a; x1=a-b; x2=b-c;
7866 do {  
7867   x=half(x1+x2);
7868   if ( x1-x0>x0 ) { 
7869     x2=x; x0+=x0; d+=d;  
7870   } else { 
7871     xx=x1+x-x0;
7872     if ( xx>x0 ) { 
7873       x2=x; x0+=x0; d+=d;
7874     }  else { 
7875       x0=x0-xx;
7876       if ( x<=x0 ) { if ( x+x2<=x0 ) no_crossing; }
7877       x1=x; d=d+d+1;
7878     }
7879   }
7880 } while (d<fraction_one);
7881 return (d-fraction_one)
7882
7883 @ Here is a routine that computes the $x$ or $y$ coordinate of the point on
7884 a cubic corresponding to the |fraction| value~|t|.
7885
7886 It is convenient to define a \.{WEB} macro |t_of_the_way| such that
7887 |t_of_the_way(a,b)| expands to |a-(a-b)*t|, i.e., to |t[a,b]|.
7888
7889 @d t_of_the_way(A,B) ((A)-mp_take_fraction(mp,(A)-(B),t))
7890
7891 @c scaled mp_eval_cubic (MP mp,pointer p, pointer q, fraction t) {
7892   scaled x1,x2,x3; /* intermediate values */
7893   x1=t_of_the_way(knot_coord(p),right_coord(p));
7894   x2=t_of_the_way(right_coord(p),left_coord(q));
7895   x3=t_of_the_way(left_coord(q),knot_coord(q));
7896   x1=t_of_the_way(x1,x2);
7897   x2=t_of_the_way(x2,x3);
7898   return t_of_the_way(x1,x2);
7899 }
7900
7901 @ The actual bounding box information is stored in global variables.
7902 Since it is convenient to address the $x$ and $y$ information
7903 separately, we define arrays indexed by |x_code..y_code| and use
7904 macros to give them more convenient names.
7905
7906 @<Types...@>=
7907 enum {
7908   mp_x_code=0, /* index for |minx| and |maxx| */
7909   mp_y_code /* index for |miny| and |maxy| */
7910 };
7911
7912
7913 @d minx mp->bbmin[mp_x_code]
7914 @d maxx mp->bbmax[mp_x_code]
7915 @d miny mp->bbmin[mp_y_code]
7916 @d maxy mp->bbmax[mp_y_code]
7917
7918 @<Glob...@>=
7919 scaled bbmin[mp_y_code+1];
7920 scaled bbmax[mp_y_code+1]; 
7921 /* the result of procedures that compute bounding box information */
7922
7923 @ Now we're ready for the key part of the bounding box computation.
7924 The |bound_cubic| procedure updates |bbmin[c]| and |bbmax[c]| based on
7925 $$B(\hbox{|knot_coord(p)|}, \hbox{|right_coord(p)|},
7926     \hbox{|left_coord(q)|}, \hbox{|knot_coord(q)|};t)
7927 $$
7928 for $0<t\le1$.  In other words, the procedure adjusts the bounds to
7929 accommodate |knot_coord(q)| and any extremes over the range $0<t<1$.
7930 The |c| parameter is |x_code| or |y_code|.
7931
7932 @c void mp_bound_cubic (MP mp,pointer p, pointer q, small_number c) {
7933   boolean wavy; /* whether we need to look for extremes */
7934   scaled del1,del2,del3,del,dmax; /* proportional to the control
7935      points of a quadratic derived from a cubic */
7936   fraction t,tt; /* where a quadratic crosses zero */
7937   scaled x; /* a value that |bbmin[c]| and |bbmax[c]| must accommodate */
7938   x=knot_coord(q);
7939   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
7940   @<Check the control points against the bounding box and set |wavy:=true|
7941     if any of them lie outside@>;
7942   if ( wavy ) {
7943     del1=right_coord(p)-knot_coord(p);
7944     del2=left_coord(q)-right_coord(p);
7945     del3=knot_coord(q)-left_coord(q);
7946     @<Scale up |del1|, |del2|, and |del3| for greater accuracy;
7947       also set |del| to the first nonzero element of |(del1,del2,del3)|@>;
7948     if ( del<0 ) {
7949       negate(del1); negate(del2); negate(del3);
7950     };
7951     t=mp_crossing_point(mp, del1,del2,del3);
7952     if ( t<fraction_one ) {
7953       @<Test the extremes of the cubic against the bounding box@>;
7954     }
7955   }
7956 }
7957
7958 @ @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>=
7959 if ( x<mp->bbmin[c] ) mp->bbmin[c]=x;
7960 if ( x>mp->bbmax[c] ) mp->bbmax[c]=x
7961
7962 @ @<Check the control points against the bounding box and set...@>=
7963 wavy=true;
7964 if ( mp->bbmin[c]<=right_coord(p) )
7965   if ( right_coord(p)<=mp->bbmax[c] )
7966     if ( mp->bbmin[c]<=left_coord(q) )
7967       if ( left_coord(q)<=mp->bbmax[c] )
7968         wavy=false
7969
7970 @ If |del1=del2=del3=0|, it's impossible to obey the title of this
7971 section. We just set |del=0| in that case.
7972
7973 @<Scale up |del1|, |del2|, and |del3| for greater accuracy...@>=
7974 if ( del1!=0 ) del=del1;
7975 else if ( del2!=0 ) del=del2;
7976 else del=del3;
7977 if ( del!=0 ) {
7978   dmax=abs(del1);
7979   if ( abs(del2)>dmax ) dmax=abs(del2);
7980   if ( abs(del3)>dmax ) dmax=abs(del3);
7981   while ( dmax<fraction_half ) {
7982     dmax+=dmax; del1+=del1; del2+=del2; del3+=del3;
7983   }
7984 }
7985
7986 @ Since |crossing_point| has tried to choose |t| so that
7987 $B(|del1|,|del2|,|del3|;\tau)$ crosses zero at $\tau=|t|$ with negative
7988 slope, the value of |del2| computed below should not be positive.
7989 But rounding error could make it slightly positive in which case we
7990 must cut it to zero to avoid confusion.
7991
7992 @<Test the extremes of the cubic against the bounding box@>=
7993
7994   x=mp_eval_cubic(mp, p,q,t);
7995   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
7996   del2=t_of_the_way(del2,del3);
7997     /* now |0,del2,del3| represent the derivative on the remaining interval */
7998   if ( del2>0 ) del2=0;
7999   tt=mp_crossing_point(mp, 0,-del2,-del3);
8000   if ( tt<fraction_one ) {
8001     @<Test the second extreme against the bounding box@>;
8002   }
8003 }
8004
8005 @ @<Test the second extreme against the bounding box@>=
8006 {
8007    x=mp_eval_cubic(mp, p,q,t_of_the_way(tt,fraction_one));
8008   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8009 }
8010
8011 @ Finding the bounding box of a path is basically a matter of applying
8012 |bound_cubic| twice for each pair of adjacent knots.
8013
8014 @c void mp_path_bbox (MP mp,pointer h) {
8015   pointer p,q; /* a pair of adjacent knots */
8016    minx=x_coord(h); miny=y_coord(h);
8017   maxx=minx; maxy=miny;
8018   p=h;
8019   do {  
8020     if ( right_type(p)==endpoint ) return;
8021     q=link(p);
8022     mp_bound_cubic(mp, x_loc(p),x_loc(q),mp_x_code);
8023     mp_bound_cubic(mp, y_loc(p),y_loc(q),mp_y_code);
8024     p=q;
8025   } while (p!=h);
8026 }
8027
8028 @ Another important way to measure a path is to find its arc length.  This
8029 is best done by using the general bisection algorithm to subdivide the path
8030 until obtaining ``well behaved'' subpaths whose arc lengths can be approximated
8031 by simple means.
8032
8033 Since the arc length is the integral with respect to time of the magnitude of
8034 the velocity, it is natural to use Simpson's rule for the approximation.
8035 @^Simpson's rule@>
8036 If $\dot B(t)$ is the spline velocity, Simpson's rule gives
8037 $$ \vb\dot B(0)\vb + 4\vb\dot B({1\over2})\vb + \vb\dot B(1)\vb \over 6 $$
8038 for the arc length of a path of length~1.  For a cubic spline
8039 $B(z_0,z_1,z_2,z_3;t)$, the time derivative $\dot B(t)$ is
8040 $3B(dz_0,dz_1,dz_2;t)$, where $dz_i=z_{i+1}-z_i$.  Hence the arc length
8041 approximation is
8042 $$ {\vb dz_0\vb \over 2} + 2\vb dz_{02}\vb + {\vb dz_2\vb \over 2}, $$
8043 where
8044 $$ dz_{02}={1\over2}\left({dz_0+dz_1\over 2}+{dz_1+dz_2\over 2}\right)$$
8045 is the result of the bisection algorithm.
8046
8047 @ The remaining problem is how to decide when a subpath is ``well behaved.''
8048 This could be done via the theoretical error bound for Simpson's rule,
8049 @^Simpson's rule@>
8050 but this is impractical because it requires an estimate of the fourth
8051 derivative of the quantity being integrated.  It is much easier to just perform
8052 a bisection step and see how much the arc length estimate changes.  Since the
8053 error for Simpson's rule is proportional to the fourth power of the sample
8054 spacing, the remaining error is typically about $1\over16$ of the amount of
8055 the change.  We say ``typically'' because the error has a pseudo-random behavior
8056 that could cause the two estimates to agree when each contain large errors.
8057
8058 To protect against disasters such as undetected cusps, the bisection process
8059 should always continue until all the $dz_i$ vectors belong to a single
8060 $90^\circ$ sector.  This ensures that no point on the spline can have velocity
8061 less than 70\% of the minimum of $\vb dz_0\vb$, $\vb dz_1\vb$ and $\vb dz_2\vb$.
8062 If such a spline happens to produce an erroneous arc length estimate that
8063 is little changed by bisection, the amount of the error is likely to be fairly
8064 small.  We will try to arrange things so that freak accidents of this type do
8065 not destroy the inverse relationship between the \&{arclength} and
8066 \&{arctime} operations.
8067 @:arclength_}{\&{arclength} primitive@>
8068 @:arctime_}{\&{arctime} primitive@>
8069
8070 @ The \&{arclength} and \&{arctime} operations are both based on a recursive
8071 @^recursion@>
8072 function that finds the arc length of a cubic spline given $dz_0$, $dz_1$,
8073 $dz_2$. This |arc_test| routine also takes an arc length goal |a_goal| and
8074 returns the time when the arc length reaches |a_goal| if there is such a time.
8075 Thus the return value is either an arc length less than |a_goal| or, if the
8076 arc length would be at least |a_goal|, it returns a time value decreased by
8077 |two|.  This allows the caller to use the sign of the result to distinguish
8078 between arc lengths and time values.  On certain types of overflow, it is
8079 possible for |a_goal| and the result of |arc_test| both to be |el_gordo|.
8080 Otherwise, the result is always less than |a_goal|.
8081
8082 Rather than halving the control point coordinates on each recursive call to
8083 |arc_test|, it is better to keep them proportional to velocity on the original
8084 curve and halve the results instead.  This means that recursive calls can
8085 potentially use larger error tolerances in their arc length estimates.  How
8086 much larger depends on to what extent the errors behave as though they are
8087 independent of each other.  To save computing time, we use optimistic assumptions
8088 and increase the tolerance by a factor of about $\sqrt2$ for each recursive
8089 call.
8090
8091 In addition to the tolerance parameter, |arc_test| should also have parameters
8092 for ${1\over3}\vb\dot B(0)\vb$, ${2\over3}\vb\dot B({1\over2})\vb$, and
8093 ${1\over3}\vb\dot B(1)\vb$.  These quantities are relatively expensive to compute
8094 and they are needed in different instances of |arc_test|.
8095
8096 @c @t\4@>@<Declare subroutines needed by |arc_test|@>;
8097 scaled mp_arc_test (MP mp, scaled dx0, scaled dy0, scaled dx1, scaled dy1, 
8098                     scaled dx2, scaled dy2, scaled  v0, scaled v02, 
8099                     scaled v2, scaled a_goal, scaled tol) {
8100   boolean simple; /* are the control points confined to a $90^\circ$ sector? */
8101   scaled dx01, dy01, dx12, dy12, dx02, dy02;  /* bisection results */
8102   scaled v002, v022;
8103     /* twice the velocity magnitudes at $t={1\over4}$ and $t={3\over4}$ */
8104   scaled arc; /* best arc length estimate before recursion */
8105   @<Other local variables in |arc_test|@>;
8106   @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,
8107     |dx2|, |dy2|@>;
8108   @<Initialize |v002|, |v022|, and the arc length estimate |arc|; if it overflows
8109     set |arc_test| and |return|@>;
8110   @<Test if the control points are confined to one quadrant or rotating them
8111     $45^\circ$ would put them in one quadrant.  Then set |simple| appropriately@>;
8112   if ( simple && (abs(arc-v02-halfp(v0+v2)) <= tol) ) {
8113     if ( arc < a_goal ) {
8114       return arc;
8115     } else {
8116        @<Estimate when the arc length reaches |a_goal| and set |arc_test| to
8117          that time minus |two|@>;
8118     }
8119   } else {
8120     @<Use one or two recursive calls to compute the |arc_test| function@>;
8121   }
8122 }
8123
8124 @ The |tol| value should by multiplied by $\sqrt 2$ before making recursive
8125 calls, but $1.5$ is an adequate approximation.  It is best to avoid using
8126 |make_fraction| in this inner loop.
8127 @^inner loop@>
8128
8129 @<Use one or two recursive calls to compute the |arc_test| function@>=
8130
8131   @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is as
8132     large as possible@>;
8133   tol = tol + halfp(tol);
8134   a = mp_arc_test(mp, dx0,dy0, dx01,dy01, dx02,dy02, v0, v002, 
8135                   halfp(v02), a_new, tol);
8136   if ( a<0 )  {
8137      return (-halfp(two-a));
8138   } else { 
8139     @<Update |a_new| to reduce |a_new+a_aux| by |a|@>;
8140     b = mp_arc_test(mp, dx02,dy02, dx12,dy12, dx2,dy2,
8141                     halfp(v02), v022, v2, a_new, tol);
8142     if ( b<0 )  
8143       return (-halfp(-b) - half_unit);
8144     else  
8145       return (a + half(b-a));
8146   }
8147 }
8148
8149 @ @<Other local variables in |arc_test|@>=
8150 scaled a,b; /* results of recursive calls */
8151 scaled a_new,a_aux; /* the sum of these gives the |a_goal| */
8152
8153 @ @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is...@>=
8154 a_aux = el_gordo - a_goal;
8155 if ( a_goal > a_aux ) {
8156   a_aux = a_goal - a_aux;
8157   a_new = el_gordo;
8158 } else { 
8159   a_new = a_goal + a_goal;
8160   a_aux = 0;
8161 }
8162
8163 @ There is no need to maintain |a_aux| at this point so we use it as a temporary
8164 to force the additions and subtractions to be done in an order that avoids
8165 overflow.
8166
8167 @<Update |a_new| to reduce |a_new+a_aux| by |a|@>=
8168 if ( a > a_aux ) {
8169   a_aux = a_aux - a;
8170   a_new = a_new + a_aux;
8171 }
8172
8173 @ This code assumes all {\it dx} and {\it dy} variables have magnitude less than
8174 |fraction_four|.  To simplify the rest of the |arc_test| routine, we strengthen
8175 this assumption by requiring the norm of each $({\it dx},{\it dy})$ pair to obey
8176 this bound.  Note that recursive calls will maintain this invariant.
8177
8178 @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,...@>=
8179 dx01 = half(dx0 + dx1);
8180 dx12 = half(dx1 + dx2);
8181 dx02 = half(dx01 + dx12);
8182 dy01 = half(dy0 + dy1);
8183 dy12 = half(dy1 + dy2);
8184 dy02 = half(dy01 + dy12)
8185
8186 @ We should be careful to keep |arc<el_gordo| so that calling |arc_test| with
8187 |a_goal=el_gordo| is guaranteed to yield the arc length.
8188
8189 @<Initialize |v002|, |v022|, and the arc length estimate |arc|;...@>=
8190 v002 = mp_pyth_add(mp, dx01+half(dx0+dx02), dy01+half(dy0+dy02));
8191 v022 = mp_pyth_add(mp, dx12+half(dx02+dx2), dy12+half(dy02+dy2));
8192 tmp = halfp(v02+2);
8193 arc1 = v002 + half(halfp(v0+tmp) - v002);
8194 arc = v022 + half(halfp(v2+tmp) - v022);
8195 if ( (arc < el_gordo-arc1) )  {
8196   arc = arc+arc1;
8197 } else { 
8198   mp->arith_error = true;
8199   if ( a_goal==el_gordo )  return (el_gordo);
8200   else return (-two);
8201 }
8202
8203 @ @<Other local variables in |arc_test|@>=
8204 scaled tmp, tmp2; /* all purpose temporary registers */
8205 scaled arc1; /* arc length estimate for the first half */
8206
8207 @ @<Test if the control points are confined to one quadrant or rotating...@>=
8208 simple = ((dx0>=0) && (dx1>=0) && (dx2>=0)) ||
8209          ((dx0<=0) && (dx1<=0) && (dx2<=0));
8210 if ( simple )
8211   simple = ((dy0>=0) && (dy1>=0) && (dy2>=0)) ||
8212            ((dy0<=0) && (dy1<=0) && (dy2<=0));
8213 if ( ! simple ) {
8214   simple = ((dx0>=dy0) && (dx1>=dy1) && (dx2>=dy2)) ||
8215            ((dx0<=dy0) && (dx1<=dy1) && (dx2<=dy2));
8216   if ( simple ) 
8217     simple = ((-dx0>=dy0) && (-dx1>=dy1) && (-dx2>=dy2)) ||
8218              ((-dx0<=dy0) && (-dx1<=dy1) && (-dx2<=dy2));
8219 }
8220
8221 @ Since Simpson's rule is based on approximating the integrand by a parabola,
8222 @^Simpson's rule@>
8223 it is appropriate to use the same approximation to decide when the integral
8224 reaches the intermediate value |a_goal|.  At this point
8225 $$\eqalign{
8226     {\vb\dot B(0)\vb\over 3} &= \hbox{|v0|}, \qquad
8227     {\vb\dot B({1\over4})\vb\over 3} = {\hbox{|v002|}\over 2}, \qquad
8228     {\vb\dot B({1\over2})\vb\over 3} = {\hbox{|v02|}\over 2}, \cr
8229     {\vb\dot B({3\over4})\vb\over 3} &= {\hbox{|v022|}\over 2}, \qquad
8230     {\vb\dot B(1)\vb\over 3} = \hbox{|v2|} \cr
8231 }
8232 $$
8233 and
8234 $$ {\vb\dot B(t)\vb\over 3} \approx
8235   \cases{B\left(\hbox{|v0|},
8236       \hbox{|v002|}-{1\over 2}\hbox{|v0|}-{1\over 4}\hbox{|v02|},
8237       {1\over 2}\hbox{|v02|}; 2t \right)&
8238     if $t\le{1\over 2}$\cr
8239   B\left({1\over 2}\hbox{|v02|},
8240       \hbox{|v022|}-{1\over 4}\hbox{|v02|}-{1\over 2}\hbox{|v2|},
8241       \hbox{|v2|}; 2t-1 \right)&
8242     if $t\ge{1\over 2}$.\cr}
8243  \eqno (*)
8244 $$
8245 We can integrate $\vb\dot B(t)\vb$ by using
8246 $$\int 3B(a,b,c;\tau)\,dt =
8247   {B(0,a,a+b,a+b+c;\tau) + {\rm constant} \over {d\tau\over dt}}.
8248 $$
8249
8250 This construction allows us to find the time when the arc length reaches
8251 |a_goal| by solving a cubic equation of the form
8252 $$ B(0,a,a+b,a+b+c;\tau) = x, $$
8253 where $\tau$ is $2t$ or $2t+1$, $x$ is |a_goal| or |a_goal-arc1|, and $a$, $b$,
8254 and $c$ are the Bernshte{\u\i}n coefficients from $(*)$ divided by
8255 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
8256 $d\tau\over dt$.  We shall define a function |solve_rising_cubic| that finds
8257 $\tau$ given $a$, $b$, $c$, and $x$.
8258
8259 @<Estimate when the arc length reaches |a_goal| and set |arc_test| to...@>=
8260
8261   tmp = (v02 + 2) / 4;
8262   if ( a_goal<=arc1 ) {
8263     tmp2 = halfp(v0);
8264     return 
8265       (halfp(mp_solve_rising_cubic(mp, tmp2, arc1-tmp2-tmp, tmp, a_goal))- two);
8266   } else { 
8267     tmp2 = halfp(v2);
8268     return ((half_unit - two) +
8269       halfp(mp_solve_rising_cubic(mp, tmp, arc-arc1-tmp-tmp2, tmp2, a_goal-arc1)));
8270   }
8271 }
8272
8273 @ Here is the |solve_rising_cubic| routine that finds the time~$t$ when
8274 $$ B(0, a, a+b, a+b+c; t) = x. $$
8275 This routine is based on |crossing_point| but is simplified by the
8276 assumptions that $B(a,b,c;t)\ge0$ for $0\le t\le1$ and that |0<=x<=a+b+c|.
8277 If rounding error causes this condition to be violated slightly, we just ignore
8278 it and proceed with binary search.  This finds a time when the function value
8279 reaches |x| and the slope is positive.
8280
8281 @<Declare subroutines needed by |arc_test|@>=
8282 scaled mp_solve_rising_cubic (MP mp,scaled a, scaled b,  scaled c, scaled x) {
8283   scaled ab, bc, ac; /* bisection results */
8284   integer t; /* $2^k+q$ where unscaled answer is in $[q2^{-k},(q+1)2^{-k})$ */
8285   integer xx; /* temporary for updating |x| */
8286   if ( (a<0) || (c<0) ) mp_confusion(mp, "rising?");
8287 @:this can't happen rising?}{\quad rising?@>
8288   if ( x<=0 ) {
8289         return 0;
8290   } else if ( x >= a+b+c ) {
8291     return unity;
8292   } else { 
8293     t = 1;
8294     @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than
8295       |el_gordo div 3|@>;
8296     do {  
8297       t+=t;
8298       @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>;
8299       xx = x - a - ab - ac;
8300       if ( xx < -x ) { x+=x; b=ab; c=ac;  }
8301       else { x = x + xx;  a=ac; b=mp->bc; t = t+1; };
8302     } while (t < unity);
8303     return (t - unity);
8304   }
8305 }
8306
8307 @ @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>=
8308 ab = half(a+b);
8309 bc = half(b+c);
8310 ac = half(ab+bc)
8311
8312 @ @d one_third_el_gordo 05252525252 /* upper bound on |a|, |b|, and |c| */
8313
8314 @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than...@>=
8315 while ((a>one_third_el_gordo)||(b>one_third_el_gordo)||(c>one_third_el_gordo)) { 
8316   a = halfp(a);
8317   b = half(b);
8318   c = halfp(c);
8319   x = halfp(x);
8320 }
8321
8322 @ It is convenient to have a simpler interface to |arc_test| that requires no
8323 unnecessary arguments and ensures that each $({\it dx},{\it dy})$ pair has
8324 length less than |fraction_four|.
8325
8326 @d arc_tol   16  /* quit when change in arc length estimate reaches this */
8327
8328 @c scaled mp_do_arc_test (MP mp,scaled dx0, scaled dy0, scaled dx1, 
8329                           scaled dy1, scaled dx2, scaled dy2, scaled a_goal) {
8330   scaled v0,v1,v2; /* length of each $({\it dx},{\it dy})$ pair */
8331   scaled v02; /* twice the norm of the quadratic at $t={1\over2}$ */
8332   v0 = mp_pyth_add(mp, dx0,dy0);
8333   v1 = mp_pyth_add(mp, dx1,dy1);
8334   v2 = mp_pyth_add(mp, dx2,dy2);
8335   if ( (v0>=fraction_four) || (v1>=fraction_four) || (v2>=fraction_four) ) { 
8336     mp->arith_error = true;
8337     if ( a_goal==el_gordo )  return el_gordo;
8338     else return (-two);
8339   } else { 
8340     v02 = mp_pyth_add(mp, dx1+half(dx0+dx2), dy1+half(dy0+dy2));
8341     return (mp_arc_test(mp, dx0,dy0, dx1,dy1, dx2,dy2,
8342                                  v0, v02, v2, a_goal, arc_tol));
8343   }
8344 }
8345
8346 @ Now it is easy to find the arc length of an entire path.
8347
8348 @c scaled mp_get_arc_length (MP mp,pointer h) {
8349   pointer p,q; /* for traversing the path */
8350   scaled a,a_tot; /* current and total arc lengths */
8351   a_tot = 0;
8352   p = h;
8353   while ( right_type(p)!=endpoint ){ 
8354     q = link(p);
8355     a = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8356       left_x(q)-right_x(p), left_y(q)-right_y(p),
8357       x_coord(q)-left_x(q), y_coord(q)-left_y(q), el_gordo);
8358     a_tot = mp_slow_add(mp, a, a_tot);
8359     if ( q==h ) break;  else p=q;
8360   }
8361   check_arith;
8362   return a_tot;
8363 }
8364
8365 @ The inverse operation of finding the time on a path~|h| when the arc length
8366 reaches some value |arc0| can also be accomplished via |do_arc_test|.  Some care
8367 is required to handle very large times or negative times on cyclic paths.  For
8368 non-cyclic paths, |arc0| values that are negative or too large cause
8369 |get_arc_time| to return 0 or the length of path~|h|.
8370
8371 If |arc0| is greater than the arc length of a cyclic path~|h|, the result is a
8372 time value greater than the length of the path.  Since it could be much greater,
8373 we must be prepared to compute the arc length of path~|h| and divide this into
8374 |arc0| to find how many multiples of the length of path~|h| to add.
8375
8376 @c scaled mp_get_arc_time (MP mp,pointer h, scaled  arc0) {
8377   pointer p,q; /* for traversing the path */
8378   scaled t_tot; /* accumulator for the result */
8379   scaled t; /* the result of |do_arc_test| */
8380   scaled arc; /* portion of |arc0| not used up so far */
8381   integer n; /* number of extra times to go around the cycle */
8382   if ( arc0<0 ) {
8383     @<Deal with a negative |arc0| value and |return|@>;
8384   }
8385   if ( arc0==el_gordo ) decr(arc0);
8386   t_tot = 0;
8387   arc = arc0;
8388   p = h;
8389   while ( (right_type(p)!=endpoint) && (arc>0) ) {
8390     q = link(p);
8391     t = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8392       left_x(q)-right_x(p), left_y(q)-right_y(p),
8393       x_coord(q)-left_x(q), y_coord(q)-left_y(q), arc);
8394     @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>;
8395     if ( q==h ) {
8396       @<Update |t_tot| and |arc| to avoid going around the cyclic
8397         path too many times but set |arith_error:=true| and |goto done| on
8398         overflow@>;
8399     }
8400     p = q;
8401   }
8402   check_arith;
8403   return t_tot;
8404 }
8405
8406 @ @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>=
8407 if ( t<0 ) { t_tot = t_tot + t + two;  arc = 0;  }
8408 else { t_tot = t_tot + unity;  arc = arc - t;  }
8409
8410 @ @<Deal with a negative |arc0| value and |return|@>=
8411
8412   if ( left_type(h)==endpoint ) {
8413     t_tot=0;
8414   } else { 
8415     p = mp_htap_ypoc(mp, h);
8416     t_tot = -mp_get_arc_time(mp, p, -arc0);
8417     mp_toss_knot_list(mp, p);
8418   }
8419   check_arith;
8420   return t_tot;
8421 }
8422
8423 @ @<Update |t_tot| and |arc| to avoid going around the cyclic...@>=
8424 if ( arc>0 ) { 
8425   n = arc / (arc0 - arc);
8426   arc = arc - n*(arc0 - arc);
8427   if ( t_tot > el_gordo / (n+1) ) { 
8428     mp->arith_error = true;
8429     t_tot = el_gordo;
8430     break;
8431   }
8432   t_tot = (n + 1)*t_tot;
8433 }
8434
8435 @* \[20] Data structures for pens.
8436 A Pen in \MP\ can be either elliptical or polygonal.  Elliptical pens result
8437 in \ps\ \&{stroke} commands, while anything drawn with a polygonal pen is
8438 @:stroke}{\&{stroke} command@>
8439 converted into an area fill as described in the next part of this program.
8440 The mathematics behind this process is based on simple aspects of the theory
8441 of tracings developed by Leo Guibas, Lyle Ramshaw, and Jorge Stolfi
8442 [``A kinematic framework for computational geometry,'' Proc.\ IEEE Symp.\
8443 Foundations of Computer Science {\bf 24} (1983), 100--111].
8444
8445 Polygonal pens are created from paths via \MP's \&{makepen} primitive.
8446 @:makepen_}{\&{makepen} primitive@>
8447 This path representation is almost sufficient for our purposes except that
8448 a pen path should always be a convex polygon with the vertices in
8449 counter-clockwise order.
8450 Since we will need to scan pen polygons both forward and backward, a pen
8451 should be represented as a doubly linked ring of knot nodes.  There is
8452 room for the extra back pointer because we do not need the
8453 |left_type| or |right_type| fields.  In fact, we don't need the |left_x|,
8454 |left_y|, |right_x|, or |right_y| fields either but we leave these alone
8455 so that certain procedures can operate on both pens and paths.  In particular,
8456 pens can be copied using |copy_path| and recycled using |toss_knot_list|.
8457
8458 @d knil info
8459   /* this replaces the |left_type| and |right_type| fields in a pen knot */
8460
8461 @ The |make_pen| procedure turns a path into a pen by initializing
8462 the |knil| pointers and making sure the knots form a convex polygon.
8463 Thus each cubic in the given path becomes a straight line and the control
8464 points are ignored.  If the path is not cyclic, the ends are connected by a
8465 straight line.
8466
8467 @d copy_pen(A) mp_make_pen(mp, mp_copy_path(mp, (A)),false)
8468
8469 @c @<Declare a function called |convex_hull|@>;
8470 pointer mp_make_pen (MP mp,pointer h, boolean need_hull) {
8471   pointer p,q; /* two consecutive knots */
8472   q=h;
8473   do {  
8474     p=q; q=link(q);
8475     knil(q)=p;
8476   } while (q!=h);
8477   if ( need_hull ){ 
8478     h=mp_convex_hull(mp, h);
8479     @<Make sure |h| isn't confused with an elliptical pen@>;
8480   }
8481   return h;
8482 }
8483
8484 @ The only information required about an elliptical pen is the overall
8485 transformation that has been applied to the original \&{pencircle}.
8486 @:pencircle_}{\&{pencircle} primitive@>
8487 Since it suffices to keep track of how the three points $(0,0)$, $(1,0)$,
8488 and $(0,1)$ are transformed, an elliptical pen can be stored in a single
8489 knot node and transformed as if it were a path.
8490
8491 @d pen_is_elliptical(A) ((A)==link((A)))
8492
8493 @c pointer mp_get_pen_circle (MP mp,scaled diam) {
8494   pointer h; /* the knot node to return */
8495   h=mp_get_node(mp, knot_node_size);
8496   link(h)=h; knil(h)=h;
8497   originator(h)=program_code;
8498   x_coord(h)=0; y_coord(h)=0;
8499   left_x(h)=diam; left_y(h)=0;
8500   right_x(h)=0; right_y(h)=diam;
8501   return h;
8502 }
8503
8504 @ If the polygon being returned by |make_pen| has only one vertex, it will
8505 be interpreted as an elliptical pen.  This is no problem since a degenerate
8506 polygon can equally well be thought of as a degenerate ellipse.  We need only
8507 initialize the |left_x|, |left_y|, |right_x|, and |right_y| fields.
8508
8509 @<Make sure |h| isn't confused with an elliptical pen@>=
8510 if ( pen_is_elliptical( h) ){ 
8511   left_x(h)=x_coord(h); left_y(h)=y_coord(h);
8512   right_x(h)=x_coord(h); right_y(h)=y_coord(h);
8513 }
8514
8515 @ We have to cheat a little here but most operations on pens only use
8516 the first three words in each knot node.
8517 @^data structure assumptions@>
8518
8519 @<Initialize a pen at |test_pen| so that it fits in nine words@>=
8520 x_coord(test_pen)=-half_unit;
8521 y_coord(test_pen)=0;
8522 x_coord(test_pen+3)=half_unit;
8523 y_coord(test_pen+3)=0;
8524 x_coord(test_pen+6)=0;
8525 y_coord(test_pen+6)=unity;
8526 link(test_pen)=test_pen+3;
8527 link(test_pen+3)=test_pen+6;
8528 link(test_pen+6)=test_pen;
8529 knil(test_pen)=test_pen+6;
8530 knil(test_pen+3)=test_pen;
8531 knil(test_pen+6)=test_pen+3
8532
8533 @ Printing a polygonal pen is very much like printing a path
8534
8535 @<Declare subroutines for printing expressions@>=
8536 void mp_pr_pen (MP mp,pointer h) {
8537   pointer p,q; /* for list traversal */
8538   if ( pen_is_elliptical(h) ) {
8539     @<Print the elliptical pen |h|@>;
8540   } else { 
8541     p=h;
8542     do {  
8543       mp_print_two(mp, x_coord(p),y_coord(p));
8544       mp_print_nl(mp, " .. ");
8545       @<Advance |p| making sure the links are OK and |return| if there is
8546         a problem@>;
8547      } while (p!=h);
8548      mp_print(mp, "cycle");
8549   }
8550 }
8551
8552 @ @<Advance |p| making sure the links are OK and |return| if there is...@>=
8553 q=link(p);
8554 if ( (q==null) || (knil(q)!=p) ) { 
8555   mp_print_nl(mp, "???"); return; /* this won't happen */
8556 @.???@>
8557 }
8558 p=q
8559
8560 @ @<Print the elliptical pen |h|@>=
8561
8562 mp_print(mp, "pencircle transformed (");
8563 mp_print_scaled(mp, x_coord(h));
8564 mp_print_char(mp, ',');
8565 mp_print_scaled(mp, y_coord(h));
8566 mp_print_char(mp, ',');
8567 mp_print_scaled(mp, left_x(h)-x_coord(h));
8568 mp_print_char(mp, ',');
8569 mp_print_scaled(mp, right_x(h)-x_coord(h));
8570 mp_print_char(mp, ',');
8571 mp_print_scaled(mp, left_y(h)-y_coord(h));
8572 mp_print_char(mp, ',');
8573 mp_print_scaled(mp, right_y(h)-y_coord(h));
8574 mp_print_char(mp, ')');
8575 }
8576
8577 @ Here us another version of |pr_pen| that prints the pen as a diagnostic
8578 message.
8579
8580 @<Declare subroutines for printing expressions@>=
8581 void mp_print_pen (MP mp,pointer h, char *s, boolean nuline) { 
8582   mp_print_diagnostic(mp, "Pen",s,nuline); mp_print_ln(mp);
8583 @.Pen at line...@>
8584   mp_pr_pen(mp, h);
8585   mp_end_diagnostic(mp, true);
8586 }
8587
8588 @ Making a polygonal pen into a path involves restoring the |left_type| and
8589 |right_type| fields and setting the control points so as to make a polygonal
8590 path.
8591
8592 @c 
8593 void mp_make_path (MP mp,pointer h) {
8594   pointer p; /* for traversing the knot list */
8595   small_number k; /* a loop counter */
8596   @<Other local variables in |make_path|@>;
8597   if ( pen_is_elliptical(h) ) {
8598     @<Make the elliptical pen |h| into a path@>;
8599   } else { 
8600     p=h;
8601     do {  
8602       left_type(p)=explicit;
8603       right_type(p)=explicit;
8604       @<copy the coordinates of knot |p| into its control points@>;
8605        p=link(p);
8606     } while (p!=h);
8607   }
8608 }
8609
8610 @ @<copy the coordinates of knot |p| into its control points@>=
8611 left_x(p)=x_coord(p);
8612 left_y(p)=y_coord(p);
8613 right_x(p)=x_coord(p);
8614 right_y(p)=y_coord(p)
8615
8616 @ We need an eight knot path to get a good approximation to an ellipse.
8617
8618 @<Make the elliptical pen |h| into a path@>=
8619
8620   @<Extract the transformation parameters from the elliptical pen~|h|@>;
8621   p=h;
8622   for (k=0;k<=7;k++ ) { 
8623     @<Initialize |p| as the |k|th knot of a circle of unit diameter,
8624       transforming it appropriately@>;
8625     if ( k==7 ) link(p)=h;  else link(p)=mp_get_node(mp, knot_node_size);
8626     p=link(p);
8627   }
8628 }
8629
8630 @ @<Extract the transformation parameters from the elliptical pen~|h|@>=
8631 center_x=x_coord(h);
8632 center_y=y_coord(h);
8633 width_x=left_x(h)-center_x;
8634 width_y=left_y(h)-center_y;
8635 height_x=right_x(h)-center_x;
8636 height_y=right_y(h)-center_y
8637
8638 @ @<Other local variables in |make_path|@>=
8639 scaled center_x,center_y; /* translation parameters for an elliptical pen */
8640 scaled width_x,width_y; /* the effect of a unit change in $x$ */
8641 scaled height_x,height_y; /* the effect of a unit change in $y$ */
8642 scaled dx,dy; /* the vector from knot |p| to its right control point */
8643 integer kk;
8644   /* |k| advanced $270^\circ$ around the ring (cf. $\sin\theta=\cos(\theta+270)$) */
8645
8646 @ The only tricky thing here are the tables |half_cos| and |d_cos| used to
8647 find the point $k/8$ of the way around the circle and the direction vector
8648 to use there.
8649
8650 @<Initialize |p| as the |k|th knot of a circle of unit diameter,...@>=
8651 kk=(k+6)% 8;
8652 x_coord(p)=center_x+mp_take_fraction(mp, mp->half_cos[k],width_x)
8653            +mp_take_fraction(mp, mp->half_cos[kk],height_x);
8654 y_coord(p)=center_y+mp_take_fraction(mp, mp->half_cos[k],width_y)
8655            +mp_take_fraction(mp, mp->half_cos[kk],height_y);
8656 dx=-mp_take_fraction(mp, mp->d_cos[kk],width_x)
8657    +mp_take_fraction(mp, mp->d_cos[k],height_x);
8658 dy=-mp_take_fraction(mp, mp->d_cos[kk],width_y)
8659    +mp_take_fraction(mp, mp->d_cos[k],height_y);
8660 right_x(p)=x_coord(p)+dx;
8661 right_y(p)=y_coord(p)+dy;
8662 left_x(p)=x_coord(p)-dx;
8663 left_y(p)=y_coord(p)-dy;
8664 left_type(p)=explicit;
8665 right_type(p)=explicit;
8666 originator(p)=program_code
8667
8668 @ @<Glob...@>=
8669 fraction half_cos[8]; /* ${1\over2}\cos(45k)$ */
8670 fraction d_cos[8]; /* a magic constant times $\cos(45k)$ */
8671
8672 @ The magic constant for |d_cos| is the distance between $({1\over2},0)$ and
8673 $({1\over4}\sqrt2,{1\over4}\sqrt2)$ times the result of the |velocity|
8674 function for $\theta=\phi=22.5^\circ$.  This comes out to be
8675 $$ d = {\sqrt{2-\sqrt2}\over 3+3\cos22.5^\circ}
8676   \approx 0.132608244919772.
8677 $$
8678
8679 @<Set init...@>=
8680 mp->half_cos[0]=fraction_half;
8681 mp->half_cos[1]=94906266; /* $2^{26}\sqrt2\approx94906265.62$ */
8682 mp->half_cos[2]=0;
8683 mp->d_cos[0]=35596755; /* $2^{28}d\approx35596754.69$ */
8684 mp->d_cos[1]=25170707; /* $2^{27}\sqrt2\,d\approx25170706.63$ */
8685 mp->d_cos[2]=0;
8686 for (k=3;k<= 4;k++ ) { 
8687   mp->half_cos[k]=-mp->half_cos[4-k];
8688   mp->d_cos[k]=-mp->d_cos[4-k];
8689 }
8690 for (k=5;k<= 7;k++ ) { 
8691   mp->half_cos[k]=mp->half_cos[8-k];
8692   mp->d_cos[k]=mp->d_cos[8-k];
8693 }
8694
8695 @ The |convex_hull| function forces a pen polygon to be convex when it is
8696 returned by |make_pen| and after any subsequent transformation where rounding
8697 error might allow the convexity to be lost.
8698 The convex hull algorithm used here is described by F.~P. Preparata and
8699 M.~I. Shamos [{\sl Computational Geometry}, Springer-Verlag, 1985].
8700
8701 @<Declare a function called |convex_hull|@>=
8702 @<Declare a procedure called |move_knot|@>;
8703 pointer mp_convex_hull (MP mp,pointer h) { /* Make a polygonal pen convex */
8704   pointer l,r; /* the leftmost and rightmost knots */
8705   pointer p,q; /* knots being scanned */
8706   pointer s; /* the starting point for an upcoming scan */
8707   scaled dx,dy; /* a temporary pointer */
8708   if ( pen_is_elliptical(h) ) {
8709      return h;
8710   } else { 
8711     @<Set |l| to the leftmost knot in polygon~|h|@>;
8712     @<Set |r| to the rightmost knot in polygon~|h|@>;
8713     if ( l!=r ) { 
8714       s=link(r);
8715       @<Find any knots on the path from |l| to |r| above the |l|-|r| line and
8716         move them past~|r|@>;
8717       @<Find any knots on the path from |s| to |l| below the |l|-|r| line and
8718         move them past~|l|@>;
8719       @<Sort the path from |l| to |r| by increasing $x$@>;
8720       @<Sort the path from |r| to |l| by decreasing $x$@>;
8721     }
8722     if ( l!=link(l) ) {
8723       @<Do a Gramm scan and remove vertices where there is no left turn@>;
8724     }
8725     return l;
8726   }
8727 }
8728
8729 @ All comparisons are done primarily on $x$ and secondarily on $y$.
8730
8731 @<Set |l| to the leftmost knot in polygon~|h|@>=
8732 l=h;
8733 p=link(h);
8734 while ( p!=h ) { 
8735   if ( x_coord(p)<=x_coord(l) )
8736     if ( (x_coord(p)<x_coord(l)) || (y_coord(p)<y_coord(l)) )
8737       l=p;
8738   p=link(p);
8739 }
8740
8741 @ @<Set |r| to the rightmost knot in polygon~|h|@>=
8742 r=h;
8743 p=link(h);
8744 while ( p!=h ) { 
8745   if ( x_coord(p)>=x_coord(r) )
8746     if ( (x_coord(p)>x_coord(r)) || (y_coord(p)>y_coord(r)) )
8747       r=p;
8748   p=link(p);
8749 }
8750
8751 @ @<Find any knots on the path from |l| to |r| above the |l|-|r| line...@>=
8752 dx=x_coord(r)-x_coord(l);
8753 dy=y_coord(r)-y_coord(l);
8754 p=link(l);
8755 while ( p!=r ) { 
8756   q=link(p);
8757   if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))>0 )
8758     mp_move_knot(mp, p, r);
8759   p=q;
8760 }
8761
8762 @ The |move_knot| procedure removes |p| from a doubly linked list and inserts
8763 it after |q|.
8764
8765 @ @<Declare a procedure called |move_knot|@>=
8766 void mp_move_knot (MP mp,pointer p, pointer q) { 
8767   link(knil(p))=link(p);
8768   knil(link(p))=knil(p);
8769   knil(p)=q;
8770   link(p)=link(q);
8771   link(q)=p;
8772   knil(link(p))=p;
8773 }
8774
8775 @ @<Find any knots on the path from |s| to |l| below the |l|-|r| line...@>=
8776 p=s;
8777 while ( p!=l ) { 
8778   q=link(p);
8779   if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))<0 )
8780     mp_move_knot(mp, p,l);
8781   p=q;
8782 }
8783
8784 @ The list is likely to be in order already so we just do linear insertions.
8785 Secondary comparisons on $y$ ensure that the sort is consistent with the
8786 choice of |l| and |r|.
8787
8788 @<Sort the path from |l| to |r| by increasing $x$@>=
8789 p=link(l);
8790 while ( p!=r ) { 
8791   q=knil(p);
8792   while ( x_coord(q)>x_coord(p) ) q=knil(q);
8793   while ( x_coord(q)==x_coord(p) ) {
8794     if ( y_coord(q)>y_coord(p) ) q=knil(q); else break;
8795   }
8796   if ( q==knil(p) ) p=link(p);
8797   else { p=link(p); mp_move_knot(mp, knil(p),q); };
8798 }
8799
8800 @ @<Sort the path from |r| to |l| by decreasing $x$@>=
8801 p=link(r);
8802 while ( p!=l ){ 
8803   q=knil(p);
8804   while ( x_coord(q)<x_coord(p) ) q=knil(q);
8805   while ( x_coord(q)==x_coord(p) ) {
8806     if ( y_coord(q)<y_coord(p) ) q=knil(q); else break;
8807   }
8808   if ( q==knil(p) ) p=link(p);
8809   else { p=link(p); mp_move_knot(mp, knil(p),q); };
8810 }
8811
8812 @ The condition involving |ab_vs_cd| tests if there is not a left turn
8813 at knot |q|.  There usually will be a left turn so we streamline the case
8814 where the |then| clause is not executed.
8815
8816 @<Do a Gramm scan and remove vertices where there...@>=
8817
8818 p=l; q=link(l);
8819 while (1) { 
8820   dx=x_coord(q)-x_coord(p);
8821   dy=y_coord(q)-y_coord(p);
8822   p=q; q=link(q);
8823   if ( p==l ) break;
8824   if ( p!=r )
8825     if ( mp_ab_vs_cd(mp, dx,y_coord(q)-y_coord(p),dy,x_coord(q)-x_coord(p))<=0 ) {
8826       @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>;
8827     }
8828   }
8829 }
8830
8831 @ @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>=
8832
8833 s=knil(p);
8834 mp_free_node(mp, p,knot_node_size);
8835 link(s)=q; knil(q)=s;
8836 if ( s==l ) p=s;
8837 else { p=knil(s); q=s; };
8838 }
8839
8840 @ The |find_offset| procedure sets global variables |(cur_x,cur_y)| to the
8841 offset associated with the given direction |(x,y)|.  If two different offsets
8842 apply, it chooses one of them.
8843
8844 @c 
8845 void mp_find_offset (MP mp,scaled x, scaled y, pointer h) {
8846   pointer p,q; /* consecutive knots */
8847   scaled wx,wy,hx,hy;
8848   /* the transformation matrix for an elliptical pen */
8849   fraction xx,yy; /* untransformed offset for an elliptical pen */
8850   fraction d; /* a temporary register */
8851   if ( pen_is_elliptical(h) ) {
8852     @<Find the offset for |(x,y)| on the elliptical pen~|h|@>
8853   } else { 
8854     q=h;
8855     do {  
8856       p=q; q=link(q);
8857     } while (! mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)>=0);
8858     do {  
8859       p=q; q=link(q);
8860     } while (! mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)<=0);
8861     mp->cur_x=x_coord(p);
8862     mp->cur_y=y_coord(p);
8863   }
8864 }
8865
8866 @ @<Glob...@>=
8867 scaled cur_x;
8868 scaled cur_y; /* all-purpose return value registers */
8869
8870 @ @<Find the offset for |(x,y)| on the elliptical pen~|h|@>=
8871 if ( (x==0) && (y==0) ) {
8872   mp->cur_x=x_coord(h); mp->cur_y=y_coord(h);  
8873 } else { 
8874   @<Find the non-constant part of the transformation for |h|@>;
8875   while ( (abs(x)<fraction_half) && (abs(y)<fraction_half) ){ 
8876     x+=x; y+=y;  
8877   };
8878   @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the
8879     untransformed version of |(x,y)|@>;
8880   mp->cur_x=x_coord(h)+mp_take_fraction(mp, xx,wx)+mp_take_fraction(mp, yy,hx);
8881   mp->cur_y=y_coord(h)+mp_take_fraction(mp, xx,wy)+mp_take_fraction(mp, yy,hy);
8882 }
8883
8884 @ @<Find the non-constant part of the transformation for |h|@>=
8885 wx=left_x(h)-x_coord(h);
8886 wy=left_y(h)-y_coord(h);
8887 hx=right_x(h)-x_coord(h);
8888 hy=right_y(h)-y_coord(h)
8889
8890 @ @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the...@>=
8891 yy=-(mp_take_fraction(mp, x,hy)+mp_take_fraction(mp, y,-hx));
8892 xx=mp_take_fraction(mp, x,-wy)+mp_take_fraction(mp, y,wx);
8893 d=mp_pyth_add(mp, xx,yy);
8894 if ( d>0 ) { 
8895   xx=half(mp_make_fraction(mp, xx,d));
8896   yy=half(mp_make_fraction(mp, yy,d));
8897 }
8898
8899 @ Finding the bounding box of a pen is easy except if the pen is elliptical.
8900 But we can handle that case by just calling |find_offset| twice.  The answer
8901 is stored in the global variables |minx|, |maxx|, |miny|, and |maxy|.
8902
8903 @c 
8904 void mp_pen_bbox (MP mp,pointer h) {
8905   pointer p; /* for scanning the knot list */
8906   if ( pen_is_elliptical(h) ) {
8907     @<Find the bounding box of an elliptical pen@>;
8908   } else { 
8909     minx=x_coord(h); maxx=minx;
8910     miny=y_coord(h); maxy=miny;
8911     p=link(h);
8912     while ( p!=h ) {
8913       if ( x_coord(p)<minx ) minx=x_coord(p);
8914       if ( y_coord(p)<miny ) miny=y_coord(p);
8915       if ( x_coord(p)>maxx ) maxx=x_coord(p);
8916       if ( y_coord(p)>maxy ) maxy=y_coord(p);
8917       p=link(p);
8918     }
8919   }
8920 }
8921
8922 @ @<Find the bounding box of an elliptical pen@>=
8923
8924 mp_find_offset(mp, 0,fraction_one,h);
8925 maxx=mp->cur_x;
8926 minx=2*x_coord(h)-mp->cur_x;
8927 mp_find_offset(mp, -fraction_one,0,h);
8928 maxy=mp->cur_y;
8929 miny=2*y_coord(h)-mp->cur_y;
8930 }
8931
8932 @* \[21] Edge structures.
8933 Now we come to \MP's internal scheme for representing pictures.
8934 The representation is very different from \MF's edge structures
8935 because \MP\ pictures contain \ps\ graphics objects instead of pixel
8936 images.  However, the basic idea is somewhat similar in that shapes
8937 are represented via their boundaries.
8938
8939 The main purpose of edge structures is to keep track of graphical objects
8940 until it is time to translate them into \ps.  Since \MP\ does not need to
8941 know anything about an edge structure other than how to translate it into
8942 \ps\ and how to find its bounding box, edge structures can be just linked
8943 lists of graphical objects.  \MP\ has no easy way to determine whether
8944 two such objects overlap, but it suffices to draw the first one first and
8945 let the second one overwrite it if necessary.
8946
8947 @ Let's consider the types of graphical objects one at a time.
8948 First of all, a filled contour is represented by a eight-word node.  The first
8949 word contains |type| and |link| fields, and the next six words contain a
8950 pointer to a cyclic path and the value to use for \ps' \&{currentrgbcolor}
8951 parameter.  If a pen is used for filling |pen_p|, |ljoin_val| and |miterlim_val|
8952 give the relevant information.
8953
8954 @d path_p(A) link((A)+1)
8955   /* a pointer to the path that needs filling */
8956 @d pen_p(A) info((A)+1)
8957   /* a pointer to the pen to fill or stroke with */
8958 @d color_model(A) type((A)+2) /*  the color model  */
8959 @d obj_red_loc(A) ((A)+3)  /* the first of three locations for the color */
8960 @d obj_cyan_loc obj_red_loc  /* the first of four locations for the color */
8961 @d obj_grey_loc obj_red_loc  /* the location for the color */
8962 @d red_val(A) mp->mem[(A)+3].sc
8963   /* the red component of the color in the range $0\ldots1$ */
8964 @d cyan_val red_val
8965 @d grey_val red_val
8966 @d green_val(A) mp->mem[(A)+4].sc
8967   /* the green component of the color in the range $0\ldots1$ */
8968 @d magenta_val green_val
8969 @d blue_val(A) mp->mem[(A)+5].sc
8970   /* the blue component of the color in the range $0\ldots1$ */
8971 @d yellow_val blue_val
8972 @d black_val(A) mp->mem[(A)+6].sc
8973   /* the blue component of the color in the range $0\ldots1$ */
8974 @d ljoin_val(A) name_type((A))  /* the value of \&{linejoin} */
8975 @:linejoin_}{\&{linejoin} primitive@>
8976 @d miterlim_val(A) mp->mem[(A)+7].sc  /* the value of \&{miterlimit} */
8977 @:miterlimit_}{\&{miterlimit} primitive@>
8978 @d obj_color_part(A) mp->mem[(A)+3-red_part].sc
8979   /* interpret an object pointer that has been offset by |red_part..blue_part| */
8980 @d pre_script(A) mp->mem[(A)+8].hh.lh
8981 @d post_script(A) mp->mem[(A)+8].hh.rh
8982 @d fill_node_size 9
8983 @d fill_code 1
8984
8985 @c 
8986 pointer mp_new_fill_node (MP mp,pointer p) {
8987   /* make a fill node for cyclic path |p| and color black */
8988   pointer t; /* the new node */
8989   t=mp_get_node(mp, fill_node_size);
8990   type(t)=fill_code;
8991   path_p(t)=p;
8992   pen_p(t)=null; /* |null| means don't use a pen */
8993   red_val(t)=0;
8994   green_val(t)=0;
8995   blue_val(t)=0;
8996   black_val(t)=0;
8997   color_model(t)=uninitialized_model;
8998   pre_script(t)=null;
8999   post_script(t)=null;
9000   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9001   return t;
9002 }
9003
9004 @ @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>=
9005 if ( mp->internal[linejoin]>unity ) ljoin_val(t)=2;
9006 else if ( mp->internal[linejoin]>0 ) ljoin_val(t)=1;
9007 else ljoin_val(t)=0;
9008 if ( mp->internal[miterlimit]<unity )
9009   miterlim_val(t)=unity;
9010 else
9011   miterlim_val(t)=mp->internal[miterlimit]
9012
9013 @ A stroked path is represented by an eight-word node that is like a filled
9014 contour node except that it contains the current \&{linecap} value, a scale
9015 factor for the dash pattern, and a pointer that is non-null if the stroke
9016 is to be dashed.  The purpose of the scale factor is to allow a picture to
9017 be transformed without touching the picture that |dash_p| points to.
9018
9019 @d dash_p(A) link((A)+9)
9020   /* a pointer to the edge structure that gives the dash pattern */
9021 @d lcap_val(A) type((A)+9)
9022   /* the value of \&{linecap} */
9023 @:linecap_}{\&{linecap} primitive@>
9024 @d dash_scale(A) mp->mem[(A)+10].sc /* dash lengths are scaled by this factor */
9025 @d stroked_node_size 11
9026 @d stroked_code 2
9027
9028 @c 
9029 pointer mp_new_stroked_node (MP mp,pointer p) {
9030   /* make a stroked node for path |p| with |pen_p(p)| temporarily |null| */
9031   pointer t; /* the new node */
9032   t=mp_get_node(mp, stroked_node_size);
9033   type(t)=stroked_code;
9034   path_p(t)=p; pen_p(t)=null;
9035   dash_p(t)=null;
9036   dash_scale(t)=unity;
9037   red_val(t)=0;
9038   green_val(t)=0;
9039   blue_val(t)=0;
9040   black_val(t)=0;
9041   color_model(t)=uninitialized_model;
9042   pre_script(t)=null;
9043   post_script(t)=null;
9044   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9045   if ( mp->internal[linecap]>unity ) lcap_val(t)=2;
9046   else if ( mp->internal[linecap]>0 ) lcap_val(t)=1;
9047   else lcap_val(t)=0;
9048   return t;
9049 }
9050
9051 @ When a dashed line is computed in a transformed coordinate system, the dash
9052 lengths get scaled like the pen shape and we need to compensate for this.  Since
9053 there is no unique scale factor for an arbitrary transformation, we use the
9054 the square root of the determinant.  The properties of the determinant make it
9055 easier to maintain the |dash_scale|.  The computation is fairly straight-forward
9056 except for the initialization of the scale factor |s|.  The factor of 64 is
9057 needed because |square_rt| scales its result by $2^8$ while we need $2^{14}$
9058 to counteract the effect of |take_fraction|.
9059
9060 @<Declare subroutines needed by |print_edges|@>=
9061 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) {
9062   scaled maxabs; /* $max(|a|,|b|,|c|,|d|)$ */
9063   integer s; /* amount by which the result of |square_rt| needs to be scaled */
9064   @<Initialize |maxabs|@>;
9065   s=64;
9066   while ( (maxabs<fraction_one) && (s>1) ){ 
9067     a+=a; b+=b; c+=c; d+=d;
9068     maxabs+=maxabs; s=halfp(s);
9069   }
9070   return s*mp_square_rt(mp, abs(mp_take_fraction(mp, a,d)-mp_take_fraction(mp, b,c)));
9071 }
9072 @#
9073 scaled mp_get_pen_scale (MP mp,pointer p) { 
9074   return mp_sqrt_det(mp, 
9075     left_x(p)-x_coord(p), right_x(p)-x_coord(p),
9076     left_y(p)-y_coord(p), right_y(p)-y_coord(p));
9077 }
9078
9079 @ @<Initialize |maxabs|@>=
9080 maxabs=abs(a);
9081 if ( abs(b)>maxabs ) maxabs=abs(b);
9082 if ( abs(c)>maxabs ) maxabs=abs(c);
9083 if ( abs(d)>maxabs ) maxabs=abs(d)
9084
9085 @ When a picture contains text, this is represented by a fourteen-word node
9086 where the color information and |type| and |link| fields are augmented by
9087 additional fields that describe the text and  how it is transformed.
9088 The |path_p| and |pen_p| pointers are replaced by a number that identifies
9089 the font and a string number that gives the text to be displayed.
9090 The |width|, |height|, and |depth| fields
9091 give the dimensions of the text at its design size, and the remaining six
9092 words give a transformation to be applied to the text.  The |new_text_node|
9093 function initializes everything to default values so that the text comes out
9094 black with its reference point at the origin.
9095
9096 @d text_p(A) link((A)+1)  /* a string pointer for the text to display */
9097 @d font_n(A) info((A)+1)  /* the font number */
9098 @d width_val(A) mp->mem[(A)+7].sc  /* unscaled width of the text */
9099 @d height_val(A) mp->mem[(A)+9].sc  /* unscaled height of the text */
9100 @d depth_val(A) mp->mem[(A)+10].sc  /* unscaled depth of the text */
9101 @d text_tx_loc(A) ((A)+11)
9102   /* the first of six locations for transformation parameters */
9103 @d tx_val(A) mp->mem[(A)+11].sc  /* $x$ shift amount */
9104 @d ty_val(A) mp->mem[(A)+12].sc  /* $y$ shift amount */
9105 @d txx_val(A) mp->mem[(A)+13].sc  /* |txx| transformation parameter */
9106 @d txy_val(A) mp->mem[(A)+14].sc  /* |txy| transformation parameter */
9107 @d tyx_val(A) mp->mem[(A)+15].sc  /* |tyx| transformation parameter */
9108 @d tyy_val(A) mp->mem[(A)+16].sc  /* |tyy| transformation parameter */
9109 @d text_trans_part(A) mp->mem[(A)+11-x_part].sc
9110     /* interpret a text node ponter that has been offset by |x_part..yy_part| */
9111 @d text_node_size 17
9112 @d text_code 3
9113
9114 @c @<Declare text measuring subroutines@>;
9115 pointer mp_new_text_node (MP mp,char *f,str_number s) {
9116   /* make a text node for font |f| and text string |s| */
9117   pointer t; /* the new node */
9118   t=mp_get_node(mp, text_node_size);
9119   type(t)=text_code;
9120   text_p(t)=s;
9121   font_n(t)=mp_find_font(mp, f); /* this identifies the font */
9122   red_val(t)=0;
9123   green_val(t)=0;
9124   blue_val(t)=0;
9125   black_val(t)=0;
9126   color_model(t)=uninitialized_model;
9127   pre_script(t)=null;
9128   post_script(t)=null;
9129   tx_val(t)=0; ty_val(t)=0;
9130   txx_val(t)=unity; txy_val(t)=0;
9131   tyx_val(t)=0; tyy_val(t)=unity;
9132   mp_set_text_box(mp, t); /* this finds the bounding box */
9133   return t;
9134 }
9135
9136 @ The last two types of graphical objects that can occur in an edge structure
9137 are clipping paths and \&{setbounds} paths.  These are slightly more difficult
9138 @:set_bounds_}{\&{setbounds} primitive@>
9139 to implement because we must keep track of exactly what is being clipped or
9140 bounded when pictures get merged together.  For this reason, each clipping or
9141 \&{setbounds} operation is represented by a pair of nodes:  first comes a
9142 two-word node whose |path_p| gives the relevant path, then there is the list
9143 of objects to clip or bound followed by a two-word node whose second word is
9144 unused.
9145
9146 Using at least two words for each graphical object node allows them all to be
9147 allocated and deallocated similarly with a global array |gr_object_size| to
9148 give the size in words for each object type.
9149
9150 @d start_clip_size 2
9151 @d start_bounds_size 2
9152 @d stop_clip_size 2 /* the second word is not used here */
9153 @d stop_bounds_size 2 /* the second word is not used here */
9154 @#
9155 @d stop_type(A) ((A)+2)
9156   /* matching |type| for |start_clip_code| or |start_bounds_code| */
9157 @d has_color(A) (type((A))<mp_start_clip_code)
9158   /* does a graphical object have color fields? */
9159 @d has_pen(A) (type((A))<text_code)
9160   /* does a graphical object have a |pen_p| field? */
9161 @d is_start_or_stop(A) (type((A))>=mp_start_clip_code)
9162 @d is_stop(A) (type((A))>=mp_stop_clip_code)
9163
9164 @<Types...@>=
9165 enum {
9166  mp_start_clip_code=4, /* |type| of a node that starts clipping */
9167  mp_start_bounds_code, /* |type| of a node that gives a \&{setbounds} path */
9168  mp_stop_clip_code, /* |type| of a node that stops clipping */
9169  mp_stop_bounds_code /* |type| of a node that stops \&{setbounds} */
9170 };
9171
9172 @ @c 
9173 pointer mp_new_bounds_node (MP mp,pointer p, small_number  c) {
9174   /* make a node of type |c| where |p| is the clipping or \&{setbounds} path */
9175   pointer t; /* the new node */
9176   t=mp_get_node(mp, mp->gr_object_size[c]);
9177   type(t)=c;
9178   path_p(t)=p;
9179   return t;
9180 };
9181
9182 @ We need an array to keep track of the sizes of graphical objects.
9183
9184 @<Glob...@>=
9185 small_number gr_object_size[mp_stop_bounds_code+1];
9186
9187 @ @<Set init...@>=
9188 mp->gr_object_size[fill_code]=fill_node_size;
9189 mp->gr_object_size[stroked_code]=stroked_node_size;
9190 mp->gr_object_size[text_code]=text_node_size;
9191 mp->gr_object_size[mp_start_clip_code]=start_clip_size;
9192 mp->gr_object_size[mp_stop_clip_code]=stop_clip_size;
9193 mp->gr_object_size[mp_start_bounds_code]=start_bounds_size;
9194 mp->gr_object_size[mp_stop_bounds_code]=stop_bounds_size;
9195
9196 @ All the essential information in an edge structure is encoded as a linked list
9197 of graphical objects as we have just seen, but it is helpful to add some
9198 redundant information.  A single edge structure might be used as a dash pattern
9199 many times, and it would be nice to avoid scanning the same structure
9200 repeatedly.  Thus, an edge structure known to be a suitable dash pattern
9201 has a header that gives a list of dashes in a sorted order designed for rapid
9202 translation into \ps.
9203
9204 Each dash is represented by a three-word node containing the initial and final
9205 $x$~coordinates as well as the usual |link| field.  The |link| fields points to
9206 the dash node with the next higher $x$-coordinates and the final link points
9207 to a special location called |null_dash|.  (There should be no overlap between
9208 dashes).  Since the $y$~coordinate of the dash pattern is needed to determine
9209 the period of repetition, this needs to be stored in the edge header along
9210 with a pointer to the list of dash nodes.
9211
9212 @d start_x(A) mp->mem[(A)+1].sc  /* the starting $x$~coordinate in a dash node */
9213 @d stop_x(A) mp->mem[(A)+2].sc  /* the ending $x$~coordinate in a dash node */
9214 @d dash_node_size 3
9215 @d dash_list link
9216   /* in an edge header this points to the first dash node */
9217 @d dash_y(A) mp->mem[(A)+1].sc  /* $y$ value for the dash list in an edge header */
9218
9219 @ It is also convenient for an edge header to contain the bounding
9220 box information needed by the \&{llcorner} and \&{urcorner} operators
9221 so that this does not have to be recomputed unnecessarily.  This is done by
9222 adding fields for the $x$~and $y$ extremes as well as a pointer that indicates
9223 how far the bounding box computation has gotten.  Thus if the user asks for
9224 the bounding box and then adds some more text to the picture before asking
9225 for more bounding box information, the second computation need only look at
9226 the additional text.
9227
9228 When the bounding box has not been computed, the |bblast| pointer points
9229 to a dummy link at the head of the graphical object list while the |minx_val|
9230 and |miny_val| fields contain |el_gordo| and the |maxx_val| and |maxy_val|
9231 fields contain |-el_gordo|.
9232
9233 Since the bounding box of pictures containing objects of type
9234 |mp_start_bounds_code| depends on the value of \&{truecorners}, the bounding box
9235 @:true_corners_}{\&{truecorners} primitive@>
9236 data might not be valid for all values of this parameter.  Hence, the |bbtype|
9237 field is needed to keep track of this.
9238
9239 @d minx_val(A) mp->mem[(A)+2].sc
9240 @d miny_val(A) mp->mem[(A)+3].sc
9241 @d maxx_val(A) mp->mem[(A)+4].sc
9242 @d maxy_val(A) mp->mem[(A)+5].sc
9243 @d bblast(A) link((A)+6)  /* last item considered in bounding box computation */
9244 @d bbtype(A) info((A)+6)  /* tells how bounding box data depends on \&{truecorners} */
9245 @d dummy_loc(A) ((A)+7)  /* where the object list begins in an edge header */
9246 @d no_bounds 0
9247   /* |bbtype| value when bounding box data is valid for all \&{truecorners} values */
9248 @d bounds_set 1
9249   /* |bbtype| value when bounding box data is for \&{truecorners}${}\le 0$ */
9250 @d bounds_unset 2
9251   /* |bbtype| value when bounding box data is for \&{truecorners}${}>0$ */
9252
9253 @c 
9254 void mp_init_bbox (MP mp,pointer h) {
9255   /* Initialize the bounding box information in edge structure |h| */
9256   bblast(h)=dummy_loc(h);
9257   bbtype(h)=no_bounds;
9258   minx_val(h)=el_gordo;
9259   miny_val(h)=el_gordo;
9260   maxx_val(h)=-el_gordo;
9261   maxy_val(h)=-el_gordo;
9262 }
9263
9264 @ The only other entries in an edge header are a reference count in the first
9265 word and a pointer to the tail of the object list in the last word.
9266
9267 @d obj_tail(A) info((A)+7)  /* points to the last entry in the object list */
9268 @d edge_header_size 8
9269
9270 @c 
9271 void mp_init_edges (MP mp,pointer h) {
9272   /* initialize an edge header to null values */
9273   dash_list(h)=null_dash;
9274   obj_tail(h)=dummy_loc(h);
9275   link(dummy_loc(h))=null;
9276   ref_count(h)=null;
9277   mp_init_bbox(mp, h);
9278 }
9279
9280 @ Here is how edge structures are deleted.  The process can be recursive because
9281 of the need to dereference edge structures that are used as dash patterns.
9282 @^recursion@>
9283
9284 @d add_edge_ref(A) incr(ref_count((A)))
9285 @d delete_edge_ref(A) { if ( ref_count((A))==null ) mp_toss_edges(mp, (A));
9286   else decr(ref_count((A))); }
9287
9288 @<Declare the recycling subroutines@>=
9289 void mp_flush_dash_list (MP mp,pointer h);
9290 pointer mp_toss_gr_object (MP mp,pointer p) ;
9291 void mp_toss_edges (MP mp,pointer h) ;
9292
9293 @ @c void mp_toss_edges (MP mp,pointer h) {
9294   pointer p,q;  /* pointers that scan the list being recycled */
9295   pointer r; /* an edge structure that object |p| refers to */
9296   mp_flush_dash_list(mp, h);
9297   q=link(dummy_loc(h));
9298   while ( (q!=null) ) { 
9299     p=q; q=link(q);
9300     r=mp_toss_gr_object(mp, p);
9301     if ( r!=null ) delete_edge_ref(r);
9302   }
9303   mp_free_node(mp, h,edge_header_size);
9304 }
9305 void mp_flush_dash_list (MP mp,pointer h) {
9306   pointer p,q;  /* pointers that scan the list being recycled */
9307   q=dash_list(h);
9308   while ( q!=null_dash ) { 
9309     p=q; q=link(q);
9310     mp_free_node(mp, p,dash_node_size);
9311   }
9312   dash_list(h)=null_dash;
9313 }
9314 pointer mp_toss_gr_object (MP mp,pointer p) {
9315   /* returns an edge structure that needs to be dereferenced */
9316   pointer e; /* the edge structure to return */
9317   e=null;
9318   @<Prepare to recycle graphical object |p|@>;
9319   mp_free_node(mp, p,mp->gr_object_size[type(p)]);
9320   return e;
9321 }
9322
9323 @ @<Prepare to recycle graphical object |p|@>=
9324 switch (type(p)) {
9325 case fill_code: 
9326   mp_toss_knot_list(mp, path_p(p));
9327   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9328   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9329   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9330   break;
9331 case stroked_code: 
9332   mp_toss_knot_list(mp, path_p(p));
9333   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9334   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9335   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9336   e=dash_p(p);
9337   break;
9338 case text_code: 
9339   delete_str_ref(text_p(p));
9340   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9341   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9342   break;
9343 case mp_start_clip_code:
9344 case mp_start_bounds_code: 
9345   mp_toss_knot_list(mp, path_p(p));
9346   break;
9347 case mp_stop_clip_code:
9348 case mp_stop_bounds_code: 
9349   break;
9350 } /* there are no other cases */
9351
9352 @ If we use |add_edge_ref| to ``copy'' edge structures, the real copying needs
9353 to be done before making a significant change to an edge structure.  Much of
9354 the work is done in a separate routine |copy_objects| that copies a list of
9355 graphical objects into a new edge header.
9356
9357 @c @<Declare a function called |copy_objects|@>;
9358 pointer mp_private_edges (MP mp,pointer h) {
9359   /* make a private copy of the edge structure headed by |h| */
9360   pointer hh;  /* the edge header for the new copy */
9361   pointer p,pp;  /* pointers for copying the dash list */
9362   if ( ref_count(h)==null ) {
9363     return h;
9364   } else { 
9365     decr(ref_count(h));
9366     hh=mp_copy_objects(mp, link(dummy_loc(h)),null);
9367     @<Copy the dash list from |h| to |hh|@>;
9368     @<Copy the bounding box information from |h| to |hh| and make |bblast(hh)|
9369       point into the new object list@>;
9370     return hh;
9371   }
9372 }
9373
9374 @ Here we use the fact that |dash_list(hh)=link(hh)|.
9375 @^data structure assumptions@>
9376
9377 @<Copy the dash list from |h| to |hh|@>=
9378 pp=hh; p=dash_list(h);
9379 while ( (p!=null_dash) ) { 
9380   link(pp)=mp_get_node(mp, dash_node_size);
9381   pp=link(pp);
9382   start_x(pp)=start_x(p);
9383   stop_x(pp)=stop_x(p);
9384   p=link(p);
9385 }
9386 link(pp)=null_dash;
9387 dash_y(hh)=dash_y(h)
9388
9389 @ @<Copy the bounding box information from |h| to |hh|...@>=
9390 minx_val(hh)=minx_val(h);
9391 miny_val(hh)=miny_val(h);
9392 maxx_val(hh)=maxx_val(h);
9393 maxy_val(hh)=maxy_val(h);
9394 bbtype(hh)=bbtype(h);
9395 p=dummy_loc(h); pp=dummy_loc(hh);
9396 while ((p!=bblast(h)) ) { 
9397   if ( p==null ) mp_confusion(mp, "bblast");
9398 @:this can't happen bblast}{\quad bblast@>
9399   p=link(p); pp=link(pp);
9400 }
9401 bblast(hh)=pp
9402
9403 @ Here is the promised routine for copying graphical objects into a new edge
9404 structure.  It starts copying at object~|p| and stops just before object~|q|.
9405 If |q| is null, it copies the entire sublist headed at |p|.  The resulting edge
9406 structure requires further initialization by |init_bbox|.
9407
9408 @<Declare a function called |copy_objects|@>=
9409 pointer mp_copy_objects (MP mp, pointer p, pointer q) {
9410   pointer hh;  /* the new edge header */
9411   pointer pp;  /* the last newly copied object */
9412   small_number k;  /* temporary register */
9413   hh=mp_get_node(mp, edge_header_size);
9414   dash_list(hh)=null_dash;
9415   ref_count(hh)=null;
9416   pp=dummy_loc(hh);
9417   while ( (p!=q) ) {
9418     @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>;
9419   }
9420   obj_tail(hh)=pp;
9421   link(pp)=null;
9422   return hh;
9423 }
9424
9425 @ @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>=
9426 { k=mp->gr_object_size[type(p)];
9427   link(pp)=mp_get_node(mp, k);
9428   pp=link(pp);
9429   while ( (k>0) ) { decr(k); mp->mem[pp+k]=mp->mem[p+k];  };
9430   @<Fix anything in graphical object |pp| that should differ from the
9431     corresponding field in |p|@>;
9432   p=link(p);
9433 }
9434
9435 @ @<Fix anything in graphical object |pp| that should differ from the...@>=
9436 switch (type(p)) {
9437 case mp_start_clip_code:
9438 case mp_start_bounds_code: 
9439   path_p(pp)=mp_copy_path(mp, path_p(p));
9440   break;
9441 case fill_code: 
9442   path_p(pp)=mp_copy_path(mp, path_p(p));
9443   if ( pen_p(p)!=null ) pen_p(pp)=copy_pen(pen_p(p));
9444   break;
9445 case stroked_code: 
9446   path_p(pp)=mp_copy_path(mp, path_p(p));
9447   pen_p(pp)=copy_pen(pen_p(p));
9448   if ( dash_p(p)!=null ) add_edge_ref(dash_p(pp));
9449   break;
9450 case text_code: 
9451   add_str_ref(text_p(pp));
9452   break;
9453 case mp_stop_clip_code:
9454 case mp_stop_bounds_code: 
9455   break;
9456 }  /* there are no other cases */
9457
9458 @ Here is one way to find an acceptable value for the second argument to
9459 |copy_objects|.  Given a non-null graphical object list, |skip_1component|
9460 skips past one picture component, where a ``picture component'' is a single
9461 graphical object, or a start bounds or start clip object and everything up
9462 through the matching stop bounds or stop clip object.  The macro version avoids
9463 procedure call overhead and error handling: |skip_component(p)(e)| advances |p|
9464 unless |p| points to a stop bounds or stop clip node, in which case it executes
9465 |e| instead.
9466
9467 @d skip_component(A)
9468     if ( ! is_start_or_stop((A)) ) (A)=link((A));
9469     else if ( ! is_stop((A)) ) (A)=mp_skip_1component(mp, (A));
9470     else 
9471
9472 @c 
9473 pointer mp_skip_1component (MP mp,pointer p) {
9474   integer lev; /* current nesting level */
9475   lev=0;
9476   do {  
9477    if ( is_start_or_stop(p) ) {
9478      if ( is_stop(p) ) decr(lev);  else incr(lev);
9479    }
9480    p=link(p);
9481   } while (lev!=0);
9482   return p;
9483 }
9484
9485 @ Here is a diagnostic routine for printing an edge structure in symbolic form.
9486
9487 @<Declare subroutines for printing expressions@>=
9488 @<Declare subroutines needed by |print_edges|@>;
9489 void mp_print_edges (MP mp,pointer h, char *s, boolean nuline) {
9490   pointer p;  /* a graphical object to be printed */
9491   pointer hh,pp;  /* temporary pointers */
9492   scaled scf;  /* a scale factor for the dash pattern */
9493   boolean ok_to_dash;  /* |false| for polygonal pen strokes */
9494   mp_print_diagnostic(mp, "Edge structure",s,nuline);
9495   p=dummy_loc(h);
9496   while ( link(p)!=null ) { 
9497     p=link(p);
9498     mp_print_ln(mp);
9499     switch (type(p)) {
9500       @<Cases for printing graphical object node |p|@>;
9501     default: 
9502           mp_print(mp, "[unknown object type!]");
9503           break;
9504     }
9505   }
9506   mp_print_nl(mp, "End edges");
9507   if ( p!=obj_tail(h) ) mp_print(mp, "?");
9508 @.End edges?@>
9509   mp_end_diagnostic(mp, true);
9510 }
9511
9512 @ @<Cases for printing graphical object node |p|@>=
9513 case fill_code: 
9514   mp_print(mp, "Filled contour ");
9515   mp_print_obj_color(mp, p);
9516   mp_print_char(mp, ':'); mp_print_ln(mp);
9517   mp_pr_path(mp, path_p(p)); mp_print_ln(mp);
9518   if ( (pen_p(p)!=null) ) {
9519     @<Print join type for graphical object |p|@>;
9520     mp_print(mp, " with pen"); mp_print_ln(mp);
9521     mp_pr_pen(mp, pen_p(p));
9522   }
9523   break;
9524
9525 @ @<Print join type for graphical object |p|@>=
9526 switch (ljoin_val(p)) {
9527 case 0:
9528   mp_print(mp, "mitered joins limited ");
9529   mp_print_scaled(mp, miterlim_val(p));
9530   break;
9531 case 1:
9532   mp_print(mp, "round joins");
9533   break;
9534 case 2:
9535   mp_print(mp, "beveled joins");
9536   break;
9537 default: 
9538   mp_print(mp, "?? joins");
9539 @.??@>
9540   break;
9541 }
9542
9543 @ For stroked nodes, we need to print |lcap_val(p)| as well.
9544
9545 @<Print join and cap types for stroked node |p|@>=
9546 switch (lcap_val(p)) {
9547 case 0:mp_print(mp, "butt"); break;
9548 case 1:mp_print(mp, "round"); break;
9549 case 2:mp_print(mp, "square"); break;
9550 default: mp_print(mp, "??"); break;
9551 @.??@>
9552 }
9553 mp_print(mp, " ends, ");
9554 @<Print join type for graphical object |p|@>
9555
9556 @ Here is a routine that prints the color of a graphical object if it isn't
9557 black (the default color).
9558
9559 @<Declare subroutines needed by |print_edges|@>=
9560 @<Declare a procedure called |print_compact_node|@>;
9561 void mp_print_obj_color (MP mp,pointer p) { 
9562   if ( color_model(p)==grey_model ) {
9563     if ( grey_val(p)>0 ) { 
9564       mp_print(mp, "greyed ");
9565       mp_print_compact_node(mp, obj_grey_loc(p),1);
9566     };
9567   } else if ( color_model(p)==cmyk_model ) {
9568     if ( (cyan_val(p)>0) || (magenta_val(p)>0) || 
9569          (yellow_val(p)>0) || (black_val(p)>0) ) { 
9570       mp_print(mp, "processcolored ");
9571       mp_print_compact_node(mp, obj_cyan_loc(p),4);
9572     };
9573   } else if ( color_model(p)==rgb_model ) {
9574     if ( (red_val(p)>0) || (green_val(p)>0) || (blue_val(p)>0) ) { 
9575       mp_print(mp, "colored "); 
9576       mp_print_compact_node(mp, obj_red_loc(p),3);
9577     };
9578   }
9579 }
9580
9581 @ We also need a procedure for printing consecutive scaled values as if they
9582 were a known big node.
9583
9584 @<Declare a procedure called |print_compact_node|@>=
9585 void mp_print_compact_node (MP mp,pointer p, small_number k) {
9586   pointer q;  /* last location to print */
9587   q=p+k-1;
9588   mp_print_char(mp, '(');
9589   while ( p<=q ){ 
9590     mp_print_scaled(mp, mp->mem[p].sc);
9591     if ( p<q ) mp_print_char(mp, ',');
9592     incr(p);
9593   }
9594   mp_print_char(mp, ')');
9595 }
9596
9597 @ @<Cases for printing graphical object node |p|@>=
9598 case stroked_code: 
9599   mp_print(mp, "Filled pen stroke ");
9600   mp_print_obj_color(mp, p);
9601   mp_print_char(mp, ':'); mp_print_ln(mp);
9602   mp_pr_path(mp, path_p(p));
9603   if ( dash_p(p)!=null ) { 
9604     mp_print_nl(mp, "dashed (");
9605     @<Finish printing the dash pattern that |p| refers to@>;
9606   }
9607   mp_print_ln(mp);
9608   @<Print join and cap types for stroked node |p|@>;
9609   mp_print(mp, " with pen"); mp_print_ln(mp);
9610   if ( pen_p(p)==null ) mp_print(mp, "???"); /* shouldn't happen */
9611 @.???@>
9612   else mp_pr_pen(mp, pen_p(p));
9613   break;
9614
9615 @ Normally, the  |dash_list| field in an edge header is set to |null_dash|
9616 when it is not known to define a suitable dash pattern.  This is disallowed
9617 here because the |dash_p| field should never point to such an edge header.
9618 Note that memory is allocated for |start_x(null_dash)| and we are free to
9619 give it any convenient value.
9620
9621 @<Finish printing the dash pattern that |p| refers to@>=
9622 ok_to_dash=pen_is_elliptical(pen_p(p));
9623 if ( ! ok_to_dash ) scf=unity; else scf=dash_scale(p);
9624 hh=dash_p(p);
9625 pp=dash_list(hh);
9626 if ( (pp==null_dash) || (dash_y(hh)<0) ) {
9627   mp_print(mp, " ??");
9628 } else { start_x(null_dash)=start_x(pp)+dash_y(hh);
9629   while ( pp!=null_dash ) { 
9630     mp_print(mp, "on ");
9631     mp_print_scaled(mp, mp_take_scaled(mp, stop_x(pp)-start_x(pp),scf));
9632     mp_print(mp, " off ");
9633     mp_print_scaled(mp, mp_take_scaled(mp, start_x(link(pp))-stop_x(pp),scf));
9634     pp = link(pp);
9635     if ( pp!=null_dash ) mp_print_char(mp, ' ');
9636   }
9637   mp_print(mp, ") shifted ");
9638   mp_print_scaled(mp, -mp_take_scaled(mp, mp_dash_offset(mp, hh),scf));
9639   if ( ! ok_to_dash || (dash_y(hh)==0) ) mp_print(mp, " (this will be ignored)");
9640 }
9641
9642 @ @<Declare subroutines needed by |print_edges|@>=
9643 scaled mp_dash_offset (MP mp,pointer h) {
9644   scaled x;  /* the answer */
9645   if ( (dash_list(h)==null_dash) || (dash_y(h)<0) ) mp_confusion(mp, "dash0");
9646 @:this can't happen dash0}{\quad dash0@>
9647   if ( dash_y(h)==0 ) {
9648     x=0; 
9649   } else { 
9650     x=-(start_x(dash_list(h)) % dash_y(h));
9651     if ( x<0 ) x=x+dash_y(h);
9652   }
9653   return x;
9654 }
9655
9656 @ @<Cases for printing graphical object node |p|@>=
9657 case text_code: 
9658   mp_print_char(mp, '"'); mp_print_str(mp,text_p(p));
9659   mp_print(mp, "\" infont \""); mp_print(mp, mp->font_name[font_n(p)]);
9660   mp_print_char(mp, '"'); mp_print_ln(mp);
9661   mp_print_obj_color(mp, p);
9662   mp_print(mp, "transformed ");
9663   mp_print_compact_node(mp, text_tx_loc(p),6);
9664   break;
9665
9666 @ @<Cases for printing graphical object node |p|@>=
9667 case mp_start_clip_code: 
9668   mp_print(mp, "clipping path:");
9669   mp_print_ln(mp);
9670   mp_pr_path(mp, path_p(p));
9671   break;
9672 case mp_stop_clip_code: 
9673   mp_print(mp, "stop clipping");
9674   break;
9675
9676 @ @<Cases for printing graphical object node |p|@>=
9677 case mp_start_bounds_code: 
9678   mp_print(mp, "setbounds path:");
9679   mp_print_ln(mp);
9680   mp_pr_path(mp, path_p(p));
9681   break;
9682 case mp_stop_bounds_code: 
9683   mp_print(mp, "end of setbounds");
9684   break;
9685
9686 @ To initialize the |dash_list| field in an edge header~|h|, we need a
9687 subroutine that scans an edge structure and tries to interpret it as a dash
9688 pattern.  This can only be done when there are no filled regions or clipping
9689 paths and all the pen strokes have the same color.  The first step is to let
9690 $y_0$ be the initial $y$~coordinate of the first pen stroke.  Then we implicitly
9691 project all the pen stroke paths onto the line $y=y_0$ and require that there
9692 be no retracing.  If the resulting paths cover a range of $x$~coordinates of
9693 length $\Delta x$, we set |dash_y(h)| to the length of the dash pattern by
9694 finding the maximum of $\Delta x$ and the absolute value of~$y_0$.
9695
9696 @c @<Declare a procedure called |x_retrace_error|@>;
9697 pointer mp_make_dashes (MP mp,pointer h) { /* returns |h| or |null| */
9698   pointer p;  /* this scans the stroked nodes in the object list */
9699   pointer p0;  /* if not |null| this points to the first stroked node */
9700   pointer pp,qq,rr;  /* pointers into |path_p(p)| */
9701   pointer d,dd;  /* pointers used to create the dash list */
9702   @<Other local variables in |make_dashes|@>;
9703   scaled y0=0;  /* the initial $y$ coordinate */
9704   if ( dash_list(h)!=null_dash ) 
9705         return h;
9706   p0=null;
9707   p=link(dummy_loc(h));
9708   while ( p!=null ) { 
9709     if ( type(p)!=stroked_code ) {
9710       @<Compain that the edge structure contains a node of the wrong type
9711         and |goto not_found|@>;
9712     }
9713     pp=path_p(p);
9714     if ( p0==null ){ p0=p; y0=y_coord(pp);  };
9715     @<Make |d| point to a new dash node created from stroke |p| and path |pp|
9716       or |goto not_found| if there is an error@>;
9717     @<Insert |d| into the dash list and |goto not_found| if there is an error@>;
9718     p=link(p);
9719   }
9720   if ( dash_list(h)==null_dash ) 
9721     goto NOT_FOUND; /* No error message */
9722   @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>;
9723   @<Set |dash_y(h)| and merge the first and last dashes if necessary@>;
9724   return h;
9725 NOT_FOUND: 
9726   @<Flush the dash list, recycle |h| and return |null|@>;
9727 };
9728
9729 @ @<Compain that the edge structure contains a node of the wrong type...@>=
9730
9731 print_err("Picture is too complicated to use as a dash pattern");
9732 help3("When you say `dashed p', picture p should not contain any")
9733   ("text, filled regions, or clipping paths.  This time it did")
9734   ("so I'll just make it a solid line instead.");
9735 mp_put_get_error(mp);
9736 goto NOT_FOUND;
9737 }
9738
9739 @ A similar error occurs when monotonicity fails.
9740
9741 @<Declare a procedure called |x_retrace_error|@>=
9742 void mp_x_retrace_error (MP mp) { 
9743 print_err("Picture is too complicated to use as a dash pattern");
9744 help3("When you say `dashed p', every path in p should be monotone")
9745   ("in x and there must be no overlapping.  This failed")
9746   ("so I'll just make it a solid line instead.");
9747 mp_put_get_error(mp);
9748 }
9749
9750 @ We stash |p| in |info(d)| if |dash_p(p)<>0| so that subsequent processing can
9751 handle the case where the pen stroke |p| is itself dashed.
9752
9753 @<Make |d| point to a new dash node created from stroke |p| and path...@>=
9754 @<Make sure |p| and |p0| are the same color and |goto not_found| if there is
9755   an error@>;
9756 rr=pp;
9757 if ( link(pp)!=pp ) {
9758   do {  
9759     qq=rr; rr=link(rr);
9760     @<Check for retracing between knots |qq| and |rr| and |goto not_found|
9761       if there is a problem@>;
9762   } while (right_type(rr)!=endpoint);
9763 }
9764 d=mp_get_node(mp, dash_node_size);
9765 if ( dash_p(p)==0 ) info(d)=0;  else info(d)=p;
9766 if ( x_coord(pp)<x_coord(rr) ) { 
9767   start_x(d)=x_coord(pp);
9768   stop_x(d)=x_coord(rr);
9769 } else { 
9770   start_x(d)=x_coord(rr);
9771   stop_x(d)=x_coord(pp);
9772 }
9773
9774 @ We also need to check for the case where the segment from |qq| to |rr| is
9775 monotone in $x$ but is reversed relative to the path from |pp| to |qq|.
9776
9777 @<Check for retracing between knots |qq| and |rr| and |goto not_found|...@>=
9778 x0=x_coord(qq);
9779 x1=right_x(qq);
9780 x2=left_x(rr);
9781 x3=x_coord(rr);
9782 if ( (x0>x1) || (x1>x2) || (x2>x3) ) {
9783   if ( (x0<x1) || (x1<x2) || (x2<x3) ) {
9784     if ( mp_ab_vs_cd(mp, x2-x1,x2-x1,x1-x0,x3-x2)>0 ) {
9785       mp_x_retrace_error(mp); goto NOT_FOUND;
9786     }
9787   }
9788 }
9789 if ( (x_coord(pp)>x0) || (x0>x3) ) {
9790   if ( (x_coord(pp)<x0) || (x0<x3) ) {
9791     mp_x_retrace_error(mp); goto NOT_FOUND;
9792   }
9793 }
9794
9795 @ @<Other local variables in |make_dashes|@>=
9796   scaled x0,x1,x2,x3;  /* $x$ coordinates of the segment from |qq| to |rr| */
9797
9798 @ @<Make sure |p| and |p0| are the same color and |goto not_found|...@>=
9799 if ( (red_val(p)!=red_val(p0)) || (black_val(p)!=black_val(p0)) ||
9800   (green_val(p)!=green_val(p0)) || (blue_val(p)!=blue_val(p0)) ) {
9801   print_err("Picture is too complicated to use as a dash pattern");
9802   help3("When you say `dashed p', everything in picture p should")
9803     ("be the same color.  I can\'t handle your color changes")
9804     ("so I'll just make it a solid line instead.");
9805   mp_put_get_error(mp);
9806   goto NOT_FOUND;
9807 }
9808
9809 @ @<Insert |d| into the dash list and |goto not_found| if there is an error@>=
9810 start_x(null_dash)=stop_x(d);
9811 dd=h; /* this makes |link(dd)=dash_list(h)| */
9812 while ( start_x(link(dd))<stop_x(d) )
9813   dd=link(dd);
9814 if ( dd!=h ) {
9815   if ( (stop_x(dd)>start_x(d)) )
9816     { mp_x_retrace_error(mp); goto NOT_FOUND;  };
9817 }
9818 link(d)=link(dd);
9819 link(dd)=d
9820
9821 @ @<Set |dash_y(h)| and merge the first and last dashes if necessary@>=
9822 d=dash_list(h);
9823 while ( (link(d)!=null_dash) )
9824   d=link(d);
9825 dd=dash_list(h);
9826 dash_y(h)=stop_x(d)-start_x(dd);
9827 if ( abs(y0)>dash_y(h) ) {
9828   dash_y(h)=abs(y0);
9829 } else if ( d!=dd ) { 
9830   dash_list(h)=link(dd);
9831   stop_x(d)=stop_x(dd)+dash_y(h);
9832   mp_free_node(mp, dd,dash_node_size);
9833 }
9834
9835 @ We get here when the argument is a null picture or when there is an error.
9836 Recovering from an error involves making |dash_list(h)| empty to indicate
9837 that |h| is not known to be a valid dash pattern.  We also dereference |h|
9838 since it is not being used for the return value.
9839
9840 @<Flush the dash list, recycle |h| and return |null|@>=
9841 mp_flush_dash_list(mp, h);
9842 delete_edge_ref(h);
9843 return null
9844
9845 @ Having carefully saved the dashed stroked nodes in the
9846 corresponding dash nodes, we must be prepared to break up these dashes into
9847 smaller dashes.
9848
9849 @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>=
9850 d=h;  /* now |link(d)=dash_list(h)| */
9851 while ( link(d)!=null_dash ) {
9852   ds=info(link(d));
9853   if ( ds==null ) { 
9854     d=link(d);
9855   } else {
9856     hh=dash_p(ds);
9857     hsf=dash_scale(ds);
9858     if ( (hh==null) ) mp_confusion(mp, "dash1");
9859 @:this can't happen dash0}{\quad dash1@>
9860     if ( dash_y(hh)==0 ) {
9861       d=link(d);
9862     } else { 
9863       if ( dash_list(hh)==null ) mp_confusion(mp, "dash1");
9864 @:this can't happen dash0}{\quad dash1@>
9865       @<Replace |link(d)| by a dashed version as determined by edge header
9866           |hh| and scale factor |ds|@>;
9867     }
9868   }
9869 }
9870
9871 @ @<Other local variables in |make_dashes|@>=
9872 pointer dln;  /* |link(d)| */
9873 pointer hh;  /* an edge header that tells how to break up |dln| */
9874 scaled hsf;  /* the dash pattern from |hh| gets scaled by this */
9875 pointer ds;  /* the stroked node from which |hh| and |hsf| are derived */
9876 scaled xoff;  /* added to $x$ values in |dash_list(hh)| to match |dln| */
9877
9878 @ @<Replace |link(d)| by a dashed version as determined by edge header...@>=
9879 dln=link(d);
9880 dd=dash_list(hh);
9881 xoff=start_x(dln)-mp_take_scaled(mp, hsf,start_x(dd))-
9882         mp_take_scaled(mp, hsf,mp_dash_offset(mp, hh));
9883 start_x(null_dash)=mp_take_scaled(mp, hsf,start_x(dd))
9884                    +mp_take_scaled(mp, hsf,dash_y(hh));
9885 stop_x(null_dash)=start_x(null_dash);
9886 @<Advance |dd| until finding the first dash that overlaps |dln| when
9887   offset by |xoff|@>;
9888 while ( start_x(dln)<=stop_x(dln) ) {
9889   @<If |dd| has `fallen off the end', back up to the beginning and fix |xoff|@>;
9890   @<Insert a dash between |d| and |dln| for the overlap with the offset version
9891     of |dd|@>;
9892   dd=link(dd);
9893   start_x(dln)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
9894 }
9895 link(d)=link(dln);
9896 mp_free_node(mp, dln,dash_node_size)
9897
9898 @ The name of this module is a bit of a lie because we actually just find the
9899 first |dd| where |take_scaled (hsf, stop_x(dd))| is large enough to make an
9900 overlap possible.  It could be that the unoffset version of dash |dln| falls
9901 in the gap between |dd| and its predecessor.
9902
9903 @<Advance |dd| until finding the first dash that overlaps |dln| when...@>=
9904 while ( xoff+mp_take_scaled(mp, hsf,stop_x(dd))<start_x(dln) ) {
9905   dd=link(dd);
9906 }
9907
9908 @ @<If |dd| has `fallen off the end', back up to the beginning and fix...@>=
9909 if ( dd==null_dash ) { 
9910   dd=dash_list(hh);
9911   xoff=xoff+mp_take_scaled(mp, hsf,dash_y(hh));
9912 }
9913
9914 @ At this point we already know that
9915 |start_x(dln)<=xoff+take_scaled(hsf,stop_x(dd))|.
9916
9917 @<Insert a dash between |d| and |dln| for the overlap with the offset...@>=
9918 if ( xoff+mp_take_scaled(mp, hsf,start_x(dd))<=stop_x(dln) ) {
9919   link(d)=mp_get_node(mp, dash_node_size);
9920   d=link(d);
9921   link(d)=dln;
9922   if ( start_x(dln)>xoff+mp_take_scaled(mp, hsf,start_x(dd)))
9923     start_x(d)=start_x(dln);
9924   else 
9925     start_x(d)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
9926   if ( stop_x(dln)<xoff+mp_take_scaled(mp, hsf,stop_x(dd)) ) 
9927     stop_x(d)=stop_x(dln);
9928   else 
9929     stop_x(d)=xoff+mp_take_scaled(mp, hsf,stop_x(dd));
9930 }
9931
9932 @ The next major task is to update the bounding box information in an edge
9933 header~|h|. This is done via a procedure |adjust_bbox| that enlarges an edge
9934 header's bounding box to accommodate the box computed by |path_bbox| or
9935 |pen_bbox|. (This is stored in global variables |minx|, |miny|, |maxx|, and
9936 |maxy|.)
9937
9938 @c void mp_adjust_bbox (MP mp,pointer h) { 
9939   if ( minx<minx_val(h) ) minx_val(h)=minx;
9940   if ( miny<miny_val(h) ) miny_val(h)=miny;
9941   if ( maxx>maxx_val(h) ) maxx_val(h)=maxx;
9942   if ( maxy>maxy_val(h) ) maxy_val(h)=maxy;
9943 }
9944
9945 @ Here is a special routine for updating the bounding box information in
9946 edge header~|h| to account for the squared-off ends of a non-cyclic path~|p|
9947 that is to be stroked with the pen~|pp|.
9948
9949 @c void mp_box_ends (MP mp, pointer p, pointer pp, pointer h) {
9950   pointer q;  /* a knot node adjacent to knot |p| */
9951   fraction dx,dy;  /* a unit vector in the direction out of the path at~|p| */
9952   scaled d;  /* a factor for adjusting the length of |(dx,dy)| */
9953   scaled z;  /* a coordinate being tested against the bounding box */
9954   scaled xx,yy;  /* the extreme pen vertex in the |(dx,dy)| direction */
9955   integer i; /* a loop counter */
9956   if ( right_type(p)!=endpoint ) { 
9957     q=link(p);
9958     while (1) { 
9959       @<Make |(dx,dy)| the final direction for the path segment from
9960         |q| to~|p|; set~|d|@>;
9961       d=mp_pyth_add(mp, dx,dy);
9962       if ( d>0 ) { 
9963          @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>;
9964          for (i=1;i<= 2;i++) { 
9965            @<Use |(dx,dy)| to generate a vertex of the square end cap and
9966              update the bounding box to accommodate it@>;
9967            dx=-dx; dy=-dy; 
9968         }
9969       }
9970       if ( right_type(p)==endpoint ) {
9971          return;
9972       } else {
9973         @<Advance |p| to the end of the path and make |q| the previous knot@>;
9974       } 
9975     }
9976   }
9977 }
9978
9979 @ @<Make |(dx,dy)| the final direction for the path segment from...@>=
9980 if ( q==link(p) ) { 
9981   dx=x_coord(p)-right_x(p);
9982   dy=y_coord(p)-right_y(p);
9983   if ( (dx==0)&&(dy==0) ) {
9984     dx=x_coord(p)-left_x(q);
9985     dy=y_coord(p)-left_y(q);
9986   }
9987 } else { 
9988   dx=x_coord(p)-left_x(p);
9989   dy=y_coord(p)-left_y(p);
9990   if ( (dx==0)&&(dy==0) ) {
9991     dx=x_coord(p)-right_x(q);
9992     dy=y_coord(p)-right_y(q);
9993   }
9994 }
9995 dx=x_coord(p)-x_coord(q);
9996 dy=y_coord(p)-y_coord(q)
9997
9998 @ @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>=
9999 dx=mp_make_fraction(mp, dx,d);
10000 dy=mp_make_fraction(mp, dy,d);
10001 mp_find_offset(mp, -dy,dx,pp);
10002 xx=mp->cur_x; yy=mp->cur_y
10003
10004 @ @<Use |(dx,dy)| to generate a vertex of the square end cap and...@>=
10005 mp_find_offset(mp, dx,dy,pp);
10006 d=mp_take_fraction(mp, xx-mp->cur_x,dx)+mp_take_fraction(mp, yy-mp->cur_y,dy);
10007 if ( ((d<0)&&(i==1)) || ((d>0)&&(i==2))) 
10008   mp_confusion(mp, "box_ends");
10009 @:this can't happen box ends}{\quad\\{box\_ends}@>
10010 z=x_coord(p)+mp->cur_x+mp_take_fraction(mp, d,dx);
10011 if ( z<minx_val(h) ) minx_val(h)=z;
10012 if ( z>maxx_val(h) ) maxx_val(h)=z;
10013 z=y_coord(p)+mp->cur_y+mp_take_fraction(mp, d,dy);
10014 if ( z<miny_val(h) ) miny_val(h)=z;
10015 if ( z>maxy_val(h) ) maxy_val(h)=z
10016
10017 @ @<Advance |p| to the end of the path and make |q| the previous knot@>=
10018 do {  
10019   q=p;
10020   p=link(p);
10021 } while (right_type(p)!=endpoint)
10022
10023 @ The major difficulty in finding the bounding box of an edge structure is the
10024 effect of clipping paths.  We treat them conservatively by only clipping to the
10025 clipping path's bounding box, but this still
10026 requires recursive calls to |set_bbox| in order to find the bounding box of
10027 @^recursion@>
10028 the objects to be clipped.  Such calls are distinguished by the fact that the
10029 boolean parameter |top_level| is false.
10030
10031 @c void mp_set_bbox (MP mp,pointer h, boolean top_level) {
10032   pointer p;  /* a graphical object being considered */
10033   scaled sminx,sminy,smaxx,smaxy;
10034   /* for saving the bounding box during recursive calls */
10035   scaled x0,x1,y0,y1;  /* temporary registers */
10036   integer lev;  /* nesting level for |mp_start_bounds_code| nodes */
10037   @<Wipe out any existing bounding box information if |bbtype(h)| is
10038   incompatible with |internal[true_corners]|@>;
10039   while ( link(bblast(h))!=null ) { 
10040     p=link(bblast(h));
10041     bblast(h)=p;
10042     switch (type(p)) {
10043     case mp_stop_clip_code: 
10044       if ( top_level ) mp_confusion(mp, "bbox");  else return;
10045 @:this can't happen bbox}{\quad bbox@>
10046       break;
10047     @<Other cases for updating the bounding box based on the type of object |p|@>;
10048     } /* all cases are enumerated above */
10049   }
10050   if ( ! top_level ) mp_confusion(mp, "bbox");
10051 }
10052
10053 @ @<Wipe out any existing bounding box information if |bbtype(h)| is...@>=
10054 switch (bbtype(h)) {
10055 case no_bounds: 
10056   break;
10057 case bounds_set: 
10058   if ( mp->internal[true_corners]>0 ) mp_init_bbox(mp, h);
10059   break;
10060 case bounds_unset: 
10061   if ( mp->internal[true_corners]<=0 ) mp_init_bbox(mp, h);
10062   break;
10063 } /* there are no other cases */
10064
10065 @ @<Other cases for updating the bounding box...@>=
10066 case fill_code: 
10067   mp_path_bbox(mp, path_p(p));
10068   if ( pen_p(p)!=null ) { 
10069     x0=minx; y0=miny;
10070     x1=maxx; y1=maxy;
10071     mp_pen_bbox(mp, pen_p(p));
10072     minx=minx+x0;
10073     miny=miny+y0;
10074     maxx=maxx+x1;
10075     maxy=maxy+y1;
10076   }
10077   mp_adjust_bbox(mp, h);
10078   break;
10079
10080 @ @<Other cases for updating the bounding box...@>=
10081 case mp_start_bounds_code: 
10082   if ( mp->internal[true_corners]>0 ) {
10083     bbtype(h)=bounds_unset;
10084   } else { 
10085     bbtype(h)=bounds_set;
10086     mp_path_bbox(mp, path_p(p));
10087     mp_adjust_bbox(mp, h);
10088     @<Scan to the matching |mp_stop_bounds_code| node and update |p| and
10089       |bblast(h)|@>;
10090   }
10091   break;
10092 case mp_stop_bounds_code: 
10093   if ( mp->internal[true_corners]<=0 ) mp_confusion(mp, "bbox2");
10094 @:this can't happen bbox2}{\quad bbox2@>
10095   break;
10096
10097 @ @<Scan to the matching |mp_stop_bounds_code| node and update |p| and...@>=
10098 lev=1;
10099 while ( lev!=0 ) { 
10100   if ( link(p)==null ) mp_confusion(mp, "bbox2");
10101 @:this can't happen bbox2}{\quad bbox2@>
10102   p=link(p);
10103   if ( type(p)==mp_start_bounds_code ) incr(lev);
10104   else if ( type(p)==mp_stop_bounds_code ) decr(lev);
10105 }
10106 bblast(h)=p
10107
10108 @ It saves a lot of grief here to be slightly conservative and not account for
10109 omitted parts of dashed lines.  We also don't worry about the material omitted
10110 when using butt end caps.  The basic computation is for round end caps and
10111 |box_ends| augments it for square end caps.
10112
10113 @<Other cases for updating the bounding box...@>=
10114 case stroked_code: 
10115   mp_path_bbox(mp, path_p(p));
10116   x0=minx; y0=miny;
10117   x1=maxx; y1=maxy;
10118   mp_pen_bbox(mp, pen_p(p));
10119   minx=minx+x0;
10120   miny=miny+y0;
10121   maxx=maxx+x1;
10122   maxy=maxy+y1;
10123   mp_adjust_bbox(mp, h);
10124   if ( (left_type(path_p(p))==endpoint)&&(lcap_val(p)==2) )
10125     mp_box_ends(mp, path_p(p), pen_p(p), h);
10126   break;
10127
10128 @ The height width and depth information stored in a text node determines a
10129 rectangle that needs to be transformed according to the transformation
10130 parameters stored in the text node.
10131
10132 @<Other cases for updating the bounding box...@>=
10133 case text_code: 
10134   x1=mp_take_scaled(mp, txx_val(p),width_val(p));
10135   y0=mp_take_scaled(mp, txy_val(p),-depth_val(p));
10136   y1=mp_take_scaled(mp, txy_val(p),height_val(p));
10137   minx=tx_val(p);
10138   maxx=minx;
10139   if ( y0<y1 ) { minx=minx+y0; maxx=maxx+y1;  }
10140   else         { minx=minx+y1; maxx=maxx+y0;  }
10141   if ( x1<0 ) minx=minx+x1;  else maxx=maxx+x1;
10142   x1=mp_take_scaled(mp, tyx_val(p),width_val(p));
10143   y0=mp_take_scaled(mp, tyy_val(p),-depth_val(p));
10144   y1=mp_take_scaled(mp, tyy_val(p),height_val(p));
10145   miny=ty_val(p);
10146   maxy=miny;
10147   if ( y0<y1 ) { miny=miny+y0; maxy=maxy+y1;  }
10148   else         { miny=miny+y1; maxy=maxy+y0;  }
10149   if ( x1<0 ) miny=miny+x1;  else maxy=maxy+x1;
10150   mp_adjust_bbox(mp, h);
10151   break;
10152
10153 @ This case involves a recursive call that advances |bblast(h)| to the node of
10154 type |mp_stop_clip_code| that matches |p|.
10155
10156 @<Other cases for updating the bounding box...@>=
10157 case mp_start_clip_code: 
10158   mp_path_bbox(mp, path_p(p));
10159   x0=minx; y0=miny;
10160   x1=maxx; y1=maxy;
10161   sminx=minx_val(h); sminy=miny_val(h);
10162   smaxx=maxx_val(h); smaxy=maxy_val(h);
10163   @<Reinitialize the bounding box in header |h| and call |set_bbox| recursively
10164     starting at |link(p)|@>;
10165   @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,
10166     |y0|, |y1|@>;
10167   minx=sminx; miny=sminy;
10168   maxx=smaxx; maxy=smaxy;
10169   mp_adjust_bbox(mp, h);
10170   break;
10171
10172 @ @<Reinitialize the bounding box in header |h| and call |set_bbox|...@>=
10173 minx_val(h)=el_gordo;
10174 miny_val(h)=el_gordo;
10175 maxx_val(h)=-el_gordo;
10176 maxy_val(h)=-el_gordo;
10177 mp_set_bbox(mp, h,false)
10178
10179 @ @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,...@>=
10180 if ( minx_val(h)<x0 ) minx_val(h)=x0;
10181 if ( miny_val(h)<y0 ) miny_val(h)=y0;
10182 if ( maxx_val(h)>x1 ) maxx_val(h)=x1;
10183 if ( maxy_val(h)>y1 ) maxy_val(h)=y1
10184
10185 @* \[22] Finding an envelope.
10186 When \MP\ has a path and a polygonal pen, it needs to express the desired
10187 shape in terms of things \ps\ can understand.  The present task is to compute
10188 a new path that describes the region to be filled.  It is convenient to
10189 define this as a two step process where the first step is determining what
10190 offset to use for each segment of the path.
10191
10192 @ Given a pointer |c| to a cyclic path,
10193 and a pointer~|h| to the first knot of a pen polygon,
10194 the |offset_prep| routine changes the path into cubics that are
10195 associated with particular pen offsets. Thus if the cubic between |p|
10196 and~|q| is associated with the |k|th offset and the cubic between |q| and~|r|
10197 has offset |l| then |info(q)=zero_off+l-k|. (The constant |zero_off| is added
10198 to because |l-k| could be negative.)
10199
10200 After overwriting the type information with offset differences, we no longer
10201 have a true path so we refer to the knot list returned by |offset_prep| as an
10202 ``envelope spec.''
10203 @^envelope spec@>
10204 Since an envelope spec only determines relative changes in pen offsets,
10205 |offset_prep| sets a global variable |spec_offset| to the relative change from
10206 |h| to the first offset.
10207
10208 @d zero_off 16384 /* added to offset changes to make them positive */
10209
10210 @<Glob...@>=
10211 integer spec_offset; /* number of pen edges between |h| and the initial offset */
10212
10213 @ @c @<Declare subroutines needed by |offset_prep|@>;
10214 pointer mp_offset_prep (MP mp,pointer c, pointer h) {
10215   halfword n; /* the number of vertices in the pen polygon */
10216   pointer p,q,r,w, ww; /* for list manipulation */
10217   integer k_needed; /* amount to be added to |info(p)| when it is computed */
10218   pointer w0; /* a pointer to pen offset to use just before |p| */
10219   scaled dxin,dyin; /* the direction into knot |p| */
10220   integer turn_amt; /* change in pen offsets for the current cubic */
10221   @<Other local variables for |offset_prep|@>;
10222   dx0=0; dy0=0;
10223   @<Initialize the pen size~|n|@>;
10224   @<Initialize the incoming direction and pen offset at |c|@>;
10225   p=c; k_needed=0;
10226   do {  
10227     q=link(p);
10228     @<Split the cubic between |p| and |q|, if necessary, into cubics
10229       associated with single offsets, after which |q| should
10230       point to the end of the final such cubic@>;
10231     @<Advance |p| to node |q|, removing any ``dead'' cubics that
10232       might have been introduced by the splitting process@>;
10233   } while (q!=c);
10234   @<Fix the offset change in |info(c)| and set the return value of
10235     |offset_prep|@>;
10236 }
10237
10238 @ We shall want to keep track of where certain knots on the cyclic path
10239 wind up in the envelope spec.  It doesn't suffice just to keep pointers to
10240 knot nodes because some nodes are deleted while removing dead cubics.  Thus
10241 |offset_prep| updates the following pointers
10242
10243 @<Glob...@>=
10244 pointer spec_p1;
10245 pointer spec_p2; /* pointers to distinguished knots */
10246
10247 @ @<Set init...@>=
10248 mp->spec_p1=null; mp->spec_p2=null;
10249
10250 @ @<Initialize the pen size~|n|@>=
10251 n=0; p=h;
10252 do {  
10253   incr(n);
10254   p=link(p);
10255 } while (p!=h)
10256
10257 @ Since the true incoming direction isn't known yet, we just pick a direction
10258 consistent with the pen offset~|h|.  If this is wrong, it can be corrected
10259 later.
10260
10261 @<Initialize the incoming direction and pen offset at |c|@>=
10262 dxin=x_coord(link(h))-x_coord(knil(h));
10263 dyin=y_coord(link(h))-y_coord(knil(h));
10264 if ( (dxin==0)&&(dyin==0) ) {
10265   dxin=y_coord(knil(h))-y_coord(h);
10266   dyin=x_coord(h)-x_coord(knil(h));
10267 }
10268 w0=h
10269
10270 @ We must be careful not to remove the only cubic in a cycle.
10271
10272 But we must also be careful for another reason. If the user-supplied
10273 path starts with a set of degenerate cubics, these should not be removed
10274 because at this point we cannot do so cleanly. The relevant bug is
10275 tracker id 267, bugs 52c, reported by Boguslav.
10276
10277 @<Advance |p| to node |q|, removing any ``dead'' cubics...@>=
10278 do {  r=link(p);
10279 if ( x_coord(p)==right_x(p) ) if ( y_coord(p)==right_y(p) )
10280  if ( x_coord(p)==left_x(r) ) if ( y_coord(p)==left_y(r) )
10281   if ( x_coord(p)==x_coord(r) ) if ( y_coord(p)==y_coord(r) )
10282     if ( r!=p ) if ( ((r!=q) || (originator(r)!=metapost_user)) ) {
10283       @<Remove the cubic following |p| and update the data structures
10284         to merge |r| into |p|@>;
10285 }
10286 p=r;
10287 } while (p!=q)
10288
10289 @ @<Remove the cubic following |p| and update the data structures...@>=
10290 { k_needed=info(p)-zero_off;
10291   if ( r==q ) { 
10292     q=p;
10293   } else { 
10294     info(p)=k_needed+info(r);
10295     k_needed=0;
10296   };
10297   if ( r==c ) { info(p)=info(c); c=p; };
10298   if ( r==mp->spec_p1 ) mp->spec_p1=p;
10299   if ( r==mp->spec_p2 ) mp->spec_p2=p;
10300   r=p; mp_remove_cubic(mp, p);
10301 }
10302
10303 @ Not setting the |info| field of the newly created knot allows the splitting
10304 routine to work for paths.
10305
10306 @<Declare subroutines needed by |offset_prep|@>=
10307 void mp_split_cubic (MP mp,pointer p, fraction t) { /* splits the cubic after |p| */
10308   scaled v; /* an intermediate value */
10309   pointer q,r; /* for list manipulation */
10310   q=link(p); r=mp_get_node(mp, knot_node_size); link(p)=r; link(r)=q;
10311   originator(r)=program_code;
10312   left_type(r)=explicit; right_type(r)=explicit;
10313   v=t_of_the_way(right_x(p),left_x(q));
10314   right_x(p)=t_of_the_way(x_coord(p),right_x(p));
10315   left_x(q)=t_of_the_way(left_x(q),x_coord(q));
10316   left_x(r)=t_of_the_way(right_x(p),v);
10317   right_x(r)=t_of_the_way(v,left_x(q));
10318   x_coord(r)=t_of_the_way(left_x(r),right_x(r));
10319   v=t_of_the_way(right_y(p),left_y(q));
10320   right_y(p)=t_of_the_way(y_coord(p),right_y(p));
10321   left_y(q)=t_of_the_way(left_y(q),y_coord(q));
10322   left_y(r)=t_of_the_way(right_y(p),v);
10323   right_y(r)=t_of_the_way(v,left_y(q));
10324   y_coord(r)=t_of_the_way(left_y(r),right_y(r));
10325 }
10326
10327 @ This does not set |info(p)| or |right_type(p)|.
10328
10329 @<Declare subroutines needed by |offset_prep|@>=
10330 void mp_remove_cubic (MP mp,pointer p) { /* removes the dead cubic following~|p| */
10331   pointer q; /* the node that disappears */
10332   q=link(p); link(p)=link(q);
10333   right_x(p)=right_x(q); right_y(p)=right_y(q);
10334   mp_free_node(mp, q,knot_node_size);
10335 }
10336
10337 @ Let $d\prec d'$ mean that the counter-clockwise angle from $d$ to~$d'$ is
10338 strictly between zero and $180^\circ$.  Then we can define $d\preceq d'$ to
10339 mean that the angle could be zero or $180^\circ$. If $w_k=(u_k,v_k)$ is the
10340 $k$th pen offset, the $k$th pen edge direction is defined by the formula
10341 $$d_k=(u\k-u_k,\,v\k-v_k).$$
10342 When listed by increasing $k$, these directions occur in counter-clockwise
10343 order so that $d_k\preceq d\k$ for all~$k$.
10344 The goal of |offset_prep| is to find an offset index~|k| to associate with
10345 each cubic, such that the direction $d(t)$ of the cubic satisfies
10346 $$d_{k-1}\preceq d(t)\preceq d_k\qquad\hbox{for $0\le t\le 1$.}\eqno(*)$$
10347 We may have to split a cubic into many pieces before each
10348 piece corresponds to a unique offset.
10349
10350 @<Split the cubic between |p| and |q|, if necessary, into cubics...@>=
10351 info(p)=zero_off+k_needed;
10352 k_needed=0;
10353 @<Prepare for derivative computations;
10354   |goto not_found| if the current cubic is dead@>;
10355 @<Find the initial direction |(dx,dy)|@>;
10356 @<Update |info(p)| and find the offset $w_k$ such that
10357   $d_{k-1}\preceq(\\{dx},\\{dy})\prec d_k$; also advance |w0| for
10358   the direction change at |p|@>;
10359 @<Find the final direction |(dxin,dyin)|@>;
10360 @<Decide on the net change in pen offsets and set |turn_amt|@>;
10361 @<Complete the offset splitting process@>;
10362 w0=mp_pen_walk(mp, w0,turn_amt);
10363 NOT_FOUND: do_nothing
10364
10365 @ @<Declare subroutines needed by |offset_prep|@>=
10366 pointer mp_pen_walk (MP mp,pointer w, integer k) {
10367   /* walk |k| steps around a pen from |w| */
10368   while ( k>0 ) { w=link(w); decr(k);  };
10369   while ( k<0 ) { w=knil(w); incr(k);  };
10370   return w;
10371 }
10372
10373 @ The direction of a cubic $B(z_0,z_1,z_2,z_3;t)=\bigl(x(t),y(t)\bigr)$ can be
10374 calculated from the quadratic polynomials
10375 ${1\over3}x'(t)=B(x_1-x_0,x_2-x_1,x_3-x_2;t)$ and
10376 ${1\over3}y'(t)=B(y_1-y_0,y_2-y_1,y_3-y_2;t)$.
10377 Since we may be calculating directions from several cubics
10378 split from the current one, it is desirable to do these calculations
10379 without losing too much precision. ``Scaled up'' values of the
10380 derivatives, which will be less tainted by accumulated errors than
10381 derivatives found from the cubics themselves, are maintained in
10382 local variables |x0|, |x1|, and |x2|, representing $X_0=2^l(x_1-x_0)$,
10383 $X_1=2^l(x_2-x_1)$, and $X_2=2^l(x_3-x_2)$; similarly |y0|, |y1|, and~|y2|
10384 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)$.
10385
10386 @<Other local variables for |offset_prep|@>=
10387 integer x0,x1,x2,y0,y1,y2; /* representatives of derivatives */
10388 integer t0,t1,t2; /* coefficients of polynomial for slope testing */
10389 integer du,dv,dx,dy; /* for directions of the pen and the curve */
10390 integer dx0,dy0; /* initial direction for the first cubic in the curve */
10391 integer mp_max_coef; /* used while scaling */
10392 integer x0a,x1a,x2a,y0a,y1a,y2a; /* intermediate values */
10393 fraction t; /* where the derivative passes through zero */
10394 fraction s; /* a temporary value */
10395
10396 @ @<Prepare for derivative computations...@>=
10397 x0=right_x(p)-x_coord(p);
10398 x2=x_coord(q)-left_x(q);
10399 x1=left_x(q)-right_x(p);
10400 y0=right_y(p)-y_coord(p); y2=y_coord(q)-left_y(q);
10401 y1=left_y(q)-right_y(p);
10402 mp_max_coef=abs(x0);
10403 if ( abs(x1)>mp_max_coef ) mp_max_coef=abs(x1);
10404 if ( abs(x2)>mp_max_coef ) mp_max_coef=abs(x2);
10405 if ( abs(y0)>mp_max_coef ) mp_max_coef=abs(y0);
10406 if ( abs(y1)>mp_max_coef ) mp_max_coef=abs(y1);
10407 if ( abs(y2)>mp_max_coef ) mp_max_coef=abs(y2);
10408 if ( mp_max_coef==0 ) goto NOT_FOUND;
10409 while ( mp_max_coef<fraction_half ) {
10410   mp_max_coef+=mp_max_coef;
10411   x0+=x0; x1+=x1; x2+=x2;
10412   y0+=y0; y1+=y1; y2+=y2;
10413 }
10414
10415 @ Let us first solve a special case of the problem: Suppose we
10416 know an index~$k$ such that either (i)~$d(t)\succeq d_{k-1}$ for all~$t$
10417 and $d(0)\prec d_k$, or (ii)~$d(t)\preceq d_k$ for all~$t$ and
10418 $d(0)\succ d_{k-1}$.
10419 Then, in a sense, we're halfway done, since one of the two relations
10420 in $(*)$ is satisfied, and the other couldn't be satisfied for
10421 any other value of~|k|.
10422
10423 Actually, the conditions can be relaxed somewhat since a relation such as
10424 $d(t)\succeq d_{k-1}$ restricts $d(t)$ to a half plane when all that really
10425 matters is whether $d(t)$ crosses the ray in the $d_{k-1}$ direction from
10426 the origin.  The condition for case~(i) becomes $d_{k-1}\preceq d(0)\prec d_k$
10427 and $d(t)$ never crosses the $d_{k-1}$ ray in the clockwise direction.
10428 Case~(ii) is similar except $d(t)$ cannot cross the $d_k$ ray in the
10429 counterclockwise direction.
10430
10431 The |fin_offset_prep| subroutine solves the stated subproblem.
10432 It has a parameter called |rise| that is |1| in
10433 case~(i), |-1| in case~(ii). Parameters |x0| through |y2| represent
10434 the derivative of the cubic following |p|.
10435 The |w| parameter should point to offset~$w_k$ and |info(p)| should already
10436 be set properly.  The |turn_amt| parameter gives the absolute value of the
10437 overall net change in pen offsets.
10438
10439 @<Declare subroutines needed by |offset_prep|@>=
10440 void mp_fin_offset_prep (MP mp,pointer p, pointer w, integer 
10441   x0,integer x1, integer x2, integer y0, integer y1, integer y2, 
10442   integer rise, integer turn_amt)  {
10443   pointer ww; /* for list manipulation */
10444   scaled du,dv; /* for slope calculation */
10445   integer t0,t1,t2; /* test coefficients */
10446   fraction t; /* place where the derivative passes a critical slope */
10447   fraction s; /* slope or reciprocal slope */
10448   integer v; /* intermediate value for updating |x0..y2| */
10449   pointer q; /* original |link(p)| */
10450   q=link(p);
10451   while (1)  { 
10452     if ( rise>0 ) ww=link(w); /* a pointer to $w\k$ */
10453     else  ww=knil(w); /* a pointer to $w_{k-1}$ */
10454     @<Compute test coefficients |(t0,t1,t2)|
10455       for $d(t)$ versus $d_k$ or $d_{k-1}$@>;
10456     t=mp_crossing_point(mp, t0,t1,t2);
10457     if ( t>=fraction_one ) {
10458       if ( turn_amt>0 ) t=fraction_one;  else return;
10459     }
10460     @<Split the cubic at $t$,
10461       and split off another cubic if the derivative crosses back@>;
10462     w=ww;
10463   }
10464 }
10465
10466 @ We want $B(\\{t0},\\{t1},\\{t2};t)$ to be the dot product of $d(t)$ with a
10467 $-90^\circ$ rotation of the vector from |w| to |ww|.  This makes the resulting
10468 function cross from positive to negative when $d_{k-1}\preceq d(t)\preceq d_k$
10469 begins to fail.
10470
10471 @<Compute test coefficients |(t0,t1,t2)| for $d(t)$ versus...@>=
10472 du=x_coord(ww)-x_coord(w); dv=y_coord(ww)-y_coord(w);
10473 if ( abs(du)>=abs(dv) ) {
10474   s=mp_make_fraction(mp, dv,du);
10475   t0=mp_take_fraction(mp, x0,s)-y0;
10476   t1=mp_take_fraction(mp, x1,s)-y1;
10477   t2=mp_take_fraction(mp, x2,s)-y2;
10478   if ( du<0 ) { negate(t0); negate(t1); negate(t2);  }
10479 } else { 
10480   s=mp_make_fraction(mp, du,dv);
10481   t0=x0-mp_take_fraction(mp, y0,s);
10482   t1=x1-mp_take_fraction(mp, y1,s);
10483   t2=x2-mp_take_fraction(mp, y2,s);
10484   if ( dv<0 ) { negate(t0); negate(t1); negate(t2);  }
10485 }
10486 if ( t0<0 ) t0=0 /* should be positive without rounding error */
10487
10488 @ The curve has crossed $d_k$ or $d_{k-1}$; its initial segment satisfies
10489 $(*)$, and it might cross again, yielding another solution of $(*)$.
10490
10491 @<Split the cubic at $t$, and split off another...@>=
10492
10493 mp_split_cubic(mp, p,t); p=link(p); info(p)=zero_off+rise;
10494 decr(turn_amt);
10495 v=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10496 x0=t_of_the_way(v,x1);
10497 v=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10498 y0=t_of_the_way(v,y1);
10499 if ( turn_amt<0 ) {
10500   t1=t_of_the_way(t1,t2);
10501   if ( t1>0 ) t1=0; /* without rounding error, |t1| would be |<=0| */
10502   t=mp_crossing_point(mp, 0,-t1,-t2);
10503   if ( t>fraction_one ) t=fraction_one;
10504   incr(turn_amt);
10505   if ( (t==fraction_one)&&(link(p)!=q) ) {
10506     info(link(p))=info(link(p))-rise;
10507   } else { 
10508     mp_split_cubic(mp, p,t); info(link(p))=zero_off-rise;
10509     v=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10510     x2=t_of_the_way(x1,v);
10511     v=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10512     y2=t_of_the_way(y1,v);
10513   }
10514 }
10515 }
10516
10517 @ Now we must consider the general problem of |offset_prep|, when
10518 nothing is known about a given cubic. We start by finding its
10519 direction in the vicinity of |t=0|.
10520
10521 If $z'(t)=0$, the given cubic is numerically unstable but |offset_prep|
10522 has not yet introduced any more numerical errors.  Thus we can compute
10523 the true initial direction for the given cubic, even if it is almost
10524 degenerate.
10525
10526 @<Find the initial direction |(dx,dy)|@>=
10527 dx=x0; dy=y0;
10528 if ( dx==0 ) if ( dy==0 ) { 
10529   dx=x1; dy=y1;
10530   if ( dx==0 ) if ( dy==0 ) { 
10531     dx=x2; dy=y2;
10532   }
10533 }
10534 if ( p==c ) { dx0=dx; dy0=dy;  }
10535
10536 @ @<Find the final direction |(dxin,dyin)|@>=
10537 dxin=x2; dyin=y2;
10538 if ( dxin==0 ) if ( dyin==0 ) {
10539   dxin=x1; dyin=y1;
10540   if ( dxin==0 ) if ( dyin==0 ) {
10541     dxin=x0; dyin=y0;
10542   }
10543 }
10544
10545 @ The next step is to bracket the initial direction between consecutive
10546 edges of the pen polygon.  We must be careful to turn clockwise only if
10547 this makes the turn less than $180^\circ$. (A $180^\circ$ turn must be
10548 counter-clockwise in order to make \&{doublepath} envelopes come out
10549 @:double_path_}{\&{doublepath} primitive@>
10550 right.) This code depends on |w0| being the offset for |(dxin,dyin)|.
10551
10552 @<Update |info(p)| and find the offset $w_k$ such that...@>=
10553 turn_amt=mp_get_turn_amt(mp, w0, dx, dy, mp_ab_vs_cd(mp, dy,dxin,dx,dyin)>=0);
10554 w=mp_pen_walk(mp, w0, turn_amt);
10555 w0=w;
10556 info(p)=info(p)+turn_amt
10557
10558 @ Decide how many pen offsets to go away from |w| in order to find the offset
10559 for |(dx,dy)|, going counterclockwise if |ccw| is |true|.  This assumes that
10560 |w| is the offset for some direction $(x',y')$ from which the angle to |(dx,dy)|
10561 in the sense determined by |ccw| is less than or equal to $180^\circ$.
10562
10563 If the pen polygon has only two edges, they could both be parallel
10564 to |(dx,dy)|.  In this case, we must be careful to stop after crossing the first
10565 such edge in order to avoid an infinite loop.
10566
10567 @<Declare subroutines needed by |offset_prep|@>=
10568 integer mp_get_turn_amt (MP mp,pointer w, scaled  dx,
10569                          scaled dy, boolean  ccw) {
10570   pointer ww; /* a neighbor of knot~|w| */
10571   integer s; /* turn amount so far */
10572   integer t; /* |ab_vs_cd| result */
10573   s=0;
10574   if ( ccw ) { 
10575     ww=link(w);
10576     do {  
10577       t=mp_ab_vs_cd(mp, dy,x_coord(ww)-x_coord(w),
10578                         dx,y_coord(ww)-y_coord(w));
10579       if ( t<0 ) break;
10580       incr(s);
10581       w=ww; ww=link(ww);
10582     } while (t>0);
10583   } else { 
10584     ww=knil(w);
10585     while ( mp_ab_vs_cd(mp, dy,x_coord(w)-x_coord(ww),
10586                             dx,y_coord(w)-y_coord(ww))<0 ) { 
10587       decr(s);
10588       w=ww; ww=knil(ww);
10589     }
10590   }
10591   return s;
10592 }
10593
10594 @ When we're all done, the final offset is |w0| and the final curve direction
10595 is |(dxin,dyin)|.  With this knowledge of the incoming direction at |c|, we
10596 can correct |info(c)| which was erroneously based on an incoming offset
10597 of~|h|.
10598
10599 @d fix_by(A) info(c)=info(c)+(A)
10600
10601 @<Fix the offset change in |info(c)| and set the return value of...@>=
10602 mp->spec_offset=info(c)-zero_off;
10603 if ( link(c)==c ) {
10604   info(c)=zero_off+n;
10605 } else { 
10606   fix_by(k_needed);
10607   while ( w0!=h ) { fix_by(1); w0=link(w0);  };
10608   while ( info(c)<=zero_off-n ) fix_by(n);
10609   while ( info(c)>zero_off ) fix_by(-n);
10610   if ( (info(c)!=zero_off)&&(mp_ab_vs_cd(mp, dy0,dxin,dx0,dyin)>=0) ) fix_by(n);
10611 }
10612 return c
10613
10614 @ Finally we want to reduce the general problem to situations that
10615 |fin_offset_prep| can handle. We split the cubic into at most three parts
10616 with respect to $d_{k-1}$, and apply |fin_offset_prep| to each part.
10617
10618 @<Complete the offset splitting process@>=
10619 ww=knil(w);
10620 @<Compute test coeff...@>;
10621 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set
10622   |t:=fraction_one+1|@>;
10623 if ( t>fraction_one ) {
10624   mp_fin_offset_prep(mp, p,w,x0,x1,x2,y0,y1,y2,1,turn_amt);
10625 } else {
10626   mp_split_cubic(mp, p,t); r=link(p);
10627   x1a=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10628   x2a=t_of_the_way(x1a,x1);
10629   y1a=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10630   y2a=t_of_the_way(y1a,y1);
10631   mp_fin_offset_prep(mp, p,w,x0,x1a,x2a,y0,y1a,y2a,1,0); x0=x2a; y0=y2a;
10632   info(r)=zero_off-1;
10633   if ( turn_amt>=0 ) {
10634     t1=t_of_the_way(t1,t2);
10635     if ( t1>0 ) t1=0;
10636     t=mp_crossing_point(mp, 0,-t1,-t2);
10637     if ( t>fraction_one ) t=fraction_one;
10638     @<Split off another rising cubic for |fin_offset_prep|@>;
10639     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,0);
10640   } else {
10641     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,-1-turn_amt);
10642   }
10643 }
10644
10645 @ @<Split off another rising cubic for |fin_offset_prep|@>=
10646 mp_split_cubic(mp, r,t); info(link(r))=zero_off+1;
10647 x1a=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10648 x0a=t_of_the_way(x1,x1a);
10649 y1a=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10650 y0a=t_of_the_way(y1,y1a);
10651 mp_fin_offset_prep(mp, link(r),w,x0a,x1a,x2,y0a,y1a,y2,1,turn_amt);
10652 x2=x0a; y2=y0a
10653
10654 @ At this point, the direction of the incoming pen edge is |(-du,-dv)|.
10655 When the component of $d(t)$ perpendicular to |(-du,-dv)| crosses zero, we
10656 need to decide whether the directions are parallel or antiparallel.  We
10657 can test this by finding the dot product of $d(t)$ and |(-du,-dv)|, but this
10658 should be avoided when the value of |turn_amt| already determines the
10659 answer.  If |t2<0|, there is one crossing and it is antiparallel only if
10660 |turn_amt>=0|.  If |turn_amt<0|, there should always be at least one
10661 crossing and the first crossing cannot be antiparallel.
10662
10663 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set...@>=
10664 t=mp_crossing_point(mp, t0,t1,t2);
10665 if ( turn_amt>=0 ) {
10666   if ( t2<0 ) {
10667     t=fraction_one+1;
10668   } else { 
10669     u0=t_of_the_way(x0,x1);
10670     u1=t_of_the_way(x1,x2);
10671     ss=mp_take_fraction(mp, -du,t_of_the_way(u0,u1));
10672     v0=t_of_the_way(y0,y1);
10673     v1=t_of_the_way(y1,y2);
10674     ss=ss+mp_take_fraction(mp, -dv,t_of_the_way(v0,v1));
10675     if ( ss<0 ) t=fraction_one+1;
10676   }
10677 } else if ( t>fraction_one ) {
10678   t=fraction_one;
10679 }
10680
10681 @ @<Other local variables for |offset_prep|@>=
10682 integer u0,u1,v0,v1; /* intermediate values for $d(t)$ calculation */
10683 integer ss = 0; /* the part of the dot product computed so far */
10684 int d_sign; /* sign of overall change in direction for this cubic */
10685
10686 @ If the cubic almost has a cusp, it is a numerically ill-conditioned
10687 problem to decide which way it loops around but that's OK as long we're
10688 consistent.  To make \&{doublepath} envelopes work properly, reversing
10689 the path should always change the sign of |turn_amt|.
10690
10691 @<Decide on the net change in pen offsets and set |turn_amt|@>=
10692 d_sign=mp_ab_vs_cd(mp, dx,dyin, dxin,dy);
10693 if ( d_sign==0 ) {
10694   if ( dx==0 ) {
10695     if ( dy>0 ) d_sign=1;  else d_sign=-1;
10696   } else if ( dx>0 ) { 
10697     d_sign=1;  
10698   } else { 
10699     d_sign=-1; 
10700   }
10701 }
10702 @<Make |ss| negative if and only if the total change in direction is
10703   more than $180^\circ$@>;
10704 turn_amt=mp_get_turn_amt(mp, w, dxin, dyin, d_sign>0);
10705 if ( ss<0 ) turn_amt=turn_amt-d_sign*n
10706
10707 @ In order to be invariant under path reversal, the result of this computation
10708 should not change when |x0|, |y0|, $\ldots$ are all negated and |(x0,y0)| is
10709 then swapped with |(x2,y2)|.  We make use of the identities
10710 |take_fraction(-a,-b)=take_fraction(a,b)| and
10711 |t_of_the_way(-a,-b)=-(t_of_the_way(a,b))|.
10712
10713 @<Make |ss| negative if and only if the total change in direction is...@>=
10714 t0=half(mp_take_fraction(mp, x0,y2))-half(mp_take_fraction(mp, x2,y0));
10715 t1=half(mp_take_fraction(mp, x1,y0+y2))-half(mp_take_fraction(mp, y1,x0+x2));
10716 if ( t0==0 ) t0=d_sign; /* path reversal always negates |d_sign| */
10717 if ( t0>0 ) {
10718   t=mp_crossing_point(mp, t0,t1,-t0);
10719   u0=t_of_the_way(x0,x1);
10720   u1=t_of_the_way(x1,x2);
10721   v0=t_of_the_way(y0,y1);
10722   v1=t_of_the_way(y1,y2);
10723 } else { 
10724   t=mp_crossing_point(mp, -t0,t1,t0);
10725   u0=t_of_the_way(x2,x1);
10726   u1=t_of_the_way(x1,x0);
10727   v0=t_of_the_way(y2,y1);
10728   v1=t_of_the_way(y1,y0);
10729 }
10730 s=mp_take_fraction(mp, x0+x2,t_of_the_way(u0,u1))+
10731   mp_take_fraction(mp, y0+y2,t_of_the_way(v0,v1))
10732
10733 @ Here's a routine that prints an envelope spec in symbolic form.  It assumes
10734 that the |cur_pen| has not been walked around to the first offset.
10735
10736 @c 
10737 void mp_print_spec (MP mp,pointer cur_spec, pointer cur_pen, char *s) {
10738   pointer p,q; /* list traversal */
10739   pointer w; /* the current pen offset */
10740   mp_print_diagnostic(mp, "Envelope spec",s,true);
10741   p=cur_spec; w=mp_pen_walk(mp, cur_pen,mp->spec_offset);
10742   mp_print_ln(mp);
10743   mp_print_two(mp, x_coord(cur_spec),y_coord(cur_spec));
10744   mp_print(mp, " % beginning with offset ");
10745   mp_print_two(mp, x_coord(w),y_coord(w));
10746   do { 
10747     do {  
10748       q=link(p);
10749       @<Print the cubic between |p| and |q|@>;
10750       p=q;
10751     } while (! ((p==cur_spec) || (info(p)!=zero_off)));
10752     if ( info(p)!=zero_off ) {
10753       @<Update |w| as indicated by |info(p)| and print an explanation@>;
10754     }
10755   } while (p!=cur_spec);
10756   mp_print_nl(mp, " & cycle");
10757   mp_end_diagnostic(mp, true);
10758 }
10759
10760 @ @<Update |w| as indicated by |info(p)| and print an explanation@>=
10761
10762   w=mp_pen_walk(mp, w,info(p)-zero_off);
10763   mp_print(mp, " % ");
10764   if ( info(p)>zero_off ) mp_print(mp, "counter");
10765   mp_print(mp, "clockwise to offset ");
10766   mp_print_two(mp, x_coord(w),y_coord(w));
10767 }
10768
10769 @ @<Print the cubic between |p| and |q|@>=
10770
10771   mp_print_nl(mp, "   ..controls ");
10772   mp_print_two(mp, right_x(p),right_y(p));
10773   mp_print(mp, " and ");
10774   mp_print_two(mp, left_x(q),left_y(q));
10775   mp_print_nl(mp, " ..");
10776   mp_print_two(mp, x_coord(q),y_coord(q));
10777 }
10778
10779 @ Once we have an envelope spec, the remaining task to construct the actual
10780 envelope by offsetting each cubic as determined by the |info| fields in
10781 the knots.  First we use |offset_prep| to convert the |c| into an envelope
10782 spec. Then we add the offsets so that |c| becomes a cyclic path that represents
10783 the envelope.
10784
10785 The |ljoin| and |miterlim| parameters control the treatment of points where the
10786 pen offset changes, and |lcap| controls the endpoints of a \&{doublepath}.
10787 The endpoints are easily located because |c| is given in undoubled form
10788 and then doubled in this procedure.  We use |spec_p1| and |spec_p2| to keep
10789 track of the endpoints and treat them like very sharp corners.
10790 Butt end caps are treated like beveled joins; round end caps are treated like
10791 round joins; and square end caps are achieved by setting |join_type:=3|.
10792
10793 None of these parameters apply to inside joins where the convolution tracing
10794 has retrograde lines.  In such cases we use a simple connect-the-endpoints
10795 approach that is achieved by setting |join_type:=2|.
10796
10797 @c @<Declare a function called |insert_knot|@>;
10798 pointer mp_make_envelope (MP mp,pointer c, pointer h, small_number ljoin,
10799   small_number lcap, scaled miterlim) {
10800   pointer p,q,r,q0; /* for manipulating the path */
10801   int join_type=0; /* codes |0..3| for mitered, round, beveled, or square */
10802   pointer w,w0; /* the pen knot for the current offset */
10803   scaled qx,qy; /* unshifted coordinates of |q| */
10804   halfword k,k0; /* controls pen edge insertion */
10805   @<Other local variables for |make_envelope|@>;
10806   dxin=0; dyin=0; dxout=0; dyout=0;
10807   mp->spec_p1=null; mp->spec_p2=null;
10808   @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>;
10809   @<Use |offset_prep| to compute the envelope spec then walk |h| around to
10810     the initial offset@>;
10811   w=h;
10812   p=c;
10813   do {  
10814     q=link(p); q0=q;
10815     qx=x_coord(q); qy=y_coord(q);
10816     k=info(q);
10817     k0=k; w0=w;
10818     if ( k!=zero_off ) {
10819       @<Set |join_type| to indicate how to handle offset changes at~|q|@>;
10820     }
10821     @<Add offset |w| to the cubic from |p| to |q|@>;
10822     while ( k!=zero_off ) { 
10823       @<Step |w| and move |k| one step closer to |zero_off|@>;
10824       if ( (join_type==1)||(k==zero_off) )
10825          q=mp_insert_knot(mp, q,qx+x_coord(w),qy+y_coord(w));
10826     };
10827     if ( q!=link(p) ) {
10828       @<Set |p=link(p)| and add knots between |p| and |q| as
10829         required by |join_type|@>;
10830     }
10831     p=q;
10832   } while (q0!=c);
10833   return c;
10834 }
10835
10836 @ @<Use |offset_prep| to compute the envelope spec then walk |h| around to...@>=
10837 c=mp_offset_prep(mp, c,h);
10838 if ( mp->internal[tracing_specs]>0 ) 
10839   mp_print_spec(mp, c,h,"");
10840 h=mp_pen_walk(mp, h,mp->spec_offset)
10841
10842 @ Mitered and squared-off joins depend on path directions that are difficult to
10843 compute for degenerate cubics.  The envelope spec computed by |offset_prep| can
10844 have degenerate cubics only if the entire cycle collapses to a single
10845 degenerate cubic.  Setting |join_type:=2| in this case makes the computed
10846 envelope degenerate as well.
10847
10848 @<Set |join_type| to indicate how to handle offset changes at~|q|@>=
10849 if ( k<zero_off ) {
10850   join_type=2;
10851 } else {
10852   if ( (q!=mp->spec_p1)&&(q!=mp->spec_p2) ) join_type=ljoin;
10853   else if ( lcap==2 ) join_type=3;
10854   else join_type=2-lcap;
10855   if ( (join_type==0)||(join_type==3) ) {
10856     @<Set the incoming and outgoing directions at |q|; in case of
10857       degeneracy set |join_type:=2|@>;
10858     if ( join_type==0 ) {
10859       @<If |miterlim| is less than the secant of half the angle at |q|
10860         then set |join_type:=2|@>;
10861     }
10862   }
10863 }
10864
10865 @ @<If |miterlim| is less than the secant of half the angle at |q|...@>=
10866
10867   tmp=mp_take_fraction(mp, miterlim,fraction_half+
10868       half(mp_take_fraction(mp, dxin,dxout)+mp_take_fraction(mp, dyin,dyout)));
10869   if ( tmp<unity )
10870     if ( mp_take_scaled(mp, miterlim,tmp)<unity ) join_type=2;
10871 }
10872
10873 @ @<Other local variables for |make_envelope|@>=
10874 fraction dxin,dyin,dxout,dyout; /* directions at |q| when square or mitered */
10875 scaled tmp; /* a temporary value */
10876
10877 @ The coordinates of |p| have already been shifted unless |p| is the first
10878 knot in which case they get shifted at the very end.
10879
10880 @<Add offset |w| to the cubic from |p| to |q|@>=
10881 right_x(p)=right_x(p)+x_coord(w);
10882 right_y(p)=right_y(p)+y_coord(w);
10883 left_x(q)=left_x(q)+x_coord(w);
10884 left_y(q)=left_y(q)+y_coord(w);
10885 x_coord(q)=x_coord(q)+x_coord(w);
10886 y_coord(q)=y_coord(q)+y_coord(w);
10887 left_type(q)=explicit;
10888 right_type(q)=explicit
10889
10890 @ @<Step |w| and move |k| one step closer to |zero_off|@>=
10891 if ( k>zero_off ){ w=link(w); decr(k);  }
10892 else { w=knil(w); incr(k);  }
10893
10894 @ The cubic from |q| to the new knot at |(x,y)| becomes a line segment and
10895 the |right_x| and |right_y| fields of |r| are set from |q|.  This is done in
10896 case the cubic containing these control points is ``yet to be examined.''
10897
10898 @<Declare a function called |insert_knot|@>=
10899 pointer mp_insert_knot (MP mp,pointer q, scaled x, scaled y) {
10900   /* returns the inserted knot */
10901   pointer r; /* the new knot */
10902   r=mp_get_node(mp, knot_node_size);
10903   link(r)=link(q); link(q)=r;
10904   right_x(r)=right_x(q);
10905   right_y(r)=right_y(q);
10906   x_coord(r)=x;
10907   y_coord(r)=y;
10908   right_x(q)=x_coord(q);
10909   right_y(q)=y_coord(q);
10910   left_x(r)=x_coord(r);
10911   left_y(r)=y_coord(r);
10912   left_type(r)=explicit;
10913   right_type(r)=explicit;
10914   originator(r)=program_code;
10915   return r;
10916 }
10917
10918 @ After setting |p:=link(p)|, either |join_type=1| or |q=link(p)|.
10919
10920 @<Set |p=link(p)| and add knots between |p| and |q| as...@>=
10921
10922   p=link(p);
10923   if ( (join_type==0)||(join_type==3) ) {
10924     if ( join_type==0 ) {
10925       @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>
10926     } else {
10927       @<Make |r| the last of two knots inserted between |p| and |q| to form a
10928         squared join@>;
10929     }
10930     if ( r!=null ) { 
10931       right_x(r)=x_coord(r);
10932       right_y(r)=y_coord(r);
10933     }
10934   }
10935 }
10936
10937 @ For very small angles, adding a knot is unnecessary and would cause numerical
10938 problems, so we just set |r:=null| in that case.
10939
10940 @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>=
10941
10942   det=mp_take_fraction(mp, dyout,dxin)-mp_take_fraction(mp, dxout,dyin);
10943   if ( abs(det)<26844 ) { 
10944      r=null; /* sine $<10^{-4}$ */
10945   } else { 
10946     tmp=mp_take_fraction(mp, x_coord(q)-x_coord(p),dyout)-
10947         mp_take_fraction(mp, y_coord(q)-y_coord(p),dxout);
10948     tmp=mp_make_fraction(mp, tmp,det);
10949     r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
10950       y_coord(p)+mp_take_fraction(mp, tmp,dyin));
10951   }
10952 }
10953
10954 @ @<Other local variables for |make_envelope|@>=
10955 fraction det; /* a determinant used for mitered join calculations */
10956
10957 @ @<Make |r| the last of two knots inserted between |p| and |q| to form a...@>=
10958
10959   ht_x=y_coord(w)-y_coord(w0);
10960   ht_y=x_coord(w0)-x_coord(w);
10961   while ( (abs(ht_x)<fraction_half)&&(abs(ht_y)<fraction_half) ) { 
10962     ht_x+=ht_x; ht_y+=ht_y;
10963   }
10964   @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range dot
10965     product with |(ht_x,ht_y)|@>;
10966   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxin,ht_x)+
10967                                   mp_take_fraction(mp, dyin,ht_y));
10968   r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
10969                          y_coord(p)+mp_take_fraction(mp, tmp,dyin));
10970   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxout,ht_x)+
10971                                   mp_take_fraction(mp, dyout,ht_y));
10972   r=mp_insert_knot(mp, r,x_coord(q)+mp_take_fraction(mp, tmp,dxout),
10973                          y_coord(q)+mp_take_fraction(mp, tmp,dyout));
10974 }
10975
10976 @ @<Other local variables for |make_envelope|@>=
10977 fraction ht_x,ht_y; /* perpendicular to the segment from |p| to |q| */
10978 scaled max_ht; /* maximum height of the pen polygon above the |w0|-|w| line */
10979 halfword kk; /* keeps track of the pen vertices being scanned */
10980 pointer ww; /* the pen vertex being tested */
10981
10982 @ The dot product of the vector from |w0| to |ww| with |(ht_x,ht_y)| ranges
10983 from zero to |max_ht|.
10984
10985 @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range...@>=
10986 max_ht=0;
10987 kk=zero_off;
10988 ww=w;
10989 while (1)  { 
10990   @<Step |ww| and move |kk| one step closer to |k0|@>;
10991   if ( kk==k0 ) break;
10992   tmp=mp_take_fraction(mp, x_coord(ww)-x_coord(w0),ht_x)+
10993       mp_take_fraction(mp, y_coord(ww)-y_coord(w0),ht_y);
10994   if ( tmp>max_ht ) max_ht=tmp;
10995 }
10996
10997
10998 @ @<Step |ww| and move |kk| one step closer to |k0|@>=
10999 if ( kk>k0 ) { ww=link(ww); decr(kk);  }
11000 else { ww=knil(ww); incr(kk);  }
11001
11002 @ @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>=
11003 if ( left_type(c)==endpoint ) { 
11004   mp->spec_p1=mp_htap_ypoc(mp, c);
11005   mp->spec_p2=mp->path_tail;
11006   originator(mp->spec_p1)=program_code;
11007   link(mp->spec_p2)=link(mp->spec_p1);
11008   link(mp->spec_p1)=c;
11009   mp_remove_cubic(mp, mp->spec_p1);
11010   c=mp->spec_p1;
11011   if ( c!=link(c) ) {
11012     originator(mp->spec_p2)=program_code;
11013     mp_remove_cubic(mp, mp->spec_p2);
11014   } else {
11015     @<Make |c| look like a cycle of length one@>;
11016   }
11017 }
11018
11019 @ @<Make |c| look like a cycle of length one@>=
11020
11021   left_type(c)=explicit; right_type(c)=explicit;
11022   left_x(c)=x_coord(c); left_y(c)=y_coord(c);
11023   right_x(c)=x_coord(c); right_y(c)=y_coord(c);
11024 }
11025
11026 @ In degenerate situations we might have to look at the knot preceding~|q|.
11027 That knot is |p| but if |p<>c|, its coordinates have already been offset by |w|.
11028
11029 @<Set the incoming and outgoing directions at |q|; in case of...@>=
11030 dxin=x_coord(q)-left_x(q);
11031 dyin=y_coord(q)-left_y(q);
11032 if ( (dxin==0)&&(dyin==0) ) {
11033   dxin=x_coord(q)-right_x(p);
11034   dyin=y_coord(q)-right_y(p);
11035   if ( (dxin==0)&&(dyin==0) ) {
11036     dxin=x_coord(q)-x_coord(p);
11037     dyin=y_coord(q)-y_coord(p);
11038     if ( p!=c ) { /* the coordinates of |p| have been offset by |w| */
11039       dxin=dxin+x_coord(w);
11040       dyin=dyin+y_coord(w);
11041     }
11042   }
11043 }
11044 tmp=mp_pyth_add(mp, dxin,dyin);
11045 if ( tmp==0 ) {
11046   join_type=2;
11047 } else { 
11048   dxin=mp_make_fraction(mp, dxin,tmp);
11049   dyin=mp_make_fraction(mp, dyin,tmp);
11050   @<Set the outgoing direction at |q|@>;
11051 }
11052
11053 @ If |q=c| then the coordinates of |r| and the control points between |q|
11054 and~|r| have already been offset by |h|.
11055
11056 @<Set the outgoing direction at |q|@>=
11057 dxout=right_x(q)-x_coord(q);
11058 dyout=right_y(q)-y_coord(q);
11059 if ( (dxout==0)&&(dyout==0) ) {
11060   r=link(q);
11061   dxout=left_x(r)-x_coord(q);
11062   dyout=left_y(r)-y_coord(q);
11063   if ( (dxout==0)&&(dyout==0) ) {
11064     dxout=x_coord(r)-x_coord(q);
11065     dyout=y_coord(r)-y_coord(q);
11066   }
11067 }
11068 if ( q==c ) {
11069   dxout=dxout-x_coord(h);
11070   dyout=dyout-y_coord(h);
11071 }
11072 tmp=mp_pyth_add(mp, dxout,dyout);
11073 if ( tmp==0 ) mp_confusion(mp, "degenerate spec");
11074 @:this can't happen degerate spec}{\quad degenerate spec@>
11075 dxout=mp_make_fraction(mp, dxout,tmp);
11076 dyout=mp_make_fraction(mp, dyout,tmp)
11077
11078 @* \[23] Direction and intersection times.
11079 A path of length $n$ is defined parametrically by functions $x(t)$ and
11080 $y(t)$, for |0<=t<=n|; we can regard $t$ as the ``time'' at which the path
11081 reaches the point $\bigl(x(t),y(t)\bigr)$.  In this section of the program
11082 we shall consider operations that determine special times associated with
11083 given paths: the first time that a path travels in a given direction, and
11084 a pair of times at which two paths cross each other.
11085
11086 @ Let's start with the easier task. The function |find_direction_time| is
11087 given a direction |(x,y)| and a path starting at~|h|. If the path never
11088 travels in direction |(x,y)|, the direction time will be~|-1|; otherwise
11089 it will be nonnegative.
11090
11091 Certain anomalous cases can arise: If |(x,y)=(0,0)|, so that the given
11092 direction is undefined, the direction time will be~0. If $\bigl(x'(t),
11093 y'(t)\bigr)=(0,0)$, so that the path direction is undefined, it will be
11094 assumed to match any given direction at time~|t|.
11095
11096 The routine solves this problem in nondegenerate cases by rotating the path
11097 and the given direction so that |(x,y)=(1,0)|; i.e., the main task will be
11098 to find when a given path first travels ``due east.''
11099
11100 @c 
11101 scaled mp_find_direction_time (MP mp,scaled x, scaled y, pointer h) {
11102   scaled max; /* $\max\bigl(\vert x\vert,\vert y\vert\bigr)$ */
11103   pointer p,q; /* for list traversal */
11104   scaled n; /* the direction time at knot |p| */
11105   scaled tt; /* the direction time within a cubic */
11106   @<Other local variables for |find_direction_time|@>;
11107   @<Normalize the given direction for better accuracy;
11108     but |return| with zero result if it's zero@>;
11109   n=0; p=h; phi=0;
11110   while (1) { 
11111     if ( right_type(p)==endpoint ) break;
11112     q=link(p);
11113     @<Rotate the cubic between |p| and |q|; then
11114       |goto found| if the rotated cubic travels due east at some time |tt|;
11115       but |break| if an entire cyclic path has been traversed@>;
11116     p=q; n=n+unity;
11117   }
11118   return (-unity);
11119 FOUND: 
11120   return (n+tt);
11121 }
11122
11123 @ @<Normalize the given direction for better accuracy...@>=
11124 if ( abs(x)<abs(y) ) { 
11125   x=mp_make_fraction(mp, x,abs(y));
11126   if ( y>0 ) y=fraction_one; else y=-fraction_one;
11127 } else if ( x==0 ) { 
11128   return 0;
11129 } else  { 
11130   y=mp_make_fraction(mp, y,abs(x));
11131   if ( x>0 ) x=fraction_one; else x=-fraction_one;
11132 }
11133
11134 @ Since we're interested in the tangent directions, we work with the
11135 derivative $${\textstyle1\over3}B'(x_0,x_1,x_2,x_3;t)=
11136 B(x_1-x_0,x_2-x_1,x_3-x_2;t)$$ instead of
11137 $B(x_0,x_1,x_2,x_3;t)$ itself. The derived coefficients are also scaled up
11138 in order to achieve better accuracy.
11139
11140 The given path may turn abruptly at a knot, and it might pass the critical
11141 tangent direction at such a time. Therefore we remember the direction |phi|
11142 in which the previous rotated cubic was traveling. (The value of |phi| will be
11143 undefined on the first cubic, i.e., when |n=0|.)
11144
11145 @<Rotate the cubic between |p| and |q|; then...@>=
11146 tt=0;
11147 @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples of the control
11148   points of the rotated derivatives@>;
11149 if ( y1==0 ) if ( x1>=0 ) goto FOUND;
11150 if ( n>0 ) { 
11151   @<Exit to |found| if an eastward direction occurs at knot |p|@>;
11152   if ( p==h ) break;
11153   };
11154 if ( (x3!=0)||(y3!=0) ) phi=mp_n_arg(mp, x3,y3);
11155 @<Exit to |found| if the curve whose derivatives are specified by
11156   |x1,x2,x3,y1,y2,y3| travels eastward at some time~|tt|@>
11157
11158 @ @<Other local variables for |find_direction_time|@>=
11159 scaled x1,x2,x3,y1,y2,y3;  /* multiples of rotated derivatives */
11160 angle theta,phi; /* angles of exit and entry at a knot */
11161 fraction t; /* temp storage */
11162
11163 @ @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples...@>=
11164 x1=right_x(p)-x_coord(p); x2=left_x(q)-right_x(p);
11165 x3=x_coord(q)-left_x(q);
11166 y1=right_y(p)-y_coord(p); y2=left_y(q)-right_y(p);
11167 y3=y_coord(q)-left_y(q);
11168 max=abs(x1);
11169 if ( abs(x2)>max ) max=abs(x2);
11170 if ( abs(x3)>max ) max=abs(x3);
11171 if ( abs(y1)>max ) max=abs(y1);
11172 if ( abs(y2)>max ) max=abs(y2);
11173 if ( abs(y3)>max ) max=abs(y3);
11174 if ( max==0 ) goto FOUND;
11175 while ( max<fraction_half ){ 
11176   max+=max; x1+=x1; x2+=x2; x3+=x3;
11177   y1+=y1; y2+=y2; y3+=y3;
11178 }
11179 t=x1; x1=mp_take_fraction(mp, x1,x)+mp_take_fraction(mp, y1,y);
11180 y1=mp_take_fraction(mp, y1,x)-mp_take_fraction(mp, t,y);
11181 t=x2; x2=mp_take_fraction(mp, x2,x)+mp_take_fraction(mp, y2,y);
11182 y2=mp_take_fraction(mp, y2,x)-mp_take_fraction(mp, t,y);
11183 t=x3; x3=mp_take_fraction(mp, x3,x)+mp_take_fraction(mp, y3,y);
11184 y3=mp_take_fraction(mp, y3,x)-mp_take_fraction(mp, t,y)
11185
11186 @ @<Exit to |found| if an eastward direction occurs at knot |p|@>=
11187 theta=mp_n_arg(mp, x1,y1);
11188 if ( theta>=0 ) if ( phi<=0 ) if ( phi>=theta-one_eighty_deg ) goto FOUND;
11189 if ( theta<=0 ) if ( phi>=0 ) if ( phi<=theta+one_eighty_deg ) goto FOUND
11190
11191 @ In this step we want to use the |crossing_point| routine to find the
11192 roots of the quadratic equation $B(y_1,y_2,y_3;t)=0$.
11193 Several complications arise: If the quadratic equation has a double root,
11194 the curve never crosses zero, and |crossing_point| will find nothing;
11195 this case occurs iff $y_1y_3=y_2^2$ and $y_1y_2<0$. If the quadratic
11196 equation has simple roots, or only one root, we may have to negate it
11197 so that $B(y_1,y_2,y_3;t)$ crosses from positive to negative at its first root.
11198 And finally, we need to do special things if $B(y_1,y_2,y_3;t)$ is
11199 identically zero.
11200
11201 @ @<Exit to |found| if the curve whose derivatives are specified by...@>=
11202 if ( x1<0 ) if ( x2<0 ) if ( x3<0 ) goto DONE;
11203 if ( mp_ab_vs_cd(mp, y1,y3,y2,y2)==0 ) {
11204   @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11205     either |goto found| or |goto done|@>;
11206 }
11207 if ( y1<=0 ) {
11208   if ( y1<0 ) { y1=-y1; y2=-y2; y3=-y3; }
11209   else if ( y2>0 ){ y2=-y2; y3=-y3; };
11210 }
11211 @<Check the places where $B(y_1,y_2,y_3;t)=0$ to see if
11212   $B(x_1,x_2,x_3;t)\ge0$@>;
11213 DONE:
11214
11215 @ The quadratic polynomial $B(y_1,y_2,y_3;t)$ begins |>=0| and has at most
11216 two roots, because we know that it isn't identically zero.
11217
11218 It must be admitted that the |crossing_point| routine is not perfectly accurate;
11219 rounding errors might cause it to find a root when $y_1y_3>y_2^2$, or to
11220 miss the roots when $y_1y_3<y_2^2$. The rotation process is itself
11221 subject to rounding errors. Yet this code optimistically tries to
11222 do the right thing.
11223
11224 @d we_found_it { tt=(t+04000) / 010000; goto FOUND; }
11225
11226 @<Check the places where $B(y_1,y_2,y_3;t)=0$...@>=
11227 t=mp_crossing_point(mp, y1,y2,y3);
11228 if ( t>fraction_one ) goto DONE;
11229 y2=t_of_the_way(y2,y3);
11230 x1=t_of_the_way(x1,x2);
11231 x2=t_of_the_way(x2,x3);
11232 x1=t_of_the_way(x1,x2);
11233 if ( x1>=0 ) we_found_it;
11234 if ( y2>0 ) y2=0;
11235 tt=t; t=mp_crossing_point(mp, 0,-y2,-y3);
11236 if ( t>fraction_one ) goto DONE;
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 ) { 
11240   t=t_of_the_way(tt,fraction_one); we_found_it;
11241 }
11242
11243 @ @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11244     either |goto found| or |goto done|@>=
11245
11246   if ( mp_ab_vs_cd(mp, y1,y2,0,0)<0 ) {
11247     t=mp_make_fraction(mp, y1,y1-y2);
11248     x1=t_of_the_way(x1,x2);
11249     x2=t_of_the_way(x2,x3);
11250     if ( t_of_the_way(x1,x2)>=0 ) we_found_it;
11251   } else if ( y3==0 ) {
11252     if ( y1==0 ) {
11253       @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|@>;
11254     } else if ( x3>=0 ) {
11255       tt=unity; goto FOUND;
11256     }
11257   }
11258   goto DONE;
11259 }
11260
11261 @ At this point we know that the derivative of |y(t)| is identically zero,
11262 and that |x1<0|; but either |x2>=0| or |x3>=0|, so there's some hope of
11263 traveling east.
11264
11265 @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|...@>=
11266
11267   t=mp_crossing_point(mp, -x1,-x2,-x3);
11268   if ( t<=fraction_one ) we_found_it;
11269   if ( mp_ab_vs_cd(mp, x1,x3,x2,x2)<=0 ) { 
11270     t=mp_make_fraction(mp, x1,x1-x2); we_found_it;
11271   }
11272 }
11273
11274 @ The intersection of two cubics can be found by an interesting variant
11275 of the general bisection scheme described in the introduction to
11276 |crossing_point|.\
11277 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)$,
11278 we wish to find a pair of times $(t_1,t_2)$ such that $w(t_1)=z(t_2)$,
11279 if an intersection exists. First we find the smallest rectangle that
11280 encloses the points $\{w_0,w_1,w_2,w_3\}$ and check that it overlaps
11281 the smallest rectangle that encloses
11282 $\{z_0,z_1,z_2,z_3\}$; if not, the cubics certainly don't intersect.
11283 But if the rectangles do overlap, we bisect the intervals, getting
11284 new cubics $w'$ and~$w''$, $z'$~and~$z''$; the intersection routine first
11285 tries for an intersection between $w'$ and~$z'$, then (if unsuccessful)
11286 between $w'$ and~$z''$, then (if still unsuccessful) between $w''$ and~$z'$,
11287 finally (if thrice unsuccessful) between $w''$ and~$z''$. After $l$~successful
11288 levels of bisection we will have determined the intersection times $t_1$
11289 and~$t_2$ to $l$~bits of accuracy.
11290
11291 \def\submin{_{\rm min}} \def\submax{_{\rm max}}
11292 As before, it is better to work with the numbers $W_k=2^l(w_k-w_{k-1})$
11293 and $Z_k=2^l(z_k-z_{k-1})$ rather than the coefficients $w_k$ and $z_k$
11294 themselves. We also need one other quantity, $\Delta=2^l(w_0-z_0)$,
11295 to determine when the enclosing rectangles overlap. Here's why:
11296 The $x$~coordinates of~$w(t)$ are between $u\submin$ and $u\submax$,
11297 and the $x$~coordinates of~$z(t)$ are between $x\submin$ and $x\submax$,
11298 if we write $w_k=(u_k,v_k)$ and $z_k=(x_k,y_k)$ and $u\submin=
11299 \min(u_0,u_1,u_2,u_3)$, etc. These intervals of $x$~coordinates
11300 overlap if and only if $u\submin\L x\submax$ and
11301 $x\submin\L u\submax$. Letting
11302 $$U\submin=\min(0,U_1,U_1+U_2,U_1+U_2+U_3),\;
11303   U\submax=\max(0,U_1,U_1+U_2,U_1+U_2+U_3),$$
11304 we have $u\submin=2^lu_0+U\submin$, etc.; the condition for overlap
11305 reduces to
11306 $$X\submin-U\submax\L 2^l(u_0-x_0)\L X\submax-U\submin.$$
11307 Thus we want to maintain the quantity $2^l(u_0-x_0)$; similarly,
11308 the quantity $2^l(v_0-y_0)$ accounts for the $y$~coordinates. The
11309 coordinates of $\Delta=2^l(w_0-z_0)$ must stay bounded as $l$ increases,
11310 because of the overlap condition; i.e., we know that $X\submin$,
11311 $X\submax$, and their relatives are bounded, hence $X\submax-
11312 U\submin$ and $X\submin-U\submax$ are bounded.
11313
11314 @ Incidentally, if the given cubics intersect more than once, the process
11315 just sketched will not necessarily find the lexicographically smallest pair
11316 $(t_1,t_2)$. The solution actually obtained will be smallest in ``shuffled
11317 order''; i.e., if $t_1=(.a_1a_2\ldots a_{16})_2$ and
11318 $t_2=(.b_1b_2\ldots b_{16})_2$, then we will minimize
11319 $a_1b_1a_2b_2\ldots a_{16}b_{16}$, not
11320 $a_1a_2\ldots a_{16}b_1b_2\ldots b_{16}$.
11321 Shuffled order agrees with lexicographic order if all pairs of solutions
11322 $(t_1,t_2)$ and $(t_1',t_2')$ have the property that $t_1<t_1'$ iff
11323 $t_2<t_2'$; but in general, lexicographic order can be quite different,
11324 and the bisection algorithm would be substantially less efficient if it were
11325 constrained by lexicographic order.
11326
11327 For example, suppose that an overlap has been found for $l=3$ and
11328 $(t_1,t_2)= (.101,.011)$ in binary, but that no overlap is produced by
11329 either of the alternatives $(.1010,.0110)$, $(.1010,.0111)$ at level~4.
11330 Then there is probably an intersection in one of the subintervals
11331 $(.1011,.011x)$; but lexicographic order would require us to explore
11332 $(.1010,.1xxx)$ and $(.1011,.00xx)$ and $(.1011,.010x)$ first. We wouldn't
11333 want to store all of the subdivision data for the second path, so the
11334 subdivisions would have to be regenerated many times. Such inefficiencies
11335 would be associated with every `1' in the binary representation of~$t_1$.
11336
11337 @ The subdivision process introduces rounding errors, hence we need to
11338 make a more liberal test for overlap. It is not hard to show that the
11339 computed values of $U_i$ differ from the truth by at most~$l$, on
11340 level~$l$, hence $U\submin$ and $U\submax$ will be at most $3l$ in error.
11341 If $\beta$ is an upper bound on the absolute error in the computed
11342 components of $\Delta=(|delx|,|dely|)$ on level~$l$, we will replace
11343 the test `$X\submin-U\submax\L|delx|$' by the more liberal test
11344 `$X\submin-U\submax\L|delx|+|tol|$', where $|tol|=6l+\beta$.
11345
11346 More accuracy is obtained if we try the algorithm first with |tol=0|;
11347 the more liberal tolerance is used only if an exact approach fails.
11348 It is convenient to do this double-take by letting `3' in the preceding
11349 paragraph be a parameter, which is first 0, then 3.
11350
11351 @<Glob...@>=
11352 unsigned int tol_step; /* either 0 or 3, usually */
11353
11354 @ We shall use an explicit stack to implement the recursive bisection
11355 method described above. The |bisect_stack| array will contain numerous 5-word
11356 packets like $(U_1,U_2,U_3,U\submin,U\submax)$, as well as 20-word packets
11357 comprising the 5-word packets for $U$, $V$, $X$, and~$Y$.
11358
11359 The following macros define the allocation of stack positions to
11360 the quantities needed for bisection-intersection.
11361
11362 @d stack_1(A) mp->bisect_stack[(A)] /* $U_1$, $V_1$, $X_1$, or $Y_1$ */
11363 @d stack_2(A) mp->bisect_stack[(A)+1] /* $U_2$, $V_2$, $X_2$, or $Y_2$ */
11364 @d stack_3(A) mp->bisect_stack[(A)+2] /* $U_3$, $V_3$, $X_3$, or $Y_3$ */
11365 @d stack_min(A) mp->bisect_stack[(A)+3]
11366   /* $U\submin$, $V\submin$, $X\submin$, or $Y\submin$ */
11367 @d stack_max(A) mp->bisect_stack[(A)+4]
11368   /* $U\submax$, $V\submax$, $X\submax$, or $Y\submax$ */
11369 @d int_packets 20 /* number of words to represent $U_k$, $V_k$, $X_k$, and $Y_k$ */
11370 @#
11371 @d u_packet(A) ((A)-5)
11372 @d v_packet(A) ((A)-10)
11373 @d x_packet(A) ((A)-15)
11374 @d y_packet(A) ((A)-20)
11375 @d l_packets (mp->bisect_ptr-int_packets)
11376 @d r_packets mp->bisect_ptr
11377 @d ul_packet u_packet(l_packets) /* base of $U'_k$ variables */
11378 @d vl_packet v_packet(l_packets) /* base of $V'_k$ variables */
11379 @d xl_packet x_packet(l_packets) /* base of $X'_k$ variables */
11380 @d yl_packet y_packet(l_packets) /* base of $Y'_k$ variables */
11381 @d ur_packet u_packet(r_packets) /* base of $U''_k$ variables */
11382 @d vr_packet v_packet(r_packets) /* base of $V''_k$ variables */
11383 @d xr_packet x_packet(r_packets) /* base of $X''_k$ variables */
11384 @d yr_packet y_packet(r_packets) /* base of $Y''_k$ variables */
11385 @#
11386 @d u1l stack_1(ul_packet) /* $U'_1$ */
11387 @d u2l stack_2(ul_packet) /* $U'_2$ */
11388 @d u3l stack_3(ul_packet) /* $U'_3$ */
11389 @d v1l stack_1(vl_packet) /* $V'_1$ */
11390 @d v2l stack_2(vl_packet) /* $V'_2$ */
11391 @d v3l stack_3(vl_packet) /* $V'_3$ */
11392 @d x1l stack_1(xl_packet) /* $X'_1$ */
11393 @d x2l stack_2(xl_packet) /* $X'_2$ */
11394 @d x3l stack_3(xl_packet) /* $X'_3$ */
11395 @d y1l stack_1(yl_packet) /* $Y'_1$ */
11396 @d y2l stack_2(yl_packet) /* $Y'_2$ */
11397 @d y3l stack_3(yl_packet) /* $Y'_3$ */
11398 @d u1r stack_1(ur_packet) /* $U''_1$ */
11399 @d u2r stack_2(ur_packet) /* $U''_2$ */
11400 @d u3r stack_3(ur_packet) /* $U''_3$ */
11401 @d v1r stack_1(vr_packet) /* $V''_1$ */
11402 @d v2r stack_2(vr_packet) /* $V''_2$ */
11403 @d v3r stack_3(vr_packet) /* $V''_3$ */
11404 @d x1r stack_1(xr_packet) /* $X''_1$ */
11405 @d x2r stack_2(xr_packet) /* $X''_2$ */
11406 @d x3r stack_3(xr_packet) /* $X''_3$ */
11407 @d y1r stack_1(yr_packet) /* $Y''_1$ */
11408 @d y2r stack_2(yr_packet) /* $Y''_2$ */
11409 @d y3r stack_3(yr_packet) /* $Y''_3$ */
11410 @#
11411 @d stack_dx mp->bisect_stack[mp->bisect_ptr] /* stacked value of |delx| */
11412 @d stack_dy mp->bisect_stack[mp->bisect_ptr+1] /* stacked value of |dely| */
11413 @d stack_tol mp->bisect_stack[mp->bisect_ptr+2] /* stacked value of |tol| */
11414 @d stack_uv mp->bisect_stack[mp->bisect_ptr+3] /* stacked value of |uv| */
11415 @d stack_xy mp->bisect_stack[mp->bisect_ptr+4] /* stacked value of |xy| */
11416 @d int_increment (int_packets+int_packets+5) /* number of stack words per level */
11417
11418 @<Glob...@>=
11419 integer *bisect_stack;
11420 unsigned int bisect_ptr;
11421
11422 @ @<Allocate or initialize ...@>=
11423 mp->bisect_stack = xmalloc((bistack_size+1),sizeof(integer));
11424
11425 @ @<Dealloc variables@>=
11426 xfree(mp->bisect_stack);
11427
11428 @ @<Check the ``constant''...@>=
11429 if ( int_packets+17*int_increment>bistack_size ) mp->bad=19;
11430
11431 @ Computation of the min and max is a tedious but fairly fast sequence of
11432 instructions; exactly four comparisons are made in each branch.
11433
11434 @d set_min_max(A) 
11435   if ( stack_1((A))<0 ) {
11436     if ( stack_3((A))>=0 ) {
11437       if ( stack_2((A))<0 ) stack_min((A))=stack_1((A))+stack_2((A));
11438       else stack_min((A))=stack_1((A));
11439       stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11440       if ( stack_max((A))<0 ) stack_max((A))=0;
11441     } else { 
11442       stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11443       if ( stack_min((A))>stack_1((A)) ) stack_min((A))=stack_1((A));
11444       stack_max((A))=stack_1((A))+stack_2((A));
11445       if ( stack_max((A))<0 ) stack_max((A))=0;
11446     }
11447   } else if ( stack_3((A))<=0 ) {
11448     if ( stack_2((A))>0 ) stack_max((A))=stack_1((A))+stack_2((A));
11449     else stack_max((A))=stack_1((A));
11450     stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11451     if ( stack_min((A))>0 ) stack_min((A))=0;
11452   } else  { 
11453     stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11454     if ( stack_max((A))<stack_1((A)) ) stack_max((A))=stack_1((A));
11455     stack_min((A))=stack_1((A))+stack_2((A));
11456     if ( stack_min((A))>0 ) stack_min((A))=0;
11457   }
11458
11459 @ It's convenient to keep the current values of $l$, $t_1$, and $t_2$ in
11460 the integer form $2^l+2^lt_1$ and $2^l+2^lt_2$. The |cubic_intersection|
11461 routine uses global variables |cur_t| and |cur_tt| for this purpose;
11462 after successful completion, |cur_t| and |cur_tt| will contain |unity|
11463 plus the |scaled| values of $t_1$ and~$t_2$.
11464
11465 The values of |cur_t| and |cur_tt| will be set to zero if |cubic_intersection|
11466 finds no intersection. The routine gives up and gives an approximate answer
11467 if it has backtracked
11468 more than 5000 times (otherwise there are cases where several minutes
11469 of fruitless computation would be possible).
11470
11471 @d max_patience 5000
11472
11473 @<Glob...@>=
11474 integer cur_t;integer cur_tt; /* controls and results of |cubic_intersection| */
11475 integer time_to_go; /* this many backtracks before giving up */
11476 integer max_t; /* maximum of $2^{l+1}$ so far achieved */
11477
11478 @ The given cubics $B(w_0,w_1,w_2,w_3;t)$ and
11479 $B(z_0,z_1,z_2,z_3;t)$ are specified in adjacent knot nodes |(p,link(p))|
11480 and |(pp,link(pp))|, respectively.
11481
11482 @c void mp_cubic_intersection (MP mp,pointer p, pointer pp) {
11483   pointer q,qq; /* |link(p)|, |link(pp)| */
11484   mp->time_to_go=max_patience; mp->max_t=2;
11485   @<Initialize for intersections at level zero@>;
11486 CONTINUE:
11487   while (1) { 
11488     if ( mp->delx-mp->tol<=stack_max(x_packet(mp->xy))-stack_min(u_packet(mp->uv)))
11489     if ( mp->delx+mp->tol>=stack_min(x_packet(mp->xy))-stack_max(u_packet(mp->uv)))
11490     if ( mp->dely-mp->tol<=stack_max(y_packet(mp->xy))-stack_min(v_packet(mp->uv)))
11491     if ( mp->dely+mp->tol>=stack_min(y_packet(mp->xy))-stack_max(v_packet(mp->uv))) 
11492     { 
11493       if ( mp->cur_t>=mp->max_t ){ 
11494         if ( mp->max_t==two ) { /* we've done 17 bisections */ 
11495            mp->cur_t=halfp(mp->cur_t+1); mp->cur_tt=halfp(mp->cur_tt+1); return;
11496         }
11497         mp->max_t+=mp->max_t; mp->appr_t=mp->cur_t; mp->appr_tt=mp->cur_tt;
11498       }
11499       @<Subdivide for a new level of intersection@>;
11500       goto CONTINUE;
11501     }
11502     if ( mp->time_to_go>0 ) {
11503       decr(mp->time_to_go);
11504     } else { 
11505       while ( mp->appr_t<unity ) { 
11506         mp->appr_t+=mp->appr_t; mp->appr_tt+=mp->appr_tt;
11507       }
11508       mp->cur_t=mp->appr_t; mp->cur_tt=mp->appr_tt; return;
11509     }
11510     @<Advance to the next pair |(cur_t,cur_tt)|@>;
11511   }
11512 }
11513
11514 @ The following variables are global, although they are used only by
11515 |cubic_intersection|, because it is necessary on some machines to
11516 split |cubic_intersection| up into two procedures.
11517
11518 @<Glob...@>=
11519 integer delx;integer dely; /* the components of $\Delta=2^l(w_0-z_0)$ */
11520 integer tol; /* bound on the uncertainly in the overlap test */
11521 unsigned int uv;
11522 unsigned int xy; /* pointers to the current packets of interest */
11523 integer three_l; /* |tol_step| times the bisection level */
11524 integer appr_t;integer appr_tt; /* best approximations known to the answers */
11525
11526 @ We shall assume that the coordinates are sufficiently non-extreme that
11527 integer overflow will not occur.
11528
11529 @<Initialize for intersections at level zero@>=
11530 q=link(p); qq=link(pp); mp->bisect_ptr=int_packets;
11531 u1r=right_x(p)-x_coord(p); u2r=left_x(q)-right_x(p);
11532 u3r=x_coord(q)-left_x(q); set_min_max(ur_packet);
11533 v1r=right_y(p)-y_coord(p); v2r=left_y(q)-right_y(p);
11534 v3r=y_coord(q)-left_y(q); set_min_max(vr_packet);
11535 x1r=right_x(pp)-x_coord(pp); x2r=left_x(qq)-right_x(pp);
11536 x3r=x_coord(qq)-left_x(qq); set_min_max(xr_packet);
11537 y1r=right_y(pp)-y_coord(pp); y2r=left_y(qq)-right_y(pp);
11538 y3r=y_coord(qq)-left_y(qq); set_min_max(yr_packet);
11539 mp->delx=x_coord(p)-x_coord(pp); mp->dely=y_coord(p)-y_coord(pp);
11540 mp->tol=0; mp->uv=r_packets; mp->xy=r_packets; 
11541 mp->three_l=0; mp->cur_t=1; mp->cur_tt=1
11542
11543 @ @<Subdivide for a new level of intersection@>=
11544 stack_dx=mp->delx; stack_dy=mp->dely; stack_tol=mp->tol; 
11545 stack_uv=mp->uv; stack_xy=mp->xy;
11546 mp->bisect_ptr=mp->bisect_ptr+int_increment;
11547 mp->cur_t+=mp->cur_t; mp->cur_tt+=mp->cur_tt;
11548 u1l=stack_1(u_packet(mp->uv)); u3r=stack_3(u_packet(mp->uv));
11549 u2l=half(u1l+stack_2(u_packet(mp->uv)));
11550 u2r=half(u3r+stack_2(u_packet(mp->uv)));
11551 u3l=half(u2l+u2r); u1r=u3l;
11552 set_min_max(ul_packet); set_min_max(ur_packet);
11553 v1l=stack_1(v_packet(mp->uv)); v3r=stack_3(v_packet(mp->uv));
11554 v2l=half(v1l+stack_2(v_packet(mp->uv)));
11555 v2r=half(v3r+stack_2(v_packet(mp->uv)));
11556 v3l=half(v2l+v2r); v1r=v3l;
11557 set_min_max(vl_packet); set_min_max(vr_packet);
11558 x1l=stack_1(x_packet(mp->xy)); x3r=stack_3(x_packet(mp->xy));
11559 x2l=half(x1l+stack_2(x_packet(mp->xy)));
11560 x2r=half(x3r+stack_2(x_packet(mp->xy)));
11561 x3l=half(x2l+x2r); x1r=x3l;
11562 set_min_max(xl_packet); set_min_max(xr_packet);
11563 y1l=stack_1(y_packet(mp->xy)); y3r=stack_3(y_packet(mp->xy));
11564 y2l=half(y1l+stack_2(y_packet(mp->xy)));
11565 y2r=half(y3r+stack_2(y_packet(mp->xy)));
11566 y3l=half(y2l+y2r); y1r=y3l;
11567 set_min_max(yl_packet); set_min_max(yr_packet);
11568 mp->uv=l_packets; mp->xy=l_packets;
11569 mp->delx+=mp->delx; mp->dely+=mp->dely;
11570 mp->tol=mp->tol-mp->three_l+mp->tol_step; 
11571 mp->tol+=mp->tol; mp->three_l=mp->three_l+mp->tol_step
11572
11573 @ @<Advance to the next pair |(cur_t,cur_tt)|@>=
11574 NOT_FOUND: 
11575 if ( odd(mp->cur_tt) ) {
11576   if ( odd(mp->cur_t) ) {
11577      @<Descend to the previous level and |goto not_found|@>;
11578   } else { 
11579     incr(mp->cur_t);
11580     mp->delx=mp->delx+stack_1(u_packet(mp->uv))+stack_2(u_packet(mp->uv))
11581       +stack_3(u_packet(mp->uv));
11582     mp->dely=mp->dely+stack_1(v_packet(mp->uv))+stack_2(v_packet(mp->uv))
11583       +stack_3(v_packet(mp->uv));
11584     mp->uv=mp->uv+int_packets; /* switch from |l_packet| to |r_packet| */
11585     decr(mp->cur_tt); mp->xy=mp->xy-int_packets; 
11586          /* switch from |r_packet| to |l_packet| */
11587     mp->delx=mp->delx+stack_1(x_packet(mp->xy))+stack_2(x_packet(mp->xy))
11588       +stack_3(x_packet(mp->xy));
11589     mp->dely=mp->dely+stack_1(y_packet(mp->xy))+stack_2(y_packet(mp->xy))
11590       +stack_3(y_packet(mp->xy));
11591   }
11592 } else { 
11593   incr(mp->cur_tt); mp->tol=mp->tol+mp->three_l;
11594   mp->delx=mp->delx-stack_1(x_packet(mp->xy))-stack_2(x_packet(mp->xy))
11595     -stack_3(x_packet(mp->xy));
11596   mp->dely=mp->dely-stack_1(y_packet(mp->xy))-stack_2(y_packet(mp->xy))
11597     -stack_3(y_packet(mp->xy));
11598   mp->xy=mp->xy+int_packets; /* switch from |l_packet| to |r_packet| */
11599 }
11600
11601 @ @<Descend to the previous level...@>=
11602
11603   mp->cur_t=halfp(mp->cur_t); mp->cur_tt=halfp(mp->cur_tt);
11604   if ( mp->cur_t==0 ) return;
11605   mp->bisect_ptr=mp->bisect_ptr-int_increment; 
11606   mp->three_l=mp->three_l-mp->tol_step;
11607   mp->delx=stack_dx; mp->dely=stack_dy; mp->tol=stack_tol; 
11608   mp->uv=stack_uv; mp->xy=stack_xy;
11609   goto NOT_FOUND;
11610 }
11611
11612 @ The |path_intersection| procedure is much simpler.
11613 It invokes |cubic_intersection| in lexicographic order until finding a
11614 pair of cubics that intersect. The final intersection times are placed in
11615 |cur_t| and~|cur_tt|.
11616
11617 @c void mp_path_intersection (MP mp,pointer h, pointer hh) {
11618   pointer p,pp; /* link registers that traverse the given paths */
11619   integer n,nn; /* integer parts of intersection times, minus |unity| */
11620   @<Change one-point paths into dead cycles@>;
11621   mp->tol_step=0;
11622   do {  
11623     n=-unity; p=h;
11624     do {  
11625       if ( right_type(p)!=endpoint ) { 
11626         nn=-unity; pp=hh;
11627         do {  
11628           if ( right_type(pp)!=endpoint )  { 
11629             mp_cubic_intersection(mp, p,pp);
11630             if ( mp->cur_t>0 ) { 
11631               mp->cur_t=mp->cur_t+n; mp->cur_tt=mp->cur_tt+nn; 
11632               return;
11633             }
11634           }
11635           nn=nn+unity; pp=link(pp);
11636         } while (pp!=hh);
11637       }
11638       n=n+unity; p=link(p);
11639     } while (p!=h);
11640     mp->tol_step=mp->tol_step+3;
11641   } while (mp->tol_step<=3);
11642   mp->cur_t=-unity; mp->cur_tt=-unity;
11643 }
11644
11645 @ @<Change one-point paths...@>=
11646 if ( right_type(h)==endpoint ) {
11647   right_x(h)=x_coord(h); left_x(h)=x_coord(h);
11648   right_y(h)=y_coord(h); left_y(h)=y_coord(h); right_type(h)=explicit;
11649 }
11650 if ( right_type(hh)==endpoint ) {
11651   right_x(hh)=x_coord(hh); left_x(hh)=x_coord(hh);
11652   right_y(hh)=y_coord(hh); left_y(hh)=y_coord(hh); right_type(hh)=explicit;
11653 }
11654
11655 @* \[24] Dynamic linear equations.
11656 \MP\ users define variables implicitly by stating equations that should be
11657 satisfied; the computer is supposed to be smart enough to solve those equations.
11658 And indeed, the computer tries valiantly to do so, by distinguishing five
11659 different types of numeric values:
11660
11661 \smallskip\hang
11662 |type(p)=mp_known| is the nice case, when |value(p)| is the |scaled| value
11663 of the variable whose address is~|p|.
11664
11665 \smallskip\hang
11666 |type(p)=mp_dependent| means that |value(p)| is not present, but |dep_list(p)|
11667 points to a {\sl dependency list\/} that expresses the value of variable~|p|
11668 as a |scaled| number plus a sum of independent variables with |fraction|
11669 coefficients.
11670
11671 \smallskip\hang
11672 |type(p)=mp_independent| means that |value(p)=64s+m|, where |s>0| is a ``serial
11673 number'' reflecting the time this variable was first used in an equation;
11674 also |0<=m<64|, and each dependent variable
11675 that refers to this one is actually referring to the future value of
11676 this variable times~$2^m$. (Usually |m=0|, but higher degrees of
11677 scaling are sometimes needed to keep the coefficients in dependency lists
11678 from getting too large. The value of~|m| will always be even.)
11679
11680 \smallskip\hang
11681 |type(p)=mp_numeric_type| means that variable |p| hasn't appeared in an
11682 equation before, but it has been explicitly declared to be numeric.
11683
11684 \smallskip\hang
11685 |type(p)=undefined| means that variable |p| hasn't appeared before.
11686
11687 \smallskip\noindent
11688 We have actually discussed these five types in the reverse order of their
11689 history during a computation: Once |known|, a variable never again
11690 becomes |dependent|; once |dependent|, it almost never again becomes
11691 |mp_independent|; once |mp_independent|, it never again becomes |mp_numeric_type|;
11692 and once |mp_numeric_type|, it never again becomes |undefined| (except
11693 of course when the user specifically decides to scrap the old value
11694 and start again). A backward step may, however, take place: Sometimes
11695 a |dependent| variable becomes |mp_independent| again, when one of the
11696 independent variables it depends on is reverting to |undefined|.
11697
11698
11699 The next patch detects overflow of independent-variable serial
11700 numbers. Diagnosed and patched by Thorsten Dahlheimer.
11701
11702 @d s_scale 64 /* the serial numbers are multiplied by this factor */
11703 @d max_indep_vars 0177777777 /* $2^{25}-1$ */
11704 @d max_serial_no 017777777700 /* |max_indep_vars*s_scale| */
11705 @d new_indep(A)  /* create a new independent variable */
11706   { if ( mp->serial_no==max_serial_no )
11707     mp_fatal_error(mp, "variable instance identifiers exhausted");
11708   type((A))=mp_independent; mp->serial_no=mp->serial_no+s_scale;
11709   value((A))=mp->serial_no;
11710   }
11711
11712 @<Glob...@>=
11713 integer serial_no; /* the most recent serial number, times |s_scale| */
11714
11715 @ @<Make variable |q+s| newly independent@>=new_indep(q+s)
11716
11717 @ But how are dependency lists represented? It's simple: The linear combination
11718 $\alpha_1v_1+\cdots+\alpha_kv_k+\beta$ appears in |k+1| value nodes. If
11719 |q=dep_list(p)| points to this list, and if |k>0|, then |value(q)=
11720 @t$\alpha_1$@>| (which is a |fraction|); |info(q)| points to the location
11721 of $\alpha_1$; and |link(p)| points to the dependency list
11722 $\alpha_2v_2+\cdots+\alpha_kv_k+\beta$. On the other hand if |k=0|,
11723 then |value(q)=@t$\beta$@>| (which is |scaled|) and |info(q)=null|.
11724 The independent variables $v_1$, \dots,~$v_k$ have been sorted so that
11725 they appear in decreasing order of their |value| fields (i.e., of
11726 their serial numbers). \ (It is convenient to use decreasing order,
11727 since |value(null)=0|. If the independent variables were not sorted by
11728 serial number but by some other criterion, such as their location in |mem|,
11729 the equation-solving mechanism would be too system-dependent, because
11730 the ordering can affect the computed results.)
11731
11732 The |link| field in the node that contains the constant term $\beta$ is
11733 called the {\sl final link\/} of the dependency list. \MP\ maintains
11734 a doubly-linked master list of all dependency lists, in terms of a permanently
11735 allocated node
11736 in |mem| called |dep_head|. If there are no dependencies, we have
11737 |link(dep_head)=dep_head| and |prev_dep(dep_head)=dep_head|;
11738 otherwise |link(dep_head)| points to the first dependent variable, say~|p|,
11739 and |prev_dep(p)=dep_head|. We have |type(p)=mp_dependent|, and |dep_list(p)|
11740 points to its dependency list. If the final link of that dependency list
11741 occurs in location~|q|, then |link(q)| points to the next dependent
11742 variable (say~|r|); and we have |prev_dep(r)=q|, etc.
11743
11744 @d dep_list(A) link(value_loc((A)))
11745   /* half of the |value| field in a |dependent| variable */
11746 @d prev_dep(A) info(value_loc((A)))
11747   /* the other half; makes a doubly linked list */
11748 @d dep_node_size 2 /* the number of words per dependency node */
11749
11750 @<Initialize table entries...@>= mp->serial_no=0;
11751 link(dep_head)=dep_head; prev_dep(dep_head)=dep_head;
11752 info(dep_head)=null; dep_list(dep_head)=null;
11753
11754 @ Actually the description above contains a little white lie. There's
11755 another kind of variable called |mp_proto_dependent|, which is
11756 just like a |dependent| one except that the $\alpha$ coefficients
11757 in its dependency list are |scaled| instead of being fractions.
11758 Proto-dependency lists are mixed with dependency lists in the
11759 nodes reachable from |dep_head|.
11760
11761 @ Here is a procedure that prints a dependency list in symbolic form.
11762 The second parameter should be either |dependent| or |mp_proto_dependent|,
11763 to indicate the scaling of the coefficients.
11764
11765 @<Declare subroutines for printing expressions@>=
11766 void mp_print_dependency (MP mp,pointer p, small_number t) {
11767   integer v; /* a coefficient */
11768   pointer pp,q; /* for list manipulation */
11769   pp=p;
11770   while (1) { 
11771     v=abs(value(p)); q=info(p);
11772     if ( q==null ) { /* the constant term */
11773       if ( (v!=0)||(p==pp) ) {
11774          if ( value(p)>0 ) if ( p!=pp ) mp_print_char(mp, '+');
11775          mp_print_scaled(mp, value(p));
11776       }
11777       return;
11778     }
11779     @<Print the coefficient, unless it's $\pm1.0$@>;
11780     if ( type(q)!=mp_independent ) mp_confusion(mp, "dep");
11781 @:this can't happen dep}{\quad dep@>
11782     mp_print_variable_name(mp, q); v=value(q) % s_scale;
11783     while ( v>0 ) { mp_print(mp, "*4"); v=v-2; }
11784     p=link(p);
11785   }
11786 }
11787
11788 @ @<Print the coefficient, unless it's $\pm1.0$@>=
11789 if ( value(p)<0 ) mp_print_char(mp, '-');
11790 else if ( p!=pp ) mp_print_char(mp, '+');
11791 if ( t==mp_dependent ) v=mp_round_fraction(mp, v);
11792 if ( v!=unity ) mp_print_scaled(mp, v)
11793
11794 @ The maximum absolute value of a coefficient in a given dependency list
11795 is returned by the following simple function.
11796
11797 @c fraction mp_max_coef (MP mp,pointer p) {
11798   fraction x; /* the maximum so far */
11799   x=0;
11800   while ( info(p)!=null ) {
11801     if ( abs(value(p))>x ) x=abs(value(p));
11802     p=link(p);
11803   }
11804   return x;
11805 }
11806
11807 @ One of the main operations needed on dependency lists is to add a multiple
11808 of one list to the other; we call this |p_plus_fq|, where |p| and~|q| point
11809 to dependency lists and |f| is a fraction.
11810
11811 If the coefficient of any independent variable becomes |coef_bound| or
11812 more, in absolute value, this procedure changes the type of that variable
11813 to `|independent_needing_fix|', and sets the global variable |fix_needed|
11814 to~|true|. The value of $|coef_bound|=\mu$ is chosen so that
11815 $\mu^2+\mu<8$; this means that the numbers we deal with won't
11816 get too large. (Instead of the ``optimum'' $\mu=(\sqrt{33}-1)/2\approx
11817 2.3723$, the safer value 7/3 is taken as the threshold.)
11818
11819 The changes mentioned in the preceding paragraph are actually done only if
11820 the global variable |watch_coefs| is |true|. But it usually is; in fact,
11821 it is |false| only when \MP\ is making a dependency list that will soon
11822 be equated to zero.
11823
11824 Several procedures that act on dependency lists, including |p_plus_fq|,
11825 set the global variable |dep_final| to the final (constant term) node of
11826 the dependency list that they produce.
11827
11828 @d coef_bound 04525252525 /* |fraction| approximation to 7/3 */
11829 @d independent_needing_fix 0
11830
11831 @<Glob...@>=
11832 boolean fix_needed; /* does at least one |independent| variable need scaling? */
11833 boolean watch_coefs; /* should we scale coefficients that exceed |coef_bound|? */
11834 pointer dep_final; /* location of the constant term and final link */
11835
11836 @ @<Set init...@>=
11837 mp->fix_needed=false; mp->watch_coefs=true;
11838
11839 @ The |p_plus_fq| procedure has a fourth parameter, |t|, that should be
11840 set to |mp_proto_dependent| if |p| is a proto-dependency list. In this
11841 case |f| will be |scaled|, not a |fraction|. Similarly, the fifth parameter~|tt|
11842 should be |mp_proto_dependent| if |q| is a proto-dependency list.
11843
11844 List |q| is unchanged by the operation; but list |p| is totally destroyed.
11845
11846 The final link of the dependency list or proto-dependency list returned
11847 by |p_plus_fq| is the same as the original final link of~|p|. Indeed, the
11848 constant term of the result will be located in the same |mem| location
11849 as the original constant term of~|p|.
11850
11851 Coefficients of the result are assumed to be zero if they are less than
11852 a certain threshold. This compensates for inevitable rounding errors,
11853 and tends to make more variables `|known|'. The threshold is approximately
11854 $10^{-5}$ in the case of normal dependency lists, $10^{-4}$ for
11855 proto-dependencies.
11856
11857 @d fraction_threshold 2685 /* a |fraction| coefficient less than this is zeroed */
11858 @d half_fraction_threshold 1342 /* half of |fraction_threshold| */
11859 @d scaled_threshold 8 /* a |scaled| coefficient less than this is zeroed */
11860 @d half_scaled_threshold 4 /* half of |scaled_threshold| */
11861
11862 @<Declare basic dependency-list subroutines@>=
11863 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
11864                       pointer q, small_number t, small_number tt) ;
11865
11866 @ @c
11867 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
11868                       pointer q, small_number t, small_number tt) {
11869   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
11870   pointer r,s; /* for list manipulation */
11871   integer mp_threshold; /* defines a neighborhood of zero */
11872   integer v; /* temporary register */
11873   if ( t==mp_dependent ) mp_threshold=fraction_threshold;
11874   else mp_threshold=scaled_threshold;
11875   r=temp_head; pp=info(p); qq=info(q);
11876   while (1) {
11877     if ( pp==qq ) {
11878       if ( pp==null ) {
11879        break;
11880       } else {
11881         @<Contribute a term from |p|, plus |f| times the
11882           corresponding term from |q|@>
11883       }
11884     } else if ( value(pp)<value(qq) ) {
11885       @<Contribute a term from |q|, multiplied by~|f|@>
11886     } else { 
11887      link(r)=p; r=p; p=link(p); pp=info(p);
11888     }
11889   }
11890   if ( t==mp_dependent )
11891     value(p)=mp_slow_add(mp, value(p),mp_take_fraction(mp, value(q),f));
11892   else  
11893     value(p)=mp_slow_add(mp, value(p),mp_take_scaled(mp, value(q),f));
11894   link(r)=p; mp->dep_final=p; 
11895   return link(temp_head);
11896 }
11897
11898 @ @<Contribute a term from |p|, plus |f|...@>=
11899
11900   if ( tt==mp_dependent ) v=value(p)+mp_take_fraction(mp, f,value(q));
11901   else v=value(p)+mp_take_scaled(mp, f,value(q));
11902   value(p)=v; s=p; p=link(p);
11903   if ( abs(v)<mp_threshold ) {
11904     mp_free_node(mp, s,dep_node_size);
11905   } else {
11906     if ( (abs(v)>=coef_bound)  && mp->watch_coefs ) { 
11907       type(qq)=independent_needing_fix; mp->fix_needed=true;
11908     }
11909     link(r)=s; r=s;
11910   };
11911   pp=info(p); q=link(q); qq=info(q);
11912 }
11913
11914 @ @<Contribute a term from |q|, multiplied by~|f|@>=
11915
11916   if ( tt==mp_dependent ) v=mp_take_fraction(mp, f,value(q));
11917   else v=mp_take_scaled(mp, f,value(q));
11918   if ( abs(v)>halfp(mp_threshold) ) { 
11919     s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=v;
11920     if ( (abs(v)>=coef_bound) && mp->watch_coefs ) { 
11921       type(qq)=independent_needing_fix; mp->fix_needed=true;
11922     }
11923     link(r)=s; r=s;
11924   }
11925   q=link(q); qq=info(q);
11926 }
11927
11928 @ It is convenient to have another subroutine for the special case
11929 of |p_plus_fq| when |f=1.0|. In this routine lists |p| and |q| are
11930 both of the same type~|t| (either |dependent| or |mp_proto_dependent|).
11931
11932 @c pointer mp_p_plus_q (MP mp,pointer p, pointer q, small_number t) {
11933   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
11934   pointer r,s; /* for list manipulation */
11935   integer mp_threshold; /* defines a neighborhood of zero */
11936   integer v; /* temporary register */
11937   if ( t==mp_dependent ) mp_threshold=fraction_threshold;
11938   else mp_threshold=scaled_threshold;
11939   r=temp_head; pp=info(p); qq=info(q);
11940   while (1) {
11941     if ( pp==qq ) {
11942       if ( pp==null ) {
11943         break;
11944       } else {
11945         @<Contribute a term from |p|, plus the
11946           corresponding term from |q|@>
11947       }
11948     } else if ( value(pp)<value(qq) ) {
11949       s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=value(q);
11950       q=link(q); qq=info(q); link(r)=s; r=s;
11951     } else { 
11952       link(r)=p; r=p; p=link(p); pp=info(p);
11953     }
11954   }
11955   value(p)=mp_slow_add(mp, value(p),value(q));
11956   link(r)=p; mp->dep_final=p; 
11957   return link(temp_head);
11958 }
11959
11960 @ @<Contribute a term from |p|, plus the...@>=
11961
11962   v=value(p)+value(q);
11963   value(p)=v; s=p; p=link(p); pp=info(p);
11964   if ( abs(v)<mp_threshold ) {
11965     mp_free_node(mp, s,dep_node_size);
11966   } else { 
11967     if ( (abs(v)>=coef_bound ) && mp->watch_coefs ) {
11968       type(qq)=independent_needing_fix; mp->fix_needed=true;
11969     }
11970     link(r)=s; r=s;
11971   }
11972   q=link(q); qq=info(q);
11973 }
11974
11975 @ A somewhat simpler routine will multiply a dependency list
11976 by a given constant~|v|. The constant is either a |fraction| less than
11977 |fraction_one|, or it is |scaled|. In the latter case we might be forced to
11978 convert a dependency list to a proto-dependency list.
11979 Parameters |t0| and |t1| are the list types before and after;
11980 they should agree unless |t0=mp_dependent| and |t1=mp_proto_dependent|
11981 and |v_is_scaled=true|.
11982
11983 @c pointer mp_p_times_v (MP mp,pointer p, integer v, small_number t0,
11984                          small_number t1, boolean v_is_scaled) {
11985   pointer r,s; /* for list manipulation */
11986   integer w; /* tentative coefficient */
11987   integer mp_threshold;
11988   boolean scaling_down;
11989   if ( t0!=t1 ) scaling_down=true; else scaling_down=! v_is_scaled;
11990   if ( t1==mp_dependent ) mp_threshold=half_fraction_threshold;
11991   else mp_threshold=half_scaled_threshold;
11992   r=temp_head;
11993   while ( info(p)!=null ) {    
11994     if ( scaling_down ) w=mp_take_fraction(mp, v,value(p));
11995     else w=mp_take_scaled(mp, v,value(p));
11996     if ( abs(w)<=mp_threshold ) { 
11997       s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
11998     } else {
11999       if ( abs(w)>=coef_bound ) { 
12000         mp->fix_needed=true; type(info(p))=independent_needing_fix;
12001       }
12002       link(r)=p; r=p; value(p)=w; p=link(p);
12003     }
12004   }
12005   link(r)=p;
12006   if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
12007   else value(p)=mp_take_fraction(mp, value(p),v);
12008   return link(temp_head);
12009 };
12010
12011 @ Similarly, we sometimes need to divide a dependency list
12012 by a given |scaled| constant.
12013
12014 @<Declare basic dependency-list subroutines@>=
12015 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number 
12016   t0, small_number t1) ;
12017
12018 @ @c
12019 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number 
12020   t0, small_number t1) {
12021   pointer r,s; /* for list manipulation */
12022   integer w; /* tentative coefficient */
12023   integer mp_threshold;
12024   boolean scaling_down;
12025   if ( t0!=t1 ) scaling_down=true; else scaling_down=false;
12026   if ( t1==mp_dependent ) mp_threshold=half_fraction_threshold;
12027   else mp_threshold=half_scaled_threshold;
12028   r=temp_head;
12029   while ( info( p)!=null ) {
12030     if ( scaling_down ) {
12031       if ( abs(v)<02000000 ) w=mp_make_scaled(mp, value(p),v*010000);
12032       else w=mp_make_scaled(mp, mp_round_fraction(mp, value(p)),v);
12033     } else {
12034       w=mp_make_scaled(mp, value(p),v);
12035     }
12036     if ( abs(w)<=mp_threshold ) {
12037       s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
12038     } else { 
12039       if ( abs(w)>=coef_bound ) {
12040          mp->fix_needed=true; type(info(p))=independent_needing_fix;
12041       }
12042       link(r)=p; r=p; value(p)=w; p=link(p);
12043     }
12044   }
12045   link(r)=p; value(p)=mp_make_scaled(mp, value(p),v);
12046   return link(temp_head);
12047 };
12048
12049 @ Here's another utility routine for dependency lists. When an independent
12050 variable becomes dependent, we want to remove it from all existing
12051 dependencies. The |p_with_x_becoming_q| function computes the
12052 dependency list of~|p| after variable~|x| has been replaced by~|q|.
12053
12054 This procedure has basically the same calling conventions as |p_plus_fq|:
12055 List~|q| is unchanged; list~|p| is destroyed; the constant node and the
12056 final link are inherited from~|p|; and the fourth parameter tells whether
12057 or not |p| is |mp_proto_dependent|. However, the global variable |dep_final|
12058 is not altered if |x| does not occur in list~|p|.
12059
12060 @c pointer mp_p_with_x_becoming_q (MP mp,pointer p,
12061            pointer x, pointer q, small_number t) {
12062   pointer r,s; /* for list manipulation */
12063   integer v; /* coefficient of |x| */
12064   integer sx; /* serial number of |x| */
12065   s=p; r=temp_head; sx=value(x);
12066   while ( value(info(s))>sx ) { r=s; s=link(s); };
12067   if ( info(s)!=x ) { 
12068     return p;
12069   } else { 
12070     link(temp_head)=p; link(r)=link(s); v=value(s);
12071     mp_free_node(mp, s,dep_node_size);
12072     return mp_p_plus_fq(mp, link(temp_head),v,q,t,mp_dependent);
12073   }
12074 }
12075
12076 @ Here's a simple procedure that reports an error when a variable
12077 has just received a known value that's out of the required range.
12078
12079 @<Declare basic dependency-list subroutines@>=
12080 void mp_val_too_big (MP mp,scaled x) ;
12081
12082 @ @c void mp_val_too_big (MP mp,scaled x) { 
12083   if ( mp->internal[warning_check]>0 ) { 
12084     print_err("Value is too large ("); mp_print_scaled(mp, x); mp_print_char(mp, ')');
12085 @.Value is too large@>
12086     help4("The equation I just processed has given some variable")
12087       ("a value of 4096 or more. Continue and I'll try to cope")
12088       ("with that big value; but it might be dangerous.")
12089       ("(Set warningcheck:=0 to suppress this message.)");
12090     mp_error(mp);
12091   }
12092 }
12093
12094 @ When a dependent variable becomes known, the following routine
12095 removes its dependency list. Here |p| points to the variable, and
12096 |q| points to the dependency list (which is one node long).
12097
12098 @<Declare basic dependency-list subroutines@>=
12099 void mp_make_known (MP mp,pointer p, pointer q) ;
12100
12101 @ @c void mp_make_known (MP mp,pointer p, pointer q) {
12102   int t; /* the previous type */
12103   prev_dep(link(q))=prev_dep(p);
12104   link(prev_dep(p))=link(q); t=type(p);
12105   type(p)=mp_known; value(p)=value(q); mp_free_node(mp, q,dep_node_size);
12106   if ( abs(value(p))>=fraction_one ) mp_val_too_big(mp, value(p));
12107   if (( mp->internal[tracing_equations]>0) && mp_interesting(mp, p) ) {
12108     mp_begin_diagnostic(mp); mp_print_nl(mp, "#### ");
12109 @:]]]\#\#\#\#_}{\.{\#\#\#\#}@>
12110     mp_print_variable_name(mp, p); 
12111     mp_print_char(mp, '='); mp_print_scaled(mp, value(p));
12112     mp_end_diagnostic(mp, false);
12113   }
12114   if (( mp->cur_exp==p ) && mp->cur_type==t ) {
12115     mp->cur_type=mp_known; mp->cur_exp=value(p);
12116     mp_free_node(mp, p,value_node_size);
12117   }
12118 }
12119
12120 @ The |fix_dependencies| routine is called into action when |fix_needed|
12121 has been triggered. The program keeps a list~|s| of independent variables
12122 whose coefficients must be divided by~4.
12123
12124 In unusual cases, this fixup process might reduce one or more coefficients
12125 to zero, so that a variable will become known more or less by default.
12126
12127 @<Declare basic dependency-list subroutines@>=
12128 void mp_fix_dependencies (MP mp);
12129
12130 @ @c void mp_fix_dependencies (MP mp) {
12131   pointer p,q,r,s,t; /* list manipulation registers */
12132   pointer x; /* an independent variable */
12133   r=link(dep_head); s=null;
12134   while ( r!=dep_head ){ 
12135     t=r;
12136     @<Run through the dependency list for variable |t|, fixing
12137       all nodes, and ending with final link~|q|@>;
12138     r=link(q);
12139     if ( q==dep_list(t) ) mp_make_known(mp, t,q);
12140   }
12141   while ( s!=null ) { 
12142     p=link(s); x=info(s); free_avail(s); s=p;
12143     type(x)=mp_independent; value(x)=value(x)+2;
12144   }
12145   mp->fix_needed=false;
12146 }
12147
12148 @ @d independent_being_fixed 1 /* this variable already appears in |s| */
12149
12150 @<Run through the dependency list for variable |t|...@>=
12151 r=value_loc(t); /* |link(r)=dep_list(t)| */
12152 while (1) { 
12153   q=link(r); x=info(q);
12154   if ( x==null ) break;
12155   if ( type(x)<=independent_being_fixed ) {
12156     if ( type(x)<independent_being_fixed ) {
12157       p=mp_get_avail(mp); link(p)=s; s=p;
12158       info(s)=x; type(x)=independent_being_fixed;
12159     }
12160     value(q)=value(q) / 4;
12161     if ( value(q)==0 ) {
12162       link(r)=link(q); mp_free_node(mp, q,dep_node_size); q=r;
12163     }
12164   }
12165   r=q;
12166 }
12167
12168
12169 @ The |new_dep| routine installs a dependency list~|p| into the value node~|q|,
12170 linking it into the list of all known dependencies. We assume that
12171 |dep_final| points to the final node of list~|p|.
12172
12173 @c void mp_new_dep (MP mp,pointer q, pointer p) {
12174   pointer r; /* what used to be the first dependency */
12175   dep_list(q)=p; prev_dep(q)=dep_head;
12176   r=link(dep_head); link(mp->dep_final)=r; prev_dep(r)=mp->dep_final;
12177   link(dep_head)=q;
12178 }
12179
12180 @ Here is one of the ways a dependency list gets started.
12181 The |const_dependency| routine produces a list that has nothing but
12182 a constant term.
12183
12184 @c pointer mp_const_dependency (MP mp, scaled v) {
12185   mp->dep_final=mp_get_node(mp, dep_node_size);
12186   value(mp->dep_final)=v; info(mp->dep_final)=null;
12187   return mp->dep_final;
12188 }
12189
12190 @ And here's a more interesting way to start a dependency list from scratch:
12191 The parameter to |single_dependency| is the location of an
12192 independent variable~|x|, and the result is the simple dependency list
12193 `|x+0|'.
12194
12195 In the unlikely event that the given independent variable has been doubled so
12196 often that we can't refer to it with a nonzero coefficient,
12197 |single_dependency| returns the simple list `0'.  This case can be
12198 recognized by testing that the returned list pointer is equal to
12199 |dep_final|.
12200
12201 @c pointer mp_single_dependency (MP mp,pointer p) {
12202   pointer q; /* the new dependency list */
12203   integer m; /* the number of doublings */
12204   m=value(p) % s_scale;
12205   if ( m>28 ) {
12206     return mp_const_dependency(mp, 0);
12207   } else { 
12208     q=mp_get_node(mp, dep_node_size);
12209     value(q)=two_to_the(28-m); info(q)=p;
12210     link(q)=mp_const_dependency(mp, 0);
12211     return q;
12212   }
12213 }
12214
12215 @ We sometimes need to make an exact copy of a dependency list.
12216
12217 @c pointer mp_copy_dep_list (MP mp,pointer p) {
12218   pointer q; /* the new dependency list */
12219   q=mp_get_node(mp, dep_node_size); mp->dep_final=q;
12220   while (1) { 
12221     info(mp->dep_final)=info(p); value(mp->dep_final)=value(p);
12222     if ( info(mp->dep_final)==null ) break;
12223     link(mp->dep_final)=mp_get_node(mp, dep_node_size);
12224     mp->dep_final=link(mp->dep_final); p=link(p);
12225   }
12226   return q;
12227 }
12228
12229 @ But how do variables normally become known? Ah, now we get to the heart of the
12230 equation-solving mechanism. The |linear_eq| procedure is given a |dependent|
12231 or |mp_proto_dependent| list,~|p|, in which at least one independent variable
12232 appears. It equates this list to zero, by choosing an independent variable
12233 with the largest coefficient and making it dependent on the others. The
12234 newly dependent variable is eliminated from all current dependencies,
12235 thereby possibly making other dependent variables known.
12236
12237 The given list |p| is, of course, totally destroyed by all this processing.
12238
12239 @c void mp_linear_eq (MP mp, pointer p, small_number t) {
12240   pointer q,r,s; /* for link manipulation */
12241   pointer x; /* the variable that loses its independence */
12242   integer n; /* the number of times |x| had been halved */
12243   integer v; /* the coefficient of |x| in list |p| */
12244   pointer prev_r; /* lags one step behind |r| */
12245   pointer final_node; /* the constant term of the new dependency list */
12246   integer w; /* a tentative coefficient */
12247    @<Find a node |q| in list |p| whose coefficient |v| is largest@>;
12248   x=info(q); n=value(x) % s_scale;
12249   @<Divide list |p| by |-v|, removing node |q|@>;
12250   if ( mp->internal[tracing_equations]>0 ) {
12251     @<Display the new dependency@>;
12252   }
12253   @<Simplify all existing dependencies by substituting for |x|@>;
12254   @<Change variable |x| from |independent| to |dependent| or |known|@>;
12255   if ( mp->fix_needed ) mp_fix_dependencies(mp);
12256 }
12257
12258 @ @<Find a node |q| in list |p| whose coefficient |v| is largest@>=
12259 q=p; r=link(p); v=value(q);
12260 while ( info(r)!=null ) { 
12261   if ( abs(value(r))>abs(v) ) { q=r; v=value(r); };
12262   r=link(r);
12263 }
12264
12265 @ Here we want to change the coefficients from |scaled| to |fraction|,
12266 except in the constant term. In the common case of a trivial equation
12267 like `\.{x=3.14}', we will have |v=-fraction_one|, |q=p|, and |t=mp_dependent|.
12268
12269 @<Divide list |p| by |-v|, removing node |q|@>=
12270 s=temp_head; link(s)=p; r=p;
12271 do { 
12272   if ( r==q ) {
12273     link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12274   } else  { 
12275     w=mp_make_fraction(mp, value(r),v);
12276     if ( abs(w)<=half_fraction_threshold ) {
12277       link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12278     } else { 
12279       value(r)=-w; s=r;
12280     }
12281   }
12282   r=link(s);
12283 } while (info(r)!=null);
12284 if ( t==mp_proto_dependent ) {
12285   value(r)=-mp_make_scaled(mp, value(r),v);
12286 } else if ( v!=-fraction_one ) {
12287   value(r)=-mp_make_fraction(mp, value(r),v);
12288 }
12289 final_node=r; p=link(temp_head)
12290
12291 @ @<Display the new dependency@>=
12292 if ( mp_interesting(mp, x) ) {
12293   mp_begin_diagnostic(mp); mp_print_nl(mp, "## "); 
12294   mp_print_variable_name(mp, x);
12295 @:]]]\#\#_}{\.{\#\#}@>
12296   w=n;
12297   while ( w>0 ) { mp_print(mp, "*4"); w=w-2;  };
12298   mp_print_char(mp, '='); mp_print_dependency(mp, p,mp_dependent); 
12299   mp_end_diagnostic(mp, false);
12300 }
12301
12302 @ @<Simplify all existing dependencies by substituting for |x|@>=
12303 prev_r=dep_head; r=link(dep_head);
12304 while ( r!=dep_head ) {
12305   s=dep_list(r); q=mp_p_with_x_becoming_q(mp, s,x,p,type(r));
12306   if ( info(q)==null ) {
12307     mp_make_known(mp, r,q);
12308   } else { 
12309     dep_list(r)=q;
12310     do {  q=link(q); } while (info(q)!=null);
12311     prev_r=q;
12312   }
12313   r=link(prev_r);
12314 }
12315
12316 @ @<Change variable |x| from |independent| to |dependent| or |known|@>=
12317 if ( n>0 ) @<Divide list |p| by $2^n$@>;
12318 if ( info(p)==null ) {
12319   type(x)=mp_known;
12320   value(x)=value(p);
12321   if ( abs(value(x))>=fraction_one ) mp_val_too_big(mp, value(x));
12322   mp_free_node(mp, p,dep_node_size);
12323   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) {
12324     mp->cur_exp=value(x); mp->cur_type=mp_known;
12325     mp_free_node(mp, x,value_node_size);
12326   }
12327 } else { 
12328   type(x)=mp_dependent; mp->dep_final=final_node; mp_new_dep(mp, x,p);
12329   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) mp->cur_type=mp_dependent;
12330 }
12331
12332 @ @<Divide list |p| by $2^n$@>=
12333
12334   s=temp_head; link(temp_head)=p; r=p;
12335   do {  
12336     if ( n>30 ) w=0;
12337     else w=value(r) / two_to_the(n);
12338     if ( (abs(w)<=half_fraction_threshold)&&(info(r)!=null) ) {
12339       link(s)=link(r);
12340       mp_free_node(mp, r,dep_node_size);
12341     } else { 
12342       value(r)=w; s=r;
12343     }
12344     r=link(s);
12345   } while (info(s)!=null);
12346   p=link(temp_head);
12347 }
12348
12349 @ The |check_mem| procedure, which is used only when \MP\ is being
12350 debugged, makes sure that the current dependency lists are well formed.
12351
12352 @<Check the list of linear dependencies@>=
12353 q=dep_head; p=link(q);
12354 while ( p!=dep_head ) {
12355   if ( prev_dep(p)!=q ) {
12356     mp_print_nl(mp, "Bad PREVDEP at "); mp_print_int(mp, p);
12357 @.Bad PREVDEP...@>
12358   }
12359   p=dep_list(p);
12360   while (1) {
12361     r=info(p); q=p; p=link(q);
12362     if ( r==null ) break;
12363     if ( value(info(p))>=value(r) ) {
12364       mp_print_nl(mp, "Out of order at "); mp_print_int(mp, p);
12365 @.Out of order...@>
12366     }
12367   }
12368 }
12369
12370 @* \[25] Dynamic nonlinear equations.
12371 Variables of numeric type are maintained by the general scheme of
12372 independent, dependent, and known values that we have just studied;
12373 and the components of pair and transform variables are handled in the
12374 same way. But \MP\ also has five other types of values: \&{boolean},
12375 \&{string}, \&{pen}, \&{path}, and \&{picture}; what about them?
12376
12377 Equations are allowed between nonlinear quantities, but only in a
12378 simple form. Two variables that haven't yet been assigned values are
12379 either equal to each other, or they're not.
12380
12381 Before a boolean variable has received a value, its type is |mp_unknown_boolean|;
12382 similarly, there are variables whose type is |mp_unknown_string|, |mp_unknown_pen|,
12383 |mp_unknown_path|, and |mp_unknown_picture|. In such cases the value is either
12384 |null| (which means that no other variables are equivalent to this one), or
12385 it points to another variable of the same undefined type. The pointers in the
12386 latter case form a cycle of nodes, which we shall call a ``ring.''
12387 Rings of undefined variables may include capsules, which arise as
12388 intermediate results within expressions or as \&{expr} parameters to macros.
12389
12390 When one member of a ring receives a value, the same value is given to
12391 all the other members. In the case of paths and pictures, this implies
12392 making separate copies of a potentially large data structure; users should
12393 restrain their enthusiasm for such generality, unless they have lots and
12394 lots of memory space.
12395
12396 @ The following procedure is called when a capsule node is being
12397 added to a ring (e.g., when an unknown variable is mentioned in an expression).
12398
12399 @c pointer mp_new_ring_entry (MP mp,pointer p) {
12400   pointer q; /* the new capsule node */
12401   q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
12402   type(q)=type(p);
12403   if ( value(p)==null ) value(q)=p; else value(q)=value(p);
12404   value(p)=q;
12405   return q;
12406 }
12407
12408 @ Conversely, we might delete a capsule or a variable before it becomes known.
12409 The following procedure simply detaches a quantity from its ring,
12410 without recycling the storage.
12411
12412 @<Declare the recycling subroutines@>=
12413 void mp_ring_delete (MP mp,pointer p) {
12414   pointer q; 
12415   q=value(p);
12416   if ( q!=null ) if ( q!=p ){ 
12417     while ( value(q)!=p ) q=value(q);
12418     value(q)=value(p);
12419   }
12420 }
12421
12422 @ Eventually there might be an equation that assigns values to all of the
12423 variables in a ring. The |nonlinear_eq| subroutine does the necessary
12424 propagation of values.
12425
12426 If the parameter |flush_p| is |true|, node |p| itself needn't receive a
12427 value, it will soon be recycled.
12428
12429 @c void mp_nonlinear_eq (MP mp,integer v, pointer p, boolean flush_p) {
12430   small_number t; /* the type of ring |p| */
12431   pointer q,r; /* link manipulation registers */
12432   t=type(p)-unknown_tag; q=value(p);
12433   if ( flush_p ) type(p)=mp_vacuous; else p=q;
12434   do {  
12435     r=value(q); type(q)=t;
12436     switch (t) {
12437     case mp_boolean_type: value(q)=v; break;
12438     case mp_string_type: value(q)=v; add_str_ref(v); break;
12439     case mp_pen_type: value(q)=copy_pen(v); break;
12440     case mp_path_type: value(q)=mp_copy_path(mp, v); break;
12441     case mp_picture_type: value(q)=v; add_edge_ref(v); break;
12442     } /* there ain't no more cases */
12443     q=r;
12444   } while (q!=p);
12445 }
12446
12447 @ If two members of rings are equated, and if they have the same type,
12448 the |ring_merge| procedure is called on to make them equivalent.
12449
12450 @c void mp_ring_merge (MP mp,pointer p, pointer q) {
12451   pointer r; /* traverses one list */
12452   r=value(p);
12453   while ( r!=p ) {
12454     if ( r==q ) {
12455       @<Exclaim about a redundant equation@>;
12456       return;
12457     };
12458     r=value(r);
12459   }
12460   r=value(p); value(p)=value(q); value(q)=r;
12461 }
12462
12463 @ @<Exclaim about a redundant equation@>=
12464
12465   print_err("Redundant equation");
12466 @.Redundant equation@>
12467   help2("I already knew that this equation was true.")
12468    ("But perhaps no harm has been done; let's continue.");
12469   mp_put_get_error(mp);
12470 }
12471
12472 @* \[26] Introduction to the syntactic routines.
12473 Let's pause a moment now and try to look at the Big Picture.
12474 The \MP\ program consists of three main parts: syntactic routines,
12475 semantic routines, and output routines. The chief purpose of the
12476 syntactic routines is to deliver the user's input to the semantic routines,
12477 while parsing expressions and locating operators and operands. The
12478 semantic routines act as an interpreter responding to these operators,
12479 which may be regarded as commands. And the output routines are
12480 periodically called on to produce compact font descriptions that can be
12481 used for typesetting or for making interim proof drawings. We have
12482 discussed the basic data structures and many of the details of semantic
12483 operations, so we are good and ready to plunge into the part of \MP\ that
12484 actually controls the activities.
12485
12486 Our current goal is to come to grips with the |get_next| procedure,
12487 which is the keystone of \MP's input mechanism. Each call of |get_next|
12488 sets the value of three variables |cur_cmd|, |cur_mod|, and |cur_sym|,
12489 representing the next input token.
12490 $$\vbox{\halign{#\hfil\cr
12491   \hbox{|cur_cmd| denotes a command code from the long list of codes
12492    given earlier;}\cr
12493   \hbox{|cur_mod| denotes a modifier of the command code;}\cr
12494   \hbox{|cur_sym| is the hash address of the symbolic token that was
12495    just scanned,}\cr
12496   \hbox{\qquad or zero in the case of a numeric or string
12497    or capsule token.}\cr}}$$
12498 Underlying this external behavior of |get_next| is all the machinery
12499 necessary to convert from character files to tokens. At a given time we
12500 may be only partially finished with the reading of several files (for
12501 which \&{input} was specified), and partially finished with the expansion
12502 of some user-defined macros and/or some macro parameters, and partially
12503 finished reading some text that the user has inserted online,
12504 and so on. When reading a character file, the characters must be
12505 converted to tokens; comments and blank spaces must
12506 be removed, numeric and string tokens must be evaluated.
12507
12508 To handle these situations, which might all be present simultaneously,
12509 \MP\ uses various stacks that hold information about the incomplete
12510 activities, and there is a finite state control for each level of the
12511 input mechanism. These stacks record the current state of an implicitly
12512 recursive process, but the |get_next| procedure is not recursive.
12513
12514 @<Glob...@>=
12515 eight_bits cur_cmd; /* current command set by |get_next| */
12516 integer cur_mod; /* operand of current command */
12517 halfword cur_sym; /* hash address of current symbol */
12518
12519 @ The |print_cmd_mod| routine prints a symbolic interpretation of a
12520 command code and its modifier.
12521 It consists of a rather tedious sequence of print
12522 commands, and most of it is essentially an inverse to the |primitive|
12523 routine that enters a \MP\ primitive into |hash| and |eqtb|. Therefore almost
12524 all of this procedure appears elsewhere in the program, together with the
12525 corresponding |primitive| calls.
12526
12527 @<Declare the procedure called |print_cmd_mod|@>=
12528 void mp_print_cmd_mod (MP mp,integer c, integer m) { 
12529  switch (c) {
12530   @<Cases of |print_cmd_mod| for symbolic printing of primitives@>
12531   default: mp_print(mp, "[unknown command code!]"); break;
12532   }
12533 }
12534
12535 @ Here is a procedure that displays a given command in braces, in the
12536 user's transcript file.
12537
12538 @d show_cur_cmd_mod mp_show_cmd_mod(mp, mp->cur_cmd,mp->cur_mod)
12539
12540 @c 
12541 void mp_show_cmd_mod (MP mp,integer c, integer m) { 
12542   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
12543   mp_print_cmd_mod(mp, c,m); mp_print_char(mp, '}');
12544   mp_end_diagnostic(mp, false);
12545 }
12546
12547 @* \[27] Input stacks and states.
12548 The state of \MP's input mechanism appears in the input stack, whose
12549 entries are records with five fields, called |index|, |start|, |loc|,
12550 |limit|, and |name|. The top element of this stack is maintained in a
12551 global variable for which no subscripting needs to be done; the other
12552 elements of the stack appear in an array. Hence the stack is declared thus:
12553
12554 @<Types...@>=
12555 typedef struct {
12556   quarterword index_field;
12557   halfword start_field, loc_field, limit_field, name_field;
12558 } in_state_record;
12559
12560 @ @<Glob...@>=
12561 in_state_record *input_stack;
12562 integer input_ptr; /* first unused location of |input_stack| */
12563 integer max_in_stack; /* largest value of |input_ptr| when pushing */
12564 in_state_record cur_input; /* the ``top'' input state */
12565 int stack_size; /* maximum number of simultaneous input sources */
12566
12567 @ @<Allocate or initialize ...@>=
12568 mp->stack_size = 300;
12569 mp->input_stack = xmalloc((mp->stack_size+1),sizeof(in_state_record));
12570
12571 @ @<Dealloc variables@>=
12572 xfree(mp->input_stack);
12573
12574 @ We've already defined the special variable |loc==cur_input.loc_field|
12575 in our discussion of basic input-output routines. The other components of
12576 |cur_input| are defined in the same way:
12577
12578 @d index mp->cur_input.index_field /* reference for buffer information */
12579 @d start mp->cur_input.start_field /* starting position in |buffer| */
12580 @d limit mp->cur_input.limit_field /* end of current line in |buffer| */
12581 @d name mp->cur_input.name_field /* name of the current file */
12582
12583 @ Let's look more closely now at the five control variables
12584 (|index|,~|start|,~|loc|,~|limit|,~|name|),
12585 assuming that \MP\ is reading a line of characters that have been input
12586 from some file or from the user's terminal. There is an array called
12587 |buffer| that acts as a stack of all lines of characters that are
12588 currently being read from files, including all lines on subsidiary
12589 levels of the input stack that are not yet completed. \MP\ will return to
12590 the other lines when it is finished with the present input file.
12591
12592 (Incidentally, on a machine with byte-oriented addressing, it would be
12593 appropriate to combine |buffer| with the |str_pool| array,
12594 letting the buffer entries grow downward from the top of the string pool
12595 and checking that these two tables don't bump into each other.)
12596
12597 The line we are currently working on begins in position |start| of the
12598 buffer; the next character we are about to read is |buffer[loc]|; and
12599 |limit| is the location of the last character present. We always have
12600 |loc<=limit|. For convenience, |buffer[limit]| has been set to |"%"|, so
12601 that the end of a line is easily sensed.
12602
12603 The |name| variable is a string number that designates the name of
12604 the current file, if we are reading an ordinary text file.  Special codes
12605 |is_term..max_spec_src| indicate other sources of input text.
12606
12607 @d is_term 0 /* |name| value when reading from the terminal for normal input */
12608 @d is_read 1 /* |name| value when executing a \&{readstring} or \&{readfrom} */
12609 @d is_scantok 2 /* |name| value when reading text generated by \&{scantokens} */
12610 @d max_spec_src is_scantok
12611
12612 @ Additional information about the current line is available via the
12613 |index| variable, which counts how many lines of characters are present
12614 in the buffer below the current level. We have |index=0| when reading
12615 from the terminal and prompting the user for each line; then if the user types,
12616 e.g., `\.{input figs}', we will have |index=1| while reading
12617 the file \.{figs.mp}. However, it does not follow that |index| is the
12618 same as the input stack pointer, since many of the levels on the input
12619 stack may come from token lists and some |index| values may correspond
12620 to \.{MPX} files that are not currently on the stack.
12621
12622 The global variable |in_open| is equal to the highest |index| value counting
12623 \.{MPX} files but excluding token-list input levels.  Thus, the number of
12624 partially read lines in the buffer is |in_open+1| and we have |in_open>=index|
12625 when we are not reading a token list.
12626
12627 If we are not currently reading from the terminal,
12628 we are reading from the file variable |input_file[index]|. We use
12629 the notation |terminal_input| as a convenient abbreviation for |name=is_term|,
12630 and |cur_file| as an abbreviation for |input_file[index]|.
12631
12632 When \MP\ is not reading from the terminal, the global variable |line| contains
12633 the line number in the current file, for use in error messages. More precisely,
12634 |line| is a macro for |line_stack[index]| and the |line_stack| array gives
12635 the line number for each file in the |input_file| array.
12636
12637 When an \.{MPX} file is opened the file name is stored in the |mpx_name|
12638 array so that the name doesn't get lost when the file is temporarily removed
12639 from the input stack.
12640 Thus when |input_file[k]| is an \.{MPX} file, its name is |mpx_name[k]|
12641 and it contains translated \TeX\ pictures for |input_file[k-1]|.
12642 Since this is not an \.{MPX} file, we have
12643 $$ \hbox{|mpx_name[k-1]<=absent|}. $$
12644 This |name| field is set to |finished| when |input_file[k]| is completely
12645 read.
12646
12647 If more information about the input state is needed, it can be
12648 included in small arrays like those shown here. For example,
12649 the current page or segment number in the input file might be put
12650 into a variable |page|, that is really a macro for the current entry
12651 in `\ignorespaces|page_stack:array[0..max_in_open] of integer|\unskip'
12652 by analogy with |line_stack|.
12653 @^system dependencies@>
12654
12655 @d terminal_input (name==is_term) /* are we reading from the terminal? */
12656 @d cur_file mp->input_file[index] /* the current |FILE *| variable */
12657 @d line mp->line_stack[index] /* current line number in the current source file */
12658 @d in_name mp->iname_stack[index] /* a string used to construct \.{MPX} file names */
12659 @d in_area mp->iarea_stack[index] /* another string for naming \.{MPX} files */
12660 @d absent 1 /* |name_field| value for unused |mpx_in_stack| entries */
12661 @d mpx_reading (mp->mpx_name[index]>absent)
12662   /* when reading a file, is it an \.{MPX} file? */
12663 @d finished 0
12664   /* |name_field| value when the corresponding \.{MPX} file is finished */
12665
12666 @<Glob...@>=
12667 integer in_open; /* the number of lines in the buffer, less one */
12668 unsigned int open_parens; /* the number of open text files */
12669 FILE  * *input_file ;
12670 integer *line_stack ; /* the line number for each file */
12671 char *  *iname_stack; /* used for naming \.{MPX} files */
12672 char *  *iarea_stack; /* used for naming \.{MPX} files */
12673 halfword*mpx_name  ;
12674
12675 @ @<Allocate or ...@>=
12676 mp->input_file  = xmalloc((mp->max_in_open+1),sizeof(FILE *));
12677 mp->line_stack  = xmalloc((mp->max_in_open+1),sizeof(integer));
12678 mp->iname_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12679 mp->iarea_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12680 mp->mpx_name    = xmalloc((mp->max_in_open+1),sizeof(halfword));
12681 {
12682   int k;
12683   for (k=0;k<=mp->max_in_open;k++) {
12684     mp->iname_stack[k] =NULL;
12685     mp->iarea_stack[k] =NULL;
12686   }
12687 }
12688
12689 @ @<Dealloc variables@>=
12690 {
12691   int l;
12692   for (l=0;l<=mp->max_in_open;l++) {
12693     xfree(mp->iname_stack[l]);
12694     xfree(mp->iarea_stack[l]);
12695   }
12696 }
12697 xfree(mp->input_file);
12698 xfree(mp->line_stack);
12699 xfree(mp->iname_stack);
12700 xfree(mp->iarea_stack);
12701 xfree(mp->mpx_name);
12702
12703
12704 @ However, all this discussion about input state really applies only to the
12705 case that we are inputting from a file. There is another important case,
12706 namely when we are currently getting input from a token list. In this case
12707 |index>max_in_open|, and the conventions about the other state variables
12708 are different:
12709
12710 \yskip\hang|loc| is a pointer to the current node in the token list, i.e.,
12711 the node that will be read next. If |loc=null|, the token list has been
12712 fully read.
12713
12714 \yskip\hang|start| points to the first node of the token list; this node
12715 may or may not contain a reference count, depending on the type of token
12716 list involved.
12717
12718 \yskip\hang|token_type|, which takes the place of |index| in the
12719 discussion above, is a code number that explains what kind of token list
12720 is being scanned.
12721
12722 \yskip\hang|name| points to the |eqtb| address of the control sequence
12723 being expanded, if the current token list is a macro not defined by
12724 \&{vardef}. Macros defined by \&{vardef} have |name=null|; their name
12725 can be deduced by looking at their first two parameters.
12726
12727 \yskip\hang|param_start|, which takes the place of |limit|, tells where
12728 the parameters of the current macro or loop text begin in the |param_stack|.
12729
12730 \yskip\noindent The |token_type| can take several values, depending on
12731 where the current token list came from:
12732
12733 \yskip
12734 \indent|forever_text|, if the token list being scanned is the body of
12735 a \&{forever} loop;
12736
12737 \indent|loop_text|, if the token list being scanned is the body of
12738 a \&{for} or \&{forsuffixes} loop;
12739
12740 \indent|parameter|, if a \&{text} or \&{suffix} parameter is being scanned;
12741
12742 \indent|backed_up|, if the token list being scanned has been inserted as
12743 `to be read again'.
12744
12745 \indent|inserted|, if the token list being scanned has been inserted as
12746 part of error recovery;
12747
12748 \indent|macro|, if the expansion of a user-defined symbolic token is being
12749 scanned.
12750
12751 \yskip\noindent
12752 The token list begins with a reference count if and only if |token_type=
12753 macro|.
12754 @^reference counts@>
12755
12756 @d token_type index /* type of current token list */
12757 @d token_state (index>(int)mp->max_in_open) /* are we scanning a token list? */
12758 @d file_state (index<=(int)mp->max_in_open) /* are we scanning a file line? */
12759 @d param_start limit /* base of macro parameters in |param_stack| */
12760 @d forever_text (mp->max_in_open+1) /* |token_type| code for loop texts */
12761 @d loop_text (mp->max_in_open+2) /* |token_type| code for loop texts */
12762 @d parameter (mp->max_in_open+3) /* |token_type| code for parameter texts */
12763 @d backed_up (mp->max_in_open+4) /* |token_type| code for texts to be reread */
12764 @d inserted (mp->max_in_open+5) /* |token_type| code for inserted texts */
12765 @d macro (mp->max_in_open+6) /* |token_type| code for macro replacement texts */
12766
12767 @ The |param_stack| is an auxiliary array used to hold pointers to the token
12768 lists for parameters at the current level and subsidiary levels of input.
12769 This stack grows at a different rate from the others.
12770
12771 @<Glob...@>=
12772 pointer *param_stack;  /* token list pointers for parameters */
12773 integer param_ptr; /* first unused entry in |param_stack| */
12774 integer max_param_stack;  /* largest value of |param_ptr| */
12775
12776 @ @<Allocate or initialize ...@>=
12777 mp->param_stack = xmalloc((mp->param_size+1),sizeof(pointer));
12778
12779 @ @<Dealloc variables@>=
12780 xfree(mp->param_stack);
12781
12782 @ Notice that the |line| isn't valid when |token_state| is true because it
12783 depends on |index|.  If we really need to know the line number for the
12784 topmost file in the index stack we use the following function.  If a page
12785 number or other information is needed, this routine should be modified to
12786 compute it as well.
12787 @^system dependencies@>
12788
12789 @<Declare a function called |true_line|@>=
12790 integer mp_true_line (MP mp) {
12791   int k; /* an index into the input stack */
12792   if ( file_state && (name>max_spec_src) ) {
12793      return line;
12794   } else { 
12795     k=mp->input_ptr;
12796     while ((k>0) &&
12797            ((mp->input_stack[(k-1)].index_field>mp->max_in_open)||
12798             (mp->input_stack[(k-1)].name_field<=max_spec_src))) {
12799       decr(k);
12800     }
12801     return mp->line_stack[(k-1)];
12802   }
12803   return 0; 
12804 }
12805
12806 @ Thus, the ``current input state'' can be very complicated indeed; there
12807 can be many levels and each level can arise in a variety of ways. The
12808 |show_context| procedure, which is used by \MP's error-reporting routine to
12809 print out the current input state on all levels down to the most recent
12810 line of characters from an input file, illustrates most of these conventions.
12811 The global variable |file_ptr| contains the lowest level that was
12812 displayed by this procedure.
12813
12814 @<Glob...@>=
12815 integer file_ptr; /* shallowest level shown by |show_context| */
12816
12817 @ The status at each level is indicated by printing two lines, where the first
12818 line indicates what was read so far and the second line shows what remains
12819 to be read. The context is cropped, if necessary, so that the first line
12820 contains at most |half_error_line| characters, and the second contains
12821 at most |error_line|. Non-current input levels whose |token_type| is
12822 `|backed_up|' are shown only if they have not been fully read.
12823
12824 @c void mp_show_context (MP mp) { /* prints where the scanner is */
12825   int old_setting; /* saved |selector| setting */
12826   @<Local variables for formatting calculations@>
12827   mp->file_ptr=mp->input_ptr; mp->input_stack[mp->file_ptr]=mp->cur_input;
12828   /* store current state */
12829   while (1) { 
12830     mp->cur_input=mp->input_stack[mp->file_ptr]; /* enter into the context */
12831     @<Display the current context@>;
12832     if ( file_state )
12833       if ( (name>max_spec_src) || (mp->file_ptr==0) ) break;
12834     decr(mp->file_ptr);
12835   }
12836   mp->cur_input=mp->input_stack[mp->input_ptr]; /* restore original state */
12837 }
12838
12839 @ @<Display the current context@>=
12840 if ( (mp->file_ptr==mp->input_ptr) || file_state ||
12841    (token_type!=backed_up) || (loc!=null) ) {
12842     /* we omit backed-up token lists that have already been read */
12843   mp->tally=0; /* get ready to count characters */
12844   old_setting=mp->selector;
12845   if ( file_state ) {
12846     @<Print location of current line@>;
12847     @<Pseudoprint the line@>;
12848   } else { 
12849     @<Print type of token list@>;
12850     @<Pseudoprint the token list@>;
12851   }
12852   mp->selector=old_setting; /* stop pseudoprinting */
12853   @<Print two lines using the tricky pseudoprinted information@>;
12854 }
12855
12856 @ This routine should be changed, if necessary, to give the best possible
12857 indication of where the current line resides in the input file.
12858 For example, on some systems it is best to print both a page and line number.
12859 @^system dependencies@>
12860
12861 @<Print location of current line@>=
12862 if ( name>max_spec_src ) {
12863   mp_print_nl(mp, "l."); mp_print_int(mp, mp_true_line(mp));
12864 } else if ( terminal_input ) {
12865   if ( mp->file_ptr==0 ) mp_print_nl(mp, "<*>");
12866   else mp_print_nl(mp, "<insert>");
12867 } else if ( name==is_scantok ) {
12868   mp_print_nl(mp, "<scantokens>");
12869 } else {
12870   mp_print_nl(mp, "<read>");
12871 }
12872 mp_print_char(mp, ' ')
12873
12874 @ Can't use case statement here because the |token_type| is not
12875 a constant expression.
12876
12877 @<Print type of token list@>=
12878 {
12879   if(token_type==forever_text) {
12880     mp_print_nl(mp, "<forever> ");
12881   } else if (token_type==loop_text) {
12882     @<Print the current loop value@>;
12883   } else if (token_type==parameter) {
12884     mp_print_nl(mp, "<argument> "); 
12885   } else if (token_type==backed_up) { 
12886     if ( loc==null ) mp_print_nl(mp, "<recently read> ");
12887     else mp_print_nl(mp, "<to be read again> ");
12888   } else if (token_type==inserted) {
12889     mp_print_nl(mp, "<inserted text> ");
12890   } else if (token_type==macro) {
12891     mp_print_ln(mp);
12892     if ( name!=null ) mp_print_text(name);
12893     else @<Print the name of a \&{vardef}'d macro@>;
12894     mp_print(mp, "->");
12895   } else {
12896     mp_print_nl(mp, "?");/* this should never happen */
12897 @.?\relax@>
12898   }
12899 }
12900
12901 @ The parameter that corresponds to a loop text is either a token list
12902 (in the case of \&{forsuffixes}) or a ``capsule'' (in the case of \&{for}).
12903 We'll discuss capsules later; for now, all we need to know is that
12904 the |link| field in a capsule parameter is |void| and that
12905 |print_exp(p,0)| displays the value of capsule~|p| in abbreviated form.
12906
12907 @d diov (null+1) /* a null pointer different from |null| */
12908
12909 @<Print the current loop value@>=
12910 { mp_print_nl(mp, "<for("); p=mp->param_stack[param_start];
12911   if ( p!=null ) {
12912     if ( link(p)==diov ) mp_print_exp(mp, p,0); /* we're in a \&{for} loop */
12913     else mp_show_token_list(mp, p,null,20,mp->tally);
12914   }
12915   mp_print(mp, ")> ");
12916 }
12917
12918 @ The first two parameters of a macro defined by \&{vardef} will be token
12919 lists representing the macro's prefix and ``at point.'' By putting these
12920 together, we get the macro's full name.
12921
12922 @<Print the name of a \&{vardef}'d macro@>=
12923 { p=mp->param_stack[param_start];
12924   if ( p==null ) {
12925     mp_show_token_list(mp, mp->param_stack[param_start+1],null,20,mp->tally);
12926   } else { 
12927     q=p;
12928     while ( link(q)!=null ) q=link(q);
12929     link(q)=mp->param_stack[param_start+1];
12930     mp_show_token_list(mp, p,null,20,mp->tally);
12931     link(q)=null;
12932   }
12933 }
12934
12935 @ Now it is necessary to explain a little trick. We don't want to store a long
12936 string that corresponds to a token list, because that string might take up
12937 lots of memory; and we are printing during a time when an error message is
12938 being given, so we dare not do anything that might overflow one of \MP's
12939 tables. So `pseudoprinting' is the answer: We enter a mode of printing
12940 that stores characters into a buffer of length |error_line|, where character
12941 $k+1$ is placed into \hbox{|trick_buf[k mod error_line]|} if
12942 |k<trick_count|, otherwise character |k| is dropped. Initially we set
12943 |tally:=0| and |trick_count:=1000000|; then when we reach the
12944 point where transition from line 1 to line 2 should occur, we
12945 set |first_count:=tally| and |trick_count:=@tmax@>(error_line,
12946 tally+1+error_line-half_error_line)|. At the end of the
12947 pseudoprinting, the values of |first_count|, |tally|, and
12948 |trick_count| give us all the information we need to print the two lines,
12949 and all of the necessary text is in |trick_buf|.
12950
12951 Namely, let |l| be the length of the descriptive information that appears
12952 on the first line. The length of the context information gathered for that
12953 line is |k=first_count|, and the length of the context information
12954 gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k<=h|,
12955 where |h=half_error_line|, we print |trick_buf[0..k-1]| after the
12956 descriptive information on line~1, and set |n:=l+k|; here |n| is the
12957 length of line~1. If $l+k>h$, some cropping is necessary, so we set |n:=h|
12958 and print `\.{...}' followed by
12959 $$\hbox{|trick_buf[(l+k-h+3)..k-1]|,}$$
12960 where subscripts of |trick_buf| are circular modulo |error_line|. The
12961 second line consists of |n|~spaces followed by |trick_buf[k..(k+m-1)]|,
12962 unless |n+m>error_line|; in the latter case, further cropping is done.
12963 This is easier to program than to explain.
12964
12965 @<Local variables for formatting...@>=
12966 int i; /* index into |buffer| */
12967 integer l; /* length of descriptive information on line 1 */
12968 integer m; /* context information gathered for line 2 */
12969 int n; /* length of line 1 */
12970 integer p; /* starting or ending place in |trick_buf| */
12971 integer q; /* temporary index */
12972
12973 @ The following code tells the print routines to gather
12974 the desired information.
12975
12976 @d begin_pseudoprint { 
12977   l=mp->tally; mp->tally=0; mp->selector=pseudo;
12978   mp->trick_count=1000000;
12979 }
12980 @d set_trick_count {
12981   mp->first_count=mp->tally;
12982   mp->trick_count=mp->tally+1+mp->error_line-mp->half_error_line;
12983   if ( mp->trick_count<mp->error_line ) mp->trick_count=mp->error_line;
12984 }
12985
12986 @ And the following code uses the information after it has been gathered.
12987
12988 @<Print two lines using the tricky pseudoprinted information@>=
12989 if ( mp->trick_count==1000000 ) set_trick_count;
12990   /* |set_trick_count| must be performed */
12991 if ( mp->tally<mp->trick_count ) m=mp->tally-mp->first_count;
12992 else m=mp->trick_count-mp->first_count; /* context on line 2 */
12993 if ( l+mp->first_count<=mp->half_error_line ) {
12994   p=0; n=l+mp->first_count;
12995 } else  { 
12996   mp_print(mp, "..."); p=l+mp->first_count-mp->half_error_line+3;
12997   n=mp->half_error_line;
12998 }
12999 for (q=p;q<=mp->first_count-1;q++) {
13000   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13001 }
13002 mp_print_ln(mp);
13003 for (q=1;q<=n;q++) {
13004   mp_print_char(mp, ' '); /* print |n| spaces to begin line~2 */
13005 }
13006 if ( m+n<=mp->error_line ) p=mp->first_count+m; 
13007 else p=mp->first_count+(mp->error_line-n-3);
13008 for (q=mp->first_count;q<=p-1;q++) {
13009   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13010 }
13011 if ( m+n>mp->error_line ) mp_print(mp, "...")
13012
13013 @ But the trick is distracting us from our current goal, which is to
13014 understand the input state. So let's concentrate on the data structures that
13015 are being pseudoprinted as we finish up the |show_context| procedure.
13016
13017 @<Pseudoprint the line@>=
13018 begin_pseudoprint;
13019 if ( limit>0 ) {
13020   for (i=start;i<=limit-1;i++) {
13021     if ( i==loc ) set_trick_count;
13022     mp_print_str(mp, mp->buffer[i]);
13023   }
13024 }
13025
13026 @ @<Pseudoprint the token list@>=
13027 begin_pseudoprint;
13028 if ( token_type!=macro ) mp_show_token_list(mp, start,loc,100000,0);
13029 else mp_show_macro(mp, start,loc,100000)
13030
13031 @ Here is the missing piece of |show_token_list| that is activated when the
13032 token beginning line~2 is about to be shown:
13033
13034 @<Do magic computation@>=set_trick_count
13035
13036 @* \[28] Maintaining the input stacks.
13037 The following subroutines change the input status in commonly needed ways.
13038
13039 First comes |push_input|, which stores the current state and creates a
13040 new level (having, initially, the same properties as the old).
13041
13042 @d push_input  { /* enter a new input level, save the old */
13043   if ( mp->input_ptr>mp->max_in_stack ) {
13044     mp->max_in_stack=mp->input_ptr;
13045     if ( mp->input_ptr==mp->stack_size ) {
13046       int l = (mp->stack_size+(mp->stack_size>>2));
13047       XREALLOC(mp->input_stack, l, in_state_record);
13048       mp->stack_size = l;
13049     }         
13050   }
13051   mp->input_stack[mp->input_ptr]=mp->cur_input; /* stack the record */
13052   incr(mp->input_ptr);
13053 }
13054
13055 @ And of course what goes up must come down.
13056
13057 @d pop_input { /* leave an input level, re-enter the old */
13058     decr(mp->input_ptr); mp->cur_input=mp->input_stack[mp->input_ptr];
13059   }
13060
13061 @ Here is a procedure that starts a new level of token-list input, given
13062 a token list |p| and its type |t|. If |t=macro|, the calling routine should
13063 set |name|, reset~|loc|, and increase the macro's reference count.
13064
13065 @d back_list(A) mp_begin_token_list(mp, (A),backed_up) /* backs up a simple token list */
13066
13067 @c void mp_begin_token_list (MP mp,pointer p, quarterword t)  { 
13068   push_input; start=p; token_type=t;
13069   param_start=mp->param_ptr; loc=p;
13070 }
13071
13072 @ When a token list has been fully scanned, the following computations
13073 should be done as we leave that level of input.
13074 @^inner loop@>
13075
13076 @c void mp_end_token_list (MP mp) { /* leave a token-list input level */
13077   pointer p; /* temporary register */
13078   if ( token_type>=backed_up ) { /* token list to be deleted */
13079     if ( token_type<=inserted ) { 
13080       mp_flush_token_list(mp, start); goto DONE;
13081     } else {
13082       mp_delete_mac_ref(mp, start); /* update reference count */
13083     }
13084   }
13085   while ( mp->param_ptr>param_start ) { /* parameters must be flushed */
13086     decr(mp->param_ptr);
13087     p=mp->param_stack[mp->param_ptr];
13088     if ( p!=null ) {
13089       if ( link(p)==diov ) { /* it's an \&{expr} parameter */
13090         mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
13091       } else {
13092         mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
13093       }
13094     }
13095   }
13096 DONE: 
13097   pop_input; check_interrupt;
13098 }
13099
13100 @ The contents of |cur_cmd,cur_mod,cur_sym| are placed into an equivalent
13101 token by the |cur_tok| routine.
13102 @^inner loop@>
13103
13104 @c @<Declare the procedure called |make_exp_copy|@>;
13105 pointer mp_cur_tok (MP mp) {
13106   pointer p; /* a new token node */
13107   small_number save_type; /* |cur_type| to be restored */
13108   integer save_exp; /* |cur_exp| to be restored */
13109   if ( mp->cur_sym==0 ) {
13110     if ( mp->cur_cmd==capsule_token ) {
13111       save_type=mp->cur_type; save_exp=mp->cur_exp;
13112       mp_make_exp_copy(mp, mp->cur_mod); p=mp_stash_cur_exp(mp); link(p)=null;
13113       mp->cur_type=save_type; mp->cur_exp=save_exp;
13114     } else { 
13115       p=mp_get_node(mp, token_node_size);
13116       value(p)=mp->cur_mod; name_type(p)=mp_token;
13117       if ( mp->cur_cmd==numeric_token ) type(p)=mp_known;
13118       else type(p)=mp_string_type;
13119     }
13120   } else { 
13121     fast_get_avail(p); info(p)=mp->cur_sym;
13122   }
13123   return p;
13124 }
13125
13126 @ Sometimes \MP\ has read too far and wants to ``unscan'' what it has
13127 seen. The |back_input| procedure takes care of this by putting the token
13128 just scanned back into the input stream, ready to be read again.
13129 If |cur_sym<>0|, the values of |cur_cmd| and |cur_mod| are irrelevant.
13130
13131 @<Declarations@>= 
13132 void mp_back_input (MP mp);
13133
13134 @ @c void mp_back_input (MP mp) {/* undoes one token of input */
13135   pointer p; /* a token list of length one */
13136   p=mp_cur_tok(mp);
13137   while ( token_state &&(loc==null) ) 
13138     mp_end_token_list(mp); /* conserve stack space */
13139   back_list(p);
13140 }
13141
13142 @ The |back_error| routine is used when we want to restore or replace an
13143 offending token just before issuing an error message.  We disable interrupts
13144 during the call of |back_input| so that the help message won't be lost.
13145
13146 @<Declarations@>=
13147 void mp_error (MP mp);
13148 void mp_back_error (MP mp);
13149
13150 @ @c void mp_back_error (MP mp) { /* back up one token and call |error| */
13151   mp->OK_to_interrupt=false; 
13152   mp_back_input(mp); 
13153   mp->OK_to_interrupt=true; mp_error(mp);
13154 }
13155 void mp_ins_error (MP mp) { /* back up one inserted token and call |error| */
13156   mp->OK_to_interrupt=false; 
13157   mp_back_input(mp); token_type=inserted;
13158   mp->OK_to_interrupt=true; mp_error(mp);
13159 }
13160
13161 @ The |begin_file_reading| procedure starts a new level of input for lines
13162 of characters to be read from a file, or as an insertion from the
13163 terminal. It does not take care of opening the file, nor does it set |loc|
13164 or |limit| or |line|.
13165 @^system dependencies@>
13166
13167 @c void mp_begin_file_reading (MP mp) { 
13168   if ( mp->in_open==mp->max_in_open ) 
13169     mp_overflow(mp, "text input levels",mp->max_in_open);
13170 @:MetaPost capacity exceeded text input levels}{\quad text input levels@>
13171   if ( mp->first==mp->buf_size ) 
13172     mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13173   incr(mp->in_open); push_input; index=mp->in_open;
13174   mp->mpx_name[index]=absent;
13175   start=mp->first;
13176   name=is_term; /* |terminal_input| is now |true| */
13177 }
13178
13179 @ Conversely, the variables must be downdated when such a level of input
13180 is finished.  Any associated \.{MPX} file must also be closed and popped
13181 off the file stack.
13182
13183 @c void mp_end_file_reading (MP mp) { 
13184   if ( mp->in_open>index ) {
13185     if ( (mp->mpx_name[mp->in_open]==absent)||(name<=max_spec_src) ) {
13186       mp_confusion(mp, "endinput");
13187 @:this can't happen endinput}{\quad endinput@>
13188     } else { 
13189       fclose(mp->input_file[mp->in_open]); /* close an \.{MPX} file */
13190       delete_str_ref(mp->mpx_name[mp->in_open]);
13191       decr(mp->in_open);
13192     }
13193   }
13194   mp->first=start;
13195   if ( index!=mp->in_open ) mp_confusion(mp, "endinput");
13196   if ( name>max_spec_src ) {
13197     fclose(cur_file);
13198     delete_str_ref(name);
13199     xfree(in_name); in_name=NULL;
13200     xfree(in_area); in_area=NULL;
13201   }
13202   pop_input; decr(mp->in_open);
13203 }
13204
13205 @ Here is a function that tries to resume input from an \.{MPX} file already
13206 associated with the current input file.  It returns |false| if this doesn't
13207 work.
13208
13209 @c boolean mp_begin_mpx_reading (MP mp) { 
13210   if ( mp->in_open!=index+1 ) {
13211      return false;
13212   } else { 
13213     if ( mp->mpx_name[mp->in_open]<=absent ) mp_confusion(mp, "mpx");
13214 @:this can't happen mpx}{\quad mpx@>
13215     if ( mp->first==mp->buf_size ) 
13216       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13217     push_input; index=mp->in_open;
13218     start=mp->first;
13219     name=mp->mpx_name[mp->in_open]; add_str_ref(name);
13220     @<Put an empty line in the input buffer@>;
13221     return true;
13222   }
13223 }
13224
13225 @ This procedure temporarily stops reading an \.{MPX} file.
13226
13227 @c void mp_end_mpx_reading (MP mp) { 
13228   if ( mp->in_open!=index ) mp_confusion(mp, "mpx");
13229 @:this can't happen mpx}{\quad mpx@>
13230   if ( loc<limit ) {
13231     @<Complain that we are not at the end of a line in the \.{MPX} file@>;
13232   }
13233   mp->first=start;
13234   pop_input;
13235 }
13236
13237 @ Here we enforce a restriction that simplifies the input stacks considerably.
13238 This should not inconvenience the user because \.{MPX} files are generated
13239 by an auxiliary program called \.{DVItoMP}.
13240
13241 @ @<Complain that we are not at the end of a line in the \.{MPX} file@>=
13242
13243 print_err("`mpxbreak' must be at the end of a line");
13244 help4("This file contains picture expressions for btex...etex")
13245   ("blocks.  Such files are normally generated automatically")
13246   ("but this one seems to be messed up.  I'm going to ignore")
13247   ("the rest of this line.");
13248 mp_error(mp);
13249 }
13250
13251 @ In order to keep the stack from overflowing during a long sequence of
13252 inserted `\.{show}' commands, the following routine removes completed
13253 error-inserted lines from memory.
13254
13255 @c void mp_clear_for_error_prompt (MP mp) { 
13256   while ( file_state && terminal_input &&
13257     (mp->input_ptr>0)&&(loc==limit) ) mp_end_file_reading(mp);
13258   mp_print_ln(mp); clear_terminal;
13259 }
13260
13261 @ To get \MP's whole input mechanism going, we perform the following
13262 actions.
13263
13264 @<Initialize the input routines@>=
13265 { mp->input_ptr=0; mp->max_in_stack=0;
13266   mp->in_open=0; mp->open_parens=0; mp->max_buf_stack=0;
13267   mp->param_ptr=0; mp->max_param_stack=0;
13268   mp->first=1;
13269   start=1; index=0; line=0; name=is_term;
13270   mp->mpx_name[0]=absent;
13271   mp->force_eof=false;
13272   if ( ! mp_init_terminal(mp) ) exit(EXIT_FAILURE);
13273   limit=mp->last; mp->first=mp->last+1; 
13274   /* |init_terminal| has set |loc| and |last| */
13275 }
13276
13277 @* \[29] Getting the next token.
13278 The heart of \MP's input mechanism is the |get_next| procedure, which
13279 we shall develop in the next few sections of the program. Perhaps we
13280 shouldn't actually call it the ``heart,'' however; it really acts as \MP's
13281 eyes and mouth, reading the source files and gobbling them up. And it also
13282 helps \MP\ to regurgitate stored token lists that are to be processed again.
13283
13284 The main duty of |get_next| is to input one token and to set |cur_cmd|
13285 and |cur_mod| to that token's command code and modifier. Furthermore, if
13286 the input token is a symbolic token, that token's |hash| address
13287 is stored in |cur_sym|; otherwise |cur_sym| is set to zero.
13288
13289 Underlying this simple description is a certain amount of complexity
13290 because of all the cases that need to be handled.
13291 However, the inner loop of |get_next| is reasonably short and fast.
13292
13293 @ Before getting into |get_next|, we need to consider a mechanism by which
13294 \MP\ helps keep errors from propagating too far. Whenever the program goes
13295 into a mode where it keeps calling |get_next| repeatedly until a certain
13296 condition is met, it sets |scanner_status| to some value other than |normal|.
13297 Then if an input file ends, or if an `\&{outer}' symbol appears,
13298 an appropriate error recovery will be possible.
13299
13300 The global variable |warning_info| helps in this error recovery by providing
13301 additional information. For example, |warning_info| might indicate the
13302 name of a macro whose replacement text is being scanned.
13303
13304 @d normal 0 /* |scanner_status| at ``quiet times'' */
13305 @d skipping 1 /* |scanner_status| when false conditional text is being skipped */
13306 @d flushing 2 /* |scanner_status| when junk after a statement is being ignored */
13307 @d absorbing 3 /* |scanner_status| when a \&{text} parameter is being scanned */
13308 @d var_defining 4 /* |scanner_status| when a \&{vardef} is being scanned */
13309 @d op_defining 5 /* |scanner_status| when a macro \&{def} is being scanned */
13310 @d loop_defining 6 /* |scanner_status| when a \&{for} loop is being scanned */
13311 @d tex_flushing 7 /* |scanner_status| when skipping \TeX\ material */
13312
13313 @<Glob...@>=
13314 integer scanner_status; /* are we scanning at high speed? */
13315 integer warning_info; /* if so, what else do we need to know,
13316     in case an error occurs? */
13317
13318 @ @<Initialize the input routines@>=
13319 mp->scanner_status=normal;
13320
13321 @ The following subroutine
13322 is called when an `\&{outer}' symbolic token has been scanned or
13323 when the end of a file has been reached. These two cases are distinguished
13324 by |cur_sym|, which is zero at the end of a file.
13325
13326 @c boolean mp_check_outer_validity (MP mp) {
13327   pointer p; /* points to inserted token list */
13328   if ( mp->scanner_status==normal ) {
13329     return true;
13330   } else if ( mp->scanner_status==tex_flushing ) {
13331     @<Check if the file has ended while flushing \TeX\ material and set the
13332       result value for |check_outer_validity|@>;
13333   } else { 
13334     mp->deletions_allowed=false;
13335     @<Back up an outer symbolic token so that it can be reread@>;
13336     if ( mp->scanner_status>skipping ) {
13337       @<Tell the user what has run away and try to recover@>;
13338     } else { 
13339       print_err("Incomplete if; all text was ignored after line ");
13340 @.Incomplete if...@>
13341       mp_print_int(mp, mp->warning_info);
13342       help3("A forbidden `outer' token occurred in skipped text.")
13343         ("This kind of error happens when you say `if...' and forget")
13344         ("the matching `fi'. I've inserted a `fi'; this might work.");
13345       if ( mp->cur_sym==0 ) 
13346         mp->help_line[2]="The file ended while I was skipping conditional text.";
13347       mp->cur_sym=frozen_fi; mp_ins_error(mp);
13348     }
13349     mp->deletions_allowed=true; 
13350         return false;
13351   }
13352 }
13353
13354 @ @<Check if the file has ended while flushing \TeX\ material and set...@>=
13355 if ( mp->cur_sym!=0 ) { 
13356    return true;
13357 } else { 
13358   mp->deletions_allowed=false;
13359   print_err("TeX mode didn't end; all text was ignored after line ");
13360   mp_print_int(mp, mp->warning_info);
13361   help2("The file ended while I was looking for the `etex' to")
13362     ("finish this TeX material.  I've inserted `etex' now.");
13363   mp->cur_sym = frozen_etex;
13364   mp_ins_error(mp);
13365   mp->deletions_allowed=true;
13366   return false;
13367 }
13368
13369 @ @<Back up an outer symbolic token so that it can be reread@>=
13370 if ( mp->cur_sym!=0 ) {
13371   p=mp_get_avail(mp); info(p)=mp->cur_sym;
13372   back_list(p); /* prepare to read the symbolic token again */
13373 }
13374
13375 @ @<Tell the user what has run away...@>=
13376
13377   mp_runaway(mp); /* print the definition-so-far */
13378   if ( mp->cur_sym==0 ) {
13379     print_err("File ended");
13380 @.File ended while scanning...@>
13381   } else { 
13382     print_err("Forbidden token found");
13383 @.Forbidden token found...@>
13384   }
13385   mp_print(mp, " while scanning ");
13386   help4("I suspect you have forgotten an `enddef',")
13387     ("causing me to read past where you wanted me to stop.")
13388     ("I'll try to recover; but if the error is serious,")
13389     ("you'd better type `E' or `X' now and fix your file.");
13390   switch (mp->scanner_status) {
13391     @<Complete the error message,
13392       and set |cur_sym| to a token that might help recover from the error@>
13393   } /* there are no other cases */
13394   mp_ins_error(mp);
13395 }
13396
13397 @ As we consider various kinds of errors, it is also appropriate to
13398 change the first line of the help message just given; |help_line[3]|
13399 points to the string that might be changed.
13400
13401 @<Complete the error message,...@>=
13402 case flushing: 
13403   mp_print(mp, "to the end of the statement");
13404   mp->help_line[3]="A previous error seems to have propagated,";
13405   mp->cur_sym=frozen_semicolon;
13406   break;
13407 case absorbing: 
13408   mp_print(mp, "a text argument");
13409   mp->help_line[3]="It seems that a right delimiter was left out,";
13410   if ( mp->warning_info==0 ) {
13411     mp->cur_sym=frozen_end_group;
13412   } else { 
13413     mp->cur_sym=frozen_right_delimiter;
13414     equiv(frozen_right_delimiter)=mp->warning_info;
13415   }
13416   break;
13417 case var_defining:
13418 case op_defining: 
13419   mp_print(mp, "the definition of ");
13420   if ( mp->scanner_status==op_defining ) 
13421      mp_print_text(mp->warning_info);
13422   else 
13423      mp_print_variable_name(mp, mp->warning_info);
13424   mp->cur_sym=frozen_end_def;
13425   break;
13426 case loop_defining: 
13427   mp_print(mp, "the text of a "); 
13428   mp_print_text(mp->warning_info);
13429   mp_print(mp, " loop");
13430   mp->help_line[3]="I suspect you have forgotten an `endfor',";
13431   mp->cur_sym=frozen_end_for;
13432   break;
13433
13434 @ The |runaway| procedure displays the first part of the text that occurred
13435 when \MP\ began its special |scanner_status|, if that text has been saved.
13436
13437 @<Declare the procedure called |runaway|@>=
13438 void mp_runaway (MP mp) { 
13439   if ( mp->scanner_status>flushing ) { 
13440      mp_print_nl(mp, "Runaway ");
13441          switch (mp->scanner_status) { 
13442          case absorbing: mp_print(mp, "text?"); break;
13443          case var_defining: 
13444      case op_defining: mp_print(mp,"definition?"); break;
13445      case loop_defining: mp_print(mp, "loop?"); break;
13446      } /* there are no other cases */
13447      mp_print_ln(mp); 
13448      mp_show_token_list(mp, link(hold_head),null,mp->error_line-10,0);
13449   }
13450 }
13451
13452 @ We need to mention a procedure that may be called by |get_next|.
13453
13454 @<Declarations@>= 
13455 void mp_firm_up_the_line (MP mp);
13456
13457 @ And now we're ready to take the plunge into |get_next| itself.
13458 Note that the behavior depends on the |scanner_status| because percent signs
13459 and double quotes need to be passed over when skipping TeX material.
13460
13461 @c 
13462 void mp_get_next (MP mp) {
13463   /* sets |cur_cmd|, |cur_mod|, |cur_sym| to next token */
13464 @^inner loop@>
13465   /*restart*/ /* go here to get the next input token */
13466   /*exit*/ /* go here when the next input token has been got */
13467   /*|common_ending|*/ /* go here to finish getting a symbolic token */
13468   /*found*/ /* go here when the end of a symbolic token has been found */
13469   /*switch*/ /* go here to branch on the class of an input character */
13470   /*|start_numeric_token|,|start_decimal_token|,|fin_numeric_token|,|done|*/
13471     /* go here at crucial stages when scanning a number */
13472   int k; /* an index into |buffer| */
13473   ASCII_code c; /* the current character in the buffer */
13474   ASCII_code class; /* its class number */
13475   integer n,f; /* registers for decimal-to-binary conversion */
13476 RESTART: 
13477   mp->cur_sym=0;
13478   if ( file_state ) {
13479     @<Input from external file; |goto restart| if no input found,
13480     or |return| if a non-symbolic token is found@>;
13481   } else {
13482     @<Input from token list; |goto restart| if end of list or
13483       if a parameter needs to be expanded,
13484       or |return| if a non-symbolic token is found@>;
13485   }
13486 COMMON_ENDING: 
13487   @<Finish getting the symbolic token in |cur_sym|;
13488    |goto restart| if it is illegal@>;
13489 }
13490
13491 @ When a symbolic token is declared to be `\&{outer}', its command code
13492 is increased by |outer_tag|.
13493 @^inner loop@>
13494
13495 @<Finish getting the symbolic token in |cur_sym|...@>=
13496 mp->cur_cmd=eq_type(mp->cur_sym); mp->cur_mod=equiv(mp->cur_sym);
13497 if ( mp->cur_cmd>=outer_tag ) {
13498   if ( mp_check_outer_validity(mp) ) 
13499     mp->cur_cmd=mp->cur_cmd-outer_tag;
13500   else 
13501     goto RESTART;
13502 }
13503
13504 @ A percent sign appears in |buffer[limit]|; this makes it unnecessary
13505 to have a special test for end-of-line.
13506 @^inner loop@>
13507
13508 @<Input from external file;...@>=
13509
13510 SWITCH: 
13511   c=mp->buffer[loc]; incr(loc); class=mp->char_class[c];
13512   switch (class) {
13513   case digit_class: goto START_NUMERIC_TOKEN; break;
13514   case period_class: 
13515     class=mp->char_class[mp->buffer[loc]];
13516     if ( class>period_class ) {
13517       goto SWITCH;
13518     } else if ( class<period_class ) { /* |class=digit_class| */
13519       n=0; goto START_DECIMAL_TOKEN;
13520     }
13521 @:. }{\..\ token@>
13522     break;
13523   case space_class: goto SWITCH; break;
13524   case percent_class: 
13525     if ( mp->scanner_status==tex_flushing ) {
13526       if ( loc<limit ) goto SWITCH;
13527     }
13528     @<Move to next line of file, or |goto restart| if there is no next line@>;
13529     check_interrupt;
13530     goto SWITCH;
13531     break;
13532   case string_class: 
13533     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13534     else @<Get a string token and |return|@>;
13535     break;
13536   case isolated_classes: 
13537     k=loc-1; goto FOUND; break;
13538   case invalid_class: 
13539     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13540     else @<Decry the invalid character and |goto restart|@>;
13541     break;
13542   default: break; /* letters, etc. */
13543   }
13544   k=loc-1;
13545   while ( mp->char_class[mp->buffer[loc]]==class ) incr(loc);
13546   goto FOUND;
13547 START_NUMERIC_TOKEN:
13548   @<Get the integer part |n| of a numeric token;
13549     set |f:=0| and |goto fin_numeric_token| if there is no decimal point@>;
13550 START_DECIMAL_TOKEN:
13551   @<Get the fraction part |f| of a numeric token@>;
13552 FIN_NUMERIC_TOKEN:
13553   @<Pack the numeric and fraction parts of a numeric token
13554     and |return|@>;
13555 FOUND: 
13556   mp->cur_sym=mp_id_lookup(mp, k,loc-k);
13557 }
13558
13559 @ We go to |restart| instead of to |SWITCH|, because |state| might equal
13560 |token_list| after the error has been dealt with
13561 (cf.\ |clear_for_error_prompt|).
13562
13563 @<Decry the invalid...@>=
13564
13565   print_err("Text line contains an invalid character");
13566 @.Text line contains...@>
13567   help2("A funny symbol that I can\'t read has just been input.")
13568     ("Continue, and I'll forget that it ever happened.");
13569   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13570   goto RESTART;
13571 }
13572
13573 @ @<Get a string token and |return|@>=
13574
13575   if ( mp->buffer[loc]=='"' ) {
13576     mp->cur_mod=rts("");
13577   } else { 
13578     k=loc; mp->buffer[limit+1]='"';
13579     do {  
13580      incr(loc);
13581     } while (mp->buffer[loc]!='"');
13582     if ( loc>limit ) {
13583       @<Decry the missing string delimiter and |goto restart|@>;
13584     }
13585     if ( loc==k+1 ) {
13586       mp->cur_mod=mp->buffer[k];
13587     } else { 
13588       str_room(loc-k);
13589       do {  
13590         append_char(mp->buffer[k]); incr(k);
13591       } while (k!=loc);
13592       mp->cur_mod=mp_make_string(mp);
13593     }
13594   }
13595   incr(loc); mp->cur_cmd=string_token; 
13596   return;
13597 }
13598
13599 @ We go to |restart| after this error message, not to |SWITCH|,
13600 because the |clear_for_error_prompt| routine might have reinstated
13601 |token_state| after |error| has finished.
13602
13603 @<Decry the missing string delimiter and |goto restart|@>=
13604
13605   loc=limit; /* the next character to be read on this line will be |"%"| */
13606   print_err("Incomplete string token has been flushed");
13607 @.Incomplete string token...@>
13608   help3("Strings should finish on the same line as they began.")
13609     ("I've deleted the partial string; you might want to")
13610     ("insert another by typing, e.g., `I\"new string\"'.");
13611   mp->deletions_allowed=false; mp_error(mp);
13612   mp->deletions_allowed=true; 
13613   goto RESTART;
13614 }
13615
13616 @ @<Get the integer part |n| of a numeric token...@>=
13617 n=c-'0';
13618 while ( mp->char_class[mp->buffer[loc]]==digit_class ) {
13619   if ( n<32768 ) n=10*n+mp->buffer[loc]-'0';
13620   incr(loc);
13621 }
13622 if ( mp->buffer[loc]=='.' ) 
13623   if ( mp->char_class[mp->buffer[loc+1]]==digit_class ) 
13624     goto DONE;
13625 f=0; 
13626 goto FIN_NUMERIC_TOKEN;
13627 DONE: incr(loc)
13628
13629 @ @<Get the fraction part |f| of a numeric token@>=
13630 k=0;
13631 do { 
13632   if ( k<17 ) { /* digits for |k>=17| cannot affect the result */
13633     mp->dig[k]=mp->buffer[loc]-'0'; incr(k);
13634   }
13635   incr(loc);
13636 } while (mp->char_class[mp->buffer[loc]]==digit_class);
13637 f=mp_round_decimals(mp, k);
13638 if ( f==unity ) {
13639   incr(n); f=0;
13640 }
13641
13642 @ @<Pack the numeric and fraction parts of a numeric token and |return|@>=
13643 if ( n<32768 ) {
13644   @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>;
13645 } else if ( mp->scanner_status!=tex_flushing ) {
13646   print_err("Enormous number has been reduced");
13647 @.Enormous number...@>
13648   help2("I can\'t handle numbers bigger than 32767.99998;")
13649     ("so I've changed your constant to that maximum amount.");
13650   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13651   mp->cur_mod=el_gordo;
13652 }
13653 mp->cur_cmd=numeric_token; return
13654
13655 @ @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>=
13656
13657   mp->cur_mod=n*unity+f;
13658   if ( mp->cur_mod>=fraction_one ) {
13659     if ( (mp->internal[warning_check]>0) &&
13660          (mp->scanner_status!=tex_flushing) ) {
13661       print_err("Number is too large (");
13662       mp_print_scaled(mp, mp->cur_mod);
13663       mp_print_char(mp, ')');
13664       help3("It is at least 4096. Continue and I'll try to cope")
13665       ("with that big value; but it might be dangerous.")
13666       ("(Set warningcheck:=0 to suppress this message.)");
13667       mp_error(mp);
13668     }
13669   }
13670 }
13671
13672 @ Let's consider now what happens when |get_next| is looking at a token list.
13673 @^inner loop@>
13674
13675 @<Input from token list;...@>=
13676 if ( loc>=mp->hi_mem_min ) { /* one-word token */
13677   mp->cur_sym=info(loc); loc=link(loc); /* move to next */
13678   if ( mp->cur_sym>=expr_base ) {
13679     if ( mp->cur_sym>=suffix_base ) {
13680       @<Insert a suffix or text parameter and |goto restart|@>;
13681     } else { 
13682       mp->cur_cmd=capsule_token;
13683       mp->cur_mod=mp->param_stack[param_start+mp->cur_sym-(expr_base)];
13684       mp->cur_sym=0; return;
13685     }
13686   }
13687 } else if ( loc>null ) {
13688   @<Get a stored numeric or string or capsule token and |return|@>
13689 } else { /* we are done with this token list */
13690   mp_end_token_list(mp); goto RESTART; /* resume previous level */
13691 }
13692
13693 @ @<Insert a suffix or text parameter...@>=
13694
13695   if ( mp->cur_sym>=text_base ) mp->cur_sym=mp->cur_sym-mp->param_size;
13696   /* |param_size=text_base-suffix_base| */
13697   mp_begin_token_list(mp,
13698                       mp->param_stack[param_start+mp->cur_sym-(suffix_base)],
13699                       parameter);
13700   goto RESTART;
13701 }
13702
13703 @ @<Get a stored numeric or string or capsule token...@>=
13704
13705   if ( name_type(loc)==mp_token ) {
13706     mp->cur_mod=value(loc);
13707     if ( type(loc)==mp_known ) {
13708       mp->cur_cmd=numeric_token;
13709     } else { 
13710       mp->cur_cmd=string_token; add_str_ref(mp->cur_mod);
13711     }
13712   } else { 
13713     mp->cur_mod=loc; mp->cur_cmd=capsule_token;
13714   };
13715   loc=link(loc); return;
13716 }
13717
13718 @ All of the easy branches of |get_next| have now been taken care of.
13719 There is one more branch.
13720
13721 @<Move to next line of file, or |goto restart|...@>=
13722 if ( name>max_spec_src ) {
13723   @<Read next line of file into |buffer|, or
13724     |goto restart| if the file has ended@>;
13725 } else { 
13726   if ( mp->input_ptr>0 ) {
13727      /* text was inserted during error recovery or by \&{scantokens} */
13728     mp_end_file_reading(mp); goto RESTART; /* resume previous level */
13729   }
13730   if ( mp->selector<log_only || mp->selector>=write_file) mp_open_log_file(mp);
13731   if ( mp->interaction>mp_nonstop_mode ) {
13732     if ( limit==start ) /* previous line was empty */
13733       mp_print_nl(mp, "(Please type a command or say `end')");
13734 @.Please type...@>
13735     mp_print_ln(mp); mp->first=start;
13736     prompt_input("*"); /* input on-line into |buffer| */
13737 @.*\relax@>
13738     limit=mp->last; mp->buffer[limit]='%';
13739     mp->first=limit+1; loc=start;
13740   } else {
13741     mp_fatal_error(mp, "*** (job aborted, no legal end found)");
13742 @.job aborted@>
13743     /* nonstop mode, which is intended for overnight batch processing,
13744     never waits for on-line input */
13745   }
13746 }
13747
13748 @ The global variable |force_eof| is normally |false|; it is set |true|
13749 by an \&{endinput} command.
13750
13751 @<Glob...@>=
13752 boolean force_eof; /* should the next \&{input} be aborted early? */
13753
13754 @ We must decrement |loc| in order to leave the buffer in a valid state
13755 when an error condition causes us to |goto restart| without calling
13756 |end_file_reading|.
13757
13758 @<Read next line of file into |buffer|, or
13759   |goto restart| if the file has ended@>=
13760
13761   incr(line); mp->first=start;
13762   if ( ! mp->force_eof ) {
13763     if ( mp_input_ln(mp, cur_file,true) ) /* not end of file */
13764       mp_firm_up_the_line(mp); /* this sets |limit| */
13765     else 
13766       mp->force_eof=true;
13767   };
13768   if ( mp->force_eof ) {
13769     mp->force_eof=false;
13770     decr(loc);
13771     if ( mpx_reading ) {
13772       @<Complain that the \.{MPX} file ended unexpectly; then set
13773         |cur_sym:=frozen_mpx_break| and |goto comon_ending|@>;
13774     } else { 
13775       mp_print_char(mp, ')'); decr(mp->open_parens);
13776       update_terminal; /* show user that file has been read */
13777       mp_end_file_reading(mp); /* resume previous level */
13778       if ( mp_check_outer_validity(mp) ) goto  RESTART;  
13779       else goto RESTART;
13780     }
13781   }
13782   mp->buffer[limit]='%'; mp->first=limit+1; loc=start; /* ready to read */
13783 }
13784
13785 @ We should never actually come to the end of an \.{MPX} file because such
13786 files should have an \&{mpxbreak} after the translation of the last
13787 \&{btex}$\,\ldots\,$\&{etex} block.
13788
13789 @<Complain that the \.{MPX} file ended unexpectly; then set...@>=
13790
13791   mp->mpx_name[index]=finished;
13792   print_err("mpx file ended unexpectedly");
13793   help4("The file had too few picture expressions for btex...etex")
13794     ("blocks.  Such files are normally generated automatically")
13795     ("but this one got messed up.  You might want to insert a")
13796     ("picture expression now.");
13797   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13798   mp->cur_sym=frozen_mpx_break; goto COMMON_ENDING;
13799 }
13800
13801 @ Sometimes we want to make it look as though we have just read a blank line
13802 without really doing so.
13803
13804 @<Put an empty line in the input buffer@>=
13805 mp->last=mp->first; limit=mp->last; /* simulate |input_ln| and |firm_up_the_line| */
13806 mp->buffer[limit]='%'; mp->first=limit+1; loc=start
13807
13808 @ If the user has set the |pausing| parameter to some positive value,
13809 and if nonstop mode has not been selected, each line of input is displayed
13810 on the terminal and the transcript file, followed by `\.{=>}'.
13811 \MP\ waits for a response. If the response is null (i.e., if nothing is
13812 typed except perhaps a few blank spaces), the original
13813 line is accepted as it stands; otherwise the line typed is
13814 used instead of the line in the file.
13815
13816 @c void mp_firm_up_the_line (MP mp) {
13817   size_t k; /* an index into |buffer| */
13818   limit=mp->last;
13819   if ( mp->internal[pausing]>0 ) if ( mp->interaction>mp_nonstop_mode ) {
13820     wake_up_terminal; mp_print_ln(mp);
13821     if ( start<limit ) {
13822       for (k=(size_t)start;k<=(size_t)(limit-1);k++) {
13823         mp_print_str(mp, mp->buffer[k]);
13824       } 
13825     }
13826     mp->first=limit; prompt_input("=>"); /* wait for user response */
13827 @.=>@>
13828     if ( mp->last>mp->first ) {
13829       for (k=mp->first;k<=mp->last-1;k++) { /* move line down in buffer */
13830         mp->buffer[k+start-mp->first]=mp->buffer[k];
13831       }
13832       limit=start+mp->last-mp->first;
13833     }
13834   }
13835 }
13836
13837 @* \[30] Dealing with \TeX\ material.
13838 The \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}$\,\ldots\,$\&{etex}
13839 features need to be implemented at a low level in the scanning process
13840 so that \MP\ can stay in synch with the a preprocessor that treats
13841 blocks of \TeX\ material as they occur in the input file without trying
13842 to expand \MP\ macros.  Thus we need a special version of |get_next|
13843 that does not expand macros and such but does handle \&{btex},
13844 \&{verbatimtex}, etc.
13845
13846 The special version of |get_next| is called |get_t_next|.  It works by flushing
13847 \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}\allowbreak
13848 $\,\ldots\,$\&{etex} blocks, switching to the \.{MPX} file when it sees
13849 \&{btex}, and switching back when it sees \&{mpxbreak}.
13850
13851 @d btex_code 0
13852 @d verbatim_code 1
13853
13854 @ @<Put each...@>=
13855 mp_primitive(mp, "btex",start_tex,btex_code);
13856 @:btex_}{\&{btex} primitive@>
13857 mp_primitive(mp, "verbatimtex",start_tex,verbatim_code);
13858 @:verbatimtex_}{\&{verbatimtex} primitive@>
13859 mp_primitive(mp, "etex",etex_marker,0); mp->eqtb[frozen_etex]=mp->eqtb[mp->cur_sym];
13860 @:etex_}{\&{etex} primitive@>
13861 mp_primitive(mp, "mpxbreak",mpx_break,0); mp->eqtb[frozen_mpx_break]=mp->eqtb[mp->cur_sym];
13862 @:mpx_break_}{\&{mpxbreak} primitive@>
13863
13864 @ @<Cases of |print_cmd...@>=
13865 case start_tex: if ( m==btex_code ) mp_print(mp, "btex");
13866   else mp_print(mp, "verbatimtex"); break;
13867 case etex_marker: mp_print(mp, "etex"); break;
13868 case mpx_break: mp_print(mp, "mpxbreak"); break;
13869
13870 @ Actually, |get_t_next| is a macro that avoids procedure overhead except
13871 in the unusual case where \&{btex}, \&{verbatimtex}, \&{etex}, or \&{mpxbreak}
13872 is encountered.
13873
13874 @d get_t_next {mp_get_next(mp); if ( mp->cur_cmd<=max_pre_command ) mp_t_next(mp); }
13875
13876 @<Declarations@>=
13877 void mp_start_mpx_input (MP mp);
13878
13879 @ @c 
13880 void mp_t_next (MP mp) {
13881   int old_status; /* saves the |scanner_status| */
13882   integer old_info; /* saves the |warning_info| */
13883   while ( mp->cur_cmd<=max_pre_command ) {
13884     if ( mp->cur_cmd==mpx_break ) {
13885       if ( ! file_state || (mp->mpx_name[index]==absent) ) {
13886         @<Complain about a misplaced \&{mpxbreak}@>;
13887       } else { 
13888         mp_end_mpx_reading(mp); 
13889         goto TEX_FLUSH;
13890       }
13891     } else if ( mp->cur_cmd==start_tex ) {
13892       if ( token_state || (name<=max_spec_src) ) {
13893         @<Complain that we are not reading a file@>;
13894       } else if ( mpx_reading ) {
13895         @<Complain that \.{MPX} files cannot contain \TeX\ material@>;
13896       } else if ( (mp->cur_mod!=verbatim_code)&&
13897                   (mp->mpx_name[index]!=finished) ) {
13898         if ( ! mp_begin_mpx_reading(mp) ) mp_start_mpx_input(mp);
13899       } else {
13900         goto TEX_FLUSH;
13901       }
13902     } else {
13903        @<Complain about a misplaced \&{etex}@>;
13904     }
13905     goto COMMON_ENDING;
13906   TEX_FLUSH: 
13907     @<Flush the \TeX\ material@>;
13908   COMMON_ENDING: 
13909     mp_get_next(mp);
13910   }
13911 }
13912
13913 @ We could be in the middle of an operation such as skipping false conditional
13914 text when \TeX\ material is encountered, so we must be careful to save the
13915 |scanner_status|.
13916
13917 @<Flush the \TeX\ material@>=
13918 old_status=mp->scanner_status;
13919 old_info=mp->warning_info;
13920 mp->scanner_status=tex_flushing;
13921 mp->warning_info=line;
13922 do {  mp_get_next(mp); } while (mp->cur_cmd!=etex_marker);
13923 mp->scanner_status=old_status;
13924 mp->warning_info=old_info
13925
13926 @ @<Complain that \.{MPX} files cannot contain \TeX\ material@>=
13927 { print_err("An mpx file cannot contain btex or verbatimtex blocks");
13928 help4("This file contains picture expressions for btex...etex")
13929   ("blocks.  Such files are normally generated automatically")
13930   ("but this one seems to be messed up.  I'll just keep going")
13931   ("and hope for the best.");
13932 mp_error(mp);
13933 }
13934
13935 @ @<Complain that we are not reading a file@>=
13936 { print_err("You can only use `btex' or `verbatimtex' in a file");
13937 help3("I'll have to ignore this preprocessor command because it")
13938   ("only works when there is a file to preprocess.  You might")
13939   ("want to delete everything up to the next `etex`.");
13940 mp_error(mp);
13941 }
13942
13943 @ @<Complain about a misplaced \&{mpxbreak}@>=
13944 { print_err("Misplaced mpxbreak");
13945 help2("I'll ignore this preprocessor command because it")
13946   ("doesn't belong here");
13947 mp_error(mp);
13948 }
13949
13950 @ @<Complain about a misplaced \&{etex}@>=
13951 { print_err("Extra etex will be ignored");
13952 help1("There is no btex or verbatimtex for this to match");
13953 mp_error(mp);
13954 }
13955
13956 @* \[31] Scanning macro definitions.
13957 \MP\ has a variety of ways to tuck tokens away into token lists for later
13958 use: Macros can be defined with \&{def}, \&{vardef}, \&{primarydef}, etc.;
13959 repeatable code can be defined with \&{for}, \&{forever}, \&{forsuffixes}.
13960 All such operations are handled by the routines in this part of the program.
13961
13962 The modifier part of each command code is zero for the ``ending delimiters''
13963 like \&{enddef} and \&{endfor}.
13964
13965 @d start_def 1 /* command modifier for \&{def} */
13966 @d var_def 2 /* command modifier for \&{vardef} */
13967 @d end_def 0 /* command modifier for \&{enddef} */
13968 @d start_forever 1 /* command modifier for \&{forever} */
13969 @d end_for 0 /* command modifier for \&{endfor} */
13970
13971 @<Put each...@>=
13972 mp_primitive(mp, "def",macro_def,start_def);
13973 @:def_}{\&{def} primitive@>
13974 mp_primitive(mp, "vardef",macro_def,var_def);
13975 @:var_def_}{\&{vardef} primitive@>
13976 mp_primitive(mp, "primarydef",macro_def,secondary_primary_macro);
13977 @:primary_def_}{\&{primarydef} primitive@>
13978 mp_primitive(mp, "secondarydef",macro_def,tertiary_secondary_macro);
13979 @:secondary_def_}{\&{secondarydef} primitive@>
13980 mp_primitive(mp, "tertiarydef",macro_def,expression_tertiary_macro);
13981 @:tertiary_def_}{\&{tertiarydef} primitive@>
13982 mp_primitive(mp, "enddef",macro_def,end_def); mp->eqtb[frozen_end_def]=mp->eqtb[mp->cur_sym];
13983 @:end_def_}{\&{enddef} primitive@>
13984 @#
13985 mp_primitive(mp, "for",iteration,expr_base);
13986 @:for_}{\&{for} primitive@>
13987 mp_primitive(mp, "forsuffixes",iteration,suffix_base);
13988 @:for_suffixes_}{\&{forsuffixes} primitive@>
13989 mp_primitive(mp, "forever",iteration,start_forever);
13990 @:forever_}{\&{forever} primitive@>
13991 mp_primitive(mp, "endfor",iteration,end_for); mp->eqtb[frozen_end_for]=mp->eqtb[mp->cur_sym];
13992 @:end_for_}{\&{endfor} primitive@>
13993
13994 @ @<Cases of |print_cmd...@>=
13995 case macro_def:
13996   if ( m<=var_def ) {
13997     if ( m==start_def ) mp_print(mp, "def");
13998     else if ( m<start_def ) mp_print(mp, "enddef");
13999     else mp_print(mp, "vardef");
14000   } else if ( m==secondary_primary_macro ) { 
14001     mp_print(mp, "primarydef");
14002   } else if ( m==tertiary_secondary_macro ) { 
14003     mp_print(mp, "secondarydef");
14004   } else { 
14005     mp_print(mp, "tertiarydef");
14006   }
14007   break;
14008 case iteration: 
14009   if ( m<=start_forever ) {
14010     if ( m==start_forever ) mp_print(mp, "forever"); 
14011     else mp_print(mp, "endfor");
14012   } else if ( m==expr_base ) {
14013     mp_print(mp, "for"); 
14014   } else { 
14015     mp_print(mp, "forsuffixes");
14016   }
14017   break;
14018
14019 @ Different macro-absorbing operations have different syntaxes, but they
14020 also have a lot in common. There is a list of special symbols that are to
14021 be replaced by parameter tokens; there is a special command code that
14022 ends the definition; the quotation conventions are identical.  Therefore
14023 it makes sense to have most of the work done by a single subroutine. That
14024 subroutine is called |scan_toks|.
14025
14026 The first parameter to |scan_toks| is the command code that will
14027 terminate scanning (either |macro_def|, |loop_repeat|, or |iteration|).
14028
14029 The second parameter, |subst_list|, points to a (possibly empty) list
14030 of two-word nodes whose |info| and |value| fields specify symbol tokens
14031 before and after replacement. The list will be returned to free storage
14032 by |scan_toks|.
14033
14034 The third parameter is simply appended to the token list that is built.
14035 And the final parameter tells how many of the special operations
14036 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#} are to be replaced by suffix parameters.
14037 When such parameters are present, they are called \.{(SUFFIX0)},
14038 \.{(SUFFIX1)}, and \.{(SUFFIX2)}.
14039
14040 @c pointer mp_scan_toks (MP mp,command_code terminator, pointer 
14041   subst_list, pointer tail_end, small_number suffix_count) {
14042   pointer p; /* tail of the token list being built */
14043   pointer q; /* temporary for link management */
14044   integer balance; /* left delimiters minus right delimiters */
14045   p=hold_head; balance=1; link(hold_head)=null;
14046   while (1) { 
14047     get_t_next;
14048     if ( mp->cur_sym>0 ) {
14049       @<Substitute for |cur_sym|, if it's on the |subst_list|@>;
14050       if ( mp->cur_cmd==terminator ) {
14051         @<Adjust the balance; |break| if it's zero@>;
14052       } else if ( mp->cur_cmd==macro_special ) {
14053         @<Handle quoted symbols, \.{\#\AT!}, \.{\AT!}, or \.{\AT!\#}@>;
14054       }
14055     }
14056     link(p)=mp_cur_tok(mp); p=link(p);
14057   }
14058   link(p)=tail_end; mp_flush_node_list(mp, subst_list);
14059   return link(hold_head);
14060 }
14061
14062 @ @<Substitute for |cur_sym|...@>=
14063
14064   q=subst_list;
14065   while ( q!=null ) {
14066     if ( info(q)==mp->cur_sym ) {
14067       mp->cur_sym=value(q); mp->cur_cmd=relax; break;
14068     }
14069     q=link(q);
14070   }
14071 }
14072
14073 @ @<Adjust the balance; |break| if it's zero@>=
14074 if ( mp->cur_mod>0 ) {
14075   incr(balance);
14076 } else { 
14077   decr(balance);
14078   if ( balance==0 )
14079     break;
14080 }
14081
14082 @ Four commands are intended to be used only within macro texts: \&{quote},
14083 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#}. They are variants of a single command
14084 code called |macro_special|.
14085
14086 @d quote 0 /* |macro_special| modifier for \&{quote} */
14087 @d macro_prefix 1 /* |macro_special| modifier for \.{\#\AT!} */
14088 @d macro_at 2 /* |macro_special| modifier for \.{\AT!} */
14089 @d macro_suffix 3 /* |macro_special| modifier for \.{\AT!\#} */
14090
14091 @<Put each...@>=
14092 mp_primitive(mp, "quote",macro_special,quote);
14093 @:quote_}{\&{quote} primitive@>
14094 mp_primitive(mp, "#@@",macro_special,macro_prefix);
14095 @:]]]\#\AT!_}{\.{\#\AT!} primitive@>
14096 mp_primitive(mp, "@@",macro_special,macro_at);
14097 @:]]]\AT!_}{\.{\AT!} primitive@>
14098 mp_primitive(mp, "@@#",macro_special,macro_suffix);
14099 @:]]]\AT!\#_}{\.{\AT!\#} primitive@>
14100
14101 @ @<Cases of |print_cmd...@>=
14102 case macro_special: 
14103   switch (m) {
14104   case macro_prefix: mp_print(mp, "#@@"); break;
14105   case macro_at: mp_print_char(mp, '@@'); break;
14106   case macro_suffix: mp_print(mp, "@@#"); break;
14107   default: mp_print(mp, "quote"); break;
14108   }
14109   break;
14110
14111 @ @<Handle quoted...@>=
14112
14113   if ( mp->cur_mod==quote ) { get_t_next; } 
14114   else if ( mp->cur_mod<=suffix_count ) 
14115     mp->cur_sym=suffix_base-1+mp->cur_mod;
14116 }
14117
14118 @ Here is a routine that's used whenever a token will be redefined. If
14119 the user's token is unredefinable, the `|frozen_inaccessible|' token is
14120 substituted; the latter is redefinable but essentially impossible to use,
14121 hence \MP's tables won't get fouled up.
14122
14123 @c void mp_get_symbol (MP mp) { /* sets |cur_sym| to a safe symbol */
14124 RESTART: 
14125   get_t_next;
14126   if ( (mp->cur_sym==0)||(mp->cur_sym>frozen_inaccessible) ) {
14127     print_err("Missing symbolic token inserted");
14128 @.Missing symbolic token...@>
14129     help3("Sorry: You can\'t redefine a number, string, or expr.")
14130       ("I've inserted an inaccessible symbol so that your")
14131       ("definition will be completed without mixing me up too badly.");
14132     if ( mp->cur_sym>0 )
14133       mp->help_line[2]="Sorry: You can\'t redefine my error-recovery tokens.";
14134     else if ( mp->cur_cmd==string_token ) 
14135       delete_str_ref(mp->cur_mod);
14136     mp->cur_sym=frozen_inaccessible; mp_ins_error(mp); goto RESTART;
14137   }
14138 }
14139
14140 @ Before we actually redefine a symbolic token, we need to clear away its
14141 former value, if it was a variable. The following stronger version of
14142 |get_symbol| does that.
14143
14144 @c void mp_get_clear_symbol (MP mp) { 
14145   mp_get_symbol(mp); mp_clear_symbol(mp, mp->cur_sym,false);
14146 }
14147
14148 @ Here's another little subroutine; it checks that an equals sign
14149 or assignment sign comes along at the proper place in a macro definition.
14150
14151 @c void mp_check_equals (MP mp) { 
14152   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
14153      mp_missing_err(mp, "=");
14154 @.Missing `='@>
14155     help5("The next thing in this `def' should have been `=',")
14156       ("because I've already looked at the definition heading.")
14157       ("But don't worry; I'll pretend that an equals sign")
14158       ("was present. Everything from here to `enddef'")
14159       ("will be the replacement text of this macro.");
14160     mp_back_error(mp);
14161   }
14162 }
14163
14164 @ A \&{primarydef}, \&{secondarydef}, or \&{tertiarydef} is rather easily
14165 handled now that we have |scan_toks|.  In this case there are
14166 two parameters, which will be \.{EXPR0} and \.{EXPR1} (i.e.,
14167 |expr_base| and |expr_base+1|).
14168
14169 @c void mp_make_op_def (MP mp) {
14170   command_code m; /* the type of definition */
14171   pointer p,q,r; /* for list manipulation */
14172   m=mp->cur_mod;
14173   mp_get_symbol(mp); q=mp_get_node(mp, token_node_size);
14174   info(q)=mp->cur_sym; value(q)=expr_base;
14175   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym;
14176   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
14177   info(p)=mp->cur_sym; value(p)=expr_base+1; link(p)=q;
14178   get_t_next; mp_check_equals(mp);
14179   mp->scanner_status=op_defining; q=mp_get_avail(mp); ref_count(q)=null;
14180   r=mp_get_avail(mp); link(q)=r; info(r)=general_macro;
14181   link(r)=mp_scan_toks(mp, macro_def,p,null,0);
14182   mp->scanner_status=normal; eq_type(mp->warning_info)=m;
14183   equiv(mp->warning_info)=q; mp_get_x_next(mp);
14184 }
14185
14186 @ Parameters to macros are introduced by the keywords \&{expr},
14187 \&{suffix}, \&{text}, \&{primary}, \&{secondary}, and \&{tertiary}.
14188
14189 @<Put each...@>=
14190 mp_primitive(mp, "expr",param_type,expr_base);
14191 @:expr_}{\&{expr} primitive@>
14192 mp_primitive(mp, "suffix",param_type,suffix_base);
14193 @:suffix_}{\&{suffix} primitive@>
14194 mp_primitive(mp, "text",param_type,text_base);
14195 @:text_}{\&{text} primitive@>
14196 mp_primitive(mp, "primary",param_type,primary_macro);
14197 @:primary_}{\&{primary} primitive@>
14198 mp_primitive(mp, "secondary",param_type,secondary_macro);
14199 @:secondary_}{\&{secondary} primitive@>
14200 mp_primitive(mp, "tertiary",param_type,tertiary_macro);
14201 @:tertiary_}{\&{tertiary} primitive@>
14202
14203 @ @<Cases of |print_cmd...@>=
14204 case param_type:
14205   if ( m>=expr_base ) {
14206     if ( m==expr_base ) mp_print(mp, "expr");
14207     else if ( m==suffix_base ) mp_print(mp, "suffix");
14208     else mp_print(mp, "text");
14209   } else if ( m<secondary_macro ) {
14210     mp_print(mp, "primary");
14211   } else if ( m==secondary_macro ) {
14212     mp_print(mp, "secondary");
14213   } else {
14214     mp_print(mp, "tertiary");
14215   }
14216   break;
14217
14218 @ Let's turn next to the more complex processing associated with \&{def}
14219 and \&{vardef}. When the following procedure is called, |cur_mod|
14220 should be either |start_def| or |var_def|.
14221
14222 @c @<Declare the procedure called |check_delimiter|@>;
14223 @<Declare the function called |scan_declared_variable|@>;
14224 void mp_scan_def (MP mp) {
14225   int m; /* the type of definition */
14226   int n; /* the number of special suffix parameters */
14227   int k; /* the total number of parameters */
14228   int c; /* the kind of macro we're defining */
14229   pointer r; /* parameter-substitution list */
14230   pointer q; /* tail of the macro token list */
14231   pointer p; /* temporary storage */
14232   halfword base; /* |expr_base|, |suffix_base|, or |text_base| */
14233   pointer l_delim,r_delim; /* matching delimiters */
14234   m=mp->cur_mod; c=general_macro; link(hold_head)=null;
14235   q=mp_get_avail(mp); ref_count(q)=null; r=null;
14236   @<Scan the token or variable to be defined;
14237     set |n|, |scanner_status|, and |warning_info|@>;
14238   k=n;
14239   if ( mp->cur_cmd==left_delimiter ) {
14240     @<Absorb delimited parameters, putting them into lists |q| and |r|@>;
14241   }
14242   if ( mp->cur_cmd==param_type ) {
14243     @<Absorb undelimited parameters, putting them into list |r|@>;
14244   }
14245   mp_check_equals(mp);
14246   p=mp_get_avail(mp); info(p)=c; link(q)=p;
14247   @<Attach the replacement text to the tail of node |p|@>;
14248   mp->scanner_status=normal; mp_get_x_next(mp);
14249 }
14250
14251 @ We don't put `|frozen_end_group|' into the replacement text of
14252 a \&{vardef}, because the user may want to redefine `\.{endgroup}'.
14253
14254 @<Attach the replacement text to the tail of node |p|@>=
14255 if ( m==start_def ) {
14256   link(p)=mp_scan_toks(mp, macro_def,r,null,n);
14257 } else { 
14258   q=mp_get_avail(mp); info(q)=mp->bg_loc; link(p)=q;
14259   p=mp_get_avail(mp); info(p)=mp->eg_loc;
14260   link(q)=mp_scan_toks(mp, macro_def,r,p,n);
14261 }
14262 if ( mp->warning_info==bad_vardef ) 
14263   mp_flush_token_list(mp, value(bad_vardef))
14264
14265 @ @<Glob...@>=
14266 int bg_loc;
14267 int eg_loc; /* hash addresses of `\.{begingroup}' and `\.{endgroup}' */
14268
14269 @ @<Scan the token or variable to be defined;...@>=
14270 if ( m==start_def ) {
14271   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym; get_t_next;
14272   mp->scanner_status=op_defining; n=0;
14273   eq_type(mp->warning_info)=defined_macro; equiv(mp->warning_info)=q;
14274 } else { 
14275   p=mp_scan_declared_variable(mp);
14276   mp_flush_variable(mp, equiv(info(p)),link(p),true);
14277   mp->warning_info=mp_find_variable(mp, p); mp_flush_list(mp, p);
14278   if ( mp->warning_info==null ) @<Change to `\.{a bad variable}'@>;
14279   mp->scanner_status=var_defining; n=2;
14280   if ( mp->cur_cmd==macro_special ) if ( mp->cur_mod==macro_suffix ) {/* \.{\AT!\#} */
14281     n=3; get_t_next;
14282   }
14283   type(mp->warning_info)=mp_unsuffixed_macro-2+n; value(mp->warning_info)=q;
14284 } /* |mp_suffixed_macro=mp_unsuffixed_macro+1| */
14285
14286 @ @<Change to `\.{a bad variable}'@>=
14287
14288   print_err("This variable already starts with a macro");
14289 @.This variable already...@>
14290   help2("After `vardef a' you can\'t say `vardef a.b'.")
14291     ("So I'll have to discard this definition.");
14292   mp_error(mp); mp->warning_info=bad_vardef;
14293 }
14294
14295 @ @<Initialize table entries...@>=
14296 name_type(bad_vardef)=mp_root; link(bad_vardef)=frozen_bad_vardef;
14297 equiv(frozen_bad_vardef)=bad_vardef; eq_type(frozen_bad_vardef)=tag_token;
14298
14299 @ @<Absorb delimited parameters, putting them into lists |q| and |r|@>=
14300 do {  
14301   l_delim=mp->cur_sym; r_delim=mp->cur_mod; get_t_next;
14302   if ( (mp->cur_cmd==param_type)&&(mp->cur_mod>=expr_base) ) {
14303    base=mp->cur_mod;
14304   } else { 
14305     print_err("Missing parameter type; `expr' will be assumed");
14306 @.Missing parameter type@>
14307     help1("You should've had `expr' or `suffix' or `text' here.");
14308     mp_back_error(mp); base=expr_base;
14309   }
14310   @<Absorb parameter tokens for type |base|@>;
14311   mp_check_delimiter(mp, l_delim,r_delim);
14312   get_t_next;
14313 } while (mp->cur_cmd==left_delimiter)
14314
14315 @ @<Absorb parameter tokens for type |base|@>=
14316 do { 
14317   link(q)=mp_get_avail(mp); q=link(q); info(q)=base+k;
14318   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size); 
14319   value(p)=base+k; info(p)=mp->cur_sym;
14320   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14321 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
14322   incr(k); link(p)=r; r=p; get_t_next;
14323 } while (mp->cur_cmd==comma)
14324
14325 @ @<Absorb undelimited parameters, putting them into list |r|@>=
14326
14327   p=mp_get_node(mp, token_node_size);
14328   if ( mp->cur_mod<expr_base ) {
14329     c=mp->cur_mod; value(p)=expr_base+k;
14330   } else { 
14331     value(p)=mp->cur_mod+k;
14332     if ( mp->cur_mod==expr_base ) c=expr_macro;
14333     else if ( mp->cur_mod==suffix_base ) c=suffix_macro;
14334     else c=text_macro;
14335   }
14336   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14337   incr(k); mp_get_symbol(mp); info(p)=mp->cur_sym; link(p)=r; r=p; get_t_next;
14338   if ( c==expr_macro ) if ( mp->cur_cmd==of_token ) {
14339     c=of_macro; p=mp_get_node(mp, token_node_size);
14340     if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14341     value(p)=expr_base+k; mp_get_symbol(mp); info(p)=mp->cur_sym;
14342     link(p)=r; r=p; get_t_next;
14343   }
14344 }
14345
14346 @* \[32] Expanding the next token.
14347 Only a few command codes |<min_command| can possibly be returned by
14348 |get_t_next|; in increasing order, they are
14349 |if_test|, |fi_or_else|, |input|, |iteration|, |repeat_loop|,
14350 |exit_test|, |relax|, |scan_tokens|, |expand_after|, and |defined_macro|.
14351
14352 \MP\ usually gets the next token of input by saying |get_x_next|. This is
14353 like |get_t_next| except that it keeps getting more tokens until
14354 finding |cur_cmd>=min_command|. In other words, |get_x_next| expands
14355 macros and removes conditionals or iterations or input instructions that
14356 might be present.
14357
14358 It follows that |get_x_next| might invoke itself recursively. In fact,
14359 there is massive recursion, since macro expansion can involve the
14360 scanning of arbitrarily complex expressions, which in turn involve
14361 macro expansion and conditionals, etc.
14362 @^recursion@>
14363
14364 Therefore it's necessary to declare a whole bunch of |forward|
14365 procedures at this point, and to insert some other procedures
14366 that will be invoked by |get_x_next|.
14367
14368 @<Declarations@>= 
14369 void mp_scan_primary (MP mp);
14370 void mp_scan_secondary (MP mp);
14371 void mp_scan_tertiary (MP mp);
14372 void mp_scan_expression (MP mp);
14373 void mp_scan_suffix (MP mp);
14374 @<Declare the procedure called |macro_call|@>;
14375 void mp_get_boolean (MP mp);
14376 void mp_pass_text (MP mp);
14377 void mp_conditional (MP mp);
14378 void mp_start_input (MP mp);
14379 void mp_begin_iteration (MP mp);
14380 void mp_resume_iteration (MP mp);
14381 void mp_stop_iteration (MP mp);
14382
14383 @ An auxiliary subroutine called |expand| is used by |get_x_next|
14384 when it has to do exotic expansion commands.
14385
14386 @c void mp_expand (MP mp) {
14387   pointer p; /* for list manipulation */
14388   size_t k; /* something that we hope is |<=buf_size| */
14389   pool_pointer j; /* index into |str_pool| */
14390   if ( mp->internal[tracing_commands]>unity ) 
14391     if ( mp->cur_cmd!=defined_macro )
14392       show_cur_cmd_mod;
14393   switch (mp->cur_cmd)  {
14394   case if_test:
14395     mp_conditional(mp); /* this procedure is discussed in Part 36 below */
14396     break;
14397   case fi_or_else:
14398     @<Terminate the current conditional and skip to \&{fi}@>;
14399     break;
14400   case input:
14401     @<Initiate or terminate input from a file@>;
14402     break;
14403   case iteration:
14404     if ( mp->cur_mod==end_for ) {
14405       @<Scold the user for having an extra \&{endfor}@>;
14406     } else {
14407       mp_begin_iteration(mp); /* this procedure is discussed in Part 37 below */
14408     }
14409     break;
14410   case repeat_loop: 
14411     @<Repeat a loop@>;
14412     break;
14413   case exit_test: 
14414     @<Exit a loop if the proper time has come@>;
14415     break;
14416   case relax: 
14417     break;
14418   case expand_after: 
14419     @<Expand the token after the next token@>;
14420     break;
14421   case scan_tokens: 
14422     @<Put a string into the input buffer@>;
14423     break;
14424   case defined_macro:
14425    mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14426    break;
14427   }; /* there are no other cases */
14428 };
14429
14430 @ @<Scold the user...@>=
14431
14432   print_err("Extra `endfor'");
14433 @.Extra `endfor'@>
14434   help2("I'm not currently working on a for loop,")
14435     ("so I had better not try to end anything.");
14436   mp_error(mp);
14437 }
14438
14439 @ The processing of \&{input} involves the |start_input| subroutine,
14440 which will be declared later; the processing of \&{endinput} is trivial.
14441
14442 @<Put each...@>=
14443 mp_primitive(mp, "input",input,0);
14444 @:input_}{\&{input} primitive@>
14445 mp_primitive(mp, "endinput",input,1);
14446 @:end_input_}{\&{endinput} primitive@>
14447
14448 @ @<Cases of |print_cmd_mod|...@>=
14449 case input: 
14450   if ( m==0 ) mp_print(mp, "input");
14451   else mp_print(mp, "endinput");
14452   break;
14453
14454 @ @<Initiate or terminate input...@>=
14455 if ( mp->cur_mod>0 ) mp->force_eof=true;
14456 else mp_start_input(mp)
14457
14458 @ We'll discuss the complicated parts of loop operations later. For now
14459 it suffices to know that there's a global variable called |loop_ptr|
14460 that will be |null| if no loop is in progress.
14461
14462 @<Repeat a loop@>=
14463 { while ( token_state &&(loc==null) ) 
14464     mp_end_token_list(mp); /* conserve stack space */
14465   if ( mp->loop_ptr==null ) {
14466     print_err("Lost loop");
14467 @.Lost loop@>
14468     help2("I'm confused; after exiting from a loop, I still seem")
14469       ("to want to repeat it. I'll try to forget the problem.");
14470     mp_error(mp);
14471   } else {
14472     mp_resume_iteration(mp); /* this procedure is in Part 37 below */
14473   }
14474 }
14475
14476 @ @<Exit a loop if the proper time has come@>=
14477 { mp_get_boolean(mp);
14478   if ( mp->internal[tracing_commands]>unity ) 
14479     mp_show_cmd_mod(mp, nullary,mp->cur_exp);
14480   if ( mp->cur_exp==true_code ) {
14481     if ( mp->loop_ptr==null ) {
14482       print_err("No loop is in progress");
14483 @.No loop is in progress@>
14484       help1("Why say `exitif' when there's nothing to exit from?");
14485       if ( mp->cur_cmd==semicolon ) mp_error(mp); else mp_back_error(mp);
14486     } else {
14487      @<Exit prematurely from an iteration@>;
14488     }
14489   } else if ( mp->cur_cmd!=semicolon ) {
14490     mp_missing_err(mp, ";");
14491 @.Missing `;'@>
14492     help2("After `exitif <boolean exp>' I expect to see a semicolon.")
14493     ("I shall pretend that one was there."); mp_back_error(mp);
14494   }
14495 }
14496
14497 @ Here we use the fact that |forever_text| is the only |token_type| that
14498 is less than |loop_text|.
14499
14500 @<Exit prematurely...@>=
14501 { p=null;
14502   do {  
14503     if ( file_state ) {
14504       mp_end_file_reading(mp);
14505     } else { 
14506       if ( token_type<=loop_text ) p=start;
14507       mp_end_token_list(mp);
14508     }
14509   } while (p==null);
14510   if ( p!=info(mp->loop_ptr) ) mp_fatal_error(mp, "*** (loop confusion)");
14511 @.loop confusion@>
14512   mp_stop_iteration(mp); /* this procedure is in Part 34 below */
14513 }
14514
14515 @ @<Expand the token after the next token@>=
14516 { get_t_next;
14517   p=mp_cur_tok(mp); get_t_next;
14518   if ( mp->cur_cmd<min_command ) mp_expand(mp); 
14519   else mp_back_input(mp);
14520   back_list(p);
14521 }
14522
14523 @ @<Put a string into the input buffer@>=
14524 { mp_get_x_next(mp); mp_scan_primary(mp);
14525   if ( mp->cur_type!=mp_string_type ) {
14526     mp_disp_err(mp, null,"Not a string");
14527 @.Not a string@>
14528     help2("I'm going to flush this expression, since")
14529        ("scantokens should be followed by a known string.");
14530     mp_put_get_flush_error(mp, 0);
14531   } else { 
14532     mp_back_input(mp);
14533     if ( length(mp->cur_exp)>0 )
14534        @<Pretend we're reading a new one-line file@>;
14535   }
14536 }
14537
14538 @ @<Pretend we're reading a new one-line file@>=
14539 { mp_begin_file_reading(mp); name=is_scantok;
14540   k=mp->first+length(mp->cur_exp);
14541   if ( k>=mp->max_buf_stack ) {
14542     while ( k>=mp->buf_size ) {
14543       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
14544     }
14545     mp->max_buf_stack=k+1;
14546   }
14547   j=mp->str_start[mp->cur_exp]; limit=k;
14548   while ( mp->first<(size_t)limit ) {
14549     mp->buffer[mp->first]=mp->str_pool[j]; incr(j); incr(mp->first);
14550   }
14551   mp->buffer[limit]='%'; mp->first=limit+1; loc=start; 
14552   mp_flush_cur_exp(mp, 0);
14553 }
14554
14555 @ Here finally is |get_x_next|.
14556
14557 The expression scanning routines to be considered later
14558 communicate via the global quantities |cur_type| and |cur_exp|;
14559 we must be very careful to save and restore these quantities while
14560 macros are being expanded.
14561 @^inner loop@>
14562
14563 @<Declarations@>=
14564 void mp_get_x_next (MP mp);
14565
14566 @ @c void mp_get_x_next (MP mp) {
14567   pointer save_exp; /* a capsule to save |cur_type| and |cur_exp| */
14568   get_t_next;
14569   if ( mp->cur_cmd<min_command ) {
14570     save_exp=mp_stash_cur_exp(mp);
14571     do {  
14572       if ( mp->cur_cmd==defined_macro ) 
14573         mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14574       else 
14575         mp_expand(mp);
14576       get_t_next;
14577      } while (mp->cur_cmd<min_command);
14578      mp_unstash_cur_exp(mp, save_exp); /* that restores |cur_type| and |cur_exp| */
14579   }
14580 }
14581
14582 @ Now let's consider the |macro_call| procedure, which is used to start up
14583 all user-defined macros. Since the arguments to a macro might be expressions,
14584 |macro_call| is recursive.
14585 @^recursion@>
14586
14587 The first parameter to |macro_call| points to the reference count of the
14588 token list that defines the macro. The second parameter contains any
14589 arguments that have already been parsed (see below).  The third parameter
14590 points to the symbolic token that names the macro. If the third parameter
14591 is |null|, the macro was defined by \&{vardef}, so its name can be
14592 reconstructed from the prefix and ``at'' arguments found within the
14593 second parameter.
14594
14595 What is this second parameter? It's simply a linked list of one-word items,
14596 whose |info| fields point to the arguments. In other words, if |arg_list=null|,
14597 no arguments have been scanned yet; otherwise |info(arg_list)| points to
14598 the first scanned argument, and |link(arg_list)| points to the list of
14599 further arguments (if any).
14600
14601 Arguments of type \&{expr} are so-called capsules, which we will
14602 discuss later when we concentrate on expressions; they can be
14603 recognized easily because their |link| field is |void|. Arguments of type
14604 \&{suffix} and \&{text} are token lists without reference counts.
14605
14606 @ After argument scanning is complete, the arguments are moved to the
14607 |param_stack|. (They can't be put on that stack any sooner, because
14608 the stack is growing and shrinking in unpredictable ways as more arguments
14609 are being acquired.)  Then the macro body is fed to the scanner; i.e.,
14610 the replacement text of the macro is placed at the top of the \MP's
14611 input stack, so that |get_t_next| will proceed to read it next.
14612
14613 @<Declare the procedure called |macro_call|@>=
14614 @<Declare the procedure called |print_macro_name|@>;
14615 @<Declare the procedure called |print_arg|@>;
14616 @<Declare the procedure called |scan_text_arg|@>;
14617 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14618                     pointer macro_name) ;
14619
14620 @ @c
14621 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14622                     pointer macro_name) {
14623   /* invokes a user-defined control sequence */
14624   pointer r; /* current node in the macro's token list */
14625   pointer p,q; /* for list manipulation */
14626   integer n; /* the number of arguments */
14627   pointer tail = 0; /* tail of the argument list */
14628   pointer l_delim=0,r_delim=0; /* a delimiter pair */
14629   r=link(def_ref); add_mac_ref(def_ref);
14630   if ( arg_list==null ) {
14631     n=0;
14632   } else {
14633    @<Determine the number |n| of arguments already supplied,
14634     and set |tail| to the tail of |arg_list|@>;
14635   }
14636   if ( mp->internal[tracing_macros]>0 ) {
14637     @<Show the text of the macro being expanded, and the existing arguments@>;
14638   }
14639   @<Scan the remaining arguments, if any; set |r| to the first token
14640     of the replacement text@>;
14641   @<Feed the arguments and replacement text to the scanner@>;
14642 }
14643
14644 @ @<Show the text of the macro...@>=
14645 mp_begin_diagnostic(mp); mp_print_ln(mp); 
14646 mp_print_macro_name(mp, arg_list,macro_name);
14647 if ( n==3 ) mp_print(mp, "@@#"); /* indicate a suffixed macro */
14648 mp_show_macro(mp, def_ref,null,100000);
14649 if ( arg_list!=null ) {
14650   n=0; p=arg_list;
14651   do {  
14652     q=info(p);
14653     mp_print_arg(mp, q,n,0);
14654     incr(n); p=link(p);
14655   } while (p!=null);
14656 }
14657 mp_end_diagnostic(mp, false)
14658
14659
14660 @ @<Declare the procedure called |print_macro_name|@>=
14661 void mp_print_macro_name (MP mp,pointer a, pointer n);
14662
14663 @ @c
14664 void mp_print_macro_name (MP mp,pointer a, pointer n) {
14665   pointer p,q; /* they traverse the first part of |a| */
14666   if ( n!=null ) {
14667     mp_print_text(n);
14668   } else  { 
14669     p=info(a);
14670     if ( p==null ) {
14671       mp_print_text(info(info(link(a))));
14672     } else { 
14673       q=p;
14674       while ( link(q)!=null ) q=link(q);
14675       link(q)=info(link(a));
14676       mp_show_token_list(mp, p,null,1000,0);
14677       link(q)=null;
14678     }
14679   }
14680 }
14681
14682 @ @<Declare the procedure called |print_arg|@>=
14683 void mp_print_arg (MP mp,pointer q, integer n, pointer b) ;
14684
14685 @ @c
14686 void mp_print_arg (MP mp,pointer q, integer n, pointer b) {
14687   if ( link(q)==diov ) mp_print_nl(mp, "(EXPR");
14688   else if ( (b<text_base)&&(b!=text_macro) ) mp_print_nl(mp, "(SUFFIX");
14689   else mp_print_nl(mp, "(TEXT");
14690   mp_print_int(mp, n); mp_print(mp, ")<-");
14691   if ( link(q)==diov ) mp_print_exp(mp, q,1);
14692   else mp_show_token_list(mp, q,null,1000,0);
14693 }
14694
14695 @ @<Determine the number |n| of arguments already supplied...@>=
14696 {  
14697   n=1; tail=arg_list;
14698   while ( link(tail)!=null ) { 
14699     incr(n); tail=link(tail);
14700   }
14701 }
14702
14703 @ @<Scan the remaining arguments, if any; set |r|...@>=
14704 mp->cur_cmd=comma+1; /* anything |<>comma| will do */
14705 while ( info(r)>=expr_base ) { 
14706   @<Scan the delimited argument represented by |info(r)|@>;
14707   r=link(r);
14708 };
14709 if ( mp->cur_cmd==comma ) {
14710   print_err("Too many arguments to ");
14711 @.Too many arguments...@>
14712   mp_print_macro_name(mp, arg_list,macro_name); mp_print_char(mp, ';');
14713   mp_print_nl(mp, "  Missing `"); mp_print_text(r_delim);
14714 @.Missing `)'...@>
14715   mp_print(mp, "' has been inserted");
14716   help3("I'm going to assume that the comma I just read was a")
14717    ("right delimiter, and then I'll begin expanding the macro.")
14718    ("You might want to delete some tokens before continuing.");
14719   mp_error(mp);
14720 }
14721 if ( info(r)!=general_macro ) {
14722   @<Scan undelimited argument(s)@>;
14723 }
14724 r=link(r)
14725
14726 @ At this point, the reader will find it advisable to review the explanation
14727 of token list format that was presented earlier, paying special attention to
14728 the conventions that apply only at the beginning of a macro's token list.
14729
14730 On the other hand, the reader will have to take the expression-parsing
14731 aspects of the following program on faith; we will explain |cur_type|
14732 and |cur_exp| later. (Several things in this program depend on each other,
14733 and it's necessary to jump into the circle somewhere.)
14734
14735 @<Scan the delimited argument represented by |info(r)|@>=
14736 if ( mp->cur_cmd!=comma ) {
14737   mp_get_x_next(mp);
14738   if ( mp->cur_cmd!=left_delimiter ) {
14739     print_err("Missing argument to ");
14740 @.Missing argument...@>
14741     mp_print_macro_name(mp, arg_list,macro_name);
14742     help3("That macro has more parameters than you thought.")
14743      ("I'll continue by pretending that each missing argument")
14744      ("is either zero or null.");
14745     if ( info(r)>=suffix_base ) {
14746       mp->cur_exp=null; mp->cur_type=mp_token_list;
14747     } else { 
14748       mp->cur_exp=0; mp->cur_type=mp_known;
14749     }
14750     mp_back_error(mp); mp->cur_cmd=right_delimiter; 
14751     goto FOUND;
14752   }
14753   l_delim=mp->cur_sym; r_delim=mp->cur_mod;
14754 }
14755 @<Scan the argument represented by |info(r)|@>;
14756 if ( mp->cur_cmd!=comma ) 
14757   @<Check that the proper right delimiter was present@>;
14758 FOUND:  
14759 @<Append the current expression to |arg_list|@>
14760
14761 @ @<Check that the proper right delim...@>=
14762 if ( (mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
14763   if ( info(link(r))>=expr_base ) {
14764     mp_missing_err(mp, ",");
14765 @.Missing `,'@>
14766     help3("I've finished reading a macro argument and am about to")
14767       ("read another; the arguments weren't delimited correctly.")
14768        ("You might want to delete some tokens before continuing.");
14769     mp_back_error(mp); mp->cur_cmd=comma;
14770   } else { 
14771     mp_missing_err(mp, str(text(r_delim)));
14772 @.Missing `)'@>
14773     help2("I've gotten to the end of the macro parameter list.")
14774        ("You might want to delete some tokens before continuing.");
14775     mp_back_error(mp);
14776   }
14777 }
14778
14779 @ A \&{suffix} or \&{text} parameter will be have been scanned as
14780 a token list pointed to by |cur_exp|, in which case we will have
14781 |cur_type=token_list|.
14782
14783 @<Append the current expression to |arg_list|@>=
14784
14785   p=mp_get_avail(mp);
14786   if ( mp->cur_type==mp_token_list ) info(p)=mp->cur_exp;
14787   else info(p)=mp_stash_cur_exp(mp);
14788   if ( mp->internal[tracing_macros]>0 ) {
14789     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,info(r)); 
14790     mp_end_diagnostic(mp, false);
14791   }
14792   if ( arg_list==null ) arg_list=p;
14793   else link(tail)=p;
14794   tail=p; incr(n);
14795 }
14796
14797 @ @<Scan the argument represented by |info(r)|@>=
14798 if ( info(r)>=text_base ) {
14799   mp_scan_text_arg(mp, l_delim,r_delim);
14800 } else { 
14801   mp_get_x_next(mp);
14802   if ( info(r)>=suffix_base ) mp_scan_suffix(mp);
14803   else mp_scan_expression(mp);
14804 }
14805
14806 @ The parameters to |scan_text_arg| are either a pair of delimiters
14807 or zero; the latter case is for undelimited text arguments, which
14808 end with the first semicolon or \&{endgroup} or \&{end} that is not
14809 contained in a group.
14810
14811 @<Declare the procedure called |scan_text_arg|@>=
14812 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) ;
14813
14814 @ @c
14815 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) {
14816   integer balance; /* excess of |l_delim| over |r_delim| */
14817   pointer p; /* list tail */
14818   mp->warning_info=l_delim; mp->scanner_status=absorbing;
14819   p=hold_head; balance=1; link(hold_head)=null;
14820   while (1)  { 
14821     get_t_next;
14822     if ( l_delim==0 ) {
14823       @<Adjust the balance for an undelimited argument; |break| if done@>;
14824     } else {
14825           @<Adjust the balance for a delimited argument; |break| if done@>;
14826     }
14827     link(p)=mp_cur_tok(mp); p=link(p);
14828   }
14829   mp->cur_exp=link(hold_head); mp->cur_type=mp_token_list;
14830   mp->scanner_status=normal;
14831 };
14832
14833 @ @<Adjust the balance for a delimited argument...@>=
14834 if ( mp->cur_cmd==right_delimiter ) { 
14835   if ( mp->cur_mod==l_delim ) { 
14836     decr(balance);
14837     if ( balance==0 ) break;
14838   }
14839 } else if ( mp->cur_cmd==left_delimiter ) {
14840   if ( mp->cur_mod==r_delim ) incr(balance);
14841 }
14842
14843 @ @<Adjust the balance for an undelimited...@>=
14844 if ( end_of_statement ) { /* |cur_cmd=semicolon|, |end_group|, or |stop| */
14845   if ( balance==1 ) { break; }
14846   else  { if ( mp->cur_cmd==end_group ) decr(balance); }
14847 } else if ( mp->cur_cmd==begin_group ) { 
14848   incr(balance); 
14849 }
14850
14851 @ @<Scan undelimited argument(s)@>=
14852
14853   if ( info(r)<text_macro ) {
14854     mp_get_x_next(mp);
14855     if ( info(r)!=suffix_macro ) {
14856       if ( (mp->cur_cmd==equals)||(mp->cur_cmd==assignment) ) mp_get_x_next(mp);
14857     }
14858   }
14859   switch (info(r)) {
14860   case primary_macro:mp_scan_primary(mp); break;
14861   case secondary_macro:mp_scan_secondary(mp); break;
14862   case tertiary_macro:mp_scan_tertiary(mp); break;
14863   case expr_macro:mp_scan_expression(mp); break;
14864   case of_macro:
14865     @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>;
14866     break;
14867   case suffix_macro:
14868     @<Scan a suffix with optional delimiters@>;
14869     break;
14870   case text_macro:mp_scan_text_arg(mp, 0,0); break;
14871   } /* there are no other cases */
14872   mp_back_input(mp); 
14873   @<Append the current expression to |arg_list|@>;
14874 }
14875
14876 @ @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>=
14877
14878   mp_scan_expression(mp); p=mp_get_avail(mp); info(p)=mp_stash_cur_exp(mp);
14879   if ( mp->internal[tracing_macros]>0 ) { 
14880     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,0); 
14881     mp_end_diagnostic(mp, false);
14882   }
14883   if ( arg_list==null ) arg_list=p; else link(tail)=p;
14884   tail=p;incr(n);
14885   if ( mp->cur_cmd!=of_token ) {
14886     mp_missing_err(mp, "of"); mp_print(mp, " for ");
14887 @.Missing `of'@>
14888     mp_print_macro_name(mp, arg_list,macro_name);
14889     help1("I've got the first argument; will look now for the other.");
14890     mp_back_error(mp);
14891   }
14892   mp_get_x_next(mp); mp_scan_primary(mp);
14893 }
14894
14895 @ @<Scan a suffix with optional delimiters@>=
14896
14897   if ( mp->cur_cmd!=left_delimiter ) {
14898     l_delim=null;
14899   } else { 
14900     l_delim=mp->cur_sym; r_delim=mp->cur_mod; mp_get_x_next(mp);
14901   };
14902   mp_scan_suffix(mp);
14903   if ( l_delim!=null ) {
14904     if ((mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
14905       mp_missing_err(mp, str(text(r_delim)));
14906 @.Missing `)'@>
14907       help2("I've gotten to the end of the macro parameter list.")
14908          ("You might want to delete some tokens before continuing.");
14909       mp_back_error(mp);
14910     }
14911     mp_get_x_next(mp);
14912   }
14913 }
14914
14915 @ Before we put a new token list on the input stack, it is wise to clean off
14916 all token lists that have recently been depleted. Then a user macro that ends
14917 with a call to itself will not require unbounded stack space.
14918
14919 @<Feed the arguments and replacement text to the scanner@>=
14920 while ( token_state &&(loc==null) ) mp_end_token_list(mp); /* conserve stack space */
14921 if ( mp->param_ptr+n>mp->max_param_stack ) {
14922   mp->max_param_stack=mp->param_ptr+n;
14923   if ( mp->max_param_stack>mp->param_size )
14924     mp_overflow(mp, "parameter stack size",mp->param_size);
14925 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
14926 }
14927 mp_begin_token_list(mp, def_ref,macro); name=macro_name; loc=r;
14928 if ( n>0 ) {
14929   p=arg_list;
14930   do {  
14931    mp->param_stack[mp->param_ptr]=info(p); incr(mp->param_ptr); p=link(p);
14932   } while (p!=null);
14933   mp_flush_list(mp, arg_list);
14934 }
14935
14936 @ It's sometimes necessary to put a single argument onto |param_stack|.
14937 The |stack_argument| subroutine does this.
14938
14939 @c void mp_stack_argument (MP mp,pointer p) { 
14940   if ( mp->param_ptr==mp->max_param_stack ) {
14941     incr(mp->max_param_stack);
14942     if ( mp->max_param_stack>mp->param_size )
14943       mp_overflow(mp, "parameter stack size",mp->param_size);
14944 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
14945   }
14946   mp->param_stack[mp->param_ptr]=p; incr(mp->param_ptr);
14947 }
14948
14949 @* \[33] Conditional processing.
14950 Let's consider now the way \&{if} commands are handled.
14951
14952 Conditions can be inside conditions, and this nesting has a stack
14953 that is independent of other stacks.
14954 Four global variables represent the top of the condition stack:
14955 |cond_ptr| points to pushed-down entries, if~any; |cur_if| tells whether
14956 we are processing \&{if} or \&{elseif}; |if_limit| specifies
14957 the largest code of a |fi_or_else| command that is syntactically legal;
14958 and |if_line| is the line number at which the current conditional began.
14959
14960 If no conditions are currently in progress, the condition stack has the
14961 special state |cond_ptr=null|, |if_limit=normal|, |cur_if=0|, |if_line=0|.
14962 Otherwise |cond_ptr| points to a two-word node; the |type|, |name_type|, and
14963 |link| fields of the first word contain |if_limit|, |cur_if|, and
14964 |cond_ptr| at the next level, and the second word contains the
14965 corresponding |if_line|.
14966
14967 @d if_node_size 2 /* number of words in stack entry for conditionals */
14968 @d if_line_field(A) mp->mem[(A)+1].cint
14969 @d if_code 1 /* code for \&{if} being evaluated */
14970 @d fi_code 2 /* code for \&{fi} */
14971 @d else_code 3 /* code for \&{else} */
14972 @d else_if_code 4 /* code for \&{elseif} */
14973
14974 @<Glob...@>=
14975 pointer cond_ptr; /* top of the condition stack */
14976 integer if_limit; /* upper bound on |fi_or_else| codes */
14977 small_number cur_if; /* type of conditional being worked on */
14978 integer if_line; /* line where that conditional began */
14979
14980 @ @<Set init...@>=
14981 mp->cond_ptr=null; mp->if_limit=normal; mp->cur_if=0; mp->if_line=0;
14982
14983 @ @<Put each...@>=
14984 mp_primitive(mp, "if",if_test,if_code);
14985 @:if_}{\&{if} primitive@>
14986 mp_primitive(mp, "fi",fi_or_else,fi_code); mp->eqtb[frozen_fi]=mp->eqtb[mp->cur_sym];
14987 @:fi_}{\&{fi} primitive@>
14988 mp_primitive(mp, "else",fi_or_else,else_code);
14989 @:else_}{\&{else} primitive@>
14990 mp_primitive(mp, "elseif",fi_or_else,else_if_code);
14991 @:else_if_}{\&{elseif} primitive@>
14992
14993 @ @<Cases of |print_cmd_mod|...@>=
14994 case if_test:
14995 case fi_or_else: 
14996   switch (m) {
14997   case if_code:mp_print(mp, "if"); break;
14998   case fi_code:mp_print(mp, "fi");  break;
14999   case else_code:mp_print(mp, "else"); break;
15000   default: mp_print(mp, "elseif"); break;
15001   }
15002   break;
15003
15004 @ Here is a procedure that ignores text until coming to an \&{elseif},
15005 \&{else}, or \&{fi} at level zero of $\&{if}\ldots\&{fi}$
15006 nesting. After it has acted, |cur_mod| will indicate the token that
15007 was found.
15008
15009 \MP's smallest two command codes are |if_test| and |fi_or_else|; this
15010 makes the skipping process a bit simpler.
15011
15012 @c 
15013 void mp_pass_text (MP mp) {
15014   integer l = 0;
15015   mp->scanner_status=skipping;
15016   mp->warning_info=mp_true_line(mp);
15017   while (1)  { 
15018     get_t_next;
15019     if ( mp->cur_cmd<=fi_or_else ) {
15020       if ( mp->cur_cmd<fi_or_else ) {
15021         incr(l);
15022       } else { 
15023         if ( l==0 ) break;
15024         if ( mp->cur_mod==fi_code ) decr(l);
15025       }
15026     } else {
15027       @<Decrease the string reference count,
15028        if the current token is a string@>;
15029     }
15030   }
15031   mp->scanner_status=normal;
15032 }
15033
15034 @ @<Decrease the string reference count...@>=
15035 if ( mp->cur_cmd==string_token ) { delete_str_ref(mp->cur_mod); }
15036
15037 @ When we begin to process a new \&{if}, we set |if_limit:=if_code|; then
15038 if \&{elseif} or \&{else} or \&{fi} occurs before the current \&{if}
15039 condition has been evaluated, a colon will be inserted.
15040 A construction like `\.{if fi}' would otherwise get \MP\ confused.
15041
15042 @<Push the condition stack@>=
15043 { p=mp_get_node(mp, if_node_size); link(p)=mp->cond_ptr; type(p)=mp->if_limit;
15044   name_type(p)=mp->cur_if; if_line_field(p)=mp->if_line;
15045   mp->cond_ptr=p; mp->if_limit=if_code; mp->if_line=mp_true_line(mp); 
15046   mp->cur_if=if_code;
15047 }
15048
15049 @ @<Pop the condition stack@>=
15050 { p=mp->cond_ptr; mp->if_line=if_line_field(p);
15051   mp->cur_if=name_type(p); mp->if_limit=type(p); mp->cond_ptr=link(p);
15052   mp_free_node(mp, p,if_node_size);
15053 }
15054
15055 @ Here's a procedure that changes the |if_limit| code corresponding to
15056 a given value of |cond_ptr|.
15057
15058 @c void mp_change_if_limit (MP mp,small_number l, pointer p) {
15059   pointer q;
15060   if ( p==mp->cond_ptr ) {
15061     mp->if_limit=l; /* that's the easy case */
15062   } else  { 
15063     q=mp->cond_ptr;
15064     while (1) { 
15065       if ( q==null ) mp_confusion(mp, "if");
15066 @:this can't happen if}{\quad if@>
15067       if ( link(q)==p ) { 
15068         type(q)=l; return;
15069       }
15070       q=link(q);
15071     }
15072   }
15073 }
15074
15075 @ The user is supposed to put colons into the proper parts of conditional
15076 statements. Therefore, \MP\ has to check for their presence.
15077
15078 @c 
15079 void mp_check_colon (MP mp) { 
15080   if ( mp->cur_cmd!=colon ) { 
15081     mp_missing_err(mp, ":");
15082 @.Missing `:'@>
15083     help2("There should've been a colon after the condition.")
15084          ("I shall pretend that one was there.");;
15085     mp_back_error(mp);
15086   }
15087 }
15088
15089 @ A condition is started when the |get_x_next| procedure encounters
15090 an |if_test| command; in that case |get_x_next| calls |conditional|,
15091 which is a recursive procedure.
15092 @^recursion@>
15093
15094 @c void mp_conditional (MP mp) {
15095   pointer save_cond_ptr; /* |cond_ptr| corresponding to this conditional */
15096   int new_if_limit; /* future value of |if_limit| */
15097   pointer p; /* temporary register */
15098   @<Push the condition stack@>; 
15099   save_cond_ptr=mp->cond_ptr;
15100 RESWITCH: 
15101   mp_get_boolean(mp); new_if_limit=else_if_code;
15102   if ( mp->internal[tracing_commands]>unity ) {
15103     @<Display the boolean value of |cur_exp|@>;
15104   }
15105 FOUND: 
15106   mp_check_colon(mp);
15107   if ( mp->cur_exp==true_code ) {
15108     mp_change_if_limit(mp, new_if_limit,save_cond_ptr);
15109     return; /* wait for \&{elseif}, \&{else}, or \&{fi} */
15110   };
15111   @<Skip to \&{elseif} or \&{else} or \&{fi}, then |goto done|@>;
15112 DONE: 
15113   mp->cur_if=mp->cur_mod; mp->if_line=mp_true_line(mp);
15114   if ( mp->cur_mod==fi_code ) {
15115     @<Pop the condition stack@>
15116   } else if ( mp->cur_mod==else_if_code ) {
15117     goto RESWITCH;
15118   } else  { 
15119     mp->cur_exp=true_code; new_if_limit=fi_code; mp_get_x_next(mp); 
15120     goto FOUND;
15121   }
15122 }
15123
15124 @ In a construction like `\&{if} \&{if} \&{true}: $0=1$: \\{foo}
15125 \&{else}: \\{bar} \&{fi}', the first \&{else}
15126 that we come to after learning that the \&{if} is false is not the
15127 \&{else} we're looking for. Hence the following curious logic is needed.
15128
15129 @<Skip to \&{elseif}...@>=
15130 while (1) { 
15131   mp_pass_text(mp);
15132   if ( mp->cond_ptr==save_cond_ptr ) goto DONE;
15133   else if ( mp->cur_mod==fi_code ) @<Pop the condition stack@>;
15134 }
15135
15136
15137 @ @<Display the boolean value...@>=
15138 { mp_begin_diagnostic(mp);
15139   if ( mp->cur_exp==true_code ) mp_print(mp, "{true}");
15140   else mp_print(mp, "{false}");
15141   mp_end_diagnostic(mp, false);
15142 }
15143
15144 @ The processing of conditionals is complete except for the following
15145 code, which is actually part of |get_x_next|. It comes into play when
15146 \&{elseif}, \&{else}, or \&{fi} is scanned.
15147
15148 @<Terminate the current conditional and skip to \&{fi}@>=
15149 if ( mp->cur_mod>mp->if_limit ) {
15150   if ( mp->if_limit==if_code ) { /* condition not yet evaluated */
15151     mp_missing_err(mp, ":");
15152 @.Missing `:'@>
15153     mp_back_input(mp); mp->cur_sym=frozen_colon; mp_ins_error(mp);
15154   } else  { 
15155     print_err("Extra "); mp_print_cmd_mod(mp, fi_or_else,mp->cur_mod);
15156 @.Extra else@>
15157 @.Extra elseif@>
15158 @.Extra fi@>
15159     help1("I'm ignoring this; it doesn't match any if.");
15160     mp_error(mp);
15161   }
15162 } else  { 
15163   while ( mp->cur_mod!=fi_code ) mp_pass_text(mp); /* skip to \&{fi} */
15164   @<Pop the condition stack@>;
15165 }
15166
15167 @* \[34] Iterations.
15168 To bring our treatment of |get_x_next| to a close, we need to consider what
15169 \MP\ does when it sees \&{for}, \&{forsuffixes}, and \&{forever}.
15170
15171 There's a global variable |loop_ptr| that keeps track of the \&{for} loops
15172 that are currently active. If |loop_ptr=null|, no loops are in progress;
15173 otherwise |info(loop_ptr)| points to the iterative text of the current
15174 (innermost) loop, and |link(loop_ptr)| points to the data for any other
15175 loops that enclose the current one.
15176
15177 A loop-control node also has two other fields, called |loop_type| and
15178 |loop_list|, whose contents depend on the type of loop:
15179
15180 \yskip\indent|loop_type(loop_ptr)=null| means that |loop_list(loop_ptr)|
15181 points to a list of one-word nodes whose |info| fields point to the
15182 remaining argument values of a suffix list and expression list.
15183
15184 \yskip\indent|loop_type(loop_ptr)=diov| means that the current loop is
15185 `\&{forever}'.
15186
15187 \yskip\indent|loop_type(loop_ptr)=progression_flag| means that
15188 |p=loop_list(loop_ptr)| points to a ``progression node'' and |value(p)|,
15189 |step_size(p)|, and |final_value(p)| contain the data for an arithmetic
15190 progression.
15191
15192 \yskip\indent|loop_type(loop_ptr)=p>diov| means that |p| points to an edge
15193 header and |loop_list(loop_ptr)| points into the graphical object list for
15194 that edge header.
15195
15196 \yskip\noindent In the case of a progression node, the first word is not used
15197 because the link field of words in the dynamic memory area cannot be arbitrary.
15198
15199 @d loop_list_loc(A) ((A)+1) /* where the |loop_list| field resides */
15200 @d loop_type(A) info(loop_list_loc((A))) /* the type of \&{for} loop */
15201 @d loop_list(A) link(loop_list_loc((A))) /* the remaining list elements */
15202 @d loop_node_size 2 /* the number of words in a loop control node */
15203 @d progression_node_size 4 /* the number of words in a progression node */
15204 @d step_size(A) mp->mem[(A)+2].sc /* the step size in an arithmetic progression */
15205 @d final_value(A) mp->mem[(A)+3].sc /* the final value in an arithmetic progression */
15206 @d progression_flag (null+2)
15207   /* |loop_type| value when |loop_list| points to a progression node */
15208
15209 @<Glob...@>=
15210 pointer loop_ptr; /* top of the loop-control-node stack */
15211
15212 @ @<Set init...@>=
15213 mp->loop_ptr=null;
15214
15215 @ If the expressions that define an arithmetic progression in
15216 a \&{for} loop don't have known numeric values, the |bad_for|
15217 subroutine screams at the user.
15218
15219 @c void mp_bad_for (MP mp, char * s) {
15220   mp_disp_err(mp, null,"Improper "); /* show the bad expression above the message */
15221 @.Improper...replaced by 0@>
15222   mp_print(mp, s); mp_print(mp, " has been replaced by 0");
15223   help4("When you say `for x=a step b until c',")
15224     ("the initial value `a' and the step size `b'")
15225     ("and the final value `c' must have known numeric values.")
15226     ("I'm zeroing this one. Proceed, with fingers crossed.");
15227   mp_put_get_flush_error(mp, 0);
15228 };
15229
15230 @ Here's what \MP\ does when \&{for}, \&{forsuffixes}, or \&{forever}
15231 has just been scanned. (This code requires slight familiarity with
15232 expression-parsing routines that we have not yet discussed; but it seems
15233 to belong in the present part of the program, even though the original author
15234 didn't write it until later. The reader may wish to come back to it.)
15235
15236 @c void mp_begin_iteration (MP mp) {
15237   halfword m; /* |expr_base| (\&{for}) or |suffix_base| (\&{forsuffixes}) */
15238   halfword n; /* hash address of the current symbol */
15239   pointer s; /* the new loop-control node */
15240   pointer p; /* substitution list for |scan_toks| */
15241   pointer q;  /* link manipulation register */
15242   pointer pp; /* a new progression node */
15243   m=mp->cur_mod; n=mp->cur_sym; s=mp_get_node(mp, loop_node_size);
15244   if ( m==start_forever ){ 
15245     loop_type(s)=diov; p=null; mp_get_x_next(mp);
15246   } else { 
15247     mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
15248     info(p)=mp->cur_sym; value(p)=m;
15249     mp_get_x_next(mp);
15250     if ( mp->cur_cmd==within_token ) {
15251       @<Set up a picture iteration@>;
15252     } else { 
15253       @<Check for the |"="| or |":="| in a loop header@>;
15254       @<Scan the values to be used in the loop@>;
15255     }
15256   }
15257   @<Check for the presence of a colon@>;
15258   @<Scan the loop text and put it on the loop control stack@>;
15259   mp_resume_iteration(mp);
15260 }
15261
15262 @ @<Check for the |"="| or |":="| in a loop header@>=
15263 if ( (mp->cur_cmd!=equals)&&(mp->cur_cmd!=assignment) ) { 
15264   mp_missing_err(mp, "=");
15265 @.Missing `='@>
15266   help3("The next thing in this loop should have been `=' or `:='.")
15267     ("But don't worry; I'll pretend that an equals sign")
15268     ("was present, and I'll look for the values next.");
15269   mp_back_error(mp);
15270 }
15271
15272 @ @<Check for the presence of a colon@>=
15273 if ( mp->cur_cmd!=colon ) { 
15274   mp_missing_err(mp, ":");
15275 @.Missing `:'@>
15276   help3("The next thing in this loop should have been a `:'.")
15277     ("So I'll pretend that a colon was present;")
15278     ("everything from here to `endfor' will be iterated.");
15279   mp_back_error(mp);
15280 }
15281
15282 @ We append a special |frozen_repeat_loop| token in place of the
15283 `\&{endfor}' at the end of the loop. This will come through \MP's scanner
15284 at the proper time to cause the loop to be repeated.
15285
15286 (If the user tries some shenanigan like `\&{for} $\ldots$ \&{let} \&{endfor}',
15287 he will be foiled by the |get_symbol| routine, which keeps frozen
15288 tokens unchanged. Furthermore the |frozen_repeat_loop| is an \&{outer}
15289 token, so it won't be lost accidentally.)
15290
15291 @ @<Scan the loop text...@>=
15292 q=mp_get_avail(mp); info(q)=frozen_repeat_loop;
15293 mp->scanner_status=loop_defining; mp->warning_info=n;
15294 info(s)=mp_scan_toks(mp, iteration,p,q,0); mp->scanner_status=normal;
15295 link(s)=mp->loop_ptr; mp->loop_ptr=s
15296
15297 @ @<Initialize table...@>=
15298 eq_type(frozen_repeat_loop)=repeat_loop+outer_tag;
15299 text(frozen_repeat_loop)=intern(" ENDFOR");
15300
15301 @ The loop text is inserted into \MP's scanning apparatus by the
15302 |resume_iteration| routine.
15303
15304 @c void mp_resume_iteration (MP mp) {
15305   pointer p,q; /* link registers */
15306   p=loop_type(mp->loop_ptr);
15307   if ( p==progression_flag ) { 
15308     p=loop_list(mp->loop_ptr); /* now |p| points to a progression node */
15309     mp->cur_exp=value(p);
15310     if ( @<The arithmetic progression has ended@> ) {
15311       mp_stop_iteration(mp);
15312       return;
15313     }
15314     mp->cur_type=mp_known; q=mp_stash_cur_exp(mp); /* make |q| an \&{expr} argument */
15315     value(p)=mp->cur_exp+step_size(p); /* set |value(p)| for the next iteration */
15316   } else if ( p==null ) { 
15317     p=loop_list(mp->loop_ptr);
15318     if ( p==null ) {
15319       mp_stop_iteration(mp);
15320       return;
15321     }
15322     loop_list(mp->loop_ptr)=link(p); q=info(p); free_avail(p);
15323   } else if ( p==diov ) { 
15324     mp_begin_token_list(mp, info(mp->loop_ptr),forever_text); return;
15325   } else {
15326     @<Make |q| a capsule containing the next picture component from
15327       |loop_list(loop_ptr)| or |goto not_found|@>;
15328   }
15329   mp_begin_token_list(mp, info(mp->loop_ptr),loop_text);
15330   mp_stack_argument(mp, q);
15331   if ( mp->internal[tracing_commands]>unity ) {
15332      @<Trace the start of a loop@>;
15333   }
15334   return;
15335 NOT_FOUND:
15336   mp_stop_iteration(mp);
15337 }
15338
15339 @ @<The arithmetic progression has ended@>=
15340 ((step_size(p)>0)&&(mp->cur_exp>final_value(p)))||
15341  ((step_size(p)<0)&&(mp->cur_exp<final_value(p)))
15342
15343 @ @<Trace the start of a loop@>=
15344
15345   mp_begin_diagnostic(mp); mp_print_nl(mp, "{loop value=");
15346 @.loop value=n@>
15347   if ( (q!=null)&&(link(q)==diov) ) mp_print_exp(mp, q,1);
15348   else mp_show_token_list(mp, q,null,50,0);
15349   mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
15350 }
15351
15352 @ @<Make |q| a capsule containing the next picture component from...@>=
15353 { q=loop_list(mp->loop_ptr);
15354   if ( q==null ) goto NOT_FOUND;
15355   skip_component(q) goto NOT_FOUND;
15356   mp->cur_exp=mp_copy_objects(mp, loop_list(mp->loop_ptr),q);
15357   mp_init_bbox(mp, mp->cur_exp);
15358   mp->cur_type=mp_picture_type;
15359   loop_list(mp->loop_ptr)=q;
15360   q=mp_stash_cur_exp(mp);
15361 }
15362
15363 @ A level of loop control disappears when |resume_iteration| has decided
15364 not to resume, or when an \&{exitif} construction has removed the loop text
15365 from the input stack.
15366
15367 @c void mp_stop_iteration (MP mp) {
15368   pointer p,q; /* the usual */
15369   p=loop_type(mp->loop_ptr);
15370   if ( p==progression_flag )  {
15371     mp_free_node(mp, loop_list(mp->loop_ptr),progression_node_size);
15372   } else if ( p==null ){ 
15373     q=loop_list(mp->loop_ptr);
15374     while ( q!=null ) {
15375       p=info(q);
15376       if ( p!=null ) {
15377         if ( link(p)==diov ) { /* it's an \&{expr} parameter */
15378           mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
15379         } else {
15380           mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
15381         }
15382       }
15383       p=q; q=link(q); free_avail(p);
15384     }
15385   } else if ( p>progression_flag ) {
15386     delete_edge_ref(p);
15387   }
15388   p=mp->loop_ptr; mp->loop_ptr=link(p); mp_flush_token_list(mp, info(p));
15389   mp_free_node(mp, p,loop_node_size);
15390 }
15391
15392 @ Now that we know all about loop control, we can finish up
15393 the missing portion of |begin_iteration| and we'll be done.
15394
15395 The following code is performed after the `\.=' has been scanned in
15396 a \&{for} construction (if |m=expr_base|) or a \&{forsuffixes} construction
15397 (if |m=suffix_base|).
15398
15399 @<Scan the values to be used in the loop@>=
15400 loop_type(s)=null; q=loop_list_loc(s); link(q)=null; /* |link(q)=loop_list(s)| */
15401 do {  
15402   mp_get_x_next(mp);
15403   if ( m!=expr_base ) {
15404     mp_scan_suffix(mp);
15405   } else { 
15406     if ( mp->cur_cmd>=colon ) if ( mp->cur_cmd<=comma ) 
15407           goto CONTINUE;
15408     mp_scan_expression(mp);
15409     if ( mp->cur_cmd==step_token ) if ( q==loop_list_loc(s) ) {
15410       @<Prepare for step-until construction and |break|@>;
15411     }
15412     mp->cur_exp=mp_stash_cur_exp(mp);
15413   }
15414   link(q)=mp_get_avail(mp); q=link(q); 
15415   info(q)=mp->cur_exp; mp->cur_type=mp_vacuous;
15416 CONTINUE:
15417   ;
15418 } while (mp->cur_cmd==comma)
15419
15420 @ @<Prepare for step-until construction and |break|@>=
15421
15422   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "initial value");
15423   pp=mp_get_node(mp, progression_node_size); value(pp)=mp->cur_exp;
15424   mp_get_x_next(mp); mp_scan_expression(mp);
15425   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "step size");
15426   step_size(pp)=mp->cur_exp;
15427   if ( mp->cur_cmd!=until_token ) { 
15428     mp_missing_err(mp, "until");
15429 @.Missing `until'@>
15430     help2("I assume you meant to say `until' after `step'.")
15431       ("So I'll look for the final value and colon next.");
15432     mp_back_error(mp);
15433   }
15434   mp_get_x_next(mp); mp_scan_expression(mp);
15435   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "final value");
15436   final_value(pp)=mp->cur_exp; loop_list(s)=pp;
15437   loop_type(s)=progression_flag; 
15438   break;
15439 }
15440
15441 @ The last case is when we have just seen ``\&{within}'', and we need to
15442 parse a picture expression and prepare to iterate over it.
15443
15444 @<Set up a picture iteration@>=
15445 { mp_get_x_next(mp);
15446   mp_scan_expression(mp);
15447   @<Make sure the current expression is a known picture@>;
15448   loop_type(s)=mp->cur_exp; mp->cur_type=mp_vacuous;
15449   q=link(dummy_loc(mp->cur_exp));
15450   if ( q!= null ) 
15451     if ( is_start_or_stop(q) )
15452       if ( mp_skip_1component(mp, q)==null ) q=link(q);
15453   loop_list(s)=q;
15454 }
15455
15456 @ @<Make sure the current expression is a known picture@>=
15457 if ( mp->cur_type!=mp_picture_type ) {
15458   mp_disp_err(mp, null,"Improper iteration spec has been replaced by nullpicture");
15459   help1("When you say `for x in p', p must be a known picture.");
15460   mp_put_get_flush_error(mp, mp_get_node(mp, edge_header_size));
15461   mp_init_edges(mp, mp->cur_exp); mp->cur_type=mp_picture_type;
15462 }
15463
15464 @* \[35] File names.
15465 It's time now to fret about file names.  Besides the fact that different
15466 operating systems treat files in different ways, we must cope with the
15467 fact that completely different naming conventions are used by different
15468 groups of people. The following programs show what is required for one
15469 particular operating system; similar routines for other systems are not
15470 difficult to devise.
15471 @^system dependencies@>
15472
15473 \MP\ assumes that a file name has three parts: the name proper; its
15474 ``extension''; and a ``file area'' where it is found in an external file
15475 system.  The extension of an input file is assumed to be
15476 `\.{.mp}' unless otherwise specified; it is `\.{.log}' on the
15477 transcript file that records each run of \MP; it is `\.{.tfm}' on the font
15478 metric files that describe characters in any fonts created by \MP; it is
15479 `\.{.ps}' or `.{\it nnn}' for some number {\it nnn} on the \ps\ output files;
15480 and it is `\.{.mem}' on the mem files written by \.{INIMP} to initialize \MP.
15481 The file area can be arbitrary on input files, but files are usually
15482 output to the user's current area.  If an input file cannot be
15483 found on the specified area, \MP\ will look for it on a special system
15484 area; this special area is intended for commonly used input files.
15485
15486 Simple uses of \MP\ refer only to file names that have no explicit
15487 extension or area. For example, a person usually says `\.{input} \.{cmr10}'
15488 instead of `\.{input} \.{cmr10.new}'. Simple file
15489 names are best, because they make the \MP\ source files portable;
15490 whenever a file name consists entirely of letters and digits, it should be
15491 treated in the same way by all implementations of \MP. However, users
15492 need the ability to refer to other files in their environment, especially
15493 when responding to error messages concerning unopenable files; therefore
15494 we want to let them use the syntax that appears in their favorite
15495 operating system.
15496
15497 @ \MP\ uses the same conventions that have proved to be satisfactory for
15498 \TeX\ and \MF. In order to isolate the system-dependent aspects of file names,
15499 @^system dependencies@>
15500 the system-independent parts of \MP\ are expressed in terms
15501 of three system-dependent
15502 procedures called |begin_name|, |more_name|, and |end_name|. In
15503 essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
15504 the system-independent driver program does the operations
15505 $$|begin_name|;\,|more_name|(c_1);\,\ldots\,;|more_name|(c_n);
15506 \,|end_name|.$$
15507 These three procedures communicate with each other via global variables.
15508 Afterwards the file name will appear in the string pool as three strings
15509 called |cur_name|\penalty10000\hskip-.05em,
15510 |cur_area|, and |cur_ext|; the latter two are null (i.e.,
15511 |""|), unless they were explicitly specified by the user.
15512
15513 Actually the situation is slightly more complicated, because \MP\ needs
15514 to know when the file name ends. The |more_name| routine is a function
15515 (with side effects) that returns |true| on the calls |more_name|$(c_1)$,
15516 \dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
15517 returns |false|; or, it returns |true| and $c_n$ is the last character
15518 on the current input line. In other words,
15519 |more_name| is supposed to return |true| unless it is sure that the
15520 file name has been completely scanned; and |end_name| is supposed to be able
15521 to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
15522 whether $|more_name|(c_n)$ returned |true| or |false|.
15523
15524 @<Glob...@>=
15525 char * cur_name; /* name of file just scanned */
15526 char * cur_area; /* file area just scanned, or \.{""} */
15527 char * cur_ext; /* file extension just scanned, or \.{""} */
15528
15529 @ It is easier to maintain reference counts if we assign initial values.
15530
15531 @<Set init...@>=
15532 mp->cur_name=xstrdup(""); 
15533 mp->cur_area=xstrdup(""); 
15534 mp->cur_ext=xstrdup("");
15535
15536 @ @<Dealloc variables@>=
15537 xfree(mp->cur_area);
15538 xfree(mp->cur_name);
15539 xfree(mp->cur_ext);
15540
15541 @ The file names we shall deal with for illustrative purposes have the
15542 following structure:  If the name contains `\.>' or `\.:', the file area
15543 consists of all characters up to and including the final such character;
15544 otherwise the file area is null.  If the remaining file name contains
15545 `\..', the file extension consists of all such characters from the first
15546 remaining `\..' to the end, otherwise the file extension is null.
15547 @^system dependencies@>
15548
15549 We can scan such file names easily by using two global variables that keep track
15550 of the occurrences of area and extension delimiters.  Note that these variables
15551 cannot be of type |pool_pointer| because a string pool compaction could occur
15552 while scanning a file name.
15553
15554 @<Glob...@>=
15555 integer area_delimiter;
15556   /* most recent `\.>' or `\.:' relative to |str_start[str_ptr]| */
15557 integer ext_delimiter; /* the relevant `\..', if any */
15558
15559 @ Input files that can't be found in the user's area may appear in standard
15560 system areas called |MP_area| and |MF_area|.  (The latter is used when the file
15561 extension is |".mf"|.)  The standard system area for font metric files
15562 to be read is |MP_font_area|.
15563 This system area name will, of course, vary from place to place.
15564 @^system dependencies@>
15565
15566 @d MP_area "MPinputs:"
15567 @.MPinputs@>
15568 @d MF_area "MFinputs:"
15569 @.MFinputs@>
15570 @d MP_font_area ""
15571 @.TeXfonts@>
15572
15573 @ Here now is the first of the system-dependent routines for file name scanning.
15574 @^system dependencies@>
15575
15576 @<Declare subroutines for parsing file names@>=
15577 void mp_begin_name (MP mp) { 
15578   xfree(mp->cur_name); 
15579   xfree(mp->cur_area); 
15580   xfree(mp->cur_ext);
15581   mp->area_delimiter=-1; 
15582   mp->ext_delimiter=-1;
15583 }
15584
15585 @ And here's the second.
15586 @^system dependencies@>
15587
15588 @<Declare subroutines for parsing file names@>=
15589 boolean mp_more_name (MP mp, ASCII_code c) { 
15590   if (c==' ') {
15591     return false;
15592   } else { 
15593     if ( (c=='>')||(c==':') ) { 
15594       mp->area_delimiter=mp->pool_ptr; 
15595       mp->ext_delimiter=-1;
15596     } else if ( (c=='.')&&(mp->ext_delimiter<0) ) {
15597       mp->ext_delimiter=mp->pool_ptr;
15598     }
15599     str_room(1); append_char(c); /* contribute |c| to the current string */
15600     return true;
15601   }
15602 }
15603
15604 @ The third.
15605 @^system dependencies@>
15606
15607 @d copy_pool_segment(A,B,C) { 
15608       A = xmalloc(C+1,sizeof(char)); 
15609       strncpy(A,(char *)(mp->str_pool+B),C);  
15610       A[C] = 0;}
15611
15612 @<Declare subroutines for parsing file names@>=
15613 void mp_end_name (MP mp) {
15614   pool_pointer s; /* length of area, name, and extension */
15615   unsigned int len;
15616   /* "my/w.mp" */
15617   s = mp->str_start[mp->str_ptr];
15618   if ( mp->area_delimiter<0 ) {
15619     mp->cur_area=xstrdup("");
15620   } else {
15621     len = mp->area_delimiter-s; 
15622     copy_pool_segment(mp->cur_area,s,len);
15623     s += len+1;
15624   }
15625   if ( mp->ext_delimiter<0 ) {
15626     mp->cur_ext=xstrdup("");
15627     len = mp->pool_ptr-s; 
15628   } else {
15629     copy_pool_segment(mp->cur_ext,mp->ext_delimiter,(mp->pool_ptr-mp->ext_delimiter));
15630     len = mp->ext_delimiter-s;
15631   }
15632   copy_pool_segment(mp->cur_name,s,len);
15633   mp->pool_ptr=s; /* don't need this partial string */
15634 }
15635
15636 @ Conversely, here is a routine that takes three strings and prints a file
15637 name that might have produced them. (The routine is system dependent, because
15638 some operating systems put the file area last instead of first.)
15639 @^system dependencies@>
15640
15641 @<Basic printing...@>=
15642 void mp_print_file_name (MP mp, char * n, char * a, char * e) { 
15643   mp_print(mp, a); mp_print(mp, n); mp_print(mp, e);
15644 };
15645
15646 @ Another system-dependent routine is needed to convert three internal
15647 \MP\ strings
15648 to the |name_of_file| value that is used to open files. The present code
15649 allows both lowercase and uppercase letters in the file name.
15650 @^system dependencies@>
15651
15652 @d append_to_name(A) { c=(A); 
15653   if ( k<file_name_size ) {
15654     mp->name_of_file[k]=xchr(c);
15655     incr(k);
15656   }
15657 }
15658
15659 @<Declare subroutines for parsing file names@>=
15660 void mp_pack_file_name (MP mp, char *n, char *a, char *e) {
15661   integer k; /* number of positions filled in |name_of_file| */
15662   ASCII_code c; /* character being packed */
15663   char *j; /* a character  index */
15664   k=0;
15665   assert(n);
15666   if (a!=NULL) {
15667     for (j=a;*j;j++) { append_to_name(*j); }
15668   }
15669   for (j=n;*j;j++) { append_to_name(*j); }
15670   if (e!=NULL) {
15671     for (j=e;*j;j++) { append_to_name(*j); }
15672   }
15673   mp->name_of_file[k]=0;
15674   mp->name_length=k; 
15675 }
15676
15677 @ @<Exported...@>=
15678 void mp_pack_file_name (MP mp, char *n, char *a, char *e) ;
15679
15680 @ A messier routine is also needed, since mem file names must be scanned
15681 before \MP's string mechanism has been initialized. We shall use the
15682 global variable |MP_mem_default| to supply the text for default system areas
15683 and extensions related to mem files.
15684 @^system dependencies@>
15685
15686 @d mem_default_length 9 /* length of the |MP_mem_default| string */
15687 @d mem_ext_length 4 /* length of its `\.{.mem}' part */
15688 @d mem_extension ".mem" /* the extension, as a \.{WEB} constant */
15689
15690 @<Glob...@>=
15691 char *MP_mem_default;
15692 char *mem_name; /* for commandline */
15693
15694 @ @<Option variables@>=
15695 char *mem_name; /* for commandline */
15696
15697 @ @<Allocate or initialize ...@>=
15698 mp->MP_mem_default = xstrdup("plain.mem");
15699 mp->mem_name = mp_xstrdup(opt.mem_name);
15700 @.plain@>
15701 @^system dependencies@>
15702
15703 @ @<Dealloc variables@>=
15704 xfree(mp->MP_mem_default);
15705 xfree(mp->mem_name);
15706
15707 @ @<Check the ``constant'' values for consistency@>=
15708 if ( mem_default_length>file_name_size ) mp->bad=20;
15709
15710 @ Here is the messy routine that was just mentioned. It sets |name_of_file|
15711 from the first |n| characters of |MP_mem_default|, followed by
15712 |buffer[a..b]|, followed by the last |mem_ext_length| characters of
15713 |MP_mem_default|.
15714
15715 We dare not give error messages here, since \MP\ calls this routine before
15716 the |error| routine is ready to roll. Instead, we simply drop excess characters,
15717 since the error will be detected in another way when a strange file name
15718 isn't found.
15719 @^system dependencies@>
15720
15721 @c void mp_pack_buffered_name (MP mp,small_number n, integer a,
15722                                integer b) {
15723   integer k; /* number of positions filled in |name_of_file| */
15724   ASCII_code c; /* character being packed */
15725   integer j; /* index into |buffer| or |MP_mem_default| */
15726   if ( n+b-a+1+mem_ext_length>file_name_size )
15727     b=a+file_name_size-n-1-mem_ext_length;
15728   k=0;
15729   for (j=0;j<n;j++) {
15730     append_to_name(xord((int)mp->MP_mem_default[j]));
15731   }
15732   for (j=a;j<=b;j++) {
15733     append_to_name(mp->buffer[j]);
15734   }
15735   for (j=mem_default_length-mem_ext_length;
15736       j<mem_default_length;j++) {
15737     append_to_name(xord((int)mp->MP_mem_default[j]));
15738   } 
15739   mp->name_of_file[k]=0;
15740   mp->name_length=k; 
15741 }
15742
15743 @ Here is the only place we use |pack_buffered_name|. This part of the program
15744 becomes active when a ``virgin'' \MP\ is trying to get going, just after
15745 the preliminary initialization, or when the user is substituting another
15746 mem file by typing `\.\&' after the initial `\.{**}' prompt.  The buffer
15747 contains the first line of input in |buffer[loc..(last-1)]|, where
15748 |loc<last| and |buffer[loc]<>" "|.
15749
15750 @<Declarations@>=
15751 boolean mp_open_mem_file (MP mp) ;
15752
15753 @ @c
15754 boolean mp_open_mem_file (MP mp) {
15755   int j; /* the first space after the file name */
15756   if (mp->mem_name!=NULL) {
15757     mp->mem_file = mp_open_file(mp, mp->mem_name, "rb", mp_filetype_memfile);
15758     if ( mp->mem_file ) return true;
15759   }
15760   j=loc;
15761   if ( mp->buffer[loc]=='&' ) {
15762     incr(loc); j=loc; mp->buffer[mp->last]=' ';
15763     while ( mp->buffer[j]!=' ' ) incr(j);
15764     mp_pack_buffered_name(mp, 0,loc,j-1); /* try first without the system file area */
15765     if ( mp_w_open_in(mp, &mp->mem_file) ) goto FOUND;
15766     wake_up_terminal;
15767     wterm_ln("Sorry, I can\'t find that mem file; will try PLAIN.");
15768 @.Sorry, I can't find...@>
15769     update_terminal;
15770   }
15771   /* now pull out all the stops: try for the system \.{plain} file */
15772   mp_pack_buffered_name(mp, mem_default_length-mem_ext_length,0,0);
15773   if ( ! mp_w_open_in(mp, &mp->mem_file) ) {
15774     wake_up_terminal;
15775     wterm_ln("I can\'t find the PLAIN mem file!\n");
15776 @.I can't find PLAIN...@>
15777 @.plain@>
15778     return false;
15779   }
15780 FOUND:
15781   loc=j; return true;
15782 }
15783
15784 @ Operating systems often make it possible to determine the exact name (and
15785 possible version number) of a file that has been opened. The following routine,
15786 which simply makes a \MP\ string from the value of |name_of_file|, should
15787 ideally be changed to deduce the full name of file~|f|, which is the file
15788 most recently opened, if it is possible to do this in a \PASCAL\ program.
15789 @^system dependencies@>
15790
15791 @<Declarations@>=
15792 #define mp_a_make_name_string(A,B)  mp_make_name_string(A)
15793 #define mp_b_make_name_string(A,B)  mp_make_name_string(A)
15794 #define mp_w_make_name_string(A,B)  mp_make_name_string(A)
15795
15796 @ @c 
15797 str_number mp_make_name_string (MP mp) {
15798   int k; /* index into |name_of_file| */
15799   str_room(mp->name_length);
15800   for (k=0;k<mp->name_length;k++) {
15801     append_char(xord((int)mp->name_of_file[k]));
15802   }
15803   return mp_make_string(mp);
15804 }
15805
15806 @ Now let's consider the ``driver''
15807 routines by which \MP\ deals with file names
15808 in a system-independent manner.  First comes a procedure that looks for a
15809 file name in the input by taking the information from the input buffer.
15810 (We can't use |get_next|, because the conversion to tokens would
15811 destroy necessary information.)
15812
15813 This procedure doesn't allow semicolons or percent signs to be part of
15814 file names, because of other conventions of \MP.
15815 {\sl The {\logos METAFONT\/}book} doesn't
15816 use semicolons or percents immediately after file names, but some users
15817 no doubt will find it natural to do so; therefore system-dependent
15818 changes to allow such characters in file names should probably
15819 be made with reluctance, and only when an entire file name that
15820 includes special characters is ``quoted'' somehow.
15821 @^system dependencies@>
15822
15823 @c void mp_scan_file_name (MP mp) { 
15824   mp_begin_name(mp);
15825   while ( mp->buffer[loc]==' ' ) incr(loc);
15826   while (1) { 
15827     if ( (mp->buffer[loc]==';')||(mp->buffer[loc]=='%') ) break;
15828     if ( ! mp_more_name(mp, mp->buffer[loc]) ) break;
15829     incr(loc);
15830   }
15831   mp_end_name(mp);
15832 }
15833
15834 @ Here is another version that takes its input from a string.
15835
15836 @<Declare subroutines for parsing file names@>=
15837 void mp_str_scan_file (MP mp,  str_number s) {
15838   pool_pointer p,q; /* current position and stopping point */
15839   mp_begin_name(mp);
15840   p=mp->str_start[s]; q=str_stop(s);
15841   while ( p<q ){ 
15842     if ( ! mp_more_name(mp, mp->str_pool[p]) ) break;
15843     incr(p);
15844   }
15845   mp_end_name(mp);
15846 }
15847
15848 @ And one that reads from a |char*|.
15849
15850 @<Declare subroutines for parsing file names@>=
15851 void mp_ptr_scan_file (MP mp,  char *s) {
15852   char *p, *q; /* current position and stopping point */
15853   mp_begin_name(mp);
15854   p=s; q=p+strlen(s);
15855   while ( p<q ){ 
15856     if ( ! mp_more_name(mp, *p)) break;
15857     p++;
15858   }
15859   mp_end_name(mp);
15860 }
15861
15862
15863 @ The global variable |job_name| contains the file name that was first
15864 \&{input} by the user. This name is extended by `\.{.log}' and `\.{ps}' and
15865 `\.{.mem}' and `\.{.tfm}' in order to make the names of \MP's output files.
15866
15867 @<Glob...@>=
15868 char *job_name; /* principal file name */
15869 boolean log_opened; /* has the transcript file been opened? */
15870 char *log_name; /* full name of the log file */
15871
15872 @ @<Option variables@>=
15873 char *job_name; /* principal file name */
15874
15875 @ Initially |job_name=NULL|; it becomes nonzero as soon as the true name is known.
15876 We have |job_name=NULL| if and only if the `\.{log}' file has not been opened,
15877 except of course for a short time just after |job_name| has become nonzero.
15878
15879 @<Allocate or ...@>=
15880 mp->job_name=mp_xstrdup(opt.job_name); 
15881 mp->log_opened=false;
15882
15883 @ @<Dealloc variables@>=
15884 xfree(mp->job_name);
15885
15886 @ Here is a routine that manufactures the output file names, assuming that
15887 |job_name<>0|. It ignores and changes the current settings of |cur_area|
15888 and |cur_ext|.
15889
15890 @d pack_cur_name mp_pack_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext)
15891
15892 @<Declarations@>=
15893 void mp_pack_job_name (MP mp, char *s) ;
15894
15895 @ @c void mp_pack_job_name (MP mp, char  *s) { /* |s = ".log"|, |".mem"|, |".ps"|, or .\\{nnn} */
15896   xfree(mp->cur_name); mp->cur_name=xstrdup(mp->job_name);
15897   xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
15898   xfree(mp->cur_ext);  mp->cur_ext=xstrdup(s);
15899   pack_cur_name;
15900 }
15901
15902 @ If some trouble arises when \MP\ tries to open a file, the following
15903 routine calls upon the user to supply another file name. Parameter~|s|
15904 is used in the error message to identify the type of file; parameter~|e|
15905 is the default extension if none is given. Upon exit from the routine,
15906 variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
15907 ready for another attempt at file opening.
15908
15909 @<Declarations@>=
15910 void mp_prompt_file_name (MP mp,char * s, char * e) ;
15911
15912 @ @c void mp_prompt_file_name (MP mp,char * s, char * e) {
15913   size_t k; /* index into |buffer| */
15914   char * saved_cur_name;
15915   if ( mp->interaction==mp_scroll_mode ) 
15916         wake_up_terminal;
15917   if (strcmp(s,"input file name")==0) {
15918         print_err("I can\'t find file `");
15919 @.I can't find file x@>
15920   } else {
15921         print_err("I can\'t write on file `");
15922   }
15923 @.I can't write on file x@>
15924   mp_print_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext); 
15925   mp_print(mp, "'.");
15926   if (strcmp(e,"")==0) 
15927         mp_show_context(mp);
15928   mp_print_nl(mp, "Please type another "); mp_print(mp, s);
15929 @.Please type...@>
15930   if ( mp->interaction<mp_scroll_mode )
15931     mp_fatal_error(mp, "*** (job aborted, file error in nonstop mode)");
15932 @.job aborted, file error...@>
15933   saved_cur_name = xstrdup(mp->cur_name);
15934   clear_terminal; prompt_input(": "); @<Scan file name in the buffer@>;
15935   if (strcmp(mp->cur_ext,"")==0) 
15936         mp->cur_ext=e;
15937   if (strlen(mp->cur_name)==0) {
15938     mp->cur_name=saved_cur_name;
15939   } else {
15940     xfree(saved_cur_name);
15941   }
15942   pack_cur_name;
15943 }
15944
15945 @ @<Scan file name in the buffer@>=
15946
15947   mp_begin_name(mp); k=mp->first;
15948   while ( (mp->buffer[k]==' ')&&(k<mp->last) ) incr(k);
15949   while (1) { 
15950     if ( k==mp->last ) break;
15951     if ( ! mp_more_name(mp, mp->buffer[k]) ) break;
15952     incr(k);
15953   }
15954   mp_end_name(mp);
15955 }
15956
15957 @ The |open_log_file| routine is used to open the transcript file and to help
15958 it catch up to what has previously been printed on the terminal.
15959
15960 @c void mp_open_log_file (MP mp) {
15961   int old_setting; /* previous |selector| setting */
15962   int k; /* index into |months| and |buffer| */
15963   int l; /* end of first input line */
15964   integer m; /* the current month */
15965   char *months="JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"; 
15966     /* abbreviations of month names */
15967   old_setting=mp->selector;
15968   if ( mp->job_name==NULL ) {
15969      mp->job_name=xstrdup("mpout");
15970   }
15971   mp_pack_job_name(mp,".log");
15972   while ( ! mp_a_open_out(mp, &mp->log_file, mp_filetype_log) ) {
15973     @<Try to get a different log file name@>;
15974   }
15975   mp->log_name=xstrdup(mp->name_of_file);
15976   mp->selector=log_only; mp->log_opened=true;
15977   @<Print the banner line, including the date and time@>;
15978   mp->input_stack[mp->input_ptr]=mp->cur_input; 
15979     /* make sure bottom level is in memory */
15980   mp_print_nl(mp, "**");
15981 @.**@>
15982   l=mp->input_stack[0].limit_field-1; /* last position of first line */
15983   for (k=0;k<=l;k++) mp_print_str(mp, mp->buffer[k]);
15984   mp_print_ln(mp); /* now the transcript file contains the first line of input */
15985   mp->selector=old_setting+2; /* |log_only| or |term_and_log| */
15986 }
15987
15988 @ @<Dealloc variables@>=
15989 xfree(mp->log_name);
15990
15991 @ Sometimes |open_log_file| is called at awkward moments when \MP\ is
15992 unable to print error messages or even to |show_context|.
15993 The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
15994 routine will not be invoked because |log_opened| will be false.
15995
15996 The normal idea of |mp_batch_mode| is that nothing at all should be written
15997 on the terminal. However, in the unusual case that
15998 no log file could be opened, we make an exception and allow
15999 an explanatory message to be seen.
16000
16001 Incidentally, the program always refers to the log file as a `\.{transcript
16002 file}', because some systems cannot use the extension `\.{.log}' for
16003 this file.
16004
16005 @<Try to get a different log file name@>=
16006 {  
16007   mp->selector=term_only;
16008   mp_prompt_file_name(mp, "transcript file name",".log");
16009 }
16010
16011 @ @<Print the banner...@>=
16012
16013   wlog(banner);
16014   mp_print(mp, mp->mem_ident); mp_print(mp, "  ");
16015   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[day])); 
16016   mp_print_char(mp, ' ');
16017   m=mp_round_unscaled(mp, mp->internal[month]);
16018   for (k=3*m-3;k<3*m;k++) { wlog_chr(months[k]); }
16019   mp_print_char(mp, ' '); 
16020   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[year])); 
16021   mp_print_char(mp, ' ');
16022   m=mp_round_unscaled(mp, mp->internal[mp_time]);
16023   mp_print_dd(mp, m / 60); mp_print_char(mp, ':'); mp_print_dd(mp, m % 60);
16024 }
16025
16026 @ The |try_extension| function tries to open an input file determined by
16027 |cur_name|, |cur_area|, and the argument |ext|.  It returns |false| if it
16028 can't find the file in |cur_area| or the appropriate system area.
16029
16030 @c boolean mp_try_extension (MP mp,char *ext) { 
16031   mp_pack_file_name(mp, mp->cur_name,mp->cur_area, ext);
16032   in_name=xstrdup(mp->cur_name); 
16033   in_area=xstrdup(mp->cur_area);
16034   if ( mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16035     return true;
16036   } else { 
16037     if (strcmp(ext,".mf")==0 ) in_area=xstrdup(MF_area);
16038     else in_area=xstrdup(MP_area);
16039     mp_pack_file_name(mp, mp->cur_name,in_area,ext);
16040     return mp_a_open_in(mp, &cur_file, mp_filetype_program);
16041   }
16042   return false;
16043 }
16044
16045 @ Let's turn now to the procedure that is used to initiate file reading
16046 when an `\.{input}' command is being processed.
16047
16048 @c void mp_start_input (MP mp) { /* \MP\ will \.{input} something */
16049   char *fname = NULL;
16050   @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>;
16051   while (1) { 
16052     mp_begin_file_reading(mp); /* set up |cur_file| and new level of input */
16053     if ( strlen(mp->cur_ext)==0 ) {
16054       if ( mp_try_extension(mp, ".mp") ) break;
16055       else if ( mp_try_extension(mp, "") ) break;
16056       else if ( mp_try_extension(mp, ".mf") ) break;
16057       /* |else do_nothing; | */
16058     } else if ( mp_try_extension(mp, mp->cur_ext) ) {
16059       break;
16060     }
16061     mp_end_file_reading(mp); /* remove the level that didn't work */
16062     mp_prompt_file_name(mp, "input file name","");
16063   }
16064   name=mp_a_make_name_string(mp, cur_file);
16065   fname = xstrdup(mp->name_of_file);
16066   if ( mp->job_name==NULL ) {
16067     mp->job_name=xstrdup(mp->cur_name); 
16068     mp_open_log_file(mp);
16069   } /* |open_log_file| doesn't |show_context|, so |limit|
16070         and |loc| needn't be set to meaningful values yet */
16071   if ( ((int)mp->term_offset+(int)strlen(fname)) > (mp->max_print_line-2)) mp_print_ln(mp);
16072   else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
16073   mp_print_char(mp, '('); incr(mp->open_parens); mp_print(mp, fname); 
16074   xfree(fname);
16075   update_terminal;
16076   @<Flush |name| and replace it with |cur_name| if it won't be needed@>;
16077   @<Read the first line of the new file@>;
16078 }
16079
16080 @ This code should be omitted if |a_make_name_string| returns something other
16081 than just a copy of its argument and the full file name is needed for opening
16082 \.{MPX} files or implementing the switch-to-editor option.
16083 @^system dependencies@>
16084
16085 @<Flush |name| and replace it with |cur_name| if it won't be needed@>=
16086 mp_flush_string(mp, name); name=rts(mp->cur_name); mp->cur_name=NULL
16087
16088 @ Here we have to remember to tell the |input_ln| routine not to
16089 start with a |get|. If the file is empty, it is considered to
16090 contain a single blank line.
16091 @^system dependencies@>
16092
16093 @<Read the first line...@>=
16094
16095   line=1;
16096   (void)mp_input_ln(mp, cur_file,false); 
16097   mp_firm_up_the_line(mp);
16098   mp->buffer[limit]='%'; mp->first=limit+1; loc=start;
16099 }
16100
16101 @ @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>=
16102 while ( token_state &&(loc==null) ) mp_end_token_list(mp);
16103 if ( token_state ) { 
16104   print_err("File names can't appear within macros");
16105 @.File names can't...@>
16106   help3("Sorry...I've converted what follows to tokens,")
16107     ("possibly garbaging the name you gave.")
16108     ("Please delete the tokens and insert the name again.");
16109   mp_error(mp);
16110 }
16111 if ( file_state ) {
16112   mp_scan_file_name(mp);
16113 } else { 
16114    xfree(mp->cur_name); mp->cur_name=xstrdup(""); 
16115    xfree(mp->cur_ext);  mp->cur_ext =xstrdup(""); 
16116    xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
16117 }
16118
16119 @ Sometimes we need to deal with two file names at once.  This procedure
16120 copies the given string into a special array for an old file name.
16121
16122 @c void mp_copy_old_name (MP mp,str_number s) {
16123   integer k; /* number of positions filled in |old_file_name| */
16124   pool_pointer j; /* index into |str_pool| */
16125   k=0;
16126   for (j=mp->str_start[s];j<=str_stop(s)-1;j++) { 
16127     incr(k);
16128     if ( k<=file_name_size ) 
16129       mp->old_file_name[k]=xchr(mp->str_pool[j]);
16130   }
16131   mp->old_file_name[++k] = 0;
16132 }
16133
16134 @ @<Glob...@>=
16135 char old_file_name[file_name_size+1];  /* analogous to |name_of_file| */
16136
16137 @ The following simple routine starts reading the \.{MPX} file associated
16138 with the current input file.
16139
16140 @c void mp_start_mpx_input (MP mp) {
16141   mp_pack_file_name(mp, in_name, in_area, ".mpx");
16142   @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16143     |goto not_found| if there is a problem@>;
16144   mp_begin_file_reading(mp);
16145   if ( ! mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16146     mp_end_file_reading(mp);
16147     goto NOT_FOUND;
16148   }
16149   name=mp_a_make_name_string(mp, cur_file);
16150   mp->mpx_name[index]=name; add_str_ref(name);
16151   @<Read the first line of the new file@>;
16152   return;
16153 NOT_FOUND: 
16154     @<Explain that the \.{MPX} file can't be read and |succumb|@>;
16155 }
16156
16157 @ This should ideally be changed to do whatever is necessary to create the
16158 \.{MPX} file given by |name_of_file| if it does not exist or if it is out
16159 of date.  This requires invoking \.{MPtoTeX} on the |old_file_name| and passing
16160 the results through \TeX\ and \.{DVItoMP}.  (It is possible to use a
16161 completely different typesetting program if suitable postprocessor is
16162 available to perform the function of \.{DVItoMP}.)
16163 @^system dependencies@>
16164
16165 @ @<Types...@>=
16166 typedef boolean (*run_make_mpx_command)(MP mp, char *origname, char *mtxname);
16167
16168 @ @<Glob...@>=
16169 run_make_mpx_command run_make_mpx;
16170
16171 @ @<Option variables@>=
16172 run_make_mpx_command run_make_mpx;
16173
16174 @ @<Allocate or initialize ...@>=
16175 set_callback_option(run_make_mpx);
16176
16177 @ @<Exported function headers@>=
16178 boolean mp_run_make_mpx (MP mp, char *origname, char *mtxname);
16179
16180 @ The default does nothing.
16181 @c 
16182 boolean mp_run_make_mpx (MP mp, char *origname, char *mtxname) {
16183   if (mp && origname && mtxname) /* for -W */
16184     return false;
16185   return false;
16186 }
16187
16188
16189
16190 @ @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16191   |goto not_found| if there is a problem@>=
16192 mp_copy_old_name(mp, name);
16193 if (!(mp->run_make_mpx)(mp, mp->old_file_name, mp->name_of_file))
16194    goto NOT_FOUND
16195
16196 @ @<Explain that the \.{MPX} file can't be read and |succumb|@>=
16197 if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16198 mp_print_nl(mp, ">> ");
16199 mp_print(mp, mp->old_file_name);
16200 mp_print_nl(mp, ">> ");
16201 mp_print(mp, mp->name_of_file);
16202 mp_print_nl(mp, "! Unable to make mpx file");
16203 help4("The two files given above are one of your source files")
16204   ("and an auxiliary file I need to read to find out what your")
16205   ("btex..etex blocks mean. If you don't know why I had trouble,")
16206   ("try running it manually through MPtoTeX, TeX, and DVItoMP");
16207 succumb;
16208
16209 @ The last file-opening commands are for files accessed via the \&{readfrom}
16210 @:read_from_}{\&{readfrom} primitive@>
16211 operator and the \&{write} command.  Such files are stored in separate arrays.
16212 @:write_}{\&{write} primitive@>
16213
16214 @<Types in the outer block@>=
16215 typedef unsigned int readf_index; /* |0..max_read_files| */
16216 typedef unsigned int write_index;  /* |0..max_write_files| */
16217
16218 @ @<Glob...@>=
16219 readf_index max_read_files; /* maximum number of simultaneously open \&{readfrom} files */
16220 FILE ** rd_file; /* \&{readfrom} files */
16221 char ** rd_fname; /* corresponding file name or 0 if file not open */
16222 readf_index read_files; /* number of valid entries in the above arrays */
16223 write_index max_write_files; /* maximum number of simultaneously open \&{write} */
16224 FILE ** wr_file; /* \&{write} files */
16225 char ** wr_fname; /* corresponding file name or 0 if file not open */
16226 write_index write_files; /* number of valid entries in the above arrays */
16227
16228 @ @<Allocate or initialize ...@>=
16229 mp->max_read_files=8;
16230 mp->rd_file = xmalloc((mp->max_read_files+1),sizeof(FILE *));
16231 mp->rd_fname = xmalloc((mp->max_read_files+1),sizeof(char *));
16232 memset(mp->rd_fname, 0, sizeof(char *)*(mp->max_read_files+1));
16233 mp->read_files=0;
16234 mp->max_write_files=8;
16235 mp->wr_file = xmalloc((mp->max_write_files+1),sizeof(FILE *));
16236 mp->wr_fname = xmalloc((mp->max_write_files+1),sizeof(char *));
16237 memset(mp->wr_fname, 0, sizeof(char *)*(mp->max_write_files+1));
16238 mp->write_files=0;
16239
16240
16241 @ This routine starts reading the file named by string~|s| without setting
16242 |loc|, |limit|, or |name|.  It returns |false| if the file is empty or cannot
16243 be opened.  Otherwise it updates |rd_file[n]| and |rd_fname[n]|.
16244
16245 @c boolean mp_start_read_input (MP mp,char *s, readf_index  n) {
16246   mp_ptr_scan_file(mp, s);
16247   pack_cur_name;
16248   mp_begin_file_reading(mp);
16249   if ( ! mp_a_open_in(mp, &mp->rd_file[n], mp_filetype_text) ) 
16250         goto NOT_FOUND;
16251   if ( ! mp_input_ln(mp, mp->rd_file[n], false) ) {
16252     fclose(mp->rd_file[n]); 
16253         goto NOT_FOUND; 
16254   }
16255   mp->rd_fname[n]=xstrdup(mp->name_of_file);
16256   return true;
16257 NOT_FOUND: 
16258   mp_end_file_reading(mp);
16259   return false;
16260 }
16261
16262 @ Open |wr_file[n]| using file name~|s| and update |wr_fname[n]|.
16263
16264 @<Declarations@>=
16265 void mp_open_write_file (MP mp, char *s, readf_index  n) ;
16266
16267 @ @c void mp_open_write_file (MP mp,char *s, readf_index  n) {
16268   mp_ptr_scan_file(mp, s);
16269   pack_cur_name;
16270   while ( ! mp_a_open_out(mp, &mp->wr_file[n], mp_filetype_text) )
16271     mp_prompt_file_name(mp, "file name for write output","");
16272   mp->wr_fname[n]=xstrdup(mp->name_of_file);
16273 }
16274
16275
16276 @* \[36] Introduction to the parsing routines.
16277 We come now to the central nervous system that sparks many of \MP's activities.
16278 By evaluating expressions, from their primary constituents to ever larger
16279 subexpressions, \MP\ builds the structures that ultimately define complete
16280 pictures or fonts of type.
16281
16282 Four mutually recursive subroutines are involved in this process: We call them
16283 $$\hbox{|scan_primary|, |scan_secondary|, |scan_tertiary|,
16284 and |scan_expression|.}$$
16285 @^recursion@>
16286 Each of them is parameterless and begins with the first token to be scanned
16287 already represented in |cur_cmd|, |cur_mod|, and |cur_sym|. After execution,
16288 the value of the primary or secondary or tertiary or expression that was
16289 found will appear in the global variables |cur_type| and |cur_exp|. The
16290 token following the expression will be represented in |cur_cmd|, |cur_mod|,
16291 and |cur_sym|.
16292
16293 Technically speaking, the parsing algorithms are ``LL(1),'' more or less;
16294 backup mechanisms have been added in order to provide reasonable error
16295 recovery.
16296
16297 @<Glob...@>=
16298 small_number cur_type; /* the type of the expression just found */
16299 integer cur_exp; /* the value of the expression just found */
16300
16301 @ @<Set init...@>=
16302 mp->cur_exp=0;
16303
16304 @ Many different kinds of expressions are possible, so it is wise to have
16305 precise descriptions of what |cur_type| and |cur_exp| mean in all cases:
16306
16307 \smallskip\hang
16308 |cur_type=mp_vacuous| means that this expression didn't turn out to have a
16309 value at all, because it arose from a \&{begingroup}$\,\ldots\,$\&{endgroup}
16310 construction in which there was no expression before the \&{endgroup}.
16311 In this case |cur_exp| has some irrelevant value.
16312
16313 \smallskip\hang
16314 |cur_type=mp_boolean_type| means that |cur_exp| is either |true_code|
16315 or |false_code|.
16316
16317 \smallskip\hang
16318 |cur_type=mp_unknown_boolean| means that |cur_exp| points to a capsule
16319 node that is in the ring of variables equivalent
16320 to at least one undefined boolean variable.
16321
16322 \smallskip\hang
16323 |cur_type=mp_string_type| means that |cur_exp| is a string number (i.e., an
16324 integer in the range |0<=cur_exp<str_ptr|). That string's reference count
16325 includes this particular reference.
16326
16327 \smallskip\hang
16328 |cur_type=mp_unknown_string| means that |cur_exp| points to a capsule
16329 node that is in the ring of variables equivalent
16330 to at least one undefined string variable.
16331
16332 \smallskip\hang
16333 |cur_type=mp_pen_type| means that |cur_exp| points to a node in a pen.  Nobody
16334 else points to any of the nodes in this pen.  The pen may be polygonal or
16335 elliptical.
16336
16337 \smallskip\hang
16338 |cur_type=mp_unknown_pen| means that |cur_exp| points to a capsule
16339 node that is in the ring of variables equivalent
16340 to at least one undefined pen variable.
16341
16342 \smallskip\hang
16343 |cur_type=mp_path_type| means that |cur_exp| points to a the first node of
16344 a path; nobody else points to this particular path. The control points of
16345 the path will have been chosen.
16346
16347 \smallskip\hang
16348 |cur_type=mp_unknown_path| means that |cur_exp| points to a capsule
16349 node that is in the ring of variables equivalent
16350 to at least one undefined path variable.
16351
16352 \smallskip\hang
16353 |cur_type=mp_picture_type| means that |cur_exp| points to an edge header node.
16354 There may be other pointers to this particular set of edges.  The header node
16355 contains a reference count that includes this particular reference.
16356
16357 \smallskip\hang
16358 |cur_type=mp_unknown_picture| means that |cur_exp| points to a capsule
16359 node that is in the ring of variables equivalent
16360 to at least one undefined picture variable.
16361
16362 \smallskip\hang
16363 |cur_type=mp_transform_type| means that |cur_exp| points to a |mp_transform_type|
16364 capsule node. The |value| part of this capsule
16365 points to a transform node that contains six numeric values,
16366 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16367
16368 \smallskip\hang
16369 |cur_type=mp_color_type| means that |cur_exp| points to a |color_type|
16370 capsule node. The |value| part of this capsule
16371 points to a color node that contains three numeric values,
16372 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16373
16374 \smallskip\hang
16375 |cur_type=mp_cmykcolor_type| means that |cur_exp| points to a |mp_cmykcolor_type|
16376 capsule node. The |value| part of this capsule
16377 points to a color node that contains four numeric values,
16378 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16379
16380 \smallskip\hang
16381 |cur_type=mp_pair_type| means that |cur_exp| points to a capsule
16382 node whose type is |mp_pair_type|. The |value| part of this capsule
16383 points to a pair node that contains two numeric values,
16384 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16385
16386 \smallskip\hang
16387 |cur_type=mp_known| means that |cur_exp| is a |scaled| value.
16388
16389 \smallskip\hang
16390 |cur_type=mp_dependent| means that |cur_exp| points to a capsule node whose type
16391 is |dependent|. The |dep_list| field in this capsule points to the associated
16392 dependency list.
16393
16394 \smallskip\hang
16395 |cur_type=mp_proto_dependent| means that |cur_exp| points to a |mp_proto_dependent|
16396 capsule node. The |dep_list| field in this capsule
16397 points to the associated dependency list.
16398
16399 \smallskip\hang
16400 |cur_type=independent| means that |cur_exp| points to a capsule node
16401 whose type is |independent|. This somewhat unusual case can arise, for
16402 example, in the expression
16403 `$x+\&{begingroup}\penalty0\,\&{string}\,x; 0\,\&{endgroup}$'.
16404
16405 \smallskip\hang
16406 |cur_type=mp_token_list| means that |cur_exp| points to a linked list of
16407 tokens. This case arises only on the left-hand side of an assignment
16408 (`\.{:=}') operation, under very special circumstances.
16409
16410 \smallskip\noindent
16411 The possible settings of |cur_type| have been listed here in increasing
16412 numerical order. Notice that |cur_type| will never be |mp_numeric_type| or
16413 |suffixed_macro| or |mp_unsuffixed_macro|, although variables of those types
16414 are allowed.  Conversely, \MP\ has no variables of type |mp_vacuous| or
16415 |token_list|.
16416
16417 @ Capsules are two-word nodes that have a similar meaning
16418 to |cur_type| and |cur_exp|. Such nodes have |name_type=capsule|
16419 and |link<=diov|; and their |type| field is one of the possibilities for
16420 |cur_type| listed above.
16421
16422 The |value| field of a capsule is, in most cases, the value that
16423 corresponds to its |type|, as |cur_exp| corresponds to |cur_type|.
16424 However, when |cur_exp| would point to a capsule,
16425 no extra layer of indirection is present; the |value|
16426 field is what would have been called |value(cur_exp)| if it had not been
16427 encapsulated.  Furthermore, if the type is |dependent| or
16428 |mp_proto_dependent|, the |value| field of a capsule is replaced by
16429 |dep_list| and |prev_dep| fields, since dependency lists in capsules are
16430 always part of the general |dep_list| structure.
16431
16432 The |get_x_next| routine is careful not to change the values of |cur_type|
16433 and |cur_exp| when it gets an expanded token. However, |get_x_next| might
16434 call a macro, which might parse an expression, which might execute lots of
16435 commands in a group; hence it's possible that |cur_type| might change
16436 from, say, |mp_unknown_boolean| to |mp_boolean_type|, or from |dependent| to
16437 |known| or |independent|, during the time |get_x_next| is called. The
16438 programs below are careful to stash sensitive intermediate results in
16439 capsules, so that \MP's generality doesn't cause trouble.
16440
16441 Here's a procedure that illustrates these conventions. It takes
16442 the contents of $(|cur_type|\kern-.3pt,|cur_exp|\kern-.3pt)$
16443 and stashes them away in a
16444 capsule. It is not used when |cur_type=mp_token_list|.
16445 After the operation, |cur_type=mp_vacuous|; hence there is no need to
16446 copy path lists or to update reference counts, etc.
16447
16448 The special link |diov| is put on the capsule returned by
16449 |stash_cur_exp|, because this procedure is used to store macro parameters
16450 that must be easily distinguishable from token lists.
16451
16452 @<Declare the stashing/unstashing routines@>=
16453 pointer mp_stash_cur_exp (MP mp) {
16454   pointer p; /* the capsule that will be returned */
16455   switch (mp->cur_type) {
16456   case unknown_types:
16457   case mp_transform_type:
16458   case mp_color_type:
16459   case mp_pair_type:
16460   case mp_dependent:
16461   case mp_proto_dependent:
16462   case mp_independent: 
16463   case mp_cmykcolor_type:
16464     p=mp->cur_exp;
16465     break;
16466   default: 
16467     p=mp_get_node(mp, value_node_size); name_type(p)=mp_capsule;
16468     type(p)=mp->cur_type; value(p)=mp->cur_exp;
16469     break;
16470   }
16471   mp->cur_type=mp_vacuous; link(p)=diov; 
16472   return p;
16473 }
16474
16475 @ The inverse of |stash_cur_exp| is the following procedure, which
16476 deletes an unnecessary capsule and puts its contents into |cur_type|
16477 and |cur_exp|.
16478
16479 The program steps of \MP\ can be divided into two categories: those in
16480 which |cur_type| and |cur_exp| are ``alive'' and those in which they are
16481 ``dead,'' in the sense that |cur_type| and |cur_exp| contain relevant
16482 information or not. It's important not to ignore them when they're alive,
16483 and it's important not to pay attention to them when they're dead.
16484
16485 There's also an intermediate category: If |cur_type=mp_vacuous|, then
16486 |cur_exp| is irrelevant, hence we can proceed without caring if |cur_type|
16487 and |cur_exp| are alive or dead. In such cases we say that |cur_type|
16488 and |cur_exp| are {\sl dormant}. It is permissible to call |get_x_next|
16489 only when they are alive or dormant.
16490
16491 The \\{stash} procedure above assumes that |cur_type| and |cur_exp|
16492 are alive or dormant. The \\{unstash} procedure assumes that they are
16493 dead or dormant; it resuscitates them.
16494
16495 @<Declare the stashing/unstashing...@>=
16496 void mp_unstash_cur_exp (MP mp,pointer p) ;
16497
16498 @ @c
16499 void mp_unstash_cur_exp (MP mp,pointer p) { 
16500   mp->cur_type=type(p);
16501   switch (mp->cur_type) {
16502   case unknown_types:
16503   case mp_transform_type:
16504   case mp_color_type:
16505   case mp_pair_type:
16506   case mp_dependent: 
16507   case mp_proto_dependent:
16508   case mp_independent:
16509   case mp_cmykcolor_type: 
16510     mp->cur_exp=p;
16511     break;
16512   default:
16513     mp->cur_exp=value(p);
16514     mp_free_node(mp, p,value_node_size);
16515     break;
16516   }
16517 }
16518
16519 @ The following procedure prints the values of expressions in an
16520 abbreviated format. If its first parameter |p| is null, the value of
16521 |(cur_type,cur_exp)| is displayed; otherwise |p| should be a capsule
16522 containing the desired value. The second parameter controls the amount of
16523 output. If it is~0, dependency lists will be abbreviated to
16524 `\.{linearform}' unless they consist of a single term.  If it is greater
16525 than~1, complicated structures (pens, pictures, and paths) will be displayed
16526 in full.
16527
16528 @<Declare subroutines for printing expressions@>=
16529 @<Declare the procedure called |print_dp|@>;
16530 @<Declare the stashing/unstashing routines@>;
16531 void mp_print_exp (MP mp,pointer p, small_number verbosity) {
16532   boolean restore_cur_exp; /* should |cur_exp| be restored? */
16533   small_number t; /* the type of the expression */
16534   pointer q; /* a big node being displayed */
16535   integer v=0; /* the value of the expression */
16536   if ( p!=null ) {
16537     restore_cur_exp=false;
16538   } else { 
16539     p=mp_stash_cur_exp(mp); restore_cur_exp=true;
16540   }
16541   t=type(p);
16542   if ( t<mp_dependent ) v=value(p); else if ( t<mp_independent ) v=dep_list(p);
16543   @<Print an abbreviated value of |v| with format depending on |t|@>;
16544   if ( restore_cur_exp ) mp_unstash_cur_exp(mp, p);
16545 }
16546
16547 @ @<Print an abbreviated value of |v| with format depending on |t|@>=
16548 switch (t) {
16549 case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
16550 case mp_boolean_type:
16551   if ( v==true_code ) mp_print(mp, "true"); else mp_print(mp, "false");
16552   break;
16553 case unknown_types: case mp_numeric_type:
16554   @<Display a variable that's been declared but not defined@>;
16555   break;
16556 case mp_string_type:
16557   mp_print_char(mp, '"'); mp_print_str(mp, v); mp_print_char(mp, '"');
16558   break;
16559 case mp_pen_type: case mp_path_type: case mp_picture_type:
16560   @<Display a complex type@>;
16561   break;
16562 case mp_transform_type: case mp_color_type: case mp_pair_type: case mp_cmykcolor_type:
16563   if ( v==null ) mp_print_type(mp, t);
16564   else @<Display a big node@>;
16565   break;
16566 case mp_known:mp_print_scaled(mp, v); break;
16567 case mp_dependent: case mp_proto_dependent:
16568   mp_print_dp(mp, t,v,verbosity);
16569   break;
16570 case mp_independent:mp_print_variable_name(mp, p); break;
16571 default: mp_confusion(mp, "exp"); break;
16572 @:this can't happen exp}{\quad exp@>
16573 }
16574
16575 @ @<Display a big node@>=
16576
16577   mp_print_char(mp, '('); q=v+mp->big_node_size[t];
16578   do {  
16579     if ( type(v)==mp_known ) mp_print_scaled(mp, value(v));
16580     else if ( type(v)==mp_independent ) mp_print_variable_name(mp, v);
16581     else mp_print_dp(mp, type(v),dep_list(v),verbosity);
16582     v=v+2;
16583     if ( v!=q ) mp_print_char(mp, ',');
16584   } while (v!=q);
16585   mp_print_char(mp, ')');
16586 }
16587
16588 @ Values of type \&{picture}, \&{path}, and \&{pen} are displayed verbosely
16589 in the log file only, unless the user has given a positive value to
16590 \\{tracingonline}.
16591
16592 @<Display a complex type@>=
16593 if ( verbosity<=1 ) {
16594   mp_print_type(mp, t);
16595 } else { 
16596   if ( mp->selector==term_and_log )
16597    if ( mp->internal[tracing_online]<=0 ) {
16598     mp->selector=term_only;
16599     mp_print_type(mp, t); mp_print(mp, " (see the transcript file)");
16600     mp->selector=term_and_log;
16601   };
16602   switch (t) {
16603   case mp_pen_type:mp_print_pen(mp, v,"",false); break;
16604   case mp_path_type:mp_print_path(mp, v,"",false); break;
16605   case mp_picture_type:mp_print_edges(mp, v,"",false); break;
16606   } /* there are no other cases */
16607 }
16608
16609 @ @<Declare the procedure called |print_dp|@>=
16610 void mp_print_dp (MP mp,small_number t, pointer p, 
16611                   small_number verbosity)  {
16612   pointer q; /* the node following |p| */
16613   q=link(p);
16614   if ( (info(q)==null) || (verbosity>0) ) mp_print_dependency(mp, p,t);
16615   else mp_print(mp, "linearform");
16616 }
16617
16618 @ The displayed name of a variable in a ring will not be a capsule unless
16619 the ring consists entirely of capsules.
16620
16621 @<Display a variable that's been declared but not defined@>=
16622 { mp_print_type(mp, t);
16623 if ( v!=null )
16624   { mp_print_char(mp, ' ');
16625   while ( (name_type(v)==mp_capsule) && (v!=p) ) v=value(v);
16626   mp_print_variable_name(mp, v);
16627   };
16628 }
16629
16630 @ When errors are detected during parsing, it is often helpful to
16631 display an expression just above the error message, using |exp_err|
16632 or |disp_err| instead of |print_err|.
16633
16634 @d exp_err(A) mp_disp_err(mp, null,(A)) /* displays the current expression */
16635
16636 @<Declare subroutines for printing expressions@>=
16637 void mp_disp_err (MP mp,pointer p, char *s) { 
16638   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16639   mp_print_nl(mp, ">> ");
16640 @.>>@>
16641   mp_print_exp(mp, p,1); /* ``medium verbose'' printing of the expression */
16642   if (strlen(s)) { 
16643     mp_print_nl(mp, "! "); mp_print(mp, s);
16644 @.!\relax@>
16645   }
16646 }
16647
16648 @ If |cur_type| and |cur_exp| contain relevant information that should
16649 be recycled, we will use the following procedure, which changes |cur_type|
16650 to |known| and stores a given value in |cur_exp|. We can think of |cur_type|
16651 and |cur_exp| as either alive or dormant after this has been done,
16652 because |cur_exp| will not contain a pointer value.
16653
16654 @ @c void mp_flush_cur_exp (MP mp,scaled v) { 
16655   switch (mp->cur_type) {
16656   case unknown_types: case mp_transform_type: case mp_color_type: case mp_pair_type:
16657   case mp_dependent: case mp_proto_dependent: case mp_independent: case mp_cmykcolor_type:
16658     mp_recycle_value(mp, mp->cur_exp); 
16659     mp_free_node(mp, mp->cur_exp,value_node_size);
16660     break;
16661   case mp_string_type:
16662     delete_str_ref(mp->cur_exp); break;
16663   case mp_pen_type: case mp_path_type: 
16664     mp_toss_knot_list(mp, mp->cur_exp); break;
16665   case mp_picture_type:
16666     delete_edge_ref(mp->cur_exp); break;
16667   default: 
16668     break;
16669   }
16670   mp->cur_type=mp_known; mp->cur_exp=v;
16671 }
16672
16673 @ There's a much more general procedure that is capable of releasing
16674 the storage associated with any two-word value packet.
16675
16676 @<Declare the recycling subroutines@>=
16677 void mp_recycle_value (MP mp,pointer p) ;
16678
16679 @ @c void mp_recycle_value (MP mp,pointer p) {
16680   small_number t; /* a type code */
16681   integer vv; /* another value */
16682   pointer q,r,s,pp; /* link manipulation registers */
16683   integer v=0; /* a value */
16684   t=type(p);
16685   if ( t<mp_dependent ) v=value(p);
16686   switch (t) {
16687   case undefined: case mp_vacuous: case mp_boolean_type: case mp_known:
16688   case mp_numeric_type:
16689     break;
16690   case unknown_types:
16691     mp_ring_delete(mp, p); break;
16692   case mp_string_type:
16693     delete_str_ref(v); break;
16694   case mp_path_type: case mp_pen_type:
16695     mp_toss_knot_list(mp, v); break;
16696   case mp_picture_type:
16697     delete_edge_ref(v); break;
16698   case mp_cmykcolor_type: case mp_pair_type: case mp_color_type:
16699   case mp_transform_type:
16700     @<Recycle a big node@>; break; 
16701   case mp_dependent: case mp_proto_dependent:
16702     @<Recycle a dependency list@>; break;
16703   case mp_independent:
16704     @<Recycle an independent variable@>; break;
16705   case mp_token_list: case mp_structured:
16706     mp_confusion(mp, "recycle"); break;
16707 @:this can't happen recycle}{\quad recycle@>
16708   case mp_unsuffixed_macro: case mp_suffixed_macro:
16709     mp_delete_mac_ref(mp, value(p)); break;
16710   } /* there are no other cases */
16711   type(p)=undefined;
16712 }
16713
16714 @ @<Recycle a big node@>=
16715 if ( v!=null ){ 
16716   q=v+mp->big_node_size[t];
16717   do {  
16718     q=q-2; mp_recycle_value(mp, q);
16719   } while (q!=v);
16720   mp_free_node(mp, v,mp->big_node_size[t]);
16721 }
16722
16723 @ @<Recycle a dependency list@>=
16724
16725   q=dep_list(p);
16726   while ( info(q)!=null ) q=link(q);
16727   link(prev_dep(p))=link(q);
16728   prev_dep(link(q))=prev_dep(p);
16729   link(q)=null; mp_flush_node_list(mp, dep_list(p));
16730 }
16731
16732 @ When an independent variable disappears, it simply fades away, unless
16733 something depends on it. In the latter case, a dependent variable whose
16734 coefficient of dependence is maximal will take its place.
16735 The relevant algorithm is due to Ignacio~A. Zabala, who implemented it
16736 as part of his Ph.D. thesis (Stanford University, December 1982).
16737 @^Zabala Salelles, Ignacio Andres@>
16738
16739 For example, suppose that variable $x$ is being recycled, and that the
16740 only variables depending on~$x$ are $y=2x+a$ and $z=x+b$. In this case
16741 we want to make $y$ independent and $z=.5y-.5a+b$; no other variables
16742 will depend on~$y$. If $\\{tracingequations}>0$ in this situation,
16743 we will print `\.{\#\#\# -2x=-y+a}'.
16744
16745 There's a slight complication, however: An independent variable $x$
16746 can occur both in dependency lists and in proto-dependency lists.
16747 This makes it necessary to be careful when deciding which coefficient
16748 is maximal.
16749
16750 Furthermore, this complication is not so slight when
16751 a proto-dependent variable is chosen to become independent. For example,
16752 suppose that $y=2x+100a$ is proto-dependent while $z=x+b$ is dependent;
16753 then we must change $z=.5y-50a+b$ to a proto-dependency, because of the
16754 large coefficient `50'.
16755
16756 In order to deal with these complications without wasting too much time,
16757 we shall link together the occurrences of~$x$ among all the linear
16758 dependencies, maintaining separate lists for the dependent and
16759 proto-dependent cases.
16760
16761 @<Recycle an independent variable@>=
16762
16763   mp->max_c[mp_dependent]=0; mp->max_c[mp_proto_dependent]=0;
16764   mp->max_link[mp_dependent]=null; mp->max_link[mp_proto_dependent]=null;
16765   q=link(dep_head);
16766   while ( q!=dep_head ) { 
16767     s=value_loc(q); /* now |link(s)=dep_list(q)| */
16768     while (1) { 
16769       r=link(s);
16770       if ( info(r)==null ) break;;
16771       if ( info(r)!=p ) { 
16772        s=r;
16773       } else  { 
16774         t=type(q); link(s)=link(r); info(r)=q;
16775         if ( abs(value(r))>mp->max_c[t] ) {
16776           @<Record a new maximum coefficient of type |t|@>;
16777         } else { 
16778           link(r)=mp->max_link[t]; mp->max_link[t]=r;
16779         }
16780       }
16781     }   
16782     q=link(r);
16783   }
16784   if ( (mp->max_c[mp_dependent]>0)||(mp->max_c[mp_proto_dependent]>0) ) {
16785     @<Choose a dependent variable to take the place of the disappearing
16786     independent variable, and change all remaining dependencies
16787     accordingly@>;
16788   }
16789 }
16790
16791 @ The code for independency removal makes use of three two-word arrays.
16792
16793 @<Glob...@>=
16794 integer max_c[mp_proto_dependent+1];  /* max coefficient magnitude */
16795 pointer max_ptr[mp_proto_dependent+1]; /* where |p| occurs with |max_c| */
16796 pointer max_link[mp_proto_dependent+1]; /* other occurrences of |p| */
16797
16798 @ @<Record a new maximum coefficient...@>=
16799
16800   if ( mp->max_c[t]>0 ) {
16801     link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
16802   }
16803   mp->max_c[t]=abs(value(r)); mp->max_ptr[t]=r;
16804 }
16805
16806 @ @<Choose a dependent...@>=
16807
16808   if ( (mp->max_c[mp_dependent] / 010000 >= mp->max_c[mp_proto_dependent]) )
16809     t=mp_dependent;
16810   else 
16811     t=mp_proto_dependent;
16812   @<Determine the dependency list |s| to substitute for the independent
16813     variable~|p|@>;
16814   t=mp_dependent+mp_proto_dependent-t; /* complement |t| */
16815   if ( mp->max_c[t]>0 ) { /* we need to pick up an unchosen dependency */ 
16816     link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
16817   }
16818   if ( t!=mp_dependent ) { @<Substitute new dependencies in place of |p|@>; }
16819   else { @<Substitute new proto-dependencies in place of |p|@>;}
16820   mp_flush_node_list(mp, s);
16821   if ( mp->fix_needed ) mp_fix_dependencies(mp);
16822   check_arith;
16823 }
16824
16825 @ Let |s=max_ptr[t]|. At this point we have $|value|(s)=\pm|max_c|[t]$,
16826 and |info(s)| points to the dependent variable~|pp| of type~|t| from
16827 whose dependency list we have removed node~|s|. We must reinsert
16828 node~|s| into the dependency list, with coefficient $-1.0$, and with
16829 |pp| as the new independent variable. Since |pp| will have a larger serial
16830 number than any other variable, we can put node |s| at the head of the
16831 list.
16832
16833 @<Determine the dep...@>=
16834 s=mp->max_ptr[t]; pp=info(s); v=value(s);
16835 if ( t==mp_dependent ) value(s)=-fraction_one; else value(s)=-unity;
16836 r=dep_list(pp); link(s)=r;
16837 while ( info(r)!=null ) r=link(r);
16838 q=link(r); link(r)=null;
16839 prev_dep(q)=prev_dep(pp); link(prev_dep(pp))=q;
16840 new_indep(pp);
16841 if ( mp->cur_exp==pp ) if ( mp->cur_type==t ) mp->cur_type=mp_independent;
16842 if ( mp->internal[tracing_equations]>0 ) { 
16843   @<Show the transformed dependency@>; 
16844 }
16845
16846 @ Now $(-v)$ times the formerly independent variable~|p| is being replaced
16847 by the dependency list~|s|.
16848
16849 @<Show the transformed...@>=
16850 if ( mp_interesting(mp, p) ) {
16851   mp_begin_diagnostic(mp); mp_print_nl(mp, "### ");
16852 @:]]]\#\#\#_}{\.{\#\#\#}@>
16853   if ( v>0 ) mp_print_char(mp, '-');
16854   if ( t==mp_dependent ) vv=mp_round_fraction(mp, mp->max_c[mp_dependent]);
16855   else vv=mp->max_c[mp_proto_dependent];
16856   if ( vv!=unity ) mp_print_scaled(mp, vv);
16857   mp_print_variable_name(mp, p);
16858   while ( value(p) % s_scale>0 ) {
16859     mp_print(mp, "*4"); value(p)=value(p)-2;
16860   }
16861   if ( t==mp_dependent ) mp_print_char(mp, '='); else mp_print(mp, " = ");
16862   mp_print_dependency(mp, s,t);
16863   mp_end_diagnostic(mp, false);
16864 }
16865
16866 @ Finally, there are dependent and proto-dependent variables whose
16867 dependency lists must be brought up to date.
16868
16869 @<Substitute new dependencies...@>=
16870 for (t=mp_dependent;t<=mp_proto_dependent;t++){ 
16871   r=mp->max_link[t];
16872   while ( r!=null ) {
16873     q=info(r);
16874     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
16875      mp_make_fraction(mp, value(r),-v),s,t,mp_dependent);
16876     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
16877     q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
16878   }
16879 }
16880
16881 @ @<Substitute new proto...@>=
16882 for (t=mp_dependent;t<=mp_proto_dependent;t++) {
16883   r=mp->max_link[t];
16884   while ( r!=null ) {
16885     q=info(r);
16886     if ( t==mp_dependent ) { /* for safety's sake, we change |q| to |mp_proto_dependent| */
16887       if ( mp->cur_exp==q ) if ( mp->cur_type==mp_dependent )
16888         mp->cur_type=mp_proto_dependent;
16889       dep_list(q)=mp_p_over_v(mp, dep_list(q),unity,mp_dependent,mp_proto_dependent);
16890       type(q)=mp_proto_dependent; value(r)=mp_round_fraction(mp, value(r));
16891     }
16892     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
16893       mp_make_scaled(mp, value(r),-v),s,mp_proto_dependent,mp_proto_dependent);
16894     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
16895     q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
16896   }
16897 }
16898
16899 @ Here are some routines that provide handy combinations of actions
16900 that are often needed during error recovery. For example,
16901 `|flush_error|' flushes the current expression, replaces it by
16902 a given value, and calls |error|.
16903
16904 Errors often are detected after an extra token has already been scanned.
16905 The `\\{put\_get}' routines put that token back before calling |error|;
16906 then they get it back again. (Or perhaps they get another token, if
16907 the user has changed things.)
16908
16909 @<Declarations@>=
16910 void mp_flush_error (MP mp,scaled v);
16911 void mp_put_get_error (MP mp);
16912 void mp_put_get_flush_error (MP mp,scaled v) ;
16913
16914 @ @c
16915 void mp_flush_error (MP mp,scaled v) { 
16916   mp_error(mp); mp_flush_cur_exp(mp, v); 
16917 }
16918 void mp_put_get_error (MP mp) { 
16919   mp_back_error(mp); mp_get_x_next(mp); 
16920 }
16921 void mp_put_get_flush_error (MP mp,scaled v) { 
16922   mp_put_get_error(mp);
16923   mp_flush_cur_exp(mp, v); 
16924 }
16925
16926 @ A global variable |var_flag| is set to a special command code
16927 just before \MP\ calls |scan_expression|, if the expression should be
16928 treated as a variable when this command code immediately follows. For
16929 example, |var_flag| is set to |assignment| at the beginning of a
16930 statement, because we want to know the {\sl location\/} of a variable at
16931 the left of `\.{:=}', not the {\sl value\/} of that variable.
16932
16933 The |scan_expression| subroutine calls |scan_tertiary|,
16934 which calls |scan_secondary|, which calls |scan_primary|, which sets
16935 |var_flag:=0|. In this way each of the scanning routines ``knows''
16936 when it has been called with a special |var_flag|, but |var_flag| is
16937 usually zero.
16938
16939 A variable preceding a command that equals |var_flag| is converted to a
16940 token list rather than a value. Furthermore, an `\.{=}' sign following an
16941 expression with |var_flag=assignment| is not considered to be a relation
16942 that produces boolean expressions.
16943
16944
16945 @<Glob...@>=
16946 int var_flag; /* command that wants a variable */
16947
16948 @ @<Set init...@>=
16949 mp->var_flag=0;
16950
16951 @* \[37] Parsing primary expressions.
16952 The first parsing routine, |scan_primary|, is also the most complicated one,
16953 since it involves so many different cases. But each case---with one
16954 exception---is fairly simple by itself.
16955
16956 When |scan_primary| begins, the first token of the primary to be scanned
16957 should already appear in |cur_cmd|, |cur_mod|, and |cur_sym|. The values
16958 of |cur_type| and |cur_exp| should be either dead or dormant, as explained
16959 earlier. If |cur_cmd| is not between |min_primary_command| and
16960 |max_primary_command|, inclusive, a syntax error will be signaled.
16961
16962 @<Declare the basic parsing subroutines@>=
16963 void mp_scan_primary (MP mp) {
16964   pointer p,q,r; /* for list manipulation */
16965   quarterword c; /* a primitive operation code */
16966   int my_var_flag; /* initial value of |my_var_flag| */
16967   pointer l_delim,r_delim; /* hash addresses of a delimiter pair */
16968   @<Other local variables for |scan_primary|@>;
16969   my_var_flag=mp->var_flag; mp->var_flag=0;
16970 RESTART:
16971   check_arith;
16972   @<Supply diagnostic information, if requested@>;
16973   switch (mp->cur_cmd) {
16974   case left_delimiter:
16975     @<Scan a delimited primary@>; break;
16976   case begin_group:
16977     @<Scan a grouped primary@>; break;
16978   case string_token:
16979     @<Scan a string constant@>; break;
16980   case numeric_token:
16981     @<Scan a primary that starts with a numeric token@>; break;
16982   case nullary:
16983     @<Scan a nullary operation@>; break;
16984   case unary: case type_name: case cycle: case plus_or_minus:
16985     @<Scan a unary operation@>; break;
16986   case primary_binary:
16987     @<Scan a binary operation with `\&{of}' between its operands@>; break;
16988   case str_op:
16989     @<Convert a suffix to a string@>; break;
16990   case internal_quantity:
16991     @<Scan an internal numeric quantity@>; break;
16992   case capsule_token:
16993     mp_make_exp_copy(mp, mp->cur_mod); break;
16994   case tag_token:
16995     @<Scan a variable primary; |goto restart| if it turns out to be a macro@>; break;
16996   default: 
16997     mp_bad_exp(mp, "A primary"); goto RESTART; break;
16998 @.A primary expression...@>
16999   }
17000   mp_get_x_next(mp); /* the routines |goto done| if they don't want this */
17001 DONE: 
17002   if ( mp->cur_cmd==left_bracket ) {
17003     if ( mp->cur_type>=mp_known ) {
17004       @<Scan a mediation construction@>;
17005     }
17006   }
17007 }
17008
17009
17010
17011 @ Errors at the beginning of expressions are flagged by |bad_exp|.
17012
17013 @c void mp_bad_exp (MP mp,char * s) {
17014   int save_flag;
17015   print_err(s); mp_print(mp, " expression can't begin with `");
17016   mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); 
17017   mp_print_char(mp, '\'');
17018   help4("I'm afraid I need some sort of value in order to continue,")
17019     ("so I've tentatively inserted `0'. You may want to")
17020     ("delete this zero and insert something else;")
17021     ("see Chapter 27 of The METAFONTbook for an example.");
17022 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
17023   mp_back_input(mp); mp->cur_sym=0; mp->cur_cmd=numeric_token; 
17024   mp->cur_mod=0; mp_ins_error(mp);
17025   save_flag=mp->var_flag; mp->var_flag=0; mp_get_x_next(mp);
17026   mp->var_flag=save_flag;
17027 }
17028
17029 @ @<Supply diagnostic information, if requested@>=
17030 #ifdef DEBUG
17031 if ( mp->panicking ) mp_check_mem(mp, false);
17032 #endif
17033 if ( mp->interrupt!=0 ) if ( mp->OK_to_interrupt ) {
17034   mp_back_input(mp); check_interrupt; mp_get_x_next(mp);
17035 }
17036
17037 @ @<Scan a delimited primary@>=
17038
17039   l_delim=mp->cur_sym; r_delim=mp->cur_mod; 
17040   mp_get_x_next(mp); mp_scan_expression(mp);
17041   if ( (mp->cur_cmd==comma) && (mp->cur_type>=mp_known) ) {
17042     @<Scan the rest of a delimited set of numerics@>;
17043   } else {
17044     mp_check_delimiter(mp, l_delim,r_delim);
17045   }
17046 }
17047
17048 @ The |stash_in| subroutine puts the current (numeric) expression into a field
17049 within a ``big node.''
17050
17051 @c void mp_stash_in (MP mp,pointer p) {
17052   pointer q; /* temporary register */
17053   type(p)=mp->cur_type;
17054   if ( mp->cur_type==mp_known ) {
17055     value(p)=mp->cur_exp;
17056   } else { 
17057     if ( mp->cur_type==mp_independent ) {
17058       @<Stash an independent |cur_exp| into a big node@>;
17059     } else { 
17060       mp->mem[value_loc(p)]=mp->mem[value_loc(mp->cur_exp)];
17061       /* |dep_list(p):=dep_list(cur_exp)| and |prev_dep(p):=prev_dep(cur_exp)| */
17062       link(prev_dep(p))=p;
17063     }
17064     mp_free_node(mp, mp->cur_exp,value_node_size);
17065   }
17066   mp->cur_type=mp_vacuous;
17067 }
17068
17069 @ In rare cases the current expression can become |independent|. There
17070 may be many dependency lists pointing to such an independent capsule,
17071 so we can't simply move it into place within a big node. Instead,
17072 we copy it, then recycle it.
17073
17074 @ @<Stash an independent |cur_exp|...@>=
17075
17076   q=mp_single_dependency(mp, mp->cur_exp);
17077   if ( q==mp->dep_final ){ 
17078     type(p)=mp_known; value(p)=0; mp_free_node(mp, q,dep_node_size);
17079   } else { 
17080     type(p)=mp_dependent; mp_new_dep(mp, p,q);
17081   }
17082   mp_recycle_value(mp, mp->cur_exp);
17083 }
17084
17085 @ This code uses the fact that |red_part_loc| and |green_part_loc|
17086 are synonymous with |x_part_loc| and |y_part_loc|.
17087
17088 @<Scan the rest of a delimited set of numerics@>=
17089
17090 p=mp_stash_cur_exp(mp);
17091 mp_get_x_next(mp); mp_scan_expression(mp);
17092 @<Make sure the second part of a pair or color has a numeric type@>;
17093 q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
17094 if ( mp->cur_cmd==comma ) type(q)=mp_color_type;
17095 else type(q)=mp_pair_type;
17096 mp_init_big_node(mp, q); r=value(q);
17097 mp_stash_in(mp, y_part_loc(r));
17098 mp_unstash_cur_exp(mp, p);
17099 mp_stash_in(mp, x_part_loc(r));
17100 if ( mp->cur_cmd==comma ) {
17101   @<Scan the last of a triplet of numerics@>;
17102 }
17103 if ( mp->cur_cmd==comma ) {
17104   type(q)=mp_cmykcolor_type;
17105   mp_init_big_node(mp, q); t=value(q);
17106   mp->mem[cyan_part_loc(t)]=mp->mem[red_part_loc(r)];
17107   value(cyan_part_loc(t))=value(red_part_loc(r));
17108   mp->mem[magenta_part_loc(t)]=mp->mem[green_part_loc(r)];
17109   value(magenta_part_loc(t))=value(green_part_loc(r));
17110   mp->mem[yellow_part_loc(t)]=mp->mem[blue_part_loc(r)];
17111   value(yellow_part_loc(t))=value(blue_part_loc(r));
17112   mp_recycle_value(mp, r);
17113   r=t;
17114   @<Scan the last of a quartet of numerics@>;
17115 }
17116 mp_check_delimiter(mp, l_delim,r_delim);
17117 mp->cur_type=type(q);
17118 mp->cur_exp=q;
17119 }
17120
17121 @ @<Make sure the second part of a pair or color has a numeric type@>=
17122 if ( mp->cur_type<mp_known ) {
17123   exp_err("Nonnumeric ypart has been replaced by 0");
17124 @.Nonnumeric...replaced by 0@>
17125   help4("I've started to scan a pair `(a,b)' or a color `(a,b,c)';")
17126     ("but after finding a nice `a' I found a `b' that isn't")
17127     ("of numeric type. So I've changed that part to zero.")
17128     ("(The b that I didn't like appears above the error message.)");
17129   mp_put_get_flush_error(mp, 0);
17130 }
17131
17132 @ @<Scan the last of a triplet of numerics@>=
17133
17134   mp_get_x_next(mp); mp_scan_expression(mp);
17135   if ( mp->cur_type<mp_known ) {
17136     exp_err("Nonnumeric third part has been replaced by 0");
17137 @.Nonnumeric...replaced by 0@>
17138     help3("I've just scanned a color `(a,b,c)' or cmykcolor(a,b,c,d); but the `c'")
17139       ("isn't of numeric type. So I've changed that part to zero.")
17140       ("(The c that I didn't like appears above the error message.)");
17141     mp_put_get_flush_error(mp, 0);
17142   }
17143   mp_stash_in(mp, blue_part_loc(r));
17144 }
17145
17146 @ @<Scan the last of a quartet of numerics@>=
17147
17148   mp_get_x_next(mp); mp_scan_expression(mp);
17149   if ( mp->cur_type<mp_known ) {
17150     exp_err("Nonnumeric blackpart has been replaced by 0");
17151 @.Nonnumeric...replaced by 0@>
17152     help3("I've just scanned a cmykcolor `(c,m,y,k)'; but the `k' isn't")
17153       ("of numeric type. So I've changed that part to zero.")
17154       ("(The k that I didn't like appears above the error message.)");
17155     mp_put_get_flush_error(mp, 0);
17156   }
17157   mp_stash_in(mp, black_part_loc(r));
17158 }
17159
17160 @ The local variable |group_line| keeps track of the line
17161 where a \&{begingroup} command occurred; this will be useful
17162 in an error message if the group doesn't actually end.
17163
17164 @<Other local variables for |scan_primary|@>=
17165 integer group_line; /* where a group began */
17166
17167 @ @<Scan a grouped primary@>=
17168
17169   group_line=mp_true_line(mp);
17170   if ( mp->internal[tracing_commands]>0 ) show_cur_cmd_mod;
17171   save_boundary_item(p);
17172   do {  
17173     mp_do_statement(mp); /* ends with |cur_cmd>=semicolon| */
17174   } while (! (mp->cur_cmd!=semicolon));
17175   if ( mp->cur_cmd!=end_group ) {
17176     print_err("A group begun on line ");
17177 @.A group...never ended@>
17178     mp_print_int(mp, group_line);
17179     mp_print(mp, " never ended");
17180     help2("I saw a `begingroup' back there that hasn't been matched")
17181          ("by `endgroup'. So I've inserted `endgroup' now.");
17182     mp_back_error(mp); mp->cur_cmd=end_group;
17183   }
17184   mp_unsave(mp); 
17185     /* this might change |cur_type|, if independent variables are recycled */
17186   if ( mp->internal[tracing_commands]>0 ) show_cur_cmd_mod;
17187 }
17188
17189 @ @<Scan a string constant@>=
17190
17191   mp->cur_type=mp_string_type; mp->cur_exp=mp->cur_mod;
17192 }
17193
17194 @ Later we'll come to procedures that perform actual operations like
17195 addition, square root, and so on; our purpose now is to do the parsing.
17196 But we might as well mention those future procedures now, so that the
17197 suspense won't be too bad:
17198
17199 \smallskip
17200 |do_nullary(c)| does primitive operations that have no operands (e.g.,
17201 `\&{true}' or `\&{pencircle}');
17202
17203 \smallskip
17204 |do_unary(c)| applies a primitive operation to the current expression;
17205
17206 \smallskip
17207 |do_binary(p,c)| applies a primitive operation to the capsule~|p|
17208 and the current expression.
17209
17210 @<Scan a nullary operation@>=mp_do_nullary(mp, mp->cur_mod)
17211
17212 @ @<Scan a unary operation@>=
17213
17214   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_primary(mp); 
17215   mp_do_unary(mp, c); goto DONE;
17216 }
17217
17218 @ A numeric token might be a primary by itself, or it might be the
17219 numerator of a fraction composed solely of numeric tokens, or it might
17220 multiply the primary that follows (provided that the primary doesn't begin
17221 with a plus sign or a minus sign). The code here uses the facts that
17222 |max_primary_command=plus_or_minus| and
17223 |max_primary_command-1=numeric_token|. If a fraction is found that is less
17224 than unity, we try to retain higher precision when we use it in scalar
17225 multiplication.
17226
17227 @<Other local variables for |scan_primary|@>=
17228 scaled num,denom; /* for primaries that are fractions, like `1/2' */
17229
17230 @ @<Scan a primary that starts with a numeric token@>=
17231
17232   mp->cur_exp=mp->cur_mod; mp->cur_type=mp_known; mp_get_x_next(mp);
17233   if ( mp->cur_cmd!=slash ) { 
17234     num=0; denom=0;
17235   } else { 
17236     mp_get_x_next(mp);
17237     if ( mp->cur_cmd!=numeric_token ) { 
17238       mp_back_input(mp);
17239       mp->cur_cmd=slash; mp->cur_mod=over; mp->cur_sym=frozen_slash;
17240       goto DONE;
17241     }
17242     num=mp->cur_exp; denom=mp->cur_mod;
17243     if ( denom==0 ) { @<Protest division by zero@>; }
17244     else { mp->cur_exp=mp_make_scaled(mp, num,denom); }
17245     check_arith; mp_get_x_next(mp);
17246   }
17247   if ( mp->cur_cmd>=min_primary_command ) {
17248    if ( mp->cur_cmd<numeric_token ) { /* in particular, |cur_cmd<>plus_or_minus| */
17249      p=mp_stash_cur_exp(mp); mp_scan_primary(mp);
17250      if ( (abs(num)>=abs(denom))||(mp->cur_type<mp_color_type) ) {
17251        mp_do_binary(mp, p,times);
17252      } else {
17253        mp_frac_mult(mp, num,denom);
17254        mp_free_node(mp, p,value_node_size);
17255      }
17256     }
17257   }
17258   goto DONE;
17259 }
17260
17261 @ @<Protest division...@>=
17262
17263   print_err("Division by zero");
17264 @.Division by zero@>
17265   help1("I'll pretend that you meant to divide by 1."); mp_error(mp);
17266 }
17267
17268 @ @<Scan a binary operation with `\&{of}' between its operands@>=
17269
17270   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
17271   if ( mp->cur_cmd!=of_token ) {
17272     mp_missing_err(mp, "of"); mp_print(mp, " for "); 
17273     mp_print_cmd_mod(mp, primary_binary,c);
17274 @.Missing `of'@>
17275     help1("I've got the first argument; will look now for the other.");
17276     mp_back_error(mp);
17277   }
17278   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_primary(mp); 
17279   mp_do_binary(mp, p,c); goto DONE;
17280 }
17281
17282 @ @<Convert a suffix to a string@>=
17283
17284   mp_get_x_next(mp); mp_scan_suffix(mp); 
17285   mp->old_setting=mp->selector; mp->selector=new_string;
17286   mp_show_token_list(mp, mp->cur_exp,null,100000,0); 
17287   mp_flush_token_list(mp, mp->cur_exp);
17288   mp->cur_exp=mp_make_string(mp); mp->selector=mp->old_setting; 
17289   mp->cur_type=mp_string_type;
17290   goto DONE;
17291 }
17292
17293 @ If an internal quantity appears all by itself on the left of an
17294 assignment, we return a token list of length one, containing the address
17295 of the internal quantity plus |hash_end|. (This accords with the conventions
17296 of the save stack, as described earlier.)
17297
17298 @<Scan an internal...@>=
17299
17300   q=mp->cur_mod;
17301   if ( my_var_flag==assignment ) {
17302     mp_get_x_next(mp);
17303     if ( mp->cur_cmd==assignment ) {
17304       mp->cur_exp=mp_get_avail(mp);
17305       info(mp->cur_exp)=q+hash_end; mp->cur_type=mp_token_list; 
17306       goto DONE;
17307     }
17308     mp_back_input(mp);
17309   }
17310   mp->cur_type=mp_known; mp->cur_exp=mp->internal[q];
17311 }
17312
17313 @ The most difficult part of |scan_primary| has been saved for last, since
17314 it was necessary to build up some confidence first. We can now face the task
17315 of scanning a variable.
17316
17317 As we scan a variable, we build a token list containing the relevant
17318 names and subscript values, simultaneously following along in the
17319 ``collective'' structure to see if we are actually dealing with a macro
17320 instead of a value.
17321
17322 The local variables |pre_head| and |post_head| will point to the beginning
17323 of the prefix and suffix lists; |tail| will point to the end of the list
17324 that is currently growing.
17325
17326 Another local variable, |tt|, contains partial information about the
17327 declared type of the variable-so-far. If |tt>=mp_unsuffixed_macro|, the
17328 relation |tt=type(q)| will always hold. If |tt=undefined|, the routine
17329 doesn't bother to update its information about type. And if
17330 |undefined<tt<mp_unsuffixed_macro|, the precise value of |tt| isn't critical.
17331
17332 @ @<Other local variables for |scan_primary|@>=
17333 pointer pre_head,post_head,tail;
17334   /* prefix and suffix list variables */
17335 small_number tt; /* approximation to the type of the variable-so-far */
17336 pointer t; /* a token */
17337 pointer macro_ref = 0; /* reference count for a suffixed macro */
17338
17339 @ @<Scan a variable primary...@>=
17340
17341   fast_get_avail(pre_head); tail=pre_head; post_head=null; tt=mp_vacuous;
17342   while (1) { 
17343     t=mp_cur_tok(mp); link(tail)=t;
17344     if ( tt!=undefined ) {
17345        @<Find the approximate type |tt| and corresponding~|q|@>;
17346       if ( tt>=mp_unsuffixed_macro ) {
17347         @<Either begin an unsuffixed macro call or
17348           prepare for a suffixed one@>;
17349       }
17350     }
17351     mp_get_x_next(mp); tail=t;
17352     if ( mp->cur_cmd==left_bracket ) {
17353       @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>;
17354     }
17355     if ( mp->cur_cmd>max_suffix_token ) break;
17356     if ( mp->cur_cmd<min_suffix_token ) break;
17357   } /* now |cur_cmd| is |internal_quantity|, |tag_token|, or |numeric_token| */
17358   @<Handle unusual cases that masquerade as variables, and |goto restart|
17359     or |goto done| if appropriate;
17360     otherwise make a copy of the variable and |goto done|@>;
17361 }
17362
17363 @ @<Either begin an unsuffixed macro call or...@>=
17364
17365   link(tail)=null;
17366   if ( tt>mp_unsuffixed_macro ) { /* |tt=mp_suffixed_macro| */
17367     post_head=mp_get_avail(mp); tail=post_head; link(tail)=t;
17368     tt=undefined; macro_ref=value(q); add_mac_ref(macro_ref);
17369   } else {
17370     @<Set up unsuffixed macro call and |goto restart|@>;
17371   }
17372 }
17373
17374 @ @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>=
17375
17376   mp_get_x_next(mp); mp_scan_expression(mp);
17377   if ( mp->cur_cmd!=right_bracket ) {
17378     @<Put the left bracket and the expression back to be rescanned@>;
17379   } else { 
17380     if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17381     mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp; mp->cur_sym=0;
17382   }
17383 }
17384
17385 @ The left bracket that we thought was introducing a subscript might have
17386 actually been the left bracket in a mediation construction like `\.{x[a,b]}'.
17387 So we don't issue an error message at this point; but we do want to back up
17388 so as to avoid any embarrassment about our incorrect assumption.
17389
17390 @<Put the left bracket and the expression back to be rescanned@>=
17391
17392   mp_back_input(mp); /* that was the token following the current expression */
17393   mp_back_expr(mp); mp->cur_cmd=left_bracket; 
17394   mp->cur_mod=0; mp->cur_sym=frozen_left_bracket;
17395 }
17396
17397 @ Here's a routine that puts the current expression back to be read again.
17398
17399 @c void mp_back_expr (MP mp) {
17400   pointer p; /* capsule token */
17401   p=mp_stash_cur_exp(mp); link(p)=null; back_list(p);
17402 }
17403
17404 @ Unknown subscripts lead to the following error message.
17405
17406 @c void mp_bad_subscript (MP mp) { 
17407   exp_err("Improper subscript has been replaced by zero");
17408 @.Improper subscript...@>
17409   help3("A bracketed subscript must have a known numeric value;")
17410     ("unfortunately, what I found was the value that appears just")
17411     ("above this error message. So I'll try a zero subscript.");
17412   mp_flush_error(mp, 0);
17413 }
17414
17415 @ Every time we call |get_x_next|, there's a chance that the variable we've
17416 been looking at will disappear. Thus, we cannot safely keep |q| pointing
17417 into the variable structure; we need to start searching from the root each time.
17418
17419 @<Find the approximate type |tt| and corresponding~|q|@>=
17420 @^inner loop@>
17421
17422   p=link(pre_head); q=info(p); tt=undefined;
17423   if ( eq_type(q) % outer_tag==tag_token ) {
17424     q=equiv(q);
17425     if ( q==null ) goto DONE2;
17426     while (1) { 
17427       p=link(p);
17428       if ( p==null ) {
17429         tt=type(q); goto DONE2;
17430       };
17431       if ( type(q)!=mp_structured ) goto DONE2;
17432       q=link(attr_head(q)); /* the |collective_subscript| attribute */
17433       if ( p>=mp->hi_mem_min ) { /* it's not a subscript */
17434         do {  q=link(q); } while (! (attr_loc(q)>=info(p)));
17435         if ( attr_loc(q)>info(p) ) goto DONE2;
17436       }
17437     }
17438   }
17439 DONE2:
17440   ;
17441 }
17442
17443 @ How do things stand now? Well, we have scanned an entire variable name,
17444 including possible subscripts and/or attributes; |cur_cmd|, |cur_mod|, and
17445 |cur_sym| represent the token that follows. If |post_head=null|, a
17446 token list for this variable name starts at |link(pre_head)|, with all
17447 subscripts evaluated. But if |post_head<>null|, the variable turned out
17448 to be a suffixed macro; |pre_head| is the head of the prefix list, while
17449 |post_head| is the head of a token list containing both `\.{\AT!}' and
17450 the suffix.
17451
17452 Our immediate problem is to see if this variable still exists. (Variable
17453 structures can change drastically whenever we call |get_x_next|; users
17454 aren't supposed to do this, but the fact that it is possible means that
17455 we must be cautious.)
17456
17457 The following procedure prints an error message when a variable
17458 unexpectedly disappears. Its help message isn't quite right for
17459 our present purposes, but we'll be able to fix that up.
17460
17461 @c 
17462 void mp_obliterated (MP mp,pointer q) { 
17463   print_err("Variable "); mp_show_token_list(mp, q,null,1000,0);
17464   mp_print(mp, " has been obliterated");
17465 @.Variable...obliterated@>
17466   help5("It seems you did a nasty thing---probably by accident,")
17467     ("but nevertheless you nearly hornswoggled me...")
17468     ("While I was evaluating the right-hand side of this")
17469     ("command, something happened, and the left-hand side")
17470     ("is no longer a variable! So I won't change anything.");
17471 }
17472
17473 @ If the variable does exist, we also need to check
17474 for a few other special cases before deciding that a plain old ordinary
17475 variable has, indeed, been scanned.
17476
17477 @<Handle unusual cases that masquerade as variables...@>=
17478 if ( post_head!=null ) {
17479   @<Set up suffixed macro call and |goto restart|@>;
17480 }
17481 q=link(pre_head); free_avail(pre_head);
17482 if ( mp->cur_cmd==my_var_flag ) { 
17483   mp->cur_type=mp_token_list; mp->cur_exp=q; goto DONE;
17484 }
17485 p=mp_find_variable(mp, q);
17486 if ( p!=null ) {
17487   mp_make_exp_copy(mp, p);
17488 } else { 
17489   mp_obliterated(mp, q);
17490   mp->help_line[2]="While I was evaluating the suffix of this variable,";
17491   mp->help_line[1]="something was redefined, and it's no longer a variable!";
17492   mp->help_line[0]="In order to get back on my feet, I've inserted `0' instead.";
17493   mp_put_get_flush_error(mp, 0);
17494 }
17495 mp_flush_node_list(mp, q); 
17496 goto DONE
17497
17498 @ The only complication associated with macro calling is that the prefix
17499 and ``at'' parameters must be packaged in an appropriate list of lists.
17500
17501 @<Set up unsuffixed macro call and |goto restart|@>=
17502
17503   p=mp_get_avail(mp); info(pre_head)=link(pre_head); link(pre_head)=p;
17504   info(p)=t; mp_macro_call(mp, value(q),pre_head,null);
17505   mp_get_x_next(mp); 
17506   goto RESTART;
17507 }
17508
17509 @ If the ``variable'' that turned out to be a suffixed macro no longer exists,
17510 we don't care, because we have reserved a pointer (|macro_ref|) to its
17511 token list.
17512
17513 @<Set up suffixed macro call and |goto restart|@>=
17514
17515   mp_back_input(mp); p=mp_get_avail(mp); q=link(post_head);
17516   info(pre_head)=link(pre_head); link(pre_head)=post_head;
17517   info(post_head)=q; link(post_head)=p; info(p)=link(q); link(q)=null;
17518   mp_macro_call(mp, macro_ref,pre_head,null); decr(ref_count(macro_ref));
17519   mp_get_x_next(mp); goto RESTART;
17520 }
17521
17522 @ Our remaining job is simply to make a copy of the value that has been
17523 found. Some cases are harder than others, but complexity arises solely
17524 because of the multiplicity of possible cases.
17525
17526 @<Declare the procedure called |make_exp_copy|@>=
17527 @<Declare subroutines needed by |make_exp_copy|@>;
17528 void mp_make_exp_copy (MP mp,pointer p) {
17529   pointer q,r,t; /* registers for list manipulation */
17530 RESTART: 
17531   mp->cur_type=type(p);
17532   switch (mp->cur_type) {
17533   case mp_vacuous: case mp_boolean_type: case mp_known:
17534     mp->cur_exp=value(p); break;
17535   case unknown_types:
17536     mp->cur_exp=mp_new_ring_entry(mp, p);
17537     break;
17538   case mp_string_type: 
17539     mp->cur_exp=value(p); add_str_ref(mp->cur_exp);
17540     break;
17541   case mp_picture_type:
17542     mp->cur_exp=value(p);add_edge_ref(mp->cur_exp);
17543     break;
17544   case mp_pen_type:
17545     mp->cur_exp=copy_pen(value(p));
17546     break; 
17547   case mp_path_type:
17548     mp->cur_exp=mp_copy_path(mp, value(p));
17549     break;
17550   case mp_transform_type: case mp_color_type: 
17551   case mp_cmykcolor_type: case mp_pair_type:
17552     @<Copy the big node |p|@>;
17553     break;
17554   case mp_dependent: case mp_proto_dependent:
17555     mp_encapsulate(mp, mp_copy_dep_list(mp, dep_list(p)));
17556     break;
17557   case mp_numeric_type: 
17558     new_indep(p); goto RESTART;
17559     break;
17560   case mp_independent: 
17561     q=mp_single_dependency(mp, p);
17562     if ( q==mp->dep_final ){ 
17563       mp->cur_type=mp_known; mp->cur_exp=0; mp_free_node(mp, q,value_node_size);
17564     } else { 
17565       mp->cur_type=mp_dependent; mp_encapsulate(mp, q);
17566     }
17567     break;
17568   default: 
17569     mp_confusion(mp, "copy");
17570 @:this can't happen copy}{\quad copy@>
17571     break;
17572   }
17573 }
17574
17575 @ The |encapsulate| subroutine assumes that |dep_final| is the
17576 tail of dependency list~|p|.
17577
17578 @<Declare subroutines needed by |make_exp_copy|@>=
17579 void mp_encapsulate (MP mp,pointer p) { 
17580   mp->cur_exp=mp_get_node(mp, value_node_size); type(mp->cur_exp)=mp->cur_type;
17581   name_type(mp->cur_exp)=mp_capsule; mp_new_dep(mp, mp->cur_exp,p);
17582 }
17583
17584 @ The most tedious case arises when the user refers to a
17585 \&{pair}, \&{color}, or \&{transform} variable; we must copy several fields,
17586 each of which can be |independent|, |dependent|, |mp_proto_dependent|,
17587 or |known|.
17588
17589 @<Copy the big node |p|@>=
17590
17591   if ( value(p)==null ) 
17592     mp_init_big_node(mp, p);
17593   t=mp_get_node(mp, value_node_size); name_type(t)=mp_capsule; type(t)=mp->cur_type;
17594   mp_init_big_node(mp, t);
17595   q=value(p)+mp->big_node_size[mp->cur_type]; 
17596   r=value(t)+mp->big_node_size[mp->cur_type];
17597   do {  
17598     q=q-2; r=r-2; mp_install(mp, r,q);
17599   } while (q!=value(p));
17600   mp->cur_exp=t;
17601 }
17602
17603 @ The |install| procedure copies a numeric field~|q| into field~|r| of
17604 a big node that will be part of a capsule.
17605
17606 @<Declare subroutines needed by |make_exp_copy|@>=
17607 void mp_install (MP mp,pointer r, pointer q) {
17608   pointer p; /* temporary register */
17609   if ( type(q)==mp_known ){ 
17610     value(r)=value(q); type(r)=mp_known;
17611   } else  if ( type(q)==mp_independent ) {
17612     p=mp_single_dependency(mp, q);
17613     if ( p==mp->dep_final ) {
17614       type(r)=mp_known; value(r)=0; mp_free_node(mp, p,value_node_size);
17615     } else  { 
17616       type(r)=mp_dependent; mp_new_dep(mp, r,p);
17617     }
17618   } else {
17619     type(r)=type(q); mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(q)));
17620   }
17621 }
17622
17623 @ Expressions of the form `\.{a[b,c]}' are converted into
17624 `\.{b+a*(c-b)}', without checking the types of \.b~or~\.c,
17625 provided that \.a is numeric.
17626
17627 @<Scan a mediation...@>=
17628
17629   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17630   if ( mp->cur_cmd!=comma ) {
17631     @<Put the left bracket and the expression back...@>;
17632     mp_unstash_cur_exp(mp, p);
17633   } else { 
17634     q=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17635     if ( mp->cur_cmd!=right_bracket ) {
17636       mp_missing_err(mp, "]");
17637 @.Missing `]'@>
17638       help3("I've scanned an expression of the form `a[b,c',")
17639       ("so a right bracket should have come next.")
17640       ("I shall pretend that one was there.");
17641       mp_back_error(mp);
17642     }
17643     r=mp_stash_cur_exp(mp); mp_make_exp_copy(mp, q);
17644     mp_do_binary(mp, r,minus); mp_do_binary(mp, p,times); 
17645     mp_do_binary(mp, q,plus); mp_get_x_next(mp);
17646   }
17647 }
17648
17649 @ Here is a comparatively simple routine that is used to scan the
17650 \&{suffix} parameters of a macro.
17651
17652 @<Declare the basic parsing subroutines@>=
17653 void mp_scan_suffix (MP mp) {
17654   pointer h,t; /* head and tail of the list being built */
17655   pointer p; /* temporary register */
17656   h=mp_get_avail(mp); t=h;
17657   while (1) { 
17658     if ( mp->cur_cmd==left_bracket ) {
17659       @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>;
17660     }
17661     if ( mp->cur_cmd==numeric_token ) {
17662       p=mp_new_num_tok(mp, mp->cur_mod);
17663     } else if ((mp->cur_cmd==tag_token)||(mp->cur_cmd==internal_quantity) ) {
17664        p=mp_get_avail(mp); info(p)=mp->cur_sym;
17665     } else {
17666       break;
17667     }
17668     link(t)=p; t=p; mp_get_x_next(mp);
17669   }
17670   mp->cur_exp=link(h); free_avail(h); mp->cur_type=mp_token_list;
17671 }
17672
17673 @ @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>=
17674
17675   mp_get_x_next(mp); mp_scan_expression(mp);
17676   if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17677   if ( mp->cur_cmd!=right_bracket ) {
17678      mp_missing_err(mp, "]");
17679 @.Missing `]'@>
17680     help3("I've seen a `[' and a subscript value, in a suffix,")
17681       ("so a right bracket should have come next.")
17682       ("I shall pretend that one was there.");
17683     mp_back_error(mp);
17684   }
17685   mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp;
17686 }
17687
17688 @* \[38] Parsing secondary and higher expressions.
17689 After the intricacies of |scan_primary|\kern-1pt,
17690 the |scan_secondary| routine is
17691 refreshingly simple. It's not trivial, but the operations are relatively
17692 straightforward; the main difficulty is, again, that expressions and data
17693 structures might change drastically every time we call |get_x_next|, so a
17694 cautious approach is mandatory. For example, a macro defined by
17695 \&{primarydef} might have disappeared by the time its second argument has
17696 been scanned; we solve this by increasing the reference count of its token
17697 list, so that the macro can be called even after it has been clobbered.
17698
17699 @<Declare the basic parsing subroutines@>=
17700 void mp_scan_secondary (MP mp) {
17701   pointer p; /* for list manipulation */
17702   halfword c,d; /* operation codes or modifiers */
17703   pointer mac_name; /* token defined with \&{primarydef} */
17704 RESTART:
17705   if ((mp->cur_cmd<min_primary_command)||
17706       (mp->cur_cmd>max_primary_command) )
17707     mp_bad_exp(mp, "A secondary");
17708 @.A secondary expression...@>
17709   mp_scan_primary(mp);
17710 CONTINUE: 
17711   if ( mp->cur_cmd<=max_secondary_command )
17712     if ( mp->cur_cmd>=min_secondary_command ) {
17713       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17714       if ( d==secondary_primary_macro ) { 
17715         mac_name=mp->cur_sym; add_mac_ref(c);
17716      }
17717      mp_get_x_next(mp); mp_scan_primary(mp);
17718      if ( d!=secondary_primary_macro ) {
17719        mp_do_binary(mp, p,c);
17720      } else  { 
17721        mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17722        decr(ref_count(c)); mp_get_x_next(mp); 
17723        goto RESTART;
17724     }
17725     goto CONTINUE;
17726   }
17727 }
17728
17729 @ The following procedure calls a macro that has two parameters,
17730 |p| and |cur_exp|.
17731
17732 @c void mp_binary_mac (MP mp,pointer p, pointer c, pointer n) {
17733   pointer q,r; /* nodes in the parameter list */
17734   q=mp_get_avail(mp); r=mp_get_avail(mp); link(q)=r;
17735   info(q)=p; info(r)=mp_stash_cur_exp(mp);
17736   mp_macro_call(mp, c,q,n);
17737 }
17738
17739 @ The next procedure, |scan_tertiary|, is pretty much the same deal.
17740
17741 @<Declare the basic parsing subroutines@>=
17742 void mp_scan_tertiary (MP mp) {
17743   pointer p; /* for list manipulation */
17744   halfword c,d; /* operation codes or modifiers */
17745   pointer mac_name; /* token defined with \&{secondarydef} */
17746 RESTART:
17747   if ((mp->cur_cmd<min_primary_command)||
17748       (mp->cur_cmd>max_primary_command) )
17749     mp_bad_exp(mp, "A tertiary");
17750 @.A tertiary expression...@>
17751   mp_scan_secondary(mp);
17752 CONTINUE: 
17753   if ( mp->cur_cmd<=max_tertiary_command ) {
17754     if ( mp->cur_cmd>=min_tertiary_command ) {
17755       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17756       if ( d==tertiary_secondary_macro ) { 
17757         mac_name=mp->cur_sym; add_mac_ref(c);
17758       };
17759       mp_get_x_next(mp); mp_scan_secondary(mp);
17760       if ( d!=tertiary_secondary_macro ) {
17761         mp_do_binary(mp, p,c);
17762       } else { 
17763         mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17764         decr(ref_count(c)); mp_get_x_next(mp); 
17765         goto RESTART;
17766       }
17767       goto CONTINUE;
17768     }
17769   }
17770 }
17771
17772 @ Finally we reach the deepest level in our quartet of parsing routines.
17773 This one is much like the others; but it has an extra complication from
17774 paths, which materialize here.
17775
17776 @d continue_path 25 /* a label inside of |scan_expression| */
17777 @d finish_path 26 /* another */
17778
17779 @<Declare the basic parsing subroutines@>=
17780 void mp_scan_expression (MP mp) {
17781   pointer p,q,r,pp,qq; /* for list manipulation */
17782   halfword c,d; /* operation codes or modifiers */
17783   int my_var_flag; /* initial value of |var_flag| */
17784   pointer mac_name; /* token defined with \&{tertiarydef} */
17785   boolean cycle_hit; /* did a path expression just end with `\&{cycle}'? */
17786   scaled x,y; /* explicit coordinates or tension at a path join */
17787   int t; /* knot type following a path join */
17788   t=0; y=0; x=0;
17789   my_var_flag=mp->var_flag; mac_name=null;
17790 RESTART:
17791   if ((mp->cur_cmd<min_primary_command)||
17792       (mp->cur_cmd>max_primary_command) )
17793     mp_bad_exp(mp, "An");
17794 @.An expression...@>
17795   mp_scan_tertiary(mp);
17796 CONTINUE: 
17797   if ( mp->cur_cmd<=max_expression_command )
17798     if ( mp->cur_cmd>=min_expression_command ) {
17799       if ( (mp->cur_cmd!=equals)||(my_var_flag!=assignment) ) {
17800         p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17801         if ( d==expression_tertiary_macro ) {
17802           mac_name=mp->cur_sym; add_mac_ref(c);
17803         }
17804         if ( (d<ampersand)||((d==ampersand)&&
17805              ((type(p)==mp_pair_type)||(type(p)==mp_path_type))) ) {
17806           @<Scan a path construction operation;
17807             but |return| if |p| has the wrong type@>;
17808         } else { 
17809           mp_get_x_next(mp); mp_scan_tertiary(mp);
17810           if ( d!=expression_tertiary_macro ) {
17811             mp_do_binary(mp, p,c);
17812           } else  { 
17813             mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17814             decr(ref_count(c)); mp_get_x_next(mp); 
17815             goto RESTART;
17816           }
17817         }
17818         goto CONTINUE;
17819      }
17820   }
17821 }
17822
17823 @ The reader should review the data structure conventions for paths before
17824 hoping to understand the next part of this code.
17825
17826 @<Scan a path construction operation...@>=
17827
17828   cycle_hit=false;
17829   @<Convert the left operand, |p|, into a partial path ending at~|q|;
17830     but |return| if |p| doesn't have a suitable type@>;
17831 CONTINUE_PATH: 
17832   @<Determine the path join parameters;
17833     but |goto finish_path| if there's only a direction specifier@>;
17834   if ( mp->cur_cmd==cycle ) {
17835     @<Get ready to close a cycle@>;
17836   } else { 
17837     mp_scan_tertiary(mp);
17838     @<Convert the right operand, |cur_exp|,
17839       into a partial path from |pp| to~|qq|@>;
17840   }
17841   @<Join the partial paths and reset |p| and |q| to the head and tail
17842     of the result@>;
17843   if ( mp->cur_cmd>=min_expression_command )
17844     if ( mp->cur_cmd<=ampersand ) if ( ! cycle_hit ) goto CONTINUE_PATH;
17845 FINISH_PATH:
17846   @<Choose control points for the path and put the result into |cur_exp|@>;
17847 }
17848
17849 @ @<Convert the left operand, |p|, into a partial path ending at~|q|...@>=
17850
17851   mp_unstash_cur_exp(mp, p);
17852   if ( mp->cur_type==mp_pair_type ) p=mp_new_knot(mp);
17853   else if ( mp->cur_type==mp_path_type ) p=mp->cur_exp;
17854   else return;
17855   q=p;
17856   while ( link(q)!=p ) q=link(q);
17857   if ( left_type(p)!=endpoint ) { /* open up a cycle */
17858     r=mp_copy_knot(mp, p); link(q)=r; q=r;
17859   }
17860   left_type(p)=open; right_type(q)=open;
17861 }
17862
17863 @ A pair of numeric values is changed into a knot node for a one-point path
17864 when \MP\ discovers that the pair is part of a path.
17865
17866 @c@<Declare the procedure called |known_pair|@>;
17867 pointer mp_new_knot (MP mp) { /* convert a pair to a knot with two endpoints */
17868   pointer q; /* the new node */
17869   q=mp_get_node(mp, knot_node_size); left_type(q)=endpoint;
17870   right_type(q)=endpoint; originator(q)=metapost_user; link(q)=q;
17871   mp_known_pair(mp); x_coord(q)=mp->cur_x; y_coord(q)=mp->cur_y;
17872   return q;
17873 }
17874
17875 @ The |known_pair| subroutine sets |cur_x| and |cur_y| to the components
17876 of the current expression, assuming that the current expression is a
17877 pair of known numerics. Unknown components are zeroed, and the
17878 current expression is flushed.
17879
17880 @<Declare the procedure called |known_pair|@>=
17881 void mp_known_pair (MP mp) {
17882   pointer p; /* the pair node */
17883   if ( mp->cur_type!=mp_pair_type ) {
17884     exp_err("Undefined coordinates have been replaced by (0,0)");
17885 @.Undefined coordinates...@>
17886     help5("I need x and y numbers for this part of the path.")
17887       ("The value I found (see above) was no good;")
17888       ("so I'll try to keep going by using zero instead.")
17889       ("(Chapter 27 of The METAFONTbook explains that")
17890 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
17891       ("you might want to type `I ??" "?' now.)");
17892     mp_put_get_flush_error(mp, 0); mp->cur_x=0; mp->cur_y=0;
17893   } else { 
17894     p=value(mp->cur_exp);
17895      @<Make sure that both |x| and |y| parts of |p| are known;
17896        copy them into |cur_x| and |cur_y|@>;
17897     mp_flush_cur_exp(mp, 0);
17898   }
17899 }
17900
17901 @ @<Make sure that both |x| and |y| parts of |p| are known...@>=
17902 if ( type(x_part_loc(p))==mp_known ) {
17903   mp->cur_x=value(x_part_loc(p));
17904 } else { 
17905   mp_disp_err(mp, x_part_loc(p),
17906     "Undefined x coordinate has been replaced by 0");
17907 @.Undefined coordinates...@>
17908   help5("I need a `known' x value for this part of the path.")
17909     ("The value I found (see above) was no good;")
17910     ("so I'll try to keep going by using zero instead.")
17911     ("(Chapter 27 of The METAFONTbook explains that")
17912 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
17913     ("you might want to type `I ??" "?' now.)");
17914   mp_put_get_error(mp); mp_recycle_value(mp, x_part_loc(p)); mp->cur_x=0;
17915 }
17916 if ( type(y_part_loc(p))==mp_known ) {
17917   mp->cur_y=value(y_part_loc(p));
17918 } else { 
17919   mp_disp_err(mp, y_part_loc(p),
17920     "Undefined y coordinate has been replaced by 0");
17921   help5("I need a `known' y value for this part of the path.")
17922     ("The value I found (see above) was no good;")
17923     ("so I'll try to keep going by using zero instead.")
17924     ("(Chapter 27 of The METAFONTbook explains that")
17925     ("you might want to type `I ??" "?' now.)");
17926   mp_put_get_error(mp); mp_recycle_value(mp, y_part_loc(p)); mp->cur_y=0;
17927 }
17928
17929 @ At this point |cur_cmd| is either |ampersand|, |left_brace|, or |path_join|.
17930
17931 @<Determine the path join parameters...@>=
17932 if ( mp->cur_cmd==left_brace ) {
17933   @<Put the pre-join direction information into node |q|@>;
17934 }
17935 d=mp->cur_cmd;
17936 if ( d==path_join ) {
17937   @<Determine the tension and/or control points@>;
17938 } else if ( d!=ampersand ) {
17939   goto FINISH_PATH;
17940 }
17941 mp_get_x_next(mp);
17942 if ( mp->cur_cmd==left_brace ) {
17943   @<Put the post-join direction information into |x| and |t|@>;
17944 } else if ( right_type(q)!=explicit ) {
17945   t=open; x=0;
17946 }
17947
17948 @ The |scan_direction| subroutine looks at the directional information
17949 that is enclosed in braces, and also scans ahead to the following character.
17950 A type code is returned, either |open| (if the direction was $(0,0)$),
17951 or |curl| (if the direction was a curl of known value |cur_exp|), or
17952 |given| (if the direction is given by the |angle| value that now
17953 appears in |cur_exp|).
17954
17955 There's nothing difficult about this subroutine, but the program is rather
17956 lengthy because a variety of potential errors need to be nipped in the bud.
17957
17958 @c small_number mp_scan_direction (MP mp) {
17959   int t; /* the type of information found */
17960   scaled x; /* an |x| coordinate */
17961   mp_get_x_next(mp);
17962   if ( mp->cur_cmd==curl_command ) {
17963      @<Scan a curl specification@>;
17964   } else {
17965     @<Scan a given direction@>;
17966   }
17967   if ( mp->cur_cmd!=right_brace ) {
17968     mp_missing_err(mp, "}");
17969 @.Missing `\char`\}'@>
17970     help3("I've scanned a direction spec for part of a path,")
17971       ("so a right brace should have come next.")
17972       ("I shall pretend that one was there.");
17973     mp_back_error(mp);
17974   }
17975   mp_get_x_next(mp); 
17976   return t;
17977 }
17978
17979 @ @<Scan a curl specification@>=
17980 { mp_get_x_next(mp); mp_scan_expression(mp);
17981 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<0) ){ 
17982   exp_err("Improper curl has been replaced by 1");
17983 @.Improper curl@>
17984   help1("A curl must be a known, nonnegative number.");
17985   mp_put_get_flush_error(mp, unity);
17986 }
17987 t=curl;
17988 }
17989
17990 @ @<Scan a given direction@>=
17991 { mp_scan_expression(mp);
17992   if ( mp->cur_type>mp_pair_type ) {
17993     @<Get given directions separated by commas@>;
17994   } else {
17995     mp_known_pair(mp);
17996   }
17997   if ( (mp->cur_x==0)&&(mp->cur_y==0) )  t=open;
17998   else  { t=given; mp->cur_exp=mp_n_arg(mp, mp->cur_x,mp->cur_y);}
17999 }
18000
18001 @ @<Get given directions separated by commas@>=
18002
18003   if ( mp->cur_type!=mp_known ) {
18004     exp_err("Undefined x coordinate has been replaced by 0");
18005 @.Undefined coordinates...@>
18006     help5("I need a `known' x value for this part of the path.")
18007       ("The value I found (see above) was no good;")
18008       ("so I'll try to keep going by using zero instead.")
18009       ("(Chapter 27 of The METAFONTbook explains that")
18010 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18011       ("you might want to type `I ??" "?' now.)");
18012     mp_put_get_flush_error(mp, 0);
18013   }
18014   x=mp->cur_exp;
18015   if ( mp->cur_cmd!=comma ) {
18016     mp_missing_err(mp, ",");
18017 @.Missing `,'@>
18018     help2("I've got the x coordinate of a path direction;")
18019       ("will look for the y coordinate next.");
18020     mp_back_error(mp);
18021   }
18022   mp_get_x_next(mp); mp_scan_expression(mp);
18023   if ( mp->cur_type!=mp_known ) {
18024      exp_err("Undefined y coordinate has been replaced by 0");
18025     help5("I need a `known' y value for this part of the path.")
18026       ("The value I found (see above) was no good;")
18027       ("so I'll try to keep going by using zero instead.")
18028       ("(Chapter 27 of The METAFONTbook explains that")
18029       ("you might want to type `I ??" "?' now.)");
18030     mp_put_get_flush_error(mp, 0);
18031   }
18032   mp->cur_y=mp->cur_exp; mp->cur_x=x;
18033 }
18034
18035 @ At this point |right_type(q)| is usually |open|, but it may have been
18036 set to some other value by a previous splicing operation. We must maintain
18037 the value of |right_type(q)| in unusual cases such as
18038 `\.{..z1\{z2\}\&\{z3\}z1\{0,0\}..}'.
18039
18040 @<Put the pre-join...@>=
18041
18042   t=mp_scan_direction(mp);
18043   if ( t!=open ) {
18044     right_type(q)=t; right_given(q)=mp->cur_exp;
18045     if ( left_type(q)==open ) {
18046       left_type(q)=t; left_given(q)=mp->cur_exp;
18047     } /* note that |left_given(q)=left_curl(q)| */
18048   }
18049 }
18050
18051 @ Since |left_tension| and |left_y| share the same position in knot nodes,
18052 and since |left_given| is similarly equivalent to |left_x|, we use
18053 |x| and |y| to hold the given direction and tension information when
18054 there are no explicit control points.
18055
18056 @<Put the post-join...@>=
18057
18058   t=mp_scan_direction(mp);
18059   if ( right_type(q)!=explicit ) x=mp->cur_exp;
18060   else t=explicit; /* the direction information is superfluous */
18061 }
18062
18063 @ @<Determine the tension and/or...@>=
18064
18065   mp_get_x_next(mp);
18066   if ( mp->cur_cmd==tension ) {
18067     @<Set explicit tensions@>;
18068   } else if ( mp->cur_cmd==controls ) {
18069     @<Set explicit control points@>;
18070   } else  { 
18071     right_tension(q)=unity; y=unity; mp_back_input(mp); /* default tension */
18072     goto DONE;
18073   };
18074   if ( mp->cur_cmd!=path_join ) {
18075      mp_missing_err(mp, "..");
18076 @.Missing `..'@>
18077     help1("A path join command should end with two dots.");
18078     mp_back_error(mp);
18079   }
18080 DONE:
18081   ;
18082 }
18083
18084 @ @<Set explicit tensions@>=
18085
18086   mp_get_x_next(mp); y=mp->cur_cmd;
18087   if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18088   mp_scan_primary(mp);
18089   @<Make sure that the current expression is a valid tension setting@>;
18090   if ( y==at_least ) negate(mp->cur_exp);
18091   right_tension(q)=mp->cur_exp;
18092   if ( mp->cur_cmd==and_command ) {
18093     mp_get_x_next(mp); y=mp->cur_cmd;
18094     if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18095     mp_scan_primary(mp);
18096     @<Make sure that the current expression is a valid tension setting@>;
18097     if ( y==at_least ) negate(mp->cur_exp);
18098   }
18099   y=mp->cur_exp;
18100 }
18101
18102 @ @d min_tension three_quarter_unit
18103
18104 @<Make sure that the current expression is a valid tension setting@>=
18105 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<min_tension) ) {
18106   exp_err("Improper tension has been set to 1");
18107 @.Improper tension@>
18108   help1("The expression above should have been a number >=3/4.");
18109   mp_put_get_flush_error(mp, unity);
18110 }
18111
18112 @ @<Set explicit control points@>=
18113
18114   right_type(q)=explicit; t=explicit; mp_get_x_next(mp); mp_scan_primary(mp);
18115   mp_known_pair(mp); right_x(q)=mp->cur_x; right_y(q)=mp->cur_y;
18116   if ( mp->cur_cmd!=and_command ) {
18117     x=right_x(q); y=right_y(q);
18118   } else { 
18119     mp_get_x_next(mp); mp_scan_primary(mp);
18120     mp_known_pair(mp); x=mp->cur_x; y=mp->cur_y;
18121   }
18122 }
18123
18124 @ @<Convert the right operand, |cur_exp|, into a partial path...@>=
18125
18126   if ( mp->cur_type!=mp_path_type ) pp=mp_new_knot(mp);
18127   else pp=mp->cur_exp;
18128   qq=pp;
18129   while ( link(qq)!=pp ) qq=link(qq);
18130   if ( left_type(pp)!=endpoint ) { /* open up a cycle */
18131     r=mp_copy_knot(mp, pp); link(qq)=r; qq=r;
18132   }
18133   left_type(pp)=open; right_type(qq)=open;
18134 }
18135
18136 @ If a person tries to define an entire path by saying `\.{(x,y)\&cycle}',
18137 we silently change the specification to `\.{(x,y)..cycle}', since a cycle
18138 shouldn't have length zero.
18139
18140 @<Get ready to close a cycle@>=
18141
18142   cycle_hit=true; mp_get_x_next(mp); pp=p; qq=p;
18143   if ( d==ampersand ) if ( p==q ) {
18144     d=path_join; right_tension(q)=unity; y=unity;
18145   }
18146 }
18147
18148 @ @<Join the partial paths and reset |p| and |q|...@>=
18149
18150 if ( d==ampersand ) {
18151   if ( (x_coord(q)!=x_coord(pp))||(y_coord(q)!=y_coord(pp)) ) {
18152     print_err("Paths don't touch; `&' will be changed to `..'");
18153 @.Paths don't touch@>
18154     help3("When you join paths `p&q', the ending point of p")
18155       ("must be exactly equal to the starting point of q.")
18156       ("So I'm going to pretend that you said `p..q' instead.");
18157     mp_put_get_error(mp); d=path_join; right_tension(q)=unity; y=unity;
18158   }
18159 }
18160 @<Plug an opening in |right_type(pp)|, if possible@>;
18161 if ( d==ampersand ) {
18162   @<Splice independent paths together@>;
18163 } else  { 
18164   @<Plug an opening in |right_type(q)|, if possible@>;
18165   link(q)=pp; left_y(pp)=y;
18166   if ( t!=open ) { left_x(pp)=x; left_type(pp)=t;  };
18167 }
18168 q=qq;
18169 }
18170
18171 @ @<Plug an opening in |right_type(q)|...@>=
18172 if ( right_type(q)==open ) {
18173   if ( (left_type(q)==curl)||(left_type(q)==given) ) {
18174     right_type(q)=left_type(q); right_given(q)=left_given(q);
18175   }
18176 }
18177
18178 @ @<Plug an opening in |right_type(pp)|...@>=
18179 if ( right_type(pp)==open ) {
18180   if ( (t==curl)||(t==given) ) {
18181     right_type(pp)=t; right_given(pp)=x;
18182   }
18183 }
18184
18185 @ @<Splice independent paths together@>=
18186
18187   if ( left_type(q)==open ) if ( right_type(q)==open ) {
18188     left_type(q)=curl; left_curl(q)=unity;
18189   }
18190   if ( right_type(pp)==open ) if ( t==open ) {
18191     right_type(pp)=curl; right_curl(pp)=unity;
18192   }
18193   right_type(q)=right_type(pp); link(q)=link(pp);
18194   right_x(q)=right_x(pp); right_y(q)=right_y(pp);
18195   mp_free_node(mp, pp,knot_node_size);
18196   if ( qq==pp ) qq=q;
18197 }
18198
18199 @ @<Choose control points for the path...@>=
18200 if ( cycle_hit ) { 
18201   if ( d==ampersand ) p=q;
18202 } else  { 
18203   left_type(p)=endpoint;
18204   if ( right_type(p)==open ) { 
18205     right_type(p)=curl; right_curl(p)=unity;
18206   }
18207   right_type(q)=endpoint;
18208   if ( left_type(q)==open ) { 
18209     left_type(q)=curl; left_curl(q)=unity;
18210   }
18211   link(q)=p;
18212 }
18213 mp_make_choices(mp, p);
18214 mp->cur_type=mp_path_type; mp->cur_exp=p
18215
18216 @ Finally, we sometimes need to scan an expression whose value is
18217 supposed to be either |true_code| or |false_code|.
18218
18219 @<Declare the basic parsing subroutines@>=
18220 void mp_get_boolean (MP mp) { 
18221   mp_get_x_next(mp); mp_scan_expression(mp);
18222   if ( mp->cur_type!=mp_boolean_type ) {
18223     exp_err("Undefined condition will be treated as `false'");
18224 @.Undefined condition...@>
18225     help2("The expression shown above should have had a definite")
18226       ("true-or-false value. I'm changing it to `false'.");
18227     mp_put_get_flush_error(mp, false_code); mp->cur_type=mp_boolean_type;
18228   }
18229 }
18230
18231 @* \[39] Doing the operations.
18232 The purpose of parsing is primarily to permit people to avoid piles of
18233 parentheses. But the real work is done after the structure of an expression
18234 has been recognized; that's when new expressions are generated. We
18235 turn now to the guts of \MP, which handles individual operators that
18236 have come through the parsing mechanism.
18237
18238 We'll start with the easy ones that take no operands, then work our way
18239 up to operators with one and ultimately two arguments. In other words,
18240 we will write the three procedures |do_nullary|, |do_unary|, and |do_binary|
18241 that are invoked periodically by the expression scanners.
18242
18243 First let's make sure that all of the primitive operators are in the
18244 hash table. Although |scan_primary| and its relatives made use of the
18245 \\{cmd} code for these operators, the \\{do} routines base everything
18246 on the \\{mod} code. For example, |do_binary| doesn't care whether the
18247 operation it performs is a |primary_binary| or |secondary_binary|, etc.
18248
18249 @<Put each...@>=
18250 mp_primitive(mp, "true",nullary,true_code);
18251 @:true_}{\&{true} primitive@>
18252 mp_primitive(mp, "false",nullary,false_code);
18253 @:false_}{\&{false} primitive@>
18254 mp_primitive(mp, "nullpicture",nullary,null_picture_code);
18255 @:null_picture_}{\&{nullpicture} primitive@>
18256 mp_primitive(mp, "nullpen",nullary,null_pen_code);
18257 @:null_pen_}{\&{nullpen} primitive@>
18258 mp_primitive(mp, "jobname",nullary,job_name_op);
18259 @:job_name_}{\&{jobname} primitive@>
18260 mp_primitive(mp, "readstring",nullary,read_string_op);
18261 @:read_string_}{\&{readstring} primitive@>
18262 mp_primitive(mp, "pencircle",nullary,pen_circle);
18263 @:pen_circle_}{\&{pencircle} primitive@>
18264 mp_primitive(mp, "normaldeviate",nullary,normal_deviate);
18265 @:normal_deviate_}{\&{normaldeviate} primitive@>
18266 mp_primitive(mp, "readfrom",unary,read_from_op);
18267 @:read_from_}{\&{readfrom} primitive@>
18268 mp_primitive(mp, "closefrom",unary,close_from_op);
18269 @:close_from_}{\&{closefrom} primitive@>
18270 mp_primitive(mp, "odd",unary,odd_op);
18271 @:odd_}{\&{odd} primitive@>
18272 mp_primitive(mp, "known",unary,known_op);
18273 @:known_}{\&{known} primitive@>
18274 mp_primitive(mp, "unknown",unary,unknown_op);
18275 @:unknown_}{\&{unknown} primitive@>
18276 mp_primitive(mp, "not",unary,not_op);
18277 @:not_}{\&{not} primitive@>
18278 mp_primitive(mp, "decimal",unary,decimal);
18279 @:decimal_}{\&{decimal} primitive@>
18280 mp_primitive(mp, "reverse",unary,reverse);
18281 @:reverse_}{\&{reverse} primitive@>
18282 mp_primitive(mp, "makepath",unary,make_path_op);
18283 @:make_path_}{\&{makepath} primitive@>
18284 mp_primitive(mp, "makepen",unary,make_pen_op);
18285 @:make_pen_}{\&{makepen} primitive@>
18286 mp_primitive(mp, "oct",unary,oct_op);
18287 @:oct_}{\&{oct} primitive@>
18288 mp_primitive(mp, "hex",unary,hex_op);
18289 @:hex_}{\&{hex} primitive@>
18290 mp_primitive(mp, "ASCII",unary,ASCII_op);
18291 @:ASCII_}{\&{ASCII} primitive@>
18292 mp_primitive(mp, "char",unary,char_op);
18293 @:char_}{\&{char} primitive@>
18294 mp_primitive(mp, "length",unary,length_op);
18295 @:length_}{\&{length} primitive@>
18296 mp_primitive(mp, "turningnumber",unary,turning_op);
18297 @:turning_number_}{\&{turningnumber} primitive@>
18298 mp_primitive(mp, "xpart",unary,x_part);
18299 @:x_part_}{\&{xpart} primitive@>
18300 mp_primitive(mp, "ypart",unary,y_part);
18301 @:y_part_}{\&{ypart} primitive@>
18302 mp_primitive(mp, "xxpart",unary,xx_part);
18303 @:xx_part_}{\&{xxpart} primitive@>
18304 mp_primitive(mp, "xypart",unary,xy_part);
18305 @:xy_part_}{\&{xypart} primitive@>
18306 mp_primitive(mp, "yxpart",unary,yx_part);
18307 @:yx_part_}{\&{yxpart} primitive@>
18308 mp_primitive(mp, "yypart",unary,yy_part);
18309 @:yy_part_}{\&{yypart} primitive@>
18310 mp_primitive(mp, "redpart",unary,red_part);
18311 @:red_part_}{\&{redpart} primitive@>
18312 mp_primitive(mp, "greenpart",unary,green_part);
18313 @:green_part_}{\&{greenpart} primitive@>
18314 mp_primitive(mp, "bluepart",unary,blue_part);
18315 @:blue_part_}{\&{bluepart} primitive@>
18316 mp_primitive(mp, "cyanpart",unary,cyan_part);
18317 @:cyan_part_}{\&{cyanpart} primitive@>
18318 mp_primitive(mp, "magentapart",unary,magenta_part);
18319 @:magenta_part_}{\&{magentapart} primitive@>
18320 mp_primitive(mp, "yellowpart",unary,yellow_part);
18321 @:yellow_part_}{\&{yellowpart} primitive@>
18322 mp_primitive(mp, "blackpart",unary,black_part);
18323 @:black_part_}{\&{blackpart} primitive@>
18324 mp_primitive(mp, "greypart",unary,grey_part);
18325 @:grey_part_}{\&{greypart} primitive@>
18326 mp_primitive(mp, "colormodel",unary,color_model_part);
18327 @:color_model_part_}{\&{colormodel} primitive@>
18328 mp_primitive(mp, "fontpart",unary,font_part);
18329 @:font_part_}{\&{fontpart} primitive@>
18330 mp_primitive(mp, "textpart",unary,text_part);
18331 @:text_part_}{\&{textpart} primitive@>
18332 mp_primitive(mp, "pathpart",unary,path_part);
18333 @:path_part_}{\&{pathpart} primitive@>
18334 mp_primitive(mp, "penpart",unary,pen_part);
18335 @:pen_part_}{\&{penpart} primitive@>
18336 mp_primitive(mp, "dashpart",unary,dash_part);
18337 @:dash_part_}{\&{dashpart} primitive@>
18338 mp_primitive(mp, "sqrt",unary,sqrt_op);
18339 @:sqrt_}{\&{sqrt} primitive@>
18340 mp_primitive(mp, "mexp",unary,m_exp_op);
18341 @:m_exp_}{\&{mexp} primitive@>
18342 mp_primitive(mp, "mlog",unary,m_log_op);
18343 @:m_log_}{\&{mlog} primitive@>
18344 mp_primitive(mp, "sind",unary,sin_d_op);
18345 @:sin_d_}{\&{sind} primitive@>
18346 mp_primitive(mp, "cosd",unary,cos_d_op);
18347 @:cos_d_}{\&{cosd} primitive@>
18348 mp_primitive(mp, "floor",unary,floor_op);
18349 @:floor_}{\&{floor} primitive@>
18350 mp_primitive(mp, "uniformdeviate",unary,uniform_deviate);
18351 @:uniform_deviate_}{\&{uniformdeviate} primitive@>
18352 mp_primitive(mp, "charexists",unary,char_exists_op);
18353 @:char_exists_}{\&{charexists} primitive@>
18354 mp_primitive(mp, "fontsize",unary,font_size);
18355 @:font_size_}{\&{fontsize} primitive@>
18356 mp_primitive(mp, "llcorner",unary,ll_corner_op);
18357 @:ll_corner_}{\&{llcorner} primitive@>
18358 mp_primitive(mp, "lrcorner",unary,lr_corner_op);
18359 @:lr_corner_}{\&{lrcorner} primitive@>
18360 mp_primitive(mp, "ulcorner",unary,ul_corner_op);
18361 @:ul_corner_}{\&{ulcorner} primitive@>
18362 mp_primitive(mp, "urcorner",unary,ur_corner_op);
18363 @:ur_corner_}{\&{urcorner} primitive@>
18364 mp_primitive(mp, "arclength",unary,arc_length);
18365 @:arc_length_}{\&{arclength} primitive@>
18366 mp_primitive(mp, "angle",unary,angle_op);
18367 @:angle_}{\&{angle} primitive@>
18368 mp_primitive(mp, "cycle",cycle,cycle_op);
18369 @:cycle_}{\&{cycle} primitive@>
18370 mp_primitive(mp, "stroked",unary,stroked_op);
18371 @:stroked_}{\&{stroked} primitive@>
18372 mp_primitive(mp, "filled",unary,filled_op);
18373 @:filled_}{\&{filled} primitive@>
18374 mp_primitive(mp, "textual",unary,textual_op);
18375 @:textual_}{\&{textual} primitive@>
18376 mp_primitive(mp, "clipped",unary,clipped_op);
18377 @:clipped_}{\&{clipped} primitive@>
18378 mp_primitive(mp, "bounded",unary,bounded_op);
18379 @:bounded_}{\&{bounded} primitive@>
18380 mp_primitive(mp, "+",plus_or_minus,plus);
18381 @:+ }{\.{+} primitive@>
18382 mp_primitive(mp, "-",plus_or_minus,minus);
18383 @:- }{\.{-} primitive@>
18384 mp_primitive(mp, "*",secondary_binary,times);
18385 @:* }{\.{*} primitive@>
18386 mp_primitive(mp, "/",slash,over); mp->eqtb[frozen_slash]=mp->eqtb[mp->cur_sym];
18387 @:/ }{\.{/} primitive@>
18388 mp_primitive(mp, "++",tertiary_binary,pythag_add);
18389 @:++_}{\.{++} primitive@>
18390 mp_primitive(mp, "+-+",tertiary_binary,pythag_sub);
18391 @:+-+_}{\.{+-+} primitive@>
18392 mp_primitive(mp, "or",tertiary_binary,or_op);
18393 @:or_}{\&{or} primitive@>
18394 mp_primitive(mp, "and",and_command,and_op);
18395 @:and_}{\&{and} primitive@>
18396 mp_primitive(mp, "<",expression_binary,less_than);
18397 @:< }{\.{<} primitive@>
18398 mp_primitive(mp, "<=",expression_binary,less_or_equal);
18399 @:<=_}{\.{<=} primitive@>
18400 mp_primitive(mp, ">",expression_binary,greater_than);
18401 @:> }{\.{>} primitive@>
18402 mp_primitive(mp, ">=",expression_binary,greater_or_equal);
18403 @:>=_}{\.{>=} primitive@>
18404 mp_primitive(mp, "=",equals,equal_to);
18405 @:= }{\.{=} primitive@>
18406 mp_primitive(mp, "<>",expression_binary,unequal_to);
18407 @:<>_}{\.{<>} primitive@>
18408 mp_primitive(mp, "substring",primary_binary,substring_of);
18409 @:substring_}{\&{substring} primitive@>
18410 mp_primitive(mp, "subpath",primary_binary,subpath_of);
18411 @:subpath_}{\&{subpath} primitive@>
18412 mp_primitive(mp, "directiontime",primary_binary,direction_time_of);
18413 @:direction_time_}{\&{directiontime} primitive@>
18414 mp_primitive(mp, "point",primary_binary,point_of);
18415 @:point_}{\&{point} primitive@>
18416 mp_primitive(mp, "precontrol",primary_binary,precontrol_of);
18417 @:precontrol_}{\&{precontrol} primitive@>
18418 mp_primitive(mp, "postcontrol",primary_binary,postcontrol_of);
18419 @:postcontrol_}{\&{postcontrol} primitive@>
18420 mp_primitive(mp, "penoffset",primary_binary,pen_offset_of);
18421 @:pen_offset_}{\&{penoffset} primitive@>
18422 mp_primitive(mp, "arctime",primary_binary,arc_time_of);
18423 @:arc_time_of_}{\&{arctime} primitive@>
18424 mp_primitive(mp, "mpversion",nullary,mp_version);
18425 @:mp_verison_}{\&{mpversion} primitive@>
18426 mp_primitive(mp, "&",ampersand,concatenate);
18427 @:!!!}{\.{\&} primitive@>
18428 mp_primitive(mp, "rotated",secondary_binary,rotated_by);
18429 @:rotated_}{\&{rotated} primitive@>
18430 mp_primitive(mp, "slanted",secondary_binary,slanted_by);
18431 @:slanted_}{\&{slanted} primitive@>
18432 mp_primitive(mp, "scaled",secondary_binary,scaled_by);
18433 @:scaled_}{\&{scaled} primitive@>
18434 mp_primitive(mp, "shifted",secondary_binary,shifted_by);
18435 @:shifted_}{\&{shifted} primitive@>
18436 mp_primitive(mp, "transformed",secondary_binary,transformed_by);
18437 @:transformed_}{\&{transformed} primitive@>
18438 mp_primitive(mp, "xscaled",secondary_binary,x_scaled);
18439 @:x_scaled_}{\&{xscaled} primitive@>
18440 mp_primitive(mp, "yscaled",secondary_binary,y_scaled);
18441 @:y_scaled_}{\&{yscaled} primitive@>
18442 mp_primitive(mp, "zscaled",secondary_binary,z_scaled);
18443 @:z_scaled_}{\&{zscaled} primitive@>
18444 mp_primitive(mp, "infont",secondary_binary,in_font);
18445 @:in_font_}{\&{infont} primitive@>
18446 mp_primitive(mp, "intersectiontimes",tertiary_binary,intersect);
18447 @:intersection_times_}{\&{intersectiontimes} primitive@>
18448
18449 @ @<Cases of |print_cmd...@>=
18450 case nullary:
18451 case unary:
18452 case primary_binary:
18453 case secondary_binary:
18454 case tertiary_binary:
18455 case expression_binary:
18456 case cycle:
18457 case plus_or_minus:
18458 case slash:
18459 case ampersand:
18460 case equals:
18461 case and_command:
18462   mp_print_op(mp, m);
18463   break;
18464
18465 @ OK, let's look at the simplest \\{do} procedure first.
18466
18467 @c @<Declare nullary action procedure@>;
18468 void mp_do_nullary (MP mp,quarterword c) { 
18469   check_arith;
18470   if ( mp->internal[tracing_commands]>two )
18471     mp_show_cmd_mod(mp, nullary,c);
18472   switch (c) {
18473   case true_code: case false_code: 
18474     mp->cur_type=mp_boolean_type; mp->cur_exp=c;
18475     break;
18476   case null_picture_code: 
18477     mp->cur_type=mp_picture_type;
18478     mp->cur_exp=mp_get_node(mp, edge_header_size); 
18479     mp_init_edges(mp, mp->cur_exp);
18480     break;
18481   case null_pen_code: 
18482     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, 0);
18483     break;
18484   case normal_deviate: 
18485     mp->cur_type=mp_known; mp->cur_exp=mp_norm_rand(mp);
18486     break;
18487   case pen_circle: 
18488     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, unity);
18489     break;
18490   case job_name_op:  
18491     if ( mp->job_name==NULL ) mp_open_log_file(mp);
18492     mp->cur_type=mp_string_type; mp->cur_exp=rts(mp->job_name);
18493     break;
18494   case mp_version: 
18495     mp->cur_type=mp_string_type; 
18496     mp->cur_exp=intern(metapost_version) ;
18497     break;
18498   case read_string_op:
18499     @<Read a string from the terminal@>;
18500     break;
18501   } /* there are no other cases */
18502   check_arith;
18503 }
18504
18505 @ @<Read a string...@>=
18506
18507   if ( mp->interaction<=mp_nonstop_mode )
18508     mp_fatal_error(mp, "*** (cannot readstring in nonstop modes)");
18509   mp_begin_file_reading(mp); name=is_read;
18510   limit=start; prompt_input("");
18511   mp_finish_read(mp);
18512 }
18513
18514 @ @<Declare nullary action procedure@>=
18515 void mp_finish_read (MP mp) { /* copy |buffer| line to |cur_exp| */
18516   size_t k;
18517   str_room((int)mp->last-start);
18518   for (k=start;k<=mp->last-1;k++) {
18519    append_char(mp->buffer[k]);
18520   }
18521   mp_end_file_reading(mp); mp->cur_type=mp_string_type; 
18522   mp->cur_exp=mp_make_string(mp);
18523 }
18524
18525 @ Things get a bit more interesting when there's an operand. The
18526 operand to |do_unary| appears in |cur_type| and |cur_exp|.
18527
18528 @c @<Declare unary action procedures@>;
18529 void mp_do_unary (MP mp,quarterword c) {
18530   pointer p,q,r; /* for list manipulation */
18531   integer x; /* a temporary register */
18532   check_arith;
18533   if ( mp->internal[tracing_commands]>two )
18534     @<Trace the current unary operation@>;
18535   switch (c) {
18536   case plus:
18537     if ( mp->cur_type<mp_color_type ) mp_bad_unary(mp, plus);
18538     break;
18539   case minus:
18540     @<Negate the current expression@>;
18541     break;
18542   @<Additional cases of unary operators@>;
18543   } /* there are no other cases */
18544   check_arith;
18545 };
18546
18547 @ The |nice_pair| function returns |true| if both components of a pair
18548 are known.
18549
18550 @<Declare unary action procedures@>=
18551 boolean mp_nice_pair (MP mp,integer p, quarterword t) { 
18552   if ( t==mp_pair_type ) {
18553     p=value(p);
18554     if ( type(x_part_loc(p))==mp_known )
18555       if ( type(y_part_loc(p))==mp_known )
18556         return true;
18557   }
18558   return false;
18559 }
18560
18561 @ The |nice_color_or_pair| function is analogous except that it also accepts
18562 fully known colors.
18563
18564 @<Declare unary action procedures@>=
18565 boolean mp_nice_color_or_pair (MP mp,integer p, quarterword t) {
18566   pointer q,r; /* for scanning the big node */
18567   if ( (t!=mp_pair_type)&&(t!=mp_color_type)&&(t!=mp_cmykcolor_type) ) {
18568     return false;
18569   } else { 
18570     q=value(p);
18571     r=q+mp->big_node_size[type(p)];
18572     do {  
18573       r=r-2;
18574       if ( type(r)!=mp_known )
18575         return false;
18576     } while (r!=q);
18577     return true;
18578   }
18579 }
18580
18581 @ @<Declare unary action...@>=
18582 void mp_print_known_or_unknown_type (MP mp,small_number t, integer v) { 
18583   mp_print_char(mp, '(');
18584   if ( t>mp_known ) mp_print(mp, "unknown numeric");
18585   else { if ( (t==mp_pair_type)||(t==mp_color_type)||(t==mp_cmykcolor_type) )
18586     if ( ! mp_nice_color_or_pair(mp, v,t) ) mp_print(mp, "unknown ");
18587     mp_print_type(mp, t);
18588   }
18589   mp_print_char(mp, ')');
18590 }
18591
18592 @ @<Declare unary action...@>=
18593 void mp_bad_unary (MP mp,quarterword c) { 
18594   exp_err("Not implemented: "); mp_print_op(mp, c);
18595 @.Not implemented...@>
18596   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
18597   help3("I'm afraid I don't know how to apply that operation to that")
18598     ("particular type. Continue, and I'll simply return the")
18599     ("argument (shown above) as the result of the operation.");
18600   mp_put_get_error(mp);
18601 }
18602
18603 @ @<Trace the current unary operation@>=
18604
18605   mp_begin_diagnostic(mp); mp_print_nl(mp, "{"); 
18606   mp_print_op(mp, c); mp_print_char(mp, '(');
18607   mp_print_exp(mp, null,0); /* show the operand, but not verbosely */
18608   mp_print(mp, ")}"); mp_end_diagnostic(mp, false);
18609 }
18610
18611 @ Negation is easy except when the current expression
18612 is of type |independent|, or when it is a pair with one or more
18613 |independent| components.
18614
18615 It is tempting to argue that the negative of an independent variable
18616 is an independent variable, hence we don't have to do anything when
18617 negating it. The fallacy is that other dependent variables pointing
18618 to the current expression must change the sign of their
18619 coefficients if we make no change to the current expression.
18620
18621 Instead, we work around the problem by copying the current expression
18622 and recycling it afterwards (cf.~the |stash_in| routine).
18623
18624 @<Negate the current expression@>=
18625 switch (mp->cur_type) {
18626 case mp_color_type:
18627 case mp_cmykcolor_type:
18628 case mp_pair_type:
18629 case mp_independent: 
18630   q=mp->cur_exp; mp_make_exp_copy(mp, q);
18631   if ( mp->cur_type==mp_dependent ) {
18632     mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18633   } else if ( mp->cur_type<=mp_pair_type ) { /* |mp_color_type| or |mp_pair_type| */
18634     p=value(mp->cur_exp);
18635     r=p+mp->big_node_size[mp->cur_type];
18636     do {  
18637       r=r-2;
18638       if ( type(r)==mp_known ) negate(value(r));
18639       else mp_negate_dep_list(mp, dep_list(r));
18640     } while (r!=p);
18641   } /* if |cur_type=mp_known| then |cur_exp=0| */
18642   mp_recycle_value(mp, q); mp_free_node(mp, q,value_node_size);
18643   break;
18644 case mp_dependent:
18645 case mp_proto_dependent:
18646   mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18647   break;
18648 case mp_known:
18649   negate(mp->cur_exp);
18650   break;
18651 default:
18652   mp_bad_unary(mp, minus);
18653   break;
18654 }
18655
18656 @ @<Declare unary action...@>=
18657 void mp_negate_dep_list (MP mp,pointer p) { 
18658   while (1) { 
18659     negate(value(p));
18660     if ( info(p)==null ) return;
18661     p=link(p);
18662   }
18663 }
18664
18665 @ @<Additional cases of unary operators@>=
18666 case not_op: 
18667   if ( mp->cur_type!=mp_boolean_type ) mp_bad_unary(mp, not_op);
18668   else mp->cur_exp=true_code+false_code-mp->cur_exp;
18669   break;
18670
18671 @ @d three_sixty_units 23592960 /* that's |360*unity| */
18672 @d boolean_reset(A) if ( (A) ) mp->cur_exp=true_code; else mp->cur_exp=false_code
18673
18674 @<Additional cases of unary operators@>=
18675 case sqrt_op:
18676 case m_exp_op:
18677 case m_log_op:
18678 case sin_d_op:
18679 case cos_d_op:
18680 case floor_op:
18681 case  uniform_deviate:
18682 case odd_op:
18683 case char_exists_op:
18684   if ( mp->cur_type!=mp_known ) {
18685     mp_bad_unary(mp, c);
18686   } else {
18687     switch (c) {
18688     case sqrt_op:mp->cur_exp=mp_square_rt(mp, mp->cur_exp);break;
18689     case m_exp_op:mp->cur_exp=mp_m_exp(mp, mp->cur_exp);break;
18690     case m_log_op:mp->cur_exp=mp_m_log(mp, mp->cur_exp);break;
18691     case sin_d_op:
18692     case cos_d_op:
18693       mp_n_sin_cos(mp, (mp->cur_exp % three_sixty_units)*16);
18694       if ( c==sin_d_op ) mp->cur_exp=mp_round_fraction(mp, mp->n_sin);
18695       else mp->cur_exp=mp_round_fraction(mp, mp->n_cos);
18696       break;
18697     case floor_op:mp->cur_exp=mp_floor_scaled(mp, mp->cur_exp);break;
18698     case uniform_deviate:mp->cur_exp=mp_unif_rand(mp, mp->cur_exp);break;
18699     case odd_op: 
18700       boolean_reset(odd(mp_round_unscaled(mp, mp->cur_exp)));
18701       mp->cur_type=mp_boolean_type;
18702       break;
18703     case char_exists_op:
18704       @<Determine if a character has been shipped out@>;
18705       break;
18706     } /* there are no other cases */
18707   }
18708   break;
18709
18710 @ @<Additional cases of unary operators@>=
18711 case angle_op:
18712   if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) ) {
18713     p=value(mp->cur_exp);
18714     x=mp_n_arg(mp, value(x_part_loc(p)),value(y_part_loc(p)));
18715     if ( x>=0 ) mp_flush_cur_exp(mp, (x+8)/ 16);
18716     else mp_flush_cur_exp(mp, -((-x+8)/ 16));
18717   } else {
18718     mp_bad_unary(mp, angle_op);
18719   }
18720   break;
18721
18722 @ If the current expression is a pair, but the context wants it to
18723 be a path, we call |pair_to_path|.
18724
18725 @<Declare unary action...@>=
18726 void mp_pair_to_path (MP mp) { 
18727   mp->cur_exp=mp_new_knot(mp); 
18728   mp->cur_type=mp_path_type;
18729 };
18730
18731 @ @<Additional cases of unary operators@>=
18732 case x_part:
18733 case y_part:
18734   if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_transform_type) )
18735     mp_take_part(mp, c);
18736   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18737   else mp_bad_unary(mp, c);
18738   break;
18739 case xx_part:
18740 case xy_part:
18741 case yx_part:
18742 case yy_part: 
18743   if ( mp->cur_type==mp_transform_type ) mp_take_part(mp, c);
18744   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18745   else mp_bad_unary(mp, c);
18746   break;
18747 case red_part:
18748 case green_part:
18749 case blue_part: 
18750   if ( mp->cur_type==mp_color_type ) mp_take_part(mp, c);
18751   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18752   else mp_bad_unary(mp, c);
18753   break;
18754 case cyan_part:
18755 case magenta_part:
18756 case yellow_part:
18757 case black_part: 
18758   if ( mp->cur_type==mp_cmykcolor_type) mp_take_part(mp, c); 
18759   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18760   else mp_bad_unary(mp, c);
18761   break;
18762 case grey_part: 
18763   if ( mp->cur_type==mp_known ) mp->cur_exp=value(c);
18764   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18765   else mp_bad_unary(mp, c);
18766   break;
18767 case color_model_part: 
18768   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18769   else mp_bad_unary(mp, c);
18770   break;
18771
18772 @ In the following procedure, |cur_exp| points to a capsule, which points to
18773 a big node. We want to delete all but one part of the big node.
18774
18775 @<Declare unary action...@>=
18776 void mp_take_part (MP mp,quarterword c) {
18777   pointer p; /* the big node */
18778   p=value(mp->cur_exp); value(temp_val)=p; type(temp_val)=mp->cur_type;
18779   link(p)=temp_val; mp_free_node(mp, mp->cur_exp,value_node_size);
18780   mp_make_exp_copy(mp, p+mp->sector_offset[c+mp_x_part_sector-x_part]);
18781   mp_recycle_value(mp, temp_val);
18782 }
18783
18784 @ @<Initialize table entries...@>=
18785 name_type(temp_val)=mp_capsule;
18786
18787 @ @<Additional cases of unary operators@>=
18788 case font_part:
18789 case text_part:
18790 case path_part:
18791 case pen_part:
18792 case dash_part:
18793   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18794   else mp_bad_unary(mp, c);
18795   break;
18796
18797 @ @<Declarations@>=
18798 void mp_scale_edges (MP mp);
18799
18800 @ @<Declare unary action...@>=
18801 void mp_take_pict_part (MP mp,quarterword c) {
18802   pointer p; /* first graphical object in |cur_exp| */
18803   p=link(dummy_loc(mp->cur_exp));
18804   if ( p!=null ) {
18805     switch (c) {
18806     case x_part: case y_part: case xx_part:
18807     case xy_part: case yx_part: case yy_part:
18808       if ( type(p)==text_code ) mp_flush_cur_exp(mp, text_trans_part(p+c));
18809       else goto NOT_FOUND;
18810       break;
18811     case red_part: case green_part: case blue_part:
18812       if ( has_color(p) ) mp_flush_cur_exp(mp, obj_color_part(p+c));
18813       else goto NOT_FOUND;
18814       break;
18815     case cyan_part: case magenta_part: case yellow_part:
18816     case black_part:
18817       if ( has_color(p) ) {
18818         if ( color_model(p)==uninitialized_model )
18819           mp_flush_cur_exp(mp, unity);
18820         else
18821           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-cyan_part)));
18822       } else goto NOT_FOUND;
18823       break;
18824     case grey_part:
18825       if ( has_color(p) )
18826           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-grey_part)));
18827       else goto NOT_FOUND;
18828       break;
18829     case color_model_part:
18830       if ( has_color(p) ) {
18831         if ( color_model(p)==uninitialized_model )
18832           mp_flush_cur_exp(mp, mp->internal[default_color_model]);
18833         else
18834           mp_flush_cur_exp(mp, color_model(p)*unity);
18835       } else goto NOT_FOUND;
18836       break;
18837     @<Handle other cases in |take_pict_part| or |goto not_found|@>;
18838     } /* all cases have been enumerated */
18839     return;
18840   };
18841 NOT_FOUND:
18842   @<Convert the current expression to a null value appropriate
18843     for |c|@>;
18844 }
18845
18846 @ @<Handle other cases in |take_pict_part| or |goto not_found|@>=
18847 case text_part: 
18848   if ( type(p)!=text_code ) goto NOT_FOUND;
18849   else { 
18850     mp_flush_cur_exp(mp, text_p(p));
18851     add_str_ref(mp->cur_exp);
18852     mp->cur_type=mp_string_type;
18853     };
18854   break;
18855 case font_part: 
18856   if ( type(p)!=text_code ) goto NOT_FOUND;
18857   else { 
18858     mp_flush_cur_exp(mp, rts(mp->font_name[font_n(p)])); 
18859     add_str_ref(mp->cur_exp);
18860     mp->cur_type=mp_string_type;
18861   };
18862   break;
18863 case path_part:
18864   if ( type(p)==text_code ) goto NOT_FOUND;
18865   else if ( is_stop(p) ) mp_confusion(mp, "pict");
18866 @:this can't happen pict}{\quad pict@>
18867   else { 
18868     mp_flush_cur_exp(mp, mp_copy_path(mp, path_p(p)));
18869     mp->cur_type=mp_path_type;
18870   }
18871   break;
18872 case pen_part: 
18873   if ( ! has_pen(p) ) goto NOT_FOUND;
18874   else {
18875     if ( pen_p(p)==null ) goto NOT_FOUND;
18876     else { mp_flush_cur_exp(mp, copy_pen(pen_p(p)));
18877       mp->cur_type=mp_pen_type;
18878     };
18879   }
18880   break;
18881 case dash_part: 
18882   if ( type(p)!=stroked_code ) goto NOT_FOUND;
18883   else { if ( dash_p(p)==null ) goto NOT_FOUND;
18884     else { add_edge_ref(dash_p(p));
18885     mp->se_sf=dash_scale(p);
18886     mp->se_pic=dash_p(p);
18887     mp_scale_edges(mp);
18888     mp_flush_cur_exp(mp, mp->se_pic);
18889     mp->cur_type=mp_picture_type;
18890     };
18891   }
18892   break;
18893
18894 @ Since |scale_edges| had to be declared |forward|, it had to be declared as a
18895 parameterless procedure even though it really takes two arguments and updates
18896 one of them.  Hence the following globals are needed.
18897
18898 @<Global...@>=
18899 pointer se_pic;  /* edge header used and updated by |scale_edges| */
18900 scaled se_sf;  /* the scale factor argument to |scale_edges| */
18901
18902 @ @<Convert the current expression to a null value appropriate...@>=
18903 switch (c) {
18904 case text_part: case font_part: 
18905   mp_flush_cur_exp(mp, rts(""));
18906   mp->cur_type=mp_string_type;
18907   break;
18908 case path_part: 
18909   mp_flush_cur_exp(mp, mp_get_node(mp, knot_node_size));
18910   left_type(mp->cur_exp)=endpoint;
18911   right_type(mp->cur_exp)=endpoint;
18912   link(mp->cur_exp)=mp->cur_exp;
18913   x_coord(mp->cur_exp)=0;
18914   y_coord(mp->cur_exp)=0;
18915   originator(mp->cur_exp)=metapost_user;
18916   mp->cur_type=mp_path_type;
18917   break;
18918 case pen_part: 
18919   mp_flush_cur_exp(mp, mp_get_pen_circle(mp, 0));
18920   mp->cur_type=mp_pen_type;
18921   break;
18922 case dash_part: 
18923   mp_flush_cur_exp(mp, mp_get_node(mp, edge_header_size));
18924   mp_init_edges(mp, mp->cur_exp);
18925   mp->cur_type=mp_picture_type;
18926   break;
18927 default: 
18928    mp_flush_cur_exp(mp, 0);
18929   break;
18930 }
18931
18932 @ @<Additional cases of unary...@>=
18933 case char_op: 
18934   if ( mp->cur_type!=mp_known ) { 
18935     mp_bad_unary(mp, char_op);
18936   } else { 
18937     mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256; 
18938     mp->cur_type=mp_string_type;
18939     if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
18940   }
18941   break;
18942 case decimal: 
18943   if ( mp->cur_type!=mp_known ) {
18944      mp_bad_unary(mp, decimal);
18945   } else { 
18946     mp->old_setting=mp->selector; mp->selector=new_string;
18947     mp_print_scaled(mp, mp->cur_exp); mp->cur_exp=mp_make_string(mp);
18948     mp->selector=mp->old_setting; mp->cur_type=mp_string_type;
18949   }
18950   break;
18951 case oct_op:
18952 case hex_op:
18953 case ASCII_op: 
18954   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
18955   else mp_str_to_num(mp, c);
18956   break;
18957 case font_size: 
18958   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, font_size);
18959   else @<Find the design size of the font whose name is |cur_exp|@>;
18960   break;
18961
18962 @ @<Declare unary action...@>=
18963 void mp_str_to_num (MP mp,quarterword c) { /* converts a string to a number */
18964   integer n; /* accumulator */
18965   ASCII_code m; /* current character */
18966   pool_pointer k; /* index into |str_pool| */
18967   int b; /* radix of conversion */
18968   boolean bad_char; /* did the string contain an invalid digit? */
18969   if ( c==ASCII_op ) {
18970     if ( length(mp->cur_exp)==0 ) n=-1;
18971     else n=mp->str_pool[mp->str_start[mp->cur_exp]];
18972   } else { 
18973     if ( c==oct_op ) b=8; else b=16;
18974     n=0; bad_char=false;
18975     for (k=mp->str_start[mp->cur_exp];k<=str_stop(mp->cur_exp)-1;k++) {
18976       m=mp->str_pool[k];
18977       if ( (m>='0')&&(m<='9') ) m=m-'0';
18978       else if ( (m>='A')&&(m<='F') ) m=m-'A'+10;
18979       else if ( (m>='a')&&(m<='f') ) m=m-'a'+10;
18980       else  { bad_char=true; m=0; };
18981       if ( m>=b ) { bad_char=true; m=0; };
18982       if ( n<32768 / b ) n=n*b+m; else n=32767;
18983     }
18984     @<Give error messages if |bad_char| or |n>=4096|@>;
18985   }
18986   mp_flush_cur_exp(mp, n*unity);
18987 }
18988
18989 @ @<Give error messages if |bad_char|...@>=
18990 if ( bad_char ) { 
18991   exp_err("String contains illegal digits");
18992 @.String contains illegal digits@>
18993   if ( c==oct_op ) {
18994     help1("I zeroed out characters that weren't in the range 0..7.");
18995   } else  {
18996     help1("I zeroed out characters that weren't hex digits.");
18997   }
18998   mp_put_get_error(mp);
18999 }
19000 if ( (n>4095) ) {
19001   if ( mp->internal[warning_check]>0 ) {
19002     print_err("Number too large ("); 
19003     mp_print_int(mp, n); mp_print_char(mp, ')');
19004 @.Number too large@>
19005     help2("I have trouble with numbers greater than 4095; watch out.")
19006       ("(Set warningcheck:=0 to suppress this message.)");
19007     mp_put_get_error(mp);
19008   }
19009 }
19010
19011 @ The length operation is somewhat unusual in that it applies to a variety
19012 of different types of operands.
19013
19014 @<Additional cases of unary...@>=
19015 case length_op: 
19016   switch (mp->cur_type) {
19017   case mp_string_type: mp_flush_cur_exp(mp, length(mp->cur_exp)*unity); break;
19018   case mp_path_type: mp_flush_cur_exp(mp, mp_path_length(mp)); break;
19019   case mp_known: mp->cur_exp=abs(mp->cur_exp); break;
19020   case mp_picture_type: mp_flush_cur_exp(mp, mp_pict_length(mp)); break;
19021   default: 
19022     if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) )
19023       mp_flush_cur_exp(mp, mp_pyth_add(mp, 
19024         value(x_part_loc(value(mp->cur_exp))),
19025         value(y_part_loc(value(mp->cur_exp)))));
19026     else mp_bad_unary(mp, c);
19027     break;
19028   }
19029   break;
19030
19031 @ @<Declare unary action...@>=
19032 scaled mp_path_length (MP mp) { /* computes the length of the current path */
19033   scaled n; /* the path length so far */
19034   pointer p; /* traverser */
19035   p=mp->cur_exp;
19036   if ( left_type(p)==endpoint ) n=-unity; else n=0;
19037   do {  p=link(p); n=n+unity; } while (p!=mp->cur_exp);
19038   return n;
19039 }
19040
19041 @ @<Declare unary action...@>=
19042 scaled mp_pict_length (MP mp) { 
19043   /* counts interior components in picture |cur_exp| */
19044   scaled n; /* the count so far */
19045   pointer p; /* traverser */
19046   n=0;
19047   p=link(dummy_loc(mp->cur_exp));
19048   if ( p!=null ) {
19049     if ( is_start_or_stop(p) )
19050       if ( mp_skip_1component(mp, p)==null ) p=link(p);
19051     while ( p!=null )  { 
19052       skip_component(p) return n; 
19053       n=n+unity;   
19054     }
19055   }
19056   return n;
19057 }
19058
19059 @ Implement |turningnumber|
19060
19061 @<Additional cases of unary...@>=
19062 case turning_op:
19063   if ( mp->cur_type==mp_pair_type ) mp_flush_cur_exp(mp, 0);
19064   else if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, turning_op);
19065   else if ( left_type(mp->cur_exp)==endpoint )
19066      mp_flush_cur_exp(mp, 0); /* not a cyclic path */
19067   else
19068     mp_flush_cur_exp(mp, mp_turn_cycles_wrapper(mp, mp->cur_exp));
19069   break;
19070
19071 @ The function |an_angle| returns the value of the |angle| primitive, or $0$ if the
19072 argument is |origin|.
19073
19074 @<Declare unary action...@>=
19075 angle mp_an_angle (MP mp,scaled xpar, scaled ypar) {
19076   if ( (! ((xpar==0) && (ypar==0))) )
19077     return mp_n_arg(mp, xpar,ypar);
19078   return 0;
19079 }
19080
19081
19082 @ The actual turning number is (for the moment) computed in a C function
19083 that receives eight integers corresponding to the four controlling points,
19084 and returns a single angle.  Besides those, we have to account for discrete
19085 moves at the actual points.
19086
19087 @d floor(a) (a>=0 ? a : -(int)(-a))
19088 @d bezier_error (720<<20)+1
19089 @d sign(v) ((v)>0 ? 1 : ((v)<0 ? -1 : 0 ))
19090 @d print_roots(a) { if (debuglevel>(65536*2))
19091    fprintf(stdout,"bezier_slope(): %s, i=%f, o=%f, angle=%f\n", (a),in,out,res); }
19092 @d out ((double)(xo>>20))
19093 @d mid ((double)(xm>>20))
19094 @d in  ((double)(xi>>20))
19095 @d divisor (256*256)
19096 @d double2angle(a) (int)floor(a*256.0*256.0*16.0)
19097
19098 @<Declare unary action...@>=
19099 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19100             integer CX,integer CY,integer DX,integer DY, int debuglevel);
19101
19102 @ @c 
19103 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19104             integer CX,integer CY,integer DX,integer DY, int debuglevel) {
19105   double a, b, c;
19106   integer deltax,deltay;
19107   double ax,ay,bx,by,cx,cy,dx,dy;
19108   angle xi = 0, xo = 0, xm = 0;
19109   double res = 0;
19110   ax=AX/divisor;  ay=AY/divisor;
19111   bx=BX/divisor;  by=BY/divisor;
19112   cx=CX/divisor;  cy=CY/divisor;
19113   dx=DX/divisor;  dy=DY/divisor;
19114
19115   deltax = (BX-AX); deltay = (BY-AY);
19116   if (deltax==0 && deltay == 0) { deltax=(CX-AX); deltay=(CY-AY); }
19117   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19118   xi = mp_an_angle(mp,deltax,deltay);
19119
19120   deltax = (CX-BX); deltay = (CY-BY);
19121   xm = mp_an_angle(mp,deltax,deltay);
19122
19123   deltax = (DX-CX); deltay = (DY-CY);
19124   if (deltax==0 && deltay == 0) { deltax=(DX-BX); deltay=(DY-BY); }
19125   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19126   xo = mp_an_angle(mp,deltax,deltay);
19127
19128   a = (bx-ax)*(cy-by) - (cx-bx)*(by-ay); /* a = (bp-ap)x(cp-bp); */
19129   b = (bx-ax)*(dy-cy) - (by-ay)*(dx-cx);; /* b = (bp-ap)x(dp-cp);*/
19130   c = (cx-bx)*(dy-cy) - (dx-cx)*(cy-by); /* c = (cp-bp)x(dp-cp);*/
19131
19132   if (debuglevel>(65536*2)) {
19133     fprintf(stdout,
19134       "bezier_slope(): (%.2f,%.2f),(%.2f,%.2f),(%.2f,%.2f),(%.2f,%.2f)\n",
19135               ax,ay,bx,by,cx,cy,dx,dy);
19136     fprintf(stdout,
19137       "bezier_slope(): a,b,c,b^2,4ac: (%.2f,%.2f,%.2f,%.2f,%.2f)\n",a,b,c,b*b,4*a*c);
19138   }
19139
19140   if ((a==0)&&(c==0)) {
19141     res = (b==0 ?  0 :  (out-in)); 
19142     print_roots("no roots (a)");
19143   } else if ((a==0)||(c==0)) {
19144     if ((sign(b) == sign(a)) || (sign(b) == sign(c))) {
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("no roots (b)");
19151     } else {
19152       res = out-in; /* ? */
19153       print_roots("one root (a)");
19154     }
19155   } else if ((sign(a)*sign(c))<0) {
19156     res = out-in; /* ? */
19157       if (res<-180.0) 
19158         res += 360.0;
19159       else if (res>180.0)
19160         res -= 360.0;
19161     print_roots("one root (b)");
19162   } else {
19163     if (sign(a) == sign(b)) {
19164       res = out-in; /* ? */
19165       if (res<-180.0) 
19166         res += 360.0;
19167       else if (res>180.0)
19168         res -= 360.0;
19169       print_roots("no roots (d)");
19170     } else {
19171       if ((b*b) == (4*a*c)) {
19172         res = bezier_error;
19173         print_roots("double root"); /* cusp */
19174       } else if ((b*b) < (4*a*c)) {
19175         res = out-in; /* ? */
19176         if (res<=0.0 &&res>-180.0) 
19177           res += 360.0;
19178         else if (res>=0.0 && res<180.0)
19179           res -= 360.0;
19180         print_roots("no roots (e)");
19181       } else {
19182         res = out-in;
19183         if (res<-180.0) 
19184           res += 360.0;
19185         else if (res>180.0)
19186           res -= 360.0;
19187         print_roots("two roots"); /* two inflections */
19188       }
19189     }
19190   }
19191   return double2angle(res);
19192 }
19193
19194 @
19195 @d p_nextnext link(link(p))
19196 @d p_next link(p)
19197 @d seven_twenty_deg 05500000000 /* $720\cdot2^{20}$, represents $720^\circ$ */
19198
19199 @<Declare unary action...@>=
19200 scaled mp_new_turn_cycles (MP mp,pointer c) {
19201   angle res,ang; /*  the angles of intermediate results  */
19202   scaled turns;  /*  the turn counter  */
19203   pointer p;     /*  for running around the path  */
19204   integer xp,yp;   /*  coordinates of next point  */
19205   integer x,y;   /*  helper coordinates  */
19206   angle in_angle,out_angle;     /*  helper angles */
19207   int old_setting; /* saved |selector| setting */
19208   res=0;
19209   turns= 0;
19210   p=c;
19211   old_setting = mp->selector; mp->selector=term_only;
19212   if ( mp->internal[tracing_commands]>unity ) {
19213     mp_begin_diagnostic(mp);
19214     mp_print_nl(mp, "");
19215     mp_end_diagnostic(mp, false);
19216   }
19217   do { 
19218     xp = x_coord(p_next); yp = y_coord(p_next);
19219     ang  = mp_bezier_slope(mp,x_coord(p), y_coord(p), right_x(p), right_y(p),
19220              left_x(p_next), left_y(p_next), xp, yp, 
19221              mp->internal[tracing_commands]);
19222     if ( ang>seven_twenty_deg ) {
19223       print_err("Strange path");
19224       mp_error(mp);
19225       mp->selector=old_setting;
19226       return 0;
19227     }
19228     res  = res + ang;
19229     if ( res > one_eighty_deg ) {
19230       res = res - three_sixty_deg;
19231       turns = turns + unity;
19232     }
19233     if ( res <= -one_eighty_deg ) {
19234       res = res + three_sixty_deg;
19235       turns = turns - unity;
19236     }
19237     /*  incoming angle at next point  */
19238     x = left_x(p_next);  y = left_y(p_next);
19239     if ( (xp==x)&&(yp==y) ) { x = right_x(p);  y = right_y(p);  };
19240     if ( (xp==x)&&(yp==y) ) { x = x_coord(p);  y = y_coord(p);  };
19241     in_angle = mp_an_angle(mp, xp - x, yp - y);
19242     /*  outgoing angle at next point  */
19243     x = right_x(p_next);  y = right_y(p_next);
19244     if ( (xp==x)&&(yp==y) ) { x = left_x(p_nextnext);  y = left_y(p_nextnext);  };
19245     if ( (xp==x)&&(yp==y) ) { x = x_coord(p_nextnext); y = y_coord(p_nextnext); };
19246     out_angle = mp_an_angle(mp, x - xp, y- yp);
19247     ang  = (out_angle - in_angle);
19248     reduce_angle(ang);
19249     if ( ang!=0 ) {
19250       res  = res + ang;
19251       if ( res >= one_eighty_deg ) {
19252         res = res - three_sixty_deg;
19253         turns = turns + unity;
19254       };
19255       if ( res <= -one_eighty_deg ) {
19256         res = res + three_sixty_deg;
19257         turns = turns - unity;
19258       };
19259     };
19260     p = link(p);
19261   } while (p!=c);
19262   mp->selector=old_setting;
19263   return turns;
19264 }
19265
19266
19267 @ This code is based on Bogus\l{}av Jackowski's
19268 |emergency_turningnumber| macro, with some minor changes by Taco
19269 Hoekwater. The macro code looked more like this:
19270 {\obeylines
19271 vardef turning\_number primary p =
19272 ~~save res, ang, turns;
19273 ~~res := 0;
19274 ~~if length p <= 2:
19275 ~~~~if Angle ((point 0 of p) - (postcontrol 0 of p)) >= 0:  1  else: -1 fi
19276 ~~else:
19277 ~~~~for t = 0 upto length p-1 :
19278 ~~~~~~angc := Angle ((point t+1 of p)  - (point t of p))
19279 ~~~~~~~~- Angle ((point t of p) - (point t-1 of p));
19280 ~~~~~~if angc > 180: angc := angc - 360; fi;
19281 ~~~~~~if angc < -180: angc := angc + 360; fi;
19282 ~~~~~~res  := res + angc;
19283 ~~~~endfor;
19284 ~~res/360
19285 ~~fi
19286 enddef;}
19287 The general idea is to calculate only the sum of the angles of
19288 straight lines between the points, of a path, not worrying about cusps
19289 or self-intersections in the segments at all. If the segment is not
19290 well-behaved, the result is not necesarily correct. But the old code
19291 was not always correct either, and worse, it sometimes failed for
19292 well-behaved paths as well. All known bugs that were triggered by the
19293 original code no longer occur with this code, and it runs roughly 3
19294 times as fast because the algorithm is much simpler.
19295
19296 @ It is possible to overflow the return value of the |turn_cycles|
19297 function when the path is sufficiently long and winding, but I am not
19298 going to bother testing for that. In any case, it would only return
19299 the looped result value, which is not a big problem.
19300
19301 The macro code for the repeat loop was a bit nicer to look
19302 at than the pascal code, because it could use |point -1 of p|. In
19303 pascal, the fastest way to loop around the path is not to look
19304 backward once, but forward twice. These defines help hide the trick.
19305
19306 @d p_to link(link(p))
19307 @d p_here link(p)
19308 @d p_from p
19309
19310 @<Declare unary action...@>=
19311 scaled mp_turn_cycles (MP mp,pointer c) {
19312   angle res,ang; /*  the angles of intermediate results  */
19313   scaled turns;  /*  the turn counter  */
19314   pointer p;     /*  for running around the path  */
19315   res=0;  turns= 0; p=c;
19316   do { 
19317     ang  = mp_an_angle (mp, x_coord(p_to) - x_coord(p_here), 
19318                             y_coord(p_to) - y_coord(p_here))
19319         - mp_an_angle (mp, x_coord(p_here) - x_coord(p_from), 
19320                            y_coord(p_here) - y_coord(p_from));
19321     reduce_angle(ang);
19322     res  = res + ang;
19323     if ( res >= three_sixty_deg )  {
19324       res = res - three_sixty_deg;
19325       turns = turns + unity;
19326     };
19327     if ( res <= -three_sixty_deg ) {
19328       res = res + three_sixty_deg;
19329       turns = turns - unity;
19330     };
19331     p = link(p);
19332   } while (p!=c);
19333   return turns;
19334 }
19335
19336 @ @<Declare unary action...@>=
19337 scaled mp_turn_cycles_wrapper (MP mp,pointer c) {
19338   scaled nval,oval;
19339   scaled saved_t_o; /* tracing\_online saved  */
19340   if ( (link(c)==c)||(link(link(c))==c) ) {
19341     if ( mp_an_angle (mp, x_coord(c) - right_x(c),  y_coord(c) - right_y(c)) > 0 )
19342       return unity;
19343     else
19344       return -unity;
19345   } else {
19346     nval = mp_new_turn_cycles(mp, c);
19347     oval = mp_turn_cycles(mp, c);
19348     if ( nval!=oval ) {
19349       saved_t_o=mp->internal[tracing_online];
19350       mp->internal[tracing_online]=unity;
19351       mp_begin_diagnostic(mp);
19352       mp_print_nl (mp, "Warning: the turningnumber algorithms do not agree."
19353                        " The current computed value is ");
19354       mp_print_scaled(mp, nval);
19355       mp_print(mp, ", but the 'connect-the-dots' algorithm returned ");
19356       mp_print_scaled(mp, oval);
19357       mp_end_diagnostic(mp, false);
19358       mp->internal[tracing_online]=saved_t_o;
19359     }
19360     return nval;
19361   }
19362 }
19363
19364 @ @<Declare unary action...@>=
19365 scaled mp_count_turns (MP mp,pointer c) {
19366   pointer p; /* a knot in envelope spec |c| */
19367   integer t; /* total pen offset changes counted */
19368   t=0; p=c;
19369   do {  
19370     t=t+info(p)-zero_off;
19371     p=link(p);
19372   } while (p!=c);
19373   return ((t / 3)*unity);
19374 }
19375
19376 @ @d type_range(A,B) { 
19377   if ( (mp->cur_type>=(A)) && (mp->cur_type<=(B)) ) 
19378     mp_flush_cur_exp(mp, true_code);
19379   else mp_flush_cur_exp(mp, false_code);
19380   mp->cur_type=mp_boolean_type;
19381   }
19382 @d type_test(A) { 
19383   if ( mp->cur_type==(A) ) mp_flush_cur_exp(mp, true_code);
19384   else mp_flush_cur_exp(mp, false_code);
19385   mp->cur_type=mp_boolean_type;
19386   }
19387
19388 @<Additional cases of unary operators@>=
19389 case mp_boolean_type: 
19390   type_range(mp_boolean_type,mp_unknown_boolean); break;
19391 case mp_string_type: 
19392   type_range(mp_string_type,mp_unknown_string); break;
19393 case mp_pen_type: 
19394   type_range(mp_pen_type,mp_unknown_pen); break;
19395 case mp_path_type: 
19396   type_range(mp_path_type,mp_unknown_path); break;
19397 case mp_picture_type: 
19398   type_range(mp_picture_type,mp_unknown_picture); break;
19399 case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
19400 case mp_pair_type: 
19401   type_test(c); break;
19402 case mp_numeric_type: 
19403   type_range(mp_known,mp_independent); break;
19404 case known_op: case unknown_op: 
19405   mp_test_known(mp, c); break;
19406
19407 @ @<Declare unary action procedures@>=
19408 void mp_test_known (MP mp,quarterword c) {
19409   int b; /* is the current expression known? */
19410   pointer p,q; /* locations in a big node */
19411   b=false_code;
19412   switch (mp->cur_type) {
19413   case mp_vacuous: case mp_boolean_type: case mp_string_type:
19414   case mp_pen_type: case mp_path_type: case mp_picture_type:
19415   case mp_known: 
19416     b=true_code;
19417     break;
19418   case mp_transform_type:
19419   case mp_color_type: case mp_cmykcolor_type: case mp_pair_type: 
19420     p=value(mp->cur_exp);
19421     q=p+mp->big_node_size[mp->cur_type];
19422     do {  
19423       q=q-2;
19424       if ( type(q)!=mp_known ) 
19425        goto DONE;
19426     } while (q!=p);
19427     b=true_code;
19428   DONE:  
19429     break;
19430   default: 
19431     break;
19432   }
19433   if ( c==known_op ) mp_flush_cur_exp(mp, b);
19434   else mp_flush_cur_exp(mp, true_code+false_code-b);
19435   mp->cur_type=mp_boolean_type;
19436 }
19437
19438 @ @<Additional cases of unary operators@>=
19439 case cycle_op: 
19440   if ( mp->cur_type!=mp_path_type ) mp_flush_cur_exp(mp, false_code);
19441   else if ( left_type(mp->cur_exp)!=endpoint ) mp_flush_cur_exp(mp, true_code);
19442   else mp_flush_cur_exp(mp, false_code);
19443   mp->cur_type=mp_boolean_type;
19444   break;
19445
19446 @ @<Additional cases of unary operators@>=
19447 case arc_length: 
19448   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19449   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, arc_length);
19450   else mp_flush_cur_exp(mp, mp_get_arc_length(mp, mp->cur_exp));
19451   break;
19452
19453 @ Here we use the fact that |c-filled_op+fill_code| is the desired graphical
19454 object |type|.
19455 @^data structure assumptions@>
19456
19457 @<Additional cases of unary operators@>=
19458 case filled_op:
19459 case stroked_op:
19460 case textual_op:
19461 case clipped_op:
19462 case bounded_op:
19463   if ( mp->cur_type!=mp_picture_type ) mp_flush_cur_exp(mp, false_code);
19464   else if ( link(dummy_loc(mp->cur_exp))==null ) mp_flush_cur_exp(mp, false_code);
19465   else if ( type(link(dummy_loc(mp->cur_exp)))==c+fill_code-filled_op )
19466     mp_flush_cur_exp(mp, true_code);
19467   else mp_flush_cur_exp(mp, false_code);
19468   mp->cur_type=mp_boolean_type;
19469   break;
19470
19471 @ @<Additional cases of unary operators@>=
19472 case make_pen_op: 
19473   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19474   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, make_pen_op);
19475   else { 
19476     mp->cur_type=mp_pen_type;
19477     mp->cur_exp=mp_make_pen(mp, mp->cur_exp,true);
19478   };
19479   break;
19480 case make_path_op: 
19481   if ( mp->cur_type!=mp_pen_type ) mp_bad_unary(mp, make_path_op);
19482   else  { 
19483     mp->cur_type=mp_path_type;
19484     mp_make_path(mp, mp->cur_exp);
19485   };
19486   break;
19487 case reverse: 
19488   if ( mp->cur_type==mp_path_type ) {
19489     p=mp_htap_ypoc(mp, mp->cur_exp);
19490     if ( right_type(p)==endpoint ) p=link(p);
19491     mp_toss_knot_list(mp, mp->cur_exp); mp->cur_exp=p;
19492   } else if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19493   else mp_bad_unary(mp, reverse);
19494   break;
19495
19496 @ The |pair_value| routine changes the current expression to a
19497 given ordered pair of values.
19498
19499 @<Declare unary action procedures@>=
19500 void mp_pair_value (MP mp,scaled x, scaled y) {
19501   pointer p; /* a pair node */
19502   p=mp_get_node(mp, value_node_size); 
19503   mp_flush_cur_exp(mp, p); mp->cur_type=mp_pair_type;
19504   type(p)=mp_pair_type; name_type(p)=mp_capsule; mp_init_big_node(mp, p);
19505   p=value(p);
19506   type(x_part_loc(p))=mp_known; value(x_part_loc(p))=x;
19507   type(y_part_loc(p))=mp_known; value(y_part_loc(p))=y;
19508 }
19509
19510 @ @<Additional cases of unary operators@>=
19511 case ll_corner_op: 
19512   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ll_corner_op);
19513   else mp_pair_value(mp, minx,miny);
19514   break;
19515 case lr_corner_op: 
19516   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, lr_corner_op);
19517   else mp_pair_value(mp, maxx,miny);
19518   break;
19519 case ul_corner_op: 
19520   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ul_corner_op);
19521   else mp_pair_value(mp, minx,maxy);
19522   break;
19523 case ur_corner_op: 
19524   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ur_corner_op);
19525   else mp_pair_value(mp, maxx,maxy);
19526   break;
19527
19528 @ Here is a function that sets |minx|, |maxx|, |miny|, |maxy| to the bounding
19529 box of the current expression.  The boolean result is |false| if the expression
19530 has the wrong type.
19531
19532 @<Declare unary action procedures@>=
19533 boolean mp_get_cur_bbox (MP mp) { 
19534   switch (mp->cur_type) {
19535   case mp_picture_type: 
19536     mp_set_bbox(mp, mp->cur_exp,true);
19537     if ( minx_val(mp->cur_exp)>maxx_val(mp->cur_exp) ) {
19538       minx=0; maxx=0; miny=0; maxy=0;
19539     } else { 
19540       minx=minx_val(mp->cur_exp);
19541       maxx=maxx_val(mp->cur_exp);
19542       miny=miny_val(mp->cur_exp);
19543       maxy=maxy_val(mp->cur_exp);
19544     }
19545     break;
19546   case mp_path_type: 
19547     mp_path_bbox(mp, mp->cur_exp);
19548     break;
19549   case mp_pen_type: 
19550     mp_pen_bbox(mp, mp->cur_exp);
19551     break;
19552   default: 
19553     return false;
19554   }
19555   return true;
19556 }
19557
19558 @ @<Additional cases of unary operators@>=
19559 case read_from_op:
19560 case close_from_op: 
19561   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19562   else mp_do_read_or_close(mp,c);
19563   break;
19564
19565 @ Here is a routine that interprets |cur_exp| as a file name and tries to read
19566 a line from the file or to close the file.
19567
19568 @d close_file 46 /* go here when closing the file */
19569
19570 @<Declare unary action procedures@>=
19571 void mp_do_read_or_close (MP mp,quarterword c) {
19572   readf_index n,n0; /* indices for searching |rd_fname| */
19573   @<Find the |n| where |rd_fname[n]=cur_exp|; if |cur_exp| must be inserted,
19574     call |start_read_input| and |goto found| or |not_found|@>;
19575   mp_begin_file_reading(mp);
19576   name=is_read;
19577   if ( mp_input_ln(mp, mp->rd_file[n],true) ) 
19578     goto FOUND;
19579   mp_end_file_reading(mp);
19580 NOT_FOUND:
19581   @<Record the end of file and set |cur_exp| to a dummy value@>;
19582   return;
19583 CLOSE_FILE:
19584   mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous; 
19585   return;
19586 FOUND:
19587   mp_flush_cur_exp(mp, 0);
19588   mp_finish_read(mp);
19589 }
19590
19591 @ Free slots in the |rd_file| and |rd_fname| arrays are marked with NULL's in
19592 |rd_fname|.
19593
19594 @<Find the |n| where |rd_fname[n]=cur_exp|...@>=
19595 {   
19596   char *fn;
19597   n=mp->read_files;
19598   n0=mp->read_files;
19599   fn = str(mp->cur_exp);
19600   while (mp_xstrcmp(fn,mp->rd_fname[n])!=0) { 
19601     if ( n>0 ) {
19602       decr(n);
19603     } else if ( c==close_from_op ) {
19604       goto CLOSE_FILE;
19605     } else {
19606       if ( n0==mp->read_files ) {
19607         if ( mp->read_files<mp->max_read_files ) {
19608           incr(mp->read_files);
19609         } else {
19610           FILE **rd_file;
19611           char **rd_fname;
19612               readf_index l,k;
19613           l = mp->max_read_files + (mp->max_read_files>>2);
19614           rd_file = xmalloc((l+1), sizeof(FILE *));
19615           rd_fname = xmalloc((l+1), sizeof(char *));
19616               for (k=0;k<=l;k++) {
19617             if (k<=mp->max_read_files) {
19618                   rd_file[k]=mp->rd_file[k]; 
19619               rd_fname[k]=mp->rd_fname[k];
19620             } else {
19621                   rd_file[k]=0; 
19622               rd_fname[k]=NULL;
19623             }
19624           }
19625               xfree(mp->rd_file); xfree(mp->rd_fname);
19626           mp->max_read_files = l;
19627           mp->rd_file = rd_file;
19628           mp->rd_fname = rd_fname;
19629         }
19630       }
19631       n=n0;
19632       if ( mp_start_read_input(mp,fn,n) ) 
19633         goto FOUND;
19634       else 
19635         goto NOT_FOUND;
19636     }
19637     if ( mp->rd_fname[n]==NULL ) { n0=n; }
19638   } 
19639   if ( c==close_from_op ) { 
19640     fclose(mp->rd_file[n]); 
19641     goto NOT_FOUND; 
19642   }
19643 }
19644
19645 @ @<Record the end of file and set |cur_exp| to a dummy value@>=
19646 xfree(mp->rd_fname[n]);
19647 mp->rd_fname[n]=NULL;
19648 if ( n==mp->read_files-1 ) mp->read_files=n;
19649 if ( c==close_from_op ) 
19650   goto CLOSE_FILE;
19651 mp_flush_cur_exp(mp, mp->eof_line);
19652 mp->cur_type=mp_string_type
19653
19654 @ The string denoting end-of-file is a one-byte string at position zero, by definition
19655
19656 @<Glob...@>=
19657 str_number eof_line;
19658
19659 @ @<Set init...@>=
19660 mp->eof_line=0;
19661
19662 @ Finally, we have the operations that combine a capsule~|p|
19663 with the current expression.
19664
19665 @c @<Declare binary action procedures@>;
19666 void mp_do_binary (MP mp,pointer p, quarterword c) {
19667   pointer q,r,rr; /* for list manipulation */
19668   pointer old_p,old_exp; /* capsules to recycle */
19669   integer v; /* for numeric manipulation */
19670   check_arith;
19671   if ( mp->internal[tracing_commands]>two ) {
19672     @<Trace the current binary operation@>;
19673   }
19674   @<Sidestep |independent| cases in capsule |p|@>;
19675   @<Sidestep |independent| cases in the current expression@>;
19676   switch (c) {
19677   case plus: case minus:
19678     @<Add or subtract the current expression from |p|@>;
19679     break;
19680   @<Additional cases of binary operators@>;
19681   }; /* there are no other cases */
19682   mp_recycle_value(mp, p); 
19683   mp_free_node(mp, p,value_node_size); /* |return| to avoid this */
19684   check_arith; 
19685   @<Recycle any sidestepped |independent| capsules@>;
19686 }
19687
19688 @ @<Declare binary action...@>=
19689 void mp_bad_binary (MP mp,pointer p, quarterword c) { 
19690   mp_disp_err(mp, p,"");
19691   exp_err("Not implemented: ");
19692 @.Not implemented...@>
19693   if ( c>=min_of ) mp_print_op(mp, c);
19694   mp_print_known_or_unknown_type(mp, type(p),p);
19695   if ( c>=min_of ) mp_print(mp, "of"); else mp_print_op(mp, c);
19696   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
19697   help3("I'm afraid I don't know how to apply that operation to that")
19698        ("combination of types. Continue, and I'll return the second")
19699       ("argument (see above) as the result of the operation.");
19700   mp_put_get_error(mp);
19701 }
19702
19703 @ @<Trace the current binary operation@>=
19704
19705   mp_begin_diagnostic(mp); mp_print_nl(mp, "{(");
19706   mp_print_exp(mp,p,0); /* show the operand, but not verbosely */
19707   mp_print_char(mp,')'); mp_print_op(mp,c); mp_print_char(mp,'(');
19708   mp_print_exp(mp,null,0); mp_print(mp,")}"); 
19709   mp_end_diagnostic(mp, false);
19710 }
19711
19712 @ Several of the binary operations are potentially complicated by the
19713 fact that |independent| values can sneak into capsules. For example,
19714 we've seen an instance of this difficulty in the unary operation
19715 of negation. In order to reduce the number of cases that need to be
19716 handled, we first change the two operands (if necessary)
19717 to rid them of |independent| components. The original operands are
19718 put into capsules called |old_p| and |old_exp|, which will be
19719 recycled after the binary operation has been safely carried out.
19720
19721 @<Recycle any sidestepped |independent| capsules@>=
19722 if ( old_p!=null ) { 
19723   mp_recycle_value(mp, old_p); mp_free_node(mp, old_p,value_node_size);
19724 }
19725 if ( old_exp!=null ) {
19726   mp_recycle_value(mp, old_exp); mp_free_node(mp, old_exp,value_node_size);
19727 }
19728
19729 @ A big node is considered to be ``tarnished'' if it contains at least one
19730 independent component. We will define a simple function called `|tarnished|'
19731 that returns |null| if and only if its argument is not tarnished.
19732
19733 @<Sidestep |independent| cases in capsule |p|@>=
19734 switch (type(p)) {
19735 case mp_transform_type:
19736 case mp_color_type:
19737 case mp_cmykcolor_type:
19738 case mp_pair_type: 
19739   old_p=mp_tarnished(mp, p);
19740   break;
19741 case mp_independent: old_p=diov; break;
19742 default: old_p=null; break;
19743 };
19744 if ( old_p!=null ) {
19745   q=mp_stash_cur_exp(mp); old_p=p; mp_make_exp_copy(mp, old_p);
19746   p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
19747 }
19748
19749 @ @<Sidestep |independent| cases in the current expression@>=
19750 switch (mp->cur_type) {
19751 case mp_transform_type:
19752 case mp_color_type:
19753 case mp_cmykcolor_type:
19754 case mp_pair_type: 
19755   old_exp=mp_tarnished(mp, mp->cur_exp);
19756   break;
19757 case mp_independent:old_exp=diov; break;
19758 default: old_exp=null; break;
19759 };
19760 if ( old_exp!=null ) {
19761   old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
19762 }
19763
19764 @ @<Declare binary action...@>=
19765 pointer mp_tarnished (MP mp,pointer p) {
19766   pointer q; /* beginning of the big node */
19767   pointer r; /* current position in the big node */
19768   q=value(p); r=q+mp->big_node_size[type(p)];
19769   do {  
19770    r=r-2;
19771    if ( type(r)==mp_independent ) return diov; 
19772   } while (r!=q);
19773   return null;
19774 }
19775
19776 @ @<Add or subtract the current expression from |p|@>=
19777 if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
19778   mp_bad_binary(mp, p,c);
19779 } else  {
19780   if ((mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
19781     mp_add_or_subtract(mp, p,null,c);
19782   } else {
19783     if ( mp->cur_type!=type(p) )  {
19784       mp_bad_binary(mp, p,c);
19785     } else { 
19786       q=value(p); r=value(mp->cur_exp);
19787       rr=r+mp->big_node_size[mp->cur_type];
19788       while ( r<rr ) { 
19789         mp_add_or_subtract(mp, q,r,c);
19790         q=q+2; r=r+2;
19791       }
19792     }
19793   }
19794 }
19795
19796 @ The first argument to |add_or_subtract| is the location of a value node
19797 in a capsule or pair node that will soon be recycled. The second argument
19798 is either a location within a pair or transform node of |cur_exp|,
19799 or it is null (which means that |cur_exp| itself should be the second
19800 argument).  The third argument is either |plus| or |minus|.
19801
19802 The sum or difference of the numeric quantities will replace the second
19803 operand.  Arithmetic overflow may go undetected; users aren't supposed to
19804 be monkeying around with really big values.
19805
19806 @<Declare binary action...@>=
19807 @<Declare the procedure called |dep_finish|@>;
19808 void mp_add_or_subtract (MP mp,pointer p, pointer q, quarterword c) {
19809   small_number s,t; /* operand types */
19810   pointer r; /* list traverser */
19811   integer v; /* second operand value */
19812   if ( q==null ) { 
19813     t=mp->cur_type;
19814     if ( t<mp_dependent ) v=mp->cur_exp; else v=dep_list(mp->cur_exp);
19815   } else { 
19816     t=type(q);
19817     if ( t<mp_dependent ) v=value(q); else v=dep_list(q);
19818   }
19819   if ( t==mp_known ) {
19820     if ( c==minus ) negate(v);
19821     if ( type(p)==mp_known ) {
19822       v=mp_slow_add(mp, value(p),v);
19823       if ( q==null ) mp->cur_exp=v; else value(q)=v;
19824       return;
19825     }
19826     @<Add a known value to the constant term of |dep_list(p)|@>;
19827   } else  { 
19828     if ( c==minus ) mp_negate_dep_list(mp, v);
19829     @<Add operand |p| to the dependency list |v|@>;
19830   }
19831 }
19832
19833 @ @<Add a known value to the constant term of |dep_list(p)|@>=
19834 r=dep_list(p);
19835 while ( info(r)!=null ) r=link(r);
19836 value(r)=mp_slow_add(mp, value(r),v);
19837 if ( q==null ) {
19838   q=mp_get_node(mp, value_node_size); mp->cur_exp=q; mp->cur_type=type(p);
19839   name_type(q)=mp_capsule;
19840 }
19841 dep_list(q)=dep_list(p); type(q)=type(p);
19842 prev_dep(q)=prev_dep(p); link(prev_dep(p))=q;
19843 type(p)=mp_known; /* this will keep the recycler from collecting non-garbage */
19844
19845 @ We prefer |dependent| lists to |mp_proto_dependent| ones, because it is
19846 nice to retain the extra accuracy of |fraction| coefficients.
19847 But we have to handle both kinds, and mixtures too.
19848
19849 @<Add operand |p| to the dependency list |v|@>=
19850 if ( type(p)==mp_known ) {
19851   @<Add the known |value(p)| to the constant term of |v|@>;
19852 } else { 
19853   s=type(p); r=dep_list(p);
19854   if ( t==mp_dependent ) {
19855     if ( s==mp_dependent ) {
19856       if ( mp_max_coef(mp, r)+mp_max_coef(mp, v)<coef_bound )
19857         v=mp_p_plus_q(mp, v,r,mp_dependent); goto DONE;
19858       } /* |fix_needed| will necessarily be false */
19859       t=mp_proto_dependent; 
19860       v=mp_p_over_v(mp, v,unity,mp_dependent,mp_proto_dependent);
19861     }
19862     if ( s==mp_proto_dependent ) v=mp_p_plus_q(mp, v,r,mp_proto_dependent);
19863     else v=mp_p_plus_fq(mp, v,unity,r,mp_proto_dependent,mp_dependent);
19864  DONE:  
19865     @<Output the answer, |v| (which might have become |known|)@>;
19866   }
19867
19868 @ @<Add the known |value(p)| to the constant term of |v|@>=
19869
19870   while ( info(v)!=null ) v=link(v);
19871   value(v)=mp_slow_add(mp, value(p),value(v));
19872 }
19873
19874 @ @<Output the answer, |v| (which might have become |known|)@>=
19875 if ( q!=null ) mp_dep_finish(mp, v,q,t);
19876 else  { mp->cur_type=t; mp_dep_finish(mp, v,null,t); }
19877
19878 @ Here's the current situation: The dependency list |v| of type |t|
19879 should either be put into the current expression (if |q=null|) or
19880 into location |q| within a pair node (otherwise). The destination (|cur_exp|
19881 or |q|) formerly held a dependency list with the same
19882 final pointer as the list |v|.
19883
19884 @<Declare the procedure called |dep_finish|@>=
19885 void mp_dep_finish (MP mp, pointer v, pointer q, small_number t) {
19886   pointer p; /* the destination */
19887   scaled vv; /* the value, if it is |known| */
19888   if ( q==null ) p=mp->cur_exp; else p=q;
19889   dep_list(p)=v; type(p)=t;
19890   if ( info(v)==null ) { 
19891     vv=value(v);
19892     if ( q==null ) { 
19893       mp_flush_cur_exp(mp, vv);
19894     } else  { 
19895       mp_recycle_value(mp, p); type(q)=mp_known; value(q)=vv; 
19896     }
19897   } else if ( q==null ) {
19898     mp->cur_type=t;
19899   }
19900   if ( mp->fix_needed ) mp_fix_dependencies(mp);
19901 }
19902
19903 @ Let's turn now to the six basic relations of comparison.
19904
19905 @<Additional cases of binary operators@>=
19906 case less_than: case less_or_equal: case greater_than:
19907 case greater_or_equal: case equal_to: case unequal_to:
19908   check_arith; /* at this point |arith_error| should be |false|? */
19909   if ( (mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
19910     mp_add_or_subtract(mp, p,null,minus); /* |cur_exp:=(p)-cur_exp| */
19911   } else if ( mp->cur_type!=type(p) ) {
19912     mp_bad_binary(mp, p,c); goto DONE; 
19913   } else if ( mp->cur_type==mp_string_type ) {
19914     mp_flush_cur_exp(mp, mp_str_vs_str(mp, value(p),mp->cur_exp));
19915   } else if ((mp->cur_type==mp_unknown_string)||
19916            (mp->cur_type==mp_unknown_boolean) ) {
19917     @<Check if unknowns have been equated@>;
19918   } else if ( (mp->cur_type<=mp_pair_type)&&(mp->cur_type>=mp_transform_type)) {
19919     @<Reduce comparison of big nodes to comparison of scalars@>;
19920   } else if ( mp->cur_type==mp_boolean_type ) {
19921     mp_flush_cur_exp(mp, mp->cur_exp-value(p));
19922   } else { 
19923     mp_bad_binary(mp, p,c); goto DONE;
19924   }
19925   @<Compare the current expression with zero@>;
19926 DONE:  
19927   mp->arith_error=false; /* ignore overflow in comparisons */
19928   break;
19929
19930 @ @<Compare the current expression with zero@>=
19931 if ( mp->cur_type!=mp_known ) {
19932   if ( mp->cur_type<mp_known ) {
19933     mp_disp_err(mp, p,"");
19934     help1("The quantities shown above have not been equated.")
19935   } else  {
19936     help2("Oh dear. I can\'t decide if the expression above is positive,")
19937      ("negative, or zero. So this comparison test won't be `true'.");
19938   }
19939   exp_err("Unknown relation will be considered false");
19940 @.Unknown relation...@>
19941   mp_put_get_flush_error(mp, false_code);
19942 } else {
19943   switch (c) {
19944   case less_than: boolean_reset(mp->cur_exp<0); break;
19945   case less_or_equal: boolean_reset(mp->cur_exp<=0); break;
19946   case greater_than: boolean_reset(mp->cur_exp>0); break;
19947   case greater_or_equal: boolean_reset(mp->cur_exp>=0); break;
19948   case equal_to: boolean_reset(mp->cur_exp==0); break;
19949   case unequal_to: boolean_reset(mp->cur_exp!=0); break;
19950   }; /* there are no other cases */
19951 }
19952 mp->cur_type=mp_boolean_type
19953
19954 @ When two unknown strings are in the same ring, we know that they are
19955 equal. Otherwise, we don't know whether they are equal or not, so we
19956 make no change.
19957
19958 @<Check if unknowns have been equated@>=
19959
19960   q=value(mp->cur_exp);
19961   while ( (q!=mp->cur_exp)&&(q!=p) ) q=value(q);
19962   if ( q==p ) mp_flush_cur_exp(mp, 0);
19963 }
19964
19965 @ @<Reduce comparison of big nodes to comparison of scalars@>=
19966
19967   q=value(p); r=value(mp->cur_exp);
19968   rr=r+mp->big_node_size[mp->cur_type]-2;
19969   while (1) { mp_add_or_subtract(mp, q,r,minus);
19970     if ( type(r)!=mp_known ) break;
19971     if ( value(r)!=0 ) break;
19972     if ( r==rr ) break;
19973     q=q+2; r=r+2;
19974   }
19975   mp_take_part(mp, name_type(r)+x_part-mp_x_part_sector);
19976 }
19977
19978 @ Here we use the sneaky fact that |and_op-false_code=or_op-true_code|.
19979
19980 @<Additional cases of binary operators@>=
19981 case and_op:
19982 case or_op: 
19983   if ( (type(p)!=mp_boolean_type)||(mp->cur_type!=mp_boolean_type) )
19984     mp_bad_binary(mp, p,c);
19985   else if ( value(p)==c+false_code-and_op ) mp->cur_exp=value(p);
19986   break;
19987
19988 @ @<Additional cases of binary operators@>=
19989 case times: 
19990   if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
19991    mp_bad_binary(mp, p,times);
19992   } else if ( (mp->cur_type==mp_known)||(type(p)==mp_known) ) {
19993     @<Multiply when at least one operand is known@>;
19994   } else if ( (mp_nice_color_or_pair(mp, p,type(p))&&(mp->cur_type>mp_pair_type))
19995       ||(mp_nice_color_or_pair(mp, mp->cur_exp,mp->cur_type)&&
19996           (type(p)>mp_pair_type)) ) {
19997     mp_hard_times(mp, p); return;
19998   } else {
19999     mp_bad_binary(mp, p,times);
20000   }
20001   break;
20002
20003 @ @<Multiply when at least one operand is known@>=
20004
20005   if ( type(p)==mp_known ) {
20006     v=value(p); mp_free_node(mp, p,value_node_size); 
20007   } else {
20008     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20009   }
20010   if ( mp->cur_type==mp_known ) {
20011     mp->cur_exp=mp_take_scaled(mp, mp->cur_exp,v);
20012   } else if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_color_type)||
20013               (mp->cur_type==mp_cmykcolor_type) ) {
20014     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20015     do {  
20016        p=p-2; mp_dep_mult(mp, p,v,true);
20017     } while (p!=value(mp->cur_exp));
20018   } else {
20019     mp_dep_mult(mp, null,v,true);
20020   }
20021   return;
20022 }
20023
20024 @ @<Declare binary action...@>=
20025 void mp_dep_mult (MP mp,pointer p, integer v, boolean v_is_scaled) {
20026   pointer q; /* the dependency list being multiplied by |v| */
20027   small_number s,t; /* its type, before and after */
20028   if ( p==null ) {
20029     q=mp->cur_exp;
20030   } else if ( type(p)!=mp_known ) {
20031     q=p;
20032   } else { 
20033     if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
20034     else value(p)=mp_take_fraction(mp, value(p),v);
20035     return;
20036   };
20037   t=type(q); q=dep_list(q); s=t;
20038   if ( t==mp_dependent ) if ( v_is_scaled )
20039     if (mp_ab_vs_cd(mp, mp_max_coef(mp,q),abs(v),coef_bound-1,unity)>=0 ) 
20040       t=mp_proto_dependent;
20041   q=mp_p_times_v(mp, q,v,s,t,v_is_scaled); 
20042   mp_dep_finish(mp, q,p,t);
20043 }
20044
20045 @ Here is a routine that is similar to |times|; but it is invoked only
20046 internally, when |v| is a |fraction| whose magnitude is at most~1,
20047 and when |cur_type>=mp_color_type|.
20048
20049 @c void mp_frac_mult (MP mp,scaled n, scaled d) {
20050   /* multiplies |cur_exp| by |n/d| */
20051   pointer p; /* a pair node */
20052   pointer old_exp; /* a capsule to recycle */
20053   fraction v; /* |n/d| */
20054   if ( mp->internal[tracing_commands]>two ) {
20055     @<Trace the fraction multiplication@>;
20056   }
20057   switch (mp->cur_type) {
20058   case mp_transform_type:
20059   case mp_color_type:
20060   case mp_cmykcolor_type:
20061   case mp_pair_type:
20062    old_exp=mp_tarnished(mp, mp->cur_exp);
20063    break;
20064   case mp_independent: old_exp=diov; break;
20065   default: old_exp=null; break;
20066   }
20067   if ( old_exp!=null ) { 
20068      old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
20069   }
20070   v=mp_make_fraction(mp, n,d);
20071   if ( mp->cur_type==mp_known ) {
20072     mp->cur_exp=mp_take_fraction(mp, mp->cur_exp,v);
20073   } else if ( mp->cur_type<=mp_pair_type ) { 
20074     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20075     do {  
20076       p=p-2;
20077       mp_dep_mult(mp, p,v,false);
20078     } while (p!=value(mp->cur_exp));
20079   } else {
20080     mp_dep_mult(mp, null,v,false);
20081   }
20082   if ( old_exp!=null ) {
20083     mp_recycle_value(mp, old_exp); 
20084     mp_free_node(mp, old_exp,value_node_size);
20085   }
20086 }
20087
20088 @ @<Trace the fraction multiplication@>=
20089
20090   mp_begin_diagnostic(mp); 
20091   mp_print_nl(mp, "{("); mp_print_scaled(mp,n); mp_print_char(mp,'/');
20092   mp_print_scaled(mp,d); mp_print(mp,")*("); mp_print_exp(mp,null,0); 
20093   mp_print(mp,")}");
20094   mp_end_diagnostic(mp, false);
20095 }
20096
20097 @ The |hard_times| routine multiplies a nice color or pair by a dependency list.
20098
20099 @<Declare binary action procedures@>=
20100 void mp_hard_times (MP mp,pointer p) {
20101   pointer q; /* a copy of the dependent variable |p| */
20102   pointer r; /* a component of the big node for the nice color or pair */
20103   scaled v; /* the known value for |r| */
20104   if ( type(p)<=mp_pair_type ) { 
20105      q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p); p=q;
20106   }; /* now |cur_type=mp_pair_type| or |cur_type=mp_color_type| */
20107   r=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20108   while (1) { 
20109     r=r-2;
20110     v=value(r);
20111     type(r)=type(p);
20112     if ( r==value(mp->cur_exp) ) 
20113       break;
20114     mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(p)));
20115     mp_dep_mult(mp, r,v,true);
20116   }
20117   mp->mem[value_loc(r)]=mp->mem[value_loc(p)];
20118   link(prev_dep(p))=r;
20119   mp_free_node(mp, p,value_node_size);
20120   mp_dep_mult(mp, r,v,true);
20121 }
20122
20123 @ @<Additional cases of binary operators@>=
20124 case over: 
20125   if ( (mp->cur_type!=mp_known)||(type(p)<mp_color_type) ) {
20126     mp_bad_binary(mp, p,over);
20127   } else { 
20128     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20129     if ( v==0 ) {
20130       @<Squeal about division by zero@>;
20131     } else { 
20132       if ( mp->cur_type==mp_known ) {
20133         mp->cur_exp=mp_make_scaled(mp, mp->cur_exp,v);
20134       } else if ( mp->cur_type<=mp_pair_type ) { 
20135         p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20136         do {  
20137           p=p-2;  mp_dep_div(mp, p,v);
20138         } while (p!=value(mp->cur_exp));
20139       } else {
20140         mp_dep_div(mp, null,v);
20141       }
20142     }
20143     return;
20144   }
20145   break;
20146
20147 @ @<Declare binary action...@>=
20148 void mp_dep_div (MP mp,pointer p, scaled v) {
20149   pointer q; /* the dependency list being divided by |v| */
20150   small_number s,t; /* its type, before and after */
20151   if ( p==null ) q=mp->cur_exp;
20152   else if ( type(p)!=mp_known ) q=p;
20153   else { value(p)=mp_make_scaled(mp, value(p),v); return; };
20154   t=type(q); q=dep_list(q); s=t;
20155   if ( t==mp_dependent )
20156     if ( mp_ab_vs_cd(mp, mp_max_coef(mp,q),unity,coef_bound-1,abs(v))>=0 ) 
20157       t=mp_proto_dependent;
20158   q=mp_p_over_v(mp, q,v,s,t); 
20159   mp_dep_finish(mp, q,p,t);
20160 }
20161
20162 @ @<Squeal about division by zero@>=
20163
20164   exp_err("Division by zero");
20165 @.Division by zero@>
20166   help2("You're trying to divide the quantity shown above the error")
20167     ("message by zero. I'm going to divide it by one instead.");
20168   mp_put_get_error(mp);
20169 }
20170
20171 @ @<Additional cases of binary operators@>=
20172 case pythag_add:
20173 case pythag_sub: 
20174    if ( (mp->cur_type==mp_known)&&(type(p)==mp_known) ) {
20175      if ( c==pythag_add ) mp->cur_exp=mp_pyth_add(mp, value(p),mp->cur_exp);
20176      else mp->cur_exp=mp_pyth_sub(mp, value(p),mp->cur_exp);
20177    } else mp_bad_binary(mp, p,c);
20178    break;
20179
20180 @ The next few sections of the program deal with affine transformations
20181 of coordinate data.
20182
20183 @<Additional cases of binary operators@>=
20184 case rotated_by: case slanted_by:
20185 case scaled_by: case shifted_by: case transformed_by:
20186 case x_scaled: case y_scaled: case z_scaled:
20187   if ( type(p)==mp_path_type ) { 
20188     path_trans(c,p); return;
20189   } else if ( type(p)==mp_pen_type ) { 
20190     pen_trans(c,p);
20191     mp->cur_exp=mp_convex_hull(mp, mp->cur_exp); 
20192       /* rounding error could destroy convexity */
20193     return;
20194   } else if ( (type(p)==mp_pair_type)||(type(p)==mp_transform_type) ) {
20195     mp_big_trans(mp, p,c);
20196   } else if ( type(p)==mp_picture_type ) {
20197     mp_do_edges_trans(mp, p,c); return;
20198   } else {
20199     mp_bad_binary(mp, p,c);
20200   }
20201   break;
20202
20203 @ Let |c| be one of the eight transform operators. The procedure call
20204 |set_up_trans(c)| first changes |cur_exp| to a transform that corresponds to
20205 |c| and the original value of |cur_exp|. (In particular, |cur_exp| doesn't
20206 change at all if |c=transformed_by|.)
20207
20208 Then, if all components of the resulting transform are |known|, they are
20209 moved to the global variables |txx|, |txy|, |tyx|, |tyy|, |tx|, |ty|;
20210 and |cur_exp| is changed to the known value zero.
20211
20212 @<Declare binary action...@>=
20213 void mp_set_up_trans (MP mp,quarterword c) {
20214   pointer p,q,r; /* list manipulation registers */
20215   if ( (c!=transformed_by)||(mp->cur_type!=mp_transform_type) ) {
20216     @<Put the current transform into |cur_exp|@>;
20217   }
20218   @<If the current transform is entirely known, stash it in global variables;
20219     otherwise |return|@>;
20220 }
20221
20222 @ @<Glob...@>=
20223 scaled txx;
20224 scaled txy;
20225 scaled tyx;
20226 scaled tyy;
20227 scaled tx;
20228 scaled ty; /* current transform coefficients */
20229
20230 @ @<Put the current transform...@>=
20231
20232   p=mp_stash_cur_exp(mp); 
20233   mp->cur_exp=mp_id_transform(mp); 
20234   mp->cur_type=mp_transform_type;
20235   q=value(mp->cur_exp);
20236   switch (c) {
20237   @<For each of the eight cases, change the relevant fields of |cur_exp|
20238     and |goto done|;
20239     but do nothing if capsule |p| doesn't have the appropriate type@>;
20240   }; /* there are no other cases */
20241   mp_disp_err(mp, p,"Improper transformation argument");
20242 @.Improper transformation argument@>
20243   help3("The expression shown above has the wrong type,")
20244        ("so I can\'t transform anything using it.")
20245        ("Proceed, and I'll omit the transformation.");
20246   mp_put_get_error(mp);
20247 DONE: 
20248   mp_recycle_value(mp, p); 
20249   mp_free_node(mp, p,value_node_size);
20250 }
20251
20252 @ @<If the current transform is entirely known, ...@>=
20253 q=value(mp->cur_exp); r=q+transform_node_size;
20254 do {  
20255   r=r-2;
20256   if ( type(r)!=mp_known ) return;
20257 } while (r!=q);
20258 mp->txx=value(xx_part_loc(q));
20259 mp->txy=value(xy_part_loc(q));
20260 mp->tyx=value(yx_part_loc(q));
20261 mp->tyy=value(yy_part_loc(q));
20262 mp->tx=value(x_part_loc(q));
20263 mp->ty=value(y_part_loc(q));
20264 mp_flush_cur_exp(mp, 0)
20265
20266 @ @<For each of the eight cases...@>=
20267 case rotated_by:
20268   if ( type(p)==mp_known )
20269     @<Install sines and cosines, then |goto done|@>;
20270   break;
20271 case slanted_by:
20272   if ( type(p)>mp_pair_type ) { 
20273    mp_install(mp, xy_part_loc(q),p); goto DONE;
20274   };
20275   break;
20276 case scaled_by:
20277   if ( type(p)>mp_pair_type ) { 
20278     mp_install(mp, xx_part_loc(q),p); mp_install(mp, yy_part_loc(q),p); 
20279     goto DONE;
20280   };
20281   break;
20282 case shifted_by:
20283   if ( type(p)==mp_pair_type ) {
20284     r=value(p); mp_install(mp, x_part_loc(q),x_part_loc(r));
20285     mp_install(mp, y_part_loc(q),y_part_loc(r)); goto DONE;
20286   };
20287   break;
20288 case x_scaled:
20289   if ( type(p)>mp_pair_type ) {
20290     mp_install(mp, xx_part_loc(q),p); goto DONE;
20291   };
20292   break;
20293 case y_scaled:
20294   if ( type(p)>mp_pair_type ) {
20295     mp_install(mp, yy_part_loc(q),p); goto DONE;
20296   };
20297   break;
20298 case z_scaled:
20299   if ( type(p)==mp_pair_type )
20300     @<Install a complex multiplier, then |goto done|@>;
20301   break;
20302 case transformed_by:
20303   break;
20304   
20305
20306 @ @<Install sines and cosines, then |goto done|@>=
20307 { mp_n_sin_cos(mp, (value(p) % three_sixty_units)*16);
20308   value(xx_part_loc(q))=mp_round_fraction(mp, mp->n_cos);
20309   value(yx_part_loc(q))=mp_round_fraction(mp, mp->n_sin);
20310   value(xy_part_loc(q))=-value(yx_part_loc(q));
20311   value(yy_part_loc(q))=value(xx_part_loc(q));
20312   goto DONE;
20313 }
20314
20315 @ @<Install a complex multiplier, then |goto done|@>=
20316
20317   r=value(p);
20318   mp_install(mp, xx_part_loc(q),x_part_loc(r));
20319   mp_install(mp, yy_part_loc(q),x_part_loc(r));
20320   mp_install(mp, yx_part_loc(q),y_part_loc(r));
20321   if ( type(y_part_loc(r))==mp_known ) negate(value(y_part_loc(r)));
20322   else mp_negate_dep_list(mp, dep_list(y_part_loc(r)));
20323   mp_install(mp, xy_part_loc(q),y_part_loc(r));
20324   goto DONE;
20325 }
20326
20327 @ Procedure |set_up_known_trans| is like |set_up_trans|, but it
20328 insists that the transformation be entirely known.
20329
20330 @<Declare binary action...@>=
20331 void mp_set_up_known_trans (MP mp,quarterword c) { 
20332   mp_set_up_trans(mp, c);
20333   if ( mp->cur_type!=mp_known ) {
20334     exp_err("Transform components aren't all known");
20335 @.Transform components...@>
20336     help3("I'm unable to apply a partially specified transformation")
20337       ("except to a fully known pair or transform.")
20338       ("Proceed, and I'll omit the transformation.");
20339     mp_put_get_flush_error(mp, 0);
20340     mp->txx=unity; mp->txy=0; mp->tyx=0; mp->tyy=unity; 
20341     mp->tx=0; mp->ty=0;
20342   }
20343 }
20344
20345 @ Here's a procedure that applies the transform |txx..ty| to a pair of
20346 coordinates in locations |p| and~|q|.
20347
20348 @<Declare binary action...@>= 
20349 void mp_trans (MP mp,pointer p, pointer q) {
20350   scaled v; /* the new |x| value */
20351   v=mp_take_scaled(mp, mp->mem[p].sc,mp->txx)+
20352   mp_take_scaled(mp, mp->mem[q].sc,mp->txy)+mp->tx;
20353   mp->mem[q].sc=mp_take_scaled(mp, mp->mem[p].sc,mp->tyx)+
20354   mp_take_scaled(mp, mp->mem[q].sc,mp->tyy)+mp->ty;
20355   mp->mem[p].sc=v;
20356 }
20357
20358 @ The simplest transformation procedure applies a transform to all
20359 coordinates of a path.  The |path_trans(c)(p)| macro applies
20360 a transformation defined by |cur_exp| and the transform operator |c|
20361 to the path~|p|.
20362
20363 @d path_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20364                      mp_unstash_cur_exp(mp, (B)); 
20365                      mp_do_path_trans(mp, mp->cur_exp); }
20366
20367 @<Declare binary action...@>=
20368 void mp_do_path_trans (MP mp,pointer p) {
20369   pointer q; /* list traverser */
20370   q=p;
20371   do { 
20372     if ( left_type(q)!=endpoint ) 
20373       mp_trans(mp, q+3,q+4); /* that's |left_x| and |left_y| */
20374     mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20375     if ( right_type(q)!=endpoint ) 
20376       mp_trans(mp, q+5,q+6); /* that's |right_x| and |right_y| */
20377 @^data structure assumptions@>
20378     q=link(q);
20379   } while (q!=p);
20380 }
20381
20382 @ Transforming a pen is very similar, except that there are no |left_type|
20383 and |right_type| fields.
20384
20385 @d pen_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20386                     mp_unstash_cur_exp(mp, (B)); 
20387                     mp_do_pen_trans(mp, mp->cur_exp); }
20388
20389 @<Declare binary action...@>=
20390 void mp_do_pen_trans (MP mp,pointer p) {
20391   pointer q; /* list traverser */
20392   if ( pen_is_elliptical(p) ) {
20393     mp_trans(mp, p+3,p+4); /* that's |left_x| and |left_y| */
20394     mp_trans(mp, p+5,p+6); /* that's |right_x| and |right_y| */
20395   };
20396   q=p;
20397   do { 
20398     mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20399 @^data structure assumptions@>
20400     q=link(q);
20401   } while (q!=p);
20402 }
20403
20404 @ The next transformation procedure applies to edge structures. It will do
20405 any transformation, but the results may be substandard if the picture contains
20406 text that uses downloaded bitmap fonts.  The binary action procedure is
20407 |do_edges_trans|, but we also need a function that just scales a picture.
20408 That routine is |scale_edges|.  Both it and the underlying routine |edges_trans|
20409 should be thought of as procedures that update an edge structure |h|, except
20410 that they have to return a (possibly new) structure because of the need to call
20411 |private_edges|.
20412
20413 @<Declare binary action...@>=
20414 pointer mp_edges_trans (MP mp, pointer h) {
20415   pointer q; /* the object being transformed */
20416   pointer r,s; /* for list manipulation */
20417   scaled sx,sy; /* saved transformation parameters */
20418   scaled sqdet; /* square root of determinant for |dash_scale| */
20419   integer sgndet; /* sign of the determinant */
20420   scaled v; /* a temporary value */
20421   h=mp_private_edges(mp, h);
20422   sqdet=mp_sqrt_det(mp, mp->txx,mp->txy,mp->tyx,mp->tyy);
20423   sgndet=mp_ab_vs_cd(mp, mp->txx,mp->tyy,mp->txy,mp->tyx);
20424   if ( dash_list(h)!=null_dash ) {
20425     @<Try to transform the dash list of |h|@>;
20426   }
20427   @<Make the bounding box of |h| unknown if it can't be updated properly
20428     without scanning the whole structure@>;  
20429   q=link(dummy_loc(h));
20430   while ( q!=null ) { 
20431     @<Transform graphical object |q|@>;
20432     q=link(q);
20433   }
20434   return h;
20435 }
20436 void mp_do_edges_trans (MP mp,pointer p, quarterword c) { 
20437   mp_set_up_known_trans(mp, c);
20438   value(p)=mp_edges_trans(mp, value(p));
20439   mp_unstash_cur_exp(mp, p);
20440 }
20441 void mp_scale_edges (MP mp) { 
20442   mp->txx=mp->se_sf; mp->tyy=mp->se_sf;
20443   mp->txy=0; mp->tyx=0; mp->tx=0; mp->ty=0;
20444   mp->se_pic=mp_edges_trans(mp, mp->se_pic);
20445 }
20446
20447 @ @<Try to transform the dash list of |h|@>=
20448 if ( (mp->txy!=0)||(mp->tyx!=0)||
20449      (mp->ty!=0)||(abs(mp->txx)!=abs(mp->tyy))) {
20450   mp_flush_dash_list(mp, h);
20451 } else { 
20452   if ( mp->txx<0 ) { @<Reverse the dash list of |h|@>; } 
20453   @<Scale the dash list by |txx| and shift it by |tx|@>;
20454   dash_y(h)=mp_take_scaled(mp, dash_y(h),abs(mp->tyy));
20455 }
20456
20457 @ @<Reverse the dash list of |h|@>=
20458
20459   r=dash_list(h);
20460   dash_list(h)=null_dash;
20461   while ( r!=null_dash ) {
20462     s=r; r=link(r);
20463     v=start_x(s); start_x(s)=stop_x(s); stop_x(s)=v;
20464     link(s)=dash_list(h);
20465     dash_list(h)=s;
20466   }
20467 }
20468
20469 @ @<Scale the dash list by |txx| and shift it by |tx|@>=
20470 r=dash_list(h);
20471 while ( r!=null_dash ) {
20472   start_x(r)=mp_take_scaled(mp, start_x(r),mp->txx)+mp->tx;
20473   stop_x(r)=mp_take_scaled(mp, stop_x(r),mp->txx)+mp->tx;
20474   r=link(r);
20475 }
20476
20477 @ @<Make the bounding box of |h| unknown if it can't be updated properly...@>=
20478 if ( (mp->txx==0)&&(mp->tyy==0) ) {
20479   @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>;
20480 } else if ( (mp->txy!=0)||(mp->tyx!=0) ) {
20481   mp_init_bbox(mp, h);
20482   goto DONE1;
20483 }
20484 if ( minx_val(h)<=maxx_val(h) ) {
20485   @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift by
20486    |(tx,ty)|@>;
20487 }
20488 DONE1:
20489
20490
20491
20492 @ @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>=
20493
20494   v=minx_val(h); minx_val(h)=miny_val(h); miny_val(h)=v;
20495   v=maxx_val(h); maxx_val(h)=maxy_val(h); maxy_val(h)=v;
20496 }
20497
20498 @ The sum ``|txx+txy|'' is whichever of |txx| or |txy| is nonzero.  The other
20499 sum is similar.
20500
20501 @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift...@>=
20502
20503   minx_val(h)=mp_take_scaled(mp, minx_val(h),mp->txx+mp->txy)+mp->tx;
20504   maxx_val(h)=mp_take_scaled(mp, maxx_val(h),mp->txx+mp->txy)+mp->tx;
20505   miny_val(h)=mp_take_scaled(mp, miny_val(h),mp->tyx+mp->tyy)+mp->ty;
20506   maxy_val(h)=mp_take_scaled(mp, maxy_val(h),mp->tyx+mp->tyy)+mp->ty;
20507   if ( mp->txx+mp->txy<0 ) {
20508     v=minx_val(h); minx_val(h)=maxx_val(h); maxx_val(h)=v;
20509   }
20510   if ( mp->tyx+mp->tyy<0 ) {
20511     v=miny_val(h); miny_val(h)=maxy_val(h); maxy_val(h)=v;
20512   }
20513 }
20514
20515 @ Now we ready for the main task of transforming the graphical objects in edge
20516 structure~|h|.
20517
20518 @<Transform graphical object |q|@>=
20519 switch (type(q)) {
20520 case fill_code: case stroked_code: 
20521   mp_do_path_trans(mp, path_p(q));
20522   @<Transform |pen_p(q)|, making sure polygonal pens stay counter-clockwise@>;
20523   break;
20524 case mp_start_clip_code: case mp_start_bounds_code: 
20525   mp_do_path_trans(mp, path_p(q));
20526   break;
20527 case text_code: 
20528   r=text_tx_loc(q);
20529   @<Transform the compact transformation starting at |r|@>;
20530   break;
20531 case mp_stop_clip_code: case mp_stop_bounds_code: 
20532   break;
20533 } /* there are no other cases */
20534
20535 @ Note that the shift parameters |(tx,ty)| apply only to the path being stroked.
20536 The |dash_scale| has to be adjusted  to scale the dash lengths in |dash_p(q)|
20537 since the \ps\ output procedures will try to compensate for the transformation
20538 we are applying to |pen_p(q)|.  Since this compensation is based on the square
20539 root of the determinant, |sqdet| is the appropriate factor.
20540
20541 @<Transform |pen_p(q)|, making sure...@>=
20542 if ( pen_p(q)!=null ) {
20543   sx=mp->tx; sy=mp->ty;
20544   mp->tx=0; mp->ty=0;
20545   mp_do_pen_trans(mp, pen_p(q));
20546   if ( ((type(q)==stroked_code)&&(dash_p(q)!=null)) )
20547     dash_scale(q)=mp_take_scaled(mp, dash_scale(q),sqdet);
20548   if ( ! pen_is_elliptical(pen_p(q)) )
20549     if ( sgndet<0 )
20550       pen_p(q)=mp_make_pen(mp, mp_copy_path(mp, pen_p(q)),true); 
20551          /* this unreverses the pen */
20552   mp->tx=sx; mp->ty=sy;
20553 }
20554
20555 @ This uses the fact that transformations are stored in the order
20556 |(tx,ty,txx,txy,tyx,tyy)|.
20557 @^data structure assumptions@>
20558
20559 @<Transform the compact transformation starting at |r|@>=
20560 mp_trans(mp, r,r+1);
20561 sx=mp->tx; sy=mp->ty;
20562 mp->tx=0; mp->ty=0;
20563 mp_trans(mp, r+2,r+4);
20564 mp_trans(mp, r+3,r+5);
20565 mp->tx=sx; mp->ty=sy
20566
20567 @ The hard cases of transformation occur when big nodes are involved,
20568 and when some of their components are unknown.
20569
20570 @<Declare binary action...@>=
20571 @<Declare subroutines needed by |big_trans|@>;
20572 void mp_big_trans (MP mp,pointer p, quarterword c) {
20573   pointer q,r,pp,qq; /* list manipulation registers */
20574   small_number s; /* size of a big node */
20575   s=mp->big_node_size[type(p)]; q=value(p); r=q+s;
20576   do {  
20577     r=r-2;
20578     if ( type(r)!=mp_known ) {
20579       @<Transform an unknown big node and |return|@>;
20580     }
20581   } while (r!=q);
20582   @<Transform a known big node@>;
20583 }; /* node |p| will now be recycled by |do_binary| */
20584
20585 @ @<Transform an unknown big node and |return|@>=
20586
20587   mp_set_up_known_trans(mp, c); mp_make_exp_copy(mp, p); 
20588   r=value(mp->cur_exp);
20589   if ( mp->cur_type==mp_transform_type ) {
20590     mp_bilin1(mp, yy_part_loc(r),mp->tyy,xy_part_loc(q),mp->tyx,0);
20591     mp_bilin1(mp, yx_part_loc(r),mp->tyy,xx_part_loc(q),mp->tyx,0);
20592     mp_bilin1(mp, xy_part_loc(r),mp->txx,yy_part_loc(q),mp->txy,0);
20593     mp_bilin1(mp, xx_part_loc(r),mp->txx,yx_part_loc(q),mp->txy,0);
20594   }
20595   mp_bilin1(mp, y_part_loc(r),mp->tyy,x_part_loc(q),mp->tyx,mp->ty);
20596   mp_bilin1(mp, x_part_loc(r),mp->txx,y_part_loc(q),mp->txy,mp->tx);
20597   return;
20598 }
20599
20600 @ Let |p| point to a two-word value field inside a big node of |cur_exp|,
20601 and let |q| point to a another value field. The |bilin1| procedure
20602 replaces |p| by $p\cdot t+q\cdot u+\delta$.
20603
20604 @<Declare subroutines needed by |big_trans|@>=
20605 void mp_bilin1 (MP mp, pointer p, scaled t, pointer q, 
20606                 scaled u, scaled delta) {
20607   pointer r; /* list traverser */
20608   if ( t!=unity ) mp_dep_mult(mp, p,t,true);
20609   if ( u!=0 ) {
20610     if ( type(q)==mp_known ) {
20611       delta+=mp_take_scaled(mp, value(q),u);
20612     } else { 
20613       @<Ensure that |type(p)=mp_proto_dependent|@>;
20614       dep_list(p)=mp_p_plus_fq(mp, dep_list(p),u,dep_list(q),
20615                                mp_proto_dependent,type(q));
20616     }
20617   }
20618   if ( type(p)==mp_known ) {
20619     value(p)+=delta;
20620   } else {
20621     r=dep_list(p);
20622     while ( info(r)!=null ) r=link(r);
20623     delta+=value(r);
20624     if ( r!=dep_list(p) ) value(r)=delta;
20625     else { mp_recycle_value(mp, p); type(p)=mp_known; value(p)=delta; };
20626   }
20627   if ( mp->fix_needed ) mp_fix_dependencies(mp);
20628 }
20629
20630 @ @<Ensure that |type(p)=mp_proto_dependent|@>=
20631 if ( type(p)!=mp_proto_dependent ) {
20632   if ( type(p)==mp_known ) 
20633     mp_new_dep(mp, p,mp_const_dependency(mp, value(p)));
20634   else 
20635     dep_list(p)=mp_p_times_v(mp, dep_list(p),unity,mp_dependent,
20636                              mp_proto_dependent,true);
20637   type(p)=mp_proto_dependent;
20638 }
20639
20640 @ @<Transform a known big node@>=
20641 mp_set_up_trans(mp, c);
20642 if ( mp->cur_type==mp_known ) {
20643   @<Transform known by known@>;
20644 } else { 
20645   pp=mp_stash_cur_exp(mp); qq=value(pp);
20646   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20647   if ( mp->cur_type==mp_transform_type ) {
20648     mp_bilin2(mp, yy_part_loc(r),yy_part_loc(qq),
20649       value(xy_part_loc(q)),yx_part_loc(qq),null);
20650     mp_bilin2(mp, yx_part_loc(r),yy_part_loc(qq),
20651       value(xx_part_loc(q)),yx_part_loc(qq),null);
20652     mp_bilin2(mp, xy_part_loc(r),xx_part_loc(qq),
20653       value(yy_part_loc(q)),xy_part_loc(qq),null);
20654     mp_bilin2(mp, xx_part_loc(r),xx_part_loc(qq),
20655       value(yx_part_loc(q)),xy_part_loc(qq),null);
20656   };
20657   mp_bilin2(mp, y_part_loc(r),yy_part_loc(qq),
20658     value(x_part_loc(q)),yx_part_loc(qq),y_part_loc(qq));
20659   mp_bilin2(mp, x_part_loc(r),xx_part_loc(qq),
20660     value(y_part_loc(q)),xy_part_loc(qq),x_part_loc(qq));
20661   mp_recycle_value(mp, pp); mp_free_node(mp, pp,value_node_size);
20662 }
20663
20664 @ Let |p| be a |mp_proto_dependent| value whose dependency list ends
20665 at |dep_final|. The following procedure adds |v| times another
20666 numeric quantity to~|p|.
20667
20668 @<Declare subroutines needed by |big_trans|@>=
20669 void mp_add_mult_dep (MP mp,pointer p, scaled v, pointer r) { 
20670   if ( type(r)==mp_known ) {
20671     value(mp->dep_final)+=mp_take_scaled(mp, value(r),v);
20672   } else  { 
20673     dep_list(p)=mp_p_plus_fq(mp, dep_list(p),v,dep_list(r),
20674                                                          mp_proto_dependent,type(r));
20675     if ( mp->fix_needed ) mp_fix_dependencies(mp);
20676   }
20677 }
20678
20679 @ The |bilin2| procedure is something like |bilin1|, but with known
20680 and unknown quantities reversed. Parameter |p| points to a value field
20681 within the big node for |cur_exp|; and |type(p)=mp_known|. Parameters
20682 |t| and~|u| point to value fields elsewhere; so does parameter~|q|,
20683 unless it is |null| (which stands for zero). Location~|p| will be
20684 replaced by $p\cdot t+v\cdot u+q$.
20685
20686 @<Declare subroutines needed by |big_trans|@>=
20687 void mp_bilin2 (MP mp,pointer p, pointer t, scaled v, 
20688                 pointer u, pointer q) {
20689   scaled vv; /* temporary storage for |value(p)| */
20690   vv=value(p); type(p)=mp_proto_dependent;
20691   mp_new_dep(mp, p,mp_const_dependency(mp, 0)); /* this sets |dep_final| */
20692   if ( vv!=0 ) 
20693     mp_add_mult_dep(mp, p,vv,t); /* |dep_final| doesn't change */
20694   if ( v!=0 ) mp_add_mult_dep(mp, p,v,u);
20695   if ( q!=null ) mp_add_mult_dep(mp, p,unity,q);
20696   if ( dep_list(p)==mp->dep_final ) {
20697     vv=value(mp->dep_final); mp_recycle_value(mp, p);
20698     type(p)=mp_known; value(p)=vv;
20699   }
20700 }
20701
20702 @ @<Transform known by known@>=
20703
20704   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20705   if ( mp->cur_type==mp_transform_type ) {
20706     mp_bilin3(mp, yy_part_loc(r),mp->tyy,value(xy_part_loc(q)),mp->tyx,0);
20707     mp_bilin3(mp, yx_part_loc(r),mp->tyy,value(xx_part_loc(q)),mp->tyx,0);
20708     mp_bilin3(mp, xy_part_loc(r),mp->txx,value(yy_part_loc(q)),mp->txy,0);
20709     mp_bilin3(mp, xx_part_loc(r),mp->txx,value(yx_part_loc(q)),mp->txy,0);
20710   }
20711   mp_bilin3(mp, y_part_loc(r),mp->tyy,value(x_part_loc(q)),mp->tyx,mp->ty);
20712   mp_bilin3(mp, x_part_loc(r),mp->txx,value(y_part_loc(q)),mp->txy,mp->tx);
20713 }
20714
20715 @ Finally, in |bilin3| everything is |known|.
20716
20717 @<Declare subroutines needed by |big_trans|@>=
20718 void mp_bilin3 (MP mp,pointer p, scaled t, 
20719                scaled v, scaled u, scaled delta) { 
20720   if ( t!=unity )
20721     delta+=mp_take_scaled(mp, value(p),t);
20722   else 
20723     delta+=value(p);
20724   if ( u!=0 ) value(p)=delta+mp_take_scaled(mp, v,u);
20725   else value(p)=delta;
20726 }
20727
20728 @ @<Additional cases of binary operators@>=
20729 case concatenate: 
20730   if ( (mp->cur_type==mp_string_type)&&(type(p)==mp_string_type) ) mp_cat(mp, p);
20731   else mp_bad_binary(mp, p,concatenate);
20732   break;
20733 case substring_of: 
20734   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_string_type) )
20735     mp_chop_string(mp, value(p));
20736   else mp_bad_binary(mp, p,substring_of);
20737   break;
20738 case subpath_of: 
20739   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
20740   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_path_type) )
20741     mp_chop_path(mp, value(p));
20742   else mp_bad_binary(mp, p,subpath_of);
20743   break;
20744
20745 @ @<Declare binary action...@>=
20746 void mp_cat (MP mp,pointer p) {
20747   str_number a,b; /* the strings being concatenated */
20748   pool_pointer k; /* index into |str_pool| */
20749   a=value(p); b=mp->cur_exp; str_room(length(a)+length(b));
20750   for (k=mp->str_start[a];k<=str_stop(a)-1;k++) {
20751     append_char(mp->str_pool[k]);
20752   }
20753   for (k=mp->str_start[b];k<=str_stop(b)-1;k++) {
20754     append_char(mp->str_pool[k]);
20755   }
20756   mp->cur_exp=mp_make_string(mp); delete_str_ref(b);
20757 }
20758
20759 @ @<Declare binary action...@>=
20760 void mp_chop_string (MP mp,pointer p) {
20761   integer a, b; /* start and stop points */
20762   integer l; /* length of the original string */
20763   integer k; /* runs from |a| to |b| */
20764   str_number s; /* the original string */
20765   boolean reversed; /* was |a>b|? */
20766   a=mp_round_unscaled(mp, value(x_part_loc(p)));
20767   b=mp_round_unscaled(mp, value(y_part_loc(p)));
20768   if ( a<=b ) reversed=false;
20769   else  { reversed=true; k=a; a=b; b=k; };
20770   s=mp->cur_exp; l=length(s);
20771   if ( a<0 ) { 
20772     a=0;
20773     if ( b<0 ) b=0;
20774   }
20775   if ( b>l ) { 
20776     b=l;
20777     if ( a>l ) a=l;
20778   }
20779   str_room(b-a);
20780   if ( reversed ) {
20781     for (k=mp->str_start[s]+b-1;k>=mp->str_start[s]+a;k--)  {
20782       append_char(mp->str_pool[k]);
20783     }
20784   } else  {
20785     for (k=mp->str_start[s]+a;k<=mp->str_start[s]+b-1;k++)  {
20786       append_char(mp->str_pool[k]);
20787     }
20788   }
20789   mp->cur_exp=mp_make_string(mp); delete_str_ref(s);
20790 }
20791
20792 @ @<Declare binary action...@>=
20793 void mp_chop_path (MP mp,pointer p) {
20794   pointer q; /* a knot in the original path */
20795   pointer pp,qq,rr,ss; /* link variables for copies of path nodes */
20796   scaled a,b,k,l; /* indices for chopping */
20797   boolean reversed; /* was |a>b|? */
20798   l=mp_path_length(mp); a=value(x_part_loc(p)); b=value(y_part_loc(p));
20799   if ( a<=b ) reversed=false;
20800   else  { reversed=true; k=a; a=b; b=k; };
20801   @<Dispense with the cases |a<0| and/or |b>l|@>;
20802   q=mp->cur_exp;
20803   while ( a>=unity ) {
20804     q=link(q); a=a-unity; b=b-unity;
20805   }
20806   if ( b==a ) {
20807     @<Construct a path from |pp| to |qq| of length zero@>; 
20808   } else { 
20809     @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>; 
20810   }
20811   left_type(pp)=endpoint; right_type(qq)=endpoint; link(qq)=pp;
20812   mp_toss_knot_list(mp, mp->cur_exp);
20813   if ( reversed ) {
20814     mp->cur_exp=link(mp_htap_ypoc(mp, pp)); mp_toss_knot_list(mp, pp);
20815   } else {
20816     mp->cur_exp=pp;
20817   }
20818 }
20819
20820 @ @<Dispense with the cases |a<0| and/or |b>l|@>=
20821 if ( a<0 ) {
20822   if ( left_type(mp->cur_exp)==endpoint ) {
20823     a=0; if ( b<0 ) b=0;
20824   } else  {
20825     do {  a=a+l; b=b+l; } while (a<0); /* a cycle always has length |l>0| */
20826   }
20827 }
20828 if ( b>l ) {
20829   if ( left_type(mp->cur_exp)==endpoint ) {
20830     b=l; if ( a>l ) a=l;
20831   } else {
20832     while ( a>=l ) { 
20833       a=a-l; b=b-l;
20834     }
20835   }
20836 }
20837
20838 @ @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>=
20839
20840   pp=mp_copy_knot(mp, q); qq=pp;
20841   do {  
20842     q=link(q); rr=qq; qq=mp_copy_knot(mp, q); link(rr)=qq; b=b-unity;
20843   } while (b>0);
20844   if ( a>0 ) {
20845     ss=pp; pp=link(pp);
20846     mp_split_cubic(mp, ss,a*010000); pp=link(ss);
20847     mp_free_node(mp, ss,knot_node_size);
20848     if ( rr==ss ) {
20849       b=mp_make_scaled(mp, b,unity-a); rr=pp;
20850     }
20851   }
20852   if ( b<0 ) {
20853     mp_split_cubic(mp, rr,(b+unity)*010000);
20854     mp_free_node(mp, qq,knot_node_size);
20855     qq=link(rr);
20856   }
20857 }
20858
20859 @ @<Construct a path from |pp| to |qq| of length zero@>=
20860
20861   if ( a>0 ) { mp_split_cubic(mp, q,a*010000); q=link(q); };
20862   pp=mp_copy_knot(mp, q); qq=pp;
20863 }
20864
20865 @ @<Additional cases of binary operators@>=
20866 case point_of: case precontrol_of: case postcontrol_of: 
20867   if ( mp->cur_type==mp_pair_type )
20868      mp_pair_to_path(mp);
20869   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
20870     mp_find_point(mp, value(p),c);
20871   else 
20872     mp_bad_binary(mp, p,c);
20873   break;
20874 case pen_offset_of: 
20875   if ( (mp->cur_type==mp_pen_type)&& mp_nice_pair(mp, p,type(p)) )
20876     mp_set_up_offset(mp, value(p));
20877   else 
20878     mp_bad_binary(mp, p,pen_offset_of);
20879   break;
20880 case direction_time_of: 
20881   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
20882   if ( (mp->cur_type==mp_path_type)&& mp_nice_pair(mp, p,type(p)) )
20883     mp_set_up_direction_time(mp, value(p));
20884   else 
20885     mp_bad_binary(mp, p,direction_time_of);
20886   break;
20887
20888 @ @<Declare binary action...@>=
20889 void mp_set_up_offset (MP mp,pointer p) { 
20890   mp_find_offset(mp, value(x_part_loc(p)),value(y_part_loc(p)),mp->cur_exp);
20891   mp_pair_value(mp, mp->cur_x,mp->cur_y);
20892 }
20893 void mp_set_up_direction_time (MP mp,pointer p) { 
20894   mp_flush_cur_exp(mp, mp_find_direction_time(mp, value(x_part_loc(p)),
20895   value(y_part_loc(p)),mp->cur_exp));
20896 }
20897
20898 @ @<Declare binary action...@>=
20899 void mp_find_point (MP mp,scaled v, quarterword c) {
20900   pointer p; /* the path */
20901   scaled n; /* its length */
20902   p=mp->cur_exp;
20903   if ( left_type(p)==endpoint ) n=-unity; else n=0;
20904   do {  p=link(p); n=n+unity; } while (p!=mp->cur_exp);
20905   if ( n==0 ) { 
20906     v=0; 
20907   } else if ( v<0 ) {
20908     if ( left_type(p)==endpoint ) v=0;
20909     else v=n-1-((-v-1) % n);
20910   } else if ( v>n ) {
20911     if ( left_type(p)==endpoint ) v=n;
20912     else v=v % n;
20913   }
20914   p=mp->cur_exp;
20915   while ( v>=unity ) { p=link(p); v=v-unity;  };
20916   if ( v!=0 ) {
20917      @<Insert a fractional node by splitting the cubic@>;
20918   }
20919   @<Set the current expression to the desired path coordinates@>;
20920 }
20921
20922 @ @<Insert a fractional node...@>=
20923 { mp_split_cubic(mp, p,v*010000); p=link(p); }
20924
20925 @ @<Set the current expression to the desired path coordinates...@>=
20926 switch (c) {
20927 case point_of: 
20928   mp_pair_value(mp, x_coord(p),y_coord(p));
20929   break;
20930 case precontrol_of: 
20931   if ( left_type(p)==endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
20932   else mp_pair_value(mp, left_x(p),left_y(p));
20933   break;
20934 case postcontrol_of: 
20935   if ( right_type(p)==endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
20936   else mp_pair_value(mp, right_x(p),right_y(p));
20937   break;
20938 } /* there are no other cases */
20939
20940 @ @<Additional cases of binary operators@>=
20941 case arc_time_of: 
20942   if ( mp->cur_type==mp_pair_type )
20943      mp_pair_to_path(mp);
20944   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
20945     mp_flush_cur_exp(mp, mp_get_arc_time(mp, mp->cur_exp,value(p)));
20946   else 
20947     mp_bad_binary(mp, p,c);
20948   break;
20949
20950 @ @<Additional cases of bin...@>=
20951 case intersect: 
20952   if ( type(p)==mp_pair_type ) {
20953     q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p);
20954     mp_pair_to_path(mp); p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
20955   };
20956   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
20957   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_path_type) ) {
20958     mp_path_intersection(mp, value(p),mp->cur_exp);
20959     mp_pair_value(mp, mp->cur_t,mp->cur_tt);
20960   } else {
20961     mp_bad_binary(mp, p,intersect);
20962   }
20963   break;
20964
20965 @ @<Additional cases of bin...@>=
20966 case in_font:
20967   if ( (mp->cur_type!=mp_string_type)||(type(p)!=mp_string_type)) 
20968     mp_bad_binary(mp, p,in_font);
20969   else { mp_do_infont(mp, p); return; }
20970   break;
20971
20972 @ Function |new_text_node| owns the reference count for its second argument
20973 (the text string) but not its first (the font name).
20974
20975 @<Declare binary action...@>=
20976 void mp_do_infont (MP mp,pointer p) {
20977   pointer q;
20978   q=mp_get_node(mp, edge_header_size);
20979   mp_init_edges(mp, q);
20980   link(obj_tail(q))=mp_new_text_node(mp, str(mp->cur_exp),value(p));
20981   obj_tail(q)=link(obj_tail(q));
20982   mp_free_node(mp, p,value_node_size);
20983   mp_flush_cur_exp(mp, q);
20984   mp->cur_type=mp_picture_type;
20985 }
20986
20987 @* \[40] Statements and commands.
20988 The chief executive of \MP\ is the |do_statement| routine, which
20989 contains the master switch that causes all the various pieces of \MP\
20990 to do their things, in the right order.
20991
20992 In a sense, this is the grand climax of the program: It applies all the
20993 tools that we have worked so hard to construct. In another sense, this is
20994 the messiest part of the program: It necessarily refers to other pieces
20995 of code all over the place, so that a person can't fully understand what is
20996 going on without paging back and forth to be reminded of conventions that
20997 are defined elsewhere. We are now at the hub of the web.
20998
20999 The structure of |do_statement| itself is quite simple.  The first token
21000 of the statement is fetched using |get_x_next|.  If it can be the first
21001 token of an expression, we look for an equation, an assignment, or a
21002 title. Otherwise we use a \&{case} construction to branch at high speed to
21003 the appropriate routine for various and sundry other types of commands,
21004 each of which has an ``action procedure'' that does the necessary work.
21005
21006 The program uses the fact that
21007 $$\hbox{|min_primary_command=max_statement_command=type_name|}$$
21008 to interpret a statement that starts with, e.g., `\&{string}',
21009 as a type declaration rather than a boolean expression.
21010
21011 @c void mp_do_statement (MP mp) { /* governs \MP's activities */
21012   mp->cur_type=mp_vacuous; mp_get_x_next(mp);
21013   if ( mp->cur_cmd>max_primary_command ) {
21014     @<Worry about bad statement@>;
21015   } else if ( mp->cur_cmd>max_statement_command ) {
21016     @<Do an equation, assignment, title, or
21017      `$\langle\,$expression$\,\rangle\,$\&{endgroup}'@>;
21018   } else {
21019     @<Do a statement that doesn't begin with an expression@>;
21020   }
21021   if ( mp->cur_cmd<semicolon )
21022     @<Flush unparsable junk that was found after the statement@>;
21023   mp->error_count=0;
21024 }
21025
21026 @ @<Declarations@>=
21027 @<Declare action procedures for use by |do_statement|@>;
21028
21029 @ The only command codes |>max_primary_command| that can be present
21030 at the beginning of a statement are |semicolon| and higher; these
21031 occur when the statement is null.
21032
21033 @<Worry about bad statement@>=
21034
21035   if ( mp->cur_cmd<semicolon ) {
21036     print_err("A statement can't begin with `");
21037 @.A statement can't begin with x@>
21038     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); mp_print_char(mp, '\'');
21039     help5("I was looking for the beginning of a new statement.")
21040       ("If you just proceed without changing anything, I'll ignore")
21041       ("everything up to the next `;'. Please insert a semicolon")
21042       ("now in front of anything that you don't want me to delete.")
21043       ("(See Chapter 27 of The METAFONTbook for an example.)");
21044 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21045     mp_back_error(mp); mp_get_x_next(mp);
21046   }
21047 }
21048
21049 @ The help message printed here says that everything is flushed up to
21050 a semicolon, but actually the commands |end_group| and |stop| will
21051 also terminate a statement.
21052
21053 @<Flush unparsable junk that was found after the statement@>=
21054
21055   print_err("Extra tokens will be flushed");
21056 @.Extra tokens will be flushed@>
21057   help6("I've just read as much of that statement as I could fathom,")
21058        ("so a semicolon should have been next. It's very puzzling...")
21059        ("but I'll try to get myself back together, by ignoring")
21060        ("everything up to the next `;'. Please insert a semicolon")
21061        ("now in front of anything that you don't want me to delete.")
21062        ("(See Chapter 27 of The METAFONTbook for an example.)");
21063 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21064   mp_back_error(mp); mp->scanner_status=flushing;
21065   do {  
21066     get_t_next;
21067     @<Decrease the string reference count...@>;
21068   } while (! end_of_statement); /* |cur_cmd=semicolon|, |end_group|, or |stop| */
21069   mp->scanner_status=normal;
21070 }
21071
21072 @ If |do_statement| ends with |cur_cmd=end_group|, we should have
21073 |cur_type=mp_vacuous| unless the statement was simply an expression;
21074 in the latter case, |cur_type| and |cur_exp| should represent that
21075 expression.
21076
21077 @<Do a statement that doesn't...@>=
21078
21079   if ( mp->internal[tracing_commands]>0 ) 
21080     show_cur_cmd_mod;
21081   switch (mp->cur_cmd ) {
21082   case type_name:mp_do_type_declaration(mp); break;
21083   case macro_def:
21084     if ( mp->cur_mod>var_def ) mp_make_op_def(mp);
21085     else if ( mp->cur_mod>end_def ) mp_scan_def(mp);
21086      break;
21087   @<Cases of |do_statement| that invoke particular commands@>;
21088   } /* there are no other cases */
21089   mp->cur_type=mp_vacuous;
21090 }
21091
21092 @ The most important statements begin with expressions.
21093
21094 @<Do an equation, assignment, title, or...@>=
21095
21096   mp->var_flag=assignment; mp_scan_expression(mp);
21097   if ( mp->cur_cmd<end_group ) {
21098     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21099     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21100     else if ( mp->cur_type==mp_string_type ) {@<Do a title@> ; }
21101     else if ( mp->cur_type!=mp_vacuous ){ 
21102       exp_err("Isolated expression");
21103 @.Isolated expression@>
21104       help3("I couldn't find an `=' or `:=' after the")
21105         ("expression that is shown above this error message,")
21106         ("so I guess I'll just ignore it and carry on.");
21107       mp_put_get_error(mp);
21108     }
21109     mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous;
21110   }
21111 }
21112
21113 @ @<Do a title@>=
21114
21115   if ( mp->internal[tracing_titles]>0 ) {
21116     mp_print_nl(mp, "");  mp_print_str(mp, mp->cur_exp); update_terminal;
21117   }
21118 }
21119
21120 @ Equations and assignments are performed by the pair of mutually recursive
21121 @^recursion@>
21122 routines |do_equation| and |do_assignment|. These routines are called when
21123 |cur_cmd=equals| and when |cur_cmd=assignment|, respectively; the left-hand
21124 side is in |cur_type| and |cur_exp|, while the right-hand side is yet
21125 to be scanned. After the routines are finished, |cur_type| and |cur_exp|
21126 will be equal to the right-hand side (which will normally be equal
21127 to the left-hand side).
21128
21129 @<Declare action procedures for use by |do_statement|@>=
21130 @<Declare the procedure called |try_eq|@>;
21131 @<Declare the procedure called |make_eq|@>;
21132 void mp_do_equation (MP mp) ;
21133
21134 @ @c
21135 void mp_do_equation (MP mp) {
21136   pointer lhs; /* capsule for the left-hand side */
21137   pointer p; /* temporary register */
21138   lhs=mp_stash_cur_exp(mp); mp_get_x_next(mp); 
21139   mp->var_flag=assignment; mp_scan_expression(mp);
21140   if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21141   else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21142   if ( mp->internal[tracing_commands]>two ) 
21143     @<Trace the current equation@>;
21144   if ( mp->cur_type==mp_unknown_path ) if ( type(lhs)==mp_pair_type ) {
21145     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, lhs); lhs=p;
21146   }; /* in this case |make_eq| will change the pair to a path */
21147   mp_make_eq(mp, lhs); /* equate |lhs| to |(cur_type,cur_exp)| */
21148 }
21149
21150 @ And |do_assignment| is similar to |do_expression|:
21151
21152 @<Declarations@>=
21153 void mp_do_assignment (MP mp);
21154
21155 @ @<Declare action procedures for use by |do_statement|@>=
21156 void mp_do_assignment (MP mp) ;
21157
21158 @ @c
21159 void mp_do_assignment (MP mp) {
21160   pointer lhs; /* token list for the left-hand side */
21161   pointer p; /* where the left-hand value is stored */
21162   pointer q; /* temporary capsule for the right-hand value */
21163   if ( mp->cur_type!=mp_token_list ) { 
21164     exp_err("Improper `:=' will be changed to `='");
21165 @.Improper `:='@>
21166     help2("I didn't find a variable name at the left of the `:=',")
21167       ("so I'm going to pretend that you said `=' instead.");
21168     mp_error(mp); mp_do_equation(mp);
21169   } else { 
21170     lhs=mp->cur_exp; mp->cur_type=mp_vacuous;
21171     mp_get_x_next(mp); mp->var_flag=assignment; mp_scan_expression(mp);
21172     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21173     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21174     if ( mp->internal[tracing_commands]>two ) 
21175       @<Trace the current assignment@>;
21176     if ( info(lhs)>hash_end ) {
21177       @<Assign the current expression to an internal variable@>;
21178     } else  {
21179       @<Assign the current expression to the variable |lhs|@>;
21180     }
21181     mp_flush_node_list(mp, lhs);
21182   }
21183 }
21184
21185 @ @<Trace the current equation@>=
21186
21187   mp_begin_diagnostic(mp); mp_print_nl(mp, "{("); mp_print_exp(mp,lhs,0);
21188   mp_print(mp,")=("); mp_print_exp(mp,null,0); 
21189   mp_print(mp,")}"); mp_end_diagnostic(mp, false);
21190 }
21191
21192 @ @<Trace the current assignment@>=
21193
21194   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
21195   if ( info(lhs)>hash_end ) 
21196      mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21197   else 
21198      mp_show_token_list(mp, lhs,null,1000,0);
21199   mp_print(mp, ":="); mp_print_exp(mp, null,0); 
21200   mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
21201 }
21202
21203 @ @<Assign the current expression to an internal variable@>=
21204 if ( mp->cur_type==mp_known )  {
21205   mp->internal[info(lhs)-(hash_end)]=mp->cur_exp;
21206 } else { 
21207   exp_err("Internal quantity `");
21208 @.Internal quantity...@>
21209   mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21210   mp_print(mp, "' must receive a known value");
21211   help2("I can\'t set an internal quantity to anything but a known")
21212     ("numeric value, so I'll have to ignore this assignment.");
21213   mp_put_get_error(mp);
21214 }
21215
21216 @ @<Assign the current expression to the variable |lhs|@>=
21217
21218   p=mp_find_variable(mp, lhs);
21219   if ( p!=null ) {
21220     q=mp_stash_cur_exp(mp); mp->cur_type=mp_und_type(mp, p); 
21221     mp_recycle_value(mp, p);
21222     type(p)=mp->cur_type; value(p)=null; mp_make_exp_copy(mp, p);
21223     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q); mp_make_eq(mp, p);
21224   } else  { 
21225     mp_obliterated(mp, lhs); mp_put_get_error(mp);
21226   }
21227 }
21228
21229
21230 @ And now we get to the nitty-gritty. The |make_eq| procedure is given
21231 a pointer to a capsule that is to be equated to the current expression.
21232
21233 @<Declare the procedure called |make_eq|@>=
21234 void mp_make_eq (MP mp,pointer lhs) ;
21235
21236
21237
21238 @c void mp_make_eq (MP mp,pointer lhs) {
21239   small_number t; /* type of the left-hand side */
21240   pointer p,q; /* pointers inside of big nodes */
21241   integer v=0; /* value of the left-hand side */
21242 RESTART: 
21243   t=type(lhs);
21244   if ( t<=mp_pair_type ) v=value(lhs);
21245   switch (t) {
21246   @<For each type |t|, make an equation and |goto done| unless |cur_type|
21247     is incompatible with~|t|@>;
21248   } /* all cases have been listed */
21249   @<Announce that the equation cannot be performed@>;
21250 DONE:
21251   check_arith; mp_recycle_value(mp, lhs); 
21252   mp_free_node(mp, lhs,value_node_size);
21253 }
21254
21255 @ @<Announce that the equation cannot be performed@>=
21256 mp_disp_err(mp, lhs,""); 
21257 exp_err("Equation cannot be performed (");
21258 @.Equation cannot be performed@>
21259 if ( type(lhs)<=mp_pair_type ) mp_print_type(mp, type(lhs));
21260 else mp_print(mp, "numeric");
21261 mp_print_char(mp, '=');
21262 if ( mp->cur_type<=mp_pair_type ) mp_print_type(mp, mp->cur_type);
21263 else mp_print(mp, "numeric");
21264 mp_print_char(mp, ')');
21265 help2("I'm sorry, but I don't know how to make such things equal.")
21266      ("(See the two expressions just above the error message.)");
21267 mp_put_get_error(mp)
21268
21269 @ @<For each type |t|, make an equation and |goto done| unless...@>=
21270 case mp_boolean_type: case mp_string_type: case mp_pen_type:
21271 case mp_path_type: case mp_picture_type:
21272   if ( mp->cur_type==t+unknown_tag ) { 
21273     mp_nonlinear_eq(mp, v,mp->cur_exp,false); goto DONE;
21274   } else if ( mp->cur_type==t ) {
21275     @<Report redundant or inconsistent equation and |goto done|@>;
21276   }
21277   break;
21278 case unknown_types:
21279   if ( mp->cur_type==t-unknown_tag ) { 
21280     mp_nonlinear_eq(mp, mp->cur_exp,lhs,true); goto DONE;
21281   } else if ( mp->cur_type==t ) { 
21282     mp_ring_merge(mp, lhs,mp->cur_exp); goto DONE;
21283   } else if ( mp->cur_type==mp_pair_type ) {
21284     if ( t==mp_unknown_path ) { 
21285      mp_pair_to_path(mp); goto RESTART;
21286     };
21287   }
21288   break;
21289 case mp_transform_type: case mp_color_type:
21290 case mp_cmykcolor_type: case mp_pair_type:
21291   if ( mp->cur_type==t ) {
21292     @<Do multiple equations and |goto done|@>;
21293   }
21294   break;
21295 case mp_known: case mp_dependent:
21296 case mp_proto_dependent: case mp_independent:
21297   if ( mp->cur_type>=mp_known ) { 
21298     mp_try_eq(mp, lhs,null); goto DONE;
21299   };
21300   break;
21301 case mp_vacuous:
21302   break;
21303
21304 @ @<Report redundant or inconsistent equation and |goto done|@>=
21305
21306   if ( mp->cur_type<=mp_string_type ) {
21307     if ( mp->cur_type==mp_string_type ) {
21308       if ( mp_str_vs_str(mp, v,mp->cur_exp)!=0 ) {
21309         goto NOT_FOUND;
21310       }
21311     } else if ( v!=mp->cur_exp ) {
21312       goto NOT_FOUND;
21313     }
21314     @<Exclaim about a redundant equation@>; goto DONE;
21315   }
21316   print_err("Redundant or inconsistent equation");
21317 @.Redundant or inconsistent equation@>
21318   help2("An equation between already-known quantities can't help.")
21319        ("But don't worry; continue and I'll just ignore it.");
21320   mp_put_get_error(mp); goto DONE;
21321 NOT_FOUND: 
21322   print_err("Inconsistent equation");
21323 @.Inconsistent equation@>
21324   help2("The equation I just read contradicts what was said before.")
21325        ("But don't worry; continue and I'll just ignore it.");
21326   mp_put_get_error(mp); goto DONE;
21327 }
21328
21329 @ @<Do multiple equations and |goto done|@>=
21330
21331   p=v+mp->big_node_size[t]; 
21332   q=value(mp->cur_exp)+mp->big_node_size[t];
21333   do {  
21334     p=p-2; q=q-2; mp_try_eq(mp, p,q);
21335   } while (p!=v);
21336   goto DONE;
21337 }
21338
21339 @ The first argument to |try_eq| is the location of a value node
21340 in a capsule that will soon be recycled. The second argument is
21341 either a location within a pair or transform node pointed to by
21342 |cur_exp|, or it is |null| (which means that |cur_exp| itself
21343 serves as the second argument). The idea is to leave |cur_exp| unchanged,
21344 but to equate the two operands.
21345
21346 @<Declare the procedure called |try_eq|@>=
21347 void mp_try_eq (MP mp,pointer l, pointer r) ;
21348
21349
21350 @c void mp_try_eq (MP mp,pointer l, pointer r) {
21351   pointer p; /* dependency list for right operand minus left operand */
21352   int t; /* the type of list |p| */
21353   pointer q; /* the constant term of |p| is here */
21354   pointer pp; /* dependency list for right operand */
21355   int tt; /* the type of list |pp| */
21356   boolean copied; /* have we copied a list that ought to be recycled? */
21357   @<Remove the left operand from its container, negate it, and
21358     put it into dependency list~|p| with constant term~|q|@>;
21359   @<Add the right operand to list |p|@>;
21360   if ( info(p)==null ) {
21361     @<Deal with redundant or inconsistent equation@>;
21362   } else { 
21363     mp_linear_eq(mp, p,t);
21364     if ( r==null ) if ( mp->cur_type!=mp_known ) {
21365       if ( type(mp->cur_exp)==mp_known ) {
21366         pp=mp->cur_exp; mp->cur_exp=value(mp->cur_exp); mp->cur_type=mp_known;
21367         mp_free_node(mp, pp,value_node_size);
21368       }
21369     }
21370   }
21371 }
21372
21373 @ @<Remove the left operand from its container, negate it, and...@>=
21374 t=type(l);
21375 if ( t==mp_known ) { 
21376   t=mp_dependent; p=mp_const_dependency(mp, -value(l)); q=p;
21377 } else if ( t==mp_independent ) {
21378   t=mp_dependent; p=mp_single_dependency(mp, l); negate(value(p));
21379   q=mp->dep_final;
21380 } else { 
21381   p=dep_list(l); q=p;
21382   while (1) { 
21383     negate(value(q));
21384     if ( info(q)==null ) break;
21385     q=link(q);
21386   }
21387   link(prev_dep(l))=link(q); prev_dep(link(q))=prev_dep(l);
21388   type(l)=mp_known;
21389 }
21390
21391 @ @<Deal with redundant or inconsistent equation@>=
21392
21393   if ( abs(value(p))>64 ) { /* off by .001 or more */
21394     print_err("Inconsistent equation");
21395 @.Inconsistent equation@>
21396     mp_print(mp, " (off by "); mp_print_scaled(mp, value(p)); 
21397     mp_print_char(mp, ')');
21398     help2("The equation I just read contradicts what was said before.")
21399       ("But don't worry; continue and I'll just ignore it.");
21400     mp_put_get_error(mp);
21401   } else if ( r==null ) {
21402     @<Exclaim about a redundant equation@>;
21403   }
21404   mp_free_node(mp, p,dep_node_size);
21405 }
21406
21407 @ @<Add the right operand to list |p|@>=
21408 if ( r==null ) {
21409   if ( mp->cur_type==mp_known ) {
21410     value(q)=value(q)+mp->cur_exp; goto DONE1;
21411   } else { 
21412     tt=mp->cur_type;
21413     if ( tt==mp_independent ) pp=mp_single_dependency(mp, mp->cur_exp);
21414     else pp=dep_list(mp->cur_exp);
21415   } 
21416 } else {
21417   if ( type(r)==mp_known ) {
21418     value(q)=value(q)+value(r); goto DONE1;
21419   } else { 
21420     tt=type(r);
21421     if ( tt==mp_independent ) pp=mp_single_dependency(mp, r);
21422     else pp=dep_list(r);
21423   }
21424 }
21425 if ( tt!=mp_independent ) copied=false;
21426 else  { copied=true; tt=mp_dependent; };
21427 @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>;
21428 if ( copied ) mp_flush_node_list(mp, pp);
21429 DONE1:
21430
21431 @ @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>=
21432 mp->watch_coefs=false;
21433 if ( t==tt ) {
21434   p=mp_p_plus_q(mp, p,pp,t);
21435 } else if ( t==mp_proto_dependent ) {
21436   p=mp_p_plus_fq(mp, p,unity,pp,mp_proto_dependent,mp_dependent);
21437 } else { 
21438   q=p;
21439   while ( info(q)!=null ) {
21440     value(q)=mp_round_fraction(mp, value(q)); q=link(q);
21441   }
21442   t=mp_proto_dependent; p=mp_p_plus_q(mp, p,pp,t);
21443 }
21444 mp->watch_coefs=true;
21445
21446 @ Our next goal is to process type declarations. For this purpose it's
21447 convenient to have a procedure that scans a $\langle\,$declared
21448 variable$\,\rangle$ and returns the corresponding token list. After the
21449 following procedure has acted, the token after the declared variable
21450 will have been scanned, so it will appear in |cur_cmd|, |cur_mod|,
21451 and~|cur_sym|.
21452
21453 @<Declare the function called |scan_declared_variable|@>=
21454 pointer mp_scan_declared_variable (MP mp) {
21455   pointer x; /* hash address of the variable's root */
21456   pointer h,t; /* head and tail of the token list to be returned */
21457   pointer l; /* hash address of left bracket */
21458   mp_get_symbol(mp); x=mp->cur_sym;
21459   if ( mp->cur_cmd!=tag_token ) mp_clear_symbol(mp, x,false);
21460   h=mp_get_avail(mp); info(h)=x; t=h;
21461   while (1) { 
21462     mp_get_x_next(mp);
21463     if ( mp->cur_sym==0 ) break;
21464     if ( mp->cur_cmd!=tag_token ) if ( mp->cur_cmd!=internal_quantity)  {
21465       if ( mp->cur_cmd==left_bracket ) {
21466         @<Descend past a collective subscript@>;
21467       } else {
21468         break;
21469       }
21470     }
21471     link(t)=mp_get_avail(mp); t=link(t); info(t)=mp->cur_sym;
21472   }
21473   if ( eq_type(x)!=tag_token ) mp_clear_symbol(mp, x,false);
21474   if ( equiv(x)==null ) mp_new_root(mp, x);
21475   return h;
21476 }
21477
21478 @ If the subscript isn't collective, we don't accept it as part of the
21479 declared variable.
21480
21481 @<Descend past a collective subscript@>=
21482
21483   l=mp->cur_sym; mp_get_x_next(mp);
21484   if ( mp->cur_cmd!=right_bracket ) {
21485     mp_back_input(mp); mp->cur_sym=l; mp->cur_cmd=left_bracket; break;
21486   } else {
21487     mp->cur_sym=collective_subscript;
21488   }
21489 }
21490
21491 @ Type declarations are introduced by the following primitive operations.
21492
21493 @<Put each...@>=
21494 mp_primitive(mp, "numeric",type_name,mp_numeric_type);
21495 @:numeric_}{\&{numeric} primitive@>
21496 mp_primitive(mp, "string",type_name,mp_string_type);
21497 @:string_}{\&{string} primitive@>
21498 mp_primitive(mp, "boolean",type_name,mp_boolean_type);
21499 @:boolean_}{\&{boolean} primitive@>
21500 mp_primitive(mp, "path",type_name,mp_path_type);
21501 @:path_}{\&{path} primitive@>
21502 mp_primitive(mp, "pen",type_name,mp_pen_type);
21503 @:pen_}{\&{pen} primitive@>
21504 mp_primitive(mp, "picture",type_name,mp_picture_type);
21505 @:picture_}{\&{picture} primitive@>
21506 mp_primitive(mp, "transform",type_name,mp_transform_type);
21507 @:transform_}{\&{transform} primitive@>
21508 mp_primitive(mp, "color",type_name,mp_color_type);
21509 @:color_}{\&{color} primitive@>
21510 mp_primitive(mp, "rgbcolor",type_name,mp_color_type);
21511 @:color_}{\&{rgbcolor} primitive@>
21512 mp_primitive(mp, "cmykcolor",type_name,mp_cmykcolor_type);
21513 @:color_}{\&{cmykcolor} primitive@>
21514 mp_primitive(mp, "pair",type_name,mp_pair_type);
21515 @:pair_}{\&{pair} primitive@>
21516
21517 @ @<Cases of |print_cmd...@>=
21518 case type_name: mp_print_type(mp, m); break;
21519
21520 @ Now we are ready to handle type declarations, assuming that a
21521 |type_name| has just been scanned.
21522
21523 @<Declare action procedures for use by |do_statement|@>=
21524 void mp_do_type_declaration (MP mp) ;
21525
21526 @ @c
21527 void mp_do_type_declaration (MP mp) {
21528   small_number t; /* the type being declared */
21529   pointer p; /* token list for a declared variable */
21530   pointer q; /* value node for the variable */
21531   if ( mp->cur_mod>=mp_transform_type ) 
21532     t=mp->cur_mod;
21533   else 
21534     t=mp->cur_mod+unknown_tag;
21535   do {  
21536     p=mp_scan_declared_variable(mp);
21537     mp_flush_variable(mp, equiv(info(p)),link(p),false);
21538     q=mp_find_variable(mp, p);
21539     if ( q!=null ) { 
21540       type(q)=t; value(q)=null; 
21541     } else  { 
21542       print_err("Declared variable conflicts with previous vardef");
21543 @.Declared variable conflicts...@>
21544       help2("You can't use, e.g., `numeric foo[]' after `vardef foo'.")
21545            ("Proceed, and I'll ignore the illegal redeclaration.");
21546       mp_put_get_error(mp);
21547     }
21548     mp_flush_list(mp, p);
21549     if ( mp->cur_cmd<comma ) {
21550       @<Flush spurious symbols after the declared variable@>;
21551     }
21552   } while (! end_of_statement);
21553 }
21554
21555 @ @<Flush spurious symbols after the declared variable@>=
21556
21557   print_err("Illegal suffix of declared variable will be flushed");
21558 @.Illegal suffix...flushed@>
21559   help5("Variables in declarations must consist entirely of")
21560     ("names and collective subscripts, e.g., `x[]a'.")
21561     ("Are you trying to use a reserved word in a variable name?")
21562     ("I'm going to discard the junk I found here,")
21563     ("up to the next comma or the end of the declaration.");
21564   if ( mp->cur_cmd==numeric_token )
21565     mp->help_line[2]="Explicit subscripts like `x15a' aren't permitted.";
21566   mp_put_get_error(mp); mp->scanner_status=flushing;
21567   do {  
21568     get_t_next;
21569     @<Decrease the string reference count...@>;
21570   } while (mp->cur_cmd<comma); /* either |end_of_statement| or |cur_cmd=comma| */
21571   mp->scanner_status=normal;
21572 }
21573
21574 @ \MP's |main_control| procedure just calls |do_statement| repeatedly
21575 until coming to the end of the user's program.
21576 Each execution of |do_statement| concludes with
21577 |cur_cmd=semicolon|, |end_group|, or |stop|.
21578
21579 @c void mp_main_control (MP mp) { 
21580   do {  
21581     mp_do_statement(mp);
21582     if ( mp->cur_cmd==end_group ) {
21583       print_err("Extra `endgroup'");
21584 @.Extra `endgroup'@>
21585       help2("I'm not currently working on a `begingroup',")
21586         ("so I had better not try to end anything.");
21587       mp_flush_error(mp, 0);
21588     }
21589   } while (mp->cur_cmd!=stop);
21590 }
21591 int mp_run (MP mp) {
21592   mp_main_control(mp); /* come to life */
21593   mp_final_cleanup(mp); /* prepare for death */
21594   mp_close_files_and_terminate(mp);
21595   return mp->history;
21596 }
21597 char * mp_mplib_version (MP mp) {
21598   assert(mp);
21599   return mplib_version;
21600 }
21601 char * mp_metapost_version (MP mp) {
21602   assert(mp);
21603   return metapost_version;
21604 }
21605
21606 @ @<Exported function headers@>=
21607 int mp_run (MP mp);
21608 char * mp_mplib_version (MP mp);
21609 char * mp_metapost_version (MP mp);
21610
21611 @ @<Put each...@>=
21612 mp_primitive(mp, "end",stop,0);
21613 @:end_}{\&{end} primitive@>
21614 mp_primitive(mp, "dump",stop,1);
21615 @:dump_}{\&{dump} primitive@>
21616
21617 @ @<Cases of |print_cmd...@>=
21618 case stop:
21619   if ( m==0 ) mp_print(mp, "end");
21620   else mp_print(mp, "dump");
21621   break;
21622
21623 @* \[41] Commands.
21624 Let's turn now to statements that are classified as ``commands'' because
21625 of their imperative nature. We'll begin with simple ones, so that it
21626 will be clear how to hook command processing into the |do_statement| routine;
21627 then we'll tackle the tougher commands.
21628
21629 Here's one of the simplest:
21630
21631 @<Cases of |do_statement|...@>=
21632 case random_seed: mp_do_random_seed(mp);  break;
21633
21634 @ @<Declare action procedures for use by |do_statement|@>=
21635 void mp_do_random_seed (MP mp) ;
21636
21637 @ @c void mp_do_random_seed (MP mp) { 
21638   mp_get_x_next(mp);
21639   if ( mp->cur_cmd!=assignment ) {
21640     mp_missing_err(mp, ":=");
21641 @.Missing `:='@>
21642     help1("Always say `randomseed:=<numeric expression>'.");
21643     mp_back_error(mp);
21644   };
21645   mp_get_x_next(mp); mp_scan_expression(mp);
21646   if ( mp->cur_type!=mp_known ) {
21647     exp_err("Unknown value will be ignored");
21648 @.Unknown value...ignored@>
21649     help2("Your expression was too random for me to handle,")
21650       ("so I won't change the random seed just now.");
21651     mp_put_get_flush_error(mp, 0);
21652   } else {
21653    @<Initialize the random seed to |cur_exp|@>;
21654   }
21655 }
21656
21657 @ @<Initialize the random seed to |cur_exp|@>=
21658
21659   mp_init_randoms(mp, mp->cur_exp);
21660   if ( mp->selector>=log_only && mp->selector<write_file) {
21661     mp->old_setting=mp->selector; mp->selector=log_only;
21662     mp_print_nl(mp, "{randomseed:="); 
21663     mp_print_scaled(mp, mp->cur_exp); 
21664     mp_print_char(mp, '}');
21665     mp_print_nl(mp, ""); mp->selector=mp->old_setting;
21666   }
21667 }
21668
21669 @ And here's another simple one (somewhat different in flavor):
21670
21671 @<Cases of |do_statement|...@>=
21672 case mode_command: 
21673   mp_print_ln(mp); mp->interaction=mp->cur_mod;
21674   @<Initialize the print |selector| based on |interaction|@>;
21675   if ( mp->log_opened ) mp->selector=mp->selector+2;
21676   mp_get_x_next(mp);
21677   break;
21678
21679 @ @<Put each...@>=
21680 mp_primitive(mp, "batchmode",mode_command,mp_batch_mode);
21681 @:mp_batch_mode_}{\&{batchmode} primitive@>
21682 mp_primitive(mp, "nonstopmode",mode_command,mp_nonstop_mode);
21683 @:mp_nonstop_mode_}{\&{nonstopmode} primitive@>
21684 mp_primitive(mp, "scrollmode",mode_command,mp_scroll_mode);
21685 @:mp_scroll_mode_}{\&{scrollmode} primitive@>
21686 mp_primitive(mp, "errorstopmode",mode_command,mp_error_stop_mode);
21687 @:mp_error_stop_mode_}{\&{errorstopmode} primitive@>
21688
21689 @ @<Cases of |print_cmd_mod|...@>=
21690 case mode_command: 
21691   switch (m) {
21692   case mp_batch_mode: mp_print(mp, "batchmode"); break;
21693   case mp_nonstop_mode: mp_print(mp, "nonstopmode"); break;
21694   case mp_scroll_mode: mp_print(mp, "scrollmode"); break;
21695   default: mp_print(mp, "errorstopmode"); break;
21696   }
21697   break;
21698
21699 @ The `\&{inner}' and `\&{outer}' commands are only slightly harder.
21700
21701 @<Cases of |do_statement|...@>=
21702 case protection_command: mp_do_protection(mp); break;
21703
21704 @ @<Put each...@>=
21705 mp_primitive(mp, "inner",protection_command,0);
21706 @:inner_}{\&{inner} primitive@>
21707 mp_primitive(mp, "outer",protection_command,1);
21708 @:outer_}{\&{outer} primitive@>
21709
21710 @ @<Cases of |print_cmd...@>=
21711 case protection_command: 
21712   if ( m==0 ) mp_print(mp, "inner");
21713   else mp_print(mp, "outer");
21714   break;
21715
21716 @ @<Declare action procedures for use by |do_statement|@>=
21717 void mp_do_protection (MP mp) ;
21718
21719 @ @c void mp_do_protection (MP mp) {
21720   int m; /* 0 to unprotect, 1 to protect */
21721   halfword t; /* the |eq_type| before we change it */
21722   m=mp->cur_mod;
21723   do {  
21724     mp_get_symbol(mp); t=eq_type(mp->cur_sym);
21725     if ( m==0 ) { 
21726       if ( t>=outer_tag ) 
21727         eq_type(mp->cur_sym)=t-outer_tag;
21728     } else if ( t<outer_tag ) {
21729       eq_type(mp->cur_sym)=t+outer_tag;
21730     }
21731     mp_get_x_next(mp);
21732   } while (mp->cur_cmd==comma);
21733 }
21734
21735 @ \MP\ never defines the tokens `\.(' and `\.)' to be primitives, but
21736 plain \MP\ begins with the declaration `\&{delimiters} \.{()}'. Such a
21737 declaration assigns the command code |left_delimiter| to `\.{(}' and
21738 |right_delimiter| to `\.{)}'; the |equiv| of each delimiter is the
21739 hash address of its mate.
21740
21741 @<Cases of |do_statement|...@>=
21742 case delimiters: mp_def_delims(mp); break;
21743
21744 @ @<Declare action procedures for use by |do_statement|@>=
21745 void mp_def_delims (MP mp) ;
21746
21747 @ @c void mp_def_delims (MP mp) {
21748   pointer l_delim,r_delim; /* the new delimiter pair */
21749   mp_get_clear_symbol(mp); l_delim=mp->cur_sym;
21750   mp_get_clear_symbol(mp); r_delim=mp->cur_sym;
21751   eq_type(l_delim)=left_delimiter; equiv(l_delim)=r_delim;
21752   eq_type(r_delim)=right_delimiter; equiv(r_delim)=l_delim;
21753   mp_get_x_next(mp);
21754 }
21755
21756 @ Here is a procedure that is called when \MP\ has reached a point
21757 where some right delimiter is mandatory.
21758
21759 @<Declare the procedure called |check_delimiter|@>=
21760 void mp_check_delimiter (MP mp,pointer l_delim, pointer r_delim) {
21761   if ( mp->cur_cmd==right_delimiter ) 
21762     if ( mp->cur_mod==l_delim ) 
21763       return;
21764   if ( mp->cur_sym!=r_delim ) {
21765      mp_missing_err(mp, str(text(r_delim)));
21766 @.Missing `)'@>
21767     help2("I found no right delimiter to match a left one. So I've")
21768       ("put one in, behind the scenes; this may fix the problem.");
21769     mp_back_error(mp);
21770   } else { 
21771     print_err("The token `"); mp_print_text(r_delim);
21772 @.The token...delimiter@>
21773     mp_print(mp, "' is no longer a right delimiter");
21774     help3("Strange: This token has lost its former meaning!")
21775       ("I'll read it as a right delimiter this time;")
21776       ("but watch out, I'll probably miss it later.");
21777     mp_error(mp);
21778   }
21779 }
21780
21781 @ The next four commands save or change the values associated with tokens.
21782
21783 @<Cases of |do_statement|...@>=
21784 case save_command: 
21785   do {  
21786     mp_get_symbol(mp); mp_save_variable(mp, mp->cur_sym); mp_get_x_next(mp);
21787   } while (mp->cur_cmd==comma);
21788   break;
21789 case interim_command: mp_do_interim(mp); break;
21790 case let_command: mp_do_let(mp); break;
21791 case new_internal: mp_do_new_internal(mp); break;
21792
21793 @ @<Declare action procedures for use by |do_statement|@>=
21794 void mp_do_statement (MP mp);
21795 void mp_do_interim (MP mp);
21796
21797 @ @c void mp_do_interim (MP mp) { 
21798   mp_get_x_next(mp);
21799   if ( mp->cur_cmd!=internal_quantity ) {
21800      print_err("The token `");
21801 @.The token...quantity@>
21802     if ( mp->cur_sym==0 ) mp_print(mp, "(%CAPSULE)");
21803     else mp_print_text(mp->cur_sym);
21804     mp_print(mp, "' isn't an internal quantity");
21805     help1("Something like `tracingonline' should follow `interim'.");
21806     mp_back_error(mp);
21807   } else { 
21808     mp_save_internal(mp, mp->cur_mod); mp_back_input(mp);
21809   }
21810   mp_do_statement(mp);
21811 }
21812
21813 @ The following procedure is careful not to undefine the left-hand symbol
21814 too soon, lest commands like `{\tt let x=x}' have a surprising effect.
21815
21816 @<Declare action procedures for use by |do_statement|@>=
21817 void mp_do_let (MP mp) ;
21818
21819 @ @c void mp_do_let (MP mp) {
21820   pointer l; /* hash location of the left-hand symbol */
21821   mp_get_symbol(mp); l=mp->cur_sym; mp_get_x_next(mp);
21822   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
21823      mp_missing_err(mp, "=");
21824 @.Missing `='@>
21825     help3("You should have said `let symbol = something'.")
21826       ("But don't worry; I'll pretend that an equals sign")
21827       ("was present. The next token I read will be `something'.");
21828     mp_back_error(mp);
21829   }
21830   mp_get_symbol(mp);
21831   switch (mp->cur_cmd) {
21832   case defined_macro: case secondary_primary_macro:
21833   case tertiary_secondary_macro: case expression_tertiary_macro: 
21834     add_mac_ref(mp->cur_mod);
21835     break;
21836   default: 
21837     break;
21838   }
21839   mp_clear_symbol(mp, l,false); eq_type(l)=mp->cur_cmd;
21840   if ( mp->cur_cmd==tag_token ) equiv(l)=null;
21841   else equiv(l)=mp->cur_mod;
21842   mp_get_x_next(mp);
21843 }
21844
21845 @ @<Declarations@>=
21846 void mp_grow_internals (MP mp, int l);
21847 void mp_do_new_internal (MP mp) ;
21848
21849 @ @c
21850 void mp_grow_internals (MP mp, int l) {
21851   scaled *internal;
21852   char * *int_name; 
21853   int k;
21854   if ( hash_end+l>max_halfword ) {
21855     mp_confusion(mp, "out of memory space"); /* can't be reached */
21856   }
21857   int_name = xmalloc ((l+1),sizeof(char *));
21858   internal = xmalloc ((l+1),sizeof(scaled));
21859   for (k=0;k<=l; k++ ) { 
21860     if (k<=mp->max_internal) {
21861       internal[k]=mp->internal[k]; 
21862       int_name[k]=mp->int_name[k]; 
21863     } else {
21864       internal[k]=0; 
21865       int_name[k]=NULL; 
21866     }
21867   }
21868   xfree(mp->internal); xfree(mp->int_name);
21869   mp->int_name = int_name;
21870   mp->internal = internal;
21871   mp->max_internal = l;
21872 }
21873
21874
21875 void mp_do_new_internal (MP mp) { 
21876   do {  
21877     if ( mp->int_ptr==mp->max_internal ) {
21878       mp_grow_internals(mp, (mp->max_internal + (mp->max_internal>>2)));
21879     }
21880     mp_get_clear_symbol(mp); incr(mp->int_ptr);
21881     eq_type(mp->cur_sym)=internal_quantity; 
21882     equiv(mp->cur_sym)=mp->int_ptr;
21883     if(mp->int_name[mp->int_ptr]!=NULL)
21884       xfree(mp->int_name[mp->int_ptr]);
21885     mp->int_name[mp->int_ptr]=str(text(mp->cur_sym)); 
21886     mp->internal[mp->int_ptr]=0;
21887     mp_get_x_next(mp);
21888   } while (mp->cur_cmd==comma);
21889 }
21890
21891 @ @<Dealloc variables@>=
21892 for (k=0;k<=mp->max_internal;k++) {
21893    xfree(mp->int_name[k]);
21894 }
21895 xfree(mp->internal); 
21896 xfree(mp->int_name); 
21897
21898
21899 @ The various `\&{show}' commands are distinguished by modifier fields
21900 in the usual way.
21901
21902 @d show_token_code 0 /* show the meaning of a single token */
21903 @d show_stats_code 1 /* show current memory and string usage */
21904 @d show_code 2 /* show a list of expressions */
21905 @d show_var_code 3 /* show a variable and its descendents */
21906 @d show_dependencies_code 4 /* show dependent variables in terms of independents */
21907
21908 @<Put each...@>=
21909 mp_primitive(mp, "showtoken",show_command,show_token_code);
21910 @:show_token_}{\&{showtoken} primitive@>
21911 mp_primitive(mp, "showstats",show_command,show_stats_code);
21912 @:show_stats_}{\&{showstats} primitive@>
21913 mp_primitive(mp, "show",show_command,show_code);
21914 @:show_}{\&{show} primitive@>
21915 mp_primitive(mp, "showvariable",show_command,show_var_code);
21916 @:show_var_}{\&{showvariable} primitive@>
21917 mp_primitive(mp, "showdependencies",show_command,show_dependencies_code);
21918 @:show_dependencies_}{\&{showdependencies} primitive@>
21919
21920 @ @<Cases of |print_cmd...@>=
21921 case show_command: 
21922   switch (m) {
21923   case show_token_code:mp_print(mp, "showtoken"); break;
21924   case show_stats_code:mp_print(mp, "showstats"); break;
21925   case show_code:mp_print(mp, "show"); break;
21926   case show_var_code:mp_print(mp, "showvariable"); break;
21927   default: mp_print(mp, "showdependencies"); break;
21928   }
21929   break;
21930
21931 @ @<Cases of |do_statement|...@>=
21932 case show_command:mp_do_show_whatever(mp); break;
21933
21934 @ The value of |cur_mod| controls the |verbosity| in the |print_exp| routine:
21935 if it's |show_code|, complicated structures are abbreviated, otherwise
21936 they aren't.
21937
21938 @<Declare action procedures for use by |do_statement|@>=
21939 void mp_do_show (MP mp) ;
21940
21941 @ @c void mp_do_show (MP mp) { 
21942   do {  
21943     mp_get_x_next(mp); mp_scan_expression(mp);
21944     mp_print_nl(mp, ">> ");
21945 @.>>@>
21946     mp_print_exp(mp, null,2); mp_flush_cur_exp(mp, 0);
21947   } while (mp->cur_cmd==comma);
21948 }
21949
21950 @ @<Declare action procedures for use by |do_statement|@>=
21951 void mp_disp_token (MP mp) ;
21952
21953 @ @c void mp_disp_token (MP mp) { 
21954   mp_print_nl(mp, "> ");
21955 @.>\relax@>
21956   if ( mp->cur_sym==0 ) {
21957     @<Show a numeric or string or capsule token@>;
21958   } else { 
21959     mp_print_text(mp->cur_sym); mp_print_char(mp, '=');
21960     if ( eq_type(mp->cur_sym)>=outer_tag ) mp_print(mp, "(outer) ");
21961     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod);
21962     if ( mp->cur_cmd==defined_macro ) {
21963       mp_print_ln(mp); mp_show_macro(mp, mp->cur_mod,null,100000);
21964     } /* this avoids recursion between |show_macro| and |print_cmd_mod| */
21965 @^recursion@>
21966   }
21967 }
21968
21969 @ @<Show a numeric or string or capsule token@>=
21970
21971   if ( mp->cur_cmd==numeric_token ) {
21972     mp_print_scaled(mp, mp->cur_mod);
21973   } else if ( mp->cur_cmd==capsule_token ) {
21974     mp->g_pointer=mp->cur_mod; mp_print_capsule(mp);
21975   } else  { 
21976     mp_print_char(mp, '"'); 
21977     mp_print_str(mp, mp->cur_mod); mp_print_char(mp, '"');
21978     delete_str_ref(mp->cur_mod);
21979   }
21980 }
21981
21982 @ The following cases of |print_cmd_mod| might arise in connection
21983 with |disp_token|, although they don't correspond to any
21984 primitive tokens.
21985
21986 @<Cases of |print_cmd_...@>=
21987 case left_delimiter:
21988 case right_delimiter: 
21989   if ( c==left_delimiter ) mp_print(mp, "left");
21990   else mp_print(mp, "right");
21991   mp_print(mp, " delimiter that matches "); 
21992   mp_print_text(m);
21993   break;
21994 case tag_token:
21995   if ( m==null ) mp_print(mp, "tag");
21996    else mp_print(mp, "variable");
21997    break;
21998 case defined_macro: 
21999    mp_print(mp, "macro:");
22000    break;
22001 case secondary_primary_macro:
22002 case tertiary_secondary_macro:
22003 case expression_tertiary_macro:
22004   mp_print_cmd_mod(mp, macro_def,c); 
22005   mp_print(mp, "'d macro:");
22006   mp_print_ln(mp); mp_show_token_list(mp, link(link(m)),null,1000,0);
22007   break;
22008 case repeat_loop:
22009   mp_print(mp, "[repeat the loop]");
22010   break;
22011 case internal_quantity:
22012   mp_print(mp, mp->int_name[m]);
22013   break;
22014
22015 @ @<Declare action procedures for use by |do_statement|@>=
22016 void mp_do_show_token (MP mp) ;
22017
22018 @ @c void mp_do_show_token (MP mp) { 
22019   do {  
22020     get_t_next; mp_disp_token(mp);
22021     mp_get_x_next(mp);
22022   } while (mp->cur_cmd==comma);
22023 }
22024
22025 @ @<Declare action procedures for use by |do_statement|@>=
22026 void mp_do_show_stats (MP mp) ;
22027
22028 @ @c void mp_do_show_stats (MP mp) { 
22029   mp_print_nl(mp, "Memory usage ");
22030 @.Memory usage...@>
22031   mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used);
22032   if ( false )
22033     mp_print(mp, "unknown");
22034   mp_print(mp, " ("); mp_print_int(mp, mp->hi_mem_min-mp->lo_mem_max-1);
22035   mp_print(mp, " still untouched)"); mp_print_ln(mp);
22036   mp_print_nl(mp, "String usage ");
22037   mp_print_int(mp, mp->strs_in_use-mp->init_str_use);
22038   mp_print_char(mp, '&'); mp_print_int(mp, mp->pool_in_use-mp->init_pool_ptr);
22039   if ( false )
22040     mp_print(mp, "unknown");
22041   mp_print(mp, " (");
22042   mp_print_int(mp, mp->max_strings-1-mp->strs_used_up); mp_print_char(mp, '&');
22043   mp_print_int(mp, mp->pool_size-mp->pool_ptr); 
22044   mp_print(mp, " now untouched)"); mp_print_ln(mp);
22045   mp_get_x_next(mp);
22046 }
22047
22048 @ Here's a recursive procedure that gives an abbreviated account
22049 of a variable, for use by |do_show_var|.
22050
22051 @<Declare action procedures for use by |do_statement|@>=
22052 void mp_disp_var (MP mp,pointer p) ;
22053
22054 @ @c void mp_disp_var (MP mp,pointer p) {
22055   pointer q; /* traverses attributes and subscripts */
22056   int n; /* amount of macro text to show */
22057   if ( type(p)==mp_structured )  {
22058     @<Descend the structure@>;
22059   } else if ( type(p)>=mp_unsuffixed_macro ) {
22060     @<Display a variable macro@>;
22061   } else if ( type(p)!=undefined ){ 
22062     mp_print_nl(mp, ""); mp_print_variable_name(mp, p); 
22063     mp_print_char(mp, '=');
22064     mp_print_exp(mp, p,0);
22065   }
22066 }
22067
22068 @ @<Descend the structure@>=
22069
22070   q=attr_head(p);
22071   do {  mp_disp_var(mp, q); q=link(q); } while (q!=end_attr);
22072   q=subscr_head(p);
22073   while ( name_type(q)==mp_subscr ) { 
22074     mp_disp_var(mp, q); q=link(q);
22075   }
22076 }
22077
22078 @ @<Display a variable macro@>=
22079
22080   mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22081   if ( type(p)>mp_unsuffixed_macro ) 
22082     mp_print(mp, "@@#"); /* |suffixed_macro| */
22083   mp_print(mp, "=macro:");
22084   if ( (int)mp->file_offset>=mp->max_print_line-20 ) n=5;
22085   else n=mp->max_print_line-mp->file_offset-15;
22086   mp_show_macro(mp, value(p),null,n);
22087 }
22088
22089 @ @<Declare action procedures for use by |do_statement|@>=
22090 void mp_do_show_var (MP mp) ;
22091
22092 @ @c void mp_do_show_var (MP mp) { 
22093   do {  
22094     get_t_next;
22095     if ( mp->cur_sym>0 ) if ( mp->cur_sym<=hash_end )
22096       if ( mp->cur_cmd==tag_token ) if ( mp->cur_mod!=null ) {
22097       mp_disp_var(mp, mp->cur_mod); goto DONE;
22098     }
22099    mp_disp_token(mp);
22100   DONE:
22101    mp_get_x_next(mp);
22102   } while (mp->cur_cmd==comma);
22103 }
22104
22105 @ @<Declare action procedures for use by |do_statement|@>=
22106 void mp_do_show_dependencies (MP mp) ;
22107
22108 @ @c void mp_do_show_dependencies (MP mp) {
22109   pointer p; /* link that runs through all dependencies */
22110   p=link(dep_head);
22111   while ( p!=dep_head ) {
22112     if ( mp_interesting(mp, p) ) {
22113       mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22114       if ( type(p)==mp_dependent ) mp_print_char(mp, '=');
22115       else mp_print(mp, " = "); /* extra spaces imply proto-dependency */
22116       mp_print_dependency(mp, dep_list(p),type(p));
22117     }
22118     p=dep_list(p);
22119     while ( info(p)!=null ) p=link(p);
22120     p=link(p);
22121   }
22122   mp_get_x_next(mp);
22123 }
22124
22125 @ Finally we are ready for the procedure that governs all of the
22126 show commands.
22127
22128 @<Declare action procedures for use by |do_statement|@>=
22129 void mp_do_show_whatever (MP mp) ;
22130
22131 @ @c void mp_do_show_whatever (MP mp) { 
22132   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
22133   switch (mp->cur_mod) {
22134   case show_token_code:mp_do_show_token(mp); break;
22135   case show_stats_code:mp_do_show_stats(mp); break;
22136   case show_code:mp_do_show(mp); break;
22137   case show_var_code:mp_do_show_var(mp); break;
22138   case show_dependencies_code:mp_do_show_dependencies(mp); break;
22139   } /* there are no other cases */
22140   if ( mp->internal[showstopping]>0 ){ 
22141     print_err("OK");
22142 @.OK@>
22143     if ( mp->interaction<mp_error_stop_mode ) { 
22144       help0; decr(mp->error_count);
22145     } else {
22146       help1("This isn't an error message; I'm just showing something.");
22147     }
22148     if ( mp->cur_cmd==semicolon ) mp_error(mp);
22149      else mp_put_get_error(mp);
22150   }
22151 }
22152
22153 @ The `\&{addto}' command needs the following additional primitives:
22154
22155 @d double_path_code 0 /* command modifier for `\&{doublepath}' */
22156 @d contour_code 1 /* command modifier for `\&{contour}' */
22157 @d also_code 2 /* command modifier for `\&{also}' */
22158
22159 @ Pre and postscripts need two new identifiers:
22160
22161 @d with_pre_script 11
22162 @d with_post_script 13
22163
22164 @<Put each...@>=
22165 mp_primitive(mp, "doublepath",thing_to_add,double_path_code);
22166 @:double_path_}{\&{doublepath} primitive@>
22167 mp_primitive(mp, "contour",thing_to_add,contour_code);
22168 @:contour_}{\&{contour} primitive@>
22169 mp_primitive(mp, "also",thing_to_add,also_code);
22170 @:also_}{\&{also} primitive@>
22171 mp_primitive(mp, "withpen",with_option,mp_pen_type);
22172 @:with_pen_}{\&{withpen} primitive@>
22173 mp_primitive(mp, "dashed",with_option,mp_picture_type);
22174 @:dashed_}{\&{dashed} primitive@>
22175 mp_primitive(mp, "withprescript",with_option,with_pre_script);
22176 @:with_pre_script_}{\&{withprescript} primitive@>
22177 mp_primitive(mp, "withpostscript",with_option,with_post_script);
22178 @:with_post_script_}{\&{withpostscript} primitive@>
22179 mp_primitive(mp, "withoutcolor",with_option,no_model);
22180 @:with_color_}{\&{withoutcolor} primitive@>
22181 mp_primitive(mp, "withgreyscale",with_option,grey_model);
22182 @:with_color_}{\&{withgreyscale} primitive@>
22183 mp_primitive(mp, "withcolor",with_option,uninitialized_model);
22184 @:with_color_}{\&{withcolor} primitive@>
22185 /*  \&{withrgbcolor} is an alias for \&{withcolor} */
22186 mp_primitive(mp, "withrgbcolor",with_option,rgb_model);
22187 @:with_color_}{\&{withrgbcolor} primitive@>
22188 mp_primitive(mp, "withcmykcolor",with_option,cmyk_model);
22189 @:with_color_}{\&{withcmykcolor} primitive@>
22190
22191 @ @<Cases of |print_cmd...@>=
22192 case thing_to_add:
22193   if ( m==contour_code ) mp_print(mp, "contour");
22194   else if ( m==double_path_code ) mp_print(mp, "doublepath");
22195   else mp_print(mp, "also");
22196   break;
22197 case with_option:
22198   if ( m==mp_pen_type ) mp_print(mp, "withpen");
22199   else if ( m==with_pre_script ) mp_print(mp, "withprescript");
22200   else if ( m==with_post_script ) mp_print(mp, "withpostscript");
22201   else if ( m==no_model ) mp_print(mp, "withoutcolor");
22202   else if ( m==rgb_model ) mp_print(mp, "withrgbcolor");
22203   else if ( m==uninitialized_model ) mp_print(mp, "withcolor");
22204   else if ( m==cmyk_model ) mp_print(mp, "withcmykcolor");
22205   else if ( m==grey_model ) mp_print(mp, "withgreyscale");
22206   else mp_print(mp, "dashed");
22207   break;
22208
22209 @ The |scan_with_list| procedure parses a $\langle$with list$\rangle$ and
22210 updates the list of graphical objects starting at |p|.  Each $\langle$with
22211 clause$\rangle$ updates all graphical objects whose |type| is compatible.
22212 Other objects are ignored.
22213
22214 @<Declare action procedures for use by |do_statement|@>=
22215 void mp_scan_with_list (MP mp,pointer p) ;
22216
22217 @ @c void mp_scan_with_list (MP mp,pointer p) {
22218   small_number t; /* |cur_mod| of the |with_option| (should match |cur_type|) */
22219   pointer q; /* for list manipulation */
22220   int old_setting; /* saved |selector| setting */
22221   pointer k; /* for finding the near-last item in a list  */
22222   str_number s; /* for string cleanup after combining  */
22223   pointer cp,pp,dp,ap,bp;
22224     /* objects being updated; |void| initially; |null| to suppress update */
22225   cp=diov; pp=diov; dp=diov; ap=diov; bp=diov;
22226   k=0;
22227   while ( mp->cur_cmd==with_option ){ 
22228     t=mp->cur_mod;
22229     mp_get_x_next(mp);
22230     if ( t!=no_model ) mp_scan_expression(mp);
22231     if (((t==with_pre_script)&&(mp->cur_type!=mp_string_type))||
22232      ((t==with_post_script)&&(mp->cur_type!=mp_string_type))||
22233      ((t==uninitialized_model)&&
22234         ((mp->cur_type!=mp_cmykcolor_type)&&(mp->cur_type!=mp_color_type)
22235           &&(mp->cur_type!=mp_known)&&(mp->cur_type!=mp_boolean_type)))||
22236      ((t==cmyk_model)&&(mp->cur_type!=mp_cmykcolor_type))||
22237      ((t==rgb_model)&&(mp->cur_type!=mp_color_type))||
22238      ((t==grey_model)&&(mp->cur_type!=mp_known))||
22239      ((t==mp_pen_type)&&(mp->cur_type!=t))||
22240      ((t==mp_picture_type)&&(mp->cur_type!=t)) ) {
22241       @<Complain about improper type@>;
22242     } else if ( t==uninitialized_model ) {
22243       if ( cp==diov ) @<Make |cp| a colored object in object list~|p|@>;
22244       if ( cp!=null )
22245         @<Transfer a color from the current expression to object~|cp|@>;
22246       mp_flush_cur_exp(mp, 0);
22247     } else if ( t==rgb_model ) {
22248       if ( cp==diov ) @<Make |cp| a colored object in object list~|p|@>;
22249       if ( cp!=null )
22250         @<Transfer a rgbcolor from the current expression to object~|cp|@>;
22251       mp_flush_cur_exp(mp, 0);
22252     } else if ( t==cmyk_model ) {
22253       if ( cp==diov ) @<Make |cp| a colored object in object list~|p|@>;
22254       if ( cp!=null )
22255         @<Transfer a cmykcolor from the current expression to object~|cp|@>;
22256       mp_flush_cur_exp(mp, 0);
22257     } else if ( t==grey_model ) {
22258       if ( cp==diov ) @<Make |cp| a colored object in object list~|p|@>;
22259       if ( cp!=null )
22260         @<Transfer a greyscale from the current expression to object~|cp|@>;
22261       mp_flush_cur_exp(mp, 0);
22262     } else if ( t==no_model ) {
22263       if ( cp==diov ) @<Make |cp| a colored object in object list~|p|@>;
22264       if ( cp!=null )
22265         @<Transfer a noncolor from the current expression to object~|cp|@>;
22266     } else if ( t==mp_pen_type ) {
22267       if ( pp==diov ) @<Make |pp| an object in list~|p| that needs a pen@>;
22268       if ( pp!=null ) {
22269         if ( pen_p(pp)!=null ) mp_toss_knot_list(mp, pen_p(pp));
22270         pen_p(pp)=mp->cur_exp; mp->cur_type=mp_vacuous;
22271       }
22272     } else if ( t==with_pre_script ) {
22273       if ( ap==diov )
22274         ap=p;
22275       while ( (ap!=null)&&(! has_color(ap)) )
22276          ap=link(ap);
22277       if ( ap!=null ) {
22278         if ( pre_script(ap)!=null ) { /*  build a new,combined string  */
22279           s=pre_script(ap);
22280           old_setting=mp->selector;
22281               mp->selector=new_string;
22282           str_room(length(pre_script(ap))+length(mp->cur_exp)+2);
22283               mp_print_str(mp, mp->cur_exp);
22284           append_char(13);  /* a forced \ps\ newline  */
22285           mp_print_str(mp, pre_script(ap));
22286           pre_script(ap)=mp_make_string(mp);
22287           delete_str_ref(s);
22288           mp->selector=old_setting;
22289         } else {
22290           pre_script(ap)=mp->cur_exp;
22291         }
22292         mp->cur_type=mp_vacuous;
22293       }
22294     } else if ( t==with_post_script ) {
22295       if ( bp==diov )
22296         k=p; 
22297       bp=k;
22298       while ( link(k)!=null ) {
22299         k=link(k);
22300         if ( has_color(k) ) bp=k;
22301       }
22302       if ( bp!=null ) {
22303          if ( post_script(bp)!=null ) {
22304            s=post_script(bp);
22305            old_setting=mp->selector;
22306                mp->selector=new_string;
22307            str_room(length(post_script(bp))+length(mp->cur_exp)+2);
22308            mp_print_str(mp, post_script(bp));
22309            append_char(13); /* a forced \ps\ newline  */
22310            mp_print_str(mp, mp->cur_exp);
22311            post_script(bp)=mp_make_string(mp);
22312            delete_str_ref(s);
22313            mp->selector=old_setting;
22314          } else {
22315            post_script(bp)=mp->cur_exp;
22316          }
22317          mp->cur_type=mp_vacuous;
22318        }
22319     } else { 
22320       if ( dp==diov ) 
22321         @<Make |dp| a stroked node in list~|p|@>;
22322       if ( dp!=null ) {
22323         if ( dash_p(dp)!=null ) delete_edge_ref(dash_p(dp));
22324         dash_p(dp)=mp_make_dashes(mp, mp->cur_exp);
22325         dash_scale(dp)=unity;
22326         mp->cur_type=mp_vacuous;
22327       }
22328     }
22329   }
22330   @<Copy the information from objects |cp|, |pp|, and |dp| into the rest
22331     of the list@>;
22332 };
22333
22334 @ @<Complain about improper type@>=
22335 { exp_err("Improper type");
22336 @.Improper type@>
22337 help2("Next time say `withpen <known pen expression>';")
22338   ("I'll ignore the bad `with' clause and look for another.");
22339 if ( t==with_pre_script )
22340   mp->help_line[1]="Next time say `withprescript <known string expression>';";
22341 else if ( t==with_post_script )
22342   mp->help_line[1]="Next time say `withpostscript <known string expression>';";
22343 else if ( t==mp_picture_type )
22344   mp->help_line[1]="Next time say `dashed <known picture expression>';";
22345 else if ( t==uninitialized_model )
22346   mp->help_line[1]="Next time say `withcolor <known color expression>';";
22347 else if ( t==rgb_model )
22348   mp->help_line[1]="Next time say `withrgbcolor <known color expression>';";
22349 else if ( t==cmyk_model )
22350   mp->help_line[1]="Next time say `withcmykcolor <known cmykcolor expression>';";
22351 else if ( t==grey_model )
22352   mp->help_line[1]="Next time say `withgreyscale <known numeric expression>';";;
22353 mp_put_get_flush_error(mp, 0);
22354 }
22355
22356 @ Forcing the color to be between |0| and |unity| here guarantees that no
22357 picture will ever contain a color outside the legal range for \ps\ graphics.
22358
22359 @<Transfer a color from the current expression to object~|cp|@>=
22360 { if ( mp->cur_type==mp_color_type )
22361    @<Transfer a rgbcolor from the current expression to object~|cp|@>
22362 else if ( mp->cur_type==mp_cmykcolor_type )
22363    @<Transfer a cmykcolor from the current expression to object~|cp|@>
22364 else if ( mp->cur_type==mp_known )
22365    @<Transfer a greyscale from the current expression to object~|cp|@>
22366 else if ( mp->cur_exp==false_code )
22367    @<Transfer a noncolor from the current expression to object~|cp|@>;
22368 }
22369
22370 @ @<Transfer a rgbcolor from the current expression to object~|cp|@>=
22371 { q=value(mp->cur_exp);
22372 cyan_val(cp)=0;
22373 magenta_val(cp)=0;
22374 yellow_val(cp)=0;
22375 black_val(cp)=0;
22376 red_val(cp)=value(red_part_loc(q));
22377 green_val(cp)=value(green_part_loc(q));
22378 blue_val(cp)=value(blue_part_loc(q));
22379 color_model(cp)=rgb_model;
22380 if ( red_val(cp)<0 ) red_val(cp)=0;
22381 if ( green_val(cp)<0 ) green_val(cp)=0;
22382 if ( blue_val(cp)<0 ) blue_val(cp)=0;
22383 if ( red_val(cp)>unity ) red_val(cp)=unity;
22384 if ( green_val(cp)>unity ) green_val(cp)=unity;
22385 if ( blue_val(cp)>unity ) blue_val(cp)=unity;
22386 }
22387
22388 @ @<Transfer a cmykcolor from the current expression to object~|cp|@>=
22389 { q=value(mp->cur_exp);
22390 cyan_val(cp)=value(cyan_part_loc(q));
22391 magenta_val(cp)=value(magenta_part_loc(q));
22392 yellow_val(cp)=value(yellow_part_loc(q));
22393 black_val(cp)=value(black_part_loc(q));
22394 color_model(cp)=cmyk_model;
22395 if ( cyan_val(cp)<0 ) cyan_val(cp)=0;
22396 if ( magenta_val(cp)<0 ) magenta_val(cp)=0;
22397 if ( yellow_val(cp)<0 ) yellow_val(cp)=0;
22398 if ( black_val(cp)<0 ) black_val(cp)=0;
22399 if ( cyan_val(cp)>unity ) cyan_val(cp)=unity;
22400 if ( magenta_val(cp)>unity ) magenta_val(cp)=unity;
22401 if ( yellow_val(cp)>unity ) yellow_val(cp)=unity;
22402 if ( black_val(cp)>unity ) black_val(cp)=unity;
22403 }
22404
22405 @ @<Transfer a greyscale from the current expression to object~|cp|@>=
22406 { q=mp->cur_exp;
22407 cyan_val(cp)=0;
22408 magenta_val(cp)=0;
22409 yellow_val(cp)=0;
22410 black_val(cp)=0;
22411 grey_val(cp)=q;
22412 color_model(cp)=grey_model;
22413 if ( grey_val(cp)<0 ) grey_val(cp)=0;
22414 if ( grey_val(cp)>unity ) grey_val(cp)=unity;
22415 }
22416
22417 @ @<Transfer a noncolor from the current expression to object~|cp|@>=
22418 {
22419 cyan_val(cp)=0;
22420 magenta_val(cp)=0;
22421 yellow_val(cp)=0;
22422 black_val(cp)=0;
22423 grey_val(cp)=0;
22424 color_model(cp)=no_model;
22425 }
22426
22427 @ @<Make |cp| a colored object in object list~|p|@>=
22428 { cp=p;
22429   while ( cp!=null ){ 
22430     if ( has_color(cp) ) break;
22431     cp=link(cp);
22432   }
22433 }
22434
22435 @ @<Make |pp| an object in list~|p| that needs a pen@>=
22436 { pp=p;
22437   while ( pp!=null ) {
22438     if ( has_pen(pp) ) break;
22439     pp=link(pp);
22440   }
22441 }
22442
22443 @ @<Make |dp| a stroked node in list~|p|@>=
22444 { dp=p;
22445   while ( dp!=null ) {
22446     if ( type(dp)==stroked_code ) break;
22447     dp=link(dp);
22448   }
22449 }
22450
22451 @ @<Copy the information from objects |cp|, |pp|, and |dp| into...@>=
22452 @<Copy |cp|'s color into the colored objects linked to~|cp|@>;
22453 if ( pp>diov )
22454   @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>;
22455 if ( dp>diov ) @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>
22456
22457 @ @<Copy |cp|'s color into the colored objects linked to~|cp|@>=
22458 { q=link(cp);
22459   while ( q!=null ) { 
22460     if ( has_color(q) ) {
22461       red_val(q)=red_val(cp);
22462       green_val(q)=green_val(cp);
22463       blue_val(q)=blue_val(cp);
22464       black_val(q)=black_val(cp);
22465       color_model(q)=color_model(cp);
22466     }
22467     q=link(q);
22468   }
22469 }
22470
22471 @ @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>=
22472 { q=link(pp);
22473   while ( q!=null ) {
22474     if ( has_pen(q) ) {
22475       if ( pen_p(q)!=null ) mp_toss_knot_list(mp, pen_p(q));
22476       pen_p(q)=copy_pen(pen_p(pp));
22477     }
22478     q=link(q);
22479   }
22480 }
22481
22482 @ @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>=
22483 { q=link(dp);
22484   while ( q!=null ) {
22485     if ( type(q)==stroked_code ) {
22486       if ( dash_p(q)!=null ) delete_edge_ref(dash_p(q));
22487       dash_p(q)=dash_p(dp);
22488       dash_scale(q)=unity;
22489       if ( dash_p(q)!=null ) add_edge_ref(dash_p(q));
22490     }
22491     q=link(q);
22492   }
22493 }
22494
22495 @ One of the things we need to do when we've parsed an \&{addto} or
22496 similar command is find the header of a supposed \&{picture} variable, given
22497 a token list for that variable.  Since the edge structure is about to be
22498 updated, we use |private_edges| to make sure that this is possible.
22499
22500 @<Declare action procedures for use by |do_statement|@>=
22501 pointer mp_find_edges_var (MP mp, pointer t) ;
22502
22503 @ @c pointer mp_find_edges_var (MP mp, pointer t) {
22504   pointer p;
22505   pointer cur_edges; /* the return value */
22506   p=mp_find_variable(mp, t); cur_edges=null;
22507   if ( p==null ) { 
22508     mp_obliterated(mp, t); mp_put_get_error(mp);
22509   } else if ( type(p)!=mp_picture_type )  { 
22510     print_err("Variable "); mp_show_token_list(mp, t,null,1000,0);
22511 @.Variable x is the wrong type@>
22512     mp_print(mp, " is the wrong type ("); 
22513     mp_print_type(mp, type(p)); mp_print_char(mp, ')');
22514     help2("I was looking for a \"known\" picture variable.")
22515          ("So I'll not change anything just now."); 
22516     mp_put_get_error(mp);
22517   } else { 
22518     value(p)=mp_private_edges(mp, value(p));
22519     cur_edges=value(p);
22520   }
22521   mp_flush_node_list(mp, t);
22522   return cur_edges;
22523 };
22524
22525 @ @<Cases of |do_statement|...@>=
22526 case add_to_command: mp_do_add_to(mp); break;
22527 case bounds_command:mp_do_bounds(mp); break;
22528
22529 @ @<Put each...@>=
22530 mp_primitive(mp, "clip",bounds_command,mp_start_clip_code);
22531 @:clip_}{\&{clip} primitive@>
22532 mp_primitive(mp, "setbounds",bounds_command,mp_start_bounds_code);
22533 @:set_bounds_}{\&{setbounds} primitive@>
22534
22535 @ @<Cases of |print_cmd...@>=
22536 case bounds_command: 
22537   if ( m==mp_start_clip_code ) mp_print(mp, "clip");
22538   else mp_print(mp, "setbounds");
22539   break;
22540
22541 @ The following function parses the beginning of an \&{addto} or \&{clip}
22542 command: it expects a variable name followed by a token with |cur_cmd=sep|
22543 and then an expression.  The function returns the token list for the variable
22544 and stores the command modifier for the separator token in the global variable
22545 |last_add_type|.  We must be careful because this variable might get overwritten
22546 any time we call |get_x_next|.
22547
22548 @<Glob...@>=
22549 quarterword last_add_type;
22550   /* command modifier that identifies the last \&{addto} command */
22551
22552 @ @<Declare action procedures for use by |do_statement|@>=
22553 pointer mp_start_draw_cmd (MP mp,quarterword sep) ;
22554
22555 @ @c pointer mp_start_draw_cmd (MP mp,quarterword sep) {
22556   pointer lhv; /* variable to add to left */
22557   quarterword add_type=0; /* value to be returned in |last_add_type| */
22558   lhv=null;
22559   mp_get_x_next(mp); mp->var_flag=sep; mp_scan_primary(mp);
22560   if ( mp->cur_type!=mp_token_list ) {
22561     @<Abandon edges command because there's no variable@>;
22562   } else  { 
22563     lhv=mp->cur_exp; add_type=mp->cur_mod;
22564     mp->cur_type=mp_vacuous; mp_get_x_next(mp); mp_scan_expression(mp);
22565   }
22566   mp->last_add_type=add_type;
22567   return lhv;
22568 }
22569
22570 @ @<Abandon edges command because there's no variable@>=
22571 { exp_err("Not a suitable variable");
22572 @.Not a suitable variable@>
22573   help4("At this point I needed to see the name of a picture variable.")
22574     ("(Or perhaps you have indeed presented me with one; I might")
22575     ("have missed it, if it wasn't followed by the proper token.)")
22576     ("So I'll not change anything just now.");
22577   mp_put_get_flush_error(mp, 0);
22578 }
22579
22580 @ Here is an example of how to use |start_draw_cmd|.
22581
22582 @<Declare action procedures for use by |do_statement|@>=
22583 void mp_do_bounds (MP mp) ;
22584
22585 @ @c void mp_do_bounds (MP mp) {
22586   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22587   pointer p; /* for list manipulation */
22588   integer m; /* initial value of |cur_mod| */
22589   m=mp->cur_mod;
22590   lhv=mp_start_draw_cmd(mp, to_token);
22591   if ( lhv!=null ) {
22592     lhe=mp_find_edges_var(mp, lhv);
22593     if ( lhe==null ) {
22594       mp_flush_cur_exp(mp, 0);
22595     } else if ( mp->cur_type!=mp_path_type ) {
22596       exp_err("Improper `clip'");
22597 @.Improper `addto'@>
22598       help2("This expression should have specified a known path.")
22599         ("So I'll not change anything just now."); 
22600       mp_put_get_flush_error(mp, 0);
22601     } else if ( left_type(mp->cur_exp)==endpoint ) {
22602       @<Complain about a non-cycle@>;
22603     } else {
22604       @<Make |cur_exp| into a \&{setbounds} or clipping path and add it to |lhe|@>;
22605     }
22606   }
22607 }
22608
22609 @ @<Complain about a non-cycle@>=
22610 { print_err("Not a cycle");
22611 @.Not a cycle@>
22612   help2("That contour should have ended with `..cycle' or `&cycle'.")
22613     ("So I'll not change anything just now."); mp_put_get_error(mp);
22614 }
22615
22616 @ @<Make |cur_exp| into a \&{setbounds} or clipping path and add...@>=
22617 { p=mp_new_bounds_node(mp, mp->cur_exp,m);
22618   link(p)=link(dummy_loc(lhe));
22619   link(dummy_loc(lhe))=p;
22620   if ( obj_tail(lhe)==dummy_loc(lhe) ) obj_tail(lhe)=p;
22621   p=mp_get_node(mp, mp->gr_object_size[stop_type(m)]);
22622   type(p)=stop_type(m);
22623   link(obj_tail(lhe))=p;
22624   obj_tail(lhe)=p;
22625   mp_init_bbox(mp, lhe);
22626 }
22627
22628 @ The |do_add_to| procedure is a little like |do_clip| but there are a lot more
22629 cases to deal with.
22630
22631 @<Declare action procedures for use by |do_statement|@>=
22632 void mp_do_add_to (MP mp) ;
22633
22634 @ @c void mp_do_add_to (MP mp) {
22635   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22636   pointer p; /* the graphical object or list for |scan_with_list| to update */
22637   pointer e; /* an edge structure to be merged */
22638   quarterword add_type; /* |also_code|, |contour_code|, or |double_path_code| */
22639   lhv=mp_start_draw_cmd(mp, thing_to_add); add_type=mp->last_add_type;
22640   if ( lhv!=null ) {
22641     if ( add_type==also_code ) {
22642       @<Make sure the current expression is a suitable picture and set |e| and |p|
22643        appropriately@>;
22644     } else {
22645       @<Create a graphical object |p| based on |add_type| and the current
22646         expression@>;
22647     }
22648     mp_scan_with_list(mp, p);
22649     @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>;
22650   }
22651 }
22652
22653 @ Setting |p:=null| causes the $\langle$with list$\rangle$ to be ignored;
22654 setting |e:=null| prevents anything from being added to |lhe|.
22655
22656 @ @<Make sure the current expression is a suitable picture and set |e|...@>=
22657
22658   p=null; e=null;
22659   if ( mp->cur_type!=mp_picture_type ) {
22660     exp_err("Improper `addto'");
22661 @.Improper `addto'@>
22662     help2("This expression should have specified a known picture.")
22663       ("So I'll not change anything just now."); mp_put_get_flush_error(mp, 0);
22664   } else { 
22665     e=mp_private_edges(mp, mp->cur_exp); mp->cur_type=mp_vacuous;
22666     p=link(dummy_loc(e));
22667   }
22668 }
22669
22670 @ In this case |add_type<>also_code| so setting |p:=null| suppresses future
22671 attempts to add to the edge structure.
22672
22673 @<Create a graphical object |p| based on |add_type| and the current...@>=
22674 { e=null; p=null;
22675   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
22676   if ( mp->cur_type!=mp_path_type ) {
22677     exp_err("Improper `addto'");
22678 @.Improper `addto'@>
22679     help2("This expression should have specified a known path.")
22680       ("So I'll not change anything just now."); 
22681     mp_put_get_flush_error(mp, 0);
22682   } else if ( add_type==contour_code ) {
22683     if ( left_type(mp->cur_exp)==endpoint ) {
22684       @<Complain about a non-cycle@>;
22685     } else { 
22686       p=mp_new_fill_node(mp, mp->cur_exp);
22687       mp->cur_type=mp_vacuous;
22688     }
22689   } else { 
22690     p=mp_new_stroked_node(mp, mp->cur_exp);
22691     mp->cur_type=mp_vacuous;
22692   }
22693 }
22694
22695 @ @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>=
22696 lhe=mp_find_edges_var(mp, lhv);
22697 if ( lhe==null ) {
22698   if ( (e==null)&&(p!=null) ) e=mp_toss_gr_object(mp, p);
22699   if ( e!=null ) delete_edge_ref(e);
22700 } else if ( add_type==also_code ) {
22701   if ( e!=null ) {
22702     @<Merge |e| into |lhe| and delete |e|@>;
22703   } else { 
22704     do_nothing;
22705   }
22706 } else if ( p!=null ) {
22707   link(obj_tail(lhe))=p;
22708   obj_tail(lhe)=p;
22709   if ( add_type==double_path_code )
22710     if ( pen_p(p)==null ) 
22711       pen_p(p)=mp_get_pen_circle(mp, 0);
22712 }
22713
22714 @ @<Merge |e| into |lhe| and delete |e|@>=
22715 { if ( link(dummy_loc(e))!=null ) {
22716     link(obj_tail(lhe))=link(dummy_loc(e));
22717     obj_tail(lhe)=obj_tail(e);
22718     obj_tail(e)=dummy_loc(e);
22719     link(dummy_loc(e))=null;
22720     mp_flush_dash_list(mp, lhe);
22721   }
22722   mp_toss_edges(mp, e);
22723 }
22724
22725 @ @<Cases of |do_statement|...@>=
22726 case ship_out_command: mp_do_ship_out(mp); break;
22727
22728 @ @<Declare action procedures for use by |do_statement|@>=
22729 @<Declare the function called |tfm_check|@>;
22730 @<Declare the \ps\ output procedures@>;
22731 void mp_do_ship_out (MP mp) ;
22732
22733 @ @c void mp_do_ship_out (MP mp) {
22734   integer c; /* the character code */
22735   mp_get_x_next(mp); mp_scan_expression(mp);
22736   if ( mp->cur_type!=mp_picture_type ) {
22737     @<Complain that it's not a known picture@>;
22738   } else { 
22739     c=mp_round_unscaled(mp, mp->internal[char_code]) % 256;
22740     if ( c<0 ) c=c+256;
22741     @<Store the width information for character code~|c|@>;
22742     mp_ship_out(mp, mp->cur_exp);
22743     mp_flush_cur_exp(mp, 0);
22744   }
22745 }
22746
22747 @ @<Complain that it's not a known picture@>=
22748
22749   exp_err("Not a known picture");
22750   help1("I can only output known pictures.");
22751   mp_put_get_flush_error(mp, 0);
22752 }
22753
22754 @ The \&{everyjob} command simply assigns a nonzero value to the global variable
22755 |start_sym|.
22756
22757 @<Cases of |do_statement|...@>=
22758 case every_job_command: 
22759   mp_get_symbol(mp); mp->start_sym=mp->cur_sym; mp_get_x_next(mp);
22760   break;
22761
22762 @ @<Glob...@>=
22763 halfword start_sym; /* a symbolic token to insert at beginning of job */
22764
22765 @ @<Set init...@>=
22766 mp->start_sym=0;
22767
22768 @ Finally, we have only the ``message'' commands remaining.
22769
22770 @d message_code 0
22771 @d err_message_code 1
22772 @d err_help_code 2
22773 @d filename_template_code 3
22774 @d print_with_leading_zeroes(A)  g = mp->pool_ptr;
22775               mp_print_int(mp, (A)); g = mp->pool_ptr-g;
22776               if ( f>g ) {
22777                 mp->pool_ptr = mp->pool_ptr - g;
22778                 while ( f>g ) {
22779                   mp_print_char(mp, '0');
22780                   decr(f);
22781                   };
22782                 mp_print_int(mp, (A));
22783               };
22784               f = 0
22785
22786 @<Put each...@>=
22787 mp_primitive(mp, "message",message_command,message_code);
22788 @:message_}{\&{message} primitive@>
22789 mp_primitive(mp, "errmessage",message_command,err_message_code);
22790 @:err_message_}{\&{errmessage} primitive@>
22791 mp_primitive(mp, "errhelp",message_command,err_help_code);
22792 @:err_help_}{\&{errhelp} primitive@>
22793 mp_primitive(mp, "filenametemplate",message_command,filename_template_code);
22794 @:filename_template_}{\&{filenametemplate} primitive@>
22795
22796 @ @<Cases of |print_cmd...@>=
22797 case message_command: 
22798   if ( m<err_message_code ) mp_print(mp, "message");
22799   else if ( m==err_message_code ) mp_print(mp, "errmessage");
22800   else if ( m==filename_template_code ) mp_print(mp, "filenametemplate");
22801   else mp_print(mp, "errhelp");
22802   break;
22803
22804 @ @<Cases of |do_statement|...@>=
22805 case message_command: mp_do_message(mp); break;
22806
22807 @ @<Declare action procedures for use by |do_statement|@>=
22808 @<Declare a procedure called |no_string_err|@>;
22809 void mp_do_message (MP mp) ;
22810
22811
22812 @c void mp_do_message (MP mp) {
22813   int m; /* the type of message */
22814   m=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
22815   if ( mp->cur_type!=mp_string_type )
22816     mp_no_string_err(mp, "A message should be a known string expression.");
22817   else {
22818     switch (m) {
22819     case message_code: 
22820       mp_print_nl(mp, ""); mp_print_str(mp, mp->cur_exp);
22821       break;
22822     case err_message_code:
22823       @<Print string |cur_exp| as an error message@>;
22824       break;
22825     case err_help_code:
22826       @<Save string |cur_exp| as the |err_help|@>;
22827       break;
22828     case filename_template_code:
22829       @<Save the filename template@>;
22830       break;
22831     } /* there are no other cases */
22832   }
22833   mp_flush_cur_exp(mp, 0);
22834 }
22835
22836 @ @<Declare a procedure called |no_string_err|@>=
22837 void mp_no_string_err (MP mp,char *s) { 
22838    exp_err("Not a string");
22839 @.Not a string@>
22840   help1(s);
22841   mp_put_get_error(mp);
22842 }
22843
22844 @ The global variable |err_help| is zero when the user has most recently
22845 given an empty help string, or if none has ever been given.
22846
22847 @<Save string |cur_exp| as the |err_help|@>=
22848
22849   if ( mp->err_help!=0 ) delete_str_ref(mp->err_help);
22850   if ( length(mp->cur_exp)==0 ) mp->err_help=0;
22851   else  { mp->err_help=mp->cur_exp; add_str_ref(mp->err_help); }
22852 }
22853
22854 @ If \&{errmessage} occurs often in |mp_scroll_mode|, without user-defined
22855 \&{errhelp}, we don't want to give a long help message each time. So we
22856 give a verbose explanation only once.
22857
22858 @<Glob...@>=
22859 boolean long_help_seen; /* has the long \.{\\errmessage} help been used? */
22860
22861 @ @<Set init...@>=mp->long_help_seen=false;
22862
22863 @ @<Print string |cur_exp| as an error message@>=
22864
22865   print_err(""); mp_print_str(mp, mp->cur_exp);
22866   if ( mp->err_help!=0 ) {
22867     mp->use_err_help=true;
22868   } else if ( mp->long_help_seen ) { 
22869     help1("(That was another `errmessage'.)") ; 
22870   } else  { 
22871    if ( mp->interaction<mp_error_stop_mode ) mp->long_help_seen=true;
22872     help4("This error message was generated by an `errmessage'")
22873      ("command, so I can\'t give any explicit help.")
22874      ("Pretend that you're Miss Marple: Examine all clues,")
22875 @^Marple, Jane@>
22876      ("and deduce the truth by inspired guesses.");
22877   }
22878   mp_put_get_error(mp); mp->use_err_help=false;
22879 }
22880
22881 @ @<Cases of |do_statement|...@>=
22882 case write_command: mp_do_write(mp); break;
22883
22884 @ @<Declare action procedures for use by |do_statement|@>=
22885 void mp_do_write (MP mp) ;
22886
22887 @ @c void mp_do_write (MP mp) {
22888   str_number t; /* the line of text to be written */
22889   write_index n,n0; /* for searching |wr_fname| and |wr_file| arrays */
22890   int old_setting; /* for saving |selector| during output */
22891   mp_get_x_next(mp);
22892   mp_scan_expression(mp);
22893   if ( mp->cur_type!=mp_string_type ) {
22894     mp_no_string_err(mp, "The text to be written should be a known string expression");
22895   } else if ( mp->cur_cmd!=to_token ) { 
22896     print_err("Missing `to' clause");
22897     help1("A write command should end with `to <filename>'");
22898     mp_put_get_error(mp);
22899   } else { 
22900     t=mp->cur_exp; mp->cur_type=mp_vacuous;
22901     mp_get_x_next(mp);
22902     mp_scan_expression(mp);
22903     if ( mp->cur_type!=mp_string_type )
22904       mp_no_string_err(mp, "I can\'t write to that file name.  It isn't a known string");
22905     else {
22906       @<Write |t| to the file named by |cur_exp|@>;
22907     }
22908     delete_str_ref(t);
22909   }
22910   mp_flush_cur_exp(mp, 0);
22911 }
22912
22913 @ @<Write |t| to the file named by |cur_exp|@>=
22914
22915   @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if
22916     |cur_exp| must be inserted@>;
22917   if ( mp_str_vs_str(mp, t,mp->eof_line)==0 ) {
22918     @<Record the end of file on |wr_file[n]|@>;
22919   } else { 
22920     old_setting=mp->selector;
22921     mp->selector=n+write_file;
22922     mp_print_str(mp, t); mp_print_ln(mp);
22923     mp->selector = old_setting;
22924   }
22925 }
22926
22927 @ @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if...@>=
22928 {
22929   char *fn = str(mp->cur_exp);
22930   n=mp->write_files;
22931   n0=mp->write_files;
22932   while (mp_xstrcmp(fn,mp->wr_fname[n])!=0) { 
22933     if ( n==0 ) { /* bottom reached */
22934           if ( n0==mp->write_files ) {
22935         if ( mp->write_files<mp->max_write_files ) {
22936           incr(mp->write_files);
22937         } else {
22938           FILE **wr_file;
22939           char **wr_fname;
22940               write_index l,k;
22941           l = mp->max_write_files + (mp->max_write_files>>2);
22942           wr_file = xmalloc((l+1),sizeof(FILE *));
22943           wr_fname = xmalloc((l+1),sizeof(char *));
22944               for (k=0;k<=l;k++) {
22945             if (k<=mp->max_write_files) {
22946                   wr_file[k]=mp->wr_file[k]; 
22947               wr_fname[k]=mp->wr_fname[k];
22948             } else {
22949                   wr_file[k]=0; 
22950               wr_fname[k]=NULL;
22951             }
22952           }
22953               xfree(mp->wr_file); xfree(mp->wr_fname);
22954           mp->max_write_files = l;
22955           mp->wr_file = wr_file;
22956           mp->wr_fname = wr_fname;
22957         }
22958       }
22959       n=n0;
22960       mp_open_write_file(mp, fn ,n);
22961     } else { 
22962       decr(n);
22963           if ( mp->wr_fname[n]==NULL )  n0=n; 
22964     }
22965   }
22966 }
22967
22968 @ @<Record the end of file on |wr_file[n]|@>=
22969 { fclose(mp->wr_file[n]);
22970   xfree(mp->wr_fname[n]);
22971   mp->wr_fname[n]=NULL;
22972   if ( n==mp->write_files-1 ) mp->write_files=n;
22973 }
22974
22975
22976 @* \[42] Writing font metric data.
22977 \TeX\ gets its knowledge about fonts from font metric files, also called
22978 \.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
22979 but other programs know about them too. One of \MP's duties is to
22980 write \.{TFM} files so that the user's fonts can readily be
22981 applied to typesetting.
22982 @:TFM files}{\.{TFM} files@>
22983 @^font metric files@>
22984
22985 The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
22986 Since the number of bytes is always a multiple of~4, we could
22987 also regard the file as a sequence of 32-bit words, but \MP\ uses the
22988 byte interpretation. The format of \.{TFM} files was designed by
22989 Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
22990 @^Ramshaw, Lyle Harold@>
22991 of information in a compact but useful form.
22992
22993 @<Glob...@>=
22994 FILE * tfm_file; /* the font metric output goes here */
22995 char * metric_file_name; /* full name of the font metric file */
22996
22997 @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
22998 integers that give the lengths of the various subsequent portions
22999 of the file. These twelve integers are, in order:
23000 $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
23001 |lf|&length of the entire file, in words;\cr
23002 |lh|&length of the header data, in words;\cr
23003 |bc|&smallest character code in the font;\cr
23004 |ec|&largest character code in the font;\cr
23005 |nw|&number of words in the width table;\cr
23006 |nh|&number of words in the height table;\cr
23007 |nd|&number of words in the depth table;\cr
23008 |ni|&number of words in the italic correction table;\cr
23009 |nl|&number of words in the lig/kern table;\cr
23010 |nk|&number of words in the kern table;\cr
23011 |ne|&number of words in the extensible character table;\cr
23012 |np|&number of font parameter words.\cr}}$$
23013 They are all nonnegative and less than $2^{15}$. We must have |bc-1<=ec<=255|,
23014 |ne<=256|, and
23015 $$\hbox{|lf=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
23016 Note that a font may contain as many as 256 characters (if |bc=0| and |ec=255|),
23017 and as few as 0 characters (if |bc=ec+1|).
23018
23019 Incidentally, when two or more 8-bit bytes are combined to form an integer of
23020 16 or more bits, the most significant bytes appear first in the file.
23021 This is called BigEndian order.
23022 @^BigEndian order@>
23023
23024 @ The rest of the \.{TFM} file may be regarded as a sequence of ten data
23025 arrays.
23026
23027 The most important data type used here is a |fix_word|, which is
23028 a 32-bit representation of a binary fraction. A |fix_word| is a signed
23029 quantity, with the two's complement of the entire word used to represent
23030 negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
23031 binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
23032 the smallest is $-2048$. We will see below, however, that all but two of
23033 the |fix_word| values must lie between $-16$ and $+16$.
23034
23035 @ The first data array is a block of header information, which contains
23036 general facts about the font. The header must contain at least two words,
23037 |header[0]| and |header[1]|, whose meaning is explained below.  Additional
23038 header information of use to other software routines might also be
23039 included, and \MP\ will generate it if the \.{headerbyte} command occurs.
23040 For example, 16 more words of header information are in use at the Xerox
23041 Palo Alto Research Center; the first ten specify the character coding
23042 scheme used (e.g., `\.{XEROX TEXT}' or `\.{TEX MATHSY}'), the next five
23043 give the font family name (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
23044 last gives the ``face byte.''
23045
23046 \yskip\hang|header[0]| is a 32-bit check sum that \MP\ will copy into
23047 the \.{GF} output file. This helps ensure consistency between files,
23048 since \TeX\ records the check sums from the \.{TFM}'s it reads, and these
23049 should match the check sums on actual fonts that are used.  The actual
23050 relation between this check sum and the rest of the \.{TFM} file is not
23051 important; the check sum is simply an identification number with the
23052 property that incompatible fonts almost always have distinct check sums.
23053 @^check sum@>
23054
23055 \yskip\hang|header[1]| is a |fix_word| containing the design size of the
23056 font, in units of \TeX\ points. This number must be at least 1.0; it is
23057 fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
23058 font, i.e., a font that was designed to look best at a 10-point size,
23059 whatever that really means. When a \TeX\ user asks for a font `\.{at}
23060 $\delta$ \.{pt}', the effect is to override the design size and replace it
23061 by $\delta$, and to multiply the $x$ and~$y$ coordinates of the points in
23062 the font image by a factor of $\delta$ divided by the design size.  {\sl
23063 All other dimensions in the\/ \.{TFM} file are |fix_word|\kern-1pt\
23064 numbers in design-size units.} Thus, for example, the value of |param[6]|,
23065 which defines the \.{em} unit, is often the |fix_word| value $2^{20}=1.0$,
23066 since many fonts have a design size equal to one em.  The other dimensions
23067 must be less than 16 design-size units in absolute value; thus,
23068 |header[1]| and |param[1]| are the only |fix_word| entries in the whole
23069 \.{TFM} file whose first byte might be something besides 0 or 255.
23070
23071 @ Next comes the |char_info| array, which contains one |char_info_word|
23072 per character. Each word in this part of the file contains six fields
23073 packed into four bytes as follows.
23074
23075 \yskip\hang first byte: |width_index| (8 bits)\par
23076 \hang second byte: |height_index| (4 bits) times 16, plus |depth_index|
23077   (4~bits)\par
23078 \hang third byte: |italic_index| (6 bits) times 4, plus |tag|
23079   (2~bits)\par
23080 \hang fourth byte: |remainder| (8 bits)\par
23081 \yskip\noindent
23082 The actual width of a character is \\{width}|[width_index]|, in design-size
23083 units; this is a device for compressing information, since many characters
23084 have the same width. Since it is quite common for many characters
23085 to have the same height, depth, or italic correction, the \.{TFM} format
23086 imposes a limit of 16 different heights, 16 different depths, and
23087 64 different italic corrections.
23088
23089 Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
23090 \\{italic}[0]=0$ should always hold, so that an index of zero implies a
23091 value of zero.  The |width_index| should never be zero unless the
23092 character does not exist in the font, since a character is valid if and
23093 only if it lies between |bc| and |ec| and has a nonzero |width_index|.
23094
23095 @ The |tag| field in a |char_info_word| has four values that explain how to
23096 interpret the |remainder| field.
23097
23098 \yskip\hang|tag=0| (|no_tag|) means that |remainder| is unused.\par
23099 \hang|tag=1| (|lig_tag|) means that this character has a ligature/kerning
23100 program starting at location |remainder| in the |lig_kern| array.\par
23101 \hang|tag=2| (|list_tag|) means that this character is part of a chain of
23102 characters of ascending sizes, and not the largest in the chain.  The
23103 |remainder| field gives the character code of the next larger character.\par
23104 \hang|tag=3| (|ext_tag|) means that this character code represents an
23105 extensible character, i.e., a character that is built up of smaller pieces
23106 so that it can be made arbitrarily large. The pieces are specified in
23107 |exten[remainder]|.\par
23108 \yskip\noindent
23109 Characters with |tag=2| and |tag=3| are treated as characters with |tag=0|
23110 unless they are used in special circumstances in math formulas. For example,
23111 \TeX's \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
23112 operation looks for both |list_tag| and |ext_tag|.
23113
23114 @d no_tag 0 /* vanilla character */
23115 @d lig_tag 1 /* character has a ligature/kerning program */
23116 @d list_tag 2 /* character has a successor in a charlist */
23117 @d ext_tag 3 /* character is extensible */
23118
23119 @ The |lig_kern| array contains instructions in a simple programming language
23120 that explains what to do for special letter pairs. Each word in this array is a
23121 |lig_kern_command| of four bytes.
23122
23123 \yskip\hang first byte: |skip_byte|, indicates that this is the final program
23124   step if the byte is 128 or more, otherwise the next step is obtained by
23125   skipping this number of intervening steps.\par
23126 \hang second byte: |next_char|, ``if |next_char| follows the current character,
23127   then perform the operation and stop, otherwise continue.''\par
23128 \hang third byte: |op_byte|, indicates a ligature step if less than~128,
23129   a kern step otherwise.\par
23130 \hang fourth byte: |remainder|.\par
23131 \yskip\noindent
23132 In a kern step, an
23133 additional space equal to |kern[256*(op_byte-128)+remainder]| is inserted
23134 between the current character and |next_char|. This amount is
23135 often negative, so that the characters are brought closer together
23136 by kerning; but it might be positive.
23137
23138 There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
23139 $0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
23140 |remainder| is inserted between the current character and |next_char|;
23141 then the current character is deleted if $b=0$, and |next_char| is
23142 deleted if $c=0$; then we pass over $a$~characters to reach the next
23143 current character (which may have a ligature/kerning program of its own).
23144
23145 If the very first instruction of the |lig_kern| array has |skip_byte=255|,
23146 the |next_char| byte is the so-called right boundary character of this font;
23147 the value of |next_char| need not lie between |bc| and~|ec|.
23148 If the very last instruction of the |lig_kern| array has |skip_byte=255|,
23149 there is a special ligature/kerning program for a left boundary character,
23150 beginning at location |256*op_byte+remainder|.
23151 The interpretation is that \TeX\ puts implicit boundary characters
23152 before and after each consecutive string of characters from the same font.
23153 These implicit characters do not appear in the output, but they can affect
23154 ligatures and kerning.
23155
23156 If the very first instruction of a character's |lig_kern| program has
23157 |skip_byte>128|, the program actually begins in location
23158 |256*op_byte+remainder|. This feature allows access to large |lig_kern|
23159 arrays, because the first instruction must otherwise
23160 appear in a location |<=255|.
23161
23162 Any instruction with |skip_byte>128| in the |lig_kern| array must satisfy
23163 the condition
23164 $$\hbox{|256*op_byte+remainder<nl|.}$$
23165 If such an instruction is encountered during
23166 normal program execution, it denotes an unconditional halt; no ligature
23167 command is performed.
23168
23169 @d stop_flag (128)
23170   /* value indicating `\.{STOP}' in a lig/kern program */
23171 @d kern_flag (128) /* op code for a kern step */
23172 @d skip_byte(A) mp->lig_kern[(A)].b0
23173 @d next_char(A) mp->lig_kern[(A)].b1
23174 @d op_byte(A) mp->lig_kern[(A)].b2
23175 @d rem_byte(A) mp->lig_kern[(A)].b3
23176
23177 @ Extensible characters are specified by an |extensible_recipe|, which
23178 consists of four bytes called |top|, |mid|, |bot|, and |rep| (in this
23179 order). These bytes are the character codes of individual pieces used to
23180 build up a large symbol.  If |top|, |mid|, or |bot| are zero, they are not
23181 present in the built-up result. For example, an extensible vertical line is
23182 like an extensible bracket, except that the top and bottom pieces are missing.
23183
23184 Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
23185 if the piece isn't present. Then the extensible characters have the form
23186 $TR^kMR^kB$ from top to bottom, for some |k>=0|, unless $M$ is absent;
23187 in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
23188 The width of the extensible character is the width of $R$; and the
23189 height-plus-depth is the sum of the individual height-plus-depths of the
23190 components used, since the pieces are butted together in a vertical list.
23191
23192 @d ext_top(A) mp->exten[(A)].b0 /* |top| piece in a recipe */
23193 @d ext_mid(A) mp->exten[(A)].b1 /* |mid| piece in a recipe */
23194 @d ext_bot(A) mp->exten[(A)].b2 /* |bot| piece in a recipe */
23195 @d ext_rep(A) mp->exten[(A)].b3 /* |rep| piece in a recipe */
23196
23197 @ The final portion of a \.{TFM} file is the |param| array, which is another
23198 sequence of |fix_word| values.
23199
23200 \yskip\hang|param[1]=slant| is the amount of italic slant, which is used
23201 to help position accents. For example, |slant=.25| means that when you go
23202 up one unit, you also go .25 units to the right. The |slant| is a pure
23203 number; it is the only |fix_word| other than the design size itself that is
23204 not scaled by the design size.
23205
23206 \hang|param[2]=space| is the normal spacing between words in text.
23207 Note that character 040 in the font need not have anything to do with
23208 blank spaces.
23209
23210 \hang|param[3]=space_stretch| is the amount of glue stretching between words.
23211
23212 \hang|param[4]=space_shrink| is the amount of glue shrinking between words.
23213
23214 \hang|param[5]=x_height| is the size of one ex in the font; it is also
23215 the height of letters for which accents don't have to be raised or lowered.
23216
23217 \hang|param[6]=quad| is the size of one em in the font.
23218
23219 \hang|param[7]=extra_space| is the amount added to |param[2]| at the
23220 ends of sentences.
23221
23222 \yskip\noindent
23223 If fewer than seven parameters are present, \TeX\ sets the missing parameters
23224 to zero.
23225
23226 @d slant_code 1
23227 @d space_code 2
23228 @d space_stretch_code 3
23229 @d space_shrink_code 4
23230 @d x_height_code 5
23231 @d quad_code 6
23232 @d extra_space_code 7
23233
23234 @ So that is what \.{TFM} files hold. One of \MP's duties is to output such
23235 information, and it does this all at once at the end of a job.
23236 In order to prepare for such frenetic activity, it squirrels away the
23237 necessary facts in various arrays as information becomes available.
23238
23239 Character dimensions (\&{charwd}, \&{charht}, \&{chardp}, and \&{charic})
23240 are stored respectively in |tfm_width|, |tfm_height|, |tfm_depth|, and
23241 |tfm_ital_corr|. Other information about a character (e.g., about
23242 its ligatures or successors) is accessible via the |char_tag| and
23243 |char_remainder| arrays. Other information about the font as a whole
23244 is kept in additional arrays called |header_byte|, |lig_kern|,
23245 |kern|, |exten|, and |param|.
23246
23247 @d max_tfm_int 32510
23248 @d undefined_label max_tfm_int /* an undefined local label */
23249
23250 @<Glob...@>=
23251 #define TFM_ITEMS 257
23252 eight_bits bc;
23253 eight_bits ec; /* smallest and largest character codes shipped out */
23254 scaled tfm_width[TFM_ITEMS]; /* \&{charwd} values */
23255 scaled tfm_height[TFM_ITEMS]; /* \&{charht} values */
23256 scaled tfm_depth[TFM_ITEMS]; /* \&{chardp} values */
23257 scaled tfm_ital_corr[TFM_ITEMS]; /* \&{charic} values */
23258 boolean char_exists[TFM_ITEMS]; /* has this code been shipped out? */
23259 int char_tag[TFM_ITEMS]; /* |remainder| category */
23260 int char_remainder[TFM_ITEMS]; /* the |remainder| byte */
23261 char *header_byte; /* bytes of the \.{TFM} header */
23262 int header_last; /* last initialized \.{TFM} header byte */
23263 int header_size; /* size of the \.{TFM} header */
23264 four_quarters *lig_kern; /* the ligature/kern table */
23265 short nl; /* the number of ligature/kern steps so far */
23266 scaled *kern; /* distinct kerning amounts */
23267 short nk; /* the number of distinct kerns so far */
23268 four_quarters exten[TFM_ITEMS]; /* extensible character recipes */
23269 short ne; /* the number of extensible characters so far */
23270 scaled *param; /* \&{fontinfo} parameters */
23271 short np; /* the largest \&{fontinfo} parameter specified so far */
23272 short nw;short nh;short nd;short ni; /* sizes of \.{TFM} subtables */
23273 short skip_table[TFM_ITEMS]; /* local label status */
23274 boolean lk_started; /* has there been a lig/kern step in this command yet? */
23275 integer bchar; /* right boundary character */
23276 short bch_label; /* left boundary starting location */
23277 short ll;short lll; /* registers used for lig/kern processing */
23278 short label_loc[257]; /* lig/kern starting addresses */
23279 eight_bits label_char[257]; /* characters for |label_loc| */
23280 short label_ptr; /* highest position occupied in |label_loc| */
23281
23282 @ @<Allocate or initialize ...@>=
23283 mp->header_last = 0; mp->header_size = 128; /* just for init */
23284 mp->header_byte = xmalloc(mp->header_size, sizeof(char));
23285 mp->lig_kern = NULL; /* allocated when needed */
23286 mp->kern = NULL; /* allocated when needed */ 
23287 mp->param = NULL; /* allocated when needed */
23288
23289 @ @<Dealloc variables@>=
23290 xfree(mp->header_byte);
23291 xfree(mp->lig_kern);
23292 xfree(mp->kern);
23293 xfree(mp->param);
23294
23295 @ @<Set init...@>=
23296 for (k=0;k<= 255;k++ ) {
23297   mp->tfm_width[k]=0; mp->tfm_height[k]=0; mp->tfm_depth[k]=0; mp->tfm_ital_corr[k]=0;
23298   mp->char_exists[k]=false; mp->char_tag[k]=no_tag; mp->char_remainder[k]=0;
23299   mp->skip_table[k]=undefined_label;
23300 };
23301 memset(mp->header_byte,0,mp->header_size);
23302 mp->bc=255; mp->ec=0; mp->nl=0; mp->nk=0; mp->ne=0; mp->np=0;
23303 mp->internal[boundary_char]=-unity;
23304 mp->bch_label=undefined_label;
23305 mp->label_loc[0]=-1; mp->label_ptr=0;
23306
23307 @ @<Declarations@>=
23308 scaled mp_tfm_check (MP mp,small_number m) ;
23309
23310 @ @<Declare the function called |tfm_check|@>=
23311 scaled mp_tfm_check (MP mp,small_number m) {
23312   if ( abs(mp->internal[m])>=fraction_half ) {
23313     print_err("Enormous "); mp_print(mp, mp->int_name[m]);
23314 @.Enormous charwd...@>
23315 @.Enormous chardp...@>
23316 @.Enormous charht...@>
23317 @.Enormous charic...@>
23318 @.Enormous designsize...@>
23319     mp_print(mp, " has been reduced");
23320     help1("Font metric dimensions must be less than 2048pt.");
23321     mp_put_get_error(mp);
23322     if ( mp->internal[m]>0 ) return (fraction_half-1);
23323     else return (1-fraction_half);
23324   } else {
23325     return mp->internal[m];
23326   }
23327 }
23328
23329 @ @<Store the width information for character code~|c|@>=
23330 if ( c<mp->bc ) mp->bc=c;
23331 if ( c>mp->ec ) mp->ec=c;
23332 mp->char_exists[c]=true;
23333 mp->tfm_width[c]=mp_tfm_check(mp, char_wd);
23334 mp->tfm_height[c]=mp_tfm_check(mp, char_ht);
23335 mp->tfm_depth[c]=mp_tfm_check(mp, char_dp);
23336 mp->tfm_ital_corr[c]=mp_tfm_check(mp, char_ic)
23337
23338 @ Now let's consider \MP's special \.{TFM}-oriented commands.
23339
23340 @<Cases of |do_statement|...@>=
23341 case tfm_command: mp_do_tfm_command(mp); break;
23342
23343 @ @d char_list_code 0
23344 @d lig_table_code 1
23345 @d extensible_code 2
23346 @d header_byte_code 3
23347 @d font_dimen_code 4
23348
23349 @<Put each...@>=
23350 mp_primitive(mp, "charlist",tfm_command,char_list_code);
23351 @:char_list_}{\&{charlist} primitive@>
23352 mp_primitive(mp, "ligtable",tfm_command,lig_table_code);
23353 @:lig_table_}{\&{ligtable} primitive@>
23354 mp_primitive(mp, "extensible",tfm_command,extensible_code);
23355 @:extensible_}{\&{extensible} primitive@>
23356 mp_primitive(mp, "headerbyte",tfm_command,header_byte_code);
23357 @:header_byte_}{\&{headerbyte} primitive@>
23358 mp_primitive(mp, "fontdimen",tfm_command,font_dimen_code);
23359 @:font_dimen_}{\&{fontdimen} primitive@>
23360
23361 @ @<Cases of |print_cmd...@>=
23362 case tfm_command: 
23363   switch (m) {
23364   case char_list_code:mp_print(mp, "charlist"); break;
23365   case lig_table_code:mp_print(mp, "ligtable"); break;
23366   case extensible_code:mp_print(mp, "extensible"); break;
23367   case header_byte_code:mp_print(mp, "headerbyte"); break;
23368   default: mp_print(mp, "fontdimen"); break;
23369   }
23370   break;
23371
23372 @ @<Declare action procedures for use by |do_statement|@>=
23373 eight_bits mp_get_code (MP mp) ;
23374
23375 @ @c eight_bits mp_get_code (MP mp) { /* scans a character code value */
23376   integer c; /* the code value found */
23377   mp_get_x_next(mp); mp_scan_expression(mp);
23378   if ( mp->cur_type==mp_known ) { 
23379     c=mp_round_unscaled(mp, mp->cur_exp);
23380     if ( c>=0 ) if ( c<256 ) return c;
23381   } else if ( mp->cur_type==mp_string_type ) {
23382     if ( length(mp->cur_exp)==1 )  { 
23383       c=mp->str_pool[mp->str_start[mp->cur_exp]];
23384       return c;
23385     }
23386   }
23387   exp_err("Invalid code has been replaced by 0");
23388 @.Invalid code...@>
23389   help2("I was looking for a number between 0 and 255, or for a")
23390        ("string of length 1. Didn't find it; will use 0 instead.");
23391   mp_put_get_flush_error(mp, 0); c=0;
23392   return c;
23393 };
23394
23395 @ @<Declare action procedures for use by |do_statement|@>=
23396 void mp_set_tag (MP mp,halfword c, small_number t, halfword r) ;
23397
23398 @ @c void mp_set_tag (MP mp,halfword c, small_number t, halfword r) { 
23399   if ( mp->char_tag[c]==no_tag ) {
23400     mp->char_tag[c]=t; mp->char_remainder[c]=r;
23401     if ( t==lig_tag ){ 
23402       incr(mp->label_ptr); mp->label_loc[mp->label_ptr]=r; 
23403       mp->label_char[mp->label_ptr]=c;
23404     }
23405   } else {
23406     @<Complain about a character tag conflict@>;
23407   }
23408 }
23409
23410 @ @<Complain about a character tag conflict@>=
23411
23412   print_err("Character ");
23413   if ( (c>' ')&&(c<127) ) mp_print_char(mp,c);
23414   else if ( c==256 ) mp_print(mp, "||");
23415   else  { mp_print(mp, "code "); mp_print_int(mp, c); };
23416   mp_print(mp, " is already ");
23417 @.Character c is already...@>
23418   switch (mp->char_tag[c]) {
23419   case lig_tag: mp_print(mp, "in a ligtable"); break;
23420   case list_tag: mp_print(mp, "in a charlist"); break;
23421   case ext_tag: mp_print(mp, "extensible"); break;
23422   } /* there are no other cases */
23423   help2("It's not legal to label a character more than once.")
23424     ("So I'll not change anything just now.");
23425   mp_put_get_error(mp); 
23426 }
23427
23428 @ @<Declare action procedures for use by |do_statement|@>=
23429 void mp_do_tfm_command (MP mp) ;
23430
23431 @ @c void mp_do_tfm_command (MP mp) {
23432   int c,cc; /* character codes */
23433   int k; /* index into the |kern| array */
23434   int j; /* index into |header_byte| or |param| */
23435   switch (mp->cur_mod) {
23436   case char_list_code: 
23437     c=mp_get_code(mp);
23438      /* we will store a list of character successors */
23439     while ( mp->cur_cmd==colon )   { 
23440       cc=mp_get_code(mp); mp_set_tag(mp, c,list_tag,cc); c=cc;
23441     };
23442     break;
23443   case lig_table_code: 
23444     if (mp->lig_kern==NULL) 
23445        mp->lig_kern = xmalloc((max_tfm_int+1),sizeof(four_quarters));
23446     if (mp->kern==NULL) 
23447        mp->kern = xmalloc((max_tfm_int+1),sizeof(scaled));
23448     @<Store a list of ligature/kern steps@>;
23449     break;
23450   case extensible_code: 
23451     @<Define an extensible recipe@>;
23452     break;
23453   case header_byte_code: 
23454   case font_dimen_code: 
23455     c=mp->cur_mod; mp_get_x_next(mp);
23456     mp_scan_expression(mp);
23457     if ( (mp->cur_type!=mp_known)||(mp->cur_exp<half_unit) ) {
23458       exp_err("Improper location");
23459 @.Improper location@>
23460       help2("I was looking for a known, positive number.")
23461        ("For safety's sake I'll ignore the present command.");
23462       mp_put_get_error(mp);
23463     } else  { 
23464       j=mp_round_unscaled(mp, mp->cur_exp);
23465       if ( mp->cur_cmd!=colon ) {
23466         mp_missing_err(mp, ":");
23467 @.Missing `:'@>
23468         help1("A colon should follow a headerbyte or fontinfo location.");
23469         mp_back_error(mp);
23470       }
23471       if ( c==header_byte_code ) { 
23472         @<Store a list of header bytes@>;
23473       } else {     
23474         if (mp->param==NULL) 
23475           mp->param = xmalloc((max_tfm_int+1),sizeof(scaled));
23476         @<Store a list of font dimensions@>;
23477       }
23478     }
23479     break;
23480   } /* there are no other cases */
23481 };
23482
23483 @ @<Store a list of ligature/kern steps@>=
23484
23485   mp->lk_started=false;
23486 CONTINUE: 
23487   mp_get_x_next(mp);
23488   if ((mp->cur_cmd==skip_to)&& mp->lk_started )
23489     @<Process a |skip_to| command and |goto done|@>;
23490   if ( mp->cur_cmd==bchar_label ) { c=256; mp->cur_cmd=colon; }
23491   else { mp_back_input(mp); c=mp_get_code(mp); };
23492   if ((mp->cur_cmd==colon)||(mp->cur_cmd==double_colon)) {
23493     @<Record a label in a lig/kern subprogram and |goto continue|@>;
23494   }
23495   if ( mp->cur_cmd==lig_kern_token ) { 
23496     @<Compile a ligature/kern command@>; 
23497   } else  { 
23498     print_err("Illegal ligtable step");
23499 @.Illegal ligtable step@>
23500     help1("I was looking for `=:' or `kern' here.");
23501     mp_back_error(mp); next_char(mp->nl)=qi(0); 
23502     op_byte(mp->nl)=qi(0); rem_byte(mp->nl)=qi(0);
23503     skip_byte(mp->nl)=stop_flag+1; /* this specifies an unconditional stop */
23504   }
23505   if ( mp->nl==max_tfm_int) mp_fatal_error(mp, "ligtable too large");
23506   incr(mp->nl);
23507   if ( mp->cur_cmd==comma ) goto CONTINUE;
23508   if ( skip_byte(mp->nl-1)<stop_flag ) skip_byte(mp->nl-1)=stop_flag;
23509 }
23510 DONE:
23511
23512 @ @<Put each...@>=
23513 mp_primitive(mp, "=:",lig_kern_token,0);
23514 @:=:_}{\.{=:} primitive@>
23515 mp_primitive(mp, "=:|",lig_kern_token,1);
23516 @:=:/_}{\.{=:\char'174} primitive@>
23517 mp_primitive(mp, "=:|>",lig_kern_token,5);
23518 @:=:/>_}{\.{=:\char'174>} primitive@>
23519 mp_primitive(mp, "|=:",lig_kern_token,2);
23520 @:=:/_}{\.{\char'174=:} primitive@>
23521 mp_primitive(mp, "|=:>",lig_kern_token,6);
23522 @:=:/>_}{\.{\char'174=:>} primitive@>
23523 mp_primitive(mp, "|=:|",lig_kern_token,3);
23524 @:=:/_}{\.{\char'174=:\char'174} primitive@>
23525 mp_primitive(mp, "|=:|>",lig_kern_token,7);
23526 @:=:/>_}{\.{\char'174=:\char'174>} primitive@>
23527 mp_primitive(mp, "|=:|>>",lig_kern_token,11);
23528 @:=:/>_}{\.{\char'174=:\char'174>>} primitive@>
23529 mp_primitive(mp, "kern",lig_kern_token,128);
23530 @:kern_}{\&{kern} primitive@>
23531
23532 @ @<Cases of |print_cmd...@>=
23533 case lig_kern_token: 
23534   switch (m) {
23535   case 0:mp_print(mp, "=:"); break;
23536   case 1:mp_print(mp, "=:|"); break;
23537   case 2:mp_print(mp, "|=:"); break;
23538   case 3:mp_print(mp, "|=:|"); break;
23539   case 5:mp_print(mp, "=:|>"); break;
23540   case 6:mp_print(mp, "|=:>"); break;
23541   case 7:mp_print(mp, "|=:|>"); break;
23542   case 11:mp_print(mp, "|=:|>>"); break;
23543   default: mp_print(mp, "kern"); break;
23544   }
23545   break;
23546
23547 @ Local labels are implemented by maintaining the |skip_table| array,
23548 where |skip_table[c]| is either |undefined_label| or the address of the
23549 most recent lig/kern instruction that skips to local label~|c|. In the
23550 latter case, the |skip_byte| in that instruction will (temporarily)
23551 be zero if there were no prior skips to this label, or it will be the
23552 distance to the prior skip.
23553
23554 We may need to cancel skips that span more than 127 lig/kern steps.
23555
23556 @d cancel_skips(A) mp->ll=(A);
23557   do {  
23558     mp->lll=qo(skip_byte(mp->ll)); 
23559     skip_byte(mp->ll)=stop_flag; mp->ll=mp->ll-mp->lll;
23560   } while (mp->lll!=0)
23561 @d skip_error(A) { print_err("Too far to skip");
23562 @.Too far to skip@>
23563   help1("At most 127 lig/kern steps can separate skipto1 from 1::.");
23564   mp_error(mp); cancel_skips((A));
23565   }
23566
23567 @<Process a |skip_to| command and |goto done|@>=
23568
23569   c=mp_get_code(mp);
23570   if ( mp->nl-mp->skip_table[c]>128 ) { /* |skip_table[c]<<nl<=undefined_label| */
23571     skip_error(mp->skip_table[c]); mp->skip_table[c]=undefined_label;
23572   }
23573   if ( mp->skip_table[c]==undefined_label ) skip_byte(mp->nl-1)=qi(0);
23574   else skip_byte(mp->nl-1)=qi(mp->nl-mp->skip_table[c]-1);
23575   mp->skip_table[c]=mp->nl-1; goto DONE;
23576 }
23577
23578 @ @<Record a label in a lig/kern subprogram and |goto continue|@>=
23579
23580   if ( mp->cur_cmd==colon ) {
23581     if ( c==256 ) mp->bch_label=mp->nl;
23582     else mp_set_tag(mp, c,lig_tag,mp->nl);
23583   } else if ( mp->skip_table[c]<undefined_label ) {
23584     mp->ll=mp->skip_table[c]; mp->skip_table[c]=undefined_label;
23585     do {  
23586       mp->lll=qo(skip_byte(mp->ll));
23587       if ( mp->nl-mp->ll>128 ) {
23588         skip_error(mp->ll); goto CONTINUE;
23589       }
23590       skip_byte(mp->ll)=qi(mp->nl-mp->ll-1); mp->ll=mp->ll-mp->lll;
23591     } while (mp->lll!=0);
23592   }
23593   goto CONTINUE;
23594 }
23595
23596 @ @<Compile a ligature/kern...@>=
23597
23598   next_char(mp->nl)=qi(c); skip_byte(mp->nl)=qi(0);
23599   if ( mp->cur_mod<128 ) { /* ligature op */
23600     op_byte(mp->nl)=qi(mp->cur_mod); rem_byte(mp->nl)=qi(mp_get_code(mp));
23601   } else { 
23602     mp_get_x_next(mp); mp_scan_expression(mp);
23603     if ( mp->cur_type!=mp_known ) {
23604       exp_err("Improper kern");
23605 @.Improper kern@>
23606       help2("The amount of kern should be a known numeric value.")
23607         ("I'm zeroing this one. Proceed, with fingers crossed.");
23608       mp_put_get_flush_error(mp, 0);
23609     }
23610     mp->kern[mp->nk]=mp->cur_exp;
23611     k=0; 
23612     while ( mp->kern[k]!=mp->cur_exp ) incr(k);
23613     if ( k==mp->nk ) {
23614       if ( mp->nk==max_tfm_int ) mp_fatal_error(mp, "too many TFM kerns");
23615       incr(mp->nk);
23616     }
23617     op_byte(mp->nl)=kern_flag+(k / 256);
23618     rem_byte(mp->nl)=qi((k % 256));
23619   }
23620   mp->lk_started=true;
23621 }
23622
23623 @ @d missing_extensible_punctuation(A) 
23624   { mp_missing_err(mp, (A));
23625 @.Missing `\char`\#'@>
23626   help1("I'm processing `extensible c: t,m,b,r'."); mp_back_error(mp);
23627   }
23628
23629 @<Define an extensible recipe@>=
23630
23631   if ( mp->ne==256 ) mp_fatal_error(mp, "too many extensible recipies");
23632   c=mp_get_code(mp); mp_set_tag(mp, c,ext_tag,mp->ne);
23633   if ( mp->cur_cmd!=colon ) missing_extensible_punctuation(":");
23634   ext_top(mp->ne)=qi(mp_get_code(mp));
23635   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23636   ext_mid(mp->ne)=qi(mp_get_code(mp));
23637   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23638   ext_bot(mp->ne)=qi(mp_get_code(mp));
23639   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23640   ext_rep(mp->ne)=qi(mp_get_code(mp));
23641   incr(mp->ne);
23642 }
23643
23644 @ The header could contain ASCII zeroes, so can't use |strdup|.
23645
23646 @<Store a list of header bytes@>=
23647 do {  
23648   if ( j>=mp->header_size ) {
23649     int l = mp->header_size + (mp->header_size >> 2);
23650     char *t = xmalloc(l,sizeof(char));
23651     memset(t,0,l); 
23652     memcpy(t,mp->header_byte,mp->header_size);
23653     xfree (mp->header_byte);
23654     mp->header_byte = t;
23655     mp->header_size = l;
23656   }
23657   mp->header_byte[j]=mp_get_code(mp); 
23658   incr(j); incr(mp->header_last);
23659 } while (mp->cur_cmd==comma)
23660
23661 @ @<Store a list of font dimensions@>=
23662 do {  
23663   if ( j>max_tfm_int ) mp_fatal_error(mp, "too many fontdimens");
23664   while ( j>mp->np ) { incr(mp->np); mp->param[mp->np]=0; };
23665   mp_get_x_next(mp); mp_scan_expression(mp);
23666   if ( mp->cur_type!=mp_known ){ 
23667     exp_err("Improper font parameter");
23668 @.Improper font parameter@>
23669     help1("I'm zeroing this one. Proceed, with fingers crossed.");
23670     mp_put_get_flush_error(mp, 0);
23671   }
23672   mp->param[j]=mp->cur_exp; incr(j);
23673 } while (mp->cur_cmd==comma)
23674
23675 @ OK: We've stored all the data that is needed for the \.{TFM} file.
23676 All that remains is to output it in the correct format.
23677
23678 An interesting problem needs to be solved in this connection, because
23679 the \.{TFM} format allows at most 256~widths, 16~heights, 16~depths,
23680 and 64~italic corrections. If the data has more distinct values than
23681 this, we want to meet the necessary restrictions by perturbing the
23682 given values as little as possible.
23683
23684 \MP\ solves this problem in two steps. First the values of a given
23685 kind (widths, heights, depths, or italic corrections) are sorted;
23686 then the list of sorted values is perturbed, if necessary.
23687
23688 The sorting operation is facilitated by having a special node of
23689 essentially infinite |value| at the end of the current list.
23690
23691 @<Initialize table entries...@>=
23692 value(inf_val)=fraction_four;
23693
23694 @ Straight linear insertion is good enough for sorting, since the lists
23695 are usually not terribly long. As we work on the data, the current list
23696 will start at |link(temp_head)| and end at |inf_val|; the nodes in this
23697 list will be in increasing order of their |value| fields.
23698
23699 Given such a list, the |sort_in| function takes a value and returns a pointer
23700 to where that value can be found in the list. The value is inserted in
23701 the proper place, if necessary.
23702
23703 At the time we need to do these operations, most of \MP's work has been
23704 completed, so we will have plenty of memory to play with. The value nodes
23705 that are allocated for sorting will never be returned to free storage.
23706
23707 @d clear_the_list link(temp_head)=inf_val
23708
23709 @c pointer mp_sort_in (MP mp,scaled v) {
23710   pointer p,q,r; /* list manipulation registers */
23711   p=temp_head;
23712   while (1) { 
23713     q=link(p);
23714     if ( v<=value(q) ) break;
23715     p=q;
23716   }
23717   if ( v<value(q) ) {
23718     r=mp_get_node(mp, value_node_size); value(r)=v; link(r)=q; link(p)=r;
23719   }
23720   return link(p);
23721 }
23722
23723 @ Now we come to the interesting part, where we reduce the list if necessary
23724 until it has the required size. The |min_cover| routine is basic to this
23725 process; it computes the minimum number~|m| such that the values of the
23726 current sorted list can be covered by |m|~intervals of width~|d|. It
23727 also sets the global value |perturbation| to the smallest value $d'>d$
23728 such that the covering found by this algorithm would be different.
23729
23730 In particular, |min_cover(0)| returns the number of distinct values in the
23731 current list and sets |perturbation| to the minimum distance between
23732 adjacent values.
23733
23734 @c integer mp_min_cover (MP mp,scaled d) {
23735   pointer p; /* runs through the current list */
23736   scaled l; /* the least element covered by the current interval */
23737   integer m; /* lower bound on the size of the minimum cover */
23738   m=0; p=link(temp_head); mp->perturbation=el_gordo;
23739   while ( p!=inf_val ){ 
23740     incr(m); l=value(p);
23741     do {  p=link(p); } while (value(p)<=l+d);
23742     if ( value(p)-l<mp->perturbation ) 
23743       mp->perturbation=value(p)-l;
23744   }
23745   return m;
23746 }
23747
23748 @ @<Glob...@>=
23749 scaled perturbation; /* quantity related to \.{TFM} rounding */
23750 integer excess; /* the list is this much too long */
23751
23752 @ The smallest |d| such that a given list can be covered with |m| intervals
23753 is determined by the |threshold| routine, which is sort of an inverse
23754 to |min_cover|. The idea is to increase the interval size rapidly until
23755 finding the range, then to go sequentially until the exact borderline has
23756 been discovered.
23757
23758 @c scaled mp_threshold (MP mp,integer m) {
23759   scaled d; /* lower bound on the smallest interval size */
23760   mp->excess=mp_min_cover(mp, 0)-m;
23761   if ( mp->excess<=0 ) {
23762     return 0;
23763   } else  { 
23764     do {  
23765       d=mp->perturbation;
23766     } while (mp_min_cover(mp, d+d)>m);
23767     while ( mp_min_cover(mp, d)>m ) 
23768       d=mp->perturbation;
23769     return d;
23770   }
23771 }
23772
23773 @ The |skimp| procedure reduces the current list to at most |m| entries,
23774 by changing values if necessary. It also sets |info(p):=k| if |value(p)|
23775 is the |k|th distinct value on the resulting list, and it sets
23776 |perturbation| to the maximum amount by which a |value| field has
23777 been changed. The size of the resulting list is returned as the
23778 value of |skimp|.
23779
23780 @c integer mp_skimp (MP mp,integer m) {
23781   scaled d; /* the size of intervals being coalesced */
23782   pointer p,q,r; /* list manipulation registers */
23783   scaled l; /* the least value in the current interval */
23784   scaled v; /* a compromise value */
23785   d=mp_threshold(mp, m); mp->perturbation=0;
23786   q=temp_head; m=0; p=link(temp_head);
23787   while ( p!=inf_val ) {
23788     incr(m); l=value(p); info(p)=m;
23789     if ( value(link(p))<=l+d ) {
23790       @<Replace an interval of values by its midpoint@>;
23791     }
23792     q=p; p=link(p);
23793   }
23794   return m;
23795 }
23796
23797 @ @<Replace an interval...@>=
23798
23799   do {  
23800     p=link(p); info(p)=m;
23801     decr(mp->excess); if ( mp->excess==0 ) d=0;
23802   } while (value(link(p))<=l+d);
23803   v=l+halfp(value(p)-l);
23804   if ( value(p)-v>mp->perturbation ) 
23805     mp->perturbation=value(p)-v;
23806   r=q;
23807   do {  
23808     r=link(r); value(r)=v;
23809   } while (r!=p);
23810   link(q)=p; /* remove duplicate values from the current list */
23811 }
23812
23813 @ A warning message is issued whenever something is perturbed by
23814 more than 1/16\thinspace pt.
23815
23816 @c void mp_tfm_warning (MP mp,small_number m) { 
23817   mp_print_nl(mp, "(some "); 
23818   mp_print(mp, mp->int_name[m]);
23819 @.some charwds...@>
23820 @.some chardps...@>
23821 @.some charhts...@>
23822 @.some charics...@>
23823   mp_print(mp, " values had to be adjusted by as much as ");
23824   mp_print_scaled(mp, mp->perturbation); mp_print(mp, "pt)");
23825 }
23826
23827 @ Here's an example of how we use these routines.
23828 The width data needs to be perturbed only if there are 256 distinct
23829 widths, but \MP\ must check for this case even though it is
23830 highly unusual.
23831
23832 An integer variable |k| will be defined when we use this code.
23833 The |dimen_head| array will contain pointers to the sorted
23834 lists of dimensions.
23835
23836 @<Massage the \.{TFM} widths@>=
23837 clear_the_list;
23838 for (k=mp->bc;k<=mp->ec;k++)  {
23839   if ( mp->char_exists[k] )
23840     mp->tfm_width[k]=mp_sort_in(mp, mp->tfm_width[k]);
23841 }
23842 mp->nw=mp_skimp(mp, 255)+1; mp->dimen_head[1]=link(temp_head);
23843 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, char_wd)
23844
23845 @ @<Glob...@>=
23846 pointer dimen_head[5]; /* lists of \.{TFM} dimensions */
23847
23848 @ Heights, depths, and italic corrections are different from widths
23849 not only because their list length is more severely restricted, but
23850 also because zero values do not need to be put into the lists.
23851
23852 @<Massage the \.{TFM} heights, depths, and italic corrections@>=
23853 clear_the_list;
23854 for (k=mp->bc;k<=mp->ec;k++) {
23855   if ( mp->char_exists[k] ) {
23856     if ( mp->tfm_height[k]==0 ) mp->tfm_height[k]=zero_val;
23857     else mp->tfm_height[k]=mp_sort_in(mp, mp->tfm_height[k]);
23858   }
23859 }
23860 mp->nh=mp_skimp(mp, 15)+1; mp->dimen_head[2]=link(temp_head);
23861 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, char_ht);
23862 clear_the_list;
23863 for (k=mp->bc;k<=mp->ec;k++) {
23864   if ( mp->char_exists[k] ) {
23865     if ( mp->tfm_depth[k]==0 ) mp->tfm_depth[k]=zero_val;
23866     else mp->tfm_depth[k]=mp_sort_in(mp, mp->tfm_depth[k]);
23867   }
23868 }
23869 mp->nd=mp_skimp(mp, 15)+1; mp->dimen_head[3]=link(temp_head);
23870 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, char_dp);
23871 clear_the_list;
23872 for (k=mp->bc;k<=mp->ec;k++) {
23873   if ( mp->char_exists[k] ) {
23874     if ( mp->tfm_ital_corr[k]==0 ) mp->tfm_ital_corr[k]=zero_val;
23875     else mp->tfm_ital_corr[k]=mp_sort_in(mp, mp->tfm_ital_corr[k]);
23876   }
23877 }
23878 mp->ni=mp_skimp(mp, 63)+1; mp->dimen_head[4]=link(temp_head);
23879 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, char_ic)
23880
23881 @ @<Initialize table entries...@>=
23882 value(zero_val)=0; info(zero_val)=0;
23883
23884 @ Bytes 5--8 of the header are set to the design size, unless the user has
23885 some crazy reason for specifying them differently.
23886
23887 Error messages are not allowed at the time this procedure is called,
23888 so a warning is printed instead.
23889
23890 The value of |max_tfm_dimen| is calculated so that
23891 $$\hbox{|make_scaled(16*max_tfm_dimen,internal[design_size])|}
23892  < \\{three\_bytes}.$$
23893
23894 @d three_bytes 0100000000 /* $2^{24}$ */
23895
23896 @c 
23897 void mp_fix_design_size (MP mp) {
23898   scaled d; /* the design size */
23899   d=mp->internal[design_size];
23900   if ( (d<unity)||(d>=fraction_half) ) {
23901     if ( d!=0 )
23902       mp_print_nl(mp, "(illegal design size has been changed to 128pt)");
23903 @.illegal design size...@>
23904     d=040000000; mp->internal[design_size]=d;
23905   }
23906   if ( mp->header_byte[4]<0 ) if ( mp->header_byte[5]<0 )
23907     if ( mp->header_byte[6]<0 ) if ( mp->header_byte[7]<0 ) {
23908      mp->header_byte[4]=d / 04000000;
23909      mp->header_byte[5]=(d / 4096) % 256;
23910      mp->header_byte[6]=(d / 16) % 256;
23911      mp->header_byte[7]=(d % 16)*16;
23912   };
23913   mp->max_tfm_dimen=16*mp->internal[design_size]-mp->internal[design_size] / 010000000;
23914   if ( mp->max_tfm_dimen>=fraction_half ) mp->max_tfm_dimen=fraction_half-1;
23915 }
23916
23917 @ The |dimen_out| procedure computes a |fix_word| relative to the
23918 design size. If the data was out of range, it is corrected and the
23919 global variable |tfm_changed| is increased by~one.
23920
23921 @c integer mp_dimen_out (MP mp,scaled x) { 
23922   if ( abs(x)>mp->max_tfm_dimen ) {
23923     incr(mp->tfm_changed);
23924     if ( x>0 ) x=three_bytes-1; else x=1-three_bytes;
23925   } else {
23926     x=mp_make_scaled(mp, x*16,mp->internal[design_size]);
23927   }
23928   return x;
23929 }
23930
23931 @ @<Glob...@>=
23932 scaled max_tfm_dimen; /* bound on widths, heights, kerns, etc. */
23933 integer tfm_changed; /* the number of data entries that were out of bounds */
23934
23935 @ If the user has not specified any of the first four header bytes,
23936 the |fix_check_sum| procedure replaces them by a ``check sum'' computed
23937 from the |tfm_width| data relative to the design size.
23938 @^check sum@>
23939
23940 @c void mp_fix_check_sum (MP mp) {
23941   eight_bits k; /* runs through character codes */
23942   eight_bits B1,B2,B3,B4; /* bytes of the check sum */
23943   integer x;  /* hash value used in check sum computation */
23944   if ( mp->header_byte[0]==0 && mp->header_byte[1]==0 &&
23945        mp->header_byte[2]==0 && mp->header_byte[3]==0 ) {
23946     @<Compute a check sum in |(b1,b2,b3,b4)|@>;
23947     mp->header_byte[0]=B1; mp->header_byte[1]=B2;
23948     mp->header_byte[2]=B3; mp->header_byte[3]=B4; 
23949     return;
23950   }
23951 }
23952
23953 @ @<Compute a check sum in |(b1,b2,b3,b4)|@>=
23954 B1=mp->bc; B2=mp->ec; B3=mp->bc; B4=mp->ec; mp->tfm_changed=0;
23955 for (k=mp->bc;k<=mp->ec;k++) { 
23956   if ( mp->char_exists[k] ) {
23957     x=mp_dimen_out(mp, value(mp->tfm_width[k]))+(k+4)*020000000; /* this is positive */
23958     B1=(B1+B1+x) % 255;
23959     B2=(B2+B2+x) % 253;
23960     B3=(B3+B3+x) % 251;
23961     B4=(B4+B4+x) % 247;
23962   }
23963 }
23964
23965 @ Finally we're ready to actually write the \.{TFM} information.
23966 Here are some utility routines for this purpose.
23967
23968 @d tfm_out(A) fputc((A),mp->tfm_file) /* output one byte to |tfm_file| */
23969
23970 @c void mp_tfm_two (MP mp,integer x) { /* output two bytes to |tfm_file| */
23971   tfm_out(x / 256); tfm_out(x % 256);
23972 }
23973 void mp_tfm_four (MP mp,integer x) { /* output four bytes to |tfm_file| */
23974   if ( x>=0 ) tfm_out(x / three_bytes);
23975   else { 
23976     x=x+010000000000; /* use two's complement for negative values */
23977     x=x+010000000000;
23978     tfm_out((x / three_bytes) + 128);
23979   };
23980   x=x % three_bytes; tfm_out(x / unity);
23981   x=x % unity; tfm_out(x / 0400);
23982   tfm_out(x % 0400);
23983 }
23984 void mp_tfm_qqqq (MP mp,four_quarters x) { /* output four quarterwords to |tfm_file| */
23985   tfm_out(qo(x.b0)); tfm_out(qo(x.b1)); 
23986   tfm_out(qo(x.b2)); tfm_out(qo(x.b3));
23987 }
23988
23989 @ @<Finish the \.{TFM} file@>=
23990 if ( mp->job_name==NULL ) mp_open_log_file(mp);
23991 mp_pack_job_name(mp, ".tfm");
23992 while ( ! mp_b_open_out(mp, &mp->tfm_file, mp_filetype_metrics) )
23993   mp_prompt_file_name(mp, "file name for font metrics",".tfm");
23994 mp->metric_file_name=xstrdup(mp->name_of_file);
23995 @<Output the subfile sizes and header bytes@>;
23996 @<Output the character information bytes, then
23997   output the dimensions themselves@>;
23998 @<Output the ligature/kern program@>;
23999 @<Output the extensible character recipes and the font metric parameters@>;
24000   if ( mp->internal[tracing_stats]>0 )
24001   @<Log the subfile sizes of the \.{TFM} file@>;
24002 mp_print_nl(mp, "Font metrics written on "); 
24003 mp_print(mp, mp->metric_file_name); mp_print_char(mp, '.');
24004 @.Font metrics written...@>
24005 fclose(mp->tfm_file)
24006
24007 @ Integer variables |lh|, |k|, and |lk_offset| will be defined when we use
24008 this code.
24009
24010 @<Output the subfile sizes and header bytes@>=
24011 k=mp->header_last;
24012 LH=(k+3) / 4; /* this is the number of header words */
24013 if ( mp->bc>mp->ec ) mp->bc=1; /* if there are no characters, |ec=0| and |bc=1| */
24014 @<Compute the ligature/kern program offset and implant the
24015   left boundary label@>;
24016 mp_tfm_two(mp,6+LH+(mp->ec-mp->bc+1)+mp->nw+mp->nh+mp->nd+mp->ni+mp->nl
24017      +lk_offset+mp->nk+mp->ne+mp->np);
24018   /* this is the total number of file words that will be output */
24019 mp_tfm_two(mp, LH); mp_tfm_two(mp, mp->bc); mp_tfm_two(mp, mp->ec); 
24020 mp_tfm_two(mp, mp->nw); mp_tfm_two(mp, mp->nh);
24021 mp_tfm_two(mp, mp->nd); mp_tfm_two(mp, mp->ni); mp_tfm_two(mp, mp->nl+lk_offset); 
24022 mp_tfm_two(mp, mp->nk); mp_tfm_two(mp, mp->ne);
24023 mp_tfm_two(mp, mp->np);
24024 for (k=0;k< 4*LH;k++)   { 
24025   tfm_out(mp->header_byte[k]);
24026 }
24027
24028 @ @<Output the character information bytes...@>=
24029 for (k=mp->bc;k<=mp->ec;k++) {
24030   if ( ! mp->char_exists[k] ) {
24031     mp_tfm_four(mp, 0);
24032   } else { 
24033     tfm_out(info(mp->tfm_width[k])); /* the width index */
24034     tfm_out((info(mp->tfm_height[k]))*16+info(mp->tfm_depth[k]));
24035     tfm_out((info(mp->tfm_ital_corr[k]))*4+mp->char_tag[k]);
24036     tfm_out(mp->char_remainder[k]);
24037   };
24038 }
24039 mp->tfm_changed=0;
24040 for (k=1;k<=4;k++) { 
24041   mp_tfm_four(mp, 0); p=mp->dimen_head[k];
24042   while ( p!=inf_val ) {
24043     mp_tfm_four(mp, mp_dimen_out(mp, value(p))); p=link(p);
24044   }
24045 }
24046
24047
24048 @ We need to output special instructions at the beginning of the
24049 |lig_kern| array in order to specify the right boundary character
24050 and/or to handle starting addresses that exceed 255. The |label_loc|
24051 and |label_char| arrays have been set up to record all the
24052 starting addresses; we have $-1=|label_loc|[0]<|label_loc|[1]\le\cdots
24053 \le|label_loc|[|label_ptr]|$.
24054
24055 @<Compute the ligature/kern program offset...@>=
24056 mp->bchar=mp_round_unscaled(mp, mp->internal[boundary_char]);
24057 if ((mp->bchar<0)||(mp->bchar>255))
24058   { mp->bchar=-1; mp->lk_started=false; lk_offset=0; }
24059 else { mp->lk_started=true; lk_offset=1; };
24060 @<Find the minimum |lk_offset| and adjust all remainders@>;
24061 if ( mp->bch_label<undefined_label )
24062   { skip_byte(mp->nl)=qi(255); next_char(mp->nl)=qi(0);
24063   op_byte(mp->nl)=qi(((mp->bch_label+lk_offset)/ 256));
24064   rem_byte(mp->nl)=qi(((mp->bch_label+lk_offset)% 256));
24065   incr(mp->nl); /* possibly |nl=lig_table_size+1| */
24066   }
24067
24068 @ @<Find the minimum |lk_offset|...@>=
24069 k=mp->label_ptr; /* pointer to the largest unallocated label */
24070 if ( mp->label_loc[k]+lk_offset>255 ) {
24071   lk_offset=0; mp->lk_started=false; /* location 0 can do double duty */
24072   do {  
24073     mp->char_remainder[mp->label_char[k]]=lk_offset;
24074     while ( mp->label_loc[k-1]==mp->label_loc[k] ) {
24075        decr(k); mp->char_remainder[mp->label_char[k]]=lk_offset;
24076     }
24077     incr(lk_offset); decr(k);
24078   } while (! (lk_offset+mp->label_loc[k]<256));
24079     /* N.B.: |lk_offset=256| satisfies this when |k=0| */
24080 };
24081 if ( lk_offset>0 ) {
24082   while ( k>0 ) {
24083     mp->char_remainder[mp->label_char[k]]
24084      =mp->char_remainder[mp->label_char[k]]+lk_offset;
24085     decr(k);
24086   }
24087 }
24088
24089 @ @<Output the ligature/kern program@>=
24090 for (k=0;k<= 255;k++ ) {
24091   if ( mp->skip_table[k]<undefined_label ) {
24092      mp_print_nl(mp, "(local label "); mp_print_int(mp, k); mp_print(mp, ":: was missing)");
24093 @.local label l:: was missing@>
24094     cancel_skips(mp->skip_table[k]);
24095   }
24096 }
24097 if ( mp->lk_started ) { /* |lk_offset=1| for the special |bchar| */
24098   tfm_out(255); tfm_out(mp->bchar); mp_tfm_two(mp, 0);
24099 } else {
24100   for (k=1;k<=lk_offset;k++) {/* output the redirection specs */
24101     mp->ll=mp->label_loc[mp->label_ptr];
24102     if ( mp->bchar<0 ) { tfm_out(254); tfm_out(0);   }
24103     else { tfm_out(255); tfm_out(mp->bchar);   };
24104     mp_tfm_two(mp, mp->ll+lk_offset);
24105     do {  
24106       decr(mp->label_ptr);
24107     } while (! (mp->label_loc[mp->label_ptr]<mp->ll));
24108   }
24109 }
24110 for (k=0;k<=mp->nl-1;k++) mp_tfm_qqqq(mp, mp->lig_kern[k]);
24111 for (k=0;k<=mp->nk-1;k++) mp_tfm_four(mp, mp_dimen_out(mp, mp->kern[k]))
24112
24113 @ @<Output the extensible character recipes...@>=
24114 for (k=0;k<=mp->ne-1;k++) 
24115   mp_tfm_qqqq(mp, mp->exten[k]);
24116 for (k=1;k<=mp->np;k++) {
24117   if ( k==1 ) {
24118     if ( abs(mp->param[1])<fraction_half ) {
24119       mp_tfm_four(mp, mp->param[1]*16);
24120     } else  { 
24121       incr(mp->tfm_changed);
24122       if ( mp->param[1]>0 ) mp_tfm_four(mp, el_gordo);
24123       else mp_tfm_four(mp, -el_gordo);
24124     }
24125   } else {
24126     mp_tfm_four(mp, mp_dimen_out(mp, mp->param[k]));
24127   }
24128 }
24129 if ( mp->tfm_changed>0 )  { 
24130   if ( mp->tfm_changed==1 ) mp_print_nl(mp, "(a font metric dimension");
24131 @.a font metric dimension...@>
24132   else  { 
24133     mp_print_nl(mp, "("); mp_print_int(mp, mp->tfm_changed);
24134 @.font metric dimensions...@>
24135     mp_print(mp, " font metric dimensions");
24136   }
24137   mp_print(mp, " had to be decreased)");
24138 }
24139
24140 @ @<Log the subfile sizes of the \.{TFM} file@>=
24141
24142   char s[200];
24143   wlog_ln(" ");
24144   if ( mp->bch_label<undefined_label ) decr(mp->nl);
24145   snprintf(s,128,"(You used %iw,%ih,%id,%ii,%il,%ik,%ie,%ip metric file positions)",
24146                  mp->nw, mp->nh, mp->nd, mp->ni, mp->nl, mp->nk, mp->ne,mp->np);
24147   wlog_ln(s);
24148 }
24149
24150 @* \[43] Reading font metric data.
24151
24152 \MP\ isn't a typesetting program but it does need to find the bounding box
24153 of a sequence of typeset characters.  Thus it needs to read \.{TFM} files as
24154 well as write them.
24155
24156 @<Glob...@>=
24157 FILE * tfm_infile;
24158
24159 @ All the width, height, and depth information is stored in an array called
24160 |font_info|.  This array is allocated sequentially and each font is stored
24161 as a series of |char_info| words followed by the width, height, and depth
24162 tables.  Since |font_name| entries are permanent, their |str_ref| values are
24163 set to |max_str_ref|.
24164
24165 @<Types...@>=
24166 typedef unsigned int font_number; /* |0..font_max| */
24167
24168 @ The |font_info| array is indexed via a group directory arrays.
24169 For example, the |char_info| data for character~|c| in font~|f| will be
24170 in |font_info[char_base[f]+c].qqqq|.
24171
24172 @<Glob...@>=
24173 font_number font_max; /* maximum font number for included text fonts */
24174 size_t      font_mem_size; /* number of words for \.{TFM} information for text fonts */
24175 memory_word *font_info; /* height, width, and depth data */
24176 char        **font_enc_name; /* encoding names, if any */
24177 boolean     *font_ps_name_fixed; /* are the postscript names fixed already?  */
24178 int         next_fmem; /* next unused entry in |font_info| */
24179 font_number last_fnum; /* last font number used so far */
24180 scaled      *font_dsize;  /* 16 times the ``design'' size in \ps\ points */
24181 char        **font_name;  /* name as specified in the \&{infont} command */
24182 char        **font_ps_name;  /* PostScript name for use when |internal[prologues]>0| */
24183 font_number last_ps_fnum; /* last valid |font_ps_name| index */
24184 eight_bits  *font_bc;
24185 eight_bits  *font_ec;  /* first and last character code */
24186 int         *char_base;  /* base address for |char_info| */
24187 int         *width_base; /* index for zeroth character width */
24188 int         *height_base; /* index for zeroth character height */
24189 int         *depth_base; /* index for zeroth character depth */
24190 pointer     *font_sizes;
24191
24192 @ @<Allocate or initialize ...@>=
24193 mp->font_mem_size = 10000; 
24194 mp->font_info = xmalloc ((mp->font_mem_size+1),sizeof(memory_word));
24195 memset (mp->font_info,0,sizeof(memory_word)*(mp->font_mem_size+1));
24196 mp->font_enc_name = NULL;
24197 mp->font_ps_name_fixed = NULL;
24198 mp->font_dsize = NULL;
24199 mp->font_name = NULL;
24200 mp->font_ps_name = NULL;
24201 mp->font_bc = NULL;
24202 mp->font_ec = NULL;
24203 mp->last_fnum = null_font;
24204 mp->char_base = NULL;
24205 mp->width_base = NULL;
24206 mp->height_base = NULL;
24207 mp->depth_base = NULL;
24208 mp->font_sizes = null;
24209
24210 @ @<Dealloc variables@>=
24211 xfree(mp->font_info);
24212 xfree(mp->font_enc_name);
24213 xfree(mp->font_ps_name_fixed);
24214 xfree(mp->font_dsize);
24215 xfree(mp->font_name);
24216 xfree(mp->font_ps_name);
24217 xfree(mp->font_bc);
24218 xfree(mp->font_ec);
24219 xfree(mp->char_base);
24220 xfree(mp->width_base);
24221 xfree(mp->height_base);
24222 xfree(mp->depth_base);
24223 xfree(mp->font_sizes);
24224
24225
24226 @c 
24227 void mp_reallocate_fonts (MP mp, font_number l) {
24228   font_number f;
24229   XREALLOC(mp->font_enc_name,      l, char *);
24230   XREALLOC(mp->font_ps_name_fixed, l, boolean);
24231   XREALLOC(mp->font_dsize,         l, scaled);
24232   XREALLOC(mp->font_name,          l, char *);
24233   XREALLOC(mp->font_ps_name,       l, char *);
24234   XREALLOC(mp->font_bc,            l, eight_bits);
24235   XREALLOC(mp->font_ec,            l, eight_bits);
24236   XREALLOC(mp->char_base,          l, int);
24237   XREALLOC(mp->width_base,         l, int);
24238   XREALLOC(mp->height_base,        l, int);
24239   XREALLOC(mp->depth_base,         l, int);
24240   XREALLOC(mp->font_sizes,         l, pointer);
24241   for (f=(mp->last_fnum+1);f<=l;f++) {
24242     mp->font_enc_name[f]=NULL;
24243     mp->font_ps_name_fixed[f] = false;
24244     mp->font_name[f]=NULL;
24245     mp->font_ps_name[f]=NULL;
24246     mp->font_sizes[f]=null;
24247   }
24248   mp->font_max = l;
24249 }
24250
24251 @ @<Declare |mp_reallocate| functions@>=
24252 void mp_reallocate_fonts (MP mp, font_number l);
24253
24254
24255 @ A |null_font| containing no characters is useful for error recovery.  Its
24256 |font_name| entry starts out empty but is reset each time an erroneous font is
24257 found.  This helps to cut down on the number of duplicate error messages without
24258 wasting a lot of space.
24259
24260 @d null_font 0 /* the |font_number| for an empty font */
24261
24262 @<Set initial...@>=
24263 mp->font_dsize[null_font]=0;
24264 mp->font_bc[null_font]=1;
24265 mp->font_ec[null_font]=0;
24266 mp->char_base[null_font]=0;
24267 mp->width_base[null_font]=0;
24268 mp->height_base[null_font]=0;
24269 mp->depth_base[null_font]=0;
24270 mp->next_fmem=0;
24271 mp->last_fnum=null_font;
24272 mp->last_ps_fnum=null_font;
24273 mp->font_name[null_font]="nullfont";
24274 mp->font_ps_name[null_font]="";
24275
24276 @ Each |char_info| word is of type |four_quarters|.  The |b0| field contains
24277 the |width index|; the |b1| field contains the height
24278 index; the |b2| fields contains the depth index, and the |b3| field used only
24279 for temporary storage. (It is used to keep track of which characters occur in
24280 an edge structure that is being shipped out.)
24281 The corresponding words in the width, height, and depth tables are stored as
24282 |scaled| values in units of \ps\ points.
24283
24284 With the macros below, the |char_info| word for character~|c| in font~|f| is
24285 |char_info(f)(c)| and the width is
24286 $$\hbox{|char_width(f)(char_info(f)(c)).sc|.}$$
24287
24288 @d char_info_end(A) (A)].qqqq
24289 @d char_info(A) mp->font_info[mp->char_base[(A)]+char_info_end
24290 @d char_width_end(A) (A).b0].sc
24291 @d char_width(A) mp->font_info[mp->width_base[(A)]+char_width_end
24292 @d char_height_end(A) (A).b1].sc
24293 @d char_height(A) mp->font_info[mp->height_base[(A)]+char_height_end
24294 @d char_depth_end(A) (A).b2].sc
24295 @d char_depth(A) mp->font_info[mp->depth_base[(A)]+char_depth_end
24296 @d ichar_exists(A) ((A).b0>0)
24297
24298 @ The |font_ps_name| for a built-in font should be what PostScript expects.
24299 A preliminary name is obtained here from the \.{TFM} name as given in the
24300 |fname| argument.  This gets updated later from an external table if necessary.
24301
24302 @<Declare text measuring subroutines@>=
24303 @<Declare subroutines for parsing file names@>;
24304 font_number mp_read_font_info (MP mp, char*fname) {
24305   boolean file_opened; /* has |tfm_infile| been opened? */
24306   font_number n; /* the number to return */
24307   halfword lf,tfm_lh,bc,ec,nw,nh,nd; /* subfile size parameters */
24308   size_t whd_size; /* words needed for heights, widths, and depths */
24309   int i,ii; /* |font_info| indices */
24310   int jj; /* counts bytes to be ignored */
24311   scaled z; /* used to compute the design size */
24312   fraction d;
24313   /* height, width, or depth as a fraction of design size times $2^{-8}$ */
24314   eight_bits h_and_d; /* height and depth indices being unpacked */
24315   int tfbyte; /* a byte read from the file */
24316   n=null_font;
24317   @<Open |tfm_infile| for input@>;
24318   @<Read data from |tfm_infile|; if there is no room, say so and |goto done|;
24319     otherwise |goto bad_tfm| or |goto done| as appropriate@>;
24320 BAD_TFM:
24321   @<Complain that the \.{TFM} file is bad@>;
24322 DONE:
24323   if ( file_opened ) fclose(mp->tfm_infile);
24324   if ( n!=null_font ) { 
24325     mp->font_ps_name[n]=fname;
24326     mp->font_name[n]=fname;
24327   }
24328   return n;
24329 }
24330
24331 @ \MP\ doesn't bother to check the entire \.{TFM} file for errors or explain
24332 precisely what is wrong if it does find a problem.  Programs called \.{TFtoPL}
24333 @.TFtoPL@> @.PLtoTF@>
24334 and \.{PLtoTF} can be used to debug \.{TFM} files.
24335
24336 @<Complain that the \.{TFM} file is bad@>=
24337 print_err("Font ");
24338 mp_print(mp, fname);
24339 if ( file_opened ) mp_print(mp, " not usable: TFM file is bad");
24340 else mp_print(mp, " not usable: TFM file not found");
24341 help3("I wasn't able to read the size data for this font so this")
24342   ("`infont' operation won't produce anything. If the font name")
24343   ("is right, you might ask an expert to make a TFM file");
24344 if ( file_opened )
24345   mp->help_line[0]="is right, try asking an expert to fix the TFM file";
24346 mp_error(mp)
24347
24348 @ @<Read data from |tfm_infile|; if there is no room, say so...@>=
24349 @<Read the \.{TFM} size fields@>;
24350 @<Use the size fields to allocate space in |font_info|@>;
24351 @<Read the \.{TFM} header@>;
24352 @<Read the character data and the width, height, and depth tables and
24353   |goto done|@>
24354
24355 @ A bad \.{TFM} file can be shorter than it claims to be.  The code given here
24356 might try to read past the end of the file if this happens.  Changes will be
24357 needed if it causes a system error to refer to |tfm_infile^| or call
24358 |get_tfm_infile| when |eof(tfm_infile)| is true.  For example, the definition
24359 @^system dependencies@>
24360 of |tfget| could be changed to
24361 ``|begin get(tfm_infile); if eof(tfm_infile) then goto bad_tfm; end|.''
24362
24363 @d tfget {tfbyte = fgetc(mp->tfm_infile); }
24364 @d read_two(A) { (A)=tfbyte;
24365   if ( (A)>127 ) goto BAD_TFM;
24366   tfget; (A)=(A)*0400+tfbyte;
24367   }
24368 @d tf_ignore(A) { for (jj=(A);jj>=1;jj--) tfget; }
24369
24370 @<Read the \.{TFM} size fields@>=
24371 tfget; read_two(lf);
24372 tfget; read_two(tfm_lh);
24373 tfget; read_two(bc);
24374 tfget; read_two(ec);
24375 if ( (bc>1+ec)||(ec>255) ) goto BAD_TFM;
24376 tfget; read_two(nw);
24377 tfget; read_two(nh);
24378 tfget; read_two(nd);
24379 whd_size=(ec+1-bc)+nw+nh+nd;
24380 if ( lf<(int)(6+tfm_lh+whd_size) ) goto BAD_TFM;
24381 tf_ignore(10)
24382
24383 @ Offsets are added to |char_base[n]| and |width_base[n]| so that is not
24384 necessary to apply the |so|  and |qo| macros when looking up the width of a
24385 character in the string pool.  In order to ensure nonnegative |char_base|
24386 values when |bc>0|, it may be necessary to reserve a few unused |font_info|
24387 elements.
24388
24389 @<Use the size fields to allocate space in |font_info|@>=
24390 if ( mp->next_fmem<bc) mp->next_fmem=bc;  /* ensure nonnegative |char_base| */
24391 if (mp->last_fnum==mp->font_max)
24392   mp_reallocate_fonts(mp,(mp->font_max+(mp->font_max>>2)));
24393 while (mp->next_fmem+whd_size>=mp->font_mem_size) {
24394   size_t l = mp->font_mem_size+(mp->font_mem_size>>2);
24395   memory_word *font_info;
24396   font_info = xmalloc ((l+1),sizeof(memory_word));
24397   memset (font_info,0,sizeof(memory_word)*(l+1));
24398   memcpy (font_info,mp->font_info,sizeof(memory_word)*(mp->font_mem_size+1));
24399   xfree(mp->font_info);
24400   mp->font_info = font_info;
24401   mp->font_mem_size = l;
24402 }
24403 incr(mp->last_fnum);
24404 n=mp->last_fnum;
24405 mp->font_bc[n]=bc;
24406 mp->font_ec[n]=ec;
24407 mp->char_base[n]=mp->next_fmem-bc;
24408 mp->width_base[n]=mp->next_fmem+ec-bc+1;
24409 mp->height_base[n]=mp->width_base[n]+nw;
24410 mp->depth_base[n]=mp->height_base[n]+nh;
24411 mp->next_fmem=mp->next_fmem+whd_size;
24412
24413
24414 @ @<Read the \.{TFM} header@>=
24415 if ( tfm_lh<2 ) goto BAD_TFM;
24416 tf_ignore(4);
24417 tfget; read_two(z);
24418 tfget; z=z*0400+tfbyte;
24419 tfget; z=z*0400+tfbyte; /* now |z| is 16 times the design size */
24420 mp->font_dsize[n]=mp_take_fraction(mp, z,267432584);
24421   /* times ${72\over72.27}2^{28}$ to convert from \TeX\ points */
24422 tf_ignore(4*(tfm_lh-2))
24423
24424 @ @<Read the character data and the width, height, and depth tables...@>=
24425 ii=mp->width_base[n];
24426 i=mp->char_base[n]+bc;
24427 while ( i<ii ) { 
24428   tfget; mp->font_info[i].qqqq.b0=qi(tfbyte);
24429   tfget; h_and_d=tfbyte;
24430   mp->font_info[i].qqqq.b1=h_and_d / 16;
24431   mp->font_info[i].qqqq.b2=h_and_d % 16;
24432   tfget; tfget;
24433   incr(i);
24434 }
24435 while ( i<mp->next_fmem ) {
24436   @<Read a four byte dimension, scale it by the design size, store it in
24437     |font_info[i]|, and increment |i|@>;
24438 }
24439 if (feof(mp->tfm_infile) ) goto BAD_TFM;
24440 goto DONE
24441
24442 @ The raw dimension read into |d| should have magnitude at most $2^{24}$ when
24443 interpreted as an integer, and this includes a scale factor of $2^{20}$.  Thus
24444 we can multiply it by sixteen and think of it as a |fraction| that has been
24445 divided by sixteen.  This cancels the extra scale factor contained in
24446 |font_dsize[n|.
24447
24448 @<Read a four byte dimension, scale it by the design size, store it in...@>=
24449
24450 tfget; d=tfbyte;
24451 if ( d>=0200 ) d=d-0400;
24452 tfget; d=d*0400+tfbyte;
24453 tfget; d=d*0400+tfbyte;
24454 tfget; d=d*0400+tfbyte;
24455 mp->font_info[i].sc=mp_take_fraction(mp, d*16,mp->font_dsize[n]);
24456 incr(i);
24457 }
24458
24459 @ This function does no longer use the file name parser, because |fname| is
24460 a C string already.
24461 @<Open |tfm_infile| for input@>=
24462 file_opened=false;
24463 mp_ptr_scan_file(mp, fname);
24464 if ( strlen(mp->cur_area)==0 ) mp->cur_area=xstrdup(MP_font_area);
24465 if ( strlen(mp->cur_ext)==0 ) mp->cur_ext=xstrdup(".tfm");
24466 mp->tfm_infile = mp_open_file(mp, fname, "rb",mp_filetype_metrics);
24467 if ( !mp->tfm_infile  ) goto BAD_TFM;
24468 file_opened=true
24469
24470 @ When we have a font name and we don't know whether it has been loaded yet,
24471 we scan the |font_name| array before calling |read_font_info|.
24472
24473 @<Declare text measuring subroutines@>=
24474 font_number mp_find_font (MP mp, char *f) {
24475   font_number n;
24476   for (n=0;n<=mp->last_fnum;n++) {
24477     if (mp_xstrcmp(f,mp->font_name[n])==0 )
24478       return n;
24479   }
24480   return mp_read_font_info(mp, f);
24481 }
24482
24483 @ One simple application of |find_font| is the implementation of the |font_size|
24484 operator that gets the design size for a given font name.
24485
24486 @<Find the design size of the font whose name is |cur_exp|@>=
24487 mp_flush_cur_exp(mp, (mp->font_dsize[mp_find_font(mp, str(mp->cur_exp))]+8) / 16)
24488
24489 @ If we discover that the font doesn't have a requested character, we omit it
24490 from the bounding box computation and expect the \ps\ interpreter to drop it.
24491 This routine issues a warning message if the user has asked for it.
24492
24493 @<Declare text measuring subroutines@>=
24494 void mp_lost_warning (MP mp,font_number f, pool_pointer k) { 
24495   if ( mp->internal[tracing_lost_chars]>0 ) { 
24496     mp_begin_diagnostic(mp);
24497     if ( mp->selector==log_only ) incr(mp->selector);
24498     mp_print_nl(mp, "Missing character: There is no ");
24499 @.Missing character@>
24500     mp_print_str(mp, mp->str_pool[k]); 
24501     mp_print(mp, " in font ");
24502     mp_print(mp, mp->font_name[f]); mp_print_char(mp, '!'); 
24503     mp_end_diagnostic(mp, false);
24504   }
24505 }
24506
24507 @ The whole purpose of saving the height, width, and depth information is to be
24508 able to find the bounding box of an item of text in an edge structure.  The
24509 |set_text_box| procedure takes a text node and adds this information.
24510
24511 @<Declare text measuring subroutines@>=
24512 void mp_set_text_box (MP mp,pointer p) {
24513   font_number f; /* |font_n(p)| */
24514   ASCII_code bc,ec; /* range of valid characters for font |f| */
24515   pool_pointer k,kk; /* current character and character to stop at */
24516   four_quarters cc; /* the |char_info| for the current character */
24517   scaled h,d; /* dimensions of the current character */
24518   width_val(p)=0;
24519   height_val(p)=-el_gordo;
24520   depth_val(p)=-el_gordo;
24521   f=font_n(p);
24522   bc=mp->font_bc[f];
24523   ec=mp->font_ec[f];
24524   kk=str_stop(text_p(p));
24525   k=mp->str_start[text_p(p)];
24526   while ( k<kk ) {
24527     @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>;
24528   }
24529   @<Set the height and depth to zero if the bounding box is empty@>;
24530 }
24531
24532 @ @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>=
24533
24534   if ( (mp->str_pool[k]<bc)||(mp->str_pool[k]>ec) ) {
24535     mp_lost_warning(mp, f,k);
24536   } else { 
24537     cc=char_info(f)(mp->str_pool[k]);
24538     if ( ! ichar_exists(cc) ) {
24539       mp_lost_warning(mp, f,k);
24540     } else { 
24541       width_val(p)=width_val(p)+char_width(f)(cc);
24542       h=char_height(f)(cc);
24543       d=char_depth(f)(cc);
24544       if ( h>height_val(p) ) height_val(p)=h;
24545       if ( d>depth_val(p) ) depth_val(p)=d;
24546     }
24547   }
24548   incr(k);
24549 }
24550
24551 @ Let's hope modern compilers do comparisons correctly when the difference would
24552 overflow.
24553
24554 @<Set the height and depth to zero if the bounding box is empty@>=
24555 if ( height_val(p)<-depth_val(p) ) { 
24556   height_val(p)=0;
24557   depth_val(p)=0;
24558 }
24559
24560 @ The new primitives fontmapfile and fontmapline.
24561
24562 @<Declare action procedures for use by |do_statement|@>=
24563 void mp_do_mapfile (MP mp) ;
24564 void mp_do_mapline (MP mp) ;
24565
24566 @ @c void mp_do_mapfile (MP mp) { 
24567   mp_get_x_next(mp); mp_scan_expression(mp);
24568   if ( mp->cur_type!=mp_string_type ) {
24569     @<Complain about improper map operation@>;
24570   } else {
24571     mp_map_file(mp,mp->cur_exp);
24572   }
24573 }
24574 void mp_do_mapline (MP mp) { 
24575   mp_get_x_next(mp); mp_scan_expression(mp);
24576   if ( mp->cur_type!=mp_string_type ) {
24577      @<Complain about improper map operation@>;
24578   } else { 
24579      mp_map_line(mp,mp->cur_exp);
24580   }
24581 }
24582
24583 @ @<Complain about improper map operation@>=
24584
24585   exp_err("Unsuitable expression");
24586   help1("Only known strings can be map files or map lines.");
24587   mp_put_get_error(mp);
24588 }
24589
24590 @
24591 @<Declare the \ps\ output procedures@>=
24592 void mp_ps_print_cmd (MP mp, char *l, char *s) {
24593   if ( mp->internal[mpprocset]>0 ) { ps_room(strlen(s)); mp_print(mp,s); }
24594   else { ps_room(strlen(l)); mp_print(mp, l); };
24595 }
24596 void mp_print_cmd (MP mp,char *l, char *s) {
24597   if ( mp->internal[mpprocset]>0 ) mp_print(mp, s); 
24598   else mp_print(mp, l);
24599 }
24600
24601 @ To print |scaled| value to PDF output we need some subroutines to ensure
24602 accurary.
24603
24604 @d max_integer   0x7FFFFFFF /* $2^{31}-1$ */
24605
24606 @<Glob...@>=
24607 scaled one_bp; /* scaled value corresponds to 1bp */
24608 scaled one_hundred_bp; /* scaled value corresponds to 100bp */
24609 scaled one_hundred_inch; /* scaled value corresponds to 100in */
24610 integer ten_pow[10]; /* $10^0..10^9$ */
24611 integer scaled_out; /* amount of |scaled| that was taken out in |divide_scaled| */
24612
24613 @ @<Set init...@>=
24614 mp->one_bp = 65782; /* 65781.76 */
24615 mp->one_hundred_bp = 6578176;
24616 mp->one_hundred_inch = 473628672;
24617 mp->ten_pow[0] = 1;
24618 for (i = 1;i<= 9; i++ ) {
24619   mp->ten_pow[i] = 10*mp->ten_pow[i - 1];
24620 }
24621
24622 @ The following function divides |s| by |m|. |dd| is number of decimal digits.
24623
24624 @c scaled mp_divide_scaled (MP mp,scaled s, scaled m, integer  dd) {
24625   scaled q,r;
24626   integer sign,i;
24627   sign = 1;
24628   if ( s < 0 ) { sign = -sign; s = -s; }
24629   if ( m < 0 ) { sign = -sign; m = -m; }
24630   if ( m == 0 )
24631     mp_confusion(mp, "arithmetic: divided by zero");
24632   else if ( m >= (max_integer / 10) )
24633     mp_confusion(mp, "arithmetic: number too big");
24634   q = s / m;
24635   r = s % m;
24636   for (i = 1;i<=dd;i++) {
24637     q = 10*q + (10*r) / m;
24638     r = (10*r) % m;
24639   }
24640   if ( 2*r >= m ) { incr(q); r = r - m; }
24641   mp->scaled_out = sign*(s - (r / mp->ten_pow[dd]));
24642   return (sign*q);
24643 }
24644
24645 @* \[44] Shipping pictures out.
24646 The |ship_out| procedure, to be described below, is given a pointer to
24647 an edge structure. Its mission is to output a file containing the \ps\
24648 description of an edge structure.
24649
24650 @ Each time an edge structure is shipped out we write a new \ps\ output
24651 file named according to the current \&{charcode}.
24652 @:char_code_}{\&{charcode} primitive@>
24653
24654 @<Declare the \ps\ output procedures@>=
24655 void mp_open_output_file (MP mp) ;
24656
24657 @ @c void mp_open_output_file (MP mp) {
24658   integer c; /* \&{charcode} rounded to the nearest integer */
24659   int old_setting; /* previous |selector| setting */
24660   pool_pointer i; /*  indexes into |filename_template|  */
24661   integer cc; /* a temporary integer for template building  */
24662   integer f,g=0; /* field widths */
24663   if ( mp->job_name==NULL ) mp_open_log_file(mp);
24664   c=mp_round_unscaled(mp, mp->internal[char_code]);
24665   if ( mp->filename_template==0 ) {
24666     char *s; /* a file extension derived from |c| */
24667     if ( c<0 ) 
24668       s=xstrdup(".ps");
24669     else 
24670       @<Use |c| to compute the file extension |s|@>;
24671     mp_pack_job_name(mp, s);
24672     xfree(s);
24673     while ( ! mp_a_open_out(mp, &mp->ps_file, mp_filetype_postscript) )
24674       mp_prompt_file_name(mp, "file name for output",s);
24675   } else { /* initializations */
24676     str_number s, n; /* a file extension derived from |c| */
24677     old_setting=mp->selector; 
24678     mp->selector=new_string;
24679     f = 0;
24680     i = mp->str_start[mp->filename_template];
24681     n = rts(""); /* initialize */
24682     while ( i<str_stop(mp->filename_template) ) {
24683        if ( mp->str_pool[i]=='%' ) {
24684       CONTINUE:
24685         incr(i);
24686         if ( i<str_stop(mp->filename_template) ) {
24687           if ( mp->str_pool[i]=='j' ) {
24688             mp_print(mp, mp->job_name);
24689           } else if ( mp->str_pool[i]=='d' ) {
24690              cc= mp_round_unscaled(mp, mp->internal[day]);
24691              print_with_leading_zeroes(cc);
24692           } else if ( mp->str_pool[i]=='m' ) {
24693              cc= mp_round_unscaled(mp, mp->internal[month]);
24694              print_with_leading_zeroes(cc);
24695           } else if ( mp->str_pool[i]=='y' ) {
24696              cc= mp_round_unscaled(mp, mp->internal[year]);
24697              print_with_leading_zeroes(cc);
24698           } else if ( mp->str_pool[i]=='H' ) {
24699              cc= mp_round_unscaled(mp, mp->internal[mp_time]) / 60;
24700              print_with_leading_zeroes(cc);
24701           }  else if ( mp->str_pool[i]=='M' ) {
24702              cc= mp_round_unscaled(mp, mp->internal[mp_time]) % 60;
24703              print_with_leading_zeroes(cc);
24704           } else if ( mp->str_pool[i]=='c' ) {
24705             if ( c<0 ) mp_print(mp, "ps");
24706             else print_with_leading_zeroes(c);
24707           } else if ( (mp->str_pool[i]>='0') && 
24708                       (mp->str_pool[i]<='9') ) {
24709             if ( (f<10)  )
24710               f = (f*10) + mp->str_pool[i]-'0';
24711             goto CONTINUE;
24712           } else {
24713             mp_print_str(mp, mp->str_pool[i]);
24714           }
24715         }
24716       } else {
24717         if ( mp->str_pool[i]=='.' )
24718           if (length(n)==0)
24719             n = mp_make_string(mp);
24720         mp_print_str(mp, mp->str_pool[i]);
24721       };
24722       incr(i);
24723     };
24724     s = mp_make_string(mp);
24725     mp->selector= old_setting;
24726     if (length(n)==0) {
24727        n=s;
24728        s=rts("");
24729     };
24730     mp_pack_file_name(mp, str(n),"",str(s));
24731     while ( ! mp_a_open_out(mp, &mp->ps_file, mp_filetype_postscript) )
24732       mp_prompt_file_name(mp, "file name for output",str(s));
24733     delete_str_ref(n);
24734     delete_str_ref(s);
24735   }
24736   @<Store the true output file name if appropriate@>;
24737   @<Begin the progress report for the output of picture~|c|@>;
24738 }
24739
24740 @ The file extension created here could be up to five characters long in
24741 extreme cases so it may have to be shortened on some systems.
24742 @^system dependencies@>
24743
24744 @<Use |c| to compute the file extension |s|@>=
24745
24746   s = xmalloc(7,1);
24747   snprintf(s,7,".%i",(int)c);
24748 }
24749
24750 @ The user won't want to see all the output file names so we only save the
24751 first and last ones and a count of how many there were.  For this purpose
24752 files are ordered primarily by \&{charcode} and secondarily by order of
24753 creation.
24754 @:char_code_}{\&{charcode} primitive@>
24755
24756 @<Store the true output file name if appropriate@>=
24757 if ((c<mp->first_output_code)&&(mp->first_output_code>=0)) {
24758   mp->first_output_code=c;
24759   xfree(mp->first_file_name);
24760   mp->first_file_name=xstrdup(mp->name_of_file);
24761 }
24762 if ( c>=mp->last_output_code ) {
24763   mp->last_output_code=c;
24764   xfree(mp->last_file_name);
24765   mp->last_file_name=xstrdup(mp->name_of_file);
24766 }
24767
24768 @ @<Glob...@>=
24769 char * first_file_name;
24770 char * last_file_name; /* full file names */
24771 integer first_output_code;integer last_output_code; /* rounded \&{charcode} values */
24772 @:char_code_}{\&{charcode} primitive@>
24773 integer total_shipped; /* total number of |ship_out| operations completed */
24774
24775 @ @<Set init...@>=
24776 mp->first_file_name=xstrdup("");
24777 mp->last_file_name=xstrdup("");
24778 mp->first_output_code=32768;
24779 mp->last_output_code=-32768;
24780 mp->total_shipped=0;
24781
24782 @ @<Dealloc variables@>=
24783 xfree(mp->first_file_name);
24784 xfree(mp->last_file_name);
24785
24786 @ @<Begin the progress report for the output of picture~|c|@>=
24787 if ( (int)mp->term_offset>mp->max_print_line-6 ) mp_print_ln(mp);
24788 else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
24789 mp_print_char(mp, '[');
24790 if ( c>=0 ) mp_print_int(mp, c)
24791
24792 @ @<End progress report@>=
24793 mp_print_char(mp, ']');
24794 update_terminal;
24795 incr(mp->total_shipped)
24796
24797 @ @<Explain what output files were written@>=
24798 if ( mp->total_shipped>0 ) { 
24799   mp_print_nl(mp, "");
24800   mp_print_int(mp, mp->total_shipped);
24801   mp_print(mp, " output file");
24802   if ( mp->total_shipped>1 ) mp_print_char(mp, 's');
24803   mp_print(mp, " written: ");
24804   mp_print(mp, mp->first_file_name);
24805   if ( mp->total_shipped>1 ) {
24806     if ( 31+strlen(mp->first_file_name)+
24807          strlen(mp->last_file_name)> (unsigned)mp->max_print_line) 
24808       mp_print_ln(mp);
24809     mp_print(mp, " .. ");
24810     mp_print(mp, mp->last_file_name);
24811   }
24812 }
24813
24814 @ We often need to print a pair of coordinates.
24815
24816 @d ps_room(A) if ( (mp->ps_offset+(int)(A))>mp->max_print_line ) 
24817   mp_print_ln(mp) /* optional line break */
24818
24819 @<Declare the \ps\ output procedures@>=
24820 void mp_ps_pair_out (MP mp,scaled x, scaled y) { 
24821   ps_room(26);
24822   mp_print_scaled(mp, x); mp_print_char(mp, ' ');
24823   mp_print_scaled(mp, y); mp_print_char(mp, ' ');
24824 }
24825
24826 @ @<Declare the \ps\ output procedures@>=
24827 void mp_ps_print (MP mp,char *s) { 
24828    ps_room(strlen(s));
24829    mp_print(mp, s);
24830 };
24831
24832 @ @<Exported...@>=
24833 void mp_ps_print (MP mp,char *s) ;
24834
24835
24836 @ The most important output procedure is the one that gives the \ps\ version of
24837 a \MP\ path.
24838
24839 @<Declare the \ps\ output procedures@>=
24840 void mp_ps_path_out (MP mp,pointer h) {
24841   pointer p,q; /* for scanning the path */
24842   scaled d; /* a temporary value */
24843   boolean curved; /* |true| unless the cubic is almost straight */
24844   ps_room(40);
24845   if ( mp->need_newpath ) 
24846     mp_print_cmd(mp, "newpath ","n ");
24847   mp->need_newpath=true;
24848   mp_ps_pair_out(mp, x_coord(h),y_coord(h));
24849   mp_print_cmd(mp, "moveto","m");
24850   p=h;
24851   do {  
24852     if ( right_type(p)==endpoint ) { 
24853       if ( p==h ) mp_ps_print_cmd(mp, " 0 0 rlineto"," 0 0 r");
24854       return;
24855     }
24856     q=link(p);
24857     @<Start a new line and print the \ps\ commands for the curve from
24858       |p| to~|q|@>;
24859     p=q;
24860   } while (p!=h);
24861   mp_ps_print_cmd(mp, " closepath"," p");
24862 }
24863
24864 @ @<Glob...@>=
24865 boolean need_newpath;
24866   /* will |ps_path_out| need to issue a \&{newpath} command next time */
24867 @:newpath_}{\&{newpath} command@>
24868
24869 @ @<Start a new line and print the \ps\ commands for the curve from...@>=
24870 curved=true;
24871 @<Set |curved:=false| if the cubic from |p| to |q| is almost straight@>;
24872 mp_print_ln(mp);
24873 if ( curved ){ 
24874   mp_ps_pair_out(mp, right_x(p),right_y(p));
24875   mp_ps_pair_out(mp, left_x(q),left_y(q));
24876   mp_ps_pair_out(mp, x_coord(q),y_coord(q));
24877   mp_ps_print_cmd(mp, "curveto","c");
24878 } else if ( q!=h ){ 
24879   mp_ps_pair_out(mp, x_coord(q),y_coord(q));
24880   mp_ps_print_cmd(mp, "lineto","l");
24881 }
24882
24883 @ Two types of straight lines come up often in \MP\ paths:
24884 cubics with zero initial and final velocity as created by |make_path| or
24885 |make_envelope|, and cubics with control points uniformly spaced on a line
24886 as created by |make_choices|.
24887
24888 @d bend_tolerance 131 /* allow rounding error of $2\cdot10^{-3}$ */
24889
24890 @<Set |curved:=false| if the cubic from |p| to |q| is almost straight@>=
24891 if ( right_x(p)==x_coord(p) )
24892   if ( right_y(p)==y_coord(p) )
24893     if ( left_x(q)==x_coord(q) )
24894       if ( left_y(q)==y_coord(q) ) curved=false;
24895 d=left_x(q)-right_x(p);
24896 if ( abs(right_x(p)-x_coord(p)-d)<=bend_tolerance )
24897   if ( abs(x_coord(q)-left_x(q)-d)<=bend_tolerance )
24898     { d=left_y(q)-right_y(p);
24899     if ( abs(right_y(p)-y_coord(p)-d)<=bend_tolerance )
24900       if ( abs(y_coord(q)-left_y(q)-d)<=bend_tolerance ) curved=false;
24901     }
24902
24903 @ We need to keep track of several parameters from the \ps\ graphics state.
24904 @^graphics state@>
24905 This allows us to be sure that \ps\ has the correct values when they are
24906 needed without wasting time and space setting them unnecessarily.
24907
24908 @d gs_node_size 10
24909 @d gs_red        mp->mem[mp->gs_state+1].sc
24910 @d gs_green      mp->mem[mp->gs_state+2].sc
24911 @d gs_blue       mp->mem[mp->gs_state+3].sc
24912 @d gs_black      mp->mem[mp->gs_state+4].sc
24913    /* color from the last \&{setcmykcolor} or \&{setrgbcolor} or \&{setgray} command */
24914 @d gs_colormodel mp->mem[mp->gs_state+5].qqqq.b0
24915    /* the current colormodel */
24916 @d gs_ljoin      mp->mem[mp->gs_state+5].qqqq.b1
24917 @d gs_lcap       mp->mem[mp->gs_state+5].qqqq.b2
24918    /* values from the last \&{setlinejoin} and \&{setlinecap} commands */
24919 @d gs_adj_wx     mp->mem[mp->gs_state+5].qqqq.b3
24920    /* what resolution-dependent adjustment applies to the width */
24921 @d gs_miterlim   mp->mem[mp->gs_state+6].sc
24922    /* the value from the last \&{setmiterlimit} command */
24923 @d gs_dash_p     mp->mem[mp->gs_state+7].hh.lh
24924    /* edge structure for last \&{setdash} command */
24925 @d gs_previous   mp->mem[mp->gs_state+7].hh.rh
24926    /* backlink to the previous |gs_state| structure */
24927 @d gs_dash_sc    mp->mem[mp->gs_state+8].sc
24928    /* scale factor used with |gs_dash_p| */
24929 @d gs_width      mp->mem[mp->gs_state+9].sc
24930    /* width setting or $-1$ if no \&{setlinewidth} command so far */
24931
24932 @<Glob...@>=
24933 pointer gs_state;
24934
24935 @ @<Set init...@>=
24936 mp->gs_state=null;
24937
24938 @ To avoid making undue assumptions about the initial graphics state, these
24939 parameters are given special values that are guaranteed not to match anything
24940 in the edge structure being shipped out.  On the other hand, the initial color
24941 should be black so that the translation of an all-black picture will have no
24942 \&{setcolor} commands.  (These would be undesirable in a font application.)
24943 Hence we use |c=0| when initializing the graphics state and we use |c<0|
24944 to recover from a situation where we have lost track of the graphics state.
24945
24946 @<Declare the \ps\ output procedures@>=
24947 void mp_unknown_graphics_state (MP mp,scaled c) ;
24948
24949 @ @c void mp_unknown_graphics_state (MP mp,scaled c) {
24950   pointer p; /* to shift graphic states around */
24951   quarterword k; /* a loop index for copying the |gs_state| */
24952   if ( (c==0)||(c==-1) ) {
24953     if ( mp->gs_state==null ) {
24954       mp->gs_state = mp_get_node(mp, gs_node_size);
24955       gs_previous=null;
24956     } else {
24957       while ( gs_previous!=null ) {
24958         p = gs_previous;
24959         mp_free_node(mp, mp->gs_state,gs_node_size);
24960         mp->gs_state=p;
24961       }
24962     }
24963     gs_red=c; gs_green=c; gs_blue=c; gs_black=c;
24964     gs_colormodel=uninitialized_model;
24965     gs_ljoin=3;
24966     gs_lcap=3;
24967     gs_miterlim=0;
24968     gs_dash_p=diov;
24969     gs_dash_sc=0;
24970     gs_width=-1;
24971   } else if ( c==1 ) {
24972     p= mp->gs_state;
24973     mp->gs_state = mp_get_node(mp, gs_node_size);
24974     for (k=1;k<=gs_node_size-1;k++)
24975       mp->mem[mp->gs_state+k]=mp->mem[p+k];
24976     gs_previous = p;
24977   } else if ( c==2 ) {
24978     p = gs_previous;
24979     mp_free_node(mp, mp->gs_state,gs_node_size);
24980     mp->gs_state=p;
24981   }
24982 }
24983
24984 @ When it is time to output a graphical object, |fix_graphics_state| ensures
24985 that \ps's idea of the graphics state agrees with what is stored in the object.
24986
24987 @<Declare the \ps\ output procedures@>=
24988 @<Declare subroutines needed by |fix_graphics_state|@>;
24989 void mp_fix_graphics_state (MP mp, pointer p) ;
24990
24991 @ @c 
24992 void mp_fix_graphics_state (MP mp, pointer p) {
24993   /* get ready to output graphical object |p| */
24994   pointer hh,pp; /* for list manipulation */
24995   scaled wx,wy,ww; /* dimensions of pen bounding box */
24996   boolean adj_wx; /* whether pixel rounding should be based on |wx| or |wy| */
24997   integer tx,ty; /* temporaries for computing |adj_wx| */
24998   scaled scf; /* a scale factor for the dash pattern */
24999   if ( has_color(p) )
25000     @<Make sure \ps\ will use the right color for object~|p|@>;
25001   if ( (type(p)==fill_code)||(type(p)==stroked_code) )
25002     if ( pen_p(p)!=null )
25003       if ( pen_is_elliptical(pen_p(p)) ) {
25004         @<Generate \ps\ code that sets the stroke width to the
25005           appropriate rounded value@>;
25006         @<Make sure \ps\ will use the right dash pattern for |dash_p(p)|@>;
25007         @<Decide whether the line cap parameter matters and set it if necessary@>;
25008         @<Set the other numeric parameters as needed for object~|p|@>;
25009       }
25010   if ( mp->ps_offset>0 ) mp_print_ln(mp);
25011 }
25012
25013 @ @<Decide whether the line cap parameter matters and set it if necessary@>=
25014 if ( type(p)==stroked_code )
25015   if ( (left_type(path_p(p))==endpoint)||(dash_p(p)!=null) )
25016     if ( gs_lcap!=lcap_val(p) ) {
25017       ps_room(13);
25018       mp_print_char(mp, ' ');
25019       mp_print_char(mp, '0'+lcap_val(p)); 
25020       mp_print_cmd(mp, " setlinecap"," lc");
25021       gs_lcap=lcap_val(p);
25022     }
25023
25024 @ @<Set the other numeric parameters as needed for object~|p|@>=
25025 if ( gs_ljoin!=ljoin_val(p) ) {
25026   ps_room(14);
25027   mp_print_char(mp, ' ');
25028   mp_print_char(mp, '0'+ljoin_val(p)); mp_print_cmd(mp, " setlinejoin"," lj");
25029   gs_ljoin=ljoin_val(p);
25030 }
25031 if ( gs_miterlim!=miterlim_val(p) ) {
25032   ps_room(27);
25033   mp_print_char(mp, ' ');
25034   mp_print_scaled(mp, miterlim_val(p)); mp_print_cmd(mp, " setmiterlimit"," ml");
25035   gs_miterlim=miterlim_val(p);
25036 }
25037
25038 @ @<Make sure \ps\ will use the right color for object~|p|@>=
25039 {
25040   if ( (color_model(p)==rgb_model)||
25041      ((color_model(p)==uninitialized_model)&&
25042      ((mp->internal[default_color_model] / unity)==rgb_model)) ) {
25043   if ( (gs_colormodel!=rgb_model)||(gs_red!=red_val(p))||
25044       (gs_green!=green_val(p))||(gs_blue!=blue_val(p)) ) {
25045       gs_red=red_val(p);
25046       gs_green=green_val(p);
25047       gs_blue=blue_val(p);
25048       gs_black= -1;
25049       gs_colormodel=rgb_model;
25050       { ps_room(36);
25051         mp_print_char(mp, ' ');
25052         mp_print_scaled(mp, gs_red); mp_print_char(mp, ' ');
25053         mp_print_scaled(mp, gs_green); mp_print_char(mp, ' ');
25054         mp_print_scaled(mp, gs_blue);
25055         mp_print_cmd(mp, " setrgbcolor", " R");
25056       }
25057     }
25058   } else if ( (color_model(p)==cmyk_model)||
25059      ((color_model(p)==uninitialized_model)&&
25060      ((mp->internal[default_color_model] / unity)==cmyk_model)) ) {
25061    if ( (gs_red!=cyan_val(p))||(gs_green!=magenta_val(p))||
25062       (gs_blue!=yellow_val(p))||(gs_black!=black_val(p))||
25063       (gs_colormodel!=cmyk_model) ) {
25064       if ( color_model(p)==uninitialized_model ) {
25065         gs_red=0;
25066         gs_green=0;
25067         gs_blue=0;
25068         gs_black=unity;
25069       } else {
25070         gs_red=cyan_val(p);
25071         gs_green=magenta_val(p);
25072         gs_blue=yellow_val(p);
25073         gs_black=black_val(p);
25074       }
25075       gs_colormodel=cmyk_model;
25076       { ps_room(45);
25077         mp_print_char(mp, ' ');
25078         mp_print_scaled(mp, gs_red); mp_print_char(mp, ' ');
25079         mp_print_scaled(mp, gs_green); mp_print_char(mp, ' ');
25080         mp_print_scaled(mp, gs_blue); mp_print_char(mp, ' ');
25081         mp_print_scaled(mp, gs_black);
25082         mp_print_cmd(mp, " setcmykcolor"," C");
25083       }
25084     }
25085   } else if ( (color_model(p)==grey_model)||
25086     ((color_model(p)==uninitialized_model)&&
25087      ((mp->internal[default_color_model] / unity)==grey_model)) ) {
25088    if ( (gs_red!=grey_val(p))||(gs_colormodel!=grey_model) ) {
25089       gs_red = grey_val(p);
25090       gs_green= -1;
25091       gs_blue= -1;
25092       gs_black= -1;
25093       gs_colormodel=grey_model;
25094       { ps_room(16);
25095         mp_print_char(mp, ' ');
25096         mp_print_scaled(mp, gs_red);
25097         mp_print_cmd(mp, " setgray"," G");
25098       }
25099     }
25100   }
25101   if ( color_model(p)==no_model )
25102     gs_colormodel=no_model;
25103 }
25104
25105 @ In order to get consistent widths for horizontal and vertical pen strokes, we
25106 want \ps\ to use an integer number of pixels for the \&{setwidth} parameter.
25107 @:setwidth}{\&{setwidth}command@>
25108 We set |gs_width| to the ideal horizontal or vertical stroke width and then
25109 generate \ps\ code that computes the rounded value.  For non-circular pens, the
25110 pen shape will be rescaled so that horizontal or vertical parts of the stroke
25111 have the computed width.
25112
25113 Rounding the width to whole pixels is not likely to improve the appearance of
25114 diagonal or curved strokes, but we do it anyway for consistency.  The
25115 \&{truncate} command generated here tends to make all the strokes a little
25116 @:truncate}{\&{truncate} command@>
25117 thinner, but this is appropriate for \ps's scan-conversion rules.  Even with
25118 truncation, an ideal with of $w$~pixels gets mapped into $\lfloor w\rfloor+1$.
25119 It would be better to have $\lceil w\rceil$ but that is ridiculously expensive
25120 to compute in \ps.
25121
25122 @<Generate \ps\ code that sets the stroke width...@>=
25123 @<Set |wx| and |wy| to the width and height of the bounding box for
25124   |pen_p(p)|@>;
25125 @<Use |pen_p(p)| and |path_p(p)| to decide whether |wx| or |wy| is more
25126   important and set |adj_wx| and |ww| accordingly@>;
25127 if ( (ww!=gs_width) || (adj_wx!=gs_adj_wx) ) {
25128   if ( adj_wx ) {
25129     ps_room(13);
25130     mp_print_char(mp, ' '); mp_print_scaled(mp, ww);
25131     mp_ps_print_cmd(mp, 
25132       " 0 dtransform exch truncate exch idtransform pop setlinewidth"," hlw");
25133   } else {
25134     if ( mp->internal[mpprocset]>0 ) {
25135       ps_room(13);
25136       mp_print_char(mp, ' ');
25137       mp_print_scaled(mp, ww);
25138       mp_ps_print(mp, " vlw");
25139     } else { 
25140       ps_room(15);
25141       mp_print(mp, " 0 "); mp_print_scaled(mp, ww);
25142       mp_ps_print(mp, " dtransform truncate idtransform setlinewidth pop");
25143     }
25144   }
25145   gs_width = ww;
25146   gs_adj_wx = adj_wx;
25147 }
25148
25149 @ @<Set |wx| and |wy| to the width and height of the bounding box for...@>=
25150 pp=pen_p(p);
25151 if ( (right_x(pp)==x_coord(pp)) && (left_y(pp)==y_coord(pp)) ) {
25152   wx = abs(left_x(pp) - x_coord(pp));
25153   wy = abs(right_y(pp) - y_coord(pp));
25154 } else {
25155   wx = mp_pyth_add(mp, left_x(pp)-x_coord(pp), right_x(pp)-x_coord(pp));
25156   wy = mp_pyth_add(mp, left_y(pp)-y_coord(pp), right_y(pp)-y_coord(pp));
25157 }
25158
25159 @ The path is considered ``essentially horizontal'' if its range of
25160 $y$~coordinates is less than the $y$~range |wy| for the pen.  ``Essentially
25161 vertical'' paths are detected similarly.  This code ensures that no component
25162 of the pen transformation is more that |aspect_bound*(ww+1)|.
25163
25164 @d aspect_bound 10 /* ``less important'' of |wx|, |wy| cannot exceed the other by
25165     more than this factor */
25166
25167 @<Use |pen_p(p)| and |path_p(p)| to decide whether |wx| or |wy| is more...@>=
25168 tx=1; ty=1;
25169 if ( mp_coord_rangeOK(mp, path_p(p), y_loc(0), wy) ) tx=aspect_bound;
25170 else if ( mp_coord_rangeOK(mp, path_p(p), x_loc(0), wx) ) ty=aspect_bound;
25171 if ( wy / ty>=wx / tx ) { ww=wy; adj_wx=false; }
25172 else { ww=wx; adj_wx=true;  }
25173
25174 @ This routine quickly tests if path |h| is ``essentially horizontal'' or
25175 ``essentially vertical,'' where |zoff| is |x_loc(0)| or |y_loc(0)| and |dz| is
25176 allowable range for $x$ or~$y$.  We do not need and cannot afford a full
25177 bounding-box computation.
25178
25179 @<Declare subroutines needed by |fix_graphics_state|@>=
25180 boolean mp_coord_rangeOK (MP mp,pointer h, 
25181                           small_number  zoff, scaled dz) {
25182   pointer p; /* for scanning the path form |h| */
25183   scaled zlo,zhi; /* coordinate range so far */
25184   scaled z; /* coordinate currently being tested */
25185   zlo=knot_coord(h+zoff);
25186   zhi=zlo;
25187   p=h;
25188   while ( right_type(p)!=endpoint ) {
25189     z=right_coord(p+zoff);
25190     @<Make |zlo..zhi| include |z| and |return false| if |zhi-zlo>dz|@>;
25191     p=link(p);
25192     z=left_coord(p+zoff);
25193     @<Make |zlo..zhi| include |z| and |return false| if |zhi-zlo>dz|@>;
25194     z=knot_coord(p+zoff);
25195     @<Make |zlo..zhi| include |z| and |return false| if |zhi-zlo>dz|@>;
25196     if ( p==h ) break;
25197   }
25198   return true;
25199 }
25200
25201 @ @<Make |zlo..zhi| include |z| and |return false| if |zhi-zlo>dz|@>=
25202 if ( z<zlo ) zlo=z;
25203 else if ( z>zhi ) zhi=z;
25204 if ( zhi-zlo>dz ) return false
25205
25206 @ Filling with an elliptical pen is implemented via a combination of \&{stroke}
25207 and \&{fill} commands and a nontrivial dash pattern would interfere with this.
25208 @:stroke}{\&{stroke} command@>
25209 @:fill}{\&{fill} command@>
25210 Note that we don't use |delete_edge_ref| because |gs_dash_p| is not counted as
25211 a reference.
25212
25213 @<Make sure \ps\ will use the right dash pattern for |dash_p(p)|@>=
25214 if ( type(p)==fill_code ) {
25215   hh=null;
25216 } else { 
25217   hh=dash_p(p);
25218   scf=mp_get_pen_scale(mp, pen_p(p));
25219   if ( scf==0 ) {
25220     if ( gs_width==0 ) scf=dash_scale(p);  else hh=null;
25221   } else { 
25222     scf=mp_make_scaled(mp, gs_width,scf);
25223     scf=mp_take_scaled(mp, scf,dash_scale(p));
25224   }
25225 }
25226 if ( hh==null ) {
25227   if ( gs_dash_p!=null ) {
25228     mp_ps_print_cmd(mp, " [] 0 setdash"," rd");
25229     gs_dash_p=null;
25230   }
25231 } else if ( (gs_dash_sc!=scf) || ! mp_same_dashes(mp, gs_dash_p,hh) ) {
25232   @<Set the dash pattern from |dash_list(hh)| scaled by |scf|@>;
25233 }
25234
25235 @ Translating a dash list into \ps\ is very similar to printing it symbolically
25236 in |print_edges|.  A dash pattern with |dash_y(hh)=0| has length zero and is
25237 ignored.  The same fate applies in the bizarre case of a dash pattern that
25238 cannot be printed without overflow.
25239
25240 @<Set the dash pattern from |dash_list(hh)| scaled by |scf|@>=
25241 { gs_dash_p=hh;
25242   gs_dash_sc=scf;
25243   if ( (dash_y(hh)==0) || (abs(dash_y(hh)) / unity >= el_gordo / scf)){
25244     mp_ps_print_cmd(mp, " [] 0 setdash"," rd");
25245   } else { 
25246     pp=dash_list(hh);
25247     start_x(null_dash)=start_x(pp)+dash_y(hh);
25248     ps_room(28);
25249     mp_print(mp, " [");
25250     while ( pp!=null_dash ) {
25251       mp_ps_pair_out(mp, mp_take_scaled(mp, stop_x(pp)-start_x(pp),scf),
25252                          mp_take_scaled(mp, start_x(link(pp))-stop_x(pp),scf));
25253       pp=link(pp);
25254     }
25255     ps_room(22);
25256     mp_print(mp, "] ");
25257     mp_print_scaled(mp, mp_take_scaled(mp, mp_dash_offset(mp, hh),scf));
25258     mp_print_cmd(mp, " setdash"," sd");
25259   }
25260 }
25261
25262 @ @<Declare subroutines needed by |fix_graphics_state|@>=
25263 boolean mp_same_dashes (MP mp,pointer h, pointer hh) ;
25264
25265 @ @c
25266 boolean mp_same_dashes (MP mp,pointer h, pointer hh) {
25267   /* do |h| and |hh| represent the same dash pattern? */
25268   pointer p,pp; /* dash nodes being compared */
25269   if ( h==hh ) return true;
25270   else if ( (h<=diov)||(hh<=diov) ) return false;
25271   else if ( dash_y(h)!=dash_y(hh) ) return false;
25272   else { @<Compare |dash_list(h)| and |dash_list(hh)|@>; }
25273   return false; /* can't happen */
25274 }
25275
25276 @ @<Compare |dash_list(h)| and |dash_list(hh)|@>=
25277 { p=dash_list(h);
25278   pp=dash_list(hh);
25279   while ( (p!=null_dash)&&(pp!=null_dash) ) {
25280     if ( (start_x(p)!=start_x(pp))||(stop_x(p)!=stop_x(pp)) ) {
25281       break;
25282     } else { 
25283       p=link(p);
25284       pp=link(pp);
25285     }
25286   }
25287   return (p==pp);
25288 }
25289
25290 @ When stroking a path with an elliptical pen, it is necessary to transform
25291 the coordinate system so that a unit circular pen will have the desired shape.
25292 To keep this transformation local, we enclose it in a
25293 $$\&{gsave}\ldots\&{grestore}$$
25294 block. Any translation component must be applied to the path being stroked
25295 while the rest of the transformation must apply only to the pen.
25296 If |fill_also=true|, the path is to be filled as well as stroked so we must
25297 insert commands to do this after giving the path.
25298
25299 @<Declare the \ps\ output procedures@>=
25300 void mp_stroke_ellipse (MP mp,pointer h, boolean fill_also) ;
25301
25302
25303 @c void mp_stroke_ellipse (MP mp,pointer h, boolean fill_also) {
25304   /* generate an elliptical pen stroke from object |h| */
25305   scaled txx,txy,tyx,tyy; /* transformation parameters */
25306   pointer p; /* the pen to stroke with */
25307   scaled d1,det; /* for tweaking transformation parameters */
25308   integer s; /* also for tweaking transformation paramters */
25309   boolean transformed; /* keeps track of whether gsave/grestore are needed */
25310   transformed=false;
25311   @<Use |pen_p(h)| to set the transformation parameters and give the initial
25312     translation@>;
25313   @<Tweak the transformation parameters so the transformation is nonsingular@>;
25314   mp_ps_path_out(mp, path_p(h));
25315   if ( mp->internal[mpprocset]==0 ) {
25316     if ( fill_also ) mp_print_nl(mp, "gsave fill grestore");
25317     @<Issue \ps\ commands to transform the coordinate system@>;
25318     mp_ps_print(mp, " stroke");
25319     if ( transformed ) mp_ps_print(mp, " grestore");
25320   } else {
25321     if ( fill_also ) mp_print_nl(mp, "B"); else mp_print_ln(mp);
25322     if ( (txy!=0)||(tyx!=0) ) {
25323       mp_print(mp, " [");
25324       mp_ps_pair_out(mp, txx,tyx);
25325       mp_ps_pair_out(mp, txy,tyy);
25326       mp_ps_print(mp, "0 0] t");
25327     } else if ((txx!=unity)||(tyy!=unity) )  {
25328       mp_ps_pair_out(mp,txx,tyy);
25329       mp_print(mp, " s");
25330     };
25331     mp_ps_print(mp, " S");
25332     if ( transformed ) mp_ps_print(mp, " Q");
25333   }
25334   mp_print_ln(mp);
25335 }
25336
25337 @ @<Use |pen_p(h)| to set the transformation parameters and give the...@>=
25338 p=pen_p(h);
25339 txx=left_x(p);
25340 tyx=left_y(p);
25341 txy=right_x(p);
25342 tyy=right_y(p);
25343 if ( (x_coord(p)!=0)||(y_coord(p)!=0) ) {
25344   mp_print_nl(mp, ""); mp_print_cmd(mp, "gsave ","q ");
25345   mp_ps_pair_out(mp, x_coord(p),y_coord(p));
25346   mp_ps_print(mp, "translate ");
25347   txx-=x_coord(p);
25348   tyx-=y_coord(p);
25349   txy-=x_coord(p);
25350   tyy-=y_coord(p);
25351   transformed=true;
25352 } else {
25353   mp_print_nl(mp, "");
25354 }
25355 @<Adjust the transformation to account for |gs_width| and output the
25356   initial \&{gsave} if |transformed| should be |true|@>
25357
25358 @ @<Adjust the transformation to account for |gs_width| and output the...@>=
25359 if ( gs_width!=unity ) {
25360   if ( gs_width==0 ) { 
25361     txx=unity; tyy=unity;
25362   } else { 
25363     txx=mp_make_scaled(mp, txx,gs_width);
25364     txy=mp_make_scaled(mp, txy,gs_width);
25365     tyx=mp_make_scaled(mp, tyx,gs_width);
25366     tyy=mp_make_scaled(mp, tyy,gs_width);
25367   };
25368 }
25369 if ( (txy!=0)||(tyx!=0)||(txx!=unity)||(tyy!=unity) ) {
25370   if ( (! transformed) ){ 
25371     mp_ps_print_cmd(mp, "gsave ","q ");
25372     transformed=true;
25373   }
25374 }
25375
25376 @ @<Issue \ps\ commands to transform the coordinate system@>=
25377 if ( (txy!=0)||(tyx!=0) ){ 
25378   mp_print_ln(mp);
25379   mp_print_char(mp, '[');
25380   mp_ps_pair_out(mp, txx,tyx);
25381   mp_ps_pair_out(mp, txy,tyy);
25382   mp_ps_print(mp, "0 0] concat");
25383 } else if ( (txx!=unity)||(tyy!=unity) ){ 
25384   mp_print_ln(mp);
25385   mp_ps_pair_out(mp, txx,tyy);
25386   mp_print(mp, "scale");
25387 }
25388
25389 @ The \ps\ interpreter will probably abort if it encounters a singular
25390 transformation matrix.  The determinant must be large enough to ensure that
25391 the printed representation will be nonsingular.  Since the printed
25392 representation is always within $2^{-17}$ of the internal |scaled| value, the
25393 total error is at most $4T_{\rm max}2^{-17}$, where $T_{\rm max}$ is a bound on
25394 the magnitudes of |txx/65536|, |txy/65536|, etc.
25395
25396 The |aspect_bound*(gs_width+1)| bound on the components of the pen
25397 transformation allows $T_{\rm max}$ to be at most |2*aspect_bound|.
25398
25399 @<Tweak the transformation parameters so the transformation is nonsingular@>=
25400 det=mp_take_scaled(mp, txx,tyy) - mp_take_scaled(mp, txy,tyx);
25401 d1=4*aspect_bound+1;
25402 if ( abs(det)<d1 ) { 
25403   if ( det>=0 ) { d1=d1-det; s=1;  }
25404   else { d1=-d1-det; s=-1;  };
25405   d1=d1*unity;
25406   if ( abs(txx)+abs(tyy)>=abs(txy)+abs(tyy) ) {
25407     if ( abs(txx)>abs(tyy) ) tyy=tyy+(d1+s*abs(txx)) / txx;
25408     else txx=txx+(d1+s*abs(tyy)) / tyy;
25409   } else {
25410     if ( abs(txy)>abs(tyx) ) tyx=tyx+(d1+s*abs(txy)) / txy;
25411     else txy=txy+(d1+s*abs(tyx)) / tyx;
25412   }
25413 }
25414
25415 @ Here is a simple routine that just fills a cycle.
25416
25417 @<Declare the \ps\ output procedures@>=
25418 void mp_ps_fill_out (MP mp,pointer p) ;
25419
25420 @ @c
25421 void mp_ps_fill_out (MP mp,pointer p) { /* fill cyclic path~|p| */
25422   mp_ps_path_out(mp, p);
25423   mp_ps_print_cmd(mp, " fill"," F");
25424   mp_print_ln(mp);
25425 }
25426
25427 @ Given a cyclic path~|p| and a graphical object~|h|, the |do_outer_envelope|
25428 procedure fills the cycle generated by |make_envelope|.  It need not do
25429 anything unless some region has positive winding number with respect to~|p|,
25430 but it does not seem worthwhile to for test this.
25431
25432 @<Declare the \ps\ output procedures@>=
25433 void mp_do_outer_envelope (MP mp,pointer p, pointer h) ;
25434
25435 @ @c
25436 void mp_do_outer_envelope (MP mp,pointer p, pointer h) {
25437   p=mp_make_envelope(mp, p, pen_p(h), ljoin_val(h), 0, miterlim_val(h));
25438   mp_ps_fill_out(mp, p);
25439   mp_toss_knot_list(mp, p);
25440 }
25441
25442 @ A text node may specify an arbitrary transformation but the usual case
25443 involves only shifting, scaling, and occasionally rotation.  The purpose
25444 of |choose_scale| is to select a scale factor so that the remaining
25445 transformation is as ``nice'' as possible.  The definition of ``nice''
25446 is somewhat arbitrary but shifting and $90^\circ$ rotation are especially
25447 nice because they work out well for bitmap fonts.  The code here selects
25448 a scale factor equal to $1/\sqrt2$ times the Frobenius norm of the
25449 non-shifting part of the transformation matrix.  It is careful to avoid
25450 additions that might cause undetected overflow.
25451
25452 @<Declare the \ps\ output procedures@>=
25453 scaled mp_choose_scale (MP mp,pointer p) ;
25454
25455 @ @c scaled mp_choose_scale (MP mp,pointer p) {
25456   /* |p| should point to a text node */
25457   scaled a,b,c,d,ad,bc; /* temporary values */
25458   a=txx_val(p);
25459   b=txy_val(p);
25460   c=tyx_val(p);
25461   d=tyy_val(p);
25462   if ( (a<0) ) negate(a);
25463   if ( (b<0) ) negate(b);
25464   if ( (c<0) ) negate(c);
25465   if ( (d<0) ) negate(d);
25466   ad=half(a-d);
25467   bc=half(b-c);
25468   return mp_pyth_add(mp, mp_pyth_add(mp, d+ad,ad), mp_pyth_add(mp, c+bc,bc));
25469 }
25470
25471 @ @<Declare the \ps\ output procedures@>=
25472 void mp_ps_string_out (MP mp, char *s) {
25473   char *i; /* current character code position */
25474   ASCII_code k; /* bits to be converted to octal */
25475   mp_print(mp, "(");
25476   i=s;
25477   while (*i) {
25478     if ( mp->ps_offset+5>mp->max_print_line ) {
25479       mp_print_char(mp, '\\');
25480       mp_print_ln(mp);
25481     }
25482     k=*i;
25483     if ( (@<Character |k| is not allowed in PostScript output@>) ) {
25484       mp_print_char(mp, '\\');
25485       mp_print_char(mp, '0'+(k / 64));
25486       mp_print_char(mp, '0'+((k / 8) % 8));
25487       mp_print_char(mp, '0'+(k % 8));
25488     } else { 
25489       if ( (k=='(')||(k==')')||(k=='\\') ) mp_print_char(mp, '\\');
25490       mp_print_char(mp, k);
25491     }
25492     incr(i);
25493   }
25494   mp_print_char(mp, ')');
25495 }
25496
25497
25498 @d mp_is_ps_name(M,A) mp_do_is_ps_name(A)
25499
25500 @<Declare the \ps\ output procedures@>=
25501 boolean mp_do_is_ps_name (char *s) {
25502   char *i; /* current character code position */
25503   ASCII_code k; /* the character being checked */
25504   i=s;
25505   while (*i) {
25506     k=*i;
25507     if ( (k<=' ')||(k>'~') ) return false;
25508     if ( (k=='(')||(k==')')||(k=='<')||(k=='>')||
25509        (k=='{')||(k=='}')||(k=='/')||(k=='%') ) return false;
25510     incr(i);
25511   }
25512   return true;
25513 }
25514
25515 @ @<Exported...@>=
25516 void mp_ps_name_out (MP mp, char *s, boolean lit) ;
25517
25518 @ @c
25519 void mp_ps_name_out (MP mp, char *s, boolean lit) {
25520   ps_room(strlen(s)+2);
25521   mp_print_char(mp, ' ');
25522   if ( mp_is_ps_name(mp, s) ) {
25523     if ( lit ) mp_print_char(mp, '/');
25524       mp_print(mp, s);
25525   } else { 
25526     mp_ps_string_out(mp, s);
25527     if ( ! lit ) mp_ps_print(mp, "cvx ");
25528       mp_ps_print(mp, "cvn");
25529   }
25530 }
25531
25532 @ @<Declare the \ps\ output procedures@>= 
25533 void mp_mark_string_chars (MP mp,font_number f, str_number s) ;
25534
25535 @ @c
25536 void mp_mark_string_chars (MP mp,font_number f, str_number s) {
25537   integer b; /* |char_base[f]| */
25538   ASCII_code bc,ec; /* only characters between these bounds are marked */
25539   pool_pointer k; /* an index into string |s| */
25540   b=mp->char_base[f];
25541   bc=mp->font_bc[f];
25542   ec=mp->font_ec[f];
25543   k=str_stop(s);
25544   while ( k>mp->str_start[s] ){ 
25545     decr(k);
25546     if ( (mp->str_pool[k]>=bc)&&(mp->str_pool[k]<=ec) )
25547       mp->font_info[b+mp->str_pool[k]].qqqq.b3=used;
25548   }
25549 }
25550
25551 @ There may be many sizes of one font and we need to keep track of the
25552 characters used for each size.  This is done by keeping a linked list of
25553 sizes for each font with a counter in each text node giving the appropriate
25554 position in the size list for its font.
25555
25556 @d sc_factor(A) mp->mem[(A)+1].sc /* the scale factor stored in a font size node */
25557 @d font_size_size 2 /* size of a font size node */
25558
25559 @ @<Exported...@>=
25560 boolean mp_has_font_size(MP mp, font_number f );
25561
25562 @ @c 
25563 boolean mp_has_font_size(MP mp, font_number f ) {
25564   return (mp->font_sizes[f]!=null);
25565 }
25566
25567
25568 @ The overflow here is caused by the fact the returned value
25569 has to fit in a |name_type|, which is a quarterword. 
25570
25571 @d fscale_tolerance 65 /* that's $.001\times2^{16}$ */
25572
25573 @<Declare the \ps\ output procedures@>=
25574 quarterword mp_size_index (MP mp, font_number f, scaled s) {
25575   pointer p,q; /* the previous and current font size nodes */
25576   quarterword i; /* the size index for |q| */
25577   q=mp->font_sizes[f];
25578   i=0;
25579   while ( q!=null ) {
25580     if ( abs(s-sc_factor(q))<=fscale_tolerance ) 
25581       return i;
25582     else 
25583       { p=q; q=link(q); incr(i); };
25584     if ( i==max_quarterword )
25585       mp_overflow(mp, "sizes per font",max_quarterword);
25586 @:MetaPost capacity exceeded sizes per font}{\quad sizes per font@>
25587   }
25588   q=mp_get_node(mp, font_size_size);
25589   sc_factor(q)=s;
25590   if ( i==0 ) mp->font_sizes[f]=q;  else link(p)=q;
25591   return i;
25592 }
25593
25594 @ @<Declare the \ps\ output procedures@>=
25595 scaled mp_indexed_size (MP mp,font_number f, quarterword j) {
25596   pointer p; /* a font size node */
25597   quarterword i; /* the size index for |p| */
25598   p=mp->font_sizes[f];
25599   i=0;
25600   if ( p==null ) mp_confusion(mp, "size");
25601   while ( (i!=j) ) { 
25602     incr(i); p=link(p);
25603     if ( p==null ) mp_confusion(mp, "size");
25604   }
25605   return sc_factor(p);
25606 }
25607
25608 @ @<Declare the \ps\ output procedures@>=
25609 void mp_clear_sizes (MP mp) ;
25610
25611 @ @c void mp_clear_sizes (MP mp) {
25612   font_number f;  /* the font whose size list is being cleared */
25613   pointer p;  /* current font size nodes */
25614   for (f=null_font+1;f<=mp->last_fnum;f++) {
25615     while ( mp->font_sizes[f]!=null ) {
25616       p=mp->font_sizes[f];
25617       mp->font_sizes[f]=link(p);
25618       mp_free_node(mp, p,font_size_size);
25619     }
25620   }
25621 }
25622
25623 @ The \&{special} command saves up lines of text to be printed during the next
25624 |ship_out| operation.  The saved items are stored as a list of capsule tokens.
25625
25626 @<Glob...@>=
25627 pointer last_pending; /* the last token in a list of pending specials */
25628
25629 @ @<Set init...@>=
25630 mp->last_pending=spec_head;
25631
25632 @ @<Cases of |do_statement|...@>=
25633 case special_command: 
25634   if ( mp->cur_mod==0 ) mp_do_special(mp); else 
25635   if ( mp->cur_mod==1 ) mp_do_mapfile(mp); else 
25636   mp_do_mapline(mp);
25637   break;
25638
25639 @ @<Declare action procedures for use by |do_statement|@>=
25640 void mp_do_special (MP mp) ;
25641
25642 @ @c void mp_do_special (MP mp) { 
25643   mp_get_x_next(mp); mp_scan_expression(mp);
25644   if ( mp->cur_type!=mp_string_type ) {
25645     @<Complain about improper special operation@>;
25646   } else { 
25647     link(mp->last_pending)=mp_stash_cur_exp(mp);
25648     mp->last_pending=link(mp->last_pending);
25649     link(mp->last_pending)=null;
25650   }
25651 }
25652
25653 @ @<Complain about improper special operation@>=
25654
25655   exp_err("Unsuitable expression");
25656   help1("Only known strings are allowed for output as specials.");
25657   mp_put_get_error(mp);
25658 }
25659
25660 @ @<Print any pending specials@>=
25661 t=link(spec_head);
25662 while ( t!=null ) {
25663   mp_print_str(mp, value(t));
25664   mp_print_ln(mp);
25665   t=link(t);
25666 }
25667 mp_flush_token_list(mp, link(spec_head));
25668 link(spec_head)=null;
25669 mp->last_pending=spec_head
25670
25671 @ We are now ready for the main output procedure.  Note that the |selector|
25672 setting is saved in a global variable so that |begin_diagnostic| can access it.
25673
25674 @<Declare the \ps\ output procedures@>=
25675 void mp_ship_out (MP mp, pointer h) ;
25676
25677 @ @c
25678 void mp_ship_out (MP mp, pointer h) { /* output edge structure |h| */
25679   pointer p; /* the current graphical object */
25680   pointer q; /* something that |p| points to */
25681   integer t; /* a temporary value */
25682   font_number f; /* fonts used in a text node or as loop counters */
25683   font_number ldf;
25684   scaled ds,scf; /* design size and scale factor for a text node */
25685   boolean transformed; /* is the coordinate system being transformed? */
25686   mp_open_output_file(mp);
25687   mp->non_ps_setting=mp->selector; mp->selector=ps_file_only;
25688   if ( (mp->internal[prologues]==two)||(mp->internal[prologues]==three) ) {
25689     @<Print improved initial comment and bounding box for edge structure~|h|@>;
25690     @<Scan all the text nodes and mark the used characters@>;
25691     mp_load_encodings(mp,mp->last_fnum);
25692     @<Update encoding names@>;
25693     @<Print the improved prologue and setup@>;
25694     @<Print any pending specials@>;
25695     mp_unknown_graphics_state(mp, 0);
25696     mp->need_newpath=true;
25697     p=link(dummy_loc(h));
25698     while ( p!=null ) { 
25699       if ( has_color(p) ) {
25700         if ( (pre_script(p))!=null ) {
25701           mp_print_nl (mp, str(pre_script(p))); mp_print_ln(mp);
25702         }
25703       }
25704       mp_fix_graphics_state(mp, p);
25705       switch (type(p)) {
25706       @<Cases for translating graphical object~|p| into \ps@>;
25707       case mp_start_bounds_code:
25708       case mp_stop_bounds_code:
25709             break;
25710       } /* all cases are enumerated */
25711       p=link(p);
25712     }
25713     mp_print_cmd(mp, "showpage","P"); mp_print_ln(mp);
25714     mp_print(mp, "%%EOF"); mp_print_ln(mp);
25715     fclose(mp->ps_file);
25716     mp->selector=mp->non_ps_setting;
25717     if ( mp->internal[prologues]<=0 ) mp_clear_sizes(mp);
25718     @<End progress report@>;
25719   } else {
25720     @<Print the initial comment and give the bounding box for edge structure~|h|@>;
25721     if ( (mp->internal[prologues]>0) && (mp->last_ps_fnum<mp->last_fnum) )
25722       mp_read_psname_table(mp);
25723     mp_print_prologue(mp, (mp->internal[prologues]>>16), (mp->internal[mpprocset]>>16), ldf);
25724     mp_print_nl(mp, "%%Page: 1 1"); mp_print_ln(mp);
25725     @<Print any pending specials@>;
25726     mp_unknown_graphics_state(mp, 0);
25727     mp->need_newpath=true;
25728     p=link(dummy_loc(h));
25729     while ( p!=null ) { 
25730       if ( has_color(p) ) {
25731         if ( (pre_script(p))!=null ) {
25732           mp_print_nl (mp, str(pre_script(p))); mp_print_ln(mp);
25733         }
25734       }
25735       mp_fix_graphics_state(mp, p);
25736       switch (type(p)) {
25737       @<Cases for translating graphical object~|p| into \ps@>;
25738       case mp_start_bounds_code:
25739       case mp_stop_bounds_code: 
25740         break;
25741       } /* all cases are enumerated */
25742       p=link(p);
25743     }
25744     mp_print_cmd(mp, "showpage","P"); mp_print_ln(mp);
25745     mp_print(mp, "%%EOF"); mp_print_ln(mp);
25746     fclose(mp->ps_file);
25747     mp->selector=mp->non_ps_setting;
25748     if ( mp->internal[prologues]<=0 ) mp_clear_sizes(mp);
25749     @<End progress report@>;
25750   }
25751   if ( mp->internal[tracing_output]>0 ) 
25752    mp_print_edges(mp, h," (just shipped out)",true);
25753 }
25754
25755 @ @<Exported...@>=
25756 void mp_apply_mark_string_chars(MP mp, pointer h, int next_size);
25757
25758 @ @c
25759 void mp_apply_mark_string_chars(MP mp, pointer h, int next_size) {
25760   pointer p;
25761   p=link(dummy_loc(h));
25762   while ( p!=null ) {
25763     if ( type(p)==text_code )
25764       if ( font_n(p)!=null_font )
25765         if ( name_type(p)==next_size )
25766           mp_mark_string_chars(mp, font_n(p),text_p(p));
25767     p=link(p);
25768   }
25769 }
25770
25771 @
25772 @<Print the improved prologue and setup@>=
25773 {
25774   mp_print_improved_prologue(mp, (mp->internal[prologues]>>16),(mp->internal[mpprocset]>>16),
25775                             (mp->internal[gtroffmode]>>16), null, h);
25776 }
25777
25778 @
25779 @<Print improved initial comment and bounding box for edge...@>=
25780 mp_print(mp, "%!PS-Adobe-3.0 EPSF-3.0");
25781 mp_print_nl(mp, "%%BoundingBox: ");
25782 mp_set_bbox(mp, h,true);
25783 if ( minx_val(h)>maxx_val(h) ) {
25784   mp_print(mp, "0 0 0 0");
25785 } else { 
25786   mp_ps_pair_out(mp, mp_floor_scaled(mp, minx_val(h)),mp_floor_scaled(mp, miny_val(h)));
25787   mp_ps_pair_out(mp, -mp_floor_scaled(mp, -maxx_val(h)),-mp_floor_scaled(mp, -maxy_val(h)));
25788 };
25789 mp_print_nl(mp, "%%HiResBoundingBox: ");
25790 if ( minx_val(h)>maxx_val(h) ) {
25791   mp_print(mp, "0 0 0 0");
25792 } else {
25793   mp_ps_pair_out(mp, minx_val(h),miny_val(h));
25794   mp_ps_pair_out(mp, maxx_val(h),maxy_val(h));
25795 }
25796 mp_print_nl(mp, "%%Creator: MetaPost ");
25797 mp_print(mp, metapost_version);
25798 mp_print_nl(mp, "%%CreationDate: ");
25799 mp_print_int(mp, mp_round_unscaled(mp, mp->internal[year])); mp_print_char(mp, '.');
25800 mp_print_dd(mp, mp_round_unscaled(mp, mp->internal[month])); mp_print_char(mp, '.');
25801 mp_print_dd(mp, mp_round_unscaled(mp, mp->internal[day])); mp_print_char(mp, ':');
25802 t=mp_round_unscaled(mp, mp->internal[mp_time]);
25803 mp_print_dd(mp, t / 60); mp_print_dd(mp, t % 60);
25804 mp_print_nl(mp, "%%Pages: 1");
25805
25806 @
25807
25808 @ @<Scan all the text nodes and mark the used ...@>=
25809 for (f=null_font+1;f<=mp->last_fnum;f++) {
25810   if ( mp->font_sizes[f]!=null ) {
25811     mp_unmark_font(mp, f);
25812     mp->font_sizes[f]=null;
25813   }
25814   if ( mp->font_enc_name[f]!=NULL )
25815      xfree(mp->font_enc_name[f]);
25816   mp->font_enc_name[f] = NULL;
25817 }
25818 for (f=null_font+1;f<=mp->last_fnum;f++) {
25819   p=link(dummy_loc(h));
25820   while ( p!=null ) {
25821     if ( type(p)==text_code ) {
25822       if ( font_n(p)!=null_font ) {
25823         mp->font_sizes[font_n(p)] = diov;
25824         mp_mark_string_chars(mp, font_n(p),text_p(p));
25825             if ( mp_has_fm_entry(mp,font_n(p),NULL) )
25826           mp->font_ps_name[font_n(p)] = mp_fm_font_name(mp,font_n(p));
25827       }
25828     }
25829     p=link(p);
25830   }
25831 }
25832
25833 @ @<Update encoding names@>=
25834 for (f=null_font+1;f<=mp->last_fnum;f++) {
25835   p=link(dummy_loc(h));
25836   while ( p!=null ) {
25837     if ( type(p)==text_code )
25838       if ( font_n(p)!=null_font )
25839             if ( mp_has_fm_entry(mp,font_n(p),NULL) )
25840           if ( mp->font_enc_name[font_n(p)]==NULL )
25841             mp->font_enc_name[font_n(p)] = mp_fm_encoding_name(mp,font_n(p));
25842     p=link(p);
25843   }
25844 }
25845
25846 @ These special comments described in the {\sl PostScript Language Reference
25847 Manual}, 2nd.~edition are understood by some \ps-reading programs.
25848 We can't normally output ``conforming'' \ps\ because
25849 the structuring conventions don't allow us to say ``Please make sure the
25850 following characters are downloaded and define the \.{fshow} macro to access
25851 them.''
25852
25853 The exact bounding box is written out if |prologues<0|, although this
25854 is not standard \ps, since it allows \TeX\ to calculate the box dimensions
25855 accurately. (Overfull boxes are avoided if an illustration is made to
25856 match a given \.{\char`\\hsize}.)
25857
25858 @<Print the initial comment and give the bounding box for edge...@>=
25859 mp_print(mp, "%!PS");
25860 if ( mp->internal[prologues]>0 ) mp_print(mp, "-Adobe-3.0 EPSF-3.0");
25861 mp_print_nl(mp, "%%BoundingBox: ");
25862 mp_set_bbox(mp, h,true);
25863 if ( minx_val(h)>maxx_val(h) ) mp_print(mp, "0 0 0 0");
25864 else if ( mp->internal[prologues]<0 ) {
25865   mp_ps_pair_out(mp, minx_val(h),miny_val(h));
25866   mp_ps_pair_out(mp, maxx_val(h),maxy_val(h));
25867 } else { 
25868   mp_ps_pair_out(mp, mp_floor_scaled(mp, minx_val(h)),mp_floor_scaled(mp, miny_val(h)));
25869   mp_ps_pair_out(mp, -mp_floor_scaled(mp, -maxx_val(h)),-mp_floor_scaled(mp, -maxy_val(h)));
25870 }
25871 mp_print_nl(mp, "%%HiResBoundingBox: ");
25872 if ( minx_val(h)>maxx_val(h) ) mp_print(mp, "0 0 0 0");
25873 else {
25874   mp_ps_pair_out(mp, minx_val(h),miny_val(h));
25875   mp_ps_pair_out(mp, maxx_val(h),maxy_val(h));
25876 }
25877 mp_print_nl(mp, "%%Creator: MetaPost ");
25878 mp_print(mp, metapost_version);
25879 mp_print_nl(mp, "%%CreationDate: ");
25880 mp_print_int(mp, mp_round_unscaled(mp, mp->internal[year])); mp_print_char(mp, '.');
25881 mp_print_dd(mp, mp_round_unscaled(mp, mp->internal[month])); mp_print_char(mp, '.');
25882 mp_print_dd(mp, mp_round_unscaled(mp, mp->internal[day])); mp_print_char(mp, ':');
25883 t=mp_round_unscaled(mp, mp->internal[mp_time]);
25884 mp_print_dd(mp, t / 60); mp_print_dd(mp, t % 60);
25885 mp_print_nl(mp, "%%Pages: 1");
25886 @<List all the fonts and magnifications for edge structure~|h|@>;
25887 mp_print_ln(mp)
25888
25889 @ @<List all the fonts and magnifications for edge structure~|h|@>=
25890 @<Scan all the text nodes and set the |font_sizes| lists;
25891   if |internal[prologues]<=0| list the sizes selected by |choose_scale|,
25892   apply |unmark_font| to each font encountered, and call |mark_string|
25893   whenever the size index is zero@>;
25894 ldf = mp_print_font_comments (mp, (mp->internal[prologues]>>16), null, h)
25895
25896 @ @<Scan all the text nodes and set the |font_sizes| lists;...@>=
25897 for (f=null_font+1;f<=mp->last_fnum;f++) 
25898   mp->font_sizes[f]=null;
25899 p=link(dummy_loc(h));
25900 while ( p!=null ) {
25901   if ( type(p)==text_code ) {
25902     if ( font_n(p)!=null_font ) {
25903       f=font_n(p);
25904       if ( mp->internal[prologues]>0 ) {
25905         mp->font_sizes[f]=diov;
25906       } else { 
25907         if ( mp->font_sizes[f]==null ) mp_unmark_font(mp, f);
25908         name_type(p)=mp_size_index(mp, f,mp_choose_scale(mp, p));
25909         if ( name_type(p)==0 )
25910           mp_mark_string_chars(mp, f,text_p(p));
25911       }
25912     }
25913   }
25914   p=link(p);
25915 }
25916
25917 @ @<Cases for translating graphical object~|p| into \ps@>=
25918 case mp_start_clip_code: 
25919   mp_print_nl(mp, ""); mp_print_cmd(mp, "gsave ","q ");
25920   mp_ps_path_out(mp, path_p(p));
25921   mp_ps_print_cmd(mp, " clip"," W");
25922   mp_print_ln(mp);
25923   if ( mp->internal[restore_clip_color]>0 )
25924     mp_unknown_graphics_state(mp, 1);
25925   break;
25926 case mp_stop_clip_code: 
25927   mp_print_nl(mp, ""); mp_print_cmd(mp, "grestore","Q");
25928   mp_print_ln(mp);
25929   if ( mp->internal[restore_clip_color]>0 )
25930     mp_unknown_graphics_state(mp, 2);
25931   else
25932     mp_unknown_graphics_state(mp, -1);
25933   break;
25934
25935 @ @<Cases for translating graphical object~|p| into \ps@>=
25936 case fill_code: 
25937   if ( pen_p(p)==null ) mp_ps_fill_out(mp, path_p(p));
25938   else if ( pen_is_elliptical(pen_p(p)) ) mp_stroke_ellipse(mp, p,true);
25939   else { 
25940     mp_do_outer_envelope(mp, mp_copy_path(mp, path_p(p)), p);
25941     mp_do_outer_envelope(mp, mp_htap_ypoc(mp, path_p(p)), p);
25942   }
25943   if ( (post_script(p))!=null ) {
25944     mp_print_nl (mp, str(post_script(p))); mp_print_ln(mp);
25945   };
25946   break;
25947 case stroked_code:
25948   if ( pen_is_elliptical(pen_p(p)) ) mp_stroke_ellipse(mp, p,false);
25949   else { 
25950     q=mp_copy_path(mp, path_p(p));
25951     t=lcap_val(p);
25952     @<Break the cycle and set |t:=1| if path |q| is cyclic@>;
25953     q=mp_make_envelope(mp, q,pen_p(p),ljoin_val(p),t,miterlim_val(p));
25954     mp_ps_fill_out(mp, q);
25955     mp_toss_knot_list(mp, q);
25956   };
25957   if ( (post_script(p))!=null ) {
25958     mp_print_nl (mp, str(post_script(p))); mp_print_ln(mp);
25959   };
25960   break;
25961
25962 @ The envelope of a cyclic path~|q| could be computed by calling
25963 |make_envelope| once for |q| and once for its reversal.  We don't do this
25964 because it would fail color regions that are covered by the pen regardless
25965 of where it is placed on~|q|.
25966
25967 @<Break the cycle and set |t:=1| if path |q| is cyclic@>=
25968 if ( left_type(q)!=endpoint ) { 
25969   left_type(mp_insert_knot(mp, q,x_coord(q),y_coord(q)))=endpoint;
25970   right_type(q)=endpoint;
25971   q=link(q);
25972   t=1;
25973 }
25974
25975 @ @<Cases for translating graphical object~|p| into \ps@>=
25976 case text_code: 
25977   if ( (font_n(p)!=null_font) && (length(text_p(p))>0) ) {
25978     if ( mp->internal[prologues]>0 )
25979       scf=mp_choose_scale(mp, p);
25980     else 
25981       scf=mp_indexed_size(mp, font_n(p), name_type(p));
25982     @<Shift or transform as necessary before outputting text node~|p| at scale
25983       factor~|scf|; set |transformed:=true| if the original transformation must
25984       be restored@>;
25985     mp_ps_string_out(mp, str(text_p(p)));
25986     mp_ps_name_out(mp, mp->font_name[font_n(p)],false);
25987     @<Print the size information and \ps\ commands for text node~|p|@>;
25988     mp_print_ln(mp);
25989   }
25990   if ( (post_script(p))!=null ) {
25991     mp_print_nl (mp, str(post_script(p))); mp_print_ln(mp);
25992   }
25993   break;
25994
25995 @ @<Print the size information and \ps\ commands for text node~|p|@>=
25996 ps_room(18);
25997 mp_print_char(mp, ' ');
25998 ds=(mp->font_dsize[font_n(p)]+8) / 16;
25999 mp_print_scaled(mp, mp_take_scaled(mp, ds,scf));
26000 mp_print(mp, " fshow");
26001 if ( transformed ) 
26002   mp_ps_print_cmd(mp, " grestore"," Q")
26003
26004 @ @<Shift or transform as necessary before outputting text node~|p| at...@>=
26005 transformed=(txx_val(p)!=scf)||(tyy_val(p)!=scf)||
26006             (txy_val(p)!=0)||(tyx_val(p)!=0);
26007 if ( transformed ) {
26008   mp_print_cmd(mp, "gsave [", "q [");
26009   mp_ps_pair_out(mp, mp_make_scaled(mp, txx_val(p),scf),
26010                      mp_make_scaled(mp, tyx_val(p),scf));
26011   mp_ps_pair_out(mp, mp_make_scaled(mp, txy_val(p),scf),
26012                      mp_make_scaled(mp, tyy_val(p),scf));
26013   mp_ps_pair_out(mp, tx_val(p),ty_val(p));
26014   mp_ps_print_cmd(mp, "] concat 0 0 moveto","] t 0 0 m");
26015 } else { 
26016   mp_ps_pair_out(mp, tx_val(p),ty_val(p));
26017   mp_ps_print_cmd(mp, "moveto","m");
26018 }
26019 mp_print_ln(mp)
26020
26021 @ Now that we've finished |ship_out|, let's look at the other commands
26022 by which a user can send things to the \.{GF} file.
26023
26024 @ @<Determine if a character has been shipped out@>=
26025
26026   mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256;
26027   if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
26028   boolean_reset(mp->char_exists[mp->cur_exp]);
26029   mp->cur_type=mp_boolean_type;
26030 }
26031
26032 @ @<Glob...@>=
26033 psout_data ps;
26034
26035 @ @<Allocate or initialize ...@>=
26036 mp_backend_initialize(mp);
26037
26038 @ @<Dealloc...@>=
26039 mp_backend_free(mp);
26040
26041
26042 @* \[45] Dumping and undumping the tables.
26043 After \.{INIMP} has seen a collection of macros, it
26044 can write all the necessary information on an auxiliary file so
26045 that production versions of \MP\ are able to initialize their
26046 memory at high speed. The present section of the program takes
26047 care of such output and input. We shall consider simultaneously
26048 the processes of storing and restoring,
26049 so that the inverse relation between them is clear.
26050 @.INIMP@>
26051
26052 The global variable |mem_ident| is a string that is printed right
26053 after the |banner| line when \MP\ is ready to start. For \.{INIMP} this
26054 string says simply `\.{(INIMP)}'; for other versions of \MP\ it says,
26055 for example, `\.{(mem=plain 90.4.14)}', showing the year,
26056 month, and day that the mem file was created. We have |mem_ident=0|
26057 before \MP's tables are loaded.
26058
26059 @<Glob...@>=
26060 char * mem_ident;
26061
26062 @ @<Set init...@>=
26063 mp->mem_ident=NULL;
26064
26065 @ @<Initialize table entries...@>=
26066 if (mp->ini_version) 
26067   mp->mem_ident=xstrdup(" (INIMP)");
26068
26069 @ @<Declare act...@>=
26070 void mp_store_mem_file (MP mp) ;
26071
26072 @ @c void mp_store_mem_file (MP mp) {
26073   integer k;  /* all-purpose index */
26074   pointer p,q; /* all-purpose pointers */
26075   integer x; /* something to dump */
26076   four_quarters w; /* four ASCII codes */
26077   memory_word WW;
26078   @<Create the |mem_ident|, open the mem file,
26079     and inform the user that dumping has begun@>;
26080   @<Dump constants for consistency check@>;
26081   @<Dump the string pool@>;
26082   @<Dump the dynamic memory@>;
26083   @<Dump the table of equivalents and the hash table@>;
26084   @<Dump a few more things and the closing check word@>;
26085   @<Close the mem file@>;
26086 }
26087
26088 @ Corresponding to the procedure that dumps a mem file, we also have a function
26089 that reads~one~in. The function returns |false| if the dumped mem is
26090 incompatible with the present \MP\ table sizes, etc.
26091
26092 @d off_base 6666 /* go here if the mem file is unacceptable */
26093 @d too_small(A) { wake_up_terminal;
26094   wterm_ln("---! Must increase the "); wterm((A));
26095 @.Must increase the x@>
26096   goto OFF_BASE;
26097   }
26098
26099 @c 
26100 boolean mp_load_mem_file (MP mp) {
26101   integer k; /* all-purpose index */
26102   pointer p,q; /* all-purpose pointers */
26103   integer x; /* something undumped */
26104   str_number s; /* some temporary string */
26105   four_quarters w; /* four ASCII codes */
26106   memory_word WW;
26107   @<Undump constants for consistency check@>;
26108   @<Undump the string pool@>;
26109   @<Undump the dynamic memory@>;
26110   @<Undump the table of equivalents and the hash table@>;
26111   @<Undump a few more things and the closing check word@>;
26112   return true; /* it worked! */
26113 OFF_BASE: 
26114   wake_up_terminal;
26115   wterm_ln("(Fatal mem file error; I'm stymied)\n");
26116 @.Fatal mem file error@>
26117    return false;
26118 }
26119
26120 @ @<Declarations@>=
26121 boolean mp_load_mem_file (MP mp) ;
26122
26123 @ Mem files consist of |memory_word| items, and we use the following
26124 macros to dump words of different types:
26125
26126 @d dump_wd(A)   { WW=(A);      fwrite(&WW,sizeof(WW),1,mp->mem_file); }
26127 @d dump_int(A)  { WW.cint=(A); fwrite(&WW,sizeof(WW),1,mp->mem_file); }
26128 @d dump_hh(A)   { WW.hh=(A);   fwrite(&WW,sizeof(WW),1,mp->mem_file); }
26129 @d dump_qqqq(A) { WW.qqqq=(A); fwrite(&WW,sizeof(WW),1,mp->mem_file); }
26130 @d dump_string(A) { dump_int(strlen(A)+1);
26131                     fwrite(A,strlen(A)+1,1,mp->mem_file); }
26132
26133 @<Glob...@>=
26134 FILE * mem_file; /* for input or output of mem information */
26135
26136 @ The inverse macros are slightly more complicated, since we need to check
26137 the range of the values we are reading in. We say `|undump(a)(b)(x)|' to
26138 read an integer value |x| that is supposed to be in the range |a<=x<=b|.
26139
26140 @d undump_wd(A)   { fread(&WW,sizeof(WW),1,mp->mem_file); (A)=WW; }
26141 @d undump_int(A)  { fread(&WW,sizeof(WW),1,mp->mem_file); (A)=WW.cint; }
26142 @d undump_hh(A)   { fread(&WW,sizeof(WW),1,mp->mem_file); (A)=WW.hh; }
26143 @d undump_qqqq(A) { fread(&WW,sizeof(WW),1,mp->mem_file); (A)=WW.qqqq; }
26144 @d undump_strings(A,B,C) { 
26145    undump_int(x); if ( (x<(A)) || (x>(B)) ) goto OFF_BASE; else (C)=str(x); }
26146 @d undump(A,B,C) { undump_int(x); if ( (x<(A)) || (x>(int)(B)) ) goto OFF_BASE; else (C)=x; }
26147 @d undump_size(A,B,C,D) { undump_int(x);
26148                if (x<(A)) goto OFF_BASE; 
26149                if (x>(B)) { too_small((C)); } else {(D)=x;} }
26150 @d undump_string(A) { integer XX=0; undump_int(XX);
26151                       A = xmalloc(XX,sizeof(char));
26152                       fread(A,XX,1,mp->mem_file); }
26153
26154 @ The next few sections of the program should make it clear how we use the
26155 dump/undump macros.
26156
26157 @<Dump constants for consistency check@>=
26158 dump_int(mp->mem_top);
26159 dump_int(mp->hash_size);
26160 dump_int(mp->hash_prime)
26161 dump_int(mp->param_size);
26162 dump_int(mp->max_in_open);
26163
26164 @ Sections of a \.{WEB} program that are ``commented out'' still contribute
26165 strings to the string pool; therefore \.{INIMP} and \MP\ will have
26166 the same strings. (And it is, of course, a good thing that they do.)
26167 @.WEB@>
26168 @^string pool@>
26169
26170 @<Undump constants for consistency check@>=
26171 undump_int(x); mp->mem_top = x;
26172 undump_int(x); if (mp->hash_size != x) goto OFF_BASE;
26173 undump_int(x); if (mp->hash_prime != x) goto OFF_BASE;
26174 undump_int(x); if (mp->param_size != x) goto OFF_BASE;
26175 undump_int(x); if (mp->max_in_open != x) goto OFF_BASE
26176
26177 @ We do string pool compaction to avoid dumping unused strings.
26178
26179 @d dump_four_ASCII 
26180   w.b0=qi(mp->str_pool[k]); w.b1=qi(mp->str_pool[k+1]);
26181   w.b2=qi(mp->str_pool[k+2]); w.b3=qi(mp->str_pool[k+3]);
26182   dump_qqqq(w)
26183
26184 @<Dump the string pool@>=
26185 mp_do_compaction(mp, mp->pool_size);
26186 dump_int(mp->pool_ptr);
26187 dump_int(mp->max_str_ptr);
26188 dump_int(mp->str_ptr);
26189 k=0;
26190 while ( (mp->next_str[k]==k+1) && (k<=mp->max_str_ptr) ) 
26191   incr(k);
26192 dump_int(k);
26193 while ( k<=mp->max_str_ptr ) { 
26194   dump_int(mp->next_str[k]); incr(k);
26195 }
26196 k=0;
26197 while (1)  { 
26198   dump_int((mp->str_start[k])); 
26199   if ( k==mp->str_ptr ) {
26200     break;
26201   } else { 
26202     k=mp->next_str[k]; 
26203   }
26204 };
26205 k=0;
26206 while (k+4<mp->pool_ptr ) { 
26207   dump_four_ASCII; k=k+4; 
26208 }
26209 k=mp->pool_ptr-4; dump_four_ASCII;
26210 mp_print_ln(mp); mp_print(mp, "at most "); mp_print_int(mp, mp->max_str_ptr);
26211 mp_print(mp, " strings of total length ");
26212 mp_print_int(mp, mp->pool_ptr)
26213
26214 @ @d undump_four_ASCII 
26215   undump_qqqq(w);
26216   mp->str_pool[k]=qo(w.b0); mp->str_pool[k+1]=qo(w.b1);
26217   mp->str_pool[k+2]=qo(w.b2); mp->str_pool[k+3]=qo(w.b3)
26218
26219 @<Undump the string pool@>=
26220 undump_int(mp->pool_ptr);
26221 mp_reallocate_pool(mp, mp->pool_ptr) ;
26222 undump_int(mp->max_str_ptr);
26223 mp_reallocate_strings (mp,mp->max_str_ptr) ;
26224 undump(0,mp->max_str_ptr,mp->str_ptr);
26225 undump(0,mp->max_str_ptr+1,s);
26226 for (k=0;k<=s-1;k++) 
26227   mp->next_str[k]=k+1;
26228 for (k=s;k<=mp->max_str_ptr;k++) 
26229   undump(s+1,mp->max_str_ptr+1,mp->next_str[k]);
26230 mp->fixed_str_use=0;
26231 k=0;
26232 while (1) { 
26233   undump(0,mp->pool_ptr,mp->str_start[k]);
26234   if ( k==mp->str_ptr ) break;
26235   mp->str_ref[k]=max_str_ref;
26236   incr(mp->fixed_str_use);
26237   mp->last_fixed_str=k; k=mp->next_str[k];
26238 }
26239 k=0;
26240 while ( k+4<mp->pool_ptr ) { 
26241   undump_four_ASCII; k=k+4;
26242 }
26243 k=mp->pool_ptr-4; undump_four_ASCII;
26244 mp->init_str_use=mp->fixed_str_use; mp->init_pool_ptr=mp->pool_ptr;
26245 mp->max_pool_ptr=mp->pool_ptr;
26246 mp->strs_used_up=mp->fixed_str_use;
26247 mp->pool_in_use=mp->str_start[mp->str_ptr]; mp->strs_in_use=mp->fixed_str_use;
26248 mp->max_pl_used=mp->pool_in_use; mp->max_strs_used=mp->strs_in_use;
26249 mp->pact_count=0; mp->pact_chars=0; mp->pact_strs=0;
26250
26251 @ By sorting the list of available spaces in the variable-size portion of
26252 |mem|, we are usually able to get by without having to dump very much
26253 of the dynamic memory.
26254
26255 We recompute |var_used| and |dyn_used|, so that \.{INIMP} dumps valid
26256 information even when it has not been gathering statistics.
26257
26258 @<Dump the dynamic memory@>=
26259 mp_sort_avail(mp); mp->var_used=0;
26260 dump_int(mp->lo_mem_max); dump_int(mp->rover);
26261 p=0; q=mp->rover; x=0;
26262 do {  
26263   for (k=p;k<= q+1;k++) 
26264     dump_wd(mp->mem[k]);
26265   x=x+q+2-p; mp->var_used=mp->var_used+q-p;
26266   p=q+node_size(q); q=rlink(q);
26267 } while (q!=mp->rover);
26268 mp->var_used=mp->var_used+mp->lo_mem_max-p; 
26269 mp->dyn_used=mp->mem_end+1-mp->hi_mem_min;
26270 for (k=p;k<= mp->lo_mem_max;k++ ) 
26271   dump_wd(mp->mem[k]);
26272 x=x+mp->lo_mem_max+1-p;
26273 dump_int(mp->hi_mem_min); dump_int(mp->avail);
26274 for (k=mp->hi_mem_min;k<=mp->mem_end;k++ ) 
26275   dump_wd(mp->mem[k]);
26276 x=x+mp->mem_end+1-mp->hi_mem_min;
26277 p=mp->avail;
26278 while ( p!=null ) { 
26279   decr(mp->dyn_used); p=link(p);
26280 }
26281 dump_int(mp->var_used); dump_int(mp->dyn_used);
26282 mp_print_ln(mp); mp_print_int(mp, x);
26283 mp_print(mp, " memory locations dumped; current usage is ");
26284 mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used)
26285
26286 @ @<Undump the dynamic memory@>=
26287 undump(lo_mem_stat_max+1000,hi_mem_stat_min-1,mp->lo_mem_max);
26288 undump(lo_mem_stat_max+1,mp->lo_mem_max,mp->rover);
26289 p=0; q=mp->rover;
26290 do {  
26291   for (k=p;k<= q+1; k++) 
26292     undump_wd(mp->mem[k]);
26293   p=q+node_size(q);
26294   if ( (p>mp->lo_mem_max)||((q>=rlink(q))&&(rlink(q)!=mp->rover)) ) 
26295     goto OFF_BASE;
26296   q=rlink(q);
26297 } while (q!=mp->rover);
26298 for (k=p;k<=mp->lo_mem_max;k++ ) 
26299   undump_wd(mp->mem[k]);
26300 undump(mp->lo_mem_max+1,hi_mem_stat_min,mp->hi_mem_min);
26301 undump(null,mp->mem_top,mp->avail); mp->mem_end=mp->mem_top;
26302 for (k=mp->hi_mem_min;k<= mp->mem_end;k++) 
26303   undump_wd(mp->mem[k]);
26304 undump_int(mp->var_used); undump_int(mp->dyn_used)
26305
26306 @ A different scheme is used to compress the hash table, since its lower region
26307 is usually sparse. When |text(p)<>0| for |p<=hash_used|, we output three
26308 words: |p|, |hash[p]|, and |eqtb[p]|. The hash table is, of course, densely
26309 packed for |p>=hash_used|, so the remaining entries are output in~a~block.
26310
26311 @<Dump the table of equivalents and the hash table@>=
26312 dump_int(mp->hash_used); 
26313 mp->st_count=frozen_inaccessible-1-mp->hash_used;
26314 for (p=1;p<=mp->hash_used;p++) {
26315   if ( text(p)!=0 ) {
26316      dump_int(p); dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]); incr(mp->st_count);
26317   }
26318 }
26319 for (p=mp->hash_used+1;p<=(int)hash_end;p++) {
26320   dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]);
26321 }
26322 dump_int(mp->st_count);
26323 mp_print_ln(mp); mp_print_int(mp, mp->st_count); mp_print(mp, " symbolic tokens")
26324
26325 @ @<Undump the table of equivalents and the hash table@>=
26326 undump(1,frozen_inaccessible,mp->hash_used); 
26327 p=0;
26328 do {  
26329   undump(p+1,mp->hash_used,p); 
26330   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
26331 } while (p!=mp->hash_used);
26332 for (p=mp->hash_used+1;p<=(int)hash_end;p++ )  { 
26333   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
26334 }
26335 undump_int(mp->st_count)
26336
26337 @ We have already printed a lot of statistics, so we set |tracing_stats:=0|
26338 to prevent them appearing again.
26339
26340 @<Dump a few more things and the closing check word@>=
26341 dump_int(mp->max_internal);
26342 dump_int(mp->int_ptr);
26343 for (k=1;k<= mp->int_ptr;k++ ) { 
26344   dump_int(mp->internal[k]); 
26345   dump_string(mp->int_name[k]);
26346 }
26347 dump_int(mp->start_sym); 
26348 dump_int(mp->interaction); 
26349 dump_string(mp->mem_ident);
26350 dump_int(mp->bg_loc); dump_int(mp->eg_loc); dump_int(mp->serial_no); dump_int(69073);
26351 mp->internal[tracing_stats]=0
26352
26353 @ @<Undump a few more things and the closing check word@>=
26354 undump_int(x);
26355 if (x>mp->max_internal) mp_grow_internals(mp,x);
26356 undump_int(mp->int_ptr);
26357 for (k=1;k<= mp->int_ptr;k++) { 
26358   undump_int(mp->internal[k]);
26359   undump_string(mp->int_name[k]);
26360 }
26361 undump(0,frozen_inaccessible,mp->start_sym);
26362 if (mp->interaction==mp_unspecified_mode) {
26363   undump(mp_unspecified_mode,mp_error_stop_mode,mp->interaction);
26364 } else {
26365   undump(mp_unspecified_mode,mp_error_stop_mode,x);
26366 }
26367 undump_string(mp->mem_ident);
26368 undump(1,hash_end,mp->bg_loc);
26369 undump(1,hash_end,mp->eg_loc);
26370 undump_int(mp->serial_no);
26371 undump_int(x); 
26372 if ( (x!=69073)|| feof(mp->mem_file) ) goto OFF_BASE
26373
26374 @ @<Create the |mem_ident|...@>=
26375
26376   xfree(mp->mem_ident);
26377   mp->mem_ident = xmalloc(256,1);
26378   snprintf(mp->mem_ident,256," (mem=%s %i.%i.%i)", 
26379            mp->job_name,
26380            (int)(mp_round_unscaled(mp, mp->internal[year]) % 100),
26381            (int)mp_round_unscaled(mp, mp->internal[month]),
26382            (int)mp_round_unscaled(mp, mp->internal[day]));
26383   mp_pack_job_name(mp, mem_extension);
26384   while (! mp_w_open_out(mp, &mp->mem_file) )
26385     mp_prompt_file_name(mp, "mem file name", mem_extension);
26386   mp_print_nl(mp, "Beginning to dump on file ");
26387 @.Beginning to dump...@>
26388   mp_print(mp, mp->name_of_file); 
26389   mp_print_nl(mp, mp->mem_ident);
26390 }
26391
26392 @ @<Dealloc variables@>=
26393 xfree(mp->mem_ident);
26394
26395 @ @<Close the mem file@>=
26396 fclose(mp->mem_file)
26397
26398 @* \[46] The main program.
26399 This is it: the part of \MP\ that executes all those procedures we have
26400 written.
26401
26402 Well---almost. We haven't put the parsing subroutines into the
26403 program yet; and we'd better leave space for a few more routines that may
26404 have been forgotten.
26405
26406 @c @<Declare the basic parsing subroutines@>;
26407 @<Declare miscellaneous procedures that were declared |forward|@>;
26408 @<Last-minute procedures@>
26409
26410 @ We've noted that there are two versions of \MP. One, called \.{INIMP},
26411 @.INIMP@>
26412 has to be run first; it initializes everything from scratch, without
26413 reading a mem file, and it has the capability of dumping a mem file.
26414 The other one is called `\.{VIRMP}'; it is a ``virgin'' program that needs
26415 @.VIRMP@>
26416 to input a mem file in order to get started. \.{VIRMP} typically has
26417 a bit more memory capacity than \.{INIMP}, because it does not need the
26418 space consumed by the dumping/undumping routines and the numerous calls on
26419 |primitive|, etc.
26420
26421 The \.{VIRMP} program cannot read a mem file instantaneously, of course;
26422 the best implementations therefore allow for production versions of \MP\ that
26423 not only avoid the loading routine for \PASCAL\ object code, they also have
26424 a mem file pre-loaded. 
26425
26426 @<Glob...@>=
26427 boolean ini_version; /* are we iniMP? */
26428
26429 @ @<Option variables@>=
26430 boolean ini_version; /* are we iniMP? */
26431
26432 @ @<Set |ini_version|@>=
26433 mp->ini_version = (opt.ini_version ? true : false);
26434
26435 @ Here we do whatever is needed to complete \MP's job gracefully on the
26436 local operating system. The code here might come into play after a fatal
26437 error; it must therefore consist entirely of ``safe'' operations that
26438 cannot produce error messages. For example, it would be a mistake to call
26439 |str_room| or |make_string| at this time, because a call on |overflow|
26440 might lead to an infinite loop.
26441 @^system dependencies@>
26442
26443 This program doesn't bother to close the input files that may still be open.
26444
26445 @<Last-minute...@>=
26446 void mp_close_files_and_terminate (MP mp) {
26447   integer k; /* all-purpose index */
26448   integer LH; /* the length of the \.{TFM} header, in words */
26449   int lk_offset; /* extra words inserted at beginning of |lig_kern| array */
26450   pointer p; /* runs through a list of \.{TFM} dimensions */
26451   @<Close all open files in the |rd_file| and |wr_file| arrays@>;
26452   if ( mp->internal[tracing_stats]>0 )
26453     @<Output statistics about this job@>;
26454   wake_up_terminal; 
26455   @<Do all the finishing work on the \.{TFM} file@>;
26456   @<Explain what output files were written@>;
26457   if ( mp->log_opened ){ 
26458     wlog_cr;
26459     fclose(mp->log_file); mp->selector=mp->selector-2;
26460     if ( mp->selector==term_only ) {
26461       mp_print_nl(mp, "Transcript written on ");
26462 @.Transcript written...@>
26463       mp_print(mp, mp->log_name); mp_print_char(mp, '.');
26464     }
26465   }
26466   mp_print_ln(mp);
26467 }
26468
26469 @ @<Declarations@>=
26470 void mp_close_files_and_terminate (MP mp) ;
26471
26472 @ @<Close all open files in the |rd_file| and |wr_file| arrays@>=
26473 for (k=0;k<=(int)mp->read_files-1;k++ ) {
26474   if ( mp->rd_fname[k]!=NULL ) fclose(mp->rd_file[k]);
26475 }
26476 for (k=0;k<=(int)mp->write_files-1;k++) {
26477   if ( mp->wr_fname[k]!=NULL ) fclose(mp->wr_file[k]);
26478 }
26479
26480 @ We want to produce a \.{TFM} file if and only if |fontmaking| is positive.
26481
26482 We reclaim all of the variable-size memory at this point, so that
26483 there is no chance of another memory overflow after the memory capacity
26484 has already been exceeded.
26485
26486 @<Do all the finishing work on the \.{TFM} file@>=
26487 if ( mp->internal[fontmaking]>0 ) {
26488   @<Make the dynamic memory into one big available node@>;
26489   @<Massage the \.{TFM} widths@>;
26490   mp_fix_design_size(mp); mp_fix_check_sum(mp);
26491   @<Massage the \.{TFM} heights, depths, and italic corrections@>;
26492   mp->internal[fontmaking]=0; /* avoid loop in case of fatal error */
26493   @<Finish the \.{TFM} file@>;
26494 }
26495
26496 @ @<Make the dynamic memory into one big available node@>=
26497 mp->rover=lo_mem_stat_max+1; link(mp->rover)=empty_flag; mp->lo_mem_max=mp->hi_mem_min-1;
26498 if ( mp->lo_mem_max-mp->rover>max_halfword ) mp->lo_mem_max=max_halfword+mp->rover;
26499 node_size(mp->rover)=mp->lo_mem_max-mp->rover; 
26500 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
26501 link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null
26502
26503 @ The present section goes directly to the log file instead of using
26504 |print| commands, because there's no need for these strings to take
26505 up |str_pool| memory when a non-{\bf stat} version of \MP\ is being used.
26506
26507 @<Output statistics...@>=
26508 if ( mp->log_opened ) { 
26509   char s[128];
26510   wlog_ln(" ");
26511   wlog_ln("Here is how much of MetaPost's memory you used:");
26512 @.Here is how much...@>
26513   snprintf(s,128," %i string%s out of %i",(int)mp->max_strs_used-mp->init_str_use,
26514           (mp->max_strs_used!=mp->init_str_use+1 ? "s" : ""),
26515           (int)(mp->max_strings-1-mp->init_str_use));
26516   wlog_ln(s);
26517   snprintf(s,128," %i string characters out of %i",
26518            (int)mp->max_pl_used-mp->init_pool_ptr,
26519            (int)mp->pool_size-mp->init_pool_ptr);
26520   wlog_ln(s);
26521   snprintf(s,128," %i words of memory out of %i",
26522            (int)mp->lo_mem_max+mp->mem_end-mp->hi_mem_min+2,
26523            (int)mp->mem_end+1);
26524   wlog_ln(s);
26525   snprintf(s,128," %i symbolic tokens out of %i", (int)mp->st_count, (int)mp->hash_size);
26526   wlog_ln(s);
26527   snprintf(s,128," %ii, %in, %ip, %ib stack positions out of %ii, %in, %ip, %ib",
26528            (int)mp->max_in_stack,(int)mp->int_ptr,
26529            (int)mp->max_param_stack,(int)mp->max_buf_stack+1,
26530            (int)mp->stack_size,(int)mp->max_internal,(int)mp->param_size,(int)mp->buf_size);
26531   wlog_ln(s);
26532   snprintf(s,128," %i string compactions (moved %i characters, %i strings)",
26533           (int)mp->pact_count,(int)mp->pact_chars,(int)mp->pact_strs);
26534   wlog_ln(s);
26535 }
26536
26537 @ We get to the |final_cleanup| routine when \&{end} or \&{dump} has
26538 been scanned.
26539
26540 @<Last-minute...@>=
26541 void mp_final_cleanup (MP mp) {
26542   small_number c; /* 0 for \&{end}, 1 for \&{dump} */
26543   c=mp->cur_mod;
26544   if ( mp->job_name==NULL ) mp_open_log_file(mp);
26545   while ( mp->input_ptr>0 ) {
26546     if ( token_state ) mp_end_token_list(mp);
26547     else  mp_end_file_reading(mp);
26548   }
26549   while ( mp->loop_ptr!=null ) mp_stop_iteration(mp);
26550   while ( mp->open_parens>0 ) { 
26551     mp_print(mp, " )"); decr(mp->open_parens);
26552   };
26553   while ( mp->cond_ptr!=null ) {
26554     mp_print_nl(mp, "(end occurred when ");
26555 @.end occurred...@>
26556     mp_print_cmd_mod(mp, fi_or_else,mp->cur_if);
26557     /* `\.{if}' or `\.{elseif}' or `\.{else}' */
26558     if ( mp->if_line!=0 ) {
26559       mp_print(mp, " on line "); mp_print_int(mp, mp->if_line);
26560     }
26561     mp_print(mp, " was incomplete)");
26562     mp->if_line=if_line_field(mp->cond_ptr);
26563     mp->cur_if=name_type(mp->cond_ptr); mp->cond_ptr=link(mp->cond_ptr);
26564   }
26565   if ( mp->history!=spotless )
26566     if ( ((mp->history==warning_issued)||(mp->interaction<mp_error_stop_mode)) )
26567       if ( mp->selector==term_and_log ) {
26568     mp->selector=term_only;
26569     mp_print_nl(mp, "(see the transcript file for additional information)");
26570 @.see the transcript file...@>
26571     mp->selector=term_and_log;
26572   }
26573   if ( c==1 ) {
26574     if (mp->ini_version) {
26575       mp_store_mem_file(mp); return;
26576     }
26577     mp_print_nl(mp, "(dump is performed only by INIMP)"); return;
26578 @.dump...only by INIMP@>
26579   }
26580 }
26581
26582 @ @<Declarations@>=
26583 void mp_final_cleanup (MP mp) ;
26584 void mp_init_prim (MP mp) ;
26585 void mp_init_tab (MP mp) ;
26586
26587 @ @<Last-minute...@>=
26588 void mp_init_prim (MP mp) { /* initialize all the primitives */
26589   @<Put each...@>;
26590 }
26591 @#
26592 void mp_init_tab (MP mp) { /* initialize other tables */
26593   integer k; /* all-purpose index */
26594   @<Initialize table entries (done by \.{INIMP} only)@>;
26595 }
26596
26597
26598 @ When we begin the following code, \MP's tables may still contain garbage;
26599 the strings might not even be present. Thus we must proceed cautiously to get
26600 bootstrapped in.
26601
26602 But when we finish this part of the program, \MP\ is ready to call on the
26603 |main_control| routine to do its work.
26604
26605 @<Get the first line...@>=
26606
26607   @<Initialize the input routines@>;
26608   if ( (mp->mem_ident==NULL)||(mp->buffer[loc]=='&') ) {
26609     if ( mp->mem_ident!=NULL ) mp_initialize(mp); /* erase preloaded mem */
26610     if ( ! mp_open_mem_file(mp) ) return false;
26611     if ( ! mp_load_mem_file(mp) ) {
26612       fclose( mp->mem_file); return false;
26613     }
26614     fclose( mp->mem_file);
26615     while ( (loc<limit)&&(mp->buffer[loc]==' ') ) incr(loc);
26616   }
26617   mp->buffer[limit]='%';
26618   mp_fix_date_and_time(mp);
26619   mp->sys_random_seed = (mp->get_random_seed)(mp);
26620   mp_init_randoms(mp, mp->sys_random_seed);
26621   @<Initialize the print |selector|...@>;
26622   if ( loc<limit ) if ( mp->buffer[loc]!='\\' ) 
26623     mp_start_input(mp); /* \&{input} assumed */
26624 }
26625
26626 @ @<Run inimpost commands@>=
26627 {
26628   mp_get_strings_started(mp);
26629   mp_init_tab(mp); /* initialize the tables */
26630   mp_init_prim(mp); /* call |primitive| for each primitive */
26631   mp->init_str_use=mp->str_ptr; mp->init_pool_ptr=mp->pool_ptr;
26632   mp->max_str_ptr=mp->str_ptr; mp->max_pool_ptr=mp->pool_ptr;
26633   mp_fix_date_and_time(mp);
26634 }
26635
26636
26637 @* \[47] Debugging.
26638 Once \MP\ is working, you should be able to diagnose most errors with
26639 the \.{show} commands and other diagnostic features. But for the initial
26640 stages of debugging, and for the revelation of really deep mysteries, you
26641 can compile \MP\ with a few more aids, including the \PASCAL\ runtime
26642 checks and its debugger. An additional routine called |debug_help|
26643 will also come into play when you type `\.D' after an error message;
26644 |debug_help| also occurs just before a fatal error causes \MP\ to succumb.
26645 @^debugging@>
26646 @^system dependencies@>
26647
26648 The interface to |debug_help| is primitive, but it is good enough when used
26649 with a \PASCAL\ debugger that allows you to set breakpoints and to read
26650 variables and change their values. After getting the prompt `\.{debug \#}', you
26651 type either a negative number (this exits |debug_help|), or zero (this
26652 goes to a location where you can set a breakpoint, thereby entering into
26653 dialog with the \PASCAL\ debugger), or a positive number |m| followed by
26654 an argument |n|. The meaning of |m| and |n| will be clear from the
26655 program below. (If |m=13|, there is an additional argument, |l|.)
26656 @.debug \#@>
26657
26658 @<Last-minute...@>=
26659 void mp_debug_help (MP mp) { /* routine to display various things */
26660   integer k;
26661   int l,m,n;
26662   while (1) { 
26663     wake_up_terminal;
26664     mp_print_nl(mp, "debug # (-1 to exit):"); update_terminal;
26665 @.debug \#@>
26666     m = 0;
26667     fscanf(mp->term_in,"%i",&m);
26668     if ( m<=0 )
26669       return;
26670     n = 0 ;
26671     fscanf(mp->term_in,"%i",&n);
26672     switch (m) {
26673     @<Numbered cases for |debug_help|@>;
26674     default: mp_print(mp, "?"); break;
26675     }
26676   }
26677 }
26678
26679 @ @<Numbered cases...@>=
26680 case 1: mp_print_word(mp, mp->mem[n]); /* display |mem[n]| in all forms */
26681   break;
26682 case 2: mp_print_int(mp, info(n));
26683   break;
26684 case 3: mp_print_int(mp, link(n));
26685   break;
26686 case 4: mp_print_int(mp, eq_type(n)); mp_print_char(mp, ':'); mp_print_int(mp, equiv(n));
26687   break;
26688 case 5: mp_print_variable_name(mp, n);
26689   break;
26690 case 6: mp_print_int(mp, mp->internal[n]);
26691   break;
26692 case 7: mp_do_show_dependencies(mp);
26693   break;
26694 case 9: mp_show_token_list(mp, n,null,100000,0);
26695   break;
26696 case 10: mp_print_str(mp, n);
26697   break;
26698 case 11: mp_check_mem(mp, n>0); /* check wellformedness; print new busy locations if |n>0| */
26699   break;
26700 case 12: mp_search_mem(mp, n); /* look for pointers to |n| */
26701   break;
26702 case 13: l = 0;  fscanf(mp->term_in,"%i",&l); mp_print_cmd_mod(mp, n,l); 
26703   break;
26704 case 14: for (k=0;k<=n;k++) mp_print_str(mp, mp->buffer[k]);
26705   break;
26706 case 15: mp->panicking=! mp->panicking;
26707   break;
26708
26709
26710 @ \MP\ used to have one single routine to print to both `write' files
26711 and the PostScript output. Web2c redefines ``Character |k| cannot be
26712 printed'', and that resulted in some bugs where 8-bit characters were
26713 written to the PostScript file (reported by Wlodek Bzyl).
26714
26715 Also, Hans Hagen requested spaces to be output as "\\040" instead of
26716 a plain space, since that makes it easier to parse the result file
26717 for postprocessing.
26718
26719 @<Character |k| is not allowed in PostScript output@>=
26720   (k<=' ')||(k>'~')
26721
26722 @ Saving the filename template
26723
26724 @<Save the filename template@>=
26725
26726   if ( mp->filename_template!=0 ) delete_str_ref(mp->filename_template);
26727   if ( length(mp->cur_exp)==0 ) mp->filename_template=0;
26728   else { 
26729     mp->filename_template=mp->cur_exp; add_str_ref(mp->filename_template);
26730   }
26731 }
26732
26733 @* \[48] System-dependent changes.
26734 This section should be replaced, if necessary, by any special
26735 modification of the program
26736 that are necessary to make \MP\ work at a particular installation.
26737 It is usually best to design your change file so that all changes to
26738 previous sections preserve the section numbering; then everybody's version
26739 will be consistent with the published program. More extensive changes,
26740 which introduce new sections, can be inserted here; then only the index
26741 itself will get a new section number.
26742 @^system dependencies@>
26743
26744 @* \[49] Index.
26745 Here is where you can find all uses of each identifier in the program,
26746 with underlined entries pointing to where the identifier was defined.
26747 If the identifier is only one letter long, however, you get to see only
26748 the underlined entries. {\sl All references are to section numbers instead of
26749 page numbers.}
26750
26751 This index also lists error messages and other aspects of the program
26752 that you might want to look up some day. For example, the entry
26753 for ``system dependencies'' lists all sections that should receive
26754 special attention from people who are installing \MP\ in a new
26755 operating environment. A list of various things that can't happen appears
26756 under ``this can't happen''.
26757 Approximately 25 sections are listed under ``inner loop''; these account
26758 for more than 60\pct! of \MP's running time, exclusive of input and output.