build the library using libtool, and a bit of cleanup
[mplib] / src / texk / web2c / mpdir / lib / mp.w
1 % $Id: mp.web,v 1.8 2005/08/24 10:54:02 taco Exp $
2 % MetaPost, by John Hobby.  Public domain.
3
4 % Much of this program was copied with permission from MF.web Version 1.9
5 % It interprets a language very similar to D.E. Knuth's METAFONT, but with
6 % changes designed to make it more suitable for PostScript output.
7
8 % TeX is a trademark of the American Mathematical Society.
9 % METAFONT is a trademark of Addison-Wesley Publishing Company.
10 % PostScript is a trademark of Adobe Systems Incorporated.
11
12 % Here is TeX material that gets inserted after \input webmac
13 \def\hang{\hangindent 3em\noindent\ignorespaces}
14 \def\textindent#1{\hangindent2.5em\noindent\hbox to2.5em{\hss#1 }\ignorespaces}
15 \def\PASCAL{Pascal}
16 \def\ps{PostScript}
17 \def\ph{\hbox{Pascal-H}}
18 \def\psqrt#1{\sqrt{\mathstrut#1}}
19 \def\k{_{k+1}}
20 \def\pct!{{\char`\%}} % percent sign in ordinary text
21 \font\tenlogo=logo10 % font used for the METAFONT logo
22 \font\logos=logosl10
23 \def\MF{{\tenlogo META}\-{\tenlogo FONT}}
24 \def\MP{{\tenlogo META}\-{\tenlogo POST}}
25 \def\[#1]{#1.} % from pascal web
26 \def\<#1>{$\langle#1\rangle$}
27 \def\section{\mathhexbox278}
28 \let\swap=\leftrightarrow
29 \def\round{\mathop{\rm round}\nolimits}
30 \mathchardef\vb="026A % synonym for `\|'
31
32 \def\(#1){} % this is used to make section names sort themselves better
33 \def\9#1{} % this is used for sort keys in the index via @@:sort key}{entry@@>
34 \def\title{MetaPost}
35 \def\glob{15} % this should be the section number of "<Global...>"
36 \def\gglob{23, 28} % this should be the next two sections of "<Global...>"
37 \pdfoutput=1
38 \pageno=3
39
40 @* \[1] Introduction.
41 This is \MP, a graphics-language processor based on D. E. Knuth's \MF.
42 The \PASCAL\ program that follows defines a standard version
43 @:PASCAL}{\PASCAL@>
44 of \MP\ that is designed to be highly portable so that identical output
45 will be obtainable on a great variety of computers.
46
47 The main purpose of the following program is to explain the algorithms of \MP\
48 as clearly as possible. As a result, the program will not necessarily be very
49 efficient when a particular \PASCAL\ compiler has translated it into a
50 particular machine language. However, the program has been written so that it
51 can be tuned to run efficiently in a wide variety of operating environments
52 by making comparatively few changes. Such flexibility is possible because
53 the documentation that follows is written in the \.{WEB} language, which is
54 at a higher level than \PASCAL; the preprocessing step that converts \.{WEB}
55 to \PASCAL\ is able to introduce most of the necessary refinements.
56 Semi-automatic translation to other languages is also feasible, because the
57 program below does not make extensive use of features that are peculiar to
58 \PASCAL.
59
60 A large piece of software like \MP\ has inherent complexity that cannot
61 be reduced below a certain level of difficulty, although each individual
62 part is fairly simple by itself. The \.{WEB} language is intended to make
63 the algorithms as readable as possible, by reflecting the way the
64 individual program pieces fit together and by providing the
65 cross-references that connect different parts. Detailed comments about
66 what is going on, and about why things were done in certain ways, have
67 been liberally sprinkled throughout the program.  These comments explain
68 features of the implementation, but they rarely attempt to explain the
69 \MP\ language itself, since the reader is supposed to be familiar with
70 {\sl The {\logos METAFONT\/}book} as well as the manual
71 @.WEB@>
72 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
73 {\sl A User's Manual for MetaPost}, Computing Science Technical Report 162,
74 AT\AM T Bell Laboratories.
75
76 @ The present implementation is a preliminary version, but the possibilities
77 for new features are limited by the desire to remain as nearly compatible
78 with \MF\ as possible.
79
80 On the other hand, the \.{WEB} description can be extended without changing
81 the core of the program, and it has been designed so that such
82 extensions are not extremely difficult to make.
83 The |banner| string defined here should be changed whenever \MP\
84 undergoes any modifications, so that it will be clear which version of
85 \MP\ might be the guilty party when a problem arises.
86 @^extensions to \MP@>
87 @^system dependencies@>
88
89 @d banner "This is MetaPost, Version 1.002" /* printed when \MP\ starts */
90 @d metapost_version "1.002"
91 @d mplib_version "0.10"
92 @d version_string " (Cweb version 0.10)"
93
94 @ Different \PASCAL s have slightly different conventions, and the present
95 @:PASCAL H}{\ph@>
96 program is expressed in a version of \PASCAL\ that D. E. Knuth used for \MF.
97 Constructions that apply to
98 this particular compiler, which we shall call \ph, should help the
99 reader see how to make an appropriate interface for other systems
100 if necessary. (\ph\ is Charles Hedrick's modification of a compiler
101 @^Hedrick, Charles Locke@>
102 for the DECsystem-10 that was originally developed at the University of
103 Hamburg; cf.\ {\sl SOFTWARE---Practice \AM\ Experience \bf6} (1976),
104 29--42. The \MP\ program below is intended to be adaptable, without
105 extensive changes, to most other versions of \PASCAL\ and commonly used
106 \PASCAL-to-C translators, so it does not fully
107 @:C@>
108 use the admirable features of \ph. Indeed, a conscious effort has been
109 made here to avoid using several idiosyncratic features of standard
110 \PASCAL\ itself, so that most of the code can be translated mechanically
111 into other high-level languages. For example, the `\&{with}' and `\\{new}'
112 features are not used, nor are pointer types, set types, or enumerated
113 scalar types; there are no `\&{var}' parameters, except in the case of files;
114 there are no tag fields on variant records; there are no |real| variables;
115 no procedures are declared local to other procedures.)
116
117 The portions of this program that involve system-dependent code, where
118 changes might be necessary because of differences between \PASCAL\ compilers
119 and/or differences between
120 operating systems, can be identified by looking at the sections whose
121 numbers are listed under `system dependencies' in the index. Furthermore,
122 the index entries for `dirty \PASCAL' list all places where the restrictions
123 of \PASCAL\ have not been followed perfectly, for one reason or another.
124 @^system dependencies@>
125 @^dirty \PASCAL@>
126
127 @ The program begins with a normal \PASCAL\ program heading, whose
128 components will be filled in later, using the conventions of \.{WEB}.
129 @.WEB@>
130 For example, the portion of the program called `\X\glob:Global
131 variables\X' below will be replaced by a sequence of variable declarations
132 that starts in $\section\glob$ of this documentation. In this way, we are able
133 to define each individual global variable when we are prepared to
134 understand what it means; we do not have to define all of the globals at
135 once.  Cross references in $\section\glob$, where it says ``See also
136 sections \gglob, \dots,'' also make it possible to look at the set of
137 all global variables, if desired.  Similar remarks apply to the other
138 portions of the program heading.
139
140 Actually the heading shown here is not quite normal: The |program| line
141 does not mention any |output| file, because \ph\ would ask the \MP\ user
142 to specify a file name if |output| were specified here.
143 @^system dependencies@>
144
145 @d true 1
146 @d false 0
147  
148 @(mplib.h@>=
149 #  ifndef LIBAVL_ALLOCATOR
150 #    define LIBAVL_ALLOCATOR
151     struct libavl_allocator {
152         void *(*libavl_malloc) (struct libavl_allocator *, size_t libavl_size);
153         void (*libavl_free) (struct libavl_allocator *, void *libavl_block);
154     };
155 #  endif
156 typedef struct psout_data_struct * psout_data;
157 typedef struct MP_instance * MP;
158 typedef int boolean;
159 typedef signed int integer;
160 @<Types in the outer block@>
161 typedef struct MP_options {
162   @<Option variables@>
163 } MP_options;
164 @<Declare helpers@>;
165 @<Exported function headers@>
166
167 @ @(mpmp.h@>=
168 @<Constants in the outer block@>
169 typedef struct MP_instance {
170   @<Global variables@>
171 } MP_instance;
172
173 @ @c 
174 #include <stdio.h>
175 #include <stdlib.h>
176 #include <string.h>
177 #include <stdarg.h>
178 #include <assert.h>
179 #include <unistd.h> /* for access() */
180 #include <time.h> /* for struct tm \& co */
181 #include "mplib.h"
182 #include "mpmp.h" /* internal header */
183 #include "mppsout.h" /* internal header */
184 @h
185 @<Declarations@>
186 @<Basic printing procedures@>
187 @<Error handling procedures@>
188
189 @ Here are the functions that set up the \MP\ instance.
190
191 @<Declarations@> =
192 @<Declare |mp_reallocate| functions@>;
193 struct MP_options mp_options (void) {
194   struct MP_options *opt;
195   opt = xmalloc(1,sizeof(MP_options));
196   memset (opt,0,sizeof(MP_options));
197   return *opt;
198
199 MP mp_new (struct MP_options opt) {
200   MP mp;
201   mp = xmalloc(1,sizeof(MP_instance));
202   @<Set |ini_version|@>;
203   @<Allocate or initialize variables@>
204   mp_reallocate_paths(mp,1000);
205   mp_reallocate_fonts(mp,8);
206   mp->term_in = stdin;
207   mp->term_out = stdout;
208   return mp;
209 }
210 void mp_free (MP mp) {
211   int k; /* loop variable */
212   @<Dealloc variables@>
213   xfree(mp);
214 }
215
216 @ @c
217 boolean mp_initialize (MP mp) { /* this procedure gets things started properly */
218   @<Local variables for initialization@>
219   mp->history=fatal_error_stop; /* in case we quit during initialization */
220   t_open_out; /* open the terminal for output */
221   @<Check the ``constant'' values...@>;
222   if ( mp->bad>0 ) {
223     fprintf(stdout,"Ouch---my internal constants have been clobbered!\n"
224                    "---case %i",(int)mp->bad);
225 @.Ouch...clobbered@>
226     return false;
227   }
228   @<Set initial values of key variables@>
229   if (mp->ini_version) {
230     @<Run inimpost commands@>;
231   }
232   @<Initialize the output routines@>;
233   @<Get the first line of input and prepare to start@>;
234   mp_set_job_id(mp,mp->internal[year],mp->internal[month],
235                        mp->internal[day],mp->internal[mp_time]);
236   mp_init_map_file(mp, mp->troff_mode);
237   mp->history=spotless; /* ready to go! */
238   if (mp->troff_mode) {
239     mp->internal[gtroffmode]=unity; 
240     mp->internal[prologues]=unity; 
241   }
242   if ( mp->start_sym>0 ) { /* insert the `\&{everyjob}' symbol */
243     mp->cur_sym=mp->start_sym; mp_back_input(mp);
244   }
245   return true;
246 }
247
248
249 @<Exported function headers@>=
250 extern struct MP_options mp_options (void);
251 extern MP mp_new (struct MP_options opt) ;
252 extern void mp_free (MP mp);
253 extern boolean mp_initialize (MP mp);
254
255
256 @ The overall \MP\ program begins with the heading just shown, after which
257 comes a bunch of procedure declarations and function declarations.
258 Finally we will get to the main program, which begins with the
259 comment `|start_here|'. If you want to skip down to the
260 main program now, you can look up `|start_here|' in the index.
261 But the author suggests that the best way to understand this program
262 is to follow pretty much the order of \MP's components as they appear in the
263 \.{WEB} description you are now reading, since the present ordering is
264 intended to combine the advantages of the ``bottom up'' and ``top down''
265 approaches to the problem of understanding a somewhat complicated system.
266
267 @ Some of the code below is intended to be used only when diagnosing the
268 strange behavior that sometimes occurs when \MP\ is being installed or
269 when system wizards are fooling around with \MP\ without quite knowing
270 what they are doing. Such code will not normally be compiled; it is
271 delimited by the preprocessor test `|#ifdef DEBUG .. #endif|'.
272
273 @ This program has two important variations: (1) There is a long and slow
274 version called \.{INIMP}, which does the extra calculations needed to
275 @.INIMP@>
276 initialize \MP's internal tables; and (2)~there is a shorter and faster
277 production version, which cuts the initialization to a bare minimum.
278
279 Which is which is decided at runtime.
280
281 @ The following parameters can be changed at compile time to extend or
282 reduce \MP's capacity. They may have different values in \.{INIMP} and
283 in production versions of \MP.
284 @.INIMP@>
285 @^system dependencies@>
286
287 @<Constants...@>=
288 #define file_name_size 255 /* file names shouldn't be longer than this */
289 #define bistack_size 1500 /* size of stack for bisection algorithms;
290   should probably be left at this value */
291
292 @ Like the preceding parameters, the following quantities can be changed
293 at compile time to extend or reduce \MP's capacity. But if they are changed,
294 it is necessary to rerun the initialization program \.{INIMP}
295 @.INIMP@>
296 to generate new tables for the production \MP\ program.
297 One can't simply make helter-skelter changes to the following constants,
298 since certain rather complex initialization
299 numbers are computed from them. 
300
301 @ @<Glob...@>=
302 int max_strings; /* maximum number of strings; must not exceed |max_halfword| */
303 int pool_size; /* maximum number of characters in strings, including all
304   error messages and help texts, and the names of all identifiers */
305 int error_line; /* width of context lines on terminal error messages */
306 int half_error_line; /* width of first lines of contexts in terminal
307   error messages; should be between 30 and |error_line-15| */
308 int max_print_line; /* width of longest text lines output; should be at least 60 */
309 int mem_max; /* greatest index in \MP's internal |mem| array;
310   must be strictly less than |max_halfword|;
311   must be equal to |mem_top| in \.{INIMP}, otherwise |>=mem_top| */
312 int mem_top; /* largest index in the |mem| array dumped by \.{INIMP};
313   must not be greater than |mem_max| */
314 int hash_size; /* maximum number of symbolic tokens,
315   must be less than |max_halfword-3*param_size| */
316 int hash_prime; /* a prime number equal to about 85\pct! of |hash_size| */
317 int param_size; /* maximum number of simultaneous macro parameters */
318 int max_in_open; /* maximum number of input files and error insertions that
319   can be going on simultaneously */
320
321 @ @<Option variables@>=
322 int error_line;
323 int half_error_line;
324 int max_print_line;
325 int main_memory;
326 int hash_size; 
327 int hash_prime; 
328 int param_size; 
329 int max_in_open; 
330
331
332 @d set_value(a,b,c) do { a=c; if (b>c) a=b; } while (0)
333
334 @<Allocate or ...@>=
335 mp->max_strings=500;
336 mp->pool_size=10000;
337 set_value(mp->error_line,opt.error_line,79);
338 set_value(mp->half_error_line,opt.half_error_line,50);
339 set_value(mp->max_print_line,opt.max_print_line,79);
340 mp->mem_max=5000;
341 mp->mem_top=5000;
342 if (opt.main_memory>mp->mem_max)
343   mp_reallocate_memory(mp,opt.main_memory);
344 set_value(mp->hash_size,opt.hash_size,9500);
345 set_value(mp->hash_prime,opt.hash_prime,7919);
346 set_value(mp->param_size,opt.param_size,150);
347 set_value(mp->max_in_open,opt.max_in_open,10);
348
349
350 @ In case somebody has inadvertently made bad settings of the ``constants,''
351 \MP\ checks them using a global variable called |bad|.
352
353 This is the first of many sections of \MP\ where global variables are
354 defined.
355
356 @<Glob...@>=
357 integer bad; /* is some ``constant'' wrong? */
358
359 @ Later on we will say `\ignorespaces|if (mem_max>=max_halfword) bad=10;|',
360 or something similar. (We can't do that until |max_halfword| has been defined.)
361
362 @<Check the ``constant'' values for consistency@>=
363 mp->bad=0;
364 if ( (mp->half_error_line<30)||(mp->half_error_line>mp->error_line-15) ) mp->bad=1;
365 if ( mp->max_print_line<60 ) mp->bad=2;
366 if ( mp->mem_top<=1100 ) mp->bad=4;
367 if (mp->hash_prime>mp->hash_size ) mp->bad=5;
368
369 @ Labels are given symbolic names by the following definitions, so that
370 occasional |goto| statements will be meaningful. We insert the label
371 `|exit|:' just before the `\ignorespaces|end|\unskip' of a procedure in
372 which we have used the `|return|' statement defined below; the label
373 `|restart|' is occasionally used at the very beginning of a procedure; and
374 the label `|reswitch|' is occasionally used just prior to a |case|
375 statement in which some cases change the conditions and we wish to branch
376 to the newly applicable case.  Loops that are set up with the |loop|
377 construction defined below are commonly exited by going to `|done|' or to
378 `|found|' or to `|not_found|', and they are sometimes repeated by going to
379 `|continue|'.  If two or more parts of a subroutine start differently but
380 end up the same, the shared code may be gathered together at
381 `|common_ending|'.
382
383 Incidentally, this program never declares a label that isn't actually used,
384 because some fussy \PASCAL\ compilers will complain about redundant labels.
385
386 @d label_exit 10 /* go here to leave a procedure */
387 @d restart 20 /* go here to start a procedure again */
388 @d reswitch 21 /* go here to start a case statement again */
389 @d continue 22 /* go here to resume a loop */
390 @d done 30 /* go here to exit a loop */
391 @d done1 31 /* like |done|, when there is more than one loop */
392 @d done2 32 /* for exiting the second loop in a long block */
393 @d done3 33 /* for exiting the third loop in a very long block */
394 @d done4 34 /* for exiting the fourth loop in an extremely long block */
395 @d done5 35 /* for exiting the fifth loop in an immense block */
396 @d done6 36 /* for exiting the sixth loop in a block */
397 @d found 40 /* go here when you've found it */
398 @d found1 41 /* like |found|, when there's more than one per routine */
399 @d found2 42 /* like |found|, when there's more than two per routine */
400 @d found3 43 /* like |found|, when there's more than three per routine */
401 @d not_found 45 /* go here when you've found nothing */
402 @d common_ending 50 /* go here when you want to merge with another branch */
403
404 @ Here are some macros for common programming idioms.
405
406 @d incr(A)   (A)=(A)+1 /* increase a variable by unity */
407 @d decr(A)   (A)=(A)-1 /* decrease a variable by unity */
408 @d negate(A)   (A)=-(A) /* change the sign of a variable */
409 @d odd(A)   ((A)%2==1)
410 @d chr(A)   (A)
411 @d do_nothing   /* empty statement */
412 @d Return   goto exit /* terminate a procedure call */
413 @f return   nil /* \.{WEB} will henceforth say |return| instead of \\{return} */
414
415 @* \[2] The character set.
416 In order to make \MP\ readily portable to a wide variety of
417 computers, all of its input text is converted to an internal eight-bit
418 code that includes standard ASCII, the ``American Standard Code for
419 Information Interchange.''  This conversion is done immediately when each
420 character is read in. Conversely, characters are converted from ASCII to
421 the user's external representation just before they are output to a
422 text file.
423 @^ASCII code@>
424
425 Such an internal code is relevant to users of \MP\ only with respect to
426 the \&{char} and \&{ASCII} operations, and the comparison of strings.
427
428 @ Characters of text that have been converted to \MP's internal form
429 are said to be of type |ASCII_code|, which is a subrange of the integers.
430
431 @<Types...@>=
432 typedef unsigned char ASCII_code; /* eight-bit numbers */
433
434 @ The original \PASCAL\ compiler was designed in the late 60s, when six-bit
435 character sets were common, so it did not make provision for lowercase
436 letters. Nowadays, of course, we need to deal with both capital and small
437 letters in a convenient way, especially in a program for font design;
438 so the present specification of \MP\ has been written under the assumption
439 that the \PASCAL\ compiler and run-time system permit the use of text files
440 with more than 64 distinguishable characters. More precisely, we assume that
441 the character set contains at least the letters and symbols associated
442 with ASCII codes 040 through 0176; all of these characters are now
443 available on most computer terminals.
444
445 Since we are dealing with more characters than were present in the first
446 \PASCAL\ compilers, we have to decide what to call the associated data
447 type. Some \PASCAL s use the original name |char| for the
448 characters in text files, even though there now are more than 64 such
449 characters, while other \PASCAL s consider |char| to be a 64-element
450 subrange of a larger data type that has some other name.
451
452 In order to accommodate this difference, we shall use the name |text_char|
453 to stand for the data type of the characters that are converted to and
454 from |ASCII_code| when they are input and output. We shall also assume
455 that |text_char| consists of the elements |chr(first_text_char)| through
456 |chr(last_text_char)|, inclusive. The following definitions should be
457 adjusted if necessary.
458 @^system dependencies@>
459
460 @d first_text_char 0 /* ordinal number of the smallest element of |text_char| */
461 @d last_text_char 255 /* ordinal number of the largest element of |text_char| */
462
463 @<Types...@>=
464 typedef unsigned char text_char; /* the data type of characters in text files */
465
466 @ @<Local variables for init...@>=
467 integer i;
468
469 @ The \MP\ processor converts between ASCII code and
470 the user's external character set by means of arrays |xord| and |xchr|
471 that are analogous to \PASCAL's |ord| and |chr| functions.
472
473 @<Glob...@>=
474 ASCII_code xord[256];  /* specifies conversion of input characters */
475 text_char xchr[256];  /* specifies conversion of output characters */
476
477 @ The core system assumes all 8-bit is acceptable.  If it is not,
478 a change file has to alter the below section.
479 @^system dependencies@>
480
481 Additionally, people with extended character sets can
482 assign codes arbitrarily, giving an |xchr| equivalent to whatever
483 characters the users of \MP\ are allowed to have in their input files.
484 Appropriate changes to \MP's |char_class| table should then be made.
485 (Unlike \TeX, each installation of \MP\ has a fixed assignment of category
486 codes, called the |char_class|.) Such changes make portability of programs
487 more difficult, so they should be introduced cautiously if at all.
488 @^character set dependencies@>
489 @^system dependencies@>
490
491 @<Set initial ...@>=
492 for (i=0;i<=0377;i++) { mp->xchr[i]=i; }
493
494 @ The following system-independent code makes the |xord| array contain a
495 suitable inverse to the information in |xchr|. Note that if |xchr[i]=xchr[j]|
496 where |i<j<0177|, the value of |xord[xchr[i]]| will turn out to be
497 |j| or more; hence, standard ASCII code numbers will be used instead of
498 codes below 040 in case there is a coincidence.
499
500 @<Set initial ...@>=
501 for (i=first_text_char;i<=last_text_char;i++) { 
502    mp->xord[chr(i)]=0177;
503 }
504 for (i=0200;i<=0377;i++) { mp->xord[mp->xchr[i]]=i;}
505 for (i=0;i<=0176;i++) {mp->xord[mp->xchr[i]]=i;}
506
507 @* \[3] Input and output.
508 The bane of portability is the fact that different operating systems treat
509 input and output quite differently, perhaps because computer scientists
510 have not given sufficient attention to this problem. People have felt somehow
511 that input and output are not part of ``real'' programming. Well, it is true
512 that some kinds of programming are more fun than others. With existing
513 input/output conventions being so diverse and so messy, the only sources of
514 joy in such parts of the code are the rare occasions when one can find a
515 way to make the program a little less bad than it might have been. We have
516 two choices, either to attack I/O now and get it over with, or to postpone
517 I/O until near the end. Neither prospect is very attractive, so let's
518 get it over with.
519
520 The basic operations we need to do are (1)~inputting and outputting of
521 text, to or from a file or the user's terminal; (2)~inputting and
522 outputting of eight-bit bytes, to or from a file; (3)~instructing the
523 operating system to initiate (``open'') or to terminate (``close'') input or
524 output from a specified file; (4)~testing whether the end of an input
525 file has been reached; (5)~display of bits on the user's screen.
526 The bit-display operation will be discussed in a later section; we shall
527 deal here only with more traditional kinds of I/O.
528
529 @ Finding files happens in a slightly roundabout fashion: the \MP\
530 instance object contains a field that holds a function pointer that finds a
531 file, and returns its name, or NULL. For this, it receives three
532 parameters: the non-qualified name |fname|, the intended |fopen|
533 operation type |fmode|, and the type of the file |ftype|.
534
535 The file types that are passed on in |ftype| can be  used to 
536 differentiate file searches if a library like kpathsea is used,
537 the fopen mode is passed along for the same reason.
538
539 @<Types...@>=
540 typedef unsigned char eight_bits ; /* unsigned one-byte quantity */
541 enum {
542   mp_filetype_program = 1, /* \MP\ language input */
543   mp_filetype_log,  /* the log file */
544   mp_filetype_postscript, /* the postscript output */
545   mp_filetype_text,  /* text files for readfrom and writeto primitives */
546   mp_filetype_memfile, /* memory dumps */
547   mp_filetype_metrics, /* TeX font metric files */
548   mp_filetype_fontmap, /* PostScript font mapping files */
549   mp_filetype_font, /*  PostScript type1 font programs */
550   mp_filetype_encoding, /*  PostScript font encoding files */
551 };
552 typedef char *(*file_finder)(char *, char *, int);
553
554 @ @<Glob...@>=
555 file_finder find_file;
556
557 @ @<Option variables@>=
558 file_finder find_file;
559
560 @ The default function for finding files is |mp_find_file|. It is 
561 pretty stupid: it will only find files in the current directory.
562
563 @c
564 char *mp_find_file (char *fname, char *fmode, int ftype)  {
565   if (fmode[0] != 'r' || access (fname,R_OK) || ftype)  
566      return xstrdup(fname);
567   return NULL;
568 }
569
570 @ This has to be done very early on, so it is best to put it in with
571 the |mp_new| allocations
572
573 @d set_callback_option(A) do { mp->A = mp_##A;
574   if (opt.A!=NULL) mp->A = opt.A;
575 } while (0)
576
577 @<Allocate or initialize ...@>=
578 set_callback_option(find_file);
579
580 @ Because |mp_find_file| is used so early, it has to be in the helpers
581 section.
582
583 @<Declare helpers@>=
584 char *mp_find_file (char *fname, char *fmode, int ftype) ;
585
586 @ The function to open files can now be very short.
587
588 @c
589 FILE *mp_open_file(MP mp, char *fname, char *fmode, int ftype)  {
590   char *s = (mp->find_file)(fname,fmode,ftype);
591   if (s!=NULL) {
592     FILE *f = fopen(s, fmode);
593     xfree(s);
594     return f;   
595   }
596   return NULL;
597 }
598
599 @ This is a legacy interface: (almost) all file names pass through |name_of_file|.
600
601 @<Glob...@>=
602 char name_of_file[file_name_size+1]; /* the name of a system file */
603 int name_length;/* this many characters are actually
604   relevant in |name_of_file| (the rest are blank) */
605 boolean print_found_names; /* configuration parameter */
606
607 @ @<Option variables@>=
608 boolean print_found_names; /* configuration parameter */
609
610 @ If this parameter is true, the terminal and log will report the found
611 file names for input files instead of the requested ones. 
612 It is off by default because it creates an extra filename lookup.
613
614 @<Allocate or initialize ...@>=
615 mp->print_found_names = (opt.print_found_names>0 ? true : false);
616
617 @ \MP's file-opening procedures return |false| if no file identified by
618 |name_of_file| could be opened.
619
620 The |OPEN_FILE| macro takes care of the |print_found_names| parameter.
621 It is not used for opening a mem file for read, because that file name 
622 is never printed.
623
624 @d OPEN_FILE(A) do {
625   if (mp->print_found_names) {
626     char *s = (mp->find_file)(mp->name_of_file,A,ftype);
627     if (s!=NULL) {
628       *f = mp_open_file(mp,mp->name_of_file,A, ftype); 
629       strncpy(mp->name_of_file,s,file_name_size);
630       xfree(s);
631     } else {
632       *f = NULL;
633     }
634   } else {
635     *f = mp_open_file(mp,mp->name_of_file,A, ftype); 
636   }
637 } while (0);
638 return (*f ? true : false)
639
640 @c 
641 boolean mp_a_open_in (MP mp, FILE **f, int ftype) {
642   /* open a text file for input */
643   OPEN_FILE("r");
644 }
645 @#
646 boolean mp_w_open_in (MP mp, FILE **f) {
647   /* open a word file for input */
648   *f = mp_open_file(mp,mp->name_of_file,"rb",mp_filetype_memfile); 
649   return (*f ? true : false);
650 }
651 @#
652 boolean mp_a_open_out (MP mp, FILE **f, int ftype) {
653   /* open a text file for output */
654   OPEN_FILE("w");
655 }
656 @#
657 boolean mp_b_open_out (MP mp, FILE **f, int ftype) {
658   /* open a binary file for output */
659   OPEN_FILE("wb");
660 }
661 @#
662 boolean mp_w_open_out (MP mp, FILE**f) {
663   /* open a word file for output */
664   int ftype = mp_filetype_memfile;
665   OPEN_FILE("wb");
666 }
667
668 @ @<Exported...@>=
669 FILE *mp_open_file(MP mp, char *fname, char *fmode, int ftype);
670
671 @ Binary input and output are done with \PASCAL's ordinary |get| and |put|
672 procedures, so we don't have to make any other special arrangements for
673 binary~I/O. Text output is also easy to do with standard \PASCAL\ routines.
674 The treatment of text input is more difficult, however, because
675 of the necessary translation to |ASCII_code| values.
676 \MP's conventions should be efficient, and they should
677 blend nicely with the user's operating environment.
678
679 @ Input from text files is read one line at a time, using a routine called
680 |input_ln|. This function is defined in terms of global variables called
681 |buffer|, |first|, and |last| that will be described in detail later; for
682 now, it suffices for us to know that |buffer| is an array of |ASCII_code|
683 values, and that |first| and |last| are indices into this array
684 representing the beginning and ending of a line of text.
685
686 @<Glob...@>=
687 size_t buf_size; /* maximum number of characters simultaneously present in
688                     current lines of open files */
689 ASCII_code *buffer; /* lines of characters being read */
690 size_t first; /* the first unused position in |buffer| */
691 size_t last; /* end of the line just input to |buffer| */
692 size_t max_buf_stack; /* largest index used in |buffer| */
693
694 @ @<Allocate or initialize ...@>=
695 mp->buf_size = 200;
696 mp->buffer = xmalloc((mp->buf_size+1),sizeof(ASCII_code));
697
698 @ @<Dealloc variables@>=
699 xfree(mp->buffer);
700
701 @ @c
702 void mp_reallocate_buffer(MP mp, size_t l) {
703   ASCII_code *buffer;
704   if (l>max_halfword) {
705     mp_confusion(mp,"buffer size"); /* can't happen (I hope) */
706   }
707   buffer = xmalloc((l+1),sizeof(ASCII_code));
708   memcpy(buffer,mp->buffer,(mp->buf_size+1));
709   xfree(mp->buffer);
710   mp->buffer = buffer ;
711   mp->buf_size = l;
712 }
713
714 @ The |input_ln| function brings the next line of input from the specified
715 field into available positions of the buffer array and returns the value
716 |true|, unless the file has already been entirely read, in which case it
717 returns |false| and sets |last:=first|.  In general, the |ASCII_code|
718 numbers that represent the next line of the file are input into
719 |buffer[first]|, |buffer[first+1]|, \dots, |buffer[last-1]|; and the
720 global variable |last| is set equal to |first| plus the length of the
721 line. Trailing blanks are removed from the line; thus, either |last=first|
722 (in which case the line was entirely blank) or |buffer[last-1]<>" "|.
723 @^inner loop@>
724
725 An overflow error is given, however, if the normal actions of |input_ln|
726 would make |last>=buf_size|; this is done so that other parts of \MP\
727 can safely look at the contents of |buffer[last+1]| without overstepping
728 the bounds of the |buffer| array. Upon entry to |input_ln|, the condition
729 |first<buf_size| will always hold, so that there is always room for an
730 ``empty'' line.
731
732 The variable |max_buf_stack|, which is used to keep track of how large
733 the |buf_size| parameter must be to accommodate the present job, is
734 also kept up to date by |input_ln|.
735
736 If the |bypass_eoln| parameter is |true|, |input_ln| will do a |get|
737 before looking at the first character of the line; this skips over
738 an |eoln| that was in |f^|. The procedure does not do a |get| when it
739 reaches the end of the line; therefore it can be used to acquire input
740 from the user's terminal as well as from ordinary text files.
741
742 Standard \PASCAL\ says that a file should have |eoln| immediately
743 before |eof|, but \MP\ needs only a weaker restriction: If |eof|
744 occurs in the middle of a line, the system function |eoln| should return
745 a |true| result (even though |f^| will be undefined).
746
747 @c 
748 boolean mp_input_ln (MP mp,FILE *  f, boolean bypass_eoln) {
749   /* inputs the next line or returns |false| */
750   int last_nonblank; /* |last| with trailing blanks removed */
751   int c;
752   if ( bypass_eoln ) {
753     c = fgetc(f);
754     if (c==EOF)
755       return false;
756     if (c!='\n' && c!='\r') {
757       ungetc(c,f);
758     }
759   }
760   /* input the first character of the line into |f^| */
761   mp->last=mp->first; /* cf.\ Matthew 19\thinspace:\thinspace30 */
762   c = fgetc(f);
763   if (c==EOF)
764         return false;
765   last_nonblank=mp->first;
766   while (c!=EOF && c!='\n' && c!='\r') { 
767     if ( mp->last>=mp->max_buf_stack ) { 
768       mp->max_buf_stack=mp->last+1;
769       if ( mp->max_buf_stack==mp->buf_size ) {
770         mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
771       }
772     }
773     mp->buffer[mp->last]=mp->xord[c]; 
774     incr(mp->last);
775     if ( mp->buffer[mp->last-1]!=' ' ) 
776       last_nonblank=mp->last;
777     c = fgetc(f); 
778   } 
779   if (c!=EOF) {
780     ungetc(c,f);
781   }
782   mp->last=last_nonblank; 
783   return true;
784 }
785
786 @ The user's terminal acts essentially like other files of text, except
787 that it is used both for input and for output. When the terminal is
788 considered an input file, the file variable is called |term_in|, and when it
789 is considered an output file the file variable is |term_out|.
790 @^system dependencies@>
791
792 @<Glob...@>=
793 FILE * term_in; /* the terminal as an input file */
794 FILE * term_out; /* the terminal as an output file */
795
796 @ Here is how to open the terminal files. In the default configuration,
797 nothing happens except that the command line (if there is one) is copied
798 to the input buffer.  The variable |command_line| will be filled by the 
799 |main| procedure. The copying can not be done earlier in the program 
800 logic because in the |INI| version, the |buffer| is also used for primitive 
801 initialization.
802
803 @^system dependencies@>
804
805 @d t_open_out  /* open the terminal for text output */
806 @d t_open_in  do { /* open the terminal for text input */
807     if (mp->command_line!=NULL) {
808       mp->last = strlen(mp->command_line);
809       strncpy((char *)mp->buffer,mp->command_line,mp->last);
810       xfree(mp->command_line);
811     }
812 } while (0)
813
814 @<Glob...@>=
815 char *command_line;
816
817 @ @<Option variables@>=
818 char *command_line;
819
820 @ @<Allocate or initialize ...@>=
821 mp->command_line = mp_xstrdup(opt.command_line);
822
823 @ Sometimes it is necessary to synchronize the input/output mixture that
824 happens on the user's terminal, and three system-dependent
825 procedures are used for this
826 purpose. The first of these, |update_terminal|, is called when we want
827 to make sure that everything we have output to the terminal so far has
828 actually left the computer's internal buffers and been sent.
829 The second, |clear_terminal|, is called when we wish to cancel any
830 input that the user may have typed ahead (since we are about to
831 issue an unexpected error message). The third, |wake_up_terminal|,
832 is supposed to revive the terminal if the user has disabled it by
833 some instruction to the operating system.  The following macros show how
834 these operations can be specified in \ph:
835 @^system dependencies@>
836
837 @d update_terminal   fflush(mp->term_out) /* empty the terminal output buffer */
838 @d clear_terminal   do_nothing /* clear the terminal input buffer */
839 @d wake_up_terminal  fflush(mp->term_out) /* cancel the user's cancellation of output */
840
841 @ We need a special routine to read the first line of \MP\ input from
842 the user's terminal. This line is different because it is read before we
843 have opened the transcript file; there is sort of a ``chicken and
844 egg'' problem here. If the user types `\.{input cmr10}' on the first
845 line, or if some macro invoked by that line does such an \.{input},
846 the transcript file will be named `\.{cmr10.log}'; but if no \.{input}
847 commands are performed during the first line of terminal input, the transcript
848 file will acquire its default name `\.{mpout.log}'. (The transcript file
849 will not contain error messages generated by the first line before the
850 first \.{input} command.)
851
852 The first line is even more special if we are lucky enough to have an operating
853 system that treats \MP\ differently from a run-of-the-mill \PASCAL\ object
854 program. It's nice to let the user start running a \MP\ job by typing
855 a command line like `\.{MP cmr10}'; in such a case, \MP\ will operate
856 as if the first line of input were `\.{cmr10}', i.e., the first line will
857 consist of the remainder of the command line, after the part that invoked \MP.
858
859 @ Different systems have different ways to get started. But regardless of
860 what conventions are adopted, the routine that initializes the terminal
861 should satisfy the following specifications:
862
863 \yskip\textindent{1)}It should open file |term_in| for input from the
864   terminal. (The file |term_out| will already be open for output to the
865   terminal.)
866
867 \textindent{2)}If the user has given a command line, this line should be
868   considered the first line of terminal input. Otherwise the
869   user should be prompted with `\.{**}', and the first line of input
870   should be whatever is typed in response.
871
872 \textindent{3)}The first line of input, which might or might not be a
873   command line, should appear in locations |first| to |last-1| of the
874   |buffer| array.
875
876 \textindent{4)}The global variable |loc| should be set so that the
877   character to be read next by \MP\ is in |buffer[loc]|. This
878   character should not be blank, and we should have |loc<last|.
879
880 \yskip\noindent(It may be necessary to prompt the user several times
881 before a non-blank line comes in. The prompt is `\.{**}' instead of the
882 later `\.*' because the meaning is slightly different: `\.{input}' need
883 not be typed immediately after~`\.{**}'.)
884
885 @d loc mp->cur_input.loc_field /* location of first unread character in |buffer| */
886
887 @ The following program does the required initialization
888 without retrieving a possible command line.
889 It should be clear how to modify this routine to deal with command lines,
890 if the system permits them.
891 @^system dependencies@>
892
893 @c 
894 boolean mp_init_terminal (MP mp) { /* gets the terminal input started */
895   t_open_in; 
896   if (mp->last!=0) {
897     loc = mp->first = 0;
898         return true;
899   }
900   while (1) { 
901     wake_up_terminal; fprintf(mp->term_out,"**"); update_terminal;
902 @.**@>
903     if ( ! mp_input_ln(mp, mp->term_in,true) ) { /* this shouldn't happen */
904       fprintf(mp->term_out,"\n! End of file on the terminal... why?");
905 @.End of file on the terminal@>
906       return false;
907     }
908     loc=mp->first;
909     while ( (loc<(int)mp->last)&&(mp->buffer[loc]==' ') ) 
910       incr(loc);
911     if ( loc<(int)mp->last ) { 
912       return true; /* return unless the line was all blank */
913     };
914     fprintf(mp->term_out,"Please type the name of your input file.\n");
915   }
916 }
917
918 @ @<Declarations@>=
919 boolean mp_init_terminal (MP mp) ;
920
921
922 @* \[4] String handling.
923 Symbolic token names and diagnostic messages are variable-length strings
924 of eight-bit characters. Since \PASCAL\ does not have a well-developed string
925 mechanism, \MP\ does all of its string processing by homegrown methods.
926
927 \MP\ uses strings more extensively than \MF\ does, but the necessary
928 operations can still be handled with a fairly simple data structure.
929 The array |str_pool| contains all of the (eight-bit) ASCII codes in all
930 of the strings, and the array |str_start| contains indices of the starting
931 points of each string. Strings are referred to by integer numbers, so that
932 string number |s| comprises the characters |str_pool[j]| for
933 |str_start[s]<=j<str_start[ss]| where |ss=next_str[s]|.  The string pool
934 is allocated sequentially and |str_pool[pool_ptr]| is the next unused
935 location.  The first string number not currently in use is |str_ptr|
936 and |next_str[str_ptr]| begins a list of free string numbers.  String
937 pool entries |str_start[str_ptr]| up to |pool_ptr| are reserved for a
938 string currently being constructed.
939
940 String numbers 0 to 255 are reserved for strings that correspond to single
941 ASCII characters. This is in accordance with the conventions of \.{WEB},
942 @.WEB@>
943 which converts single-character strings into the ASCII code number of the
944 single character involved, while it converts other strings into integers
945 and builds a string pool file. Thus, when the string constant \.{"."} appears
946 in the program below, \.{WEB} converts it into the integer 46, which is the
947 ASCII code for a period, while \.{WEB} will convert a string like \.{"hello"}
948 into some integer greater than~255. String number 46 will presumably be the
949 single character `\..'\thinspace; but some ASCII codes have no standard visible
950 representation, and \MP\ may need to be able to print an arbitrary
951 ASCII character, so the first 256 strings are used to specify exactly what
952 should be printed for each of the 256 possibilities.
953
954 @<Types...@>=
955 typedef int pool_pointer; /* for variables that point into |str_pool| */
956 typedef int str_number; /* for variables that point into |str_start| */
957
958 @ @<Glob...@>=
959 ASCII_code *str_pool; /* the characters */
960 pool_pointer *str_start; /* the starting pointers */
961 str_number *next_str; /* for linking strings in order */
962 pool_pointer pool_ptr; /* first unused position in |str_pool| */
963 str_number str_ptr; /* number of the current string being created */
964 pool_pointer init_pool_ptr; /* the starting value of |pool_ptr| */
965 str_number init_str_use; /* the initial number of strings in use */
966 pool_pointer max_pool_ptr; /* the maximum so far of |pool_ptr| */
967 str_number max_str_ptr; /* the maximum so far of |str_ptr| */
968
969 @ @<Allocate or initialize ...@>=
970 mp->str_pool  = xmalloc ((mp->pool_size +1),sizeof(ASCII_code));
971 mp->str_start = xmalloc ((mp->max_strings+1),sizeof(pool_pointer));
972 mp->next_str  = xmalloc ((mp->max_strings+1),sizeof(str_number));
973
974 @ @<Dealloc variables@>=
975 xfree(mp->str_pool);
976 xfree(mp->str_start);
977 xfree(mp->next_str);
978
979 @ Most printing is done from |char *|s, but sometimes not. Here are
980 functions that convert an internal string into a |char *| for use
981 by the printing routines, and vice versa.
982
983 @d str(A) mp_str(mp,A)
984 @d rts(A) mp_rts(mp,A)
985
986 @<Exported function headers@>=
987 int mp_xstrcmp (const char *a, const char *b);
988 char * mp_str (MP mp, str_number s);
989
990 @ @<Declarations@>=
991 str_number mp_rts (MP mp, char *s);
992 str_number mp_make_string (MP mp);
993
994 @ The attempt to catch interrupted strings that is in |mp_rts|, is not 
995 very good: it does not handle nesting over more than one level.
996
997 @c 
998 int mp_xstrcmp (const char *a, const char *b) {
999         if (a==NULL && b==NULL) 
1000           return 0;
1001     if (a==NULL)
1002       return -1;
1003     if (b==NULL)
1004       return 1;
1005     return strcmp(a,b);
1006 }
1007
1008 @ @c
1009 char * mp_str (MP mp, str_number ss) {
1010   char *s;
1011   int len = length(ss);
1012   s = xmalloc(len+1,sizeof(char));
1013   strncpy(s,(char *)(mp->str_pool+(mp->str_start[ss])),len);
1014   s[len] = 0;
1015   return (char *)s;
1016 }
1017 str_number mp_rts (MP mp, char *s) {
1018   int r; /* the new string */ 
1019   int old; /* a possible string in progress */
1020   int i=0;
1021   if (strlen(s)==0) {
1022     return 256;
1023   } else if (strlen(s)==1) {
1024     return s[0];
1025   } else {
1026    old=0;
1027    str_room((integer)strlen(s));
1028    if (mp->str_start[mp->str_ptr]<mp->pool_ptr)
1029      old = mp_make_string(mp);
1030    while (*s) {
1031      append_char(*s);
1032      s++;
1033    }
1034    r = mp_make_string(mp);
1035    if (old!=0) {
1036       str_room(length(old));
1037       while (i<length(old)) {
1038         append_char((mp->str_start[old]+i));
1039       } 
1040       mp_flush_string(mp,old);
1041     }
1042     return r;
1043   }
1044 }
1045
1046 @ Except for |strs_used_up|, the following string statistics are only
1047 maintained when code between |stat| $\ldots$ |tats| delimiters is not
1048 commented out:
1049
1050 @<Glob...@>=
1051 integer strs_used_up; /* strings in use or unused but not reclaimed */
1052 integer pool_in_use; /* total number of cells of |str_pool| actually in use */
1053 integer strs_in_use; /* total number of strings actually in use */
1054 integer max_pl_used; /* maximum |pool_in_use| so far */
1055 integer max_strs_used; /* maximum |strs_in_use| so far */
1056
1057 @ Several of the elementary string operations are performed using \.{WEB}
1058 macros instead of \PASCAL\ procedures, because many of the
1059 operations are done quite frequently and we want to avoid the
1060 overhead of procedure calls. For example, here is
1061 a simple macro that computes the length of a string.
1062 @.WEB@>
1063
1064 @d str_stop(A) mp->str_start[mp->next_str[(A)]] /* one cell past the end of string
1065   number \# */
1066 @d length(A) (str_stop((A))-mp->str_start[(A)]) /* the number of characters in string \# */
1067
1068 @ The length of the current string is called |cur_length|.  If we decide that
1069 the current string is not needed, |flush_cur_string| resets |pool_ptr| so that
1070 |cur_length| becomes zero.
1071
1072 @d cur_length   (mp->pool_ptr - mp->str_start[mp->str_ptr])
1073 @d flush_cur_string   mp->pool_ptr=mp->str_start[mp->str_ptr]
1074
1075 @ Strings are created by appending character codes to |str_pool|.
1076 The |append_char| macro, defined here, does not check to see if the
1077 value of |pool_ptr| has gotten too high; this test is supposed to be
1078 made before |append_char| is used.
1079
1080 To test if there is room to append |l| more characters to |str_pool|,
1081 we shall write |str_room(l)|, which tries to make sure there is enough room
1082 by compacting the string pool if necessary.  If this does not work,
1083 |do_compaction| aborts \MP\ and gives an apologetic error message.
1084
1085 @d append_char(A)   /* put |ASCII_code| \# at the end of |str_pool| */
1086 { mp->str_pool[mp->pool_ptr]=(A); incr(mp->pool_ptr);
1087 }
1088 @d str_room(A)   /* make sure that the pool hasn't overflowed */
1089   { if ( mp->pool_ptr+(A) > mp->max_pool_ptr ) {
1090     if ( mp->pool_ptr+(A) > mp->pool_size ) mp_do_compaction(mp, (A));
1091     else mp->max_pool_ptr=mp->pool_ptr+(A); }
1092   }
1093
1094 @ The following routine is similar to |str_room(1)| but it uses the
1095 argument |mp->pool_size| to prevent |do_compaction| from aborting when
1096 string space is exhausted.
1097
1098 @<Declare the procedure called |unit_str_room|@>=
1099 void mp_unit_str_room (MP mp);
1100
1101 @ @c
1102 void mp_unit_str_room (MP mp) { 
1103   if ( mp->pool_ptr>=mp->pool_size ) mp_do_compaction(mp, mp->pool_size);
1104   if ( mp->pool_ptr>=mp->max_pool_ptr ) mp->max_pool_ptr=mp->pool_ptr+1;
1105 }
1106
1107 @ \MP's string expressions are implemented in a brute-force way: Every
1108 new string or substring that is needed is simply copied into the string pool.
1109 Space is eventually reclaimed by a procedure called |do_compaction| with
1110 the aid of a simple system system of reference counts.
1111 @^reference counts@>
1112
1113 The number of references to string number |s| will be |str_ref[s]|. The
1114 special value |str_ref[s]=max_str_ref=127| is used to denote an unknown
1115 positive number of references; such strings will never be recycled. If
1116 a string is ever referred to more than 126 times, simultaneously, we
1117 put it in this category. Hence a single byte suffices to store each |str_ref|.
1118
1119 @d max_str_ref 127 /* ``infinite'' number of references */
1120 @d add_str_ref(A) { if ( mp->str_ref[(A)]<max_str_ref ) incr(mp->str_ref[(A)]);
1121   }
1122
1123 @<Glob...@>=
1124 int *str_ref;
1125
1126 @ @<Allocate or initialize ...@>=
1127 mp->str_ref = xmalloc ((mp->max_strings+1),sizeof(int));
1128
1129 @ @<Dealloc variables@>=
1130 xfree(mp->str_ref);
1131
1132 @ Here's what we do when a string reference disappears:
1133
1134 @d delete_str_ref(A)  { 
1135     if ( mp->str_ref[(A)]<max_str_ref ) {
1136        if ( mp->str_ref[(A)]>1 ) decr(mp->str_ref[(A)]); 
1137        else mp_flush_string(mp, (A));
1138     }
1139   }
1140
1141 @<Declare the procedure called |flush_string|@>=
1142 void mp_flush_string (MP mp,str_number s) ;
1143
1144
1145 @ We can't flush the first set of static strings at all, so there 
1146 is no point in trying
1147
1148 @c
1149 void mp_flush_string (MP mp,str_number s) { 
1150   if (length(s)>1) {
1151     mp->pool_in_use=mp->pool_in_use-length(s);
1152     decr(mp->strs_in_use);
1153     if ( mp->next_str[s]!=mp->str_ptr ) {
1154       mp->str_ref[s]=0;
1155     } else { 
1156       mp->str_ptr=s;
1157       decr(mp->strs_used_up);
1158     }
1159     mp->pool_ptr=mp->str_start[mp->str_ptr];
1160   }
1161 }
1162
1163 @ C literals cannot be simply added, they need to be set so they can't
1164 be flushed.
1165
1166 @d intern(A) mp_intern(mp,(A))
1167
1168 @c
1169 str_number mp_intern (MP mp, char *s) {
1170   str_number r ;
1171   r = rts(s);
1172   mp->str_ref[r] = max_str_ref;
1173   return r;
1174 }
1175
1176 @ @<Declarations@>=
1177 str_number mp_intern (MP mp, char *s);
1178
1179
1180 @ Once a sequence of characters has been appended to |str_pool|, it
1181 officially becomes a string when the function |make_string| is called.
1182 This function returns the identification number of the new string as its
1183 value.
1184
1185 When getting the next unused string number from the linked list, we pretend
1186 that
1187 $$ \hbox{|max_str_ptr+1|, |max_str_ptr+2|, $\ldots$, |mp->max_strings|} $$
1188 are linked sequentially even though the |next_str| entries have not been
1189 initialized yet.  We never allow |str_ptr| to reach |mp->max_strings|;
1190 |do_compaction| is responsible for making sure of this.
1191
1192 @<Declarations@>=
1193 @<Declare the procedure called |do_compaction|@>;
1194 @<Declare the procedure called |unit_str_room|@>;
1195 str_number mp_make_string (MP mp);
1196
1197 @ @c 
1198 str_number mp_make_string (MP mp) { /* current string enters the pool */
1199   str_number s; /* the new string */
1200 RESTART: 
1201   s=mp->str_ptr;
1202   mp->str_ptr=mp->next_str[s];
1203   if ( mp->str_ptr>mp->max_str_ptr ) {
1204     if ( mp->str_ptr==mp->max_strings ) { 
1205       mp->str_ptr=s;
1206       mp_do_compaction(mp, 0);
1207       goto RESTART;
1208     } else {
1209 #ifdef DEBUG 
1210       if ( mp->strs_used_up!=mp->max_str_ptr ) mp_confusion(mp, "s");
1211 @:this can't happen s}{\quad \.s@>
1212 #endif
1213       mp->max_str_ptr=mp->str_ptr;
1214       mp->next_str[mp->str_ptr]=mp->max_str_ptr+1;
1215     }
1216   }
1217   mp->str_ref[s]=1;
1218   mp->str_start[mp->str_ptr]=mp->pool_ptr;
1219   incr(mp->strs_used_up);
1220   incr(mp->strs_in_use);
1221   mp->pool_in_use=mp->pool_in_use+length(s);
1222   if ( mp->pool_in_use>mp->max_pl_used ) 
1223     mp->max_pl_used=mp->pool_in_use;
1224   if ( mp->strs_in_use>mp->max_strs_used ) 
1225     mp->max_strs_used=mp->strs_in_use;
1226   return s;
1227 }
1228
1229 @ The most interesting string operation is string pool compaction.  The idea
1230 is to recover unused space in the |str_pool| array by recopying the strings
1231 to close the gaps created when some strings become unused.  All string
1232 numbers~$k$ where |str_ref[k]=0| are to be linked into the list of free string
1233 numbers after |str_ptr|.  If this fails to free enough pool space we issue an
1234 |overflow| error unless |needed=mp->pool_size|.  Calling |do_compaction|
1235 with |needed=mp->pool_size| supresses all overflow tests.
1236
1237 The compaction process starts with |last_fixed_str| because all lower numbered
1238 strings are permanently allocated with |max_str_ref| in their |str_ref| entries.
1239
1240 @<Glob...@>=
1241 str_number last_fixed_str; /* last permanently allocated string */
1242 str_number fixed_str_use; /* number of permanently allocated strings */
1243
1244 @ @<Declare the procedure called |do_compaction|@>=
1245 void mp_do_compaction (MP mp, pool_pointer needed) ;
1246
1247 @ @c
1248 void mp_do_compaction (MP mp, pool_pointer needed) {
1249   str_number str_use; /* a count of strings in use */
1250   str_number r,s,t; /* strings being manipulated */
1251   pool_pointer p,q; /* destination and source for copying string characters */
1252   @<Advance |last_fixed_str| as far as possible and set |str_use|@>;
1253   r=mp->last_fixed_str;
1254   s=mp->next_str[r];
1255   p=mp->str_start[s];
1256   while ( s!=mp->str_ptr ) { 
1257     while ( mp->str_ref[s]==0 ) {
1258       @<Advance |s| and add the old |s| to the list of free string numbers;
1259         then |break| if |s=str_ptr|@>;
1260     }
1261     r=s; s=mp->next_str[s];
1262     incr(str_use);
1263     @<Move string |r| back so that |str_start[r]=p|; make |p| the location
1264      after the end of the string@>;
1265   }
1266   @<Move the current string back so that it starts at |p|@>;
1267   if ( needed<mp->pool_size ) {
1268     @<Make sure that there is room for another string with |needed| characters@>;
1269   }
1270   @<Account for the compaction and make sure the statistics agree with the
1271      global versions@>;
1272   mp->strs_used_up=str_use;
1273 }
1274
1275 @ @<Advance |last_fixed_str| as far as possible and set |str_use|@>=
1276 t=mp->next_str[mp->last_fixed_str];
1277 while ( (mp->str_ref[t]==max_str_ref)&&(t!=mp->str_ptr) ) { 
1278   incr(mp->fixed_str_use);
1279   mp->last_fixed_str=t;
1280   t=mp->next_str[t];
1281 }
1282 str_use=mp->fixed_str_use
1283
1284 @ Because of the way |flush_string| has been written, it should never be
1285 necessary to |break| here.  The extra line of code seems worthwhile to
1286 preserve the generality of |do_compaction|.
1287
1288 @<Advance |s| and add the old |s| to the list of free string numbers;...@>=
1289 {
1290 t=s;
1291 s=mp->next_str[s];
1292 mp->next_str[r]=s;
1293 mp->next_str[t]=mp->next_str[mp->str_ptr];
1294 mp->next_str[mp->str_ptr]=t;
1295 if ( s==mp->str_ptr ) break;
1296 }
1297
1298 @ The string currently starts at |str_start[r]| and ends just before
1299 |str_start[s]|.  We don't change |str_start[s]| because it might be needed
1300 to locate the next string.
1301
1302 @<Move string |r| back so that |str_start[r]=p|; make |p| the location...@>=
1303 q=mp->str_start[r];
1304 mp->str_start[r]=p;
1305 while ( q<mp->str_start[s] ) { 
1306   mp->str_pool[p]=mp->str_pool[q];
1307   incr(p); incr(q);
1308 }
1309
1310 @ Pointers |str_start[str_ptr]| and |pool_ptr| have not been updated.  When
1311 we do this, anything between them should be moved.
1312
1313 @ @<Move the current string back so that it starts at |p|@>=
1314 q=mp->str_start[mp->str_ptr];
1315 mp->str_start[mp->str_ptr]=p;
1316 while ( q<mp->pool_ptr ) { 
1317   mp->str_pool[p]=mp->str_pool[q];
1318   incr(p); incr(q);
1319 }
1320 mp->pool_ptr=p
1321
1322 @ We must remember that |str_ptr| is not allowed to reach |mp->max_strings|.
1323
1324 @<Make sure that there is room for another string with |needed| char...@>=
1325 if ( str_use>=mp->max_strings-1 )
1326   mp_reallocate_strings (mp,str_use);
1327 if ( mp->pool_ptr+needed>mp->max_pool_ptr ) {
1328   mp_reallocate_pool(mp, mp->pool_ptr+needed);
1329   mp->max_pool_ptr=mp->pool_ptr+needed;
1330 }
1331
1332 @ @<Declarations@>=
1333 void mp_reallocate_strings (MP mp, str_number str_use) ;
1334 void mp_reallocate_pool(MP mp, pool_pointer needed) ;
1335
1336 @ @c 
1337 void mp_reallocate_strings (MP mp, str_number str_use) { 
1338   while ( str_use>=mp->max_strings-1 ) {
1339     int l = mp->max_strings + (mp->max_strings>>2);
1340     XREALLOC (mp->str_ref,   (l+1),sizeof(int));
1341     XREALLOC (mp->str_start, (l+1),sizeof(pool_pointer));
1342     XREALLOC (mp->next_str,  (l+1),sizeof(str_number));
1343     mp->max_strings = l;
1344   }
1345 }
1346 void mp_reallocate_pool(MP mp, pool_pointer needed) {
1347   while ( needed>mp->pool_size ) {
1348     int l = mp->pool_size + (mp->pool_size>>2);
1349         XREALLOC (mp->str_pool, (l+1),sizeof(ASCII_code));
1350     mp->pool_size = l;
1351   }
1352 }
1353
1354 @ @<Account for the compaction and make sure the statistics agree with...@>=
1355 if ( (mp->str_start[mp->str_ptr]!=mp->pool_in_use)||(str_use!=mp->strs_in_use) )
1356   mp_confusion(mp, "string");
1357 @:this can't happen string}{\quad string@>
1358 incr(mp->pact_count);
1359 mp->pact_chars=mp->pact_chars+mp->pool_ptr-str_stop(mp->last_fixed_str);
1360 mp->pact_strs=mp->pact_strs+str_use-mp->fixed_str_use;
1361 #ifdef DEBUG
1362 s=mp->str_ptr; t=str_use;
1363 while ( s<=mp->max_str_ptr ){
1364   if ( t>mp->max_str_ptr ) mp_confusion(mp, "\"");
1365   incr(t); s=mp->next_str[s];
1366 };
1367 if ( t<=mp->max_str_ptr ) mp_confusion(mp, "\"");
1368 #endif
1369
1370 @ A few more global variables are needed to keep track of statistics when
1371 |stat| $\ldots$ |tats| blocks are not commented out.
1372
1373 @<Glob...@>=
1374 integer pact_count; /* number of string pool compactions so far */
1375 integer pact_chars; /* total number of characters moved during compactions */
1376 integer pact_strs; /* total number of strings moved during compactions */
1377
1378 @ @<Initialize compaction statistics@>=
1379 mp->pact_count=0;
1380 mp->pact_chars=0;
1381 mp->pact_strs=0;
1382
1383 @ The following subroutine compares string |s| with another string of the
1384 same length that appears in |buffer| starting at position |k|;
1385 the result is |true| if and only if the strings are equal.
1386
1387 @c 
1388 boolean mp_str_eq_buf (MP mp,str_number s, integer k) {
1389   /* test equality of strings */
1390   pool_pointer j; /* running index */
1391   j=mp->str_start[s];
1392   while ( j<str_stop(s) ) { 
1393     if ( mp->str_pool[j++]!=mp->buffer[k++] ) 
1394       return false;
1395   }
1396   return true;
1397 }
1398
1399 @ Here is a similar routine, but it compares two strings in the string pool,
1400 and it does not assume that they have the same length. If the first string
1401 is lexicographically greater than, less than, or equal to the second,
1402 the result is respectively positive, negative, or zero.
1403
1404 @c 
1405 integer mp_str_vs_str (MP mp, str_number s, str_number t) {
1406   /* test equality of strings */
1407   pool_pointer j,k; /* running indices */
1408   integer ls,lt; /* lengths */
1409   integer l; /* length remaining to test */
1410   ls=length(s); lt=length(t);
1411   if ( ls<=lt ) l=ls; else l=lt;
1412   j=mp->str_start[s]; k=mp->str_start[t];
1413   while ( l-->0 ) { 
1414     if ( mp->str_pool[j]!=mp->str_pool[k] ) {
1415        return (mp->str_pool[j]-mp->str_pool[k]); 
1416     }
1417     incr(j); incr(k);
1418   }
1419   return (ls-lt);
1420 }
1421
1422 @ The initial values of |str_pool|, |str_start|, |pool_ptr|,
1423 and |str_ptr| are computed by the \.{INIMP} program, based in part
1424 on the information that \.{WEB} has output while processing \MP.
1425 @.INIMP@>
1426 @^string pool@>
1427
1428 @c 
1429 void mp_get_strings_started (MP mp) { 
1430   /* initializes the string pool,
1431     but returns |false| if something goes wrong */
1432   int k; /* small indices or counters */
1433   str_number g; /* a new string */
1434   mp->pool_ptr=0; mp->str_ptr=0; mp->max_pool_ptr=0; mp->max_str_ptr=0;
1435   mp->str_start[0]=0;
1436   mp->next_str[0]=1;
1437   mp->pool_in_use=0; mp->strs_in_use=0;
1438   mp->max_pl_used=0; mp->max_strs_used=0;
1439   @<Initialize compaction statistics@>;
1440   mp->strs_used_up=0;
1441   @<Make the first 256 strings@>;
1442   g=mp_make_string(mp); /* string 256 == "" */
1443   mp->last_fixed_str=mp->str_ptr-1;
1444   mp->fixed_str_use=mp->str_ptr;
1445   return;
1446 }
1447
1448 @ @<Declarations@>=
1449 void mp_get_strings_started (MP mp);
1450
1451 @ The first 256 strings will consist of a single character only.
1452
1453 @<Make the first 256...@>=
1454 for (k=0;k<=255;k++) { 
1455   append_char(k);
1456   g=mp_make_string(mp); 
1457   mp->str_ref[g]=max_str_ref;
1458 }
1459
1460 @ The first 128 strings will contain 95 standard ASCII characters, and the
1461 other 33 characters will be printed in three-symbol form like `\.{\^\^A}'
1462 unless a system-dependent change is made here. Installations that have
1463 an extended character set, where for example |xchr[032]=@t\.{'^^Z'}@>|,
1464 would like string 032 to be printed as the single character 032 instead
1465 of the three characters 0136, 0136, 0132 (\.{\^\^Z}). On the other hand,
1466 even people with an extended character set will want to represent string
1467 015 by \.{\^\^M}, since 015 is ASCII's ``carriage return'' code; the idea is
1468 to produce visible strings instead of tabs or line-feeds or carriage-returns
1469 or bell-rings or characters that are treated anomalously in text files.
1470
1471 Unprintable characters of codes 128--255 are, similarly, rendered
1472 \.{\^\^80}--\.{\^\^ff}.
1473
1474 The boolean expression defined here should be |true| unless \MP\ internal
1475 code number~|k| corresponds to a non-troublesome visible symbol in the
1476 local character set.
1477 If character |k| cannot be printed, and |k<0200|, then character |k+0100| or
1478 |k-0100| must be printable; moreover, ASCII codes |[060..071, 0141..0146]|
1479 must be printable.
1480 @^character set dependencies@>
1481 @^system dependencies@>
1482
1483 @<Character |k| cannot be printed@>=
1484   (k<' ')||(k>'~')
1485
1486 @* \[5] On-line and off-line printing.
1487 Messages that are sent to a user's terminal and to the transcript-log file
1488 are produced by several `|print|' procedures. These procedures will
1489 direct their output to a variety of places, based on the setting of
1490 the global variable |selector|, which has the following possible
1491 values:
1492
1493 \yskip
1494 \hang |term_and_log|, the normal setting, prints on the terminal and on the
1495   transcript file.
1496
1497 \hang |log_only|, prints only on the transcript file.
1498
1499 \hang |term_only|, prints only on the terminal.
1500
1501 \hang |no_print|, doesn't print at all. This is used only in rare cases
1502   before the transcript file is open.
1503
1504 \hang |ps_file_only| prints only on the \ps\ output file.
1505
1506 \hang |pseudo|, puts output into a cyclic buffer that is used
1507   by the |show_context| routine; when we get to that routine we shall discuss
1508   the reasoning behind this curious mode.
1509
1510 \hang |new_string|, appends the output to the current string in the
1511   string pool.
1512
1513 \hang |>=write_file| prints on one of the files used for the \&{write}
1514 @:write_}{\&{write} primitive@>
1515   command.
1516
1517 \yskip
1518 \noindent The symbolic names `|term_and_log|', etc., have been assigned
1519 numeric codes that satisfy the convenient relations |no_print+1=term_only|,
1520 |no_print+2=log_only|, |term_only+2=log_only+1=term_and_log|.  These
1521 relations are not used when |selector| could be |pseudo|, |new_string|,
1522 or |ps_file_only|.  We need not check for unprintable characters when
1523 |selector<pseudo|.
1524
1525 Four additional global variables, |tally|, |term_offset|, |file_offset|,
1526 and |ps_offset| record the number of characters that have been printed
1527 since they were most recently cleared to zero. We use |tally| to record
1528 the length of (possibly very long) stretches of printing; |term_offset|,
1529 |file_offset|, and |ps_offset|, on the other hand, keep track of how many
1530 characters have appeared so far on the current line that has been output
1531 to the terminal, the transcript file, or the \ps\ output file, respectively.
1532
1533 @d new_string 0 /* printing is deflected to the string pool */
1534 @d ps_file_only 1 /* printing goes to the \ps\ output file */
1535 @d pseudo 2 /* special |selector| setting for |show_context| */
1536 @d no_print 3 /* |selector| setting that makes data disappear */
1537 @d term_only 4 /* printing is destined for the terminal only */
1538 @d log_only 5 /* printing is destined for the transcript file only */
1539 @d term_and_log 6 /* normal |selector| setting */
1540 @d write_file 7 /* first write file selector */
1541
1542 @<Glob...@>=
1543 FILE * log_file; /* transcript of \MP\ session */
1544 FILE * ps_file; /* the generic font output goes here */
1545 unsigned int selector; /* where to print a message */
1546 unsigned char dig[23]; /* digits in a number being output */
1547 integer tally; /* the number of characters recently printed */
1548 unsigned int term_offset;
1549   /* the number of characters on the current terminal line */
1550 unsigned int file_offset;
1551   /* the number of characters on the current file line */
1552 integer ps_offset;
1553   /* the number of characters on the current \ps\ file line */
1554 ASCII_code *trick_buf; /* circular buffer for pseudoprinting */
1555 integer trick_count; /* threshold for pseudoprinting, explained later */
1556 integer first_count; /* another variable for pseudoprinting */
1557
1558 @ @<Allocate or initialize ...@>=
1559 memset(mp->dig,0,23);
1560 mp->trick_buf = xmalloc((mp->error_line+1),sizeof(ASCII_code));
1561
1562 @ @<Dealloc variables@>=
1563 xfree(mp->trick_buf);
1564
1565 @ @<Initialize the output routines@>=
1566 mp->selector=term_only; mp->tally=0; mp->term_offset=0; mp->file_offset=0; mp->ps_offset=0;
1567
1568 @ Macro abbreviations for output to the terminal and to the log file are
1569 defined here for convenience. Some systems need special conventions
1570 for terminal output, and it is possible to adhere to those conventions
1571 by changing |wterm|, |wterm_ln|, and |wterm_cr| here.
1572 @^system dependencies@>
1573
1574 @d wterm(A)    fprintf(mp->term_out,"%s",(A))
1575 @d wterm_chr(A)fprintf(mp->term_out,"%c",(A))
1576 @d wterm_ln(A) fprintf(mp->term_out,"\n%s",(A))
1577 @d wterm_cr    fprintf(mp->term_out,"\n")
1578 @d wlog(A)     fprintf(mp->log_file,"%s",(A))
1579 @d wlog_chr(A) fprintf(mp->log_file,"%c",(A))
1580 @d wlog_ln(A)  fprintf(mp->log_file,"\n%s",(A))
1581 @d wlog_cr     fprintf(mp->log_file, "\n")
1582 @d wps(A)      fprintf(mp->ps_file,"%s",(A))
1583 @d wps_chr(A)  fprintf(mp->ps_file,"%c",(A))
1584 @d wps_ln(A)   fprintf(mp->ps_file,,"\n%s",(A))
1585 @d wps_cr      fprintf(mp->ps_file,"\n")
1586
1587 @ To end a line of text output, we call |print_ln|.  Cases |0..max_write_files|
1588 use an array |wr_file| that will be declared later.
1589
1590 @d mp_print_text(A) mp_print_str(mp,text((A)))
1591
1592 @<Exported...@>=
1593 void mp_print_ln (MP mp);
1594 void mp_print_visible_char (MP mp, ASCII_code s); 
1595 void mp_print_char (MP mp, ASCII_code k);
1596 void mp_print (MP mp, char *s);
1597 void mp_print_str (MP mp, str_number s);
1598 void mp_print_nl (MP mp, char *s);
1599 void mp_print_two (MP mp,scaled x, scaled y) ;
1600 void mp_print_scaled (MP mp,scaled s);
1601
1602 @ @<Basic print...@>=
1603 void mp_print_ln (MP mp) { /* prints an end-of-line */
1604  switch (mp->selector) {
1605   case term_and_log: 
1606     wterm_cr; wlog_cr;
1607     mp->term_offset=0;  mp->file_offset=0;
1608     break;
1609   case log_only: 
1610     wlog_cr; mp->file_offset=0;
1611     break;
1612   case term_only: 
1613     wterm_cr; mp->term_offset=0;
1614     break;
1615   case ps_file_only: 
1616     wps_cr; mp->ps_offset=0;
1617     break;
1618   case no_print:
1619   case pseudo: 
1620   case new_string: 
1621     break;
1622   default: 
1623     fprintf(mp->wr_file[(mp->selector-write_file)],"\n");
1624   }
1625 } /* note that |tally| is not affected */
1626
1627 @ The |print_visible_char| procedure sends one character to the desired
1628 destination, using the |xchr| array to map it into an external character
1629 compatible with |input_ln|.  (It assumes that it is always called with
1630 a visible ASCII character.)  All printing comes through |print_ln| or
1631 |print_char|, which ultimately calls |print_visible_char|, hence these
1632 routines are the ones that limit lines to at most |max_print_line| characters.
1633 But we must make an exception for the \ps\ output file since it is not safe
1634 to cut up lines arbitrarily in \ps.
1635
1636 Procedure |unit_str_room| needs to be declared |forward| here because it calls
1637 |do_compaction| and |do_compaction| can call the error routines.  Actually,
1638 |unit_str_room| avoids |overflow| errors but it can call |confusion|.
1639
1640 @<Basic printing...@>=
1641 void mp_print_visible_char (MP mp, ASCII_code s) { /* prints a single character */
1642   switch (mp->selector) {
1643   case term_and_log: 
1644     wterm_chr(mp->xchr[s]); wlog_chr(mp->xchr[s]);
1645     incr(mp->term_offset); incr(mp->file_offset);
1646     if ( mp->term_offset==(unsigned)mp->max_print_line ) { 
1647        wterm_cr; mp->term_offset=0;
1648     };
1649     if ( mp->file_offset==(unsigned)mp->max_print_line ) { 
1650        wlog_cr; mp->file_offset=0;
1651     };
1652     break;
1653   case log_only: 
1654     wlog_chr(mp->xchr[s]); incr(mp->file_offset);
1655     if ( mp->file_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1656     break;
1657   case term_only: 
1658     wterm_chr(mp->xchr[s]); incr(mp->term_offset);
1659     if ( mp->term_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1660     break;
1661   case ps_file_only: 
1662     if ( s==13 ) {
1663       wps_cr; mp->ps_offset=0;
1664     } else {
1665       wps_chr(mp->xchr[s]); incr(mp->ps_offset);
1666     };
1667     break;
1668   case no_print: 
1669     break;
1670   case pseudo: 
1671     if ( mp->tally<mp->trick_count ) 
1672       mp->trick_buf[mp->tally % mp->error_line]=s;
1673     break;
1674   case new_string: 
1675     if ( mp->pool_ptr>=mp->max_pool_ptr ) { 
1676       mp_unit_str_room(mp);
1677       if ( mp->pool_ptr>=mp->pool_size ) 
1678         goto DONE; /* drop characters if string space is full */
1679     };
1680     append_char(s);
1681     break;
1682   default:
1683     fprintf(mp->wr_file[(mp->selector-write_file)],"%c",mp->xchr[s]);
1684   }
1685 DONE:
1686   incr(mp->tally);
1687 }
1688
1689 @ The |print_char| procedure sends one character to the desired destination.
1690 File names and string expressions might contain |ASCII_code| values that
1691 can't be printed using |print_visible_char|.  These characters will be
1692 printed in three- or four-symbol form like `\.{\^\^A}' or `\.{\^\^e4}'.
1693 (This procedure assumes that it is safe to bypass all checks for unprintable
1694 characters when |selector| is in the range |0..max_write_files-1| or when
1695 |selector=ps_file_only|.  In the former case the user might want to write
1696 unprintable characters, and in the latter case the \ps\ printing routines
1697 check their arguments themselves before calling |print_char| or |print|.)
1698
1699 @d print_lc_hex(A) do { l=(A);
1700     mp_print_visible_char(mp, (l<10 ? l+'0' : l-10+'a'));
1701   } while (0)
1702
1703 @<Basic printing...@>=
1704 void mp_print_char (MP mp, ASCII_code k) { /* prints a single character */
1705   int l; /* small index or counter */
1706   if ( mp->selector<pseudo || mp->selector>=write_file) {
1707     mp_print_visible_char(mp, k);
1708   } else if ( @<Character |k| cannot be printed@> ) { 
1709     mp_print(mp, "^^"); 
1710     if ( k<0100 ) { 
1711       mp_print_visible_char(mp, k+0100); 
1712     } else if ( k<0200 ) { 
1713       mp_print_visible_char(mp, k-0100); 
1714     } else { 
1715       print_lc_hex(k / 16);  
1716       print_lc_hex(k % 16); 
1717     }
1718   } else {
1719     mp_print_visible_char(mp, k);
1720   }
1721 };
1722
1723 @ An entire string is output by calling |print|. Note that if we are outputting
1724 the single standard ASCII character \.c, we could call |print("c")|, since
1725 |"c"=99| is the number of a single-character string, as explained above. But
1726 |print_char("c")| is quicker, so \MP\ goes directly to the |print_char|
1727 routine when it knows that this is safe. (The present implementation
1728 assumes that it is always safe to print a visible ASCII character.)
1729 @^system dependencies@>
1730
1731 @<Basic print...@>=
1732 void mp_do_print (MP mp, char *ss, unsigned int len) { /* prints string |s| */
1733   unsigned int j = 0;
1734   while ( j<len ){ 
1735     mp_print_char(mp, ss[j]); incr(j);
1736   }
1737 }
1738
1739
1740 @<Basic print...@>=
1741 void mp_print (MP mp, char *ss) {
1742   mp_do_print(mp, ss, strlen(ss));
1743 }
1744 void mp_print_str (MP mp, str_number s) {
1745   pool_pointer j; /* current character code position */
1746   if ( (s<0)||(s>mp->max_str_ptr) ) {
1747      mp_do_print(mp,"???",3); /* this can't happen */
1748 @.???@>
1749   }
1750   j=mp->str_start[s];
1751   mp_do_print(mp, (char *)(mp->str_pool+j), (str_stop(s)-j));
1752 }
1753
1754
1755 @ Here is the very first thing that \MP\ prints: a headline that identifies
1756 the version number and base name. The |term_offset| variable is temporarily
1757 incorrect, but the discrepancy is not serious since we assume that the banner
1758 and mem identifier together will occupy at most |max_print_line|
1759 character positions.
1760
1761 @<Initialize the output...@>=
1762 wterm (banner);
1763 wterm (version_string);
1764 if (mp->mem_ident!=NULL) 
1765   mp_print(mp,mp->mem_ident); 
1766 mp_print_ln(mp);
1767 update_terminal;
1768
1769 @ The procedure |print_nl| is like |print|, but it makes sure that the
1770 string appears at the beginning of a new line.
1771
1772 @<Basic print...@>=
1773 void mp_print_nl (MP mp, char *s) { /* prints string |s| at beginning of line */
1774   switch(mp->selector) {
1775   case term_and_log: 
1776     if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_ln(mp);
1777     break;
1778   case log_only: 
1779     if ( mp->file_offset>0 ) mp_print_ln(mp);
1780     break;
1781   case term_only: 
1782     if ( mp->term_offset>0 ) mp_print_ln(mp);
1783     break;
1784   case ps_file_only: 
1785     if ( mp->ps_offset>0 ) mp_print_ln(mp);
1786     break;
1787   case no_print:
1788   case pseudo:
1789   case new_string: 
1790         break;
1791   } /* there are no other cases */
1792   mp_print(mp, s);
1793 }
1794
1795 @ An array of digits in the range |0..9| is printed by |print_the_digs|.
1796
1797 @<Basic print...@>=
1798 void mp_print_the_digs (MP mp, eight_bits k) {
1799   /* prints |dig[k-1]|$\,\ldots\,$|dig[0]| */
1800   while ( k>0 ){ 
1801     decr(k); mp_print_char(mp, '0'+mp->dig[k]);
1802   }
1803 };
1804
1805 @ The following procedure, which prints out the decimal representation of a
1806 given integer |n|, has been written carefully so that it works properly
1807 if |n=0| or if |(-n)| would cause overflow. It does not apply |mod| or |div|
1808 to negative arguments, since such operations are not implemented consistently
1809 by all \PASCAL\ compilers.
1810
1811 @<Basic print...@>=
1812 void mp_print_int (MP mp,integer n) { /* prints an integer in decimal form */
1813   integer m; /* used to negate |n| in possibly dangerous cases */
1814   int k = 0; /* index to current digit; we assume that $|n|<10^{23}$ */
1815   if ( n<0 ) { 
1816     mp_print_char(mp, '-');
1817     if ( n>-100000000 ) {
1818           negate(n);
1819     } else  { 
1820           m=-1-n; n=m / 10; m=(m % 10)+1; k=1;
1821       if ( m<10 ) {
1822         mp->dig[0]=m;
1823       } else { 
1824         mp->dig[0]=0; incr(n);
1825       }
1826     }
1827   }
1828   do {  
1829     mp->dig[k]=n % 10; n=n / 10; incr(k);
1830   } while (n!=0);
1831   mp_print_the_digs(mp, k);
1832 };
1833
1834 @ @<Exported...@>=
1835 void mp_print_int (MP mp,integer n);
1836
1837 @ \MP\ also makes use of a trivial procedure to print two digits. The
1838 following subroutine is usually called with a parameter in the range |0<=n<=99|.
1839
1840 @c 
1841 void mp_print_dd (MP mp,integer n) { /* prints two least significant digits */
1842   n=abs(n) % 100; 
1843   mp_print_char(mp, '0'+(n / 10));
1844   mp_print_char(mp, '0'+(n % 10));
1845 }
1846
1847 @ Here is a procedure that asks the user to type a line of input,
1848 assuming that the |selector| setting is either |term_only| or |term_and_log|.
1849 The input is placed into locations |first| through |last-1| of the
1850 |buffer| array, and echoed on the transcript file if appropriate.
1851
1852 This procedure is never called when |interaction<mp_scroll_mode|.
1853
1854 @d prompt_input(A) do { 
1855     wake_up_terminal; mp_print(mp, (A)); mp_term_input(mp);
1856   } while (0) /* prints a string and gets a line of input */
1857
1858 @c 
1859 void mp_term_input (MP mp) { /* gets a line from the terminal */
1860   size_t k; /* index into |buffer| */
1861   update_terminal; /* Now the user sees the prompt for sure */
1862   if (!mp_input_ln(mp, mp->term_in,true)) 
1863     mp_fatal_error(mp, "End of file on the terminal!");
1864 @.End of file on the terminal@>
1865   mp->term_offset=0; /* the user's line ended with \<\rm return> */
1866   decr(mp->selector); /* prepare to echo the input */
1867   if ( mp->last!=mp->first ) {
1868     for (k=mp->first;k<=mp->last-1;k++) {
1869       mp_print_char(mp, mp->buffer[k]);
1870     }
1871   }
1872   mp_print_ln(mp); 
1873   mp->buffer[mp->last]='%'; 
1874   incr(mp->selector); /* restore previous status */
1875 };
1876
1877 @* \[6] Reporting errors.
1878 When something anomalous is detected, \MP\ typically does something like this:
1879 $$\vbox{\halign{#\hfil\cr
1880 |print_err("Something anomalous has been detected");|\cr
1881 |help3("This is the first line of my offer to help.")|\cr
1882 |("This is the second line. I'm trying to")|\cr
1883 |("explain the best way for you to proceed.");|\cr
1884 |error;|\cr}}$$
1885 A two-line help message would be given using |help2|, etc.; these informal
1886 helps should use simple vocabulary that complements the words used in the
1887 official error message that was printed. (Outside the U.S.A., the help
1888 messages should preferably be translated into the local vernacular. Each
1889 line of help is at most 60 characters long, in the present implementation,
1890 so that |max_print_line| will not be exceeded.)
1891
1892 The |print_err| procedure supplies a `\.!' before the official message,
1893 and makes sure that the terminal is awake if a stop is going to occur.
1894 The |error| procedure supplies a `\..' after the official message, then it
1895 shows the location of the error; and if |interaction=error_stop_mode|,
1896 it also enters into a dialog with the user, during which time the help
1897 message may be printed.
1898 @^system dependencies@>
1899
1900 @ The global variable |interaction| has four settings, representing increasing
1901 amounts of user interaction:
1902
1903 @<Types...@>=
1904 enum { 
1905  mp_unspecified_mode=0, /* extra value for command-line switch */
1906  mp_batch_mode, /* omits all stops and omits terminal output */
1907  mp_nonstop_mode, /* omits all stops */
1908  mp_scroll_mode, /* omits error stops */
1909  mp_error_stop_mode, /* stops at every opportunity to interact */
1910 };
1911
1912 @ @<Glob...@>=
1913 int interaction; /* current level of interaction */
1914
1915 @ @<Option variables@>=
1916 int interaction; /* current level of interaction */
1917
1918 @ Set it here so it can be overwritten by the commandline
1919
1920 @<Allocate or initialize ...@>=
1921 mp->interaction=opt.interaction;
1922 if (mp->interaction==mp_unspecified_mode || mp->interaction>mp_error_stop_mode) 
1923   mp->interaction=mp_error_stop_mode;
1924 if (mp->interaction<mp_unspecified_mode) 
1925   mp->interaction=mp_batch_mode;
1926
1927
1928
1929 @d print_err(A) mp_print_err(mp,(A))
1930
1931 @<Exported...@>=
1932 void mp_print_err(MP mp, char * A);
1933
1934 @ @c
1935 void mp_print_err(MP mp, char * A) { 
1936   if ( mp->interaction==mp_error_stop_mode ) 
1937     wake_up_terminal;
1938   mp_print_nl(mp, "! "); 
1939   mp_print(mp, A);
1940 @.!\relax@>
1941 }
1942
1943
1944 @ \MP\ is careful not to call |error| when the print |selector| setting
1945 might be unusual. The only possible values of |selector| at the time of
1946 error messages are
1947
1948 \yskip\hang|no_print| (when |interaction=mp_batch_mode|
1949   and |log_file| not yet open);
1950
1951 \hang|term_only| (when |interaction>mp_batch_mode| and |log_file| not yet open);
1952
1953 \hang|log_only| (when |interaction=mp_batch_mode| and |log_file| is open);
1954
1955 \hang|term_and_log| (when |interaction>mp_batch_mode| and |log_file| is open).
1956
1957 @<Initialize the print |selector| based on |interaction|@>=
1958 if ( mp->interaction==mp_batch_mode ) mp->selector=no_print; else mp->selector=term_only
1959
1960 @ A global variable |deletions_allowed| is set |false| if the |get_next|
1961 routine is active when |error| is called; this ensures that |get_next|
1962 will never be called recursively.
1963 @^recursion@>
1964
1965 The global variable |history| records the worst level of error that
1966 has been detected. It has four possible values: |spotless|, |warning_issued|,
1967 |error_message_issued|, and |fatal_error_stop|.
1968
1969 Another global variable, |error_count|, is increased by one when an
1970 |error| occurs without an interactive dialog, and it is reset to zero at
1971 the end of every statement.  If |error_count| reaches 100, \MP\ decides
1972 that there is no point in continuing further.
1973
1974 @d spotless 0 /* |history| value when nothing has been amiss yet */
1975 @d warning_issued 1 /* |history| value when |begin_diagnostic| has been called */
1976 @d error_message_issued 2 /* |history| value when |error| has been called */
1977 @d fatal_error_stop 3 /* |history| value when termination was premature */
1978
1979 @<Glob...@>=
1980 boolean deletions_allowed; /* is it safe for |error| to call |get_next|? */
1981 int history; /* has the source input been clean so far? */
1982 int error_count; /* the number of scrolled errors since the last statement ended */
1983
1984 @ The value of |history| is initially |fatal_error_stop|, but it will
1985 be changed to |spotless| if \MP\ survives the initialization process.
1986
1987 @<Allocate or ...@>=
1988 mp->deletions_allowed=true; mp->error_count=0; /* |history| is initialized elsewhere */
1989
1990 @ Since errors can be detected almost anywhere in \MP, we want to declare the
1991 error procedures near the beginning of the program. But the error procedures
1992 in turn use some other procedures, which need to be declared |forward|
1993 before we get to |error| itself.
1994
1995 It is possible for |error| to be called recursively if some error arises
1996 when |get_next| is being used to delete a token, and/or if some fatal error
1997 occurs while \MP\ is trying to fix a non-fatal one. But such recursion
1998 @^recursion@>
1999 is never more than two levels deep.
2000
2001 @<Declarations@>=
2002 void mp_get_next (MP mp);
2003 void mp_term_input (MP mp);
2004 void mp_show_context (MP mp);
2005 void mp_begin_file_reading (MP mp);
2006 void mp_open_log_file (MP mp);
2007 void mp_clear_for_error_prompt (MP mp);
2008 void mp_debug_help (MP mp);
2009 @<Declare the procedure called |flush_string|@>
2010
2011 @ @<Exported...@>=
2012 void mp_normalize_selector (MP mp);
2013
2014 @ Individual lines of help are recorded in the array |help_line|, which
2015 contains entries in positions |0..(help_ptr-1)|. They should be printed
2016 in reverse order, i.e., with |help_line[0]| appearing last.
2017
2018 @d hlp1(A) mp->help_line[0]=(A); }
2019 @d hlp2(A) mp->help_line[1]=(A); hlp1
2020 @d hlp3(A) mp->help_line[2]=(A); hlp2
2021 @d hlp4(A) mp->help_line[3]=(A); hlp3
2022 @d hlp5(A) mp->help_line[4]=(A); hlp4
2023 @d hlp6(A) mp->help_line[5]=(A); hlp5
2024 @d help0 mp->help_ptr=0 /* sometimes there might be no help */
2025 @d help1  { mp->help_ptr=1; hlp1 /* use this with one help line */
2026 @d help2  { mp->help_ptr=2; hlp2 /* use this with two help lines */
2027 @d help3  { mp->help_ptr=3; hlp3 /* use this with three help lines */
2028 @d help4  { mp->help_ptr=4; hlp4 /* use this with four help lines */
2029 @d help5  { mp->help_ptr=5; hlp5 /* use this with five help lines */
2030 @d help6  { mp->help_ptr=6; hlp6 /* use this with six help lines */
2031
2032 @<Glob...@>=
2033 char * help_line[6]; /* helps for the next |error| */
2034 unsigned int help_ptr; /* the number of help lines present */
2035 boolean use_err_help; /* should the |err_help| string be shown? */
2036 str_number err_help; /* a string set up by \&{errhelp} */
2037 str_number filename_template; /* a string set up by \&{filenametemplate} */
2038
2039 @ @<Allocate or ...@>=
2040 mp->help_ptr=0; mp->use_err_help=false; mp->err_help=0; mp->filename_template=0;
2041
2042 @ The |jump_out| procedure just cuts across all active procedure levels and
2043 goes to |end_of_MP|. This is the only nonlocal |goto| statement in the
2044 whole program. It is used when there is no recovery from a particular error.
2045
2046 Some \PASCAL\ compilers do not implement non-local |goto| statements.
2047 @^system dependencies@>
2048 In such cases the body of |jump_out| should simply be
2049 `|close_files_and_terminate|;\thinspace' followed by a call on some system
2050 procedure that quietly terminates the program.
2051
2052 @<Error hand...@>=
2053 void mp_jump_out (MP mp) { 
2054  exit(mp->history);
2055 };
2056
2057 @ Here now is the general |error| routine.
2058
2059 @<Error hand...@>=
2060 void mp_error (MP mp) { /* completes the job of error reporting */
2061   ASCII_code c; /* what the user types */
2062   integer s1,s2,s3; /* used to save global variables when deleting tokens */
2063   pool_pointer j; /* character position being printed */
2064   if ( mp->history<error_message_issued ) mp->history=error_message_issued;
2065   mp_print_char(mp, '.'); mp_show_context(mp);
2066   if ( mp->interaction==mp_error_stop_mode ) {
2067     @<Get user's advice and |return|@>;
2068   }
2069   incr(mp->error_count);
2070   if ( mp->error_count==100 ) { 
2071     mp_print_nl(mp,"(That makes 100 errors; please try again.)");
2072 @.That makes 100 errors...@>
2073     mp->history=fatal_error_stop; mp_jump_out(mp);
2074   }
2075   @<Put help message on the transcript file@>;
2076 }
2077 void mp_warn (MP mp, char *msg) {
2078   int saved_selector = mp->selector;
2079   mp_normalize_selector(mp);
2080   mp_print_nl(mp,"Warning: ");
2081   mp_print(mp,msg);
2082   mp->selector = saved_selector;
2083 }
2084
2085 @ @<Exported...@>=
2086 void mp_error (MP mp);
2087 void mp_warn (MP mp, char *msg);
2088
2089
2090 @ @<Get user's advice...@>=
2091 while (1) { 
2092 CONTINUE:
2093   mp_clear_for_error_prompt(mp); prompt_input("? ");
2094 @.?\relax@>
2095   if ( mp->last==mp->first ) return;
2096   c=mp->buffer[mp->first];
2097   if ( c>='a' ) c=c+'A'-'a'; /* convert to uppercase */
2098   @<Interpret code |c| and |return| if done@>;
2099 }
2100
2101 @ It is desirable to provide an `\.E' option here that gives the user
2102 an easy way to return from \MP\ to the system editor, with the offending
2103 line ready to be edited. But such an extension requires some system
2104 wizardry, so the present implementation simply types out the name of the
2105 file that should be
2106 edited and the relevant line number.
2107 @^system dependencies@>
2108
2109 @<Types...@>=
2110 typedef void (*run_editor_command)(MP, char *, int);
2111
2112 @ @<Glob...@>=
2113 run_editor_command run_editor;
2114
2115 @ @<Option variables@>=
2116 run_editor_command run_editor;
2117
2118 @ @<Allocate or initialize ...@>=
2119 set_callback_option(run_editor);
2120
2121 @ @<Exported function headers@>=
2122 void mp_run_editor (MP mp, char *fname, int fline);
2123
2124 @ @c void mp_run_editor (MP mp, char *fname, int fline) {
2125     mp_print_nl(mp, "You want to edit file ");
2126 @.You want to edit file x@>
2127     mp_print(mp, fname);
2128     mp_print(mp, " at line "); 
2129     mp_print_int(mp, fline);
2130     mp->interaction=mp_scroll_mode; 
2131     mp_jump_out(mp);
2132 }
2133
2134
2135 There is a secret `\.D' option available when the debugging routines haven't
2136 been commented~out.
2137 @^debugging@>
2138
2139 @<Interpret code |c| and |return| if done@>=
2140 switch (c) {
2141 case '0': case '1': case '2': case '3': case '4':
2142 case '5': case '6': case '7': case '8': case '9': 
2143   if ( mp->deletions_allowed ) {
2144     @<Delete |c-"0"| tokens and |continue|@>;
2145   }
2146   break;
2147 #ifdef DEBUG
2148 case 'D': 
2149   mp_debug_help(mp); continue; 
2150   break;
2151 #endif
2152 case 'E': 
2153   if ( mp->file_ptr>0 ){ 
2154     (mp->run_editor)(mp, 
2155                      str(mp->input_stack[mp->file_ptr].name_field), 
2156                      mp_true_line(mp));
2157   }
2158   break;
2159 case 'H': 
2160   @<Print the help information and |continue|@>;
2161   break;
2162 case 'I':
2163   @<Introduce new material from the terminal and |return|@>;
2164   break;
2165 case 'Q': case 'R': case 'S':
2166   @<Change the interaction level and |return|@>;
2167   break;
2168 case 'X':
2169   mp->interaction=mp_scroll_mode; mp_jump_out(mp);
2170   break;
2171 default:
2172   break;
2173 }
2174 @<Print the menu of available options@>
2175
2176 @ @<Print the menu...@>=
2177
2178   mp_print(mp, "Type <return> to proceed, S to scroll future error messages,");
2179 @.Type <return> to proceed...@>
2180   mp_print_nl(mp, "R to run without stopping, Q to run quietly,");
2181   mp_print_nl(mp, "I to insert something, ");
2182   if ( mp->file_ptr>0 ) 
2183     mp_print(mp, "E to edit your file,");
2184   if ( mp->deletions_allowed )
2185     mp_print_nl(mp, "1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
2186   mp_print_nl(mp, "H for help, X to quit.");
2187 }
2188
2189 @ Here the author of \MP\ apologizes for making use of the numerical
2190 relation between |"Q"|, |"R"|, |"S"|, and the desired interaction settings
2191 |mp_batch_mode|, |mp_nonstop_mode|, |mp_scroll_mode|.
2192 @^Knuth, Donald Ervin@>
2193
2194 @<Change the interaction...@>=
2195
2196   mp->error_count=0; mp->interaction=mp_batch_mode+c-'Q';
2197   mp_print(mp, "OK, entering ");
2198   switch (c) {
2199   case 'Q': mp_print(mp, "batchmode"); decr(mp->selector); break;
2200   case 'R': mp_print(mp, "nonstopmode"); break;
2201   case 'S': mp_print(mp, "scrollmode"); break;
2202   } /* there are no other cases */
2203   mp_print(mp, "..."); mp_print_ln(mp); update_terminal; return;
2204 }
2205
2206 @ When the following code is executed, |buffer[(first+1)..(last-1)]| may
2207 contain the material inserted by the user; otherwise another prompt will
2208 be given. In order to understand this part of the program fully, you need
2209 to be familiar with \MP's input stacks.
2210
2211 @<Introduce new material...@>=
2212
2213   mp_begin_file_reading(mp); /* enter a new syntactic level for terminal input */
2214   if ( mp->last>mp->first+1 ) { 
2215     loc=mp->first+1; mp->buffer[mp->first]=' ';
2216   } else { 
2217    prompt_input("insert>"); loc=mp->first;
2218 @.insert>@>
2219   };
2220   mp->first=mp->last+1; mp->cur_input.limit_field=mp->last; return;
2221 }
2222
2223 @ We allow deletion of up to 99 tokens at a time.
2224
2225 @<Delete |c-"0"| tokens...@>=
2226
2227   s1=mp->cur_cmd; s2=mp->cur_mod; s3=mp->cur_sym; mp->OK_to_interrupt=false;
2228   if ( (mp->last>mp->first+1) && (mp->buffer[mp->first+1]>='0')&&(mp->buffer[mp->first+1]<='9') )
2229     c=c*10+mp->buffer[mp->first+1]-'0'*11;
2230   else 
2231     c=c-'0';
2232   while ( c>0 ) { 
2233     mp_get_next(mp); /* one-level recursive call of |error| is possible */
2234     @<Decrease the string reference count, if the current token is a string@>;
2235     decr(c);
2236   };
2237   mp->cur_cmd=s1; mp->cur_mod=s2; mp->cur_sym=s3; mp->OK_to_interrupt=true;
2238   help2("I have just deleted some text, as you asked.")
2239        ("You can now delete more, or insert, or whatever.");
2240   mp_show_context(mp); 
2241   goto CONTINUE;
2242 }
2243
2244 @ @<Print the help info...@>=
2245
2246   if ( mp->use_err_help ) { 
2247     @<Print the string |err_help|, possibly on several lines@>;
2248     mp->use_err_help=false;
2249   } else { 
2250     if ( mp->help_ptr==0 ) {
2251       help2("Sorry, I don't know how to help in this situation.")
2252            ("Maybe you should try asking a human?");
2253      }
2254     do { 
2255       decr(mp->help_ptr); mp_print(mp, mp->help_line[mp->help_ptr]); mp_print_ln(mp);
2256     } while (mp->help_ptr!=0);
2257   };
2258   help4("Sorry, I already gave what help I could...")
2259        ("Maybe you should try asking a human?")
2260        ("An error might have occurred before I noticed any problems.")
2261        ("``If all else fails, read the instructions.''");
2262   goto CONTINUE;
2263 }
2264
2265 @ @<Print the string |err_help|, possibly on several lines@>=
2266 j=mp->str_start[mp->err_help];
2267 while ( j<str_stop(mp->err_help) ) { 
2268   if ( mp->str_pool[j]!='%' ) mp_print_str(mp, mp->str_pool[j]);
2269   else if ( j+1==str_stop(mp->err_help) ) mp_print_ln(mp);
2270   else if ( mp->str_pool[j+1]!='%' ) mp_print_ln(mp);
2271   else  { incr(j); mp_print_char(mp, '%'); };
2272   incr(j);
2273 }
2274
2275 @ @<Put help message on the transcript file@>=
2276 if ( mp->interaction>mp_batch_mode ) decr(mp->selector); /* avoid terminal output */
2277 if ( mp->use_err_help ) { 
2278   mp_print_nl(mp, "");
2279   @<Print the string |err_help|, possibly on several lines@>;
2280 } else { 
2281   while ( mp->help_ptr>0 ){ 
2282     decr(mp->help_ptr); mp_print_nl(mp, mp->help_line[mp->help_ptr]);
2283   };
2284 }
2285 mp_print_ln(mp);
2286 if ( mp->interaction>mp_batch_mode ) incr(mp->selector); /* re-enable terminal output */
2287 mp_print_ln(mp)
2288
2289 @ In anomalous cases, the print selector might be in an unknown state;
2290 the following subroutine is called to fix things just enough to keep
2291 running a bit longer.
2292
2293 @c 
2294 void mp_normalize_selector (MP mp) { 
2295   if ( mp->log_opened ) mp->selector=term_and_log;
2296   else mp->selector=term_only;
2297   if ( mp->job_name==NULL ) mp_open_log_file(mp);
2298   if ( mp->interaction==mp_batch_mode ) decr(mp->selector);
2299 }
2300
2301 @ The following procedure prints \MP's last words before dying.
2302
2303 @d succumb { if ( mp->interaction==mp_error_stop_mode )
2304     mp->interaction=mp_scroll_mode; /* no more interaction */
2305   if ( mp->log_opened ) mp_error(mp);
2306   /* if ( mp->interaction>mp_batch_mode ) mp_debug_help(mp); */
2307   mp->history=fatal_error_stop; mp_jump_out(mp); /* irrecoverable error */
2308   }
2309
2310 @<Error hand...@>=
2311 void mp_fatal_error (MP mp, char *s) { /* prints |s|, and that's it */
2312   mp_normalize_selector(mp);
2313   print_err("Emergency stop"); help1(s); succumb;
2314 @.Emergency stop@>
2315 }
2316
2317 @ @<Exported...@>=
2318 void mp_fatal_error (MP mp, char *s);
2319
2320
2321 @ Here is the most dreaded error message.
2322
2323 @<Error hand...@>=
2324 void mp_overflow (MP mp, char *s, integer n) { /* stop due to finiteness */
2325   mp_normalize_selector(mp);
2326   print_err("MetaPost capacity exceeded, sorry [");
2327 @.MetaPost capacity exceeded ...@>
2328   mp_print(mp, s); mp_print_char(mp, '='); mp_print_int(mp, n); mp_print_char(mp, ']');
2329   help2("If you really absolutely need more capacity,")
2330        ("you can ask a wizard to enlarge me.");
2331   succumb;
2332 }
2333
2334 @ @<Declarations@>=
2335 void mp_overflow (MP mp, char *s, integer n);
2336
2337 @ The program might sometime run completely amok, at which point there is
2338 no choice but to stop. If no previous error has been detected, that's bad
2339 news; a message is printed that is really intended for the \MP\
2340 maintenance person instead of the user (unless the user has been
2341 particularly diabolical).  The index entries for `this can't happen' may
2342 help to pinpoint the problem.
2343 @^dry rot@>
2344
2345 @<Declarations@>=
2346 void mp_confusion (MP mp,char *s);
2347
2348 @ @<Error hand...@>=
2349 void mp_confusion (MP mp,char *s) {
2350   /* consistency check violated; |s| tells where */
2351   mp_normalize_selector(mp);
2352   if ( mp->history<error_message_issued ) { 
2353     print_err("This can't happen ("); mp_print(mp, s); mp_print_char(mp, ')');
2354 @.This can't happen@>
2355     help1("I'm broken. Please show this to someone who can fix can fix");
2356   } else { 
2357     print_err("I can\'t go on meeting you like this");
2358 @.I can't go on...@>
2359     help2("One of your faux pas seems to have wounded me deeply...")
2360          ("in fact, I'm barely conscious. Please fix it and try again.");
2361   }
2362   succumb;
2363 }
2364
2365 @ Users occasionally want to interrupt \MP\ while it's running.
2366 If the \PASCAL\ runtime system allows this, one can implement
2367 a routine that sets the global variable |interrupt| to some nonzero value
2368 when such an interrupt is signaled. Otherwise there is probably at least
2369 a way to make |interrupt| nonzero using the \PASCAL\ debugger.
2370 @^system dependencies@>
2371 @^debugging@>
2372
2373 @d check_interrupt { if ( mp->interrupt!=0 )
2374    mp_pause_for_instructions(mp); }
2375
2376 @<Global...@>=
2377 integer interrupt; /* should \MP\ pause for instructions? */
2378 boolean OK_to_interrupt; /* should interrupts be observed? */
2379
2380 @ @<Allocate or ...@>=
2381 mp->interrupt=0; mp->OK_to_interrupt=true;
2382
2383 @ When an interrupt has been detected, the program goes into its
2384 highest interaction level and lets the user have the full flexibility of
2385 the |error| routine.  \MP\ checks for interrupts only at times when it is
2386 safe to do this.
2387
2388 @c 
2389 void mp_pause_for_instructions (MP mp) { 
2390   if ( mp->OK_to_interrupt ) { 
2391     mp->interaction=mp_error_stop_mode;
2392     if ( (mp->selector==log_only)||(mp->selector==no_print) )
2393       incr(mp->selector);
2394     print_err("Interruption");
2395 @.Interruption@>
2396     help3("You rang?")
2397          ("Try to insert some instructions for me (e.g.,`I show x'),")
2398          ("unless you just want to quit by typing `X'.");
2399     mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
2400     mp->interrupt=0;
2401   }
2402 }
2403
2404 @ Many of \MP's error messages state that a missing token has been
2405 inserted behind the scenes. We can save string space and program space
2406 by putting this common code into a subroutine.
2407
2408 @c 
2409 void mp_missing_err (MP mp, char *s) { 
2410   print_err("Missing `"); mp_print(mp, s); mp_print(mp, "' has been inserted");
2411 @.Missing...inserted@>
2412 }
2413
2414 @* \[7] Arithmetic with scaled numbers.
2415 The principal computations performed by \MP\ are done entirely in terms of
2416 integers less than $2^{31}$ in magnitude; thus, the arithmetic specified in this
2417 program can be carried out in exactly the same way on a wide variety of
2418 computers, including some small ones.
2419 @^small computers@>
2420
2421 But \PASCAL\ does not define the |div|
2422 operation in the case of negative dividends; for example, the result of
2423 |(-2*n-1) div 2| is |-(n+1)| on some computers and |-n| on others.
2424 There are two principal types of arithmetic: ``translation-preserving,''
2425 in which the identity |(a+q*b)div b=(a div b)+q| is valid; and
2426 ``negation-preserving,'' in which |(-a)div b=-(a div b)|. This leads to
2427 two \MP s, which can produce different results, although the differences
2428 should be negligible when the language is being used properly.
2429 The \TeX\ processor has been defined carefully so that both varieties
2430 of arithmetic will produce identical output, but it would be too
2431 inefficient to constrain \MP\ in a similar way.
2432
2433 @d el_gordo   017777777777 /* $2^{31}-1$, the largest value that \MP\ likes */
2434
2435 @ One of \MP's most common operations is the calculation of
2436 $\lfloor{a+b\over2}\rfloor$,
2437 the midpoint of two given integers |a| and~|b|. The only decent way to do
2438 this in \PASCAL\ is to write `|(a+b) div 2|'; but on most machines it is
2439 far more efficient to calculate `|(a+b)| right shifted one bit'.
2440
2441 Therefore the midpoint operation will always be denoted by `|half(a+b)|'
2442 in this program. If \MP\ is being implemented with languages that permit
2443 binary shifting, the |half| macro should be changed to make this operation
2444 as efficient as possible.  Since some languages have shift operators that can
2445 only be trusted to work on positive numbers, there is also a macro |halfp|
2446 that is used only when the quantity being halved is known to be positive
2447 or zero.
2448
2449 @d half(A) ((A)) / 2
2450 @d halfp(A) ((A)) / 2
2451
2452 @ A single computation might use several subroutine calls, and it is
2453 desirable to avoid producing multiple error messages in case of arithmetic
2454 overflow. So the routines below set the global variable |arith_error| to |true|
2455 instead of reporting errors directly to the user.
2456
2457 @<Glob...@>=
2458 boolean arith_error; /* has arithmetic overflow occurred recently? */
2459
2460 @ @<Allocate or ...@>=
2461 mp->arith_error=false;
2462
2463 @ At crucial points the program will say |check_arith|, to test if
2464 an arithmetic error has been detected.
2465
2466 @d check_arith { if ( mp->arith_error ) mp_clear_arith(mp); }
2467
2468 @c 
2469 void mp_clear_arith (MP mp) { 
2470   print_err("Arithmetic overflow");
2471 @.Arithmetic overflow@>
2472   help4("Uh, oh. A little while ago one of the quantities that I was")
2473        ("computing got too large, so I'm afraid your answers will be")
2474        ("somewhat askew. You'll probably have to adopt different")
2475        ("tactics next time. But I shall try to carry on anyway.");
2476   mp_error(mp); 
2477   mp->arith_error=false;
2478 }
2479
2480 @ Addition is not always checked to make sure that it doesn't overflow,
2481 but in places where overflow isn't too unlikely the |slow_add| routine
2482 is used.
2483
2484 @c integer mp_slow_add (MP mp,integer x, integer y) { 
2485   if ( x>=0 )  {
2486     if ( y<=el_gordo-x ) { 
2487       return x+y;
2488     } else  { 
2489       mp->arith_error=true; 
2490           return el_gordo;
2491     }
2492   } else  if ( -y<=el_gordo+x ) {
2493     return x+y;
2494   } else { 
2495     mp->arith_error=true; 
2496         return -el_gordo;
2497   }
2498 }
2499
2500 @ Fixed-point arithmetic is done on {\sl scaled integers\/} that are multiples
2501 of $2^{-16}$. In other words, a binary point is assumed to be sixteen bit
2502 positions from the right end of a binary computer word.
2503
2504 @d quarter_unit   040000 /* $2^{14}$, represents 0.250000 */
2505 @d half_unit   0100000 /* $2^{15}$, represents 0.50000 */
2506 @d three_quarter_unit   0140000 /* $3\cdot2^{14}$, represents 0.75000 */
2507 @d unity   0200000 /* $2^{16}$, represents 1.00000 */
2508 @d two   0400000 /* $2^{17}$, represents 2.00000 */
2509 @d three   0600000 /* $2^{17}+2^{16}$, represents 3.00000 */
2510
2511 @<Types...@>=
2512 typedef integer scaled; /* this type is used for scaled integers */
2513 typedef unsigned char small_number; /* this type is self-explanatory */
2514
2515 @ The following function is used to create a scaled integer from a given decimal
2516 fraction $(.d_0d_1\ldots d_{k-1})$, where |0<=k<=17|. The digit $d_i$ is
2517 given in |dig[i]|, and the calculation produces a correctly rounded result.
2518
2519 @c 
2520 scaled mp_round_decimals (MP mp,small_number k) {
2521   /* converts a decimal fraction */
2522  integer a = 0; /* the accumulator */
2523  while ( k-->0 ) { 
2524     a=(a+mp->dig[k]*two) / 10;
2525   }
2526   return halfp(a+1);
2527 }
2528
2529 @ Conversely, here is a procedure analogous to |print_int|. If the output
2530 of this procedure is subsequently read by \MP\ and converted by the
2531 |round_decimals| routine above, it turns out that the original value will
2532 be reproduced exactly. A decimal point is printed only if the value is
2533 not an integer. If there is more than one way to print the result with
2534 the optimum number of digits following the decimal point, the closest
2535 possible value is given.
2536
2537 The invariant relation in the \&{repeat} loop is that a sequence of
2538 decimal digits yet to be printed will yield the original number if and only if
2539 they form a fraction~$f$ in the range $s-\delta\L10\cdot2^{16}f<s$.
2540 We can stop if and only if $f=0$ satisfies this condition; the loop will
2541 terminate before $s$ can possibly become zero.
2542
2543 @<Basic printing...@>=
2544 void mp_print_scaled (MP mp,scaled s) { /* prints scaled real, rounded to five  digits */
2545   scaled delta; /* amount of allowable inaccuracy */
2546   if ( s<0 ) { 
2547         mp_print_char(mp, '-'); 
2548     negate(s); /* print the sign, if negative */
2549   }
2550   mp_print_int(mp, s / unity); /* print the integer part */
2551   s=10*(s % unity)+5;
2552   if ( s!=5 ) { 
2553     delta=10; 
2554     mp_print_char(mp, '.');
2555     do {  
2556       if ( delta>unity )
2557         s=s+0100000-(delta / 2); /* round the final digit */
2558       mp_print_char(mp, '0'+(s / unity)); 
2559       s=10*(s % unity); 
2560       delta=delta*10;
2561     } while (s>delta);
2562   }
2563 }
2564
2565 @ We often want to print two scaled quantities in parentheses,
2566 separated by a comma.
2567
2568 @<Basic printing...@>=
2569 void mp_print_two (MP mp,scaled x, scaled y) { /* prints `|(x,y)|' */
2570   mp_print_char(mp, '('); 
2571   mp_print_scaled(mp, x); 
2572   mp_print_char(mp, ','); 
2573   mp_print_scaled(mp, y);
2574   mp_print_char(mp, ')');
2575 }
2576
2577 @ The |scaled| quantities in \MP\ programs are generally supposed to be
2578 less than $2^{12}$ in absolute value, so \MP\ does much of its internal
2579 arithmetic with 28~significant bits of precision. A |fraction| denotes
2580 a scaled integer whose binary point is assumed to be 28 bit positions
2581 from the right.
2582
2583 @d fraction_half 01000000000 /* $2^{27}$, represents 0.50000000 */
2584 @d fraction_one 02000000000 /* $2^{28}$, represents 1.00000000 */
2585 @d fraction_two 04000000000 /* $2^{29}$, represents 2.00000000 */
2586 @d fraction_three 06000000000 /* $3\cdot2^{28}$, represents 3.00000000 */
2587 @d fraction_four 010000000000 /* $2^{30}$, represents 4.00000000 */
2588
2589 @<Types...@>=
2590 typedef integer fraction; /* this type is used for scaled fractions */
2591
2592 @ In fact, the two sorts of scaling discussed above aren't quite
2593 sufficient; \MP\ has yet another, used internally to keep track of angles
2594 in units of $2^{-20}$ degrees.
2595
2596 @d forty_five_deg 0264000000 /* $45\cdot2^{20}$, represents $45^\circ$ */
2597 @d ninety_deg 0550000000 /* $90\cdot2^{20}$, represents $90^\circ$ */
2598 @d one_eighty_deg 01320000000 /* $180\cdot2^{20}$, represents $180^\circ$ */
2599 @d three_sixty_deg 02640000000 /* $360\cdot2^{20}$, represents $360^\circ$ */
2600
2601 @<Types...@>=
2602 typedef integer angle; /* this type is used for scaled angles */
2603
2604 @ The |make_fraction| routine produces the |fraction| equivalent of
2605 |p/q|, given integers |p| and~|q|; it computes the integer
2606 $f=\lfloor2^{28}p/q+{1\over2}\rfloor$, when $p$ and $q$ are
2607 positive. If |p| and |q| are both of the same scaled type |t|,
2608 the ``type relation'' |make_fraction(t,t)=fraction| is valid;
2609 and it's also possible to use the subroutine ``backwards,'' using
2610 the relation |make_fraction(t,fraction)=t| between scaled types.
2611
2612 If the result would have magnitude $2^{31}$ or more, |make_fraction|
2613 sets |arith_error:=true|. Most of \MP's internal computations have
2614 been designed to avoid this sort of error.
2615
2616 If this subroutine were programmed in assembly language on a typical
2617 machine, we could simply compute |(@t$2^{28}$@>*p)div q|, since a
2618 double-precision product can often be input to a fixed-point division
2619 instruction. But when we are restricted to \PASCAL\ arithmetic it
2620 is necessary either to resort to multiple-precision maneuvering
2621 or to use a simple but slow iteration. The multiple-precision technique
2622 would be about three times faster than the code adopted here, but it
2623 would be comparatively long and tricky, involving about sixteen
2624 additional multiplications and divisions.
2625
2626 This operation is part of \MP's ``inner loop''; indeed, it will
2627 consume nearly 10\pct! of the running time (exclusive of input and output)
2628 if the code below is left unchanged. A machine-dependent recoding
2629 will therefore make \MP\ run faster. The present implementation
2630 is highly portable, but slow; it avoids multiplication and division
2631 except in the initial stage. System wizards should be careful to
2632 replace it with a routine that is guaranteed to produce identical
2633 results in all cases.
2634 @^system dependencies@>
2635
2636 As noted below, a few more routines should also be replaced by machine-dependent
2637 code, for efficiency. But when a procedure is not part of the ``inner loop,''
2638 such changes aren't advisable; simplicity and robustness are
2639 preferable to trickery, unless the cost is too high.
2640 @^inner loop@>
2641
2642 @<Exported...@>=
2643 fraction mp_make_fraction (MP mp,integer p, integer q);
2644 integer mp_take_scaled (MP mp,integer q, scaled f) ;
2645
2646 @ If FIXPT is not defined, we need these preprocessor values
2647
2648 @d ELGORDO  0x7fffffff
2649 @d TWEXP31  2147483648.0
2650 @d TWEXP28  268435456.0
2651 @d TWEXP16 65536.0
2652 @d TWEXP_16 (1.0/65536.0)
2653 @d TWEXP_28 (1.0/268435456.0)
2654
2655
2656 @c 
2657 fraction mp_make_fraction (MP mp,integer p, integer q) {
2658 #ifdef FIXPT
2659   integer f; /* the fraction bits, with a leading 1 bit */
2660   integer n; /* the integer part of $\vert p/q\vert$ */
2661   integer be_careful; /* disables certain compiler optimizations */
2662   boolean negative = false; /* should the result be negated? */
2663   if ( p<0 ) {
2664     negate(p); negative=true;
2665   }
2666   if ( q<=0 ) { 
2667 #ifdef DEBUG
2668     if ( q==0 ) mp_confusion(mp, '/');
2669 #endif
2670 @:this can't happen /}{\quad \./@>
2671     negate(q); negative = ! negative;
2672   };
2673   n=p / q; p=p % q;
2674   if ( n>=8 ){ 
2675     mp->arith_error=true;
2676     return ( negative ? -el_gordo : el_gordo);
2677   } else { 
2678     n=(n-1)*fraction_one;
2679     @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>;
2680     return (negative ? (-(f+n)) : (f+n));
2681   }
2682 #else /* FIXPT */
2683     register double d;
2684         register integer i;
2685 #ifdef DEBUG
2686         if (q==0) mp_confusion(mp,'/'); 
2687 #endif /* DEBUG */
2688         d = TWEXP28 * (double)p /(double)q;
2689         if ((p^q) >= 0) {
2690                 d += 0.5;
2691                 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
2692                 i = (integer) d;
2693                 if (d==i && ( ((q>0 ? -q : q)&077777)
2694                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2695         } else {
2696                 d -= 0.5;
2697                 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
2698                 i = (integer) d;
2699                 if (d==i && ( ((q>0 ? q : -q)&077777)
2700                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
2701         }
2702         return i;
2703 #endif /* FIXPT */
2704 }
2705
2706 @ The |repeat| loop here preserves the following invariant relations
2707 between |f|, |p|, and~|q|:
2708 (i)~|0<=p<q|; (ii)~$fq+p=2^k(q+p_0)$, where $k$ is an integer and
2709 $p_0$ is the original value of~$p$.
2710
2711 Notice that the computation specifies
2712 |(p-q)+p| instead of |(p+p)-q|, because the latter could overflow.
2713 Let us hope that optimizing compilers do not miss this point; a
2714 special variable |be_careful| is used to emphasize the necessary
2715 order of computation. Optimizing compilers should keep |be_careful|
2716 in a register, not store it in memory.
2717 @^inner loop@>
2718
2719 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>=
2720 {
2721   f=1;
2722   do {  
2723     be_careful=p-q; p=be_careful+p;
2724     if ( p>=0 ) { 
2725       f=f+f+1;
2726     } else  { 
2727       f+=f; p=p+q;
2728     }
2729   } while (f<fraction_one);
2730   be_careful=p-q;
2731   if ( be_careful+p>=0 ) incr(f);
2732 }
2733
2734 @ The dual of |make_fraction| is |take_fraction|, which multiplies a
2735 given integer~|q| by a fraction~|f|. When the operands are positive, it
2736 computes $p=\lfloor qf/2^{28}+{1\over2}\rfloor$, a symmetric function
2737 of |q| and~|f|.
2738
2739 This routine is even more ``inner loopy'' than |make_fraction|;
2740 the present implementation consumes almost 20\pct! of \MP's computation
2741 time during typical jobs, so a machine-language substitute is advisable.
2742 @^inner loop@> @^system dependencies@>
2743
2744 @<Declarations@>=
2745 integer mp_take_fraction (MP mp,integer q, fraction f) ;
2746
2747 @ @c 
2748 #ifdef FIXPT
2749 integer mp_take_fraction (MP mp,integer q, fraction f) {
2750   integer p; /* the fraction so far */
2751   boolean negative; /* should the result be negated? */
2752   integer n; /* additional multiple of $q$ */
2753   integer be_careful; /* disables certain compiler optimizations */
2754   @<Reduce to the case that |f>=0| and |q>0|@>;
2755   if ( f<fraction_one ) { 
2756     n=0;
2757   } else { 
2758     n=f / fraction_one; f=f % fraction_one;
2759     if ( q<=el_gordo / n ) { 
2760       n=n*q ; 
2761     } else { 
2762       mp->arith_error=true; n=el_gordo;
2763     }
2764   }
2765   f=f+fraction_one;
2766   @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>;
2767   be_careful=n-el_gordo;
2768   if ( be_careful+p>0 ){ 
2769     mp->arith_error=true; n=el_gordo-p;
2770   }
2771   if ( negative ) 
2772         return (-(n+p));
2773   else 
2774     return (n+p);
2775 #else /* FIXPT */
2776 integer mp_take_fraction (MP mp,integer p, fraction q) {
2777     register double d;
2778         register integer i;
2779         d = (double)p * (double)q * TWEXP_28;
2780         if ((p^q) >= 0) {
2781                 d += 0.5;
2782                 if (d>=TWEXP31) {
2783                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2784                                 mp->arith_error = true;
2785                         return ELGORDO;
2786                 }
2787                 i = (integer) d;
2788                 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2789         } else {
2790                 d -= 0.5;
2791                 if (d<= -TWEXP31) {
2792                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2793                                 mp->arith_error = true;
2794                         return -ELGORDO;
2795                 }
2796                 i = (integer) d;
2797                 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2798         }
2799         return i;
2800 #endif /* FIXPT */
2801 }
2802
2803 @ @<Reduce to the case that |f>=0| and |q>0|@>=
2804 if ( f>=0 ) {
2805   negative=false;
2806 } else { 
2807   negate( f); negative=true;
2808 }
2809 if ( q<0 ) { 
2810   negate(q); negative=! negative;
2811 }
2812
2813 @ The invariant relations in this case are (i)~$\lfloor(qf+p)/2^k\rfloor
2814 =\lfloor qf_0/2^{28}+{1\over2}\rfloor$, where $k$ is an integer and
2815 $f_0$ is the original value of~$f$; (ii)~$2^k\L f<2^{k+1}$.
2816 @^inner loop@>
2817
2818 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>=
2819 p=fraction_half; /* that's $2^{27}$; the invariants hold now with $k=28$ */
2820 if ( q<fraction_four ) {
2821   do {  
2822     if ( odd(f) ) p=halfp(p+q); else p=halfp(p);
2823     f=halfp(f);
2824   } while (f!=1);
2825 } else  {
2826   do {  
2827     if ( odd(f) ) p=p+halfp(q-p); else p=halfp(p);
2828     f=halfp(f);
2829   } while (f!=1);
2830 }
2831
2832
2833 @ When we want to multiply something by a |scaled| quantity, we use a scheme
2834 analogous to |take_fraction| but with a different scaling.
2835 Given positive operands, |take_scaled|
2836 computes the quantity $p=\lfloor qf/2^{16}+{1\over2}\rfloor$.
2837
2838 Once again it is a good idea to use a machine-language replacement if
2839 possible; otherwise |take_scaled| will use more than 2\pct! of the running time
2840 when the Computer Modern fonts are being generated.
2841 @^inner loop@>
2842
2843 @c 
2844 #ifdef FIXPT
2845 integer mp_take_scaled (MP mp,integer q, scaled f) {
2846   integer p; /* the fraction so far */
2847   boolean negative; /* should the result be negated? */
2848   integer n; /* additional multiple of $q$ */
2849   integer be_careful; /* disables certain compiler optimizations */
2850   @<Reduce to the case that |f>=0| and |q>0|@>;
2851   if ( f<unity ) { 
2852     n=0;
2853   } else  { 
2854     n=f / unity; f=f % unity;
2855     if ( q<=el_gordo / n ) {
2856       n=n*q;
2857     } else  { 
2858       mp->arith_error=true; n=el_gordo;
2859     }
2860   }
2861   f=f+unity;
2862   @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>;
2863   be_careful=n-el_gordo;
2864   if ( be_careful+p>0 ) { 
2865     mp->arith_error=true; n=el_gordo-p;
2866   }
2867   return ( negative ?(-(n+p)) :(n+p));
2868 #else /* FIXPT */
2869 integer mp_take_scaled (MP mp,integer p, scaled q) {
2870     register double d;
2871         register integer i;
2872         d = (double)p * (double)q * TWEXP_16;
2873         if ((p^q) >= 0) {
2874                 d += 0.5;
2875                 if (d>=TWEXP31) {
2876                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2877                                 mp->arith_error = true;
2878                         return ELGORDO;
2879                 }
2880                 i = (integer) d;
2881                 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2882         } else {
2883                 d -= 0.5;
2884                 if (d<= -TWEXP31) {
2885                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2886                                 mp->arith_error = true;
2887                         return -ELGORDO;
2888                 }
2889                 i = (integer) d;
2890                 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2891         }
2892         return i;
2893 #endif /* FIXPT */
2894 }
2895
2896 @ @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>=
2897 p=half_unit; /* that's $2^{15}$; the invariants hold now with $k=16$ */
2898 @^inner loop@>
2899 if ( q<fraction_four ) {
2900   do {  
2901     p = (odd(f) ? halfp(p+q) : halfp(p));
2902     f=halfp(f);
2903   } while (f!=1);
2904 } else {
2905   do {  
2906     p = (odd(f) ? p+halfp(q-p) : halfp(p));
2907     f=halfp(f);
2908   } while (f!=1);
2909 }
2910
2911 @ For completeness, there's also |make_scaled|, which computes a
2912 quotient as a |scaled| number instead of as a |fraction|.
2913 In other words, the result is $\lfloor2^{16}p/q+{1\over2}\rfloor$, if the
2914 operands are positive. \ (This procedure is not used especially often,
2915 so it is not part of \MP's inner loop.)
2916
2917 @c 
2918 scaled mp_make_scaled (MP mp,integer p, integer q) {
2919 #ifdef FIXPT 
2920   integer f; /* the fraction bits, with a leading 1 bit */
2921   integer n; /* the integer part of $\vert p/q\vert$ */
2922   boolean negative; /* should the result be negated? */
2923   integer be_careful; /* disables certain compiler optimizations */
2924   if ( p>=0 ) negative=false;
2925   else  { negate(p); negative=true; };
2926   if ( q<=0 ) { 
2927 #ifdef DEBUG 
2928     if ( q==0 ) mp_confusion(mp, "/");
2929 @:this can't happen /}{\quad \./@>
2930 #endif
2931     negate(q); negative=! negative;
2932   }
2933   n=p / q; p=p % q;
2934   if ( n>=0100000 ) { 
2935     mp->arith_error=true;
2936     return (negative ? (-el_gordo) : el_gordo);
2937   } else  { 
2938     n=(n-1)*unity;
2939     @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>;
2940     return ( negative ? (-(f+n)) :(f+n));
2941   }
2942 #else /* FIXPT */
2943     register double d;
2944         register integer i;
2945 #ifdef DEBUG
2946         if (q==0) mp_confusion(mp,"/"); 
2947 #endif /* DEBUG */
2948         d = TWEXP16 * (double)p /(double)q;
2949         if ((p^q) >= 0) {
2950                 d += 0.5;
2951                 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
2952                 i = (integer) d;
2953                 if (d==i && ( ((q>0 ? -q : q)&077777)
2954                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2955         } else {
2956                 d -= 0.5;
2957                 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
2958                 i = (integer) d;
2959                 if (d==i && ( ((q>0 ? q : -q)&077777)
2960                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
2961         }
2962         return i;
2963 #endif /* FIXPT */
2964 }
2965
2966 @ @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>=
2967 f=1;
2968 do {  
2969   be_careful=p-q; p=be_careful+p;
2970   if ( p>=0 ) f=f+f+1;
2971   else  { f+=f; p=p+q; };
2972 } while (f<unity);
2973 be_careful=p-q;
2974 if ( be_careful+p>=0 ) incr(f)
2975
2976 @ Here is a typical example of how the routines above can be used.
2977 It computes the function
2978 $${1\over3\tau}f(\theta,\phi)=
2979 {\tau^{-1}\bigl(2+\sqrt2\,(\sin\theta-{1\over16}\sin\phi)
2980  (\sin\phi-{1\over16}\sin\theta)(\cos\theta-\cos\phi)\bigr)\over
2981 3\,\bigl(1+{1\over2}(\sqrt5-1)\cos\theta+{1\over2}(3-\sqrt5\,)\cos\phi\bigr)},$$
2982 where $\tau$ is a |scaled| ``tension'' parameter. This is \MP's magic
2983 fudge factor for placing the first control point of a curve that starts
2984 at an angle $\theta$ and ends at an angle $\phi$ from the straight path.
2985 (Actually, if the stated quantity exceeds 4, \MP\ reduces it to~4.)
2986
2987 The trigonometric quantity to be multiplied by $\sqrt2$ is less than $\sqrt2$.
2988 (It's a sum of eight terms whose absolute values can be bounded using
2989 relations such as $\sin\theta\cos\theta\L{1\over2}$.) Thus the numerator
2990 is positive; and since the tension $\tau$ is constrained to be at least
2991 $3\over4$, the numerator is less than $16\over3$. The denominator is
2992 nonnegative and at most~6.  Hence the fixed-point calculations below
2993 are guaranteed to stay within the bounds of a 32-bit computer word.
2994
2995 The angles $\theta$ and $\phi$ are given implicitly in terms of |fraction|
2996 arguments |st|, |ct|, |sf|, and |cf|, representing $\sin\theta$, $\cos\theta$,
2997 $\sin\phi$, and $\cos\phi$, respectively.
2998
2999 @c 
3000 fraction mp_velocity (MP mp,fraction st, fraction ct, fraction sf,
3001                       fraction cf, scaled t) {
3002   integer acc,num,denom; /* registers for intermediate calculations */
3003   acc=mp_take_fraction(mp, st-(sf / 16), sf-(st / 16));
3004   acc=mp_take_fraction(mp, acc,ct-cf);
3005   num=fraction_two+mp_take_fraction(mp, acc,379625062);
3006                    /* $2^{28}\sqrt2\approx379625062.497$ */
3007   denom=fraction_three+mp_take_fraction(mp, ct,497706707)+mp_take_fraction(mp, cf,307599661);
3008                       /* $3\cdot2^{27}\cdot(\sqrt5-1)\approx497706706.78$ and
3009                          $3\cdot2^{27}\cdot(3-\sqrt5\,)\approx307599661.22$ */
3010   if ( t!=unity ) num=mp_make_scaled(mp, num,t);
3011   /* |make_scaled(fraction,scaled)=fraction| */
3012   if ( num / 4>=denom ) 
3013     return fraction_four;
3014   else 
3015     return mp_make_fraction(mp, num, denom);
3016 }
3017
3018 @ The following somewhat different subroutine tests rigorously if $ab$ is
3019 greater than, equal to, or less than~$cd$,
3020 given integers $(a,b,c,d)$. In most cases a quick decision is reached.
3021 The result is $+1$, 0, or~$-1$ in the three respective cases.
3022
3023 @d mp_ab_vs_cd(M,A,B,C,D) mp_do_ab_vs_cd(A,B,C,D)
3024
3025 @c 
3026 integer mp_do_ab_vs_cd (integer a,integer b, integer c, integer d) {
3027   integer q,r; /* temporary registers */
3028   @<Reduce to the case that |a,c>=0|, |b,d>0|@>;
3029   while (1) { 
3030     q = a / d; r = c / b;
3031     if ( q!=r )
3032       return ( q>r ? 1 : -1);
3033     q = a % d; r = c % b;
3034     if ( r==0 )
3035       return (q ? 1 : 0);
3036     if ( q==0 ) return -1;
3037     a=b; b=q; c=d; d=r;
3038   } /* now |a>d>0| and |c>b>0| */
3039 }
3040
3041 @ @<Reduce to the case that |a...@>=
3042 if ( a<0 ) { negate(a); negate(b);  };
3043 if ( c<0 ) { negate(c); negate(d);  };
3044 if ( d<=0 ) { 
3045   if ( b>=0 ) {
3046     if ( (a==0||b==0)&&(c==0||d==0) ) return 0;
3047     else return 1;
3048   }
3049   if ( d==0 )
3050     return ( a==0 ? 0 : -1);
3051   q=a; a=c; c=q; q=-b; b=-d; d=q;
3052 } else if ( b<=0 ) { 
3053   if ( b<0 ) if ( a>0 ) return -1;
3054   return (c==0 ? 0 : -1);
3055 }
3056
3057 @ We conclude this set of elementary routines with some simple rounding
3058 and truncation operations that are coded in a machine-independent fashion.
3059 The routines are slightly complicated because we want them to work
3060 without overflow whenever $-2^{31}\L x<2^{31}$.
3061
3062 @<Declarations@>=
3063 #define mp_floor_scaled(M,i) ((i)&(-65536))
3064 #define mp_round_unscaled(M,i) (((i>>15)+1)>>1)
3065 #define mp_round_fraction(M,i) (((i>>11)+1)>>1)
3066
3067
3068 @* \[8] Algebraic and transcendental functions.
3069 \MP\ computes all of the necessary special functions from scratch, without
3070 relying on |real| arithmetic or system subroutines for sines, cosines, etc.
3071
3072 @ To get the square root of a |scaled| number |x|, we want to calculate
3073 $s=\lfloor 2^8\!\sqrt x +{1\over2}\rfloor$. If $x>0$, this is the unique
3074 integer such that $2^{16}x-s\L s^2<2^{16}x+s$. The following subroutine
3075 determines $s$ by an iterative method that maintains the invariant
3076 relations $x=2^{46-2k}x_0\bmod 2^{30}$, $0<y=\lfloor 2^{16-2k}x_0\rfloor
3077 -s^2+s\L q=2s$, where $x_0$ is the initial value of $x$. The value of~$y$
3078 might, however, be zero at the start of the first iteration.
3079
3080 @<Declarations@>=
3081 scaled mp_square_rt (MP mp,scaled x) ;
3082
3083 @ @c 
3084 scaled mp_square_rt (MP mp,scaled x) {
3085   small_number k; /* iteration control counter */
3086   integer y,q; /* registers for intermediate calculations */
3087   if ( x<=0 ) { 
3088     @<Handle square root of zero or negative argument@>;
3089   } else { 
3090     k=23; q=2;
3091     while ( x<fraction_two ) { /* i.e., |while x<@t$2^{29}$@>|\unskip */
3092       decr(k); x=x+x+x+x;
3093     }
3094     if ( x<fraction_four ) y=0;
3095     else  { x=x-fraction_four; y=1; };
3096     do {  
3097       @<Decrease |k| by 1, maintaining the invariant
3098       relations between |x|, |y|, and~|q|@>;
3099     } while (k!=0);
3100     return (halfp(q));
3101   }
3102 }
3103
3104 @ @<Handle square root of zero...@>=
3105
3106   if ( x<0 ) { 
3107     print_err("Square root of ");
3108 @.Square root...replaced by 0@>
3109     mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3110     help2("Since I don't take square roots of negative numbers,")
3111          ("I'm zeroing this one. Proceed, with fingers crossed.");
3112     mp_error(mp);
3113   };
3114   return 0;
3115 }
3116
3117 @ @<Decrease |k| by 1, maintaining...@>=
3118 x+=x; y+=y;
3119 if ( x>=fraction_four ) { /* note that |fraction_four=@t$2^{30}$@>| */
3120   x=x-fraction_four; incr(y);
3121 };
3122 x+=x; y=y+y-q; q+=q;
3123 if ( x>=fraction_four ) { x=x-fraction_four; incr(y); };
3124 if ( y>q ){ y=y-q; q=q+2; }
3125 else if ( y<=0 )  { q=q-2; y=y+q;  };
3126 decr(k)
3127
3128 @ Pythagorean addition $\psqrt{a^2+b^2}$ is implemented by an elegant
3129 iterative scheme due to Cleve Moler and Donald Morrison [{\sl IBM Journal
3130 @^Moler, Cleve Barry@>
3131 @^Morrison, Donald Ross@>
3132 of Research and Development\/ \bf27} (1983), 577--581]. It modifies |a| and~|b|
3133 in such a way that their Pythagorean sum remains invariant, while the
3134 smaller argument decreases.
3135
3136 @c 
3137 integer mp_pyth_add (MP mp,integer a, integer b) {
3138   fraction r; /* register used to transform |a| and |b| */
3139   boolean big; /* is the result dangerously near $2^{31}$? */
3140   a=abs(a); b=abs(b);
3141   if ( a<b ) { r=b; b=a; a=r; }; /* now |0<=b<=a| */
3142   if ( b>0 ) {
3143     if ( a<fraction_two ) {
3144       big=false;
3145     } else { 
3146       a=a / 4; b=b / 4; big=true;
3147     }; /* we reduced the precision to avoid arithmetic overflow */
3148     @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>;
3149     if ( big ) {
3150       if ( a<fraction_two ) {
3151         a=a+a+a+a;
3152       } else  { 
3153         mp->arith_error=true; a=el_gordo;
3154       };
3155     }
3156   }
3157   return a;
3158 }
3159
3160 @ The key idea here is to reflect the vector $(a,b)$ about the
3161 line through $(a,b/2)$.
3162
3163 @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>=
3164 while (1) {  
3165   r=mp_make_fraction(mp, b,a);
3166   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3167   if ( r==0 ) break;
3168   r=mp_make_fraction(mp, r,fraction_four+r);
3169   a=a+mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3170 }
3171
3172
3173 @ Here is a similar algorithm for $\psqrt{a^2-b^2}$.
3174 It converges slowly when $b$ is near $a$, but otherwise it works fine.
3175
3176 @c 
3177 integer mp_pyth_sub (MP mp,integer a, integer b) {
3178   fraction r; /* register used to transform |a| and |b| */
3179   boolean big; /* is the input dangerously near $2^{31}$? */
3180   a=abs(a); b=abs(b);
3181   if ( a<=b ) {
3182     @<Handle erroneous |pyth_sub| and set |a:=0|@>;
3183   } else { 
3184     if ( a<fraction_four ) {
3185       big=false;
3186     } else  { 
3187       a=halfp(a); b=halfp(b); big=true;
3188     }
3189     @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>;
3190     if ( big ) a=a+a;
3191   }
3192   return a;
3193 }
3194
3195 @ @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>=
3196 while (1) { 
3197   r=mp_make_fraction(mp, b,a);
3198   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3199   if ( r==0 ) break;
3200   r=mp_make_fraction(mp, r,fraction_four-r);
3201   a=a-mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3202 }
3203
3204 @ @<Handle erroneous |pyth_sub| and set |a:=0|@>=
3205
3206   if ( a<b ){ 
3207     print_err("Pythagorean subtraction "); mp_print_scaled(mp, a);
3208     mp_print(mp, "+-+"); mp_print_scaled(mp, b); 
3209     mp_print(mp, " has been replaced by 0");
3210 @.Pythagorean...@>
3211     help2("Since I don't take square roots of negative numbers,")
3212          ("I'm zeroing this one. Proceed, with fingers crossed.");
3213     mp_error(mp);
3214   }
3215   a=0;
3216 }
3217
3218 @ The subroutines for logarithm and exponential involve two tables.
3219 The first is simple: |two_to_the[k]| equals $2^k$. The second involves
3220 a bit more calculation, which the author claims to have done correctly:
3221 |spec_log[k]| is $2^{27}$ times $\ln\bigl(1/(1-2^{-k})\bigr)=
3222 2^{-k}+{1\over2}2^{-2k}+{1\over3}2^{-3k}+\cdots\,$, rounded to the
3223 nearest integer.
3224
3225 @d two_to_the(A) (1<<(A))
3226
3227 @<Constants ...@>=
3228 static const integer spec_log[29] = { 0, /* special logarithms */
3229 93032640, 38612034, 17922280, 8662214, 4261238, 2113709,
3230 1052693, 525315, 262400, 131136, 65552, 32772, 16385,
3231 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 1 };
3232
3233 @ @<Local variables for initialization@>=
3234 integer k; /* all-purpose loop index */
3235
3236
3237 @ Here is the routine that calculates $2^8$ times the natural logarithm
3238 of a |scaled| quantity; it is an integer approximation to $2^{24}\ln(x/2^{16})$,
3239 when |x| is a given positive integer.
3240
3241 The method is based on exercise 1.2.2--25 in {\sl The Art of Computer
3242 Programming\/}: During the main iteration we have $1\L 2^{-30}x<1/(1-2^{1-k})$,
3243 and the logarithm of $2^{30}x$ remains to be added to an accumulator
3244 register called~$y$. Three auxiliary bits of accuracy are retained in~$y$
3245 during the calculation, and sixteen auxiliary bits to extend |y| are
3246 kept in~|z| during the initial argument reduction. (We add
3247 $100\cdot2^{16}=6553600$ to~|z| and subtract 100 from~|y| so that |z| will
3248 not become negative; also, the actual amount subtracted from~|y| is~96,
3249 not~100, because we want to add~4 for rounding before the final division by~8.)
3250
3251 @c 
3252 scaled mp_m_log (MP mp,scaled x) {
3253   integer y,z; /* auxiliary registers */
3254   integer k; /* iteration counter */
3255   if ( x<=0 ) {
3256      @<Handle non-positive logarithm@>;
3257   } else  { 
3258     y=1302456956+4-100; /* $14\times2^{27}\ln2\approx1302456956.421063$ */
3259     z=27595+6553600; /* and $2^{16}\times .421063\approx 27595$ */
3260     while ( x<fraction_four ) {
3261        x+=x; y=y-93032639; z=z-48782;
3262     } /* $2^{27}\ln2\approx 93032639.74436163$ and $2^{16}\times.74436163\approx 48782$ */
3263     y=y+(z / unity); k=2;
3264     while ( x>fraction_four+4 ) {
3265       @<Increase |k| until |x| can be multiplied by a
3266         factor of $2^{-k}$, and adjust $y$ accordingly@>;
3267     }
3268     return (y / 8);
3269   }
3270 }
3271
3272 @ @<Increase |k| until |x| can...@>=
3273
3274   z=((x-1) / two_to_the(k))+1; /* $z=\lceil x/2^k\rceil$ */
3275   while ( x<fraction_four+z ) { z=halfp(z+1); k=k+1; };
3276   y=y+spec_log[k]; x=x-z;
3277 }
3278
3279 @ @<Handle non-positive logarithm@>=
3280
3281   print_err("Logarithm of ");
3282 @.Logarithm...replaced by 0@>
3283   mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3284   help2("Since I don't take logs of non-positive numbers,")
3285        ("I'm zeroing this one. Proceed, with fingers crossed.");
3286   mp_error(mp); 
3287   return 0;
3288 }
3289
3290 @ Conversely, the exponential routine calculates $\exp(x/2^8)$,
3291 when |x| is |scaled|. The result is an integer approximation to
3292 $2^{16}\exp(x/2^{24})$, when |x| is regarded as an integer.
3293
3294 @c 
3295 scaled mp_m_exp (MP mp,scaled x) {
3296   small_number k; /* loop control index */
3297   integer y,z; /* auxiliary registers */
3298   if ( x>174436200 ) {
3299     /* $2^{24}\ln((2^{31}-1)/2^{16})\approx 174436199.51$ */
3300     mp->arith_error=true; 
3301     return el_gordo;
3302   } else if ( x<-197694359 ) {
3303         /* $2^{24}\ln(2^{-1}/2^{16})\approx-197694359.45$ */
3304     return 0;
3305   } else { 
3306     if ( x<=0 ) { 
3307        z=-8*x; y=04000000; /* $y=2^{20}$ */
3308     } else { 
3309       if ( x<=127919879 ) { 
3310         z=1023359037-8*x;
3311         /* $2^{27}\ln((2^{31}-1)/2^{20})\approx 1023359037.125$ */
3312       } else {
3313        z=8*(174436200-x); /* |z| is always nonnegative */
3314       }
3315       y=el_gordo;
3316     };
3317     @<Multiply |y| by $\exp(-z/2^{27})$@>;
3318     if ( x<=127919879 ) 
3319        return ((y+8) / 16);
3320      else 
3321        return y;
3322   }
3323 }
3324
3325 @ The idea here is that subtracting |spec_log[k]| from |z| corresponds
3326 to multiplying |y| by $1-2^{-k}$.
3327
3328 A subtle point (which had to be checked) was that if $x=127919879$, the
3329 value of~|y| will decrease so that |y+8| doesn't overflow. In fact,
3330 $z$ will be 5 in this case, and |y| will decrease by~64 when |k=25|
3331 and by~16 when |k=27|.
3332
3333 @<Multiply |y| by...@>=
3334 k=1;
3335 while ( z>0 ) { 
3336   while ( z>=spec_log[k] ) { 
3337     z-=spec_log[k];
3338     y=y-1-((y-two_to_the(k-1)) / two_to_the(k));
3339   }
3340   incr(k);
3341 }
3342
3343 @ The trigonometric subroutines use an auxiliary table such that
3344 |spec_atan[k]| contains an approximation to the |angle| whose tangent
3345 is~$1/2^k$. $\arctan2^{-k}$ times $2^{20}\cdot180/\pi$ 
3346
3347 @<Constants ...@>=
3348 static const angle spec_atan[27] = { 0, 27855475, 14718068, 7471121, 3750058, 
3349 1876857, 938658, 469357, 234682, 117342, 58671, 29335, 14668, 7334, 3667, 
3350 1833, 917, 458, 229, 115, 57, 29, 14, 7, 4, 2, 1 };
3351
3352 @ Given integers |x| and |y|, not both zero, the |n_arg| function
3353 returns the |angle| whose tangent points in the direction $(x,y)$.
3354 This subroutine first determines the correct octant, then solves the
3355 problem for |0<=y<=x|, then converts the result appropriately to
3356 return an answer in the range |-one_eighty_deg<=@t$\theta$@><=one_eighty_deg|.
3357 (The answer is |+one_eighty_deg| if |y=0| and |x<0|, but an answer of
3358 |-one_eighty_deg| is possible if, for example, |y=-1| and $x=-2^{30}$.)
3359
3360 The octants are represented in a ``Gray code,'' since that turns out
3361 to be computationally simplest.
3362
3363 @d negate_x 1
3364 @d negate_y 2
3365 @d switch_x_and_y 4
3366 @d first_octant 1
3367 @d second_octant (first_octant+switch_x_and_y)
3368 @d third_octant (first_octant+switch_x_and_y+negate_x)
3369 @d fourth_octant (first_octant+negate_x)
3370 @d fifth_octant (first_octant+negate_x+negate_y)
3371 @d sixth_octant (first_octant+switch_x_and_y+negate_x+negate_y)
3372 @d seventh_octant (first_octant+switch_x_and_y+negate_y)
3373 @d eighth_octant (first_octant+negate_y)
3374
3375 @c 
3376 angle mp_n_arg (MP mp,integer x, integer y) {
3377   angle z; /* auxiliary register */
3378   integer t; /* temporary storage */
3379   small_number k; /* loop counter */
3380   int octant; /* octant code */
3381   if ( x>=0 ) {
3382     octant=first_octant;
3383   } else { 
3384     negate(x); octant=first_octant+negate_x;
3385   }
3386   if ( y<0 ) { 
3387     negate(y); octant=octant+negate_y;
3388   }
3389   if ( x<y ) { 
3390     t=y; y=x; x=t; octant=octant+switch_x_and_y;
3391   }
3392   if ( x==0 ) { 
3393     @<Handle undefined arg@>; 
3394   } else { 
3395     @<Set variable |z| to the arg of $(x,y)$@>;
3396     @<Return an appropriate answer based on |z| and |octant|@>;
3397   }
3398 }
3399
3400 @ @<Handle undefined arg@>=
3401
3402   print_err("angle(0,0) is taken as zero");
3403 @.angle(0,0)...zero@>
3404   help2("The `angle' between two identical points is undefined.")
3405        ("I'm zeroing this one. Proceed, with fingers crossed.");
3406   mp_error(mp); 
3407   return 0;
3408 }
3409
3410 @ @<Return an appropriate answer...@>=
3411 switch (octant) {
3412 case first_octant: return z;
3413 case second_octant: return (ninety_deg-z);
3414 case third_octant: return (ninety_deg+z);
3415 case fourth_octant: return (one_eighty_deg-z);
3416 case fifth_octant: return (z-one_eighty_deg);
3417 case sixth_octant: return (-z-ninety_deg);
3418 case seventh_octant: return (z-ninety_deg);
3419 case eighth_octant: return (-z);
3420 }; /* there are no other cases */
3421 return 0
3422
3423 @ At this point we have |x>=y>=0|, and |x>0|. The numbers are scaled up
3424 or down until $2^{28}\L x<2^{29}$, so that accurate fixed-point calculations
3425 will be made.
3426
3427 @<Set variable |z| to the arg...@>=
3428 while ( x>=fraction_two ) { 
3429   x=halfp(x); y=halfp(y);
3430 }
3431 z=0;
3432 if ( y>0 ) { 
3433  while ( x<fraction_one ) { 
3434     x+=x; y+=y; 
3435  };
3436  @<Increase |z| to the arg of $(x,y)$@>;
3437 }
3438
3439 @ During the calculations of this section, variables |x| and~|y|
3440 represent actual coordinates $(x,2^{-k}y)$. We will maintain the
3441 condition |x>=y|, so that the tangent will be at most $2^{-k}$.
3442 If $x<2y$, the tangent is greater than $2^{-k-1}$. The transformation
3443 $(a,b)\mapsto(a+b\tan\phi,b-a\tan\phi)$ replaces $(a,b)$ by
3444 coordinates whose angle has decreased by~$\phi$; in the special case
3445 $a=x$, $b=2^{-k}y$, and $\tan\phi=2^{-k-1}$, this operation reduces
3446 to the particularly simple iteration shown here. [Cf.~John E. Meggitt,
3447 @^Meggitt, John E.@>
3448 {\sl IBM Journal of Research and Development\/ \bf6} (1962), 210--226.]
3449
3450 The initial value of |x| will be multiplied by at most
3451 $(1+{1\over2})(1+{1\over8})(1+{1\over32})\cdots\approx 1.7584$; hence
3452 there is no chance of integer overflow.
3453
3454 @<Increase |z|...@>=
3455 k=0;
3456 do {  
3457   y+=y; incr(k);
3458   if ( y>x ){ 
3459     z=z+spec_atan[k]; t=x; x=x+(y / two_to_the(k+k)); y=y-t;
3460   };
3461 } while (k!=15);
3462 do {  
3463   y+=y; incr(k);
3464   if ( y>x ) { z=z+spec_atan[k]; y=y-x; };
3465 } while (k!=26)
3466
3467 @ Conversely, the |n_sin_cos| routine takes an |angle| and produces the sine
3468 and cosine of that angle. The results of this routine are
3469 stored in global integer variables |n_sin| and |n_cos|.
3470
3471 @<Glob...@>=
3472 fraction n_sin;fraction n_cos; /* results computed by |n_sin_cos| */
3473
3474 @ Given an integer |z| that is $2^{20}$ times an angle $\theta$ in degrees,
3475 the purpose of |n_sin_cos(z)| is to set
3476 |x=@t$r\cos\theta$@>| and |y=@t$r\sin\theta$@>| (approximately),
3477 for some rather large number~|r|. The maximum of |x| and |y|
3478 will be between $2^{28}$ and $2^{30}$, so that there will be hardly
3479 any loss of accuracy. Then |x| and~|y| are divided by~|r|.
3480
3481 @c 
3482 void mp_n_sin_cos (MP mp,angle z) { /* computes a multiple of the sine
3483                                        and cosine */ 
3484   small_number k; /* loop control variable */
3485   int q; /* specifies the quadrant */
3486   fraction r; /* magnitude of |(x,y)| */
3487   integer x,y,t; /* temporary registers */
3488   while ( z<0 ) z=z+three_sixty_deg;
3489   z=z % three_sixty_deg; /* now |0<=z<three_sixty_deg| */
3490   q=z / forty_five_deg; z=z % forty_five_deg;
3491   x=fraction_one; y=x;
3492   if ( ! odd(q) ) z=forty_five_deg-z;
3493   @<Subtract angle |z| from |(x,y)|@>;
3494   @<Convert |(x,y)| to the octant determined by~|q|@>;
3495   r=mp_pyth_add(mp, x,y); 
3496   mp->n_cos=mp_make_fraction(mp, x,r); 
3497   mp->n_sin=mp_make_fraction(mp, y,r);
3498 }
3499
3500 @ In this case the octants are numbered sequentially.
3501
3502 @<Convert |(x,...@>=
3503 switch (q) {
3504 case 0: break;
3505 case 1: t=x; x=y; y=t; break;
3506 case 2: t=x; x=-y; y=t; break;
3507 case 3: negate(x); break;
3508 case 4: negate(x); negate(y); break;
3509 case 5: t=x; x=-y; y=-t; break;
3510 case 6: t=x; x=y; y=-t; break;
3511 case 7: negate(y); break;
3512 } /* there are no other cases */
3513
3514 @ The main iteration of |n_sin_cos| is similar to that of |n_arg| but
3515 applied in reverse. The values of |spec_atan[k]| decrease slowly enough
3516 that this loop is guaranteed to terminate before the (nonexistent) value
3517 |spec_atan[27]| would be required.
3518
3519 @<Subtract angle |z|...@>=
3520 k=1;
3521 while ( z>0 ){ 
3522   if ( z>=spec_atan[k] ) { 
3523     z=z-spec_atan[k]; t=x;
3524     x=t+y / two_to_the(k);
3525     y=y-t / two_to_the(k);
3526   }
3527   incr(k);
3528 }
3529 if ( y<0 ) y=0 /* this precaution may never be needed */
3530
3531 @ And now let's complete our collection of numeric utility routines
3532 by considering random number generation.
3533 \MP\ generates pseudo-random numbers with the additive scheme recommended
3534 in Section 3.6 of {\sl The Art of Computer Programming}; however, the
3535 results are random fractions between 0 and |fraction_one-1|, inclusive.
3536
3537 There's an auxiliary array |randoms| that contains 55 pseudo-random
3538 fractions. Using the recurrence $x_n=(x_{n-55}-x_{n-31})\bmod 2^{28}$,
3539 we generate batches of 55 new $x_n$'s at a time by calling |new_randoms|.
3540 The global variable |j_random| tells which element has most recently
3541 been consumed.
3542 The global variable |sys_random_seed| was introduced in version 0.9,
3543 for the sole reason of stressing the fact that the initial value of the
3544 random seed is system-dependant. The pascal code below will initialize
3545 this variable to |(internal[time] div unity)+internal[day]|, but this is
3546 not good enough on modern fast machines that are capable of running
3547 multiple MetaPost processes within the same second.
3548 @^system dependencies@>
3549
3550 @<Glob...@>=
3551 fraction randoms[55]; /* the last 55 random values generated */
3552 int j_random; /* the number of unused |randoms| */
3553 scaled sys_random_seed; /* the default random seed */
3554
3555 @ @<Types...@>=
3556 typedef scaled (*get_random_seed_command)(MP mp);
3557
3558 @ @<Glob...@>=
3559 get_random_seed_command get_random_seed;
3560
3561 @ @<Option variables@>=
3562 get_random_seed_command get_random_seed;
3563
3564 @ @<Allocate or initialize ...@>=
3565 set_callback_option(get_random_seed);
3566
3567 @ @<Exported function headers@>=
3568 scaled mp_get_random_seed (MP mp);
3569
3570 @ @c 
3571 scaled mp_get_random_seed (MP mp) {
3572   return (mp->internal[mp_time] / unity)+mp->internal[day];
3573 }
3574
3575 @ To consume a random fraction, the program below will say `|next_random|'
3576 and then it will fetch |randoms[j_random]|.
3577
3578 @d next_random { if ( mp->j_random==0 ) mp_new_randoms(mp);
3579   else decr(mp->j_random); }
3580
3581 @c 
3582 void mp_new_randoms (MP mp) {
3583   int k; /* index into |randoms| */
3584   fraction x; /* accumulator */
3585   for (k=0;k<=23;k++) { 
3586    x=mp->randoms[k]-mp->randoms[k+31];
3587     if ( x<0 ) x=x+fraction_one;
3588     mp->randoms[k]=x;
3589   }
3590   for (k=24;k<= 54;k++){ 
3591     x=mp->randoms[k]-mp->randoms[k-24];
3592     if ( x<0 ) x=x+fraction_one;
3593     mp->randoms[k]=x;
3594   }
3595   mp->j_random=54;
3596 }
3597
3598 @ @<Declarations@>=
3599 void mp_init_randoms (MP mp,scaled seed);
3600
3601 @ To initialize the |randoms| table, we call the following routine.
3602
3603 @c 
3604 void mp_init_randoms (MP mp,scaled seed) {
3605   fraction j,jj,k; /* more or less random integers */
3606   int i; /* index into |randoms| */
3607   j=abs(seed);
3608   while ( j>=fraction_one ) j=halfp(j);
3609   k=1;
3610   for (i=0;i<=54;i++ ){ 
3611     jj=k; k=j-k; j=jj;
3612     if ( k<0 ) k=k+fraction_one;
3613     mp->randoms[(i*21)% 55]=j;
3614   }
3615   mp_new_randoms(mp); 
3616   mp_new_randoms(mp); 
3617   mp_new_randoms(mp); /* ``warm up'' the array */
3618 }
3619
3620 @ To produce a uniform random number in the range |0<=u<x| or |0>=u>x|
3621 or |0=u=x|, given a |scaled| value~|x|, we proceed as shown here.
3622
3623 Note that the call of |take_fraction| will produce the values 0 and~|x|
3624 with about half the probability that it will produce any other particular
3625 values between 0 and~|x|, because it rounds its answers.
3626
3627 @c 
3628 scaled mp_unif_rand (MP mp,scaled x) {
3629   scaled y; /* trial value */
3630   next_random; y=mp_take_fraction(mp, abs(x),mp->randoms[mp->j_random]);
3631   if ( y==abs(x) ) return 0;
3632   else if ( x>0 ) return y;
3633   else return (-y);
3634 }
3635
3636 @ Finally, a normal deviate with mean zero and unit standard deviation
3637 can readily be obtained with the ratio method (Algorithm 3.4.1R in
3638 {\sl The Art of Computer Programming\/}).
3639
3640 @c 
3641 scaled mp_norm_rand (MP mp) {
3642   integer x,u,l; /* what the book would call $2^{16}X$, $2^{28}U$, and $-2^{24}\ln U$ */
3643   do { 
3644     do {  
3645       next_random;
3646       x=mp_take_fraction(mp, 112429,mp->randoms[mp->j_random]-fraction_half);
3647       /* $2^{16}\sqrt{8/e}\approx 112428.82793$ */
3648       next_random; u=mp->randoms[mp->j_random];
3649     } while (abs(x)>=u);
3650     x=mp_make_fraction(mp, x,u);
3651     l=139548960-mp_m_log(mp, u); /* $2^{24}\cdot12\ln2\approx139548959.6165$ */
3652   } while (mp_ab_vs_cd(mp, 1024,l,x,x)<0);
3653   return x;
3654 }
3655
3656 @* \[9] Packed data.
3657 In order to make efficient use of storage space, \MP\ bases its major data
3658 structures on a |memory_word|, which contains either a (signed) integer,
3659 possibly scaled, or a small number of fields that are one half or one
3660 quarter of the size used for storing integers.
3661
3662 If |x| is a variable of type |memory_word|, it contains up to four
3663 fields that can be referred to as follows:
3664 $$\vbox{\halign{\hfil#&#\hfil&#\hfil\cr
3665 |x|&.|int|&(an |integer|)\cr
3666 |x|&.|sc|\qquad&(a |scaled| integer)\cr
3667 |x.hh.lh|, |x.hh|&.|rh|&(two halfword fields)\cr
3668 |x.hh.b0|, |x.hh.b1|, |x.hh|&.|rh|&(two quarterword fields, one halfword
3669   field)\cr
3670 |x.qqqq.b0|, |x.qqqq.b1|, |x.qqqq|&.|b2|, |x.qqqq.b3|\hskip-100pt
3671   &\qquad\qquad\qquad(four quarterword fields)\cr}}$$
3672 This is somewhat cumbersome to write, and not very readable either, but
3673 macros will be used to make the notation shorter and more transparent.
3674 The code below gives a formal definition of |memory_word| and
3675 its subsidiary types, using packed variant records. \MP\ makes no
3676 assumptions about the relative positions of the fields within a word.
3677
3678 @d max_quarterword 0x3FFF /* largest allowable value in a |quarterword| */
3679 @d max_halfword 0xFFFFFFF /* largest allowable value in a |halfword| */
3680
3681 @ Here are the inequalities that the quarterword and halfword values
3682 must satisfy (or rather, the inequalities that they mustn't satisfy):
3683
3684 @<Check the ``constant''...@>=
3685 if (mp->ini_version) {
3686   if ( mp->mem_max!=mp->mem_top ) mp->bad=8;
3687 } else {
3688   if ( mp->mem_max<mp->mem_top ) mp->bad=8;
3689 }
3690 if ( max_quarterword<255 ) mp->bad=9;
3691 if ( max_halfword<65535 ) mp->bad=10;
3692 if ( max_quarterword>max_halfword ) mp->bad=11;
3693 if ( mp->mem_max>=max_halfword ) mp->bad=12;
3694 if ( mp->max_strings>max_halfword ) mp->bad=13;
3695
3696 @ The macros |qi| and |qo| are used for input to and output 
3697 from quarterwords. These are legacy macros.
3698 @^system dependencies@>
3699
3700 @d qo(A) (A) /* to read eight bits from a quarterword */
3701 @d qi(A) (A) /* to store eight bits in a quarterword */
3702
3703 @ The reader should study the following definitions closely:
3704 @^system dependencies@>
3705
3706 @d sc cint /* |scaled| data is equivalent to |integer| */
3707
3708 @<Types...@>=
3709 typedef short quarterword; /* 1/4 of a word */
3710 typedef int halfword; /* 1/2 of a word */
3711 typedef union {
3712   struct {
3713     halfword RH, LH;
3714   } v;
3715   struct { /* Make B0,B1 overlap the most significant bytes of LH.  */
3716     halfword junk;
3717     quarterword B0, B1;
3718   } u;
3719 } two_halves;
3720 typedef struct {
3721   struct {
3722     quarterword B2, B3, B0, B1;
3723   } u;
3724 } four_quarters;
3725 typedef union {
3726   two_halves hh;
3727   integer cint;
3728   four_quarters qqqq;
3729 } memory_word;
3730 #define b0 u.B0
3731 #define b1 u.B1
3732 #define b2 u.B2
3733 #define b3 u.B3
3734 #define rh v.RH
3735 #define lh v.LH
3736
3737 @ When debugging, we may want to print a |memory_word| without knowing
3738 what type it is; so we print it in all modes.
3739 @^dirty \PASCAL@>@^debugging@>
3740
3741 @c 
3742 void mp_print_word (MP mp,memory_word w) {
3743   /* prints |w| in all ways */
3744   mp_print_int(mp, w.cint); mp_print_char(mp, ' ');
3745   mp_print_scaled(mp, w.sc); mp_print_char(mp, ' '); 
3746   mp_print_scaled(mp, w.sc / 010000); mp_print_ln(mp);
3747   mp_print_int(mp, w.hh.lh); mp_print_char(mp, '='); 
3748   mp_print_int(mp, w.hh.b0); mp_print_char(mp, ':');
3749   mp_print_int(mp, w.hh.b1); mp_print_char(mp, ';'); 
3750   mp_print_int(mp, w.hh.rh); mp_print_char(mp, ' ');
3751   mp_print_int(mp, w.qqqq.b0); mp_print_char(mp, ':'); 
3752   mp_print_int(mp, w.qqqq.b1); mp_print_char(mp, ':');
3753   mp_print_int(mp, w.qqqq.b2); mp_print_char(mp, ':'); 
3754   mp_print_int(mp, w.qqqq.b3);
3755 }
3756
3757
3758 @* \[10] Dynamic memory allocation.
3759
3760 The \MP\ system does nearly all of its own memory allocation, so that it
3761 can readily be transported into environments that do not have automatic
3762 facilities for strings, garbage collection, etc., and so that it can be in
3763 control of what error messages the user receives. The dynamic storage
3764 requirements of \MP\ are handled by providing a large array |mem| in
3765 which consecutive blocks of words are used as nodes by the \MP\ routines.
3766
3767 Pointer variables are indices into this array, or into another array
3768 called |eqtb| that will be explained later. A pointer variable might
3769 also be a special flag that lies outside the bounds of |mem|, so we
3770 allow pointers to assume any |halfword| value. The minimum memory
3771 index represents a null pointer.
3772
3773 @d null 0 /* the null pointer */
3774
3775 @<Types...@>=
3776 typedef halfword pointer; /* a flag or a location in |mem| or |eqtb| */
3777
3778 @ The |mem| array is divided into two regions that are allocated separately,
3779 but the dividing line between these two regions is not fixed; they grow
3780 together until finding their ``natural'' size in a particular job.
3781 Locations less than or equal to |lo_mem_max| are used for storing
3782 variable-length records consisting of two or more words each. This region
3783 is maintained using an algorithm similar to the one described in exercise
3784 2.5--19 of {\sl The Art of Computer Programming}. However, no size field
3785 appears in the allocated nodes; the program is responsible for knowing the
3786 relevant size when a node is freed. Locations greater than or equal to
3787 |hi_mem_min| are used for storing one-word records; a conventional
3788 \.{AVAIL} stack is used for allocation in this region.
3789
3790 Locations of |mem| between |0| and |mem_top| may be dumped as part
3791 of preloaded format files, by the \.{INIMP} preprocessor.
3792 @.INIMP@>
3793 Production versions of \MP\ may extend the memory at the top end in order to
3794 provide more space; these locations, between |mem_top| and |mem_max|,
3795 are always used for single-word nodes.
3796
3797 The key pointers that govern |mem| allocation have a prescribed order:
3798 $$\hbox{|null=0<lo_mem_max<hi_mem_min<mem_top<=mem_end<=mem_max|.}$$
3799
3800 @<Glob...@>=
3801 memory_word *mem; /* the big dynamic storage area */
3802 pointer lo_mem_max; /* the largest location of variable-size memory in use */
3803 pointer hi_mem_min; /* the smallest location of one-word memory in use */
3804
3805
3806
3807 @d xfree    mp_xfree
3808 @d xrealloc mp_xrealloc
3809 @d xmalloc  mp_xmalloc
3810 @d xstrdup  mp_xstrdup
3811 @d XREALLOC(a,b,c) a = xrealloc(a,b,sizeof(c));
3812
3813 @<Declare helpers@>=
3814 void mp_xfree (void *x);
3815 void *mp_xrealloc (void *p, size_t nmem, size_t size) ;
3816 void *mp_xmalloc (size_t nmem, size_t size) ;
3817 char *mp_xstrdup(const char *s);
3818
3819 @ The |max_size_test| guards against overflow, on the assumption that
3820 |size_t| is at least 31bits wide.
3821
3822 @d max_size_test 0x7FFFFFFF
3823
3824 @c
3825 void mp_xfree (void *x) {
3826   if (x!=NULL) free(x);
3827 }
3828 void  *mp_xrealloc (void *p, size_t nmem, size_t size) {
3829   void *w ; 
3830   if ((max_size_test/size)<nmem) {
3831     fprintf(stderr,"Memory size overflow!\n");
3832     exit(1);
3833   }
3834   w = realloc (p,(nmem*size));
3835   if (w==NULL) {
3836     fprintf(stderr,"Out of memory!\n");
3837     exit(1);
3838   }
3839   return w;
3840 }
3841 void  *mp_xmalloc (size_t nmem, size_t size) {
3842   void *w;
3843   if ((max_size_test/size)<nmem) {
3844     fprintf(stderr,"Memory size overflow!\n");
3845     exit(1);
3846   }
3847   w = malloc (nmem*size);
3848   if (w==NULL) {
3849     fprintf(stderr,"Out of memory!\n");
3850     exit(1);
3851   }
3852   return w;
3853 }
3854 char *mp_xstrdup(const char *s) {
3855   char *w; 
3856   if (s==NULL)
3857     return NULL;
3858   w = strdup(s);
3859   if (w==NULL) {
3860     fprintf(stderr,"Out of memory!\n");
3861     exit(1);
3862   }
3863   return w;
3864 }
3865
3866
3867
3868 @<Allocate or initialize ...@>=
3869 mp->mem = xmalloc ((mp->mem_max+1),sizeof (memory_word));
3870
3871 @ @<Dealloc variables@>=
3872 xfree(mp->mem);
3873
3874 @ Users who wish to study the memory requirements of particular applications can
3875 can use optional special features that keep track of current and
3876 maximum memory usage. When code between the delimiters |stat| $\ldots$
3877 |tats| is not ``commented out,'' \MP\ will run a bit slower but it will
3878 report these statistics when |tracing_stats| is positive.
3879
3880 @<Glob...@>=
3881 integer var_used; integer dyn_used; /* how much memory is in use */
3882
3883 @ Let's consider the one-word memory region first, since it's the
3884 simplest. The pointer variable |mem_end| holds the highest-numbered location
3885 of |mem| that has ever been used. The free locations of |mem| that
3886 occur between |hi_mem_min| and |mem_end|, inclusive, are of type
3887 |two_halves|, and we write |info(p)| and |link(p)| for the |lh|
3888 and |rh| fields of |mem[p]| when it is of this type. The single-word
3889 free locations form a linked list
3890 $$|avail|,\;\hbox{|link(avail)|},\;\hbox{|link(link(avail))|},\;\ldots$$
3891 terminated by |null|.
3892
3893 @d link(A)   mp->mem[(A)].hh.rh /* the |link| field of a memory word */
3894 @d info(A)   mp->mem[(A)].hh.lh /* the |info| field of a memory word */
3895
3896 @<Glob...@>=
3897 pointer avail; /* head of the list of available one-word nodes */
3898 pointer mem_end; /* the last one-word node used in |mem| */
3899
3900 @ If one-word memory is exhausted, it might mean that the user has forgotten
3901 a token like `\&{enddef}' or `\&{endfor}'. We will define some procedures
3902 later that try to help pinpoint the trouble.
3903
3904 @c 
3905 @<Declare the procedure called |show_token_list|@>;
3906 @<Declare the procedure called |runaway|@>
3907
3908 @ The function |get_avail| returns a pointer to a new one-word node whose
3909 |link| field is null. However, \MP\ will halt if there is no more room left.
3910 @^inner loop@>
3911
3912 @c 
3913 pointer mp_get_avail (MP mp) { /* single-word node allocation */
3914   pointer p; /* the new node being got */
3915   p=mp->avail; /* get top location in the |avail| stack */
3916   if ( p!=null ) {
3917     mp->avail=link(mp->avail); /* and pop it off */
3918   } else if ( mp->mem_end<mp->mem_max ) { /* or go into virgin territory */
3919     incr(mp->mem_end); p=mp->mem_end;
3920   } else { 
3921     decr(mp->hi_mem_min); p=mp->hi_mem_min;
3922     if ( mp->hi_mem_min<=mp->lo_mem_max ) { 
3923       mp_runaway(mp); /* if memory is exhausted, display possible runaway text */
3924       mp_overflow(mp, "main memory size",mp->mem_max);
3925       /* quit; all one-word nodes are busy */
3926 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
3927     }
3928   }
3929   link(p)=null; /* provide an oft-desired initialization of the new node */
3930   incr(mp->dyn_used);/* maintain statistics */
3931   return p;
3932 };
3933
3934 @ Conversely, a one-word node is recycled by calling |free_avail|.
3935
3936 @d free_avail(A)  /* single-word node liberation */
3937   { link((A))=mp->avail; mp->avail=(A); decr(mp->dyn_used);  }
3938
3939 @ There's also a |fast_get_avail| routine, which saves the procedure-call
3940 overhead at the expense of extra programming. This macro is used in
3941 the places that would otherwise account for the most calls of |get_avail|.
3942 @^inner loop@>
3943
3944 @d fast_get_avail(A) { 
3945   (A)=mp->avail; /* avoid |get_avail| if possible, to save time */
3946   if ( (A)==null ) { (A)=mp_get_avail(mp); } 
3947   else { mp->avail=link((A)); link((A))=null;  incr(mp->dyn_used); }
3948   }
3949
3950 @ The available-space list that keeps track of the variable-size portion
3951 of |mem| is a nonempty, doubly-linked circular list of empty nodes,
3952 pointed to by the roving pointer |rover|.
3953
3954 Each empty node has size 2 or more; the first word contains the special
3955 value |max_halfword| in its |link| field and the size in its |info| field;
3956 the second word contains the two pointers for double linking.
3957
3958 Each nonempty node also has size 2 or more. Its first word is of type
3959 |two_halves|\kern-1pt, and its |link| field is never equal to |max_halfword|.
3960 Otherwise there is complete flexibility with respect to the contents
3961 of its other fields and its other words.
3962
3963 (We require |mem_max<max_halfword| because terrible things can happen
3964 when |max_halfword| appears in the |link| field of a nonempty node.)
3965
3966 @d empty_flag   max_halfword /* the |link| of an empty variable-size node */
3967 @d is_empty(A)   (link((A))==empty_flag) /* tests for empty node */
3968 @d node_size   info /* the size field in empty variable-size nodes */
3969 @d llink(A)   info((A)+1) /* left link in doubly-linked list of empty nodes */
3970 @d rlink(A)   link((A)+1) /* right link in doubly-linked list of empty nodes */
3971
3972 @<Glob...@>=
3973 pointer rover; /* points to some node in the list of empties */
3974
3975 @ A call to |get_node| with argument |s| returns a pointer to a new node
3976 of size~|s|, which must be 2~or more. The |link| field of the first word
3977 of this new node is set to null. An overflow stop occurs if no suitable
3978 space exists.
3979
3980 If |get_node| is called with $s=2^{30}$, it simply merges adjacent free
3981 areas and returns the value |max_halfword|.
3982
3983 @<Declarations@>=
3984 pointer mp_get_node (MP mp,integer s) ;
3985
3986 @ @c 
3987 pointer mp_get_node (MP mp,integer s) { /* variable-size node allocation */
3988   pointer p; /* the node currently under inspection */
3989   pointer q;  /* the node physically after node |p| */
3990   integer r; /* the newly allocated node, or a candidate for this honor */
3991   integer t,tt; /* temporary registers */
3992 @^inner loop@>
3993  RESTART: 
3994   p=mp->rover; /* start at some free node in the ring */
3995   do {  
3996     @<Try to allocate within node |p| and its physical successors,
3997      and |goto found| if allocation was possible@>;
3998     p=rlink(p); /* move to the next node in the ring */
3999   } while (p!=mp->rover); /* repeat until the whole list has been traversed */
4000   if ( s==010000000000 ) { 
4001     return max_halfword;
4002   };
4003   if ( mp->lo_mem_max+2<mp->hi_mem_min ) {
4004     if ( mp->lo_mem_max+2<=max_halfword ) {
4005       @<Grow more variable-size memory and |goto restart|@>;
4006     }
4007   }
4008   mp_overflow(mp, "main memory size",mp->mem_max);
4009   /* sorry, nothing satisfactory is left */
4010 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
4011 FOUND: 
4012   link(r)=null; /* this node is now nonempty */
4013   mp->var_used=mp->var_used+s; /* maintain usage statistics */
4014   return r;
4015 }
4016
4017 @ The lower part of |mem| grows by 1000 words at a time, unless
4018 we are very close to going under. When it grows, we simply link
4019 a new node into the available-space list. This method of controlled
4020 growth helps to keep the |mem| usage consecutive when \MP\ is
4021 implemented on ``virtual memory'' systems.
4022 @^virtual memory@>
4023
4024 @<Grow more variable-size memory and |goto restart|@>=
4025
4026   if ( mp->hi_mem_min-mp->lo_mem_max>=1998 ) {
4027     t=mp->lo_mem_max+1000;
4028   } else {
4029     t=mp->lo_mem_max+1+(mp->hi_mem_min-mp->lo_mem_max) / 2; 
4030     /* |lo_mem_max+2<=t<hi_mem_min| */
4031   }
4032   if ( t>max_halfword ) t=max_halfword;
4033   p=llink(mp->rover); q=mp->lo_mem_max; rlink(p)=q; llink(mp->rover)=q;
4034   rlink(q)=mp->rover; llink(q)=p; link(q)=empty_flag; node_size(q)=t-mp->lo_mem_max;
4035   mp->lo_mem_max=t; link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4036   mp->rover=q; 
4037   goto RESTART;
4038 }
4039
4040 @ @<Try to allocate...@>=
4041 q=p+node_size(p); /* find the physical successor */
4042 while ( is_empty(q) ) { /* merge node |p| with node |q| */
4043   t=rlink(q); tt=llink(q);
4044 @^inner loop@>
4045   if ( q==mp->rover ) mp->rover=t;
4046   llink(t)=tt; rlink(tt)=t;
4047   q=q+node_size(q);
4048 }
4049 r=q-s;
4050 if ( r>p+1 ) {
4051   @<Allocate from the top of node |p| and |goto found|@>;
4052 }
4053 if ( r==p ) { 
4054   if ( rlink(p)!=p ) {
4055     @<Allocate entire node |p| and |goto found|@>;
4056   }
4057 }
4058 node_size(p)=q-p /* reset the size in case it grew */
4059
4060 @ @<Allocate from the top...@>=
4061
4062   node_size(p)=r-p; /* store the remaining size */
4063   mp->rover=p; /* start searching here next time */
4064   goto FOUND;
4065 }
4066
4067 @ Here we delete node |p| from the ring, and let |rover| rove around.
4068
4069 @<Allocate entire...@>=
4070
4071   mp->rover=rlink(p); t=llink(p);
4072   llink(mp->rover)=t; rlink(t)=mp->rover;
4073   goto FOUND;
4074 }
4075
4076 @ Conversely, when some variable-size node |p| of size |s| is no longer needed,
4077 the operation |free_node(p,s)| will make its words available, by inserting
4078 |p| as a new empty node just before where |rover| now points.
4079
4080 @<Declarations@>=
4081 void mp_free_node (MP mp, pointer p, halfword s) ;
4082
4083 @ @c 
4084 void mp_free_node (MP mp, pointer p, halfword s) { /* variable-size node
4085   liberation */
4086   pointer q; /* |llink(rover)| */
4087   node_size(p)=s; link(p)=empty_flag;
4088 @^inner loop@>
4089   q=llink(mp->rover); llink(p)=q; rlink(p)=mp->rover; /* set both links */
4090   llink(mp->rover)=p; rlink(q)=p; /* insert |p| into the ring */
4091   mp->var_used=mp->var_used-s; /* maintain statistics */
4092 }
4093
4094 @ Just before \.{INIMP} writes out the memory, it sorts the doubly linked
4095 available space list. The list is probably very short at such times, so a
4096 simple insertion sort is used. The smallest available location will be
4097 pointed to by |rover|, the next-smallest by |rlink(rover)|, etc.
4098
4099 @c 
4100 void mp_sort_avail (MP mp) { /* sorts the available variable-size nodes
4101   by location */
4102   pointer p,q,r; /* indices into |mem| */
4103   pointer old_rover; /* initial |rover| setting */
4104   p=mp_get_node(mp, 010000000000); /* merge adjacent free areas */
4105   p=rlink(mp->rover); rlink(mp->rover)=max_halfword; old_rover=mp->rover;
4106   while ( p!=old_rover ) {
4107     @<Sort |p| into the list starting at |rover|
4108      and advance |p| to |rlink(p)|@>;
4109   }
4110   p=mp->rover;
4111   while ( rlink(p)!=max_halfword ) { 
4112     llink(rlink(p))=p; p=rlink(p);
4113   };
4114   rlink(p)=mp->rover; llink(mp->rover)=p;
4115 }
4116
4117 @ The following |while| loop is guaranteed to
4118 terminate, since the list that starts at
4119 |rover| ends with |max_halfword| during the sorting procedure.
4120
4121 @<Sort |p|...@>=
4122 if ( p<mp->rover ) { 
4123   q=p; p=rlink(q); rlink(q)=mp->rover; mp->rover=q;
4124 } else  { 
4125   q=mp->rover;
4126   while ( rlink(q)<p ) q=rlink(q);
4127   r=rlink(p); rlink(p)=rlink(q); rlink(q)=p; p=r;
4128 }
4129
4130 @* \[11] Memory layout.
4131 Some areas of |mem| are dedicated to fixed usage, since static allocation is
4132 more efficient than dynamic allocation when we can get away with it. For
4133 example, locations |0| to |1| are always used to store a
4134 two-word dummy token whose second word is zero.
4135 The following macro definitions accomplish the static allocation by giving
4136 symbolic names to the fixed positions. Static variable-size nodes appear
4137 in locations |0| through |lo_mem_stat_max|, and static single-word nodes
4138 appear in locations |hi_mem_stat_min| through |mem_top|, inclusive.
4139
4140 @d null_dash (2) /* the first two words are reserved for a null value */
4141 @d dep_head (null_dash+3) /* we will define |dash_node_size=3| */
4142 @d zero_val (dep_head+2) /* two words for a permanently zero value */
4143 @d temp_val (zero_val+2) /* two words for a temporary value node */
4144 @d end_attr temp_val /* we use |end_attr+2| only */
4145 @d inf_val (end_attr+2) /* and |inf_val+1| only */
4146 @d test_pen (inf_val+2)
4147   /* nine words for a pen used when testing the turning number */
4148 @d bad_vardef (test_pen+9) /* two words for \&{vardef} error recovery */
4149 @d lo_mem_stat_max (bad_vardef+1)  /* largest statically
4150   allocated word in the variable-size |mem| */
4151 @#
4152 @d sentinel mp->mem_top /* end of sorted lists */
4153 @d temp_head (mp->mem_top-1) /* head of a temporary list of some kind */
4154 @d hold_head (mp->mem_top-2) /* head of a temporary list of another kind */
4155 @d spec_head (mp->mem_top-3) /* head of a list of unprocessed \&{special} items */
4156 @d hi_mem_stat_min (mp->mem_top-3) /* smallest statically allocated word in
4157   the one-word |mem| */
4158
4159 @ The following code gets the dynamic part of |mem| off to a good start,
4160 when \MP\ is initializing itself the slow way.
4161
4162 @<Initialize table entries (done by \.{INIMP} only)@>=
4163 @^data structure assumptions@>
4164 mp->rover=lo_mem_stat_max+1; /* initialize the dynamic memory */
4165 link(mp->rover)=empty_flag;
4166 node_size(mp->rover)=1000; /* which is a 1000-word available node */
4167 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
4168 mp->lo_mem_max=mp->rover+1000; link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4169 for (k=hi_mem_stat_min;k<=(int)mp->mem_top;k++) {
4170   mp->mem[k]=mp->mem[mp->lo_mem_max]; /* clear list heads */
4171 }
4172 mp->avail=null; mp->mem_end=mp->mem_top;
4173 mp->hi_mem_min=hi_mem_stat_min; /* initialize the one-word memory */
4174 mp->var_used=lo_mem_stat_max+1; 
4175 mp->dyn_used=mp->mem_top+1-(hi_mem_stat_min);  /* initialize statistics */
4176 @<Initialize a pen at |test_pen| so that it fits in nine words@>;
4177
4178 @ The procedure |flush_list(p)| frees an entire linked list of one-word
4179 nodes that starts at a given position, until coming to |sentinel| or a
4180 pointer that is not in the one-word region. Another procedure,
4181 |flush_node_list|, frees an entire linked list of one-word and two-word
4182 nodes, until coming to a |null| pointer.
4183 @^inner loop@>
4184
4185 @c 
4186 void mp_flush_list (MP mp,pointer p) { /* makes list of single-word nodes  available */
4187   pointer q,r; /* list traversers */
4188   if ( p>=mp->hi_mem_min ) if ( p!=sentinel ) { 
4189     r=p;
4190     do {  
4191       q=r; r=link(r); 
4192       decr(mp->dyn_used);
4193       if ( r<mp->hi_mem_min ) break;
4194     } while (r!=sentinel);
4195   /* now |q| is the last node on the list */
4196     link(q)=mp->avail; mp->avail=p;
4197   }
4198 }
4199 @#
4200 void mp_flush_node_list (MP mp,pointer p) {
4201   pointer q; /* the node being recycled */
4202   while ( p!=null ){ 
4203     q=p; p=link(p);
4204     if ( q<mp->hi_mem_min ) 
4205       mp_free_node(mp, q,2);
4206     else 
4207       free_avail(q);
4208   }
4209 }
4210
4211 @ If \MP\ is extended improperly, the |mem| array might get screwed up.
4212 For example, some pointers might be wrong, or some ``dead'' nodes might not
4213 have been freed when the last reference to them disappeared. Procedures
4214 |check_mem| and |search_mem| are available to help diagnose such
4215 problems. These procedures make use of two arrays called |free| and
4216 |was_free| that are present only if \MP's debugging routines have
4217 been included. (You may want to decrease the size of |mem| while you
4218 @^debugging@>
4219 are debugging.)
4220
4221 Because |boolean|s are typedef-d as ints, it is better to use
4222 unsigned chars here.
4223
4224 @<Glob...@>=
4225 unsigned char *free; /* free cells */
4226 unsigned char *was_free; /* previously free cells */
4227 pointer was_mem_end; pointer was_lo_max; pointer was_hi_min;
4228   /* previous |mem_end|, |lo_mem_max|,and |hi_mem_min| */
4229 boolean panicking; /* do we want to check memory constantly? */
4230
4231 @ @<Allocate or initialize ...@>=
4232 mp->free = xmalloc ((mp->mem_max+1),sizeof (unsigned char));
4233 mp->was_free = xmalloc ((mp->mem_max+1), sizeof (unsigned char));
4234
4235 @ @<Dealloc variables@>=
4236 xfree(mp->free);
4237 xfree(mp->was_free);
4238
4239 @ @<Allocate or ...@>=
4240 mp->was_mem_end=0; /* indicate that everything was previously free */
4241 mp->was_lo_max=0; mp->was_hi_min=mp->mem_max;
4242 mp->panicking=false;
4243
4244 @ @<Declare |mp_reallocate| functions@>=
4245 void mp_reallocate_memory(MP mp, int l) ;
4246
4247 @ @c
4248 void mp_reallocate_memory(MP mp, int l) {
4249    XREALLOC(mp->free,     (l+1), unsigned char);
4250    XREALLOC(mp->was_free, (l+1), unsigned char);
4251    XREALLOC(mp->mem,      (l+1), memory_word);
4252    mp->mem_max = l;
4253    if (mp->ini_version) 
4254      mp->mem_top = l;
4255 }
4256
4257
4258
4259 @ Procedure |check_mem| makes sure that the available space lists of
4260 |mem| are well formed, and it optionally prints out all locations
4261 that are reserved now but were free the last time this procedure was called.
4262
4263 @c 
4264 void mp_check_mem (MP mp,boolean print_locs ) {
4265   pointer p,q,r; /* current locations of interest in |mem| */
4266   boolean clobbered; /* is something amiss? */
4267   for (p=0;p<=mp->lo_mem_max;p++) {
4268     mp->free[p]=false; /* you can probably do this faster */
4269   }
4270   for (p=mp->hi_mem_min;p<= mp->mem_end;p++) {
4271     mp->free[p]=false; /* ditto */
4272   }
4273   @<Check single-word |avail| list@>;
4274   @<Check variable-size |avail| list@>;
4275   @<Check flags of unavailable nodes@>;
4276   @<Check the list of linear dependencies@>;
4277   if ( print_locs ) {
4278     @<Print newly busy locations@>;
4279   }
4280   for (p=0;p<=mp->lo_mem_max;p++) {
4281     mp->was_free[p]=mp->free[p];
4282   }
4283   for (p=mp->hi_mem_min;p<=mp->mem_end;p++) {
4284     mp->was_free[p]=mp->free[p];
4285   }
4286   /* |was_free:=free| might be faster */
4287   mp->was_mem_end=mp->mem_end; 
4288   mp->was_lo_max=mp->lo_mem_max; 
4289   mp->was_hi_min=mp->hi_mem_min;
4290 }
4291
4292 @ @<Check single-word...@>=
4293 p=mp->avail; q=null; clobbered=false;
4294 while ( p!=null ) { 
4295   if ( (p>mp->mem_end)||(p<mp->hi_mem_min) ) clobbered=true;
4296   else if ( mp->free[p] ) clobbered=true;
4297   if ( clobbered ) { 
4298     mp_print_nl(mp, "AVAIL list clobbered at ");
4299 @.AVAIL list clobbered...@>
4300     mp_print_int(mp, q); break;
4301   }
4302   mp->free[p]=true; q=p; p=link(q);
4303 }
4304
4305 @ @<Check variable-size...@>=
4306 p=mp->rover; q=null; clobbered=false;
4307 do {  
4308   if ( (p>=mp->lo_mem_max)||(p<0) ) clobbered=true;
4309   else if ( (rlink(p)>=mp->lo_mem_max)||(rlink(p)<0) ) clobbered=true;
4310   else if (  !(is_empty(p))||(node_size(p)<2)||
4311    (p+node_size(p)>mp->lo_mem_max)|| (llink(rlink(p))!=p) ) clobbered=true;
4312   if ( clobbered ) { 
4313     mp_print_nl(mp, "Double-AVAIL list clobbered at ");
4314 @.Double-AVAIL list clobbered...@>
4315     mp_print_int(mp, q); break;
4316   }
4317   for (q=p;q<=p+node_size(p)-1;q++) { /* mark all locations free */
4318     if ( mp->free[q] ) { 
4319       mp_print_nl(mp, "Doubly free location at ");
4320 @.Doubly free location...@>
4321       mp_print_int(mp, q); break;
4322     }
4323     mp->free[q]=true;
4324   }
4325   q=p; p=rlink(p);
4326 } while (p!=mp->rover)
4327
4328
4329 @ @<Check flags...@>=
4330 p=0;
4331 while ( p<=mp->lo_mem_max ) { /* node |p| should not be empty */
4332   if ( is_empty(p) ) {
4333     mp_print_nl(mp, "Bad flag at "); mp_print_int(mp, p);
4334 @.Bad flag...@>
4335   }
4336   while ( (p<=mp->lo_mem_max) && ! mp->free[p] ) incr(p);
4337   while ( (p<=mp->lo_mem_max) && mp->free[p] ) incr(p);
4338 }
4339
4340 @ @<Print newly busy...@>=
4341
4342   @<Do intialization required before printing new busy locations@>;
4343   mp_print_nl(mp, "New busy locs:");
4344 @.New busy locs@>
4345   for (p=0;p<= mp->lo_mem_max;p++ ) {
4346     if ( ! mp->free[p] && ((p>mp->was_lo_max) || mp->was_free[p]) ) {
4347       @<Indicate that |p| is a new busy location@>;
4348     }
4349   }
4350   for (p=mp->hi_mem_min;p<=mp->mem_end;p++ ) {
4351     if ( ! mp->free[p] &&
4352         ((p<mp->was_hi_min) || (p>mp->was_mem_end) || mp->was_free[p]) ) {
4353       @<Indicate that |p| is a new busy location@>;
4354     }
4355   }
4356   @<Finish printing new busy locations@>;
4357 }
4358
4359 @ There might be many new busy locations so we are careful to print contiguous
4360 blocks compactly.  During this operation |q| is the last new busy location and
4361 |r| is the start of the block containing |q|.
4362
4363 @<Indicate that |p| is a new busy location@>=
4364
4365   if ( p>q+1 ) { 
4366     if ( q>r ) { 
4367       mp_print(mp, ".."); mp_print_int(mp, q);
4368     }
4369     mp_print_char(mp, ' '); mp_print_int(mp, p);
4370     r=p;
4371   }
4372   q=p;
4373 }
4374
4375 @ @<Do intialization required before printing new busy locations@>=
4376 q=mp->mem_max; r=mp->mem_max
4377
4378 @ @<Finish printing new busy locations@>=
4379 if ( q>r ) { 
4380   mp_print(mp, ".."); mp_print_int(mp, q);
4381 }
4382
4383 @ The |search_mem| procedure attempts to answer the question ``Who points
4384 to node~|p|?'' In doing so, it fetches |link| and |info| fields of |mem|
4385 that might not be of type |two_halves|. Strictly speaking, this is
4386 @^dirty \PASCAL@>
4387 undefined in \PASCAL, and it can lead to ``false drops'' (words that seem to
4388 point to |p| purely by coincidence). But for debugging purposes, we want
4389 to rule out the places that do {\sl not\/} point to |p|, so a few false
4390 drops are tolerable.
4391
4392 @c
4393 void mp_search_mem (MP mp, pointer p) { /* look for pointers to |p| */
4394   integer q; /* current position being searched */
4395   for (q=0;q<=mp->lo_mem_max;q++) { 
4396     if ( link(q)==p ){ 
4397       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4398     }
4399     if ( info(q)==p ) { 
4400       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4401     }
4402   }
4403   for (q=mp->hi_mem_min;q<=mp->mem_end;q++) {
4404     if ( link(q)==p ) {
4405       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4406     }
4407     if ( info(q)==p ) {
4408       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4409     }
4410   }
4411   @<Search |eqtb| for equivalents equal to |p|@>;
4412 }
4413
4414 @* \[12] The command codes.
4415 Before we can go much further, we need to define symbolic names for the internal
4416 code numbers that represent the various commands obeyed by \MP. These codes
4417 are somewhat arbitrary, but not completely so. For example,
4418 some codes have been made adjacent so that |case| statements in the
4419 program need not consider cases that are widely spaced, or so that |case|
4420 statements can be replaced by |if| statements. A command can begin an
4421 expression if and only if its code lies between |min_primary_command| and
4422 |max_primary_command|, inclusive. The first token of a statement that doesn't
4423 begin with an expression has a command code between |min_command| and
4424 |max_statement_command|, inclusive. Anything less than |min_command| is
4425 eliminated during macro expansions, and anything no more than |max_pre_command|
4426 is eliminated when expanding \TeX\ material.  Ranges such as
4427 |min_secondary_command..max_secondary_command| are used when parsing
4428 expressions, but the relative ordering within such a range is generally not
4429 critical.
4430
4431 The ordering of the highest-numbered commands
4432 (|comma<semicolon<end_group<stop|) is crucial for the parsing and
4433 error-recovery methods of this program as is the ordering |if_test<fi_or_else|
4434 for the smallest two commands.  The ordering is also important in the ranges
4435 |numeric_token..plus_or_minus| and |left_brace..ampersand|.
4436
4437 At any rate, here is the list, for future reference.
4438
4439 @d start_tex 1 /* begin \TeX\ material (\&{btex}, \&{verbatimtex}) */
4440 @d etex_marker 2 /* end \TeX\ material (\&{etex}) */
4441 @d mpx_break 3 /* stop reading an \.{MPX} file (\&{mpxbreak}) */
4442 @d max_pre_command mpx_break
4443 @d if_test 4 /* conditional text (\&{if}) */
4444 @d fi_or_else 5 /* delimiters for conditionals (\&{elseif}, \&{else}, \&{fi} */
4445 @d input 6 /* input a source file (\&{input}, \&{endinput}) */
4446 @d iteration 7 /* iterate (\&{for}, \&{forsuffixes}, \&{forever}, \&{endfor}) */
4447 @d repeat_loop 8 /* special command substituted for \&{endfor} */
4448 @d exit_test 9 /* premature exit from a loop (\&{exitif}) */
4449 @d relax 10 /* do nothing (\.{\char`\\}) */
4450 @d scan_tokens 11 /* put a string into the input buffer */
4451 @d expand_after 12 /* look ahead one token */
4452 @d defined_macro 13 /* a macro defined by the user */
4453 @d min_command (defined_macro+1)
4454 @d save_command 14 /* save a list of tokens (\&{save}) */
4455 @d interim_command 15 /* save an internal quantity (\&{interim}) */
4456 @d let_command 16 /* redefine a symbolic token (\&{let}) */
4457 @d new_internal 17 /* define a new internal quantity (\&{newinternal}) */
4458 @d macro_def 18 /* define a macro (\&{def}, \&{vardef}, etc.) */
4459 @d ship_out_command 19 /* output a character (\&{shipout}) */
4460 @d add_to_command 20 /* add to edges (\&{addto}) */
4461 @d bounds_command 21  /* add bounding path to edges (\&{setbounds}, \&{clip}) */
4462 @d tfm_command 22 /* command for font metric info (\&{ligtable}, etc.) */
4463 @d protection_command 23 /* set protection flag (\&{outer}, \&{inner}) */
4464 @d show_command 24 /* diagnostic output (\&{show}, \&{showvariable}, etc.) */
4465 @d mode_command 25 /* set interaction level (\&{batchmode}, etc.) */
4466 @d random_seed 26 /* initialize random number generator (\&{randomseed}) */
4467 @d message_command 27 /* communicate to user (\&{message}, \&{errmessage}) */
4468 @d every_job_command 28 /* designate a starting token (\&{everyjob}) */
4469 @d delimiters 29 /* define a pair of delimiters (\&{delimiters}) */
4470 @d special_command 30 /* output special info (\&{special})
4471                        or font map info (\&{fontmapfile}, \&{fontmapline}) */
4472 @d write_command 31 /* write text to a file (\&{write}) */
4473 @d type_name 32 /* declare a type (\&{numeric}, \&{pair}, etc. */
4474 @d max_statement_command type_name
4475 @d min_primary_command type_name
4476 @d left_delimiter 33 /* the left delimiter of a matching pair */
4477 @d begin_group 34 /* beginning of a group (\&{begingroup}) */
4478 @d nullary 35 /* an operator without arguments (e.g., \&{normaldeviate}) */
4479 @d unary 36 /* an operator with one argument (e.g., \&{sqrt}) */
4480 @d str_op 37 /* convert a suffix to a string (\&{str}) */
4481 @d cycle 38 /* close a cyclic path (\&{cycle}) */
4482 @d primary_binary 39 /* binary operation taking `\&{of}' (e.g., \&{point}) */
4483 @d capsule_token 40 /* a value that has been put into a token list */
4484 @d string_token 41 /* a string constant (e.g., |"hello"|) */
4485 @d internal_quantity 42 /* internal numeric parameter (e.g., \&{pausing}) */
4486 @d min_suffix_token internal_quantity
4487 @d tag_token 43 /* a symbolic token without a primitive meaning */
4488 @d numeric_token 44 /* a numeric constant (e.g., \.{3.14159}) */
4489 @d max_suffix_token numeric_token
4490 @d plus_or_minus 45 /* either `\.+' or `\.-' */
4491 @d max_primary_command plus_or_minus /* should also be |numeric_token+1| */
4492 @d min_tertiary_command plus_or_minus
4493 @d tertiary_secondary_macro 46 /* a macro defined by \&{secondarydef} */
4494 @d tertiary_binary 47 /* an operator at the tertiary level (e.g., `\.{++}') */
4495 @d max_tertiary_command tertiary_binary
4496 @d left_brace 48 /* the operator `\.{\char`\{}' */
4497 @d min_expression_command left_brace
4498 @d path_join 49 /* the operator `\.{..}' */
4499 @d ampersand 50 /* the operator `\.\&' */
4500 @d expression_tertiary_macro 51 /* a macro defined by \&{tertiarydef} */
4501 @d expression_binary 52 /* an operator at the expression level (e.g., `\.<') */
4502 @d equals 53 /* the operator `\.=' */
4503 @d max_expression_command equals
4504 @d and_command 54 /* the operator `\&{and}' */
4505 @d min_secondary_command and_command
4506 @d secondary_primary_macro 55 /* a macro defined by \&{primarydef} */
4507 @d slash 56 /* the operator `\./' */
4508 @d secondary_binary 57 /* an operator at the binary level (e.g., \&{shifted}) */
4509 @d max_secondary_command secondary_binary
4510 @d param_type 58 /* type of parameter (\&{primary}, \&{expr}, \&{suffix}, etc.) */
4511 @d controls 59 /* specify control points explicitly (\&{controls}) */
4512 @d tension 60 /* specify tension between knots (\&{tension}) */
4513 @d at_least 61 /* bounded tension value (\&{atleast}) */
4514 @d curl_command 62 /* specify curl at an end knot (\&{curl}) */
4515 @d macro_special 63 /* special macro operators (\&{quote}, \.{\#\AT!}, etc.) */
4516 @d right_delimiter 64 /* the right delimiter of a matching pair */
4517 @d left_bracket 65 /* the operator `\.[' */
4518 @d right_bracket 66 /* the operator `\.]' */
4519 @d right_brace 67 /* the operator `\.{\char`\}}' */
4520 @d with_option 68 /* option for filling (\&{withpen}, \&{withweight}, etc.) */
4521 @d thing_to_add 69
4522   /* variant of \&{addto} (\&{contour}, \&{doublepath}, \&{also}) */
4523 @d of_token 70 /* the operator `\&{of}' */
4524 @d to_token 71 /* the operator `\&{to}' */
4525 @d step_token 72 /* the operator `\&{step}' */
4526 @d until_token 73 /* the operator `\&{until}' */
4527 @d within_token 74 /* the operator `\&{within}' */
4528 @d lig_kern_token 75
4529   /* the operators `\&{kern}' and `\.{=:}' and `\.{=:\char'174}, etc. */
4530 @d assignment 76 /* the operator `\.{:=}' */
4531 @d skip_to 77 /* the operation `\&{skipto}' */
4532 @d bchar_label 78 /* the operator `\.{\char'174\char'174:}' */
4533 @d double_colon 79 /* the operator `\.{::}' */
4534 @d colon 80 /* the operator `\.:' */
4535 @#
4536 @d comma 81 /* the operator `\.,', must be |colon+1| */
4537 @d end_of_statement (mp->cur_cmd>comma)
4538 @d semicolon 82 /* the operator `\.;', must be |comma+1| */
4539 @d end_group 83 /* end a group (\&{endgroup}), must be |semicolon+1| */
4540 @d stop 84 /* end a job (\&{end}, \&{dump}), must be |end_group+1| */
4541 @d max_command_code stop
4542 @d outer_tag (max_command_code+1) /* protection code added to command code */
4543
4544 @<Types...@>=
4545 typedef int command_code;
4546
4547 @ Variables and capsules in \MP\ have a variety of ``types,''
4548 distinguished by the code numbers defined here. These numbers are also
4549 not completely arbitrary.  Things that get expanded must have types
4550 |>mp_independent|; a type remaining after expansion is numeric if and only if
4551 its code number is at least |numeric_type|; objects containing numeric
4552 parts must have types between |transform_type| and |pair_type|;
4553 all other types must be smaller than |transform_type|; and among the types
4554 that are not unknown or vacuous, the smallest two must be |boolean_type|
4555 and |string_type| in that order.
4556  
4557 @d undefined 0 /* no type has been declared */
4558 @d unknown_tag 1 /* this constant is added to certain type codes below */
4559 @d unknown_types mp_unknown_boolean: case mp_unknown_string:
4560   case mp_unknown_pen: case mp_unknown_picture: case mp_unknown_path
4561
4562 @<Types...@>=
4563 enum {
4564 mp_vacuous=1, /* no expression was present */
4565 mp_boolean_type, /* \&{boolean} with a known value */
4566 mp_unknown_boolean,
4567 mp_string_type, /* \&{string} with a known value */
4568 mp_unknown_string,
4569 mp_pen_type, /* \&{pen} with a known value */
4570 mp_unknown_pen,
4571 mp_path_type, /* \&{path} with a known value */
4572 mp_unknown_path,
4573 mp_picture_type, /* \&{picture} with a known value */
4574 mp_unknown_picture,
4575 mp_transform_type, /* \&{transform} variable or capsule */
4576 mp_color_type, /* \&{color} variable or capsule */
4577 mp_cmykcolor_type, /* \&{cmykcolor} variable or capsule */
4578 mp_pair_type, /* \&{pair} variable or capsule */
4579 mp_numeric_type, /* variable that has been declared \&{numeric} but not used */
4580 mp_known, /* \&{numeric} with a known value */
4581 mp_dependent, /* a linear combination with |fraction| coefficients */
4582 mp_proto_dependent, /* a linear combination with |scaled| coefficients */
4583 mp_independent, /* \&{numeric} with unknown value */
4584 mp_token_list, /* variable name or suffix argument or text argument */
4585 mp_structured, /* variable with subscripts and attributes */
4586 mp_unsuffixed_macro, /* variable defined with \&{vardef} but no \.{\AT!\#} */
4587 mp_suffixed_macro /* variable defined with \&{vardef} and \.{\AT!\#} */
4588 };
4589
4590 @ @<Declarations@>=
4591 void mp_print_type (MP mp,small_number t) ;
4592
4593 @ @<Basic printing procedures@>=
4594 void mp_print_type (MP mp,small_number t) { 
4595   switch (t) {
4596   case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
4597   case mp_boolean_type:mp_print(mp, "boolean"); break;
4598   case mp_unknown_boolean:mp_print(mp, "unknown boolean"); break;
4599   case mp_string_type:mp_print(mp, "string"); break;
4600   case mp_unknown_string:mp_print(mp, "unknown string"); break;
4601   case mp_pen_type:mp_print(mp, "pen"); break;
4602   case mp_unknown_pen:mp_print(mp, "unknown pen"); break;
4603   case mp_path_type:mp_print(mp, "path"); break;
4604   case mp_unknown_path:mp_print(mp, "unknown path"); break;
4605   case mp_picture_type:mp_print(mp, "picture"); break;
4606   case mp_unknown_picture:mp_print(mp, "unknown picture"); break;
4607   case mp_transform_type:mp_print(mp, "transform"); break;
4608   case mp_color_type:mp_print(mp, "color"); break;
4609   case mp_cmykcolor_type:mp_print(mp, "cmykcolor"); break;
4610   case mp_pair_type:mp_print(mp, "pair"); break;
4611   case mp_known:mp_print(mp, "known numeric"); break;
4612   case mp_dependent:mp_print(mp, "dependent"); break;
4613   case mp_proto_dependent:mp_print(mp, "proto-dependent"); break;
4614   case mp_numeric_type:mp_print(mp, "numeric"); break;
4615   case mp_independent:mp_print(mp, "independent"); break;
4616   case mp_token_list:mp_print(mp, "token list"); break;
4617   case mp_structured:mp_print(mp, "mp_structured"); break;
4618   case mp_unsuffixed_macro:mp_print(mp, "unsuffixed macro"); break;
4619   case mp_suffixed_macro:mp_print(mp, "suffixed macro"); break;
4620   default: mp_print(mp, "undefined"); break;
4621   }
4622 }
4623
4624 @ Values inside \MP\ are stored in two-word nodes that have a |name_type|
4625 as well as a |type|. The possibilities for |name_type| are defined
4626 here; they will be explained in more detail later.
4627
4628 @<Types...@>=
4629 enum {
4630  mp_root=0, /* |name_type| at the top level of a variable */
4631  mp_saved_root, /* same, when the variable has been saved */
4632  mp_structured_root, /* |name_type| where a |mp_structured| branch occurs */
4633  mp_subscr, /* |name_type| in a subscript node */
4634  mp_attr, /* |name_type| in an attribute node */
4635  mp_x_part_sector, /* |name_type| in the \&{xpart} of a node */
4636  mp_y_part_sector, /* |name_type| in the \&{ypart} of a node */
4637  mp_xx_part_sector, /* |name_type| in the \&{xxpart} of a node */
4638  mp_xy_part_sector, /* |name_type| in the \&{xypart} of a node */
4639  mp_yx_part_sector, /* |name_type| in the \&{yxpart} of a node */
4640  mp_yy_part_sector, /* |name_type| in the \&{yypart} of a node */
4641  mp_red_part_sector, /* |name_type| in the \&{redpart} of a node */
4642  mp_green_part_sector, /* |name_type| in the \&{greenpart} of a node */
4643  mp_blue_part_sector, /* |name_type| in the \&{bluepart} of a node */
4644  mp_cyan_part_sector, /* |name_type| in the \&{redpart} of a node */
4645  mp_magenta_part_sector, /* |name_type| in the \&{greenpart} of a node */
4646  mp_yellow_part_sector, /* |name_type| in the \&{bluepart} of a node */
4647  mp_black_part_sector, /* |name_type| in the \&{greenpart} of a node */
4648  mp_grey_part_sector, /* |name_type| in the \&{bluepart} of a node */
4649  mp_capsule, /* |name_type| in stashed-away subexpressions */
4650  mp_token  /* |name_type| in a numeric token or string token */
4651 };
4652
4653 @ Primitive operations that produce values have a secondary identification
4654 code in addition to their command code; it's something like genera and species.
4655 For example, `\.*' has the command code |primary_binary|, and its
4656 secondary identification is |times|. The secondary codes start at 30 so that
4657 they don't overlap with the type codes; some type codes (e.g., |mp_string_type|)
4658 are used as operators as well as type identifications.  The relative values
4659 are not critical, except for |true_code..false_code|, |or_op..and_op|,
4660 and |filled_op..bounded_op|.  The restrictions are that
4661 |and_op-false_code=or_op-true_code|, that the ordering of
4662 |x_part...blue_part| must match that of |x_part_sector..mp_blue_part_sector|,
4663 and the ordering of |filled_op..bounded_op| must match that of the code
4664 values they test for.
4665
4666 @d true_code 30 /* operation code for \.{true} */
4667 @d false_code 31 /* operation code for \.{false} */
4668 @d null_picture_code 32 /* operation code for \.{nullpicture} */
4669 @d null_pen_code 33 /* operation code for \.{nullpen} */
4670 @d job_name_op 34 /* operation code for \.{jobname} */
4671 @d read_string_op 35 /* operation code for \.{readstring} */
4672 @d pen_circle 36 /* operation code for \.{pencircle} */
4673 @d normal_deviate 37 /* operation code for \.{normaldeviate} */
4674 @d read_from_op 38 /* operation code for \.{readfrom} */
4675 @d close_from_op 39 /* operation code for \.{closefrom} */
4676 @d odd_op 40 /* operation code for \.{odd} */
4677 @d known_op 41 /* operation code for \.{known} */
4678 @d unknown_op 42 /* operation code for \.{unknown} */
4679 @d not_op 43 /* operation code for \.{not} */
4680 @d decimal 44 /* operation code for \.{decimal} */
4681 @d reverse 45 /* operation code for \.{reverse} */
4682 @d make_path_op 46 /* operation code for \.{makepath} */
4683 @d make_pen_op 47 /* operation code for \.{makepen} */
4684 @d oct_op 48 /* operation code for \.{oct} */
4685 @d hex_op 49 /* operation code for \.{hex} */
4686 @d ASCII_op 50 /* operation code for \.{ASCII} */
4687 @d char_op 51 /* operation code for \.{char} */
4688 @d length_op 52 /* operation code for \.{length} */
4689 @d turning_op 53 /* operation code for \.{turningnumber} */
4690 @d color_model_part 54 /* operation code for \.{colormodel} */
4691 @d x_part 55 /* operation code for \.{xpart} */
4692 @d y_part 56 /* operation code for \.{ypart} */
4693 @d xx_part 57 /* operation code for \.{xxpart} */
4694 @d xy_part 58 /* operation code for \.{xypart} */
4695 @d yx_part 59 /* operation code for \.{yxpart} */
4696 @d yy_part 60 /* operation code for \.{yypart} */
4697 @d red_part 61 /* operation code for \.{redpart} */
4698 @d green_part 62 /* operation code for \.{greenpart} */
4699 @d blue_part 63 /* operation code for \.{bluepart} */
4700 @d cyan_part 64 /* operation code for \.{cyanpart} */
4701 @d magenta_part 65 /* operation code for \.{magentapart} */
4702 @d yellow_part 66 /* operation code for \.{yellowpart} */
4703 @d black_part 67 /* operation code for \.{blackpart} */
4704 @d grey_part 68 /* operation code for \.{greypart} */
4705 @d font_part 69 /* operation code for \.{fontpart} */
4706 @d text_part 70 /* operation code for \.{textpart} */
4707 @d path_part 71 /* operation code for \.{pathpart} */
4708 @d pen_part 72 /* operation code for \.{penpart} */
4709 @d dash_part 73 /* operation code for \.{dashpart} */
4710 @d sqrt_op 74 /* operation code for \.{sqrt} */
4711 @d m_exp_op 75 /* operation code for \.{mexp} */
4712 @d m_log_op 76 /* operation code for \.{mlog} */
4713 @d sin_d_op 77 /* operation code for \.{sind} */
4714 @d cos_d_op 78 /* operation code for \.{cosd} */
4715 @d floor_op 79 /* operation code for \.{floor} */
4716 @d uniform_deviate 80 /* operation code for \.{uniformdeviate} */
4717 @d char_exists_op 81 /* operation code for \.{charexists} */
4718 @d font_size 82 /* operation code for \.{fontsize} */
4719 @d ll_corner_op 83 /* operation code for \.{llcorner} */
4720 @d lr_corner_op 84 /* operation code for \.{lrcorner} */
4721 @d ul_corner_op 85 /* operation code for \.{ulcorner} */
4722 @d ur_corner_op 86 /* operation code for \.{urcorner} */
4723 @d arc_length 87 /* operation code for \.{arclength} */
4724 @d angle_op 88 /* operation code for \.{angle} */
4725 @d cycle_op 89 /* operation code for \.{cycle} */
4726 @d filled_op 90 /* operation code for \.{filled} */
4727 @d stroked_op 91 /* operation code for \.{stroked} */
4728 @d textual_op 92 /* operation code for \.{textual} */
4729 @d clipped_op 93 /* operation code for \.{clipped} */
4730 @d bounded_op 94 /* operation code for \.{bounded} */
4731 @d plus 95 /* operation code for \.+ */
4732 @d minus 96 /* operation code for \.- */
4733 @d times 97 /* operation code for \.* */
4734 @d over 98 /* operation code for \./ */
4735 @d pythag_add 99 /* operation code for \.{++} */
4736 @d pythag_sub 100 /* operation code for \.{+-+} */
4737 @d or_op 101 /* operation code for \.{or} */
4738 @d and_op 102 /* operation code for \.{and} */
4739 @d less_than 103 /* operation code for \.< */
4740 @d less_or_equal 104 /* operation code for \.{<=} */
4741 @d greater_than 105 /* operation code for \.> */
4742 @d greater_or_equal 106 /* operation code for \.{>=} */
4743 @d equal_to 107 /* operation code for \.= */
4744 @d unequal_to 108 /* operation code for \.{<>} */
4745 @d concatenate 109 /* operation code for \.\& */
4746 @d rotated_by 110 /* operation code for \.{rotated} */
4747 @d slanted_by 111 /* operation code for \.{slanted} */
4748 @d scaled_by 112 /* operation code for \.{scaled} */
4749 @d shifted_by 113 /* operation code for \.{shifted} */
4750 @d transformed_by 114 /* operation code for \.{transformed} */
4751 @d x_scaled 115 /* operation code for \.{xscaled} */
4752 @d y_scaled 116 /* operation code for \.{yscaled} */
4753 @d z_scaled 117 /* operation code for \.{zscaled} */
4754 @d in_font 118 /* operation code for \.{infont} */
4755 @d intersect 119 /* operation code for \.{intersectiontimes} */
4756 @d double_dot 120 /* operation code for improper \.{..} */
4757 @d substring_of 121 /* operation code for \.{substring} */
4758 @d min_of substring_of
4759 @d subpath_of 122 /* operation code for \.{subpath} */
4760 @d direction_time_of 123 /* operation code for \.{directiontime} */
4761 @d point_of 124 /* operation code for \.{point} */
4762 @d precontrol_of 125 /* operation code for \.{precontrol} */
4763 @d postcontrol_of 126 /* operation code for \.{postcontrol} */
4764 @d pen_offset_of 127 /* operation code for \.{penoffset} */
4765 @d arc_time_of 128 /* operation code for \.{arctime} */
4766 @d mp_version 129 /* operation code for \.{mpversion} */
4767
4768 @c void mp_print_op (MP mp,quarterword c) { 
4769   if (c<=mp_numeric_type ) {
4770     mp_print_type(mp, c);
4771   } else {
4772     switch (c) {
4773     case true_code:mp_print(mp, "true"); break;
4774     case false_code:mp_print(mp, "false"); break;
4775     case null_picture_code:mp_print(mp, "nullpicture"); break;
4776     case null_pen_code:mp_print(mp, "nullpen"); break;
4777     case job_name_op:mp_print(mp, "jobname"); break;
4778     case read_string_op:mp_print(mp, "readstring"); break;
4779     case pen_circle:mp_print(mp, "pencircle"); break;
4780     case normal_deviate:mp_print(mp, "normaldeviate"); break;
4781     case read_from_op:mp_print(mp, "readfrom"); break;
4782     case close_from_op:mp_print(mp, "closefrom"); break;
4783     case odd_op:mp_print(mp, "odd"); break;
4784     case known_op:mp_print(mp, "known"); break;
4785     case unknown_op:mp_print(mp, "unknown"); break;
4786     case not_op:mp_print(mp, "not"); break;
4787     case decimal:mp_print(mp, "decimal"); break;
4788     case reverse:mp_print(mp, "reverse"); break;
4789     case make_path_op:mp_print(mp, "makepath"); break;
4790     case make_pen_op:mp_print(mp, "makepen"); break;
4791     case oct_op:mp_print(mp, "oct"); break;
4792     case hex_op:mp_print(mp, "hex"); break;
4793     case ASCII_op:mp_print(mp, "ASCII"); break;
4794     case char_op:mp_print(mp, "char"); break;
4795     case length_op:mp_print(mp, "length"); break;
4796     case turning_op:mp_print(mp, "turningnumber"); break;
4797     case x_part:mp_print(mp, "xpart"); break;
4798     case y_part:mp_print(mp, "ypart"); break;
4799     case xx_part:mp_print(mp, "xxpart"); break;
4800     case xy_part:mp_print(mp, "xypart"); break;
4801     case yx_part:mp_print(mp, "yxpart"); break;
4802     case yy_part:mp_print(mp, "yypart"); break;
4803     case red_part:mp_print(mp, "redpart"); break;
4804     case green_part:mp_print(mp, "greenpart"); break;
4805     case blue_part:mp_print(mp, "bluepart"); break;
4806     case cyan_part:mp_print(mp, "cyanpart"); break;
4807     case magenta_part:mp_print(mp, "magentapart"); break;
4808     case yellow_part:mp_print(mp, "yellowpart"); break;
4809     case black_part:mp_print(mp, "blackpart"); break;
4810     case grey_part:mp_print(mp, "greypart"); break;
4811     case color_model_part:mp_print(mp, "colormodel"); break;
4812     case font_part:mp_print(mp, "fontpart"); break;
4813     case text_part:mp_print(mp, "textpart"); break;
4814     case path_part:mp_print(mp, "pathpart"); break;
4815     case pen_part:mp_print(mp, "penpart"); break;
4816     case dash_part:mp_print(mp, "dashpart"); break;
4817     case sqrt_op:mp_print(mp, "sqrt"); break;
4818     case m_exp_op:mp_print(mp, "mexp"); break;
4819     case m_log_op:mp_print(mp, "mlog"); break;
4820     case sin_d_op:mp_print(mp, "sind"); break;
4821     case cos_d_op:mp_print(mp, "cosd"); break;
4822     case floor_op:mp_print(mp, "floor"); break;
4823     case uniform_deviate:mp_print(mp, "uniformdeviate"); break;
4824     case char_exists_op:mp_print(mp, "charexists"); break;
4825     case font_size:mp_print(mp, "fontsize"); break;
4826     case ll_corner_op:mp_print(mp, "llcorner"); break;
4827     case lr_corner_op:mp_print(mp, "lrcorner"); break;
4828     case ul_corner_op:mp_print(mp, "ulcorner"); break;
4829     case ur_corner_op:mp_print(mp, "urcorner"); break;
4830     case arc_length:mp_print(mp, "arclength"); break;
4831     case angle_op:mp_print(mp, "angle"); break;
4832     case cycle_op:mp_print(mp, "cycle"); break;
4833     case filled_op:mp_print(mp, "filled"); break;
4834     case stroked_op:mp_print(mp, "stroked"); break;
4835     case textual_op:mp_print(mp, "textual"); break;
4836     case clipped_op:mp_print(mp, "clipped"); break;
4837     case bounded_op:mp_print(mp, "bounded"); break;
4838     case plus:mp_print_char(mp, '+'); break;
4839     case minus:mp_print_char(mp, '-'); break;
4840     case times:mp_print_char(mp, '*'); break;
4841     case over:mp_print_char(mp, '/'); break;
4842     case pythag_add:mp_print(mp, "++"); break;
4843     case pythag_sub:mp_print(mp, "+-+"); break;
4844     case or_op:mp_print(mp, "or"); break;
4845     case and_op:mp_print(mp, "and"); break;
4846     case less_than:mp_print_char(mp, '<'); break;
4847     case less_or_equal:mp_print(mp, "<="); break;
4848     case greater_than:mp_print_char(mp, '>'); break;
4849     case greater_or_equal:mp_print(mp, ">="); break;
4850     case equal_to:mp_print_char(mp, '='); break;
4851     case unequal_to:mp_print(mp, "<>"); break;
4852     case concatenate:mp_print(mp, "&"); break;
4853     case rotated_by:mp_print(mp, "rotated"); break;
4854     case slanted_by:mp_print(mp, "slanted"); break;
4855     case scaled_by:mp_print(mp, "scaled"); break;
4856     case shifted_by:mp_print(mp, "shifted"); break;
4857     case transformed_by:mp_print(mp, "transformed"); break;
4858     case x_scaled:mp_print(mp, "xscaled"); break;
4859     case y_scaled:mp_print(mp, "yscaled"); break;
4860     case z_scaled:mp_print(mp, "zscaled"); break;
4861     case in_font:mp_print(mp, "infont"); break;
4862     case intersect:mp_print(mp, "intersectiontimes"); break;
4863     case substring_of:mp_print(mp, "substring"); break;
4864     case subpath_of:mp_print(mp, "subpath"); break;
4865     case direction_time_of:mp_print(mp, "directiontime"); break;
4866     case point_of:mp_print(mp, "point"); break;
4867     case precontrol_of:mp_print(mp, "precontrol"); break;
4868     case postcontrol_of:mp_print(mp, "postcontrol"); break;
4869     case pen_offset_of:mp_print(mp, "penoffset"); break;
4870     case arc_time_of:mp_print(mp, "arctime"); break;
4871     case mp_version:mp_print(mp, "mpversion"); break;
4872     default: mp_print(mp, ".."); break;
4873     }
4874   }
4875 }
4876
4877 @ \MP\ also has a bunch of internal parameters that a user might want to
4878 fuss with. Every such parameter has an identifying code number, defined here.
4879
4880 @d tracing_titles 1 /* show titles online when they appear */
4881 @d tracing_equations 2 /* show each variable when it becomes known */
4882 @d tracing_capsules 3 /* show capsules too */
4883 @d tracing_choices 4 /* show the control points chosen for paths */
4884 @d tracing_specs 5 /* show path subdivision prior to filling with polygonal a pen */
4885 @d tracing_commands 6 /* show commands and operations before they are performed */
4886 @d tracing_restores 7 /* show when a variable or internal is restored */
4887 @d tracing_macros 8 /* show macros before they are expanded */
4888 @d tracing_output 9 /* show digitized edges as they are output */
4889 @d tracing_stats 10 /* show memory usage at end of job */
4890 @d tracing_lost_chars 11 /* show characters that aren't \&{infont} */
4891 @d tracing_online 12 /* show long diagnostics on terminal and in the log file */
4892 @d year 13 /* the current year (e.g., 1984) */
4893 @d month 14 /* the current month (e.g, 3 $\equiv$ March) */
4894 @d day 15 /* the current day of the month */
4895 @d mp_time 16 /* the number of minutes past midnight when this job started */
4896 @d char_code 17 /* the number of the next character to be output */
4897 @d char_ext 18 /* the extension code of the next character to be output */
4898 @d char_wd 19 /* the width of the next character to be output */
4899 @d char_ht 20 /* the height of the next character to be output */
4900 @d char_dp 21 /* the depth of the next character to be output */
4901 @d char_ic 22 /* the italic correction of the next character to be output */
4902 @d design_size 23 /* the unit of measure used for |char_wd..char_ic|, in points */
4903 @d pausing 24 /* positive to display lines on the terminal before they are read */
4904 @d showstopping 25 /* positive to stop after each \&{show} command */
4905 @d fontmaking 26 /* positive if font metric output is to be produced */
4906 @d linejoin 27 /* as in \ps: 0 for mitered, 1 for round, 2 for beveled */
4907 @d linecap 28 /* as in \ps: 0 for butt, 1 for round, 2 for square */
4908 @d miterlimit 29 /* controls miter length as in \ps */
4909 @d warning_check 30 /* controls error message when variable value is large */
4910 @d boundary_char 31 /* the right boundary character for ligatures */
4911 @d prologues 32 /* positive to output conforming PostScript using built-in fonts */
4912 @d true_corners 33 /* positive to make \&{llcorner} etc. ignore \&{setbounds} */
4913 @d default_color_model 34 /* the default color model for unspecified items */
4914 @d restore_clip_color 35
4915 @d mpprocset 36 /* wether or not create PostScript command shortcuts */
4916 @d gtroffmode 37 /* whether the user specified |-troff| on the command line */
4917 @d max_given_internal 37
4918
4919 @<Glob...@>=
4920 scaled *internal;  /* the values of internal quantities */
4921 char **int_name;  /* their names */
4922 int int_ptr;  /* the maximum internal quantity defined so far */
4923 int max_internal; /* current maximum number of internal quantities */
4924 boolean troff_mode; 
4925
4926 @ @<Option variables@>=
4927 boolean troff_mode; 
4928
4929 @ @<Allocate or initialize ...@>=
4930 mp->max_internal=2*max_given_internal;
4931 mp->internal = xmalloc ((mp->max_internal+1), sizeof(scaled));
4932 mp->int_name = xmalloc ((mp->max_internal+1), sizeof(char *));
4933 mp->troff_mode=(opt.troff_mode>0 ? true : false);
4934
4935 @ @<Exported ...@>=
4936 int mp_troff_mode(MP mp);
4937
4938 @ @c
4939 int mp_troff_mode(MP mp) { return mp->troff_mode; }
4940
4941 @ @<Set initial ...@>=
4942 for (k=0;k<= mp->max_internal; k++ ) { 
4943    mp->internal[k]=0; 
4944    mp->int_name[k]=NULL; 
4945 }
4946 mp->int_ptr=max_given_internal;
4947
4948 @ The symbolic names for internal quantities are put into \MP's hash table
4949 by using a routine called |primitive|, which will be defined later. Let us
4950 enter them now, so that we don't have to list all those names again
4951 anywhere else.
4952
4953 @<Put each of \MP's primitives into the hash table@>=
4954 mp_primitive(mp, "tracingtitles",internal_quantity,tracing_titles);
4955 @:tracingtitles_}{\&{tracingtitles} primitive@>
4956 mp_primitive(mp, "tracingequations",internal_quantity,tracing_equations);
4957 @:tracing_equations_}{\&{tracingequations} primitive@>
4958 mp_primitive(mp, "tracingcapsules",internal_quantity,tracing_capsules);
4959 @:tracing_capsules_}{\&{tracingcapsules} primitive@>
4960 mp_primitive(mp, "tracingchoices",internal_quantity,tracing_choices);
4961 @:tracing_choices_}{\&{tracingchoices} primitive@>
4962 mp_primitive(mp, "tracingspecs",internal_quantity,tracing_specs);
4963 @:tracing_specs_}{\&{tracingspecs} primitive@>
4964 mp_primitive(mp, "tracingcommands",internal_quantity,tracing_commands);
4965 @:tracing_commands_}{\&{tracingcommands} primitive@>
4966 mp_primitive(mp, "tracingrestores",internal_quantity,tracing_restores);
4967 @:tracing_restores_}{\&{tracingrestores} primitive@>
4968 mp_primitive(mp, "tracingmacros",internal_quantity,tracing_macros);
4969 @:tracing_macros_}{\&{tracingmacros} primitive@>
4970 mp_primitive(mp, "tracingoutput",internal_quantity,tracing_output);
4971 @:tracing_output_}{\&{tracingoutput} primitive@>
4972 mp_primitive(mp, "tracingstats",internal_quantity,tracing_stats);
4973 @:tracing_stats_}{\&{tracingstats} primitive@>
4974 mp_primitive(mp, "tracinglostchars",internal_quantity,tracing_lost_chars);
4975 @:tracing_lost_chars_}{\&{tracinglostchars} primitive@>
4976 mp_primitive(mp, "tracingonline",internal_quantity,tracing_online);
4977 @:tracing_online_}{\&{tracingonline} primitive@>
4978 mp_primitive(mp, "year",internal_quantity,year);
4979 @:year_}{\&{year} primitive@>
4980 mp_primitive(mp, "month",internal_quantity,month);
4981 @:month_}{\&{month} primitive@>
4982 mp_primitive(mp, "day",internal_quantity,day);
4983 @:day_}{\&{day} primitive@>
4984 mp_primitive(mp, "time",internal_quantity,mp_time);
4985 @:time_}{\&{time} primitive@>
4986 mp_primitive(mp, "charcode",internal_quantity,char_code);
4987 @:char_code_}{\&{charcode} primitive@>
4988 mp_primitive(mp, "charext",internal_quantity,char_ext);
4989 @:char_ext_}{\&{charext} primitive@>
4990 mp_primitive(mp, "charwd",internal_quantity,char_wd);
4991 @:char_wd_}{\&{charwd} primitive@>
4992 mp_primitive(mp, "charht",internal_quantity,char_ht);
4993 @:char_ht_}{\&{charht} primitive@>
4994 mp_primitive(mp, "chardp",internal_quantity,char_dp);
4995 @:char_dp_}{\&{chardp} primitive@>
4996 mp_primitive(mp, "charic",internal_quantity,char_ic);
4997 @:char_ic_}{\&{charic} primitive@>
4998 mp_primitive(mp, "designsize",internal_quantity,design_size);
4999 @:design_size_}{\&{designsize} primitive@>
5000 mp_primitive(mp, "pausing",internal_quantity,pausing);
5001 @:pausing_}{\&{pausing} primitive@>
5002 mp_primitive(mp, "showstopping",internal_quantity,showstopping);
5003 @:showstopping_}{\&{showstopping} primitive@>
5004 mp_primitive(mp, "fontmaking",internal_quantity,fontmaking);
5005 @:fontmaking_}{\&{fontmaking} primitive@>
5006 mp_primitive(mp, "linejoin",internal_quantity,linejoin);
5007 @:linejoin_}{\&{linejoin} primitive@>
5008 mp_primitive(mp, "linecap",internal_quantity,linecap);
5009 @:linecap_}{\&{linecap} primitive@>
5010 mp_primitive(mp, "miterlimit",internal_quantity,miterlimit);
5011 @:miterlimit_}{\&{miterlimit} primitive@>
5012 mp_primitive(mp, "warningcheck",internal_quantity,warning_check);
5013 @:warning_check_}{\&{warningcheck} primitive@>
5014 mp_primitive(mp, "boundarychar",internal_quantity,boundary_char);
5015 @:boundary_char_}{\&{boundarychar} primitive@>
5016 mp_primitive(mp, "prologues",internal_quantity,prologues);
5017 @:prologues_}{\&{prologues} primitive@>
5018 mp_primitive(mp, "truecorners",internal_quantity,true_corners);
5019 @:true_corners_}{\&{truecorners} primitive@>
5020 mp_primitive(mp, "mpprocset",internal_quantity,mpprocset);
5021 @:mpprocset_}{\&{mpprocset} primitive@>
5022 mp_primitive(mp, "troffmode",internal_quantity,gtroffmode);
5023 @:troffmode_}{\&{troffmode} primitive@>
5024 mp_primitive(mp, "defaultcolormodel",internal_quantity,default_color_model);
5025 @:default_color_model_}{\&{defaultcolormodel} primitive@>
5026 mp_primitive(mp, "restoreclipcolor",internal_quantity,restore_clip_color);
5027 @:restore_clip_color_}{\&{restoreclipcolor} primitive@>
5028
5029 @ Colors can be specified in four color models. In the special
5030 case of |no_model|, MetaPost does not output any color operator to
5031 the postscript output.
5032
5033 Note: these values are passed directly on to |with_option|. This only
5034 works because the other possible values passed to |with_option| are
5035 8 and 10 respectively (from |with_pen| and |with_picture|).
5036
5037 There is a first state, that is only used for |gs_colormodel|. It flags
5038 the fact that there has not been any kind of color specification by
5039 the user so far in the game.
5040
5041 @d no_model 1
5042 @d grey_model 3
5043 @d rgb_model 5
5044 @d cmyk_model 7
5045 @d uninitialized_model 9
5046
5047 @<Initialize table entries (done by \.{INIMP} only)@>=
5048 mp->internal[default_color_model]=(rgb_model*unity);
5049 mp->internal[restore_clip_color]=unity;
5050
5051 @ Well, we do have to list the names one more time, for use in symbolic
5052 printouts.
5053
5054 @<Initialize table...@>=
5055 mp->int_name[tracing_titles]=xstrdup("tracingtitles");
5056 mp->int_name[tracing_equations]=xstrdup("tracingequations");
5057 mp->int_name[tracing_capsules]=xstrdup("tracingcapsules");
5058 mp->int_name[tracing_choices]=xstrdup("tracingchoices");
5059 mp->int_name[tracing_specs]=xstrdup("tracingspecs");
5060 mp->int_name[tracing_commands]=xstrdup("tracingcommands");
5061 mp->int_name[tracing_restores]=xstrdup("tracingrestores");
5062 mp->int_name[tracing_macros]=xstrdup("tracingmacros");
5063 mp->int_name[tracing_output]=xstrdup("tracingoutput");
5064 mp->int_name[tracing_stats]=xstrdup("tracingstats");
5065 mp->int_name[tracing_lost_chars]=xstrdup("tracinglostchars");
5066 mp->int_name[tracing_online]=xstrdup("tracingonline");
5067 mp->int_name[year]=xstrdup("year");
5068 mp->int_name[month]=xstrdup("month");
5069 mp->int_name[day]=xstrdup("day");
5070 mp->int_name[mp_time]=xstrdup("time");
5071 mp->int_name[char_code]=xstrdup("charcode");
5072 mp->int_name[char_ext]=xstrdup("charext");
5073 mp->int_name[char_wd]=xstrdup("charwd");
5074 mp->int_name[char_ht]=xstrdup("charht");
5075 mp->int_name[char_dp]=xstrdup("chardp");
5076 mp->int_name[char_ic]=xstrdup("charic");
5077 mp->int_name[design_size]=xstrdup("designsize");
5078 mp->int_name[pausing]=xstrdup("pausing");
5079 mp->int_name[showstopping]=xstrdup("showstopping");
5080 mp->int_name[fontmaking]=xstrdup("fontmaking");
5081 mp->int_name[linejoin]=xstrdup("linejoin");
5082 mp->int_name[linecap]=xstrdup("linecap");
5083 mp->int_name[miterlimit]=xstrdup("miterlimit");
5084 mp->int_name[warning_check]=xstrdup("warningcheck");
5085 mp->int_name[boundary_char]=xstrdup("boundarychar");
5086 mp->int_name[prologues]=xstrdup("prologues");
5087 mp->int_name[true_corners]=xstrdup("truecorners");
5088 mp->int_name[default_color_model]=xstrdup("defaultcolormodel");
5089 mp->int_name[mpprocset]=xstrdup("mpprocset");
5090 mp->int_name[gtroffmode]=xstrdup("troffmode");
5091 mp->int_name[restore_clip_color]=xstrdup("restoreclipcolor");
5092
5093 @ The following procedure, which is called just before \MP\ initializes its
5094 input and output, establishes the initial values of the date and time.
5095 @^system dependencies@>
5096
5097 Note that the values are |scaled| integers. Hence \MP\ can no longer
5098 be used after the year 32767.
5099
5100 @c 
5101 void mp_fix_date_and_time (MP mp) { 
5102   time_t clock = time ((time_t *) 0);
5103   struct tm *tmptr = localtime (&clock);
5104   mp->internal[mp_time]=
5105       (tmptr->tm_hour*60+tmptr->tm_min)*unity; /* minutes since midnight */
5106   mp->internal[day]=(tmptr->tm_mday)*unity; /* fourth day of the month */
5107   mp->internal[month]=(tmptr->tm_mon+1)*unity; /* seventh month of the year */
5108   mp->internal[year]=(tmptr->tm_year+1900)*unity; /* Anno Domini */
5109 }
5110
5111 @ @<Declarations@>=
5112 void mp_fix_date_and_time (MP mp) ;
5113
5114 @ \MP\ is occasionally supposed to print diagnostic information that
5115 goes only into the transcript file, unless |tracing_online| is positive.
5116 Now that we have defined |tracing_online| we can define
5117 two routines that adjust the destination of print commands:
5118
5119 @<Declarations@>=
5120 void mp_begin_diagnostic (MP mp) ;
5121 void mp_end_diagnostic (MP mp,boolean blank_line);
5122 void mp_print_diagnostic (MP mp, char *s, char *t, boolean nuline) ;
5123
5124 @ @<Basic printing...@>=
5125 @<Declare a function called |true_line|@>;
5126 void mp_begin_diagnostic (MP mp) { /* prepare to do some tracing */
5127   mp->old_setting=mp->selector;
5128   if ( mp->selector==ps_file_only ) mp->selector=mp->non_ps_setting;
5129   if ((mp->internal[tracing_online]<=0)&&(mp->selector==term_and_log)){ 
5130     decr(mp->selector);
5131     if ( mp->history==spotless ) mp->history=warning_issued;
5132   }
5133 }
5134 @#
5135 void mp_end_diagnostic (MP mp,boolean blank_line) {
5136   /* restore proper conditions after tracing */
5137   mp_print_nl(mp, "");
5138   if ( blank_line ) mp_print_ln(mp);
5139   mp->selector=mp->old_setting;
5140 }
5141
5142 @ The global variable |non_ps_setting| is initialized when it is time to print
5143 on |ps_file|.
5144
5145 @<Glob...@>=
5146 unsigned int old_setting;
5147 unsigned int non_ps_setting;
5148
5149 @ We will occasionally use |begin_diagnostic| in connection with line-number
5150 printing, as follows. (The parameter |s| is typically |"Path"| or
5151 |"Cycle spec"|, etc.)
5152
5153 @<Basic printing...@>=
5154 void mp_print_diagnostic (MP mp, char *s, char *t, boolean nuline) { 
5155   mp_begin_diagnostic(mp);
5156   if ( nuline ) mp_print_nl(mp, s); else mp_print(mp, s);
5157   mp_print(mp, " at line "); 
5158   mp_print_int(mp, mp_true_line(mp));
5159   mp_print(mp, t); mp_print_char(mp, ':');
5160 }
5161
5162 @ The 256 |ASCII_code| characters are grouped into classes by means of
5163 the |char_class| table. Individual class numbers have no semantic
5164 or syntactic significance, except in a few instances defined here.
5165 There's also |max_class|, which can be used as a basis for additional
5166 class numbers in nonstandard extensions of \MP.
5167
5168 @d digit_class 0 /* the class number of \.{0123456789} */
5169 @d period_class 1 /* the class number of `\..' */
5170 @d space_class 2 /* the class number of spaces and nonstandard characters */
5171 @d percent_class 3 /* the class number of `\.\%' */
5172 @d string_class 4 /* the class number of `\."' */
5173 @d right_paren_class 8 /* the class number of `\.)' */
5174 @d isolated_classes 5: case 6: case 7: case 8 /* characters that make length-one tokens only */
5175 @d letter_class 9 /* letters and the underline character */
5176 @d left_bracket_class 17 /* `\.[' */
5177 @d right_bracket_class 18 /* `\.]' */
5178 @d invalid_class 20 /* bad character in the input */
5179 @d max_class 20 /* the largest class number */
5180
5181 @<Glob...@>=
5182 int char_class[256]; /* the class numbers */
5183
5184 @ If changes are made to accommodate non-ASCII character sets, they should
5185 follow the guidelines in Appendix~C of {\sl The {\logos METAFONT\/}book}.
5186 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
5187 @^system dependencies@>
5188
5189 @<Set initial ...@>=
5190 for (k='0';k<='9';k++) 
5191   mp->char_class[k]=digit_class;
5192 mp->char_class['.']=period_class;
5193 mp->char_class[' ']=space_class;
5194 mp->char_class['%']=percent_class;
5195 mp->char_class['"']=string_class;
5196 mp->char_class[',']=5;
5197 mp->char_class[';']=6;
5198 mp->char_class['(']=7;
5199 mp->char_class[')']=right_paren_class;
5200 for (k='A';k<= 'Z';k++ )
5201   mp->char_class[k]=letter_class;
5202 for (k='a';k<='z';k++) 
5203   mp->char_class[k]=letter_class;
5204 mp->char_class['_']=letter_class;
5205 mp->char_class['<']=10;
5206 mp->char_class['=']=10;
5207 mp->char_class['>']=10;
5208 mp->char_class[':']=10;
5209 mp->char_class['|']=10;
5210 mp->char_class['`']=11;
5211 mp->char_class['\'']=11;
5212 mp->char_class['+']=12;
5213 mp->char_class['-']=12;
5214 mp->char_class['/']=13;
5215 mp->char_class['*']=13;
5216 mp->char_class['\\']=13;
5217 mp->char_class['!']=14;
5218 mp->char_class['?']=14;
5219 mp->char_class['#']=15;
5220 mp->char_class['&']=15;
5221 mp->char_class['@@']=15;
5222 mp->char_class['$']=15;
5223 mp->char_class['^']=16;
5224 mp->char_class['~']=16;
5225 mp->char_class['[']=left_bracket_class;
5226 mp->char_class[']']=right_bracket_class;
5227 mp->char_class['{']=19;
5228 mp->char_class['}']=19;
5229 for (k=0;k<' ';k++)
5230   mp->char_class[k]=invalid_class;
5231 mp->char_class['\t']=space_class;
5232 mp->char_class['\f']=space_class;
5233 for (k=127;k<=255;k++)
5234   mp->char_class[k]=invalid_class;
5235
5236 @* \[13] The hash table.
5237 Symbolic tokens are stored and retrieved by means of a fairly standard hash
5238 table algorithm called the method of ``coalescing lists'' (cf.\ Algorithm 6.4C
5239 in {\sl The Art of Computer Programming\/}). Once a symbolic token enters the
5240 table, it is never removed.
5241
5242 The actual sequence of characters forming a symbolic token is
5243 stored in the |str_pool| array together with all the other strings. An
5244 auxiliary array |hash| consists of items with two halfword fields per
5245 word. The first of these, called |next(p)|, points to the next identifier
5246 belonging to the same coalesced list as the identifier corresponding to~|p|;
5247 and the other, called |text(p)|, points to the |str_start| entry for
5248 |p|'s identifier. If position~|p| of the hash table is empty, we have
5249 |text(p)=0|; if position |p| is either empty or the end of a coalesced
5250 hash list, we have |next(p)=0|.
5251
5252 An auxiliary pointer variable called |hash_used| is maintained in such a
5253 way that all locations |p>=hash_used| are nonempty. The global variable
5254 |st_count| tells how many symbolic tokens have been defined, if statistics
5255 are being kept.
5256
5257 The first 256 locations of |hash| are reserved for symbols of length one.
5258
5259 There's a parallel array called |eqtb| that contains the current equivalent
5260 values of each symbolic token. The entries of this array consist of
5261 two halfwords called |eq_type| (a command code) and |equiv| (a secondary
5262 piece of information that qualifies the |eq_type|).
5263
5264 @d next(A)   mp->hash[(A)].lh /* link for coalesced lists */
5265 @d text(A)   mp->hash[(A)].rh /* string number for symbolic token name */
5266 @d eq_type(A)   mp->eqtb[(A)].lh /* the current ``meaning'' of a symbolic token */
5267 @d equiv(A)   mp->eqtb[(A)].rh /* parametric part of a token's meaning */
5268 @d hash_base 257 /* hashing actually starts here */
5269 @d hash_is_full   (mp->hash_used==hash_base) /* are all positions occupied? */
5270
5271 @<Glob...@>=
5272 pointer hash_used; /* allocation pointer for |hash| */
5273 integer st_count; /* total number of known identifiers */
5274
5275 @ Certain entries in the hash table are ``frozen'' and not redefinable,
5276 since they are used in error recovery.
5277
5278 @d hash_top (hash_base+mp->hash_size) /* the first location of the frozen area */
5279 @d frozen_inaccessible hash_top /* |hash| location to protect the frozen area */
5280 @d frozen_repeat_loop (hash_top+1) /* |hash| location of a loop-repeat token */
5281 @d frozen_right_delimiter (hash_top+2) /* |hash| location of a permanent `\.)' */
5282 @d frozen_left_bracket (hash_top+3) /* |hash| location of a permanent `\.[' */
5283 @d frozen_slash (hash_top+4) /* |hash| location of a permanent `\./' */
5284 @d frozen_colon (hash_top+5) /* |hash| location of a permanent `\.:' */
5285 @d frozen_semicolon (hash_top+6) /* |hash| location of a permanent `\.;' */
5286 @d frozen_end_for (hash_top+7) /* |hash| location of a permanent \&{endfor} */
5287 @d frozen_end_def (hash_top+8) /* |hash| location of a permanent \&{enddef} */
5288 @d frozen_fi (hash_top+9) /* |hash| location of a permanent \&{fi} */
5289 @d frozen_end_group (hash_top+10) /* |hash| location of a permanent `\.{endgroup}' */
5290 @d frozen_etex (hash_top+11) /* |hash| location of a permanent \&{etex} */
5291 @d frozen_mpx_break (hash_top+12) /* |hash| location of a permanent \&{mpxbreak} */
5292 @d frozen_bad_vardef (hash_top+13) /* |hash| location of `\.{a bad variable}' */
5293 @d frozen_undefined (hash_top+14) /* |hash| location that never gets defined */
5294 @d hash_end (hash_top+14) /* the actual size of the |hash| and |eqtb| arrays */
5295
5296 @<Glob...@>=
5297 two_halves *hash; /* the hash table */
5298 two_halves *eqtb; /* the equivalents */
5299
5300 @ @<Allocate or initialize ...@>=
5301 mp->hash = xmalloc((hash_end+1),sizeof(two_halves));
5302 mp->eqtb = xmalloc((hash_end+1),sizeof(two_halves));
5303
5304 @ @<Dealloc variables@>=
5305 xfree(mp->hash);
5306 xfree(mp->eqtb);
5307
5308 @ @<Set init...@>=
5309 next(1)=0; text(1)=0; eq_type(1)=tag_token; equiv(1)=null;
5310 for (k=2;k<=hash_end;k++)  { 
5311   mp->hash[k]=mp->hash[1]; mp->eqtb[k]=mp->eqtb[1];
5312 }
5313
5314 @ @<Initialize table entries...@>=
5315 mp->hash_used=frozen_inaccessible; /* nothing is used */
5316 mp->st_count=0;
5317 text(frozen_bad_vardef)=intern("a bad variable");
5318 text(frozen_etex)=intern("etex");
5319 text(frozen_mpx_break)=intern("mpxbreak");
5320 text(frozen_fi)=intern("fi");
5321 text(frozen_end_group)=intern("endgroup");
5322 text(frozen_end_def)=intern("enddef");
5323 text(frozen_end_for)=intern("endfor");
5324 text(frozen_semicolon)=intern(";");
5325 text(frozen_colon)=intern(":");
5326 text(frozen_slash)=intern("/");
5327 text(frozen_left_bracket)=intern("[");
5328 text(frozen_right_delimiter)=intern(")");
5329 text(frozen_inaccessible)=intern(" INACCESSIBLE");
5330 eq_type(frozen_right_delimiter)=right_delimiter;
5331
5332 @ @<Check the ``constant'' values...@>=
5333 if ( hash_end+mp->max_internal>max_halfword ) mp->bad=17;
5334
5335 @ Here is the subroutine that searches the hash table for an identifier
5336 that matches a given string of length~|l| appearing in |buffer[j..
5337 (j+l-1)]|. If the identifier is not found, it is inserted; hence it
5338 will always be found, and the corresponding hash table address
5339 will be returned.
5340
5341 @c 
5342 pointer mp_id_lookup (MP mp,integer j, integer l) { /* search the hash table */
5343   integer h; /* hash code */
5344   pointer p; /* index in |hash| array */
5345   pointer k; /* index in |buffer| array */
5346   if (l==1) {
5347     @<Treat special case of length 1 and |break|@>;
5348   }
5349   @<Compute the hash code |h|@>;
5350   p=h+hash_base; /* we start searching here; note that |0<=h<hash_prime| */
5351   while (true)  { 
5352         if (text(p)>0 && length(text(p))==l && mp_str_eq_buf(mp, text(p),j)) 
5353       break;
5354     if ( next(p)==0 ) {
5355       @<Insert a new symbolic token after |p|, then
5356         make |p| point to it and |break|@>;
5357     }
5358     p=next(p);
5359   }
5360   return p;
5361 };
5362
5363 @ @<Treat special case of length 1...@>=
5364  p=mp->buffer[j]+1; text(p)=p-1; return p;
5365
5366
5367 @ @<Insert a new symbolic...@>=
5368 {
5369 if ( text(p)>0 ) { 
5370   do {  
5371     if ( hash_is_full )
5372       mp_overflow(mp, "hash size",mp->hash_size);
5373 @:MetaPost capacity exceeded hash size}{\quad hash size@>
5374     decr(mp->hash_used);
5375   } while (text(mp->hash_used)!=0); /* search for an empty location in |hash| */
5376   next(p)=mp->hash_used; 
5377   p=mp->hash_used;
5378 }
5379 str_room(l);
5380 for (k=j;k<=j+l-1;k++) {
5381   append_char(mp->buffer[k]);
5382 }
5383 text(p)=mp_make_string(mp); 
5384 mp->str_ref[text(p)]=max_str_ref;
5385 incr(mp->st_count);
5386 break;
5387 }
5388
5389
5390 @ The value of |hash_prime| should be roughly 85\pct! of |hash_size|, and it
5391 should be a prime number.  The theory of hashing tells us to expect fewer
5392 than two table probes, on the average, when the search is successful.
5393 [See J.~S. Vitter, {\sl Journal of the ACM\/ \bf30} (1983), 231--258.]
5394 @^Vitter, Jeffrey Scott@>
5395
5396 @<Compute the hash code |h|@>=
5397 h=mp->buffer[j];
5398 for (k=j+1;k<=j+l-1;k++){ 
5399   h=h+h+mp->buffer[k];
5400   while ( h>=mp->hash_prime ) h=h-mp->hash_prime;
5401 }
5402
5403 @ @<Search |eqtb| for equivalents equal to |p|@>=
5404 for (q=1;q<=hash_end;q++) { 
5405   if ( equiv(q)==p ) { 
5406     mp_print_nl(mp, "EQUIV("); 
5407     mp_print_int(mp, q); 
5408     mp_print_char(mp, ')');
5409   }
5410 }
5411
5412 @ We need to put \MP's ``primitive'' symbolic tokens into the hash
5413 table, together with their command code (which will be the |eq_type|)
5414 and an operand (which will be the |equiv|). The |primitive| procedure
5415 does this, in a way that no \MP\ user can. The global value |cur_sym|
5416 contains the new |eqtb| pointer after |primitive| has acted.
5417
5418 @c 
5419 void mp_primitive (MP mp, char *ss, halfword c, halfword o) {
5420   pool_pointer k; /* index into |str_pool| */
5421   small_number j; /* index into |buffer| */
5422   small_number l; /* length of the string */
5423   str_number s;
5424   s = intern(ss);
5425   k=mp->str_start[s]; l=str_stop(s)-k;
5426   /* we will move |s| into the (empty) |buffer| */
5427   for (j=0;j<=l-1;j++) {
5428     mp->buffer[j]=mp->str_pool[k+j];
5429   }
5430   mp->cur_sym=mp_id_lookup(mp, 0,l);
5431   if ( s>=256 ) { /* we don't want to have the string twice */
5432     mp_flush_string(mp, text(mp->cur_sym)); text(mp->cur_sym)=s;
5433   };
5434   eq_type(mp->cur_sym)=c; 
5435   equiv(mp->cur_sym)=o;
5436 }
5437
5438
5439 @ Many of \MP's primitives need no |equiv|, since they are identifiable
5440 by their |eq_type| alone. These primitives are loaded into the hash table
5441 as follows:
5442
5443 @<Put each of \MP's primitives into the hash table@>=
5444 mp_primitive(mp, "..",path_join,0);
5445 @:.._}{\.{..} primitive@>
5446 mp_primitive(mp, "[",left_bracket,0); mp->eqtb[frozen_left_bracket]=mp->eqtb[mp->cur_sym];
5447 @:[ }{\.{[} primitive@>
5448 mp_primitive(mp, "]",right_bracket,0);
5449 @:] }{\.{]} primitive@>
5450 mp_primitive(mp, "}",right_brace,0);
5451 @:]]}{\.{\char`\}} primitive@>
5452 mp_primitive(mp, "{",left_brace,0);
5453 @:][}{\.{\char`\{} primitive@>
5454 mp_primitive(mp, ":",colon,0); mp->eqtb[frozen_colon]=mp->eqtb[mp->cur_sym];
5455 @:: }{\.{:} primitive@>
5456 mp_primitive(mp, "::",double_colon,0);
5457 @::: }{\.{::} primitive@>
5458 mp_primitive(mp, "||:",bchar_label,0);
5459 @:::: }{\.{\char'174\char'174:} primitive@>
5460 mp_primitive(mp, ":=",assignment,0);
5461 @::=_}{\.{:=} primitive@>
5462 mp_primitive(mp, ",",comma,0);
5463 @:, }{\., primitive@>
5464 mp_primitive(mp, ";",semicolon,0); mp->eqtb[frozen_semicolon]=mp->eqtb[mp->cur_sym];
5465 @:; }{\.; primitive@>
5466 mp_primitive(mp, "\\",relax,0);
5467 @:]]\\}{\.{\char`\\} primitive@>
5468 @#
5469 mp_primitive(mp, "addto",add_to_command,0);
5470 @:add_to_}{\&{addto} primitive@>
5471 mp_primitive(mp, "atleast",at_least,0);
5472 @:at_least_}{\&{atleast} primitive@>
5473 mp_primitive(mp, "begingroup",begin_group,0); mp->bg_loc=mp->cur_sym;
5474 @:begin_group_}{\&{begingroup} primitive@>
5475 mp_primitive(mp, "controls",controls,0);
5476 @:controls_}{\&{controls} primitive@>
5477 mp_primitive(mp, "curl",curl_command,0);
5478 @:curl_}{\&{curl} primitive@>
5479 mp_primitive(mp, "delimiters",delimiters,0);
5480 @:delimiters_}{\&{delimiters} primitive@>
5481 mp_primitive(mp, "endgroup",end_group,0);
5482  mp->eqtb[frozen_end_group]=mp->eqtb[mp->cur_sym]; mp->eg_loc=mp->cur_sym;
5483 @:endgroup_}{\&{endgroup} primitive@>
5484 mp_primitive(mp, "everyjob",every_job_command,0);
5485 @:every_job_}{\&{everyjob} primitive@>
5486 mp_primitive(mp, "exitif",exit_test,0);
5487 @:exit_if_}{\&{exitif} primitive@>
5488 mp_primitive(mp, "expandafter",expand_after,0);
5489 @:expand_after_}{\&{expandafter} primitive@>
5490 mp_primitive(mp, "interim",interim_command,0);
5491 @:interim_}{\&{interim} primitive@>
5492 mp_primitive(mp, "let",let_command,0);
5493 @:let_}{\&{let} primitive@>
5494 mp_primitive(mp, "newinternal",new_internal,0);
5495 @:new_internal_}{\&{newinternal} primitive@>
5496 mp_primitive(mp, "of",of_token,0);
5497 @:of_}{\&{of} primitive@>
5498 mp_primitive(mp, "randomseed",random_seed,0);
5499 @:random_seed_}{\&{randomseed} primitive@>
5500 mp_primitive(mp, "save",save_command,0);
5501 @:save_}{\&{save} primitive@>
5502 mp_primitive(mp, "scantokens",scan_tokens,0);
5503 @:scan_tokens_}{\&{scantokens} primitive@>
5504 mp_primitive(mp, "shipout",ship_out_command,0);
5505 @:ship_out_}{\&{shipout} primitive@>
5506 mp_primitive(mp, "skipto",skip_to,0);
5507 @:skip_to_}{\&{skipto} primitive@>
5508 mp_primitive(mp, "special",special_command,0);
5509 @:special}{\&{special} primitive@>
5510 mp_primitive(mp, "fontmapfile",special_command,1);
5511 @:fontmapfile}{\&{fontmapfile} primitive@>
5512 mp_primitive(mp, "fontmapline",special_command,2);
5513 @:fontmapline}{\&{fontmapline} primitive@>
5514 mp_primitive(mp, "step",step_token,0);
5515 @:step_}{\&{step} primitive@>
5516 mp_primitive(mp, "str",str_op,0);
5517 @:str_}{\&{str} primitive@>
5518 mp_primitive(mp, "tension",tension,0);
5519 @:tension_}{\&{tension} primitive@>
5520 mp_primitive(mp, "to",to_token,0);
5521 @:to_}{\&{to} primitive@>
5522 mp_primitive(mp, "until",until_token,0);
5523 @:until_}{\&{until} primitive@>
5524 mp_primitive(mp, "within",within_token,0);
5525 @:within_}{\&{within} primitive@>
5526 mp_primitive(mp, "write",write_command,0);
5527 @:write_}{\&{write} primitive@>
5528
5529 @ Each primitive has a corresponding inverse, so that it is possible to
5530 display the cryptic numeric contents of |eqtb| in symbolic form.
5531 Every call of |primitive| in this program is therefore accompanied by some
5532 straightforward code that forms part of the |print_cmd_mod| routine
5533 explained below.
5534
5535 @<Cases of |print_cmd_mod| for symbolic printing of primitives@>=
5536 case add_to_command:mp_print(mp, "addto"); break;
5537 case assignment:mp_print(mp, ":="); break;
5538 case at_least:mp_print(mp, "atleast"); break;
5539 case bchar_label:mp_print(mp, "||:"); break;
5540 case begin_group:mp_print(mp, "begingroup"); break;
5541 case colon:mp_print(mp, ":"); break;
5542 case comma:mp_print(mp, ","); break;
5543 case controls:mp_print(mp, "controls"); break;
5544 case curl_command:mp_print(mp, "curl"); break;
5545 case delimiters:mp_print(mp, "delimiters"); break;
5546 case double_colon:mp_print(mp, "::"); break;
5547 case end_group:mp_print(mp, "endgroup"); break;
5548 case every_job_command:mp_print(mp, "everyjob"); break;
5549 case exit_test:mp_print(mp, "exitif"); break;
5550 case expand_after:mp_print(mp, "expandafter"); break;
5551 case interim_command:mp_print(mp, "interim"); break;
5552 case left_brace:mp_print(mp, "{"); break;
5553 case left_bracket:mp_print(mp, "["); break;
5554 case let_command:mp_print(mp, "let"); break;
5555 case new_internal:mp_print(mp, "newinternal"); break;
5556 case of_token:mp_print(mp, "of"); break;
5557 case path_join:mp_print(mp, ".."); break;
5558 case random_seed:mp_print(mp, "randomseed"); break;
5559 case relax:mp_print_char(mp, '\\'); break;
5560 case right_brace:mp_print(mp, "}"); break;
5561 case right_bracket:mp_print(mp, "]"); break;
5562 case save_command:mp_print(mp, "save"); break;
5563 case scan_tokens:mp_print(mp, "scantokens"); break;
5564 case semicolon:mp_print(mp, ";"); break;
5565 case ship_out_command:mp_print(mp, "shipout"); break;
5566 case skip_to:mp_print(mp, "skipto"); break;
5567 case special_command: if ( m==2 ) mp_print(mp, "fontmapline"); else
5568                  if ( m==1 ) mp_print(mp, "fontmapfile"); else
5569                  mp_print(mp, "special"); break;
5570 case step_token:mp_print(mp, "step"); break;
5571 case str_op:mp_print(mp, "str"); break;
5572 case tension:mp_print(mp, "tension"); break;
5573 case to_token:mp_print(mp, "to"); break;
5574 case until_token:mp_print(mp, "until"); break;
5575 case within_token:mp_print(mp, "within"); break;
5576 case write_command:mp_print(mp, "write"); break;
5577
5578 @ We will deal with the other primitives later, at some point in the program
5579 where their |eq_type| and |equiv| values are more meaningful.  For example,
5580 the primitives for macro definitions will be loaded when we consider the
5581 routines that define macros.
5582 It is easy to find where each particular
5583 primitive was treated by looking in the index at the end; for example, the
5584 section where |"def"| entered |eqtb| is listed under `\&{def} primitive'.
5585
5586 @* \[14] Token lists.
5587 A \MP\ token is either symbolic or numeric or a string, or it denotes
5588 a macro parameter or capsule; so there are five corresponding ways to encode it
5589 @^token@>
5590 internally: (1)~A symbolic token whose hash code is~|p|
5591 is represented by the number |p|, in the |info| field of a single-word
5592 node in~|mem|. (2)~A numeric token whose |scaled| value is~|v| is
5593 represented in a two-word node of~|mem|; the |type| field is |known|,
5594 the |name_type| field is |token|, and the |value| field holds~|v|.
5595 The fact that this token appears in a two-word node rather than a
5596 one-word node is, of course, clear from the node address.
5597 (3)~A string token is also represented in a two-word node; the |type|
5598 field is |mp_string_type|, the |name_type| field is |token|, and the
5599 |value| field holds the corresponding |str_number|.  (4)~Capsules have
5600 |name_type=capsule|, and their |type| and |value| fields represent
5601 arbitrary values (in ways to be explained later).  (5)~Macro parameters
5602 are like symbolic tokens in that they appear in |info| fields of
5603 one-word nodes. The $k$th parameter is represented by |expr_base+k| if it
5604 is of type \&{expr}, or by |suffix_base+k| if it is of type \&{suffix}, or
5605 by |text_base+k| if it is of type \&{text}.  (Here |0<=k<param_size|.)
5606 Actual values of these parameters are kept in a separate stack, as we will
5607 see later.  The constants |expr_base|, |suffix_base|, and |text_base| are,
5608 of course, chosen so that there will be no confusion between symbolic
5609 tokens and parameters of various types.
5610
5611 Note that
5612 the `\\{type}' field of a node has nothing to do with ``type'' in a
5613 printer's sense. It's curious that the same word is used in such different ways.
5614
5615 @d type(A)   mp->mem[(A)].hh.b0 /* identifies what kind of value this is */
5616 @d name_type(A)   mp->mem[(A)].hh.b1 /* a clue to the name of this value */
5617 @d token_node_size 2 /* the number of words in a large token node */
5618 @d value_loc(A) ((A)+1) /* the word that contains the |value| field */
5619 @d value(A) mp->mem[value_loc((A))].cint /* the value stored in a large token node */
5620 @d expr_base (hash_end+1) /* code for the zeroth \&{expr} parameter */
5621 @d suffix_base (expr_base+mp->param_size) /* code for the zeroth \&{suffix} parameter */
5622 @d text_base (suffix_base+mp->param_size) /* code for the zeroth \&{text} parameter */
5623
5624 @<Check the ``constant''...@>=
5625 if ( text_base+mp->param_size>max_halfword ) mp->bad=18;
5626
5627 @ We have set aside a two word node beginning at |null| so that we can have
5628 |value(null)=0|.  We will make use of this coincidence later.
5629
5630 @<Initialize table entries...@>=
5631 link(null)=null; value(null)=0;
5632
5633 @ A numeric token is created by the following trivial routine.
5634
5635 @c 
5636 pointer mp_new_num_tok (MP mp,scaled v) {
5637   pointer p; /* the new node */
5638   p=mp_get_node(mp, token_node_size); value(p)=v;
5639   type(p)=mp_known; name_type(p)=mp_token; 
5640   return p;
5641 }
5642
5643 @ A token list is a singly linked list of nodes in |mem|, where
5644 each node contains a token and a link.  Here's a subroutine that gets rid
5645 of a token list when it is no longer needed.
5646
5647 @<Declarations@>=
5648 void mp_token_recycle (MP mp);
5649
5650
5651 @c void mp_flush_token_list (MP mp,pointer p) {
5652   pointer q; /* the node being recycled */
5653   while ( p!=null ) { 
5654     q=p; p=link(p);
5655     if ( q>=mp->hi_mem_min ) {
5656      free_avail(q);
5657     } else { 
5658       switch (type(q)) {
5659       case mp_vacuous: case mp_boolean_type: case mp_known:
5660         break;
5661       case mp_string_type:
5662         delete_str_ref(value(q));
5663         break;
5664       case unknown_types: case mp_pen_type: case mp_path_type: 
5665       case mp_picture_type: case mp_pair_type: case mp_color_type:
5666       case mp_cmykcolor_type: case mp_transform_type: case mp_dependent:
5667       case mp_proto_dependent: case mp_independent:
5668         mp->g_pointer=q; mp_token_recycle(mp);
5669         break;
5670       default: mp_confusion(mp, "token");
5671 @:this can't happen token}{\quad token@>
5672       }
5673       mp_free_node(mp, q,token_node_size);
5674     }
5675   }
5676 }
5677
5678 @ The procedure |show_token_list|, which prints a symbolic form of
5679 the token list that starts at a given node |p|, illustrates these
5680 conventions. The token list being displayed should not begin with a reference
5681 count. However, the procedure is intended to be fairly robust, so that if the
5682 memory links are awry or if |p| is not really a pointer to a token list,
5683 almost nothing catastrophic can happen.
5684
5685 An additional parameter |q| is also given; this parameter is either null
5686 or it points to a node in the token list where a certain magic computation
5687 takes place that will be explained later. (Basically, |q| is non-null when
5688 we are printing the two-line context information at the time of an error
5689 message; |q| marks the place corresponding to where the second line
5690 should begin.)
5691
5692 The generation will stop, and `\.{\char`\ ETC.}' will be printed, if the length
5693 of printing exceeds a given limit~|l|; the length of printing upon entry is
5694 assumed to be a given amount called |null_tally|. (Note that
5695 |show_token_list| sometimes uses itself recursively to print
5696 variable names within a capsule.)
5697 @^recursion@>
5698
5699 Unusual entries are printed in the form of all-caps tokens
5700 preceded by a space, e.g., `\.{\char`\ BAD}'.
5701
5702 @<Declarations@>=
5703 void mp_print_capsule (MP mp);
5704
5705 @ @<Declare the procedure called |show_token_list|@>=
5706 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5707                          integer null_tally) ;
5708
5709 @ @c
5710 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5711                          integer null_tally) {
5712   small_number class,c; /* the |char_class| of previous and new tokens */
5713   integer r,v; /* temporary registers */
5714   class=percent_class;
5715   mp->tally=null_tally;
5716   while ( (p!=null) && (mp->tally<l) ) { 
5717     if ( p==q ) 
5718       @<Do magic computation@>;
5719     @<Display token |p| and set |c| to its class;
5720       but |return| if there are problems@>;
5721     class=c; p=link(p);
5722   }
5723   if ( p!=null ) 
5724      mp_print(mp, " ETC.");
5725 @.ETC@>
5726   return;
5727 };
5728
5729 @ @<Display token |p| and set |c| to its class...@>=
5730 c=letter_class; /* the default */
5731 if ( (p<0)||(p>mp->mem_end) ) { 
5732   mp_print(mp, " CLOBBERED"); return;
5733 @.CLOBBERED@>
5734 }
5735 if ( p<mp->hi_mem_min ) { 
5736   @<Display two-word token@>;
5737 } else { 
5738   r=info(p);
5739   if ( r>=expr_base ) {
5740      @<Display a parameter token@>;
5741   } else {
5742     if ( r<1 ) {
5743       if ( r==0 ) { 
5744         @<Display a collective subscript@>
5745       } else {
5746         mp_print(mp, " IMPOSSIBLE");
5747 @.IMPOSSIBLE@>
5748       }
5749     } else { 
5750       r=text(r);
5751       if ( (r<0)||(r>mp->max_str_ptr) ) {
5752         mp_print(mp, " NONEXISTENT");
5753 @.NONEXISTENT@>
5754       } else {
5755        @<Print string |r| as a symbolic token
5756         and set |c| to its class@>;
5757       }
5758     }
5759   }
5760 }
5761
5762 @ @<Display two-word token@>=
5763 if ( name_type(p)==mp_token ) {
5764   if ( type(p)==mp_known ) {
5765     @<Display a numeric token@>;
5766   } else if ( type(p)!=mp_string_type ) {
5767     mp_print(mp, " BAD");
5768 @.BAD@>
5769   } else { 
5770     mp_print_char(mp, '"'); mp_print_str(mp, value(p)); mp_print_char(mp, '"');
5771     c=string_class;
5772   }
5773 } else if ((name_type(p)!=mp_capsule)||(type(p)<mp_vacuous)||(type(p)>mp_independent) ) {
5774   mp_print(mp, " BAD");
5775 } else { 
5776   mp->g_pointer=p; mp_print_capsule(mp); c=right_paren_class;
5777 }
5778
5779 @ @<Display a numeric token@>=
5780 if ( class==digit_class ) 
5781   mp_print_char(mp, ' ');
5782 v=value(p);
5783 if ( v<0 ){ 
5784   if ( class==left_bracket_class ) 
5785     mp_print_char(mp, ' ');
5786   mp_print_char(mp, '['); mp_print_scaled(mp, v); mp_print_char(mp, ']');
5787   c=right_bracket_class;
5788 } else { 
5789   mp_print_scaled(mp, v); c=digit_class;
5790 }
5791
5792
5793 @ Strictly speaking, a genuine token will never have |info(p)=0|.
5794 But we will see later (in the |print_variable_name| routine) that
5795 it is convenient to let |info(p)=0| stand for `\.{[]}'.
5796
5797 @<Display a collective subscript@>=
5798 {
5799 if ( class==left_bracket_class ) 
5800   mp_print_char(mp, ' ');
5801 mp_print(mp, "[]"); c=right_bracket_class;
5802 }
5803
5804 @ @<Display a parameter token@>=
5805 {
5806 if ( r<suffix_base ) { 
5807   mp_print(mp, "(EXPR"); r=r-(expr_base);
5808 @.EXPR@>
5809 } else if ( r<text_base ) { 
5810   mp_print(mp, "(SUFFIX"); r=r-(suffix_base);
5811 @.SUFFIX@>
5812 } else { 
5813   mp_print(mp, "(TEXT"); r=r-(text_base);
5814 @.TEXT@>
5815 }
5816 mp_print_int(mp, r); mp_print_char(mp, ')'); c=right_paren_class;
5817 }
5818
5819
5820 @ @<Print string |r| as a symbolic token...@>=
5821
5822 c=mp->char_class[mp->str_pool[mp->str_start[r]]];
5823 if ( c==class ) {
5824   switch (c) {
5825   case letter_class:mp_print_char(mp, '.'); break;
5826   case isolated_classes: break;
5827   default: mp_print_char(mp, ' '); break;
5828   }
5829 }
5830 mp_print_str(mp, r);
5831 }
5832
5833 @ The following procedures have been declared |forward| with no parameters,
5834 because the author dislikes \PASCAL's convention about |forward| procedures
5835 with parameters. It was necessary to do something, because |show_token_list|
5836 is recursive (although the recursion is limited to one level), and because
5837 |flush_token_list| is syntactically (but not semantically) recursive.
5838 @^recursion@>
5839
5840 @<Declare miscellaneous procedures that were declared |forward|@>=
5841 void mp_print_capsule (MP mp) { 
5842   mp_print_char(mp, '('); mp_print_exp(mp, mp->g_pointer,0); mp_print_char(mp, ')');
5843 };
5844 @#
5845 void mp_token_recycle (MP mp) { 
5846   mp_recycle_value(mp, mp->g_pointer);
5847 };
5848
5849 @ @<Glob...@>=
5850 pointer g_pointer; /* (global) parameter to the |forward| procedures */
5851
5852 @ Macro definitions are kept in \MP's memory in the form of token lists
5853 that have a few extra one-word nodes at the beginning.
5854
5855 The first node contains a reference count that is used to tell when the
5856 list is no longer needed. To emphasize the fact that a reference count is
5857 present, we shall refer to the |info| field of this special node as the
5858 |ref_count| field.
5859 @^reference counts@>
5860
5861 The next node or nodes after the reference count serve to describe the
5862 formal parameters. They either contain a code word that specifies all
5863 of the parameters, or they contain zero or more parameter tokens followed
5864 by the code `|general_macro|'.
5865
5866 @d ref_count info
5867   /* reference count preceding a macro definition or picture header */
5868 @d add_mac_ref(A) incr(ref_count((A))) /* make a new reference to a macro list */
5869 @d general_macro 0 /* preface to a macro defined with a parameter list */
5870 @d primary_macro 1 /* preface to a macro with a \&{primary} parameter */
5871 @d secondary_macro 2 /* preface to a macro with a \&{secondary} parameter */
5872 @d tertiary_macro 3 /* preface to a macro with a \&{tertiary} parameter */
5873 @d expr_macro 4 /* preface to a macro with an undelimited \&{expr} parameter */
5874 @d of_macro 5 /* preface to a macro with
5875   undelimited `\&{expr} |x| \&{of}~|y|' parameters */
5876 @d suffix_macro 6 /* preface to a macro with an undelimited \&{suffix} parameter */
5877 @d text_macro 7 /* preface to a macro with an undelimited \&{text} parameter */
5878
5879 @c 
5880 void mp_delete_mac_ref (MP mp,pointer p) {
5881   /* |p| points to the reference count of a macro list that is
5882     losing one reference */
5883   if ( ref_count(p)==null ) mp_flush_token_list(mp, p);
5884   else decr(ref_count(p));
5885 }
5886
5887 @ The following subroutine displays a macro, given a pointer to its
5888 reference count.
5889
5890 @c 
5891 @<Declare the procedure called |print_cmd_mod|@>;
5892 void mp_show_macro (MP mp, pointer p, integer q, integer l) {
5893   pointer r; /* temporary storage */
5894   p=link(p); /* bypass the reference count */
5895   while ( info(p)>text_macro ){ 
5896     r=link(p); link(p)=null;
5897     mp_show_token_list(mp, p,null,l,0); link(p)=r; p=r;
5898     if ( l>0 ) l=l-mp->tally; else return;
5899   } /* control printing of `\.{ETC.}' */
5900 @.ETC@>
5901   mp->tally=0;
5902   switch(info(p)) {
5903   case general_macro:mp_print(mp, "->"); break;
5904 @.->@>
5905   case primary_macro: case secondary_macro: case tertiary_macro:
5906     mp_print_char(mp, '<');
5907     mp_print_cmd_mod(mp, param_type,info(p)); 
5908     mp_print(mp, ">->");
5909     break;
5910   case expr_macro:mp_print(mp, "<expr>->"); break;
5911   case of_macro:mp_print(mp, "<expr>of<primary>->"); break;
5912   case suffix_macro:mp_print(mp, "<suffix>->"); break;
5913   case text_macro:mp_print(mp, "<text>->"); break;
5914   } /* there are no other cases */
5915   mp_show_token_list(mp, link(p),q,l-mp->tally,0);
5916 }
5917
5918 @* \[15] Data structures for variables.
5919 The variables of \MP\ programs can be simple, like `\.x', or they can
5920 combine the structural properties of arrays and records, like `\.{x20a.b}'.
5921 A \MP\ user assigns a type to a variable like \.{x20a.b} by saying, for
5922 example, `\.{boolean} \.{x20a.b}'. It's time for us to study how such
5923 things are represented inside of the computer.
5924
5925 Each variable value occupies two consecutive words, either in a two-word
5926 node called a value node, or as a two-word subfield of a larger node.  One
5927 of those two words is called the |value| field; it is an integer,
5928 containing either a |scaled| numeric value or the representation of some
5929 other type of quantity. (It might also be subdivided into halfwords, in
5930 which case it is referred to by other names instead of |value|.) The other
5931 word is broken into subfields called |type|, |name_type|, and |link|.  The
5932 |type| field is a quarterword that specifies the variable's type, and
5933 |name_type| is a quarterword from which \MP\ can reconstruct the
5934 variable's name (sometimes by using the |link| field as well).  Thus, only
5935 1.25 words are actually devoted to the value itself; the other
5936 three-quarters of a word are overhead, but they aren't wasted because they
5937 allow \MP\ to deal with sparse arrays and to provide meaningful diagnostics.
5938
5939 In this section we shall be concerned only with the structural aspects of
5940 variables, not their values. Later parts of the program will change the
5941 |type| and |value| fields, but we shall treat those fields as black boxes
5942 whose contents should not be touched.
5943
5944 However, if the |type| field is |mp_structured|, there is no |value| field,
5945 and the second word is broken into two pointer fields called |attr_head|
5946 and |subscr_head|. Those fields point to additional nodes that
5947 contain structural information, as we shall see.
5948
5949 @d subscr_head_loc(A)   (A)+1 /* where |value|, |subscr_head| and |attr_head| are */
5950 @d attr_head(A)   info(subscr_head_loc((A))) /* pointer to attribute info */
5951 @d subscr_head(A)   link(subscr_head_loc((A))) /* pointer to subscript info */
5952 @d value_node_size 2 /* the number of words in a value node */
5953
5954 @ An attribute node is three words long. Two of these words contain |type|
5955 and |value| fields as described above, and the third word contains
5956 additional information:  There is an |attr_loc| field, which contains the
5957 hash address of the token that names this attribute; and there's also a
5958 |parent| field, which points to the value node of |mp_structured| type at the
5959 next higher level (i.e., at the level to which this attribute is
5960 subsidiary).  The |name_type| in an attribute node is `|attr|'.  The
5961 |link| field points to the next attribute with the same parent; these are
5962 arranged in increasing order, so that |attr_loc(link(p))>attr_loc(p)|. The
5963 final attribute node links to the constant |end_attr|, whose |attr_loc|
5964 field is greater than any legal hash address. The |attr_head| in the
5965 parent points to a node whose |name_type| is |mp_structured_root|; this
5966 node represents the null attribute, i.e., the variable that is relevant
5967 when no attributes are attached to the parent. The |attr_head| node is either
5968 a value node, a subscript node, or an attribute node, depending on what
5969 the parent would be if it were not structured; but the subscript and
5970 attribute fields are ignored, so it effectively contains only the data of
5971 a value node. The |link| field in this special node points to an attribute
5972 node whose |attr_loc| field is zero; the latter node represents a collective
5973 subscript `\.{[]}' attached to the parent, and its |link| field points to
5974 the first non-special attribute node (or to |end_attr| if there are none).
5975
5976 A subscript node likewise occupies three words, with |type| and |value| fields
5977 plus extra information; its |name_type| is |subscr|. In this case the
5978 third word is called the |subscript| field, which is a |scaled| integer.
5979 The |link| field points to the subscript node with the next larger
5980 subscript, if any; otherwise the |link| points to the attribute node
5981 for collective subscripts at this level. We have seen that the latter node
5982 contains an upward pointer, so that the parent can be deduced.
5983
5984 The |name_type| in a parent-less value node is |root|, and the |link|
5985 is the hash address of the token that names this value.
5986
5987 In other words, variables have a hierarchical structure that includes
5988 enough threads running around so that the program is able to move easily
5989 between siblings, parents, and children. An example should be helpful:
5990 (The reader is advised to draw a picture while reading the following
5991 description, since that will help to firm up the ideas.)
5992 Suppose that `\.x' and `\.{x.a}' and `\.{x[]b}' and `\.{x5}'
5993 and `\.{x20b}' have been mentioned in a user's program, where
5994 \.{x[]b} has been declared to be of \&{boolean} type. Let |h(x)|, |h(a)|,
5995 and |h(b)| be the hash addresses of \.x, \.a, and~\.b. Then
5996 |eq_type(h(x))=name| and |equiv(h(x))=p|, where |p|~is a two-word value
5997 node with |name_type(p)=root| and |link(p)=h(x)|. We have |type(p)=mp_structured|,
5998 |attr_head(p)=q|, and |subscr_head(p)=r|, where |q| points to a value
5999 node and |r| to a subscript node. (Are you still following this? Use
6000 a pencil to draw a diagram.) The lone variable `\.x' is represented by
6001 |type(q)| and |value(q)|; furthermore
6002 |name_type(q)=mp_structured_root| and |link(q)=q1|, where |q1| points
6003 to an attribute node representing `\.{x[]}'. Thus |name_type(q1)=attr|,
6004 |attr_loc(q1)=collective_subscript=0|, |parent(q1)=p|,
6005 |type(q1)=mp_structured|, |attr_head(q1)=qq|, and |subscr_head(q1)=qq1|;
6006 |qq| is a value node with |type(qq)=mp_numeric_type| (assuming that \.{x5} is
6007 numeric, because |qq| represents `\.{x[]}' with no further attributes),
6008 |name_type(qq)=mp_structured_root|, and
6009 |link(qq)=qq1|. (Now pay attention to the next part.) Node |qq1| is
6010 an attribute node representing `\.{x[][]}', which has never yet
6011 occurred; its |type| field is |undefined|, and its |value| field is
6012 undefined. We have |name_type(qq1)=attr|, |attr_loc(qq1)=collective_subscript|,
6013 |parent(qq1)=q1|, and |link(qq1)=qq2|. Since |qq2| represents
6014 `\.{x[]b}', |type(qq2)=mp_unknown_boolean|; also |attr_loc(qq2)=h(b)|,
6015 |parent(qq2)=q1|, |name_type(qq2)=attr|, |link(qq2)=end_attr|.
6016 (Maybe colored lines will help untangle your picture.)
6017  Node |r| is a subscript node with |type| and |value|
6018 representing `\.{x5}'; |name_type(r)=subscr|, |subscript(r)=5.0|,
6019 and |link(r)=r1| is another subscript node. To complete the picture,
6020 see if you can guess what |link(r1)| is; give up? It's~|q1|.
6021 Furthermore |subscript(r1)=20.0|, |name_type(r1)=subscr|,
6022 |type(r1)=mp_structured|, |attr_head(r1)=qqq|, |subscr_head(r1)=qqq1|,
6023 and we finish things off with three more nodes
6024 |qqq|, |qqq1|, and |qqq2| hung onto~|r1|. (Perhaps you should start again
6025 with a larger sheet of paper.) The value of variable \.{x20b}
6026 appears in node~|qqq2|, as you can well imagine.
6027
6028 If the example in the previous paragraph doesn't make things crystal
6029 clear, a glance at some of the simpler subroutines below will reveal how
6030 things work out in practice.
6031
6032 The only really unusual thing about these conventions is the use of
6033 collective subscript attributes. The idea is to avoid repeating a lot of
6034 type information when many elements of an array are identical macros
6035 (for which distinct values need not be stored) or when they don't have
6036 all of the possible attributes. Branches of the structure below collective
6037 subscript attributes do not carry actual values except for macro identifiers;
6038 branches of the structure below subscript nodes do not carry significant
6039 information in their collective subscript attributes.
6040
6041 @d attr_loc_loc(A) ((A)+2) /* where the |attr_loc| and |parent| fields are */
6042 @d attr_loc(A) info(attr_loc_loc((A))) /* hash address of this attribute */
6043 @d parent(A) link(attr_loc_loc((A))) /* pointer to |mp_structured| variable */
6044 @d subscript_loc(A) ((A)+2) /* where the |subscript| field lives */
6045 @d subscript(A) mp->mem[subscript_loc((A))].sc /* subscript of this variable */
6046 @d attr_node_size 3 /* the number of words in an attribute node */
6047 @d subscr_node_size 3 /* the number of words in a subscript node */
6048 @d collective_subscript 0 /* code for the attribute `\.{[]}' */
6049
6050 @<Initialize table...@>=
6051 attr_loc(end_attr)=hash_end+1; parent(end_attr)=null;
6052
6053 @ Variables of type \&{pair} will have values that point to four-word
6054 nodes containing two numeric values. The first of these values has
6055 |name_type=mp_x_part_sector| and the second has |name_type=mp_y_part_sector|;
6056 the |link| in the first points back to the node whose |value| points
6057 to this four-word node.
6058
6059 Variables of type \&{transform} are similar, but in this case their
6060 |value| points to a 12-word node containing six values, identified by
6061 |x_part_sector|, |y_part_sector|, |mp_xx_part_sector|, |mp_xy_part_sector|,
6062 |mp_yx_part_sector|, and |mp_yy_part_sector|.
6063 Finally, variables of type \&{color} have three values in six words
6064 identified by |mp_red_part_sector|, |mp_green_part_sector|, and |mp_blue_part_sector|.
6065
6066 When an entire structured variable is saved, the |root| indication
6067 is temporarily replaced by |saved_root|.
6068
6069 Some variables have no name; they just are used for temporary storage
6070 while expressions are being evaluated. We call them {\sl capsules}.
6071
6072 @d x_part_loc(A) (A) /* where the \&{xpart} is found in a pair or transform node */
6073 @d y_part_loc(A) ((A)+2) /* where the \&{ypart} is found in a pair or transform node */
6074 @d xx_part_loc(A) ((A)+4) /* where the \&{xxpart} is found in a transform node */
6075 @d xy_part_loc(A) ((A)+6) /* where the \&{xypart} is found in a transform node */
6076 @d yx_part_loc(A) ((A)+8) /* where the \&{yxpart} is found in a transform node */
6077 @d yy_part_loc(A) ((A)+10) /* where the \&{yypart} is found in a transform node */
6078 @d red_part_loc(A) (A) /* where the \&{redpart} is found in a color node */
6079 @d green_part_loc(A) ((A)+2) /* where the \&{greenpart} is found in a color node */
6080 @d blue_part_loc(A) ((A)+4) /* where the \&{bluepart} is found in a color node */
6081 @d cyan_part_loc(A) (A) /* where the \&{cyanpart} is found in a color node */
6082 @d magenta_part_loc(A) ((A)+2) /* where the \&{magentapart} is found in a color node */
6083 @d yellow_part_loc(A) ((A)+4) /* where the \&{yellowpart} is found in a color node */
6084 @d black_part_loc(A) ((A)+6) /* where the \&{blackpart} is found in a color node */
6085 @d grey_part_loc(A) (A) /* where the \&{greypart} is found in a color node */
6086 @#
6087 @d pair_node_size 4 /* the number of words in a pair node */
6088 @d transform_node_size 12 /* the number of words in a transform node */
6089 @d color_node_size 6 /* the number of words in a color node */
6090 @d cmykcolor_node_size 8 /* the number of words in a color node */
6091
6092 @<Glob...@>=
6093 small_number big_node_size[mp_pair_type+1];
6094 small_number sector0[mp_pair_type+1];
6095 small_number sector_offset[mp_black_part_sector+1];
6096
6097 @ The |sector0| array gives for each big node type, |name_type| values
6098 for its first subfield; the |sector_offset| array gives for each
6099 |name_type| value, the offset from the first subfield in words;
6100 and the |big_node_size| array gives the size in words for each type of
6101 big node.
6102
6103 @<Set init...@>=
6104 mp->big_node_size[mp_transform_type]=transform_node_size;
6105 mp->big_node_size[mp_pair_type]=pair_node_size;
6106 mp->big_node_size[mp_color_type]=color_node_size;
6107 mp->big_node_size[mp_cmykcolor_type]=cmykcolor_node_size;
6108 mp->sector0[mp_transform_type]=mp_x_part_sector;
6109 mp->sector0[mp_pair_type]=mp_x_part_sector;
6110 mp->sector0[mp_color_type]=mp_red_part_sector;
6111 mp->sector0[mp_cmykcolor_type]=mp_cyan_part_sector;
6112 for (k=mp_x_part_sector;k<= mp_yy_part_sector;k++ ) {
6113   mp->sector_offset[k]=2*(k-mp_x_part_sector);
6114 }
6115 for (k=mp_red_part_sector;k<= mp_blue_part_sector ; k++) {
6116   mp->sector_offset[k]=2*(k-mp_red_part_sector);
6117 }
6118 for (k=mp_cyan_part_sector;k<= mp_black_part_sector;k++ ) {
6119   mp->sector_offset[k]=2*(k-mp_cyan_part_sector);
6120 }
6121
6122 @ If |type(p)=mp_pair_type| or |mp_transform_type| and if |value(p)=null|, the
6123 procedure call |init_big_node(p)| will allocate a pair or transform node
6124 for~|p|.  The individual parts of such nodes are initially of type
6125 |mp_independent|.
6126
6127 @c 
6128 void mp_init_big_node (MP mp,pointer p) {
6129   pointer q; /* the new node */
6130   small_number s; /* its size */
6131   s=mp->big_node_size[type(p)]; q=mp_get_node(mp, s);
6132   do {  
6133     s=s-2; 
6134     @<Make variable |q+s| newly independent@>;
6135     name_type(q+s)=halfp(s)+mp->sector0[type(p)]; 
6136     link(q+s)=null;
6137   } while (s!=0);
6138   link(q)=p; value(p)=q;
6139 }
6140
6141 @ The |id_transform| function creates a capsule for the
6142 identity transformation.
6143
6144 @c 
6145 pointer mp_id_transform (MP mp) {
6146   pointer p,q,r; /* list manipulation registers */
6147   p=mp_get_node(mp, value_node_size); type(p)=mp_transform_type;
6148   name_type(p)=mp_capsule; value(p)=null; mp_init_big_node(mp, p); q=value(p);
6149   r=q+transform_node_size;
6150   do {  
6151     r=r-2;
6152     type(r)=mp_known; value(r)=0;
6153   } while (r!=q);
6154   value(xx_part_loc(q))=unity; 
6155   value(yy_part_loc(q))=unity;
6156   return p;
6157 }
6158
6159 @ Tokens are of type |tag_token| when they first appear, but they point
6160 to |null| until they are first used as the root of a variable.
6161 The following subroutine establishes the root node on such grand occasions.
6162
6163 @c 
6164 void mp_new_root (MP mp,pointer x) {
6165   pointer p; /* the new node */
6166   p=mp_get_node(mp, value_node_size); type(p)=undefined; name_type(p)=mp_root;
6167   link(p)=x; equiv(x)=p;
6168 }
6169
6170 @ These conventions for variable representation are illustrated by the
6171 |print_variable_name| routine, which displays the full name of a
6172 variable given only a pointer to its two-word value packet.
6173
6174 @<Declarations@>=
6175 void mp_print_variable_name (MP mp, pointer p);
6176
6177 @ @c 
6178 void mp_print_variable_name (MP mp, pointer p) {
6179   pointer q; /* a token list that will name the variable's suffix */
6180   pointer r; /* temporary for token list creation */
6181   while ( name_type(p)>=mp_x_part_sector ) {
6182     @<Preface the output with a part specifier; |return| in the
6183       case of a capsule@>;
6184   }
6185   q=null;
6186   while ( name_type(p)>mp_saved_root ) {
6187     @<Ascend one level, pushing a token onto list |q|
6188      and replacing |p| by its parent@>;
6189   }
6190   r=mp_get_avail(mp); info(r)=link(p); link(r)=q;
6191   if ( name_type(p)==mp_saved_root ) mp_print(mp, "(SAVED)");
6192 @.SAVED@>
6193   mp_show_token_list(mp, r,null,el_gordo,mp->tally); 
6194   mp_flush_token_list(mp, r);
6195 }
6196
6197 @ @<Ascend one level, pushing a token onto list |q|...@>=
6198
6199   if ( name_type(p)==mp_subscr ) { 
6200     r=mp_new_num_tok(mp, subscript(p));
6201     do {  
6202       p=link(p);
6203     } while (name_type(p)!=mp_attr);
6204   } else if ( name_type(p)==mp_structured_root ) {
6205     p=link(p); goto FOUND;
6206   } else { 
6207     if ( name_type(p)!=mp_attr ) mp_confusion(mp, "var");
6208 @:this can't happen var}{\quad var@>
6209     r=mp_get_avail(mp); info(r)=attr_loc(p);
6210   }
6211   link(r)=q; q=r;
6212 FOUND:  
6213   p=parent(p);
6214 }
6215
6216 @ @<Preface the output with a part specifier...@>=
6217 { switch (name_type(p)) {
6218   case mp_x_part_sector: mp_print_char(mp, 'x'); break;
6219   case mp_y_part_sector: mp_print_char(mp, 'y'); break;
6220   case mp_xx_part_sector: mp_print(mp, "xx"); break;
6221   case mp_xy_part_sector: mp_print(mp, "xy"); break;
6222   case mp_yx_part_sector: mp_print(mp, "yx"); break;
6223   case mp_yy_part_sector: mp_print(mp, "yy"); break;
6224   case mp_red_part_sector: mp_print(mp, "red"); break;
6225   case mp_green_part_sector: mp_print(mp, "green"); break;
6226   case mp_blue_part_sector: mp_print(mp, "blue"); break;
6227   case mp_cyan_part_sector: mp_print(mp, "cyan"); break;
6228   case mp_magenta_part_sector: mp_print(mp, "magenta"); break;
6229   case mp_yellow_part_sector: mp_print(mp, "yellow"); break;
6230   case mp_black_part_sector: mp_print(mp, "black"); break;
6231   case mp_grey_part_sector: mp_print(mp, "grey"); break;
6232   case mp_capsule: 
6233     mp_print(mp, "%CAPSULE"); mp_print_int(mp, p-null); return;
6234     break;
6235 @.CAPSULE@>
6236   } /* there are no other cases */
6237   mp_print(mp, "part "); 
6238   p=link(p-mp->sector_offset[name_type(p)]);
6239 }
6240
6241 @ The |interesting| function returns |true| if a given variable is not
6242 in a capsule, or if the user wants to trace capsules.
6243
6244 @c 
6245 boolean mp_interesting (MP mp,pointer p) {
6246   small_number t; /* a |name_type| */
6247   if ( mp->internal[tracing_capsules]>0 ) {
6248     return true;
6249   } else { 
6250     t=name_type(p);
6251     if ( t>=mp_x_part_sector ) if ( t!=mp_capsule )
6252       t=name_type(link(p-mp->sector_offset[t]));
6253     return (t!=mp_capsule);
6254   }
6255 }
6256
6257 @ Now here is a subroutine that converts an unstructured type into an
6258 equivalent structured type, by inserting a |mp_structured| node that is
6259 capable of growing. This operation is done only when |name_type(p)=root|,
6260 |subscr|, or |attr|.
6261
6262 The procedure returns a pointer to the new node that has taken node~|p|'s
6263 place in the structure. Node~|p| itself does not move, nor are its
6264 |value| or |type| fields changed in any way.
6265
6266 @c 
6267 pointer mp_new_structure (MP mp,pointer p) {
6268   pointer q,r=0; /* list manipulation registers */
6269   switch (name_type(p)) {
6270   case mp_root: 
6271     q=link(p); r=mp_get_node(mp, value_node_size); equiv(q)=r;
6272     break;
6273   case mp_subscr: 
6274     @<Link a new subscript node |r| in place of node |p|@>;
6275     break;
6276   case mp_attr: 
6277     @<Link a new attribute node |r| in place of node |p|@>;
6278     break;
6279   default: 
6280     mp_confusion(mp, "struct");
6281 @:this can't happen struct}{\quad struct@>
6282     break;
6283   }
6284   link(r)=link(p); type(r)=mp_structured; name_type(r)=name_type(p);
6285   attr_head(r)=p; name_type(p)=mp_structured_root;
6286   q=mp_get_node(mp, attr_node_size); link(p)=q; subscr_head(r)=q;
6287   parent(q)=r; type(q)=undefined; name_type(q)=mp_attr; link(q)=end_attr;
6288   attr_loc(q)=collective_subscript; 
6289   return r;
6290 };
6291
6292 @ @<Link a new subscript node |r| in place of node |p|@>=
6293
6294   q=p;
6295   do {  
6296     q=link(q);
6297   } while (name_type(q)!=mp_attr);
6298   q=parent(q); r=subscr_head_loc(q); /* |link(r)=subscr_head(q)| */
6299   do {  
6300     q=r; r=link(r);
6301   } while (r!=p);
6302   r=mp_get_node(mp, subscr_node_size);
6303   link(q)=r; subscript(r)=subscript(p);
6304 }
6305
6306 @ If the attribute is |collective_subscript|, there are two pointers to
6307 node~|p|, so we must change both of them.
6308
6309 @<Link a new attribute node |r| in place of node |p|@>=
6310
6311   q=parent(p); r=attr_head(q);
6312   do {  
6313     q=r; r=link(r);
6314   } while (r!=p);
6315   r=mp_get_node(mp, attr_node_size); link(q)=r;
6316   mp->mem[attr_loc_loc(r)]=mp->mem[attr_loc_loc(p)]; /* copy |attr_loc| and |parent| */
6317   if ( attr_loc(p)==collective_subscript ) { 
6318     q=subscr_head_loc(parent(p));
6319     while ( link(q)!=p ) q=link(q);
6320     link(q)=r;
6321   }
6322 }
6323
6324 @ The |find_variable| routine is given a pointer~|t| to a nonempty token
6325 list of suffixes; it returns a pointer to the corresponding two-word
6326 value. For example, if |t| points to token \.x followed by a numeric
6327 token containing the value~7, |find_variable| finds where the value of
6328 \.{x7} is stored in memory. This may seem a simple task, and it
6329 usually is, except when \.{x7} has never been referenced before.
6330 Indeed, \.x may never have even been subscripted before; complexities
6331 arise with respect to updating the collective subscript information.
6332
6333 If a macro type is detected anywhere along path~|t|, or if the first
6334 item on |t| isn't a |tag_token|, the value |null| is returned.
6335 Otherwise |p| will be a non-null pointer to a node such that
6336 |undefined<type(p)<mp_structured|.
6337
6338 @d abort_find { return null; }
6339
6340 @c 
6341 pointer mp_find_variable (MP mp,pointer t) {
6342   pointer p,q,r,s; /* nodes in the ``value'' line */
6343   pointer pp,qq,rr,ss; /* nodes in the ``collective'' line */
6344   integer n; /* subscript or attribute */
6345   memory_word save_word; /* temporary storage for a word of |mem| */
6346 @^inner loop@>
6347   p=info(t); t=link(t);
6348   if ( (eq_type(p) % outer_tag) != tag_token ) abort_find;
6349   if ( equiv(p)==null ) mp_new_root(mp, p);
6350   p=equiv(p); pp=p;
6351   while ( t!=null ) { 
6352     @<Make sure that both nodes |p| and |pp| are of |mp_structured| type@>;
6353     if ( t<mp->hi_mem_min ) {
6354       @<Descend one level for the subscript |value(t)|@>
6355     } else {
6356       @<Descend one level for the attribute |info(t)|@>;
6357     }
6358     t=link(t);
6359   }
6360   if ( type(pp)>=mp_structured ) {
6361     if ( type(pp)==mp_structured ) pp=attr_head(pp); else abort_find;
6362   }
6363   if ( type(p)==mp_structured ) p=attr_head(p);
6364   if ( type(p)==undefined ) { 
6365     if ( type(pp)==undefined ) { type(pp)=mp_numeric_type; value(pp)=null; };
6366     type(p)=type(pp); value(p)=null;
6367   };
6368   return p;
6369 }
6370
6371 @ Although |pp| and |p| begin together, they diverge when a subscript occurs;
6372 |pp|~stays in the collective line while |p|~goes through actual subscript
6373 values.
6374
6375 @<Make sure that both nodes |p| and |pp|...@>=
6376 if ( type(pp)!=mp_structured ) { 
6377   if ( type(pp)>mp_structured ) abort_find;
6378   ss=mp_new_structure(mp, pp);
6379   if ( p==pp ) p=ss;
6380   pp=ss;
6381 }; /* now |type(pp)=mp_structured| */
6382 if ( type(p)!=mp_structured ) /* it cannot be |>mp_structured| */
6383   p=mp_new_structure(mp, p) /* now |type(p)=mp_structured| */
6384
6385 @ We want this part of the program to be reasonably fast, in case there are
6386 @^inner loop@>
6387 lots of subscripts at the same level of the data structure. Therefore
6388 we store an ``infinite'' value in the word that appears at the end of the
6389 subscript list, even though that word isn't part of a subscript node.
6390
6391 @<Descend one level for the subscript |value(t)|@>=
6392
6393   n=value(t);
6394   pp=link(attr_head(pp)); /* now |attr_loc(pp)=collective_subscript| */
6395   q=link(attr_head(p)); save_word=mp->mem[subscript_loc(q)];
6396   subscript(q)=el_gordo; s=subscr_head_loc(p); /* |link(s)=subscr_head(p)| */
6397   do {  
6398     r=s; s=link(s);
6399   } while (n>subscript(s));
6400   if ( n==subscript(s) ) {
6401     p=s;
6402   } else { 
6403     p=mp_get_node(mp, subscr_node_size); link(r)=p; link(p)=s;
6404     subscript(p)=n; name_type(p)=mp_subscr; type(p)=undefined;
6405   }
6406   mp->mem[subscript_loc(q)]=save_word;
6407 }
6408
6409 @ @<Descend one level for the attribute |info(t)|@>=
6410
6411   n=info(t);
6412   ss=attr_head(pp);
6413   do {  
6414     rr=ss; ss=link(ss);
6415   } while (n>attr_loc(ss));
6416   if ( n<attr_loc(ss) ) { 
6417     qq=mp_get_node(mp, attr_node_size); link(rr)=qq; link(qq)=ss;
6418     attr_loc(qq)=n; name_type(qq)=mp_attr; type(qq)=undefined;
6419     parent(qq)=pp; ss=qq;
6420   }
6421   if ( p==pp ) { 
6422     p=ss; pp=ss;
6423   } else { 
6424     pp=ss; s=attr_head(p);
6425     do {  
6426       r=s; s=link(s);
6427     } while (n>attr_loc(s));
6428     if ( n==attr_loc(s) ) {
6429       p=s;
6430     } else { 
6431       q=mp_get_node(mp, attr_node_size); link(r)=q; link(q)=s;
6432       attr_loc(q)=n; name_type(q)=mp_attr; type(q)=undefined;
6433       parent(q)=p; p=q;
6434     }
6435   }
6436 }
6437
6438 @ Variables lose their former values when they appear in a type declaration,
6439 or when they are defined to be macros or \&{let} equal to something else.
6440 A subroutine will be defined later that recycles the storage associated
6441 with any particular |type| or |value|; our goal now is to study a higher
6442 level process called |flush_variable|, which selectively frees parts of a
6443 variable structure.
6444
6445 This routine has some complexity because of examples such as
6446 `\hbox{\tt numeric x[]a[]b}'
6447 which recycles all variables of the form \.{x[i]a[j]b} (and no others), while
6448 `\hbox{\tt vardef x[]a[]=...}'
6449 discards all variables of the form \.{x[i]a[j]} followed by an arbitrary
6450 suffix, except for the collective node \.{x[]a[]} itself. The obvious way
6451 to handle such examples is to use recursion; so that's what we~do.
6452 @^recursion@>
6453
6454 Parameter |p| points to the root information of the variable;
6455 parameter |t| points to a list of one-word nodes that represent
6456 suffixes, with |info=collective_subscript| for subscripts.
6457
6458 @<Declarations@>=
6459 @<Declare subroutines for printing expressions@>
6460 @<Declare basic dependency-list subroutines@>
6461 @<Declare the recycling subroutines@>
6462 void mp_flush_cur_exp (MP mp,scaled v) ;
6463 @<Declare the procedure called |flush_below_variable|@>
6464
6465 @ @c 
6466 void mp_flush_variable (MP mp,pointer p, pointer t, boolean discard_suffixes) {
6467   pointer q,r; /* list manipulation */
6468   halfword n; /* attribute to match */
6469   while ( t!=null ) { 
6470     if ( type(p)!=mp_structured ) return;
6471     n=info(t); t=link(t);
6472     if ( n==collective_subscript ) { 
6473       r=subscr_head_loc(p); q=link(r); /* |q=subscr_head(p)| */
6474       while ( name_type(q)==mp_subscr ){ 
6475         mp_flush_variable(mp, q,t,discard_suffixes);
6476         if ( t==null ) {
6477           if ( type(q)==mp_structured ) r=q;
6478           else  { link(r)=link(q); mp_free_node(mp, q,subscr_node_size);   }
6479         } else {
6480           r=q;
6481         }
6482         q=link(r);
6483       }
6484     }
6485     p=attr_head(p);
6486     do {  
6487       r=p; p=link(p);
6488     } while (attr_loc(p)<n);
6489     if ( attr_loc(p)!=n ) return;
6490   }
6491   if ( discard_suffixes ) {
6492     mp_flush_below_variable(mp, p);
6493   } else { 
6494     if ( type(p)==mp_structured ) p=attr_head(p);
6495     mp_recycle_value(mp, p);
6496   }
6497 }
6498
6499 @ The next procedure is simpler; it wipes out everything but |p| itself,
6500 which becomes undefined.
6501
6502 @<Declare the procedure called |flush_below_variable|@>=
6503 void mp_flush_below_variable (MP mp, pointer p);
6504
6505 @ @c
6506 void mp_flush_below_variable (MP mp,pointer p) {
6507    pointer q,r; /* list manipulation registers */
6508   if ( type(p)!=mp_structured ) {
6509     mp_recycle_value(mp, p); /* this sets |type(p)=undefined| */
6510   } else { 
6511     q=subscr_head(p);
6512     while ( name_type(q)==mp_subscr ) { 
6513       mp_flush_below_variable(mp, q); r=q; q=link(q);
6514       mp_free_node(mp, r,subscr_node_size);
6515     }
6516     r=attr_head(p); q=link(r); mp_recycle_value(mp, r);
6517     if ( name_type(p)<=mp_saved_root ) mp_free_node(mp, r,value_node_size);
6518     else mp_free_node(mp, r,subscr_node_size);
6519     /* we assume that |subscr_node_size=attr_node_size| */
6520     do {  
6521       mp_flush_below_variable(mp, q); r=q; q=link(q); mp_free_node(mp, r,attr_node_size);
6522     } while (q!=end_attr);
6523     type(p)=undefined;
6524   }
6525 }
6526
6527 @ Just before assigning a new value to a variable, we will recycle the
6528 old value and make the old value undefined. The |und_type| routine
6529 determines what type of undefined value should be given, based on
6530 the current type before recycling.
6531
6532 @c 
6533 small_number mp_und_type (MP mp,pointer p) { 
6534   switch (type(p)) {
6535   case undefined: case mp_vacuous:
6536     return undefined;
6537   case mp_boolean_type: case mp_unknown_boolean:
6538     return mp_unknown_boolean;
6539   case mp_string_type: case mp_unknown_string:
6540     return mp_unknown_string;
6541   case mp_pen_type: case mp_unknown_pen:
6542     return mp_unknown_pen;
6543   case mp_path_type: case mp_unknown_path:
6544     return mp_unknown_path;
6545   case mp_picture_type: case mp_unknown_picture:
6546     return mp_unknown_picture;
6547   case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
6548   case mp_pair_type: case mp_numeric_type: 
6549     return type(p);
6550   case mp_known: case mp_dependent: case mp_proto_dependent: case mp_independent:
6551     return mp_numeric_type;
6552   } /* there are no other cases */
6553   return 0;
6554 }
6555
6556 @ The |clear_symbol| routine is used when we want to redefine the equivalent
6557 of a symbolic token. It must remove any variable structure or macro
6558 definition that is currently attached to that symbol. If the |saving|
6559 parameter is true, a subsidiary structure is saved instead of destroyed.
6560
6561 @c 
6562 void mp_clear_symbol (MP mp,pointer p, boolean saving) {
6563   pointer q; /* |equiv(p)| */
6564   q=equiv(p);
6565   switch (eq_type(p) % outer_tag)  {
6566   case defined_macro:
6567   case secondary_primary_macro:
6568   case tertiary_secondary_macro:
6569   case expression_tertiary_macro: 
6570     if ( ! saving ) mp_delete_mac_ref(mp, q);
6571     break;
6572   case tag_token:
6573     if ( q!=null ) {
6574       if ( saving ) {
6575         name_type(q)=mp_saved_root;
6576       } else { 
6577         mp_flush_below_variable(mp, q); mp_free_node(mp,q,value_node_size); 
6578       }
6579     }
6580     break;
6581   default:
6582     break;
6583   }
6584   mp->eqtb[p]=mp->eqtb[frozen_undefined];
6585 };
6586
6587 @* \[16] Saving and restoring equivalents.
6588 The nested structure given by \&{begingroup} and \&{endgroup}
6589 allows |eqtb| entries to be saved and restored, so that temporary changes
6590 can be made without difficulty.  When the user requests a current value to
6591 be saved, \MP\ puts that value into its ``save stack.'' An appearance of
6592 \&{endgroup} ultimately causes the old values to be removed from the save
6593 stack and put back in their former places.
6594
6595 The save stack is a linked list containing three kinds of entries,
6596 distinguished by their |info| fields. If |p| points to a saved item,
6597 then
6598
6599 \smallskip\hang
6600 |info(p)=0| stands for a group boundary; each \&{begingroup} contributes
6601 such an item to the save stack and each \&{endgroup} cuts back the stack
6602 until the most recent such entry has been removed.
6603
6604 \smallskip\hang
6605 |info(p)=q|, where |1<=q<=hash_end|, means that |mem[p+1]| holds the former
6606 contents of |eqtb[q]|. Such save stack entries are generated by \&{save}
6607 commands or suitable \&{interim} commands.
6608
6609 \smallskip\hang
6610 |info(p)=hash_end+q|, where |q>0|, means that |value(p)| is a |scaled|
6611 integer to be restored to internal parameter number~|q|. Such entries
6612 are generated by \&{interim} commands.
6613
6614 \smallskip\noindent
6615 The global variable |save_ptr| points to the top item on the save stack.
6616
6617 @d save_node_size 2 /* number of words per non-boundary save-stack node */
6618 @d saved_equiv(A) mp->mem[(A)+1].hh /* where an |eqtb| entry gets saved */
6619 @d save_boundary_item(A) { (A)=mp_get_avail(mp); info((A))=0;
6620   link((A))=mp->save_ptr; mp->save_ptr=(A);
6621   }
6622
6623 @<Glob...@>=
6624 pointer save_ptr; /* the most recently saved item */
6625
6626 @ @<Set init...@>=mp->save_ptr=null;
6627
6628 @ The |save_variable| routine is given a hash address |q|; it salts this
6629 address in the save stack, together with its current equivalent,
6630 then makes token~|q| behave as though it were brand new.
6631
6632 Nothing is stacked when |save_ptr=null|, however; there's no way to remove
6633 things from the stack when the program is not inside a group, so there's
6634 no point in wasting the space.
6635
6636 @c void mp_save_variable (MP mp,pointer q) {
6637   pointer p; /* temporary register */
6638   if ( mp->save_ptr!=null ){ 
6639     p=mp_get_node(mp, save_node_size); info(p)=q; link(p)=mp->save_ptr;
6640     saved_equiv(p)=mp->eqtb[q]; mp->save_ptr=p;
6641   }
6642   mp_clear_symbol(mp, q,(mp->save_ptr!=null));
6643 }
6644
6645 @ Similarly, |save_internal| is given the location |q| of an internal
6646 quantity like |tracing_pens|. It creates a save stack entry of the
6647 third kind.
6648
6649 @c void mp_save_internal (MP mp,halfword q) {
6650   pointer p; /* new item for the save stack */
6651   if ( mp->save_ptr!=null ){ 
6652      p=mp_get_node(mp, save_node_size); info(p)=hash_end+q;
6653     link(p)=mp->save_ptr; value(p)=mp->internal[q]; mp->save_ptr=p;
6654   }
6655 }
6656
6657 @ At the end of a group, the |unsave| routine restores all of the saved
6658 equivalents in reverse order. This routine will be called only when there
6659 is at least one boundary item on the save stack.
6660
6661 @c 
6662 void mp_unsave (MP mp) {
6663   pointer q; /* index to saved item */
6664   pointer p; /* temporary register */
6665   while ( info(mp->save_ptr)!=0 ) {
6666     q=info(mp->save_ptr);
6667     if ( q>hash_end ) {
6668       if ( mp->internal[tracing_restores]>0 ) {
6669         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6670         mp_print(mp, mp->int_name[q-(hash_end)]); mp_print_char(mp, '=');
6671         mp_print_scaled(mp, value(mp->save_ptr)); mp_print_char(mp, '}');
6672         mp_end_diagnostic(mp, false);
6673       }
6674       mp->internal[q-(hash_end)]=value(mp->save_ptr);
6675     } else { 
6676       if ( mp->internal[tracing_restores]>0 ) {
6677         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6678         mp_print_text(q); mp_print_char(mp, '}');
6679         mp_end_diagnostic(mp, false);
6680       }
6681       mp_clear_symbol(mp, q,false);
6682       mp->eqtb[q]=saved_equiv(mp->save_ptr);
6683       if ( eq_type(q) % outer_tag==tag_token ) {
6684         p=equiv(q);
6685         if ( p!=null ) name_type(p)=mp_root;
6686       }
6687     }
6688     p=link(mp->save_ptr); 
6689     mp_free_node(mp, mp->save_ptr,save_node_size); mp->save_ptr=p;
6690   }
6691   p=link(mp->save_ptr); free_avail(mp->save_ptr); mp->save_ptr=p;
6692 }
6693
6694 @* \[17] Data structures for paths.
6695 When a \MP\ user specifies a path, \MP\ will create a list of knots
6696 and control points for the associated cubic spline curves. If the
6697 knots are $z_0$, $z_1$, \dots, $z_n$, there are control points
6698 $z_k^+$ and $z_{k+1}^-$ such that the cubic splines between knots
6699 $z_k$ and $z_{k+1}$ are defined by B\'ezier's formula
6700 @:Bezier}{B\'ezier, Pierre Etienne@>
6701 $$\eqalign{z(t)&=B(z_k,z_k^+,z_{k+1}^-,z_{k+1};t)\cr
6702 &=(1-t)^3z_k+3(1-t)^2tz_k^++3(1-t)t^2z_{k+1}^-+t^3z_{k+1}\cr}$$
6703 for |0<=t<=1|.
6704
6705 There is a 8-word node for each knot $z_k$, containing one word of
6706 control information and six words for the |x| and |y| coordinates of
6707 $z_k^-$ and $z_k$ and~$z_k^+$. The control information appears in the
6708 |left_type| and |right_type| fields, which each occupy a quarter of
6709 the first word in the node; they specify properties of the curve as it
6710 enters and leaves the knot. There's also a halfword |link| field,
6711 which points to the following knot, and a final supplementary word (of
6712 which only a quarter is used).
6713
6714 If the path is a closed contour, knots 0 and |n| are identical;
6715 i.e., the |link| in knot |n-1| points to knot~0. But if the path
6716 is not closed, the |left_type| of knot~0 and the |right_type| of knot~|n|
6717 are equal to |endpoint|. In the latter case the |link| in knot~|n| points
6718 to knot~0, and the control points $z_0^-$ and $z_n^+$ are not used.
6719
6720 @d left_type(A)   mp->mem[(A)].hh.b0 /* characterizes the path entering this knot */
6721 @d right_type(A)   mp->mem[(A)].hh.b1 /* characterizes the path leaving this knot */
6722 @d endpoint 0 /* |left_type| at path beginning and |right_type| at path end */
6723 @d x_coord(A)   mp->mem[(A)+1].sc /* the |x| coordinate of this knot */
6724 @d y_coord(A)   mp->mem[(A)+2].sc /* the |y| coordinate of this knot */
6725 @d left_x(A)   mp->mem[(A)+3].sc /* the |x| coordinate of previous control point */
6726 @d left_y(A)   mp->mem[(A)+4].sc /* the |y| coordinate of previous control point */
6727 @d right_x(A)   mp->mem[(A)+5].sc /* the |x| coordinate of next control point */
6728 @d right_y(A)   mp->mem[(A)+6].sc /* the |y| coordinate of next control point */
6729 @d x_loc(A)   ((A)+1) /* where the |x| coordinate is stored in a knot */
6730 @d y_loc(A)   ((A)+2) /* where the |y| coordinate is stored in a knot */
6731 @d knot_coord(A)   mp->mem[(A)].sc /* |x| or |y| coordinate given |x_loc| or |y_loc| */
6732 @d left_coord(A)   mp->mem[(A)+2].sc
6733   /* coordinate of previous control point given |x_loc| or |y_loc| */
6734 @d right_coord(A)   mp->mem[(A)+4].sc
6735   /* coordinate of next control point given |x_loc| or |y_loc| */
6736 @d knot_node_size 8 /* number of words in a knot node */
6737
6738 @ Before the B\'ezier control points have been calculated, the memory
6739 space they will ultimately occupy is taken up by information that can be
6740 used to compute them. There are four cases:
6741
6742 \yskip
6743 \textindent{$\bullet$} If |right_type=open|, the curve should leave
6744 the knot in the same direction it entered; \MP\ will figure out a
6745 suitable direction.
6746
6747 \yskip
6748 \textindent{$\bullet$} If |right_type=curl|, the curve should leave the
6749 knot in a direction depending on the angle at which it enters the next
6750 knot and on the curl parameter stored in |right_curl|.
6751
6752 \yskip
6753 \textindent{$\bullet$} If |right_type=given|, the curve should leave the
6754 knot in a nonzero direction stored as an |angle| in |right_given|.
6755
6756 \yskip
6757 \textindent{$\bullet$} If |right_type=explicit|, the B\'ezier control
6758 point for leaving this knot has already been computed; it is in the
6759 |right_x| and |right_y| fields.
6760
6761 \yskip\noindent
6762 The rules for |left_type| are similar, but they refer to the curve entering
6763 the knot, and to \\{left} fields instead of \\{right} fields.
6764
6765 Non-|explicit| control points will be chosen based on ``tension'' parameters
6766 in the |left_tension| and |right_tension| fields. The
6767 `\&{atleast}' option is represented by negative tension values.
6768 @:at_least_}{\&{atleast} primitive@>
6769
6770 For example, the \MP\ path specification
6771 $$\.{z0..z1..tension atleast 1..\{curl 2\}z2..z3\{-1,-2\}..tension
6772   3 and 4..p},$$
6773 where \.p is the path `\.{z4..controls z45 and z54..z5}', will be represented
6774 by the six knots
6775 \def\lodash{\hbox to 1.1em{\thinspace\hrulefill\thinspace}}
6776 $$\vbox{\halign{#\hfil&&\qquad#\hfil\cr
6777 |left_type|&\\{left} info&|x_coord,y_coord|&|right_type|&\\{right} info\cr
6778 \noalign{\yskip}
6779 |endpoint|&\lodash$,\,$\lodash&$x_0,y_0$&|curl|&$1.0,1.0$\cr
6780 |open|&\lodash$,1.0$&$x_1,y_1$&|open|&\lodash$,-1.0$\cr
6781 |curl|&$2.0,-1.0$&$x_2,y_2$&|curl|&$2.0,1.0$\cr
6782 |given|&$d,1.0$&$x_3,y_3$&|given|&$d,3.0$\cr
6783 |open|&\lodash$,4.0$&$x_4,y_4$&|explicit|&$x_{45},y_{45}$\cr
6784 |explicit|&$x_{54},y_{54}$&$x_5,y_5$&|endpoint|&\lodash$,\,$\lodash\cr}}$$
6785 Here |d| is the |angle| obtained by calling |n_arg(-unity,-two)|.
6786 Of course, this example is more complicated than anything a normal user
6787 would ever write.
6788
6789 These types must satisfy certain restrictions because of the form of \MP's
6790 path syntax:
6791 (i)~|open| type never appears in the same node together with |endpoint|,
6792 |given|, or |curl|.
6793 (ii)~The |right_type| of a node is |explicit| if and only if the
6794 |left_type| of the following node is |explicit|.
6795 (iii)~|endpoint| types occur only at the ends, as mentioned above.
6796
6797 @d left_curl left_x /* curl information when entering this knot */
6798 @d left_given left_x /* given direction when entering this knot */
6799 @d left_tension left_y /* tension information when entering this knot */
6800 @d right_curl right_x /* curl information when leaving this knot */
6801 @d right_given right_x /* given direction when leaving this knot */
6802 @d right_tension right_y /* tension information when leaving this knot */
6803 @d explicit 1 /* |left_type| or |right_type| when control points are known */
6804 @d given 2 /* |left_type| or |right_type| when a direction is given */
6805 @d curl 3 /* |left_type| or |right_type| when a curl is desired */
6806 @d open 4 /* |left_type| or |right_type| when \MP\ should choose the direction */
6807
6808 @ Knots can be user-supplied, or they can be created by program code,
6809 like the |split_cubic| function, or |copy_path|. The distinction is
6810 needed for the cleanup routine that runs after |split_cubic|, because
6811 it should only delete knots it has previously inserted, and never
6812 anything that was user-supplied. In order to be able to differentiate
6813 one knot from another, we will set |originator(p):=metapost_user| when
6814 it appeared in the actual metapost program, and
6815 |originator(p):=program_code| in all other cases.
6816
6817 @d originator(A)   mp->mem[(A)+7].hh.b0 /* the creator of this knot */
6818 @d program_code 0 /* not created by a user */
6819 @d metapost_user 1 /* created by a user */
6820
6821 @ Here is a routine that prints a given knot list
6822 in symbolic form. It illustrates the conventions discussed above,
6823 and checks for anomalies that might arise while \MP\ is being debugged.
6824
6825 @<Declare subroutines for printing expressions@>=
6826 void mp_pr_path (MP mp,pointer h);
6827
6828 @ @c
6829 void mp_pr_path (MP mp,pointer h) {
6830   pointer p,q; /* for list traversal */
6831   p=h;
6832   do {  
6833     q=link(p);
6834     if ( (p==null)||(q==null) ) { 
6835       mp_print_nl(mp, "???"); return; /* this won't happen */
6836 @.???@>
6837     }
6838     @<Print information for adjacent knots |p| and |q|@>;
6839   DONE1:
6840     p=q;
6841     if ( (p!=h)||(left_type(h)!=endpoint) ) {
6842       @<Print two dots, followed by |given| or |curl| if present@>;
6843     }
6844   } while (p!=h);
6845   if ( left_type(h)!=endpoint ) 
6846     mp_print(mp, "cycle");
6847 }
6848
6849 @ @<Print information for adjacent knots...@>=
6850 mp_print_two(mp, x_coord(p),y_coord(p));
6851 switch (right_type(p)) {
6852 case endpoint: 
6853   if ( left_type(p)==open ) mp_print(mp, "{open?}"); /* can't happen */
6854 @.open?@>
6855   if ( (left_type(q)!=endpoint)||(q!=h) ) q=null; /* force an error */
6856   goto DONE1;
6857   break;
6858 case explicit: 
6859   @<Print control points between |p| and |q|, then |goto done1|@>;
6860   break;
6861 case open: 
6862   @<Print information for a curve that begins |open|@>;
6863   break;
6864 case curl:
6865 case given: 
6866   @<Print information for a curve that begins |curl| or |given|@>;
6867   break;
6868 default:
6869   mp_print(mp, "???"); /* can't happen */
6870 @.???@>
6871   break;
6872 }
6873 if ( left_type(q)<=explicit ) {
6874   mp_print(mp, "..control?"); /* can't happen */
6875 @.control?@>
6876 } else if ( (right_tension(p)!=unity)||(left_tension(q)!=unity) ) {
6877   @<Print tension between |p| and |q|@>;
6878 }
6879
6880 @ Since |n_sin_cos| produces |fraction| results, which we will print as if they
6881 were |scaled|, the magnitude of a |given| direction vector will be~4096.
6882
6883 @<Print two dots...@>=
6884
6885   mp_print_nl(mp, " ..");
6886   if ( left_type(p)==given ) { 
6887     mp_n_sin_cos(mp, left_given(p)); mp_print_char(mp, '{');
6888     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ',');
6889     mp_print_scaled(mp, mp->n_sin); mp_print_char(mp, '}');
6890   } else if ( left_type(p)==curl ){ 
6891     mp_print(mp, "{curl "); 
6892     mp_print_scaled(mp, left_curl(p)); mp_print_char(mp, '}');
6893   }
6894 }
6895
6896 @ @<Print tension between |p| and |q|@>=
6897
6898   mp_print(mp, "..tension ");
6899   if ( right_tension(p)<0 ) mp_print(mp, "atleast");
6900   mp_print_scaled(mp, abs(right_tension(p)));
6901   if ( right_tension(p)!=left_tension(q) ){ 
6902     mp_print(mp, " and ");
6903     if ( left_tension(q)<0 ) mp_print(mp, "atleast");
6904     mp_print_scaled(mp, abs(left_tension(q)));
6905   }
6906 }
6907
6908 @ @<Print control points between |p| and |q|, then |goto done1|@>=
6909
6910   mp_print(mp, "..controls "); 
6911   mp_print_two(mp, right_x(p),right_y(p)); 
6912   mp_print(mp, " and ");
6913   if ( left_type(q)!=explicit ) { 
6914     mp_print(mp, "??"); /* can't happen */
6915 @.??@>
6916   } else {
6917     mp_print_two(mp, left_x(q),left_y(q));
6918   }
6919   goto DONE1;
6920 }
6921
6922 @ @<Print information for a curve that begins |open|@>=
6923 if ( (left_type(p)!=explicit)&&(left_type(p)!=open) ) {
6924   mp_print(mp, "{open?}"); /* can't happen */
6925 @.open?@>
6926 }
6927
6928 @ A curl of 1 is shown explicitly, so that the user sees clearly that
6929 \MP's default curl is present.
6930
6931 The code here uses the fact that |left_curl==left_given| and
6932 |right_curl==right_given|.
6933
6934 @<Print information for a curve that begins |curl|...@>=
6935
6936   if ( left_type(p)==open )  
6937     mp_print(mp, "??"); /* can't happen */
6938 @.??@>
6939   if ( right_type(p)==curl ) { 
6940     mp_print(mp, "{curl "); mp_print_scaled(mp, right_curl(p));
6941   } else { 
6942     mp_n_sin_cos(mp, right_given(p)); mp_print_char(mp, '{');
6943     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ','); 
6944     mp_print_scaled(mp, mp->n_sin);
6945   }
6946   mp_print_char(mp, '}');
6947 }
6948
6949 @ It is convenient to have another version of |pr_path| that prints the path
6950 as a diagnostic message.
6951
6952 @<Declare subroutines for printing expressions@>=
6953 void mp_print_path (MP mp,pointer h, char *s, boolean nuline) { 
6954   mp_print_diagnostic(mp, "Path", s, nuline); mp_print_ln(mp);
6955 @.Path at line...@>
6956   mp_pr_path(mp, h);
6957   mp_end_diagnostic(mp, true);
6958 }
6959
6960 @ If we want to duplicate a knot node, we can say |copy_knot|:
6961
6962 @c 
6963 pointer mp_copy_knot (MP mp,pointer p) {
6964   pointer q; /* the copy */
6965   int k; /* runs through the words of a knot node */
6966   q=mp_get_node(mp, knot_node_size);
6967   for (k=0;k<=knot_node_size-1;k++) {
6968     mp->mem[q+k]=mp->mem[p+k];
6969   }
6970   originator(q)=originator(p);
6971   return q;
6972 }
6973
6974 @ The |copy_path| routine makes a clone of a given path.
6975
6976 @c 
6977 pointer mp_copy_path (MP mp, pointer p) {
6978   pointer q,pp,qq; /* for list manipulation */
6979   q=mp_copy_knot(mp, p);
6980   qq=q; pp=link(p);
6981   while ( pp!=p ) { 
6982     link(qq)=mp_copy_knot(mp, pp);
6983     qq=link(qq);
6984     pp=link(pp);
6985   }
6986   link(qq)=q;
6987   return q;
6988 }
6989
6990 @ Similarly, there's a way to copy the {\sl reverse\/} of a path. This procedure
6991 returns a pointer to the first node of the copy, if the path is a cycle,
6992 but to the final node of a non-cyclic copy. The global
6993 variable |path_tail| will point to the final node of the original path;
6994 this trick makes it easier to implement `\&{doublepath}'.
6995
6996 All node types are assumed to be |endpoint| or |explicit| only.
6997
6998 @c 
6999 pointer mp_htap_ypoc (MP mp,pointer p) {
7000   pointer q,pp,qq,rr; /* for list manipulation */
7001   q=mp_get_node(mp, knot_node_size); /* this will correspond to |p| */
7002   qq=q; pp=p;
7003   while (1) { 
7004     right_type(qq)=left_type(pp); left_type(qq)=right_type(pp);
7005     x_coord(qq)=x_coord(pp); y_coord(qq)=y_coord(pp);
7006     right_x(qq)=left_x(pp); right_y(qq)=left_y(pp);
7007     left_x(qq)=right_x(pp); left_y(qq)=right_y(pp);
7008     originator(qq)=originator(pp);
7009     if ( link(pp)==p ) { 
7010       link(q)=qq; mp->path_tail=pp; return q;
7011     }
7012     rr=mp_get_node(mp, knot_node_size); link(rr)=qq; qq=rr; pp=link(pp);
7013   }
7014 }
7015
7016 @ @<Glob...@>=
7017 pointer path_tail; /* the node that links to the beginning of a path */
7018
7019 @ When a cyclic list of knot nodes is no longer needed, it can be recycled by
7020 calling the following subroutine.
7021
7022 @<Declare the recycling subroutines@>=
7023 void mp_toss_knot_list (MP mp,pointer p) ;
7024
7025 @ @c
7026 void mp_toss_knot_list (MP mp,pointer p) {
7027   pointer q; /* the node being freed */
7028   pointer r; /* the next node */
7029   q=p;
7030   do {  
7031     r=link(q); 
7032     mp_free_node(mp, q,knot_node_size); q=r;
7033   } while (q!=p);
7034 }
7035
7036 @* \[18] Choosing control points.
7037 Now we must actually delve into one of \MP's more difficult routines,
7038 the |make_choices| procedure that chooses angles and control points for
7039 the splines of a curve when the user has not specified them explicitly.
7040 The parameter to |make_choices| points to a list of knots and
7041 path information, as described above.
7042
7043 A path decomposes into independent segments at ``breakpoint'' knots,
7044 which are knots whose left and right angles are both prespecified in
7045 some way (i.e., their |left_type| and |right_type| aren't both open).
7046
7047 @c 
7048 @<Declare the procedure called |solve_choices|@>;
7049 void mp_make_choices (MP mp,pointer knots) {
7050   pointer h; /* the first breakpoint */
7051   pointer p,q; /* consecutive breakpoints being processed */
7052   @<Other local variables for |make_choices|@>;
7053   check_arith; /* make sure that |arith_error=false| */
7054   if ( mp->internal[tracing_choices]>0 )
7055     mp_print_path(mp, knots,", before choices",true);
7056   @<If consecutive knots are equal, join them explicitly@>;
7057   @<Find the first breakpoint, |h|, on the path;
7058     insert an artificial breakpoint if the path is an unbroken cycle@>;
7059   p=h;
7060   do {  
7061     @<Fill in the control points between |p| and the next breakpoint,
7062       then advance |p| to that breakpoint@>;
7063   } while (p!=h);
7064   if ( mp->internal[tracing_choices]>0 )
7065     mp_print_path(mp, knots,", after choices",true);
7066   if ( mp->arith_error ) {
7067     @<Report an unexpected problem during the choice-making@>;
7068   }
7069 }
7070
7071 @ @<Report an unexpected problem during the choice...@>=
7072
7073   print_err("Some number got too big");
7074 @.Some number got too big@>
7075   help2("The path that I just computed is out of range.")
7076        ("So it will probably look funny. Proceed, for a laugh.");
7077   mp_put_get_error(mp); mp->arith_error=false;
7078 }
7079
7080 @ Two knots in a row with the same coordinates will always be joined
7081 by an explicit ``curve'' whose control points are identical with the
7082 knots.
7083
7084 @<If consecutive knots are equal, join them explicitly@>=
7085 p=knots;
7086 do {  
7087   q=link(p);
7088   if ( x_coord(p)==x_coord(q) && y_coord(p)==y_coord(q) && right_type(p)>explicit ) { 
7089     right_type(p)=explicit;
7090     if ( left_type(p)==open ) { 
7091       left_type(p)=curl; left_curl(p)=unity;
7092     }
7093     left_type(q)=explicit;
7094     if ( right_type(q)==open ) { 
7095       right_type(q)=curl; right_curl(q)=unity;
7096     }
7097     right_x(p)=x_coord(p); left_x(q)=x_coord(p);
7098     right_y(p)=y_coord(p); left_y(q)=y_coord(p);
7099   }
7100   p=q;
7101 } while (p!=knots)
7102
7103 @ If there are no breakpoints, it is necessary to compute the direction
7104 angles around an entire cycle. In this case the |left_type| of the first
7105 node is temporarily changed to |end_cycle|.
7106
7107 @d end_cycle (open+1)
7108
7109 @<Find the first breakpoint, |h|, on the path...@>=
7110 h=knots;
7111 while (1) { 
7112   if ( left_type(h)!=open ) break;
7113   if ( right_type(h)!=open ) break;
7114   h=link(h);
7115   if ( h==knots ) { 
7116     left_type(h)=end_cycle; break;
7117   }
7118 }
7119
7120 @ If |right_type(p)<given| and |q=link(p)|, we must have
7121 |right_type(p)=left_type(q)=explicit| or |endpoint|.
7122
7123 @<Fill in the control points between |p| and the next breakpoint...@>=
7124 q=link(p);
7125 if ( right_type(p)>=given ) { 
7126   while ( (left_type(q)==open)&&(right_type(q)==open) ) q=link(q);
7127   @<Fill in the control information between
7128     consecutive breakpoints |p| and |q|@>;
7129 } else if ( right_type(p)==endpoint ) {
7130   @<Give reasonable values for the unused control points between |p| and~|q|@>;
7131 }
7132 p=q
7133
7134 @ This step makes it possible to transform an explicitly computed path without
7135 checking the |left_type| and |right_type| fields.
7136
7137 @<Give reasonable values for the unused control points between |p| and~|q|@>=
7138
7139   right_x(p)=x_coord(p); right_y(p)=y_coord(p);
7140   left_x(q)=x_coord(q); left_y(q)=y_coord(q);
7141 }
7142
7143 @ Before we can go further into the way choices are made, we need to
7144 consider the underlying theory. The basic ideas implemented in |make_choices|
7145 are due to John Hobby, who introduced the notion of ``mock curvature''
7146 @^Hobby, John Douglas@>
7147 at a knot. Angles are chosen so that they preserve mock curvature when
7148 a knot is passed, and this has been found to produce excellent results.
7149
7150 It is convenient to introduce some notations that simplify the necessary
7151 formulas. Let $d_{k,k+1}=\vert z\k-z_k\vert$ be the (nonzero) distance
7152 between knots |k| and |k+1|; and let
7153 $${z\k-z_k\over z_k-z_{k-1}}={d_{k,k+1}\over d_{k-1,k}}e^{i\psi_k}$$
7154 so that a polygonal line from $z_{k-1}$ to $z_k$ to $z\k$ turns left
7155 through an angle of~$\psi_k$. We assume that $\vert\psi_k\vert\L180^\circ$.
7156 The control points for the spline from $z_k$ to $z\k$ will be denoted by
7157 $$\eqalign{z_k^+&=z_k+
7158   \textstyle{1\over3}\rho_k e^{i\theta_k}(z\k-z_k),\cr
7159  z\k^-&=z\k-
7160   \textstyle{1\over3}\sigma\k e^{-i\phi\k}(z\k-z_k),\cr}$$
7161 where $\rho_k$ and $\sigma\k$ are nonnegative ``velocity ratios'' at the
7162 beginning and end of the curve, while $\theta_k$ and $\phi\k$ are the
7163 corresponding ``offset angles.'' These angles satisfy the condition
7164 $$\theta_k+\phi_k+\psi_k=0,\eqno(*)$$
7165 whenever the curve leaves an intermediate knot~|k| in the direction that
7166 it enters.
7167
7168 @ Let $\alpha_k$ and $\beta\k$ be the reciprocals of the ``tension'' of
7169 the curve at its beginning and ending points. This means that
7170 $\rho_k=\alpha_k f(\theta_k,\phi\k)$ and $\sigma\k=\beta\k f(\phi\k,\theta_k)$,
7171 where $f(\theta,\phi)$ is \MP's standard velocity function defined in
7172 the |velocity| subroutine. The cubic spline $B(z_k^{\phantom+},z_k^+,
7173 z\k^-,z\k^{\phantom+};t)$
7174 has curvature
7175 @^curvature@>
7176 $${2\sigma\k\sin(\theta_k+\phi\k)-6\sin\theta_k\over\rho_k^2d_{k,k+1}}
7177 \qquad{\rm and}\qquad
7178 {2\rho_k\sin(\theta_k+\phi\k)-6\sin\phi\k\over\sigma\k^2d_{k,k+1}}$$
7179 at |t=0| and |t=1|, respectively. The mock curvature is the linear
7180 @^mock curvature@>
7181 approximation to this true curvature that arises in the limit for
7182 small $\theta_k$ and~$\phi\k$, if second-order terms are discarded.
7183 The standard velocity function satisfies
7184 $$f(\theta,\phi)=1+O(\theta^2+\theta\phi+\phi^2);$$
7185 hence the mock curvatures are respectively
7186 $${2\beta\k(\theta_k+\phi\k)-6\theta_k\over\alpha_k^2d_{k,k+1}}
7187 \qquad{\rm and}\qquad
7188 {2\alpha_k(\theta_k+\phi\k)-6\phi\k\over\beta\k^2d_{k,k+1}}.\eqno(**)$$
7189
7190 @ The turning angles $\psi_k$ are given, and equation $(*)$ above
7191 determines $\phi_k$ when $\theta_k$ is known, so the task of
7192 angle selection is essentially to choose appropriate values for each
7193 $\theta_k$. When equation~$(*)$ is used to eliminate $\phi$~variables
7194 from $(**)$, we obtain a system of linear equations of the form
7195 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7196 where
7197 $$A_k={\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7198 \qquad B_k={3-\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7199 \qquad C_k={3-\beta\k\over\alpha_k^2d_{k,k+1}},
7200 \qquad D_k={\beta\k\over\alpha_k^2d_{k,k+1}}.$$
7201 The tensions are always $3\over4$ or more, hence each $\alpha$ and~$\beta$
7202 will be at most $4\over3$. It follows that $B_k\G{5\over4}A_k$ and
7203 $C_k\G{5\over4}D_k$; hence the equations are diagonally dominant;
7204 hence they have a unique solution. Moreover, in most cases the tensions
7205 are equal to~1, so that $B_k=2A_k$ and $C_k=2D_k$. This makes the
7206 solution numerically stable, and there is an exponential damping
7207 effect: The data at knot $k\pm j$ affects the angle at knot~$k$ by
7208 a factor of~$O(2^{-j})$.
7209
7210 @ However, we still must consider the angles at the starting and ending
7211 knots of a non-cyclic path. These angles might be given explicitly, or
7212 they might be specified implicitly in terms of an amount of ``curl.''
7213
7214 Let's assume that angles need to be determined for a non-cyclic path
7215 starting at $z_0$ and ending at~$z_n$. Then equations of the form
7216 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta_{k+1}=R_k$$
7217 have been given for $0<k<n$, and it will be convenient to introduce
7218 equations of the same form for $k=0$ and $k=n$, where
7219 $$A_0=B_0=C_n=D_n=0.$$
7220 If $\theta_0$ is supposed to have a given value $E_0$, we simply
7221 define $C_0=0$, $D_0=0$, and $R_0=E_0$. Otherwise a curl
7222 parameter, $\gamma_0$, has been specified at~$z_0$; this means
7223 that the mock curvature at $z_0$ should be $\gamma_0$ times the
7224 mock curvature at $z_1$; i.e.,
7225 $${2\beta_1(\theta_0+\phi_1)-6\theta_0\over\alpha_0^2d_{01}}
7226 =\gamma_0{2\alpha_0(\theta_0+\phi_1)-6\phi_1\over\beta_1^2d_{01}}.$$
7227 This equation simplifies to
7228 $$(\alpha_0\chi_0+3-\beta_1)\theta_0+
7229  \bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\theta_1=
7230  -\bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\psi_1,$$
7231 where $\chi_0=\alpha_0^2\gamma_0/\beta_1^2$; so we can set $C_0=
7232 \chi_0\alpha_0+3-\beta_1$, $D_0=(3-\alpha_0)\chi_0+\beta_1$, $R_0=-D_0\psi_1$.
7233 It can be shown that $C_0>0$ and $C_0B_1-A_1D_0>0$ when $\gamma_0\G0$,
7234 hence the linear equations remain nonsingular.
7235
7236 Similar considerations apply at the right end, when the final angle $\phi_n$
7237 may or may not need to be determined. It is convenient to let $\psi_n=0$,
7238 hence $\theta_n=-\phi_n$. We either have an explicit equation $\theta_n=E_n$,
7239 or we have
7240 $$\bigl((3-\beta_n)\chi_n+\alpha_{n-1}\bigr)\theta_{n-1}+
7241 (\beta_n\chi_n+3-\alpha_{n-1})\theta_n=0,\qquad
7242   \chi_n={\beta_n^2\gamma_n\over\alpha_{n-1}^2}.$$
7243
7244 When |make_choices| chooses angles, it must compute the coefficients of
7245 these linear equations, then solve the equations. To compute the coefficients,
7246 it is necessary to compute arctangents of the given turning angles~$\psi_k$.
7247 When the equations are solved, the chosen directions $\theta_k$ are put
7248 back into the form of control points by essentially computing sines and
7249 cosines.
7250
7251 @ OK, we are ready to make the hard choices of |make_choices|.
7252 Most of the work is relegated to an auxiliary procedure
7253 called |solve_choices|, which has been introduced to keep
7254 |make_choices| from being extremely long.
7255
7256 @<Fill in the control information between...@>=
7257 @<Calculate the turning angles $\psi_k$ and the distances $d_{k,k+1}$;
7258   set $n$ to the length of the path@>;
7259 @<Remove |open| types at the breakpoints@>;
7260 mp_solve_choices(mp, p,q,n)
7261
7262 @ It's convenient to precompute quantities that will be needed several
7263 times later. The values of |delta_x[k]| and |delta_y[k]| will be the
7264 coordinates of $z\k-z_k$, and the magnitude of this vector will be
7265 |delta[k]=@t$d_{k,k+1}$@>|. The path angle $\psi_k$ between $z_k-z_{k-1}$
7266 and $z\k-z_k$ will be stored in |psi[k]|.
7267
7268 @<Glob...@>=
7269 int path_size; /* maximum number of knots between breakpoints of a path */
7270 scaled *delta_x;
7271 scaled *delta_y;
7272 scaled *delta; /* knot differences */
7273 angle  *psi; /* turning angles */
7274
7275 @ @<Allocate or initialize ...@>=
7276 mp->delta_x = NULL;
7277 mp->delta_y = NULL;
7278 mp->delta = NULL;
7279 mp->psi = NULL;
7280
7281 @ @<Dealloc variables@>=
7282 xfree(mp->delta_x);
7283 xfree(mp->delta_y);
7284 xfree(mp->delta);
7285 xfree(mp->psi);
7286
7287 @ @<Other local variables for |make_choices|@>=
7288   int k,n; /* current and final knot numbers */
7289   pointer s,t; /* registers for list traversal */
7290   scaled delx,dely; /* directions where |open| meets |explicit| */
7291   fraction sine,cosine; /* trig functions of various angles */
7292
7293 @ @<Calculate the turning angles...@>=
7294 {
7295 RESTART:
7296   k=0; s=p; n=mp->path_size;
7297   do {  
7298     t=link(s);
7299     mp->delta_x[k]=x_coord(t)-x_coord(s);
7300     mp->delta_y[k]=y_coord(t)-y_coord(s);
7301     mp->delta[k]=mp_pyth_add(mp, mp->delta_x[k],mp->delta_y[k]);
7302     if ( k>0 ) { 
7303       sine=mp_make_fraction(mp, mp->delta_y[k-1],mp->delta[k-1]);
7304       cosine=mp_make_fraction(mp, mp->delta_x[k-1],mp->delta[k-1]);
7305       mp->psi[k]=mp_n_arg(mp, mp_take_fraction(mp, mp->delta_x[k],cosine)+
7306         mp_take_fraction(mp, mp->delta_y[k],sine),
7307         mp_take_fraction(mp, mp->delta_y[k],cosine)-
7308           mp_take_fraction(mp, mp->delta_x[k],sine));
7309     }
7310     incr(k); s=t;
7311     if ( k==mp->path_size ) {
7312       mp_reallocate_paths(mp, mp->path_size+(mp->path_size>>2));
7313       goto RESTART; /* retry, loop size has changed */
7314     }
7315     if ( s==q ) n=k;
7316   } while (! (k>=n)&&(left_type(s)!=end_cycle));
7317   if ( k==n ) mp->psi[n]=0; else mp->psi[k]=mp->psi[1];
7318 }
7319
7320 @ When we get to this point of the code, |right_type(p)| is either
7321 |given| or |curl| or |open|. If it is |open|, we must have
7322 |left_type(p)=end_cycle| or |left_type(p)=explicit|. In the latter
7323 case, the |open| type is converted to |given|; however, if the
7324 velocity coming into this knot is zero, the |open| type is
7325 converted to a |curl|, since we don't know the incoming direction.
7326
7327 Similarly, |left_type(q)| is either |given| or |curl| or |open| or
7328 |end_cycle|. The |open| possibility is reduced either to |given| or to |curl|.
7329
7330 @<Remove |open| types at the breakpoints@>=
7331 if ( left_type(q)==open ) { 
7332   delx=right_x(q)-x_coord(q); dely=right_y(q)-y_coord(q);
7333   if ( (delx==0)&&(dely==0) ) { 
7334     left_type(q)=curl; left_curl(q)=unity;
7335   } else { 
7336     left_type(q)=given; left_given(q)=mp_n_arg(mp, delx,dely);
7337   }
7338 }
7339 if ( (right_type(p)==open)&&(left_type(p)==explicit) ) { 
7340   delx=x_coord(p)-left_x(p); dely=y_coord(p)-left_y(p);
7341   if ( (delx==0)&&(dely==0) ) { 
7342     right_type(p)=curl; right_curl(p)=unity;
7343   } else { 
7344     right_type(p)=given; right_given(p)=mp_n_arg(mp, delx,dely);
7345   }
7346 }
7347
7348 @ Linear equations need to be solved whenever |n>1|; and also when |n=1|
7349 and exactly one of the breakpoints involves a curl. The simplest case occurs
7350 when |n=1| and there is a curl at both breakpoints; then we simply draw
7351 a straight line.
7352
7353 But before coding up the simple cases, we might as well face the general case,
7354 since we must deal with it sooner or later, and since the general case
7355 is likely to give some insight into the way simple cases can be handled best.
7356
7357 When there is no cycle, the linear equations to be solved form a tridiagonal
7358 system, and we can apply the standard technique of Gaussian elimination
7359 to convert that system to a sequence of equations of the form
7360 $$\theta_0+u_0\theta_1=v_0,\quad
7361 \theta_1+u_1\theta_2=v_1,\quad\ldots,\quad
7362 \theta_{n-1}+u_{n-1}\theta_n=v_{n-1},\quad
7363 \theta_n=v_n.$$
7364 It is possible to do this diagonalization while generating the equations.
7365 Once $\theta_n$ is known, it is easy to determine $\theta_{n-1}$, \dots,
7366 $\theta_1$, $\theta_0$; thus, the equations will be solved.
7367
7368 The procedure is slightly more complex when there is a cycle, but the
7369 basic idea will be nearly the same. In the cyclic case the right-hand
7370 sides will be $v_k+w_k\theta_0$ instead of simply $v_k$, and we will start
7371 the process off with $u_0=v_0=0$, $w_0=1$. The final equation will be not
7372 $\theta_n=v_n$ but $\theta_n+u_n\theta_1=v_n+w_n\theta_0$; an appropriate
7373 ending routine will take account of the fact that $\theta_n=\theta_0$ and
7374 eliminate the $w$'s from the system, after which the solution can be
7375 obtained as before.
7376
7377 When $u_k$, $v_k$, and $w_k$ are being computed, the three pointer
7378 variables |r|, |s|,~|t| will point respectively to knots |k-1|, |k|,
7379 and~|k+1|. The $u$'s and $w$'s are scaled by $2^{28}$, i.e., they are
7380 of type |fraction|; the $\theta$'s and $v$'s are of type |angle|.
7381
7382 @<Glob...@>=
7383 angle *theta; /* values of $\theta_k$ */
7384 fraction *uu; /* values of $u_k$ */
7385 angle *vv; /* values of $v_k$ */
7386 fraction *ww; /* values of $w_k$ */
7387
7388 @ @<Allocate or initialize ...@>=
7389 mp->theta = NULL;
7390 mp->uu = NULL;
7391 mp->vv = NULL;
7392 mp->ww = NULL;
7393
7394 @ @<Dealloc variables@>=
7395 xfree(mp->theta);
7396 xfree(mp->uu);
7397 xfree(mp->vv);
7398 xfree(mp->ww);
7399
7400 @ @<Declare |mp_reallocate| functions@>=
7401 void mp_reallocate_paths (MP mp, int l);
7402
7403 @ @c
7404 void mp_reallocate_paths (MP mp, int l) {
7405   XREALLOC (mp->delta_x, (l+1), scaled);
7406   XREALLOC (mp->delta_y, (l+1), scaled);
7407   XREALLOC (mp->delta,   (l+1), scaled);
7408   XREALLOC (mp->psi,     (l+1), angle);
7409   XREALLOC (mp->theta,   (l+1), angle);
7410   XREALLOC (mp->uu,      (l+1), fraction);
7411   XREALLOC (mp->vv,      (l+1), angle);
7412   XREALLOC (mp->ww,      (l+1), fraction);
7413   mp->path_size = l;
7414 }
7415
7416 @ Our immediate problem is to get the ball rolling by setting up the
7417 first equation or by realizing that no equations are needed, and to fit
7418 this initialization into a framework suitable for the overall computation.
7419
7420 @<Declare the procedure called |solve_choices|@>=
7421 @<Declare subroutines needed by |solve_choices|@>;
7422 void mp_solve_choices (MP mp,pointer p, pointer q, halfword n) {
7423   int k; /* current knot number */
7424   pointer r,s,t; /* registers for list traversal */
7425   @<Other local variables for |solve_choices|@>;
7426   k=0; s=p; r=0;
7427   while (1) { 
7428     t=link(s);
7429     if ( k==0 ) {
7430       @<Get the linear equations started; or |return|
7431         with the control points in place, if linear equations
7432         needn't be solved@>
7433     } else  { 
7434       switch (left_type(s)) {
7435       case end_cycle: case open:
7436         @<Set up equation to match mock curvatures
7437           at $z_k$; then |goto found| with $\theta_n$
7438           adjusted to equal $\theta_0$, if a cycle has ended@>;
7439         break;
7440       case curl:
7441         @<Set up equation for a curl at $\theta_n$
7442           and |goto found|@>;
7443         break;
7444       case given:
7445         @<Calculate the given value of $\theta_n$
7446           and |goto found|@>;
7447         break;
7448       } /* there are no other cases */
7449     }
7450     r=s; s=t; incr(k);
7451   }
7452 FOUND:
7453   @<Finish choosing angles and assigning control points@>;
7454 }
7455
7456 @ On the first time through the loop, we have |k=0| and |r| is not yet
7457 defined. The first linear equation, if any, will have $A_0=B_0=0$.
7458
7459 @<Get the linear equations started...@>=
7460 switch (right_type(s)) {
7461 case given: 
7462   if ( left_type(t)==given ) {
7463     @<Reduce to simple case of two givens  and |return|@>
7464   } else {
7465     @<Set up the equation for a given value of $\theta_0$@>;
7466   }
7467   break;
7468 case curl: 
7469   if ( left_type(t)==curl ) {
7470     @<Reduce to simple case of straight line and |return|@>
7471   } else {
7472     @<Set up the equation for a curl at $\theta_0$@>;
7473   }
7474   break;
7475 case open: 
7476   mp->uu[0]=0; mp->vv[0]=0; mp->ww[0]=fraction_one;
7477   /* this begins a cycle */
7478   break;
7479 } /* there are no other cases */
7480
7481 @ The general equation that specifies equality of mock curvature at $z_k$ is
7482 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7483 as derived above. We want to combine this with the already-derived equation
7484 $\theta_{k-1}+u_{k-1}\theta_k=v_{k-1}+w_{k-1}\theta_0$ in order to obtain
7485 a new equation
7486 $\theta_k+u_k\theta\k=v_k+w_k\theta_0$. This can be done by dividing the
7487 equation
7488 $$(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}
7489     -A_kw_{k-1}\theta_0$$
7490 by $B_k-u_{k-1}A_k+C_k$. The trick is to do this carefully with
7491 fixed-point arithmetic, avoiding the chance of overflow while retaining
7492 suitable precision.
7493
7494 The calculations will be performed in several registers that
7495 provide temporary storage for intermediate quantities.
7496
7497 @<Other local variables for |solve_choices|@>=
7498 fraction aa,bb,cc,ff,acc; /* temporary registers */
7499 scaled dd,ee; /* likewise, but |scaled| */
7500 scaled lt,rt; /* tension values */
7501
7502 @ @<Set up equation to match mock curvatures...@>=
7503 { @<Calculate the values $\\{aa}=A_k/B_k$, $\\{bb}=D_k/C_k$,
7504     $\\{dd}=(3-\alpha_{k-1})d_{k,k+1}$, $\\{ee}=(3-\beta\k)d_{k-1,k}$,
7505     and $\\{cc}=(B_k-u_{k-1}A_k)/B_k$@>;
7506   @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>;
7507   mp->uu[k]=mp_take_fraction(mp, ff,bb);
7508   @<Calculate the values of $v_k$ and $w_k$@>;
7509   if ( left_type(s)==end_cycle ) {
7510     @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>;
7511   }
7512 }
7513
7514 @ Since tension values are never less than 3/4, the values |aa| and
7515 |bb| computed here are never more than 4/5.
7516
7517 @<Calculate the values $\\{aa}=...@>=
7518 if ( abs(right_tension(r))==unity) { 
7519   aa=fraction_half; dd=2*mp->delta[k];
7520 } else { 
7521   aa=mp_make_fraction(mp, unity,3*abs(right_tension(r))-unity);
7522   dd=mp_take_fraction(mp, mp->delta[k],
7523     fraction_three-mp_make_fraction(mp, unity,abs(right_tension(r))));
7524 }
7525 if ( abs(left_tension(t))==unity ){ 
7526   bb=fraction_half; ee=2*mp->delta[k-1];
7527 } else { 
7528   bb=mp_make_fraction(mp, unity,3*abs(left_tension(t))-unity);
7529   ee=mp_take_fraction(mp, mp->delta[k-1],
7530     fraction_three-mp_make_fraction(mp, unity,abs(left_tension(t))));
7531 }
7532 cc=fraction_one-mp_take_fraction(mp, mp->uu[k-1],aa)
7533
7534 @ The ratio to be calculated in this step can be written in the form
7535 $$\beta_k^2\cdot\\{ee}\over\beta_k^2\cdot\\{ee}+\alpha_k^2\cdot
7536   \\{cc}\cdot\\{dd},$$
7537 because of the quantities just calculated. The values of |dd| and |ee|
7538 will not be needed after this step has been performed.
7539
7540 @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>=
7541 dd=mp_take_fraction(mp, dd,cc); lt=abs(left_tension(s)); rt=abs(right_tension(s));
7542 if ( lt!=rt ) { /* $\beta_k^{-1}\ne\alpha_k^{-1}$ */
7543   if ( lt<rt ) { 
7544     ff=mp_make_fraction(mp, lt,rt);
7545     ff=mp_take_fraction(mp, ff,ff); /* $\alpha_k^2/\beta_k^2$ */
7546     dd=mp_take_fraction(mp, dd,ff);
7547   } else { 
7548     ff=mp_make_fraction(mp, rt,lt);
7549     ff=mp_take_fraction(mp, ff,ff); /* $\beta_k^2/\alpha_k^2$ */
7550     ee=mp_take_fraction(mp, ee,ff);
7551   }
7552 }
7553 ff=mp_make_fraction(mp, ee,ee+dd)
7554
7555 @ The value of $u_{k-1}$ will be |<=1| except when $k=1$ and the previous
7556 equation was specified by a curl. In that case we must use a special
7557 method of computation to prevent overflow.
7558
7559 Fortunately, the calculations turn out to be even simpler in this ``hard''
7560 case. The curl equation makes $w_0=0$ and $v_0=-u_0\psi_1$, hence
7561 $-B_1\psi_1-A_1v_0=-(B_1-u_0A_1)\psi_1=-\\{cc}\cdot B_1\psi_1$.
7562
7563 @<Calculate the values of $v_k$ and $w_k$@>=
7564 acc=-mp_take_fraction(mp, mp->psi[k+1],mp->uu[k]);
7565 if ( right_type(r)==curl ) { 
7566   mp->ww[k]=0;
7567   mp->vv[k]=acc-mp_take_fraction(mp, mp->psi[1],fraction_one-ff);
7568 } else { 
7569   ff=mp_make_fraction(mp, fraction_one-ff,cc); /* this is
7570     $B_k/(C_k+B_k-u_{k-1}A_k)<5$ */
7571   acc=acc-mp_take_fraction(mp, mp->psi[k],ff);
7572   ff=mp_take_fraction(mp, ff,aa); /* this is $A_k/(C_k+B_k-u_{k-1}A_k)$ */
7573   mp->vv[k]=acc-mp_take_fraction(mp, mp->vv[k-1],ff);
7574   if ( mp->ww[k-1]==0 ) mp->ww[k]=0;
7575   else mp->ww[k]=-mp_take_fraction(mp, mp->ww[k-1],ff);
7576 }
7577
7578 @ When a complete cycle has been traversed, we have $\theta_k+u_k\theta\k=
7579 v_k+w_k\theta_0$, for |1<=k<=n|. We would like to determine the value of
7580 $\theta_n$ and reduce the system to the form $\theta_k+u_k\theta\k=v_k$
7581 for |0<=k<n|, so that the cyclic case can be finished up just as if there
7582 were no cycle.
7583
7584 The idea in the following code is to observe that
7585 $$\eqalign{\theta_n&=v_n+w_n\theta_0-u_n\theta_1=\cdots\cr
7586 &=v_n+w_n\theta_0-u_n\bigl(v_1+w_1\theta_0-u_1(v_2+\cdots
7587   -u_{n-2}(v_{n-1}+w_{n-1}\theta_0-u_{n-1}\theta_0))\bigr),\cr}$$
7588 so we can solve for $\theta_n=\theta_0$.
7589
7590 @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>=
7591
7592 aa=0; bb=fraction_one; /* we have |k=n| */
7593 do {  decr(k);
7594 if ( k==0 ) k=n;
7595   aa=mp->vv[k]-mp_take_fraction(mp, aa,mp->uu[k]);
7596   bb=mp->ww[k]-mp_take_fraction(mp, bb,mp->uu[k]);
7597 } while (k!=n); /* now $\theta_n=\\{aa}+\\{bb}\cdot\theta_n$ */
7598 aa=mp_make_fraction(mp, aa,fraction_one-bb);
7599 mp->theta[n]=aa; mp->vv[0]=aa;
7600 for (k=1;k<=n-1;k++) {
7601   mp->vv[k]=mp->vv[k]+mp_take_fraction(mp, aa,mp->ww[k]);
7602 }
7603 goto FOUND;
7604 }
7605
7606 @ @d reduce_angle(A) if ( abs((A))>one_eighty_deg ) {
7607   if ( (A)>0 ) (A)=(A)-three_sixty_deg; else (A)=(A)+three_sixty_deg; }
7608
7609 @<Calculate the given value of $\theta_n$...@>=
7610
7611   mp->theta[n]=left_given(s)-mp_n_arg(mp, mp->delta_x[n-1],mp->delta_y[n-1]);
7612   reduce_angle(mp->theta[n]);
7613   goto FOUND;
7614 }
7615
7616 @ @<Set up the equation for a given value of $\theta_0$@>=
7617
7618   mp->vv[0]=right_given(s)-mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7619   reduce_angle(mp->vv[0]);
7620   mp->uu[0]=0; mp->ww[0]=0;
7621 }
7622
7623 @ @<Set up the equation for a curl at $\theta_0$@>=
7624 { cc=right_curl(s); lt=abs(left_tension(t)); rt=abs(right_tension(s));
7625   if ( (rt==unity)&&(lt==unity) )
7626     mp->uu[0]=mp_make_fraction(mp, cc+cc+unity,cc+two);
7627   else 
7628     mp->uu[0]=mp_curl_ratio(mp, cc,rt,lt);
7629   mp->vv[0]=-mp_take_fraction(mp, mp->psi[1],mp->uu[0]); mp->ww[0]=0;
7630 }
7631
7632 @ @<Set up equation for a curl at $\theta_n$...@>=
7633 { cc=left_curl(s); lt=abs(left_tension(s)); rt=abs(right_tension(r));
7634   if ( (rt==unity)&&(lt==unity) )
7635     ff=mp_make_fraction(mp, cc+cc+unity,cc+two);
7636   else 
7637     ff=mp_curl_ratio(mp, cc,lt,rt);
7638   mp->theta[n]=-mp_make_fraction(mp, mp_take_fraction(mp, mp->vv[n-1],ff),
7639     fraction_one-mp_take_fraction(mp, ff,mp->uu[n-1]));
7640   goto FOUND;
7641 }
7642
7643 @ The |curl_ratio| subroutine has three arguments, which our previous notation
7644 encourages us to call $\gamma$, $\alpha^{-1}$, and $\beta^{-1}$. It is
7645 a somewhat tedious program to calculate
7646 $${(3-\alpha)\alpha^2\gamma+\beta^3\over
7647   \alpha^3\gamma+(3-\beta)\beta^2},$$
7648 with the result reduced to 4 if it exceeds 4. (This reduction of curl
7649 is necessary only if the curl and tension are both large.)
7650 The values of $\alpha$ and $\beta$ will be at most~4/3.
7651
7652 @<Declare subroutines needed by |solve_choices|@>=
7653 fraction mp_curl_ratio (MP mp,scaled gamma, scaled a_tension, 
7654                         scaled b_tension) {
7655   fraction alpha,beta,num,denom,ff; /* registers */
7656   alpha=mp_make_fraction(mp, unity,a_tension);
7657   beta=mp_make_fraction(mp, unity,b_tension);
7658   if ( alpha<=beta ) {
7659     ff=mp_make_fraction(mp, alpha,beta); ff=mp_take_fraction(mp, ff,ff);
7660     gamma=mp_take_fraction(mp, gamma,ff);
7661     beta=beta / 010000; /* convert |fraction| to |scaled| */
7662     denom=mp_take_fraction(mp, gamma,alpha)+three-beta;
7663     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7664   } else { 
7665     ff=mp_make_fraction(mp, beta,alpha); ff=mp_take_fraction(mp, ff,ff);
7666     beta=mp_take_fraction(mp, beta,ff) / 010000; /* convert |fraction| to |scaled| */
7667     denom=mp_take_fraction(mp, gamma,alpha)+(ff / 1365)-beta;
7668       /* $1365\approx 2^{12}/3$ */
7669     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7670   }
7671   if ( num>=denom+denom+denom+denom ) return fraction_four;
7672   else return mp_make_fraction(mp, num,denom);
7673 }
7674
7675 @ We're in the home stretch now.
7676
7677 @<Finish choosing angles and assigning control points@>=
7678 for (k=n-1;k>=0;k--) {
7679   mp->theta[k]=mp->vv[k]-mp_take_fraction(mp,mp->theta[k+1],mp->uu[k]);
7680 }
7681 s=p; k=0;
7682 do {  
7683   t=link(s);
7684   mp_n_sin_cos(mp, mp->theta[k]); mp->st=mp->n_sin; mp->ct=mp->n_cos;
7685   mp_n_sin_cos(mp, -mp->psi[k+1]-mp->theta[k+1]); mp->sf=mp->n_sin; mp->cf=mp->n_cos;
7686   mp_set_controls(mp, s,t,k);
7687   incr(k); s=t;
7688 } while (k!=n)
7689
7690 @ The |set_controls| routine actually puts the control points into
7691 a pair of consecutive nodes |p| and~|q|. Global variables are used to
7692 record the values of $\sin\theta$, $\cos\theta$, $\sin\phi$, and
7693 $\cos\phi$ needed in this calculation.
7694
7695 @<Glob...@>=
7696 fraction st;
7697 fraction ct;
7698 fraction sf;
7699 fraction cf; /* sines and cosines */
7700
7701 @ @<Declare subroutines needed by |solve_choices|@>=
7702 void mp_set_controls (MP mp,pointer p, pointer q, integer k) {
7703   fraction rr,ss; /* velocities, divided by thrice the tension */
7704   scaled lt,rt; /* tensions */
7705   fraction sine; /* $\sin(\theta+\phi)$ */
7706   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7707   rr=mp_velocity(mp, mp->st,mp->ct,mp->sf,mp->cf,rt);
7708   ss=mp_velocity(mp, mp->sf,mp->cf,mp->st,mp->ct,lt);
7709   if ( (right_tension(p)<0)||(left_tension(q)<0) ) {
7710     @<Decrease the velocities,
7711       if necessary, to stay inside the bounding triangle@>;
7712   }
7713   right_x(p)=x_coord(p)+mp_take_fraction(mp, 
7714                           mp_take_fraction(mp, mp->delta_x[k],mp->ct)-
7715                           mp_take_fraction(mp, mp->delta_y[k],mp->st),rr);
7716   right_y(p)=y_coord(p)+mp_take_fraction(mp, 
7717                           mp_take_fraction(mp, mp->delta_y[k],mp->ct)+
7718                           mp_take_fraction(mp, mp->delta_x[k],mp->st),rr);
7719   left_x(q)=x_coord(q)-mp_take_fraction(mp, 
7720                          mp_take_fraction(mp, mp->delta_x[k],mp->cf)+
7721                          mp_take_fraction(mp, mp->delta_y[k],mp->sf),ss);
7722   left_y(q)=y_coord(q)-mp_take_fraction(mp, 
7723                          mp_take_fraction(mp, mp->delta_y[k],mp->cf)-
7724                          mp_take_fraction(mp, mp->delta_x[k],mp->sf),ss);
7725   right_type(p)=explicit; left_type(q)=explicit;
7726 }
7727
7728 @ The boundedness conditions $\\{rr}\L\sin\phi\,/\sin(\theta+\phi)$ and
7729 $\\{ss}\L\sin\theta\,/\sin(\theta+\phi)$ are to be enforced if $\sin\theta$,
7730 $\sin\phi$, and $\sin(\theta+\phi)$ all have the same sign. Otherwise
7731 there is no ``bounding triangle.''
7732 @:at_least_}{\&{atleast} primitive@>
7733
7734 @<Decrease the velocities, if necessary...@>=
7735 if (((mp->st>=0)&&(mp->sf>=0))||((mp->st<=0)&&(mp->sf<=0)) ) {
7736   sine=mp_take_fraction(mp, abs(mp->st),mp->cf)+
7737                             mp_take_fraction(mp, abs(mp->sf),mp->ct);
7738   if ( sine>0 ) {
7739     sine=mp_take_fraction(mp, sine,fraction_one+unity); /* safety factor */
7740     if ( right_tension(p)<0 )
7741      if ( mp_ab_vs_cd(mp, abs(mp->sf),fraction_one,rr,sine)<0 )
7742       rr=mp_make_fraction(mp, abs(mp->sf),sine);
7743     if ( left_tension(q)<0 )
7744      if ( mp_ab_vs_cd(mp, abs(mp->st),fraction_one,ss,sine)<0 )
7745       ss=mp_make_fraction(mp, abs(mp->st),sine);
7746   }
7747 }
7748
7749 @ Only the simple cases remain to be handled.
7750
7751 @<Reduce to simple case of two givens and |return|@>=
7752
7753   aa=mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7754   mp_n_sin_cos(mp, right_given(p)-aa); mp->ct=mp->n_cos; mp->st=mp->n_sin;
7755   mp_n_sin_cos(mp, left_given(q)-aa); mp->cf=mp->n_cos; mp->sf=-mp->n_sin;
7756   mp_set_controls(mp, p,q,0); return;
7757 }
7758
7759 @ @<Reduce to simple case of straight line and |return|@>=
7760
7761   right_type(p)=explicit; left_type(q)=explicit;
7762   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7763   if ( rt==unity ) {
7764     if ( mp->delta_x[0]>=0 ) right_x(p)=x_coord(p)+((mp->delta_x[0]+1) / 3);
7765     else right_x(p)=x_coord(p)+((mp->delta_x[0]-1) / 3);
7766     if ( mp->delta_y[0]>=0 ) right_y(p)=y_coord(p)+((mp->delta_y[0]+1) / 3);
7767     else right_y(p)=y_coord(p)+((mp->delta_y[0]-1) / 3);
7768   } else { 
7769     ff=mp_make_fraction(mp, unity,3*rt); /* $\alpha/3$ */
7770     right_x(p)=x_coord(p)+mp_take_fraction(mp, mp->delta_x[0],ff);
7771     right_y(p)=y_coord(p)+mp_take_fraction(mp, mp->delta_y[0],ff);
7772   }
7773   if ( lt==unity ) {
7774     if ( mp->delta_x[0]>=0 ) left_x(q)=x_coord(q)-((mp->delta_x[0]+1) / 3);
7775     else left_x(q)=x_coord(q)-((mp->delta_x[0]-1) / 3);
7776     if ( mp->delta_y[0]>=0 ) left_y(q)=y_coord(q)-((mp->delta_y[0]+1) / 3);
7777     else left_y(q)=y_coord(q)-((mp->delta_y[0]-1) / 3);
7778   } else  { 
7779     ff=mp_make_fraction(mp, unity,3*lt); /* $\beta/3$ */
7780     left_x(q)=x_coord(q)-mp_take_fraction(mp, mp->delta_x[0],ff);
7781     left_y(q)=y_coord(q)-mp_take_fraction(mp, mp->delta_y[0],ff);
7782   }
7783   return;
7784 }
7785
7786 @* \[19] Measuring paths.
7787 \MP's \&{llcorner}, \&{lrcorner}, \&{ulcorner}, and \&{urcorner} operators
7788 allow the user to measure the bounding box of anything that can go into a
7789 picture.  It's easy to get rough bounds on the $x$ and $y$ extent of a path
7790 by just finding the bounding box of the knots and the control points. We
7791 need a more accurate version of the bounding box, but we can still use the
7792 easy estimate to save time by focusing on the interesting parts of the path.
7793
7794 @ Computing an accurate bounding box involves a theme that will come up again
7795 and again. Given a Bernshte{\u\i}n polynomial
7796 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
7797 $$B(z_0,z_1,\ldots,z_n;t)=\sum_k{n\choose k}t^k(1-t)^{n-k}z_k,$$
7798 we can conveniently bisect its range as follows:
7799
7800 \smallskip
7801 \textindent{1)} Let $z_k^{(0)}=z_k$, for |0<=k<=n|.
7802
7803 \smallskip
7804 \textindent{2)} Let $z_k^{(j+1)}={1\over2}(z_k^{(j)}+z\k^{(j)})$, for
7805 |0<=k<n-j|, for |0<=j<n|.
7806
7807 \smallskip\noindent
7808 Then
7809 $$B(z_0,z_1,\ldots,z_n;t)=B(z_0^{(0)},z_0^{(1)},\ldots,z_0^{(n)};2t)
7810  =B(z_0^{(n)},z_1^{(n-1)},\ldots,z_n^{(0)};2t-1).$$
7811 This formula gives us the coefficients of polynomials to use over the ranges
7812 $0\L t\L{1\over2}$ and ${1\over2}\L t\L1$.
7813
7814 @ Now here's a subroutine that's handy for all sorts of path computations:
7815 Given a quadratic polynomial $B(a,b,c;t)$, the |crossing_point| function
7816 returns the unique |fraction| value |t| between 0 and~1 at which
7817 $B(a,b,c;t)$ changes from positive to negative, or returns
7818 |t=fraction_one+1| if no such value exists. If |a<0| (so that $B(a,b,c;t)$
7819 is already negative at |t=0|), |crossing_point| returns the value zero.
7820
7821 @d no_crossing {  return (fraction_one+1); }
7822 @d one_crossing { return fraction_one; }
7823 @d zero_crossing { return 0; }
7824 @d mp_crossing_point(M,A,B,C) mp_do_crossing_point(A,B,C)
7825
7826 @c fraction mp_do_crossing_point (integer a, integer b, integer c) {
7827   integer d; /* recursive counter */
7828   integer x,xx,x0,x1,x2; /* temporary registers for bisection */
7829   if ( a<0 ) zero_crossing;
7830   if ( c>=0 ) { 
7831     if ( b>=0 ) {
7832       if ( c>0 ) { no_crossing; }
7833       else if ( (a==0)&&(b==0) ) { no_crossing;} 
7834       else { one_crossing; } 
7835     }
7836     if ( a==0 ) zero_crossing;
7837   } else if ( a==0 ) {
7838     if ( b<=0 ) zero_crossing;
7839   }
7840   @<Use bisection to find the crossing point, if one exists@>;
7841 }
7842
7843 @ The general bisection method is quite simple when $n=2$, hence
7844 |crossing_point| does not take much time. At each stage in the
7845 recursion we have a subinterval defined by |l| and~|j| such that
7846 $B(a,b,c;2^{-l}(j+t))=B(x_0,x_1,x_2;t)$, and we want to ``zero in'' on
7847 the subinterval where $x_0\G0$ and $\min(x_1,x_2)<0$.
7848
7849 It is convenient for purposes of calculation to combine the values
7850 of |l| and~|j| in a single variable $d=2^l+j$, because the operation
7851 of bisection then corresponds simply to doubling $d$ and possibly
7852 adding~1. Furthermore it proves to be convenient to modify
7853 our previous conventions for bisection slightly, maintaining the
7854 variables $X_0=2^lx_0$, $X_1=2^l(x_0-x_1)$, and $X_2=2^l(x_1-x_2)$.
7855 With these variables the conditions $x_0\ge0$ and $\min(x_1,x_2)<0$ are
7856 equivalent to $\max(X_1,X_1+X_2)>X_0\ge0$.
7857
7858 The following code maintains the invariant relations
7859 $0\L|x0|<\max(|x1|,|x1|+|x2|)$,
7860 $\vert|x1|\vert<2^{30}$, $\vert|x2|\vert<2^{30}$;
7861 it has been constructed in such a way that no arithmetic overflow
7862 will occur if the inputs satisfy
7863 $a<2^{30}$, $\vert a-b\vert<2^{30}$, and $\vert b-c\vert<2^{30}$.
7864
7865 @<Use bisection to find the crossing point...@>=
7866 d=1; x0=a; x1=a-b; x2=b-c;
7867 do {  
7868   x=half(x1+x2);
7869   if ( x1-x0>x0 ) { 
7870     x2=x; x0+=x0; d+=d;  
7871   } else { 
7872     xx=x1+x-x0;
7873     if ( xx>x0 ) { 
7874       x2=x; x0+=x0; d+=d;
7875     }  else { 
7876       x0=x0-xx;
7877       if ( x<=x0 ) { if ( x+x2<=x0 ) no_crossing; }
7878       x1=x; d=d+d+1;
7879     }
7880   }
7881 } while (d<fraction_one);
7882 return (d-fraction_one)
7883
7884 @ Here is a routine that computes the $x$ or $y$ coordinate of the point on
7885 a cubic corresponding to the |fraction| value~|t|.
7886
7887 It is convenient to define a \.{WEB} macro |t_of_the_way| such that
7888 |t_of_the_way(a,b)| expands to |a-(a-b)*t|, i.e., to |t[a,b]|.
7889
7890 @d t_of_the_way(A,B) ((A)-mp_take_fraction(mp,(A)-(B),t))
7891
7892 @c scaled mp_eval_cubic (MP mp,pointer p, pointer q, fraction t) {
7893   scaled x1,x2,x3; /* intermediate values */
7894   x1=t_of_the_way(knot_coord(p),right_coord(p));
7895   x2=t_of_the_way(right_coord(p),left_coord(q));
7896   x3=t_of_the_way(left_coord(q),knot_coord(q));
7897   x1=t_of_the_way(x1,x2);
7898   x2=t_of_the_way(x2,x3);
7899   return t_of_the_way(x1,x2);
7900 }
7901
7902 @ The actual bounding box information is stored in global variables.
7903 Since it is convenient to address the $x$ and $y$ information
7904 separately, we define arrays indexed by |x_code..y_code| and use
7905 macros to give them more convenient names.
7906
7907 @<Types...@>=
7908 enum {
7909   mp_x_code=0, /* index for |minx| and |maxx| */
7910   mp_y_code /* index for |miny| and |maxy| */
7911 };
7912
7913
7914 @d minx mp->bbmin[mp_x_code]
7915 @d maxx mp->bbmax[mp_x_code]
7916 @d miny mp->bbmin[mp_y_code]
7917 @d maxy mp->bbmax[mp_y_code]
7918
7919 @<Glob...@>=
7920 scaled bbmin[mp_y_code+1];
7921 scaled bbmax[mp_y_code+1]; 
7922 /* the result of procedures that compute bounding box information */
7923
7924 @ Now we're ready for the key part of the bounding box computation.
7925 The |bound_cubic| procedure updates |bbmin[c]| and |bbmax[c]| based on
7926 $$B(\hbox{|knot_coord(p)|}, \hbox{|right_coord(p)|},
7927     \hbox{|left_coord(q)|}, \hbox{|knot_coord(q)|};t)
7928 $$
7929 for $0<t\le1$.  In other words, the procedure adjusts the bounds to
7930 accommodate |knot_coord(q)| and any extremes over the range $0<t<1$.
7931 The |c| parameter is |x_code| or |y_code|.
7932
7933 @c void mp_bound_cubic (MP mp,pointer p, pointer q, small_number c) {
7934   boolean wavy; /* whether we need to look for extremes */
7935   scaled del1,del2,del3,del,dmax; /* proportional to the control
7936      points of a quadratic derived from a cubic */
7937   fraction t,tt; /* where a quadratic crosses zero */
7938   scaled x; /* a value that |bbmin[c]| and |bbmax[c]| must accommodate */
7939   x=knot_coord(q);
7940   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
7941   @<Check the control points against the bounding box and set |wavy:=true|
7942     if any of them lie outside@>;
7943   if ( wavy ) {
7944     del1=right_coord(p)-knot_coord(p);
7945     del2=left_coord(q)-right_coord(p);
7946     del3=knot_coord(q)-left_coord(q);
7947     @<Scale up |del1|, |del2|, and |del3| for greater accuracy;
7948       also set |del| to the first nonzero element of |(del1,del2,del3)|@>;
7949     if ( del<0 ) {
7950       negate(del1); negate(del2); negate(del3);
7951     };
7952     t=mp_crossing_point(mp, del1,del2,del3);
7953     if ( t<fraction_one ) {
7954       @<Test the extremes of the cubic against the bounding box@>;
7955     }
7956   }
7957 }
7958
7959 @ @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>=
7960 if ( x<mp->bbmin[c] ) mp->bbmin[c]=x;
7961 if ( x>mp->bbmax[c] ) mp->bbmax[c]=x
7962
7963 @ @<Check the control points against the bounding box and set...@>=
7964 wavy=true;
7965 if ( mp->bbmin[c]<=right_coord(p) )
7966   if ( right_coord(p)<=mp->bbmax[c] )
7967     if ( mp->bbmin[c]<=left_coord(q) )
7968       if ( left_coord(q)<=mp->bbmax[c] )
7969         wavy=false
7970
7971 @ If |del1=del2=del3=0|, it's impossible to obey the title of this
7972 section. We just set |del=0| in that case.
7973
7974 @<Scale up |del1|, |del2|, and |del3| for greater accuracy...@>=
7975 if ( del1!=0 ) del=del1;
7976 else if ( del2!=0 ) del=del2;
7977 else del=del3;
7978 if ( del!=0 ) {
7979   dmax=abs(del1);
7980   if ( abs(del2)>dmax ) dmax=abs(del2);
7981   if ( abs(del3)>dmax ) dmax=abs(del3);
7982   while ( dmax<fraction_half ) {
7983     dmax+=dmax; del1+=del1; del2+=del2; del3+=del3;
7984   }
7985 }
7986
7987 @ Since |crossing_point| has tried to choose |t| so that
7988 $B(|del1|,|del2|,|del3|;\tau)$ crosses zero at $\tau=|t|$ with negative
7989 slope, the value of |del2| computed below should not be positive.
7990 But rounding error could make it slightly positive in which case we
7991 must cut it to zero to avoid confusion.
7992
7993 @<Test the extremes of the cubic against the bounding box@>=
7994
7995   x=mp_eval_cubic(mp, p,q,t);
7996   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
7997   del2=t_of_the_way(del2,del3);
7998     /* now |0,del2,del3| represent the derivative on the remaining interval */
7999   if ( del2>0 ) del2=0;
8000   tt=mp_crossing_point(mp, 0,-del2,-del3);
8001   if ( tt<fraction_one ) {
8002     @<Test the second extreme against the bounding box@>;
8003   }
8004 }
8005
8006 @ @<Test the second extreme against the bounding box@>=
8007 {
8008    x=mp_eval_cubic(mp, p,q,t_of_the_way(tt,fraction_one));
8009   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8010 }
8011
8012 @ Finding the bounding box of a path is basically a matter of applying
8013 |bound_cubic| twice for each pair of adjacent knots.
8014
8015 @c void mp_path_bbox (MP mp,pointer h) {
8016   pointer p,q; /* a pair of adjacent knots */
8017    minx=x_coord(h); miny=y_coord(h);
8018   maxx=minx; maxy=miny;
8019   p=h;
8020   do {  
8021     if ( right_type(p)==endpoint ) return;
8022     q=link(p);
8023     mp_bound_cubic(mp, x_loc(p),x_loc(q),mp_x_code);
8024     mp_bound_cubic(mp, y_loc(p),y_loc(q),mp_y_code);
8025     p=q;
8026   } while (p!=h);
8027 }
8028
8029 @ Another important way to measure a path is to find its arc length.  This
8030 is best done by using the general bisection algorithm to subdivide the path
8031 until obtaining ``well behaved'' subpaths whose arc lengths can be approximated
8032 by simple means.
8033
8034 Since the arc length is the integral with respect to time of the magnitude of
8035 the velocity, it is natural to use Simpson's rule for the approximation.
8036 @^Simpson's rule@>
8037 If $\dot B(t)$ is the spline velocity, Simpson's rule gives
8038 $$ \vb\dot B(0)\vb + 4\vb\dot B({1\over2})\vb + \vb\dot B(1)\vb \over 6 $$
8039 for the arc length of a path of length~1.  For a cubic spline
8040 $B(z_0,z_1,z_2,z_3;t)$, the time derivative $\dot B(t)$ is
8041 $3B(dz_0,dz_1,dz_2;t)$, where $dz_i=z_{i+1}-z_i$.  Hence the arc length
8042 approximation is
8043 $$ {\vb dz_0\vb \over 2} + 2\vb dz_{02}\vb + {\vb dz_2\vb \over 2}, $$
8044 where
8045 $$ dz_{02}={1\over2}\left({dz_0+dz_1\over 2}+{dz_1+dz_2\over 2}\right)$$
8046 is the result of the bisection algorithm.
8047
8048 @ The remaining problem is how to decide when a subpath is ``well behaved.''
8049 This could be done via the theoretical error bound for Simpson's rule,
8050 @^Simpson's rule@>
8051 but this is impractical because it requires an estimate of the fourth
8052 derivative of the quantity being integrated.  It is much easier to just perform
8053 a bisection step and see how much the arc length estimate changes.  Since the
8054 error for Simpson's rule is proportional to the fourth power of the sample
8055 spacing, the remaining error is typically about $1\over16$ of the amount of
8056 the change.  We say ``typically'' because the error has a pseudo-random behavior
8057 that could cause the two estimates to agree when each contain large errors.
8058
8059 To protect against disasters such as undetected cusps, the bisection process
8060 should always continue until all the $dz_i$ vectors belong to a single
8061 $90^\circ$ sector.  This ensures that no point on the spline can have velocity
8062 less than 70\% of the minimum of $\vb dz_0\vb$, $\vb dz_1\vb$ and $\vb dz_2\vb$.
8063 If such a spline happens to produce an erroneous arc length estimate that
8064 is little changed by bisection, the amount of the error is likely to be fairly
8065 small.  We will try to arrange things so that freak accidents of this type do
8066 not destroy the inverse relationship between the \&{arclength} and
8067 \&{arctime} operations.
8068 @:arclength_}{\&{arclength} primitive@>
8069 @:arctime_}{\&{arctime} primitive@>
8070
8071 @ The \&{arclength} and \&{arctime} operations are both based on a recursive
8072 @^recursion@>
8073 function that finds the arc length of a cubic spline given $dz_0$, $dz_1$,
8074 $dz_2$. This |arc_test| routine also takes an arc length goal |a_goal| and
8075 returns the time when the arc length reaches |a_goal| if there is such a time.
8076 Thus the return value is either an arc length less than |a_goal| or, if the
8077 arc length would be at least |a_goal|, it returns a time value decreased by
8078 |two|.  This allows the caller to use the sign of the result to distinguish
8079 between arc lengths and time values.  On certain types of overflow, it is
8080 possible for |a_goal| and the result of |arc_test| both to be |el_gordo|.
8081 Otherwise, the result is always less than |a_goal|.
8082
8083 Rather than halving the control point coordinates on each recursive call to
8084 |arc_test|, it is better to keep them proportional to velocity on the original
8085 curve and halve the results instead.  This means that recursive calls can
8086 potentially use larger error tolerances in their arc length estimates.  How
8087 much larger depends on to what extent the errors behave as though they are
8088 independent of each other.  To save computing time, we use optimistic assumptions
8089 and increase the tolerance by a factor of about $\sqrt2$ for each recursive
8090 call.
8091
8092 In addition to the tolerance parameter, |arc_test| should also have parameters
8093 for ${1\over3}\vb\dot B(0)\vb$, ${2\over3}\vb\dot B({1\over2})\vb$, and
8094 ${1\over3}\vb\dot B(1)\vb$.  These quantities are relatively expensive to compute
8095 and they are needed in different instances of |arc_test|.
8096
8097 @c @t\4@>@<Declare subroutines needed by |arc_test|@>;
8098 scaled mp_arc_test (MP mp, scaled dx0, scaled dy0, scaled dx1, scaled dy1, 
8099                     scaled dx2, scaled dy2, scaled  v0, scaled v02, 
8100                     scaled v2, scaled a_goal, scaled tol) {
8101   boolean simple; /* are the control points confined to a $90^\circ$ sector? */
8102   scaled dx01, dy01, dx12, dy12, dx02, dy02;  /* bisection results */
8103   scaled v002, v022;
8104     /* twice the velocity magnitudes at $t={1\over4}$ and $t={3\over4}$ */
8105   scaled arc; /* best arc length estimate before recursion */
8106   @<Other local variables in |arc_test|@>;
8107   @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,
8108     |dx2|, |dy2|@>;
8109   @<Initialize |v002|, |v022|, and the arc length estimate |arc|; if it overflows
8110     set |arc_test| and |return|@>;
8111   @<Test if the control points are confined to one quadrant or rotating them
8112     $45^\circ$ would put them in one quadrant.  Then set |simple| appropriately@>;
8113   if ( simple && (abs(arc-v02-halfp(v0+v2)) <= tol) ) {
8114     if ( arc < a_goal ) {
8115       return arc;
8116     } else {
8117        @<Estimate when the arc length reaches |a_goal| and set |arc_test| to
8118          that time minus |two|@>;
8119     }
8120   } else {
8121     @<Use one or two recursive calls to compute the |arc_test| function@>;
8122   }
8123 }
8124
8125 @ The |tol| value should by multiplied by $\sqrt 2$ before making recursive
8126 calls, but $1.5$ is an adequate approximation.  It is best to avoid using
8127 |make_fraction| in this inner loop.
8128 @^inner loop@>
8129
8130 @<Use one or two recursive calls to compute the |arc_test| function@>=
8131
8132   @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is as
8133     large as possible@>;
8134   tol = tol + halfp(tol);
8135   a = mp_arc_test(mp, dx0,dy0, dx01,dy01, dx02,dy02, v0, v002, 
8136                   halfp(v02), a_new, tol);
8137   if ( a<0 )  {
8138      return (-halfp(two-a));
8139   } else { 
8140     @<Update |a_new| to reduce |a_new+a_aux| by |a|@>;
8141     b = mp_arc_test(mp, dx02,dy02, dx12,dy12, dx2,dy2,
8142                     halfp(v02), v022, v2, a_new, tol);
8143     if ( b<0 )  
8144       return (-halfp(-b) - half_unit);
8145     else  
8146       return (a + half(b-a));
8147   }
8148 }
8149
8150 @ @<Other local variables in |arc_test|@>=
8151 scaled a,b; /* results of recursive calls */
8152 scaled a_new,a_aux; /* the sum of these gives the |a_goal| */
8153
8154 @ @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is...@>=
8155 a_aux = el_gordo - a_goal;
8156 if ( a_goal > a_aux ) {
8157   a_aux = a_goal - a_aux;
8158   a_new = el_gordo;
8159 } else { 
8160   a_new = a_goal + a_goal;
8161   a_aux = 0;
8162 }
8163
8164 @ There is no need to maintain |a_aux| at this point so we use it as a temporary
8165 to force the additions and subtractions to be done in an order that avoids
8166 overflow.
8167
8168 @<Update |a_new| to reduce |a_new+a_aux| by |a|@>=
8169 if ( a > a_aux ) {
8170   a_aux = a_aux - a;
8171   a_new = a_new + a_aux;
8172 }
8173
8174 @ This code assumes all {\it dx} and {\it dy} variables have magnitude less than
8175 |fraction_four|.  To simplify the rest of the |arc_test| routine, we strengthen
8176 this assumption by requiring the norm of each $({\it dx},{\it dy})$ pair to obey
8177 this bound.  Note that recursive calls will maintain this invariant.
8178
8179 @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,...@>=
8180 dx01 = half(dx0 + dx1);
8181 dx12 = half(dx1 + dx2);
8182 dx02 = half(dx01 + dx12);
8183 dy01 = half(dy0 + dy1);
8184 dy12 = half(dy1 + dy2);
8185 dy02 = half(dy01 + dy12)
8186
8187 @ We should be careful to keep |arc<el_gordo| so that calling |arc_test| with
8188 |a_goal=el_gordo| is guaranteed to yield the arc length.
8189
8190 @<Initialize |v002|, |v022|, and the arc length estimate |arc|;...@>=
8191 v002 = mp_pyth_add(mp, dx01+half(dx0+dx02), dy01+half(dy0+dy02));
8192 v022 = mp_pyth_add(mp, dx12+half(dx02+dx2), dy12+half(dy02+dy2));
8193 tmp = halfp(v02+2);
8194 arc1 = v002 + half(halfp(v0+tmp) - v002);
8195 arc = v022 + half(halfp(v2+tmp) - v022);
8196 if ( (arc < el_gordo-arc1) )  {
8197   arc = arc+arc1;
8198 } else { 
8199   mp->arith_error = true;
8200   if ( a_goal==el_gordo )  return (el_gordo);
8201   else return (-two);
8202 }
8203
8204 @ @<Other local variables in |arc_test|@>=
8205 scaled tmp, tmp2; /* all purpose temporary registers */
8206 scaled arc1; /* arc length estimate for the first half */
8207
8208 @ @<Test if the control points are confined to one quadrant or rotating...@>=
8209 simple = ((dx0>=0) && (dx1>=0) && (dx2>=0)) ||
8210          ((dx0<=0) && (dx1<=0) && (dx2<=0));
8211 if ( simple )
8212   simple = ((dy0>=0) && (dy1>=0) && (dy2>=0)) ||
8213            ((dy0<=0) && (dy1<=0) && (dy2<=0));
8214 if ( ! simple ) {
8215   simple = ((dx0>=dy0) && (dx1>=dy1) && (dx2>=dy2)) ||
8216            ((dx0<=dy0) && (dx1<=dy1) && (dx2<=dy2));
8217   if ( simple ) 
8218     simple = ((-dx0>=dy0) && (-dx1>=dy1) && (-dx2>=dy2)) ||
8219              ((-dx0<=dy0) && (-dx1<=dy1) && (-dx2<=dy2));
8220 }
8221
8222 @ Since Simpson's rule is based on approximating the integrand by a parabola,
8223 @^Simpson's rule@>
8224 it is appropriate to use the same approximation to decide when the integral
8225 reaches the intermediate value |a_goal|.  At this point
8226 $$\eqalign{
8227     {\vb\dot B(0)\vb\over 3} &= \hbox{|v0|}, \qquad
8228     {\vb\dot B({1\over4})\vb\over 3} = {\hbox{|v002|}\over 2}, \qquad
8229     {\vb\dot B({1\over2})\vb\over 3} = {\hbox{|v02|}\over 2}, \cr
8230     {\vb\dot B({3\over4})\vb\over 3} &= {\hbox{|v022|}\over 2}, \qquad
8231     {\vb\dot B(1)\vb\over 3} = \hbox{|v2|} \cr
8232 }
8233 $$
8234 and
8235 $$ {\vb\dot B(t)\vb\over 3} \approx
8236   \cases{B\left(\hbox{|v0|},
8237       \hbox{|v002|}-{1\over 2}\hbox{|v0|}-{1\over 4}\hbox{|v02|},
8238       {1\over 2}\hbox{|v02|}; 2t \right)&
8239     if $t\le{1\over 2}$\cr
8240   B\left({1\over 2}\hbox{|v02|},
8241       \hbox{|v022|}-{1\over 4}\hbox{|v02|}-{1\over 2}\hbox{|v2|},
8242       \hbox{|v2|}; 2t-1 \right)&
8243     if $t\ge{1\over 2}$.\cr}
8244  \eqno (*)
8245 $$
8246 We can integrate $\vb\dot B(t)\vb$ by using
8247 $$\int 3B(a,b,c;\tau)\,dt =
8248   {B(0,a,a+b,a+b+c;\tau) + {\rm constant} \over {d\tau\over dt}}.
8249 $$
8250
8251 This construction allows us to find the time when the arc length reaches
8252 |a_goal| by solving a cubic equation of the form
8253 $$ B(0,a,a+b,a+b+c;\tau) = x, $$
8254 where $\tau$ is $2t$ or $2t+1$, $x$ is |a_goal| or |a_goal-arc1|, and $a$, $b$,
8255 and $c$ are the Bernshte{\u\i}n coefficients from $(*)$ divided by
8256 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
8257 $d\tau\over dt$.  We shall define a function |solve_rising_cubic| that finds
8258 $\tau$ given $a$, $b$, $c$, and $x$.
8259
8260 @<Estimate when the arc length reaches |a_goal| and set |arc_test| to...@>=
8261
8262   tmp = (v02 + 2) / 4;
8263   if ( a_goal<=arc1 ) {
8264     tmp2 = halfp(v0);
8265     return 
8266       (halfp(mp_solve_rising_cubic(mp, tmp2, arc1-tmp2-tmp, tmp, a_goal))- two);
8267   } else { 
8268     tmp2 = halfp(v2);
8269     return ((half_unit - two) +
8270       halfp(mp_solve_rising_cubic(mp, tmp, arc-arc1-tmp-tmp2, tmp2, a_goal-arc1)));
8271   }
8272 }
8273
8274 @ Here is the |solve_rising_cubic| routine that finds the time~$t$ when
8275 $$ B(0, a, a+b, a+b+c; t) = x. $$
8276 This routine is based on |crossing_point| but is simplified by the
8277 assumptions that $B(a,b,c;t)\ge0$ for $0\le t\le1$ and that |0<=x<=a+b+c|.
8278 If rounding error causes this condition to be violated slightly, we just ignore
8279 it and proceed with binary search.  This finds a time when the function value
8280 reaches |x| and the slope is positive.
8281
8282 @<Declare subroutines needed by |arc_test|@>=
8283 scaled mp_solve_rising_cubic (MP mp,scaled a, scaled b,  scaled c, scaled x) {
8284   scaled ab, bc, ac; /* bisection results */
8285   integer t; /* $2^k+q$ where unscaled answer is in $[q2^{-k},(q+1)2^{-k})$ */
8286   integer xx; /* temporary for updating |x| */
8287   if ( (a<0) || (c<0) ) mp_confusion(mp, "rising?");
8288 @:this can't happen rising?}{\quad rising?@>
8289   if ( x<=0 ) {
8290         return 0;
8291   } else if ( x >= a+b+c ) {
8292     return unity;
8293   } else { 
8294     t = 1;
8295     @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than
8296       |el_gordo div 3|@>;
8297     do {  
8298       t+=t;
8299       @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>;
8300       xx = x - a - ab - ac;
8301       if ( xx < -x ) { x+=x; b=ab; c=ac;  }
8302       else { x = x + xx;  a=ac; b=mp->bc; t = t+1; };
8303     } while (t < unity);
8304     return (t - unity);
8305   }
8306 }
8307
8308 @ @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>=
8309 ab = half(a+b);
8310 bc = half(b+c);
8311 ac = half(ab+bc)
8312
8313 @ @d one_third_el_gordo 05252525252 /* upper bound on |a|, |b|, and |c| */
8314
8315 @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than...@>=
8316 while ((a>one_third_el_gordo)||(b>one_third_el_gordo)||(c>one_third_el_gordo)) { 
8317   a = halfp(a);
8318   b = half(b);
8319   c = halfp(c);
8320   x = halfp(x);
8321 }
8322
8323 @ It is convenient to have a simpler interface to |arc_test| that requires no
8324 unnecessary arguments and ensures that each $({\it dx},{\it dy})$ pair has
8325 length less than |fraction_four|.
8326
8327 @d arc_tol   16  /* quit when change in arc length estimate reaches this */
8328
8329 @c scaled mp_do_arc_test (MP mp,scaled dx0, scaled dy0, scaled dx1, 
8330                           scaled dy1, scaled dx2, scaled dy2, scaled a_goal) {
8331   scaled v0,v1,v2; /* length of each $({\it dx},{\it dy})$ pair */
8332   scaled v02; /* twice the norm of the quadratic at $t={1\over2}$ */
8333   v0 = mp_pyth_add(mp, dx0,dy0);
8334   v1 = mp_pyth_add(mp, dx1,dy1);
8335   v2 = mp_pyth_add(mp, dx2,dy2);
8336   if ( (v0>=fraction_four) || (v1>=fraction_four) || (v2>=fraction_four) ) { 
8337     mp->arith_error = true;
8338     if ( a_goal==el_gordo )  return el_gordo;
8339     else return (-two);
8340   } else { 
8341     v02 = mp_pyth_add(mp, dx1+half(dx0+dx2), dy1+half(dy0+dy2));
8342     return (mp_arc_test(mp, dx0,dy0, dx1,dy1, dx2,dy2,
8343                                  v0, v02, v2, a_goal, arc_tol));
8344   }
8345 }
8346
8347 @ Now it is easy to find the arc length of an entire path.
8348
8349 @c scaled mp_get_arc_length (MP mp,pointer h) {
8350   pointer p,q; /* for traversing the path */
8351   scaled a,a_tot; /* current and total arc lengths */
8352   a_tot = 0;
8353   p = h;
8354   while ( right_type(p)!=endpoint ){ 
8355     q = link(p);
8356     a = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8357       left_x(q)-right_x(p), left_y(q)-right_y(p),
8358       x_coord(q)-left_x(q), y_coord(q)-left_y(q), el_gordo);
8359     a_tot = mp_slow_add(mp, a, a_tot);
8360     if ( q==h ) break;  else p=q;
8361   }
8362   check_arith;
8363   return a_tot;
8364 }
8365
8366 @ The inverse operation of finding the time on a path~|h| when the arc length
8367 reaches some value |arc0| can also be accomplished via |do_arc_test|.  Some care
8368 is required to handle very large times or negative times on cyclic paths.  For
8369 non-cyclic paths, |arc0| values that are negative or too large cause
8370 |get_arc_time| to return 0 or the length of path~|h|.
8371
8372 If |arc0| is greater than the arc length of a cyclic path~|h|, the result is a
8373 time value greater than the length of the path.  Since it could be much greater,
8374 we must be prepared to compute the arc length of path~|h| and divide this into
8375 |arc0| to find how many multiples of the length of path~|h| to add.
8376
8377 @c scaled mp_get_arc_time (MP mp,pointer h, scaled  arc0) {
8378   pointer p,q; /* for traversing the path */
8379   scaled t_tot; /* accumulator for the result */
8380   scaled t; /* the result of |do_arc_test| */
8381   scaled arc; /* portion of |arc0| not used up so far */
8382   integer n; /* number of extra times to go around the cycle */
8383   if ( arc0<0 ) {
8384     @<Deal with a negative |arc0| value and |return|@>;
8385   }
8386   if ( arc0==el_gordo ) decr(arc0);
8387   t_tot = 0;
8388   arc = arc0;
8389   p = h;
8390   while ( (right_type(p)!=endpoint) && (arc>0) ) {
8391     q = link(p);
8392     t = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8393       left_x(q)-right_x(p), left_y(q)-right_y(p),
8394       x_coord(q)-left_x(q), y_coord(q)-left_y(q), arc);
8395     @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>;
8396     if ( q==h ) {
8397       @<Update |t_tot| and |arc| to avoid going around the cyclic
8398         path too many times but set |arith_error:=true| and |goto done| on
8399         overflow@>;
8400     }
8401     p = q;
8402   }
8403   check_arith;
8404   return t_tot;
8405 }
8406
8407 @ @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>=
8408 if ( t<0 ) { t_tot = t_tot + t + two;  arc = 0;  }
8409 else { t_tot = t_tot + unity;  arc = arc - t;  }
8410
8411 @ @<Deal with a negative |arc0| value and |return|@>=
8412
8413   if ( left_type(h)==endpoint ) {
8414     t_tot=0;
8415   } else { 
8416     p = mp_htap_ypoc(mp, h);
8417     t_tot = -mp_get_arc_time(mp, p, -arc0);
8418     mp_toss_knot_list(mp, p);
8419   }
8420   check_arith;
8421   return t_tot;
8422 }
8423
8424 @ @<Update |t_tot| and |arc| to avoid going around the cyclic...@>=
8425 if ( arc>0 ) { 
8426   n = arc / (arc0 - arc);
8427   arc = arc - n*(arc0 - arc);
8428   if ( t_tot > el_gordo / (n+1) ) { 
8429     mp->arith_error = true;
8430     t_tot = el_gordo;
8431     break;
8432   }
8433   t_tot = (n + 1)*t_tot;
8434 }
8435
8436 @* \[20] Data structures for pens.
8437 A Pen in \MP\ can be either elliptical or polygonal.  Elliptical pens result
8438 in \ps\ \&{stroke} commands, while anything drawn with a polygonal pen is
8439 @:stroke}{\&{stroke} command@>
8440 converted into an area fill as described in the next part of this program.
8441 The mathematics behind this process is based on simple aspects of the theory
8442 of tracings developed by Leo Guibas, Lyle Ramshaw, and Jorge Stolfi
8443 [``A kinematic framework for computational geometry,'' Proc.\ IEEE Symp.\
8444 Foundations of Computer Science {\bf 24} (1983), 100--111].
8445
8446 Polygonal pens are created from paths via \MP's \&{makepen} primitive.
8447 @:makepen_}{\&{makepen} primitive@>
8448 This path representation is almost sufficient for our purposes except that
8449 a pen path should always be a convex polygon with the vertices in
8450 counter-clockwise order.
8451 Since we will need to scan pen polygons both forward and backward, a pen
8452 should be represented as a doubly linked ring of knot nodes.  There is
8453 room for the extra back pointer because we do not need the
8454 |left_type| or |right_type| fields.  In fact, we don't need the |left_x|,
8455 |left_y|, |right_x|, or |right_y| fields either but we leave these alone
8456 so that certain procedures can operate on both pens and paths.  In particular,
8457 pens can be copied using |copy_path| and recycled using |toss_knot_list|.
8458
8459 @d knil info
8460   /* this replaces the |left_type| and |right_type| fields in a pen knot */
8461
8462 @ The |make_pen| procedure turns a path into a pen by initializing
8463 the |knil| pointers and making sure the knots form a convex polygon.
8464 Thus each cubic in the given path becomes a straight line and the control
8465 points are ignored.  If the path is not cyclic, the ends are connected by a
8466 straight line.
8467
8468 @d copy_pen(A) mp_make_pen(mp, mp_copy_path(mp, (A)),false)
8469
8470 @c @<Declare a function called |convex_hull|@>;
8471 pointer mp_make_pen (MP mp,pointer h, boolean need_hull) {
8472   pointer p,q; /* two consecutive knots */
8473   q=h;
8474   do {  
8475     p=q; q=link(q);
8476     knil(q)=p;
8477   } while (q!=h);
8478   if ( need_hull ){ 
8479     h=mp_convex_hull(mp, h);
8480     @<Make sure |h| isn't confused with an elliptical pen@>;
8481   }
8482   return h;
8483 }
8484
8485 @ The only information required about an elliptical pen is the overall
8486 transformation that has been applied to the original \&{pencircle}.
8487 @:pencircle_}{\&{pencircle} primitive@>
8488 Since it suffices to keep track of how the three points $(0,0)$, $(1,0)$,
8489 and $(0,1)$ are transformed, an elliptical pen can be stored in a single
8490 knot node and transformed as if it were a path.
8491
8492 @d pen_is_elliptical(A) ((A)==link((A)))
8493
8494 @c pointer mp_get_pen_circle (MP mp,scaled diam) {
8495   pointer h; /* the knot node to return */
8496   h=mp_get_node(mp, knot_node_size);
8497   link(h)=h; knil(h)=h;
8498   originator(h)=program_code;
8499   x_coord(h)=0; y_coord(h)=0;
8500   left_x(h)=diam; left_y(h)=0;
8501   right_x(h)=0; right_y(h)=diam;
8502   return h;
8503 }
8504
8505 @ If the polygon being returned by |make_pen| has only one vertex, it will
8506 be interpreted as an elliptical pen.  This is no problem since a degenerate
8507 polygon can equally well be thought of as a degenerate ellipse.  We need only
8508 initialize the |left_x|, |left_y|, |right_x|, and |right_y| fields.
8509
8510 @<Make sure |h| isn't confused with an elliptical pen@>=
8511 if ( pen_is_elliptical( h) ){ 
8512   left_x(h)=x_coord(h); left_y(h)=y_coord(h);
8513   right_x(h)=x_coord(h); right_y(h)=y_coord(h);
8514 }
8515
8516 @ We have to cheat a little here but most operations on pens only use
8517 the first three words in each knot node.
8518 @^data structure assumptions@>
8519
8520 @<Initialize a pen at |test_pen| so that it fits in nine words@>=
8521 x_coord(test_pen)=-half_unit;
8522 y_coord(test_pen)=0;
8523 x_coord(test_pen+3)=half_unit;
8524 y_coord(test_pen+3)=0;
8525 x_coord(test_pen+6)=0;
8526 y_coord(test_pen+6)=unity;
8527 link(test_pen)=test_pen+3;
8528 link(test_pen+3)=test_pen+6;
8529 link(test_pen+6)=test_pen;
8530 knil(test_pen)=test_pen+6;
8531 knil(test_pen+3)=test_pen;
8532 knil(test_pen+6)=test_pen+3
8533
8534 @ Printing a polygonal pen is very much like printing a path
8535
8536 @<Declare subroutines for printing expressions@>=
8537 void mp_pr_pen (MP mp,pointer h) {
8538   pointer p,q; /* for list traversal */
8539   if ( pen_is_elliptical(h) ) {
8540     @<Print the elliptical pen |h|@>;
8541   } else { 
8542     p=h;
8543     do {  
8544       mp_print_two(mp, x_coord(p),y_coord(p));
8545       mp_print_nl(mp, " .. ");
8546       @<Advance |p| making sure the links are OK and |return| if there is
8547         a problem@>;
8548      } while (p!=h);
8549      mp_print(mp, "cycle");
8550   }
8551 }
8552
8553 @ @<Advance |p| making sure the links are OK and |return| if there is...@>=
8554 q=link(p);
8555 if ( (q==null) || (knil(q)!=p) ) { 
8556   mp_print_nl(mp, "???"); return; /* this won't happen */
8557 @.???@>
8558 }
8559 p=q
8560
8561 @ @<Print the elliptical pen |h|@>=
8562
8563 mp_print(mp, "pencircle transformed (");
8564 mp_print_scaled(mp, x_coord(h));
8565 mp_print_char(mp, ',');
8566 mp_print_scaled(mp, y_coord(h));
8567 mp_print_char(mp, ',');
8568 mp_print_scaled(mp, left_x(h)-x_coord(h));
8569 mp_print_char(mp, ',');
8570 mp_print_scaled(mp, right_x(h)-x_coord(h));
8571 mp_print_char(mp, ',');
8572 mp_print_scaled(mp, left_y(h)-y_coord(h));
8573 mp_print_char(mp, ',');
8574 mp_print_scaled(mp, right_y(h)-y_coord(h));
8575 mp_print_char(mp, ')');
8576 }
8577
8578 @ Here us another version of |pr_pen| that prints the pen as a diagnostic
8579 message.
8580
8581 @<Declare subroutines for printing expressions@>=
8582 void mp_print_pen (MP mp,pointer h, char *s, boolean nuline) { 
8583   mp_print_diagnostic(mp, "Pen",s,nuline); mp_print_ln(mp);
8584 @.Pen at line...@>
8585   mp_pr_pen(mp, h);
8586   mp_end_diagnostic(mp, true);
8587 }
8588
8589 @ Making a polygonal pen into a path involves restoring the |left_type| and
8590 |right_type| fields and setting the control points so as to make a polygonal
8591 path.
8592
8593 @c 
8594 void mp_make_path (MP mp,pointer h) {
8595   pointer p; /* for traversing the knot list */
8596   small_number k; /* a loop counter */
8597   @<Other local variables in |make_path|@>;
8598   if ( pen_is_elliptical(h) ) {
8599     @<Make the elliptical pen |h| into a path@>;
8600   } else { 
8601     p=h;
8602     do {  
8603       left_type(p)=explicit;
8604       right_type(p)=explicit;
8605       @<copy the coordinates of knot |p| into its control points@>;
8606        p=link(p);
8607     } while (p!=h);
8608   }
8609 }
8610
8611 @ @<copy the coordinates of knot |p| into its control points@>=
8612 left_x(p)=x_coord(p);
8613 left_y(p)=y_coord(p);
8614 right_x(p)=x_coord(p);
8615 right_y(p)=y_coord(p)
8616
8617 @ We need an eight knot path to get a good approximation to an ellipse.
8618
8619 @<Make the elliptical pen |h| into a path@>=
8620
8621   @<Extract the transformation parameters from the elliptical pen~|h|@>;
8622   p=h;
8623   for (k=0;k<=7;k++ ) { 
8624     @<Initialize |p| as the |k|th knot of a circle of unit diameter,
8625       transforming it appropriately@>;
8626     if ( k==7 ) link(p)=h;  else link(p)=mp_get_node(mp, knot_node_size);
8627     p=link(p);
8628   }
8629 }
8630
8631 @ @<Extract the transformation parameters from the elliptical pen~|h|@>=
8632 center_x=x_coord(h);
8633 center_y=y_coord(h);
8634 width_x=left_x(h)-center_x;
8635 width_y=left_y(h)-center_y;
8636 height_x=right_x(h)-center_x;
8637 height_y=right_y(h)-center_y
8638
8639 @ @<Other local variables in |make_path|@>=
8640 scaled center_x,center_y; /* translation parameters for an elliptical pen */
8641 scaled width_x,width_y; /* the effect of a unit change in $x$ */
8642 scaled height_x,height_y; /* the effect of a unit change in $y$ */
8643 scaled dx,dy; /* the vector from knot |p| to its right control point */
8644 integer kk;
8645   /* |k| advanced $270^\circ$ around the ring (cf. $\sin\theta=\cos(\theta+270)$) */
8646
8647 @ The only tricky thing here are the tables |half_cos| and |d_cos| used to
8648 find the point $k/8$ of the way around the circle and the direction vector
8649 to use there.
8650
8651 @<Initialize |p| as the |k|th knot of a circle of unit diameter,...@>=
8652 kk=(k+6)% 8;
8653 x_coord(p)=center_x+mp_take_fraction(mp, mp->half_cos[k],width_x)
8654            +mp_take_fraction(mp, mp->half_cos[kk],height_x);
8655 y_coord(p)=center_y+mp_take_fraction(mp, mp->half_cos[k],width_y)
8656            +mp_take_fraction(mp, mp->half_cos[kk],height_y);
8657 dx=-mp_take_fraction(mp, mp->d_cos[kk],width_x)
8658    +mp_take_fraction(mp, mp->d_cos[k],height_x);
8659 dy=-mp_take_fraction(mp, mp->d_cos[kk],width_y)
8660    +mp_take_fraction(mp, mp->d_cos[k],height_y);
8661 right_x(p)=x_coord(p)+dx;
8662 right_y(p)=y_coord(p)+dy;
8663 left_x(p)=x_coord(p)-dx;
8664 left_y(p)=y_coord(p)-dy;
8665 left_type(p)=explicit;
8666 right_type(p)=explicit;
8667 originator(p)=program_code
8668
8669 @ @<Glob...@>=
8670 fraction half_cos[8]; /* ${1\over2}\cos(45k)$ */
8671 fraction d_cos[8]; /* a magic constant times $\cos(45k)$ */
8672
8673 @ The magic constant for |d_cos| is the distance between $({1\over2},0)$ and
8674 $({1\over4}\sqrt2,{1\over4}\sqrt2)$ times the result of the |velocity|
8675 function for $\theta=\phi=22.5^\circ$.  This comes out to be
8676 $$ d = {\sqrt{2-\sqrt2}\over 3+3\cos22.5^\circ}
8677   \approx 0.132608244919772.
8678 $$
8679
8680 @<Set init...@>=
8681 mp->half_cos[0]=fraction_half;
8682 mp->half_cos[1]=94906266; /* $2^{26}\sqrt2\approx94906265.62$ */
8683 mp->half_cos[2]=0;
8684 mp->d_cos[0]=35596755; /* $2^{28}d\approx35596754.69$ */
8685 mp->d_cos[1]=25170707; /* $2^{27}\sqrt2\,d\approx25170706.63$ */
8686 mp->d_cos[2]=0;
8687 for (k=3;k<= 4;k++ ) { 
8688   mp->half_cos[k]=-mp->half_cos[4-k];
8689   mp->d_cos[k]=-mp->d_cos[4-k];
8690 }
8691 for (k=5;k<= 7;k++ ) { 
8692   mp->half_cos[k]=mp->half_cos[8-k];
8693   mp->d_cos[k]=mp->d_cos[8-k];
8694 }
8695
8696 @ The |convex_hull| function forces a pen polygon to be convex when it is
8697 returned by |make_pen| and after any subsequent transformation where rounding
8698 error might allow the convexity to be lost.
8699 The convex hull algorithm used here is described by F.~P. Preparata and
8700 M.~I. Shamos [{\sl Computational Geometry}, Springer-Verlag, 1985].
8701
8702 @<Declare a function called |convex_hull|@>=
8703 @<Declare a procedure called |move_knot|@>;
8704 pointer mp_convex_hull (MP mp,pointer h) { /* Make a polygonal pen convex */
8705   pointer l,r; /* the leftmost and rightmost knots */
8706   pointer p,q; /* knots being scanned */
8707   pointer s; /* the starting point for an upcoming scan */
8708   scaled dx,dy; /* a temporary pointer */
8709   if ( pen_is_elliptical(h) ) {
8710      return h;
8711   } else { 
8712     @<Set |l| to the leftmost knot in polygon~|h|@>;
8713     @<Set |r| to the rightmost knot in polygon~|h|@>;
8714     if ( l!=r ) { 
8715       s=link(r);
8716       @<Find any knots on the path from |l| to |r| above the |l|-|r| line and
8717         move them past~|r|@>;
8718       @<Find any knots on the path from |s| to |l| below the |l|-|r| line and
8719         move them past~|l|@>;
8720       @<Sort the path from |l| to |r| by increasing $x$@>;
8721       @<Sort the path from |r| to |l| by decreasing $x$@>;
8722     }
8723     if ( l!=link(l) ) {
8724       @<Do a Gramm scan and remove vertices where there is no left turn@>;
8725     }
8726     return l;
8727   }
8728 }
8729
8730 @ All comparisons are done primarily on $x$ and secondarily on $y$.
8731
8732 @<Set |l| to the leftmost knot in polygon~|h|@>=
8733 l=h;
8734 p=link(h);
8735 while ( p!=h ) { 
8736   if ( x_coord(p)<=x_coord(l) )
8737     if ( (x_coord(p)<x_coord(l)) || (y_coord(p)<y_coord(l)) )
8738       l=p;
8739   p=link(p);
8740 }
8741
8742 @ @<Set |r| to the rightmost knot in polygon~|h|@>=
8743 r=h;
8744 p=link(h);
8745 while ( p!=h ) { 
8746   if ( x_coord(p)>=x_coord(r) )
8747     if ( (x_coord(p)>x_coord(r)) || (y_coord(p)>y_coord(r)) )
8748       r=p;
8749   p=link(p);
8750 }
8751
8752 @ @<Find any knots on the path from |l| to |r| above the |l|-|r| line...@>=
8753 dx=x_coord(r)-x_coord(l);
8754 dy=y_coord(r)-y_coord(l);
8755 p=link(l);
8756 while ( p!=r ) { 
8757   q=link(p);
8758   if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))>0 )
8759     mp_move_knot(mp, p, r);
8760   p=q;
8761 }
8762
8763 @ The |move_knot| procedure removes |p| from a doubly linked list and inserts
8764 it after |q|.
8765
8766 @ @<Declare a procedure called |move_knot|@>=
8767 void mp_move_knot (MP mp,pointer p, pointer q) { 
8768   link(knil(p))=link(p);
8769   knil(link(p))=knil(p);
8770   knil(p)=q;
8771   link(p)=link(q);
8772   link(q)=p;
8773   knil(link(p))=p;
8774 }
8775
8776 @ @<Find any knots on the path from |s| to |l| below the |l|-|r| line...@>=
8777 p=s;
8778 while ( p!=l ) { 
8779   q=link(p);
8780   if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))<0 )
8781     mp_move_knot(mp, p,l);
8782   p=q;
8783 }
8784
8785 @ The list is likely to be in order already so we just do linear insertions.
8786 Secondary comparisons on $y$ ensure that the sort is consistent with the
8787 choice of |l| and |r|.
8788
8789 @<Sort the path from |l| to |r| by increasing $x$@>=
8790 p=link(l);
8791 while ( p!=r ) { 
8792   q=knil(p);
8793   while ( x_coord(q)>x_coord(p) ) q=knil(q);
8794   while ( x_coord(q)==x_coord(p) ) {
8795     if ( y_coord(q)>y_coord(p) ) q=knil(q); else break;
8796   }
8797   if ( q==knil(p) ) p=link(p);
8798   else { p=link(p); mp_move_knot(mp, knil(p),q); };
8799 }
8800
8801 @ @<Sort the path from |r| to |l| by decreasing $x$@>=
8802 p=link(r);
8803 while ( p!=l ){ 
8804   q=knil(p);
8805   while ( x_coord(q)<x_coord(p) ) q=knil(q);
8806   while ( x_coord(q)==x_coord(p) ) {
8807     if ( y_coord(q)<y_coord(p) ) q=knil(q); else break;
8808   }
8809   if ( q==knil(p) ) p=link(p);
8810   else { p=link(p); mp_move_knot(mp, knil(p),q); };
8811 }
8812
8813 @ The condition involving |ab_vs_cd| tests if there is not a left turn
8814 at knot |q|.  There usually will be a left turn so we streamline the case
8815 where the |then| clause is not executed.
8816
8817 @<Do a Gramm scan and remove vertices where there...@>=
8818
8819 p=l; q=link(l);
8820 while (1) { 
8821   dx=x_coord(q)-x_coord(p);
8822   dy=y_coord(q)-y_coord(p);
8823   p=q; q=link(q);
8824   if ( p==l ) break;
8825   if ( p!=r )
8826     if ( mp_ab_vs_cd(mp, dx,y_coord(q)-y_coord(p),dy,x_coord(q)-x_coord(p))<=0 ) {
8827       @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>;
8828     }
8829   }
8830 }
8831
8832 @ @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>=
8833
8834 s=knil(p);
8835 mp_free_node(mp, p,knot_node_size);
8836 link(s)=q; knil(q)=s;
8837 if ( s==l ) p=s;
8838 else { p=knil(s); q=s; };
8839 }
8840
8841 @ The |find_offset| procedure sets global variables |(cur_x,cur_y)| to the
8842 offset associated with the given direction |(x,y)|.  If two different offsets
8843 apply, it chooses one of them.
8844
8845 @c 
8846 void mp_find_offset (MP mp,scaled x, scaled y, pointer h) {
8847   pointer p,q; /* consecutive knots */
8848   scaled wx,wy,hx,hy;
8849   /* the transformation matrix for an elliptical pen */
8850   fraction xx,yy; /* untransformed offset for an elliptical pen */
8851   fraction d; /* a temporary register */
8852   if ( pen_is_elliptical(h) ) {
8853     @<Find the offset for |(x,y)| on the elliptical pen~|h|@>
8854   } else { 
8855     q=h;
8856     do {  
8857       p=q; q=link(q);
8858     } while (! mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)>=0);
8859     do {  
8860       p=q; q=link(q);
8861     } while (! mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)<=0);
8862     mp->cur_x=x_coord(p);
8863     mp->cur_y=y_coord(p);
8864   }
8865 }
8866
8867 @ @<Glob...@>=
8868 scaled cur_x;
8869 scaled cur_y; /* all-purpose return value registers */
8870
8871 @ @<Find the offset for |(x,y)| on the elliptical pen~|h|@>=
8872 if ( (x==0) && (y==0) ) {
8873   mp->cur_x=x_coord(h); mp->cur_y=y_coord(h);  
8874 } else { 
8875   @<Find the non-constant part of the transformation for |h|@>;
8876   while ( (abs(x)<fraction_half) && (abs(y)<fraction_half) ){ 
8877     x+=x; y+=y;  
8878   };
8879   @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the
8880     untransformed version of |(x,y)|@>;
8881   mp->cur_x=x_coord(h)+mp_take_fraction(mp, xx,wx)+mp_take_fraction(mp, yy,hx);
8882   mp->cur_y=y_coord(h)+mp_take_fraction(mp, xx,wy)+mp_take_fraction(mp, yy,hy);
8883 }
8884
8885 @ @<Find the non-constant part of the transformation for |h|@>=
8886 wx=left_x(h)-x_coord(h);
8887 wy=left_y(h)-y_coord(h);
8888 hx=right_x(h)-x_coord(h);
8889 hy=right_y(h)-y_coord(h)
8890
8891 @ @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the...@>=
8892 yy=-(mp_take_fraction(mp, x,hy)+mp_take_fraction(mp, y,-hx));
8893 xx=mp_take_fraction(mp, x,-wy)+mp_take_fraction(mp, y,wx);
8894 d=mp_pyth_add(mp, xx,yy);
8895 if ( d>0 ) { 
8896   xx=half(mp_make_fraction(mp, xx,d));
8897   yy=half(mp_make_fraction(mp, yy,d));
8898 }
8899
8900 @ Finding the bounding box of a pen is easy except if the pen is elliptical.
8901 But we can handle that case by just calling |find_offset| twice.  The answer
8902 is stored in the global variables |minx|, |maxx|, |miny|, and |maxy|.
8903
8904 @c 
8905 void mp_pen_bbox (MP mp,pointer h) {
8906   pointer p; /* for scanning the knot list */
8907   if ( pen_is_elliptical(h) ) {
8908     @<Find the bounding box of an elliptical pen@>;
8909   } else { 
8910     minx=x_coord(h); maxx=minx;
8911     miny=y_coord(h); maxy=miny;
8912     p=link(h);
8913     while ( p!=h ) {
8914       if ( x_coord(p)<minx ) minx=x_coord(p);
8915       if ( y_coord(p)<miny ) miny=y_coord(p);
8916       if ( x_coord(p)>maxx ) maxx=x_coord(p);
8917       if ( y_coord(p)>maxy ) maxy=y_coord(p);
8918       p=link(p);
8919     }
8920   }
8921 }
8922
8923 @ @<Find the bounding box of an elliptical pen@>=
8924
8925 mp_find_offset(mp, 0,fraction_one,h);
8926 maxx=mp->cur_x;
8927 minx=2*x_coord(h)-mp->cur_x;
8928 mp_find_offset(mp, -fraction_one,0,h);
8929 maxy=mp->cur_y;
8930 miny=2*y_coord(h)-mp->cur_y;
8931 }
8932
8933 @* \[21] Edge structures.
8934 Now we come to \MP's internal scheme for representing pictures.
8935 The representation is very different from \MF's edge structures
8936 because \MP\ pictures contain \ps\ graphics objects instead of pixel
8937 images.  However, the basic idea is somewhat similar in that shapes
8938 are represented via their boundaries.
8939
8940 The main purpose of edge structures is to keep track of graphical objects
8941 until it is time to translate them into \ps.  Since \MP\ does not need to
8942 know anything about an edge structure other than how to translate it into
8943 \ps\ and how to find its bounding box, edge structures can be just linked
8944 lists of graphical objects.  \MP\ has no easy way to determine whether
8945 two such objects overlap, but it suffices to draw the first one first and
8946 let the second one overwrite it if necessary.
8947
8948 @ Let's consider the types of graphical objects one at a time.
8949 First of all, a filled contour is represented by a eight-word node.  The first
8950 word contains |type| and |link| fields, and the next six words contain a
8951 pointer to a cyclic path and the value to use for \ps' \&{currentrgbcolor}
8952 parameter.  If a pen is used for filling |pen_p|, |ljoin_val| and |miterlim_val|
8953 give the relevant information.
8954
8955 @d path_p(A) link((A)+1)
8956   /* a pointer to the path that needs filling */
8957 @d pen_p(A) info((A)+1)
8958   /* a pointer to the pen to fill or stroke with */
8959 @d color_model(A) type((A)+2) /*  the color model  */
8960 @d obj_red_loc(A) ((A)+3)  /* the first of three locations for the color */
8961 @d obj_cyan_loc obj_red_loc  /* the first of four locations for the color */
8962 @d obj_grey_loc obj_red_loc  /* the location for the color */
8963 @d red_val(A) mp->mem[(A)+3].sc
8964   /* the red component of the color in the range $0\ldots1$ */
8965 @d cyan_val red_val
8966 @d grey_val red_val
8967 @d green_val(A) mp->mem[(A)+4].sc
8968   /* the green component of the color in the range $0\ldots1$ */
8969 @d magenta_val green_val
8970 @d blue_val(A) mp->mem[(A)+5].sc
8971   /* the blue component of the color in the range $0\ldots1$ */
8972 @d yellow_val blue_val
8973 @d black_val(A) mp->mem[(A)+6].sc
8974   /* the blue component of the color in the range $0\ldots1$ */
8975 @d ljoin_val(A) name_type((A))  /* the value of \&{linejoin} */
8976 @:linejoin_}{\&{linejoin} primitive@>
8977 @d miterlim_val(A) mp->mem[(A)+7].sc  /* the value of \&{miterlimit} */
8978 @:miterlimit_}{\&{miterlimit} primitive@>
8979 @d obj_color_part(A) mp->mem[(A)+3-red_part].sc
8980   /* interpret an object pointer that has been offset by |red_part..blue_part| */
8981 @d pre_script(A) mp->mem[(A)+8].hh.lh
8982 @d post_script(A) mp->mem[(A)+8].hh.rh
8983 @d fill_node_size 9
8984 @d fill_code 1
8985
8986 @c 
8987 pointer mp_new_fill_node (MP mp,pointer p) {
8988   /* make a fill node for cyclic path |p| and color black */
8989   pointer t; /* the new node */
8990   t=mp_get_node(mp, fill_node_size);
8991   type(t)=fill_code;
8992   path_p(t)=p;
8993   pen_p(t)=null; /* |null| means don't use a pen */
8994   red_val(t)=0;
8995   green_val(t)=0;
8996   blue_val(t)=0;
8997   black_val(t)=0;
8998   color_model(t)=uninitialized_model;
8999   pre_script(t)=null;
9000   post_script(t)=null;
9001   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9002   return t;
9003 }
9004
9005 @ @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>=
9006 if ( mp->internal[linejoin]>unity ) ljoin_val(t)=2;
9007 else if ( mp->internal[linejoin]>0 ) ljoin_val(t)=1;
9008 else ljoin_val(t)=0;
9009 if ( mp->internal[miterlimit]<unity )
9010   miterlim_val(t)=unity;
9011 else
9012   miterlim_val(t)=mp->internal[miterlimit]
9013
9014 @ A stroked path is represented by an eight-word node that is like a filled
9015 contour node except that it contains the current \&{linecap} value, a scale
9016 factor for the dash pattern, and a pointer that is non-null if the stroke
9017 is to be dashed.  The purpose of the scale factor is to allow a picture to
9018 be transformed without touching the picture that |dash_p| points to.
9019
9020 @d dash_p(A) link((A)+9)
9021   /* a pointer to the edge structure that gives the dash pattern */
9022 @d lcap_val(A) type((A)+9)
9023   /* the value of \&{linecap} */
9024 @:linecap_}{\&{linecap} primitive@>
9025 @d dash_scale(A) mp->mem[(A)+10].sc /* dash lengths are scaled by this factor */
9026 @d stroked_node_size 11
9027 @d stroked_code 2
9028
9029 @c 
9030 pointer mp_new_stroked_node (MP mp,pointer p) {
9031   /* make a stroked node for path |p| with |pen_p(p)| temporarily |null| */
9032   pointer t; /* the new node */
9033   t=mp_get_node(mp, stroked_node_size);
9034   type(t)=stroked_code;
9035   path_p(t)=p; pen_p(t)=null;
9036   dash_p(t)=null;
9037   dash_scale(t)=unity;
9038   red_val(t)=0;
9039   green_val(t)=0;
9040   blue_val(t)=0;
9041   black_val(t)=0;
9042   color_model(t)=uninitialized_model;
9043   pre_script(t)=null;
9044   post_script(t)=null;
9045   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9046   if ( mp->internal[linecap]>unity ) lcap_val(t)=2;
9047   else if ( mp->internal[linecap]>0 ) lcap_val(t)=1;
9048   else lcap_val(t)=0;
9049   return t;
9050 }
9051
9052 @ When a dashed line is computed in a transformed coordinate system, the dash
9053 lengths get scaled like the pen shape and we need to compensate for this.  Since
9054 there is no unique scale factor for an arbitrary transformation, we use the
9055 the square root of the determinant.  The properties of the determinant make it
9056 easier to maintain the |dash_scale|.  The computation is fairly straight-forward
9057 except for the initialization of the scale factor |s|.  The factor of 64 is
9058 needed because |square_rt| scales its result by $2^8$ while we need $2^{14}$
9059 to counteract the effect of |take_fraction|.
9060
9061 @<Declare subroutines needed by |print_edges|@>=
9062 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) {
9063   scaled maxabs; /* $max(|a|,|b|,|c|,|d|)$ */
9064   integer s; /* amount by which the result of |square_rt| needs to be scaled */
9065   @<Initialize |maxabs|@>;
9066   s=64;
9067   while ( (maxabs<fraction_one) && (s>1) ){ 
9068     a+=a; b+=b; c+=c; d+=d;
9069     maxabs+=maxabs; s=halfp(s);
9070   }
9071   return s*mp_square_rt(mp, abs(mp_take_fraction(mp, a,d)-mp_take_fraction(mp, b,c)));
9072 }
9073 @#
9074 scaled mp_get_pen_scale (MP mp,pointer p) { 
9075   return mp_sqrt_det(mp, 
9076     left_x(p)-x_coord(p), right_x(p)-x_coord(p),
9077     left_y(p)-y_coord(p), right_y(p)-y_coord(p));
9078 }
9079
9080 @ @<Initialize |maxabs|@>=
9081 maxabs=abs(a);
9082 if ( abs(b)>maxabs ) maxabs=abs(b);
9083 if ( abs(c)>maxabs ) maxabs=abs(c);
9084 if ( abs(d)>maxabs ) maxabs=abs(d)
9085
9086 @ When a picture contains text, this is represented by a fourteen-word node
9087 where the color information and |type| and |link| fields are augmented by
9088 additional fields that describe the text and  how it is transformed.
9089 The |path_p| and |pen_p| pointers are replaced by a number that identifies
9090 the font and a string number that gives the text to be displayed.
9091 The |width|, |height|, and |depth| fields
9092 give the dimensions of the text at its design size, and the remaining six
9093 words give a transformation to be applied to the text.  The |new_text_node|
9094 function initializes everything to default values so that the text comes out
9095 black with its reference point at the origin.
9096
9097 @d text_p(A) link((A)+1)  /* a string pointer for the text to display */
9098 @d font_n(A) info((A)+1)  /* the font number */
9099 @d width_val(A) mp->mem[(A)+7].sc  /* unscaled width of the text */
9100 @d height_val(A) mp->mem[(A)+9].sc  /* unscaled height of the text */
9101 @d depth_val(A) mp->mem[(A)+10].sc  /* unscaled depth of the text */
9102 @d text_tx_loc(A) ((A)+11)
9103   /* the first of six locations for transformation parameters */
9104 @d tx_val(A) mp->mem[(A)+11].sc  /* $x$ shift amount */
9105 @d ty_val(A) mp->mem[(A)+12].sc  /* $y$ shift amount */
9106 @d txx_val(A) mp->mem[(A)+13].sc  /* |txx| transformation parameter */
9107 @d txy_val(A) mp->mem[(A)+14].sc  /* |txy| transformation parameter */
9108 @d tyx_val(A) mp->mem[(A)+15].sc  /* |tyx| transformation parameter */
9109 @d tyy_val(A) mp->mem[(A)+16].sc  /* |tyy| transformation parameter */
9110 @d text_trans_part(A) mp->mem[(A)+11-x_part].sc
9111     /* interpret a text node ponter that has been offset by |x_part..yy_part| */
9112 @d text_node_size 17
9113 @d text_code 3
9114
9115 @c @<Declare text measuring subroutines@>;
9116 pointer mp_new_text_node (MP mp,char *f,str_number s) {
9117   /* make a text node for font |f| and text string |s| */
9118   pointer t; /* the new node */
9119   t=mp_get_node(mp, text_node_size);
9120   type(t)=text_code;
9121   text_p(t)=s;
9122   font_n(t)=mp_find_font(mp, f); /* this identifies the font */
9123   red_val(t)=0;
9124   green_val(t)=0;
9125   blue_val(t)=0;
9126   black_val(t)=0;
9127   color_model(t)=uninitialized_model;
9128   pre_script(t)=null;
9129   post_script(t)=null;
9130   tx_val(t)=0; ty_val(t)=0;
9131   txx_val(t)=unity; txy_val(t)=0;
9132   tyx_val(t)=0; tyy_val(t)=unity;
9133   mp_set_text_box(mp, t); /* this finds the bounding box */
9134   return t;
9135 }
9136
9137 @ The last two types of graphical objects that can occur in an edge structure
9138 are clipping paths and \&{setbounds} paths.  These are slightly more difficult
9139 @:set_bounds_}{\&{setbounds} primitive@>
9140 to implement because we must keep track of exactly what is being clipped or
9141 bounded when pictures get merged together.  For this reason, each clipping or
9142 \&{setbounds} operation is represented by a pair of nodes:  first comes a
9143 two-word node whose |path_p| gives the relevant path, then there is the list
9144 of objects to clip or bound followed by a two-word node whose second word is
9145 unused.
9146
9147 Using at least two words for each graphical object node allows them all to be
9148 allocated and deallocated similarly with a global array |gr_object_size| to
9149 give the size in words for each object type.
9150
9151 @d start_clip_size 2
9152 @d start_bounds_size 2
9153 @d stop_clip_size 2 /* the second word is not used here */
9154 @d stop_bounds_size 2 /* the second word is not used here */
9155 @#
9156 @d stop_type(A) ((A)+2)
9157   /* matching |type| for |start_clip_code| or |start_bounds_code| */
9158 @d has_color(A) (type((A))<mp_start_clip_code)
9159   /* does a graphical object have color fields? */
9160 @d has_pen(A) (type((A))<text_code)
9161   /* does a graphical object have a |pen_p| field? */
9162 @d is_start_or_stop(A) (type((A))>=mp_start_clip_code)
9163 @d is_stop(A) (type((A))>=mp_stop_clip_code)
9164
9165 @<Types...@>=
9166 enum {
9167  mp_start_clip_code=4, /* |type| of a node that starts clipping */
9168  mp_start_bounds_code, /* |type| of a node that gives a \&{setbounds} path */
9169  mp_stop_clip_code, /* |type| of a node that stops clipping */
9170  mp_stop_bounds_code /* |type| of a node that stops \&{setbounds} */
9171 };
9172
9173 @ @c 
9174 pointer mp_new_bounds_node (MP mp,pointer p, small_number  c) {
9175   /* make a node of type |c| where |p| is the clipping or \&{setbounds} path */
9176   pointer t; /* the new node */
9177   t=mp_get_node(mp, mp->gr_object_size[c]);
9178   type(t)=c;
9179   path_p(t)=p;
9180   return t;
9181 };
9182
9183 @ We need an array to keep track of the sizes of graphical objects.
9184
9185 @<Glob...@>=
9186 small_number gr_object_size[mp_stop_bounds_code+1];
9187
9188 @ @<Set init...@>=
9189 mp->gr_object_size[fill_code]=fill_node_size;
9190 mp->gr_object_size[stroked_code]=stroked_node_size;
9191 mp->gr_object_size[text_code]=text_node_size;
9192 mp->gr_object_size[mp_start_clip_code]=start_clip_size;
9193 mp->gr_object_size[mp_stop_clip_code]=stop_clip_size;
9194 mp->gr_object_size[mp_start_bounds_code]=start_bounds_size;
9195 mp->gr_object_size[mp_stop_bounds_code]=stop_bounds_size;
9196
9197 @ All the essential information in an edge structure is encoded as a linked list
9198 of graphical objects as we have just seen, but it is helpful to add some
9199 redundant information.  A single edge structure might be used as a dash pattern
9200 many times, and it would be nice to avoid scanning the same structure
9201 repeatedly.  Thus, an edge structure known to be a suitable dash pattern
9202 has a header that gives a list of dashes in a sorted order designed for rapid
9203 translation into \ps.
9204
9205 Each dash is represented by a three-word node containing the initial and final
9206 $x$~coordinates as well as the usual |link| field.  The |link| fields points to
9207 the dash node with the next higher $x$-coordinates and the final link points
9208 to a special location called |null_dash|.  (There should be no overlap between
9209 dashes).  Since the $y$~coordinate of the dash pattern is needed to determine
9210 the period of repetition, this needs to be stored in the edge header along
9211 with a pointer to the list of dash nodes.
9212
9213 @d start_x(A) mp->mem[(A)+1].sc  /* the starting $x$~coordinate in a dash node */
9214 @d stop_x(A) mp->mem[(A)+2].sc  /* the ending $x$~coordinate in a dash node */
9215 @d dash_node_size 3
9216 @d dash_list link
9217   /* in an edge header this points to the first dash node */
9218 @d dash_y(A) mp->mem[(A)+1].sc  /* $y$ value for the dash list in an edge header */
9219
9220 @ It is also convenient for an edge header to contain the bounding
9221 box information needed by the \&{llcorner} and \&{urcorner} operators
9222 so that this does not have to be recomputed unnecessarily.  This is done by
9223 adding fields for the $x$~and $y$ extremes as well as a pointer that indicates
9224 how far the bounding box computation has gotten.  Thus if the user asks for
9225 the bounding box and then adds some more text to the picture before asking
9226 for more bounding box information, the second computation need only look at
9227 the additional text.
9228
9229 When the bounding box has not been computed, the |bblast| pointer points
9230 to a dummy link at the head of the graphical object list while the |minx_val|
9231 and |miny_val| fields contain |el_gordo| and the |maxx_val| and |maxy_val|
9232 fields contain |-el_gordo|.
9233
9234 Since the bounding box of pictures containing objects of type
9235 |mp_start_bounds_code| depends on the value of \&{truecorners}, the bounding box
9236 @:true_corners_}{\&{truecorners} primitive@>
9237 data might not be valid for all values of this parameter.  Hence, the |bbtype|
9238 field is needed to keep track of this.
9239
9240 @d minx_val(A) mp->mem[(A)+2].sc
9241 @d miny_val(A) mp->mem[(A)+3].sc
9242 @d maxx_val(A) mp->mem[(A)+4].sc
9243 @d maxy_val(A) mp->mem[(A)+5].sc
9244 @d bblast(A) link((A)+6)  /* last item considered in bounding box computation */
9245 @d bbtype(A) info((A)+6)  /* tells how bounding box data depends on \&{truecorners} */
9246 @d dummy_loc(A) ((A)+7)  /* where the object list begins in an edge header */
9247 @d no_bounds 0
9248   /* |bbtype| value when bounding box data is valid for all \&{truecorners} values */
9249 @d bounds_set 1
9250   /* |bbtype| value when bounding box data is for \&{truecorners}${}\le 0$ */
9251 @d bounds_unset 2
9252   /* |bbtype| value when bounding box data is for \&{truecorners}${}>0$ */
9253
9254 @c 
9255 void mp_init_bbox (MP mp,pointer h) {
9256   /* Initialize the bounding box information in edge structure |h| */
9257   bblast(h)=dummy_loc(h);
9258   bbtype(h)=no_bounds;
9259   minx_val(h)=el_gordo;
9260   miny_val(h)=el_gordo;
9261   maxx_val(h)=-el_gordo;
9262   maxy_val(h)=-el_gordo;
9263 }
9264
9265 @ The only other entries in an edge header are a reference count in the first
9266 word and a pointer to the tail of the object list in the last word.
9267
9268 @d obj_tail(A) info((A)+7)  /* points to the last entry in the object list */
9269 @d edge_header_size 8
9270
9271 @c 
9272 void mp_init_edges (MP mp,pointer h) {
9273   /* initialize an edge header to null values */
9274   dash_list(h)=null_dash;
9275   obj_tail(h)=dummy_loc(h);
9276   link(dummy_loc(h))=null;
9277   ref_count(h)=null;
9278   mp_init_bbox(mp, h);
9279 }
9280
9281 @ Here is how edge structures are deleted.  The process can be recursive because
9282 of the need to dereference edge structures that are used as dash patterns.
9283 @^recursion@>
9284
9285 @d add_edge_ref(A) incr(ref_count((A)))
9286 @d delete_edge_ref(A) { if ( ref_count((A))==null ) mp_toss_edges(mp, (A));
9287   else decr(ref_count((A))); }
9288
9289 @<Declare the recycling subroutines@>=
9290 void mp_flush_dash_list (MP mp,pointer h);
9291 pointer mp_toss_gr_object (MP mp,pointer p) ;
9292 void mp_toss_edges (MP mp,pointer h) ;
9293
9294 @ @c void mp_toss_edges (MP mp,pointer h) {
9295   pointer p,q;  /* pointers that scan the list being recycled */
9296   pointer r; /* an edge structure that object |p| refers to */
9297   mp_flush_dash_list(mp, h);
9298   q=link(dummy_loc(h));
9299   while ( (q!=null) ) { 
9300     p=q; q=link(q);
9301     r=mp_toss_gr_object(mp, p);
9302     if ( r!=null ) delete_edge_ref(r);
9303   }
9304   mp_free_node(mp, h,edge_header_size);
9305 }
9306 void mp_flush_dash_list (MP mp,pointer h) {
9307   pointer p,q;  /* pointers that scan the list being recycled */
9308   q=dash_list(h);
9309   while ( q!=null_dash ) { 
9310     p=q; q=link(q);
9311     mp_free_node(mp, p,dash_node_size);
9312   }
9313   dash_list(h)=null_dash;
9314 }
9315 pointer mp_toss_gr_object (MP mp,pointer p) {
9316   /* returns an edge structure that needs to be dereferenced */
9317   pointer e; /* the edge structure to return */
9318   e=null;
9319   @<Prepare to recycle graphical object |p|@>;
9320   mp_free_node(mp, p,mp->gr_object_size[type(p)]);
9321   return e;
9322 }
9323
9324 @ @<Prepare to recycle graphical object |p|@>=
9325 switch (type(p)) {
9326 case fill_code: 
9327   mp_toss_knot_list(mp, path_p(p));
9328   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9329   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9330   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9331   break;
9332 case stroked_code: 
9333   mp_toss_knot_list(mp, path_p(p));
9334   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9335   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9336   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9337   e=dash_p(p);
9338   break;
9339 case text_code: 
9340   delete_str_ref(text_p(p));
9341   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9342   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9343   break;
9344 case mp_start_clip_code:
9345 case mp_start_bounds_code: 
9346   mp_toss_knot_list(mp, path_p(p));
9347   break;
9348 case mp_stop_clip_code:
9349 case mp_stop_bounds_code: 
9350   break;
9351 } /* there are no other cases */
9352
9353 @ If we use |add_edge_ref| to ``copy'' edge structures, the real copying needs
9354 to be done before making a significant change to an edge structure.  Much of
9355 the work is done in a separate routine |copy_objects| that copies a list of
9356 graphical objects into a new edge header.
9357
9358 @c @<Declare a function called |copy_objects|@>;
9359 pointer mp_private_edges (MP mp,pointer h) {
9360   /* make a private copy of the edge structure headed by |h| */
9361   pointer hh;  /* the edge header for the new copy */
9362   pointer p,pp;  /* pointers for copying the dash list */
9363   if ( ref_count(h)==null ) {
9364     return h;
9365   } else { 
9366     decr(ref_count(h));
9367     hh=mp_copy_objects(mp, link(dummy_loc(h)),null);
9368     @<Copy the dash list from |h| to |hh|@>;
9369     @<Copy the bounding box information from |h| to |hh| and make |bblast(hh)|
9370       point into the new object list@>;
9371     return hh;
9372   }
9373 }
9374
9375 @ Here we use the fact that |dash_list(hh)=link(hh)|.
9376 @^data structure assumptions@>
9377
9378 @<Copy the dash list from |h| to |hh|@>=
9379 pp=hh; p=dash_list(h);
9380 while ( (p!=null_dash) ) { 
9381   link(pp)=mp_get_node(mp, dash_node_size);
9382   pp=link(pp);
9383   start_x(pp)=start_x(p);
9384   stop_x(pp)=stop_x(p);
9385   p=link(p);
9386 }
9387 link(pp)=null_dash;
9388 dash_y(hh)=dash_y(h)
9389
9390 @ @<Copy the bounding box information from |h| to |hh|...@>=
9391 minx_val(hh)=minx_val(h);
9392 miny_val(hh)=miny_val(h);
9393 maxx_val(hh)=maxx_val(h);
9394 maxy_val(hh)=maxy_val(h);
9395 bbtype(hh)=bbtype(h);
9396 p=dummy_loc(h); pp=dummy_loc(hh);
9397 while ((p!=bblast(h)) ) { 
9398   if ( p==null ) mp_confusion(mp, "bblast");
9399 @:this can't happen bblast}{\quad bblast@>
9400   p=link(p); pp=link(pp);
9401 }
9402 bblast(hh)=pp
9403
9404 @ Here is the promised routine for copying graphical objects into a new edge
9405 structure.  It starts copying at object~|p| and stops just before object~|q|.
9406 If |q| is null, it copies the entire sublist headed at |p|.  The resulting edge
9407 structure requires further initialization by |init_bbox|.
9408
9409 @<Declare a function called |copy_objects|@>=
9410 pointer mp_copy_objects (MP mp, pointer p, pointer q) {
9411   pointer hh;  /* the new edge header */
9412   pointer pp;  /* the last newly copied object */
9413   small_number k;  /* temporary register */
9414   hh=mp_get_node(mp, edge_header_size);
9415   dash_list(hh)=null_dash;
9416   ref_count(hh)=null;
9417   pp=dummy_loc(hh);
9418   while ( (p!=q) ) {
9419     @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>;
9420   }
9421   obj_tail(hh)=pp;
9422   link(pp)=null;
9423   return hh;
9424 }
9425
9426 @ @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>=
9427 { k=mp->gr_object_size[type(p)];
9428   link(pp)=mp_get_node(mp, k);
9429   pp=link(pp);
9430   while ( (k>0) ) { decr(k); mp->mem[pp+k]=mp->mem[p+k];  };
9431   @<Fix anything in graphical object |pp| that should differ from the
9432     corresponding field in |p|@>;
9433   p=link(p);
9434 }
9435
9436 @ @<Fix anything in graphical object |pp| that should differ from the...@>=
9437 switch (type(p)) {
9438 case mp_start_clip_code:
9439 case mp_start_bounds_code: 
9440   path_p(pp)=mp_copy_path(mp, path_p(p));
9441   break;
9442 case fill_code: 
9443   path_p(pp)=mp_copy_path(mp, path_p(p));
9444   if ( pen_p(p)!=null ) pen_p(pp)=copy_pen(pen_p(p));
9445   break;
9446 case stroked_code: 
9447   path_p(pp)=mp_copy_path(mp, path_p(p));
9448   pen_p(pp)=copy_pen(pen_p(p));
9449   if ( dash_p(p)!=null ) add_edge_ref(dash_p(pp));
9450   break;
9451 case text_code: 
9452   add_str_ref(text_p(pp));
9453   break;
9454 case mp_stop_clip_code:
9455 case mp_stop_bounds_code: 
9456   break;
9457 }  /* there are no other cases */
9458
9459 @ Here is one way to find an acceptable value for the second argument to
9460 |copy_objects|.  Given a non-null graphical object list, |skip_1component|
9461 skips past one picture component, where a ``picture component'' is a single
9462 graphical object, or a start bounds or start clip object and everything up
9463 through the matching stop bounds or stop clip object.  The macro version avoids
9464 procedure call overhead and error handling: |skip_component(p)(e)| advances |p|
9465 unless |p| points to a stop bounds or stop clip node, in which case it executes
9466 |e| instead.
9467
9468 @d skip_component(A)
9469     if ( ! is_start_or_stop((A)) ) (A)=link((A));
9470     else if ( ! is_stop((A)) ) (A)=mp_skip_1component(mp, (A));
9471     else 
9472
9473 @c 
9474 pointer mp_skip_1component (MP mp,pointer p) {
9475   integer lev; /* current nesting level */
9476   lev=0;
9477   do {  
9478    if ( is_start_or_stop(p) ) {
9479      if ( is_stop(p) ) decr(lev);  else incr(lev);
9480    }
9481    p=link(p);
9482   } while (lev!=0);
9483   return p;
9484 }
9485
9486 @ Here is a diagnostic routine for printing an edge structure in symbolic form.
9487
9488 @<Declare subroutines for printing expressions@>=
9489 @<Declare subroutines needed by |print_edges|@>;
9490 void mp_print_edges (MP mp,pointer h, char *s, boolean nuline) {
9491   pointer p;  /* a graphical object to be printed */
9492   pointer hh,pp;  /* temporary pointers */
9493   scaled scf;  /* a scale factor for the dash pattern */
9494   boolean ok_to_dash;  /* |false| for polygonal pen strokes */
9495   mp_print_diagnostic(mp, "Edge structure",s,nuline);
9496   p=dummy_loc(h);
9497   while ( link(p)!=null ) { 
9498     p=link(p);
9499     mp_print_ln(mp);
9500     switch (type(p)) {
9501       @<Cases for printing graphical object node |p|@>;
9502     default: 
9503           mp_print(mp, "[unknown object type!]");
9504           break;
9505     }
9506   }
9507   mp_print_nl(mp, "End edges");
9508   if ( p!=obj_tail(h) ) mp_print(mp, "?");
9509 @.End edges?@>
9510   mp_end_diagnostic(mp, true);
9511 }
9512
9513 @ @<Cases for printing graphical object node |p|@>=
9514 case fill_code: 
9515   mp_print(mp, "Filled contour ");
9516   mp_print_obj_color(mp, p);
9517   mp_print_char(mp, ':'); mp_print_ln(mp);
9518   mp_pr_path(mp, path_p(p)); mp_print_ln(mp);
9519   if ( (pen_p(p)!=null) ) {
9520     @<Print join type for graphical object |p|@>;
9521     mp_print(mp, " with pen"); mp_print_ln(mp);
9522     mp_pr_pen(mp, pen_p(p));
9523   }
9524   break;
9525
9526 @ @<Print join type for graphical object |p|@>=
9527 switch (ljoin_val(p)) {
9528 case 0:
9529   mp_print(mp, "mitered joins limited ");
9530   mp_print_scaled(mp, miterlim_val(p));
9531   break;
9532 case 1:
9533   mp_print(mp, "round joins");
9534   break;
9535 case 2:
9536   mp_print(mp, "beveled joins");
9537   break;
9538 default: 
9539   mp_print(mp, "?? joins");
9540 @.??@>
9541   break;
9542 }
9543
9544 @ For stroked nodes, we need to print |lcap_val(p)| as well.
9545
9546 @<Print join and cap types for stroked node |p|@>=
9547 switch (lcap_val(p)) {
9548 case 0:mp_print(mp, "butt"); break;
9549 case 1:mp_print(mp, "round"); break;
9550 case 2:mp_print(mp, "square"); break;
9551 default: mp_print(mp, "??"); break;
9552 @.??@>
9553 }
9554 mp_print(mp, " ends, ");
9555 @<Print join type for graphical object |p|@>
9556
9557 @ Here is a routine that prints the color of a graphical object if it isn't
9558 black (the default color).
9559
9560 @<Declare subroutines needed by |print_edges|@>=
9561 @<Declare a procedure called |print_compact_node|@>;
9562 void mp_print_obj_color (MP mp,pointer p) { 
9563   if ( color_model(p)==grey_model ) {
9564     if ( grey_val(p)>0 ) { 
9565       mp_print(mp, "greyed ");
9566       mp_print_compact_node(mp, obj_grey_loc(p),1);
9567     };
9568   } else if ( color_model(p)==cmyk_model ) {
9569     if ( (cyan_val(p)>0) || (magenta_val(p)>0) || 
9570          (yellow_val(p)>0) || (black_val(p)>0) ) { 
9571       mp_print(mp, "processcolored ");
9572       mp_print_compact_node(mp, obj_cyan_loc(p),4);
9573     };
9574   } else if ( color_model(p)==rgb_model ) {
9575     if ( (red_val(p)>0) || (green_val(p)>0) || (blue_val(p)>0) ) { 
9576       mp_print(mp, "colored "); 
9577       mp_print_compact_node(mp, obj_red_loc(p),3);
9578     };
9579   }
9580 }
9581
9582 @ We also need a procedure for printing consecutive scaled values as if they
9583 were a known big node.
9584
9585 @<Declare a procedure called |print_compact_node|@>=
9586 void mp_print_compact_node (MP mp,pointer p, small_number k) {
9587   pointer q;  /* last location to print */
9588   q=p+k-1;
9589   mp_print_char(mp, '(');
9590   while ( p<=q ){ 
9591     mp_print_scaled(mp, mp->mem[p].sc);
9592     if ( p<q ) mp_print_char(mp, ',');
9593     incr(p);
9594   }
9595   mp_print_char(mp, ')');
9596 }
9597
9598 @ @<Cases for printing graphical object node |p|@>=
9599 case stroked_code: 
9600   mp_print(mp, "Filled pen stroke ");
9601   mp_print_obj_color(mp, p);
9602   mp_print_char(mp, ':'); mp_print_ln(mp);
9603   mp_pr_path(mp, path_p(p));
9604   if ( dash_p(p)!=null ) { 
9605     mp_print_nl(mp, "dashed (");
9606     @<Finish printing the dash pattern that |p| refers to@>;
9607   }
9608   mp_print_ln(mp);
9609   @<Print join and cap types for stroked node |p|@>;
9610   mp_print(mp, " with pen"); mp_print_ln(mp);
9611   if ( pen_p(p)==null ) mp_print(mp, "???"); /* shouldn't happen */
9612 @.???@>
9613   else mp_pr_pen(mp, pen_p(p));
9614   break;
9615
9616 @ Normally, the  |dash_list| field in an edge header is set to |null_dash|
9617 when it is not known to define a suitable dash pattern.  This is disallowed
9618 here because the |dash_p| field should never point to such an edge header.
9619 Note that memory is allocated for |start_x(null_dash)| and we are free to
9620 give it any convenient value.
9621
9622 @<Finish printing the dash pattern that |p| refers to@>=
9623 ok_to_dash=pen_is_elliptical(pen_p(p));
9624 if ( ! ok_to_dash ) scf=unity; else scf=dash_scale(p);
9625 hh=dash_p(p);
9626 pp=dash_list(hh);
9627 if ( (pp==null_dash) || (dash_y(hh)<0) ) {
9628   mp_print(mp, " ??");
9629 } else { start_x(null_dash)=start_x(pp)+dash_y(hh);
9630   while ( pp!=null_dash ) { 
9631     mp_print(mp, "on ");
9632     mp_print_scaled(mp, mp_take_scaled(mp, stop_x(pp)-start_x(pp),scf));
9633     mp_print(mp, " off ");
9634     mp_print_scaled(mp, mp_take_scaled(mp, start_x(link(pp))-stop_x(pp),scf));
9635     pp = link(pp);
9636     if ( pp!=null_dash ) mp_print_char(mp, ' ');
9637   }
9638   mp_print(mp, ") shifted ");
9639   mp_print_scaled(mp, -mp_take_scaled(mp, mp_dash_offset(mp, hh),scf));
9640   if ( ! ok_to_dash || (dash_y(hh)==0) ) mp_print(mp, " (this will be ignored)");
9641 }
9642
9643 @ @<Declare subroutines needed by |print_edges|@>=
9644 scaled mp_dash_offset (MP mp,pointer h) {
9645   scaled x;  /* the answer */
9646   if ( (dash_list(h)==null_dash) || (dash_y(h)<0) ) mp_confusion(mp, "dash0");
9647 @:this can't happen dash0}{\quad dash0@>
9648   if ( dash_y(h)==0 ) {
9649     x=0; 
9650   } else { 
9651     x=-(start_x(dash_list(h)) % dash_y(h));
9652     if ( x<0 ) x=x+dash_y(h);
9653   }
9654   return x;
9655 }
9656
9657 @ @<Cases for printing graphical object node |p|@>=
9658 case text_code: 
9659   mp_print_char(mp, '"'); mp_print_str(mp,text_p(p));
9660   mp_print(mp, "\" infont \""); mp_print(mp, mp->font_name[font_n(p)]);
9661   mp_print_char(mp, '"'); mp_print_ln(mp);
9662   mp_print_obj_color(mp, p);
9663   mp_print(mp, "transformed ");
9664   mp_print_compact_node(mp, text_tx_loc(p),6);
9665   break;
9666
9667 @ @<Cases for printing graphical object node |p|@>=
9668 case mp_start_clip_code: 
9669   mp_print(mp, "clipping path:");
9670   mp_print_ln(mp);
9671   mp_pr_path(mp, path_p(p));
9672   break;
9673 case mp_stop_clip_code: 
9674   mp_print(mp, "stop clipping");
9675   break;
9676
9677 @ @<Cases for printing graphical object node |p|@>=
9678 case mp_start_bounds_code: 
9679   mp_print(mp, "setbounds path:");
9680   mp_print_ln(mp);
9681   mp_pr_path(mp, path_p(p));
9682   break;
9683 case mp_stop_bounds_code: 
9684   mp_print(mp, "end of setbounds");
9685   break;
9686
9687 @ To initialize the |dash_list| field in an edge header~|h|, we need a
9688 subroutine that scans an edge structure and tries to interpret it as a dash
9689 pattern.  This can only be done when there are no filled regions or clipping
9690 paths and all the pen strokes have the same color.  The first step is to let
9691 $y_0$ be the initial $y$~coordinate of the first pen stroke.  Then we implicitly
9692 project all the pen stroke paths onto the line $y=y_0$ and require that there
9693 be no retracing.  If the resulting paths cover a range of $x$~coordinates of
9694 length $\Delta x$, we set |dash_y(h)| to the length of the dash pattern by
9695 finding the maximum of $\Delta x$ and the absolute value of~$y_0$.
9696
9697 @c @<Declare a procedure called |x_retrace_error|@>;
9698 pointer mp_make_dashes (MP mp,pointer h) { /* returns |h| or |null| */
9699   pointer p;  /* this scans the stroked nodes in the object list */
9700   pointer p0;  /* if not |null| this points to the first stroked node */
9701   pointer pp,qq,rr;  /* pointers into |path_p(p)| */
9702   pointer d,dd;  /* pointers used to create the dash list */
9703   @<Other local variables in |make_dashes|@>;
9704   scaled y0=0;  /* the initial $y$ coordinate */
9705   if ( dash_list(h)!=null_dash ) 
9706         return h;
9707   p0=null;
9708   p=link(dummy_loc(h));
9709   while ( p!=null ) { 
9710     if ( type(p)!=stroked_code ) {
9711       @<Compain that the edge structure contains a node of the wrong type
9712         and |goto not_found|@>;
9713     }
9714     pp=path_p(p);
9715     if ( p0==null ){ p0=p; y0=y_coord(pp);  };
9716     @<Make |d| point to a new dash node created from stroke |p| and path |pp|
9717       or |goto not_found| if there is an error@>;
9718     @<Insert |d| into the dash list and |goto not_found| if there is an error@>;
9719     p=link(p);
9720   }
9721   if ( dash_list(h)==null_dash ) 
9722     goto NOT_FOUND; /* No error message */
9723   @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>;
9724   @<Set |dash_y(h)| and merge the first and last dashes if necessary@>;
9725   return h;
9726 NOT_FOUND: 
9727   @<Flush the dash list, recycle |h| and return |null|@>;
9728 };
9729
9730 @ @<Compain that the edge structure contains a node of the wrong type...@>=
9731
9732 print_err("Picture is too complicated to use as a dash pattern");
9733 help3("When you say `dashed p', picture p should not contain any")
9734   ("text, filled regions, or clipping paths.  This time it did")
9735   ("so I'll just make it a solid line instead.");
9736 mp_put_get_error(mp);
9737 goto NOT_FOUND;
9738 }
9739
9740 @ A similar error occurs when monotonicity fails.
9741
9742 @<Declare a procedure called |x_retrace_error|@>=
9743 void mp_x_retrace_error (MP mp) { 
9744 print_err("Picture is too complicated to use as a dash pattern");
9745 help3("When you say `dashed p', every path in p should be monotone")
9746   ("in x and there must be no overlapping.  This failed")
9747   ("so I'll just make it a solid line instead.");
9748 mp_put_get_error(mp);
9749 }
9750
9751 @ We stash |p| in |info(d)| if |dash_p(p)<>0| so that subsequent processing can
9752 handle the case where the pen stroke |p| is itself dashed.
9753
9754 @<Make |d| point to a new dash node created from stroke |p| and path...@>=
9755 @<Make sure |p| and |p0| are the same color and |goto not_found| if there is
9756   an error@>;
9757 rr=pp;
9758 if ( link(pp)!=pp ) {
9759   do {  
9760     qq=rr; rr=link(rr);
9761     @<Check for retracing between knots |qq| and |rr| and |goto not_found|
9762       if there is a problem@>;
9763   } while (right_type(rr)!=endpoint);
9764 }
9765 d=mp_get_node(mp, dash_node_size);
9766 if ( dash_p(p)==0 ) info(d)=0;  else info(d)=p;
9767 if ( x_coord(pp)<x_coord(rr) ) { 
9768   start_x(d)=x_coord(pp);
9769   stop_x(d)=x_coord(rr);
9770 } else { 
9771   start_x(d)=x_coord(rr);
9772   stop_x(d)=x_coord(pp);
9773 }
9774
9775 @ We also need to check for the case where the segment from |qq| to |rr| is
9776 monotone in $x$ but is reversed relative to the path from |pp| to |qq|.
9777
9778 @<Check for retracing between knots |qq| and |rr| and |goto not_found|...@>=
9779 x0=x_coord(qq);
9780 x1=right_x(qq);
9781 x2=left_x(rr);
9782 x3=x_coord(rr);
9783 if ( (x0>x1) || (x1>x2) || (x2>x3) ) {
9784   if ( (x0<x1) || (x1<x2) || (x2<x3) ) {
9785     if ( mp_ab_vs_cd(mp, x2-x1,x2-x1,x1-x0,x3-x2)>0 ) {
9786       mp_x_retrace_error(mp); goto NOT_FOUND;
9787     }
9788   }
9789 }
9790 if ( (x_coord(pp)>x0) || (x0>x3) ) {
9791   if ( (x_coord(pp)<x0) || (x0<x3) ) {
9792     mp_x_retrace_error(mp); goto NOT_FOUND;
9793   }
9794 }
9795
9796 @ @<Other local variables in |make_dashes|@>=
9797   scaled x0,x1,x2,x3;  /* $x$ coordinates of the segment from |qq| to |rr| */
9798
9799 @ @<Make sure |p| and |p0| are the same color and |goto not_found|...@>=
9800 if ( (red_val(p)!=red_val(p0)) || (black_val(p)!=black_val(p0)) ||
9801   (green_val(p)!=green_val(p0)) || (blue_val(p)!=blue_val(p0)) ) {
9802   print_err("Picture is too complicated to use as a dash pattern");
9803   help3("When you say `dashed p', everything in picture p should")
9804     ("be the same color.  I can\'t handle your color changes")
9805     ("so I'll just make it a solid line instead.");
9806   mp_put_get_error(mp);
9807   goto NOT_FOUND;
9808 }
9809
9810 @ @<Insert |d| into the dash list and |goto not_found| if there is an error@>=
9811 start_x(null_dash)=stop_x(d);
9812 dd=h; /* this makes |link(dd)=dash_list(h)| */
9813 while ( start_x(link(dd))<stop_x(d) )
9814   dd=link(dd);
9815 if ( dd!=h ) {
9816   if ( (stop_x(dd)>start_x(d)) )
9817     { mp_x_retrace_error(mp); goto NOT_FOUND;  };
9818 }
9819 link(d)=link(dd);
9820 link(dd)=d
9821
9822 @ @<Set |dash_y(h)| and merge the first and last dashes if necessary@>=
9823 d=dash_list(h);
9824 while ( (link(d)!=null_dash) )
9825   d=link(d);
9826 dd=dash_list(h);
9827 dash_y(h)=stop_x(d)-start_x(dd);
9828 if ( abs(y0)>dash_y(h) ) {
9829   dash_y(h)=abs(y0);
9830 } else if ( d!=dd ) { 
9831   dash_list(h)=link(dd);
9832   stop_x(d)=stop_x(dd)+dash_y(h);
9833   mp_free_node(mp, dd,dash_node_size);
9834 }
9835
9836 @ We get here when the argument is a null picture or when there is an error.
9837 Recovering from an error involves making |dash_list(h)| empty to indicate
9838 that |h| is not known to be a valid dash pattern.  We also dereference |h|
9839 since it is not being used for the return value.
9840
9841 @<Flush the dash list, recycle |h| and return |null|@>=
9842 mp_flush_dash_list(mp, h);
9843 delete_edge_ref(h);
9844 return null
9845
9846 @ Having carefully saved the dashed stroked nodes in the
9847 corresponding dash nodes, we must be prepared to break up these dashes into
9848 smaller dashes.
9849
9850 @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>=
9851 d=h;  /* now |link(d)=dash_list(h)| */
9852 while ( link(d)!=null_dash ) {
9853   ds=info(link(d));
9854   if ( ds==null ) { 
9855     d=link(d);
9856   } else {
9857     hh=dash_p(ds);
9858     hsf=dash_scale(ds);
9859     if ( (hh==null) ) mp_confusion(mp, "dash1");
9860 @:this can't happen dash0}{\quad dash1@>
9861     if ( dash_y(hh)==0 ) {
9862       d=link(d);
9863     } else { 
9864       if ( dash_list(hh)==null ) mp_confusion(mp, "dash1");
9865 @:this can't happen dash0}{\quad dash1@>
9866       @<Replace |link(d)| by a dashed version as determined by edge header
9867           |hh| and scale factor |ds|@>;
9868     }
9869   }
9870 }
9871
9872 @ @<Other local variables in |make_dashes|@>=
9873 pointer dln;  /* |link(d)| */
9874 pointer hh;  /* an edge header that tells how to break up |dln| */
9875 scaled hsf;  /* the dash pattern from |hh| gets scaled by this */
9876 pointer ds;  /* the stroked node from which |hh| and |hsf| are derived */
9877 scaled xoff;  /* added to $x$ values in |dash_list(hh)| to match |dln| */
9878
9879 @ @<Replace |link(d)| by a dashed version as determined by edge header...@>=
9880 dln=link(d);
9881 dd=dash_list(hh);
9882 xoff=start_x(dln)-mp_take_scaled(mp, hsf,start_x(dd))-
9883         mp_take_scaled(mp, hsf,mp_dash_offset(mp, hh));
9884 start_x(null_dash)=mp_take_scaled(mp, hsf,start_x(dd))
9885                    +mp_take_scaled(mp, hsf,dash_y(hh));
9886 stop_x(null_dash)=start_x(null_dash);
9887 @<Advance |dd| until finding the first dash that overlaps |dln| when
9888   offset by |xoff|@>;
9889 while ( start_x(dln)<=stop_x(dln) ) {
9890   @<If |dd| has `fallen off the end', back up to the beginning and fix |xoff|@>;
9891   @<Insert a dash between |d| and |dln| for the overlap with the offset version
9892     of |dd|@>;
9893   dd=link(dd);
9894   start_x(dln)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
9895 }
9896 link(d)=link(dln);
9897 mp_free_node(mp, dln,dash_node_size)
9898
9899 @ The name of this module is a bit of a lie because we actually just find the
9900 first |dd| where |take_scaled (hsf, stop_x(dd))| is large enough to make an
9901 overlap possible.  It could be that the unoffset version of dash |dln| falls
9902 in the gap between |dd| and its predecessor.
9903
9904 @<Advance |dd| until finding the first dash that overlaps |dln| when...@>=
9905 while ( xoff+mp_take_scaled(mp, hsf,stop_x(dd))<start_x(dln) ) {
9906   dd=link(dd);
9907 }
9908
9909 @ @<If |dd| has `fallen off the end', back up to the beginning and fix...@>=
9910 if ( dd==null_dash ) { 
9911   dd=dash_list(hh);
9912   xoff=xoff+mp_take_scaled(mp, hsf,dash_y(hh));
9913 }
9914
9915 @ At this point we already know that
9916 |start_x(dln)<=xoff+take_scaled(hsf,stop_x(dd))|.
9917
9918 @<Insert a dash between |d| and |dln| for the overlap with the offset...@>=
9919 if ( xoff+mp_take_scaled(mp, hsf,start_x(dd))<=stop_x(dln) ) {
9920   link(d)=mp_get_node(mp, dash_node_size);
9921   d=link(d);
9922   link(d)=dln;
9923   if ( start_x(dln)>xoff+mp_take_scaled(mp, hsf,start_x(dd)))
9924     start_x(d)=start_x(dln);
9925   else 
9926     start_x(d)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
9927   if ( stop_x(dln)<xoff+mp_take_scaled(mp, hsf,stop_x(dd)) ) 
9928     stop_x(d)=stop_x(dln);
9929   else 
9930     stop_x(d)=xoff+mp_take_scaled(mp, hsf,stop_x(dd));
9931 }
9932
9933 @ The next major task is to update the bounding box information in an edge
9934 header~|h|. This is done via a procedure |adjust_bbox| that enlarges an edge
9935 header's bounding box to accommodate the box computed by |path_bbox| or
9936 |pen_bbox|. (This is stored in global variables |minx|, |miny|, |maxx|, and
9937 |maxy|.)
9938
9939 @c void mp_adjust_bbox (MP mp,pointer h) { 
9940   if ( minx<minx_val(h) ) minx_val(h)=minx;
9941   if ( miny<miny_val(h) ) miny_val(h)=miny;
9942   if ( maxx>maxx_val(h) ) maxx_val(h)=maxx;
9943   if ( maxy>maxy_val(h) ) maxy_val(h)=maxy;
9944 }
9945
9946 @ Here is a special routine for updating the bounding box information in
9947 edge header~|h| to account for the squared-off ends of a non-cyclic path~|p|
9948 that is to be stroked with the pen~|pp|.
9949
9950 @c void mp_box_ends (MP mp, pointer p, pointer pp, pointer h) {
9951   pointer q;  /* a knot node adjacent to knot |p| */
9952   fraction dx,dy;  /* a unit vector in the direction out of the path at~|p| */
9953   scaled d;  /* a factor for adjusting the length of |(dx,dy)| */
9954   scaled z;  /* a coordinate being tested against the bounding box */
9955   scaled xx,yy;  /* the extreme pen vertex in the |(dx,dy)| direction */
9956   integer i; /* a loop counter */
9957   if ( right_type(p)!=endpoint ) { 
9958     q=link(p);
9959     while (1) { 
9960       @<Make |(dx,dy)| the final direction for the path segment from
9961         |q| to~|p|; set~|d|@>;
9962       d=mp_pyth_add(mp, dx,dy);
9963       if ( d>0 ) { 
9964          @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>;
9965          for (i=1;i<= 2;i++) { 
9966            @<Use |(dx,dy)| to generate a vertex of the square end cap and
9967              update the bounding box to accommodate it@>;
9968            dx=-dx; dy=-dy; 
9969         }
9970       }
9971       if ( right_type(p)==endpoint ) {
9972          return;
9973       } else {
9974         @<Advance |p| to the end of the path and make |q| the previous knot@>;
9975       } 
9976     }
9977   }
9978 }
9979
9980 @ @<Make |(dx,dy)| the final direction for the path segment from...@>=
9981 if ( q==link(p) ) { 
9982   dx=x_coord(p)-right_x(p);
9983   dy=y_coord(p)-right_y(p);
9984   if ( (dx==0)&&(dy==0) ) {
9985     dx=x_coord(p)-left_x(q);
9986     dy=y_coord(p)-left_y(q);
9987   }
9988 } else { 
9989   dx=x_coord(p)-left_x(p);
9990   dy=y_coord(p)-left_y(p);
9991   if ( (dx==0)&&(dy==0) ) {
9992     dx=x_coord(p)-right_x(q);
9993     dy=y_coord(p)-right_y(q);
9994   }
9995 }
9996 dx=x_coord(p)-x_coord(q);
9997 dy=y_coord(p)-y_coord(q)
9998
9999 @ @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>=
10000 dx=mp_make_fraction(mp, dx,d);
10001 dy=mp_make_fraction(mp, dy,d);
10002 mp_find_offset(mp, -dy,dx,pp);
10003 xx=mp->cur_x; yy=mp->cur_y
10004
10005 @ @<Use |(dx,dy)| to generate a vertex of the square end cap and...@>=
10006 mp_find_offset(mp, dx,dy,pp);
10007 d=mp_take_fraction(mp, xx-mp->cur_x,dx)+mp_take_fraction(mp, yy-mp->cur_y,dy);
10008 if ( ((d<0)&&(i==1)) || ((d>0)&&(i==2))) 
10009   mp_confusion(mp, "box_ends");
10010 @:this can't happen box ends}{\quad\\{box\_ends}@>
10011 z=x_coord(p)+mp->cur_x+mp_take_fraction(mp, d,dx);
10012 if ( z<minx_val(h) ) minx_val(h)=z;
10013 if ( z>maxx_val(h) ) maxx_val(h)=z;
10014 z=y_coord(p)+mp->cur_y+mp_take_fraction(mp, d,dy);
10015 if ( z<miny_val(h) ) miny_val(h)=z;
10016 if ( z>maxy_val(h) ) maxy_val(h)=z
10017
10018 @ @<Advance |p| to the end of the path and make |q| the previous knot@>=
10019 do {  
10020   q=p;
10021   p=link(p);
10022 } while (right_type(p)!=endpoint)
10023
10024 @ The major difficulty in finding the bounding box of an edge structure is the
10025 effect of clipping paths.  We treat them conservatively by only clipping to the
10026 clipping path's bounding box, but this still
10027 requires recursive calls to |set_bbox| in order to find the bounding box of
10028 @^recursion@>
10029 the objects to be clipped.  Such calls are distinguished by the fact that the
10030 boolean parameter |top_level| is false.
10031
10032 @c void mp_set_bbox (MP mp,pointer h, boolean top_level) {
10033   pointer p;  /* a graphical object being considered */
10034   scaled sminx,sminy,smaxx,smaxy;
10035   /* for saving the bounding box during recursive calls */
10036   scaled x0,x1,y0,y1;  /* temporary registers */
10037   integer lev;  /* nesting level for |mp_start_bounds_code| nodes */
10038   @<Wipe out any existing bounding box information if |bbtype(h)| is
10039   incompatible with |internal[true_corners]|@>;
10040   while ( link(bblast(h))!=null ) { 
10041     p=link(bblast(h));
10042     bblast(h)=p;
10043     switch (type(p)) {
10044     case mp_stop_clip_code: 
10045       if ( top_level ) mp_confusion(mp, "bbox");  else return;
10046 @:this can't happen bbox}{\quad bbox@>
10047       break;
10048     @<Other cases for updating the bounding box based on the type of object |p|@>;
10049     } /* all cases are enumerated above */
10050   }
10051   if ( ! top_level ) mp_confusion(mp, "bbox");
10052 }
10053
10054 @ @<Wipe out any existing bounding box information if |bbtype(h)| is...@>=
10055 switch (bbtype(h)) {
10056 case no_bounds: 
10057   break;
10058 case bounds_set: 
10059   if ( mp->internal[true_corners]>0 ) mp_init_bbox(mp, h);
10060   break;
10061 case bounds_unset: 
10062   if ( mp->internal[true_corners]<=0 ) mp_init_bbox(mp, h);
10063   break;
10064 } /* there are no other cases */
10065
10066 @ @<Other cases for updating the bounding box...@>=
10067 case fill_code: 
10068   mp_path_bbox(mp, path_p(p));
10069   if ( pen_p(p)!=null ) { 
10070     x0=minx; y0=miny;
10071     x1=maxx; y1=maxy;
10072     mp_pen_bbox(mp, pen_p(p));
10073     minx=minx+x0;
10074     miny=miny+y0;
10075     maxx=maxx+x1;
10076     maxy=maxy+y1;
10077   }
10078   mp_adjust_bbox(mp, h);
10079   break;
10080
10081 @ @<Other cases for updating the bounding box...@>=
10082 case mp_start_bounds_code: 
10083   if ( mp->internal[true_corners]>0 ) {
10084     bbtype(h)=bounds_unset;
10085   } else { 
10086     bbtype(h)=bounds_set;
10087     mp_path_bbox(mp, path_p(p));
10088     mp_adjust_bbox(mp, h);
10089     @<Scan to the matching |mp_stop_bounds_code| node and update |p| and
10090       |bblast(h)|@>;
10091   }
10092   break;
10093 case mp_stop_bounds_code: 
10094   if ( mp->internal[true_corners]<=0 ) mp_confusion(mp, "bbox2");
10095 @:this can't happen bbox2}{\quad bbox2@>
10096   break;
10097
10098 @ @<Scan to the matching |mp_stop_bounds_code| node and update |p| and...@>=
10099 lev=1;
10100 while ( lev!=0 ) { 
10101   if ( link(p)==null ) mp_confusion(mp, "bbox2");
10102 @:this can't happen bbox2}{\quad bbox2@>
10103   p=link(p);
10104   if ( type(p)==mp_start_bounds_code ) incr(lev);
10105   else if ( type(p)==mp_stop_bounds_code ) decr(lev);
10106 }
10107 bblast(h)=p
10108
10109 @ It saves a lot of grief here to be slightly conservative and not account for
10110 omitted parts of dashed lines.  We also don't worry about the material omitted
10111 when using butt end caps.  The basic computation is for round end caps and
10112 |box_ends| augments it for square end caps.
10113
10114 @<Other cases for updating the bounding box...@>=
10115 case stroked_code: 
10116   mp_path_bbox(mp, path_p(p));
10117   x0=minx; y0=miny;
10118   x1=maxx; y1=maxy;
10119   mp_pen_bbox(mp, pen_p(p));
10120   minx=minx+x0;
10121   miny=miny+y0;
10122   maxx=maxx+x1;
10123   maxy=maxy+y1;
10124   mp_adjust_bbox(mp, h);
10125   if ( (left_type(path_p(p))==endpoint)&&(lcap_val(p)==2) )
10126     mp_box_ends(mp, path_p(p), pen_p(p), h);
10127   break;
10128
10129 @ The height width and depth information stored in a text node determines a
10130 rectangle that needs to be transformed according to the transformation
10131 parameters stored in the text node.
10132
10133 @<Other cases for updating the bounding box...@>=
10134 case text_code: 
10135   x1=mp_take_scaled(mp, txx_val(p),width_val(p));
10136   y0=mp_take_scaled(mp, txy_val(p),-depth_val(p));
10137   y1=mp_take_scaled(mp, txy_val(p),height_val(p));
10138   minx=tx_val(p);
10139   maxx=minx;
10140   if ( y0<y1 ) { minx=minx+y0; maxx=maxx+y1;  }
10141   else         { minx=minx+y1; maxx=maxx+y0;  }
10142   if ( x1<0 ) minx=minx+x1;  else maxx=maxx+x1;
10143   x1=mp_take_scaled(mp, tyx_val(p),width_val(p));
10144   y0=mp_take_scaled(mp, tyy_val(p),-depth_val(p));
10145   y1=mp_take_scaled(mp, tyy_val(p),height_val(p));
10146   miny=ty_val(p);
10147   maxy=miny;
10148   if ( y0<y1 ) { miny=miny+y0; maxy=maxy+y1;  }
10149   else         { miny=miny+y1; maxy=maxy+y0;  }
10150   if ( x1<0 ) miny=miny+x1;  else maxy=maxy+x1;
10151   mp_adjust_bbox(mp, h);
10152   break;
10153
10154 @ This case involves a recursive call that advances |bblast(h)| to the node of
10155 type |mp_stop_clip_code| that matches |p|.
10156
10157 @<Other cases for updating the bounding box...@>=
10158 case mp_start_clip_code: 
10159   mp_path_bbox(mp, path_p(p));
10160   x0=minx; y0=miny;
10161   x1=maxx; y1=maxy;
10162   sminx=minx_val(h); sminy=miny_val(h);
10163   smaxx=maxx_val(h); smaxy=maxy_val(h);
10164   @<Reinitialize the bounding box in header |h| and call |set_bbox| recursively
10165     starting at |link(p)|@>;
10166   @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,
10167     |y0|, |y1|@>;
10168   minx=sminx; miny=sminy;
10169   maxx=smaxx; maxy=smaxy;
10170   mp_adjust_bbox(mp, h);
10171   break;
10172
10173 @ @<Reinitialize the bounding box in header |h| and call |set_bbox|...@>=
10174 minx_val(h)=el_gordo;
10175 miny_val(h)=el_gordo;
10176 maxx_val(h)=-el_gordo;
10177 maxy_val(h)=-el_gordo;
10178 mp_set_bbox(mp, h,false)
10179
10180 @ @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,...@>=
10181 if ( minx_val(h)<x0 ) minx_val(h)=x0;
10182 if ( miny_val(h)<y0 ) miny_val(h)=y0;
10183 if ( maxx_val(h)>x1 ) maxx_val(h)=x1;
10184 if ( maxy_val(h)>y1 ) maxy_val(h)=y1
10185
10186 @* \[22] Finding an envelope.
10187 When \MP\ has a path and a polygonal pen, it needs to express the desired
10188 shape in terms of things \ps\ can understand.  The present task is to compute
10189 a new path that describes the region to be filled.  It is convenient to
10190 define this as a two step process where the first step is determining what
10191 offset to use for each segment of the path.
10192
10193 @ Given a pointer |c| to a cyclic path,
10194 and a pointer~|h| to the first knot of a pen polygon,
10195 the |offset_prep| routine changes the path into cubics that are
10196 associated with particular pen offsets. Thus if the cubic between |p|
10197 and~|q| is associated with the |k|th offset and the cubic between |q| and~|r|
10198 has offset |l| then |info(q)=zero_off+l-k|. (The constant |zero_off| is added
10199 to because |l-k| could be negative.)
10200
10201 After overwriting the type information with offset differences, we no longer
10202 have a true path so we refer to the knot list returned by |offset_prep| as an
10203 ``envelope spec.''
10204 @^envelope spec@>
10205 Since an envelope spec only determines relative changes in pen offsets,
10206 |offset_prep| sets a global variable |spec_offset| to the relative change from
10207 |h| to the first offset.
10208
10209 @d zero_off 16384 /* added to offset changes to make them positive */
10210
10211 @<Glob...@>=
10212 integer spec_offset; /* number of pen edges between |h| and the initial offset */
10213
10214 @ @c @<Declare subroutines needed by |offset_prep|@>;
10215 pointer mp_offset_prep (MP mp,pointer c, pointer h) {
10216   halfword n; /* the number of vertices in the pen polygon */
10217   pointer p,q,r,w, ww; /* for list manipulation */
10218   integer k_needed; /* amount to be added to |info(p)| when it is computed */
10219   pointer w0; /* a pointer to pen offset to use just before |p| */
10220   scaled dxin,dyin; /* the direction into knot |p| */
10221   integer turn_amt; /* change in pen offsets for the current cubic */
10222   @<Other local variables for |offset_prep|@>;
10223   dx0=0; dy0=0;
10224   @<Initialize the pen size~|n|@>;
10225   @<Initialize the incoming direction and pen offset at |c|@>;
10226   p=c; k_needed=0;
10227   do {  
10228     q=link(p);
10229     @<Split the cubic between |p| and |q|, if necessary, into cubics
10230       associated with single offsets, after which |q| should
10231       point to the end of the final such cubic@>;
10232     @<Advance |p| to node |q|, removing any ``dead'' cubics that
10233       might have been introduced by the splitting process@>;
10234   } while (q!=c);
10235   @<Fix the offset change in |info(c)| and set the return value of
10236     |offset_prep|@>;
10237 }
10238
10239 @ We shall want to keep track of where certain knots on the cyclic path
10240 wind up in the envelope spec.  It doesn't suffice just to keep pointers to
10241 knot nodes because some nodes are deleted while removing dead cubics.  Thus
10242 |offset_prep| updates the following pointers
10243
10244 @<Glob...@>=
10245 pointer spec_p1;
10246 pointer spec_p2; /* pointers to distinguished knots */
10247
10248 @ @<Set init...@>=
10249 mp->spec_p1=null; mp->spec_p2=null;
10250
10251 @ @<Initialize the pen size~|n|@>=
10252 n=0; p=h;
10253 do {  
10254   incr(n);
10255   p=link(p);
10256 } while (p!=h)
10257
10258 @ Since the true incoming direction isn't known yet, we just pick a direction
10259 consistent with the pen offset~|h|.  If this is wrong, it can be corrected
10260 later.
10261
10262 @<Initialize the incoming direction and pen offset at |c|@>=
10263 dxin=x_coord(link(h))-x_coord(knil(h));
10264 dyin=y_coord(link(h))-y_coord(knil(h));
10265 if ( (dxin==0)&&(dyin==0) ) {
10266   dxin=y_coord(knil(h))-y_coord(h);
10267   dyin=x_coord(h)-x_coord(knil(h));
10268 }
10269 w0=h
10270
10271 @ We must be careful not to remove the only cubic in a cycle.
10272
10273 But we must also be careful for another reason. If the user-supplied
10274 path starts with a set of degenerate cubics, these should not be removed
10275 because at this point we cannot do so cleanly. The relevant bug is
10276 tracker id 267, bugs 52c, reported by Boguslav.
10277
10278 @<Advance |p| to node |q|, removing any ``dead'' cubics...@>=
10279 do {  r=link(p);
10280 if ( x_coord(p)==right_x(p) ) if ( y_coord(p)==right_y(p) )
10281  if ( x_coord(p)==left_x(r) ) if ( y_coord(p)==left_y(r) )
10282   if ( x_coord(p)==x_coord(r) ) if ( y_coord(p)==y_coord(r) )
10283     if ( r!=p ) if ( ((r!=q) || (originator(r)!=metapost_user)) ) {
10284       @<Remove the cubic following |p| and update the data structures
10285         to merge |r| into |p|@>;
10286 }
10287 p=r;
10288 } while (p!=q)
10289
10290 @ @<Remove the cubic following |p| and update the data structures...@>=
10291 { k_needed=info(p)-zero_off;
10292   if ( r==q ) { 
10293     q=p;
10294   } else { 
10295     info(p)=k_needed+info(r);
10296     k_needed=0;
10297   };
10298   if ( r==c ) { info(p)=info(c); c=p; };
10299   if ( r==mp->spec_p1 ) mp->spec_p1=p;
10300   if ( r==mp->spec_p2 ) mp->spec_p2=p;
10301   r=p; mp_remove_cubic(mp, p);
10302 }
10303
10304 @ Not setting the |info| field of the newly created knot allows the splitting
10305 routine to work for paths.
10306
10307 @<Declare subroutines needed by |offset_prep|@>=
10308 void mp_split_cubic (MP mp,pointer p, fraction t) { /* splits the cubic after |p| */
10309   scaled v; /* an intermediate value */
10310   pointer q,r; /* for list manipulation */
10311   q=link(p); r=mp_get_node(mp, knot_node_size); link(p)=r; link(r)=q;
10312   originator(r)=program_code;
10313   left_type(r)=explicit; right_type(r)=explicit;
10314   v=t_of_the_way(right_x(p),left_x(q));
10315   right_x(p)=t_of_the_way(x_coord(p),right_x(p));
10316   left_x(q)=t_of_the_way(left_x(q),x_coord(q));
10317   left_x(r)=t_of_the_way(right_x(p),v);
10318   right_x(r)=t_of_the_way(v,left_x(q));
10319   x_coord(r)=t_of_the_way(left_x(r),right_x(r));
10320   v=t_of_the_way(right_y(p),left_y(q));
10321   right_y(p)=t_of_the_way(y_coord(p),right_y(p));
10322   left_y(q)=t_of_the_way(left_y(q),y_coord(q));
10323   left_y(r)=t_of_the_way(right_y(p),v);
10324   right_y(r)=t_of_the_way(v,left_y(q));
10325   y_coord(r)=t_of_the_way(left_y(r),right_y(r));
10326 }
10327
10328 @ This does not set |info(p)| or |right_type(p)|.
10329
10330 @<Declare subroutines needed by |offset_prep|@>=
10331 void mp_remove_cubic (MP mp,pointer p) { /* removes the dead cubic following~|p| */
10332   pointer q; /* the node that disappears */
10333   q=link(p); link(p)=link(q);
10334   right_x(p)=right_x(q); right_y(p)=right_y(q);
10335   mp_free_node(mp, q,knot_node_size);
10336 }
10337
10338 @ Let $d\prec d'$ mean that the counter-clockwise angle from $d$ to~$d'$ is
10339 strictly between zero and $180^\circ$.  Then we can define $d\preceq d'$ to
10340 mean that the angle could be zero or $180^\circ$. If $w_k=(u_k,v_k)$ is the
10341 $k$th pen offset, the $k$th pen edge direction is defined by the formula
10342 $$d_k=(u\k-u_k,\,v\k-v_k).$$
10343 When listed by increasing $k$, these directions occur in counter-clockwise
10344 order so that $d_k\preceq d\k$ for all~$k$.
10345 The goal of |offset_prep| is to find an offset index~|k| to associate with
10346 each cubic, such that the direction $d(t)$ of the cubic satisfies
10347 $$d_{k-1}\preceq d(t)\preceq d_k\qquad\hbox{for $0\le t\le 1$.}\eqno(*)$$
10348 We may have to split a cubic into many pieces before each
10349 piece corresponds to a unique offset.
10350
10351 @<Split the cubic between |p| and |q|, if necessary, into cubics...@>=
10352 info(p)=zero_off+k_needed;
10353 k_needed=0;
10354 @<Prepare for derivative computations;
10355   |goto not_found| if the current cubic is dead@>;
10356 @<Find the initial direction |(dx,dy)|@>;
10357 @<Update |info(p)| and find the offset $w_k$ such that
10358   $d_{k-1}\preceq(\\{dx},\\{dy})\prec d_k$; also advance |w0| for
10359   the direction change at |p|@>;
10360 @<Find the final direction |(dxin,dyin)|@>;
10361 @<Decide on the net change in pen offsets and set |turn_amt|@>;
10362 @<Complete the offset splitting process@>;
10363 w0=mp_pen_walk(mp, w0,turn_amt);
10364 NOT_FOUND: do_nothing
10365
10366 @ @<Declare subroutines needed by |offset_prep|@>=
10367 pointer mp_pen_walk (MP mp,pointer w, integer k) {
10368   /* walk |k| steps around a pen from |w| */
10369   while ( k>0 ) { w=link(w); decr(k);  };
10370   while ( k<0 ) { w=knil(w); incr(k);  };
10371   return w;
10372 }
10373
10374 @ The direction of a cubic $B(z_0,z_1,z_2,z_3;t)=\bigl(x(t),y(t)\bigr)$ can be
10375 calculated from the quadratic polynomials
10376 ${1\over3}x'(t)=B(x_1-x_0,x_2-x_1,x_3-x_2;t)$ and
10377 ${1\over3}y'(t)=B(y_1-y_0,y_2-y_1,y_3-y_2;t)$.
10378 Since we may be calculating directions from several cubics
10379 split from the current one, it is desirable to do these calculations
10380 without losing too much precision. ``Scaled up'' values of the
10381 derivatives, which will be less tainted by accumulated errors than
10382 derivatives found from the cubics themselves, are maintained in
10383 local variables |x0|, |x1|, and |x2|, representing $X_0=2^l(x_1-x_0)$,
10384 $X_1=2^l(x_2-x_1)$, and $X_2=2^l(x_3-x_2)$; similarly |y0|, |y1|, and~|y2|
10385 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)$.
10386
10387 @<Other local variables for |offset_prep|@>=
10388 integer x0,x1,x2,y0,y1,y2; /* representatives of derivatives */
10389 integer t0,t1,t2; /* coefficients of polynomial for slope testing */
10390 integer du,dv,dx,dy; /* for directions of the pen and the curve */
10391 integer dx0,dy0; /* initial direction for the first cubic in the curve */
10392 integer mp_max_coef; /* used while scaling */
10393 integer x0a,x1a,x2a,y0a,y1a,y2a; /* intermediate values */
10394 fraction t; /* where the derivative passes through zero */
10395 fraction s; /* a temporary value */
10396
10397 @ @<Prepare for derivative computations...@>=
10398 x0=right_x(p)-x_coord(p);
10399 x2=x_coord(q)-left_x(q);
10400 x1=left_x(q)-right_x(p);
10401 y0=right_y(p)-y_coord(p); y2=y_coord(q)-left_y(q);
10402 y1=left_y(q)-right_y(p);
10403 mp_max_coef=abs(x0);
10404 if ( abs(x1)>mp_max_coef ) mp_max_coef=abs(x1);
10405 if ( abs(x2)>mp_max_coef ) mp_max_coef=abs(x2);
10406 if ( abs(y0)>mp_max_coef ) mp_max_coef=abs(y0);
10407 if ( abs(y1)>mp_max_coef ) mp_max_coef=abs(y1);
10408 if ( abs(y2)>mp_max_coef ) mp_max_coef=abs(y2);
10409 if ( mp_max_coef==0 ) goto NOT_FOUND;
10410 while ( mp_max_coef<fraction_half ) {
10411   mp_max_coef+=mp_max_coef;
10412   x0+=x0; x1+=x1; x2+=x2;
10413   y0+=y0; y1+=y1; y2+=y2;
10414 }
10415
10416 @ Let us first solve a special case of the problem: Suppose we
10417 know an index~$k$ such that either (i)~$d(t)\succeq d_{k-1}$ for all~$t$
10418 and $d(0)\prec d_k$, or (ii)~$d(t)\preceq d_k$ for all~$t$ and
10419 $d(0)\succ d_{k-1}$.
10420 Then, in a sense, we're halfway done, since one of the two relations
10421 in $(*)$ is satisfied, and the other couldn't be satisfied for
10422 any other value of~|k|.
10423
10424 Actually, the conditions can be relaxed somewhat since a relation such as
10425 $d(t)\succeq d_{k-1}$ restricts $d(t)$ to a half plane when all that really
10426 matters is whether $d(t)$ crosses the ray in the $d_{k-1}$ direction from
10427 the origin.  The condition for case~(i) becomes $d_{k-1}\preceq d(0)\prec d_k$
10428 and $d(t)$ never crosses the $d_{k-1}$ ray in the clockwise direction.
10429 Case~(ii) is similar except $d(t)$ cannot cross the $d_k$ ray in the
10430 counterclockwise direction.
10431
10432 The |fin_offset_prep| subroutine solves the stated subproblem.
10433 It has a parameter called |rise| that is |1| in
10434 case~(i), |-1| in case~(ii). Parameters |x0| through |y2| represent
10435 the derivative of the cubic following |p|.
10436 The |w| parameter should point to offset~$w_k$ and |info(p)| should already
10437 be set properly.  The |turn_amt| parameter gives the absolute value of the
10438 overall net change in pen offsets.
10439
10440 @<Declare subroutines needed by |offset_prep|@>=
10441 void mp_fin_offset_prep (MP mp,pointer p, pointer w, integer 
10442   x0,integer x1, integer x2, integer y0, integer y1, integer y2, 
10443   integer rise, integer turn_amt)  {
10444   pointer ww; /* for list manipulation */
10445   scaled du,dv; /* for slope calculation */
10446   integer t0,t1,t2; /* test coefficients */
10447   fraction t; /* place where the derivative passes a critical slope */
10448   fraction s; /* slope or reciprocal slope */
10449   integer v; /* intermediate value for updating |x0..y2| */
10450   pointer q; /* original |link(p)| */
10451   q=link(p);
10452   while (1)  { 
10453     if ( rise>0 ) ww=link(w); /* a pointer to $w\k$ */
10454     else  ww=knil(w); /* a pointer to $w_{k-1}$ */
10455     @<Compute test coefficients |(t0,t1,t2)|
10456       for $d(t)$ versus $d_k$ or $d_{k-1}$@>;
10457     t=mp_crossing_point(mp, t0,t1,t2);
10458     if ( t>=fraction_one ) {
10459       if ( turn_amt>0 ) t=fraction_one;  else return;
10460     }
10461     @<Split the cubic at $t$,
10462       and split off another cubic if the derivative crosses back@>;
10463     w=ww;
10464   }
10465 }
10466
10467 @ We want $B(\\{t0},\\{t1},\\{t2};t)$ to be the dot product of $d(t)$ with a
10468 $-90^\circ$ rotation of the vector from |w| to |ww|.  This makes the resulting
10469 function cross from positive to negative when $d_{k-1}\preceq d(t)\preceq d_k$
10470 begins to fail.
10471
10472 @<Compute test coefficients |(t0,t1,t2)| for $d(t)$ versus...@>=
10473 du=x_coord(ww)-x_coord(w); dv=y_coord(ww)-y_coord(w);
10474 if ( abs(du)>=abs(dv) ) {
10475   s=mp_make_fraction(mp, dv,du);
10476   t0=mp_take_fraction(mp, x0,s)-y0;
10477   t1=mp_take_fraction(mp, x1,s)-y1;
10478   t2=mp_take_fraction(mp, x2,s)-y2;
10479   if ( du<0 ) { negate(t0); negate(t1); negate(t2);  }
10480 } else { 
10481   s=mp_make_fraction(mp, du,dv);
10482   t0=x0-mp_take_fraction(mp, y0,s);
10483   t1=x1-mp_take_fraction(mp, y1,s);
10484   t2=x2-mp_take_fraction(mp, y2,s);
10485   if ( dv<0 ) { negate(t0); negate(t1); negate(t2);  }
10486 }
10487 if ( t0<0 ) t0=0 /* should be positive without rounding error */
10488
10489 @ The curve has crossed $d_k$ or $d_{k-1}$; its initial segment satisfies
10490 $(*)$, and it might cross again, yielding another solution of $(*)$.
10491
10492 @<Split the cubic at $t$, and split off another...@>=
10493
10494 mp_split_cubic(mp, p,t); p=link(p); info(p)=zero_off+rise;
10495 decr(turn_amt);
10496 v=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10497 x0=t_of_the_way(v,x1);
10498 v=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10499 y0=t_of_the_way(v,y1);
10500 if ( turn_amt<0 ) {
10501   t1=t_of_the_way(t1,t2);
10502   if ( t1>0 ) t1=0; /* without rounding error, |t1| would be |<=0| */
10503   t=mp_crossing_point(mp, 0,-t1,-t2);
10504   if ( t>fraction_one ) t=fraction_one;
10505   incr(turn_amt);
10506   if ( (t==fraction_one)&&(link(p)!=q) ) {
10507     info(link(p))=info(link(p))-rise;
10508   } else { 
10509     mp_split_cubic(mp, p,t); info(link(p))=zero_off-rise;
10510     v=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10511     x2=t_of_the_way(x1,v);
10512     v=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10513     y2=t_of_the_way(y1,v);
10514   }
10515 }
10516 }
10517
10518 @ Now we must consider the general problem of |offset_prep|, when
10519 nothing is known about a given cubic. We start by finding its
10520 direction in the vicinity of |t=0|.
10521
10522 If $z'(t)=0$, the given cubic is numerically unstable but |offset_prep|
10523 has not yet introduced any more numerical errors.  Thus we can compute
10524 the true initial direction for the given cubic, even if it is almost
10525 degenerate.
10526
10527 @<Find the initial direction |(dx,dy)|@>=
10528 dx=x0; dy=y0;
10529 if ( dx==0 ) if ( dy==0 ) { 
10530   dx=x1; dy=y1;
10531   if ( dx==0 ) if ( dy==0 ) { 
10532     dx=x2; dy=y2;
10533   }
10534 }
10535 if ( p==c ) { dx0=dx; dy0=dy;  }
10536
10537 @ @<Find the final direction |(dxin,dyin)|@>=
10538 dxin=x2; dyin=y2;
10539 if ( dxin==0 ) if ( dyin==0 ) {
10540   dxin=x1; dyin=y1;
10541   if ( dxin==0 ) if ( dyin==0 ) {
10542     dxin=x0; dyin=y0;
10543   }
10544 }
10545
10546 @ The next step is to bracket the initial direction between consecutive
10547 edges of the pen polygon.  We must be careful to turn clockwise only if
10548 this makes the turn less than $180^\circ$. (A $180^\circ$ turn must be
10549 counter-clockwise in order to make \&{doublepath} envelopes come out
10550 @:double_path_}{\&{doublepath} primitive@>
10551 right.) This code depends on |w0| being the offset for |(dxin,dyin)|.
10552
10553 @<Update |info(p)| and find the offset $w_k$ such that...@>=
10554 turn_amt=mp_get_turn_amt(mp, w0, dx, dy, mp_ab_vs_cd(mp, dy,dxin,dx,dyin)>=0);
10555 w=mp_pen_walk(mp, w0, turn_amt);
10556 w0=w;
10557 info(p)=info(p)+turn_amt
10558
10559 @ Decide how many pen offsets to go away from |w| in order to find the offset
10560 for |(dx,dy)|, going counterclockwise if |ccw| is |true|.  This assumes that
10561 |w| is the offset for some direction $(x',y')$ from which the angle to |(dx,dy)|
10562 in the sense determined by |ccw| is less than or equal to $180^\circ$.
10563
10564 If the pen polygon has only two edges, they could both be parallel
10565 to |(dx,dy)|.  In this case, we must be careful to stop after crossing the first
10566 such edge in order to avoid an infinite loop.
10567
10568 @<Declare subroutines needed by |offset_prep|@>=
10569 integer mp_get_turn_amt (MP mp,pointer w, scaled  dx,
10570                          scaled dy, boolean  ccw) {
10571   pointer ww; /* a neighbor of knot~|w| */
10572   integer s; /* turn amount so far */
10573   integer t; /* |ab_vs_cd| result */
10574   s=0;
10575   if ( ccw ) { 
10576     ww=link(w);
10577     do {  
10578       t=mp_ab_vs_cd(mp, dy,x_coord(ww)-x_coord(w),
10579                         dx,y_coord(ww)-y_coord(w));
10580       if ( t<0 ) break;
10581       incr(s);
10582       w=ww; ww=link(ww);
10583     } while (t>0);
10584   } else { 
10585     ww=knil(w);
10586     while ( mp_ab_vs_cd(mp, dy,x_coord(w)-x_coord(ww),
10587                             dx,y_coord(w)-y_coord(ww))<0 ) { 
10588       decr(s);
10589       w=ww; ww=knil(ww);
10590     }
10591   }
10592   return s;
10593 }
10594
10595 @ When we're all done, the final offset is |w0| and the final curve direction
10596 is |(dxin,dyin)|.  With this knowledge of the incoming direction at |c|, we
10597 can correct |info(c)| which was erroneously based on an incoming offset
10598 of~|h|.
10599
10600 @d fix_by(A) info(c)=info(c)+(A)
10601
10602 @<Fix the offset change in |info(c)| and set the return value of...@>=
10603 mp->spec_offset=info(c)-zero_off;
10604 if ( link(c)==c ) {
10605   info(c)=zero_off+n;
10606 } else { 
10607   fix_by(k_needed);
10608   while ( w0!=h ) { fix_by(1); w0=link(w0);  };
10609   while ( info(c)<=zero_off-n ) fix_by(n);
10610   while ( info(c)>zero_off ) fix_by(-n);
10611   if ( (info(c)!=zero_off)&&(mp_ab_vs_cd(mp, dy0,dxin,dx0,dyin)>=0) ) fix_by(n);
10612 }
10613 return c
10614
10615 @ Finally we want to reduce the general problem to situations that
10616 |fin_offset_prep| can handle. We split the cubic into at most three parts
10617 with respect to $d_{k-1}$, and apply |fin_offset_prep| to each part.
10618
10619 @<Complete the offset splitting process@>=
10620 ww=knil(w);
10621 @<Compute test coeff...@>;
10622 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set
10623   |t:=fraction_one+1|@>;
10624 if ( t>fraction_one ) {
10625   mp_fin_offset_prep(mp, p,w,x0,x1,x2,y0,y1,y2,1,turn_amt);
10626 } else {
10627   mp_split_cubic(mp, p,t); r=link(p);
10628   x1a=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10629   x2a=t_of_the_way(x1a,x1);
10630   y1a=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10631   y2a=t_of_the_way(y1a,y1);
10632   mp_fin_offset_prep(mp, p,w,x0,x1a,x2a,y0,y1a,y2a,1,0); x0=x2a; y0=y2a;
10633   info(r)=zero_off-1;
10634   if ( turn_amt>=0 ) {
10635     t1=t_of_the_way(t1,t2);
10636     if ( t1>0 ) t1=0;
10637     t=mp_crossing_point(mp, 0,-t1,-t2);
10638     if ( t>fraction_one ) t=fraction_one;
10639     @<Split off another rising cubic for |fin_offset_prep|@>;
10640     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,0);
10641   } else {
10642     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,-1-turn_amt);
10643   }
10644 }
10645
10646 @ @<Split off another rising cubic for |fin_offset_prep|@>=
10647 mp_split_cubic(mp, r,t); info(link(r))=zero_off+1;
10648 x1a=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10649 x0a=t_of_the_way(x1,x1a);
10650 y1a=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10651 y0a=t_of_the_way(y1,y1a);
10652 mp_fin_offset_prep(mp, link(r),w,x0a,x1a,x2,y0a,y1a,y2,1,turn_amt);
10653 x2=x0a; y2=y0a
10654
10655 @ At this point, the direction of the incoming pen edge is |(-du,-dv)|.
10656 When the component of $d(t)$ perpendicular to |(-du,-dv)| crosses zero, we
10657 need to decide whether the directions are parallel or antiparallel.  We
10658 can test this by finding the dot product of $d(t)$ and |(-du,-dv)|, but this
10659 should be avoided when the value of |turn_amt| already determines the
10660 answer.  If |t2<0|, there is one crossing and it is antiparallel only if
10661 |turn_amt>=0|.  If |turn_amt<0|, there should always be at least one
10662 crossing and the first crossing cannot be antiparallel.
10663
10664 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set...@>=
10665 t=mp_crossing_point(mp, t0,t1,t2);
10666 if ( turn_amt>=0 ) {
10667   if ( t2<0 ) {
10668     t=fraction_one+1;
10669   } else { 
10670     u0=t_of_the_way(x0,x1);
10671     u1=t_of_the_way(x1,x2);
10672     ss=mp_take_fraction(mp, -du,t_of_the_way(u0,u1));
10673     v0=t_of_the_way(y0,y1);
10674     v1=t_of_the_way(y1,y2);
10675     ss=ss+mp_take_fraction(mp, -dv,t_of_the_way(v0,v1));
10676     if ( ss<0 ) t=fraction_one+1;
10677   }
10678 } else if ( t>fraction_one ) {
10679   t=fraction_one;
10680 }
10681
10682 @ @<Other local variables for |offset_prep|@>=
10683 integer u0,u1,v0,v1; /* intermediate values for $d(t)$ calculation */
10684 integer ss = 0; /* the part of the dot product computed so far */
10685 int d_sign; /* sign of overall change in direction for this cubic */
10686
10687 @ If the cubic almost has a cusp, it is a numerically ill-conditioned
10688 problem to decide which way it loops around but that's OK as long we're
10689 consistent.  To make \&{doublepath} envelopes work properly, reversing
10690 the path should always change the sign of |turn_amt|.
10691
10692 @<Decide on the net change in pen offsets and set |turn_amt|@>=
10693 d_sign=mp_ab_vs_cd(mp, dx,dyin, dxin,dy);
10694 if ( d_sign==0 ) {
10695   if ( dx==0 ) {
10696     if ( dy>0 ) d_sign=1;  else d_sign=-1;
10697   } else if ( dx>0 ) { 
10698     d_sign=1;  
10699   } else { 
10700     d_sign=-1; 
10701   }
10702 }
10703 @<Make |ss| negative if and only if the total change in direction is
10704   more than $180^\circ$@>;
10705 turn_amt=mp_get_turn_amt(mp, w, dxin, dyin, d_sign>0);
10706 if ( ss<0 ) turn_amt=turn_amt-d_sign*n
10707
10708 @ In order to be invariant under path reversal, the result of this computation
10709 should not change when |x0|, |y0|, $\ldots$ are all negated and |(x0,y0)| is
10710 then swapped with |(x2,y2)|.  We make use of the identities
10711 |take_fraction(-a,-b)=take_fraction(a,b)| and
10712 |t_of_the_way(-a,-b)=-(t_of_the_way(a,b))|.
10713
10714 @<Make |ss| negative if and only if the total change in direction is...@>=
10715 t0=half(mp_take_fraction(mp, x0,y2))-half(mp_take_fraction(mp, x2,y0));
10716 t1=half(mp_take_fraction(mp, x1,y0+y2))-half(mp_take_fraction(mp, y1,x0+x2));
10717 if ( t0==0 ) t0=d_sign; /* path reversal always negates |d_sign| */
10718 if ( t0>0 ) {
10719   t=mp_crossing_point(mp, t0,t1,-t0);
10720   u0=t_of_the_way(x0,x1);
10721   u1=t_of_the_way(x1,x2);
10722   v0=t_of_the_way(y0,y1);
10723   v1=t_of_the_way(y1,y2);
10724 } else { 
10725   t=mp_crossing_point(mp, -t0,t1,t0);
10726   u0=t_of_the_way(x2,x1);
10727   u1=t_of_the_way(x1,x0);
10728   v0=t_of_the_way(y2,y1);
10729   v1=t_of_the_way(y1,y0);
10730 }
10731 s=mp_take_fraction(mp, x0+x2,t_of_the_way(u0,u1))+
10732   mp_take_fraction(mp, y0+y2,t_of_the_way(v0,v1))
10733
10734 @ Here's a routine that prints an envelope spec in symbolic form.  It assumes
10735 that the |cur_pen| has not been walked around to the first offset.
10736
10737 @c 
10738 void mp_print_spec (MP mp,pointer cur_spec, pointer cur_pen, char *s) {
10739   pointer p,q; /* list traversal */
10740   pointer w; /* the current pen offset */
10741   mp_print_diagnostic(mp, "Envelope spec",s,true);
10742   p=cur_spec; w=mp_pen_walk(mp, cur_pen,mp->spec_offset);
10743   mp_print_ln(mp);
10744   mp_print_two(mp, x_coord(cur_spec),y_coord(cur_spec));
10745   mp_print(mp, " % beginning with offset ");
10746   mp_print_two(mp, x_coord(w),y_coord(w));
10747   do { 
10748     do {  
10749       q=link(p);
10750       @<Print the cubic between |p| and |q|@>;
10751       p=q;
10752     } while (! ((p==cur_spec) || (info(p)!=zero_off)));
10753     if ( info(p)!=zero_off ) {
10754       @<Update |w| as indicated by |info(p)| and print an explanation@>;
10755     }
10756   } while (p!=cur_spec);
10757   mp_print_nl(mp, " & cycle");
10758   mp_end_diagnostic(mp, true);
10759 }
10760
10761 @ @<Update |w| as indicated by |info(p)| and print an explanation@>=
10762
10763   w=mp_pen_walk(mp, w,info(p)-zero_off);
10764   mp_print(mp, " % ");
10765   if ( info(p)>zero_off ) mp_print(mp, "counter");
10766   mp_print(mp, "clockwise to offset ");
10767   mp_print_two(mp, x_coord(w),y_coord(w));
10768 }
10769
10770 @ @<Print the cubic between |p| and |q|@>=
10771
10772   mp_print_nl(mp, "   ..controls ");
10773   mp_print_two(mp, right_x(p),right_y(p));
10774   mp_print(mp, " and ");
10775   mp_print_two(mp, left_x(q),left_y(q));
10776   mp_print_nl(mp, " ..");
10777   mp_print_two(mp, x_coord(q),y_coord(q));
10778 }
10779
10780 @ Once we have an envelope spec, the remaining task to construct the actual
10781 envelope by offsetting each cubic as determined by the |info| fields in
10782 the knots.  First we use |offset_prep| to convert the |c| into an envelope
10783 spec. Then we add the offsets so that |c| becomes a cyclic path that represents
10784 the envelope.
10785
10786 The |ljoin| and |miterlim| parameters control the treatment of points where the
10787 pen offset changes, and |lcap| controls the endpoints of a \&{doublepath}.
10788 The endpoints are easily located because |c| is given in undoubled form
10789 and then doubled in this procedure.  We use |spec_p1| and |spec_p2| to keep
10790 track of the endpoints and treat them like very sharp corners.
10791 Butt end caps are treated like beveled joins; round end caps are treated like
10792 round joins; and square end caps are achieved by setting |join_type:=3|.
10793
10794 None of these parameters apply to inside joins where the convolution tracing
10795 has retrograde lines.  In such cases we use a simple connect-the-endpoints
10796 approach that is achieved by setting |join_type:=2|.
10797
10798 @c @<Declare a function called |insert_knot|@>;
10799 pointer mp_make_envelope (MP mp,pointer c, pointer h, small_number ljoin,
10800   small_number lcap, scaled miterlim) {
10801   pointer p,q,r,q0; /* for manipulating the path */
10802   int join_type=0; /* codes |0..3| for mitered, round, beveled, or square */
10803   pointer w,w0; /* the pen knot for the current offset */
10804   scaled qx,qy; /* unshifted coordinates of |q| */
10805   halfword k,k0; /* controls pen edge insertion */
10806   @<Other local variables for |make_envelope|@>;
10807   dxin=0; dyin=0; dxout=0; dyout=0;
10808   mp->spec_p1=null; mp->spec_p2=null;
10809   @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>;
10810   @<Use |offset_prep| to compute the envelope spec then walk |h| around to
10811     the initial offset@>;
10812   w=h;
10813   p=c;
10814   do {  
10815     q=link(p); q0=q;
10816     qx=x_coord(q); qy=y_coord(q);
10817     k=info(q);
10818     k0=k; w0=w;
10819     if ( k!=zero_off ) {
10820       @<Set |join_type| to indicate how to handle offset changes at~|q|@>;
10821     }
10822     @<Add offset |w| to the cubic from |p| to |q|@>;
10823     while ( k!=zero_off ) { 
10824       @<Step |w| and move |k| one step closer to |zero_off|@>;
10825       if ( (join_type==1)||(k==zero_off) )
10826          q=mp_insert_knot(mp, q,qx+x_coord(w),qy+y_coord(w));
10827     };
10828     if ( q!=link(p) ) {
10829       @<Set |p=link(p)| and add knots between |p| and |q| as
10830         required by |join_type|@>;
10831     }
10832     p=q;
10833   } while (q0!=c);
10834   return c;
10835 }
10836
10837 @ @<Use |offset_prep| to compute the envelope spec then walk |h| around to...@>=
10838 c=mp_offset_prep(mp, c,h);
10839 if ( mp->internal[tracing_specs]>0 ) 
10840   mp_print_spec(mp, c,h,"");
10841 h=mp_pen_walk(mp, h,mp->spec_offset)
10842
10843 @ Mitered and squared-off joins depend on path directions that are difficult to
10844 compute for degenerate cubics.  The envelope spec computed by |offset_prep| can
10845 have degenerate cubics only if the entire cycle collapses to a single
10846 degenerate cubic.  Setting |join_type:=2| in this case makes the computed
10847 envelope degenerate as well.
10848
10849 @<Set |join_type| to indicate how to handle offset changes at~|q|@>=
10850 if ( k<zero_off ) {
10851   join_type=2;
10852 } else {
10853   if ( (q!=mp->spec_p1)&&(q!=mp->spec_p2) ) join_type=ljoin;
10854   else if ( lcap==2 ) join_type=3;
10855   else join_type=2-lcap;
10856   if ( (join_type==0)||(join_type==3) ) {
10857     @<Set the incoming and outgoing directions at |q|; in case of
10858       degeneracy set |join_type:=2|@>;
10859     if ( join_type==0 ) {
10860       @<If |miterlim| is less than the secant of half the angle at |q|
10861         then set |join_type:=2|@>;
10862     }
10863   }
10864 }
10865
10866 @ @<If |miterlim| is less than the secant of half the angle at |q|...@>=
10867
10868   tmp=mp_take_fraction(mp, miterlim,fraction_half+
10869       half(mp_take_fraction(mp, dxin,dxout)+mp_take_fraction(mp, dyin,dyout)));
10870   if ( tmp<unity )
10871     if ( mp_take_scaled(mp, miterlim,tmp)<unity ) join_type=2;
10872 }
10873
10874 @ @<Other local variables for |make_envelope|@>=
10875 fraction dxin,dyin,dxout,dyout; /* directions at |q| when square or mitered */
10876 scaled tmp; /* a temporary value */
10877
10878 @ The coordinates of |p| have already been shifted unless |p| is the first
10879 knot in which case they get shifted at the very end.
10880
10881 @<Add offset |w| to the cubic from |p| to |q|@>=
10882 right_x(p)=right_x(p)+x_coord(w);
10883 right_y(p)=right_y(p)+y_coord(w);
10884 left_x(q)=left_x(q)+x_coord(w);
10885 left_y(q)=left_y(q)+y_coord(w);
10886 x_coord(q)=x_coord(q)+x_coord(w);
10887 y_coord(q)=y_coord(q)+y_coord(w);
10888 left_type(q)=explicit;
10889 right_type(q)=explicit
10890
10891 @ @<Step |w| and move |k| one step closer to |zero_off|@>=
10892 if ( k>zero_off ){ w=link(w); decr(k);  }
10893 else { w=knil(w); incr(k);  }
10894
10895 @ The cubic from |q| to the new knot at |(x,y)| becomes a line segment and
10896 the |right_x| and |right_y| fields of |r| are set from |q|.  This is done in
10897 case the cubic containing these control points is ``yet to be examined.''
10898
10899 @<Declare a function called |insert_knot|@>=
10900 pointer mp_insert_knot (MP mp,pointer q, scaled x, scaled y) {
10901   /* returns the inserted knot */
10902   pointer r; /* the new knot */
10903   r=mp_get_node(mp, knot_node_size);
10904   link(r)=link(q); link(q)=r;
10905   right_x(r)=right_x(q);
10906   right_y(r)=right_y(q);
10907   x_coord(r)=x;
10908   y_coord(r)=y;
10909   right_x(q)=x_coord(q);
10910   right_y(q)=y_coord(q);
10911   left_x(r)=x_coord(r);
10912   left_y(r)=y_coord(r);
10913   left_type(r)=explicit;
10914   right_type(r)=explicit;
10915   originator(r)=program_code;
10916   return r;
10917 }
10918
10919 @ After setting |p:=link(p)|, either |join_type=1| or |q=link(p)|.
10920
10921 @<Set |p=link(p)| and add knots between |p| and |q| as...@>=
10922
10923   p=link(p);
10924   if ( (join_type==0)||(join_type==3) ) {
10925     if ( join_type==0 ) {
10926       @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>
10927     } else {
10928       @<Make |r| the last of two knots inserted between |p| and |q| to form a
10929         squared join@>;
10930     }
10931     if ( r!=null ) { 
10932       right_x(r)=x_coord(r);
10933       right_y(r)=y_coord(r);
10934     }
10935   }
10936 }
10937
10938 @ For very small angles, adding a knot is unnecessary and would cause numerical
10939 problems, so we just set |r:=null| in that case.
10940
10941 @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>=
10942
10943   det=mp_take_fraction(mp, dyout,dxin)-mp_take_fraction(mp, dxout,dyin);
10944   if ( abs(det)<26844 ) { 
10945      r=null; /* sine $<10^{-4}$ */
10946   } else { 
10947     tmp=mp_take_fraction(mp, x_coord(q)-x_coord(p),dyout)-
10948         mp_take_fraction(mp, y_coord(q)-y_coord(p),dxout);
10949     tmp=mp_make_fraction(mp, tmp,det);
10950     r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
10951       y_coord(p)+mp_take_fraction(mp, tmp,dyin));
10952   }
10953 }
10954
10955 @ @<Other local variables for |make_envelope|@>=
10956 fraction det; /* a determinant used for mitered join calculations */
10957
10958 @ @<Make |r| the last of two knots inserted between |p| and |q| to form a...@>=
10959
10960   ht_x=y_coord(w)-y_coord(w0);
10961   ht_y=x_coord(w0)-x_coord(w);
10962   while ( (abs(ht_x)<fraction_half)&&(abs(ht_y)<fraction_half) ) { 
10963     ht_x+=ht_x; ht_y+=ht_y;
10964   }
10965   @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range dot
10966     product with |(ht_x,ht_y)|@>;
10967   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxin,ht_x)+
10968                                   mp_take_fraction(mp, dyin,ht_y));
10969   r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
10970                          y_coord(p)+mp_take_fraction(mp, tmp,dyin));
10971   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxout,ht_x)+
10972                                   mp_take_fraction(mp, dyout,ht_y));
10973   r=mp_insert_knot(mp, r,x_coord(q)+mp_take_fraction(mp, tmp,dxout),
10974                          y_coord(q)+mp_take_fraction(mp, tmp,dyout));
10975 }
10976
10977 @ @<Other local variables for |make_envelope|@>=
10978 fraction ht_x,ht_y; /* perpendicular to the segment from |p| to |q| */
10979 scaled max_ht; /* maximum height of the pen polygon above the |w0|-|w| line */
10980 halfword kk; /* keeps track of the pen vertices being scanned */
10981 pointer ww; /* the pen vertex being tested */
10982
10983 @ The dot product of the vector from |w0| to |ww| with |(ht_x,ht_y)| ranges
10984 from zero to |max_ht|.
10985
10986 @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range...@>=
10987 max_ht=0;
10988 kk=zero_off;
10989 ww=w;
10990 while (1)  { 
10991   @<Step |ww| and move |kk| one step closer to |k0|@>;
10992   if ( kk==k0 ) break;
10993   tmp=mp_take_fraction(mp, x_coord(ww)-x_coord(w0),ht_x)+
10994       mp_take_fraction(mp, y_coord(ww)-y_coord(w0),ht_y);
10995   if ( tmp>max_ht ) max_ht=tmp;
10996 }
10997
10998
10999 @ @<Step |ww| and move |kk| one step closer to |k0|@>=
11000 if ( kk>k0 ) { ww=link(ww); decr(kk);  }
11001 else { ww=knil(ww); incr(kk);  }
11002
11003 @ @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>=
11004 if ( left_type(c)==endpoint ) { 
11005   mp->spec_p1=mp_htap_ypoc(mp, c);
11006   mp->spec_p2=mp->path_tail;
11007   originator(mp->spec_p1)=program_code;
11008   link(mp->spec_p2)=link(mp->spec_p1);
11009   link(mp->spec_p1)=c;
11010   mp_remove_cubic(mp, mp->spec_p1);
11011   c=mp->spec_p1;
11012   if ( c!=link(c) ) {
11013     originator(mp->spec_p2)=program_code;
11014     mp_remove_cubic(mp, mp->spec_p2);
11015   } else {
11016     @<Make |c| look like a cycle of length one@>;
11017   }
11018 }
11019
11020 @ @<Make |c| look like a cycle of length one@>=
11021
11022   left_type(c)=explicit; right_type(c)=explicit;
11023   left_x(c)=x_coord(c); left_y(c)=y_coord(c);
11024   right_x(c)=x_coord(c); right_y(c)=y_coord(c);
11025 }
11026
11027 @ In degenerate situations we might have to look at the knot preceding~|q|.
11028 That knot is |p| but if |p<>c|, its coordinates have already been offset by |w|.
11029
11030 @<Set the incoming and outgoing directions at |q|; in case of...@>=
11031 dxin=x_coord(q)-left_x(q);
11032 dyin=y_coord(q)-left_y(q);
11033 if ( (dxin==0)&&(dyin==0) ) {
11034   dxin=x_coord(q)-right_x(p);
11035   dyin=y_coord(q)-right_y(p);
11036   if ( (dxin==0)&&(dyin==0) ) {
11037     dxin=x_coord(q)-x_coord(p);
11038     dyin=y_coord(q)-y_coord(p);
11039     if ( p!=c ) { /* the coordinates of |p| have been offset by |w| */
11040       dxin=dxin+x_coord(w);
11041       dyin=dyin+y_coord(w);
11042     }
11043   }
11044 }
11045 tmp=mp_pyth_add(mp, dxin,dyin);
11046 if ( tmp==0 ) {
11047   join_type=2;
11048 } else { 
11049   dxin=mp_make_fraction(mp, dxin,tmp);
11050   dyin=mp_make_fraction(mp, dyin,tmp);
11051   @<Set the outgoing direction at |q|@>;
11052 }
11053
11054 @ If |q=c| then the coordinates of |r| and the control points between |q|
11055 and~|r| have already been offset by |h|.
11056
11057 @<Set the outgoing direction at |q|@>=
11058 dxout=right_x(q)-x_coord(q);
11059 dyout=right_y(q)-y_coord(q);
11060 if ( (dxout==0)&&(dyout==0) ) {
11061   r=link(q);
11062   dxout=left_x(r)-x_coord(q);
11063   dyout=left_y(r)-y_coord(q);
11064   if ( (dxout==0)&&(dyout==0) ) {
11065     dxout=x_coord(r)-x_coord(q);
11066     dyout=y_coord(r)-y_coord(q);
11067   }
11068 }
11069 if ( q==c ) {
11070   dxout=dxout-x_coord(h);
11071   dyout=dyout-y_coord(h);
11072 }
11073 tmp=mp_pyth_add(mp, dxout,dyout);
11074 if ( tmp==0 ) mp_confusion(mp, "degenerate spec");
11075 @:this can't happen degerate spec}{\quad degenerate spec@>
11076 dxout=mp_make_fraction(mp, dxout,tmp);
11077 dyout=mp_make_fraction(mp, dyout,tmp)
11078
11079 @* \[23] Direction and intersection times.
11080 A path of length $n$ is defined parametrically by functions $x(t)$ and
11081 $y(t)$, for |0<=t<=n|; we can regard $t$ as the ``time'' at which the path
11082 reaches the point $\bigl(x(t),y(t)\bigr)$.  In this section of the program
11083 we shall consider operations that determine special times associated with
11084 given paths: the first time that a path travels in a given direction, and
11085 a pair of times at which two paths cross each other.
11086
11087 @ Let's start with the easier task. The function |find_direction_time| is
11088 given a direction |(x,y)| and a path starting at~|h|. If the path never
11089 travels in direction |(x,y)|, the direction time will be~|-1|; otherwise
11090 it will be nonnegative.
11091
11092 Certain anomalous cases can arise: If |(x,y)=(0,0)|, so that the given
11093 direction is undefined, the direction time will be~0. If $\bigl(x'(t),
11094 y'(t)\bigr)=(0,0)$, so that the path direction is undefined, it will be
11095 assumed to match any given direction at time~|t|.
11096
11097 The routine solves this problem in nondegenerate cases by rotating the path
11098 and the given direction so that |(x,y)=(1,0)|; i.e., the main task will be
11099 to find when a given path first travels ``due east.''
11100
11101 @c 
11102 scaled mp_find_direction_time (MP mp,scaled x, scaled y, pointer h) {
11103   scaled max; /* $\max\bigl(\vert x\vert,\vert y\vert\bigr)$ */
11104   pointer p,q; /* for list traversal */
11105   scaled n; /* the direction time at knot |p| */
11106   scaled tt; /* the direction time within a cubic */
11107   @<Other local variables for |find_direction_time|@>;
11108   @<Normalize the given direction for better accuracy;
11109     but |return| with zero result if it's zero@>;
11110   n=0; p=h; phi=0;
11111   while (1) { 
11112     if ( right_type(p)==endpoint ) break;
11113     q=link(p);
11114     @<Rotate the cubic between |p| and |q|; then
11115       |goto found| if the rotated cubic travels due east at some time |tt|;
11116       but |break| if an entire cyclic path has been traversed@>;
11117     p=q; n=n+unity;
11118   }
11119   return (-unity);
11120 FOUND: 
11121   return (n+tt);
11122 }
11123
11124 @ @<Normalize the given direction for better accuracy...@>=
11125 if ( abs(x)<abs(y) ) { 
11126   x=mp_make_fraction(mp, x,abs(y));
11127   if ( y>0 ) y=fraction_one; else y=-fraction_one;
11128 } else if ( x==0 ) { 
11129   return 0;
11130 } else  { 
11131   y=mp_make_fraction(mp, y,abs(x));
11132   if ( x>0 ) x=fraction_one; else x=-fraction_one;
11133 }
11134
11135 @ Since we're interested in the tangent directions, we work with the
11136 derivative $${\textstyle1\over3}B'(x_0,x_1,x_2,x_3;t)=
11137 B(x_1-x_0,x_2-x_1,x_3-x_2;t)$$ instead of
11138 $B(x_0,x_1,x_2,x_3;t)$ itself. The derived coefficients are also scaled up
11139 in order to achieve better accuracy.
11140
11141 The given path may turn abruptly at a knot, and it might pass the critical
11142 tangent direction at such a time. Therefore we remember the direction |phi|
11143 in which the previous rotated cubic was traveling. (The value of |phi| will be
11144 undefined on the first cubic, i.e., when |n=0|.)
11145
11146 @<Rotate the cubic between |p| and |q|; then...@>=
11147 tt=0;
11148 @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples of the control
11149   points of the rotated derivatives@>;
11150 if ( y1==0 ) if ( x1>=0 ) goto FOUND;
11151 if ( n>0 ) { 
11152   @<Exit to |found| if an eastward direction occurs at knot |p|@>;
11153   if ( p==h ) break;
11154   };
11155 if ( (x3!=0)||(y3!=0) ) phi=mp_n_arg(mp, x3,y3);
11156 @<Exit to |found| if the curve whose derivatives are specified by
11157   |x1,x2,x3,y1,y2,y3| travels eastward at some time~|tt|@>
11158
11159 @ @<Other local variables for |find_direction_time|@>=
11160 scaled x1,x2,x3,y1,y2,y3;  /* multiples of rotated derivatives */
11161 angle theta,phi; /* angles of exit and entry at a knot */
11162 fraction t; /* temp storage */
11163
11164 @ @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples...@>=
11165 x1=right_x(p)-x_coord(p); x2=left_x(q)-right_x(p);
11166 x3=x_coord(q)-left_x(q);
11167 y1=right_y(p)-y_coord(p); y2=left_y(q)-right_y(p);
11168 y3=y_coord(q)-left_y(q);
11169 max=abs(x1);
11170 if ( abs(x2)>max ) max=abs(x2);
11171 if ( abs(x3)>max ) max=abs(x3);
11172 if ( abs(y1)>max ) max=abs(y1);
11173 if ( abs(y2)>max ) max=abs(y2);
11174 if ( abs(y3)>max ) max=abs(y3);
11175 if ( max==0 ) goto FOUND;
11176 while ( max<fraction_half ){ 
11177   max+=max; x1+=x1; x2+=x2; x3+=x3;
11178   y1+=y1; y2+=y2; y3+=y3;
11179 }
11180 t=x1; x1=mp_take_fraction(mp, x1,x)+mp_take_fraction(mp, y1,y);
11181 y1=mp_take_fraction(mp, y1,x)-mp_take_fraction(mp, t,y);
11182 t=x2; x2=mp_take_fraction(mp, x2,x)+mp_take_fraction(mp, y2,y);
11183 y2=mp_take_fraction(mp, y2,x)-mp_take_fraction(mp, t,y);
11184 t=x3; x3=mp_take_fraction(mp, x3,x)+mp_take_fraction(mp, y3,y);
11185 y3=mp_take_fraction(mp, y3,x)-mp_take_fraction(mp, t,y)
11186
11187 @ @<Exit to |found| if an eastward direction occurs at knot |p|@>=
11188 theta=mp_n_arg(mp, x1,y1);
11189 if ( theta>=0 ) if ( phi<=0 ) if ( phi>=theta-one_eighty_deg ) goto FOUND;
11190 if ( theta<=0 ) if ( phi>=0 ) if ( phi<=theta+one_eighty_deg ) goto FOUND
11191
11192 @ In this step we want to use the |crossing_point| routine to find the
11193 roots of the quadratic equation $B(y_1,y_2,y_3;t)=0$.
11194 Several complications arise: If the quadratic equation has a double root,
11195 the curve never crosses zero, and |crossing_point| will find nothing;
11196 this case occurs iff $y_1y_3=y_2^2$ and $y_1y_2<0$. If the quadratic
11197 equation has simple roots, or only one root, we may have to negate it
11198 so that $B(y_1,y_2,y_3;t)$ crosses from positive to negative at its first root.
11199 And finally, we need to do special things if $B(y_1,y_2,y_3;t)$ is
11200 identically zero.
11201
11202 @ @<Exit to |found| if the curve whose derivatives are specified by...@>=
11203 if ( x1<0 ) if ( x2<0 ) if ( x3<0 ) goto DONE;
11204 if ( mp_ab_vs_cd(mp, y1,y3,y2,y2)==0 ) {
11205   @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11206     either |goto found| or |goto done|@>;
11207 }
11208 if ( y1<=0 ) {
11209   if ( y1<0 ) { y1=-y1; y2=-y2; y3=-y3; }
11210   else if ( y2>0 ){ y2=-y2; y3=-y3; };
11211 }
11212 @<Check the places where $B(y_1,y_2,y_3;t)=0$ to see if
11213   $B(x_1,x_2,x_3;t)\ge0$@>;
11214 DONE:
11215
11216 @ The quadratic polynomial $B(y_1,y_2,y_3;t)$ begins |>=0| and has at most
11217 two roots, because we know that it isn't identically zero.
11218
11219 It must be admitted that the |crossing_point| routine is not perfectly accurate;
11220 rounding errors might cause it to find a root when $y_1y_3>y_2^2$, or to
11221 miss the roots when $y_1y_3<y_2^2$. The rotation process is itself
11222 subject to rounding errors. Yet this code optimistically tries to
11223 do the right thing.
11224
11225 @d we_found_it { tt=(t+04000) / 010000; goto FOUND; }
11226
11227 @<Check the places where $B(y_1,y_2,y_3;t)=0$...@>=
11228 t=mp_crossing_point(mp, y1,y2,y3);
11229 if ( t>fraction_one ) goto DONE;
11230 y2=t_of_the_way(y2,y3);
11231 x1=t_of_the_way(x1,x2);
11232 x2=t_of_the_way(x2,x3);
11233 x1=t_of_the_way(x1,x2);
11234 if ( x1>=0 ) we_found_it;
11235 if ( y2>0 ) y2=0;
11236 tt=t; t=mp_crossing_point(mp, 0,-y2,-y3);
11237 if ( t>fraction_one ) goto DONE;
11238 x1=t_of_the_way(x1,x2);
11239 x2=t_of_the_way(x2,x3);
11240 if ( t_of_the_way(x1,x2)>=0 ) { 
11241   t=t_of_the_way(tt,fraction_one); we_found_it;
11242 }
11243
11244 @ @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11245     either |goto found| or |goto done|@>=
11246
11247   if ( mp_ab_vs_cd(mp, y1,y2,0,0)<0 ) {
11248     t=mp_make_fraction(mp, y1,y1-y2);
11249     x1=t_of_the_way(x1,x2);
11250     x2=t_of_the_way(x2,x3);
11251     if ( t_of_the_way(x1,x2)>=0 ) we_found_it;
11252   } else if ( y3==0 ) {
11253     if ( y1==0 ) {
11254       @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|@>;
11255     } else if ( x3>=0 ) {
11256       tt=unity; goto FOUND;
11257     }
11258   }
11259   goto DONE;
11260 }
11261
11262 @ At this point we know that the derivative of |y(t)| is identically zero,
11263 and that |x1<0|; but either |x2>=0| or |x3>=0|, so there's some hope of
11264 traveling east.
11265
11266 @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|...@>=
11267
11268   t=mp_crossing_point(mp, -x1,-x2,-x3);
11269   if ( t<=fraction_one ) we_found_it;
11270   if ( mp_ab_vs_cd(mp, x1,x3,x2,x2)<=0 ) { 
11271     t=mp_make_fraction(mp, x1,x1-x2); we_found_it;
11272   }
11273 }
11274
11275 @ The intersection of two cubics can be found by an interesting variant
11276 of the general bisection scheme described in the introduction to
11277 |crossing_point|.\
11278 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)$,
11279 we wish to find a pair of times $(t_1,t_2)$ such that $w(t_1)=z(t_2)$,
11280 if an intersection exists. First we find the smallest rectangle that
11281 encloses the points $\{w_0,w_1,w_2,w_3\}$ and check that it overlaps
11282 the smallest rectangle that encloses
11283 $\{z_0,z_1,z_2,z_3\}$; if not, the cubics certainly don't intersect.
11284 But if the rectangles do overlap, we bisect the intervals, getting
11285 new cubics $w'$ and~$w''$, $z'$~and~$z''$; the intersection routine first
11286 tries for an intersection between $w'$ and~$z'$, then (if unsuccessful)
11287 between $w'$ and~$z''$, then (if still unsuccessful) between $w''$ and~$z'$,
11288 finally (if thrice unsuccessful) between $w''$ and~$z''$. After $l$~successful
11289 levels of bisection we will have determined the intersection times $t_1$
11290 and~$t_2$ to $l$~bits of accuracy.
11291
11292 \def\submin{_{\rm min}} \def\submax{_{\rm max}}
11293 As before, it is better to work with the numbers $W_k=2^l(w_k-w_{k-1})$
11294 and $Z_k=2^l(z_k-z_{k-1})$ rather than the coefficients $w_k$ and $z_k$
11295 themselves. We also need one other quantity, $\Delta=2^l(w_0-z_0)$,
11296 to determine when the enclosing rectangles overlap. Here's why:
11297 The $x$~coordinates of~$w(t)$ are between $u\submin$ and $u\submax$,
11298 and the $x$~coordinates of~$z(t)$ are between $x\submin$ and $x\submax$,
11299 if we write $w_k=(u_k,v_k)$ and $z_k=(x_k,y_k)$ and $u\submin=
11300 \min(u_0,u_1,u_2,u_3)$, etc. These intervals of $x$~coordinates
11301 overlap if and only if $u\submin\L x\submax$ and
11302 $x\submin\L u\submax$. Letting
11303 $$U\submin=\min(0,U_1,U_1+U_2,U_1+U_2+U_3),\;
11304   U\submax=\max(0,U_1,U_1+U_2,U_1+U_2+U_3),$$
11305 we have $u\submin=2^lu_0+U\submin$, etc.; the condition for overlap
11306 reduces to
11307 $$X\submin-U\submax\L 2^l(u_0-x_0)\L X\submax-U\submin.$$
11308 Thus we want to maintain the quantity $2^l(u_0-x_0)$; similarly,
11309 the quantity $2^l(v_0-y_0)$ accounts for the $y$~coordinates. The
11310 coordinates of $\Delta=2^l(w_0-z_0)$ must stay bounded as $l$ increases,
11311 because of the overlap condition; i.e., we know that $X\submin$,
11312 $X\submax$, and their relatives are bounded, hence $X\submax-
11313 U\submin$ and $X\submin-U\submax$ are bounded.
11314
11315 @ Incidentally, if the given cubics intersect more than once, the process
11316 just sketched will not necessarily find the lexicographically smallest pair
11317 $(t_1,t_2)$. The solution actually obtained will be smallest in ``shuffled
11318 order''; i.e., if $t_1=(.a_1a_2\ldots a_{16})_2$ and
11319 $t_2=(.b_1b_2\ldots b_{16})_2$, then we will minimize
11320 $a_1b_1a_2b_2\ldots a_{16}b_{16}$, not
11321 $a_1a_2\ldots a_{16}b_1b_2\ldots b_{16}$.
11322 Shuffled order agrees with lexicographic order if all pairs of solutions
11323 $(t_1,t_2)$ and $(t_1',t_2')$ have the property that $t_1<t_1'$ iff
11324 $t_2<t_2'$; but in general, lexicographic order can be quite different,
11325 and the bisection algorithm would be substantially less efficient if it were
11326 constrained by lexicographic order.
11327
11328 For example, suppose that an overlap has been found for $l=3$ and
11329 $(t_1,t_2)= (.101,.011)$ in binary, but that no overlap is produced by
11330 either of the alternatives $(.1010,.0110)$, $(.1010,.0111)$ at level~4.
11331 Then there is probably an intersection in one of the subintervals
11332 $(.1011,.011x)$; but lexicographic order would require us to explore
11333 $(.1010,.1xxx)$ and $(.1011,.00xx)$ and $(.1011,.010x)$ first. We wouldn't
11334 want to store all of the subdivision data for the second path, so the
11335 subdivisions would have to be regenerated many times. Such inefficiencies
11336 would be associated with every `1' in the binary representation of~$t_1$.
11337
11338 @ The subdivision process introduces rounding errors, hence we need to
11339 make a more liberal test for overlap. It is not hard to show that the
11340 computed values of $U_i$ differ from the truth by at most~$l$, on
11341 level~$l$, hence $U\submin$ and $U\submax$ will be at most $3l$ in error.
11342 If $\beta$ is an upper bound on the absolute error in the computed
11343 components of $\Delta=(|delx|,|dely|)$ on level~$l$, we will replace
11344 the test `$X\submin-U\submax\L|delx|$' by the more liberal test
11345 `$X\submin-U\submax\L|delx|+|tol|$', where $|tol|=6l+\beta$.
11346
11347 More accuracy is obtained if we try the algorithm first with |tol=0|;
11348 the more liberal tolerance is used only if an exact approach fails.
11349 It is convenient to do this double-take by letting `3' in the preceding
11350 paragraph be a parameter, which is first 0, then 3.
11351
11352 @<Glob...@>=
11353 unsigned int tol_step; /* either 0 or 3, usually */
11354
11355 @ We shall use an explicit stack to implement the recursive bisection
11356 method described above. The |bisect_stack| array will contain numerous 5-word
11357 packets like $(U_1,U_2,U_3,U\submin,U\submax)$, as well as 20-word packets
11358 comprising the 5-word packets for $U$, $V$, $X$, and~$Y$.
11359
11360 The following macros define the allocation of stack positions to
11361 the quantities needed for bisection-intersection.
11362
11363 @d stack_1(A) mp->bisect_stack[(A)] /* $U_1$, $V_1$, $X_1$, or $Y_1$ */
11364 @d stack_2(A) mp->bisect_stack[(A)+1] /* $U_2$, $V_2$, $X_2$, or $Y_2$ */
11365 @d stack_3(A) mp->bisect_stack[(A)+2] /* $U_3$, $V_3$, $X_3$, or $Y_3$ */
11366 @d stack_min(A) mp->bisect_stack[(A)+3]
11367   /* $U\submin$, $V\submin$, $X\submin$, or $Y\submin$ */
11368 @d stack_max(A) mp->bisect_stack[(A)+4]
11369   /* $U\submax$, $V\submax$, $X\submax$, or $Y\submax$ */
11370 @d int_packets 20 /* number of words to represent $U_k$, $V_k$, $X_k$, and $Y_k$ */
11371 @#
11372 @d u_packet(A) ((A)-5)
11373 @d v_packet(A) ((A)-10)
11374 @d x_packet(A) ((A)-15)
11375 @d y_packet(A) ((A)-20)
11376 @d l_packets (mp->bisect_ptr-int_packets)
11377 @d r_packets mp->bisect_ptr
11378 @d ul_packet u_packet(l_packets) /* base of $U'_k$ variables */
11379 @d vl_packet v_packet(l_packets) /* base of $V'_k$ variables */
11380 @d xl_packet x_packet(l_packets) /* base of $X'_k$ variables */
11381 @d yl_packet y_packet(l_packets) /* base of $Y'_k$ variables */
11382 @d ur_packet u_packet(r_packets) /* base of $U''_k$ variables */
11383 @d vr_packet v_packet(r_packets) /* base of $V''_k$ variables */
11384 @d xr_packet x_packet(r_packets) /* base of $X''_k$ variables */
11385 @d yr_packet y_packet(r_packets) /* base of $Y''_k$ variables */
11386 @#
11387 @d u1l stack_1(ul_packet) /* $U'_1$ */
11388 @d u2l stack_2(ul_packet) /* $U'_2$ */
11389 @d u3l stack_3(ul_packet) /* $U'_3$ */
11390 @d v1l stack_1(vl_packet) /* $V'_1$ */
11391 @d v2l stack_2(vl_packet) /* $V'_2$ */
11392 @d v3l stack_3(vl_packet) /* $V'_3$ */
11393 @d x1l stack_1(xl_packet) /* $X'_1$ */
11394 @d x2l stack_2(xl_packet) /* $X'_2$ */
11395 @d x3l stack_3(xl_packet) /* $X'_3$ */
11396 @d y1l stack_1(yl_packet) /* $Y'_1$ */
11397 @d y2l stack_2(yl_packet) /* $Y'_2$ */
11398 @d y3l stack_3(yl_packet) /* $Y'_3$ */
11399 @d u1r stack_1(ur_packet) /* $U''_1$ */
11400 @d u2r stack_2(ur_packet) /* $U''_2$ */
11401 @d u3r stack_3(ur_packet) /* $U''_3$ */
11402 @d v1r stack_1(vr_packet) /* $V''_1$ */
11403 @d v2r stack_2(vr_packet) /* $V''_2$ */
11404 @d v3r stack_3(vr_packet) /* $V''_3$ */
11405 @d x1r stack_1(xr_packet) /* $X''_1$ */
11406 @d x2r stack_2(xr_packet) /* $X''_2$ */
11407 @d x3r stack_3(xr_packet) /* $X''_3$ */
11408 @d y1r stack_1(yr_packet) /* $Y''_1$ */
11409 @d y2r stack_2(yr_packet) /* $Y''_2$ */
11410 @d y3r stack_3(yr_packet) /* $Y''_3$ */
11411 @#
11412 @d stack_dx mp->bisect_stack[mp->bisect_ptr] /* stacked value of |delx| */
11413 @d stack_dy mp->bisect_stack[mp->bisect_ptr+1] /* stacked value of |dely| */
11414 @d stack_tol mp->bisect_stack[mp->bisect_ptr+2] /* stacked value of |tol| */
11415 @d stack_uv mp->bisect_stack[mp->bisect_ptr+3] /* stacked value of |uv| */
11416 @d stack_xy mp->bisect_stack[mp->bisect_ptr+4] /* stacked value of |xy| */
11417 @d int_increment (int_packets+int_packets+5) /* number of stack words per level */
11418
11419 @<Glob...@>=
11420 integer *bisect_stack;
11421 unsigned int bisect_ptr;
11422
11423 @ @<Allocate or initialize ...@>=
11424 mp->bisect_stack = xmalloc((bistack_size+1),sizeof(integer));
11425
11426 @ @<Dealloc variables@>=
11427 xfree(mp->bisect_stack);
11428
11429 @ @<Check the ``constant''...@>=
11430 if ( int_packets+17*int_increment>bistack_size ) mp->bad=19;
11431
11432 @ Computation of the min and max is a tedious but fairly fast sequence of
11433 instructions; exactly four comparisons are made in each branch.
11434
11435 @d set_min_max(A) 
11436   if ( stack_1((A))<0 ) {
11437     if ( stack_3((A))>=0 ) {
11438       if ( stack_2((A))<0 ) stack_min((A))=stack_1((A))+stack_2((A));
11439       else stack_min((A))=stack_1((A));
11440       stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11441       if ( stack_max((A))<0 ) stack_max((A))=0;
11442     } else { 
11443       stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11444       if ( stack_min((A))>stack_1((A)) ) stack_min((A))=stack_1((A));
11445       stack_max((A))=stack_1((A))+stack_2((A));
11446       if ( stack_max((A))<0 ) stack_max((A))=0;
11447     }
11448   } else if ( stack_3((A))<=0 ) {
11449     if ( stack_2((A))>0 ) stack_max((A))=stack_1((A))+stack_2((A));
11450     else stack_max((A))=stack_1((A));
11451     stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11452     if ( stack_min((A))>0 ) stack_min((A))=0;
11453   } else  { 
11454     stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11455     if ( stack_max((A))<stack_1((A)) ) stack_max((A))=stack_1((A));
11456     stack_min((A))=stack_1((A))+stack_2((A));
11457     if ( stack_min((A))>0 ) stack_min((A))=0;
11458   }
11459
11460 @ It's convenient to keep the current values of $l$, $t_1$, and $t_2$ in
11461 the integer form $2^l+2^lt_1$ and $2^l+2^lt_2$. The |cubic_intersection|
11462 routine uses global variables |cur_t| and |cur_tt| for this purpose;
11463 after successful completion, |cur_t| and |cur_tt| will contain |unity|
11464 plus the |scaled| values of $t_1$ and~$t_2$.
11465
11466 The values of |cur_t| and |cur_tt| will be set to zero if |cubic_intersection|
11467 finds no intersection. The routine gives up and gives an approximate answer
11468 if it has backtracked
11469 more than 5000 times (otherwise there are cases where several minutes
11470 of fruitless computation would be possible).
11471
11472 @d max_patience 5000
11473
11474 @<Glob...@>=
11475 integer cur_t;integer cur_tt; /* controls and results of |cubic_intersection| */
11476 integer time_to_go; /* this many backtracks before giving up */
11477 integer max_t; /* maximum of $2^{l+1}$ so far achieved */
11478
11479 @ The given cubics $B(w_0,w_1,w_2,w_3;t)$ and
11480 $B(z_0,z_1,z_2,z_3;t)$ are specified in adjacent knot nodes |(p,link(p))|
11481 and |(pp,link(pp))|, respectively.
11482
11483 @c void mp_cubic_intersection (MP mp,pointer p, pointer pp) {
11484   pointer q,qq; /* |link(p)|, |link(pp)| */
11485   mp->time_to_go=max_patience; mp->max_t=2;
11486   @<Initialize for intersections at level zero@>;
11487 CONTINUE:
11488   while (1) { 
11489     if ( mp->delx-mp->tol<=stack_max(x_packet(mp->xy))-stack_min(u_packet(mp->uv)))
11490     if ( mp->delx+mp->tol>=stack_min(x_packet(mp->xy))-stack_max(u_packet(mp->uv)))
11491     if ( mp->dely-mp->tol<=stack_max(y_packet(mp->xy))-stack_min(v_packet(mp->uv)))
11492     if ( mp->dely+mp->tol>=stack_min(y_packet(mp->xy))-stack_max(v_packet(mp->uv))) 
11493     { 
11494       if ( mp->cur_t>=mp->max_t ){ 
11495         if ( mp->max_t==two ) { /* we've done 17 bisections */ 
11496            mp->cur_t=halfp(mp->cur_t+1); mp->cur_tt=halfp(mp->cur_tt+1); return;
11497         }
11498         mp->max_t+=mp->max_t; mp->appr_t=mp->cur_t; mp->appr_tt=mp->cur_tt;
11499       }
11500       @<Subdivide for a new level of intersection@>;
11501       goto CONTINUE;
11502     }
11503     if ( mp->time_to_go>0 ) {
11504       decr(mp->time_to_go);
11505     } else { 
11506       while ( mp->appr_t<unity ) { 
11507         mp->appr_t+=mp->appr_t; mp->appr_tt+=mp->appr_tt;
11508       }
11509       mp->cur_t=mp->appr_t; mp->cur_tt=mp->appr_tt; return;
11510     }
11511     @<Advance to the next pair |(cur_t,cur_tt)|@>;
11512   }
11513 }
11514
11515 @ The following variables are global, although they are used only by
11516 |cubic_intersection|, because it is necessary on some machines to
11517 split |cubic_intersection| up into two procedures.
11518
11519 @<Glob...@>=
11520 integer delx;integer dely; /* the components of $\Delta=2^l(w_0-z_0)$ */
11521 integer tol; /* bound on the uncertainly in the overlap test */
11522 unsigned int uv;
11523 unsigned int xy; /* pointers to the current packets of interest */
11524 integer three_l; /* |tol_step| times the bisection level */
11525 integer appr_t;integer appr_tt; /* best approximations known to the answers */
11526
11527 @ We shall assume that the coordinates are sufficiently non-extreme that
11528 integer overflow will not occur.
11529
11530 @<Initialize for intersections at level zero@>=
11531 q=link(p); qq=link(pp); mp->bisect_ptr=int_packets;
11532 u1r=right_x(p)-x_coord(p); u2r=left_x(q)-right_x(p);
11533 u3r=x_coord(q)-left_x(q); set_min_max(ur_packet);
11534 v1r=right_y(p)-y_coord(p); v2r=left_y(q)-right_y(p);
11535 v3r=y_coord(q)-left_y(q); set_min_max(vr_packet);
11536 x1r=right_x(pp)-x_coord(pp); x2r=left_x(qq)-right_x(pp);
11537 x3r=x_coord(qq)-left_x(qq); set_min_max(xr_packet);
11538 y1r=right_y(pp)-y_coord(pp); y2r=left_y(qq)-right_y(pp);
11539 y3r=y_coord(qq)-left_y(qq); set_min_max(yr_packet);
11540 mp->delx=x_coord(p)-x_coord(pp); mp->dely=y_coord(p)-y_coord(pp);
11541 mp->tol=0; mp->uv=r_packets; mp->xy=r_packets; 
11542 mp->three_l=0; mp->cur_t=1; mp->cur_tt=1
11543
11544 @ @<Subdivide for a new level of intersection@>=
11545 stack_dx=mp->delx; stack_dy=mp->dely; stack_tol=mp->tol; 
11546 stack_uv=mp->uv; stack_xy=mp->xy;
11547 mp->bisect_ptr=mp->bisect_ptr+int_increment;
11548 mp->cur_t+=mp->cur_t; mp->cur_tt+=mp->cur_tt;
11549 u1l=stack_1(u_packet(mp->uv)); u3r=stack_3(u_packet(mp->uv));
11550 u2l=half(u1l+stack_2(u_packet(mp->uv)));
11551 u2r=half(u3r+stack_2(u_packet(mp->uv)));
11552 u3l=half(u2l+u2r); u1r=u3l;
11553 set_min_max(ul_packet); set_min_max(ur_packet);
11554 v1l=stack_1(v_packet(mp->uv)); v3r=stack_3(v_packet(mp->uv));
11555 v2l=half(v1l+stack_2(v_packet(mp->uv)));
11556 v2r=half(v3r+stack_2(v_packet(mp->uv)));
11557 v3l=half(v2l+v2r); v1r=v3l;
11558 set_min_max(vl_packet); set_min_max(vr_packet);
11559 x1l=stack_1(x_packet(mp->xy)); x3r=stack_3(x_packet(mp->xy));
11560 x2l=half(x1l+stack_2(x_packet(mp->xy)));
11561 x2r=half(x3r+stack_2(x_packet(mp->xy)));
11562 x3l=half(x2l+x2r); x1r=x3l;
11563 set_min_max(xl_packet); set_min_max(xr_packet);
11564 y1l=stack_1(y_packet(mp->xy)); y3r=stack_3(y_packet(mp->xy));
11565 y2l=half(y1l+stack_2(y_packet(mp->xy)));
11566 y2r=half(y3r+stack_2(y_packet(mp->xy)));
11567 y3l=half(y2l+y2r); y1r=y3l;
11568 set_min_max(yl_packet); set_min_max(yr_packet);
11569 mp->uv=l_packets; mp->xy=l_packets;
11570 mp->delx+=mp->delx; mp->dely+=mp->dely;
11571 mp->tol=mp->tol-mp->three_l+mp->tol_step; 
11572 mp->tol+=mp->tol; mp->three_l=mp->three_l+mp->tol_step
11573
11574 @ @<Advance to the next pair |(cur_t,cur_tt)|@>=
11575 NOT_FOUND: 
11576 if ( odd(mp->cur_tt) ) {
11577   if ( odd(mp->cur_t) ) {
11578      @<Descend to the previous level and |goto not_found|@>;
11579   } else { 
11580     incr(mp->cur_t);
11581     mp->delx=mp->delx+stack_1(u_packet(mp->uv))+stack_2(u_packet(mp->uv))
11582       +stack_3(u_packet(mp->uv));
11583     mp->dely=mp->dely+stack_1(v_packet(mp->uv))+stack_2(v_packet(mp->uv))
11584       +stack_3(v_packet(mp->uv));
11585     mp->uv=mp->uv+int_packets; /* switch from |l_packet| to |r_packet| */
11586     decr(mp->cur_tt); mp->xy=mp->xy-int_packets; 
11587          /* switch from |r_packet| to |l_packet| */
11588     mp->delx=mp->delx+stack_1(x_packet(mp->xy))+stack_2(x_packet(mp->xy))
11589       +stack_3(x_packet(mp->xy));
11590     mp->dely=mp->dely+stack_1(y_packet(mp->xy))+stack_2(y_packet(mp->xy))
11591       +stack_3(y_packet(mp->xy));
11592   }
11593 } else { 
11594   incr(mp->cur_tt); mp->tol=mp->tol+mp->three_l;
11595   mp->delx=mp->delx-stack_1(x_packet(mp->xy))-stack_2(x_packet(mp->xy))
11596     -stack_3(x_packet(mp->xy));
11597   mp->dely=mp->dely-stack_1(y_packet(mp->xy))-stack_2(y_packet(mp->xy))
11598     -stack_3(y_packet(mp->xy));
11599   mp->xy=mp->xy+int_packets; /* switch from |l_packet| to |r_packet| */
11600 }
11601
11602 @ @<Descend to the previous level...@>=
11603
11604   mp->cur_t=halfp(mp->cur_t); mp->cur_tt=halfp(mp->cur_tt);
11605   if ( mp->cur_t==0 ) return;
11606   mp->bisect_ptr=mp->bisect_ptr-int_increment; 
11607   mp->three_l=mp->three_l-mp->tol_step;
11608   mp->delx=stack_dx; mp->dely=stack_dy; mp->tol=stack_tol; 
11609   mp->uv=stack_uv; mp->xy=stack_xy;
11610   goto NOT_FOUND;
11611 }
11612
11613 @ The |path_intersection| procedure is much simpler.
11614 It invokes |cubic_intersection| in lexicographic order until finding a
11615 pair of cubics that intersect. The final intersection times are placed in
11616 |cur_t| and~|cur_tt|.
11617
11618 @c void mp_path_intersection (MP mp,pointer h, pointer hh) {
11619   pointer p,pp; /* link registers that traverse the given paths */
11620   integer n,nn; /* integer parts of intersection times, minus |unity| */
11621   @<Change one-point paths into dead cycles@>;
11622   mp->tol_step=0;
11623   do {  
11624     n=-unity; p=h;
11625     do {  
11626       if ( right_type(p)!=endpoint ) { 
11627         nn=-unity; pp=hh;
11628         do {  
11629           if ( right_type(pp)!=endpoint )  { 
11630             mp_cubic_intersection(mp, p,pp);
11631             if ( mp->cur_t>0 ) { 
11632               mp->cur_t=mp->cur_t+n; mp->cur_tt=mp->cur_tt+nn; 
11633               return;
11634             }
11635           }
11636           nn=nn+unity; pp=link(pp);
11637         } while (pp!=hh);
11638       }
11639       n=n+unity; p=link(p);
11640     } while (p!=h);
11641     mp->tol_step=mp->tol_step+3;
11642   } while (mp->tol_step<=3);
11643   mp->cur_t=-unity; mp->cur_tt=-unity;
11644 }
11645
11646 @ @<Change one-point paths...@>=
11647 if ( right_type(h)==endpoint ) {
11648   right_x(h)=x_coord(h); left_x(h)=x_coord(h);
11649   right_y(h)=y_coord(h); left_y(h)=y_coord(h); right_type(h)=explicit;
11650 }
11651 if ( right_type(hh)==endpoint ) {
11652   right_x(hh)=x_coord(hh); left_x(hh)=x_coord(hh);
11653   right_y(hh)=y_coord(hh); left_y(hh)=y_coord(hh); right_type(hh)=explicit;
11654 }
11655
11656 @* \[24] Dynamic linear equations.
11657 \MP\ users define variables implicitly by stating equations that should be
11658 satisfied; the computer is supposed to be smart enough to solve those equations.
11659 And indeed, the computer tries valiantly to do so, by distinguishing five
11660 different types of numeric values:
11661
11662 \smallskip\hang
11663 |type(p)=mp_known| is the nice case, when |value(p)| is the |scaled| value
11664 of the variable whose address is~|p|.
11665
11666 \smallskip\hang
11667 |type(p)=mp_dependent| means that |value(p)| is not present, but |dep_list(p)|
11668 points to a {\sl dependency list\/} that expresses the value of variable~|p|
11669 as a |scaled| number plus a sum of independent variables with |fraction|
11670 coefficients.
11671
11672 \smallskip\hang
11673 |type(p)=mp_independent| means that |value(p)=64s+m|, where |s>0| is a ``serial
11674 number'' reflecting the time this variable was first used in an equation;
11675 also |0<=m<64|, and each dependent variable
11676 that refers to this one is actually referring to the future value of
11677 this variable times~$2^m$. (Usually |m=0|, but higher degrees of
11678 scaling are sometimes needed to keep the coefficients in dependency lists
11679 from getting too large. The value of~|m| will always be even.)
11680
11681 \smallskip\hang
11682 |type(p)=mp_numeric_type| means that variable |p| hasn't appeared in an
11683 equation before, but it has been explicitly declared to be numeric.
11684
11685 \smallskip\hang
11686 |type(p)=undefined| means that variable |p| hasn't appeared before.
11687
11688 \smallskip\noindent
11689 We have actually discussed these five types in the reverse order of their
11690 history during a computation: Once |known|, a variable never again
11691 becomes |dependent|; once |dependent|, it almost never again becomes
11692 |mp_independent|; once |mp_independent|, it never again becomes |mp_numeric_type|;
11693 and once |mp_numeric_type|, it never again becomes |undefined| (except
11694 of course when the user specifically decides to scrap the old value
11695 and start again). A backward step may, however, take place: Sometimes
11696 a |dependent| variable becomes |mp_independent| again, when one of the
11697 independent variables it depends on is reverting to |undefined|.
11698
11699
11700 The next patch detects overflow of independent-variable serial
11701 numbers. Diagnosed and patched by Thorsten Dahlheimer.
11702
11703 @d s_scale 64 /* the serial numbers are multiplied by this factor */
11704 @d max_indep_vars 0177777777 /* $2^{25}-1$ */
11705 @d max_serial_no 017777777700 /* |max_indep_vars*s_scale| */
11706 @d new_indep(A)  /* create a new independent variable */
11707   { if ( mp->serial_no==max_serial_no )
11708     mp_fatal_error(mp, "variable instance identifiers exhausted");
11709   type((A))=mp_independent; mp->serial_no=mp->serial_no+s_scale;
11710   value((A))=mp->serial_no;
11711   }
11712
11713 @<Glob...@>=
11714 integer serial_no; /* the most recent serial number, times |s_scale| */
11715
11716 @ @<Make variable |q+s| newly independent@>=new_indep(q+s)
11717
11718 @ But how are dependency lists represented? It's simple: The linear combination
11719 $\alpha_1v_1+\cdots+\alpha_kv_k+\beta$ appears in |k+1| value nodes. If
11720 |q=dep_list(p)| points to this list, and if |k>0|, then |value(q)=
11721 @t$\alpha_1$@>| (which is a |fraction|); |info(q)| points to the location
11722 of $\alpha_1$; and |link(p)| points to the dependency list
11723 $\alpha_2v_2+\cdots+\alpha_kv_k+\beta$. On the other hand if |k=0|,
11724 then |value(q)=@t$\beta$@>| (which is |scaled|) and |info(q)=null|.
11725 The independent variables $v_1$, \dots,~$v_k$ have been sorted so that
11726 they appear in decreasing order of their |value| fields (i.e., of
11727 their serial numbers). \ (It is convenient to use decreasing order,
11728 since |value(null)=0|. If the independent variables were not sorted by
11729 serial number but by some other criterion, such as their location in |mem|,
11730 the equation-solving mechanism would be too system-dependent, because
11731 the ordering can affect the computed results.)
11732
11733 The |link| field in the node that contains the constant term $\beta$ is
11734 called the {\sl final link\/} of the dependency list. \MP\ maintains
11735 a doubly-linked master list of all dependency lists, in terms of a permanently
11736 allocated node
11737 in |mem| called |dep_head|. If there are no dependencies, we have
11738 |link(dep_head)=dep_head| and |prev_dep(dep_head)=dep_head|;
11739 otherwise |link(dep_head)| points to the first dependent variable, say~|p|,
11740 and |prev_dep(p)=dep_head|. We have |type(p)=mp_dependent|, and |dep_list(p)|
11741 points to its dependency list. If the final link of that dependency list
11742 occurs in location~|q|, then |link(q)| points to the next dependent
11743 variable (say~|r|); and we have |prev_dep(r)=q|, etc.
11744
11745 @d dep_list(A) link(value_loc((A)))
11746   /* half of the |value| field in a |dependent| variable */
11747 @d prev_dep(A) info(value_loc((A)))
11748   /* the other half; makes a doubly linked list */
11749 @d dep_node_size 2 /* the number of words per dependency node */
11750
11751 @<Initialize table entries...@>= mp->serial_no=0;
11752 link(dep_head)=dep_head; prev_dep(dep_head)=dep_head;
11753 info(dep_head)=null; dep_list(dep_head)=null;
11754
11755 @ Actually the description above contains a little white lie. There's
11756 another kind of variable called |mp_proto_dependent|, which is
11757 just like a |dependent| one except that the $\alpha$ coefficients
11758 in its dependency list are |scaled| instead of being fractions.
11759 Proto-dependency lists are mixed with dependency lists in the
11760 nodes reachable from |dep_head|.
11761
11762 @ Here is a procedure that prints a dependency list in symbolic form.
11763 The second parameter should be either |dependent| or |mp_proto_dependent|,
11764 to indicate the scaling of the coefficients.
11765
11766 @<Declare subroutines for printing expressions@>=
11767 void mp_print_dependency (MP mp,pointer p, small_number t) {
11768   integer v; /* a coefficient */
11769   pointer pp,q; /* for list manipulation */
11770   pp=p;
11771   while (1) { 
11772     v=abs(value(p)); q=info(p);
11773     if ( q==null ) { /* the constant term */
11774       if ( (v!=0)||(p==pp) ) {
11775          if ( value(p)>0 ) if ( p!=pp ) mp_print_char(mp, '+');
11776          mp_print_scaled(mp, value(p));
11777       }
11778       return;
11779     }
11780     @<Print the coefficient, unless it's $\pm1.0$@>;
11781     if ( type(q)!=mp_independent ) mp_confusion(mp, "dep");
11782 @:this can't happen dep}{\quad dep@>
11783     mp_print_variable_name(mp, q); v=value(q) % s_scale;
11784     while ( v>0 ) { mp_print(mp, "*4"); v=v-2; }
11785     p=link(p);
11786   }
11787 }
11788
11789 @ @<Print the coefficient, unless it's $\pm1.0$@>=
11790 if ( value(p)<0 ) mp_print_char(mp, '-');
11791 else if ( p!=pp ) mp_print_char(mp, '+');
11792 if ( t==mp_dependent ) v=mp_round_fraction(mp, v);
11793 if ( v!=unity ) mp_print_scaled(mp, v)
11794
11795 @ The maximum absolute value of a coefficient in a given dependency list
11796 is returned by the following simple function.
11797
11798 @c fraction mp_max_coef (MP mp,pointer p) {
11799   fraction x; /* the maximum so far */
11800   x=0;
11801   while ( info(p)!=null ) {
11802     if ( abs(value(p))>x ) x=abs(value(p));
11803     p=link(p);
11804   }
11805   return x;
11806 }
11807
11808 @ One of the main operations needed on dependency lists is to add a multiple
11809 of one list to the other; we call this |p_plus_fq|, where |p| and~|q| point
11810 to dependency lists and |f| is a fraction.
11811
11812 If the coefficient of any independent variable becomes |coef_bound| or
11813 more, in absolute value, this procedure changes the type of that variable
11814 to `|independent_needing_fix|', and sets the global variable |fix_needed|
11815 to~|true|. The value of $|coef_bound|=\mu$ is chosen so that
11816 $\mu^2+\mu<8$; this means that the numbers we deal with won't
11817 get too large. (Instead of the ``optimum'' $\mu=(\sqrt{33}-1)/2\approx
11818 2.3723$, the safer value 7/3 is taken as the threshold.)
11819
11820 The changes mentioned in the preceding paragraph are actually done only if
11821 the global variable |watch_coefs| is |true|. But it usually is; in fact,
11822 it is |false| only when \MP\ is making a dependency list that will soon
11823 be equated to zero.
11824
11825 Several procedures that act on dependency lists, including |p_plus_fq|,
11826 set the global variable |dep_final| to the final (constant term) node of
11827 the dependency list that they produce.
11828
11829 @d coef_bound 04525252525 /* |fraction| approximation to 7/3 */
11830 @d independent_needing_fix 0
11831
11832 @<Glob...@>=
11833 boolean fix_needed; /* does at least one |independent| variable need scaling? */
11834 boolean watch_coefs; /* should we scale coefficients that exceed |coef_bound|? */
11835 pointer dep_final; /* location of the constant term and final link */
11836
11837 @ @<Set init...@>=
11838 mp->fix_needed=false; mp->watch_coefs=true;
11839
11840 @ The |p_plus_fq| procedure has a fourth parameter, |t|, that should be
11841 set to |mp_proto_dependent| if |p| is a proto-dependency list. In this
11842 case |f| will be |scaled|, not a |fraction|. Similarly, the fifth parameter~|tt|
11843 should be |mp_proto_dependent| if |q| is a proto-dependency list.
11844
11845 List |q| is unchanged by the operation; but list |p| is totally destroyed.
11846
11847 The final link of the dependency list or proto-dependency list returned
11848 by |p_plus_fq| is the same as the original final link of~|p|. Indeed, the
11849 constant term of the result will be located in the same |mem| location
11850 as the original constant term of~|p|.
11851
11852 Coefficients of the result are assumed to be zero if they are less than
11853 a certain threshold. This compensates for inevitable rounding errors,
11854 and tends to make more variables `|known|'. The threshold is approximately
11855 $10^{-5}$ in the case of normal dependency lists, $10^{-4}$ for
11856 proto-dependencies.
11857
11858 @d fraction_threshold 2685 /* a |fraction| coefficient less than this is zeroed */
11859 @d half_fraction_threshold 1342 /* half of |fraction_threshold| */
11860 @d scaled_threshold 8 /* a |scaled| coefficient less than this is zeroed */
11861 @d half_scaled_threshold 4 /* half of |scaled_threshold| */
11862
11863 @<Declare basic dependency-list subroutines@>=
11864 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
11865                       pointer q, small_number t, small_number tt) ;
11866
11867 @ @c
11868 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
11869                       pointer q, small_number t, small_number tt) {
11870   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
11871   pointer r,s; /* for list manipulation */
11872   integer mp_threshold; /* defines a neighborhood of zero */
11873   integer v; /* temporary register */
11874   if ( t==mp_dependent ) mp_threshold=fraction_threshold;
11875   else mp_threshold=scaled_threshold;
11876   r=temp_head; pp=info(p); qq=info(q);
11877   while (1) {
11878     if ( pp==qq ) {
11879       if ( pp==null ) {
11880        break;
11881       } else {
11882         @<Contribute a term from |p|, plus |f| times the
11883           corresponding term from |q|@>
11884       }
11885     } else if ( value(pp)<value(qq) ) {
11886       @<Contribute a term from |q|, multiplied by~|f|@>
11887     } else { 
11888      link(r)=p; r=p; p=link(p); pp=info(p);
11889     }
11890   }
11891   if ( t==mp_dependent )
11892     value(p)=mp_slow_add(mp, value(p),mp_take_fraction(mp, value(q),f));
11893   else  
11894     value(p)=mp_slow_add(mp, value(p),mp_take_scaled(mp, value(q),f));
11895   link(r)=p; mp->dep_final=p; 
11896   return link(temp_head);
11897 }
11898
11899 @ @<Contribute a term from |p|, plus |f|...@>=
11900
11901   if ( tt==mp_dependent ) v=value(p)+mp_take_fraction(mp, f,value(q));
11902   else v=value(p)+mp_take_scaled(mp, f,value(q));
11903   value(p)=v; s=p; p=link(p);
11904   if ( abs(v)<mp_threshold ) {
11905     mp_free_node(mp, s,dep_node_size);
11906   } else {
11907     if ( (abs(v)>=coef_bound)  && mp->watch_coefs ) { 
11908       type(qq)=independent_needing_fix; mp->fix_needed=true;
11909     }
11910     link(r)=s; r=s;
11911   };
11912   pp=info(p); q=link(q); qq=info(q);
11913 }
11914
11915 @ @<Contribute a term from |q|, multiplied by~|f|@>=
11916
11917   if ( tt==mp_dependent ) v=mp_take_fraction(mp, f,value(q));
11918   else v=mp_take_scaled(mp, f,value(q));
11919   if ( abs(v)>halfp(mp_threshold) ) { 
11920     s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=v;
11921     if ( (abs(v)>=coef_bound) && mp->watch_coefs ) { 
11922       type(qq)=independent_needing_fix; mp->fix_needed=true;
11923     }
11924     link(r)=s; r=s;
11925   }
11926   q=link(q); qq=info(q);
11927 }
11928
11929 @ It is convenient to have another subroutine for the special case
11930 of |p_plus_fq| when |f=1.0|. In this routine lists |p| and |q| are
11931 both of the same type~|t| (either |dependent| or |mp_proto_dependent|).
11932
11933 @c pointer mp_p_plus_q (MP mp,pointer p, pointer q, small_number t) {
11934   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
11935   pointer r,s; /* for list manipulation */
11936   integer mp_threshold; /* defines a neighborhood of zero */
11937   integer v; /* temporary register */
11938   if ( t==mp_dependent ) mp_threshold=fraction_threshold;
11939   else mp_threshold=scaled_threshold;
11940   r=temp_head; pp=info(p); qq=info(q);
11941   while (1) {
11942     if ( pp==qq ) {
11943       if ( pp==null ) {
11944         break;
11945       } else {
11946         @<Contribute a term from |p|, plus the
11947           corresponding term from |q|@>
11948       }
11949     } else if ( value(pp)<value(qq) ) {
11950       s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=value(q);
11951       q=link(q); qq=info(q); link(r)=s; r=s;
11952     } else { 
11953       link(r)=p; r=p; p=link(p); pp=info(p);
11954     }
11955   }
11956   value(p)=mp_slow_add(mp, value(p),value(q));
11957   link(r)=p; mp->dep_final=p; 
11958   return link(temp_head);
11959 }
11960
11961 @ @<Contribute a term from |p|, plus the...@>=
11962
11963   v=value(p)+value(q);
11964   value(p)=v; s=p; p=link(p); pp=info(p);
11965   if ( abs(v)<mp_threshold ) {
11966     mp_free_node(mp, s,dep_node_size);
11967   } else { 
11968     if ( (abs(v)>=coef_bound ) && mp->watch_coefs ) {
11969       type(qq)=independent_needing_fix; mp->fix_needed=true;
11970     }
11971     link(r)=s; r=s;
11972   }
11973   q=link(q); qq=info(q);
11974 }
11975
11976 @ A somewhat simpler routine will multiply a dependency list
11977 by a given constant~|v|. The constant is either a |fraction| less than
11978 |fraction_one|, or it is |scaled|. In the latter case we might be forced to
11979 convert a dependency list to a proto-dependency list.
11980 Parameters |t0| and |t1| are the list types before and after;
11981 they should agree unless |t0=mp_dependent| and |t1=mp_proto_dependent|
11982 and |v_is_scaled=true|.
11983
11984 @c pointer mp_p_times_v (MP mp,pointer p, integer v, small_number t0,
11985                          small_number t1, boolean v_is_scaled) {
11986   pointer r,s; /* for list manipulation */
11987   integer w; /* tentative coefficient */
11988   integer mp_threshold;
11989   boolean scaling_down;
11990   if ( t0!=t1 ) scaling_down=true; else scaling_down=! v_is_scaled;
11991   if ( t1==mp_dependent ) mp_threshold=half_fraction_threshold;
11992   else mp_threshold=half_scaled_threshold;
11993   r=temp_head;
11994   while ( info(p)!=null ) {    
11995     if ( scaling_down ) w=mp_take_fraction(mp, v,value(p));
11996     else w=mp_take_scaled(mp, v,value(p));
11997     if ( abs(w)<=mp_threshold ) { 
11998       s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
11999     } else {
12000       if ( abs(w)>=coef_bound ) { 
12001         mp->fix_needed=true; type(info(p))=independent_needing_fix;
12002       }
12003       link(r)=p; r=p; value(p)=w; p=link(p);
12004     }
12005   }
12006   link(r)=p;
12007   if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
12008   else value(p)=mp_take_fraction(mp, value(p),v);
12009   return link(temp_head);
12010 };
12011
12012 @ Similarly, we sometimes need to divide a dependency list
12013 by a given |scaled| constant.
12014
12015 @<Declare basic dependency-list subroutines@>=
12016 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number 
12017   t0, small_number t1) ;
12018
12019 @ @c
12020 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number 
12021   t0, small_number t1) {
12022   pointer r,s; /* for list manipulation */
12023   integer w; /* tentative coefficient */
12024   integer mp_threshold;
12025   boolean scaling_down;
12026   if ( t0!=t1 ) scaling_down=true; else scaling_down=false;
12027   if ( t1==mp_dependent ) mp_threshold=half_fraction_threshold;
12028   else mp_threshold=half_scaled_threshold;
12029   r=temp_head;
12030   while ( info( p)!=null ) {
12031     if ( scaling_down ) {
12032       if ( abs(v)<02000000 ) w=mp_make_scaled(mp, value(p),v*010000);
12033       else w=mp_make_scaled(mp, mp_round_fraction(mp, value(p)),v);
12034     } else {
12035       w=mp_make_scaled(mp, value(p),v);
12036     }
12037     if ( abs(w)<=mp_threshold ) {
12038       s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
12039     } else { 
12040       if ( abs(w)>=coef_bound ) {
12041          mp->fix_needed=true; type(info(p))=independent_needing_fix;
12042       }
12043       link(r)=p; r=p; value(p)=w; p=link(p);
12044     }
12045   }
12046   link(r)=p; value(p)=mp_make_scaled(mp, value(p),v);
12047   return link(temp_head);
12048 };
12049
12050 @ Here's another utility routine for dependency lists. When an independent
12051 variable becomes dependent, we want to remove it from all existing
12052 dependencies. The |p_with_x_becoming_q| function computes the
12053 dependency list of~|p| after variable~|x| has been replaced by~|q|.
12054
12055 This procedure has basically the same calling conventions as |p_plus_fq|:
12056 List~|q| is unchanged; list~|p| is destroyed; the constant node and the
12057 final link are inherited from~|p|; and the fourth parameter tells whether
12058 or not |p| is |mp_proto_dependent|. However, the global variable |dep_final|
12059 is not altered if |x| does not occur in list~|p|.
12060
12061 @c pointer mp_p_with_x_becoming_q (MP mp,pointer p,
12062            pointer x, pointer q, small_number t) {
12063   pointer r,s; /* for list manipulation */
12064   integer v; /* coefficient of |x| */
12065   integer sx; /* serial number of |x| */
12066   s=p; r=temp_head; sx=value(x);
12067   while ( value(info(s))>sx ) { r=s; s=link(s); };
12068   if ( info(s)!=x ) { 
12069     return p;
12070   } else { 
12071     link(temp_head)=p; link(r)=link(s); v=value(s);
12072     mp_free_node(mp, s,dep_node_size);
12073     return mp_p_plus_fq(mp, link(temp_head),v,q,t,mp_dependent);
12074   }
12075 }
12076
12077 @ Here's a simple procedure that reports an error when a variable
12078 has just received a known value that's out of the required range.
12079
12080 @<Declare basic dependency-list subroutines@>=
12081 void mp_val_too_big (MP mp,scaled x) ;
12082
12083 @ @c void mp_val_too_big (MP mp,scaled x) { 
12084   if ( mp->internal[warning_check]>0 ) { 
12085     print_err("Value is too large ("); mp_print_scaled(mp, x); mp_print_char(mp, ')');
12086 @.Value is too large@>
12087     help4("The equation I just processed has given some variable")
12088       ("a value of 4096 or more. Continue and I'll try to cope")
12089       ("with that big value; but it might be dangerous.")
12090       ("(Set warningcheck:=0 to suppress this message.)");
12091     mp_error(mp);
12092   }
12093 }
12094
12095 @ When a dependent variable becomes known, the following routine
12096 removes its dependency list. Here |p| points to the variable, and
12097 |q| points to the dependency list (which is one node long).
12098
12099 @<Declare basic dependency-list subroutines@>=
12100 void mp_make_known (MP mp,pointer p, pointer q) ;
12101
12102 @ @c void mp_make_known (MP mp,pointer p, pointer q) {
12103   int t; /* the previous type */
12104   prev_dep(link(q))=prev_dep(p);
12105   link(prev_dep(p))=link(q); t=type(p);
12106   type(p)=mp_known; value(p)=value(q); mp_free_node(mp, q,dep_node_size);
12107   if ( abs(value(p))>=fraction_one ) mp_val_too_big(mp, value(p));
12108   if (( mp->internal[tracing_equations]>0) && mp_interesting(mp, p) ) {
12109     mp_begin_diagnostic(mp); mp_print_nl(mp, "#### ");
12110 @:]]]\#\#\#\#_}{\.{\#\#\#\#}@>
12111     mp_print_variable_name(mp, p); 
12112     mp_print_char(mp, '='); mp_print_scaled(mp, value(p));
12113     mp_end_diagnostic(mp, false);
12114   }
12115   if (( mp->cur_exp==p ) && mp->cur_type==t ) {
12116     mp->cur_type=mp_known; mp->cur_exp=value(p);
12117     mp_free_node(mp, p,value_node_size);
12118   }
12119 }
12120
12121 @ The |fix_dependencies| routine is called into action when |fix_needed|
12122 has been triggered. The program keeps a list~|s| of independent variables
12123 whose coefficients must be divided by~4.
12124
12125 In unusual cases, this fixup process might reduce one or more coefficients
12126 to zero, so that a variable will become known more or less by default.
12127
12128 @<Declare basic dependency-list subroutines@>=
12129 void mp_fix_dependencies (MP mp);
12130
12131 @ @c void mp_fix_dependencies (MP mp) {
12132   pointer p,q,r,s,t; /* list manipulation registers */
12133   pointer x; /* an independent variable */
12134   r=link(dep_head); s=null;
12135   while ( r!=dep_head ){ 
12136     t=r;
12137     @<Run through the dependency list for variable |t|, fixing
12138       all nodes, and ending with final link~|q|@>;
12139     r=link(q);
12140     if ( q==dep_list(t) ) mp_make_known(mp, t,q);
12141   }
12142   while ( s!=null ) { 
12143     p=link(s); x=info(s); free_avail(s); s=p;
12144     type(x)=mp_independent; value(x)=value(x)+2;
12145   }
12146   mp->fix_needed=false;
12147 }
12148
12149 @ @d independent_being_fixed 1 /* this variable already appears in |s| */
12150
12151 @<Run through the dependency list for variable |t|...@>=
12152 r=value_loc(t); /* |link(r)=dep_list(t)| */
12153 while (1) { 
12154   q=link(r); x=info(q);
12155   if ( x==null ) break;
12156   if ( type(x)<=independent_being_fixed ) {
12157     if ( type(x)<independent_being_fixed ) {
12158       p=mp_get_avail(mp); link(p)=s; s=p;
12159       info(s)=x; type(x)=independent_being_fixed;
12160     }
12161     value(q)=value(q) / 4;
12162     if ( value(q)==0 ) {
12163       link(r)=link(q); mp_free_node(mp, q,dep_node_size); q=r;
12164     }
12165   }
12166   r=q;
12167 }
12168
12169
12170 @ The |new_dep| routine installs a dependency list~|p| into the value node~|q|,
12171 linking it into the list of all known dependencies. We assume that
12172 |dep_final| points to the final node of list~|p|.
12173
12174 @c void mp_new_dep (MP mp,pointer q, pointer p) {
12175   pointer r; /* what used to be the first dependency */
12176   dep_list(q)=p; prev_dep(q)=dep_head;
12177   r=link(dep_head); link(mp->dep_final)=r; prev_dep(r)=mp->dep_final;
12178   link(dep_head)=q;
12179 }
12180
12181 @ Here is one of the ways a dependency list gets started.
12182 The |const_dependency| routine produces a list that has nothing but
12183 a constant term.
12184
12185 @c pointer mp_const_dependency (MP mp, scaled v) {
12186   mp->dep_final=mp_get_node(mp, dep_node_size);
12187   value(mp->dep_final)=v; info(mp->dep_final)=null;
12188   return mp->dep_final;
12189 }
12190
12191 @ And here's a more interesting way to start a dependency list from scratch:
12192 The parameter to |single_dependency| is the location of an
12193 independent variable~|x|, and the result is the simple dependency list
12194 `|x+0|'.
12195
12196 In the unlikely event that the given independent variable has been doubled so
12197 often that we can't refer to it with a nonzero coefficient,
12198 |single_dependency| returns the simple list `0'.  This case can be
12199 recognized by testing that the returned list pointer is equal to
12200 |dep_final|.
12201
12202 @c pointer mp_single_dependency (MP mp,pointer p) {
12203   pointer q; /* the new dependency list */
12204   integer m; /* the number of doublings */
12205   m=value(p) % s_scale;
12206   if ( m>28 ) {
12207     return mp_const_dependency(mp, 0);
12208   } else { 
12209     q=mp_get_node(mp, dep_node_size);
12210     value(q)=two_to_the(28-m); info(q)=p;
12211     link(q)=mp_const_dependency(mp, 0);
12212     return q;
12213   }
12214 }
12215
12216 @ We sometimes need to make an exact copy of a dependency list.
12217
12218 @c pointer mp_copy_dep_list (MP mp,pointer p) {
12219   pointer q; /* the new dependency list */
12220   q=mp_get_node(mp, dep_node_size); mp->dep_final=q;
12221   while (1) { 
12222     info(mp->dep_final)=info(p); value(mp->dep_final)=value(p);
12223     if ( info(mp->dep_final)==null ) break;
12224     link(mp->dep_final)=mp_get_node(mp, dep_node_size);
12225     mp->dep_final=link(mp->dep_final); p=link(p);
12226   }
12227   return q;
12228 }
12229
12230 @ But how do variables normally become known? Ah, now we get to the heart of the
12231 equation-solving mechanism. The |linear_eq| procedure is given a |dependent|
12232 or |mp_proto_dependent| list,~|p|, in which at least one independent variable
12233 appears. It equates this list to zero, by choosing an independent variable
12234 with the largest coefficient and making it dependent on the others. The
12235 newly dependent variable is eliminated from all current dependencies,
12236 thereby possibly making other dependent variables known.
12237
12238 The given list |p| is, of course, totally destroyed by all this processing.
12239
12240 @c void mp_linear_eq (MP mp, pointer p, small_number t) {
12241   pointer q,r,s; /* for link manipulation */
12242   pointer x; /* the variable that loses its independence */
12243   integer n; /* the number of times |x| had been halved */
12244   integer v; /* the coefficient of |x| in list |p| */
12245   pointer prev_r; /* lags one step behind |r| */
12246   pointer final_node; /* the constant term of the new dependency list */
12247   integer w; /* a tentative coefficient */
12248    @<Find a node |q| in list |p| whose coefficient |v| is largest@>;
12249   x=info(q); n=value(x) % s_scale;
12250   @<Divide list |p| by |-v|, removing node |q|@>;
12251   if ( mp->internal[tracing_equations]>0 ) {
12252     @<Display the new dependency@>;
12253   }
12254   @<Simplify all existing dependencies by substituting for |x|@>;
12255   @<Change variable |x| from |independent| to |dependent| or |known|@>;
12256   if ( mp->fix_needed ) mp_fix_dependencies(mp);
12257 }
12258
12259 @ @<Find a node |q| in list |p| whose coefficient |v| is largest@>=
12260 q=p; r=link(p); v=value(q);
12261 while ( info(r)!=null ) { 
12262   if ( abs(value(r))>abs(v) ) { q=r; v=value(r); };
12263   r=link(r);
12264 }
12265
12266 @ Here we want to change the coefficients from |scaled| to |fraction|,
12267 except in the constant term. In the common case of a trivial equation
12268 like `\.{x=3.14}', we will have |v=-fraction_one|, |q=p|, and |t=mp_dependent|.
12269
12270 @<Divide list |p| by |-v|, removing node |q|@>=
12271 s=temp_head; link(s)=p; r=p;
12272 do { 
12273   if ( r==q ) {
12274     link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12275   } else  { 
12276     w=mp_make_fraction(mp, value(r),v);
12277     if ( abs(w)<=half_fraction_threshold ) {
12278       link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12279     } else { 
12280       value(r)=-w; s=r;
12281     }
12282   }
12283   r=link(s);
12284 } while (info(r)!=null);
12285 if ( t==mp_proto_dependent ) {
12286   value(r)=-mp_make_scaled(mp, value(r),v);
12287 } else if ( v!=-fraction_one ) {
12288   value(r)=-mp_make_fraction(mp, value(r),v);
12289 }
12290 final_node=r; p=link(temp_head)
12291
12292 @ @<Display the new dependency@>=
12293 if ( mp_interesting(mp, x) ) {
12294   mp_begin_diagnostic(mp); mp_print_nl(mp, "## "); 
12295   mp_print_variable_name(mp, x);
12296 @:]]]\#\#_}{\.{\#\#}@>
12297   w=n;
12298   while ( w>0 ) { mp_print(mp, "*4"); w=w-2;  };
12299   mp_print_char(mp, '='); mp_print_dependency(mp, p,mp_dependent); 
12300   mp_end_diagnostic(mp, false);
12301 }
12302
12303 @ @<Simplify all existing dependencies by substituting for |x|@>=
12304 prev_r=dep_head; r=link(dep_head);
12305 while ( r!=dep_head ) {
12306   s=dep_list(r); q=mp_p_with_x_becoming_q(mp, s,x,p,type(r));
12307   if ( info(q)==null ) {
12308     mp_make_known(mp, r,q);
12309   } else { 
12310     dep_list(r)=q;
12311     do {  q=link(q); } while (info(q)!=null);
12312     prev_r=q;
12313   }
12314   r=link(prev_r);
12315 }
12316
12317 @ @<Change variable |x| from |independent| to |dependent| or |known|@>=
12318 if ( n>0 ) @<Divide list |p| by $2^n$@>;
12319 if ( info(p)==null ) {
12320   type(x)=mp_known;
12321   value(x)=value(p);
12322   if ( abs(value(x))>=fraction_one ) mp_val_too_big(mp, value(x));
12323   mp_free_node(mp, p,dep_node_size);
12324   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) {
12325     mp->cur_exp=value(x); mp->cur_type=mp_known;
12326     mp_free_node(mp, x,value_node_size);
12327   }
12328 } else { 
12329   type(x)=mp_dependent; mp->dep_final=final_node; mp_new_dep(mp, x,p);
12330   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) mp->cur_type=mp_dependent;
12331 }
12332
12333 @ @<Divide list |p| by $2^n$@>=
12334
12335   s=temp_head; link(temp_head)=p; r=p;
12336   do {  
12337     if ( n>30 ) w=0;
12338     else w=value(r) / two_to_the(n);
12339     if ( (abs(w)<=half_fraction_threshold)&&(info(r)!=null) ) {
12340       link(s)=link(r);
12341       mp_free_node(mp, r,dep_node_size);
12342     } else { 
12343       value(r)=w; s=r;
12344     }
12345     r=link(s);
12346   } while (info(s)!=null);
12347   p=link(temp_head);
12348 }
12349
12350 @ The |check_mem| procedure, which is used only when \MP\ is being
12351 debugged, makes sure that the current dependency lists are well formed.
12352
12353 @<Check the list of linear dependencies@>=
12354 q=dep_head; p=link(q);
12355 while ( p!=dep_head ) {
12356   if ( prev_dep(p)!=q ) {
12357     mp_print_nl(mp, "Bad PREVDEP at "); mp_print_int(mp, p);
12358 @.Bad PREVDEP...@>
12359   }
12360   p=dep_list(p);
12361   while (1) {
12362     r=info(p); q=p; p=link(q);
12363     if ( r==null ) break;
12364     if ( value(info(p))>=value(r) ) {
12365       mp_print_nl(mp, "Out of order at "); mp_print_int(mp, p);
12366 @.Out of order...@>
12367     }
12368   }
12369 }
12370
12371 @* \[25] Dynamic nonlinear equations.
12372 Variables of numeric type are maintained by the general scheme of
12373 independent, dependent, and known values that we have just studied;
12374 and the components of pair and transform variables are handled in the
12375 same way. But \MP\ also has five other types of values: \&{boolean},
12376 \&{string}, \&{pen}, \&{path}, and \&{picture}; what about them?
12377
12378 Equations are allowed between nonlinear quantities, but only in a
12379 simple form. Two variables that haven't yet been assigned values are
12380 either equal to each other, or they're not.
12381
12382 Before a boolean variable has received a value, its type is |mp_unknown_boolean|;
12383 similarly, there are variables whose type is |mp_unknown_string|, |mp_unknown_pen|,
12384 |mp_unknown_path|, and |mp_unknown_picture|. In such cases the value is either
12385 |null| (which means that no other variables are equivalent to this one), or
12386 it points to another variable of the same undefined type. The pointers in the
12387 latter case form a cycle of nodes, which we shall call a ``ring.''
12388 Rings of undefined variables may include capsules, which arise as
12389 intermediate results within expressions or as \&{expr} parameters to macros.
12390
12391 When one member of a ring receives a value, the same value is given to
12392 all the other members. In the case of paths and pictures, this implies
12393 making separate copies of a potentially large data structure; users should
12394 restrain their enthusiasm for such generality, unless they have lots and
12395 lots of memory space.
12396
12397 @ The following procedure is called when a capsule node is being
12398 added to a ring (e.g., when an unknown variable is mentioned in an expression).
12399
12400 @c pointer mp_new_ring_entry (MP mp,pointer p) {
12401   pointer q; /* the new capsule node */
12402   q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
12403   type(q)=type(p);
12404   if ( value(p)==null ) value(q)=p; else value(q)=value(p);
12405   value(p)=q;
12406   return q;
12407 }
12408
12409 @ Conversely, we might delete a capsule or a variable before it becomes known.
12410 The following procedure simply detaches a quantity from its ring,
12411 without recycling the storage.
12412
12413 @<Declare the recycling subroutines@>=
12414 void mp_ring_delete (MP mp,pointer p) {
12415   pointer q; 
12416   q=value(p);
12417   if ( q!=null ) if ( q!=p ){ 
12418     while ( value(q)!=p ) q=value(q);
12419     value(q)=value(p);
12420   }
12421 }
12422
12423 @ Eventually there might be an equation that assigns values to all of the
12424 variables in a ring. The |nonlinear_eq| subroutine does the necessary
12425 propagation of values.
12426
12427 If the parameter |flush_p| is |true|, node |p| itself needn't receive a
12428 value, it will soon be recycled.
12429
12430 @c void mp_nonlinear_eq (MP mp,integer v, pointer p, boolean flush_p) {
12431   small_number t; /* the type of ring |p| */
12432   pointer q,r; /* link manipulation registers */
12433   t=type(p)-unknown_tag; q=value(p);
12434   if ( flush_p ) type(p)=mp_vacuous; else p=q;
12435   do {  
12436     r=value(q); type(q)=t;
12437     switch (t) {
12438     case mp_boolean_type: value(q)=v; break;
12439     case mp_string_type: value(q)=v; add_str_ref(v); break;
12440     case mp_pen_type: value(q)=copy_pen(v); break;
12441     case mp_path_type: value(q)=mp_copy_path(mp, v); break;
12442     case mp_picture_type: value(q)=v; add_edge_ref(v); break;
12443     } /* there ain't no more cases */
12444     q=r;
12445   } while (q!=p);
12446 }
12447
12448 @ If two members of rings are equated, and if they have the same type,
12449 the |ring_merge| procedure is called on to make them equivalent.
12450
12451 @c void mp_ring_merge (MP mp,pointer p, pointer q) {
12452   pointer r; /* traverses one list */
12453   r=value(p);
12454   while ( r!=p ) {
12455     if ( r==q ) {
12456       @<Exclaim about a redundant equation@>;
12457       return;
12458     };
12459     r=value(r);
12460   }
12461   r=value(p); value(p)=value(q); value(q)=r;
12462 }
12463
12464 @ @<Exclaim about a redundant equation@>=
12465
12466   print_err("Redundant equation");
12467 @.Redundant equation@>
12468   help2("I already knew that this equation was true.")
12469    ("But perhaps no harm has been done; let's continue.");
12470   mp_put_get_error(mp);
12471 }
12472
12473 @* \[26] Introduction to the syntactic routines.
12474 Let's pause a moment now and try to look at the Big Picture.
12475 The \MP\ program consists of three main parts: syntactic routines,
12476 semantic routines, and output routines. The chief purpose of the
12477 syntactic routines is to deliver the user's input to the semantic routines,
12478 while parsing expressions and locating operators and operands. The
12479 semantic routines act as an interpreter responding to these operators,
12480 which may be regarded as commands. And the output routines are
12481 periodically called on to produce compact font descriptions that can be
12482 used for typesetting or for making interim proof drawings. We have
12483 discussed the basic data structures and many of the details of semantic
12484 operations, so we are good and ready to plunge into the part of \MP\ that
12485 actually controls the activities.
12486
12487 Our current goal is to come to grips with the |get_next| procedure,
12488 which is the keystone of \MP's input mechanism. Each call of |get_next|
12489 sets the value of three variables |cur_cmd|, |cur_mod|, and |cur_sym|,
12490 representing the next input token.
12491 $$\vbox{\halign{#\hfil\cr
12492   \hbox{|cur_cmd| denotes a command code from the long list of codes
12493    given earlier;}\cr
12494   \hbox{|cur_mod| denotes a modifier of the command code;}\cr
12495   \hbox{|cur_sym| is the hash address of the symbolic token that was
12496    just scanned,}\cr
12497   \hbox{\qquad or zero in the case of a numeric or string
12498    or capsule token.}\cr}}$$
12499 Underlying this external behavior of |get_next| is all the machinery
12500 necessary to convert from character files to tokens. At a given time we
12501 may be only partially finished with the reading of several files (for
12502 which \&{input} was specified), and partially finished with the expansion
12503 of some user-defined macros and/or some macro parameters, and partially
12504 finished reading some text that the user has inserted online,
12505 and so on. When reading a character file, the characters must be
12506 converted to tokens; comments and blank spaces must
12507 be removed, numeric and string tokens must be evaluated.
12508
12509 To handle these situations, which might all be present simultaneously,
12510 \MP\ uses various stacks that hold information about the incomplete
12511 activities, and there is a finite state control for each level of the
12512 input mechanism. These stacks record the current state of an implicitly
12513 recursive process, but the |get_next| procedure is not recursive.
12514
12515 @<Glob...@>=
12516 eight_bits cur_cmd; /* current command set by |get_next| */
12517 integer cur_mod; /* operand of current command */
12518 halfword cur_sym; /* hash address of current symbol */
12519
12520 @ The |print_cmd_mod| routine prints a symbolic interpretation of a
12521 command code and its modifier.
12522 It consists of a rather tedious sequence of print
12523 commands, and most of it is essentially an inverse to the |primitive|
12524 routine that enters a \MP\ primitive into |hash| and |eqtb|. Therefore almost
12525 all of this procedure appears elsewhere in the program, together with the
12526 corresponding |primitive| calls.
12527
12528 @<Declare the procedure called |print_cmd_mod|@>=
12529 void mp_print_cmd_mod (MP mp,integer c, integer m) { 
12530  switch (c) {
12531   @<Cases of |print_cmd_mod| for symbolic printing of primitives@>
12532   default: mp_print(mp, "[unknown command code!]"); break;
12533   }
12534 }
12535
12536 @ Here is a procedure that displays a given command in braces, in the
12537 user's transcript file.
12538
12539 @d show_cur_cmd_mod mp_show_cmd_mod(mp, mp->cur_cmd,mp->cur_mod)
12540
12541 @c 
12542 void mp_show_cmd_mod (MP mp,integer c, integer m) { 
12543   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
12544   mp_print_cmd_mod(mp, c,m); mp_print_char(mp, '}');
12545   mp_end_diagnostic(mp, false);
12546 }
12547
12548 @* \[27] Input stacks and states.
12549 The state of \MP's input mechanism appears in the input stack, whose
12550 entries are records with five fields, called |index|, |start|, |loc|,
12551 |limit|, and |name|. The top element of this stack is maintained in a
12552 global variable for which no subscripting needs to be done; the other
12553 elements of the stack appear in an array. Hence the stack is declared thus:
12554
12555 @<Types...@>=
12556 typedef struct {
12557   quarterword index_field;
12558   halfword start_field, loc_field, limit_field, name_field;
12559 } in_state_record;
12560
12561 @ @<Glob...@>=
12562 in_state_record *input_stack;
12563 integer input_ptr; /* first unused location of |input_stack| */
12564 integer max_in_stack; /* largest value of |input_ptr| when pushing */
12565 in_state_record cur_input; /* the ``top'' input state */
12566 int stack_size; /* maximum number of simultaneous input sources */
12567
12568 @ @<Allocate or initialize ...@>=
12569 mp->stack_size = 300;
12570 mp->input_stack = xmalloc((mp->stack_size+1),sizeof(in_state_record));
12571
12572 @ @<Dealloc variables@>=
12573 xfree(mp->input_stack);
12574
12575 @ We've already defined the special variable |loc==cur_input.loc_field|
12576 in our discussion of basic input-output routines. The other components of
12577 |cur_input| are defined in the same way:
12578
12579 @d index mp->cur_input.index_field /* reference for buffer information */
12580 @d start mp->cur_input.start_field /* starting position in |buffer| */
12581 @d limit mp->cur_input.limit_field /* end of current line in |buffer| */
12582 @d name mp->cur_input.name_field /* name of the current file */
12583
12584 @ Let's look more closely now at the five control variables
12585 (|index|,~|start|,~|loc|,~|limit|,~|name|),
12586 assuming that \MP\ is reading a line of characters that have been input
12587 from some file or from the user's terminal. There is an array called
12588 |buffer| that acts as a stack of all lines of characters that are
12589 currently being read from files, including all lines on subsidiary
12590 levels of the input stack that are not yet completed. \MP\ will return to
12591 the other lines when it is finished with the present input file.
12592
12593 (Incidentally, on a machine with byte-oriented addressing, it would be
12594 appropriate to combine |buffer| with the |str_pool| array,
12595 letting the buffer entries grow downward from the top of the string pool
12596 and checking that these two tables don't bump into each other.)
12597
12598 The line we are currently working on begins in position |start| of the
12599 buffer; the next character we are about to read is |buffer[loc]|; and
12600 |limit| is the location of the last character present. We always have
12601 |loc<=limit|. For convenience, |buffer[limit]| has been set to |"%"|, so
12602 that the end of a line is easily sensed.
12603
12604 The |name| variable is a string number that designates the name of
12605 the current file, if we are reading an ordinary text file.  Special codes
12606 |is_term..max_spec_src| indicate other sources of input text.
12607
12608 @d is_term 0 /* |name| value when reading from the terminal for normal input */
12609 @d is_read 1 /* |name| value when executing a \&{readstring} or \&{readfrom} */
12610 @d is_scantok 2 /* |name| value when reading text generated by \&{scantokens} */
12611 @d max_spec_src is_scantok
12612
12613 @ Additional information about the current line is available via the
12614 |index| variable, which counts how many lines of characters are present
12615 in the buffer below the current level. We have |index=0| when reading
12616 from the terminal and prompting the user for each line; then if the user types,
12617 e.g., `\.{input figs}', we will have |index=1| while reading
12618 the file \.{figs.mp}. However, it does not follow that |index| is the
12619 same as the input stack pointer, since many of the levels on the input
12620 stack may come from token lists and some |index| values may correspond
12621 to \.{MPX} files that are not currently on the stack.
12622
12623 The global variable |in_open| is equal to the highest |index| value counting
12624 \.{MPX} files but excluding token-list input levels.  Thus, the number of
12625 partially read lines in the buffer is |in_open+1| and we have |in_open>=index|
12626 when we are not reading a token list.
12627
12628 If we are not currently reading from the terminal,
12629 we are reading from the file variable |input_file[index]|. We use
12630 the notation |terminal_input| as a convenient abbreviation for |name=is_term|,
12631 and |cur_file| as an abbreviation for |input_file[index]|.
12632
12633 When \MP\ is not reading from the terminal, the global variable |line| contains
12634 the line number in the current file, for use in error messages. More precisely,
12635 |line| is a macro for |line_stack[index]| and the |line_stack| array gives
12636 the line number for each file in the |input_file| array.
12637
12638 When an \.{MPX} file is opened the file name is stored in the |mpx_name|
12639 array so that the name doesn't get lost when the file is temporarily removed
12640 from the input stack.
12641 Thus when |input_file[k]| is an \.{MPX} file, its name is |mpx_name[k]|
12642 and it contains translated \TeX\ pictures for |input_file[k-1]|.
12643 Since this is not an \.{MPX} file, we have
12644 $$ \hbox{|mpx_name[k-1]<=absent|}. $$
12645 This |name| field is set to |finished| when |input_file[k]| is completely
12646 read.
12647
12648 If more information about the input state is needed, it can be
12649 included in small arrays like those shown here. For example,
12650 the current page or segment number in the input file might be put
12651 into a variable |page|, that is really a macro for the current entry
12652 in `\ignorespaces|page_stack:array[0..max_in_open] of integer|\unskip'
12653 by analogy with |line_stack|.
12654 @^system dependencies@>
12655
12656 @d terminal_input (name==is_term) /* are we reading from the terminal? */
12657 @d cur_file mp->input_file[index] /* the current |FILE *| variable */
12658 @d line mp->line_stack[index] /* current line number in the current source file */
12659 @d in_name mp->iname_stack[index] /* a string used to construct \.{MPX} file names */
12660 @d in_area mp->iarea_stack[index] /* another string for naming \.{MPX} files */
12661 @d absent 1 /* |name_field| value for unused |mpx_in_stack| entries */
12662 @d mpx_reading (mp->mpx_name[index]>absent)
12663   /* when reading a file, is it an \.{MPX} file? */
12664 @d finished 0
12665   /* |name_field| value when the corresponding \.{MPX} file is finished */
12666
12667 @<Glob...@>=
12668 integer in_open; /* the number of lines in the buffer, less one */
12669 unsigned int open_parens; /* the number of open text files */
12670 FILE  * *input_file ;
12671 integer *line_stack ; /* the line number for each file */
12672 char *  *iname_stack; /* used for naming \.{MPX} files */
12673 char *  *iarea_stack; /* used for naming \.{MPX} files */
12674 halfword*mpx_name  ;
12675
12676 @ @<Allocate or ...@>=
12677 mp->input_file  = xmalloc((mp->max_in_open+1),sizeof(FILE *));
12678 mp->line_stack  = xmalloc((mp->max_in_open+1),sizeof(integer));
12679 mp->iname_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12680 mp->iarea_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12681 mp->mpx_name    = xmalloc((mp->max_in_open+1),sizeof(halfword));
12682 {
12683   int k;
12684   for (k=0;k<=mp->max_in_open;k++) {
12685     mp->iname_stack[k] =NULL;
12686     mp->iarea_stack[k] =NULL;
12687   }
12688 }
12689
12690 @ @<Dealloc variables@>=
12691 {
12692   int l;
12693   for (l=0;l<=mp->max_in_open;l++) {
12694     xfree(mp->iname_stack[l]);
12695     xfree(mp->iarea_stack[l]);
12696   }
12697 }
12698 xfree(mp->input_file);
12699 xfree(mp->line_stack);
12700 xfree(mp->iname_stack);
12701 xfree(mp->iarea_stack);
12702 xfree(mp->mpx_name);
12703
12704
12705 @ However, all this discussion about input state really applies only to the
12706 case that we are inputting from a file. There is another important case,
12707 namely when we are currently getting input from a token list. In this case
12708 |index>max_in_open|, and the conventions about the other state variables
12709 are different:
12710
12711 \yskip\hang|loc| is a pointer to the current node in the token list, i.e.,
12712 the node that will be read next. If |loc=null|, the token list has been
12713 fully read.
12714
12715 \yskip\hang|start| points to the first node of the token list; this node
12716 may or may not contain a reference count, depending on the type of token
12717 list involved.
12718
12719 \yskip\hang|token_type|, which takes the place of |index| in the
12720 discussion above, is a code number that explains what kind of token list
12721 is being scanned.
12722
12723 \yskip\hang|name| points to the |eqtb| address of the control sequence
12724 being expanded, if the current token list is a macro not defined by
12725 \&{vardef}. Macros defined by \&{vardef} have |name=null|; their name
12726 can be deduced by looking at their first two parameters.
12727
12728 \yskip\hang|param_start|, which takes the place of |limit|, tells where
12729 the parameters of the current macro or loop text begin in the |param_stack|.
12730
12731 \yskip\noindent The |token_type| can take several values, depending on
12732 where the current token list came from:
12733
12734 \yskip
12735 \indent|forever_text|, if the token list being scanned is the body of
12736 a \&{forever} loop;
12737
12738 \indent|loop_text|, if the token list being scanned is the body of
12739 a \&{for} or \&{forsuffixes} loop;
12740
12741 \indent|parameter|, if a \&{text} or \&{suffix} parameter is being scanned;
12742
12743 \indent|backed_up|, if the token list being scanned has been inserted as
12744 `to be read again'.
12745
12746 \indent|inserted|, if the token list being scanned has been inserted as
12747 part of error recovery;
12748
12749 \indent|macro|, if the expansion of a user-defined symbolic token is being
12750 scanned.
12751
12752 \yskip\noindent
12753 The token list begins with a reference count if and only if |token_type=
12754 macro|.
12755 @^reference counts@>
12756
12757 @d token_type index /* type of current token list */
12758 @d token_state (index>(int)mp->max_in_open) /* are we scanning a token list? */
12759 @d file_state (index<=(int)mp->max_in_open) /* are we scanning a file line? */
12760 @d param_start limit /* base of macro parameters in |param_stack| */
12761 @d forever_text (mp->max_in_open+1) /* |token_type| code for loop texts */
12762 @d loop_text (mp->max_in_open+2) /* |token_type| code for loop texts */
12763 @d parameter (mp->max_in_open+3) /* |token_type| code for parameter texts */
12764 @d backed_up (mp->max_in_open+4) /* |token_type| code for texts to be reread */
12765 @d inserted (mp->max_in_open+5) /* |token_type| code for inserted texts */
12766 @d macro (mp->max_in_open+6) /* |token_type| code for macro replacement texts */
12767
12768 @ The |param_stack| is an auxiliary array used to hold pointers to the token
12769 lists for parameters at the current level and subsidiary levels of input.
12770 This stack grows at a different rate from the others.
12771
12772 @<Glob...@>=
12773 pointer *param_stack;  /* token list pointers for parameters */
12774 integer param_ptr; /* first unused entry in |param_stack| */
12775 integer max_param_stack;  /* largest value of |param_ptr| */
12776
12777 @ @<Allocate or initialize ...@>=
12778 mp->param_stack = xmalloc((mp->param_size+1),sizeof(pointer));
12779
12780 @ @<Dealloc variables@>=
12781 xfree(mp->param_stack);
12782
12783 @ Notice that the |line| isn't valid when |token_state| is true because it
12784 depends on |index|.  If we really need to know the line number for the
12785 topmost file in the index stack we use the following function.  If a page
12786 number or other information is needed, this routine should be modified to
12787 compute it as well.
12788 @^system dependencies@>
12789
12790 @<Declare a function called |true_line|@>=
12791 integer mp_true_line (MP mp) {
12792   int k; /* an index into the input stack */
12793   if ( file_state && (name>max_spec_src) ) {
12794      return line;
12795   } else { 
12796     k=mp->input_ptr;
12797     while ((k>0) &&
12798            ((mp->input_stack[(k-1)].index_field>mp->max_in_open)||
12799             (mp->input_stack[(k-1)].name_field<=max_spec_src))) {
12800       decr(k);
12801     }
12802     return mp->line_stack[(k-1)];
12803   }
12804   return 0; 
12805 }
12806
12807 @ Thus, the ``current input state'' can be very complicated indeed; there
12808 can be many levels and each level can arise in a variety of ways. The
12809 |show_context| procedure, which is used by \MP's error-reporting routine to
12810 print out the current input state on all levels down to the most recent
12811 line of characters from an input file, illustrates most of these conventions.
12812 The global variable |file_ptr| contains the lowest level that was
12813 displayed by this procedure.
12814
12815 @<Glob...@>=
12816 integer file_ptr; /* shallowest level shown by |show_context| */
12817
12818 @ The status at each level is indicated by printing two lines, where the first
12819 line indicates what was read so far and the second line shows what remains
12820 to be read. The context is cropped, if necessary, so that the first line
12821 contains at most |half_error_line| characters, and the second contains
12822 at most |error_line|. Non-current input levels whose |token_type| is
12823 `|backed_up|' are shown only if they have not been fully read.
12824
12825 @c void mp_show_context (MP mp) { /* prints where the scanner is */
12826   int old_setting; /* saved |selector| setting */
12827   @<Local variables for formatting calculations@>
12828   mp->file_ptr=mp->input_ptr; mp->input_stack[mp->file_ptr]=mp->cur_input;
12829   /* store current state */
12830   while (1) { 
12831     mp->cur_input=mp->input_stack[mp->file_ptr]; /* enter into the context */
12832     @<Display the current context@>;
12833     if ( file_state )
12834       if ( (name>max_spec_src) || (mp->file_ptr==0) ) break;
12835     decr(mp->file_ptr);
12836   }
12837   mp->cur_input=mp->input_stack[mp->input_ptr]; /* restore original state */
12838 }
12839
12840 @ @<Display the current context@>=
12841 if ( (mp->file_ptr==mp->input_ptr) || file_state ||
12842    (token_type!=backed_up) || (loc!=null) ) {
12843     /* we omit backed-up token lists that have already been read */
12844   mp->tally=0; /* get ready to count characters */
12845   old_setting=mp->selector;
12846   if ( file_state ) {
12847     @<Print location of current line@>;
12848     @<Pseudoprint the line@>;
12849   } else { 
12850     @<Print type of token list@>;
12851     @<Pseudoprint the token list@>;
12852   }
12853   mp->selector=old_setting; /* stop pseudoprinting */
12854   @<Print two lines using the tricky pseudoprinted information@>;
12855 }
12856
12857 @ This routine should be changed, if necessary, to give the best possible
12858 indication of where the current line resides in the input file.
12859 For example, on some systems it is best to print both a page and line number.
12860 @^system dependencies@>
12861
12862 @<Print location of current line@>=
12863 if ( name>max_spec_src ) {
12864   mp_print_nl(mp, "l."); mp_print_int(mp, mp_true_line(mp));
12865 } else if ( terminal_input ) {
12866   if ( mp->file_ptr==0 ) mp_print_nl(mp, "<*>");
12867   else mp_print_nl(mp, "<insert>");
12868 } else if ( name==is_scantok ) {
12869   mp_print_nl(mp, "<scantokens>");
12870 } else {
12871   mp_print_nl(mp, "<read>");
12872 }
12873 mp_print_char(mp, ' ')
12874
12875 @ Can't use case statement here because the |token_type| is not
12876 a constant expression.
12877
12878 @<Print type of token list@>=
12879 {
12880   if(token_type==forever_text) {
12881     mp_print_nl(mp, "<forever> ");
12882   } else if (token_type==loop_text) {
12883     @<Print the current loop value@>;
12884   } else if (token_type==parameter) {
12885     mp_print_nl(mp, "<argument> "); 
12886   } else if (token_type==backed_up) { 
12887     if ( loc==null ) mp_print_nl(mp, "<recently read> ");
12888     else mp_print_nl(mp, "<to be read again> ");
12889   } else if (token_type==inserted) {
12890     mp_print_nl(mp, "<inserted text> ");
12891   } else if (token_type==macro) {
12892     mp_print_ln(mp);
12893     if ( name!=null ) mp_print_text(name);
12894     else @<Print the name of a \&{vardef}'d macro@>;
12895     mp_print(mp, "->");
12896   } else {
12897     mp_print_nl(mp, "?");/* this should never happen */
12898 @.?\relax@>
12899   }
12900 }
12901
12902 @ The parameter that corresponds to a loop text is either a token list
12903 (in the case of \&{forsuffixes}) or a ``capsule'' (in the case of \&{for}).
12904 We'll discuss capsules later; for now, all we need to know is that
12905 the |link| field in a capsule parameter is |void| and that
12906 |print_exp(p,0)| displays the value of capsule~|p| in abbreviated form.
12907
12908 @d diov (null+1) /* a null pointer different from |null| */
12909
12910 @<Print the current loop value@>=
12911 { mp_print_nl(mp, "<for("); p=mp->param_stack[param_start];
12912   if ( p!=null ) {
12913     if ( link(p)==diov ) mp_print_exp(mp, p,0); /* we're in a \&{for} loop */
12914     else mp_show_token_list(mp, p,null,20,mp->tally);
12915   }
12916   mp_print(mp, ")> ");
12917 }
12918
12919 @ The first two parameters of a macro defined by \&{vardef} will be token
12920 lists representing the macro's prefix and ``at point.'' By putting these
12921 together, we get the macro's full name.
12922
12923 @<Print the name of a \&{vardef}'d macro@>=
12924 { p=mp->param_stack[param_start];
12925   if ( p==null ) {
12926     mp_show_token_list(mp, mp->param_stack[param_start+1],null,20,mp->tally);
12927   } else { 
12928     q=p;
12929     while ( link(q)!=null ) q=link(q);
12930     link(q)=mp->param_stack[param_start+1];
12931     mp_show_token_list(mp, p,null,20,mp->tally);
12932     link(q)=null;
12933   }
12934 }
12935
12936 @ Now it is necessary to explain a little trick. We don't want to store a long
12937 string that corresponds to a token list, because that string might take up
12938 lots of memory; and we are printing during a time when an error message is
12939 being given, so we dare not do anything that might overflow one of \MP's
12940 tables. So `pseudoprinting' is the answer: We enter a mode of printing
12941 that stores characters into a buffer of length |error_line|, where character
12942 $k+1$ is placed into \hbox{|trick_buf[k mod error_line]|} if
12943 |k<trick_count|, otherwise character |k| is dropped. Initially we set
12944 |tally:=0| and |trick_count:=1000000|; then when we reach the
12945 point where transition from line 1 to line 2 should occur, we
12946 set |first_count:=tally| and |trick_count:=@tmax@>(error_line,
12947 tally+1+error_line-half_error_line)|. At the end of the
12948 pseudoprinting, the values of |first_count|, |tally|, and
12949 |trick_count| give us all the information we need to print the two lines,
12950 and all of the necessary text is in |trick_buf|.
12951
12952 Namely, let |l| be the length of the descriptive information that appears
12953 on the first line. The length of the context information gathered for that
12954 line is |k=first_count|, and the length of the context information
12955 gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k<=h|,
12956 where |h=half_error_line|, we print |trick_buf[0..k-1]| after the
12957 descriptive information on line~1, and set |n:=l+k|; here |n| is the
12958 length of line~1. If $l+k>h$, some cropping is necessary, so we set |n:=h|
12959 and print `\.{...}' followed by
12960 $$\hbox{|trick_buf[(l+k-h+3)..k-1]|,}$$
12961 where subscripts of |trick_buf| are circular modulo |error_line|. The
12962 second line consists of |n|~spaces followed by |trick_buf[k..(k+m-1)]|,
12963 unless |n+m>error_line|; in the latter case, further cropping is done.
12964 This is easier to program than to explain.
12965
12966 @<Local variables for formatting...@>=
12967 int i; /* index into |buffer| */
12968 integer l; /* length of descriptive information on line 1 */
12969 integer m; /* context information gathered for line 2 */
12970 int n; /* length of line 1 */
12971 integer p; /* starting or ending place in |trick_buf| */
12972 integer q; /* temporary index */
12973
12974 @ The following code tells the print routines to gather
12975 the desired information.
12976
12977 @d begin_pseudoprint { 
12978   l=mp->tally; mp->tally=0; mp->selector=pseudo;
12979   mp->trick_count=1000000;
12980 }
12981 @d set_trick_count {
12982   mp->first_count=mp->tally;
12983   mp->trick_count=mp->tally+1+mp->error_line-mp->half_error_line;
12984   if ( mp->trick_count<mp->error_line ) mp->trick_count=mp->error_line;
12985 }
12986
12987 @ And the following code uses the information after it has been gathered.
12988
12989 @<Print two lines using the tricky pseudoprinted information@>=
12990 if ( mp->trick_count==1000000 ) set_trick_count;
12991   /* |set_trick_count| must be performed */
12992 if ( mp->tally<mp->trick_count ) m=mp->tally-mp->first_count;
12993 else m=mp->trick_count-mp->first_count; /* context on line 2 */
12994 if ( l+mp->first_count<=mp->half_error_line ) {
12995   p=0; n=l+mp->first_count;
12996 } else  { 
12997   mp_print(mp, "..."); p=l+mp->first_count-mp->half_error_line+3;
12998   n=mp->half_error_line;
12999 }
13000 for (q=p;q<=mp->first_count-1;q++) {
13001   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13002 }
13003 mp_print_ln(mp);
13004 for (q=1;q<=n;q++) {
13005   mp_print_char(mp, ' '); /* print |n| spaces to begin line~2 */
13006 }
13007 if ( m+n<=mp->error_line ) p=mp->first_count+m; 
13008 else p=mp->first_count+(mp->error_line-n-3);
13009 for (q=mp->first_count;q<=p-1;q++) {
13010   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13011 }
13012 if ( m+n>mp->error_line ) mp_print(mp, "...")
13013
13014 @ But the trick is distracting us from our current goal, which is to
13015 understand the input state. So let's concentrate on the data structures that
13016 are being pseudoprinted as we finish up the |show_context| procedure.
13017
13018 @<Pseudoprint the line@>=
13019 begin_pseudoprint;
13020 if ( limit>0 ) {
13021   for (i=start;i<=limit-1;i++) {
13022     if ( i==loc ) set_trick_count;
13023     mp_print_str(mp, mp->buffer[i]);
13024   }
13025 }
13026
13027 @ @<Pseudoprint the token list@>=
13028 begin_pseudoprint;
13029 if ( token_type!=macro ) mp_show_token_list(mp, start,loc,100000,0);
13030 else mp_show_macro(mp, start,loc,100000)
13031
13032 @ Here is the missing piece of |show_token_list| that is activated when the
13033 token beginning line~2 is about to be shown:
13034
13035 @<Do magic computation@>=set_trick_count
13036
13037 @* \[28] Maintaining the input stacks.
13038 The following subroutines change the input status in commonly needed ways.
13039
13040 First comes |push_input|, which stores the current state and creates a
13041 new level (having, initially, the same properties as the old).
13042
13043 @d push_input  { /* enter a new input level, save the old */
13044   if ( mp->input_ptr>mp->max_in_stack ) {
13045     mp->max_in_stack=mp->input_ptr;
13046     if ( mp->input_ptr==mp->stack_size ) {
13047       int l = (mp->stack_size+(mp->stack_size>>2));
13048       XREALLOC(mp->input_stack, (l+1), in_state_record);
13049       mp->stack_size = l;
13050     }         
13051   }
13052   mp->input_stack[mp->input_ptr]=mp->cur_input; /* stack the record */
13053   incr(mp->input_ptr);
13054 }
13055
13056 @ And of course what goes up must come down.
13057
13058 @d pop_input { /* leave an input level, re-enter the old */
13059     decr(mp->input_ptr); mp->cur_input=mp->input_stack[mp->input_ptr];
13060   }
13061
13062 @ Here is a procedure that starts a new level of token-list input, given
13063 a token list |p| and its type |t|. If |t=macro|, the calling routine should
13064 set |name|, reset~|loc|, and increase the macro's reference count.
13065
13066 @d back_list(A) mp_begin_token_list(mp, (A),backed_up) /* backs up a simple token list */
13067
13068 @c void mp_begin_token_list (MP mp,pointer p, quarterword t)  { 
13069   push_input; start=p; token_type=t;
13070   param_start=mp->param_ptr; loc=p;
13071 }
13072
13073 @ When a token list has been fully scanned, the following computations
13074 should be done as we leave that level of input.
13075 @^inner loop@>
13076
13077 @c void mp_end_token_list (MP mp) { /* leave a token-list input level */
13078   pointer p; /* temporary register */
13079   if ( token_type>=backed_up ) { /* token list to be deleted */
13080     if ( token_type<=inserted ) { 
13081       mp_flush_token_list(mp, start); goto DONE;
13082     } else {
13083       mp_delete_mac_ref(mp, start); /* update reference count */
13084     }
13085   }
13086   while ( mp->param_ptr>param_start ) { /* parameters must be flushed */
13087     decr(mp->param_ptr);
13088     p=mp->param_stack[mp->param_ptr];
13089     if ( p!=null ) {
13090       if ( link(p)==diov ) { /* it's an \&{expr} parameter */
13091         mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
13092       } else {
13093         mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
13094       }
13095     }
13096   }
13097 DONE: 
13098   pop_input; check_interrupt;
13099 }
13100
13101 @ The contents of |cur_cmd,cur_mod,cur_sym| are placed into an equivalent
13102 token by the |cur_tok| routine.
13103 @^inner loop@>
13104
13105 @c @<Declare the procedure called |make_exp_copy|@>;
13106 pointer mp_cur_tok (MP mp) {
13107   pointer p; /* a new token node */
13108   small_number save_type; /* |cur_type| to be restored */
13109   integer save_exp; /* |cur_exp| to be restored */
13110   if ( mp->cur_sym==0 ) {
13111     if ( mp->cur_cmd==capsule_token ) {
13112       save_type=mp->cur_type; save_exp=mp->cur_exp;
13113       mp_make_exp_copy(mp, mp->cur_mod); p=mp_stash_cur_exp(mp); link(p)=null;
13114       mp->cur_type=save_type; mp->cur_exp=save_exp;
13115     } else { 
13116       p=mp_get_node(mp, token_node_size);
13117       value(p)=mp->cur_mod; name_type(p)=mp_token;
13118       if ( mp->cur_cmd==numeric_token ) type(p)=mp_known;
13119       else type(p)=mp_string_type;
13120     }
13121   } else { 
13122     fast_get_avail(p); info(p)=mp->cur_sym;
13123   }
13124   return p;
13125 }
13126
13127 @ Sometimes \MP\ has read too far and wants to ``unscan'' what it has
13128 seen. The |back_input| procedure takes care of this by putting the token
13129 just scanned back into the input stream, ready to be read again.
13130 If |cur_sym<>0|, the values of |cur_cmd| and |cur_mod| are irrelevant.
13131
13132 @<Declarations@>= 
13133 void mp_back_input (MP mp);
13134
13135 @ @c void mp_back_input (MP mp) {/* undoes one token of input */
13136   pointer p; /* a token list of length one */
13137   p=mp_cur_tok(mp);
13138   while ( token_state &&(loc==null) ) 
13139     mp_end_token_list(mp); /* conserve stack space */
13140   back_list(p);
13141 }
13142
13143 @ The |back_error| routine is used when we want to restore or replace an
13144 offending token just before issuing an error message.  We disable interrupts
13145 during the call of |back_input| so that the help message won't be lost.
13146
13147 @<Declarations@>=
13148 void mp_error (MP mp);
13149 void mp_back_error (MP mp);
13150
13151 @ @c void mp_back_error (MP mp) { /* back up one token and call |error| */
13152   mp->OK_to_interrupt=false; 
13153   mp_back_input(mp); 
13154   mp->OK_to_interrupt=true; mp_error(mp);
13155 }
13156 void mp_ins_error (MP mp) { /* back up one inserted token and call |error| */
13157   mp->OK_to_interrupt=false; 
13158   mp_back_input(mp); token_type=inserted;
13159   mp->OK_to_interrupt=true; mp_error(mp);
13160 }
13161
13162 @ The |begin_file_reading| procedure starts a new level of input for lines
13163 of characters to be read from a file, or as an insertion from the
13164 terminal. It does not take care of opening the file, nor does it set |loc|
13165 or |limit| or |line|.
13166 @^system dependencies@>
13167
13168 @c void mp_begin_file_reading (MP mp) { 
13169   if ( mp->in_open==mp->max_in_open ) 
13170     mp_overflow(mp, "text input levels",mp->max_in_open);
13171 @:MetaPost capacity exceeded text input levels}{\quad text input levels@>
13172   if ( mp->first==mp->buf_size ) 
13173     mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13174   incr(mp->in_open); push_input; index=mp->in_open;
13175   mp->mpx_name[index]=absent;
13176   start=mp->first;
13177   name=is_term; /* |terminal_input| is now |true| */
13178 }
13179
13180 @ Conversely, the variables must be downdated when such a level of input
13181 is finished.  Any associated \.{MPX} file must also be closed and popped
13182 off the file stack.
13183
13184 @c void mp_end_file_reading (MP mp) { 
13185   if ( mp->in_open>index ) {
13186     if ( (mp->mpx_name[mp->in_open]==absent)||(name<=max_spec_src) ) {
13187       mp_confusion(mp, "endinput");
13188 @:this can't happen endinput}{\quad endinput@>
13189     } else { 
13190       fclose(mp->input_file[mp->in_open]); /* close an \.{MPX} file */
13191       delete_str_ref(mp->mpx_name[mp->in_open]);
13192       decr(mp->in_open);
13193     }
13194   }
13195   mp->first=start;
13196   if ( index!=mp->in_open ) mp_confusion(mp, "endinput");
13197   if ( name>max_spec_src ) {
13198     fclose(cur_file);
13199     delete_str_ref(name);
13200     xfree(in_name); in_name=NULL;
13201     xfree(in_area); in_area=NULL;
13202   }
13203   pop_input; decr(mp->in_open);
13204 }
13205
13206 @ Here is a function that tries to resume input from an \.{MPX} file already
13207 associated with the current input file.  It returns |false| if this doesn't
13208 work.
13209
13210 @c boolean mp_begin_mpx_reading (MP mp) { 
13211   if ( mp->in_open!=index+1 ) {
13212      return false;
13213   } else { 
13214     if ( mp->mpx_name[mp->in_open]<=absent ) mp_confusion(mp, "mpx");
13215 @:this can't happen mpx}{\quad mpx@>
13216     if ( mp->first==mp->buf_size ) 
13217       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13218     push_input; index=mp->in_open;
13219     start=mp->first;
13220     name=mp->mpx_name[mp->in_open]; add_str_ref(name);
13221     @<Put an empty line in the input buffer@>;
13222     return true;
13223   }
13224 }
13225
13226 @ This procedure temporarily stops reading an \.{MPX} file.
13227
13228 @c void mp_end_mpx_reading (MP mp) { 
13229   if ( mp->in_open!=index ) mp_confusion(mp, "mpx");
13230 @:this can't happen mpx}{\quad mpx@>
13231   if ( loc<limit ) {
13232     @<Complain that we are not at the end of a line in the \.{MPX} file@>;
13233   }
13234   mp->first=start;
13235   pop_input;
13236 }
13237
13238 @ Here we enforce a restriction that simplifies the input stacks considerably.
13239 This should not inconvenience the user because \.{MPX} files are generated
13240 by an auxiliary program called \.{DVItoMP}.
13241
13242 @ @<Complain that we are not at the end of a line in the \.{MPX} file@>=
13243
13244 print_err("`mpxbreak' must be at the end of a line");
13245 help4("This file contains picture expressions for btex...etex")
13246   ("blocks.  Such files are normally generated automatically")
13247   ("but this one seems to be messed up.  I'm going to ignore")
13248   ("the rest of this line.");
13249 mp_error(mp);
13250 }
13251
13252 @ In order to keep the stack from overflowing during a long sequence of
13253 inserted `\.{show}' commands, the following routine removes completed
13254 error-inserted lines from memory.
13255
13256 @c void mp_clear_for_error_prompt (MP mp) { 
13257   while ( file_state && terminal_input &&
13258     (mp->input_ptr>0)&&(loc==limit) ) mp_end_file_reading(mp);
13259   mp_print_ln(mp); clear_terminal;
13260 }
13261
13262 @ To get \MP's whole input mechanism going, we perform the following
13263 actions.
13264
13265 @<Initialize the input routines@>=
13266 { mp->input_ptr=0; mp->max_in_stack=0;
13267   mp->in_open=0; mp->open_parens=0; mp->max_buf_stack=0;
13268   mp->param_ptr=0; mp->max_param_stack=0;
13269   mp->first=1;
13270   start=1; index=0; line=0; name=is_term;
13271   mp->mpx_name[0]=absent;
13272   mp->force_eof=false;
13273   if ( ! mp_init_terminal(mp) ) exit(EXIT_FAILURE);
13274   limit=mp->last; mp->first=mp->last+1; 
13275   /* |init_terminal| has set |loc| and |last| */
13276 }
13277
13278 @* \[29] Getting the next token.
13279 The heart of \MP's input mechanism is the |get_next| procedure, which
13280 we shall develop in the next few sections of the program. Perhaps we
13281 shouldn't actually call it the ``heart,'' however; it really acts as \MP's
13282 eyes and mouth, reading the source files and gobbling them up. And it also
13283 helps \MP\ to regurgitate stored token lists that are to be processed again.
13284
13285 The main duty of |get_next| is to input one token and to set |cur_cmd|
13286 and |cur_mod| to that token's command code and modifier. Furthermore, if
13287 the input token is a symbolic token, that token's |hash| address
13288 is stored in |cur_sym|; otherwise |cur_sym| is set to zero.
13289
13290 Underlying this simple description is a certain amount of complexity
13291 because of all the cases that need to be handled.
13292 However, the inner loop of |get_next| is reasonably short and fast.
13293
13294 @ Before getting into |get_next|, we need to consider a mechanism by which
13295 \MP\ helps keep errors from propagating too far. Whenever the program goes
13296 into a mode where it keeps calling |get_next| repeatedly until a certain
13297 condition is met, it sets |scanner_status| to some value other than |normal|.
13298 Then if an input file ends, or if an `\&{outer}' symbol appears,
13299 an appropriate error recovery will be possible.
13300
13301 The global variable |warning_info| helps in this error recovery by providing
13302 additional information. For example, |warning_info| might indicate the
13303 name of a macro whose replacement text is being scanned.
13304
13305 @d normal 0 /* |scanner_status| at ``quiet times'' */
13306 @d skipping 1 /* |scanner_status| when false conditional text is being skipped */
13307 @d flushing 2 /* |scanner_status| when junk after a statement is being ignored */
13308 @d absorbing 3 /* |scanner_status| when a \&{text} parameter is being scanned */
13309 @d var_defining 4 /* |scanner_status| when a \&{vardef} is being scanned */
13310 @d op_defining 5 /* |scanner_status| when a macro \&{def} is being scanned */
13311 @d loop_defining 6 /* |scanner_status| when a \&{for} loop is being scanned */
13312 @d tex_flushing 7 /* |scanner_status| when skipping \TeX\ material */
13313
13314 @<Glob...@>=
13315 integer scanner_status; /* are we scanning at high speed? */
13316 integer warning_info; /* if so, what else do we need to know,
13317     in case an error occurs? */
13318
13319 @ @<Initialize the input routines@>=
13320 mp->scanner_status=normal;
13321
13322 @ The following subroutine
13323 is called when an `\&{outer}' symbolic token has been scanned or
13324 when the end of a file has been reached. These two cases are distinguished
13325 by |cur_sym|, which is zero at the end of a file.
13326
13327 @c boolean mp_check_outer_validity (MP mp) {
13328   pointer p; /* points to inserted token list */
13329   if ( mp->scanner_status==normal ) {
13330     return true;
13331   } else if ( mp->scanner_status==tex_flushing ) {
13332     @<Check if the file has ended while flushing \TeX\ material and set the
13333       result value for |check_outer_validity|@>;
13334   } else { 
13335     mp->deletions_allowed=false;
13336     @<Back up an outer symbolic token so that it can be reread@>;
13337     if ( mp->scanner_status>skipping ) {
13338       @<Tell the user what has run away and try to recover@>;
13339     } else { 
13340       print_err("Incomplete if; all text was ignored after line ");
13341 @.Incomplete if...@>
13342       mp_print_int(mp, mp->warning_info);
13343       help3("A forbidden `outer' token occurred in skipped text.")
13344         ("This kind of error happens when you say `if...' and forget")
13345         ("the matching `fi'. I've inserted a `fi'; this might work.");
13346       if ( mp->cur_sym==0 ) 
13347         mp->help_line[2]="The file ended while I was skipping conditional text.";
13348       mp->cur_sym=frozen_fi; mp_ins_error(mp);
13349     }
13350     mp->deletions_allowed=true; 
13351         return false;
13352   }
13353 }
13354
13355 @ @<Check if the file has ended while flushing \TeX\ material and set...@>=
13356 if ( mp->cur_sym!=0 ) { 
13357    return true;
13358 } else { 
13359   mp->deletions_allowed=false;
13360   print_err("TeX mode didn't end; all text was ignored after line ");
13361   mp_print_int(mp, mp->warning_info);
13362   help2("The file ended while I was looking for the `etex' to")
13363     ("finish this TeX material.  I've inserted `etex' now.");
13364   mp->cur_sym = frozen_etex;
13365   mp_ins_error(mp);
13366   mp->deletions_allowed=true;
13367   return false;
13368 }
13369
13370 @ @<Back up an outer symbolic token so that it can be reread@>=
13371 if ( mp->cur_sym!=0 ) {
13372   p=mp_get_avail(mp); info(p)=mp->cur_sym;
13373   back_list(p); /* prepare to read the symbolic token again */
13374 }
13375
13376 @ @<Tell the user what has run away...@>=
13377
13378   mp_runaway(mp); /* print the definition-so-far */
13379   if ( mp->cur_sym==0 ) {
13380     print_err("File ended");
13381 @.File ended while scanning...@>
13382   } else { 
13383     print_err("Forbidden token found");
13384 @.Forbidden token found...@>
13385   }
13386   mp_print(mp, " while scanning ");
13387   help4("I suspect you have forgotten an `enddef',")
13388     ("causing me to read past where you wanted me to stop.")
13389     ("I'll try to recover; but if the error is serious,")
13390     ("you'd better type `E' or `X' now and fix your file.");
13391   switch (mp->scanner_status) {
13392     @<Complete the error message,
13393       and set |cur_sym| to a token that might help recover from the error@>
13394   } /* there are no other cases */
13395   mp_ins_error(mp);
13396 }
13397
13398 @ As we consider various kinds of errors, it is also appropriate to
13399 change the first line of the help message just given; |help_line[3]|
13400 points to the string that might be changed.
13401
13402 @<Complete the error message,...@>=
13403 case flushing: 
13404   mp_print(mp, "to the end of the statement");
13405   mp->help_line[3]="A previous error seems to have propagated,";
13406   mp->cur_sym=frozen_semicolon;
13407   break;
13408 case absorbing: 
13409   mp_print(mp, "a text argument");
13410   mp->help_line[3]="It seems that a right delimiter was left out,";
13411   if ( mp->warning_info==0 ) {
13412     mp->cur_sym=frozen_end_group;
13413   } else { 
13414     mp->cur_sym=frozen_right_delimiter;
13415     equiv(frozen_right_delimiter)=mp->warning_info;
13416   }
13417   break;
13418 case var_defining:
13419 case op_defining: 
13420   mp_print(mp, "the definition of ");
13421   if ( mp->scanner_status==op_defining ) 
13422      mp_print_text(mp->warning_info);
13423   else 
13424      mp_print_variable_name(mp, mp->warning_info);
13425   mp->cur_sym=frozen_end_def;
13426   break;
13427 case loop_defining: 
13428   mp_print(mp, "the text of a "); 
13429   mp_print_text(mp->warning_info);
13430   mp_print(mp, " loop");
13431   mp->help_line[3]="I suspect you have forgotten an `endfor',";
13432   mp->cur_sym=frozen_end_for;
13433   break;
13434
13435 @ The |runaway| procedure displays the first part of the text that occurred
13436 when \MP\ began its special |scanner_status|, if that text has been saved.
13437
13438 @<Declare the procedure called |runaway|@>=
13439 void mp_runaway (MP mp) { 
13440   if ( mp->scanner_status>flushing ) { 
13441      mp_print_nl(mp, "Runaway ");
13442          switch (mp->scanner_status) { 
13443          case absorbing: mp_print(mp, "text?"); break;
13444          case var_defining: 
13445      case op_defining: mp_print(mp,"definition?"); break;
13446      case loop_defining: mp_print(mp, "loop?"); break;
13447      } /* there are no other cases */
13448      mp_print_ln(mp); 
13449      mp_show_token_list(mp, link(hold_head),null,mp->error_line-10,0);
13450   }
13451 }
13452
13453 @ We need to mention a procedure that may be called by |get_next|.
13454
13455 @<Declarations@>= 
13456 void mp_firm_up_the_line (MP mp);
13457
13458 @ And now we're ready to take the plunge into |get_next| itself.
13459 Note that the behavior depends on the |scanner_status| because percent signs
13460 and double quotes need to be passed over when skipping TeX material.
13461
13462 @c 
13463 void mp_get_next (MP mp) {
13464   /* sets |cur_cmd|, |cur_mod|, |cur_sym| to next token */
13465 @^inner loop@>
13466   /*restart*/ /* go here to get the next input token */
13467   /*exit*/ /* go here when the next input token has been got */
13468   /*|common_ending|*/ /* go here to finish getting a symbolic token */
13469   /*found*/ /* go here when the end of a symbolic token has been found */
13470   /*switch*/ /* go here to branch on the class of an input character */
13471   /*|start_numeric_token|,|start_decimal_token|,|fin_numeric_token|,|done|*/
13472     /* go here at crucial stages when scanning a number */
13473   int k; /* an index into |buffer| */
13474   ASCII_code c; /* the current character in the buffer */
13475   ASCII_code class; /* its class number */
13476   integer n,f; /* registers for decimal-to-binary conversion */
13477 RESTART: 
13478   mp->cur_sym=0;
13479   if ( file_state ) {
13480     @<Input from external file; |goto restart| if no input found,
13481     or |return| if a non-symbolic token is found@>;
13482   } else {
13483     @<Input from token list; |goto restart| if end of list or
13484       if a parameter needs to be expanded,
13485       or |return| if a non-symbolic token is found@>;
13486   }
13487 COMMON_ENDING: 
13488   @<Finish getting the symbolic token in |cur_sym|;
13489    |goto restart| if it is illegal@>;
13490 }
13491
13492 @ When a symbolic token is declared to be `\&{outer}', its command code
13493 is increased by |outer_tag|.
13494 @^inner loop@>
13495
13496 @<Finish getting the symbolic token in |cur_sym|...@>=
13497 mp->cur_cmd=eq_type(mp->cur_sym); mp->cur_mod=equiv(mp->cur_sym);
13498 if ( mp->cur_cmd>=outer_tag ) {
13499   if ( mp_check_outer_validity(mp) ) 
13500     mp->cur_cmd=mp->cur_cmd-outer_tag;
13501   else 
13502     goto RESTART;
13503 }
13504
13505 @ A percent sign appears in |buffer[limit]|; this makes it unnecessary
13506 to have a special test for end-of-line.
13507 @^inner loop@>
13508
13509 @<Input from external file;...@>=
13510
13511 SWITCH: 
13512   c=mp->buffer[loc]; incr(loc); class=mp->char_class[c];
13513   switch (class) {
13514   case digit_class: goto START_NUMERIC_TOKEN; break;
13515   case period_class: 
13516     class=mp->char_class[mp->buffer[loc]];
13517     if ( class>period_class ) {
13518       goto SWITCH;
13519     } else if ( class<period_class ) { /* |class=digit_class| */
13520       n=0; goto START_DECIMAL_TOKEN;
13521     }
13522 @:. }{\..\ token@>
13523     break;
13524   case space_class: goto SWITCH; break;
13525   case percent_class: 
13526     if ( mp->scanner_status==tex_flushing ) {
13527       if ( loc<limit ) goto SWITCH;
13528     }
13529     @<Move to next line of file, or |goto restart| if there is no next line@>;
13530     check_interrupt;
13531     goto SWITCH;
13532     break;
13533   case string_class: 
13534     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13535     else @<Get a string token and |return|@>;
13536     break;
13537   case isolated_classes: 
13538     k=loc-1; goto FOUND; break;
13539   case invalid_class: 
13540     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13541     else @<Decry the invalid character and |goto restart|@>;
13542     break;
13543   default: break; /* letters, etc. */
13544   }
13545   k=loc-1;
13546   while ( mp->char_class[mp->buffer[loc]]==class ) incr(loc);
13547   goto FOUND;
13548 START_NUMERIC_TOKEN:
13549   @<Get the integer part |n| of a numeric token;
13550     set |f:=0| and |goto fin_numeric_token| if there is no decimal point@>;
13551 START_DECIMAL_TOKEN:
13552   @<Get the fraction part |f| of a numeric token@>;
13553 FIN_NUMERIC_TOKEN:
13554   @<Pack the numeric and fraction parts of a numeric token
13555     and |return|@>;
13556 FOUND: 
13557   mp->cur_sym=mp_id_lookup(mp, k,loc-k);
13558 }
13559
13560 @ We go to |restart| instead of to |SWITCH|, because |state| might equal
13561 |token_list| after the error has been dealt with
13562 (cf.\ |clear_for_error_prompt|).
13563
13564 @<Decry the invalid...@>=
13565
13566   print_err("Text line contains an invalid character");
13567 @.Text line contains...@>
13568   help2("A funny symbol that I can\'t read has just been input.")
13569     ("Continue, and I'll forget that it ever happened.");
13570   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13571   goto RESTART;
13572 }
13573
13574 @ @<Get a string token and |return|@>=
13575
13576   if ( mp->buffer[loc]=='"' ) {
13577     mp->cur_mod=rts("");
13578   } else { 
13579     k=loc; mp->buffer[limit+1]='"';
13580     do {  
13581      incr(loc);
13582     } while (mp->buffer[loc]!='"');
13583     if ( loc>limit ) {
13584       @<Decry the missing string delimiter and |goto restart|@>;
13585     }
13586     if ( loc==k+1 ) {
13587       mp->cur_mod=mp->buffer[k];
13588     } else { 
13589       str_room(loc-k);
13590       do {  
13591         append_char(mp->buffer[k]); incr(k);
13592       } while (k!=loc);
13593       mp->cur_mod=mp_make_string(mp);
13594     }
13595   }
13596   incr(loc); mp->cur_cmd=string_token; 
13597   return;
13598 }
13599
13600 @ We go to |restart| after this error message, not to |SWITCH|,
13601 because the |clear_for_error_prompt| routine might have reinstated
13602 |token_state| after |error| has finished.
13603
13604 @<Decry the missing string delimiter and |goto restart|@>=
13605
13606   loc=limit; /* the next character to be read on this line will be |"%"| */
13607   print_err("Incomplete string token has been flushed");
13608 @.Incomplete string token...@>
13609   help3("Strings should finish on the same line as they began.")
13610     ("I've deleted the partial string; you might want to")
13611     ("insert another by typing, e.g., `I\"new string\"'.");
13612   mp->deletions_allowed=false; mp_error(mp);
13613   mp->deletions_allowed=true; 
13614   goto RESTART;
13615 }
13616
13617 @ @<Get the integer part |n| of a numeric token...@>=
13618 n=c-'0';
13619 while ( mp->char_class[mp->buffer[loc]]==digit_class ) {
13620   if ( n<32768 ) n=10*n+mp->buffer[loc]-'0';
13621   incr(loc);
13622 }
13623 if ( mp->buffer[loc]=='.' ) 
13624   if ( mp->char_class[mp->buffer[loc+1]]==digit_class ) 
13625     goto DONE;
13626 f=0; 
13627 goto FIN_NUMERIC_TOKEN;
13628 DONE: incr(loc)
13629
13630 @ @<Get the fraction part |f| of a numeric token@>=
13631 k=0;
13632 do { 
13633   if ( k<17 ) { /* digits for |k>=17| cannot affect the result */
13634     mp->dig[k]=mp->buffer[loc]-'0'; incr(k);
13635   }
13636   incr(loc);
13637 } while (mp->char_class[mp->buffer[loc]]==digit_class);
13638 f=mp_round_decimals(mp, k);
13639 if ( f==unity ) {
13640   incr(n); f=0;
13641 }
13642
13643 @ @<Pack the numeric and fraction parts of a numeric token and |return|@>=
13644 if ( n<32768 ) {
13645   @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>;
13646 } else if ( mp->scanner_status!=tex_flushing ) {
13647   print_err("Enormous number has been reduced");
13648 @.Enormous number...@>
13649   help2("I can\'t handle numbers bigger than 32767.99998;")
13650     ("so I've changed your constant to that maximum amount.");
13651   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13652   mp->cur_mod=el_gordo;
13653 }
13654 mp->cur_cmd=numeric_token; return
13655
13656 @ @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>=
13657
13658   mp->cur_mod=n*unity+f;
13659   if ( mp->cur_mod>=fraction_one ) {
13660     if ( (mp->internal[warning_check]>0) &&
13661          (mp->scanner_status!=tex_flushing) ) {
13662       print_err("Number is too large (");
13663       mp_print_scaled(mp, mp->cur_mod);
13664       mp_print_char(mp, ')');
13665       help3("It is at least 4096. Continue and I'll try to cope")
13666       ("with that big value; but it might be dangerous.")
13667       ("(Set warningcheck:=0 to suppress this message.)");
13668       mp_error(mp);
13669     }
13670   }
13671 }
13672
13673 @ Let's consider now what happens when |get_next| is looking at a token list.
13674 @^inner loop@>
13675
13676 @<Input from token list;...@>=
13677 if ( loc>=mp->hi_mem_min ) { /* one-word token */
13678   mp->cur_sym=info(loc); loc=link(loc); /* move to next */
13679   if ( mp->cur_sym>=expr_base ) {
13680     if ( mp->cur_sym>=suffix_base ) {
13681       @<Insert a suffix or text parameter and |goto restart|@>;
13682     } else { 
13683       mp->cur_cmd=capsule_token;
13684       mp->cur_mod=mp->param_stack[param_start+mp->cur_sym-(expr_base)];
13685       mp->cur_sym=0; return;
13686     }
13687   }
13688 } else if ( loc>null ) {
13689   @<Get a stored numeric or string or capsule token and |return|@>
13690 } else { /* we are done with this token list */
13691   mp_end_token_list(mp); goto RESTART; /* resume previous level */
13692 }
13693
13694 @ @<Insert a suffix or text parameter...@>=
13695
13696   if ( mp->cur_sym>=text_base ) mp->cur_sym=mp->cur_sym-mp->param_size;
13697   /* |param_size=text_base-suffix_base| */
13698   mp_begin_token_list(mp,
13699                       mp->param_stack[param_start+mp->cur_sym-(suffix_base)],
13700                       parameter);
13701   goto RESTART;
13702 }
13703
13704 @ @<Get a stored numeric or string or capsule token...@>=
13705
13706   if ( name_type(loc)==mp_token ) {
13707     mp->cur_mod=value(loc);
13708     if ( type(loc)==mp_known ) {
13709       mp->cur_cmd=numeric_token;
13710     } else { 
13711       mp->cur_cmd=string_token; add_str_ref(mp->cur_mod);
13712     }
13713   } else { 
13714     mp->cur_mod=loc; mp->cur_cmd=capsule_token;
13715   };
13716   loc=link(loc); return;
13717 }
13718
13719 @ All of the easy branches of |get_next| have now been taken care of.
13720 There is one more branch.
13721
13722 @<Move to next line of file, or |goto restart|...@>=
13723 if ( name>max_spec_src ) {
13724   @<Read next line of file into |buffer|, or
13725     |goto restart| if the file has ended@>;
13726 } else { 
13727   if ( mp->input_ptr>0 ) {
13728      /* text was inserted during error recovery or by \&{scantokens} */
13729     mp_end_file_reading(mp); goto RESTART; /* resume previous level */
13730   }
13731   if ( mp->selector<log_only || mp->selector>=write_file) mp_open_log_file(mp);
13732   if ( mp->interaction>mp_nonstop_mode ) {
13733     if ( limit==start ) /* previous line was empty */
13734       mp_print_nl(mp, "(Please type a command or say `end')");
13735 @.Please type...@>
13736     mp_print_ln(mp); mp->first=start;
13737     prompt_input("*"); /* input on-line into |buffer| */
13738 @.*\relax@>
13739     limit=mp->last; mp->buffer[limit]='%';
13740     mp->first=limit+1; loc=start;
13741   } else {
13742     mp_fatal_error(mp, "*** (job aborted, no legal end found)");
13743 @.job aborted@>
13744     /* nonstop mode, which is intended for overnight batch processing,
13745     never waits for on-line input */
13746   }
13747 }
13748
13749 @ The global variable |force_eof| is normally |false|; it is set |true|
13750 by an \&{endinput} command.
13751
13752 @<Glob...@>=
13753 boolean force_eof; /* should the next \&{input} be aborted early? */
13754
13755 @ We must decrement |loc| in order to leave the buffer in a valid state
13756 when an error condition causes us to |goto restart| without calling
13757 |end_file_reading|.
13758
13759 @<Read next line of file into |buffer|, or
13760   |goto restart| if the file has ended@>=
13761
13762   incr(line); mp->first=start;
13763   if ( ! mp->force_eof ) {
13764     if ( mp_input_ln(mp, cur_file,true) ) /* not end of file */
13765       mp_firm_up_the_line(mp); /* this sets |limit| */
13766     else 
13767       mp->force_eof=true;
13768   };
13769   if ( mp->force_eof ) {
13770     mp->force_eof=false;
13771     decr(loc);
13772     if ( mpx_reading ) {
13773       @<Complain that the \.{MPX} file ended unexpectly; then set
13774         |cur_sym:=frozen_mpx_break| and |goto comon_ending|@>;
13775     } else { 
13776       mp_print_char(mp, ')'); decr(mp->open_parens);
13777       update_terminal; /* show user that file has been read */
13778       mp_end_file_reading(mp); /* resume previous level */
13779       if ( mp_check_outer_validity(mp) ) goto  RESTART;  
13780       else goto RESTART;
13781     }
13782   }
13783   mp->buffer[limit]='%'; mp->first=limit+1; loc=start; /* ready to read */
13784 }
13785
13786 @ We should never actually come to the end of an \.{MPX} file because such
13787 files should have an \&{mpxbreak} after the translation of the last
13788 \&{btex}$\,\ldots\,$\&{etex} block.
13789
13790 @<Complain that the \.{MPX} file ended unexpectly; then set...@>=
13791
13792   mp->mpx_name[index]=finished;
13793   print_err("mpx file ended unexpectedly");
13794   help4("The file had too few picture expressions for btex...etex")
13795     ("blocks.  Such files are normally generated automatically")
13796     ("but this one got messed up.  You might want to insert a")
13797     ("picture expression now.");
13798   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13799   mp->cur_sym=frozen_mpx_break; goto COMMON_ENDING;
13800 }
13801
13802 @ Sometimes we want to make it look as though we have just read a blank line
13803 without really doing so.
13804
13805 @<Put an empty line in the input buffer@>=
13806 mp->last=mp->first; limit=mp->last; /* simulate |input_ln| and |firm_up_the_line| */
13807 mp->buffer[limit]='%'; mp->first=limit+1; loc=start
13808
13809 @ If the user has set the |pausing| parameter to some positive value,
13810 and if nonstop mode has not been selected, each line of input is displayed
13811 on the terminal and the transcript file, followed by `\.{=>}'.
13812 \MP\ waits for a response. If the response is null (i.e., if nothing is
13813 typed except perhaps a few blank spaces), the original
13814 line is accepted as it stands; otherwise the line typed is
13815 used instead of the line in the file.
13816
13817 @c void mp_firm_up_the_line (MP mp) {
13818   size_t k; /* an index into |buffer| */
13819   limit=mp->last;
13820   if ( mp->internal[pausing]>0 ) if ( mp->interaction>mp_nonstop_mode ) {
13821     wake_up_terminal; mp_print_ln(mp);
13822     if ( start<limit ) {
13823       for (k=(size_t)start;k<=(size_t)(limit-1);k++) {
13824         mp_print_str(mp, mp->buffer[k]);
13825       } 
13826     }
13827     mp->first=limit; prompt_input("=>"); /* wait for user response */
13828 @.=>@>
13829     if ( mp->last>mp->first ) {
13830       for (k=mp->first;k<=mp->last-1;k++) { /* move line down in buffer */
13831         mp->buffer[k+start-mp->first]=mp->buffer[k];
13832       }
13833       limit=start+mp->last-mp->first;
13834     }
13835   }
13836 }
13837
13838 @* \[30] Dealing with \TeX\ material.
13839 The \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}$\,\ldots\,$\&{etex}
13840 features need to be implemented at a low level in the scanning process
13841 so that \MP\ can stay in synch with the a preprocessor that treats
13842 blocks of \TeX\ material as they occur in the input file without trying
13843 to expand \MP\ macros.  Thus we need a special version of |get_next|
13844 that does not expand macros and such but does handle \&{btex},
13845 \&{verbatimtex}, etc.
13846
13847 The special version of |get_next| is called |get_t_next|.  It works by flushing
13848 \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}\allowbreak
13849 $\,\ldots\,$\&{etex} blocks, switching to the \.{MPX} file when it sees
13850 \&{btex}, and switching back when it sees \&{mpxbreak}.
13851
13852 @d btex_code 0
13853 @d verbatim_code 1
13854
13855 @ @<Put each...@>=
13856 mp_primitive(mp, "btex",start_tex,btex_code);
13857 @:btex_}{\&{btex} primitive@>
13858 mp_primitive(mp, "verbatimtex",start_tex,verbatim_code);
13859 @:verbatimtex_}{\&{verbatimtex} primitive@>
13860 mp_primitive(mp, "etex",etex_marker,0); mp->eqtb[frozen_etex]=mp->eqtb[mp->cur_sym];
13861 @:etex_}{\&{etex} primitive@>
13862 mp_primitive(mp, "mpxbreak",mpx_break,0); mp->eqtb[frozen_mpx_break]=mp->eqtb[mp->cur_sym];
13863 @:mpx_break_}{\&{mpxbreak} primitive@>
13864
13865 @ @<Cases of |print_cmd...@>=
13866 case start_tex: if ( m==btex_code ) mp_print(mp, "btex");
13867   else mp_print(mp, "verbatimtex"); break;
13868 case etex_marker: mp_print(mp, "etex"); break;
13869 case mpx_break: mp_print(mp, "mpxbreak"); break;
13870
13871 @ Actually, |get_t_next| is a macro that avoids procedure overhead except
13872 in the unusual case where \&{btex}, \&{verbatimtex}, \&{etex}, or \&{mpxbreak}
13873 is encountered.
13874
13875 @d get_t_next {mp_get_next(mp); if ( mp->cur_cmd<=max_pre_command ) mp_t_next(mp); }
13876
13877 @<Declarations@>=
13878 void mp_start_mpx_input (MP mp);
13879
13880 @ @c 
13881 void mp_t_next (MP mp) {
13882   int old_status; /* saves the |scanner_status| */
13883   integer old_info; /* saves the |warning_info| */
13884   while ( mp->cur_cmd<=max_pre_command ) {
13885     if ( mp->cur_cmd==mpx_break ) {
13886       if ( ! file_state || (mp->mpx_name[index]==absent) ) {
13887         @<Complain about a misplaced \&{mpxbreak}@>;
13888       } else { 
13889         mp_end_mpx_reading(mp); 
13890         goto TEX_FLUSH;
13891       }
13892     } else if ( mp->cur_cmd==start_tex ) {
13893       if ( token_state || (name<=max_spec_src) ) {
13894         @<Complain that we are not reading a file@>;
13895       } else if ( mpx_reading ) {
13896         @<Complain that \.{MPX} files cannot contain \TeX\ material@>;
13897       } else if ( (mp->cur_mod!=verbatim_code)&&
13898                   (mp->mpx_name[index]!=finished) ) {
13899         if ( ! mp_begin_mpx_reading(mp) ) mp_start_mpx_input(mp);
13900       } else {
13901         goto TEX_FLUSH;
13902       }
13903     } else {
13904        @<Complain about a misplaced \&{etex}@>;
13905     }
13906     goto COMMON_ENDING;
13907   TEX_FLUSH: 
13908     @<Flush the \TeX\ material@>;
13909   COMMON_ENDING: 
13910     mp_get_next(mp);
13911   }
13912 }
13913
13914 @ We could be in the middle of an operation such as skipping false conditional
13915 text when \TeX\ material is encountered, so we must be careful to save the
13916 |scanner_status|.
13917
13918 @<Flush the \TeX\ material@>=
13919 old_status=mp->scanner_status;
13920 old_info=mp->warning_info;
13921 mp->scanner_status=tex_flushing;
13922 mp->warning_info=line;
13923 do {  mp_get_next(mp); } while (mp->cur_cmd!=etex_marker);
13924 mp->scanner_status=old_status;
13925 mp->warning_info=old_info
13926
13927 @ @<Complain that \.{MPX} files cannot contain \TeX\ material@>=
13928 { print_err("An mpx file cannot contain btex or verbatimtex blocks");
13929 help4("This file contains picture expressions for btex...etex")
13930   ("blocks.  Such files are normally generated automatically")
13931   ("but this one seems to be messed up.  I'll just keep going")
13932   ("and hope for the best.");
13933 mp_error(mp);
13934 }
13935
13936 @ @<Complain that we are not reading a file@>=
13937 { print_err("You can only use `btex' or `verbatimtex' in a file");
13938 help3("I'll have to ignore this preprocessor command because it")
13939   ("only works when there is a file to preprocess.  You might")
13940   ("want to delete everything up to the next `etex`.");
13941 mp_error(mp);
13942 }
13943
13944 @ @<Complain about a misplaced \&{mpxbreak}@>=
13945 { print_err("Misplaced mpxbreak");
13946 help2("I'll ignore this preprocessor command because it")
13947   ("doesn't belong here");
13948 mp_error(mp);
13949 }
13950
13951 @ @<Complain about a misplaced \&{etex}@>=
13952 { print_err("Extra etex will be ignored");
13953 help1("There is no btex or verbatimtex for this to match");
13954 mp_error(mp);
13955 }
13956
13957 @* \[31] Scanning macro definitions.
13958 \MP\ has a variety of ways to tuck tokens away into token lists for later
13959 use: Macros can be defined with \&{def}, \&{vardef}, \&{primarydef}, etc.;
13960 repeatable code can be defined with \&{for}, \&{forever}, \&{forsuffixes}.
13961 All such operations are handled by the routines in this part of the program.
13962
13963 The modifier part of each command code is zero for the ``ending delimiters''
13964 like \&{enddef} and \&{endfor}.
13965
13966 @d start_def 1 /* command modifier for \&{def} */
13967 @d var_def 2 /* command modifier for \&{vardef} */
13968 @d end_def 0 /* command modifier for \&{enddef} */
13969 @d start_forever 1 /* command modifier for \&{forever} */
13970 @d end_for 0 /* command modifier for \&{endfor} */
13971
13972 @<Put each...@>=
13973 mp_primitive(mp, "def",macro_def,start_def);
13974 @:def_}{\&{def} primitive@>
13975 mp_primitive(mp, "vardef",macro_def,var_def);
13976 @:var_def_}{\&{vardef} primitive@>
13977 mp_primitive(mp, "primarydef",macro_def,secondary_primary_macro);
13978 @:primary_def_}{\&{primarydef} primitive@>
13979 mp_primitive(mp, "secondarydef",macro_def,tertiary_secondary_macro);
13980 @:secondary_def_}{\&{secondarydef} primitive@>
13981 mp_primitive(mp, "tertiarydef",macro_def,expression_tertiary_macro);
13982 @:tertiary_def_}{\&{tertiarydef} primitive@>
13983 mp_primitive(mp, "enddef",macro_def,end_def); mp->eqtb[frozen_end_def]=mp->eqtb[mp->cur_sym];
13984 @:end_def_}{\&{enddef} primitive@>
13985 @#
13986 mp_primitive(mp, "for",iteration,expr_base);
13987 @:for_}{\&{for} primitive@>
13988 mp_primitive(mp, "forsuffixes",iteration,suffix_base);
13989 @:for_suffixes_}{\&{forsuffixes} primitive@>
13990 mp_primitive(mp, "forever",iteration,start_forever);
13991 @:forever_}{\&{forever} primitive@>
13992 mp_primitive(mp, "endfor",iteration,end_for); mp->eqtb[frozen_end_for]=mp->eqtb[mp->cur_sym];
13993 @:end_for_}{\&{endfor} primitive@>
13994
13995 @ @<Cases of |print_cmd...@>=
13996 case macro_def:
13997   if ( m<=var_def ) {
13998     if ( m==start_def ) mp_print(mp, "def");
13999     else if ( m<start_def ) mp_print(mp, "enddef");
14000     else mp_print(mp, "vardef");
14001   } else if ( m==secondary_primary_macro ) { 
14002     mp_print(mp, "primarydef");
14003   } else if ( m==tertiary_secondary_macro ) { 
14004     mp_print(mp, "secondarydef");
14005   } else { 
14006     mp_print(mp, "tertiarydef");
14007   }
14008   break;
14009 case iteration: 
14010   if ( m<=start_forever ) {
14011     if ( m==start_forever ) mp_print(mp, "forever"); 
14012     else mp_print(mp, "endfor");
14013   } else if ( m==expr_base ) {
14014     mp_print(mp, "for"); 
14015   } else { 
14016     mp_print(mp, "forsuffixes");
14017   }
14018   break;
14019
14020 @ Different macro-absorbing operations have different syntaxes, but they
14021 also have a lot in common. There is a list of special symbols that are to
14022 be replaced by parameter tokens; there is a special command code that
14023 ends the definition; the quotation conventions are identical.  Therefore
14024 it makes sense to have most of the work done by a single subroutine. That
14025 subroutine is called |scan_toks|.
14026
14027 The first parameter to |scan_toks| is the command code that will
14028 terminate scanning (either |macro_def|, |loop_repeat|, or |iteration|).
14029
14030 The second parameter, |subst_list|, points to a (possibly empty) list
14031 of two-word nodes whose |info| and |value| fields specify symbol tokens
14032 before and after replacement. The list will be returned to free storage
14033 by |scan_toks|.
14034
14035 The third parameter is simply appended to the token list that is built.
14036 And the final parameter tells how many of the special operations
14037 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#} are to be replaced by suffix parameters.
14038 When such parameters are present, they are called \.{(SUFFIX0)},
14039 \.{(SUFFIX1)}, and \.{(SUFFIX2)}.
14040
14041 @c pointer mp_scan_toks (MP mp,command_code terminator, pointer 
14042   subst_list, pointer tail_end, small_number suffix_count) {
14043   pointer p; /* tail of the token list being built */
14044   pointer q; /* temporary for link management */
14045   integer balance; /* left delimiters minus right delimiters */
14046   p=hold_head; balance=1; link(hold_head)=null;
14047   while (1) { 
14048     get_t_next;
14049     if ( mp->cur_sym>0 ) {
14050       @<Substitute for |cur_sym|, if it's on the |subst_list|@>;
14051       if ( mp->cur_cmd==terminator ) {
14052         @<Adjust the balance; |break| if it's zero@>;
14053       } else if ( mp->cur_cmd==macro_special ) {
14054         @<Handle quoted symbols, \.{\#\AT!}, \.{\AT!}, or \.{\AT!\#}@>;
14055       }
14056     }
14057     link(p)=mp_cur_tok(mp); p=link(p);
14058   }
14059   link(p)=tail_end; mp_flush_node_list(mp, subst_list);
14060   return link(hold_head);
14061 }
14062
14063 @ @<Substitute for |cur_sym|...@>=
14064
14065   q=subst_list;
14066   while ( q!=null ) {
14067     if ( info(q)==mp->cur_sym ) {
14068       mp->cur_sym=value(q); mp->cur_cmd=relax; break;
14069     }
14070     q=link(q);
14071   }
14072 }
14073
14074 @ @<Adjust the balance; |break| if it's zero@>=
14075 if ( mp->cur_mod>0 ) {
14076   incr(balance);
14077 } else { 
14078   decr(balance);
14079   if ( balance==0 )
14080     break;
14081 }
14082
14083 @ Four commands are intended to be used only within macro texts: \&{quote},
14084 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#}. They are variants of a single command
14085 code called |macro_special|.
14086
14087 @d quote 0 /* |macro_special| modifier for \&{quote} */
14088 @d macro_prefix 1 /* |macro_special| modifier for \.{\#\AT!} */
14089 @d macro_at 2 /* |macro_special| modifier for \.{\AT!} */
14090 @d macro_suffix 3 /* |macro_special| modifier for \.{\AT!\#} */
14091
14092 @<Put each...@>=
14093 mp_primitive(mp, "quote",macro_special,quote);
14094 @:quote_}{\&{quote} primitive@>
14095 mp_primitive(mp, "#@@",macro_special,macro_prefix);
14096 @:]]]\#\AT!_}{\.{\#\AT!} primitive@>
14097 mp_primitive(mp, "@@",macro_special,macro_at);
14098 @:]]]\AT!_}{\.{\AT!} primitive@>
14099 mp_primitive(mp, "@@#",macro_special,macro_suffix);
14100 @:]]]\AT!\#_}{\.{\AT!\#} primitive@>
14101
14102 @ @<Cases of |print_cmd...@>=
14103 case macro_special: 
14104   switch (m) {
14105   case macro_prefix: mp_print(mp, "#@@"); break;
14106   case macro_at: mp_print_char(mp, '@@'); break;
14107   case macro_suffix: mp_print(mp, "@@#"); break;
14108   default: mp_print(mp, "quote"); break;
14109   }
14110   break;
14111
14112 @ @<Handle quoted...@>=
14113
14114   if ( mp->cur_mod==quote ) { get_t_next; } 
14115   else if ( mp->cur_mod<=suffix_count ) 
14116     mp->cur_sym=suffix_base-1+mp->cur_mod;
14117 }
14118
14119 @ Here is a routine that's used whenever a token will be redefined. If
14120 the user's token is unredefinable, the `|frozen_inaccessible|' token is
14121 substituted; the latter is redefinable but essentially impossible to use,
14122 hence \MP's tables won't get fouled up.
14123
14124 @c void mp_get_symbol (MP mp) { /* sets |cur_sym| to a safe symbol */
14125 RESTART: 
14126   get_t_next;
14127   if ( (mp->cur_sym==0)||(mp->cur_sym>frozen_inaccessible) ) {
14128     print_err("Missing symbolic token inserted");
14129 @.Missing symbolic token...@>
14130     help3("Sorry: You can\'t redefine a number, string, or expr.")
14131       ("I've inserted an inaccessible symbol so that your")
14132       ("definition will be completed without mixing me up too badly.");
14133     if ( mp->cur_sym>0 )
14134       mp->help_line[2]="Sorry: You can\'t redefine my error-recovery tokens.";
14135     else if ( mp->cur_cmd==string_token ) 
14136       delete_str_ref(mp->cur_mod);
14137     mp->cur_sym=frozen_inaccessible; mp_ins_error(mp); goto RESTART;
14138   }
14139 }
14140
14141 @ Before we actually redefine a symbolic token, we need to clear away its
14142 former value, if it was a variable. The following stronger version of
14143 |get_symbol| does that.
14144
14145 @c void mp_get_clear_symbol (MP mp) { 
14146   mp_get_symbol(mp); mp_clear_symbol(mp, mp->cur_sym,false);
14147 }
14148
14149 @ Here's another little subroutine; it checks that an equals sign
14150 or assignment sign comes along at the proper place in a macro definition.
14151
14152 @c void mp_check_equals (MP mp) { 
14153   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
14154      mp_missing_err(mp, "=");
14155 @.Missing `='@>
14156     help5("The next thing in this `def' should have been `=',")
14157       ("because I've already looked at the definition heading.")
14158       ("But don't worry; I'll pretend that an equals sign")
14159       ("was present. Everything from here to `enddef'")
14160       ("will be the replacement text of this macro.");
14161     mp_back_error(mp);
14162   }
14163 }
14164
14165 @ A \&{primarydef}, \&{secondarydef}, or \&{tertiarydef} is rather easily
14166 handled now that we have |scan_toks|.  In this case there are
14167 two parameters, which will be \.{EXPR0} and \.{EXPR1} (i.e.,
14168 |expr_base| and |expr_base+1|).
14169
14170 @c void mp_make_op_def (MP mp) {
14171   command_code m; /* the type of definition */
14172   pointer p,q,r; /* for list manipulation */
14173   m=mp->cur_mod;
14174   mp_get_symbol(mp); q=mp_get_node(mp, token_node_size);
14175   info(q)=mp->cur_sym; value(q)=expr_base;
14176   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym;
14177   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
14178   info(p)=mp->cur_sym; value(p)=expr_base+1; link(p)=q;
14179   get_t_next; mp_check_equals(mp);
14180   mp->scanner_status=op_defining; q=mp_get_avail(mp); ref_count(q)=null;
14181   r=mp_get_avail(mp); link(q)=r; info(r)=general_macro;
14182   link(r)=mp_scan_toks(mp, macro_def,p,null,0);
14183   mp->scanner_status=normal; eq_type(mp->warning_info)=m;
14184   equiv(mp->warning_info)=q; mp_get_x_next(mp);
14185 }
14186
14187 @ Parameters to macros are introduced by the keywords \&{expr},
14188 \&{suffix}, \&{text}, \&{primary}, \&{secondary}, and \&{tertiary}.
14189
14190 @<Put each...@>=
14191 mp_primitive(mp, "expr",param_type,expr_base);
14192 @:expr_}{\&{expr} primitive@>
14193 mp_primitive(mp, "suffix",param_type,suffix_base);
14194 @:suffix_}{\&{suffix} primitive@>
14195 mp_primitive(mp, "text",param_type,text_base);
14196 @:text_}{\&{text} primitive@>
14197 mp_primitive(mp, "primary",param_type,primary_macro);
14198 @:primary_}{\&{primary} primitive@>
14199 mp_primitive(mp, "secondary",param_type,secondary_macro);
14200 @:secondary_}{\&{secondary} primitive@>
14201 mp_primitive(mp, "tertiary",param_type,tertiary_macro);
14202 @:tertiary_}{\&{tertiary} primitive@>
14203
14204 @ @<Cases of |print_cmd...@>=
14205 case param_type:
14206   if ( m>=expr_base ) {
14207     if ( m==expr_base ) mp_print(mp, "expr");
14208     else if ( m==suffix_base ) mp_print(mp, "suffix");
14209     else mp_print(mp, "text");
14210   } else if ( m<secondary_macro ) {
14211     mp_print(mp, "primary");
14212   } else if ( m==secondary_macro ) {
14213     mp_print(mp, "secondary");
14214   } else {
14215     mp_print(mp, "tertiary");
14216   }
14217   break;
14218
14219 @ Let's turn next to the more complex processing associated with \&{def}
14220 and \&{vardef}. When the following procedure is called, |cur_mod|
14221 should be either |start_def| or |var_def|.
14222
14223 @c @<Declare the procedure called |check_delimiter|@>;
14224 @<Declare the function called |scan_declared_variable|@>;
14225 void mp_scan_def (MP mp) {
14226   int m; /* the type of definition */
14227   int n; /* the number of special suffix parameters */
14228   int k; /* the total number of parameters */
14229   int c; /* the kind of macro we're defining */
14230   pointer r; /* parameter-substitution list */
14231   pointer q; /* tail of the macro token list */
14232   pointer p; /* temporary storage */
14233   halfword base; /* |expr_base|, |suffix_base|, or |text_base| */
14234   pointer l_delim,r_delim; /* matching delimiters */
14235   m=mp->cur_mod; c=general_macro; link(hold_head)=null;
14236   q=mp_get_avail(mp); ref_count(q)=null; r=null;
14237   @<Scan the token or variable to be defined;
14238     set |n|, |scanner_status|, and |warning_info|@>;
14239   k=n;
14240   if ( mp->cur_cmd==left_delimiter ) {
14241     @<Absorb delimited parameters, putting them into lists |q| and |r|@>;
14242   }
14243   if ( mp->cur_cmd==param_type ) {
14244     @<Absorb undelimited parameters, putting them into list |r|@>;
14245   }
14246   mp_check_equals(mp);
14247   p=mp_get_avail(mp); info(p)=c; link(q)=p;
14248   @<Attach the replacement text to the tail of node |p|@>;
14249   mp->scanner_status=normal; mp_get_x_next(mp);
14250 }
14251
14252 @ We don't put `|frozen_end_group|' into the replacement text of
14253 a \&{vardef}, because the user may want to redefine `\.{endgroup}'.
14254
14255 @<Attach the replacement text to the tail of node |p|@>=
14256 if ( m==start_def ) {
14257   link(p)=mp_scan_toks(mp, macro_def,r,null,n);
14258 } else { 
14259   q=mp_get_avail(mp); info(q)=mp->bg_loc; link(p)=q;
14260   p=mp_get_avail(mp); info(p)=mp->eg_loc;
14261   link(q)=mp_scan_toks(mp, macro_def,r,p,n);
14262 }
14263 if ( mp->warning_info==bad_vardef ) 
14264   mp_flush_token_list(mp, value(bad_vardef))
14265
14266 @ @<Glob...@>=
14267 int bg_loc;
14268 int eg_loc; /* hash addresses of `\.{begingroup}' and `\.{endgroup}' */
14269
14270 @ @<Scan the token or variable to be defined;...@>=
14271 if ( m==start_def ) {
14272   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym; get_t_next;
14273   mp->scanner_status=op_defining; n=0;
14274   eq_type(mp->warning_info)=defined_macro; equiv(mp->warning_info)=q;
14275 } else { 
14276   p=mp_scan_declared_variable(mp);
14277   mp_flush_variable(mp, equiv(info(p)),link(p),true);
14278   mp->warning_info=mp_find_variable(mp, p); mp_flush_list(mp, p);
14279   if ( mp->warning_info==null ) @<Change to `\.{a bad variable}'@>;
14280   mp->scanner_status=var_defining; n=2;
14281   if ( mp->cur_cmd==macro_special ) if ( mp->cur_mod==macro_suffix ) {/* \.{\AT!\#} */
14282     n=3; get_t_next;
14283   }
14284   type(mp->warning_info)=mp_unsuffixed_macro-2+n; value(mp->warning_info)=q;
14285 } /* |mp_suffixed_macro=mp_unsuffixed_macro+1| */
14286
14287 @ @<Change to `\.{a bad variable}'@>=
14288
14289   print_err("This variable already starts with a macro");
14290 @.This variable already...@>
14291   help2("After `vardef a' you can\'t say `vardef a.b'.")
14292     ("So I'll have to discard this definition.");
14293   mp_error(mp); mp->warning_info=bad_vardef;
14294 }
14295
14296 @ @<Initialize table entries...@>=
14297 name_type(bad_vardef)=mp_root; link(bad_vardef)=frozen_bad_vardef;
14298 equiv(frozen_bad_vardef)=bad_vardef; eq_type(frozen_bad_vardef)=tag_token;
14299
14300 @ @<Absorb delimited parameters, putting them into lists |q| and |r|@>=
14301 do {  
14302   l_delim=mp->cur_sym; r_delim=mp->cur_mod; get_t_next;
14303   if ( (mp->cur_cmd==param_type)&&(mp->cur_mod>=expr_base) ) {
14304    base=mp->cur_mod;
14305   } else { 
14306     print_err("Missing parameter type; `expr' will be assumed");
14307 @.Missing parameter type@>
14308     help1("You should've had `expr' or `suffix' or `text' here.");
14309     mp_back_error(mp); base=expr_base;
14310   }
14311   @<Absorb parameter tokens for type |base|@>;
14312   mp_check_delimiter(mp, l_delim,r_delim);
14313   get_t_next;
14314 } while (mp->cur_cmd==left_delimiter)
14315
14316 @ @<Absorb parameter tokens for type |base|@>=
14317 do { 
14318   link(q)=mp_get_avail(mp); q=link(q); info(q)=base+k;
14319   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size); 
14320   value(p)=base+k; info(p)=mp->cur_sym;
14321   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14322 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
14323   incr(k); link(p)=r; r=p; get_t_next;
14324 } while (mp->cur_cmd==comma)
14325
14326 @ @<Absorb undelimited parameters, putting them into list |r|@>=
14327
14328   p=mp_get_node(mp, token_node_size);
14329   if ( mp->cur_mod<expr_base ) {
14330     c=mp->cur_mod; value(p)=expr_base+k;
14331   } else { 
14332     value(p)=mp->cur_mod+k;
14333     if ( mp->cur_mod==expr_base ) c=expr_macro;
14334     else if ( mp->cur_mod==suffix_base ) c=suffix_macro;
14335     else c=text_macro;
14336   }
14337   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14338   incr(k); mp_get_symbol(mp); info(p)=mp->cur_sym; link(p)=r; r=p; get_t_next;
14339   if ( c==expr_macro ) if ( mp->cur_cmd==of_token ) {
14340     c=of_macro; p=mp_get_node(mp, token_node_size);
14341     if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14342     value(p)=expr_base+k; mp_get_symbol(mp); info(p)=mp->cur_sym;
14343     link(p)=r; r=p; get_t_next;
14344   }
14345 }
14346
14347 @* \[32] Expanding the next token.
14348 Only a few command codes |<min_command| can possibly be returned by
14349 |get_t_next|; in increasing order, they are
14350 |if_test|, |fi_or_else|, |input|, |iteration|, |repeat_loop|,
14351 |exit_test|, |relax|, |scan_tokens|, |expand_after|, and |defined_macro|.
14352
14353 \MP\ usually gets the next token of input by saying |get_x_next|. This is
14354 like |get_t_next| except that it keeps getting more tokens until
14355 finding |cur_cmd>=min_command|. In other words, |get_x_next| expands
14356 macros and removes conditionals or iterations or input instructions that
14357 might be present.
14358
14359 It follows that |get_x_next| might invoke itself recursively. In fact,
14360 there is massive recursion, since macro expansion can involve the
14361 scanning of arbitrarily complex expressions, which in turn involve
14362 macro expansion and conditionals, etc.
14363 @^recursion@>
14364
14365 Therefore it's necessary to declare a whole bunch of |forward|
14366 procedures at this point, and to insert some other procedures
14367 that will be invoked by |get_x_next|.
14368
14369 @<Declarations@>= 
14370 void mp_scan_primary (MP mp);
14371 void mp_scan_secondary (MP mp);
14372 void mp_scan_tertiary (MP mp);
14373 void mp_scan_expression (MP mp);
14374 void mp_scan_suffix (MP mp);
14375 @<Declare the procedure called |macro_call|@>;
14376 void mp_get_boolean (MP mp);
14377 void mp_pass_text (MP mp);
14378 void mp_conditional (MP mp);
14379 void mp_start_input (MP mp);
14380 void mp_begin_iteration (MP mp);
14381 void mp_resume_iteration (MP mp);
14382 void mp_stop_iteration (MP mp);
14383
14384 @ An auxiliary subroutine called |expand| is used by |get_x_next|
14385 when it has to do exotic expansion commands.
14386
14387 @c void mp_expand (MP mp) {
14388   pointer p; /* for list manipulation */
14389   size_t k; /* something that we hope is |<=buf_size| */
14390   pool_pointer j; /* index into |str_pool| */
14391   if ( mp->internal[tracing_commands]>unity ) 
14392     if ( mp->cur_cmd!=defined_macro )
14393       show_cur_cmd_mod;
14394   switch (mp->cur_cmd)  {
14395   case if_test:
14396     mp_conditional(mp); /* this procedure is discussed in Part 36 below */
14397     break;
14398   case fi_or_else:
14399     @<Terminate the current conditional and skip to \&{fi}@>;
14400     break;
14401   case input:
14402     @<Initiate or terminate input from a file@>;
14403     break;
14404   case iteration:
14405     if ( mp->cur_mod==end_for ) {
14406       @<Scold the user for having an extra \&{endfor}@>;
14407     } else {
14408       mp_begin_iteration(mp); /* this procedure is discussed in Part 37 below */
14409     }
14410     break;
14411   case repeat_loop: 
14412     @<Repeat a loop@>;
14413     break;
14414   case exit_test: 
14415     @<Exit a loop if the proper time has come@>;
14416     break;
14417   case relax: 
14418     break;
14419   case expand_after: 
14420     @<Expand the token after the next token@>;
14421     break;
14422   case scan_tokens: 
14423     @<Put a string into the input buffer@>;
14424     break;
14425   case defined_macro:
14426    mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14427    break;
14428   }; /* there are no other cases */
14429 };
14430
14431 @ @<Scold the user...@>=
14432
14433   print_err("Extra `endfor'");
14434 @.Extra `endfor'@>
14435   help2("I'm not currently working on a for loop,")
14436     ("so I had better not try to end anything.");
14437   mp_error(mp);
14438 }
14439
14440 @ The processing of \&{input} involves the |start_input| subroutine,
14441 which will be declared later; the processing of \&{endinput} is trivial.
14442
14443 @<Put each...@>=
14444 mp_primitive(mp, "input",input,0);
14445 @:input_}{\&{input} primitive@>
14446 mp_primitive(mp, "endinput",input,1);
14447 @:end_input_}{\&{endinput} primitive@>
14448
14449 @ @<Cases of |print_cmd_mod|...@>=
14450 case input: 
14451   if ( m==0 ) mp_print(mp, "input");
14452   else mp_print(mp, "endinput");
14453   break;
14454
14455 @ @<Initiate or terminate input...@>=
14456 if ( mp->cur_mod>0 ) mp->force_eof=true;
14457 else mp_start_input(mp)
14458
14459 @ We'll discuss the complicated parts of loop operations later. For now
14460 it suffices to know that there's a global variable called |loop_ptr|
14461 that will be |null| if no loop is in progress.
14462
14463 @<Repeat a loop@>=
14464 { while ( token_state &&(loc==null) ) 
14465     mp_end_token_list(mp); /* conserve stack space */
14466   if ( mp->loop_ptr==null ) {
14467     print_err("Lost loop");
14468 @.Lost loop@>
14469     help2("I'm confused; after exiting from a loop, I still seem")
14470       ("to want to repeat it. I'll try to forget the problem.");
14471     mp_error(mp);
14472   } else {
14473     mp_resume_iteration(mp); /* this procedure is in Part 37 below */
14474   }
14475 }
14476
14477 @ @<Exit a loop if the proper time has come@>=
14478 { mp_get_boolean(mp);
14479   if ( mp->internal[tracing_commands]>unity ) 
14480     mp_show_cmd_mod(mp, nullary,mp->cur_exp);
14481   if ( mp->cur_exp==true_code ) {
14482     if ( mp->loop_ptr==null ) {
14483       print_err("No loop is in progress");
14484 @.No loop is in progress@>
14485       help1("Why say `exitif' when there's nothing to exit from?");
14486       if ( mp->cur_cmd==semicolon ) mp_error(mp); else mp_back_error(mp);
14487     } else {
14488      @<Exit prematurely from an iteration@>;
14489     }
14490   } else if ( mp->cur_cmd!=semicolon ) {
14491     mp_missing_err(mp, ";");
14492 @.Missing `;'@>
14493     help2("After `exitif <boolean exp>' I expect to see a semicolon.")
14494     ("I shall pretend that one was there."); mp_back_error(mp);
14495   }
14496 }
14497
14498 @ Here we use the fact that |forever_text| is the only |token_type| that
14499 is less than |loop_text|.
14500
14501 @<Exit prematurely...@>=
14502 { p=null;
14503   do {  
14504     if ( file_state ) {
14505       mp_end_file_reading(mp);
14506     } else { 
14507       if ( token_type<=loop_text ) p=start;
14508       mp_end_token_list(mp);
14509     }
14510   } while (p==null);
14511   if ( p!=info(mp->loop_ptr) ) mp_fatal_error(mp, "*** (loop confusion)");
14512 @.loop confusion@>
14513   mp_stop_iteration(mp); /* this procedure is in Part 34 below */
14514 }
14515
14516 @ @<Expand the token after the next token@>=
14517 { get_t_next;
14518   p=mp_cur_tok(mp); get_t_next;
14519   if ( mp->cur_cmd<min_command ) mp_expand(mp); 
14520   else mp_back_input(mp);
14521   back_list(p);
14522 }
14523
14524 @ @<Put a string into the input buffer@>=
14525 { mp_get_x_next(mp); mp_scan_primary(mp);
14526   if ( mp->cur_type!=mp_string_type ) {
14527     mp_disp_err(mp, null,"Not a string");
14528 @.Not a string@>
14529     help2("I'm going to flush this expression, since")
14530        ("scantokens should be followed by a known string.");
14531     mp_put_get_flush_error(mp, 0);
14532   } else { 
14533     mp_back_input(mp);
14534     if ( length(mp->cur_exp)>0 )
14535        @<Pretend we're reading a new one-line file@>;
14536   }
14537 }
14538
14539 @ @<Pretend we're reading a new one-line file@>=
14540 { mp_begin_file_reading(mp); name=is_scantok;
14541   k=mp->first+length(mp->cur_exp);
14542   if ( k>=mp->max_buf_stack ) {
14543     while ( k>=mp->buf_size ) {
14544       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
14545     }
14546     mp->max_buf_stack=k+1;
14547   }
14548   j=mp->str_start[mp->cur_exp]; limit=k;
14549   while ( mp->first<(size_t)limit ) {
14550     mp->buffer[mp->first]=mp->str_pool[j]; incr(j); incr(mp->first);
14551   }
14552   mp->buffer[limit]='%'; mp->first=limit+1; loc=start; 
14553   mp_flush_cur_exp(mp, 0);
14554 }
14555
14556 @ Here finally is |get_x_next|.
14557
14558 The expression scanning routines to be considered later
14559 communicate via the global quantities |cur_type| and |cur_exp|;
14560 we must be very careful to save and restore these quantities while
14561 macros are being expanded.
14562 @^inner loop@>
14563
14564 @<Declarations@>=
14565 void mp_get_x_next (MP mp);
14566
14567 @ @c void mp_get_x_next (MP mp) {
14568   pointer save_exp; /* a capsule to save |cur_type| and |cur_exp| */
14569   get_t_next;
14570   if ( mp->cur_cmd<min_command ) {
14571     save_exp=mp_stash_cur_exp(mp);
14572     do {  
14573       if ( mp->cur_cmd==defined_macro ) 
14574         mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14575       else 
14576         mp_expand(mp);
14577       get_t_next;
14578      } while (mp->cur_cmd<min_command);
14579      mp_unstash_cur_exp(mp, save_exp); /* that restores |cur_type| and |cur_exp| */
14580   }
14581 }
14582
14583 @ Now let's consider the |macro_call| procedure, which is used to start up
14584 all user-defined macros. Since the arguments to a macro might be expressions,
14585 |macro_call| is recursive.
14586 @^recursion@>
14587
14588 The first parameter to |macro_call| points to the reference count of the
14589 token list that defines the macro. The second parameter contains any
14590 arguments that have already been parsed (see below).  The third parameter
14591 points to the symbolic token that names the macro. If the third parameter
14592 is |null|, the macro was defined by \&{vardef}, so its name can be
14593 reconstructed from the prefix and ``at'' arguments found within the
14594 second parameter.
14595
14596 What is this second parameter? It's simply a linked list of one-word items,
14597 whose |info| fields point to the arguments. In other words, if |arg_list=null|,
14598 no arguments have been scanned yet; otherwise |info(arg_list)| points to
14599 the first scanned argument, and |link(arg_list)| points to the list of
14600 further arguments (if any).
14601
14602 Arguments of type \&{expr} are so-called capsules, which we will
14603 discuss later when we concentrate on expressions; they can be
14604 recognized easily because their |link| field is |void|. Arguments of type
14605 \&{suffix} and \&{text} are token lists without reference counts.
14606
14607 @ After argument scanning is complete, the arguments are moved to the
14608 |param_stack|. (They can't be put on that stack any sooner, because
14609 the stack is growing and shrinking in unpredictable ways as more arguments
14610 are being acquired.)  Then the macro body is fed to the scanner; i.e.,
14611 the replacement text of the macro is placed at the top of the \MP's
14612 input stack, so that |get_t_next| will proceed to read it next.
14613
14614 @<Declare the procedure called |macro_call|@>=
14615 @<Declare the procedure called |print_macro_name|@>;
14616 @<Declare the procedure called |print_arg|@>;
14617 @<Declare the procedure called |scan_text_arg|@>;
14618 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14619                     pointer macro_name) ;
14620
14621 @ @c
14622 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14623                     pointer macro_name) {
14624   /* invokes a user-defined control sequence */
14625   pointer r; /* current node in the macro's token list */
14626   pointer p,q; /* for list manipulation */
14627   integer n; /* the number of arguments */
14628   pointer tail = 0; /* tail of the argument list */
14629   pointer l_delim=0,r_delim=0; /* a delimiter pair */
14630   r=link(def_ref); add_mac_ref(def_ref);
14631   if ( arg_list==null ) {
14632     n=0;
14633   } else {
14634    @<Determine the number |n| of arguments already supplied,
14635     and set |tail| to the tail of |arg_list|@>;
14636   }
14637   if ( mp->internal[tracing_macros]>0 ) {
14638     @<Show the text of the macro being expanded, and the existing arguments@>;
14639   }
14640   @<Scan the remaining arguments, if any; set |r| to the first token
14641     of the replacement text@>;
14642   @<Feed the arguments and replacement text to the scanner@>;
14643 }
14644
14645 @ @<Show the text of the macro...@>=
14646 mp_begin_diagnostic(mp); mp_print_ln(mp); 
14647 mp_print_macro_name(mp, arg_list,macro_name);
14648 if ( n==3 ) mp_print(mp, "@@#"); /* indicate a suffixed macro */
14649 mp_show_macro(mp, def_ref,null,100000);
14650 if ( arg_list!=null ) {
14651   n=0; p=arg_list;
14652   do {  
14653     q=info(p);
14654     mp_print_arg(mp, q,n,0);
14655     incr(n); p=link(p);
14656   } while (p!=null);
14657 }
14658 mp_end_diagnostic(mp, false)
14659
14660
14661 @ @<Declare the procedure called |print_macro_name|@>=
14662 void mp_print_macro_name (MP mp,pointer a, pointer n);
14663
14664 @ @c
14665 void mp_print_macro_name (MP mp,pointer a, pointer n) {
14666   pointer p,q; /* they traverse the first part of |a| */
14667   if ( n!=null ) {
14668     mp_print_text(n);
14669   } else  { 
14670     p=info(a);
14671     if ( p==null ) {
14672       mp_print_text(info(info(link(a))));
14673     } else { 
14674       q=p;
14675       while ( link(q)!=null ) q=link(q);
14676       link(q)=info(link(a));
14677       mp_show_token_list(mp, p,null,1000,0);
14678       link(q)=null;
14679     }
14680   }
14681 }
14682
14683 @ @<Declare the procedure called |print_arg|@>=
14684 void mp_print_arg (MP mp,pointer q, integer n, pointer b) ;
14685
14686 @ @c
14687 void mp_print_arg (MP mp,pointer q, integer n, pointer b) {
14688   if ( link(q)==diov ) mp_print_nl(mp, "(EXPR");
14689   else if ( (b<text_base)&&(b!=text_macro) ) mp_print_nl(mp, "(SUFFIX");
14690   else mp_print_nl(mp, "(TEXT");
14691   mp_print_int(mp, n); mp_print(mp, ")<-");
14692   if ( link(q)==diov ) mp_print_exp(mp, q,1);
14693   else mp_show_token_list(mp, q,null,1000,0);
14694 }
14695
14696 @ @<Determine the number |n| of arguments already supplied...@>=
14697 {  
14698   n=1; tail=arg_list;
14699   while ( link(tail)!=null ) { 
14700     incr(n); tail=link(tail);
14701   }
14702 }
14703
14704 @ @<Scan the remaining arguments, if any; set |r|...@>=
14705 mp->cur_cmd=comma+1; /* anything |<>comma| will do */
14706 while ( info(r)>=expr_base ) { 
14707   @<Scan the delimited argument represented by |info(r)|@>;
14708   r=link(r);
14709 };
14710 if ( mp->cur_cmd==comma ) {
14711   print_err("Too many arguments to ");
14712 @.Too many arguments...@>
14713   mp_print_macro_name(mp, arg_list,macro_name); mp_print_char(mp, ';');
14714   mp_print_nl(mp, "  Missing `"); mp_print_text(r_delim);
14715 @.Missing `)'...@>
14716   mp_print(mp, "' has been inserted");
14717   help3("I'm going to assume that the comma I just read was a")
14718    ("right delimiter, and then I'll begin expanding the macro.")
14719    ("You might want to delete some tokens before continuing.");
14720   mp_error(mp);
14721 }
14722 if ( info(r)!=general_macro ) {
14723   @<Scan undelimited argument(s)@>;
14724 }
14725 r=link(r)
14726
14727 @ At this point, the reader will find it advisable to review the explanation
14728 of token list format that was presented earlier, paying special attention to
14729 the conventions that apply only at the beginning of a macro's token list.
14730
14731 On the other hand, the reader will have to take the expression-parsing
14732 aspects of the following program on faith; we will explain |cur_type|
14733 and |cur_exp| later. (Several things in this program depend on each other,
14734 and it's necessary to jump into the circle somewhere.)
14735
14736 @<Scan the delimited argument represented by |info(r)|@>=
14737 if ( mp->cur_cmd!=comma ) {
14738   mp_get_x_next(mp);
14739   if ( mp->cur_cmd!=left_delimiter ) {
14740     print_err("Missing argument to ");
14741 @.Missing argument...@>
14742     mp_print_macro_name(mp, arg_list,macro_name);
14743     help3("That macro has more parameters than you thought.")
14744      ("I'll continue by pretending that each missing argument")
14745      ("is either zero or null.");
14746     if ( info(r)>=suffix_base ) {
14747       mp->cur_exp=null; mp->cur_type=mp_token_list;
14748     } else { 
14749       mp->cur_exp=0; mp->cur_type=mp_known;
14750     }
14751     mp_back_error(mp); mp->cur_cmd=right_delimiter; 
14752     goto FOUND;
14753   }
14754   l_delim=mp->cur_sym; r_delim=mp->cur_mod;
14755 }
14756 @<Scan the argument represented by |info(r)|@>;
14757 if ( mp->cur_cmd!=comma ) 
14758   @<Check that the proper right delimiter was present@>;
14759 FOUND:  
14760 @<Append the current expression to |arg_list|@>
14761
14762 @ @<Check that the proper right delim...@>=
14763 if ( (mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
14764   if ( info(link(r))>=expr_base ) {
14765     mp_missing_err(mp, ",");
14766 @.Missing `,'@>
14767     help3("I've finished reading a macro argument and am about to")
14768       ("read another; the arguments weren't delimited correctly.")
14769        ("You might want to delete some tokens before continuing.");
14770     mp_back_error(mp); mp->cur_cmd=comma;
14771   } else { 
14772     mp_missing_err(mp, str(text(r_delim)));
14773 @.Missing `)'@>
14774     help2("I've gotten to the end of the macro parameter list.")
14775        ("You might want to delete some tokens before continuing.");
14776     mp_back_error(mp);
14777   }
14778 }
14779
14780 @ A \&{suffix} or \&{text} parameter will be have been scanned as
14781 a token list pointed to by |cur_exp|, in which case we will have
14782 |cur_type=token_list|.
14783
14784 @<Append the current expression to |arg_list|@>=
14785
14786   p=mp_get_avail(mp);
14787   if ( mp->cur_type==mp_token_list ) info(p)=mp->cur_exp;
14788   else info(p)=mp_stash_cur_exp(mp);
14789   if ( mp->internal[tracing_macros]>0 ) {
14790     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,info(r)); 
14791     mp_end_diagnostic(mp, false);
14792   }
14793   if ( arg_list==null ) arg_list=p;
14794   else link(tail)=p;
14795   tail=p; incr(n);
14796 }
14797
14798 @ @<Scan the argument represented by |info(r)|@>=
14799 if ( info(r)>=text_base ) {
14800   mp_scan_text_arg(mp, l_delim,r_delim);
14801 } else { 
14802   mp_get_x_next(mp);
14803   if ( info(r)>=suffix_base ) mp_scan_suffix(mp);
14804   else mp_scan_expression(mp);
14805 }
14806
14807 @ The parameters to |scan_text_arg| are either a pair of delimiters
14808 or zero; the latter case is for undelimited text arguments, which
14809 end with the first semicolon or \&{endgroup} or \&{end} that is not
14810 contained in a group.
14811
14812 @<Declare the procedure called |scan_text_arg|@>=
14813 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) ;
14814
14815 @ @c
14816 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) {
14817   integer balance; /* excess of |l_delim| over |r_delim| */
14818   pointer p; /* list tail */
14819   mp->warning_info=l_delim; mp->scanner_status=absorbing;
14820   p=hold_head; balance=1; link(hold_head)=null;
14821   while (1)  { 
14822     get_t_next;
14823     if ( l_delim==0 ) {
14824       @<Adjust the balance for an undelimited argument; |break| if done@>;
14825     } else {
14826           @<Adjust the balance for a delimited argument; |break| if done@>;
14827     }
14828     link(p)=mp_cur_tok(mp); p=link(p);
14829   }
14830   mp->cur_exp=link(hold_head); mp->cur_type=mp_token_list;
14831   mp->scanner_status=normal;
14832 };
14833
14834 @ @<Adjust the balance for a delimited argument...@>=
14835 if ( mp->cur_cmd==right_delimiter ) { 
14836   if ( mp->cur_mod==l_delim ) { 
14837     decr(balance);
14838     if ( balance==0 ) break;
14839   }
14840 } else if ( mp->cur_cmd==left_delimiter ) {
14841   if ( mp->cur_mod==r_delim ) incr(balance);
14842 }
14843
14844 @ @<Adjust the balance for an undelimited...@>=
14845 if ( end_of_statement ) { /* |cur_cmd=semicolon|, |end_group|, or |stop| */
14846   if ( balance==1 ) { break; }
14847   else  { if ( mp->cur_cmd==end_group ) decr(balance); }
14848 } else if ( mp->cur_cmd==begin_group ) { 
14849   incr(balance); 
14850 }
14851
14852 @ @<Scan undelimited argument(s)@>=
14853
14854   if ( info(r)<text_macro ) {
14855     mp_get_x_next(mp);
14856     if ( info(r)!=suffix_macro ) {
14857       if ( (mp->cur_cmd==equals)||(mp->cur_cmd==assignment) ) mp_get_x_next(mp);
14858     }
14859   }
14860   switch (info(r)) {
14861   case primary_macro:mp_scan_primary(mp); break;
14862   case secondary_macro:mp_scan_secondary(mp); break;
14863   case tertiary_macro:mp_scan_tertiary(mp); break;
14864   case expr_macro:mp_scan_expression(mp); break;
14865   case of_macro:
14866     @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>;
14867     break;
14868   case suffix_macro:
14869     @<Scan a suffix with optional delimiters@>;
14870     break;
14871   case text_macro:mp_scan_text_arg(mp, 0,0); break;
14872   } /* there are no other cases */
14873   mp_back_input(mp); 
14874   @<Append the current expression to |arg_list|@>;
14875 }
14876
14877 @ @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>=
14878
14879   mp_scan_expression(mp); p=mp_get_avail(mp); info(p)=mp_stash_cur_exp(mp);
14880   if ( mp->internal[tracing_macros]>0 ) { 
14881     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,0); 
14882     mp_end_diagnostic(mp, false);
14883   }
14884   if ( arg_list==null ) arg_list=p; else link(tail)=p;
14885   tail=p;incr(n);
14886   if ( mp->cur_cmd!=of_token ) {
14887     mp_missing_err(mp, "of"); mp_print(mp, " for ");
14888 @.Missing `of'@>
14889     mp_print_macro_name(mp, arg_list,macro_name);
14890     help1("I've got the first argument; will look now for the other.");
14891     mp_back_error(mp);
14892   }
14893   mp_get_x_next(mp); mp_scan_primary(mp);
14894 }
14895
14896 @ @<Scan a suffix with optional delimiters@>=
14897
14898   if ( mp->cur_cmd!=left_delimiter ) {
14899     l_delim=null;
14900   } else { 
14901     l_delim=mp->cur_sym; r_delim=mp->cur_mod; mp_get_x_next(mp);
14902   };
14903   mp_scan_suffix(mp);
14904   if ( l_delim!=null ) {
14905     if ((mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
14906       mp_missing_err(mp, str(text(r_delim)));
14907 @.Missing `)'@>
14908       help2("I've gotten to the end of the macro parameter list.")
14909          ("You might want to delete some tokens before continuing.");
14910       mp_back_error(mp);
14911     }
14912     mp_get_x_next(mp);
14913   }
14914 }
14915
14916 @ Before we put a new token list on the input stack, it is wise to clean off
14917 all token lists that have recently been depleted. Then a user macro that ends
14918 with a call to itself will not require unbounded stack space.
14919
14920 @<Feed the arguments and replacement text to the scanner@>=
14921 while ( token_state &&(loc==null) ) mp_end_token_list(mp); /* conserve stack space */
14922 if ( mp->param_ptr+n>mp->max_param_stack ) {
14923   mp->max_param_stack=mp->param_ptr+n;
14924   if ( mp->max_param_stack>mp->param_size )
14925     mp_overflow(mp, "parameter stack size",mp->param_size);
14926 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
14927 }
14928 mp_begin_token_list(mp, def_ref,macro); name=macro_name; loc=r;
14929 if ( n>0 ) {
14930   p=arg_list;
14931   do {  
14932    mp->param_stack[mp->param_ptr]=info(p); incr(mp->param_ptr); p=link(p);
14933   } while (p!=null);
14934   mp_flush_list(mp, arg_list);
14935 }
14936
14937 @ It's sometimes necessary to put a single argument onto |param_stack|.
14938 The |stack_argument| subroutine does this.
14939
14940 @c void mp_stack_argument (MP mp,pointer p) { 
14941   if ( mp->param_ptr==mp->max_param_stack ) {
14942     incr(mp->max_param_stack);
14943     if ( mp->max_param_stack>mp->param_size )
14944       mp_overflow(mp, "parameter stack size",mp->param_size);
14945 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
14946   }
14947   mp->param_stack[mp->param_ptr]=p; incr(mp->param_ptr);
14948 }
14949
14950 @* \[33] Conditional processing.
14951 Let's consider now the way \&{if} commands are handled.
14952
14953 Conditions can be inside conditions, and this nesting has a stack
14954 that is independent of other stacks.
14955 Four global variables represent the top of the condition stack:
14956 |cond_ptr| points to pushed-down entries, if~any; |cur_if| tells whether
14957 we are processing \&{if} or \&{elseif}; |if_limit| specifies
14958 the largest code of a |fi_or_else| command that is syntactically legal;
14959 and |if_line| is the line number at which the current conditional began.
14960
14961 If no conditions are currently in progress, the condition stack has the
14962 special state |cond_ptr=null|, |if_limit=normal|, |cur_if=0|, |if_line=0|.
14963 Otherwise |cond_ptr| points to a two-word node; the |type|, |name_type|, and
14964 |link| fields of the first word contain |if_limit|, |cur_if|, and
14965 |cond_ptr| at the next level, and the second word contains the
14966 corresponding |if_line|.
14967
14968 @d if_node_size 2 /* number of words in stack entry for conditionals */
14969 @d if_line_field(A) mp->mem[(A)+1].cint
14970 @d if_code 1 /* code for \&{if} being evaluated */
14971 @d fi_code 2 /* code for \&{fi} */
14972 @d else_code 3 /* code for \&{else} */
14973 @d else_if_code 4 /* code for \&{elseif} */
14974
14975 @<Glob...@>=
14976 pointer cond_ptr; /* top of the condition stack */
14977 integer if_limit; /* upper bound on |fi_or_else| codes */
14978 small_number cur_if; /* type of conditional being worked on */
14979 integer if_line; /* line where that conditional began */
14980
14981 @ @<Set init...@>=
14982 mp->cond_ptr=null; mp->if_limit=normal; mp->cur_if=0; mp->if_line=0;
14983
14984 @ @<Put each...@>=
14985 mp_primitive(mp, "if",if_test,if_code);
14986 @:if_}{\&{if} primitive@>
14987 mp_primitive(mp, "fi",fi_or_else,fi_code); mp->eqtb[frozen_fi]=mp->eqtb[mp->cur_sym];
14988 @:fi_}{\&{fi} primitive@>
14989 mp_primitive(mp, "else",fi_or_else,else_code);
14990 @:else_}{\&{else} primitive@>
14991 mp_primitive(mp, "elseif",fi_or_else,else_if_code);
14992 @:else_if_}{\&{elseif} primitive@>
14993
14994 @ @<Cases of |print_cmd_mod|...@>=
14995 case if_test:
14996 case fi_or_else: 
14997   switch (m) {
14998   case if_code:mp_print(mp, "if"); break;
14999   case fi_code:mp_print(mp, "fi");  break;
15000   case else_code:mp_print(mp, "else"); break;
15001   default: mp_print(mp, "elseif"); break;
15002   }
15003   break;
15004
15005 @ Here is a procedure that ignores text until coming to an \&{elseif},
15006 \&{else}, or \&{fi} at level zero of $\&{if}\ldots\&{fi}$
15007 nesting. After it has acted, |cur_mod| will indicate the token that
15008 was found.
15009
15010 \MP's smallest two command codes are |if_test| and |fi_or_else|; this
15011 makes the skipping process a bit simpler.
15012
15013 @c 
15014 void mp_pass_text (MP mp) {
15015   integer l = 0;
15016   mp->scanner_status=skipping;
15017   mp->warning_info=mp_true_line(mp);
15018   while (1)  { 
15019     get_t_next;
15020     if ( mp->cur_cmd<=fi_or_else ) {
15021       if ( mp->cur_cmd<fi_or_else ) {
15022         incr(l);
15023       } else { 
15024         if ( l==0 ) break;
15025         if ( mp->cur_mod==fi_code ) decr(l);
15026       }
15027     } else {
15028       @<Decrease the string reference count,
15029        if the current token is a string@>;
15030     }
15031   }
15032   mp->scanner_status=normal;
15033 }
15034
15035 @ @<Decrease the string reference count...@>=
15036 if ( mp->cur_cmd==string_token ) { delete_str_ref(mp->cur_mod); }
15037
15038 @ When we begin to process a new \&{if}, we set |if_limit:=if_code|; then
15039 if \&{elseif} or \&{else} or \&{fi} occurs before the current \&{if}
15040 condition has been evaluated, a colon will be inserted.
15041 A construction like `\.{if fi}' would otherwise get \MP\ confused.
15042
15043 @<Push the condition stack@>=
15044 { p=mp_get_node(mp, if_node_size); link(p)=mp->cond_ptr; type(p)=mp->if_limit;
15045   name_type(p)=mp->cur_if; if_line_field(p)=mp->if_line;
15046   mp->cond_ptr=p; mp->if_limit=if_code; mp->if_line=mp_true_line(mp); 
15047   mp->cur_if=if_code;
15048 }
15049
15050 @ @<Pop the condition stack@>=
15051 { p=mp->cond_ptr; mp->if_line=if_line_field(p);
15052   mp->cur_if=name_type(p); mp->if_limit=type(p); mp->cond_ptr=link(p);
15053   mp_free_node(mp, p,if_node_size);
15054 }
15055
15056 @ Here's a procedure that changes the |if_limit| code corresponding to
15057 a given value of |cond_ptr|.
15058
15059 @c void mp_change_if_limit (MP mp,small_number l, pointer p) {
15060   pointer q;
15061   if ( p==mp->cond_ptr ) {
15062     mp->if_limit=l; /* that's the easy case */
15063   } else  { 
15064     q=mp->cond_ptr;
15065     while (1) { 
15066       if ( q==null ) mp_confusion(mp, "if");
15067 @:this can't happen if}{\quad if@>
15068       if ( link(q)==p ) { 
15069         type(q)=l; return;
15070       }
15071       q=link(q);
15072     }
15073   }
15074 }
15075
15076 @ The user is supposed to put colons into the proper parts of conditional
15077 statements. Therefore, \MP\ has to check for their presence.
15078
15079 @c 
15080 void mp_check_colon (MP mp) { 
15081   if ( mp->cur_cmd!=colon ) { 
15082     mp_missing_err(mp, ":");
15083 @.Missing `:'@>
15084     help2("There should've been a colon after the condition.")
15085          ("I shall pretend that one was there.");;
15086     mp_back_error(mp);
15087   }
15088 }
15089
15090 @ A condition is started when the |get_x_next| procedure encounters
15091 an |if_test| command; in that case |get_x_next| calls |conditional|,
15092 which is a recursive procedure.
15093 @^recursion@>
15094
15095 @c void mp_conditional (MP mp) {
15096   pointer save_cond_ptr; /* |cond_ptr| corresponding to this conditional */
15097   int new_if_limit; /* future value of |if_limit| */
15098   pointer p; /* temporary register */
15099   @<Push the condition stack@>; 
15100   save_cond_ptr=mp->cond_ptr;
15101 RESWITCH: 
15102   mp_get_boolean(mp); new_if_limit=else_if_code;
15103   if ( mp->internal[tracing_commands]>unity ) {
15104     @<Display the boolean value of |cur_exp|@>;
15105   }
15106 FOUND: 
15107   mp_check_colon(mp);
15108   if ( mp->cur_exp==true_code ) {
15109     mp_change_if_limit(mp, new_if_limit,save_cond_ptr);
15110     return; /* wait for \&{elseif}, \&{else}, or \&{fi} */
15111   };
15112   @<Skip to \&{elseif} or \&{else} or \&{fi}, then |goto done|@>;
15113 DONE: 
15114   mp->cur_if=mp->cur_mod; mp->if_line=mp_true_line(mp);
15115   if ( mp->cur_mod==fi_code ) {
15116     @<Pop the condition stack@>
15117   } else if ( mp->cur_mod==else_if_code ) {
15118     goto RESWITCH;
15119   } else  { 
15120     mp->cur_exp=true_code; new_if_limit=fi_code; mp_get_x_next(mp); 
15121     goto FOUND;
15122   }
15123 }
15124
15125 @ In a construction like `\&{if} \&{if} \&{true}: $0=1$: \\{foo}
15126 \&{else}: \\{bar} \&{fi}', the first \&{else}
15127 that we come to after learning that the \&{if} is false is not the
15128 \&{else} we're looking for. Hence the following curious logic is needed.
15129
15130 @<Skip to \&{elseif}...@>=
15131 while (1) { 
15132   mp_pass_text(mp);
15133   if ( mp->cond_ptr==save_cond_ptr ) goto DONE;
15134   else if ( mp->cur_mod==fi_code ) @<Pop the condition stack@>;
15135 }
15136
15137
15138 @ @<Display the boolean value...@>=
15139 { mp_begin_diagnostic(mp);
15140   if ( mp->cur_exp==true_code ) mp_print(mp, "{true}");
15141   else mp_print(mp, "{false}");
15142   mp_end_diagnostic(mp, false);
15143 }
15144
15145 @ The processing of conditionals is complete except for the following
15146 code, which is actually part of |get_x_next|. It comes into play when
15147 \&{elseif}, \&{else}, or \&{fi} is scanned.
15148
15149 @<Terminate the current conditional and skip to \&{fi}@>=
15150 if ( mp->cur_mod>mp->if_limit ) {
15151   if ( mp->if_limit==if_code ) { /* condition not yet evaluated */
15152     mp_missing_err(mp, ":");
15153 @.Missing `:'@>
15154     mp_back_input(mp); mp->cur_sym=frozen_colon; mp_ins_error(mp);
15155   } else  { 
15156     print_err("Extra "); mp_print_cmd_mod(mp, fi_or_else,mp->cur_mod);
15157 @.Extra else@>
15158 @.Extra elseif@>
15159 @.Extra fi@>
15160     help1("I'm ignoring this; it doesn't match any if.");
15161     mp_error(mp);
15162   }
15163 } else  { 
15164   while ( mp->cur_mod!=fi_code ) mp_pass_text(mp); /* skip to \&{fi} */
15165   @<Pop the condition stack@>;
15166 }
15167
15168 @* \[34] Iterations.
15169 To bring our treatment of |get_x_next| to a close, we need to consider what
15170 \MP\ does when it sees \&{for}, \&{forsuffixes}, and \&{forever}.
15171
15172 There's a global variable |loop_ptr| that keeps track of the \&{for} loops
15173 that are currently active. If |loop_ptr=null|, no loops are in progress;
15174 otherwise |info(loop_ptr)| points to the iterative text of the current
15175 (innermost) loop, and |link(loop_ptr)| points to the data for any other
15176 loops that enclose the current one.
15177
15178 A loop-control node also has two other fields, called |loop_type| and
15179 |loop_list|, whose contents depend on the type of loop:
15180
15181 \yskip\indent|loop_type(loop_ptr)=null| means that |loop_list(loop_ptr)|
15182 points to a list of one-word nodes whose |info| fields point to the
15183 remaining argument values of a suffix list and expression list.
15184
15185 \yskip\indent|loop_type(loop_ptr)=diov| means that the current loop is
15186 `\&{forever}'.
15187
15188 \yskip\indent|loop_type(loop_ptr)=progression_flag| means that
15189 |p=loop_list(loop_ptr)| points to a ``progression node'' and |value(p)|,
15190 |step_size(p)|, and |final_value(p)| contain the data for an arithmetic
15191 progression.
15192
15193 \yskip\indent|loop_type(loop_ptr)=p>diov| means that |p| points to an edge
15194 header and |loop_list(loop_ptr)| points into the graphical object list for
15195 that edge header.
15196
15197 \yskip\noindent In the case of a progression node, the first word is not used
15198 because the link field of words in the dynamic memory area cannot be arbitrary.
15199
15200 @d loop_list_loc(A) ((A)+1) /* where the |loop_list| field resides */
15201 @d loop_type(A) info(loop_list_loc((A))) /* the type of \&{for} loop */
15202 @d loop_list(A) link(loop_list_loc((A))) /* the remaining list elements */
15203 @d loop_node_size 2 /* the number of words in a loop control node */
15204 @d progression_node_size 4 /* the number of words in a progression node */
15205 @d step_size(A) mp->mem[(A)+2].sc /* the step size in an arithmetic progression */
15206 @d final_value(A) mp->mem[(A)+3].sc /* the final value in an arithmetic progression */
15207 @d progression_flag (null+2)
15208   /* |loop_type| value when |loop_list| points to a progression node */
15209
15210 @<Glob...@>=
15211 pointer loop_ptr; /* top of the loop-control-node stack */
15212
15213 @ @<Set init...@>=
15214 mp->loop_ptr=null;
15215
15216 @ If the expressions that define an arithmetic progression in
15217 a \&{for} loop don't have known numeric values, the |bad_for|
15218 subroutine screams at the user.
15219
15220 @c void mp_bad_for (MP mp, char * s) {
15221   mp_disp_err(mp, null,"Improper "); /* show the bad expression above the message */
15222 @.Improper...replaced by 0@>
15223   mp_print(mp, s); mp_print(mp, " has been replaced by 0");
15224   help4("When you say `for x=a step b until c',")
15225     ("the initial value `a' and the step size `b'")
15226     ("and the final value `c' must have known numeric values.")
15227     ("I'm zeroing this one. Proceed, with fingers crossed.");
15228   mp_put_get_flush_error(mp, 0);
15229 };
15230
15231 @ Here's what \MP\ does when \&{for}, \&{forsuffixes}, or \&{forever}
15232 has just been scanned. (This code requires slight familiarity with
15233 expression-parsing routines that we have not yet discussed; but it seems
15234 to belong in the present part of the program, even though the original author
15235 didn't write it until later. The reader may wish to come back to it.)
15236
15237 @c void mp_begin_iteration (MP mp) {
15238   halfword m; /* |expr_base| (\&{for}) or |suffix_base| (\&{forsuffixes}) */
15239   halfword n; /* hash address of the current symbol */
15240   pointer s; /* the new loop-control node */
15241   pointer p; /* substitution list for |scan_toks| */
15242   pointer q;  /* link manipulation register */
15243   pointer pp; /* a new progression node */
15244   m=mp->cur_mod; n=mp->cur_sym; s=mp_get_node(mp, loop_node_size);
15245   if ( m==start_forever ){ 
15246     loop_type(s)=diov; p=null; mp_get_x_next(mp);
15247   } else { 
15248     mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
15249     info(p)=mp->cur_sym; value(p)=m;
15250     mp_get_x_next(mp);
15251     if ( mp->cur_cmd==within_token ) {
15252       @<Set up a picture iteration@>;
15253     } else { 
15254       @<Check for the |"="| or |":="| in a loop header@>;
15255       @<Scan the values to be used in the loop@>;
15256     }
15257   }
15258   @<Check for the presence of a colon@>;
15259   @<Scan the loop text and put it on the loop control stack@>;
15260   mp_resume_iteration(mp);
15261 }
15262
15263 @ @<Check for the |"="| or |":="| in a loop header@>=
15264 if ( (mp->cur_cmd!=equals)&&(mp->cur_cmd!=assignment) ) { 
15265   mp_missing_err(mp, "=");
15266 @.Missing `='@>
15267   help3("The next thing in this loop should have been `=' or `:='.")
15268     ("But don't worry; I'll pretend that an equals sign")
15269     ("was present, and I'll look for the values next.");
15270   mp_back_error(mp);
15271 }
15272
15273 @ @<Check for the presence of a colon@>=
15274 if ( mp->cur_cmd!=colon ) { 
15275   mp_missing_err(mp, ":");
15276 @.Missing `:'@>
15277   help3("The next thing in this loop should have been a `:'.")
15278     ("So I'll pretend that a colon was present;")
15279     ("everything from here to `endfor' will be iterated.");
15280   mp_back_error(mp);
15281 }
15282
15283 @ We append a special |frozen_repeat_loop| token in place of the
15284 `\&{endfor}' at the end of the loop. This will come through \MP's scanner
15285 at the proper time to cause the loop to be repeated.
15286
15287 (If the user tries some shenanigan like `\&{for} $\ldots$ \&{let} \&{endfor}',
15288 he will be foiled by the |get_symbol| routine, which keeps frozen
15289 tokens unchanged. Furthermore the |frozen_repeat_loop| is an \&{outer}
15290 token, so it won't be lost accidentally.)
15291
15292 @ @<Scan the loop text...@>=
15293 q=mp_get_avail(mp); info(q)=frozen_repeat_loop;
15294 mp->scanner_status=loop_defining; mp->warning_info=n;
15295 info(s)=mp_scan_toks(mp, iteration,p,q,0); mp->scanner_status=normal;
15296 link(s)=mp->loop_ptr; mp->loop_ptr=s
15297
15298 @ @<Initialize table...@>=
15299 eq_type(frozen_repeat_loop)=repeat_loop+outer_tag;
15300 text(frozen_repeat_loop)=intern(" ENDFOR");
15301
15302 @ The loop text is inserted into \MP's scanning apparatus by the
15303 |resume_iteration| routine.
15304
15305 @c void mp_resume_iteration (MP mp) {
15306   pointer p,q; /* link registers */
15307   p=loop_type(mp->loop_ptr);
15308   if ( p==progression_flag ) { 
15309     p=loop_list(mp->loop_ptr); /* now |p| points to a progression node */
15310     mp->cur_exp=value(p);
15311     if ( @<The arithmetic progression has ended@> ) {
15312       mp_stop_iteration(mp);
15313       return;
15314     }
15315     mp->cur_type=mp_known; q=mp_stash_cur_exp(mp); /* make |q| an \&{expr} argument */
15316     value(p)=mp->cur_exp+step_size(p); /* set |value(p)| for the next iteration */
15317   } else if ( p==null ) { 
15318     p=loop_list(mp->loop_ptr);
15319     if ( p==null ) {
15320       mp_stop_iteration(mp);
15321       return;
15322     }
15323     loop_list(mp->loop_ptr)=link(p); q=info(p); free_avail(p);
15324   } else if ( p==diov ) { 
15325     mp_begin_token_list(mp, info(mp->loop_ptr),forever_text); return;
15326   } else {
15327     @<Make |q| a capsule containing the next picture component from
15328       |loop_list(loop_ptr)| or |goto not_found|@>;
15329   }
15330   mp_begin_token_list(mp, info(mp->loop_ptr),loop_text);
15331   mp_stack_argument(mp, q);
15332   if ( mp->internal[tracing_commands]>unity ) {
15333      @<Trace the start of a loop@>;
15334   }
15335   return;
15336 NOT_FOUND:
15337   mp_stop_iteration(mp);
15338 }
15339
15340 @ @<The arithmetic progression has ended@>=
15341 ((step_size(p)>0)&&(mp->cur_exp>final_value(p)))||
15342  ((step_size(p)<0)&&(mp->cur_exp<final_value(p)))
15343
15344 @ @<Trace the start of a loop@>=
15345
15346   mp_begin_diagnostic(mp); mp_print_nl(mp, "{loop value=");
15347 @.loop value=n@>
15348   if ( (q!=null)&&(link(q)==diov) ) mp_print_exp(mp, q,1);
15349   else mp_show_token_list(mp, q,null,50,0);
15350   mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
15351 }
15352
15353 @ @<Make |q| a capsule containing the next picture component from...@>=
15354 { q=loop_list(mp->loop_ptr);
15355   if ( q==null ) goto NOT_FOUND;
15356   skip_component(q) goto NOT_FOUND;
15357   mp->cur_exp=mp_copy_objects(mp, loop_list(mp->loop_ptr),q);
15358   mp_init_bbox(mp, mp->cur_exp);
15359   mp->cur_type=mp_picture_type;
15360   loop_list(mp->loop_ptr)=q;
15361   q=mp_stash_cur_exp(mp);
15362 }
15363
15364 @ A level of loop control disappears when |resume_iteration| has decided
15365 not to resume, or when an \&{exitif} construction has removed the loop text
15366 from the input stack.
15367
15368 @c void mp_stop_iteration (MP mp) {
15369   pointer p,q; /* the usual */
15370   p=loop_type(mp->loop_ptr);
15371   if ( p==progression_flag )  {
15372     mp_free_node(mp, loop_list(mp->loop_ptr),progression_node_size);
15373   } else if ( p==null ){ 
15374     q=loop_list(mp->loop_ptr);
15375     while ( q!=null ) {
15376       p=info(q);
15377       if ( p!=null ) {
15378         if ( link(p)==diov ) { /* it's an \&{expr} parameter */
15379           mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
15380         } else {
15381           mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
15382         }
15383       }
15384       p=q; q=link(q); free_avail(p);
15385     }
15386   } else if ( p>progression_flag ) {
15387     delete_edge_ref(p);
15388   }
15389   p=mp->loop_ptr; mp->loop_ptr=link(p); mp_flush_token_list(mp, info(p));
15390   mp_free_node(mp, p,loop_node_size);
15391 }
15392
15393 @ Now that we know all about loop control, we can finish up
15394 the missing portion of |begin_iteration| and we'll be done.
15395
15396 The following code is performed after the `\.=' has been scanned in
15397 a \&{for} construction (if |m=expr_base|) or a \&{forsuffixes} construction
15398 (if |m=suffix_base|).
15399
15400 @<Scan the values to be used in the loop@>=
15401 loop_type(s)=null; q=loop_list_loc(s); link(q)=null; /* |link(q)=loop_list(s)| */
15402 do {  
15403   mp_get_x_next(mp);
15404   if ( m!=expr_base ) {
15405     mp_scan_suffix(mp);
15406   } else { 
15407     if ( mp->cur_cmd>=colon ) if ( mp->cur_cmd<=comma ) 
15408           goto CONTINUE;
15409     mp_scan_expression(mp);
15410     if ( mp->cur_cmd==step_token ) if ( q==loop_list_loc(s) ) {
15411       @<Prepare for step-until construction and |break|@>;
15412     }
15413     mp->cur_exp=mp_stash_cur_exp(mp);
15414   }
15415   link(q)=mp_get_avail(mp); q=link(q); 
15416   info(q)=mp->cur_exp; mp->cur_type=mp_vacuous;
15417 CONTINUE:
15418   ;
15419 } while (mp->cur_cmd==comma)
15420
15421 @ @<Prepare for step-until construction and |break|@>=
15422
15423   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "initial value");
15424   pp=mp_get_node(mp, progression_node_size); value(pp)=mp->cur_exp;
15425   mp_get_x_next(mp); mp_scan_expression(mp);
15426   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "step size");
15427   step_size(pp)=mp->cur_exp;
15428   if ( mp->cur_cmd!=until_token ) { 
15429     mp_missing_err(mp, "until");
15430 @.Missing `until'@>
15431     help2("I assume you meant to say `until' after `step'.")
15432       ("So I'll look for the final value and colon next.");
15433     mp_back_error(mp);
15434   }
15435   mp_get_x_next(mp); mp_scan_expression(mp);
15436   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "final value");
15437   final_value(pp)=mp->cur_exp; loop_list(s)=pp;
15438   loop_type(s)=progression_flag; 
15439   break;
15440 }
15441
15442 @ The last case is when we have just seen ``\&{within}'', and we need to
15443 parse a picture expression and prepare to iterate over it.
15444
15445 @<Set up a picture iteration@>=
15446 { mp_get_x_next(mp);
15447   mp_scan_expression(mp);
15448   @<Make sure the current expression is a known picture@>;
15449   loop_type(s)=mp->cur_exp; mp->cur_type=mp_vacuous;
15450   q=link(dummy_loc(mp->cur_exp));
15451   if ( q!= null ) 
15452     if ( is_start_or_stop(q) )
15453       if ( mp_skip_1component(mp, q)==null ) q=link(q);
15454   loop_list(s)=q;
15455 }
15456
15457 @ @<Make sure the current expression is a known picture@>=
15458 if ( mp->cur_type!=mp_picture_type ) {
15459   mp_disp_err(mp, null,"Improper iteration spec has been replaced by nullpicture");
15460   help1("When you say `for x in p', p must be a known picture.");
15461   mp_put_get_flush_error(mp, mp_get_node(mp, edge_header_size));
15462   mp_init_edges(mp, mp->cur_exp); mp->cur_type=mp_picture_type;
15463 }
15464
15465 @* \[35] File names.
15466 It's time now to fret about file names.  Besides the fact that different
15467 operating systems treat files in different ways, we must cope with the
15468 fact that completely different naming conventions are used by different
15469 groups of people. The following programs show what is required for one
15470 particular operating system; similar routines for other systems are not
15471 difficult to devise.
15472 @^system dependencies@>
15473
15474 \MP\ assumes that a file name has three parts: the name proper; its
15475 ``extension''; and a ``file area'' where it is found in an external file
15476 system.  The extension of an input file is assumed to be
15477 `\.{.mp}' unless otherwise specified; it is `\.{.log}' on the
15478 transcript file that records each run of \MP; it is `\.{.tfm}' on the font
15479 metric files that describe characters in any fonts created by \MP; it is
15480 `\.{.ps}' or `.{\it nnn}' for some number {\it nnn} on the \ps\ output files;
15481 and it is `\.{.mem}' on the mem files written by \.{INIMP} to initialize \MP.
15482 The file area can be arbitrary on input files, but files are usually
15483 output to the user's current area.  If an input file cannot be
15484 found on the specified area, \MP\ will look for it on a special system
15485 area; this special area is intended for commonly used input files.
15486
15487 Simple uses of \MP\ refer only to file names that have no explicit
15488 extension or area. For example, a person usually says `\.{input} \.{cmr10}'
15489 instead of `\.{input} \.{cmr10.new}'. Simple file
15490 names are best, because they make the \MP\ source files portable;
15491 whenever a file name consists entirely of letters and digits, it should be
15492 treated in the same way by all implementations of \MP. However, users
15493 need the ability to refer to other files in their environment, especially
15494 when responding to error messages concerning unopenable files; therefore
15495 we want to let them use the syntax that appears in their favorite
15496 operating system.
15497
15498 @ \MP\ uses the same conventions that have proved to be satisfactory for
15499 \TeX\ and \MF. In order to isolate the system-dependent aspects of file names,
15500 @^system dependencies@>
15501 the system-independent parts of \MP\ are expressed in terms
15502 of three system-dependent
15503 procedures called |begin_name|, |more_name|, and |end_name|. In
15504 essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
15505 the system-independent driver program does the operations
15506 $$|begin_name|;\,|more_name|(c_1);\,\ldots\,;|more_name|(c_n);
15507 \,|end_name|.$$
15508 These three procedures communicate with each other via global variables.
15509 Afterwards the file name will appear in the string pool as three strings
15510 called |cur_name|\penalty10000\hskip-.05em,
15511 |cur_area|, and |cur_ext|; the latter two are null (i.e.,
15512 |""|), unless they were explicitly specified by the user.
15513
15514 Actually the situation is slightly more complicated, because \MP\ needs
15515 to know when the file name ends. The |more_name| routine is a function
15516 (with side effects) that returns |true| on the calls |more_name|$(c_1)$,
15517 \dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
15518 returns |false|; or, it returns |true| and $c_n$ is the last character
15519 on the current input line. In other words,
15520 |more_name| is supposed to return |true| unless it is sure that the
15521 file name has been completely scanned; and |end_name| is supposed to be able
15522 to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
15523 whether $|more_name|(c_n)$ returned |true| or |false|.
15524
15525 @<Glob...@>=
15526 char * cur_name; /* name of file just scanned */
15527 char * cur_area; /* file area just scanned, or \.{""} */
15528 char * cur_ext; /* file extension just scanned, or \.{""} */
15529
15530 @ It is easier to maintain reference counts if we assign initial values.
15531
15532 @<Set init...@>=
15533 mp->cur_name=xstrdup(""); 
15534 mp->cur_area=xstrdup(""); 
15535 mp->cur_ext=xstrdup("");
15536
15537 @ @<Dealloc variables@>=
15538 xfree(mp->cur_area);
15539 xfree(mp->cur_name);
15540 xfree(mp->cur_ext);
15541
15542 @ The file names we shall deal with for illustrative purposes have the
15543 following structure:  If the name contains `\.>' or `\.:', the file area
15544 consists of all characters up to and including the final such character;
15545 otherwise the file area is null.  If the remaining file name contains
15546 `\..', the file extension consists of all such characters from the first
15547 remaining `\..' to the end, otherwise the file extension is null.
15548 @^system dependencies@>
15549
15550 We can scan such file names easily by using two global variables that keep track
15551 of the occurrences of area and extension delimiters.  Note that these variables
15552 cannot be of type |pool_pointer| because a string pool compaction could occur
15553 while scanning a file name.
15554
15555 @<Glob...@>=
15556 integer area_delimiter;
15557   /* most recent `\.>' or `\.:' relative to |str_start[str_ptr]| */
15558 integer ext_delimiter; /* the relevant `\..', if any */
15559
15560 @ Input files that can't be found in the user's area may appear in standard
15561 system areas called |MP_area| and |MF_area|.  (The latter is used when the file
15562 extension is |".mf"|.)  The standard system area for font metric files
15563 to be read is |MP_font_area|.
15564 This system area name will, of course, vary from place to place.
15565 @^system dependencies@>
15566
15567 @d MP_area "MPinputs:"
15568 @.MPinputs@>
15569 @d MF_area "MFinputs:"
15570 @.MFinputs@>
15571 @d MP_font_area ""
15572 @.TeXfonts@>
15573
15574 @ Here now is the first of the system-dependent routines for file name scanning.
15575 @^system dependencies@>
15576
15577 @<Declare subroutines for parsing file names@>=
15578 void mp_begin_name (MP mp) { 
15579   xfree(mp->cur_name); 
15580   xfree(mp->cur_area); 
15581   xfree(mp->cur_ext);
15582   mp->area_delimiter=-1; 
15583   mp->ext_delimiter=-1;
15584 }
15585
15586 @ And here's the second.
15587 @^system dependencies@>
15588
15589 @<Declare subroutines for parsing file names@>=
15590 boolean mp_more_name (MP mp, ASCII_code c) { 
15591   if (c==' ') {
15592     return false;
15593   } else { 
15594     if ( (c=='>')||(c==':') ) { 
15595       mp->area_delimiter=mp->pool_ptr; 
15596       mp->ext_delimiter=-1;
15597     } else if ( (c=='.')&&(mp->ext_delimiter<0) ) {
15598       mp->ext_delimiter=mp->pool_ptr;
15599     }
15600     str_room(1); append_char(c); /* contribute |c| to the current string */
15601     return true;
15602   }
15603 }
15604
15605 @ The third.
15606 @^system dependencies@>
15607
15608 @d copy_pool_segment(A,B,C) { 
15609       A = xmalloc(C+1,sizeof(char)); 
15610       strncpy(A,(char *)(mp->str_pool+B),C);  
15611       A[C] = 0;}
15612
15613 @<Declare subroutines for parsing file names@>=
15614 void mp_end_name (MP mp) {
15615   pool_pointer s; /* length of area, name, and extension */
15616   unsigned int len;
15617   /* "my/w.mp" */
15618   s = mp->str_start[mp->str_ptr];
15619   if ( mp->area_delimiter<0 ) {
15620     mp->cur_area=xstrdup("");
15621   } else {
15622     len = mp->area_delimiter-s; 
15623     copy_pool_segment(mp->cur_area,s,len);
15624     s += len+1;
15625   }
15626   if ( mp->ext_delimiter<0 ) {
15627     mp->cur_ext=xstrdup("");
15628     len = mp->pool_ptr-s; 
15629   } else {
15630     copy_pool_segment(mp->cur_ext,mp->ext_delimiter,(mp->pool_ptr-mp->ext_delimiter));
15631     len = mp->ext_delimiter-s;
15632   }
15633   copy_pool_segment(mp->cur_name,s,len);
15634   mp->pool_ptr=s; /* don't need this partial string */
15635 }
15636
15637 @ Conversely, here is a routine that takes three strings and prints a file
15638 name that might have produced them. (The routine is system dependent, because
15639 some operating systems put the file area last instead of first.)
15640 @^system dependencies@>
15641
15642 @<Basic printing...@>=
15643 void mp_print_file_name (MP mp, char * n, char * a, char * e) { 
15644   mp_print(mp, a); mp_print(mp, n); mp_print(mp, e);
15645 };
15646
15647 @ Another system-dependent routine is needed to convert three internal
15648 \MP\ strings
15649 to the |name_of_file| value that is used to open files. The present code
15650 allows both lowercase and uppercase letters in the file name.
15651 @^system dependencies@>
15652
15653 @d append_to_name(A) { c=(A); 
15654   if ( k<file_name_size ) {
15655     mp->name_of_file[k]=mp->xchr[c];
15656     incr(k);
15657   }
15658 }
15659
15660 @<Declare subroutines for parsing file names@>=
15661 void mp_pack_file_name (MP mp, char *n, char *a, char *e) {
15662   integer k; /* number of positions filled in |name_of_file| */
15663   ASCII_code c; /* character being packed */
15664   char *j; /* a character  index */
15665   k=0;
15666   assert(n);
15667   if (a!=NULL) {
15668     for (j=a;*j;j++) { append_to_name(*j); }
15669   }
15670   for (j=n;*j;j++) { append_to_name(*j); }
15671   if (e!=NULL) {
15672     for (j=e;*j;j++) { append_to_name(*j); }
15673   }
15674   mp->name_of_file[k]=0;
15675   mp->name_length=k; 
15676 }
15677
15678 @ @<Exported...@>=
15679 void mp_pack_file_name (MP mp, char *n, char *a, char *e) ;
15680
15681 @ A messier routine is also needed, since mem file names must be scanned
15682 before \MP's string mechanism has been initialized. We shall use the
15683 global variable |MP_mem_default| to supply the text for default system areas
15684 and extensions related to mem files.
15685 @^system dependencies@>
15686
15687 @d mem_default_length 9 /* length of the |MP_mem_default| string */
15688 @d mem_ext_length 4 /* length of its `\.{.mem}' part */
15689 @d mem_extension ".mem" /* the extension, as a \.{WEB} constant */
15690
15691 @<Glob...@>=
15692 char *MP_mem_default;
15693 char *mem_name; /* for commandline */
15694
15695 @ @<Option variables@>=
15696 char *mem_name; /* for commandline */
15697
15698 @ @<Allocate or initialize ...@>=
15699 mp->MP_mem_default = xstrdup("plain.mem");
15700 mp->mem_name = mp_xstrdup(opt.mem_name);
15701 @.plain@>
15702 @^system dependencies@>
15703
15704 @ @<Dealloc variables@>=
15705 xfree(mp->MP_mem_default);
15706 xfree(mp->mem_name);
15707
15708 @ @<Check the ``constant'' values for consistency@>=
15709 if ( mem_default_length>file_name_size ) mp->bad=20;
15710
15711 @ Here is the messy routine that was just mentioned. It sets |name_of_file|
15712 from the first |n| characters of |MP_mem_default|, followed by
15713 |buffer[a..b]|, followed by the last |mem_ext_length| characters of
15714 |MP_mem_default|.
15715
15716 We dare not give error messages here, since \MP\ calls this routine before
15717 the |error| routine is ready to roll. Instead, we simply drop excess characters,
15718 since the error will be detected in another way when a strange file name
15719 isn't found.
15720 @^system dependencies@>
15721
15722 @c void mp_pack_buffered_name (MP mp,small_number n, integer a,
15723                                integer b) {
15724   integer k; /* number of positions filled in |name_of_file| */
15725   ASCII_code c; /* character being packed */
15726   integer j; /* index into |buffer| or |MP_mem_default| */
15727   if ( n+b-a+1+mem_ext_length>file_name_size )
15728     b=a+file_name_size-n-1-mem_ext_length;
15729   k=0;
15730   for (j=0;j<n;j++) {
15731     append_to_name(mp->xord[(int)mp->MP_mem_default[j]]);
15732   }
15733   for (j=a;j<=b;j++) {
15734     append_to_name(mp->buffer[j]);
15735   }
15736   for (j=mem_default_length-mem_ext_length;
15737       j<mem_default_length;j++) {
15738     append_to_name(mp->xord[(int)mp->MP_mem_default[j]]);
15739   } 
15740   mp->name_of_file[k]=0;
15741   mp->name_length=k; 
15742 }
15743
15744 @ Here is the only place we use |pack_buffered_name|. This part of the program
15745 becomes active when a ``virgin'' \MP\ is trying to get going, just after
15746 the preliminary initialization, or when the user is substituting another
15747 mem file by typing `\.\&' after the initial `\.{**}' prompt.  The buffer
15748 contains the first line of input in |buffer[loc..(last-1)]|, where
15749 |loc<last| and |buffer[loc]<>" "|.
15750
15751 @<Declarations@>=
15752 boolean mp_open_mem_file (MP mp) ;
15753
15754 @ @c
15755 boolean mp_open_mem_file (MP mp) {
15756   int j; /* the first space after the file name */
15757   if (mp->mem_name!=NULL) {
15758     mp->mem_file = mp_open_file(mp, mp->mem_name, "rb", mp_filetype_memfile);
15759     if ( mp->mem_file ) return true;
15760   }
15761   j=loc;
15762   if ( mp->buffer[loc]=='&' ) {
15763     incr(loc); j=loc; mp->buffer[mp->last]=' ';
15764     while ( mp->buffer[j]!=' ' ) incr(j);
15765     mp_pack_buffered_name(mp, 0,loc,j-1); /* try first without the system file area */
15766     if ( mp_w_open_in(mp, &mp->mem_file) ) goto FOUND;
15767     wake_up_terminal;
15768     wterm_ln("Sorry, I can\'t find that mem file; will try PLAIN.");
15769 @.Sorry, I can't find...@>
15770     update_terminal;
15771   }
15772   /* now pull out all the stops: try for the system \.{plain} file */
15773   mp_pack_buffered_name(mp, mem_default_length-mem_ext_length,0,0);
15774   if ( ! mp_w_open_in(mp, &mp->mem_file) ) {
15775     wake_up_terminal;
15776     wterm_ln("I can\'t find the PLAIN mem file!\n");
15777 @.I can't find PLAIN...@>
15778 @.plain@>
15779     return false;
15780   }
15781 FOUND:
15782   loc=j; return true;
15783 }
15784
15785 @ Operating systems often make it possible to determine the exact name (and
15786 possible version number) of a file that has been opened. The following routine,
15787 which simply makes a \MP\ string from the value of |name_of_file|, should
15788 ideally be changed to deduce the full name of file~|f|, which is the file
15789 most recently opened, if it is possible to do this in a \PASCAL\ program.
15790 @^system dependencies@>
15791
15792 @<Declarations@>=
15793 #define mp_a_make_name_string(A,B)  mp_make_name_string(A)
15794 #define mp_b_make_name_string(A,B)  mp_make_name_string(A)
15795 #define mp_w_make_name_string(A,B)  mp_make_name_string(A)
15796
15797 @ @c 
15798 str_number mp_make_name_string (MP mp) {
15799   int k; /* index into |name_of_file| */
15800   str_room(mp->name_length);
15801   for (k=0;k<mp->name_length;k++) {
15802     append_char(mp->xord[(int)mp->name_of_file[k]]);
15803   }
15804   return mp_make_string(mp);
15805 }
15806
15807 @ Now let's consider the ``driver''
15808 routines by which \MP\ deals with file names
15809 in a system-independent manner.  First comes a procedure that looks for a
15810 file name in the input by taking the information from the input buffer.
15811 (We can't use |get_next|, because the conversion to tokens would
15812 destroy necessary information.)
15813
15814 This procedure doesn't allow semicolons or percent signs to be part of
15815 file names, because of other conventions of \MP.
15816 {\sl The {\logos METAFONT\/}book} doesn't
15817 use semicolons or percents immediately after file names, but some users
15818 no doubt will find it natural to do so; therefore system-dependent
15819 changes to allow such characters in file names should probably
15820 be made with reluctance, and only when an entire file name that
15821 includes special characters is ``quoted'' somehow.
15822 @^system dependencies@>
15823
15824 @c void mp_scan_file_name (MP mp) { 
15825   mp_begin_name(mp);
15826   while ( mp->buffer[loc]==' ' ) incr(loc);
15827   while (1) { 
15828     if ( (mp->buffer[loc]==';')||(mp->buffer[loc]=='%') ) break;
15829     if ( ! mp_more_name(mp, mp->buffer[loc]) ) break;
15830     incr(loc);
15831   }
15832   mp_end_name(mp);
15833 }
15834
15835 @ Here is another version that takes its input from a string.
15836
15837 @<Declare subroutines for parsing file names@>=
15838 void mp_str_scan_file (MP mp,  str_number s) {
15839   pool_pointer p,q; /* current position and stopping point */
15840   mp_begin_name(mp);
15841   p=mp->str_start[s]; q=str_stop(s);
15842   while ( p<q ){ 
15843     if ( ! mp_more_name(mp, mp->str_pool[p]) ) break;
15844     incr(p);
15845   }
15846   mp_end_name(mp);
15847 }
15848
15849 @ And one that reads from a |char*|.
15850
15851 @<Declare subroutines for parsing file names@>=
15852 void mp_ptr_scan_file (MP mp,  char *s) {
15853   char *p, *q; /* current position and stopping point */
15854   mp_begin_name(mp);
15855   p=s; q=p+strlen(s);
15856   while ( p<q ){ 
15857     if ( ! mp_more_name(mp, *p)) break;
15858     p++;
15859   }
15860   mp_end_name(mp);
15861 }
15862
15863
15864 @ The global variable |job_name| contains the file name that was first
15865 \&{input} by the user. This name is extended by `\.{.log}' and `\.{ps}' and
15866 `\.{.mem}' and `\.{.tfm}' in order to make the names of \MP's output files.
15867
15868 @<Glob...@>=
15869 char *job_name; /* principal file name */
15870 boolean log_opened; /* has the transcript file been opened? */
15871 char *log_name; /* full name of the log file */
15872
15873 @ @<Option variables@>=
15874 char *job_name; /* principal file name */
15875
15876 @ Initially |job_name=NULL|; it becomes nonzero as soon as the true name is known.
15877 We have |job_name=NULL| if and only if the `\.{log}' file has not been opened,
15878 except of course for a short time just after |job_name| has become nonzero.
15879
15880 @<Allocate or ...@>=
15881 mp->job_name=mp_xstrdup(opt.job_name); 
15882 mp->log_opened=false;
15883
15884 @ @<Dealloc variables@>=
15885 xfree(mp->job_name);
15886
15887 @ Here is a routine that manufactures the output file names, assuming that
15888 |job_name<>0|. It ignores and changes the current settings of |cur_area|
15889 and |cur_ext|.
15890
15891 @d pack_cur_name mp_pack_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext)
15892
15893 @<Declarations@>=
15894 void mp_pack_job_name (MP mp, char *s) ;
15895
15896 @ @c void mp_pack_job_name (MP mp, char  *s) { /* |s = ".log"|, |".mem"|, |".ps"|, or .\\{nnn} */
15897   xfree(mp->cur_name); mp->cur_name=xstrdup(mp->job_name);
15898   xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
15899   xfree(mp->cur_ext);  mp->cur_ext=xstrdup(s);
15900   pack_cur_name;
15901 }
15902
15903 @ If some trouble arises when \MP\ tries to open a file, the following
15904 routine calls upon the user to supply another file name. Parameter~|s|
15905 is used in the error message to identify the type of file; parameter~|e|
15906 is the default extension if none is given. Upon exit from the routine,
15907 variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
15908 ready for another attempt at file opening.
15909
15910 @<Declarations@>=
15911 void mp_prompt_file_name (MP mp,char * s, char * e) ;
15912
15913 @ @c void mp_prompt_file_name (MP mp,char * s, char * e) {
15914   size_t k; /* index into |buffer| */
15915   char * saved_cur_name;
15916   if ( mp->interaction==mp_scroll_mode ) 
15917         wake_up_terminal;
15918   if (strcmp(s,"input file name")==0) {
15919         print_err("I can\'t find file `");
15920 @.I can't find file x@>
15921   } else {
15922         print_err("I can\'t write on file `");
15923   }
15924 @.I can't write on file x@>
15925   mp_print_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext); 
15926   mp_print(mp, "'.");
15927   if (strcmp(e,"")==0) 
15928         mp_show_context(mp);
15929   mp_print_nl(mp, "Please type another "); mp_print(mp, s);
15930 @.Please type...@>
15931   if ( mp->interaction<mp_scroll_mode )
15932     mp_fatal_error(mp, "*** (job aborted, file error in nonstop mode)");
15933 @.job aborted, file error...@>
15934   saved_cur_name = xstrdup(mp->cur_name);
15935   clear_terminal; prompt_input(": "); @<Scan file name in the buffer@>;
15936   if (strcmp(mp->cur_ext,"")==0) 
15937         mp->cur_ext=e;
15938   if (strlen(mp->cur_name)==0) {
15939     mp->cur_name=saved_cur_name;
15940   } else {
15941     xfree(saved_cur_name);
15942   }
15943   pack_cur_name;
15944 }
15945
15946 @ @<Scan file name in the buffer@>=
15947
15948   mp_begin_name(mp); k=mp->first;
15949   while ( (mp->buffer[k]==' ')&&(k<mp->last) ) incr(k);
15950   while (1) { 
15951     if ( k==mp->last ) break;
15952     if ( ! mp_more_name(mp, mp->buffer[k]) ) break;
15953     incr(k);
15954   }
15955   mp_end_name(mp);
15956 }
15957
15958 @ The |open_log_file| routine is used to open the transcript file and to help
15959 it catch up to what has previously been printed on the terminal.
15960
15961 @c void mp_open_log_file (MP mp) {
15962   int old_setting; /* previous |selector| setting */
15963   int k; /* index into |months| and |buffer| */
15964   int l; /* end of first input line */
15965   integer m; /* the current month */
15966   char *months="JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"; 
15967     /* abbreviations of month names */
15968   old_setting=mp->selector;
15969   if ( mp->job_name==NULL ) {
15970      mp->job_name=xstrdup("mpout");
15971   }
15972   mp_pack_job_name(mp,".log");
15973   while ( ! mp_a_open_out(mp, &mp->log_file, mp_filetype_log) ) {
15974     @<Try to get a different log file name@>;
15975   }
15976   mp->log_name=xstrdup(mp->name_of_file);
15977   mp->selector=log_only; mp->log_opened=true;
15978   @<Print the banner line, including the date and time@>;
15979   mp->input_stack[mp->input_ptr]=mp->cur_input; 
15980     /* make sure bottom level is in memory */
15981   mp_print_nl(mp, "**");
15982 @.**@>
15983   l=mp->input_stack[0].limit_field-1; /* last position of first line */
15984   for (k=0;k<=l;k++) mp_print_str(mp, mp->buffer[k]);
15985   mp_print_ln(mp); /* now the transcript file contains the first line of input */
15986   mp->selector=old_setting+2; /* |log_only| or |term_and_log| */
15987 }
15988
15989 @ @<Dealloc variables@>=
15990 xfree(mp->log_name);
15991
15992 @ Sometimes |open_log_file| is called at awkward moments when \MP\ is
15993 unable to print error messages or even to |show_context|.
15994 The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
15995 routine will not be invoked because |log_opened| will be false.
15996
15997 The normal idea of |mp_batch_mode| is that nothing at all should be written
15998 on the terminal. However, in the unusual case that
15999 no log file could be opened, we make an exception and allow
16000 an explanatory message to be seen.
16001
16002 Incidentally, the program always refers to the log file as a `\.{transcript
16003 file}', because some systems cannot use the extension `\.{.log}' for
16004 this file.
16005
16006 @<Try to get a different log file name@>=
16007 {  
16008   mp->selector=term_only;
16009   mp_prompt_file_name(mp, "transcript file name",".log");
16010 }
16011
16012 @ @<Print the banner...@>=
16013
16014   wlog(banner);
16015   mp_print(mp, mp->mem_ident); mp_print(mp, "  ");
16016   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[day])); 
16017   mp_print_char(mp, ' ');
16018   m=mp_round_unscaled(mp, mp->internal[month]);
16019   for (k=3*m-3;k<3*m;k++) { wlog_chr(months[k]); }
16020   mp_print_char(mp, ' '); 
16021   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[year])); 
16022   mp_print_char(mp, ' ');
16023   m=mp_round_unscaled(mp, mp->internal[mp_time]);
16024   mp_print_dd(mp, m / 60); mp_print_char(mp, ':'); mp_print_dd(mp, m % 60);
16025 }
16026
16027 @ The |try_extension| function tries to open an input file determined by
16028 |cur_name|, |cur_area|, and the argument |ext|.  It returns |false| if it
16029 can't find the file in |cur_area| or the appropriate system area.
16030
16031 @c boolean mp_try_extension (MP mp,char *ext) { 
16032   mp_pack_file_name(mp, mp->cur_name,mp->cur_area, ext);
16033   in_name=xstrdup(mp->cur_name); 
16034   in_area=xstrdup(mp->cur_area);
16035   if ( mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16036     return true;
16037   } else { 
16038     if (strcmp(ext,".mf")==0 ) in_area=xstrdup(MF_area);
16039     else in_area=xstrdup(MP_area);
16040     mp_pack_file_name(mp, mp->cur_name,in_area,ext);
16041     return mp_a_open_in(mp, &cur_file, mp_filetype_program);
16042   }
16043   return false;
16044 }
16045
16046 @ Let's turn now to the procedure that is used to initiate file reading
16047 when an `\.{input}' command is being processed.
16048
16049 @c void mp_start_input (MP mp) { /* \MP\ will \.{input} something */
16050   char *fname = NULL;
16051   @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>;
16052   while (1) { 
16053     mp_begin_file_reading(mp); /* set up |cur_file| and new level of input */
16054     if ( strlen(mp->cur_ext)==0 ) {
16055       if ( mp_try_extension(mp, ".mp") ) break;
16056       else if ( mp_try_extension(mp, "") ) break;
16057       else if ( mp_try_extension(mp, ".mf") ) break;
16058       /* |else do_nothing; | */
16059     } else if ( mp_try_extension(mp, mp->cur_ext) ) {
16060       break;
16061     }
16062     mp_end_file_reading(mp); /* remove the level that didn't work */
16063     mp_prompt_file_name(mp, "input file name","");
16064   }
16065   name=mp_a_make_name_string(mp, cur_file);
16066   fname = xstrdup(mp->name_of_file);
16067   if ( mp->job_name==NULL ) {
16068     mp->job_name=xstrdup(mp->cur_name); 
16069     mp_open_log_file(mp);
16070   } /* |open_log_file| doesn't |show_context|, so |limit|
16071         and |loc| needn't be set to meaningful values yet */
16072   if ( ((int)mp->term_offset+(int)strlen(fname)) > (mp->max_print_line-2)) mp_print_ln(mp);
16073   else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
16074   mp_print_char(mp, '('); incr(mp->open_parens); mp_print(mp, fname); 
16075   xfree(fname);
16076   update_terminal;
16077   @<Flush |name| and replace it with |cur_name| if it won't be needed@>;
16078   @<Read the first line of the new file@>;
16079 }
16080
16081 @ This code should be omitted if |a_make_name_string| returns something other
16082 than just a copy of its argument and the full file name is needed for opening
16083 \.{MPX} files or implementing the switch-to-editor option.
16084 @^system dependencies@>
16085
16086 @<Flush |name| and replace it with |cur_name| if it won't be needed@>=
16087 mp_flush_string(mp, name); name=rts(mp->cur_name); mp->cur_name=NULL
16088
16089 @ Here we have to remember to tell the |input_ln| routine not to
16090 start with a |get|. If the file is empty, it is considered to
16091 contain a single blank line.
16092 @^system dependencies@>
16093
16094 @<Read the first line...@>=
16095
16096   line=1;
16097   (void)mp_input_ln(mp, cur_file,false); 
16098   mp_firm_up_the_line(mp);
16099   mp->buffer[limit]='%'; mp->first=limit+1; loc=start;
16100 }
16101
16102 @ @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>=
16103 while ( token_state &&(loc==null) ) mp_end_token_list(mp);
16104 if ( token_state ) { 
16105   print_err("File names can't appear within macros");
16106 @.File names can't...@>
16107   help3("Sorry...I've converted what follows to tokens,")
16108     ("possibly garbaging the name you gave.")
16109     ("Please delete the tokens and insert the name again.");
16110   mp_error(mp);
16111 }
16112 if ( file_state ) {
16113   mp_scan_file_name(mp);
16114 } else { 
16115    xfree(mp->cur_name); mp->cur_name=xstrdup(""); 
16116    xfree(mp->cur_ext);  mp->cur_ext =xstrdup(""); 
16117    xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
16118 }
16119
16120 @ Sometimes we need to deal with two file names at once.  This procedure
16121 copies the given string into a special array for an old file name.
16122
16123 @c void mp_copy_old_name (MP mp,str_number s) {
16124   integer k; /* number of positions filled in |old_file_name| */
16125   pool_pointer j; /* index into |str_pool| */
16126   k=0;
16127   for (j=mp->str_start[s];j<=str_stop(s)-1;j++) { 
16128     incr(k);
16129     if ( k<=file_name_size ) 
16130       mp->old_file_name[k]=mp->xchr[mp->str_pool[j]];
16131   }
16132   mp->old_file_name[++k] = 0;
16133 }
16134
16135 @ @<Glob...@>=
16136 char old_file_name[file_name_size+1];  /* analogous to |name_of_file| */
16137
16138 @ The following simple routine starts reading the \.{MPX} file associated
16139 with the current input file.
16140
16141 @c void mp_start_mpx_input (MP mp) {
16142   mp_pack_file_name(mp, in_name, in_area, ".mpx");
16143   @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16144     |goto not_found| if there is a problem@>;
16145   mp_begin_file_reading(mp);
16146   if ( ! mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16147     mp_end_file_reading(mp);
16148     goto NOT_FOUND;
16149   }
16150   name=mp_a_make_name_string(mp, cur_file);
16151   mp->mpx_name[index]=name; add_str_ref(name);
16152   @<Read the first line of the new file@>;
16153   return;
16154 NOT_FOUND: 
16155     @<Explain that the \.{MPX} file can't be read and |succumb|@>;
16156 }
16157
16158 @ This should ideally be changed to do whatever is necessary to create the
16159 \.{MPX} file given by |name_of_file| if it does not exist or if it is out
16160 of date.  This requires invoking \.{MPtoTeX} on the |old_file_name| and passing
16161 the results through \TeX\ and \.{DVItoMP}.  (It is possible to use a
16162 completely different typesetting program if suitable postprocessor is
16163 available to perform the function of \.{DVItoMP}.)
16164 @^system dependencies@>
16165
16166 @ @<Types...@>=
16167 typedef boolean (*run_make_mpx_command)(MP mp, char *origname, char *mtxname);
16168
16169 @ @<Glob...@>=
16170 run_make_mpx_command run_make_mpx;
16171
16172 @ @<Option variables@>=
16173 run_make_mpx_command run_make_mpx;
16174
16175 @ @<Allocate or initialize ...@>=
16176 set_callback_option(run_make_mpx);
16177
16178 @ @<Exported function headers@>=
16179 boolean mp_run_make_mpx (MP mp, char *origname, char *mtxname);
16180
16181 @ The default does nothing.
16182 @c 
16183 boolean mp_run_make_mpx (MP mp, char *origname, char *mtxname) {
16184   if (mp && origname && mtxname) /* for -W */
16185     return false;
16186   return false;
16187 }
16188
16189
16190
16191 @ @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16192   |goto not_found| if there is a problem@>=
16193 mp_copy_old_name(mp, name);
16194 if (!(mp->run_make_mpx)(mp, mp->old_file_name, mp->name_of_file))
16195    goto NOT_FOUND
16196
16197 @ @<Explain that the \.{MPX} file can't be read and |succumb|@>=
16198 if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16199 mp_print_nl(mp, ">> ");
16200 mp_print(mp, mp->old_file_name);
16201 mp_print_nl(mp, ">> ");
16202 mp_print(mp, mp->name_of_file);
16203 mp_print_nl(mp, "! Unable to make mpx file");
16204 help4("The two files given above are one of your source files")
16205   ("and an auxiliary file I need to read to find out what your")
16206   ("btex..etex blocks mean. If you don't know why I had trouble,")
16207   ("try running it manually through MPtoTeX, TeX, and DVItoMP");
16208 succumb;
16209
16210 @ The last file-opening commands are for files accessed via the \&{readfrom}
16211 @:read_from_}{\&{readfrom} primitive@>
16212 operator and the \&{write} command.  Such files are stored in separate arrays.
16213 @:write_}{\&{write} primitive@>
16214
16215 @<Types in the outer block@>=
16216 typedef unsigned int readf_index; /* |0..max_read_files| */
16217 typedef unsigned int write_index;  /* |0..max_write_files| */
16218
16219 @ @<Glob...@>=
16220 readf_index max_read_files; /* maximum number of simultaneously open \&{readfrom} files */
16221 FILE ** rd_file; /* \&{readfrom} files */
16222 char ** rd_fname; /* corresponding file name or 0 if file not open */
16223 readf_index read_files; /* number of valid entries in the above arrays */
16224 write_index max_write_files; /* maximum number of simultaneously open \&{write} */
16225 FILE ** wr_file; /* \&{write} files */
16226 char ** wr_fname; /* corresponding file name or 0 if file not open */
16227 write_index write_files; /* number of valid entries in the above arrays */
16228
16229 @ @<Allocate or initialize ...@>=
16230 mp->max_read_files=8;
16231 mp->rd_file = xmalloc((mp->max_read_files+1),sizeof(FILE *));
16232 mp->rd_fname = xmalloc((mp->max_read_files+1),sizeof(char *));
16233 memset(mp->rd_fname, 0, sizeof(char *)*(mp->max_read_files+1));
16234 mp->read_files=0;
16235 mp->max_write_files=8;
16236 mp->wr_file = xmalloc((mp->max_write_files+1),sizeof(FILE *));
16237 mp->wr_fname = xmalloc((mp->max_write_files+1),sizeof(char *));
16238 memset(mp->wr_fname, 0, sizeof(char *)*(mp->max_write_files+1));
16239 mp->write_files=0;
16240
16241
16242 @ This routine starts reading the file named by string~|s| without setting
16243 |loc|, |limit|, or |name|.  It returns |false| if the file is empty or cannot
16244 be opened.  Otherwise it updates |rd_file[n]| and |rd_fname[n]|.
16245
16246 @c boolean mp_start_read_input (MP mp,char *s, readf_index  n) {
16247   mp_ptr_scan_file(mp, s);
16248   pack_cur_name;
16249   mp_begin_file_reading(mp);
16250   if ( ! mp_a_open_in(mp, &mp->rd_file[n], mp_filetype_text) ) 
16251         goto NOT_FOUND;
16252   if ( ! mp_input_ln(mp, mp->rd_file[n], false) ) {
16253     fclose(mp->rd_file[n]); 
16254         goto NOT_FOUND; 
16255   }
16256   mp->rd_fname[n]=xstrdup(mp->name_of_file);
16257   return true;
16258 NOT_FOUND: 
16259   mp_end_file_reading(mp);
16260   return false;
16261 }
16262
16263 @ Open |wr_file[n]| using file name~|s| and update |wr_fname[n]|.
16264
16265 @<Declarations@>=
16266 void mp_open_write_file (MP mp, char *s, readf_index  n) ;
16267
16268 @ @c void mp_open_write_file (MP mp,char *s, readf_index  n) {
16269   mp_ptr_scan_file(mp, s);
16270   pack_cur_name;
16271   while ( ! mp_a_open_out(mp, &mp->wr_file[n], mp_filetype_text) )
16272     mp_prompt_file_name(mp, "file name for write output","");
16273   mp->wr_fname[n]=xstrdup(mp->name_of_file);
16274 }
16275
16276
16277 @* \[36] Introduction to the parsing routines.
16278 We come now to the central nervous system that sparks many of \MP's activities.
16279 By evaluating expressions, from their primary constituents to ever larger
16280 subexpressions, \MP\ builds the structures that ultimately define complete
16281 pictures or fonts of type.
16282
16283 Four mutually recursive subroutines are involved in this process: We call them
16284 $$\hbox{|scan_primary|, |scan_secondary|, |scan_tertiary|,
16285 and |scan_expression|.}$$
16286 @^recursion@>
16287 Each of them is parameterless and begins with the first token to be scanned
16288 already represented in |cur_cmd|, |cur_mod|, and |cur_sym|. After execution,
16289 the value of the primary or secondary or tertiary or expression that was
16290 found will appear in the global variables |cur_type| and |cur_exp|. The
16291 token following the expression will be represented in |cur_cmd|, |cur_mod|,
16292 and |cur_sym|.
16293
16294 Technically speaking, the parsing algorithms are ``LL(1),'' more or less;
16295 backup mechanisms have been added in order to provide reasonable error
16296 recovery.
16297
16298 @<Glob...@>=
16299 small_number cur_type; /* the type of the expression just found */
16300 integer cur_exp; /* the value of the expression just found */
16301
16302 @ @<Set init...@>=
16303 mp->cur_exp=0;
16304
16305 @ Many different kinds of expressions are possible, so it is wise to have
16306 precise descriptions of what |cur_type| and |cur_exp| mean in all cases:
16307
16308 \smallskip\hang
16309 |cur_type=mp_vacuous| means that this expression didn't turn out to have a
16310 value at all, because it arose from a \&{begingroup}$\,\ldots\,$\&{endgroup}
16311 construction in which there was no expression before the \&{endgroup}.
16312 In this case |cur_exp| has some irrelevant value.
16313
16314 \smallskip\hang
16315 |cur_type=mp_boolean_type| means that |cur_exp| is either |true_code|
16316 or |false_code|.
16317
16318 \smallskip\hang
16319 |cur_type=mp_unknown_boolean| means that |cur_exp| points to a capsule
16320 node that is in the ring of variables equivalent
16321 to at least one undefined boolean variable.
16322
16323 \smallskip\hang
16324 |cur_type=mp_string_type| means that |cur_exp| is a string number (i.e., an
16325 integer in the range |0<=cur_exp<str_ptr|). That string's reference count
16326 includes this particular reference.
16327
16328 \smallskip\hang
16329 |cur_type=mp_unknown_string| means that |cur_exp| points to a capsule
16330 node that is in the ring of variables equivalent
16331 to at least one undefined string variable.
16332
16333 \smallskip\hang
16334 |cur_type=mp_pen_type| means that |cur_exp| points to a node in a pen.  Nobody
16335 else points to any of the nodes in this pen.  The pen may be polygonal or
16336 elliptical.
16337
16338 \smallskip\hang
16339 |cur_type=mp_unknown_pen| means that |cur_exp| points to a capsule
16340 node that is in the ring of variables equivalent
16341 to at least one undefined pen variable.
16342
16343 \smallskip\hang
16344 |cur_type=mp_path_type| means that |cur_exp| points to a the first node of
16345 a path; nobody else points to this particular path. The control points of
16346 the path will have been chosen.
16347
16348 \smallskip\hang
16349 |cur_type=mp_unknown_path| means that |cur_exp| points to a capsule
16350 node that is in the ring of variables equivalent
16351 to at least one undefined path variable.
16352
16353 \smallskip\hang
16354 |cur_type=mp_picture_type| means that |cur_exp| points to an edge header node.
16355 There may be other pointers to this particular set of edges.  The header node
16356 contains a reference count that includes this particular reference.
16357
16358 \smallskip\hang
16359 |cur_type=mp_unknown_picture| means that |cur_exp| points to a capsule
16360 node that is in the ring of variables equivalent
16361 to at least one undefined picture variable.
16362
16363 \smallskip\hang
16364 |cur_type=mp_transform_type| means that |cur_exp| points to a |mp_transform_type|
16365 capsule node. The |value| part of this capsule
16366 points to a transform node that contains six numeric values,
16367 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16368
16369 \smallskip\hang
16370 |cur_type=mp_color_type| means that |cur_exp| points to a |color_type|
16371 capsule node. The |value| part of this capsule
16372 points to a color node that contains three numeric values,
16373 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16374
16375 \smallskip\hang
16376 |cur_type=mp_cmykcolor_type| means that |cur_exp| points to a |mp_cmykcolor_type|
16377 capsule node. The |value| part of this capsule
16378 points to a color node that contains four numeric values,
16379 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16380
16381 \smallskip\hang
16382 |cur_type=mp_pair_type| means that |cur_exp| points to a capsule
16383 node whose type is |mp_pair_type|. The |value| part of this capsule
16384 points to a pair node that contains two numeric values,
16385 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16386
16387 \smallskip\hang
16388 |cur_type=mp_known| means that |cur_exp| is a |scaled| value.
16389
16390 \smallskip\hang
16391 |cur_type=mp_dependent| means that |cur_exp| points to a capsule node whose type
16392 is |dependent|. The |dep_list| field in this capsule points to the associated
16393 dependency list.
16394
16395 \smallskip\hang
16396 |cur_type=mp_proto_dependent| means that |cur_exp| points to a |mp_proto_dependent|
16397 capsule node. The |dep_list| field in this capsule
16398 points to the associated dependency list.
16399
16400 \smallskip\hang
16401 |cur_type=independent| means that |cur_exp| points to a capsule node
16402 whose type is |independent|. This somewhat unusual case can arise, for
16403 example, in the expression
16404 `$x+\&{begingroup}\penalty0\,\&{string}\,x; 0\,\&{endgroup}$'.
16405
16406 \smallskip\hang
16407 |cur_type=mp_token_list| means that |cur_exp| points to a linked list of
16408 tokens. This case arises only on the left-hand side of an assignment
16409 (`\.{:=}') operation, under very special circumstances.
16410
16411 \smallskip\noindent
16412 The possible settings of |cur_type| have been listed here in increasing
16413 numerical order. Notice that |cur_type| will never be |mp_numeric_type| or
16414 |suffixed_macro| or |mp_unsuffixed_macro|, although variables of those types
16415 are allowed.  Conversely, \MP\ has no variables of type |mp_vacuous| or
16416 |token_list|.
16417
16418 @ Capsules are two-word nodes that have a similar meaning
16419 to |cur_type| and |cur_exp|. Such nodes have |name_type=capsule|
16420 and |link<=diov|; and their |type| field is one of the possibilities for
16421 |cur_type| listed above.
16422
16423 The |value| field of a capsule is, in most cases, the value that
16424 corresponds to its |type|, as |cur_exp| corresponds to |cur_type|.
16425 However, when |cur_exp| would point to a capsule,
16426 no extra layer of indirection is present; the |value|
16427 field is what would have been called |value(cur_exp)| if it had not been
16428 encapsulated.  Furthermore, if the type is |dependent| or
16429 |mp_proto_dependent|, the |value| field of a capsule is replaced by
16430 |dep_list| and |prev_dep| fields, since dependency lists in capsules are
16431 always part of the general |dep_list| structure.
16432
16433 The |get_x_next| routine is careful not to change the values of |cur_type|
16434 and |cur_exp| when it gets an expanded token. However, |get_x_next| might
16435 call a macro, which might parse an expression, which might execute lots of
16436 commands in a group; hence it's possible that |cur_type| might change
16437 from, say, |mp_unknown_boolean| to |mp_boolean_type|, or from |dependent| to
16438 |known| or |independent|, during the time |get_x_next| is called. The
16439 programs below are careful to stash sensitive intermediate results in
16440 capsules, so that \MP's generality doesn't cause trouble.
16441
16442 Here's a procedure that illustrates these conventions. It takes
16443 the contents of $(|cur_type|\kern-.3pt,|cur_exp|\kern-.3pt)$
16444 and stashes them away in a
16445 capsule. It is not used when |cur_type=mp_token_list|.
16446 After the operation, |cur_type=mp_vacuous|; hence there is no need to
16447 copy path lists or to update reference counts, etc.
16448
16449 The special link |diov| is put on the capsule returned by
16450 |stash_cur_exp|, because this procedure is used to store macro parameters
16451 that must be easily distinguishable from token lists.
16452
16453 @<Declare the stashing/unstashing routines@>=
16454 pointer mp_stash_cur_exp (MP mp) {
16455   pointer p; /* the capsule that will be returned */
16456   switch (mp->cur_type) {
16457   case unknown_types:
16458   case mp_transform_type:
16459   case mp_color_type:
16460   case mp_pair_type:
16461   case mp_dependent:
16462   case mp_proto_dependent:
16463   case mp_independent: 
16464   case mp_cmykcolor_type:
16465     p=mp->cur_exp;
16466     break;
16467   default: 
16468     p=mp_get_node(mp, value_node_size); name_type(p)=mp_capsule;
16469     type(p)=mp->cur_type; value(p)=mp->cur_exp;
16470     break;
16471   }
16472   mp->cur_type=mp_vacuous; link(p)=diov; 
16473   return p;
16474 }
16475
16476 @ The inverse of |stash_cur_exp| is the following procedure, which
16477 deletes an unnecessary capsule and puts its contents into |cur_type|
16478 and |cur_exp|.
16479
16480 The program steps of \MP\ can be divided into two categories: those in
16481 which |cur_type| and |cur_exp| are ``alive'' and those in which they are
16482 ``dead,'' in the sense that |cur_type| and |cur_exp| contain relevant
16483 information or not. It's important not to ignore them when they're alive,
16484 and it's important not to pay attention to them when they're dead.
16485
16486 There's also an intermediate category: If |cur_type=mp_vacuous|, then
16487 |cur_exp| is irrelevant, hence we can proceed without caring if |cur_type|
16488 and |cur_exp| are alive or dead. In such cases we say that |cur_type|
16489 and |cur_exp| are {\sl dormant}. It is permissible to call |get_x_next|
16490 only when they are alive or dormant.
16491
16492 The \\{stash} procedure above assumes that |cur_type| and |cur_exp|
16493 are alive or dormant. The \\{unstash} procedure assumes that they are
16494 dead or dormant; it resuscitates them.
16495
16496 @<Declare the stashing/unstashing...@>=
16497 void mp_unstash_cur_exp (MP mp,pointer p) ;
16498
16499 @ @c
16500 void mp_unstash_cur_exp (MP mp,pointer p) { 
16501   mp->cur_type=type(p);
16502   switch (mp->cur_type) {
16503   case unknown_types:
16504   case mp_transform_type:
16505   case mp_color_type:
16506   case mp_pair_type:
16507   case mp_dependent: 
16508   case mp_proto_dependent:
16509   case mp_independent:
16510   case mp_cmykcolor_type: 
16511     mp->cur_exp=p;
16512     break;
16513   default:
16514     mp->cur_exp=value(p);
16515     mp_free_node(mp, p,value_node_size);
16516     break;
16517   }
16518 }
16519
16520 @ The following procedure prints the values of expressions in an
16521 abbreviated format. If its first parameter |p| is null, the value of
16522 |(cur_type,cur_exp)| is displayed; otherwise |p| should be a capsule
16523 containing the desired value. The second parameter controls the amount of
16524 output. If it is~0, dependency lists will be abbreviated to
16525 `\.{linearform}' unless they consist of a single term.  If it is greater
16526 than~1, complicated structures (pens, pictures, and paths) will be displayed
16527 in full.
16528
16529 @<Declare subroutines for printing expressions@>=
16530 @<Declare the procedure called |print_dp|@>;
16531 @<Declare the stashing/unstashing routines@>;
16532 void mp_print_exp (MP mp,pointer p, small_number verbosity) {
16533   boolean restore_cur_exp; /* should |cur_exp| be restored? */
16534   small_number t; /* the type of the expression */
16535   pointer q; /* a big node being displayed */
16536   integer v=0; /* the value of the expression */
16537   if ( p!=null ) {
16538     restore_cur_exp=false;
16539   } else { 
16540     p=mp_stash_cur_exp(mp); restore_cur_exp=true;
16541   }
16542   t=type(p);
16543   if ( t<mp_dependent ) v=value(p); else if ( t<mp_independent ) v=dep_list(p);
16544   @<Print an abbreviated value of |v| with format depending on |t|@>;
16545   if ( restore_cur_exp ) mp_unstash_cur_exp(mp, p);
16546 }
16547
16548 @ @<Print an abbreviated value of |v| with format depending on |t|@>=
16549 switch (t) {
16550 case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
16551 case mp_boolean_type:
16552   if ( v==true_code ) mp_print(mp, "true"); else mp_print(mp, "false");
16553   break;
16554 case unknown_types: case mp_numeric_type:
16555   @<Display a variable that's been declared but not defined@>;
16556   break;
16557 case mp_string_type:
16558   mp_print_char(mp, '"'); mp_print_str(mp, v); mp_print_char(mp, '"');
16559   break;
16560 case mp_pen_type: case mp_path_type: case mp_picture_type:
16561   @<Display a complex type@>;
16562   break;
16563 case mp_transform_type: case mp_color_type: case mp_pair_type: case mp_cmykcolor_type:
16564   if ( v==null ) mp_print_type(mp, t);
16565   else @<Display a big node@>;
16566   break;
16567 case mp_known:mp_print_scaled(mp, v); break;
16568 case mp_dependent: case mp_proto_dependent:
16569   mp_print_dp(mp, t,v,verbosity);
16570   break;
16571 case mp_independent:mp_print_variable_name(mp, p); break;
16572 default: mp_confusion(mp, "exp"); break;
16573 @:this can't happen exp}{\quad exp@>
16574 }
16575
16576 @ @<Display a big node@>=
16577
16578   mp_print_char(mp, '('); q=v+mp->big_node_size[t];
16579   do {  
16580     if ( type(v)==mp_known ) mp_print_scaled(mp, value(v));
16581     else if ( type(v)==mp_independent ) mp_print_variable_name(mp, v);
16582     else mp_print_dp(mp, type(v),dep_list(v),verbosity);
16583     v=v+2;
16584     if ( v!=q ) mp_print_char(mp, ',');
16585   } while (v!=q);
16586   mp_print_char(mp, ')');
16587 }
16588
16589 @ Values of type \&{picture}, \&{path}, and \&{pen} are displayed verbosely
16590 in the log file only, unless the user has given a positive value to
16591 \\{tracingonline}.
16592
16593 @<Display a complex type@>=
16594 if ( verbosity<=1 ) {
16595   mp_print_type(mp, t);
16596 } else { 
16597   if ( mp->selector==term_and_log )
16598    if ( mp->internal[tracing_online]<=0 ) {
16599     mp->selector=term_only;
16600     mp_print_type(mp, t); mp_print(mp, " (see the transcript file)");
16601     mp->selector=term_and_log;
16602   };
16603   switch (t) {
16604   case mp_pen_type:mp_print_pen(mp, v,"",false); break;
16605   case mp_path_type:mp_print_path(mp, v,"",false); break;
16606   case mp_picture_type:mp_print_edges(mp, v,"",false); break;
16607   } /* there are no other cases */
16608 }
16609
16610 @ @<Declare the procedure called |print_dp|@>=
16611 void mp_print_dp (MP mp,small_number t, pointer p, 
16612                   small_number verbosity)  {
16613   pointer q; /* the node following |p| */
16614   q=link(p);
16615   if ( (info(q)==null) || (verbosity>0) ) mp_print_dependency(mp, p,t);
16616   else mp_print(mp, "linearform");
16617 }
16618
16619 @ The displayed name of a variable in a ring will not be a capsule unless
16620 the ring consists entirely of capsules.
16621
16622 @<Display a variable that's been declared but not defined@>=
16623 { mp_print_type(mp, t);
16624 if ( v!=null )
16625   { mp_print_char(mp, ' ');
16626   while ( (name_type(v)==mp_capsule) && (v!=p) ) v=value(v);
16627   mp_print_variable_name(mp, v);
16628   };
16629 }
16630
16631 @ When errors are detected during parsing, it is often helpful to
16632 display an expression just above the error message, using |exp_err|
16633 or |disp_err| instead of |print_err|.
16634
16635 @d exp_err(A) mp_disp_err(mp, null,(A)) /* displays the current expression */
16636
16637 @<Declare subroutines for printing expressions@>=
16638 void mp_disp_err (MP mp,pointer p, char *s) { 
16639   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16640   mp_print_nl(mp, ">> ");
16641 @.>>@>
16642   mp_print_exp(mp, p,1); /* ``medium verbose'' printing of the expression */
16643   if (strlen(s)) { 
16644     mp_print_nl(mp, "! "); mp_print(mp, s);
16645 @.!\relax@>
16646   }
16647 }
16648
16649 @ If |cur_type| and |cur_exp| contain relevant information that should
16650 be recycled, we will use the following procedure, which changes |cur_type|
16651 to |known| and stores a given value in |cur_exp|. We can think of |cur_type|
16652 and |cur_exp| as either alive or dormant after this has been done,
16653 because |cur_exp| will not contain a pointer value.
16654
16655 @ @c void mp_flush_cur_exp (MP mp,scaled v) { 
16656   switch (mp->cur_type) {
16657   case unknown_types: case mp_transform_type: case mp_color_type: case mp_pair_type:
16658   case mp_dependent: case mp_proto_dependent: case mp_independent: case mp_cmykcolor_type:
16659     mp_recycle_value(mp, mp->cur_exp); 
16660     mp_free_node(mp, mp->cur_exp,value_node_size);
16661     break;
16662   case mp_string_type:
16663     delete_str_ref(mp->cur_exp); break;
16664   case mp_pen_type: case mp_path_type: 
16665     mp_toss_knot_list(mp, mp->cur_exp); break;
16666   case mp_picture_type:
16667     delete_edge_ref(mp->cur_exp); break;
16668   default: 
16669     break;
16670   }
16671   mp->cur_type=mp_known; mp->cur_exp=v;
16672 }
16673
16674 @ There's a much more general procedure that is capable of releasing
16675 the storage associated with any two-word value packet.
16676
16677 @<Declare the recycling subroutines@>=
16678 void mp_recycle_value (MP mp,pointer p) ;
16679
16680 @ @c void mp_recycle_value (MP mp,pointer p) {
16681   small_number t; /* a type code */
16682   integer vv; /* another value */
16683   pointer q,r,s,pp; /* link manipulation registers */
16684   integer v=0; /* a value */
16685   t=type(p);
16686   if ( t<mp_dependent ) v=value(p);
16687   switch (t) {
16688   case undefined: case mp_vacuous: case mp_boolean_type: case mp_known:
16689   case mp_numeric_type:
16690     break;
16691   case unknown_types:
16692     mp_ring_delete(mp, p); break;
16693   case mp_string_type:
16694     delete_str_ref(v); break;
16695   case mp_path_type: case mp_pen_type:
16696     mp_toss_knot_list(mp, v); break;
16697   case mp_picture_type:
16698     delete_edge_ref(v); break;
16699   case mp_cmykcolor_type: case mp_pair_type: case mp_color_type:
16700   case mp_transform_type:
16701     @<Recycle a big node@>; break; 
16702   case mp_dependent: case mp_proto_dependent:
16703     @<Recycle a dependency list@>; break;
16704   case mp_independent:
16705     @<Recycle an independent variable@>; break;
16706   case mp_token_list: case mp_structured:
16707     mp_confusion(mp, "recycle"); break;
16708 @:this can't happen recycle}{\quad recycle@>
16709   case mp_unsuffixed_macro: case mp_suffixed_macro:
16710     mp_delete_mac_ref(mp, value(p)); break;
16711   } /* there are no other cases */
16712   type(p)=undefined;
16713 }
16714
16715 @ @<Recycle a big node@>=
16716 if ( v!=null ){ 
16717   q=v+mp->big_node_size[t];
16718   do {  
16719     q=q-2; mp_recycle_value(mp, q);
16720   } while (q!=v);
16721   mp_free_node(mp, v,mp->big_node_size[t]);
16722 }
16723
16724 @ @<Recycle a dependency list@>=
16725
16726   q=dep_list(p);
16727   while ( info(q)!=null ) q=link(q);
16728   link(prev_dep(p))=link(q);
16729   prev_dep(link(q))=prev_dep(p);
16730   link(q)=null; mp_flush_node_list(mp, dep_list(p));
16731 }
16732
16733 @ When an independent variable disappears, it simply fades away, unless
16734 something depends on it. In the latter case, a dependent variable whose
16735 coefficient of dependence is maximal will take its place.
16736 The relevant algorithm is due to Ignacio~A. Zabala, who implemented it
16737 as part of his Ph.D. thesis (Stanford University, December 1982).
16738 @^Zabala Salelles, Ignacio Andres@>
16739
16740 For example, suppose that variable $x$ is being recycled, and that the
16741 only variables depending on~$x$ are $y=2x+a$ and $z=x+b$. In this case
16742 we want to make $y$ independent and $z=.5y-.5a+b$; no other variables
16743 will depend on~$y$. If $\\{tracingequations}>0$ in this situation,
16744 we will print `\.{\#\#\# -2x=-y+a}'.
16745
16746 There's a slight complication, however: An independent variable $x$
16747 can occur both in dependency lists and in proto-dependency lists.
16748 This makes it necessary to be careful when deciding which coefficient
16749 is maximal.
16750
16751 Furthermore, this complication is not so slight when
16752 a proto-dependent variable is chosen to become independent. For example,
16753 suppose that $y=2x+100a$ is proto-dependent while $z=x+b$ is dependent;
16754 then we must change $z=.5y-50a+b$ to a proto-dependency, because of the
16755 large coefficient `50'.
16756
16757 In order to deal with these complications without wasting too much time,
16758 we shall link together the occurrences of~$x$ among all the linear
16759 dependencies, maintaining separate lists for the dependent and
16760 proto-dependent cases.
16761
16762 @<Recycle an independent variable@>=
16763
16764   mp->max_c[mp_dependent]=0; mp->max_c[mp_proto_dependent]=0;
16765   mp->max_link[mp_dependent]=null; mp->max_link[mp_proto_dependent]=null;
16766   q=link(dep_head);
16767   while ( q!=dep_head ) { 
16768     s=value_loc(q); /* now |link(s)=dep_list(q)| */
16769     while (1) { 
16770       r=link(s);
16771       if ( info(r)==null ) break;;
16772       if ( info(r)!=p ) { 
16773        s=r;
16774       } else  { 
16775         t=type(q); link(s)=link(r); info(r)=q;
16776         if ( abs(value(r))>mp->max_c[t] ) {
16777           @<Record a new maximum coefficient of type |t|@>;
16778         } else { 
16779           link(r)=mp->max_link[t]; mp->max_link[t]=r;
16780         }
16781       }
16782     }   
16783     q=link(r);
16784   }
16785   if ( (mp->max_c[mp_dependent]>0)||(mp->max_c[mp_proto_dependent]>0) ) {
16786     @<Choose a dependent variable to take the place of the disappearing
16787     independent variable, and change all remaining dependencies
16788     accordingly@>;
16789   }
16790 }
16791
16792 @ The code for independency removal makes use of three two-word arrays.
16793
16794 @<Glob...@>=
16795 integer max_c[mp_proto_dependent+1];  /* max coefficient magnitude */
16796 pointer max_ptr[mp_proto_dependent+1]; /* where |p| occurs with |max_c| */
16797 pointer max_link[mp_proto_dependent+1]; /* other occurrences of |p| */
16798
16799 @ @<Record a new maximum coefficient...@>=
16800
16801   if ( mp->max_c[t]>0 ) {
16802     link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
16803   }
16804   mp->max_c[t]=abs(value(r)); mp->max_ptr[t]=r;
16805 }
16806
16807 @ @<Choose a dependent...@>=
16808
16809   if ( (mp->max_c[mp_dependent] / 010000 >= mp->max_c[mp_proto_dependent]) )
16810     t=mp_dependent;
16811   else 
16812     t=mp_proto_dependent;
16813   @<Determine the dependency list |s| to substitute for the independent
16814     variable~|p|@>;
16815   t=mp_dependent+mp_proto_dependent-t; /* complement |t| */
16816   if ( mp->max_c[t]>0 ) { /* we need to pick up an unchosen dependency */ 
16817     link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
16818   }
16819   if ( t!=mp_dependent ) { @<Substitute new dependencies in place of |p|@>; }
16820   else { @<Substitute new proto-dependencies in place of |p|@>;}
16821   mp_flush_node_list(mp, s);
16822   if ( mp->fix_needed ) mp_fix_dependencies(mp);
16823   check_arith;
16824 }
16825
16826 @ Let |s=max_ptr[t]|. At this point we have $|value|(s)=\pm|max_c|[t]$,
16827 and |info(s)| points to the dependent variable~|pp| of type~|t| from
16828 whose dependency list we have removed node~|s|. We must reinsert
16829 node~|s| into the dependency list, with coefficient $-1.0$, and with
16830 |pp| as the new independent variable. Since |pp| will have a larger serial
16831 number than any other variable, we can put node |s| at the head of the
16832 list.
16833
16834 @<Determine the dep...@>=
16835 s=mp->max_ptr[t]; pp=info(s); v=value(s);
16836 if ( t==mp_dependent ) value(s)=-fraction_one; else value(s)=-unity;
16837 r=dep_list(pp); link(s)=r;
16838 while ( info(r)!=null ) r=link(r);
16839 q=link(r); link(r)=null;
16840 prev_dep(q)=prev_dep(pp); link(prev_dep(pp))=q;
16841 new_indep(pp);
16842 if ( mp->cur_exp==pp ) if ( mp->cur_type==t ) mp->cur_type=mp_independent;
16843 if ( mp->internal[tracing_equations]>0 ) { 
16844   @<Show the transformed dependency@>; 
16845 }
16846
16847 @ Now $(-v)$ times the formerly independent variable~|p| is being replaced
16848 by the dependency list~|s|.
16849
16850 @<Show the transformed...@>=
16851 if ( mp_interesting(mp, p) ) {
16852   mp_begin_diagnostic(mp); mp_print_nl(mp, "### ");
16853 @:]]]\#\#\#_}{\.{\#\#\#}@>
16854   if ( v>0 ) mp_print_char(mp, '-');
16855   if ( t==mp_dependent ) vv=mp_round_fraction(mp, mp->max_c[mp_dependent]);
16856   else vv=mp->max_c[mp_proto_dependent];
16857   if ( vv!=unity ) mp_print_scaled(mp, vv);
16858   mp_print_variable_name(mp, p);
16859   while ( value(p) % s_scale>0 ) {
16860     mp_print(mp, "*4"); value(p)=value(p)-2;
16861   }
16862   if ( t==mp_dependent ) mp_print_char(mp, '='); else mp_print(mp, " = ");
16863   mp_print_dependency(mp, s,t);
16864   mp_end_diagnostic(mp, false);
16865 }
16866
16867 @ Finally, there are dependent and proto-dependent variables whose
16868 dependency lists must be brought up to date.
16869
16870 @<Substitute new dependencies...@>=
16871 for (t=mp_dependent;t<=mp_proto_dependent;t++){ 
16872   r=mp->max_link[t];
16873   while ( r!=null ) {
16874     q=info(r);
16875     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
16876      mp_make_fraction(mp, value(r),-v),s,t,mp_dependent);
16877     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
16878     q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
16879   }
16880 }
16881
16882 @ @<Substitute new proto...@>=
16883 for (t=mp_dependent;t<=mp_proto_dependent;t++) {
16884   r=mp->max_link[t];
16885   while ( r!=null ) {
16886     q=info(r);
16887     if ( t==mp_dependent ) { /* for safety's sake, we change |q| to |mp_proto_dependent| */
16888       if ( mp->cur_exp==q ) if ( mp->cur_type==mp_dependent )
16889         mp->cur_type=mp_proto_dependent;
16890       dep_list(q)=mp_p_over_v(mp, dep_list(q),unity,mp_dependent,mp_proto_dependent);
16891       type(q)=mp_proto_dependent; value(r)=mp_round_fraction(mp, value(r));
16892     }
16893     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
16894       mp_make_scaled(mp, value(r),-v),s,mp_proto_dependent,mp_proto_dependent);
16895     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
16896     q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
16897   }
16898 }
16899
16900 @ Here are some routines that provide handy combinations of actions
16901 that are often needed during error recovery. For example,
16902 `|flush_error|' flushes the current expression, replaces it by
16903 a given value, and calls |error|.
16904
16905 Errors often are detected after an extra token has already been scanned.
16906 The `\\{put\_get}' routines put that token back before calling |error|;
16907 then they get it back again. (Or perhaps they get another token, if
16908 the user has changed things.)
16909
16910 @<Declarations@>=
16911 void mp_flush_error (MP mp,scaled v);
16912 void mp_put_get_error (MP mp);
16913 void mp_put_get_flush_error (MP mp,scaled v) ;
16914
16915 @ @c
16916 void mp_flush_error (MP mp,scaled v) { 
16917   mp_error(mp); mp_flush_cur_exp(mp, v); 
16918 }
16919 void mp_put_get_error (MP mp) { 
16920   mp_back_error(mp); mp_get_x_next(mp); 
16921 }
16922 void mp_put_get_flush_error (MP mp,scaled v) { 
16923   mp_put_get_error(mp);
16924   mp_flush_cur_exp(mp, v); 
16925 }
16926
16927 @ A global variable |var_flag| is set to a special command code
16928 just before \MP\ calls |scan_expression|, if the expression should be
16929 treated as a variable when this command code immediately follows. For
16930 example, |var_flag| is set to |assignment| at the beginning of a
16931 statement, because we want to know the {\sl location\/} of a variable at
16932 the left of `\.{:=}', not the {\sl value\/} of that variable.
16933
16934 The |scan_expression| subroutine calls |scan_tertiary|,
16935 which calls |scan_secondary|, which calls |scan_primary|, which sets
16936 |var_flag:=0|. In this way each of the scanning routines ``knows''
16937 when it has been called with a special |var_flag|, but |var_flag| is
16938 usually zero.
16939
16940 A variable preceding a command that equals |var_flag| is converted to a
16941 token list rather than a value. Furthermore, an `\.{=}' sign following an
16942 expression with |var_flag=assignment| is not considered to be a relation
16943 that produces boolean expressions.
16944
16945
16946 @<Glob...@>=
16947 int var_flag; /* command that wants a variable */
16948
16949 @ @<Set init...@>=
16950 mp->var_flag=0;
16951
16952 @* \[37] Parsing primary expressions.
16953 The first parsing routine, |scan_primary|, is also the most complicated one,
16954 since it involves so many different cases. But each case---with one
16955 exception---is fairly simple by itself.
16956
16957 When |scan_primary| begins, the first token of the primary to be scanned
16958 should already appear in |cur_cmd|, |cur_mod|, and |cur_sym|. The values
16959 of |cur_type| and |cur_exp| should be either dead or dormant, as explained
16960 earlier. If |cur_cmd| is not between |min_primary_command| and
16961 |max_primary_command|, inclusive, a syntax error will be signaled.
16962
16963 @<Declare the basic parsing subroutines@>=
16964 void mp_scan_primary (MP mp) {
16965   pointer p,q,r; /* for list manipulation */
16966   quarterword c; /* a primitive operation code */
16967   int my_var_flag; /* initial value of |my_var_flag| */
16968   pointer l_delim,r_delim; /* hash addresses of a delimiter pair */
16969   @<Other local variables for |scan_primary|@>;
16970   my_var_flag=mp->var_flag; mp->var_flag=0;
16971 RESTART:
16972   check_arith;
16973   @<Supply diagnostic information, if requested@>;
16974   switch (mp->cur_cmd) {
16975   case left_delimiter:
16976     @<Scan a delimited primary@>; break;
16977   case begin_group:
16978     @<Scan a grouped primary@>; break;
16979   case string_token:
16980     @<Scan a string constant@>; break;
16981   case numeric_token:
16982     @<Scan a primary that starts with a numeric token@>; break;
16983   case nullary:
16984     @<Scan a nullary operation@>; break;
16985   case unary: case type_name: case cycle: case plus_or_minus:
16986     @<Scan a unary operation@>; break;
16987   case primary_binary:
16988     @<Scan a binary operation with `\&{of}' between its operands@>; break;
16989   case str_op:
16990     @<Convert a suffix to a string@>; break;
16991   case internal_quantity:
16992     @<Scan an internal numeric quantity@>; break;
16993   case capsule_token:
16994     mp_make_exp_copy(mp, mp->cur_mod); break;
16995   case tag_token:
16996     @<Scan a variable primary; |goto restart| if it turns out to be a macro@>; break;
16997   default: 
16998     mp_bad_exp(mp, "A primary"); goto RESTART; break;
16999 @.A primary expression...@>
17000   }
17001   mp_get_x_next(mp); /* the routines |goto done| if they don't want this */
17002 DONE: 
17003   if ( mp->cur_cmd==left_bracket ) {
17004     if ( mp->cur_type>=mp_known ) {
17005       @<Scan a mediation construction@>;
17006     }
17007   }
17008 }
17009
17010
17011
17012 @ Errors at the beginning of expressions are flagged by |bad_exp|.
17013
17014 @c void mp_bad_exp (MP mp,char * s) {
17015   int save_flag;
17016   print_err(s); mp_print(mp, " expression can't begin with `");
17017   mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); 
17018   mp_print_char(mp, '\'');
17019   help4("I'm afraid I need some sort of value in order to continue,")
17020     ("so I've tentatively inserted `0'. You may want to")
17021     ("delete this zero and insert something else;")
17022     ("see Chapter 27 of The METAFONTbook for an example.");
17023 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
17024   mp_back_input(mp); mp->cur_sym=0; mp->cur_cmd=numeric_token; 
17025   mp->cur_mod=0; mp_ins_error(mp);
17026   save_flag=mp->var_flag; mp->var_flag=0; mp_get_x_next(mp);
17027   mp->var_flag=save_flag;
17028 }
17029
17030 @ @<Supply diagnostic information, if requested@>=
17031 #ifdef DEBUG
17032 if ( mp->panicking ) mp_check_mem(mp, false);
17033 #endif
17034 if ( mp->interrupt!=0 ) if ( mp->OK_to_interrupt ) {
17035   mp_back_input(mp); check_interrupt; mp_get_x_next(mp);
17036 }
17037
17038 @ @<Scan a delimited primary@>=
17039
17040   l_delim=mp->cur_sym; r_delim=mp->cur_mod; 
17041   mp_get_x_next(mp); mp_scan_expression(mp);
17042   if ( (mp->cur_cmd==comma) && (mp->cur_type>=mp_known) ) {
17043     @<Scan the rest of a delimited set of numerics@>;
17044   } else {
17045     mp_check_delimiter(mp, l_delim,r_delim);
17046   }
17047 }
17048
17049 @ The |stash_in| subroutine puts the current (numeric) expression into a field
17050 within a ``big node.''
17051
17052 @c void mp_stash_in (MP mp,pointer p) {
17053   pointer q; /* temporary register */
17054   type(p)=mp->cur_type;
17055   if ( mp->cur_type==mp_known ) {
17056     value(p)=mp->cur_exp;
17057   } else { 
17058     if ( mp->cur_type==mp_independent ) {
17059       @<Stash an independent |cur_exp| into a big node@>;
17060     } else { 
17061       mp->mem[value_loc(p)]=mp->mem[value_loc(mp->cur_exp)];
17062       /* |dep_list(p):=dep_list(cur_exp)| and |prev_dep(p):=prev_dep(cur_exp)| */
17063       link(prev_dep(p))=p;
17064     }
17065     mp_free_node(mp, mp->cur_exp,value_node_size);
17066   }
17067   mp->cur_type=mp_vacuous;
17068 }
17069
17070 @ In rare cases the current expression can become |independent|. There
17071 may be many dependency lists pointing to such an independent capsule,
17072 so we can't simply move it into place within a big node. Instead,
17073 we copy it, then recycle it.
17074
17075 @ @<Stash an independent |cur_exp|...@>=
17076
17077   q=mp_single_dependency(mp, mp->cur_exp);
17078   if ( q==mp->dep_final ){ 
17079     type(p)=mp_known; value(p)=0; mp_free_node(mp, q,dep_node_size);
17080   } else { 
17081     type(p)=mp_dependent; mp_new_dep(mp, p,q);
17082   }
17083   mp_recycle_value(mp, mp->cur_exp);
17084 }
17085
17086 @ This code uses the fact that |red_part_loc| and |green_part_loc|
17087 are synonymous with |x_part_loc| and |y_part_loc|.
17088
17089 @<Scan the rest of a delimited set of numerics@>=
17090
17091 p=mp_stash_cur_exp(mp);
17092 mp_get_x_next(mp); mp_scan_expression(mp);
17093 @<Make sure the second part of a pair or color has a numeric type@>;
17094 q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
17095 if ( mp->cur_cmd==comma ) type(q)=mp_color_type;
17096 else type(q)=mp_pair_type;
17097 mp_init_big_node(mp, q); r=value(q);
17098 mp_stash_in(mp, y_part_loc(r));
17099 mp_unstash_cur_exp(mp, p);
17100 mp_stash_in(mp, x_part_loc(r));
17101 if ( mp->cur_cmd==comma ) {
17102   @<Scan the last of a triplet of numerics@>;
17103 }
17104 if ( mp->cur_cmd==comma ) {
17105   type(q)=mp_cmykcolor_type;
17106   mp_init_big_node(mp, q); t=value(q);
17107   mp->mem[cyan_part_loc(t)]=mp->mem[red_part_loc(r)];
17108   value(cyan_part_loc(t))=value(red_part_loc(r));
17109   mp->mem[magenta_part_loc(t)]=mp->mem[green_part_loc(r)];
17110   value(magenta_part_loc(t))=value(green_part_loc(r));
17111   mp->mem[yellow_part_loc(t)]=mp->mem[blue_part_loc(r)];
17112   value(yellow_part_loc(t))=value(blue_part_loc(r));
17113   mp_recycle_value(mp, r);
17114   r=t;
17115   @<Scan the last of a quartet of numerics@>;
17116 }
17117 mp_check_delimiter(mp, l_delim,r_delim);
17118 mp->cur_type=type(q);
17119 mp->cur_exp=q;
17120 }
17121
17122 @ @<Make sure the second part of a pair or color has a numeric type@>=
17123 if ( mp->cur_type<mp_known ) {
17124   exp_err("Nonnumeric ypart has been replaced by 0");
17125 @.Nonnumeric...replaced by 0@>
17126   help4("I've started to scan a pair `(a,b)' or a color `(a,b,c)';")
17127     ("but after finding a nice `a' I found a `b' that isn't")
17128     ("of numeric type. So I've changed that part to zero.")
17129     ("(The b that I didn't like appears above the error message.)");
17130   mp_put_get_flush_error(mp, 0);
17131 }
17132
17133 @ @<Scan the last of a triplet of numerics@>=
17134
17135   mp_get_x_next(mp); mp_scan_expression(mp);
17136   if ( mp->cur_type<mp_known ) {
17137     exp_err("Nonnumeric third part has been replaced by 0");
17138 @.Nonnumeric...replaced by 0@>
17139     help3("I've just scanned a color `(a,b,c)' or cmykcolor(a,b,c,d); but the `c'")
17140       ("isn't of numeric type. So I've changed that part to zero.")
17141       ("(The c that I didn't like appears above the error message.)");
17142     mp_put_get_flush_error(mp, 0);
17143   }
17144   mp_stash_in(mp, blue_part_loc(r));
17145 }
17146
17147 @ @<Scan the last of a quartet of numerics@>=
17148
17149   mp_get_x_next(mp); mp_scan_expression(mp);
17150   if ( mp->cur_type<mp_known ) {
17151     exp_err("Nonnumeric blackpart has been replaced by 0");
17152 @.Nonnumeric...replaced by 0@>
17153     help3("I've just scanned a cmykcolor `(c,m,y,k)'; but the `k' isn't")
17154       ("of numeric type. So I've changed that part to zero.")
17155       ("(The k that I didn't like appears above the error message.)");
17156     mp_put_get_flush_error(mp, 0);
17157   }
17158   mp_stash_in(mp, black_part_loc(r));
17159 }
17160
17161 @ The local variable |group_line| keeps track of the line
17162 where a \&{begingroup} command occurred; this will be useful
17163 in an error message if the group doesn't actually end.
17164
17165 @<Other local variables for |scan_primary|@>=
17166 integer group_line; /* where a group began */
17167
17168 @ @<Scan a grouped primary@>=
17169
17170   group_line=mp_true_line(mp);
17171   if ( mp->internal[tracing_commands]>0 ) show_cur_cmd_mod;
17172   save_boundary_item(p);
17173   do {  
17174     mp_do_statement(mp); /* ends with |cur_cmd>=semicolon| */
17175   } while (! (mp->cur_cmd!=semicolon));
17176   if ( mp->cur_cmd!=end_group ) {
17177     print_err("A group begun on line ");
17178 @.A group...never ended@>
17179     mp_print_int(mp, group_line);
17180     mp_print(mp, " never ended");
17181     help2("I saw a `begingroup' back there that hasn't been matched")
17182          ("by `endgroup'. So I've inserted `endgroup' now.");
17183     mp_back_error(mp); mp->cur_cmd=end_group;
17184   }
17185   mp_unsave(mp); 
17186     /* this might change |cur_type|, if independent variables are recycled */
17187   if ( mp->internal[tracing_commands]>0 ) show_cur_cmd_mod;
17188 }
17189
17190 @ @<Scan a string constant@>=
17191
17192   mp->cur_type=mp_string_type; mp->cur_exp=mp->cur_mod;
17193 }
17194
17195 @ Later we'll come to procedures that perform actual operations like
17196 addition, square root, and so on; our purpose now is to do the parsing.
17197 But we might as well mention those future procedures now, so that the
17198 suspense won't be too bad:
17199
17200 \smallskip
17201 |do_nullary(c)| does primitive operations that have no operands (e.g.,
17202 `\&{true}' or `\&{pencircle}');
17203
17204 \smallskip
17205 |do_unary(c)| applies a primitive operation to the current expression;
17206
17207 \smallskip
17208 |do_binary(p,c)| applies a primitive operation to the capsule~|p|
17209 and the current expression.
17210
17211 @<Scan a nullary operation@>=mp_do_nullary(mp, mp->cur_mod)
17212
17213 @ @<Scan a unary operation@>=
17214
17215   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_primary(mp); 
17216   mp_do_unary(mp, c); goto DONE;
17217 }
17218
17219 @ A numeric token might be a primary by itself, or it might be the
17220 numerator of a fraction composed solely of numeric tokens, or it might
17221 multiply the primary that follows (provided that the primary doesn't begin
17222 with a plus sign or a minus sign). The code here uses the facts that
17223 |max_primary_command=plus_or_minus| and
17224 |max_primary_command-1=numeric_token|. If a fraction is found that is less
17225 than unity, we try to retain higher precision when we use it in scalar
17226 multiplication.
17227
17228 @<Other local variables for |scan_primary|@>=
17229 scaled num,denom; /* for primaries that are fractions, like `1/2' */
17230
17231 @ @<Scan a primary that starts with a numeric token@>=
17232
17233   mp->cur_exp=mp->cur_mod; mp->cur_type=mp_known; mp_get_x_next(mp);
17234   if ( mp->cur_cmd!=slash ) { 
17235     num=0; denom=0;
17236   } else { 
17237     mp_get_x_next(mp);
17238     if ( mp->cur_cmd!=numeric_token ) { 
17239       mp_back_input(mp);
17240       mp->cur_cmd=slash; mp->cur_mod=over; mp->cur_sym=frozen_slash;
17241       goto DONE;
17242     }
17243     num=mp->cur_exp; denom=mp->cur_mod;
17244     if ( denom==0 ) { @<Protest division by zero@>; }
17245     else { mp->cur_exp=mp_make_scaled(mp, num,denom); }
17246     check_arith; mp_get_x_next(mp);
17247   }
17248   if ( mp->cur_cmd>=min_primary_command ) {
17249    if ( mp->cur_cmd<numeric_token ) { /* in particular, |cur_cmd<>plus_or_minus| */
17250      p=mp_stash_cur_exp(mp); mp_scan_primary(mp);
17251      if ( (abs(num)>=abs(denom))||(mp->cur_type<mp_color_type) ) {
17252        mp_do_binary(mp, p,times);
17253      } else {
17254        mp_frac_mult(mp, num,denom);
17255        mp_free_node(mp, p,value_node_size);
17256      }
17257     }
17258   }
17259   goto DONE;
17260 }
17261
17262 @ @<Protest division...@>=
17263
17264   print_err("Division by zero");
17265 @.Division by zero@>
17266   help1("I'll pretend that you meant to divide by 1."); mp_error(mp);
17267 }
17268
17269 @ @<Scan a binary operation with `\&{of}' between its operands@>=
17270
17271   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
17272   if ( mp->cur_cmd!=of_token ) {
17273     mp_missing_err(mp, "of"); mp_print(mp, " for "); 
17274     mp_print_cmd_mod(mp, primary_binary,c);
17275 @.Missing `of'@>
17276     help1("I've got the first argument; will look now for the other.");
17277     mp_back_error(mp);
17278   }
17279   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_primary(mp); 
17280   mp_do_binary(mp, p,c); goto DONE;
17281 }
17282
17283 @ @<Convert a suffix to a string@>=
17284
17285   mp_get_x_next(mp); mp_scan_suffix(mp); 
17286   mp->old_setting=mp->selector; mp->selector=new_string;
17287   mp_show_token_list(mp, mp->cur_exp,null,100000,0); 
17288   mp_flush_token_list(mp, mp->cur_exp);
17289   mp->cur_exp=mp_make_string(mp); mp->selector=mp->old_setting; 
17290   mp->cur_type=mp_string_type;
17291   goto DONE;
17292 }
17293
17294 @ If an internal quantity appears all by itself on the left of an
17295 assignment, we return a token list of length one, containing the address
17296 of the internal quantity plus |hash_end|. (This accords with the conventions
17297 of the save stack, as described earlier.)
17298
17299 @<Scan an internal...@>=
17300
17301   q=mp->cur_mod;
17302   if ( my_var_flag==assignment ) {
17303     mp_get_x_next(mp);
17304     if ( mp->cur_cmd==assignment ) {
17305       mp->cur_exp=mp_get_avail(mp);
17306       info(mp->cur_exp)=q+hash_end; mp->cur_type=mp_token_list; 
17307       goto DONE;
17308     }
17309     mp_back_input(mp);
17310   }
17311   mp->cur_type=mp_known; mp->cur_exp=mp->internal[q];
17312 }
17313
17314 @ The most difficult part of |scan_primary| has been saved for last, since
17315 it was necessary to build up some confidence first. We can now face the task
17316 of scanning a variable.
17317
17318 As we scan a variable, we build a token list containing the relevant
17319 names and subscript values, simultaneously following along in the
17320 ``collective'' structure to see if we are actually dealing with a macro
17321 instead of a value.
17322
17323 The local variables |pre_head| and |post_head| will point to the beginning
17324 of the prefix and suffix lists; |tail| will point to the end of the list
17325 that is currently growing.
17326
17327 Another local variable, |tt|, contains partial information about the
17328 declared type of the variable-so-far. If |tt>=mp_unsuffixed_macro|, the
17329 relation |tt=type(q)| will always hold. If |tt=undefined|, the routine
17330 doesn't bother to update its information about type. And if
17331 |undefined<tt<mp_unsuffixed_macro|, the precise value of |tt| isn't critical.
17332
17333 @ @<Other local variables for |scan_primary|@>=
17334 pointer pre_head,post_head,tail;
17335   /* prefix and suffix list variables */
17336 small_number tt; /* approximation to the type of the variable-so-far */
17337 pointer t; /* a token */
17338 pointer macro_ref = 0; /* reference count for a suffixed macro */
17339
17340 @ @<Scan a variable primary...@>=
17341
17342   fast_get_avail(pre_head); tail=pre_head; post_head=null; tt=mp_vacuous;
17343   while (1) { 
17344     t=mp_cur_tok(mp); link(tail)=t;
17345     if ( tt!=undefined ) {
17346        @<Find the approximate type |tt| and corresponding~|q|@>;
17347       if ( tt>=mp_unsuffixed_macro ) {
17348         @<Either begin an unsuffixed macro call or
17349           prepare for a suffixed one@>;
17350       }
17351     }
17352     mp_get_x_next(mp); tail=t;
17353     if ( mp->cur_cmd==left_bracket ) {
17354       @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>;
17355     }
17356     if ( mp->cur_cmd>max_suffix_token ) break;
17357     if ( mp->cur_cmd<min_suffix_token ) break;
17358   } /* now |cur_cmd| is |internal_quantity|, |tag_token|, or |numeric_token| */
17359   @<Handle unusual cases that masquerade as variables, and |goto restart|
17360     or |goto done| if appropriate;
17361     otherwise make a copy of the variable and |goto done|@>;
17362 }
17363
17364 @ @<Either begin an unsuffixed macro call or...@>=
17365
17366   link(tail)=null;
17367   if ( tt>mp_unsuffixed_macro ) { /* |tt=mp_suffixed_macro| */
17368     post_head=mp_get_avail(mp); tail=post_head; link(tail)=t;
17369     tt=undefined; macro_ref=value(q); add_mac_ref(macro_ref);
17370   } else {
17371     @<Set up unsuffixed macro call and |goto restart|@>;
17372   }
17373 }
17374
17375 @ @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>=
17376
17377   mp_get_x_next(mp); mp_scan_expression(mp);
17378   if ( mp->cur_cmd!=right_bracket ) {
17379     @<Put the left bracket and the expression back to be rescanned@>;
17380   } else { 
17381     if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17382     mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp; mp->cur_sym=0;
17383   }
17384 }
17385
17386 @ The left bracket that we thought was introducing a subscript might have
17387 actually been the left bracket in a mediation construction like `\.{x[a,b]}'.
17388 So we don't issue an error message at this point; but we do want to back up
17389 so as to avoid any embarrassment about our incorrect assumption.
17390
17391 @<Put the left bracket and the expression back to be rescanned@>=
17392
17393   mp_back_input(mp); /* that was the token following the current expression */
17394   mp_back_expr(mp); mp->cur_cmd=left_bracket; 
17395   mp->cur_mod=0; mp->cur_sym=frozen_left_bracket;
17396 }
17397
17398 @ Here's a routine that puts the current expression back to be read again.
17399
17400 @c void mp_back_expr (MP mp) {
17401   pointer p; /* capsule token */
17402   p=mp_stash_cur_exp(mp); link(p)=null; back_list(p);
17403 }
17404
17405 @ Unknown subscripts lead to the following error message.
17406
17407 @c void mp_bad_subscript (MP mp) { 
17408   exp_err("Improper subscript has been replaced by zero");
17409 @.Improper subscript...@>
17410   help3("A bracketed subscript must have a known numeric value;")
17411     ("unfortunately, what I found was the value that appears just")
17412     ("above this error message. So I'll try a zero subscript.");
17413   mp_flush_error(mp, 0);
17414 }
17415
17416 @ Every time we call |get_x_next|, there's a chance that the variable we've
17417 been looking at will disappear. Thus, we cannot safely keep |q| pointing
17418 into the variable structure; we need to start searching from the root each time.
17419
17420 @<Find the approximate type |tt| and corresponding~|q|@>=
17421 @^inner loop@>
17422
17423   p=link(pre_head); q=info(p); tt=undefined;
17424   if ( eq_type(q) % outer_tag==tag_token ) {
17425     q=equiv(q);
17426     if ( q==null ) goto DONE2;
17427     while (1) { 
17428       p=link(p);
17429       if ( p==null ) {
17430         tt=type(q); goto DONE2;
17431       };
17432       if ( type(q)!=mp_structured ) goto DONE2;
17433       q=link(attr_head(q)); /* the |collective_subscript| attribute */
17434       if ( p>=mp->hi_mem_min ) { /* it's not a subscript */
17435         do {  q=link(q); } while (! (attr_loc(q)>=info(p)));
17436         if ( attr_loc(q)>info(p) ) goto DONE2;
17437       }
17438     }
17439   }
17440 DONE2:
17441   ;
17442 }
17443
17444 @ How do things stand now? Well, we have scanned an entire variable name,
17445 including possible subscripts and/or attributes; |cur_cmd|, |cur_mod|, and
17446 |cur_sym| represent the token that follows. If |post_head=null|, a
17447 token list for this variable name starts at |link(pre_head)|, with all
17448 subscripts evaluated. But if |post_head<>null|, the variable turned out
17449 to be a suffixed macro; |pre_head| is the head of the prefix list, while
17450 |post_head| is the head of a token list containing both `\.{\AT!}' and
17451 the suffix.
17452
17453 Our immediate problem is to see if this variable still exists. (Variable
17454 structures can change drastically whenever we call |get_x_next|; users
17455 aren't supposed to do this, but the fact that it is possible means that
17456 we must be cautious.)
17457
17458 The following procedure prints an error message when a variable
17459 unexpectedly disappears. Its help message isn't quite right for
17460 our present purposes, but we'll be able to fix that up.
17461
17462 @c 
17463 void mp_obliterated (MP mp,pointer q) { 
17464   print_err("Variable "); mp_show_token_list(mp, q,null,1000,0);
17465   mp_print(mp, " has been obliterated");
17466 @.Variable...obliterated@>
17467   help5("It seems you did a nasty thing---probably by accident,")
17468     ("but nevertheless you nearly hornswoggled me...")
17469     ("While I was evaluating the right-hand side of this")
17470     ("command, something happened, and the left-hand side")
17471     ("is no longer a variable! So I won't change anything.");
17472 }
17473
17474 @ If the variable does exist, we also need to check
17475 for a few other special cases before deciding that a plain old ordinary
17476 variable has, indeed, been scanned.
17477
17478 @<Handle unusual cases that masquerade as variables...@>=
17479 if ( post_head!=null ) {
17480   @<Set up suffixed macro call and |goto restart|@>;
17481 }
17482 q=link(pre_head); free_avail(pre_head);
17483 if ( mp->cur_cmd==my_var_flag ) { 
17484   mp->cur_type=mp_token_list; mp->cur_exp=q; goto DONE;
17485 }
17486 p=mp_find_variable(mp, q);
17487 if ( p!=null ) {
17488   mp_make_exp_copy(mp, p);
17489 } else { 
17490   mp_obliterated(mp, q);
17491   mp->help_line[2]="While I was evaluating the suffix of this variable,";
17492   mp->help_line[1]="something was redefined, and it's no longer a variable!";
17493   mp->help_line[0]="In order to get back on my feet, I've inserted `0' instead.";
17494   mp_put_get_flush_error(mp, 0);
17495 }
17496 mp_flush_node_list(mp, q); 
17497 goto DONE
17498
17499 @ The only complication associated with macro calling is that the prefix
17500 and ``at'' parameters must be packaged in an appropriate list of lists.
17501
17502 @<Set up unsuffixed macro call and |goto restart|@>=
17503
17504   p=mp_get_avail(mp); info(pre_head)=link(pre_head); link(pre_head)=p;
17505   info(p)=t; mp_macro_call(mp, value(q),pre_head,null);
17506   mp_get_x_next(mp); 
17507   goto RESTART;
17508 }
17509
17510 @ If the ``variable'' that turned out to be a suffixed macro no longer exists,
17511 we don't care, because we have reserved a pointer (|macro_ref|) to its
17512 token list.
17513
17514 @<Set up suffixed macro call and |goto restart|@>=
17515
17516   mp_back_input(mp); p=mp_get_avail(mp); q=link(post_head);
17517   info(pre_head)=link(pre_head); link(pre_head)=post_head;
17518   info(post_head)=q; link(post_head)=p; info(p)=link(q); link(q)=null;
17519   mp_macro_call(mp, macro_ref,pre_head,null); decr(ref_count(macro_ref));
17520   mp_get_x_next(mp); goto RESTART;
17521 }
17522
17523 @ Our remaining job is simply to make a copy of the value that has been
17524 found. Some cases are harder than others, but complexity arises solely
17525 because of the multiplicity of possible cases.
17526
17527 @<Declare the procedure called |make_exp_copy|@>=
17528 @<Declare subroutines needed by |make_exp_copy|@>;
17529 void mp_make_exp_copy (MP mp,pointer p) {
17530   pointer q,r,t; /* registers for list manipulation */
17531 RESTART: 
17532   mp->cur_type=type(p);
17533   switch (mp->cur_type) {
17534   case mp_vacuous: case mp_boolean_type: case mp_known:
17535     mp->cur_exp=value(p); break;
17536   case unknown_types:
17537     mp->cur_exp=mp_new_ring_entry(mp, p);
17538     break;
17539   case mp_string_type: 
17540     mp->cur_exp=value(p); add_str_ref(mp->cur_exp);
17541     break;
17542   case mp_picture_type:
17543     mp->cur_exp=value(p);add_edge_ref(mp->cur_exp);
17544     break;
17545   case mp_pen_type:
17546     mp->cur_exp=copy_pen(value(p));
17547     break; 
17548   case mp_path_type:
17549     mp->cur_exp=mp_copy_path(mp, value(p));
17550     break;
17551   case mp_transform_type: case mp_color_type: 
17552   case mp_cmykcolor_type: case mp_pair_type:
17553     @<Copy the big node |p|@>;
17554     break;
17555   case mp_dependent: case mp_proto_dependent:
17556     mp_encapsulate(mp, mp_copy_dep_list(mp, dep_list(p)));
17557     break;
17558   case mp_numeric_type: 
17559     new_indep(p); goto RESTART;
17560     break;
17561   case mp_independent: 
17562     q=mp_single_dependency(mp, p);
17563     if ( q==mp->dep_final ){ 
17564       mp->cur_type=mp_known; mp->cur_exp=0; mp_free_node(mp, q,value_node_size);
17565     } else { 
17566       mp->cur_type=mp_dependent; mp_encapsulate(mp, q);
17567     }
17568     break;
17569   default: 
17570     mp_confusion(mp, "copy");
17571 @:this can't happen copy}{\quad copy@>
17572     break;
17573   }
17574 }
17575
17576 @ The |encapsulate| subroutine assumes that |dep_final| is the
17577 tail of dependency list~|p|.
17578
17579 @<Declare subroutines needed by |make_exp_copy|@>=
17580 void mp_encapsulate (MP mp,pointer p) { 
17581   mp->cur_exp=mp_get_node(mp, value_node_size); type(mp->cur_exp)=mp->cur_type;
17582   name_type(mp->cur_exp)=mp_capsule; mp_new_dep(mp, mp->cur_exp,p);
17583 }
17584
17585 @ The most tedious case arises when the user refers to a
17586 \&{pair}, \&{color}, or \&{transform} variable; we must copy several fields,
17587 each of which can be |independent|, |dependent|, |mp_proto_dependent|,
17588 or |known|.
17589
17590 @<Copy the big node |p|@>=
17591
17592   if ( value(p)==null ) 
17593     mp_init_big_node(mp, p);
17594   t=mp_get_node(mp, value_node_size); name_type(t)=mp_capsule; type(t)=mp->cur_type;
17595   mp_init_big_node(mp, t);
17596   q=value(p)+mp->big_node_size[mp->cur_type]; 
17597   r=value(t)+mp->big_node_size[mp->cur_type];
17598   do {  
17599     q=q-2; r=r-2; mp_install(mp, r,q);
17600   } while (q!=value(p));
17601   mp->cur_exp=t;
17602 }
17603
17604 @ The |install| procedure copies a numeric field~|q| into field~|r| of
17605 a big node that will be part of a capsule.
17606
17607 @<Declare subroutines needed by |make_exp_copy|@>=
17608 void mp_install (MP mp,pointer r, pointer q) {
17609   pointer p; /* temporary register */
17610   if ( type(q)==mp_known ){ 
17611     value(r)=value(q); type(r)=mp_known;
17612   } else  if ( type(q)==mp_independent ) {
17613     p=mp_single_dependency(mp, q);
17614     if ( p==mp->dep_final ) {
17615       type(r)=mp_known; value(r)=0; mp_free_node(mp, p,value_node_size);
17616     } else  { 
17617       type(r)=mp_dependent; mp_new_dep(mp, r,p);
17618     }
17619   } else {
17620     type(r)=type(q); mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(q)));
17621   }
17622 }
17623
17624 @ Expressions of the form `\.{a[b,c]}' are converted into
17625 `\.{b+a*(c-b)}', without checking the types of \.b~or~\.c,
17626 provided that \.a is numeric.
17627
17628 @<Scan a mediation...@>=
17629
17630   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17631   if ( mp->cur_cmd!=comma ) {
17632     @<Put the left bracket and the expression back...@>;
17633     mp_unstash_cur_exp(mp, p);
17634   } else { 
17635     q=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17636     if ( mp->cur_cmd!=right_bracket ) {
17637       mp_missing_err(mp, "]");
17638 @.Missing `]'@>
17639       help3("I've scanned an expression of the form `a[b,c',")
17640       ("so a right bracket should have come next.")
17641       ("I shall pretend that one was there.");
17642       mp_back_error(mp);
17643     }
17644     r=mp_stash_cur_exp(mp); mp_make_exp_copy(mp, q);
17645     mp_do_binary(mp, r,minus); mp_do_binary(mp, p,times); 
17646     mp_do_binary(mp, q,plus); mp_get_x_next(mp);
17647   }
17648 }
17649
17650 @ Here is a comparatively simple routine that is used to scan the
17651 \&{suffix} parameters of a macro.
17652
17653 @<Declare the basic parsing subroutines@>=
17654 void mp_scan_suffix (MP mp) {
17655   pointer h,t; /* head and tail of the list being built */
17656   pointer p; /* temporary register */
17657   h=mp_get_avail(mp); t=h;
17658   while (1) { 
17659     if ( mp->cur_cmd==left_bracket ) {
17660       @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>;
17661     }
17662     if ( mp->cur_cmd==numeric_token ) {
17663       p=mp_new_num_tok(mp, mp->cur_mod);
17664     } else if ((mp->cur_cmd==tag_token)||(mp->cur_cmd==internal_quantity) ) {
17665        p=mp_get_avail(mp); info(p)=mp->cur_sym;
17666     } else {
17667       break;
17668     }
17669     link(t)=p; t=p; mp_get_x_next(mp);
17670   }
17671   mp->cur_exp=link(h); free_avail(h); mp->cur_type=mp_token_list;
17672 }
17673
17674 @ @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>=
17675
17676   mp_get_x_next(mp); mp_scan_expression(mp);
17677   if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17678   if ( mp->cur_cmd!=right_bracket ) {
17679      mp_missing_err(mp, "]");
17680 @.Missing `]'@>
17681     help3("I've seen a `[' and a subscript value, in a suffix,")
17682       ("so a right bracket should have come next.")
17683       ("I shall pretend that one was there.");
17684     mp_back_error(mp);
17685   }
17686   mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp;
17687 }
17688
17689 @* \[38] Parsing secondary and higher expressions.
17690 After the intricacies of |scan_primary|\kern-1pt,
17691 the |scan_secondary| routine is
17692 refreshingly simple. It's not trivial, but the operations are relatively
17693 straightforward; the main difficulty is, again, that expressions and data
17694 structures might change drastically every time we call |get_x_next|, so a
17695 cautious approach is mandatory. For example, a macro defined by
17696 \&{primarydef} might have disappeared by the time its second argument has
17697 been scanned; we solve this by increasing the reference count of its token
17698 list, so that the macro can be called even after it has been clobbered.
17699
17700 @<Declare the basic parsing subroutines@>=
17701 void mp_scan_secondary (MP mp) {
17702   pointer p; /* for list manipulation */
17703   halfword c,d; /* operation codes or modifiers */
17704   pointer mac_name; /* token defined with \&{primarydef} */
17705 RESTART:
17706   if ((mp->cur_cmd<min_primary_command)||
17707       (mp->cur_cmd>max_primary_command) )
17708     mp_bad_exp(mp, "A secondary");
17709 @.A secondary expression...@>
17710   mp_scan_primary(mp);
17711 CONTINUE: 
17712   if ( mp->cur_cmd<=max_secondary_command )
17713     if ( mp->cur_cmd>=min_secondary_command ) {
17714       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17715       if ( d==secondary_primary_macro ) { 
17716         mac_name=mp->cur_sym; add_mac_ref(c);
17717      }
17718      mp_get_x_next(mp); mp_scan_primary(mp);
17719      if ( d!=secondary_primary_macro ) {
17720        mp_do_binary(mp, p,c);
17721      } else  { 
17722        mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17723        decr(ref_count(c)); mp_get_x_next(mp); 
17724        goto RESTART;
17725     }
17726     goto CONTINUE;
17727   }
17728 }
17729
17730 @ The following procedure calls a macro that has two parameters,
17731 |p| and |cur_exp|.
17732
17733 @c void mp_binary_mac (MP mp,pointer p, pointer c, pointer n) {
17734   pointer q,r; /* nodes in the parameter list */
17735   q=mp_get_avail(mp); r=mp_get_avail(mp); link(q)=r;
17736   info(q)=p; info(r)=mp_stash_cur_exp(mp);
17737   mp_macro_call(mp, c,q,n);
17738 }
17739
17740 @ The next procedure, |scan_tertiary|, is pretty much the same deal.
17741
17742 @<Declare the basic parsing subroutines@>=
17743 void mp_scan_tertiary (MP mp) {
17744   pointer p; /* for list manipulation */
17745   halfword c,d; /* operation codes or modifiers */
17746   pointer mac_name; /* token defined with \&{secondarydef} */
17747 RESTART:
17748   if ((mp->cur_cmd<min_primary_command)||
17749       (mp->cur_cmd>max_primary_command) )
17750     mp_bad_exp(mp, "A tertiary");
17751 @.A tertiary expression...@>
17752   mp_scan_secondary(mp);
17753 CONTINUE: 
17754   if ( mp->cur_cmd<=max_tertiary_command ) {
17755     if ( mp->cur_cmd>=min_tertiary_command ) {
17756       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17757       if ( d==tertiary_secondary_macro ) { 
17758         mac_name=mp->cur_sym; add_mac_ref(c);
17759       };
17760       mp_get_x_next(mp); mp_scan_secondary(mp);
17761       if ( d!=tertiary_secondary_macro ) {
17762         mp_do_binary(mp, p,c);
17763       } else { 
17764         mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17765         decr(ref_count(c)); mp_get_x_next(mp); 
17766         goto RESTART;
17767       }
17768       goto CONTINUE;
17769     }
17770   }
17771 }
17772
17773 @ Finally we reach the deepest level in our quartet of parsing routines.
17774 This one is much like the others; but it has an extra complication from
17775 paths, which materialize here.
17776
17777 @d continue_path 25 /* a label inside of |scan_expression| */
17778 @d finish_path 26 /* another */
17779
17780 @<Declare the basic parsing subroutines@>=
17781 void mp_scan_expression (MP mp) {
17782   pointer p,q,r,pp,qq; /* for list manipulation */
17783   halfword c,d; /* operation codes or modifiers */
17784   int my_var_flag; /* initial value of |var_flag| */
17785   pointer mac_name; /* token defined with \&{tertiarydef} */
17786   boolean cycle_hit; /* did a path expression just end with `\&{cycle}'? */
17787   scaled x,y; /* explicit coordinates or tension at a path join */
17788   int t; /* knot type following a path join */
17789   t=0; y=0; x=0;
17790   my_var_flag=mp->var_flag; mac_name=null;
17791 RESTART:
17792   if ((mp->cur_cmd<min_primary_command)||
17793       (mp->cur_cmd>max_primary_command) )
17794     mp_bad_exp(mp, "An");
17795 @.An expression...@>
17796   mp_scan_tertiary(mp);
17797 CONTINUE: 
17798   if ( mp->cur_cmd<=max_expression_command )
17799     if ( mp->cur_cmd>=min_expression_command ) {
17800       if ( (mp->cur_cmd!=equals)||(my_var_flag!=assignment) ) {
17801         p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17802         if ( d==expression_tertiary_macro ) {
17803           mac_name=mp->cur_sym; add_mac_ref(c);
17804         }
17805         if ( (d<ampersand)||((d==ampersand)&&
17806              ((type(p)==mp_pair_type)||(type(p)==mp_path_type))) ) {
17807           @<Scan a path construction operation;
17808             but |return| if |p| has the wrong type@>;
17809         } else { 
17810           mp_get_x_next(mp); mp_scan_tertiary(mp);
17811           if ( d!=expression_tertiary_macro ) {
17812             mp_do_binary(mp, p,c);
17813           } else  { 
17814             mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17815             decr(ref_count(c)); mp_get_x_next(mp); 
17816             goto RESTART;
17817           }
17818         }
17819         goto CONTINUE;
17820      }
17821   }
17822 }
17823
17824 @ The reader should review the data structure conventions for paths before
17825 hoping to understand the next part of this code.
17826
17827 @<Scan a path construction operation...@>=
17828
17829   cycle_hit=false;
17830   @<Convert the left operand, |p|, into a partial path ending at~|q|;
17831     but |return| if |p| doesn't have a suitable type@>;
17832 CONTINUE_PATH: 
17833   @<Determine the path join parameters;
17834     but |goto finish_path| if there's only a direction specifier@>;
17835   if ( mp->cur_cmd==cycle ) {
17836     @<Get ready to close a cycle@>;
17837   } else { 
17838     mp_scan_tertiary(mp);
17839     @<Convert the right operand, |cur_exp|,
17840       into a partial path from |pp| to~|qq|@>;
17841   }
17842   @<Join the partial paths and reset |p| and |q| to the head and tail
17843     of the result@>;
17844   if ( mp->cur_cmd>=min_expression_command )
17845     if ( mp->cur_cmd<=ampersand ) if ( ! cycle_hit ) goto CONTINUE_PATH;
17846 FINISH_PATH:
17847   @<Choose control points for the path and put the result into |cur_exp|@>;
17848 }
17849
17850 @ @<Convert the left operand, |p|, into a partial path ending at~|q|...@>=
17851
17852   mp_unstash_cur_exp(mp, p);
17853   if ( mp->cur_type==mp_pair_type ) p=mp_new_knot(mp);
17854   else if ( mp->cur_type==mp_path_type ) p=mp->cur_exp;
17855   else return;
17856   q=p;
17857   while ( link(q)!=p ) q=link(q);
17858   if ( left_type(p)!=endpoint ) { /* open up a cycle */
17859     r=mp_copy_knot(mp, p); link(q)=r; q=r;
17860   }
17861   left_type(p)=open; right_type(q)=open;
17862 }
17863
17864 @ A pair of numeric values is changed into a knot node for a one-point path
17865 when \MP\ discovers that the pair is part of a path.
17866
17867 @c@<Declare the procedure called |known_pair|@>;
17868 pointer mp_new_knot (MP mp) { /* convert a pair to a knot with two endpoints */
17869   pointer q; /* the new node */
17870   q=mp_get_node(mp, knot_node_size); left_type(q)=endpoint;
17871   right_type(q)=endpoint; originator(q)=metapost_user; link(q)=q;
17872   mp_known_pair(mp); x_coord(q)=mp->cur_x; y_coord(q)=mp->cur_y;
17873   return q;
17874 }
17875
17876 @ The |known_pair| subroutine sets |cur_x| and |cur_y| to the components
17877 of the current expression, assuming that the current expression is a
17878 pair of known numerics. Unknown components are zeroed, and the
17879 current expression is flushed.
17880
17881 @<Declare the procedure called |known_pair|@>=
17882 void mp_known_pair (MP mp) {
17883   pointer p; /* the pair node */
17884   if ( mp->cur_type!=mp_pair_type ) {
17885     exp_err("Undefined coordinates have been replaced by (0,0)");
17886 @.Undefined coordinates...@>
17887     help5("I need x and y numbers for this part of the path.")
17888       ("The value I found (see above) was no good;")
17889       ("so I'll try to keep going by using zero instead.")
17890       ("(Chapter 27 of The METAFONTbook explains that")
17891 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
17892       ("you might want to type `I ??" "?' now.)");
17893     mp_put_get_flush_error(mp, 0); mp->cur_x=0; mp->cur_y=0;
17894   } else { 
17895     p=value(mp->cur_exp);
17896      @<Make sure that both |x| and |y| parts of |p| are known;
17897        copy them into |cur_x| and |cur_y|@>;
17898     mp_flush_cur_exp(mp, 0);
17899   }
17900 }
17901
17902 @ @<Make sure that both |x| and |y| parts of |p| are known...@>=
17903 if ( type(x_part_loc(p))==mp_known ) {
17904   mp->cur_x=value(x_part_loc(p));
17905 } else { 
17906   mp_disp_err(mp, x_part_loc(p),
17907     "Undefined x coordinate has been replaced by 0");
17908 @.Undefined coordinates...@>
17909   help5("I need a `known' x value for this part of the path.")
17910     ("The value I found (see above) was no good;")
17911     ("so I'll try to keep going by using zero instead.")
17912     ("(Chapter 27 of The METAFONTbook explains that")
17913 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
17914     ("you might want to type `I ??" "?' now.)");
17915   mp_put_get_error(mp); mp_recycle_value(mp, x_part_loc(p)); mp->cur_x=0;
17916 }
17917 if ( type(y_part_loc(p))==mp_known ) {
17918   mp->cur_y=value(y_part_loc(p));
17919 } else { 
17920   mp_disp_err(mp, y_part_loc(p),
17921     "Undefined y coordinate has been replaced by 0");
17922   help5("I need a `known' y value for this part of the path.")
17923     ("The value I found (see above) was no good;")
17924     ("so I'll try to keep going by using zero instead.")
17925     ("(Chapter 27 of The METAFONTbook explains that")
17926     ("you might want to type `I ??" "?' now.)");
17927   mp_put_get_error(mp); mp_recycle_value(mp, y_part_loc(p)); mp->cur_y=0;
17928 }
17929
17930 @ At this point |cur_cmd| is either |ampersand|, |left_brace|, or |path_join|.
17931
17932 @<Determine the path join parameters...@>=
17933 if ( mp->cur_cmd==left_brace ) {
17934   @<Put the pre-join direction information into node |q|@>;
17935 }
17936 d=mp->cur_cmd;
17937 if ( d==path_join ) {
17938   @<Determine the tension and/or control points@>;
17939 } else if ( d!=ampersand ) {
17940   goto FINISH_PATH;
17941 }
17942 mp_get_x_next(mp);
17943 if ( mp->cur_cmd==left_brace ) {
17944   @<Put the post-join direction information into |x| and |t|@>;
17945 } else if ( right_type(q)!=explicit ) {
17946   t=open; x=0;
17947 }
17948
17949 @ The |scan_direction| subroutine looks at the directional information
17950 that is enclosed in braces, and also scans ahead to the following character.
17951 A type code is returned, either |open| (if the direction was $(0,0)$),
17952 or |curl| (if the direction was a curl of known value |cur_exp|), or
17953 |given| (if the direction is given by the |angle| value that now
17954 appears in |cur_exp|).
17955
17956 There's nothing difficult about this subroutine, but the program is rather
17957 lengthy because a variety of potential errors need to be nipped in the bud.
17958
17959 @c small_number mp_scan_direction (MP mp) {
17960   int t; /* the type of information found */
17961   scaled x; /* an |x| coordinate */
17962   mp_get_x_next(mp);
17963   if ( mp->cur_cmd==curl_command ) {
17964      @<Scan a curl specification@>;
17965   } else {
17966     @<Scan a given direction@>;
17967   }
17968   if ( mp->cur_cmd!=right_brace ) {
17969     mp_missing_err(mp, "}");
17970 @.Missing `\char`\}'@>
17971     help3("I've scanned a direction spec for part of a path,")
17972       ("so a right brace should have come next.")
17973       ("I shall pretend that one was there.");
17974     mp_back_error(mp);
17975   }
17976   mp_get_x_next(mp); 
17977   return t;
17978 }
17979
17980 @ @<Scan a curl specification@>=
17981 { mp_get_x_next(mp); mp_scan_expression(mp);
17982 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<0) ){ 
17983   exp_err("Improper curl has been replaced by 1");
17984 @.Improper curl@>
17985   help1("A curl must be a known, nonnegative number.");
17986   mp_put_get_flush_error(mp, unity);
17987 }
17988 t=curl;
17989 }
17990
17991 @ @<Scan a given direction@>=
17992 { mp_scan_expression(mp);
17993   if ( mp->cur_type>mp_pair_type ) {
17994     @<Get given directions separated by commas@>;
17995   } else {
17996     mp_known_pair(mp);
17997   }
17998   if ( (mp->cur_x==0)&&(mp->cur_y==0) )  t=open;
17999   else  { t=given; mp->cur_exp=mp_n_arg(mp, mp->cur_x,mp->cur_y);}
18000 }
18001
18002 @ @<Get given directions separated by commas@>=
18003
18004   if ( mp->cur_type!=mp_known ) {
18005     exp_err("Undefined x coordinate has been replaced by 0");
18006 @.Undefined coordinates...@>
18007     help5("I need a `known' x value for this part of the path.")
18008       ("The value I found (see above) was no good;")
18009       ("so I'll try to keep going by using zero instead.")
18010       ("(Chapter 27 of The METAFONTbook explains that")
18011 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18012       ("you might want to type `I ??" "?' now.)");
18013     mp_put_get_flush_error(mp, 0);
18014   }
18015   x=mp->cur_exp;
18016   if ( mp->cur_cmd!=comma ) {
18017     mp_missing_err(mp, ",");
18018 @.Missing `,'@>
18019     help2("I've got the x coordinate of a path direction;")
18020       ("will look for the y coordinate next.");
18021     mp_back_error(mp);
18022   }
18023   mp_get_x_next(mp); mp_scan_expression(mp);
18024   if ( mp->cur_type!=mp_known ) {
18025      exp_err("Undefined y coordinate has been replaced by 0");
18026     help5("I need a `known' y value for this part of the path.")
18027       ("The value I found (see above) was no good;")
18028       ("so I'll try to keep going by using zero instead.")
18029       ("(Chapter 27 of The METAFONTbook explains that")
18030       ("you might want to type `I ??" "?' now.)");
18031     mp_put_get_flush_error(mp, 0);
18032   }
18033   mp->cur_y=mp->cur_exp; mp->cur_x=x;
18034 }
18035
18036 @ At this point |right_type(q)| is usually |open|, but it may have been
18037 set to some other value by a previous splicing operation. We must maintain
18038 the value of |right_type(q)| in unusual cases such as
18039 `\.{..z1\{z2\}\&\{z3\}z1\{0,0\}..}'.
18040
18041 @<Put the pre-join...@>=
18042
18043   t=mp_scan_direction(mp);
18044   if ( t!=open ) {
18045     right_type(q)=t; right_given(q)=mp->cur_exp;
18046     if ( left_type(q)==open ) {
18047       left_type(q)=t; left_given(q)=mp->cur_exp;
18048     } /* note that |left_given(q)=left_curl(q)| */
18049   }
18050 }
18051
18052 @ Since |left_tension| and |left_y| share the same position in knot nodes,
18053 and since |left_given| is similarly equivalent to |left_x|, we use
18054 |x| and |y| to hold the given direction and tension information when
18055 there are no explicit control points.
18056
18057 @<Put the post-join...@>=
18058
18059   t=mp_scan_direction(mp);
18060   if ( right_type(q)!=explicit ) x=mp->cur_exp;
18061   else t=explicit; /* the direction information is superfluous */
18062 }
18063
18064 @ @<Determine the tension and/or...@>=
18065
18066   mp_get_x_next(mp);
18067   if ( mp->cur_cmd==tension ) {
18068     @<Set explicit tensions@>;
18069   } else if ( mp->cur_cmd==controls ) {
18070     @<Set explicit control points@>;
18071   } else  { 
18072     right_tension(q)=unity; y=unity; mp_back_input(mp); /* default tension */
18073     goto DONE;
18074   };
18075   if ( mp->cur_cmd!=path_join ) {
18076      mp_missing_err(mp, "..");
18077 @.Missing `..'@>
18078     help1("A path join command should end with two dots.");
18079     mp_back_error(mp);
18080   }
18081 DONE:
18082   ;
18083 }
18084
18085 @ @<Set explicit tensions@>=
18086
18087   mp_get_x_next(mp); y=mp->cur_cmd;
18088   if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18089   mp_scan_primary(mp);
18090   @<Make sure that the current expression is a valid tension setting@>;
18091   if ( y==at_least ) negate(mp->cur_exp);
18092   right_tension(q)=mp->cur_exp;
18093   if ( mp->cur_cmd==and_command ) {
18094     mp_get_x_next(mp); y=mp->cur_cmd;
18095     if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18096     mp_scan_primary(mp);
18097     @<Make sure that the current expression is a valid tension setting@>;
18098     if ( y==at_least ) negate(mp->cur_exp);
18099   }
18100   y=mp->cur_exp;
18101 }
18102
18103 @ @d min_tension three_quarter_unit
18104
18105 @<Make sure that the current expression is a valid tension setting@>=
18106 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<min_tension) ) {
18107   exp_err("Improper tension has been set to 1");
18108 @.Improper tension@>
18109   help1("The expression above should have been a number >=3/4.");
18110   mp_put_get_flush_error(mp, unity);
18111 }
18112
18113 @ @<Set explicit control points@>=
18114
18115   right_type(q)=explicit; t=explicit; mp_get_x_next(mp); mp_scan_primary(mp);
18116   mp_known_pair(mp); right_x(q)=mp->cur_x; right_y(q)=mp->cur_y;
18117   if ( mp->cur_cmd!=and_command ) {
18118     x=right_x(q); y=right_y(q);
18119   } else { 
18120     mp_get_x_next(mp); mp_scan_primary(mp);
18121     mp_known_pair(mp); x=mp->cur_x; y=mp->cur_y;
18122   }
18123 }
18124
18125 @ @<Convert the right operand, |cur_exp|, into a partial path...@>=
18126
18127   if ( mp->cur_type!=mp_path_type ) pp=mp_new_knot(mp);
18128   else pp=mp->cur_exp;
18129   qq=pp;
18130   while ( link(qq)!=pp ) qq=link(qq);
18131   if ( left_type(pp)!=endpoint ) { /* open up a cycle */
18132     r=mp_copy_knot(mp, pp); link(qq)=r; qq=r;
18133   }
18134   left_type(pp)=open; right_type(qq)=open;
18135 }
18136
18137 @ If a person tries to define an entire path by saying `\.{(x,y)\&cycle}',
18138 we silently change the specification to `\.{(x,y)..cycle}', since a cycle
18139 shouldn't have length zero.
18140
18141 @<Get ready to close a cycle@>=
18142
18143   cycle_hit=true; mp_get_x_next(mp); pp=p; qq=p;
18144   if ( d==ampersand ) if ( p==q ) {
18145     d=path_join; right_tension(q)=unity; y=unity;
18146   }
18147 }
18148
18149 @ @<Join the partial paths and reset |p| and |q|...@>=
18150
18151 if ( d==ampersand ) {
18152   if ( (x_coord(q)!=x_coord(pp))||(y_coord(q)!=y_coord(pp)) ) {
18153     print_err("Paths don't touch; `&' will be changed to `..'");
18154 @.Paths don't touch@>
18155     help3("When you join paths `p&q', the ending point of p")
18156       ("must be exactly equal to the starting point of q.")
18157       ("So I'm going to pretend that you said `p..q' instead.");
18158     mp_put_get_error(mp); d=path_join; right_tension(q)=unity; y=unity;
18159   }
18160 }
18161 @<Plug an opening in |right_type(pp)|, if possible@>;
18162 if ( d==ampersand ) {
18163   @<Splice independent paths together@>;
18164 } else  { 
18165   @<Plug an opening in |right_type(q)|, if possible@>;
18166   link(q)=pp; left_y(pp)=y;
18167   if ( t!=open ) { left_x(pp)=x; left_type(pp)=t;  };
18168 }
18169 q=qq;
18170 }
18171
18172 @ @<Plug an opening in |right_type(q)|...@>=
18173 if ( right_type(q)==open ) {
18174   if ( (left_type(q)==curl)||(left_type(q)==given) ) {
18175     right_type(q)=left_type(q); right_given(q)=left_given(q);
18176   }
18177 }
18178
18179 @ @<Plug an opening in |right_type(pp)|...@>=
18180 if ( right_type(pp)==open ) {
18181   if ( (t==curl)||(t==given) ) {
18182     right_type(pp)=t; right_given(pp)=x;
18183   }
18184 }
18185
18186 @ @<Splice independent paths together@>=
18187
18188   if ( left_type(q)==open ) if ( right_type(q)==open ) {
18189     left_type(q)=curl; left_curl(q)=unity;
18190   }
18191   if ( right_type(pp)==open ) if ( t==open ) {
18192     right_type(pp)=curl; right_curl(pp)=unity;
18193   }
18194   right_type(q)=right_type(pp); link(q)=link(pp);
18195   right_x(q)=right_x(pp); right_y(q)=right_y(pp);
18196   mp_free_node(mp, pp,knot_node_size);
18197   if ( qq==pp ) qq=q;
18198 }
18199
18200 @ @<Choose control points for the path...@>=
18201 if ( cycle_hit ) { 
18202   if ( d==ampersand ) p=q;
18203 } else  { 
18204   left_type(p)=endpoint;
18205   if ( right_type(p)==open ) { 
18206     right_type(p)=curl; right_curl(p)=unity;
18207   }
18208   right_type(q)=endpoint;
18209   if ( left_type(q)==open ) { 
18210     left_type(q)=curl; left_curl(q)=unity;
18211   }
18212   link(q)=p;
18213 }
18214 mp_make_choices(mp, p);
18215 mp->cur_type=mp_path_type; mp->cur_exp=p
18216
18217 @ Finally, we sometimes need to scan an expression whose value is
18218 supposed to be either |true_code| or |false_code|.
18219
18220 @<Declare the basic parsing subroutines@>=
18221 void mp_get_boolean (MP mp) { 
18222   mp_get_x_next(mp); mp_scan_expression(mp);
18223   if ( mp->cur_type!=mp_boolean_type ) {
18224     exp_err("Undefined condition will be treated as `false'");
18225 @.Undefined condition...@>
18226     help2("The expression shown above should have had a definite")
18227       ("true-or-false value. I'm changing it to `false'.");
18228     mp_put_get_flush_error(mp, false_code); mp->cur_type=mp_boolean_type;
18229   }
18230 }
18231
18232 @* \[39] Doing the operations.
18233 The purpose of parsing is primarily to permit people to avoid piles of
18234 parentheses. But the real work is done after the structure of an expression
18235 has been recognized; that's when new expressions are generated. We
18236 turn now to the guts of \MP, which handles individual operators that
18237 have come through the parsing mechanism.
18238
18239 We'll start with the easy ones that take no operands, then work our way
18240 up to operators with one and ultimately two arguments. In other words,
18241 we will write the three procedures |do_nullary|, |do_unary|, and |do_binary|
18242 that are invoked periodically by the expression scanners.
18243
18244 First let's make sure that all of the primitive operators are in the
18245 hash table. Although |scan_primary| and its relatives made use of the
18246 \\{cmd} code for these operators, the \\{do} routines base everything
18247 on the \\{mod} code. For example, |do_binary| doesn't care whether the
18248 operation it performs is a |primary_binary| or |secondary_binary|, etc.
18249
18250 @<Put each...@>=
18251 mp_primitive(mp, "true",nullary,true_code);
18252 @:true_}{\&{true} primitive@>
18253 mp_primitive(mp, "false",nullary,false_code);
18254 @:false_}{\&{false} primitive@>
18255 mp_primitive(mp, "nullpicture",nullary,null_picture_code);
18256 @:null_picture_}{\&{nullpicture} primitive@>
18257 mp_primitive(mp, "nullpen",nullary,null_pen_code);
18258 @:null_pen_}{\&{nullpen} primitive@>
18259 mp_primitive(mp, "jobname",nullary,job_name_op);
18260 @:job_name_}{\&{jobname} primitive@>
18261 mp_primitive(mp, "readstring",nullary,read_string_op);
18262 @:read_string_}{\&{readstring} primitive@>
18263 mp_primitive(mp, "pencircle",nullary,pen_circle);
18264 @:pen_circle_}{\&{pencircle} primitive@>
18265 mp_primitive(mp, "normaldeviate",nullary,normal_deviate);
18266 @:normal_deviate_}{\&{normaldeviate} primitive@>
18267 mp_primitive(mp, "readfrom",unary,read_from_op);
18268 @:read_from_}{\&{readfrom} primitive@>
18269 mp_primitive(mp, "closefrom",unary,close_from_op);
18270 @:close_from_}{\&{closefrom} primitive@>
18271 mp_primitive(mp, "odd",unary,odd_op);
18272 @:odd_}{\&{odd} primitive@>
18273 mp_primitive(mp, "known",unary,known_op);
18274 @:known_}{\&{known} primitive@>
18275 mp_primitive(mp, "unknown",unary,unknown_op);
18276 @:unknown_}{\&{unknown} primitive@>
18277 mp_primitive(mp, "not",unary,not_op);
18278 @:not_}{\&{not} primitive@>
18279 mp_primitive(mp, "decimal",unary,decimal);
18280 @:decimal_}{\&{decimal} primitive@>
18281 mp_primitive(mp, "reverse",unary,reverse);
18282 @:reverse_}{\&{reverse} primitive@>
18283 mp_primitive(mp, "makepath",unary,make_path_op);
18284 @:make_path_}{\&{makepath} primitive@>
18285 mp_primitive(mp, "makepen",unary,make_pen_op);
18286 @:make_pen_}{\&{makepen} primitive@>
18287 mp_primitive(mp, "oct",unary,oct_op);
18288 @:oct_}{\&{oct} primitive@>
18289 mp_primitive(mp, "hex",unary,hex_op);
18290 @:hex_}{\&{hex} primitive@>
18291 mp_primitive(mp, "ASCII",unary,ASCII_op);
18292 @:ASCII_}{\&{ASCII} primitive@>
18293 mp_primitive(mp, "char",unary,char_op);
18294 @:char_}{\&{char} primitive@>
18295 mp_primitive(mp, "length",unary,length_op);
18296 @:length_}{\&{length} primitive@>
18297 mp_primitive(mp, "turningnumber",unary,turning_op);
18298 @:turning_number_}{\&{turningnumber} primitive@>
18299 mp_primitive(mp, "xpart",unary,x_part);
18300 @:x_part_}{\&{xpart} primitive@>
18301 mp_primitive(mp, "ypart",unary,y_part);
18302 @:y_part_}{\&{ypart} primitive@>
18303 mp_primitive(mp, "xxpart",unary,xx_part);
18304 @:xx_part_}{\&{xxpart} primitive@>
18305 mp_primitive(mp, "xypart",unary,xy_part);
18306 @:xy_part_}{\&{xypart} primitive@>
18307 mp_primitive(mp, "yxpart",unary,yx_part);
18308 @:yx_part_}{\&{yxpart} primitive@>
18309 mp_primitive(mp, "yypart",unary,yy_part);
18310 @:yy_part_}{\&{yypart} primitive@>
18311 mp_primitive(mp, "redpart",unary,red_part);
18312 @:red_part_}{\&{redpart} primitive@>
18313 mp_primitive(mp, "greenpart",unary,green_part);
18314 @:green_part_}{\&{greenpart} primitive@>
18315 mp_primitive(mp, "bluepart",unary,blue_part);
18316 @:blue_part_}{\&{bluepart} primitive@>
18317 mp_primitive(mp, "cyanpart",unary,cyan_part);
18318 @:cyan_part_}{\&{cyanpart} primitive@>
18319 mp_primitive(mp, "magentapart",unary,magenta_part);
18320 @:magenta_part_}{\&{magentapart} primitive@>
18321 mp_primitive(mp, "yellowpart",unary,yellow_part);
18322 @:yellow_part_}{\&{yellowpart} primitive@>
18323 mp_primitive(mp, "blackpart",unary,black_part);
18324 @:black_part_}{\&{blackpart} primitive@>
18325 mp_primitive(mp, "greypart",unary,grey_part);
18326 @:grey_part_}{\&{greypart} primitive@>
18327 mp_primitive(mp, "colormodel",unary,color_model_part);
18328 @:color_model_part_}{\&{colormodel} primitive@>
18329 mp_primitive(mp, "fontpart",unary,font_part);
18330 @:font_part_}{\&{fontpart} primitive@>
18331 mp_primitive(mp, "textpart",unary,text_part);
18332 @:text_part_}{\&{textpart} primitive@>
18333 mp_primitive(mp, "pathpart",unary,path_part);
18334 @:path_part_}{\&{pathpart} primitive@>
18335 mp_primitive(mp, "penpart",unary,pen_part);
18336 @:pen_part_}{\&{penpart} primitive@>
18337 mp_primitive(mp, "dashpart",unary,dash_part);
18338 @:dash_part_}{\&{dashpart} primitive@>
18339 mp_primitive(mp, "sqrt",unary,sqrt_op);
18340 @:sqrt_}{\&{sqrt} primitive@>
18341 mp_primitive(mp, "mexp",unary,m_exp_op);
18342 @:m_exp_}{\&{mexp} primitive@>
18343 mp_primitive(mp, "mlog",unary,m_log_op);
18344 @:m_log_}{\&{mlog} primitive@>
18345 mp_primitive(mp, "sind",unary,sin_d_op);
18346 @:sin_d_}{\&{sind} primitive@>
18347 mp_primitive(mp, "cosd",unary,cos_d_op);
18348 @:cos_d_}{\&{cosd} primitive@>
18349 mp_primitive(mp, "floor",unary,floor_op);
18350 @:floor_}{\&{floor} primitive@>
18351 mp_primitive(mp, "uniformdeviate",unary,uniform_deviate);
18352 @:uniform_deviate_}{\&{uniformdeviate} primitive@>
18353 mp_primitive(mp, "charexists",unary,char_exists_op);
18354 @:char_exists_}{\&{charexists} primitive@>
18355 mp_primitive(mp, "fontsize",unary,font_size);
18356 @:font_size_}{\&{fontsize} primitive@>
18357 mp_primitive(mp, "llcorner",unary,ll_corner_op);
18358 @:ll_corner_}{\&{llcorner} primitive@>
18359 mp_primitive(mp, "lrcorner",unary,lr_corner_op);
18360 @:lr_corner_}{\&{lrcorner} primitive@>
18361 mp_primitive(mp, "ulcorner",unary,ul_corner_op);
18362 @:ul_corner_}{\&{ulcorner} primitive@>
18363 mp_primitive(mp, "urcorner",unary,ur_corner_op);
18364 @:ur_corner_}{\&{urcorner} primitive@>
18365 mp_primitive(mp, "arclength",unary,arc_length);
18366 @:arc_length_}{\&{arclength} primitive@>
18367 mp_primitive(mp, "angle",unary,angle_op);
18368 @:angle_}{\&{angle} primitive@>
18369 mp_primitive(mp, "cycle",cycle,cycle_op);
18370 @:cycle_}{\&{cycle} primitive@>
18371 mp_primitive(mp, "stroked",unary,stroked_op);
18372 @:stroked_}{\&{stroked} primitive@>
18373 mp_primitive(mp, "filled",unary,filled_op);
18374 @:filled_}{\&{filled} primitive@>
18375 mp_primitive(mp, "textual",unary,textual_op);
18376 @:textual_}{\&{textual} primitive@>
18377 mp_primitive(mp, "clipped",unary,clipped_op);
18378 @:clipped_}{\&{clipped} primitive@>
18379 mp_primitive(mp, "bounded",unary,bounded_op);
18380 @:bounded_}{\&{bounded} primitive@>
18381 mp_primitive(mp, "+",plus_or_minus,plus);
18382 @:+ }{\.{+} primitive@>
18383 mp_primitive(mp, "-",plus_or_minus,minus);
18384 @:- }{\.{-} primitive@>
18385 mp_primitive(mp, "*",secondary_binary,times);
18386 @:* }{\.{*} primitive@>
18387 mp_primitive(mp, "/",slash,over); mp->eqtb[frozen_slash]=mp->eqtb[mp->cur_sym];
18388 @:/ }{\.{/} primitive@>
18389 mp_primitive(mp, "++",tertiary_binary,pythag_add);
18390 @:++_}{\.{++} primitive@>
18391 mp_primitive(mp, "+-+",tertiary_binary,pythag_sub);
18392 @:+-+_}{\.{+-+} primitive@>
18393 mp_primitive(mp, "or",tertiary_binary,or_op);
18394 @:or_}{\&{or} primitive@>
18395 mp_primitive(mp, "and",and_command,and_op);
18396 @:and_}{\&{and} primitive@>
18397 mp_primitive(mp, "<",expression_binary,less_than);
18398 @:< }{\.{<} primitive@>
18399 mp_primitive(mp, "<=",expression_binary,less_or_equal);
18400 @:<=_}{\.{<=} primitive@>
18401 mp_primitive(mp, ">",expression_binary,greater_than);
18402 @:> }{\.{>} primitive@>
18403 mp_primitive(mp, ">=",expression_binary,greater_or_equal);
18404 @:>=_}{\.{>=} primitive@>
18405 mp_primitive(mp, "=",equals,equal_to);
18406 @:= }{\.{=} primitive@>
18407 mp_primitive(mp, "<>",expression_binary,unequal_to);
18408 @:<>_}{\.{<>} primitive@>
18409 mp_primitive(mp, "substring",primary_binary,substring_of);
18410 @:substring_}{\&{substring} primitive@>
18411 mp_primitive(mp, "subpath",primary_binary,subpath_of);
18412 @:subpath_}{\&{subpath} primitive@>
18413 mp_primitive(mp, "directiontime",primary_binary,direction_time_of);
18414 @:direction_time_}{\&{directiontime} primitive@>
18415 mp_primitive(mp, "point",primary_binary,point_of);
18416 @:point_}{\&{point} primitive@>
18417 mp_primitive(mp, "precontrol",primary_binary,precontrol_of);
18418 @:precontrol_}{\&{precontrol} primitive@>
18419 mp_primitive(mp, "postcontrol",primary_binary,postcontrol_of);
18420 @:postcontrol_}{\&{postcontrol} primitive@>
18421 mp_primitive(mp, "penoffset",primary_binary,pen_offset_of);
18422 @:pen_offset_}{\&{penoffset} primitive@>
18423 mp_primitive(mp, "arctime",primary_binary,arc_time_of);
18424 @:arc_time_of_}{\&{arctime} primitive@>
18425 mp_primitive(mp, "mpversion",nullary,mp_version);
18426 @:mp_verison_}{\&{mpversion} primitive@>
18427 mp_primitive(mp, "&",ampersand,concatenate);
18428 @:!!!}{\.{\&} primitive@>
18429 mp_primitive(mp, "rotated",secondary_binary,rotated_by);
18430 @:rotated_}{\&{rotated} primitive@>
18431 mp_primitive(mp, "slanted",secondary_binary,slanted_by);
18432 @:slanted_}{\&{slanted} primitive@>
18433 mp_primitive(mp, "scaled",secondary_binary,scaled_by);
18434 @:scaled_}{\&{scaled} primitive@>
18435 mp_primitive(mp, "shifted",secondary_binary,shifted_by);
18436 @:shifted_}{\&{shifted} primitive@>
18437 mp_primitive(mp, "transformed",secondary_binary,transformed_by);
18438 @:transformed_}{\&{transformed} primitive@>
18439 mp_primitive(mp, "xscaled",secondary_binary,x_scaled);
18440 @:x_scaled_}{\&{xscaled} primitive@>
18441 mp_primitive(mp, "yscaled",secondary_binary,y_scaled);
18442 @:y_scaled_}{\&{yscaled} primitive@>
18443 mp_primitive(mp, "zscaled",secondary_binary,z_scaled);
18444 @:z_scaled_}{\&{zscaled} primitive@>
18445 mp_primitive(mp, "infont",secondary_binary,in_font);
18446 @:in_font_}{\&{infont} primitive@>
18447 mp_primitive(mp, "intersectiontimes",tertiary_binary,intersect);
18448 @:intersection_times_}{\&{intersectiontimes} primitive@>
18449
18450 @ @<Cases of |print_cmd...@>=
18451 case nullary:
18452 case unary:
18453 case primary_binary:
18454 case secondary_binary:
18455 case tertiary_binary:
18456 case expression_binary:
18457 case cycle:
18458 case plus_or_minus:
18459 case slash:
18460 case ampersand:
18461 case equals:
18462 case and_command:
18463   mp_print_op(mp, m);
18464   break;
18465
18466 @ OK, let's look at the simplest \\{do} procedure first.
18467
18468 @c @<Declare nullary action procedure@>;
18469 void mp_do_nullary (MP mp,quarterword c) { 
18470   check_arith;
18471   if ( mp->internal[tracing_commands]>two )
18472     mp_show_cmd_mod(mp, nullary,c);
18473   switch (c) {
18474   case true_code: case false_code: 
18475     mp->cur_type=mp_boolean_type; mp->cur_exp=c;
18476     break;
18477   case null_picture_code: 
18478     mp->cur_type=mp_picture_type;
18479     mp->cur_exp=mp_get_node(mp, edge_header_size); 
18480     mp_init_edges(mp, mp->cur_exp);
18481     break;
18482   case null_pen_code: 
18483     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, 0);
18484     break;
18485   case normal_deviate: 
18486     mp->cur_type=mp_known; mp->cur_exp=mp_norm_rand(mp);
18487     break;
18488   case pen_circle: 
18489     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, unity);
18490     break;
18491   case job_name_op:  
18492     if ( mp->job_name==NULL ) mp_open_log_file(mp);
18493     mp->cur_type=mp_string_type; mp->cur_exp=rts(mp->job_name);
18494     break;
18495   case mp_version: 
18496     mp->cur_type=mp_string_type; 
18497     mp->cur_exp=intern(metapost_version) ;
18498     break;
18499   case read_string_op:
18500     @<Read a string from the terminal@>;
18501     break;
18502   } /* there are no other cases */
18503   check_arith;
18504 }
18505
18506 @ @<Read a string...@>=
18507
18508   if ( mp->interaction<=mp_nonstop_mode )
18509     mp_fatal_error(mp, "*** (cannot readstring in nonstop modes)");
18510   mp_begin_file_reading(mp); name=is_read;
18511   limit=start; prompt_input("");
18512   mp_finish_read(mp);
18513 }
18514
18515 @ @<Declare nullary action procedure@>=
18516 void mp_finish_read (MP mp) { /* copy |buffer| line to |cur_exp| */
18517   size_t k;
18518   str_room((int)mp->last-start);
18519   for (k=start;k<=mp->last-1;k++) {
18520    append_char(mp->buffer[k]);
18521   }
18522   mp_end_file_reading(mp); mp->cur_type=mp_string_type; 
18523   mp->cur_exp=mp_make_string(mp);
18524 }
18525
18526 @ Things get a bit more interesting when there's an operand. The
18527 operand to |do_unary| appears in |cur_type| and |cur_exp|.
18528
18529 @c @<Declare unary action procedures@>;
18530 void mp_do_unary (MP mp,quarterword c) {
18531   pointer p,q,r; /* for list manipulation */
18532   integer x; /* a temporary register */
18533   check_arith;
18534   if ( mp->internal[tracing_commands]>two )
18535     @<Trace the current unary operation@>;
18536   switch (c) {
18537   case plus:
18538     if ( mp->cur_type<mp_color_type ) mp_bad_unary(mp, plus);
18539     break;
18540   case minus:
18541     @<Negate the current expression@>;
18542     break;
18543   @<Additional cases of unary operators@>;
18544   } /* there are no other cases */
18545   check_arith;
18546 };
18547
18548 @ The |nice_pair| function returns |true| if both components of a pair
18549 are known.
18550
18551 @<Declare unary action procedures@>=
18552 boolean mp_nice_pair (MP mp,integer p, quarterword t) { 
18553   if ( t==mp_pair_type ) {
18554     p=value(p);
18555     if ( type(x_part_loc(p))==mp_known )
18556       if ( type(y_part_loc(p))==mp_known )
18557         return true;
18558   }
18559   return false;
18560 }
18561
18562 @ The |nice_color_or_pair| function is analogous except that it also accepts
18563 fully known colors.
18564
18565 @<Declare unary action procedures@>=
18566 boolean mp_nice_color_or_pair (MP mp,integer p, quarterword t) {
18567   pointer q,r; /* for scanning the big node */
18568   if ( (t!=mp_pair_type)&&(t!=mp_color_type)&&(t!=mp_cmykcolor_type) ) {
18569     return false;
18570   } else { 
18571     q=value(p);
18572     r=q+mp->big_node_size[type(p)];
18573     do {  
18574       r=r-2;
18575       if ( type(r)!=mp_known )
18576         return false;
18577     } while (r!=q);
18578     return true;
18579   }
18580 }
18581
18582 @ @<Declare unary action...@>=
18583 void mp_print_known_or_unknown_type (MP mp,small_number t, integer v) { 
18584   mp_print_char(mp, '(');
18585   if ( t>mp_known ) mp_print(mp, "unknown numeric");
18586   else { if ( (t==mp_pair_type)||(t==mp_color_type)||(t==mp_cmykcolor_type) )
18587     if ( ! mp_nice_color_or_pair(mp, v,t) ) mp_print(mp, "unknown ");
18588     mp_print_type(mp, t);
18589   }
18590   mp_print_char(mp, ')');
18591 }
18592
18593 @ @<Declare unary action...@>=
18594 void mp_bad_unary (MP mp,quarterword c) { 
18595   exp_err("Not implemented: "); mp_print_op(mp, c);
18596 @.Not implemented...@>
18597   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
18598   help3("I'm afraid I don't know how to apply that operation to that")
18599     ("particular type. Continue, and I'll simply return the")
18600     ("argument (shown above) as the result of the operation.");
18601   mp_put_get_error(mp);
18602 }
18603
18604 @ @<Trace the current unary operation@>=
18605
18606   mp_begin_diagnostic(mp); mp_print_nl(mp, "{"); 
18607   mp_print_op(mp, c); mp_print_char(mp, '(');
18608   mp_print_exp(mp, null,0); /* show the operand, but not verbosely */
18609   mp_print(mp, ")}"); mp_end_diagnostic(mp, false);
18610 }
18611
18612 @ Negation is easy except when the current expression
18613 is of type |independent|, or when it is a pair with one or more
18614 |independent| components.
18615
18616 It is tempting to argue that the negative of an independent variable
18617 is an independent variable, hence we don't have to do anything when
18618 negating it. The fallacy is that other dependent variables pointing
18619 to the current expression must change the sign of their
18620 coefficients if we make no change to the current expression.
18621
18622 Instead, we work around the problem by copying the current expression
18623 and recycling it afterwards (cf.~the |stash_in| routine).
18624
18625 @<Negate the current expression@>=
18626 switch (mp->cur_type) {
18627 case mp_color_type:
18628 case mp_cmykcolor_type:
18629 case mp_pair_type:
18630 case mp_independent: 
18631   q=mp->cur_exp; mp_make_exp_copy(mp, q);
18632   if ( mp->cur_type==mp_dependent ) {
18633     mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18634   } else if ( mp->cur_type<=mp_pair_type ) { /* |mp_color_type| or |mp_pair_type| */
18635     p=value(mp->cur_exp);
18636     r=p+mp->big_node_size[mp->cur_type];
18637     do {  
18638       r=r-2;
18639       if ( type(r)==mp_known ) negate(value(r));
18640       else mp_negate_dep_list(mp, dep_list(r));
18641     } while (r!=p);
18642   } /* if |cur_type=mp_known| then |cur_exp=0| */
18643   mp_recycle_value(mp, q); mp_free_node(mp, q,value_node_size);
18644   break;
18645 case mp_dependent:
18646 case mp_proto_dependent:
18647   mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18648   break;
18649 case mp_known:
18650   negate(mp->cur_exp);
18651   break;
18652 default:
18653   mp_bad_unary(mp, minus);
18654   break;
18655 }
18656
18657 @ @<Declare unary action...@>=
18658 void mp_negate_dep_list (MP mp,pointer p) { 
18659   while (1) { 
18660     negate(value(p));
18661     if ( info(p)==null ) return;
18662     p=link(p);
18663   }
18664 }
18665
18666 @ @<Additional cases of unary operators@>=
18667 case not_op: 
18668   if ( mp->cur_type!=mp_boolean_type ) mp_bad_unary(mp, not_op);
18669   else mp->cur_exp=true_code+false_code-mp->cur_exp;
18670   break;
18671
18672 @ @d three_sixty_units 23592960 /* that's |360*unity| */
18673 @d boolean_reset(A) if ( (A) ) mp->cur_exp=true_code; else mp->cur_exp=false_code
18674
18675 @<Additional cases of unary operators@>=
18676 case sqrt_op:
18677 case m_exp_op:
18678 case m_log_op:
18679 case sin_d_op:
18680 case cos_d_op:
18681 case floor_op:
18682 case  uniform_deviate:
18683 case odd_op:
18684 case char_exists_op:
18685   if ( mp->cur_type!=mp_known ) {
18686     mp_bad_unary(mp, c);
18687   } else {
18688     switch (c) {
18689     case sqrt_op:mp->cur_exp=mp_square_rt(mp, mp->cur_exp);break;
18690     case m_exp_op:mp->cur_exp=mp_m_exp(mp, mp->cur_exp);break;
18691     case m_log_op:mp->cur_exp=mp_m_log(mp, mp->cur_exp);break;
18692     case sin_d_op:
18693     case cos_d_op:
18694       mp_n_sin_cos(mp, (mp->cur_exp % three_sixty_units)*16);
18695       if ( c==sin_d_op ) mp->cur_exp=mp_round_fraction(mp, mp->n_sin);
18696       else mp->cur_exp=mp_round_fraction(mp, mp->n_cos);
18697       break;
18698     case floor_op:mp->cur_exp=mp_floor_scaled(mp, mp->cur_exp);break;
18699     case uniform_deviate:mp->cur_exp=mp_unif_rand(mp, mp->cur_exp);break;
18700     case odd_op: 
18701       boolean_reset(odd(mp_round_unscaled(mp, mp->cur_exp)));
18702       mp->cur_type=mp_boolean_type;
18703       break;
18704     case char_exists_op:
18705       @<Determine if a character has been shipped out@>;
18706       break;
18707     } /* there are no other cases */
18708   }
18709   break;
18710
18711 @ @<Additional cases of unary operators@>=
18712 case angle_op:
18713   if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) ) {
18714     p=value(mp->cur_exp);
18715     x=mp_n_arg(mp, value(x_part_loc(p)),value(y_part_loc(p)));
18716     if ( x>=0 ) mp_flush_cur_exp(mp, (x+8)/ 16);
18717     else mp_flush_cur_exp(mp, -((-x+8)/ 16));
18718   } else {
18719     mp_bad_unary(mp, angle_op);
18720   }
18721   break;
18722
18723 @ If the current expression is a pair, but the context wants it to
18724 be a path, we call |pair_to_path|.
18725
18726 @<Declare unary action...@>=
18727 void mp_pair_to_path (MP mp) { 
18728   mp->cur_exp=mp_new_knot(mp); 
18729   mp->cur_type=mp_path_type;
18730 };
18731
18732 @ @<Additional cases of unary operators@>=
18733 case x_part:
18734 case y_part:
18735   if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_transform_type) )
18736     mp_take_part(mp, c);
18737   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18738   else mp_bad_unary(mp, c);
18739   break;
18740 case xx_part:
18741 case xy_part:
18742 case yx_part:
18743 case yy_part: 
18744   if ( mp->cur_type==mp_transform_type ) mp_take_part(mp, c);
18745   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18746   else mp_bad_unary(mp, c);
18747   break;
18748 case red_part:
18749 case green_part:
18750 case blue_part: 
18751   if ( mp->cur_type==mp_color_type ) mp_take_part(mp, c);
18752   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18753   else mp_bad_unary(mp, c);
18754   break;
18755 case cyan_part:
18756 case magenta_part:
18757 case yellow_part:
18758 case black_part: 
18759   if ( mp->cur_type==mp_cmykcolor_type) mp_take_part(mp, c); 
18760   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18761   else mp_bad_unary(mp, c);
18762   break;
18763 case grey_part: 
18764   if ( mp->cur_type==mp_known ) mp->cur_exp=value(c);
18765   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18766   else mp_bad_unary(mp, c);
18767   break;
18768 case color_model_part: 
18769   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18770   else mp_bad_unary(mp, c);
18771   break;
18772
18773 @ In the following procedure, |cur_exp| points to a capsule, which points to
18774 a big node. We want to delete all but one part of the big node.
18775
18776 @<Declare unary action...@>=
18777 void mp_take_part (MP mp,quarterword c) {
18778   pointer p; /* the big node */
18779   p=value(mp->cur_exp); value(temp_val)=p; type(temp_val)=mp->cur_type;
18780   link(p)=temp_val; mp_free_node(mp, mp->cur_exp,value_node_size);
18781   mp_make_exp_copy(mp, p+mp->sector_offset[c+mp_x_part_sector-x_part]);
18782   mp_recycle_value(mp, temp_val);
18783 }
18784
18785 @ @<Initialize table entries...@>=
18786 name_type(temp_val)=mp_capsule;
18787
18788 @ @<Additional cases of unary operators@>=
18789 case font_part:
18790 case text_part:
18791 case path_part:
18792 case pen_part:
18793 case dash_part:
18794   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18795   else mp_bad_unary(mp, c);
18796   break;
18797
18798 @ @<Declarations@>=
18799 void mp_scale_edges (MP mp);
18800
18801 @ @<Declare unary action...@>=
18802 void mp_take_pict_part (MP mp,quarterword c) {
18803   pointer p; /* first graphical object in |cur_exp| */
18804   p=link(dummy_loc(mp->cur_exp));
18805   if ( p!=null ) {
18806     switch (c) {
18807     case x_part: case y_part: case xx_part:
18808     case xy_part: case yx_part: case yy_part:
18809       if ( type(p)==text_code ) mp_flush_cur_exp(mp, text_trans_part(p+c));
18810       else goto NOT_FOUND;
18811       break;
18812     case red_part: case green_part: case blue_part:
18813       if ( has_color(p) ) mp_flush_cur_exp(mp, obj_color_part(p+c));
18814       else goto NOT_FOUND;
18815       break;
18816     case cyan_part: case magenta_part: case yellow_part:
18817     case black_part:
18818       if ( has_color(p) ) {
18819         if ( color_model(p)==uninitialized_model )
18820           mp_flush_cur_exp(mp, unity);
18821         else
18822           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-cyan_part)));
18823       } else goto NOT_FOUND;
18824       break;
18825     case grey_part:
18826       if ( has_color(p) )
18827           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-grey_part)));
18828       else goto NOT_FOUND;
18829       break;
18830     case color_model_part:
18831       if ( has_color(p) ) {
18832         if ( color_model(p)==uninitialized_model )
18833           mp_flush_cur_exp(mp, mp->internal[default_color_model]);
18834         else
18835           mp_flush_cur_exp(mp, color_model(p)*unity);
18836       } else goto NOT_FOUND;
18837       break;
18838     @<Handle other cases in |take_pict_part| or |goto not_found|@>;
18839     } /* all cases have been enumerated */
18840     return;
18841   };
18842 NOT_FOUND:
18843   @<Convert the current expression to a null value appropriate
18844     for |c|@>;
18845 }
18846
18847 @ @<Handle other cases in |take_pict_part| or |goto not_found|@>=
18848 case text_part: 
18849   if ( type(p)!=text_code ) goto NOT_FOUND;
18850   else { 
18851     mp_flush_cur_exp(mp, text_p(p));
18852     add_str_ref(mp->cur_exp);
18853     mp->cur_type=mp_string_type;
18854     };
18855   break;
18856 case font_part: 
18857   if ( type(p)!=text_code ) goto NOT_FOUND;
18858   else { 
18859     mp_flush_cur_exp(mp, rts(mp->font_name[font_n(p)])); 
18860     add_str_ref(mp->cur_exp);
18861     mp->cur_type=mp_string_type;
18862   };
18863   break;
18864 case path_part:
18865   if ( type(p)==text_code ) goto NOT_FOUND;
18866   else if ( is_stop(p) ) mp_confusion(mp, "pict");
18867 @:this can't happen pict}{\quad pict@>
18868   else { 
18869     mp_flush_cur_exp(mp, mp_copy_path(mp, path_p(p)));
18870     mp->cur_type=mp_path_type;
18871   }
18872   break;
18873 case pen_part: 
18874   if ( ! has_pen(p) ) goto NOT_FOUND;
18875   else {
18876     if ( pen_p(p)==null ) goto NOT_FOUND;
18877     else { mp_flush_cur_exp(mp, copy_pen(pen_p(p)));
18878       mp->cur_type=mp_pen_type;
18879     };
18880   }
18881   break;
18882 case dash_part: 
18883   if ( type(p)!=stroked_code ) goto NOT_FOUND;
18884   else { if ( dash_p(p)==null ) goto NOT_FOUND;
18885     else { add_edge_ref(dash_p(p));
18886     mp->se_sf=dash_scale(p);
18887     mp->se_pic=dash_p(p);
18888     mp_scale_edges(mp);
18889     mp_flush_cur_exp(mp, mp->se_pic);
18890     mp->cur_type=mp_picture_type;
18891     };
18892   }
18893   break;
18894
18895 @ Since |scale_edges| had to be declared |forward|, it had to be declared as a
18896 parameterless procedure even though it really takes two arguments and updates
18897 one of them.  Hence the following globals are needed.
18898
18899 @<Global...@>=
18900 pointer se_pic;  /* edge header used and updated by |scale_edges| */
18901 scaled se_sf;  /* the scale factor argument to |scale_edges| */
18902
18903 @ @<Convert the current expression to a null value appropriate...@>=
18904 switch (c) {
18905 case text_part: case font_part: 
18906   mp_flush_cur_exp(mp, rts(""));
18907   mp->cur_type=mp_string_type;
18908   break;
18909 case path_part: 
18910   mp_flush_cur_exp(mp, mp_get_node(mp, knot_node_size));
18911   left_type(mp->cur_exp)=endpoint;
18912   right_type(mp->cur_exp)=endpoint;
18913   link(mp->cur_exp)=mp->cur_exp;
18914   x_coord(mp->cur_exp)=0;
18915   y_coord(mp->cur_exp)=0;
18916   originator(mp->cur_exp)=metapost_user;
18917   mp->cur_type=mp_path_type;
18918   break;
18919 case pen_part: 
18920   mp_flush_cur_exp(mp, mp_get_pen_circle(mp, 0));
18921   mp->cur_type=mp_pen_type;
18922   break;
18923 case dash_part: 
18924   mp_flush_cur_exp(mp, mp_get_node(mp, edge_header_size));
18925   mp_init_edges(mp, mp->cur_exp);
18926   mp->cur_type=mp_picture_type;
18927   break;
18928 default: 
18929    mp_flush_cur_exp(mp, 0);
18930   break;
18931 }
18932
18933 @ @<Additional cases of unary...@>=
18934 case char_op: 
18935   if ( mp->cur_type!=mp_known ) { 
18936     mp_bad_unary(mp, char_op);
18937   } else { 
18938     mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256; 
18939     mp->cur_type=mp_string_type;
18940     if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
18941   }
18942   break;
18943 case decimal: 
18944   if ( mp->cur_type!=mp_known ) {
18945      mp_bad_unary(mp, decimal);
18946   } else { 
18947     mp->old_setting=mp->selector; mp->selector=new_string;
18948     mp_print_scaled(mp, mp->cur_exp); mp->cur_exp=mp_make_string(mp);
18949     mp->selector=mp->old_setting; mp->cur_type=mp_string_type;
18950   }
18951   break;
18952 case oct_op:
18953 case hex_op:
18954 case ASCII_op: 
18955   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
18956   else mp_str_to_num(mp, c);
18957   break;
18958 case font_size: 
18959   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, font_size);
18960   else @<Find the design size of the font whose name is |cur_exp|@>;
18961   break;
18962
18963 @ @<Declare unary action...@>=
18964 void mp_str_to_num (MP mp,quarterword c) { /* converts a string to a number */
18965   integer n; /* accumulator */
18966   ASCII_code m; /* current character */
18967   pool_pointer k; /* index into |str_pool| */
18968   int b; /* radix of conversion */
18969   boolean bad_char; /* did the string contain an invalid digit? */
18970   if ( c==ASCII_op ) {
18971     if ( length(mp->cur_exp)==0 ) n=-1;
18972     else n=mp->str_pool[mp->str_start[mp->cur_exp]];
18973   } else { 
18974     if ( c==oct_op ) b=8; else b=16;
18975     n=0; bad_char=false;
18976     for (k=mp->str_start[mp->cur_exp];k<=str_stop(mp->cur_exp)-1;k++) {
18977       m=mp->str_pool[k];
18978       if ( (m>='0')&&(m<='9') ) m=m-'0';
18979       else if ( (m>='A')&&(m<='F') ) m=m-'A'+10;
18980       else if ( (m>='a')&&(m<='f') ) m=m-'a'+10;
18981       else  { bad_char=true; m=0; };
18982       if ( m>=b ) { bad_char=true; m=0; };
18983       if ( n<32768 / b ) n=n*b+m; else n=32767;
18984     }
18985     @<Give error messages if |bad_char| or |n>=4096|@>;
18986   }
18987   mp_flush_cur_exp(mp, n*unity);
18988 }
18989
18990 @ @<Give error messages if |bad_char|...@>=
18991 if ( bad_char ) { 
18992   exp_err("String contains illegal digits");
18993 @.String contains illegal digits@>
18994   if ( c==oct_op ) {
18995     help1("I zeroed out characters that weren't in the range 0..7.");
18996   } else  {
18997     help1("I zeroed out characters that weren't hex digits.");
18998   }
18999   mp_put_get_error(mp);
19000 }
19001 if ( (n>4095) ) {
19002   if ( mp->internal[warning_check]>0 ) {
19003     print_err("Number too large ("); 
19004     mp_print_int(mp, n); mp_print_char(mp, ')');
19005 @.Number too large@>
19006     help2("I have trouble with numbers greater than 4095; watch out.")
19007       ("(Set warningcheck:=0 to suppress this message.)");
19008     mp_put_get_error(mp);
19009   }
19010 }
19011
19012 @ The length operation is somewhat unusual in that it applies to a variety
19013 of different types of operands.
19014
19015 @<Additional cases of unary...@>=
19016 case length_op: 
19017   switch (mp->cur_type) {
19018   case mp_string_type: mp_flush_cur_exp(mp, length(mp->cur_exp)*unity); break;
19019   case mp_path_type: mp_flush_cur_exp(mp, mp_path_length(mp)); break;
19020   case mp_known: mp->cur_exp=abs(mp->cur_exp); break;
19021   case mp_picture_type: mp_flush_cur_exp(mp, mp_pict_length(mp)); break;
19022   default: 
19023     if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) )
19024       mp_flush_cur_exp(mp, mp_pyth_add(mp, 
19025         value(x_part_loc(value(mp->cur_exp))),
19026         value(y_part_loc(value(mp->cur_exp)))));
19027     else mp_bad_unary(mp, c);
19028     break;
19029   }
19030   break;
19031
19032 @ @<Declare unary action...@>=
19033 scaled mp_path_length (MP mp) { /* computes the length of the current path */
19034   scaled n; /* the path length so far */
19035   pointer p; /* traverser */
19036   p=mp->cur_exp;
19037   if ( left_type(p)==endpoint ) n=-unity; else n=0;
19038   do {  p=link(p); n=n+unity; } while (p!=mp->cur_exp);
19039   return n;
19040 }
19041
19042 @ @<Declare unary action...@>=
19043 scaled mp_pict_length (MP mp) { 
19044   /* counts interior components in picture |cur_exp| */
19045   scaled n; /* the count so far */
19046   pointer p; /* traverser */
19047   n=0;
19048   p=link(dummy_loc(mp->cur_exp));
19049   if ( p!=null ) {
19050     if ( is_start_or_stop(p) )
19051       if ( mp_skip_1component(mp, p)==null ) p=link(p);
19052     while ( p!=null )  { 
19053       skip_component(p) return n; 
19054       n=n+unity;   
19055     }
19056   }
19057   return n;
19058 }
19059
19060 @ Implement |turningnumber|
19061
19062 @<Additional cases of unary...@>=
19063 case turning_op:
19064   if ( mp->cur_type==mp_pair_type ) mp_flush_cur_exp(mp, 0);
19065   else if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, turning_op);
19066   else if ( left_type(mp->cur_exp)==endpoint )
19067      mp_flush_cur_exp(mp, 0); /* not a cyclic path */
19068   else
19069     mp_flush_cur_exp(mp, mp_turn_cycles_wrapper(mp, mp->cur_exp));
19070   break;
19071
19072 @ The function |an_angle| returns the value of the |angle| primitive, or $0$ if the
19073 argument is |origin|.
19074
19075 @<Declare unary action...@>=
19076 angle mp_an_angle (MP mp,scaled xpar, scaled ypar) {
19077   if ( (! ((xpar==0) && (ypar==0))) )
19078     return mp_n_arg(mp, xpar,ypar);
19079   return 0;
19080 }
19081
19082
19083 @ The actual turning number is (for the moment) computed in a C function
19084 that receives eight integers corresponding to the four controlling points,
19085 and returns a single angle.  Besides those, we have to account for discrete
19086 moves at the actual points.
19087
19088 @d floor(a) (a>=0 ? a : -(int)(-a))
19089 @d bezier_error (720<<20)+1
19090 @d sign(v) ((v)>0 ? 1 : ((v)<0 ? -1 : 0 ))
19091 @d print_roots(a) { if (debuglevel>(65536*2))
19092    fprintf(stdout,"bezier_slope(): %s, i=%f, o=%f, angle=%f\n", (a),in,out,res); }
19093 @d out ((double)(xo>>20))
19094 @d mid ((double)(xm>>20))
19095 @d in  ((double)(xi>>20))
19096 @d divisor (256*256)
19097 @d double2angle(a) (int)floor(a*256.0*256.0*16.0)
19098
19099 @<Declare unary action...@>=
19100 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19101             integer CX,integer CY,integer DX,integer DY, int debuglevel);
19102
19103 @ @c 
19104 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19105             integer CX,integer CY,integer DX,integer DY, int debuglevel) {
19106   double a, b, c;
19107   integer deltax,deltay;
19108   double ax,ay,bx,by,cx,cy,dx,dy;
19109   angle xi = 0, xo = 0, xm = 0;
19110   double res = 0;
19111   ax=AX/divisor;  ay=AY/divisor;
19112   bx=BX/divisor;  by=BY/divisor;
19113   cx=CX/divisor;  cy=CY/divisor;
19114   dx=DX/divisor;  dy=DY/divisor;
19115
19116   deltax = (BX-AX); deltay = (BY-AY);
19117   if (deltax==0 && deltay == 0) { deltax=(CX-AX); deltay=(CY-AY); }
19118   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19119   xi = mp_an_angle(mp,deltax,deltay);
19120
19121   deltax = (CX-BX); deltay = (CY-BY);
19122   xm = mp_an_angle(mp,deltax,deltay);
19123
19124   deltax = (DX-CX); deltay = (DY-CY);
19125   if (deltax==0 && deltay == 0) { deltax=(DX-BX); deltay=(DY-BY); }
19126   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19127   xo = mp_an_angle(mp,deltax,deltay);
19128
19129   a = (bx-ax)*(cy-by) - (cx-bx)*(by-ay); /* a = (bp-ap)x(cp-bp); */
19130   b = (bx-ax)*(dy-cy) - (by-ay)*(dx-cx);; /* b = (bp-ap)x(dp-cp);*/
19131   c = (cx-bx)*(dy-cy) - (dx-cx)*(cy-by); /* c = (cp-bp)x(dp-cp);*/
19132
19133   if (debuglevel>(65536*2)) {
19134     fprintf(stdout,
19135       "bezier_slope(): (%.2f,%.2f),(%.2f,%.2f),(%.2f,%.2f),(%.2f,%.2f)\n",
19136               ax,ay,bx,by,cx,cy,dx,dy);
19137     fprintf(stdout,
19138       "bezier_slope(): a,b,c,b^2,4ac: (%.2f,%.2f,%.2f,%.2f,%.2f)\n",a,b,c,b*b,4*a*c);
19139   }
19140
19141   if ((a==0)&&(c==0)) {
19142     res = (b==0 ?  0 :  (out-in)); 
19143     print_roots("no roots (a)");
19144   } else if ((a==0)||(c==0)) {
19145     if ((sign(b) == sign(a)) || (sign(b) == sign(c))) {
19146       res = out-in; /* ? */
19147       if (res<-180.0) 
19148         res += 360.0;
19149       else if (res>180.0)
19150         res -= 360.0;
19151       print_roots("no roots (b)");
19152     } else {
19153       res = out-in; /* ? */
19154       print_roots("one root (a)");
19155     }
19156   } else if ((sign(a)*sign(c))<0) {
19157     res = out-in; /* ? */
19158       if (res<-180.0) 
19159         res += 360.0;
19160       else if (res>180.0)
19161         res -= 360.0;
19162     print_roots("one root (b)");
19163   } else {
19164     if (sign(a) == sign(b)) {
19165       res = out-in; /* ? */
19166       if (res<-180.0) 
19167         res += 360.0;
19168       else if (res>180.0)
19169         res -= 360.0;
19170       print_roots("no roots (d)");
19171     } else {
19172       if ((b*b) == (4*a*c)) {
19173         res = bezier_error;
19174         print_roots("double root"); /* cusp */
19175       } else if ((b*b) < (4*a*c)) {
19176         res = out-in; /* ? */
19177         if (res<=0.0 &&res>-180.0) 
19178           res += 360.0;
19179         else if (res>=0.0 && res<180.0)
19180           res -= 360.0;
19181         print_roots("no roots (e)");
19182       } else {
19183         res = out-in;
19184         if (res<-180.0) 
19185           res += 360.0;
19186         else if (res>180.0)
19187           res -= 360.0;
19188         print_roots("two roots"); /* two inflections */
19189       }
19190     }
19191   }
19192   return double2angle(res);
19193 }
19194
19195 @
19196 @d p_nextnext link(link(p))
19197 @d p_next link(p)
19198 @d seven_twenty_deg 05500000000 /* $720\cdot2^{20}$, represents $720^\circ$ */
19199
19200 @<Declare unary action...@>=
19201 scaled mp_new_turn_cycles (MP mp,pointer c) {
19202   angle res,ang; /*  the angles of intermediate results  */
19203   scaled turns;  /*  the turn counter  */
19204   pointer p;     /*  for running around the path  */
19205   integer xp,yp;   /*  coordinates of next point  */
19206   integer x,y;   /*  helper coordinates  */
19207   angle in_angle,out_angle;     /*  helper angles */
19208   int old_setting; /* saved |selector| setting */
19209   res=0;
19210   turns= 0;
19211   p=c;
19212   old_setting = mp->selector; mp->selector=term_only;
19213   if ( mp->internal[tracing_commands]>unity ) {
19214     mp_begin_diagnostic(mp);
19215     mp_print_nl(mp, "");
19216     mp_end_diagnostic(mp, false);
19217   }
19218   do { 
19219     xp = x_coord(p_next); yp = y_coord(p_next);
19220     ang  = mp_bezier_slope(mp,x_coord(p), y_coord(p), right_x(p), right_y(p),
19221              left_x(p_next), left_y(p_next), xp, yp, 
19222              mp->internal[tracing_commands]);
19223     if ( ang>seven_twenty_deg ) {
19224       print_err("Strange path");
19225       mp_error(mp);
19226       mp->selector=old_setting;
19227       return 0;
19228     }
19229     res  = res + ang;
19230     if ( res > one_eighty_deg ) {
19231       res = res - three_sixty_deg;
19232       turns = turns + unity;
19233     }
19234     if ( res <= -one_eighty_deg ) {
19235       res = res + three_sixty_deg;
19236       turns = turns - unity;
19237     }
19238     /*  incoming angle at next point  */
19239     x = left_x(p_next);  y = left_y(p_next);
19240     if ( (xp==x)&&(yp==y) ) { x = right_x(p);  y = right_y(p);  };
19241     if ( (xp==x)&&(yp==y) ) { x = x_coord(p);  y = y_coord(p);  };
19242     in_angle = mp_an_angle(mp, xp - x, yp - y);
19243     /*  outgoing angle at next point  */
19244     x = right_x(p_next);  y = right_y(p_next);
19245     if ( (xp==x)&&(yp==y) ) { x = left_x(p_nextnext);  y = left_y(p_nextnext);  };
19246     if ( (xp==x)&&(yp==y) ) { x = x_coord(p_nextnext); y = y_coord(p_nextnext); };
19247     out_angle = mp_an_angle(mp, x - xp, y- yp);
19248     ang  = (out_angle - in_angle);
19249     reduce_angle(ang);
19250     if ( ang!=0 ) {
19251       res  = res + ang;
19252       if ( res >= one_eighty_deg ) {
19253         res = res - three_sixty_deg;
19254         turns = turns + unity;
19255       };
19256       if ( res <= -one_eighty_deg ) {
19257         res = res + three_sixty_deg;
19258         turns = turns - unity;
19259       };
19260     };
19261     p = link(p);
19262   } while (p!=c);
19263   mp->selector=old_setting;
19264   return turns;
19265 }
19266
19267
19268 @ This code is based on Bogus\l{}av Jackowski's
19269 |emergency_turningnumber| macro, with some minor changes by Taco
19270 Hoekwater. The macro code looked more like this:
19271 {\obeylines
19272 vardef turning\_number primary p =
19273 ~~save res, ang, turns;
19274 ~~res := 0;
19275 ~~if length p <= 2:
19276 ~~~~if Angle ((point 0 of p) - (postcontrol 0 of p)) >= 0:  1  else: -1 fi
19277 ~~else:
19278 ~~~~for t = 0 upto length p-1 :
19279 ~~~~~~angc := Angle ((point t+1 of p)  - (point t of p))
19280 ~~~~~~~~- Angle ((point t of p) - (point t-1 of p));
19281 ~~~~~~if angc > 180: angc := angc - 360; fi;
19282 ~~~~~~if angc < -180: angc := angc + 360; fi;
19283 ~~~~~~res  := res + angc;
19284 ~~~~endfor;
19285 ~~res/360
19286 ~~fi
19287 enddef;}
19288 The general idea is to calculate only the sum of the angles of
19289 straight lines between the points, of a path, not worrying about cusps
19290 or self-intersections in the segments at all. If the segment is not
19291 well-behaved, the result is not necesarily correct. But the old code
19292 was not always correct either, and worse, it sometimes failed for
19293 well-behaved paths as well. All known bugs that were triggered by the
19294 original code no longer occur with this code, and it runs roughly 3
19295 times as fast because the algorithm is much simpler.
19296
19297 @ It is possible to overflow the return value of the |turn_cycles|
19298 function when the path is sufficiently long and winding, but I am not
19299 going to bother testing for that. In any case, it would only return
19300 the looped result value, which is not a big problem.
19301
19302 The macro code for the repeat loop was a bit nicer to look
19303 at than the pascal code, because it could use |point -1 of p|. In
19304 pascal, the fastest way to loop around the path is not to look
19305 backward once, but forward twice. These defines help hide the trick.
19306
19307 @d p_to link(link(p))
19308 @d p_here link(p)
19309 @d p_from p
19310
19311 @<Declare unary action...@>=
19312 scaled mp_turn_cycles (MP mp,pointer c) {
19313   angle res,ang; /*  the angles of intermediate results  */
19314   scaled turns;  /*  the turn counter  */
19315   pointer p;     /*  for running around the path  */
19316   res=0;  turns= 0; p=c;
19317   do { 
19318     ang  = mp_an_angle (mp, x_coord(p_to) - x_coord(p_here), 
19319                             y_coord(p_to) - y_coord(p_here))
19320         - mp_an_angle (mp, x_coord(p_here) - x_coord(p_from), 
19321                            y_coord(p_here) - y_coord(p_from));
19322     reduce_angle(ang);
19323     res  = res + ang;
19324     if ( res >= three_sixty_deg )  {
19325       res = res - three_sixty_deg;
19326       turns = turns + unity;
19327     };
19328     if ( res <= -three_sixty_deg ) {
19329       res = res + three_sixty_deg;
19330       turns = turns - unity;
19331     };
19332     p = link(p);
19333   } while (p!=c);
19334   return turns;
19335 }
19336
19337 @ @<Declare unary action...@>=
19338 scaled mp_turn_cycles_wrapper (MP mp,pointer c) {
19339   scaled nval,oval;
19340   scaled saved_t_o; /* tracing\_online saved  */
19341   if ( (link(c)==c)||(link(link(c))==c) ) {
19342     if ( mp_an_angle (mp, x_coord(c) - right_x(c),  y_coord(c) - right_y(c)) > 0 )
19343       return unity;
19344     else
19345       return -unity;
19346   } else {
19347     nval = mp_new_turn_cycles(mp, c);
19348     oval = mp_turn_cycles(mp, c);
19349     if ( nval!=oval ) {
19350       saved_t_o=mp->internal[tracing_online];
19351       mp->internal[tracing_online]=unity;
19352       mp_begin_diagnostic(mp);
19353       mp_print_nl (mp, "Warning: the turningnumber algorithms do not agree."
19354                        " The current computed value is ");
19355       mp_print_scaled(mp, nval);
19356       mp_print(mp, ", but the 'connect-the-dots' algorithm returned ");
19357       mp_print_scaled(mp, oval);
19358       mp_end_diagnostic(mp, false);
19359       mp->internal[tracing_online]=saved_t_o;
19360     }
19361     return nval;
19362   }
19363 }
19364
19365 @ @<Declare unary action...@>=
19366 scaled mp_count_turns (MP mp,pointer c) {
19367   pointer p; /* a knot in envelope spec |c| */
19368   integer t; /* total pen offset changes counted */
19369   t=0; p=c;
19370   do {  
19371     t=t+info(p)-zero_off;
19372     p=link(p);
19373   } while (p!=c);
19374   return ((t / 3)*unity);
19375 }
19376
19377 @ @d type_range(A,B) { 
19378   if ( (mp->cur_type>=(A)) && (mp->cur_type<=(B)) ) 
19379     mp_flush_cur_exp(mp, true_code);
19380   else mp_flush_cur_exp(mp, false_code);
19381   mp->cur_type=mp_boolean_type;
19382   }
19383 @d type_test(A) { 
19384   if ( mp->cur_type==(A) ) mp_flush_cur_exp(mp, true_code);
19385   else mp_flush_cur_exp(mp, false_code);
19386   mp->cur_type=mp_boolean_type;
19387   }
19388
19389 @<Additional cases of unary operators@>=
19390 case mp_boolean_type: 
19391   type_range(mp_boolean_type,mp_unknown_boolean); break;
19392 case mp_string_type: 
19393   type_range(mp_string_type,mp_unknown_string); break;
19394 case mp_pen_type: 
19395   type_range(mp_pen_type,mp_unknown_pen); break;
19396 case mp_path_type: 
19397   type_range(mp_path_type,mp_unknown_path); break;
19398 case mp_picture_type: 
19399   type_range(mp_picture_type,mp_unknown_picture); break;
19400 case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
19401 case mp_pair_type: 
19402   type_test(c); break;
19403 case mp_numeric_type: 
19404   type_range(mp_known,mp_independent); break;
19405 case known_op: case unknown_op: 
19406   mp_test_known(mp, c); break;
19407
19408 @ @<Declare unary action procedures@>=
19409 void mp_test_known (MP mp,quarterword c) {
19410   int b; /* is the current expression known? */
19411   pointer p,q; /* locations in a big node */
19412   b=false_code;
19413   switch (mp->cur_type) {
19414   case mp_vacuous: case mp_boolean_type: case mp_string_type:
19415   case mp_pen_type: case mp_path_type: case mp_picture_type:
19416   case mp_known: 
19417     b=true_code;
19418     break;
19419   case mp_transform_type:
19420   case mp_color_type: case mp_cmykcolor_type: case mp_pair_type: 
19421     p=value(mp->cur_exp);
19422     q=p+mp->big_node_size[mp->cur_type];
19423     do {  
19424       q=q-2;
19425       if ( type(q)!=mp_known ) 
19426        goto DONE;
19427     } while (q!=p);
19428     b=true_code;
19429   DONE:  
19430     break;
19431   default: 
19432     break;
19433   }
19434   if ( c==known_op ) mp_flush_cur_exp(mp, b);
19435   else mp_flush_cur_exp(mp, true_code+false_code-b);
19436   mp->cur_type=mp_boolean_type;
19437 }
19438
19439 @ @<Additional cases of unary operators@>=
19440 case cycle_op: 
19441   if ( mp->cur_type!=mp_path_type ) mp_flush_cur_exp(mp, false_code);
19442   else if ( left_type(mp->cur_exp)!=endpoint ) mp_flush_cur_exp(mp, true_code);
19443   else mp_flush_cur_exp(mp, false_code);
19444   mp->cur_type=mp_boolean_type;
19445   break;
19446
19447 @ @<Additional cases of unary operators@>=
19448 case arc_length: 
19449   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19450   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, arc_length);
19451   else mp_flush_cur_exp(mp, mp_get_arc_length(mp, mp->cur_exp));
19452   break;
19453
19454 @ Here we use the fact that |c-filled_op+fill_code| is the desired graphical
19455 object |type|.
19456 @^data structure assumptions@>
19457
19458 @<Additional cases of unary operators@>=
19459 case filled_op:
19460 case stroked_op:
19461 case textual_op:
19462 case clipped_op:
19463 case bounded_op:
19464   if ( mp->cur_type!=mp_picture_type ) mp_flush_cur_exp(mp, false_code);
19465   else if ( link(dummy_loc(mp->cur_exp))==null ) mp_flush_cur_exp(mp, false_code);
19466   else if ( type(link(dummy_loc(mp->cur_exp)))==c+fill_code-filled_op )
19467     mp_flush_cur_exp(mp, true_code);
19468   else mp_flush_cur_exp(mp, false_code);
19469   mp->cur_type=mp_boolean_type;
19470   break;
19471
19472 @ @<Additional cases of unary operators@>=
19473 case make_pen_op: 
19474   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19475   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, make_pen_op);
19476   else { 
19477     mp->cur_type=mp_pen_type;
19478     mp->cur_exp=mp_make_pen(mp, mp->cur_exp,true);
19479   };
19480   break;
19481 case make_path_op: 
19482   if ( mp->cur_type!=mp_pen_type ) mp_bad_unary(mp, make_path_op);
19483   else  { 
19484     mp->cur_type=mp_path_type;
19485     mp_make_path(mp, mp->cur_exp);
19486   };
19487   break;
19488 case reverse: 
19489   if ( mp->cur_type==mp_path_type ) {
19490     p=mp_htap_ypoc(mp, mp->cur_exp);
19491     if ( right_type(p)==endpoint ) p=link(p);
19492     mp_toss_knot_list(mp, mp->cur_exp); mp->cur_exp=p;
19493   } else if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19494   else mp_bad_unary(mp, reverse);
19495   break;
19496
19497 @ The |pair_value| routine changes the current expression to a
19498 given ordered pair of values.
19499
19500 @<Declare unary action procedures@>=
19501 void mp_pair_value (MP mp,scaled x, scaled y) {
19502   pointer p; /* a pair node */
19503   p=mp_get_node(mp, value_node_size); 
19504   mp_flush_cur_exp(mp, p); mp->cur_type=mp_pair_type;
19505   type(p)=mp_pair_type; name_type(p)=mp_capsule; mp_init_big_node(mp, p);
19506   p=value(p);
19507   type(x_part_loc(p))=mp_known; value(x_part_loc(p))=x;
19508   type(y_part_loc(p))=mp_known; value(y_part_loc(p))=y;
19509 }
19510
19511 @ @<Additional cases of unary operators@>=
19512 case ll_corner_op: 
19513   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ll_corner_op);
19514   else mp_pair_value(mp, minx,miny);
19515   break;
19516 case lr_corner_op: 
19517   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, lr_corner_op);
19518   else mp_pair_value(mp, maxx,miny);
19519   break;
19520 case ul_corner_op: 
19521   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ul_corner_op);
19522   else mp_pair_value(mp, minx,maxy);
19523   break;
19524 case ur_corner_op: 
19525   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ur_corner_op);
19526   else mp_pair_value(mp, maxx,maxy);
19527   break;
19528
19529 @ Here is a function that sets |minx|, |maxx|, |miny|, |maxy| to the bounding
19530 box of the current expression.  The boolean result is |false| if the expression
19531 has the wrong type.
19532
19533 @<Declare unary action procedures@>=
19534 boolean mp_get_cur_bbox (MP mp) { 
19535   switch (mp->cur_type) {
19536   case mp_picture_type: 
19537     mp_set_bbox(mp, mp->cur_exp,true);
19538     if ( minx_val(mp->cur_exp)>maxx_val(mp->cur_exp) ) {
19539       minx=0; maxx=0; miny=0; maxy=0;
19540     } else { 
19541       minx=minx_val(mp->cur_exp);
19542       maxx=maxx_val(mp->cur_exp);
19543       miny=miny_val(mp->cur_exp);
19544       maxy=maxy_val(mp->cur_exp);
19545     }
19546     break;
19547   case mp_path_type: 
19548     mp_path_bbox(mp, mp->cur_exp);
19549     break;
19550   case mp_pen_type: 
19551     mp_pen_bbox(mp, mp->cur_exp);
19552     break;
19553   default: 
19554     return false;
19555   }
19556   return true;
19557 }
19558
19559 @ @<Additional cases of unary operators@>=
19560 case read_from_op:
19561 case close_from_op: 
19562   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19563   else mp_do_read_or_close(mp,c);
19564   break;
19565
19566 @ Here is a routine that interprets |cur_exp| as a file name and tries to read
19567 a line from the file or to close the file.
19568
19569 @d close_file 46 /* go here when closing the file */
19570
19571 @<Declare unary action procedures@>=
19572 void mp_do_read_or_close (MP mp,quarterword c) {
19573   readf_index n,n0; /* indices for searching |rd_fname| */
19574   @<Find the |n| where |rd_fname[n]=cur_exp|; if |cur_exp| must be inserted,
19575     call |start_read_input| and |goto found| or |not_found|@>;
19576   mp_begin_file_reading(mp);
19577   name=is_read;
19578   if ( mp_input_ln(mp, mp->rd_file[n],true) ) 
19579     goto FOUND;
19580   mp_end_file_reading(mp);
19581 NOT_FOUND:
19582   @<Record the end of file and set |cur_exp| to a dummy value@>;
19583   return;
19584 CLOSE_FILE:
19585   mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous; 
19586   return;
19587 FOUND:
19588   mp_flush_cur_exp(mp, 0);
19589   mp_finish_read(mp);
19590 }
19591
19592 @ Free slots in the |rd_file| and |rd_fname| arrays are marked with NULL's in
19593 |rd_fname|.
19594
19595 @<Find the |n| where |rd_fname[n]=cur_exp|...@>=
19596 {   
19597   char *fn;
19598   n=mp->read_files;
19599   n0=mp->read_files;
19600   fn = str(mp->cur_exp);
19601   while (mp_xstrcmp(fn,mp->rd_fname[n])!=0) { 
19602     if ( n>0 ) {
19603       decr(n);
19604     } else if ( c==close_from_op ) {
19605       goto CLOSE_FILE;
19606     } else {
19607       if ( n0==mp->read_files ) {
19608         if ( mp->read_files<mp->max_read_files ) {
19609           incr(mp->read_files);
19610         } else {
19611           FILE **rd_file;
19612           char **rd_fname;
19613               readf_index l,k;
19614           l = mp->max_read_files + (mp->max_read_files>>2);
19615           rd_file = xmalloc((l+1), sizeof(FILE *));
19616           rd_fname = xmalloc((l+1), sizeof(char *));
19617               for (k=0;k<=l;k++) {
19618             if (k<=mp->max_read_files) {
19619                   rd_file[k]=mp->rd_file[k]; 
19620               rd_fname[k]=mp->rd_fname[k];
19621             } else {
19622                   rd_file[k]=0; 
19623               rd_fname[k]=NULL;
19624             }
19625           }
19626               xfree(mp->rd_file); xfree(mp->rd_fname);
19627           mp->max_read_files = l;
19628           mp->rd_file = rd_file;
19629           mp->rd_fname = rd_fname;
19630         }
19631       }
19632       n=n0;
19633       if ( mp_start_read_input(mp,fn,n) ) 
19634         goto FOUND;
19635       else 
19636         goto NOT_FOUND;
19637     }
19638     if ( mp->rd_fname[n]==NULL ) { n0=n; }
19639   } 
19640   if ( c==close_from_op ) { 
19641     fclose(mp->rd_file[n]); 
19642     goto NOT_FOUND; 
19643   }
19644 }
19645
19646 @ @<Record the end of file and set |cur_exp| to a dummy value@>=
19647 xfree(mp->rd_fname[n]);
19648 mp->rd_fname[n]=NULL;
19649 if ( n==mp->read_files-1 ) mp->read_files=n;
19650 if ( c==close_from_op ) 
19651   goto CLOSE_FILE;
19652 mp_flush_cur_exp(mp, mp->eof_line);
19653 mp->cur_type=mp_string_type
19654
19655 @ The string denoting end-of-file is a one-byte string at position zero, by definition
19656
19657 @<Glob...@>=
19658 str_number eof_line;
19659
19660 @ @<Set init...@>=
19661 mp->eof_line=0;
19662
19663 @ Finally, we have the operations that combine a capsule~|p|
19664 with the current expression.
19665
19666 @c @<Declare binary action procedures@>;
19667 void mp_do_binary (MP mp,pointer p, quarterword c) {
19668   pointer q,r,rr; /* for list manipulation */
19669   pointer old_p,old_exp; /* capsules to recycle */
19670   integer v; /* for numeric manipulation */
19671   check_arith;
19672   if ( mp->internal[tracing_commands]>two ) {
19673     @<Trace the current binary operation@>;
19674   }
19675   @<Sidestep |independent| cases in capsule |p|@>;
19676   @<Sidestep |independent| cases in the current expression@>;
19677   switch (c) {
19678   case plus: case minus:
19679     @<Add or subtract the current expression from |p|@>;
19680     break;
19681   @<Additional cases of binary operators@>;
19682   }; /* there are no other cases */
19683   mp_recycle_value(mp, p); 
19684   mp_free_node(mp, p,value_node_size); /* |return| to avoid this */
19685   check_arith; 
19686   @<Recycle any sidestepped |independent| capsules@>;
19687 }
19688
19689 @ @<Declare binary action...@>=
19690 void mp_bad_binary (MP mp,pointer p, quarterword c) { 
19691   mp_disp_err(mp, p,"");
19692   exp_err("Not implemented: ");
19693 @.Not implemented...@>
19694   if ( c>=min_of ) mp_print_op(mp, c);
19695   mp_print_known_or_unknown_type(mp, type(p),p);
19696   if ( c>=min_of ) mp_print(mp, "of"); else mp_print_op(mp, c);
19697   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
19698   help3("I'm afraid I don't know how to apply that operation to that")
19699        ("combination of types. Continue, and I'll return the second")
19700       ("argument (see above) as the result of the operation.");
19701   mp_put_get_error(mp);
19702 }
19703
19704 @ @<Trace the current binary operation@>=
19705
19706   mp_begin_diagnostic(mp); mp_print_nl(mp, "{(");
19707   mp_print_exp(mp,p,0); /* show the operand, but not verbosely */
19708   mp_print_char(mp,')'); mp_print_op(mp,c); mp_print_char(mp,'(');
19709   mp_print_exp(mp,null,0); mp_print(mp,")}"); 
19710   mp_end_diagnostic(mp, false);
19711 }
19712
19713 @ Several of the binary operations are potentially complicated by the
19714 fact that |independent| values can sneak into capsules. For example,
19715 we've seen an instance of this difficulty in the unary operation
19716 of negation. In order to reduce the number of cases that need to be
19717 handled, we first change the two operands (if necessary)
19718 to rid them of |independent| components. The original operands are
19719 put into capsules called |old_p| and |old_exp|, which will be
19720 recycled after the binary operation has been safely carried out.
19721
19722 @<Recycle any sidestepped |independent| capsules@>=
19723 if ( old_p!=null ) { 
19724   mp_recycle_value(mp, old_p); mp_free_node(mp, old_p,value_node_size);
19725 }
19726 if ( old_exp!=null ) {
19727   mp_recycle_value(mp, old_exp); mp_free_node(mp, old_exp,value_node_size);
19728 }
19729
19730 @ A big node is considered to be ``tarnished'' if it contains at least one
19731 independent component. We will define a simple function called `|tarnished|'
19732 that returns |null| if and only if its argument is not tarnished.
19733
19734 @<Sidestep |independent| cases in capsule |p|@>=
19735 switch (type(p)) {
19736 case mp_transform_type:
19737 case mp_color_type:
19738 case mp_cmykcolor_type:
19739 case mp_pair_type: 
19740   old_p=mp_tarnished(mp, p);
19741   break;
19742 case mp_independent: old_p=diov; break;
19743 default: old_p=null; break;
19744 };
19745 if ( old_p!=null ) {
19746   q=mp_stash_cur_exp(mp); old_p=p; mp_make_exp_copy(mp, old_p);
19747   p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
19748 }
19749
19750 @ @<Sidestep |independent| cases in the current expression@>=
19751 switch (mp->cur_type) {
19752 case mp_transform_type:
19753 case mp_color_type:
19754 case mp_cmykcolor_type:
19755 case mp_pair_type: 
19756   old_exp=mp_tarnished(mp, mp->cur_exp);
19757   break;
19758 case mp_independent:old_exp=diov; break;
19759 default: old_exp=null; break;
19760 };
19761 if ( old_exp!=null ) {
19762   old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
19763 }
19764
19765 @ @<Declare binary action...@>=
19766 pointer mp_tarnished (MP mp,pointer p) {
19767   pointer q; /* beginning of the big node */
19768   pointer r; /* current position in the big node */
19769   q=value(p); r=q+mp->big_node_size[type(p)];
19770   do {  
19771    r=r-2;
19772    if ( type(r)==mp_independent ) return diov; 
19773   } while (r!=q);
19774   return null;
19775 }
19776
19777 @ @<Add or subtract the current expression from |p|@>=
19778 if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
19779   mp_bad_binary(mp, p,c);
19780 } else  {
19781   if ((mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
19782     mp_add_or_subtract(mp, p,null,c);
19783   } else {
19784     if ( mp->cur_type!=type(p) )  {
19785       mp_bad_binary(mp, p,c);
19786     } else { 
19787       q=value(p); r=value(mp->cur_exp);
19788       rr=r+mp->big_node_size[mp->cur_type];
19789       while ( r<rr ) { 
19790         mp_add_or_subtract(mp, q,r,c);
19791         q=q+2; r=r+2;
19792       }
19793     }
19794   }
19795 }
19796
19797 @ The first argument to |add_or_subtract| is the location of a value node
19798 in a capsule or pair node that will soon be recycled. The second argument
19799 is either a location within a pair or transform node of |cur_exp|,
19800 or it is null (which means that |cur_exp| itself should be the second
19801 argument).  The third argument is either |plus| or |minus|.
19802
19803 The sum or difference of the numeric quantities will replace the second
19804 operand.  Arithmetic overflow may go undetected; users aren't supposed to
19805 be monkeying around with really big values.
19806
19807 @<Declare binary action...@>=
19808 @<Declare the procedure called |dep_finish|@>;
19809 void mp_add_or_subtract (MP mp,pointer p, pointer q, quarterword c) {
19810   small_number s,t; /* operand types */
19811   pointer r; /* list traverser */
19812   integer v; /* second operand value */
19813   if ( q==null ) { 
19814     t=mp->cur_type;
19815     if ( t<mp_dependent ) v=mp->cur_exp; else v=dep_list(mp->cur_exp);
19816   } else { 
19817     t=type(q);
19818     if ( t<mp_dependent ) v=value(q); else v=dep_list(q);
19819   }
19820   if ( t==mp_known ) {
19821     if ( c==minus ) negate(v);
19822     if ( type(p)==mp_known ) {
19823       v=mp_slow_add(mp, value(p),v);
19824       if ( q==null ) mp->cur_exp=v; else value(q)=v;
19825       return;
19826     }
19827     @<Add a known value to the constant term of |dep_list(p)|@>;
19828   } else  { 
19829     if ( c==minus ) mp_negate_dep_list(mp, v);
19830     @<Add operand |p| to the dependency list |v|@>;
19831   }
19832 }
19833
19834 @ @<Add a known value to the constant term of |dep_list(p)|@>=
19835 r=dep_list(p);
19836 while ( info(r)!=null ) r=link(r);
19837 value(r)=mp_slow_add(mp, value(r),v);
19838 if ( q==null ) {
19839   q=mp_get_node(mp, value_node_size); mp->cur_exp=q; mp->cur_type=type(p);
19840   name_type(q)=mp_capsule;
19841 }
19842 dep_list(q)=dep_list(p); type(q)=type(p);
19843 prev_dep(q)=prev_dep(p); link(prev_dep(p))=q;
19844 type(p)=mp_known; /* this will keep the recycler from collecting non-garbage */
19845
19846 @ We prefer |dependent| lists to |mp_proto_dependent| ones, because it is
19847 nice to retain the extra accuracy of |fraction| coefficients.
19848 But we have to handle both kinds, and mixtures too.
19849
19850 @<Add operand |p| to the dependency list |v|@>=
19851 if ( type(p)==mp_known ) {
19852   @<Add the known |value(p)| to the constant term of |v|@>;
19853 } else { 
19854   s=type(p); r=dep_list(p);
19855   if ( t==mp_dependent ) {
19856     if ( s==mp_dependent ) {
19857       if ( mp_max_coef(mp, r)+mp_max_coef(mp, v)<coef_bound )
19858         v=mp_p_plus_q(mp, v,r,mp_dependent); goto DONE;
19859       } /* |fix_needed| will necessarily be false */
19860       t=mp_proto_dependent; 
19861       v=mp_p_over_v(mp, v,unity,mp_dependent,mp_proto_dependent);
19862     }
19863     if ( s==mp_proto_dependent ) v=mp_p_plus_q(mp, v,r,mp_proto_dependent);
19864     else v=mp_p_plus_fq(mp, v,unity,r,mp_proto_dependent,mp_dependent);
19865  DONE:  
19866     @<Output the answer, |v| (which might have become |known|)@>;
19867   }
19868
19869 @ @<Add the known |value(p)| to the constant term of |v|@>=
19870
19871   while ( info(v)!=null ) v=link(v);
19872   value(v)=mp_slow_add(mp, value(p),value(v));
19873 }
19874
19875 @ @<Output the answer, |v| (which might have become |known|)@>=
19876 if ( q!=null ) mp_dep_finish(mp, v,q,t);
19877 else  { mp->cur_type=t; mp_dep_finish(mp, v,null,t); }
19878
19879 @ Here's the current situation: The dependency list |v| of type |t|
19880 should either be put into the current expression (if |q=null|) or
19881 into location |q| within a pair node (otherwise). The destination (|cur_exp|
19882 or |q|) formerly held a dependency list with the same
19883 final pointer as the list |v|.
19884
19885 @<Declare the procedure called |dep_finish|@>=
19886 void mp_dep_finish (MP mp, pointer v, pointer q, small_number t) {
19887   pointer p; /* the destination */
19888   scaled vv; /* the value, if it is |known| */
19889   if ( q==null ) p=mp->cur_exp; else p=q;
19890   dep_list(p)=v; type(p)=t;
19891   if ( info(v)==null ) { 
19892     vv=value(v);
19893     if ( q==null ) { 
19894       mp_flush_cur_exp(mp, vv);
19895     } else  { 
19896       mp_recycle_value(mp, p); type(q)=mp_known; value(q)=vv; 
19897     }
19898   } else if ( q==null ) {
19899     mp->cur_type=t;
19900   }
19901   if ( mp->fix_needed ) mp_fix_dependencies(mp);
19902 }
19903
19904 @ Let's turn now to the six basic relations of comparison.
19905
19906 @<Additional cases of binary operators@>=
19907 case less_than: case less_or_equal: case greater_than:
19908 case greater_or_equal: case equal_to: case unequal_to:
19909   check_arith; /* at this point |arith_error| should be |false|? */
19910   if ( (mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
19911     mp_add_or_subtract(mp, p,null,minus); /* |cur_exp:=(p)-cur_exp| */
19912   } else if ( mp->cur_type!=type(p) ) {
19913     mp_bad_binary(mp, p,c); goto DONE; 
19914   } else if ( mp->cur_type==mp_string_type ) {
19915     mp_flush_cur_exp(mp, mp_str_vs_str(mp, value(p),mp->cur_exp));
19916   } else if ((mp->cur_type==mp_unknown_string)||
19917            (mp->cur_type==mp_unknown_boolean) ) {
19918     @<Check if unknowns have been equated@>;
19919   } else if ( (mp->cur_type<=mp_pair_type)&&(mp->cur_type>=mp_transform_type)) {
19920     @<Reduce comparison of big nodes to comparison of scalars@>;
19921   } else if ( mp->cur_type==mp_boolean_type ) {
19922     mp_flush_cur_exp(mp, mp->cur_exp-value(p));
19923   } else { 
19924     mp_bad_binary(mp, p,c); goto DONE;
19925   }
19926   @<Compare the current expression with zero@>;
19927 DONE:  
19928   mp->arith_error=false; /* ignore overflow in comparisons */
19929   break;
19930
19931 @ @<Compare the current expression with zero@>=
19932 if ( mp->cur_type!=mp_known ) {
19933   if ( mp->cur_type<mp_known ) {
19934     mp_disp_err(mp, p,"");
19935     help1("The quantities shown above have not been equated.")
19936   } else  {
19937     help2("Oh dear. I can\'t decide if the expression above is positive,")
19938      ("negative, or zero. So this comparison test won't be `true'.");
19939   }
19940   exp_err("Unknown relation will be considered false");
19941 @.Unknown relation...@>
19942   mp_put_get_flush_error(mp, false_code);
19943 } else {
19944   switch (c) {
19945   case less_than: boolean_reset(mp->cur_exp<0); break;
19946   case less_or_equal: boolean_reset(mp->cur_exp<=0); break;
19947   case greater_than: boolean_reset(mp->cur_exp>0); break;
19948   case greater_or_equal: boolean_reset(mp->cur_exp>=0); break;
19949   case equal_to: boolean_reset(mp->cur_exp==0); break;
19950   case unequal_to: boolean_reset(mp->cur_exp!=0); break;
19951   }; /* there are no other cases */
19952 }
19953 mp->cur_type=mp_boolean_type
19954
19955 @ When two unknown strings are in the same ring, we know that they are
19956 equal. Otherwise, we don't know whether they are equal or not, so we
19957 make no change.
19958
19959 @<Check if unknowns have been equated@>=
19960
19961   q=value(mp->cur_exp);
19962   while ( (q!=mp->cur_exp)&&(q!=p) ) q=value(q);
19963   if ( q==p ) mp_flush_cur_exp(mp, 0);
19964 }
19965
19966 @ @<Reduce comparison of big nodes to comparison of scalars@>=
19967
19968   q=value(p); r=value(mp->cur_exp);
19969   rr=r+mp->big_node_size[mp->cur_type]-2;
19970   while (1) { mp_add_or_subtract(mp, q,r,minus);
19971     if ( type(r)!=mp_known ) break;
19972     if ( value(r)!=0 ) break;
19973     if ( r==rr ) break;
19974     q=q+2; r=r+2;
19975   }
19976   mp_take_part(mp, name_type(r)+x_part-mp_x_part_sector);
19977 }
19978
19979 @ Here we use the sneaky fact that |and_op-false_code=or_op-true_code|.
19980
19981 @<Additional cases of binary operators@>=
19982 case and_op:
19983 case or_op: 
19984   if ( (type(p)!=mp_boolean_type)||(mp->cur_type!=mp_boolean_type) )
19985     mp_bad_binary(mp, p,c);
19986   else if ( value(p)==c+false_code-and_op ) mp->cur_exp=value(p);
19987   break;
19988
19989 @ @<Additional cases of binary operators@>=
19990 case times: 
19991   if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
19992    mp_bad_binary(mp, p,times);
19993   } else if ( (mp->cur_type==mp_known)||(type(p)==mp_known) ) {
19994     @<Multiply when at least one operand is known@>;
19995   } else if ( (mp_nice_color_or_pair(mp, p,type(p))&&(mp->cur_type>mp_pair_type))
19996       ||(mp_nice_color_or_pair(mp, mp->cur_exp,mp->cur_type)&&
19997           (type(p)>mp_pair_type)) ) {
19998     mp_hard_times(mp, p); return;
19999   } else {
20000     mp_bad_binary(mp, p,times);
20001   }
20002   break;
20003
20004 @ @<Multiply when at least one operand is known@>=
20005
20006   if ( type(p)==mp_known ) {
20007     v=value(p); mp_free_node(mp, p,value_node_size); 
20008   } else {
20009     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20010   }
20011   if ( mp->cur_type==mp_known ) {
20012     mp->cur_exp=mp_take_scaled(mp, mp->cur_exp,v);
20013   } else if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_color_type)||
20014               (mp->cur_type==mp_cmykcolor_type) ) {
20015     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20016     do {  
20017        p=p-2; mp_dep_mult(mp, p,v,true);
20018     } while (p!=value(mp->cur_exp));
20019   } else {
20020     mp_dep_mult(mp, null,v,true);
20021   }
20022   return;
20023 }
20024
20025 @ @<Declare binary action...@>=
20026 void mp_dep_mult (MP mp,pointer p, integer v, boolean v_is_scaled) {
20027   pointer q; /* the dependency list being multiplied by |v| */
20028   small_number s,t; /* its type, before and after */
20029   if ( p==null ) {
20030     q=mp->cur_exp;
20031   } else if ( type(p)!=mp_known ) {
20032     q=p;
20033   } else { 
20034     if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
20035     else value(p)=mp_take_fraction(mp, value(p),v);
20036     return;
20037   };
20038   t=type(q); q=dep_list(q); s=t;
20039   if ( t==mp_dependent ) if ( v_is_scaled )
20040     if (mp_ab_vs_cd(mp, mp_max_coef(mp,q),abs(v),coef_bound-1,unity)>=0 ) 
20041       t=mp_proto_dependent;
20042   q=mp_p_times_v(mp, q,v,s,t,v_is_scaled); 
20043   mp_dep_finish(mp, q,p,t);
20044 }
20045
20046 @ Here is a routine that is similar to |times|; but it is invoked only
20047 internally, when |v| is a |fraction| whose magnitude is at most~1,
20048 and when |cur_type>=mp_color_type|.
20049
20050 @c void mp_frac_mult (MP mp,scaled n, scaled d) {
20051   /* multiplies |cur_exp| by |n/d| */
20052   pointer p; /* a pair node */
20053   pointer old_exp; /* a capsule to recycle */
20054   fraction v; /* |n/d| */
20055   if ( mp->internal[tracing_commands]>two ) {
20056     @<Trace the fraction multiplication@>;
20057   }
20058   switch (mp->cur_type) {
20059   case mp_transform_type:
20060   case mp_color_type:
20061   case mp_cmykcolor_type:
20062   case mp_pair_type:
20063    old_exp=mp_tarnished(mp, mp->cur_exp);
20064    break;
20065   case mp_independent: old_exp=diov; break;
20066   default: old_exp=null; break;
20067   }
20068   if ( old_exp!=null ) { 
20069      old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
20070   }
20071   v=mp_make_fraction(mp, n,d);
20072   if ( mp->cur_type==mp_known ) {
20073     mp->cur_exp=mp_take_fraction(mp, mp->cur_exp,v);
20074   } else if ( mp->cur_type<=mp_pair_type ) { 
20075     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20076     do {  
20077       p=p-2;
20078       mp_dep_mult(mp, p,v,false);
20079     } while (p!=value(mp->cur_exp));
20080   } else {
20081     mp_dep_mult(mp, null,v,false);
20082   }
20083   if ( old_exp!=null ) {
20084     mp_recycle_value(mp, old_exp); 
20085     mp_free_node(mp, old_exp,value_node_size);
20086   }
20087 }
20088
20089 @ @<Trace the fraction multiplication@>=
20090
20091   mp_begin_diagnostic(mp); 
20092   mp_print_nl(mp, "{("); mp_print_scaled(mp,n); mp_print_char(mp,'/');
20093   mp_print_scaled(mp,d); mp_print(mp,")*("); mp_print_exp(mp,null,0); 
20094   mp_print(mp,")}");
20095   mp_end_diagnostic(mp, false);
20096 }
20097
20098 @ The |hard_times| routine multiplies a nice color or pair by a dependency list.
20099
20100 @<Declare binary action procedures@>=
20101 void mp_hard_times (MP mp,pointer p) {
20102   pointer q; /* a copy of the dependent variable |p| */
20103   pointer r; /* a component of the big node for the nice color or pair */
20104   scaled v; /* the known value for |r| */
20105   if ( type(p)<=mp_pair_type ) { 
20106      q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p); p=q;
20107   }; /* now |cur_type=mp_pair_type| or |cur_type=mp_color_type| */
20108   r=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20109   while (1) { 
20110     r=r-2;
20111     v=value(r);
20112     type(r)=type(p);
20113     if ( r==value(mp->cur_exp) ) 
20114       break;
20115     mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(p)));
20116     mp_dep_mult(mp, r,v,true);
20117   }
20118   mp->mem[value_loc(r)]=mp->mem[value_loc(p)];
20119   link(prev_dep(p))=r;
20120   mp_free_node(mp, p,value_node_size);
20121   mp_dep_mult(mp, r,v,true);
20122 }
20123
20124 @ @<Additional cases of binary operators@>=
20125 case over: 
20126   if ( (mp->cur_type!=mp_known)||(type(p)<mp_color_type) ) {
20127     mp_bad_binary(mp, p,over);
20128   } else { 
20129     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20130     if ( v==0 ) {
20131       @<Squeal about division by zero@>;
20132     } else { 
20133       if ( mp->cur_type==mp_known ) {
20134         mp->cur_exp=mp_make_scaled(mp, mp->cur_exp,v);
20135       } else if ( mp->cur_type<=mp_pair_type ) { 
20136         p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20137         do {  
20138           p=p-2;  mp_dep_div(mp, p,v);
20139         } while (p!=value(mp->cur_exp));
20140       } else {
20141         mp_dep_div(mp, null,v);
20142       }
20143     }
20144     return;
20145   }
20146   break;
20147
20148 @ @<Declare binary action...@>=
20149 void mp_dep_div (MP mp,pointer p, scaled v) {
20150   pointer q; /* the dependency list being divided by |v| */
20151   small_number s,t; /* its type, before and after */
20152   if ( p==null ) q=mp->cur_exp;
20153   else if ( type(p)!=mp_known ) q=p;
20154   else { value(p)=mp_make_scaled(mp, value(p),v); return; };
20155   t=type(q); q=dep_list(q); s=t;
20156   if ( t==mp_dependent )
20157     if ( mp_ab_vs_cd(mp, mp_max_coef(mp,q),unity,coef_bound-1,abs(v))>=0 ) 
20158       t=mp_proto_dependent;
20159   q=mp_p_over_v(mp, q,v,s,t); 
20160   mp_dep_finish(mp, q,p,t);
20161 }
20162
20163 @ @<Squeal about division by zero@>=
20164
20165   exp_err("Division by zero");
20166 @.Division by zero@>
20167   help2("You're trying to divide the quantity shown above the error")
20168     ("message by zero. I'm going to divide it by one instead.");
20169   mp_put_get_error(mp);
20170 }
20171
20172 @ @<Additional cases of binary operators@>=
20173 case pythag_add:
20174 case pythag_sub: 
20175    if ( (mp->cur_type==mp_known)&&(type(p)==mp_known) ) {
20176      if ( c==pythag_add ) mp->cur_exp=mp_pyth_add(mp, value(p),mp->cur_exp);
20177      else mp->cur_exp=mp_pyth_sub(mp, value(p),mp->cur_exp);
20178    } else mp_bad_binary(mp, p,c);
20179    break;
20180
20181 @ The next few sections of the program deal with affine transformations
20182 of coordinate data.
20183
20184 @<Additional cases of binary operators@>=
20185 case rotated_by: case slanted_by:
20186 case scaled_by: case shifted_by: case transformed_by:
20187 case x_scaled: case y_scaled: case z_scaled:
20188   if ( type(p)==mp_path_type ) { 
20189     path_trans(c,p); return;
20190   } else if ( type(p)==mp_pen_type ) { 
20191     pen_trans(c,p);
20192     mp->cur_exp=mp_convex_hull(mp, mp->cur_exp); 
20193       /* rounding error could destroy convexity */
20194     return;
20195   } else if ( (type(p)==mp_pair_type)||(type(p)==mp_transform_type) ) {
20196     mp_big_trans(mp, p,c);
20197   } else if ( type(p)==mp_picture_type ) {
20198     mp_do_edges_trans(mp, p,c); return;
20199   } else {
20200     mp_bad_binary(mp, p,c);
20201   }
20202   break;
20203
20204 @ Let |c| be one of the eight transform operators. The procedure call
20205 |set_up_trans(c)| first changes |cur_exp| to a transform that corresponds to
20206 |c| and the original value of |cur_exp|. (In particular, |cur_exp| doesn't
20207 change at all if |c=transformed_by|.)
20208
20209 Then, if all components of the resulting transform are |known|, they are
20210 moved to the global variables |txx|, |txy|, |tyx|, |tyy|, |tx|, |ty|;
20211 and |cur_exp| is changed to the known value zero.
20212
20213 @<Declare binary action...@>=
20214 void mp_set_up_trans (MP mp,quarterword c) {
20215   pointer p,q,r; /* list manipulation registers */
20216   if ( (c!=transformed_by)||(mp->cur_type!=mp_transform_type) ) {
20217     @<Put the current transform into |cur_exp|@>;
20218   }
20219   @<If the current transform is entirely known, stash it in global variables;
20220     otherwise |return|@>;
20221 }
20222
20223 @ @<Glob...@>=
20224 scaled txx;
20225 scaled txy;
20226 scaled tyx;
20227 scaled tyy;
20228 scaled tx;
20229 scaled ty; /* current transform coefficients */
20230
20231 @ @<Put the current transform...@>=
20232
20233   p=mp_stash_cur_exp(mp); 
20234   mp->cur_exp=mp_id_transform(mp); 
20235   mp->cur_type=mp_transform_type;
20236   q=value(mp->cur_exp);
20237   switch (c) {
20238   @<For each of the eight cases, change the relevant fields of |cur_exp|
20239     and |goto done|;
20240     but do nothing if capsule |p| doesn't have the appropriate type@>;
20241   }; /* there are no other cases */
20242   mp_disp_err(mp, p,"Improper transformation argument");
20243 @.Improper transformation argument@>
20244   help3("The expression shown above has the wrong type,")
20245        ("so I can\'t transform anything using it.")
20246        ("Proceed, and I'll omit the transformation.");
20247   mp_put_get_error(mp);
20248 DONE: 
20249   mp_recycle_value(mp, p); 
20250   mp_free_node(mp, p,value_node_size);
20251 }
20252
20253 @ @<If the current transform is entirely known, ...@>=
20254 q=value(mp->cur_exp); r=q+transform_node_size;
20255 do {  
20256   r=r-2;
20257   if ( type(r)!=mp_known ) return;
20258 } while (r!=q);
20259 mp->txx=value(xx_part_loc(q));
20260 mp->txy=value(xy_part_loc(q));
20261 mp->tyx=value(yx_part_loc(q));
20262 mp->tyy=value(yy_part_loc(q));
20263 mp->tx=value(x_part_loc(q));
20264 mp->ty=value(y_part_loc(q));
20265 mp_flush_cur_exp(mp, 0)
20266
20267 @ @<For each of the eight cases...@>=
20268 case rotated_by:
20269   if ( type(p)==mp_known )
20270     @<Install sines and cosines, then |goto done|@>;
20271   break;
20272 case slanted_by:
20273   if ( type(p)>mp_pair_type ) { 
20274    mp_install(mp, xy_part_loc(q),p); goto DONE;
20275   };
20276   break;
20277 case scaled_by:
20278   if ( type(p)>mp_pair_type ) { 
20279     mp_install(mp, xx_part_loc(q),p); mp_install(mp, yy_part_loc(q),p); 
20280     goto DONE;
20281   };
20282   break;
20283 case shifted_by:
20284   if ( type(p)==mp_pair_type ) {
20285     r=value(p); mp_install(mp, x_part_loc(q),x_part_loc(r));
20286     mp_install(mp, y_part_loc(q),y_part_loc(r)); goto DONE;
20287   };
20288   break;
20289 case x_scaled:
20290   if ( type(p)>mp_pair_type ) {
20291     mp_install(mp, xx_part_loc(q),p); goto DONE;
20292   };
20293   break;
20294 case y_scaled:
20295   if ( type(p)>mp_pair_type ) {
20296     mp_install(mp, yy_part_loc(q),p); goto DONE;
20297   };
20298   break;
20299 case z_scaled:
20300   if ( type(p)==mp_pair_type )
20301     @<Install a complex multiplier, then |goto done|@>;
20302   break;
20303 case transformed_by:
20304   break;
20305   
20306
20307 @ @<Install sines and cosines, then |goto done|@>=
20308 { mp_n_sin_cos(mp, (value(p) % three_sixty_units)*16);
20309   value(xx_part_loc(q))=mp_round_fraction(mp, mp->n_cos);
20310   value(yx_part_loc(q))=mp_round_fraction(mp, mp->n_sin);
20311   value(xy_part_loc(q))=-value(yx_part_loc(q));
20312   value(yy_part_loc(q))=value(xx_part_loc(q));
20313   goto DONE;
20314 }
20315
20316 @ @<Install a complex multiplier, then |goto done|@>=
20317
20318   r=value(p);
20319   mp_install(mp, xx_part_loc(q),x_part_loc(r));
20320   mp_install(mp, yy_part_loc(q),x_part_loc(r));
20321   mp_install(mp, yx_part_loc(q),y_part_loc(r));
20322   if ( type(y_part_loc(r))==mp_known ) negate(value(y_part_loc(r)));
20323   else mp_negate_dep_list(mp, dep_list(y_part_loc(r)));
20324   mp_install(mp, xy_part_loc(q),y_part_loc(r));
20325   goto DONE;
20326 }
20327
20328 @ Procedure |set_up_known_trans| is like |set_up_trans|, but it
20329 insists that the transformation be entirely known.
20330
20331 @<Declare binary action...@>=
20332 void mp_set_up_known_trans (MP mp,quarterword c) { 
20333   mp_set_up_trans(mp, c);
20334   if ( mp->cur_type!=mp_known ) {
20335     exp_err("Transform components aren't all known");
20336 @.Transform components...@>
20337     help3("I'm unable to apply a partially specified transformation")
20338       ("except to a fully known pair or transform.")
20339       ("Proceed, and I'll omit the transformation.");
20340     mp_put_get_flush_error(mp, 0);
20341     mp->txx=unity; mp->txy=0; mp->tyx=0; mp->tyy=unity; 
20342     mp->tx=0; mp->ty=0;
20343   }
20344 }
20345
20346 @ Here's a procedure that applies the transform |txx..ty| to a pair of
20347 coordinates in locations |p| and~|q|.
20348
20349 @<Declare binary action...@>= 
20350 void mp_trans (MP mp,pointer p, pointer q) {
20351   scaled v; /* the new |x| value */
20352   v=mp_take_scaled(mp, mp->mem[p].sc,mp->txx)+
20353   mp_take_scaled(mp, mp->mem[q].sc,mp->txy)+mp->tx;
20354   mp->mem[q].sc=mp_take_scaled(mp, mp->mem[p].sc,mp->tyx)+
20355   mp_take_scaled(mp, mp->mem[q].sc,mp->tyy)+mp->ty;
20356   mp->mem[p].sc=v;
20357 }
20358
20359 @ The simplest transformation procedure applies a transform to all
20360 coordinates of a path.  The |path_trans(c)(p)| macro applies
20361 a transformation defined by |cur_exp| and the transform operator |c|
20362 to the path~|p|.
20363
20364 @d path_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20365                      mp_unstash_cur_exp(mp, (B)); 
20366                      mp_do_path_trans(mp, mp->cur_exp); }
20367
20368 @<Declare binary action...@>=
20369 void mp_do_path_trans (MP mp,pointer p) {
20370   pointer q; /* list traverser */
20371   q=p;
20372   do { 
20373     if ( left_type(q)!=endpoint ) 
20374       mp_trans(mp, q+3,q+4); /* that's |left_x| and |left_y| */
20375     mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20376     if ( right_type(q)!=endpoint ) 
20377       mp_trans(mp, q+5,q+6); /* that's |right_x| and |right_y| */
20378 @^data structure assumptions@>
20379     q=link(q);
20380   } while (q!=p);
20381 }
20382
20383 @ Transforming a pen is very similar, except that there are no |left_type|
20384 and |right_type| fields.
20385
20386 @d pen_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20387                     mp_unstash_cur_exp(mp, (B)); 
20388                     mp_do_pen_trans(mp, mp->cur_exp); }
20389
20390 @<Declare binary action...@>=
20391 void mp_do_pen_trans (MP mp,pointer p) {
20392   pointer q; /* list traverser */
20393   if ( pen_is_elliptical(p) ) {
20394     mp_trans(mp, p+3,p+4); /* that's |left_x| and |left_y| */
20395     mp_trans(mp, p+5,p+6); /* that's |right_x| and |right_y| */
20396   };
20397   q=p;
20398   do { 
20399     mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20400 @^data structure assumptions@>
20401     q=link(q);
20402   } while (q!=p);
20403 }
20404
20405 @ The next transformation procedure applies to edge structures. It will do
20406 any transformation, but the results may be substandard if the picture contains
20407 text that uses downloaded bitmap fonts.  The binary action procedure is
20408 |do_edges_trans|, but we also need a function that just scales a picture.
20409 That routine is |scale_edges|.  Both it and the underlying routine |edges_trans|
20410 should be thought of as procedures that update an edge structure |h|, except
20411 that they have to return a (possibly new) structure because of the need to call
20412 |private_edges|.
20413
20414 @<Declare binary action...@>=
20415 pointer mp_edges_trans (MP mp, pointer h) {
20416   pointer q; /* the object being transformed */
20417   pointer r,s; /* for list manipulation */
20418   scaled sx,sy; /* saved transformation parameters */
20419   scaled sqdet; /* square root of determinant for |dash_scale| */
20420   integer sgndet; /* sign of the determinant */
20421   scaled v; /* a temporary value */
20422   h=mp_private_edges(mp, h);
20423   sqdet=mp_sqrt_det(mp, mp->txx,mp->txy,mp->tyx,mp->tyy);
20424   sgndet=mp_ab_vs_cd(mp, mp->txx,mp->tyy,mp->txy,mp->tyx);
20425   if ( dash_list(h)!=null_dash ) {
20426     @<Try to transform the dash list of |h|@>;
20427   }
20428   @<Make the bounding box of |h| unknown if it can't be updated properly
20429     without scanning the whole structure@>;  
20430   q=link(dummy_loc(h));
20431   while ( q!=null ) { 
20432     @<Transform graphical object |q|@>;
20433     q=link(q);
20434   }
20435   return h;
20436 }
20437 void mp_do_edges_trans (MP mp,pointer p, quarterword c) { 
20438   mp_set_up_known_trans(mp, c);
20439   value(p)=mp_edges_trans(mp, value(p));
20440   mp_unstash_cur_exp(mp, p);
20441 }
20442 void mp_scale_edges (MP mp) { 
20443   mp->txx=mp->se_sf; mp->tyy=mp->se_sf;
20444   mp->txy=0; mp->tyx=0; mp->tx=0; mp->ty=0;
20445   mp->se_pic=mp_edges_trans(mp, mp->se_pic);
20446 }
20447
20448 @ @<Try to transform the dash list of |h|@>=
20449 if ( (mp->txy!=0)||(mp->tyx!=0)||
20450      (mp->ty!=0)||(abs(mp->txx)!=abs(mp->tyy))) {
20451   mp_flush_dash_list(mp, h);
20452 } else { 
20453   if ( mp->txx<0 ) { @<Reverse the dash list of |h|@>; } 
20454   @<Scale the dash list by |txx| and shift it by |tx|@>;
20455   dash_y(h)=mp_take_scaled(mp, dash_y(h),abs(mp->tyy));
20456 }
20457
20458 @ @<Reverse the dash list of |h|@>=
20459
20460   r=dash_list(h);
20461   dash_list(h)=null_dash;
20462   while ( r!=null_dash ) {
20463     s=r; r=link(r);
20464     v=start_x(s); start_x(s)=stop_x(s); stop_x(s)=v;
20465     link(s)=dash_list(h);
20466     dash_list(h)=s;
20467   }
20468 }
20469
20470 @ @<Scale the dash list by |txx| and shift it by |tx|@>=
20471 r=dash_list(h);
20472 while ( r!=null_dash ) {
20473   start_x(r)=mp_take_scaled(mp, start_x(r),mp->txx)+mp->tx;
20474   stop_x(r)=mp_take_scaled(mp, stop_x(r),mp->txx)+mp->tx;
20475   r=link(r);
20476 }
20477
20478 @ @<Make the bounding box of |h| unknown if it can't be updated properly...@>=
20479 if ( (mp->txx==0)&&(mp->tyy==0) ) {
20480   @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>;
20481 } else if ( (mp->txy!=0)||(mp->tyx!=0) ) {
20482   mp_init_bbox(mp, h);
20483   goto DONE1;
20484 }
20485 if ( minx_val(h)<=maxx_val(h) ) {
20486   @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift by
20487    |(tx,ty)|@>;
20488 }
20489 DONE1:
20490
20491
20492
20493 @ @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>=
20494
20495   v=minx_val(h); minx_val(h)=miny_val(h); miny_val(h)=v;
20496   v=maxx_val(h); maxx_val(h)=maxy_val(h); maxy_val(h)=v;
20497 }
20498
20499 @ The sum ``|txx+txy|'' is whichever of |txx| or |txy| is nonzero.  The other
20500 sum is similar.
20501
20502 @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift...@>=
20503
20504   minx_val(h)=mp_take_scaled(mp, minx_val(h),mp->txx+mp->txy)+mp->tx;
20505   maxx_val(h)=mp_take_scaled(mp, maxx_val(h),mp->txx+mp->txy)+mp->tx;
20506   miny_val(h)=mp_take_scaled(mp, miny_val(h),mp->tyx+mp->tyy)+mp->ty;
20507   maxy_val(h)=mp_take_scaled(mp, maxy_val(h),mp->tyx+mp->tyy)+mp->ty;
20508   if ( mp->txx+mp->txy<0 ) {
20509     v=minx_val(h); minx_val(h)=maxx_val(h); maxx_val(h)=v;
20510   }
20511   if ( mp->tyx+mp->tyy<0 ) {
20512     v=miny_val(h); miny_val(h)=maxy_val(h); maxy_val(h)=v;
20513   }
20514 }
20515
20516 @ Now we ready for the main task of transforming the graphical objects in edge
20517 structure~|h|.
20518
20519 @<Transform graphical object |q|@>=
20520 switch (type(q)) {
20521 case fill_code: case stroked_code: 
20522   mp_do_path_trans(mp, path_p(q));
20523   @<Transform |pen_p(q)|, making sure polygonal pens stay counter-clockwise@>;
20524   break;
20525 case mp_start_clip_code: case mp_start_bounds_code: 
20526   mp_do_path_trans(mp, path_p(q));
20527   break;
20528 case text_code: 
20529   r=text_tx_loc(q);
20530   @<Transform the compact transformation starting at |r|@>;
20531   break;
20532 case mp_stop_clip_code: case mp_stop_bounds_code: 
20533   break;
20534 } /* there are no other cases */
20535
20536 @ Note that the shift parameters |(tx,ty)| apply only to the path being stroked.
20537 The |dash_scale| has to be adjusted  to scale the dash lengths in |dash_p(q)|
20538 since the \ps\ output procedures will try to compensate for the transformation
20539 we are applying to |pen_p(q)|.  Since this compensation is based on the square
20540 root of the determinant, |sqdet| is the appropriate factor.
20541
20542 @<Transform |pen_p(q)|, making sure...@>=
20543 if ( pen_p(q)!=null ) {
20544   sx=mp->tx; sy=mp->ty;
20545   mp->tx=0; mp->ty=0;
20546   mp_do_pen_trans(mp, pen_p(q));
20547   if ( ((type(q)==stroked_code)&&(dash_p(q)!=null)) )
20548     dash_scale(q)=mp_take_scaled(mp, dash_scale(q),sqdet);
20549   if ( ! pen_is_elliptical(pen_p(q)) )
20550     if ( sgndet<0 )
20551       pen_p(q)=mp_make_pen(mp, mp_copy_path(mp, pen_p(q)),true); 
20552          /* this unreverses the pen */
20553   mp->tx=sx; mp->ty=sy;
20554 }
20555
20556 @ This uses the fact that transformations are stored in the order
20557 |(tx,ty,txx,txy,tyx,tyy)|.
20558 @^data structure assumptions@>
20559
20560 @<Transform the compact transformation starting at |r|@>=
20561 mp_trans(mp, r,r+1);
20562 sx=mp->tx; sy=mp->ty;
20563 mp->tx=0; mp->ty=0;
20564 mp_trans(mp, r+2,r+4);
20565 mp_trans(mp, r+3,r+5);
20566 mp->tx=sx; mp->ty=sy
20567
20568 @ The hard cases of transformation occur when big nodes are involved,
20569 and when some of their components are unknown.
20570
20571 @<Declare binary action...@>=
20572 @<Declare subroutines needed by |big_trans|@>;
20573 void mp_big_trans (MP mp,pointer p, quarterword c) {
20574   pointer q,r,pp,qq; /* list manipulation registers */
20575   small_number s; /* size of a big node */
20576   s=mp->big_node_size[type(p)]; q=value(p); r=q+s;
20577   do {  
20578     r=r-2;
20579     if ( type(r)!=mp_known ) {
20580       @<Transform an unknown big node and |return|@>;
20581     }
20582   } while (r!=q);
20583   @<Transform a known big node@>;
20584 }; /* node |p| will now be recycled by |do_binary| */
20585
20586 @ @<Transform an unknown big node and |return|@>=
20587
20588   mp_set_up_known_trans(mp, c); mp_make_exp_copy(mp, p); 
20589   r=value(mp->cur_exp);
20590   if ( mp->cur_type==mp_transform_type ) {
20591     mp_bilin1(mp, yy_part_loc(r),mp->tyy,xy_part_loc(q),mp->tyx,0);
20592     mp_bilin1(mp, yx_part_loc(r),mp->tyy,xx_part_loc(q),mp->tyx,0);
20593     mp_bilin1(mp, xy_part_loc(r),mp->txx,yy_part_loc(q),mp->txy,0);
20594     mp_bilin1(mp, xx_part_loc(r),mp->txx,yx_part_loc(q),mp->txy,0);
20595   }
20596   mp_bilin1(mp, y_part_loc(r),mp->tyy,x_part_loc(q),mp->tyx,mp->ty);
20597   mp_bilin1(mp, x_part_loc(r),mp->txx,y_part_loc(q),mp->txy,mp->tx);
20598   return;
20599 }
20600
20601 @ Let |p| point to a two-word value field inside a big node of |cur_exp|,
20602 and let |q| point to a another value field. The |bilin1| procedure
20603 replaces |p| by $p\cdot t+q\cdot u+\delta$.
20604
20605 @<Declare subroutines needed by |big_trans|@>=
20606 void mp_bilin1 (MP mp, pointer p, scaled t, pointer q, 
20607                 scaled u, scaled delta) {
20608   pointer r; /* list traverser */
20609   if ( t!=unity ) mp_dep_mult(mp, p,t,true);
20610   if ( u!=0 ) {
20611     if ( type(q)==mp_known ) {
20612       delta+=mp_take_scaled(mp, value(q),u);
20613     } else { 
20614       @<Ensure that |type(p)=mp_proto_dependent|@>;
20615       dep_list(p)=mp_p_plus_fq(mp, dep_list(p),u,dep_list(q),
20616                                mp_proto_dependent,type(q));
20617     }
20618   }
20619   if ( type(p)==mp_known ) {
20620     value(p)+=delta;
20621   } else {
20622     r=dep_list(p);
20623     while ( info(r)!=null ) r=link(r);
20624     delta+=value(r);
20625     if ( r!=dep_list(p) ) value(r)=delta;
20626     else { mp_recycle_value(mp, p); type(p)=mp_known; value(p)=delta; };
20627   }
20628   if ( mp->fix_needed ) mp_fix_dependencies(mp);
20629 }
20630
20631 @ @<Ensure that |type(p)=mp_proto_dependent|@>=
20632 if ( type(p)!=mp_proto_dependent ) {
20633   if ( type(p)==mp_known ) 
20634     mp_new_dep(mp, p,mp_const_dependency(mp, value(p)));
20635   else 
20636     dep_list(p)=mp_p_times_v(mp, dep_list(p),unity,mp_dependent,
20637                              mp_proto_dependent,true);
20638   type(p)=mp_proto_dependent;
20639 }
20640
20641 @ @<Transform a known big node@>=
20642 mp_set_up_trans(mp, c);
20643 if ( mp->cur_type==mp_known ) {
20644   @<Transform known by known@>;
20645 } else { 
20646   pp=mp_stash_cur_exp(mp); qq=value(pp);
20647   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20648   if ( mp->cur_type==mp_transform_type ) {
20649     mp_bilin2(mp, yy_part_loc(r),yy_part_loc(qq),
20650       value(xy_part_loc(q)),yx_part_loc(qq),null);
20651     mp_bilin2(mp, yx_part_loc(r),yy_part_loc(qq),
20652       value(xx_part_loc(q)),yx_part_loc(qq),null);
20653     mp_bilin2(mp, xy_part_loc(r),xx_part_loc(qq),
20654       value(yy_part_loc(q)),xy_part_loc(qq),null);
20655     mp_bilin2(mp, xx_part_loc(r),xx_part_loc(qq),
20656       value(yx_part_loc(q)),xy_part_loc(qq),null);
20657   };
20658   mp_bilin2(mp, y_part_loc(r),yy_part_loc(qq),
20659     value(x_part_loc(q)),yx_part_loc(qq),y_part_loc(qq));
20660   mp_bilin2(mp, x_part_loc(r),xx_part_loc(qq),
20661     value(y_part_loc(q)),xy_part_loc(qq),x_part_loc(qq));
20662   mp_recycle_value(mp, pp); mp_free_node(mp, pp,value_node_size);
20663 }
20664
20665 @ Let |p| be a |mp_proto_dependent| value whose dependency list ends
20666 at |dep_final|. The following procedure adds |v| times another
20667 numeric quantity to~|p|.
20668
20669 @<Declare subroutines needed by |big_trans|@>=
20670 void mp_add_mult_dep (MP mp,pointer p, scaled v, pointer r) { 
20671   if ( type(r)==mp_known ) {
20672     value(mp->dep_final)+=mp_take_scaled(mp, value(r),v);
20673   } else  { 
20674     dep_list(p)=mp_p_plus_fq(mp, dep_list(p),v,dep_list(r),
20675                                                          mp_proto_dependent,type(r));
20676     if ( mp->fix_needed ) mp_fix_dependencies(mp);
20677   }
20678 }
20679
20680 @ The |bilin2| procedure is something like |bilin1|, but with known
20681 and unknown quantities reversed. Parameter |p| points to a value field
20682 within the big node for |cur_exp|; and |type(p)=mp_known|. Parameters
20683 |t| and~|u| point to value fields elsewhere; so does parameter~|q|,
20684 unless it is |null| (which stands for zero). Location~|p| will be
20685 replaced by $p\cdot t+v\cdot u+q$.
20686
20687 @<Declare subroutines needed by |big_trans|@>=
20688 void mp_bilin2 (MP mp,pointer p, pointer t, scaled v, 
20689                 pointer u, pointer q) {
20690   scaled vv; /* temporary storage for |value(p)| */
20691   vv=value(p); type(p)=mp_proto_dependent;
20692   mp_new_dep(mp, p,mp_const_dependency(mp, 0)); /* this sets |dep_final| */
20693   if ( vv!=0 ) 
20694     mp_add_mult_dep(mp, p,vv,t); /* |dep_final| doesn't change */
20695   if ( v!=0 ) mp_add_mult_dep(mp, p,v,u);
20696   if ( q!=null ) mp_add_mult_dep(mp, p,unity,q);
20697   if ( dep_list(p)==mp->dep_final ) {
20698     vv=value(mp->dep_final); mp_recycle_value(mp, p);
20699     type(p)=mp_known; value(p)=vv;
20700   }
20701 }
20702
20703 @ @<Transform known by known@>=
20704
20705   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20706   if ( mp->cur_type==mp_transform_type ) {
20707     mp_bilin3(mp, yy_part_loc(r),mp->tyy,value(xy_part_loc(q)),mp->tyx,0);
20708     mp_bilin3(mp, yx_part_loc(r),mp->tyy,value(xx_part_loc(q)),mp->tyx,0);
20709     mp_bilin3(mp, xy_part_loc(r),mp->txx,value(yy_part_loc(q)),mp->txy,0);
20710     mp_bilin3(mp, xx_part_loc(r),mp->txx,value(yx_part_loc(q)),mp->txy,0);
20711   }
20712   mp_bilin3(mp, y_part_loc(r),mp->tyy,value(x_part_loc(q)),mp->tyx,mp->ty);
20713   mp_bilin3(mp, x_part_loc(r),mp->txx,value(y_part_loc(q)),mp->txy,mp->tx);
20714 }
20715
20716 @ Finally, in |bilin3| everything is |known|.
20717
20718 @<Declare subroutines needed by |big_trans|@>=
20719 void mp_bilin3 (MP mp,pointer p, scaled t, 
20720                scaled v, scaled u, scaled delta) { 
20721   if ( t!=unity )
20722     delta+=mp_take_scaled(mp, value(p),t);
20723   else 
20724     delta+=value(p);
20725   if ( u!=0 ) value(p)=delta+mp_take_scaled(mp, v,u);
20726   else value(p)=delta;
20727 }
20728
20729 @ @<Additional cases of binary operators@>=
20730 case concatenate: 
20731   if ( (mp->cur_type==mp_string_type)&&(type(p)==mp_string_type) ) mp_cat(mp, p);
20732   else mp_bad_binary(mp, p,concatenate);
20733   break;
20734 case substring_of: 
20735   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_string_type) )
20736     mp_chop_string(mp, value(p));
20737   else mp_bad_binary(mp, p,substring_of);
20738   break;
20739 case subpath_of: 
20740   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
20741   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_path_type) )
20742     mp_chop_path(mp, value(p));
20743   else mp_bad_binary(mp, p,subpath_of);
20744   break;
20745
20746 @ @<Declare binary action...@>=
20747 void mp_cat (MP mp,pointer p) {
20748   str_number a,b; /* the strings being concatenated */
20749   pool_pointer k; /* index into |str_pool| */
20750   a=value(p); b=mp->cur_exp; str_room(length(a)+length(b));
20751   for (k=mp->str_start[a];k<=str_stop(a)-1;k++) {
20752     append_char(mp->str_pool[k]);
20753   }
20754   for (k=mp->str_start[b];k<=str_stop(b)-1;k++) {
20755     append_char(mp->str_pool[k]);
20756   }
20757   mp->cur_exp=mp_make_string(mp); delete_str_ref(b);
20758 }
20759
20760 @ @<Declare binary action...@>=
20761 void mp_chop_string (MP mp,pointer p) {
20762   integer a, b; /* start and stop points */
20763   integer l; /* length of the original string */
20764   integer k; /* runs from |a| to |b| */
20765   str_number s; /* the original string */
20766   boolean reversed; /* was |a>b|? */
20767   a=mp_round_unscaled(mp, value(x_part_loc(p)));
20768   b=mp_round_unscaled(mp, value(y_part_loc(p)));
20769   if ( a<=b ) reversed=false;
20770   else  { reversed=true; k=a; a=b; b=k; };
20771   s=mp->cur_exp; l=length(s);
20772   if ( a<0 ) { 
20773     a=0;
20774     if ( b<0 ) b=0;
20775   }
20776   if ( b>l ) { 
20777     b=l;
20778     if ( a>l ) a=l;
20779   }
20780   str_room(b-a);
20781   if ( reversed ) {
20782     for (k=mp->str_start[s]+b-1;k>=mp->str_start[s]+a;k--)  {
20783       append_char(mp->str_pool[k]);
20784     }
20785   } else  {
20786     for (k=mp->str_start[s]+a;k<=mp->str_start[s]+b-1;k++)  {
20787       append_char(mp->str_pool[k]);
20788     }
20789   }
20790   mp->cur_exp=mp_make_string(mp); delete_str_ref(s);
20791 }
20792
20793 @ @<Declare binary action...@>=
20794 void mp_chop_path (MP mp,pointer p) {
20795   pointer q; /* a knot in the original path */
20796   pointer pp,qq,rr,ss; /* link variables for copies of path nodes */
20797   scaled a,b,k,l; /* indices for chopping */
20798   boolean reversed; /* was |a>b|? */
20799   l=mp_path_length(mp); a=value(x_part_loc(p)); b=value(y_part_loc(p));
20800   if ( a<=b ) reversed=false;
20801   else  { reversed=true; k=a; a=b; b=k; };
20802   @<Dispense with the cases |a<0| and/or |b>l|@>;
20803   q=mp->cur_exp;
20804   while ( a>=unity ) {
20805     q=link(q); a=a-unity; b=b-unity;
20806   }
20807   if ( b==a ) {
20808     @<Construct a path from |pp| to |qq| of length zero@>; 
20809   } else { 
20810     @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>; 
20811   }
20812   left_type(pp)=endpoint; right_type(qq)=endpoint; link(qq)=pp;
20813   mp_toss_knot_list(mp, mp->cur_exp);
20814   if ( reversed ) {
20815     mp->cur_exp=link(mp_htap_ypoc(mp, pp)); mp_toss_knot_list(mp, pp);
20816   } else {
20817     mp->cur_exp=pp;
20818   }
20819 }
20820
20821 @ @<Dispense with the cases |a<0| and/or |b>l|@>=
20822 if ( a<0 ) {
20823   if ( left_type(mp->cur_exp)==endpoint ) {
20824     a=0; if ( b<0 ) b=0;
20825   } else  {
20826     do {  a=a+l; b=b+l; } while (a<0); /* a cycle always has length |l>0| */
20827   }
20828 }
20829 if ( b>l ) {
20830   if ( left_type(mp->cur_exp)==endpoint ) {
20831     b=l; if ( a>l ) a=l;
20832   } else {
20833     while ( a>=l ) { 
20834       a=a-l; b=b-l;
20835     }
20836   }
20837 }
20838
20839 @ @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>=
20840
20841   pp=mp_copy_knot(mp, q); qq=pp;
20842   do {  
20843     q=link(q); rr=qq; qq=mp_copy_knot(mp, q); link(rr)=qq; b=b-unity;
20844   } while (b>0);
20845   if ( a>0 ) {
20846     ss=pp; pp=link(pp);
20847     mp_split_cubic(mp, ss,a*010000); pp=link(ss);
20848     mp_free_node(mp, ss,knot_node_size);
20849     if ( rr==ss ) {
20850       b=mp_make_scaled(mp, b,unity-a); rr=pp;
20851     }
20852   }
20853   if ( b<0 ) {
20854     mp_split_cubic(mp, rr,(b+unity)*010000);
20855     mp_free_node(mp, qq,knot_node_size);
20856     qq=link(rr);
20857   }
20858 }
20859
20860 @ @<Construct a path from |pp| to |qq| of length zero@>=
20861
20862   if ( a>0 ) { mp_split_cubic(mp, q,a*010000); q=link(q); };
20863   pp=mp_copy_knot(mp, q); qq=pp;
20864 }
20865
20866 @ @<Additional cases of binary operators@>=
20867 case point_of: case precontrol_of: case postcontrol_of: 
20868   if ( mp->cur_type==mp_pair_type )
20869      mp_pair_to_path(mp);
20870   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
20871     mp_find_point(mp, value(p),c);
20872   else 
20873     mp_bad_binary(mp, p,c);
20874   break;
20875 case pen_offset_of: 
20876   if ( (mp->cur_type==mp_pen_type)&& mp_nice_pair(mp, p,type(p)) )
20877     mp_set_up_offset(mp, value(p));
20878   else 
20879     mp_bad_binary(mp, p,pen_offset_of);
20880   break;
20881 case direction_time_of: 
20882   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
20883   if ( (mp->cur_type==mp_path_type)&& mp_nice_pair(mp, p,type(p)) )
20884     mp_set_up_direction_time(mp, value(p));
20885   else 
20886     mp_bad_binary(mp, p,direction_time_of);
20887   break;
20888
20889 @ @<Declare binary action...@>=
20890 void mp_set_up_offset (MP mp,pointer p) { 
20891   mp_find_offset(mp, value(x_part_loc(p)),value(y_part_loc(p)),mp->cur_exp);
20892   mp_pair_value(mp, mp->cur_x,mp->cur_y);
20893 }
20894 void mp_set_up_direction_time (MP mp,pointer p) { 
20895   mp_flush_cur_exp(mp, mp_find_direction_time(mp, value(x_part_loc(p)),
20896   value(y_part_loc(p)),mp->cur_exp));
20897 }
20898
20899 @ @<Declare binary action...@>=
20900 void mp_find_point (MP mp,scaled v, quarterword c) {
20901   pointer p; /* the path */
20902   scaled n; /* its length */
20903   p=mp->cur_exp;
20904   if ( left_type(p)==endpoint ) n=-unity; else n=0;
20905   do {  p=link(p); n=n+unity; } while (p!=mp->cur_exp);
20906   if ( n==0 ) { 
20907     v=0; 
20908   } else if ( v<0 ) {
20909     if ( left_type(p)==endpoint ) v=0;
20910     else v=n-1-((-v-1) % n);
20911   } else if ( v>n ) {
20912     if ( left_type(p)==endpoint ) v=n;
20913     else v=v % n;
20914   }
20915   p=mp->cur_exp;
20916   while ( v>=unity ) { p=link(p); v=v-unity;  };
20917   if ( v!=0 ) {
20918      @<Insert a fractional node by splitting the cubic@>;
20919   }
20920   @<Set the current expression to the desired path coordinates@>;
20921 }
20922
20923 @ @<Insert a fractional node...@>=
20924 { mp_split_cubic(mp, p,v*010000); p=link(p); }
20925
20926 @ @<Set the current expression to the desired path coordinates...@>=
20927 switch (c) {
20928 case point_of: 
20929   mp_pair_value(mp, x_coord(p),y_coord(p));
20930   break;
20931 case precontrol_of: 
20932   if ( left_type(p)==endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
20933   else mp_pair_value(mp, left_x(p),left_y(p));
20934   break;
20935 case postcontrol_of: 
20936   if ( right_type(p)==endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
20937   else mp_pair_value(mp, right_x(p),right_y(p));
20938   break;
20939 } /* there are no other cases */
20940
20941 @ @<Additional cases of binary operators@>=
20942 case arc_time_of: 
20943   if ( mp->cur_type==mp_pair_type )
20944      mp_pair_to_path(mp);
20945   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
20946     mp_flush_cur_exp(mp, mp_get_arc_time(mp, mp->cur_exp,value(p)));
20947   else 
20948     mp_bad_binary(mp, p,c);
20949   break;
20950
20951 @ @<Additional cases of bin...@>=
20952 case intersect: 
20953   if ( type(p)==mp_pair_type ) {
20954     q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p);
20955     mp_pair_to_path(mp); p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
20956   };
20957   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
20958   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_path_type) ) {
20959     mp_path_intersection(mp, value(p),mp->cur_exp);
20960     mp_pair_value(mp, mp->cur_t,mp->cur_tt);
20961   } else {
20962     mp_bad_binary(mp, p,intersect);
20963   }
20964   break;
20965
20966 @ @<Additional cases of bin...@>=
20967 case in_font:
20968   if ( (mp->cur_type!=mp_string_type)||(type(p)!=mp_string_type)) 
20969     mp_bad_binary(mp, p,in_font);
20970   else { mp_do_infont(mp, p); return; }
20971   break;
20972
20973 @ Function |new_text_node| owns the reference count for its second argument
20974 (the text string) but not its first (the font name).
20975
20976 @<Declare binary action...@>=
20977 void mp_do_infont (MP mp,pointer p) {
20978   pointer q;
20979   q=mp_get_node(mp, edge_header_size);
20980   mp_init_edges(mp, q);
20981   link(obj_tail(q))=mp_new_text_node(mp, str(mp->cur_exp),value(p));
20982   obj_tail(q)=link(obj_tail(q));
20983   mp_free_node(mp, p,value_node_size);
20984   mp_flush_cur_exp(mp, q);
20985   mp->cur_type=mp_picture_type;
20986 }
20987
20988 @* \[40] Statements and commands.
20989 The chief executive of \MP\ is the |do_statement| routine, which
20990 contains the master switch that causes all the various pieces of \MP\
20991 to do their things, in the right order.
20992
20993 In a sense, this is the grand climax of the program: It applies all the
20994 tools that we have worked so hard to construct. In another sense, this is
20995 the messiest part of the program: It necessarily refers to other pieces
20996 of code all over the place, so that a person can't fully understand what is
20997 going on without paging back and forth to be reminded of conventions that
20998 are defined elsewhere. We are now at the hub of the web.
20999
21000 The structure of |do_statement| itself is quite simple.  The first token
21001 of the statement is fetched using |get_x_next|.  If it can be the first
21002 token of an expression, we look for an equation, an assignment, or a
21003 title. Otherwise we use a \&{case} construction to branch at high speed to
21004 the appropriate routine for various and sundry other types of commands,
21005 each of which has an ``action procedure'' that does the necessary work.
21006
21007 The program uses the fact that
21008 $$\hbox{|min_primary_command=max_statement_command=type_name|}$$
21009 to interpret a statement that starts with, e.g., `\&{string}',
21010 as a type declaration rather than a boolean expression.
21011
21012 @c void mp_do_statement (MP mp) { /* governs \MP's activities */
21013   mp->cur_type=mp_vacuous; mp_get_x_next(mp);
21014   if ( mp->cur_cmd>max_primary_command ) {
21015     @<Worry about bad statement@>;
21016   } else if ( mp->cur_cmd>max_statement_command ) {
21017     @<Do an equation, assignment, title, or
21018      `$\langle\,$expression$\,\rangle\,$\&{endgroup}'@>;
21019   } else {
21020     @<Do a statement that doesn't begin with an expression@>;
21021   }
21022   if ( mp->cur_cmd<semicolon )
21023     @<Flush unparsable junk that was found after the statement@>;
21024   mp->error_count=0;
21025 }
21026
21027 @ @<Declarations@>=
21028 @<Declare action procedures for use by |do_statement|@>;
21029
21030 @ The only command codes |>max_primary_command| that can be present
21031 at the beginning of a statement are |semicolon| and higher; these
21032 occur when the statement is null.
21033
21034 @<Worry about bad statement@>=
21035
21036   if ( mp->cur_cmd<semicolon ) {
21037     print_err("A statement can't begin with `");
21038 @.A statement can't begin with x@>
21039     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); mp_print_char(mp, '\'');
21040     help5("I was looking for the beginning of a new statement.")
21041       ("If you just proceed without changing anything, I'll ignore")
21042       ("everything up to the next `;'. Please insert a semicolon")
21043       ("now in front of anything that you don't want me to delete.")
21044       ("(See Chapter 27 of The METAFONTbook for an example.)");
21045 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21046     mp_back_error(mp); mp_get_x_next(mp);
21047   }
21048 }
21049
21050 @ The help message printed here says that everything is flushed up to
21051 a semicolon, but actually the commands |end_group| and |stop| will
21052 also terminate a statement.
21053
21054 @<Flush unparsable junk that was found after the statement@>=
21055
21056   print_err("Extra tokens will be flushed");
21057 @.Extra tokens will be flushed@>
21058   help6("I've just read as much of that statement as I could fathom,")
21059        ("so a semicolon should have been next. It's very puzzling...")
21060        ("but I'll try to get myself back together, by ignoring")
21061        ("everything up to the next `;'. Please insert a semicolon")
21062        ("now in front of anything that you don't want me to delete.")
21063        ("(See Chapter 27 of The METAFONTbook for an example.)");
21064 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21065   mp_back_error(mp); mp->scanner_status=flushing;
21066   do {  
21067     get_t_next;
21068     @<Decrease the string reference count...@>;
21069   } while (! end_of_statement); /* |cur_cmd=semicolon|, |end_group|, or |stop| */
21070   mp->scanner_status=normal;
21071 }
21072
21073 @ If |do_statement| ends with |cur_cmd=end_group|, we should have
21074 |cur_type=mp_vacuous| unless the statement was simply an expression;
21075 in the latter case, |cur_type| and |cur_exp| should represent that
21076 expression.
21077
21078 @<Do a statement that doesn't...@>=
21079
21080   if ( mp->internal[tracing_commands]>0 ) 
21081     show_cur_cmd_mod;
21082   switch (mp->cur_cmd ) {
21083   case type_name:mp_do_type_declaration(mp); break;
21084   case macro_def:
21085     if ( mp->cur_mod>var_def ) mp_make_op_def(mp);
21086     else if ( mp->cur_mod>end_def ) mp_scan_def(mp);
21087      break;
21088   @<Cases of |do_statement| that invoke particular commands@>;
21089   } /* there are no other cases */
21090   mp->cur_type=mp_vacuous;
21091 }
21092
21093 @ The most important statements begin with expressions.
21094
21095 @<Do an equation, assignment, title, or...@>=
21096
21097   mp->var_flag=assignment; mp_scan_expression(mp);
21098   if ( mp->cur_cmd<end_group ) {
21099     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21100     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21101     else if ( mp->cur_type==mp_string_type ) {@<Do a title@> ; }
21102     else if ( mp->cur_type!=mp_vacuous ){ 
21103       exp_err("Isolated expression");
21104 @.Isolated expression@>
21105       help3("I couldn't find an `=' or `:=' after the")
21106         ("expression that is shown above this error message,")
21107         ("so I guess I'll just ignore it and carry on.");
21108       mp_put_get_error(mp);
21109     }
21110     mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous;
21111   }
21112 }
21113
21114 @ @<Do a title@>=
21115
21116   if ( mp->internal[tracing_titles]>0 ) {
21117     mp_print_nl(mp, "");  mp_print_str(mp, mp->cur_exp); update_terminal;
21118   }
21119 }
21120
21121 @ Equations and assignments are performed by the pair of mutually recursive
21122 @^recursion@>
21123 routines |do_equation| and |do_assignment|. These routines are called when
21124 |cur_cmd=equals| and when |cur_cmd=assignment|, respectively; the left-hand
21125 side is in |cur_type| and |cur_exp|, while the right-hand side is yet
21126 to be scanned. After the routines are finished, |cur_type| and |cur_exp|
21127 will be equal to the right-hand side (which will normally be equal
21128 to the left-hand side).
21129
21130 @<Declare action procedures for use by |do_statement|@>=
21131 @<Declare the procedure called |try_eq|@>;
21132 @<Declare the procedure called |make_eq|@>;
21133 void mp_do_equation (MP mp) ;
21134
21135 @ @c
21136 void mp_do_equation (MP mp) {
21137   pointer lhs; /* capsule for the left-hand side */
21138   pointer p; /* temporary register */
21139   lhs=mp_stash_cur_exp(mp); mp_get_x_next(mp); 
21140   mp->var_flag=assignment; mp_scan_expression(mp);
21141   if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21142   else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21143   if ( mp->internal[tracing_commands]>two ) 
21144     @<Trace the current equation@>;
21145   if ( mp->cur_type==mp_unknown_path ) if ( type(lhs)==mp_pair_type ) {
21146     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, lhs); lhs=p;
21147   }; /* in this case |make_eq| will change the pair to a path */
21148   mp_make_eq(mp, lhs); /* equate |lhs| to |(cur_type,cur_exp)| */
21149 }
21150
21151 @ And |do_assignment| is similar to |do_expression|:
21152
21153 @<Declarations@>=
21154 void mp_do_assignment (MP mp);
21155
21156 @ @<Declare action procedures for use by |do_statement|@>=
21157 void mp_do_assignment (MP mp) ;
21158
21159 @ @c
21160 void mp_do_assignment (MP mp) {
21161   pointer lhs; /* token list for the left-hand side */
21162   pointer p; /* where the left-hand value is stored */
21163   pointer q; /* temporary capsule for the right-hand value */
21164   if ( mp->cur_type!=mp_token_list ) { 
21165     exp_err("Improper `:=' will be changed to `='");
21166 @.Improper `:='@>
21167     help2("I didn't find a variable name at the left of the `:=',")
21168       ("so I'm going to pretend that you said `=' instead.");
21169     mp_error(mp); mp_do_equation(mp);
21170   } else { 
21171     lhs=mp->cur_exp; mp->cur_type=mp_vacuous;
21172     mp_get_x_next(mp); mp->var_flag=assignment; mp_scan_expression(mp);
21173     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21174     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21175     if ( mp->internal[tracing_commands]>two ) 
21176       @<Trace the current assignment@>;
21177     if ( info(lhs)>hash_end ) {
21178       @<Assign the current expression to an internal variable@>;
21179     } else  {
21180       @<Assign the current expression to the variable |lhs|@>;
21181     }
21182     mp_flush_node_list(mp, lhs);
21183   }
21184 }
21185
21186 @ @<Trace the current equation@>=
21187
21188   mp_begin_diagnostic(mp); mp_print_nl(mp, "{("); mp_print_exp(mp,lhs,0);
21189   mp_print(mp,")=("); mp_print_exp(mp,null,0); 
21190   mp_print(mp,")}"); mp_end_diagnostic(mp, false);
21191 }
21192
21193 @ @<Trace the current assignment@>=
21194
21195   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
21196   if ( info(lhs)>hash_end ) 
21197      mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21198   else 
21199      mp_show_token_list(mp, lhs,null,1000,0);
21200   mp_print(mp, ":="); mp_print_exp(mp, null,0); 
21201   mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
21202 }
21203
21204 @ @<Assign the current expression to an internal variable@>=
21205 if ( mp->cur_type==mp_known )  {
21206   mp->internal[info(lhs)-(hash_end)]=mp->cur_exp;
21207 } else { 
21208   exp_err("Internal quantity `");
21209 @.Internal quantity...@>
21210   mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21211   mp_print(mp, "' must receive a known value");
21212   help2("I can\'t set an internal quantity to anything but a known")
21213     ("numeric value, so I'll have to ignore this assignment.");
21214   mp_put_get_error(mp);
21215 }
21216
21217 @ @<Assign the current expression to the variable |lhs|@>=
21218
21219   p=mp_find_variable(mp, lhs);
21220   if ( p!=null ) {
21221     q=mp_stash_cur_exp(mp); mp->cur_type=mp_und_type(mp, p); 
21222     mp_recycle_value(mp, p);
21223     type(p)=mp->cur_type; value(p)=null; mp_make_exp_copy(mp, p);
21224     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q); mp_make_eq(mp, p);
21225   } else  { 
21226     mp_obliterated(mp, lhs); mp_put_get_error(mp);
21227   }
21228 }
21229
21230
21231 @ And now we get to the nitty-gritty. The |make_eq| procedure is given
21232 a pointer to a capsule that is to be equated to the current expression.
21233
21234 @<Declare the procedure called |make_eq|@>=
21235 void mp_make_eq (MP mp,pointer lhs) ;
21236
21237
21238
21239 @c void mp_make_eq (MP mp,pointer lhs) {
21240   small_number t; /* type of the left-hand side */
21241   pointer p,q; /* pointers inside of big nodes */
21242   integer v=0; /* value of the left-hand side */
21243 RESTART: 
21244   t=type(lhs);
21245   if ( t<=mp_pair_type ) v=value(lhs);
21246   switch (t) {
21247   @<For each type |t|, make an equation and |goto done| unless |cur_type|
21248     is incompatible with~|t|@>;
21249   } /* all cases have been listed */
21250   @<Announce that the equation cannot be performed@>;
21251 DONE:
21252   check_arith; mp_recycle_value(mp, lhs); 
21253   mp_free_node(mp, lhs,value_node_size);
21254 }
21255
21256 @ @<Announce that the equation cannot be performed@>=
21257 mp_disp_err(mp, lhs,""); 
21258 exp_err("Equation cannot be performed (");
21259 @.Equation cannot be performed@>
21260 if ( type(lhs)<=mp_pair_type ) mp_print_type(mp, type(lhs));
21261 else mp_print(mp, "numeric");
21262 mp_print_char(mp, '=');
21263 if ( mp->cur_type<=mp_pair_type ) mp_print_type(mp, mp->cur_type);
21264 else mp_print(mp, "numeric");
21265 mp_print_char(mp, ')');
21266 help2("I'm sorry, but I don't know how to make such things equal.")
21267      ("(See the two expressions just above the error message.)");
21268 mp_put_get_error(mp)
21269
21270 @ @<For each type |t|, make an equation and |goto done| unless...@>=
21271 case mp_boolean_type: case mp_string_type: case mp_pen_type:
21272 case mp_path_type: case mp_picture_type:
21273   if ( mp->cur_type==t+unknown_tag ) { 
21274     mp_nonlinear_eq(mp, v,mp->cur_exp,false); goto DONE;
21275   } else if ( mp->cur_type==t ) {
21276     @<Report redundant or inconsistent equation and |goto done|@>;
21277   }
21278   break;
21279 case unknown_types:
21280   if ( mp->cur_type==t-unknown_tag ) { 
21281     mp_nonlinear_eq(mp, mp->cur_exp,lhs,true); goto DONE;
21282   } else if ( mp->cur_type==t ) { 
21283     mp_ring_merge(mp, lhs,mp->cur_exp); goto DONE;
21284   } else if ( mp->cur_type==mp_pair_type ) {
21285     if ( t==mp_unknown_path ) { 
21286      mp_pair_to_path(mp); goto RESTART;
21287     };
21288   }
21289   break;
21290 case mp_transform_type: case mp_color_type:
21291 case mp_cmykcolor_type: case mp_pair_type:
21292   if ( mp->cur_type==t ) {
21293     @<Do multiple equations and |goto done|@>;
21294   }
21295   break;
21296 case mp_known: case mp_dependent:
21297 case mp_proto_dependent: case mp_independent:
21298   if ( mp->cur_type>=mp_known ) { 
21299     mp_try_eq(mp, lhs,null); goto DONE;
21300   };
21301   break;
21302 case mp_vacuous:
21303   break;
21304
21305 @ @<Report redundant or inconsistent equation and |goto done|@>=
21306
21307   if ( mp->cur_type<=mp_string_type ) {
21308     if ( mp->cur_type==mp_string_type ) {
21309       if ( mp_str_vs_str(mp, v,mp->cur_exp)!=0 ) {
21310         goto NOT_FOUND;
21311       }
21312     } else if ( v!=mp->cur_exp ) {
21313       goto NOT_FOUND;
21314     }
21315     @<Exclaim about a redundant equation@>; goto DONE;
21316   }
21317   print_err("Redundant or inconsistent equation");
21318 @.Redundant or inconsistent equation@>
21319   help2("An equation between already-known quantities can't help.")
21320        ("But don't worry; continue and I'll just ignore it.");
21321   mp_put_get_error(mp); goto DONE;
21322 NOT_FOUND: 
21323   print_err("Inconsistent equation");
21324 @.Inconsistent equation@>
21325   help2("The equation I just read contradicts what was said before.")
21326        ("But don't worry; continue and I'll just ignore it.");
21327   mp_put_get_error(mp); goto DONE;
21328 }
21329
21330 @ @<Do multiple equations and |goto done|@>=
21331
21332   p=v+mp->big_node_size[t]; 
21333   q=value(mp->cur_exp)+mp->big_node_size[t];
21334   do {  
21335     p=p-2; q=q-2; mp_try_eq(mp, p,q);
21336   } while (p!=v);
21337   goto DONE;
21338 }
21339
21340 @ The first argument to |try_eq| is the location of a value node
21341 in a capsule that will soon be recycled. The second argument is
21342 either a location within a pair or transform node pointed to by
21343 |cur_exp|, or it is |null| (which means that |cur_exp| itself
21344 serves as the second argument). The idea is to leave |cur_exp| unchanged,
21345 but to equate the two operands.
21346
21347 @<Declare the procedure called |try_eq|@>=
21348 void mp_try_eq (MP mp,pointer l, pointer r) ;
21349
21350
21351 @c void mp_try_eq (MP mp,pointer l, pointer r) {
21352   pointer p; /* dependency list for right operand minus left operand */
21353   int t; /* the type of list |p| */
21354   pointer q; /* the constant term of |p| is here */
21355   pointer pp; /* dependency list for right operand */
21356   int tt; /* the type of list |pp| */
21357   boolean copied; /* have we copied a list that ought to be recycled? */
21358   @<Remove the left operand from its container, negate it, and
21359     put it into dependency list~|p| with constant term~|q|@>;
21360   @<Add the right operand to list |p|@>;
21361   if ( info(p)==null ) {
21362     @<Deal with redundant or inconsistent equation@>;
21363   } else { 
21364     mp_linear_eq(mp, p,t);
21365     if ( r==null ) if ( mp->cur_type!=mp_known ) {
21366       if ( type(mp->cur_exp)==mp_known ) {
21367         pp=mp->cur_exp; mp->cur_exp=value(mp->cur_exp); mp->cur_type=mp_known;
21368         mp_free_node(mp, pp,value_node_size);
21369       }
21370     }
21371   }
21372 }
21373
21374 @ @<Remove the left operand from its container, negate it, and...@>=
21375 t=type(l);
21376 if ( t==mp_known ) { 
21377   t=mp_dependent; p=mp_const_dependency(mp, -value(l)); q=p;
21378 } else if ( t==mp_independent ) {
21379   t=mp_dependent; p=mp_single_dependency(mp, l); negate(value(p));
21380   q=mp->dep_final;
21381 } else { 
21382   p=dep_list(l); q=p;
21383   while (1) { 
21384     negate(value(q));
21385     if ( info(q)==null ) break;
21386     q=link(q);
21387   }
21388   link(prev_dep(l))=link(q); prev_dep(link(q))=prev_dep(l);
21389   type(l)=mp_known;
21390 }
21391
21392 @ @<Deal with redundant or inconsistent equation@>=
21393
21394   if ( abs(value(p))>64 ) { /* off by .001 or more */
21395     print_err("Inconsistent equation");
21396 @.Inconsistent equation@>
21397     mp_print(mp, " (off by "); mp_print_scaled(mp, value(p)); 
21398     mp_print_char(mp, ')');
21399     help2("The equation I just read contradicts what was said before.")
21400       ("But don't worry; continue and I'll just ignore it.");
21401     mp_put_get_error(mp);
21402   } else if ( r==null ) {
21403     @<Exclaim about a redundant equation@>;
21404   }
21405   mp_free_node(mp, p,dep_node_size);
21406 }
21407
21408 @ @<Add the right operand to list |p|@>=
21409 if ( r==null ) {
21410   if ( mp->cur_type==mp_known ) {
21411     value(q)=value(q)+mp->cur_exp; goto DONE1;
21412   } else { 
21413     tt=mp->cur_type;
21414     if ( tt==mp_independent ) pp=mp_single_dependency(mp, mp->cur_exp);
21415     else pp=dep_list(mp->cur_exp);
21416   } 
21417 } else {
21418   if ( type(r)==mp_known ) {
21419     value(q)=value(q)+value(r); goto DONE1;
21420   } else { 
21421     tt=type(r);
21422     if ( tt==mp_independent ) pp=mp_single_dependency(mp, r);
21423     else pp=dep_list(r);
21424   }
21425 }
21426 if ( tt!=mp_independent ) copied=false;
21427 else  { copied=true; tt=mp_dependent; };
21428 @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>;
21429 if ( copied ) mp_flush_node_list(mp, pp);
21430 DONE1:
21431
21432 @ @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>=
21433 mp->watch_coefs=false;
21434 if ( t==tt ) {
21435   p=mp_p_plus_q(mp, p,pp,t);
21436 } else if ( t==mp_proto_dependent ) {
21437   p=mp_p_plus_fq(mp, p,unity,pp,mp_proto_dependent,mp_dependent);
21438 } else { 
21439   q=p;
21440   while ( info(q)!=null ) {
21441     value(q)=mp_round_fraction(mp, value(q)); q=link(q);
21442   }
21443   t=mp_proto_dependent; p=mp_p_plus_q(mp, p,pp,t);
21444 }
21445 mp->watch_coefs=true;
21446
21447 @ Our next goal is to process type declarations. For this purpose it's
21448 convenient to have a procedure that scans a $\langle\,$declared
21449 variable$\,\rangle$ and returns the corresponding token list. After the
21450 following procedure has acted, the token after the declared variable
21451 will have been scanned, so it will appear in |cur_cmd|, |cur_mod|,
21452 and~|cur_sym|.
21453
21454 @<Declare the function called |scan_declared_variable|@>=
21455 pointer mp_scan_declared_variable (MP mp) {
21456   pointer x; /* hash address of the variable's root */
21457   pointer h,t; /* head and tail of the token list to be returned */
21458   pointer l; /* hash address of left bracket */
21459   mp_get_symbol(mp); x=mp->cur_sym;
21460   if ( mp->cur_cmd!=tag_token ) mp_clear_symbol(mp, x,false);
21461   h=mp_get_avail(mp); info(h)=x; t=h;
21462   while (1) { 
21463     mp_get_x_next(mp);
21464     if ( mp->cur_sym==0 ) break;
21465     if ( mp->cur_cmd!=tag_token ) if ( mp->cur_cmd!=internal_quantity)  {
21466       if ( mp->cur_cmd==left_bracket ) {
21467         @<Descend past a collective subscript@>;
21468       } else {
21469         break;
21470       }
21471     }
21472     link(t)=mp_get_avail(mp); t=link(t); info(t)=mp->cur_sym;
21473   }
21474   if ( eq_type(x)!=tag_token ) mp_clear_symbol(mp, x,false);
21475   if ( equiv(x)==null ) mp_new_root(mp, x);
21476   return h;
21477 }
21478
21479 @ If the subscript isn't collective, we don't accept it as part of the
21480 declared variable.
21481
21482 @<Descend past a collective subscript@>=
21483
21484   l=mp->cur_sym; mp_get_x_next(mp);
21485   if ( mp->cur_cmd!=right_bracket ) {
21486     mp_back_input(mp); mp->cur_sym=l; mp->cur_cmd=left_bracket; break;
21487   } else {
21488     mp->cur_sym=collective_subscript;
21489   }
21490 }
21491
21492 @ Type declarations are introduced by the following primitive operations.
21493
21494 @<Put each...@>=
21495 mp_primitive(mp, "numeric",type_name,mp_numeric_type);
21496 @:numeric_}{\&{numeric} primitive@>
21497 mp_primitive(mp, "string",type_name,mp_string_type);
21498 @:string_}{\&{string} primitive@>
21499 mp_primitive(mp, "boolean",type_name,mp_boolean_type);
21500 @:boolean_}{\&{boolean} primitive@>
21501 mp_primitive(mp, "path",type_name,mp_path_type);
21502 @:path_}{\&{path} primitive@>
21503 mp_primitive(mp, "pen",type_name,mp_pen_type);
21504 @:pen_}{\&{pen} primitive@>
21505 mp_primitive(mp, "picture",type_name,mp_picture_type);
21506 @:picture_}{\&{picture} primitive@>
21507 mp_primitive(mp, "transform",type_name,mp_transform_type);
21508 @:transform_}{\&{transform} primitive@>
21509 mp_primitive(mp, "color",type_name,mp_color_type);
21510 @:color_}{\&{color} primitive@>
21511 mp_primitive(mp, "rgbcolor",type_name,mp_color_type);
21512 @:color_}{\&{rgbcolor} primitive@>
21513 mp_primitive(mp, "cmykcolor",type_name,mp_cmykcolor_type);
21514 @:color_}{\&{cmykcolor} primitive@>
21515 mp_primitive(mp, "pair",type_name,mp_pair_type);
21516 @:pair_}{\&{pair} primitive@>
21517
21518 @ @<Cases of |print_cmd...@>=
21519 case type_name: mp_print_type(mp, m); break;
21520
21521 @ Now we are ready to handle type declarations, assuming that a
21522 |type_name| has just been scanned.
21523
21524 @<Declare action procedures for use by |do_statement|@>=
21525 void mp_do_type_declaration (MP mp) ;
21526
21527 @ @c
21528 void mp_do_type_declaration (MP mp) {
21529   small_number t; /* the type being declared */
21530   pointer p; /* token list for a declared variable */
21531   pointer q; /* value node for the variable */
21532   if ( mp->cur_mod>=mp_transform_type ) 
21533     t=mp->cur_mod;
21534   else 
21535     t=mp->cur_mod+unknown_tag;
21536   do {  
21537     p=mp_scan_declared_variable(mp);
21538     mp_flush_variable(mp, equiv(info(p)),link(p),false);
21539     q=mp_find_variable(mp, p);
21540     if ( q!=null ) { 
21541       type(q)=t; value(q)=null; 
21542     } else  { 
21543       print_err("Declared variable conflicts with previous vardef");
21544 @.Declared variable conflicts...@>
21545       help2("You can't use, e.g., `numeric foo[]' after `vardef foo'.")
21546            ("Proceed, and I'll ignore the illegal redeclaration.");
21547       mp_put_get_error(mp);
21548     }
21549     mp_flush_list(mp, p);
21550     if ( mp->cur_cmd<comma ) {
21551       @<Flush spurious symbols after the declared variable@>;
21552     }
21553   } while (! end_of_statement);
21554 }
21555
21556 @ @<Flush spurious symbols after the declared variable@>=
21557
21558   print_err("Illegal suffix of declared variable will be flushed");
21559 @.Illegal suffix...flushed@>
21560   help5("Variables in declarations must consist entirely of")
21561     ("names and collective subscripts, e.g., `x[]a'.")
21562     ("Are you trying to use a reserved word in a variable name?")
21563     ("I'm going to discard the junk I found here,")
21564     ("up to the next comma or the end of the declaration.");
21565   if ( mp->cur_cmd==numeric_token )
21566     mp->help_line[2]="Explicit subscripts like `x15a' aren't permitted.";
21567   mp_put_get_error(mp); mp->scanner_status=flushing;
21568   do {  
21569     get_t_next;
21570     @<Decrease the string reference count...@>;
21571   } while (mp->cur_cmd<comma); /* either |end_of_statement| or |cur_cmd=comma| */
21572   mp->scanner_status=normal;
21573 }
21574
21575 @ \MP's |main_control| procedure just calls |do_statement| repeatedly
21576 until coming to the end of the user's program.
21577 Each execution of |do_statement| concludes with
21578 |cur_cmd=semicolon|, |end_group|, or |stop|.
21579
21580 @c void mp_main_control (MP mp) { 
21581   do {  
21582     mp_do_statement(mp);
21583     if ( mp->cur_cmd==end_group ) {
21584       print_err("Extra `endgroup'");
21585 @.Extra `endgroup'@>
21586       help2("I'm not currently working on a `begingroup',")
21587         ("so I had better not try to end anything.");
21588       mp_flush_error(mp, 0);
21589     }
21590   } while (mp->cur_cmd!=stop);
21591 }
21592 int mp_run (MP mp) {
21593   mp_main_control(mp); /* come to life */
21594   mp_final_cleanup(mp); /* prepare for death */
21595   mp_close_files_and_terminate(mp);
21596   return mp->history;
21597 }
21598 char * mp_mplib_version (MP mp) {
21599   assert(mp);
21600   return mplib_version;
21601 }
21602 char * mp_metapost_version (MP mp) {
21603   assert(mp);
21604   return metapost_version;
21605 }
21606
21607 @ @<Exported function headers@>=
21608 int mp_run (MP mp);
21609 char * mp_mplib_version (MP mp);
21610 char * mp_metapost_version (MP mp);
21611
21612 @ @<Put each...@>=
21613 mp_primitive(mp, "end",stop,0);
21614 @:end_}{\&{end} primitive@>
21615 mp_primitive(mp, "dump",stop,1);
21616 @:dump_}{\&{dump} primitive@>
21617
21618 @ @<Cases of |print_cmd...@>=
21619 case stop:
21620   if ( m==0 ) mp_print(mp, "end");
21621   else mp_print(mp, "dump");
21622   break;
21623
21624 @* \[41] Commands.
21625 Let's turn now to statements that are classified as ``commands'' because
21626 of their imperative nature. We'll begin with simple ones, so that it
21627 will be clear how to hook command processing into the |do_statement| routine;
21628 then we'll tackle the tougher commands.
21629
21630 Here's one of the simplest:
21631
21632 @<Cases of |do_statement|...@>=
21633 case random_seed: mp_do_random_seed(mp);  break;
21634
21635 @ @<Declare action procedures for use by |do_statement|@>=
21636 void mp_do_random_seed (MP mp) ;
21637
21638 @ @c void mp_do_random_seed (MP mp) { 
21639   mp_get_x_next(mp);
21640   if ( mp->cur_cmd!=assignment ) {
21641     mp_missing_err(mp, ":=");
21642 @.Missing `:='@>
21643     help1("Always say `randomseed:=<numeric expression>'.");
21644     mp_back_error(mp);
21645   };
21646   mp_get_x_next(mp); mp_scan_expression(mp);
21647   if ( mp->cur_type!=mp_known ) {
21648     exp_err("Unknown value will be ignored");
21649 @.Unknown value...ignored@>
21650     help2("Your expression was too random for me to handle,")
21651       ("so I won't change the random seed just now.");
21652     mp_put_get_flush_error(mp, 0);
21653   } else {
21654    @<Initialize the random seed to |cur_exp|@>;
21655   }
21656 }
21657
21658 @ @<Initialize the random seed to |cur_exp|@>=
21659
21660   mp_init_randoms(mp, mp->cur_exp);
21661   if ( mp->selector>=log_only && mp->selector<write_file) {
21662     mp->old_setting=mp->selector; mp->selector=log_only;
21663     mp_print_nl(mp, "{randomseed:="); 
21664     mp_print_scaled(mp, mp->cur_exp); 
21665     mp_print_char(mp, '}');
21666     mp_print_nl(mp, ""); mp->selector=mp->old_setting;
21667   }
21668 }
21669
21670 @ And here's another simple one (somewhat different in flavor):
21671
21672 @<Cases of |do_statement|...@>=
21673 case mode_command: 
21674   mp_print_ln(mp); mp->interaction=mp->cur_mod;
21675   @<Initialize the print |selector| based on |interaction|@>;
21676   if ( mp->log_opened ) mp->selector=mp->selector+2;
21677   mp_get_x_next(mp);
21678   break;
21679
21680 @ @<Put each...@>=
21681 mp_primitive(mp, "batchmode",mode_command,mp_batch_mode);
21682 @:mp_batch_mode_}{\&{batchmode} primitive@>
21683 mp_primitive(mp, "nonstopmode",mode_command,mp_nonstop_mode);
21684 @:mp_nonstop_mode_}{\&{nonstopmode} primitive@>
21685 mp_primitive(mp, "scrollmode",mode_command,mp_scroll_mode);
21686 @:mp_scroll_mode_}{\&{scrollmode} primitive@>
21687 mp_primitive(mp, "errorstopmode",mode_command,mp_error_stop_mode);
21688 @:mp_error_stop_mode_}{\&{errorstopmode} primitive@>
21689
21690 @ @<Cases of |print_cmd_mod|...@>=
21691 case mode_command: 
21692   switch (m) {
21693   case mp_batch_mode: mp_print(mp, "batchmode"); break;
21694   case mp_nonstop_mode: mp_print(mp, "nonstopmode"); break;
21695   case mp_scroll_mode: mp_print(mp, "scrollmode"); break;
21696   default: mp_print(mp, "errorstopmode"); break;
21697   }
21698   break;
21699
21700 @ The `\&{inner}' and `\&{outer}' commands are only slightly harder.
21701
21702 @<Cases of |do_statement|...@>=
21703 case protection_command: mp_do_protection(mp); break;
21704
21705 @ @<Put each...@>=
21706 mp_primitive(mp, "inner",protection_command,0);
21707 @:inner_}{\&{inner} primitive@>
21708 mp_primitive(mp, "outer",protection_command,1);
21709 @:outer_}{\&{outer} primitive@>
21710
21711 @ @<Cases of |print_cmd...@>=
21712 case protection_command: 
21713   if ( m==0 ) mp_print(mp, "inner");
21714   else mp_print(mp, "outer");
21715   break;
21716
21717 @ @<Declare action procedures for use by |do_statement|@>=
21718 void mp_do_protection (MP mp) ;
21719
21720 @ @c void mp_do_protection (MP mp) {
21721   int m; /* 0 to unprotect, 1 to protect */
21722   halfword t; /* the |eq_type| before we change it */
21723   m=mp->cur_mod;
21724   do {  
21725     mp_get_symbol(mp); t=eq_type(mp->cur_sym);
21726     if ( m==0 ) { 
21727       if ( t>=outer_tag ) 
21728         eq_type(mp->cur_sym)=t-outer_tag;
21729     } else if ( t<outer_tag ) {
21730       eq_type(mp->cur_sym)=t+outer_tag;
21731     }
21732     mp_get_x_next(mp);
21733   } while (mp->cur_cmd==comma);
21734 }
21735
21736 @ \MP\ never defines the tokens `\.(' and `\.)' to be primitives, but
21737 plain \MP\ begins with the declaration `\&{delimiters} \.{()}'. Such a
21738 declaration assigns the command code |left_delimiter| to `\.{(}' and
21739 |right_delimiter| to `\.{)}'; the |equiv| of each delimiter is the
21740 hash address of its mate.
21741
21742 @<Cases of |do_statement|...@>=
21743 case delimiters: mp_def_delims(mp); break;
21744
21745 @ @<Declare action procedures for use by |do_statement|@>=
21746 void mp_def_delims (MP mp) ;
21747
21748 @ @c void mp_def_delims (MP mp) {
21749   pointer l_delim,r_delim; /* the new delimiter pair */
21750   mp_get_clear_symbol(mp); l_delim=mp->cur_sym;
21751   mp_get_clear_symbol(mp); r_delim=mp->cur_sym;
21752   eq_type(l_delim)=left_delimiter; equiv(l_delim)=r_delim;
21753   eq_type(r_delim)=right_delimiter; equiv(r_delim)=l_delim;
21754   mp_get_x_next(mp);
21755 }
21756
21757 @ Here is a procedure that is called when \MP\ has reached a point
21758 where some right delimiter is mandatory.
21759
21760 @<Declare the procedure called |check_delimiter|@>=
21761 void mp_check_delimiter (MP mp,pointer l_delim, pointer r_delim) {
21762   if ( mp->cur_cmd==right_delimiter ) 
21763     if ( mp->cur_mod==l_delim ) 
21764       return;
21765   if ( mp->cur_sym!=r_delim ) {
21766      mp_missing_err(mp, str(text(r_delim)));
21767 @.Missing `)'@>
21768     help2("I found no right delimiter to match a left one. So I've")
21769       ("put one in, behind the scenes; this may fix the problem.");
21770     mp_back_error(mp);
21771   } else { 
21772     print_err("The token `"); mp_print_text(r_delim);
21773 @.The token...delimiter@>
21774     mp_print(mp, "' is no longer a right delimiter");
21775     help3("Strange: This token has lost its former meaning!")
21776       ("I'll read it as a right delimiter this time;")
21777       ("but watch out, I'll probably miss it later.");
21778     mp_error(mp);
21779   }
21780 }
21781
21782 @ The next four commands save or change the values associated with tokens.
21783
21784 @<Cases of |do_statement|...@>=
21785 case save_command: 
21786   do {  
21787     mp_get_symbol(mp); mp_save_variable(mp, mp->cur_sym); mp_get_x_next(mp);
21788   } while (mp->cur_cmd==comma);
21789   break;
21790 case interim_command: mp_do_interim(mp); break;
21791 case let_command: mp_do_let(mp); break;
21792 case new_internal: mp_do_new_internal(mp); break;
21793
21794 @ @<Declare action procedures for use by |do_statement|@>=
21795 void mp_do_statement (MP mp);
21796 void mp_do_interim (MP mp);
21797
21798 @ @c void mp_do_interim (MP mp) { 
21799   mp_get_x_next(mp);
21800   if ( mp->cur_cmd!=internal_quantity ) {
21801      print_err("The token `");
21802 @.The token...quantity@>
21803     if ( mp->cur_sym==0 ) mp_print(mp, "(%CAPSULE)");
21804     else mp_print_text(mp->cur_sym);
21805     mp_print(mp, "' isn't an internal quantity");
21806     help1("Something like `tracingonline' should follow `interim'.");
21807     mp_back_error(mp);
21808   } else { 
21809     mp_save_internal(mp, mp->cur_mod); mp_back_input(mp);
21810   }
21811   mp_do_statement(mp);
21812 }
21813
21814 @ The following procedure is careful not to undefine the left-hand symbol
21815 too soon, lest commands like `{\tt let x=x}' have a surprising effect.
21816
21817 @<Declare action procedures for use by |do_statement|@>=
21818 void mp_do_let (MP mp) ;
21819
21820 @ @c void mp_do_let (MP mp) {
21821   pointer l; /* hash location of the left-hand symbol */
21822   mp_get_symbol(mp); l=mp->cur_sym; mp_get_x_next(mp);
21823   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
21824      mp_missing_err(mp, "=");
21825 @.Missing `='@>
21826     help3("You should have said `let symbol = something'.")
21827       ("But don't worry; I'll pretend that an equals sign")
21828       ("was present. The next token I read will be `something'.");
21829     mp_back_error(mp);
21830   }
21831   mp_get_symbol(mp);
21832   switch (mp->cur_cmd) {
21833   case defined_macro: case secondary_primary_macro:
21834   case tertiary_secondary_macro: case expression_tertiary_macro: 
21835     add_mac_ref(mp->cur_mod);
21836     break;
21837   default: 
21838     break;
21839   }
21840   mp_clear_symbol(mp, l,false); eq_type(l)=mp->cur_cmd;
21841   if ( mp->cur_cmd==tag_token ) equiv(l)=null;
21842   else equiv(l)=mp->cur_mod;
21843   mp_get_x_next(mp);
21844 }
21845
21846 @ @<Declarations@>=
21847 void mp_grow_internals (MP mp, int l);
21848 void mp_do_new_internal (MP mp) ;
21849
21850 @ @c
21851 void mp_grow_internals (MP mp, int l) {
21852   scaled *internal;
21853   char * *int_name; 
21854   int k;
21855   if ( hash_end+l>max_halfword ) {
21856     mp_confusion(mp, "out of memory space"); /* can't be reached */
21857   }
21858   int_name = xmalloc ((l+1),sizeof(char *));
21859   internal = xmalloc ((l+1),sizeof(scaled));
21860   for (k=0;k<=l; k++ ) { 
21861     if (k<=mp->max_internal) {
21862       internal[k]=mp->internal[k]; 
21863       int_name[k]=mp->int_name[k]; 
21864     } else {
21865       internal[k]=0; 
21866       int_name[k]=NULL; 
21867     }
21868   }
21869   xfree(mp->internal); xfree(mp->int_name);
21870   mp->int_name = int_name;
21871   mp->internal = internal;
21872   mp->max_internal = l;
21873 }
21874
21875
21876 void mp_do_new_internal (MP mp) { 
21877   do {  
21878     if ( mp->int_ptr==mp->max_internal ) {
21879       mp_grow_internals(mp, (mp->max_internal + (mp->max_internal>>2)));
21880     }
21881     mp_get_clear_symbol(mp); incr(mp->int_ptr);
21882     eq_type(mp->cur_sym)=internal_quantity; 
21883     equiv(mp->cur_sym)=mp->int_ptr;
21884     if(mp->int_name[mp->int_ptr]!=NULL)
21885       xfree(mp->int_name[mp->int_ptr]);
21886     mp->int_name[mp->int_ptr]=str(text(mp->cur_sym)); 
21887     mp->internal[mp->int_ptr]=0;
21888     mp_get_x_next(mp);
21889   } while (mp->cur_cmd==comma);
21890 }
21891
21892 @ @<Dealloc variables@>=
21893 for (k=0;k<=mp->max_internal;k++) {
21894    xfree(mp->int_name[k]);
21895 }
21896 xfree(mp->internal); 
21897 xfree(mp->int_name); 
21898
21899
21900 @ The various `\&{show}' commands are distinguished by modifier fields
21901 in the usual way.
21902
21903 @d show_token_code 0 /* show the meaning of a single token */
21904 @d show_stats_code 1 /* show current memory and string usage */
21905 @d show_code 2 /* show a list of expressions */
21906 @d show_var_code 3 /* show a variable and its descendents */
21907 @d show_dependencies_code 4 /* show dependent variables in terms of independents */
21908
21909 @<Put each...@>=
21910 mp_primitive(mp, "showtoken",show_command,show_token_code);
21911 @:show_token_}{\&{showtoken} primitive@>
21912 mp_primitive(mp, "showstats",show_command,show_stats_code);
21913 @:show_stats_}{\&{showstats} primitive@>
21914 mp_primitive(mp, "show",show_command,show_code);
21915 @:show_}{\&{show} primitive@>
21916 mp_primitive(mp, "showvariable",show_command,show_var_code);
21917 @:show_var_}{\&{showvariable} primitive@>
21918 mp_primitive(mp, "showdependencies",show_command,show_dependencies_code);
21919 @:show_dependencies_}{\&{showdependencies} primitive@>
21920
21921 @ @<Cases of |print_cmd...@>=
21922 case show_command: 
21923   switch (m) {
21924   case show_token_code:mp_print(mp, "showtoken"); break;
21925   case show_stats_code:mp_print(mp, "showstats"); break;
21926   case show_code:mp_print(mp, "show"); break;
21927   case show_var_code:mp_print(mp, "showvariable"); break;
21928   default: mp_print(mp, "showdependencies"); break;
21929   }
21930   break;
21931
21932 @ @<Cases of |do_statement|...@>=
21933 case show_command:mp_do_show_whatever(mp); break;
21934
21935 @ The value of |cur_mod| controls the |verbosity| in the |print_exp| routine:
21936 if it's |show_code|, complicated structures are abbreviated, otherwise
21937 they aren't.
21938
21939 @<Declare action procedures for use by |do_statement|@>=
21940 void mp_do_show (MP mp) ;
21941
21942 @ @c void mp_do_show (MP mp) { 
21943   do {  
21944     mp_get_x_next(mp); mp_scan_expression(mp);
21945     mp_print_nl(mp, ">> ");
21946 @.>>@>
21947     mp_print_exp(mp, null,2); mp_flush_cur_exp(mp, 0);
21948   } while (mp->cur_cmd==comma);
21949 }
21950
21951 @ @<Declare action procedures for use by |do_statement|@>=
21952 void mp_disp_token (MP mp) ;
21953
21954 @ @c void mp_disp_token (MP mp) { 
21955   mp_print_nl(mp, "> ");
21956 @.>\relax@>
21957   if ( mp->cur_sym==0 ) {
21958     @<Show a numeric or string or capsule token@>;
21959   } else { 
21960     mp_print_text(mp->cur_sym); mp_print_char(mp, '=');
21961     if ( eq_type(mp->cur_sym)>=outer_tag ) mp_print(mp, "(outer) ");
21962     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod);
21963     if ( mp->cur_cmd==defined_macro ) {
21964       mp_print_ln(mp); mp_show_macro(mp, mp->cur_mod,null,100000);
21965     } /* this avoids recursion between |show_macro| and |print_cmd_mod| */
21966 @^recursion@>
21967   }
21968 }
21969
21970 @ @<Show a numeric or string or capsule token@>=
21971
21972   if ( mp->cur_cmd==numeric_token ) {
21973     mp_print_scaled(mp, mp->cur_mod);
21974   } else if ( mp->cur_cmd==capsule_token ) {
21975     mp->g_pointer=mp->cur_mod; mp_print_capsule(mp);
21976   } else  { 
21977     mp_print_char(mp, '"'); 
21978     mp_print_str(mp, mp->cur_mod); mp_print_char(mp, '"');
21979     delete_str_ref(mp->cur_mod);
21980   }
21981 }
21982
21983 @ The following cases of |print_cmd_mod| might arise in connection
21984 with |disp_token|, although they don't correspond to any
21985 primitive tokens.
21986
21987 @<Cases of |print_cmd_...@>=
21988 case left_delimiter:
21989 case right_delimiter: 
21990   if ( c==left_delimiter ) mp_print(mp, "left");
21991   else mp_print(mp, "right");
21992   mp_print(mp, " delimiter that matches "); 
21993   mp_print_text(m);
21994   break;
21995 case tag_token:
21996   if ( m==null ) mp_print(mp, "tag");
21997    else mp_print(mp, "variable");
21998    break;
21999 case defined_macro: 
22000    mp_print(mp, "macro:");
22001    break;
22002 case secondary_primary_macro:
22003 case tertiary_secondary_macro:
22004 case expression_tertiary_macro:
22005   mp_print_cmd_mod(mp, macro_def,c); 
22006   mp_print(mp, "'d macro:");
22007   mp_print_ln(mp); mp_show_token_list(mp, link(link(m)),null,1000,0);
22008   break;
22009 case repeat_loop:
22010   mp_print(mp, "[repeat the loop]");
22011   break;
22012 case internal_quantity:
22013   mp_print(mp, mp->int_name[m]);
22014   break;
22015
22016 @ @<Declare action procedures for use by |do_statement|@>=
22017 void mp_do_show_token (MP mp) ;
22018
22019 @ @c void mp_do_show_token (MP mp) { 
22020   do {  
22021     get_t_next; mp_disp_token(mp);
22022     mp_get_x_next(mp);
22023   } while (mp->cur_cmd==comma);
22024 }
22025
22026 @ @<Declare action procedures for use by |do_statement|@>=
22027 void mp_do_show_stats (MP mp) ;
22028
22029 @ @c void mp_do_show_stats (MP mp) { 
22030   mp_print_nl(mp, "Memory usage ");
22031 @.Memory usage...@>
22032   mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used);
22033   if ( false )
22034     mp_print(mp, "unknown");
22035   mp_print(mp, " ("); mp_print_int(mp, mp->hi_mem_min-mp->lo_mem_max-1);
22036   mp_print(mp, " still untouched)"); mp_print_ln(mp);
22037   mp_print_nl(mp, "String usage ");
22038   mp_print_int(mp, mp->strs_in_use-mp->init_str_use);
22039   mp_print_char(mp, '&'); mp_print_int(mp, mp->pool_in_use-mp->init_pool_ptr);
22040   if ( false )
22041     mp_print(mp, "unknown");
22042   mp_print(mp, " (");
22043   mp_print_int(mp, mp->max_strings-1-mp->strs_used_up); mp_print_char(mp, '&');
22044   mp_print_int(mp, mp->pool_size-mp->pool_ptr); 
22045   mp_print(mp, " now untouched)"); mp_print_ln(mp);
22046   mp_get_x_next(mp);
22047 }
22048
22049 @ Here's a recursive procedure that gives an abbreviated account
22050 of a variable, for use by |do_show_var|.
22051
22052 @<Declare action procedures for use by |do_statement|@>=
22053 void mp_disp_var (MP mp,pointer p) ;
22054
22055 @ @c void mp_disp_var (MP mp,pointer p) {
22056   pointer q; /* traverses attributes and subscripts */
22057   int n; /* amount of macro text to show */
22058   if ( type(p)==mp_structured )  {
22059     @<Descend the structure@>;
22060   } else if ( type(p)>=mp_unsuffixed_macro ) {
22061     @<Display a variable macro@>;
22062   } else if ( type(p)!=undefined ){ 
22063     mp_print_nl(mp, ""); mp_print_variable_name(mp, p); 
22064     mp_print_char(mp, '=');
22065     mp_print_exp(mp, p,0);
22066   }
22067 }
22068
22069 @ @<Descend the structure@>=
22070
22071   q=attr_head(p);
22072   do {  mp_disp_var(mp, q); q=link(q); } while (q!=end_attr);
22073   q=subscr_head(p);
22074   while ( name_type(q)==mp_subscr ) { 
22075     mp_disp_var(mp, q); q=link(q);
22076   }
22077 }
22078
22079 @ @<Display a variable macro@>=
22080
22081   mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22082   if ( type(p)>mp_unsuffixed_macro ) 
22083     mp_print(mp, "@@#"); /* |suffixed_macro| */
22084   mp_print(mp, "=macro:");
22085   if ( (int)mp->file_offset>=mp->max_print_line-20 ) n=5;
22086   else n=mp->max_print_line-mp->file_offset-15;
22087   mp_show_macro(mp, value(p),null,n);
22088 }
22089
22090 @ @<Declare action procedures for use by |do_statement|@>=
22091 void mp_do_show_var (MP mp) ;
22092
22093 @ @c void mp_do_show_var (MP mp) { 
22094   do {  
22095     get_t_next;
22096     if ( mp->cur_sym>0 ) if ( mp->cur_sym<=hash_end )
22097       if ( mp->cur_cmd==tag_token ) if ( mp->cur_mod!=null ) {
22098       mp_disp_var(mp, mp->cur_mod); goto DONE;
22099     }
22100    mp_disp_token(mp);
22101   DONE:
22102    mp_get_x_next(mp);
22103   } while (mp->cur_cmd==comma);
22104 }
22105
22106 @ @<Declare action procedures for use by |do_statement|@>=
22107 void mp_do_show_dependencies (MP mp) ;
22108
22109 @ @c void mp_do_show_dependencies (MP mp) {
22110   pointer p; /* link that runs through all dependencies */
22111   p=link(dep_head);
22112   while ( p!=dep_head ) {
22113     if ( mp_interesting(mp, p) ) {
22114       mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22115       if ( type(p)==mp_dependent ) mp_print_char(mp, '=');
22116       else mp_print(mp, " = "); /* extra spaces imply proto-dependency */
22117       mp_print_dependency(mp, dep_list(p),type(p));
22118     }
22119     p=dep_list(p);
22120     while ( info(p)!=null ) p=link(p);
22121     p=link(p);
22122   }
22123   mp_get_x_next(mp);
22124 }
22125
22126 @ Finally we are ready for the procedure that governs all of the
22127 show commands.
22128
22129 @<Declare action procedures for use by |do_statement|@>=
22130 void mp_do_show_whatever (MP mp) ;
22131
22132 @ @c void mp_do_show_whatever (MP mp) { 
22133   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
22134   switch (mp->cur_mod) {
22135   case show_token_code:mp_do_show_token(mp); break;
22136   case show_stats_code:mp_do_show_stats(mp); break;
22137   case show_code:mp_do_show(mp); break;
22138   case show_var_code:mp_do_show_var(mp); break;
22139   case show_dependencies_code:mp_do_show_dependencies(mp); break;
22140   } /* there are no other cases */
22141   if ( mp->internal[showstopping]>0 ){ 
22142     print_err("OK");
22143 @.OK@>
22144     if ( mp->interaction<mp_error_stop_mode ) { 
22145       help0; decr(mp->error_count);
22146     } else {
22147       help1("This isn't an error message; I'm just showing something.");
22148     }
22149     if ( mp->cur_cmd==semicolon ) mp_error(mp);
22150      else mp_put_get_error(mp);
22151   }
22152 }
22153
22154 @ The `\&{addto}' command needs the following additional primitives:
22155
22156 @d double_path_code 0 /* command modifier for `\&{doublepath}' */
22157 @d contour_code 1 /* command modifier for `\&{contour}' */
22158 @d also_code 2 /* command modifier for `\&{also}' */
22159
22160 @ Pre and postscripts need two new identifiers:
22161
22162 @d with_pre_script 11
22163 @d with_post_script 13
22164
22165 @<Put each...@>=
22166 mp_primitive(mp, "doublepath",thing_to_add,double_path_code);
22167 @:double_path_}{\&{doublepath} primitive@>
22168 mp_primitive(mp, "contour",thing_to_add,contour_code);
22169 @:contour_}{\&{contour} primitive@>
22170 mp_primitive(mp, "also",thing_to_add,also_code);
22171 @:also_}{\&{also} primitive@>
22172 mp_primitive(mp, "withpen",with_option,mp_pen_type);
22173 @:with_pen_}{\&{withpen} primitive@>
22174 mp_primitive(mp, "dashed",with_option,mp_picture_type);
22175 @:dashed_}{\&{dashed} primitive@>
22176 mp_primitive(mp, "withprescript",with_option,with_pre_script);
22177 @:with_pre_script_}{\&{withprescript} primitive@>
22178 mp_primitive(mp, "withpostscript",with_option,with_post_script);
22179 @:with_post_script_}{\&{withpostscript} primitive@>
22180 mp_primitive(mp, "withoutcolor",with_option,no_model);
22181 @:with_color_}{\&{withoutcolor} primitive@>
22182 mp_primitive(mp, "withgreyscale",with_option,grey_model);
22183 @:with_color_}{\&{withgreyscale} primitive@>
22184 mp_primitive(mp, "withcolor",with_option,uninitialized_model);
22185 @:with_color_}{\&{withcolor} primitive@>
22186 /*  \&{withrgbcolor} is an alias for \&{withcolor} */
22187 mp_primitive(mp, "withrgbcolor",with_option,rgb_model);
22188 @:with_color_}{\&{withrgbcolor} primitive@>
22189 mp_primitive(mp, "withcmykcolor",with_option,cmyk_model);
22190 @:with_color_}{\&{withcmykcolor} primitive@>
22191
22192 @ @<Cases of |print_cmd...@>=
22193 case thing_to_add:
22194   if ( m==contour_code ) mp_print(mp, "contour");
22195   else if ( m==double_path_code ) mp_print(mp, "doublepath");
22196   else mp_print(mp, "also");
22197   break;
22198 case with_option:
22199   if ( m==mp_pen_type ) mp_print(mp, "withpen");
22200   else if ( m==with_pre_script ) mp_print(mp, "withprescript");
22201   else if ( m==with_post_script ) mp_print(mp, "withpostscript");
22202   else if ( m==no_model ) mp_print(mp, "withoutcolor");
22203   else if ( m==rgb_model ) mp_print(mp, "withrgbcolor");
22204   else if ( m==uninitialized_model ) mp_print(mp, "withcolor");
22205   else if ( m==cmyk_model ) mp_print(mp, "withcmykcolor");
22206   else if ( m==grey_model ) mp_print(mp, "withgreyscale");
22207   else mp_print(mp, "dashed");
22208   break;
22209
22210 @ The |scan_with_list| procedure parses a $\langle$with list$\rangle$ and
22211 updates the list of graphical objects starting at |p|.  Each $\langle$with
22212 clause$\rangle$ updates all graphical objects whose |type| is compatible.
22213 Other objects are ignored.
22214
22215 @<Declare action procedures for use by |do_statement|@>=
22216 void mp_scan_with_list (MP mp,pointer p) ;
22217
22218 @ @c void mp_scan_with_list (MP mp,pointer p) {
22219   small_number t; /* |cur_mod| of the |with_option| (should match |cur_type|) */
22220   pointer q; /* for list manipulation */
22221   int old_setting; /* saved |selector| setting */
22222   pointer k; /* for finding the near-last item in a list  */
22223   str_number s; /* for string cleanup after combining  */
22224   pointer cp,pp,dp,ap,bp;
22225     /* objects being updated; |void| initially; |null| to suppress update */
22226   cp=diov; pp=diov; dp=diov; ap=diov; bp=diov;
22227   k=0;
22228   while ( mp->cur_cmd==with_option ){ 
22229     t=mp->cur_mod;
22230     mp_get_x_next(mp);
22231     if ( t!=no_model ) mp_scan_expression(mp);
22232     if (((t==with_pre_script)&&(mp->cur_type!=mp_string_type))||
22233      ((t==with_post_script)&&(mp->cur_type!=mp_string_type))||
22234      ((t==uninitialized_model)&&
22235         ((mp->cur_type!=mp_cmykcolor_type)&&(mp->cur_type!=mp_color_type)
22236           &&(mp->cur_type!=mp_known)&&(mp->cur_type!=mp_boolean_type)))||
22237      ((t==cmyk_model)&&(mp->cur_type!=mp_cmykcolor_type))||
22238      ((t==rgb_model)&&(mp->cur_type!=mp_color_type))||
22239      ((t==grey_model)&&(mp->cur_type!=mp_known))||
22240      ((t==mp_pen_type)&&(mp->cur_type!=t))||
22241      ((t==mp_picture_type)&&(mp->cur_type!=t)) ) {
22242       @<Complain about improper type@>;
22243     } else if ( t==uninitialized_model ) {
22244       if ( cp==diov ) @<Make |cp| a colored object in object list~|p|@>;
22245       if ( cp!=null )
22246         @<Transfer a color from the current expression to object~|cp|@>;
22247       mp_flush_cur_exp(mp, 0);
22248     } else if ( t==rgb_model ) {
22249       if ( cp==diov ) @<Make |cp| a colored object in object list~|p|@>;
22250       if ( cp!=null )
22251         @<Transfer a rgbcolor from the current expression to object~|cp|@>;
22252       mp_flush_cur_exp(mp, 0);
22253     } else if ( t==cmyk_model ) {
22254       if ( cp==diov ) @<Make |cp| a colored object in object list~|p|@>;
22255       if ( cp!=null )
22256         @<Transfer a cmykcolor from the current expression to object~|cp|@>;
22257       mp_flush_cur_exp(mp, 0);
22258     } else if ( t==grey_model ) {
22259       if ( cp==diov ) @<Make |cp| a colored object in object list~|p|@>;
22260       if ( cp!=null )
22261         @<Transfer a greyscale from the current expression to object~|cp|@>;
22262       mp_flush_cur_exp(mp, 0);
22263     } else if ( t==no_model ) {
22264       if ( cp==diov ) @<Make |cp| a colored object in object list~|p|@>;
22265       if ( cp!=null )
22266         @<Transfer a noncolor from the current expression to object~|cp|@>;
22267     } else if ( t==mp_pen_type ) {
22268       if ( pp==diov ) @<Make |pp| an object in list~|p| that needs a pen@>;
22269       if ( pp!=null ) {
22270         if ( pen_p(pp)!=null ) mp_toss_knot_list(mp, pen_p(pp));
22271         pen_p(pp)=mp->cur_exp; mp->cur_type=mp_vacuous;
22272       }
22273     } else if ( t==with_pre_script ) {
22274       if ( ap==diov )
22275         ap=p;
22276       while ( (ap!=null)&&(! has_color(ap)) )
22277          ap=link(ap);
22278       if ( ap!=null ) {
22279         if ( pre_script(ap)!=null ) { /*  build a new,combined string  */
22280           s=pre_script(ap);
22281           old_setting=mp->selector;
22282               mp->selector=new_string;
22283           str_room(length(pre_script(ap))+length(mp->cur_exp)+2);
22284               mp_print_str(mp, mp->cur_exp);
22285           append_char(13);  /* a forced \ps\ newline  */
22286           mp_print_str(mp, pre_script(ap));
22287           pre_script(ap)=mp_make_string(mp);
22288           delete_str_ref(s);
22289           mp->selector=old_setting;
22290         } else {
22291           pre_script(ap)=mp->cur_exp;
22292         }
22293         mp->cur_type=mp_vacuous;
22294       }
22295     } else if ( t==with_post_script ) {
22296       if ( bp==diov )
22297         k=p; 
22298       bp=k;
22299       while ( link(k)!=null ) {
22300         k=link(k);
22301         if ( has_color(k) ) bp=k;
22302       }
22303       if ( bp!=null ) {
22304          if ( post_script(bp)!=null ) {
22305            s=post_script(bp);
22306            old_setting=mp->selector;
22307                mp->selector=new_string;
22308            str_room(length(post_script(bp))+length(mp->cur_exp)+2);
22309            mp_print_str(mp, post_script(bp));
22310            append_char(13); /* a forced \ps\ newline  */
22311            mp_print_str(mp, mp->cur_exp);
22312            post_script(bp)=mp_make_string(mp);
22313            delete_str_ref(s);
22314            mp->selector=old_setting;
22315          } else {
22316            post_script(bp)=mp->cur_exp;
22317          }
22318          mp->cur_type=mp_vacuous;
22319        }
22320     } else { 
22321       if ( dp==diov ) 
22322         @<Make |dp| a stroked node in list~|p|@>;
22323       if ( dp!=null ) {
22324         if ( dash_p(dp)!=null ) delete_edge_ref(dash_p(dp));
22325         dash_p(dp)=mp_make_dashes(mp, mp->cur_exp);
22326         dash_scale(dp)=unity;
22327         mp->cur_type=mp_vacuous;
22328       }
22329     }
22330   }
22331   @<Copy the information from objects |cp|, |pp|, and |dp| into the rest
22332     of the list@>;
22333 };
22334
22335 @ @<Complain about improper type@>=
22336 { exp_err("Improper type");
22337 @.Improper type@>
22338 help2("Next time say `withpen <known pen expression>';")
22339   ("I'll ignore the bad `with' clause and look for another.");
22340 if ( t==with_pre_script )
22341   mp->help_line[1]="Next time say `withprescript <known string expression>';";
22342 else if ( t==with_post_script )
22343   mp->help_line[1]="Next time say `withpostscript <known string expression>';";
22344 else if ( t==mp_picture_type )
22345   mp->help_line[1]="Next time say `dashed <known picture expression>';";
22346 else if ( t==uninitialized_model )
22347   mp->help_line[1]="Next time say `withcolor <known color expression>';";
22348 else if ( t==rgb_model )
22349   mp->help_line[1]="Next time say `withrgbcolor <known color expression>';";
22350 else if ( t==cmyk_model )
22351   mp->help_line[1]="Next time say `withcmykcolor <known cmykcolor expression>';";
22352 else if ( t==grey_model )
22353   mp->help_line[1]="Next time say `withgreyscale <known numeric expression>';";;
22354 mp_put_get_flush_error(mp, 0);
22355 }
22356
22357 @ Forcing the color to be between |0| and |unity| here guarantees that no
22358 picture will ever contain a color outside the legal range for \ps\ graphics.
22359
22360 @<Transfer a color from the current expression to object~|cp|@>=
22361 { if ( mp->cur_type==mp_color_type )
22362    @<Transfer a rgbcolor from the current expression to object~|cp|@>
22363 else if ( mp->cur_type==mp_cmykcolor_type )
22364    @<Transfer a cmykcolor from the current expression to object~|cp|@>
22365 else if ( mp->cur_type==mp_known )
22366    @<Transfer a greyscale from the current expression to object~|cp|@>
22367 else if ( mp->cur_exp==false_code )
22368    @<Transfer a noncolor from the current expression to object~|cp|@>;
22369 }
22370
22371 @ @<Transfer a rgbcolor from the current expression to object~|cp|@>=
22372 { q=value(mp->cur_exp);
22373 cyan_val(cp)=0;
22374 magenta_val(cp)=0;
22375 yellow_val(cp)=0;
22376 black_val(cp)=0;
22377 red_val(cp)=value(red_part_loc(q));
22378 green_val(cp)=value(green_part_loc(q));
22379 blue_val(cp)=value(blue_part_loc(q));
22380 color_model(cp)=rgb_model;
22381 if ( red_val(cp)<0 ) red_val(cp)=0;
22382 if ( green_val(cp)<0 ) green_val(cp)=0;
22383 if ( blue_val(cp)<0 ) blue_val(cp)=0;
22384 if ( red_val(cp)>unity ) red_val(cp)=unity;
22385 if ( green_val(cp)>unity ) green_val(cp)=unity;
22386 if ( blue_val(cp)>unity ) blue_val(cp)=unity;
22387 }
22388
22389 @ @<Transfer a cmykcolor from the current expression to object~|cp|@>=
22390 { q=value(mp->cur_exp);
22391 cyan_val(cp)=value(cyan_part_loc(q));
22392 magenta_val(cp)=value(magenta_part_loc(q));
22393 yellow_val(cp)=value(yellow_part_loc(q));
22394 black_val(cp)=value(black_part_loc(q));
22395 color_model(cp)=cmyk_model;
22396 if ( cyan_val(cp)<0 ) cyan_val(cp)=0;
22397 if ( magenta_val(cp)<0 ) magenta_val(cp)=0;
22398 if ( yellow_val(cp)<0 ) yellow_val(cp)=0;
22399 if ( black_val(cp)<0 ) black_val(cp)=0;
22400 if ( cyan_val(cp)>unity ) cyan_val(cp)=unity;
22401 if ( magenta_val(cp)>unity ) magenta_val(cp)=unity;
22402 if ( yellow_val(cp)>unity ) yellow_val(cp)=unity;
22403 if ( black_val(cp)>unity ) black_val(cp)=unity;
22404 }
22405
22406 @ @<Transfer a greyscale from the current expression to object~|cp|@>=
22407 { q=mp->cur_exp;
22408 cyan_val(cp)=0;
22409 magenta_val(cp)=0;
22410 yellow_val(cp)=0;
22411 black_val(cp)=0;
22412 grey_val(cp)=q;
22413 color_model(cp)=grey_model;
22414 if ( grey_val(cp)<0 ) grey_val(cp)=0;
22415 if ( grey_val(cp)>unity ) grey_val(cp)=unity;
22416 }
22417
22418 @ @<Transfer a noncolor from the current expression to object~|cp|@>=
22419 {
22420 cyan_val(cp)=0;
22421 magenta_val(cp)=0;
22422 yellow_val(cp)=0;
22423 black_val(cp)=0;
22424 grey_val(cp)=0;
22425 color_model(cp)=no_model;
22426 }
22427
22428 @ @<Make |cp| a colored object in object list~|p|@>=
22429 { cp=p;
22430   while ( cp!=null ){ 
22431     if ( has_color(cp) ) break;
22432     cp=link(cp);
22433   }
22434 }
22435
22436 @ @<Make |pp| an object in list~|p| that needs a pen@>=
22437 { pp=p;
22438   while ( pp!=null ) {
22439     if ( has_pen(pp) ) break;
22440     pp=link(pp);
22441   }
22442 }
22443
22444 @ @<Make |dp| a stroked node in list~|p|@>=
22445 { dp=p;
22446   while ( dp!=null ) {
22447     if ( type(dp)==stroked_code ) break;
22448     dp=link(dp);
22449   }
22450 }
22451
22452 @ @<Copy the information from objects |cp|, |pp|, and |dp| into...@>=
22453 @<Copy |cp|'s color into the colored objects linked to~|cp|@>;
22454 if ( pp>diov )
22455   @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>;
22456 if ( dp>diov ) @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>
22457
22458 @ @<Copy |cp|'s color into the colored objects linked to~|cp|@>=
22459 { q=link(cp);
22460   while ( q!=null ) { 
22461     if ( has_color(q) ) {
22462       red_val(q)=red_val(cp);
22463       green_val(q)=green_val(cp);
22464       blue_val(q)=blue_val(cp);
22465       black_val(q)=black_val(cp);
22466       color_model(q)=color_model(cp);
22467     }
22468     q=link(q);
22469   }
22470 }
22471
22472 @ @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>=
22473 { q=link(pp);
22474   while ( q!=null ) {
22475     if ( has_pen(q) ) {
22476       if ( pen_p(q)!=null ) mp_toss_knot_list(mp, pen_p(q));
22477       pen_p(q)=copy_pen(pen_p(pp));
22478     }
22479     q=link(q);
22480   }
22481 }
22482
22483 @ @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>=
22484 { q=link(dp);
22485   while ( q!=null ) {
22486     if ( type(q)==stroked_code ) {
22487       if ( dash_p(q)!=null ) delete_edge_ref(dash_p(q));
22488       dash_p(q)=dash_p(dp);
22489       dash_scale(q)=unity;
22490       if ( dash_p(q)!=null ) add_edge_ref(dash_p(q));
22491     }
22492     q=link(q);
22493   }
22494 }
22495
22496 @ One of the things we need to do when we've parsed an \&{addto} or
22497 similar command is find the header of a supposed \&{picture} variable, given
22498 a token list for that variable.  Since the edge structure is about to be
22499 updated, we use |private_edges| to make sure that this is possible.
22500
22501 @<Declare action procedures for use by |do_statement|@>=
22502 pointer mp_find_edges_var (MP mp, pointer t) ;
22503
22504 @ @c pointer mp_find_edges_var (MP mp, pointer t) {
22505   pointer p;
22506   pointer cur_edges; /* the return value */
22507   p=mp_find_variable(mp, t); cur_edges=null;
22508   if ( p==null ) { 
22509     mp_obliterated(mp, t); mp_put_get_error(mp);
22510   } else if ( type(p)!=mp_picture_type )  { 
22511     print_err("Variable "); mp_show_token_list(mp, t,null,1000,0);
22512 @.Variable x is the wrong type@>
22513     mp_print(mp, " is the wrong type ("); 
22514     mp_print_type(mp, type(p)); mp_print_char(mp, ')');
22515     help2("I was looking for a \"known\" picture variable.")
22516          ("So I'll not change anything just now."); 
22517     mp_put_get_error(mp);
22518   } else { 
22519     value(p)=mp_private_edges(mp, value(p));
22520     cur_edges=value(p);
22521   }
22522   mp_flush_node_list(mp, t);
22523   return cur_edges;
22524 };
22525
22526 @ @<Cases of |do_statement|...@>=
22527 case add_to_command: mp_do_add_to(mp); break;
22528 case bounds_command:mp_do_bounds(mp); break;
22529
22530 @ @<Put each...@>=
22531 mp_primitive(mp, "clip",bounds_command,mp_start_clip_code);
22532 @:clip_}{\&{clip} primitive@>
22533 mp_primitive(mp, "setbounds",bounds_command,mp_start_bounds_code);
22534 @:set_bounds_}{\&{setbounds} primitive@>
22535
22536 @ @<Cases of |print_cmd...@>=
22537 case bounds_command: 
22538   if ( m==mp_start_clip_code ) mp_print(mp, "clip");
22539   else mp_print(mp, "setbounds");
22540   break;
22541
22542 @ The following function parses the beginning of an \&{addto} or \&{clip}
22543 command: it expects a variable name followed by a token with |cur_cmd=sep|
22544 and then an expression.  The function returns the token list for the variable
22545 and stores the command modifier for the separator token in the global variable
22546 |last_add_type|.  We must be careful because this variable might get overwritten
22547 any time we call |get_x_next|.
22548
22549 @<Glob...@>=
22550 quarterword last_add_type;
22551   /* command modifier that identifies the last \&{addto} command */
22552
22553 @ @<Declare action procedures for use by |do_statement|@>=
22554 pointer mp_start_draw_cmd (MP mp,quarterword sep) ;
22555
22556 @ @c pointer mp_start_draw_cmd (MP mp,quarterword sep) {
22557   pointer lhv; /* variable to add to left */
22558   quarterword add_type=0; /* value to be returned in |last_add_type| */
22559   lhv=null;
22560   mp_get_x_next(mp); mp->var_flag=sep; mp_scan_primary(mp);
22561   if ( mp->cur_type!=mp_token_list ) {
22562     @<Abandon edges command because there's no variable@>;
22563   } else  { 
22564     lhv=mp->cur_exp; add_type=mp->cur_mod;
22565     mp->cur_type=mp_vacuous; mp_get_x_next(mp); mp_scan_expression(mp);
22566   }
22567   mp->last_add_type=add_type;
22568   return lhv;
22569 }
22570
22571 @ @<Abandon edges command because there's no variable@>=
22572 { exp_err("Not a suitable variable");
22573 @.Not a suitable variable@>
22574   help4("At this point I needed to see the name of a picture variable.")
22575     ("(Or perhaps you have indeed presented me with one; I might")
22576     ("have missed it, if it wasn't followed by the proper token.)")
22577     ("So I'll not change anything just now.");
22578   mp_put_get_flush_error(mp, 0);
22579 }
22580
22581 @ Here is an example of how to use |start_draw_cmd|.
22582
22583 @<Declare action procedures for use by |do_statement|@>=
22584 void mp_do_bounds (MP mp) ;
22585
22586 @ @c void mp_do_bounds (MP mp) {
22587   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22588   pointer p; /* for list manipulation */
22589   integer m; /* initial value of |cur_mod| */
22590   m=mp->cur_mod;
22591   lhv=mp_start_draw_cmd(mp, to_token);
22592   if ( lhv!=null ) {
22593     lhe=mp_find_edges_var(mp, lhv);
22594     if ( lhe==null ) {
22595       mp_flush_cur_exp(mp, 0);
22596     } else if ( mp->cur_type!=mp_path_type ) {
22597       exp_err("Improper `clip'");
22598 @.Improper `addto'@>
22599       help2("This expression should have specified a known path.")
22600         ("So I'll not change anything just now."); 
22601       mp_put_get_flush_error(mp, 0);
22602     } else if ( left_type(mp->cur_exp)==endpoint ) {
22603       @<Complain about a non-cycle@>;
22604     } else {
22605       @<Make |cur_exp| into a \&{setbounds} or clipping path and add it to |lhe|@>;
22606     }
22607   }
22608 }
22609
22610 @ @<Complain about a non-cycle@>=
22611 { print_err("Not a cycle");
22612 @.Not a cycle@>
22613   help2("That contour should have ended with `..cycle' or `&cycle'.")
22614     ("So I'll not change anything just now."); mp_put_get_error(mp);
22615 }
22616
22617 @ @<Make |cur_exp| into a \&{setbounds} or clipping path and add...@>=
22618 { p=mp_new_bounds_node(mp, mp->cur_exp,m);
22619   link(p)=link(dummy_loc(lhe));
22620   link(dummy_loc(lhe))=p;
22621   if ( obj_tail(lhe)==dummy_loc(lhe) ) obj_tail(lhe)=p;
22622   p=mp_get_node(mp, mp->gr_object_size[stop_type(m)]);
22623   type(p)=stop_type(m);
22624   link(obj_tail(lhe))=p;
22625   obj_tail(lhe)=p;
22626   mp_init_bbox(mp, lhe);
22627 }
22628
22629 @ The |do_add_to| procedure is a little like |do_clip| but there are a lot more
22630 cases to deal with.
22631
22632 @<Declare action procedures for use by |do_statement|@>=
22633 void mp_do_add_to (MP mp) ;
22634
22635 @ @c void mp_do_add_to (MP mp) {
22636   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22637   pointer p; /* the graphical object or list for |scan_with_list| to update */
22638   pointer e; /* an edge structure to be merged */
22639   quarterword add_type; /* |also_code|, |contour_code|, or |double_path_code| */
22640   lhv=mp_start_draw_cmd(mp, thing_to_add); add_type=mp->last_add_type;
22641   if ( lhv!=null ) {
22642     if ( add_type==also_code ) {
22643       @<Make sure the current expression is a suitable picture and set |e| and |p|
22644        appropriately@>;
22645     } else {
22646       @<Create a graphical object |p| based on |add_type| and the current
22647         expression@>;
22648     }
22649     mp_scan_with_list(mp, p);
22650     @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>;
22651   }
22652 }
22653
22654 @ Setting |p:=null| causes the $\langle$with list$\rangle$ to be ignored;
22655 setting |e:=null| prevents anything from being added to |lhe|.
22656
22657 @ @<Make sure the current expression is a suitable picture and set |e|...@>=
22658
22659   p=null; e=null;
22660   if ( mp->cur_type!=mp_picture_type ) {
22661     exp_err("Improper `addto'");
22662 @.Improper `addto'@>
22663     help2("This expression should have specified a known picture.")
22664       ("So I'll not change anything just now."); mp_put_get_flush_error(mp, 0);
22665   } else { 
22666     e=mp_private_edges(mp, mp->cur_exp); mp->cur_type=mp_vacuous;
22667     p=link(dummy_loc(e));
22668   }
22669 }
22670
22671 @ In this case |add_type<>also_code| so setting |p:=null| suppresses future
22672 attempts to add to the edge structure.
22673
22674 @<Create a graphical object |p| based on |add_type| and the current...@>=
22675 { e=null; p=null;
22676   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
22677   if ( mp->cur_type!=mp_path_type ) {
22678     exp_err("Improper `addto'");
22679 @.Improper `addto'@>
22680     help2("This expression should have specified a known path.")
22681       ("So I'll not change anything just now."); 
22682     mp_put_get_flush_error(mp, 0);
22683   } else if ( add_type==contour_code ) {
22684     if ( left_type(mp->cur_exp)==endpoint ) {
22685       @<Complain about a non-cycle@>;
22686     } else { 
22687       p=mp_new_fill_node(mp, mp->cur_exp);
22688       mp->cur_type=mp_vacuous;
22689     }
22690   } else { 
22691     p=mp_new_stroked_node(mp, mp->cur_exp);
22692     mp->cur_type=mp_vacuous;
22693   }
22694 }
22695
22696 @ @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>=
22697 lhe=mp_find_edges_var(mp, lhv);
22698 if ( lhe==null ) {
22699   if ( (e==null)&&(p!=null) ) e=mp_toss_gr_object(mp, p);
22700   if ( e!=null ) delete_edge_ref(e);
22701 } else if ( add_type==also_code ) {
22702   if ( e!=null ) {
22703     @<Merge |e| into |lhe| and delete |e|@>;
22704   } else { 
22705     do_nothing;
22706   }
22707 } else if ( p!=null ) {
22708   link(obj_tail(lhe))=p;
22709   obj_tail(lhe)=p;
22710   if ( add_type==double_path_code )
22711     if ( pen_p(p)==null ) 
22712       pen_p(p)=mp_get_pen_circle(mp, 0);
22713 }
22714
22715 @ @<Merge |e| into |lhe| and delete |e|@>=
22716 { if ( link(dummy_loc(e))!=null ) {
22717     link(obj_tail(lhe))=link(dummy_loc(e));
22718     obj_tail(lhe)=obj_tail(e);
22719     obj_tail(e)=dummy_loc(e);
22720     link(dummy_loc(e))=null;
22721     mp_flush_dash_list(mp, lhe);
22722   }
22723   mp_toss_edges(mp, e);
22724 }
22725
22726 @ @<Cases of |do_statement|...@>=
22727 case ship_out_command: mp_do_ship_out(mp); break;
22728
22729 @ @<Declare action procedures for use by |do_statement|@>=
22730 @<Declare the function called |tfm_check|@>;
22731 @<Declare the \ps\ output procedures@>;
22732 void mp_do_ship_out (MP mp) ;
22733
22734 @ @c void mp_do_ship_out (MP mp) {
22735   integer c; /* the character code */
22736   mp_get_x_next(mp); mp_scan_expression(mp);
22737   if ( mp->cur_type!=mp_picture_type ) {
22738     @<Complain that it's not a known picture@>;
22739   } else { 
22740     c=mp_round_unscaled(mp, mp->internal[char_code]) % 256;
22741     if ( c<0 ) c=c+256;
22742     @<Store the width information for character code~|c|@>;
22743     mp_ship_out(mp, mp->cur_exp);
22744     mp_flush_cur_exp(mp, 0);
22745   }
22746 }
22747
22748 @ @<Complain that it's not a known picture@>=
22749
22750   exp_err("Not a known picture");
22751   help1("I can only output known pictures.");
22752   mp_put_get_flush_error(mp, 0);
22753 }
22754
22755 @ The \&{everyjob} command simply assigns a nonzero value to the global variable
22756 |start_sym|.
22757
22758 @<Cases of |do_statement|...@>=
22759 case every_job_command: 
22760   mp_get_symbol(mp); mp->start_sym=mp->cur_sym; mp_get_x_next(mp);
22761   break;
22762
22763 @ @<Glob...@>=
22764 halfword start_sym; /* a symbolic token to insert at beginning of job */
22765
22766 @ @<Set init...@>=
22767 mp->start_sym=0;
22768
22769 @ Finally, we have only the ``message'' commands remaining.
22770
22771 @d message_code 0
22772 @d err_message_code 1
22773 @d err_help_code 2
22774 @d filename_template_code 3
22775 @d print_with_leading_zeroes(A)  g = mp->pool_ptr;
22776               mp_print_int(mp, (A)); g = mp->pool_ptr-g;
22777               if ( f>g ) {
22778                 mp->pool_ptr = mp->pool_ptr - g;
22779                 while ( f>g ) {
22780                   mp_print_char(mp, '0');
22781                   decr(f);
22782                   };
22783                 mp_print_int(mp, (A));
22784               };
22785               f = 0
22786
22787 @<Put each...@>=
22788 mp_primitive(mp, "message",message_command,message_code);
22789 @:message_}{\&{message} primitive@>
22790 mp_primitive(mp, "errmessage",message_command,err_message_code);
22791 @:err_message_}{\&{errmessage} primitive@>
22792 mp_primitive(mp, "errhelp",message_command,err_help_code);
22793 @:err_help_}{\&{errhelp} primitive@>
22794 mp_primitive(mp, "filenametemplate",message_command,filename_template_code);
22795 @:filename_template_}{\&{filenametemplate} primitive@>
22796
22797 @ @<Cases of |print_cmd...@>=
22798 case message_command: 
22799   if ( m<err_message_code ) mp_print(mp, "message");
22800   else if ( m==err_message_code ) mp_print(mp, "errmessage");
22801   else if ( m==filename_template_code ) mp_print(mp, "filenametemplate");
22802   else mp_print(mp, "errhelp");
22803   break;
22804
22805 @ @<Cases of |do_statement|...@>=
22806 case message_command: mp_do_message(mp); break;
22807
22808 @ @<Declare action procedures for use by |do_statement|@>=
22809 @<Declare a procedure called |no_string_err|@>;
22810 void mp_do_message (MP mp) ;
22811
22812
22813 @c void mp_do_message (MP mp) {
22814   int m; /* the type of message */
22815   m=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
22816   if ( mp->cur_type!=mp_string_type )
22817     mp_no_string_err(mp, "A message should be a known string expression.");
22818   else {
22819     switch (m) {
22820     case message_code: 
22821       mp_print_nl(mp, ""); mp_print_str(mp, mp->cur_exp);
22822       break;
22823     case err_message_code:
22824       @<Print string |cur_exp| as an error message@>;
22825       break;
22826     case err_help_code:
22827       @<Save string |cur_exp| as the |err_help|@>;
22828       break;
22829     case filename_template_code:
22830       @<Save the filename template@>;
22831       break;
22832     } /* there are no other cases */
22833   }
22834   mp_flush_cur_exp(mp, 0);
22835 }
22836
22837 @ @<Declare a procedure called |no_string_err|@>=
22838 void mp_no_string_err (MP mp,char *s) { 
22839    exp_err("Not a string");
22840 @.Not a string@>
22841   help1(s);
22842   mp_put_get_error(mp);
22843 }
22844
22845 @ The global variable |err_help| is zero when the user has most recently
22846 given an empty help string, or if none has ever been given.
22847
22848 @<Save string |cur_exp| as the |err_help|@>=
22849
22850   if ( mp->err_help!=0 ) delete_str_ref(mp->err_help);
22851   if ( length(mp->cur_exp)==0 ) mp->err_help=0;
22852   else  { mp->err_help=mp->cur_exp; add_str_ref(mp->err_help); }
22853 }
22854
22855 @ If \&{errmessage} occurs often in |mp_scroll_mode|, without user-defined
22856 \&{errhelp}, we don't want to give a long help message each time. So we
22857 give a verbose explanation only once.
22858
22859 @<Glob...@>=
22860 boolean long_help_seen; /* has the long \.{\\errmessage} help been used? */
22861
22862 @ @<Set init...@>=mp->long_help_seen=false;
22863
22864 @ @<Print string |cur_exp| as an error message@>=
22865
22866   print_err(""); mp_print_str(mp, mp->cur_exp);
22867   if ( mp->err_help!=0 ) {
22868     mp->use_err_help=true;
22869   } else if ( mp->long_help_seen ) { 
22870     help1("(That was another `errmessage'.)") ; 
22871   } else  { 
22872    if ( mp->interaction<mp_error_stop_mode ) mp->long_help_seen=true;
22873     help4("This error message was generated by an `errmessage'")
22874      ("command, so I can\'t give any explicit help.")
22875      ("Pretend that you're Miss Marple: Examine all clues,")
22876 @^Marple, Jane@>
22877      ("and deduce the truth by inspired guesses.");
22878   }
22879   mp_put_get_error(mp); mp->use_err_help=false;
22880 }
22881
22882 @ @<Cases of |do_statement|...@>=
22883 case write_command: mp_do_write(mp); break;
22884
22885 @ @<Declare action procedures for use by |do_statement|@>=
22886 void mp_do_write (MP mp) ;
22887
22888 @ @c void mp_do_write (MP mp) {
22889   str_number t; /* the line of text to be written */
22890   write_index n,n0; /* for searching |wr_fname| and |wr_file| arrays */
22891   int old_setting; /* for saving |selector| during output */
22892   mp_get_x_next(mp);
22893   mp_scan_expression(mp);
22894   if ( mp->cur_type!=mp_string_type ) {
22895     mp_no_string_err(mp, "The text to be written should be a known string expression");
22896   } else if ( mp->cur_cmd!=to_token ) { 
22897     print_err("Missing `to' clause");
22898     help1("A write command should end with `to <filename>'");
22899     mp_put_get_error(mp);
22900   } else { 
22901     t=mp->cur_exp; mp->cur_type=mp_vacuous;
22902     mp_get_x_next(mp);
22903     mp_scan_expression(mp);
22904     if ( mp->cur_type!=mp_string_type )
22905       mp_no_string_err(mp, "I can\'t write to that file name.  It isn't a known string");
22906     else {
22907       @<Write |t| to the file named by |cur_exp|@>;
22908     }
22909     delete_str_ref(t);
22910   }
22911   mp_flush_cur_exp(mp, 0);
22912 }
22913
22914 @ @<Write |t| to the file named by |cur_exp|@>=
22915
22916   @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if
22917     |cur_exp| must be inserted@>;
22918   if ( mp_str_vs_str(mp, t,mp->eof_line)==0 ) {
22919     @<Record the end of file on |wr_file[n]|@>;
22920   } else { 
22921     old_setting=mp->selector;
22922     mp->selector=n+write_file;
22923     mp_print_str(mp, t); mp_print_ln(mp);
22924     mp->selector = old_setting;
22925   }
22926 }
22927
22928 @ @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if...@>=
22929 {
22930   char *fn = str(mp->cur_exp);
22931   n=mp->write_files;
22932   n0=mp->write_files;
22933   while (mp_xstrcmp(fn,mp->wr_fname[n])!=0) { 
22934     if ( n==0 ) { /* bottom reached */
22935           if ( n0==mp->write_files ) {
22936         if ( mp->write_files<mp->max_write_files ) {
22937           incr(mp->write_files);
22938         } else {
22939           FILE **wr_file;
22940           char **wr_fname;
22941               write_index l,k;
22942           l = mp->max_write_files + (mp->max_write_files>>2);
22943           wr_file = xmalloc((l+1),sizeof(FILE *));
22944           wr_fname = xmalloc((l+1),sizeof(char *));
22945               for (k=0;k<=l;k++) {
22946             if (k<=mp->max_write_files) {
22947                   wr_file[k]=mp->wr_file[k]; 
22948               wr_fname[k]=mp->wr_fname[k];
22949             } else {
22950                   wr_file[k]=0; 
22951               wr_fname[k]=NULL;
22952             }
22953           }
22954               xfree(mp->wr_file); xfree(mp->wr_fname);
22955           mp->max_write_files = l;
22956           mp->wr_file = wr_file;
22957           mp->wr_fname = wr_fname;
22958         }
22959       }
22960       n=n0;
22961       mp_open_write_file(mp, fn ,n);
22962     } else { 
22963       decr(n);
22964           if ( mp->wr_fname[n]==NULL )  n0=n; 
22965     }
22966   }
22967 }
22968
22969 @ @<Record the end of file on |wr_file[n]|@>=
22970 { fclose(mp->wr_file[n]);
22971   xfree(mp->wr_fname[n]);
22972   mp->wr_fname[n]=NULL;
22973   if ( n==mp->write_files-1 ) mp->write_files=n;
22974 }
22975
22976
22977 @* \[42] Writing font metric data.
22978 \TeX\ gets its knowledge about fonts from font metric files, also called
22979 \.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
22980 but other programs know about them too. One of \MP's duties is to
22981 write \.{TFM} files so that the user's fonts can readily be
22982 applied to typesetting.
22983 @:TFM files}{\.{TFM} files@>
22984 @^font metric files@>
22985
22986 The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
22987 Since the number of bytes is always a multiple of~4, we could
22988 also regard the file as a sequence of 32-bit words, but \MP\ uses the
22989 byte interpretation. The format of \.{TFM} files was designed by
22990 Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
22991 @^Ramshaw, Lyle Harold@>
22992 of information in a compact but useful form.
22993
22994 @<Glob...@>=
22995 FILE * tfm_file; /* the font metric output goes here */
22996 char * metric_file_name; /* full name of the font metric file */
22997
22998 @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
22999 integers that give the lengths of the various subsequent portions
23000 of the file. These twelve integers are, in order:
23001 $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
23002 |lf|&length of the entire file, in words;\cr
23003 |lh|&length of the header data, in words;\cr
23004 |bc|&smallest character code in the font;\cr
23005 |ec|&largest character code in the font;\cr
23006 |nw|&number of words in the width table;\cr
23007 |nh|&number of words in the height table;\cr
23008 |nd|&number of words in the depth table;\cr
23009 |ni|&number of words in the italic correction table;\cr
23010 |nl|&number of words in the lig/kern table;\cr
23011 |nk|&number of words in the kern table;\cr
23012 |ne|&number of words in the extensible character table;\cr
23013 |np|&number of font parameter words.\cr}}$$
23014 They are all nonnegative and less than $2^{15}$. We must have |bc-1<=ec<=255|,
23015 |ne<=256|, and
23016 $$\hbox{|lf=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
23017 Note that a font may contain as many as 256 characters (if |bc=0| and |ec=255|),
23018 and as few as 0 characters (if |bc=ec+1|).
23019
23020 Incidentally, when two or more 8-bit bytes are combined to form an integer of
23021 16 or more bits, the most significant bytes appear first in the file.
23022 This is called BigEndian order.
23023 @^BigEndian order@>
23024
23025 @ The rest of the \.{TFM} file may be regarded as a sequence of ten data
23026 arrays.
23027
23028 The most important data type used here is a |fix_word|, which is
23029 a 32-bit representation of a binary fraction. A |fix_word| is a signed
23030 quantity, with the two's complement of the entire word used to represent
23031 negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
23032 binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
23033 the smallest is $-2048$. We will see below, however, that all but two of
23034 the |fix_word| values must lie between $-16$ and $+16$.
23035
23036 @ The first data array is a block of header information, which contains
23037 general facts about the font. The header must contain at least two words,
23038 |header[0]| and |header[1]|, whose meaning is explained below.  Additional
23039 header information of use to other software routines might also be
23040 included, and \MP\ will generate it if the \.{headerbyte} command occurs.
23041 For example, 16 more words of header information are in use at the Xerox
23042 Palo Alto Research Center; the first ten specify the character coding
23043 scheme used (e.g., `\.{XEROX TEXT}' or `\.{TEX MATHSY}'), the next five
23044 give the font family name (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
23045 last gives the ``face byte.''
23046
23047 \yskip\hang|header[0]| is a 32-bit check sum that \MP\ will copy into
23048 the \.{GF} output file. This helps ensure consistency between files,
23049 since \TeX\ records the check sums from the \.{TFM}'s it reads, and these
23050 should match the check sums on actual fonts that are used.  The actual
23051 relation between this check sum and the rest of the \.{TFM} file is not
23052 important; the check sum is simply an identification number with the
23053 property that incompatible fonts almost always have distinct check sums.
23054 @^check sum@>
23055
23056 \yskip\hang|header[1]| is a |fix_word| containing the design size of the
23057 font, in units of \TeX\ points. This number must be at least 1.0; it is
23058 fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
23059 font, i.e., a font that was designed to look best at a 10-point size,
23060 whatever that really means. When a \TeX\ user asks for a font `\.{at}
23061 $\delta$ \.{pt}', the effect is to override the design size and replace it
23062 by $\delta$, and to multiply the $x$ and~$y$ coordinates of the points in
23063 the font image by a factor of $\delta$ divided by the design size.  {\sl
23064 All other dimensions in the\/ \.{TFM} file are |fix_word|\kern-1pt\
23065 numbers in design-size units.} Thus, for example, the value of |param[6]|,
23066 which defines the \.{em} unit, is often the |fix_word| value $2^{20}=1.0$,
23067 since many fonts have a design size equal to one em.  The other dimensions
23068 must be less than 16 design-size units in absolute value; thus,
23069 |header[1]| and |param[1]| are the only |fix_word| entries in the whole
23070 \.{TFM} file whose first byte might be something besides 0 or 255.
23071
23072 @ Next comes the |char_info| array, which contains one |char_info_word|
23073 per character. Each word in this part of the file contains six fields
23074 packed into four bytes as follows.
23075
23076 \yskip\hang first byte: |width_index| (8 bits)\par
23077 \hang second byte: |height_index| (4 bits) times 16, plus |depth_index|
23078   (4~bits)\par
23079 \hang third byte: |italic_index| (6 bits) times 4, plus |tag|
23080   (2~bits)\par
23081 \hang fourth byte: |remainder| (8 bits)\par
23082 \yskip\noindent
23083 The actual width of a character is \\{width}|[width_index]|, in design-size
23084 units; this is a device for compressing information, since many characters
23085 have the same width. Since it is quite common for many characters
23086 to have the same height, depth, or italic correction, the \.{TFM} format
23087 imposes a limit of 16 different heights, 16 different depths, and
23088 64 different italic corrections.
23089
23090 Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
23091 \\{italic}[0]=0$ should always hold, so that an index of zero implies a
23092 value of zero.  The |width_index| should never be zero unless the
23093 character does not exist in the font, since a character is valid if and
23094 only if it lies between |bc| and |ec| and has a nonzero |width_index|.
23095
23096 @ The |tag| field in a |char_info_word| has four values that explain how to
23097 interpret the |remainder| field.
23098
23099 \yskip\hang|tag=0| (|no_tag|) means that |remainder| is unused.\par
23100 \hang|tag=1| (|lig_tag|) means that this character has a ligature/kerning
23101 program starting at location |remainder| in the |lig_kern| array.\par
23102 \hang|tag=2| (|list_tag|) means that this character is part of a chain of
23103 characters of ascending sizes, and not the largest in the chain.  The
23104 |remainder| field gives the character code of the next larger character.\par
23105 \hang|tag=3| (|ext_tag|) means that this character code represents an
23106 extensible character, i.e., a character that is built up of smaller pieces
23107 so that it can be made arbitrarily large. The pieces are specified in
23108 |exten[remainder]|.\par
23109 \yskip\noindent
23110 Characters with |tag=2| and |tag=3| are treated as characters with |tag=0|
23111 unless they are used in special circumstances in math formulas. For example,
23112 \TeX's \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
23113 operation looks for both |list_tag| and |ext_tag|.
23114
23115 @d no_tag 0 /* vanilla character */
23116 @d lig_tag 1 /* character has a ligature/kerning program */
23117 @d list_tag 2 /* character has a successor in a charlist */
23118 @d ext_tag 3 /* character is extensible */
23119
23120 @ The |lig_kern| array contains instructions in a simple programming language
23121 that explains what to do for special letter pairs. Each word in this array is a
23122 |lig_kern_command| of four bytes.
23123
23124 \yskip\hang first byte: |skip_byte|, indicates that this is the final program
23125   step if the byte is 128 or more, otherwise the next step is obtained by
23126   skipping this number of intervening steps.\par
23127 \hang second byte: |next_char|, ``if |next_char| follows the current character,
23128   then perform the operation and stop, otherwise continue.''\par
23129 \hang third byte: |op_byte|, indicates a ligature step if less than~128,
23130   a kern step otherwise.\par
23131 \hang fourth byte: |remainder|.\par
23132 \yskip\noindent
23133 In a kern step, an
23134 additional space equal to |kern[256*(op_byte-128)+remainder]| is inserted
23135 between the current character and |next_char|. This amount is
23136 often negative, so that the characters are brought closer together
23137 by kerning; but it might be positive.
23138
23139 There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
23140 $0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
23141 |remainder| is inserted between the current character and |next_char|;
23142 then the current character is deleted if $b=0$, and |next_char| is
23143 deleted if $c=0$; then we pass over $a$~characters to reach the next
23144 current character (which may have a ligature/kerning program of its own).
23145
23146 If the very first instruction of the |lig_kern| array has |skip_byte=255|,
23147 the |next_char| byte is the so-called right boundary character of this font;
23148 the value of |next_char| need not lie between |bc| and~|ec|.
23149 If the very last instruction of the |lig_kern| array has |skip_byte=255|,
23150 there is a special ligature/kerning program for a left boundary character,
23151 beginning at location |256*op_byte+remainder|.
23152 The interpretation is that \TeX\ puts implicit boundary characters
23153 before and after each consecutive string of characters from the same font.
23154 These implicit characters do not appear in the output, but they can affect
23155 ligatures and kerning.
23156
23157 If the very first instruction of a character's |lig_kern| program has
23158 |skip_byte>128|, the program actually begins in location
23159 |256*op_byte+remainder|. This feature allows access to large |lig_kern|
23160 arrays, because the first instruction must otherwise
23161 appear in a location |<=255|.
23162
23163 Any instruction with |skip_byte>128| in the |lig_kern| array must satisfy
23164 the condition
23165 $$\hbox{|256*op_byte+remainder<nl|.}$$
23166 If such an instruction is encountered during
23167 normal program execution, it denotes an unconditional halt; no ligature
23168 command is performed.
23169
23170 @d stop_flag (128)
23171   /* value indicating `\.{STOP}' in a lig/kern program */
23172 @d kern_flag (128) /* op code for a kern step */
23173 @d skip_byte(A) mp->lig_kern[(A)].b0
23174 @d next_char(A) mp->lig_kern[(A)].b1
23175 @d op_byte(A) mp->lig_kern[(A)].b2
23176 @d rem_byte(A) mp->lig_kern[(A)].b3
23177
23178 @ Extensible characters are specified by an |extensible_recipe|, which
23179 consists of four bytes called |top|, |mid|, |bot|, and |rep| (in this
23180 order). These bytes are the character codes of individual pieces used to
23181 build up a large symbol.  If |top|, |mid|, or |bot| are zero, they are not
23182 present in the built-up result. For example, an extensible vertical line is
23183 like an extensible bracket, except that the top and bottom pieces are missing.
23184
23185 Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
23186 if the piece isn't present. Then the extensible characters have the form
23187 $TR^kMR^kB$ from top to bottom, for some |k>=0|, unless $M$ is absent;
23188 in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
23189 The width of the extensible character is the width of $R$; and the
23190 height-plus-depth is the sum of the individual height-plus-depths of the
23191 components used, since the pieces are butted together in a vertical list.
23192
23193 @d ext_top(A) mp->exten[(A)].b0 /* |top| piece in a recipe */
23194 @d ext_mid(A) mp->exten[(A)].b1 /* |mid| piece in a recipe */
23195 @d ext_bot(A) mp->exten[(A)].b2 /* |bot| piece in a recipe */
23196 @d ext_rep(A) mp->exten[(A)].b3 /* |rep| piece in a recipe */
23197
23198 @ The final portion of a \.{TFM} file is the |param| array, which is another
23199 sequence of |fix_word| values.
23200
23201 \yskip\hang|param[1]=slant| is the amount of italic slant, which is used
23202 to help position accents. For example, |slant=.25| means that when you go
23203 up one unit, you also go .25 units to the right. The |slant| is a pure
23204 number; it is the only |fix_word| other than the design size itself that is
23205 not scaled by the design size.
23206
23207 \hang|param[2]=space| is the normal spacing between words in text.
23208 Note that character 040 in the font need not have anything to do with
23209 blank spaces.
23210
23211 \hang|param[3]=space_stretch| is the amount of glue stretching between words.
23212
23213 \hang|param[4]=space_shrink| is the amount of glue shrinking between words.
23214
23215 \hang|param[5]=x_height| is the size of one ex in the font; it is also
23216 the height of letters for which accents don't have to be raised or lowered.
23217
23218 \hang|param[6]=quad| is the size of one em in the font.
23219
23220 \hang|param[7]=extra_space| is the amount added to |param[2]| at the
23221 ends of sentences.
23222
23223 \yskip\noindent
23224 If fewer than seven parameters are present, \TeX\ sets the missing parameters
23225 to zero.
23226
23227 @d slant_code 1
23228 @d space_code 2
23229 @d space_stretch_code 3
23230 @d space_shrink_code 4
23231 @d x_height_code 5
23232 @d quad_code 6
23233 @d extra_space_code 7
23234
23235 @ So that is what \.{TFM} files hold. One of \MP's duties is to output such
23236 information, and it does this all at once at the end of a job.
23237 In order to prepare for such frenetic activity, it squirrels away the
23238 necessary facts in various arrays as information becomes available.
23239
23240 Character dimensions (\&{charwd}, \&{charht}, \&{chardp}, and \&{charic})
23241 are stored respectively in |tfm_width|, |tfm_height|, |tfm_depth|, and
23242 |tfm_ital_corr|. Other information about a character (e.g., about
23243 its ligatures or successors) is accessible via the |char_tag| and
23244 |char_remainder| arrays. Other information about the font as a whole
23245 is kept in additional arrays called |header_byte|, |lig_kern|,
23246 |kern|, |exten|, and |param|.
23247
23248 @d max_tfm_int 32510
23249 @d undefined_label max_tfm_int /* an undefined local label */
23250
23251 @<Glob...@>=
23252 #define TFM_ITEMS 257
23253 eight_bits bc;
23254 eight_bits ec; /* smallest and largest character codes shipped out */
23255 scaled tfm_width[TFM_ITEMS]; /* \&{charwd} values */
23256 scaled tfm_height[TFM_ITEMS]; /* \&{charht} values */
23257 scaled tfm_depth[TFM_ITEMS]; /* \&{chardp} values */
23258 scaled tfm_ital_corr[TFM_ITEMS]; /* \&{charic} values */
23259 boolean char_exists[TFM_ITEMS]; /* has this code been shipped out? */
23260 int char_tag[TFM_ITEMS]; /* |remainder| category */
23261 int char_remainder[TFM_ITEMS]; /* the |remainder| byte */
23262 char *header_byte; /* bytes of the \.{TFM} header */
23263 int header_last; /* last initialized \.{TFM} header byte */
23264 int header_size; /* size of the \.{TFM} header */
23265 four_quarters *lig_kern; /* the ligature/kern table */
23266 short nl; /* the number of ligature/kern steps so far */
23267 scaled *kern; /* distinct kerning amounts */
23268 short nk; /* the number of distinct kerns so far */
23269 four_quarters exten[TFM_ITEMS]; /* extensible character recipes */
23270 short ne; /* the number of extensible characters so far */
23271 scaled *param; /* \&{fontinfo} parameters */
23272 short np; /* the largest \&{fontinfo} parameter specified so far */
23273 short nw;short nh;short nd;short ni; /* sizes of \.{TFM} subtables */
23274 short skip_table[TFM_ITEMS]; /* local label status */
23275 boolean lk_started; /* has there been a lig/kern step in this command yet? */
23276 integer bchar; /* right boundary character */
23277 short bch_label; /* left boundary starting location */
23278 short ll;short lll; /* registers used for lig/kern processing */
23279 short label_loc[257]; /* lig/kern starting addresses */
23280 eight_bits label_char[257]; /* characters for |label_loc| */
23281 short label_ptr; /* highest position occupied in |label_loc| */
23282
23283 @ @<Allocate or initialize ...@>=
23284 mp->header_last = 0; mp->header_size = 128; /* just for init */
23285 mp->header_byte = xmalloc(mp->header_size, sizeof(char));
23286 mp->lig_kern = NULL; /* allocated when needed */
23287 mp->kern = NULL; /* allocated when needed */ 
23288 mp->param = NULL; /* allocated when needed */
23289
23290 @ @<Dealloc variables@>=
23291 xfree(mp->header_byte);
23292 xfree(mp->lig_kern);
23293 xfree(mp->kern);
23294 xfree(mp->param);
23295
23296 @ @<Set init...@>=
23297 for (k=0;k<= 255;k++ ) {
23298   mp->tfm_width[k]=0; mp->tfm_height[k]=0; mp->tfm_depth[k]=0; mp->tfm_ital_corr[k]=0;
23299   mp->char_exists[k]=false; mp->char_tag[k]=no_tag; mp->char_remainder[k]=0;
23300   mp->skip_table[k]=undefined_label;
23301 };
23302 memset(mp->header_byte,0,mp->header_size);
23303 mp->bc=255; mp->ec=0; mp->nl=0; mp->nk=0; mp->ne=0; mp->np=0;
23304 mp->internal[boundary_char]=-unity;
23305 mp->bch_label=undefined_label;
23306 mp->label_loc[0]=-1; mp->label_ptr=0;
23307
23308 @ @<Declarations@>=
23309 scaled mp_tfm_check (MP mp,small_number m) ;
23310
23311 @ @<Declare the function called |tfm_check|@>=
23312 scaled mp_tfm_check (MP mp,small_number m) {
23313   if ( abs(mp->internal[m])>=fraction_half ) {
23314     print_err("Enormous "); mp_print(mp, mp->int_name[m]);
23315 @.Enormous charwd...@>
23316 @.Enormous chardp...@>
23317 @.Enormous charht...@>
23318 @.Enormous charic...@>
23319 @.Enormous designsize...@>
23320     mp_print(mp, " has been reduced");
23321     help1("Font metric dimensions must be less than 2048pt.");
23322     mp_put_get_error(mp);
23323     if ( mp->internal[m]>0 ) return (fraction_half-1);
23324     else return (1-fraction_half);
23325   } else {
23326     return mp->internal[m];
23327   }
23328 }
23329
23330 @ @<Store the width information for character code~|c|@>=
23331 if ( c<mp->bc ) mp->bc=c;
23332 if ( c>mp->ec ) mp->ec=c;
23333 mp->char_exists[c]=true;
23334 mp->tfm_width[c]=mp_tfm_check(mp, char_wd);
23335 mp->tfm_height[c]=mp_tfm_check(mp, char_ht);
23336 mp->tfm_depth[c]=mp_tfm_check(mp, char_dp);
23337 mp->tfm_ital_corr[c]=mp_tfm_check(mp, char_ic)
23338
23339 @ Now let's consider \MP's special \.{TFM}-oriented commands.
23340
23341 @<Cases of |do_statement|...@>=
23342 case tfm_command: mp_do_tfm_command(mp); break;
23343
23344 @ @d char_list_code 0
23345 @d lig_table_code 1
23346 @d extensible_code 2
23347 @d header_byte_code 3
23348 @d font_dimen_code 4
23349
23350 @<Put each...@>=
23351 mp_primitive(mp, "charlist",tfm_command,char_list_code);
23352 @:char_list_}{\&{charlist} primitive@>
23353 mp_primitive(mp, "ligtable",tfm_command,lig_table_code);
23354 @:lig_table_}{\&{ligtable} primitive@>
23355 mp_primitive(mp, "extensible",tfm_command,extensible_code);
23356 @:extensible_}{\&{extensible} primitive@>
23357 mp_primitive(mp, "headerbyte",tfm_command,header_byte_code);
23358 @:header_byte_}{\&{headerbyte} primitive@>
23359 mp_primitive(mp, "fontdimen",tfm_command,font_dimen_code);
23360 @:font_dimen_}{\&{fontdimen} primitive@>
23361
23362 @ @<Cases of |print_cmd...@>=
23363 case tfm_command: 
23364   switch (m) {
23365   case char_list_code:mp_print(mp, "charlist"); break;
23366   case lig_table_code:mp_print(mp, "ligtable"); break;
23367   case extensible_code:mp_print(mp, "extensible"); break;
23368   case header_byte_code:mp_print(mp, "headerbyte"); break;
23369   default: mp_print(mp, "fontdimen"); break;
23370   }
23371   break;
23372
23373 @ @<Declare action procedures for use by |do_statement|@>=
23374 eight_bits mp_get_code (MP mp) ;
23375
23376 @ @c eight_bits mp_get_code (MP mp) { /* scans a character code value */
23377   integer c; /* the code value found */
23378   mp_get_x_next(mp); mp_scan_expression(mp);
23379   if ( mp->cur_type==mp_known ) { 
23380     c=mp_round_unscaled(mp, mp->cur_exp);
23381     if ( c>=0 ) if ( c<256 ) return c;
23382   } else if ( mp->cur_type==mp_string_type ) {
23383     if ( length(mp->cur_exp)==1 )  { 
23384       c=mp->str_pool[mp->str_start[mp->cur_exp]];
23385       return c;
23386     }
23387   }
23388   exp_err("Invalid code has been replaced by 0");
23389 @.Invalid code...@>
23390   help2("I was looking for a number between 0 and 255, or for a")
23391        ("string of length 1. Didn't find it; will use 0 instead.");
23392   mp_put_get_flush_error(mp, 0); c=0;
23393   return c;
23394 };
23395
23396 @ @<Declare action procedures for use by |do_statement|@>=
23397 void mp_set_tag (MP mp,halfword c, small_number t, halfword r) ;
23398
23399 @ @c void mp_set_tag (MP mp,halfword c, small_number t, halfword r) { 
23400   if ( mp->char_tag[c]==no_tag ) {
23401     mp->char_tag[c]=t; mp->char_remainder[c]=r;
23402     if ( t==lig_tag ){ 
23403       incr(mp->label_ptr); mp->label_loc[mp->label_ptr]=r; 
23404       mp->label_char[mp->label_ptr]=c;
23405     }
23406   } else {
23407     @<Complain about a character tag conflict@>;
23408   }
23409 }
23410
23411 @ @<Complain about a character tag conflict@>=
23412
23413   print_err("Character ");
23414   if ( (c>' ')&&(c<127) ) mp_print_char(mp,c);
23415   else if ( c==256 ) mp_print(mp, "||");
23416   else  { mp_print(mp, "code "); mp_print_int(mp, c); };
23417   mp_print(mp, " is already ");
23418 @.Character c is already...@>
23419   switch (mp->char_tag[c]) {
23420   case lig_tag: mp_print(mp, "in a ligtable"); break;
23421   case list_tag: mp_print(mp, "in a charlist"); break;
23422   case ext_tag: mp_print(mp, "extensible"); break;
23423   } /* there are no other cases */
23424   help2("It's not legal to label a character more than once.")
23425     ("So I'll not change anything just now.");
23426   mp_put_get_error(mp); 
23427 }
23428
23429 @ @<Declare action procedures for use by |do_statement|@>=
23430 void mp_do_tfm_command (MP mp) ;
23431
23432 @ @c void mp_do_tfm_command (MP mp) {
23433   int c,cc; /* character codes */
23434   int k; /* index into the |kern| array */
23435   int j; /* index into |header_byte| or |param| */
23436   switch (mp->cur_mod) {
23437   case char_list_code: 
23438     c=mp_get_code(mp);
23439      /* we will store a list of character successors */
23440     while ( mp->cur_cmd==colon )   { 
23441       cc=mp_get_code(mp); mp_set_tag(mp, c,list_tag,cc); c=cc;
23442     };
23443     break;
23444   case lig_table_code: 
23445     if (mp->lig_kern==NULL) 
23446        mp->lig_kern = xmalloc((max_tfm_int+1),sizeof(four_quarters));
23447     if (mp->kern==NULL) 
23448        mp->kern = xmalloc((max_tfm_int+1),sizeof(scaled));
23449     @<Store a list of ligature/kern steps@>;
23450     break;
23451   case extensible_code: 
23452     @<Define an extensible recipe@>;
23453     break;
23454   case header_byte_code: 
23455   case font_dimen_code: 
23456     c=mp->cur_mod; mp_get_x_next(mp);
23457     mp_scan_expression(mp);
23458     if ( (mp->cur_type!=mp_known)||(mp->cur_exp<half_unit) ) {
23459       exp_err("Improper location");
23460 @.Improper location@>
23461       help2("I was looking for a known, positive number.")
23462        ("For safety's sake I'll ignore the present command.");
23463       mp_put_get_error(mp);
23464     } else  { 
23465       j=mp_round_unscaled(mp, mp->cur_exp);
23466       if ( mp->cur_cmd!=colon ) {
23467         mp_missing_err(mp, ":");
23468 @.Missing `:'@>
23469         help1("A colon should follow a headerbyte or fontinfo location.");
23470         mp_back_error(mp);
23471       }
23472       if ( c==header_byte_code ) { 
23473         @<Store a list of header bytes@>;
23474       } else {     
23475         if (mp->param==NULL) 
23476           mp->param = xmalloc((max_tfm_int+1),sizeof(scaled));
23477         @<Store a list of font dimensions@>;
23478       }
23479     }
23480     break;
23481   } /* there are no other cases */
23482 };
23483
23484 @ @<Store a list of ligature/kern steps@>=
23485
23486   mp->lk_started=false;
23487 CONTINUE: 
23488   mp_get_x_next(mp);
23489   if ((mp->cur_cmd==skip_to)&& mp->lk_started )
23490     @<Process a |skip_to| command and |goto done|@>;
23491   if ( mp->cur_cmd==bchar_label ) { c=256; mp->cur_cmd=colon; }
23492   else { mp_back_input(mp); c=mp_get_code(mp); };
23493   if ((mp->cur_cmd==colon)||(mp->cur_cmd==double_colon)) {
23494     @<Record a label in a lig/kern subprogram and |goto continue|@>;
23495   }
23496   if ( mp->cur_cmd==lig_kern_token ) { 
23497     @<Compile a ligature/kern command@>; 
23498   } else  { 
23499     print_err("Illegal ligtable step");
23500 @.Illegal ligtable step@>
23501     help1("I was looking for `=:' or `kern' here.");
23502     mp_back_error(mp); next_char(mp->nl)=qi(0); 
23503     op_byte(mp->nl)=qi(0); rem_byte(mp->nl)=qi(0);
23504     skip_byte(mp->nl)=stop_flag+1; /* this specifies an unconditional stop */
23505   }
23506   if ( mp->nl==max_tfm_int) mp_fatal_error(mp, "ligtable too large");
23507   incr(mp->nl);
23508   if ( mp->cur_cmd==comma ) goto CONTINUE;
23509   if ( skip_byte(mp->nl-1)<stop_flag ) skip_byte(mp->nl-1)=stop_flag;
23510 }
23511 DONE:
23512
23513 @ @<Put each...@>=
23514 mp_primitive(mp, "=:",lig_kern_token,0);
23515 @:=:_}{\.{=:} primitive@>
23516 mp_primitive(mp, "=:|",lig_kern_token,1);
23517 @:=:/_}{\.{=:\char'174} primitive@>
23518 mp_primitive(mp, "=:|>",lig_kern_token,5);
23519 @:=:/>_}{\.{=:\char'174>} primitive@>
23520 mp_primitive(mp, "|=:",lig_kern_token,2);
23521 @:=:/_}{\.{\char'174=:} primitive@>
23522 mp_primitive(mp, "|=:>",lig_kern_token,6);
23523 @:=:/>_}{\.{\char'174=:>} primitive@>
23524 mp_primitive(mp, "|=:|",lig_kern_token,3);
23525 @:=:/_}{\.{\char'174=:\char'174} primitive@>
23526 mp_primitive(mp, "|=:|>",lig_kern_token,7);
23527 @:=:/>_}{\.{\char'174=:\char'174>} primitive@>
23528 mp_primitive(mp, "|=:|>>",lig_kern_token,11);
23529 @:=:/>_}{\.{\char'174=:\char'174>>} primitive@>
23530 mp_primitive(mp, "kern",lig_kern_token,128);
23531 @:kern_}{\&{kern} primitive@>
23532
23533 @ @<Cases of |print_cmd...@>=
23534 case lig_kern_token: 
23535   switch (m) {
23536   case 0:mp_print(mp, "=:"); break;
23537   case 1:mp_print(mp, "=:|"); break;
23538   case 2:mp_print(mp, "|=:"); break;
23539   case 3:mp_print(mp, "|=:|"); break;
23540   case 5:mp_print(mp, "=:|>"); break;
23541   case 6:mp_print(mp, "|=:>"); break;
23542   case 7:mp_print(mp, "|=:|>"); break;
23543   case 11:mp_print(mp, "|=:|>>"); break;
23544   default: mp_print(mp, "kern"); break;
23545   }
23546   break;
23547
23548 @ Local labels are implemented by maintaining the |skip_table| array,
23549 where |skip_table[c]| is either |undefined_label| or the address of the
23550 most recent lig/kern instruction that skips to local label~|c|. In the
23551 latter case, the |skip_byte| in that instruction will (temporarily)
23552 be zero if there were no prior skips to this label, or it will be the
23553 distance to the prior skip.
23554
23555 We may need to cancel skips that span more than 127 lig/kern steps.
23556
23557 @d cancel_skips(A) mp->ll=(A);
23558   do {  
23559     mp->lll=qo(skip_byte(mp->ll)); 
23560     skip_byte(mp->ll)=stop_flag; mp->ll=mp->ll-mp->lll;
23561   } while (mp->lll!=0)
23562 @d skip_error(A) { print_err("Too far to skip");
23563 @.Too far to skip@>
23564   help1("At most 127 lig/kern steps can separate skipto1 from 1::.");
23565   mp_error(mp); cancel_skips((A));
23566   }
23567
23568 @<Process a |skip_to| command and |goto done|@>=
23569
23570   c=mp_get_code(mp);
23571   if ( mp->nl-mp->skip_table[c]>128 ) { /* |skip_table[c]<<nl<=undefined_label| */
23572     skip_error(mp->skip_table[c]); mp->skip_table[c]=undefined_label;
23573   }
23574   if ( mp->skip_table[c]==undefined_label ) skip_byte(mp->nl-1)=qi(0);
23575   else skip_byte(mp->nl-1)=qi(mp->nl-mp->skip_table[c]-1);
23576   mp->skip_table[c]=mp->nl-1; goto DONE;
23577 }
23578
23579 @ @<Record a label in a lig/kern subprogram and |goto continue|@>=
23580
23581   if ( mp->cur_cmd==colon ) {
23582     if ( c==256 ) mp->bch_label=mp->nl;
23583     else mp_set_tag(mp, c,lig_tag,mp->nl);
23584   } else if ( mp->skip_table[c]<undefined_label ) {
23585     mp->ll=mp->skip_table[c]; mp->skip_table[c]=undefined_label;
23586     do {  
23587       mp->lll=qo(skip_byte(mp->ll));
23588       if ( mp->nl-mp->ll>128 ) {
23589         skip_error(mp->ll); goto CONTINUE;
23590       }
23591       skip_byte(mp->ll)=qi(mp->nl-mp->ll-1); mp->ll=mp->ll-mp->lll;
23592     } while (mp->lll!=0);
23593   }
23594   goto CONTINUE;
23595 }
23596
23597 @ @<Compile a ligature/kern...@>=
23598
23599   next_char(mp->nl)=qi(c); skip_byte(mp->nl)=qi(0);
23600   if ( mp->cur_mod<128 ) { /* ligature op */
23601     op_byte(mp->nl)=qi(mp->cur_mod); rem_byte(mp->nl)=qi(mp_get_code(mp));
23602   } else { 
23603     mp_get_x_next(mp); mp_scan_expression(mp);
23604     if ( mp->cur_type!=mp_known ) {
23605       exp_err("Improper kern");
23606 @.Improper kern@>
23607       help2("The amount of kern should be a known numeric value.")
23608         ("I'm zeroing this one. Proceed, with fingers crossed.");
23609       mp_put_get_flush_error(mp, 0);
23610     }
23611     mp->kern[mp->nk]=mp->cur_exp;
23612     k=0; 
23613     while ( mp->kern[k]!=mp->cur_exp ) incr(k);
23614     if ( k==mp->nk ) {
23615       if ( mp->nk==max_tfm_int ) mp_fatal_error(mp, "too many TFM kerns");
23616       incr(mp->nk);
23617     }
23618     op_byte(mp->nl)=kern_flag+(k / 256);
23619     rem_byte(mp->nl)=qi((k % 256));
23620   }
23621   mp->lk_started=true;
23622 }
23623
23624 @ @d missing_extensible_punctuation(A) 
23625   { mp_missing_err(mp, (A));
23626 @.Missing `\char`\#'@>
23627   help1("I'm processing `extensible c: t,m,b,r'."); mp_back_error(mp);
23628   }
23629
23630 @<Define an extensible recipe@>=
23631
23632   if ( mp->ne==256 ) mp_fatal_error(mp, "too many extensible recipies");
23633   c=mp_get_code(mp); mp_set_tag(mp, c,ext_tag,mp->ne);
23634   if ( mp->cur_cmd!=colon ) missing_extensible_punctuation(":");
23635   ext_top(mp->ne)=qi(mp_get_code(mp));
23636   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23637   ext_mid(mp->ne)=qi(mp_get_code(mp));
23638   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23639   ext_bot(mp->ne)=qi(mp_get_code(mp));
23640   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23641   ext_rep(mp->ne)=qi(mp_get_code(mp));
23642   incr(mp->ne);
23643 }
23644
23645 @ The header could contain ASCII zeroes, so can't use |strdup|.
23646
23647 @<Store a list of header bytes@>=
23648 do {  
23649   if ( j>=mp->header_size ) {
23650     int l = mp->header_size + (mp->header_size >> 2);
23651     char *t = xmalloc(l,sizeof(char));
23652     memset(t,0,l); 
23653     memcpy(t,mp->header_byte,mp->header_size);
23654     xfree (mp->header_byte);
23655     mp->header_byte = t;
23656     mp->header_size = l;
23657   }
23658   mp->header_byte[j]=mp_get_code(mp); 
23659   incr(j); incr(mp->header_last);
23660 } while (mp->cur_cmd==comma)
23661
23662 @ @<Store a list of font dimensions@>=
23663 do {  
23664   if ( j>max_tfm_int ) mp_fatal_error(mp, "too many fontdimens");
23665   while ( j>mp->np ) { incr(mp->np); mp->param[mp->np]=0; };
23666   mp_get_x_next(mp); mp_scan_expression(mp);
23667   if ( mp->cur_type!=mp_known ){ 
23668     exp_err("Improper font parameter");
23669 @.Improper font parameter@>
23670     help1("I'm zeroing this one. Proceed, with fingers crossed.");
23671     mp_put_get_flush_error(mp, 0);
23672   }
23673   mp->param[j]=mp->cur_exp; incr(j);
23674 } while (mp->cur_cmd==comma)
23675
23676 @ OK: We've stored all the data that is needed for the \.{TFM} file.
23677 All that remains is to output it in the correct format.
23678
23679 An interesting problem needs to be solved in this connection, because
23680 the \.{TFM} format allows at most 256~widths, 16~heights, 16~depths,
23681 and 64~italic corrections. If the data has more distinct values than
23682 this, we want to meet the necessary restrictions by perturbing the
23683 given values as little as possible.
23684
23685 \MP\ solves this problem in two steps. First the values of a given
23686 kind (widths, heights, depths, or italic corrections) are sorted;
23687 then the list of sorted values is perturbed, if necessary.
23688
23689 The sorting operation is facilitated by having a special node of
23690 essentially infinite |value| at the end of the current list.
23691
23692 @<Initialize table entries...@>=
23693 value(inf_val)=fraction_four;
23694
23695 @ Straight linear insertion is good enough for sorting, since the lists
23696 are usually not terribly long. As we work on the data, the current list
23697 will start at |link(temp_head)| and end at |inf_val|; the nodes in this
23698 list will be in increasing order of their |value| fields.
23699
23700 Given such a list, the |sort_in| function takes a value and returns a pointer
23701 to where that value can be found in the list. The value is inserted in
23702 the proper place, if necessary.
23703
23704 At the time we need to do these operations, most of \MP's work has been
23705 completed, so we will have plenty of memory to play with. The value nodes
23706 that are allocated for sorting will never be returned to free storage.
23707
23708 @d clear_the_list link(temp_head)=inf_val
23709
23710 @c pointer mp_sort_in (MP mp,scaled v) {
23711   pointer p,q,r; /* list manipulation registers */
23712   p=temp_head;
23713   while (1) { 
23714     q=link(p);
23715     if ( v<=value(q) ) break;
23716     p=q;
23717   }
23718   if ( v<value(q) ) {
23719     r=mp_get_node(mp, value_node_size); value(r)=v; link(r)=q; link(p)=r;
23720   }
23721   return link(p);
23722 }
23723
23724 @ Now we come to the interesting part, where we reduce the list if necessary
23725 until it has the required size. The |min_cover| routine is basic to this
23726 process; it computes the minimum number~|m| such that the values of the
23727 current sorted list can be covered by |m|~intervals of width~|d|. It
23728 also sets the global value |perturbation| to the smallest value $d'>d$
23729 such that the covering found by this algorithm would be different.
23730
23731 In particular, |min_cover(0)| returns the number of distinct values in the
23732 current list and sets |perturbation| to the minimum distance between
23733 adjacent values.
23734
23735 @c integer mp_min_cover (MP mp,scaled d) {
23736   pointer p; /* runs through the current list */
23737   scaled l; /* the least element covered by the current interval */
23738   integer m; /* lower bound on the size of the minimum cover */
23739   m=0; p=link(temp_head); mp->perturbation=el_gordo;
23740   while ( p!=inf_val ){ 
23741     incr(m); l=value(p);
23742     do {  p=link(p); } while (value(p)<=l+d);
23743     if ( value(p)-l<mp->perturbation ) 
23744       mp->perturbation=value(p)-l;
23745   }
23746   return m;
23747 }
23748
23749 @ @<Glob...@>=
23750 scaled perturbation; /* quantity related to \.{TFM} rounding */
23751 integer excess; /* the list is this much too long */
23752
23753 @ The smallest |d| such that a given list can be covered with |m| intervals
23754 is determined by the |threshold| routine, which is sort of an inverse
23755 to |min_cover|. The idea is to increase the interval size rapidly until
23756 finding the range, then to go sequentially until the exact borderline has
23757 been discovered.
23758
23759 @c scaled mp_threshold (MP mp,integer m) {
23760   scaled d; /* lower bound on the smallest interval size */
23761   mp->excess=mp_min_cover(mp, 0)-m;
23762   if ( mp->excess<=0 ) {
23763     return 0;
23764   } else  { 
23765     do {  
23766       d=mp->perturbation;
23767     } while (mp_min_cover(mp, d+d)>m);
23768     while ( mp_min_cover(mp, d)>m ) 
23769       d=mp->perturbation;
23770     return d;
23771   }
23772 }
23773
23774 @ The |skimp| procedure reduces the current list to at most |m| entries,
23775 by changing values if necessary. It also sets |info(p):=k| if |value(p)|
23776 is the |k|th distinct value on the resulting list, and it sets
23777 |perturbation| to the maximum amount by which a |value| field has
23778 been changed. The size of the resulting list is returned as the
23779 value of |skimp|.
23780
23781 @c integer mp_skimp (MP mp,integer m) {
23782   scaled d; /* the size of intervals being coalesced */
23783   pointer p,q,r; /* list manipulation registers */
23784   scaled l; /* the least value in the current interval */
23785   scaled v; /* a compromise value */
23786   d=mp_threshold(mp, m); mp->perturbation=0;
23787   q=temp_head; m=0; p=link(temp_head);
23788   while ( p!=inf_val ) {
23789     incr(m); l=value(p); info(p)=m;
23790     if ( value(link(p))<=l+d ) {
23791       @<Replace an interval of values by its midpoint@>;
23792     }
23793     q=p; p=link(p);
23794   }
23795   return m;
23796 }
23797
23798 @ @<Replace an interval...@>=
23799
23800   do {  
23801     p=link(p); info(p)=m;
23802     decr(mp->excess); if ( mp->excess==0 ) d=0;
23803   } while (value(link(p))<=l+d);
23804   v=l+halfp(value(p)-l);
23805   if ( value(p)-v>mp->perturbation ) 
23806     mp->perturbation=value(p)-v;
23807   r=q;
23808   do {  
23809     r=link(r); value(r)=v;
23810   } while (r!=p);
23811   link(q)=p; /* remove duplicate values from the current list */
23812 }
23813
23814 @ A warning message is issued whenever something is perturbed by
23815 more than 1/16\thinspace pt.
23816
23817 @c void mp_tfm_warning (MP mp,small_number m) { 
23818   mp_print_nl(mp, "(some "); 
23819   mp_print(mp, mp->int_name[m]);
23820 @.some charwds...@>
23821 @.some chardps...@>
23822 @.some charhts...@>
23823 @.some charics...@>
23824   mp_print(mp, " values had to be adjusted by as much as ");
23825   mp_print_scaled(mp, mp->perturbation); mp_print(mp, "pt)");
23826 }
23827
23828 @ Here's an example of how we use these routines.
23829 The width data needs to be perturbed only if there are 256 distinct
23830 widths, but \MP\ must check for this case even though it is
23831 highly unusual.
23832
23833 An integer variable |k| will be defined when we use this code.
23834 The |dimen_head| array will contain pointers to the sorted
23835 lists of dimensions.
23836
23837 @<Massage the \.{TFM} widths@>=
23838 clear_the_list;
23839 for (k=mp->bc;k<=mp->ec;k++)  {
23840   if ( mp->char_exists[k] )
23841     mp->tfm_width[k]=mp_sort_in(mp, mp->tfm_width[k]);
23842 }
23843 mp->nw=mp_skimp(mp, 255)+1; mp->dimen_head[1]=link(temp_head);
23844 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, char_wd)
23845
23846 @ @<Glob...@>=
23847 pointer dimen_head[5]; /* lists of \.{TFM} dimensions */
23848
23849 @ Heights, depths, and italic corrections are different from widths
23850 not only because their list length is more severely restricted, but
23851 also because zero values do not need to be put into the lists.
23852
23853 @<Massage the \.{TFM} heights, depths, and italic corrections@>=
23854 clear_the_list;
23855 for (k=mp->bc;k<=mp->ec;k++) {
23856   if ( mp->char_exists[k] ) {
23857     if ( mp->tfm_height[k]==0 ) mp->tfm_height[k]=zero_val;
23858     else mp->tfm_height[k]=mp_sort_in(mp, mp->tfm_height[k]);
23859   }
23860 }
23861 mp->nh=mp_skimp(mp, 15)+1; mp->dimen_head[2]=link(temp_head);
23862 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, char_ht);
23863 clear_the_list;
23864 for (k=mp->bc;k<=mp->ec;k++) {
23865   if ( mp->char_exists[k] ) {
23866     if ( mp->tfm_depth[k]==0 ) mp->tfm_depth[k]=zero_val;
23867     else mp->tfm_depth[k]=mp_sort_in(mp, mp->tfm_depth[k]);
23868   }
23869 }
23870 mp->nd=mp_skimp(mp, 15)+1; mp->dimen_head[3]=link(temp_head);
23871 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, char_dp);
23872 clear_the_list;
23873 for (k=mp->bc;k<=mp->ec;k++) {
23874   if ( mp->char_exists[k] ) {
23875     if ( mp->tfm_ital_corr[k]==0 ) mp->tfm_ital_corr[k]=zero_val;
23876     else mp->tfm_ital_corr[k]=mp_sort_in(mp, mp->tfm_ital_corr[k]);
23877   }
23878 }
23879 mp->ni=mp_skimp(mp, 63)+1; mp->dimen_head[4]=link(temp_head);
23880 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, char_ic)
23881
23882 @ @<Initialize table entries...@>=
23883 value(zero_val)=0; info(zero_val)=0;
23884
23885 @ Bytes 5--8 of the header are set to the design size, unless the user has
23886 some crazy reason for specifying them differently.
23887
23888 Error messages are not allowed at the time this procedure is called,
23889 so a warning is printed instead.
23890
23891 The value of |max_tfm_dimen| is calculated so that
23892 $$\hbox{|make_scaled(16*max_tfm_dimen,internal[design_size])|}
23893  < \\{three\_bytes}.$$
23894
23895 @d three_bytes 0100000000 /* $2^{24}$ */
23896
23897 @c 
23898 void mp_fix_design_size (MP mp) {
23899   scaled d; /* the design size */
23900   d=mp->internal[design_size];
23901   if ( (d<unity)||(d>=fraction_half) ) {
23902     if ( d!=0 )
23903       mp_print_nl(mp, "(illegal design size has been changed to 128pt)");
23904 @.illegal design size...@>
23905     d=040000000; mp->internal[design_size]=d;
23906   }
23907   if ( mp->header_byte[4]<0 ) if ( mp->header_byte[5]<0 )
23908     if ( mp->header_byte[6]<0 ) if ( mp->header_byte[7]<0 ) {
23909      mp->header_byte[4]=d / 04000000;
23910      mp->header_byte[5]=(d / 4096) % 256;
23911      mp->header_byte[6]=(d / 16) % 256;
23912      mp->header_byte[7]=(d % 16)*16;
23913   };
23914   mp->max_tfm_dimen=16*mp->internal[design_size]-mp->internal[design_size] / 010000000;
23915   if ( mp->max_tfm_dimen>=fraction_half ) mp->max_tfm_dimen=fraction_half-1;
23916 }
23917
23918 @ The |dimen_out| procedure computes a |fix_word| relative to the
23919 design size. If the data was out of range, it is corrected and the
23920 global variable |tfm_changed| is increased by~one.
23921
23922 @c integer mp_dimen_out (MP mp,scaled x) { 
23923   if ( abs(x)>mp->max_tfm_dimen ) {
23924     incr(mp->tfm_changed);
23925     if ( x>0 ) x=three_bytes-1; else x=1-three_bytes;
23926   } else {
23927     x=mp_make_scaled(mp, x*16,mp->internal[design_size]);
23928   }
23929   return x;
23930 }
23931
23932 @ @<Glob...@>=
23933 scaled max_tfm_dimen; /* bound on widths, heights, kerns, etc. */
23934 integer tfm_changed; /* the number of data entries that were out of bounds */
23935
23936 @ If the user has not specified any of the first four header bytes,
23937 the |fix_check_sum| procedure replaces them by a ``check sum'' computed
23938 from the |tfm_width| data relative to the design size.
23939 @^check sum@>
23940
23941 @c void mp_fix_check_sum (MP mp) {
23942   eight_bits k; /* runs through character codes */
23943   eight_bits B1,B2,B3,B4; /* bytes of the check sum */
23944   integer x;  /* hash value used in check sum computation */
23945   if ( mp->header_byte[0]==0 && mp->header_byte[1]==0 &&
23946        mp->header_byte[2]==0 && mp->header_byte[3]==0 ) {
23947     @<Compute a check sum in |(b1,b2,b3,b4)|@>;
23948     mp->header_byte[0]=B1; mp->header_byte[1]=B2;
23949     mp->header_byte[2]=B3; mp->header_byte[3]=B4; 
23950     return;
23951   }
23952 }
23953
23954 @ @<Compute a check sum in |(b1,b2,b3,b4)|@>=
23955 B1=mp->bc; B2=mp->ec; B3=mp->bc; B4=mp->ec; mp->tfm_changed=0;
23956 for (k=mp->bc;k<=mp->ec;k++) { 
23957   if ( mp->char_exists[k] ) {
23958     x=mp_dimen_out(mp, value(mp->tfm_width[k]))+(k+4)*020000000; /* this is positive */
23959     B1=(B1+B1+x) % 255;
23960     B2=(B2+B2+x) % 253;
23961     B3=(B3+B3+x) % 251;
23962     B4=(B4+B4+x) % 247;
23963   }
23964 }
23965
23966 @ Finally we're ready to actually write the \.{TFM} information.
23967 Here are some utility routines for this purpose.
23968
23969 @d tfm_out(A) fputc((A),mp->tfm_file) /* output one byte to |tfm_file| */
23970
23971 @c void mp_tfm_two (MP mp,integer x) { /* output two bytes to |tfm_file| */
23972   tfm_out(x / 256); tfm_out(x % 256);
23973 }
23974 void mp_tfm_four (MP mp,integer x) { /* output four bytes to |tfm_file| */
23975   if ( x>=0 ) tfm_out(x / three_bytes);
23976   else { 
23977     x=x+010000000000; /* use two's complement for negative values */
23978     x=x+010000000000;
23979     tfm_out((x / three_bytes) + 128);
23980   };
23981   x=x % three_bytes; tfm_out(x / unity);
23982   x=x % unity; tfm_out(x / 0400);
23983   tfm_out(x % 0400);
23984 }
23985 void mp_tfm_qqqq (MP mp,four_quarters x) { /* output four quarterwords to |tfm_file| */
23986   tfm_out(qo(x.b0)); tfm_out(qo(x.b1)); 
23987   tfm_out(qo(x.b2)); tfm_out(qo(x.b3));
23988 }
23989
23990 @ @<Finish the \.{TFM} file@>=
23991 if ( mp->job_name==NULL ) mp_open_log_file(mp);
23992 mp_pack_job_name(mp, ".tfm");
23993 while ( ! mp_b_open_out(mp, &mp->tfm_file, mp_filetype_metrics) )
23994   mp_prompt_file_name(mp, "file name for font metrics",".tfm");
23995 mp->metric_file_name=xstrdup(mp->name_of_file);
23996 @<Output the subfile sizes and header bytes@>;
23997 @<Output the character information bytes, then
23998   output the dimensions themselves@>;
23999 @<Output the ligature/kern program@>;
24000 @<Output the extensible character recipes and the font metric parameters@>;
24001   if ( mp->internal[tracing_stats]>0 )
24002   @<Log the subfile sizes of the \.{TFM} file@>;
24003 mp_print_nl(mp, "Font metrics written on "); 
24004 mp_print(mp, mp->metric_file_name); mp_print_char(mp, '.');
24005 @.Font metrics written...@>
24006 fclose(mp->tfm_file)
24007
24008 @ Integer variables |lh|, |k|, and |lk_offset| will be defined when we use
24009 this code.
24010
24011 @<Output the subfile sizes and header bytes@>=
24012 k=mp->header_last;
24013 LH=(k+3) / 4; /* this is the number of header words */
24014 if ( mp->bc>mp->ec ) mp->bc=1; /* if there are no characters, |ec=0| and |bc=1| */
24015 @<Compute the ligature/kern program offset and implant the
24016   left boundary label@>;
24017 mp_tfm_two(mp,6+LH+(mp->ec-mp->bc+1)+mp->nw+mp->nh+mp->nd+mp->ni+mp->nl
24018      +lk_offset+mp->nk+mp->ne+mp->np);
24019   /* this is the total number of file words that will be output */
24020 mp_tfm_two(mp, LH); mp_tfm_two(mp, mp->bc); mp_tfm_two(mp, mp->ec); 
24021 mp_tfm_two(mp, mp->nw); mp_tfm_two(mp, mp->nh);
24022 mp_tfm_two(mp, mp->nd); mp_tfm_two(mp, mp->ni); mp_tfm_two(mp, mp->nl+lk_offset); 
24023 mp_tfm_two(mp, mp->nk); mp_tfm_two(mp, mp->ne);
24024 mp_tfm_two(mp, mp->np);
24025 for (k=0;k< 4*LH;k++)   { 
24026   tfm_out(mp->header_byte[k]);
24027 }
24028
24029 @ @<Output the character information bytes...@>=
24030 for (k=mp->bc;k<=mp->ec;k++) {
24031   if ( ! mp->char_exists[k] ) {
24032     mp_tfm_four(mp, 0);
24033   } else { 
24034     tfm_out(info(mp->tfm_width[k])); /* the width index */
24035     tfm_out((info(mp->tfm_height[k]))*16+info(mp->tfm_depth[k]));
24036     tfm_out((info(mp->tfm_ital_corr[k]))*4+mp->char_tag[k]);
24037     tfm_out(mp->char_remainder[k]);
24038   };
24039 }
24040 mp->tfm_changed=0;
24041 for (k=1;k<=4;k++) { 
24042   mp_tfm_four(mp, 0); p=mp->dimen_head[k];
24043   while ( p!=inf_val ) {
24044     mp_tfm_four(mp, mp_dimen_out(mp, value(p))); p=link(p);
24045   }
24046 }
24047
24048
24049 @ We need to output special instructions at the beginning of the
24050 |lig_kern| array in order to specify the right boundary character
24051 and/or to handle starting addresses that exceed 255. The |label_loc|
24052 and |label_char| arrays have been set up to record all the
24053 starting addresses; we have $-1=|label_loc|[0]<|label_loc|[1]\le\cdots
24054 \le|label_loc|[|label_ptr]|$.
24055
24056 @<Compute the ligature/kern program offset...@>=
24057 mp->bchar=mp_round_unscaled(mp, mp->internal[boundary_char]);
24058 if ((mp->bchar<0)||(mp->bchar>255))
24059   { mp->bchar=-1; mp->lk_started=false; lk_offset=0; }
24060 else { mp->lk_started=true; lk_offset=1; };
24061 @<Find the minimum |lk_offset| and adjust all remainders@>;
24062 if ( mp->bch_label<undefined_label )
24063   { skip_byte(mp->nl)=qi(255); next_char(mp->nl)=qi(0);
24064   op_byte(mp->nl)=qi(((mp->bch_label+lk_offset)/ 256));
24065   rem_byte(mp->nl)=qi(((mp->bch_label+lk_offset)% 256));
24066   incr(mp->nl); /* possibly |nl=lig_table_size+1| */
24067   }
24068
24069 @ @<Find the minimum |lk_offset|...@>=
24070 k=mp->label_ptr; /* pointer to the largest unallocated label */
24071 if ( mp->label_loc[k]+lk_offset>255 ) {
24072   lk_offset=0; mp->lk_started=false; /* location 0 can do double duty */
24073   do {  
24074     mp->char_remainder[mp->label_char[k]]=lk_offset;
24075     while ( mp->label_loc[k-1]==mp->label_loc[k] ) {
24076        decr(k); mp->char_remainder[mp->label_char[k]]=lk_offset;
24077     }
24078     incr(lk_offset); decr(k);
24079   } while (! (lk_offset+mp->label_loc[k]<256));
24080     /* N.B.: |lk_offset=256| satisfies this when |k=0| */
24081 };
24082 if ( lk_offset>0 ) {
24083   while ( k>0 ) {
24084     mp->char_remainder[mp->label_char[k]]
24085      =mp->char_remainder[mp->label_char[k]]+lk_offset;
24086     decr(k);
24087   }
24088 }
24089
24090 @ @<Output the ligature/kern program@>=
24091 for (k=0;k<= 255;k++ ) {
24092   if ( mp->skip_table[k]<undefined_label ) {
24093      mp_print_nl(mp, "(local label "); mp_print_int(mp, k); mp_print(mp, ":: was missing)");
24094 @.local label l:: was missing@>
24095     cancel_skips(mp->skip_table[k]);
24096   }
24097 }
24098 if ( mp->lk_started ) { /* |lk_offset=1| for the special |bchar| */
24099   tfm_out(255); tfm_out(mp->bchar); mp_tfm_two(mp, 0);
24100 } else {
24101   for (k=1;k<=lk_offset;k++) {/* output the redirection specs */
24102     mp->ll=mp->label_loc[mp->label_ptr];
24103     if ( mp->bchar<0 ) { tfm_out(254); tfm_out(0);   }
24104     else { tfm_out(255); tfm_out(mp->bchar);   };
24105     mp_tfm_two(mp, mp->ll+lk_offset);
24106     do {  
24107       decr(mp->label_ptr);
24108     } while (! (mp->label_loc[mp->label_ptr]<mp->ll));
24109   }
24110 }
24111 for (k=0;k<=mp->nl-1;k++) mp_tfm_qqqq(mp, mp->lig_kern[k]);
24112 for (k=0;k<=mp->nk-1;k++) mp_tfm_four(mp, mp_dimen_out(mp, mp->kern[k]))
24113
24114 @ @<Output the extensible character recipes...@>=
24115 for (k=0;k<=mp->ne-1;k++) 
24116   mp_tfm_qqqq(mp, mp->exten[k]);
24117 for (k=1;k<=mp->np;k++) {
24118   if ( k==1 ) {
24119     if ( abs(mp->param[1])<fraction_half ) {
24120       mp_tfm_four(mp, mp->param[1]*16);
24121     } else  { 
24122       incr(mp->tfm_changed);
24123       if ( mp->param[1]>0 ) mp_tfm_four(mp, el_gordo);
24124       else mp_tfm_four(mp, -el_gordo);
24125     }
24126   } else {
24127     mp_tfm_four(mp, mp_dimen_out(mp, mp->param[k]));
24128   }
24129 }
24130 if ( mp->tfm_changed>0 )  { 
24131   if ( mp->tfm_changed==1 ) mp_print_nl(mp, "(a font metric dimension");
24132 @.a font metric dimension...@>
24133   else  { 
24134     mp_print_nl(mp, "("); mp_print_int(mp, mp->tfm_changed);
24135 @.font metric dimensions...@>
24136     mp_print(mp, " font metric dimensions");
24137   }
24138   mp_print(mp, " had to be decreased)");
24139 }
24140
24141 @ @<Log the subfile sizes of the \.{TFM} file@>=
24142
24143   char s[200];
24144   wlog_ln(" ");
24145   if ( mp->bch_label<undefined_label ) decr(mp->nl);
24146   snprintf(s,128,"(You used %iw,%ih,%id,%ii,%il,%ik,%ie,%ip metric file positions)",
24147                  mp->nw, mp->nh, mp->nd, mp->ni, mp->nl, mp->nk, mp->ne,mp->np);
24148   wlog_ln(s);
24149 }
24150
24151 @* \[43] Reading font metric data.
24152
24153 \MP\ isn't a typesetting program but it does need to find the bounding box
24154 of a sequence of typeset characters.  Thus it needs to read \.{TFM} files as
24155 well as write them.
24156
24157 @<Glob...@>=
24158 FILE * tfm_infile;
24159
24160 @ All the width, height, and depth information is stored in an array called
24161 |font_info|.  This array is allocated sequentially and each font is stored
24162 as a series of |char_info| words followed by the width, height, and depth
24163 tables.  Since |font_name| entries are permanent, their |str_ref| values are
24164 set to |max_str_ref|.
24165
24166 @<Types...@>=
24167 typedef unsigned int font_number; /* |0..font_max| */
24168
24169 @ The |font_info| array is indexed via a group directory arrays.
24170 For example, the |char_info| data for character~|c| in font~|f| will be
24171 in |font_info[char_base[f]+c].qqqq|.
24172
24173 @<Glob...@>=
24174 font_number font_max; /* maximum font number for included text fonts */
24175 size_t      font_mem_size; /* number of words for \.{TFM} information for text fonts */
24176 memory_word *font_info; /* height, width, and depth data */
24177 char        **font_enc_name; /* encoding names, if any */
24178 boolean     *font_ps_name_fixed; /* are the postscript names fixed already?  */
24179 int         next_fmem; /* next unused entry in |font_info| */
24180 font_number last_fnum; /* last font number used so far */
24181 scaled      *font_dsize;  /* 16 times the ``design'' size in \ps\ points */
24182 char        **font_name;  /* name as specified in the \&{infont} command */
24183 char        **font_ps_name;  /* PostScript name for use when |internal[prologues]>0| */
24184 font_number last_ps_fnum; /* last valid |font_ps_name| index */
24185 eight_bits  *font_bc;
24186 eight_bits  *font_ec;  /* first and last character code */
24187 int         *char_base;  /* base address for |char_info| */
24188 int         *width_base; /* index for zeroth character width */
24189 int         *height_base; /* index for zeroth character height */
24190 int         *depth_base; /* index for zeroth character depth */
24191 pointer     *font_sizes;
24192
24193 @ @<Allocate or initialize ...@>=
24194 mp->font_mem_size = 10000; 
24195 mp->font_info = xmalloc ((mp->font_mem_size+1),sizeof(memory_word));
24196 memset (mp->font_info,0,sizeof(memory_word)*(mp->font_mem_size+1));
24197 mp->font_enc_name = NULL;
24198 mp->font_ps_name_fixed = NULL;
24199 mp->font_dsize = NULL;
24200 mp->font_name = NULL;
24201 mp->font_ps_name = NULL;
24202 mp->font_bc = NULL;
24203 mp->font_ec = NULL;
24204 mp->last_fnum = null_font;
24205 mp->char_base = NULL;
24206 mp->width_base = NULL;
24207 mp->height_base = NULL;
24208 mp->depth_base = NULL;
24209 mp->font_sizes = null;
24210
24211 @ @<Dealloc variables@>=
24212 xfree(mp->font_info);
24213 xfree(mp->font_enc_name);
24214 xfree(mp->font_ps_name_fixed);
24215 xfree(mp->font_dsize);
24216 xfree(mp->font_name);
24217 xfree(mp->font_ps_name);
24218 xfree(mp->font_bc);
24219 xfree(mp->font_ec);
24220 xfree(mp->char_base);
24221 xfree(mp->width_base);
24222 xfree(mp->height_base);
24223 xfree(mp->depth_base);
24224 xfree(mp->font_sizes);
24225
24226
24227 @c 
24228 void mp_reallocate_fonts (MP mp, font_number l) {
24229   font_number f;
24230   XREALLOC(mp->font_enc_name,      (l+1), char *);
24231   XREALLOC(mp->font_ps_name_fixed, (l+1), boolean);
24232   XREALLOC(mp->font_dsize,         (l+1), scaled);
24233   XREALLOC(mp->font_name,          (l+1), char *);
24234   XREALLOC(mp->font_ps_name,       (l+1), char *);
24235   XREALLOC(mp->font_bc,            (l+1), eight_bits);
24236   XREALLOC(mp->font_ec,            (l+1), eight_bits);
24237   XREALLOC(mp->char_base,          (l+1), int);
24238   XREALLOC(mp->width_base,         (l+1), int);
24239   XREALLOC(mp->height_base,        (l+1), int);
24240   XREALLOC(mp->depth_base,         (l+1), int);
24241   XREALLOC(mp->font_sizes,         (l+1), pointer);
24242   for (f=(mp->last_fnum+1);f<=l;f++) {
24243     mp->font_enc_name[f]=NULL;
24244     mp->font_ps_name_fixed[f] = false;
24245     mp->font_name[f]=NULL;
24246     mp->font_ps_name[f]=NULL;
24247     mp->font_sizes[f]=null;
24248   }
24249   mp->font_max = l;
24250 }
24251
24252 @ @<Declare |mp_reallocate| functions@>=
24253 void mp_reallocate_fonts (MP mp, font_number l);
24254
24255
24256 @ A |null_font| containing no characters is useful for error recovery.  Its
24257 |font_name| entry starts out empty but is reset each time an erroneous font is
24258 found.  This helps to cut down on the number of duplicate error messages without
24259 wasting a lot of space.
24260
24261 @d null_font 0 /* the |font_number| for an empty font */
24262
24263 @<Set initial...@>=
24264 mp->font_dsize[null_font]=0;
24265 mp->font_bc[null_font]=1;
24266 mp->font_ec[null_font]=0;
24267 mp->char_base[null_font]=0;
24268 mp->width_base[null_font]=0;
24269 mp->height_base[null_font]=0;
24270 mp->depth_base[null_font]=0;
24271 mp->next_fmem=0;
24272 mp->last_fnum=null_font;
24273 mp->last_ps_fnum=null_font;
24274 mp->font_name[null_font]="nullfont";
24275 mp->font_ps_name[null_font]="";
24276
24277 @ Each |char_info| word is of type |four_quarters|.  The |b0| field contains
24278 the |width index|; the |b1| field contains the height
24279 index; the |b2| fields contains the depth index, and the |b3| field used only
24280 for temporary storage. (It is used to keep track of which characters occur in
24281 an edge structure that is being shipped out.)
24282 The corresponding words in the width, height, and depth tables are stored as
24283 |scaled| values in units of \ps\ points.
24284
24285 With the macros below, the |char_info| word for character~|c| in font~|f| is
24286 |char_info(f)(c)| and the width is
24287 $$\hbox{|char_width(f)(char_info(f)(c)).sc|.}$$
24288
24289 @d char_info_end(A) (A)].qqqq
24290 @d char_info(A) mp->font_info[mp->char_base[(A)]+char_info_end
24291 @d char_width_end(A) (A).b0].sc
24292 @d char_width(A) mp->font_info[mp->width_base[(A)]+char_width_end
24293 @d char_height_end(A) (A).b1].sc
24294 @d char_height(A) mp->font_info[mp->height_base[(A)]+char_height_end
24295 @d char_depth_end(A) (A).b2].sc
24296 @d char_depth(A) mp->font_info[mp->depth_base[(A)]+char_depth_end
24297 @d ichar_exists(A) ((A).b0>0)
24298
24299 @ The |font_ps_name| for a built-in font should be what PostScript expects.
24300 A preliminary name is obtained here from the \.{TFM} name as given in the
24301 |fname| argument.  This gets updated later from an external table if necessary.
24302
24303 @<Declare text measuring subroutines@>=
24304 @<Declare subroutines for parsing file names@>;
24305 font_number mp_read_font_info (MP mp, char*fname) {
24306   boolean file_opened; /* has |tfm_infile| been opened? */
24307   font_number n; /* the number to return */
24308   halfword lf,tfm_lh,bc,ec,nw,nh,nd; /* subfile size parameters */
24309   size_t whd_size; /* words needed for heights, widths, and depths */
24310   int i,ii; /* |font_info| indices */
24311   int jj; /* counts bytes to be ignored */
24312   scaled z; /* used to compute the design size */
24313   fraction d;
24314   /* height, width, or depth as a fraction of design size times $2^{-8}$ */
24315   eight_bits h_and_d; /* height and depth indices being unpacked */
24316   int tfbyte; /* a byte read from the file */
24317   n=null_font;
24318   @<Open |tfm_infile| for input@>;
24319   @<Read data from |tfm_infile|; if there is no room, say so and |goto done|;
24320     otherwise |goto bad_tfm| or |goto done| as appropriate@>;
24321 BAD_TFM:
24322   @<Complain that the \.{TFM} file is bad@>;
24323 DONE:
24324   if ( file_opened ) fclose(mp->tfm_infile);
24325   if ( n!=null_font ) { 
24326     mp->font_ps_name[n]=fname;
24327     mp->font_name[n]=fname;
24328   }
24329   return n;
24330 }
24331
24332 @ \MP\ doesn't bother to check the entire \.{TFM} file for errors or explain
24333 precisely what is wrong if it does find a problem.  Programs called \.{TFtoPL}
24334 @.TFtoPL@> @.PLtoTF@>
24335 and \.{PLtoTF} can be used to debug \.{TFM} files.
24336
24337 @<Complain that the \.{TFM} file is bad@>=
24338 print_err("Font ");
24339 mp_print(mp, fname);
24340 if ( file_opened ) mp_print(mp, " not usable: TFM file is bad");
24341 else mp_print(mp, " not usable: TFM file not found");
24342 help3("I wasn't able to read the size data for this font so this")
24343   ("`infont' operation won't produce anything. If the font name")
24344   ("is right, you might ask an expert to make a TFM file");
24345 if ( file_opened )
24346   mp->help_line[0]="is right, try asking an expert to fix the TFM file";
24347 mp_error(mp)
24348
24349 @ @<Read data from |tfm_infile|; if there is no room, say so...@>=
24350 @<Read the \.{TFM} size fields@>;
24351 @<Use the size fields to allocate space in |font_info|@>;
24352 @<Read the \.{TFM} header@>;
24353 @<Read the character data and the width, height, and depth tables and
24354   |goto done|@>
24355
24356 @ A bad \.{TFM} file can be shorter than it claims to be.  The code given here
24357 might try to read past the end of the file if this happens.  Changes will be
24358 needed if it causes a system error to refer to |tfm_infile^| or call
24359 |get_tfm_infile| when |eof(tfm_infile)| is true.  For example, the definition
24360 @^system dependencies@>
24361 of |tfget| could be changed to
24362 ``|begin get(tfm_infile); if eof(tfm_infile) then goto bad_tfm; end|.''
24363
24364 @d tfget {tfbyte = fgetc(mp->tfm_infile); }
24365 @d read_two(A) { (A)=tfbyte;
24366   if ( (A)>127 ) goto BAD_TFM;
24367   tfget; (A)=(A)*0400+tfbyte;
24368   }
24369 @d tf_ignore(A) { for (jj=(A);jj>=1;jj--) tfget; }
24370
24371 @<Read the \.{TFM} size fields@>=
24372 tfget; read_two(lf);
24373 tfget; read_two(tfm_lh);
24374 tfget; read_two(bc);
24375 tfget; read_two(ec);
24376 if ( (bc>1+ec)||(ec>255) ) goto BAD_TFM;
24377 tfget; read_two(nw);
24378 tfget; read_two(nh);
24379 tfget; read_two(nd);
24380 whd_size=(ec+1-bc)+nw+nh+nd;
24381 if ( lf<(int)(6+tfm_lh+whd_size) ) goto BAD_TFM;
24382 tf_ignore(10)
24383
24384 @ Offsets are added to |char_base[n]| and |width_base[n]| so that is not
24385 necessary to apply the |so|  and |qo| macros when looking up the width of a
24386 character in the string pool.  In order to ensure nonnegative |char_base|
24387 values when |bc>0|, it may be necessary to reserve a few unused |font_info|
24388 elements.
24389
24390 @<Use the size fields to allocate space in |font_info|@>=
24391 if ( mp->next_fmem<bc) mp->next_fmem=bc;  /* ensure nonnegative |char_base| */
24392 if (mp->last_fnum==mp->font_max)
24393   mp_reallocate_fonts(mp,(mp->font_max+(mp->font_max>>2)));
24394 while (mp->next_fmem+whd_size>=mp->font_mem_size) {
24395   size_t l = mp->font_mem_size+(mp->font_mem_size>>2);
24396   memory_word *font_info;
24397   font_info = xmalloc ((l+1),sizeof(memory_word));
24398   memset (font_info,0,sizeof(memory_word)*(l+1));
24399   memcpy (font_info,mp->font_info,sizeof(memory_word)*(mp->font_mem_size+1));
24400   xfree(mp->font_info);
24401   mp->font_info = font_info;
24402   mp->font_mem_size = l;
24403 }
24404 incr(mp->last_fnum);
24405 n=mp->last_fnum;
24406 mp->font_bc[n]=bc;
24407 mp->font_ec[n]=ec;
24408 mp->char_base[n]=mp->next_fmem-bc;
24409 mp->width_base[n]=mp->next_fmem+ec-bc+1;
24410 mp->height_base[n]=mp->width_base[n]+nw;
24411 mp->depth_base[n]=mp->height_base[n]+nh;
24412 mp->next_fmem=mp->next_fmem+whd_size;
24413
24414
24415 @ @<Read the \.{TFM} header@>=
24416 if ( tfm_lh<2 ) goto BAD_TFM;
24417 tf_ignore(4);
24418 tfget; read_two(z);
24419 tfget; z=z*0400+tfbyte;
24420 tfget; z=z*0400+tfbyte; /* now |z| is 16 times the design size */
24421 mp->font_dsize[n]=mp_take_fraction(mp, z,267432584);
24422   /* times ${72\over72.27}2^{28}$ to convert from \TeX\ points */
24423 tf_ignore(4*(tfm_lh-2))
24424
24425 @ @<Read the character data and the width, height, and depth tables...@>=
24426 ii=mp->width_base[n];
24427 i=mp->char_base[n]+bc;
24428 while ( i<ii ) { 
24429   tfget; mp->font_info[i].qqqq.b0=qi(tfbyte);
24430   tfget; h_and_d=tfbyte;
24431   mp->font_info[i].qqqq.b1=h_and_d / 16;
24432   mp->font_info[i].qqqq.b2=h_and_d % 16;
24433   tfget; tfget;
24434   incr(i);
24435 }
24436 while ( i<mp->next_fmem ) {
24437   @<Read a four byte dimension, scale it by the design size, store it in
24438     |font_info[i]|, and increment |i|@>;
24439 }
24440 if (feof(mp->tfm_infile) ) goto BAD_TFM;
24441 goto DONE
24442
24443 @ The raw dimension read into |d| should have magnitude at most $2^{24}$ when
24444 interpreted as an integer, and this includes a scale factor of $2^{20}$.  Thus
24445 we can multiply it by sixteen and think of it as a |fraction| that has been
24446 divided by sixteen.  This cancels the extra scale factor contained in
24447 |font_dsize[n|.
24448
24449 @<Read a four byte dimension, scale it by the design size, store it in...@>=
24450
24451 tfget; d=tfbyte;
24452 if ( d>=0200 ) d=d-0400;
24453 tfget; d=d*0400+tfbyte;
24454 tfget; d=d*0400+tfbyte;
24455 tfget; d=d*0400+tfbyte;
24456 mp->font_info[i].sc=mp_take_fraction(mp, d*16,mp->font_dsize[n]);
24457 incr(i);
24458 }
24459
24460 @ This function does no longer use the file name parser, because |fname| is
24461 a C string already.
24462 @<Open |tfm_infile| for input@>=
24463 file_opened=false;
24464 mp_ptr_scan_file(mp, fname);
24465 if ( strlen(mp->cur_area)==0 ) mp->cur_area=xstrdup(MP_font_area);
24466 if ( strlen(mp->cur_ext)==0 ) mp->cur_ext=xstrdup(".tfm");
24467 mp->tfm_infile = mp_open_file(mp, fname, "rb",mp_filetype_metrics);
24468 if ( !mp->tfm_infile  ) goto BAD_TFM;
24469 file_opened=true
24470
24471 @ When we have a font name and we don't know whether it has been loaded yet,
24472 we scan the |font_name| array before calling |read_font_info|.
24473
24474 @<Declare text measuring subroutines@>=
24475 font_number mp_find_font (MP mp, char *f) {
24476   font_number n;
24477   for (n=0;n<=mp->last_fnum;n++) {
24478     if (mp_xstrcmp(f,mp->font_name[n])==0 )
24479       return n;
24480   }
24481   return mp_read_font_info(mp, f);
24482 }
24483
24484 @ One simple application of |find_font| is the implementation of the |font_size|
24485 operator that gets the design size for a given font name.
24486
24487 @<Find the design size of the font whose name is |cur_exp|@>=
24488 mp_flush_cur_exp(mp, (mp->font_dsize[mp_find_font(mp, str(mp->cur_exp))]+8) / 16)
24489
24490 @ If we discover that the font doesn't have a requested character, we omit it
24491 from the bounding box computation and expect the \ps\ interpreter to drop it.
24492 This routine issues a warning message if the user has asked for it.
24493
24494 @<Declare text measuring subroutines@>=
24495 void mp_lost_warning (MP mp,font_number f, pool_pointer k) { 
24496   if ( mp->internal[tracing_lost_chars]>0 ) { 
24497     mp_begin_diagnostic(mp);
24498     if ( mp->selector==log_only ) incr(mp->selector);
24499     mp_print_nl(mp, "Missing character: There is no ");
24500 @.Missing character@>
24501     mp_print_str(mp, mp->str_pool[k]); 
24502     mp_print(mp, " in font ");
24503     mp_print(mp, mp->font_name[f]); mp_print_char(mp, '!'); 
24504     mp_end_diagnostic(mp, false);
24505   }
24506 }
24507
24508 @ The whole purpose of saving the height, width, and depth information is to be
24509 able to find the bounding box of an item of text in an edge structure.  The
24510 |set_text_box| procedure takes a text node and adds this information.
24511
24512 @<Declare text measuring subroutines@>=
24513 void mp_set_text_box (MP mp,pointer p) {
24514   font_number f; /* |font_n(p)| */
24515   ASCII_code bc,ec; /* range of valid characters for font |f| */
24516   pool_pointer k,kk; /* current character and character to stop at */
24517   four_quarters cc; /* the |char_info| for the current character */
24518   scaled h,d; /* dimensions of the current character */
24519   width_val(p)=0;
24520   height_val(p)=-el_gordo;
24521   depth_val(p)=-el_gordo;
24522   f=font_n(p);
24523   bc=mp->font_bc[f];
24524   ec=mp->font_ec[f];
24525   kk=str_stop(text_p(p));
24526   k=mp->str_start[text_p(p)];
24527   while ( k<kk ) {
24528     @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>;
24529   }
24530   @<Set the height and depth to zero if the bounding box is empty@>;
24531 }
24532
24533 @ @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>=
24534
24535   if ( (mp->str_pool[k]<bc)||(mp->str_pool[k]>ec) ) {
24536     mp_lost_warning(mp, f,k);
24537   } else { 
24538     cc=char_info(f)(mp->str_pool[k]);
24539     if ( ! ichar_exists(cc) ) {
24540       mp_lost_warning(mp, f,k);
24541     } else { 
24542       width_val(p)=width_val(p)+char_width(f)(cc);
24543       h=char_height(f)(cc);
24544       d=char_depth(f)(cc);
24545       if ( h>height_val(p) ) height_val(p)=h;
24546       if ( d>depth_val(p) ) depth_val(p)=d;
24547     }
24548   }
24549   incr(k);
24550 }
24551
24552 @ Let's hope modern compilers do comparisons correctly when the difference would
24553 overflow.
24554
24555 @<Set the height and depth to zero if the bounding box is empty@>=
24556 if ( height_val(p)<-depth_val(p) ) { 
24557   height_val(p)=0;
24558   depth_val(p)=0;
24559 }
24560
24561 @ The new primitives fontmapfile and fontmapline.
24562
24563 @<Declare action procedures for use by |do_statement|@>=
24564 void mp_do_mapfile (MP mp) ;
24565 void mp_do_mapline (MP mp) ;
24566
24567 @ @c void mp_do_mapfile (MP mp) { 
24568   mp_get_x_next(mp); mp_scan_expression(mp);
24569   if ( mp->cur_type!=mp_string_type ) {
24570     @<Complain about improper map operation@>;
24571   } else {
24572     mp_map_file(mp,mp->cur_exp);
24573   }
24574 }
24575 void mp_do_mapline (MP mp) { 
24576   mp_get_x_next(mp); mp_scan_expression(mp);
24577   if ( mp->cur_type!=mp_string_type ) {
24578      @<Complain about improper map operation@>;
24579   } else { 
24580      mp_map_line(mp,mp->cur_exp);
24581   }
24582 }
24583
24584 @ @<Complain about improper map operation@>=
24585
24586   exp_err("Unsuitable expression");
24587   help1("Only known strings can be map files or map lines.");
24588   mp_put_get_error(mp);
24589 }
24590
24591 @
24592 @<Declare the \ps\ output procedures@>=
24593 void mp_ps_print_cmd (MP mp, char *l, char *s) {
24594   if ( mp->internal[mpprocset]>0 ) { ps_room(strlen(s)); mp_print(mp,s); }
24595   else { ps_room(strlen(l)); mp_print(mp, l); };
24596 }
24597 void mp_print_cmd (MP mp,char *l, char *s) {
24598   if ( mp->internal[mpprocset]>0 ) mp_print(mp, s); 
24599   else mp_print(mp, l);
24600 }
24601
24602 @ To print |scaled| value to PDF output we need some subroutines to ensure
24603 accurary.
24604
24605 @d max_integer   0x7FFFFFFF /* $2^{31}-1$ */
24606
24607 @<Glob...@>=
24608 scaled one_bp; /* scaled value corresponds to 1bp */
24609 scaled one_hundred_bp; /* scaled value corresponds to 100bp */
24610 scaled one_hundred_inch; /* scaled value corresponds to 100in */
24611 integer ten_pow[10]; /* $10^0..10^9$ */
24612 integer scaled_out; /* amount of |scaled| that was taken out in |divide_scaled| */
24613
24614 @ @<Set init...@>=
24615 mp->one_bp = 65782; /* 65781.76 */
24616 mp->one_hundred_bp = 6578176;
24617 mp->one_hundred_inch = 473628672;
24618 mp->ten_pow[0] = 1;
24619 for (i = 1;i<= 9; i++ ) {
24620   mp->ten_pow[i] = 10*mp->ten_pow[i - 1];
24621 }
24622
24623 @ The following function divides |s| by |m|. |dd| is number of decimal digits.
24624
24625 @c scaled mp_divide_scaled (MP mp,scaled s, scaled m, integer  dd) {
24626   scaled q,r;
24627   integer sign,i;
24628   sign = 1;
24629   if ( s < 0 ) { sign = -sign; s = -s; }
24630   if ( m < 0 ) { sign = -sign; m = -m; }
24631   if ( m == 0 )
24632     mp_confusion(mp, "arithmetic: divided by zero");
24633   else if ( m >= (max_integer / 10) )
24634     mp_confusion(mp, "arithmetic: number too big");
24635   q = s / m;
24636   r = s % m;
24637   for (i = 1;i<=dd;i++) {
24638     q = 10*q + (10*r) / m;
24639     r = (10*r) % m;
24640   }
24641   if ( 2*r >= m ) { incr(q); r = r - m; }
24642   mp->scaled_out = sign*(s - (r / mp->ten_pow[dd]));
24643   return (sign*q);
24644 }
24645
24646 @* \[44] Shipping pictures out.
24647 The |ship_out| procedure, to be described below, is given a pointer to
24648 an edge structure. Its mission is to output a file containing the \ps\
24649 description of an edge structure.
24650
24651 @ Each time an edge structure is shipped out we write a new \ps\ output
24652 file named according to the current \&{charcode}.
24653 @:char_code_}{\&{charcode} primitive@>
24654
24655 @<Declare the \ps\ output procedures@>=
24656 void mp_open_output_file (MP mp) ;
24657
24658 @ @c void mp_open_output_file (MP mp) {
24659   integer c; /* \&{charcode} rounded to the nearest integer */
24660   int old_setting; /* previous |selector| setting */
24661   pool_pointer i; /*  indexes into |filename_template|  */
24662   integer cc; /* a temporary integer for template building  */
24663   integer f,g=0; /* field widths */
24664   if ( mp->job_name==NULL ) mp_open_log_file(mp);
24665   c=mp_round_unscaled(mp, mp->internal[char_code]);
24666   if ( mp->filename_template==0 ) {
24667     char *s; /* a file extension derived from |c| */
24668     if ( c<0 ) 
24669       s=xstrdup(".ps");
24670     else 
24671       @<Use |c| to compute the file extension |s|@>;
24672     mp_pack_job_name(mp, s);
24673     xfree(s);
24674     while ( ! mp_a_open_out(mp, &mp->ps_file, mp_filetype_postscript) )
24675       mp_prompt_file_name(mp, "file name for output",s);
24676   } else { /* initializations */
24677     str_number s, n; /* a file extension derived from |c| */
24678     old_setting=mp->selector; 
24679     mp->selector=new_string;
24680     f = 0;
24681     i = mp->str_start[mp->filename_template];
24682     n = rts(""); /* initialize */
24683     while ( i<str_stop(mp->filename_template) ) {
24684        if ( mp->str_pool[i]=='%' ) {
24685       CONTINUE:
24686         incr(i);
24687         if ( i<str_stop(mp->filename_template) ) {
24688           if ( mp->str_pool[i]=='j' ) {
24689             mp_print(mp, mp->job_name);
24690           } else if ( mp->str_pool[i]=='d' ) {
24691              cc= mp_round_unscaled(mp, mp->internal[day]);
24692              print_with_leading_zeroes(cc);
24693           } else if ( mp->str_pool[i]=='m' ) {
24694              cc= mp_round_unscaled(mp, mp->internal[month]);
24695              print_with_leading_zeroes(cc);
24696           } else if ( mp->str_pool[i]=='y' ) {
24697              cc= mp_round_unscaled(mp, mp->internal[year]);
24698              print_with_leading_zeroes(cc);
24699           } else if ( mp->str_pool[i]=='H' ) {
24700              cc= mp_round_unscaled(mp, mp->internal[mp_time]) / 60;
24701              print_with_leading_zeroes(cc);
24702           }  else if ( mp->str_pool[i]=='M' ) {
24703              cc= mp_round_unscaled(mp, mp->internal[mp_time]) % 60;
24704              print_with_leading_zeroes(cc);
24705           } else if ( mp->str_pool[i]=='c' ) {
24706             if ( c<0 ) mp_print(mp, "ps");
24707             else print_with_leading_zeroes(c);
24708           } else if ( (mp->str_pool[i]>='0') && 
24709                       (mp->str_pool[i]<='9') ) {
24710             if ( (f<10)  )
24711               f = (f*10) + mp->str_pool[i]-'0';
24712             goto CONTINUE;
24713           } else {
24714             mp_print_str(mp, mp->str_pool[i]);
24715           }
24716         }
24717       } else {
24718         if ( mp->str_pool[i]=='.' )
24719           if (length(n)==0)
24720             n = mp_make_string(mp);
24721         mp_print_str(mp, mp->str_pool[i]);
24722       };
24723       incr(i);
24724     };
24725     s = mp_make_string(mp);
24726     mp->selector= old_setting;
24727     if (length(n)==0) {
24728        n=s;
24729        s=rts("");
24730     };
24731     mp_pack_file_name(mp, str(n),"",str(s));
24732     while ( ! mp_a_open_out(mp, &mp->ps_file, mp_filetype_postscript) )
24733       mp_prompt_file_name(mp, "file name for output",str(s));
24734     delete_str_ref(n);
24735     delete_str_ref(s);
24736   }
24737   @<Store the true output file name if appropriate@>;
24738   @<Begin the progress report for the output of picture~|c|@>;
24739 }
24740
24741 @ The file extension created here could be up to five characters long in
24742 extreme cases so it may have to be shortened on some systems.
24743 @^system dependencies@>
24744
24745 @<Use |c| to compute the file extension |s|@>=
24746
24747   s = xmalloc(7,1);
24748   snprintf(s,7,".%i",(int)c);
24749 }
24750
24751 @ The user won't want to see all the output file names so we only save the
24752 first and last ones and a count of how many there were.  For this purpose
24753 files are ordered primarily by \&{charcode} and secondarily by order of
24754 creation.
24755 @:char_code_}{\&{charcode} primitive@>
24756
24757 @<Store the true output file name if appropriate@>=
24758 if ((c<mp->first_output_code)&&(mp->first_output_code>=0)) {
24759   mp->first_output_code=c;
24760   xfree(mp->first_file_name);
24761   mp->first_file_name=xstrdup(mp->name_of_file);
24762 }
24763 if ( c>=mp->last_output_code ) {
24764   mp->last_output_code=c;
24765   xfree(mp->last_file_name);
24766   mp->last_file_name=xstrdup(mp->name_of_file);
24767 }
24768
24769 @ @<Glob...@>=
24770 char * first_file_name;
24771 char * last_file_name; /* full file names */
24772 integer first_output_code;integer last_output_code; /* rounded \&{charcode} values */
24773 @:char_code_}{\&{charcode} primitive@>
24774 integer total_shipped; /* total number of |ship_out| operations completed */
24775
24776 @ @<Set init...@>=
24777 mp->first_file_name=xstrdup("");
24778 mp->last_file_name=xstrdup("");
24779 mp->first_output_code=32768;
24780 mp->last_output_code=-32768;
24781 mp->total_shipped=0;
24782
24783 @ @<Dealloc variables@>=
24784 xfree(mp->first_file_name);
24785 xfree(mp->last_file_name);
24786
24787 @ @<Begin the progress report for the output of picture~|c|@>=
24788 if ( (int)mp->term_offset>mp->max_print_line-6 ) mp_print_ln(mp);
24789 else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
24790 mp_print_char(mp, '[');
24791 if ( c>=0 ) mp_print_int(mp, c)
24792
24793 @ @<End progress report@>=
24794 mp_print_char(mp, ']');
24795 update_terminal;
24796 incr(mp->total_shipped)
24797
24798 @ @<Explain what output files were written@>=
24799 if ( mp->total_shipped>0 ) { 
24800   mp_print_nl(mp, "");
24801   mp_print_int(mp, mp->total_shipped);
24802   mp_print(mp, " output file");
24803   if ( mp->total_shipped>1 ) mp_print_char(mp, 's');
24804   mp_print(mp, " written: ");
24805   mp_print(mp, mp->first_file_name);
24806   if ( mp->total_shipped>1 ) {
24807     if ( 31+strlen(mp->first_file_name)+
24808          strlen(mp->last_file_name)> (unsigned)mp->max_print_line) 
24809       mp_print_ln(mp);
24810     mp_print(mp, " .. ");
24811     mp_print(mp, mp->last_file_name);
24812   }
24813 }
24814
24815 @ We often need to print a pair of coordinates.
24816
24817 @d ps_room(A) if ( (mp->ps_offset+(int)(A))>mp->max_print_line ) 
24818   mp_print_ln(mp) /* optional line break */
24819
24820 @<Declare the \ps\ output procedures@>=
24821 void mp_ps_pair_out (MP mp,scaled x, scaled y) { 
24822   ps_room(26);
24823   mp_print_scaled(mp, x); mp_print_char(mp, ' ');
24824   mp_print_scaled(mp, y); mp_print_char(mp, ' ');
24825 }
24826
24827 @ @<Declare the \ps\ output procedures@>=
24828 void mp_ps_print (MP mp,char *s) { 
24829    ps_room(strlen(s));
24830    mp_print(mp, s);
24831 };
24832
24833 @ @<Exported...@>=
24834 void mp_ps_print (MP mp,char *s) ;
24835
24836
24837 @ The most important output procedure is the one that gives the \ps\ version of
24838 a \MP\ path.
24839
24840 @<Declare the \ps\ output procedures@>=
24841 void mp_ps_path_out (MP mp,pointer h) {
24842   pointer p,q; /* for scanning the path */
24843   scaled d; /* a temporary value */
24844   boolean curved; /* |true| unless the cubic is almost straight */
24845   ps_room(40);
24846   if ( mp->need_newpath ) 
24847     mp_print_cmd(mp, "newpath ","n ");
24848   mp->need_newpath=true;
24849   mp_ps_pair_out(mp, x_coord(h),y_coord(h));
24850   mp_print_cmd(mp, "moveto","m");
24851   p=h;
24852   do {  
24853     if ( right_type(p)==endpoint ) { 
24854       if ( p==h ) mp_ps_print_cmd(mp, " 0 0 rlineto"," 0 0 r");
24855       return;
24856     }
24857     q=link(p);
24858     @<Start a new line and print the \ps\ commands for the curve from
24859       |p| to~|q|@>;
24860     p=q;
24861   } while (p!=h);
24862   mp_ps_print_cmd(mp, " closepath"," p");
24863 }
24864
24865 @ @<Glob...@>=
24866 boolean need_newpath;
24867   /* will |ps_path_out| need to issue a \&{newpath} command next time */
24868 @:newpath_}{\&{newpath} command@>
24869
24870 @ @<Start a new line and print the \ps\ commands for the curve from...@>=
24871 curved=true;
24872 @<Set |curved:=false| if the cubic from |p| to |q| is almost straight@>;
24873 mp_print_ln(mp);
24874 if ( curved ){ 
24875   mp_ps_pair_out(mp, right_x(p),right_y(p));
24876   mp_ps_pair_out(mp, left_x(q),left_y(q));
24877   mp_ps_pair_out(mp, x_coord(q),y_coord(q));
24878   mp_ps_print_cmd(mp, "curveto","c");
24879 } else if ( q!=h ){ 
24880   mp_ps_pair_out(mp, x_coord(q),y_coord(q));
24881   mp_ps_print_cmd(mp, "lineto","l");
24882 }
24883
24884 @ Two types of straight lines come up often in \MP\ paths:
24885 cubics with zero initial and final velocity as created by |make_path| or
24886 |make_envelope|, and cubics with control points uniformly spaced on a line
24887 as created by |make_choices|.
24888
24889 @d bend_tolerance 131 /* allow rounding error of $2\cdot10^{-3}$ */
24890
24891 @<Set |curved:=false| if the cubic from |p| to |q| is almost straight@>=
24892 if ( right_x(p)==x_coord(p) )
24893   if ( right_y(p)==y_coord(p) )
24894     if ( left_x(q)==x_coord(q) )
24895       if ( left_y(q)==y_coord(q) ) curved=false;
24896 d=left_x(q)-right_x(p);
24897 if ( abs(right_x(p)-x_coord(p)-d)<=bend_tolerance )
24898   if ( abs(x_coord(q)-left_x(q)-d)<=bend_tolerance )
24899     { d=left_y(q)-right_y(p);
24900     if ( abs(right_y(p)-y_coord(p)-d)<=bend_tolerance )
24901       if ( abs(y_coord(q)-left_y(q)-d)<=bend_tolerance ) curved=false;
24902     }
24903
24904 @ We need to keep track of several parameters from the \ps\ graphics state.
24905 @^graphics state@>
24906 This allows us to be sure that \ps\ has the correct values when they are
24907 needed without wasting time and space setting them unnecessarily.
24908
24909 @d gs_node_size 10
24910 @d gs_red        mp->mem[mp->gs_state+1].sc
24911 @d gs_green      mp->mem[mp->gs_state+2].sc
24912 @d gs_blue       mp->mem[mp->gs_state+3].sc
24913 @d gs_black      mp->mem[mp->gs_state+4].sc
24914    /* color from the last \&{setcmykcolor} or \&{setrgbcolor} or \&{setgray} command */
24915 @d gs_colormodel mp->mem[mp->gs_state+5].qqqq.b0
24916    /* the current colormodel */
24917 @d gs_ljoin      mp->mem[mp->gs_state+5].qqqq.b1
24918 @d gs_lcap       mp->mem[mp->gs_state+5].qqqq.b2
24919    /* values from the last \&{setlinejoin} and \&{setlinecap} commands */
24920 @d gs_adj_wx     mp->mem[mp->gs_state+5].qqqq.b3
24921    /* what resolution-dependent adjustment applies to the width */
24922 @d gs_miterlim   mp->mem[mp->gs_state+6].sc
24923    /* the value from the last \&{setmiterlimit} command */
24924 @d gs_dash_p     mp->mem[mp->gs_state+7].hh.lh
24925    /* edge structure for last \&{setdash} command */
24926 @d gs_previous   mp->mem[mp->gs_state+7].hh.rh
24927    /* backlink to the previous |gs_state| structure */
24928 @d gs_dash_sc    mp->mem[mp->gs_state+8].sc
24929    /* scale factor used with |gs_dash_p| */
24930 @d gs_width      mp->mem[mp->gs_state+9].sc
24931    /* width setting or $-1$ if no \&{setlinewidth} command so far */
24932
24933 @<Glob...@>=
24934 pointer gs_state;
24935
24936 @ @<Set init...@>=
24937 mp->gs_state=null;
24938
24939 @ To avoid making undue assumptions about the initial graphics state, these
24940 parameters are given special values that are guaranteed not to match anything
24941 in the edge structure being shipped out.  On the other hand, the initial color
24942 should be black so that the translation of an all-black picture will have no
24943 \&{setcolor} commands.  (These would be undesirable in a font application.)
24944 Hence we use |c=0| when initializing the graphics state and we use |c<0|
24945 to recover from a situation where we have lost track of the graphics state.
24946
24947 @<Declare the \ps\ output procedures@>=
24948 void mp_unknown_graphics_state (MP mp,scaled c) ;
24949
24950 @ @c void mp_unknown_graphics_state (MP mp,scaled c) {
24951   pointer p; /* to shift graphic states around */
24952   quarterword k; /* a loop index for copying the |gs_state| */
24953   if ( (c==0)||(c==-1) ) {
24954     if ( mp->gs_state==null ) {
24955       mp->gs_state = mp_get_node(mp, gs_node_size);
24956       gs_previous=null;
24957     } else {
24958       while ( gs_previous!=null ) {
24959         p = gs_previous;
24960         mp_free_node(mp, mp->gs_state,gs_node_size);
24961         mp->gs_state=p;
24962       }
24963     }
24964     gs_red=c; gs_green=c; gs_blue=c; gs_black=c;
24965     gs_colormodel=uninitialized_model;
24966     gs_ljoin=3;
24967     gs_lcap=3;
24968     gs_miterlim=0;
24969     gs_dash_p=diov;
24970     gs_dash_sc=0;
24971     gs_width=-1;
24972   } else if ( c==1 ) {
24973     p= mp->gs_state;
24974     mp->gs_state = mp_get_node(mp, gs_node_size);
24975     for (k=1;k<=gs_node_size-1;k++)
24976       mp->mem[mp->gs_state+k]=mp->mem[p+k];
24977     gs_previous = p;
24978   } else if ( c==2 ) {
24979     p = gs_previous;
24980     mp_free_node(mp, mp->gs_state,gs_node_size);
24981     mp->gs_state=p;
24982   }
24983 }
24984
24985 @ When it is time to output a graphical object, |fix_graphics_state| ensures
24986 that \ps's idea of the graphics state agrees with what is stored in the object.
24987
24988 @<Declare the \ps\ output procedures@>=
24989 @<Declare subroutines needed by |fix_graphics_state|@>;
24990 void mp_fix_graphics_state (MP mp, pointer p) ;
24991
24992 @ @c 
24993 void mp_fix_graphics_state (MP mp, pointer p) {
24994   /* get ready to output graphical object |p| */
24995   pointer hh,pp; /* for list manipulation */
24996   scaled wx,wy,ww; /* dimensions of pen bounding box */
24997   boolean adj_wx; /* whether pixel rounding should be based on |wx| or |wy| */
24998   integer tx,ty; /* temporaries for computing |adj_wx| */
24999   scaled scf; /* a scale factor for the dash pattern */
25000   if ( has_color(p) )
25001     @<Make sure \ps\ will use the right color for object~|p|@>;
25002   if ( (type(p)==fill_code)||(type(p)==stroked_code) )
25003     if ( pen_p(p)!=null )
25004       if ( pen_is_elliptical(pen_p(p)) ) {
25005         @<Generate \ps\ code that sets the stroke width to the
25006           appropriate rounded value@>;
25007         @<Make sure \ps\ will use the right dash pattern for |dash_p(p)|@>;
25008         @<Decide whether the line cap parameter matters and set it if necessary@>;
25009         @<Set the other numeric parameters as needed for object~|p|@>;
25010       }
25011   if ( mp->ps_offset>0 ) mp_print_ln(mp);
25012 }
25013
25014 @ @<Decide whether the line cap parameter matters and set it if necessary@>=
25015 if ( type(p)==stroked_code )
25016   if ( (left_type(path_p(p))==endpoint)||(dash_p(p)!=null) )
25017     if ( gs_lcap!=lcap_val(p) ) {
25018       ps_room(13);
25019       mp_print_char(mp, ' ');
25020       mp_print_char(mp, '0'+lcap_val(p)); 
25021       mp_print_cmd(mp, " setlinecap"," lc");
25022       gs_lcap=lcap_val(p);
25023     }
25024
25025 @ @<Set the other numeric parameters as needed for object~|p|@>=
25026 if ( gs_ljoin!=ljoin_val(p) ) {
25027   ps_room(14);
25028   mp_print_char(mp, ' ');
25029   mp_print_char(mp, '0'+ljoin_val(p)); mp_print_cmd(mp, " setlinejoin"," lj");
25030   gs_ljoin=ljoin_val(p);
25031 }
25032 if ( gs_miterlim!=miterlim_val(p) ) {
25033   ps_room(27);
25034   mp_print_char(mp, ' ');
25035   mp_print_scaled(mp, miterlim_val(p)); mp_print_cmd(mp, " setmiterlimit"," ml");
25036   gs_miterlim=miterlim_val(p);
25037 }
25038
25039 @ @<Make sure \ps\ will use the right color for object~|p|@>=
25040 {
25041   if ( (color_model(p)==rgb_model)||
25042      ((color_model(p)==uninitialized_model)&&
25043      ((mp->internal[default_color_model] / unity)==rgb_model)) ) {
25044   if ( (gs_colormodel!=rgb_model)||(gs_red!=red_val(p))||
25045       (gs_green!=green_val(p))||(gs_blue!=blue_val(p)) ) {
25046       gs_red=red_val(p);
25047       gs_green=green_val(p);
25048       gs_blue=blue_val(p);
25049       gs_black= -1;
25050       gs_colormodel=rgb_model;
25051       { ps_room(36);
25052         mp_print_char(mp, ' ');
25053         mp_print_scaled(mp, gs_red); mp_print_char(mp, ' ');
25054         mp_print_scaled(mp, gs_green); mp_print_char(mp, ' ');
25055         mp_print_scaled(mp, gs_blue);
25056         mp_print_cmd(mp, " setrgbcolor", " R");
25057       }
25058     }
25059   } else if ( (color_model(p)==cmyk_model)||
25060      ((color_model(p)==uninitialized_model)&&
25061      ((mp->internal[default_color_model] / unity)==cmyk_model)) ) {
25062    if ( (gs_red!=cyan_val(p))||(gs_green!=magenta_val(p))||
25063       (gs_blue!=yellow_val(p))||(gs_black!=black_val(p))||
25064       (gs_colormodel!=cmyk_model) ) {
25065       if ( color_model(p)==uninitialized_model ) {
25066         gs_red=0;
25067         gs_green=0;
25068         gs_blue=0;
25069         gs_black=unity;
25070       } else {
25071         gs_red=cyan_val(p);
25072         gs_green=magenta_val(p);
25073         gs_blue=yellow_val(p);
25074         gs_black=black_val(p);
25075       }
25076       gs_colormodel=cmyk_model;
25077       { ps_room(45);
25078         mp_print_char(mp, ' ');
25079         mp_print_scaled(mp, gs_red); mp_print_char(mp, ' ');
25080         mp_print_scaled(mp, gs_green); mp_print_char(mp, ' ');
25081         mp_print_scaled(mp, gs_blue); mp_print_char(mp, ' ');
25082         mp_print_scaled(mp, gs_black);
25083         mp_print_cmd(mp, " setcmykcolor"," C");
25084       }
25085     }
25086   } else if ( (color_model(p)==grey_model)||
25087     ((color_model(p)==uninitialized_model)&&
25088      ((mp->internal[default_color_model] / unity)==grey_model)) ) {
25089    if ( (gs_red!=grey_val(p))||(gs_colormodel!=grey_model) ) {
25090       gs_red = grey_val(p);
25091       gs_green= -1;
25092       gs_blue= -1;
25093       gs_black= -1;
25094       gs_colormodel=grey_model;
25095       { ps_room(16);
25096         mp_print_char(mp, ' ');
25097         mp_print_scaled(mp, gs_red);
25098         mp_print_cmd(mp, " setgray"," G");
25099       }
25100     }
25101   }
25102   if ( color_model(p)==no_model )
25103     gs_colormodel=no_model;
25104 }
25105
25106 @ In order to get consistent widths for horizontal and vertical pen strokes, we
25107 want \ps\ to use an integer number of pixels for the \&{setwidth} parameter.
25108 @:setwidth}{\&{setwidth}command@>
25109 We set |gs_width| to the ideal horizontal or vertical stroke width and then
25110 generate \ps\ code that computes the rounded value.  For non-circular pens, the
25111 pen shape will be rescaled so that horizontal or vertical parts of the stroke
25112 have the computed width.
25113
25114 Rounding the width to whole pixels is not likely to improve the appearance of
25115 diagonal or curved strokes, but we do it anyway for consistency.  The
25116 \&{truncate} command generated here tends to make all the strokes a little
25117 @:truncate}{\&{truncate} command@>
25118 thinner, but this is appropriate for \ps's scan-conversion rules.  Even with
25119 truncation, an ideal with of $w$~pixels gets mapped into $\lfloor w\rfloor+1$.
25120 It would be better to have $\lceil w\rceil$ but that is ridiculously expensive
25121 to compute in \ps.
25122
25123 @<Generate \ps\ code that sets the stroke width...@>=
25124 @<Set |wx| and |wy| to the width and height of the bounding box for
25125   |pen_p(p)|@>;
25126 @<Use |pen_p(p)| and |path_p(p)| to decide whether |wx| or |wy| is more
25127   important and set |adj_wx| and |ww| accordingly@>;
25128 if ( (ww!=gs_width) || (adj_wx!=gs_adj_wx) ) {
25129   if ( adj_wx ) {
25130     ps_room(13);
25131     mp_print_char(mp, ' '); mp_print_scaled(mp, ww);
25132     mp_ps_print_cmd(mp, 
25133       " 0 dtransform exch truncate exch idtransform pop setlinewidth"," hlw");
25134   } else {
25135     if ( mp->internal[mpprocset]>0 ) {
25136       ps_room(13);
25137       mp_print_char(mp, ' ');
25138       mp_print_scaled(mp, ww);
25139       mp_ps_print(mp, " vlw");
25140     } else { 
25141       ps_room(15);
25142       mp_print(mp, " 0 "); mp_print_scaled(mp, ww);
25143       mp_ps_print(mp, " dtransform truncate idtransform setlinewidth pop");
25144     }
25145   }
25146   gs_width = ww;
25147   gs_adj_wx = adj_wx;
25148 }
25149
25150 @ @<Set |wx| and |wy| to the width and height of the bounding box for...@>=
25151 pp=pen_p(p);
25152 if ( (right_x(pp)==x_coord(pp)) && (left_y(pp)==y_coord(pp)) ) {
25153   wx = abs(left_x(pp) - x_coord(pp));
25154   wy = abs(right_y(pp) - y_coord(pp));
25155 } else {
25156   wx = mp_pyth_add(mp, left_x(pp)-x_coord(pp), right_x(pp)-x_coord(pp));
25157   wy = mp_pyth_add(mp, left_y(pp)-y_coord(pp), right_y(pp)-y_coord(pp));
25158 }
25159
25160 @ The path is considered ``essentially horizontal'' if its range of
25161 $y$~coordinates is less than the $y$~range |wy| for the pen.  ``Essentially
25162 vertical'' paths are detected similarly.  This code ensures that no component
25163 of the pen transformation is more that |aspect_bound*(ww+1)|.
25164
25165 @d aspect_bound 10 /* ``less important'' of |wx|, |wy| cannot exceed the other by
25166     more than this factor */
25167
25168 @<Use |pen_p(p)| and |path_p(p)| to decide whether |wx| or |wy| is more...@>=
25169 tx=1; ty=1;
25170 if ( mp_coord_rangeOK(mp, path_p(p), y_loc(0), wy) ) tx=aspect_bound;
25171 else if ( mp_coord_rangeOK(mp, path_p(p), x_loc(0), wx) ) ty=aspect_bound;
25172 if ( wy / ty>=wx / tx ) { ww=wy; adj_wx=false; }
25173 else { ww=wx; adj_wx=true;  }
25174
25175 @ This routine quickly tests if path |h| is ``essentially horizontal'' or
25176 ``essentially vertical,'' where |zoff| is |x_loc(0)| or |y_loc(0)| and |dz| is
25177 allowable range for $x$ or~$y$.  We do not need and cannot afford a full
25178 bounding-box computation.
25179
25180 @<Declare subroutines needed by |fix_graphics_state|@>=
25181 boolean mp_coord_rangeOK (MP mp,pointer h, 
25182                           small_number  zoff, scaled dz) {
25183   pointer p; /* for scanning the path form |h| */
25184   scaled zlo,zhi; /* coordinate range so far */
25185   scaled z; /* coordinate currently being tested */
25186   zlo=knot_coord(h+zoff);
25187   zhi=zlo;
25188   p=h;
25189   while ( right_type(p)!=endpoint ) {
25190     z=right_coord(p+zoff);
25191     @<Make |zlo..zhi| include |z| and |return false| if |zhi-zlo>dz|@>;
25192     p=link(p);
25193     z=left_coord(p+zoff);
25194     @<Make |zlo..zhi| include |z| and |return false| if |zhi-zlo>dz|@>;
25195     z=knot_coord(p+zoff);
25196     @<Make |zlo..zhi| include |z| and |return false| if |zhi-zlo>dz|@>;
25197     if ( p==h ) break;
25198   }
25199   return true;
25200 }
25201
25202 @ @<Make |zlo..zhi| include |z| and |return false| if |zhi-zlo>dz|@>=
25203 if ( z<zlo ) zlo=z;
25204 else if ( z>zhi ) zhi=z;
25205 if ( zhi-zlo>dz ) return false
25206
25207 @ Filling with an elliptical pen is implemented via a combination of \&{stroke}
25208 and \&{fill} commands and a nontrivial dash pattern would interfere with this.
25209 @:stroke}{\&{stroke} command@>
25210 @:fill}{\&{fill} command@>
25211 Note that we don't use |delete_edge_ref| because |gs_dash_p| is not counted as
25212 a reference.
25213
25214 @<Make sure \ps\ will use the right dash pattern for |dash_p(p)|@>=
25215 if ( type(p)==fill_code ) {
25216   hh=null;
25217 } else { 
25218   hh=dash_p(p);
25219   scf=mp_get_pen_scale(mp, pen_p(p));
25220   if ( scf==0 ) {
25221     if ( gs_width==0 ) scf=dash_scale(p);  else hh=null;
25222   } else { 
25223     scf=mp_make_scaled(mp, gs_width,scf);
25224     scf=mp_take_scaled(mp, scf,dash_scale(p));
25225   }
25226 }
25227 if ( hh==null ) {
25228   if ( gs_dash_p!=null ) {
25229     mp_ps_print_cmd(mp, " [] 0 setdash"," rd");
25230     gs_dash_p=null;
25231   }
25232 } else if ( (gs_dash_sc!=scf) || ! mp_same_dashes(mp, gs_dash_p,hh) ) {
25233   @<Set the dash pattern from |dash_list(hh)| scaled by |scf|@>;
25234 }
25235
25236 @ Translating a dash list into \ps\ is very similar to printing it symbolically
25237 in |print_edges|.  A dash pattern with |dash_y(hh)=0| has length zero and is
25238 ignored.  The same fate applies in the bizarre case of a dash pattern that
25239 cannot be printed without overflow.
25240
25241 @<Set the dash pattern from |dash_list(hh)| scaled by |scf|@>=
25242 { gs_dash_p=hh;
25243   gs_dash_sc=scf;
25244   if ( (dash_y(hh)==0) || (abs(dash_y(hh)) / unity >= el_gordo / scf)){
25245     mp_ps_print_cmd(mp, " [] 0 setdash"," rd");
25246   } else { 
25247     pp=dash_list(hh);
25248     start_x(null_dash)=start_x(pp)+dash_y(hh);
25249     ps_room(28);
25250     mp_print(mp, " [");
25251     while ( pp!=null_dash ) {
25252       mp_ps_pair_out(mp, mp_take_scaled(mp, stop_x(pp)-start_x(pp),scf),
25253                          mp_take_scaled(mp, start_x(link(pp))-stop_x(pp),scf));
25254       pp=link(pp);
25255     }
25256     ps_room(22);
25257     mp_print(mp, "] ");
25258     mp_print_scaled(mp, mp_take_scaled(mp, mp_dash_offset(mp, hh),scf));
25259     mp_print_cmd(mp, " setdash"," sd");
25260   }
25261 }
25262
25263 @ @<Declare subroutines needed by |fix_graphics_state|@>=
25264 boolean mp_same_dashes (MP mp,pointer h, pointer hh) ;
25265
25266 @ @c
25267 boolean mp_same_dashes (MP mp,pointer h, pointer hh) {
25268   /* do |h| and |hh| represent the same dash pattern? */
25269   pointer p,pp; /* dash nodes being compared */
25270   if ( h==hh ) return true;
25271   else if ( (h<=diov)||(hh<=diov) ) return false;
25272   else if ( dash_y(h)!=dash_y(hh) ) return false;
25273   else { @<Compare |dash_list(h)| and |dash_list(hh)|@>; }
25274   return false; /* can't happen */
25275 }
25276
25277 @ @<Compare |dash_list(h)| and |dash_list(hh)|@>=
25278 { p=dash_list(h);
25279   pp=dash_list(hh);
25280   while ( (p!=null_dash)&&(pp!=null_dash) ) {
25281     if ( (start_x(p)!=start_x(pp))||(stop_x(p)!=stop_x(pp)) ) {
25282       break;
25283     } else { 
25284       p=link(p);
25285       pp=link(pp);
25286     }
25287   }
25288   return (p==pp);
25289 }
25290
25291 @ When stroking a path with an elliptical pen, it is necessary to transform
25292 the coordinate system so that a unit circular pen will have the desired shape.
25293 To keep this transformation local, we enclose it in a
25294 $$\&{gsave}\ldots\&{grestore}$$
25295 block. Any translation component must be applied to the path being stroked
25296 while the rest of the transformation must apply only to the pen.
25297 If |fill_also=true|, the path is to be filled as well as stroked so we must
25298 insert commands to do this after giving the path.
25299
25300 @<Declare the \ps\ output procedures@>=
25301 void mp_stroke_ellipse (MP mp,pointer h, boolean fill_also) ;
25302
25303
25304 @c void mp_stroke_ellipse (MP mp,pointer h, boolean fill_also) {
25305   /* generate an elliptical pen stroke from object |h| */
25306   scaled txx,txy,tyx,tyy; /* transformation parameters */
25307   pointer p; /* the pen to stroke with */
25308   scaled d1,det; /* for tweaking transformation parameters */
25309   integer s; /* also for tweaking transformation paramters */
25310   boolean transformed; /* keeps track of whether gsave/grestore are needed */
25311   transformed=false;
25312   @<Use |pen_p(h)| to set the transformation parameters and give the initial
25313     translation@>;
25314   @<Tweak the transformation parameters so the transformation is nonsingular@>;
25315   mp_ps_path_out(mp, path_p(h));
25316   if ( mp->internal[mpprocset]==0 ) {
25317     if ( fill_also ) mp_print_nl(mp, "gsave fill grestore");
25318     @<Issue \ps\ commands to transform the coordinate system@>;
25319     mp_ps_print(mp, " stroke");
25320     if ( transformed ) mp_ps_print(mp, " grestore");
25321   } else {
25322     if ( fill_also ) mp_print_nl(mp, "B"); else mp_print_ln(mp);
25323     if ( (txy!=0)||(tyx!=0) ) {
25324       mp_print(mp, " [");
25325       mp_ps_pair_out(mp, txx,tyx);
25326       mp_ps_pair_out(mp, txy,tyy);
25327       mp_ps_print(mp, "0 0] t");
25328     } else if ((txx!=unity)||(tyy!=unity) )  {
25329       mp_ps_pair_out(mp,txx,tyy);
25330       mp_print(mp, " s");
25331     };
25332     mp_ps_print(mp, " S");
25333     if ( transformed ) mp_ps_print(mp, " Q");
25334   }
25335   mp_print_ln(mp);
25336 }
25337
25338 @ @<Use |pen_p(h)| to set the transformation parameters and give the...@>=
25339 p=pen_p(h);
25340 txx=left_x(p);
25341 tyx=left_y(p);
25342 txy=right_x(p);
25343 tyy=right_y(p);
25344 if ( (x_coord(p)!=0)||(y_coord(p)!=0) ) {
25345   mp_print_nl(mp, ""); mp_print_cmd(mp, "gsave ","q ");
25346   mp_ps_pair_out(mp, x_coord(p),y_coord(p));
25347   mp_ps_print(mp, "translate ");
25348   txx-=x_coord(p);
25349   tyx-=y_coord(p);
25350   txy-=x_coord(p);
25351   tyy-=y_coord(p);
25352   transformed=true;
25353 } else {
25354   mp_print_nl(mp, "");
25355 }
25356 @<Adjust the transformation to account for |gs_width| and output the
25357   initial \&{gsave} if |transformed| should be |true|@>
25358
25359 @ @<Adjust the transformation to account for |gs_width| and output the...@>=
25360 if ( gs_width!=unity ) {
25361   if ( gs_width==0 ) { 
25362     txx=unity; tyy=unity;
25363   } else { 
25364     txx=mp_make_scaled(mp, txx,gs_width);
25365     txy=mp_make_scaled(mp, txy,gs_width);
25366     tyx=mp_make_scaled(mp, tyx,gs_width);
25367     tyy=mp_make_scaled(mp, tyy,gs_width);
25368   };
25369 }
25370 if ( (txy!=0)||(tyx!=0)||(txx!=unity)||(tyy!=unity) ) {
25371   if ( (! transformed) ){ 
25372     mp_ps_print_cmd(mp, "gsave ","q ");
25373     transformed=true;
25374   }
25375 }
25376
25377 @ @<Issue \ps\ commands to transform the coordinate system@>=
25378 if ( (txy!=0)||(tyx!=0) ){ 
25379   mp_print_ln(mp);
25380   mp_print_char(mp, '[');
25381   mp_ps_pair_out(mp, txx,tyx);
25382   mp_ps_pair_out(mp, txy,tyy);
25383   mp_ps_print(mp, "0 0] concat");
25384 } else if ( (txx!=unity)||(tyy!=unity) ){ 
25385   mp_print_ln(mp);
25386   mp_ps_pair_out(mp, txx,tyy);
25387   mp_print(mp, "scale");
25388 }
25389
25390 @ The \ps\ interpreter will probably abort if it encounters a singular
25391 transformation matrix.  The determinant must be large enough to ensure that
25392 the printed representation will be nonsingular.  Since the printed
25393 representation is always within $2^{-17}$ of the internal |scaled| value, the
25394 total error is at most $4T_{\rm max}2^{-17}$, where $T_{\rm max}$ is a bound on
25395 the magnitudes of |txx/65536|, |txy/65536|, etc.
25396
25397 The |aspect_bound*(gs_width+1)| bound on the components of the pen
25398 transformation allows $T_{\rm max}$ to be at most |2*aspect_bound|.
25399
25400 @<Tweak the transformation parameters so the transformation is nonsingular@>=
25401 det=mp_take_scaled(mp, txx,tyy) - mp_take_scaled(mp, txy,tyx);
25402 d1=4*aspect_bound+1;
25403 if ( abs(det)<d1 ) { 
25404   if ( det>=0 ) { d1=d1-det; s=1;  }
25405   else { d1=-d1-det; s=-1;  };
25406   d1=d1*unity;
25407   if ( abs(txx)+abs(tyy)>=abs(txy)+abs(tyy) ) {
25408     if ( abs(txx)>abs(tyy) ) tyy=tyy+(d1+s*abs(txx)) / txx;
25409     else txx=txx+(d1+s*abs(tyy)) / tyy;
25410   } else {
25411     if ( abs(txy)>abs(tyx) ) tyx=tyx+(d1+s*abs(txy)) / txy;
25412     else txy=txy+(d1+s*abs(tyx)) / tyx;
25413   }
25414 }
25415
25416 @ Here is a simple routine that just fills a cycle.
25417
25418 @<Declare the \ps\ output procedures@>=
25419 void mp_ps_fill_out (MP mp,pointer p) ;
25420
25421 @ @c
25422 void mp_ps_fill_out (MP mp,pointer p) { /* fill cyclic path~|p| */
25423   mp_ps_path_out(mp, p);
25424   mp_ps_print_cmd(mp, " fill"," F");
25425   mp_print_ln(mp);
25426 }
25427
25428 @ Given a cyclic path~|p| and a graphical object~|h|, the |do_outer_envelope|
25429 procedure fills the cycle generated by |make_envelope|.  It need not do
25430 anything unless some region has positive winding number with respect to~|p|,
25431 but it does not seem worthwhile to for test this.
25432
25433 @<Declare the \ps\ output procedures@>=
25434 void mp_do_outer_envelope (MP mp,pointer p, pointer h) ;
25435
25436 @ @c
25437 void mp_do_outer_envelope (MP mp,pointer p, pointer h) {
25438   p=mp_make_envelope(mp, p, pen_p(h), ljoin_val(h), 0, miterlim_val(h));
25439   mp_ps_fill_out(mp, p);
25440   mp_toss_knot_list(mp, p);
25441 }
25442
25443 @ A text node may specify an arbitrary transformation but the usual case
25444 involves only shifting, scaling, and occasionally rotation.  The purpose
25445 of |choose_scale| is to select a scale factor so that the remaining
25446 transformation is as ``nice'' as possible.  The definition of ``nice''
25447 is somewhat arbitrary but shifting and $90^\circ$ rotation are especially
25448 nice because they work out well for bitmap fonts.  The code here selects
25449 a scale factor equal to $1/\sqrt2$ times the Frobenius norm of the
25450 non-shifting part of the transformation matrix.  It is careful to avoid
25451 additions that might cause undetected overflow.
25452
25453 @<Declare the \ps\ output procedures@>=
25454 scaled mp_choose_scale (MP mp,pointer p) ;
25455
25456 @ @c scaled mp_choose_scale (MP mp,pointer p) {
25457   /* |p| should point to a text node */
25458   scaled a,b,c,d,ad,bc; /* temporary values */
25459   a=txx_val(p);
25460   b=txy_val(p);
25461   c=tyx_val(p);
25462   d=tyy_val(p);
25463   if ( (a<0) ) negate(a);
25464   if ( (b<0) ) negate(b);
25465   if ( (c<0) ) negate(c);
25466   if ( (d<0) ) negate(d);
25467   ad=half(a-d);
25468   bc=half(b-c);
25469   return mp_pyth_add(mp, mp_pyth_add(mp, d+ad,ad), mp_pyth_add(mp, c+bc,bc));
25470 }
25471
25472 @ @<Declare the \ps\ output procedures@>=
25473 void mp_ps_string_out (MP mp, char *s) {
25474   char *i; /* current character code position */
25475   ASCII_code k; /* bits to be converted to octal */
25476   mp_print(mp, "(");
25477   i=s;
25478   while (*i) {
25479     if ( mp->ps_offset+5>mp->max_print_line ) {
25480       mp_print_char(mp, '\\');
25481       mp_print_ln(mp);
25482     }
25483     k=*i;
25484     if ( (@<Character |k| is not allowed in PostScript output@>) ) {
25485       mp_print_char(mp, '\\');
25486       mp_print_char(mp, '0'+(k / 64));
25487       mp_print_char(mp, '0'+((k / 8) % 8));
25488       mp_print_char(mp, '0'+(k % 8));
25489     } else { 
25490       if ( (k=='(')||(k==')')||(k=='\\') ) mp_print_char(mp, '\\');
25491       mp_print_char(mp, k);
25492     }
25493     incr(i);
25494   }
25495   mp_print_char(mp, ')');
25496 }
25497
25498
25499 @d mp_is_ps_name(M,A) mp_do_is_ps_name(A)
25500
25501 @<Declare the \ps\ output procedures@>=
25502 boolean mp_do_is_ps_name (char *s) {
25503   char *i; /* current character code position */
25504   ASCII_code k; /* the character being checked */
25505   i=s;
25506   while (*i) {
25507     k=*i;
25508     if ( (k<=' ')||(k>'~') ) return false;
25509     if ( (k=='(')||(k==')')||(k=='<')||(k=='>')||
25510        (k=='{')||(k=='}')||(k=='/')||(k=='%') ) return false;
25511     incr(i);
25512   }
25513   return true;
25514 }
25515
25516 @ @<Exported...@>=
25517 void mp_ps_name_out (MP mp, char *s, boolean lit) ;
25518
25519 @ @c
25520 void mp_ps_name_out (MP mp, char *s, boolean lit) {
25521   ps_room(strlen(s)+2);
25522   mp_print_char(mp, ' ');
25523   if ( mp_is_ps_name(mp, s) ) {
25524     if ( lit ) mp_print_char(mp, '/');
25525       mp_print(mp, s);
25526   } else { 
25527     mp_ps_string_out(mp, s);
25528     if ( ! lit ) mp_ps_print(mp, "cvx ");
25529       mp_ps_print(mp, "cvn");
25530   }
25531 }
25532
25533 @ @<Declare the \ps\ output procedures@>= 
25534 void mp_mark_string_chars (MP mp,font_number f, str_number s) ;
25535
25536 @ @c
25537 void mp_mark_string_chars (MP mp,font_number f, str_number s) {
25538   integer b; /* |char_base[f]| */
25539   ASCII_code bc,ec; /* only characters between these bounds are marked */
25540   pool_pointer k; /* an index into string |s| */
25541   b=mp->char_base[f];
25542   bc=mp->font_bc[f];
25543   ec=mp->font_ec[f];
25544   k=str_stop(s);
25545   while ( k>mp->str_start[s] ){ 
25546     decr(k);
25547     if ( (mp->str_pool[k]>=bc)&&(mp->str_pool[k]<=ec) )
25548       mp->font_info[b+mp->str_pool[k]].qqqq.b3=used;
25549   }
25550 }
25551
25552 @ There may be many sizes of one font and we need to keep track of the
25553 characters used for each size.  This is done by keeping a linked list of
25554 sizes for each font with a counter in each text node giving the appropriate
25555 position in the size list for its font.
25556
25557 @d sc_factor(A) mp->mem[(A)+1].sc /* the scale factor stored in a font size node */
25558 @d font_size_size 2 /* size of a font size node */
25559
25560 @ @<Exported...@>=
25561 boolean mp_has_font_size(MP mp, font_number f );
25562
25563 @ @c 
25564 boolean mp_has_font_size(MP mp, font_number f ) {
25565   return (mp->font_sizes[f]!=null);
25566 }
25567
25568
25569 @ The overflow here is caused by the fact the returned value
25570 has to fit in a |name_type|, which is a quarterword. 
25571
25572 @d fscale_tolerance 65 /* that's $.001\times2^{16}$ */
25573
25574 @<Declare the \ps\ output procedures@>=
25575 quarterword mp_size_index (MP mp, font_number f, scaled s) {
25576   pointer p,q; /* the previous and current font size nodes */
25577   quarterword i; /* the size index for |q| */
25578   q=mp->font_sizes[f];
25579   i=0;
25580   while ( q!=null ) {
25581     if ( abs(s-sc_factor(q))<=fscale_tolerance ) 
25582       return i;
25583     else 
25584       { p=q; q=link(q); incr(i); };
25585     if ( i==max_quarterword )
25586       mp_overflow(mp, "sizes per font",max_quarterword);
25587 @:MetaPost capacity exceeded sizes per font}{\quad sizes per font@>
25588   }
25589   q=mp_get_node(mp, font_size_size);
25590   sc_factor(q)=s;
25591   if ( i==0 ) mp->font_sizes[f]=q;  else link(p)=q;
25592   return i;
25593 }
25594
25595 @ @<Declare the \ps\ output procedures@>=
25596 scaled mp_indexed_size (MP mp,font_number f, quarterword j) {
25597   pointer p; /* a font size node */
25598   quarterword i; /* the size index for |p| */
25599   p=mp->font_sizes[f];
25600   i=0;
25601   if ( p==null ) mp_confusion(mp, "size");
25602   while ( (i!=j) ) { 
25603     incr(i); p=link(p);
25604     if ( p==null ) mp_confusion(mp, "size");
25605   }
25606   return sc_factor(p);
25607 }
25608
25609 @ @<Declare the \ps\ output procedures@>=
25610 void mp_clear_sizes (MP mp) ;
25611
25612 @ @c void mp_clear_sizes (MP mp) {
25613   font_number f;  /* the font whose size list is being cleared */
25614   pointer p;  /* current font size nodes */
25615   for (f=null_font+1;f<=mp->last_fnum;f++) {
25616     while ( mp->font_sizes[f]!=null ) {
25617       p=mp->font_sizes[f];
25618       mp->font_sizes[f]=link(p);
25619       mp_free_node(mp, p,font_size_size);
25620     }
25621   }
25622 }
25623
25624 @ The \&{special} command saves up lines of text to be printed during the next
25625 |ship_out| operation.  The saved items are stored as a list of capsule tokens.
25626
25627 @<Glob...@>=
25628 pointer last_pending; /* the last token in a list of pending specials */
25629
25630 @ @<Set init...@>=
25631 mp->last_pending=spec_head;
25632
25633 @ @<Cases of |do_statement|...@>=
25634 case special_command: 
25635   if ( mp->cur_mod==0 ) mp_do_special(mp); else 
25636   if ( mp->cur_mod==1 ) mp_do_mapfile(mp); else 
25637   mp_do_mapline(mp);
25638   break;
25639
25640 @ @<Declare action procedures for use by |do_statement|@>=
25641 void mp_do_special (MP mp) ;
25642
25643 @ @c void mp_do_special (MP mp) { 
25644   mp_get_x_next(mp); mp_scan_expression(mp);
25645   if ( mp->cur_type!=mp_string_type ) {
25646     @<Complain about improper special operation@>;
25647   } else { 
25648     link(mp->last_pending)=mp_stash_cur_exp(mp);
25649     mp->last_pending=link(mp->last_pending);
25650     link(mp->last_pending)=null;
25651   }
25652 }
25653
25654 @ @<Complain about improper special operation@>=
25655
25656   exp_err("Unsuitable expression");
25657   help1("Only known strings are allowed for output as specials.");
25658   mp_put_get_error(mp);
25659 }
25660
25661 @ @<Print any pending specials@>=
25662 t=link(spec_head);
25663 while ( t!=null ) {
25664   mp_print_str(mp, value(t));
25665   mp_print_ln(mp);
25666   t=link(t);
25667 }
25668 mp_flush_token_list(mp, link(spec_head));
25669 link(spec_head)=null;
25670 mp->last_pending=spec_head
25671
25672 @ We are now ready for the main output procedure.  Note that the |selector|
25673 setting is saved in a global variable so that |begin_diagnostic| can access it.
25674
25675 @<Declare the \ps\ output procedures@>=
25676 void mp_ship_out (MP mp, pointer h) ;
25677
25678 @ @c
25679 void mp_ship_out (MP mp, pointer h) { /* output edge structure |h| */
25680   pointer p; /* the current graphical object */
25681   pointer q; /* something that |p| points to */
25682   integer t; /* a temporary value */
25683   font_number f; /* fonts used in a text node or as loop counters */
25684   font_number ldf;
25685   scaled ds,scf; /* design size and scale factor for a text node */
25686   boolean transformed; /* is the coordinate system being transformed? */
25687   mp_open_output_file(mp);
25688   mp->non_ps_setting=mp->selector; mp->selector=ps_file_only;
25689   if ( (mp->internal[prologues]==two)||(mp->internal[prologues]==three) ) {
25690     @<Print improved initial comment and bounding box for edge structure~|h|@>;
25691     @<Scan all the text nodes and mark the used characters@>;
25692     mp_load_encodings(mp,mp->last_fnum);
25693     @<Update encoding names@>;
25694     @<Print the improved prologue and setup@>;
25695     @<Print any pending specials@>;
25696     mp_unknown_graphics_state(mp, 0);
25697     mp->need_newpath=true;
25698     p=link(dummy_loc(h));
25699     while ( p!=null ) { 
25700       if ( has_color(p) ) {
25701         if ( (pre_script(p))!=null ) {
25702           mp_print_nl (mp, str(pre_script(p))); mp_print_ln(mp);
25703         }
25704       }
25705       mp_fix_graphics_state(mp, p);
25706       switch (type(p)) {
25707       @<Cases for translating graphical object~|p| into \ps@>;
25708       case mp_start_bounds_code:
25709       case mp_stop_bounds_code:
25710             break;
25711       } /* all cases are enumerated */
25712       p=link(p);
25713     }
25714     mp_print_cmd(mp, "showpage","P"); mp_print_ln(mp);
25715     mp_print(mp, "%%EOF"); mp_print_ln(mp);
25716     fclose(mp->ps_file);
25717     mp->selector=mp->non_ps_setting;
25718     if ( mp->internal[prologues]<=0 ) mp_clear_sizes(mp);
25719     @<End progress report@>;
25720   } else {
25721     @<Print the initial comment and give the bounding box for edge structure~|h|@>;
25722     if ( (mp->internal[prologues]>0) && (mp->last_ps_fnum<mp->last_fnum) )
25723       mp_read_psname_table(mp);
25724     mp_print_prologue(mp, (mp->internal[prologues]>>16), (mp->internal[mpprocset]>>16), ldf);
25725     mp_print_nl(mp, "%%Page: 1 1"); mp_print_ln(mp);
25726     @<Print any pending specials@>;
25727     mp_unknown_graphics_state(mp, 0);
25728     mp->need_newpath=true;
25729     p=link(dummy_loc(h));
25730     while ( p!=null ) { 
25731       if ( has_color(p) ) {
25732         if ( (pre_script(p))!=null ) {
25733           mp_print_nl (mp, str(pre_script(p))); mp_print_ln(mp);
25734         }
25735       }
25736       mp_fix_graphics_state(mp, p);
25737       switch (type(p)) {
25738       @<Cases for translating graphical object~|p| into \ps@>;
25739       case mp_start_bounds_code:
25740       case mp_stop_bounds_code: 
25741         break;
25742       } /* all cases are enumerated */
25743       p=link(p);
25744     }
25745     mp_print_cmd(mp, "showpage","P"); mp_print_ln(mp);
25746     mp_print(mp, "%%EOF"); mp_print_ln(mp);
25747     fclose(mp->ps_file);
25748     mp->selector=mp->non_ps_setting;
25749     if ( mp->internal[prologues]<=0 ) mp_clear_sizes(mp);
25750     @<End progress report@>;
25751   }
25752   if ( mp->internal[tracing_output]>0 ) 
25753    mp_print_edges(mp, h," (just shipped out)",true);
25754 }
25755
25756 @ @<Exported...@>=
25757 void mp_apply_mark_string_chars(MP mp, pointer h, int next_size);
25758
25759 @ @c
25760 void mp_apply_mark_string_chars(MP mp, pointer h, int next_size) {
25761   pointer p;
25762   p=link(dummy_loc(h));
25763   while ( p!=null ) {
25764     if ( type(p)==text_code )
25765       if ( font_n(p)!=null_font )
25766         if ( name_type(p)==next_size )
25767           mp_mark_string_chars(mp, font_n(p),text_p(p));
25768     p=link(p);
25769   }
25770 }
25771
25772 @
25773 @<Print the improved prologue and setup@>=
25774 {
25775   mp_print_improved_prologue(mp, (mp->internal[prologues]>>16),(mp->internal[mpprocset]>>16),
25776                             (mp->internal[gtroffmode]>>16), null, h);
25777 }
25778
25779 @
25780 @<Print improved initial comment and bounding box for edge...@>=
25781 mp_print(mp, "%!PS-Adobe-3.0 EPSF-3.0");
25782 mp_print_nl(mp, "%%BoundingBox: ");
25783 mp_set_bbox(mp, h,true);
25784 if ( minx_val(h)>maxx_val(h) ) {
25785   mp_print(mp, "0 0 0 0");
25786 } else { 
25787   mp_ps_pair_out(mp, mp_floor_scaled(mp, minx_val(h)),mp_floor_scaled(mp, miny_val(h)));
25788   mp_ps_pair_out(mp, -mp_floor_scaled(mp, -maxx_val(h)),-mp_floor_scaled(mp, -maxy_val(h)));
25789 };
25790 mp_print_nl(mp, "%%HiResBoundingBox: ");
25791 if ( minx_val(h)>maxx_val(h) ) {
25792   mp_print(mp, "0 0 0 0");
25793 } else {
25794   mp_ps_pair_out(mp, minx_val(h),miny_val(h));
25795   mp_ps_pair_out(mp, maxx_val(h),maxy_val(h));
25796 }
25797 mp_print_nl(mp, "%%Creator: MetaPost ");
25798 mp_print(mp, metapost_version);
25799 mp_print_nl(mp, "%%CreationDate: ");
25800 mp_print_int(mp, mp_round_unscaled(mp, mp->internal[year])); mp_print_char(mp, '.');
25801 mp_print_dd(mp, mp_round_unscaled(mp, mp->internal[month])); mp_print_char(mp, '.');
25802 mp_print_dd(mp, mp_round_unscaled(mp, mp->internal[day])); mp_print_char(mp, ':');
25803 t=mp_round_unscaled(mp, mp->internal[mp_time]);
25804 mp_print_dd(mp, t / 60); mp_print_dd(mp, t % 60);
25805 mp_print_nl(mp, "%%Pages: 1");
25806
25807 @
25808
25809 @ @<Scan all the text nodes and mark the used ...@>=
25810 for (f=null_font+1;f<=mp->last_fnum;f++) {
25811   if ( mp->font_sizes[f]!=null ) {
25812     mp_unmark_font(mp, f);
25813     mp->font_sizes[f]=null;
25814   }
25815   if ( mp->font_enc_name[f]!=NULL )
25816      xfree(mp->font_enc_name[f]);
25817   mp->font_enc_name[f] = NULL;
25818 }
25819 for (f=null_font+1;f<=mp->last_fnum;f++) {
25820   p=link(dummy_loc(h));
25821   while ( p!=null ) {
25822     if ( type(p)==text_code ) {
25823       if ( font_n(p)!=null_font ) {
25824         mp->font_sizes[font_n(p)] = diov;
25825         mp_mark_string_chars(mp, font_n(p),text_p(p));
25826             if ( mp_has_fm_entry(mp,font_n(p),NULL) )
25827           mp->font_ps_name[font_n(p)] = mp_fm_font_name(mp,font_n(p));
25828       }
25829     }
25830     p=link(p);
25831   }
25832 }
25833
25834 @ @<Update encoding names@>=
25835 for (f=null_font+1;f<=mp->last_fnum;f++) {
25836   p=link(dummy_loc(h));
25837   while ( p!=null ) {
25838     if ( type(p)==text_code )
25839       if ( font_n(p)!=null_font )
25840             if ( mp_has_fm_entry(mp,font_n(p),NULL) )
25841           if ( mp->font_enc_name[font_n(p)]==NULL )
25842             mp->font_enc_name[font_n(p)] = mp_fm_encoding_name(mp,font_n(p));
25843     p=link(p);
25844   }
25845 }
25846
25847 @ These special comments described in the {\sl PostScript Language Reference
25848 Manual}, 2nd.~edition are understood by some \ps-reading programs.
25849 We can't normally output ``conforming'' \ps\ because
25850 the structuring conventions don't allow us to say ``Please make sure the
25851 following characters are downloaded and define the \.{fshow} macro to access
25852 them.''
25853
25854 The exact bounding box is written out if |prologues<0|, although this
25855 is not standard \ps, since it allows \TeX\ to calculate the box dimensions
25856 accurately. (Overfull boxes are avoided if an illustration is made to
25857 match a given \.{\char`\\hsize}.)
25858
25859 @<Print the initial comment and give the bounding box for edge...@>=
25860 mp_print(mp, "%!PS");
25861 if ( mp->internal[prologues]>0 ) mp_print(mp, "-Adobe-3.0 EPSF-3.0");
25862 mp_print_nl(mp, "%%BoundingBox: ");
25863 mp_set_bbox(mp, h,true);
25864 if ( minx_val(h)>maxx_val(h) ) mp_print(mp, "0 0 0 0");
25865 else if ( mp->internal[prologues]<0 ) {
25866   mp_ps_pair_out(mp, minx_val(h),miny_val(h));
25867   mp_ps_pair_out(mp, maxx_val(h),maxy_val(h));
25868 } else { 
25869   mp_ps_pair_out(mp, mp_floor_scaled(mp, minx_val(h)),mp_floor_scaled(mp, miny_val(h)));
25870   mp_ps_pair_out(mp, -mp_floor_scaled(mp, -maxx_val(h)),-mp_floor_scaled(mp, -maxy_val(h)));
25871 }
25872 mp_print_nl(mp, "%%HiResBoundingBox: ");
25873 if ( minx_val(h)>maxx_val(h) ) mp_print(mp, "0 0 0 0");
25874 else {
25875   mp_ps_pair_out(mp, minx_val(h),miny_val(h));
25876   mp_ps_pair_out(mp, maxx_val(h),maxy_val(h));
25877 }
25878 mp_print_nl(mp, "%%Creator: MetaPost ");
25879 mp_print(mp, metapost_version);
25880 mp_print_nl(mp, "%%CreationDate: ");
25881 mp_print_int(mp, mp_round_unscaled(mp, mp->internal[year])); mp_print_char(mp, '.');
25882 mp_print_dd(mp, mp_round_unscaled(mp, mp->internal[month])); mp_print_char(mp, '.');
25883 mp_print_dd(mp, mp_round_unscaled(mp, mp->internal[day])); mp_print_char(mp, ':');
25884 t=mp_round_unscaled(mp, mp->internal[mp_time]);
25885 mp_print_dd(mp, t / 60); mp_print_dd(mp, t % 60);
25886 mp_print_nl(mp, "%%Pages: 1");
25887 @<List all the fonts and magnifications for edge structure~|h|@>;
25888 mp_print_ln(mp)
25889
25890 @ @<List all the fonts and magnifications for edge structure~|h|@>=
25891 @<Scan all the text nodes and set the |font_sizes| lists;
25892   if |internal[prologues]<=0| list the sizes selected by |choose_scale|,
25893   apply |unmark_font| to each font encountered, and call |mark_string|
25894   whenever the size index is zero@>;
25895 ldf = mp_print_font_comments (mp, (mp->internal[prologues]>>16), null, h)
25896
25897 @ @<Scan all the text nodes and set the |font_sizes| lists;...@>=
25898 for (f=null_font+1;f<=mp->last_fnum;f++) 
25899   mp->font_sizes[f]=null;
25900 p=link(dummy_loc(h));
25901 while ( p!=null ) {
25902   if ( type(p)==text_code ) {
25903     if ( font_n(p)!=null_font ) {
25904       f=font_n(p);
25905       if ( mp->internal[prologues]>0 ) {
25906         mp->font_sizes[f]=diov;
25907       } else { 
25908         if ( mp->font_sizes[f]==null ) mp_unmark_font(mp, f);
25909         name_type(p)=mp_size_index(mp, f,mp_choose_scale(mp, p));
25910         if ( name_type(p)==0 )
25911           mp_mark_string_chars(mp, f,text_p(p));
25912       }
25913     }
25914   }
25915   p=link(p);
25916 }
25917
25918 @ @<Cases for translating graphical object~|p| into \ps@>=
25919 case mp_start_clip_code: 
25920   mp_print_nl(mp, ""); mp_print_cmd(mp, "gsave ","q ");
25921   mp_ps_path_out(mp, path_p(p));
25922   mp_ps_print_cmd(mp, " clip"," W");
25923   mp_print_ln(mp);
25924   if ( mp->internal[restore_clip_color]>0 )
25925     mp_unknown_graphics_state(mp, 1);
25926   break;
25927 case mp_stop_clip_code: 
25928   mp_print_nl(mp, ""); mp_print_cmd(mp, "grestore","Q");
25929   mp_print_ln(mp);
25930   if ( mp->internal[restore_clip_color]>0 )
25931     mp_unknown_graphics_state(mp, 2);
25932   else
25933     mp_unknown_graphics_state(mp, -1);
25934   break;
25935
25936 @ @<Cases for translating graphical object~|p| into \ps@>=
25937 case fill_code: 
25938   if ( pen_p(p)==null ) mp_ps_fill_out(mp, path_p(p));
25939   else if ( pen_is_elliptical(pen_p(p)) ) mp_stroke_ellipse(mp, p,true);
25940   else { 
25941     mp_do_outer_envelope(mp, mp_copy_path(mp, path_p(p)), p);
25942     mp_do_outer_envelope(mp, mp_htap_ypoc(mp, path_p(p)), p);
25943   }
25944   if ( (post_script(p))!=null ) {
25945     mp_print_nl (mp, str(post_script(p))); mp_print_ln(mp);
25946   };
25947   break;
25948 case stroked_code:
25949   if ( pen_is_elliptical(pen_p(p)) ) mp_stroke_ellipse(mp, p,false);
25950   else { 
25951     q=mp_copy_path(mp, path_p(p));
25952     t=lcap_val(p);
25953     @<Break the cycle and set |t:=1| if path |q| is cyclic@>;
25954     q=mp_make_envelope(mp, q,pen_p(p),ljoin_val(p),t,miterlim_val(p));
25955     mp_ps_fill_out(mp, q);
25956     mp_toss_knot_list(mp, q);
25957   };
25958   if ( (post_script(p))!=null ) {
25959     mp_print_nl (mp, str(post_script(p))); mp_print_ln(mp);
25960   };
25961   break;
25962
25963 @ The envelope of a cyclic path~|q| could be computed by calling
25964 |make_envelope| once for |q| and once for its reversal.  We don't do this
25965 because it would fail color regions that are covered by the pen regardless
25966 of where it is placed on~|q|.
25967
25968 @<Break the cycle and set |t:=1| if path |q| is cyclic@>=
25969 if ( left_type(q)!=endpoint ) { 
25970   left_type(mp_insert_knot(mp, q,x_coord(q),y_coord(q)))=endpoint;
25971   right_type(q)=endpoint;
25972   q=link(q);
25973   t=1;
25974 }
25975
25976 @ @<Cases for translating graphical object~|p| into \ps@>=
25977 case text_code: 
25978   if ( (font_n(p)!=null_font) && (length(text_p(p))>0) ) {
25979     if ( mp->internal[prologues]>0 )
25980       scf=mp_choose_scale(mp, p);
25981     else 
25982       scf=mp_indexed_size(mp, font_n(p), name_type(p));
25983     @<Shift or transform as necessary before outputting text node~|p| at scale
25984       factor~|scf|; set |transformed:=true| if the original transformation must
25985       be restored@>;
25986     mp_ps_string_out(mp, str(text_p(p)));
25987     mp_ps_name_out(mp, mp->font_name[font_n(p)],false);
25988     @<Print the size information and \ps\ commands for text node~|p|@>;
25989     mp_print_ln(mp);
25990   }
25991   if ( (post_script(p))!=null ) {
25992     mp_print_nl (mp, str(post_script(p))); mp_print_ln(mp);
25993   }
25994   break;
25995
25996 @ @<Print the size information and \ps\ commands for text node~|p|@>=
25997 ps_room(18);
25998 mp_print_char(mp, ' ');
25999 ds=(mp->font_dsize[font_n(p)]+8) / 16;
26000 mp_print_scaled(mp, mp_take_scaled(mp, ds,scf));
26001 mp_print(mp, " fshow");
26002 if ( transformed ) 
26003   mp_ps_print_cmd(mp, " grestore"," Q")
26004
26005 @ @<Shift or transform as necessary before outputting text node~|p| at...@>=
26006 transformed=(txx_val(p)!=scf)||(tyy_val(p)!=scf)||
26007             (txy_val(p)!=0)||(tyx_val(p)!=0);
26008 if ( transformed ) {
26009   mp_print_cmd(mp, "gsave [", "q [");
26010   mp_ps_pair_out(mp, mp_make_scaled(mp, txx_val(p),scf),
26011                      mp_make_scaled(mp, tyx_val(p),scf));
26012   mp_ps_pair_out(mp, mp_make_scaled(mp, txy_val(p),scf),
26013                      mp_make_scaled(mp, tyy_val(p),scf));
26014   mp_ps_pair_out(mp, tx_val(p),ty_val(p));
26015   mp_ps_print_cmd(mp, "] concat 0 0 moveto","] t 0 0 m");
26016 } else { 
26017   mp_ps_pair_out(mp, tx_val(p),ty_val(p));
26018   mp_ps_print_cmd(mp, "moveto","m");
26019 }
26020 mp_print_ln(mp)
26021
26022 @ Now that we've finished |ship_out|, let's look at the other commands
26023 by which a user can send things to the \.{GF} file.
26024
26025 @ @<Determine if a character has been shipped out@>=
26026
26027   mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256;
26028   if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
26029   boolean_reset(mp->char_exists[mp->cur_exp]);
26030   mp->cur_type=mp_boolean_type;
26031 }
26032
26033 @ @<Glob...@>=
26034 psout_data ps;
26035
26036 @ @<Allocate or initialize ...@>=
26037 mp_backend_initialize(mp);
26038
26039 @ @<Dealloc...@>=
26040 mp_backend_free(mp);
26041
26042
26043 @* \[45] Dumping and undumping the tables.
26044 After \.{INIMP} has seen a collection of macros, it
26045 can write all the necessary information on an auxiliary file so
26046 that production versions of \MP\ are able to initialize their
26047 memory at high speed. The present section of the program takes
26048 care of such output and input. We shall consider simultaneously
26049 the processes of storing and restoring,
26050 so that the inverse relation between them is clear.
26051 @.INIMP@>
26052
26053 The global variable |mem_ident| is a string that is printed right
26054 after the |banner| line when \MP\ is ready to start. For \.{INIMP} this
26055 string says simply `\.{(INIMP)}'; for other versions of \MP\ it says,
26056 for example, `\.{(mem=plain 90.4.14)}', showing the year,
26057 month, and day that the mem file was created. We have |mem_ident=0|
26058 before \MP's tables are loaded.
26059
26060 @<Glob...@>=
26061 char * mem_ident;
26062
26063 @ @<Set init...@>=
26064 mp->mem_ident=NULL;
26065
26066 @ @<Initialize table entries...@>=
26067 if (mp->ini_version) 
26068   mp->mem_ident=xstrdup(" (INIMP)");
26069
26070 @ @<Declare act...@>=
26071 void mp_store_mem_file (MP mp) ;
26072
26073 @ @c void mp_store_mem_file (MP mp) {
26074   integer k;  /* all-purpose index */
26075   pointer p,q; /* all-purpose pointers */
26076   integer x; /* something to dump */
26077   four_quarters w; /* four ASCII codes */
26078   memory_word WW;
26079   @<Create the |mem_ident|, open the mem file,
26080     and inform the user that dumping has begun@>;
26081   @<Dump constants for consistency check@>;
26082   @<Dump the string pool@>;
26083   @<Dump the dynamic memory@>;
26084   @<Dump the table of equivalents and the hash table@>;
26085   @<Dump a few more things and the closing check word@>;
26086   @<Close the mem file@>;
26087 }
26088
26089 @ Corresponding to the procedure that dumps a mem file, we also have a function
26090 that reads~one~in. The function returns |false| if the dumped mem is
26091 incompatible with the present \MP\ table sizes, etc.
26092
26093 @d off_base 6666 /* go here if the mem file is unacceptable */
26094 @d too_small(A) { wake_up_terminal;
26095   wterm_ln("---! Must increase the "); wterm((A));
26096 @.Must increase the x@>
26097   goto OFF_BASE;
26098   }
26099
26100 @c 
26101 boolean mp_load_mem_file (MP mp) {
26102   integer k; /* all-purpose index */
26103   pointer p,q; /* all-purpose pointers */
26104   integer x; /* something undumped */
26105   str_number s; /* some temporary string */
26106   four_quarters w; /* four ASCII codes */
26107   memory_word WW;
26108   @<Undump constants for consistency check@>;
26109   @<Undump the string pool@>;
26110   @<Undump the dynamic memory@>;
26111   @<Undump the table of equivalents and the hash table@>;
26112   @<Undump a few more things and the closing check word@>;
26113   return true; /* it worked! */
26114 OFF_BASE: 
26115   wake_up_terminal;
26116   wterm_ln("(Fatal mem file error; I'm stymied)\n");
26117 @.Fatal mem file error@>
26118    return false;
26119 }
26120
26121 @ @<Declarations@>=
26122 boolean mp_load_mem_file (MP mp) ;
26123
26124 @ Mem files consist of |memory_word| items, and we use the following
26125 macros to dump words of different types:
26126
26127 @d dump_wd(A)   { WW=(A);      fwrite(&WW,sizeof(WW),1,mp->mem_file); }
26128 @d dump_int(A)  { WW.cint=(A); fwrite(&WW,sizeof(WW),1,mp->mem_file); }
26129 @d dump_hh(A)   { WW.hh=(A);   fwrite(&WW,sizeof(WW),1,mp->mem_file); }
26130 @d dump_qqqq(A) { WW.qqqq=(A); fwrite(&WW,sizeof(WW),1,mp->mem_file); }
26131 @d dump_string(A) { dump_int(strlen(A)+1);
26132                     fwrite(A,strlen(A)+1,1,mp->mem_file); }
26133
26134 @<Glob...@>=
26135 FILE * mem_file; /* for input or output of mem information */
26136
26137 @ The inverse macros are slightly more complicated, since we need to check
26138 the range of the values we are reading in. We say `|undump(a)(b)(x)|' to
26139 read an integer value |x| that is supposed to be in the range |a<=x<=b|.
26140
26141 @d undump_wd(A)   { fread(&WW,sizeof(WW),1,mp->mem_file); (A)=WW; }
26142 @d undump_int(A)  { fread(&WW,sizeof(WW),1,mp->mem_file); (A)=WW.cint; }
26143 @d undump_hh(A)   { fread(&WW,sizeof(WW),1,mp->mem_file); (A)=WW.hh; }
26144 @d undump_qqqq(A) { fread(&WW,sizeof(WW),1,mp->mem_file); (A)=WW.qqqq; }
26145 @d undump_strings(A,B,C) { 
26146    undump_int(x); if ( (x<(A)) || (x>(B)) ) goto OFF_BASE; else (C)=str(x); }
26147 @d undump(A,B,C) { undump_int(x); if ( (x<(A)) || (x>(int)(B)) ) goto OFF_BASE; else (C)=x; }
26148 @d undump_size(A,B,C,D) { undump_int(x);
26149                if (x<(A)) goto OFF_BASE; 
26150                if (x>(B)) { too_small((C)); } else {(D)=x;} }
26151 @d undump_string(A) { integer XX=0; undump_int(XX);
26152                       A = xmalloc(XX,sizeof(char));
26153                       fread(A,XX,1,mp->mem_file); }
26154
26155 @ The next few sections of the program should make it clear how we use the
26156 dump/undump macros.
26157
26158 @<Dump constants for consistency check@>=
26159 dump_int(mp->mem_top);
26160 dump_int(mp->hash_size);
26161 dump_int(mp->hash_prime)
26162 dump_int(mp->param_size);
26163 dump_int(mp->max_in_open);
26164
26165 @ Sections of a \.{WEB} program that are ``commented out'' still contribute
26166 strings to the string pool; therefore \.{INIMP} and \MP\ will have
26167 the same strings. (And it is, of course, a good thing that they do.)
26168 @.WEB@>
26169 @^string pool@>
26170
26171 @<Undump constants for consistency check@>=
26172 undump_int(x); mp->mem_top = x;
26173 undump_int(x); if (mp->hash_size != x) goto OFF_BASE;
26174 undump_int(x); if (mp->hash_prime != x) goto OFF_BASE;
26175 undump_int(x); if (mp->param_size != x) goto OFF_BASE;
26176 undump_int(x); if (mp->max_in_open != x) goto OFF_BASE
26177
26178 @ We do string pool compaction to avoid dumping unused strings.
26179
26180 @d dump_four_ASCII 
26181   w.b0=qi(mp->str_pool[k]); w.b1=qi(mp->str_pool[k+1]);
26182   w.b2=qi(mp->str_pool[k+2]); w.b3=qi(mp->str_pool[k+3]);
26183   dump_qqqq(w)
26184
26185 @<Dump the string pool@>=
26186 mp_do_compaction(mp, mp->pool_size);
26187 dump_int(mp->pool_ptr);
26188 dump_int(mp->max_str_ptr);
26189 dump_int(mp->str_ptr);
26190 k=0;
26191 while ( (mp->next_str[k]==k+1) && (k<=mp->max_str_ptr) ) 
26192   incr(k);
26193 dump_int(k);
26194 while ( k<=mp->max_str_ptr ) { 
26195   dump_int(mp->next_str[k]); incr(k);
26196 }
26197 k=0;
26198 while (1)  { 
26199   dump_int((mp->str_start[k])); 
26200   if ( k==mp->str_ptr ) {
26201     break;
26202   } else { 
26203     k=mp->next_str[k]; 
26204   }
26205 };
26206 k=0;
26207 while (k+4<mp->pool_ptr ) { 
26208   dump_four_ASCII; k=k+4; 
26209 }
26210 k=mp->pool_ptr-4; dump_four_ASCII;
26211 mp_print_ln(mp); mp_print(mp, "at most "); mp_print_int(mp, mp->max_str_ptr);
26212 mp_print(mp, " strings of total length ");
26213 mp_print_int(mp, mp->pool_ptr)
26214
26215 @ @d undump_four_ASCII 
26216   undump_qqqq(w);
26217   mp->str_pool[k]=qo(w.b0); mp->str_pool[k+1]=qo(w.b1);
26218   mp->str_pool[k+2]=qo(w.b2); mp->str_pool[k+3]=qo(w.b3)
26219
26220 @<Undump the string pool@>=
26221 undump_int(mp->pool_ptr);
26222 mp_reallocate_pool(mp, mp->pool_ptr) ;
26223 undump_int(mp->max_str_ptr);
26224 mp_reallocate_strings (mp,mp->max_str_ptr) ;
26225 undump(0,mp->max_str_ptr,mp->str_ptr);
26226 undump(0,mp->max_str_ptr+1,s);
26227 for (k=0;k<=s-1;k++) 
26228   mp->next_str[k]=k+1;
26229 for (k=s;k<=mp->max_str_ptr;k++) 
26230   undump(s+1,mp->max_str_ptr+1,mp->next_str[k]);
26231 mp->fixed_str_use=0;
26232 k=0;
26233 while (1) { 
26234   undump(0,mp->pool_ptr,mp->str_start[k]);
26235   if ( k==mp->str_ptr ) break;
26236   mp->str_ref[k]=max_str_ref;
26237   incr(mp->fixed_str_use);
26238   mp->last_fixed_str=k; k=mp->next_str[k];
26239 }
26240 k=0;
26241 while ( k+4<mp->pool_ptr ) { 
26242   undump_four_ASCII; k=k+4;
26243 }
26244 k=mp->pool_ptr-4; undump_four_ASCII;
26245 mp->init_str_use=mp->fixed_str_use; mp->init_pool_ptr=mp->pool_ptr;
26246 mp->max_pool_ptr=mp->pool_ptr;
26247 mp->strs_used_up=mp->fixed_str_use;
26248 mp->pool_in_use=mp->str_start[mp->str_ptr]; mp->strs_in_use=mp->fixed_str_use;
26249 mp->max_pl_used=mp->pool_in_use; mp->max_strs_used=mp->strs_in_use;
26250 mp->pact_count=0; mp->pact_chars=0; mp->pact_strs=0;
26251
26252 @ By sorting the list of available spaces in the variable-size portion of
26253 |mem|, we are usually able to get by without having to dump very much
26254 of the dynamic memory.
26255
26256 We recompute |var_used| and |dyn_used|, so that \.{INIMP} dumps valid
26257 information even when it has not been gathering statistics.
26258
26259 @<Dump the dynamic memory@>=
26260 mp_sort_avail(mp); mp->var_used=0;
26261 dump_int(mp->lo_mem_max); dump_int(mp->rover);
26262 p=0; q=mp->rover; x=0;
26263 do {  
26264   for (k=p;k<= q+1;k++) 
26265     dump_wd(mp->mem[k]);
26266   x=x+q+2-p; mp->var_used=mp->var_used+q-p;
26267   p=q+node_size(q); q=rlink(q);
26268 } while (q!=mp->rover);
26269 mp->var_used=mp->var_used+mp->lo_mem_max-p; 
26270 mp->dyn_used=mp->mem_end+1-mp->hi_mem_min;
26271 for (k=p;k<= mp->lo_mem_max;k++ ) 
26272   dump_wd(mp->mem[k]);
26273 x=x+mp->lo_mem_max+1-p;
26274 dump_int(mp->hi_mem_min); dump_int(mp->avail);
26275 for (k=mp->hi_mem_min;k<=mp->mem_end;k++ ) 
26276   dump_wd(mp->mem[k]);
26277 x=x+mp->mem_end+1-mp->hi_mem_min;
26278 p=mp->avail;
26279 while ( p!=null ) { 
26280   decr(mp->dyn_used); p=link(p);
26281 }
26282 dump_int(mp->var_used); dump_int(mp->dyn_used);
26283 mp_print_ln(mp); mp_print_int(mp, x);
26284 mp_print(mp, " memory locations dumped; current usage is ");
26285 mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used)
26286
26287 @ @<Undump the dynamic memory@>=
26288 undump(lo_mem_stat_max+1000,hi_mem_stat_min-1,mp->lo_mem_max);
26289 undump(lo_mem_stat_max+1,mp->lo_mem_max,mp->rover);
26290 p=0; q=mp->rover;
26291 do {  
26292   for (k=p;k<= q+1; k++) 
26293     undump_wd(mp->mem[k]);
26294   p=q+node_size(q);
26295   if ( (p>mp->lo_mem_max)||((q>=rlink(q))&&(rlink(q)!=mp->rover)) ) 
26296     goto OFF_BASE;
26297   q=rlink(q);
26298 } while (q!=mp->rover);
26299 for (k=p;k<=mp->lo_mem_max;k++ ) 
26300   undump_wd(mp->mem[k]);
26301 undump(mp->lo_mem_max+1,hi_mem_stat_min,mp->hi_mem_min);
26302 undump(null,mp->mem_top,mp->avail); mp->mem_end=mp->mem_top;
26303 for (k=mp->hi_mem_min;k<= mp->mem_end;k++) 
26304   undump_wd(mp->mem[k]);
26305 undump_int(mp->var_used); undump_int(mp->dyn_used)
26306
26307 @ A different scheme is used to compress the hash table, since its lower region
26308 is usually sparse. When |text(p)<>0| for |p<=hash_used|, we output three
26309 words: |p|, |hash[p]|, and |eqtb[p]|. The hash table is, of course, densely
26310 packed for |p>=hash_used|, so the remaining entries are output in~a~block.
26311
26312 @<Dump the table of equivalents and the hash table@>=
26313 dump_int(mp->hash_used); 
26314 mp->st_count=frozen_inaccessible-1-mp->hash_used;
26315 for (p=1;p<=mp->hash_used;p++) {
26316   if ( text(p)!=0 ) {
26317      dump_int(p); dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]); incr(mp->st_count);
26318   }
26319 }
26320 for (p=mp->hash_used+1;p<=(int)hash_end;p++) {
26321   dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]);
26322 }
26323 dump_int(mp->st_count);
26324 mp_print_ln(mp); mp_print_int(mp, mp->st_count); mp_print(mp, " symbolic tokens")
26325
26326 @ @<Undump the table of equivalents and the hash table@>=
26327 undump(1,frozen_inaccessible,mp->hash_used); 
26328 p=0;
26329 do {  
26330   undump(p+1,mp->hash_used,p); 
26331   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
26332 } while (p!=mp->hash_used);
26333 for (p=mp->hash_used+1;p<=(int)hash_end;p++ )  { 
26334   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
26335 }
26336 undump_int(mp->st_count)
26337
26338 @ We have already printed a lot of statistics, so we set |tracing_stats:=0|
26339 to prevent them appearing again.
26340
26341 @<Dump a few more things and the closing check word@>=
26342 dump_int(mp->max_internal);
26343 dump_int(mp->int_ptr);
26344 for (k=1;k<= mp->int_ptr;k++ ) { 
26345   dump_int(mp->internal[k]); 
26346   dump_string(mp->int_name[k]);
26347 }
26348 dump_int(mp->start_sym); 
26349 dump_int(mp->interaction); 
26350 dump_string(mp->mem_ident);
26351 dump_int(mp->bg_loc); dump_int(mp->eg_loc); dump_int(mp->serial_no); dump_int(69073);
26352 mp->internal[tracing_stats]=0
26353
26354 @ @<Undump a few more things and the closing check word@>=
26355 undump_int(x);
26356 if (x>mp->max_internal) mp_grow_internals(mp,x);
26357 undump_int(mp->int_ptr);
26358 for (k=1;k<= mp->int_ptr;k++) { 
26359   undump_int(mp->internal[k]);
26360   undump_string(mp->int_name[k]);
26361 }
26362 undump(0,frozen_inaccessible,mp->start_sym);
26363 if (mp->interaction==mp_unspecified_mode) {
26364   undump(mp_unspecified_mode,mp_error_stop_mode,mp->interaction);
26365 } else {
26366   undump(mp_unspecified_mode,mp_error_stop_mode,x);
26367 }
26368 undump_string(mp->mem_ident);
26369 undump(1,hash_end,mp->bg_loc);
26370 undump(1,hash_end,mp->eg_loc);
26371 undump_int(mp->serial_no);
26372 undump_int(x); 
26373 if ( (x!=69073)|| feof(mp->mem_file) ) goto OFF_BASE
26374
26375 @ @<Create the |mem_ident|...@>=
26376
26377   xfree(mp->mem_ident);
26378   mp->mem_ident = xmalloc(256,1);
26379   snprintf(mp->mem_ident,256," (mem=%s %i.%i.%i)", 
26380            mp->job_name,
26381            (int)(mp_round_unscaled(mp, mp->internal[year]) % 100),
26382            (int)mp_round_unscaled(mp, mp->internal[month]),
26383            (int)mp_round_unscaled(mp, mp->internal[day]));
26384   mp_pack_job_name(mp, mem_extension);
26385   while (! mp_w_open_out(mp, &mp->mem_file) )
26386     mp_prompt_file_name(mp, "mem file name", mem_extension);
26387   mp_print_nl(mp, "Beginning to dump on file ");
26388 @.Beginning to dump...@>
26389   mp_print(mp, mp->name_of_file); 
26390   mp_print_nl(mp, mp->mem_ident);
26391 }
26392
26393 @ @<Dealloc variables@>=
26394 xfree(mp->mem_ident);
26395
26396 @ @<Close the mem file@>=
26397 fclose(mp->mem_file)
26398
26399 @* \[46] The main program.
26400 This is it: the part of \MP\ that executes all those procedures we have
26401 written.
26402
26403 Well---almost. We haven't put the parsing subroutines into the
26404 program yet; and we'd better leave space for a few more routines that may
26405 have been forgotten.
26406
26407 @c @<Declare the basic parsing subroutines@>;
26408 @<Declare miscellaneous procedures that were declared |forward|@>;
26409 @<Last-minute procedures@>
26410
26411 @ We've noted that there are two versions of \MP. One, called \.{INIMP},
26412 @.INIMP@>
26413 has to be run first; it initializes everything from scratch, without
26414 reading a mem file, and it has the capability of dumping a mem file.
26415 The other one is called `\.{VIRMP}'; it is a ``virgin'' program that needs
26416 @.VIRMP@>
26417 to input a mem file in order to get started. \.{VIRMP} typically has
26418 a bit more memory capacity than \.{INIMP}, because it does not need the
26419 space consumed by the dumping/undumping routines and the numerous calls on
26420 |primitive|, etc.
26421
26422 The \.{VIRMP} program cannot read a mem file instantaneously, of course;
26423 the best implementations therefore allow for production versions of \MP\ that
26424 not only avoid the loading routine for \PASCAL\ object code, they also have
26425 a mem file pre-loaded. 
26426
26427 @<Glob...@>=
26428 boolean ini_version; /* are we iniMP? */
26429
26430 @ @<Option variables@>=
26431 boolean ini_version; /* are we iniMP? */
26432
26433 @ @<Set |ini_version|@>=
26434 mp->ini_version = (opt.ini_version ? true : false);
26435
26436 @ Here we do whatever is needed to complete \MP's job gracefully on the
26437 local operating system. The code here might come into play after a fatal
26438 error; it must therefore consist entirely of ``safe'' operations that
26439 cannot produce error messages. For example, it would be a mistake to call
26440 |str_room| or |make_string| at this time, because a call on |overflow|
26441 might lead to an infinite loop.
26442 @^system dependencies@>
26443
26444 This program doesn't bother to close the input files that may still be open.
26445
26446 @<Last-minute...@>=
26447 void mp_close_files_and_terminate (MP mp) {
26448   integer k; /* all-purpose index */
26449   integer LH; /* the length of the \.{TFM} header, in words */
26450   int lk_offset; /* extra words inserted at beginning of |lig_kern| array */
26451   pointer p; /* runs through a list of \.{TFM} dimensions */
26452   @<Close all open files in the |rd_file| and |wr_file| arrays@>;
26453   if ( mp->internal[tracing_stats]>0 )
26454     @<Output statistics about this job@>;
26455   wake_up_terminal; 
26456   @<Do all the finishing work on the \.{TFM} file@>;
26457   @<Explain what output files were written@>;
26458   if ( mp->log_opened ){ 
26459     wlog_cr;
26460     fclose(mp->log_file); mp->selector=mp->selector-2;
26461     if ( mp->selector==term_only ) {
26462       mp_print_nl(mp, "Transcript written on ");
26463 @.Transcript written...@>
26464       mp_print(mp, mp->log_name); mp_print_char(mp, '.');
26465     }
26466   }
26467   mp_print_ln(mp);
26468 }
26469
26470 @ @<Declarations@>=
26471 void mp_close_files_and_terminate (MP mp) ;
26472
26473 @ @<Close all open files in the |rd_file| and |wr_file| arrays@>=
26474 for (k=0;k<=(int)mp->read_files-1;k++ ) {
26475   if ( mp->rd_fname[k]!=NULL ) fclose(mp->rd_file[k]);
26476 }
26477 for (k=0;k<=(int)mp->write_files-1;k++) {
26478   if ( mp->wr_fname[k]!=NULL ) fclose(mp->wr_file[k]);
26479 }
26480
26481 @ We want to produce a \.{TFM} file if and only if |fontmaking| is positive.
26482
26483 We reclaim all of the variable-size memory at this point, so that
26484 there is no chance of another memory overflow after the memory capacity
26485 has already been exceeded.
26486
26487 @<Do all the finishing work on the \.{TFM} file@>=
26488 if ( mp->internal[fontmaking]>0 ) {
26489   @<Make the dynamic memory into one big available node@>;
26490   @<Massage the \.{TFM} widths@>;
26491   mp_fix_design_size(mp); mp_fix_check_sum(mp);
26492   @<Massage the \.{TFM} heights, depths, and italic corrections@>;
26493   mp->internal[fontmaking]=0; /* avoid loop in case of fatal error */
26494   @<Finish the \.{TFM} file@>;
26495 }
26496
26497 @ @<Make the dynamic memory into one big available node@>=
26498 mp->rover=lo_mem_stat_max+1; link(mp->rover)=empty_flag; mp->lo_mem_max=mp->hi_mem_min-1;
26499 if ( mp->lo_mem_max-mp->rover>max_halfword ) mp->lo_mem_max=max_halfword+mp->rover;
26500 node_size(mp->rover)=mp->lo_mem_max-mp->rover; 
26501 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
26502 link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null
26503
26504 @ The present section goes directly to the log file instead of using
26505 |print| commands, because there's no need for these strings to take
26506 up |str_pool| memory when a non-{\bf stat} version of \MP\ is being used.
26507
26508 @<Output statistics...@>=
26509 if ( mp->log_opened ) { 
26510   char s[128];
26511   wlog_ln(" ");
26512   wlog_ln("Here is how much of MetaPost's memory you used:");
26513 @.Here is how much...@>
26514   snprintf(s,128," %i string%s out of %i",(int)mp->max_strs_used-mp->init_str_use,
26515           (mp->max_strs_used!=mp->init_str_use+1 ? "s" : ""),
26516           (int)(mp->max_strings-1-mp->init_str_use));
26517   wlog_ln(s);
26518   snprintf(s,128," %i string characters out of %i",
26519            (int)mp->max_pl_used-mp->init_pool_ptr,
26520            (int)mp->pool_size-mp->init_pool_ptr);
26521   wlog_ln(s);
26522   snprintf(s,128," %i words of memory out of %i",
26523            (int)mp->lo_mem_max+mp->mem_end-mp->hi_mem_min+2,
26524            (int)mp->mem_end+1);
26525   wlog_ln(s);
26526   snprintf(s,128," %i symbolic tokens out of %i", (int)mp->st_count, (int)mp->hash_size);
26527   wlog_ln(s);
26528   snprintf(s,128," %ii, %in, %ip, %ib stack positions out of %ii, %in, %ip, %ib",
26529            (int)mp->max_in_stack,(int)mp->int_ptr,
26530            (int)mp->max_param_stack,(int)mp->max_buf_stack+1,
26531            (int)mp->stack_size,(int)mp->max_internal,(int)mp->param_size,(int)mp->buf_size);
26532   wlog_ln(s);
26533   snprintf(s,128," %i string compactions (moved %i characters, %i strings)",
26534           (int)mp->pact_count,(int)mp->pact_chars,(int)mp->pact_strs);
26535   wlog_ln(s);
26536 }
26537
26538 @ We get to the |final_cleanup| routine when \&{end} or \&{dump} has
26539 been scanned.
26540
26541 @<Last-minute...@>=
26542 void mp_final_cleanup (MP mp) {
26543   small_number c; /* 0 for \&{end}, 1 for \&{dump} */
26544   c=mp->cur_mod;
26545   if ( mp->job_name==NULL ) mp_open_log_file(mp);
26546   while ( mp->input_ptr>0 ) {
26547     if ( token_state ) mp_end_token_list(mp);
26548     else  mp_end_file_reading(mp);
26549   }
26550   while ( mp->loop_ptr!=null ) mp_stop_iteration(mp);
26551   while ( mp->open_parens>0 ) { 
26552     mp_print(mp, " )"); decr(mp->open_parens);
26553   };
26554   while ( mp->cond_ptr!=null ) {
26555     mp_print_nl(mp, "(end occurred when ");
26556 @.end occurred...@>
26557     mp_print_cmd_mod(mp, fi_or_else,mp->cur_if);
26558     /* `\.{if}' or `\.{elseif}' or `\.{else}' */
26559     if ( mp->if_line!=0 ) {
26560       mp_print(mp, " on line "); mp_print_int(mp, mp->if_line);
26561     }
26562     mp_print(mp, " was incomplete)");
26563     mp->if_line=if_line_field(mp->cond_ptr);
26564     mp->cur_if=name_type(mp->cond_ptr); mp->cond_ptr=link(mp->cond_ptr);
26565   }
26566   if ( mp->history!=spotless )
26567     if ( ((mp->history==warning_issued)||(mp->interaction<mp_error_stop_mode)) )
26568       if ( mp->selector==term_and_log ) {
26569     mp->selector=term_only;
26570     mp_print_nl(mp, "(see the transcript file for additional information)");
26571 @.see the transcript file...@>
26572     mp->selector=term_and_log;
26573   }
26574   if ( c==1 ) {
26575     if (mp->ini_version) {
26576       mp_store_mem_file(mp); return;
26577     }
26578     mp_print_nl(mp, "(dump is performed only by INIMP)"); return;
26579 @.dump...only by INIMP@>
26580   }
26581 }
26582
26583 @ @<Declarations@>=
26584 void mp_final_cleanup (MP mp) ;
26585 void mp_init_prim (MP mp) ;
26586 void mp_init_tab (MP mp) ;
26587
26588 @ @<Last-minute...@>=
26589 void mp_init_prim (MP mp) { /* initialize all the primitives */
26590   @<Put each...@>;
26591 }
26592 @#
26593 void mp_init_tab (MP mp) { /* initialize other tables */
26594   integer k; /* all-purpose index */
26595   @<Initialize table entries (done by \.{INIMP} only)@>;
26596 }
26597
26598
26599 @ When we begin the following code, \MP's tables may still contain garbage;
26600 the strings might not even be present. Thus we must proceed cautiously to get
26601 bootstrapped in.
26602
26603 But when we finish this part of the program, \MP\ is ready to call on the
26604 |main_control| routine to do its work.
26605
26606 @<Get the first line...@>=
26607
26608   @<Initialize the input routines@>;
26609   if ( (mp->mem_ident==NULL)||(mp->buffer[loc]=='&') ) {
26610     if ( mp->mem_ident!=NULL ) mp_initialize(mp); /* erase preloaded mem */
26611     if ( ! mp_open_mem_file(mp) ) return false;
26612     if ( ! mp_load_mem_file(mp) ) {
26613       fclose( mp->mem_file); return false;
26614     }
26615     fclose( mp->mem_file);
26616     while ( (loc<limit)&&(mp->buffer[loc]==' ') ) incr(loc);
26617   }
26618   mp->buffer[limit]='%';
26619   mp_fix_date_and_time(mp);
26620   mp->sys_random_seed = (mp->get_random_seed)(mp);
26621   mp_init_randoms(mp, mp->sys_random_seed);
26622   @<Initialize the print |selector|...@>;
26623   if ( loc<limit ) if ( mp->buffer[loc]!='\\' ) 
26624     mp_start_input(mp); /* \&{input} assumed */
26625 }
26626
26627 @ @<Run inimpost commands@>=
26628 {
26629   mp_get_strings_started(mp);
26630   mp_init_tab(mp); /* initialize the tables */
26631   mp_init_prim(mp); /* call |primitive| for each primitive */
26632   mp->init_str_use=mp->str_ptr; mp->init_pool_ptr=mp->pool_ptr;
26633   mp->max_str_ptr=mp->str_ptr; mp->max_pool_ptr=mp->pool_ptr;
26634   mp_fix_date_and_time(mp);
26635 }
26636
26637
26638 @* \[47] Debugging.
26639 Once \MP\ is working, you should be able to diagnose most errors with
26640 the \.{show} commands and other diagnostic features. But for the initial
26641 stages of debugging, and for the revelation of really deep mysteries, you
26642 can compile \MP\ with a few more aids, including the \PASCAL\ runtime
26643 checks and its debugger. An additional routine called |debug_help|
26644 will also come into play when you type `\.D' after an error message;
26645 |debug_help| also occurs just before a fatal error causes \MP\ to succumb.
26646 @^debugging@>
26647 @^system dependencies@>
26648
26649 The interface to |debug_help| is primitive, but it is good enough when used
26650 with a \PASCAL\ debugger that allows you to set breakpoints and to read
26651 variables and change their values. After getting the prompt `\.{debug \#}', you
26652 type either a negative number (this exits |debug_help|), or zero (this
26653 goes to a location where you can set a breakpoint, thereby entering into
26654 dialog with the \PASCAL\ debugger), or a positive number |m| followed by
26655 an argument |n|. The meaning of |m| and |n| will be clear from the
26656 program below. (If |m=13|, there is an additional argument, |l|.)
26657 @.debug \#@>
26658
26659 @<Last-minute...@>=
26660 void mp_debug_help (MP mp) { /* routine to display various things */
26661   integer k;
26662   int l,m,n;
26663   while (1) { 
26664     wake_up_terminal;
26665     mp_print_nl(mp, "debug # (-1 to exit):"); update_terminal;
26666 @.debug \#@>
26667     m = 0;
26668     fscanf(mp->term_in,"%i",&m);
26669     if ( m<=0 )
26670       return;
26671     n = 0 ;
26672     fscanf(mp->term_in,"%i",&n);
26673     switch (m) {
26674     @<Numbered cases for |debug_help|@>;
26675     default: mp_print(mp, "?"); break;
26676     }
26677   }
26678 }
26679
26680 @ @<Numbered cases...@>=
26681 case 1: mp_print_word(mp, mp->mem[n]); /* display |mem[n]| in all forms */
26682   break;
26683 case 2: mp_print_int(mp, info(n));
26684   break;
26685 case 3: mp_print_int(mp, link(n));
26686   break;
26687 case 4: mp_print_int(mp, eq_type(n)); mp_print_char(mp, ':'); mp_print_int(mp, equiv(n));
26688   break;
26689 case 5: mp_print_variable_name(mp, n);
26690   break;
26691 case 6: mp_print_int(mp, mp->internal[n]);
26692   break;
26693 case 7: mp_do_show_dependencies(mp);
26694   break;
26695 case 9: mp_show_token_list(mp, n,null,100000,0);
26696   break;
26697 case 10: mp_print_str(mp, n);
26698   break;
26699 case 11: mp_check_mem(mp, n>0); /* check wellformedness; print new busy locations if |n>0| */
26700   break;
26701 case 12: mp_search_mem(mp, n); /* look for pointers to |n| */
26702   break;
26703 case 13: l = 0;  fscanf(mp->term_in,"%i",&l); mp_print_cmd_mod(mp, n,l); 
26704   break;
26705 case 14: for (k=0;k<=n;k++) mp_print_str(mp, mp->buffer[k]);
26706   break;
26707 case 15: mp->panicking=! mp->panicking;
26708   break;
26709
26710
26711 @ \MP\ used to have one single routine to print to both `write' files
26712 and the PostScript output. Web2c redefines ``Character |k| cannot be
26713 printed'', and that resulted in some bugs where 8-bit characters were
26714 written to the PostScript file (reported by Wlodek Bzyl).
26715
26716 Also, Hans Hagen requested spaces to be output as "\\040" instead of
26717 a plain space, since that makes it easier to parse the result file
26718 for postprocessing.
26719
26720 @<Character |k| is not allowed in PostScript output@>=
26721   (k<=' ')||(k>'~')
26722
26723 @ Saving the filename template
26724
26725 @<Save the filename template@>=
26726
26727   if ( mp->filename_template!=0 ) delete_str_ref(mp->filename_template);
26728   if ( length(mp->cur_exp)==0 ) mp->filename_template=0;
26729   else { 
26730     mp->filename_template=mp->cur_exp; add_str_ref(mp->filename_template);
26731   }
26732 }
26733
26734 @* \[48] System-dependent changes.
26735 This section should be replaced, if necessary, by any special
26736 modification of the program
26737 that are necessary to make \MP\ work at a particular installation.
26738 It is usually best to design your change file so that all changes to
26739 previous sections preserve the section numbering; then everybody's version
26740 will be consistent with the published program. More extensive changes,
26741 which introduce new sections, can be inserted here; then only the index
26742 itself will get a new section number.
26743 @^system dependencies@>
26744
26745 @* \[49] Index.
26746 Here is where you can find all uses of each identifier in the program,
26747 with underlined entries pointing to where the identifier was defined.
26748 If the identifier is only one letter long, however, you get to see only
26749 the underlined entries. {\sl All references are to section numbers instead of
26750 page numbers.}
26751
26752 This index also lists error messages and other aspects of the program
26753 that you might want to look up some day. For example, the entry
26754 for ``system dependencies'' lists all sections that should receive
26755 special attention from people who are installing \MP\ in a new
26756 operating environment. A list of various things that can't happen appears
26757 under ``this can't happen''.
26758 Approximately 25 sections are listed under ``inner loop''; these account
26759 for more than 60\pct! of \MP's running time, exclusive of input and output.