simplified the start of ship_out a bit
[mplib] / src / texk / web2c / mpdir / lib / mp.w
1 % $Id: mp.web,v 1.8 2005/08/24 10:54:02 taco Exp $
2 % MetaPost, by John Hobby.  Public domain.
3
4 % Much of this program was copied with permission from MF.web Version 1.9
5 % It interprets a language very similar to D.E. Knuth's METAFONT, but with
6 % changes designed to make it more suitable for PostScript output.
7
8 % TeX is a trademark of the American Mathematical Society.
9 % METAFONT is a trademark of Addison-Wesley Publishing Company.
10 % PostScript is a trademark of Adobe Systems Incorporated.
11
12 % Here is TeX material that gets inserted after \input webmac
13 \def\hang{\hangindent 3em\noindent\ignorespaces}
14 \def\textindent#1{\hangindent2.5em\noindent\hbox to2.5em{\hss#1 }\ignorespaces}
15 \def\PASCAL{Pascal}
16 \def\ps{PostScript}
17 \def\ph{\hbox{Pascal-H}}
18 \def\psqrt#1{\sqrt{\mathstrut#1}}
19 \def\k{_{k+1}}
20 \def\pct!{{\char`\%}} % percent sign in ordinary text
21 \font\tenlogo=logo10 % font used for the METAFONT logo
22 \font\logos=logosl10
23 \def\MF{{\tenlogo META}\-{\tenlogo FONT}}
24 \def\MP{{\tenlogo META}\-{\tenlogo POST}}
25 \def\[#1]{#1.} % from pascal web
26 \def\<#1>{$\langle#1\rangle$}
27 \def\section{\mathhexbox278}
28 \let\swap=\leftrightarrow
29 \def\round{\mathop{\rm round}\nolimits}
30 \mathchardef\vb="026A % synonym for `\|'
31
32 \def\(#1){} % this is used to make section names sort themselves better
33 \def\9#1{} % this is used for sort keys in the index via @@:sort key}{entry@@>
34 \def\title{MetaPost}
35 \def\glob{15} % this should be the section number of "<Global...>"
36 \def\gglob{23, 28} % this should be the next two sections of "<Global...>"
37 \pdfoutput=1
38 \pageno=3
39
40 @* \[1] Introduction.
41 This is \MP, a graphics-language processor based on D. E. Knuth's \MF.
42
43 The main purpose of the following program is to explain the algorithms of \MP\
44 as clearly as possible. As a result, the program will not necessarily be very
45 efficient when a particular \PASCAL\ compiler has translated it into a
46 particular machine language. However, the program has been written so that it
47 can be tuned to run efficiently in a wide variety of operating environments
48 by making comparatively few changes. Such flexibility is possible because
49 the documentation that follows is written in the \.{WEB} language, which is
50 at a higher level than \PASCAL; the preprocessing step that converts \.{WEB}
51 to \PASCAL\ is able to introduce most of the necessary refinements.
52 Semi-automatic translation to other languages is also feasible, because the
53 program below does not make extensive use of features that are peculiar to
54 \PASCAL.
55
56 A large piece of software like \MP\ has inherent complexity that cannot
57 be reduced below a certain level of difficulty, although each individual
58 part is fairly simple by itself. The \.{WEB} language is intended to make
59 the algorithms as readable as possible, by reflecting the way the
60 individual program pieces fit together and by providing the
61 cross-references that connect different parts. Detailed comments about
62 what is going on, and about why things were done in certain ways, have
63 been liberally sprinkled throughout the program.  These comments explain
64 features of the implementation, but they rarely attempt to explain the
65 \MP\ language itself, since the reader is supposed to be familiar with
66 {\sl The {\logos METAFONT\/}book} as well as the manual
67 @.WEB@>
68 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
69 {\sl A User's Manual for MetaPost}, Computing Science Technical Report 162,
70 AT\AM T Bell Laboratories.
71
72 @ The present implementation is a preliminary version, but the possibilities
73 for new features are limited by the desire to remain as nearly compatible
74 with \MF\ as possible.
75
76 On the other hand, the \.{WEB} description can be extended without changing
77 the core of the program, and it has been designed so that such
78 extensions are not extremely difficult to make.
79 The |banner| string defined here should be changed whenever \MP\
80 undergoes any modifications, so that it will be clear which version of
81 \MP\ might be the guilty party when a problem arises.
82 @^extensions to \MP@>
83 @^system dependencies@>
84
85 @d banner "This is MetaPost, Version 1.002" /* printed when \MP\ starts */
86 @d metapost_version "1.002"
87 @d mplib_version "0.10"
88 @d version_string " (Cweb version 0.10)"
89
90 @ Different \PASCAL s have slightly different conventions, and the present
91 @:PASCAL H}{\ph@>
92 program is expressed in a version of \PASCAL\ that D. E. Knuth used for \MF.
93 Constructions that apply to
94 this particular compiler, which we shall call \ph, should help the
95 reader see how to make an appropriate interface for other systems
96 if necessary. (\ph\ is Charles Hedrick's modification of a compiler
97 @^Hedrick, Charles Locke@>
98 for the DECsystem-10 that was originally developed at the University of
99 Hamburg; cf.\ {\sl SOFTWARE---Practice \AM\ Experience \bf6} (1976),
100 29--42. The \MP\ program below is intended to be adaptable, without
101 extensive changes, to most other versions of \PASCAL\ and commonly used
102 \PASCAL-to-C translators, so it does not fully
103 @:C@>
104 use the admirable features of \ph. Indeed, a conscious effort has been
105 made here to avoid using several idiosyncratic features of standard
106 \PASCAL\ itself, so that most of the code can be translated mechanically
107 into other high-level languages. For example, the `\&{with}' and `\\{new}'
108 features are not used, nor are pointer types, set types, or enumerated
109 scalar types; there are no `\&{var}' parameters, except in the case of files;
110 there are no tag fields on variant records; there are no |real| variables;
111 no procedures are declared local to other procedures.)
112
113 The portions of this program that involve system-dependent code, where
114 changes might be necessary because of differences between \PASCAL\ compilers
115 and/or differences between
116 operating systems, can be identified by looking at the sections whose
117 numbers are listed under `system dependencies' in the index. Furthermore,
118 the index entries for `dirty \PASCAL' list all places where the restrictions
119 of \PASCAL\ have not been followed perfectly, for one reason or another.
120 @^system dependencies@>
121 @^dirty \PASCAL@>
122
123 @ The program begins with a normal \PASCAL\ program heading, whose
124 components will be filled in later, using the conventions of \.{WEB}.
125 @.WEB@>
126 For example, the portion of the program called `\X\glob:Global
127 variables\X' below will be replaced by a sequence of variable declarations
128 that starts in $\section\glob$ of this documentation. In this way, we are able
129 to define each individual global variable when we are prepared to
130 understand what it means; we do not have to define all of the globals at
131 once.  Cross references in $\section\glob$, where it says ``See also
132 sections \gglob, \dots,'' also make it possible to look at the set of
133 all global variables, if desired.  Similar remarks apply to the other
134 portions of the program heading.
135
136 Actually the heading shown here is not quite normal: The |program| line
137 does not mention any |output| file, because \ph\ would ask the \MP\ user
138 to specify a file name if |output| were specified here.
139 @^system dependencies@>
140
141 @d true 1
142 @d false 0
143  
144 @(mplib.h@>=
145 typedef struct MP_instance * MP;
146 @<Exported types@>
147 typedef struct MP_options {
148   @<Option variables@>
149 } MP_options;
150 @<Exported function headers@>
151
152 @ @(mpmp.h@>=
153 #include <setjmp.h>
154 typedef struct psout_data_struct * psout_data;
155 typedef int boolean;
156 typedef signed int integer;
157 @<Declare helpers@>;
158 @<Types in the outer block@>;
159 @<Constants in the outer block@>
160 #  ifndef LIBAVL_ALLOCATOR
161 #    define LIBAVL_ALLOCATOR
162     struct libavl_allocator {
163         void *(*libavl_malloc) (struct libavl_allocator *, size_t libavl_size);
164         void (*libavl_free) (struct libavl_allocator *, void *libavl_block);
165     };
166 #  endif
167 typedef struct MP_instance {
168   @<Global variables@>
169 } MP_instance;
170 @<Internal library declarations@>
171
172 @ @c 
173 #include <stdio.h>
174 #include <stdlib.h>
175 #include <string.h>
176 #include <stdarg.h>
177 #include <assert.h>
178 #include <unistd.h> /* for access() */
179 #include <time.h> /* for struct tm \& co */
180 #include "mplib.h"
181 #include "mpmp.h" /* internal header */
182 #include "mppsout.h" /* internal header */
183 @h
184 @<Declarations@>
185 @<Basic printing procedures@>
186 @<Error handling procedures@>
187
188 @ Here are the functions that set up the \MP\ instance.
189
190 @<Declarations@> =
191 @<Declare |mp_reallocate| functions@>;
192 struct MP_options *mp_options (void);
193 MP mp_new (struct MP_options *opt);
194
195 @ @c
196 struct MP_options *mp_options (void) {
197   struct MP_options *opt;
198   opt = malloc(sizeof(MP_options));
199   if (opt!=NULL) {
200     memset (opt,0,sizeof(MP_options));
201   }
202   return opt;
203
204 MP mp_new (struct MP_options *opt) {
205   MP mp;
206   mp = xmalloc(1,sizeof(MP_instance));
207   @<Set |ini_version|@>;
208   @<Setup the non-local jump buffer in |mp_new|@>;
209   @<Allocate or initialize variables@>
210   if (opt->main_memory>mp->mem_max)
211     mp_reallocate_memory(mp,opt->main_memory);
212   mp_reallocate_paths(mp,1000);
213   mp_reallocate_fonts(mp,8);
214   mp->term_in = stdin;
215   mp->term_out = stdout;
216   return mp;
217 }
218 void mp_free (MP mp) {
219   int k; /* loop variable */
220   @<Dealloc variables@>
221   xfree(mp);
222 }
223
224 @ @c
225 void mp_do_initialize ( MP mp) {
226   @<Local variables for initialization@>
227   @<Set initial values of key variables@>
228 }
229 int mp_initialize (MP mp) { /* this procedure gets things started properly */
230   mp->history=mp_fatal_error_stop; /* in case we quit during initialization */
231   @<Install and test the non-local jump buffer@>;
232   t_open_out; /* open the terminal for output */
233   @<Check the ``constant'' values...@>;
234   if ( mp->bad>0 ) {
235     fprintf(stdout,"Ouch---my internal constants have been clobbered!\n"
236                    "---case %i",(int)mp->bad);
237 @.Ouch...clobbered@>
238     return mp->history;
239   }
240   mp_do_initialize(mp); /* erase preloaded mem */
241   if (mp->ini_version) {
242     @<Run inimpost commands@>;
243   }
244   @<Initialize the output routines@>;
245   @<Get the first line of input and prepare to start@>;
246   mp_set_job_id(mp);
247   mp_init_map_file(mp, mp->troff_mode);
248   mp->history=mp_spotless; /* ready to go! */
249   if (mp->troff_mode) {
250     mp->internal[mp_gtroffmode]=unity; 
251     mp->internal[mp_prologues]=unity; 
252   }
253   if ( mp->start_sym>0 ) { /* insert the `\&{everyjob}' symbol */
254     mp->cur_sym=mp->start_sym; mp_back_input(mp);
255   }
256   return mp->history;
257 }
258
259
260 @<Exported function headers@>=
261 extern struct MP_options *mp_options (void);
262 extern MP mp_new (struct MP_options *opt) ;
263 extern void mp_free (MP mp);
264 extern int mp_initialize (MP mp);
265
266 @ @<Declarations@>=
267 void mp_do_initialize (MP mp);
268
269
270 @ The overall \MP\ program begins with the heading just shown, after which
271 comes a bunch of procedure declarations and function declarations.
272 Finally we will get to the main program, which begins with the
273 comment `|start_here|'. If you want to skip down to the
274 main program now, you can look up `|start_here|' in the index.
275 But the author suggests that the best way to understand this program
276 is to follow pretty much the order of \MP's components as they appear in the
277 \.{WEB} description you are now reading, since the present ordering is
278 intended to combine the advantages of the ``bottom up'' and ``top down''
279 approaches to the problem of understanding a somewhat complicated system.
280
281 @ Some of the code below is intended to be used only when diagnosing the
282 strange behavior that sometimes occurs when \MP\ is being installed or
283 when system wizards are fooling around with \MP\ without quite knowing
284 what they are doing. Such code will not normally be compiled; it is
285 delimited by the preprocessor test `|#ifdef DEBUG .. #endif|'.
286
287 @ This program has two important variations: (1) There is a long and slow
288 version called \.{INIMP}, which does the extra calculations needed to
289 @.INIMP@>
290 initialize \MP's internal tables; and (2)~there is a shorter and faster
291 production version, which cuts the initialization to a bare minimum.
292
293 Which is which is decided at runtime.
294
295 @ The following parameters can be changed at compile time to extend or
296 reduce \MP's capacity. They may have different values in \.{INIMP} and
297 in production versions of \MP.
298 @.INIMP@>
299 @^system dependencies@>
300
301 @<Constants...@>=
302 #define file_name_size 255 /* file names shouldn't be longer than this */
303 #define bistack_size 1500 /* size of stack for bisection algorithms;
304   should probably be left at this value */
305
306 @ Like the preceding parameters, the following quantities can be changed
307 at compile time to extend or reduce \MP's capacity. But if they are changed,
308 it is necessary to rerun the initialization program \.{INIMP}
309 @.INIMP@>
310 to generate new tables for the production \MP\ program.
311 One can't simply make helter-skelter changes to the following constants,
312 since certain rather complex initialization
313 numbers are computed from them. 
314
315 @ @<Glob...@>=
316 int max_strings; /* maximum number of strings; must not exceed |max_halfword| */
317 int pool_size; /* maximum number of characters in strings, including all
318   error messages and help texts, and the names of all identifiers */
319 int error_line; /* width of context lines on terminal error messages */
320 int half_error_line; /* width of first lines of contexts in terminal
321   error messages; should be between 30 and |error_line-15| */
322 int max_print_line; /* width of longest text lines output; should be at least 60 */
323 int mem_max; /* greatest index in \MP's internal |mem| array;
324   must be strictly less than |max_halfword|;
325   must be equal to |mem_top| in \.{INIMP}, otherwise |>=mem_top| */
326 int mem_top; /* largest index in the |mem| array dumped by \.{INIMP};
327   must not be greater than |mem_max| */
328 int hash_size; /* maximum number of symbolic tokens,
329   must be less than |max_halfword-3*param_size| */
330 int hash_prime; /* a prime number equal to about 85\pct! of |hash_size| */
331 int param_size; /* maximum number of simultaneous macro parameters */
332 int max_in_open; /* maximum number of input files and error insertions that
333   can be going on simultaneously */
334
335 @ @<Option variables@>=
336 int error_line;
337 int half_error_line;
338 int max_print_line;
339 int main_memory;
340 int hash_size; 
341 int hash_prime; 
342 int param_size; 
343 int max_in_open; 
344
345
346 @d set_value(a,b,c) do { a=c; if (b>c) a=b; } while (0)
347
348 @<Allocate or ...@>=
349 mp->max_strings=500;
350 mp->pool_size=10000;
351 set_value(mp->error_line,opt->error_line,79);
352 set_value(mp->half_error_line,opt->half_error_line,50);
353 set_value(mp->max_print_line,opt->max_print_line,79);
354 mp->mem_max=5000;
355 mp->mem_top=5000;
356 set_value(mp->hash_size,opt->hash_size,9500);
357 set_value(mp->hash_prime,opt->hash_prime,7919);
358 set_value(mp->param_size,opt->param_size,150);
359 set_value(mp->max_in_open,opt->max_in_open,10);
360
361
362 @ In case somebody has inadvertently made bad settings of the ``constants,''
363 \MP\ checks them using a global variable called |bad|.
364
365 This is the first of many sections of \MP\ where global variables are
366 defined.
367
368 @<Glob...@>=
369 integer bad; /* is some ``constant'' wrong? */
370
371 @ Later on we will say `\ignorespaces|if (mem_max>=max_halfword) bad=10;|',
372 or something similar. (We can't do that until |max_halfword| has been defined.)
373
374 @<Check the ``constant'' values for consistency@>=
375 mp->bad=0;
376 if ( (mp->half_error_line<30)||(mp->half_error_line>mp->error_line-15) ) mp->bad=1;
377 if ( mp->max_print_line<60 ) mp->bad=2;
378 if ( mp->mem_top<=1100 ) mp->bad=4;
379 if (mp->hash_prime>mp->hash_size ) mp->bad=5;
380
381 @ Labels are given symbolic names by the following definitions, so that
382 occasional |goto| statements will be meaningful. We insert the label
383 `|exit|:' just before the `\ignorespaces|end|\unskip' of a procedure in
384 which we have used the `|return|' statement defined below; the label
385 `|restart|' is occasionally used at the very beginning of a procedure; and
386 the label `|reswitch|' is occasionally used just prior to a |case|
387 statement in which some cases change the conditions and we wish to branch
388 to the newly applicable case.  Loops that are set up with the |loop|
389 construction defined below are commonly exited by going to `|done|' or to
390 `|found|' or to `|not_found|', and they are sometimes repeated by going to
391 `|continue|'.  If two or more parts of a subroutine start differently but
392 end up the same, the shared code may be gathered together at
393 `|common_ending|'.
394
395 Incidentally, this program never declares a label that isn't actually used,
396 because some fussy \PASCAL\ compilers will complain about redundant labels.
397
398 @d label_exit 10 /* go here to leave a procedure */
399 @d restart 20 /* go here to start a procedure again */
400 @d reswitch 21 /* go here to start a case statement again */
401 @d continue 22 /* go here to resume a loop */
402 @d done 30 /* go here to exit a loop */
403 @d done1 31 /* like |done|, when there is more than one loop */
404 @d done2 32 /* for exiting the second loop in a long block */
405 @d done3 33 /* for exiting the third loop in a very long block */
406 @d done4 34 /* for exiting the fourth loop in an extremely long block */
407 @d done5 35 /* for exiting the fifth loop in an immense block */
408 @d done6 36 /* for exiting the sixth loop in a block */
409 @d found 40 /* go here when you've found it */
410 @d found1 41 /* like |found|, when there's more than one per routine */
411 @d found2 42 /* like |found|, when there's more than two per routine */
412 @d found3 43 /* like |found|, when there's more than three per routine */
413 @d not_found 45 /* go here when you've found nothing */
414 @d common_ending 50 /* go here when you want to merge with another branch */
415
416 @ Here are some macros for common programming idioms.
417
418 @d incr(A)   (A)=(A)+1 /* increase a variable by unity */
419 @d decr(A)   (A)=(A)-1 /* decrease a variable by unity */
420 @d negate(A) (A)=-(A) /* change the sign of a variable */
421 @d double(A) (A)=(A)+(A)
422 @d odd(A)   ((A)%2==1)
423 @d chr(A)   (A)
424 @d do_nothing   /* empty statement */
425 @d Return   goto exit /* terminate a procedure call */
426 @f return   nil /* \.{WEB} will henceforth say |return| instead of \\{return} */
427
428 @* \[2] The character set.
429 In order to make \MP\ readily portable to a wide variety of
430 computers, all of its input text is converted to an internal eight-bit
431 code that includes standard ASCII, the ``American Standard Code for
432 Information Interchange.''  This conversion is done immediately when each
433 character is read in. Conversely, characters are converted from ASCII to
434 the user's external representation just before they are output to a
435 text file.
436 @^ASCII code@>
437
438 Such an internal code is relevant to users of \MP\ only with respect to
439 the \&{char} and \&{ASCII} operations, and the comparison of strings.
440
441 @ Characters of text that have been converted to \MP's internal form
442 are said to be of type |ASCII_code|, which is a subrange of the integers.
443
444 @<Types...@>=
445 typedef unsigned char ASCII_code; /* eight-bit numbers */
446
447 @ The original \PASCAL\ compiler was designed in the late 60s, when six-bit
448 character sets were common, so it did not make provision for lowercase
449 letters. Nowadays, of course, we need to deal with both capital and small
450 letters in a convenient way, especially in a program for font design;
451 so the present specification of \MP\ has been written under the assumption
452 that the \PASCAL\ compiler and run-time system permit the use of text files
453 with more than 64 distinguishable characters. More precisely, we assume that
454 the character set contains at least the letters and symbols associated
455 with ASCII codes 040 through 0176; all of these characters are now
456 available on most computer terminals.
457
458 Since we are dealing with more characters than were present in the first
459 \PASCAL\ compilers, we have to decide what to call the associated data
460 type. Some \PASCAL s use the original name |char| for the
461 characters in text files, even though there now are more than 64 such
462 characters, while other \PASCAL s consider |char| to be a 64-element
463 subrange of a larger data type that has some other name.
464
465 In order to accommodate this difference, we shall use the name |text_char|
466 to stand for the data type of the characters that are converted to and
467 from |ASCII_code| when they are input and output. We shall also assume
468 that |text_char| consists of the elements |chr(first_text_char)| through
469 |chr(last_text_char)|, inclusive. The following definitions should be
470 adjusted if necessary.
471 @^system dependencies@>
472
473 @d first_text_char 0 /* ordinal number of the smallest element of |text_char| */
474 @d last_text_char 255 /* ordinal number of the largest element of |text_char| */
475
476 @<Types...@>=
477 typedef unsigned char text_char; /* the data type of characters in text files */
478
479 @ @<Local variables for init...@>=
480 integer i;
481
482 @ The \MP\ processor converts between ASCII code and
483 the user's external character set by means of arrays |xord| and |xchr|
484 that are analogous to \PASCAL's |ord| and |chr| functions.
485
486 @d xchr(A) mp->xchr[(A)]
487 @d xord(A) mp->xord[(A)]
488
489 @<Glob...@>=
490 ASCII_code xord[256];  /* specifies conversion of input characters */
491 text_char xchr[256];  /* specifies conversion of output characters */
492
493 @ The core system assumes all 8-bit is acceptable.  If it is not,
494 a change file has to alter the below section.
495 @^system dependencies@>
496
497 Additionally, people with extended character sets can
498 assign codes arbitrarily, giving an |xchr| equivalent to whatever
499 characters the users of \MP\ are allowed to have in their input files.
500 Appropriate changes to \MP's |char_class| table should then be made.
501 (Unlike \TeX, each installation of \MP\ has a fixed assignment of category
502 codes, called the |char_class|.) Such changes make portability of programs
503 more difficult, so they should be introduced cautiously if at all.
504 @^character set dependencies@>
505 @^system dependencies@>
506
507 @<Set initial ...@>=
508 for (i=0;i<=0377;i++) { xchr(i)=i; }
509
510 @ The following system-independent code makes the |xord| array contain a
511 suitable inverse to the information in |xchr|. Note that if |xchr[i]=xchr[j]|
512 where |i<j<0177|, the value of |xord[xchr[i]]| will turn out to be
513 |j| or more; hence, standard ASCII code numbers will be used instead of
514 codes below 040 in case there is a coincidence.
515
516 @<Set initial ...@>=
517 for (i=first_text_char;i<=last_text_char;i++) { 
518    xord(chr(i))=0177;
519 }
520 for (i=0200;i<=0377;i++) { xord(xchr(i))=i;}
521 for (i=0;i<=0176;i++) { xord(xchr(i))=i;}
522
523 @* \[3] Input and output.
524 The bane of portability is the fact that different operating systems treat
525 input and output quite differently, perhaps because computer scientists
526 have not given sufficient attention to this problem. People have felt somehow
527 that input and output are not part of ``real'' programming. Well, it is true
528 that some kinds of programming are more fun than others. With existing
529 input/output conventions being so diverse and so messy, the only sources of
530 joy in such parts of the code are the rare occasions when one can find a
531 way to make the program a little less bad than it might have been. We have
532 two choices, either to attack I/O now and get it over with, or to postpone
533 I/O until near the end. Neither prospect is very attractive, so let's
534 get it over with.
535
536 The basic operations we need to do are (1)~inputting and outputting of
537 text, to or from a file or the user's terminal; (2)~inputting and
538 outputting of eight-bit bytes, to or from a file; (3)~instructing the
539 operating system to initiate (``open'') or to terminate (``close'') input or
540 output from a specified file; (4)~testing whether the end of an input
541 file has been reached; (5)~display of bits on the user's screen.
542 The bit-display operation will be discussed in a later section; we shall
543 deal here only with more traditional kinds of I/O.
544
545 @ Finding files happens in a slightly roundabout fashion: the \MP\
546 instance object contains a field that holds a function pointer that finds a
547 file, and returns its name, or NULL. For this, it receives three
548 parameters: the non-qualified name |fname|, the intended |fopen|
549 operation type |fmode|, and the type of the file |ftype|.
550
551 The file types that are passed on in |ftype| can be  used to 
552 differentiate file searches if a library like kpathsea is used,
553 the fopen mode is passed along for the same reason.
554
555 @<Types...@>=
556 typedef unsigned char eight_bits ; /* unsigned one-byte quantity */
557
558 @ @<Exported types@>=
559 enum mp_filetype {
560   mp_filetype_program = 1, /* \MP\ language input */
561   mp_filetype_log,  /* the log file */
562   mp_filetype_postscript, /* the postscript output */
563   mp_filetype_text,  /* text files for readfrom and writeto primitives */
564   mp_filetype_memfile, /* memory dumps */
565   mp_filetype_metrics, /* TeX font metric files */
566   mp_filetype_fontmap, /* PostScript font mapping files */
567   mp_filetype_font, /*  PostScript type1 font programs */
568   mp_filetype_encoding, /*  PostScript font encoding files */
569 };
570 typedef char *(*mp_file_finder)(char *, char *, int);
571
572 @ @<Glob...@>=
573 mp_file_finder find_file;
574
575 @ @<Option variables@>=
576 mp_file_finder find_file;
577
578 @ The default function for finding files is |mp_find_file|. It is 
579 pretty stupid: it will only find files in the current directory.
580
581 @c
582 char *mp_find_file (char *fname, char *fmode, int ftype)  {
583   if (fmode[0] != 'r' || access (fname,R_OK) || ftype)  
584      return strdup(fname);
585   return NULL;
586 }
587
588 @ This has to be done very early on, so it is best to put it in with
589 the |mp_new| allocations
590
591 @d set_callback_option(A) do { mp->A = mp_##A;
592   if (opt->A!=NULL) mp->A = opt->A;
593 } while (0)
594
595 @<Allocate or initialize ...@>=
596 set_callback_option(find_file);
597
598 @ Because |mp_find_file| is used so early, it has to be in the helpers
599 section.
600
601 @<Internal ...@>=
602 char *mp_find_file (char *fname, char *fmode, int ftype) ;
603
604 @ The function to open files can now be very short.
605
606 @c
607 FILE *mp_open_file(MP mp, char *fname, char *fmode, int ftype)  {
608   char *s = (mp->find_file)(fname,fmode,ftype);
609   if (s!=NULL) {
610     FILE *f = fopen(s, fmode);
611     xfree(s);
612     return f;   
613   }
614   return NULL;
615 }
616
617 @ This is a legacy interface: (almost) all file names pass through |name_of_file|.
618
619 @<Glob...@>=
620 char name_of_file[file_name_size+1]; /* the name of a system file */
621 int name_length;/* this many characters are actually
622   relevant in |name_of_file| (the rest are blank) */
623 boolean print_found_names; /* configuration parameter */
624
625 @ @<Option variables@>=
626 int print_found_names; /* configuration parameter */
627
628 @ If this parameter is true, the terminal and log will report the found
629 file names for input files instead of the requested ones. 
630 It is off by default because it creates an extra filename lookup.
631
632 @<Allocate or initialize ...@>=
633 mp->print_found_names = (opt->print_found_names>0 ? true : false);
634
635 @ \MP's file-opening procedures return |false| if no file identified by
636 |name_of_file| could be opened.
637
638 The |OPEN_FILE| macro takes care of the |print_found_names| parameter.
639 It is not used for opening a mem file for read, because that file name 
640 is never printed.
641
642 @d OPEN_FILE(A) do {
643   if (mp->print_found_names) {
644     char *s = (mp->find_file)(mp->name_of_file,A,ftype);
645     if (s!=NULL) {
646       *f = mp_open_file(mp,mp->name_of_file,A, ftype); 
647       strncpy(mp->name_of_file,s,file_name_size);
648       xfree(s);
649     } else {
650       *f = NULL;
651     }
652   } else {
653     *f = mp_open_file(mp,mp->name_of_file,A, ftype); 
654   }
655 } while (0);
656 return (*f ? true : false)
657
658 @c 
659 boolean mp_a_open_in (MP mp, FILE **f, int ftype) {
660   /* open a text file for input */
661   OPEN_FILE("r");
662 }
663 @#
664 boolean mp_w_open_in (MP mp, FILE **f) {
665   /* open a word file for input */
666   *f = mp_open_file(mp,mp->name_of_file,"rb",mp_filetype_memfile); 
667   return (*f ? true : false);
668 }
669 @#
670 boolean mp_a_open_out (MP mp, FILE **f, int ftype) {
671   /* open a text file for output */
672   OPEN_FILE("w");
673 }
674 @#
675 boolean mp_b_open_out (MP mp, FILE **f, int ftype) {
676   /* open a binary file for output */
677   OPEN_FILE("wb");
678 }
679 @#
680 boolean mp_w_open_out (MP mp, FILE**f) {
681   /* open a word file for output */
682   int ftype = mp_filetype_memfile;
683   OPEN_FILE("wb");
684 }
685
686 @ @<Internal ...@>=
687 FILE *mp_open_file(MP mp, char *fname, char *fmode, int ftype);
688
689 @ Binary input and output are done with \PASCAL's ordinary |get| and |put|
690 procedures, so we don't have to make any other special arrangements for
691 binary~I/O. Text output is also easy to do with standard \PASCAL\ routines.
692 The treatment of text input is more difficult, however, because
693 of the necessary translation to |ASCII_code| values.
694 \MP's conventions should be efficient, and they should
695 blend nicely with the user's operating environment.
696
697 @ Input from text files is read one line at a time, using a routine called
698 |input_ln|. This function is defined in terms of global variables called
699 |buffer|, |first|, and |last| that will be described in detail later; for
700 now, it suffices for us to know that |buffer| is an array of |ASCII_code|
701 values, and that |first| and |last| are indices into this array
702 representing the beginning and ending of a line of text.
703
704 @<Glob...@>=
705 size_t buf_size; /* maximum number of characters simultaneously present in
706                     current lines of open files */
707 ASCII_code *buffer; /* lines of characters being read */
708 size_t first; /* the first unused position in |buffer| */
709 size_t last; /* end of the line just input to |buffer| */
710 size_t max_buf_stack; /* largest index used in |buffer| */
711
712 @ @<Allocate or initialize ...@>=
713 mp->buf_size = 200;
714 mp->buffer = xmalloc((mp->buf_size+1),sizeof(ASCII_code));
715
716 @ @<Dealloc variables@>=
717 xfree(mp->buffer);
718
719 @ @c
720 void mp_reallocate_buffer(MP mp, size_t l) {
721   ASCII_code *buffer;
722   if (l>max_halfword) {
723     mp_confusion(mp,"buffer size"); /* can't happen (I hope) */
724   }
725   buffer = xmalloc((l+1),sizeof(ASCII_code));
726   memcpy(buffer,mp->buffer,(mp->buf_size+1));
727   xfree(mp->buffer);
728   mp->buffer = buffer ;
729   mp->buf_size = l;
730 }
731
732 @ The |input_ln| function brings the next line of input from the specified
733 field into available positions of the buffer array and returns the value
734 |true|, unless the file has already been entirely read, in which case it
735 returns |false| and sets |last:=first|.  In general, the |ASCII_code|
736 numbers that represent the next line of the file are input into
737 |buffer[first]|, |buffer[first+1]|, \dots, |buffer[last-1]|; and the
738 global variable |last| is set equal to |first| plus the length of the
739 line. Trailing blanks are removed from the line; thus, either |last=first|
740 (in which case the line was entirely blank) or |buffer[last-1]<>" "|.
741 @^inner loop@>
742
743 An overflow error is given, however, if the normal actions of |input_ln|
744 would make |last>=buf_size|; this is done so that other parts of \MP\
745 can safely look at the contents of |buffer[last+1]| without overstepping
746 the bounds of the |buffer| array. Upon entry to |input_ln|, the condition
747 |first<buf_size| will always hold, so that there is always room for an
748 ``empty'' line.
749
750 The variable |max_buf_stack|, which is used to keep track of how large
751 the |buf_size| parameter must be to accommodate the present job, is
752 also kept up to date by |input_ln|.
753
754 If the |bypass_eoln| parameter is |true|, |input_ln| will do a |get|
755 before looking at the first character of the line; this skips over
756 an |eoln| that was in |f^|. The procedure does not do a |get| when it
757 reaches the end of the line; therefore it can be used to acquire input
758 from the user's terminal as well as from ordinary text files.
759
760 Standard \PASCAL\ says that a file should have |eoln| immediately
761 before |eof|, but \MP\ needs only a weaker restriction: If |eof|
762 occurs in the middle of a line, the system function |eoln| should return
763 a |true| result (even though |f^| will be undefined).
764
765 @c 
766 boolean mp_input_ln (MP mp,FILE *  f, boolean bypass_eoln) {
767   /* inputs the next line or returns |false| */
768   int last_nonblank; /* |last| with trailing blanks removed */
769   int c;
770   if ( bypass_eoln ) {
771     c = fgetc(f);
772     if (c==EOF)
773       return false;
774     if (c!='\n' && c!='\r') {
775       ungetc(c,f);
776     }
777   }
778   /* input the first character of the line into |f^| */
779   mp->last=mp->first; /* cf.\ Matthew 19\thinspace:\thinspace30 */
780   c = fgetc(f);
781   if (c==EOF)
782         return false;
783   last_nonblank=mp->first;
784   while (c!=EOF && c!='\n' && c!='\r') { 
785     if ( mp->last>=mp->max_buf_stack ) { 
786       mp->max_buf_stack=mp->last+1;
787       if ( mp->max_buf_stack==mp->buf_size ) {
788         mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
789       }
790     }
791     mp->buffer[mp->last]=xord(c); 
792     incr(mp->last);
793     if ( mp->buffer[mp->last-1]!=' ' ) 
794       last_nonblank=mp->last;
795     c = fgetc(f); 
796   } 
797   if (c!=EOF) {
798     ungetc(c,f);
799   }
800   mp->last=last_nonblank; 
801   return true;
802 }
803
804 @ The user's terminal acts essentially like other files of text, except
805 that it is used both for input and for output. When the terminal is
806 considered an input file, the file variable is called |term_in|, and when it
807 is considered an output file the file variable is |term_out|.
808 @^system dependencies@>
809
810 @<Glob...@>=
811 FILE * term_in; /* the terminal as an input file */
812 FILE * term_out; /* the terminal as an output file */
813
814 @ Here is how to open the terminal files. In the default configuration,
815 nothing happens except that the command line (if there is one) is copied
816 to the input buffer.  The variable |command_line| will be filled by the 
817 |main| procedure. The copying can not be done earlier in the program 
818 logic because in the |INI| version, the |buffer| is also used for primitive 
819 initialization.
820
821 @^system dependencies@>
822
823 @d t_open_out  /* open the terminal for text output */
824 @d t_open_in  do { /* open the terminal for text input */
825     if (mp->command_line!=NULL) {
826       mp->last = strlen(mp->command_line);
827       strncpy((char *)mp->buffer,mp->command_line,mp->last);
828       xfree(mp->command_line);
829     }
830 } while (0)
831
832 @<Glob...@>=
833 char *command_line;
834
835 @ @<Option variables@>=
836 char *command_line;
837
838 @ @<Allocate or initialize ...@>=
839 mp->command_line = opt->command_line;
840
841 @ Sometimes it is necessary to synchronize the input/output mixture that
842 happens on the user's terminal, and three system-dependent
843 procedures are used for this
844 purpose. The first of these, |update_terminal|, is called when we want
845 to make sure that everything we have output to the terminal so far has
846 actually left the computer's internal buffers and been sent.
847 The second, |clear_terminal|, is called when we wish to cancel any
848 input that the user may have typed ahead (since we are about to
849 issue an unexpected error message). The third, |wake_up_terminal|,
850 is supposed to revive the terminal if the user has disabled it by
851 some instruction to the operating system.  The following macros show how
852 these operations can be specified in \ph:
853 @^system dependencies@>
854
855 @d update_terminal   fflush(mp->term_out) /* empty the terminal output buffer */
856 @d clear_terminal   do_nothing /* clear the terminal input buffer */
857 @d wake_up_terminal  fflush(mp->term_out) /* cancel the user's cancellation of output */
858
859 @ We need a special routine to read the first line of \MP\ input from
860 the user's terminal. This line is different because it is read before we
861 have opened the transcript file; there is sort of a ``chicken and
862 egg'' problem here. If the user types `\.{input cmr10}' on the first
863 line, or if some macro invoked by that line does such an \.{input},
864 the transcript file will be named `\.{cmr10.log}'; but if no \.{input}
865 commands are performed during the first line of terminal input, the transcript
866 file will acquire its default name `\.{mpout.log}'. (The transcript file
867 will not contain error messages generated by the first line before the
868 first \.{input} command.)
869
870 The first line is even more special if we are lucky enough to have an operating
871 system that treats \MP\ differently from a run-of-the-mill \PASCAL\ object
872 program. It's nice to let the user start running a \MP\ job by typing
873 a command line like `\.{MP cmr10}'; in such a case, \MP\ will operate
874 as if the first line of input were `\.{cmr10}', i.e., the first line will
875 consist of the remainder of the command line, after the part that invoked \MP.
876
877 @ Different systems have different ways to get started. But regardless of
878 what conventions are adopted, the routine that initializes the terminal
879 should satisfy the following specifications:
880
881 \yskip\textindent{1)}It should open file |term_in| for input from the
882   terminal. (The file |term_out| will already be open for output to the
883   terminal.)
884
885 \textindent{2)}If the user has given a command line, this line should be
886   considered the first line of terminal input. Otherwise the
887   user should be prompted with `\.{**}', and the first line of input
888   should be whatever is typed in response.
889
890 \textindent{3)}The first line of input, which might or might not be a
891   command line, should appear in locations |first| to |last-1| of the
892   |buffer| array.
893
894 \textindent{4)}The global variable |loc| should be set so that the
895   character to be read next by \MP\ is in |buffer[loc]|. This
896   character should not be blank, and we should have |loc<last|.
897
898 \yskip\noindent(It may be necessary to prompt the user several times
899 before a non-blank line comes in. The prompt is `\.{**}' instead of the
900 later `\.*' because the meaning is slightly different: `\.{input}' need
901 not be typed immediately after~`\.{**}'.)
902
903 @d loc mp->cur_input.loc_field /* location of first unread character in |buffer| */
904
905 @ The following program does the required initialization
906 without retrieving a possible command line.
907 It should be clear how to modify this routine to deal with command lines,
908 if the system permits them.
909 @^system dependencies@>
910
911 @c 
912 boolean mp_init_terminal (MP mp) { /* gets the terminal input started */
913   t_open_in; 
914   if (mp->last!=0) {
915     loc = mp->first = 0;
916         return true;
917   }
918   while (1) { 
919     wake_up_terminal; fprintf(mp->term_out,"**"); update_terminal;
920 @.**@>
921     if ( ! mp_input_ln(mp, mp->term_in,true) ) { /* this shouldn't happen */
922       fprintf(mp->term_out,"\n! End of file on the terminal... why?");
923 @.End of file on the terminal@>
924       return false;
925     }
926     loc=mp->first;
927     while ( (loc<(int)mp->last)&&(mp->buffer[loc]==' ') ) 
928       incr(loc);
929     if ( loc<(int)mp->last ) { 
930       return true; /* return unless the line was all blank */
931     };
932     fprintf(mp->term_out,"Please type the name of your input file.\n");
933   }
934 }
935
936 @ @<Declarations@>=
937 boolean mp_init_terminal (MP mp) ;
938
939
940 @* \[4] String handling.
941 Symbolic token names and diagnostic messages are variable-length strings
942 of eight-bit characters. Since \PASCAL\ does not have a well-developed string
943 mechanism, \MP\ does all of its string processing by homegrown methods.
944
945 \MP\ uses strings more extensively than \MF\ does, but the necessary
946 operations can still be handled with a fairly simple data structure.
947 The array |str_pool| contains all of the (eight-bit) ASCII codes in all
948 of the strings, and the array |str_start| contains indices of the starting
949 points of each string. Strings are referred to by integer numbers, so that
950 string number |s| comprises the characters |str_pool[j]| for
951 |str_start[s]<=j<str_start[ss]| where |ss=next_str[s]|.  The string pool
952 is allocated sequentially and |str_pool[pool_ptr]| is the next unused
953 location.  The first string number not currently in use is |str_ptr|
954 and |next_str[str_ptr]| begins a list of free string numbers.  String
955 pool entries |str_start[str_ptr]| up to |pool_ptr| are reserved for a
956 string currently being constructed.
957
958 String numbers 0 to 255 are reserved for strings that correspond to single
959 ASCII characters. This is in accordance with the conventions of \.{WEB},
960 @.WEB@>
961 which converts single-character strings into the ASCII code number of the
962 single character involved, while it converts other strings into integers
963 and builds a string pool file. Thus, when the string constant \.{"."} appears
964 in the program below, \.{WEB} converts it into the integer 46, which is the
965 ASCII code for a period, while \.{WEB} will convert a string like \.{"hello"}
966 into some integer greater than~255. String number 46 will presumably be the
967 single character `\..'\thinspace; but some ASCII codes have no standard visible
968 representation, and \MP\ may need to be able to print an arbitrary
969 ASCII character, so the first 256 strings are used to specify exactly what
970 should be printed for each of the 256 possibilities.
971
972 @<Types...@>=
973 typedef int pool_pointer; /* for variables that point into |str_pool| */
974 typedef int str_number; /* for variables that point into |str_start| */
975
976 @ @<Glob...@>=
977 ASCII_code *str_pool; /* the characters */
978 pool_pointer *str_start; /* the starting pointers */
979 str_number *next_str; /* for linking strings in order */
980 pool_pointer pool_ptr; /* first unused position in |str_pool| */
981 str_number str_ptr; /* number of the current string being created */
982 pool_pointer init_pool_ptr; /* the starting value of |pool_ptr| */
983 str_number init_str_use; /* the initial number of strings in use */
984 pool_pointer max_pool_ptr; /* the maximum so far of |pool_ptr| */
985 str_number max_str_ptr; /* the maximum so far of |str_ptr| */
986
987 @ @<Allocate or initialize ...@>=
988 mp->str_pool  = xmalloc ((mp->pool_size +1),sizeof(ASCII_code));
989 mp->str_start = xmalloc ((mp->max_strings+1),sizeof(pool_pointer));
990 mp->next_str  = xmalloc ((mp->max_strings+1),sizeof(str_number));
991
992 @ @<Dealloc variables@>=
993 xfree(mp->str_pool);
994 xfree(mp->str_start);
995 xfree(mp->next_str);
996
997 @ Most printing is done from |char *|s, but sometimes not. Here are
998 functions that convert an internal string into a |char *| for use
999 by the printing routines, and vice versa.
1000
1001 @d str(A) mp_str(mp,A)
1002 @d rts(A) mp_rts(mp,A)
1003
1004 @<Internal ...@>=
1005 int mp_xstrcmp (const char *a, const char *b);
1006 char * mp_str (MP mp, str_number s);
1007
1008 @ @<Declarations@>=
1009 str_number mp_rts (MP mp, char *s);
1010 str_number mp_make_string (MP mp);
1011
1012 @ The attempt to catch interrupted strings that is in |mp_rts|, is not 
1013 very good: it does not handle nesting over more than one level.
1014
1015 @c 
1016 int mp_xstrcmp (const char *a, const char *b) {
1017         if (a==NULL && b==NULL) 
1018           return 0;
1019     if (a==NULL)
1020       return -1;
1021     if (b==NULL)
1022       return 1;
1023     return strcmp(a,b);
1024 }
1025
1026 @ @c
1027 char * mp_str (MP mp, str_number ss) {
1028   char *s;
1029   int len;
1030   if (ss==mp->str_ptr) {
1031     return NULL;
1032   } else {
1033     len = length(ss);
1034     s = xmalloc(len+1,sizeof(char));
1035     strncpy(s,(char *)(mp->str_pool+(mp->str_start[ss])),len);
1036     s[len] = 0;
1037     return (char *)s;
1038   }
1039 }
1040 str_number mp_rts (MP mp, char *s) {
1041   int r; /* the new string */ 
1042   int old; /* a possible string in progress */
1043   int i=0;
1044   if (strlen(s)==0) {
1045     return 256;
1046   } else if (strlen(s)==1) {
1047     return s[0];
1048   } else {
1049    old=0;
1050    str_room((integer)strlen(s));
1051    if (mp->str_start[mp->str_ptr]<mp->pool_ptr)
1052      old = mp_make_string(mp);
1053    while (*s) {
1054      append_char(*s);
1055      s++;
1056    }
1057    r = mp_make_string(mp);
1058    if (old!=0) {
1059       str_room(length(old));
1060       while (i<length(old)) {
1061         append_char((mp->str_start[old]+i));
1062       } 
1063       mp_flush_string(mp,old);
1064     }
1065     return r;
1066   }
1067 }
1068
1069 @ Except for |strs_used_up|, the following string statistics are only
1070 maintained when code between |stat| $\ldots$ |tats| delimiters is not
1071 commented out:
1072
1073 @<Glob...@>=
1074 integer strs_used_up; /* strings in use or unused but not reclaimed */
1075 integer pool_in_use; /* total number of cells of |str_pool| actually in use */
1076 integer strs_in_use; /* total number of strings actually in use */
1077 integer max_pl_used; /* maximum |pool_in_use| so far */
1078 integer max_strs_used; /* maximum |strs_in_use| so far */
1079
1080 @ Several of the elementary string operations are performed using \.{WEB}
1081 macros instead of \PASCAL\ procedures, because many of the
1082 operations are done quite frequently and we want to avoid the
1083 overhead of procedure calls. For example, here is
1084 a simple macro that computes the length of a string.
1085 @.WEB@>
1086
1087 @d str_stop(A) mp->str_start[mp->next_str[(A)]] /* one cell past the end of string
1088   number \# */
1089 @d length(A) (str_stop((A))-mp->str_start[(A)]) /* the number of characters in string \# */
1090
1091 @ The length of the current string is called |cur_length|.  If we decide that
1092 the current string is not needed, |flush_cur_string| resets |pool_ptr| so that
1093 |cur_length| becomes zero.
1094
1095 @d cur_length   (mp->pool_ptr - mp->str_start[mp->str_ptr])
1096 @d flush_cur_string   mp->pool_ptr=mp->str_start[mp->str_ptr]
1097
1098 @ Strings are created by appending character codes to |str_pool|.
1099 The |append_char| macro, defined here, does not check to see if the
1100 value of |pool_ptr| has gotten too high; this test is supposed to be
1101 made before |append_char| is used.
1102
1103 To test if there is room to append |l| more characters to |str_pool|,
1104 we shall write |str_room(l)|, which tries to make sure there is enough room
1105 by compacting the string pool if necessary.  If this does not work,
1106 |do_compaction| aborts \MP\ and gives an apologetic error message.
1107
1108 @d append_char(A)   /* put |ASCII_code| \# at the end of |str_pool| */
1109 { mp->str_pool[mp->pool_ptr]=(A); incr(mp->pool_ptr);
1110 }
1111 @d str_room(A)   /* make sure that the pool hasn't overflowed */
1112   { if ( mp->pool_ptr+(A) > mp->max_pool_ptr ) {
1113     if ( mp->pool_ptr+(A) > mp->pool_size ) mp_do_compaction(mp, (A));
1114     else mp->max_pool_ptr=mp->pool_ptr+(A); }
1115   }
1116
1117 @ The following routine is similar to |str_room(1)| but it uses the
1118 argument |mp->pool_size| to prevent |do_compaction| from aborting when
1119 string space is exhausted.
1120
1121 @<Declare the procedure called |unit_str_room|@>=
1122 void mp_unit_str_room (MP mp);
1123
1124 @ @c
1125 void mp_unit_str_room (MP mp) { 
1126   if ( mp->pool_ptr>=mp->pool_size ) mp_do_compaction(mp, mp->pool_size);
1127   if ( mp->pool_ptr>=mp->max_pool_ptr ) mp->max_pool_ptr=mp->pool_ptr+1;
1128 }
1129
1130 @ \MP's string expressions are implemented in a brute-force way: Every
1131 new string or substring that is needed is simply copied into the string pool.
1132 Space is eventually reclaimed by a procedure called |do_compaction| with
1133 the aid of a simple system system of reference counts.
1134 @^reference counts@>
1135
1136 The number of references to string number |s| will be |str_ref[s]|. The
1137 special value |str_ref[s]=max_str_ref=127| is used to denote an unknown
1138 positive number of references; such strings will never be recycled. If
1139 a string is ever referred to more than 126 times, simultaneously, we
1140 put it in this category. Hence a single byte suffices to store each |str_ref|.
1141
1142 @d max_str_ref 127 /* ``infinite'' number of references */
1143 @d add_str_ref(A) { if ( mp->str_ref[(A)]<max_str_ref ) incr(mp->str_ref[(A)]);
1144   }
1145
1146 @<Glob...@>=
1147 int *str_ref;
1148
1149 @ @<Allocate or initialize ...@>=
1150 mp->str_ref = xmalloc ((mp->max_strings+1),sizeof(int));
1151
1152 @ @<Dealloc variables@>=
1153 xfree(mp->str_ref);
1154
1155 @ Here's what we do when a string reference disappears:
1156
1157 @d delete_str_ref(A)  { 
1158     if ( mp->str_ref[(A)]<max_str_ref ) {
1159        if ( mp->str_ref[(A)]>1 ) decr(mp->str_ref[(A)]); 
1160        else mp_flush_string(mp, (A));
1161     }
1162   }
1163
1164 @<Declare the procedure called |flush_string|@>=
1165 void mp_flush_string (MP mp,str_number s) ;
1166
1167
1168 @ We can't flush the first set of static strings at all, so there 
1169 is no point in trying
1170
1171 @c
1172 void mp_flush_string (MP mp,str_number s) { 
1173   if (length(s)>1) {
1174     mp->pool_in_use=mp->pool_in_use-length(s);
1175     decr(mp->strs_in_use);
1176     if ( mp->next_str[s]!=mp->str_ptr ) {
1177       mp->str_ref[s]=0;
1178     } else { 
1179       mp->str_ptr=s;
1180       decr(mp->strs_used_up);
1181     }
1182     mp->pool_ptr=mp->str_start[mp->str_ptr];
1183   }
1184 }
1185
1186 @ C literals cannot be simply added, they need to be set so they can't
1187 be flushed.
1188
1189 @d intern(A) mp_intern(mp,(A))
1190
1191 @c
1192 str_number mp_intern (MP mp, char *s) {
1193   str_number r ;
1194   r = rts(s);
1195   mp->str_ref[r] = max_str_ref;
1196   return r;
1197 }
1198
1199 @ @<Declarations@>=
1200 str_number mp_intern (MP mp, char *s);
1201
1202
1203 @ Once a sequence of characters has been appended to |str_pool|, it
1204 officially becomes a string when the function |make_string| is called.
1205 This function returns the identification number of the new string as its
1206 value.
1207
1208 When getting the next unused string number from the linked list, we pretend
1209 that
1210 $$ \hbox{|max_str_ptr+1|, |max_str_ptr+2|, $\ldots$, |mp->max_strings|} $$
1211 are linked sequentially even though the |next_str| entries have not been
1212 initialized yet.  We never allow |str_ptr| to reach |mp->max_strings|;
1213 |do_compaction| is responsible for making sure of this.
1214
1215 @<Declarations@>=
1216 @<Declare the procedure called |do_compaction|@>;
1217 @<Declare the procedure called |unit_str_room|@>;
1218 str_number mp_make_string (MP mp);
1219
1220 @ @c 
1221 str_number mp_make_string (MP mp) { /* current string enters the pool */
1222   str_number s; /* the new string */
1223 RESTART: 
1224   s=mp->str_ptr;
1225   mp->str_ptr=mp->next_str[s];
1226   if ( mp->str_ptr>mp->max_str_ptr ) {
1227     if ( mp->str_ptr==mp->max_strings ) { 
1228       mp->str_ptr=s;
1229       mp_do_compaction(mp, 0);
1230       goto RESTART;
1231     } else {
1232 #ifdef DEBUG 
1233       if ( mp->strs_used_up!=mp->max_str_ptr ) mp_confusion(mp, "s");
1234 @:this can't happen s}{\quad \.s@>
1235 #endif
1236       mp->max_str_ptr=mp->str_ptr;
1237       mp->next_str[mp->str_ptr]=mp->max_str_ptr+1;
1238     }
1239   }
1240   mp->str_ref[s]=1;
1241   mp->str_start[mp->str_ptr]=mp->pool_ptr;
1242   incr(mp->strs_used_up);
1243   incr(mp->strs_in_use);
1244   mp->pool_in_use=mp->pool_in_use+length(s);
1245   if ( mp->pool_in_use>mp->max_pl_used ) 
1246     mp->max_pl_used=mp->pool_in_use;
1247   if ( mp->strs_in_use>mp->max_strs_used ) 
1248     mp->max_strs_used=mp->strs_in_use;
1249   return s;
1250 }
1251
1252 @ The most interesting string operation is string pool compaction.  The idea
1253 is to recover unused space in the |str_pool| array by recopying the strings
1254 to close the gaps created when some strings become unused.  All string
1255 numbers~$k$ where |str_ref[k]=0| are to be linked into the list of free string
1256 numbers after |str_ptr|.  If this fails to free enough pool space we issue an
1257 |overflow| error unless |needed=mp->pool_size|.  Calling |do_compaction|
1258 with |needed=mp->pool_size| supresses all overflow tests.
1259
1260 The compaction process starts with |last_fixed_str| because all lower numbered
1261 strings are permanently allocated with |max_str_ref| in their |str_ref| entries.
1262
1263 @<Glob...@>=
1264 str_number last_fixed_str; /* last permanently allocated string */
1265 str_number fixed_str_use; /* number of permanently allocated strings */
1266
1267 @ @<Declare the procedure called |do_compaction|@>=
1268 void mp_do_compaction (MP mp, pool_pointer needed) ;
1269
1270 @ @c
1271 void mp_do_compaction (MP mp, pool_pointer needed) {
1272   str_number str_use; /* a count of strings in use */
1273   str_number r,s,t; /* strings being manipulated */
1274   pool_pointer p,q; /* destination and source for copying string characters */
1275   @<Advance |last_fixed_str| as far as possible and set |str_use|@>;
1276   r=mp->last_fixed_str;
1277   s=mp->next_str[r];
1278   p=mp->str_start[s];
1279   while ( s!=mp->str_ptr ) { 
1280     while ( mp->str_ref[s]==0 ) {
1281       @<Advance |s| and add the old |s| to the list of free string numbers;
1282         then |break| if |s=str_ptr|@>;
1283     }
1284     r=s; s=mp->next_str[s];
1285     incr(str_use);
1286     @<Move string |r| back so that |str_start[r]=p|; make |p| the location
1287      after the end of the string@>;
1288   }
1289   @<Move the current string back so that it starts at |p|@>;
1290   if ( needed<mp->pool_size ) {
1291     @<Make sure that there is room for another string with |needed| characters@>;
1292   }
1293   @<Account for the compaction and make sure the statistics agree with the
1294      global versions@>;
1295   mp->strs_used_up=str_use;
1296 }
1297
1298 @ @<Advance |last_fixed_str| as far as possible and set |str_use|@>=
1299 t=mp->next_str[mp->last_fixed_str];
1300 while (t!=mp->str_ptr && mp->str_ref[t]==max_str_ref) {
1301   incr(mp->fixed_str_use);
1302   mp->last_fixed_str=t;
1303   t=mp->next_str[t];
1304 }
1305 str_use=mp->fixed_str_use
1306
1307 @ Because of the way |flush_string| has been written, it should never be
1308 necessary to |break| here.  The extra line of code seems worthwhile to
1309 preserve the generality of |do_compaction|.
1310
1311 @<Advance |s| and add the old |s| to the list of free string numbers;...@>=
1312 {
1313 t=s;
1314 s=mp->next_str[s];
1315 mp->next_str[r]=s;
1316 mp->next_str[t]=mp->next_str[mp->str_ptr];
1317 mp->next_str[mp->str_ptr]=t;
1318 if ( s==mp->str_ptr ) break;
1319 }
1320
1321 @ The string currently starts at |str_start[r]| and ends just before
1322 |str_start[s]|.  We don't change |str_start[s]| because it might be needed
1323 to locate the next string.
1324
1325 @<Move string |r| back so that |str_start[r]=p|; make |p| the location...@>=
1326 q=mp->str_start[r];
1327 mp->str_start[r]=p;
1328 while ( q<mp->str_start[s] ) { 
1329   mp->str_pool[p]=mp->str_pool[q];
1330   incr(p); incr(q);
1331 }
1332
1333 @ Pointers |str_start[str_ptr]| and |pool_ptr| have not been updated.  When
1334 we do this, anything between them should be moved.
1335
1336 @ @<Move the current string back so that it starts at |p|@>=
1337 q=mp->str_start[mp->str_ptr];
1338 mp->str_start[mp->str_ptr]=p;
1339 while ( q<mp->pool_ptr ) { 
1340   mp->str_pool[p]=mp->str_pool[q];
1341   incr(p); incr(q);
1342 }
1343 mp->pool_ptr=p
1344
1345 @ We must remember that |str_ptr| is not allowed to reach |mp->max_strings|.
1346
1347 @<Make sure that there is room for another string with |needed| char...@>=
1348 if ( str_use>=mp->max_strings-1 )
1349   mp_reallocate_strings (mp,str_use);
1350 if ( mp->pool_ptr+needed>mp->max_pool_ptr ) {
1351   mp_reallocate_pool(mp, mp->pool_ptr+needed);
1352   mp->max_pool_ptr=mp->pool_ptr+needed;
1353 }
1354
1355 @ @<Declarations@>=
1356 void mp_reallocate_strings (MP mp, str_number str_use) ;
1357 void mp_reallocate_pool(MP mp, pool_pointer needed) ;
1358
1359 @ @c 
1360 void mp_reallocate_strings (MP mp, str_number str_use) { 
1361   while ( str_use>=mp->max_strings-1 ) {
1362     int l = mp->max_strings + (mp->max_strings>>2);
1363     XREALLOC (mp->str_ref,   l, int);
1364     XREALLOC (mp->str_start, l, pool_pointer);
1365     XREALLOC (mp->next_str,  l, str_number);
1366     mp->max_strings = l;
1367   }
1368 }
1369 void mp_reallocate_pool(MP mp, pool_pointer needed) {
1370   while ( needed>mp->pool_size ) {
1371     int l = mp->pool_size + (mp->pool_size>>2);
1372         XREALLOC (mp->str_pool, l, ASCII_code);
1373     mp->pool_size = l;
1374   }
1375 }
1376
1377 @ @<Account for the compaction and make sure the statistics agree with...@>=
1378 if ( (mp->str_start[mp->str_ptr]!=mp->pool_in_use)||(str_use!=mp->strs_in_use) )
1379   mp_confusion(mp, "string");
1380 @:this can't happen string}{\quad string@>
1381 incr(mp->pact_count);
1382 mp->pact_chars=mp->pact_chars+mp->pool_ptr-str_stop(mp->last_fixed_str);
1383 mp->pact_strs=mp->pact_strs+str_use-mp->fixed_str_use;
1384 #ifdef DEBUG
1385 s=mp->str_ptr; t=str_use;
1386 while ( s<=mp->max_str_ptr ){
1387   if ( t>mp->max_str_ptr ) mp_confusion(mp, "\"");
1388   incr(t); s=mp->next_str[s];
1389 };
1390 if ( t<=mp->max_str_ptr ) mp_confusion(mp, "\"");
1391 #endif
1392
1393 @ A few more global variables are needed to keep track of statistics when
1394 |stat| $\ldots$ |tats| blocks are not commented out.
1395
1396 @<Glob...@>=
1397 integer pact_count; /* number of string pool compactions so far */
1398 integer pact_chars; /* total number of characters moved during compactions */
1399 integer pact_strs; /* total number of strings moved during compactions */
1400
1401 @ @<Initialize compaction statistics@>=
1402 mp->pact_count=0;
1403 mp->pact_chars=0;
1404 mp->pact_strs=0;
1405
1406 @ The following subroutine compares string |s| with another string of the
1407 same length that appears in |buffer| starting at position |k|;
1408 the result is |true| if and only if the strings are equal.
1409
1410 @c 
1411 boolean mp_str_eq_buf (MP mp,str_number s, integer k) {
1412   /* test equality of strings */
1413   pool_pointer j; /* running index */
1414   j=mp->str_start[s];
1415   while ( j<str_stop(s) ) { 
1416     if ( mp->str_pool[j++]!=mp->buffer[k++] ) 
1417       return false;
1418   }
1419   return true;
1420 }
1421
1422 @ Here is a similar routine, but it compares two strings in the string pool,
1423 and it does not assume that they have the same length. If the first string
1424 is lexicographically greater than, less than, or equal to the second,
1425 the result is respectively positive, negative, or zero.
1426
1427 @c 
1428 integer mp_str_vs_str (MP mp, str_number s, str_number t) {
1429   /* test equality of strings */
1430   pool_pointer j,k; /* running indices */
1431   integer ls,lt; /* lengths */
1432   integer l; /* length remaining to test */
1433   ls=length(s); lt=length(t);
1434   if ( ls<=lt ) l=ls; else l=lt;
1435   j=mp->str_start[s]; k=mp->str_start[t];
1436   while ( l-->0 ) { 
1437     if ( mp->str_pool[j]!=mp->str_pool[k] ) {
1438        return (mp->str_pool[j]-mp->str_pool[k]); 
1439     }
1440     incr(j); incr(k);
1441   }
1442   return (ls-lt);
1443 }
1444
1445 @ The initial values of |str_pool|, |str_start|, |pool_ptr|,
1446 and |str_ptr| are computed by the \.{INIMP} program, based in part
1447 on the information that \.{WEB} has output while processing \MP.
1448 @.INIMP@>
1449 @^string pool@>
1450
1451 @c 
1452 void mp_get_strings_started (MP mp) { 
1453   /* initializes the string pool,
1454     but returns |false| if something goes wrong */
1455   int k; /* small indices or counters */
1456   str_number g; /* a new string */
1457   mp->pool_ptr=0; mp->str_ptr=0; mp->max_pool_ptr=0; mp->max_str_ptr=0;
1458   mp->str_start[0]=0;
1459   mp->next_str[0]=1;
1460   mp->pool_in_use=0; mp->strs_in_use=0;
1461   mp->max_pl_used=0; mp->max_strs_used=0;
1462   @<Initialize compaction statistics@>;
1463   mp->strs_used_up=0;
1464   @<Make the first 256 strings@>;
1465   g=mp_make_string(mp); /* string 256 == "" */
1466   mp->str_ref[g]=max_str_ref;
1467   mp->last_fixed_str=mp->str_ptr-1;
1468   mp->fixed_str_use=mp->str_ptr;
1469   return;
1470 }
1471
1472 @ @<Declarations@>=
1473 void mp_get_strings_started (MP mp);
1474
1475 @ The first 256 strings will consist of a single character only.
1476
1477 @<Make the first 256...@>=
1478 for (k=0;k<=255;k++) { 
1479   append_char(k);
1480   g=mp_make_string(mp); 
1481   mp->str_ref[g]=max_str_ref;
1482 }
1483
1484 @ The first 128 strings will contain 95 standard ASCII characters, and the
1485 other 33 characters will be printed in three-symbol form like `\.{\^\^A}'
1486 unless a system-dependent change is made here. Installations that have
1487 an extended character set, where for example |xchr[032]=@t\.{'^^Z'}@>|,
1488 would like string 032 to be printed as the single character 032 instead
1489 of the three characters 0136, 0136, 0132 (\.{\^\^Z}). On the other hand,
1490 even people with an extended character set will want to represent string
1491 015 by \.{\^\^M}, since 015 is ASCII's ``carriage return'' code; the idea is
1492 to produce visible strings instead of tabs or line-feeds or carriage-returns
1493 or bell-rings or characters that are treated anomalously in text files.
1494
1495 Unprintable characters of codes 128--255 are, similarly, rendered
1496 \.{\^\^80}--\.{\^\^ff}.
1497
1498 The boolean expression defined here should be |true| unless \MP\ internal
1499 code number~|k| corresponds to a non-troublesome visible symbol in the
1500 local character set.
1501 If character |k| cannot be printed, and |k<0200|, then character |k+0100| or
1502 |k-0100| must be printable; moreover, ASCII codes |[060..071, 0141..0146]|
1503 must be printable.
1504 @^character set dependencies@>
1505 @^system dependencies@>
1506
1507 @<Character |k| cannot be printed@>=
1508   (k<' ')||(k>'~')
1509
1510 @* \[5] On-line and off-line printing.
1511 Messages that are sent to a user's terminal and to the transcript-log file
1512 are produced by several `|print|' procedures. These procedures will
1513 direct their output to a variety of places, based on the setting of
1514 the global variable |selector|, which has the following possible
1515 values:
1516
1517 \yskip
1518 \hang |term_and_log|, the normal setting, prints on the terminal and on the
1519   transcript file.
1520
1521 \hang |log_only|, prints only on the transcript file.
1522
1523 \hang |term_only|, prints only on the terminal.
1524
1525 \hang |no_print|, doesn't print at all. This is used only in rare cases
1526   before the transcript file is open.
1527
1528 \hang |ps_file_only| prints only on the \ps\ output file.
1529
1530 \hang |pseudo|, puts output into a cyclic buffer that is used
1531   by the |show_context| routine; when we get to that routine we shall discuss
1532   the reasoning behind this curious mode.
1533
1534 \hang |new_string|, appends the output to the current string in the
1535   string pool.
1536
1537 \hang |>=write_file| prints on one of the files used for the \&{write}
1538 @:write_}{\&{write} primitive@>
1539   command.
1540
1541 \yskip
1542 \noindent The symbolic names `|term_and_log|', etc., have been assigned
1543 numeric codes that satisfy the convenient relations |no_print+1=term_only|,
1544 |no_print+2=log_only|, |term_only+2=log_only+1=term_and_log|.  These
1545 relations are not used when |selector| could be |pseudo|, |new_string|,
1546 or |ps_file_only|.  We need not check for unprintable characters when
1547 |selector<pseudo|.
1548
1549 Four additional global variables, |tally|, |term_offset|, |file_offset|,
1550 and |ps_offset| record the number of characters that have been printed
1551 since they were most recently cleared to zero. We use |tally| to record
1552 the length of (possibly very long) stretches of printing; |term_offset|,
1553 |file_offset|, and |ps_offset|, on the other hand, keep track of how many
1554 characters have appeared so far on the current line that has been output
1555 to the terminal, the transcript file, or the \ps\ output file, respectively.
1556
1557 @d new_string 0 /* printing is deflected to the string pool */
1558 @d ps_file_only 1 /* printing goes to the \ps\ output file */
1559 @d pseudo 2 /* special |selector| setting for |show_context| */
1560 @d no_print 3 /* |selector| setting that makes data disappear */
1561 @d term_only 4 /* printing is destined for the terminal only */
1562 @d log_only 5 /* printing is destined for the transcript file only */
1563 @d term_and_log 6 /* normal |selector| setting */
1564 @d write_file 7 /* first write file selector */
1565
1566 @<Glob...@>=
1567 FILE * log_file; /* transcript of \MP\ session */
1568 FILE * ps_file; /* the generic font output goes here */
1569 unsigned int selector; /* where to print a message */
1570 unsigned char dig[23]; /* digits in a number being output */
1571 integer tally; /* the number of characters recently printed */
1572 unsigned int term_offset;
1573   /* the number of characters on the current terminal line */
1574 unsigned int file_offset;
1575   /* the number of characters on the current file line */
1576 integer ps_offset;
1577   /* the number of characters on the current \ps\ file line */
1578 ASCII_code *trick_buf; /* circular buffer for pseudoprinting */
1579 integer trick_count; /* threshold for pseudoprinting, explained later */
1580 integer first_count; /* another variable for pseudoprinting */
1581
1582 @ @<Allocate or initialize ...@>=
1583 memset(mp->dig,0,23);
1584 mp->trick_buf = xmalloc((mp->error_line+1),sizeof(ASCII_code));
1585
1586 @ @<Dealloc variables@>=
1587 xfree(mp->trick_buf);
1588
1589 @ @<Initialize the output routines@>=
1590 mp->selector=term_only; mp->tally=0; mp->term_offset=0; mp->file_offset=0; mp->ps_offset=0;
1591
1592 @ Macro abbreviations for output to the terminal and to the log file are
1593 defined here for convenience. Some systems need special conventions
1594 for terminal output, and it is possible to adhere to those conventions
1595 by changing |wterm|, |wterm_ln|, and |wterm_cr| here.
1596 @^system dependencies@>
1597
1598 @d wterm(A)    fprintf(mp->term_out,"%s",(A))
1599 @d wterm_chr(A)fprintf(mp->term_out,"%c",(A))
1600 @d wterm_ln(A) fprintf(mp->term_out,"\n%s",(A))
1601 @d wterm_cr    fprintf(mp->term_out,"\n")
1602 @d wlog(A)     fprintf(mp->log_file,"%s",(A))
1603 @d wlog_chr(A) fprintf(mp->log_file,"%c",(A))
1604 @d wlog_ln(A)  fprintf(mp->log_file,"\n%s",(A))
1605 @d wlog_cr     fprintf(mp->log_file, "\n")
1606 @d wps(A)      fprintf(mp->ps_file,"%s",(A))
1607 @d wps_chr(A)  fprintf(mp->ps_file,"%c",(A))
1608 @d wps_ln(A)   fprintf(mp->ps_file,,"\n%s",(A))
1609 @d wps_cr      fprintf(mp->ps_file,"\n")
1610
1611 @ To end a line of text output, we call |print_ln|.  Cases |0..max_write_files|
1612 use an array |wr_file| that will be declared later.
1613
1614 @d mp_print_text(A) mp_print_str(mp,text((A)))
1615
1616 @<Internal ...@>=
1617 void mp_print_ln (MP mp);
1618 void mp_print_visible_char (MP mp, ASCII_code s); 
1619 void mp_print_char (MP mp, ASCII_code k);
1620 void mp_print (MP mp, char *s);
1621 void mp_print_str (MP mp, str_number s);
1622 void mp_print_nl (MP mp, char *s);
1623 void mp_print_two (MP mp,scaled x, scaled y) ;
1624 void mp_print_scaled (MP mp,scaled s);
1625
1626 @ @<Basic print...@>=
1627 void mp_print_ln (MP mp) { /* prints an end-of-line */
1628  switch (mp->selector) {
1629   case term_and_log: 
1630     wterm_cr; wlog_cr;
1631     mp->term_offset=0;  mp->file_offset=0;
1632     break;
1633   case log_only: 
1634     wlog_cr; mp->file_offset=0;
1635     break;
1636   case term_only: 
1637     wterm_cr; mp->term_offset=0;
1638     break;
1639   case ps_file_only: 
1640     wps_cr; mp->ps_offset=0;
1641     break;
1642   case no_print:
1643   case pseudo: 
1644   case new_string: 
1645     break;
1646   default: 
1647     fprintf(mp->wr_file[(mp->selector-write_file)],"\n");
1648   }
1649 } /* note that |tally| is not affected */
1650
1651 @ The |print_visible_char| procedure sends one character to the desired
1652 destination, using the |xchr| array to map it into an external character
1653 compatible with |input_ln|.  (It assumes that it is always called with
1654 a visible ASCII character.)  All printing comes through |print_ln| or
1655 |print_char|, which ultimately calls |print_visible_char|, hence these
1656 routines are the ones that limit lines to at most |max_print_line| characters.
1657 But we must make an exception for the \ps\ output file since it is not safe
1658 to cut up lines arbitrarily in \ps.
1659
1660 Procedure |unit_str_room| needs to be declared |forward| here because it calls
1661 |do_compaction| and |do_compaction| can call the error routines.  Actually,
1662 |unit_str_room| avoids |overflow| errors but it can call |confusion|.
1663
1664 @<Basic printing...@>=
1665 void mp_print_visible_char (MP mp, ASCII_code s) { /* prints a single character */
1666   switch (mp->selector) {
1667   case term_and_log: 
1668     wterm_chr(xchr(s)); wlog_chr(xchr(s));
1669     incr(mp->term_offset); incr(mp->file_offset);
1670     if ( mp->term_offset==(unsigned)mp->max_print_line ) { 
1671        wterm_cr; mp->term_offset=0;
1672     };
1673     if ( mp->file_offset==(unsigned)mp->max_print_line ) { 
1674        wlog_cr; mp->file_offset=0;
1675     };
1676     break;
1677   case log_only: 
1678     wlog_chr(xchr(s)); incr(mp->file_offset);
1679     if ( mp->file_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1680     break;
1681   case term_only: 
1682     wterm_chr(xchr(s)); incr(mp->term_offset);
1683     if ( mp->term_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1684     break;
1685   case ps_file_only: 
1686     if ( s==13 ) {
1687       wps_cr; mp->ps_offset=0;
1688     } else {
1689       wps_chr(xchr(s)); incr(mp->ps_offset);
1690     };
1691     break;
1692   case no_print: 
1693     break;
1694   case pseudo: 
1695     if ( mp->tally<mp->trick_count ) 
1696       mp->trick_buf[mp->tally % mp->error_line]=s;
1697     break;
1698   case new_string: 
1699     if ( mp->pool_ptr>=mp->max_pool_ptr ) { 
1700       mp_unit_str_room(mp);
1701       if ( mp->pool_ptr>=mp->pool_size ) 
1702         goto DONE; /* drop characters if string space is full */
1703     };
1704     append_char(s);
1705     break;
1706   default:
1707     fprintf(mp->wr_file[(mp->selector-write_file)],"%c",xchr(s));
1708   }
1709 DONE:
1710   incr(mp->tally);
1711 }
1712
1713 @ The |print_char| procedure sends one character to the desired destination.
1714 File names and string expressions might contain |ASCII_code| values that
1715 can't be printed using |print_visible_char|.  These characters will be
1716 printed in three- or four-symbol form like `\.{\^\^A}' or `\.{\^\^e4}'.
1717 (This procedure assumes that it is safe to bypass all checks for unprintable
1718 characters when |selector| is in the range |0..max_write_files-1| or when
1719 |selector=ps_file_only|.  In the former case the user might want to write
1720 unprintable characters, and in the latter case the \ps\ printing routines
1721 check their arguments themselves before calling |print_char| or |print|.)
1722
1723 @d print_lc_hex(A) do { l=(A);
1724     mp_print_visible_char(mp, (l<10 ? l+'0' : l-10+'a'));
1725   } while (0)
1726
1727 @<Basic printing...@>=
1728 void mp_print_char (MP mp, ASCII_code k) { /* prints a single character */
1729   int l; /* small index or counter */
1730   if ( mp->selector<pseudo || mp->selector>=write_file) {
1731     mp_print_visible_char(mp, k);
1732   } else if ( @<Character |k| cannot be printed@> ) { 
1733     mp_print(mp, "^^"); 
1734     if ( k<0100 ) { 
1735       mp_print_visible_char(mp, k+0100); 
1736     } else if ( k<0200 ) { 
1737       mp_print_visible_char(mp, k-0100); 
1738     } else { 
1739       print_lc_hex(k / 16);  
1740       print_lc_hex(k % 16); 
1741     }
1742   } else {
1743     mp_print_visible_char(mp, k);
1744   }
1745 };
1746
1747 @ An entire string is output by calling |print|. Note that if we are outputting
1748 the single standard ASCII character \.c, we could call |print("c")|, since
1749 |"c"=99| is the number of a single-character string, as explained above. But
1750 |print_char("c")| is quicker, so \MP\ goes directly to the |print_char|
1751 routine when it knows that this is safe. (The present implementation
1752 assumes that it is always safe to print a visible ASCII character.)
1753 @^system dependencies@>
1754
1755 @<Basic print...@>=
1756 void mp_do_print (MP mp, char *ss, unsigned int len) { /* prints string |s| */
1757   unsigned int j = 0;
1758   while ( j<len ){ 
1759     mp_print_char(mp, ss[j]); incr(j);
1760   }
1761 }
1762
1763
1764 @<Basic print...@>=
1765 void mp_print (MP mp, char *ss) {
1766   mp_do_print(mp, ss, strlen(ss));
1767 }
1768 void mp_print_str (MP mp, str_number s) {
1769   pool_pointer j; /* current character code position */
1770   if ( (s<0)||(s>mp->max_str_ptr) ) {
1771      mp_do_print(mp,"???",3); /* this can't happen */
1772 @.???@>
1773   }
1774   j=mp->str_start[s];
1775   mp_do_print(mp, (char *)(mp->str_pool+j), (str_stop(s)-j));
1776 }
1777
1778
1779 @ Here is the very first thing that \MP\ prints: a headline that identifies
1780 the version number and base name. The |term_offset| variable is temporarily
1781 incorrect, but the discrepancy is not serious since we assume that the banner
1782 and mem identifier together will occupy at most |max_print_line|
1783 character positions.
1784
1785 @<Initialize the output...@>=
1786 wterm (banner);
1787 wterm (version_string);
1788 if (mp->mem_ident!=NULL) 
1789   mp_print(mp,mp->mem_ident); 
1790 mp_print_ln(mp);
1791 update_terminal;
1792
1793 @ The procedure |print_nl| is like |print|, but it makes sure that the
1794 string appears at the beginning of a new line.
1795
1796 @<Basic print...@>=
1797 void mp_print_nl (MP mp, char *s) { /* prints string |s| at beginning of line */
1798   switch(mp->selector) {
1799   case term_and_log: 
1800     if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_ln(mp);
1801     break;
1802   case log_only: 
1803     if ( mp->file_offset>0 ) mp_print_ln(mp);
1804     break;
1805   case term_only: 
1806     if ( mp->term_offset>0 ) mp_print_ln(mp);
1807     break;
1808   case ps_file_only: 
1809     if ( mp->ps_offset>0 ) mp_print_ln(mp);
1810     break;
1811   case no_print:
1812   case pseudo:
1813   case new_string: 
1814         break;
1815   } /* there are no other cases */
1816   mp_print(mp, s);
1817 }
1818
1819 @ An array of digits in the range |0..9| is printed by |print_the_digs|.
1820
1821 @<Basic print...@>=
1822 void mp_print_the_digs (MP mp, eight_bits k) {
1823   /* prints |dig[k-1]|$\,\ldots\,$|dig[0]| */
1824   while ( k>0 ){ 
1825     decr(k); mp_print_char(mp, '0'+mp->dig[k]);
1826   }
1827 };
1828
1829 @ The following procedure, which prints out the decimal representation of a
1830 given integer |n|, has been written carefully so that it works properly
1831 if |n=0| or if |(-n)| would cause overflow. It does not apply |mod| or |div|
1832 to negative arguments, since such operations are not implemented consistently
1833 by all \PASCAL\ compilers.
1834
1835 @<Basic print...@>=
1836 void mp_print_int (MP mp,integer n) { /* prints an integer in decimal form */
1837   integer m; /* used to negate |n| in possibly dangerous cases */
1838   int k = 0; /* index to current digit; we assume that $|n|<10^{23}$ */
1839   if ( n<0 ) { 
1840     mp_print_char(mp, '-');
1841     if ( n>-100000000 ) {
1842           negate(n);
1843     } else  { 
1844           m=-1-n; n=m / 10; m=(m % 10)+1; k=1;
1845       if ( m<10 ) {
1846         mp->dig[0]=m;
1847       } else { 
1848         mp->dig[0]=0; incr(n);
1849       }
1850     }
1851   }
1852   do {  
1853     mp->dig[k]=n % 10; n=n / 10; incr(k);
1854   } while (n!=0);
1855   mp_print_the_digs(mp, k);
1856 };
1857
1858 @ @<Internal ...@>=
1859 void mp_print_int (MP mp,integer n);
1860
1861 @ \MP\ also makes use of a trivial procedure to print two digits. The
1862 following subroutine is usually called with a parameter in the range |0<=n<=99|.
1863
1864 @c 
1865 void mp_print_dd (MP mp,integer n) { /* prints two least significant digits */
1866   n=abs(n) % 100; 
1867   mp_print_char(mp, '0'+(n / 10));
1868   mp_print_char(mp, '0'+(n % 10));
1869 }
1870
1871
1872 @ @<Internal ...@>=
1873 void mp_print_dd (MP mp,integer n);
1874
1875 @ Here is a procedure that asks the user to type a line of input,
1876 assuming that the |selector| setting is either |term_only| or |term_and_log|.
1877 The input is placed into locations |first| through |last-1| of the
1878 |buffer| array, and echoed on the transcript file if appropriate.
1879
1880 This procedure is never called when |interaction<mp_scroll_mode|.
1881
1882 @d prompt_input(A) do { 
1883     wake_up_terminal; mp_print(mp, (A)); mp_term_input(mp);
1884   } while (0) /* prints a string and gets a line of input */
1885
1886 @c 
1887 void mp_term_input (MP mp) { /* gets a line from the terminal */
1888   size_t k; /* index into |buffer| */
1889   update_terminal; /* Now the user sees the prompt for sure */
1890   if (!mp_input_ln(mp, mp->term_in,true)) 
1891     mp_fatal_error(mp, "End of file on the terminal!");
1892 @.End of file on the terminal@>
1893   mp->term_offset=0; /* the user's line ended with \<\rm return> */
1894   decr(mp->selector); /* prepare to echo the input */
1895   if ( mp->last!=mp->first ) {
1896     for (k=mp->first;k<=mp->last-1;k++) {
1897       mp_print_char(mp, mp->buffer[k]);
1898     }
1899   }
1900   mp_print_ln(mp); 
1901   mp->buffer[mp->last]='%'; 
1902   incr(mp->selector); /* restore previous status */
1903 };
1904
1905 @* \[6] Reporting errors.
1906 When something anomalous is detected, \MP\ typically does something like this:
1907 $$\vbox{\halign{#\hfil\cr
1908 |print_err("Something anomalous has been detected");|\cr
1909 |help3("This is the first line of my offer to help.")|\cr
1910 |("This is the second line. I'm trying to")|\cr
1911 |("explain the best way for you to proceed.");|\cr
1912 |error;|\cr}}$$
1913 A two-line help message would be given using |help2|, etc.; these informal
1914 helps should use simple vocabulary that complements the words used in the
1915 official error message that was printed. (Outside the U.S.A., the help
1916 messages should preferably be translated into the local vernacular. Each
1917 line of help is at most 60 characters long, in the present implementation,
1918 so that |max_print_line| will not be exceeded.)
1919
1920 The |print_err| procedure supplies a `\.!' before the official message,
1921 and makes sure that the terminal is awake if a stop is going to occur.
1922 The |error| procedure supplies a `\..' after the official message, then it
1923 shows the location of the error; and if |interaction=error_stop_mode|,
1924 it also enters into a dialog with the user, during which time the help
1925 message may be printed.
1926 @^system dependencies@>
1927
1928 @ The global variable |interaction| has four settings, representing increasing
1929 amounts of user interaction:
1930
1931 @<Exported types@>=
1932 enum mp_interaction_mode { 
1933  mp_unspecified_mode=0, /* extra value for command-line switch */
1934  mp_batch_mode, /* omits all stops and omits terminal output */
1935  mp_nonstop_mode, /* omits all stops */
1936  mp_scroll_mode, /* omits error stops */
1937  mp_error_stop_mode, /* stops at every opportunity to interact */
1938 };
1939
1940 @ @<Glob...@>=
1941 int interaction; /* current level of interaction */
1942
1943 @ @<Option variables@>=
1944 int interaction; /* current level of interaction */
1945
1946 @ Set it here so it can be overwritten by the commandline
1947
1948 @<Allocate or initialize ...@>=
1949 mp->interaction=opt->interaction;
1950 if (mp->interaction==mp_unspecified_mode || mp->interaction>mp_error_stop_mode) 
1951   mp->interaction=mp_error_stop_mode;
1952 if (mp->interaction<mp_unspecified_mode) 
1953   mp->interaction=mp_batch_mode;
1954
1955
1956
1957 @d print_err(A) mp_print_err(mp,(A))
1958
1959 @<Internal ...@>=
1960 void mp_print_err(MP mp, char * A);
1961
1962 @ @c
1963 void mp_print_err(MP mp, char * A) { 
1964   if ( mp->interaction==mp_error_stop_mode ) 
1965     wake_up_terminal;
1966   mp_print_nl(mp, "! "); 
1967   mp_print(mp, A);
1968 @.!\relax@>
1969 }
1970
1971
1972 @ \MP\ is careful not to call |error| when the print |selector| setting
1973 might be unusual. The only possible values of |selector| at the time of
1974 error messages are
1975
1976 \yskip\hang|no_print| (when |interaction=mp_batch_mode|
1977   and |log_file| not yet open);
1978
1979 \hang|term_only| (when |interaction>mp_batch_mode| and |log_file| not yet open);
1980
1981 \hang|log_only| (when |interaction=mp_batch_mode| and |log_file| is open);
1982
1983 \hang|term_and_log| (when |interaction>mp_batch_mode| and |log_file| is open).
1984
1985 @<Initialize the print |selector| based on |interaction|@>=
1986 if ( mp->interaction==mp_batch_mode ) mp->selector=no_print; else mp->selector=term_only
1987
1988 @ A global variable |deletions_allowed| is set |false| if the |get_next|
1989 routine is active when |error| is called; this ensures that |get_next|
1990 will never be called recursively.
1991 @^recursion@>
1992
1993 The global variable |history| records the worst level of error that
1994 has been detected. It has four possible values: |spotless|, |warning_issued|,
1995 |error_message_issued|, and |fatal_error_stop|.
1996
1997 Another global variable, |error_count|, is increased by one when an
1998 |error| occurs without an interactive dialog, and it is reset to zero at
1999 the end of every statement.  If |error_count| reaches 100, \MP\ decides
2000 that there is no point in continuing further.
2001
2002 @<Types...@>=
2003 enum mp_history_states {
2004   mp_spotless=0, /* |history| value when nothing has been amiss yet */
2005   mp_warning_issued, /* |history| value when |begin_diagnostic| has been called */
2006   mp_error_message_issued, /* |history| value when |error| has been called */
2007   mp_fatal_error_stop, /* |history| value when termination was premature */
2008 };
2009
2010 @ @<Glob...@>=
2011 boolean deletions_allowed; /* is it safe for |error| to call |get_next|? */
2012 int history; /* has the source input been clean so far? */
2013 int error_count; /* the number of scrolled errors since the last statement ended */
2014
2015 @ The value of |history| is initially |fatal_error_stop|, but it will
2016 be changed to |spotless| if \MP\ survives the initialization process.
2017
2018 @<Allocate or ...@>=
2019 mp->deletions_allowed=true; mp->error_count=0; /* |history| is initialized elsewhere */
2020
2021 @ Since errors can be detected almost anywhere in \MP, we want to declare the
2022 error procedures near the beginning of the program. But the error procedures
2023 in turn use some other procedures, which need to be declared |forward|
2024 before we get to |error| itself.
2025
2026 It is possible for |error| to be called recursively if some error arises
2027 when |get_next| is being used to delete a token, and/or if some fatal error
2028 occurs while \MP\ is trying to fix a non-fatal one. But such recursion
2029 @^recursion@>
2030 is never more than two levels deep.
2031
2032 @<Declarations@>=
2033 void mp_get_next (MP mp);
2034 void mp_term_input (MP mp);
2035 void mp_show_context (MP mp);
2036 void mp_begin_file_reading (MP mp);
2037 void mp_open_log_file (MP mp);
2038 void mp_clear_for_error_prompt (MP mp);
2039 void mp_debug_help (MP mp);
2040 @<Declare the procedure called |flush_string|@>
2041
2042 @ @<Internal ...@>=
2043 void mp_normalize_selector (MP mp);
2044
2045 @ Individual lines of help are recorded in the array |help_line|, which
2046 contains entries in positions |0..(help_ptr-1)|. They should be printed
2047 in reverse order, i.e., with |help_line[0]| appearing last.
2048
2049 @d hlp1(A) mp->help_line[0]=(A); }
2050 @d hlp2(A) mp->help_line[1]=(A); hlp1
2051 @d hlp3(A) mp->help_line[2]=(A); hlp2
2052 @d hlp4(A) mp->help_line[3]=(A); hlp3
2053 @d hlp5(A) mp->help_line[4]=(A); hlp4
2054 @d hlp6(A) mp->help_line[5]=(A); hlp5
2055 @d help0 mp->help_ptr=0 /* sometimes there might be no help */
2056 @d help1  { mp->help_ptr=1; hlp1 /* use this with one help line */
2057 @d help2  { mp->help_ptr=2; hlp2 /* use this with two help lines */
2058 @d help3  { mp->help_ptr=3; hlp3 /* use this with three help lines */
2059 @d help4  { mp->help_ptr=4; hlp4 /* use this with four help lines */
2060 @d help5  { mp->help_ptr=5; hlp5 /* use this with five help lines */
2061 @d help6  { mp->help_ptr=6; hlp6 /* use this with six help lines */
2062
2063 @<Glob...@>=
2064 char * help_line[6]; /* helps for the next |error| */
2065 unsigned int help_ptr; /* the number of help lines present */
2066 boolean use_err_help; /* should the |err_help| string be shown? */
2067 str_number err_help; /* a string set up by \&{errhelp} */
2068 str_number filename_template; /* a string set up by \&{filenametemplate} */
2069
2070 @ @<Allocate or ...@>=
2071 mp->help_ptr=0; mp->use_err_help=false; mp->err_help=0; mp->filename_template=0;
2072
2073 @ The |jump_out| procedure just cuts across all active procedure levels and
2074 goes to |end_of_MP|. This is the only nonlocal |goto| statement in the
2075 whole program. It is used when there is no recovery from a particular error.
2076
2077 The program uses a |jump_buf| to handle this, this is initialized at three
2078 spots: the start of |mp_new|, the start of |mp_initialize|, and the start 
2079 of |mp_run|. Those are the only library enty points.
2080
2081 @^system dependencies@>
2082
2083 @<Glob...@>=
2084 jmp_buf jump_buf;
2085
2086 @ @<Install and test the non-local jump buffer@>=
2087 if (setjmp(mp->jump_buf) != 0) return mp->history;
2088
2089 @ @<Setup the non-local jump buffer in |mp_new|@>=
2090 if (setjmp(mp->jump_buf) != 0) return NULL;
2091
2092 @ If |mp->internal| is zero, then a crash occured during initialization,
2093 and it is not safe to run |mp_close_files_and_terminate|.
2094
2095 @<Error hand...@>=
2096 void mp_jump_out (MP mp) { 
2097   if(mp->internal!=NULL)
2098     mp_close_files_and_terminate(mp);
2099   longjmp(mp->jump_buf,1);
2100 }
2101
2102 @ Here now is the general |error| routine.
2103
2104 @<Error hand...@>=
2105 void mp_error (MP mp) { /* completes the job of error reporting */
2106   ASCII_code c; /* what the user types */
2107   integer s1,s2,s3; /* used to save global variables when deleting tokens */
2108   pool_pointer j; /* character position being printed */
2109   if ( mp->history<mp_error_message_issued ) mp->history=mp_error_message_issued;
2110   mp_print_char(mp, '.'); mp_show_context(mp);
2111   if ( mp->interaction==mp_error_stop_mode ) {
2112     @<Get user's advice and |return|@>;
2113   }
2114   incr(mp->error_count);
2115   if ( mp->error_count==100 ) { 
2116     mp_print_nl(mp,"(That makes 100 errors; please try again.)");
2117 @.That makes 100 errors...@>
2118     mp->history=mp_fatal_error_stop; mp_jump_out(mp);
2119   }
2120   @<Put help message on the transcript file@>;
2121 }
2122 void mp_warn (MP mp, char *msg) {
2123   int saved_selector = mp->selector;
2124   mp_normalize_selector(mp);
2125   mp_print_nl(mp,"Warning: ");
2126   mp_print(mp,msg);
2127   mp->selector = saved_selector;
2128 }
2129
2130 @ @<Exported function ...@>=
2131 void mp_error (MP mp);
2132 void mp_warn (MP mp, char *msg);
2133
2134
2135 @ @<Get user's advice...@>=
2136 while (1) { 
2137 CONTINUE:
2138   mp_clear_for_error_prompt(mp); prompt_input("? ");
2139 @.?\relax@>
2140   if ( mp->last==mp->first ) return;
2141   c=mp->buffer[mp->first];
2142   if ( c>='a' ) c=c+'A'-'a'; /* convert to uppercase */
2143   @<Interpret code |c| and |return| if done@>;
2144 }
2145
2146 @ It is desirable to provide an `\.E' option here that gives the user
2147 an easy way to return from \MP\ to the system editor, with the offending
2148 line ready to be edited. But such an extension requires some system
2149 wizardry, so the present implementation simply types out the name of the
2150 file that should be
2151 edited and the relevant line number.
2152 @^system dependencies@>
2153
2154 @<Exported types@>=
2155 typedef void (*mp_run_editor_command)(MP, char *, int);
2156
2157 @ @<Glob...@>=
2158 mp_run_editor_command run_editor;
2159
2160 @ @<Option variables@>=
2161 mp_run_editor_command run_editor;
2162
2163 @ @<Allocate or initialize ...@>=
2164 set_callback_option(run_editor);
2165
2166 @ @<Declarations@>=
2167 void mp_run_editor (MP mp, char *fname, int fline);
2168
2169 @ @c void mp_run_editor (MP mp, char *fname, int fline) {
2170     mp_print_nl(mp, "You want to edit file ");
2171 @.You want to edit file x@>
2172     mp_print(mp, fname);
2173     mp_print(mp, " at line "); 
2174     mp_print_int(mp, fline);
2175     mp->interaction=mp_scroll_mode; 
2176     mp_jump_out(mp);
2177 }
2178
2179
2180 There is a secret `\.D' option available when the debugging routines haven't
2181 been commented~out.
2182 @^debugging@>
2183
2184 @<Interpret code |c| and |return| if done@>=
2185 switch (c) {
2186 case '0': case '1': case '2': case '3': case '4':
2187 case '5': case '6': case '7': case '8': case '9': 
2188   if ( mp->deletions_allowed ) {
2189     @<Delete |c-"0"| tokens and |continue|@>;
2190   }
2191   break;
2192 #ifdef DEBUG
2193 case 'D': 
2194   mp_debug_help(mp); continue; 
2195   break;
2196 #endif
2197 case 'E': 
2198   if ( mp->file_ptr>0 ){ 
2199     (mp->run_editor)(mp, 
2200                      str(mp->input_stack[mp->file_ptr].name_field), 
2201                      mp_true_line(mp));
2202   }
2203   break;
2204 case 'H': 
2205   @<Print the help information and |continue|@>;
2206   break;
2207 case 'I':
2208   @<Introduce new material from the terminal and |return|@>;
2209   break;
2210 case 'Q': case 'R': case 'S':
2211   @<Change the interaction level and |return|@>;
2212   break;
2213 case 'X':
2214   mp->interaction=mp_scroll_mode; mp_jump_out(mp);
2215   break;
2216 default:
2217   break;
2218 }
2219 @<Print the menu of available options@>
2220
2221 @ @<Print the menu...@>=
2222
2223   mp_print(mp, "Type <return> to proceed, S to scroll future error messages,");
2224 @.Type <return> to proceed...@>
2225   mp_print_nl(mp, "R to run without stopping, Q to run quietly,");
2226   mp_print_nl(mp, "I to insert something, ");
2227   if ( mp->file_ptr>0 ) 
2228     mp_print(mp, "E to edit your file,");
2229   if ( mp->deletions_allowed )
2230     mp_print_nl(mp, "1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
2231   mp_print_nl(mp, "H for help, X to quit.");
2232 }
2233
2234 @ Here the author of \MP\ apologizes for making use of the numerical
2235 relation between |"Q"|, |"R"|, |"S"|, and the desired interaction settings
2236 |mp_batch_mode|, |mp_nonstop_mode|, |mp_scroll_mode|.
2237 @^Knuth, Donald Ervin@>
2238
2239 @<Change the interaction...@>=
2240
2241   mp->error_count=0; mp->interaction=mp_batch_mode+c-'Q';
2242   mp_print(mp, "OK, entering ");
2243   switch (c) {
2244   case 'Q': mp_print(mp, "batchmode"); decr(mp->selector); break;
2245   case 'R': mp_print(mp, "nonstopmode"); break;
2246   case 'S': mp_print(mp, "scrollmode"); break;
2247   } /* there are no other cases */
2248   mp_print(mp, "..."); mp_print_ln(mp); update_terminal; return;
2249 }
2250
2251 @ When the following code is executed, |buffer[(first+1)..(last-1)]| may
2252 contain the material inserted by the user; otherwise another prompt will
2253 be given. In order to understand this part of the program fully, you need
2254 to be familiar with \MP's input stacks.
2255
2256 @<Introduce new material...@>=
2257
2258   mp_begin_file_reading(mp); /* enter a new syntactic level for terminal input */
2259   if ( mp->last>mp->first+1 ) { 
2260     loc=mp->first+1; mp->buffer[mp->first]=' ';
2261   } else { 
2262    prompt_input("insert>"); loc=mp->first;
2263 @.insert>@>
2264   };
2265   mp->first=mp->last+1; mp->cur_input.limit_field=mp->last; return;
2266 }
2267
2268 @ We allow deletion of up to 99 tokens at a time.
2269
2270 @<Delete |c-"0"| tokens...@>=
2271
2272   s1=mp->cur_cmd; s2=mp->cur_mod; s3=mp->cur_sym; mp->OK_to_interrupt=false;
2273   if ( (mp->last>mp->first+1) && (mp->buffer[mp->first+1]>='0')&&(mp->buffer[mp->first+1]<='9') )
2274     c=c*10+mp->buffer[mp->first+1]-'0'*11;
2275   else 
2276     c=c-'0';
2277   while ( c>0 ) { 
2278     mp_get_next(mp); /* one-level recursive call of |error| is possible */
2279     @<Decrease the string reference count, if the current token is a string@>;
2280     decr(c);
2281   };
2282   mp->cur_cmd=s1; mp->cur_mod=s2; mp->cur_sym=s3; mp->OK_to_interrupt=true;
2283   help2("I have just deleted some text, as you asked.")
2284        ("You can now delete more, or insert, or whatever.");
2285   mp_show_context(mp); 
2286   goto CONTINUE;
2287 }
2288
2289 @ @<Print the help info...@>=
2290
2291   if ( mp->use_err_help ) { 
2292     @<Print the string |err_help|, possibly on several lines@>;
2293     mp->use_err_help=false;
2294   } else { 
2295     if ( mp->help_ptr==0 ) {
2296       help2("Sorry, I don't know how to help in this situation.")
2297            ("Maybe you should try asking a human?");
2298      }
2299     do { 
2300       decr(mp->help_ptr); mp_print(mp, mp->help_line[mp->help_ptr]); mp_print_ln(mp);
2301     } while (mp->help_ptr!=0);
2302   };
2303   help4("Sorry, I already gave what help I could...")
2304        ("Maybe you should try asking a human?")
2305        ("An error might have occurred before I noticed any problems.")
2306        ("``If all else fails, read the instructions.''");
2307   goto CONTINUE;
2308 }
2309
2310 @ @<Print the string |err_help|, possibly on several lines@>=
2311 j=mp->str_start[mp->err_help];
2312 while ( j<str_stop(mp->err_help) ) { 
2313   if ( mp->str_pool[j]!='%' ) mp_print_str(mp, mp->str_pool[j]);
2314   else if ( j+1==str_stop(mp->err_help) ) mp_print_ln(mp);
2315   else if ( mp->str_pool[j+1]!='%' ) mp_print_ln(mp);
2316   else  { incr(j); mp_print_char(mp, '%'); };
2317   incr(j);
2318 }
2319
2320 @ @<Put help message on the transcript file@>=
2321 if ( mp->interaction>mp_batch_mode ) decr(mp->selector); /* avoid terminal output */
2322 if ( mp->use_err_help ) { 
2323   mp_print_nl(mp, "");
2324   @<Print the string |err_help|, possibly on several lines@>;
2325 } else { 
2326   while ( mp->help_ptr>0 ){ 
2327     decr(mp->help_ptr); mp_print_nl(mp, mp->help_line[mp->help_ptr]);
2328   };
2329 }
2330 mp_print_ln(mp);
2331 if ( mp->interaction>mp_batch_mode ) incr(mp->selector); /* re-enable terminal output */
2332 mp_print_ln(mp)
2333
2334 @ In anomalous cases, the print selector might be in an unknown state;
2335 the following subroutine is called to fix things just enough to keep
2336 running a bit longer.
2337
2338 @c 
2339 void mp_normalize_selector (MP mp) { 
2340   if ( mp->log_opened ) mp->selector=term_and_log;
2341   else mp->selector=term_only;
2342   if ( mp->job_name==NULL ) mp_open_log_file(mp);
2343   if ( mp->interaction==mp_batch_mode ) decr(mp->selector);
2344 }
2345
2346 @ The following procedure prints \MP's last words before dying.
2347
2348 @d succumb { if ( mp->interaction==mp_error_stop_mode )
2349     mp->interaction=mp_scroll_mode; /* no more interaction */
2350   if ( mp->log_opened ) mp_error(mp);
2351   /* if ( mp->interaction>mp_batch_mode ) mp_debug_help(mp); */
2352   mp->history=mp_fatal_error_stop; mp_jump_out(mp); /* irrecoverable error */
2353   }
2354
2355 @<Error hand...@>=
2356 void mp_fatal_error (MP mp, char *s) { /* prints |s|, and that's it */
2357   mp_normalize_selector(mp);
2358   print_err("Emergency stop"); help1(s); succumb;
2359 @.Emergency stop@>
2360 }
2361
2362 @ @<Exported function ...@>=
2363 void mp_fatal_error (MP mp, char *s);
2364
2365
2366 @ Here is the most dreaded error message.
2367
2368 @<Error hand...@>=
2369 void mp_overflow (MP mp, char *s, integer n) { /* stop due to finiteness */
2370   mp_normalize_selector(mp);
2371   print_err("MetaPost capacity exceeded, sorry [");
2372 @.MetaPost capacity exceeded ...@>
2373   mp_print(mp, s); mp_print_char(mp, '='); mp_print_int(mp, n); mp_print_char(mp, ']');
2374   help2("If you really absolutely need more capacity,")
2375        ("you can ask a wizard to enlarge me.");
2376   succumb;
2377 }
2378
2379 @ @<Declarations@>=
2380 void mp_overflow (MP mp, char *s, integer n);
2381
2382 @ The program might sometime run completely amok, at which point there is
2383 no choice but to stop. If no previous error has been detected, that's bad
2384 news; a message is printed that is really intended for the \MP\
2385 maintenance person instead of the user (unless the user has been
2386 particularly diabolical).  The index entries for `this can't happen' may
2387 help to pinpoint the problem.
2388 @^dry rot@>
2389
2390 @<Internal library ...@>=
2391 void mp_confusion (MP mp,char *s);
2392
2393 @ @<Error hand...@>=
2394 void mp_confusion (MP mp,char *s) {
2395   /* consistency check violated; |s| tells where */
2396   mp_normalize_selector(mp);
2397   if ( mp->history<mp_error_message_issued ) { 
2398     print_err("This can't happen ("); mp_print(mp, s); mp_print_char(mp, ')');
2399 @.This can't happen@>
2400     help1("I'm broken. Please show this to someone who can fix can fix");
2401   } else { 
2402     print_err("I can\'t go on meeting you like this");
2403 @.I can't go on...@>
2404     help2("One of your faux pas seems to have wounded me deeply...")
2405          ("in fact, I'm barely conscious. Please fix it and try again.");
2406   }
2407   succumb;
2408 }
2409
2410 @ Users occasionally want to interrupt \MP\ while it's running.
2411 If the \PASCAL\ runtime system allows this, one can implement
2412 a routine that sets the global variable |interrupt| to some nonzero value
2413 when such an interrupt is signaled. Otherwise there is probably at least
2414 a way to make |interrupt| nonzero using the \PASCAL\ debugger.
2415 @^system dependencies@>
2416 @^debugging@>
2417
2418 @d check_interrupt { if ( mp->interrupt!=0 )
2419    mp_pause_for_instructions(mp); }
2420
2421 @<Global...@>=
2422 integer interrupt; /* should \MP\ pause for instructions? */
2423 boolean OK_to_interrupt; /* should interrupts be observed? */
2424
2425 @ @<Allocate or ...@>=
2426 mp->interrupt=0; mp->OK_to_interrupt=true;
2427
2428 @ When an interrupt has been detected, the program goes into its
2429 highest interaction level and lets the user have the full flexibility of
2430 the |error| routine.  \MP\ checks for interrupts only at times when it is
2431 safe to do this.
2432
2433 @c 
2434 void mp_pause_for_instructions (MP mp) { 
2435   if ( mp->OK_to_interrupt ) { 
2436     mp->interaction=mp_error_stop_mode;
2437     if ( (mp->selector==log_only)||(mp->selector==no_print) )
2438       incr(mp->selector);
2439     print_err("Interruption");
2440 @.Interruption@>
2441     help3("You rang?")
2442          ("Try to insert some instructions for me (e.g.,`I show x'),")
2443          ("unless you just want to quit by typing `X'.");
2444     mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
2445     mp->interrupt=0;
2446   }
2447 }
2448
2449 @ Many of \MP's error messages state that a missing token has been
2450 inserted behind the scenes. We can save string space and program space
2451 by putting this common code into a subroutine.
2452
2453 @c 
2454 void mp_missing_err (MP mp, char *s) { 
2455   print_err("Missing `"); mp_print(mp, s); mp_print(mp, "' has been inserted");
2456 @.Missing...inserted@>
2457 }
2458
2459 @* \[7] Arithmetic with scaled numbers.
2460 The principal computations performed by \MP\ are done entirely in terms of
2461 integers less than $2^{31}$ in magnitude; thus, the arithmetic specified in this
2462 program can be carried out in exactly the same way on a wide variety of
2463 computers, including some small ones.
2464 @^small computers@>
2465
2466 But \PASCAL\ does not define the |div|
2467 operation in the case of negative dividends; for example, the result of
2468 |(-2*n-1) div 2| is |-(n+1)| on some computers and |-n| on others.
2469 There are two principal types of arithmetic: ``translation-preserving,''
2470 in which the identity |(a+q*b)div b=(a div b)+q| is valid; and
2471 ``negation-preserving,'' in which |(-a)div b=-(a div b)|. This leads to
2472 two \MP s, which can produce different results, although the differences
2473 should be negligible when the language is being used properly.
2474 The \TeX\ processor has been defined carefully so that both varieties
2475 of arithmetic will produce identical output, but it would be too
2476 inefficient to constrain \MP\ in a similar way.
2477
2478 @d el_gordo   017777777777 /* $2^{31}-1$, the largest value that \MP\ likes */
2479
2480 @ One of \MP's most common operations is the calculation of
2481 $\lfloor{a+b\over2}\rfloor$,
2482 the midpoint of two given integers |a| and~|b|. The only decent way to do
2483 this in \PASCAL\ is to write `|(a+b) div 2|'; but on most machines it is
2484 far more efficient to calculate `|(a+b)| right shifted one bit'.
2485
2486 Therefore the midpoint operation will always be denoted by `|half(a+b)|'
2487 in this program. If \MP\ is being implemented with languages that permit
2488 binary shifting, the |half| macro should be changed to make this operation
2489 as efficient as possible.  Since some languages have shift operators that can
2490 only be trusted to work on positive numbers, there is also a macro |halfp|
2491 that is used only when the quantity being halved is known to be positive
2492 or zero.
2493
2494 @d half(A) ((A) / 2)
2495 @d halfp(A) ((A) / 2)
2496
2497 @ A single computation might use several subroutine calls, and it is
2498 desirable to avoid producing multiple error messages in case of arithmetic
2499 overflow. So the routines below set the global variable |arith_error| to |true|
2500 instead of reporting errors directly to the user.
2501
2502 @<Glob...@>=
2503 boolean arith_error; /* has arithmetic overflow occurred recently? */
2504
2505 @ @<Allocate or ...@>=
2506 mp->arith_error=false;
2507
2508 @ At crucial points the program will say |check_arith|, to test if
2509 an arithmetic error has been detected.
2510
2511 @d check_arith { if ( mp->arith_error ) mp_clear_arith(mp); }
2512
2513 @c 
2514 void mp_clear_arith (MP mp) { 
2515   print_err("Arithmetic overflow");
2516 @.Arithmetic overflow@>
2517   help4("Uh, oh. A little while ago one of the quantities that I was")
2518        ("computing got too large, so I'm afraid your answers will be")
2519        ("somewhat askew. You'll probably have to adopt different")
2520        ("tactics next time. But I shall try to carry on anyway.");
2521   mp_error(mp); 
2522   mp->arith_error=false;
2523 }
2524
2525 @ Addition is not always checked to make sure that it doesn't overflow,
2526 but in places where overflow isn't too unlikely the |slow_add| routine
2527 is used.
2528
2529 @c integer mp_slow_add (MP mp,integer x, integer y) { 
2530   if ( x>=0 )  {
2531     if ( y<=el_gordo-x ) { 
2532       return x+y;
2533     } else  { 
2534       mp->arith_error=true; 
2535           return el_gordo;
2536     }
2537   } else  if ( -y<=el_gordo+x ) {
2538     return x+y;
2539   } else { 
2540     mp->arith_error=true; 
2541         return -el_gordo;
2542   }
2543 }
2544
2545 @ Fixed-point arithmetic is done on {\sl scaled integers\/} that are multiples
2546 of $2^{-16}$. In other words, a binary point is assumed to be sixteen bit
2547 positions from the right end of a binary computer word.
2548
2549 @d quarter_unit   040000 /* $2^{14}$, represents 0.250000 */
2550 @d half_unit   0100000 /* $2^{15}$, represents 0.50000 */
2551 @d three_quarter_unit   0140000 /* $3\cdot2^{14}$, represents 0.75000 */
2552 @d unity   0200000 /* $2^{16}$, represents 1.00000 */
2553 @d two   0400000 /* $2^{17}$, represents 2.00000 */
2554 @d three   0600000 /* $2^{17}+2^{16}$, represents 3.00000 */
2555
2556 @<Types...@>=
2557 typedef integer scaled; /* this type is used for scaled integers */
2558 typedef unsigned char small_number; /* this type is self-explanatory */
2559
2560 @ The following function is used to create a scaled integer from a given decimal
2561 fraction $(.d_0d_1\ldots d_{k-1})$, where |0<=k<=17|. The digit $d_i$ is
2562 given in |dig[i]|, and the calculation produces a correctly rounded result.
2563
2564 @c 
2565 scaled mp_round_decimals (MP mp,small_number k) {
2566   /* converts a decimal fraction */
2567  integer a = 0; /* the accumulator */
2568  while ( k-->0 ) { 
2569     a=(a+mp->dig[k]*two) / 10;
2570   }
2571   return halfp(a+1);
2572 }
2573
2574 @ Conversely, here is a procedure analogous to |print_int|. If the output
2575 of this procedure is subsequently read by \MP\ and converted by the
2576 |round_decimals| routine above, it turns out that the original value will
2577 be reproduced exactly. A decimal point is printed only if the value is
2578 not an integer. If there is more than one way to print the result with
2579 the optimum number of digits following the decimal point, the closest
2580 possible value is given.
2581
2582 The invariant relation in the \&{repeat} loop is that a sequence of
2583 decimal digits yet to be printed will yield the original number if and only if
2584 they form a fraction~$f$ in the range $s-\delta\L10\cdot2^{16}f<s$.
2585 We can stop if and only if $f=0$ satisfies this condition; the loop will
2586 terminate before $s$ can possibly become zero.
2587
2588 @<Basic printing...@>=
2589 void mp_print_scaled (MP mp,scaled s) { /* prints scaled real, rounded to five  digits */
2590   scaled delta; /* amount of allowable inaccuracy */
2591   if ( s<0 ) { 
2592         mp_print_char(mp, '-'); 
2593     negate(s); /* print the sign, if negative */
2594   }
2595   mp_print_int(mp, s / unity); /* print the integer part */
2596   s=10*(s % unity)+5;
2597   if ( s!=5 ) { 
2598     delta=10; 
2599     mp_print_char(mp, '.');
2600     do {  
2601       if ( delta>unity )
2602         s=s+0100000-(delta / 2); /* round the final digit */
2603       mp_print_char(mp, '0'+(s / unity)); 
2604       s=10*(s % unity); 
2605       delta=delta*10;
2606     } while (s>delta);
2607   }
2608 }
2609
2610 @ We often want to print two scaled quantities in parentheses,
2611 separated by a comma.
2612
2613 @<Basic printing...@>=
2614 void mp_print_two (MP mp,scaled x, scaled y) { /* prints `|(x,y)|' */
2615   mp_print_char(mp, '('); 
2616   mp_print_scaled(mp, x); 
2617   mp_print_char(mp, ','); 
2618   mp_print_scaled(mp, y);
2619   mp_print_char(mp, ')');
2620 }
2621
2622 @ The |scaled| quantities in \MP\ programs are generally supposed to be
2623 less than $2^{12}$ in absolute value, so \MP\ does much of its internal
2624 arithmetic with 28~significant bits of precision. A |fraction| denotes
2625 a scaled integer whose binary point is assumed to be 28 bit positions
2626 from the right.
2627
2628 @d fraction_half 01000000000 /* $2^{27}$, represents 0.50000000 */
2629 @d fraction_one 02000000000 /* $2^{28}$, represents 1.00000000 */
2630 @d fraction_two 04000000000 /* $2^{29}$, represents 2.00000000 */
2631 @d fraction_three 06000000000 /* $3\cdot2^{28}$, represents 3.00000000 */
2632 @d fraction_four 010000000000 /* $2^{30}$, represents 4.00000000 */
2633
2634 @<Types...@>=
2635 typedef integer fraction; /* this type is used for scaled fractions */
2636
2637 @ In fact, the two sorts of scaling discussed above aren't quite
2638 sufficient; \MP\ has yet another, used internally to keep track of angles
2639 in units of $2^{-20}$ degrees.
2640
2641 @d forty_five_deg 0264000000 /* $45\cdot2^{20}$, represents $45^\circ$ */
2642 @d ninety_deg 0550000000 /* $90\cdot2^{20}$, represents $90^\circ$ */
2643 @d one_eighty_deg 01320000000 /* $180\cdot2^{20}$, represents $180^\circ$ */
2644 @d three_sixty_deg 02640000000 /* $360\cdot2^{20}$, represents $360^\circ$ */
2645
2646 @<Types...@>=
2647 typedef integer angle; /* this type is used for scaled angles */
2648
2649 @ The |make_fraction| routine produces the |fraction| equivalent of
2650 |p/q|, given integers |p| and~|q|; it computes the integer
2651 $f=\lfloor2^{28}p/q+{1\over2}\rfloor$, when $p$ and $q$ are
2652 positive. If |p| and |q| are both of the same scaled type |t|,
2653 the ``type relation'' |make_fraction(t,t)=fraction| is valid;
2654 and it's also possible to use the subroutine ``backwards,'' using
2655 the relation |make_fraction(t,fraction)=t| between scaled types.
2656
2657 If the result would have magnitude $2^{31}$ or more, |make_fraction|
2658 sets |arith_error:=true|. Most of \MP's internal computations have
2659 been designed to avoid this sort of error.
2660
2661 If this subroutine were programmed in assembly language on a typical
2662 machine, we could simply compute |(@t$2^{28}$@>*p)div q|, since a
2663 double-precision product can often be input to a fixed-point division
2664 instruction. But when we are restricted to \PASCAL\ arithmetic it
2665 is necessary either to resort to multiple-precision maneuvering
2666 or to use a simple but slow iteration. The multiple-precision technique
2667 would be about three times faster than the code adopted here, but it
2668 would be comparatively long and tricky, involving about sixteen
2669 additional multiplications and divisions.
2670
2671 This operation is part of \MP's ``inner loop''; indeed, it will
2672 consume nearly 10\pct! of the running time (exclusive of input and output)
2673 if the code below is left unchanged. A machine-dependent recoding
2674 will therefore make \MP\ run faster. The present implementation
2675 is highly portable, but slow; it avoids multiplication and division
2676 except in the initial stage. System wizards should be careful to
2677 replace it with a routine that is guaranteed to produce identical
2678 results in all cases.
2679 @^system dependencies@>
2680
2681 As noted below, a few more routines should also be replaced by machine-dependent
2682 code, for efficiency. But when a procedure is not part of the ``inner loop,''
2683 such changes aren't advisable; simplicity and robustness are
2684 preferable to trickery, unless the cost is too high.
2685 @^inner loop@>
2686
2687 @<Internal ...@>=
2688 fraction mp_make_fraction (MP mp,integer p, integer q);
2689 integer mp_take_scaled (MP mp,integer q, scaled f) ;
2690
2691 @ If FIXPT is not defined, we need these preprocessor values
2692
2693 @d ELGORDO  0x7fffffff
2694 @d TWEXP31  2147483648.0
2695 @d TWEXP28  268435456.0
2696 @d TWEXP16 65536.0
2697 @d TWEXP_16 (1.0/65536.0)
2698 @d TWEXP_28 (1.0/268435456.0)
2699
2700
2701 @c 
2702 fraction mp_make_fraction (MP mp,integer p, integer q) {
2703 #ifdef FIXPT
2704   integer f; /* the fraction bits, with a leading 1 bit */
2705   integer n; /* the integer part of $\vert p/q\vert$ */
2706   integer be_careful; /* disables certain compiler optimizations */
2707   boolean negative = false; /* should the result be negated? */
2708   if ( p<0 ) {
2709     negate(p); negative=true;
2710   }
2711   if ( q<=0 ) { 
2712 #ifdef DEBUG
2713     if ( q==0 ) mp_confusion(mp, '/');
2714 #endif
2715 @:this can't happen /}{\quad \./@>
2716     negate(q); negative = ! negative;
2717   };
2718   n=p / q; p=p % q;
2719   if ( n>=8 ){ 
2720     mp->arith_error=true;
2721     return ( negative ? -el_gordo : el_gordo);
2722   } else { 
2723     n=(n-1)*fraction_one;
2724     @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>;
2725     return (negative ? (-(f+n)) : (f+n));
2726   }
2727 #else /* FIXPT */
2728     register double d;
2729         register integer i;
2730 #ifdef DEBUG
2731         if (q==0) mp_confusion(mp,'/'); 
2732 #endif /* DEBUG */
2733         d = TWEXP28 * (double)p /(double)q;
2734         if ((p^q) >= 0) {
2735                 d += 0.5;
2736                 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
2737                 i = (integer) d;
2738                 if (d==i && ( ((q>0 ? -q : q)&077777)
2739                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2740         } else {
2741                 d -= 0.5;
2742                 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
2743                 i = (integer) d;
2744                 if (d==i && ( ((q>0 ? q : -q)&077777)
2745                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
2746         }
2747         return i;
2748 #endif /* FIXPT */
2749 }
2750
2751 @ The |repeat| loop here preserves the following invariant relations
2752 between |f|, |p|, and~|q|:
2753 (i)~|0<=p<q|; (ii)~$fq+p=2^k(q+p_0)$, where $k$ is an integer and
2754 $p_0$ is the original value of~$p$.
2755
2756 Notice that the computation specifies
2757 |(p-q)+p| instead of |(p+p)-q|, because the latter could overflow.
2758 Let us hope that optimizing compilers do not miss this point; a
2759 special variable |be_careful| is used to emphasize the necessary
2760 order of computation. Optimizing compilers should keep |be_careful|
2761 in a register, not store it in memory.
2762 @^inner loop@>
2763
2764 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>=
2765 {
2766   f=1;
2767   do {  
2768     be_careful=p-q; p=be_careful+p;
2769     if ( p>=0 ) { 
2770       f=f+f+1;
2771     } else  { 
2772       f+=f; p=p+q;
2773     }
2774   } while (f<fraction_one);
2775   be_careful=p-q;
2776   if ( be_careful+p>=0 ) incr(f);
2777 }
2778
2779 @ The dual of |make_fraction| is |take_fraction|, which multiplies a
2780 given integer~|q| by a fraction~|f|. When the operands are positive, it
2781 computes $p=\lfloor qf/2^{28}+{1\over2}\rfloor$, a symmetric function
2782 of |q| and~|f|.
2783
2784 This routine is even more ``inner loopy'' than |make_fraction|;
2785 the present implementation consumes almost 20\pct! of \MP's computation
2786 time during typical jobs, so a machine-language substitute is advisable.
2787 @^inner loop@> @^system dependencies@>
2788
2789 @<Declarations@>=
2790 integer mp_take_fraction (MP mp,integer q, fraction f) ;
2791
2792 @ @c 
2793 #ifdef FIXPT
2794 integer mp_take_fraction (MP mp,integer q, fraction f) {
2795   integer p; /* the fraction so far */
2796   boolean negative; /* should the result be negated? */
2797   integer n; /* additional multiple of $q$ */
2798   integer be_careful; /* disables certain compiler optimizations */
2799   @<Reduce to the case that |f>=0| and |q>0|@>;
2800   if ( f<fraction_one ) { 
2801     n=0;
2802   } else { 
2803     n=f / fraction_one; f=f % fraction_one;
2804     if ( q<=el_gordo / n ) { 
2805       n=n*q ; 
2806     } else { 
2807       mp->arith_error=true; n=el_gordo;
2808     }
2809   }
2810   f=f+fraction_one;
2811   @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>;
2812   be_careful=n-el_gordo;
2813   if ( be_careful+p>0 ){ 
2814     mp->arith_error=true; n=el_gordo-p;
2815   }
2816   if ( negative ) 
2817         return (-(n+p));
2818   else 
2819     return (n+p);
2820 #else /* FIXPT */
2821 integer mp_take_fraction (MP mp,integer p, fraction q) {
2822     register double d;
2823         register integer i;
2824         d = (double)p * (double)q * TWEXP_28;
2825         if ((p^q) >= 0) {
2826                 d += 0.5;
2827                 if (d>=TWEXP31) {
2828                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2829                                 mp->arith_error = true;
2830                         return ELGORDO;
2831                 }
2832                 i = (integer) d;
2833                 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2834         } else {
2835                 d -= 0.5;
2836                 if (d<= -TWEXP31) {
2837                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2838                                 mp->arith_error = true;
2839                         return -ELGORDO;
2840                 }
2841                 i = (integer) d;
2842                 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2843         }
2844         return i;
2845 #endif /* FIXPT */
2846 }
2847
2848 @ @<Reduce to the case that |f>=0| and |q>0|@>=
2849 if ( f>=0 ) {
2850   negative=false;
2851 } else { 
2852   negate( f); negative=true;
2853 }
2854 if ( q<0 ) { 
2855   negate(q); negative=! negative;
2856 }
2857
2858 @ The invariant relations in this case are (i)~$\lfloor(qf+p)/2^k\rfloor
2859 =\lfloor qf_0/2^{28}+{1\over2}\rfloor$, where $k$ is an integer and
2860 $f_0$ is the original value of~$f$; (ii)~$2^k\L f<2^{k+1}$.
2861 @^inner loop@>
2862
2863 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>=
2864 p=fraction_half; /* that's $2^{27}$; the invariants hold now with $k=28$ */
2865 if ( q<fraction_four ) {
2866   do {  
2867     if ( odd(f) ) p=halfp(p+q); else p=halfp(p);
2868     f=halfp(f);
2869   } while (f!=1);
2870 } else  {
2871   do {  
2872     if ( odd(f) ) p=p+halfp(q-p); else p=halfp(p);
2873     f=halfp(f);
2874   } while (f!=1);
2875 }
2876
2877
2878 @ When we want to multiply something by a |scaled| quantity, we use a scheme
2879 analogous to |take_fraction| but with a different scaling.
2880 Given positive operands, |take_scaled|
2881 computes the quantity $p=\lfloor qf/2^{16}+{1\over2}\rfloor$.
2882
2883 Once again it is a good idea to use a machine-language replacement if
2884 possible; otherwise |take_scaled| will use more than 2\pct! of the running time
2885 when the Computer Modern fonts are being generated.
2886 @^inner loop@>
2887
2888 @c 
2889 #ifdef FIXPT
2890 integer mp_take_scaled (MP mp,integer q, scaled f) {
2891   integer p; /* the fraction so far */
2892   boolean negative; /* should the result be negated? */
2893   integer n; /* additional multiple of $q$ */
2894   integer be_careful; /* disables certain compiler optimizations */
2895   @<Reduce to the case that |f>=0| and |q>0|@>;
2896   if ( f<unity ) { 
2897     n=0;
2898   } else  { 
2899     n=f / unity; f=f % unity;
2900     if ( q<=el_gordo / n ) {
2901       n=n*q;
2902     } else  { 
2903       mp->arith_error=true; n=el_gordo;
2904     }
2905   }
2906   f=f+unity;
2907   @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>;
2908   be_careful=n-el_gordo;
2909   if ( be_careful+p>0 ) { 
2910     mp->arith_error=true; n=el_gordo-p;
2911   }
2912   return ( negative ?(-(n+p)) :(n+p));
2913 #else /* FIXPT */
2914 integer mp_take_scaled (MP mp,integer p, scaled q) {
2915     register double d;
2916         register integer i;
2917         d = (double)p * (double)q * TWEXP_16;
2918         if ((p^q) >= 0) {
2919                 d += 0.5;
2920                 if (d>=TWEXP31) {
2921                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2922                                 mp->arith_error = true;
2923                         return ELGORDO;
2924                 }
2925                 i = (integer) d;
2926                 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2927         } else {
2928                 d -= 0.5;
2929                 if (d<= -TWEXP31) {
2930                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2931                                 mp->arith_error = true;
2932                         return -ELGORDO;
2933                 }
2934                 i = (integer) d;
2935                 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2936         }
2937         return i;
2938 #endif /* FIXPT */
2939 }
2940
2941 @ @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>=
2942 p=half_unit; /* that's $2^{15}$; the invariants hold now with $k=16$ */
2943 @^inner loop@>
2944 if ( q<fraction_four ) {
2945   do {  
2946     p = (odd(f) ? halfp(p+q) : halfp(p));
2947     f=halfp(f);
2948   } while (f!=1);
2949 } else {
2950   do {  
2951     p = (odd(f) ? p+halfp(q-p) : halfp(p));
2952     f=halfp(f);
2953   } while (f!=1);
2954 }
2955
2956 @ For completeness, there's also |make_scaled|, which computes a
2957 quotient as a |scaled| number instead of as a |fraction|.
2958 In other words, the result is $\lfloor2^{16}p/q+{1\over2}\rfloor$, if the
2959 operands are positive. \ (This procedure is not used especially often,
2960 so it is not part of \MP's inner loop.)
2961
2962 @<Internal library ...@>=
2963 scaled mp_make_scaled (MP mp,integer p, integer q) ;
2964
2965 @ @c 
2966 scaled mp_make_scaled (MP mp,integer p, integer q) {
2967 #ifdef FIXPT 
2968   integer f; /* the fraction bits, with a leading 1 bit */
2969   integer n; /* the integer part of $\vert p/q\vert$ */
2970   boolean negative; /* should the result be negated? */
2971   integer be_careful; /* disables certain compiler optimizations */
2972   if ( p>=0 ) negative=false;
2973   else  { negate(p); negative=true; };
2974   if ( q<=0 ) { 
2975 #ifdef DEBUG 
2976     if ( q==0 ) mp_confusion(mp, "/");
2977 @:this can't happen /}{\quad \./@>
2978 #endif
2979     negate(q); negative=! negative;
2980   }
2981   n=p / q; p=p % q;
2982   if ( n>=0100000 ) { 
2983     mp->arith_error=true;
2984     return (negative ? (-el_gordo) : el_gordo);
2985   } else  { 
2986     n=(n-1)*unity;
2987     @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>;
2988     return ( negative ? (-(f+n)) :(f+n));
2989   }
2990 #else /* FIXPT */
2991     register double d;
2992         register integer i;
2993 #ifdef DEBUG
2994         if (q==0) mp_confusion(mp,"/"); 
2995 #endif /* DEBUG */
2996         d = TWEXP16 * (double)p /(double)q;
2997         if ((p^q) >= 0) {
2998                 d += 0.5;
2999                 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
3000                 i = (integer) d;
3001                 if (d==i && ( ((q>0 ? -q : q)&077777)
3002                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
3003         } else {
3004                 d -= 0.5;
3005                 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
3006                 i = (integer) d;
3007                 if (d==i && ( ((q>0 ? q : -q)&077777)
3008                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
3009         }
3010         return i;
3011 #endif /* FIXPT */
3012 }
3013
3014 @ @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>=
3015 f=1;
3016 do {  
3017   be_careful=p-q; p=be_careful+p;
3018   if ( p>=0 ) f=f+f+1;
3019   else  { f+=f; p=p+q; };
3020 } while (f<unity);
3021 be_careful=p-q;
3022 if ( be_careful+p>=0 ) incr(f)
3023
3024 @ Here is a typical example of how the routines above can be used.
3025 It computes the function
3026 $${1\over3\tau}f(\theta,\phi)=
3027 {\tau^{-1}\bigl(2+\sqrt2\,(\sin\theta-{1\over16}\sin\phi)
3028  (\sin\phi-{1\over16}\sin\theta)(\cos\theta-\cos\phi)\bigr)\over
3029 3\,\bigl(1+{1\over2}(\sqrt5-1)\cos\theta+{1\over2}(3-\sqrt5\,)\cos\phi\bigr)},$$
3030 where $\tau$ is a |scaled| ``tension'' parameter. This is \MP's magic
3031 fudge factor for placing the first control point of a curve that starts
3032 at an angle $\theta$ and ends at an angle $\phi$ from the straight path.
3033 (Actually, if the stated quantity exceeds 4, \MP\ reduces it to~4.)
3034
3035 The trigonometric quantity to be multiplied by $\sqrt2$ is less than $\sqrt2$.
3036 (It's a sum of eight terms whose absolute values can be bounded using
3037 relations such as $\sin\theta\cos\theta\L{1\over2}$.) Thus the numerator
3038 is positive; and since the tension $\tau$ is constrained to be at least
3039 $3\over4$, the numerator is less than $16\over3$. The denominator is
3040 nonnegative and at most~6.  Hence the fixed-point calculations below
3041 are guaranteed to stay within the bounds of a 32-bit computer word.
3042
3043 The angles $\theta$ and $\phi$ are given implicitly in terms of |fraction|
3044 arguments |st|, |ct|, |sf|, and |cf|, representing $\sin\theta$, $\cos\theta$,
3045 $\sin\phi$, and $\cos\phi$, respectively.
3046
3047 @c 
3048 fraction mp_velocity (MP mp,fraction st, fraction ct, fraction sf,
3049                       fraction cf, scaled t) {
3050   integer acc,num,denom; /* registers for intermediate calculations */
3051   acc=mp_take_fraction(mp, st-(sf / 16), sf-(st / 16));
3052   acc=mp_take_fraction(mp, acc,ct-cf);
3053   num=fraction_two+mp_take_fraction(mp, acc,379625062);
3054                    /* $2^{28}\sqrt2\approx379625062.497$ */
3055   denom=fraction_three+mp_take_fraction(mp, ct,497706707)+mp_take_fraction(mp, cf,307599661);
3056                       /* $3\cdot2^{27}\cdot(\sqrt5-1)\approx497706706.78$ and
3057                          $3\cdot2^{27}\cdot(3-\sqrt5\,)\approx307599661.22$ */
3058   if ( t!=unity ) num=mp_make_scaled(mp, num,t);
3059   /* |make_scaled(fraction,scaled)=fraction| */
3060   if ( num / 4>=denom ) 
3061     return fraction_four;
3062   else 
3063     return mp_make_fraction(mp, num, denom);
3064 }
3065
3066 @ The following somewhat different subroutine tests rigorously if $ab$ is
3067 greater than, equal to, or less than~$cd$,
3068 given integers $(a,b,c,d)$. In most cases a quick decision is reached.
3069 The result is $+1$, 0, or~$-1$ in the three respective cases.
3070
3071 @d mp_ab_vs_cd(M,A,B,C,D) mp_do_ab_vs_cd(A,B,C,D)
3072
3073 @c 
3074 integer mp_do_ab_vs_cd (integer a,integer b, integer c, integer d) {
3075   integer q,r; /* temporary registers */
3076   @<Reduce to the case that |a,c>=0|, |b,d>0|@>;
3077   while (1) { 
3078     q = a / d; r = c / b;
3079     if ( q!=r )
3080       return ( q>r ? 1 : -1);
3081     q = a % d; r = c % b;
3082     if ( r==0 )
3083       return (q ? 1 : 0);
3084     if ( q==0 ) return -1;
3085     a=b; b=q; c=d; d=r;
3086   } /* now |a>d>0| and |c>b>0| */
3087 }
3088
3089 @ @<Reduce to the case that |a...@>=
3090 if ( a<0 ) { negate(a); negate(b);  };
3091 if ( c<0 ) { negate(c); negate(d);  };
3092 if ( d<=0 ) { 
3093   if ( b>=0 ) {
3094     if ( (a==0||b==0)&&(c==0||d==0) ) return 0;
3095     else return 1;
3096   }
3097   if ( d==0 )
3098     return ( a==0 ? 0 : -1);
3099   q=a; a=c; c=q; q=-b; b=-d; d=q;
3100 } else if ( b<=0 ) { 
3101   if ( b<0 ) if ( a>0 ) return -1;
3102   return (c==0 ? 0 : -1);
3103 }
3104
3105 @ We conclude this set of elementary routines with some simple rounding
3106 and truncation operations.
3107
3108 @<Internal library declarations@>=
3109 #define mp_floor_scaled(M,i) ((i)&(-65536))
3110 #define mp_round_unscaled(M,i) (((i>>15)+1)>>1)
3111 #define mp_round_fraction(M,i) (((i>>11)+1)>>1)
3112
3113
3114 @* \[8] Algebraic and transcendental functions.
3115 \MP\ computes all of the necessary special functions from scratch, without
3116 relying on |real| arithmetic or system subroutines for sines, cosines, etc.
3117
3118 @ To get the square root of a |scaled| number |x|, we want to calculate
3119 $s=\lfloor 2^8\!\sqrt x +{1\over2}\rfloor$. If $x>0$, this is the unique
3120 integer such that $2^{16}x-s\L s^2<2^{16}x+s$. The following subroutine
3121 determines $s$ by an iterative method that maintains the invariant
3122 relations $x=2^{46-2k}x_0\bmod 2^{30}$, $0<y=\lfloor 2^{16-2k}x_0\rfloor
3123 -s^2+s\L q=2s$, where $x_0$ is the initial value of $x$. The value of~$y$
3124 might, however, be zero at the start of the first iteration.
3125
3126 @<Declarations@>=
3127 scaled mp_square_rt (MP mp,scaled x) ;
3128
3129 @ @c 
3130 scaled mp_square_rt (MP mp,scaled x) {
3131   small_number k; /* iteration control counter */
3132   integer y,q; /* registers for intermediate calculations */
3133   if ( x<=0 ) { 
3134     @<Handle square root of zero or negative argument@>;
3135   } else { 
3136     k=23; q=2;
3137     while ( x<fraction_two ) { /* i.e., |while x<@t$2^{29}$@>|\unskip */
3138       decr(k); x=x+x+x+x;
3139     }
3140     if ( x<fraction_four ) y=0;
3141     else  { x=x-fraction_four; y=1; };
3142     do {  
3143       @<Decrease |k| by 1, maintaining the invariant
3144       relations between |x|, |y|, and~|q|@>;
3145     } while (k!=0);
3146     return (halfp(q));
3147   }
3148 }
3149
3150 @ @<Handle square root of zero...@>=
3151
3152   if ( x<0 ) { 
3153     print_err("Square root of ");
3154 @.Square root...replaced by 0@>
3155     mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3156     help2("Since I don't take square roots of negative numbers,")
3157          ("I'm zeroing this one. Proceed, with fingers crossed.");
3158     mp_error(mp);
3159   };
3160   return 0;
3161 }
3162
3163 @ @<Decrease |k| by 1, maintaining...@>=
3164 x+=x; y+=y;
3165 if ( x>=fraction_four ) { /* note that |fraction_four=@t$2^{30}$@>| */
3166   x=x-fraction_four; incr(y);
3167 };
3168 x+=x; y=y+y-q; q+=q;
3169 if ( x>=fraction_four ) { x=x-fraction_four; incr(y); };
3170 if ( y>q ){ y=y-q; q=q+2; }
3171 else if ( y<=0 )  { q=q-2; y=y+q;  };
3172 decr(k)
3173
3174 @ Pythagorean addition $\psqrt{a^2+b^2}$ is implemented by an elegant
3175 iterative scheme due to Cleve Moler and Donald Morrison [{\sl IBM Journal
3176 @^Moler, Cleve Barry@>
3177 @^Morrison, Donald Ross@>
3178 of Research and Development\/ \bf27} (1983), 577--581]. It modifies |a| and~|b|
3179 in such a way that their Pythagorean sum remains invariant, while the
3180 smaller argument decreases.
3181
3182 @<Internal library ...@>=
3183 integer mp_pyth_add (MP mp,integer a, integer b);
3184
3185
3186 @ @c 
3187 integer mp_pyth_add (MP mp,integer a, integer b) {
3188   fraction r; /* register used to transform |a| and |b| */
3189   boolean big; /* is the result dangerously near $2^{31}$? */
3190   a=abs(a); b=abs(b);
3191   if ( a<b ) { r=b; b=a; a=r; }; /* now |0<=b<=a| */
3192   if ( b>0 ) {
3193     if ( a<fraction_two ) {
3194       big=false;
3195     } else { 
3196       a=a / 4; b=b / 4; big=true;
3197     }; /* we reduced the precision to avoid arithmetic overflow */
3198     @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>;
3199     if ( big ) {
3200       if ( a<fraction_two ) {
3201         a=a+a+a+a;
3202       } else  { 
3203         mp->arith_error=true; a=el_gordo;
3204       };
3205     }
3206   }
3207   return a;
3208 }
3209
3210 @ The key idea here is to reflect the vector $(a,b)$ about the
3211 line through $(a,b/2)$.
3212
3213 @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>=
3214 while (1) {  
3215   r=mp_make_fraction(mp, b,a);
3216   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3217   if ( r==0 ) break;
3218   r=mp_make_fraction(mp, r,fraction_four+r);
3219   a=a+mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3220 }
3221
3222
3223 @ Here is a similar algorithm for $\psqrt{a^2-b^2}$.
3224 It converges slowly when $b$ is near $a$, but otherwise it works fine.
3225
3226 @c 
3227 integer mp_pyth_sub (MP mp,integer a, integer b) {
3228   fraction r; /* register used to transform |a| and |b| */
3229   boolean big; /* is the input dangerously near $2^{31}$? */
3230   a=abs(a); b=abs(b);
3231   if ( a<=b ) {
3232     @<Handle erroneous |pyth_sub| and set |a:=0|@>;
3233   } else { 
3234     if ( a<fraction_four ) {
3235       big=false;
3236     } else  { 
3237       a=halfp(a); b=halfp(b); big=true;
3238     }
3239     @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>;
3240     if ( big ) double(a);
3241   }
3242   return a;
3243 }
3244
3245 @ @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>=
3246 while (1) { 
3247   r=mp_make_fraction(mp, b,a);
3248   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3249   if ( r==0 ) break;
3250   r=mp_make_fraction(mp, r,fraction_four-r);
3251   a=a-mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3252 }
3253
3254 @ @<Handle erroneous |pyth_sub| and set |a:=0|@>=
3255
3256   if ( a<b ){ 
3257     print_err("Pythagorean subtraction "); mp_print_scaled(mp, a);
3258     mp_print(mp, "+-+"); mp_print_scaled(mp, b); 
3259     mp_print(mp, " has been replaced by 0");
3260 @.Pythagorean...@>
3261     help2("Since I don't take square roots of negative numbers,")
3262          ("I'm zeroing this one. Proceed, with fingers crossed.");
3263     mp_error(mp);
3264   }
3265   a=0;
3266 }
3267
3268 @ The subroutines for logarithm and exponential involve two tables.
3269 The first is simple: |two_to_the[k]| equals $2^k$. The second involves
3270 a bit more calculation, which the author claims to have done correctly:
3271 |spec_log[k]| is $2^{27}$ times $\ln\bigl(1/(1-2^{-k})\bigr)=
3272 2^{-k}+{1\over2}2^{-2k}+{1\over3}2^{-3k}+\cdots\,$, rounded to the
3273 nearest integer.
3274
3275 @d two_to_the(A) (1<<(A))
3276
3277 @<Constants ...@>=
3278 static const integer spec_log[29] = { 0, /* special logarithms */
3279 93032640, 38612034, 17922280, 8662214, 4261238, 2113709,
3280 1052693, 525315, 262400, 131136, 65552, 32772, 16385,
3281 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 1 };
3282
3283 @ @<Local variables for initialization@>=
3284 integer k; /* all-purpose loop index */
3285
3286
3287 @ Here is the routine that calculates $2^8$ times the natural logarithm
3288 of a |scaled| quantity; it is an integer approximation to $2^{24}\ln(x/2^{16})$,
3289 when |x| is a given positive integer.
3290
3291 The method is based on exercise 1.2.2--25 in {\sl The Art of Computer
3292 Programming\/}: During the main iteration we have $1\L 2^{-30}x<1/(1-2^{1-k})$,
3293 and the logarithm of $2^{30}x$ remains to be added to an accumulator
3294 register called~$y$. Three auxiliary bits of accuracy are retained in~$y$
3295 during the calculation, and sixteen auxiliary bits to extend |y| are
3296 kept in~|z| during the initial argument reduction. (We add
3297 $100\cdot2^{16}=6553600$ to~|z| and subtract 100 from~|y| so that |z| will
3298 not become negative; also, the actual amount subtracted from~|y| is~96,
3299 not~100, because we want to add~4 for rounding before the final division by~8.)
3300
3301 @c 
3302 scaled mp_m_log (MP mp,scaled x) {
3303   integer y,z; /* auxiliary registers */
3304   integer k; /* iteration counter */
3305   if ( x<=0 ) {
3306      @<Handle non-positive logarithm@>;
3307   } else  { 
3308     y=1302456956+4-100; /* $14\times2^{27}\ln2\approx1302456956.421063$ */
3309     z=27595+6553600; /* and $2^{16}\times .421063\approx 27595$ */
3310     while ( x<fraction_four ) {
3311        double(x); y-=93032639; z-=48782;
3312     } /* $2^{27}\ln2\approx 93032639.74436163$ and $2^{16}\times.74436163\approx 48782$ */
3313     y=y+(z / unity); k=2;
3314     while ( x>fraction_four+4 ) {
3315       @<Increase |k| until |x| can be multiplied by a
3316         factor of $2^{-k}$, and adjust $y$ accordingly@>;
3317     }
3318     return (y / 8);
3319   }
3320 }
3321
3322 @ @<Increase |k| until |x| can...@>=
3323
3324   z=((x-1) / two_to_the(k))+1; /* $z=\lceil x/2^k\rceil$ */
3325   while ( x<fraction_four+z ) { z=halfp(z+1); incr(k); };
3326   y+=spec_log[k]; x-=z;
3327 }
3328
3329 @ @<Handle non-positive logarithm@>=
3330
3331   print_err("Logarithm of ");
3332 @.Logarithm...replaced by 0@>
3333   mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3334   help2("Since I don't take logs of non-positive numbers,")
3335        ("I'm zeroing this one. Proceed, with fingers crossed.");
3336   mp_error(mp); 
3337   return 0;
3338 }
3339
3340 @ Conversely, the exponential routine calculates $\exp(x/2^8)$,
3341 when |x| is |scaled|. The result is an integer approximation to
3342 $2^{16}\exp(x/2^{24})$, when |x| is regarded as an integer.
3343
3344 @c 
3345 scaled mp_m_exp (MP mp,scaled x) {
3346   small_number k; /* loop control index */
3347   integer y,z; /* auxiliary registers */
3348   if ( x>174436200 ) {
3349     /* $2^{24}\ln((2^{31}-1)/2^{16})\approx 174436199.51$ */
3350     mp->arith_error=true; 
3351     return el_gordo;
3352   } else if ( x<-197694359 ) {
3353         /* $2^{24}\ln(2^{-1}/2^{16})\approx-197694359.45$ */
3354     return 0;
3355   } else { 
3356     if ( x<=0 ) { 
3357        z=-8*x; y=04000000; /* $y=2^{20}$ */
3358     } else { 
3359       if ( x<=127919879 ) { 
3360         z=1023359037-8*x;
3361         /* $2^{27}\ln((2^{31}-1)/2^{20})\approx 1023359037.125$ */
3362       } else {
3363        z=8*(174436200-x); /* |z| is always nonnegative */
3364       }
3365       y=el_gordo;
3366     };
3367     @<Multiply |y| by $\exp(-z/2^{27})$@>;
3368     if ( x<=127919879 ) 
3369        return ((y+8) / 16);
3370      else 
3371        return y;
3372   }
3373 }
3374
3375 @ The idea here is that subtracting |spec_log[k]| from |z| corresponds
3376 to multiplying |y| by $1-2^{-k}$.
3377
3378 A subtle point (which had to be checked) was that if $x=127919879$, the
3379 value of~|y| will decrease so that |y+8| doesn't overflow. In fact,
3380 $z$ will be 5 in this case, and |y| will decrease by~64 when |k=25|
3381 and by~16 when |k=27|.
3382
3383 @<Multiply |y| by...@>=
3384 k=1;
3385 while ( z>0 ) { 
3386   while ( z>=spec_log[k] ) { 
3387     z-=spec_log[k];
3388     y=y-1-((y-two_to_the(k-1)) / two_to_the(k));
3389   }
3390   incr(k);
3391 }
3392
3393 @ The trigonometric subroutines use an auxiliary table such that
3394 |spec_atan[k]| contains an approximation to the |angle| whose tangent
3395 is~$1/2^k$. $\arctan2^{-k}$ times $2^{20}\cdot180/\pi$ 
3396
3397 @<Constants ...@>=
3398 static const angle spec_atan[27] = { 0, 27855475, 14718068, 7471121, 3750058, 
3399 1876857, 938658, 469357, 234682, 117342, 58671, 29335, 14668, 7334, 3667, 
3400 1833, 917, 458, 229, 115, 57, 29, 14, 7, 4, 2, 1 };
3401
3402 @ Given integers |x| and |y|, not both zero, the |n_arg| function
3403 returns the |angle| whose tangent points in the direction $(x,y)$.
3404 This subroutine first determines the correct octant, then solves the
3405 problem for |0<=y<=x|, then converts the result appropriately to
3406 return an answer in the range |-one_eighty_deg<=@t$\theta$@><=one_eighty_deg|.
3407 (The answer is |+one_eighty_deg| if |y=0| and |x<0|, but an answer of
3408 |-one_eighty_deg| is possible if, for example, |y=-1| and $x=-2^{30}$.)
3409
3410 The octants are represented in a ``Gray code,'' since that turns out
3411 to be computationally simplest.
3412
3413 @d negate_x 1
3414 @d negate_y 2
3415 @d switch_x_and_y 4
3416 @d first_octant 1
3417 @d second_octant (first_octant+switch_x_and_y)
3418 @d third_octant (first_octant+switch_x_and_y+negate_x)
3419 @d fourth_octant (first_octant+negate_x)
3420 @d fifth_octant (first_octant+negate_x+negate_y)
3421 @d sixth_octant (first_octant+switch_x_and_y+negate_x+negate_y)
3422 @d seventh_octant (first_octant+switch_x_and_y+negate_y)
3423 @d eighth_octant (first_octant+negate_y)
3424
3425 @c 
3426 angle mp_n_arg (MP mp,integer x, integer y) {
3427   angle z; /* auxiliary register */
3428   integer t; /* temporary storage */
3429   small_number k; /* loop counter */
3430   int octant; /* octant code */
3431   if ( x>=0 ) {
3432     octant=first_octant;
3433   } else { 
3434     negate(x); octant=first_octant+negate_x;
3435   }
3436   if ( y<0 ) { 
3437     negate(y); octant=octant+negate_y;
3438   }
3439   if ( x<y ) { 
3440     t=y; y=x; x=t; octant=octant+switch_x_and_y;
3441   }
3442   if ( x==0 ) { 
3443     @<Handle undefined arg@>; 
3444   } else { 
3445     @<Set variable |z| to the arg of $(x,y)$@>;
3446     @<Return an appropriate answer based on |z| and |octant|@>;
3447   }
3448 }
3449
3450 @ @<Handle undefined arg@>=
3451
3452   print_err("angle(0,0) is taken as zero");
3453 @.angle(0,0)...zero@>
3454   help2("The `angle' between two identical points is undefined.")
3455        ("I'm zeroing this one. Proceed, with fingers crossed.");
3456   mp_error(mp); 
3457   return 0;
3458 }
3459
3460 @ @<Return an appropriate answer...@>=
3461 switch (octant) {
3462 case first_octant: return z;
3463 case second_octant: return (ninety_deg-z);
3464 case third_octant: return (ninety_deg+z);
3465 case fourth_octant: return (one_eighty_deg-z);
3466 case fifth_octant: return (z-one_eighty_deg);
3467 case sixth_octant: return (-z-ninety_deg);
3468 case seventh_octant: return (z-ninety_deg);
3469 case eighth_octant: return (-z);
3470 }; /* there are no other cases */
3471 return 0
3472
3473 @ At this point we have |x>=y>=0|, and |x>0|. The numbers are scaled up
3474 or down until $2^{28}\L x<2^{29}$, so that accurate fixed-point calculations
3475 will be made.
3476
3477 @<Set variable |z| to the arg...@>=
3478 while ( x>=fraction_two ) { 
3479   x=halfp(x); y=halfp(y);
3480 }
3481 z=0;
3482 if ( y>0 ) { 
3483  while ( x<fraction_one ) { 
3484     x+=x; y+=y; 
3485  };
3486  @<Increase |z| to the arg of $(x,y)$@>;
3487 }
3488
3489 @ During the calculations of this section, variables |x| and~|y|
3490 represent actual coordinates $(x,2^{-k}y)$. We will maintain the
3491 condition |x>=y|, so that the tangent will be at most $2^{-k}$.
3492 If $x<2y$, the tangent is greater than $2^{-k-1}$. The transformation
3493 $(a,b)\mapsto(a+b\tan\phi,b-a\tan\phi)$ replaces $(a,b)$ by
3494 coordinates whose angle has decreased by~$\phi$; in the special case
3495 $a=x$, $b=2^{-k}y$, and $\tan\phi=2^{-k-1}$, this operation reduces
3496 to the particularly simple iteration shown here. [Cf.~John E. Meggitt,
3497 @^Meggitt, John E.@>
3498 {\sl IBM Journal of Research and Development\/ \bf6} (1962), 210--226.]
3499
3500 The initial value of |x| will be multiplied by at most
3501 $(1+{1\over2})(1+{1\over8})(1+{1\over32})\cdots\approx 1.7584$; hence
3502 there is no chance of integer overflow.
3503
3504 @<Increase |z|...@>=
3505 k=0;
3506 do {  
3507   y+=y; incr(k);
3508   if ( y>x ){ 
3509     z=z+spec_atan[k]; t=x; x=x+(y / two_to_the(k+k)); y=y-t;
3510   };
3511 } while (k!=15);
3512 do {  
3513   y+=y; incr(k);
3514   if ( y>x ) { z=z+spec_atan[k]; y=y-x; };
3515 } while (k!=26)
3516
3517 @ Conversely, the |n_sin_cos| routine takes an |angle| and produces the sine
3518 and cosine of that angle. The results of this routine are
3519 stored in global integer variables |n_sin| and |n_cos|.
3520
3521 @<Glob...@>=
3522 fraction n_sin;fraction n_cos; /* results computed by |n_sin_cos| */
3523
3524 @ Given an integer |z| that is $2^{20}$ times an angle $\theta$ in degrees,
3525 the purpose of |n_sin_cos(z)| is to set
3526 |x=@t$r\cos\theta$@>| and |y=@t$r\sin\theta$@>| (approximately),
3527 for some rather large number~|r|. The maximum of |x| and |y|
3528 will be between $2^{28}$ and $2^{30}$, so that there will be hardly
3529 any loss of accuracy. Then |x| and~|y| are divided by~|r|.
3530
3531 @c 
3532 void mp_n_sin_cos (MP mp,angle z) { /* computes a multiple of the sine
3533                                        and cosine */ 
3534   small_number k; /* loop control variable */
3535   int q; /* specifies the quadrant */
3536   fraction r; /* magnitude of |(x,y)| */
3537   integer x,y,t; /* temporary registers */
3538   while ( z<0 ) z=z+three_sixty_deg;
3539   z=z % three_sixty_deg; /* now |0<=z<three_sixty_deg| */
3540   q=z / forty_five_deg; z=z % forty_five_deg;
3541   x=fraction_one; y=x;
3542   if ( ! odd(q) ) z=forty_five_deg-z;
3543   @<Subtract angle |z| from |(x,y)|@>;
3544   @<Convert |(x,y)| to the octant determined by~|q|@>;
3545   r=mp_pyth_add(mp, x,y); 
3546   mp->n_cos=mp_make_fraction(mp, x,r); 
3547   mp->n_sin=mp_make_fraction(mp, y,r);
3548 }
3549
3550 @ In this case the octants are numbered sequentially.
3551
3552 @<Convert |(x,...@>=
3553 switch (q) {
3554 case 0: break;
3555 case 1: t=x; x=y; y=t; break;
3556 case 2: t=x; x=-y; y=t; break;
3557 case 3: negate(x); break;
3558 case 4: negate(x); negate(y); break;
3559 case 5: t=x; x=-y; y=-t; break;
3560 case 6: t=x; x=y; y=-t; break;
3561 case 7: negate(y); break;
3562 } /* there are no other cases */
3563
3564 @ The main iteration of |n_sin_cos| is similar to that of |n_arg| but
3565 applied in reverse. The values of |spec_atan[k]| decrease slowly enough
3566 that this loop is guaranteed to terminate before the (nonexistent) value
3567 |spec_atan[27]| would be required.
3568
3569 @<Subtract angle |z|...@>=
3570 k=1;
3571 while ( z>0 ){ 
3572   if ( z>=spec_atan[k] ) { 
3573     z=z-spec_atan[k]; t=x;
3574     x=t+y / two_to_the(k);
3575     y=y-t / two_to_the(k);
3576   }
3577   incr(k);
3578 }
3579 if ( y<0 ) y=0 /* this precaution may never be needed */
3580
3581 @ And now let's complete our collection of numeric utility routines
3582 by considering random number generation.
3583 \MP\ generates pseudo-random numbers with the additive scheme recommended
3584 in Section 3.6 of {\sl The Art of Computer Programming}; however, the
3585 results are random fractions between 0 and |fraction_one-1|, inclusive.
3586
3587 There's an auxiliary array |randoms| that contains 55 pseudo-random
3588 fractions. Using the recurrence $x_n=(x_{n-55}-x_{n-31})\bmod 2^{28}$,
3589 we generate batches of 55 new $x_n$'s at a time by calling |new_randoms|.
3590 The global variable |j_random| tells which element has most recently
3591 been consumed.
3592 The global variable |sys_random_seed| was introduced in version 0.9,
3593 for the sole reason of stressing the fact that the initial value of the
3594 random seed is system-dependant. The pascal code below will initialize
3595 this variable to |(internal[mp_time] div unity)+internal[mp_day]|, but this 
3596 is not good enough on modern fast machines that are capable of running
3597 multiple MetaPost processes within the same second.
3598 @^system dependencies@>
3599
3600 @<Glob...@>=
3601 fraction randoms[55]; /* the last 55 random values generated */
3602 int j_random; /* the number of unused |randoms| */
3603 scaled sys_random_seed; /* the default random seed */
3604
3605 @ @<Exported types@>=
3606 typedef int (*mp_get_random_seed_command)(MP mp);
3607
3608 @ @<Glob...@>=
3609 mp_get_random_seed_command get_random_seed;
3610
3611 @ @<Option variables@>=
3612 mp_get_random_seed_command get_random_seed;
3613
3614 @ @<Allocate or initialize ...@>=
3615 set_callback_option(get_random_seed);
3616
3617 @ @<Internal library declarations@>=
3618 int mp_get_random_seed (MP mp);
3619
3620 @ @c 
3621 int mp_get_random_seed (MP mp) {
3622   return (mp->internal[mp_time] / unity)+mp->internal[mp_day];
3623 }
3624
3625 @ To consume a random fraction, the program below will say `|next_random|'
3626 and then it will fetch |randoms[j_random]|.
3627
3628 @d next_random { if ( mp->j_random==0 ) mp_new_randoms(mp);
3629   else decr(mp->j_random); }
3630
3631 @c 
3632 void mp_new_randoms (MP mp) {
3633   int k; /* index into |randoms| */
3634   fraction x; /* accumulator */
3635   for (k=0;k<=23;k++) { 
3636    x=mp->randoms[k]-mp->randoms[k+31];
3637     if ( x<0 ) x=x+fraction_one;
3638     mp->randoms[k]=x;
3639   }
3640   for (k=24;k<= 54;k++){ 
3641     x=mp->randoms[k]-mp->randoms[k-24];
3642     if ( x<0 ) x=x+fraction_one;
3643     mp->randoms[k]=x;
3644   }
3645   mp->j_random=54;
3646 }
3647
3648 @ @<Declarations@>=
3649 void mp_init_randoms (MP mp,scaled seed);
3650
3651 @ To initialize the |randoms| table, we call the following routine.
3652
3653 @c 
3654 void mp_init_randoms (MP mp,scaled seed) {
3655   fraction j,jj,k; /* more or less random integers */
3656   int i; /* index into |randoms| */
3657   j=abs(seed);
3658   while ( j>=fraction_one ) j=halfp(j);
3659   k=1;
3660   for (i=0;i<=54;i++ ){ 
3661     jj=k; k=j-k; j=jj;
3662     if ( k<0 ) k=k+fraction_one;
3663     mp->randoms[(i*21)% 55]=j;
3664   }
3665   mp_new_randoms(mp); 
3666   mp_new_randoms(mp); 
3667   mp_new_randoms(mp); /* ``warm up'' the array */
3668 }
3669
3670 @ To produce a uniform random number in the range |0<=u<x| or |0>=u>x|
3671 or |0=u=x|, given a |scaled| value~|x|, we proceed as shown here.
3672
3673 Note that the call of |take_fraction| will produce the values 0 and~|x|
3674 with about half the probability that it will produce any other particular
3675 values between 0 and~|x|, because it rounds its answers.
3676
3677 @c 
3678 scaled mp_unif_rand (MP mp,scaled x) {
3679   scaled y; /* trial value */
3680   next_random; y=mp_take_fraction(mp, abs(x),mp->randoms[mp->j_random]);
3681   if ( y==abs(x) ) return 0;
3682   else if ( x>0 ) return y;
3683   else return (-y);
3684 }
3685
3686 @ Finally, a normal deviate with mean zero and unit standard deviation
3687 can readily be obtained with the ratio method (Algorithm 3.4.1R in
3688 {\sl The Art of Computer Programming\/}).
3689
3690 @c 
3691 scaled mp_norm_rand (MP mp) {
3692   integer x,u,l; /* what the book would call $2^{16}X$, $2^{28}U$, and $-2^{24}\ln U$ */
3693   do { 
3694     do {  
3695       next_random;
3696       x=mp_take_fraction(mp, 112429,mp->randoms[mp->j_random]-fraction_half);
3697       /* $2^{16}\sqrt{8/e}\approx 112428.82793$ */
3698       next_random; u=mp->randoms[mp->j_random];
3699     } while (abs(x)>=u);
3700     x=mp_make_fraction(mp, x,u);
3701     l=139548960-mp_m_log(mp, u); /* $2^{24}\cdot12\ln2\approx139548959.6165$ */
3702   } while (mp_ab_vs_cd(mp, 1024,l,x,x)<0);
3703   return x;
3704 }
3705
3706 @* \[9] Packed data.
3707 In order to make efficient use of storage space, \MP\ bases its major data
3708 structures on a |memory_word|, which contains either a (signed) integer,
3709 possibly scaled, or a small number of fields that are one half or one
3710 quarter of the size used for storing integers.
3711
3712 If |x| is a variable of type |memory_word|, it contains up to four
3713 fields that can be referred to as follows:
3714 $$\vbox{\halign{\hfil#&#\hfil&#\hfil\cr
3715 |x|&.|int|&(an |integer|)\cr
3716 |x|&.|sc|\qquad&(a |scaled| integer)\cr
3717 |x.hh.lh|, |x.hh|&.|rh|&(two halfword fields)\cr
3718 |x.hh.b0|, |x.hh.b1|, |x.hh|&.|rh|&(two quarterword fields, one halfword
3719   field)\cr
3720 |x.qqqq.b0|, |x.qqqq.b1|, |x.qqqq|&.|b2|, |x.qqqq.b3|\hskip-100pt
3721   &\qquad\qquad\qquad(four quarterword fields)\cr}}$$
3722 This is somewhat cumbersome to write, and not very readable either, but
3723 macros will be used to make the notation shorter and more transparent.
3724 The code below gives a formal definition of |memory_word| and
3725 its subsidiary types, using packed variant records. \MP\ makes no
3726 assumptions about the relative positions of the fields within a word.
3727
3728 @d max_quarterword 0x3FFF /* largest allowable value in a |quarterword| */
3729 @d max_halfword 0xFFFFFFF /* largest allowable value in a |halfword| */
3730
3731 @ Here are the inequalities that the quarterword and halfword values
3732 must satisfy (or rather, the inequalities that they mustn't satisfy):
3733
3734 @<Check the ``constant''...@>=
3735 if (mp->ini_version) {
3736   if ( mp->mem_max!=mp->mem_top ) mp->bad=8;
3737 } else {
3738   if ( mp->mem_max<mp->mem_top ) mp->bad=8;
3739 }
3740 if ( max_quarterword<255 ) mp->bad=9;
3741 if ( max_halfword<65535 ) mp->bad=10;
3742 if ( max_quarterword>max_halfword ) mp->bad=11;
3743 if ( mp->mem_max>=max_halfword ) mp->bad=12;
3744 if ( mp->max_strings>max_halfword ) mp->bad=13;
3745
3746 @ The macros |qi| and |qo| are used for input to and output 
3747 from quarterwords. These are legacy macros.
3748 @^system dependencies@>
3749
3750 @d qo(A) (A) /* to read eight bits from a quarterword */
3751 @d qi(A) (A) /* to store eight bits in a quarterword */
3752
3753 @ The reader should study the following definitions closely:
3754 @^system dependencies@>
3755
3756 @d sc cint /* |scaled| data is equivalent to |integer| */
3757
3758 @<Types...@>=
3759 typedef short quarterword; /* 1/4 of a word */
3760 typedef int halfword; /* 1/2 of a word */
3761 typedef union {
3762   struct {
3763     halfword RH, LH;
3764   } v;
3765   struct { /* Make B0,B1 overlap the most significant bytes of LH.  */
3766     halfword junk;
3767     quarterword B0, B1;
3768   } u;
3769 } two_halves;
3770 typedef struct {
3771   struct {
3772     quarterword B2, B3, B0, B1;
3773   } u;
3774 } four_quarters;
3775 typedef union {
3776   two_halves hh;
3777   integer cint;
3778   four_quarters qqqq;
3779 } memory_word;
3780 #define b0 u.B0
3781 #define b1 u.B1
3782 #define b2 u.B2
3783 #define b3 u.B3
3784 #define rh v.RH
3785 #define lh v.LH
3786
3787 @ When debugging, we may want to print a |memory_word| without knowing
3788 what type it is; so we print it in all modes.
3789 @^dirty \PASCAL@>@^debugging@>
3790
3791 @c 
3792 void mp_print_word (MP mp,memory_word w) {
3793   /* prints |w| in all ways */
3794   mp_print_int(mp, w.cint); mp_print_char(mp, ' ');
3795   mp_print_scaled(mp, w.sc); mp_print_char(mp, ' '); 
3796   mp_print_scaled(mp, w.sc / 010000); mp_print_ln(mp);
3797   mp_print_int(mp, w.hh.lh); mp_print_char(mp, '='); 
3798   mp_print_int(mp, w.hh.b0); mp_print_char(mp, ':');
3799   mp_print_int(mp, w.hh.b1); mp_print_char(mp, ';'); 
3800   mp_print_int(mp, w.hh.rh); mp_print_char(mp, ' ');
3801   mp_print_int(mp, w.qqqq.b0); mp_print_char(mp, ':'); 
3802   mp_print_int(mp, w.qqqq.b1); mp_print_char(mp, ':');
3803   mp_print_int(mp, w.qqqq.b2); mp_print_char(mp, ':'); 
3804   mp_print_int(mp, w.qqqq.b3);
3805 }
3806
3807
3808 @* \[10] Dynamic memory allocation.
3809
3810 The \MP\ system does nearly all of its own memory allocation, so that it
3811 can readily be transported into environments that do not have automatic
3812 facilities for strings, garbage collection, etc., and so that it can be in
3813 control of what error messages the user receives. The dynamic storage
3814 requirements of \MP\ are handled by providing a large array |mem| in
3815 which consecutive blocks of words are used as nodes by the \MP\ routines.
3816
3817 Pointer variables are indices into this array, or into another array
3818 called |eqtb| that will be explained later. A pointer variable might
3819 also be a special flag that lies outside the bounds of |mem|, so we
3820 allow pointers to assume any |halfword| value. The minimum memory
3821 index represents a null pointer.
3822
3823 @d null 0 /* the null pointer */
3824 @d mp_void (null+1) /* a null pointer different from |null| */
3825
3826
3827 @<Types...@>=
3828 typedef halfword pointer; /* a flag or a location in |mem| or |eqtb| */
3829
3830 @ The |mem| array is divided into two regions that are allocated separately,
3831 but the dividing line between these two regions is not fixed; they grow
3832 together until finding their ``natural'' size in a particular job.
3833 Locations less than or equal to |lo_mem_max| are used for storing
3834 variable-length records consisting of two or more words each. This region
3835 is maintained using an algorithm similar to the one described in exercise
3836 2.5--19 of {\sl The Art of Computer Programming}. However, no size field
3837 appears in the allocated nodes; the program is responsible for knowing the
3838 relevant size when a node is freed. Locations greater than or equal to
3839 |hi_mem_min| are used for storing one-word records; a conventional
3840 \.{AVAIL} stack is used for allocation in this region.
3841
3842 Locations of |mem| between |0| and |mem_top| may be dumped as part
3843 of preloaded format files, by the \.{INIMP} preprocessor.
3844 @.INIMP@>
3845 Production versions of \MP\ may extend the memory at the top end in order to
3846 provide more space; these locations, between |mem_top| and |mem_max|,
3847 are always used for single-word nodes.
3848
3849 The key pointers that govern |mem| allocation have a prescribed order:
3850 $$\hbox{|null=0<lo_mem_max<hi_mem_min<mem_top<=mem_end<=mem_max|.}$$
3851
3852 @<Glob...@>=
3853 memory_word *mem; /* the big dynamic storage area */
3854 pointer lo_mem_max; /* the largest location of variable-size memory in use */
3855 pointer hi_mem_min; /* the smallest location of one-word memory in use */
3856
3857
3858
3859 @d xfree(A) do { mp_xfree(A); A=NULL; } while (0)
3860 @d xrealloc(P,A,B) mp_xrealloc(mp,P,A,B)
3861 @d xmalloc(A,B)  mp_xmalloc(mp,A,B)
3862 @d xstrdup(A)  mp_xstrdup(mp,A)
3863 @d XREALLOC(a,b,c) a = xrealloc(a,(b+1),sizeof(c));
3864
3865 @<Declare helpers@>=
3866 void mp_xfree (void *x);
3867 void *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) ;
3868 void *mp_xmalloc (MP mp, size_t nmem, size_t size) ;
3869 char *mp_xstrdup(MP mp, const char *s);
3870
3871 @ The |max_size_test| guards against overflow, on the assumption that
3872 |size_t| is at least 31bits wide.
3873
3874 @d max_size_test 0x7FFFFFFF
3875
3876 @c
3877 void mp_xfree (void *x) {
3878   if (x!=NULL) free(x);
3879 }
3880 void  *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) {
3881   void *w ; 
3882   if ((max_size_test/size)<nmem) {
3883     fprintf(stderr,"Memory size overflow!\n");
3884     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3885   }
3886   w = realloc (p,(nmem*size));
3887   if (w==NULL) {
3888     fprintf(stderr,"Out of memory!\n");
3889     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3890   }
3891   return w;
3892 }
3893 void  *mp_xmalloc (MP mp, size_t nmem, size_t size) {
3894   void *w;
3895   if ((max_size_test/size)<nmem) {
3896     fprintf(stderr,"Memory size overflow!\n");
3897     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3898   }
3899   w = malloc (nmem*size);
3900   if (w==NULL) {
3901     fprintf(stderr,"Out of memory!\n");
3902     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3903   }
3904   return w;
3905 }
3906 char *mp_xstrdup(MP mp, const char *s) {
3907   char *w; 
3908   if (s==NULL)
3909     return NULL;
3910   w = strdup(s);
3911   if (w==NULL) {
3912     fprintf(stderr,"Out of memory!\n");
3913     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3914   }
3915   return w;
3916 }
3917
3918
3919
3920 @<Allocate or initialize ...@>=
3921 mp->mem = xmalloc ((mp->mem_max+1),sizeof (memory_word));
3922 memset(mp->mem,0,(mp->mem_max+1)*sizeof (memory_word));
3923
3924 @ @<Dealloc variables@>=
3925 xfree(mp->mem);
3926
3927 @ Users who wish to study the memory requirements of particular applications can
3928 can use optional special features that keep track of current and
3929 maximum memory usage. When code between the delimiters |stat| $\ldots$
3930 |tats| is not ``commented out,'' \MP\ will run a bit slower but it will
3931 report these statistics when |mp_tracing_stats| is positive.
3932
3933 @<Glob...@>=
3934 integer var_used; integer dyn_used; /* how much memory is in use */
3935
3936 @ Let's consider the one-word memory region first, since it's the
3937 simplest. The pointer variable |mem_end| holds the highest-numbered location
3938 of |mem| that has ever been used. The free locations of |mem| that
3939 occur between |hi_mem_min| and |mem_end|, inclusive, are of type
3940 |two_halves|, and we write |info(p)| and |link(p)| for the |lh|
3941 and |rh| fields of |mem[p]| when it is of this type. The single-word
3942 free locations form a linked list
3943 $$|avail|,\;\hbox{|link(avail)|},\;\hbox{|link(link(avail))|},\;\ldots$$
3944 terminated by |null|.
3945
3946 @d link(A)   mp->mem[(A)].hh.rh /* the |link| field of a memory word */
3947 @d info(A)   mp->mem[(A)].hh.lh /* the |info| field of a memory word */
3948
3949 @<Glob...@>=
3950 pointer avail; /* head of the list of available one-word nodes */
3951 pointer mem_end; /* the last one-word node used in |mem| */
3952
3953 @ If one-word memory is exhausted, it might mean that the user has forgotten
3954 a token like `\&{enddef}' or `\&{endfor}'. We will define some procedures
3955 later that try to help pinpoint the trouble.
3956
3957 @c 
3958 @<Declare the procedure called |show_token_list|@>;
3959 @<Declare the procedure called |runaway|@>
3960
3961 @ The function |get_avail| returns a pointer to a new one-word node whose
3962 |link| field is null. However, \MP\ will halt if there is no more room left.
3963 @^inner loop@>
3964
3965 @c 
3966 pointer mp_get_avail (MP mp) { /* single-word node allocation */
3967   pointer p; /* the new node being got */
3968   p=mp->avail; /* get top location in the |avail| stack */
3969   if ( p!=null ) {
3970     mp->avail=link(mp->avail); /* and pop it off */
3971   } else if ( mp->mem_end<mp->mem_max ) { /* or go into virgin territory */
3972     incr(mp->mem_end); p=mp->mem_end;
3973   } else { 
3974     decr(mp->hi_mem_min); p=mp->hi_mem_min;
3975     if ( mp->hi_mem_min<=mp->lo_mem_max ) { 
3976       mp_runaway(mp); /* if memory is exhausted, display possible runaway text */
3977       mp_overflow(mp, "main memory size",mp->mem_max);
3978       /* quit; all one-word nodes are busy */
3979 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
3980     }
3981   }
3982   link(p)=null; /* provide an oft-desired initialization of the new node */
3983   incr(mp->dyn_used);/* maintain statistics */
3984   return p;
3985 };
3986
3987 @ Conversely, a one-word node is recycled by calling |free_avail|.
3988
3989 @d free_avail(A)  /* single-word node liberation */
3990   { link((A))=mp->avail; mp->avail=(A); decr(mp->dyn_used);  }
3991
3992 @ There's also a |fast_get_avail| routine, which saves the procedure-call
3993 overhead at the expense of extra programming. This macro is used in
3994 the places that would otherwise account for the most calls of |get_avail|.
3995 @^inner loop@>
3996
3997 @d fast_get_avail(A) { 
3998   (A)=mp->avail; /* avoid |get_avail| if possible, to save time */
3999   if ( (A)==null ) { (A)=mp_get_avail(mp); } 
4000   else { mp->avail=link((A)); link((A))=null;  incr(mp->dyn_used); }
4001   }
4002
4003 @ The available-space list that keeps track of the variable-size portion
4004 of |mem| is a nonempty, doubly-linked circular list of empty nodes,
4005 pointed to by the roving pointer |rover|.
4006
4007 Each empty node has size 2 or more; the first word contains the special
4008 value |max_halfword| in its |link| field and the size in its |info| field;
4009 the second word contains the two pointers for double linking.
4010
4011 Each nonempty node also has size 2 or more. Its first word is of type
4012 |two_halves|\kern-1pt, and its |link| field is never equal to |max_halfword|.
4013 Otherwise there is complete flexibility with respect to the contents
4014 of its other fields and its other words.
4015
4016 (We require |mem_max<max_halfword| because terrible things can happen
4017 when |max_halfword| appears in the |link| field of a nonempty node.)
4018
4019 @d empty_flag   max_halfword /* the |link| of an empty variable-size node */
4020 @d is_empty(A)   (link((A))==empty_flag) /* tests for empty node */
4021 @d node_size   info /* the size field in empty variable-size nodes */
4022 @d llink(A)   info((A)+1) /* left link in doubly-linked list of empty nodes */
4023 @d rlink(A)   link((A)+1) /* right link in doubly-linked list of empty nodes */
4024
4025 @<Glob...@>=
4026 pointer rover; /* points to some node in the list of empties */
4027
4028 @ A call to |get_node| with argument |s| returns a pointer to a new node
4029 of size~|s|, which must be 2~or more. The |link| field of the first word
4030 of this new node is set to null. An overflow stop occurs if no suitable
4031 space exists.
4032
4033 If |get_node| is called with $s=2^{30}$, it simply merges adjacent free
4034 areas and returns the value |max_halfword|.
4035
4036 @<Declarations@>=
4037 pointer mp_get_node (MP mp,integer s) ;
4038
4039 @ @c 
4040 pointer mp_get_node (MP mp,integer s) { /* variable-size node allocation */
4041   pointer p; /* the node currently under inspection */
4042   pointer q;  /* the node physically after node |p| */
4043   integer r; /* the newly allocated node, or a candidate for this honor */
4044   integer t,tt; /* temporary registers */
4045 @^inner loop@>
4046  RESTART: 
4047   p=mp->rover; /* start at some free node in the ring */
4048   do {  
4049     @<Try to allocate within node |p| and its physical successors,
4050      and |goto found| if allocation was possible@>;
4051     if (rlink(p)==null || rlink(p)==p) {
4052       print_err("Free list garbled");
4053       help3("I found an entry in the list of free nodes that links")
4054        ("badly. I will try to ignore the broken link, but something")
4055        ("is seriously amiss. It is wise to warn the maintainers.")
4056           mp_error(mp);
4057       rlink(p)=mp->rover;
4058     }
4059         p=rlink(p); /* move to the next node in the ring */
4060   } while (p!=mp->rover); /* repeat until the whole list has been traversed */
4061   if ( s==010000000000 ) { 
4062     return max_halfword;
4063   };
4064   if ( mp->lo_mem_max+2<mp->hi_mem_min ) {
4065     if ( mp->lo_mem_max+2<=max_halfword ) {
4066       @<Grow more variable-size memory and |goto restart|@>;
4067     }
4068   }
4069   mp_overflow(mp, "main memory size",mp->mem_max);
4070   /* sorry, nothing satisfactory is left */
4071 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
4072 FOUND: 
4073   link(r)=null; /* this node is now nonempty */
4074   mp->var_used+=s; /* maintain usage statistics */
4075   return r;
4076 }
4077
4078 @ The lower part of |mem| grows by 1000 words at a time, unless
4079 we are very close to going under. When it grows, we simply link
4080 a new node into the available-space list. This method of controlled
4081 growth helps to keep the |mem| usage consecutive when \MP\ is
4082 implemented on ``virtual memory'' systems.
4083 @^virtual memory@>
4084
4085 @<Grow more variable-size memory and |goto restart|@>=
4086
4087   if ( mp->hi_mem_min-mp->lo_mem_max>=1998 ) {
4088     t=mp->lo_mem_max+1000;
4089   } else {
4090     t=mp->lo_mem_max+1+(mp->hi_mem_min-mp->lo_mem_max) / 2; 
4091     /* |lo_mem_max+2<=t<hi_mem_min| */
4092   }
4093   if ( t>max_halfword ) t=max_halfword;
4094   p=llink(mp->rover); q=mp->lo_mem_max; rlink(p)=q; llink(mp->rover)=q;
4095   rlink(q)=mp->rover; llink(q)=p; link(q)=empty_flag; 
4096   node_size(q)=t-mp->lo_mem_max;
4097   mp->lo_mem_max=t; link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4098   mp->rover=q; 
4099   goto RESTART;
4100 }
4101
4102 @ @<Try to allocate...@>=
4103 q=p+node_size(p); /* find the physical successor */
4104 while ( is_empty(q) ) { /* merge node |p| with node |q| */
4105   t=rlink(q); tt=llink(q);
4106 @^inner loop@>
4107   if ( q==mp->rover ) mp->rover=t;
4108   llink(t)=tt; rlink(tt)=t;
4109   q=q+node_size(q);
4110 }
4111 r=q-s;
4112 if ( r>p+1 ) {
4113   @<Allocate from the top of node |p| and |goto found|@>;
4114 }
4115 if ( r==p ) { 
4116   if ( rlink(p)!=p ) {
4117     @<Allocate entire node |p| and |goto found|@>;
4118   }
4119 }
4120 node_size(p)=q-p /* reset the size in case it grew */
4121
4122 @ @<Allocate from the top...@>=
4123
4124   node_size(p)=r-p; /* store the remaining size */
4125   mp->rover=p; /* start searching here next time */
4126   goto FOUND;
4127 }
4128
4129 @ Here we delete node |p| from the ring, and let |rover| rove around.
4130
4131 @<Allocate entire...@>=
4132
4133   mp->rover=rlink(p); t=llink(p);
4134   llink(mp->rover)=t; rlink(t)=mp->rover;
4135   goto FOUND;
4136 }
4137
4138 @ Conversely, when some variable-size node |p| of size |s| is no longer needed,
4139 the operation |free_node(p,s)| will make its words available, by inserting
4140 |p| as a new empty node just before where |rover| now points.
4141
4142 @<Declarations@>=
4143 void mp_free_node (MP mp, pointer p, halfword s) ;
4144
4145 @ @c 
4146 void mp_free_node (MP mp, pointer p, halfword s) { /* variable-size node
4147   liberation */
4148   pointer q; /* |llink(rover)| */
4149   node_size(p)=s; link(p)=empty_flag;
4150 @^inner loop@>
4151   q=llink(mp->rover); llink(p)=q; rlink(p)=mp->rover; /* set both links */
4152   llink(mp->rover)=p; rlink(q)=p; /* insert |p| into the ring */
4153   mp->var_used-=s; /* maintain statistics */
4154 }
4155
4156 @ Just before \.{INIMP} writes out the memory, it sorts the doubly linked
4157 available space list. The list is probably very short at such times, so a
4158 simple insertion sort is used. The smallest available location will be
4159 pointed to by |rover|, the next-smallest by |rlink(rover)|, etc.
4160
4161 @c 
4162 void mp_sort_avail (MP mp) { /* sorts the available variable-size nodes
4163   by location */
4164   pointer p,q,r; /* indices into |mem| */
4165   pointer old_rover; /* initial |rover| setting */
4166   p=mp_get_node(mp, 010000000000); /* merge adjacent free areas */
4167   p=rlink(mp->rover); rlink(mp->rover)=max_halfword; old_rover=mp->rover;
4168   while ( p!=old_rover ) {
4169     @<Sort |p| into the list starting at |rover|
4170      and advance |p| to |rlink(p)|@>;
4171   }
4172   p=mp->rover;
4173   while ( rlink(p)!=max_halfword ) { 
4174     llink(rlink(p))=p; p=rlink(p);
4175   };
4176   rlink(p)=mp->rover; llink(mp->rover)=p;
4177 }
4178
4179 @ The following |while| loop is guaranteed to
4180 terminate, since the list that starts at
4181 |rover| ends with |max_halfword| during the sorting procedure.
4182
4183 @<Sort |p|...@>=
4184 if ( p<mp->rover ) { 
4185   q=p; p=rlink(q); rlink(q)=mp->rover; mp->rover=q;
4186 } else  { 
4187   q=mp->rover;
4188   while ( rlink(q)<p ) q=rlink(q);
4189   r=rlink(p); rlink(p)=rlink(q); rlink(q)=p; p=r;
4190 }
4191
4192 @* \[11] Memory layout.
4193 Some areas of |mem| are dedicated to fixed usage, since static allocation is
4194 more efficient than dynamic allocation when we can get away with it. For
4195 example, locations |0| to |1| are always used to store a
4196 two-word dummy token whose second word is zero.
4197 The following macro definitions accomplish the static allocation by giving
4198 symbolic names to the fixed positions. Static variable-size nodes appear
4199 in locations |0| through |lo_mem_stat_max|, and static single-word nodes
4200 appear in locations |hi_mem_stat_min| through |mem_top|, inclusive.
4201
4202 @d null_dash (2) /* the first two words are reserved for a null value */
4203 @d dep_head (null_dash+3) /* we will define |dash_node_size=3| */
4204 @d zero_val (dep_head+2) /* two words for a permanently zero value */
4205 @d temp_val (zero_val+2) /* two words for a temporary value node */
4206 @d end_attr temp_val /* we use |end_attr+2| only */
4207 @d inf_val (end_attr+2) /* and |inf_val+1| only */
4208 @d test_pen (inf_val+2)
4209   /* nine words for a pen used when testing the turning number */
4210 @d bad_vardef (test_pen+9) /* two words for \&{vardef} error recovery */
4211 @d lo_mem_stat_max (bad_vardef+1)  /* largest statically
4212   allocated word in the variable-size |mem| */
4213 @#
4214 @d sentinel mp->mem_top /* end of sorted lists */
4215 @d temp_head (mp->mem_top-1) /* head of a temporary list of some kind */
4216 @d hold_head (mp->mem_top-2) /* head of a temporary list of another kind */
4217 @d spec_head (mp->mem_top-3) /* head of a list of unprocessed \&{special} items */
4218 @d hi_mem_stat_min (mp->mem_top-3) /* smallest statically allocated word in
4219   the one-word |mem| */
4220
4221 @ The following code gets the dynamic part of |mem| off to a good start,
4222 when \MP\ is initializing itself the slow way.
4223
4224 @<Initialize table entries (done by \.{INIMP} only)@>=
4225 @^data structure assumptions@>
4226 mp->rover=lo_mem_stat_max+1; /* initialize the dynamic memory */
4227 link(mp->rover)=empty_flag;
4228 node_size(mp->rover)=1000; /* which is a 1000-word available node */
4229 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
4230 mp->lo_mem_max=mp->rover+1000; 
4231 link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4232 for (k=hi_mem_stat_min;k<=(int)mp->mem_top;k++) {
4233   mp->mem[k]=mp->mem[mp->lo_mem_max]; /* clear list heads */
4234 }
4235 mp->avail=null; mp->mem_end=mp->mem_top;
4236 mp->hi_mem_min=hi_mem_stat_min; /* initialize the one-word memory */
4237 mp->var_used=lo_mem_stat_max+1; 
4238 mp->dyn_used=mp->mem_top+1-(hi_mem_stat_min);  /* initialize statistics */
4239 @<Initialize a pen at |test_pen| so that it fits in nine words@>;
4240
4241 @ The procedure |flush_list(p)| frees an entire linked list of one-word
4242 nodes that starts at a given position, until coming to |sentinel| or a
4243 pointer that is not in the one-word region. Another procedure,
4244 |flush_node_list|, frees an entire linked list of one-word and two-word
4245 nodes, until coming to a |null| pointer.
4246 @^inner loop@>
4247
4248 @c 
4249 void mp_flush_list (MP mp,pointer p) { /* makes list of single-word nodes  available */
4250   pointer q,r; /* list traversers */
4251   if ( p>=mp->hi_mem_min ) if ( p!=sentinel ) { 
4252     r=p;
4253     do {  
4254       q=r; r=link(r); 
4255       decr(mp->dyn_used);
4256       if ( r<mp->hi_mem_min ) break;
4257     } while (r!=sentinel);
4258   /* now |q| is the last node on the list */
4259     link(q)=mp->avail; mp->avail=p;
4260   }
4261 }
4262 @#
4263 void mp_flush_node_list (MP mp,pointer p) {
4264   pointer q; /* the node being recycled */
4265   while ( p!=null ){ 
4266     q=p; p=link(p);
4267     if ( q<mp->hi_mem_min ) 
4268       mp_free_node(mp, q,2);
4269     else 
4270       free_avail(q);
4271   }
4272 }
4273
4274 @ If \MP\ is extended improperly, the |mem| array might get screwed up.
4275 For example, some pointers might be wrong, or some ``dead'' nodes might not
4276 have been freed when the last reference to them disappeared. Procedures
4277 |check_mem| and |search_mem| are available to help diagnose such
4278 problems. These procedures make use of two arrays called |free| and
4279 |was_free| that are present only if \MP's debugging routines have
4280 been included. (You may want to decrease the size of |mem| while you
4281 @^debugging@>
4282 are debugging.)
4283
4284 Because |boolean|s are typedef-d as ints, it is better to use
4285 unsigned chars here.
4286
4287 @<Glob...@>=
4288 unsigned char *free; /* free cells */
4289 unsigned char *was_free; /* previously free cells */
4290 pointer was_mem_end; pointer was_lo_max; pointer was_hi_min;
4291   /* previous |mem_end|, |lo_mem_max|,and |hi_mem_min| */
4292 boolean panicking; /* do we want to check memory constantly? */
4293
4294 @ @<Allocate or initialize ...@>=
4295 mp->free = xmalloc ((mp->mem_max+1),sizeof (unsigned char));
4296 mp->was_free = xmalloc ((mp->mem_max+1), sizeof (unsigned char));
4297
4298 @ @<Dealloc variables@>=
4299 xfree(mp->free);
4300 xfree(mp->was_free);
4301
4302 @ @<Allocate or ...@>=
4303 mp->was_mem_end=0; /* indicate that everything was previously free */
4304 mp->was_lo_max=0; mp->was_hi_min=mp->mem_max;
4305 mp->panicking=false;
4306
4307 @ @<Declare |mp_reallocate| functions@>=
4308 void mp_reallocate_memory(MP mp, int l) ;
4309
4310 @ @c
4311 void mp_reallocate_memory(MP mp, int l) {
4312    XREALLOC(mp->free,     l, unsigned char);
4313    XREALLOC(mp->was_free, l, unsigned char);
4314    if (mp->mem) {
4315          int newarea = l-mp->mem_max;
4316      XREALLOC(mp->mem,      l, memory_word);
4317      memset (mp->mem+(mp->mem_max+1),0,sizeof(memory_word)*(newarea));
4318    } else {
4319      XREALLOC(mp->mem,      l, memory_word);
4320      memset(mp->mem,0,sizeof(memory_word)*(l+1));
4321    }
4322    mp->mem_max = l;
4323    if (mp->ini_version) 
4324      mp->mem_top = l;
4325 }
4326
4327
4328
4329 @ Procedure |check_mem| makes sure that the available space lists of
4330 |mem| are well formed, and it optionally prints out all locations
4331 that are reserved now but were free the last time this procedure was called.
4332
4333 @c 
4334 void mp_check_mem (MP mp,boolean print_locs ) {
4335   pointer p,q,r; /* current locations of interest in |mem| */
4336   boolean clobbered; /* is something amiss? */
4337   for (p=0;p<=mp->lo_mem_max;p++) {
4338     mp->free[p]=false; /* you can probably do this faster */
4339   }
4340   for (p=mp->hi_mem_min;p<= mp->mem_end;p++) {
4341     mp->free[p]=false; /* ditto */
4342   }
4343   @<Check single-word |avail| list@>;
4344   @<Check variable-size |avail| list@>;
4345   @<Check flags of unavailable nodes@>;
4346   @<Check the list of linear dependencies@>;
4347   if ( print_locs ) {
4348     @<Print newly busy locations@>;
4349   }
4350   memcpy(mp->was_free,mp->free, sizeof(char)*(mp->mem_end+1));
4351   mp->was_mem_end=mp->mem_end; 
4352   mp->was_lo_max=mp->lo_mem_max; 
4353   mp->was_hi_min=mp->hi_mem_min;
4354 }
4355
4356 @ @<Check single-word...@>=
4357 p=mp->avail; q=null; clobbered=false;
4358 while ( p!=null ) { 
4359   if ( (p>mp->mem_end)||(p<mp->hi_mem_min) ) clobbered=true;
4360   else if ( mp->free[p] ) clobbered=true;
4361   if ( clobbered ) { 
4362     mp_print_nl(mp, "AVAIL list clobbered at ");
4363 @.AVAIL list clobbered...@>
4364     mp_print_int(mp, q); break;
4365   }
4366   mp->free[p]=true; q=p; p=link(q);
4367 }
4368
4369 @ @<Check variable-size...@>=
4370 p=mp->rover; q=null; clobbered=false;
4371 do {  
4372   if ( (p>=mp->lo_mem_max)||(p<0) ) clobbered=true;
4373   else if ( (rlink(p)>=mp->lo_mem_max)||(rlink(p)<0) ) clobbered=true;
4374   else if (  !(is_empty(p))||(node_size(p)<2)||
4375    (p+node_size(p)>mp->lo_mem_max)|| (llink(rlink(p))!=p) ) clobbered=true;
4376   if ( clobbered ) { 
4377     mp_print_nl(mp, "Double-AVAIL list clobbered at ");
4378 @.Double-AVAIL list clobbered...@>
4379     mp_print_int(mp, q); break;
4380   }
4381   for (q=p;q<=p+node_size(p)-1;q++) { /* mark all locations free */
4382     if ( mp->free[q] ) { 
4383       mp_print_nl(mp, "Doubly free location at ");
4384 @.Doubly free location...@>
4385       mp_print_int(mp, q); break;
4386     }
4387     mp->free[q]=true;
4388   }
4389   q=p; p=rlink(p);
4390 } while (p!=mp->rover)
4391
4392
4393 @ @<Check flags...@>=
4394 p=0;
4395 while ( p<=mp->lo_mem_max ) { /* node |p| should not be empty */
4396   if ( is_empty(p) ) {
4397     mp_print_nl(mp, "Bad flag at "); mp_print_int(mp, p);
4398 @.Bad flag...@>
4399   }
4400   while ( (p<=mp->lo_mem_max) && ! mp->free[p] ) incr(p);
4401   while ( (p<=mp->lo_mem_max) && mp->free[p] ) incr(p);
4402 }
4403
4404 @ @<Print newly busy...@>=
4405
4406   @<Do intialization required before printing new busy locations@>;
4407   mp_print_nl(mp, "New busy locs:");
4408 @.New busy locs@>
4409   for (p=0;p<= mp->lo_mem_max;p++ ) {
4410     if ( ! mp->free[p] && ((p>mp->was_lo_max) || mp->was_free[p]) ) {
4411       @<Indicate that |p| is a new busy location@>;
4412     }
4413   }
4414   for (p=mp->hi_mem_min;p<=mp->mem_end;p++ ) {
4415     if ( ! mp->free[p] &&
4416         ((p<mp->was_hi_min) || (p>mp->was_mem_end) || mp->was_free[p]) ) {
4417       @<Indicate that |p| is a new busy location@>;
4418     }
4419   }
4420   @<Finish printing new busy locations@>;
4421 }
4422
4423 @ There might be many new busy locations so we are careful to print contiguous
4424 blocks compactly.  During this operation |q| is the last new busy location and
4425 |r| is the start of the block containing |q|.
4426
4427 @<Indicate that |p| is a new busy location@>=
4428
4429   if ( p>q+1 ) { 
4430     if ( q>r ) { 
4431       mp_print(mp, ".."); mp_print_int(mp, q);
4432     }
4433     mp_print_char(mp, ' '); mp_print_int(mp, p);
4434     r=p;
4435   }
4436   q=p;
4437 }
4438
4439 @ @<Do intialization required before printing new busy locations@>=
4440 q=mp->mem_max; r=mp->mem_max
4441
4442 @ @<Finish printing new busy locations@>=
4443 if ( q>r ) { 
4444   mp_print(mp, ".."); mp_print_int(mp, q);
4445 }
4446
4447 @ The |search_mem| procedure attempts to answer the question ``Who points
4448 to node~|p|?'' In doing so, it fetches |link| and |info| fields of |mem|
4449 that might not be of type |two_halves|. Strictly speaking, this is
4450 @^dirty \PASCAL@>
4451 undefined in \PASCAL, and it can lead to ``false drops'' (words that seem to
4452 point to |p| purely by coincidence). But for debugging purposes, we want
4453 to rule out the places that do {\sl not\/} point to |p|, so a few false
4454 drops are tolerable.
4455
4456 @c
4457 void mp_search_mem (MP mp, pointer p) { /* look for pointers to |p| */
4458   integer q; /* current position being searched */
4459   for (q=0;q<=mp->lo_mem_max;q++) { 
4460     if ( link(q)==p ){ 
4461       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4462     }
4463     if ( info(q)==p ) { 
4464       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4465     }
4466   }
4467   for (q=mp->hi_mem_min;q<=mp->mem_end;q++) {
4468     if ( link(q)==p ) {
4469       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4470     }
4471     if ( info(q)==p ) {
4472       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4473     }
4474   }
4475   @<Search |eqtb| for equivalents equal to |p|@>;
4476 }
4477
4478 @* \[12] The command codes.
4479 Before we can go much further, we need to define symbolic names for the internal
4480 code numbers that represent the various commands obeyed by \MP. These codes
4481 are somewhat arbitrary, but not completely so. For example,
4482 some codes have been made adjacent so that |case| statements in the
4483 program need not consider cases that are widely spaced, or so that |case|
4484 statements can be replaced by |if| statements. A command can begin an
4485 expression if and only if its code lies between |min_primary_command| and
4486 |max_primary_command|, inclusive. The first token of a statement that doesn't
4487 begin with an expression has a command code between |min_command| and
4488 |max_statement_command|, inclusive. Anything less than |min_command| is
4489 eliminated during macro expansions, and anything no more than |max_pre_command|
4490 is eliminated when expanding \TeX\ material.  Ranges such as
4491 |min_secondary_command..max_secondary_command| are used when parsing
4492 expressions, but the relative ordering within such a range is generally not
4493 critical.
4494
4495 The ordering of the highest-numbered commands
4496 (|comma<semicolon<end_group<stop|) is crucial for the parsing and
4497 error-recovery methods of this program as is the ordering |if_test<fi_or_else|
4498 for the smallest two commands.  The ordering is also important in the ranges
4499 |numeric_token..plus_or_minus| and |left_brace..ampersand|.
4500
4501 At any rate, here is the list, for future reference.
4502
4503 @d start_tex 1 /* begin \TeX\ material (\&{btex}, \&{verbatimtex}) */
4504 @d etex_marker 2 /* end \TeX\ material (\&{etex}) */
4505 @d mpx_break 3 /* stop reading an \.{MPX} file (\&{mpxbreak}) */
4506 @d max_pre_command mpx_break
4507 @d if_test 4 /* conditional text (\&{if}) */
4508 @d fi_or_else 5 /* delimiters for conditionals (\&{elseif}, \&{else}, \&{fi} */
4509 @d input 6 /* input a source file (\&{input}, \&{endinput}) */
4510 @d iteration 7 /* iterate (\&{for}, \&{forsuffixes}, \&{forever}, \&{endfor}) */
4511 @d repeat_loop 8 /* special command substituted for \&{endfor} */
4512 @d exit_test 9 /* premature exit from a loop (\&{exitif}) */
4513 @d relax 10 /* do nothing (\.{\char`\\}) */
4514 @d scan_tokens 11 /* put a string into the input buffer */
4515 @d expand_after 12 /* look ahead one token */
4516 @d defined_macro 13 /* a macro defined by the user */
4517 @d min_command (defined_macro+1)
4518 @d save_command 14 /* save a list of tokens (\&{save}) */
4519 @d interim_command 15 /* save an internal quantity (\&{interim}) */
4520 @d let_command 16 /* redefine a symbolic token (\&{let}) */
4521 @d new_internal 17 /* define a new internal quantity (\&{newinternal}) */
4522 @d macro_def 18 /* define a macro (\&{def}, \&{vardef}, etc.) */
4523 @d ship_out_command 19 /* output a character (\&{shipout}) */
4524 @d add_to_command 20 /* add to edges (\&{addto}) */
4525 @d bounds_command 21  /* add bounding path to edges (\&{setbounds}, \&{clip}) */
4526 @d tfm_command 22 /* command for font metric info (\&{ligtable}, etc.) */
4527 @d protection_command 23 /* set protection flag (\&{outer}, \&{inner}) */
4528 @d show_command 24 /* diagnostic output (\&{show}, \&{showvariable}, etc.) */
4529 @d mode_command 25 /* set interaction level (\&{batchmode}, etc.) */
4530 @d random_seed 26 /* initialize random number generator (\&{randomseed}) */
4531 @d message_command 27 /* communicate to user (\&{message}, \&{errmessage}) */
4532 @d every_job_command 28 /* designate a starting token (\&{everyjob}) */
4533 @d delimiters 29 /* define a pair of delimiters (\&{delimiters}) */
4534 @d special_command 30 /* output special info (\&{special})
4535                        or font map info (\&{fontmapfile}, \&{fontmapline}) */
4536 @d write_command 31 /* write text to a file (\&{write}) */
4537 @d type_name 32 /* declare a type (\&{numeric}, \&{pair}, etc. */
4538 @d max_statement_command type_name
4539 @d min_primary_command type_name
4540 @d left_delimiter 33 /* the left delimiter of a matching pair */
4541 @d begin_group 34 /* beginning of a group (\&{begingroup}) */
4542 @d nullary 35 /* an operator without arguments (e.g., \&{normaldeviate}) */
4543 @d unary 36 /* an operator with one argument (e.g., \&{sqrt}) */
4544 @d str_op 37 /* convert a suffix to a string (\&{str}) */
4545 @d cycle 38 /* close a cyclic path (\&{cycle}) */
4546 @d primary_binary 39 /* binary operation taking `\&{of}' (e.g., \&{point}) */
4547 @d capsule_token 40 /* a value that has been put into a token list */
4548 @d string_token 41 /* a string constant (e.g., |"hello"|) */
4549 @d internal_quantity 42 /* internal numeric parameter (e.g., \&{pausing}) */
4550 @d min_suffix_token internal_quantity
4551 @d tag_token 43 /* a symbolic token without a primitive meaning */
4552 @d numeric_token 44 /* a numeric constant (e.g., \.{3.14159}) */
4553 @d max_suffix_token numeric_token
4554 @d plus_or_minus 45 /* either `\.+' or `\.-' */
4555 @d max_primary_command plus_or_minus /* should also be |numeric_token+1| */
4556 @d min_tertiary_command plus_or_minus
4557 @d tertiary_secondary_macro 46 /* a macro defined by \&{secondarydef} */
4558 @d tertiary_binary 47 /* an operator at the tertiary level (e.g., `\.{++}') */
4559 @d max_tertiary_command tertiary_binary
4560 @d left_brace 48 /* the operator `\.{\char`\{}' */
4561 @d min_expression_command left_brace
4562 @d path_join 49 /* the operator `\.{..}' */
4563 @d ampersand 50 /* the operator `\.\&' */
4564 @d expression_tertiary_macro 51 /* a macro defined by \&{tertiarydef} */
4565 @d expression_binary 52 /* an operator at the expression level (e.g., `\.<') */
4566 @d equals 53 /* the operator `\.=' */
4567 @d max_expression_command equals
4568 @d and_command 54 /* the operator `\&{and}' */
4569 @d min_secondary_command and_command
4570 @d secondary_primary_macro 55 /* a macro defined by \&{primarydef} */
4571 @d slash 56 /* the operator `\./' */
4572 @d secondary_binary 57 /* an operator at the binary level (e.g., \&{shifted}) */
4573 @d max_secondary_command secondary_binary
4574 @d param_type 58 /* type of parameter (\&{primary}, \&{expr}, \&{suffix}, etc.) */
4575 @d controls 59 /* specify control points explicitly (\&{controls}) */
4576 @d tension 60 /* specify tension between knots (\&{tension}) */
4577 @d at_least 61 /* bounded tension value (\&{atleast}) */
4578 @d curl_command 62 /* specify curl at an end knot (\&{curl}) */
4579 @d macro_special 63 /* special macro operators (\&{quote}, \.{\#\AT!}, etc.) */
4580 @d right_delimiter 64 /* the right delimiter of a matching pair */
4581 @d left_bracket 65 /* the operator `\.[' */
4582 @d right_bracket 66 /* the operator `\.]' */
4583 @d right_brace 67 /* the operator `\.{\char`\}}' */
4584 @d with_option 68 /* option for filling (\&{withpen}, \&{withweight}, etc.) */
4585 @d thing_to_add 69
4586   /* variant of \&{addto} (\&{contour}, \&{doublepath}, \&{also}) */
4587 @d of_token 70 /* the operator `\&{of}' */
4588 @d to_token 71 /* the operator `\&{to}' */
4589 @d step_token 72 /* the operator `\&{step}' */
4590 @d until_token 73 /* the operator `\&{until}' */
4591 @d within_token 74 /* the operator `\&{within}' */
4592 @d lig_kern_token 75
4593   /* the operators `\&{kern}' and `\.{=:}' and `\.{=:\char'174}, etc. */
4594 @d assignment 76 /* the operator `\.{:=}' */
4595 @d skip_to 77 /* the operation `\&{skipto}' */
4596 @d bchar_label 78 /* the operator `\.{\char'174\char'174:}' */
4597 @d double_colon 79 /* the operator `\.{::}' */
4598 @d colon 80 /* the operator `\.:' */
4599 @#
4600 @d comma 81 /* the operator `\.,', must be |colon+1| */
4601 @d end_of_statement (mp->cur_cmd>comma)
4602 @d semicolon 82 /* the operator `\.;', must be |comma+1| */
4603 @d end_group 83 /* end a group (\&{endgroup}), must be |semicolon+1| */
4604 @d stop 84 /* end a job (\&{end}, \&{dump}), must be |end_group+1| */
4605 @d max_command_code stop
4606 @d outer_tag (max_command_code+1) /* protection code added to command code */
4607
4608 @<Types...@>=
4609 typedef int command_code;
4610
4611 @ Variables and capsules in \MP\ have a variety of ``types,''
4612 distinguished by the code numbers defined here. These numbers are also
4613 not completely arbitrary.  Things that get expanded must have types
4614 |>mp_independent|; a type remaining after expansion is numeric if and only if
4615 its code number is at least |numeric_type|; objects containing numeric
4616 parts must have types between |transform_type| and |pair_type|;
4617 all other types must be smaller than |transform_type|; and among the types
4618 that are not unknown or vacuous, the smallest two must be |boolean_type|
4619 and |string_type| in that order.
4620  
4621 @d undefined 0 /* no type has been declared */
4622 @d unknown_tag 1 /* this constant is added to certain type codes below */
4623 @d unknown_types mp_unknown_boolean: case mp_unknown_string:
4624   case mp_unknown_pen: case mp_unknown_picture: case mp_unknown_path
4625
4626 @<Types...@>=
4627 enum mp_variable_type {
4628 mp_vacuous=1, /* no expression was present */
4629 mp_boolean_type, /* \&{boolean} with a known value */
4630 mp_unknown_boolean,
4631 mp_string_type, /* \&{string} with a known value */
4632 mp_unknown_string,
4633 mp_pen_type, /* \&{pen} with a known value */
4634 mp_unknown_pen,
4635 mp_path_type, /* \&{path} with a known value */
4636 mp_unknown_path,
4637 mp_picture_type, /* \&{picture} with a known value */
4638 mp_unknown_picture,
4639 mp_transform_type, /* \&{transform} variable or capsule */
4640 mp_color_type, /* \&{color} variable or capsule */
4641 mp_cmykcolor_type, /* \&{cmykcolor} variable or capsule */
4642 mp_pair_type, /* \&{pair} variable or capsule */
4643 mp_numeric_type, /* variable that has been declared \&{numeric} but not used */
4644 mp_known, /* \&{numeric} with a known value */
4645 mp_dependent, /* a linear combination with |fraction| coefficients */
4646 mp_proto_dependent, /* a linear combination with |scaled| coefficients */
4647 mp_independent, /* \&{numeric} with unknown value */
4648 mp_token_list, /* variable name or suffix argument or text argument */
4649 mp_structured, /* variable with subscripts and attributes */
4650 mp_unsuffixed_macro, /* variable defined with \&{vardef} but no \.{\AT!\#} */
4651 mp_suffixed_macro /* variable defined with \&{vardef} and \.{\AT!\#} */
4652 } ;
4653
4654 @ @<Declarations@>=
4655 void mp_print_type (MP mp,small_number t) ;
4656
4657 @ @<Basic printing procedures@>=
4658 void mp_print_type (MP mp,small_number t) { 
4659   switch (t) {
4660   case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
4661   case mp_boolean_type:mp_print(mp, "boolean"); break;
4662   case mp_unknown_boolean:mp_print(mp, "unknown boolean"); break;
4663   case mp_string_type:mp_print(mp, "string"); break;
4664   case mp_unknown_string:mp_print(mp, "unknown string"); break;
4665   case mp_pen_type:mp_print(mp, "pen"); break;
4666   case mp_unknown_pen:mp_print(mp, "unknown pen"); break;
4667   case mp_path_type:mp_print(mp, "path"); break;
4668   case mp_unknown_path:mp_print(mp, "unknown path"); break;
4669   case mp_picture_type:mp_print(mp, "picture"); break;
4670   case mp_unknown_picture:mp_print(mp, "unknown picture"); break;
4671   case mp_transform_type:mp_print(mp, "transform"); break;
4672   case mp_color_type:mp_print(mp, "color"); break;
4673   case mp_cmykcolor_type:mp_print(mp, "cmykcolor"); break;
4674   case mp_pair_type:mp_print(mp, "pair"); break;
4675   case mp_known:mp_print(mp, "known numeric"); break;
4676   case mp_dependent:mp_print(mp, "dependent"); break;
4677   case mp_proto_dependent:mp_print(mp, "proto-dependent"); break;
4678   case mp_numeric_type:mp_print(mp, "numeric"); break;
4679   case mp_independent:mp_print(mp, "independent"); break;
4680   case mp_token_list:mp_print(mp, "token list"); break;
4681   case mp_structured:mp_print(mp, "mp_structured"); break;
4682   case mp_unsuffixed_macro:mp_print(mp, "unsuffixed macro"); break;
4683   case mp_suffixed_macro:mp_print(mp, "suffixed macro"); break;
4684   default: mp_print(mp, "undefined"); break;
4685   }
4686 }
4687
4688 @ Values inside \MP\ are stored in two-word nodes that have a |name_type|
4689 as well as a |type|. The possibilities for |name_type| are defined
4690 here; they will be explained in more detail later.
4691
4692 @<Types...@>=
4693 enum mp_name_type {
4694  mp_root=0, /* |name_type| at the top level of a variable */
4695  mp_saved_root, /* same, when the variable has been saved */
4696  mp_structured_root, /* |name_type| where a |mp_structured| branch occurs */
4697  mp_subscr, /* |name_type| in a subscript node */
4698  mp_attr, /* |name_type| in an attribute node */
4699  mp_x_part_sector, /* |name_type| in the \&{xpart} of a node */
4700  mp_y_part_sector, /* |name_type| in the \&{ypart} of a node */
4701  mp_xx_part_sector, /* |name_type| in the \&{xxpart} of a node */
4702  mp_xy_part_sector, /* |name_type| in the \&{xypart} of a node */
4703  mp_yx_part_sector, /* |name_type| in the \&{yxpart} of a node */
4704  mp_yy_part_sector, /* |name_type| in the \&{yypart} of a node */
4705  mp_red_part_sector, /* |name_type| in the \&{redpart} of a node */
4706  mp_green_part_sector, /* |name_type| in the \&{greenpart} of a node */
4707  mp_blue_part_sector, /* |name_type| in the \&{bluepart} of a node */
4708  mp_cyan_part_sector, /* |name_type| in the \&{redpart} of a node */
4709  mp_magenta_part_sector, /* |name_type| in the \&{greenpart} of a node */
4710  mp_yellow_part_sector, /* |name_type| in the \&{bluepart} of a node */
4711  mp_black_part_sector, /* |name_type| in the \&{greenpart} of a node */
4712  mp_grey_part_sector, /* |name_type| in the \&{bluepart} of a node */
4713  mp_capsule, /* |name_type| in stashed-away subexpressions */
4714  mp_token  /* |name_type| in a numeric token or string token */
4715 };
4716
4717 @ Primitive operations that produce values have a secondary identification
4718 code in addition to their command code; it's something like genera and species.
4719 For example, `\.*' has the command code |primary_binary|, and its
4720 secondary identification is |times|. The secondary codes start at 30 so that
4721 they don't overlap with the type codes; some type codes (e.g., |mp_string_type|)
4722 are used as operators as well as type identifications.  The relative values
4723 are not critical, except for |true_code..false_code|, |or_op..and_op|,
4724 and |filled_op..bounded_op|.  The restrictions are that
4725 |and_op-false_code=or_op-true_code|, that the ordering of
4726 |x_part...blue_part| must match that of |x_part_sector..mp_blue_part_sector|,
4727 and the ordering of |filled_op..bounded_op| must match that of the code
4728 values they test for.
4729
4730 @d true_code 30 /* operation code for \.{true} */
4731 @d false_code 31 /* operation code for \.{false} */
4732 @d null_picture_code 32 /* operation code for \.{nullpicture} */
4733 @d null_pen_code 33 /* operation code for \.{nullpen} */
4734 @d job_name_op 34 /* operation code for \.{jobname} */
4735 @d read_string_op 35 /* operation code for \.{readstring} */
4736 @d pen_circle 36 /* operation code for \.{pencircle} */
4737 @d normal_deviate 37 /* operation code for \.{normaldeviate} */
4738 @d read_from_op 38 /* operation code for \.{readfrom} */
4739 @d close_from_op 39 /* operation code for \.{closefrom} */
4740 @d odd_op 40 /* operation code for \.{odd} */
4741 @d known_op 41 /* operation code for \.{known} */
4742 @d unknown_op 42 /* operation code for \.{unknown} */
4743 @d not_op 43 /* operation code for \.{not} */
4744 @d decimal 44 /* operation code for \.{decimal} */
4745 @d reverse 45 /* operation code for \.{reverse} */
4746 @d make_path_op 46 /* operation code for \.{makepath} */
4747 @d make_pen_op 47 /* operation code for \.{makepen} */
4748 @d oct_op 48 /* operation code for \.{oct} */
4749 @d hex_op 49 /* operation code for \.{hex} */
4750 @d ASCII_op 50 /* operation code for \.{ASCII} */
4751 @d char_op 51 /* operation code for \.{char} */
4752 @d length_op 52 /* operation code for \.{length} */
4753 @d turning_op 53 /* operation code for \.{turningnumber} */
4754 @d color_model_part 54 /* operation code for \.{colormodel} */
4755 @d x_part 55 /* operation code for \.{xpart} */
4756 @d y_part 56 /* operation code for \.{ypart} */
4757 @d xx_part 57 /* operation code for \.{xxpart} */
4758 @d xy_part 58 /* operation code for \.{xypart} */
4759 @d yx_part 59 /* operation code for \.{yxpart} */
4760 @d yy_part 60 /* operation code for \.{yypart} */
4761 @d red_part 61 /* operation code for \.{redpart} */
4762 @d green_part 62 /* operation code for \.{greenpart} */
4763 @d blue_part 63 /* operation code for \.{bluepart} */
4764 @d cyan_part 64 /* operation code for \.{cyanpart} */
4765 @d magenta_part 65 /* operation code for \.{magentapart} */
4766 @d yellow_part 66 /* operation code for \.{yellowpart} */
4767 @d black_part 67 /* operation code for \.{blackpart} */
4768 @d grey_part 68 /* operation code for \.{greypart} */
4769 @d font_part 69 /* operation code for \.{fontpart} */
4770 @d text_part 70 /* operation code for \.{textpart} */
4771 @d path_part 71 /* operation code for \.{pathpart} */
4772 @d pen_part 72 /* operation code for \.{penpart} */
4773 @d dash_part 73 /* operation code for \.{dashpart} */
4774 @d sqrt_op 74 /* operation code for \.{sqrt} */
4775 @d m_exp_op 75 /* operation code for \.{mexp} */
4776 @d m_log_op 76 /* operation code for \.{mlog} */
4777 @d sin_d_op 77 /* operation code for \.{sind} */
4778 @d cos_d_op 78 /* operation code for \.{cosd} */
4779 @d floor_op 79 /* operation code for \.{floor} */
4780 @d uniform_deviate 80 /* operation code for \.{uniformdeviate} */
4781 @d char_exists_op 81 /* operation code for \.{charexists} */
4782 @d font_size 82 /* operation code for \.{fontsize} */
4783 @d ll_corner_op 83 /* operation code for \.{llcorner} */
4784 @d lr_corner_op 84 /* operation code for \.{lrcorner} */
4785 @d ul_corner_op 85 /* operation code for \.{ulcorner} */
4786 @d ur_corner_op 86 /* operation code for \.{urcorner} */
4787 @d arc_length 87 /* operation code for \.{arclength} */
4788 @d angle_op 88 /* operation code for \.{angle} */
4789 @d cycle_op 89 /* operation code for \.{cycle} */
4790 @d filled_op 90 /* operation code for \.{filled} */
4791 @d stroked_op 91 /* operation code for \.{stroked} */
4792 @d textual_op 92 /* operation code for \.{textual} */
4793 @d clipped_op 93 /* operation code for \.{clipped} */
4794 @d bounded_op 94 /* operation code for \.{bounded} */
4795 @d plus 95 /* operation code for \.+ */
4796 @d minus 96 /* operation code for \.- */
4797 @d times 97 /* operation code for \.* */
4798 @d over 98 /* operation code for \./ */
4799 @d pythag_add 99 /* operation code for \.{++} */
4800 @d pythag_sub 100 /* operation code for \.{+-+} */
4801 @d or_op 101 /* operation code for \.{or} */
4802 @d and_op 102 /* operation code for \.{and} */
4803 @d less_than 103 /* operation code for \.< */
4804 @d less_or_equal 104 /* operation code for \.{<=} */
4805 @d greater_than 105 /* operation code for \.> */
4806 @d greater_or_equal 106 /* operation code for \.{>=} */
4807 @d equal_to 107 /* operation code for \.= */
4808 @d unequal_to 108 /* operation code for \.{<>} */
4809 @d concatenate 109 /* operation code for \.\& */
4810 @d rotated_by 110 /* operation code for \.{rotated} */
4811 @d slanted_by 111 /* operation code for \.{slanted} */
4812 @d scaled_by 112 /* operation code for \.{scaled} */
4813 @d shifted_by 113 /* operation code for \.{shifted} */
4814 @d transformed_by 114 /* operation code for \.{transformed} */
4815 @d x_scaled 115 /* operation code for \.{xscaled} */
4816 @d y_scaled 116 /* operation code for \.{yscaled} */
4817 @d z_scaled 117 /* operation code for \.{zscaled} */
4818 @d in_font 118 /* operation code for \.{infont} */
4819 @d intersect 119 /* operation code for \.{intersectiontimes} */
4820 @d double_dot 120 /* operation code for improper \.{..} */
4821 @d substring_of 121 /* operation code for \.{substring} */
4822 @d min_of substring_of
4823 @d subpath_of 122 /* operation code for \.{subpath} */
4824 @d direction_time_of 123 /* operation code for \.{directiontime} */
4825 @d point_of 124 /* operation code for \.{point} */
4826 @d precontrol_of 125 /* operation code for \.{precontrol} */
4827 @d postcontrol_of 126 /* operation code for \.{postcontrol} */
4828 @d pen_offset_of 127 /* operation code for \.{penoffset} */
4829 @d arc_time_of 128 /* operation code for \.{arctime} */
4830 @d mp_version 129 /* operation code for \.{mpversion} */
4831
4832 @c void mp_print_op (MP mp,quarterword c) { 
4833   if (c<=mp_numeric_type ) {
4834     mp_print_type(mp, c);
4835   } else {
4836     switch (c) {
4837     case true_code:mp_print(mp, "true"); break;
4838     case false_code:mp_print(mp, "false"); break;
4839     case null_picture_code:mp_print(mp, "nullpicture"); break;
4840     case null_pen_code:mp_print(mp, "nullpen"); break;
4841     case job_name_op:mp_print(mp, "jobname"); break;
4842     case read_string_op:mp_print(mp, "readstring"); break;
4843     case pen_circle:mp_print(mp, "pencircle"); break;
4844     case normal_deviate:mp_print(mp, "normaldeviate"); break;
4845     case read_from_op:mp_print(mp, "readfrom"); break;
4846     case close_from_op:mp_print(mp, "closefrom"); break;
4847     case odd_op:mp_print(mp, "odd"); break;
4848     case known_op:mp_print(mp, "known"); break;
4849     case unknown_op:mp_print(mp, "unknown"); break;
4850     case not_op:mp_print(mp, "not"); break;
4851     case decimal:mp_print(mp, "decimal"); break;
4852     case reverse:mp_print(mp, "reverse"); break;
4853     case make_path_op:mp_print(mp, "makepath"); break;
4854     case make_pen_op:mp_print(mp, "makepen"); break;
4855     case oct_op:mp_print(mp, "oct"); break;
4856     case hex_op:mp_print(mp, "hex"); break;
4857     case ASCII_op:mp_print(mp, "ASCII"); break;
4858     case char_op:mp_print(mp, "char"); break;
4859     case length_op:mp_print(mp, "length"); break;
4860     case turning_op:mp_print(mp, "turningnumber"); break;
4861     case x_part:mp_print(mp, "xpart"); break;
4862     case y_part:mp_print(mp, "ypart"); break;
4863     case xx_part:mp_print(mp, "xxpart"); break;
4864     case xy_part:mp_print(mp, "xypart"); break;
4865     case yx_part:mp_print(mp, "yxpart"); break;
4866     case yy_part:mp_print(mp, "yypart"); break;
4867     case red_part:mp_print(mp, "redpart"); break;
4868     case green_part:mp_print(mp, "greenpart"); break;
4869     case blue_part:mp_print(mp, "bluepart"); break;
4870     case cyan_part:mp_print(mp, "cyanpart"); break;
4871     case magenta_part:mp_print(mp, "magentapart"); break;
4872     case yellow_part:mp_print(mp, "yellowpart"); break;
4873     case black_part:mp_print(mp, "blackpart"); break;
4874     case grey_part:mp_print(mp, "greypart"); break;
4875     case color_model_part:mp_print(mp, "colormodel"); break;
4876     case font_part:mp_print(mp, "fontpart"); break;
4877     case text_part:mp_print(mp, "textpart"); break;
4878     case path_part:mp_print(mp, "pathpart"); break;
4879     case pen_part:mp_print(mp, "penpart"); break;
4880     case dash_part:mp_print(mp, "dashpart"); break;
4881     case sqrt_op:mp_print(mp, "sqrt"); break;
4882     case m_exp_op:mp_print(mp, "mexp"); break;
4883     case m_log_op:mp_print(mp, "mlog"); break;
4884     case sin_d_op:mp_print(mp, "sind"); break;
4885     case cos_d_op:mp_print(mp, "cosd"); break;
4886     case floor_op:mp_print(mp, "floor"); break;
4887     case uniform_deviate:mp_print(mp, "uniformdeviate"); break;
4888     case char_exists_op:mp_print(mp, "charexists"); break;
4889     case font_size:mp_print(mp, "fontsize"); break;
4890     case ll_corner_op:mp_print(mp, "llcorner"); break;
4891     case lr_corner_op:mp_print(mp, "lrcorner"); break;
4892     case ul_corner_op:mp_print(mp, "ulcorner"); break;
4893     case ur_corner_op:mp_print(mp, "urcorner"); break;
4894     case arc_length:mp_print(mp, "arclength"); break;
4895     case angle_op:mp_print(mp, "angle"); break;
4896     case cycle_op:mp_print(mp, "cycle"); break;
4897     case filled_op:mp_print(mp, "filled"); break;
4898     case stroked_op:mp_print(mp, "stroked"); break;
4899     case textual_op:mp_print(mp, "textual"); break;
4900     case clipped_op:mp_print(mp, "clipped"); break;
4901     case bounded_op:mp_print(mp, "bounded"); break;
4902     case plus:mp_print_char(mp, '+'); break;
4903     case minus:mp_print_char(mp, '-'); break;
4904     case times:mp_print_char(mp, '*'); break;
4905     case over:mp_print_char(mp, '/'); break;
4906     case pythag_add:mp_print(mp, "++"); break;
4907     case pythag_sub:mp_print(mp, "+-+"); break;
4908     case or_op:mp_print(mp, "or"); break;
4909     case and_op:mp_print(mp, "and"); break;
4910     case less_than:mp_print_char(mp, '<'); break;
4911     case less_or_equal:mp_print(mp, "<="); break;
4912     case greater_than:mp_print_char(mp, '>'); break;
4913     case greater_or_equal:mp_print(mp, ">="); break;
4914     case equal_to:mp_print_char(mp, '='); break;
4915     case unequal_to:mp_print(mp, "<>"); break;
4916     case concatenate:mp_print(mp, "&"); break;
4917     case rotated_by:mp_print(mp, "rotated"); break;
4918     case slanted_by:mp_print(mp, "slanted"); break;
4919     case scaled_by:mp_print(mp, "scaled"); break;
4920     case shifted_by:mp_print(mp, "shifted"); break;
4921     case transformed_by:mp_print(mp, "transformed"); break;
4922     case x_scaled:mp_print(mp, "xscaled"); break;
4923     case y_scaled:mp_print(mp, "yscaled"); break;
4924     case z_scaled:mp_print(mp, "zscaled"); break;
4925     case in_font:mp_print(mp, "infont"); break;
4926     case intersect:mp_print(mp, "intersectiontimes"); break;
4927     case substring_of:mp_print(mp, "substring"); break;
4928     case subpath_of:mp_print(mp, "subpath"); break;
4929     case direction_time_of:mp_print(mp, "directiontime"); break;
4930     case point_of:mp_print(mp, "point"); break;
4931     case precontrol_of:mp_print(mp, "precontrol"); break;
4932     case postcontrol_of:mp_print(mp, "postcontrol"); break;
4933     case pen_offset_of:mp_print(mp, "penoffset"); break;
4934     case arc_time_of:mp_print(mp, "arctime"); break;
4935     case mp_version:mp_print(mp, "mpversion"); break;
4936     default: mp_print(mp, ".."); break;
4937     }
4938   }
4939 }
4940
4941 @ \MP\ also has a bunch of internal parameters that a user might want to
4942 fuss with. Every such parameter has an identifying code number, defined here.
4943
4944 @<Types...@>=
4945 enum mp_given_internal {
4946   mp_tracing_titles=1, /* show titles online when they appear */
4947   mp_tracing_equations, /* show each variable when it becomes known */
4948   mp_tracing_capsules, /* show capsules too */
4949   mp_tracing_choices, /* show the control points chosen for paths */
4950   mp_tracing_specs, /* show path subdivision prior to filling with polygonal a pen */
4951   mp_tracing_commands, /* show commands and operations before they are performed */
4952   mp_tracing_restores, /* show when a variable or internal is restored */
4953   mp_tracing_macros, /* show macros before they are expanded */
4954   mp_tracing_output, /* show digitized edges as they are output */
4955   mp_tracing_stats, /* show memory usage at end of job */
4956   mp_tracing_lost_chars, /* show characters that aren't \&{infont} */
4957   mp_tracing_online, /* show long diagnostics on terminal and in the log file */
4958   mp_year, /* the current year (e.g., 1984) */
4959   mp_month, /* the current month (e.g, 3 $\equiv$ March) */
4960   mp_day, /* the current day of the month */
4961   mp_time, /* the number of minutes past midnight when this job started */
4962   mp_char_code, /* the number of the next character to be output */
4963   mp_char_ext, /* the extension code of the next character to be output */
4964   mp_char_wd, /* the width of the next character to be output */
4965   mp_char_ht, /* the height of the next character to be output */
4966   mp_char_dp, /* the depth of the next character to be output */
4967   mp_char_ic, /* the italic correction of the next character to be output */
4968   mp_design_size, /* the unit of measure used for |mp_char_wd..mp_char_ic|, in points */
4969   mp_pausing, /* positive to display lines on the terminal before they are read */
4970   mp_showstopping, /* positive to stop after each \&{show} command */
4971   mp_fontmaking, /* positive if font metric output is to be produced */
4972   mp_linejoin, /* as in \ps: 0 for mitered, 1 for round, 2 for beveled */
4973   mp_linecap, /* as in \ps: 0 for butt, 1 for round, 2 for square */
4974   mp_miterlimit, /* controls miter length as in \ps */
4975   mp_warning_check, /* controls error message when variable value is large */
4976   mp_boundary_char, /* the right boundary character for ligatures */
4977   mp_prologues, /* positive to output conforming PostScript using built-in fonts */
4978   mp_true_corners, /* positive to make \&{llcorner} etc. ignore \&{setbounds} */
4979   mp_default_color_model, /* the default color model for unspecified items */
4980   mp_restore_clip_color,
4981   mp_procset, /* wether or not create PostScript command shortcuts */
4982   mp_gtroffmode,  /* whether the user specified |-troff| on the command line */
4983 };
4984
4985 @
4986
4987 @d max_given_internal mp_gtroffmode
4988
4989 @<Glob...@>=
4990 scaled *internal;  /* the values of internal quantities */
4991 char **int_name;  /* their names */
4992 int int_ptr;  /* the maximum internal quantity defined so far */
4993 int max_internal; /* current maximum number of internal quantities */
4994 boolean troff_mode; 
4995
4996 @ @<Option variables@>=
4997 int troff_mode; 
4998
4999 @ @<Allocate or initialize ...@>=
5000 mp->max_internal=2*max_given_internal;
5001 mp->internal = xmalloc ((mp->max_internal+1), sizeof(scaled));
5002 mp->int_name = xmalloc ((mp->max_internal+1), sizeof(char *));
5003 mp->troff_mode=(opt->troff_mode>0 ? true : false);
5004
5005 @ @<Exported function ...@>=
5006 int mp_troff_mode(MP mp);
5007
5008 @ @c
5009 int mp_troff_mode(MP mp) { return mp->troff_mode; }
5010
5011 @ @<Set initial ...@>=
5012 for (k=0;k<= mp->max_internal; k++ ) { 
5013    mp->internal[k]=0; 
5014    mp->int_name[k]=NULL; 
5015 }
5016 mp->int_ptr=max_given_internal;
5017
5018 @ The symbolic names for internal quantities are put into \MP's hash table
5019 by using a routine called |primitive|, which will be defined later. Let us
5020 enter them now, so that we don't have to list all those names again
5021 anywhere else.
5022
5023 @<Put each of \MP's primitives into the hash table@>=
5024 mp_primitive(mp, "tracingtitles",internal_quantity,mp_tracing_titles);
5025 @:tracingtitles_}{\&{tracingtitles} primitive@>
5026 mp_primitive(mp, "tracingequations",internal_quantity,mp_tracing_equations);
5027 @:mp_tracing_equations_}{\&{tracingequations} primitive@>
5028 mp_primitive(mp, "tracingcapsules",internal_quantity,mp_tracing_capsules);
5029 @:mp_tracing_capsules_}{\&{tracingcapsules} primitive@>
5030 mp_primitive(mp, "tracingchoices",internal_quantity,mp_tracing_choices);
5031 @:mp_tracing_choices_}{\&{tracingchoices} primitive@>
5032 mp_primitive(mp, "tracingspecs",internal_quantity,mp_tracing_specs);
5033 @:mp_tracing_specs_}{\&{tracingspecs} primitive@>
5034 mp_primitive(mp, "tracingcommands",internal_quantity,mp_tracing_commands);
5035 @:mp_tracing_commands_}{\&{tracingcommands} primitive@>
5036 mp_primitive(mp, "tracingrestores",internal_quantity,mp_tracing_restores);
5037 @:mp_tracing_restores_}{\&{tracingrestores} primitive@>
5038 mp_primitive(mp, "tracingmacros",internal_quantity,mp_tracing_macros);
5039 @:mp_tracing_macros_}{\&{tracingmacros} primitive@>
5040 mp_primitive(mp, "tracingoutput",internal_quantity,mp_tracing_output);
5041 @:mp_tracing_output_}{\&{tracingoutput} primitive@>
5042 mp_primitive(mp, "tracingstats",internal_quantity,mp_tracing_stats);
5043 @:mp_tracing_stats_}{\&{tracingstats} primitive@>
5044 mp_primitive(mp, "tracinglostchars",internal_quantity,mp_tracing_lost_chars);
5045 @:mp_tracing_lost_chars_}{\&{tracinglostchars} primitive@>
5046 mp_primitive(mp, "tracingonline",internal_quantity,mp_tracing_online);
5047 @:mp_tracing_online_}{\&{tracingonline} primitive@>
5048 mp_primitive(mp, "year",internal_quantity,mp_year);
5049 @:mp_year_}{\&{year} primitive@>
5050 mp_primitive(mp, "month",internal_quantity,mp_month);
5051 @:mp_month_}{\&{month} primitive@>
5052 mp_primitive(mp, "day",internal_quantity,mp_day);
5053 @:mp_day_}{\&{day} primitive@>
5054 mp_primitive(mp, "time",internal_quantity,mp_time);
5055 @:time_}{\&{time} primitive@>
5056 mp_primitive(mp, "charcode",internal_quantity,mp_char_code);
5057 @:mp_char_code_}{\&{charcode} primitive@>
5058 mp_primitive(mp, "charext",internal_quantity,mp_char_ext);
5059 @:mp_char_ext_}{\&{charext} primitive@>
5060 mp_primitive(mp, "charwd",internal_quantity,mp_char_wd);
5061 @:mp_char_wd_}{\&{charwd} primitive@>
5062 mp_primitive(mp, "charht",internal_quantity,mp_char_ht);
5063 @:mp_char_ht_}{\&{charht} primitive@>
5064 mp_primitive(mp, "chardp",internal_quantity,mp_char_dp);
5065 @:mp_char_dp_}{\&{chardp} primitive@>
5066 mp_primitive(mp, "charic",internal_quantity,mp_char_ic);
5067 @:mp_char_ic_}{\&{charic} primitive@>
5068 mp_primitive(mp, "designsize",internal_quantity,mp_design_size);
5069 @:mp_design_size_}{\&{designsize} primitive@>
5070 mp_primitive(mp, "pausing",internal_quantity,mp_pausing);
5071 @:mp_pausing_}{\&{pausing} primitive@>
5072 mp_primitive(mp, "showstopping",internal_quantity,mp_showstopping);
5073 @:mp_showstopping_}{\&{showstopping} primitive@>
5074 mp_primitive(mp, "fontmaking",internal_quantity,mp_fontmaking);
5075 @:mp_fontmaking_}{\&{fontmaking} primitive@>
5076 mp_primitive(mp, "linejoin",internal_quantity,mp_linejoin);
5077 @:mp_linejoin_}{\&{linejoin} primitive@>
5078 mp_primitive(mp, "linecap",internal_quantity,mp_linecap);
5079 @:mp_linecap_}{\&{linecap} primitive@>
5080 mp_primitive(mp, "miterlimit",internal_quantity,mp_miterlimit);
5081 @:mp_miterlimit_}{\&{miterlimit} primitive@>
5082 mp_primitive(mp, "warningcheck",internal_quantity,mp_warning_check);
5083 @:mp_warning_check_}{\&{warningcheck} primitive@>
5084 mp_primitive(mp, "boundarychar",internal_quantity,mp_boundary_char);
5085 @:mp_boundary_char_}{\&{boundarychar} primitive@>
5086 mp_primitive(mp, "prologues",internal_quantity,mp_prologues);
5087 @:mp_prologues_}{\&{prologues} primitive@>
5088 mp_primitive(mp, "truecorners",internal_quantity,mp_true_corners);
5089 @:mp_true_corners_}{\&{truecorners} primitive@>
5090 mp_primitive(mp, "mpprocset",internal_quantity,mp_procset);
5091 @:mp_procset_}{\&{mpprocset} primitive@>
5092 mp_primitive(mp, "troffmode",internal_quantity,mp_gtroffmode);
5093 @:troffmode_}{\&{troffmode} primitive@>
5094 mp_primitive(mp, "defaultcolormodel",internal_quantity,mp_default_color_model);
5095 @:mp_default_color_model_}{\&{defaultcolormodel} primitive@>
5096 mp_primitive(mp, "restoreclipcolor",internal_quantity,mp_restore_clip_color);
5097 @:mp_restore_clip_color_}{\&{restoreclipcolor} primitive@>
5098
5099 @ Colors can be specified in four color models. In the special
5100 case of |no_model|, MetaPost does not output any color operator to
5101 the postscript output.
5102
5103 Note: these values are passed directly on to |with_option|. This only
5104 works because the other possible values passed to |with_option| are
5105 8 and 10 respectively (from |with_pen| and |with_picture|).
5106
5107 There is a first state, that is only used for |gs_colormodel|. It flags
5108 the fact that there has not been any kind of color specification by
5109 the user so far in the game.
5110
5111 @<Types...@>=
5112 enum mp_color_model {
5113   mp_no_model=1,
5114   mp_grey_model=3,
5115   mp_rgb_model=5,
5116   mp_cmyk_model=7,
5117   mp_uninitialized_model=9,
5118 };
5119
5120
5121 @ @<Initialize table entries (done by \.{INIMP} only)@>=
5122 mp->internal[mp_default_color_model]=(mp_rgb_model*unity);
5123 mp->internal[mp_restore_clip_color]=unity;
5124
5125 @ Well, we do have to list the names one more time, for use in symbolic
5126 printouts.
5127
5128 @<Initialize table...@>=
5129 mp->int_name[mp_tracing_titles]=xstrdup("tracingtitles");
5130 mp->int_name[mp_tracing_equations]=xstrdup("tracingequations");
5131 mp->int_name[mp_tracing_capsules]=xstrdup("tracingcapsules");
5132 mp->int_name[mp_tracing_choices]=xstrdup("tracingchoices");
5133 mp->int_name[mp_tracing_specs]=xstrdup("tracingspecs");
5134 mp->int_name[mp_tracing_commands]=xstrdup("tracingcommands");
5135 mp->int_name[mp_tracing_restores]=xstrdup("tracingrestores");
5136 mp->int_name[mp_tracing_macros]=xstrdup("tracingmacros");
5137 mp->int_name[mp_tracing_output]=xstrdup("tracingoutput");
5138 mp->int_name[mp_tracing_stats]=xstrdup("tracingstats");
5139 mp->int_name[mp_tracing_lost_chars]=xstrdup("tracinglostchars");
5140 mp->int_name[mp_tracing_online]=xstrdup("tracingonline");
5141 mp->int_name[mp_year]=xstrdup("year");
5142 mp->int_name[mp_month]=xstrdup("month");
5143 mp->int_name[mp_day]=xstrdup("day");
5144 mp->int_name[mp_time]=xstrdup("time");
5145 mp->int_name[mp_char_code]=xstrdup("charcode");
5146 mp->int_name[mp_char_ext]=xstrdup("charext");
5147 mp->int_name[mp_char_wd]=xstrdup("charwd");
5148 mp->int_name[mp_char_ht]=xstrdup("charht");
5149 mp->int_name[mp_char_dp]=xstrdup("chardp");
5150 mp->int_name[mp_char_ic]=xstrdup("charic");
5151 mp->int_name[mp_design_size]=xstrdup("designsize");
5152 mp->int_name[mp_pausing]=xstrdup("pausing");
5153 mp->int_name[mp_showstopping]=xstrdup("showstopping");
5154 mp->int_name[mp_fontmaking]=xstrdup("fontmaking");
5155 mp->int_name[mp_linejoin]=xstrdup("linejoin");
5156 mp->int_name[mp_linecap]=xstrdup("linecap");
5157 mp->int_name[mp_miterlimit]=xstrdup("miterlimit");
5158 mp->int_name[mp_warning_check]=xstrdup("warningcheck");
5159 mp->int_name[mp_boundary_char]=xstrdup("boundarychar");
5160 mp->int_name[mp_prologues]=xstrdup("prologues");
5161 mp->int_name[mp_true_corners]=xstrdup("truecorners");
5162 mp->int_name[mp_default_color_model]=xstrdup("defaultcolormodel");
5163 mp->int_name[mp_procset]=xstrdup("mpprocset");
5164 mp->int_name[mp_gtroffmode]=xstrdup("troffmode");
5165 mp->int_name[mp_restore_clip_color]=xstrdup("restoreclipcolor");
5166
5167 @ The following procedure, which is called just before \MP\ initializes its
5168 input and output, establishes the initial values of the date and time.
5169 @^system dependencies@>
5170
5171 Note that the values are |scaled| integers. Hence \MP\ can no longer
5172 be used after the year 32767.
5173
5174 @c 
5175 void mp_fix_date_and_time (MP mp) { 
5176   time_t clock = time ((time_t *) 0);
5177   struct tm *tmptr = localtime (&clock);
5178   mp->internal[mp_time]=
5179       (tmptr->tm_hour*60+tmptr->tm_min)*unity; /* minutes since midnight */
5180   mp->internal[mp_day]=(tmptr->tm_mday)*unity; /* fourth day of the month */
5181   mp->internal[mp_month]=(tmptr->tm_mon+1)*unity; /* seventh month of the year */
5182   mp->internal[mp_year]=(tmptr->tm_year+1900)*unity; /* Anno Domini */
5183 }
5184
5185 @ @<Declarations@>=
5186 void mp_fix_date_and_time (MP mp) ;
5187
5188 @ \MP\ is occasionally supposed to print diagnostic information that
5189 goes only into the transcript file, unless |mp_tracing_online| is positive.
5190 Now that we have defined |mp_tracing_online| we can define
5191 two routines that adjust the destination of print commands:
5192
5193 @<Declarations@>=
5194 void mp_begin_diagnostic (MP mp) ;
5195 void mp_end_diagnostic (MP mp,boolean blank_line);
5196 void mp_print_diagnostic (MP mp, char *s, char *t, boolean nuline) ;
5197
5198 @ @<Basic printing...@>=
5199 @<Declare a function called |true_line|@>;
5200 void mp_begin_diagnostic (MP mp) { /* prepare to do some tracing */
5201   mp->old_setting=mp->selector;
5202   if ( mp->selector==ps_file_only ) mp->selector=mp->non_ps_setting;
5203   if ((mp->internal[mp_tracing_online]<=0)&&(mp->selector==term_and_log)){ 
5204     decr(mp->selector);
5205     if ( mp->history==mp_spotless ) mp->history=mp_warning_issued;
5206   }
5207 }
5208 @#
5209 void mp_end_diagnostic (MP mp,boolean blank_line) {
5210   /* restore proper conditions after tracing */
5211   mp_print_nl(mp, "");
5212   if ( blank_line ) mp_print_ln(mp);
5213   mp->selector=mp->old_setting;
5214 }
5215
5216 @ The global variable |non_ps_setting| is initialized when it is time to print
5217 on |ps_file|.
5218
5219 @<Glob...@>=
5220 unsigned int old_setting;
5221 unsigned int non_ps_setting;
5222
5223 @ We will occasionally use |begin_diagnostic| in connection with line-number
5224 printing, as follows. (The parameter |s| is typically |"Path"| or
5225 |"Cycle spec"|, etc.)
5226
5227 @<Basic printing...@>=
5228 void mp_print_diagnostic (MP mp, char *s, char *t, boolean nuline) { 
5229   mp_begin_diagnostic(mp);
5230   if ( nuline ) mp_print_nl(mp, s); else mp_print(mp, s);
5231   mp_print(mp, " at line "); 
5232   mp_print_int(mp, mp_true_line(mp));
5233   mp_print(mp, t); mp_print_char(mp, ':');
5234 }
5235
5236 @ The 256 |ASCII_code| characters are grouped into classes by means of
5237 the |char_class| table. Individual class numbers have no semantic
5238 or syntactic significance, except in a few instances defined here.
5239 There's also |max_class|, which can be used as a basis for additional
5240 class numbers in nonstandard extensions of \MP.
5241
5242 @d digit_class 0 /* the class number of \.{0123456789} */
5243 @d period_class 1 /* the class number of `\..' */
5244 @d space_class 2 /* the class number of spaces and nonstandard characters */
5245 @d percent_class 3 /* the class number of `\.\%' */
5246 @d string_class 4 /* the class number of `\."' */
5247 @d right_paren_class 8 /* the class number of `\.)' */
5248 @d isolated_classes 5: case 6: case 7: case 8 /* characters that make length-one tokens only */
5249 @d letter_class 9 /* letters and the underline character */
5250 @d left_bracket_class 17 /* `\.[' */
5251 @d right_bracket_class 18 /* `\.]' */
5252 @d invalid_class 20 /* bad character in the input */
5253 @d max_class 20 /* the largest class number */
5254
5255 @<Glob...@>=
5256 int char_class[256]; /* the class numbers */
5257
5258 @ If changes are made to accommodate non-ASCII character sets, they should
5259 follow the guidelines in Appendix~C of {\sl The {\logos METAFONT\/}book}.
5260 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
5261 @^system dependencies@>
5262
5263 @<Set initial ...@>=
5264 for (k='0';k<='9';k++) 
5265   mp->char_class[k]=digit_class;
5266 mp->char_class['.']=period_class;
5267 mp->char_class[' ']=space_class;
5268 mp->char_class['%']=percent_class;
5269 mp->char_class['"']=string_class;
5270 mp->char_class[',']=5;
5271 mp->char_class[';']=6;
5272 mp->char_class['(']=7;
5273 mp->char_class[')']=right_paren_class;
5274 for (k='A';k<= 'Z';k++ )
5275   mp->char_class[k]=letter_class;
5276 for (k='a';k<='z';k++) 
5277   mp->char_class[k]=letter_class;
5278 mp->char_class['_']=letter_class;
5279 mp->char_class['<']=10;
5280 mp->char_class['=']=10;
5281 mp->char_class['>']=10;
5282 mp->char_class[':']=10;
5283 mp->char_class['|']=10;
5284 mp->char_class['`']=11;
5285 mp->char_class['\'']=11;
5286 mp->char_class['+']=12;
5287 mp->char_class['-']=12;
5288 mp->char_class['/']=13;
5289 mp->char_class['*']=13;
5290 mp->char_class['\\']=13;
5291 mp->char_class['!']=14;
5292 mp->char_class['?']=14;
5293 mp->char_class['#']=15;
5294 mp->char_class['&']=15;
5295 mp->char_class['@@']=15;
5296 mp->char_class['$']=15;
5297 mp->char_class['^']=16;
5298 mp->char_class['~']=16;
5299 mp->char_class['[']=left_bracket_class;
5300 mp->char_class[']']=right_bracket_class;
5301 mp->char_class['{']=19;
5302 mp->char_class['}']=19;
5303 for (k=0;k<' ';k++)
5304   mp->char_class[k]=invalid_class;
5305 mp->char_class['\t']=space_class;
5306 mp->char_class['\f']=space_class;
5307 for (k=127;k<=255;k++)
5308   mp->char_class[k]=invalid_class;
5309
5310 @* \[13] The hash table.
5311 Symbolic tokens are stored and retrieved by means of a fairly standard hash
5312 table algorithm called the method of ``coalescing lists'' (cf.\ Algorithm 6.4C
5313 in {\sl The Art of Computer Programming\/}). Once a symbolic token enters the
5314 table, it is never removed.
5315
5316 The actual sequence of characters forming a symbolic token is
5317 stored in the |str_pool| array together with all the other strings. An
5318 auxiliary array |hash| consists of items with two halfword fields per
5319 word. The first of these, called |next(p)|, points to the next identifier
5320 belonging to the same coalesced list as the identifier corresponding to~|p|;
5321 and the other, called |text(p)|, points to the |str_start| entry for
5322 |p|'s identifier. If position~|p| of the hash table is empty, we have
5323 |text(p)=0|; if position |p| is either empty or the end of a coalesced
5324 hash list, we have |next(p)=0|.
5325
5326 An auxiliary pointer variable called |hash_used| is maintained in such a
5327 way that all locations |p>=hash_used| are nonempty. The global variable
5328 |st_count| tells how many symbolic tokens have been defined, if statistics
5329 are being kept.
5330
5331 The first 256 locations of |hash| are reserved for symbols of length one.
5332
5333 There's a parallel array called |eqtb| that contains the current equivalent
5334 values of each symbolic token. The entries of this array consist of
5335 two halfwords called |eq_type| (a command code) and |equiv| (a secondary
5336 piece of information that qualifies the |eq_type|).
5337
5338 @d next(A)   mp->hash[(A)].lh /* link for coalesced lists */
5339 @d text(A)   mp->hash[(A)].rh /* string number for symbolic token name */
5340 @d eq_type(A)   mp->eqtb[(A)].lh /* the current ``meaning'' of a symbolic token */
5341 @d equiv(A)   mp->eqtb[(A)].rh /* parametric part of a token's meaning */
5342 @d hash_base 257 /* hashing actually starts here */
5343 @d hash_is_full   (mp->hash_used==hash_base) /* are all positions occupied? */
5344
5345 @<Glob...@>=
5346 pointer hash_used; /* allocation pointer for |hash| */
5347 integer st_count; /* total number of known identifiers */
5348
5349 @ Certain entries in the hash table are ``frozen'' and not redefinable,
5350 since they are used in error recovery.
5351
5352 @d hash_top (hash_base+mp->hash_size) /* the first location of the frozen area */
5353 @d frozen_inaccessible hash_top /* |hash| location to protect the frozen area */
5354 @d frozen_repeat_loop (hash_top+1) /* |hash| location of a loop-repeat token */
5355 @d frozen_right_delimiter (hash_top+2) /* |hash| location of a permanent `\.)' */
5356 @d frozen_left_bracket (hash_top+3) /* |hash| location of a permanent `\.[' */
5357 @d frozen_slash (hash_top+4) /* |hash| location of a permanent `\./' */
5358 @d frozen_colon (hash_top+5) /* |hash| location of a permanent `\.:' */
5359 @d frozen_semicolon (hash_top+6) /* |hash| location of a permanent `\.;' */
5360 @d frozen_end_for (hash_top+7) /* |hash| location of a permanent \&{endfor} */
5361 @d frozen_end_def (hash_top+8) /* |hash| location of a permanent \&{enddef} */
5362 @d frozen_fi (hash_top+9) /* |hash| location of a permanent \&{fi} */
5363 @d frozen_end_group (hash_top+10) /* |hash| location of a permanent `\.{endgroup}' */
5364 @d frozen_etex (hash_top+11) /* |hash| location of a permanent \&{etex} */
5365 @d frozen_mpx_break (hash_top+12) /* |hash| location of a permanent \&{mpxbreak} */
5366 @d frozen_bad_vardef (hash_top+13) /* |hash| location of `\.{a bad variable}' */
5367 @d frozen_undefined (hash_top+14) /* |hash| location that never gets defined */
5368 @d hash_end (hash_top+14) /* the actual size of the |hash| and |eqtb| arrays */
5369
5370 @<Glob...@>=
5371 two_halves *hash; /* the hash table */
5372 two_halves *eqtb; /* the equivalents */
5373
5374 @ @<Allocate or initialize ...@>=
5375 mp->hash = xmalloc((hash_end+1),sizeof(two_halves));
5376 mp->eqtb = xmalloc((hash_end+1),sizeof(two_halves));
5377
5378 @ @<Dealloc variables@>=
5379 xfree(mp->hash);
5380 xfree(mp->eqtb);
5381
5382 @ @<Set init...@>=
5383 next(1)=0; text(1)=0; eq_type(1)=tag_token; equiv(1)=null;
5384 for (k=2;k<=hash_end;k++)  { 
5385   mp->hash[k]=mp->hash[1]; mp->eqtb[k]=mp->eqtb[1];
5386 }
5387
5388 @ @<Initialize table entries...@>=
5389 mp->hash_used=frozen_inaccessible; /* nothing is used */
5390 mp->st_count=0;
5391 text(frozen_bad_vardef)=intern("a bad variable");
5392 text(frozen_etex)=intern("etex");
5393 text(frozen_mpx_break)=intern("mpxbreak");
5394 text(frozen_fi)=intern("fi");
5395 text(frozen_end_group)=intern("endgroup");
5396 text(frozen_end_def)=intern("enddef");
5397 text(frozen_end_for)=intern("endfor");
5398 text(frozen_semicolon)=intern(";");
5399 text(frozen_colon)=intern(":");
5400 text(frozen_slash)=intern("/");
5401 text(frozen_left_bracket)=intern("[");
5402 text(frozen_right_delimiter)=intern(")");
5403 text(frozen_inaccessible)=intern(" INACCESSIBLE");
5404 eq_type(frozen_right_delimiter)=right_delimiter;
5405
5406 @ @<Check the ``constant'' values...@>=
5407 if ( hash_end+mp->max_internal>max_halfword ) mp->bad=17;
5408
5409 @ Here is the subroutine that searches the hash table for an identifier
5410 that matches a given string of length~|l| appearing in |buffer[j..
5411 (j+l-1)]|. If the identifier is not found, it is inserted; hence it
5412 will always be found, and the corresponding hash table address
5413 will be returned.
5414
5415 @c 
5416 pointer mp_id_lookup (MP mp,integer j, integer l) { /* search the hash table */
5417   integer h; /* hash code */
5418   pointer p; /* index in |hash| array */
5419   pointer k; /* index in |buffer| array */
5420   if (l==1) {
5421     @<Treat special case of length 1 and |break|@>;
5422   }
5423   @<Compute the hash code |h|@>;
5424   p=h+hash_base; /* we start searching here; note that |0<=h<hash_prime| */
5425   while (true)  { 
5426         if (text(p)>0 && length(text(p))==l && mp_str_eq_buf(mp, text(p),j)) 
5427       break;
5428     if ( next(p)==0 ) {
5429       @<Insert a new symbolic token after |p|, then
5430         make |p| point to it and |break|@>;
5431     }
5432     p=next(p);
5433   }
5434   return p;
5435 };
5436
5437 @ @<Treat special case of length 1...@>=
5438  p=mp->buffer[j]+1; text(p)=p-1; return p;
5439
5440
5441 @ @<Insert a new symbolic...@>=
5442 {
5443 if ( text(p)>0 ) { 
5444   do {  
5445     if ( hash_is_full )
5446       mp_overflow(mp, "hash size",mp->hash_size);
5447 @:MetaPost capacity exceeded hash size}{\quad hash size@>
5448     decr(mp->hash_used);
5449   } while (text(mp->hash_used)!=0); /* search for an empty location in |hash| */
5450   next(p)=mp->hash_used; 
5451   p=mp->hash_used;
5452 }
5453 str_room(l);
5454 for (k=j;k<=j+l-1;k++) {
5455   append_char(mp->buffer[k]);
5456 }
5457 text(p)=mp_make_string(mp); 
5458 mp->str_ref[text(p)]=max_str_ref;
5459 incr(mp->st_count);
5460 break;
5461 }
5462
5463
5464 @ The value of |hash_prime| should be roughly 85\pct! of |hash_size|, and it
5465 should be a prime number.  The theory of hashing tells us to expect fewer
5466 than two table probes, on the average, when the search is successful.
5467 [See J.~S. Vitter, {\sl Journal of the ACM\/ \bf30} (1983), 231--258.]
5468 @^Vitter, Jeffrey Scott@>
5469
5470 @<Compute the hash code |h|@>=
5471 h=mp->buffer[j];
5472 for (k=j+1;k<=j+l-1;k++){ 
5473   h=h+h+mp->buffer[k];
5474   while ( h>=mp->hash_prime ) h=h-mp->hash_prime;
5475 }
5476
5477 @ @<Search |eqtb| for equivalents equal to |p|@>=
5478 for (q=1;q<=hash_end;q++) { 
5479   if ( equiv(q)==p ) { 
5480     mp_print_nl(mp, "EQUIV("); 
5481     mp_print_int(mp, q); 
5482     mp_print_char(mp, ')');
5483   }
5484 }
5485
5486 @ We need to put \MP's ``primitive'' symbolic tokens into the hash
5487 table, together with their command code (which will be the |eq_type|)
5488 and an operand (which will be the |equiv|). The |primitive| procedure
5489 does this, in a way that no \MP\ user can. The global value |cur_sym|
5490 contains the new |eqtb| pointer after |primitive| has acted.
5491
5492 @c 
5493 void mp_primitive (MP mp, char *ss, halfword c, halfword o) {
5494   pool_pointer k; /* index into |str_pool| */
5495   small_number j; /* index into |buffer| */
5496   small_number l; /* length of the string */
5497   str_number s;
5498   s = intern(ss);
5499   k=mp->str_start[s]; l=str_stop(s)-k;
5500   /* we will move |s| into the (empty) |buffer| */
5501   for (j=0;j<=l-1;j++) {
5502     mp->buffer[j]=mp->str_pool[k+j];
5503   }
5504   mp->cur_sym=mp_id_lookup(mp, 0,l);
5505   if ( s>=256 ) { /* we don't want to have the string twice */
5506     mp_flush_string(mp, text(mp->cur_sym)); text(mp->cur_sym)=s;
5507   };
5508   eq_type(mp->cur_sym)=c; 
5509   equiv(mp->cur_sym)=o;
5510 }
5511
5512
5513 @ Many of \MP's primitives need no |equiv|, since they are identifiable
5514 by their |eq_type| alone. These primitives are loaded into the hash table
5515 as follows:
5516
5517 @<Put each of \MP's primitives into the hash table@>=
5518 mp_primitive(mp, "..",path_join,0);
5519 @:.._}{\.{..} primitive@>
5520 mp_primitive(mp, "[",left_bracket,0); mp->eqtb[frozen_left_bracket]=mp->eqtb[mp->cur_sym];
5521 @:[ }{\.{[} primitive@>
5522 mp_primitive(mp, "]",right_bracket,0);
5523 @:] }{\.{]} primitive@>
5524 mp_primitive(mp, "}",right_brace,0);
5525 @:]]}{\.{\char`\}} primitive@>
5526 mp_primitive(mp, "{",left_brace,0);
5527 @:][}{\.{\char`\{} primitive@>
5528 mp_primitive(mp, ":",colon,0); mp->eqtb[frozen_colon]=mp->eqtb[mp->cur_sym];
5529 @:: }{\.{:} primitive@>
5530 mp_primitive(mp, "::",double_colon,0);
5531 @::: }{\.{::} primitive@>
5532 mp_primitive(mp, "||:",bchar_label,0);
5533 @:::: }{\.{\char'174\char'174:} primitive@>
5534 mp_primitive(mp, ":=",assignment,0);
5535 @::=_}{\.{:=} primitive@>
5536 mp_primitive(mp, ",",comma,0);
5537 @:, }{\., primitive@>
5538 mp_primitive(mp, ";",semicolon,0); mp->eqtb[frozen_semicolon]=mp->eqtb[mp->cur_sym];
5539 @:; }{\.; primitive@>
5540 mp_primitive(mp, "\\",relax,0);
5541 @:]]\\}{\.{\char`\\} primitive@>
5542 @#
5543 mp_primitive(mp, "addto",add_to_command,0);
5544 @:add_to_}{\&{addto} primitive@>
5545 mp_primitive(mp, "atleast",at_least,0);
5546 @:at_least_}{\&{atleast} primitive@>
5547 mp_primitive(mp, "begingroup",begin_group,0); mp->bg_loc=mp->cur_sym;
5548 @:begin_group_}{\&{begingroup} primitive@>
5549 mp_primitive(mp, "controls",controls,0);
5550 @:controls_}{\&{controls} primitive@>
5551 mp_primitive(mp, "curl",curl_command,0);
5552 @:curl_}{\&{curl} primitive@>
5553 mp_primitive(mp, "delimiters",delimiters,0);
5554 @:delimiters_}{\&{delimiters} primitive@>
5555 mp_primitive(mp, "endgroup",end_group,0);
5556  mp->eqtb[frozen_end_group]=mp->eqtb[mp->cur_sym]; mp->eg_loc=mp->cur_sym;
5557 @:endgroup_}{\&{endgroup} primitive@>
5558 mp_primitive(mp, "everyjob",every_job_command,0);
5559 @:every_job_}{\&{everyjob} primitive@>
5560 mp_primitive(mp, "exitif",exit_test,0);
5561 @:exit_if_}{\&{exitif} primitive@>
5562 mp_primitive(mp, "expandafter",expand_after,0);
5563 @:expand_after_}{\&{expandafter} primitive@>
5564 mp_primitive(mp, "interim",interim_command,0);
5565 @:interim_}{\&{interim} primitive@>
5566 mp_primitive(mp, "let",let_command,0);
5567 @:let_}{\&{let} primitive@>
5568 mp_primitive(mp, "newinternal",new_internal,0);
5569 @:new_internal_}{\&{newinternal} primitive@>
5570 mp_primitive(mp, "of",of_token,0);
5571 @:of_}{\&{of} primitive@>
5572 mp_primitive(mp, "randomseed",random_seed,0);
5573 @:random_seed_}{\&{randomseed} primitive@>
5574 mp_primitive(mp, "save",save_command,0);
5575 @:save_}{\&{save} primitive@>
5576 mp_primitive(mp, "scantokens",scan_tokens,0);
5577 @:scan_tokens_}{\&{scantokens} primitive@>
5578 mp_primitive(mp, "shipout",ship_out_command,0);
5579 @:ship_out_}{\&{shipout} primitive@>
5580 mp_primitive(mp, "skipto",skip_to,0);
5581 @:skip_to_}{\&{skipto} primitive@>
5582 mp_primitive(mp, "special",special_command,0);
5583 @:special}{\&{special} primitive@>
5584 mp_primitive(mp, "fontmapfile",special_command,1);
5585 @:fontmapfile}{\&{fontmapfile} primitive@>
5586 mp_primitive(mp, "fontmapline",special_command,2);
5587 @:fontmapline}{\&{fontmapline} primitive@>
5588 mp_primitive(mp, "step",step_token,0);
5589 @:step_}{\&{step} primitive@>
5590 mp_primitive(mp, "str",str_op,0);
5591 @:str_}{\&{str} primitive@>
5592 mp_primitive(mp, "tension",tension,0);
5593 @:tension_}{\&{tension} primitive@>
5594 mp_primitive(mp, "to",to_token,0);
5595 @:to_}{\&{to} primitive@>
5596 mp_primitive(mp, "until",until_token,0);
5597 @:until_}{\&{until} primitive@>
5598 mp_primitive(mp, "within",within_token,0);
5599 @:within_}{\&{within} primitive@>
5600 mp_primitive(mp, "write",write_command,0);
5601 @:write_}{\&{write} primitive@>
5602
5603 @ Each primitive has a corresponding inverse, so that it is possible to
5604 display the cryptic numeric contents of |eqtb| in symbolic form.
5605 Every call of |primitive| in this program is therefore accompanied by some
5606 straightforward code that forms part of the |print_cmd_mod| routine
5607 explained below.
5608
5609 @<Cases of |print_cmd_mod| for symbolic printing of primitives@>=
5610 case add_to_command:mp_print(mp, "addto"); break;
5611 case assignment:mp_print(mp, ":="); break;
5612 case at_least:mp_print(mp, "atleast"); break;
5613 case bchar_label:mp_print(mp, "||:"); break;
5614 case begin_group:mp_print(mp, "begingroup"); break;
5615 case colon:mp_print(mp, ":"); break;
5616 case comma:mp_print(mp, ","); break;
5617 case controls:mp_print(mp, "controls"); break;
5618 case curl_command:mp_print(mp, "curl"); break;
5619 case delimiters:mp_print(mp, "delimiters"); break;
5620 case double_colon:mp_print(mp, "::"); break;
5621 case end_group:mp_print(mp, "endgroup"); break;
5622 case every_job_command:mp_print(mp, "everyjob"); break;
5623 case exit_test:mp_print(mp, "exitif"); break;
5624 case expand_after:mp_print(mp, "expandafter"); break;
5625 case interim_command:mp_print(mp, "interim"); break;
5626 case left_brace:mp_print(mp, "{"); break;
5627 case left_bracket:mp_print(mp, "["); break;
5628 case let_command:mp_print(mp, "let"); break;
5629 case new_internal:mp_print(mp, "newinternal"); break;
5630 case of_token:mp_print(mp, "of"); break;
5631 case path_join:mp_print(mp, ".."); break;
5632 case random_seed:mp_print(mp, "randomseed"); break;
5633 case relax:mp_print_char(mp, '\\'); break;
5634 case right_brace:mp_print(mp, "}"); break;
5635 case right_bracket:mp_print(mp, "]"); break;
5636 case save_command:mp_print(mp, "save"); break;
5637 case scan_tokens:mp_print(mp, "scantokens"); break;
5638 case semicolon:mp_print(mp, ";"); break;
5639 case ship_out_command:mp_print(mp, "shipout"); break;
5640 case skip_to:mp_print(mp, "skipto"); break;
5641 case special_command: if ( m==2 ) mp_print(mp, "fontmapline"); else
5642                  if ( m==1 ) mp_print(mp, "fontmapfile"); else
5643                  mp_print(mp, "special"); break;
5644 case step_token:mp_print(mp, "step"); break;
5645 case str_op:mp_print(mp, "str"); break;
5646 case tension:mp_print(mp, "tension"); break;
5647 case to_token:mp_print(mp, "to"); break;
5648 case until_token:mp_print(mp, "until"); break;
5649 case within_token:mp_print(mp, "within"); break;
5650 case write_command:mp_print(mp, "write"); break;
5651
5652 @ We will deal with the other primitives later, at some point in the program
5653 where their |eq_type| and |equiv| values are more meaningful.  For example,
5654 the primitives for macro definitions will be loaded when we consider the
5655 routines that define macros.
5656 It is easy to find where each particular
5657 primitive was treated by looking in the index at the end; for example, the
5658 section where |"def"| entered |eqtb| is listed under `\&{def} primitive'.
5659
5660 @* \[14] Token lists.
5661 A \MP\ token is either symbolic or numeric or a string, or it denotes
5662 a macro parameter or capsule; so there are five corresponding ways to encode it
5663 @^token@>
5664 internally: (1)~A symbolic token whose hash code is~|p|
5665 is represented by the number |p|, in the |info| field of a single-word
5666 node in~|mem|. (2)~A numeric token whose |scaled| value is~|v| is
5667 represented in a two-word node of~|mem|; the |type| field is |known|,
5668 the |name_type| field is |token|, and the |value| field holds~|v|.
5669 The fact that this token appears in a two-word node rather than a
5670 one-word node is, of course, clear from the node address.
5671 (3)~A string token is also represented in a two-word node; the |type|
5672 field is |mp_string_type|, the |name_type| field is |token|, and the
5673 |value| field holds the corresponding |str_number|.  (4)~Capsules have
5674 |name_type=capsule|, and their |type| and |value| fields represent
5675 arbitrary values (in ways to be explained later).  (5)~Macro parameters
5676 are like symbolic tokens in that they appear in |info| fields of
5677 one-word nodes. The $k$th parameter is represented by |expr_base+k| if it
5678 is of type \&{expr}, or by |suffix_base+k| if it is of type \&{suffix}, or
5679 by |text_base+k| if it is of type \&{text}.  (Here |0<=k<param_size|.)
5680 Actual values of these parameters are kept in a separate stack, as we will
5681 see later.  The constants |expr_base|, |suffix_base|, and |text_base| are,
5682 of course, chosen so that there will be no confusion between symbolic
5683 tokens and parameters of various types.
5684
5685 Note that
5686 the `\\{type}' field of a node has nothing to do with ``type'' in a
5687 printer's sense. It's curious that the same word is used in such different ways.
5688
5689 @d type(A)   mp->mem[(A)].hh.b0 /* identifies what kind of value this is */
5690 @d name_type(A)   mp->mem[(A)].hh.b1 /* a clue to the name of this value */
5691 @d token_node_size 2 /* the number of words in a large token node */
5692 @d value_loc(A) ((A)+1) /* the word that contains the |value| field */
5693 @d value(A) mp->mem[value_loc((A))].cint /* the value stored in a large token node */
5694 @d expr_base (hash_end+1) /* code for the zeroth \&{expr} parameter */
5695 @d suffix_base (expr_base+mp->param_size) /* code for the zeroth \&{suffix} parameter */
5696 @d text_base (suffix_base+mp->param_size) /* code for the zeroth \&{text} parameter */
5697
5698 @<Check the ``constant''...@>=
5699 if ( text_base+mp->param_size>max_halfword ) mp->bad=18;
5700
5701 @ We have set aside a two word node beginning at |null| so that we can have
5702 |value(null)=0|.  We will make use of this coincidence later.
5703
5704 @<Initialize table entries...@>=
5705 link(null)=null; value(null)=0;
5706
5707 @ A numeric token is created by the following trivial routine.
5708
5709 @c 
5710 pointer mp_new_num_tok (MP mp,scaled v) {
5711   pointer p; /* the new node */
5712   p=mp_get_node(mp, token_node_size); value(p)=v;
5713   type(p)=mp_known; name_type(p)=mp_token; 
5714   return p;
5715 }
5716
5717 @ A token list is a singly linked list of nodes in |mem|, where
5718 each node contains a token and a link.  Here's a subroutine that gets rid
5719 of a token list when it is no longer needed.
5720
5721 @<Declarations@>=
5722 void mp_token_recycle (MP mp);
5723
5724
5725 @c void mp_flush_token_list (MP mp,pointer p) {
5726   pointer q; /* the node being recycled */
5727   while ( p!=null ) { 
5728     q=p; p=link(p);
5729     if ( q>=mp->hi_mem_min ) {
5730      free_avail(q);
5731     } else { 
5732       switch (type(q)) {
5733       case mp_vacuous: case mp_boolean_type: case mp_known:
5734         break;
5735       case mp_string_type:
5736         delete_str_ref(value(q));
5737         break;
5738       case unknown_types: case mp_pen_type: case mp_path_type: 
5739       case mp_picture_type: case mp_pair_type: case mp_color_type:
5740       case mp_cmykcolor_type: case mp_transform_type: case mp_dependent:
5741       case mp_proto_dependent: case mp_independent:
5742         mp->g_pointer=q; mp_token_recycle(mp);
5743         break;
5744       default: mp_confusion(mp, "token");
5745 @:this can't happen token}{\quad token@>
5746       }
5747       mp_free_node(mp, q,token_node_size);
5748     }
5749   }
5750 }
5751
5752 @ The procedure |show_token_list|, which prints a symbolic form of
5753 the token list that starts at a given node |p|, illustrates these
5754 conventions. The token list being displayed should not begin with a reference
5755 count. However, the procedure is intended to be fairly robust, so that if the
5756 memory links are awry or if |p| is not really a pointer to a token list,
5757 almost nothing catastrophic can happen.
5758
5759 An additional parameter |q| is also given; this parameter is either null
5760 or it points to a node in the token list where a certain magic computation
5761 takes place that will be explained later. (Basically, |q| is non-null when
5762 we are printing the two-line context information at the time of an error
5763 message; |q| marks the place corresponding to where the second line
5764 should begin.)
5765
5766 The generation will stop, and `\.{\char`\ ETC.}' will be printed, if the length
5767 of printing exceeds a given limit~|l|; the length of printing upon entry is
5768 assumed to be a given amount called |null_tally|. (Note that
5769 |show_token_list| sometimes uses itself recursively to print
5770 variable names within a capsule.)
5771 @^recursion@>
5772
5773 Unusual entries are printed in the form of all-caps tokens
5774 preceded by a space, e.g., `\.{\char`\ BAD}'.
5775
5776 @<Declarations@>=
5777 void mp_print_capsule (MP mp);
5778
5779 @ @<Declare the procedure called |show_token_list|@>=
5780 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5781                          integer null_tally) ;
5782
5783 @ @c
5784 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5785                          integer null_tally) {
5786   small_number class,c; /* the |char_class| of previous and new tokens */
5787   integer r,v; /* temporary registers */
5788   class=percent_class;
5789   mp->tally=null_tally;
5790   while ( (p!=null) && (mp->tally<l) ) { 
5791     if ( p==q ) 
5792       @<Do magic computation@>;
5793     @<Display token |p| and set |c| to its class;
5794       but |return| if there are problems@>;
5795     class=c; p=link(p);
5796   }
5797   if ( p!=null ) 
5798      mp_print(mp, " ETC.");
5799 @.ETC@>
5800   return;
5801 };
5802
5803 @ @<Display token |p| and set |c| to its class...@>=
5804 c=letter_class; /* the default */
5805 if ( (p<0)||(p>mp->mem_end) ) { 
5806   mp_print(mp, " CLOBBERED"); return;
5807 @.CLOBBERED@>
5808 }
5809 if ( p<mp->hi_mem_min ) { 
5810   @<Display two-word token@>;
5811 } else { 
5812   r=info(p);
5813   if ( r>=expr_base ) {
5814      @<Display a parameter token@>;
5815   } else {
5816     if ( r<1 ) {
5817       if ( r==0 ) { 
5818         @<Display a collective subscript@>
5819       } else {
5820         mp_print(mp, " IMPOSSIBLE");
5821 @.IMPOSSIBLE@>
5822       }
5823     } else { 
5824       r=text(r);
5825       if ( (r<0)||(r>mp->max_str_ptr) ) {
5826         mp_print(mp, " NONEXISTENT");
5827 @.NONEXISTENT@>
5828       } else {
5829        @<Print string |r| as a symbolic token
5830         and set |c| to its class@>;
5831       }
5832     }
5833   }
5834 }
5835
5836 @ @<Display two-word token@>=
5837 if ( name_type(p)==mp_token ) {
5838   if ( type(p)==mp_known ) {
5839     @<Display a numeric token@>;
5840   } else if ( type(p)!=mp_string_type ) {
5841     mp_print(mp, " BAD");
5842 @.BAD@>
5843   } else { 
5844     mp_print_char(mp, '"'); mp_print_str(mp, value(p)); mp_print_char(mp, '"');
5845     c=string_class;
5846   }
5847 } else if ((name_type(p)!=mp_capsule)||(type(p)<mp_vacuous)||(type(p)>mp_independent) ) {
5848   mp_print(mp, " BAD");
5849 } else { 
5850   mp->g_pointer=p; mp_print_capsule(mp); c=right_paren_class;
5851 }
5852
5853 @ @<Display a numeric token@>=
5854 if ( class==digit_class ) 
5855   mp_print_char(mp, ' ');
5856 v=value(p);
5857 if ( v<0 ){ 
5858   if ( class==left_bracket_class ) 
5859     mp_print_char(mp, ' ');
5860   mp_print_char(mp, '['); mp_print_scaled(mp, v); mp_print_char(mp, ']');
5861   c=right_bracket_class;
5862 } else { 
5863   mp_print_scaled(mp, v); c=digit_class;
5864 }
5865
5866
5867 @ Strictly speaking, a genuine token will never have |info(p)=0|.
5868 But we will see later (in the |print_variable_name| routine) that
5869 it is convenient to let |info(p)=0| stand for `\.{[]}'.
5870
5871 @<Display a collective subscript@>=
5872 {
5873 if ( class==left_bracket_class ) 
5874   mp_print_char(mp, ' ');
5875 mp_print(mp, "[]"); c=right_bracket_class;
5876 }
5877
5878 @ @<Display a parameter token@>=
5879 {
5880 if ( r<suffix_base ) { 
5881   mp_print(mp, "(EXPR"); r=r-(expr_base);
5882 @.EXPR@>
5883 } else if ( r<text_base ) { 
5884   mp_print(mp, "(SUFFIX"); r=r-(suffix_base);
5885 @.SUFFIX@>
5886 } else { 
5887   mp_print(mp, "(TEXT"); r=r-(text_base);
5888 @.TEXT@>
5889 }
5890 mp_print_int(mp, r); mp_print_char(mp, ')'); c=right_paren_class;
5891 }
5892
5893
5894 @ @<Print string |r| as a symbolic token...@>=
5895
5896 c=mp->char_class[mp->str_pool[mp->str_start[r]]];
5897 if ( c==class ) {
5898   switch (c) {
5899   case letter_class:mp_print_char(mp, '.'); break;
5900   case isolated_classes: break;
5901   default: mp_print_char(mp, ' '); break;
5902   }
5903 }
5904 mp_print_str(mp, r);
5905 }
5906
5907 @ The following procedures have been declared |forward| with no parameters,
5908 because the author dislikes \PASCAL's convention about |forward| procedures
5909 with parameters. It was necessary to do something, because |show_token_list|
5910 is recursive (although the recursion is limited to one level), and because
5911 |flush_token_list| is syntactically (but not semantically) recursive.
5912 @^recursion@>
5913
5914 @<Declare miscellaneous procedures that were declared |forward|@>=
5915 void mp_print_capsule (MP mp) { 
5916   mp_print_char(mp, '('); mp_print_exp(mp, mp->g_pointer,0); mp_print_char(mp, ')');
5917 };
5918 @#
5919 void mp_token_recycle (MP mp) { 
5920   mp_recycle_value(mp, mp->g_pointer);
5921 };
5922
5923 @ @<Glob...@>=
5924 pointer g_pointer; /* (global) parameter to the |forward| procedures */
5925
5926 @ Macro definitions are kept in \MP's memory in the form of token lists
5927 that have a few extra one-word nodes at the beginning.
5928
5929 The first node contains a reference count that is used to tell when the
5930 list is no longer needed. To emphasize the fact that a reference count is
5931 present, we shall refer to the |info| field of this special node as the
5932 |ref_count| field.
5933 @^reference counts@>
5934
5935 The next node or nodes after the reference count serve to describe the
5936 formal parameters. They either contain a code word that specifies all
5937 of the parameters, or they contain zero or more parameter tokens followed
5938 by the code `|general_macro|'.
5939
5940 @d ref_count info
5941   /* reference count preceding a macro definition or picture header */
5942 @d add_mac_ref(A) incr(ref_count((A))) /* make a new reference to a macro list */
5943 @d general_macro 0 /* preface to a macro defined with a parameter list */
5944 @d primary_macro 1 /* preface to a macro with a \&{primary} parameter */
5945 @d secondary_macro 2 /* preface to a macro with a \&{secondary} parameter */
5946 @d tertiary_macro 3 /* preface to a macro with a \&{tertiary} parameter */
5947 @d expr_macro 4 /* preface to a macro with an undelimited \&{expr} parameter */
5948 @d of_macro 5 /* preface to a macro with
5949   undelimited `\&{expr} |x| \&{of}~|y|' parameters */
5950 @d suffix_macro 6 /* preface to a macro with an undelimited \&{suffix} parameter */
5951 @d text_macro 7 /* preface to a macro with an undelimited \&{text} parameter */
5952
5953 @c 
5954 void mp_delete_mac_ref (MP mp,pointer p) {
5955   /* |p| points to the reference count of a macro list that is
5956     losing one reference */
5957   if ( ref_count(p)==null ) mp_flush_token_list(mp, p);
5958   else decr(ref_count(p));
5959 }
5960
5961 @ The following subroutine displays a macro, given a pointer to its
5962 reference count.
5963
5964 @c 
5965 @<Declare the procedure called |print_cmd_mod|@>;
5966 void mp_show_macro (MP mp, pointer p, integer q, integer l) {
5967   pointer r; /* temporary storage */
5968   p=link(p); /* bypass the reference count */
5969   while ( info(p)>text_macro ){ 
5970     r=link(p); link(p)=null;
5971     mp_show_token_list(mp, p,null,l,0); link(p)=r; p=r;
5972     if ( l>0 ) l=l-mp->tally; else return;
5973   } /* control printing of `\.{ETC.}' */
5974 @.ETC@>
5975   mp->tally=0;
5976   switch(info(p)) {
5977   case general_macro:mp_print(mp, "->"); break;
5978 @.->@>
5979   case primary_macro: case secondary_macro: case tertiary_macro:
5980     mp_print_char(mp, '<');
5981     mp_print_cmd_mod(mp, param_type,info(p)); 
5982     mp_print(mp, ">->");
5983     break;
5984   case expr_macro:mp_print(mp, "<expr>->"); break;
5985   case of_macro:mp_print(mp, "<expr>of<primary>->"); break;
5986   case suffix_macro:mp_print(mp, "<suffix>->"); break;
5987   case text_macro:mp_print(mp, "<text>->"); break;
5988   } /* there are no other cases */
5989   mp_show_token_list(mp, link(p),q,l-mp->tally,0);
5990 }
5991
5992 @* \[15] Data structures for variables.
5993 The variables of \MP\ programs can be simple, like `\.x', or they can
5994 combine the structural properties of arrays and records, like `\.{x20a.b}'.
5995 A \MP\ user assigns a type to a variable like \.{x20a.b} by saying, for
5996 example, `\.{boolean} \.{x20a.b}'. It's time for us to study how such
5997 things are represented inside of the computer.
5998
5999 Each variable value occupies two consecutive words, either in a two-word
6000 node called a value node, or as a two-word subfield of a larger node.  One
6001 of those two words is called the |value| field; it is an integer,
6002 containing either a |scaled| numeric value or the representation of some
6003 other type of quantity. (It might also be subdivided into halfwords, in
6004 which case it is referred to by other names instead of |value|.) The other
6005 word is broken into subfields called |type|, |name_type|, and |link|.  The
6006 |type| field is a quarterword that specifies the variable's type, and
6007 |name_type| is a quarterword from which \MP\ can reconstruct the
6008 variable's name (sometimes by using the |link| field as well).  Thus, only
6009 1.25 words are actually devoted to the value itself; the other
6010 three-quarters of a word are overhead, but they aren't wasted because they
6011 allow \MP\ to deal with sparse arrays and to provide meaningful diagnostics.
6012
6013 In this section we shall be concerned only with the structural aspects of
6014 variables, not their values. Later parts of the program will change the
6015 |type| and |value| fields, but we shall treat those fields as black boxes
6016 whose contents should not be touched.
6017
6018 However, if the |type| field is |mp_structured|, there is no |value| field,
6019 and the second word is broken into two pointer fields called |attr_head|
6020 and |subscr_head|. Those fields point to additional nodes that
6021 contain structural information, as we shall see.
6022
6023 @d subscr_head_loc(A)   (A)+1 /* where |value|, |subscr_head| and |attr_head| are */
6024 @d attr_head(A)   info(subscr_head_loc((A))) /* pointer to attribute info */
6025 @d subscr_head(A)   link(subscr_head_loc((A))) /* pointer to subscript info */
6026 @d value_node_size 2 /* the number of words in a value node */
6027
6028 @ An attribute node is three words long. Two of these words contain |type|
6029 and |value| fields as described above, and the third word contains
6030 additional information:  There is an |attr_loc| field, which contains the
6031 hash address of the token that names this attribute; and there's also a
6032 |parent| field, which points to the value node of |mp_structured| type at the
6033 next higher level (i.e., at the level to which this attribute is
6034 subsidiary).  The |name_type| in an attribute node is `|attr|'.  The
6035 |link| field points to the next attribute with the same parent; these are
6036 arranged in increasing order, so that |attr_loc(link(p))>attr_loc(p)|. The
6037 final attribute node links to the constant |end_attr|, whose |attr_loc|
6038 field is greater than any legal hash address. The |attr_head| in the
6039 parent points to a node whose |name_type| is |mp_structured_root|; this
6040 node represents the null attribute, i.e., the variable that is relevant
6041 when no attributes are attached to the parent. The |attr_head| node is either
6042 a value node, a subscript node, or an attribute node, depending on what
6043 the parent would be if it were not structured; but the subscript and
6044 attribute fields are ignored, so it effectively contains only the data of
6045 a value node. The |link| field in this special node points to an attribute
6046 node whose |attr_loc| field is zero; the latter node represents a collective
6047 subscript `\.{[]}' attached to the parent, and its |link| field points to
6048 the first non-special attribute node (or to |end_attr| if there are none).
6049
6050 A subscript node likewise occupies three words, with |type| and |value| fields
6051 plus extra information; its |name_type| is |subscr|. In this case the
6052 third word is called the |subscript| field, which is a |scaled| integer.
6053 The |link| field points to the subscript node with the next larger
6054 subscript, if any; otherwise the |link| points to the attribute node
6055 for collective subscripts at this level. We have seen that the latter node
6056 contains an upward pointer, so that the parent can be deduced.
6057
6058 The |name_type| in a parent-less value node is |root|, and the |link|
6059 is the hash address of the token that names this value.
6060
6061 In other words, variables have a hierarchical structure that includes
6062 enough threads running around so that the program is able to move easily
6063 between siblings, parents, and children. An example should be helpful:
6064 (The reader is advised to draw a picture while reading the following
6065 description, since that will help to firm up the ideas.)
6066 Suppose that `\.x' and `\.{x.a}' and `\.{x[]b}' and `\.{x5}'
6067 and `\.{x20b}' have been mentioned in a user's program, where
6068 \.{x[]b} has been declared to be of \&{boolean} type. Let |h(x)|, |h(a)|,
6069 and |h(b)| be the hash addresses of \.x, \.a, and~\.b. Then
6070 |eq_type(h(x))=name| and |equiv(h(x))=p|, where |p|~is a two-word value
6071 node with |name_type(p)=root| and |link(p)=h(x)|. We have |type(p)=mp_structured|,
6072 |attr_head(p)=q|, and |subscr_head(p)=r|, where |q| points to a value
6073 node and |r| to a subscript node. (Are you still following this? Use
6074 a pencil to draw a diagram.) The lone variable `\.x' is represented by
6075 |type(q)| and |value(q)|; furthermore
6076 |name_type(q)=mp_structured_root| and |link(q)=q1|, where |q1| points
6077 to an attribute node representing `\.{x[]}'. Thus |name_type(q1)=attr|,
6078 |attr_loc(q1)=collective_subscript=0|, |parent(q1)=p|,
6079 |type(q1)=mp_structured|, |attr_head(q1)=qq|, and |subscr_head(q1)=qq1|;
6080 |qq| is a value node with |type(qq)=mp_numeric_type| (assuming that \.{x5} is
6081 numeric, because |qq| represents `\.{x[]}' with no further attributes),
6082 |name_type(qq)=mp_structured_root|, and
6083 |link(qq)=qq1|. (Now pay attention to the next part.) Node |qq1| is
6084 an attribute node representing `\.{x[][]}', which has never yet
6085 occurred; its |type| field is |undefined|, and its |value| field is
6086 undefined. We have |name_type(qq1)=attr|, |attr_loc(qq1)=collective_subscript|,
6087 |parent(qq1)=q1|, and |link(qq1)=qq2|. Since |qq2| represents
6088 `\.{x[]b}', |type(qq2)=mp_unknown_boolean|; also |attr_loc(qq2)=h(b)|,
6089 |parent(qq2)=q1|, |name_type(qq2)=attr|, |link(qq2)=end_attr|.
6090 (Maybe colored lines will help untangle your picture.)
6091  Node |r| is a subscript node with |type| and |value|
6092 representing `\.{x5}'; |name_type(r)=subscr|, |subscript(r)=5.0|,
6093 and |link(r)=r1| is another subscript node. To complete the picture,
6094 see if you can guess what |link(r1)| is; give up? It's~|q1|.
6095 Furthermore |subscript(r1)=20.0|, |name_type(r1)=subscr|,
6096 |type(r1)=mp_structured|, |attr_head(r1)=qqq|, |subscr_head(r1)=qqq1|,
6097 and we finish things off with three more nodes
6098 |qqq|, |qqq1|, and |qqq2| hung onto~|r1|. (Perhaps you should start again
6099 with a larger sheet of paper.) The value of variable \.{x20b}
6100 appears in node~|qqq2|, as you can well imagine.
6101
6102 If the example in the previous paragraph doesn't make things crystal
6103 clear, a glance at some of the simpler subroutines below will reveal how
6104 things work out in practice.
6105
6106 The only really unusual thing about these conventions is the use of
6107 collective subscript attributes. The idea is to avoid repeating a lot of
6108 type information when many elements of an array are identical macros
6109 (for which distinct values need not be stored) or when they don't have
6110 all of the possible attributes. Branches of the structure below collective
6111 subscript attributes do not carry actual values except for macro identifiers;
6112 branches of the structure below subscript nodes do not carry significant
6113 information in their collective subscript attributes.
6114
6115 @d attr_loc_loc(A) ((A)+2) /* where the |attr_loc| and |parent| fields are */
6116 @d attr_loc(A) info(attr_loc_loc((A))) /* hash address of this attribute */
6117 @d parent(A) link(attr_loc_loc((A))) /* pointer to |mp_structured| variable */
6118 @d subscript_loc(A) ((A)+2) /* where the |subscript| field lives */
6119 @d subscript(A) mp->mem[subscript_loc((A))].sc /* subscript of this variable */
6120 @d attr_node_size 3 /* the number of words in an attribute node */
6121 @d subscr_node_size 3 /* the number of words in a subscript node */
6122 @d collective_subscript 0 /* code for the attribute `\.{[]}' */
6123
6124 @<Initialize table...@>=
6125 attr_loc(end_attr)=hash_end+1; parent(end_attr)=null;
6126
6127 @ Variables of type \&{pair} will have values that point to four-word
6128 nodes containing two numeric values. The first of these values has
6129 |name_type=mp_x_part_sector| and the second has |name_type=mp_y_part_sector|;
6130 the |link| in the first points back to the node whose |value| points
6131 to this four-word node.
6132
6133 Variables of type \&{transform} are similar, but in this case their
6134 |value| points to a 12-word node containing six values, identified by
6135 |x_part_sector|, |y_part_sector|, |mp_xx_part_sector|, |mp_xy_part_sector|,
6136 |mp_yx_part_sector|, and |mp_yy_part_sector|.
6137 Finally, variables of type \&{color} have three values in six words
6138 identified by |mp_red_part_sector|, |mp_green_part_sector|, and |mp_blue_part_sector|.
6139
6140 When an entire structured variable is saved, the |root| indication
6141 is temporarily replaced by |saved_root|.
6142
6143 Some variables have no name; they just are used for temporary storage
6144 while expressions are being evaluated. We call them {\sl capsules}.
6145
6146 @d x_part_loc(A) (A) /* where the \&{xpart} is found in a pair or transform node */
6147 @d y_part_loc(A) ((A)+2) /* where the \&{ypart} is found in a pair or transform node */
6148 @d xx_part_loc(A) ((A)+4) /* where the \&{xxpart} is found in a transform node */
6149 @d xy_part_loc(A) ((A)+6) /* where the \&{xypart} is found in a transform node */
6150 @d yx_part_loc(A) ((A)+8) /* where the \&{yxpart} is found in a transform node */
6151 @d yy_part_loc(A) ((A)+10) /* where the \&{yypart} is found in a transform node */
6152 @d red_part_loc(A) (A) /* where the \&{redpart} is found in a color node */
6153 @d green_part_loc(A) ((A)+2) /* where the \&{greenpart} is found in a color node */
6154 @d blue_part_loc(A) ((A)+4) /* where the \&{bluepart} is found in a color node */
6155 @d cyan_part_loc(A) (A) /* where the \&{cyanpart} is found in a color node */
6156 @d magenta_part_loc(A) ((A)+2) /* where the \&{magentapart} is found in a color node */
6157 @d yellow_part_loc(A) ((A)+4) /* where the \&{yellowpart} is found in a color node */
6158 @d black_part_loc(A) ((A)+6) /* where the \&{blackpart} is found in a color node */
6159 @d grey_part_loc(A) (A) /* where the \&{greypart} is found in a color node */
6160 @#
6161 @d pair_node_size 4 /* the number of words in a pair node */
6162 @d transform_node_size 12 /* the number of words in a transform node */
6163 @d color_node_size 6 /* the number of words in a color node */
6164 @d cmykcolor_node_size 8 /* the number of words in a color node */
6165
6166 @<Glob...@>=
6167 small_number big_node_size[mp_pair_type+1];
6168 small_number sector0[mp_pair_type+1];
6169 small_number sector_offset[mp_black_part_sector+1];
6170
6171 @ The |sector0| array gives for each big node type, |name_type| values
6172 for its first subfield; the |sector_offset| array gives for each
6173 |name_type| value, the offset from the first subfield in words;
6174 and the |big_node_size| array gives the size in words for each type of
6175 big node.
6176
6177 @<Set init...@>=
6178 mp->big_node_size[mp_transform_type]=transform_node_size;
6179 mp->big_node_size[mp_pair_type]=pair_node_size;
6180 mp->big_node_size[mp_color_type]=color_node_size;
6181 mp->big_node_size[mp_cmykcolor_type]=cmykcolor_node_size;
6182 mp->sector0[mp_transform_type]=mp_x_part_sector;
6183 mp->sector0[mp_pair_type]=mp_x_part_sector;
6184 mp->sector0[mp_color_type]=mp_red_part_sector;
6185 mp->sector0[mp_cmykcolor_type]=mp_cyan_part_sector;
6186 for (k=mp_x_part_sector;k<= mp_yy_part_sector;k++ ) {
6187   mp->sector_offset[k]=2*(k-mp_x_part_sector);
6188 }
6189 for (k=mp_red_part_sector;k<= mp_blue_part_sector ; k++) {
6190   mp->sector_offset[k]=2*(k-mp_red_part_sector);
6191 }
6192 for (k=mp_cyan_part_sector;k<= mp_black_part_sector;k++ ) {
6193   mp->sector_offset[k]=2*(k-mp_cyan_part_sector);
6194 }
6195
6196 @ If |type(p)=mp_pair_type| or |mp_transform_type| and if |value(p)=null|, the
6197 procedure call |init_big_node(p)| will allocate a pair or transform node
6198 for~|p|.  The individual parts of such nodes are initially of type
6199 |mp_independent|.
6200
6201 @c 
6202 void mp_init_big_node (MP mp,pointer p) {
6203   pointer q; /* the new node */
6204   small_number s; /* its size */
6205   s=mp->big_node_size[type(p)]; q=mp_get_node(mp, s);
6206   do {  
6207     s=s-2; 
6208     @<Make variable |q+s| newly independent@>;
6209     name_type(q+s)=halfp(s)+mp->sector0[type(p)]; 
6210     link(q+s)=null;
6211   } while (s!=0);
6212   link(q)=p; value(p)=q;
6213 }
6214
6215 @ The |id_transform| function creates a capsule for the
6216 identity transformation.
6217
6218 @c 
6219 pointer mp_id_transform (MP mp) {
6220   pointer p,q,r; /* list manipulation registers */
6221   p=mp_get_node(mp, value_node_size); type(p)=mp_transform_type;
6222   name_type(p)=mp_capsule; value(p)=null; mp_init_big_node(mp, p); q=value(p);
6223   r=q+transform_node_size;
6224   do {  
6225     r=r-2;
6226     type(r)=mp_known; value(r)=0;
6227   } while (r!=q);
6228   value(xx_part_loc(q))=unity; 
6229   value(yy_part_loc(q))=unity;
6230   return p;
6231 }
6232
6233 @ Tokens are of type |tag_token| when they first appear, but they point
6234 to |null| until they are first used as the root of a variable.
6235 The following subroutine establishes the root node on such grand occasions.
6236
6237 @c 
6238 void mp_new_root (MP mp,pointer x) {
6239   pointer p; /* the new node */
6240   p=mp_get_node(mp, value_node_size); type(p)=undefined; name_type(p)=mp_root;
6241   link(p)=x; equiv(x)=p;
6242 }
6243
6244 @ These conventions for variable representation are illustrated by the
6245 |print_variable_name| routine, which displays the full name of a
6246 variable given only a pointer to its two-word value packet.
6247
6248 @<Declarations@>=
6249 void mp_print_variable_name (MP mp, pointer p);
6250
6251 @ @c 
6252 void mp_print_variable_name (MP mp, pointer p) {
6253   pointer q; /* a token list that will name the variable's suffix */
6254   pointer r; /* temporary for token list creation */
6255   while ( name_type(p)>=mp_x_part_sector ) {
6256     @<Preface the output with a part specifier; |return| in the
6257       case of a capsule@>;
6258   }
6259   q=null;
6260   while ( name_type(p)>mp_saved_root ) {
6261     @<Ascend one level, pushing a token onto list |q|
6262      and replacing |p| by its parent@>;
6263   }
6264   r=mp_get_avail(mp); info(r)=link(p); link(r)=q;
6265   if ( name_type(p)==mp_saved_root ) mp_print(mp, "(SAVED)");
6266 @.SAVED@>
6267   mp_show_token_list(mp, r,null,el_gordo,mp->tally); 
6268   mp_flush_token_list(mp, r);
6269 }
6270
6271 @ @<Ascend one level, pushing a token onto list |q|...@>=
6272
6273   if ( name_type(p)==mp_subscr ) { 
6274     r=mp_new_num_tok(mp, subscript(p));
6275     do {  
6276       p=link(p);
6277     } while (name_type(p)!=mp_attr);
6278   } else if ( name_type(p)==mp_structured_root ) {
6279     p=link(p); goto FOUND;
6280   } else { 
6281     if ( name_type(p)!=mp_attr ) mp_confusion(mp, "var");
6282 @:this can't happen var}{\quad var@>
6283     r=mp_get_avail(mp); info(r)=attr_loc(p);
6284   }
6285   link(r)=q; q=r;
6286 FOUND:  
6287   p=parent(p);
6288 }
6289
6290 @ @<Preface the output with a part specifier...@>=
6291 { switch (name_type(p)) {
6292   case mp_x_part_sector: mp_print_char(mp, 'x'); break;
6293   case mp_y_part_sector: mp_print_char(mp, 'y'); break;
6294   case mp_xx_part_sector: mp_print(mp, "xx"); break;
6295   case mp_xy_part_sector: mp_print(mp, "xy"); break;
6296   case mp_yx_part_sector: mp_print(mp, "yx"); break;
6297   case mp_yy_part_sector: mp_print(mp, "yy"); break;
6298   case mp_red_part_sector: mp_print(mp, "red"); break;
6299   case mp_green_part_sector: mp_print(mp, "green"); break;
6300   case mp_blue_part_sector: mp_print(mp, "blue"); break;
6301   case mp_cyan_part_sector: mp_print(mp, "cyan"); break;
6302   case mp_magenta_part_sector: mp_print(mp, "magenta"); break;
6303   case mp_yellow_part_sector: mp_print(mp, "yellow"); break;
6304   case mp_black_part_sector: mp_print(mp, "black"); break;
6305   case mp_grey_part_sector: mp_print(mp, "grey"); break;
6306   case mp_capsule: 
6307     mp_print(mp, "%CAPSULE"); mp_print_int(mp, p-null); return;
6308     break;
6309 @.CAPSULE@>
6310   } /* there are no other cases */
6311   mp_print(mp, "part "); 
6312   p=link(p-mp->sector_offset[name_type(p)]);
6313 }
6314
6315 @ The |interesting| function returns |true| if a given variable is not
6316 in a capsule, or if the user wants to trace capsules.
6317
6318 @c 
6319 boolean mp_interesting (MP mp,pointer p) {
6320   small_number t; /* a |name_type| */
6321   if ( mp->internal[mp_tracing_capsules]>0 ) {
6322     return true;
6323   } else { 
6324     t=name_type(p);
6325     if ( t>=mp_x_part_sector ) if ( t!=mp_capsule )
6326       t=name_type(link(p-mp->sector_offset[t]));
6327     return (t!=mp_capsule);
6328   }
6329 }
6330
6331 @ Now here is a subroutine that converts an unstructured type into an
6332 equivalent structured type, by inserting a |mp_structured| node that is
6333 capable of growing. This operation is done only when |name_type(p)=root|,
6334 |subscr|, or |attr|.
6335
6336 The procedure returns a pointer to the new node that has taken node~|p|'s
6337 place in the structure. Node~|p| itself does not move, nor are its
6338 |value| or |type| fields changed in any way.
6339
6340 @c 
6341 pointer mp_new_structure (MP mp,pointer p) {
6342   pointer q,r=0; /* list manipulation registers */
6343   switch (name_type(p)) {
6344   case mp_root: 
6345     q=link(p); r=mp_get_node(mp, value_node_size); equiv(q)=r;
6346     break;
6347   case mp_subscr: 
6348     @<Link a new subscript node |r| in place of node |p|@>;
6349     break;
6350   case mp_attr: 
6351     @<Link a new attribute node |r| in place of node |p|@>;
6352     break;
6353   default: 
6354     mp_confusion(mp, "struct");
6355 @:this can't happen struct}{\quad struct@>
6356     break;
6357   }
6358   link(r)=link(p); type(r)=mp_structured; name_type(r)=name_type(p);
6359   attr_head(r)=p; name_type(p)=mp_structured_root;
6360   q=mp_get_node(mp, attr_node_size); link(p)=q; subscr_head(r)=q;
6361   parent(q)=r; type(q)=undefined; name_type(q)=mp_attr; link(q)=end_attr;
6362   attr_loc(q)=collective_subscript; 
6363   return r;
6364 };
6365
6366 @ @<Link a new subscript node |r| in place of node |p|@>=
6367
6368   q=p;
6369   do {  
6370     q=link(q);
6371   } while (name_type(q)!=mp_attr);
6372   q=parent(q); r=subscr_head_loc(q); /* |link(r)=subscr_head(q)| */
6373   do {  
6374     q=r; r=link(r);
6375   } while (r!=p);
6376   r=mp_get_node(mp, subscr_node_size);
6377   link(q)=r; subscript(r)=subscript(p);
6378 }
6379
6380 @ If the attribute is |collective_subscript|, there are two pointers to
6381 node~|p|, so we must change both of them.
6382
6383 @<Link a new attribute node |r| in place of node |p|@>=
6384
6385   q=parent(p); r=attr_head(q);
6386   do {  
6387     q=r; r=link(r);
6388   } while (r!=p);
6389   r=mp_get_node(mp, attr_node_size); link(q)=r;
6390   mp->mem[attr_loc_loc(r)]=mp->mem[attr_loc_loc(p)]; /* copy |attr_loc| and |parent| */
6391   if ( attr_loc(p)==collective_subscript ) { 
6392     q=subscr_head_loc(parent(p));
6393     while ( link(q)!=p ) q=link(q);
6394     link(q)=r;
6395   }
6396 }
6397
6398 @ The |find_variable| routine is given a pointer~|t| to a nonempty token
6399 list of suffixes; it returns a pointer to the corresponding two-word
6400 value. For example, if |t| points to token \.x followed by a numeric
6401 token containing the value~7, |find_variable| finds where the value of
6402 \.{x7} is stored in memory. This may seem a simple task, and it
6403 usually is, except when \.{x7} has never been referenced before.
6404 Indeed, \.x may never have even been subscripted before; complexities
6405 arise with respect to updating the collective subscript information.
6406
6407 If a macro type is detected anywhere along path~|t|, or if the first
6408 item on |t| isn't a |tag_token|, the value |null| is returned.
6409 Otherwise |p| will be a non-null pointer to a node such that
6410 |undefined<type(p)<mp_structured|.
6411
6412 @d abort_find { return null; }
6413
6414 @c 
6415 pointer mp_find_variable (MP mp,pointer t) {
6416   pointer p,q,r,s; /* nodes in the ``value'' line */
6417   pointer pp,qq,rr,ss; /* nodes in the ``collective'' line */
6418   integer n; /* subscript or attribute */
6419   memory_word save_word; /* temporary storage for a word of |mem| */
6420 @^inner loop@>
6421   p=info(t); t=link(t);
6422   if ( (eq_type(p) % outer_tag) != tag_token ) abort_find;
6423   if ( equiv(p)==null ) mp_new_root(mp, p);
6424   p=equiv(p); pp=p;
6425   while ( t!=null ) { 
6426     @<Make sure that both nodes |p| and |pp| are of |mp_structured| type@>;
6427     if ( t<mp->hi_mem_min ) {
6428       @<Descend one level for the subscript |value(t)|@>
6429     } else {
6430       @<Descend one level for the attribute |info(t)|@>;
6431     }
6432     t=link(t);
6433   }
6434   if ( type(pp)>=mp_structured ) {
6435     if ( type(pp)==mp_structured ) pp=attr_head(pp); else abort_find;
6436   }
6437   if ( type(p)==mp_structured ) p=attr_head(p);
6438   if ( type(p)==undefined ) { 
6439     if ( type(pp)==undefined ) { type(pp)=mp_numeric_type; value(pp)=null; };
6440     type(p)=type(pp); value(p)=null;
6441   };
6442   return p;
6443 }
6444
6445 @ Although |pp| and |p| begin together, they diverge when a subscript occurs;
6446 |pp|~stays in the collective line while |p|~goes through actual subscript
6447 values.
6448
6449 @<Make sure that both nodes |p| and |pp|...@>=
6450 if ( type(pp)!=mp_structured ) { 
6451   if ( type(pp)>mp_structured ) abort_find;
6452   ss=mp_new_structure(mp, pp);
6453   if ( p==pp ) p=ss;
6454   pp=ss;
6455 }; /* now |type(pp)=mp_structured| */
6456 if ( type(p)!=mp_structured ) /* it cannot be |>mp_structured| */
6457   p=mp_new_structure(mp, p) /* now |type(p)=mp_structured| */
6458
6459 @ We want this part of the program to be reasonably fast, in case there are
6460 @^inner loop@>
6461 lots of subscripts at the same level of the data structure. Therefore
6462 we store an ``infinite'' value in the word that appears at the end of the
6463 subscript list, even though that word isn't part of a subscript node.
6464
6465 @<Descend one level for the subscript |value(t)|@>=
6466
6467   n=value(t);
6468   pp=link(attr_head(pp)); /* now |attr_loc(pp)=collective_subscript| */
6469   q=link(attr_head(p)); save_word=mp->mem[subscript_loc(q)];
6470   subscript(q)=el_gordo; s=subscr_head_loc(p); /* |link(s)=subscr_head(p)| */
6471   do {  
6472     r=s; s=link(s);
6473   } while (n>subscript(s));
6474   if ( n==subscript(s) ) {
6475     p=s;
6476   } else { 
6477     p=mp_get_node(mp, subscr_node_size); link(r)=p; link(p)=s;
6478     subscript(p)=n; name_type(p)=mp_subscr; type(p)=undefined;
6479   }
6480   mp->mem[subscript_loc(q)]=save_word;
6481 }
6482
6483 @ @<Descend one level for the attribute |info(t)|@>=
6484
6485   n=info(t);
6486   ss=attr_head(pp);
6487   do {  
6488     rr=ss; ss=link(ss);
6489   } while (n>attr_loc(ss));
6490   if ( n<attr_loc(ss) ) { 
6491     qq=mp_get_node(mp, attr_node_size); link(rr)=qq; link(qq)=ss;
6492     attr_loc(qq)=n; name_type(qq)=mp_attr; type(qq)=undefined;
6493     parent(qq)=pp; ss=qq;
6494   }
6495   if ( p==pp ) { 
6496     p=ss; pp=ss;
6497   } else { 
6498     pp=ss; s=attr_head(p);
6499     do {  
6500       r=s; s=link(s);
6501     } while (n>attr_loc(s));
6502     if ( n==attr_loc(s) ) {
6503       p=s;
6504     } else { 
6505       q=mp_get_node(mp, attr_node_size); link(r)=q; link(q)=s;
6506       attr_loc(q)=n; name_type(q)=mp_attr; type(q)=undefined;
6507       parent(q)=p; p=q;
6508     }
6509   }
6510 }
6511
6512 @ Variables lose their former values when they appear in a type declaration,
6513 or when they are defined to be macros or \&{let} equal to something else.
6514 A subroutine will be defined later that recycles the storage associated
6515 with any particular |type| or |value|; our goal now is to study a higher
6516 level process called |flush_variable|, which selectively frees parts of a
6517 variable structure.
6518
6519 This routine has some complexity because of examples such as
6520 `\hbox{\tt numeric x[]a[]b}'
6521 which recycles all variables of the form \.{x[i]a[j]b} (and no others), while
6522 `\hbox{\tt vardef x[]a[]=...}'
6523 discards all variables of the form \.{x[i]a[j]} followed by an arbitrary
6524 suffix, except for the collective node \.{x[]a[]} itself. The obvious way
6525 to handle such examples is to use recursion; so that's what we~do.
6526 @^recursion@>
6527
6528 Parameter |p| points to the root information of the variable;
6529 parameter |t| points to a list of one-word nodes that represent
6530 suffixes, with |info=collective_subscript| for subscripts.
6531
6532 @<Declarations@>=
6533 @<Declare subroutines for printing expressions@>
6534 @<Declare basic dependency-list subroutines@>
6535 @<Declare the recycling subroutines@>
6536 void mp_flush_cur_exp (MP mp,scaled v) ;
6537 @<Declare the procedure called |flush_below_variable|@>
6538
6539 @ @c 
6540 void mp_flush_variable (MP mp,pointer p, pointer t, boolean discard_suffixes) {
6541   pointer q,r; /* list manipulation */
6542   halfword n; /* attribute to match */
6543   while ( t!=null ) { 
6544     if ( type(p)!=mp_structured ) return;
6545     n=info(t); t=link(t);
6546     if ( n==collective_subscript ) { 
6547       r=subscr_head_loc(p); q=link(r); /* |q=subscr_head(p)| */
6548       while ( name_type(q)==mp_subscr ){ 
6549         mp_flush_variable(mp, q,t,discard_suffixes);
6550         if ( t==null ) {
6551           if ( type(q)==mp_structured ) r=q;
6552           else  { link(r)=link(q); mp_free_node(mp, q,subscr_node_size);   }
6553         } else {
6554           r=q;
6555         }
6556         q=link(r);
6557       }
6558     }
6559     p=attr_head(p);
6560     do {  
6561       r=p; p=link(p);
6562     } while (attr_loc(p)<n);
6563     if ( attr_loc(p)!=n ) return;
6564   }
6565   if ( discard_suffixes ) {
6566     mp_flush_below_variable(mp, p);
6567   } else { 
6568     if ( type(p)==mp_structured ) p=attr_head(p);
6569     mp_recycle_value(mp, p);
6570   }
6571 }
6572
6573 @ The next procedure is simpler; it wipes out everything but |p| itself,
6574 which becomes undefined.
6575
6576 @<Declare the procedure called |flush_below_variable|@>=
6577 void mp_flush_below_variable (MP mp, pointer p);
6578
6579 @ @c
6580 void mp_flush_below_variable (MP mp,pointer p) {
6581    pointer q,r; /* list manipulation registers */
6582   if ( type(p)!=mp_structured ) {
6583     mp_recycle_value(mp, p); /* this sets |type(p)=undefined| */
6584   } else { 
6585     q=subscr_head(p);
6586     while ( name_type(q)==mp_subscr ) { 
6587       mp_flush_below_variable(mp, q); r=q; q=link(q);
6588       mp_free_node(mp, r,subscr_node_size);
6589     }
6590     r=attr_head(p); q=link(r); mp_recycle_value(mp, r);
6591     if ( name_type(p)<=mp_saved_root ) mp_free_node(mp, r,value_node_size);
6592     else mp_free_node(mp, r,subscr_node_size);
6593     /* we assume that |subscr_node_size=attr_node_size| */
6594     do {  
6595       mp_flush_below_variable(mp, q); r=q; q=link(q); mp_free_node(mp, r,attr_node_size);
6596     } while (q!=end_attr);
6597     type(p)=undefined;
6598   }
6599 }
6600
6601 @ Just before assigning a new value to a variable, we will recycle the
6602 old value and make the old value undefined. The |und_type| routine
6603 determines what type of undefined value should be given, based on
6604 the current type before recycling.
6605
6606 @c 
6607 small_number mp_und_type (MP mp,pointer p) { 
6608   switch (type(p)) {
6609   case undefined: case mp_vacuous:
6610     return undefined;
6611   case mp_boolean_type: case mp_unknown_boolean:
6612     return mp_unknown_boolean;
6613   case mp_string_type: case mp_unknown_string:
6614     return mp_unknown_string;
6615   case mp_pen_type: case mp_unknown_pen:
6616     return mp_unknown_pen;
6617   case mp_path_type: case mp_unknown_path:
6618     return mp_unknown_path;
6619   case mp_picture_type: case mp_unknown_picture:
6620     return mp_unknown_picture;
6621   case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
6622   case mp_pair_type: case mp_numeric_type: 
6623     return type(p);
6624   case mp_known: case mp_dependent: case mp_proto_dependent: case mp_independent:
6625     return mp_numeric_type;
6626   } /* there are no other cases */
6627   return 0;
6628 }
6629
6630 @ The |clear_symbol| routine is used when we want to redefine the equivalent
6631 of a symbolic token. It must remove any variable structure or macro
6632 definition that is currently attached to that symbol. If the |saving|
6633 parameter is true, a subsidiary structure is saved instead of destroyed.
6634
6635 @c 
6636 void mp_clear_symbol (MP mp,pointer p, boolean saving) {
6637   pointer q; /* |equiv(p)| */
6638   q=equiv(p);
6639   switch (eq_type(p) % outer_tag)  {
6640   case defined_macro:
6641   case secondary_primary_macro:
6642   case tertiary_secondary_macro:
6643   case expression_tertiary_macro: 
6644     if ( ! saving ) mp_delete_mac_ref(mp, q);
6645     break;
6646   case tag_token:
6647     if ( q!=null ) {
6648       if ( saving ) {
6649         name_type(q)=mp_saved_root;
6650       } else { 
6651         mp_flush_below_variable(mp, q); mp_free_node(mp,q,value_node_size); 
6652       }
6653     }
6654     break;
6655   default:
6656     break;
6657   }
6658   mp->eqtb[p]=mp->eqtb[frozen_undefined];
6659 };
6660
6661 @* \[16] Saving and restoring equivalents.
6662 The nested structure given by \&{begingroup} and \&{endgroup}
6663 allows |eqtb| entries to be saved and restored, so that temporary changes
6664 can be made without difficulty.  When the user requests a current value to
6665 be saved, \MP\ puts that value into its ``save stack.'' An appearance of
6666 \&{endgroup} ultimately causes the old values to be removed from the save
6667 stack and put back in their former places.
6668
6669 The save stack is a linked list containing three kinds of entries,
6670 distinguished by their |info| fields. If |p| points to a saved item,
6671 then
6672
6673 \smallskip\hang
6674 |info(p)=0| stands for a group boundary; each \&{begingroup} contributes
6675 such an item to the save stack and each \&{endgroup} cuts back the stack
6676 until the most recent such entry has been removed.
6677
6678 \smallskip\hang
6679 |info(p)=q|, where |1<=q<=hash_end|, means that |mem[p+1]| holds the former
6680 contents of |eqtb[q]|. Such save stack entries are generated by \&{save}
6681 commands or suitable \&{interim} commands.
6682
6683 \smallskip\hang
6684 |info(p)=hash_end+q|, where |q>0|, means that |value(p)| is a |scaled|
6685 integer to be restored to internal parameter number~|q|. Such entries
6686 are generated by \&{interim} commands.
6687
6688 \smallskip\noindent
6689 The global variable |save_ptr| points to the top item on the save stack.
6690
6691 @d save_node_size 2 /* number of words per non-boundary save-stack node */
6692 @d saved_equiv(A) mp->mem[(A)+1].hh /* where an |eqtb| entry gets saved */
6693 @d save_boundary_item(A) { (A)=mp_get_avail(mp); info((A))=0;
6694   link((A))=mp->save_ptr; mp->save_ptr=(A);
6695   }
6696
6697 @<Glob...@>=
6698 pointer save_ptr; /* the most recently saved item */
6699
6700 @ @<Set init...@>=mp->save_ptr=null;
6701
6702 @ The |save_variable| routine is given a hash address |q|; it salts this
6703 address in the save stack, together with its current equivalent,
6704 then makes token~|q| behave as though it were brand new.
6705
6706 Nothing is stacked when |save_ptr=null|, however; there's no way to remove
6707 things from the stack when the program is not inside a group, so there's
6708 no point in wasting the space.
6709
6710 @c void mp_save_variable (MP mp,pointer q) {
6711   pointer p; /* temporary register */
6712   if ( mp->save_ptr!=null ){ 
6713     p=mp_get_node(mp, save_node_size); info(p)=q; link(p)=mp->save_ptr;
6714     saved_equiv(p)=mp->eqtb[q]; mp->save_ptr=p;
6715   }
6716   mp_clear_symbol(mp, q,(mp->save_ptr!=null));
6717 }
6718
6719 @ Similarly, |save_internal| is given the location |q| of an internal
6720 quantity like |mp_tracing_pens|. It creates a save stack entry of the
6721 third kind.
6722
6723 @c void mp_save_internal (MP mp,halfword q) {
6724   pointer p; /* new item for the save stack */
6725   if ( mp->save_ptr!=null ){ 
6726      p=mp_get_node(mp, save_node_size); info(p)=hash_end+q;
6727     link(p)=mp->save_ptr; value(p)=mp->internal[q]; mp->save_ptr=p;
6728   }
6729 }
6730
6731 @ At the end of a group, the |unsave| routine restores all of the saved
6732 equivalents in reverse order. This routine will be called only when there
6733 is at least one boundary item on the save stack.
6734
6735 @c 
6736 void mp_unsave (MP mp) {
6737   pointer q; /* index to saved item */
6738   pointer p; /* temporary register */
6739   while ( info(mp->save_ptr)!=0 ) {
6740     q=info(mp->save_ptr);
6741     if ( q>hash_end ) {
6742       if ( mp->internal[mp_tracing_restores]>0 ) {
6743         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6744         mp_print(mp, mp->int_name[q-(hash_end)]); mp_print_char(mp, '=');
6745         mp_print_scaled(mp, value(mp->save_ptr)); mp_print_char(mp, '}');
6746         mp_end_diagnostic(mp, false);
6747       }
6748       mp->internal[q-(hash_end)]=value(mp->save_ptr);
6749     } else { 
6750       if ( mp->internal[mp_tracing_restores]>0 ) {
6751         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6752         mp_print_text(q); mp_print_char(mp, '}');
6753         mp_end_diagnostic(mp, false);
6754       }
6755       mp_clear_symbol(mp, q,false);
6756       mp->eqtb[q]=saved_equiv(mp->save_ptr);
6757       if ( eq_type(q) % outer_tag==tag_token ) {
6758         p=equiv(q);
6759         if ( p!=null ) name_type(p)=mp_root;
6760       }
6761     }
6762     p=link(mp->save_ptr); 
6763     mp_free_node(mp, mp->save_ptr,save_node_size); mp->save_ptr=p;
6764   }
6765   p=link(mp->save_ptr); free_avail(mp->save_ptr); mp->save_ptr=p;
6766 }
6767
6768 @* \[17] Data structures for paths.
6769 When a \MP\ user specifies a path, \MP\ will create a list of knots
6770 and control points for the associated cubic spline curves. If the
6771 knots are $z_0$, $z_1$, \dots, $z_n$, there are control points
6772 $z_k^+$ and $z_{k+1}^-$ such that the cubic splines between knots
6773 $z_k$ and $z_{k+1}$ are defined by B\'ezier's formula
6774 @:Bezier}{B\'ezier, Pierre Etienne@>
6775 $$\eqalign{z(t)&=B(z_k,z_k^+,z_{k+1}^-,z_{k+1};t)\cr
6776 &=(1-t)^3z_k+3(1-t)^2tz_k^++3(1-t)t^2z_{k+1}^-+t^3z_{k+1}\cr}$$
6777 for |0<=t<=1|.
6778
6779 There is a 8-word node for each knot $z_k$, containing one word of
6780 control information and six words for the |x| and |y| coordinates of
6781 $z_k^-$ and $z_k$ and~$z_k^+$. The control information appears in the
6782 |left_type| and |right_type| fields, which each occupy a quarter of
6783 the first word in the node; they specify properties of the curve as it
6784 enters and leaves the knot. There's also a halfword |link| field,
6785 which points to the following knot, and a final supplementary word (of
6786 which only a quarter is used).
6787
6788 If the path is a closed contour, knots 0 and |n| are identical;
6789 i.e., the |link| in knot |n-1| points to knot~0. But if the path
6790 is not closed, the |left_type| of knot~0 and the |right_type| of knot~|n|
6791 are equal to |endpoint|. In the latter case the |link| in knot~|n| points
6792 to knot~0, and the control points $z_0^-$ and $z_n^+$ are not used.
6793
6794 @d left_type(A)   mp->mem[(A)].hh.b0 /* characterizes the path entering this knot */
6795 @d right_type(A)   mp->mem[(A)].hh.b1 /* characterizes the path leaving this knot */
6796 @d x_coord(A)   mp->mem[(A)+1].sc /* the |x| coordinate of this knot */
6797 @d y_coord(A)   mp->mem[(A)+2].sc /* the |y| coordinate of this knot */
6798 @d left_x(A)   mp->mem[(A)+3].sc /* the |x| coordinate of previous control point */
6799 @d left_y(A)   mp->mem[(A)+4].sc /* the |y| coordinate of previous control point */
6800 @d right_x(A)   mp->mem[(A)+5].sc /* the |x| coordinate of next control point */
6801 @d right_y(A)   mp->mem[(A)+6].sc /* the |y| coordinate of next control point */
6802 @d x_loc(A)   ((A)+1) /* where the |x| coordinate is stored in a knot */
6803 @d y_loc(A)   ((A)+2) /* where the |y| coordinate is stored in a knot */
6804 @d knot_coord(A)   mp->mem[(A)].sc /* |x| or |y| coordinate given |x_loc| or |y_loc| */
6805 @d left_coord(A)   mp->mem[(A)+2].sc
6806   /* coordinate of previous control point given |x_loc| or |y_loc| */
6807 @d right_coord(A)   mp->mem[(A)+4].sc
6808   /* coordinate of next control point given |x_loc| or |y_loc| */
6809 @d knot_node_size 8 /* number of words in a knot node */
6810
6811 @<Types...@>=
6812 enum mp_knot_type {
6813  mp_endpoint=0, /* |left_type| at path beginning and |right_type| at path end */
6814  mp_explicit, /* |left_type| or |right_type| when control points are known */
6815  mp_given, /* |left_type| or |right_type| when a direction is given */
6816  mp_curl, /* |left_type| or |right_type| when a curl is desired */
6817  mp_open, /* |left_type| or |right_type| when \MP\ should choose the direction */
6818  mp_end_cycle
6819 } ;
6820
6821 @ Before the B\'ezier control points have been calculated, the memory
6822 space they will ultimately occupy is taken up by information that can be
6823 used to compute them. There are four cases:
6824
6825 \yskip
6826 \textindent{$\bullet$} If |right_type=mp_open|, the curve should leave
6827 the knot in the same direction it entered; \MP\ will figure out a
6828 suitable direction.
6829
6830 \yskip
6831 \textindent{$\bullet$} If |right_type=mp_curl|, the curve should leave the
6832 knot in a direction depending on the angle at which it enters the next
6833 knot and on the curl parameter stored in |right_curl|.
6834
6835 \yskip
6836 \textindent{$\bullet$} If |right_type=mp_given|, the curve should leave the
6837 knot in a nonzero direction stored as an |angle| in |right_given|.
6838
6839 \yskip
6840 \textindent{$\bullet$} If |right_type=mp_explicit|, the B\'ezier control
6841 point for leaving this knot has already been computed; it is in the
6842 |right_x| and |right_y| fields.
6843
6844 \yskip\noindent
6845 The rules for |left_type| are similar, but they refer to the curve entering
6846 the knot, and to \\{left} fields instead of \\{right} fields.
6847
6848 Non-|explicit| control points will be chosen based on ``tension'' parameters
6849 in the |left_tension| and |right_tension| fields. The
6850 `\&{atleast}' option is represented by negative tension values.
6851 @:at_least_}{\&{atleast} primitive@>
6852
6853 For example, the \MP\ path specification
6854 $$\.{z0..z1..tension atleast 1..\{curl 2\}z2..z3\{-1,-2\}..tension
6855   3 and 4..p},$$
6856 where \.p is the path `\.{z4..controls z45 and z54..z5}', will be represented
6857 by the six knots
6858 \def\lodash{\hbox to 1.1em{\thinspace\hrulefill\thinspace}}
6859 $$\vbox{\halign{#\hfil&&\qquad#\hfil\cr
6860 |left_type|&\\{left} info&|x_coord,y_coord|&|right_type|&\\{right} info\cr
6861 \noalign{\yskip}
6862 |endpoint|&\lodash$,\,$\lodash&$x_0,y_0$&|curl|&$1.0,1.0$\cr
6863 |open|&\lodash$,1.0$&$x_1,y_1$&|open|&\lodash$,-1.0$\cr
6864 |curl|&$2.0,-1.0$&$x_2,y_2$&|curl|&$2.0,1.0$\cr
6865 |given|&$d,1.0$&$x_3,y_3$&|given|&$d,3.0$\cr
6866 |open|&\lodash$,4.0$&$x_4,y_4$&|explicit|&$x_{45},y_{45}$\cr
6867 |explicit|&$x_{54},y_{54}$&$x_5,y_5$&|endpoint|&\lodash$,\,$\lodash\cr}}$$
6868 Here |d| is the |angle| obtained by calling |n_arg(-unity,-two)|.
6869 Of course, this example is more complicated than anything a normal user
6870 would ever write.
6871
6872 These types must satisfy certain restrictions because of the form of \MP's
6873 path syntax:
6874 (i)~|open| type never appears in the same node together with |endpoint|,
6875 |given|, or |curl|.
6876 (ii)~The |right_type| of a node is |explicit| if and only if the
6877 |left_type| of the following node is |explicit|.
6878 (iii)~|endpoint| types occur only at the ends, as mentioned above.
6879
6880 @d left_curl left_x /* curl information when entering this knot */
6881 @d left_given left_x /* given direction when entering this knot */
6882 @d left_tension left_y /* tension information when entering this knot */
6883 @d right_curl right_x /* curl information when leaving this knot */
6884 @d right_given right_x /* given direction when leaving this knot */
6885 @d right_tension right_y /* tension information when leaving this knot */
6886
6887 @ Knots can be user-supplied, or they can be created by program code,
6888 like the |split_cubic| function, or |copy_path|. The distinction is
6889 needed for the cleanup routine that runs after |split_cubic|, because
6890 it should only delete knots it has previously inserted, and never
6891 anything that was user-supplied. In order to be able to differentiate
6892 one knot from another, we will set |originator(p):=mp_metapost_user| when
6893 it appeared in the actual metapost program, and
6894 |originator(p):=mp_program_code| in all other cases.
6895
6896 @d originator(A)   mp->mem[(A)+7].hh.b0 /* the creator of this knot */
6897
6898 @<Types...@>=
6899 enum {
6900   mp_program_code=0, /* not created by a user */
6901   mp_metapost_user, /* created by a user */
6902 };
6903
6904 @ Here is a routine that prints a given knot list
6905 in symbolic form. It illustrates the conventions discussed above,
6906 and checks for anomalies that might arise while \MP\ is being debugged.
6907
6908 @<Declare subroutines for printing expressions@>=
6909 void mp_pr_path (MP mp,pointer h);
6910
6911 @ @c
6912 void mp_pr_path (MP mp,pointer h) {
6913   pointer p,q; /* for list traversal */
6914   p=h;
6915   do {  
6916     q=link(p);
6917     if ( (p==null)||(q==null) ) { 
6918       mp_print_nl(mp, "???"); return; /* this won't happen */
6919 @.???@>
6920     }
6921     @<Print information for adjacent knots |p| and |q|@>;
6922   DONE1:
6923     p=q;
6924     if ( (p!=h)||(left_type(h)!=mp_endpoint) ) {
6925       @<Print two dots, followed by |given| or |curl| if present@>;
6926     }
6927   } while (p!=h);
6928   if ( left_type(h)!=mp_endpoint ) 
6929     mp_print(mp, "cycle");
6930 }
6931
6932 @ @<Print information for adjacent knots...@>=
6933 mp_print_two(mp, x_coord(p),y_coord(p));
6934 switch (right_type(p)) {
6935 case mp_endpoint: 
6936   if ( left_type(p)==mp_open ) mp_print(mp, "{open?}"); /* can't happen */
6937 @.open?@>
6938   if ( (left_type(q)!=mp_endpoint)||(q!=h) ) q=null; /* force an error */
6939   goto DONE1;
6940   break;
6941 case mp_explicit: 
6942   @<Print control points between |p| and |q|, then |goto done1|@>;
6943   break;
6944 case mp_open: 
6945   @<Print information for a curve that begins |open|@>;
6946   break;
6947 case mp_curl:
6948 case mp_given: 
6949   @<Print information for a curve that begins |curl| or |given|@>;
6950   break;
6951 default:
6952   mp_print(mp, "???"); /* can't happen */
6953 @.???@>
6954   break;
6955 }
6956 if ( left_type(q)<=mp_explicit ) {
6957   mp_print(mp, "..control?"); /* can't happen */
6958 @.control?@>
6959 } else if ( (right_tension(p)!=unity)||(left_tension(q)!=unity) ) {
6960   @<Print tension between |p| and |q|@>;
6961 }
6962
6963 @ Since |n_sin_cos| produces |fraction| results, which we will print as if they
6964 were |scaled|, the magnitude of a |given| direction vector will be~4096.
6965
6966 @<Print two dots...@>=
6967
6968   mp_print_nl(mp, " ..");
6969   if ( left_type(p)==mp_given ) { 
6970     mp_n_sin_cos(mp, left_given(p)); mp_print_char(mp, '{');
6971     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ',');
6972     mp_print_scaled(mp, mp->n_sin); mp_print_char(mp, '}');
6973   } else if ( left_type(p)==mp_curl ){ 
6974     mp_print(mp, "{curl "); 
6975     mp_print_scaled(mp, left_curl(p)); mp_print_char(mp, '}');
6976   }
6977 }
6978
6979 @ @<Print tension between |p| and |q|@>=
6980
6981   mp_print(mp, "..tension ");
6982   if ( right_tension(p)<0 ) mp_print(mp, "atleast");
6983   mp_print_scaled(mp, abs(right_tension(p)));
6984   if ( right_tension(p)!=left_tension(q) ){ 
6985     mp_print(mp, " and ");
6986     if ( left_tension(q)<0 ) mp_print(mp, "atleast");
6987     mp_print_scaled(mp, abs(left_tension(q)));
6988   }
6989 }
6990
6991 @ @<Print control points between |p| and |q|, then |goto done1|@>=
6992
6993   mp_print(mp, "..controls "); 
6994   mp_print_two(mp, right_x(p),right_y(p)); 
6995   mp_print(mp, " and ");
6996   if ( left_type(q)!=mp_explicit ) { 
6997     mp_print(mp, "??"); /* can't happen */
6998 @.??@>
6999   } else {
7000     mp_print_two(mp, left_x(q),left_y(q));
7001   }
7002   goto DONE1;
7003 }
7004
7005 @ @<Print information for a curve that begins |open|@>=
7006 if ( (left_type(p)!=mp_explicit)&&(left_type(p)!=mp_open) ) {
7007   mp_print(mp, "{open?}"); /* can't happen */
7008 @.open?@>
7009 }
7010
7011 @ A curl of 1 is shown explicitly, so that the user sees clearly that
7012 \MP's default curl is present.
7013
7014 The code here uses the fact that |left_curl==left_given| and
7015 |right_curl==right_given|.
7016
7017 @<Print information for a curve that begins |curl|...@>=
7018
7019   if ( left_type(p)==mp_open )  
7020     mp_print(mp, "??"); /* can't happen */
7021 @.??@>
7022   if ( right_type(p)==mp_curl ) { 
7023     mp_print(mp, "{curl "); mp_print_scaled(mp, right_curl(p));
7024   } else { 
7025     mp_n_sin_cos(mp, right_given(p)); mp_print_char(mp, '{');
7026     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ','); 
7027     mp_print_scaled(mp, mp->n_sin);
7028   }
7029   mp_print_char(mp, '}');
7030 }
7031
7032 @ It is convenient to have another version of |pr_path| that prints the path
7033 as a diagnostic message.
7034
7035 @<Declare subroutines for printing expressions@>=
7036 void mp_print_path (MP mp,pointer h, char *s, boolean nuline) { 
7037   mp_print_diagnostic(mp, "Path", s, nuline); mp_print_ln(mp);
7038 @.Path at line...@>
7039   mp_pr_path(mp, h);
7040   mp_end_diagnostic(mp, true);
7041 }
7042
7043 @ If we want to duplicate a knot node, we can say |copy_knot|:
7044
7045 @c 
7046 pointer mp_copy_knot (MP mp,pointer p) {
7047   pointer q; /* the copy */
7048   int k; /* runs through the words of a knot node */
7049   q=mp_get_node(mp, knot_node_size);
7050   for (k=0;k<knot_node_size;k++) {
7051     mp->mem[q+k]=mp->mem[p+k];
7052   }
7053   originator(q)=originator(p);
7054   return q;
7055 }
7056
7057 @ The |copy_path| routine makes a clone of a given path.
7058
7059 @c 
7060 pointer mp_copy_path (MP mp, pointer p) {
7061   pointer q,pp,qq; /* for list manipulation */
7062   q=mp_copy_knot(mp, p);
7063   qq=q; pp=link(p);
7064   while ( pp!=p ) { 
7065     link(qq)=mp_copy_knot(mp, pp);
7066     qq=link(qq);
7067     pp=link(pp);
7068   }
7069   link(qq)=q;
7070   return q;
7071 }
7072
7073
7074 @ Just before |ship_out|, knot lists are exported for printing.
7075
7076 @d gr_left_type(A)  (A)->left_type_field 
7077 @d gr_right_type(A) (A)->right_type_field
7078 @d gr_x_coord(A)    (A)->x_coord_field   
7079 @d gr_y_coord(A)    (A)->y_coord_field   
7080 @d gr_left_x(A)     (A)->left_x_field    
7081 @d gr_left_y(A)     (A)->left_y_field    
7082 @d gr_right_x(A)    (A)->right_x_field   
7083 @d gr_right_y(A)    (A)->right_y_field   
7084 @d gr_next_knot(A)  (A)->next_field
7085 @d gr_originator(A) (A)->originator_field
7086
7087 @c 
7088 struct mp_knot *mp_export_knot (MP mp,pointer p) {
7089   struct mp_knot *q; /* the copy */
7090   if (p==null)
7091      return NULL;
7092   q = mp_xmalloc(mp, 1, sizeof (struct mp_knot));
7093   memset(q,0,sizeof (struct mp_knot));
7094   gr_left_type(q)  = left_type(p);
7095   gr_right_type(q) = right_type(p);
7096   gr_x_coord(q)    = x_coord(p);
7097   gr_y_coord(q)    = y_coord(p);
7098   gr_left_x(q)     = left_x(p);
7099   gr_left_y(q)     = left_y(p);
7100   gr_right_x(q)    = right_x(p);
7101   gr_right_y(q)    = right_y(p);
7102   gr_originator(q) = originator(p);
7103   return q;
7104 }
7105
7106 @ The |export_knot_list| routine therefore also makes a clone 
7107 of a given path.
7108
7109 @c 
7110 struct mp_knot *mp_export_knot_list (MP mp, pointer p) {
7111   struct mp_knot *q, *qq; /* for list manipulation */
7112   pointer pp; /* for list manipulation */
7113   if (p==null)
7114      return NULL;
7115   q=mp_export_knot(mp, p);
7116   qq=q; pp=link(p);
7117   while ( pp!=p ) { 
7118     gr_next_knot(qq)=mp_export_knot(mp, pp);
7119     qq=gr_next_knot(qq);
7120     pp=link(pp);
7121   }
7122   gr_next_knot(qq)=q;
7123   return q;
7124 }
7125
7126
7127 @ Similarly, there's a way to copy the {\sl reverse\/} of a path. This procedure
7128 returns a pointer to the first node of the copy, if the path is a cycle,
7129 but to the final node of a non-cyclic copy. The global
7130 variable |path_tail| will point to the final node of the original path;
7131 this trick makes it easier to implement `\&{doublepath}'.
7132
7133 All node types are assumed to be |endpoint| or |explicit| only.
7134
7135 @c 
7136 pointer mp_htap_ypoc (MP mp,pointer p) {
7137   pointer q,pp,qq,rr; /* for list manipulation */
7138   q=mp_get_node(mp, knot_node_size); /* this will correspond to |p| */
7139   qq=q; pp=p;
7140   while (1) { 
7141     right_type(qq)=left_type(pp); left_type(qq)=right_type(pp);
7142     x_coord(qq)=x_coord(pp); y_coord(qq)=y_coord(pp);
7143     right_x(qq)=left_x(pp); right_y(qq)=left_y(pp);
7144     left_x(qq)=right_x(pp); left_y(qq)=right_y(pp);
7145     originator(qq)=originator(pp);
7146     if ( link(pp)==p ) { 
7147       link(q)=qq; mp->path_tail=pp; return q;
7148     }
7149     rr=mp_get_node(mp, knot_node_size); link(rr)=qq; qq=rr; pp=link(pp);
7150   }
7151 }
7152
7153 @ @<Glob...@>=
7154 pointer path_tail; /* the node that links to the beginning of a path */
7155
7156 @ When a cyclic list of knot nodes is no longer needed, it can be recycled by
7157 calling the following subroutine.
7158
7159 @<Declare the recycling subroutines@>=
7160 void mp_toss_knot_list (MP mp,pointer p) ;
7161
7162 @ @c
7163 void mp_toss_knot_list (MP mp,pointer p) {
7164   pointer q; /* the node being freed */
7165   pointer r; /* the next node */
7166   q=p;
7167   do {  
7168     r=link(q); 
7169     mp_free_node(mp, q,knot_node_size); q=r;
7170   } while (q!=p);
7171 }
7172
7173 @* \[18] Choosing control points.
7174 Now we must actually delve into one of \MP's more difficult routines,
7175 the |make_choices| procedure that chooses angles and control points for
7176 the splines of a curve when the user has not specified them explicitly.
7177 The parameter to |make_choices| points to a list of knots and
7178 path information, as described above.
7179
7180 A path decomposes into independent segments at ``breakpoint'' knots,
7181 which are knots whose left and right angles are both prespecified in
7182 some way (i.e., their |left_type| and |right_type| aren't both open).
7183
7184 @c 
7185 @<Declare the procedure called |solve_choices|@>;
7186 void mp_make_choices (MP mp,pointer knots) {
7187   pointer h; /* the first breakpoint */
7188   pointer p,q; /* consecutive breakpoints being processed */
7189   @<Other local variables for |make_choices|@>;
7190   check_arith; /* make sure that |arith_error=false| */
7191   if ( mp->internal[mp_tracing_choices]>0 )
7192     mp_print_path(mp, knots,", before choices",true);
7193   @<If consecutive knots are equal, join them explicitly@>;
7194   @<Find the first breakpoint, |h|, on the path;
7195     insert an artificial breakpoint if the path is an unbroken cycle@>;
7196   p=h;
7197   do {  
7198     @<Fill in the control points between |p| and the next breakpoint,
7199       then advance |p| to that breakpoint@>;
7200   } while (p!=h);
7201   if ( mp->internal[mp_tracing_choices]>0 )
7202     mp_print_path(mp, knots,", after choices",true);
7203   if ( mp->arith_error ) {
7204     @<Report an unexpected problem during the choice-making@>;
7205   }
7206 }
7207
7208 @ @<Report an unexpected problem during the choice...@>=
7209
7210   print_err("Some number got too big");
7211 @.Some number got too big@>
7212   help2("The path that I just computed is out of range.")
7213        ("So it will probably look funny. Proceed, for a laugh.");
7214   mp_put_get_error(mp); mp->arith_error=false;
7215 }
7216
7217 @ Two knots in a row with the same coordinates will always be joined
7218 by an explicit ``curve'' whose control points are identical with the
7219 knots.
7220
7221 @<If consecutive knots are equal, join them explicitly@>=
7222 p=knots;
7223 do {  
7224   q=link(p);
7225   if ( x_coord(p)==x_coord(q) && y_coord(p)==y_coord(q) && right_type(p)>mp_explicit ) { 
7226     right_type(p)=mp_explicit;
7227     if ( left_type(p)==mp_open ) { 
7228       left_type(p)=mp_curl; left_curl(p)=unity;
7229     }
7230     left_type(q)=mp_explicit;
7231     if ( right_type(q)==mp_open ) { 
7232       right_type(q)=mp_curl; right_curl(q)=unity;
7233     }
7234     right_x(p)=x_coord(p); left_x(q)=x_coord(p);
7235     right_y(p)=y_coord(p); left_y(q)=y_coord(p);
7236   }
7237   p=q;
7238 } while (p!=knots)
7239
7240 @ If there are no breakpoints, it is necessary to compute the direction
7241 angles around an entire cycle. In this case the |left_type| of the first
7242 node is temporarily changed to |end_cycle|.
7243
7244 @<Find the first breakpoint, |h|, on the path...@>=
7245 h=knots;
7246 while (1) { 
7247   if ( left_type(h)!=mp_open ) break;
7248   if ( right_type(h)!=mp_open ) break;
7249   h=link(h);
7250   if ( h==knots ) { 
7251     left_type(h)=mp_end_cycle; break;
7252   }
7253 }
7254
7255 @ If |right_type(p)<given| and |q=link(p)|, we must have
7256 |right_type(p)=left_type(q)=mp_explicit| or |endpoint|.
7257
7258 @<Fill in the control points between |p| and the next breakpoint...@>=
7259 q=link(p);
7260 if ( right_type(p)>=mp_given ) { 
7261   while ( (left_type(q)==mp_open)&&(right_type(q)==mp_open) ) q=link(q);
7262   @<Fill in the control information between
7263     consecutive breakpoints |p| and |q|@>;
7264 } else if ( right_type(p)==mp_endpoint ) {
7265   @<Give reasonable values for the unused control points between |p| and~|q|@>;
7266 }
7267 p=q
7268
7269 @ This step makes it possible to transform an explicitly computed path without
7270 checking the |left_type| and |right_type| fields.
7271
7272 @<Give reasonable values for the unused control points between |p| and~|q|@>=
7273
7274   right_x(p)=x_coord(p); right_y(p)=y_coord(p);
7275   left_x(q)=x_coord(q); left_y(q)=y_coord(q);
7276 }
7277
7278 @ Before we can go further into the way choices are made, we need to
7279 consider the underlying theory. The basic ideas implemented in |make_choices|
7280 are due to John Hobby, who introduced the notion of ``mock curvature''
7281 @^Hobby, John Douglas@>
7282 at a knot. Angles are chosen so that they preserve mock curvature when
7283 a knot is passed, and this has been found to produce excellent results.
7284
7285 It is convenient to introduce some notations that simplify the necessary
7286 formulas. Let $d_{k,k+1}=\vert z\k-z_k\vert$ be the (nonzero) distance
7287 between knots |k| and |k+1|; and let
7288 $${z\k-z_k\over z_k-z_{k-1}}={d_{k,k+1}\over d_{k-1,k}}e^{i\psi_k}$$
7289 so that a polygonal line from $z_{k-1}$ to $z_k$ to $z\k$ turns left
7290 through an angle of~$\psi_k$. We assume that $\vert\psi_k\vert\L180^\circ$.
7291 The control points for the spline from $z_k$ to $z\k$ will be denoted by
7292 $$\eqalign{z_k^+&=z_k+
7293   \textstyle{1\over3}\rho_k e^{i\theta_k}(z\k-z_k),\cr
7294  z\k^-&=z\k-
7295   \textstyle{1\over3}\sigma\k e^{-i\phi\k}(z\k-z_k),\cr}$$
7296 where $\rho_k$ and $\sigma\k$ are nonnegative ``velocity ratios'' at the
7297 beginning and end of the curve, while $\theta_k$ and $\phi\k$ are the
7298 corresponding ``offset angles.'' These angles satisfy the condition
7299 $$\theta_k+\phi_k+\psi_k=0,\eqno(*)$$
7300 whenever the curve leaves an intermediate knot~|k| in the direction that
7301 it enters.
7302
7303 @ Let $\alpha_k$ and $\beta\k$ be the reciprocals of the ``tension'' of
7304 the curve at its beginning and ending points. This means that
7305 $\rho_k=\alpha_k f(\theta_k,\phi\k)$ and $\sigma\k=\beta\k f(\phi\k,\theta_k)$,
7306 where $f(\theta,\phi)$ is \MP's standard velocity function defined in
7307 the |velocity| subroutine. The cubic spline $B(z_k^{\phantom+},z_k^+,
7308 z\k^-,z\k^{\phantom+};t)$
7309 has curvature
7310 @^curvature@>
7311 $${2\sigma\k\sin(\theta_k+\phi\k)-6\sin\theta_k\over\rho_k^2d_{k,k+1}}
7312 \qquad{\rm and}\qquad
7313 {2\rho_k\sin(\theta_k+\phi\k)-6\sin\phi\k\over\sigma\k^2d_{k,k+1}}$$
7314 at |t=0| and |t=1|, respectively. The mock curvature is the linear
7315 @^mock curvature@>
7316 approximation to this true curvature that arises in the limit for
7317 small $\theta_k$ and~$\phi\k$, if second-order terms are discarded.
7318 The standard velocity function satisfies
7319 $$f(\theta,\phi)=1+O(\theta^2+\theta\phi+\phi^2);$$
7320 hence the mock curvatures are respectively
7321 $${2\beta\k(\theta_k+\phi\k)-6\theta_k\over\alpha_k^2d_{k,k+1}}
7322 \qquad{\rm and}\qquad
7323 {2\alpha_k(\theta_k+\phi\k)-6\phi\k\over\beta\k^2d_{k,k+1}}.\eqno(**)$$
7324
7325 @ The turning angles $\psi_k$ are given, and equation $(*)$ above
7326 determines $\phi_k$ when $\theta_k$ is known, so the task of
7327 angle selection is essentially to choose appropriate values for each
7328 $\theta_k$. When equation~$(*)$ is used to eliminate $\phi$~variables
7329 from $(**)$, we obtain a system of linear equations of the form
7330 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7331 where
7332 $$A_k={\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7333 \qquad B_k={3-\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7334 \qquad C_k={3-\beta\k\over\alpha_k^2d_{k,k+1}},
7335 \qquad D_k={\beta\k\over\alpha_k^2d_{k,k+1}}.$$
7336 The tensions are always $3\over4$ or more, hence each $\alpha$ and~$\beta$
7337 will be at most $4\over3$. It follows that $B_k\G{5\over4}A_k$ and
7338 $C_k\G{5\over4}D_k$; hence the equations are diagonally dominant;
7339 hence they have a unique solution. Moreover, in most cases the tensions
7340 are equal to~1, so that $B_k=2A_k$ and $C_k=2D_k$. This makes the
7341 solution numerically stable, and there is an exponential damping
7342 effect: The data at knot $k\pm j$ affects the angle at knot~$k$ by
7343 a factor of~$O(2^{-j})$.
7344
7345 @ However, we still must consider the angles at the starting and ending
7346 knots of a non-cyclic path. These angles might be given explicitly, or
7347 they might be specified implicitly in terms of an amount of ``curl.''
7348
7349 Let's assume that angles need to be determined for a non-cyclic path
7350 starting at $z_0$ and ending at~$z_n$. Then equations of the form
7351 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta_{k+1}=R_k$$
7352 have been given for $0<k<n$, and it will be convenient to introduce
7353 equations of the same form for $k=0$ and $k=n$, where
7354 $$A_0=B_0=C_n=D_n=0.$$
7355 If $\theta_0$ is supposed to have a given value $E_0$, we simply
7356 define $C_0=0$, $D_0=0$, and $R_0=E_0$. Otherwise a curl
7357 parameter, $\gamma_0$, has been specified at~$z_0$; this means
7358 that the mock curvature at $z_0$ should be $\gamma_0$ times the
7359 mock curvature at $z_1$; i.e.,
7360 $${2\beta_1(\theta_0+\phi_1)-6\theta_0\over\alpha_0^2d_{01}}
7361 =\gamma_0{2\alpha_0(\theta_0+\phi_1)-6\phi_1\over\beta_1^2d_{01}}.$$
7362 This equation simplifies to
7363 $$(\alpha_0\chi_0+3-\beta_1)\theta_0+
7364  \bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\theta_1=
7365  -\bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\psi_1,$$
7366 where $\chi_0=\alpha_0^2\gamma_0/\beta_1^2$; so we can set $C_0=
7367 \chi_0\alpha_0+3-\beta_1$, $D_0=(3-\alpha_0)\chi_0+\beta_1$, $R_0=-D_0\psi_1$.
7368 It can be shown that $C_0>0$ and $C_0B_1-A_1D_0>0$ when $\gamma_0\G0$,
7369 hence the linear equations remain nonsingular.
7370
7371 Similar considerations apply at the right end, when the final angle $\phi_n$
7372 may or may not need to be determined. It is convenient to let $\psi_n=0$,
7373 hence $\theta_n=-\phi_n$. We either have an explicit equation $\theta_n=E_n$,
7374 or we have
7375 $$\bigl((3-\beta_n)\chi_n+\alpha_{n-1}\bigr)\theta_{n-1}+
7376 (\beta_n\chi_n+3-\alpha_{n-1})\theta_n=0,\qquad
7377   \chi_n={\beta_n^2\gamma_n\over\alpha_{n-1}^2}.$$
7378
7379 When |make_choices| chooses angles, it must compute the coefficients of
7380 these linear equations, then solve the equations. To compute the coefficients,
7381 it is necessary to compute arctangents of the given turning angles~$\psi_k$.
7382 When the equations are solved, the chosen directions $\theta_k$ are put
7383 back into the form of control points by essentially computing sines and
7384 cosines.
7385
7386 @ OK, we are ready to make the hard choices of |make_choices|.
7387 Most of the work is relegated to an auxiliary procedure
7388 called |solve_choices|, which has been introduced to keep
7389 |make_choices| from being extremely long.
7390
7391 @<Fill in the control information between...@>=
7392 @<Calculate the turning angles $\psi_k$ and the distances $d_{k,k+1}$;
7393   set $n$ to the length of the path@>;
7394 @<Remove |open| types at the breakpoints@>;
7395 mp_solve_choices(mp, p,q,n)
7396
7397 @ It's convenient to precompute quantities that will be needed several
7398 times later. The values of |delta_x[k]| and |delta_y[k]| will be the
7399 coordinates of $z\k-z_k$, and the magnitude of this vector will be
7400 |delta[k]=@t$d_{k,k+1}$@>|. The path angle $\psi_k$ between $z_k-z_{k-1}$
7401 and $z\k-z_k$ will be stored in |psi[k]|.
7402
7403 @<Glob...@>=
7404 int path_size; /* maximum number of knots between breakpoints of a path */
7405 scaled *delta_x;
7406 scaled *delta_y;
7407 scaled *delta; /* knot differences */
7408 angle  *psi; /* turning angles */
7409
7410 @ @<Allocate or initialize ...@>=
7411 mp->delta_x = NULL;
7412 mp->delta_y = NULL;
7413 mp->delta = NULL;
7414 mp->psi = NULL;
7415
7416 @ @<Dealloc variables@>=
7417 xfree(mp->delta_x);
7418 xfree(mp->delta_y);
7419 xfree(mp->delta);
7420 xfree(mp->psi);
7421
7422 @ @<Other local variables for |make_choices|@>=
7423   int k,n; /* current and final knot numbers */
7424   pointer s,t; /* registers for list traversal */
7425   scaled delx,dely; /* directions where |open| meets |explicit| */
7426   fraction sine,cosine; /* trig functions of various angles */
7427
7428 @ @<Calculate the turning angles...@>=
7429 {
7430 RESTART:
7431   k=0; s=p; n=mp->path_size;
7432   do {  
7433     t=link(s);
7434     mp->delta_x[k]=x_coord(t)-x_coord(s);
7435     mp->delta_y[k]=y_coord(t)-y_coord(s);
7436     mp->delta[k]=mp_pyth_add(mp, mp->delta_x[k],mp->delta_y[k]);
7437     if ( k>0 ) { 
7438       sine=mp_make_fraction(mp, mp->delta_y[k-1],mp->delta[k-1]);
7439       cosine=mp_make_fraction(mp, mp->delta_x[k-1],mp->delta[k-1]);
7440       mp->psi[k]=mp_n_arg(mp, mp_take_fraction(mp, mp->delta_x[k],cosine)+
7441         mp_take_fraction(mp, mp->delta_y[k],sine),
7442         mp_take_fraction(mp, mp->delta_y[k],cosine)-
7443           mp_take_fraction(mp, mp->delta_x[k],sine));
7444     }
7445     incr(k); s=t;
7446     if ( k==mp->path_size ) {
7447       mp_reallocate_paths(mp, mp->path_size+(mp->path_size>>2));
7448       goto RESTART; /* retry, loop size has changed */
7449     }
7450     if ( s==q ) n=k;
7451   } while (!((k>=n)&&(left_type(s)!=mp_end_cycle)));
7452   if ( k==n ) mp->psi[n]=0; else mp->psi[k]=mp->psi[1];
7453 }
7454
7455 @ When we get to this point of the code, |right_type(p)| is either
7456 |given| or |curl| or |open|. If it is |open|, we must have
7457 |left_type(p)=mp_end_cycle| or |left_type(p)=mp_explicit|. In the latter
7458 case, the |open| type is converted to |given|; however, if the
7459 velocity coming into this knot is zero, the |open| type is
7460 converted to a |curl|, since we don't know the incoming direction.
7461
7462 Similarly, |left_type(q)| is either |given| or |curl| or |open| or
7463 |mp_end_cycle|. The |open| possibility is reduced either to |given| or to |curl|.
7464
7465 @<Remove |open| types at the breakpoints@>=
7466 if ( left_type(q)==mp_open ) { 
7467   delx=right_x(q)-x_coord(q); dely=right_y(q)-y_coord(q);
7468   if ( (delx==0)&&(dely==0) ) { 
7469     left_type(q)=mp_curl; left_curl(q)=unity;
7470   } else { 
7471     left_type(q)=mp_given; left_given(q)=mp_n_arg(mp, delx,dely);
7472   }
7473 }
7474 if ( (right_type(p)==mp_open)&&(left_type(p)==mp_explicit) ) { 
7475   delx=x_coord(p)-left_x(p); dely=y_coord(p)-left_y(p);
7476   if ( (delx==0)&&(dely==0) ) { 
7477     right_type(p)=mp_curl; right_curl(p)=unity;
7478   } else { 
7479     right_type(p)=mp_given; right_given(p)=mp_n_arg(mp, delx,dely);
7480   }
7481 }
7482
7483 @ Linear equations need to be solved whenever |n>1|; and also when |n=1|
7484 and exactly one of the breakpoints involves a curl. The simplest case occurs
7485 when |n=1| and there is a curl at both breakpoints; then we simply draw
7486 a straight line.
7487
7488 But before coding up the simple cases, we might as well face the general case,
7489 since we must deal with it sooner or later, and since the general case
7490 is likely to give some insight into the way simple cases can be handled best.
7491
7492 When there is no cycle, the linear equations to be solved form a tridiagonal
7493 system, and we can apply the standard technique of Gaussian elimination
7494 to convert that system to a sequence of equations of the form
7495 $$\theta_0+u_0\theta_1=v_0,\quad
7496 \theta_1+u_1\theta_2=v_1,\quad\ldots,\quad
7497 \theta_{n-1}+u_{n-1}\theta_n=v_{n-1},\quad
7498 \theta_n=v_n.$$
7499 It is possible to do this diagonalization while generating the equations.
7500 Once $\theta_n$ is known, it is easy to determine $\theta_{n-1}$, \dots,
7501 $\theta_1$, $\theta_0$; thus, the equations will be solved.
7502
7503 The procedure is slightly more complex when there is a cycle, but the
7504 basic idea will be nearly the same. In the cyclic case the right-hand
7505 sides will be $v_k+w_k\theta_0$ instead of simply $v_k$, and we will start
7506 the process off with $u_0=v_0=0$, $w_0=1$. The final equation will be not
7507 $\theta_n=v_n$ but $\theta_n+u_n\theta_1=v_n+w_n\theta_0$; an appropriate
7508 ending routine will take account of the fact that $\theta_n=\theta_0$ and
7509 eliminate the $w$'s from the system, after which the solution can be
7510 obtained as before.
7511
7512 When $u_k$, $v_k$, and $w_k$ are being computed, the three pointer
7513 variables |r|, |s|,~|t| will point respectively to knots |k-1|, |k|,
7514 and~|k+1|. The $u$'s and $w$'s are scaled by $2^{28}$, i.e., they are
7515 of type |fraction|; the $\theta$'s and $v$'s are of type |angle|.
7516
7517 @<Glob...@>=
7518 angle *theta; /* values of $\theta_k$ */
7519 fraction *uu; /* values of $u_k$ */
7520 angle *vv; /* values of $v_k$ */
7521 fraction *ww; /* values of $w_k$ */
7522
7523 @ @<Allocate or initialize ...@>=
7524 mp->theta = NULL;
7525 mp->uu = NULL;
7526 mp->vv = NULL;
7527 mp->ww = NULL;
7528
7529 @ @<Dealloc variables@>=
7530 xfree(mp->theta);
7531 xfree(mp->uu);
7532 xfree(mp->vv);
7533 xfree(mp->ww);
7534
7535 @ @<Declare |mp_reallocate| functions@>=
7536 void mp_reallocate_paths (MP mp, int l);
7537
7538 @ @c
7539 void mp_reallocate_paths (MP mp, int l) {
7540   XREALLOC (mp->delta_x, l, scaled);
7541   XREALLOC (mp->delta_y, l, scaled);
7542   XREALLOC (mp->delta,   l, scaled);
7543   XREALLOC (mp->psi,     l, angle);
7544   XREALLOC (mp->theta,   l, angle);
7545   XREALLOC (mp->uu,      l, fraction);
7546   XREALLOC (mp->vv,      l, angle);
7547   XREALLOC (mp->ww,      l, fraction);
7548   mp->path_size = l;
7549 }
7550
7551 @ Our immediate problem is to get the ball rolling by setting up the
7552 first equation or by realizing that no equations are needed, and to fit
7553 this initialization into a framework suitable for the overall computation.
7554
7555 @<Declare the procedure called |solve_choices|@>=
7556 @<Declare subroutines needed by |solve_choices|@>;
7557 void mp_solve_choices (MP mp,pointer p, pointer q, halfword n) {
7558   int k; /* current knot number */
7559   pointer r,s,t; /* registers for list traversal */
7560   @<Other local variables for |solve_choices|@>;
7561   k=0; s=p; r=0;
7562   while (1) { 
7563     t=link(s);
7564     if ( k==0 ) {
7565       @<Get the linear equations started; or |return|
7566         with the control points in place, if linear equations
7567         needn't be solved@>
7568     } else  { 
7569       switch (left_type(s)) {
7570       case mp_end_cycle: case mp_open:
7571         @<Set up equation to match mock curvatures
7572           at $z_k$; then |goto found| with $\theta_n$
7573           adjusted to equal $\theta_0$, if a cycle has ended@>;
7574         break;
7575       case mp_curl:
7576         @<Set up equation for a curl at $\theta_n$
7577           and |goto found|@>;
7578         break;
7579       case mp_given:
7580         @<Calculate the given value of $\theta_n$
7581           and |goto found|@>;
7582         break;
7583       } /* there are no other cases */
7584     }
7585     r=s; s=t; incr(k);
7586   }
7587 FOUND:
7588   @<Finish choosing angles and assigning control points@>;
7589 }
7590
7591 @ On the first time through the loop, we have |k=0| and |r| is not yet
7592 defined. The first linear equation, if any, will have $A_0=B_0=0$.
7593
7594 @<Get the linear equations started...@>=
7595 switch (right_type(s)) {
7596 case mp_given: 
7597   if ( left_type(t)==mp_given ) {
7598     @<Reduce to simple case of two givens  and |return|@>
7599   } else {
7600     @<Set up the equation for a given value of $\theta_0$@>;
7601   }
7602   break;
7603 case mp_curl: 
7604   if ( left_type(t)==mp_curl ) {
7605     @<Reduce to simple case of straight line and |return|@>
7606   } else {
7607     @<Set up the equation for a curl at $\theta_0$@>;
7608   }
7609   break;
7610 case mp_open: 
7611   mp->uu[0]=0; mp->vv[0]=0; mp->ww[0]=fraction_one;
7612   /* this begins a cycle */
7613   break;
7614 } /* there are no other cases */
7615
7616 @ The general equation that specifies equality of mock curvature at $z_k$ is
7617 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7618 as derived above. We want to combine this with the already-derived equation
7619 $\theta_{k-1}+u_{k-1}\theta_k=v_{k-1}+w_{k-1}\theta_0$ in order to obtain
7620 a new equation
7621 $\theta_k+u_k\theta\k=v_k+w_k\theta_0$. This can be done by dividing the
7622 equation
7623 $$(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}
7624     -A_kw_{k-1}\theta_0$$
7625 by $B_k-u_{k-1}A_k+C_k$. The trick is to do this carefully with
7626 fixed-point arithmetic, avoiding the chance of overflow while retaining
7627 suitable precision.
7628
7629 The calculations will be performed in several registers that
7630 provide temporary storage for intermediate quantities.
7631
7632 @<Other local variables for |solve_choices|@>=
7633 fraction aa,bb,cc,ff,acc; /* temporary registers */
7634 scaled dd,ee; /* likewise, but |scaled| */
7635 scaled lt,rt; /* tension values */
7636
7637 @ @<Set up equation to match mock curvatures...@>=
7638 { @<Calculate the values $\\{aa}=A_k/B_k$, $\\{bb}=D_k/C_k$,
7639     $\\{dd}=(3-\alpha_{k-1})d_{k,k+1}$, $\\{ee}=(3-\beta\k)d_{k-1,k}$,
7640     and $\\{cc}=(B_k-u_{k-1}A_k)/B_k$@>;
7641   @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>;
7642   mp->uu[k]=mp_take_fraction(mp, ff,bb);
7643   @<Calculate the values of $v_k$ and $w_k$@>;
7644   if ( left_type(s)==mp_end_cycle ) {
7645     @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>;
7646   }
7647 }
7648
7649 @ Since tension values are never less than 3/4, the values |aa| and
7650 |bb| computed here are never more than 4/5.
7651
7652 @<Calculate the values $\\{aa}=...@>=
7653 if ( abs(right_tension(r))==unity) { 
7654   aa=fraction_half; dd=2*mp->delta[k];
7655 } else { 
7656   aa=mp_make_fraction(mp, unity,3*abs(right_tension(r))-unity);
7657   dd=mp_take_fraction(mp, mp->delta[k],
7658     fraction_three-mp_make_fraction(mp, unity,abs(right_tension(r))));
7659 }
7660 if ( abs(left_tension(t))==unity ){ 
7661   bb=fraction_half; ee=2*mp->delta[k-1];
7662 } else { 
7663   bb=mp_make_fraction(mp, unity,3*abs(left_tension(t))-unity);
7664   ee=mp_take_fraction(mp, mp->delta[k-1],
7665     fraction_three-mp_make_fraction(mp, unity,abs(left_tension(t))));
7666 }
7667 cc=fraction_one-mp_take_fraction(mp, mp->uu[k-1],aa)
7668
7669 @ The ratio to be calculated in this step can be written in the form
7670 $$\beta_k^2\cdot\\{ee}\over\beta_k^2\cdot\\{ee}+\alpha_k^2\cdot
7671   \\{cc}\cdot\\{dd},$$
7672 because of the quantities just calculated. The values of |dd| and |ee|
7673 will not be needed after this step has been performed.
7674
7675 @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>=
7676 dd=mp_take_fraction(mp, dd,cc); lt=abs(left_tension(s)); rt=abs(right_tension(s));
7677 if ( lt!=rt ) { /* $\beta_k^{-1}\ne\alpha_k^{-1}$ */
7678   if ( lt<rt ) { 
7679     ff=mp_make_fraction(mp, lt,rt);
7680     ff=mp_take_fraction(mp, ff,ff); /* $\alpha_k^2/\beta_k^2$ */
7681     dd=mp_take_fraction(mp, dd,ff);
7682   } else { 
7683     ff=mp_make_fraction(mp, rt,lt);
7684     ff=mp_take_fraction(mp, ff,ff); /* $\beta_k^2/\alpha_k^2$ */
7685     ee=mp_take_fraction(mp, ee,ff);
7686   }
7687 }
7688 ff=mp_make_fraction(mp, ee,ee+dd)
7689
7690 @ The value of $u_{k-1}$ will be |<=1| except when $k=1$ and the previous
7691 equation was specified by a curl. In that case we must use a special
7692 method of computation to prevent overflow.
7693
7694 Fortunately, the calculations turn out to be even simpler in this ``hard''
7695 case. The curl equation makes $w_0=0$ and $v_0=-u_0\psi_1$, hence
7696 $-B_1\psi_1-A_1v_0=-(B_1-u_0A_1)\psi_1=-\\{cc}\cdot B_1\psi_1$.
7697
7698 @<Calculate the values of $v_k$ and $w_k$@>=
7699 acc=-mp_take_fraction(mp, mp->psi[k+1],mp->uu[k]);
7700 if ( right_type(r)==mp_curl ) { 
7701   mp->ww[k]=0;
7702   mp->vv[k]=acc-mp_take_fraction(mp, mp->psi[1],fraction_one-ff);
7703 } else { 
7704   ff=mp_make_fraction(mp, fraction_one-ff,cc); /* this is
7705     $B_k/(C_k+B_k-u_{k-1}A_k)<5$ */
7706   acc=acc-mp_take_fraction(mp, mp->psi[k],ff);
7707   ff=mp_take_fraction(mp, ff,aa); /* this is $A_k/(C_k+B_k-u_{k-1}A_k)$ */
7708   mp->vv[k]=acc-mp_take_fraction(mp, mp->vv[k-1],ff);
7709   if ( mp->ww[k-1]==0 ) mp->ww[k]=0;
7710   else mp->ww[k]=-mp_take_fraction(mp, mp->ww[k-1],ff);
7711 }
7712
7713 @ When a complete cycle has been traversed, we have $\theta_k+u_k\theta\k=
7714 v_k+w_k\theta_0$, for |1<=k<=n|. We would like to determine the value of
7715 $\theta_n$ and reduce the system to the form $\theta_k+u_k\theta\k=v_k$
7716 for |0<=k<n|, so that the cyclic case can be finished up just as if there
7717 were no cycle.
7718
7719 The idea in the following code is to observe that
7720 $$\eqalign{\theta_n&=v_n+w_n\theta_0-u_n\theta_1=\cdots\cr
7721 &=v_n+w_n\theta_0-u_n\bigl(v_1+w_1\theta_0-u_1(v_2+\cdots
7722   -u_{n-2}(v_{n-1}+w_{n-1}\theta_0-u_{n-1}\theta_0))\bigr),\cr}$$
7723 so we can solve for $\theta_n=\theta_0$.
7724
7725 @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>=
7726
7727 aa=0; bb=fraction_one; /* we have |k=n| */
7728 do {  decr(k);
7729 if ( k==0 ) k=n;
7730   aa=mp->vv[k]-mp_take_fraction(mp, aa,mp->uu[k]);
7731   bb=mp->ww[k]-mp_take_fraction(mp, bb,mp->uu[k]);
7732 } while (k!=n); /* now $\theta_n=\\{aa}+\\{bb}\cdot\theta_n$ */
7733 aa=mp_make_fraction(mp, aa,fraction_one-bb);
7734 mp->theta[n]=aa; mp->vv[0]=aa;
7735 for (k=1;k<=n-1;k++) {
7736   mp->vv[k]=mp->vv[k]+mp_take_fraction(mp, aa,mp->ww[k]);
7737 }
7738 goto FOUND;
7739 }
7740
7741 @ @d reduce_angle(A) if ( abs((A))>one_eighty_deg ) {
7742   if ( (A)>0 ) (A)=(A)-three_sixty_deg; else (A)=(A)+three_sixty_deg; }
7743
7744 @<Calculate the given value of $\theta_n$...@>=
7745
7746   mp->theta[n]=left_given(s)-mp_n_arg(mp, mp->delta_x[n-1],mp->delta_y[n-1]);
7747   reduce_angle(mp->theta[n]);
7748   goto FOUND;
7749 }
7750
7751 @ @<Set up the equation for a given value of $\theta_0$@>=
7752
7753   mp->vv[0]=right_given(s)-mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7754   reduce_angle(mp->vv[0]);
7755   mp->uu[0]=0; mp->ww[0]=0;
7756 }
7757
7758 @ @<Set up the equation for a curl at $\theta_0$@>=
7759 { cc=right_curl(s); lt=abs(left_tension(t)); rt=abs(right_tension(s));
7760   if ( (rt==unity)&&(lt==unity) )
7761     mp->uu[0]=mp_make_fraction(mp, cc+cc+unity,cc+two);
7762   else 
7763     mp->uu[0]=mp_curl_ratio(mp, cc,rt,lt);
7764   mp->vv[0]=-mp_take_fraction(mp, mp->psi[1],mp->uu[0]); mp->ww[0]=0;
7765 }
7766
7767 @ @<Set up equation for a curl at $\theta_n$...@>=
7768 { cc=left_curl(s); lt=abs(left_tension(s)); rt=abs(right_tension(r));
7769   if ( (rt==unity)&&(lt==unity) )
7770     ff=mp_make_fraction(mp, cc+cc+unity,cc+two);
7771   else 
7772     ff=mp_curl_ratio(mp, cc,lt,rt);
7773   mp->theta[n]=-mp_make_fraction(mp, mp_take_fraction(mp, mp->vv[n-1],ff),
7774     fraction_one-mp_take_fraction(mp, ff,mp->uu[n-1]));
7775   goto FOUND;
7776 }
7777
7778 @ The |curl_ratio| subroutine has three arguments, which our previous notation
7779 encourages us to call $\gamma$, $\alpha^{-1}$, and $\beta^{-1}$. It is
7780 a somewhat tedious program to calculate
7781 $${(3-\alpha)\alpha^2\gamma+\beta^3\over
7782   \alpha^3\gamma+(3-\beta)\beta^2},$$
7783 with the result reduced to 4 if it exceeds 4. (This reduction of curl
7784 is necessary only if the curl and tension are both large.)
7785 The values of $\alpha$ and $\beta$ will be at most~4/3.
7786
7787 @<Declare subroutines needed by |solve_choices|@>=
7788 fraction mp_curl_ratio (MP mp,scaled gamma, scaled a_tension, 
7789                         scaled b_tension) {
7790   fraction alpha,beta,num,denom,ff; /* registers */
7791   alpha=mp_make_fraction(mp, unity,a_tension);
7792   beta=mp_make_fraction(mp, unity,b_tension);
7793   if ( alpha<=beta ) {
7794     ff=mp_make_fraction(mp, alpha,beta); ff=mp_take_fraction(mp, ff,ff);
7795     gamma=mp_take_fraction(mp, gamma,ff);
7796     beta=beta / 010000; /* convert |fraction| to |scaled| */
7797     denom=mp_take_fraction(mp, gamma,alpha)+three-beta;
7798     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7799   } else { 
7800     ff=mp_make_fraction(mp, beta,alpha); ff=mp_take_fraction(mp, ff,ff);
7801     beta=mp_take_fraction(mp, beta,ff) / 010000; /* convert |fraction| to |scaled| */
7802     denom=mp_take_fraction(mp, gamma,alpha)+(ff / 1365)-beta;
7803       /* $1365\approx 2^{12}/3$ */
7804     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7805   }
7806   if ( num>=denom+denom+denom+denom ) return fraction_four;
7807   else return mp_make_fraction(mp, num,denom);
7808 }
7809
7810 @ We're in the home stretch now.
7811
7812 @<Finish choosing angles and assigning control points@>=
7813 for (k=n-1;k>=0;k--) {
7814   mp->theta[k]=mp->vv[k]-mp_take_fraction(mp,mp->theta[k+1],mp->uu[k]);
7815 }
7816 s=p; k=0;
7817 do {  
7818   t=link(s);
7819   mp_n_sin_cos(mp, mp->theta[k]); mp->st=mp->n_sin; mp->ct=mp->n_cos;
7820   mp_n_sin_cos(mp, -mp->psi[k+1]-mp->theta[k+1]); mp->sf=mp->n_sin; mp->cf=mp->n_cos;
7821   mp_set_controls(mp, s,t,k);
7822   incr(k); s=t;
7823 } while (k!=n)
7824
7825 @ The |set_controls| routine actually puts the control points into
7826 a pair of consecutive nodes |p| and~|q|. Global variables are used to
7827 record the values of $\sin\theta$, $\cos\theta$, $\sin\phi$, and
7828 $\cos\phi$ needed in this calculation.
7829
7830 @<Glob...@>=
7831 fraction st;
7832 fraction ct;
7833 fraction sf;
7834 fraction cf; /* sines and cosines */
7835
7836 @ @<Declare subroutines needed by |solve_choices|@>=
7837 void mp_set_controls (MP mp,pointer p, pointer q, integer k) {
7838   fraction rr,ss; /* velocities, divided by thrice the tension */
7839   scaled lt,rt; /* tensions */
7840   fraction sine; /* $\sin(\theta+\phi)$ */
7841   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7842   rr=mp_velocity(mp, mp->st,mp->ct,mp->sf,mp->cf,rt);
7843   ss=mp_velocity(mp, mp->sf,mp->cf,mp->st,mp->ct,lt);
7844   if ( (right_tension(p)<0)||(left_tension(q)<0) ) {
7845     @<Decrease the velocities,
7846       if necessary, to stay inside the bounding triangle@>;
7847   }
7848   right_x(p)=x_coord(p)+mp_take_fraction(mp, 
7849                           mp_take_fraction(mp, mp->delta_x[k],mp->ct)-
7850                           mp_take_fraction(mp, mp->delta_y[k],mp->st),rr);
7851   right_y(p)=y_coord(p)+mp_take_fraction(mp, 
7852                           mp_take_fraction(mp, mp->delta_y[k],mp->ct)+
7853                           mp_take_fraction(mp, mp->delta_x[k],mp->st),rr);
7854   left_x(q)=x_coord(q)-mp_take_fraction(mp, 
7855                          mp_take_fraction(mp, mp->delta_x[k],mp->cf)+
7856                          mp_take_fraction(mp, mp->delta_y[k],mp->sf),ss);
7857   left_y(q)=y_coord(q)-mp_take_fraction(mp, 
7858                          mp_take_fraction(mp, mp->delta_y[k],mp->cf)-
7859                          mp_take_fraction(mp, mp->delta_x[k],mp->sf),ss);
7860   right_type(p)=mp_explicit; left_type(q)=mp_explicit;
7861 }
7862
7863 @ The boundedness conditions $\\{rr}\L\sin\phi\,/\sin(\theta+\phi)$ and
7864 $\\{ss}\L\sin\theta\,/\sin(\theta+\phi)$ are to be enforced if $\sin\theta$,
7865 $\sin\phi$, and $\sin(\theta+\phi)$ all have the same sign. Otherwise
7866 there is no ``bounding triangle.''
7867 @:at_least_}{\&{atleast} primitive@>
7868
7869 @<Decrease the velocities, if necessary...@>=
7870 if (((mp->st>=0)&&(mp->sf>=0))||((mp->st<=0)&&(mp->sf<=0)) ) {
7871   sine=mp_take_fraction(mp, abs(mp->st),mp->cf)+
7872                             mp_take_fraction(mp, abs(mp->sf),mp->ct);
7873   if ( sine>0 ) {
7874     sine=mp_take_fraction(mp, sine,fraction_one+unity); /* safety factor */
7875     if ( right_tension(p)<0 )
7876      if ( mp_ab_vs_cd(mp, abs(mp->sf),fraction_one,rr,sine)<0 )
7877       rr=mp_make_fraction(mp, abs(mp->sf),sine);
7878     if ( left_tension(q)<0 )
7879      if ( mp_ab_vs_cd(mp, abs(mp->st),fraction_one,ss,sine)<0 )
7880       ss=mp_make_fraction(mp, abs(mp->st),sine);
7881   }
7882 }
7883
7884 @ Only the simple cases remain to be handled.
7885
7886 @<Reduce to simple case of two givens and |return|@>=
7887
7888   aa=mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7889   mp_n_sin_cos(mp, right_given(p)-aa); mp->ct=mp->n_cos; mp->st=mp->n_sin;
7890   mp_n_sin_cos(mp, left_given(q)-aa); mp->cf=mp->n_cos; mp->sf=-mp->n_sin;
7891   mp_set_controls(mp, p,q,0); return;
7892 }
7893
7894 @ @<Reduce to simple case of straight line and |return|@>=
7895
7896   right_type(p)=mp_explicit; left_type(q)=mp_explicit;
7897   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7898   if ( rt==unity ) {
7899     if ( mp->delta_x[0]>=0 ) right_x(p)=x_coord(p)+((mp->delta_x[0]+1) / 3);
7900     else right_x(p)=x_coord(p)+((mp->delta_x[0]-1) / 3);
7901     if ( mp->delta_y[0]>=0 ) right_y(p)=y_coord(p)+((mp->delta_y[0]+1) / 3);
7902     else right_y(p)=y_coord(p)+((mp->delta_y[0]-1) / 3);
7903   } else { 
7904     ff=mp_make_fraction(mp, unity,3*rt); /* $\alpha/3$ */
7905     right_x(p)=x_coord(p)+mp_take_fraction(mp, mp->delta_x[0],ff);
7906     right_y(p)=y_coord(p)+mp_take_fraction(mp, mp->delta_y[0],ff);
7907   }
7908   if ( lt==unity ) {
7909     if ( mp->delta_x[0]>=0 ) left_x(q)=x_coord(q)-((mp->delta_x[0]+1) / 3);
7910     else left_x(q)=x_coord(q)-((mp->delta_x[0]-1) / 3);
7911     if ( mp->delta_y[0]>=0 ) left_y(q)=y_coord(q)-((mp->delta_y[0]+1) / 3);
7912     else left_y(q)=y_coord(q)-((mp->delta_y[0]-1) / 3);
7913   } else  { 
7914     ff=mp_make_fraction(mp, unity,3*lt); /* $\beta/3$ */
7915     left_x(q)=x_coord(q)-mp_take_fraction(mp, mp->delta_x[0],ff);
7916     left_y(q)=y_coord(q)-mp_take_fraction(mp, mp->delta_y[0],ff);
7917   }
7918   return;
7919 }
7920
7921 @* \[19] Measuring paths.
7922 \MP's \&{llcorner}, \&{lrcorner}, \&{ulcorner}, and \&{urcorner} operators
7923 allow the user to measure the bounding box of anything that can go into a
7924 picture.  It's easy to get rough bounds on the $x$ and $y$ extent of a path
7925 by just finding the bounding box of the knots and the control points. We
7926 need a more accurate version of the bounding box, but we can still use the
7927 easy estimate to save time by focusing on the interesting parts of the path.
7928
7929 @ Computing an accurate bounding box involves a theme that will come up again
7930 and again. Given a Bernshte{\u\i}n polynomial
7931 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
7932 $$B(z_0,z_1,\ldots,z_n;t)=\sum_k{n\choose k}t^k(1-t)^{n-k}z_k,$$
7933 we can conveniently bisect its range as follows:
7934
7935 \smallskip
7936 \textindent{1)} Let $z_k^{(0)}=z_k$, for |0<=k<=n|.
7937
7938 \smallskip
7939 \textindent{2)} Let $z_k^{(j+1)}={1\over2}(z_k^{(j)}+z\k^{(j)})$, for
7940 |0<=k<n-j|, for |0<=j<n|.
7941
7942 \smallskip\noindent
7943 Then
7944 $$B(z_0,z_1,\ldots,z_n;t)=B(z_0^{(0)},z_0^{(1)},\ldots,z_0^{(n)};2t)
7945  =B(z_0^{(n)},z_1^{(n-1)},\ldots,z_n^{(0)};2t-1).$$
7946 This formula gives us the coefficients of polynomials to use over the ranges
7947 $0\L t\L{1\over2}$ and ${1\over2}\L t\L1$.
7948
7949 @ Now here's a subroutine that's handy for all sorts of path computations:
7950 Given a quadratic polynomial $B(a,b,c;t)$, the |crossing_point| function
7951 returns the unique |fraction| value |t| between 0 and~1 at which
7952 $B(a,b,c;t)$ changes from positive to negative, or returns
7953 |t=fraction_one+1| if no such value exists. If |a<0| (so that $B(a,b,c;t)$
7954 is already negative at |t=0|), |crossing_point| returns the value zero.
7955
7956 @d no_crossing {  return (fraction_one+1); }
7957 @d one_crossing { return fraction_one; }
7958 @d zero_crossing { return 0; }
7959 @d mp_crossing_point(M,A,B,C) mp_do_crossing_point(A,B,C)
7960
7961 @c fraction mp_do_crossing_point (integer a, integer b, integer c) {
7962   integer d; /* recursive counter */
7963   integer x,xx,x0,x1,x2; /* temporary registers for bisection */
7964   if ( a<0 ) zero_crossing;
7965   if ( c>=0 ) { 
7966     if ( b>=0 ) {
7967       if ( c>0 ) { no_crossing; }
7968       else if ( (a==0)&&(b==0) ) { no_crossing;} 
7969       else { one_crossing; } 
7970     }
7971     if ( a==0 ) zero_crossing;
7972   } else if ( a==0 ) {
7973     if ( b<=0 ) zero_crossing;
7974   }
7975   @<Use bisection to find the crossing point, if one exists@>;
7976 }
7977
7978 @ The general bisection method is quite simple when $n=2$, hence
7979 |crossing_point| does not take much time. At each stage in the
7980 recursion we have a subinterval defined by |l| and~|j| such that
7981 $B(a,b,c;2^{-l}(j+t))=B(x_0,x_1,x_2;t)$, and we want to ``zero in'' on
7982 the subinterval where $x_0\G0$ and $\min(x_1,x_2)<0$.
7983
7984 It is convenient for purposes of calculation to combine the values
7985 of |l| and~|j| in a single variable $d=2^l+j$, because the operation
7986 of bisection then corresponds simply to doubling $d$ and possibly
7987 adding~1. Furthermore it proves to be convenient to modify
7988 our previous conventions for bisection slightly, maintaining the
7989 variables $X_0=2^lx_0$, $X_1=2^l(x_0-x_1)$, and $X_2=2^l(x_1-x_2)$.
7990 With these variables the conditions $x_0\ge0$ and $\min(x_1,x_2)<0$ are
7991 equivalent to $\max(X_1,X_1+X_2)>X_0\ge0$.
7992
7993 The following code maintains the invariant relations
7994 $0\L|x0|<\max(|x1|,|x1|+|x2|)$,
7995 $\vert|x1|\vert<2^{30}$, $\vert|x2|\vert<2^{30}$;
7996 it has been constructed in such a way that no arithmetic overflow
7997 will occur if the inputs satisfy
7998 $a<2^{30}$, $\vert a-b\vert<2^{30}$, and $\vert b-c\vert<2^{30}$.
7999
8000 @<Use bisection to find the crossing point...@>=
8001 d=1; x0=a; x1=a-b; x2=b-c;
8002 do {  
8003   x=half(x1+x2);
8004   if ( x1-x0>x0 ) { 
8005     x2=x; x0+=x0; d+=d;  
8006   } else { 
8007     xx=x1+x-x0;
8008     if ( xx>x0 ) { 
8009       x2=x; x0+=x0; d+=d;
8010     }  else { 
8011       x0=x0-xx;
8012       if ( x<=x0 ) { if ( x+x2<=x0 ) no_crossing; }
8013       x1=x; d=d+d+1;
8014     }
8015   }
8016 } while (d<fraction_one);
8017 return (d-fraction_one)
8018
8019 @ Here is a routine that computes the $x$ or $y$ coordinate of the point on
8020 a cubic corresponding to the |fraction| value~|t|.
8021
8022 It is convenient to define a \.{WEB} macro |t_of_the_way| such that
8023 |t_of_the_way(a,b)| expands to |a-(a-b)*t|, i.e., to |t[a,b]|.
8024
8025 @d t_of_the_way(A,B) ((A)-mp_take_fraction(mp,((A)-(B)),t))
8026
8027 @c scaled mp_eval_cubic (MP mp,pointer p, pointer q, fraction t) {
8028   scaled x1,x2,x3; /* intermediate values */
8029   x1=t_of_the_way(knot_coord(p),right_coord(p));
8030   x2=t_of_the_way(right_coord(p),left_coord(q));
8031   x3=t_of_the_way(left_coord(q),knot_coord(q));
8032   x1=t_of_the_way(x1,x2);
8033   x2=t_of_the_way(x2,x3);
8034   return t_of_the_way(x1,x2);
8035 }
8036
8037 @ The actual bounding box information is stored in global variables.
8038 Since it is convenient to address the $x$ and $y$ information
8039 separately, we define arrays indexed by |x_code..y_code| and use
8040 macros to give them more convenient names.
8041
8042 @<Types...@>=
8043 enum mp_bb_code  {
8044   mp_x_code=0, /* index for |minx| and |maxx| */
8045   mp_y_code /* index for |miny| and |maxy| */
8046 } ;
8047
8048
8049 @d minx mp->bbmin[mp_x_code]
8050 @d maxx mp->bbmax[mp_x_code]
8051 @d miny mp->bbmin[mp_y_code]
8052 @d maxy mp->bbmax[mp_y_code]
8053
8054 @<Glob...@>=
8055 scaled bbmin[mp_y_code+1];
8056 scaled bbmax[mp_y_code+1]; 
8057 /* the result of procedures that compute bounding box information */
8058
8059 @ Now we're ready for the key part of the bounding box computation.
8060 The |bound_cubic| procedure updates |bbmin[c]| and |bbmax[c]| based on
8061 $$B(\hbox{|knot_coord(p)|}, \hbox{|right_coord(p)|},
8062     \hbox{|left_coord(q)|}, \hbox{|knot_coord(q)|};t)
8063 $$
8064 for $0<t\le1$.  In other words, the procedure adjusts the bounds to
8065 accommodate |knot_coord(q)| and any extremes over the range $0<t<1$.
8066 The |c| parameter is |x_code| or |y_code|.
8067
8068 @c void mp_bound_cubic (MP mp,pointer p, pointer q, small_number c) {
8069   boolean wavy; /* whether we need to look for extremes */
8070   scaled del1,del2,del3,del,dmax; /* proportional to the control
8071      points of a quadratic derived from a cubic */
8072   fraction t,tt; /* where a quadratic crosses zero */
8073   scaled x; /* a value that |bbmin[c]| and |bbmax[c]| must accommodate */
8074   x=knot_coord(q);
8075   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8076   @<Check the control points against the bounding box and set |wavy:=true|
8077     if any of them lie outside@>;
8078   if ( wavy ) {
8079     del1=right_coord(p)-knot_coord(p);
8080     del2=left_coord(q)-right_coord(p);
8081     del3=knot_coord(q)-left_coord(q);
8082     @<Scale up |del1|, |del2|, and |del3| for greater accuracy;
8083       also set |del| to the first nonzero element of |(del1,del2,del3)|@>;
8084     if ( del<0 ) {
8085       negate(del1); negate(del2); negate(del3);
8086     };
8087     t=mp_crossing_point(mp, del1,del2,del3);
8088     if ( t<fraction_one ) {
8089       @<Test the extremes of the cubic against the bounding box@>;
8090     }
8091   }
8092 }
8093
8094 @ @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>=
8095 if ( x<mp->bbmin[c] ) mp->bbmin[c]=x;
8096 if ( x>mp->bbmax[c] ) mp->bbmax[c]=x
8097
8098 @ @<Check the control points against the bounding box and set...@>=
8099 wavy=true;
8100 if ( mp->bbmin[c]<=right_coord(p) )
8101   if ( right_coord(p)<=mp->bbmax[c] )
8102     if ( mp->bbmin[c]<=left_coord(q) )
8103       if ( left_coord(q)<=mp->bbmax[c] )
8104         wavy=false
8105
8106 @ If |del1=del2=del3=0|, it's impossible to obey the title of this
8107 section. We just set |del=0| in that case.
8108
8109 @<Scale up |del1|, |del2|, and |del3| for greater accuracy...@>=
8110 if ( del1!=0 ) del=del1;
8111 else if ( del2!=0 ) del=del2;
8112 else del=del3;
8113 if ( del!=0 ) {
8114   dmax=abs(del1);
8115   if ( abs(del2)>dmax ) dmax=abs(del2);
8116   if ( abs(del3)>dmax ) dmax=abs(del3);
8117   while ( dmax<fraction_half ) {
8118     dmax+=dmax; del1+=del1; del2+=del2; del3+=del3;
8119   }
8120 }
8121
8122 @ Since |crossing_point| has tried to choose |t| so that
8123 $B(|del1|,|del2|,|del3|;\tau)$ crosses zero at $\tau=|t|$ with negative
8124 slope, the value of |del2| computed below should not be positive.
8125 But rounding error could make it slightly positive in which case we
8126 must cut it to zero to avoid confusion.
8127
8128 @<Test the extremes of the cubic against the bounding box@>=
8129
8130   x=mp_eval_cubic(mp, p,q,t);
8131   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8132   del2=t_of_the_way(del2,del3);
8133     /* now |0,del2,del3| represent the derivative on the remaining interval */
8134   if ( del2>0 ) del2=0;
8135   tt=mp_crossing_point(mp, 0,-del2,-del3);
8136   if ( tt<fraction_one ) {
8137     @<Test the second extreme against the bounding box@>;
8138   }
8139 }
8140
8141 @ @<Test the second extreme against the bounding box@>=
8142 {
8143    x=mp_eval_cubic(mp, p,q,t_of_the_way(tt,fraction_one));
8144   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8145 }
8146
8147 @ Finding the bounding box of a path is basically a matter of applying
8148 |bound_cubic| twice for each pair of adjacent knots.
8149
8150 @c void mp_path_bbox (MP mp,pointer h) {
8151   pointer p,q; /* a pair of adjacent knots */
8152    minx=x_coord(h); miny=y_coord(h);
8153   maxx=minx; maxy=miny;
8154   p=h;
8155   do {  
8156     if ( right_type(p)==mp_endpoint ) return;
8157     q=link(p);
8158     mp_bound_cubic(mp, x_loc(p),x_loc(q),mp_x_code);
8159     mp_bound_cubic(mp, y_loc(p),y_loc(q),mp_y_code);
8160     p=q;
8161   } while (p!=h);
8162 }
8163
8164 @ Another important way to measure a path is to find its arc length.  This
8165 is best done by using the general bisection algorithm to subdivide the path
8166 until obtaining ``well behaved'' subpaths whose arc lengths can be approximated
8167 by simple means.
8168
8169 Since the arc length is the integral with respect to time of the magnitude of
8170 the velocity, it is natural to use Simpson's rule for the approximation.
8171 @^Simpson's rule@>
8172 If $\dot B(t)$ is the spline velocity, Simpson's rule gives
8173 $$ \vb\dot B(0)\vb + 4\vb\dot B({1\over2})\vb + \vb\dot B(1)\vb \over 6 $$
8174 for the arc length of a path of length~1.  For a cubic spline
8175 $B(z_0,z_1,z_2,z_3;t)$, the time derivative $\dot B(t)$ is
8176 $3B(dz_0,dz_1,dz_2;t)$, where $dz_i=z_{i+1}-z_i$.  Hence the arc length
8177 approximation is
8178 $$ {\vb dz_0\vb \over 2} + 2\vb dz_{02}\vb + {\vb dz_2\vb \over 2}, $$
8179 where
8180 $$ dz_{02}={1\over2}\left({dz_0+dz_1\over 2}+{dz_1+dz_2\over 2}\right)$$
8181 is the result of the bisection algorithm.
8182
8183 @ The remaining problem is how to decide when a subpath is ``well behaved.''
8184 This could be done via the theoretical error bound for Simpson's rule,
8185 @^Simpson's rule@>
8186 but this is impractical because it requires an estimate of the fourth
8187 derivative of the quantity being integrated.  It is much easier to just perform
8188 a bisection step and see how much the arc length estimate changes.  Since the
8189 error for Simpson's rule is proportional to the fourth power of the sample
8190 spacing, the remaining error is typically about $1\over16$ of the amount of
8191 the change.  We say ``typically'' because the error has a pseudo-random behavior
8192 that could cause the two estimates to agree when each contain large errors.
8193
8194 To protect against disasters such as undetected cusps, the bisection process
8195 should always continue until all the $dz_i$ vectors belong to a single
8196 $90^\circ$ sector.  This ensures that no point on the spline can have velocity
8197 less than 70\% of the minimum of $\vb dz_0\vb$, $\vb dz_1\vb$ and $\vb dz_2\vb$.
8198 If such a spline happens to produce an erroneous arc length estimate that
8199 is little changed by bisection, the amount of the error is likely to be fairly
8200 small.  We will try to arrange things so that freak accidents of this type do
8201 not destroy the inverse relationship between the \&{arclength} and
8202 \&{arctime} operations.
8203 @:arclength_}{\&{arclength} primitive@>
8204 @:arctime_}{\&{arctime} primitive@>
8205
8206 @ The \&{arclength} and \&{arctime} operations are both based on a recursive
8207 @^recursion@>
8208 function that finds the arc length of a cubic spline given $dz_0$, $dz_1$,
8209 $dz_2$. This |arc_test| routine also takes an arc length goal |a_goal| and
8210 returns the time when the arc length reaches |a_goal| if there is such a time.
8211 Thus the return value is either an arc length less than |a_goal| or, if the
8212 arc length would be at least |a_goal|, it returns a time value decreased by
8213 |two|.  This allows the caller to use the sign of the result to distinguish
8214 between arc lengths and time values.  On certain types of overflow, it is
8215 possible for |a_goal| and the result of |arc_test| both to be |el_gordo|.
8216 Otherwise, the result is always less than |a_goal|.
8217
8218 Rather than halving the control point coordinates on each recursive call to
8219 |arc_test|, it is better to keep them proportional to velocity on the original
8220 curve and halve the results instead.  This means that recursive calls can
8221 potentially use larger error tolerances in their arc length estimates.  How
8222 much larger depends on to what extent the errors behave as though they are
8223 independent of each other.  To save computing time, we use optimistic assumptions
8224 and increase the tolerance by a factor of about $\sqrt2$ for each recursive
8225 call.
8226
8227 In addition to the tolerance parameter, |arc_test| should also have parameters
8228 for ${1\over3}\vb\dot B(0)\vb$, ${2\over3}\vb\dot B({1\over2})\vb$, and
8229 ${1\over3}\vb\dot B(1)\vb$.  These quantities are relatively expensive to compute
8230 and they are needed in different instances of |arc_test|.
8231
8232 @c @t\4@>@<Declare subroutines needed by |arc_test|@>;
8233 scaled mp_arc_test (MP mp, scaled dx0, scaled dy0, scaled dx1, scaled dy1, 
8234                     scaled dx2, scaled dy2, scaled  v0, scaled v02, 
8235                     scaled v2, scaled a_goal, scaled tol) {
8236   boolean simple; /* are the control points confined to a $90^\circ$ sector? */
8237   scaled dx01, dy01, dx12, dy12, dx02, dy02;  /* bisection results */
8238   scaled v002, v022;
8239     /* twice the velocity magnitudes at $t={1\over4}$ and $t={3\over4}$ */
8240   scaled arc; /* best arc length estimate before recursion */
8241   @<Other local variables in |arc_test|@>;
8242   @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,
8243     |dx2|, |dy2|@>;
8244   @<Initialize |v002|, |v022|, and the arc length estimate |arc|; if it overflows
8245     set |arc_test| and |return|@>;
8246   @<Test if the control points are confined to one quadrant or rotating them
8247     $45^\circ$ would put them in one quadrant.  Then set |simple| appropriately@>;
8248   if ( simple && (abs(arc-v02-halfp(v0+v2)) <= tol) ) {
8249     if ( arc < a_goal ) {
8250       return arc;
8251     } else {
8252        @<Estimate when the arc length reaches |a_goal| and set |arc_test| to
8253          that time minus |two|@>;
8254     }
8255   } else {
8256     @<Use one or two recursive calls to compute the |arc_test| function@>;
8257   }
8258 }
8259
8260 @ The |tol| value should by multiplied by $\sqrt 2$ before making recursive
8261 calls, but $1.5$ is an adequate approximation.  It is best to avoid using
8262 |make_fraction| in this inner loop.
8263 @^inner loop@>
8264
8265 @<Use one or two recursive calls to compute the |arc_test| function@>=
8266
8267   @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is as
8268     large as possible@>;
8269   tol = tol + halfp(tol);
8270   a = mp_arc_test(mp, dx0,dy0, dx01,dy01, dx02,dy02, v0, v002, 
8271                   halfp(v02), a_new, tol);
8272   if ( a<0 )  {
8273      return (-halfp(two-a));
8274   } else { 
8275     @<Update |a_new| to reduce |a_new+a_aux| by |a|@>;
8276     b = mp_arc_test(mp, dx02,dy02, dx12,dy12, dx2,dy2,
8277                     halfp(v02), v022, v2, a_new, tol);
8278     if ( b<0 )  
8279       return (-halfp(-b) - half_unit);
8280     else  
8281       return (a + half(b-a));
8282   }
8283 }
8284
8285 @ @<Other local variables in |arc_test|@>=
8286 scaled a,b; /* results of recursive calls */
8287 scaled a_new,a_aux; /* the sum of these gives the |a_goal| */
8288
8289 @ @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is...@>=
8290 a_aux = el_gordo - a_goal;
8291 if ( a_goal > a_aux ) {
8292   a_aux = a_goal - a_aux;
8293   a_new = el_gordo;
8294 } else { 
8295   a_new = a_goal + a_goal;
8296   a_aux = 0;
8297 }
8298
8299 @ There is no need to maintain |a_aux| at this point so we use it as a temporary
8300 to force the additions and subtractions to be done in an order that avoids
8301 overflow.
8302
8303 @<Update |a_new| to reduce |a_new+a_aux| by |a|@>=
8304 if ( a > a_aux ) {
8305   a_aux = a_aux - a;
8306   a_new = a_new + a_aux;
8307 }
8308
8309 @ This code assumes all {\it dx} and {\it dy} variables have magnitude less than
8310 |fraction_four|.  To simplify the rest of the |arc_test| routine, we strengthen
8311 this assumption by requiring the norm of each $({\it dx},{\it dy})$ pair to obey
8312 this bound.  Note that recursive calls will maintain this invariant.
8313
8314 @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,...@>=
8315 dx01 = half(dx0 + dx1);
8316 dx12 = half(dx1 + dx2);
8317 dx02 = half(dx01 + dx12);
8318 dy01 = half(dy0 + dy1);
8319 dy12 = half(dy1 + dy2);
8320 dy02 = half(dy01 + dy12)
8321
8322 @ We should be careful to keep |arc<el_gordo| so that calling |arc_test| with
8323 |a_goal=el_gordo| is guaranteed to yield the arc length.
8324
8325 @<Initialize |v002|, |v022|, and the arc length estimate |arc|;...@>=
8326 v002 = mp_pyth_add(mp, dx01+half(dx0+dx02), dy01+half(dy0+dy02));
8327 v022 = mp_pyth_add(mp, dx12+half(dx02+dx2), dy12+half(dy02+dy2));
8328 tmp = halfp(v02+2);
8329 arc1 = v002 + half(halfp(v0+tmp) - v002);
8330 arc = v022 + half(halfp(v2+tmp) - v022);
8331 if ( (arc < el_gordo-arc1) )  {
8332   arc = arc+arc1;
8333 } else { 
8334   mp->arith_error = true;
8335   if ( a_goal==el_gordo )  return (el_gordo);
8336   else return (-two);
8337 }
8338
8339 @ @<Other local variables in |arc_test|@>=
8340 scaled tmp, tmp2; /* all purpose temporary registers */
8341 scaled arc1; /* arc length estimate for the first half */
8342
8343 @ @<Test if the control points are confined to one quadrant or rotating...@>=
8344 simple = ((dx0>=0) && (dx1>=0) && (dx2>=0)) ||
8345          ((dx0<=0) && (dx1<=0) && (dx2<=0));
8346 if ( simple )
8347   simple = ((dy0>=0) && (dy1>=0) && (dy2>=0)) ||
8348            ((dy0<=0) && (dy1<=0) && (dy2<=0));
8349 if ( ! simple ) {
8350   simple = ((dx0>=dy0) && (dx1>=dy1) && (dx2>=dy2)) ||
8351            ((dx0<=dy0) && (dx1<=dy1) && (dx2<=dy2));
8352   if ( simple ) 
8353     simple = ((-dx0>=dy0) && (-dx1>=dy1) && (-dx2>=dy2)) ||
8354              ((-dx0<=dy0) && (-dx1<=dy1) && (-dx2<=dy2));
8355 }
8356
8357 @ Since Simpson's rule is based on approximating the integrand by a parabola,
8358 @^Simpson's rule@>
8359 it is appropriate to use the same approximation to decide when the integral
8360 reaches the intermediate value |a_goal|.  At this point
8361 $$\eqalign{
8362     {\vb\dot B(0)\vb\over 3} &= \hbox{|v0|}, \qquad
8363     {\vb\dot B({1\over4})\vb\over 3} = {\hbox{|v002|}\over 2}, \qquad
8364     {\vb\dot B({1\over2})\vb\over 3} = {\hbox{|v02|}\over 2}, \cr
8365     {\vb\dot B({3\over4})\vb\over 3} &= {\hbox{|v022|}\over 2}, \qquad
8366     {\vb\dot B(1)\vb\over 3} = \hbox{|v2|} \cr
8367 }
8368 $$
8369 and
8370 $$ {\vb\dot B(t)\vb\over 3} \approx
8371   \cases{B\left(\hbox{|v0|},
8372       \hbox{|v002|}-{1\over 2}\hbox{|v0|}-{1\over 4}\hbox{|v02|},
8373       {1\over 2}\hbox{|v02|}; 2t \right)&
8374     if $t\le{1\over 2}$\cr
8375   B\left({1\over 2}\hbox{|v02|},
8376       \hbox{|v022|}-{1\over 4}\hbox{|v02|}-{1\over 2}\hbox{|v2|},
8377       \hbox{|v2|}; 2t-1 \right)&
8378     if $t\ge{1\over 2}$.\cr}
8379  \eqno (*)
8380 $$
8381 We can integrate $\vb\dot B(t)\vb$ by using
8382 $$\int 3B(a,b,c;\tau)\,dt =
8383   {B(0,a,a+b,a+b+c;\tau) + {\rm constant} \over {d\tau\over dt}}.
8384 $$
8385
8386 This construction allows us to find the time when the arc length reaches
8387 |a_goal| by solving a cubic equation of the form
8388 $$ B(0,a,a+b,a+b+c;\tau) = x, $$
8389 where $\tau$ is $2t$ or $2t+1$, $x$ is |a_goal| or |a_goal-arc1|, and $a$, $b$,
8390 and $c$ are the Bernshte{\u\i}n coefficients from $(*)$ divided by
8391 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
8392 $d\tau\over dt$.  We shall define a function |solve_rising_cubic| that finds
8393 $\tau$ given $a$, $b$, $c$, and $x$.
8394
8395 @<Estimate when the arc length reaches |a_goal| and set |arc_test| to...@>=
8396
8397   tmp = (v02 + 2) / 4;
8398   if ( a_goal<=arc1 ) {
8399     tmp2 = halfp(v0);
8400     return 
8401       (halfp(mp_solve_rising_cubic(mp, tmp2, arc1-tmp2-tmp, tmp, a_goal))- two);
8402   } else { 
8403     tmp2 = halfp(v2);
8404     return ((half_unit - two) +
8405       halfp(mp_solve_rising_cubic(mp, tmp, arc-arc1-tmp-tmp2, tmp2, a_goal-arc1)));
8406   }
8407 }
8408
8409 @ Here is the |solve_rising_cubic| routine that finds the time~$t$ when
8410 $$ B(0, a, a+b, a+b+c; t) = x. $$
8411 This routine is based on |crossing_point| but is simplified by the
8412 assumptions that $B(a,b,c;t)\ge0$ for $0\le t\le1$ and that |0<=x<=a+b+c|.
8413 If rounding error causes this condition to be violated slightly, we just ignore
8414 it and proceed with binary search.  This finds a time when the function value
8415 reaches |x| and the slope is positive.
8416
8417 @<Declare subroutines needed by |arc_test|@>=
8418 scaled mp_solve_rising_cubic (MP mp,scaled a, scaled b,  scaled c, scaled x) {
8419   scaled ab, bc, ac; /* bisection results */
8420   integer t; /* $2^k+q$ where unscaled answer is in $[q2^{-k},(q+1)2^{-k})$ */
8421   integer xx; /* temporary for updating |x| */
8422   if ( (a<0) || (c<0) ) mp_confusion(mp, "rising?");
8423 @:this can't happen rising?}{\quad rising?@>
8424   if ( x<=0 ) {
8425         return 0;
8426   } else if ( x >= a+b+c ) {
8427     return unity;
8428   } else { 
8429     t = 1;
8430     @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than
8431       |el_gordo div 3|@>;
8432     do {  
8433       t+=t;
8434       @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>;
8435       xx = x - a - ab - ac;
8436       if ( xx < -x ) { x+=x; b=ab; c=ac;  }
8437       else { x = x + xx;  a=ac; b=mp->bc; t = t+1; };
8438     } while (t < unity);
8439     return (t - unity);
8440   }
8441 }
8442
8443 @ @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>=
8444 ab = half(a+b);
8445 bc = half(b+c);
8446 ac = half(ab+bc)
8447
8448 @ @d one_third_el_gordo 05252525252 /* upper bound on |a|, |b|, and |c| */
8449
8450 @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than...@>=
8451 while ((a>one_third_el_gordo)||(b>one_third_el_gordo)||(c>one_third_el_gordo)) { 
8452   a = halfp(a);
8453   b = half(b);
8454   c = halfp(c);
8455   x = halfp(x);
8456 }
8457
8458 @ It is convenient to have a simpler interface to |arc_test| that requires no
8459 unnecessary arguments and ensures that each $({\it dx},{\it dy})$ pair has
8460 length less than |fraction_four|.
8461
8462 @d arc_tol   16  /* quit when change in arc length estimate reaches this */
8463
8464 @c scaled mp_do_arc_test (MP mp,scaled dx0, scaled dy0, scaled dx1, 
8465                           scaled dy1, scaled dx2, scaled dy2, scaled a_goal) {
8466   scaled v0,v1,v2; /* length of each $({\it dx},{\it dy})$ pair */
8467   scaled v02; /* twice the norm of the quadratic at $t={1\over2}$ */
8468   v0 = mp_pyth_add(mp, dx0,dy0);
8469   v1 = mp_pyth_add(mp, dx1,dy1);
8470   v2 = mp_pyth_add(mp, dx2,dy2);
8471   if ( (v0>=fraction_four) || (v1>=fraction_four) || (v2>=fraction_four) ) { 
8472     mp->arith_error = true;
8473     if ( a_goal==el_gordo )  return el_gordo;
8474     else return (-two);
8475   } else { 
8476     v02 = mp_pyth_add(mp, dx1+half(dx0+dx2), dy1+half(dy0+dy2));
8477     return (mp_arc_test(mp, dx0,dy0, dx1,dy1, dx2,dy2,
8478                                  v0, v02, v2, a_goal, arc_tol));
8479   }
8480 }
8481
8482 @ Now it is easy to find the arc length of an entire path.
8483
8484 @c scaled mp_get_arc_length (MP mp,pointer h) {
8485   pointer p,q; /* for traversing the path */
8486   scaled a,a_tot; /* current and total arc lengths */
8487   a_tot = 0;
8488   p = h;
8489   while ( right_type(p)!=mp_endpoint ){ 
8490     q = link(p);
8491     a = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8492       left_x(q)-right_x(p), left_y(q)-right_y(p),
8493       x_coord(q)-left_x(q), y_coord(q)-left_y(q), el_gordo);
8494     a_tot = mp_slow_add(mp, a, a_tot);
8495     if ( q==h ) break;  else p=q;
8496   }
8497   check_arith;
8498   return a_tot;
8499 }
8500
8501 @ The inverse operation of finding the time on a path~|h| when the arc length
8502 reaches some value |arc0| can also be accomplished via |do_arc_test|.  Some care
8503 is required to handle very large times or negative times on cyclic paths.  For
8504 non-cyclic paths, |arc0| values that are negative or too large cause
8505 |get_arc_time| to return 0 or the length of path~|h|.
8506
8507 If |arc0| is greater than the arc length of a cyclic path~|h|, the result is a
8508 time value greater than the length of the path.  Since it could be much greater,
8509 we must be prepared to compute the arc length of path~|h| and divide this into
8510 |arc0| to find how many multiples of the length of path~|h| to add.
8511
8512 @c scaled mp_get_arc_time (MP mp,pointer h, scaled  arc0) {
8513   pointer p,q; /* for traversing the path */
8514   scaled t_tot; /* accumulator for the result */
8515   scaled t; /* the result of |do_arc_test| */
8516   scaled arc; /* portion of |arc0| not used up so far */
8517   integer n; /* number of extra times to go around the cycle */
8518   if ( arc0<0 ) {
8519     @<Deal with a negative |arc0| value and |return|@>;
8520   }
8521   if ( arc0==el_gordo ) decr(arc0);
8522   t_tot = 0;
8523   arc = arc0;
8524   p = h;
8525   while ( (right_type(p)!=mp_endpoint) && (arc>0) ) {
8526     q = link(p);
8527     t = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8528       left_x(q)-right_x(p), left_y(q)-right_y(p),
8529       x_coord(q)-left_x(q), y_coord(q)-left_y(q), arc);
8530     @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>;
8531     if ( q==h ) {
8532       @<Update |t_tot| and |arc| to avoid going around the cyclic
8533         path too many times but set |arith_error:=true| and |goto done| on
8534         overflow@>;
8535     }
8536     p = q;
8537   }
8538   check_arith;
8539   return t_tot;
8540 }
8541
8542 @ @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>=
8543 if ( t<0 ) { t_tot = t_tot + t + two;  arc = 0;  }
8544 else { t_tot = t_tot + unity;  arc = arc - t;  }
8545
8546 @ @<Deal with a negative |arc0| value and |return|@>=
8547
8548   if ( left_type(h)==mp_endpoint ) {
8549     t_tot=0;
8550   } else { 
8551     p = mp_htap_ypoc(mp, h);
8552     t_tot = -mp_get_arc_time(mp, p, -arc0);
8553     mp_toss_knot_list(mp, p);
8554   }
8555   check_arith;
8556   return t_tot;
8557 }
8558
8559 @ @<Update |t_tot| and |arc| to avoid going around the cyclic...@>=
8560 if ( arc>0 ) { 
8561   n = arc / (arc0 - arc);
8562   arc = arc - n*(arc0 - arc);
8563   if ( t_tot > el_gordo / (n+1) ) { 
8564     mp->arith_error = true;
8565     t_tot = el_gordo;
8566     break;
8567   }
8568   t_tot = (n + 1)*t_tot;
8569 }
8570
8571 @* \[20] Data structures for pens.
8572 A Pen in \MP\ can be either elliptical or polygonal.  Elliptical pens result
8573 in \ps\ \&{stroke} commands, while anything drawn with a polygonal pen is
8574 @:stroke}{\&{stroke} command@>
8575 converted into an area fill as described in the next part of this program.
8576 The mathematics behind this process is based on simple aspects of the theory
8577 of tracings developed by Leo Guibas, Lyle Ramshaw, and Jorge Stolfi
8578 [``A kinematic framework for computational geometry,'' Proc.\ IEEE Symp.\
8579 Foundations of Computer Science {\bf 24} (1983), 100--111].
8580
8581 Polygonal pens are created from paths via \MP's \&{makepen} primitive.
8582 @:makepen_}{\&{makepen} primitive@>
8583 This path representation is almost sufficient for our purposes except that
8584 a pen path should always be a convex polygon with the vertices in
8585 counter-clockwise order.
8586 Since we will need to scan pen polygons both forward and backward, a pen
8587 should be represented as a doubly linked ring of knot nodes.  There is
8588 room for the extra back pointer because we do not need the
8589 |left_type| or |right_type| fields.  In fact, we don't need the |left_x|,
8590 |left_y|, |right_x|, or |right_y| fields either but we leave these alone
8591 so that certain procedures can operate on both pens and paths.  In particular,
8592 pens can be copied using |copy_path| and recycled using |toss_knot_list|.
8593
8594 @d knil info
8595   /* this replaces the |left_type| and |right_type| fields in a pen knot */
8596
8597 @ The |make_pen| procedure turns a path into a pen by initializing
8598 the |knil| pointers and making sure the knots form a convex polygon.
8599 Thus each cubic in the given path becomes a straight line and the control
8600 points are ignored.  If the path is not cyclic, the ends are connected by a
8601 straight line.
8602
8603 @d copy_pen(A) mp_make_pen(mp, mp_copy_path(mp, (A)),false)
8604
8605 @c @<Declare a function called |convex_hull|@>;
8606 pointer mp_make_pen (MP mp,pointer h, boolean need_hull) {
8607   pointer p,q; /* two consecutive knots */
8608   q=h;
8609   do {  
8610     p=q; q=link(q);
8611     knil(q)=p;
8612   } while (q!=h);
8613   if ( need_hull ){ 
8614     h=mp_convex_hull(mp, h);
8615     @<Make sure |h| isn't confused with an elliptical pen@>;
8616   }
8617   return h;
8618 }
8619
8620 @ The only information required about an elliptical pen is the overall
8621 transformation that has been applied to the original \&{pencircle}.
8622 @:pencircle_}{\&{pencircle} primitive@>
8623 Since it suffices to keep track of how the three points $(0,0)$, $(1,0)$,
8624 and $(0,1)$ are transformed, an elliptical pen can be stored in a single
8625 knot node and transformed as if it were a path.
8626
8627 @d pen_is_elliptical(A) ((A)==link((A)))
8628
8629 @c pointer mp_get_pen_circle (MP mp,scaled diam) {
8630   pointer h; /* the knot node to return */
8631   h=mp_get_node(mp, knot_node_size);
8632   link(h)=h; knil(h)=h;
8633   originator(h)=mp_program_code;
8634   x_coord(h)=0; y_coord(h)=0;
8635   left_x(h)=diam; left_y(h)=0;
8636   right_x(h)=0; right_y(h)=diam;
8637   return h;
8638 }
8639
8640 @ If the polygon being returned by |make_pen| has only one vertex, it will
8641 be interpreted as an elliptical pen.  This is no problem since a degenerate
8642 polygon can equally well be thought of as a degenerate ellipse.  We need only
8643 initialize the |left_x|, |left_y|, |right_x|, and |right_y| fields.
8644
8645 @<Make sure |h| isn't confused with an elliptical pen@>=
8646 if ( pen_is_elliptical( h) ){ 
8647   left_x(h)=x_coord(h); left_y(h)=y_coord(h);
8648   right_x(h)=x_coord(h); right_y(h)=y_coord(h);
8649 }
8650
8651 @ We have to cheat a little here but most operations on pens only use
8652 the first three words in each knot node.
8653 @^data structure assumptions@>
8654
8655 @<Initialize a pen at |test_pen| so that it fits in nine words@>=
8656 x_coord(test_pen)=-half_unit;
8657 y_coord(test_pen)=0;
8658 x_coord(test_pen+3)=half_unit;
8659 y_coord(test_pen+3)=0;
8660 x_coord(test_pen+6)=0;
8661 y_coord(test_pen+6)=unity;
8662 link(test_pen)=test_pen+3;
8663 link(test_pen+3)=test_pen+6;
8664 link(test_pen+6)=test_pen;
8665 knil(test_pen)=test_pen+6;
8666 knil(test_pen+3)=test_pen;
8667 knil(test_pen+6)=test_pen+3
8668
8669 @ Printing a polygonal pen is very much like printing a path
8670
8671 @<Declare subroutines for printing expressions@>=
8672 void mp_pr_pen (MP mp,pointer h) {
8673   pointer p,q; /* for list traversal */
8674   if ( pen_is_elliptical(h) ) {
8675     @<Print the elliptical pen |h|@>;
8676   } else { 
8677     p=h;
8678     do {  
8679       mp_print_two(mp, x_coord(p),y_coord(p));
8680       mp_print_nl(mp, " .. ");
8681       @<Advance |p| making sure the links are OK and |return| if there is
8682         a problem@>;
8683      } while (p!=h);
8684      mp_print(mp, "cycle");
8685   }
8686 }
8687
8688 @ @<Advance |p| making sure the links are OK and |return| if there is...@>=
8689 q=link(p);
8690 if ( (q==null) || (knil(q)!=p) ) { 
8691   mp_print_nl(mp, "???"); return; /* this won't happen */
8692 @.???@>
8693 }
8694 p=q
8695
8696 @ @<Print the elliptical pen |h|@>=
8697
8698 mp_print(mp, "pencircle transformed (");
8699 mp_print_scaled(mp, x_coord(h));
8700 mp_print_char(mp, ',');
8701 mp_print_scaled(mp, y_coord(h));
8702 mp_print_char(mp, ',');
8703 mp_print_scaled(mp, left_x(h)-x_coord(h));
8704 mp_print_char(mp, ',');
8705 mp_print_scaled(mp, right_x(h)-x_coord(h));
8706 mp_print_char(mp, ',');
8707 mp_print_scaled(mp, left_y(h)-y_coord(h));
8708 mp_print_char(mp, ',');
8709 mp_print_scaled(mp, right_y(h)-y_coord(h));
8710 mp_print_char(mp, ')');
8711 }
8712
8713 @ Here us another version of |pr_pen| that prints the pen as a diagnostic
8714 message.
8715
8716 @<Declare subroutines for printing expressions@>=
8717 void mp_print_pen (MP mp,pointer h, char *s, boolean nuline) { 
8718   mp_print_diagnostic(mp, "Pen",s,nuline); mp_print_ln(mp);
8719 @.Pen at line...@>
8720   mp_pr_pen(mp, h);
8721   mp_end_diagnostic(mp, true);
8722 }
8723
8724 @ Making a polygonal pen into a path involves restoring the |left_type| and
8725 |right_type| fields and setting the control points so as to make a polygonal
8726 path.
8727
8728 @c 
8729 void mp_make_path (MP mp,pointer h) {
8730   pointer p; /* for traversing the knot list */
8731   small_number k; /* a loop counter */
8732   @<Other local variables in |make_path|@>;
8733   if ( pen_is_elliptical(h) ) {
8734     @<Make the elliptical pen |h| into a path@>;
8735   } else { 
8736     p=h;
8737     do {  
8738       left_type(p)=mp_explicit;
8739       right_type(p)=mp_explicit;
8740       @<copy the coordinates of knot |p| into its control points@>;
8741        p=link(p);
8742     } while (p!=h);
8743   }
8744 }
8745
8746 @ @<copy the coordinates of knot |p| into its control points@>=
8747 left_x(p)=x_coord(p);
8748 left_y(p)=y_coord(p);
8749 right_x(p)=x_coord(p);
8750 right_y(p)=y_coord(p)
8751
8752 @ We need an eight knot path to get a good approximation to an ellipse.
8753
8754 @<Make the elliptical pen |h| into a path@>=
8755
8756   @<Extract the transformation parameters from the elliptical pen~|h|@>;
8757   p=h;
8758   for (k=0;k<=7;k++ ) { 
8759     @<Initialize |p| as the |k|th knot of a circle of unit diameter,
8760       transforming it appropriately@>;
8761     if ( k==7 ) link(p)=h;  else link(p)=mp_get_node(mp, knot_node_size);
8762     p=link(p);
8763   }
8764 }
8765
8766 @ @<Extract the transformation parameters from the elliptical pen~|h|@>=
8767 center_x=x_coord(h);
8768 center_y=y_coord(h);
8769 width_x=left_x(h)-center_x;
8770 width_y=left_y(h)-center_y;
8771 height_x=right_x(h)-center_x;
8772 height_y=right_y(h)-center_y
8773
8774 @ @<Other local variables in |make_path|@>=
8775 scaled center_x,center_y; /* translation parameters for an elliptical pen */
8776 scaled width_x,width_y; /* the effect of a unit change in $x$ */
8777 scaled height_x,height_y; /* the effect of a unit change in $y$ */
8778 scaled dx,dy; /* the vector from knot |p| to its right control point */
8779 integer kk;
8780   /* |k| advanced $270^\circ$ around the ring (cf. $\sin\theta=\cos(\theta+270)$) */
8781
8782 @ The only tricky thing here are the tables |half_cos| and |d_cos| used to
8783 find the point $k/8$ of the way around the circle and the direction vector
8784 to use there.
8785
8786 @<Initialize |p| as the |k|th knot of a circle of unit diameter,...@>=
8787 kk=(k+6)% 8;
8788 x_coord(p)=center_x+mp_take_fraction(mp, mp->half_cos[k],width_x)
8789            +mp_take_fraction(mp, mp->half_cos[kk],height_x);
8790 y_coord(p)=center_y+mp_take_fraction(mp, mp->half_cos[k],width_y)
8791            +mp_take_fraction(mp, mp->half_cos[kk],height_y);
8792 dx=-mp_take_fraction(mp, mp->d_cos[kk],width_x)
8793    +mp_take_fraction(mp, mp->d_cos[k],height_x);
8794 dy=-mp_take_fraction(mp, mp->d_cos[kk],width_y)
8795    +mp_take_fraction(mp, mp->d_cos[k],height_y);
8796 right_x(p)=x_coord(p)+dx;
8797 right_y(p)=y_coord(p)+dy;
8798 left_x(p)=x_coord(p)-dx;
8799 left_y(p)=y_coord(p)-dy;
8800 left_type(p)=mp_explicit;
8801 right_type(p)=mp_explicit;
8802 originator(p)=mp_program_code
8803
8804 @ @<Glob...@>=
8805 fraction half_cos[8]; /* ${1\over2}\cos(45k)$ */
8806 fraction d_cos[8]; /* a magic constant times $\cos(45k)$ */
8807
8808 @ The magic constant for |d_cos| is the distance between $({1\over2},0)$ and
8809 $({1\over4}\sqrt2,{1\over4}\sqrt2)$ times the result of the |velocity|
8810 function for $\theta=\phi=22.5^\circ$.  This comes out to be
8811 $$ d = {\sqrt{2-\sqrt2}\over 3+3\cos22.5^\circ}
8812   \approx 0.132608244919772.
8813 $$
8814
8815 @<Set init...@>=
8816 mp->half_cos[0]=fraction_half;
8817 mp->half_cos[1]=94906266; /* $2^{26}\sqrt2\approx94906265.62$ */
8818 mp->half_cos[2]=0;
8819 mp->d_cos[0]=35596755; /* $2^{28}d\approx35596754.69$ */
8820 mp->d_cos[1]=25170707; /* $2^{27}\sqrt2\,d\approx25170706.63$ */
8821 mp->d_cos[2]=0;
8822 for (k=3;k<= 4;k++ ) { 
8823   mp->half_cos[k]=-mp->half_cos[4-k];
8824   mp->d_cos[k]=-mp->d_cos[4-k];
8825 }
8826 for (k=5;k<= 7;k++ ) { 
8827   mp->half_cos[k]=mp->half_cos[8-k];
8828   mp->d_cos[k]=mp->d_cos[8-k];
8829 }
8830
8831 @ The |convex_hull| function forces a pen polygon to be convex when it is
8832 returned by |make_pen| and after any subsequent transformation where rounding
8833 error might allow the convexity to be lost.
8834 The convex hull algorithm used here is described by F.~P. Preparata and
8835 M.~I. Shamos [{\sl Computational Geometry}, Springer-Verlag, 1985].
8836
8837 @<Declare a function called |convex_hull|@>=
8838 @<Declare a procedure called |move_knot|@>;
8839 pointer mp_convex_hull (MP mp,pointer h) { /* Make a polygonal pen convex */
8840   pointer l,r; /* the leftmost and rightmost knots */
8841   pointer p,q; /* knots being scanned */
8842   pointer s; /* the starting point for an upcoming scan */
8843   scaled dx,dy; /* a temporary pointer */
8844   if ( pen_is_elliptical(h) ) {
8845      return h;
8846   } else { 
8847     @<Set |l| to the leftmost knot in polygon~|h|@>;
8848     @<Set |r| to the rightmost knot in polygon~|h|@>;
8849     if ( l!=r ) { 
8850       s=link(r);
8851       @<Find any knots on the path from |l| to |r| above the |l|-|r| line and
8852         move them past~|r|@>;
8853       @<Find any knots on the path from |s| to |l| below the |l|-|r| line and
8854         move them past~|l|@>;
8855       @<Sort the path from |l| to |r| by increasing $x$@>;
8856       @<Sort the path from |r| to |l| by decreasing $x$@>;
8857     }
8858     if ( l!=link(l) ) {
8859       @<Do a Gramm scan and remove vertices where there is no left turn@>;
8860     }
8861     return l;
8862   }
8863 }
8864
8865 @ All comparisons are done primarily on $x$ and secondarily on $y$.
8866
8867 @<Set |l| to the leftmost knot in polygon~|h|@>=
8868 l=h;
8869 p=link(h);
8870 while ( p!=h ) { 
8871   if ( x_coord(p)<=x_coord(l) )
8872     if ( (x_coord(p)<x_coord(l)) || (y_coord(p)<y_coord(l)) )
8873       l=p;
8874   p=link(p);
8875 }
8876
8877 @ @<Set |r| to the rightmost knot in polygon~|h|@>=
8878 r=h;
8879 p=link(h);
8880 while ( p!=h ) { 
8881   if ( x_coord(p)>=x_coord(r) )
8882     if ( (x_coord(p)>x_coord(r)) || (y_coord(p)>y_coord(r)) )
8883       r=p;
8884   p=link(p);
8885 }
8886
8887 @ @<Find any knots on the path from |l| to |r| above the |l|-|r| line...@>=
8888 dx=x_coord(r)-x_coord(l);
8889 dy=y_coord(r)-y_coord(l);
8890 p=link(l);
8891 while ( p!=r ) { 
8892   q=link(p);
8893   if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))>0 )
8894     mp_move_knot(mp, p, r);
8895   p=q;
8896 }
8897
8898 @ The |move_knot| procedure removes |p| from a doubly linked list and inserts
8899 it after |q|.
8900
8901 @ @<Declare a procedure called |move_knot|@>=
8902 void mp_move_knot (MP mp,pointer p, pointer q) { 
8903   link(knil(p))=link(p);
8904   knil(link(p))=knil(p);
8905   knil(p)=q;
8906   link(p)=link(q);
8907   link(q)=p;
8908   knil(link(p))=p;
8909 }
8910
8911 @ @<Find any knots on the path from |s| to |l| below the |l|-|r| line...@>=
8912 p=s;
8913 while ( p!=l ) { 
8914   q=link(p);
8915   if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))<0 )
8916     mp_move_knot(mp, p,l);
8917   p=q;
8918 }
8919
8920 @ The list is likely to be in order already so we just do linear insertions.
8921 Secondary comparisons on $y$ ensure that the sort is consistent with the
8922 choice of |l| and |r|.
8923
8924 @<Sort the path from |l| to |r| by increasing $x$@>=
8925 p=link(l);
8926 while ( p!=r ) { 
8927   q=knil(p);
8928   while ( x_coord(q)>x_coord(p) ) q=knil(q);
8929   while ( x_coord(q)==x_coord(p) ) {
8930     if ( y_coord(q)>y_coord(p) ) q=knil(q); else break;
8931   }
8932   if ( q==knil(p) ) p=link(p);
8933   else { p=link(p); mp_move_knot(mp, knil(p),q); };
8934 }
8935
8936 @ @<Sort the path from |r| to |l| by decreasing $x$@>=
8937 p=link(r);
8938 while ( p!=l ){ 
8939   q=knil(p);
8940   while ( x_coord(q)<x_coord(p) ) q=knil(q);
8941   while ( x_coord(q)==x_coord(p) ) {
8942     if ( y_coord(q)<y_coord(p) ) q=knil(q); else break;
8943   }
8944   if ( q==knil(p) ) p=link(p);
8945   else { p=link(p); mp_move_knot(mp, knil(p),q); };
8946 }
8947
8948 @ The condition involving |ab_vs_cd| tests if there is not a left turn
8949 at knot |q|.  There usually will be a left turn so we streamline the case
8950 where the |then| clause is not executed.
8951
8952 @<Do a Gramm scan and remove vertices where there...@>=
8953
8954 p=l; q=link(l);
8955 while (1) { 
8956   dx=x_coord(q)-x_coord(p);
8957   dy=y_coord(q)-y_coord(p);
8958   p=q; q=link(q);
8959   if ( p==l ) break;
8960   if ( p!=r )
8961     if ( mp_ab_vs_cd(mp, dx,y_coord(q)-y_coord(p),dy,x_coord(q)-x_coord(p))<=0 ) {
8962       @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>;
8963     }
8964   }
8965 }
8966
8967 @ @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>=
8968
8969 s=knil(p);
8970 mp_free_node(mp, p,knot_node_size);
8971 link(s)=q; knil(q)=s;
8972 if ( s==l ) p=s;
8973 else { p=knil(s); q=s; };
8974 }
8975
8976 @ The |find_offset| procedure sets global variables |(cur_x,cur_y)| to the
8977 offset associated with the given direction |(x,y)|.  If two different offsets
8978 apply, it chooses one of them.
8979
8980 @c 
8981 void mp_find_offset (MP mp,scaled x, scaled y, pointer h) {
8982   pointer p,q; /* consecutive knots */
8983   scaled wx,wy,hx,hy;
8984   /* the transformation matrix for an elliptical pen */
8985   fraction xx,yy; /* untransformed offset for an elliptical pen */
8986   fraction d; /* a temporary register */
8987   if ( pen_is_elliptical(h) ) {
8988     @<Find the offset for |(x,y)| on the elliptical pen~|h|@>
8989   } else { 
8990     q=h;
8991     do {  
8992       p=q; q=link(q);
8993     } while (!(mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)>=0));
8994     do {  
8995       p=q; q=link(q);
8996     } while (!(mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)<=0));
8997     mp->cur_x=x_coord(p);
8998     mp->cur_y=y_coord(p);
8999   }
9000 }
9001
9002 @ @<Glob...@>=
9003 scaled cur_x;
9004 scaled cur_y; /* all-purpose return value registers */
9005
9006 @ @<Find the offset for |(x,y)| on the elliptical pen~|h|@>=
9007 if ( (x==0) && (y==0) ) {
9008   mp->cur_x=x_coord(h); mp->cur_y=y_coord(h);  
9009 } else { 
9010   @<Find the non-constant part of the transformation for |h|@>;
9011   while ( (abs(x)<fraction_half) && (abs(y)<fraction_half) ){ 
9012     x+=x; y+=y;  
9013   };
9014   @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the
9015     untransformed version of |(x,y)|@>;
9016   mp->cur_x=x_coord(h)+mp_take_fraction(mp, xx,wx)+mp_take_fraction(mp, yy,hx);
9017   mp->cur_y=y_coord(h)+mp_take_fraction(mp, xx,wy)+mp_take_fraction(mp, yy,hy);
9018 }
9019
9020 @ @<Find the non-constant part of the transformation for |h|@>=
9021 wx=left_x(h)-x_coord(h);
9022 wy=left_y(h)-y_coord(h);
9023 hx=right_x(h)-x_coord(h);
9024 hy=right_y(h)-y_coord(h)
9025
9026 @ @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the...@>=
9027 yy=-(mp_take_fraction(mp, x,hy)+mp_take_fraction(mp, y,-hx));
9028 xx=mp_take_fraction(mp, x,-wy)+mp_take_fraction(mp, y,wx);
9029 d=mp_pyth_add(mp, xx,yy);
9030 if ( d>0 ) { 
9031   xx=half(mp_make_fraction(mp, xx,d));
9032   yy=half(mp_make_fraction(mp, yy,d));
9033 }
9034
9035 @ Finding the bounding box of a pen is easy except if the pen is elliptical.
9036 But we can handle that case by just calling |find_offset| twice.  The answer
9037 is stored in the global variables |minx|, |maxx|, |miny|, and |maxy|.
9038
9039 @c 
9040 void mp_pen_bbox (MP mp,pointer h) {
9041   pointer p; /* for scanning the knot list */
9042   if ( pen_is_elliptical(h) ) {
9043     @<Find the bounding box of an elliptical pen@>;
9044   } else { 
9045     minx=x_coord(h); maxx=minx;
9046     miny=y_coord(h); maxy=miny;
9047     p=link(h);
9048     while ( p!=h ) {
9049       if ( x_coord(p)<minx ) minx=x_coord(p);
9050       if ( y_coord(p)<miny ) miny=y_coord(p);
9051       if ( x_coord(p)>maxx ) maxx=x_coord(p);
9052       if ( y_coord(p)>maxy ) maxy=y_coord(p);
9053       p=link(p);
9054     }
9055   }
9056 }
9057
9058 @ @<Find the bounding box of an elliptical pen@>=
9059
9060 mp_find_offset(mp, 0,fraction_one,h);
9061 maxx=mp->cur_x;
9062 minx=2*x_coord(h)-mp->cur_x;
9063 mp_find_offset(mp, -fraction_one,0,h);
9064 maxy=mp->cur_y;
9065 miny=2*y_coord(h)-mp->cur_y;
9066 }
9067
9068 @* \[21] Edge structures.
9069 Now we come to \MP's internal scheme for representing pictures.
9070 The representation is very different from \MF's edge structures
9071 because \MP\ pictures contain \ps\ graphics objects instead of pixel
9072 images.  However, the basic idea is somewhat similar in that shapes
9073 are represented via their boundaries.
9074
9075 The main purpose of edge structures is to keep track of graphical objects
9076 until it is time to translate them into \ps.  Since \MP\ does not need to
9077 know anything about an edge structure other than how to translate it into
9078 \ps\ and how to find its bounding box, edge structures can be just linked
9079 lists of graphical objects.  \MP\ has no easy way to determine whether
9080 two such objects overlap, but it suffices to draw the first one first and
9081 let the second one overwrite it if necessary.
9082
9083 @<Types...@>=
9084 enum mp_graphical_object_code {
9085   @<Graphical object codes@>
9086 };
9087
9088 @ Let's consider the types of graphical objects one at a time.
9089 First of all, a filled contour is represented by a eight-word node.  The first
9090 word contains |type| and |link| fields, and the next six words contain a
9091 pointer to a cyclic path and the value to use for \ps' \&{currentrgbcolor}
9092 parameter.  If a pen is used for filling |pen_p|, |ljoin_val| and |miterlim_val|
9093 give the relevant information.
9094
9095 @d path_p(A) link((A)+1)
9096   /* a pointer to the path that needs filling */
9097 @d pen_p(A) info((A)+1)
9098   /* a pointer to the pen to fill or stroke with */
9099 @d color_model(A) type((A)+2) /*  the color model  */
9100 @d obj_red_loc(A) ((A)+3)  /* the first of three locations for the color */
9101 @d obj_cyan_loc obj_red_loc  /* the first of four locations for the color */
9102 @d obj_grey_loc obj_red_loc  /* the location for the color */
9103 @d red_val(A) mp->mem[(A)+3].sc
9104   /* the red component of the color in the range $0\ldots1$ */
9105 @d cyan_val red_val
9106 @d grey_val red_val
9107 @d green_val(A) mp->mem[(A)+4].sc
9108   /* the green component of the color in the range $0\ldots1$ */
9109 @d magenta_val green_val
9110 @d blue_val(A) mp->mem[(A)+5].sc
9111   /* the blue component of the color in the range $0\ldots1$ */
9112 @d yellow_val blue_val
9113 @d black_val(A) mp->mem[(A)+6].sc
9114   /* the blue component of the color in the range $0\ldots1$ */
9115 @d ljoin_val(A) name_type((A))  /* the value of \&{linejoin} */
9116 @:mp_linejoin_}{\&{linejoin} primitive@>
9117 @d miterlim_val(A) mp->mem[(A)+7].sc  /* the value of \&{miterlimit} */
9118 @:mp_miterlimit_}{\&{miterlimit} primitive@>
9119 @d obj_color_part(A) mp->mem[(A)+3-red_part].sc
9120   /* interpret an object pointer that has been offset by |red_part..blue_part| */
9121 @d pre_script(A) mp->mem[(A)+8].hh.lh
9122 @d post_script(A) mp->mem[(A)+8].hh.rh
9123 @d fill_node_size 9
9124
9125 @ @<Graphical object codes@>=
9126 mp_fill_code=1,
9127
9128 @ @c 
9129 pointer mp_new_fill_node (MP mp,pointer p) {
9130   /* make a fill node for cyclic path |p| and color black */
9131   pointer t; /* the new node */
9132   t=mp_get_node(mp, fill_node_size);
9133   type(t)=mp_fill_code;
9134   path_p(t)=p;
9135   pen_p(t)=null; /* |null| means don't use a pen */
9136   red_val(t)=0;
9137   green_val(t)=0;
9138   blue_val(t)=0;
9139   black_val(t)=0;
9140   color_model(t)=mp_uninitialized_model;
9141   pre_script(t)=null;
9142   post_script(t)=null;
9143   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9144   return t;
9145 }
9146
9147 @ @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>=
9148 if ( mp->internal[mp_linejoin]>unity ) ljoin_val(t)=2;
9149 else if ( mp->internal[mp_linejoin]>0 ) ljoin_val(t)=1;
9150 else ljoin_val(t)=0;
9151 if ( mp->internal[mp_miterlimit]<unity )
9152   miterlim_val(t)=unity;
9153 else
9154   miterlim_val(t)=mp->internal[mp_miterlimit]
9155
9156 @ A stroked path is represented by an eight-word node that is like a filled
9157 contour node except that it contains the current \&{linecap} value, a scale
9158 factor for the dash pattern, and a pointer that is non-null if the stroke
9159 is to be dashed.  The purpose of the scale factor is to allow a picture to
9160 be transformed without touching the picture that |dash_p| points to.
9161
9162 @d dash_p(A) link((A)+9)
9163   /* a pointer to the edge structure that gives the dash pattern */
9164 @d lcap_val(A) type((A)+9)
9165   /* the value of \&{linecap} */
9166 @:mp_linecap_}{\&{linecap} primitive@>
9167 @d dash_scale(A) mp->mem[(A)+10].sc /* dash lengths are scaled by this factor */
9168 @d stroked_node_size 11
9169
9170 @ @<Graphical object codes@>=
9171 mp_stroked_code=2,
9172
9173 @ @c 
9174 pointer mp_new_stroked_node (MP mp,pointer p) {
9175   /* make a stroked node for path |p| with |pen_p(p)| temporarily |null| */
9176   pointer t; /* the new node */
9177   t=mp_get_node(mp, stroked_node_size);
9178   type(t)=mp_stroked_code;
9179   path_p(t)=p; pen_p(t)=null;
9180   dash_p(t)=null;
9181   dash_scale(t)=unity;
9182   red_val(t)=0;
9183   green_val(t)=0;
9184   blue_val(t)=0;
9185   black_val(t)=0;
9186   color_model(t)=mp_uninitialized_model;
9187   pre_script(t)=null;
9188   post_script(t)=null;
9189   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9190   if ( mp->internal[mp_linecap]>unity ) lcap_val(t)=2;
9191   else if ( mp->internal[mp_linecap]>0 ) lcap_val(t)=1;
9192   else lcap_val(t)=0;
9193   return t;
9194 }
9195
9196 @ When a dashed line is computed in a transformed coordinate system, the dash
9197 lengths get scaled like the pen shape and we need to compensate for this.  Since
9198 there is no unique scale factor for an arbitrary transformation, we use the
9199 the square root of the determinant.  The properties of the determinant make it
9200 easier to maintain the |dash_scale|.  The computation is fairly straight-forward
9201 except for the initialization of the scale factor |s|.  The factor of 64 is
9202 needed because |square_rt| scales its result by $2^8$ while we need $2^{14}$
9203 to counteract the effect of |take_fraction|.
9204
9205 @<Declare subroutines needed by |print_edges|@>=
9206 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) {
9207   scaled maxabs; /* $max(|a|,|b|,|c|,|d|)$ */
9208   integer s; /* amount by which the result of |square_rt| needs to be scaled */
9209   @<Initialize |maxabs|@>;
9210   s=64;
9211   while ( (maxabs<fraction_one) && (s>1) ){ 
9212     a+=a; b+=b; c+=c; d+=d;
9213     maxabs+=maxabs; s=halfp(s);
9214   }
9215   return s*mp_square_rt(mp, abs(mp_take_fraction(mp, a,d)-mp_take_fraction(mp, b,c)));
9216 }
9217 @#
9218 scaled mp_get_pen_scale (MP mp,pointer p) { 
9219   return mp_sqrt_det(mp, 
9220     left_x(p)-x_coord(p), right_x(p)-x_coord(p),
9221     left_y(p)-y_coord(p), right_y(p)-y_coord(p));
9222 }
9223
9224 @ @<Internal library ...@>=
9225 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) ;
9226
9227
9228 @ @<Initialize |maxabs|@>=
9229 maxabs=abs(a);
9230 if ( abs(b)>maxabs ) maxabs=abs(b);
9231 if ( abs(c)>maxabs ) maxabs=abs(c);
9232 if ( abs(d)>maxabs ) maxabs=abs(d)
9233
9234 @ When a picture contains text, this is represented by a fourteen-word node
9235 where the color information and |type| and |link| fields are augmented by
9236 additional fields that describe the text and  how it is transformed.
9237 The |path_p| and |pen_p| pointers are replaced by a number that identifies
9238 the font and a string number that gives the text to be displayed.
9239 The |width|, |height|, and |depth| fields
9240 give the dimensions of the text at its design size, and the remaining six
9241 words give a transformation to be applied to the text.  The |new_text_node|
9242 function initializes everything to default values so that the text comes out
9243 black with its reference point at the origin.
9244
9245 @d text_p(A) link((A)+1)  /* a string pointer for the text to display */
9246 @d font_n(A) info((A)+1)  /* the font number */
9247 @d width_val(A) mp->mem[(A)+7].sc  /* unscaled width of the text */
9248 @d height_val(A) mp->mem[(A)+9].sc  /* unscaled height of the text */
9249 @d depth_val(A) mp->mem[(A)+10].sc  /* unscaled depth of the text */
9250 @d text_tx_loc(A) ((A)+11)
9251   /* the first of six locations for transformation parameters */
9252 @d tx_val(A) mp->mem[(A)+11].sc  /* $x$ shift amount */
9253 @d ty_val(A) mp->mem[(A)+12].sc  /* $y$ shift amount */
9254 @d txx_val(A) mp->mem[(A)+13].sc  /* |txx| transformation parameter */
9255 @d txy_val(A) mp->mem[(A)+14].sc  /* |txy| transformation parameter */
9256 @d tyx_val(A) mp->mem[(A)+15].sc  /* |tyx| transformation parameter */
9257 @d tyy_val(A) mp->mem[(A)+16].sc  /* |tyy| transformation parameter */
9258 @d text_trans_part(A) mp->mem[(A)+11-x_part].sc
9259     /* interpret a text node pointer that has been offset by |x_part..yy_part| */
9260 @d text_node_size 17
9261
9262 @ @<Graphical object codes@>=
9263 mp_text_code=3,
9264
9265 @ @c @<Declare text measuring subroutines@>;
9266 pointer mp_new_text_node (MP mp,char *f,str_number s) {
9267   /* make a text node for font |f| and text string |s| */
9268   pointer t; /* the new node */
9269   t=mp_get_node(mp, text_node_size);
9270   type(t)=mp_text_code;
9271   text_p(t)=s;
9272   font_n(t)=mp_find_font(mp, f); /* this identifies the font */
9273   red_val(t)=0;
9274   green_val(t)=0;
9275   blue_val(t)=0;
9276   black_val(t)=0;
9277   color_model(t)=mp_uninitialized_model;
9278   pre_script(t)=null;
9279   post_script(t)=null;
9280   tx_val(t)=0; ty_val(t)=0;
9281   txx_val(t)=unity; txy_val(t)=0;
9282   tyx_val(t)=0; tyy_val(t)=unity;
9283   mp_set_text_box(mp, t); /* this finds the bounding box */
9284   return t;
9285 }
9286
9287 @ The last two types of graphical objects that can occur in an edge structure
9288 are clipping paths and \&{setbounds} paths.  These are slightly more difficult
9289 @:set_bounds_}{\&{setbounds} primitive@>
9290 to implement because we must keep track of exactly what is being clipped or
9291 bounded when pictures get merged together.  For this reason, each clipping or
9292 \&{setbounds} operation is represented by a pair of nodes:  first comes a
9293 two-word node whose |path_p| gives the relevant path, then there is the list
9294 of objects to clip or bound followed by a two-word node whose second word is
9295 unused.
9296
9297 Using at least two words for each graphical object node allows them all to be
9298 allocated and deallocated similarly with a global array |gr_object_size| to
9299 give the size in words for each object type.
9300
9301 @d start_clip_size 2
9302 @d start_bounds_size 2
9303 @d stop_clip_size 2 /* the second word is not used here */
9304 @d stop_bounds_size 2 /* the second word is not used here */
9305 @#
9306 @d stop_type(A) ((A)+2)
9307   /* matching |type| for |start_clip_code| or |start_bounds_code| */
9308 @d has_color(A) (type((A))<mp_start_clip_code)
9309   /* does a graphical object have color fields? */
9310 @d has_pen(A) (type((A))<mp_text_code)
9311   /* does a graphical object have a |pen_p| field? */
9312 @d is_start_or_stop(A) (type((A))>=mp_start_clip_code)
9313 @d is_stop(A) (type((A))>=mp_stop_clip_code)
9314
9315 @ @<Graphical object codes@>=
9316 mp_start_clip_code=4, /* |type| of a node that starts clipping */
9317 mp_start_bounds_code=5, /* |type| of a node that gives a \&{setbounds} path */
9318 mp_stop_clip_code=6, /* |type| of a node that stops clipping */
9319 mp_stop_bounds_code=7, /* |type| of a node that stops \&{setbounds} */
9320
9321 @ @c 
9322 pointer mp_new_bounds_node (MP mp,pointer p, small_number  c) {
9323   /* make a node of type |c| where |p| is the clipping or \&{setbounds} path */
9324   pointer t; /* the new node */
9325   t=mp_get_node(mp, mp->gr_object_size[c]);
9326   type(t)=c;
9327   path_p(t)=p;
9328   return t;
9329 };
9330
9331 @ We need an array to keep track of the sizes of graphical objects.
9332
9333 @<Glob...@>=
9334 small_number gr_object_size[mp_stop_bounds_code+1];
9335
9336 @ @<Set init...@>=
9337 mp->gr_object_size[mp_fill_code]=fill_node_size;
9338 mp->gr_object_size[mp_stroked_code]=stroked_node_size;
9339 mp->gr_object_size[mp_text_code]=text_node_size;
9340 mp->gr_object_size[mp_start_clip_code]=start_clip_size;
9341 mp->gr_object_size[mp_stop_clip_code]=stop_clip_size;
9342 mp->gr_object_size[mp_start_bounds_code]=start_bounds_size;
9343 mp->gr_object_size[mp_stop_bounds_code]=stop_bounds_size;
9344
9345 @ All the essential information in an edge structure is encoded as a linked list
9346 of graphical objects as we have just seen, but it is helpful to add some
9347 redundant information.  A single edge structure might be used as a dash pattern
9348 many times, and it would be nice to avoid scanning the same structure
9349 repeatedly.  Thus, an edge structure known to be a suitable dash pattern
9350 has a header that gives a list of dashes in a sorted order designed for rapid
9351 translation into \ps.
9352
9353 Each dash is represented by a three-word node containing the initial and final
9354 $x$~coordinates as well as the usual |link| field.  The |link| fields points to
9355 the dash node with the next higher $x$-coordinates and the final link points
9356 to a special location called |null_dash|.  (There should be no overlap between
9357 dashes).  Since the $y$~coordinate of the dash pattern is needed to determine
9358 the period of repetition, this needs to be stored in the edge header along
9359 with a pointer to the list of dash nodes.
9360
9361 @d start_x(A) mp->mem[(A)+1].sc  /* the starting $x$~coordinate in a dash node */
9362 @d stop_x(A) mp->mem[(A)+2].sc  /* the ending $x$~coordinate in a dash node */
9363 @d dash_node_size 3
9364 @d dash_list link
9365   /* in an edge header this points to the first dash node */
9366 @d dash_y(A) mp->mem[(A)+1].sc  /* $y$ value for the dash list in an edge header */
9367
9368 @ It is also convenient for an edge header to contain the bounding
9369 box information needed by the \&{llcorner} and \&{urcorner} operators
9370 so that this does not have to be recomputed unnecessarily.  This is done by
9371 adding fields for the $x$~and $y$ extremes as well as a pointer that indicates
9372 how far the bounding box computation has gotten.  Thus if the user asks for
9373 the bounding box and then adds some more text to the picture before asking
9374 for more bounding box information, the second computation need only look at
9375 the additional text.
9376
9377 When the bounding box has not been computed, the |bblast| pointer points
9378 to a dummy link at the head of the graphical object list while the |minx_val|
9379 and |miny_val| fields contain |el_gordo| and the |maxx_val| and |maxy_val|
9380 fields contain |-el_gordo|.
9381
9382 Since the bounding box of pictures containing objects of type
9383 |mp_start_bounds_code| depends on the value of \&{truecorners}, the bounding box
9384 @:mp_true_corners_}{\&{truecorners} primitive@>
9385 data might not be valid for all values of this parameter.  Hence, the |bbtype|
9386 field is needed to keep track of this.
9387
9388 @d minx_val(A) mp->mem[(A)+2].sc
9389 @d miny_val(A) mp->mem[(A)+3].sc
9390 @d maxx_val(A) mp->mem[(A)+4].sc
9391 @d maxy_val(A) mp->mem[(A)+5].sc
9392 @d bblast(A) link((A)+6)  /* last item considered in bounding box computation */
9393 @d bbtype(A) info((A)+6)  /* tells how bounding box data depends on \&{truecorners} */
9394 @d dummy_loc(A) ((A)+7)  /* where the object list begins in an edge header */
9395 @d no_bounds 0
9396   /* |bbtype| value when bounding box data is valid for all \&{truecorners} values */
9397 @d bounds_set 1
9398   /* |bbtype| value when bounding box data is for \&{truecorners}${}\le 0$ */
9399 @d bounds_unset 2
9400   /* |bbtype| value when bounding box data is for \&{truecorners}${}>0$ */
9401
9402 @c 
9403 void mp_init_bbox (MP mp,pointer h) {
9404   /* Initialize the bounding box information in edge structure |h| */
9405   bblast(h)=dummy_loc(h);
9406   bbtype(h)=no_bounds;
9407   minx_val(h)=el_gordo;
9408   miny_val(h)=el_gordo;
9409   maxx_val(h)=-el_gordo;
9410   maxy_val(h)=-el_gordo;
9411 }
9412
9413 @ The only other entries in an edge header are a reference count in the first
9414 word and a pointer to the tail of the object list in the last word.
9415
9416 @d obj_tail(A) info((A)+7)  /* points to the last entry in the object list */
9417 @d edge_header_size 8
9418
9419 @c 
9420 void mp_init_edges (MP mp,pointer h) {
9421   /* initialize an edge header to null values */
9422   dash_list(h)=null_dash;
9423   obj_tail(h)=dummy_loc(h);
9424   link(dummy_loc(h))=null;
9425   ref_count(h)=null;
9426   mp_init_bbox(mp, h);
9427 }
9428
9429 @ Here is how edge structures are deleted.  The process can be recursive because
9430 of the need to dereference edge structures that are used as dash patterns.
9431 @^recursion@>
9432
9433 @d add_edge_ref(A) incr(ref_count(A))
9434 @d delete_edge_ref(A) { 
9435    if ( ref_count((A))==null ) 
9436      mp_toss_edges(mp, A);
9437    else 
9438      decr(ref_count(A)); 
9439    }
9440
9441 @<Declare the recycling subroutines@>=
9442 void mp_flush_dash_list (MP mp,pointer h);
9443 pointer mp_toss_gr_object (MP mp,pointer p) ;
9444 void mp_toss_edges (MP mp,pointer h) ;
9445
9446 @ @c void mp_toss_edges (MP mp,pointer h) {
9447   pointer p,q;  /* pointers that scan the list being recycled */
9448   pointer r; /* an edge structure that object |p| refers to */
9449   mp_flush_dash_list(mp, h);
9450   q=link(dummy_loc(h));
9451   while ( (q!=null) ) { 
9452     p=q; q=link(q);
9453     r=mp_toss_gr_object(mp, p);
9454     if ( r!=null ) delete_edge_ref(r);
9455   }
9456   mp_free_node(mp, h,edge_header_size);
9457 }
9458 void mp_flush_dash_list (MP mp,pointer h) {
9459   pointer p,q;  /* pointers that scan the list being recycled */
9460   q=dash_list(h);
9461   while ( q!=null_dash ) { 
9462     p=q; q=link(q);
9463     mp_free_node(mp, p,dash_node_size);
9464   }
9465   dash_list(h)=null_dash;
9466 }
9467 pointer mp_toss_gr_object (MP mp,pointer p) {
9468   /* returns an edge structure that needs to be dereferenced */
9469   pointer e; /* the edge structure to return */
9470   e=null;
9471   @<Prepare to recycle graphical object |p|@>;
9472   mp_free_node(mp, p,mp->gr_object_size[type(p)]);
9473   return e;
9474 }
9475
9476 @ @<Prepare to recycle graphical object |p|@>=
9477 switch (type(p)) {
9478 case mp_fill_code: 
9479   mp_toss_knot_list(mp, path_p(p));
9480   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9481   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9482   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9483   break;
9484 case mp_stroked_code: 
9485   mp_toss_knot_list(mp, path_p(p));
9486   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9487   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9488   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9489   e=dash_p(p);
9490   break;
9491 case mp_text_code: 
9492   delete_str_ref(text_p(p));
9493   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9494   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9495   break;
9496 case mp_start_clip_code:
9497 case mp_start_bounds_code: 
9498   mp_toss_knot_list(mp, path_p(p));
9499   break;
9500 case mp_stop_clip_code:
9501 case mp_stop_bounds_code: 
9502   break;
9503 } /* there are no other cases */
9504
9505 @ If we use |add_edge_ref| to ``copy'' edge structures, the real copying needs
9506 to be done before making a significant change to an edge structure.  Much of
9507 the work is done in a separate routine |copy_objects| that copies a list of
9508 graphical objects into a new edge header.
9509
9510 @c @<Declare a function called |copy_objects|@>;
9511 pointer mp_private_edges (MP mp,pointer h) {
9512   /* make a private copy of the edge structure headed by |h| */
9513   pointer hh;  /* the edge header for the new copy */
9514   pointer p,pp;  /* pointers for copying the dash list */
9515   if ( ref_count(h)==null ) {
9516     return h;
9517   } else { 
9518     decr(ref_count(h));
9519     hh=mp_copy_objects(mp, link(dummy_loc(h)),null);
9520     @<Copy the dash list from |h| to |hh|@>;
9521     @<Copy the bounding box information from |h| to |hh| and make |bblast(hh)|
9522       point into the new object list@>;
9523     return hh;
9524   }
9525 }
9526
9527 @ Here we use the fact that |dash_list(hh)=link(hh)|.
9528 @^data structure assumptions@>
9529
9530 @<Copy the dash list from |h| to |hh|@>=
9531 pp=hh; p=dash_list(h);
9532 while ( (p!=null_dash) ) { 
9533   link(pp)=mp_get_node(mp, dash_node_size);
9534   pp=link(pp);
9535   start_x(pp)=start_x(p);
9536   stop_x(pp)=stop_x(p);
9537   p=link(p);
9538 }
9539 link(pp)=null_dash;
9540 dash_y(hh)=dash_y(h)
9541
9542
9543 @ |h| is an edge structure
9544
9545 @d gr_start_x(A)    (A)->start_x_field
9546 @d gr_stop_x(A)     (A)->stop_x_field
9547 @d gr_dash_link(A)  (A)->next_field
9548
9549 @d gr_dash_list(A)  (A)->list_field
9550 @d gr_dash_y(A)     (A)->y_field
9551
9552 @c
9553 struct mp_dash_list *mp_export_dashes (MP mp, pointer h) {
9554   struct mp_dash_list *dl;
9555   struct mp_dash_item *dh, *di;
9556   pointer p;
9557   if (h==null ||  dash_list(h)==null_dash) 
9558         return NULL;
9559   p = dash_list(h);
9560   dl = mp_xmalloc(mp,1,sizeof(struct mp_dash_list));
9561   gr_dash_list(dl) = NULL;
9562   gr_dash_y(dl) = dash_y(h);
9563   dh = NULL;
9564   while (p != null_dash) { 
9565     di=mp_xmalloc(mp,1,sizeof(struct mp_dash_item));
9566     gr_dash_link(di) = NULL;
9567     gr_start_x(di) = start_x(p);
9568     gr_stop_x(di) = stop_x(p);
9569     if (dh==NULL) {
9570       gr_dash_list(dl) = di;
9571     } else {
9572       gr_dash_link(dh) = di;
9573     }
9574     dh = di;
9575     p=link(p);
9576   }
9577   return dl;
9578 }
9579
9580
9581 @ @<Copy the bounding box information from |h| to |hh|...@>=
9582 minx_val(hh)=minx_val(h);
9583 miny_val(hh)=miny_val(h);
9584 maxx_val(hh)=maxx_val(h);
9585 maxy_val(hh)=maxy_val(h);
9586 bbtype(hh)=bbtype(h);
9587 p=dummy_loc(h); pp=dummy_loc(hh);
9588 while ((p!=bblast(h)) ) { 
9589   if ( p==null ) mp_confusion(mp, "bblast");
9590 @:this can't happen bblast}{\quad bblast@>
9591   p=link(p); pp=link(pp);
9592 }
9593 bblast(hh)=pp
9594
9595 @ Here is the promised routine for copying graphical objects into a new edge
9596 structure.  It starts copying at object~|p| and stops just before object~|q|.
9597 If |q| is null, it copies the entire sublist headed at |p|.  The resulting edge
9598 structure requires further initialization by |init_bbox|.
9599
9600 @<Declare a function called |copy_objects|@>=
9601 pointer mp_copy_objects (MP mp, pointer p, pointer q) {
9602   pointer hh;  /* the new edge header */
9603   pointer pp;  /* the last newly copied object */
9604   small_number k;  /* temporary register */
9605   hh=mp_get_node(mp, edge_header_size);
9606   dash_list(hh)=null_dash;
9607   ref_count(hh)=null;
9608   pp=dummy_loc(hh);
9609   while ( (p!=q) ) {
9610     @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>;
9611   }
9612   obj_tail(hh)=pp;
9613   link(pp)=null;
9614   return hh;
9615 }
9616
9617 @ @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>=
9618 { k=mp->gr_object_size[type(p)];
9619   link(pp)=mp_get_node(mp, k);
9620   pp=link(pp);
9621   while ( (k>0) ) { decr(k); mp->mem[pp+k]=mp->mem[p+k];  };
9622   @<Fix anything in graphical object |pp| that should differ from the
9623     corresponding field in |p|@>;
9624   p=link(p);
9625 }
9626
9627 @ @<Fix anything in graphical object |pp| that should differ from the...@>=
9628 switch (type(p)) {
9629 case mp_start_clip_code:
9630 case mp_start_bounds_code: 
9631   path_p(pp)=mp_copy_path(mp, path_p(p));
9632   break;
9633 case mp_fill_code: 
9634   path_p(pp)=mp_copy_path(mp, path_p(p));
9635   if ( pen_p(p)!=null ) pen_p(pp)=copy_pen(pen_p(p));
9636   break;
9637 case mp_stroked_code: 
9638   path_p(pp)=mp_copy_path(mp, path_p(p));
9639   pen_p(pp)=copy_pen(pen_p(p));
9640   if ( dash_p(p)!=null ) add_edge_ref(dash_p(pp));
9641   break;
9642 case mp_text_code: 
9643   add_str_ref(text_p(pp));
9644   break;
9645 case mp_stop_clip_code:
9646 case mp_stop_bounds_code: 
9647   break;
9648 }  /* there are no other cases */
9649
9650 @ Here is one way to find an acceptable value for the second argument to
9651 |copy_objects|.  Given a non-null graphical object list, |skip_1component|
9652 skips past one picture component, where a ``picture component'' is a single
9653 graphical object, or a start bounds or start clip object and everything up
9654 through the matching stop bounds or stop clip object.  The macro version avoids
9655 procedure call overhead and error handling: |skip_component(p)(e)| advances |p|
9656 unless |p| points to a stop bounds or stop clip node, in which case it executes
9657 |e| instead.
9658
9659 @d skip_component(A)
9660     if ( ! is_start_or_stop((A)) ) (A)=link((A));
9661     else if ( ! is_stop((A)) ) (A)=mp_skip_1component(mp, (A));
9662     else 
9663
9664 @c 
9665 pointer mp_skip_1component (MP mp,pointer p) {
9666   integer lev; /* current nesting level */
9667   lev=0;
9668   do {  
9669    if ( is_start_or_stop(p) ) {
9670      if ( is_stop(p) ) decr(lev);  else incr(lev);
9671    }
9672    p=link(p);
9673   } while (lev!=0);
9674   return p;
9675 }
9676
9677 @ Here is a diagnostic routine for printing an edge structure in symbolic form.
9678
9679 @<Declare subroutines for printing expressions@>=
9680 @<Declare subroutines needed by |print_edges|@>;
9681 void mp_print_edges (MP mp,pointer h, char *s, boolean nuline) {
9682   pointer p;  /* a graphical object to be printed */
9683   pointer hh,pp;  /* temporary pointers */
9684   scaled scf;  /* a scale factor for the dash pattern */
9685   boolean ok_to_dash;  /* |false| for polygonal pen strokes */
9686   mp_print_diagnostic(mp, "Edge structure",s,nuline);
9687   p=dummy_loc(h);
9688   while ( link(p)!=null ) { 
9689     p=link(p);
9690     mp_print_ln(mp);
9691     switch (type(p)) {
9692       @<Cases for printing graphical object node |p|@>;
9693     default: 
9694           mp_print(mp, "[unknown object type!]");
9695           break;
9696     }
9697   }
9698   mp_print_nl(mp, "End edges");
9699   if ( p!=obj_tail(h) ) mp_print(mp, "?");
9700 @.End edges?@>
9701   mp_end_diagnostic(mp, true);
9702 }
9703
9704 @ @<Cases for printing graphical object node |p|@>=
9705 case mp_fill_code: 
9706   mp_print(mp, "Filled contour ");
9707   mp_print_obj_color(mp, p);
9708   mp_print_char(mp, ':'); mp_print_ln(mp);
9709   mp_pr_path(mp, path_p(p)); mp_print_ln(mp);
9710   if ( (pen_p(p)!=null) ) {
9711     @<Print join type for graphical object |p|@>;
9712     mp_print(mp, " with pen"); mp_print_ln(mp);
9713     mp_pr_pen(mp, pen_p(p));
9714   }
9715   break;
9716
9717 @ @<Print join type for graphical object |p|@>=
9718 switch (ljoin_val(p)) {
9719 case 0:
9720   mp_print(mp, "mitered joins limited ");
9721   mp_print_scaled(mp, miterlim_val(p));
9722   break;
9723 case 1:
9724   mp_print(mp, "round joins");
9725   break;
9726 case 2:
9727   mp_print(mp, "beveled joins");
9728   break;
9729 default: 
9730   mp_print(mp, "?? joins");
9731 @.??@>
9732   break;
9733 }
9734
9735 @ For stroked nodes, we need to print |lcap_val(p)| as well.
9736
9737 @<Print join and cap types for stroked node |p|@>=
9738 switch (lcap_val(p)) {
9739 case 0:mp_print(mp, "butt"); break;
9740 case 1:mp_print(mp, "round"); break;
9741 case 2:mp_print(mp, "square"); break;
9742 default: mp_print(mp, "??"); break;
9743 @.??@>
9744 }
9745 mp_print(mp, " ends, ");
9746 @<Print join type for graphical object |p|@>
9747
9748 @ Here is a routine that prints the color of a graphical object if it isn't
9749 black (the default color).
9750
9751 @<Declare subroutines needed by |print_edges|@>=
9752 @<Declare a procedure called |print_compact_node|@>;
9753 void mp_print_obj_color (MP mp,pointer p) { 
9754   if ( color_model(p)==mp_grey_model ) {
9755     if ( grey_val(p)>0 ) { 
9756       mp_print(mp, "greyed ");
9757       mp_print_compact_node(mp, obj_grey_loc(p),1);
9758     };
9759   } else if ( color_model(p)==mp_cmyk_model ) {
9760     if ( (cyan_val(p)>0) || (magenta_val(p)>0) || 
9761          (yellow_val(p)>0) || (black_val(p)>0) ) { 
9762       mp_print(mp, "processcolored ");
9763       mp_print_compact_node(mp, obj_cyan_loc(p),4);
9764     };
9765   } else if ( color_model(p)==mp_rgb_model ) {
9766     if ( (red_val(p)>0) || (green_val(p)>0) || (blue_val(p)>0) ) { 
9767       mp_print(mp, "colored "); 
9768       mp_print_compact_node(mp, obj_red_loc(p),3);
9769     };
9770   }
9771 }
9772
9773 @ We also need a procedure for printing consecutive scaled values as if they
9774 were a known big node.
9775
9776 @<Declare a procedure called |print_compact_node|@>=
9777 void mp_print_compact_node (MP mp,pointer p, small_number k) {
9778   pointer q;  /* last location to print */
9779   q=p+k-1;
9780   mp_print_char(mp, '(');
9781   while ( p<=q ){ 
9782     mp_print_scaled(mp, mp->mem[p].sc);
9783     if ( p<q ) mp_print_char(mp, ',');
9784     incr(p);
9785   }
9786   mp_print_char(mp, ')');
9787 }
9788
9789 @ @<Cases for printing graphical object node |p|@>=
9790 case mp_stroked_code: 
9791   mp_print(mp, "Filled pen stroke ");
9792   mp_print_obj_color(mp, p);
9793   mp_print_char(mp, ':'); mp_print_ln(mp);
9794   mp_pr_path(mp, path_p(p));
9795   if ( dash_p(p)!=null ) { 
9796     mp_print_nl(mp, "dashed (");
9797     @<Finish printing the dash pattern that |p| refers to@>;
9798   }
9799   mp_print_ln(mp);
9800   @<Print join and cap types for stroked node |p|@>;
9801   mp_print(mp, " with pen"); mp_print_ln(mp);
9802   if ( pen_p(p)==null ) mp_print(mp, "???"); /* shouldn't happen */
9803 @.???@>
9804   else mp_pr_pen(mp, pen_p(p));
9805   break;
9806
9807 @ Normally, the  |dash_list| field in an edge header is set to |null_dash|
9808 when it is not known to define a suitable dash pattern.  This is disallowed
9809 here because the |dash_p| field should never point to such an edge header.
9810 Note that memory is allocated for |start_x(null_dash)| and we are free to
9811 give it any convenient value.
9812
9813 @<Finish printing the dash pattern that |p| refers to@>=
9814 ok_to_dash=pen_is_elliptical(pen_p(p));
9815 if ( ! ok_to_dash ) scf=unity; else scf=dash_scale(p);
9816 hh=dash_p(p);
9817 pp=dash_list(hh);
9818 if ( (pp==null_dash) || (dash_y(hh)<0) ) {
9819   mp_print(mp, " ??");
9820 } else { start_x(null_dash)=start_x(pp)+dash_y(hh);
9821   while ( pp!=null_dash ) { 
9822     mp_print(mp, "on ");
9823     mp_print_scaled(mp, mp_take_scaled(mp, stop_x(pp)-start_x(pp),scf));
9824     mp_print(mp, " off ");
9825     mp_print_scaled(mp, mp_take_scaled(mp, start_x(link(pp))-stop_x(pp),scf));
9826     pp = link(pp);
9827     if ( pp!=null_dash ) mp_print_char(mp, ' ');
9828   }
9829   mp_print(mp, ") shifted ");
9830   mp_print_scaled(mp, -mp_take_scaled(mp, mp_dash_offset(mp, hh),scf));
9831   if ( ! ok_to_dash || (dash_y(hh)==0) ) mp_print(mp, " (this will be ignored)");
9832 }
9833
9834 @ @<Declare subroutines needed by |print_edges|@>=
9835 scaled mp_dash_offset (MP mp,pointer h) {
9836   scaled x;  /* the answer */
9837   if (dash_list(h)==null_dash || dash_y(h)<0) mp_confusion(mp, "dash0");
9838 @:this can't happen dash0}{\quad dash0@>
9839   if ( dash_y(h)==0 ) {
9840     x=0; 
9841   } else { 
9842     x=-(start_x(dash_list(h)) % dash_y(h));
9843     if ( x<0 ) x=x+dash_y(h);
9844   }
9845   return x;
9846 }
9847
9848 @ @<Cases for printing graphical object node |p|@>=
9849 case mp_text_code: 
9850   mp_print_char(mp, '"'); mp_print_str(mp,text_p(p));
9851   mp_print(mp, "\" infont \""); mp_print(mp, mp->font_name[font_n(p)]);
9852   mp_print_char(mp, '"'); mp_print_ln(mp);
9853   mp_print_obj_color(mp, p);
9854   mp_print(mp, "transformed ");
9855   mp_print_compact_node(mp, text_tx_loc(p),6);
9856   break;
9857
9858 @ @<Cases for printing graphical object node |p|@>=
9859 case mp_start_clip_code: 
9860   mp_print(mp, "clipping path:");
9861   mp_print_ln(mp);
9862   mp_pr_path(mp, path_p(p));
9863   break;
9864 case mp_stop_clip_code: 
9865   mp_print(mp, "stop clipping");
9866   break;
9867
9868 @ @<Cases for printing graphical object node |p|@>=
9869 case mp_start_bounds_code: 
9870   mp_print(mp, "setbounds path:");
9871   mp_print_ln(mp);
9872   mp_pr_path(mp, path_p(p));
9873   break;
9874 case mp_stop_bounds_code: 
9875   mp_print(mp, "end of setbounds");
9876   break;
9877
9878 @ To initialize the |dash_list| field in an edge header~|h|, we need a
9879 subroutine that scans an edge structure and tries to interpret it as a dash
9880 pattern.  This can only be done when there are no filled regions or clipping
9881 paths and all the pen strokes have the same color.  The first step is to let
9882 $y_0$ be the initial $y$~coordinate of the first pen stroke.  Then we implicitly
9883 project all the pen stroke paths onto the line $y=y_0$ and require that there
9884 be no retracing.  If the resulting paths cover a range of $x$~coordinates of
9885 length $\Delta x$, we set |dash_y(h)| to the length of the dash pattern by
9886 finding the maximum of $\Delta x$ and the absolute value of~$y_0$.
9887
9888 @c @<Declare a procedure called |x_retrace_error|@>;
9889 pointer mp_make_dashes (MP mp,pointer h) { /* returns |h| or |null| */
9890   pointer p;  /* this scans the stroked nodes in the object list */
9891   pointer p0;  /* if not |null| this points to the first stroked node */
9892   pointer pp,qq,rr;  /* pointers into |path_p(p)| */
9893   pointer d,dd;  /* pointers used to create the dash list */
9894   @<Other local variables in |make_dashes|@>;
9895   scaled y0=0;  /* the initial $y$ coordinate */
9896   if ( dash_list(h)!=null_dash ) 
9897         return h;
9898   p0=null;
9899   p=link(dummy_loc(h));
9900   while ( p!=null ) { 
9901     if ( type(p)!=mp_stroked_code ) {
9902       @<Compain that the edge structure contains a node of the wrong type
9903         and |goto not_found|@>;
9904     }
9905     pp=path_p(p);
9906     if ( p0==null ){ p0=p; y0=y_coord(pp);  };
9907     @<Make |d| point to a new dash node created from stroke |p| and path |pp|
9908       or |goto not_found| if there is an error@>;
9909     @<Insert |d| into the dash list and |goto not_found| if there is an error@>;
9910     p=link(p);
9911   }
9912   if ( dash_list(h)==null_dash ) 
9913     goto NOT_FOUND; /* No error message */
9914   @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>;
9915   @<Set |dash_y(h)| and merge the first and last dashes if necessary@>;
9916   return h;
9917 NOT_FOUND: 
9918   @<Flush the dash list, recycle |h| and return |null|@>;
9919 };
9920
9921 @ @<Compain that the edge structure contains a node of the wrong type...@>=
9922
9923 print_err("Picture is too complicated to use as a dash pattern");
9924 help3("When you say `dashed p', picture p should not contain any")
9925   ("text, filled regions, or clipping paths.  This time it did")
9926   ("so I'll just make it a solid line instead.");
9927 mp_put_get_error(mp);
9928 goto NOT_FOUND;
9929 }
9930
9931 @ A similar error occurs when monotonicity fails.
9932
9933 @<Declare a procedure called |x_retrace_error|@>=
9934 void mp_x_retrace_error (MP mp) { 
9935 print_err("Picture is too complicated to use as a dash pattern");
9936 help3("When you say `dashed p', every path in p should be monotone")
9937   ("in x and there must be no overlapping.  This failed")
9938   ("so I'll just make it a solid line instead.");
9939 mp_put_get_error(mp);
9940 }
9941
9942 @ We stash |p| in |info(d)| if |dash_p(p)<>0| so that subsequent processing can
9943 handle the case where the pen stroke |p| is itself dashed.
9944
9945 @<Make |d| point to a new dash node created from stroke |p| and path...@>=
9946 @<Make sure |p| and |p0| are the same color and |goto not_found| if there is
9947   an error@>;
9948 rr=pp;
9949 if ( link(pp)!=pp ) {
9950   do {  
9951     qq=rr; rr=link(rr);
9952     @<Check for retracing between knots |qq| and |rr| and |goto not_found|
9953       if there is a problem@>;
9954   } while (right_type(rr)!=mp_endpoint);
9955 }
9956 d=mp_get_node(mp, dash_node_size);
9957 if ( dash_p(p)==0 ) info(d)=0;  else info(d)=p;
9958 if ( x_coord(pp)<x_coord(rr) ) { 
9959   start_x(d)=x_coord(pp);
9960   stop_x(d)=x_coord(rr);
9961 } else { 
9962   start_x(d)=x_coord(rr);
9963   stop_x(d)=x_coord(pp);
9964 }
9965
9966 @ We also need to check for the case where the segment from |qq| to |rr| is
9967 monotone in $x$ but is reversed relative to the path from |pp| to |qq|.
9968
9969 @<Check for retracing between knots |qq| and |rr| and |goto not_found|...@>=
9970 x0=x_coord(qq);
9971 x1=right_x(qq);
9972 x2=left_x(rr);
9973 x3=x_coord(rr);
9974 if ( (x0>x1) || (x1>x2) || (x2>x3) ) {
9975   if ( (x0<x1) || (x1<x2) || (x2<x3) ) {
9976     if ( mp_ab_vs_cd(mp, x2-x1,x2-x1,x1-x0,x3-x2)>0 ) {
9977       mp_x_retrace_error(mp); goto NOT_FOUND;
9978     }
9979   }
9980 }
9981 if ( (x_coord(pp)>x0) || (x0>x3) ) {
9982   if ( (x_coord(pp)<x0) || (x0<x3) ) {
9983     mp_x_retrace_error(mp); goto NOT_FOUND;
9984   }
9985 }
9986
9987 @ @<Other local variables in |make_dashes|@>=
9988   scaled x0,x1,x2,x3;  /* $x$ coordinates of the segment from |qq| to |rr| */
9989
9990 @ @<Make sure |p| and |p0| are the same color and |goto not_found|...@>=
9991 if ( (red_val(p)!=red_val(p0)) || (black_val(p)!=black_val(p0)) ||
9992   (green_val(p)!=green_val(p0)) || (blue_val(p)!=blue_val(p0)) ) {
9993   print_err("Picture is too complicated to use as a dash pattern");
9994   help3("When you say `dashed p', everything in picture p should")
9995     ("be the same color.  I can\'t handle your color changes")
9996     ("so I'll just make it a solid line instead.");
9997   mp_put_get_error(mp);
9998   goto NOT_FOUND;
9999 }
10000
10001 @ @<Insert |d| into the dash list and |goto not_found| if there is an error@>=
10002 start_x(null_dash)=stop_x(d);
10003 dd=h; /* this makes |link(dd)=dash_list(h)| */
10004 while ( start_x(link(dd))<stop_x(d) )
10005   dd=link(dd);
10006 if ( dd!=h ) {
10007   if ( (stop_x(dd)>start_x(d)) )
10008     { mp_x_retrace_error(mp); goto NOT_FOUND;  };
10009 }
10010 link(d)=link(dd);
10011 link(dd)=d
10012
10013 @ @<Set |dash_y(h)| and merge the first and last dashes if necessary@>=
10014 d=dash_list(h);
10015 while ( (link(d)!=null_dash) )
10016   d=link(d);
10017 dd=dash_list(h);
10018 dash_y(h)=stop_x(d)-start_x(dd);
10019 if ( abs(y0)>dash_y(h) ) {
10020   dash_y(h)=abs(y0);
10021 } else if ( d!=dd ) { 
10022   dash_list(h)=link(dd);
10023   stop_x(d)=stop_x(dd)+dash_y(h);
10024   mp_free_node(mp, dd,dash_node_size);
10025 }
10026
10027 @ We get here when the argument is a null picture or when there is an error.
10028 Recovering from an error involves making |dash_list(h)| empty to indicate
10029 that |h| is not known to be a valid dash pattern.  We also dereference |h|
10030 since it is not being used for the return value.
10031
10032 @<Flush the dash list, recycle |h| and return |null|@>=
10033 mp_flush_dash_list(mp, h);
10034 delete_edge_ref(h);
10035 return null
10036
10037 @ Having carefully saved the dashed stroked nodes in the
10038 corresponding dash nodes, we must be prepared to break up these dashes into
10039 smaller dashes.
10040
10041 @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>=
10042 d=h;  /* now |link(d)=dash_list(h)| */
10043 while ( link(d)!=null_dash ) {
10044   ds=info(link(d));
10045   if ( ds==null ) { 
10046     d=link(d);
10047   } else {
10048     hh=dash_p(ds);
10049     hsf=dash_scale(ds);
10050     if ( (hh==null) ) mp_confusion(mp, "dash1");
10051 @:this can't happen dash0}{\quad dash1@>
10052     if ( dash_y(hh)==0 ) {
10053       d=link(d);
10054     } else { 
10055       if ( dash_list(hh)==null ) mp_confusion(mp, "dash1");
10056 @:this can't happen dash0}{\quad dash1@>
10057       @<Replace |link(d)| by a dashed version as determined by edge header
10058           |hh| and scale factor |ds|@>;
10059     }
10060   }
10061 }
10062
10063 @ @<Other local variables in |make_dashes|@>=
10064 pointer dln;  /* |link(d)| */
10065 pointer hh;  /* an edge header that tells how to break up |dln| */
10066 scaled hsf;  /* the dash pattern from |hh| gets scaled by this */
10067 pointer ds;  /* the stroked node from which |hh| and |hsf| are derived */
10068 scaled xoff;  /* added to $x$ values in |dash_list(hh)| to match |dln| */
10069
10070 @ @<Replace |link(d)| by a dashed version as determined by edge header...@>=
10071 dln=link(d);
10072 dd=dash_list(hh);
10073 xoff=start_x(dln)-mp_take_scaled(mp, hsf,start_x(dd))-
10074         mp_take_scaled(mp, hsf,mp_dash_offset(mp, hh));
10075 start_x(null_dash)=mp_take_scaled(mp, hsf,start_x(dd))
10076                    +mp_take_scaled(mp, hsf,dash_y(hh));
10077 stop_x(null_dash)=start_x(null_dash);
10078 @<Advance |dd| until finding the first dash that overlaps |dln| when
10079   offset by |xoff|@>;
10080 while ( start_x(dln)<=stop_x(dln) ) {
10081   @<If |dd| has `fallen off the end', back up to the beginning and fix |xoff|@>;
10082   @<Insert a dash between |d| and |dln| for the overlap with the offset version
10083     of |dd|@>;
10084   dd=link(dd);
10085   start_x(dln)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10086 }
10087 link(d)=link(dln);
10088 mp_free_node(mp, dln,dash_node_size)
10089
10090 @ The name of this module is a bit of a lie because we actually just find the
10091 first |dd| where |take_scaled (hsf, stop_x(dd))| is large enough to make an
10092 overlap possible.  It could be that the unoffset version of dash |dln| falls
10093 in the gap between |dd| and its predecessor.
10094
10095 @<Advance |dd| until finding the first dash that overlaps |dln| when...@>=
10096 while ( xoff+mp_take_scaled(mp, hsf,stop_x(dd))<start_x(dln) ) {
10097   dd=link(dd);
10098 }
10099
10100 @ @<If |dd| has `fallen off the end', back up to the beginning and fix...@>=
10101 if ( dd==null_dash ) { 
10102   dd=dash_list(hh);
10103   xoff=xoff+mp_take_scaled(mp, hsf,dash_y(hh));
10104 }
10105
10106 @ At this point we already know that
10107 |start_x(dln)<=xoff+take_scaled(hsf,stop_x(dd))|.
10108
10109 @<Insert a dash between |d| and |dln| for the overlap with the offset...@>=
10110 if ( (xoff+mp_take_scaled(mp, hsf,start_x(dd)))<=stop_x(dln) ) {
10111   link(d)=mp_get_node(mp, dash_node_size);
10112   d=link(d);
10113   link(d)=dln;
10114   if ( start_x(dln)>(xoff+mp_take_scaled(mp, hsf,start_x(dd))))
10115     start_x(d)=start_x(dln);
10116   else 
10117     start_x(d)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10118   if ( stop_x(dln)<(xoff+mp_take_scaled(mp, hsf,stop_x(dd)))) 
10119     stop_x(d)=stop_x(dln);
10120   else 
10121     stop_x(d)=xoff+mp_take_scaled(mp, hsf,stop_x(dd));
10122 }
10123
10124 @ The next major task is to update the bounding box information in an edge
10125 header~|h|. This is done via a procedure |adjust_bbox| that enlarges an edge
10126 header's bounding box to accommodate the box computed by |path_bbox| or
10127 |pen_bbox|. (This is stored in global variables |minx|, |miny|, |maxx|, and
10128 |maxy|.)
10129
10130 @c void mp_adjust_bbox (MP mp,pointer h) { 
10131   if ( minx<minx_val(h) ) minx_val(h)=minx;
10132   if ( miny<miny_val(h) ) miny_val(h)=miny;
10133   if ( maxx>maxx_val(h) ) maxx_val(h)=maxx;
10134   if ( maxy>maxy_val(h) ) maxy_val(h)=maxy;
10135 }
10136
10137 @ Here is a special routine for updating the bounding box information in
10138 edge header~|h| to account for the squared-off ends of a non-cyclic path~|p|
10139 that is to be stroked with the pen~|pp|.
10140
10141 @c void mp_box_ends (MP mp, pointer p, pointer pp, pointer h) {
10142   pointer q;  /* a knot node adjacent to knot |p| */
10143   fraction dx,dy;  /* a unit vector in the direction out of the path at~|p| */
10144   scaled d;  /* a factor for adjusting the length of |(dx,dy)| */
10145   scaled z;  /* a coordinate being tested against the bounding box */
10146   scaled xx,yy;  /* the extreme pen vertex in the |(dx,dy)| direction */
10147   integer i; /* a loop counter */
10148   if ( right_type(p)!=mp_endpoint ) { 
10149     q=link(p);
10150     while (1) { 
10151       @<Make |(dx,dy)| the final direction for the path segment from
10152         |q| to~|p|; set~|d|@>;
10153       d=mp_pyth_add(mp, dx,dy);
10154       if ( d>0 ) { 
10155          @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>;
10156          for (i=1;i<= 2;i++) { 
10157            @<Use |(dx,dy)| to generate a vertex of the square end cap and
10158              update the bounding box to accommodate it@>;
10159            dx=-dx; dy=-dy; 
10160         }
10161       }
10162       if ( right_type(p)==mp_endpoint ) {
10163          return;
10164       } else {
10165         @<Advance |p| to the end of the path and make |q| the previous knot@>;
10166       } 
10167     }
10168   }
10169 }
10170
10171 @ @<Make |(dx,dy)| the final direction for the path segment from...@>=
10172 if ( q==link(p) ) { 
10173   dx=x_coord(p)-right_x(p);
10174   dy=y_coord(p)-right_y(p);
10175   if ( (dx==0)&&(dy==0) ) {
10176     dx=x_coord(p)-left_x(q);
10177     dy=y_coord(p)-left_y(q);
10178   }
10179 } else { 
10180   dx=x_coord(p)-left_x(p);
10181   dy=y_coord(p)-left_y(p);
10182   if ( (dx==0)&&(dy==0) ) {
10183     dx=x_coord(p)-right_x(q);
10184     dy=y_coord(p)-right_y(q);
10185   }
10186 }
10187 dx=x_coord(p)-x_coord(q);
10188 dy=y_coord(p)-y_coord(q)
10189
10190 @ @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>=
10191 dx=mp_make_fraction(mp, dx,d);
10192 dy=mp_make_fraction(mp, dy,d);
10193 mp_find_offset(mp, -dy,dx,pp);
10194 xx=mp->cur_x; yy=mp->cur_y
10195
10196 @ @<Use |(dx,dy)| to generate a vertex of the square end cap and...@>=
10197 mp_find_offset(mp, dx,dy,pp);
10198 d=mp_take_fraction(mp, xx-mp->cur_x,dx)+mp_take_fraction(mp, yy-mp->cur_y,dy);
10199 if ( ((d<0)&&(i==1)) || ((d>0)&&(i==2))) 
10200   mp_confusion(mp, "box_ends");
10201 @:this can't happen box ends}{\quad\\{box\_ends}@>
10202 z=x_coord(p)+mp->cur_x+mp_take_fraction(mp, d,dx);
10203 if ( z<minx_val(h) ) minx_val(h)=z;
10204 if ( z>maxx_val(h) ) maxx_val(h)=z;
10205 z=y_coord(p)+mp->cur_y+mp_take_fraction(mp, d,dy);
10206 if ( z<miny_val(h) ) miny_val(h)=z;
10207 if ( z>maxy_val(h) ) maxy_val(h)=z
10208
10209 @ @<Advance |p| to the end of the path and make |q| the previous knot@>=
10210 do {  
10211   q=p;
10212   p=link(p);
10213 } while (right_type(p)!=mp_endpoint)
10214
10215 @ The major difficulty in finding the bounding box of an edge structure is the
10216 effect of clipping paths.  We treat them conservatively by only clipping to the
10217 clipping path's bounding box, but this still
10218 requires recursive calls to |set_bbox| in order to find the bounding box of
10219 @^recursion@>
10220 the objects to be clipped.  Such calls are distinguished by the fact that the
10221 boolean parameter |top_level| is false.
10222
10223 @c void mp_set_bbox (MP mp,pointer h, boolean top_level) {
10224   pointer p;  /* a graphical object being considered */
10225   scaled sminx,sminy,smaxx,smaxy;
10226   /* for saving the bounding box during recursive calls */
10227   scaled x0,x1,y0,y1;  /* temporary registers */
10228   integer lev;  /* nesting level for |mp_start_bounds_code| nodes */
10229   @<Wipe out any existing bounding box information if |bbtype(h)| is
10230   incompatible with |internal[mp_true_corners]|@>;
10231   while ( link(bblast(h))!=null ) { 
10232     p=link(bblast(h));
10233     bblast(h)=p;
10234     switch (type(p)) {
10235     case mp_stop_clip_code: 
10236       if ( top_level ) mp_confusion(mp, "bbox");  else return;
10237 @:this can't happen bbox}{\quad bbox@>
10238       break;
10239     @<Other cases for updating the bounding box based on the type of object |p|@>;
10240     } /* all cases are enumerated above */
10241   }
10242   if ( ! top_level ) mp_confusion(mp, "bbox");
10243 }
10244
10245 @ @<Internal library declarations@>=
10246 void mp_set_bbox (MP mp,pointer h, boolean top_level);
10247
10248 @ @<Wipe out any existing bounding box information if |bbtype(h)| is...@>=
10249 switch (bbtype(h)) {
10250 case no_bounds: 
10251   break;
10252 case bounds_set: 
10253   if ( mp->internal[mp_true_corners]>0 ) mp_init_bbox(mp, h);
10254   break;
10255 case bounds_unset: 
10256   if ( mp->internal[mp_true_corners]<=0 ) mp_init_bbox(mp, h);
10257   break;
10258 } /* there are no other cases */
10259
10260 @ @<Other cases for updating the bounding box...@>=
10261 case mp_fill_code: 
10262   mp_path_bbox(mp, path_p(p));
10263   if ( pen_p(p)!=null ) { 
10264     x0=minx; y0=miny;
10265     x1=maxx; y1=maxy;
10266     mp_pen_bbox(mp, pen_p(p));
10267     minx=minx+x0;
10268     miny=miny+y0;
10269     maxx=maxx+x1;
10270     maxy=maxy+y1;
10271   }
10272   mp_adjust_bbox(mp, h);
10273   break;
10274
10275 @ @<Other cases for updating the bounding box...@>=
10276 case mp_start_bounds_code: 
10277   if ( mp->internal[mp_true_corners]>0 ) {
10278     bbtype(h)=bounds_unset;
10279   } else { 
10280     bbtype(h)=bounds_set;
10281     mp_path_bbox(mp, path_p(p));
10282     mp_adjust_bbox(mp, h);
10283     @<Scan to the matching |mp_stop_bounds_code| node and update |p| and
10284       |bblast(h)|@>;
10285   }
10286   break;
10287 case mp_stop_bounds_code: 
10288   if ( mp->internal[mp_true_corners]<=0 ) mp_confusion(mp, "bbox2");
10289 @:this can't happen bbox2}{\quad bbox2@>
10290   break;
10291
10292 @ @<Scan to the matching |mp_stop_bounds_code| node and update |p| and...@>=
10293 lev=1;
10294 while ( lev!=0 ) { 
10295   if ( link(p)==null ) mp_confusion(mp, "bbox2");
10296 @:this can't happen bbox2}{\quad bbox2@>
10297   p=link(p);
10298   if ( type(p)==mp_start_bounds_code ) incr(lev);
10299   else if ( type(p)==mp_stop_bounds_code ) decr(lev);
10300 }
10301 bblast(h)=p
10302
10303 @ It saves a lot of grief here to be slightly conservative and not account for
10304 omitted parts of dashed lines.  We also don't worry about the material omitted
10305 when using butt end caps.  The basic computation is for round end caps and
10306 |box_ends| augments it for square end caps.
10307
10308 @<Other cases for updating the bounding box...@>=
10309 case mp_stroked_code: 
10310   mp_path_bbox(mp, path_p(p));
10311   x0=minx; y0=miny;
10312   x1=maxx; y1=maxy;
10313   mp_pen_bbox(mp, pen_p(p));
10314   minx=minx+x0;
10315   miny=miny+y0;
10316   maxx=maxx+x1;
10317   maxy=maxy+y1;
10318   mp_adjust_bbox(mp, h);
10319   if ( (left_type(path_p(p))==mp_endpoint)&&(lcap_val(p)==2) )
10320     mp_box_ends(mp, path_p(p), pen_p(p), h);
10321   break;
10322
10323 @ The height width and depth information stored in a text node determines a
10324 rectangle that needs to be transformed according to the transformation
10325 parameters stored in the text node.
10326
10327 @<Other cases for updating the bounding box...@>=
10328 case mp_text_code: 
10329   x1=mp_take_scaled(mp, txx_val(p),width_val(p));
10330   y0=mp_take_scaled(mp, txy_val(p),-depth_val(p));
10331   y1=mp_take_scaled(mp, txy_val(p),height_val(p));
10332   minx=tx_val(p);
10333   maxx=minx;
10334   if ( y0<y1 ) { minx=minx+y0; maxx=maxx+y1;  }
10335   else         { minx=minx+y1; maxx=maxx+y0;  }
10336   if ( x1<0 ) minx=minx+x1;  else maxx=maxx+x1;
10337   x1=mp_take_scaled(mp, tyx_val(p),width_val(p));
10338   y0=mp_take_scaled(mp, tyy_val(p),-depth_val(p));
10339   y1=mp_take_scaled(mp, tyy_val(p),height_val(p));
10340   miny=ty_val(p);
10341   maxy=miny;
10342   if ( y0<y1 ) { miny=miny+y0; maxy=maxy+y1;  }
10343   else         { miny=miny+y1; maxy=maxy+y0;  }
10344   if ( x1<0 ) miny=miny+x1;  else maxy=maxy+x1;
10345   mp_adjust_bbox(mp, h);
10346   break;
10347
10348 @ This case involves a recursive call that advances |bblast(h)| to the node of
10349 type |mp_stop_clip_code| that matches |p|.
10350
10351 @<Other cases for updating the bounding box...@>=
10352 case mp_start_clip_code: 
10353   mp_path_bbox(mp, path_p(p));
10354   x0=minx; y0=miny;
10355   x1=maxx; y1=maxy;
10356   sminx=minx_val(h); sminy=miny_val(h);
10357   smaxx=maxx_val(h); smaxy=maxy_val(h);
10358   @<Reinitialize the bounding box in header |h| and call |set_bbox| recursively
10359     starting at |link(p)|@>;
10360   @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,
10361     |y0|, |y1|@>;
10362   minx=sminx; miny=sminy;
10363   maxx=smaxx; maxy=smaxy;
10364   mp_adjust_bbox(mp, h);
10365   break;
10366
10367 @ @<Reinitialize the bounding box in header |h| and call |set_bbox|...@>=
10368 minx_val(h)=el_gordo;
10369 miny_val(h)=el_gordo;
10370 maxx_val(h)=-el_gordo;
10371 maxy_val(h)=-el_gordo;
10372 mp_set_bbox(mp, h,false)
10373
10374 @ @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,...@>=
10375 if ( minx_val(h)<x0 ) minx_val(h)=x0;
10376 if ( miny_val(h)<y0 ) miny_val(h)=y0;
10377 if ( maxx_val(h)>x1 ) maxx_val(h)=x1;
10378 if ( maxy_val(h)>y1 ) maxy_val(h)=y1
10379
10380 @* \[22] Finding an envelope.
10381 When \MP\ has a path and a polygonal pen, it needs to express the desired
10382 shape in terms of things \ps\ can understand.  The present task is to compute
10383 a new path that describes the region to be filled.  It is convenient to
10384 define this as a two step process where the first step is determining what
10385 offset to use for each segment of the path.
10386
10387 @ Given a pointer |c| to a cyclic path,
10388 and a pointer~|h| to the first knot of a pen polygon,
10389 the |offset_prep| routine changes the path into cubics that are
10390 associated with particular pen offsets. Thus if the cubic between |p|
10391 and~|q| is associated with the |k|th offset and the cubic between |q| and~|r|
10392 has offset |l| then |info(q)=zero_off+l-k|. (The constant |zero_off| is added
10393 to because |l-k| could be negative.)
10394
10395 After overwriting the type information with offset differences, we no longer
10396 have a true path so we refer to the knot list returned by |offset_prep| as an
10397 ``envelope spec.''
10398 @^envelope spec@>
10399 Since an envelope spec only determines relative changes in pen offsets,
10400 |offset_prep| sets a global variable |spec_offset| to the relative change from
10401 |h| to the first offset.
10402
10403 @d zero_off 16384 /* added to offset changes to make them positive */
10404
10405 @<Glob...@>=
10406 integer spec_offset; /* number of pen edges between |h| and the initial offset */
10407
10408 @ @c @<Declare subroutines needed by |offset_prep|@>;
10409 pointer mp_offset_prep (MP mp,pointer c, pointer h) {
10410   halfword n; /* the number of vertices in the pen polygon */
10411   pointer p,q,q0,r,w, ww; /* for list manipulation */
10412   integer k_needed; /* amount to be added to |info(p)| when it is computed */
10413   pointer w0; /* a pointer to pen offset to use just before |p| */
10414   scaled dxin,dyin; /* the direction into knot |p| */
10415   integer turn_amt; /* change in pen offsets for the current cubic */
10416   @<Other local variables for |offset_prep|@>;
10417   dx0=0; dy0=0;
10418   @<Initialize the pen size~|n|@>;
10419   @<Initialize the incoming direction and pen offset at |c|@>;
10420   p=c; k_needed=0;
10421   do {  
10422     q=link(p);
10423     @<Split the cubic between |p| and |q|, if necessary, into cubics
10424       associated with single offsets, after which |q| should
10425       point to the end of the final such cubic@>;
10426   NOT_FOUND:
10427     @<Advance |p| to node |q|, removing any ``dead'' cubics that
10428       might have been introduced by the splitting process@>;
10429   } while (q!=c);
10430   @<Fix the offset change in |info(c)| and set |c| to the return value of
10431     |offset_prep|@>;
10432   return c;
10433 }
10434
10435 @ We shall want to keep track of where certain knots on the cyclic path
10436 wind up in the envelope spec.  It doesn't suffice just to keep pointers to
10437 knot nodes because some nodes are deleted while removing dead cubics.  Thus
10438 |offset_prep| updates the following pointers
10439
10440 @<Glob...@>=
10441 pointer spec_p1;
10442 pointer spec_p2; /* pointers to distinguished knots */
10443
10444 @ @<Set init...@>=
10445 mp->spec_p1=null; mp->spec_p2=null;
10446
10447 @ @<Initialize the pen size~|n|@>=
10448 n=0; p=h;
10449 do {  
10450   incr(n);
10451   p=link(p);
10452 } while (p!=h)
10453
10454 @ Since the true incoming direction isn't known yet, we just pick a direction
10455 consistent with the pen offset~|h|.  If this is wrong, it can be corrected
10456 later.
10457
10458 @<Initialize the incoming direction and pen offset at |c|@>=
10459 dxin=x_coord(link(h))-x_coord(knil(h));
10460 dyin=y_coord(link(h))-y_coord(knil(h));
10461 if ( (dxin==0)&&(dyin==0) ) {
10462   dxin=y_coord(knil(h))-y_coord(h);
10463   dyin=x_coord(h)-x_coord(knil(h));
10464 }
10465 w0=h
10466
10467 @ We must be careful not to remove the only cubic in a cycle.
10468
10469 But we must also be careful for another reason. If the user-supplied
10470 path starts with a set of degenerate cubics, the target node |q| can
10471 be collapsed to the initial node |p| which might be the same as the
10472 initial node |c| of the curve. This would cause the |offset_prep| routine
10473 to bail out too early, causing distress later on. (See for example
10474 the testcase reported by Bogus\l{}aw Jackowski in tracker id 267, case 52c
10475 on Sarovar.)
10476
10477 @<Advance |p| to node |q|, removing any ``dead'' cubics...@>=
10478 q0=q;
10479 do { 
10480   r=link(p);
10481   if ( x_coord(p)==right_x(p) && y_coord(p)==right_y(p) &&
10482        x_coord(p)==left_x(r)  && y_coord(p)==left_y(r) &&
10483        x_coord(p)==x_coord(r) && y_coord(p)==y_coord(r) &&
10484        r!=p ) {
10485       @<Remove the cubic following |p| and update the data structures
10486         to merge |r| into |p|@>;
10487   }
10488   p=r;
10489 } while (p!=q);
10490 /* Check if we removed too much */
10491 if(q!=q0)
10492   q = link(q)
10493
10494 @ @<Remove the cubic following |p| and update the data structures...@>=
10495 { k_needed=info(p)-zero_off;
10496   if ( r==q ) { 
10497     q=p;
10498   } else { 
10499     info(p)=k_needed+info(r);
10500     k_needed=0;
10501   };
10502   if ( r==c ) { info(p)=info(c); c=p; };
10503   if ( r==mp->spec_p1 ) mp->spec_p1=p;
10504   if ( r==mp->spec_p2 ) mp->spec_p2=p;
10505   r=p; mp_remove_cubic(mp, p);
10506 }
10507
10508 @ Not setting the |info| field of the newly created knot allows the splitting
10509 routine to work for paths.
10510
10511 @<Declare subroutines needed by |offset_prep|@>=
10512 void mp_split_cubic (MP mp,pointer p, fraction t) { /* splits the cubic after |p| */
10513   scaled v; /* an intermediate value */
10514   pointer q,r; /* for list manipulation */
10515   q=link(p); r=mp_get_node(mp, knot_node_size); link(p)=r; link(r)=q;
10516   originator(r)=mp_program_code;
10517   left_type(r)=mp_explicit; right_type(r)=mp_explicit;
10518   v=t_of_the_way(right_x(p),left_x(q));
10519   right_x(p)=t_of_the_way(x_coord(p),right_x(p));
10520   left_x(q)=t_of_the_way(left_x(q),x_coord(q));
10521   left_x(r)=t_of_the_way(right_x(p),v);
10522   right_x(r)=t_of_the_way(v,left_x(q));
10523   x_coord(r)=t_of_the_way(left_x(r),right_x(r));
10524   v=t_of_the_way(right_y(p),left_y(q));
10525   right_y(p)=t_of_the_way(y_coord(p),right_y(p));
10526   left_y(q)=t_of_the_way(left_y(q),y_coord(q));
10527   left_y(r)=t_of_the_way(right_y(p),v);
10528   right_y(r)=t_of_the_way(v,left_y(q));
10529   y_coord(r)=t_of_the_way(left_y(r),right_y(r));
10530 }
10531
10532 @ This does not set |info(p)| or |right_type(p)|.
10533
10534 @<Declare subroutines needed by |offset_prep|@>=
10535 void mp_remove_cubic (MP mp,pointer p) { /* removes the dead cubic following~|p| */
10536   pointer q; /* the node that disappears */
10537   q=link(p); link(p)=link(q);
10538   right_x(p)=right_x(q); right_y(p)=right_y(q);
10539   mp_free_node(mp, q,knot_node_size);
10540 }
10541
10542 @ Let $d\prec d'$ mean that the counter-clockwise angle from $d$ to~$d'$ is
10543 strictly between zero and $180^\circ$.  Then we can define $d\preceq d'$ to
10544 mean that the angle could be zero or $180^\circ$. If $w_k=(u_k,v_k)$ is the
10545 $k$th pen offset, the $k$th pen edge direction is defined by the formula
10546 $$d_k=(u\k-u_k,\,v\k-v_k).$$
10547 When listed by increasing $k$, these directions occur in counter-clockwise
10548 order so that $d_k\preceq d\k$ for all~$k$.
10549 The goal of |offset_prep| is to find an offset index~|k| to associate with
10550 each cubic, such that the direction $d(t)$ of the cubic satisfies
10551 $$d_{k-1}\preceq d(t)\preceq d_k\qquad\hbox{for $0\le t\le 1$.}\eqno(*)$$
10552 We may have to split a cubic into many pieces before each
10553 piece corresponds to a unique offset.
10554
10555 @<Split the cubic between |p| and |q|, if necessary, into cubics...@>=
10556 info(p)=zero_off+k_needed;
10557 k_needed=0;
10558 @<Prepare for derivative computations;
10559   |goto not_found| if the current cubic is dead@>;
10560 @<Find the initial direction |(dx,dy)|@>;
10561 @<Update |info(p)| and find the offset $w_k$ such that
10562   $d_{k-1}\preceq(\\{dx},\\{dy})\prec d_k$; also advance |w0| for
10563   the direction change at |p|@>;
10564 @<Find the final direction |(dxin,dyin)|@>;
10565 @<Decide on the net change in pen offsets and set |turn_amt|@>;
10566 @<Complete the offset splitting process@>;
10567 w0=mp_pen_walk(mp, w0,turn_amt)
10568
10569 @ @<Declare subroutines needed by |offset_prep|@>=
10570 pointer mp_pen_walk (MP mp,pointer w, integer k) {
10571   /* walk |k| steps around a pen from |w| */
10572   while ( k>0 ) { w=link(w); decr(k);  };
10573   while ( k<0 ) { w=knil(w); incr(k);  };
10574   return w;
10575 }
10576
10577 @ The direction of a cubic $B(z_0,z_1,z_2,z_3;t)=\bigl(x(t),y(t)\bigr)$ can be
10578 calculated from the quadratic polynomials
10579 ${1\over3}x'(t)=B(x_1-x_0,x_2-x_1,x_3-x_2;t)$ and
10580 ${1\over3}y'(t)=B(y_1-y_0,y_2-y_1,y_3-y_2;t)$.
10581 Since we may be calculating directions from several cubics
10582 split from the current one, it is desirable to do these calculations
10583 without losing too much precision. ``Scaled up'' values of the
10584 derivatives, which will be less tainted by accumulated errors than
10585 derivatives found from the cubics themselves, are maintained in
10586 local variables |x0|, |x1|, and |x2|, representing $X_0=2^l(x_1-x_0)$,
10587 $X_1=2^l(x_2-x_1)$, and $X_2=2^l(x_3-x_2)$; similarly |y0|, |y1|, and~|y2|
10588 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)$.
10589
10590 @<Other local variables for |offset_prep|@>=
10591 integer x0,x1,x2,y0,y1,y2; /* representatives of derivatives */
10592 integer t0,t1,t2; /* coefficients of polynomial for slope testing */
10593 integer du,dv,dx,dy; /* for directions of the pen and the curve */
10594 integer dx0,dy0; /* initial direction for the first cubic in the curve */
10595 integer max_coef; /* used while scaling */
10596 integer x0a,x1a,x2a,y0a,y1a,y2a; /* intermediate values */
10597 fraction t; /* where the derivative passes through zero */
10598 fraction s; /* a temporary value */
10599
10600 @ @<Prepare for derivative computations...@>=
10601 x0=right_x(p)-x_coord(p);
10602 x2=x_coord(q)-left_x(q);
10603 x1=left_x(q)-right_x(p);
10604 y0=right_y(p)-y_coord(p); y2=y_coord(q)-left_y(q);
10605 y1=left_y(q)-right_y(p);
10606 max_coef=abs(x0);
10607 if ( abs(x1)>max_coef ) max_coef=abs(x1);
10608 if ( abs(x2)>max_coef ) max_coef=abs(x2);
10609 if ( abs(y0)>max_coef ) max_coef=abs(y0);
10610 if ( abs(y1)>max_coef ) max_coef=abs(y1);
10611 if ( abs(y2)>max_coef ) max_coef=abs(y2);
10612 if ( max_coef==0 ) goto NOT_FOUND;
10613 while ( max_coef<fraction_half ) {
10614   double(max_coef);
10615   double(x0); double(x1); double(x2);
10616   double(y0); double(y1); double(y2);
10617 }
10618
10619 @ Let us first solve a special case of the problem: Suppose we
10620 know an index~$k$ such that either (i)~$d(t)\succeq d_{k-1}$ for all~$t$
10621 and $d(0)\prec d_k$, or (ii)~$d(t)\preceq d_k$ for all~$t$ and
10622 $d(0)\succ d_{k-1}$.
10623 Then, in a sense, we're halfway done, since one of the two relations
10624 in $(*)$ is satisfied, and the other couldn't be satisfied for
10625 any other value of~|k|.
10626
10627 Actually, the conditions can be relaxed somewhat since a relation such as
10628 $d(t)\succeq d_{k-1}$ restricts $d(t)$ to a half plane when all that really
10629 matters is whether $d(t)$ crosses the ray in the $d_{k-1}$ direction from
10630 the origin.  The condition for case~(i) becomes $d_{k-1}\preceq d(0)\prec d_k$
10631 and $d(t)$ never crosses the $d_{k-1}$ ray in the clockwise direction.
10632 Case~(ii) is similar except $d(t)$ cannot cross the $d_k$ ray in the
10633 counterclockwise direction.
10634
10635 The |fin_offset_prep| subroutine solves the stated subproblem.
10636 It has a parameter called |rise| that is |1| in
10637 case~(i), |-1| in case~(ii). Parameters |x0| through |y2| represent
10638 the derivative of the cubic following |p|.
10639 The |w| parameter should point to offset~$w_k$ and |info(p)| should already
10640 be set properly.  The |turn_amt| parameter gives the absolute value of the
10641 overall net change in pen offsets.
10642
10643 @<Declare subroutines needed by |offset_prep|@>=
10644 void mp_fin_offset_prep (MP mp,pointer p, pointer w, integer 
10645   x0,integer x1, integer x2, integer y0, integer y1, integer y2, 
10646   integer rise, integer turn_amt)  {
10647   pointer ww; /* for list manipulation */
10648   scaled du,dv; /* for slope calculation */
10649   integer t0,t1,t2; /* test coefficients */
10650   fraction t; /* place where the derivative passes a critical slope */
10651   fraction s; /* slope or reciprocal slope */
10652   integer v; /* intermediate value for updating |x0..y2| */
10653   pointer q; /* original |link(p)| */
10654   q=link(p);
10655   while (1)  { 
10656     if ( rise>0 ) ww=link(w); /* a pointer to $w\k$ */
10657     else  ww=knil(w); /* a pointer to $w_{k-1}$ */
10658     @<Compute test coefficients |(t0,t1,t2)|
10659       for $d(t)$ versus $d_k$ or $d_{k-1}$@>;
10660     t=mp_crossing_point(mp, t0,t1,t2);
10661     if ( t>=fraction_one ) {
10662       if ( turn_amt>0 ) t=fraction_one;  else return;
10663     }
10664     @<Split the cubic at $t$,
10665       and split off another cubic if the derivative crosses back@>;
10666     w=ww;
10667   }
10668 }
10669
10670 @ We want $B(\\{t0},\\{t1},\\{t2};t)$ to be the dot product of $d(t)$ with a
10671 $-90^\circ$ rotation of the vector from |w| to |ww|.  This makes the resulting
10672 function cross from positive to negative when $d_{k-1}\preceq d(t)\preceq d_k$
10673 begins to fail.
10674
10675 @<Compute test coefficients |(t0,t1,t2)| for $d(t)$ versus...@>=
10676 du=x_coord(ww)-x_coord(w); dv=y_coord(ww)-y_coord(w);
10677 if ( abs(du)>=abs(dv) ) {
10678   s=mp_make_fraction(mp, dv,du);
10679   t0=mp_take_fraction(mp, x0,s)-y0;
10680   t1=mp_take_fraction(mp, x1,s)-y1;
10681   t2=mp_take_fraction(mp, x2,s)-y2;
10682   if ( du<0 ) { negate(t0); negate(t1); negate(t2);  }
10683 } else { 
10684   s=mp_make_fraction(mp, du,dv);
10685   t0=x0-mp_take_fraction(mp, y0,s);
10686   t1=x1-mp_take_fraction(mp, y1,s);
10687   t2=x2-mp_take_fraction(mp, y2,s);
10688   if ( dv<0 ) { negate(t0); negate(t1); negate(t2);  }
10689 }
10690 if ( t0<0 ) t0=0 /* should be positive without rounding error */
10691
10692 @ The curve has crossed $d_k$ or $d_{k-1}$; its initial segment satisfies
10693 $(*)$, and it might cross again, yielding another solution of $(*)$.
10694
10695 @<Split the cubic at $t$, and split off another...@>=
10696
10697 mp_split_cubic(mp, p,t); p=link(p); info(p)=zero_off+rise;
10698 decr(turn_amt);
10699 v=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10700 x0=t_of_the_way(v,x1);
10701 v=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10702 y0=t_of_the_way(v,y1);
10703 if ( turn_amt<0 ) {
10704   t1=t_of_the_way(t1,t2);
10705   if ( t1>0 ) t1=0; /* without rounding error, |t1| would be |<=0| */
10706   t=mp_crossing_point(mp, 0,-t1,-t2);
10707   if ( t>fraction_one ) t=fraction_one;
10708   incr(turn_amt);
10709   if ( (t==fraction_one)&&(link(p)!=q) ) {
10710     info(link(p))=info(link(p))-rise;
10711   } else { 
10712     mp_split_cubic(mp, p,t); info(link(p))=zero_off-rise;
10713     v=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10714     x2=t_of_the_way(x1,v);
10715     v=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10716     y2=t_of_the_way(y1,v);
10717   }
10718 }
10719 }
10720
10721 @ Now we must consider the general problem of |offset_prep|, when
10722 nothing is known about a given cubic. We start by finding its
10723 direction in the vicinity of |t=0|.
10724
10725 If $z'(t)=0$, the given cubic is numerically unstable but |offset_prep|
10726 has not yet introduced any more numerical errors.  Thus we can compute
10727 the true initial direction for the given cubic, even if it is almost
10728 degenerate.
10729
10730 @<Find the initial direction |(dx,dy)|@>=
10731 dx=x0; dy=y0;
10732 if ( dx==0 && dy==0 ) { 
10733   dx=x1; dy=y1;
10734   if ( dx==0 && dy==0 ) { 
10735     dx=x2; dy=y2;
10736   }
10737 }
10738 if ( p==c ) { dx0=dx; dy0=dy;  }
10739
10740 @ @<Find the final direction |(dxin,dyin)|@>=
10741 dxin=x2; dyin=y2;
10742 if ( dxin==0 && dyin==0 ) {
10743   dxin=x1; dyin=y1;
10744   if ( dxin==0 && dyin==0 ) {
10745     dxin=x0; dyin=y0;
10746   }
10747 }
10748
10749 @ The next step is to bracket the initial direction between consecutive
10750 edges of the pen polygon.  We must be careful to turn clockwise only if
10751 this makes the turn less than $180^\circ$. (A $180^\circ$ turn must be
10752 counter-clockwise in order to make \&{doublepath} envelopes come out
10753 @:double_path_}{\&{doublepath} primitive@>
10754 right.) This code depends on |w0| being the offset for |(dxin,dyin)|.
10755
10756 @<Update |info(p)| and find the offset $w_k$ such that...@>=
10757 turn_amt=mp_get_turn_amt(mp,w0,dx,dy,(mp_ab_vs_cd(mp, dy,dxin,dx,dyin)>=0));
10758 w=mp_pen_walk(mp, w0, turn_amt);
10759 w0=w;
10760 info(p)=info(p)+turn_amt
10761
10762 @ Decide how many pen offsets to go away from |w| in order to find the offset
10763 for |(dx,dy)|, going counterclockwise if |ccw| is |true|.  This assumes that
10764 |w| is the offset for some direction $(x',y')$ from which the angle to |(dx,dy)|
10765 in the sense determined by |ccw| is less than or equal to $180^\circ$.
10766
10767 If the pen polygon has only two edges, they could both be parallel
10768 to |(dx,dy)|.  In this case, we must be careful to stop after crossing the first
10769 such edge in order to avoid an infinite loop.
10770
10771 @<Declare subroutines needed by |offset_prep|@>=
10772 integer mp_get_turn_amt (MP mp,pointer w, scaled  dx,
10773                          scaled dy, boolean  ccw) {
10774   pointer ww; /* a neighbor of knot~|w| */
10775   integer s; /* turn amount so far */
10776   integer t; /* |ab_vs_cd| result */
10777   s=0;
10778   if ( ccw ) { 
10779     ww=link(w);
10780     do {  
10781       t=mp_ab_vs_cd(mp, dy,(x_coord(ww)-x_coord(w)),
10782                         dx,(y_coord(ww)-y_coord(w)));
10783       if ( t<0 ) break;
10784       incr(s);
10785       w=ww; ww=link(ww);
10786     } while (t>0);
10787   } else { 
10788     ww=knil(w);
10789     while ( mp_ab_vs_cd(mp, dy,(x_coord(w)-x_coord(ww)),
10790                             dx,(y_coord(w)-y_coord(ww))) < 0) { 
10791       decr(s);
10792       w=ww; ww=knil(ww);
10793     }
10794   }
10795   return s;
10796 }
10797
10798 @ When we're all done, the final offset is |w0| and the final curve direction
10799 is |(dxin,dyin)|.  With this knowledge of the incoming direction at |c|, we
10800 can correct |info(c)| which was erroneously based on an incoming offset
10801 of~|h|.
10802
10803 @d fix_by(A) info(c)=info(c)+(A)
10804
10805 @<Fix the offset change in |info(c)| and set |c| to the return value of...@>=
10806 mp->spec_offset=info(c)-zero_off;
10807 if ( link(c)==c ) {
10808   info(c)=zero_off+n;
10809 } else { 
10810   fix_by(k_needed);
10811   while ( w0!=h ) { fix_by(1); w0=link(w0);  };
10812   while ( info(c)<=zero_off-n ) fix_by(n);
10813   while ( info(c)>zero_off ) fix_by(-n);
10814   if ( (info(c)!=zero_off)&&(mp_ab_vs_cd(mp, dy0,dxin,dx0,dyin)>=0) ) fix_by(n);
10815 }
10816 return c
10817
10818 @ Finally we want to reduce the general problem to situations that
10819 |fin_offset_prep| can handle. We split the cubic into at most three parts
10820 with respect to $d_{k-1}$, and apply |fin_offset_prep| to each part.
10821
10822 @<Complete the offset splitting process@>=
10823 ww=knil(w);
10824 @<Compute test coeff...@>;
10825 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set
10826   |t:=fraction_one+1|@>;
10827 if ( t>fraction_one ) {
10828   mp_fin_offset_prep(mp, p,w,x0,x1,x2,y0,y1,y2,1,turn_amt);
10829 } else {
10830   mp_split_cubic(mp, p,t); r=link(p);
10831   x1a=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10832   x2a=t_of_the_way(x1a,x1);
10833   y1a=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10834   y2a=t_of_the_way(y1a,y1);
10835   mp_fin_offset_prep(mp, p,w,x0,x1a,x2a,y0,y1a,y2a,1,0); x0=x2a; y0=y2a;
10836   info(r)=zero_off-1;
10837   if ( turn_amt>=0 ) {
10838     t1=t_of_the_way(t1,t2);
10839     if ( t1>0 ) t1=0;
10840     t=mp_crossing_point(mp, 0,-t1,-t2);
10841     if ( t>fraction_one ) t=fraction_one;
10842     @<Split off another rising cubic for |fin_offset_prep|@>;
10843     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,0);
10844   } else {
10845     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,(-1-turn_amt));
10846   }
10847 }
10848
10849 @ @<Split off another rising cubic for |fin_offset_prep|@>=
10850 mp_split_cubic(mp, r,t); info(link(r))=zero_off+1;
10851 x1a=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10852 x0a=t_of_the_way(x1,x1a);
10853 y1a=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10854 y0a=t_of_the_way(y1,y1a);
10855 mp_fin_offset_prep(mp, link(r),w,x0a,x1a,x2,y0a,y1a,y2,1,turn_amt);
10856 x2=x0a; y2=y0a
10857
10858 @ At this point, the direction of the incoming pen edge is |(-du,-dv)|.
10859 When the component of $d(t)$ perpendicular to |(-du,-dv)| crosses zero, we
10860 need to decide whether the directions are parallel or antiparallel.  We
10861 can test this by finding the dot product of $d(t)$ and |(-du,-dv)|, but this
10862 should be avoided when the value of |turn_amt| already determines the
10863 answer.  If |t2<0|, there is one crossing and it is antiparallel only if
10864 |turn_amt>=0|.  If |turn_amt<0|, there should always be at least one
10865 crossing and the first crossing cannot be antiparallel.
10866
10867 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set...@>=
10868 t=mp_crossing_point(mp, t0,t1,t2);
10869 if ( turn_amt>=0 ) {
10870   if ( t2<0 ) {
10871     t=fraction_one+1;
10872   } else { 
10873     u0=t_of_the_way(x0,x1);
10874     u1=t_of_the_way(x1,x2);
10875     ss=mp_take_fraction(mp, -du,t_of_the_way(u0,u1));
10876     v0=t_of_the_way(y0,y1);
10877     v1=t_of_the_way(y1,y2);
10878     ss=ss+mp_take_fraction(mp, -dv,t_of_the_way(v0,v1));
10879     if ( ss<0 ) t=fraction_one+1;
10880   }
10881 } else if ( t>fraction_one ) {
10882   t=fraction_one;
10883 }
10884
10885 @ @<Other local variables for |offset_prep|@>=
10886 integer u0,u1,v0,v1; /* intermediate values for $d(t)$ calculation */
10887 integer ss = 0; /* the part of the dot product computed so far */
10888 int d_sign; /* sign of overall change in direction for this cubic */
10889
10890 @ If the cubic almost has a cusp, it is a numerically ill-conditioned
10891 problem to decide which way it loops around but that's OK as long we're
10892 consistent.  To make \&{doublepath} envelopes work properly, reversing
10893 the path should always change the sign of |turn_amt|.
10894
10895 @<Decide on the net change in pen offsets and set |turn_amt|@>=
10896 d_sign=mp_ab_vs_cd(mp, dx,dyin, dxin,dy);
10897 if ( d_sign==0 ) {
10898   @<Check rotation direction based on node position@>
10899 }
10900 if ( d_sign==0 ) {
10901   if ( dx==0 ) {
10902     if ( dy>0 ) d_sign=1;  else d_sign=-1;
10903   } else {
10904     if ( dx>0 ) d_sign=1;  else d_sign=-1; 
10905   }
10906 }
10907 @<Make |ss| negative if and only if the total change in direction is
10908   more than $180^\circ$@>;
10909 turn_amt=mp_get_turn_amt(mp, w, dxin, dyin, (d_sign>0));
10910 if ( ss<0 ) turn_amt=turn_amt-d_sign*n
10911
10912 @ We check rotation direction by looking at the vector connecting the current
10913 node with the next. If its angle with incoming and outgoing tangents has the
10914 same sign, we pick this as |d_sign|, since it means we have a flex, not a cusp.
10915 Otherwise we proceed to the cusp code.
10916
10917 @<Check rotation direction based on node position@>=
10918 u0=x_coord(q)-x_coord(p);
10919 u1=y_coord(q)-y_coord(p);
10920 d_sign = half(mp_ab_vs_cd(mp, dx, u1, u0, dy)+
10921   mp_ab_vs_cd(mp, u0, dyin, dxin, u1));
10922
10923 @ In order to be invariant under path reversal, the result of this computation
10924 should not change when |x0|, |y0|, $\ldots$ are all negated and |(x0,y0)| is
10925 then swapped with |(x2,y2)|.  We make use of the identities
10926 |take_fraction(-a,-b)=take_fraction(a,b)| and
10927 |t_of_the_way(-a,-b)=-(t_of_the_way(a,b))|.
10928
10929 @<Make |ss| negative if and only if the total change in direction is...@>=
10930 t0=half(mp_take_fraction(mp, x0,y2))-half(mp_take_fraction(mp, x2,y0));
10931 t1=half(mp_take_fraction(mp, x1,(y0+y2)))-half(mp_take_fraction(mp, y1,(x0+x2)));
10932 if ( t0==0 ) t0=d_sign; /* path reversal always negates |d_sign| */
10933 if ( t0>0 ) {
10934   t=mp_crossing_point(mp, t0,t1,-t0);
10935   u0=t_of_the_way(x0,x1);
10936   u1=t_of_the_way(x1,x2);
10937   v0=t_of_the_way(y0,y1);
10938   v1=t_of_the_way(y1,y2);
10939 } else { 
10940   t=mp_crossing_point(mp, -t0,t1,t0);
10941   u0=t_of_the_way(x2,x1);
10942   u1=t_of_the_way(x1,x0);
10943   v0=t_of_the_way(y2,y1);
10944   v1=t_of_the_way(y1,y0);
10945 }
10946 ss=mp_take_fraction(mp, (x0+x2),t_of_the_way(u0,u1))+
10947    mp_take_fraction(mp, (y0+y2),t_of_the_way(v0,v1))
10948
10949 @ Here's a routine that prints an envelope spec in symbolic form.  It assumes
10950 that the |cur_pen| has not been walked around to the first offset.
10951
10952 @c 
10953 void mp_print_spec (MP mp,pointer cur_spec, pointer cur_pen, char *s) {
10954   pointer p,q; /* list traversal */
10955   pointer w; /* the current pen offset */
10956   mp_print_diagnostic(mp, "Envelope spec",s,true);
10957   p=cur_spec; w=mp_pen_walk(mp, cur_pen,mp->spec_offset);
10958   mp_print_ln(mp);
10959   mp_print_two(mp, x_coord(cur_spec),y_coord(cur_spec));
10960   mp_print(mp, " % beginning with offset ");
10961   mp_print_two(mp, x_coord(w),y_coord(w));
10962   do { 
10963     while (1) {  
10964       q=link(p);
10965       @<Print the cubic between |p| and |q|@>;
10966       p=q;
10967           if ((p==cur_spec) || (info(p)!=zero_off)) 
10968         break;
10969     }
10970     if ( info(p)!=zero_off ) {
10971       @<Update |w| as indicated by |info(p)| and print an explanation@>;
10972     }
10973   } while (p!=cur_spec);
10974   mp_print_nl(mp, " & cycle");
10975   mp_end_diagnostic(mp, true);
10976 }
10977
10978 @ @<Update |w| as indicated by |info(p)| and print an explanation@>=
10979
10980   w=mp_pen_walk(mp, w, (info(p)-zero_off));
10981   mp_print(mp, " % ");
10982   if ( info(p)>zero_off ) mp_print(mp, "counter");
10983   mp_print(mp, "clockwise to offset ");
10984   mp_print_two(mp, x_coord(w),y_coord(w));
10985 }
10986
10987 @ @<Print the cubic between |p| and |q|@>=
10988
10989   mp_print_nl(mp, "   ..controls ");
10990   mp_print_two(mp, right_x(p),right_y(p));
10991   mp_print(mp, " and ");
10992   mp_print_two(mp, left_x(q),left_y(q));
10993   mp_print_nl(mp, " ..");
10994   mp_print_two(mp, x_coord(q),y_coord(q));
10995 }
10996
10997 @ Once we have an envelope spec, the remaining task to construct the actual
10998 envelope by offsetting each cubic as determined by the |info| fields in
10999 the knots.  First we use |offset_prep| to convert the |c| into an envelope
11000 spec. Then we add the offsets so that |c| becomes a cyclic path that represents
11001 the envelope.
11002
11003 The |ljoin| and |miterlim| parameters control the treatment of points where the
11004 pen offset changes, and |lcap| controls the endpoints of a \&{doublepath}.
11005 The endpoints are easily located because |c| is given in undoubled form
11006 and then doubled in this procedure.  We use |spec_p1| and |spec_p2| to keep
11007 track of the endpoints and treat them like very sharp corners.
11008 Butt end caps are treated like beveled joins; round end caps are treated like
11009 round joins; and square end caps are achieved by setting |join_type:=3|.
11010
11011 None of these parameters apply to inside joins where the convolution tracing
11012 has retrograde lines.  In such cases we use a simple connect-the-endpoints
11013 approach that is achieved by setting |join_type:=2|.
11014
11015 @c @<Declare a function called |insert_knot|@>;
11016 pointer mp_make_envelope (MP mp,pointer c, pointer h, small_number ljoin,
11017   small_number lcap, scaled miterlim) {
11018   pointer p,q,r,q0; /* for manipulating the path */
11019   int join_type=0; /* codes |0..3| for mitered, round, beveled, or square */
11020   pointer w,w0; /* the pen knot for the current offset */
11021   scaled qx,qy; /* unshifted coordinates of |q| */
11022   halfword k,k0; /* controls pen edge insertion */
11023   @<Other local variables for |make_envelope|@>;
11024   dxin=0; dyin=0; dxout=0; dyout=0;
11025   mp->spec_p1=null; mp->spec_p2=null;
11026   @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>;
11027   @<Use |offset_prep| to compute the envelope spec then walk |h| around to
11028     the initial offset@>;
11029   w=h;
11030   p=c;
11031   do {  
11032     q=link(p); q0=q;
11033     qx=x_coord(q); qy=y_coord(q);
11034     k=info(q);
11035     k0=k; w0=w;
11036     if ( k!=zero_off ) {
11037       @<Set |join_type| to indicate how to handle offset changes at~|q|@>;
11038     }
11039     @<Add offset |w| to the cubic from |p| to |q|@>;
11040     while ( k!=zero_off ) { 
11041       @<Step |w| and move |k| one step closer to |zero_off|@>;
11042       if ( (join_type==1)||(k==zero_off) )
11043          q=mp_insert_knot(mp, q,qx+x_coord(w),qy+y_coord(w));
11044     };
11045     if ( q!=link(p) ) {
11046       @<Set |p=link(p)| and add knots between |p| and |q| as
11047         required by |join_type|@>;
11048     }
11049     p=q;
11050   } while (q0!=c);
11051   return c;
11052 }
11053
11054 @ @<Use |offset_prep| to compute the envelope spec then walk |h| around to...@>=
11055 c=mp_offset_prep(mp, c,h);
11056 if ( mp->internal[mp_tracing_specs]>0 ) 
11057   mp_print_spec(mp, c,h,"");
11058 h=mp_pen_walk(mp, h,mp->spec_offset)
11059
11060 @ Mitered and squared-off joins depend on path directions that are difficult to
11061 compute for degenerate cubics.  The envelope spec computed by |offset_prep| can
11062 have degenerate cubics only if the entire cycle collapses to a single
11063 degenerate cubic.  Setting |join_type:=2| in this case makes the computed
11064 envelope degenerate as well.
11065
11066 @<Set |join_type| to indicate how to handle offset changes at~|q|@>=
11067 if ( k<zero_off ) {
11068   join_type=2;
11069 } else {
11070   if ( (q!=mp->spec_p1)&&(q!=mp->spec_p2) ) join_type=ljoin;
11071   else if ( lcap==2 ) join_type=3;
11072   else join_type=2-lcap;
11073   if ( (join_type==0)||(join_type==3) ) {
11074     @<Set the incoming and outgoing directions at |q|; in case of
11075       degeneracy set |join_type:=2|@>;
11076     if ( join_type==0 ) {
11077       @<If |miterlim| is less than the secant of half the angle at |q|
11078         then set |join_type:=2|@>;
11079     }
11080   }
11081 }
11082
11083 @ @<If |miterlim| is less than the secant of half the angle at |q|...@>=
11084
11085   tmp=mp_take_fraction(mp, miterlim,fraction_half+
11086       half(mp_take_fraction(mp, dxin,dxout)+mp_take_fraction(mp, dyin,dyout)));
11087   if ( tmp<unity )
11088     if ( mp_take_scaled(mp, miterlim,tmp)<unity ) join_type=2;
11089 }
11090
11091 @ @<Other local variables for |make_envelope|@>=
11092 fraction dxin,dyin,dxout,dyout; /* directions at |q| when square or mitered */
11093 scaled tmp; /* a temporary value */
11094
11095 @ The coordinates of |p| have already been shifted unless |p| is the first
11096 knot in which case they get shifted at the very end.
11097
11098 @<Add offset |w| to the cubic from |p| to |q|@>=
11099 right_x(p)=right_x(p)+x_coord(w);
11100 right_y(p)=right_y(p)+y_coord(w);
11101 left_x(q)=left_x(q)+x_coord(w);
11102 left_y(q)=left_y(q)+y_coord(w);
11103 x_coord(q)=x_coord(q)+x_coord(w);
11104 y_coord(q)=y_coord(q)+y_coord(w);
11105 left_type(q)=mp_explicit;
11106 right_type(q)=mp_explicit
11107
11108 @ @<Step |w| and move |k| one step closer to |zero_off|@>=
11109 if ( k>zero_off ){ w=link(w); decr(k);  }
11110 else { w=knil(w); incr(k);  }
11111
11112 @ The cubic from |q| to the new knot at |(x,y)| becomes a line segment and
11113 the |right_x| and |right_y| fields of |r| are set from |q|.  This is done in
11114 case the cubic containing these control points is ``yet to be examined.''
11115
11116 @<Declare a function called |insert_knot|@>=
11117 pointer mp_insert_knot (MP mp,pointer q, scaled x, scaled y) {
11118   /* returns the inserted knot */
11119   pointer r; /* the new knot */
11120   r=mp_get_node(mp, knot_node_size);
11121   link(r)=link(q); link(q)=r;
11122   right_x(r)=right_x(q);
11123   right_y(r)=right_y(q);
11124   x_coord(r)=x;
11125   y_coord(r)=y;
11126   right_x(q)=x_coord(q);
11127   right_y(q)=y_coord(q);
11128   left_x(r)=x_coord(r);
11129   left_y(r)=y_coord(r);
11130   left_type(r)=mp_explicit;
11131   right_type(r)=mp_explicit;
11132   originator(r)=mp_program_code;
11133   return r;
11134 }
11135
11136 @ After setting |p:=link(p)|, either |join_type=1| or |q=link(p)|.
11137
11138 @<Set |p=link(p)| and add knots between |p| and |q| as...@>=
11139
11140   p=link(p);
11141   if ( (join_type==0)||(join_type==3) ) {
11142     if ( join_type==0 ) {
11143       @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>
11144     } else {
11145       @<Make |r| the last of two knots inserted between |p| and |q| to form a
11146         squared join@>;
11147     }
11148     if ( r!=null ) { 
11149       right_x(r)=x_coord(r);
11150       right_y(r)=y_coord(r);
11151     }
11152   }
11153 }
11154
11155 @ For very small angles, adding a knot is unnecessary and would cause numerical
11156 problems, so we just set |r:=null| in that case.
11157
11158 @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>=
11159
11160   det=mp_take_fraction(mp, dyout,dxin)-mp_take_fraction(mp, dxout,dyin);
11161   if ( abs(det)<26844 ) { 
11162      r=null; /* sine $<10^{-4}$ */
11163   } else { 
11164     tmp=mp_take_fraction(mp, x_coord(q)-x_coord(p),dyout)-
11165         mp_take_fraction(mp, y_coord(q)-y_coord(p),dxout);
11166     tmp=mp_make_fraction(mp, tmp,det);
11167     r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11168       y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11169   }
11170 }
11171
11172 @ @<Other local variables for |make_envelope|@>=
11173 fraction det; /* a determinant used for mitered join calculations */
11174
11175 @ @<Make |r| the last of two knots inserted between |p| and |q| to form a...@>=
11176
11177   ht_x=y_coord(w)-y_coord(w0);
11178   ht_y=x_coord(w0)-x_coord(w);
11179   while ( (abs(ht_x)<fraction_half)&&(abs(ht_y)<fraction_half) ) { 
11180     ht_x+=ht_x; ht_y+=ht_y;
11181   }
11182   @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range dot
11183     product with |(ht_x,ht_y)|@>;
11184   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxin,ht_x)+
11185                                   mp_take_fraction(mp, dyin,ht_y));
11186   r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11187                          y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11188   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxout,ht_x)+
11189                                   mp_take_fraction(mp, dyout,ht_y));
11190   r=mp_insert_knot(mp, r,x_coord(q)+mp_take_fraction(mp, tmp,dxout),
11191                          y_coord(q)+mp_take_fraction(mp, tmp,dyout));
11192 }
11193
11194 @ @<Other local variables for |make_envelope|@>=
11195 fraction ht_x,ht_y; /* perpendicular to the segment from |p| to |q| */
11196 scaled max_ht; /* maximum height of the pen polygon above the |w0|-|w| line */
11197 halfword kk; /* keeps track of the pen vertices being scanned */
11198 pointer ww; /* the pen vertex being tested */
11199
11200 @ The dot product of the vector from |w0| to |ww| with |(ht_x,ht_y)| ranges
11201 from zero to |max_ht|.
11202
11203 @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range...@>=
11204 max_ht=0;
11205 kk=zero_off;
11206 ww=w;
11207 while (1)  { 
11208   @<Step |ww| and move |kk| one step closer to |k0|@>;
11209   if ( kk==k0 ) break;
11210   tmp=mp_take_fraction(mp, (x_coord(ww)-x_coord(w0)),ht_x)+
11211       mp_take_fraction(mp, (y_coord(ww)-y_coord(w0)),ht_y);
11212   if ( tmp>max_ht ) max_ht=tmp;
11213 }
11214
11215
11216 @ @<Step |ww| and move |kk| one step closer to |k0|@>=
11217 if ( kk>k0 ) { ww=link(ww); decr(kk);  }
11218 else { ww=knil(ww); incr(kk);  }
11219
11220 @ @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>=
11221 if ( left_type(c)==mp_endpoint ) { 
11222   mp->spec_p1=mp_htap_ypoc(mp, c);
11223   mp->spec_p2=mp->path_tail;
11224   originator(mp->spec_p1)=mp_program_code;
11225   link(mp->spec_p2)=link(mp->spec_p1);
11226   link(mp->spec_p1)=c;
11227   mp_remove_cubic(mp, mp->spec_p1);
11228   c=mp->spec_p1;
11229   if ( c!=link(c) ) {
11230     originator(mp->spec_p2)=mp_program_code;
11231     mp_remove_cubic(mp, mp->spec_p2);
11232   } else {
11233     @<Make |c| look like a cycle of length one@>;
11234   }
11235 }
11236
11237 @ @<Make |c| look like a cycle of length one@>=
11238
11239   left_type(c)=mp_explicit; right_type(c)=mp_explicit;
11240   left_x(c)=x_coord(c); left_y(c)=y_coord(c);
11241   right_x(c)=x_coord(c); right_y(c)=y_coord(c);
11242 }
11243
11244 @ In degenerate situations we might have to look at the knot preceding~|q|.
11245 That knot is |p| but if |p<>c|, its coordinates have already been offset by |w|.
11246
11247 @<Set the incoming and outgoing directions at |q|; in case of...@>=
11248 dxin=x_coord(q)-left_x(q);
11249 dyin=y_coord(q)-left_y(q);
11250 if ( (dxin==0)&&(dyin==0) ) {
11251   dxin=x_coord(q)-right_x(p);
11252   dyin=y_coord(q)-right_y(p);
11253   if ( (dxin==0)&&(dyin==0) ) {
11254     dxin=x_coord(q)-x_coord(p);
11255     dyin=y_coord(q)-y_coord(p);
11256     if ( p!=c ) { /* the coordinates of |p| have been offset by |w| */
11257       dxin=dxin+x_coord(w);
11258       dyin=dyin+y_coord(w);
11259     }
11260   }
11261 }
11262 tmp=mp_pyth_add(mp, dxin,dyin);
11263 if ( tmp==0 ) {
11264   join_type=2;
11265 } else { 
11266   dxin=mp_make_fraction(mp, dxin,tmp);
11267   dyin=mp_make_fraction(mp, dyin,tmp);
11268   @<Set the outgoing direction at |q|@>;
11269 }
11270
11271 @ If |q=c| then the coordinates of |r| and the control points between |q|
11272 and~|r| have already been offset by |h|.
11273
11274 @<Set the outgoing direction at |q|@>=
11275 dxout=right_x(q)-x_coord(q);
11276 dyout=right_y(q)-y_coord(q);
11277 if ( (dxout==0)&&(dyout==0) ) {
11278   r=link(q);
11279   dxout=left_x(r)-x_coord(q);
11280   dyout=left_y(r)-y_coord(q);
11281   if ( (dxout==0)&&(dyout==0) ) {
11282     dxout=x_coord(r)-x_coord(q);
11283     dyout=y_coord(r)-y_coord(q);
11284   }
11285 }
11286 if ( q==c ) {
11287   dxout=dxout-x_coord(h);
11288   dyout=dyout-y_coord(h);
11289 }
11290 tmp=mp_pyth_add(mp, dxout,dyout);
11291 if ( tmp==0 ) mp_confusion(mp, "degenerate spec");
11292 @:this can't happen degerate spec}{\quad degenerate spec@>
11293 dxout=mp_make_fraction(mp, dxout,tmp);
11294 dyout=mp_make_fraction(mp, dyout,tmp)
11295
11296 @* \[23] Direction and intersection times.
11297 A path of length $n$ is defined parametrically by functions $x(t)$ and
11298 $y(t)$, for |0<=t<=n|; we can regard $t$ as the ``time'' at which the path
11299 reaches the point $\bigl(x(t),y(t)\bigr)$.  In this section of the program
11300 we shall consider operations that determine special times associated with
11301 given paths: the first time that a path travels in a given direction, and
11302 a pair of times at which two paths cross each other.
11303
11304 @ Let's start with the easier task. The function |find_direction_time| is
11305 given a direction |(x,y)| and a path starting at~|h|. If the path never
11306 travels in direction |(x,y)|, the direction time will be~|-1|; otherwise
11307 it will be nonnegative.
11308
11309 Certain anomalous cases can arise: If |(x,y)=(0,0)|, so that the given
11310 direction is undefined, the direction time will be~0. If $\bigl(x'(t),
11311 y'(t)\bigr)=(0,0)$, so that the path direction is undefined, it will be
11312 assumed to match any given direction at time~|t|.
11313
11314 The routine solves this problem in nondegenerate cases by rotating the path
11315 and the given direction so that |(x,y)=(1,0)|; i.e., the main task will be
11316 to find when a given path first travels ``due east.''
11317
11318 @c 
11319 scaled mp_find_direction_time (MP mp,scaled x, scaled y, pointer h) {
11320   scaled max; /* $\max\bigl(\vert x\vert,\vert y\vert\bigr)$ */
11321   pointer p,q; /* for list traversal */
11322   scaled n; /* the direction time at knot |p| */
11323   scaled tt; /* the direction time within a cubic */
11324   @<Other local variables for |find_direction_time|@>;
11325   @<Normalize the given direction for better accuracy;
11326     but |return| with zero result if it's zero@>;
11327   n=0; p=h; phi=0;
11328   while (1) { 
11329     if ( right_type(p)==mp_endpoint ) break;
11330     q=link(p);
11331     @<Rotate the cubic between |p| and |q|; then
11332       |goto found| if the rotated cubic travels due east at some time |tt|;
11333       but |break| if an entire cyclic path has been traversed@>;
11334     p=q; n=n+unity;
11335   }
11336   return (-unity);
11337 FOUND: 
11338   return (n+tt);
11339 }
11340
11341 @ @<Normalize the given direction for better accuracy...@>=
11342 if ( abs(x)<abs(y) ) { 
11343   x=mp_make_fraction(mp, x,abs(y));
11344   if ( y>0 ) y=fraction_one; else y=-fraction_one;
11345 } else if ( x==0 ) { 
11346   return 0;
11347 } else  { 
11348   y=mp_make_fraction(mp, y,abs(x));
11349   if ( x>0 ) x=fraction_one; else x=-fraction_one;
11350 }
11351
11352 @ Since we're interested in the tangent directions, we work with the
11353 derivative $${\textstyle1\over3}B'(x_0,x_1,x_2,x_3;t)=
11354 B(x_1-x_0,x_2-x_1,x_3-x_2;t)$$ instead of
11355 $B(x_0,x_1,x_2,x_3;t)$ itself. The derived coefficients are also scaled up
11356 in order to achieve better accuracy.
11357
11358 The given path may turn abruptly at a knot, and it might pass the critical
11359 tangent direction at such a time. Therefore we remember the direction |phi|
11360 in which the previous rotated cubic was traveling. (The value of |phi| will be
11361 undefined on the first cubic, i.e., when |n=0|.)
11362
11363 @<Rotate the cubic between |p| and |q|; then...@>=
11364 tt=0;
11365 @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples of the control
11366   points of the rotated derivatives@>;
11367 if ( y1==0 ) if ( x1>=0 ) goto FOUND;
11368 if ( n>0 ) { 
11369   @<Exit to |found| if an eastward direction occurs at knot |p|@>;
11370   if ( p==h ) break;
11371   };
11372 if ( (x3!=0)||(y3!=0) ) phi=mp_n_arg(mp, x3,y3);
11373 @<Exit to |found| if the curve whose derivatives are specified by
11374   |x1,x2,x3,y1,y2,y3| travels eastward at some time~|tt|@>
11375
11376 @ @<Other local variables for |find_direction_time|@>=
11377 scaled x1,x2,x3,y1,y2,y3;  /* multiples of rotated derivatives */
11378 angle theta,phi; /* angles of exit and entry at a knot */
11379 fraction t; /* temp storage */
11380
11381 @ @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples...@>=
11382 x1=right_x(p)-x_coord(p); x2=left_x(q)-right_x(p);
11383 x3=x_coord(q)-left_x(q);
11384 y1=right_y(p)-y_coord(p); y2=left_y(q)-right_y(p);
11385 y3=y_coord(q)-left_y(q);
11386 max=abs(x1);
11387 if ( abs(x2)>max ) max=abs(x2);
11388 if ( abs(x3)>max ) max=abs(x3);
11389 if ( abs(y1)>max ) max=abs(y1);
11390 if ( abs(y2)>max ) max=abs(y2);
11391 if ( abs(y3)>max ) max=abs(y3);
11392 if ( max==0 ) goto FOUND;
11393 while ( max<fraction_half ){ 
11394   max+=max; x1+=x1; x2+=x2; x3+=x3;
11395   y1+=y1; y2+=y2; y3+=y3;
11396 }
11397 t=x1; x1=mp_take_fraction(mp, x1,x)+mp_take_fraction(mp, y1,y);
11398 y1=mp_take_fraction(mp, y1,x)-mp_take_fraction(mp, t,y);
11399 t=x2; x2=mp_take_fraction(mp, x2,x)+mp_take_fraction(mp, y2,y);
11400 y2=mp_take_fraction(mp, y2,x)-mp_take_fraction(mp, t,y);
11401 t=x3; x3=mp_take_fraction(mp, x3,x)+mp_take_fraction(mp, y3,y);
11402 y3=mp_take_fraction(mp, y3,x)-mp_take_fraction(mp, t,y)
11403
11404 @ @<Exit to |found| if an eastward direction occurs at knot |p|@>=
11405 theta=mp_n_arg(mp, x1,y1);
11406 if ( theta>=0 ) if ( phi<=0 ) if ( phi>=theta-one_eighty_deg ) goto FOUND;
11407 if ( theta<=0 ) if ( phi>=0 ) if ( phi<=theta+one_eighty_deg ) goto FOUND
11408
11409 @ In this step we want to use the |crossing_point| routine to find the
11410 roots of the quadratic equation $B(y_1,y_2,y_3;t)=0$.
11411 Several complications arise: If the quadratic equation has a double root,
11412 the curve never crosses zero, and |crossing_point| will find nothing;
11413 this case occurs iff $y_1y_3=y_2^2$ and $y_1y_2<0$. If the quadratic
11414 equation has simple roots, or only one root, we may have to negate it
11415 so that $B(y_1,y_2,y_3;t)$ crosses from positive to negative at its first root.
11416 And finally, we need to do special things if $B(y_1,y_2,y_3;t)$ is
11417 identically zero.
11418
11419 @ @<Exit to |found| if the curve whose derivatives are specified by...@>=
11420 if ( x1<0 ) if ( x2<0 ) if ( x3<0 ) goto DONE;
11421 if ( mp_ab_vs_cd(mp, y1,y3,y2,y2)==0 ) {
11422   @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11423     either |goto found| or |goto done|@>;
11424 }
11425 if ( y1<=0 ) {
11426   if ( y1<0 ) { y1=-y1; y2=-y2; y3=-y3; }
11427   else if ( y2>0 ){ y2=-y2; y3=-y3; };
11428 }
11429 @<Check the places where $B(y_1,y_2,y_3;t)=0$ to see if
11430   $B(x_1,x_2,x_3;t)\ge0$@>;
11431 DONE:
11432
11433 @ The quadratic polynomial $B(y_1,y_2,y_3;t)$ begins |>=0| and has at most
11434 two roots, because we know that it isn't identically zero.
11435
11436 It must be admitted that the |crossing_point| routine is not perfectly accurate;
11437 rounding errors might cause it to find a root when $y_1y_3>y_2^2$, or to
11438 miss the roots when $y_1y_3<y_2^2$. The rotation process is itself
11439 subject to rounding errors. Yet this code optimistically tries to
11440 do the right thing.
11441
11442 @d we_found_it { tt=(t+04000) / 010000; goto FOUND; }
11443
11444 @<Check the places where $B(y_1,y_2,y_3;t)=0$...@>=
11445 t=mp_crossing_point(mp, y1,y2,y3);
11446 if ( t>fraction_one ) goto DONE;
11447 y2=t_of_the_way(y2,y3);
11448 x1=t_of_the_way(x1,x2);
11449 x2=t_of_the_way(x2,x3);
11450 x1=t_of_the_way(x1,x2);
11451 if ( x1>=0 ) we_found_it;
11452 if ( y2>0 ) y2=0;
11453 tt=t; t=mp_crossing_point(mp, 0,-y2,-y3);
11454 if ( t>fraction_one ) goto DONE;
11455 x1=t_of_the_way(x1,x2);
11456 x2=t_of_the_way(x2,x3);
11457 if ( t_of_the_way(x1,x2)>=0 ) { 
11458   t=t_of_the_way(tt,fraction_one); we_found_it;
11459 }
11460
11461 @ @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11462     either |goto found| or |goto done|@>=
11463
11464   if ( mp_ab_vs_cd(mp, y1,y2,0,0)<0 ) {
11465     t=mp_make_fraction(mp, y1,y1-y2);
11466     x1=t_of_the_way(x1,x2);
11467     x2=t_of_the_way(x2,x3);
11468     if ( t_of_the_way(x1,x2)>=0 ) we_found_it;
11469   } else if ( y3==0 ) {
11470     if ( y1==0 ) {
11471       @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|@>;
11472     } else if ( x3>=0 ) {
11473       tt=unity; goto FOUND;
11474     }
11475   }
11476   goto DONE;
11477 }
11478
11479 @ At this point we know that the derivative of |y(t)| is identically zero,
11480 and that |x1<0|; but either |x2>=0| or |x3>=0|, so there's some hope of
11481 traveling east.
11482
11483 @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|...@>=
11484
11485   t=mp_crossing_point(mp, -x1,-x2,-x3);
11486   if ( t<=fraction_one ) we_found_it;
11487   if ( mp_ab_vs_cd(mp, x1,x3,x2,x2)<=0 ) { 
11488     t=mp_make_fraction(mp, x1,x1-x2); we_found_it;
11489   }
11490 }
11491
11492 @ The intersection of two cubics can be found by an interesting variant
11493 of the general bisection scheme described in the introduction to
11494 |crossing_point|.\
11495 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)$,
11496 we wish to find a pair of times $(t_1,t_2)$ such that $w(t_1)=z(t_2)$,
11497 if an intersection exists. First we find the smallest rectangle that
11498 encloses the points $\{w_0,w_1,w_2,w_3\}$ and check that it overlaps
11499 the smallest rectangle that encloses
11500 $\{z_0,z_1,z_2,z_3\}$; if not, the cubics certainly don't intersect.
11501 But if the rectangles do overlap, we bisect the intervals, getting
11502 new cubics $w'$ and~$w''$, $z'$~and~$z''$; the intersection routine first
11503 tries for an intersection between $w'$ and~$z'$, then (if unsuccessful)
11504 between $w'$ and~$z''$, then (if still unsuccessful) between $w''$ and~$z'$,
11505 finally (if thrice unsuccessful) between $w''$ and~$z''$. After $l$~successful
11506 levels of bisection we will have determined the intersection times $t_1$
11507 and~$t_2$ to $l$~bits of accuracy.
11508
11509 \def\submin{_{\rm min}} \def\submax{_{\rm max}}
11510 As before, it is better to work with the numbers $W_k=2^l(w_k-w_{k-1})$
11511 and $Z_k=2^l(z_k-z_{k-1})$ rather than the coefficients $w_k$ and $z_k$
11512 themselves. We also need one other quantity, $\Delta=2^l(w_0-z_0)$,
11513 to determine when the enclosing rectangles overlap. Here's why:
11514 The $x$~coordinates of~$w(t)$ are between $u\submin$ and $u\submax$,
11515 and the $x$~coordinates of~$z(t)$ are between $x\submin$ and $x\submax$,
11516 if we write $w_k=(u_k,v_k)$ and $z_k=(x_k,y_k)$ and $u\submin=
11517 \min(u_0,u_1,u_2,u_3)$, etc. These intervals of $x$~coordinates
11518 overlap if and only if $u\submin\L x\submax$ and
11519 $x\submin\L u\submax$. Letting
11520 $$U\submin=\min(0,U_1,U_1+U_2,U_1+U_2+U_3),\;
11521   U\submax=\max(0,U_1,U_1+U_2,U_1+U_2+U_3),$$
11522 we have $u\submin=2^lu_0+U\submin$, etc.; the condition for overlap
11523 reduces to
11524 $$X\submin-U\submax\L 2^l(u_0-x_0)\L X\submax-U\submin.$$
11525 Thus we want to maintain the quantity $2^l(u_0-x_0)$; similarly,
11526 the quantity $2^l(v_0-y_0)$ accounts for the $y$~coordinates. The
11527 coordinates of $\Delta=2^l(w_0-z_0)$ must stay bounded as $l$ increases,
11528 because of the overlap condition; i.e., we know that $X\submin$,
11529 $X\submax$, and their relatives are bounded, hence $X\submax-
11530 U\submin$ and $X\submin-U\submax$ are bounded.
11531
11532 @ Incidentally, if the given cubics intersect more than once, the process
11533 just sketched will not necessarily find the lexicographically smallest pair
11534 $(t_1,t_2)$. The solution actually obtained will be smallest in ``shuffled
11535 order''; i.e., if $t_1=(.a_1a_2\ldots a_{16})_2$ and
11536 $t_2=(.b_1b_2\ldots b_{16})_2$, then we will minimize
11537 $a_1b_1a_2b_2\ldots a_{16}b_{16}$, not
11538 $a_1a_2\ldots a_{16}b_1b_2\ldots b_{16}$.
11539 Shuffled order agrees with lexicographic order if all pairs of solutions
11540 $(t_1,t_2)$ and $(t_1',t_2')$ have the property that $t_1<t_1'$ iff
11541 $t_2<t_2'$; but in general, lexicographic order can be quite different,
11542 and the bisection algorithm would be substantially less efficient if it were
11543 constrained by lexicographic order.
11544
11545 For example, suppose that an overlap has been found for $l=3$ and
11546 $(t_1,t_2)= (.101,.011)$ in binary, but that no overlap is produced by
11547 either of the alternatives $(.1010,.0110)$, $(.1010,.0111)$ at level~4.
11548 Then there is probably an intersection in one of the subintervals
11549 $(.1011,.011x)$; but lexicographic order would require us to explore
11550 $(.1010,.1xxx)$ and $(.1011,.00xx)$ and $(.1011,.010x)$ first. We wouldn't
11551 want to store all of the subdivision data for the second path, so the
11552 subdivisions would have to be regenerated many times. Such inefficiencies
11553 would be associated with every `1' in the binary representation of~$t_1$.
11554
11555 @ The subdivision process introduces rounding errors, hence we need to
11556 make a more liberal test for overlap. It is not hard to show that the
11557 computed values of $U_i$ differ from the truth by at most~$l$, on
11558 level~$l$, hence $U\submin$ and $U\submax$ will be at most $3l$ in error.
11559 If $\beta$ is an upper bound on the absolute error in the computed
11560 components of $\Delta=(|delx|,|dely|)$ on level~$l$, we will replace
11561 the test `$X\submin-U\submax\L|delx|$' by the more liberal test
11562 `$X\submin-U\submax\L|delx|+|tol|$', where $|tol|=6l+\beta$.
11563
11564 More accuracy is obtained if we try the algorithm first with |tol=0|;
11565 the more liberal tolerance is used only if an exact approach fails.
11566 It is convenient to do this double-take by letting `3' in the preceding
11567 paragraph be a parameter, which is first 0, then 3.
11568
11569 @<Glob...@>=
11570 unsigned int tol_step; /* either 0 or 3, usually */
11571
11572 @ We shall use an explicit stack to implement the recursive bisection
11573 method described above. The |bisect_stack| array will contain numerous 5-word
11574 packets like $(U_1,U_2,U_3,U\submin,U\submax)$, as well as 20-word packets
11575 comprising the 5-word packets for $U$, $V$, $X$, and~$Y$.
11576
11577 The following macros define the allocation of stack positions to
11578 the quantities needed for bisection-intersection.
11579
11580 @d stack_1(A) mp->bisect_stack[(A)] /* $U_1$, $V_1$, $X_1$, or $Y_1$ */
11581 @d stack_2(A) mp->bisect_stack[(A)+1] /* $U_2$, $V_2$, $X_2$, or $Y_2$ */
11582 @d stack_3(A) mp->bisect_stack[(A)+2] /* $U_3$, $V_3$, $X_3$, or $Y_3$ */
11583 @d stack_min(A) mp->bisect_stack[(A)+3]
11584   /* $U\submin$, $V\submin$, $X\submin$, or $Y\submin$ */
11585 @d stack_max(A) mp->bisect_stack[(A)+4]
11586   /* $U\submax$, $V\submax$, $X\submax$, or $Y\submax$ */
11587 @d int_packets 20 /* number of words to represent $U_k$, $V_k$, $X_k$, and $Y_k$ */
11588 @#
11589 @d u_packet(A) ((A)-5)
11590 @d v_packet(A) ((A)-10)
11591 @d x_packet(A) ((A)-15)
11592 @d y_packet(A) ((A)-20)
11593 @d l_packets (mp->bisect_ptr-int_packets)
11594 @d r_packets mp->bisect_ptr
11595 @d ul_packet u_packet(l_packets) /* base of $U'_k$ variables */
11596 @d vl_packet v_packet(l_packets) /* base of $V'_k$ variables */
11597 @d xl_packet x_packet(l_packets) /* base of $X'_k$ variables */
11598 @d yl_packet y_packet(l_packets) /* base of $Y'_k$ variables */
11599 @d ur_packet u_packet(r_packets) /* base of $U''_k$ variables */
11600 @d vr_packet v_packet(r_packets) /* base of $V''_k$ variables */
11601 @d xr_packet x_packet(r_packets) /* base of $X''_k$ variables */
11602 @d yr_packet y_packet(r_packets) /* base of $Y''_k$ variables */
11603 @#
11604 @d u1l stack_1(ul_packet) /* $U'_1$ */
11605 @d u2l stack_2(ul_packet) /* $U'_2$ */
11606 @d u3l stack_3(ul_packet) /* $U'_3$ */
11607 @d v1l stack_1(vl_packet) /* $V'_1$ */
11608 @d v2l stack_2(vl_packet) /* $V'_2$ */
11609 @d v3l stack_3(vl_packet) /* $V'_3$ */
11610 @d x1l stack_1(xl_packet) /* $X'_1$ */
11611 @d x2l stack_2(xl_packet) /* $X'_2$ */
11612 @d x3l stack_3(xl_packet) /* $X'_3$ */
11613 @d y1l stack_1(yl_packet) /* $Y'_1$ */
11614 @d y2l stack_2(yl_packet) /* $Y'_2$ */
11615 @d y3l stack_3(yl_packet) /* $Y'_3$ */
11616 @d u1r stack_1(ur_packet) /* $U''_1$ */
11617 @d u2r stack_2(ur_packet) /* $U''_2$ */
11618 @d u3r stack_3(ur_packet) /* $U''_3$ */
11619 @d v1r stack_1(vr_packet) /* $V''_1$ */
11620 @d v2r stack_2(vr_packet) /* $V''_2$ */
11621 @d v3r stack_3(vr_packet) /* $V''_3$ */
11622 @d x1r stack_1(xr_packet) /* $X''_1$ */
11623 @d x2r stack_2(xr_packet) /* $X''_2$ */
11624 @d x3r stack_3(xr_packet) /* $X''_3$ */
11625 @d y1r stack_1(yr_packet) /* $Y''_1$ */
11626 @d y2r stack_2(yr_packet) /* $Y''_2$ */
11627 @d y3r stack_3(yr_packet) /* $Y''_3$ */
11628 @#
11629 @d stack_dx mp->bisect_stack[mp->bisect_ptr] /* stacked value of |delx| */
11630 @d stack_dy mp->bisect_stack[mp->bisect_ptr+1] /* stacked value of |dely| */
11631 @d stack_tol mp->bisect_stack[mp->bisect_ptr+2] /* stacked value of |tol| */
11632 @d stack_uv mp->bisect_stack[mp->bisect_ptr+3] /* stacked value of |uv| */
11633 @d stack_xy mp->bisect_stack[mp->bisect_ptr+4] /* stacked value of |xy| */
11634 @d int_increment (int_packets+int_packets+5) /* number of stack words per level */
11635
11636 @<Glob...@>=
11637 integer *bisect_stack;
11638 unsigned int bisect_ptr;
11639
11640 @ @<Allocate or initialize ...@>=
11641 mp->bisect_stack = xmalloc((bistack_size+1),sizeof(integer));
11642
11643 @ @<Dealloc variables@>=
11644 xfree(mp->bisect_stack);
11645
11646 @ @<Check the ``constant''...@>=
11647 if ( int_packets+17*int_increment>bistack_size ) mp->bad=19;
11648
11649 @ Computation of the min and max is a tedious but fairly fast sequence of
11650 instructions; exactly four comparisons are made in each branch.
11651
11652 @d set_min_max(A) 
11653   if ( stack_1((A))<0 ) {
11654     if ( stack_3((A))>=0 ) {
11655       if ( stack_2((A))<0 ) stack_min((A))=stack_1((A))+stack_2((A));
11656       else stack_min((A))=stack_1((A));
11657       stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11658       if ( stack_max((A))<0 ) stack_max((A))=0;
11659     } else { 
11660       stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11661       if ( stack_min((A))>stack_1((A)) ) stack_min((A))=stack_1((A));
11662       stack_max((A))=stack_1((A))+stack_2((A));
11663       if ( stack_max((A))<0 ) stack_max((A))=0;
11664     }
11665   } else if ( stack_3((A))<=0 ) {
11666     if ( stack_2((A))>0 ) stack_max((A))=stack_1((A))+stack_2((A));
11667     else stack_max((A))=stack_1((A));
11668     stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11669     if ( stack_min((A))>0 ) stack_min((A))=0;
11670   } else  { 
11671     stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11672     if ( stack_max((A))<stack_1((A)) ) stack_max((A))=stack_1((A));
11673     stack_min((A))=stack_1((A))+stack_2((A));
11674     if ( stack_min((A))>0 ) stack_min((A))=0;
11675   }
11676
11677 @ It's convenient to keep the current values of $l$, $t_1$, and $t_2$ in
11678 the integer form $2^l+2^lt_1$ and $2^l+2^lt_2$. The |cubic_intersection|
11679 routine uses global variables |cur_t| and |cur_tt| for this purpose;
11680 after successful completion, |cur_t| and |cur_tt| will contain |unity|
11681 plus the |scaled| values of $t_1$ and~$t_2$.
11682
11683 The values of |cur_t| and |cur_tt| will be set to zero if |cubic_intersection|
11684 finds no intersection. The routine gives up and gives an approximate answer
11685 if it has backtracked
11686 more than 5000 times (otherwise there are cases where several minutes
11687 of fruitless computation would be possible).
11688
11689 @d max_patience 5000
11690
11691 @<Glob...@>=
11692 integer cur_t;integer cur_tt; /* controls and results of |cubic_intersection| */
11693 integer time_to_go; /* this many backtracks before giving up */
11694 integer max_t; /* maximum of $2^{l+1}$ so far achieved */
11695
11696 @ The given cubics $B(w_0,w_1,w_2,w_3;t)$ and
11697 $B(z_0,z_1,z_2,z_3;t)$ are specified in adjacent knot nodes |(p,link(p))|
11698 and |(pp,link(pp))|, respectively.
11699
11700 @c void mp_cubic_intersection (MP mp,pointer p, pointer pp) {
11701   pointer q,qq; /* |link(p)|, |link(pp)| */
11702   mp->time_to_go=max_patience; mp->max_t=2;
11703   @<Initialize for intersections at level zero@>;
11704 CONTINUE:
11705   while (1) { 
11706     if ( mp->delx-mp->tol<=stack_max(x_packet(mp->xy))-stack_min(u_packet(mp->uv)))
11707     if ( mp->delx+mp->tol>=stack_min(x_packet(mp->xy))-stack_max(u_packet(mp->uv)))
11708     if ( mp->dely-mp->tol<=stack_max(y_packet(mp->xy))-stack_min(v_packet(mp->uv)))
11709     if ( mp->dely+mp->tol>=stack_min(y_packet(mp->xy))-stack_max(v_packet(mp->uv))) 
11710     { 
11711       if ( mp->cur_t>=mp->max_t ){ 
11712         if ( mp->max_t==two ) { /* we've done 17 bisections */ 
11713            mp->cur_t=halfp(mp->cur_t+1); mp->cur_tt=halfp(mp->cur_tt+1); return;
11714         }
11715         mp->max_t+=mp->max_t; mp->appr_t=mp->cur_t; mp->appr_tt=mp->cur_tt;
11716       }
11717       @<Subdivide for a new level of intersection@>;
11718       goto CONTINUE;
11719     }
11720     if ( mp->time_to_go>0 ) {
11721       decr(mp->time_to_go);
11722     } else { 
11723       while ( mp->appr_t<unity ) { 
11724         mp->appr_t+=mp->appr_t; mp->appr_tt+=mp->appr_tt;
11725       }
11726       mp->cur_t=mp->appr_t; mp->cur_tt=mp->appr_tt; return;
11727     }
11728     @<Advance to the next pair |(cur_t,cur_tt)|@>;
11729   }
11730 }
11731
11732 @ The following variables are global, although they are used only by
11733 |cubic_intersection|, because it is necessary on some machines to
11734 split |cubic_intersection| up into two procedures.
11735
11736 @<Glob...@>=
11737 integer delx;integer dely; /* the components of $\Delta=2^l(w_0-z_0)$ */
11738 integer tol; /* bound on the uncertainly in the overlap test */
11739 unsigned int uv;
11740 unsigned int xy; /* pointers to the current packets of interest */
11741 integer three_l; /* |tol_step| times the bisection level */
11742 integer appr_t;integer appr_tt; /* best approximations known to the answers */
11743
11744 @ We shall assume that the coordinates are sufficiently non-extreme that
11745 integer overflow will not occur.
11746
11747 @<Initialize for intersections at level zero@>=
11748 q=link(p); qq=link(pp); mp->bisect_ptr=int_packets;
11749 u1r=right_x(p)-x_coord(p); u2r=left_x(q)-right_x(p);
11750 u3r=x_coord(q)-left_x(q); set_min_max(ur_packet);
11751 v1r=right_y(p)-y_coord(p); v2r=left_y(q)-right_y(p);
11752 v3r=y_coord(q)-left_y(q); set_min_max(vr_packet);
11753 x1r=right_x(pp)-x_coord(pp); x2r=left_x(qq)-right_x(pp);
11754 x3r=x_coord(qq)-left_x(qq); set_min_max(xr_packet);
11755 y1r=right_y(pp)-y_coord(pp); y2r=left_y(qq)-right_y(pp);
11756 y3r=y_coord(qq)-left_y(qq); set_min_max(yr_packet);
11757 mp->delx=x_coord(p)-x_coord(pp); mp->dely=y_coord(p)-y_coord(pp);
11758 mp->tol=0; mp->uv=r_packets; mp->xy=r_packets; 
11759 mp->three_l=0; mp->cur_t=1; mp->cur_tt=1
11760
11761 @ @<Subdivide for a new level of intersection@>=
11762 stack_dx=mp->delx; stack_dy=mp->dely; stack_tol=mp->tol; 
11763 stack_uv=mp->uv; stack_xy=mp->xy;
11764 mp->bisect_ptr=mp->bisect_ptr+int_increment;
11765 mp->cur_t+=mp->cur_t; mp->cur_tt+=mp->cur_tt;
11766 u1l=stack_1(u_packet(mp->uv)); u3r=stack_3(u_packet(mp->uv));
11767 u2l=half(u1l+stack_2(u_packet(mp->uv)));
11768 u2r=half(u3r+stack_2(u_packet(mp->uv)));
11769 u3l=half(u2l+u2r); u1r=u3l;
11770 set_min_max(ul_packet); set_min_max(ur_packet);
11771 v1l=stack_1(v_packet(mp->uv)); v3r=stack_3(v_packet(mp->uv));
11772 v2l=half(v1l+stack_2(v_packet(mp->uv)));
11773 v2r=half(v3r+stack_2(v_packet(mp->uv)));
11774 v3l=half(v2l+v2r); v1r=v3l;
11775 set_min_max(vl_packet); set_min_max(vr_packet);
11776 x1l=stack_1(x_packet(mp->xy)); x3r=stack_3(x_packet(mp->xy));
11777 x2l=half(x1l+stack_2(x_packet(mp->xy)));
11778 x2r=half(x3r+stack_2(x_packet(mp->xy)));
11779 x3l=half(x2l+x2r); x1r=x3l;
11780 set_min_max(xl_packet); set_min_max(xr_packet);
11781 y1l=stack_1(y_packet(mp->xy)); y3r=stack_3(y_packet(mp->xy));
11782 y2l=half(y1l+stack_2(y_packet(mp->xy)));
11783 y2r=half(y3r+stack_2(y_packet(mp->xy)));
11784 y3l=half(y2l+y2r); y1r=y3l;
11785 set_min_max(yl_packet); set_min_max(yr_packet);
11786 mp->uv=l_packets; mp->xy=l_packets;
11787 mp->delx+=mp->delx; mp->dely+=mp->dely;
11788 mp->tol=mp->tol-mp->three_l+mp->tol_step; 
11789 mp->tol+=mp->tol; mp->three_l=mp->three_l+mp->tol_step
11790
11791 @ @<Advance to the next pair |(cur_t,cur_tt)|@>=
11792 NOT_FOUND: 
11793 if ( odd(mp->cur_tt) ) {
11794   if ( odd(mp->cur_t) ) {
11795      @<Descend to the previous level and |goto not_found|@>;
11796   } else { 
11797     incr(mp->cur_t);
11798     mp->delx=mp->delx+stack_1(u_packet(mp->uv))+stack_2(u_packet(mp->uv))
11799       +stack_3(u_packet(mp->uv));
11800     mp->dely=mp->dely+stack_1(v_packet(mp->uv))+stack_2(v_packet(mp->uv))
11801       +stack_3(v_packet(mp->uv));
11802     mp->uv=mp->uv+int_packets; /* switch from |l_packet| to |r_packet| */
11803     decr(mp->cur_tt); mp->xy=mp->xy-int_packets; 
11804          /* switch from |r_packet| to |l_packet| */
11805     mp->delx=mp->delx+stack_1(x_packet(mp->xy))+stack_2(x_packet(mp->xy))
11806       +stack_3(x_packet(mp->xy));
11807     mp->dely=mp->dely+stack_1(y_packet(mp->xy))+stack_2(y_packet(mp->xy))
11808       +stack_3(y_packet(mp->xy));
11809   }
11810 } else { 
11811   incr(mp->cur_tt); mp->tol=mp->tol+mp->three_l;
11812   mp->delx=mp->delx-stack_1(x_packet(mp->xy))-stack_2(x_packet(mp->xy))
11813     -stack_3(x_packet(mp->xy));
11814   mp->dely=mp->dely-stack_1(y_packet(mp->xy))-stack_2(y_packet(mp->xy))
11815     -stack_3(y_packet(mp->xy));
11816   mp->xy=mp->xy+int_packets; /* switch from |l_packet| to |r_packet| */
11817 }
11818
11819 @ @<Descend to the previous level...@>=
11820
11821   mp->cur_t=halfp(mp->cur_t); mp->cur_tt=halfp(mp->cur_tt);
11822   if ( mp->cur_t==0 ) return;
11823   mp->bisect_ptr=mp->bisect_ptr-int_increment; 
11824   mp->three_l=mp->three_l-mp->tol_step;
11825   mp->delx=stack_dx; mp->dely=stack_dy; mp->tol=stack_tol; 
11826   mp->uv=stack_uv; mp->xy=stack_xy;
11827   goto NOT_FOUND;
11828 }
11829
11830 @ The |path_intersection| procedure is much simpler.
11831 It invokes |cubic_intersection| in lexicographic order until finding a
11832 pair of cubics that intersect. The final intersection times are placed in
11833 |cur_t| and~|cur_tt|.
11834
11835 @c void mp_path_intersection (MP mp,pointer h, pointer hh) {
11836   pointer p,pp; /* link registers that traverse the given paths */
11837   integer n,nn; /* integer parts of intersection times, minus |unity| */
11838   @<Change one-point paths into dead cycles@>;
11839   mp->tol_step=0;
11840   do {  
11841     n=-unity; p=h;
11842     do {  
11843       if ( right_type(p)!=mp_endpoint ) { 
11844         nn=-unity; pp=hh;
11845         do {  
11846           if ( right_type(pp)!=mp_endpoint )  { 
11847             mp_cubic_intersection(mp, p,pp);
11848             if ( mp->cur_t>0 ) { 
11849               mp->cur_t=mp->cur_t+n; mp->cur_tt=mp->cur_tt+nn; 
11850               return;
11851             }
11852           }
11853           nn=nn+unity; pp=link(pp);
11854         } while (pp!=hh);
11855       }
11856       n=n+unity; p=link(p);
11857     } while (p!=h);
11858     mp->tol_step=mp->tol_step+3;
11859   } while (mp->tol_step<=3);
11860   mp->cur_t=-unity; mp->cur_tt=-unity;
11861 }
11862
11863 @ @<Change one-point paths...@>=
11864 if ( right_type(h)==mp_endpoint ) {
11865   right_x(h)=x_coord(h); left_x(h)=x_coord(h);
11866   right_y(h)=y_coord(h); left_y(h)=y_coord(h); right_type(h)=mp_explicit;
11867 }
11868 if ( right_type(hh)==mp_endpoint ) {
11869   right_x(hh)=x_coord(hh); left_x(hh)=x_coord(hh);
11870   right_y(hh)=y_coord(hh); left_y(hh)=y_coord(hh); right_type(hh)=mp_explicit;
11871 }
11872
11873 @* \[24] Dynamic linear equations.
11874 \MP\ users define variables implicitly by stating equations that should be
11875 satisfied; the computer is supposed to be smart enough to solve those equations.
11876 And indeed, the computer tries valiantly to do so, by distinguishing five
11877 different types of numeric values:
11878
11879 \smallskip\hang
11880 |type(p)=mp_known| is the nice case, when |value(p)| is the |scaled| value
11881 of the variable whose address is~|p|.
11882
11883 \smallskip\hang
11884 |type(p)=mp_dependent| means that |value(p)| is not present, but |dep_list(p)|
11885 points to a {\sl dependency list\/} that expresses the value of variable~|p|
11886 as a |scaled| number plus a sum of independent variables with |fraction|
11887 coefficients.
11888
11889 \smallskip\hang
11890 |type(p)=mp_independent| means that |value(p)=64s+m|, where |s>0| is a ``serial
11891 number'' reflecting the time this variable was first used in an equation;
11892 also |0<=m<64|, and each dependent variable
11893 that refers to this one is actually referring to the future value of
11894 this variable times~$2^m$. (Usually |m=0|, but higher degrees of
11895 scaling are sometimes needed to keep the coefficients in dependency lists
11896 from getting too large. The value of~|m| will always be even.)
11897
11898 \smallskip\hang
11899 |type(p)=mp_numeric_type| means that variable |p| hasn't appeared in an
11900 equation before, but it has been explicitly declared to be numeric.
11901
11902 \smallskip\hang
11903 |type(p)=undefined| means that variable |p| hasn't appeared before.
11904
11905 \smallskip\noindent
11906 We have actually discussed these five types in the reverse order of their
11907 history during a computation: Once |known|, a variable never again
11908 becomes |dependent|; once |dependent|, it almost never again becomes
11909 |mp_independent|; once |mp_independent|, it never again becomes |mp_numeric_type|;
11910 and once |mp_numeric_type|, it never again becomes |undefined| (except
11911 of course when the user specifically decides to scrap the old value
11912 and start again). A backward step may, however, take place: Sometimes
11913 a |dependent| variable becomes |mp_independent| again, when one of the
11914 independent variables it depends on is reverting to |undefined|.
11915
11916
11917 The next patch detects overflow of independent-variable serial
11918 numbers. Diagnosed and patched by Thorsten Dahlheimer.
11919
11920 @d s_scale 64 /* the serial numbers are multiplied by this factor */
11921 @d max_indep_vars 0177777777 /* $2^{25}-1$ */
11922 @d max_serial_no 017777777700 /* |max_indep_vars*s_scale| */
11923 @d new_indep(A)  /* create a new independent variable */
11924   { if ( mp->serial_no==max_serial_no )
11925     mp_fatal_error(mp, "variable instance identifiers exhausted");
11926   type((A))=mp_independent; mp->serial_no=mp->serial_no+s_scale;
11927   value((A))=mp->serial_no;
11928   }
11929
11930 @<Glob...@>=
11931 integer serial_no; /* the most recent serial number, times |s_scale| */
11932
11933 @ @<Make variable |q+s| newly independent@>=new_indep(q+s)
11934
11935 @ But how are dependency lists represented? It's simple: The linear combination
11936 $\alpha_1v_1+\cdots+\alpha_kv_k+\beta$ appears in |k+1| value nodes. If
11937 |q=dep_list(p)| points to this list, and if |k>0|, then |value(q)=
11938 @t$\alpha_1$@>| (which is a |fraction|); |info(q)| points to the location
11939 of $\alpha_1$; and |link(p)| points to the dependency list
11940 $\alpha_2v_2+\cdots+\alpha_kv_k+\beta$. On the other hand if |k=0|,
11941 then |value(q)=@t$\beta$@>| (which is |scaled|) and |info(q)=null|.
11942 The independent variables $v_1$, \dots,~$v_k$ have been sorted so that
11943 they appear in decreasing order of their |value| fields (i.e., of
11944 their serial numbers). \ (It is convenient to use decreasing order,
11945 since |value(null)=0|. If the independent variables were not sorted by
11946 serial number but by some other criterion, such as their location in |mem|,
11947 the equation-solving mechanism would be too system-dependent, because
11948 the ordering can affect the computed results.)
11949
11950 The |link| field in the node that contains the constant term $\beta$ is
11951 called the {\sl final link\/} of the dependency list. \MP\ maintains
11952 a doubly-linked master list of all dependency lists, in terms of a permanently
11953 allocated node
11954 in |mem| called |dep_head|. If there are no dependencies, we have
11955 |link(dep_head)=dep_head| and |prev_dep(dep_head)=dep_head|;
11956 otherwise |link(dep_head)| points to the first dependent variable, say~|p|,
11957 and |prev_dep(p)=dep_head|. We have |type(p)=mp_dependent|, and |dep_list(p)|
11958 points to its dependency list. If the final link of that dependency list
11959 occurs in location~|q|, then |link(q)| points to the next dependent
11960 variable (say~|r|); and we have |prev_dep(r)=q|, etc.
11961
11962 @d dep_list(A) link(value_loc((A)))
11963   /* half of the |value| field in a |dependent| variable */
11964 @d prev_dep(A) info(value_loc((A)))
11965   /* the other half; makes a doubly linked list */
11966 @d dep_node_size 2 /* the number of words per dependency node */
11967
11968 @<Initialize table entries...@>= mp->serial_no=0;
11969 link(dep_head)=dep_head; prev_dep(dep_head)=dep_head;
11970 info(dep_head)=null; dep_list(dep_head)=null;
11971
11972 @ Actually the description above contains a little white lie. There's
11973 another kind of variable called |mp_proto_dependent|, which is
11974 just like a |dependent| one except that the $\alpha$ coefficients
11975 in its dependency list are |scaled| instead of being fractions.
11976 Proto-dependency lists are mixed with dependency lists in the
11977 nodes reachable from |dep_head|.
11978
11979 @ Here is a procedure that prints a dependency list in symbolic form.
11980 The second parameter should be either |dependent| or |mp_proto_dependent|,
11981 to indicate the scaling of the coefficients.
11982
11983 @<Declare subroutines for printing expressions@>=
11984 void mp_print_dependency (MP mp,pointer p, small_number t) {
11985   integer v; /* a coefficient */
11986   pointer pp,q; /* for list manipulation */
11987   pp=p;
11988   while (1) { 
11989     v=abs(value(p)); q=info(p);
11990     if ( q==null ) { /* the constant term */
11991       if ( (v!=0)||(p==pp) ) {
11992          if ( value(p)>0 ) if ( p!=pp ) mp_print_char(mp, '+');
11993          mp_print_scaled(mp, value(p));
11994       }
11995       return;
11996     }
11997     @<Print the coefficient, unless it's $\pm1.0$@>;
11998     if ( type(q)!=mp_independent ) mp_confusion(mp, "dep");
11999 @:this can't happen dep}{\quad dep@>
12000     mp_print_variable_name(mp, q); v=value(q) % s_scale;
12001     while ( v>0 ) { mp_print(mp, "*4"); v=v-2; }
12002     p=link(p);
12003   }
12004 }
12005
12006 @ @<Print the coefficient, unless it's $\pm1.0$@>=
12007 if ( value(p)<0 ) mp_print_char(mp, '-');
12008 else if ( p!=pp ) mp_print_char(mp, '+');
12009 if ( t==mp_dependent ) v=mp_round_fraction(mp, v);
12010 if ( v!=unity ) mp_print_scaled(mp, v)
12011
12012 @ The maximum absolute value of a coefficient in a given dependency list
12013 is returned by the following simple function.
12014
12015 @c fraction mp_max_coef (MP mp,pointer p) {
12016   fraction x; /* the maximum so far */
12017   x=0;
12018   while ( info(p)!=null ) {
12019     if ( abs(value(p))>x ) x=abs(value(p));
12020     p=link(p);
12021   }
12022   return x;
12023 }
12024
12025 @ One of the main operations needed on dependency lists is to add a multiple
12026 of one list to the other; we call this |p_plus_fq|, where |p| and~|q| point
12027 to dependency lists and |f| is a fraction.
12028
12029 If the coefficient of any independent variable becomes |coef_bound| or
12030 more, in absolute value, this procedure changes the type of that variable
12031 to `|independent_needing_fix|', and sets the global variable |fix_needed|
12032 to~|true|. The value of $|coef_bound|=\mu$ is chosen so that
12033 $\mu^2+\mu<8$; this means that the numbers we deal with won't
12034 get too large. (Instead of the ``optimum'' $\mu=(\sqrt{33}-1)/2\approx
12035 2.3723$, the safer value 7/3 is taken as the threshold.)
12036
12037 The changes mentioned in the preceding paragraph are actually done only if
12038 the global variable |watch_coefs| is |true|. But it usually is; in fact,
12039 it is |false| only when \MP\ is making a dependency list that will soon
12040 be equated to zero.
12041
12042 Several procedures that act on dependency lists, including |p_plus_fq|,
12043 set the global variable |dep_final| to the final (constant term) node of
12044 the dependency list that they produce.
12045
12046 @d coef_bound 04525252525 /* |fraction| approximation to 7/3 */
12047 @d independent_needing_fix 0
12048
12049 @<Glob...@>=
12050 boolean fix_needed; /* does at least one |independent| variable need scaling? */
12051 boolean watch_coefs; /* should we scale coefficients that exceed |coef_bound|? */
12052 pointer dep_final; /* location of the constant term and final link */
12053
12054 @ @<Set init...@>=
12055 mp->fix_needed=false; mp->watch_coefs=true;
12056
12057 @ The |p_plus_fq| procedure has a fourth parameter, |t|, that should be
12058 set to |mp_proto_dependent| if |p| is a proto-dependency list. In this
12059 case |f| will be |scaled|, not a |fraction|. Similarly, the fifth parameter~|tt|
12060 should be |mp_proto_dependent| if |q| is a proto-dependency list.
12061
12062 List |q| is unchanged by the operation; but list |p| is totally destroyed.
12063
12064 The final link of the dependency list or proto-dependency list returned
12065 by |p_plus_fq| is the same as the original final link of~|p|. Indeed, the
12066 constant term of the result will be located in the same |mem| location
12067 as the original constant term of~|p|.
12068
12069 Coefficients of the result are assumed to be zero if they are less than
12070 a certain threshold. This compensates for inevitable rounding errors,
12071 and tends to make more variables `|known|'. The threshold is approximately
12072 $10^{-5}$ in the case of normal dependency lists, $10^{-4}$ for
12073 proto-dependencies.
12074
12075 @d fraction_threshold 2685 /* a |fraction| coefficient less than this is zeroed */
12076 @d half_fraction_threshold 1342 /* half of |fraction_threshold| */
12077 @d scaled_threshold 8 /* a |scaled| coefficient less than this is zeroed */
12078 @d half_scaled_threshold 4 /* half of |scaled_threshold| */
12079
12080 @<Declare basic dependency-list subroutines@>=
12081 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
12082                       pointer q, small_number t, small_number tt) ;
12083
12084 @ @c
12085 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
12086                       pointer q, small_number t, small_number tt) {
12087   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
12088   pointer r,s; /* for list manipulation */
12089   integer mp_threshold; /* defines a neighborhood of zero */
12090   integer v; /* temporary register */
12091   if ( t==mp_dependent ) mp_threshold=fraction_threshold;
12092   else mp_threshold=scaled_threshold;
12093   r=temp_head; pp=info(p); qq=info(q);
12094   while (1) {
12095     if ( pp==qq ) {
12096       if ( pp==null ) {
12097        break;
12098       } else {
12099         @<Contribute a term from |p|, plus |f| times the
12100           corresponding term from |q|@>
12101       }
12102     } else if ( value(pp)<value(qq) ) {
12103       @<Contribute a term from |q|, multiplied by~|f|@>
12104     } else { 
12105      link(r)=p; r=p; p=link(p); pp=info(p);
12106     }
12107   }
12108   if ( t==mp_dependent )
12109     value(p)=mp_slow_add(mp, value(p),mp_take_fraction(mp, value(q),f));
12110   else  
12111     value(p)=mp_slow_add(mp, value(p),mp_take_scaled(mp, value(q),f));
12112   link(r)=p; mp->dep_final=p; 
12113   return link(temp_head);
12114 }
12115
12116 @ @<Contribute a term from |p|, plus |f|...@>=
12117
12118   if ( tt==mp_dependent ) v=value(p)+mp_take_fraction(mp, f,value(q));
12119   else v=value(p)+mp_take_scaled(mp, f,value(q));
12120   value(p)=v; s=p; p=link(p);
12121   if ( abs(v)<mp_threshold ) {
12122     mp_free_node(mp, s,dep_node_size);
12123   } else {
12124     if ( (abs(v)>=coef_bound)  && mp->watch_coefs ) { 
12125       type(qq)=independent_needing_fix; mp->fix_needed=true;
12126     }
12127     link(r)=s; r=s;
12128   };
12129   pp=info(p); q=link(q); qq=info(q);
12130 }
12131
12132 @ @<Contribute a term from |q|, multiplied by~|f|@>=
12133
12134   if ( tt==mp_dependent ) v=mp_take_fraction(mp, f,value(q));
12135   else v=mp_take_scaled(mp, f,value(q));
12136   if ( abs(v)>halfp(mp_threshold) ) { 
12137     s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=v;
12138     if ( (abs(v)>=coef_bound) && mp->watch_coefs ) { 
12139       type(qq)=independent_needing_fix; mp->fix_needed=true;
12140     }
12141     link(r)=s; r=s;
12142   }
12143   q=link(q); qq=info(q);
12144 }
12145
12146 @ It is convenient to have another subroutine for the special case
12147 of |p_plus_fq| when |f=1.0|. In this routine lists |p| and |q| are
12148 both of the same type~|t| (either |dependent| or |mp_proto_dependent|).
12149
12150 @c pointer mp_p_plus_q (MP mp,pointer p, pointer q, small_number t) {
12151   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
12152   pointer r,s; /* for list manipulation */
12153   integer mp_threshold; /* defines a neighborhood of zero */
12154   integer v; /* temporary register */
12155   if ( t==mp_dependent ) mp_threshold=fraction_threshold;
12156   else mp_threshold=scaled_threshold;
12157   r=temp_head; pp=info(p); qq=info(q);
12158   while (1) {
12159     if ( pp==qq ) {
12160       if ( pp==null ) {
12161         break;
12162       } else {
12163         @<Contribute a term from |p|, plus the
12164           corresponding term from |q|@>
12165       }
12166     } else if ( value(pp)<value(qq) ) {
12167       s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=value(q);
12168       q=link(q); qq=info(q); link(r)=s; r=s;
12169     } else { 
12170       link(r)=p; r=p; p=link(p); pp=info(p);
12171     }
12172   }
12173   value(p)=mp_slow_add(mp, value(p),value(q));
12174   link(r)=p; mp->dep_final=p; 
12175   return link(temp_head);
12176 }
12177
12178 @ @<Contribute a term from |p|, plus the...@>=
12179
12180   v=value(p)+value(q);
12181   value(p)=v; s=p; p=link(p); pp=info(p);
12182   if ( abs(v)<mp_threshold ) {
12183     mp_free_node(mp, s,dep_node_size);
12184   } else { 
12185     if ( (abs(v)>=coef_bound ) && mp->watch_coefs ) {
12186       type(qq)=independent_needing_fix; mp->fix_needed=true;
12187     }
12188     link(r)=s; r=s;
12189   }
12190   q=link(q); qq=info(q);
12191 }
12192
12193 @ A somewhat simpler routine will multiply a dependency list
12194 by a given constant~|v|. The constant is either a |fraction| less than
12195 |fraction_one|, or it is |scaled|. In the latter case we might be forced to
12196 convert a dependency list to a proto-dependency list.
12197 Parameters |t0| and |t1| are the list types before and after;
12198 they should agree unless |t0=mp_dependent| and |t1=mp_proto_dependent|
12199 and |v_is_scaled=true|.
12200
12201 @c pointer mp_p_times_v (MP mp,pointer p, integer v, small_number t0,
12202                          small_number t1, boolean v_is_scaled) {
12203   pointer r,s; /* for list manipulation */
12204   integer w; /* tentative coefficient */
12205   integer mp_threshold;
12206   boolean scaling_down;
12207   if ( t0!=t1 ) scaling_down=true; else scaling_down=! v_is_scaled;
12208   if ( t1==mp_dependent ) mp_threshold=half_fraction_threshold;
12209   else mp_threshold=half_scaled_threshold;
12210   r=temp_head;
12211   while ( info(p)!=null ) {    
12212     if ( scaling_down ) w=mp_take_fraction(mp, v,value(p));
12213     else w=mp_take_scaled(mp, v,value(p));
12214     if ( abs(w)<=mp_threshold ) { 
12215       s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
12216     } else {
12217       if ( abs(w)>=coef_bound ) { 
12218         mp->fix_needed=true; type(info(p))=independent_needing_fix;
12219       }
12220       link(r)=p; r=p; value(p)=w; p=link(p);
12221     }
12222   }
12223   link(r)=p;
12224   if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
12225   else value(p)=mp_take_fraction(mp, value(p),v);
12226   return link(temp_head);
12227 };
12228
12229 @ Similarly, we sometimes need to divide a dependency list
12230 by a given |scaled| constant.
12231
12232 @<Declare basic dependency-list subroutines@>=
12233 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number 
12234   t0, small_number t1) ;
12235
12236 @ @c
12237 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number 
12238   t0, small_number t1) {
12239   pointer r,s; /* for list manipulation */
12240   integer w; /* tentative coefficient */
12241   integer mp_threshold;
12242   boolean scaling_down;
12243   if ( t0!=t1 ) scaling_down=true; else scaling_down=false;
12244   if ( t1==mp_dependent ) mp_threshold=half_fraction_threshold;
12245   else mp_threshold=half_scaled_threshold;
12246   r=temp_head;
12247   while ( info( p)!=null ) {
12248     if ( scaling_down ) {
12249       if ( abs(v)<02000000 ) w=mp_make_scaled(mp, value(p),v*010000);
12250       else w=mp_make_scaled(mp, mp_round_fraction(mp, value(p)),v);
12251     } else {
12252       w=mp_make_scaled(mp, value(p),v);
12253     }
12254     if ( abs(w)<=mp_threshold ) {
12255       s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
12256     } else { 
12257       if ( abs(w)>=coef_bound ) {
12258          mp->fix_needed=true; type(info(p))=independent_needing_fix;
12259       }
12260       link(r)=p; r=p; value(p)=w; p=link(p);
12261     }
12262   }
12263   link(r)=p; value(p)=mp_make_scaled(mp, value(p),v);
12264   return link(temp_head);
12265 };
12266
12267 @ Here's another utility routine for dependency lists. When an independent
12268 variable becomes dependent, we want to remove it from all existing
12269 dependencies. The |p_with_x_becoming_q| function computes the
12270 dependency list of~|p| after variable~|x| has been replaced by~|q|.
12271
12272 This procedure has basically the same calling conventions as |p_plus_fq|:
12273 List~|q| is unchanged; list~|p| is destroyed; the constant node and the
12274 final link are inherited from~|p|; and the fourth parameter tells whether
12275 or not |p| is |mp_proto_dependent|. However, the global variable |dep_final|
12276 is not altered if |x| does not occur in list~|p|.
12277
12278 @c pointer mp_p_with_x_becoming_q (MP mp,pointer p,
12279            pointer x, pointer q, small_number t) {
12280   pointer r,s; /* for list manipulation */
12281   integer v; /* coefficient of |x| */
12282   integer sx; /* serial number of |x| */
12283   s=p; r=temp_head; sx=value(x);
12284   while ( value(info(s))>sx ) { r=s; s=link(s); };
12285   if ( info(s)!=x ) { 
12286     return p;
12287   } else { 
12288     link(temp_head)=p; link(r)=link(s); v=value(s);
12289     mp_free_node(mp, s,dep_node_size);
12290     return mp_p_plus_fq(mp, link(temp_head),v,q,t,mp_dependent);
12291   }
12292 }
12293
12294 @ Here's a simple procedure that reports an error when a variable
12295 has just received a known value that's out of the required range.
12296
12297 @<Declare basic dependency-list subroutines@>=
12298 void mp_val_too_big (MP mp,scaled x) ;
12299
12300 @ @c void mp_val_too_big (MP mp,scaled x) { 
12301   if ( mp->internal[mp_warning_check]>0 ) { 
12302     print_err("Value is too large ("); mp_print_scaled(mp, x); mp_print_char(mp, ')');
12303 @.Value is too large@>
12304     help4("The equation I just processed has given some variable")
12305       ("a value of 4096 or more. Continue and I'll try to cope")
12306       ("with that big value; but it might be dangerous.")
12307       ("(Set warningcheck:=0 to suppress this message.)");
12308     mp_error(mp);
12309   }
12310 }
12311
12312 @ When a dependent variable becomes known, the following routine
12313 removes its dependency list. Here |p| points to the variable, and
12314 |q| points to the dependency list (which is one node long).
12315
12316 @<Declare basic dependency-list subroutines@>=
12317 void mp_make_known (MP mp,pointer p, pointer q) ;
12318
12319 @ @c void mp_make_known (MP mp,pointer p, pointer q) {
12320   int t; /* the previous type */
12321   prev_dep(link(q))=prev_dep(p);
12322   link(prev_dep(p))=link(q); t=type(p);
12323   type(p)=mp_known; value(p)=value(q); mp_free_node(mp, q,dep_node_size);
12324   if ( abs(value(p))>=fraction_one ) mp_val_too_big(mp, value(p));
12325   if (( mp->internal[mp_tracing_equations]>0) && mp_interesting(mp, p) ) {
12326     mp_begin_diagnostic(mp); mp_print_nl(mp, "#### ");
12327 @:]]]\#\#\#\#_}{\.{\#\#\#\#}@>
12328     mp_print_variable_name(mp, p); 
12329     mp_print_char(mp, '='); mp_print_scaled(mp, value(p));
12330     mp_end_diagnostic(mp, false);
12331   }
12332   if (( mp->cur_exp==p ) && mp->cur_type==t ) {
12333     mp->cur_type=mp_known; mp->cur_exp=value(p);
12334     mp_free_node(mp, p,value_node_size);
12335   }
12336 }
12337
12338 @ The |fix_dependencies| routine is called into action when |fix_needed|
12339 has been triggered. The program keeps a list~|s| of independent variables
12340 whose coefficients must be divided by~4.
12341
12342 In unusual cases, this fixup process might reduce one or more coefficients
12343 to zero, so that a variable will become known more or less by default.
12344
12345 @<Declare basic dependency-list subroutines@>=
12346 void mp_fix_dependencies (MP mp);
12347
12348 @ @c void mp_fix_dependencies (MP mp) {
12349   pointer p,q,r,s,t; /* list manipulation registers */
12350   pointer x; /* an independent variable */
12351   r=link(dep_head); s=null;
12352   while ( r!=dep_head ){ 
12353     t=r;
12354     @<Run through the dependency list for variable |t|, fixing
12355       all nodes, and ending with final link~|q|@>;
12356     r=link(q);
12357     if ( q==dep_list(t) ) mp_make_known(mp, t,q);
12358   }
12359   while ( s!=null ) { 
12360     p=link(s); x=info(s); free_avail(s); s=p;
12361     type(x)=mp_independent; value(x)=value(x)+2;
12362   }
12363   mp->fix_needed=false;
12364 }
12365
12366 @ @d independent_being_fixed 1 /* this variable already appears in |s| */
12367
12368 @<Run through the dependency list for variable |t|...@>=
12369 r=value_loc(t); /* |link(r)=dep_list(t)| */
12370 while (1) { 
12371   q=link(r); x=info(q);
12372   if ( x==null ) break;
12373   if ( type(x)<=independent_being_fixed ) {
12374     if ( type(x)<independent_being_fixed ) {
12375       p=mp_get_avail(mp); link(p)=s; s=p;
12376       info(s)=x; type(x)=independent_being_fixed;
12377     }
12378     value(q)=value(q) / 4;
12379     if ( value(q)==0 ) {
12380       link(r)=link(q); mp_free_node(mp, q,dep_node_size); q=r;
12381     }
12382   }
12383   r=q;
12384 }
12385
12386
12387 @ The |new_dep| routine installs a dependency list~|p| into the value node~|q|,
12388 linking it into the list of all known dependencies. We assume that
12389 |dep_final| points to the final node of list~|p|.
12390
12391 @c void mp_new_dep (MP mp,pointer q, pointer p) {
12392   pointer r; /* what used to be the first dependency */
12393   dep_list(q)=p; prev_dep(q)=dep_head;
12394   r=link(dep_head); link(mp->dep_final)=r; prev_dep(r)=mp->dep_final;
12395   link(dep_head)=q;
12396 }
12397
12398 @ Here is one of the ways a dependency list gets started.
12399 The |const_dependency| routine produces a list that has nothing but
12400 a constant term.
12401
12402 @c pointer mp_const_dependency (MP mp, scaled v) {
12403   mp->dep_final=mp_get_node(mp, dep_node_size);
12404   value(mp->dep_final)=v; info(mp->dep_final)=null;
12405   return mp->dep_final;
12406 }
12407
12408 @ And here's a more interesting way to start a dependency list from scratch:
12409 The parameter to |single_dependency| is the location of an
12410 independent variable~|x|, and the result is the simple dependency list
12411 `|x+0|'.
12412
12413 In the unlikely event that the given independent variable has been doubled so
12414 often that we can't refer to it with a nonzero coefficient,
12415 |single_dependency| returns the simple list `0'.  This case can be
12416 recognized by testing that the returned list pointer is equal to
12417 |dep_final|.
12418
12419 @c pointer mp_single_dependency (MP mp,pointer p) {
12420   pointer q; /* the new dependency list */
12421   integer m; /* the number of doublings */
12422   m=value(p) % s_scale;
12423   if ( m>28 ) {
12424     return mp_const_dependency(mp, 0);
12425   } else { 
12426     q=mp_get_node(mp, dep_node_size);
12427     value(q)=two_to_the(28-m); info(q)=p;
12428     link(q)=mp_const_dependency(mp, 0);
12429     return q;
12430   }
12431 }
12432
12433 @ We sometimes need to make an exact copy of a dependency list.
12434
12435 @c pointer mp_copy_dep_list (MP mp,pointer p) {
12436   pointer q; /* the new dependency list */
12437   q=mp_get_node(mp, dep_node_size); mp->dep_final=q;
12438   while (1) { 
12439     info(mp->dep_final)=info(p); value(mp->dep_final)=value(p);
12440     if ( info(mp->dep_final)==null ) break;
12441     link(mp->dep_final)=mp_get_node(mp, dep_node_size);
12442     mp->dep_final=link(mp->dep_final); p=link(p);
12443   }
12444   return q;
12445 }
12446
12447 @ But how do variables normally become known? Ah, now we get to the heart of the
12448 equation-solving mechanism. The |linear_eq| procedure is given a |dependent|
12449 or |mp_proto_dependent| list,~|p|, in which at least one independent variable
12450 appears. It equates this list to zero, by choosing an independent variable
12451 with the largest coefficient and making it dependent on the others. The
12452 newly dependent variable is eliminated from all current dependencies,
12453 thereby possibly making other dependent variables known.
12454
12455 The given list |p| is, of course, totally destroyed by all this processing.
12456
12457 @c void mp_linear_eq (MP mp, pointer p, small_number t) {
12458   pointer q,r,s; /* for link manipulation */
12459   pointer x; /* the variable that loses its independence */
12460   integer n; /* the number of times |x| had been halved */
12461   integer v; /* the coefficient of |x| in list |p| */
12462   pointer prev_r; /* lags one step behind |r| */
12463   pointer final_node; /* the constant term of the new dependency list */
12464   integer w; /* a tentative coefficient */
12465    @<Find a node |q| in list |p| whose coefficient |v| is largest@>;
12466   x=info(q); n=value(x) % s_scale;
12467   @<Divide list |p| by |-v|, removing node |q|@>;
12468   if ( mp->internal[mp_tracing_equations]>0 ) {
12469     @<Display the new dependency@>;
12470   }
12471   @<Simplify all existing dependencies by substituting for |x|@>;
12472   @<Change variable |x| from |independent| to |dependent| or |known|@>;
12473   if ( mp->fix_needed ) mp_fix_dependencies(mp);
12474 }
12475
12476 @ @<Find a node |q| in list |p| whose coefficient |v| is largest@>=
12477 q=p; r=link(p); v=value(q);
12478 while ( info(r)!=null ) { 
12479   if ( abs(value(r))>abs(v) ) { q=r; v=value(r); };
12480   r=link(r);
12481 }
12482
12483 @ Here we want to change the coefficients from |scaled| to |fraction|,
12484 except in the constant term. In the common case of a trivial equation
12485 like `\.{x=3.14}', we will have |v=-fraction_one|, |q=p|, and |t=mp_dependent|.
12486
12487 @<Divide list |p| by |-v|, removing node |q|@>=
12488 s=temp_head; link(s)=p; r=p;
12489 do { 
12490   if ( r==q ) {
12491     link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12492   } else  { 
12493     w=mp_make_fraction(mp, value(r),v);
12494     if ( abs(w)<=half_fraction_threshold ) {
12495       link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12496     } else { 
12497       value(r)=-w; s=r;
12498     }
12499   }
12500   r=link(s);
12501 } while (info(r)!=null);
12502 if ( t==mp_proto_dependent ) {
12503   value(r)=-mp_make_scaled(mp, value(r),v);
12504 } else if ( v!=-fraction_one ) {
12505   value(r)=-mp_make_fraction(mp, value(r),v);
12506 }
12507 final_node=r; p=link(temp_head)
12508
12509 @ @<Display the new dependency@>=
12510 if ( mp_interesting(mp, x) ) {
12511   mp_begin_diagnostic(mp); mp_print_nl(mp, "## "); 
12512   mp_print_variable_name(mp, x);
12513 @:]]]\#\#_}{\.{\#\#}@>
12514   w=n;
12515   while ( w>0 ) { mp_print(mp, "*4"); w=w-2;  };
12516   mp_print_char(mp, '='); mp_print_dependency(mp, p,mp_dependent); 
12517   mp_end_diagnostic(mp, false);
12518 }
12519
12520 @ @<Simplify all existing dependencies by substituting for |x|@>=
12521 prev_r=dep_head; r=link(dep_head);
12522 while ( r!=dep_head ) {
12523   s=dep_list(r); q=mp_p_with_x_becoming_q(mp, s,x,p,type(r));
12524   if ( info(q)==null ) {
12525     mp_make_known(mp, r,q);
12526   } else { 
12527     dep_list(r)=q;
12528     do {  q=link(q); } while (info(q)!=null);
12529     prev_r=q;
12530   }
12531   r=link(prev_r);
12532 }
12533
12534 @ @<Change variable |x| from |independent| to |dependent| or |known|@>=
12535 if ( n>0 ) @<Divide list |p| by $2^n$@>;
12536 if ( info(p)==null ) {
12537   type(x)=mp_known;
12538   value(x)=value(p);
12539   if ( abs(value(x))>=fraction_one ) mp_val_too_big(mp, value(x));
12540   mp_free_node(mp, p,dep_node_size);
12541   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) {
12542     mp->cur_exp=value(x); mp->cur_type=mp_known;
12543     mp_free_node(mp, x,value_node_size);
12544   }
12545 } else { 
12546   type(x)=mp_dependent; mp->dep_final=final_node; mp_new_dep(mp, x,p);
12547   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) mp->cur_type=mp_dependent;
12548 }
12549
12550 @ @<Divide list |p| by $2^n$@>=
12551
12552   s=temp_head; link(temp_head)=p; r=p;
12553   do {  
12554     if ( n>30 ) w=0;
12555     else w=value(r) / two_to_the(n);
12556     if ( (abs(w)<=half_fraction_threshold)&&(info(r)!=null) ) {
12557       link(s)=link(r);
12558       mp_free_node(mp, r,dep_node_size);
12559     } else { 
12560       value(r)=w; s=r;
12561     }
12562     r=link(s);
12563   } while (info(s)!=null);
12564   p=link(temp_head);
12565 }
12566
12567 @ The |check_mem| procedure, which is used only when \MP\ is being
12568 debugged, makes sure that the current dependency lists are well formed.
12569
12570 @<Check the list of linear dependencies@>=
12571 q=dep_head; p=link(q);
12572 while ( p!=dep_head ) {
12573   if ( prev_dep(p)!=q ) {
12574     mp_print_nl(mp, "Bad PREVDEP at "); mp_print_int(mp, p);
12575 @.Bad PREVDEP...@>
12576   }
12577   p=dep_list(p);
12578   while (1) {
12579     r=info(p); q=p; p=link(q);
12580     if ( r==null ) break;
12581     if ( value(info(p))>=value(r) ) {
12582       mp_print_nl(mp, "Out of order at "); mp_print_int(mp, p);
12583 @.Out of order...@>
12584     }
12585   }
12586 }
12587
12588 @* \[25] Dynamic nonlinear equations.
12589 Variables of numeric type are maintained by the general scheme of
12590 independent, dependent, and known values that we have just studied;
12591 and the components of pair and transform variables are handled in the
12592 same way. But \MP\ also has five other types of values: \&{boolean},
12593 \&{string}, \&{pen}, \&{path}, and \&{picture}; what about them?
12594
12595 Equations are allowed between nonlinear quantities, but only in a
12596 simple form. Two variables that haven't yet been assigned values are
12597 either equal to each other, or they're not.
12598
12599 Before a boolean variable has received a value, its type is |mp_unknown_boolean|;
12600 similarly, there are variables whose type is |mp_unknown_string|, |mp_unknown_pen|,
12601 |mp_unknown_path|, and |mp_unknown_picture|. In such cases the value is either
12602 |null| (which means that no other variables are equivalent to this one), or
12603 it points to another variable of the same undefined type. The pointers in the
12604 latter case form a cycle of nodes, which we shall call a ``ring.''
12605 Rings of undefined variables may include capsules, which arise as
12606 intermediate results within expressions or as \&{expr} parameters to macros.
12607
12608 When one member of a ring receives a value, the same value is given to
12609 all the other members. In the case of paths and pictures, this implies
12610 making separate copies of a potentially large data structure; users should
12611 restrain their enthusiasm for such generality, unless they have lots and
12612 lots of memory space.
12613
12614 @ The following procedure is called when a capsule node is being
12615 added to a ring (e.g., when an unknown variable is mentioned in an expression).
12616
12617 @c pointer mp_new_ring_entry (MP mp,pointer p) {
12618   pointer q; /* the new capsule node */
12619   q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
12620   type(q)=type(p);
12621   if ( value(p)==null ) value(q)=p; else value(q)=value(p);
12622   value(p)=q;
12623   return q;
12624 }
12625
12626 @ Conversely, we might delete a capsule or a variable before it becomes known.
12627 The following procedure simply detaches a quantity from its ring,
12628 without recycling the storage.
12629
12630 @<Declare the recycling subroutines@>=
12631 void mp_ring_delete (MP mp,pointer p) {
12632   pointer q; 
12633   q=value(p);
12634   if ( q!=null ) if ( q!=p ){ 
12635     while ( value(q)!=p ) q=value(q);
12636     value(q)=value(p);
12637   }
12638 }
12639
12640 @ Eventually there might be an equation that assigns values to all of the
12641 variables in a ring. The |nonlinear_eq| subroutine does the necessary
12642 propagation of values.
12643
12644 If the parameter |flush_p| is |true|, node |p| itself needn't receive a
12645 value, it will soon be recycled.
12646
12647 @c void mp_nonlinear_eq (MP mp,integer v, pointer p, boolean flush_p) {
12648   small_number t; /* the type of ring |p| */
12649   pointer q,r; /* link manipulation registers */
12650   t=type(p)-unknown_tag; q=value(p);
12651   if ( flush_p ) type(p)=mp_vacuous; else p=q;
12652   do {  
12653     r=value(q); type(q)=t;
12654     switch (t) {
12655     case mp_boolean_type: value(q)=v; break;
12656     case mp_string_type: value(q)=v; add_str_ref(v); break;
12657     case mp_pen_type: value(q)=copy_pen(v); break;
12658     case mp_path_type: value(q)=mp_copy_path(mp, v); break;
12659     case mp_picture_type: value(q)=v; add_edge_ref(v); break;
12660     } /* there ain't no more cases */
12661     q=r;
12662   } while (q!=p);
12663 }
12664
12665 @ If two members of rings are equated, and if they have the same type,
12666 the |ring_merge| procedure is called on to make them equivalent.
12667
12668 @c void mp_ring_merge (MP mp,pointer p, pointer q) {
12669   pointer r; /* traverses one list */
12670   r=value(p);
12671   while ( r!=p ) {
12672     if ( r==q ) {
12673       @<Exclaim about a redundant equation@>;
12674       return;
12675     };
12676     r=value(r);
12677   }
12678   r=value(p); value(p)=value(q); value(q)=r;
12679 }
12680
12681 @ @<Exclaim about a redundant equation@>=
12682
12683   print_err("Redundant equation");
12684 @.Redundant equation@>
12685   help2("I already knew that this equation was true.")
12686    ("But perhaps no harm has been done; let's continue.");
12687   mp_put_get_error(mp);
12688 }
12689
12690 @* \[26] Introduction to the syntactic routines.
12691 Let's pause a moment now and try to look at the Big Picture.
12692 The \MP\ program consists of three main parts: syntactic routines,
12693 semantic routines, and output routines. The chief purpose of the
12694 syntactic routines is to deliver the user's input to the semantic routines,
12695 while parsing expressions and locating operators and operands. The
12696 semantic routines act as an interpreter responding to these operators,
12697 which may be regarded as commands. And the output routines are
12698 periodically called on to produce compact font descriptions that can be
12699 used for typesetting or for making interim proof drawings. We have
12700 discussed the basic data structures and many of the details of semantic
12701 operations, so we are good and ready to plunge into the part of \MP\ that
12702 actually controls the activities.
12703
12704 Our current goal is to come to grips with the |get_next| procedure,
12705 which is the keystone of \MP's input mechanism. Each call of |get_next|
12706 sets the value of three variables |cur_cmd|, |cur_mod|, and |cur_sym|,
12707 representing the next input token.
12708 $$\vbox{\halign{#\hfil\cr
12709   \hbox{|cur_cmd| denotes a command code from the long list of codes
12710    given earlier;}\cr
12711   \hbox{|cur_mod| denotes a modifier of the command code;}\cr
12712   \hbox{|cur_sym| is the hash address of the symbolic token that was
12713    just scanned,}\cr
12714   \hbox{\qquad or zero in the case of a numeric or string
12715    or capsule token.}\cr}}$$
12716 Underlying this external behavior of |get_next| is all the machinery
12717 necessary to convert from character files to tokens. At a given time we
12718 may be only partially finished with the reading of several files (for
12719 which \&{input} was specified), and partially finished with the expansion
12720 of some user-defined macros and/or some macro parameters, and partially
12721 finished reading some text that the user has inserted online,
12722 and so on. When reading a character file, the characters must be
12723 converted to tokens; comments and blank spaces must
12724 be removed, numeric and string tokens must be evaluated.
12725
12726 To handle these situations, which might all be present simultaneously,
12727 \MP\ uses various stacks that hold information about the incomplete
12728 activities, and there is a finite state control for each level of the
12729 input mechanism. These stacks record the current state of an implicitly
12730 recursive process, but the |get_next| procedure is not recursive.
12731
12732 @<Glob...@>=
12733 eight_bits cur_cmd; /* current command set by |get_next| */
12734 integer cur_mod; /* operand of current command */
12735 halfword cur_sym; /* hash address of current symbol */
12736
12737 @ The |print_cmd_mod| routine prints a symbolic interpretation of a
12738 command code and its modifier.
12739 It consists of a rather tedious sequence of print
12740 commands, and most of it is essentially an inverse to the |primitive|
12741 routine that enters a \MP\ primitive into |hash| and |eqtb|. Therefore almost
12742 all of this procedure appears elsewhere in the program, together with the
12743 corresponding |primitive| calls.
12744
12745 @<Declare the procedure called |print_cmd_mod|@>=
12746 void mp_print_cmd_mod (MP mp,integer c, integer m) { 
12747  switch (c) {
12748   @<Cases of |print_cmd_mod| for symbolic printing of primitives@>
12749   default: mp_print(mp, "[unknown command code!]"); break;
12750   }
12751 }
12752
12753 @ Here is a procedure that displays a given command in braces, in the
12754 user's transcript file.
12755
12756 @d show_cur_cmd_mod mp_show_cmd_mod(mp, mp->cur_cmd,mp->cur_mod)
12757
12758 @c 
12759 void mp_show_cmd_mod (MP mp,integer c, integer m) { 
12760   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
12761   mp_print_cmd_mod(mp, c,m); mp_print_char(mp, '}');
12762   mp_end_diagnostic(mp, false);
12763 }
12764
12765 @* \[27] Input stacks and states.
12766 The state of \MP's input mechanism appears in the input stack, whose
12767 entries are records with five fields, called |index|, |start|, |loc|,
12768 |limit|, and |name|. The top element of this stack is maintained in a
12769 global variable for which no subscripting needs to be done; the other
12770 elements of the stack appear in an array. Hence the stack is declared thus:
12771
12772 @<Types...@>=
12773 typedef struct {
12774   quarterword index_field;
12775   halfword start_field, loc_field, limit_field, name_field;
12776 } in_state_record;
12777
12778 @ @<Glob...@>=
12779 in_state_record *input_stack;
12780 integer input_ptr; /* first unused location of |input_stack| */
12781 integer max_in_stack; /* largest value of |input_ptr| when pushing */
12782 in_state_record cur_input; /* the ``top'' input state */
12783 int stack_size; /* maximum number of simultaneous input sources */
12784
12785 @ @<Allocate or initialize ...@>=
12786 mp->stack_size = 300;
12787 mp->input_stack = xmalloc((mp->stack_size+1),sizeof(in_state_record));
12788
12789 @ @<Dealloc variables@>=
12790 xfree(mp->input_stack);
12791
12792 @ We've already defined the special variable |loc==cur_input.loc_field|
12793 in our discussion of basic input-output routines. The other components of
12794 |cur_input| are defined in the same way:
12795
12796 @d index mp->cur_input.index_field /* reference for buffer information */
12797 @d start mp->cur_input.start_field /* starting position in |buffer| */
12798 @d limit mp->cur_input.limit_field /* end of current line in |buffer| */
12799 @d name mp->cur_input.name_field /* name of the current file */
12800
12801 @ Let's look more closely now at the five control variables
12802 (|index|,~|start|,~|loc|,~|limit|,~|name|),
12803 assuming that \MP\ is reading a line of characters that have been input
12804 from some file or from the user's terminal. There is an array called
12805 |buffer| that acts as a stack of all lines of characters that are
12806 currently being read from files, including all lines on subsidiary
12807 levels of the input stack that are not yet completed. \MP\ will return to
12808 the other lines when it is finished with the present input file.
12809
12810 (Incidentally, on a machine with byte-oriented addressing, it would be
12811 appropriate to combine |buffer| with the |str_pool| array,
12812 letting the buffer entries grow downward from the top of the string pool
12813 and checking that these two tables don't bump into each other.)
12814
12815 The line we are currently working on begins in position |start| of the
12816 buffer; the next character we are about to read is |buffer[loc]|; and
12817 |limit| is the location of the last character present. We always have
12818 |loc<=limit|. For convenience, |buffer[limit]| has been set to |"%"|, so
12819 that the end of a line is easily sensed.
12820
12821 The |name| variable is a string number that designates the name of
12822 the current file, if we are reading an ordinary text file.  Special codes
12823 |is_term..max_spec_src| indicate other sources of input text.
12824
12825 @d is_term 0 /* |name| value when reading from the terminal for normal input */
12826 @d is_read 1 /* |name| value when executing a \&{readstring} or \&{readfrom} */
12827 @d is_scantok 2 /* |name| value when reading text generated by \&{scantokens} */
12828 @d max_spec_src is_scantok
12829
12830 @ Additional information about the current line is available via the
12831 |index| variable, which counts how many lines of characters are present
12832 in the buffer below the current level. We have |index=0| when reading
12833 from the terminal and prompting the user for each line; then if the user types,
12834 e.g., `\.{input figs}', we will have |index=1| while reading
12835 the file \.{figs.mp}. However, it does not follow that |index| is the
12836 same as the input stack pointer, since many of the levels on the input
12837 stack may come from token lists and some |index| values may correspond
12838 to \.{MPX} files that are not currently on the stack.
12839
12840 The global variable |in_open| is equal to the highest |index| value counting
12841 \.{MPX} files but excluding token-list input levels.  Thus, the number of
12842 partially read lines in the buffer is |in_open+1| and we have |in_open>=index|
12843 when we are not reading a token list.
12844
12845 If we are not currently reading from the terminal,
12846 we are reading from the file variable |input_file[index]|. We use
12847 the notation |terminal_input| as a convenient abbreviation for |name=is_term|,
12848 and |cur_file| as an abbreviation for |input_file[index]|.
12849
12850 When \MP\ is not reading from the terminal, the global variable |line| contains
12851 the line number in the current file, for use in error messages. More precisely,
12852 |line| is a macro for |line_stack[index]| and the |line_stack| array gives
12853 the line number for each file in the |input_file| array.
12854
12855 When an \.{MPX} file is opened the file name is stored in the |mpx_name|
12856 array so that the name doesn't get lost when the file is temporarily removed
12857 from the input stack.
12858 Thus when |input_file[k]| is an \.{MPX} file, its name is |mpx_name[k]|
12859 and it contains translated \TeX\ pictures for |input_file[k-1]|.
12860 Since this is not an \.{MPX} file, we have
12861 $$ \hbox{|mpx_name[k-1]<=absent|}. $$
12862 This |name| field is set to |finished| when |input_file[k]| is completely
12863 read.
12864
12865 If more information about the input state is needed, it can be
12866 included in small arrays like those shown here. For example,
12867 the current page or segment number in the input file might be put
12868 into a variable |page|, that is really a macro for the current entry
12869 in `\ignorespaces|page_stack:array[0..max_in_open] of integer|\unskip'
12870 by analogy with |line_stack|.
12871 @^system dependencies@>
12872
12873 @d terminal_input (name==is_term) /* are we reading from the terminal? */
12874 @d cur_file mp->input_file[index] /* the current |FILE *| variable */
12875 @d line mp->line_stack[index] /* current line number in the current source file */
12876 @d in_name mp->iname_stack[index] /* a string used to construct \.{MPX} file names */
12877 @d in_area mp->iarea_stack[index] /* another string for naming \.{MPX} files */
12878 @d absent 1 /* |name_field| value for unused |mpx_in_stack| entries */
12879 @d mpx_reading (mp->mpx_name[index]>absent)
12880   /* when reading a file, is it an \.{MPX} file? */
12881 @d finished 0
12882   /* |name_field| value when the corresponding \.{MPX} file is finished */
12883
12884 @<Glob...@>=
12885 integer in_open; /* the number of lines in the buffer, less one */
12886 unsigned int open_parens; /* the number of open text files */
12887 FILE  * *input_file ;
12888 integer *line_stack ; /* the line number for each file */
12889 char *  *iname_stack; /* used for naming \.{MPX} files */
12890 char *  *iarea_stack; /* used for naming \.{MPX} files */
12891 halfword*mpx_name  ;
12892
12893 @ @<Allocate or ...@>=
12894 mp->input_file  = xmalloc((mp->max_in_open+1),sizeof(FILE *));
12895 mp->line_stack  = xmalloc((mp->max_in_open+1),sizeof(integer));
12896 mp->iname_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12897 mp->iarea_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12898 mp->mpx_name    = xmalloc((mp->max_in_open+1),sizeof(halfword));
12899 {
12900   int k;
12901   for (k=0;k<=mp->max_in_open;k++) {
12902     mp->iname_stack[k] =NULL;
12903     mp->iarea_stack[k] =NULL;
12904   }
12905 }
12906
12907 @ @<Dealloc variables@>=
12908 {
12909   int l;
12910   for (l=0;l<=mp->max_in_open;l++) {
12911     xfree(mp->iname_stack[l]);
12912     xfree(mp->iarea_stack[l]);
12913   }
12914 }
12915 xfree(mp->input_file);
12916 xfree(mp->line_stack);
12917 xfree(mp->iname_stack);
12918 xfree(mp->iarea_stack);
12919 xfree(mp->mpx_name);
12920
12921
12922 @ However, all this discussion about input state really applies only to the
12923 case that we are inputting from a file. There is another important case,
12924 namely when we are currently getting input from a token list. In this case
12925 |index>max_in_open|, and the conventions about the other state variables
12926 are different:
12927
12928 \yskip\hang|loc| is a pointer to the current node in the token list, i.e.,
12929 the node that will be read next. If |loc=null|, the token list has been
12930 fully read.
12931
12932 \yskip\hang|start| points to the first node of the token list; this node
12933 may or may not contain a reference count, depending on the type of token
12934 list involved.
12935
12936 \yskip\hang|token_type|, which takes the place of |index| in the
12937 discussion above, is a code number that explains what kind of token list
12938 is being scanned.
12939
12940 \yskip\hang|name| points to the |eqtb| address of the control sequence
12941 being expanded, if the current token list is a macro not defined by
12942 \&{vardef}. Macros defined by \&{vardef} have |name=null|; their name
12943 can be deduced by looking at their first two parameters.
12944
12945 \yskip\hang|param_start|, which takes the place of |limit|, tells where
12946 the parameters of the current macro or loop text begin in the |param_stack|.
12947
12948 \yskip\noindent The |token_type| can take several values, depending on
12949 where the current token list came from:
12950
12951 \yskip
12952 \indent|forever_text|, if the token list being scanned is the body of
12953 a \&{forever} loop;
12954
12955 \indent|loop_text|, if the token list being scanned is the body of
12956 a \&{for} or \&{forsuffixes} loop;
12957
12958 \indent|parameter|, if a \&{text} or \&{suffix} parameter is being scanned;
12959
12960 \indent|backed_up|, if the token list being scanned has been inserted as
12961 `to be read again'.
12962
12963 \indent|inserted|, if the token list being scanned has been inserted as
12964 part of error recovery;
12965
12966 \indent|macro|, if the expansion of a user-defined symbolic token is being
12967 scanned.
12968
12969 \yskip\noindent
12970 The token list begins with a reference count if and only if |token_type=
12971 macro|.
12972 @^reference counts@>
12973
12974 @d token_type index /* type of current token list */
12975 @d token_state (index>(int)mp->max_in_open) /* are we scanning a token list? */
12976 @d file_state (index<=(int)mp->max_in_open) /* are we scanning a file line? */
12977 @d param_start limit /* base of macro parameters in |param_stack| */
12978 @d forever_text (mp->max_in_open+1) /* |token_type| code for loop texts */
12979 @d loop_text (mp->max_in_open+2) /* |token_type| code for loop texts */
12980 @d parameter (mp->max_in_open+3) /* |token_type| code for parameter texts */
12981 @d backed_up (mp->max_in_open+4) /* |token_type| code for texts to be reread */
12982 @d inserted (mp->max_in_open+5) /* |token_type| code for inserted texts */
12983 @d macro (mp->max_in_open+6) /* |token_type| code for macro replacement texts */
12984
12985 @ The |param_stack| is an auxiliary array used to hold pointers to the token
12986 lists for parameters at the current level and subsidiary levels of input.
12987 This stack grows at a different rate from the others.
12988
12989 @<Glob...@>=
12990 pointer *param_stack;  /* token list pointers for parameters */
12991 integer param_ptr; /* first unused entry in |param_stack| */
12992 integer max_param_stack;  /* largest value of |param_ptr| */
12993
12994 @ @<Allocate or initialize ...@>=
12995 mp->param_stack = xmalloc((mp->param_size+1),sizeof(pointer));
12996
12997 @ @<Dealloc variables@>=
12998 xfree(mp->param_stack);
12999
13000 @ Notice that the |line| isn't valid when |token_state| is true because it
13001 depends on |index|.  If we really need to know the line number for the
13002 topmost file in the index stack we use the following function.  If a page
13003 number or other information is needed, this routine should be modified to
13004 compute it as well.
13005 @^system dependencies@>
13006
13007 @<Declare a function called |true_line|@>=
13008 integer mp_true_line (MP mp) {
13009   int k; /* an index into the input stack */
13010   if ( file_state && (name>max_spec_src) ) {
13011      return line;
13012   } else { 
13013     k=mp->input_ptr;
13014     while ((k>0) &&
13015            ((mp->input_stack[(k-1)].index_field>mp->max_in_open)||
13016             (mp->input_stack[(k-1)].name_field<=max_spec_src))) {
13017       decr(k);
13018     }
13019     return mp->line_stack[(k-1)];
13020   }
13021   return 0; 
13022 }
13023
13024 @ Thus, the ``current input state'' can be very complicated indeed; there
13025 can be many levels and each level can arise in a variety of ways. The
13026 |show_context| procedure, which is used by \MP's error-reporting routine to
13027 print out the current input state on all levels down to the most recent
13028 line of characters from an input file, illustrates most of these conventions.
13029 The global variable |file_ptr| contains the lowest level that was
13030 displayed by this procedure.
13031
13032 @<Glob...@>=
13033 integer file_ptr; /* shallowest level shown by |show_context| */
13034
13035 @ The status at each level is indicated by printing two lines, where the first
13036 line indicates what was read so far and the second line shows what remains
13037 to be read. The context is cropped, if necessary, so that the first line
13038 contains at most |half_error_line| characters, and the second contains
13039 at most |error_line|. Non-current input levels whose |token_type| is
13040 `|backed_up|' are shown only if they have not been fully read.
13041
13042 @c void mp_show_context (MP mp) { /* prints where the scanner is */
13043   int old_setting; /* saved |selector| setting */
13044   @<Local variables for formatting calculations@>
13045   mp->file_ptr=mp->input_ptr; mp->input_stack[mp->file_ptr]=mp->cur_input;
13046   /* store current state */
13047   while (1) { 
13048     mp->cur_input=mp->input_stack[mp->file_ptr]; /* enter into the context */
13049     @<Display the current context@>;
13050     if ( file_state )
13051       if ( (name>max_spec_src) || (mp->file_ptr==0) ) break;
13052     decr(mp->file_ptr);
13053   }
13054   mp->cur_input=mp->input_stack[mp->input_ptr]; /* restore original state */
13055 }
13056
13057 @ @<Display the current context@>=
13058 if ( (mp->file_ptr==mp->input_ptr) || file_state ||
13059    (token_type!=backed_up) || (loc!=null) ) {
13060     /* we omit backed-up token lists that have already been read */
13061   mp->tally=0; /* get ready to count characters */
13062   old_setting=mp->selector;
13063   if ( file_state ) {
13064     @<Print location of current line@>;
13065     @<Pseudoprint the line@>;
13066   } else { 
13067     @<Print type of token list@>;
13068     @<Pseudoprint the token list@>;
13069   }
13070   mp->selector=old_setting; /* stop pseudoprinting */
13071   @<Print two lines using the tricky pseudoprinted information@>;
13072 }
13073
13074 @ This routine should be changed, if necessary, to give the best possible
13075 indication of where the current line resides in the input file.
13076 For example, on some systems it is best to print both a page and line number.
13077 @^system dependencies@>
13078
13079 @<Print location of current line@>=
13080 if ( name>max_spec_src ) {
13081   mp_print_nl(mp, "l."); mp_print_int(mp, mp_true_line(mp));
13082 } else if ( terminal_input ) {
13083   if ( mp->file_ptr==0 ) mp_print_nl(mp, "<*>");
13084   else mp_print_nl(mp, "<insert>");
13085 } else if ( name==is_scantok ) {
13086   mp_print_nl(mp, "<scantokens>");
13087 } else {
13088   mp_print_nl(mp, "<read>");
13089 }
13090 mp_print_char(mp, ' ')
13091
13092 @ Can't use case statement here because the |token_type| is not
13093 a constant expression.
13094
13095 @<Print type of token list@>=
13096 {
13097   if(token_type==forever_text) {
13098     mp_print_nl(mp, "<forever> ");
13099   } else if (token_type==loop_text) {
13100     @<Print the current loop value@>;
13101   } else if (token_type==parameter) {
13102     mp_print_nl(mp, "<argument> "); 
13103   } else if (token_type==backed_up) { 
13104     if ( loc==null ) mp_print_nl(mp, "<recently read> ");
13105     else mp_print_nl(mp, "<to be read again> ");
13106   } else if (token_type==inserted) {
13107     mp_print_nl(mp, "<inserted text> ");
13108   } else if (token_type==macro) {
13109     mp_print_ln(mp);
13110     if ( name!=null ) mp_print_text(name);
13111     else @<Print the name of a \&{vardef}'d macro@>;
13112     mp_print(mp, "->");
13113   } else {
13114     mp_print_nl(mp, "?");/* this should never happen */
13115 @.?\relax@>
13116   }
13117 }
13118
13119 @ The parameter that corresponds to a loop text is either a token list
13120 (in the case of \&{forsuffixes}) or a ``capsule'' (in the case of \&{for}).
13121 We'll discuss capsules later; for now, all we need to know is that
13122 the |link| field in a capsule parameter is |void| and that
13123 |print_exp(p,0)| displays the value of capsule~|p| in abbreviated form.
13124
13125 @<Print the current loop value@>=
13126 { mp_print_nl(mp, "<for("); p=mp->param_stack[param_start];
13127   if ( p!=null ) {
13128     if ( link(p)==mp_void ) mp_print_exp(mp, p,0); /* we're in a \&{for} loop */
13129     else mp_show_token_list(mp, p,null,20,mp->tally);
13130   }
13131   mp_print(mp, ")> ");
13132 }
13133
13134 @ The first two parameters of a macro defined by \&{vardef} will be token
13135 lists representing the macro's prefix and ``at point.'' By putting these
13136 together, we get the macro's full name.
13137
13138 @<Print the name of a \&{vardef}'d macro@>=
13139 { p=mp->param_stack[param_start];
13140   if ( p==null ) {
13141     mp_show_token_list(mp, mp->param_stack[param_start+1],null,20,mp->tally);
13142   } else { 
13143     q=p;
13144     while ( link(q)!=null ) q=link(q);
13145     link(q)=mp->param_stack[param_start+1];
13146     mp_show_token_list(mp, p,null,20,mp->tally);
13147     link(q)=null;
13148   }
13149 }
13150
13151 @ Now it is necessary to explain a little trick. We don't want to store a long
13152 string that corresponds to a token list, because that string might take up
13153 lots of memory; and we are printing during a time when an error message is
13154 being given, so we dare not do anything that might overflow one of \MP's
13155 tables. So `pseudoprinting' is the answer: We enter a mode of printing
13156 that stores characters into a buffer of length |error_line|, where character
13157 $k+1$ is placed into \hbox{|trick_buf[k mod error_line]|} if
13158 |k<trick_count|, otherwise character |k| is dropped. Initially we set
13159 |tally:=0| and |trick_count:=1000000|; then when we reach the
13160 point where transition from line 1 to line 2 should occur, we
13161 set |first_count:=tally| and |trick_count:=@tmax@>(error_line,
13162 tally+1+error_line-half_error_line)|. At the end of the
13163 pseudoprinting, the values of |first_count|, |tally|, and
13164 |trick_count| give us all the information we need to print the two lines,
13165 and all of the necessary text is in |trick_buf|.
13166
13167 Namely, let |l| be the length of the descriptive information that appears
13168 on the first line. The length of the context information gathered for that
13169 line is |k=first_count|, and the length of the context information
13170 gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k<=h|,
13171 where |h=half_error_line|, we print |trick_buf[0..k-1]| after the
13172 descriptive information on line~1, and set |n:=l+k|; here |n| is the
13173 length of line~1. If $l+k>h$, some cropping is necessary, so we set |n:=h|
13174 and print `\.{...}' followed by
13175 $$\hbox{|trick_buf[(l+k-h+3)..k-1]|,}$$
13176 where subscripts of |trick_buf| are circular modulo |error_line|. The
13177 second line consists of |n|~spaces followed by |trick_buf[k..(k+m-1)]|,
13178 unless |n+m>error_line|; in the latter case, further cropping is done.
13179 This is easier to program than to explain.
13180
13181 @<Local variables for formatting...@>=
13182 int i; /* index into |buffer| */
13183 integer l; /* length of descriptive information on line 1 */
13184 integer m; /* context information gathered for line 2 */
13185 int n; /* length of line 1 */
13186 integer p; /* starting or ending place in |trick_buf| */
13187 integer q; /* temporary index */
13188
13189 @ The following code tells the print routines to gather
13190 the desired information.
13191
13192 @d begin_pseudoprint { 
13193   l=mp->tally; mp->tally=0; mp->selector=pseudo;
13194   mp->trick_count=1000000;
13195 }
13196 @d set_trick_count {
13197   mp->first_count=mp->tally;
13198   mp->trick_count=mp->tally+1+mp->error_line-mp->half_error_line;
13199   if ( mp->trick_count<mp->error_line ) mp->trick_count=mp->error_line;
13200 }
13201
13202 @ And the following code uses the information after it has been gathered.
13203
13204 @<Print two lines using the tricky pseudoprinted information@>=
13205 if ( mp->trick_count==1000000 ) set_trick_count;
13206   /* |set_trick_count| must be performed */
13207 if ( mp->tally<mp->trick_count ) m=mp->tally-mp->first_count;
13208 else m=mp->trick_count-mp->first_count; /* context on line 2 */
13209 if ( l+mp->first_count<=mp->half_error_line ) {
13210   p=0; n=l+mp->first_count;
13211 } else  { 
13212   mp_print(mp, "..."); p=l+mp->first_count-mp->half_error_line+3;
13213   n=mp->half_error_line;
13214 }
13215 for (q=p;q<=mp->first_count-1;q++) {
13216   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13217 }
13218 mp_print_ln(mp);
13219 for (q=1;q<=n;q++) {
13220   mp_print_char(mp, ' '); /* print |n| spaces to begin line~2 */
13221 }
13222 if ( m+n<=mp->error_line ) p=mp->first_count+m; 
13223 else p=mp->first_count+(mp->error_line-n-3);
13224 for (q=mp->first_count;q<=p-1;q++) {
13225   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13226 }
13227 if ( m+n>mp->error_line ) mp_print(mp, "...")
13228
13229 @ But the trick is distracting us from our current goal, which is to
13230 understand the input state. So let's concentrate on the data structures that
13231 are being pseudoprinted as we finish up the |show_context| procedure.
13232
13233 @<Pseudoprint the line@>=
13234 begin_pseudoprint;
13235 if ( limit>0 ) {
13236   for (i=start;i<=limit-1;i++) {
13237     if ( i==loc ) set_trick_count;
13238     mp_print_str(mp, mp->buffer[i]);
13239   }
13240 }
13241
13242 @ @<Pseudoprint the token list@>=
13243 begin_pseudoprint;
13244 if ( token_type!=macro ) mp_show_token_list(mp, start,loc,100000,0);
13245 else mp_show_macro(mp, start,loc,100000)
13246
13247 @ Here is the missing piece of |show_token_list| that is activated when the
13248 token beginning line~2 is about to be shown:
13249
13250 @<Do magic computation@>=set_trick_count
13251
13252 @* \[28] Maintaining the input stacks.
13253 The following subroutines change the input status in commonly needed ways.
13254
13255 First comes |push_input|, which stores the current state and creates a
13256 new level (having, initially, the same properties as the old).
13257
13258 @d push_input  { /* enter a new input level, save the old */
13259   if ( mp->input_ptr>mp->max_in_stack ) {
13260     mp->max_in_stack=mp->input_ptr;
13261     if ( mp->input_ptr==mp->stack_size ) {
13262       int l = (mp->stack_size+(mp->stack_size>>2));
13263       XREALLOC(mp->input_stack, l, in_state_record);
13264       mp->stack_size = l;
13265     }         
13266   }
13267   mp->input_stack[mp->input_ptr]=mp->cur_input; /* stack the record */
13268   incr(mp->input_ptr);
13269 }
13270
13271 @ And of course what goes up must come down.
13272
13273 @d pop_input { /* leave an input level, re-enter the old */
13274     decr(mp->input_ptr); mp->cur_input=mp->input_stack[mp->input_ptr];
13275   }
13276
13277 @ Here is a procedure that starts a new level of token-list input, given
13278 a token list |p| and its type |t|. If |t=macro|, the calling routine should
13279 set |name|, reset~|loc|, and increase the macro's reference count.
13280
13281 @d back_list(A) mp_begin_token_list(mp, (A),backed_up) /* backs up a simple token list */
13282
13283 @c void mp_begin_token_list (MP mp,pointer p, quarterword t)  { 
13284   push_input; start=p; token_type=t;
13285   param_start=mp->param_ptr; loc=p;
13286 }
13287
13288 @ When a token list has been fully scanned, the following computations
13289 should be done as we leave that level of input.
13290 @^inner loop@>
13291
13292 @c void mp_end_token_list (MP mp) { /* leave a token-list input level */
13293   pointer p; /* temporary register */
13294   if ( token_type>=backed_up ) { /* token list to be deleted */
13295     if ( token_type<=inserted ) { 
13296       mp_flush_token_list(mp, start); goto DONE;
13297     } else {
13298       mp_delete_mac_ref(mp, start); /* update reference count */
13299     }
13300   }
13301   while ( mp->param_ptr>param_start ) { /* parameters must be flushed */
13302     decr(mp->param_ptr);
13303     p=mp->param_stack[mp->param_ptr];
13304     if ( p!=null ) {
13305       if ( link(p)==mp_void ) { /* it's an \&{expr} parameter */
13306         mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
13307       } else {
13308         mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
13309       }
13310     }
13311   }
13312 DONE: 
13313   pop_input; check_interrupt;
13314 }
13315
13316 @ The contents of |cur_cmd,cur_mod,cur_sym| are placed into an equivalent
13317 token by the |cur_tok| routine.
13318 @^inner loop@>
13319
13320 @c @<Declare the procedure called |make_exp_copy|@>;
13321 pointer mp_cur_tok (MP mp) {
13322   pointer p; /* a new token node */
13323   small_number save_type; /* |cur_type| to be restored */
13324   integer save_exp; /* |cur_exp| to be restored */
13325   if ( mp->cur_sym==0 ) {
13326     if ( mp->cur_cmd==capsule_token ) {
13327       save_type=mp->cur_type; save_exp=mp->cur_exp;
13328       mp_make_exp_copy(mp, mp->cur_mod); p=mp_stash_cur_exp(mp); link(p)=null;
13329       mp->cur_type=save_type; mp->cur_exp=save_exp;
13330     } else { 
13331       p=mp_get_node(mp, token_node_size);
13332       value(p)=mp->cur_mod; name_type(p)=mp_token;
13333       if ( mp->cur_cmd==numeric_token ) type(p)=mp_known;
13334       else type(p)=mp_string_type;
13335     }
13336   } else { 
13337     fast_get_avail(p); info(p)=mp->cur_sym;
13338   }
13339   return p;
13340 }
13341
13342 @ Sometimes \MP\ has read too far and wants to ``unscan'' what it has
13343 seen. The |back_input| procedure takes care of this by putting the token
13344 just scanned back into the input stream, ready to be read again.
13345 If |cur_sym<>0|, the values of |cur_cmd| and |cur_mod| are irrelevant.
13346
13347 @<Declarations@>= 
13348 void mp_back_input (MP mp);
13349
13350 @ @c void mp_back_input (MP mp) {/* undoes one token of input */
13351   pointer p; /* a token list of length one */
13352   p=mp_cur_tok(mp);
13353   while ( token_state &&(loc==null) ) 
13354     mp_end_token_list(mp); /* conserve stack space */
13355   back_list(p);
13356 }
13357
13358 @ The |back_error| routine is used when we want to restore or replace an
13359 offending token just before issuing an error message.  We disable interrupts
13360 during the call of |back_input| so that the help message won't be lost.
13361
13362 @<Declarations@>=
13363 void mp_error (MP mp);
13364 void mp_back_error (MP mp);
13365
13366 @ @c void mp_back_error (MP mp) { /* back up one token and call |error| */
13367   mp->OK_to_interrupt=false; 
13368   mp_back_input(mp); 
13369   mp->OK_to_interrupt=true; mp_error(mp);
13370 }
13371 void mp_ins_error (MP mp) { /* back up one inserted token and call |error| */
13372   mp->OK_to_interrupt=false; 
13373   mp_back_input(mp); token_type=inserted;
13374   mp->OK_to_interrupt=true; mp_error(mp);
13375 }
13376
13377 @ The |begin_file_reading| procedure starts a new level of input for lines
13378 of characters to be read from a file, or as an insertion from the
13379 terminal. It does not take care of opening the file, nor does it set |loc|
13380 or |limit| or |line|.
13381 @^system dependencies@>
13382
13383 @c void mp_begin_file_reading (MP mp) { 
13384   if ( mp->in_open==mp->max_in_open ) 
13385     mp_overflow(mp, "text input levels",mp->max_in_open);
13386 @:MetaPost capacity exceeded text input levels}{\quad text input levels@>
13387   if ( mp->first==mp->buf_size ) 
13388     mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13389   incr(mp->in_open); push_input; index=mp->in_open;
13390   mp->mpx_name[index]=absent;
13391   start=mp->first;
13392   name=is_term; /* |terminal_input| is now |true| */
13393 }
13394
13395 @ Conversely, the variables must be downdated when such a level of input
13396 is finished.  Any associated \.{MPX} file must also be closed and popped
13397 off the file stack.
13398
13399 @c void mp_end_file_reading (MP mp) { 
13400   if ( mp->in_open>index ) {
13401     if ( (mp->mpx_name[mp->in_open]==absent)||(name<=max_spec_src) ) {
13402       mp_confusion(mp, "endinput");
13403 @:this can't happen endinput}{\quad endinput@>
13404     } else { 
13405       fclose(mp->input_file[mp->in_open]); /* close an \.{MPX} file */
13406       delete_str_ref(mp->mpx_name[mp->in_open]);
13407       decr(mp->in_open);
13408     }
13409   }
13410   mp->first=start;
13411   if ( index!=mp->in_open ) mp_confusion(mp, "endinput");
13412   if ( name>max_spec_src ) {
13413     fclose(cur_file);
13414     delete_str_ref(name);
13415     xfree(in_name); 
13416     xfree(in_area);
13417   }
13418   pop_input; decr(mp->in_open);
13419 }
13420
13421 @ Here is a function that tries to resume input from an \.{MPX} file already
13422 associated with the current input file.  It returns |false| if this doesn't
13423 work.
13424
13425 @c boolean mp_begin_mpx_reading (MP mp) { 
13426   if ( mp->in_open!=index+1 ) {
13427      return false;
13428   } else { 
13429     if ( mp->mpx_name[mp->in_open]<=absent ) mp_confusion(mp, "mpx");
13430 @:this can't happen mpx}{\quad mpx@>
13431     if ( mp->first==mp->buf_size ) 
13432       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13433     push_input; index=mp->in_open;
13434     start=mp->first;
13435     name=mp->mpx_name[mp->in_open]; add_str_ref(name);
13436     @<Put an empty line in the input buffer@>;
13437     return true;
13438   }
13439 }
13440
13441 @ This procedure temporarily stops reading an \.{MPX} file.
13442
13443 @c void mp_end_mpx_reading (MP mp) { 
13444   if ( mp->in_open!=index ) mp_confusion(mp, "mpx");
13445 @:this can't happen mpx}{\quad mpx@>
13446   if ( loc<limit ) {
13447     @<Complain that we are not at the end of a line in the \.{MPX} file@>;
13448   }
13449   mp->first=start;
13450   pop_input;
13451 }
13452
13453 @ Here we enforce a restriction that simplifies the input stacks considerably.
13454 This should not inconvenience the user because \.{MPX} files are generated
13455 by an auxiliary program called \.{DVItoMP}.
13456
13457 @ @<Complain that we are not at the end of a line in the \.{MPX} file@>=
13458
13459 print_err("`mpxbreak' must be at the end of a line");
13460 help4("This file contains picture expressions for btex...etex")
13461   ("blocks.  Such files are normally generated automatically")
13462   ("but this one seems to be messed up.  I'm going to ignore")
13463   ("the rest of this line.");
13464 mp_error(mp);
13465 }
13466
13467 @ In order to keep the stack from overflowing during a long sequence of
13468 inserted `\.{show}' commands, the following routine removes completed
13469 error-inserted lines from memory.
13470
13471 @c void mp_clear_for_error_prompt (MP mp) { 
13472   while ( file_state && terminal_input &&
13473     (mp->input_ptr>0)&&(loc==limit) ) mp_end_file_reading(mp);
13474   mp_print_ln(mp); clear_terminal;
13475 }
13476
13477 @ To get \MP's whole input mechanism going, we perform the following
13478 actions.
13479
13480 @<Initialize the input routines@>=
13481 { mp->input_ptr=0; mp->max_in_stack=0;
13482   mp->in_open=0; mp->open_parens=0; mp->max_buf_stack=0;
13483   mp->param_ptr=0; mp->max_param_stack=0;
13484   mp->first=1;
13485   start=1; index=0; line=0; name=is_term;
13486   mp->mpx_name[0]=absent;
13487   mp->force_eof=false;
13488   if ( ! mp_init_terminal(mp) ) mp_jump_out(mp);
13489   limit=mp->last; mp->first=mp->last+1; 
13490   /* |init_terminal| has set |loc| and |last| */
13491 }
13492
13493 @* \[29] Getting the next token.
13494 The heart of \MP's input mechanism is the |get_next| procedure, which
13495 we shall develop in the next few sections of the program. Perhaps we
13496 shouldn't actually call it the ``heart,'' however; it really acts as \MP's
13497 eyes and mouth, reading the source files and gobbling them up. And it also
13498 helps \MP\ to regurgitate stored token lists that are to be processed again.
13499
13500 The main duty of |get_next| is to input one token and to set |cur_cmd|
13501 and |cur_mod| to that token's command code and modifier. Furthermore, if
13502 the input token is a symbolic token, that token's |hash| address
13503 is stored in |cur_sym|; otherwise |cur_sym| is set to zero.
13504
13505 Underlying this simple description is a certain amount of complexity
13506 because of all the cases that need to be handled.
13507 However, the inner loop of |get_next| is reasonably short and fast.
13508
13509 @ Before getting into |get_next|, we need to consider a mechanism by which
13510 \MP\ helps keep errors from propagating too far. Whenever the program goes
13511 into a mode where it keeps calling |get_next| repeatedly until a certain
13512 condition is met, it sets |scanner_status| to some value other than |normal|.
13513 Then if an input file ends, or if an `\&{outer}' symbol appears,
13514 an appropriate error recovery will be possible.
13515
13516 The global variable |warning_info| helps in this error recovery by providing
13517 additional information. For example, |warning_info| might indicate the
13518 name of a macro whose replacement text is being scanned.
13519
13520 @d normal 0 /* |scanner_status| at ``quiet times'' */
13521 @d skipping 1 /* |scanner_status| when false conditional text is being skipped */
13522 @d flushing 2 /* |scanner_status| when junk after a statement is being ignored */
13523 @d absorbing 3 /* |scanner_status| when a \&{text} parameter is being scanned */
13524 @d var_defining 4 /* |scanner_status| when a \&{vardef} is being scanned */
13525 @d op_defining 5 /* |scanner_status| when a macro \&{def} is being scanned */
13526 @d loop_defining 6 /* |scanner_status| when a \&{for} loop is being scanned */
13527 @d tex_flushing 7 /* |scanner_status| when skipping \TeX\ material */
13528
13529 @<Glob...@>=
13530 integer scanner_status; /* are we scanning at high speed? */
13531 integer warning_info; /* if so, what else do we need to know,
13532     in case an error occurs? */
13533
13534 @ @<Initialize the input routines@>=
13535 mp->scanner_status=normal;
13536
13537 @ The following subroutine
13538 is called when an `\&{outer}' symbolic token has been scanned or
13539 when the end of a file has been reached. These two cases are distinguished
13540 by |cur_sym|, which is zero at the end of a file.
13541
13542 @c boolean mp_check_outer_validity (MP mp) {
13543   pointer p; /* points to inserted token list */
13544   if ( mp->scanner_status==normal ) {
13545     return true;
13546   } else if ( mp->scanner_status==tex_flushing ) {
13547     @<Check if the file has ended while flushing \TeX\ material and set the
13548       result value for |check_outer_validity|@>;
13549   } else { 
13550     mp->deletions_allowed=false;
13551     @<Back up an outer symbolic token so that it can be reread@>;
13552     if ( mp->scanner_status>skipping ) {
13553       @<Tell the user what has run away and try to recover@>;
13554     } else { 
13555       print_err("Incomplete if; all text was ignored after line ");
13556 @.Incomplete if...@>
13557       mp_print_int(mp, mp->warning_info);
13558       help3("A forbidden `outer' token occurred in skipped text.")
13559         ("This kind of error happens when you say `if...' and forget")
13560         ("the matching `fi'. I've inserted a `fi'; this might work.");
13561       if ( mp->cur_sym==0 ) 
13562         mp->help_line[2]="The file ended while I was skipping conditional text.";
13563       mp->cur_sym=frozen_fi; mp_ins_error(mp);
13564     }
13565     mp->deletions_allowed=true; 
13566         return false;
13567   }
13568 }
13569
13570 @ @<Check if the file has ended while flushing \TeX\ material and set...@>=
13571 if ( mp->cur_sym!=0 ) { 
13572    return true;
13573 } else { 
13574   mp->deletions_allowed=false;
13575   print_err("TeX mode didn't end; all text was ignored after line ");
13576   mp_print_int(mp, mp->warning_info);
13577   help2("The file ended while I was looking for the `etex' to")
13578     ("finish this TeX material.  I've inserted `etex' now.");
13579   mp->cur_sym = frozen_etex;
13580   mp_ins_error(mp);
13581   mp->deletions_allowed=true;
13582   return false;
13583 }
13584
13585 @ @<Back up an outer symbolic token so that it can be reread@>=
13586 if ( mp->cur_sym!=0 ) {
13587   p=mp_get_avail(mp); info(p)=mp->cur_sym;
13588   back_list(p); /* prepare to read the symbolic token again */
13589 }
13590
13591 @ @<Tell the user what has run away...@>=
13592
13593   mp_runaway(mp); /* print the definition-so-far */
13594   if ( mp->cur_sym==0 ) {
13595     print_err("File ended");
13596 @.File ended while scanning...@>
13597   } else { 
13598     print_err("Forbidden token found");
13599 @.Forbidden token found...@>
13600   }
13601   mp_print(mp, " while scanning ");
13602   help4("I suspect you have forgotten an `enddef',")
13603     ("causing me to read past where you wanted me to stop.")
13604     ("I'll try to recover; but if the error is serious,")
13605     ("you'd better type `E' or `X' now and fix your file.");
13606   switch (mp->scanner_status) {
13607     @<Complete the error message,
13608       and set |cur_sym| to a token that might help recover from the error@>
13609   } /* there are no other cases */
13610   mp_ins_error(mp);
13611 }
13612
13613 @ As we consider various kinds of errors, it is also appropriate to
13614 change the first line of the help message just given; |help_line[3]|
13615 points to the string that might be changed.
13616
13617 @<Complete the error message,...@>=
13618 case flushing: 
13619   mp_print(mp, "to the end of the statement");
13620   mp->help_line[3]="A previous error seems to have propagated,";
13621   mp->cur_sym=frozen_semicolon;
13622   break;
13623 case absorbing: 
13624   mp_print(mp, "a text argument");
13625   mp->help_line[3]="It seems that a right delimiter was left out,";
13626   if ( mp->warning_info==0 ) {
13627     mp->cur_sym=frozen_end_group;
13628   } else { 
13629     mp->cur_sym=frozen_right_delimiter;
13630     equiv(frozen_right_delimiter)=mp->warning_info;
13631   }
13632   break;
13633 case var_defining:
13634 case op_defining: 
13635   mp_print(mp, "the definition of ");
13636   if ( mp->scanner_status==op_defining ) 
13637      mp_print_text(mp->warning_info);
13638   else 
13639      mp_print_variable_name(mp, mp->warning_info);
13640   mp->cur_sym=frozen_end_def;
13641   break;
13642 case loop_defining: 
13643   mp_print(mp, "the text of a "); 
13644   mp_print_text(mp->warning_info);
13645   mp_print(mp, " loop");
13646   mp->help_line[3]="I suspect you have forgotten an `endfor',";
13647   mp->cur_sym=frozen_end_for;
13648   break;
13649
13650 @ The |runaway| procedure displays the first part of the text that occurred
13651 when \MP\ began its special |scanner_status|, if that text has been saved.
13652
13653 @<Declare the procedure called |runaway|@>=
13654 void mp_runaway (MP mp) { 
13655   if ( mp->scanner_status>flushing ) { 
13656      mp_print_nl(mp, "Runaway ");
13657          switch (mp->scanner_status) { 
13658          case absorbing: mp_print(mp, "text?"); break;
13659          case var_defining: 
13660      case op_defining: mp_print(mp,"definition?"); break;
13661      case loop_defining: mp_print(mp, "loop?"); break;
13662      } /* there are no other cases */
13663      mp_print_ln(mp); 
13664      mp_show_token_list(mp, link(hold_head),null,mp->error_line-10,0);
13665   }
13666 }
13667
13668 @ We need to mention a procedure that may be called by |get_next|.
13669
13670 @<Declarations@>= 
13671 void mp_firm_up_the_line (MP mp);
13672
13673 @ And now we're ready to take the plunge into |get_next| itself.
13674 Note that the behavior depends on the |scanner_status| because percent signs
13675 and double quotes need to be passed over when skipping TeX material.
13676
13677 @c 
13678 void mp_get_next (MP mp) {
13679   /* sets |cur_cmd|, |cur_mod|, |cur_sym| to next token */
13680 @^inner loop@>
13681   /*restart*/ /* go here to get the next input token */
13682   /*exit*/ /* go here when the next input token has been got */
13683   /*|common_ending|*/ /* go here to finish getting a symbolic token */
13684   /*found*/ /* go here when the end of a symbolic token has been found */
13685   /*switch*/ /* go here to branch on the class of an input character */
13686   /*|start_numeric_token|,|start_decimal_token|,|fin_numeric_token|,|done|*/
13687     /* go here at crucial stages when scanning a number */
13688   int k; /* an index into |buffer| */
13689   ASCII_code c; /* the current character in the buffer */
13690   ASCII_code class; /* its class number */
13691   integer n,f; /* registers for decimal-to-binary conversion */
13692 RESTART: 
13693   mp->cur_sym=0;
13694   if ( file_state ) {
13695     @<Input from external file; |goto restart| if no input found,
13696     or |return| if a non-symbolic token is found@>;
13697   } else {
13698     @<Input from token list; |goto restart| if end of list or
13699       if a parameter needs to be expanded,
13700       or |return| if a non-symbolic token is found@>;
13701   }
13702 COMMON_ENDING: 
13703   @<Finish getting the symbolic token in |cur_sym|;
13704    |goto restart| if it is illegal@>;
13705 }
13706
13707 @ When a symbolic token is declared to be `\&{outer}', its command code
13708 is increased by |outer_tag|.
13709 @^inner loop@>
13710
13711 @<Finish getting the symbolic token in |cur_sym|...@>=
13712 mp->cur_cmd=eq_type(mp->cur_sym); mp->cur_mod=equiv(mp->cur_sym);
13713 if ( mp->cur_cmd>=outer_tag ) {
13714   if ( mp_check_outer_validity(mp) ) 
13715     mp->cur_cmd=mp->cur_cmd-outer_tag;
13716   else 
13717     goto RESTART;
13718 }
13719
13720 @ A percent sign appears in |buffer[limit]|; this makes it unnecessary
13721 to have a special test for end-of-line.
13722 @^inner loop@>
13723
13724 @<Input from external file;...@>=
13725
13726 SWITCH: 
13727   c=mp->buffer[loc]; incr(loc); class=mp->char_class[c];
13728   switch (class) {
13729   case digit_class: goto START_NUMERIC_TOKEN; break;
13730   case period_class: 
13731     class=mp->char_class[mp->buffer[loc]];
13732     if ( class>period_class ) {
13733       goto SWITCH;
13734     } else if ( class<period_class ) { /* |class=digit_class| */
13735       n=0; goto START_DECIMAL_TOKEN;
13736     }
13737 @:. }{\..\ token@>
13738     break;
13739   case space_class: goto SWITCH; break;
13740   case percent_class: 
13741     if ( mp->scanner_status==tex_flushing ) {
13742       if ( loc<limit ) goto SWITCH;
13743     }
13744     @<Move to next line of file, or |goto restart| if there is no next line@>;
13745     check_interrupt;
13746     goto SWITCH;
13747     break;
13748   case string_class: 
13749     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13750     else @<Get a string token and |return|@>;
13751     break;
13752   case isolated_classes: 
13753     k=loc-1; goto FOUND; break;
13754   case invalid_class: 
13755     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13756     else @<Decry the invalid character and |goto restart|@>;
13757     break;
13758   default: break; /* letters, etc. */
13759   }
13760   k=loc-1;
13761   while ( mp->char_class[mp->buffer[loc]]==class ) incr(loc);
13762   goto FOUND;
13763 START_NUMERIC_TOKEN:
13764   @<Get the integer part |n| of a numeric token;
13765     set |f:=0| and |goto fin_numeric_token| if there is no decimal point@>;
13766 START_DECIMAL_TOKEN:
13767   @<Get the fraction part |f| of a numeric token@>;
13768 FIN_NUMERIC_TOKEN:
13769   @<Pack the numeric and fraction parts of a numeric token
13770     and |return|@>;
13771 FOUND: 
13772   mp->cur_sym=mp_id_lookup(mp, k,loc-k);
13773 }
13774
13775 @ We go to |restart| instead of to |SWITCH|, because |state| might equal
13776 |token_list| after the error has been dealt with
13777 (cf.\ |clear_for_error_prompt|).
13778
13779 @<Decry the invalid...@>=
13780
13781   print_err("Text line contains an invalid character");
13782 @.Text line contains...@>
13783   help2("A funny symbol that I can\'t read has just been input.")
13784     ("Continue, and I'll forget that it ever happened.");
13785   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13786   goto RESTART;
13787 }
13788
13789 @ @<Get a string token and |return|@>=
13790
13791   if ( mp->buffer[loc]=='"' ) {
13792     mp->cur_mod=rts("");
13793   } else { 
13794     k=loc; mp->buffer[limit+1]='"';
13795     do {  
13796      incr(loc);
13797     } while (mp->buffer[loc]!='"');
13798     if ( loc>limit ) {
13799       @<Decry the missing string delimiter and |goto restart|@>;
13800     }
13801     if ( loc==k+1 ) {
13802       mp->cur_mod=mp->buffer[k];
13803     } else { 
13804       str_room(loc-k);
13805       do {  
13806         append_char(mp->buffer[k]); incr(k);
13807       } while (k!=loc);
13808       mp->cur_mod=mp_make_string(mp);
13809     }
13810   }
13811   incr(loc); mp->cur_cmd=string_token; 
13812   return;
13813 }
13814
13815 @ We go to |restart| after this error message, not to |SWITCH|,
13816 because the |clear_for_error_prompt| routine might have reinstated
13817 |token_state| after |error| has finished.
13818
13819 @<Decry the missing string delimiter and |goto restart|@>=
13820
13821   loc=limit; /* the next character to be read on this line will be |"%"| */
13822   print_err("Incomplete string token has been flushed");
13823 @.Incomplete string token...@>
13824   help3("Strings should finish on the same line as they began.")
13825     ("I've deleted the partial string; you might want to")
13826     ("insert another by typing, e.g., `I\"new string\"'.");
13827   mp->deletions_allowed=false; mp_error(mp);
13828   mp->deletions_allowed=true; 
13829   goto RESTART;
13830 }
13831
13832 @ @<Get the integer part |n| of a numeric token...@>=
13833 n=c-'0';
13834 while ( mp->char_class[mp->buffer[loc]]==digit_class ) {
13835   if ( n<32768 ) n=10*n+mp->buffer[loc]-'0';
13836   incr(loc);
13837 }
13838 if ( mp->buffer[loc]=='.' ) 
13839   if ( mp->char_class[mp->buffer[loc+1]]==digit_class ) 
13840     goto DONE;
13841 f=0; 
13842 goto FIN_NUMERIC_TOKEN;
13843 DONE: incr(loc)
13844
13845 @ @<Get the fraction part |f| of a numeric token@>=
13846 k=0;
13847 do { 
13848   if ( k<17 ) { /* digits for |k>=17| cannot affect the result */
13849     mp->dig[k]=mp->buffer[loc]-'0'; incr(k);
13850   }
13851   incr(loc);
13852 } while (mp->char_class[mp->buffer[loc]]==digit_class);
13853 f=mp_round_decimals(mp, k);
13854 if ( f==unity ) {
13855   incr(n); f=0;
13856 }
13857
13858 @ @<Pack the numeric and fraction parts of a numeric token and |return|@>=
13859 if ( n<32768 ) {
13860   @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>;
13861 } else if ( mp->scanner_status!=tex_flushing ) {
13862   print_err("Enormous number has been reduced");
13863 @.Enormous number...@>
13864   help2("I can\'t handle numbers bigger than 32767.99998;")
13865     ("so I've changed your constant to that maximum amount.");
13866   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13867   mp->cur_mod=el_gordo;
13868 }
13869 mp->cur_cmd=numeric_token; return
13870
13871 @ @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>=
13872
13873   mp->cur_mod=n*unity+f;
13874   if ( mp->cur_mod>=fraction_one ) {
13875     if ( (mp->internal[mp_warning_check]>0) &&
13876          (mp->scanner_status!=tex_flushing) ) {
13877       print_err("Number is too large (");
13878       mp_print_scaled(mp, mp->cur_mod);
13879       mp_print_char(mp, ')');
13880       help3("It is at least 4096. Continue and I'll try to cope")
13881       ("with that big value; but it might be dangerous.")
13882       ("(Set warningcheck:=0 to suppress this message.)");
13883       mp_error(mp);
13884     }
13885   }
13886 }
13887
13888 @ Let's consider now what happens when |get_next| is looking at a token list.
13889 @^inner loop@>
13890
13891 @<Input from token list;...@>=
13892 if ( loc>=mp->hi_mem_min ) { /* one-word token */
13893   mp->cur_sym=info(loc); loc=link(loc); /* move to next */
13894   if ( mp->cur_sym>=expr_base ) {
13895     if ( mp->cur_sym>=suffix_base ) {
13896       @<Insert a suffix or text parameter and |goto restart|@>;
13897     } else { 
13898       mp->cur_cmd=capsule_token;
13899       mp->cur_mod=mp->param_stack[param_start+mp->cur_sym-(expr_base)];
13900       mp->cur_sym=0; return;
13901     }
13902   }
13903 } else if ( loc>null ) {
13904   @<Get a stored numeric or string or capsule token and |return|@>
13905 } else { /* we are done with this token list */
13906   mp_end_token_list(mp); goto RESTART; /* resume previous level */
13907 }
13908
13909 @ @<Insert a suffix or text parameter...@>=
13910
13911   if ( mp->cur_sym>=text_base ) mp->cur_sym=mp->cur_sym-mp->param_size;
13912   /* |param_size=text_base-suffix_base| */
13913   mp_begin_token_list(mp,
13914                       mp->param_stack[param_start+mp->cur_sym-(suffix_base)],
13915                       parameter);
13916   goto RESTART;
13917 }
13918
13919 @ @<Get a stored numeric or string or capsule token...@>=
13920
13921   if ( name_type(loc)==mp_token ) {
13922     mp->cur_mod=value(loc);
13923     if ( type(loc)==mp_known ) {
13924       mp->cur_cmd=numeric_token;
13925     } else { 
13926       mp->cur_cmd=string_token; add_str_ref(mp->cur_mod);
13927     }
13928   } else { 
13929     mp->cur_mod=loc; mp->cur_cmd=capsule_token;
13930   };
13931   loc=link(loc); return;
13932 }
13933
13934 @ All of the easy branches of |get_next| have now been taken care of.
13935 There is one more branch.
13936
13937 @<Move to next line of file, or |goto restart|...@>=
13938 if ( name>max_spec_src ) {
13939   @<Read next line of file into |buffer|, or
13940     |goto restart| if the file has ended@>;
13941 } else { 
13942   if ( mp->input_ptr>0 ) {
13943      /* text was inserted during error recovery or by \&{scantokens} */
13944     mp_end_file_reading(mp); goto RESTART; /* resume previous level */
13945   }
13946   if ( mp->selector<log_only || mp->selector>=write_file) mp_open_log_file(mp);
13947   if ( mp->interaction>mp_nonstop_mode ) {
13948     if ( limit==start ) /* previous line was empty */
13949       mp_print_nl(mp, "(Please type a command or say `end')");
13950 @.Please type...@>
13951     mp_print_ln(mp); mp->first=start;
13952     prompt_input("*"); /* input on-line into |buffer| */
13953 @.*\relax@>
13954     limit=mp->last; mp->buffer[limit]='%';
13955     mp->first=limit+1; loc=start;
13956   } else {
13957     mp_fatal_error(mp, "*** (job aborted, no legal end found)");
13958 @.job aborted@>
13959     /* nonstop mode, which is intended for overnight batch processing,
13960     never waits for on-line input */
13961   }
13962 }
13963
13964 @ The global variable |force_eof| is normally |false|; it is set |true|
13965 by an \&{endinput} command.
13966
13967 @<Glob...@>=
13968 boolean force_eof; /* should the next \&{input} be aborted early? */
13969
13970 @ We must decrement |loc| in order to leave the buffer in a valid state
13971 when an error condition causes us to |goto restart| without calling
13972 |end_file_reading|.
13973
13974 @<Read next line of file into |buffer|, or
13975   |goto restart| if the file has ended@>=
13976
13977   incr(line); mp->first=start;
13978   if ( ! mp->force_eof ) {
13979     if ( mp_input_ln(mp, cur_file,true) ) /* not end of file */
13980       mp_firm_up_the_line(mp); /* this sets |limit| */
13981     else 
13982       mp->force_eof=true;
13983   };
13984   if ( mp->force_eof ) {
13985     mp->force_eof=false;
13986     decr(loc);
13987     if ( mpx_reading ) {
13988       @<Complain that the \.{MPX} file ended unexpectly; then set
13989         |cur_sym:=frozen_mpx_break| and |goto comon_ending|@>;
13990     } else { 
13991       mp_print_char(mp, ')'); decr(mp->open_parens);
13992       update_terminal; /* show user that file has been read */
13993       mp_end_file_reading(mp); /* resume previous level */
13994       if ( mp_check_outer_validity(mp) ) goto  RESTART;  
13995       else goto RESTART;
13996     }
13997   }
13998   mp->buffer[limit]='%'; mp->first=limit+1; loc=start; /* ready to read */
13999 }
14000
14001 @ We should never actually come to the end of an \.{MPX} file because such
14002 files should have an \&{mpxbreak} after the translation of the last
14003 \&{btex}$\,\ldots\,$\&{etex} block.
14004
14005 @<Complain that the \.{MPX} file ended unexpectly; then set...@>=
14006
14007   mp->mpx_name[index]=finished;
14008   print_err("mpx file ended unexpectedly");
14009   help4("The file had too few picture expressions for btex...etex")
14010     ("blocks.  Such files are normally generated automatically")
14011     ("but this one got messed up.  You might want to insert a")
14012     ("picture expression now.");
14013   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
14014   mp->cur_sym=frozen_mpx_break; goto COMMON_ENDING;
14015 }
14016
14017 @ Sometimes we want to make it look as though we have just read a blank line
14018 without really doing so.
14019
14020 @<Put an empty line in the input buffer@>=
14021 mp->last=mp->first; limit=mp->last; /* simulate |input_ln| and |firm_up_the_line| */
14022 mp->buffer[limit]='%'; mp->first=limit+1; loc=start
14023
14024 @ If the user has set the |mp_pausing| parameter to some positive value,
14025 and if nonstop mode has not been selected, each line of input is displayed
14026 on the terminal and the transcript file, followed by `\.{=>}'.
14027 \MP\ waits for a response. If the response is null (i.e., if nothing is
14028 typed except perhaps a few blank spaces), the original
14029 line is accepted as it stands; otherwise the line typed is
14030 used instead of the line in the file.
14031
14032 @c void mp_firm_up_the_line (MP mp) {
14033   size_t k; /* an index into |buffer| */
14034   limit=mp->last;
14035   if ( mp->internal[mp_pausing]>0 ) if ( mp->interaction>mp_nonstop_mode ) {
14036     wake_up_terminal; mp_print_ln(mp);
14037     if ( start<limit ) {
14038       for (k=(size_t)start;k<=(size_t)(limit-1);k++) {
14039         mp_print_str(mp, mp->buffer[k]);
14040       } 
14041     }
14042     mp->first=limit; prompt_input("=>"); /* wait for user response */
14043 @.=>@>
14044     if ( mp->last>mp->first ) {
14045       for (k=mp->first;k<=mp->last-1;k++) { /* move line down in buffer */
14046         mp->buffer[k+start-mp->first]=mp->buffer[k];
14047       }
14048       limit=start+mp->last-mp->first;
14049     }
14050   }
14051 }
14052
14053 @* \[30] Dealing with \TeX\ material.
14054 The \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}$\,\ldots\,$\&{etex}
14055 features need to be implemented at a low level in the scanning process
14056 so that \MP\ can stay in synch with the a preprocessor that treats
14057 blocks of \TeX\ material as they occur in the input file without trying
14058 to expand \MP\ macros.  Thus we need a special version of |get_next|
14059 that does not expand macros and such but does handle \&{btex},
14060 \&{verbatimtex}, etc.
14061
14062 The special version of |get_next| is called |get_t_next|.  It works by flushing
14063 \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}\allowbreak
14064 $\,\ldots\,$\&{etex} blocks, switching to the \.{MPX} file when it sees
14065 \&{btex}, and switching back when it sees \&{mpxbreak}.
14066
14067 @d btex_code 0
14068 @d verbatim_code 1
14069
14070 @ @<Put each...@>=
14071 mp_primitive(mp, "btex",start_tex,btex_code);
14072 @:btex_}{\&{btex} primitive@>
14073 mp_primitive(mp, "verbatimtex",start_tex,verbatim_code);
14074 @:verbatimtex_}{\&{verbatimtex} primitive@>
14075 mp_primitive(mp, "etex",etex_marker,0); mp->eqtb[frozen_etex]=mp->eqtb[mp->cur_sym];
14076 @:etex_}{\&{etex} primitive@>
14077 mp_primitive(mp, "mpxbreak",mpx_break,0); mp->eqtb[frozen_mpx_break]=mp->eqtb[mp->cur_sym];
14078 @:mpx_break_}{\&{mpxbreak} primitive@>
14079
14080 @ @<Cases of |print_cmd...@>=
14081 case start_tex: if ( m==btex_code ) mp_print(mp, "btex");
14082   else mp_print(mp, "verbatimtex"); break;
14083 case etex_marker: mp_print(mp, "etex"); break;
14084 case mpx_break: mp_print(mp, "mpxbreak"); break;
14085
14086 @ Actually, |get_t_next| is a macro that avoids procedure overhead except
14087 in the unusual case where \&{btex}, \&{verbatimtex}, \&{etex}, or \&{mpxbreak}
14088 is encountered.
14089
14090 @d get_t_next {mp_get_next(mp); if ( mp->cur_cmd<=max_pre_command ) mp_t_next(mp); }
14091
14092 @<Declarations@>=
14093 void mp_start_mpx_input (MP mp);
14094
14095 @ @c 
14096 void mp_t_next (MP mp) {
14097   int old_status; /* saves the |scanner_status| */
14098   integer old_info; /* saves the |warning_info| */
14099   while ( mp->cur_cmd<=max_pre_command ) {
14100     if ( mp->cur_cmd==mpx_break ) {
14101       if ( ! file_state || (mp->mpx_name[index]==absent) ) {
14102         @<Complain about a misplaced \&{mpxbreak}@>;
14103       } else { 
14104         mp_end_mpx_reading(mp); 
14105         goto TEX_FLUSH;
14106       }
14107     } else if ( mp->cur_cmd==start_tex ) {
14108       if ( token_state || (name<=max_spec_src) ) {
14109         @<Complain that we are not reading a file@>;
14110       } else if ( mpx_reading ) {
14111         @<Complain that \.{MPX} files cannot contain \TeX\ material@>;
14112       } else if ( (mp->cur_mod!=verbatim_code)&&
14113                   (mp->mpx_name[index]!=finished) ) {
14114         if ( ! mp_begin_mpx_reading(mp) ) mp_start_mpx_input(mp);
14115       } else {
14116         goto TEX_FLUSH;
14117       }
14118     } else {
14119        @<Complain about a misplaced \&{etex}@>;
14120     }
14121     goto COMMON_ENDING;
14122   TEX_FLUSH: 
14123     @<Flush the \TeX\ material@>;
14124   COMMON_ENDING: 
14125     mp_get_next(mp);
14126   }
14127 }
14128
14129 @ We could be in the middle of an operation such as skipping false conditional
14130 text when \TeX\ material is encountered, so we must be careful to save the
14131 |scanner_status|.
14132
14133 @<Flush the \TeX\ material@>=
14134 old_status=mp->scanner_status;
14135 old_info=mp->warning_info;
14136 mp->scanner_status=tex_flushing;
14137 mp->warning_info=line;
14138 do {  mp_get_next(mp); } while (mp->cur_cmd!=etex_marker);
14139 mp->scanner_status=old_status;
14140 mp->warning_info=old_info
14141
14142 @ @<Complain that \.{MPX} files cannot contain \TeX\ material@>=
14143 { print_err("An mpx file cannot contain btex or verbatimtex blocks");
14144 help4("This file contains picture expressions for btex...etex")
14145   ("blocks.  Such files are normally generated automatically")
14146   ("but this one seems to be messed up.  I'll just keep going")
14147   ("and hope for the best.");
14148 mp_error(mp);
14149 }
14150
14151 @ @<Complain that we are not reading a file@>=
14152 { print_err("You can only use `btex' or `verbatimtex' in a file");
14153 help3("I'll have to ignore this preprocessor command because it")
14154   ("only works when there is a file to preprocess.  You might")
14155   ("want to delete everything up to the next `etex`.");
14156 mp_error(mp);
14157 }
14158
14159 @ @<Complain about a misplaced \&{mpxbreak}@>=
14160 { print_err("Misplaced mpxbreak");
14161 help2("I'll ignore this preprocessor command because it")
14162   ("doesn't belong here");
14163 mp_error(mp);
14164 }
14165
14166 @ @<Complain about a misplaced \&{etex}@>=
14167 { print_err("Extra etex will be ignored");
14168 help1("There is no btex or verbatimtex for this to match");
14169 mp_error(mp);
14170 }
14171
14172 @* \[31] Scanning macro definitions.
14173 \MP\ has a variety of ways to tuck tokens away into token lists for later
14174 use: Macros can be defined with \&{def}, \&{vardef}, \&{primarydef}, etc.;
14175 repeatable code can be defined with \&{for}, \&{forever}, \&{forsuffixes}.
14176 All such operations are handled by the routines in this part of the program.
14177
14178 The modifier part of each command code is zero for the ``ending delimiters''
14179 like \&{enddef} and \&{endfor}.
14180
14181 @d start_def 1 /* command modifier for \&{def} */
14182 @d var_def 2 /* command modifier for \&{vardef} */
14183 @d end_def 0 /* command modifier for \&{enddef} */
14184 @d start_forever 1 /* command modifier for \&{forever} */
14185 @d end_for 0 /* command modifier for \&{endfor} */
14186
14187 @<Put each...@>=
14188 mp_primitive(mp, "def",macro_def,start_def);
14189 @:def_}{\&{def} primitive@>
14190 mp_primitive(mp, "vardef",macro_def,var_def);
14191 @:var_def_}{\&{vardef} primitive@>
14192 mp_primitive(mp, "primarydef",macro_def,secondary_primary_macro);
14193 @:primary_def_}{\&{primarydef} primitive@>
14194 mp_primitive(mp, "secondarydef",macro_def,tertiary_secondary_macro);
14195 @:secondary_def_}{\&{secondarydef} primitive@>
14196 mp_primitive(mp, "tertiarydef",macro_def,expression_tertiary_macro);
14197 @:tertiary_def_}{\&{tertiarydef} primitive@>
14198 mp_primitive(mp, "enddef",macro_def,end_def); mp->eqtb[frozen_end_def]=mp->eqtb[mp->cur_sym];
14199 @:end_def_}{\&{enddef} primitive@>
14200 @#
14201 mp_primitive(mp, "for",iteration,expr_base);
14202 @:for_}{\&{for} primitive@>
14203 mp_primitive(mp, "forsuffixes",iteration,suffix_base);
14204 @:for_suffixes_}{\&{forsuffixes} primitive@>
14205 mp_primitive(mp, "forever",iteration,start_forever);
14206 @:forever_}{\&{forever} primitive@>
14207 mp_primitive(mp, "endfor",iteration,end_for); mp->eqtb[frozen_end_for]=mp->eqtb[mp->cur_sym];
14208 @:end_for_}{\&{endfor} primitive@>
14209
14210 @ @<Cases of |print_cmd...@>=
14211 case macro_def:
14212   if ( m<=var_def ) {
14213     if ( m==start_def ) mp_print(mp, "def");
14214     else if ( m<start_def ) mp_print(mp, "enddef");
14215     else mp_print(mp, "vardef");
14216   } else if ( m==secondary_primary_macro ) { 
14217     mp_print(mp, "primarydef");
14218   } else if ( m==tertiary_secondary_macro ) { 
14219     mp_print(mp, "secondarydef");
14220   } else { 
14221     mp_print(mp, "tertiarydef");
14222   }
14223   break;
14224 case iteration: 
14225   if ( m<=start_forever ) {
14226     if ( m==start_forever ) mp_print(mp, "forever"); 
14227     else mp_print(mp, "endfor");
14228   } else if ( m==expr_base ) {
14229     mp_print(mp, "for"); 
14230   } else { 
14231     mp_print(mp, "forsuffixes");
14232   }
14233   break;
14234
14235 @ Different macro-absorbing operations have different syntaxes, but they
14236 also have a lot in common. There is a list of special symbols that are to
14237 be replaced by parameter tokens; there is a special command code that
14238 ends the definition; the quotation conventions are identical.  Therefore
14239 it makes sense to have most of the work done by a single subroutine. That
14240 subroutine is called |scan_toks|.
14241
14242 The first parameter to |scan_toks| is the command code that will
14243 terminate scanning (either |macro_def|, |loop_repeat|, or |iteration|).
14244
14245 The second parameter, |subst_list|, points to a (possibly empty) list
14246 of two-word nodes whose |info| and |value| fields specify symbol tokens
14247 before and after replacement. The list will be returned to free storage
14248 by |scan_toks|.
14249
14250 The third parameter is simply appended to the token list that is built.
14251 And the final parameter tells how many of the special operations
14252 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#} are to be replaced by suffix parameters.
14253 When such parameters are present, they are called \.{(SUFFIX0)},
14254 \.{(SUFFIX1)}, and \.{(SUFFIX2)}.
14255
14256 @c pointer mp_scan_toks (MP mp,command_code terminator, pointer 
14257   subst_list, pointer tail_end, small_number suffix_count) {
14258   pointer p; /* tail of the token list being built */
14259   pointer q; /* temporary for link management */
14260   integer balance; /* left delimiters minus right delimiters */
14261   p=hold_head; balance=1; link(hold_head)=null;
14262   while (1) { 
14263     get_t_next;
14264     if ( mp->cur_sym>0 ) {
14265       @<Substitute for |cur_sym|, if it's on the |subst_list|@>;
14266       if ( mp->cur_cmd==terminator ) {
14267         @<Adjust the balance; |break| if it's zero@>;
14268       } else if ( mp->cur_cmd==macro_special ) {
14269         @<Handle quoted symbols, \.{\#\AT!}, \.{\AT!}, or \.{\AT!\#}@>;
14270       }
14271     }
14272     link(p)=mp_cur_tok(mp); p=link(p);
14273   }
14274   link(p)=tail_end; mp_flush_node_list(mp, subst_list);
14275   return link(hold_head);
14276 }
14277
14278 @ @<Substitute for |cur_sym|...@>=
14279
14280   q=subst_list;
14281   while ( q!=null ) {
14282     if ( info(q)==mp->cur_sym ) {
14283       mp->cur_sym=value(q); mp->cur_cmd=relax; break;
14284     }
14285     q=link(q);
14286   }
14287 }
14288
14289 @ @<Adjust the balance; |break| if it's zero@>=
14290 if ( mp->cur_mod>0 ) {
14291   incr(balance);
14292 } else { 
14293   decr(balance);
14294   if ( balance==0 )
14295     break;
14296 }
14297
14298 @ Four commands are intended to be used only within macro texts: \&{quote},
14299 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#}. They are variants of a single command
14300 code called |macro_special|.
14301
14302 @d quote 0 /* |macro_special| modifier for \&{quote} */
14303 @d macro_prefix 1 /* |macro_special| modifier for \.{\#\AT!} */
14304 @d macro_at 2 /* |macro_special| modifier for \.{\AT!} */
14305 @d macro_suffix 3 /* |macro_special| modifier for \.{\AT!\#} */
14306
14307 @<Put each...@>=
14308 mp_primitive(mp, "quote",macro_special,quote);
14309 @:quote_}{\&{quote} primitive@>
14310 mp_primitive(mp, "#@@",macro_special,macro_prefix);
14311 @:]]]\#\AT!_}{\.{\#\AT!} primitive@>
14312 mp_primitive(mp, "@@",macro_special,macro_at);
14313 @:]]]\AT!_}{\.{\AT!} primitive@>
14314 mp_primitive(mp, "@@#",macro_special,macro_suffix);
14315 @:]]]\AT!\#_}{\.{\AT!\#} primitive@>
14316
14317 @ @<Cases of |print_cmd...@>=
14318 case macro_special: 
14319   switch (m) {
14320   case macro_prefix: mp_print(mp, "#@@"); break;
14321   case macro_at: mp_print_char(mp, '@@'); break;
14322   case macro_suffix: mp_print(mp, "@@#"); break;
14323   default: mp_print(mp, "quote"); break;
14324   }
14325   break;
14326
14327 @ @<Handle quoted...@>=
14328
14329   if ( mp->cur_mod==quote ) { get_t_next; } 
14330   else if ( mp->cur_mod<=suffix_count ) 
14331     mp->cur_sym=suffix_base-1+mp->cur_mod;
14332 }
14333
14334 @ Here is a routine that's used whenever a token will be redefined. If
14335 the user's token is unredefinable, the `|frozen_inaccessible|' token is
14336 substituted; the latter is redefinable but essentially impossible to use,
14337 hence \MP's tables won't get fouled up.
14338
14339 @c void mp_get_symbol (MP mp) { /* sets |cur_sym| to a safe symbol */
14340 RESTART: 
14341   get_t_next;
14342   if ( (mp->cur_sym==0)||(mp->cur_sym>frozen_inaccessible) ) {
14343     print_err("Missing symbolic token inserted");
14344 @.Missing symbolic token...@>
14345     help3("Sorry: You can\'t redefine a number, string, or expr.")
14346       ("I've inserted an inaccessible symbol so that your")
14347       ("definition will be completed without mixing me up too badly.");
14348     if ( mp->cur_sym>0 )
14349       mp->help_line[2]="Sorry: You can\'t redefine my error-recovery tokens.";
14350     else if ( mp->cur_cmd==string_token ) 
14351       delete_str_ref(mp->cur_mod);
14352     mp->cur_sym=frozen_inaccessible; mp_ins_error(mp); goto RESTART;
14353   }
14354 }
14355
14356 @ Before we actually redefine a symbolic token, we need to clear away its
14357 former value, if it was a variable. The following stronger version of
14358 |get_symbol| does that.
14359
14360 @c void mp_get_clear_symbol (MP mp) { 
14361   mp_get_symbol(mp); mp_clear_symbol(mp, mp->cur_sym,false);
14362 }
14363
14364 @ Here's another little subroutine; it checks that an equals sign
14365 or assignment sign comes along at the proper place in a macro definition.
14366
14367 @c void mp_check_equals (MP mp) { 
14368   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
14369      mp_missing_err(mp, "=");
14370 @.Missing `='@>
14371     help5("The next thing in this `def' should have been `=',")
14372       ("because I've already looked at the definition heading.")
14373       ("But don't worry; I'll pretend that an equals sign")
14374       ("was present. Everything from here to `enddef'")
14375       ("will be the replacement text of this macro.");
14376     mp_back_error(mp);
14377   }
14378 }
14379
14380 @ A \&{primarydef}, \&{secondarydef}, or \&{tertiarydef} is rather easily
14381 handled now that we have |scan_toks|.  In this case there are
14382 two parameters, which will be \.{EXPR0} and \.{EXPR1} (i.e.,
14383 |expr_base| and |expr_base+1|).
14384
14385 @c void mp_make_op_def (MP mp) {
14386   command_code m; /* the type of definition */
14387   pointer p,q,r; /* for list manipulation */
14388   m=mp->cur_mod;
14389   mp_get_symbol(mp); q=mp_get_node(mp, token_node_size);
14390   info(q)=mp->cur_sym; value(q)=expr_base;
14391   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym;
14392   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
14393   info(p)=mp->cur_sym; value(p)=expr_base+1; link(p)=q;
14394   get_t_next; mp_check_equals(mp);
14395   mp->scanner_status=op_defining; q=mp_get_avail(mp); ref_count(q)=null;
14396   r=mp_get_avail(mp); link(q)=r; info(r)=general_macro;
14397   link(r)=mp_scan_toks(mp, macro_def,p,null,0);
14398   mp->scanner_status=normal; eq_type(mp->warning_info)=m;
14399   equiv(mp->warning_info)=q; mp_get_x_next(mp);
14400 }
14401
14402 @ Parameters to macros are introduced by the keywords \&{expr},
14403 \&{suffix}, \&{text}, \&{primary}, \&{secondary}, and \&{tertiary}.
14404
14405 @<Put each...@>=
14406 mp_primitive(mp, "expr",param_type,expr_base);
14407 @:expr_}{\&{expr} primitive@>
14408 mp_primitive(mp, "suffix",param_type,suffix_base);
14409 @:suffix_}{\&{suffix} primitive@>
14410 mp_primitive(mp, "text",param_type,text_base);
14411 @:text_}{\&{text} primitive@>
14412 mp_primitive(mp, "primary",param_type,primary_macro);
14413 @:primary_}{\&{primary} primitive@>
14414 mp_primitive(mp, "secondary",param_type,secondary_macro);
14415 @:secondary_}{\&{secondary} primitive@>
14416 mp_primitive(mp, "tertiary",param_type,tertiary_macro);
14417 @:tertiary_}{\&{tertiary} primitive@>
14418
14419 @ @<Cases of |print_cmd...@>=
14420 case param_type:
14421   if ( m>=expr_base ) {
14422     if ( m==expr_base ) mp_print(mp, "expr");
14423     else if ( m==suffix_base ) mp_print(mp, "suffix");
14424     else mp_print(mp, "text");
14425   } else if ( m<secondary_macro ) {
14426     mp_print(mp, "primary");
14427   } else if ( m==secondary_macro ) {
14428     mp_print(mp, "secondary");
14429   } else {
14430     mp_print(mp, "tertiary");
14431   }
14432   break;
14433
14434 @ Let's turn next to the more complex processing associated with \&{def}
14435 and \&{vardef}. When the following procedure is called, |cur_mod|
14436 should be either |start_def| or |var_def|.
14437
14438 @c @<Declare the procedure called |check_delimiter|@>;
14439 @<Declare the function called |scan_declared_variable|@>;
14440 void mp_scan_def (MP mp) {
14441   int m; /* the type of definition */
14442   int n; /* the number of special suffix parameters */
14443   int k; /* the total number of parameters */
14444   int c; /* the kind of macro we're defining */
14445   pointer r; /* parameter-substitution list */
14446   pointer q; /* tail of the macro token list */
14447   pointer p; /* temporary storage */
14448   halfword base; /* |expr_base|, |suffix_base|, or |text_base| */
14449   pointer l_delim,r_delim; /* matching delimiters */
14450   m=mp->cur_mod; c=general_macro; link(hold_head)=null;
14451   q=mp_get_avail(mp); ref_count(q)=null; r=null;
14452   @<Scan the token or variable to be defined;
14453     set |n|, |scanner_status|, and |warning_info|@>;
14454   k=n;
14455   if ( mp->cur_cmd==left_delimiter ) {
14456     @<Absorb delimited parameters, putting them into lists |q| and |r|@>;
14457   }
14458   if ( mp->cur_cmd==param_type ) {
14459     @<Absorb undelimited parameters, putting them into list |r|@>;
14460   }
14461   mp_check_equals(mp);
14462   p=mp_get_avail(mp); info(p)=c; link(q)=p;
14463   @<Attach the replacement text to the tail of node |p|@>;
14464   mp->scanner_status=normal; mp_get_x_next(mp);
14465 }
14466
14467 @ We don't put `|frozen_end_group|' into the replacement text of
14468 a \&{vardef}, because the user may want to redefine `\.{endgroup}'.
14469
14470 @<Attach the replacement text to the tail of node |p|@>=
14471 if ( m==start_def ) {
14472   link(p)=mp_scan_toks(mp, macro_def,r,null,n);
14473 } else { 
14474   q=mp_get_avail(mp); info(q)=mp->bg_loc; link(p)=q;
14475   p=mp_get_avail(mp); info(p)=mp->eg_loc;
14476   link(q)=mp_scan_toks(mp, macro_def,r,p,n);
14477 }
14478 if ( mp->warning_info==bad_vardef ) 
14479   mp_flush_token_list(mp, value(bad_vardef))
14480
14481 @ @<Glob...@>=
14482 int bg_loc;
14483 int eg_loc; /* hash addresses of `\.{begingroup}' and `\.{endgroup}' */
14484
14485 @ @<Scan the token or variable to be defined;...@>=
14486 if ( m==start_def ) {
14487   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym; get_t_next;
14488   mp->scanner_status=op_defining; n=0;
14489   eq_type(mp->warning_info)=defined_macro; equiv(mp->warning_info)=q;
14490 } else { 
14491   p=mp_scan_declared_variable(mp);
14492   mp_flush_variable(mp, equiv(info(p)),link(p),true);
14493   mp->warning_info=mp_find_variable(mp, p); mp_flush_list(mp, p);
14494   if ( mp->warning_info==null ) @<Change to `\.{a bad variable}'@>;
14495   mp->scanner_status=var_defining; n=2;
14496   if ( mp->cur_cmd==macro_special ) if ( mp->cur_mod==macro_suffix ) {/* \.{\AT!\#} */
14497     n=3; get_t_next;
14498   }
14499   type(mp->warning_info)=mp_unsuffixed_macro-2+n; value(mp->warning_info)=q;
14500 } /* |mp_suffixed_macro=mp_unsuffixed_macro+1| */
14501
14502 @ @<Change to `\.{a bad variable}'@>=
14503
14504   print_err("This variable already starts with a macro");
14505 @.This variable already...@>
14506   help2("After `vardef a' you can\'t say `vardef a.b'.")
14507     ("So I'll have to discard this definition.");
14508   mp_error(mp); mp->warning_info=bad_vardef;
14509 }
14510
14511 @ @<Initialize table entries...@>=
14512 name_type(bad_vardef)=mp_root; link(bad_vardef)=frozen_bad_vardef;
14513 equiv(frozen_bad_vardef)=bad_vardef; eq_type(frozen_bad_vardef)=tag_token;
14514
14515 @ @<Absorb delimited parameters, putting them into lists |q| and |r|@>=
14516 do {  
14517   l_delim=mp->cur_sym; r_delim=mp->cur_mod; get_t_next;
14518   if ( (mp->cur_cmd==param_type)&&(mp->cur_mod>=expr_base) ) {
14519    base=mp->cur_mod;
14520   } else { 
14521     print_err("Missing parameter type; `expr' will be assumed");
14522 @.Missing parameter type@>
14523     help1("You should've had `expr' or `suffix' or `text' here.");
14524     mp_back_error(mp); base=expr_base;
14525   }
14526   @<Absorb parameter tokens for type |base|@>;
14527   mp_check_delimiter(mp, l_delim,r_delim);
14528   get_t_next;
14529 } while (mp->cur_cmd==left_delimiter)
14530
14531 @ @<Absorb parameter tokens for type |base|@>=
14532 do { 
14533   link(q)=mp_get_avail(mp); q=link(q); info(q)=base+k;
14534   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size); 
14535   value(p)=base+k; info(p)=mp->cur_sym;
14536   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14537 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
14538   incr(k); link(p)=r; r=p; get_t_next;
14539 } while (mp->cur_cmd==comma)
14540
14541 @ @<Absorb undelimited parameters, putting them into list |r|@>=
14542
14543   p=mp_get_node(mp, token_node_size);
14544   if ( mp->cur_mod<expr_base ) {
14545     c=mp->cur_mod; value(p)=expr_base+k;
14546   } else { 
14547     value(p)=mp->cur_mod+k;
14548     if ( mp->cur_mod==expr_base ) c=expr_macro;
14549     else if ( mp->cur_mod==suffix_base ) c=suffix_macro;
14550     else c=text_macro;
14551   }
14552   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14553   incr(k); mp_get_symbol(mp); info(p)=mp->cur_sym; link(p)=r; r=p; get_t_next;
14554   if ( c==expr_macro ) if ( mp->cur_cmd==of_token ) {
14555     c=of_macro; p=mp_get_node(mp, token_node_size);
14556     if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14557     value(p)=expr_base+k; mp_get_symbol(mp); info(p)=mp->cur_sym;
14558     link(p)=r; r=p; get_t_next;
14559   }
14560 }
14561
14562 @* \[32] Expanding the next token.
14563 Only a few command codes |<min_command| can possibly be returned by
14564 |get_t_next|; in increasing order, they are
14565 |if_test|, |fi_or_else|, |input|, |iteration|, |repeat_loop|,
14566 |exit_test|, |relax|, |scan_tokens|, |expand_after|, and |defined_macro|.
14567
14568 \MP\ usually gets the next token of input by saying |get_x_next|. This is
14569 like |get_t_next| except that it keeps getting more tokens until
14570 finding |cur_cmd>=min_command|. In other words, |get_x_next| expands
14571 macros and removes conditionals or iterations or input instructions that
14572 might be present.
14573
14574 It follows that |get_x_next| might invoke itself recursively. In fact,
14575 there is massive recursion, since macro expansion can involve the
14576 scanning of arbitrarily complex expressions, which in turn involve
14577 macro expansion and conditionals, etc.
14578 @^recursion@>
14579
14580 Therefore it's necessary to declare a whole bunch of |forward|
14581 procedures at this point, and to insert some other procedures
14582 that will be invoked by |get_x_next|.
14583
14584 @<Declarations@>= 
14585 void mp_scan_primary (MP mp);
14586 void mp_scan_secondary (MP mp);
14587 void mp_scan_tertiary (MP mp);
14588 void mp_scan_expression (MP mp);
14589 void mp_scan_suffix (MP mp);
14590 @<Declare the procedure called |macro_call|@>;
14591 void mp_get_boolean (MP mp);
14592 void mp_pass_text (MP mp);
14593 void mp_conditional (MP mp);
14594 void mp_start_input (MP mp);
14595 void mp_begin_iteration (MP mp);
14596 void mp_resume_iteration (MP mp);
14597 void mp_stop_iteration (MP mp);
14598
14599 @ An auxiliary subroutine called |expand| is used by |get_x_next|
14600 when it has to do exotic expansion commands.
14601
14602 @c void mp_expand (MP mp) {
14603   pointer p; /* for list manipulation */
14604   size_t k; /* something that we hope is |<=buf_size| */
14605   pool_pointer j; /* index into |str_pool| */
14606   if ( mp->internal[mp_tracing_commands]>unity ) 
14607     if ( mp->cur_cmd!=defined_macro )
14608       show_cur_cmd_mod;
14609   switch (mp->cur_cmd)  {
14610   case if_test:
14611     mp_conditional(mp); /* this procedure is discussed in Part 36 below */
14612     break;
14613   case fi_or_else:
14614     @<Terminate the current conditional and skip to \&{fi}@>;
14615     break;
14616   case input:
14617     @<Initiate or terminate input from a file@>;
14618     break;
14619   case iteration:
14620     if ( mp->cur_mod==end_for ) {
14621       @<Scold the user for having an extra \&{endfor}@>;
14622     } else {
14623       mp_begin_iteration(mp); /* this procedure is discussed in Part 37 below */
14624     }
14625     break;
14626   case repeat_loop: 
14627     @<Repeat a loop@>;
14628     break;
14629   case exit_test: 
14630     @<Exit a loop if the proper time has come@>;
14631     break;
14632   case relax: 
14633     break;
14634   case expand_after: 
14635     @<Expand the token after the next token@>;
14636     break;
14637   case scan_tokens: 
14638     @<Put a string into the input buffer@>;
14639     break;
14640   case defined_macro:
14641    mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14642    break;
14643   }; /* there are no other cases */
14644 };
14645
14646 @ @<Scold the user...@>=
14647
14648   print_err("Extra `endfor'");
14649 @.Extra `endfor'@>
14650   help2("I'm not currently working on a for loop,")
14651     ("so I had better not try to end anything.");
14652   mp_error(mp);
14653 }
14654
14655 @ The processing of \&{input} involves the |start_input| subroutine,
14656 which will be declared later; the processing of \&{endinput} is trivial.
14657
14658 @<Put each...@>=
14659 mp_primitive(mp, "input",input,0);
14660 @:input_}{\&{input} primitive@>
14661 mp_primitive(mp, "endinput",input,1);
14662 @:end_input_}{\&{endinput} primitive@>
14663
14664 @ @<Cases of |print_cmd_mod|...@>=
14665 case input: 
14666   if ( m==0 ) mp_print(mp, "input");
14667   else mp_print(mp, "endinput");
14668   break;
14669
14670 @ @<Initiate or terminate input...@>=
14671 if ( mp->cur_mod>0 ) mp->force_eof=true;
14672 else mp_start_input(mp)
14673
14674 @ We'll discuss the complicated parts of loop operations later. For now
14675 it suffices to know that there's a global variable called |loop_ptr|
14676 that will be |null| if no loop is in progress.
14677
14678 @<Repeat a loop@>=
14679 { while ( token_state &&(loc==null) ) 
14680     mp_end_token_list(mp); /* conserve stack space */
14681   if ( mp->loop_ptr==null ) {
14682     print_err("Lost loop");
14683 @.Lost loop@>
14684     help2("I'm confused; after exiting from a loop, I still seem")
14685       ("to want to repeat it. I'll try to forget the problem.");
14686     mp_error(mp);
14687   } else {
14688     mp_resume_iteration(mp); /* this procedure is in Part 37 below */
14689   }
14690 }
14691
14692 @ @<Exit a loop if the proper time has come@>=
14693 { mp_get_boolean(mp);
14694   if ( mp->internal[mp_tracing_commands]>unity ) 
14695     mp_show_cmd_mod(mp, nullary,mp->cur_exp);
14696   if ( mp->cur_exp==true_code ) {
14697     if ( mp->loop_ptr==null ) {
14698       print_err("No loop is in progress");
14699 @.No loop is in progress@>
14700       help1("Why say `exitif' when there's nothing to exit from?");
14701       if ( mp->cur_cmd==semicolon ) mp_error(mp); else mp_back_error(mp);
14702     } else {
14703      @<Exit prematurely from an iteration@>;
14704     }
14705   } else if ( mp->cur_cmd!=semicolon ) {
14706     mp_missing_err(mp, ";");
14707 @.Missing `;'@>
14708     help2("After `exitif <boolean exp>' I expect to see a semicolon.")
14709     ("I shall pretend that one was there."); mp_back_error(mp);
14710   }
14711 }
14712
14713 @ Here we use the fact that |forever_text| is the only |token_type| that
14714 is less than |loop_text|.
14715
14716 @<Exit prematurely...@>=
14717 { p=null;
14718   do {  
14719     if ( file_state ) {
14720       mp_end_file_reading(mp);
14721     } else { 
14722       if ( token_type<=loop_text ) p=start;
14723       mp_end_token_list(mp);
14724     }
14725   } while (p==null);
14726   if ( p!=info(mp->loop_ptr) ) mp_fatal_error(mp, "*** (loop confusion)");
14727 @.loop confusion@>
14728   mp_stop_iteration(mp); /* this procedure is in Part 34 below */
14729 }
14730
14731 @ @<Expand the token after the next token@>=
14732 { get_t_next;
14733   p=mp_cur_tok(mp); get_t_next;
14734   if ( mp->cur_cmd<min_command ) mp_expand(mp); 
14735   else mp_back_input(mp);
14736   back_list(p);
14737 }
14738
14739 @ @<Put a string into the input buffer@>=
14740 { mp_get_x_next(mp); mp_scan_primary(mp);
14741   if ( mp->cur_type!=mp_string_type ) {
14742     mp_disp_err(mp, null,"Not a string");
14743 @.Not a string@>
14744     help2("I'm going to flush this expression, since")
14745        ("scantokens should be followed by a known string.");
14746     mp_put_get_flush_error(mp, 0);
14747   } else { 
14748     mp_back_input(mp);
14749     if ( length(mp->cur_exp)>0 )
14750        @<Pretend we're reading a new one-line file@>;
14751   }
14752 }
14753
14754 @ @<Pretend we're reading a new one-line file@>=
14755 { mp_begin_file_reading(mp); name=is_scantok;
14756   k=mp->first+length(mp->cur_exp);
14757   if ( k>=mp->max_buf_stack ) {
14758     while ( k>=mp->buf_size ) {
14759       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
14760     }
14761     mp->max_buf_stack=k+1;
14762   }
14763   j=mp->str_start[mp->cur_exp]; limit=k;
14764   while ( mp->first<(size_t)limit ) {
14765     mp->buffer[mp->first]=mp->str_pool[j]; incr(j); incr(mp->first);
14766   }
14767   mp->buffer[limit]='%'; mp->first=limit+1; loc=start; 
14768   mp_flush_cur_exp(mp, 0);
14769 }
14770
14771 @ Here finally is |get_x_next|.
14772
14773 The expression scanning routines to be considered later
14774 communicate via the global quantities |cur_type| and |cur_exp|;
14775 we must be very careful to save and restore these quantities while
14776 macros are being expanded.
14777 @^inner loop@>
14778
14779 @<Declarations@>=
14780 void mp_get_x_next (MP mp);
14781
14782 @ @c void mp_get_x_next (MP mp) {
14783   pointer save_exp; /* a capsule to save |cur_type| and |cur_exp| */
14784   get_t_next;
14785   if ( mp->cur_cmd<min_command ) {
14786     save_exp=mp_stash_cur_exp(mp);
14787     do {  
14788       if ( mp->cur_cmd==defined_macro ) 
14789         mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14790       else 
14791         mp_expand(mp);
14792       get_t_next;
14793      } while (mp->cur_cmd<min_command);
14794      mp_unstash_cur_exp(mp, save_exp); /* that restores |cur_type| and |cur_exp| */
14795   }
14796 }
14797
14798 @ Now let's consider the |macro_call| procedure, which is used to start up
14799 all user-defined macros. Since the arguments to a macro might be expressions,
14800 |macro_call| is recursive.
14801 @^recursion@>
14802
14803 The first parameter to |macro_call| points to the reference count of the
14804 token list that defines the macro. The second parameter contains any
14805 arguments that have already been parsed (see below).  The third parameter
14806 points to the symbolic token that names the macro. If the third parameter
14807 is |null|, the macro was defined by \&{vardef}, so its name can be
14808 reconstructed from the prefix and ``at'' arguments found within the
14809 second parameter.
14810
14811 What is this second parameter? It's simply a linked list of one-word items,
14812 whose |info| fields point to the arguments. In other words, if |arg_list=null|,
14813 no arguments have been scanned yet; otherwise |info(arg_list)| points to
14814 the first scanned argument, and |link(arg_list)| points to the list of
14815 further arguments (if any).
14816
14817 Arguments of type \&{expr} are so-called capsules, which we will
14818 discuss later when we concentrate on expressions; they can be
14819 recognized easily because their |link| field is |void|. Arguments of type
14820 \&{suffix} and \&{text} are token lists without reference counts.
14821
14822 @ After argument scanning is complete, the arguments are moved to the
14823 |param_stack|. (They can't be put on that stack any sooner, because
14824 the stack is growing and shrinking in unpredictable ways as more arguments
14825 are being acquired.)  Then the macro body is fed to the scanner; i.e.,
14826 the replacement text of the macro is placed at the top of the \MP's
14827 input stack, so that |get_t_next| will proceed to read it next.
14828
14829 @<Declare the procedure called |macro_call|@>=
14830 @<Declare the procedure called |print_macro_name|@>;
14831 @<Declare the procedure called |print_arg|@>;
14832 @<Declare the procedure called |scan_text_arg|@>;
14833 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14834                     pointer macro_name) ;
14835
14836 @ @c
14837 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14838                     pointer macro_name) {
14839   /* invokes a user-defined control sequence */
14840   pointer r; /* current node in the macro's token list */
14841   pointer p,q; /* for list manipulation */
14842   integer n; /* the number of arguments */
14843   pointer tail = 0; /* tail of the argument list */
14844   pointer l_delim=0,r_delim=0; /* a delimiter pair */
14845   r=link(def_ref); add_mac_ref(def_ref);
14846   if ( arg_list==null ) {
14847     n=0;
14848   } else {
14849    @<Determine the number |n| of arguments already supplied,
14850     and set |tail| to the tail of |arg_list|@>;
14851   }
14852   if ( mp->internal[mp_tracing_macros]>0 ) {
14853     @<Show the text of the macro being expanded, and the existing arguments@>;
14854   }
14855   @<Scan the remaining arguments, if any; set |r| to the first token
14856     of the replacement text@>;
14857   @<Feed the arguments and replacement text to the scanner@>;
14858 }
14859
14860 @ @<Show the text of the macro...@>=
14861 mp_begin_diagnostic(mp); mp_print_ln(mp); 
14862 mp_print_macro_name(mp, arg_list,macro_name);
14863 if ( n==3 ) mp_print(mp, "@@#"); /* indicate a suffixed macro */
14864 mp_show_macro(mp, def_ref,null,100000);
14865 if ( arg_list!=null ) {
14866   n=0; p=arg_list;
14867   do {  
14868     q=info(p);
14869     mp_print_arg(mp, q,n,0);
14870     incr(n); p=link(p);
14871   } while (p!=null);
14872 }
14873 mp_end_diagnostic(mp, false)
14874
14875
14876 @ @<Declare the procedure called |print_macro_name|@>=
14877 void mp_print_macro_name (MP mp,pointer a, pointer n);
14878
14879 @ @c
14880 void mp_print_macro_name (MP mp,pointer a, pointer n) {
14881   pointer p,q; /* they traverse the first part of |a| */
14882   if ( n!=null ) {
14883     mp_print_text(n);
14884   } else  { 
14885     p=info(a);
14886     if ( p==null ) {
14887       mp_print_text(info(info(link(a))));
14888     } else { 
14889       q=p;
14890       while ( link(q)!=null ) q=link(q);
14891       link(q)=info(link(a));
14892       mp_show_token_list(mp, p,null,1000,0);
14893       link(q)=null;
14894     }
14895   }
14896 }
14897
14898 @ @<Declare the procedure called |print_arg|@>=
14899 void mp_print_arg (MP mp,pointer q, integer n, pointer b) ;
14900
14901 @ @c
14902 void mp_print_arg (MP mp,pointer q, integer n, pointer b) {
14903   if ( link(q)==mp_void ) mp_print_nl(mp, "(EXPR");
14904   else if ( (b<text_base)&&(b!=text_macro) ) mp_print_nl(mp, "(SUFFIX");
14905   else mp_print_nl(mp, "(TEXT");
14906   mp_print_int(mp, n); mp_print(mp, ")<-");
14907   if ( link(q)==mp_void ) mp_print_exp(mp, q,1);
14908   else mp_show_token_list(mp, q,null,1000,0);
14909 }
14910
14911 @ @<Determine the number |n| of arguments already supplied...@>=
14912 {  
14913   n=1; tail=arg_list;
14914   while ( link(tail)!=null ) { 
14915     incr(n); tail=link(tail);
14916   }
14917 }
14918
14919 @ @<Scan the remaining arguments, if any; set |r|...@>=
14920 mp->cur_cmd=comma+1; /* anything |<>comma| will do */
14921 while ( info(r)>=expr_base ) { 
14922   @<Scan the delimited argument represented by |info(r)|@>;
14923   r=link(r);
14924 };
14925 if ( mp->cur_cmd==comma ) {
14926   print_err("Too many arguments to ");
14927 @.Too many arguments...@>
14928   mp_print_macro_name(mp, arg_list,macro_name); mp_print_char(mp, ';');
14929   mp_print_nl(mp, "  Missing `"); mp_print_text(r_delim);
14930 @.Missing `)'...@>
14931   mp_print(mp, "' has been inserted");
14932   help3("I'm going to assume that the comma I just read was a")
14933    ("right delimiter, and then I'll begin expanding the macro.")
14934    ("You might want to delete some tokens before continuing.");
14935   mp_error(mp);
14936 }
14937 if ( info(r)!=general_macro ) {
14938   @<Scan undelimited argument(s)@>;
14939 }
14940 r=link(r)
14941
14942 @ At this point, the reader will find it advisable to review the explanation
14943 of token list format that was presented earlier, paying special attention to
14944 the conventions that apply only at the beginning of a macro's token list.
14945
14946 On the other hand, the reader will have to take the expression-parsing
14947 aspects of the following program on faith; we will explain |cur_type|
14948 and |cur_exp| later. (Several things in this program depend on each other,
14949 and it's necessary to jump into the circle somewhere.)
14950
14951 @<Scan the delimited argument represented by |info(r)|@>=
14952 if ( mp->cur_cmd!=comma ) {
14953   mp_get_x_next(mp);
14954   if ( mp->cur_cmd!=left_delimiter ) {
14955     print_err("Missing argument to ");
14956 @.Missing argument...@>
14957     mp_print_macro_name(mp, arg_list,macro_name);
14958     help3("That macro has more parameters than you thought.")
14959      ("I'll continue by pretending that each missing argument")
14960      ("is either zero or null.");
14961     if ( info(r)>=suffix_base ) {
14962       mp->cur_exp=null; mp->cur_type=mp_token_list;
14963     } else { 
14964       mp->cur_exp=0; mp->cur_type=mp_known;
14965     }
14966     mp_back_error(mp); mp->cur_cmd=right_delimiter; 
14967     goto FOUND;
14968   }
14969   l_delim=mp->cur_sym; r_delim=mp->cur_mod;
14970 }
14971 @<Scan the argument represented by |info(r)|@>;
14972 if ( mp->cur_cmd!=comma ) 
14973   @<Check that the proper right delimiter was present@>;
14974 FOUND:  
14975 @<Append the current expression to |arg_list|@>
14976
14977 @ @<Check that the proper right delim...@>=
14978 if ( (mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
14979   if ( info(link(r))>=expr_base ) {
14980     mp_missing_err(mp, ",");
14981 @.Missing `,'@>
14982     help3("I've finished reading a macro argument and am about to")
14983       ("read another; the arguments weren't delimited correctly.")
14984        ("You might want to delete some tokens before continuing.");
14985     mp_back_error(mp); mp->cur_cmd=comma;
14986   } else { 
14987     mp_missing_err(mp, str(text(r_delim)));
14988 @.Missing `)'@>
14989     help2("I've gotten to the end of the macro parameter list.")
14990        ("You might want to delete some tokens before continuing.");
14991     mp_back_error(mp);
14992   }
14993 }
14994
14995 @ A \&{suffix} or \&{text} parameter will be have been scanned as
14996 a token list pointed to by |cur_exp|, in which case we will have
14997 |cur_type=token_list|.
14998
14999 @<Append the current expression to |arg_list|@>=
15000
15001   p=mp_get_avail(mp);
15002   if ( mp->cur_type==mp_token_list ) info(p)=mp->cur_exp;
15003   else info(p)=mp_stash_cur_exp(mp);
15004   if ( mp->internal[mp_tracing_macros]>0 ) {
15005     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,info(r)); 
15006     mp_end_diagnostic(mp, false);
15007   }
15008   if ( arg_list==null ) arg_list=p;
15009   else link(tail)=p;
15010   tail=p; incr(n);
15011 }
15012
15013 @ @<Scan the argument represented by |info(r)|@>=
15014 if ( info(r)>=text_base ) {
15015   mp_scan_text_arg(mp, l_delim,r_delim);
15016 } else { 
15017   mp_get_x_next(mp);
15018   if ( info(r)>=suffix_base ) mp_scan_suffix(mp);
15019   else mp_scan_expression(mp);
15020 }
15021
15022 @ The parameters to |scan_text_arg| are either a pair of delimiters
15023 or zero; the latter case is for undelimited text arguments, which
15024 end with the first semicolon or \&{endgroup} or \&{end} that is not
15025 contained in a group.
15026
15027 @<Declare the procedure called |scan_text_arg|@>=
15028 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) ;
15029
15030 @ @c
15031 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) {
15032   integer balance; /* excess of |l_delim| over |r_delim| */
15033   pointer p; /* list tail */
15034   mp->warning_info=l_delim; mp->scanner_status=absorbing;
15035   p=hold_head; balance=1; link(hold_head)=null;
15036   while (1)  { 
15037     get_t_next;
15038     if ( l_delim==0 ) {
15039       @<Adjust the balance for an undelimited argument; |break| if done@>;
15040     } else {
15041           @<Adjust the balance for a delimited argument; |break| if done@>;
15042     }
15043     link(p)=mp_cur_tok(mp); p=link(p);
15044   }
15045   mp->cur_exp=link(hold_head); mp->cur_type=mp_token_list;
15046   mp->scanner_status=normal;
15047 };
15048
15049 @ @<Adjust the balance for a delimited argument...@>=
15050 if ( mp->cur_cmd==right_delimiter ) { 
15051   if ( mp->cur_mod==l_delim ) { 
15052     decr(balance);
15053     if ( balance==0 ) break;
15054   }
15055 } else if ( mp->cur_cmd==left_delimiter ) {
15056   if ( mp->cur_mod==r_delim ) incr(balance);
15057 }
15058
15059 @ @<Adjust the balance for an undelimited...@>=
15060 if ( end_of_statement ) { /* |cur_cmd=semicolon|, |end_group|, or |stop| */
15061   if ( balance==1 ) { break; }
15062   else  { if ( mp->cur_cmd==end_group ) decr(balance); }
15063 } else if ( mp->cur_cmd==begin_group ) { 
15064   incr(balance); 
15065 }
15066
15067 @ @<Scan undelimited argument(s)@>=
15068
15069   if ( info(r)<text_macro ) {
15070     mp_get_x_next(mp);
15071     if ( info(r)!=suffix_macro ) {
15072       if ( (mp->cur_cmd==equals)||(mp->cur_cmd==assignment) ) mp_get_x_next(mp);
15073     }
15074   }
15075   switch (info(r)) {
15076   case primary_macro:mp_scan_primary(mp); break;
15077   case secondary_macro:mp_scan_secondary(mp); break;
15078   case tertiary_macro:mp_scan_tertiary(mp); break;
15079   case expr_macro:mp_scan_expression(mp); break;
15080   case of_macro:
15081     @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>;
15082     break;
15083   case suffix_macro:
15084     @<Scan a suffix with optional delimiters@>;
15085     break;
15086   case text_macro:mp_scan_text_arg(mp, 0,0); break;
15087   } /* there are no other cases */
15088   mp_back_input(mp); 
15089   @<Append the current expression to |arg_list|@>;
15090 }
15091
15092 @ @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>=
15093
15094   mp_scan_expression(mp); p=mp_get_avail(mp); info(p)=mp_stash_cur_exp(mp);
15095   if ( mp->internal[mp_tracing_macros]>0 ) { 
15096     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,0); 
15097     mp_end_diagnostic(mp, false);
15098   }
15099   if ( arg_list==null ) arg_list=p; else link(tail)=p;
15100   tail=p;incr(n);
15101   if ( mp->cur_cmd!=of_token ) {
15102     mp_missing_err(mp, "of"); mp_print(mp, " for ");
15103 @.Missing `of'@>
15104     mp_print_macro_name(mp, arg_list,macro_name);
15105     help1("I've got the first argument; will look now for the other.");
15106     mp_back_error(mp);
15107   }
15108   mp_get_x_next(mp); mp_scan_primary(mp);
15109 }
15110
15111 @ @<Scan a suffix with optional delimiters@>=
15112
15113   if ( mp->cur_cmd!=left_delimiter ) {
15114     l_delim=null;
15115   } else { 
15116     l_delim=mp->cur_sym; r_delim=mp->cur_mod; mp_get_x_next(mp);
15117   };
15118   mp_scan_suffix(mp);
15119   if ( l_delim!=null ) {
15120     if ((mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
15121       mp_missing_err(mp, str(text(r_delim)));
15122 @.Missing `)'@>
15123       help2("I've gotten to the end of the macro parameter list.")
15124          ("You might want to delete some tokens before continuing.");
15125       mp_back_error(mp);
15126     }
15127     mp_get_x_next(mp);
15128   }
15129 }
15130
15131 @ Before we put a new token list on the input stack, it is wise to clean off
15132 all token lists that have recently been depleted. Then a user macro that ends
15133 with a call to itself will not require unbounded stack space.
15134
15135 @<Feed the arguments and replacement text to the scanner@>=
15136 while ( token_state &&(loc==null) ) mp_end_token_list(mp); /* conserve stack space */
15137 if ( mp->param_ptr+n>mp->max_param_stack ) {
15138   mp->max_param_stack=mp->param_ptr+n;
15139   if ( mp->max_param_stack>mp->param_size )
15140     mp_overflow(mp, "parameter stack size",mp->param_size);
15141 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15142 }
15143 mp_begin_token_list(mp, def_ref,macro); name=macro_name; loc=r;
15144 if ( n>0 ) {
15145   p=arg_list;
15146   do {  
15147    mp->param_stack[mp->param_ptr]=info(p); incr(mp->param_ptr); p=link(p);
15148   } while (p!=null);
15149   mp_flush_list(mp, arg_list);
15150 }
15151
15152 @ It's sometimes necessary to put a single argument onto |param_stack|.
15153 The |stack_argument| subroutine does this.
15154
15155 @c void mp_stack_argument (MP mp,pointer p) { 
15156   if ( mp->param_ptr==mp->max_param_stack ) {
15157     incr(mp->max_param_stack);
15158     if ( mp->max_param_stack>mp->param_size )
15159       mp_overflow(mp, "parameter stack size",mp->param_size);
15160 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15161   }
15162   mp->param_stack[mp->param_ptr]=p; incr(mp->param_ptr);
15163 }
15164
15165 @* \[33] Conditional processing.
15166 Let's consider now the way \&{if} commands are handled.
15167
15168 Conditions can be inside conditions, and this nesting has a stack
15169 that is independent of other stacks.
15170 Four global variables represent the top of the condition stack:
15171 |cond_ptr| points to pushed-down entries, if~any; |cur_if| tells whether
15172 we are processing \&{if} or \&{elseif}; |if_limit| specifies
15173 the largest code of a |fi_or_else| command that is syntactically legal;
15174 and |if_line| is the line number at which the current conditional began.
15175
15176 If no conditions are currently in progress, the condition stack has the
15177 special state |cond_ptr=null|, |if_limit=normal|, |cur_if=0|, |if_line=0|.
15178 Otherwise |cond_ptr| points to a two-word node; the |type|, |name_type|, and
15179 |link| fields of the first word contain |if_limit|, |cur_if|, and
15180 |cond_ptr| at the next level, and the second word contains the
15181 corresponding |if_line|.
15182
15183 @d if_node_size 2 /* number of words in stack entry for conditionals */
15184 @d if_line_field(A) mp->mem[(A)+1].cint
15185 @d if_code 1 /* code for \&{if} being evaluated */
15186 @d fi_code 2 /* code for \&{fi} */
15187 @d else_code 3 /* code for \&{else} */
15188 @d else_if_code 4 /* code for \&{elseif} */
15189
15190 @<Glob...@>=
15191 pointer cond_ptr; /* top of the condition stack */
15192 integer if_limit; /* upper bound on |fi_or_else| codes */
15193 small_number cur_if; /* type of conditional being worked on */
15194 integer if_line; /* line where that conditional began */
15195
15196 @ @<Set init...@>=
15197 mp->cond_ptr=null; mp->if_limit=normal; mp->cur_if=0; mp->if_line=0;
15198
15199 @ @<Put each...@>=
15200 mp_primitive(mp, "if",if_test,if_code);
15201 @:if_}{\&{if} primitive@>
15202 mp_primitive(mp, "fi",fi_or_else,fi_code); mp->eqtb[frozen_fi]=mp->eqtb[mp->cur_sym];
15203 @:fi_}{\&{fi} primitive@>
15204 mp_primitive(mp, "else",fi_or_else,else_code);
15205 @:else_}{\&{else} primitive@>
15206 mp_primitive(mp, "elseif",fi_or_else,else_if_code);
15207 @:else_if_}{\&{elseif} primitive@>
15208
15209 @ @<Cases of |print_cmd_mod|...@>=
15210 case if_test:
15211 case fi_or_else: 
15212   switch (m) {
15213   case if_code:mp_print(mp, "if"); break;
15214   case fi_code:mp_print(mp, "fi");  break;
15215   case else_code:mp_print(mp, "else"); break;
15216   default: mp_print(mp, "elseif"); break;
15217   }
15218   break;
15219
15220 @ Here is a procedure that ignores text until coming to an \&{elseif},
15221 \&{else}, or \&{fi} at level zero of $\&{if}\ldots\&{fi}$
15222 nesting. After it has acted, |cur_mod| will indicate the token that
15223 was found.
15224
15225 \MP's smallest two command codes are |if_test| and |fi_or_else|; this
15226 makes the skipping process a bit simpler.
15227
15228 @c 
15229 void mp_pass_text (MP mp) {
15230   integer l = 0;
15231   mp->scanner_status=skipping;
15232   mp->warning_info=mp_true_line(mp);
15233   while (1)  { 
15234     get_t_next;
15235     if ( mp->cur_cmd<=fi_or_else ) {
15236       if ( mp->cur_cmd<fi_or_else ) {
15237         incr(l);
15238       } else { 
15239         if ( l==0 ) break;
15240         if ( mp->cur_mod==fi_code ) decr(l);
15241       }
15242     } else {
15243       @<Decrease the string reference count,
15244        if the current token is a string@>;
15245     }
15246   }
15247   mp->scanner_status=normal;
15248 }
15249
15250 @ @<Decrease the string reference count...@>=
15251 if ( mp->cur_cmd==string_token ) { delete_str_ref(mp->cur_mod); }
15252
15253 @ When we begin to process a new \&{if}, we set |if_limit:=if_code|; then
15254 if \&{elseif} or \&{else} or \&{fi} occurs before the current \&{if}
15255 condition has been evaluated, a colon will be inserted.
15256 A construction like `\.{if fi}' would otherwise get \MP\ confused.
15257
15258 @<Push the condition stack@>=
15259 { p=mp_get_node(mp, if_node_size); link(p)=mp->cond_ptr; type(p)=mp->if_limit;
15260   name_type(p)=mp->cur_if; if_line_field(p)=mp->if_line;
15261   mp->cond_ptr=p; mp->if_limit=if_code; mp->if_line=mp_true_line(mp); 
15262   mp->cur_if=if_code;
15263 }
15264
15265 @ @<Pop the condition stack@>=
15266 { p=mp->cond_ptr; mp->if_line=if_line_field(p);
15267   mp->cur_if=name_type(p); mp->if_limit=type(p); mp->cond_ptr=link(p);
15268   mp_free_node(mp, p,if_node_size);
15269 }
15270
15271 @ Here's a procedure that changes the |if_limit| code corresponding to
15272 a given value of |cond_ptr|.
15273
15274 @c void mp_change_if_limit (MP mp,small_number l, pointer p) {
15275   pointer q;
15276   if ( p==mp->cond_ptr ) {
15277     mp->if_limit=l; /* that's the easy case */
15278   } else  { 
15279     q=mp->cond_ptr;
15280     while (1) { 
15281       if ( q==null ) mp_confusion(mp, "if");
15282 @:this can't happen if}{\quad if@>
15283       if ( link(q)==p ) { 
15284         type(q)=l; return;
15285       }
15286       q=link(q);
15287     }
15288   }
15289 }
15290
15291 @ The user is supposed to put colons into the proper parts of conditional
15292 statements. Therefore, \MP\ has to check for their presence.
15293
15294 @c 
15295 void mp_check_colon (MP mp) { 
15296   if ( mp->cur_cmd!=colon ) { 
15297     mp_missing_err(mp, ":");
15298 @.Missing `:'@>
15299     help2("There should've been a colon after the condition.")
15300          ("I shall pretend that one was there.");;
15301     mp_back_error(mp);
15302   }
15303 }
15304
15305 @ A condition is started when the |get_x_next| procedure encounters
15306 an |if_test| command; in that case |get_x_next| calls |conditional|,
15307 which is a recursive procedure.
15308 @^recursion@>
15309
15310 @c void mp_conditional (MP mp) {
15311   pointer save_cond_ptr; /* |cond_ptr| corresponding to this conditional */
15312   int new_if_limit; /* future value of |if_limit| */
15313   pointer p; /* temporary register */
15314   @<Push the condition stack@>; 
15315   save_cond_ptr=mp->cond_ptr;
15316 RESWITCH: 
15317   mp_get_boolean(mp); new_if_limit=else_if_code;
15318   if ( mp->internal[mp_tracing_commands]>unity ) {
15319     @<Display the boolean value of |cur_exp|@>;
15320   }
15321 FOUND: 
15322   mp_check_colon(mp);
15323   if ( mp->cur_exp==true_code ) {
15324     mp_change_if_limit(mp, new_if_limit,save_cond_ptr);
15325     return; /* wait for \&{elseif}, \&{else}, or \&{fi} */
15326   };
15327   @<Skip to \&{elseif} or \&{else} or \&{fi}, then |goto done|@>;
15328 DONE: 
15329   mp->cur_if=mp->cur_mod; mp->if_line=mp_true_line(mp);
15330   if ( mp->cur_mod==fi_code ) {
15331     @<Pop the condition stack@>
15332   } else if ( mp->cur_mod==else_if_code ) {
15333     goto RESWITCH;
15334   } else  { 
15335     mp->cur_exp=true_code; new_if_limit=fi_code; mp_get_x_next(mp); 
15336     goto FOUND;
15337   }
15338 }
15339
15340 @ In a construction like `\&{if} \&{if} \&{true}: $0=1$: \\{foo}
15341 \&{else}: \\{bar} \&{fi}', the first \&{else}
15342 that we come to after learning that the \&{if} is false is not the
15343 \&{else} we're looking for. Hence the following curious logic is needed.
15344
15345 @<Skip to \&{elseif}...@>=
15346 while (1) { 
15347   mp_pass_text(mp);
15348   if ( mp->cond_ptr==save_cond_ptr ) goto DONE;
15349   else if ( mp->cur_mod==fi_code ) @<Pop the condition stack@>;
15350 }
15351
15352
15353 @ @<Display the boolean value...@>=
15354 { mp_begin_diagnostic(mp);
15355   if ( mp->cur_exp==true_code ) mp_print(mp, "{true}");
15356   else mp_print(mp, "{false}");
15357   mp_end_diagnostic(mp, false);
15358 }
15359
15360 @ The processing of conditionals is complete except for the following
15361 code, which is actually part of |get_x_next|. It comes into play when
15362 \&{elseif}, \&{else}, or \&{fi} is scanned.
15363
15364 @<Terminate the current conditional and skip to \&{fi}@>=
15365 if ( mp->cur_mod>mp->if_limit ) {
15366   if ( mp->if_limit==if_code ) { /* condition not yet evaluated */
15367     mp_missing_err(mp, ":");
15368 @.Missing `:'@>
15369     mp_back_input(mp); mp->cur_sym=frozen_colon; mp_ins_error(mp);
15370   } else  { 
15371     print_err("Extra "); mp_print_cmd_mod(mp, fi_or_else,mp->cur_mod);
15372 @.Extra else@>
15373 @.Extra elseif@>
15374 @.Extra fi@>
15375     help1("I'm ignoring this; it doesn't match any if.");
15376     mp_error(mp);
15377   }
15378 } else  { 
15379   while ( mp->cur_mod!=fi_code ) mp_pass_text(mp); /* skip to \&{fi} */
15380   @<Pop the condition stack@>;
15381 }
15382
15383 @* \[34] Iterations.
15384 To bring our treatment of |get_x_next| to a close, we need to consider what
15385 \MP\ does when it sees \&{for}, \&{forsuffixes}, and \&{forever}.
15386
15387 There's a global variable |loop_ptr| that keeps track of the \&{for} loops
15388 that are currently active. If |loop_ptr=null|, no loops are in progress;
15389 otherwise |info(loop_ptr)| points to the iterative text of the current
15390 (innermost) loop, and |link(loop_ptr)| points to the data for any other
15391 loops that enclose the current one.
15392
15393 A loop-control node also has two other fields, called |loop_type| and
15394 |loop_list|, whose contents depend on the type of loop:
15395
15396 \yskip\indent|loop_type(loop_ptr)=null| means that |loop_list(loop_ptr)|
15397 points to a list of one-word nodes whose |info| fields point to the
15398 remaining argument values of a suffix list and expression list.
15399
15400 \yskip\indent|loop_type(loop_ptr)=mp_void| means that the current loop is
15401 `\&{forever}'.
15402
15403 \yskip\indent|loop_type(loop_ptr)=progression_flag| means that
15404 |p=loop_list(loop_ptr)| points to a ``progression node'' and |value(p)|,
15405 |step_size(p)|, and |final_value(p)| contain the data for an arithmetic
15406 progression.
15407
15408 \yskip\indent|loop_type(loop_ptr)=p>mp_void| means that |p| points to an edge
15409 header and |loop_list(loop_ptr)| points into the graphical object list for
15410 that edge header.
15411
15412 \yskip\noindent In the case of a progression node, the first word is not used
15413 because the link field of words in the dynamic memory area cannot be arbitrary.
15414
15415 @d loop_list_loc(A) ((A)+1) /* where the |loop_list| field resides */
15416 @d loop_type(A) info(loop_list_loc((A))) /* the type of \&{for} loop */
15417 @d loop_list(A) link(loop_list_loc((A))) /* the remaining list elements */
15418 @d loop_node_size 2 /* the number of words in a loop control node */
15419 @d progression_node_size 4 /* the number of words in a progression node */
15420 @d step_size(A) mp->mem[(A)+2].sc /* the step size in an arithmetic progression */
15421 @d final_value(A) mp->mem[(A)+3].sc /* the final value in an arithmetic progression */
15422 @d progression_flag (null+2)
15423   /* |loop_type| value when |loop_list| points to a progression node */
15424
15425 @<Glob...@>=
15426 pointer loop_ptr; /* top of the loop-control-node stack */
15427
15428 @ @<Set init...@>=
15429 mp->loop_ptr=null;
15430
15431 @ If the expressions that define an arithmetic progression in
15432 a \&{for} loop don't have known numeric values, the |bad_for|
15433 subroutine screams at the user.
15434
15435 @c void mp_bad_for (MP mp, char * s) {
15436   mp_disp_err(mp, null,"Improper "); /* show the bad expression above the message */
15437 @.Improper...replaced by 0@>
15438   mp_print(mp, s); mp_print(mp, " has been replaced by 0");
15439   help4("When you say `for x=a step b until c',")
15440     ("the initial value `a' and the step size `b'")
15441     ("and the final value `c' must have known numeric values.")
15442     ("I'm zeroing this one. Proceed, with fingers crossed.");
15443   mp_put_get_flush_error(mp, 0);
15444 };
15445
15446 @ Here's what \MP\ does when \&{for}, \&{forsuffixes}, or \&{forever}
15447 has just been scanned. (This code requires slight familiarity with
15448 expression-parsing routines that we have not yet discussed; but it seems
15449 to belong in the present part of the program, even though the original author
15450 didn't write it until later. The reader may wish to come back to it.)
15451
15452 @c void mp_begin_iteration (MP mp) {
15453   halfword m; /* |expr_base| (\&{for}) or |suffix_base| (\&{forsuffixes}) */
15454   halfword n; /* hash address of the current symbol */
15455   pointer s; /* the new loop-control node */
15456   pointer p; /* substitution list for |scan_toks| */
15457   pointer q;  /* link manipulation register */
15458   pointer pp; /* a new progression node */
15459   m=mp->cur_mod; n=mp->cur_sym; s=mp_get_node(mp, loop_node_size);
15460   if ( m==start_forever ){ 
15461     loop_type(s)=mp_void; p=null; mp_get_x_next(mp);
15462   } else { 
15463     mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
15464     info(p)=mp->cur_sym; value(p)=m;
15465     mp_get_x_next(mp);
15466     if ( mp->cur_cmd==within_token ) {
15467       @<Set up a picture iteration@>;
15468     } else { 
15469       @<Check for the |"="| or |":="| in a loop header@>;
15470       @<Scan the values to be used in the loop@>;
15471     }
15472   }
15473   @<Check for the presence of a colon@>;
15474   @<Scan the loop text and put it on the loop control stack@>;
15475   mp_resume_iteration(mp);
15476 }
15477
15478 @ @<Check for the |"="| or |":="| in a loop header@>=
15479 if ( (mp->cur_cmd!=equals)&&(mp->cur_cmd!=assignment) ) { 
15480   mp_missing_err(mp, "=");
15481 @.Missing `='@>
15482   help3("The next thing in this loop should have been `=' or `:='.")
15483     ("But don't worry; I'll pretend that an equals sign")
15484     ("was present, and I'll look for the values next.");
15485   mp_back_error(mp);
15486 }
15487
15488 @ @<Check for the presence of a colon@>=
15489 if ( mp->cur_cmd!=colon ) { 
15490   mp_missing_err(mp, ":");
15491 @.Missing `:'@>
15492   help3("The next thing in this loop should have been a `:'.")
15493     ("So I'll pretend that a colon was present;")
15494     ("everything from here to `endfor' will be iterated.");
15495   mp_back_error(mp);
15496 }
15497
15498 @ We append a special |frozen_repeat_loop| token in place of the
15499 `\&{endfor}' at the end of the loop. This will come through \MP's scanner
15500 at the proper time to cause the loop to be repeated.
15501
15502 (If the user tries some shenanigan like `\&{for} $\ldots$ \&{let} \&{endfor}',
15503 he will be foiled by the |get_symbol| routine, which keeps frozen
15504 tokens unchanged. Furthermore the |frozen_repeat_loop| is an \&{outer}
15505 token, so it won't be lost accidentally.)
15506
15507 @ @<Scan the loop text...@>=
15508 q=mp_get_avail(mp); info(q)=frozen_repeat_loop;
15509 mp->scanner_status=loop_defining; mp->warning_info=n;
15510 info(s)=mp_scan_toks(mp, iteration,p,q,0); mp->scanner_status=normal;
15511 link(s)=mp->loop_ptr; mp->loop_ptr=s
15512
15513 @ @<Initialize table...@>=
15514 eq_type(frozen_repeat_loop)=repeat_loop+outer_tag;
15515 text(frozen_repeat_loop)=intern(" ENDFOR");
15516
15517 @ The loop text is inserted into \MP's scanning apparatus by the
15518 |resume_iteration| routine.
15519
15520 @c void mp_resume_iteration (MP mp) {
15521   pointer p,q; /* link registers */
15522   p=loop_type(mp->loop_ptr);
15523   if ( p==progression_flag ) { 
15524     p=loop_list(mp->loop_ptr); /* now |p| points to a progression node */
15525     mp->cur_exp=value(p);
15526     if ( @<The arithmetic progression has ended@> ) {
15527       mp_stop_iteration(mp);
15528       return;
15529     }
15530     mp->cur_type=mp_known; q=mp_stash_cur_exp(mp); /* make |q| an \&{expr} argument */
15531     value(p)=mp->cur_exp+step_size(p); /* set |value(p)| for the next iteration */
15532   } else if ( p==null ) { 
15533     p=loop_list(mp->loop_ptr);
15534     if ( p==null ) {
15535       mp_stop_iteration(mp);
15536       return;
15537     }
15538     loop_list(mp->loop_ptr)=link(p); q=info(p); free_avail(p);
15539   } else if ( p==mp_void ) { 
15540     mp_begin_token_list(mp, info(mp->loop_ptr),forever_text); return;
15541   } else {
15542     @<Make |q| a capsule containing the next picture component from
15543       |loop_list(loop_ptr)| or |goto not_found|@>;
15544   }
15545   mp_begin_token_list(mp, info(mp->loop_ptr),loop_text);
15546   mp_stack_argument(mp, q);
15547   if ( mp->internal[mp_tracing_commands]>unity ) {
15548      @<Trace the start of a loop@>;
15549   }
15550   return;
15551 NOT_FOUND:
15552   mp_stop_iteration(mp);
15553 }
15554
15555 @ @<The arithmetic progression has ended@>=
15556 ((step_size(p)>0)&&(mp->cur_exp>final_value(p)))||
15557  ((step_size(p)<0)&&(mp->cur_exp<final_value(p)))
15558
15559 @ @<Trace the start of a loop@>=
15560
15561   mp_begin_diagnostic(mp); mp_print_nl(mp, "{loop value=");
15562 @.loop value=n@>
15563   if ( (q!=null)&&(link(q)==mp_void) ) mp_print_exp(mp, q,1);
15564   else mp_show_token_list(mp, q,null,50,0);
15565   mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
15566 }
15567
15568 @ @<Make |q| a capsule containing the next picture component from...@>=
15569 { q=loop_list(mp->loop_ptr);
15570   if ( q==null ) goto NOT_FOUND;
15571   skip_component(q) goto NOT_FOUND;
15572   mp->cur_exp=mp_copy_objects(mp, loop_list(mp->loop_ptr),q);
15573   mp_init_bbox(mp, mp->cur_exp);
15574   mp->cur_type=mp_picture_type;
15575   loop_list(mp->loop_ptr)=q;
15576   q=mp_stash_cur_exp(mp);
15577 }
15578
15579 @ A level of loop control disappears when |resume_iteration| has decided
15580 not to resume, or when an \&{exitif} construction has removed the loop text
15581 from the input stack.
15582
15583 @c void mp_stop_iteration (MP mp) {
15584   pointer p,q; /* the usual */
15585   p=loop_type(mp->loop_ptr);
15586   if ( p==progression_flag )  {
15587     mp_free_node(mp, loop_list(mp->loop_ptr),progression_node_size);
15588   } else if ( p==null ){ 
15589     q=loop_list(mp->loop_ptr);
15590     while ( q!=null ) {
15591       p=info(q);
15592       if ( p!=null ) {
15593         if ( link(p)==mp_void ) { /* it's an \&{expr} parameter */
15594           mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
15595         } else {
15596           mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
15597         }
15598       }
15599       p=q; q=link(q); free_avail(p);
15600     }
15601   } else if ( p>progression_flag ) {
15602     delete_edge_ref(p);
15603   }
15604   p=mp->loop_ptr; mp->loop_ptr=link(p); mp_flush_token_list(mp, info(p));
15605   mp_free_node(mp, p,loop_node_size);
15606 }
15607
15608 @ Now that we know all about loop control, we can finish up
15609 the missing portion of |begin_iteration| and we'll be done.
15610
15611 The following code is performed after the `\.=' has been scanned in
15612 a \&{for} construction (if |m=expr_base|) or a \&{forsuffixes} construction
15613 (if |m=suffix_base|).
15614
15615 @<Scan the values to be used in the loop@>=
15616 loop_type(s)=null; q=loop_list_loc(s); link(q)=null; /* |link(q)=loop_list(s)| */
15617 do {  
15618   mp_get_x_next(mp);
15619   if ( m!=expr_base ) {
15620     mp_scan_suffix(mp);
15621   } else { 
15622     if ( mp->cur_cmd>=colon ) if ( mp->cur_cmd<=comma ) 
15623           goto CONTINUE;
15624     mp_scan_expression(mp);
15625     if ( mp->cur_cmd==step_token ) if ( q==loop_list_loc(s) ) {
15626       @<Prepare for step-until construction and |break|@>;
15627     }
15628     mp->cur_exp=mp_stash_cur_exp(mp);
15629   }
15630   link(q)=mp_get_avail(mp); q=link(q); 
15631   info(q)=mp->cur_exp; mp->cur_type=mp_vacuous;
15632 CONTINUE:
15633   ;
15634 } while (mp->cur_cmd==comma)
15635
15636 @ @<Prepare for step-until construction and |break|@>=
15637
15638   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "initial value");
15639   pp=mp_get_node(mp, progression_node_size); value(pp)=mp->cur_exp;
15640   mp_get_x_next(mp); mp_scan_expression(mp);
15641   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "step size");
15642   step_size(pp)=mp->cur_exp;
15643   if ( mp->cur_cmd!=until_token ) { 
15644     mp_missing_err(mp, "until");
15645 @.Missing `until'@>
15646     help2("I assume you meant to say `until' after `step'.")
15647       ("So I'll look for the final value and colon next.");
15648     mp_back_error(mp);
15649   }
15650   mp_get_x_next(mp); mp_scan_expression(mp);
15651   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "final value");
15652   final_value(pp)=mp->cur_exp; loop_list(s)=pp;
15653   loop_type(s)=progression_flag; 
15654   break;
15655 }
15656
15657 @ The last case is when we have just seen ``\&{within}'', and we need to
15658 parse a picture expression and prepare to iterate over it.
15659
15660 @<Set up a picture iteration@>=
15661 { mp_get_x_next(mp);
15662   mp_scan_expression(mp);
15663   @<Make sure the current expression is a known picture@>;
15664   loop_type(s)=mp->cur_exp; mp->cur_type=mp_vacuous;
15665   q=link(dummy_loc(mp->cur_exp));
15666   if ( q!= null ) 
15667     if ( is_start_or_stop(q) )
15668       if ( mp_skip_1component(mp, q)==null ) q=link(q);
15669   loop_list(s)=q;
15670 }
15671
15672 @ @<Make sure the current expression is a known picture@>=
15673 if ( mp->cur_type!=mp_picture_type ) {
15674   mp_disp_err(mp, null,"Improper iteration spec has been replaced by nullpicture");
15675   help1("When you say `for x in p', p must be a known picture.");
15676   mp_put_get_flush_error(mp, mp_get_node(mp, edge_header_size));
15677   mp_init_edges(mp, mp->cur_exp); mp->cur_type=mp_picture_type;
15678 }
15679
15680 @* \[35] File names.
15681 It's time now to fret about file names.  Besides the fact that different
15682 operating systems treat files in different ways, we must cope with the
15683 fact that completely different naming conventions are used by different
15684 groups of people. The following programs show what is required for one
15685 particular operating system; similar routines for other systems are not
15686 difficult to devise.
15687 @^system dependencies@>
15688
15689 \MP\ assumes that a file name has three parts: the name proper; its
15690 ``extension''; and a ``file area'' where it is found in an external file
15691 system.  The extension of an input file is assumed to be
15692 `\.{.mp}' unless otherwise specified; it is `\.{.log}' on the
15693 transcript file that records each run of \MP; it is `\.{.tfm}' on the font
15694 metric files that describe characters in any fonts created by \MP; it is
15695 `\.{.ps}' or `.{\it nnn}' for some number {\it nnn} on the \ps\ output files;
15696 and it is `\.{.mem}' on the mem files written by \.{INIMP} to initialize \MP.
15697 The file area can be arbitrary on input files, but files are usually
15698 output to the user's current area.  If an input file cannot be
15699 found on the specified area, \MP\ will look for it on a special system
15700 area; this special area is intended for commonly used input files.
15701
15702 Simple uses of \MP\ refer only to file names that have no explicit
15703 extension or area. For example, a person usually says `\.{input} \.{cmr10}'
15704 instead of `\.{input} \.{cmr10.new}'. Simple file
15705 names are best, because they make the \MP\ source files portable;
15706 whenever a file name consists entirely of letters and digits, it should be
15707 treated in the same way by all implementations of \MP. However, users
15708 need the ability to refer to other files in their environment, especially
15709 when responding to error messages concerning unopenable files; therefore
15710 we want to let them use the syntax that appears in their favorite
15711 operating system.
15712
15713 @ \MP\ uses the same conventions that have proved to be satisfactory for
15714 \TeX\ and \MF. In order to isolate the system-dependent aspects of file names,
15715 @^system dependencies@>
15716 the system-independent parts of \MP\ are expressed in terms
15717 of three system-dependent
15718 procedures called |begin_name|, |more_name|, and |end_name|. In
15719 essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
15720 the system-independent driver program does the operations
15721 $$|begin_name|;\,|more_name|(c_1);\,\ldots\,;|more_name|(c_n);
15722 \,|end_name|.$$
15723 These three procedures communicate with each other via global variables.
15724 Afterwards the file name will appear in the string pool as three strings
15725 called |cur_name|\penalty10000\hskip-.05em,
15726 |cur_area|, and |cur_ext|; the latter two are null (i.e.,
15727 |""|), unless they were explicitly specified by the user.
15728
15729 Actually the situation is slightly more complicated, because \MP\ needs
15730 to know when the file name ends. The |more_name| routine is a function
15731 (with side effects) that returns |true| on the calls |more_name|$(c_1)$,
15732 \dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
15733 returns |false|; or, it returns |true| and $c_n$ is the last character
15734 on the current input line. In other words,
15735 |more_name| is supposed to return |true| unless it is sure that the
15736 file name has been completely scanned; and |end_name| is supposed to be able
15737 to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
15738 whether $|more_name|(c_n)$ returned |true| or |false|.
15739
15740 @<Glob...@>=
15741 char * cur_name; /* name of file just scanned */
15742 char * cur_area; /* file area just scanned, or \.{""} */
15743 char * cur_ext; /* file extension just scanned, or \.{""} */
15744
15745 @ It is easier to maintain reference counts if we assign initial values.
15746
15747 @<Set init...@>=
15748 mp->cur_name=xstrdup(""); 
15749 mp->cur_area=xstrdup(""); 
15750 mp->cur_ext=xstrdup("");
15751
15752 @ @<Dealloc variables@>=
15753 xfree(mp->cur_area);
15754 xfree(mp->cur_name);
15755 xfree(mp->cur_ext);
15756
15757 @ The file names we shall deal with for illustrative purposes have the
15758 following structure:  If the name contains `\.>' or `\.:', the file area
15759 consists of all characters up to and including the final such character;
15760 otherwise the file area is null.  If the remaining file name contains
15761 `\..', the file extension consists of all such characters from the first
15762 remaining `\..' to the end, otherwise the file extension is null.
15763 @^system dependencies@>
15764
15765 We can scan such file names easily by using two global variables that keep track
15766 of the occurrences of area and extension delimiters.  Note that these variables
15767 cannot be of type |pool_pointer| because a string pool compaction could occur
15768 while scanning a file name.
15769
15770 @<Glob...@>=
15771 integer area_delimiter;
15772   /* most recent `\.>' or `\.:' relative to |str_start[str_ptr]| */
15773 integer ext_delimiter; /* the relevant `\..', if any */
15774
15775 @ Input files that can't be found in the user's area may appear in standard
15776 system areas called |MP_area| and |MF_area|.  (The latter is used when the file
15777 extension is |".mf"|.)  The standard system area for font metric files
15778 to be read is |MP_font_area|.
15779 This system area name will, of course, vary from place to place.
15780 @^system dependencies@>
15781
15782 @d MP_area "MPinputs:"
15783 @.MPinputs@>
15784 @d MF_area "MFinputs:"
15785 @.MFinputs@>
15786 @d MP_font_area ""
15787 @.TeXfonts@>
15788
15789 @ Here now is the first of the system-dependent routines for file name scanning.
15790 @^system dependencies@>
15791
15792 @<Declare subroutines for parsing file names@>=
15793 void mp_begin_name (MP mp) { 
15794   xfree(mp->cur_name); 
15795   xfree(mp->cur_area); 
15796   xfree(mp->cur_ext);
15797   mp->area_delimiter=-1; 
15798   mp->ext_delimiter=-1;
15799 }
15800
15801 @ And here's the second.
15802 @^system dependencies@>
15803
15804 @<Declare subroutines for parsing file names@>=
15805 boolean mp_more_name (MP mp, ASCII_code c) { 
15806   if (c==' ') {
15807     return false;
15808   } else { 
15809     if ( (c=='>')||(c==':') ) { 
15810       mp->area_delimiter=mp->pool_ptr; 
15811       mp->ext_delimiter=-1;
15812     } else if ( (c=='.')&&(mp->ext_delimiter<0) ) {
15813       mp->ext_delimiter=mp->pool_ptr;
15814     }
15815     str_room(1); append_char(c); /* contribute |c| to the current string */
15816     return true;
15817   }
15818 }
15819
15820 @ The third.
15821 @^system dependencies@>
15822
15823 @d copy_pool_segment(A,B,C) { 
15824       A = xmalloc(C+1,sizeof(char)); 
15825       strncpy(A,(char *)(mp->str_pool+B),C);  
15826       A[C] = 0;}
15827
15828 @<Declare subroutines for parsing file names@>=
15829 void mp_end_name (MP mp) {
15830   pool_pointer s; /* length of area, name, and extension */
15831   unsigned int len;
15832   /* "my/w.mp" */
15833   s = mp->str_start[mp->str_ptr];
15834   if ( mp->area_delimiter<0 ) {    
15835     mp->cur_area=xstrdup("");
15836   } else {
15837     len = mp->area_delimiter-s; 
15838     copy_pool_segment(mp->cur_area,s,len);
15839     s += len+1;
15840   }
15841   if ( mp->ext_delimiter<0 ) {
15842     mp->cur_ext=xstrdup("");
15843     len = mp->pool_ptr-s; 
15844   } else {
15845     copy_pool_segment(mp->cur_ext,mp->ext_delimiter,(mp->pool_ptr-mp->ext_delimiter));
15846     len = mp->ext_delimiter-s;
15847   }
15848   copy_pool_segment(mp->cur_name,s,len);
15849   mp->pool_ptr=s; /* don't need this partial string */
15850 }
15851
15852 @ Conversely, here is a routine that takes three strings and prints a file
15853 name that might have produced them. (The routine is system dependent, because
15854 some operating systems put the file area last instead of first.)
15855 @^system dependencies@>
15856
15857 @<Basic printing...@>=
15858 void mp_print_file_name (MP mp, char * n, char * a, char * e) { 
15859   mp_print(mp, a); mp_print(mp, n); mp_print(mp, e);
15860 };
15861
15862 @ Another system-dependent routine is needed to convert three internal
15863 \MP\ strings
15864 to the |name_of_file| value that is used to open files. The present code
15865 allows both lowercase and uppercase letters in the file name.
15866 @^system dependencies@>
15867
15868 @d append_to_name(A) { c=(A); 
15869   if ( k<file_name_size ) {
15870     mp->name_of_file[k]=xchr(c);
15871     incr(k);
15872   }
15873 }
15874
15875 @<Declare subroutines for parsing file names@>=
15876 void mp_pack_file_name (MP mp, char *n, char *a, char *e) {
15877   integer k; /* number of positions filled in |name_of_file| */
15878   ASCII_code c; /* character being packed */
15879   char *j; /* a character  index */
15880   k=0;
15881   assert(n);
15882   if (a!=NULL) {
15883     for (j=a;*j;j++) { append_to_name(*j); }
15884   }
15885   for (j=n;*j;j++) { append_to_name(*j); }
15886   if (e!=NULL) {
15887     for (j=e;*j;j++) { append_to_name(*j); }
15888   }
15889   mp->name_of_file[k]=0;
15890   mp->name_length=k; 
15891 }
15892
15893 @ @<Internal library declarations@>=
15894 void mp_pack_file_name (MP mp, char *n, char *a, char *e) ;
15895
15896 @ A messier routine is also needed, since mem file names must be scanned
15897 before \MP's string mechanism has been initialized. We shall use the
15898 global variable |MP_mem_default| to supply the text for default system areas
15899 and extensions related to mem files.
15900 @^system dependencies@>
15901
15902 @d mem_default_length 9 /* length of the |MP_mem_default| string */
15903 @d mem_ext_length 4 /* length of its `\.{.mem}' part */
15904 @d mem_extension ".mem" /* the extension, as a \.{WEB} constant */
15905
15906 @<Glob...@>=
15907 char *MP_mem_default;
15908 char *mem_name; /* for commandline */
15909
15910 @ @<Option variables@>=
15911 char *mem_name; /* for commandline */
15912
15913 @ @<Allocate or initialize ...@>=
15914 mp->MP_mem_default = xstrdup("plain.mem");
15915 mp->mem_name = xstrdup(opt->mem_name);
15916 @.plain@>
15917 @^system dependencies@>
15918
15919 @ @<Dealloc variables@>=
15920 xfree(mp->MP_mem_default);
15921 xfree(mp->mem_name);
15922
15923 @ @<Check the ``constant'' values for consistency@>=
15924 if ( mem_default_length>file_name_size ) mp->bad=20;
15925
15926 @ Here is the messy routine that was just mentioned. It sets |name_of_file|
15927 from the first |n| characters of |MP_mem_default|, followed by
15928 |buffer[a..b-1]|, followed by the last |mem_ext_length| characters of
15929 |MP_mem_default|.
15930
15931 We dare not give error messages here, since \MP\ calls this routine before
15932 the |error| routine is ready to roll. Instead, we simply drop excess characters,
15933 since the error will be detected in another way when a strange file name
15934 isn't found.
15935 @^system dependencies@>
15936
15937 @c void mp_pack_buffered_name (MP mp,small_number n, integer a,
15938                                integer b) {
15939   integer k; /* number of positions filled in |name_of_file| */
15940   ASCII_code c; /* character being packed */
15941   integer j; /* index into |buffer| or |MP_mem_default| */
15942   if ( n+b-a+1+mem_ext_length>file_name_size )
15943     b=a+file_name_size-n-1-mem_ext_length;
15944   k=0;
15945   for (j=0;j<n;j++) {
15946     append_to_name(xord((int)mp->MP_mem_default[j]));
15947   }
15948   for (j=a;j<b;j++) {
15949     append_to_name(mp->buffer[j]);
15950   }
15951   for (j=mem_default_length-mem_ext_length;
15952       j<mem_default_length;j++) {
15953     append_to_name(xord((int)mp->MP_mem_default[j]));
15954   } 
15955   mp->name_of_file[k]=0;
15956   mp->name_length=k; 
15957 }
15958
15959 @ Here is the only place we use |pack_buffered_name|. This part of the program
15960 becomes active when a ``virgin'' \MP\ is trying to get going, just after
15961 the preliminary initialization, or when the user is substituting another
15962 mem file by typing `\.\&' after the initial `\.{**}' prompt.  The buffer
15963 contains the first line of input in |buffer[loc..(last-1)]|, where
15964 |loc<last| and |buffer[loc]<>" "|.
15965
15966 @<Declarations@>=
15967 boolean mp_open_mem_file (MP mp) ;
15968
15969 @ @c
15970 boolean mp_open_mem_file (MP mp) {
15971   int j; /* the first space after the file name */
15972   if (mp->mem_name!=NULL) {
15973     mp->mem_file = mp_open_file(mp, mp->mem_name, "rb", mp_filetype_memfile);
15974     if ( mp->mem_file ) return true;
15975   }
15976   j=loc;
15977   if ( mp->buffer[loc]=='&' ) {
15978     incr(loc); j=loc; mp->buffer[mp->last]=' ';
15979     while ( mp->buffer[j]!=' ' ) incr(j);
15980     mp_pack_buffered_name(mp, 0,loc,j); /* try first without the system file area */
15981     if ( mp_w_open_in(mp, &mp->mem_file) ) goto FOUND;
15982     wake_up_terminal;
15983     wterm_ln("Sorry, I can\'t find that mem file; will try PLAIN.");
15984 @.Sorry, I can't find...@>
15985     update_terminal;
15986   }
15987   /* now pull out all the stops: try for the system \.{plain} file */
15988   mp_pack_buffered_name(mp, mem_default_length-mem_ext_length,0,0);
15989   if ( ! mp_w_open_in(mp, &mp->mem_file) ) {
15990     wake_up_terminal;
15991     wterm_ln("I can\'t find the PLAIN mem file!\n");
15992 @.I can't find PLAIN...@>
15993 @.plain@>
15994     return false;
15995   }
15996 FOUND:
15997   loc=j; return true;
15998 }
15999
16000 @ Operating systems often make it possible to determine the exact name (and
16001 possible version number) of a file that has been opened. The following routine,
16002 which simply makes a \MP\ string from the value of |name_of_file|, should
16003 ideally be changed to deduce the full name of file~|f|, which is the file
16004 most recently opened, if it is possible to do this in a \PASCAL\ program.
16005 @^system dependencies@>
16006
16007 @<Declarations@>=
16008 #define mp_a_make_name_string(A,B)  mp_make_name_string(A)
16009 #define mp_b_make_name_string(A,B)  mp_make_name_string(A)
16010 #define mp_w_make_name_string(A,B)  mp_make_name_string(A)
16011
16012 @ @c 
16013 str_number mp_make_name_string (MP mp) {
16014   int k; /* index into |name_of_file| */
16015   str_room(mp->name_length);
16016   for (k=0;k<mp->name_length;k++) {
16017     append_char(xord((int)mp->name_of_file[k]));
16018   }
16019   return mp_make_string(mp);
16020 }
16021
16022 @ Now let's consider the ``driver''
16023 routines by which \MP\ deals with file names
16024 in a system-independent manner.  First comes a procedure that looks for a
16025 file name in the input by taking the information from the input buffer.
16026 (We can't use |get_next|, because the conversion to tokens would
16027 destroy necessary information.)
16028
16029 This procedure doesn't allow semicolons or percent signs to be part of
16030 file names, because of other conventions of \MP.
16031 {\sl The {\logos METAFONT\/}book} doesn't
16032 use semicolons or percents immediately after file names, but some users
16033 no doubt will find it natural to do so; therefore system-dependent
16034 changes to allow such characters in file names should probably
16035 be made with reluctance, and only when an entire file name that
16036 includes special characters is ``quoted'' somehow.
16037 @^system dependencies@>
16038
16039 @c void mp_scan_file_name (MP mp) { 
16040   mp_begin_name(mp);
16041   while ( mp->buffer[loc]==' ' ) incr(loc);
16042   while (1) { 
16043     if ( (mp->buffer[loc]==';')||(mp->buffer[loc]=='%') ) break;
16044     if ( ! mp_more_name(mp, mp->buffer[loc]) ) break;
16045     incr(loc);
16046   }
16047   mp_end_name(mp);
16048 }
16049
16050 @ Here is another version that takes its input from a string.
16051
16052 @<Declare subroutines for parsing file names@>=
16053 void mp_str_scan_file (MP mp,  str_number s) {
16054   pool_pointer p,q; /* current position and stopping point */
16055   mp_begin_name(mp);
16056   p=mp->str_start[s]; q=str_stop(s);
16057   while ( p<q ){ 
16058     if ( ! mp_more_name(mp, mp->str_pool[p]) ) break;
16059     incr(p);
16060   }
16061   mp_end_name(mp);
16062 }
16063
16064 @ And one that reads from a |char*|.
16065
16066 @<Declare subroutines for parsing file names@>=
16067 void mp_ptr_scan_file (MP mp,  char *s) {
16068   char *p, *q; /* current position and stopping point */
16069   mp_begin_name(mp);
16070   p=s; q=p+strlen(s);
16071   while ( p<q ){ 
16072     if ( ! mp_more_name(mp, *p)) break;
16073     p++;
16074   }
16075   mp_end_name(mp);
16076 }
16077
16078
16079 @ The global variable |job_name| contains the file name that was first
16080 \&{input} by the user. This name is extended by `\.{.log}' and `\.{ps}' and
16081 `\.{.mem}' and `\.{.tfm}' in order to make the names of \MP's output files.
16082
16083 @<Glob...@>=
16084 char *job_name; /* principal file name */
16085 boolean log_opened; /* has the transcript file been opened? */
16086 char *log_name; /* full name of the log file */
16087
16088 @ @<Option variables@>=
16089 char *job_name; /* principal file name */
16090
16091 @ Initially |job_name=NULL|; it becomes nonzero as soon as the true name is known.
16092 We have |job_name=NULL| if and only if the `\.{log}' file has not been opened,
16093 except of course for a short time just after |job_name| has become nonzero.
16094
16095 @<Allocate or ...@>=
16096 mp->job_name=opt->job_name; 
16097 mp->log_opened=false;
16098
16099 @ @<Dealloc variables@>=
16100 xfree(mp->job_name);
16101
16102 @ Here is a routine that manufactures the output file names, assuming that
16103 |job_name<>0|. It ignores and changes the current settings of |cur_area|
16104 and |cur_ext|.
16105
16106 @d pack_cur_name mp_pack_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext)
16107
16108 @<Declarations@>=
16109 void mp_pack_job_name (MP mp, char *s) ;
16110
16111 @ @c void mp_pack_job_name (MP mp, char  *s) { /* |s = ".log"|, |".mem"|, |".ps"|, or .\\{nnn} */
16112   xfree(mp->cur_name); mp->cur_name=xstrdup(mp->job_name);
16113   xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
16114   xfree(mp->cur_ext);  mp->cur_ext=xstrdup(s);
16115   pack_cur_name;
16116 }
16117
16118 @ If some trouble arises when \MP\ tries to open a file, the following
16119 routine calls upon the user to supply another file name. Parameter~|s|
16120 is used in the error message to identify the type of file; parameter~|e|
16121 is the default extension if none is given. Upon exit from the routine,
16122 variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
16123 ready for another attempt at file opening.
16124
16125 @<Declarations@>=
16126 void mp_prompt_file_name (MP mp,char * s, char * e) ;
16127
16128 @ @c void mp_prompt_file_name (MP mp,char * s, char * e) {
16129   size_t k; /* index into |buffer| */
16130   char * saved_cur_name;
16131   if ( mp->interaction==mp_scroll_mode ) 
16132         wake_up_terminal;
16133   if (strcmp(s,"input file name")==0) {
16134         print_err("I can\'t find file `");
16135 @.I can't find file x@>
16136   } else {
16137         print_err("I can\'t write on file `");
16138   }
16139 @.I can't write on file x@>
16140   mp_print_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext); 
16141   mp_print(mp, "'.");
16142   if (strcmp(e,"")==0) 
16143         mp_show_context(mp);
16144   mp_print_nl(mp, "Please type another "); mp_print(mp, s);
16145 @.Please type...@>
16146   if ( mp->interaction<mp_scroll_mode )
16147     mp_fatal_error(mp, "*** (job aborted, file error in nonstop mode)");
16148 @.job aborted, file error...@>
16149   saved_cur_name = xstrdup(mp->cur_name);
16150   clear_terminal; prompt_input(": "); @<Scan file name in the buffer@>;
16151   if (strcmp(mp->cur_ext,"")==0) 
16152         mp->cur_ext=e;
16153   if (strlen(mp->cur_name)==0) {
16154     mp->cur_name=saved_cur_name;
16155   } else {
16156     xfree(saved_cur_name);
16157   }
16158   pack_cur_name;
16159 }
16160
16161 @ @<Scan file name in the buffer@>=
16162
16163   mp_begin_name(mp); k=mp->first;
16164   while ( (mp->buffer[k]==' ')&&(k<mp->last) ) incr(k);
16165   while (1) { 
16166     if ( k==mp->last ) break;
16167     if ( ! mp_more_name(mp, mp->buffer[k]) ) break;
16168     incr(k);
16169   }
16170   mp_end_name(mp);
16171 }
16172
16173 @ The |open_log_file| routine is used to open the transcript file and to help
16174 it catch up to what has previously been printed on the terminal.
16175
16176 @c void mp_open_log_file (MP mp) {
16177   int old_setting; /* previous |selector| setting */
16178   int k; /* index into |months| and |buffer| */
16179   int l; /* end of first input line */
16180   integer m; /* the current month */
16181   char *months="JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"; 
16182     /* abbreviations of month names */
16183   old_setting=mp->selector;
16184   if ( mp->job_name==NULL ) {
16185      mp->job_name=xstrdup("mpout");
16186   }
16187   mp_pack_job_name(mp,".log");
16188   while ( ! mp_a_open_out(mp, &mp->log_file, mp_filetype_log) ) {
16189     @<Try to get a different log file name@>;
16190   }
16191   mp->log_name=xstrdup(mp->name_of_file);
16192   mp->selector=log_only; mp->log_opened=true;
16193   @<Print the banner line, including the date and time@>;
16194   mp->input_stack[mp->input_ptr]=mp->cur_input; 
16195     /* make sure bottom level is in memory */
16196   mp_print_nl(mp, "**");
16197 @.**@>
16198   l=mp->input_stack[0].limit_field-1; /* last position of first line */
16199   for (k=0;k<=l;k++) mp_print_str(mp, mp->buffer[k]);
16200   mp_print_ln(mp); /* now the transcript file contains the first line of input */
16201   mp->selector=old_setting+2; /* |log_only| or |term_and_log| */
16202 }
16203
16204 @ @<Dealloc variables@>=
16205 xfree(mp->log_name);
16206
16207 @ Sometimes |open_log_file| is called at awkward moments when \MP\ is
16208 unable to print error messages or even to |show_context|.
16209 The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
16210 routine will not be invoked because |log_opened| will be false.
16211
16212 The normal idea of |mp_batch_mode| is that nothing at all should be written
16213 on the terminal. However, in the unusual case that
16214 no log file could be opened, we make an exception and allow
16215 an explanatory message to be seen.
16216
16217 Incidentally, the program always refers to the log file as a `\.{transcript
16218 file}', because some systems cannot use the extension `\.{.log}' for
16219 this file.
16220
16221 @<Try to get a different log file name@>=
16222 {  
16223   mp->selector=term_only;
16224   mp_prompt_file_name(mp, "transcript file name",".log");
16225 }
16226
16227 @ @<Print the banner...@>=
16228
16229   wlog(banner);
16230   mp_print(mp, mp->mem_ident); mp_print(mp, "  ");
16231   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_day])); 
16232   mp_print_char(mp, ' ');
16233   m=mp_round_unscaled(mp, mp->internal[mp_month]);
16234   for (k=3*m-3;k<3*m;k++) { wlog_chr(months[k]); }
16235   mp_print_char(mp, ' '); 
16236   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_year])); 
16237   mp_print_char(mp, ' ');
16238   m=mp_round_unscaled(mp, mp->internal[mp_time]);
16239   mp_print_dd(mp, m / 60); mp_print_char(mp, ':'); mp_print_dd(mp, m % 60);
16240 }
16241
16242 @ The |try_extension| function tries to open an input file determined by
16243 |cur_name|, |cur_area|, and the argument |ext|.  It returns |false| if it
16244 can't find the file in |cur_area| or the appropriate system area.
16245
16246 @c boolean mp_try_extension (MP mp,char *ext) { 
16247   mp_pack_file_name(mp, mp->cur_name,mp->cur_area, ext);
16248   in_name=xstrdup(mp->cur_name); 
16249   in_area=xstrdup(mp->cur_area);
16250   if ( mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16251     return true;
16252   } else { 
16253     if (strcmp(ext,".mf")==0 ) in_area=xstrdup(MF_area);
16254     else in_area=xstrdup(MP_area);
16255     mp_pack_file_name(mp, mp->cur_name,in_area,ext);
16256     return mp_a_open_in(mp, &cur_file, mp_filetype_program);
16257   }
16258   return false;
16259 }
16260
16261 @ Let's turn now to the procedure that is used to initiate file reading
16262 when an `\.{input}' command is being processed.
16263
16264 @c void mp_start_input (MP mp) { /* \MP\ will \.{input} something */
16265   char *fname = NULL;
16266   @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>;
16267   while (1) { 
16268     mp_begin_file_reading(mp); /* set up |cur_file| and new level of input */
16269     if ( strlen(mp->cur_ext)==0 ) {
16270       if ( mp_try_extension(mp, ".mp") ) break;
16271       else if ( mp_try_extension(mp, "") ) break;
16272       else if ( mp_try_extension(mp, ".mf") ) break;
16273       /* |else do_nothing; | */
16274     } else if ( mp_try_extension(mp, mp->cur_ext) ) {
16275       break;
16276     }
16277     mp_end_file_reading(mp); /* remove the level that didn't work */
16278     mp_prompt_file_name(mp, "input file name","");
16279   }
16280   name=mp_a_make_name_string(mp, cur_file);
16281   fname = xstrdup(mp->name_of_file);
16282   if ( mp->job_name==NULL ) {
16283     mp->job_name=xstrdup(mp->cur_name); 
16284     mp_open_log_file(mp);
16285   } /* |open_log_file| doesn't |show_context|, so |limit|
16286         and |loc| needn't be set to meaningful values yet */
16287   if ( ((int)mp->term_offset+(int)strlen(fname)) > (mp->max_print_line-2)) mp_print_ln(mp);
16288   else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
16289   mp_print_char(mp, '('); incr(mp->open_parens); mp_print(mp, fname); 
16290   xfree(fname);
16291   update_terminal;
16292   @<Flush |name| and replace it with |cur_name| if it won't be needed@>;
16293   @<Read the first line of the new file@>;
16294 }
16295
16296 @ This code should be omitted if |a_make_name_string| returns something other
16297 than just a copy of its argument and the full file name is needed for opening
16298 \.{MPX} files or implementing the switch-to-editor option.
16299 @^system dependencies@>
16300
16301 @<Flush |name| and replace it with |cur_name| if it won't be needed@>=
16302 mp_flush_string(mp, name); name=rts(mp->cur_name); xfree(mp->cur_name)
16303
16304 @ Here we have to remember to tell the |input_ln| routine not to
16305 start with a |get|. If the file is empty, it is considered to
16306 contain a single blank line.
16307 @^system dependencies@>
16308
16309 @<Read the first line...@>=
16310
16311   line=1;
16312   (void)mp_input_ln(mp, cur_file,false); 
16313   mp_firm_up_the_line(mp);
16314   mp->buffer[limit]='%'; mp->first=limit+1; loc=start;
16315 }
16316
16317 @ @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>=
16318 while ( token_state &&(loc==null) ) mp_end_token_list(mp);
16319 if ( token_state ) { 
16320   print_err("File names can't appear within macros");
16321 @.File names can't...@>
16322   help3("Sorry...I've converted what follows to tokens,")
16323     ("possibly garbaging the name you gave.")
16324     ("Please delete the tokens and insert the name again.");
16325   mp_error(mp);
16326 }
16327 if ( file_state ) {
16328   mp_scan_file_name(mp);
16329 } else { 
16330    xfree(mp->cur_name); mp->cur_name=xstrdup(""); 
16331    xfree(mp->cur_ext);  mp->cur_ext =xstrdup(""); 
16332    xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
16333 }
16334
16335 @ Sometimes we need to deal with two file names at once.  This procedure
16336 copies the given string into a special array for an old file name.
16337
16338 @c void mp_copy_old_name (MP mp,str_number s) {
16339   integer k; /* number of positions filled in |old_file_name| */
16340   pool_pointer j; /* index into |str_pool| */
16341   k=0;
16342   for (j=mp->str_start[s];j<=str_stop(s)-1;j++) { 
16343     incr(k);
16344     if ( k<=file_name_size ) 
16345       mp->old_file_name[k]=xchr(mp->str_pool[j]);
16346   }
16347   mp->old_file_name[++k] = 0;
16348 }
16349
16350 @ @<Glob...@>=
16351 char old_file_name[file_name_size+1];  /* analogous to |name_of_file| */
16352
16353 @ The following simple routine starts reading the \.{MPX} file associated
16354 with the current input file.
16355
16356 @c void mp_start_mpx_input (MP mp) {
16357   mp_pack_file_name(mp, in_name, in_area, ".mpx");
16358   @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16359     |goto not_found| if there is a problem@>;
16360   mp_begin_file_reading(mp);
16361   if ( ! mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16362     mp_end_file_reading(mp);
16363     goto NOT_FOUND;
16364   }
16365   name=mp_a_make_name_string(mp, cur_file);
16366   mp->mpx_name[index]=name; add_str_ref(name);
16367   @<Read the first line of the new file@>;
16368   return;
16369 NOT_FOUND: 
16370     @<Explain that the \.{MPX} file can't be read and |succumb|@>;
16371 }
16372
16373 @ This should ideally be changed to do whatever is necessary to create the
16374 \.{MPX} file given by |name_of_file| if it does not exist or if it is out
16375 of date.  This requires invoking \.{MPtoTeX} on the |old_file_name| and passing
16376 the results through \TeX\ and \.{DVItoMP}.  (It is possible to use a
16377 completely different typesetting program if suitable postprocessor is
16378 available to perform the function of \.{DVItoMP}.)
16379 @^system dependencies@>
16380
16381 @ @<Exported types@>=
16382 typedef int (*mp_run_make_mpx_command)(MP mp, char *origname, char *mtxname);
16383
16384 @ @<Glob...@>=
16385 mp_run_make_mpx_command run_make_mpx;
16386
16387 @ @<Option variables@>=
16388 mp_run_make_mpx_command run_make_mpx;
16389
16390 @ @<Allocate or initialize ...@>=
16391 set_callback_option(run_make_mpx);
16392
16393 @ @<Internal library declarations@>=
16394 int mp_run_make_mpx (MP mp, char *origname, char *mtxname);
16395
16396 @ The default does nothing.
16397 @c 
16398 int mp_run_make_mpx (MP mp, char *origname, char *mtxname) {
16399   if (mp && origname && mtxname) /* for -W */
16400     return false;
16401   return false;
16402 }
16403
16404
16405
16406 @ @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16407   |goto not_found| if there is a problem@>=
16408 mp_copy_old_name(mp, name);
16409 if (!(mp->run_make_mpx)(mp, mp->old_file_name, mp->name_of_file))
16410    goto NOT_FOUND
16411
16412 @ @<Explain that the \.{MPX} file can't be read and |succumb|@>=
16413 if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16414 mp_print_nl(mp, ">> ");
16415 mp_print(mp, mp->old_file_name);
16416 mp_print_nl(mp, ">> ");
16417 mp_print(mp, mp->name_of_file);
16418 mp_print_nl(mp, "! Unable to make mpx file");
16419 help4("The two files given above are one of your source files")
16420   ("and an auxiliary file I need to read to find out what your")
16421   ("btex..etex blocks mean. If you don't know why I had trouble,")
16422   ("try running it manually through MPtoTeX, TeX, and DVItoMP");
16423 succumb;
16424
16425 @ The last file-opening commands are for files accessed via the \&{readfrom}
16426 @:read_from_}{\&{readfrom} primitive@>
16427 operator and the \&{write} command.  Such files are stored in separate arrays.
16428 @:write_}{\&{write} primitive@>
16429
16430 @<Types in the outer block@>=
16431 typedef unsigned int readf_index; /* |0..max_read_files| */
16432 typedef unsigned int write_index;  /* |0..max_write_files| */
16433
16434 @ @<Glob...@>=
16435 readf_index max_read_files; /* maximum number of simultaneously open \&{readfrom} files */
16436 FILE ** rd_file; /* \&{readfrom} files */
16437 char ** rd_fname; /* corresponding file name or 0 if file not open */
16438 readf_index read_files; /* number of valid entries in the above arrays */
16439 write_index max_write_files; /* maximum number of simultaneously open \&{write} */
16440 FILE ** wr_file; /* \&{write} files */
16441 char ** wr_fname; /* corresponding file name or 0 if file not open */
16442 write_index write_files; /* number of valid entries in the above arrays */
16443
16444 @ @<Allocate or initialize ...@>=
16445 mp->max_read_files=8;
16446 mp->rd_file = xmalloc((mp->max_read_files+1),sizeof(FILE *));
16447 mp->rd_fname = xmalloc((mp->max_read_files+1),sizeof(char *));
16448 memset(mp->rd_fname, 0, sizeof(char *)*(mp->max_read_files+1));
16449 mp->read_files=0;
16450 mp->max_write_files=8;
16451 mp->wr_file = xmalloc((mp->max_write_files+1),sizeof(FILE *));
16452 mp->wr_fname = xmalloc((mp->max_write_files+1),sizeof(char *));
16453 memset(mp->wr_fname, 0, sizeof(char *)*(mp->max_write_files+1));
16454 mp->write_files=0;
16455
16456
16457 @ This routine starts reading the file named by string~|s| without setting
16458 |loc|, |limit|, or |name|.  It returns |false| if the file is empty or cannot
16459 be opened.  Otherwise it updates |rd_file[n]| and |rd_fname[n]|.
16460
16461 @c boolean mp_start_read_input (MP mp,char *s, readf_index  n) {
16462   mp_ptr_scan_file(mp, s);
16463   pack_cur_name;
16464   mp_begin_file_reading(mp);
16465   if ( ! mp_a_open_in(mp, &mp->rd_file[n], mp_filetype_text) ) 
16466         goto NOT_FOUND;
16467   if ( ! mp_input_ln(mp, mp->rd_file[n], false) ) {
16468     fclose(mp->rd_file[n]); 
16469         goto NOT_FOUND; 
16470   }
16471   mp->rd_fname[n]=xstrdup(mp->name_of_file);
16472   return true;
16473 NOT_FOUND: 
16474   mp_end_file_reading(mp);
16475   return false;
16476 }
16477
16478 @ Open |wr_file[n]| using file name~|s| and update |wr_fname[n]|.
16479
16480 @<Declarations@>=
16481 void mp_open_write_file (MP mp, char *s, readf_index  n) ;
16482
16483 @ @c void mp_open_write_file (MP mp,char *s, readf_index  n) {
16484   mp_ptr_scan_file(mp, s);
16485   pack_cur_name;
16486   while ( ! mp_a_open_out(mp, &mp->wr_file[n], mp_filetype_text) )
16487     mp_prompt_file_name(mp, "file name for write output","");
16488   mp->wr_fname[n]=xstrdup(mp->name_of_file);
16489 }
16490
16491
16492 @* \[36] Introduction to the parsing routines.
16493 We come now to the central nervous system that sparks many of \MP's activities.
16494 By evaluating expressions, from their primary constituents to ever larger
16495 subexpressions, \MP\ builds the structures that ultimately define complete
16496 pictures or fonts of type.
16497
16498 Four mutually recursive subroutines are involved in this process: We call them
16499 $$\hbox{|scan_primary|, |scan_secondary|, |scan_tertiary|,
16500 and |scan_expression|.}$$
16501 @^recursion@>
16502 Each of them is parameterless and begins with the first token to be scanned
16503 already represented in |cur_cmd|, |cur_mod|, and |cur_sym|. After execution,
16504 the value of the primary or secondary or tertiary or expression that was
16505 found will appear in the global variables |cur_type| and |cur_exp|. The
16506 token following the expression will be represented in |cur_cmd|, |cur_mod|,
16507 and |cur_sym|.
16508
16509 Technically speaking, the parsing algorithms are ``LL(1),'' more or less;
16510 backup mechanisms have been added in order to provide reasonable error
16511 recovery.
16512
16513 @<Glob...@>=
16514 small_number cur_type; /* the type of the expression just found */
16515 integer cur_exp; /* the value of the expression just found */
16516
16517 @ @<Set init...@>=
16518 mp->cur_exp=0;
16519
16520 @ Many different kinds of expressions are possible, so it is wise to have
16521 precise descriptions of what |cur_type| and |cur_exp| mean in all cases:
16522
16523 \smallskip\hang
16524 |cur_type=mp_vacuous| means that this expression didn't turn out to have a
16525 value at all, because it arose from a \&{begingroup}$\,\ldots\,$\&{endgroup}
16526 construction in which there was no expression before the \&{endgroup}.
16527 In this case |cur_exp| has some irrelevant value.
16528
16529 \smallskip\hang
16530 |cur_type=mp_boolean_type| means that |cur_exp| is either |true_code|
16531 or |false_code|.
16532
16533 \smallskip\hang
16534 |cur_type=mp_unknown_boolean| means that |cur_exp| points to a capsule
16535 node that is in the ring of variables equivalent
16536 to at least one undefined boolean variable.
16537
16538 \smallskip\hang
16539 |cur_type=mp_string_type| means that |cur_exp| is a string number (i.e., an
16540 integer in the range |0<=cur_exp<str_ptr|). That string's reference count
16541 includes this particular reference.
16542
16543 \smallskip\hang
16544 |cur_type=mp_unknown_string| means that |cur_exp| points to a capsule
16545 node that is in the ring of variables equivalent
16546 to at least one undefined string variable.
16547
16548 \smallskip\hang
16549 |cur_type=mp_pen_type| means that |cur_exp| points to a node in a pen.  Nobody
16550 else points to any of the nodes in this pen.  The pen may be polygonal or
16551 elliptical.
16552
16553 \smallskip\hang
16554 |cur_type=mp_unknown_pen| means that |cur_exp| points to a capsule
16555 node that is in the ring of variables equivalent
16556 to at least one undefined pen variable.
16557
16558 \smallskip\hang
16559 |cur_type=mp_path_type| means that |cur_exp| points to a the first node of
16560 a path; nobody else points to this particular path. The control points of
16561 the path will have been chosen.
16562
16563 \smallskip\hang
16564 |cur_type=mp_unknown_path| means that |cur_exp| points to a capsule
16565 node that is in the ring of variables equivalent
16566 to at least one undefined path variable.
16567
16568 \smallskip\hang
16569 |cur_type=mp_picture_type| means that |cur_exp| points to an edge header node.
16570 There may be other pointers to this particular set of edges.  The header node
16571 contains a reference count that includes this particular reference.
16572
16573 \smallskip\hang
16574 |cur_type=mp_unknown_picture| means that |cur_exp| points to a capsule
16575 node that is in the ring of variables equivalent
16576 to at least one undefined picture variable.
16577
16578 \smallskip\hang
16579 |cur_type=mp_transform_type| means that |cur_exp| points to a |mp_transform_type|
16580 capsule node. The |value| part of this capsule
16581 points to a transform node that contains six numeric values,
16582 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16583
16584 \smallskip\hang
16585 |cur_type=mp_color_type| means that |cur_exp| points to a |color_type|
16586 capsule node. The |value| part of this capsule
16587 points to a color node that contains three numeric values,
16588 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16589
16590 \smallskip\hang
16591 |cur_type=mp_cmykcolor_type| means that |cur_exp| points to a |mp_cmykcolor_type|
16592 capsule node. The |value| part of this capsule
16593 points to a color node that contains four numeric values,
16594 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16595
16596 \smallskip\hang
16597 |cur_type=mp_pair_type| means that |cur_exp| points to a capsule
16598 node whose type is |mp_pair_type|. The |value| part of this capsule
16599 points to a pair node that contains two numeric values,
16600 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16601
16602 \smallskip\hang
16603 |cur_type=mp_known| means that |cur_exp| is a |scaled| value.
16604
16605 \smallskip\hang
16606 |cur_type=mp_dependent| means that |cur_exp| points to a capsule node whose type
16607 is |dependent|. The |dep_list| field in this capsule points to the associated
16608 dependency list.
16609
16610 \smallskip\hang
16611 |cur_type=mp_proto_dependent| means that |cur_exp| points to a |mp_proto_dependent|
16612 capsule node. The |dep_list| field in this capsule
16613 points to the associated dependency list.
16614
16615 \smallskip\hang
16616 |cur_type=independent| means that |cur_exp| points to a capsule node
16617 whose type is |independent|. This somewhat unusual case can arise, for
16618 example, in the expression
16619 `$x+\&{begingroup}\penalty0\,\&{string}\,x; 0\,\&{endgroup}$'.
16620
16621 \smallskip\hang
16622 |cur_type=mp_token_list| means that |cur_exp| points to a linked list of
16623 tokens. This case arises only on the left-hand side of an assignment
16624 (`\.{:=}') operation, under very special circumstances.
16625
16626 \smallskip\noindent
16627 The possible settings of |cur_type| have been listed here in increasing
16628 numerical order. Notice that |cur_type| will never be |mp_numeric_type| or
16629 |suffixed_macro| or |mp_unsuffixed_macro|, although variables of those types
16630 are allowed.  Conversely, \MP\ has no variables of type |mp_vacuous| or
16631 |token_list|.
16632
16633 @ Capsules are two-word nodes that have a similar meaning
16634 to |cur_type| and |cur_exp|. Such nodes have |name_type=capsule|
16635 and |link<=mp_void|; and their |type| field is one of the possibilities for
16636 |cur_type| listed above.
16637
16638 The |value| field of a capsule is, in most cases, the value that
16639 corresponds to its |type|, as |cur_exp| corresponds to |cur_type|.
16640 However, when |cur_exp| would point to a capsule,
16641 no extra layer of indirection is present; the |value|
16642 field is what would have been called |value(cur_exp)| if it had not been
16643 encapsulated.  Furthermore, if the type is |dependent| or
16644 |mp_proto_dependent|, the |value| field of a capsule is replaced by
16645 |dep_list| and |prev_dep| fields, since dependency lists in capsules are
16646 always part of the general |dep_list| structure.
16647
16648 The |get_x_next| routine is careful not to change the values of |cur_type|
16649 and |cur_exp| when it gets an expanded token. However, |get_x_next| might
16650 call a macro, which might parse an expression, which might execute lots of
16651 commands in a group; hence it's possible that |cur_type| might change
16652 from, say, |mp_unknown_boolean| to |mp_boolean_type|, or from |dependent| to
16653 |known| or |independent|, during the time |get_x_next| is called. The
16654 programs below are careful to stash sensitive intermediate results in
16655 capsules, so that \MP's generality doesn't cause trouble.
16656
16657 Here's a procedure that illustrates these conventions. It takes
16658 the contents of $(|cur_type|\kern-.3pt,|cur_exp|\kern-.3pt)$
16659 and stashes them away in a
16660 capsule. It is not used when |cur_type=mp_token_list|.
16661 After the operation, |cur_type=mp_vacuous|; hence there is no need to
16662 copy path lists or to update reference counts, etc.
16663
16664 The special link |mp_void| is put on the capsule returned by
16665 |stash_cur_exp|, because this procedure is used to store macro parameters
16666 that must be easily distinguishable from token lists.
16667
16668 @<Declare the stashing/unstashing routines@>=
16669 pointer mp_stash_cur_exp (MP mp) {
16670   pointer p; /* the capsule that will be returned */
16671   switch (mp->cur_type) {
16672   case unknown_types:
16673   case mp_transform_type:
16674   case mp_color_type:
16675   case mp_pair_type:
16676   case mp_dependent:
16677   case mp_proto_dependent:
16678   case mp_independent: 
16679   case mp_cmykcolor_type:
16680     p=mp->cur_exp;
16681     break;
16682   default: 
16683     p=mp_get_node(mp, value_node_size); name_type(p)=mp_capsule;
16684     type(p)=mp->cur_type; value(p)=mp->cur_exp;
16685     break;
16686   }
16687   mp->cur_type=mp_vacuous; link(p)=mp_void; 
16688   return p;
16689 }
16690
16691 @ The inverse of |stash_cur_exp| is the following procedure, which
16692 deletes an unnecessary capsule and puts its contents into |cur_type|
16693 and |cur_exp|.
16694
16695 The program steps of \MP\ can be divided into two categories: those in
16696 which |cur_type| and |cur_exp| are ``alive'' and those in which they are
16697 ``dead,'' in the sense that |cur_type| and |cur_exp| contain relevant
16698 information or not. It's important not to ignore them when they're alive,
16699 and it's important not to pay attention to them when they're dead.
16700
16701 There's also an intermediate category: If |cur_type=mp_vacuous|, then
16702 |cur_exp| is irrelevant, hence we can proceed without caring if |cur_type|
16703 and |cur_exp| are alive or dead. In such cases we say that |cur_type|
16704 and |cur_exp| are {\sl dormant}. It is permissible to call |get_x_next|
16705 only when they are alive or dormant.
16706
16707 The \\{stash} procedure above assumes that |cur_type| and |cur_exp|
16708 are alive or dormant. The \\{unstash} procedure assumes that they are
16709 dead or dormant; it resuscitates them.
16710
16711 @<Declare the stashing/unstashing...@>=
16712 void mp_unstash_cur_exp (MP mp,pointer p) ;
16713
16714 @ @c
16715 void mp_unstash_cur_exp (MP mp,pointer p) { 
16716   mp->cur_type=type(p);
16717   switch (mp->cur_type) {
16718   case unknown_types:
16719   case mp_transform_type:
16720   case mp_color_type:
16721   case mp_pair_type:
16722   case mp_dependent: 
16723   case mp_proto_dependent:
16724   case mp_independent:
16725   case mp_cmykcolor_type: 
16726     mp->cur_exp=p;
16727     break;
16728   default:
16729     mp->cur_exp=value(p);
16730     mp_free_node(mp, p,value_node_size);
16731     break;
16732   }
16733 }
16734
16735 @ The following procedure prints the values of expressions in an
16736 abbreviated format. If its first parameter |p| is null, the value of
16737 |(cur_type,cur_exp)| is displayed; otherwise |p| should be a capsule
16738 containing the desired value. The second parameter controls the amount of
16739 output. If it is~0, dependency lists will be abbreviated to
16740 `\.{linearform}' unless they consist of a single term.  If it is greater
16741 than~1, complicated structures (pens, pictures, and paths) will be displayed
16742 in full.
16743
16744 @<Declare subroutines for printing expressions@>=
16745 @<Declare the procedure called |print_dp|@>;
16746 @<Declare the stashing/unstashing routines@>;
16747 void mp_print_exp (MP mp,pointer p, small_number verbosity) {
16748   boolean restore_cur_exp; /* should |cur_exp| be restored? */
16749   small_number t; /* the type of the expression */
16750   pointer q; /* a big node being displayed */
16751   integer v=0; /* the value of the expression */
16752   if ( p!=null ) {
16753     restore_cur_exp=false;
16754   } else { 
16755     p=mp_stash_cur_exp(mp); restore_cur_exp=true;
16756   }
16757   t=type(p);
16758   if ( t<mp_dependent ) v=value(p); else if ( t<mp_independent ) v=dep_list(p);
16759   @<Print an abbreviated value of |v| with format depending on |t|@>;
16760   if ( restore_cur_exp ) mp_unstash_cur_exp(mp, p);
16761 }
16762
16763 @ @<Print an abbreviated value of |v| with format depending on |t|@>=
16764 switch (t) {
16765 case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
16766 case mp_boolean_type:
16767   if ( v==true_code ) mp_print(mp, "true"); else mp_print(mp, "false");
16768   break;
16769 case unknown_types: case mp_numeric_type:
16770   @<Display a variable that's been declared but not defined@>;
16771   break;
16772 case mp_string_type:
16773   mp_print_char(mp, '"'); mp_print_str(mp, v); mp_print_char(mp, '"');
16774   break;
16775 case mp_pen_type: case mp_path_type: case mp_picture_type:
16776   @<Display a complex type@>;
16777   break;
16778 case mp_transform_type: case mp_color_type: case mp_pair_type: case mp_cmykcolor_type:
16779   if ( v==null ) mp_print_type(mp, t);
16780   else @<Display a big node@>;
16781   break;
16782 case mp_known:mp_print_scaled(mp, v); break;
16783 case mp_dependent: case mp_proto_dependent:
16784   mp_print_dp(mp, t,v,verbosity);
16785   break;
16786 case mp_independent:mp_print_variable_name(mp, p); break;
16787 default: mp_confusion(mp, "exp"); break;
16788 @:this can't happen exp}{\quad exp@>
16789 }
16790
16791 @ @<Display a big node@>=
16792
16793   mp_print_char(mp, '('); q=v+mp->big_node_size[t];
16794   do {  
16795     if ( type(v)==mp_known ) mp_print_scaled(mp, value(v));
16796     else if ( type(v)==mp_independent ) mp_print_variable_name(mp, v);
16797     else mp_print_dp(mp, type(v),dep_list(v),verbosity);
16798     v=v+2;
16799     if ( v!=q ) mp_print_char(mp, ',');
16800   } while (v!=q);
16801   mp_print_char(mp, ')');
16802 }
16803
16804 @ Values of type \&{picture}, \&{path}, and \&{pen} are displayed verbosely
16805 in the log file only, unless the user has given a positive value to
16806 \\{tracingonline}.
16807
16808 @<Display a complex type@>=
16809 if ( verbosity<=1 ) {
16810   mp_print_type(mp, t);
16811 } else { 
16812   if ( mp->selector==term_and_log )
16813    if ( mp->internal[mp_tracing_online]<=0 ) {
16814     mp->selector=term_only;
16815     mp_print_type(mp, t); mp_print(mp, " (see the transcript file)");
16816     mp->selector=term_and_log;
16817   };
16818   switch (t) {
16819   case mp_pen_type:mp_print_pen(mp, v,"",false); break;
16820   case mp_path_type:mp_print_path(mp, v,"",false); break;
16821   case mp_picture_type:mp_print_edges(mp, v,"",false); break;
16822   } /* there are no other cases */
16823 }
16824
16825 @ @<Declare the procedure called |print_dp|@>=
16826 void mp_print_dp (MP mp,small_number t, pointer p, 
16827                   small_number verbosity)  {
16828   pointer q; /* the node following |p| */
16829   q=link(p);
16830   if ( (info(q)==null) || (verbosity>0) ) mp_print_dependency(mp, p,t);
16831   else mp_print(mp, "linearform");
16832 }
16833
16834 @ The displayed name of a variable in a ring will not be a capsule unless
16835 the ring consists entirely of capsules.
16836
16837 @<Display a variable that's been declared but not defined@>=
16838 { mp_print_type(mp, t);
16839 if ( v!=null )
16840   { mp_print_char(mp, ' ');
16841   while ( (name_type(v)==mp_capsule) && (v!=p) ) v=value(v);
16842   mp_print_variable_name(mp, v);
16843   };
16844 }
16845
16846 @ When errors are detected during parsing, it is often helpful to
16847 display an expression just above the error message, using |exp_err|
16848 or |disp_err| instead of |print_err|.
16849
16850 @d exp_err(A) mp_disp_err(mp, null,(A)) /* displays the current expression */
16851
16852 @<Declare subroutines for printing expressions@>=
16853 void mp_disp_err (MP mp,pointer p, char *s) { 
16854   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16855   mp_print_nl(mp, ">> ");
16856 @.>>@>
16857   mp_print_exp(mp, p,1); /* ``medium verbose'' printing of the expression */
16858   if (strlen(s)) { 
16859     mp_print_nl(mp, "! "); mp_print(mp, s);
16860 @.!\relax@>
16861   }
16862 }
16863
16864 @ If |cur_type| and |cur_exp| contain relevant information that should
16865 be recycled, we will use the following procedure, which changes |cur_type|
16866 to |known| and stores a given value in |cur_exp|. We can think of |cur_type|
16867 and |cur_exp| as either alive or dormant after this has been done,
16868 because |cur_exp| will not contain a pointer value.
16869
16870 @ @c void mp_flush_cur_exp (MP mp,scaled v) { 
16871   switch (mp->cur_type) {
16872   case unknown_types: case mp_transform_type: case mp_color_type: case mp_pair_type:
16873   case mp_dependent: case mp_proto_dependent: case mp_independent: case mp_cmykcolor_type:
16874     mp_recycle_value(mp, mp->cur_exp); 
16875     mp_free_node(mp, mp->cur_exp,value_node_size);
16876     break;
16877   case mp_string_type:
16878     delete_str_ref(mp->cur_exp); break;
16879   case mp_pen_type: case mp_path_type: 
16880     mp_toss_knot_list(mp, mp->cur_exp); break;
16881   case mp_picture_type:
16882     delete_edge_ref(mp->cur_exp); break;
16883   default: 
16884     break;
16885   }
16886   mp->cur_type=mp_known; mp->cur_exp=v;
16887 }
16888
16889 @ There's a much more general procedure that is capable of releasing
16890 the storage associated with any two-word value packet.
16891
16892 @<Declare the recycling subroutines@>=
16893 void mp_recycle_value (MP mp,pointer p) ;
16894
16895 @ @c void mp_recycle_value (MP mp,pointer p) {
16896   small_number t; /* a type code */
16897   integer vv; /* another value */
16898   pointer q,r,s,pp; /* link manipulation registers */
16899   integer v=0; /* a value */
16900   t=type(p);
16901   if ( t<mp_dependent ) v=value(p);
16902   switch (t) {
16903   case undefined: case mp_vacuous: case mp_boolean_type: case mp_known:
16904   case mp_numeric_type:
16905     break;
16906   case unknown_types:
16907     mp_ring_delete(mp, p); break;
16908   case mp_string_type:
16909     delete_str_ref(v); break;
16910   case mp_path_type: case mp_pen_type:
16911     mp_toss_knot_list(mp, v); break;
16912   case mp_picture_type:
16913     delete_edge_ref(v); break;
16914   case mp_cmykcolor_type: case mp_pair_type: case mp_color_type:
16915   case mp_transform_type:
16916     @<Recycle a big node@>; break; 
16917   case mp_dependent: case mp_proto_dependent:
16918     @<Recycle a dependency list@>; break;
16919   case mp_independent:
16920     @<Recycle an independent variable@>; break;
16921   case mp_token_list: case mp_structured:
16922     mp_confusion(mp, "recycle"); break;
16923 @:this can't happen recycle}{\quad recycle@>
16924   case mp_unsuffixed_macro: case mp_suffixed_macro:
16925     mp_delete_mac_ref(mp, value(p)); break;
16926   } /* there are no other cases */
16927   type(p)=undefined;
16928 }
16929
16930 @ @<Recycle a big node@>=
16931 if ( v!=null ){ 
16932   q=v+mp->big_node_size[t];
16933   do {  
16934     q=q-2; mp_recycle_value(mp, q);
16935   } while (q!=v);
16936   mp_free_node(mp, v,mp->big_node_size[t]);
16937 }
16938
16939 @ @<Recycle a dependency list@>=
16940
16941   q=dep_list(p);
16942   while ( info(q)!=null ) q=link(q);
16943   link(prev_dep(p))=link(q);
16944   prev_dep(link(q))=prev_dep(p);
16945   link(q)=null; mp_flush_node_list(mp, dep_list(p));
16946 }
16947
16948 @ When an independent variable disappears, it simply fades away, unless
16949 something depends on it. In the latter case, a dependent variable whose
16950 coefficient of dependence is maximal will take its place.
16951 The relevant algorithm is due to Ignacio~A. Zabala, who implemented it
16952 as part of his Ph.D. thesis (Stanford University, December 1982).
16953 @^Zabala Salelles, Ignacio Andres@>
16954
16955 For example, suppose that variable $x$ is being recycled, and that the
16956 only variables depending on~$x$ are $y=2x+a$ and $z=x+b$. In this case
16957 we want to make $y$ independent and $z=.5y-.5a+b$; no other variables
16958 will depend on~$y$. If $\\{tracingequations}>0$ in this situation,
16959 we will print `\.{\#\#\# -2x=-y+a}'.
16960
16961 There's a slight complication, however: An independent variable $x$
16962 can occur both in dependency lists and in proto-dependency lists.
16963 This makes it necessary to be careful when deciding which coefficient
16964 is maximal.
16965
16966 Furthermore, this complication is not so slight when
16967 a proto-dependent variable is chosen to become independent. For example,
16968 suppose that $y=2x+100a$ is proto-dependent while $z=x+b$ is dependent;
16969 then we must change $z=.5y-50a+b$ to a proto-dependency, because of the
16970 large coefficient `50'.
16971
16972 In order to deal with these complications without wasting too much time,
16973 we shall link together the occurrences of~$x$ among all the linear
16974 dependencies, maintaining separate lists for the dependent and
16975 proto-dependent cases.
16976
16977 @<Recycle an independent variable@>=
16978
16979   mp->max_c[mp_dependent]=0; mp->max_c[mp_proto_dependent]=0;
16980   mp->max_link[mp_dependent]=null; mp->max_link[mp_proto_dependent]=null;
16981   q=link(dep_head);
16982   while ( q!=dep_head ) { 
16983     s=value_loc(q); /* now |link(s)=dep_list(q)| */
16984     while (1) { 
16985       r=link(s);
16986       if ( info(r)==null ) break;;
16987       if ( info(r)!=p ) { 
16988        s=r;
16989       } else  { 
16990         t=type(q); link(s)=link(r); info(r)=q;
16991         if ( abs(value(r))>mp->max_c[t] ) {
16992           @<Record a new maximum coefficient of type |t|@>;
16993         } else { 
16994           link(r)=mp->max_link[t]; mp->max_link[t]=r;
16995         }
16996       }
16997     }   
16998     q=link(r);
16999   }
17000   if ( (mp->max_c[mp_dependent]>0)||(mp->max_c[mp_proto_dependent]>0) ) {
17001     @<Choose a dependent variable to take the place of the disappearing
17002     independent variable, and change all remaining dependencies
17003     accordingly@>;
17004   }
17005 }
17006
17007 @ The code for independency removal makes use of three two-word arrays.
17008
17009 @<Glob...@>=
17010 integer max_c[mp_proto_dependent+1];  /* max coefficient magnitude */
17011 pointer max_ptr[mp_proto_dependent+1]; /* where |p| occurs with |max_c| */
17012 pointer max_link[mp_proto_dependent+1]; /* other occurrences of |p| */
17013
17014 @ @<Record a new maximum coefficient...@>=
17015
17016   if ( mp->max_c[t]>0 ) {
17017     link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
17018   }
17019   mp->max_c[t]=abs(value(r)); mp->max_ptr[t]=r;
17020 }
17021
17022 @ @<Choose a dependent...@>=
17023
17024   if ( (mp->max_c[mp_dependent] / 010000 >= mp->max_c[mp_proto_dependent]) )
17025     t=mp_dependent;
17026   else 
17027     t=mp_proto_dependent;
17028   @<Determine the dependency list |s| to substitute for the independent
17029     variable~|p|@>;
17030   t=mp_dependent+mp_proto_dependent-t; /* complement |t| */
17031   if ( mp->max_c[t]>0 ) { /* we need to pick up an unchosen dependency */ 
17032     link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
17033   }
17034   if ( t!=mp_dependent ) { @<Substitute new dependencies in place of |p|@>; }
17035   else { @<Substitute new proto-dependencies in place of |p|@>;}
17036   mp_flush_node_list(mp, s);
17037   if ( mp->fix_needed ) mp_fix_dependencies(mp);
17038   check_arith;
17039 }
17040
17041 @ Let |s=max_ptr[t]|. At this point we have $|value|(s)=\pm|max_c|[t]$,
17042 and |info(s)| points to the dependent variable~|pp| of type~|t| from
17043 whose dependency list we have removed node~|s|. We must reinsert
17044 node~|s| into the dependency list, with coefficient $-1.0$, and with
17045 |pp| as the new independent variable. Since |pp| will have a larger serial
17046 number than any other variable, we can put node |s| at the head of the
17047 list.
17048
17049 @<Determine the dep...@>=
17050 s=mp->max_ptr[t]; pp=info(s); v=value(s);
17051 if ( t==mp_dependent ) value(s)=-fraction_one; else value(s)=-unity;
17052 r=dep_list(pp); link(s)=r;
17053 while ( info(r)!=null ) r=link(r);
17054 q=link(r); link(r)=null;
17055 prev_dep(q)=prev_dep(pp); link(prev_dep(pp))=q;
17056 new_indep(pp);
17057 if ( mp->cur_exp==pp ) if ( mp->cur_type==t ) mp->cur_type=mp_independent;
17058 if ( mp->internal[mp_tracing_equations]>0 ) { 
17059   @<Show the transformed dependency@>; 
17060 }
17061
17062 @ Now $(-v)$ times the formerly independent variable~|p| is being replaced
17063 by the dependency list~|s|.
17064
17065 @<Show the transformed...@>=
17066 if ( mp_interesting(mp, p) ) {
17067   mp_begin_diagnostic(mp); mp_print_nl(mp, "### ");
17068 @:]]]\#\#\#_}{\.{\#\#\#}@>
17069   if ( v>0 ) mp_print_char(mp, '-');
17070   if ( t==mp_dependent ) vv=mp_round_fraction(mp, mp->max_c[mp_dependent]);
17071   else vv=mp->max_c[mp_proto_dependent];
17072   if ( vv!=unity ) mp_print_scaled(mp, vv);
17073   mp_print_variable_name(mp, p);
17074   while ( value(p) % s_scale>0 ) {
17075     mp_print(mp, "*4"); value(p)=value(p)-2;
17076   }
17077   if ( t==mp_dependent ) mp_print_char(mp, '='); else mp_print(mp, " = ");
17078   mp_print_dependency(mp, s,t);
17079   mp_end_diagnostic(mp, false);
17080 }
17081
17082 @ Finally, there are dependent and proto-dependent variables whose
17083 dependency lists must be brought up to date.
17084
17085 @<Substitute new dependencies...@>=
17086 for (t=mp_dependent;t<=mp_proto_dependent;t++){ 
17087   r=mp->max_link[t];
17088   while ( r!=null ) {
17089     q=info(r);
17090     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
17091      mp_make_fraction(mp, value(r),-v),s,t,mp_dependent);
17092     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
17093     q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
17094   }
17095 }
17096
17097 @ @<Substitute new proto...@>=
17098 for (t=mp_dependent;t<=mp_proto_dependent;t++) {
17099   r=mp->max_link[t];
17100   while ( r!=null ) {
17101     q=info(r);
17102     if ( t==mp_dependent ) { /* for safety's sake, we change |q| to |mp_proto_dependent| */
17103       if ( mp->cur_exp==q ) if ( mp->cur_type==mp_dependent )
17104         mp->cur_type=mp_proto_dependent;
17105       dep_list(q)=mp_p_over_v(mp, dep_list(q),unity,mp_dependent,mp_proto_dependent);
17106       type(q)=mp_proto_dependent; value(r)=mp_round_fraction(mp, value(r));
17107     }
17108     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
17109       mp_make_scaled(mp, value(r),-v),s,mp_proto_dependent,mp_proto_dependent);
17110     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
17111     q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
17112   }
17113 }
17114
17115 @ Here are some routines that provide handy combinations of actions
17116 that are often needed during error recovery. For example,
17117 `|flush_error|' flushes the current expression, replaces it by
17118 a given value, and calls |error|.
17119
17120 Errors often are detected after an extra token has already been scanned.
17121 The `\\{put\_get}' routines put that token back before calling |error|;
17122 then they get it back again. (Or perhaps they get another token, if
17123 the user has changed things.)
17124
17125 @<Declarations@>=
17126 void mp_flush_error (MP mp,scaled v);
17127 void mp_put_get_error (MP mp);
17128 void mp_put_get_flush_error (MP mp,scaled v) ;
17129
17130 @ @c
17131 void mp_flush_error (MP mp,scaled v) { 
17132   mp_error(mp); mp_flush_cur_exp(mp, v); 
17133 }
17134 void mp_put_get_error (MP mp) { 
17135   mp_back_error(mp); mp_get_x_next(mp); 
17136 }
17137 void mp_put_get_flush_error (MP mp,scaled v) { 
17138   mp_put_get_error(mp);
17139   mp_flush_cur_exp(mp, v); 
17140 }
17141
17142 @ A global variable |var_flag| is set to a special command code
17143 just before \MP\ calls |scan_expression|, if the expression should be
17144 treated as a variable when this command code immediately follows. For
17145 example, |var_flag| is set to |assignment| at the beginning of a
17146 statement, because we want to know the {\sl location\/} of a variable at
17147 the left of `\.{:=}', not the {\sl value\/} of that variable.
17148
17149 The |scan_expression| subroutine calls |scan_tertiary|,
17150 which calls |scan_secondary|, which calls |scan_primary|, which sets
17151 |var_flag:=0|. In this way each of the scanning routines ``knows''
17152 when it has been called with a special |var_flag|, but |var_flag| is
17153 usually zero.
17154
17155 A variable preceding a command that equals |var_flag| is converted to a
17156 token list rather than a value. Furthermore, an `\.{=}' sign following an
17157 expression with |var_flag=assignment| is not considered to be a relation
17158 that produces boolean expressions.
17159
17160
17161 @<Glob...@>=
17162 int var_flag; /* command that wants a variable */
17163
17164 @ @<Set init...@>=
17165 mp->var_flag=0;
17166
17167 @* \[37] Parsing primary expressions.
17168 The first parsing routine, |scan_primary|, is also the most complicated one,
17169 since it involves so many different cases. But each case---with one
17170 exception---is fairly simple by itself.
17171
17172 When |scan_primary| begins, the first token of the primary to be scanned
17173 should already appear in |cur_cmd|, |cur_mod|, and |cur_sym|. The values
17174 of |cur_type| and |cur_exp| should be either dead or dormant, as explained
17175 earlier. If |cur_cmd| is not between |min_primary_command| and
17176 |max_primary_command|, inclusive, a syntax error will be signaled.
17177
17178 @<Declare the basic parsing subroutines@>=
17179 void mp_scan_primary (MP mp) {
17180   pointer p,q,r; /* for list manipulation */
17181   quarterword c; /* a primitive operation code */
17182   int my_var_flag; /* initial value of |my_var_flag| */
17183   pointer l_delim,r_delim; /* hash addresses of a delimiter pair */
17184   @<Other local variables for |scan_primary|@>;
17185   my_var_flag=mp->var_flag; mp->var_flag=0;
17186 RESTART:
17187   check_arith;
17188   @<Supply diagnostic information, if requested@>;
17189   switch (mp->cur_cmd) {
17190   case left_delimiter:
17191     @<Scan a delimited primary@>; break;
17192   case begin_group:
17193     @<Scan a grouped primary@>; break;
17194   case string_token:
17195     @<Scan a string constant@>; break;
17196   case numeric_token:
17197     @<Scan a primary that starts with a numeric token@>; break;
17198   case nullary:
17199     @<Scan a nullary operation@>; break;
17200   case unary: case type_name: case cycle: case plus_or_minus:
17201     @<Scan a unary operation@>; break;
17202   case primary_binary:
17203     @<Scan a binary operation with `\&{of}' between its operands@>; break;
17204   case str_op:
17205     @<Convert a suffix to a string@>; break;
17206   case internal_quantity:
17207     @<Scan an internal numeric quantity@>; break;
17208   case capsule_token:
17209     mp_make_exp_copy(mp, mp->cur_mod); break;
17210   case tag_token:
17211     @<Scan a variable primary; |goto restart| if it turns out to be a macro@>; break;
17212   default: 
17213     mp_bad_exp(mp, "A primary"); goto RESTART; break;
17214 @.A primary expression...@>
17215   }
17216   mp_get_x_next(mp); /* the routines |goto done| if they don't want this */
17217 DONE: 
17218   if ( mp->cur_cmd==left_bracket ) {
17219     if ( mp->cur_type>=mp_known ) {
17220       @<Scan a mediation construction@>;
17221     }
17222   }
17223 }
17224
17225
17226
17227 @ Errors at the beginning of expressions are flagged by |bad_exp|.
17228
17229 @c void mp_bad_exp (MP mp,char * s) {
17230   int save_flag;
17231   print_err(s); mp_print(mp, " expression can't begin with `");
17232   mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); 
17233   mp_print_char(mp, '\'');
17234   help4("I'm afraid I need some sort of value in order to continue,")
17235     ("so I've tentatively inserted `0'. You may want to")
17236     ("delete this zero and insert something else;")
17237     ("see Chapter 27 of The METAFONTbook for an example.");
17238 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
17239   mp_back_input(mp); mp->cur_sym=0; mp->cur_cmd=numeric_token; 
17240   mp->cur_mod=0; mp_ins_error(mp);
17241   save_flag=mp->var_flag; mp->var_flag=0; mp_get_x_next(mp);
17242   mp->var_flag=save_flag;
17243 }
17244
17245 @ @<Supply diagnostic information, if requested@>=
17246 #ifdef DEBUG
17247 if ( mp->panicking ) mp_check_mem(mp, false);
17248 #endif
17249 if ( mp->interrupt!=0 ) if ( mp->OK_to_interrupt ) {
17250   mp_back_input(mp); check_interrupt; mp_get_x_next(mp);
17251 }
17252
17253 @ @<Scan a delimited primary@>=
17254
17255   l_delim=mp->cur_sym; r_delim=mp->cur_mod; 
17256   mp_get_x_next(mp); mp_scan_expression(mp);
17257   if ( (mp->cur_cmd==comma) && (mp->cur_type>=mp_known) ) {
17258     @<Scan the rest of a delimited set of numerics@>;
17259   } else {
17260     mp_check_delimiter(mp, l_delim,r_delim);
17261   }
17262 }
17263
17264 @ The |stash_in| subroutine puts the current (numeric) expression into a field
17265 within a ``big node.''
17266
17267 @c void mp_stash_in (MP mp,pointer p) {
17268   pointer q; /* temporary register */
17269   type(p)=mp->cur_type;
17270   if ( mp->cur_type==mp_known ) {
17271     value(p)=mp->cur_exp;
17272   } else { 
17273     if ( mp->cur_type==mp_independent ) {
17274       @<Stash an independent |cur_exp| into a big node@>;
17275     } else { 
17276       mp->mem[value_loc(p)]=mp->mem[value_loc(mp->cur_exp)];
17277       /* |dep_list(p):=dep_list(cur_exp)| and |prev_dep(p):=prev_dep(cur_exp)| */
17278       link(prev_dep(p))=p;
17279     }
17280     mp_free_node(mp, mp->cur_exp,value_node_size);
17281   }
17282   mp->cur_type=mp_vacuous;
17283 }
17284
17285 @ In rare cases the current expression can become |independent|. There
17286 may be many dependency lists pointing to such an independent capsule,
17287 so we can't simply move it into place within a big node. Instead,
17288 we copy it, then recycle it.
17289
17290 @ @<Stash an independent |cur_exp|...@>=
17291
17292   q=mp_single_dependency(mp, mp->cur_exp);
17293   if ( q==mp->dep_final ){ 
17294     type(p)=mp_known; value(p)=0; mp_free_node(mp, q,dep_node_size);
17295   } else { 
17296     type(p)=mp_dependent; mp_new_dep(mp, p,q);
17297   }
17298   mp_recycle_value(mp, mp->cur_exp);
17299 }
17300
17301 @ This code uses the fact that |red_part_loc| and |green_part_loc|
17302 are synonymous with |x_part_loc| and |y_part_loc|.
17303
17304 @<Scan the rest of a delimited set of numerics@>=
17305
17306 p=mp_stash_cur_exp(mp);
17307 mp_get_x_next(mp); mp_scan_expression(mp);
17308 @<Make sure the second part of a pair or color has a numeric type@>;
17309 q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
17310 if ( mp->cur_cmd==comma ) type(q)=mp_color_type;
17311 else type(q)=mp_pair_type;
17312 mp_init_big_node(mp, q); r=value(q);
17313 mp_stash_in(mp, y_part_loc(r));
17314 mp_unstash_cur_exp(mp, p);
17315 mp_stash_in(mp, x_part_loc(r));
17316 if ( mp->cur_cmd==comma ) {
17317   @<Scan the last of a triplet of numerics@>;
17318 }
17319 if ( mp->cur_cmd==comma ) {
17320   type(q)=mp_cmykcolor_type;
17321   mp_init_big_node(mp, q); t=value(q);
17322   mp->mem[cyan_part_loc(t)]=mp->mem[red_part_loc(r)];
17323   value(cyan_part_loc(t))=value(red_part_loc(r));
17324   mp->mem[magenta_part_loc(t)]=mp->mem[green_part_loc(r)];
17325   value(magenta_part_loc(t))=value(green_part_loc(r));
17326   mp->mem[yellow_part_loc(t)]=mp->mem[blue_part_loc(r)];
17327   value(yellow_part_loc(t))=value(blue_part_loc(r));
17328   mp_recycle_value(mp, r);
17329   r=t;
17330   @<Scan the last of a quartet of numerics@>;
17331 }
17332 mp_check_delimiter(mp, l_delim,r_delim);
17333 mp->cur_type=type(q);
17334 mp->cur_exp=q;
17335 }
17336
17337 @ @<Make sure the second part of a pair or color has a numeric type@>=
17338 if ( mp->cur_type<mp_known ) {
17339   exp_err("Nonnumeric ypart has been replaced by 0");
17340 @.Nonnumeric...replaced by 0@>
17341   help4("I've started to scan a pair `(a,b)' or a color `(a,b,c)';")
17342     ("but after finding a nice `a' I found a `b' that isn't")
17343     ("of numeric type. So I've changed that part to zero.")
17344     ("(The b that I didn't like appears above the error message.)");
17345   mp_put_get_flush_error(mp, 0);
17346 }
17347
17348 @ @<Scan the last of a triplet of numerics@>=
17349
17350   mp_get_x_next(mp); mp_scan_expression(mp);
17351   if ( mp->cur_type<mp_known ) {
17352     exp_err("Nonnumeric third part has been replaced by 0");
17353 @.Nonnumeric...replaced by 0@>
17354     help3("I've just scanned a color `(a,b,c)' or cmykcolor(a,b,c,d); but the `c'")
17355       ("isn't of numeric type. So I've changed that part to zero.")
17356       ("(The c that I didn't like appears above the error message.)");
17357     mp_put_get_flush_error(mp, 0);
17358   }
17359   mp_stash_in(mp, blue_part_loc(r));
17360 }
17361
17362 @ @<Scan the last of a quartet of numerics@>=
17363
17364   mp_get_x_next(mp); mp_scan_expression(mp);
17365   if ( mp->cur_type<mp_known ) {
17366     exp_err("Nonnumeric blackpart has been replaced by 0");
17367 @.Nonnumeric...replaced by 0@>
17368     help3("I've just scanned a cmykcolor `(c,m,y,k)'; but the `k' isn't")
17369       ("of numeric type. So I've changed that part to zero.")
17370       ("(The k that I didn't like appears above the error message.)");
17371     mp_put_get_flush_error(mp, 0);
17372   }
17373   mp_stash_in(mp, black_part_loc(r));
17374 }
17375
17376 @ The local variable |group_line| keeps track of the line
17377 where a \&{begingroup} command occurred; this will be useful
17378 in an error message if the group doesn't actually end.
17379
17380 @<Other local variables for |scan_primary|@>=
17381 integer group_line; /* where a group began */
17382
17383 @ @<Scan a grouped primary@>=
17384
17385   group_line=mp_true_line(mp);
17386   if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17387   save_boundary_item(p);
17388   do {  
17389     mp_do_statement(mp); /* ends with |cur_cmd>=semicolon| */
17390   } while (! (mp->cur_cmd!=semicolon));
17391   if ( mp->cur_cmd!=end_group ) {
17392     print_err("A group begun on line ");
17393 @.A group...never ended@>
17394     mp_print_int(mp, group_line);
17395     mp_print(mp, " never ended");
17396     help2("I saw a `begingroup' back there that hasn't been matched")
17397          ("by `endgroup'. So I've inserted `endgroup' now.");
17398     mp_back_error(mp); mp->cur_cmd=end_group;
17399   }
17400   mp_unsave(mp); 
17401     /* this might change |cur_type|, if independent variables are recycled */
17402   if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17403 }
17404
17405 @ @<Scan a string constant@>=
17406
17407   mp->cur_type=mp_string_type; mp->cur_exp=mp->cur_mod;
17408 }
17409
17410 @ Later we'll come to procedures that perform actual operations like
17411 addition, square root, and so on; our purpose now is to do the parsing.
17412 But we might as well mention those future procedures now, so that the
17413 suspense won't be too bad:
17414
17415 \smallskip
17416 |do_nullary(c)| does primitive operations that have no operands (e.g.,
17417 `\&{true}' or `\&{pencircle}');
17418
17419 \smallskip
17420 |do_unary(c)| applies a primitive operation to the current expression;
17421
17422 \smallskip
17423 |do_binary(p,c)| applies a primitive operation to the capsule~|p|
17424 and the current expression.
17425
17426 @<Scan a nullary operation@>=mp_do_nullary(mp, mp->cur_mod)
17427
17428 @ @<Scan a unary operation@>=
17429
17430   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_primary(mp); 
17431   mp_do_unary(mp, c); goto DONE;
17432 }
17433
17434 @ A numeric token might be a primary by itself, or it might be the
17435 numerator of a fraction composed solely of numeric tokens, or it might
17436 multiply the primary that follows (provided that the primary doesn't begin
17437 with a plus sign or a minus sign). The code here uses the facts that
17438 |max_primary_command=plus_or_minus| and
17439 |max_primary_command-1=numeric_token|. If a fraction is found that is less
17440 than unity, we try to retain higher precision when we use it in scalar
17441 multiplication.
17442
17443 @<Other local variables for |scan_primary|@>=
17444 scaled num,denom; /* for primaries that are fractions, like `1/2' */
17445
17446 @ @<Scan a primary that starts with a numeric token@>=
17447
17448   mp->cur_exp=mp->cur_mod; mp->cur_type=mp_known; mp_get_x_next(mp);
17449   if ( mp->cur_cmd!=slash ) { 
17450     num=0; denom=0;
17451   } else { 
17452     mp_get_x_next(mp);
17453     if ( mp->cur_cmd!=numeric_token ) { 
17454       mp_back_input(mp);
17455       mp->cur_cmd=slash; mp->cur_mod=over; mp->cur_sym=frozen_slash;
17456       goto DONE;
17457     }
17458     num=mp->cur_exp; denom=mp->cur_mod;
17459     if ( denom==0 ) { @<Protest division by zero@>; }
17460     else { mp->cur_exp=mp_make_scaled(mp, num,denom); }
17461     check_arith; mp_get_x_next(mp);
17462   }
17463   if ( mp->cur_cmd>=min_primary_command ) {
17464    if ( mp->cur_cmd<numeric_token ) { /* in particular, |cur_cmd<>plus_or_minus| */
17465      p=mp_stash_cur_exp(mp); mp_scan_primary(mp);
17466      if ( (abs(num)>=abs(denom))||(mp->cur_type<mp_color_type) ) {
17467        mp_do_binary(mp, p,times);
17468      } else {
17469        mp_frac_mult(mp, num,denom);
17470        mp_free_node(mp, p,value_node_size);
17471      }
17472     }
17473   }
17474   goto DONE;
17475 }
17476
17477 @ @<Protest division...@>=
17478
17479   print_err("Division by zero");
17480 @.Division by zero@>
17481   help1("I'll pretend that you meant to divide by 1."); mp_error(mp);
17482 }
17483
17484 @ @<Scan a binary operation with `\&{of}' between its operands@>=
17485
17486   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
17487   if ( mp->cur_cmd!=of_token ) {
17488     mp_missing_err(mp, "of"); mp_print(mp, " for "); 
17489     mp_print_cmd_mod(mp, primary_binary,c);
17490 @.Missing `of'@>
17491     help1("I've got the first argument; will look now for the other.");
17492     mp_back_error(mp);
17493   }
17494   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_primary(mp); 
17495   mp_do_binary(mp, p,c); goto DONE;
17496 }
17497
17498 @ @<Convert a suffix to a string@>=
17499
17500   mp_get_x_next(mp); mp_scan_suffix(mp); 
17501   mp->old_setting=mp->selector; mp->selector=new_string;
17502   mp_show_token_list(mp, mp->cur_exp,null,100000,0); 
17503   mp_flush_token_list(mp, mp->cur_exp);
17504   mp->cur_exp=mp_make_string(mp); mp->selector=mp->old_setting; 
17505   mp->cur_type=mp_string_type;
17506   goto DONE;
17507 }
17508
17509 @ If an internal quantity appears all by itself on the left of an
17510 assignment, we return a token list of length one, containing the address
17511 of the internal quantity plus |hash_end|. (This accords with the conventions
17512 of the save stack, as described earlier.)
17513
17514 @<Scan an internal...@>=
17515
17516   q=mp->cur_mod;
17517   if ( my_var_flag==assignment ) {
17518     mp_get_x_next(mp);
17519     if ( mp->cur_cmd==assignment ) {
17520       mp->cur_exp=mp_get_avail(mp);
17521       info(mp->cur_exp)=q+hash_end; mp->cur_type=mp_token_list; 
17522       goto DONE;
17523     }
17524     mp_back_input(mp);
17525   }
17526   mp->cur_type=mp_known; mp->cur_exp=mp->internal[q];
17527 }
17528
17529 @ The most difficult part of |scan_primary| has been saved for last, since
17530 it was necessary to build up some confidence first. We can now face the task
17531 of scanning a variable.
17532
17533 As we scan a variable, we build a token list containing the relevant
17534 names and subscript values, simultaneously following along in the
17535 ``collective'' structure to see if we are actually dealing with a macro
17536 instead of a value.
17537
17538 The local variables |pre_head| and |post_head| will point to the beginning
17539 of the prefix and suffix lists; |tail| will point to the end of the list
17540 that is currently growing.
17541
17542 Another local variable, |tt|, contains partial information about the
17543 declared type of the variable-so-far. If |tt>=mp_unsuffixed_macro|, the
17544 relation |tt=type(q)| will always hold. If |tt=undefined|, the routine
17545 doesn't bother to update its information about type. And if
17546 |undefined<tt<mp_unsuffixed_macro|, the precise value of |tt| isn't critical.
17547
17548 @ @<Other local variables for |scan_primary|@>=
17549 pointer pre_head,post_head,tail;
17550   /* prefix and suffix list variables */
17551 small_number tt; /* approximation to the type of the variable-so-far */
17552 pointer t; /* a token */
17553 pointer macro_ref = 0; /* reference count for a suffixed macro */
17554
17555 @ @<Scan a variable primary...@>=
17556
17557   fast_get_avail(pre_head); tail=pre_head; post_head=null; tt=mp_vacuous;
17558   while (1) { 
17559     t=mp_cur_tok(mp); link(tail)=t;
17560     if ( tt!=undefined ) {
17561        @<Find the approximate type |tt| and corresponding~|q|@>;
17562       if ( tt>=mp_unsuffixed_macro ) {
17563         @<Either begin an unsuffixed macro call or
17564           prepare for a suffixed one@>;
17565       }
17566     }
17567     mp_get_x_next(mp); tail=t;
17568     if ( mp->cur_cmd==left_bracket ) {
17569       @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>;
17570     }
17571     if ( mp->cur_cmd>max_suffix_token ) break;
17572     if ( mp->cur_cmd<min_suffix_token ) break;
17573   } /* now |cur_cmd| is |internal_quantity|, |tag_token|, or |numeric_token| */
17574   @<Handle unusual cases that masquerade as variables, and |goto restart|
17575     or |goto done| if appropriate;
17576     otherwise make a copy of the variable and |goto done|@>;
17577 }
17578
17579 @ @<Either begin an unsuffixed macro call or...@>=
17580
17581   link(tail)=null;
17582   if ( tt>mp_unsuffixed_macro ) { /* |tt=mp_suffixed_macro| */
17583     post_head=mp_get_avail(mp); tail=post_head; link(tail)=t;
17584     tt=undefined; macro_ref=value(q); add_mac_ref(macro_ref);
17585   } else {
17586     @<Set up unsuffixed macro call and |goto restart|@>;
17587   }
17588 }
17589
17590 @ @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>=
17591
17592   mp_get_x_next(mp); mp_scan_expression(mp);
17593   if ( mp->cur_cmd!=right_bracket ) {
17594     @<Put the left bracket and the expression back to be rescanned@>;
17595   } else { 
17596     if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17597     mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp; mp->cur_sym=0;
17598   }
17599 }
17600
17601 @ The left bracket that we thought was introducing a subscript might have
17602 actually been the left bracket in a mediation construction like `\.{x[a,b]}'.
17603 So we don't issue an error message at this point; but we do want to back up
17604 so as to avoid any embarrassment about our incorrect assumption.
17605
17606 @<Put the left bracket and the expression back to be rescanned@>=
17607
17608   mp_back_input(mp); /* that was the token following the current expression */
17609   mp_back_expr(mp); mp->cur_cmd=left_bracket; 
17610   mp->cur_mod=0; mp->cur_sym=frozen_left_bracket;
17611 }
17612
17613 @ Here's a routine that puts the current expression back to be read again.
17614
17615 @c void mp_back_expr (MP mp) {
17616   pointer p; /* capsule token */
17617   p=mp_stash_cur_exp(mp); link(p)=null; back_list(p);
17618 }
17619
17620 @ Unknown subscripts lead to the following error message.
17621
17622 @c void mp_bad_subscript (MP mp) { 
17623   exp_err("Improper subscript has been replaced by zero");
17624 @.Improper subscript...@>
17625   help3("A bracketed subscript must have a known numeric value;")
17626     ("unfortunately, what I found was the value that appears just")
17627     ("above this error message. So I'll try a zero subscript.");
17628   mp_flush_error(mp, 0);
17629 }
17630
17631 @ Every time we call |get_x_next|, there's a chance that the variable we've
17632 been looking at will disappear. Thus, we cannot safely keep |q| pointing
17633 into the variable structure; we need to start searching from the root each time.
17634
17635 @<Find the approximate type |tt| and corresponding~|q|@>=
17636 @^inner loop@>
17637
17638   p=link(pre_head); q=info(p); tt=undefined;
17639   if ( eq_type(q) % outer_tag==tag_token ) {
17640     q=equiv(q);
17641     if ( q==null ) goto DONE2;
17642     while (1) { 
17643       p=link(p);
17644       if ( p==null ) {
17645         tt=type(q); goto DONE2;
17646       };
17647       if ( type(q)!=mp_structured ) goto DONE2;
17648       q=link(attr_head(q)); /* the |collective_subscript| attribute */
17649       if ( p>=mp->hi_mem_min ) { /* it's not a subscript */
17650         do {  q=link(q); } while (! (attr_loc(q)>=info(p)));
17651         if ( attr_loc(q)>info(p) ) goto DONE2;
17652       }
17653     }
17654   }
17655 DONE2:
17656   ;
17657 }
17658
17659 @ How do things stand now? Well, we have scanned an entire variable name,
17660 including possible subscripts and/or attributes; |cur_cmd|, |cur_mod|, and
17661 |cur_sym| represent the token that follows. If |post_head=null|, a
17662 token list for this variable name starts at |link(pre_head)|, with all
17663 subscripts evaluated. But if |post_head<>null|, the variable turned out
17664 to be a suffixed macro; |pre_head| is the head of the prefix list, while
17665 |post_head| is the head of a token list containing both `\.{\AT!}' and
17666 the suffix.
17667
17668 Our immediate problem is to see if this variable still exists. (Variable
17669 structures can change drastically whenever we call |get_x_next|; users
17670 aren't supposed to do this, but the fact that it is possible means that
17671 we must be cautious.)
17672
17673 The following procedure prints an error message when a variable
17674 unexpectedly disappears. Its help message isn't quite right for
17675 our present purposes, but we'll be able to fix that up.
17676
17677 @c 
17678 void mp_obliterated (MP mp,pointer q) { 
17679   print_err("Variable "); mp_show_token_list(mp, q,null,1000,0);
17680   mp_print(mp, " has been obliterated");
17681 @.Variable...obliterated@>
17682   help5("It seems you did a nasty thing---probably by accident,")
17683     ("but nevertheless you nearly hornswoggled me...")
17684     ("While I was evaluating the right-hand side of this")
17685     ("command, something happened, and the left-hand side")
17686     ("is no longer a variable! So I won't change anything.");
17687 }
17688
17689 @ If the variable does exist, we also need to check
17690 for a few other special cases before deciding that a plain old ordinary
17691 variable has, indeed, been scanned.
17692
17693 @<Handle unusual cases that masquerade as variables...@>=
17694 if ( post_head!=null ) {
17695   @<Set up suffixed macro call and |goto restart|@>;
17696 }
17697 q=link(pre_head); free_avail(pre_head);
17698 if ( mp->cur_cmd==my_var_flag ) { 
17699   mp->cur_type=mp_token_list; mp->cur_exp=q; goto DONE;
17700 }
17701 p=mp_find_variable(mp, q);
17702 if ( p!=null ) {
17703   mp_make_exp_copy(mp, p);
17704 } else { 
17705   mp_obliterated(mp, q);
17706   mp->help_line[2]="While I was evaluating the suffix of this variable,";
17707   mp->help_line[1]="something was redefined, and it's no longer a variable!";
17708   mp->help_line[0]="In order to get back on my feet, I've inserted `0' instead.";
17709   mp_put_get_flush_error(mp, 0);
17710 }
17711 mp_flush_node_list(mp, q); 
17712 goto DONE
17713
17714 @ The only complication associated with macro calling is that the prefix
17715 and ``at'' parameters must be packaged in an appropriate list of lists.
17716
17717 @<Set up unsuffixed macro call and |goto restart|@>=
17718
17719   p=mp_get_avail(mp); info(pre_head)=link(pre_head); link(pre_head)=p;
17720   info(p)=t; mp_macro_call(mp, value(q),pre_head,null);
17721   mp_get_x_next(mp); 
17722   goto RESTART;
17723 }
17724
17725 @ If the ``variable'' that turned out to be a suffixed macro no longer exists,
17726 we don't care, because we have reserved a pointer (|macro_ref|) to its
17727 token list.
17728
17729 @<Set up suffixed macro call and |goto restart|@>=
17730
17731   mp_back_input(mp); p=mp_get_avail(mp); q=link(post_head);
17732   info(pre_head)=link(pre_head); link(pre_head)=post_head;
17733   info(post_head)=q; link(post_head)=p; info(p)=link(q); link(q)=null;
17734   mp_macro_call(mp, macro_ref,pre_head,null); decr(ref_count(macro_ref));
17735   mp_get_x_next(mp); goto RESTART;
17736 }
17737
17738 @ Our remaining job is simply to make a copy of the value that has been
17739 found. Some cases are harder than others, but complexity arises solely
17740 because of the multiplicity of possible cases.
17741
17742 @<Declare the procedure called |make_exp_copy|@>=
17743 @<Declare subroutines needed by |make_exp_copy|@>;
17744 void mp_make_exp_copy (MP mp,pointer p) {
17745   pointer q,r,t; /* registers for list manipulation */
17746 RESTART: 
17747   mp->cur_type=type(p);
17748   switch (mp->cur_type) {
17749   case mp_vacuous: case mp_boolean_type: case mp_known:
17750     mp->cur_exp=value(p); break;
17751   case unknown_types:
17752     mp->cur_exp=mp_new_ring_entry(mp, p);
17753     break;
17754   case mp_string_type: 
17755     mp->cur_exp=value(p); add_str_ref(mp->cur_exp);
17756     break;
17757   case mp_picture_type:
17758     mp->cur_exp=value(p);add_edge_ref(mp->cur_exp);
17759     break;
17760   case mp_pen_type:
17761     mp->cur_exp=copy_pen(value(p));
17762     break; 
17763   case mp_path_type:
17764     mp->cur_exp=mp_copy_path(mp, value(p));
17765     break;
17766   case mp_transform_type: case mp_color_type: 
17767   case mp_cmykcolor_type: case mp_pair_type:
17768     @<Copy the big node |p|@>;
17769     break;
17770   case mp_dependent: case mp_proto_dependent:
17771     mp_encapsulate(mp, mp_copy_dep_list(mp, dep_list(p)));
17772     break;
17773   case mp_numeric_type: 
17774     new_indep(p); goto RESTART;
17775     break;
17776   case mp_independent: 
17777     q=mp_single_dependency(mp, p);
17778     if ( q==mp->dep_final ){ 
17779       mp->cur_type=mp_known; mp->cur_exp=0; mp_free_node(mp, q,value_node_size);
17780     } else { 
17781       mp->cur_type=mp_dependent; mp_encapsulate(mp, q);
17782     }
17783     break;
17784   default: 
17785     mp_confusion(mp, "copy");
17786 @:this can't happen copy}{\quad copy@>
17787     break;
17788   }
17789 }
17790
17791 @ The |encapsulate| subroutine assumes that |dep_final| is the
17792 tail of dependency list~|p|.
17793
17794 @<Declare subroutines needed by |make_exp_copy|@>=
17795 void mp_encapsulate (MP mp,pointer p) { 
17796   mp->cur_exp=mp_get_node(mp, value_node_size); type(mp->cur_exp)=mp->cur_type;
17797   name_type(mp->cur_exp)=mp_capsule; mp_new_dep(mp, mp->cur_exp,p);
17798 }
17799
17800 @ The most tedious case arises when the user refers to a
17801 \&{pair}, \&{color}, or \&{transform} variable; we must copy several fields,
17802 each of which can be |independent|, |dependent|, |mp_proto_dependent|,
17803 or |known|.
17804
17805 @<Copy the big node |p|@>=
17806
17807   if ( value(p)==null ) 
17808     mp_init_big_node(mp, p);
17809   t=mp_get_node(mp, value_node_size); name_type(t)=mp_capsule; type(t)=mp->cur_type;
17810   mp_init_big_node(mp, t);
17811   q=value(p)+mp->big_node_size[mp->cur_type]; 
17812   r=value(t)+mp->big_node_size[mp->cur_type];
17813   do {  
17814     q=q-2; r=r-2; mp_install(mp, r,q);
17815   } while (q!=value(p));
17816   mp->cur_exp=t;
17817 }
17818
17819 @ The |install| procedure copies a numeric field~|q| into field~|r| of
17820 a big node that will be part of a capsule.
17821
17822 @<Declare subroutines needed by |make_exp_copy|@>=
17823 void mp_install (MP mp,pointer r, pointer q) {
17824   pointer p; /* temporary register */
17825   if ( type(q)==mp_known ){ 
17826     value(r)=value(q); type(r)=mp_known;
17827   } else  if ( type(q)==mp_independent ) {
17828     p=mp_single_dependency(mp, q);
17829     if ( p==mp->dep_final ) {
17830       type(r)=mp_known; value(r)=0; mp_free_node(mp, p,value_node_size);
17831     } else  { 
17832       type(r)=mp_dependent; mp_new_dep(mp, r,p);
17833     }
17834   } else {
17835     type(r)=type(q); mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(q)));
17836   }
17837 }
17838
17839 @ Expressions of the form `\.{a[b,c]}' are converted into
17840 `\.{b+a*(c-b)}', without checking the types of \.b~or~\.c,
17841 provided that \.a is numeric.
17842
17843 @<Scan a mediation...@>=
17844
17845   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17846   if ( mp->cur_cmd!=comma ) {
17847     @<Put the left bracket and the expression back...@>;
17848     mp_unstash_cur_exp(mp, p);
17849   } else { 
17850     q=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17851     if ( mp->cur_cmd!=right_bracket ) {
17852       mp_missing_err(mp, "]");
17853 @.Missing `]'@>
17854       help3("I've scanned an expression of the form `a[b,c',")
17855       ("so a right bracket should have come next.")
17856       ("I shall pretend that one was there.");
17857       mp_back_error(mp);
17858     }
17859     r=mp_stash_cur_exp(mp); mp_make_exp_copy(mp, q);
17860     mp_do_binary(mp, r,minus); mp_do_binary(mp, p,times); 
17861     mp_do_binary(mp, q,plus); mp_get_x_next(mp);
17862   }
17863 }
17864
17865 @ Here is a comparatively simple routine that is used to scan the
17866 \&{suffix} parameters of a macro.
17867
17868 @<Declare the basic parsing subroutines@>=
17869 void mp_scan_suffix (MP mp) {
17870   pointer h,t; /* head and tail of the list being built */
17871   pointer p; /* temporary register */
17872   h=mp_get_avail(mp); t=h;
17873   while (1) { 
17874     if ( mp->cur_cmd==left_bracket ) {
17875       @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>;
17876     }
17877     if ( mp->cur_cmd==numeric_token ) {
17878       p=mp_new_num_tok(mp, mp->cur_mod);
17879     } else if ((mp->cur_cmd==tag_token)||(mp->cur_cmd==internal_quantity) ) {
17880        p=mp_get_avail(mp); info(p)=mp->cur_sym;
17881     } else {
17882       break;
17883     }
17884     link(t)=p; t=p; mp_get_x_next(mp);
17885   }
17886   mp->cur_exp=link(h); free_avail(h); mp->cur_type=mp_token_list;
17887 }
17888
17889 @ @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>=
17890
17891   mp_get_x_next(mp); mp_scan_expression(mp);
17892   if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17893   if ( mp->cur_cmd!=right_bracket ) {
17894      mp_missing_err(mp, "]");
17895 @.Missing `]'@>
17896     help3("I've seen a `[' and a subscript value, in a suffix,")
17897       ("so a right bracket should have come next.")
17898       ("I shall pretend that one was there.");
17899     mp_back_error(mp);
17900   }
17901   mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp;
17902 }
17903
17904 @* \[38] Parsing secondary and higher expressions.
17905 After the intricacies of |scan_primary|\kern-1pt,
17906 the |scan_secondary| routine is
17907 refreshingly simple. It's not trivial, but the operations are relatively
17908 straightforward; the main difficulty is, again, that expressions and data
17909 structures might change drastically every time we call |get_x_next|, so a
17910 cautious approach is mandatory. For example, a macro defined by
17911 \&{primarydef} might have disappeared by the time its second argument has
17912 been scanned; we solve this by increasing the reference count of its token
17913 list, so that the macro can be called even after it has been clobbered.
17914
17915 @<Declare the basic parsing subroutines@>=
17916 void mp_scan_secondary (MP mp) {
17917   pointer p; /* for list manipulation */
17918   halfword c,d; /* operation codes or modifiers */
17919   pointer mac_name; /* token defined with \&{primarydef} */
17920 RESTART:
17921   if ((mp->cur_cmd<min_primary_command)||
17922       (mp->cur_cmd>max_primary_command) )
17923     mp_bad_exp(mp, "A secondary");
17924 @.A secondary expression...@>
17925   mp_scan_primary(mp);
17926 CONTINUE: 
17927   if ( mp->cur_cmd<=max_secondary_command )
17928     if ( mp->cur_cmd>=min_secondary_command ) {
17929       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17930       if ( d==secondary_primary_macro ) { 
17931         mac_name=mp->cur_sym; add_mac_ref(c);
17932      }
17933      mp_get_x_next(mp); mp_scan_primary(mp);
17934      if ( d!=secondary_primary_macro ) {
17935        mp_do_binary(mp, p,c);
17936      } else  { 
17937        mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17938        decr(ref_count(c)); mp_get_x_next(mp); 
17939        goto RESTART;
17940     }
17941     goto CONTINUE;
17942   }
17943 }
17944
17945 @ The following procedure calls a macro that has two parameters,
17946 |p| and |cur_exp|.
17947
17948 @c void mp_binary_mac (MP mp,pointer p, pointer c, pointer n) {
17949   pointer q,r; /* nodes in the parameter list */
17950   q=mp_get_avail(mp); r=mp_get_avail(mp); link(q)=r;
17951   info(q)=p; info(r)=mp_stash_cur_exp(mp);
17952   mp_macro_call(mp, c,q,n);
17953 }
17954
17955 @ The next procedure, |scan_tertiary|, is pretty much the same deal.
17956
17957 @<Declare the basic parsing subroutines@>=
17958 void mp_scan_tertiary (MP mp) {
17959   pointer p; /* for list manipulation */
17960   halfword c,d; /* operation codes or modifiers */
17961   pointer mac_name; /* token defined with \&{secondarydef} */
17962 RESTART:
17963   if ((mp->cur_cmd<min_primary_command)||
17964       (mp->cur_cmd>max_primary_command) )
17965     mp_bad_exp(mp, "A tertiary");
17966 @.A tertiary expression...@>
17967   mp_scan_secondary(mp);
17968 CONTINUE: 
17969   if ( mp->cur_cmd<=max_tertiary_command ) {
17970     if ( mp->cur_cmd>=min_tertiary_command ) {
17971       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17972       if ( d==tertiary_secondary_macro ) { 
17973         mac_name=mp->cur_sym; add_mac_ref(c);
17974       };
17975       mp_get_x_next(mp); mp_scan_secondary(mp);
17976       if ( d!=tertiary_secondary_macro ) {
17977         mp_do_binary(mp, p,c);
17978       } else { 
17979         mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17980         decr(ref_count(c)); mp_get_x_next(mp); 
17981         goto RESTART;
17982       }
17983       goto CONTINUE;
17984     }
17985   }
17986 }
17987
17988 @ Finally we reach the deepest level in our quartet of parsing routines.
17989 This one is much like the others; but it has an extra complication from
17990 paths, which materialize here.
17991
17992 @d continue_path 25 /* a label inside of |scan_expression| */
17993 @d finish_path 26 /* another */
17994
17995 @<Declare the basic parsing subroutines@>=
17996 void mp_scan_expression (MP mp) {
17997   pointer p,q,r,pp,qq; /* for list manipulation */
17998   halfword c,d; /* operation codes or modifiers */
17999   int my_var_flag; /* initial value of |var_flag| */
18000   pointer mac_name; /* token defined with \&{tertiarydef} */
18001   boolean cycle_hit; /* did a path expression just end with `\&{cycle}'? */
18002   scaled x,y; /* explicit coordinates or tension at a path join */
18003   int t; /* knot type following a path join */
18004   t=0; y=0; x=0;
18005   my_var_flag=mp->var_flag; mac_name=null;
18006 RESTART:
18007   if ((mp->cur_cmd<min_primary_command)||
18008       (mp->cur_cmd>max_primary_command) )
18009     mp_bad_exp(mp, "An");
18010 @.An expression...@>
18011   mp_scan_tertiary(mp);
18012 CONTINUE: 
18013   if ( mp->cur_cmd<=max_expression_command )
18014     if ( mp->cur_cmd>=min_expression_command ) {
18015       if ( (mp->cur_cmd!=equals)||(my_var_flag!=assignment) ) {
18016         p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
18017         if ( d==expression_tertiary_macro ) {
18018           mac_name=mp->cur_sym; add_mac_ref(c);
18019         }
18020         if ( (d<ampersand)||((d==ampersand)&&
18021              ((type(p)==mp_pair_type)||(type(p)==mp_path_type))) ) {
18022           @<Scan a path construction operation;
18023             but |return| if |p| has the wrong type@>;
18024         } else { 
18025           mp_get_x_next(mp); mp_scan_tertiary(mp);
18026           if ( d!=expression_tertiary_macro ) {
18027             mp_do_binary(mp, p,c);
18028           } else  { 
18029             mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
18030             decr(ref_count(c)); mp_get_x_next(mp); 
18031             goto RESTART;
18032           }
18033         }
18034         goto CONTINUE;
18035      }
18036   }
18037 }
18038
18039 @ The reader should review the data structure conventions for paths before
18040 hoping to understand the next part of this code.
18041
18042 @<Scan a path construction operation...@>=
18043
18044   cycle_hit=false;
18045   @<Convert the left operand, |p|, into a partial path ending at~|q|;
18046     but |return| if |p| doesn't have a suitable type@>;
18047 CONTINUE_PATH: 
18048   @<Determine the path join parameters;
18049     but |goto finish_path| if there's only a direction specifier@>;
18050   if ( mp->cur_cmd==cycle ) {
18051     @<Get ready to close a cycle@>;
18052   } else { 
18053     mp_scan_tertiary(mp);
18054     @<Convert the right operand, |cur_exp|,
18055       into a partial path from |pp| to~|qq|@>;
18056   }
18057   @<Join the partial paths and reset |p| and |q| to the head and tail
18058     of the result@>;
18059   if ( mp->cur_cmd>=min_expression_command )
18060     if ( mp->cur_cmd<=ampersand ) if ( ! cycle_hit ) goto CONTINUE_PATH;
18061 FINISH_PATH:
18062   @<Choose control points for the path and put the result into |cur_exp|@>;
18063 }
18064
18065 @ @<Convert the left operand, |p|, into a partial path ending at~|q|...@>=
18066
18067   mp_unstash_cur_exp(mp, p);
18068   if ( mp->cur_type==mp_pair_type ) p=mp_new_knot(mp);
18069   else if ( mp->cur_type==mp_path_type ) p=mp->cur_exp;
18070   else return;
18071   q=p;
18072   while ( link(q)!=p ) q=link(q);
18073   if ( left_type(p)!=mp_endpoint ) { /* open up a cycle */
18074     r=mp_copy_knot(mp, p); link(q)=r; q=r;
18075   }
18076   left_type(p)=mp_open; right_type(q)=mp_open;
18077 }
18078
18079 @ A pair of numeric values is changed into a knot node for a one-point path
18080 when \MP\ discovers that the pair is part of a path.
18081
18082 @c@<Declare the procedure called |known_pair|@>;
18083 pointer mp_new_knot (MP mp) { /* convert a pair to a knot with two endpoints */
18084   pointer q; /* the new node */
18085   q=mp_get_node(mp, knot_node_size); left_type(q)=mp_endpoint;
18086   right_type(q)=mp_endpoint; originator(q)=mp_metapost_user; link(q)=q;
18087   mp_known_pair(mp); x_coord(q)=mp->cur_x; y_coord(q)=mp->cur_y;
18088   return q;
18089 }
18090
18091 @ The |known_pair| subroutine sets |cur_x| and |cur_y| to the components
18092 of the current expression, assuming that the current expression is a
18093 pair of known numerics. Unknown components are zeroed, and the
18094 current expression is flushed.
18095
18096 @<Declare the procedure called |known_pair|@>=
18097 void mp_known_pair (MP mp) {
18098   pointer p; /* the pair node */
18099   if ( mp->cur_type!=mp_pair_type ) {
18100     exp_err("Undefined coordinates have been replaced by (0,0)");
18101 @.Undefined coordinates...@>
18102     help5("I need x and y numbers for this part of the path.")
18103       ("The value I found (see above) was no good;")
18104       ("so I'll try to keep going by using zero instead.")
18105       ("(Chapter 27 of The METAFONTbook explains that")
18106 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18107       ("you might want to type `I ??" "?' now.)");
18108     mp_put_get_flush_error(mp, 0); mp->cur_x=0; mp->cur_y=0;
18109   } else { 
18110     p=value(mp->cur_exp);
18111      @<Make sure that both |x| and |y| parts of |p| are known;
18112        copy them into |cur_x| and |cur_y|@>;
18113     mp_flush_cur_exp(mp, 0);
18114   }
18115 }
18116
18117 @ @<Make sure that both |x| and |y| parts of |p| are known...@>=
18118 if ( type(x_part_loc(p))==mp_known ) {
18119   mp->cur_x=value(x_part_loc(p));
18120 } else { 
18121   mp_disp_err(mp, x_part_loc(p),
18122     "Undefined x coordinate has been replaced by 0");
18123 @.Undefined coordinates...@>
18124   help5("I need a `known' x value for this part of the path.")
18125     ("The value I found (see above) was no good;")
18126     ("so I'll try to keep going by using zero instead.")
18127     ("(Chapter 27 of The METAFONTbook explains that")
18128 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18129     ("you might want to type `I ??" "?' now.)");
18130   mp_put_get_error(mp); mp_recycle_value(mp, x_part_loc(p)); mp->cur_x=0;
18131 }
18132 if ( type(y_part_loc(p))==mp_known ) {
18133   mp->cur_y=value(y_part_loc(p));
18134 } else { 
18135   mp_disp_err(mp, y_part_loc(p),
18136     "Undefined y coordinate has been replaced by 0");
18137   help5("I need a `known' y value for this part of the path.")
18138     ("The value I found (see above) was no good;")
18139     ("so I'll try to keep going by using zero instead.")
18140     ("(Chapter 27 of The METAFONTbook explains that")
18141     ("you might want to type `I ??" "?' now.)");
18142   mp_put_get_error(mp); mp_recycle_value(mp, y_part_loc(p)); mp->cur_y=0;
18143 }
18144
18145 @ At this point |cur_cmd| is either |ampersand|, |left_brace|, or |path_join|.
18146
18147 @<Determine the path join parameters...@>=
18148 if ( mp->cur_cmd==left_brace ) {
18149   @<Put the pre-join direction information into node |q|@>;
18150 }
18151 d=mp->cur_cmd;
18152 if ( d==path_join ) {
18153   @<Determine the tension and/or control points@>;
18154 } else if ( d!=ampersand ) {
18155   goto FINISH_PATH;
18156 }
18157 mp_get_x_next(mp);
18158 if ( mp->cur_cmd==left_brace ) {
18159   @<Put the post-join direction information into |x| and |t|@>;
18160 } else if ( right_type(q)!=mp_explicit ) {
18161   t=mp_open; x=0;
18162 }
18163
18164 @ The |scan_direction| subroutine looks at the directional information
18165 that is enclosed in braces, and also scans ahead to the following character.
18166 A type code is returned, either |open| (if the direction was $(0,0)$),
18167 or |curl| (if the direction was a curl of known value |cur_exp|), or
18168 |given| (if the direction is given by the |angle| value that now
18169 appears in |cur_exp|).
18170
18171 There's nothing difficult about this subroutine, but the program is rather
18172 lengthy because a variety of potential errors need to be nipped in the bud.
18173
18174 @c small_number mp_scan_direction (MP mp) {
18175   int t; /* the type of information found */
18176   scaled x; /* an |x| coordinate */
18177   mp_get_x_next(mp);
18178   if ( mp->cur_cmd==curl_command ) {
18179      @<Scan a curl specification@>;
18180   } else {
18181     @<Scan a given direction@>;
18182   }
18183   if ( mp->cur_cmd!=right_brace ) {
18184     mp_missing_err(mp, "}");
18185 @.Missing `\char`\}'@>
18186     help3("I've scanned a direction spec for part of a path,")
18187       ("so a right brace should have come next.")
18188       ("I shall pretend that one was there.");
18189     mp_back_error(mp);
18190   }
18191   mp_get_x_next(mp); 
18192   return t;
18193 }
18194
18195 @ @<Scan a curl specification@>=
18196 { mp_get_x_next(mp); mp_scan_expression(mp);
18197 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<0) ){ 
18198   exp_err("Improper curl has been replaced by 1");
18199 @.Improper curl@>
18200   help1("A curl must be a known, nonnegative number.");
18201   mp_put_get_flush_error(mp, unity);
18202 }
18203 t=mp_curl;
18204 }
18205
18206 @ @<Scan a given direction@>=
18207 { mp_scan_expression(mp);
18208   if ( mp->cur_type>mp_pair_type ) {
18209     @<Get given directions separated by commas@>;
18210   } else {
18211     mp_known_pair(mp);
18212   }
18213   if ( (mp->cur_x==0)&&(mp->cur_y==0) )  t=mp_open;
18214   else  { t=mp_given; mp->cur_exp=mp_n_arg(mp, mp->cur_x,mp->cur_y);}
18215 }
18216
18217 @ @<Get given directions separated by commas@>=
18218
18219   if ( mp->cur_type!=mp_known ) {
18220     exp_err("Undefined x coordinate has been replaced by 0");
18221 @.Undefined coordinates...@>
18222     help5("I need a `known' x value for this part of the path.")
18223       ("The value I found (see above) was no good;")
18224       ("so I'll try to keep going by using zero instead.")
18225       ("(Chapter 27 of The METAFONTbook explains that")
18226 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18227       ("you might want to type `I ??" "?' now.)");
18228     mp_put_get_flush_error(mp, 0);
18229   }
18230   x=mp->cur_exp;
18231   if ( mp->cur_cmd!=comma ) {
18232     mp_missing_err(mp, ",");
18233 @.Missing `,'@>
18234     help2("I've got the x coordinate of a path direction;")
18235       ("will look for the y coordinate next.");
18236     mp_back_error(mp);
18237   }
18238   mp_get_x_next(mp); mp_scan_expression(mp);
18239   if ( mp->cur_type!=mp_known ) {
18240      exp_err("Undefined y coordinate has been replaced by 0");
18241     help5("I need a `known' y value for this part of the path.")
18242       ("The value I found (see above) was no good;")
18243       ("so I'll try to keep going by using zero instead.")
18244       ("(Chapter 27 of The METAFONTbook explains that")
18245       ("you might want to type `I ??" "?' now.)");
18246     mp_put_get_flush_error(mp, 0);
18247   }
18248   mp->cur_y=mp->cur_exp; mp->cur_x=x;
18249 }
18250
18251 @ At this point |right_type(q)| is usually |open|, but it may have been
18252 set to some other value by a previous splicing operation. We must maintain
18253 the value of |right_type(q)| in unusual cases such as
18254 `\.{..z1\{z2\}\&\{z3\}z1\{0,0\}..}'.
18255
18256 @<Put the pre-join...@>=
18257
18258   t=mp_scan_direction(mp);
18259   if ( t!=mp_open ) {
18260     right_type(q)=t; right_given(q)=mp->cur_exp;
18261     if ( left_type(q)==mp_open ) {
18262       left_type(q)=t; left_given(q)=mp->cur_exp;
18263     } /* note that |left_given(q)=left_curl(q)| */
18264   }
18265 }
18266
18267 @ Since |left_tension| and |left_y| share the same position in knot nodes,
18268 and since |left_given| is similarly equivalent to |left_x|, we use
18269 |x| and |y| to hold the given direction and tension information when
18270 there are no explicit control points.
18271
18272 @<Put the post-join...@>=
18273
18274   t=mp_scan_direction(mp);
18275   if ( right_type(q)!=mp_explicit ) x=mp->cur_exp;
18276   else t=mp_explicit; /* the direction information is superfluous */
18277 }
18278
18279 @ @<Determine the tension and/or...@>=
18280
18281   mp_get_x_next(mp);
18282   if ( mp->cur_cmd==tension ) {
18283     @<Set explicit tensions@>;
18284   } else if ( mp->cur_cmd==controls ) {
18285     @<Set explicit control points@>;
18286   } else  { 
18287     right_tension(q)=unity; y=unity; mp_back_input(mp); /* default tension */
18288     goto DONE;
18289   };
18290   if ( mp->cur_cmd!=path_join ) {
18291      mp_missing_err(mp, "..");
18292 @.Missing `..'@>
18293     help1("A path join command should end with two dots.");
18294     mp_back_error(mp);
18295   }
18296 DONE:
18297   ;
18298 }
18299
18300 @ @<Set explicit tensions@>=
18301
18302   mp_get_x_next(mp); y=mp->cur_cmd;
18303   if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18304   mp_scan_primary(mp);
18305   @<Make sure that the current expression is a valid tension setting@>;
18306   if ( y==at_least ) negate(mp->cur_exp);
18307   right_tension(q)=mp->cur_exp;
18308   if ( mp->cur_cmd==and_command ) {
18309     mp_get_x_next(mp); y=mp->cur_cmd;
18310     if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18311     mp_scan_primary(mp);
18312     @<Make sure that the current expression is a valid tension setting@>;
18313     if ( y==at_least ) negate(mp->cur_exp);
18314   }
18315   y=mp->cur_exp;
18316 }
18317
18318 @ @d min_tension three_quarter_unit
18319
18320 @<Make sure that the current expression is a valid tension setting@>=
18321 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<min_tension) ) {
18322   exp_err("Improper tension has been set to 1");
18323 @.Improper tension@>
18324   help1("The expression above should have been a number >=3/4.");
18325   mp_put_get_flush_error(mp, unity);
18326 }
18327
18328 @ @<Set explicit control points@>=
18329
18330   right_type(q)=mp_explicit; t=mp_explicit; mp_get_x_next(mp); mp_scan_primary(mp);
18331   mp_known_pair(mp); right_x(q)=mp->cur_x; right_y(q)=mp->cur_y;
18332   if ( mp->cur_cmd!=and_command ) {
18333     x=right_x(q); y=right_y(q);
18334   } else { 
18335     mp_get_x_next(mp); mp_scan_primary(mp);
18336     mp_known_pair(mp); x=mp->cur_x; y=mp->cur_y;
18337   }
18338 }
18339
18340 @ @<Convert the right operand, |cur_exp|, into a partial path...@>=
18341
18342   if ( mp->cur_type!=mp_path_type ) pp=mp_new_knot(mp);
18343   else pp=mp->cur_exp;
18344   qq=pp;
18345   while ( link(qq)!=pp ) qq=link(qq);
18346   if ( left_type(pp)!=mp_endpoint ) { /* open up a cycle */
18347     r=mp_copy_knot(mp, pp); link(qq)=r; qq=r;
18348   }
18349   left_type(pp)=mp_open; right_type(qq)=mp_open;
18350 }
18351
18352 @ If a person tries to define an entire path by saying `\.{(x,y)\&cycle}',
18353 we silently change the specification to `\.{(x,y)..cycle}', since a cycle
18354 shouldn't have length zero.
18355
18356 @<Get ready to close a cycle@>=
18357
18358   cycle_hit=true; mp_get_x_next(mp); pp=p; qq=p;
18359   if ( d==ampersand ) if ( p==q ) {
18360     d=path_join; right_tension(q)=unity; y=unity;
18361   }
18362 }
18363
18364 @ @<Join the partial paths and reset |p| and |q|...@>=
18365
18366 if ( d==ampersand ) {
18367   if ( (x_coord(q)!=x_coord(pp))||(y_coord(q)!=y_coord(pp)) ) {
18368     print_err("Paths don't touch; `&' will be changed to `..'");
18369 @.Paths don't touch@>
18370     help3("When you join paths `p&q', the ending point of p")
18371       ("must be exactly equal to the starting point of q.")
18372       ("So I'm going to pretend that you said `p..q' instead.");
18373     mp_put_get_error(mp); d=path_join; right_tension(q)=unity; y=unity;
18374   }
18375 }
18376 @<Plug an opening in |right_type(pp)|, if possible@>;
18377 if ( d==ampersand ) {
18378   @<Splice independent paths together@>;
18379 } else  { 
18380   @<Plug an opening in |right_type(q)|, if possible@>;
18381   link(q)=pp; left_y(pp)=y;
18382   if ( t!=mp_open ) { left_x(pp)=x; left_type(pp)=t;  };
18383 }
18384 q=qq;
18385 }
18386
18387 @ @<Plug an opening in |right_type(q)|...@>=
18388 if ( right_type(q)==mp_open ) {
18389   if ( (left_type(q)==mp_curl)||(left_type(q)==mp_given) ) {
18390     right_type(q)=left_type(q); right_given(q)=left_given(q);
18391   }
18392 }
18393
18394 @ @<Plug an opening in |right_type(pp)|...@>=
18395 if ( right_type(pp)==mp_open ) {
18396   if ( (t==mp_curl)||(t==mp_given) ) {
18397     right_type(pp)=t; right_given(pp)=x;
18398   }
18399 }
18400
18401 @ @<Splice independent paths together@>=
18402
18403   if ( left_type(q)==mp_open ) if ( right_type(q)==mp_open ) {
18404     left_type(q)=mp_curl; left_curl(q)=unity;
18405   }
18406   if ( right_type(pp)==mp_open ) if ( t==mp_open ) {
18407     right_type(pp)=mp_curl; right_curl(pp)=unity;
18408   }
18409   right_type(q)=right_type(pp); link(q)=link(pp);
18410   right_x(q)=right_x(pp); right_y(q)=right_y(pp);
18411   mp_free_node(mp, pp,knot_node_size);
18412   if ( qq==pp ) qq=q;
18413 }
18414
18415 @ @<Choose control points for the path...@>=
18416 if ( cycle_hit ) { 
18417   if ( d==ampersand ) p=q;
18418 } else  { 
18419   left_type(p)=mp_endpoint;
18420   if ( right_type(p)==mp_open ) { 
18421     right_type(p)=mp_curl; right_curl(p)=unity;
18422   }
18423   right_type(q)=mp_endpoint;
18424   if ( left_type(q)==mp_open ) { 
18425     left_type(q)=mp_curl; left_curl(q)=unity;
18426   }
18427   link(q)=p;
18428 }
18429 mp_make_choices(mp, p);
18430 mp->cur_type=mp_path_type; mp->cur_exp=p
18431
18432 @ Finally, we sometimes need to scan an expression whose value is
18433 supposed to be either |true_code| or |false_code|.
18434
18435 @<Declare the basic parsing subroutines@>=
18436 void mp_get_boolean (MP mp) { 
18437   mp_get_x_next(mp); mp_scan_expression(mp);
18438   if ( mp->cur_type!=mp_boolean_type ) {
18439     exp_err("Undefined condition will be treated as `false'");
18440 @.Undefined condition...@>
18441     help2("The expression shown above should have had a definite")
18442       ("true-or-false value. I'm changing it to `false'.");
18443     mp_put_get_flush_error(mp, false_code); mp->cur_type=mp_boolean_type;
18444   }
18445 }
18446
18447 @* \[39] Doing the operations.
18448 The purpose of parsing is primarily to permit people to avoid piles of
18449 parentheses. But the real work is done after the structure of an expression
18450 has been recognized; that's when new expressions are generated. We
18451 turn now to the guts of \MP, which handles individual operators that
18452 have come through the parsing mechanism.
18453
18454 We'll start with the easy ones that take no operands, then work our way
18455 up to operators with one and ultimately two arguments. In other words,
18456 we will write the three procedures |do_nullary|, |do_unary|, and |do_binary|
18457 that are invoked periodically by the expression scanners.
18458
18459 First let's make sure that all of the primitive operators are in the
18460 hash table. Although |scan_primary| and its relatives made use of the
18461 \\{cmd} code for these operators, the \\{do} routines base everything
18462 on the \\{mod} code. For example, |do_binary| doesn't care whether the
18463 operation it performs is a |primary_binary| or |secondary_binary|, etc.
18464
18465 @<Put each...@>=
18466 mp_primitive(mp, "true",nullary,true_code);
18467 @:true_}{\&{true} primitive@>
18468 mp_primitive(mp, "false",nullary,false_code);
18469 @:false_}{\&{false} primitive@>
18470 mp_primitive(mp, "nullpicture",nullary,null_picture_code);
18471 @:null_picture_}{\&{nullpicture} primitive@>
18472 mp_primitive(mp, "nullpen",nullary,null_pen_code);
18473 @:null_pen_}{\&{nullpen} primitive@>
18474 mp_primitive(mp, "jobname",nullary,job_name_op);
18475 @:job_name_}{\&{jobname} primitive@>
18476 mp_primitive(mp, "readstring",nullary,read_string_op);
18477 @:read_string_}{\&{readstring} primitive@>
18478 mp_primitive(mp, "pencircle",nullary,pen_circle);
18479 @:pen_circle_}{\&{pencircle} primitive@>
18480 mp_primitive(mp, "normaldeviate",nullary,normal_deviate);
18481 @:normal_deviate_}{\&{normaldeviate} primitive@>
18482 mp_primitive(mp, "readfrom",unary,read_from_op);
18483 @:read_from_}{\&{readfrom} primitive@>
18484 mp_primitive(mp, "closefrom",unary,close_from_op);
18485 @:close_from_}{\&{closefrom} primitive@>
18486 mp_primitive(mp, "odd",unary,odd_op);
18487 @:odd_}{\&{odd} primitive@>
18488 mp_primitive(mp, "known",unary,known_op);
18489 @:known_}{\&{known} primitive@>
18490 mp_primitive(mp, "unknown",unary,unknown_op);
18491 @:unknown_}{\&{unknown} primitive@>
18492 mp_primitive(mp, "not",unary,not_op);
18493 @:not_}{\&{not} primitive@>
18494 mp_primitive(mp, "decimal",unary,decimal);
18495 @:decimal_}{\&{decimal} primitive@>
18496 mp_primitive(mp, "reverse",unary,reverse);
18497 @:reverse_}{\&{reverse} primitive@>
18498 mp_primitive(mp, "makepath",unary,make_path_op);
18499 @:make_path_}{\&{makepath} primitive@>
18500 mp_primitive(mp, "makepen",unary,make_pen_op);
18501 @:make_pen_}{\&{makepen} primitive@>
18502 mp_primitive(mp, "oct",unary,oct_op);
18503 @:oct_}{\&{oct} primitive@>
18504 mp_primitive(mp, "hex",unary,hex_op);
18505 @:hex_}{\&{hex} primitive@>
18506 mp_primitive(mp, "ASCII",unary,ASCII_op);
18507 @:ASCII_}{\&{ASCII} primitive@>
18508 mp_primitive(mp, "char",unary,char_op);
18509 @:char_}{\&{char} primitive@>
18510 mp_primitive(mp, "length",unary,length_op);
18511 @:length_}{\&{length} primitive@>
18512 mp_primitive(mp, "turningnumber",unary,turning_op);
18513 @:turning_number_}{\&{turningnumber} primitive@>
18514 mp_primitive(mp, "xpart",unary,x_part);
18515 @:x_part_}{\&{xpart} primitive@>
18516 mp_primitive(mp, "ypart",unary,y_part);
18517 @:y_part_}{\&{ypart} primitive@>
18518 mp_primitive(mp, "xxpart",unary,xx_part);
18519 @:xx_part_}{\&{xxpart} primitive@>
18520 mp_primitive(mp, "xypart",unary,xy_part);
18521 @:xy_part_}{\&{xypart} primitive@>
18522 mp_primitive(mp, "yxpart",unary,yx_part);
18523 @:yx_part_}{\&{yxpart} primitive@>
18524 mp_primitive(mp, "yypart",unary,yy_part);
18525 @:yy_part_}{\&{yypart} primitive@>
18526 mp_primitive(mp, "redpart",unary,red_part);
18527 @:red_part_}{\&{redpart} primitive@>
18528 mp_primitive(mp, "greenpart",unary,green_part);
18529 @:green_part_}{\&{greenpart} primitive@>
18530 mp_primitive(mp, "bluepart",unary,blue_part);
18531 @:blue_part_}{\&{bluepart} primitive@>
18532 mp_primitive(mp, "cyanpart",unary,cyan_part);
18533 @:cyan_part_}{\&{cyanpart} primitive@>
18534 mp_primitive(mp, "magentapart",unary,magenta_part);
18535 @:magenta_part_}{\&{magentapart} primitive@>
18536 mp_primitive(mp, "yellowpart",unary,yellow_part);
18537 @:yellow_part_}{\&{yellowpart} primitive@>
18538 mp_primitive(mp, "blackpart",unary,black_part);
18539 @:black_part_}{\&{blackpart} primitive@>
18540 mp_primitive(mp, "greypart",unary,grey_part);
18541 @:grey_part_}{\&{greypart} primitive@>
18542 mp_primitive(mp, "colormodel",unary,color_model_part);
18543 @:color_model_part_}{\&{colormodel} primitive@>
18544 mp_primitive(mp, "fontpart",unary,font_part);
18545 @:font_part_}{\&{fontpart} primitive@>
18546 mp_primitive(mp, "textpart",unary,text_part);
18547 @:text_part_}{\&{textpart} primitive@>
18548 mp_primitive(mp, "pathpart",unary,path_part);
18549 @:path_part_}{\&{pathpart} primitive@>
18550 mp_primitive(mp, "penpart",unary,pen_part);
18551 @:pen_part_}{\&{penpart} primitive@>
18552 mp_primitive(mp, "dashpart",unary,dash_part);
18553 @:dash_part_}{\&{dashpart} primitive@>
18554 mp_primitive(mp, "sqrt",unary,sqrt_op);
18555 @:sqrt_}{\&{sqrt} primitive@>
18556 mp_primitive(mp, "mexp",unary,m_exp_op);
18557 @:m_exp_}{\&{mexp} primitive@>
18558 mp_primitive(mp, "mlog",unary,m_log_op);
18559 @:m_log_}{\&{mlog} primitive@>
18560 mp_primitive(mp, "sind",unary,sin_d_op);
18561 @:sin_d_}{\&{sind} primitive@>
18562 mp_primitive(mp, "cosd",unary,cos_d_op);
18563 @:cos_d_}{\&{cosd} primitive@>
18564 mp_primitive(mp, "floor",unary,floor_op);
18565 @:floor_}{\&{floor} primitive@>
18566 mp_primitive(mp, "uniformdeviate",unary,uniform_deviate);
18567 @:uniform_deviate_}{\&{uniformdeviate} primitive@>
18568 mp_primitive(mp, "charexists",unary,char_exists_op);
18569 @:char_exists_}{\&{charexists} primitive@>
18570 mp_primitive(mp, "fontsize",unary,font_size);
18571 @:font_size_}{\&{fontsize} primitive@>
18572 mp_primitive(mp, "llcorner",unary,ll_corner_op);
18573 @:ll_corner_}{\&{llcorner} primitive@>
18574 mp_primitive(mp, "lrcorner",unary,lr_corner_op);
18575 @:lr_corner_}{\&{lrcorner} primitive@>
18576 mp_primitive(mp, "ulcorner",unary,ul_corner_op);
18577 @:ul_corner_}{\&{ulcorner} primitive@>
18578 mp_primitive(mp, "urcorner",unary,ur_corner_op);
18579 @:ur_corner_}{\&{urcorner} primitive@>
18580 mp_primitive(mp, "arclength",unary,arc_length);
18581 @:arc_length_}{\&{arclength} primitive@>
18582 mp_primitive(mp, "angle",unary,angle_op);
18583 @:angle_}{\&{angle} primitive@>
18584 mp_primitive(mp, "cycle",cycle,cycle_op);
18585 @:cycle_}{\&{cycle} primitive@>
18586 mp_primitive(mp, "stroked",unary,stroked_op);
18587 @:stroked_}{\&{stroked} primitive@>
18588 mp_primitive(mp, "filled",unary,filled_op);
18589 @:filled_}{\&{filled} primitive@>
18590 mp_primitive(mp, "textual",unary,textual_op);
18591 @:textual_}{\&{textual} primitive@>
18592 mp_primitive(mp, "clipped",unary,clipped_op);
18593 @:clipped_}{\&{clipped} primitive@>
18594 mp_primitive(mp, "bounded",unary,bounded_op);
18595 @:bounded_}{\&{bounded} primitive@>
18596 mp_primitive(mp, "+",plus_or_minus,plus);
18597 @:+ }{\.{+} primitive@>
18598 mp_primitive(mp, "-",plus_or_minus,minus);
18599 @:- }{\.{-} primitive@>
18600 mp_primitive(mp, "*",secondary_binary,times);
18601 @:* }{\.{*} primitive@>
18602 mp_primitive(mp, "/",slash,over); mp->eqtb[frozen_slash]=mp->eqtb[mp->cur_sym];
18603 @:/ }{\.{/} primitive@>
18604 mp_primitive(mp, "++",tertiary_binary,pythag_add);
18605 @:++_}{\.{++} primitive@>
18606 mp_primitive(mp, "+-+",tertiary_binary,pythag_sub);
18607 @:+-+_}{\.{+-+} primitive@>
18608 mp_primitive(mp, "or",tertiary_binary,or_op);
18609 @:or_}{\&{or} primitive@>
18610 mp_primitive(mp, "and",and_command,and_op);
18611 @:and_}{\&{and} primitive@>
18612 mp_primitive(mp, "<",expression_binary,less_than);
18613 @:< }{\.{<} primitive@>
18614 mp_primitive(mp, "<=",expression_binary,less_or_equal);
18615 @:<=_}{\.{<=} primitive@>
18616 mp_primitive(mp, ">",expression_binary,greater_than);
18617 @:> }{\.{>} primitive@>
18618 mp_primitive(mp, ">=",expression_binary,greater_or_equal);
18619 @:>=_}{\.{>=} primitive@>
18620 mp_primitive(mp, "=",equals,equal_to);
18621 @:= }{\.{=} primitive@>
18622 mp_primitive(mp, "<>",expression_binary,unequal_to);
18623 @:<>_}{\.{<>} primitive@>
18624 mp_primitive(mp, "substring",primary_binary,substring_of);
18625 @:substring_}{\&{substring} primitive@>
18626 mp_primitive(mp, "subpath",primary_binary,subpath_of);
18627 @:subpath_}{\&{subpath} primitive@>
18628 mp_primitive(mp, "directiontime",primary_binary,direction_time_of);
18629 @:direction_time_}{\&{directiontime} primitive@>
18630 mp_primitive(mp, "point",primary_binary,point_of);
18631 @:point_}{\&{point} primitive@>
18632 mp_primitive(mp, "precontrol",primary_binary,precontrol_of);
18633 @:precontrol_}{\&{precontrol} primitive@>
18634 mp_primitive(mp, "postcontrol",primary_binary,postcontrol_of);
18635 @:postcontrol_}{\&{postcontrol} primitive@>
18636 mp_primitive(mp, "penoffset",primary_binary,pen_offset_of);
18637 @:pen_offset_}{\&{penoffset} primitive@>
18638 mp_primitive(mp, "arctime",primary_binary,arc_time_of);
18639 @:arc_time_of_}{\&{arctime} primitive@>
18640 mp_primitive(mp, "mpversion",nullary,mp_version);
18641 @:mp_verison_}{\&{mpversion} primitive@>
18642 mp_primitive(mp, "&",ampersand,concatenate);
18643 @:!!!}{\.{\&} primitive@>
18644 mp_primitive(mp, "rotated",secondary_binary,rotated_by);
18645 @:rotated_}{\&{rotated} primitive@>
18646 mp_primitive(mp, "slanted",secondary_binary,slanted_by);
18647 @:slanted_}{\&{slanted} primitive@>
18648 mp_primitive(mp, "scaled",secondary_binary,scaled_by);
18649 @:scaled_}{\&{scaled} primitive@>
18650 mp_primitive(mp, "shifted",secondary_binary,shifted_by);
18651 @:shifted_}{\&{shifted} primitive@>
18652 mp_primitive(mp, "transformed",secondary_binary,transformed_by);
18653 @:transformed_}{\&{transformed} primitive@>
18654 mp_primitive(mp, "xscaled",secondary_binary,x_scaled);
18655 @:x_scaled_}{\&{xscaled} primitive@>
18656 mp_primitive(mp, "yscaled",secondary_binary,y_scaled);
18657 @:y_scaled_}{\&{yscaled} primitive@>
18658 mp_primitive(mp, "zscaled",secondary_binary,z_scaled);
18659 @:z_scaled_}{\&{zscaled} primitive@>
18660 mp_primitive(mp, "infont",secondary_binary,in_font);
18661 @:in_font_}{\&{infont} primitive@>
18662 mp_primitive(mp, "intersectiontimes",tertiary_binary,intersect);
18663 @:intersection_times_}{\&{intersectiontimes} primitive@>
18664
18665 @ @<Cases of |print_cmd...@>=
18666 case nullary:
18667 case unary:
18668 case primary_binary:
18669 case secondary_binary:
18670 case tertiary_binary:
18671 case expression_binary:
18672 case cycle:
18673 case plus_or_minus:
18674 case slash:
18675 case ampersand:
18676 case equals:
18677 case and_command:
18678   mp_print_op(mp, m);
18679   break;
18680
18681 @ OK, let's look at the simplest \\{do} procedure first.
18682
18683 @c @<Declare nullary action procedure@>;
18684 void mp_do_nullary (MP mp,quarterword c) { 
18685   check_arith;
18686   if ( mp->internal[mp_tracing_commands]>two )
18687     mp_show_cmd_mod(mp, nullary,c);
18688   switch (c) {
18689   case true_code: case false_code: 
18690     mp->cur_type=mp_boolean_type; mp->cur_exp=c;
18691     break;
18692   case null_picture_code: 
18693     mp->cur_type=mp_picture_type;
18694     mp->cur_exp=mp_get_node(mp, edge_header_size); 
18695     mp_init_edges(mp, mp->cur_exp);
18696     break;
18697   case null_pen_code: 
18698     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, 0);
18699     break;
18700   case normal_deviate: 
18701     mp->cur_type=mp_known; mp->cur_exp=mp_norm_rand(mp);
18702     break;
18703   case pen_circle: 
18704     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, unity);
18705     break;
18706   case job_name_op:  
18707     if ( mp->job_name==NULL ) mp_open_log_file(mp);
18708     mp->cur_type=mp_string_type; mp->cur_exp=rts(mp->job_name);
18709     break;
18710   case mp_version: 
18711     mp->cur_type=mp_string_type; 
18712     mp->cur_exp=intern(metapost_version) ;
18713     break;
18714   case read_string_op:
18715     @<Read a string from the terminal@>;
18716     break;
18717   } /* there are no other cases */
18718   check_arith;
18719 }
18720
18721 @ @<Read a string...@>=
18722
18723   if ( mp->interaction<=mp_nonstop_mode )
18724     mp_fatal_error(mp, "*** (cannot readstring in nonstop modes)");
18725   mp_begin_file_reading(mp); name=is_read;
18726   limit=start; prompt_input("");
18727   mp_finish_read(mp);
18728 }
18729
18730 @ @<Declare nullary action procedure@>=
18731 void mp_finish_read (MP mp) { /* copy |buffer| line to |cur_exp| */
18732   size_t k;
18733   str_room((int)mp->last-start);
18734   for (k=start;k<=mp->last-1;k++) {
18735    append_char(mp->buffer[k]);
18736   }
18737   mp_end_file_reading(mp); mp->cur_type=mp_string_type; 
18738   mp->cur_exp=mp_make_string(mp);
18739 }
18740
18741 @ Things get a bit more interesting when there's an operand. The
18742 operand to |do_unary| appears in |cur_type| and |cur_exp|.
18743
18744 @c @<Declare unary action procedures@>;
18745 void mp_do_unary (MP mp,quarterword c) {
18746   pointer p,q,r; /* for list manipulation */
18747   integer x; /* a temporary register */
18748   check_arith;
18749   if ( mp->internal[mp_tracing_commands]>two )
18750     @<Trace the current unary operation@>;
18751   switch (c) {
18752   case plus:
18753     if ( mp->cur_type<mp_color_type ) mp_bad_unary(mp, plus);
18754     break;
18755   case minus:
18756     @<Negate the current expression@>;
18757     break;
18758   @<Additional cases of unary operators@>;
18759   } /* there are no other cases */
18760   check_arith;
18761 };
18762
18763 @ The |nice_pair| function returns |true| if both components of a pair
18764 are known.
18765
18766 @<Declare unary action procedures@>=
18767 boolean mp_nice_pair (MP mp,integer p, quarterword t) { 
18768   if ( t==mp_pair_type ) {
18769     p=value(p);
18770     if ( type(x_part_loc(p))==mp_known )
18771       if ( type(y_part_loc(p))==mp_known )
18772         return true;
18773   }
18774   return false;
18775 }
18776
18777 @ The |nice_color_or_pair| function is analogous except that it also accepts
18778 fully known colors.
18779
18780 @<Declare unary action procedures@>=
18781 boolean mp_nice_color_or_pair (MP mp,integer p, quarterword t) {
18782   pointer q,r; /* for scanning the big node */
18783   if ( (t!=mp_pair_type)&&(t!=mp_color_type)&&(t!=mp_cmykcolor_type) ) {
18784     return false;
18785   } else { 
18786     q=value(p);
18787     r=q+mp->big_node_size[type(p)];
18788     do {  
18789       r=r-2;
18790       if ( type(r)!=mp_known )
18791         return false;
18792     } while (r!=q);
18793     return true;
18794   }
18795 }
18796
18797 @ @<Declare unary action...@>=
18798 void mp_print_known_or_unknown_type (MP mp,small_number t, integer v) { 
18799   mp_print_char(mp, '(');
18800   if ( t>mp_known ) mp_print(mp, "unknown numeric");
18801   else { if ( (t==mp_pair_type)||(t==mp_color_type)||(t==mp_cmykcolor_type) )
18802     if ( ! mp_nice_color_or_pair(mp, v,t) ) mp_print(mp, "unknown ");
18803     mp_print_type(mp, t);
18804   }
18805   mp_print_char(mp, ')');
18806 }
18807
18808 @ @<Declare unary action...@>=
18809 void mp_bad_unary (MP mp,quarterword c) { 
18810   exp_err("Not implemented: "); mp_print_op(mp, c);
18811 @.Not implemented...@>
18812   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
18813   help3("I'm afraid I don't know how to apply that operation to that")
18814     ("particular type. Continue, and I'll simply return the")
18815     ("argument (shown above) as the result of the operation.");
18816   mp_put_get_error(mp);
18817 }
18818
18819 @ @<Trace the current unary operation@>=
18820
18821   mp_begin_diagnostic(mp); mp_print_nl(mp, "{"); 
18822   mp_print_op(mp, c); mp_print_char(mp, '(');
18823   mp_print_exp(mp, null,0); /* show the operand, but not verbosely */
18824   mp_print(mp, ")}"); mp_end_diagnostic(mp, false);
18825 }
18826
18827 @ Negation is easy except when the current expression
18828 is of type |independent|, or when it is a pair with one or more
18829 |independent| components.
18830
18831 It is tempting to argue that the negative of an independent variable
18832 is an independent variable, hence we don't have to do anything when
18833 negating it. The fallacy is that other dependent variables pointing
18834 to the current expression must change the sign of their
18835 coefficients if we make no change to the current expression.
18836
18837 Instead, we work around the problem by copying the current expression
18838 and recycling it afterwards (cf.~the |stash_in| routine).
18839
18840 @<Negate the current expression@>=
18841 switch (mp->cur_type) {
18842 case mp_color_type:
18843 case mp_cmykcolor_type:
18844 case mp_pair_type:
18845 case mp_independent: 
18846   q=mp->cur_exp; mp_make_exp_copy(mp, q);
18847   if ( mp->cur_type==mp_dependent ) {
18848     mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18849   } else if ( mp->cur_type<=mp_pair_type ) { /* |mp_color_type| or |mp_pair_type| */
18850     p=value(mp->cur_exp);
18851     r=p+mp->big_node_size[mp->cur_type];
18852     do {  
18853       r=r-2;
18854       if ( type(r)==mp_known ) negate(value(r));
18855       else mp_negate_dep_list(mp, dep_list(r));
18856     } while (r!=p);
18857   } /* if |cur_type=mp_known| then |cur_exp=0| */
18858   mp_recycle_value(mp, q); mp_free_node(mp, q,value_node_size);
18859   break;
18860 case mp_dependent:
18861 case mp_proto_dependent:
18862   mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18863   break;
18864 case mp_known:
18865   negate(mp->cur_exp);
18866   break;
18867 default:
18868   mp_bad_unary(mp, minus);
18869   break;
18870 }
18871
18872 @ @<Declare unary action...@>=
18873 void mp_negate_dep_list (MP mp,pointer p) { 
18874   while (1) { 
18875     negate(value(p));
18876     if ( info(p)==null ) return;
18877     p=link(p);
18878   }
18879 }
18880
18881 @ @<Additional cases of unary operators@>=
18882 case not_op: 
18883   if ( mp->cur_type!=mp_boolean_type ) mp_bad_unary(mp, not_op);
18884   else mp->cur_exp=true_code+false_code-mp->cur_exp;
18885   break;
18886
18887 @ @d three_sixty_units 23592960 /* that's |360*unity| */
18888 @d boolean_reset(A) if ( (A) ) mp->cur_exp=true_code; else mp->cur_exp=false_code
18889
18890 @<Additional cases of unary operators@>=
18891 case sqrt_op:
18892 case m_exp_op:
18893 case m_log_op:
18894 case sin_d_op:
18895 case cos_d_op:
18896 case floor_op:
18897 case  uniform_deviate:
18898 case odd_op:
18899 case char_exists_op:
18900   if ( mp->cur_type!=mp_known ) {
18901     mp_bad_unary(mp, c);
18902   } else {
18903     switch (c) {
18904     case sqrt_op:mp->cur_exp=mp_square_rt(mp, mp->cur_exp);break;
18905     case m_exp_op:mp->cur_exp=mp_m_exp(mp, mp->cur_exp);break;
18906     case m_log_op:mp->cur_exp=mp_m_log(mp, mp->cur_exp);break;
18907     case sin_d_op:
18908     case cos_d_op:
18909       mp_n_sin_cos(mp, (mp->cur_exp % three_sixty_units)*16);
18910       if ( c==sin_d_op ) mp->cur_exp=mp_round_fraction(mp, mp->n_sin);
18911       else mp->cur_exp=mp_round_fraction(mp, mp->n_cos);
18912       break;
18913     case floor_op:mp->cur_exp=mp_floor_scaled(mp, mp->cur_exp);break;
18914     case uniform_deviate:mp->cur_exp=mp_unif_rand(mp, mp->cur_exp);break;
18915     case odd_op: 
18916       boolean_reset(odd(mp_round_unscaled(mp, mp->cur_exp)));
18917       mp->cur_type=mp_boolean_type;
18918       break;
18919     case char_exists_op:
18920       @<Determine if a character has been shipped out@>;
18921       break;
18922     } /* there are no other cases */
18923   }
18924   break;
18925
18926 @ @<Additional cases of unary operators@>=
18927 case angle_op:
18928   if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) ) {
18929     p=value(mp->cur_exp);
18930     x=mp_n_arg(mp, value(x_part_loc(p)),value(y_part_loc(p)));
18931     if ( x>=0 ) mp_flush_cur_exp(mp, (x+8)/ 16);
18932     else mp_flush_cur_exp(mp, -((-x+8)/ 16));
18933   } else {
18934     mp_bad_unary(mp, angle_op);
18935   }
18936   break;
18937
18938 @ If the current expression is a pair, but the context wants it to
18939 be a path, we call |pair_to_path|.
18940
18941 @<Declare unary action...@>=
18942 void mp_pair_to_path (MP mp) { 
18943   mp->cur_exp=mp_new_knot(mp); 
18944   mp->cur_type=mp_path_type;
18945 };
18946
18947 @ @<Additional cases of unary operators@>=
18948 case x_part:
18949 case y_part:
18950   if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_transform_type) )
18951     mp_take_part(mp, c);
18952   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18953   else mp_bad_unary(mp, c);
18954   break;
18955 case xx_part:
18956 case xy_part:
18957 case yx_part:
18958 case yy_part: 
18959   if ( mp->cur_type==mp_transform_type ) mp_take_part(mp, c);
18960   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18961   else mp_bad_unary(mp, c);
18962   break;
18963 case red_part:
18964 case green_part:
18965 case blue_part: 
18966   if ( mp->cur_type==mp_color_type ) mp_take_part(mp, c);
18967   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18968   else mp_bad_unary(mp, c);
18969   break;
18970 case cyan_part:
18971 case magenta_part:
18972 case yellow_part:
18973 case black_part: 
18974   if ( mp->cur_type==mp_cmykcolor_type) mp_take_part(mp, c); 
18975   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18976   else mp_bad_unary(mp, c);
18977   break;
18978 case grey_part: 
18979   if ( mp->cur_type==mp_known ) mp->cur_exp=value(c);
18980   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18981   else mp_bad_unary(mp, c);
18982   break;
18983 case color_model_part: 
18984   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18985   else mp_bad_unary(mp, c);
18986   break;
18987
18988 @ In the following procedure, |cur_exp| points to a capsule, which points to
18989 a big node. We want to delete all but one part of the big node.
18990
18991 @<Declare unary action...@>=
18992 void mp_take_part (MP mp,quarterword c) {
18993   pointer p; /* the big node */
18994   p=value(mp->cur_exp); value(temp_val)=p; type(temp_val)=mp->cur_type;
18995   link(p)=temp_val; mp_free_node(mp, mp->cur_exp,value_node_size);
18996   mp_make_exp_copy(mp, p+mp->sector_offset[c+mp_x_part_sector-x_part]);
18997   mp_recycle_value(mp, temp_val);
18998 }
18999
19000 @ @<Initialize table entries...@>=
19001 name_type(temp_val)=mp_capsule;
19002
19003 @ @<Additional cases of unary operators@>=
19004 case font_part:
19005 case text_part:
19006 case path_part:
19007 case pen_part:
19008 case dash_part:
19009   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
19010   else mp_bad_unary(mp, c);
19011   break;
19012
19013 @ @<Declarations@>=
19014 void mp_scale_edges (MP mp);
19015
19016 @ @<Declare unary action...@>=
19017 void mp_take_pict_part (MP mp,quarterword c) {
19018   pointer p; /* first graphical object in |cur_exp| */
19019   p=link(dummy_loc(mp->cur_exp));
19020   if ( p!=null ) {
19021     switch (c) {
19022     case x_part: case y_part: case xx_part:
19023     case xy_part: case yx_part: case yy_part:
19024       if ( type(p)==mp_text_code ) mp_flush_cur_exp(mp, text_trans_part(p+c));
19025       else goto NOT_FOUND;
19026       break;
19027     case red_part: case green_part: case blue_part:
19028       if ( has_color(p) ) mp_flush_cur_exp(mp, obj_color_part(p+c));
19029       else goto NOT_FOUND;
19030       break;
19031     case cyan_part: case magenta_part: case yellow_part:
19032     case black_part:
19033       if ( has_color(p) ) {
19034         if ( color_model(p)==mp_uninitialized_model )
19035           mp_flush_cur_exp(mp, unity);
19036         else
19037           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-cyan_part)));
19038       } else goto NOT_FOUND;
19039       break;
19040     case grey_part:
19041       if ( has_color(p) )
19042           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-grey_part)));
19043       else goto NOT_FOUND;
19044       break;
19045     case color_model_part:
19046       if ( has_color(p) ) {
19047         if ( color_model(p)==mp_uninitialized_model )
19048           mp_flush_cur_exp(mp, mp->internal[mp_default_color_model]);
19049         else
19050           mp_flush_cur_exp(mp, color_model(p)*unity);
19051       } else goto NOT_FOUND;
19052       break;
19053     @<Handle other cases in |take_pict_part| or |goto not_found|@>;
19054     } /* all cases have been enumerated */
19055     return;
19056   };
19057 NOT_FOUND:
19058   @<Convert the current expression to a null value appropriate
19059     for |c|@>;
19060 }
19061
19062 @ @<Handle other cases in |take_pict_part| or |goto not_found|@>=
19063 case text_part: 
19064   if ( type(p)!=mp_text_code ) goto NOT_FOUND;
19065   else { 
19066     mp_flush_cur_exp(mp, text_p(p));
19067     add_str_ref(mp->cur_exp);
19068     mp->cur_type=mp_string_type;
19069     };
19070   break;
19071 case font_part: 
19072   if ( type(p)!=mp_text_code ) goto NOT_FOUND;
19073   else { 
19074     mp_flush_cur_exp(mp, rts(mp->font_name[font_n(p)])); 
19075     add_str_ref(mp->cur_exp);
19076     mp->cur_type=mp_string_type;
19077   };
19078   break;
19079 case path_part:
19080   if ( type(p)==mp_text_code ) goto NOT_FOUND;
19081   else if ( is_stop(p) ) mp_confusion(mp, "pict");
19082 @:this can't happen pict}{\quad pict@>
19083   else { 
19084     mp_flush_cur_exp(mp, mp_copy_path(mp, path_p(p)));
19085     mp->cur_type=mp_path_type;
19086   }
19087   break;
19088 case pen_part: 
19089   if ( ! has_pen(p) ) goto NOT_FOUND;
19090   else {
19091     if ( pen_p(p)==null ) goto NOT_FOUND;
19092     else { mp_flush_cur_exp(mp, copy_pen(pen_p(p)));
19093       mp->cur_type=mp_pen_type;
19094     };
19095   }
19096   break;
19097 case dash_part: 
19098   if ( type(p)!=mp_stroked_code ) goto NOT_FOUND;
19099   else { if ( dash_p(p)==null ) goto NOT_FOUND;
19100     else { add_edge_ref(dash_p(p));
19101     mp->se_sf=dash_scale(p);
19102     mp->se_pic=dash_p(p);
19103     mp_scale_edges(mp);
19104     mp_flush_cur_exp(mp, mp->se_pic);
19105     mp->cur_type=mp_picture_type;
19106     };
19107   }
19108   break;
19109
19110 @ Since |scale_edges| had to be declared |forward|, it had to be declared as a
19111 parameterless procedure even though it really takes two arguments and updates
19112 one of them.  Hence the following globals are needed.
19113
19114 @<Global...@>=
19115 pointer se_pic;  /* edge header used and updated by |scale_edges| */
19116 scaled se_sf;  /* the scale factor argument to |scale_edges| */
19117
19118 @ @<Convert the current expression to a null value appropriate...@>=
19119 switch (c) {
19120 case text_part: case font_part: 
19121   mp_flush_cur_exp(mp, rts(""));
19122   mp->cur_type=mp_string_type;
19123   break;
19124 case path_part: 
19125   mp_flush_cur_exp(mp, mp_get_node(mp, knot_node_size));
19126   left_type(mp->cur_exp)=mp_endpoint;
19127   right_type(mp->cur_exp)=mp_endpoint;
19128   link(mp->cur_exp)=mp->cur_exp;
19129   x_coord(mp->cur_exp)=0;
19130   y_coord(mp->cur_exp)=0;
19131   originator(mp->cur_exp)=mp_metapost_user;
19132   mp->cur_type=mp_path_type;
19133   break;
19134 case pen_part: 
19135   mp_flush_cur_exp(mp, mp_get_pen_circle(mp, 0));
19136   mp->cur_type=mp_pen_type;
19137   break;
19138 case dash_part: 
19139   mp_flush_cur_exp(mp, mp_get_node(mp, edge_header_size));
19140   mp_init_edges(mp, mp->cur_exp);
19141   mp->cur_type=mp_picture_type;
19142   break;
19143 default: 
19144    mp_flush_cur_exp(mp, 0);
19145   break;
19146 }
19147
19148 @ @<Additional cases of unary...@>=
19149 case char_op: 
19150   if ( mp->cur_type!=mp_known ) { 
19151     mp_bad_unary(mp, char_op);
19152   } else { 
19153     mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256; 
19154     mp->cur_type=mp_string_type;
19155     if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
19156   }
19157   break;
19158 case decimal: 
19159   if ( mp->cur_type!=mp_known ) {
19160      mp_bad_unary(mp, decimal);
19161   } else { 
19162     mp->old_setting=mp->selector; mp->selector=new_string;
19163     mp_print_scaled(mp, mp->cur_exp); mp->cur_exp=mp_make_string(mp);
19164     mp->selector=mp->old_setting; mp->cur_type=mp_string_type;
19165   }
19166   break;
19167 case oct_op:
19168 case hex_op:
19169 case ASCII_op: 
19170   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19171   else mp_str_to_num(mp, c);
19172   break;
19173 case font_size: 
19174   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, font_size);
19175   else @<Find the design size of the font whose name is |cur_exp|@>;
19176   break;
19177
19178 @ @<Declare unary action...@>=
19179 void mp_str_to_num (MP mp,quarterword c) { /* converts a string to a number */
19180   integer n; /* accumulator */
19181   ASCII_code m; /* current character */
19182   pool_pointer k; /* index into |str_pool| */
19183   int b; /* radix of conversion */
19184   boolean bad_char; /* did the string contain an invalid digit? */
19185   if ( c==ASCII_op ) {
19186     if ( length(mp->cur_exp)==0 ) n=-1;
19187     else n=mp->str_pool[mp->str_start[mp->cur_exp]];
19188   } else { 
19189     if ( c==oct_op ) b=8; else b=16;
19190     n=0; bad_char=false;
19191     for (k=mp->str_start[mp->cur_exp];k<=str_stop(mp->cur_exp)-1;k++) {
19192       m=mp->str_pool[k];
19193       if ( (m>='0')&&(m<='9') ) m=m-'0';
19194       else if ( (m>='A')&&(m<='F') ) m=m-'A'+10;
19195       else if ( (m>='a')&&(m<='f') ) m=m-'a'+10;
19196       else  { bad_char=true; m=0; };
19197       if ( m>=b ) { bad_char=true; m=0; };
19198       if ( n<32768 / b ) n=n*b+m; else n=32767;
19199     }
19200     @<Give error messages if |bad_char| or |n>=4096|@>;
19201   }
19202   mp_flush_cur_exp(mp, n*unity);
19203 }
19204
19205 @ @<Give error messages if |bad_char|...@>=
19206 if ( bad_char ) { 
19207   exp_err("String contains illegal digits");
19208 @.String contains illegal digits@>
19209   if ( c==oct_op ) {
19210     help1("I zeroed out characters that weren't in the range 0..7.");
19211   } else  {
19212     help1("I zeroed out characters that weren't hex digits.");
19213   }
19214   mp_put_get_error(mp);
19215 }
19216 if ( (n>4095) ) {
19217   if ( mp->internal[mp_warning_check]>0 ) {
19218     print_err("Number too large ("); 
19219     mp_print_int(mp, n); mp_print_char(mp, ')');
19220 @.Number too large@>
19221     help2("I have trouble with numbers greater than 4095; watch out.")
19222       ("(Set warningcheck:=0 to suppress this message.)");
19223     mp_put_get_error(mp);
19224   }
19225 }
19226
19227 @ The length operation is somewhat unusual in that it applies to a variety
19228 of different types of operands.
19229
19230 @<Additional cases of unary...@>=
19231 case length_op: 
19232   switch (mp->cur_type) {
19233   case mp_string_type: mp_flush_cur_exp(mp, length(mp->cur_exp)*unity); break;
19234   case mp_path_type: mp_flush_cur_exp(mp, mp_path_length(mp)); break;
19235   case mp_known: mp->cur_exp=abs(mp->cur_exp); break;
19236   case mp_picture_type: mp_flush_cur_exp(mp, mp_pict_length(mp)); break;
19237   default: 
19238     if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) )
19239       mp_flush_cur_exp(mp, mp_pyth_add(mp, 
19240         value(x_part_loc(value(mp->cur_exp))),
19241         value(y_part_loc(value(mp->cur_exp)))));
19242     else mp_bad_unary(mp, c);
19243     break;
19244   }
19245   break;
19246
19247 @ @<Declare unary action...@>=
19248 scaled mp_path_length (MP mp) { /* computes the length of the current path */
19249   scaled n; /* the path length so far */
19250   pointer p; /* traverser */
19251   p=mp->cur_exp;
19252   if ( left_type(p)==mp_endpoint ) n=-unity; else n=0;
19253   do {  p=link(p); n=n+unity; } while (p!=mp->cur_exp);
19254   return n;
19255 }
19256
19257 @ @<Declare unary action...@>=
19258 scaled mp_pict_length (MP mp) { 
19259   /* counts interior components in picture |cur_exp| */
19260   scaled n; /* the count so far */
19261   pointer p; /* traverser */
19262   n=0;
19263   p=link(dummy_loc(mp->cur_exp));
19264   if ( p!=null ) {
19265     if ( is_start_or_stop(p) )
19266       if ( mp_skip_1component(mp, p)==null ) p=link(p);
19267     while ( p!=null )  { 
19268       skip_component(p) return n; 
19269       n=n+unity;   
19270     }
19271   }
19272   return n;
19273 }
19274
19275 @ Implement |turningnumber|
19276
19277 @<Additional cases of unary...@>=
19278 case turning_op:
19279   if ( mp->cur_type==mp_pair_type ) mp_flush_cur_exp(mp, 0);
19280   else if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, turning_op);
19281   else if ( left_type(mp->cur_exp)==mp_endpoint )
19282      mp_flush_cur_exp(mp, 0); /* not a cyclic path */
19283   else
19284     mp_flush_cur_exp(mp, mp_turn_cycles_wrapper(mp, mp->cur_exp));
19285   break;
19286
19287 @ The function |an_angle| returns the value of the |angle| primitive, or $0$ if the
19288 argument is |origin|.
19289
19290 @<Declare unary action...@>=
19291 angle mp_an_angle (MP mp,scaled xpar, scaled ypar) {
19292   if ( (! ((xpar==0) && (ypar==0))) )
19293     return mp_n_arg(mp, xpar,ypar);
19294   return 0;
19295 }
19296
19297
19298 @ The actual turning number is (for the moment) computed in a C function
19299 that receives eight integers corresponding to the four controlling points,
19300 and returns a single angle.  Besides those, we have to account for discrete
19301 moves at the actual points.
19302
19303 @d floor(a) (a>=0 ? a : -(int)(-a))
19304 @d bezier_error (720<<20)+1
19305 @d sign(v) ((v)>0 ? 1 : ((v)<0 ? -1 : 0 ))
19306 @d print_roots(a) { if (debuglevel>(65536*2))
19307    fprintf(stdout,"bezier_slope(): %s, i=%f, o=%f, angle=%f\n", (a),in,out,res); }
19308 @d out ((double)(xo>>20))
19309 @d mid ((double)(xm>>20))
19310 @d in  ((double)(xi>>20))
19311 @d divisor (256*256)
19312 @d double2angle(a) (int)floor(a*256.0*256.0*16.0)
19313
19314 @<Declare unary action...@>=
19315 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19316             integer CX,integer CY,integer DX,integer DY, int debuglevel);
19317
19318 @ @c 
19319 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19320             integer CX,integer CY,integer DX,integer DY, int debuglevel) {
19321   double a, b, c;
19322   integer deltax,deltay;
19323   double ax,ay,bx,by,cx,cy,dx,dy;
19324   angle xi = 0, xo = 0, xm = 0;
19325   double res = 0;
19326   ax=AX/divisor;  ay=AY/divisor;
19327   bx=BX/divisor;  by=BY/divisor;
19328   cx=CX/divisor;  cy=CY/divisor;
19329   dx=DX/divisor;  dy=DY/divisor;
19330
19331   deltax = (BX-AX); deltay = (BY-AY);
19332   if (deltax==0 && deltay == 0) { deltax=(CX-AX); deltay=(CY-AY); }
19333   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19334   xi = mp_an_angle(mp,deltax,deltay);
19335
19336   deltax = (CX-BX); deltay = (CY-BY);
19337   xm = mp_an_angle(mp,deltax,deltay);
19338
19339   deltax = (DX-CX); deltay = (DY-CY);
19340   if (deltax==0 && deltay == 0) { deltax=(DX-BX); deltay=(DY-BY); }
19341   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19342   xo = mp_an_angle(mp,deltax,deltay);
19343
19344   a = (bx-ax)*(cy-by) - (cx-bx)*(by-ay); /* a = (bp-ap)x(cp-bp); */
19345   b = (bx-ax)*(dy-cy) - (by-ay)*(dx-cx);; /* b = (bp-ap)x(dp-cp);*/
19346   c = (cx-bx)*(dy-cy) - (dx-cx)*(cy-by); /* c = (cp-bp)x(dp-cp);*/
19347
19348   if (debuglevel>(65536*2)) {
19349     fprintf(stdout,
19350       "bezier_slope(): (%.2f,%.2f),(%.2f,%.2f),(%.2f,%.2f),(%.2f,%.2f)\n",
19351               ax,ay,bx,by,cx,cy,dx,dy);
19352     fprintf(stdout,
19353       "bezier_slope(): a,b,c,b^2,4ac: (%.2f,%.2f,%.2f,%.2f,%.2f)\n",a,b,c,b*b,4*a*c);
19354   }
19355
19356   if ((a==0)&&(c==0)) {
19357     res = (b==0 ?  0 :  (out-in)); 
19358     print_roots("no roots (a)");
19359   } else if ((a==0)||(c==0)) {
19360     if ((sign(b) == sign(a)) || (sign(b) == sign(c))) {
19361       res = out-in; /* ? */
19362       if (res<-180.0) 
19363         res += 360.0;
19364       else if (res>180.0)
19365         res -= 360.0;
19366       print_roots("no roots (b)");
19367     } else {
19368       res = out-in; /* ? */
19369       print_roots("one root (a)");
19370     }
19371   } else if ((sign(a)*sign(c))<0) {
19372     res = out-in; /* ? */
19373       if (res<-180.0) 
19374         res += 360.0;
19375       else if (res>180.0)
19376         res -= 360.0;
19377     print_roots("one root (b)");
19378   } else {
19379     if (sign(a) == sign(b)) {
19380       res = out-in; /* ? */
19381       if (res<-180.0) 
19382         res += 360.0;
19383       else if (res>180.0)
19384         res -= 360.0;
19385       print_roots("no roots (d)");
19386     } else {
19387       if ((b*b) == (4*a*c)) {
19388         res = bezier_error;
19389         print_roots("double root"); /* cusp */
19390       } else if ((b*b) < (4*a*c)) {
19391         res = out-in; /* ? */
19392         if (res<=0.0 &&res>-180.0) 
19393           res += 360.0;
19394         else if (res>=0.0 && res<180.0)
19395           res -= 360.0;
19396         print_roots("no roots (e)");
19397       } else {
19398         res = out-in;
19399         if (res<-180.0) 
19400           res += 360.0;
19401         else if (res>180.0)
19402           res -= 360.0;
19403         print_roots("two roots"); /* two inflections */
19404       }
19405     }
19406   }
19407   return double2angle(res);
19408 }
19409
19410 @
19411 @d p_nextnext link(link(p))
19412 @d p_next link(p)
19413 @d seven_twenty_deg 05500000000 /* $720\cdot2^{20}$, represents $720^\circ$ */
19414
19415 @<Declare unary action...@>=
19416 scaled mp_new_turn_cycles (MP mp,pointer c) {
19417   angle res,ang; /*  the angles of intermediate results  */
19418   scaled turns;  /*  the turn counter  */
19419   pointer p;     /*  for running around the path  */
19420   integer xp,yp;   /*  coordinates of next point  */
19421   integer x,y;   /*  helper coordinates  */
19422   angle in_angle,out_angle;     /*  helper angles */
19423   int old_setting; /* saved |selector| setting */
19424   res=0;
19425   turns= 0;
19426   p=c;
19427   old_setting = mp->selector; mp->selector=term_only;
19428   if ( mp->internal[mp_tracing_commands]>unity ) {
19429     mp_begin_diagnostic(mp);
19430     mp_print_nl(mp, "");
19431     mp_end_diagnostic(mp, false);
19432   }
19433   do { 
19434     xp = x_coord(p_next); yp = y_coord(p_next);
19435     ang  = mp_bezier_slope(mp,x_coord(p), y_coord(p), right_x(p), right_y(p),
19436              left_x(p_next), left_y(p_next), xp, yp, 
19437              mp->internal[mp_tracing_commands]);
19438     if ( ang>seven_twenty_deg ) {
19439       print_err("Strange path");
19440       mp_error(mp);
19441       mp->selector=old_setting;
19442       return 0;
19443     }
19444     res  = res + ang;
19445     if ( res > one_eighty_deg ) {
19446       res = res - three_sixty_deg;
19447       turns = turns + unity;
19448     }
19449     if ( res <= -one_eighty_deg ) {
19450       res = res + three_sixty_deg;
19451       turns = turns - unity;
19452     }
19453     /*  incoming angle at next point  */
19454     x = left_x(p_next);  y = left_y(p_next);
19455     if ( (xp==x)&&(yp==y) ) { x = right_x(p);  y = right_y(p);  };
19456     if ( (xp==x)&&(yp==y) ) { x = x_coord(p);  y = y_coord(p);  };
19457     in_angle = mp_an_angle(mp, xp - x, yp - y);
19458     /*  outgoing angle at next point  */
19459     x = right_x(p_next);  y = right_y(p_next);
19460     if ( (xp==x)&&(yp==y) ) { x = left_x(p_nextnext);  y = left_y(p_nextnext);  };
19461     if ( (xp==x)&&(yp==y) ) { x = x_coord(p_nextnext); y = y_coord(p_nextnext); };
19462     out_angle = mp_an_angle(mp, x - xp, y- yp);
19463     ang  = (out_angle - in_angle);
19464     reduce_angle(ang);
19465     if ( ang!=0 ) {
19466       res  = res + ang;
19467       if ( res >= one_eighty_deg ) {
19468         res = res - three_sixty_deg;
19469         turns = turns + unity;
19470       };
19471       if ( res <= -one_eighty_deg ) {
19472         res = res + three_sixty_deg;
19473         turns = turns - unity;
19474       };
19475     };
19476     p = link(p);
19477   } while (p!=c);
19478   mp->selector=old_setting;
19479   return turns;
19480 }
19481
19482
19483 @ This code is based on Bogus\l{}av Jackowski's
19484 |emergency_turningnumber| macro, with some minor changes by Taco
19485 Hoekwater. The macro code looked more like this:
19486 {\obeylines
19487 vardef turning\_number primary p =
19488 ~~save res, ang, turns;
19489 ~~res := 0;
19490 ~~if length p <= 2:
19491 ~~~~if Angle ((point 0 of p) - (postcontrol 0 of p)) >= 0:  1  else: -1 fi
19492 ~~else:
19493 ~~~~for t = 0 upto length p-1 :
19494 ~~~~~~angc := Angle ((point t+1 of p)  - (point t of p))
19495 ~~~~~~~~- Angle ((point t of p) - (point t-1 of p));
19496 ~~~~~~if angc > 180: angc := angc - 360; fi;
19497 ~~~~~~if angc < -180: angc := angc + 360; fi;
19498 ~~~~~~res  := res + angc;
19499 ~~~~endfor;
19500 ~~res/360
19501 ~~fi
19502 enddef;}
19503 The general idea is to calculate only the sum of the angles of
19504 straight lines between the points, of a path, not worrying about cusps
19505 or self-intersections in the segments at all. If the segment is not
19506 well-behaved, the result is not necesarily correct. But the old code
19507 was not always correct either, and worse, it sometimes failed for
19508 well-behaved paths as well. All known bugs that were triggered by the
19509 original code no longer occur with this code, and it runs roughly 3
19510 times as fast because the algorithm is much simpler.
19511
19512 @ It is possible to overflow the return value of the |turn_cycles|
19513 function when the path is sufficiently long and winding, but I am not
19514 going to bother testing for that. In any case, it would only return
19515 the looped result value, which is not a big problem.
19516
19517 The macro code for the repeat loop was a bit nicer to look
19518 at than the pascal code, because it could use |point -1 of p|. In
19519 pascal, the fastest way to loop around the path is not to look
19520 backward once, but forward twice. These defines help hide the trick.
19521
19522 @d p_to link(link(p))
19523 @d p_here link(p)
19524 @d p_from p
19525
19526 @<Declare unary action...@>=
19527 scaled mp_turn_cycles (MP mp,pointer c) {
19528   angle res,ang; /*  the angles of intermediate results  */
19529   scaled turns;  /*  the turn counter  */
19530   pointer p;     /*  for running around the path  */
19531   res=0;  turns= 0; p=c;
19532   do { 
19533     ang  = mp_an_angle (mp, x_coord(p_to) - x_coord(p_here), 
19534                             y_coord(p_to) - y_coord(p_here))
19535         - mp_an_angle (mp, x_coord(p_here) - x_coord(p_from), 
19536                            y_coord(p_here) - y_coord(p_from));
19537     reduce_angle(ang);
19538     res  = res + ang;
19539     if ( res >= three_sixty_deg )  {
19540       res = res - three_sixty_deg;
19541       turns = turns + unity;
19542     };
19543     if ( res <= -three_sixty_deg ) {
19544       res = res + three_sixty_deg;
19545       turns = turns - unity;
19546     };
19547     p = link(p);
19548   } while (p!=c);
19549   return turns;
19550 }
19551
19552 @ @<Declare unary action...@>=
19553 scaled mp_turn_cycles_wrapper (MP mp,pointer c) {
19554   scaled nval,oval;
19555   scaled saved_t_o; /* tracing\_online saved  */
19556   if ( (link(c)==c)||(link(link(c))==c) ) {
19557     if ( mp_an_angle (mp, x_coord(c) - right_x(c),  y_coord(c) - right_y(c)) > 0 )
19558       return unity;
19559     else
19560       return -unity;
19561   } else {
19562     nval = mp_new_turn_cycles(mp, c);
19563     oval = mp_turn_cycles(mp, c);
19564     if ( nval!=oval ) {
19565       saved_t_o=mp->internal[mp_tracing_online];
19566       mp->internal[mp_tracing_online]=unity;
19567       mp_begin_diagnostic(mp);
19568       mp_print_nl (mp, "Warning: the turningnumber algorithms do not agree."
19569                        " The current computed value is ");
19570       mp_print_scaled(mp, nval);
19571       mp_print(mp, ", but the 'connect-the-dots' algorithm returned ");
19572       mp_print_scaled(mp, oval);
19573       mp_end_diagnostic(mp, false);
19574       mp->internal[mp_tracing_online]=saved_t_o;
19575     }
19576     return nval;
19577   }
19578 }
19579
19580 @ @<Declare unary action...@>=
19581 scaled mp_count_turns (MP mp,pointer c) {
19582   pointer p; /* a knot in envelope spec |c| */
19583   integer t; /* total pen offset changes counted */
19584   t=0; p=c;
19585   do {  
19586     t=t+info(p)-zero_off;
19587     p=link(p);
19588   } while (p!=c);
19589   return ((t / 3)*unity);
19590 }
19591
19592 @ @d type_range(A,B) { 
19593   if ( (mp->cur_type>=(A)) && (mp->cur_type<=(B)) ) 
19594     mp_flush_cur_exp(mp, true_code);
19595   else mp_flush_cur_exp(mp, false_code);
19596   mp->cur_type=mp_boolean_type;
19597   }
19598 @d type_test(A) { 
19599   if ( mp->cur_type==(A) ) mp_flush_cur_exp(mp, true_code);
19600   else mp_flush_cur_exp(mp, false_code);
19601   mp->cur_type=mp_boolean_type;
19602   }
19603
19604 @<Additional cases of unary operators@>=
19605 case mp_boolean_type: 
19606   type_range(mp_boolean_type,mp_unknown_boolean); break;
19607 case mp_string_type: 
19608   type_range(mp_string_type,mp_unknown_string); break;
19609 case mp_pen_type: 
19610   type_range(mp_pen_type,mp_unknown_pen); break;
19611 case mp_path_type: 
19612   type_range(mp_path_type,mp_unknown_path); break;
19613 case mp_picture_type: 
19614   type_range(mp_picture_type,mp_unknown_picture); break;
19615 case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
19616 case mp_pair_type: 
19617   type_test(c); break;
19618 case mp_numeric_type: 
19619   type_range(mp_known,mp_independent); break;
19620 case known_op: case unknown_op: 
19621   mp_test_known(mp, c); break;
19622
19623 @ @<Declare unary action procedures@>=
19624 void mp_test_known (MP mp,quarterword c) {
19625   int b; /* is the current expression known? */
19626   pointer p,q; /* locations in a big node */
19627   b=false_code;
19628   switch (mp->cur_type) {
19629   case mp_vacuous: case mp_boolean_type: case mp_string_type:
19630   case mp_pen_type: case mp_path_type: case mp_picture_type:
19631   case mp_known: 
19632     b=true_code;
19633     break;
19634   case mp_transform_type:
19635   case mp_color_type: case mp_cmykcolor_type: case mp_pair_type: 
19636     p=value(mp->cur_exp);
19637     q=p+mp->big_node_size[mp->cur_type];
19638     do {  
19639       q=q-2;
19640       if ( type(q)!=mp_known ) 
19641        goto DONE;
19642     } while (q!=p);
19643     b=true_code;
19644   DONE:  
19645     break;
19646   default: 
19647     break;
19648   }
19649   if ( c==known_op ) mp_flush_cur_exp(mp, b);
19650   else mp_flush_cur_exp(mp, true_code+false_code-b);
19651   mp->cur_type=mp_boolean_type;
19652 }
19653
19654 @ @<Additional cases of unary operators@>=
19655 case cycle_op: 
19656   if ( mp->cur_type!=mp_path_type ) mp_flush_cur_exp(mp, false_code);
19657   else if ( left_type(mp->cur_exp)!=mp_endpoint ) mp_flush_cur_exp(mp, true_code);
19658   else mp_flush_cur_exp(mp, false_code);
19659   mp->cur_type=mp_boolean_type;
19660   break;
19661
19662 @ @<Additional cases of unary operators@>=
19663 case arc_length: 
19664   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19665   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, arc_length);
19666   else mp_flush_cur_exp(mp, mp_get_arc_length(mp, mp->cur_exp));
19667   break;
19668
19669 @ Here we use the fact that |c-filled_op+fill_code| is the desired graphical
19670 object |type|.
19671 @^data structure assumptions@>
19672
19673 @<Additional cases of unary operators@>=
19674 case filled_op:
19675 case stroked_op:
19676 case textual_op:
19677 case clipped_op:
19678 case bounded_op:
19679   if ( mp->cur_type!=mp_picture_type ) mp_flush_cur_exp(mp, false_code);
19680   else if ( link(dummy_loc(mp->cur_exp))==null ) mp_flush_cur_exp(mp, false_code);
19681   else if ( type(link(dummy_loc(mp->cur_exp)))==c+mp_fill_code-filled_op )
19682     mp_flush_cur_exp(mp, true_code);
19683   else mp_flush_cur_exp(mp, false_code);
19684   mp->cur_type=mp_boolean_type;
19685   break;
19686
19687 @ @<Additional cases of unary operators@>=
19688 case make_pen_op: 
19689   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19690   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, make_pen_op);
19691   else { 
19692     mp->cur_type=mp_pen_type;
19693     mp->cur_exp=mp_make_pen(mp, mp->cur_exp,true);
19694   };
19695   break;
19696 case make_path_op: 
19697   if ( mp->cur_type!=mp_pen_type ) mp_bad_unary(mp, make_path_op);
19698   else  { 
19699     mp->cur_type=mp_path_type;
19700     mp_make_path(mp, mp->cur_exp);
19701   };
19702   break;
19703 case reverse: 
19704   if ( mp->cur_type==mp_path_type ) {
19705     p=mp_htap_ypoc(mp, mp->cur_exp);
19706     if ( right_type(p)==mp_endpoint ) p=link(p);
19707     mp_toss_knot_list(mp, mp->cur_exp); mp->cur_exp=p;
19708   } else if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19709   else mp_bad_unary(mp, reverse);
19710   break;
19711
19712 @ The |pair_value| routine changes the current expression to a
19713 given ordered pair of values.
19714
19715 @<Declare unary action procedures@>=
19716 void mp_pair_value (MP mp,scaled x, scaled y) {
19717   pointer p; /* a pair node */
19718   p=mp_get_node(mp, value_node_size); 
19719   mp_flush_cur_exp(mp, p); mp->cur_type=mp_pair_type;
19720   type(p)=mp_pair_type; name_type(p)=mp_capsule; mp_init_big_node(mp, p);
19721   p=value(p);
19722   type(x_part_loc(p))=mp_known; value(x_part_loc(p))=x;
19723   type(y_part_loc(p))=mp_known; value(y_part_loc(p))=y;
19724 }
19725
19726 @ @<Additional cases of unary operators@>=
19727 case ll_corner_op: 
19728   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ll_corner_op);
19729   else mp_pair_value(mp, minx,miny);
19730   break;
19731 case lr_corner_op: 
19732   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, lr_corner_op);
19733   else mp_pair_value(mp, maxx,miny);
19734   break;
19735 case ul_corner_op: 
19736   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ul_corner_op);
19737   else mp_pair_value(mp, minx,maxy);
19738   break;
19739 case ur_corner_op: 
19740   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ur_corner_op);
19741   else mp_pair_value(mp, maxx,maxy);
19742   break;
19743
19744 @ Here is a function that sets |minx|, |maxx|, |miny|, |maxy| to the bounding
19745 box of the current expression.  The boolean result is |false| if the expression
19746 has the wrong type.
19747
19748 @<Declare unary action procedures@>=
19749 boolean mp_get_cur_bbox (MP mp) { 
19750   switch (mp->cur_type) {
19751   case mp_picture_type: 
19752     mp_set_bbox(mp, mp->cur_exp,true);
19753     if ( minx_val(mp->cur_exp)>maxx_val(mp->cur_exp) ) {
19754       minx=0; maxx=0; miny=0; maxy=0;
19755     } else { 
19756       minx=minx_val(mp->cur_exp);
19757       maxx=maxx_val(mp->cur_exp);
19758       miny=miny_val(mp->cur_exp);
19759       maxy=maxy_val(mp->cur_exp);
19760     }
19761     break;
19762   case mp_path_type: 
19763     mp_path_bbox(mp, mp->cur_exp);
19764     break;
19765   case mp_pen_type: 
19766     mp_pen_bbox(mp, mp->cur_exp);
19767     break;
19768   default: 
19769     return false;
19770   }
19771   return true;
19772 }
19773
19774 @ @<Additional cases of unary operators@>=
19775 case read_from_op:
19776 case close_from_op: 
19777   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19778   else mp_do_read_or_close(mp,c);
19779   break;
19780
19781 @ Here is a routine that interprets |cur_exp| as a file name and tries to read
19782 a line from the file or to close the file.
19783
19784 @d close_file 46 /* go here when closing the file */
19785
19786 @<Declare unary action procedures@>=
19787 void mp_do_read_or_close (MP mp,quarterword c) {
19788   readf_index n,n0; /* indices for searching |rd_fname| */
19789   @<Find the |n| where |rd_fname[n]=cur_exp|; if |cur_exp| must be inserted,
19790     call |start_read_input| and |goto found| or |not_found|@>;
19791   mp_begin_file_reading(mp);
19792   name=is_read;
19793   if ( mp_input_ln(mp, mp->rd_file[n],true) ) 
19794     goto FOUND;
19795   mp_end_file_reading(mp);
19796 NOT_FOUND:
19797   @<Record the end of file and set |cur_exp| to a dummy value@>;
19798   return;
19799 CLOSE_FILE:
19800   mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous; 
19801   return;
19802 FOUND:
19803   mp_flush_cur_exp(mp, 0);
19804   mp_finish_read(mp);
19805 }
19806
19807 @ Free slots in the |rd_file| and |rd_fname| arrays are marked with NULL's in
19808 |rd_fname|.
19809
19810 @<Find the |n| where |rd_fname[n]=cur_exp|...@>=
19811 {   
19812   char *fn;
19813   n=mp->read_files;
19814   n0=mp->read_files;
19815   fn = str(mp->cur_exp);
19816   while (mp_xstrcmp(fn,mp->rd_fname[n])!=0) { 
19817     if ( n>0 ) {
19818       decr(n);
19819     } else if ( c==close_from_op ) {
19820       goto CLOSE_FILE;
19821     } else {
19822       if ( n0==mp->read_files ) {
19823         if ( mp->read_files<mp->max_read_files ) {
19824           incr(mp->read_files);
19825         } else {
19826           FILE **rd_file;
19827           char **rd_fname;
19828               readf_index l,k;
19829           l = mp->max_read_files + (mp->max_read_files>>2);
19830           rd_file = xmalloc((l+1), sizeof(FILE *));
19831           rd_fname = xmalloc((l+1), sizeof(char *));
19832               for (k=0;k<=l;k++) {
19833             if (k<=mp->max_read_files) {
19834                   rd_file[k]=mp->rd_file[k]; 
19835               rd_fname[k]=mp->rd_fname[k];
19836             } else {
19837               rd_file[k]=0; 
19838               rd_fname[k]=NULL;
19839             }
19840           }
19841               xfree(mp->rd_file); xfree(mp->rd_fname);
19842           mp->max_read_files = l;
19843           mp->rd_file = rd_file;
19844           mp->rd_fname = rd_fname;
19845         }
19846       }
19847       n=n0;
19848       if ( mp_start_read_input(mp,fn,n) ) 
19849         goto FOUND;
19850       else 
19851         goto NOT_FOUND;
19852     }
19853     if ( mp->rd_fname[n]==NULL ) { n0=n; }
19854   } 
19855   if ( c==close_from_op ) { 
19856     fclose(mp->rd_file[n]); 
19857     goto NOT_FOUND; 
19858   }
19859 }
19860
19861 @ @<Record the end of file and set |cur_exp| to a dummy value@>=
19862 xfree(mp->rd_fname[n]);
19863 mp->rd_fname[n]=NULL;
19864 if ( n==mp->read_files-1 ) mp->read_files=n;
19865 if ( c==close_from_op ) 
19866   goto CLOSE_FILE;
19867 mp_flush_cur_exp(mp, mp->eof_line);
19868 mp->cur_type=mp_string_type
19869
19870 @ The string denoting end-of-file is a one-byte string at position zero, by definition
19871
19872 @<Glob...@>=
19873 str_number eof_line;
19874
19875 @ @<Set init...@>=
19876 mp->eof_line=0;
19877
19878 @ Finally, we have the operations that combine a capsule~|p|
19879 with the current expression.
19880
19881 @c @<Declare binary action procedures@>;
19882 void mp_do_binary (MP mp,pointer p, quarterword c) {
19883   pointer q,r,rr; /* for list manipulation */
19884   pointer old_p,old_exp; /* capsules to recycle */
19885   integer v; /* for numeric manipulation */
19886   check_arith;
19887   if ( mp->internal[mp_tracing_commands]>two ) {
19888     @<Trace the current binary operation@>;
19889   }
19890   @<Sidestep |independent| cases in capsule |p|@>;
19891   @<Sidestep |independent| cases in the current expression@>;
19892   switch (c) {
19893   case plus: case minus:
19894     @<Add or subtract the current expression from |p|@>;
19895     break;
19896   @<Additional cases of binary operators@>;
19897   }; /* there are no other cases */
19898   mp_recycle_value(mp, p); 
19899   mp_free_node(mp, p,value_node_size); /* |return| to avoid this */
19900   check_arith; 
19901   @<Recycle any sidestepped |independent| capsules@>;
19902 }
19903
19904 @ @<Declare binary action...@>=
19905 void mp_bad_binary (MP mp,pointer p, quarterword c) { 
19906   mp_disp_err(mp, p,"");
19907   exp_err("Not implemented: ");
19908 @.Not implemented...@>
19909   if ( c>=min_of ) mp_print_op(mp, c);
19910   mp_print_known_or_unknown_type(mp, type(p),p);
19911   if ( c>=min_of ) mp_print(mp, "of"); else mp_print_op(mp, c);
19912   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
19913   help3("I'm afraid I don't know how to apply that operation to that")
19914        ("combination of types. Continue, and I'll return the second")
19915       ("argument (see above) as the result of the operation.");
19916   mp_put_get_error(mp);
19917 }
19918
19919 @ @<Trace the current binary operation@>=
19920
19921   mp_begin_diagnostic(mp); mp_print_nl(mp, "{(");
19922   mp_print_exp(mp,p,0); /* show the operand, but not verbosely */
19923   mp_print_char(mp,')'); mp_print_op(mp,c); mp_print_char(mp,'(');
19924   mp_print_exp(mp,null,0); mp_print(mp,")}"); 
19925   mp_end_diagnostic(mp, false);
19926 }
19927
19928 @ Several of the binary operations are potentially complicated by the
19929 fact that |independent| values can sneak into capsules. For example,
19930 we've seen an instance of this difficulty in the unary operation
19931 of negation. In order to reduce the number of cases that need to be
19932 handled, we first change the two operands (if necessary)
19933 to rid them of |independent| components. The original operands are
19934 put into capsules called |old_p| and |old_exp|, which will be
19935 recycled after the binary operation has been safely carried out.
19936
19937 @<Recycle any sidestepped |independent| capsules@>=
19938 if ( old_p!=null ) { 
19939   mp_recycle_value(mp, old_p); mp_free_node(mp, old_p,value_node_size);
19940 }
19941 if ( old_exp!=null ) {
19942   mp_recycle_value(mp, old_exp); mp_free_node(mp, old_exp,value_node_size);
19943 }
19944
19945 @ A big node is considered to be ``tarnished'' if it contains at least one
19946 independent component. We will define a simple function called `|tarnished|'
19947 that returns |null| if and only if its argument is not tarnished.
19948
19949 @<Sidestep |independent| cases in capsule |p|@>=
19950 switch (type(p)) {
19951 case mp_transform_type:
19952 case mp_color_type:
19953 case mp_cmykcolor_type:
19954 case mp_pair_type: 
19955   old_p=mp_tarnished(mp, p);
19956   break;
19957 case mp_independent: old_p=mp_void; break;
19958 default: old_p=null; break;
19959 };
19960 if ( old_p!=null ) {
19961   q=mp_stash_cur_exp(mp); old_p=p; mp_make_exp_copy(mp, old_p);
19962   p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
19963 }
19964
19965 @ @<Sidestep |independent| cases in the current expression@>=
19966 switch (mp->cur_type) {
19967 case mp_transform_type:
19968 case mp_color_type:
19969 case mp_cmykcolor_type:
19970 case mp_pair_type: 
19971   old_exp=mp_tarnished(mp, mp->cur_exp);
19972   break;
19973 case mp_independent:old_exp=mp_void; break;
19974 default: old_exp=null; break;
19975 };
19976 if ( old_exp!=null ) {
19977   old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
19978 }
19979
19980 @ @<Declare binary action...@>=
19981 pointer mp_tarnished (MP mp,pointer p) {
19982   pointer q; /* beginning of the big node */
19983   pointer r; /* current position in the big node */
19984   q=value(p); r=q+mp->big_node_size[type(p)];
19985   do {  
19986    r=r-2;
19987    if ( type(r)==mp_independent ) return mp_void; 
19988   } while (r!=q);
19989   return null;
19990 }
19991
19992 @ @<Add or subtract the current expression from |p|@>=
19993 if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
19994   mp_bad_binary(mp, p,c);
19995 } else  {
19996   if ((mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
19997     mp_add_or_subtract(mp, p,null,c);
19998   } else {
19999     if ( mp->cur_type!=type(p) )  {
20000       mp_bad_binary(mp, p,c);
20001     } else { 
20002       q=value(p); r=value(mp->cur_exp);
20003       rr=r+mp->big_node_size[mp->cur_type];
20004       while ( r<rr ) { 
20005         mp_add_or_subtract(mp, q,r,c);
20006         q=q+2; r=r+2;
20007       }
20008     }
20009   }
20010 }
20011
20012 @ The first argument to |add_or_subtract| is the location of a value node
20013 in a capsule or pair node that will soon be recycled. The second argument
20014 is either a location within a pair or transform node of |cur_exp|,
20015 or it is null (which means that |cur_exp| itself should be the second
20016 argument).  The third argument is either |plus| or |minus|.
20017
20018 The sum or difference of the numeric quantities will replace the second
20019 operand.  Arithmetic overflow may go undetected; users aren't supposed to
20020 be monkeying around with really big values.
20021
20022 @<Declare binary action...@>=
20023 @<Declare the procedure called |dep_finish|@>;
20024 void mp_add_or_subtract (MP mp,pointer p, pointer q, quarterword c) {
20025   small_number s,t; /* operand types */
20026   pointer r; /* list traverser */
20027   integer v; /* second operand value */
20028   if ( q==null ) { 
20029     t=mp->cur_type;
20030     if ( t<mp_dependent ) v=mp->cur_exp; else v=dep_list(mp->cur_exp);
20031   } else { 
20032     t=type(q);
20033     if ( t<mp_dependent ) v=value(q); else v=dep_list(q);
20034   }
20035   if ( t==mp_known ) {
20036     if ( c==minus ) negate(v);
20037     if ( type(p)==mp_known ) {
20038       v=mp_slow_add(mp, value(p),v);
20039       if ( q==null ) mp->cur_exp=v; else value(q)=v;
20040       return;
20041     }
20042     @<Add a known value to the constant term of |dep_list(p)|@>;
20043   } else  { 
20044     if ( c==minus ) mp_negate_dep_list(mp, v);
20045     @<Add operand |p| to the dependency list |v|@>;
20046   }
20047 }
20048
20049 @ @<Add a known value to the constant term of |dep_list(p)|@>=
20050 r=dep_list(p);
20051 while ( info(r)!=null ) r=link(r);
20052 value(r)=mp_slow_add(mp, value(r),v);
20053 if ( q==null ) {
20054   q=mp_get_node(mp, value_node_size); mp->cur_exp=q; mp->cur_type=type(p);
20055   name_type(q)=mp_capsule;
20056 }
20057 dep_list(q)=dep_list(p); type(q)=type(p);
20058 prev_dep(q)=prev_dep(p); link(prev_dep(p))=q;
20059 type(p)=mp_known; /* this will keep the recycler from collecting non-garbage */
20060
20061 @ We prefer |dependent| lists to |mp_proto_dependent| ones, because it is
20062 nice to retain the extra accuracy of |fraction| coefficients.
20063 But we have to handle both kinds, and mixtures too.
20064
20065 @<Add operand |p| to the dependency list |v|@>=
20066 if ( type(p)==mp_known ) {
20067   @<Add the known |value(p)| to the constant term of |v|@>;
20068 } else { 
20069   s=type(p); r=dep_list(p);
20070   if ( t==mp_dependent ) {
20071     if ( s==mp_dependent ) {
20072       if ( mp_max_coef(mp, r)+mp_max_coef(mp, v)<coef_bound )
20073         v=mp_p_plus_q(mp, v,r,mp_dependent); goto DONE;
20074       } /* |fix_needed| will necessarily be false */
20075       t=mp_proto_dependent; 
20076       v=mp_p_over_v(mp, v,unity,mp_dependent,mp_proto_dependent);
20077     }
20078     if ( s==mp_proto_dependent ) v=mp_p_plus_q(mp, v,r,mp_proto_dependent);
20079     else v=mp_p_plus_fq(mp, v,unity,r,mp_proto_dependent,mp_dependent);
20080  DONE:  
20081     @<Output the answer, |v| (which might have become |known|)@>;
20082   }
20083
20084 @ @<Add the known |value(p)| to the constant term of |v|@>=
20085
20086   while ( info(v)!=null ) v=link(v);
20087   value(v)=mp_slow_add(mp, value(p),value(v));
20088 }
20089
20090 @ @<Output the answer, |v| (which might have become |known|)@>=
20091 if ( q!=null ) mp_dep_finish(mp, v,q,t);
20092 else  { mp->cur_type=t; mp_dep_finish(mp, v,null,t); }
20093
20094 @ Here's the current situation: The dependency list |v| of type |t|
20095 should either be put into the current expression (if |q=null|) or
20096 into location |q| within a pair node (otherwise). The destination (|cur_exp|
20097 or |q|) formerly held a dependency list with the same
20098 final pointer as the list |v|.
20099
20100 @<Declare the procedure called |dep_finish|@>=
20101 void mp_dep_finish (MP mp, pointer v, pointer q, small_number t) {
20102   pointer p; /* the destination */
20103   scaled vv; /* the value, if it is |known| */
20104   if ( q==null ) p=mp->cur_exp; else p=q;
20105   dep_list(p)=v; type(p)=t;
20106   if ( info(v)==null ) { 
20107     vv=value(v);
20108     if ( q==null ) { 
20109       mp_flush_cur_exp(mp, vv);
20110     } else  { 
20111       mp_recycle_value(mp, p); type(q)=mp_known; value(q)=vv; 
20112     }
20113   } else if ( q==null ) {
20114     mp->cur_type=t;
20115   }
20116   if ( mp->fix_needed ) mp_fix_dependencies(mp);
20117 }
20118
20119 @ Let's turn now to the six basic relations of comparison.
20120
20121 @<Additional cases of binary operators@>=
20122 case less_than: case less_or_equal: case greater_than:
20123 case greater_or_equal: case equal_to: case unequal_to:
20124   check_arith; /* at this point |arith_error| should be |false|? */
20125   if ( (mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
20126     mp_add_or_subtract(mp, p,null,minus); /* |cur_exp:=(p)-cur_exp| */
20127   } else if ( mp->cur_type!=type(p) ) {
20128     mp_bad_binary(mp, p,c); goto DONE; 
20129   } else if ( mp->cur_type==mp_string_type ) {
20130     mp_flush_cur_exp(mp, mp_str_vs_str(mp, value(p),mp->cur_exp));
20131   } else if ((mp->cur_type==mp_unknown_string)||
20132            (mp->cur_type==mp_unknown_boolean) ) {
20133     @<Check if unknowns have been equated@>;
20134   } else if ( (mp->cur_type<=mp_pair_type)&&(mp->cur_type>=mp_transform_type)) {
20135     @<Reduce comparison of big nodes to comparison of scalars@>;
20136   } else if ( mp->cur_type==mp_boolean_type ) {
20137     mp_flush_cur_exp(mp, mp->cur_exp-value(p));
20138   } else { 
20139     mp_bad_binary(mp, p,c); goto DONE;
20140   }
20141   @<Compare the current expression with zero@>;
20142 DONE:  
20143   mp->arith_error=false; /* ignore overflow in comparisons */
20144   break;
20145
20146 @ @<Compare the current expression with zero@>=
20147 if ( mp->cur_type!=mp_known ) {
20148   if ( mp->cur_type<mp_known ) {
20149     mp_disp_err(mp, p,"");
20150     help1("The quantities shown above have not been equated.")
20151   } else  {
20152     help2("Oh dear. I can\'t decide if the expression above is positive,")
20153      ("negative, or zero. So this comparison test won't be `true'.");
20154   }
20155   exp_err("Unknown relation will be considered false");
20156 @.Unknown relation...@>
20157   mp_put_get_flush_error(mp, false_code);
20158 } else {
20159   switch (c) {
20160   case less_than: boolean_reset(mp->cur_exp<0); break;
20161   case less_or_equal: boolean_reset(mp->cur_exp<=0); break;
20162   case greater_than: boolean_reset(mp->cur_exp>0); break;
20163   case greater_or_equal: boolean_reset(mp->cur_exp>=0); break;
20164   case equal_to: boolean_reset(mp->cur_exp==0); break;
20165   case unequal_to: boolean_reset(mp->cur_exp!=0); break;
20166   }; /* there are no other cases */
20167 }
20168 mp->cur_type=mp_boolean_type
20169
20170 @ When two unknown strings are in the same ring, we know that they are
20171 equal. Otherwise, we don't know whether they are equal or not, so we
20172 make no change.
20173
20174 @<Check if unknowns have been equated@>=
20175
20176   q=value(mp->cur_exp);
20177   while ( (q!=mp->cur_exp)&&(q!=p) ) q=value(q);
20178   if ( q==p ) mp_flush_cur_exp(mp, 0);
20179 }
20180
20181 @ @<Reduce comparison of big nodes to comparison of scalars@>=
20182
20183   q=value(p); r=value(mp->cur_exp);
20184   rr=r+mp->big_node_size[mp->cur_type]-2;
20185   while (1) { mp_add_or_subtract(mp, q,r,minus);
20186     if ( type(r)!=mp_known ) break;
20187     if ( value(r)!=0 ) break;
20188     if ( r==rr ) break;
20189     q=q+2; r=r+2;
20190   }
20191   mp_take_part(mp, name_type(r)+x_part-mp_x_part_sector);
20192 }
20193
20194 @ Here we use the sneaky fact that |and_op-false_code=or_op-true_code|.
20195
20196 @<Additional cases of binary operators@>=
20197 case and_op:
20198 case or_op: 
20199   if ( (type(p)!=mp_boolean_type)||(mp->cur_type!=mp_boolean_type) )
20200     mp_bad_binary(mp, p,c);
20201   else if ( value(p)==c+false_code-and_op ) mp->cur_exp=value(p);
20202   break;
20203
20204 @ @<Additional cases of binary operators@>=
20205 case times: 
20206   if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
20207    mp_bad_binary(mp, p,times);
20208   } else if ( (mp->cur_type==mp_known)||(type(p)==mp_known) ) {
20209     @<Multiply when at least one operand is known@>;
20210   } else if ( (mp_nice_color_or_pair(mp, p,type(p))&&(mp->cur_type>mp_pair_type))
20211       ||(mp_nice_color_or_pair(mp, mp->cur_exp,mp->cur_type)&&
20212           (type(p)>mp_pair_type)) ) {
20213     mp_hard_times(mp, p); return;
20214   } else {
20215     mp_bad_binary(mp, p,times);
20216   }
20217   break;
20218
20219 @ @<Multiply when at least one operand is known@>=
20220
20221   if ( type(p)==mp_known ) {
20222     v=value(p); mp_free_node(mp, p,value_node_size); 
20223   } else {
20224     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20225   }
20226   if ( mp->cur_type==mp_known ) {
20227     mp->cur_exp=mp_take_scaled(mp, mp->cur_exp,v);
20228   } else if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_color_type)||
20229               (mp->cur_type==mp_cmykcolor_type) ) {
20230     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20231     do {  
20232        p=p-2; mp_dep_mult(mp, p,v,true);
20233     } while (p!=value(mp->cur_exp));
20234   } else {
20235     mp_dep_mult(mp, null,v,true);
20236   }
20237   return;
20238 }
20239
20240 @ @<Declare binary action...@>=
20241 void mp_dep_mult (MP mp,pointer p, integer v, boolean v_is_scaled) {
20242   pointer q; /* the dependency list being multiplied by |v| */
20243   small_number s,t; /* its type, before and after */
20244   if ( p==null ) {
20245     q=mp->cur_exp;
20246   } else if ( type(p)!=mp_known ) {
20247     q=p;
20248   } else { 
20249     if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
20250     else value(p)=mp_take_fraction(mp, value(p),v);
20251     return;
20252   };
20253   t=type(q); q=dep_list(q); s=t;
20254   if ( t==mp_dependent ) if ( v_is_scaled )
20255     if (mp_ab_vs_cd(mp, mp_max_coef(mp,q),abs(v),coef_bound-1,unity)>=0 ) 
20256       t=mp_proto_dependent;
20257   q=mp_p_times_v(mp, q,v,s,t,v_is_scaled); 
20258   mp_dep_finish(mp, q,p,t);
20259 }
20260
20261 @ Here is a routine that is similar to |times|; but it is invoked only
20262 internally, when |v| is a |fraction| whose magnitude is at most~1,
20263 and when |cur_type>=mp_color_type|.
20264
20265 @c void mp_frac_mult (MP mp,scaled n, scaled d) {
20266   /* multiplies |cur_exp| by |n/d| */
20267   pointer p; /* a pair node */
20268   pointer old_exp; /* a capsule to recycle */
20269   fraction v; /* |n/d| */
20270   if ( mp->internal[mp_tracing_commands]>two ) {
20271     @<Trace the fraction multiplication@>;
20272   }
20273   switch (mp->cur_type) {
20274   case mp_transform_type:
20275   case mp_color_type:
20276   case mp_cmykcolor_type:
20277   case mp_pair_type:
20278    old_exp=mp_tarnished(mp, mp->cur_exp);
20279    break;
20280   case mp_independent: old_exp=mp_void; break;
20281   default: old_exp=null; break;
20282   }
20283   if ( old_exp!=null ) { 
20284      old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
20285   }
20286   v=mp_make_fraction(mp, n,d);
20287   if ( mp->cur_type==mp_known ) {
20288     mp->cur_exp=mp_take_fraction(mp, mp->cur_exp,v);
20289   } else if ( mp->cur_type<=mp_pair_type ) { 
20290     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20291     do {  
20292       p=p-2;
20293       mp_dep_mult(mp, p,v,false);
20294     } while (p!=value(mp->cur_exp));
20295   } else {
20296     mp_dep_mult(mp, null,v,false);
20297   }
20298   if ( old_exp!=null ) {
20299     mp_recycle_value(mp, old_exp); 
20300     mp_free_node(mp, old_exp,value_node_size);
20301   }
20302 }
20303
20304 @ @<Trace the fraction multiplication@>=
20305
20306   mp_begin_diagnostic(mp); 
20307   mp_print_nl(mp, "{("); mp_print_scaled(mp,n); mp_print_char(mp,'/');
20308   mp_print_scaled(mp,d); mp_print(mp,")*("); mp_print_exp(mp,null,0); 
20309   mp_print(mp,")}");
20310   mp_end_diagnostic(mp, false);
20311 }
20312
20313 @ The |hard_times| routine multiplies a nice color or pair by a dependency list.
20314
20315 @<Declare binary action procedures@>=
20316 void mp_hard_times (MP mp,pointer p) {
20317   pointer q; /* a copy of the dependent variable |p| */
20318   pointer r; /* a component of the big node for the nice color or pair */
20319   scaled v; /* the known value for |r| */
20320   if ( type(p)<=mp_pair_type ) { 
20321      q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p); p=q;
20322   }; /* now |cur_type=mp_pair_type| or |cur_type=mp_color_type| */
20323   r=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20324   while (1) { 
20325     r=r-2;
20326     v=value(r);
20327     type(r)=type(p);
20328     if ( r==value(mp->cur_exp) ) 
20329       break;
20330     mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(p)));
20331     mp_dep_mult(mp, r,v,true);
20332   }
20333   mp->mem[value_loc(r)]=mp->mem[value_loc(p)];
20334   link(prev_dep(p))=r;
20335   mp_free_node(mp, p,value_node_size);
20336   mp_dep_mult(mp, r,v,true);
20337 }
20338
20339 @ @<Additional cases of binary operators@>=
20340 case over: 
20341   if ( (mp->cur_type!=mp_known)||(type(p)<mp_color_type) ) {
20342     mp_bad_binary(mp, p,over);
20343   } else { 
20344     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20345     if ( v==0 ) {
20346       @<Squeal about division by zero@>;
20347     } else { 
20348       if ( mp->cur_type==mp_known ) {
20349         mp->cur_exp=mp_make_scaled(mp, mp->cur_exp,v);
20350       } else if ( mp->cur_type<=mp_pair_type ) { 
20351         p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20352         do {  
20353           p=p-2;  mp_dep_div(mp, p,v);
20354         } while (p!=value(mp->cur_exp));
20355       } else {
20356         mp_dep_div(mp, null,v);
20357       }
20358     }
20359     return;
20360   }
20361   break;
20362
20363 @ @<Declare binary action...@>=
20364 void mp_dep_div (MP mp,pointer p, scaled v) {
20365   pointer q; /* the dependency list being divided by |v| */
20366   small_number s,t; /* its type, before and after */
20367   if ( p==null ) q=mp->cur_exp;
20368   else if ( type(p)!=mp_known ) q=p;
20369   else { value(p)=mp_make_scaled(mp, value(p),v); return; };
20370   t=type(q); q=dep_list(q); s=t;
20371   if ( t==mp_dependent )
20372     if ( mp_ab_vs_cd(mp, mp_max_coef(mp,q),unity,coef_bound-1,abs(v))>=0 ) 
20373       t=mp_proto_dependent;
20374   q=mp_p_over_v(mp, q,v,s,t); 
20375   mp_dep_finish(mp, q,p,t);
20376 }
20377
20378 @ @<Squeal about division by zero@>=
20379
20380   exp_err("Division by zero");
20381 @.Division by zero@>
20382   help2("You're trying to divide the quantity shown above the error")
20383     ("message by zero. I'm going to divide it by one instead.");
20384   mp_put_get_error(mp);
20385 }
20386
20387 @ @<Additional cases of binary operators@>=
20388 case pythag_add:
20389 case pythag_sub: 
20390    if ( (mp->cur_type==mp_known)&&(type(p)==mp_known) ) {
20391      if ( c==pythag_add ) mp->cur_exp=mp_pyth_add(mp, value(p),mp->cur_exp);
20392      else mp->cur_exp=mp_pyth_sub(mp, value(p),mp->cur_exp);
20393    } else mp_bad_binary(mp, p,c);
20394    break;
20395
20396 @ The next few sections of the program deal with affine transformations
20397 of coordinate data.
20398
20399 @<Additional cases of binary operators@>=
20400 case rotated_by: case slanted_by:
20401 case scaled_by: case shifted_by: case transformed_by:
20402 case x_scaled: case y_scaled: case z_scaled:
20403   if ( type(p)==mp_path_type ) { 
20404     path_trans(c,p); return;
20405   } else if ( type(p)==mp_pen_type ) { 
20406     pen_trans(c,p);
20407     mp->cur_exp=mp_convex_hull(mp, mp->cur_exp); 
20408       /* rounding error could destroy convexity */
20409     return;
20410   } else if ( (type(p)==mp_pair_type)||(type(p)==mp_transform_type) ) {
20411     mp_big_trans(mp, p,c);
20412   } else if ( type(p)==mp_picture_type ) {
20413     mp_do_edges_trans(mp, p,c); return;
20414   } else {
20415     mp_bad_binary(mp, p,c);
20416   }
20417   break;
20418
20419 @ Let |c| be one of the eight transform operators. The procedure call
20420 |set_up_trans(c)| first changes |cur_exp| to a transform that corresponds to
20421 |c| and the original value of |cur_exp|. (In particular, |cur_exp| doesn't
20422 change at all if |c=transformed_by|.)
20423
20424 Then, if all components of the resulting transform are |known|, they are
20425 moved to the global variables |txx|, |txy|, |tyx|, |tyy|, |tx|, |ty|;
20426 and |cur_exp| is changed to the known value zero.
20427
20428 @<Declare binary action...@>=
20429 void mp_set_up_trans (MP mp,quarterword c) {
20430   pointer p,q,r; /* list manipulation registers */
20431   if ( (c!=transformed_by)||(mp->cur_type!=mp_transform_type) ) {
20432     @<Put the current transform into |cur_exp|@>;
20433   }
20434   @<If the current transform is entirely known, stash it in global variables;
20435     otherwise |return|@>;
20436 }
20437
20438 @ @<Glob...@>=
20439 scaled txx;
20440 scaled txy;
20441 scaled tyx;
20442 scaled tyy;
20443 scaled tx;
20444 scaled ty; /* current transform coefficients */
20445
20446 @ @<Put the current transform...@>=
20447
20448   p=mp_stash_cur_exp(mp); 
20449   mp->cur_exp=mp_id_transform(mp); 
20450   mp->cur_type=mp_transform_type;
20451   q=value(mp->cur_exp);
20452   switch (c) {
20453   @<For each of the eight cases, change the relevant fields of |cur_exp|
20454     and |goto done|;
20455     but do nothing if capsule |p| doesn't have the appropriate type@>;
20456   }; /* there are no other cases */
20457   mp_disp_err(mp, p,"Improper transformation argument");
20458 @.Improper transformation argument@>
20459   help3("The expression shown above has the wrong type,")
20460        ("so I can\'t transform anything using it.")
20461        ("Proceed, and I'll omit the transformation.");
20462   mp_put_get_error(mp);
20463 DONE: 
20464   mp_recycle_value(mp, p); 
20465   mp_free_node(mp, p,value_node_size);
20466 }
20467
20468 @ @<If the current transform is entirely known, ...@>=
20469 q=value(mp->cur_exp); r=q+transform_node_size;
20470 do {  
20471   r=r-2;
20472   if ( type(r)!=mp_known ) return;
20473 } while (r!=q);
20474 mp->txx=value(xx_part_loc(q));
20475 mp->txy=value(xy_part_loc(q));
20476 mp->tyx=value(yx_part_loc(q));
20477 mp->tyy=value(yy_part_loc(q));
20478 mp->tx=value(x_part_loc(q));
20479 mp->ty=value(y_part_loc(q));
20480 mp_flush_cur_exp(mp, 0)
20481
20482 @ @<For each of the eight cases...@>=
20483 case rotated_by:
20484   if ( type(p)==mp_known )
20485     @<Install sines and cosines, then |goto done|@>;
20486   break;
20487 case slanted_by:
20488   if ( type(p)>mp_pair_type ) { 
20489    mp_install(mp, xy_part_loc(q),p); goto DONE;
20490   };
20491   break;
20492 case scaled_by:
20493   if ( type(p)>mp_pair_type ) { 
20494     mp_install(mp, xx_part_loc(q),p); mp_install(mp, yy_part_loc(q),p); 
20495     goto DONE;
20496   };
20497   break;
20498 case shifted_by:
20499   if ( type(p)==mp_pair_type ) {
20500     r=value(p); mp_install(mp, x_part_loc(q),x_part_loc(r));
20501     mp_install(mp, y_part_loc(q),y_part_loc(r)); goto DONE;
20502   };
20503   break;
20504 case x_scaled:
20505   if ( type(p)>mp_pair_type ) {
20506     mp_install(mp, xx_part_loc(q),p); goto DONE;
20507   };
20508   break;
20509 case y_scaled:
20510   if ( type(p)>mp_pair_type ) {
20511     mp_install(mp, yy_part_loc(q),p); goto DONE;
20512   };
20513   break;
20514 case z_scaled:
20515   if ( type(p)==mp_pair_type )
20516     @<Install a complex multiplier, then |goto done|@>;
20517   break;
20518 case transformed_by:
20519   break;
20520   
20521
20522 @ @<Install sines and cosines, then |goto done|@>=
20523 { mp_n_sin_cos(mp, (value(p) % three_sixty_units)*16);
20524   value(xx_part_loc(q))=mp_round_fraction(mp, mp->n_cos);
20525   value(yx_part_loc(q))=mp_round_fraction(mp, mp->n_sin);
20526   value(xy_part_loc(q))=-value(yx_part_loc(q));
20527   value(yy_part_loc(q))=value(xx_part_loc(q));
20528   goto DONE;
20529 }
20530
20531 @ @<Install a complex multiplier, then |goto done|@>=
20532
20533   r=value(p);
20534   mp_install(mp, xx_part_loc(q),x_part_loc(r));
20535   mp_install(mp, yy_part_loc(q),x_part_loc(r));
20536   mp_install(mp, yx_part_loc(q),y_part_loc(r));
20537   if ( type(y_part_loc(r))==mp_known ) negate(value(y_part_loc(r)));
20538   else mp_negate_dep_list(mp, dep_list(y_part_loc(r)));
20539   mp_install(mp, xy_part_loc(q),y_part_loc(r));
20540   goto DONE;
20541 }
20542
20543 @ Procedure |set_up_known_trans| is like |set_up_trans|, but it
20544 insists that the transformation be entirely known.
20545
20546 @<Declare binary action...@>=
20547 void mp_set_up_known_trans (MP mp,quarterword c) { 
20548   mp_set_up_trans(mp, c);
20549   if ( mp->cur_type!=mp_known ) {
20550     exp_err("Transform components aren't all known");
20551 @.Transform components...@>
20552     help3("I'm unable to apply a partially specified transformation")
20553       ("except to a fully known pair or transform.")
20554       ("Proceed, and I'll omit the transformation.");
20555     mp_put_get_flush_error(mp, 0);
20556     mp->txx=unity; mp->txy=0; mp->tyx=0; mp->tyy=unity; 
20557     mp->tx=0; mp->ty=0;
20558   }
20559 }
20560
20561 @ Here's a procedure that applies the transform |txx..ty| to a pair of
20562 coordinates in locations |p| and~|q|.
20563
20564 @<Declare binary action...@>= 
20565 void mp_trans (MP mp,pointer p, pointer q) {
20566   scaled v; /* the new |x| value */
20567   v=mp_take_scaled(mp, mp->mem[p].sc,mp->txx)+
20568   mp_take_scaled(mp, mp->mem[q].sc,mp->txy)+mp->tx;
20569   mp->mem[q].sc=mp_take_scaled(mp, mp->mem[p].sc,mp->tyx)+
20570   mp_take_scaled(mp, mp->mem[q].sc,mp->tyy)+mp->ty;
20571   mp->mem[p].sc=v;
20572 }
20573
20574 @ The simplest transformation procedure applies a transform to all
20575 coordinates of a path.  The |path_trans(c)(p)| macro applies
20576 a transformation defined by |cur_exp| and the transform operator |c|
20577 to the path~|p|.
20578
20579 @d path_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20580                      mp_unstash_cur_exp(mp, (B)); 
20581                      mp_do_path_trans(mp, mp->cur_exp); }
20582
20583 @<Declare binary action...@>=
20584 void mp_do_path_trans (MP mp,pointer p) {
20585   pointer q; /* list traverser */
20586   q=p;
20587   do { 
20588     if ( left_type(q)!=mp_endpoint ) 
20589       mp_trans(mp, q+3,q+4); /* that's |left_x| and |left_y| */
20590     mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20591     if ( right_type(q)!=mp_endpoint ) 
20592       mp_trans(mp, q+5,q+6); /* that's |right_x| and |right_y| */
20593 @^data structure assumptions@>
20594     q=link(q);
20595   } while (q!=p);
20596 }
20597
20598 @ Transforming a pen is very similar, except that there are no |left_type|
20599 and |right_type| fields.
20600
20601 @d pen_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20602                     mp_unstash_cur_exp(mp, (B)); 
20603                     mp_do_pen_trans(mp, mp->cur_exp); }
20604
20605 @<Declare binary action...@>=
20606 void mp_do_pen_trans (MP mp,pointer p) {
20607   pointer q; /* list traverser */
20608   if ( pen_is_elliptical(p) ) {
20609     mp_trans(mp, p+3,p+4); /* that's |left_x| and |left_y| */
20610     mp_trans(mp, p+5,p+6); /* that's |right_x| and |right_y| */
20611   };
20612   q=p;
20613   do { 
20614     mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20615 @^data structure assumptions@>
20616     q=link(q);
20617   } while (q!=p);
20618 }
20619
20620 @ The next transformation procedure applies to edge structures. It will do
20621 any transformation, but the results may be substandard if the picture contains
20622 text that uses downloaded bitmap fonts.  The binary action procedure is
20623 |do_edges_trans|, but we also need a function that just scales a picture.
20624 That routine is |scale_edges|.  Both it and the underlying routine |edges_trans|
20625 should be thought of as procedures that update an edge structure |h|, except
20626 that they have to return a (possibly new) structure because of the need to call
20627 |private_edges|.
20628
20629 @<Declare binary action...@>=
20630 pointer mp_edges_trans (MP mp, pointer h) {
20631   pointer q; /* the object being transformed */
20632   pointer r,s; /* for list manipulation */
20633   scaled sx,sy; /* saved transformation parameters */
20634   scaled sqdet; /* square root of determinant for |dash_scale| */
20635   integer sgndet; /* sign of the determinant */
20636   scaled v; /* a temporary value */
20637   h=mp_private_edges(mp, h);
20638   sqdet=mp_sqrt_det(mp, mp->txx,mp->txy,mp->tyx,mp->tyy);
20639   sgndet=mp_ab_vs_cd(mp, mp->txx,mp->tyy,mp->txy,mp->tyx);
20640   if ( dash_list(h)!=null_dash ) {
20641     @<Try to transform the dash list of |h|@>;
20642   }
20643   @<Make the bounding box of |h| unknown if it can't be updated properly
20644     without scanning the whole structure@>;  
20645   q=link(dummy_loc(h));
20646   while ( q!=null ) { 
20647     @<Transform graphical object |q|@>;
20648     q=link(q);
20649   }
20650   return h;
20651 }
20652 void mp_do_edges_trans (MP mp,pointer p, quarterword c) { 
20653   mp_set_up_known_trans(mp, c);
20654   value(p)=mp_edges_trans(mp, value(p));
20655   mp_unstash_cur_exp(mp, p);
20656 }
20657 void mp_scale_edges (MP mp) { 
20658   mp->txx=mp->se_sf; mp->tyy=mp->se_sf;
20659   mp->txy=0; mp->tyx=0; mp->tx=0; mp->ty=0;
20660   mp->se_pic=mp_edges_trans(mp, mp->se_pic);
20661 }
20662
20663 @ @<Try to transform the dash list of |h|@>=
20664 if ( (mp->txy!=0)||(mp->tyx!=0)||
20665      (mp->ty!=0)||(abs(mp->txx)!=abs(mp->tyy))) {
20666   mp_flush_dash_list(mp, h);
20667 } else { 
20668   if ( mp->txx<0 ) { @<Reverse the dash list of |h|@>; } 
20669   @<Scale the dash list by |txx| and shift it by |tx|@>;
20670   dash_y(h)=mp_take_scaled(mp, dash_y(h),abs(mp->tyy));
20671 }
20672
20673 @ @<Reverse the dash list of |h|@>=
20674
20675   r=dash_list(h);
20676   dash_list(h)=null_dash;
20677   while ( r!=null_dash ) {
20678     s=r; r=link(r);
20679     v=start_x(s); start_x(s)=stop_x(s); stop_x(s)=v;
20680     link(s)=dash_list(h);
20681     dash_list(h)=s;
20682   }
20683 }
20684
20685 @ @<Scale the dash list by |txx| and shift it by |tx|@>=
20686 r=dash_list(h);
20687 while ( r!=null_dash ) {
20688   start_x(r)=mp_take_scaled(mp, start_x(r),mp->txx)+mp->tx;
20689   stop_x(r)=mp_take_scaled(mp, stop_x(r),mp->txx)+mp->tx;
20690   r=link(r);
20691 }
20692
20693 @ @<Make the bounding box of |h| unknown if it can't be updated properly...@>=
20694 if ( (mp->txx==0)&&(mp->tyy==0) ) {
20695   @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>;
20696 } else if ( (mp->txy!=0)||(mp->tyx!=0) ) {
20697   mp_init_bbox(mp, h);
20698   goto DONE1;
20699 }
20700 if ( minx_val(h)<=maxx_val(h) ) {
20701   @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift by
20702    |(tx,ty)|@>;
20703 }
20704 DONE1:
20705
20706
20707
20708 @ @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>=
20709
20710   v=minx_val(h); minx_val(h)=miny_val(h); miny_val(h)=v;
20711   v=maxx_val(h); maxx_val(h)=maxy_val(h); maxy_val(h)=v;
20712 }
20713
20714 @ The sum ``|txx+txy|'' is whichever of |txx| or |txy| is nonzero.  The other
20715 sum is similar.
20716
20717 @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift...@>=
20718
20719   minx_val(h)=mp_take_scaled(mp, minx_val(h),mp->txx+mp->txy)+mp->tx;
20720   maxx_val(h)=mp_take_scaled(mp, maxx_val(h),mp->txx+mp->txy)+mp->tx;
20721   miny_val(h)=mp_take_scaled(mp, miny_val(h),mp->tyx+mp->tyy)+mp->ty;
20722   maxy_val(h)=mp_take_scaled(mp, maxy_val(h),mp->tyx+mp->tyy)+mp->ty;
20723   if ( mp->txx+mp->txy<0 ) {
20724     v=minx_val(h); minx_val(h)=maxx_val(h); maxx_val(h)=v;
20725   }
20726   if ( mp->tyx+mp->tyy<0 ) {
20727     v=miny_val(h); miny_val(h)=maxy_val(h); maxy_val(h)=v;
20728   }
20729 }
20730
20731 @ Now we ready for the main task of transforming the graphical objects in edge
20732 structure~|h|.
20733
20734 @<Transform graphical object |q|@>=
20735 switch (type(q)) {
20736 case mp_fill_code: case mp_stroked_code: 
20737   mp_do_path_trans(mp, path_p(q));
20738   @<Transform |pen_p(q)|, making sure polygonal pens stay counter-clockwise@>;
20739   break;
20740 case mp_start_clip_code: case mp_start_bounds_code: 
20741   mp_do_path_trans(mp, path_p(q));
20742   break;
20743 case mp_text_code: 
20744   r=text_tx_loc(q);
20745   @<Transform the compact transformation starting at |r|@>;
20746   break;
20747 case mp_stop_clip_code: case mp_stop_bounds_code: 
20748   break;
20749 } /* there are no other cases */
20750
20751 @ Note that the shift parameters |(tx,ty)| apply only to the path being stroked.
20752 The |dash_scale| has to be adjusted  to scale the dash lengths in |dash_p(q)|
20753 since the \ps\ output procedures will try to compensate for the transformation
20754 we are applying to |pen_p(q)|.  Since this compensation is based on the square
20755 root of the determinant, |sqdet| is the appropriate factor.
20756
20757 @<Transform |pen_p(q)|, making sure...@>=
20758 if ( pen_p(q)!=null ) {
20759   sx=mp->tx; sy=mp->ty;
20760   mp->tx=0; mp->ty=0;
20761   mp_do_pen_trans(mp, pen_p(q));
20762   if ( ((type(q)==mp_stroked_code)&&(dash_p(q)!=null)) )
20763     dash_scale(q)=mp_take_scaled(mp, dash_scale(q),sqdet);
20764   if ( ! pen_is_elliptical(pen_p(q)) )
20765     if ( sgndet<0 )
20766       pen_p(q)=mp_make_pen(mp, mp_copy_path(mp, pen_p(q)),true); 
20767          /* this unreverses the pen */
20768   mp->tx=sx; mp->ty=sy;
20769 }
20770
20771 @ This uses the fact that transformations are stored in the order
20772 |(tx,ty,txx,txy,tyx,tyy)|.
20773 @^data structure assumptions@>
20774
20775 @<Transform the compact transformation starting at |r|@>=
20776 mp_trans(mp, r,r+1);
20777 sx=mp->tx; sy=mp->ty;
20778 mp->tx=0; mp->ty=0;
20779 mp_trans(mp, r+2,r+4);
20780 mp_trans(mp, r+3,r+5);
20781 mp->tx=sx; mp->ty=sy
20782
20783 @ The hard cases of transformation occur when big nodes are involved,
20784 and when some of their components are unknown.
20785
20786 @<Declare binary action...@>=
20787 @<Declare subroutines needed by |big_trans|@>;
20788 void mp_big_trans (MP mp,pointer p, quarterword c) {
20789   pointer q,r,pp,qq; /* list manipulation registers */
20790   small_number s; /* size of a big node */
20791   s=mp->big_node_size[type(p)]; q=value(p); r=q+s;
20792   do {  
20793     r=r-2;
20794     if ( type(r)!=mp_known ) {
20795       @<Transform an unknown big node and |return|@>;
20796     }
20797   } while (r!=q);
20798   @<Transform a known big node@>;
20799 }; /* node |p| will now be recycled by |do_binary| */
20800
20801 @ @<Transform an unknown big node and |return|@>=
20802
20803   mp_set_up_known_trans(mp, c); mp_make_exp_copy(mp, p); 
20804   r=value(mp->cur_exp);
20805   if ( mp->cur_type==mp_transform_type ) {
20806     mp_bilin1(mp, yy_part_loc(r),mp->tyy,xy_part_loc(q),mp->tyx,0);
20807     mp_bilin1(mp, yx_part_loc(r),mp->tyy,xx_part_loc(q),mp->tyx,0);
20808     mp_bilin1(mp, xy_part_loc(r),mp->txx,yy_part_loc(q),mp->txy,0);
20809     mp_bilin1(mp, xx_part_loc(r),mp->txx,yx_part_loc(q),mp->txy,0);
20810   }
20811   mp_bilin1(mp, y_part_loc(r),mp->tyy,x_part_loc(q),mp->tyx,mp->ty);
20812   mp_bilin1(mp, x_part_loc(r),mp->txx,y_part_loc(q),mp->txy,mp->tx);
20813   return;
20814 }
20815
20816 @ Let |p| point to a two-word value field inside a big node of |cur_exp|,
20817 and let |q| point to a another value field. The |bilin1| procedure
20818 replaces |p| by $p\cdot t+q\cdot u+\delta$.
20819
20820 @<Declare subroutines needed by |big_trans|@>=
20821 void mp_bilin1 (MP mp, pointer p, scaled t, pointer q, 
20822                 scaled u, scaled delta) {
20823   pointer r; /* list traverser */
20824   if ( t!=unity ) mp_dep_mult(mp, p,t,true);
20825   if ( u!=0 ) {
20826     if ( type(q)==mp_known ) {
20827       delta+=mp_take_scaled(mp, value(q),u);
20828     } else { 
20829       @<Ensure that |type(p)=mp_proto_dependent|@>;
20830       dep_list(p)=mp_p_plus_fq(mp, dep_list(p),u,dep_list(q),
20831                                mp_proto_dependent,type(q));
20832     }
20833   }
20834   if ( type(p)==mp_known ) {
20835     value(p)+=delta;
20836   } else {
20837     r=dep_list(p);
20838     while ( info(r)!=null ) r=link(r);
20839     delta+=value(r);
20840     if ( r!=dep_list(p) ) value(r)=delta;
20841     else { mp_recycle_value(mp, p); type(p)=mp_known; value(p)=delta; };
20842   }
20843   if ( mp->fix_needed ) mp_fix_dependencies(mp);
20844 }
20845
20846 @ @<Ensure that |type(p)=mp_proto_dependent|@>=
20847 if ( type(p)!=mp_proto_dependent ) {
20848   if ( type(p)==mp_known ) 
20849     mp_new_dep(mp, p,mp_const_dependency(mp, value(p)));
20850   else 
20851     dep_list(p)=mp_p_times_v(mp, dep_list(p),unity,mp_dependent,
20852                              mp_proto_dependent,true);
20853   type(p)=mp_proto_dependent;
20854 }
20855
20856 @ @<Transform a known big node@>=
20857 mp_set_up_trans(mp, c);
20858 if ( mp->cur_type==mp_known ) {
20859   @<Transform known by known@>;
20860 } else { 
20861   pp=mp_stash_cur_exp(mp); qq=value(pp);
20862   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20863   if ( mp->cur_type==mp_transform_type ) {
20864     mp_bilin2(mp, yy_part_loc(r),yy_part_loc(qq),
20865       value(xy_part_loc(q)),yx_part_loc(qq),null);
20866     mp_bilin2(mp, yx_part_loc(r),yy_part_loc(qq),
20867       value(xx_part_loc(q)),yx_part_loc(qq),null);
20868     mp_bilin2(mp, xy_part_loc(r),xx_part_loc(qq),
20869       value(yy_part_loc(q)),xy_part_loc(qq),null);
20870     mp_bilin2(mp, xx_part_loc(r),xx_part_loc(qq),
20871       value(yx_part_loc(q)),xy_part_loc(qq),null);
20872   };
20873   mp_bilin2(mp, y_part_loc(r),yy_part_loc(qq),
20874     value(x_part_loc(q)),yx_part_loc(qq),y_part_loc(qq));
20875   mp_bilin2(mp, x_part_loc(r),xx_part_loc(qq),
20876     value(y_part_loc(q)),xy_part_loc(qq),x_part_loc(qq));
20877   mp_recycle_value(mp, pp); mp_free_node(mp, pp,value_node_size);
20878 }
20879
20880 @ Let |p| be a |mp_proto_dependent| value whose dependency list ends
20881 at |dep_final|. The following procedure adds |v| times another
20882 numeric quantity to~|p|.
20883
20884 @<Declare subroutines needed by |big_trans|@>=
20885 void mp_add_mult_dep (MP mp,pointer p, scaled v, pointer r) { 
20886   if ( type(r)==mp_known ) {
20887     value(mp->dep_final)+=mp_take_scaled(mp, value(r),v);
20888   } else  { 
20889     dep_list(p)=mp_p_plus_fq(mp, dep_list(p),v,dep_list(r),
20890                                                          mp_proto_dependent,type(r));
20891     if ( mp->fix_needed ) mp_fix_dependencies(mp);
20892   }
20893 }
20894
20895 @ The |bilin2| procedure is something like |bilin1|, but with known
20896 and unknown quantities reversed. Parameter |p| points to a value field
20897 within the big node for |cur_exp|; and |type(p)=mp_known|. Parameters
20898 |t| and~|u| point to value fields elsewhere; so does parameter~|q|,
20899 unless it is |null| (which stands for zero). Location~|p| will be
20900 replaced by $p\cdot t+v\cdot u+q$.
20901
20902 @<Declare subroutines needed by |big_trans|@>=
20903 void mp_bilin2 (MP mp,pointer p, pointer t, scaled v, 
20904                 pointer u, pointer q) {
20905   scaled vv; /* temporary storage for |value(p)| */
20906   vv=value(p); type(p)=mp_proto_dependent;
20907   mp_new_dep(mp, p,mp_const_dependency(mp, 0)); /* this sets |dep_final| */
20908   if ( vv!=0 ) 
20909     mp_add_mult_dep(mp, p,vv,t); /* |dep_final| doesn't change */
20910   if ( v!=0 ) mp_add_mult_dep(mp, p,v,u);
20911   if ( q!=null ) mp_add_mult_dep(mp, p,unity,q);
20912   if ( dep_list(p)==mp->dep_final ) {
20913     vv=value(mp->dep_final); mp_recycle_value(mp, p);
20914     type(p)=mp_known; value(p)=vv;
20915   }
20916 }
20917
20918 @ @<Transform known by known@>=
20919
20920   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20921   if ( mp->cur_type==mp_transform_type ) {
20922     mp_bilin3(mp, yy_part_loc(r),mp->tyy,value(xy_part_loc(q)),mp->tyx,0);
20923     mp_bilin3(mp, yx_part_loc(r),mp->tyy,value(xx_part_loc(q)),mp->tyx,0);
20924     mp_bilin3(mp, xy_part_loc(r),mp->txx,value(yy_part_loc(q)),mp->txy,0);
20925     mp_bilin3(mp, xx_part_loc(r),mp->txx,value(yx_part_loc(q)),mp->txy,0);
20926   }
20927   mp_bilin3(mp, y_part_loc(r),mp->tyy,value(x_part_loc(q)),mp->tyx,mp->ty);
20928   mp_bilin3(mp, x_part_loc(r),mp->txx,value(y_part_loc(q)),mp->txy,mp->tx);
20929 }
20930
20931 @ Finally, in |bilin3| everything is |known|.
20932
20933 @<Declare subroutines needed by |big_trans|@>=
20934 void mp_bilin3 (MP mp,pointer p, scaled t, 
20935                scaled v, scaled u, scaled delta) { 
20936   if ( t!=unity )
20937     delta+=mp_take_scaled(mp, value(p),t);
20938   else 
20939     delta+=value(p);
20940   if ( u!=0 ) value(p)=delta+mp_take_scaled(mp, v,u);
20941   else value(p)=delta;
20942 }
20943
20944 @ @<Additional cases of binary operators@>=
20945 case concatenate: 
20946   if ( (mp->cur_type==mp_string_type)&&(type(p)==mp_string_type) ) mp_cat(mp, p);
20947   else mp_bad_binary(mp, p,concatenate);
20948   break;
20949 case substring_of: 
20950   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_string_type) )
20951     mp_chop_string(mp, value(p));
20952   else mp_bad_binary(mp, p,substring_of);
20953   break;
20954 case subpath_of: 
20955   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
20956   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_path_type) )
20957     mp_chop_path(mp, value(p));
20958   else mp_bad_binary(mp, p,subpath_of);
20959   break;
20960
20961 @ @<Declare binary action...@>=
20962 void mp_cat (MP mp,pointer p) {
20963   str_number a,b; /* the strings being concatenated */
20964   pool_pointer k; /* index into |str_pool| */
20965   a=value(p); b=mp->cur_exp; str_room(length(a)+length(b));
20966   for (k=mp->str_start[a];k<=str_stop(a)-1;k++) {
20967     append_char(mp->str_pool[k]);
20968   }
20969   for (k=mp->str_start[b];k<=str_stop(b)-1;k++) {
20970     append_char(mp->str_pool[k]);
20971   }
20972   mp->cur_exp=mp_make_string(mp); delete_str_ref(b);
20973 }
20974
20975 @ @<Declare binary action...@>=
20976 void mp_chop_string (MP mp,pointer p) {
20977   integer a, b; /* start and stop points */
20978   integer l; /* length of the original string */
20979   integer k; /* runs from |a| to |b| */
20980   str_number s; /* the original string */
20981   boolean reversed; /* was |a>b|? */
20982   a=mp_round_unscaled(mp, value(x_part_loc(p)));
20983   b=mp_round_unscaled(mp, value(y_part_loc(p)));
20984   if ( a<=b ) reversed=false;
20985   else  { reversed=true; k=a; a=b; b=k; };
20986   s=mp->cur_exp; l=length(s);
20987   if ( a<0 ) { 
20988     a=0;
20989     if ( b<0 ) b=0;
20990   }
20991   if ( b>l ) { 
20992     b=l;
20993     if ( a>l ) a=l;
20994   }
20995   str_room(b-a);
20996   if ( reversed ) {
20997     for (k=mp->str_start[s]+b-1;k>=mp->str_start[s]+a;k--)  {
20998       append_char(mp->str_pool[k]);
20999     }
21000   } else  {
21001     for (k=mp->str_start[s]+a;k<=mp->str_start[s]+b-1;k++)  {
21002       append_char(mp->str_pool[k]);
21003     }
21004   }
21005   mp->cur_exp=mp_make_string(mp); delete_str_ref(s);
21006 }
21007
21008 @ @<Declare binary action...@>=
21009 void mp_chop_path (MP mp,pointer p) {
21010   pointer q; /* a knot in the original path */
21011   pointer pp,qq,rr,ss; /* link variables for copies of path nodes */
21012   scaled a,b,k,l; /* indices for chopping */
21013   boolean reversed; /* was |a>b|? */
21014   l=mp_path_length(mp); a=value(x_part_loc(p)); b=value(y_part_loc(p));
21015   if ( a<=b ) reversed=false;
21016   else  { reversed=true; k=a; a=b; b=k; };
21017   @<Dispense with the cases |a<0| and/or |b>l|@>;
21018   q=mp->cur_exp;
21019   while ( a>=unity ) {
21020     q=link(q); a=a-unity; b=b-unity;
21021   }
21022   if ( b==a ) {
21023     @<Construct a path from |pp| to |qq| of length zero@>; 
21024   } else { 
21025     @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>; 
21026   }
21027   left_type(pp)=mp_endpoint; right_type(qq)=mp_endpoint; link(qq)=pp;
21028   mp_toss_knot_list(mp, mp->cur_exp);
21029   if ( reversed ) {
21030     mp->cur_exp=link(mp_htap_ypoc(mp, pp)); mp_toss_knot_list(mp, pp);
21031   } else {
21032     mp->cur_exp=pp;
21033   }
21034 }
21035
21036 @ @<Dispense with the cases |a<0| and/or |b>l|@>=
21037 if ( a<0 ) {
21038   if ( left_type(mp->cur_exp)==mp_endpoint ) {
21039     a=0; if ( b<0 ) b=0;
21040   } else  {
21041     do {  a=a+l; b=b+l; } while (a<0); /* a cycle always has length |l>0| */
21042   }
21043 }
21044 if ( b>l ) {
21045   if ( left_type(mp->cur_exp)==mp_endpoint ) {
21046     b=l; if ( a>l ) a=l;
21047   } else {
21048     while ( a>=l ) { 
21049       a=a-l; b=b-l;
21050     }
21051   }
21052 }
21053
21054 @ @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>=
21055
21056   pp=mp_copy_knot(mp, q); qq=pp;
21057   do {  
21058     q=link(q); rr=qq; qq=mp_copy_knot(mp, q); link(rr)=qq; b=b-unity;
21059   } while (b>0);
21060   if ( a>0 ) {
21061     ss=pp; pp=link(pp);
21062     mp_split_cubic(mp, ss,a*010000); pp=link(ss);
21063     mp_free_node(mp, ss,knot_node_size);
21064     if ( rr==ss ) {
21065       b=mp_make_scaled(mp, b,unity-a); rr=pp;
21066     }
21067   }
21068   if ( b<0 ) {
21069     mp_split_cubic(mp, rr,(b+unity)*010000);
21070     mp_free_node(mp, qq,knot_node_size);
21071     qq=link(rr);
21072   }
21073 }
21074
21075 @ @<Construct a path from |pp| to |qq| of length zero@>=
21076
21077   if ( a>0 ) { mp_split_cubic(mp, q,a*010000); q=link(q); };
21078   pp=mp_copy_knot(mp, q); qq=pp;
21079 }
21080
21081 @ @<Additional cases of binary operators@>=
21082 case point_of: case precontrol_of: case postcontrol_of: 
21083   if ( mp->cur_type==mp_pair_type )
21084      mp_pair_to_path(mp);
21085   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
21086     mp_find_point(mp, value(p),c);
21087   else 
21088     mp_bad_binary(mp, p,c);
21089   break;
21090 case pen_offset_of: 
21091   if ( (mp->cur_type==mp_pen_type)&& mp_nice_pair(mp, p,type(p)) )
21092     mp_set_up_offset(mp, value(p));
21093   else 
21094     mp_bad_binary(mp, p,pen_offset_of);
21095   break;
21096 case direction_time_of: 
21097   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21098   if ( (mp->cur_type==mp_path_type)&& mp_nice_pair(mp, p,type(p)) )
21099     mp_set_up_direction_time(mp, value(p));
21100   else 
21101     mp_bad_binary(mp, p,direction_time_of);
21102   break;
21103
21104 @ @<Declare binary action...@>=
21105 void mp_set_up_offset (MP mp,pointer p) { 
21106   mp_find_offset(mp, value(x_part_loc(p)),value(y_part_loc(p)),mp->cur_exp);
21107   mp_pair_value(mp, mp->cur_x,mp->cur_y);
21108 }
21109 void mp_set_up_direction_time (MP mp,pointer p) { 
21110   mp_flush_cur_exp(mp, mp_find_direction_time(mp, value(x_part_loc(p)),
21111   value(y_part_loc(p)),mp->cur_exp));
21112 }
21113
21114 @ @<Declare binary action...@>=
21115 void mp_find_point (MP mp,scaled v, quarterword c) {
21116   pointer p; /* the path */
21117   scaled n; /* its length */
21118   p=mp->cur_exp;
21119   if ( left_type(p)==mp_endpoint ) n=-unity; else n=0;
21120   do {  p=link(p); n=n+unity; } while (p!=mp->cur_exp);
21121   if ( n==0 ) { 
21122     v=0; 
21123   } else if ( v<0 ) {
21124     if ( left_type(p)==mp_endpoint ) v=0;
21125     else v=n-1-((-v-1) % n);
21126   } else if ( v>n ) {
21127     if ( left_type(p)==mp_endpoint ) v=n;
21128     else v=v % n;
21129   }
21130   p=mp->cur_exp;
21131   while ( v>=unity ) { p=link(p); v=v-unity;  };
21132   if ( v!=0 ) {
21133      @<Insert a fractional node by splitting the cubic@>;
21134   }
21135   @<Set the current expression to the desired path coordinates@>;
21136 }
21137
21138 @ @<Insert a fractional node...@>=
21139 { mp_split_cubic(mp, p,v*010000); p=link(p); }
21140
21141 @ @<Set the current expression to the desired path coordinates...@>=
21142 switch (c) {
21143 case point_of: 
21144   mp_pair_value(mp, x_coord(p),y_coord(p));
21145   break;
21146 case precontrol_of: 
21147   if ( left_type(p)==mp_endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
21148   else mp_pair_value(mp, left_x(p),left_y(p));
21149   break;
21150 case postcontrol_of: 
21151   if ( right_type(p)==mp_endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
21152   else mp_pair_value(mp, right_x(p),right_y(p));
21153   break;
21154 } /* there are no other cases */
21155
21156 @ @<Additional cases of binary operators@>=
21157 case arc_time_of: 
21158   if ( mp->cur_type==mp_pair_type )
21159      mp_pair_to_path(mp);
21160   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
21161     mp_flush_cur_exp(mp, mp_get_arc_time(mp, mp->cur_exp,value(p)));
21162   else 
21163     mp_bad_binary(mp, p,c);
21164   break;
21165
21166 @ @<Additional cases of bin...@>=
21167 case intersect: 
21168   if ( type(p)==mp_pair_type ) {
21169     q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p);
21170     mp_pair_to_path(mp); p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
21171   };
21172   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21173   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_path_type) ) {
21174     mp_path_intersection(mp, value(p),mp->cur_exp);
21175     mp_pair_value(mp, mp->cur_t,mp->cur_tt);
21176   } else {
21177     mp_bad_binary(mp, p,intersect);
21178   }
21179   break;
21180
21181 @ @<Additional cases of bin...@>=
21182 case in_font:
21183   if ( (mp->cur_type!=mp_string_type)||(type(p)!=mp_string_type)) 
21184     mp_bad_binary(mp, p,in_font);
21185   else { mp_do_infont(mp, p); return; }
21186   break;
21187
21188 @ Function |new_text_node| owns the reference count for its second argument
21189 (the text string) but not its first (the font name).
21190
21191 @<Declare binary action...@>=
21192 void mp_do_infont (MP mp,pointer p) {
21193   pointer q;
21194   q=mp_get_node(mp, edge_header_size);
21195   mp_init_edges(mp, q);
21196   link(obj_tail(q))=mp_new_text_node(mp, str(mp->cur_exp),value(p));
21197   obj_tail(q)=link(obj_tail(q));
21198   mp_free_node(mp, p,value_node_size);
21199   mp_flush_cur_exp(mp, q);
21200   mp->cur_type=mp_picture_type;
21201 }
21202
21203 @* \[40] Statements and commands.
21204 The chief executive of \MP\ is the |do_statement| routine, which
21205 contains the master switch that causes all the various pieces of \MP\
21206 to do their things, in the right order.
21207
21208 In a sense, this is the grand climax of the program: It applies all the
21209 tools that we have worked so hard to construct. In another sense, this is
21210 the messiest part of the program: It necessarily refers to other pieces
21211 of code all over the place, so that a person can't fully understand what is
21212 going on without paging back and forth to be reminded of conventions that
21213 are defined elsewhere. We are now at the hub of the web.
21214
21215 The structure of |do_statement| itself is quite simple.  The first token
21216 of the statement is fetched using |get_x_next|.  If it can be the first
21217 token of an expression, we look for an equation, an assignment, or a
21218 title. Otherwise we use a \&{case} construction to branch at high speed to
21219 the appropriate routine for various and sundry other types of commands,
21220 each of which has an ``action procedure'' that does the necessary work.
21221
21222 The program uses the fact that
21223 $$\hbox{|min_primary_command=max_statement_command=type_name|}$$
21224 to interpret a statement that starts with, e.g., `\&{string}',
21225 as a type declaration rather than a boolean expression.
21226
21227 @c void mp_do_statement (MP mp) { /* governs \MP's activities */
21228   mp->cur_type=mp_vacuous; mp_get_x_next(mp);
21229   if ( mp->cur_cmd>max_primary_command ) {
21230     @<Worry about bad statement@>;
21231   } else if ( mp->cur_cmd>max_statement_command ) {
21232     @<Do an equation, assignment, title, or
21233      `$\langle\,$expression$\,\rangle\,$\&{endgroup}'@>;
21234   } else {
21235     @<Do a statement that doesn't begin with an expression@>;
21236   }
21237   if ( mp->cur_cmd<semicolon )
21238     @<Flush unparsable junk that was found after the statement@>;
21239   mp->error_count=0;
21240 }
21241
21242 @ @<Declarations@>=
21243 @<Declare action procedures for use by |do_statement|@>;
21244
21245 @ The only command codes |>max_primary_command| that can be present
21246 at the beginning of a statement are |semicolon| and higher; these
21247 occur when the statement is null.
21248
21249 @<Worry about bad statement@>=
21250
21251   if ( mp->cur_cmd<semicolon ) {
21252     print_err("A statement can't begin with `");
21253 @.A statement can't begin with x@>
21254     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); mp_print_char(mp, '\'');
21255     help5("I was looking for the beginning of a new statement.")
21256       ("If you just proceed without changing anything, I'll ignore")
21257       ("everything up to the next `;'. Please insert a semicolon")
21258       ("now in front of anything that you don't want me to delete.")
21259       ("(See Chapter 27 of The METAFONTbook for an example.)");
21260 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21261     mp_back_error(mp); mp_get_x_next(mp);
21262   }
21263 }
21264
21265 @ The help message printed here says that everything is flushed up to
21266 a semicolon, but actually the commands |end_group| and |stop| will
21267 also terminate a statement.
21268
21269 @<Flush unparsable junk that was found after the statement@>=
21270
21271   print_err("Extra tokens will be flushed");
21272 @.Extra tokens will be flushed@>
21273   help6("I've just read as much of that statement as I could fathom,")
21274        ("so a semicolon should have been next. It's very puzzling...")
21275        ("but I'll try to get myself back together, by ignoring")
21276        ("everything up to the next `;'. Please insert a semicolon")
21277        ("now in front of anything that you don't want me to delete.")
21278        ("(See Chapter 27 of The METAFONTbook for an example.)");
21279 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21280   mp_back_error(mp); mp->scanner_status=flushing;
21281   do {  
21282     get_t_next;
21283     @<Decrease the string reference count...@>;
21284   } while (! end_of_statement); /* |cur_cmd=semicolon|, |end_group|, or |stop| */
21285   mp->scanner_status=normal;
21286 }
21287
21288 @ If |do_statement| ends with |cur_cmd=end_group|, we should have
21289 |cur_type=mp_vacuous| unless the statement was simply an expression;
21290 in the latter case, |cur_type| and |cur_exp| should represent that
21291 expression.
21292
21293 @<Do a statement that doesn't...@>=
21294
21295   if ( mp->internal[mp_tracing_commands]>0 ) 
21296     show_cur_cmd_mod;
21297   switch (mp->cur_cmd ) {
21298   case type_name:mp_do_type_declaration(mp); break;
21299   case macro_def:
21300     if ( mp->cur_mod>var_def ) mp_make_op_def(mp);
21301     else if ( mp->cur_mod>end_def ) mp_scan_def(mp);
21302      break;
21303   @<Cases of |do_statement| that invoke particular commands@>;
21304   } /* there are no other cases */
21305   mp->cur_type=mp_vacuous;
21306 }
21307
21308 @ The most important statements begin with expressions.
21309
21310 @<Do an equation, assignment, title, or...@>=
21311
21312   mp->var_flag=assignment; mp_scan_expression(mp);
21313   if ( mp->cur_cmd<end_group ) {
21314     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21315     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21316     else if ( mp->cur_type==mp_string_type ) {@<Do a title@> ; }
21317     else if ( mp->cur_type!=mp_vacuous ){ 
21318       exp_err("Isolated expression");
21319 @.Isolated expression@>
21320       help3("I couldn't find an `=' or `:=' after the")
21321         ("expression that is shown above this error message,")
21322         ("so I guess I'll just ignore it and carry on.");
21323       mp_put_get_error(mp);
21324     }
21325     mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous;
21326   }
21327 }
21328
21329 @ @<Do a title@>=
21330
21331   if ( mp->internal[mp_tracing_titles]>0 ) {
21332     mp_print_nl(mp, "");  mp_print_str(mp, mp->cur_exp); update_terminal;
21333   }
21334 }
21335
21336 @ Equations and assignments are performed by the pair of mutually recursive
21337 @^recursion@>
21338 routines |do_equation| and |do_assignment|. These routines are called when
21339 |cur_cmd=equals| and when |cur_cmd=assignment|, respectively; the left-hand
21340 side is in |cur_type| and |cur_exp|, while the right-hand side is yet
21341 to be scanned. After the routines are finished, |cur_type| and |cur_exp|
21342 will be equal to the right-hand side (which will normally be equal
21343 to the left-hand side).
21344
21345 @<Declare action procedures for use by |do_statement|@>=
21346 @<Declare the procedure called |try_eq|@>;
21347 @<Declare the procedure called |make_eq|@>;
21348 void mp_do_equation (MP mp) ;
21349
21350 @ @c
21351 void mp_do_equation (MP mp) {
21352   pointer lhs; /* capsule for the left-hand side */
21353   pointer p; /* temporary register */
21354   lhs=mp_stash_cur_exp(mp); mp_get_x_next(mp); 
21355   mp->var_flag=assignment; mp_scan_expression(mp);
21356   if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21357   else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21358   if ( mp->internal[mp_tracing_commands]>two ) 
21359     @<Trace the current equation@>;
21360   if ( mp->cur_type==mp_unknown_path ) if ( type(lhs)==mp_pair_type ) {
21361     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, lhs); lhs=p;
21362   }; /* in this case |make_eq| will change the pair to a path */
21363   mp_make_eq(mp, lhs); /* equate |lhs| to |(cur_type,cur_exp)| */
21364 }
21365
21366 @ And |do_assignment| is similar to |do_expression|:
21367
21368 @<Declarations@>=
21369 void mp_do_assignment (MP mp);
21370
21371 @ @<Declare action procedures for use by |do_statement|@>=
21372 void mp_do_assignment (MP mp) ;
21373
21374 @ @c
21375 void mp_do_assignment (MP mp) {
21376   pointer lhs; /* token list for the left-hand side */
21377   pointer p; /* where the left-hand value is stored */
21378   pointer q; /* temporary capsule for the right-hand value */
21379   if ( mp->cur_type!=mp_token_list ) { 
21380     exp_err("Improper `:=' will be changed to `='");
21381 @.Improper `:='@>
21382     help2("I didn't find a variable name at the left of the `:=',")
21383       ("so I'm going to pretend that you said `=' instead.");
21384     mp_error(mp); mp_do_equation(mp);
21385   } else { 
21386     lhs=mp->cur_exp; mp->cur_type=mp_vacuous;
21387     mp_get_x_next(mp); mp->var_flag=assignment; mp_scan_expression(mp);
21388     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21389     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21390     if ( mp->internal[mp_tracing_commands]>two ) 
21391       @<Trace the current assignment@>;
21392     if ( info(lhs)>hash_end ) {
21393       @<Assign the current expression to an internal variable@>;
21394     } else  {
21395       @<Assign the current expression to the variable |lhs|@>;
21396     }
21397     mp_flush_node_list(mp, lhs);
21398   }
21399 }
21400
21401 @ @<Trace the current equation@>=
21402
21403   mp_begin_diagnostic(mp); mp_print_nl(mp, "{("); mp_print_exp(mp,lhs,0);
21404   mp_print(mp,")=("); mp_print_exp(mp,null,0); 
21405   mp_print(mp,")}"); mp_end_diagnostic(mp, false);
21406 }
21407
21408 @ @<Trace the current assignment@>=
21409
21410   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
21411   if ( info(lhs)>hash_end ) 
21412      mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21413   else 
21414      mp_show_token_list(mp, lhs,null,1000,0);
21415   mp_print(mp, ":="); mp_print_exp(mp, null,0); 
21416   mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
21417 }
21418
21419 @ @<Assign the current expression to an internal variable@>=
21420 if ( mp->cur_type==mp_known )  {
21421   mp->internal[info(lhs)-(hash_end)]=mp->cur_exp;
21422 } else { 
21423   exp_err("Internal quantity `");
21424 @.Internal quantity...@>
21425   mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21426   mp_print(mp, "' must receive a known value");
21427   help2("I can\'t set an internal quantity to anything but a known")
21428     ("numeric value, so I'll have to ignore this assignment.");
21429   mp_put_get_error(mp);
21430 }
21431
21432 @ @<Assign the current expression to the variable |lhs|@>=
21433
21434   p=mp_find_variable(mp, lhs);
21435   if ( p!=null ) {
21436     q=mp_stash_cur_exp(mp); mp->cur_type=mp_und_type(mp, p); 
21437     mp_recycle_value(mp, p);
21438     type(p)=mp->cur_type; value(p)=null; mp_make_exp_copy(mp, p);
21439     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q); mp_make_eq(mp, p);
21440   } else  { 
21441     mp_obliterated(mp, lhs); mp_put_get_error(mp);
21442   }
21443 }
21444
21445
21446 @ And now we get to the nitty-gritty. The |make_eq| procedure is given
21447 a pointer to a capsule that is to be equated to the current expression.
21448
21449 @<Declare the procedure called |make_eq|@>=
21450 void mp_make_eq (MP mp,pointer lhs) ;
21451
21452
21453
21454 @c void mp_make_eq (MP mp,pointer lhs) {
21455   small_number t; /* type of the left-hand side */
21456   pointer p,q; /* pointers inside of big nodes */
21457   integer v=0; /* value of the left-hand side */
21458 RESTART: 
21459   t=type(lhs);
21460   if ( t<=mp_pair_type ) v=value(lhs);
21461   switch (t) {
21462   @<For each type |t|, make an equation and |goto done| unless |cur_type|
21463     is incompatible with~|t|@>;
21464   } /* all cases have been listed */
21465   @<Announce that the equation cannot be performed@>;
21466 DONE:
21467   check_arith; mp_recycle_value(mp, lhs); 
21468   mp_free_node(mp, lhs,value_node_size);
21469 }
21470
21471 @ @<Announce that the equation cannot be performed@>=
21472 mp_disp_err(mp, lhs,""); 
21473 exp_err("Equation cannot be performed (");
21474 @.Equation cannot be performed@>
21475 if ( type(lhs)<=mp_pair_type ) mp_print_type(mp, type(lhs));
21476 else mp_print(mp, "numeric");
21477 mp_print_char(mp, '=');
21478 if ( mp->cur_type<=mp_pair_type ) mp_print_type(mp, mp->cur_type);
21479 else mp_print(mp, "numeric");
21480 mp_print_char(mp, ')');
21481 help2("I'm sorry, but I don't know how to make such things equal.")
21482      ("(See the two expressions just above the error message.)");
21483 mp_put_get_error(mp)
21484
21485 @ @<For each type |t|, make an equation and |goto done| unless...@>=
21486 case mp_boolean_type: case mp_string_type: case mp_pen_type:
21487 case mp_path_type: case mp_picture_type:
21488   if ( mp->cur_type==t+unknown_tag ) { 
21489     mp_nonlinear_eq(mp, v,mp->cur_exp,false); goto DONE;
21490   } else if ( mp->cur_type==t ) {
21491     @<Report redundant or inconsistent equation and |goto done|@>;
21492   }
21493   break;
21494 case unknown_types:
21495   if ( mp->cur_type==t-unknown_tag ) { 
21496     mp_nonlinear_eq(mp, mp->cur_exp,lhs,true); goto DONE;
21497   } else if ( mp->cur_type==t ) { 
21498     mp_ring_merge(mp, lhs,mp->cur_exp); goto DONE;
21499   } else if ( mp->cur_type==mp_pair_type ) {
21500     if ( t==mp_unknown_path ) { 
21501      mp_pair_to_path(mp); goto RESTART;
21502     };
21503   }
21504   break;
21505 case mp_transform_type: case mp_color_type:
21506 case mp_cmykcolor_type: case mp_pair_type:
21507   if ( mp->cur_type==t ) {
21508     @<Do multiple equations and |goto done|@>;
21509   }
21510   break;
21511 case mp_known: case mp_dependent:
21512 case mp_proto_dependent: case mp_independent:
21513   if ( mp->cur_type>=mp_known ) { 
21514     mp_try_eq(mp, lhs,null); goto DONE;
21515   };
21516   break;
21517 case mp_vacuous:
21518   break;
21519
21520 @ @<Report redundant or inconsistent equation and |goto done|@>=
21521
21522   if ( mp->cur_type<=mp_string_type ) {
21523     if ( mp->cur_type==mp_string_type ) {
21524       if ( mp_str_vs_str(mp, v,mp->cur_exp)!=0 ) {
21525         goto NOT_FOUND;
21526       }
21527     } else if ( v!=mp->cur_exp ) {
21528       goto NOT_FOUND;
21529     }
21530     @<Exclaim about a redundant equation@>; goto DONE;
21531   }
21532   print_err("Redundant or inconsistent equation");
21533 @.Redundant or inconsistent equation@>
21534   help2("An equation between already-known quantities can't help.")
21535        ("But don't worry; continue and I'll just ignore it.");
21536   mp_put_get_error(mp); goto DONE;
21537 NOT_FOUND: 
21538   print_err("Inconsistent equation");
21539 @.Inconsistent equation@>
21540   help2("The equation I just read contradicts what was said before.")
21541        ("But don't worry; continue and I'll just ignore it.");
21542   mp_put_get_error(mp); goto DONE;
21543 }
21544
21545 @ @<Do multiple equations and |goto done|@>=
21546
21547   p=v+mp->big_node_size[t]; 
21548   q=value(mp->cur_exp)+mp->big_node_size[t];
21549   do {  
21550     p=p-2; q=q-2; mp_try_eq(mp, p,q);
21551   } while (p!=v);
21552   goto DONE;
21553 }
21554
21555 @ The first argument to |try_eq| is the location of a value node
21556 in a capsule that will soon be recycled. The second argument is
21557 either a location within a pair or transform node pointed to by
21558 |cur_exp|, or it is |null| (which means that |cur_exp| itself
21559 serves as the second argument). The idea is to leave |cur_exp| unchanged,
21560 but to equate the two operands.
21561
21562 @<Declare the procedure called |try_eq|@>=
21563 void mp_try_eq (MP mp,pointer l, pointer r) ;
21564
21565
21566 @c void mp_try_eq (MP mp,pointer l, pointer r) {
21567   pointer p; /* dependency list for right operand minus left operand */
21568   int t; /* the type of list |p| */
21569   pointer q; /* the constant term of |p| is here */
21570   pointer pp; /* dependency list for right operand */
21571   int tt; /* the type of list |pp| */
21572   boolean copied; /* have we copied a list that ought to be recycled? */
21573   @<Remove the left operand from its container, negate it, and
21574     put it into dependency list~|p| with constant term~|q|@>;
21575   @<Add the right operand to list |p|@>;
21576   if ( info(p)==null ) {
21577     @<Deal with redundant or inconsistent equation@>;
21578   } else { 
21579     mp_linear_eq(mp, p,t);
21580     if ( r==null ) if ( mp->cur_type!=mp_known ) {
21581       if ( type(mp->cur_exp)==mp_known ) {
21582         pp=mp->cur_exp; mp->cur_exp=value(mp->cur_exp); mp->cur_type=mp_known;
21583         mp_free_node(mp, pp,value_node_size);
21584       }
21585     }
21586   }
21587 }
21588
21589 @ @<Remove the left operand from its container, negate it, and...@>=
21590 t=type(l);
21591 if ( t==mp_known ) { 
21592   t=mp_dependent; p=mp_const_dependency(mp, -value(l)); q=p;
21593 } else if ( t==mp_independent ) {
21594   t=mp_dependent; p=mp_single_dependency(mp, l); negate(value(p));
21595   q=mp->dep_final;
21596 } else { 
21597   p=dep_list(l); q=p;
21598   while (1) { 
21599     negate(value(q));
21600     if ( info(q)==null ) break;
21601     q=link(q);
21602   }
21603   link(prev_dep(l))=link(q); prev_dep(link(q))=prev_dep(l);
21604   type(l)=mp_known;
21605 }
21606
21607 @ @<Deal with redundant or inconsistent equation@>=
21608
21609   if ( abs(value(p))>64 ) { /* off by .001 or more */
21610     print_err("Inconsistent equation");
21611 @.Inconsistent equation@>
21612     mp_print(mp, " (off by "); mp_print_scaled(mp, value(p)); 
21613     mp_print_char(mp, ')');
21614     help2("The equation I just read contradicts what was said before.")
21615       ("But don't worry; continue and I'll just ignore it.");
21616     mp_put_get_error(mp);
21617   } else if ( r==null ) {
21618     @<Exclaim about a redundant equation@>;
21619   }
21620   mp_free_node(mp, p,dep_node_size);
21621 }
21622
21623 @ @<Add the right operand to list |p|@>=
21624 if ( r==null ) {
21625   if ( mp->cur_type==mp_known ) {
21626     value(q)=value(q)+mp->cur_exp; goto DONE1;
21627   } else { 
21628     tt=mp->cur_type;
21629     if ( tt==mp_independent ) pp=mp_single_dependency(mp, mp->cur_exp);
21630     else pp=dep_list(mp->cur_exp);
21631   } 
21632 } else {
21633   if ( type(r)==mp_known ) {
21634     value(q)=value(q)+value(r); goto DONE1;
21635   } else { 
21636     tt=type(r);
21637     if ( tt==mp_independent ) pp=mp_single_dependency(mp, r);
21638     else pp=dep_list(r);
21639   }
21640 }
21641 if ( tt!=mp_independent ) copied=false;
21642 else  { copied=true; tt=mp_dependent; };
21643 @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>;
21644 if ( copied ) mp_flush_node_list(mp, pp);
21645 DONE1:
21646
21647 @ @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>=
21648 mp->watch_coefs=false;
21649 if ( t==tt ) {
21650   p=mp_p_plus_q(mp, p,pp,t);
21651 } else if ( t==mp_proto_dependent ) {
21652   p=mp_p_plus_fq(mp, p,unity,pp,mp_proto_dependent,mp_dependent);
21653 } else { 
21654   q=p;
21655   while ( info(q)!=null ) {
21656     value(q)=mp_round_fraction(mp, value(q)); q=link(q);
21657   }
21658   t=mp_proto_dependent; p=mp_p_plus_q(mp, p,pp,t);
21659 }
21660 mp->watch_coefs=true;
21661
21662 @ Our next goal is to process type declarations. For this purpose it's
21663 convenient to have a procedure that scans a $\langle\,$declared
21664 variable$\,\rangle$ and returns the corresponding token list. After the
21665 following procedure has acted, the token after the declared variable
21666 will have been scanned, so it will appear in |cur_cmd|, |cur_mod|,
21667 and~|cur_sym|.
21668
21669 @<Declare the function called |scan_declared_variable|@>=
21670 pointer mp_scan_declared_variable (MP mp) {
21671   pointer x; /* hash address of the variable's root */
21672   pointer h,t; /* head and tail of the token list to be returned */
21673   pointer l; /* hash address of left bracket */
21674   mp_get_symbol(mp); x=mp->cur_sym;
21675   if ( mp->cur_cmd!=tag_token ) mp_clear_symbol(mp, x,false);
21676   h=mp_get_avail(mp); info(h)=x; t=h;
21677   while (1) { 
21678     mp_get_x_next(mp);
21679     if ( mp->cur_sym==0 ) break;
21680     if ( mp->cur_cmd!=tag_token ) if ( mp->cur_cmd!=internal_quantity)  {
21681       if ( mp->cur_cmd==left_bracket ) {
21682         @<Descend past a collective subscript@>;
21683       } else {
21684         break;
21685       }
21686     }
21687     link(t)=mp_get_avail(mp); t=link(t); info(t)=mp->cur_sym;
21688   }
21689   if ( eq_type(x)!=tag_token ) mp_clear_symbol(mp, x,false);
21690   if ( equiv(x)==null ) mp_new_root(mp, x);
21691   return h;
21692 }
21693
21694 @ If the subscript isn't collective, we don't accept it as part of the
21695 declared variable.
21696
21697 @<Descend past a collective subscript@>=
21698
21699   l=mp->cur_sym; mp_get_x_next(mp);
21700   if ( mp->cur_cmd!=right_bracket ) {
21701     mp_back_input(mp); mp->cur_sym=l; mp->cur_cmd=left_bracket; break;
21702   } else {
21703     mp->cur_sym=collective_subscript;
21704   }
21705 }
21706
21707 @ Type declarations are introduced by the following primitive operations.
21708
21709 @<Put each...@>=
21710 mp_primitive(mp, "numeric",type_name,mp_numeric_type);
21711 @:numeric_}{\&{numeric} primitive@>
21712 mp_primitive(mp, "string",type_name,mp_string_type);
21713 @:string_}{\&{string} primitive@>
21714 mp_primitive(mp, "boolean",type_name,mp_boolean_type);
21715 @:boolean_}{\&{boolean} primitive@>
21716 mp_primitive(mp, "path",type_name,mp_path_type);
21717 @:path_}{\&{path} primitive@>
21718 mp_primitive(mp, "pen",type_name,mp_pen_type);
21719 @:pen_}{\&{pen} primitive@>
21720 mp_primitive(mp, "picture",type_name,mp_picture_type);
21721 @:picture_}{\&{picture} primitive@>
21722 mp_primitive(mp, "transform",type_name,mp_transform_type);
21723 @:transform_}{\&{transform} primitive@>
21724 mp_primitive(mp, "color",type_name,mp_color_type);
21725 @:color_}{\&{color} primitive@>
21726 mp_primitive(mp, "rgbcolor",type_name,mp_color_type);
21727 @:color_}{\&{rgbcolor} primitive@>
21728 mp_primitive(mp, "cmykcolor",type_name,mp_cmykcolor_type);
21729 @:color_}{\&{cmykcolor} primitive@>
21730 mp_primitive(mp, "pair",type_name,mp_pair_type);
21731 @:pair_}{\&{pair} primitive@>
21732
21733 @ @<Cases of |print_cmd...@>=
21734 case type_name: mp_print_type(mp, m); break;
21735
21736 @ Now we are ready to handle type declarations, assuming that a
21737 |type_name| has just been scanned.
21738
21739 @<Declare action procedures for use by |do_statement|@>=
21740 void mp_do_type_declaration (MP mp) ;
21741
21742 @ @c
21743 void mp_do_type_declaration (MP mp) {
21744   small_number t; /* the type being declared */
21745   pointer p; /* token list for a declared variable */
21746   pointer q; /* value node for the variable */
21747   if ( mp->cur_mod>=mp_transform_type ) 
21748     t=mp->cur_mod;
21749   else 
21750     t=mp->cur_mod+unknown_tag;
21751   do {  
21752     p=mp_scan_declared_variable(mp);
21753     mp_flush_variable(mp, equiv(info(p)),link(p),false);
21754     q=mp_find_variable(mp, p);
21755     if ( q!=null ) { 
21756       type(q)=t; value(q)=null; 
21757     } else  { 
21758       print_err("Declared variable conflicts with previous vardef");
21759 @.Declared variable conflicts...@>
21760       help2("You can't use, e.g., `numeric foo[]' after `vardef foo'.")
21761            ("Proceed, and I'll ignore the illegal redeclaration.");
21762       mp_put_get_error(mp);
21763     }
21764     mp_flush_list(mp, p);
21765     if ( mp->cur_cmd<comma ) {
21766       @<Flush spurious symbols after the declared variable@>;
21767     }
21768   } while (! end_of_statement);
21769 }
21770
21771 @ @<Flush spurious symbols after the declared variable@>=
21772
21773   print_err("Illegal suffix of declared variable will be flushed");
21774 @.Illegal suffix...flushed@>
21775   help5("Variables in declarations must consist entirely of")
21776     ("names and collective subscripts, e.g., `x[]a'.")
21777     ("Are you trying to use a reserved word in a variable name?")
21778     ("I'm going to discard the junk I found here,")
21779     ("up to the next comma or the end of the declaration.");
21780   if ( mp->cur_cmd==numeric_token )
21781     mp->help_line[2]="Explicit subscripts like `x15a' aren't permitted.";
21782   mp_put_get_error(mp); mp->scanner_status=flushing;
21783   do {  
21784     get_t_next;
21785     @<Decrease the string reference count...@>;
21786   } while (mp->cur_cmd<comma); /* either |end_of_statement| or |cur_cmd=comma| */
21787   mp->scanner_status=normal;
21788 }
21789
21790 @ \MP's |main_control| procedure just calls |do_statement| repeatedly
21791 until coming to the end of the user's program.
21792 Each execution of |do_statement| concludes with
21793 |cur_cmd=semicolon|, |end_group|, or |stop|.
21794
21795 @c void mp_main_control (MP mp) { 
21796   do {  
21797     mp_do_statement(mp);
21798     if ( mp->cur_cmd==end_group ) {
21799       print_err("Extra `endgroup'");
21800 @.Extra `endgroup'@>
21801       help2("I'm not currently working on a `begingroup',")
21802         ("so I had better not try to end anything.");
21803       mp_flush_error(mp, 0);
21804     }
21805   } while (mp->cur_cmd!=stop);
21806 }
21807 int mp_run (MP mp) {
21808   @<Install and test the non-local jump buffer@>;
21809   mp_main_control(mp); /* come to life */
21810   mp_final_cleanup(mp); /* prepare for death */
21811   mp_close_files_and_terminate(mp);
21812   return mp->history;
21813 }
21814 char * mp_mplib_version (MP mp) {
21815   assert(mp);
21816   return mplib_version;
21817 }
21818 char * mp_metapost_version (MP mp) {
21819   assert(mp);
21820   return metapost_version;
21821 }
21822
21823 @ @<Exported function headers@>=
21824 int mp_run (MP mp);
21825 char * mp_mplib_version (MP mp);
21826 char * mp_metapost_version (MP mp);
21827
21828 @ @<Put each...@>=
21829 mp_primitive(mp, "end",stop,0);
21830 @:end_}{\&{end} primitive@>
21831 mp_primitive(mp, "dump",stop,1);
21832 @:dump_}{\&{dump} primitive@>
21833
21834 @ @<Cases of |print_cmd...@>=
21835 case stop:
21836   if ( m==0 ) mp_print(mp, "end");
21837   else mp_print(mp, "dump");
21838   break;
21839
21840 @* \[41] Commands.
21841 Let's turn now to statements that are classified as ``commands'' because
21842 of their imperative nature. We'll begin with simple ones, so that it
21843 will be clear how to hook command processing into the |do_statement| routine;
21844 then we'll tackle the tougher commands.
21845
21846 Here's one of the simplest:
21847
21848 @<Cases of |do_statement|...@>=
21849 case random_seed: mp_do_random_seed(mp);  break;
21850
21851 @ @<Declare action procedures for use by |do_statement|@>=
21852 void mp_do_random_seed (MP mp) ;
21853
21854 @ @c void mp_do_random_seed (MP mp) { 
21855   mp_get_x_next(mp);
21856   if ( mp->cur_cmd!=assignment ) {
21857     mp_missing_err(mp, ":=");
21858 @.Missing `:='@>
21859     help1("Always say `randomseed:=<numeric expression>'.");
21860     mp_back_error(mp);
21861   };
21862   mp_get_x_next(mp); mp_scan_expression(mp);
21863   if ( mp->cur_type!=mp_known ) {
21864     exp_err("Unknown value will be ignored");
21865 @.Unknown value...ignored@>
21866     help2("Your expression was too random for me to handle,")
21867       ("so I won't change the random seed just now.");
21868     mp_put_get_flush_error(mp, 0);
21869   } else {
21870    @<Initialize the random seed to |cur_exp|@>;
21871   }
21872 }
21873
21874 @ @<Initialize the random seed to |cur_exp|@>=
21875
21876   mp_init_randoms(mp, mp->cur_exp);
21877   if ( mp->selector>=log_only && mp->selector<write_file) {
21878     mp->old_setting=mp->selector; mp->selector=log_only;
21879     mp_print_nl(mp, "{randomseed:="); 
21880     mp_print_scaled(mp, mp->cur_exp); 
21881     mp_print_char(mp, '}');
21882     mp_print_nl(mp, ""); mp->selector=mp->old_setting;
21883   }
21884 }
21885
21886 @ And here's another simple one (somewhat different in flavor):
21887
21888 @<Cases of |do_statement|...@>=
21889 case mode_command: 
21890   mp_print_ln(mp); mp->interaction=mp->cur_mod;
21891   @<Initialize the print |selector| based on |interaction|@>;
21892   if ( mp->log_opened ) mp->selector=mp->selector+2;
21893   mp_get_x_next(mp);
21894   break;
21895
21896 @ @<Put each...@>=
21897 mp_primitive(mp, "batchmode",mode_command,mp_batch_mode);
21898 @:mp_batch_mode_}{\&{batchmode} primitive@>
21899 mp_primitive(mp, "nonstopmode",mode_command,mp_nonstop_mode);
21900 @:mp_nonstop_mode_}{\&{nonstopmode} primitive@>
21901 mp_primitive(mp, "scrollmode",mode_command,mp_scroll_mode);
21902 @:mp_scroll_mode_}{\&{scrollmode} primitive@>
21903 mp_primitive(mp, "errorstopmode",mode_command,mp_error_stop_mode);
21904 @:mp_error_stop_mode_}{\&{errorstopmode} primitive@>
21905
21906 @ @<Cases of |print_cmd_mod|...@>=
21907 case mode_command: 
21908   switch (m) {
21909   case mp_batch_mode: mp_print(mp, "batchmode"); break;
21910   case mp_nonstop_mode: mp_print(mp, "nonstopmode"); break;
21911   case mp_scroll_mode: mp_print(mp, "scrollmode"); break;
21912   default: mp_print(mp, "errorstopmode"); break;
21913   }
21914   break;
21915
21916 @ The `\&{inner}' and `\&{outer}' commands are only slightly harder.
21917
21918 @<Cases of |do_statement|...@>=
21919 case protection_command: mp_do_protection(mp); break;
21920
21921 @ @<Put each...@>=
21922 mp_primitive(mp, "inner",protection_command,0);
21923 @:inner_}{\&{inner} primitive@>
21924 mp_primitive(mp, "outer",protection_command,1);
21925 @:outer_}{\&{outer} primitive@>
21926
21927 @ @<Cases of |print_cmd...@>=
21928 case protection_command: 
21929   if ( m==0 ) mp_print(mp, "inner");
21930   else mp_print(mp, "outer");
21931   break;
21932
21933 @ @<Declare action procedures for use by |do_statement|@>=
21934 void mp_do_protection (MP mp) ;
21935
21936 @ @c void mp_do_protection (MP mp) {
21937   int m; /* 0 to unprotect, 1 to protect */
21938   halfword t; /* the |eq_type| before we change it */
21939   m=mp->cur_mod;
21940   do {  
21941     mp_get_symbol(mp); t=eq_type(mp->cur_sym);
21942     if ( m==0 ) { 
21943       if ( t>=outer_tag ) 
21944         eq_type(mp->cur_sym)=t-outer_tag;
21945     } else if ( t<outer_tag ) {
21946       eq_type(mp->cur_sym)=t+outer_tag;
21947     }
21948     mp_get_x_next(mp);
21949   } while (mp->cur_cmd==comma);
21950 }
21951
21952 @ \MP\ never defines the tokens `\.(' and `\.)' to be primitives, but
21953 plain \MP\ begins with the declaration `\&{delimiters} \.{()}'. Such a
21954 declaration assigns the command code |left_delimiter| to `\.{(}' and
21955 |right_delimiter| to `\.{)}'; the |equiv| of each delimiter is the
21956 hash address of its mate.
21957
21958 @<Cases of |do_statement|...@>=
21959 case delimiters: mp_def_delims(mp); break;
21960
21961 @ @<Declare action procedures for use by |do_statement|@>=
21962 void mp_def_delims (MP mp) ;
21963
21964 @ @c void mp_def_delims (MP mp) {
21965   pointer l_delim,r_delim; /* the new delimiter pair */
21966   mp_get_clear_symbol(mp); l_delim=mp->cur_sym;
21967   mp_get_clear_symbol(mp); r_delim=mp->cur_sym;
21968   eq_type(l_delim)=left_delimiter; equiv(l_delim)=r_delim;
21969   eq_type(r_delim)=right_delimiter; equiv(r_delim)=l_delim;
21970   mp_get_x_next(mp);
21971 }
21972
21973 @ Here is a procedure that is called when \MP\ has reached a point
21974 where some right delimiter is mandatory.
21975
21976 @<Declare the procedure called |check_delimiter|@>=
21977 void mp_check_delimiter (MP mp,pointer l_delim, pointer r_delim) {
21978   if ( mp->cur_cmd==right_delimiter ) 
21979     if ( mp->cur_mod==l_delim ) 
21980       return;
21981   if ( mp->cur_sym!=r_delim ) {
21982      mp_missing_err(mp, str(text(r_delim)));
21983 @.Missing `)'@>
21984     help2("I found no right delimiter to match a left one. So I've")
21985       ("put one in, behind the scenes; this may fix the problem.");
21986     mp_back_error(mp);
21987   } else { 
21988     print_err("The token `"); mp_print_text(r_delim);
21989 @.The token...delimiter@>
21990     mp_print(mp, "' is no longer a right delimiter");
21991     help3("Strange: This token has lost its former meaning!")
21992       ("I'll read it as a right delimiter this time;")
21993       ("but watch out, I'll probably miss it later.");
21994     mp_error(mp);
21995   }
21996 }
21997
21998 @ The next four commands save or change the values associated with tokens.
21999
22000 @<Cases of |do_statement|...@>=
22001 case save_command: 
22002   do {  
22003     mp_get_symbol(mp); mp_save_variable(mp, mp->cur_sym); mp_get_x_next(mp);
22004   } while (mp->cur_cmd==comma);
22005   break;
22006 case interim_command: mp_do_interim(mp); break;
22007 case let_command: mp_do_let(mp); break;
22008 case new_internal: mp_do_new_internal(mp); break;
22009
22010 @ @<Declare action procedures for use by |do_statement|@>=
22011 void mp_do_statement (MP mp);
22012 void mp_do_interim (MP mp);
22013
22014 @ @c void mp_do_interim (MP mp) { 
22015   mp_get_x_next(mp);
22016   if ( mp->cur_cmd!=internal_quantity ) {
22017      print_err("The token `");
22018 @.The token...quantity@>
22019     if ( mp->cur_sym==0 ) mp_print(mp, "(%CAPSULE)");
22020     else mp_print_text(mp->cur_sym);
22021     mp_print(mp, "' isn't an internal quantity");
22022     help1("Something like `tracingonline' should follow `interim'.");
22023     mp_back_error(mp);
22024   } else { 
22025     mp_save_internal(mp, mp->cur_mod); mp_back_input(mp);
22026   }
22027   mp_do_statement(mp);
22028 }
22029
22030 @ The following procedure is careful not to undefine the left-hand symbol
22031 too soon, lest commands like `{\tt let x=x}' have a surprising effect.
22032
22033 @<Declare action procedures for use by |do_statement|@>=
22034 void mp_do_let (MP mp) ;
22035
22036 @ @c void mp_do_let (MP mp) {
22037   pointer l; /* hash location of the left-hand symbol */
22038   mp_get_symbol(mp); l=mp->cur_sym; mp_get_x_next(mp);
22039   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
22040      mp_missing_err(mp, "=");
22041 @.Missing `='@>
22042     help3("You should have said `let symbol = something'.")
22043       ("But don't worry; I'll pretend that an equals sign")
22044       ("was present. The next token I read will be `something'.");
22045     mp_back_error(mp);
22046   }
22047   mp_get_symbol(mp);
22048   switch (mp->cur_cmd) {
22049   case defined_macro: case secondary_primary_macro:
22050   case tertiary_secondary_macro: case expression_tertiary_macro: 
22051     add_mac_ref(mp->cur_mod);
22052     break;
22053   default: 
22054     break;
22055   }
22056   mp_clear_symbol(mp, l,false); eq_type(l)=mp->cur_cmd;
22057   if ( mp->cur_cmd==tag_token ) equiv(l)=null;
22058   else equiv(l)=mp->cur_mod;
22059   mp_get_x_next(mp);
22060 }
22061
22062 @ @<Declarations@>=
22063 void mp_grow_internals (MP mp, int l);
22064 void mp_do_new_internal (MP mp) ;
22065
22066 @ @c
22067 void mp_grow_internals (MP mp, int l) {
22068   scaled *internal;
22069   char * *int_name; 
22070   int k;
22071   if ( hash_end+l>max_halfword ) {
22072     mp_confusion(mp, "out of memory space"); /* can't be reached */
22073   }
22074   int_name = xmalloc ((l+1),sizeof(char *));
22075   internal = xmalloc ((l+1),sizeof(scaled));
22076   for (k=0;k<=l; k++ ) { 
22077     if (k<=mp->max_internal) {
22078       internal[k]=mp->internal[k]; 
22079       int_name[k]=mp->int_name[k]; 
22080     } else {
22081       internal[k]=0; 
22082       int_name[k]=NULL; 
22083     }
22084   }
22085   xfree(mp->internal); xfree(mp->int_name);
22086   mp->int_name = int_name;
22087   mp->internal = internal;
22088   mp->max_internal = l;
22089 }
22090
22091
22092 void mp_do_new_internal (MP mp) { 
22093   do {  
22094     if ( mp->int_ptr==mp->max_internal ) {
22095       mp_grow_internals(mp, (mp->max_internal + (mp->max_internal>>2)));
22096     }
22097     mp_get_clear_symbol(mp); incr(mp->int_ptr);
22098     eq_type(mp->cur_sym)=internal_quantity; 
22099     equiv(mp->cur_sym)=mp->int_ptr;
22100     if(mp->int_name[mp->int_ptr]!=NULL)
22101       xfree(mp->int_name[mp->int_ptr]);
22102     mp->int_name[mp->int_ptr]=str(text(mp->cur_sym)); 
22103     mp->internal[mp->int_ptr]=0;
22104     mp_get_x_next(mp);
22105   } while (mp->cur_cmd==comma);
22106 }
22107
22108 @ @<Dealloc variables@>=
22109 for (k=0;k<=mp->max_internal;k++) {
22110    xfree(mp->int_name[k]);
22111 }
22112 xfree(mp->internal); 
22113 xfree(mp->int_name); 
22114
22115
22116 @ The various `\&{show}' commands are distinguished by modifier fields
22117 in the usual way.
22118
22119 @d show_token_code 0 /* show the meaning of a single token */
22120 @d show_stats_code 1 /* show current memory and string usage */
22121 @d show_code 2 /* show a list of expressions */
22122 @d show_var_code 3 /* show a variable and its descendents */
22123 @d show_dependencies_code 4 /* show dependent variables in terms of independents */
22124
22125 @<Put each...@>=
22126 mp_primitive(mp, "showtoken",show_command,show_token_code);
22127 @:show_token_}{\&{showtoken} primitive@>
22128 mp_primitive(mp, "showstats",show_command,show_stats_code);
22129 @:show_stats_}{\&{showstats} primitive@>
22130 mp_primitive(mp, "show",show_command,show_code);
22131 @:show_}{\&{show} primitive@>
22132 mp_primitive(mp, "showvariable",show_command,show_var_code);
22133 @:show_var_}{\&{showvariable} primitive@>
22134 mp_primitive(mp, "showdependencies",show_command,show_dependencies_code);
22135 @:show_dependencies_}{\&{showdependencies} primitive@>
22136
22137 @ @<Cases of |print_cmd...@>=
22138 case show_command: 
22139   switch (m) {
22140   case show_token_code:mp_print(mp, "showtoken"); break;
22141   case show_stats_code:mp_print(mp, "showstats"); break;
22142   case show_code:mp_print(mp, "show"); break;
22143   case show_var_code:mp_print(mp, "showvariable"); break;
22144   default: mp_print(mp, "showdependencies"); break;
22145   }
22146   break;
22147
22148 @ @<Cases of |do_statement|...@>=
22149 case show_command:mp_do_show_whatever(mp); break;
22150
22151 @ The value of |cur_mod| controls the |verbosity| in the |print_exp| routine:
22152 if it's |show_code|, complicated structures are abbreviated, otherwise
22153 they aren't.
22154
22155 @<Declare action procedures for use by |do_statement|@>=
22156 void mp_do_show (MP mp) ;
22157
22158 @ @c void mp_do_show (MP mp) { 
22159   do {  
22160     mp_get_x_next(mp); mp_scan_expression(mp);
22161     mp_print_nl(mp, ">> ");
22162 @.>>@>
22163     mp_print_exp(mp, null,2); mp_flush_cur_exp(mp, 0);
22164   } while (mp->cur_cmd==comma);
22165 }
22166
22167 @ @<Declare action procedures for use by |do_statement|@>=
22168 void mp_disp_token (MP mp) ;
22169
22170 @ @c void mp_disp_token (MP mp) { 
22171   mp_print_nl(mp, "> ");
22172 @.>\relax@>
22173   if ( mp->cur_sym==0 ) {
22174     @<Show a numeric or string or capsule token@>;
22175   } else { 
22176     mp_print_text(mp->cur_sym); mp_print_char(mp, '=');
22177     if ( eq_type(mp->cur_sym)>=outer_tag ) mp_print(mp, "(outer) ");
22178     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod);
22179     if ( mp->cur_cmd==defined_macro ) {
22180       mp_print_ln(mp); mp_show_macro(mp, mp->cur_mod,null,100000);
22181     } /* this avoids recursion between |show_macro| and |print_cmd_mod| */
22182 @^recursion@>
22183   }
22184 }
22185
22186 @ @<Show a numeric or string or capsule token@>=
22187
22188   if ( mp->cur_cmd==numeric_token ) {
22189     mp_print_scaled(mp, mp->cur_mod);
22190   } else if ( mp->cur_cmd==capsule_token ) {
22191     mp->g_pointer=mp->cur_mod; mp_print_capsule(mp);
22192   } else  { 
22193     mp_print_char(mp, '"'); 
22194     mp_print_str(mp, mp->cur_mod); mp_print_char(mp, '"');
22195     delete_str_ref(mp->cur_mod);
22196   }
22197 }
22198
22199 @ The following cases of |print_cmd_mod| might arise in connection
22200 with |disp_token|, although they don't correspond to any
22201 primitive tokens.
22202
22203 @<Cases of |print_cmd_...@>=
22204 case left_delimiter:
22205 case right_delimiter: 
22206   if ( c==left_delimiter ) mp_print(mp, "left");
22207   else mp_print(mp, "right");
22208   mp_print(mp, " delimiter that matches "); 
22209   mp_print_text(m);
22210   break;
22211 case tag_token:
22212   if ( m==null ) mp_print(mp, "tag");
22213    else mp_print(mp, "variable");
22214    break;
22215 case defined_macro: 
22216    mp_print(mp, "macro:");
22217    break;
22218 case secondary_primary_macro:
22219 case tertiary_secondary_macro:
22220 case expression_tertiary_macro:
22221   mp_print_cmd_mod(mp, macro_def,c); 
22222   mp_print(mp, "'d macro:");
22223   mp_print_ln(mp); mp_show_token_list(mp, link(link(m)),null,1000,0);
22224   break;
22225 case repeat_loop:
22226   mp_print(mp, "[repeat the loop]");
22227   break;
22228 case internal_quantity:
22229   mp_print(mp, mp->int_name[m]);
22230   break;
22231
22232 @ @<Declare action procedures for use by |do_statement|@>=
22233 void mp_do_show_token (MP mp) ;
22234
22235 @ @c void mp_do_show_token (MP mp) { 
22236   do {  
22237     get_t_next; mp_disp_token(mp);
22238     mp_get_x_next(mp);
22239   } while (mp->cur_cmd==comma);
22240 }
22241
22242 @ @<Declare action procedures for use by |do_statement|@>=
22243 void mp_do_show_stats (MP mp) ;
22244
22245 @ @c void mp_do_show_stats (MP mp) { 
22246   mp_print_nl(mp, "Memory usage ");
22247 @.Memory usage...@>
22248   mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used);
22249   if ( false )
22250     mp_print(mp, "unknown");
22251   mp_print(mp, " ("); mp_print_int(mp, mp->hi_mem_min-mp->lo_mem_max-1);
22252   mp_print(mp, " still untouched)"); mp_print_ln(mp);
22253   mp_print_nl(mp, "String usage ");
22254   mp_print_int(mp, mp->strs_in_use-mp->init_str_use);
22255   mp_print_char(mp, '&'); mp_print_int(mp, mp->pool_in_use-mp->init_pool_ptr);
22256   if ( false )
22257     mp_print(mp, "unknown");
22258   mp_print(mp, " (");
22259   mp_print_int(mp, mp->max_strings-1-mp->strs_used_up); mp_print_char(mp, '&');
22260   mp_print_int(mp, mp->pool_size-mp->pool_ptr); 
22261   mp_print(mp, " now untouched)"); mp_print_ln(mp);
22262   mp_get_x_next(mp);
22263 }
22264
22265 @ Here's a recursive procedure that gives an abbreviated account
22266 of a variable, for use by |do_show_var|.
22267
22268 @<Declare action procedures for use by |do_statement|@>=
22269 void mp_disp_var (MP mp,pointer p) ;
22270
22271 @ @c void mp_disp_var (MP mp,pointer p) {
22272   pointer q; /* traverses attributes and subscripts */
22273   int n; /* amount of macro text to show */
22274   if ( type(p)==mp_structured )  {
22275     @<Descend the structure@>;
22276   } else if ( type(p)>=mp_unsuffixed_macro ) {
22277     @<Display a variable macro@>;
22278   } else if ( type(p)!=undefined ){ 
22279     mp_print_nl(mp, ""); mp_print_variable_name(mp, p); 
22280     mp_print_char(mp, '=');
22281     mp_print_exp(mp, p,0);
22282   }
22283 }
22284
22285 @ @<Descend the structure@>=
22286
22287   q=attr_head(p);
22288   do {  mp_disp_var(mp, q); q=link(q); } while (q!=end_attr);
22289   q=subscr_head(p);
22290   while ( name_type(q)==mp_subscr ) { 
22291     mp_disp_var(mp, q); q=link(q);
22292   }
22293 }
22294
22295 @ @<Display a variable macro@>=
22296
22297   mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22298   if ( type(p)>mp_unsuffixed_macro ) 
22299     mp_print(mp, "@@#"); /* |suffixed_macro| */
22300   mp_print(mp, "=macro:");
22301   if ( (int)mp->file_offset>=mp->max_print_line-20 ) n=5;
22302   else n=mp->max_print_line-mp->file_offset-15;
22303   mp_show_macro(mp, value(p),null,n);
22304 }
22305
22306 @ @<Declare action procedures for use by |do_statement|@>=
22307 void mp_do_show_var (MP mp) ;
22308
22309 @ @c void mp_do_show_var (MP mp) { 
22310   do {  
22311     get_t_next;
22312     if ( mp->cur_sym>0 ) if ( mp->cur_sym<=hash_end )
22313       if ( mp->cur_cmd==tag_token ) if ( mp->cur_mod!=null ) {
22314       mp_disp_var(mp, mp->cur_mod); goto DONE;
22315     }
22316    mp_disp_token(mp);
22317   DONE:
22318    mp_get_x_next(mp);
22319   } while (mp->cur_cmd==comma);
22320 }
22321
22322 @ @<Declare action procedures for use by |do_statement|@>=
22323 void mp_do_show_dependencies (MP mp) ;
22324
22325 @ @c void mp_do_show_dependencies (MP mp) {
22326   pointer p; /* link that runs through all dependencies */
22327   p=link(dep_head);
22328   while ( p!=dep_head ) {
22329     if ( mp_interesting(mp, p) ) {
22330       mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22331       if ( type(p)==mp_dependent ) mp_print_char(mp, '=');
22332       else mp_print(mp, " = "); /* extra spaces imply proto-dependency */
22333       mp_print_dependency(mp, dep_list(p),type(p));
22334     }
22335     p=dep_list(p);
22336     while ( info(p)!=null ) p=link(p);
22337     p=link(p);
22338   }
22339   mp_get_x_next(mp);
22340 }
22341
22342 @ Finally we are ready for the procedure that governs all of the
22343 show commands.
22344
22345 @<Declare action procedures for use by |do_statement|@>=
22346 void mp_do_show_whatever (MP mp) ;
22347
22348 @ @c void mp_do_show_whatever (MP mp) { 
22349   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
22350   switch (mp->cur_mod) {
22351   case show_token_code:mp_do_show_token(mp); break;
22352   case show_stats_code:mp_do_show_stats(mp); break;
22353   case show_code:mp_do_show(mp); break;
22354   case show_var_code:mp_do_show_var(mp); break;
22355   case show_dependencies_code:mp_do_show_dependencies(mp); break;
22356   } /* there are no other cases */
22357   if ( mp->internal[mp_showstopping]>0 ){ 
22358     print_err("OK");
22359 @.OK@>
22360     if ( mp->interaction<mp_error_stop_mode ) { 
22361       help0; decr(mp->error_count);
22362     } else {
22363       help1("This isn't an error message; I'm just showing something.");
22364     }
22365     if ( mp->cur_cmd==semicolon ) mp_error(mp);
22366      else mp_put_get_error(mp);
22367   }
22368 }
22369
22370 @ The `\&{addto}' command needs the following additional primitives:
22371
22372 @d double_path_code 0 /* command modifier for `\&{doublepath}' */
22373 @d contour_code 1 /* command modifier for `\&{contour}' */
22374 @d also_code 2 /* command modifier for `\&{also}' */
22375
22376 @ Pre and postscripts need two new identifiers:
22377
22378 @d with_pre_script 11
22379 @d with_post_script 13
22380
22381 @<Put each...@>=
22382 mp_primitive(mp, "doublepath",thing_to_add,double_path_code);
22383 @:double_path_}{\&{doublepath} primitive@>
22384 mp_primitive(mp, "contour",thing_to_add,contour_code);
22385 @:contour_}{\&{contour} primitive@>
22386 mp_primitive(mp, "also",thing_to_add,also_code);
22387 @:also_}{\&{also} primitive@>
22388 mp_primitive(mp, "withpen",with_option,mp_pen_type);
22389 @:with_pen_}{\&{withpen} primitive@>
22390 mp_primitive(mp, "dashed",with_option,mp_picture_type);
22391 @:dashed_}{\&{dashed} primitive@>
22392 mp_primitive(mp, "withprescript",with_option,with_pre_script);
22393 @:with_pre_script_}{\&{withprescript} primitive@>
22394 mp_primitive(mp, "withpostscript",with_option,with_post_script);
22395 @:with_post_script_}{\&{withpostscript} primitive@>
22396 mp_primitive(mp, "withoutcolor",with_option,mp_no_model);
22397 @:with_color_}{\&{withoutcolor} primitive@>
22398 mp_primitive(mp, "withgreyscale",with_option,mp_grey_model);
22399 @:with_color_}{\&{withgreyscale} primitive@>
22400 mp_primitive(mp, "withcolor",with_option,mp_uninitialized_model);
22401 @:with_color_}{\&{withcolor} primitive@>
22402 /*  \&{withrgbcolor} is an alias for \&{withcolor} */
22403 mp_primitive(mp, "withrgbcolor",with_option,mp_rgb_model);
22404 @:with_color_}{\&{withrgbcolor} primitive@>
22405 mp_primitive(mp, "withcmykcolor",with_option,mp_cmyk_model);
22406 @:with_color_}{\&{withcmykcolor} primitive@>
22407
22408 @ @<Cases of |print_cmd...@>=
22409 case thing_to_add:
22410   if ( m==contour_code ) mp_print(mp, "contour");
22411   else if ( m==double_path_code ) mp_print(mp, "doublepath");
22412   else mp_print(mp, "also");
22413   break;
22414 case with_option:
22415   if ( m==mp_pen_type ) mp_print(mp, "withpen");
22416   else if ( m==with_pre_script ) mp_print(mp, "withprescript");
22417   else if ( m==with_post_script ) mp_print(mp, "withpostscript");
22418   else if ( m==mp_no_model ) mp_print(mp, "withoutcolor");
22419   else if ( m==mp_rgb_model ) mp_print(mp, "withrgbcolor");
22420   else if ( m==mp_uninitialized_model ) mp_print(mp, "withcolor");
22421   else if ( m==mp_cmyk_model ) mp_print(mp, "withcmykcolor");
22422   else if ( m==mp_grey_model ) mp_print(mp, "withgreyscale");
22423   else mp_print(mp, "dashed");
22424   break;
22425
22426 @ The |scan_with_list| procedure parses a $\langle$with list$\rangle$ and
22427 updates the list of graphical objects starting at |p|.  Each $\langle$with
22428 clause$\rangle$ updates all graphical objects whose |type| is compatible.
22429 Other objects are ignored.
22430
22431 @<Declare action procedures for use by |do_statement|@>=
22432 void mp_scan_with_list (MP mp,pointer p) ;
22433
22434 @ @c void mp_scan_with_list (MP mp,pointer p) {
22435   small_number t; /* |cur_mod| of the |with_option| (should match |cur_type|) */
22436   pointer q; /* for list manipulation */
22437   int old_setting; /* saved |selector| setting */
22438   pointer k; /* for finding the near-last item in a list  */
22439   str_number s; /* for string cleanup after combining  */
22440   pointer cp,pp,dp,ap,bp;
22441     /* objects being updated; |void| initially; |null| to suppress update */
22442   cp=mp_void; pp=mp_void; dp=mp_void; ap=mp_void; bp=mp_void;
22443   k=0;
22444   while ( mp->cur_cmd==with_option ){ 
22445     t=mp->cur_mod;
22446     mp_get_x_next(mp);
22447     if ( t!=mp_no_model ) mp_scan_expression(mp);
22448     if (((t==with_pre_script)&&(mp->cur_type!=mp_string_type))||
22449      ((t==with_post_script)&&(mp->cur_type!=mp_string_type))||
22450      ((t==mp_uninitialized_model)&&
22451         ((mp->cur_type!=mp_cmykcolor_type)&&(mp->cur_type!=mp_color_type)
22452           &&(mp->cur_type!=mp_known)&&(mp->cur_type!=mp_boolean_type)))||
22453      ((t==mp_cmyk_model)&&(mp->cur_type!=mp_cmykcolor_type))||
22454      ((t==mp_rgb_model)&&(mp->cur_type!=mp_color_type))||
22455      ((t==mp_grey_model)&&(mp->cur_type!=mp_known))||
22456      ((t==mp_pen_type)&&(mp->cur_type!=t))||
22457      ((t==mp_picture_type)&&(mp->cur_type!=t)) ) {
22458       @<Complain about improper type@>;
22459     } else if ( t==mp_uninitialized_model ) {
22460       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22461       if ( cp!=null )
22462         @<Transfer a color from the current expression to object~|cp|@>;
22463       mp_flush_cur_exp(mp, 0);
22464     } else if ( t==mp_rgb_model ) {
22465       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22466       if ( cp!=null )
22467         @<Transfer a rgbcolor from the current expression to object~|cp|@>;
22468       mp_flush_cur_exp(mp, 0);
22469     } else if ( t==mp_cmyk_model ) {
22470       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22471       if ( cp!=null )
22472         @<Transfer a cmykcolor from the current expression to object~|cp|@>;
22473       mp_flush_cur_exp(mp, 0);
22474     } else if ( t==mp_grey_model ) {
22475       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22476       if ( cp!=null )
22477         @<Transfer a greyscale from the current expression to object~|cp|@>;
22478       mp_flush_cur_exp(mp, 0);
22479     } else if ( t==mp_no_model ) {
22480       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22481       if ( cp!=null )
22482         @<Transfer a noncolor from the current expression to object~|cp|@>;
22483     } else if ( t==mp_pen_type ) {
22484       if ( pp==mp_void ) @<Make |pp| an object in list~|p| that needs a pen@>;
22485       if ( pp!=null ) {
22486         if ( pen_p(pp)!=null ) mp_toss_knot_list(mp, pen_p(pp));
22487         pen_p(pp)=mp->cur_exp; mp->cur_type=mp_vacuous;
22488       }
22489     } else if ( t==with_pre_script ) {
22490       if ( ap==mp_void )
22491         ap=p;
22492       while ( (ap!=null)&&(! has_color(ap)) )
22493          ap=link(ap);
22494       if ( ap!=null ) {
22495         if ( pre_script(ap)!=null ) { /*  build a new,combined string  */
22496           s=pre_script(ap);
22497           old_setting=mp->selector;
22498               mp->selector=new_string;
22499           str_room(length(pre_script(ap))+length(mp->cur_exp)+2);
22500               mp_print_str(mp, mp->cur_exp);
22501           append_char(13);  /* a forced \ps\ newline  */
22502           mp_print_str(mp, pre_script(ap));
22503           pre_script(ap)=mp_make_string(mp);
22504           delete_str_ref(s);
22505           mp->selector=old_setting;
22506         } else {
22507           pre_script(ap)=mp->cur_exp;
22508         }
22509         mp->cur_type=mp_vacuous;
22510       }
22511     } else if ( t==with_post_script ) {
22512       if ( bp==mp_void )
22513         k=p; 
22514       bp=k;
22515       while ( link(k)!=null ) {
22516         k=link(k);
22517         if ( has_color(k) ) bp=k;
22518       }
22519       if ( bp!=null ) {
22520          if ( post_script(bp)!=null ) {
22521            s=post_script(bp);
22522            old_setting=mp->selector;
22523                mp->selector=new_string;
22524            str_room(length(post_script(bp))+length(mp->cur_exp)+2);
22525            mp_print_str(mp, post_script(bp));
22526            append_char(13); /* a forced \ps\ newline  */
22527            mp_print_str(mp, mp->cur_exp);
22528            post_script(bp)=mp_make_string(mp);
22529            delete_str_ref(s);
22530            mp->selector=old_setting;
22531          } else {
22532            post_script(bp)=mp->cur_exp;
22533          }
22534          mp->cur_type=mp_vacuous;
22535        }
22536     } else { 
22537       if ( dp==mp_void ) {
22538         @<Make |dp| a stroked node in list~|p|@>;
22539       }
22540       if ( dp!=null ) {
22541         if ( dash_p(dp)!=null ) delete_edge_ref(dash_p(dp));
22542         dash_p(dp)=mp_make_dashes(mp, mp->cur_exp);
22543         dash_scale(dp)=unity;
22544         mp->cur_type=mp_vacuous;
22545       }
22546     }
22547   }
22548   @<Copy the information from objects |cp|, |pp|, and |dp| into the rest
22549     of the list@>;
22550 };
22551
22552 @ @<Complain about improper type@>=
22553 { exp_err("Improper type");
22554 @.Improper type@>
22555 help2("Next time say `withpen <known pen expression>';")
22556   ("I'll ignore the bad `with' clause and look for another.");
22557 if ( t==with_pre_script )
22558   mp->help_line[1]="Next time say `withprescript <known string expression>';";
22559 else if ( t==with_post_script )
22560   mp->help_line[1]="Next time say `withpostscript <known string expression>';";
22561 else if ( t==mp_picture_type )
22562   mp->help_line[1]="Next time say `dashed <known picture expression>';";
22563 else if ( t==mp_uninitialized_model )
22564   mp->help_line[1]="Next time say `withcolor <known color expression>';";
22565 else if ( t==mp_rgb_model )
22566   mp->help_line[1]="Next time say `withrgbcolor <known color expression>';";
22567 else if ( t==mp_cmyk_model )
22568   mp->help_line[1]="Next time say `withcmykcolor <known cmykcolor expression>';";
22569 else if ( t==mp_grey_model )
22570   mp->help_line[1]="Next time say `withgreyscale <known numeric expression>';";;
22571 mp_put_get_flush_error(mp, 0);
22572 }
22573
22574 @ Forcing the color to be between |0| and |unity| here guarantees that no
22575 picture will ever contain a color outside the legal range for \ps\ graphics.
22576
22577 @<Transfer a color from the current expression to object~|cp|@>=
22578 { if ( mp->cur_type==mp_color_type )
22579    @<Transfer a rgbcolor from the current expression to object~|cp|@>
22580 else if ( mp->cur_type==mp_cmykcolor_type )
22581    @<Transfer a cmykcolor from the current expression to object~|cp|@>
22582 else if ( mp->cur_type==mp_known )
22583    @<Transfer a greyscale from the current expression to object~|cp|@>
22584 else if ( mp->cur_exp==false_code )
22585    @<Transfer a noncolor from the current expression to object~|cp|@>;
22586 }
22587
22588 @ @<Transfer a rgbcolor from the current expression to object~|cp|@>=
22589 { q=value(mp->cur_exp);
22590 cyan_val(cp)=0;
22591 magenta_val(cp)=0;
22592 yellow_val(cp)=0;
22593 black_val(cp)=0;
22594 red_val(cp)=value(red_part_loc(q));
22595 green_val(cp)=value(green_part_loc(q));
22596 blue_val(cp)=value(blue_part_loc(q));
22597 color_model(cp)=mp_rgb_model;
22598 if ( red_val(cp)<0 ) red_val(cp)=0;
22599 if ( green_val(cp)<0 ) green_val(cp)=0;
22600 if ( blue_val(cp)<0 ) blue_val(cp)=0;
22601 if ( red_val(cp)>unity ) red_val(cp)=unity;
22602 if ( green_val(cp)>unity ) green_val(cp)=unity;
22603 if ( blue_val(cp)>unity ) blue_val(cp)=unity;
22604 }
22605
22606 @ @<Transfer a cmykcolor from the current expression to object~|cp|@>=
22607 { q=value(mp->cur_exp);
22608 cyan_val(cp)=value(cyan_part_loc(q));
22609 magenta_val(cp)=value(magenta_part_loc(q));
22610 yellow_val(cp)=value(yellow_part_loc(q));
22611 black_val(cp)=value(black_part_loc(q));
22612 color_model(cp)=mp_cmyk_model;
22613 if ( cyan_val(cp)<0 ) cyan_val(cp)=0;
22614 if ( magenta_val(cp)<0 ) magenta_val(cp)=0;
22615 if ( yellow_val(cp)<0 ) yellow_val(cp)=0;
22616 if ( black_val(cp)<0 ) black_val(cp)=0;
22617 if ( cyan_val(cp)>unity ) cyan_val(cp)=unity;
22618 if ( magenta_val(cp)>unity ) magenta_val(cp)=unity;
22619 if ( yellow_val(cp)>unity ) yellow_val(cp)=unity;
22620 if ( black_val(cp)>unity ) black_val(cp)=unity;
22621 }
22622
22623 @ @<Transfer a greyscale from the current expression to object~|cp|@>=
22624 { q=mp->cur_exp;
22625 cyan_val(cp)=0;
22626 magenta_val(cp)=0;
22627 yellow_val(cp)=0;
22628 black_val(cp)=0;
22629 grey_val(cp)=q;
22630 color_model(cp)=mp_grey_model;
22631 if ( grey_val(cp)<0 ) grey_val(cp)=0;
22632 if ( grey_val(cp)>unity ) grey_val(cp)=unity;
22633 }
22634
22635 @ @<Transfer a noncolor from the current expression to object~|cp|@>=
22636 {
22637 cyan_val(cp)=0;
22638 magenta_val(cp)=0;
22639 yellow_val(cp)=0;
22640 black_val(cp)=0;
22641 grey_val(cp)=0;
22642 color_model(cp)=mp_no_model;
22643 }
22644
22645 @ @<Make |cp| a colored object in object list~|p|@>=
22646 { cp=p;
22647   while ( cp!=null ){ 
22648     if ( has_color(cp) ) break;
22649     cp=link(cp);
22650   }
22651 }
22652
22653 @ @<Make |pp| an object in list~|p| that needs a pen@>=
22654 { pp=p;
22655   while ( pp!=null ) {
22656     if ( has_pen(pp) ) break;
22657     pp=link(pp);
22658   }
22659 }
22660
22661 @ @<Make |dp| a stroked node in list~|p|@>=
22662 { dp=p;
22663   while ( dp!=null ) {
22664     if ( type(dp)==mp_stroked_code ) break;
22665     dp=link(dp);
22666   }
22667 }
22668
22669 @ @<Copy the information from objects |cp|, |pp|, and |dp| into...@>=
22670 @<Copy |cp|'s color into the colored objects linked to~|cp|@>;
22671 if ( pp>mp_void ) {
22672   @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>;
22673 }
22674 if ( dp>mp_void ) {
22675   @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>;
22676 }
22677
22678
22679 @ @<Copy |cp|'s color into the colored objects linked to~|cp|@>=
22680 { q=link(cp);
22681   while ( q!=null ) { 
22682     if ( has_color(q) ) {
22683       red_val(q)=red_val(cp);
22684       green_val(q)=green_val(cp);
22685       blue_val(q)=blue_val(cp);
22686       black_val(q)=black_val(cp);
22687       color_model(q)=color_model(cp);
22688     }
22689     q=link(q);
22690   }
22691 }
22692
22693 @ @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>=
22694 { q=link(pp);
22695   while ( q!=null ) {
22696     if ( has_pen(q) ) {
22697       if ( pen_p(q)!=null ) mp_toss_knot_list(mp, pen_p(q));
22698       pen_p(q)=copy_pen(pen_p(pp));
22699     }
22700     q=link(q);
22701   }
22702 }
22703
22704 @ @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>=
22705 { q=link(dp);
22706   while ( q!=null ) {
22707     if ( type(q)==mp_stroked_code ) {
22708       if ( dash_p(q)!=null ) delete_edge_ref(dash_p(q));
22709       dash_p(q)=dash_p(dp);
22710       dash_scale(q)=unity;
22711       if ( dash_p(q)!=null ) add_edge_ref(dash_p(q));
22712     }
22713     q=link(q);
22714   }
22715 }
22716
22717 @ One of the things we need to do when we've parsed an \&{addto} or
22718 similar command is find the header of a supposed \&{picture} variable, given
22719 a token list for that variable.  Since the edge structure is about to be
22720 updated, we use |private_edges| to make sure that this is possible.
22721
22722 @<Declare action procedures for use by |do_statement|@>=
22723 pointer mp_find_edges_var (MP mp, pointer t) ;
22724
22725 @ @c pointer mp_find_edges_var (MP mp, pointer t) {
22726   pointer p;
22727   pointer cur_edges; /* the return value */
22728   p=mp_find_variable(mp, t); cur_edges=null;
22729   if ( p==null ) { 
22730     mp_obliterated(mp, t); mp_put_get_error(mp);
22731   } else if ( type(p)!=mp_picture_type )  { 
22732     print_err("Variable "); mp_show_token_list(mp, t,null,1000,0);
22733 @.Variable x is the wrong type@>
22734     mp_print(mp, " is the wrong type ("); 
22735     mp_print_type(mp, type(p)); mp_print_char(mp, ')');
22736     help2("I was looking for a \"known\" picture variable.")
22737          ("So I'll not change anything just now."); 
22738     mp_put_get_error(mp);
22739   } else { 
22740     value(p)=mp_private_edges(mp, value(p));
22741     cur_edges=value(p);
22742   }
22743   mp_flush_node_list(mp, t);
22744   return cur_edges;
22745 };
22746
22747 @ @<Cases of |do_statement|...@>=
22748 case add_to_command: mp_do_add_to(mp); break;
22749 case bounds_command:mp_do_bounds(mp); break;
22750
22751 @ @<Put each...@>=
22752 mp_primitive(mp, "clip",bounds_command,mp_start_clip_code);
22753 @:clip_}{\&{clip} primitive@>
22754 mp_primitive(mp, "setbounds",bounds_command,mp_start_bounds_code);
22755 @:set_bounds_}{\&{setbounds} primitive@>
22756
22757 @ @<Cases of |print_cmd...@>=
22758 case bounds_command: 
22759   if ( m==mp_start_clip_code ) mp_print(mp, "clip");
22760   else mp_print(mp, "setbounds");
22761   break;
22762
22763 @ The following function parses the beginning of an \&{addto} or \&{clip}
22764 command: it expects a variable name followed by a token with |cur_cmd=sep|
22765 and then an expression.  The function returns the token list for the variable
22766 and stores the command modifier for the separator token in the global variable
22767 |last_add_type|.  We must be careful because this variable might get overwritten
22768 any time we call |get_x_next|.
22769
22770 @<Glob...@>=
22771 quarterword last_add_type;
22772   /* command modifier that identifies the last \&{addto} command */
22773
22774 @ @<Declare action procedures for use by |do_statement|@>=
22775 pointer mp_start_draw_cmd (MP mp,quarterword sep) ;
22776
22777 @ @c pointer mp_start_draw_cmd (MP mp,quarterword sep) {
22778   pointer lhv; /* variable to add to left */
22779   quarterword add_type=0; /* value to be returned in |last_add_type| */
22780   lhv=null;
22781   mp_get_x_next(mp); mp->var_flag=sep; mp_scan_primary(mp);
22782   if ( mp->cur_type!=mp_token_list ) {
22783     @<Abandon edges command because there's no variable@>;
22784   } else  { 
22785     lhv=mp->cur_exp; add_type=mp->cur_mod;
22786     mp->cur_type=mp_vacuous; mp_get_x_next(mp); mp_scan_expression(mp);
22787   }
22788   mp->last_add_type=add_type;
22789   return lhv;
22790 }
22791
22792 @ @<Abandon edges command because there's no variable@>=
22793 { exp_err("Not a suitable variable");
22794 @.Not a suitable variable@>
22795   help4("At this point I needed to see the name of a picture variable.")
22796     ("(Or perhaps you have indeed presented me with one; I might")
22797     ("have missed it, if it wasn't followed by the proper token.)")
22798     ("So I'll not change anything just now.");
22799   mp_put_get_flush_error(mp, 0);
22800 }
22801
22802 @ Here is an example of how to use |start_draw_cmd|.
22803
22804 @<Declare action procedures for use by |do_statement|@>=
22805 void mp_do_bounds (MP mp) ;
22806
22807 @ @c void mp_do_bounds (MP mp) {
22808   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22809   pointer p; /* for list manipulation */
22810   integer m; /* initial value of |cur_mod| */
22811   m=mp->cur_mod;
22812   lhv=mp_start_draw_cmd(mp, to_token);
22813   if ( lhv!=null ) {
22814     lhe=mp_find_edges_var(mp, lhv);
22815     if ( lhe==null ) {
22816       mp_flush_cur_exp(mp, 0);
22817     } else if ( mp->cur_type!=mp_path_type ) {
22818       exp_err("Improper `clip'");
22819 @.Improper `addto'@>
22820       help2("This expression should have specified a known path.")
22821         ("So I'll not change anything just now."); 
22822       mp_put_get_flush_error(mp, 0);
22823     } else if ( left_type(mp->cur_exp)==mp_endpoint ) {
22824       @<Complain about a non-cycle@>;
22825     } else {
22826       @<Make |cur_exp| into a \&{setbounds} or clipping path and add it to |lhe|@>;
22827     }
22828   }
22829 }
22830
22831 @ @<Complain about a non-cycle@>=
22832 { print_err("Not a cycle");
22833 @.Not a cycle@>
22834   help2("That contour should have ended with `..cycle' or `&cycle'.")
22835     ("So I'll not change anything just now."); mp_put_get_error(mp);
22836 }
22837
22838 @ @<Make |cur_exp| into a \&{setbounds} or clipping path and add...@>=
22839 { p=mp_new_bounds_node(mp, mp->cur_exp,m);
22840   link(p)=link(dummy_loc(lhe));
22841   link(dummy_loc(lhe))=p;
22842   if ( obj_tail(lhe)==dummy_loc(lhe) ) obj_tail(lhe)=p;
22843   p=mp_get_node(mp, mp->gr_object_size[stop_type(m)]);
22844   type(p)=stop_type(m);
22845   link(obj_tail(lhe))=p;
22846   obj_tail(lhe)=p;
22847   mp_init_bbox(mp, lhe);
22848 }
22849
22850 @ The |do_add_to| procedure is a little like |do_clip| but there are a lot more
22851 cases to deal with.
22852
22853 @<Declare action procedures for use by |do_statement|@>=
22854 void mp_do_add_to (MP mp) ;
22855
22856 @ @c void mp_do_add_to (MP mp) {
22857   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22858   pointer p; /* the graphical object or list for |scan_with_list| to update */
22859   pointer e; /* an edge structure to be merged */
22860   quarterword add_type; /* |also_code|, |contour_code|, or |double_path_code| */
22861   lhv=mp_start_draw_cmd(mp, thing_to_add); add_type=mp->last_add_type;
22862   if ( lhv!=null ) {
22863     if ( add_type==also_code ) {
22864       @<Make sure the current expression is a suitable picture and set |e| and |p|
22865        appropriately@>;
22866     } else {
22867       @<Create a graphical object |p| based on |add_type| and the current
22868         expression@>;
22869     }
22870     mp_scan_with_list(mp, p);
22871     @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>;
22872   }
22873 }
22874
22875 @ Setting |p:=null| causes the $\langle$with list$\rangle$ to be ignored;
22876 setting |e:=null| prevents anything from being added to |lhe|.
22877
22878 @ @<Make sure the current expression is a suitable picture and set |e|...@>=
22879
22880   p=null; e=null;
22881   if ( mp->cur_type!=mp_picture_type ) {
22882     exp_err("Improper `addto'");
22883 @.Improper `addto'@>
22884     help2("This expression should have specified a known picture.")
22885       ("So I'll not change anything just now."); mp_put_get_flush_error(mp, 0);
22886   } else { 
22887     e=mp_private_edges(mp, mp->cur_exp); mp->cur_type=mp_vacuous;
22888     p=link(dummy_loc(e));
22889   }
22890 }
22891
22892 @ In this case |add_type<>also_code| so setting |p:=null| suppresses future
22893 attempts to add to the edge structure.
22894
22895 @<Create a graphical object |p| based on |add_type| and the current...@>=
22896 { e=null; p=null;
22897   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
22898   if ( mp->cur_type!=mp_path_type ) {
22899     exp_err("Improper `addto'");
22900 @.Improper `addto'@>
22901     help2("This expression should have specified a known path.")
22902       ("So I'll not change anything just now."); 
22903     mp_put_get_flush_error(mp, 0);
22904   } else if ( add_type==contour_code ) {
22905     if ( left_type(mp->cur_exp)==mp_endpoint ) {
22906       @<Complain about a non-cycle@>;
22907     } else { 
22908       p=mp_new_fill_node(mp, mp->cur_exp);
22909       mp->cur_type=mp_vacuous;
22910     }
22911   } else { 
22912     p=mp_new_stroked_node(mp, mp->cur_exp);
22913     mp->cur_type=mp_vacuous;
22914   }
22915 }
22916
22917 @ @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>=
22918 lhe=mp_find_edges_var(mp, lhv);
22919 if ( lhe==null ) {
22920   if ( (e==null)&&(p!=null) ) e=mp_toss_gr_object(mp, p);
22921   if ( e!=null ) delete_edge_ref(e);
22922 } else if ( add_type==also_code ) {
22923   if ( e!=null ) {
22924     @<Merge |e| into |lhe| and delete |e|@>;
22925   } else { 
22926     do_nothing;
22927   }
22928 } else if ( p!=null ) {
22929   link(obj_tail(lhe))=p;
22930   obj_tail(lhe)=p;
22931   if ( add_type==double_path_code )
22932     if ( pen_p(p)==null ) 
22933       pen_p(p)=mp_get_pen_circle(mp, 0);
22934 }
22935
22936 @ @<Merge |e| into |lhe| and delete |e|@>=
22937 { if ( link(dummy_loc(e))!=null ) {
22938     link(obj_tail(lhe))=link(dummy_loc(e));
22939     obj_tail(lhe)=obj_tail(e);
22940     obj_tail(e)=dummy_loc(e);
22941     link(dummy_loc(e))=null;
22942     mp_flush_dash_list(mp, lhe);
22943   }
22944   mp_toss_edges(mp, e);
22945 }
22946
22947 @ @<Cases of |do_statement|...@>=
22948 case ship_out_command: mp_do_ship_out(mp); break;
22949
22950 @ @<Declare action procedures for use by |do_statement|@>=
22951 @<Declare the function called |tfm_check|@>;
22952 @<Declare the \ps\ output procedures@>;
22953 void mp_do_ship_out (MP mp) ;
22954
22955 @ @c void mp_do_ship_out (MP mp) {
22956   integer c; /* the character code */
22957   mp_get_x_next(mp); mp_scan_expression(mp);
22958   if ( mp->cur_type!=mp_picture_type ) {
22959     @<Complain that it's not a known picture@>;
22960   } else { 
22961     c=mp_round_unscaled(mp, mp->internal[mp_char_code]) % 256;
22962     if ( c<0 ) c=c+256;
22963     @<Store the width information for character code~|c|@>;
22964     mp_ship_out(mp, mp->cur_exp);
22965     mp_flush_cur_exp(mp, 0);
22966   }
22967 }
22968
22969 @ @<Complain that it's not a known picture@>=
22970
22971   exp_err("Not a known picture");
22972   help1("I can only output known pictures.");
22973   mp_put_get_flush_error(mp, 0);
22974 }
22975
22976 @ The \&{everyjob} command simply assigns a nonzero value to the global variable
22977 |start_sym|.
22978
22979 @<Cases of |do_statement|...@>=
22980 case every_job_command: 
22981   mp_get_symbol(mp); mp->start_sym=mp->cur_sym; mp_get_x_next(mp);
22982   break;
22983
22984 @ @<Glob...@>=
22985 halfword start_sym; /* a symbolic token to insert at beginning of job */
22986
22987 @ @<Set init...@>=
22988 mp->start_sym=0;
22989
22990 @ Finally, we have only the ``message'' commands remaining.
22991
22992 @d message_code 0
22993 @d err_message_code 1
22994 @d err_help_code 2
22995 @d filename_template_code 3
22996 @d print_with_leading_zeroes(A)  g = mp->pool_ptr;
22997               mp_print_int(mp, (A)); g = mp->pool_ptr-g;
22998               if ( f>g ) {
22999                 mp->pool_ptr = mp->pool_ptr - g;
23000                 while ( f>g ) {
23001                   mp_print_char(mp, '0');
23002                   decr(f);
23003                   };
23004                 mp_print_int(mp, (A));
23005               };
23006               f = 0
23007
23008 @<Put each...@>=
23009 mp_primitive(mp, "message",message_command,message_code);
23010 @:message_}{\&{message} primitive@>
23011 mp_primitive(mp, "errmessage",message_command,err_message_code);
23012 @:err_message_}{\&{errmessage} primitive@>
23013 mp_primitive(mp, "errhelp",message_command,err_help_code);
23014 @:err_help_}{\&{errhelp} primitive@>
23015 mp_primitive(mp, "filenametemplate",message_command,filename_template_code);
23016 @:filename_template_}{\&{filenametemplate} primitive@>
23017
23018 @ @<Cases of |print_cmd...@>=
23019 case message_command: 
23020   if ( m<err_message_code ) mp_print(mp, "message");
23021   else if ( m==err_message_code ) mp_print(mp, "errmessage");
23022   else if ( m==filename_template_code ) mp_print(mp, "filenametemplate");
23023   else mp_print(mp, "errhelp");
23024   break;
23025
23026 @ @<Cases of |do_statement|...@>=
23027 case message_command: mp_do_message(mp); break;
23028
23029 @ @<Declare action procedures for use by |do_statement|@>=
23030 @<Declare a procedure called |no_string_err|@>;
23031 void mp_do_message (MP mp) ;
23032
23033
23034 @c void mp_do_message (MP mp) {
23035   int m; /* the type of message */
23036   m=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
23037   if ( mp->cur_type!=mp_string_type )
23038     mp_no_string_err(mp, "A message should be a known string expression.");
23039   else {
23040     switch (m) {
23041     case message_code: 
23042       mp_print_nl(mp, ""); mp_print_str(mp, mp->cur_exp);
23043       break;
23044     case err_message_code:
23045       @<Print string |cur_exp| as an error message@>;
23046       break;
23047     case err_help_code:
23048       @<Save string |cur_exp| as the |err_help|@>;
23049       break;
23050     case filename_template_code:
23051       @<Save the filename template@>;
23052       break;
23053     } /* there are no other cases */
23054   }
23055   mp_flush_cur_exp(mp, 0);
23056 }
23057
23058 @ @<Declare a procedure called |no_string_err|@>=
23059 void mp_no_string_err (MP mp,char *s) { 
23060    exp_err("Not a string");
23061 @.Not a string@>
23062   help1(s);
23063   mp_put_get_error(mp);
23064 }
23065
23066 @ The global variable |err_help| is zero when the user has most recently
23067 given an empty help string, or if none has ever been given.
23068
23069 @<Save string |cur_exp| as the |err_help|@>=
23070
23071   if ( mp->err_help!=0 ) delete_str_ref(mp->err_help);
23072   if ( length(mp->cur_exp)==0 ) mp->err_help=0;
23073   else  { mp->err_help=mp->cur_exp; add_str_ref(mp->err_help); }
23074 }
23075
23076 @ If \&{errmessage} occurs often in |mp_scroll_mode|, without user-defined
23077 \&{errhelp}, we don't want to give a long help message each time. So we
23078 give a verbose explanation only once.
23079
23080 @<Glob...@>=
23081 boolean long_help_seen; /* has the long \.{\\errmessage} help been used? */
23082
23083 @ @<Set init...@>=mp->long_help_seen=false;
23084
23085 @ @<Print string |cur_exp| as an error message@>=
23086
23087   print_err(""); mp_print_str(mp, mp->cur_exp);
23088   if ( mp->err_help!=0 ) {
23089     mp->use_err_help=true;
23090   } else if ( mp->long_help_seen ) { 
23091     help1("(That was another `errmessage'.)") ; 
23092   } else  { 
23093    if ( mp->interaction<mp_error_stop_mode ) mp->long_help_seen=true;
23094     help4("This error message was generated by an `errmessage'")
23095      ("command, so I can\'t give any explicit help.")
23096      ("Pretend that you're Miss Marple: Examine all clues,")
23097 @^Marple, Jane@>
23098      ("and deduce the truth by inspired guesses.");
23099   }
23100   mp_put_get_error(mp); mp->use_err_help=false;
23101 }
23102
23103 @ @<Cases of |do_statement|...@>=
23104 case write_command: mp_do_write(mp); break;
23105
23106 @ @<Declare action procedures for use by |do_statement|@>=
23107 void mp_do_write (MP mp) ;
23108
23109 @ @c void mp_do_write (MP mp) {
23110   str_number t; /* the line of text to be written */
23111   write_index n,n0; /* for searching |wr_fname| and |wr_file| arrays */
23112   int old_setting; /* for saving |selector| during output */
23113   mp_get_x_next(mp);
23114   mp_scan_expression(mp);
23115   if ( mp->cur_type!=mp_string_type ) {
23116     mp_no_string_err(mp, "The text to be written should be a known string expression");
23117   } else if ( mp->cur_cmd!=to_token ) { 
23118     print_err("Missing `to' clause");
23119     help1("A write command should end with `to <filename>'");
23120     mp_put_get_error(mp);
23121   } else { 
23122     t=mp->cur_exp; mp->cur_type=mp_vacuous;
23123     mp_get_x_next(mp);
23124     mp_scan_expression(mp);
23125     if ( mp->cur_type!=mp_string_type )
23126       mp_no_string_err(mp, "I can\'t write to that file name.  It isn't a known string");
23127     else {
23128       @<Write |t| to the file named by |cur_exp|@>;
23129     }
23130     delete_str_ref(t);
23131   }
23132   mp_flush_cur_exp(mp, 0);
23133 }
23134
23135 @ @<Write |t| to the file named by |cur_exp|@>=
23136
23137   @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if
23138     |cur_exp| must be inserted@>;
23139   if ( mp_str_vs_str(mp, t,mp->eof_line)==0 ) {
23140     @<Record the end of file on |wr_file[n]|@>;
23141   } else { 
23142     old_setting=mp->selector;
23143     mp->selector=n+write_file;
23144     mp_print_str(mp, t); mp_print_ln(mp);
23145     mp->selector = old_setting;
23146   }
23147 }
23148
23149 @ @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if...@>=
23150 {
23151   char *fn = str(mp->cur_exp);
23152   n=mp->write_files;
23153   n0=mp->write_files;
23154   while (mp_xstrcmp(fn,mp->wr_fname[n])!=0) { 
23155     if ( n==0 ) { /* bottom reached */
23156           if ( n0==mp->write_files ) {
23157         if ( mp->write_files<mp->max_write_files ) {
23158           incr(mp->write_files);
23159         } else {
23160           FILE **wr_file;
23161           char **wr_fname;
23162               write_index l,k;
23163           l = mp->max_write_files + (mp->max_write_files>>2);
23164           wr_file = xmalloc((l+1),sizeof(FILE *));
23165           wr_fname = xmalloc((l+1),sizeof(char *));
23166               for (k=0;k<=l;k++) {
23167             if (k<=mp->max_write_files) {
23168                   wr_file[k]=mp->wr_file[k]; 
23169               wr_fname[k]=mp->wr_fname[k];
23170             } else {
23171                   wr_file[k]=0; 
23172               wr_fname[k]=NULL;
23173             }
23174           }
23175               xfree(mp->wr_file); xfree(mp->wr_fname);
23176           mp->max_write_files = l;
23177           mp->wr_file = wr_file;
23178           mp->wr_fname = wr_fname;
23179         }
23180       }
23181       n=n0;
23182       mp_open_write_file(mp, fn ,n);
23183     } else { 
23184       decr(n);
23185           if ( mp->wr_fname[n]==NULL )  n0=n; 
23186     }
23187   }
23188 }
23189
23190 @ @<Record the end of file on |wr_file[n]|@>=
23191 { fclose(mp->wr_file[n]);
23192   xfree(mp->wr_fname[n]);
23193   mp->wr_fname[n]=NULL;
23194   if ( n==mp->write_files-1 ) mp->write_files=n;
23195 }
23196
23197
23198 @* \[42] Writing font metric data.
23199 \TeX\ gets its knowledge about fonts from font metric files, also called
23200 \.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
23201 but other programs know about them too. One of \MP's duties is to
23202 write \.{TFM} files so that the user's fonts can readily be
23203 applied to typesetting.
23204 @:TFM files}{\.{TFM} files@>
23205 @^font metric files@>
23206
23207 The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
23208 Since the number of bytes is always a multiple of~4, we could
23209 also regard the file as a sequence of 32-bit words, but \MP\ uses the
23210 byte interpretation. The format of \.{TFM} files was designed by
23211 Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
23212 @^Ramshaw, Lyle Harold@>
23213 of information in a compact but useful form.
23214
23215 @<Glob...@>=
23216 FILE * tfm_file; /* the font metric output goes here */
23217 char * metric_file_name; /* full name of the font metric file */
23218
23219 @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
23220 integers that give the lengths of the various subsequent portions
23221 of the file. These twelve integers are, in order:
23222 $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
23223 |lf|&length of the entire file, in words;\cr
23224 |lh|&length of the header data, in words;\cr
23225 |bc|&smallest character code in the font;\cr
23226 |ec|&largest character code in the font;\cr
23227 |nw|&number of words in the width table;\cr
23228 |nh|&number of words in the height table;\cr
23229 |nd|&number of words in the depth table;\cr
23230 |ni|&number of words in the italic correction table;\cr
23231 |nl|&number of words in the lig/kern table;\cr
23232 |nk|&number of words in the kern table;\cr
23233 |ne|&number of words in the extensible character table;\cr
23234 |np|&number of font parameter words.\cr}}$$
23235 They are all nonnegative and less than $2^{15}$. We must have |bc-1<=ec<=255|,
23236 |ne<=256|, and
23237 $$\hbox{|lf=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
23238 Note that a font may contain as many as 256 characters (if |bc=0| and |ec=255|),
23239 and as few as 0 characters (if |bc=ec+1|).
23240
23241 Incidentally, when two or more 8-bit bytes are combined to form an integer of
23242 16 or more bits, the most significant bytes appear first in the file.
23243 This is called BigEndian order.
23244 @^BigEndian order@>
23245
23246 @ The rest of the \.{TFM} file may be regarded as a sequence of ten data
23247 arrays.
23248
23249 The most important data type used here is a |fix_word|, which is
23250 a 32-bit representation of a binary fraction. A |fix_word| is a signed
23251 quantity, with the two's complement of the entire word used to represent
23252 negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
23253 binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
23254 the smallest is $-2048$. We will see below, however, that all but two of
23255 the |fix_word| values must lie between $-16$ and $+16$.
23256
23257 @ The first data array is a block of header information, which contains
23258 general facts about the font. The header must contain at least two words,
23259 |header[0]| and |header[1]|, whose meaning is explained below.  Additional
23260 header information of use to other software routines might also be
23261 included, and \MP\ will generate it if the \.{headerbyte} command occurs.
23262 For example, 16 more words of header information are in use at the Xerox
23263 Palo Alto Research Center; the first ten specify the character coding
23264 scheme used (e.g., `\.{XEROX TEXT}' or `\.{TEX MATHSY}'), the next five
23265 give the font family name (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
23266 last gives the ``face byte.''
23267
23268 \yskip\hang|header[0]| is a 32-bit check sum that \MP\ will copy into
23269 the \.{GF} output file. This helps ensure consistency between files,
23270 since \TeX\ records the check sums from the \.{TFM}'s it reads, and these
23271 should match the check sums on actual fonts that are used.  The actual
23272 relation between this check sum and the rest of the \.{TFM} file is not
23273 important; the check sum is simply an identification number with the
23274 property that incompatible fonts almost always have distinct check sums.
23275 @^check sum@>
23276
23277 \yskip\hang|header[1]| is a |fix_word| containing the design size of the
23278 font, in units of \TeX\ points. This number must be at least 1.0; it is
23279 fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
23280 font, i.e., a font that was designed to look best at a 10-point size,
23281 whatever that really means. When a \TeX\ user asks for a font `\.{at}
23282 $\delta$ \.{pt}', the effect is to override the design size and replace it
23283 by $\delta$, and to multiply the $x$ and~$y$ coordinates of the points in
23284 the font image by a factor of $\delta$ divided by the design size.  {\sl
23285 All other dimensions in the\/ \.{TFM} file are |fix_word|\kern-1pt\
23286 numbers in design-size units.} Thus, for example, the value of |param[6]|,
23287 which defines the \.{em} unit, is often the |fix_word| value $2^{20}=1.0$,
23288 since many fonts have a design size equal to one em.  The other dimensions
23289 must be less than 16 design-size units in absolute value; thus,
23290 |header[1]| and |param[1]| are the only |fix_word| entries in the whole
23291 \.{TFM} file whose first byte might be something besides 0 or 255.
23292
23293 @ Next comes the |char_info| array, which contains one |char_info_word|
23294 per character. Each word in this part of the file contains six fields
23295 packed into four bytes as follows.
23296
23297 \yskip\hang first byte: |width_index| (8 bits)\par
23298 \hang second byte: |height_index| (4 bits) times 16, plus |depth_index|
23299   (4~bits)\par
23300 \hang third byte: |italic_index| (6 bits) times 4, plus |tag|
23301   (2~bits)\par
23302 \hang fourth byte: |remainder| (8 bits)\par
23303 \yskip\noindent
23304 The actual width of a character is \\{width}|[width_index]|, in design-size
23305 units; this is a device for compressing information, since many characters
23306 have the same width. Since it is quite common for many characters
23307 to have the same height, depth, or italic correction, the \.{TFM} format
23308 imposes a limit of 16 different heights, 16 different depths, and
23309 64 different italic corrections.
23310
23311 Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
23312 \\{italic}[0]=0$ should always hold, so that an index of zero implies a
23313 value of zero.  The |width_index| should never be zero unless the
23314 character does not exist in the font, since a character is valid if and
23315 only if it lies between |bc| and |ec| and has a nonzero |width_index|.
23316
23317 @ The |tag| field in a |char_info_word| has four values that explain how to
23318 interpret the |remainder| field.
23319
23320 \yskip\hang|tag=0| (|no_tag|) means that |remainder| is unused.\par
23321 \hang|tag=1| (|lig_tag|) means that this character has a ligature/kerning
23322 program starting at location |remainder| in the |lig_kern| array.\par
23323 \hang|tag=2| (|list_tag|) means that this character is part of a chain of
23324 characters of ascending sizes, and not the largest in the chain.  The
23325 |remainder| field gives the character code of the next larger character.\par
23326 \hang|tag=3| (|ext_tag|) means that this character code represents an
23327 extensible character, i.e., a character that is built up of smaller pieces
23328 so that it can be made arbitrarily large. The pieces are specified in
23329 |exten[remainder]|.\par
23330 \yskip\noindent
23331 Characters with |tag=2| and |tag=3| are treated as characters with |tag=0|
23332 unless they are used in special circumstances in math formulas. For example,
23333 \TeX's \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
23334 operation looks for both |list_tag| and |ext_tag|.
23335
23336 @d no_tag 0 /* vanilla character */
23337 @d lig_tag 1 /* character has a ligature/kerning program */
23338 @d list_tag 2 /* character has a successor in a charlist */
23339 @d ext_tag 3 /* character is extensible */
23340
23341 @ The |lig_kern| array contains instructions in a simple programming language
23342 that explains what to do for special letter pairs. Each word in this array is a
23343 |lig_kern_command| of four bytes.
23344
23345 \yskip\hang first byte: |skip_byte|, indicates that this is the final program
23346   step if the byte is 128 or more, otherwise the next step is obtained by
23347   skipping this number of intervening steps.\par
23348 \hang second byte: |next_char|, ``if |next_char| follows the current character,
23349   then perform the operation and stop, otherwise continue.''\par
23350 \hang third byte: |op_byte|, indicates a ligature step if less than~128,
23351   a kern step otherwise.\par
23352 \hang fourth byte: |remainder|.\par
23353 \yskip\noindent
23354 In a kern step, an
23355 additional space equal to |kern[256*(op_byte-128)+remainder]| is inserted
23356 between the current character and |next_char|. This amount is
23357 often negative, so that the characters are brought closer together
23358 by kerning; but it might be positive.
23359
23360 There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
23361 $0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
23362 |remainder| is inserted between the current character and |next_char|;
23363 then the current character is deleted if $b=0$, and |next_char| is
23364 deleted if $c=0$; then we pass over $a$~characters to reach the next
23365 current character (which may have a ligature/kerning program of its own).
23366
23367 If the very first instruction of the |lig_kern| array has |skip_byte=255|,
23368 the |next_char| byte is the so-called right boundary character of this font;
23369 the value of |next_char| need not lie between |bc| and~|ec|.
23370 If the very last instruction of the |lig_kern| array has |skip_byte=255|,
23371 there is a special ligature/kerning program for a left boundary character,
23372 beginning at location |256*op_byte+remainder|.
23373 The interpretation is that \TeX\ puts implicit boundary characters
23374 before and after each consecutive string of characters from the same font.
23375 These implicit characters do not appear in the output, but they can affect
23376 ligatures and kerning.
23377
23378 If the very first instruction of a character's |lig_kern| program has
23379 |skip_byte>128|, the program actually begins in location
23380 |256*op_byte+remainder|. This feature allows access to large |lig_kern|
23381 arrays, because the first instruction must otherwise
23382 appear in a location |<=255|.
23383
23384 Any instruction with |skip_byte>128| in the |lig_kern| array must satisfy
23385 the condition
23386 $$\hbox{|256*op_byte+remainder<nl|.}$$
23387 If such an instruction is encountered during
23388 normal program execution, it denotes an unconditional halt; no ligature
23389 command is performed.
23390
23391 @d stop_flag (128)
23392   /* value indicating `\.{STOP}' in a lig/kern program */
23393 @d kern_flag (128) /* op code for a kern step */
23394 @d skip_byte(A) mp->lig_kern[(A)].b0
23395 @d next_char(A) mp->lig_kern[(A)].b1
23396 @d op_byte(A) mp->lig_kern[(A)].b2
23397 @d rem_byte(A) mp->lig_kern[(A)].b3
23398
23399 @ Extensible characters are specified by an |extensible_recipe|, which
23400 consists of four bytes called |top|, |mid|, |bot|, and |rep| (in this
23401 order). These bytes are the character codes of individual pieces used to
23402 build up a large symbol.  If |top|, |mid|, or |bot| are zero, they are not
23403 present in the built-up result. For example, an extensible vertical line is
23404 like an extensible bracket, except that the top and bottom pieces are missing.
23405
23406 Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
23407 if the piece isn't present. Then the extensible characters have the form
23408 $TR^kMR^kB$ from top to bottom, for some |k>=0|, unless $M$ is absent;
23409 in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
23410 The width of the extensible character is the width of $R$; and the
23411 height-plus-depth is the sum of the individual height-plus-depths of the
23412 components used, since the pieces are butted together in a vertical list.
23413
23414 @d ext_top(A) mp->exten[(A)].b0 /* |top| piece in a recipe */
23415 @d ext_mid(A) mp->exten[(A)].b1 /* |mid| piece in a recipe */
23416 @d ext_bot(A) mp->exten[(A)].b2 /* |bot| piece in a recipe */
23417 @d ext_rep(A) mp->exten[(A)].b3 /* |rep| piece in a recipe */
23418
23419 @ The final portion of a \.{TFM} file is the |param| array, which is another
23420 sequence of |fix_word| values.
23421
23422 \yskip\hang|param[1]=slant| is the amount of italic slant, which is used
23423 to help position accents. For example, |slant=.25| means that when you go
23424 up one unit, you also go .25 units to the right. The |slant| is a pure
23425 number; it is the only |fix_word| other than the design size itself that is
23426 not scaled by the design size.
23427
23428 \hang|param[2]=space| is the normal spacing between words in text.
23429 Note that character 040 in the font need not have anything to do with
23430 blank spaces.
23431
23432 \hang|param[3]=space_stretch| is the amount of glue stretching between words.
23433
23434 \hang|param[4]=space_shrink| is the amount of glue shrinking between words.
23435
23436 \hang|param[5]=x_height| is the size of one ex in the font; it is also
23437 the height of letters for which accents don't have to be raised or lowered.
23438
23439 \hang|param[6]=quad| is the size of one em in the font.
23440
23441 \hang|param[7]=extra_space| is the amount added to |param[2]| at the
23442 ends of sentences.
23443
23444 \yskip\noindent
23445 If fewer than seven parameters are present, \TeX\ sets the missing parameters
23446 to zero.
23447
23448 @d slant_code 1
23449 @d space_code 2
23450 @d space_stretch_code 3
23451 @d space_shrink_code 4
23452 @d x_height_code 5
23453 @d quad_code 6
23454 @d extra_space_code 7
23455
23456 @ So that is what \.{TFM} files hold. One of \MP's duties is to output such
23457 information, and it does this all at once at the end of a job.
23458 In order to prepare for such frenetic activity, it squirrels away the
23459 necessary facts in various arrays as information becomes available.
23460
23461 Character dimensions (\&{charwd}, \&{charht}, \&{chardp}, and \&{charic})
23462 are stored respectively in |tfm_width|, |tfm_height|, |tfm_depth|, and
23463 |tfm_ital_corr|. Other information about a character (e.g., about
23464 its ligatures or successors) is accessible via the |char_tag| and
23465 |char_remainder| arrays. Other information about the font as a whole
23466 is kept in additional arrays called |header_byte|, |lig_kern|,
23467 |kern|, |exten|, and |param|.
23468
23469 @d max_tfm_int 32510
23470 @d undefined_label max_tfm_int /* an undefined local label */
23471
23472 @<Glob...@>=
23473 #define TFM_ITEMS 257
23474 eight_bits bc;
23475 eight_bits ec; /* smallest and largest character codes shipped out */
23476 scaled tfm_width[TFM_ITEMS]; /* \&{charwd} values */
23477 scaled tfm_height[TFM_ITEMS]; /* \&{charht} values */
23478 scaled tfm_depth[TFM_ITEMS]; /* \&{chardp} values */
23479 scaled tfm_ital_corr[TFM_ITEMS]; /* \&{charic} values */
23480 boolean char_exists[TFM_ITEMS]; /* has this code been shipped out? */
23481 int char_tag[TFM_ITEMS]; /* |remainder| category */
23482 int char_remainder[TFM_ITEMS]; /* the |remainder| byte */
23483 char *header_byte; /* bytes of the \.{TFM} header */
23484 int header_last; /* last initialized \.{TFM} header byte */
23485 int header_size; /* size of the \.{TFM} header */
23486 four_quarters *lig_kern; /* the ligature/kern table */
23487 short nl; /* the number of ligature/kern steps so far */
23488 scaled *kern; /* distinct kerning amounts */
23489 short nk; /* the number of distinct kerns so far */
23490 four_quarters exten[TFM_ITEMS]; /* extensible character recipes */
23491 short ne; /* the number of extensible characters so far */
23492 scaled *param; /* \&{fontinfo} parameters */
23493 short np; /* the largest \&{fontinfo} parameter specified so far */
23494 short nw;short nh;short nd;short ni; /* sizes of \.{TFM} subtables */
23495 short skip_table[TFM_ITEMS]; /* local label status */
23496 boolean lk_started; /* has there been a lig/kern step in this command yet? */
23497 integer bchar; /* right boundary character */
23498 short bch_label; /* left boundary starting location */
23499 short ll;short lll; /* registers used for lig/kern processing */
23500 short label_loc[257]; /* lig/kern starting addresses */
23501 eight_bits label_char[257]; /* characters for |label_loc| */
23502 short label_ptr; /* highest position occupied in |label_loc| */
23503
23504 @ @<Allocate or initialize ...@>=
23505 mp->header_last = 0; mp->header_size = 128; /* just for init */
23506 mp->header_byte = xmalloc(mp->header_size, sizeof(char));
23507 mp->lig_kern = NULL; /* allocated when needed */
23508 mp->kern = NULL; /* allocated when needed */ 
23509 mp->param = NULL; /* allocated when needed */
23510
23511 @ @<Dealloc variables@>=
23512 xfree(mp->header_byte);
23513 xfree(mp->lig_kern);
23514 xfree(mp->kern);
23515 xfree(mp->param);
23516
23517 @ @<Set init...@>=
23518 for (k=0;k<= 255;k++ ) {
23519   mp->tfm_width[k]=0; mp->tfm_height[k]=0; mp->tfm_depth[k]=0; mp->tfm_ital_corr[k]=0;
23520   mp->char_exists[k]=false; mp->char_tag[k]=no_tag; mp->char_remainder[k]=0;
23521   mp->skip_table[k]=undefined_label;
23522 };
23523 memset(mp->header_byte,0,mp->header_size);
23524 mp->bc=255; mp->ec=0; mp->nl=0; mp->nk=0; mp->ne=0; mp->np=0;
23525 mp->internal[mp_boundary_char]=-unity;
23526 mp->bch_label=undefined_label;
23527 mp->label_loc[0]=-1; mp->label_ptr=0;
23528
23529 @ @<Declarations@>=
23530 scaled mp_tfm_check (MP mp,small_number m) ;
23531
23532 @ @<Declare the function called |tfm_check|@>=
23533 scaled mp_tfm_check (MP mp,small_number m) {
23534   if ( abs(mp->internal[m])>=fraction_half ) {
23535     print_err("Enormous "); mp_print(mp, mp->int_name[m]);
23536 @.Enormous charwd...@>
23537 @.Enormous chardp...@>
23538 @.Enormous charht...@>
23539 @.Enormous charic...@>
23540 @.Enormous designsize...@>
23541     mp_print(mp, " has been reduced");
23542     help1("Font metric dimensions must be less than 2048pt.");
23543     mp_put_get_error(mp);
23544     if ( mp->internal[m]>0 ) return (fraction_half-1);
23545     else return (1-fraction_half);
23546   } else {
23547     return mp->internal[m];
23548   }
23549 }
23550
23551 @ @<Store the width information for character code~|c|@>=
23552 if ( c<mp->bc ) mp->bc=c;
23553 if ( c>mp->ec ) mp->ec=c;
23554 mp->char_exists[c]=true;
23555 mp->tfm_width[c]=mp_tfm_check(mp, mp_char_wd);
23556 mp->tfm_height[c]=mp_tfm_check(mp, mp_char_ht);
23557 mp->tfm_depth[c]=mp_tfm_check(mp, mp_char_dp);
23558 mp->tfm_ital_corr[c]=mp_tfm_check(mp, mp_char_ic)
23559
23560 @ Now let's consider \MP's special \.{TFM}-oriented commands.
23561
23562 @<Cases of |do_statement|...@>=
23563 case tfm_command: mp_do_tfm_command(mp); break;
23564
23565 @ @d char_list_code 0
23566 @d lig_table_code 1
23567 @d extensible_code 2
23568 @d header_byte_code 3
23569 @d font_dimen_code 4
23570
23571 @<Put each...@>=
23572 mp_primitive(mp, "charlist",tfm_command,char_list_code);
23573 @:char_list_}{\&{charlist} primitive@>
23574 mp_primitive(mp, "ligtable",tfm_command,lig_table_code);
23575 @:lig_table_}{\&{ligtable} primitive@>
23576 mp_primitive(mp, "extensible",tfm_command,extensible_code);
23577 @:extensible_}{\&{extensible} primitive@>
23578 mp_primitive(mp, "headerbyte",tfm_command,header_byte_code);
23579 @:header_byte_}{\&{headerbyte} primitive@>
23580 mp_primitive(mp, "fontdimen",tfm_command,font_dimen_code);
23581 @:font_dimen_}{\&{fontdimen} primitive@>
23582
23583 @ @<Cases of |print_cmd...@>=
23584 case tfm_command: 
23585   switch (m) {
23586   case char_list_code:mp_print(mp, "charlist"); break;
23587   case lig_table_code:mp_print(mp, "ligtable"); break;
23588   case extensible_code:mp_print(mp, "extensible"); break;
23589   case header_byte_code:mp_print(mp, "headerbyte"); break;
23590   default: mp_print(mp, "fontdimen"); break;
23591   }
23592   break;
23593
23594 @ @<Declare action procedures for use by |do_statement|@>=
23595 eight_bits mp_get_code (MP mp) ;
23596
23597 @ @c eight_bits mp_get_code (MP mp) { /* scans a character code value */
23598   integer c; /* the code value found */
23599   mp_get_x_next(mp); mp_scan_expression(mp);
23600   if ( mp->cur_type==mp_known ) { 
23601     c=mp_round_unscaled(mp, mp->cur_exp);
23602     if ( c>=0 ) if ( c<256 ) return c;
23603   } else if ( mp->cur_type==mp_string_type ) {
23604     if ( length(mp->cur_exp)==1 )  { 
23605       c=mp->str_pool[mp->str_start[mp->cur_exp]];
23606       return c;
23607     }
23608   }
23609   exp_err("Invalid code has been replaced by 0");
23610 @.Invalid code...@>
23611   help2("I was looking for a number between 0 and 255, or for a")
23612        ("string of length 1. Didn't find it; will use 0 instead.");
23613   mp_put_get_flush_error(mp, 0); c=0;
23614   return c;
23615 };
23616
23617 @ @<Declare action procedures for use by |do_statement|@>=
23618 void mp_set_tag (MP mp,halfword c, small_number t, halfword r) ;
23619
23620 @ @c void mp_set_tag (MP mp,halfword c, small_number t, halfword r) { 
23621   if ( mp->char_tag[c]==no_tag ) {
23622     mp->char_tag[c]=t; mp->char_remainder[c]=r;
23623     if ( t==lig_tag ){ 
23624       incr(mp->label_ptr); mp->label_loc[mp->label_ptr]=r; 
23625       mp->label_char[mp->label_ptr]=c;
23626     }
23627   } else {
23628     @<Complain about a character tag conflict@>;
23629   }
23630 }
23631
23632 @ @<Complain about a character tag conflict@>=
23633
23634   print_err("Character ");
23635   if ( (c>' ')&&(c<127) ) mp_print_char(mp,c);
23636   else if ( c==256 ) mp_print(mp, "||");
23637   else  { mp_print(mp, "code "); mp_print_int(mp, c); };
23638   mp_print(mp, " is already ");
23639 @.Character c is already...@>
23640   switch (mp->char_tag[c]) {
23641   case lig_tag: mp_print(mp, "in a ligtable"); break;
23642   case list_tag: mp_print(mp, "in a charlist"); break;
23643   case ext_tag: mp_print(mp, "extensible"); break;
23644   } /* there are no other cases */
23645   help2("It's not legal to label a character more than once.")
23646     ("So I'll not change anything just now.");
23647   mp_put_get_error(mp); 
23648 }
23649
23650 @ @<Declare action procedures for use by |do_statement|@>=
23651 void mp_do_tfm_command (MP mp) ;
23652
23653 @ @c void mp_do_tfm_command (MP mp) {
23654   int c,cc; /* character codes */
23655   int k; /* index into the |kern| array */
23656   int j; /* index into |header_byte| or |param| */
23657   switch (mp->cur_mod) {
23658   case char_list_code: 
23659     c=mp_get_code(mp);
23660      /* we will store a list of character successors */
23661     while ( mp->cur_cmd==colon )   { 
23662       cc=mp_get_code(mp); mp_set_tag(mp, c,list_tag,cc); c=cc;
23663     };
23664     break;
23665   case lig_table_code: 
23666     if (mp->lig_kern==NULL) 
23667        mp->lig_kern = xmalloc((max_tfm_int+1),sizeof(four_quarters));
23668     if (mp->kern==NULL) 
23669        mp->kern = xmalloc((max_tfm_int+1),sizeof(scaled));
23670     @<Store a list of ligature/kern steps@>;
23671     break;
23672   case extensible_code: 
23673     @<Define an extensible recipe@>;
23674     break;
23675   case header_byte_code: 
23676   case font_dimen_code: 
23677     c=mp->cur_mod; mp_get_x_next(mp);
23678     mp_scan_expression(mp);
23679     if ( (mp->cur_type!=mp_known)||(mp->cur_exp<half_unit) ) {
23680       exp_err("Improper location");
23681 @.Improper location@>
23682       help2("I was looking for a known, positive number.")
23683        ("For safety's sake I'll ignore the present command.");
23684       mp_put_get_error(mp);
23685     } else  { 
23686       j=mp_round_unscaled(mp, mp->cur_exp);
23687       if ( mp->cur_cmd!=colon ) {
23688         mp_missing_err(mp, ":");
23689 @.Missing `:'@>
23690         help1("A colon should follow a headerbyte or fontinfo location.");
23691         mp_back_error(mp);
23692       }
23693       if ( c==header_byte_code ) { 
23694         @<Store a list of header bytes@>;
23695       } else {     
23696         if (mp->param==NULL) 
23697           mp->param = xmalloc((max_tfm_int+1),sizeof(scaled));
23698         @<Store a list of font dimensions@>;
23699       }
23700     }
23701     break;
23702   } /* there are no other cases */
23703 };
23704
23705 @ @<Store a list of ligature/kern steps@>=
23706
23707   mp->lk_started=false;
23708 CONTINUE: 
23709   mp_get_x_next(mp);
23710   if ((mp->cur_cmd==skip_to)&& mp->lk_started )
23711     @<Process a |skip_to| command and |goto done|@>;
23712   if ( mp->cur_cmd==bchar_label ) { c=256; mp->cur_cmd=colon; }
23713   else { mp_back_input(mp); c=mp_get_code(mp); };
23714   if ((mp->cur_cmd==colon)||(mp->cur_cmd==double_colon)) {
23715     @<Record a label in a lig/kern subprogram and |goto continue|@>;
23716   }
23717   if ( mp->cur_cmd==lig_kern_token ) { 
23718     @<Compile a ligature/kern command@>; 
23719   } else  { 
23720     print_err("Illegal ligtable step");
23721 @.Illegal ligtable step@>
23722     help1("I was looking for `=:' or `kern' here.");
23723     mp_back_error(mp); next_char(mp->nl)=qi(0); 
23724     op_byte(mp->nl)=qi(0); rem_byte(mp->nl)=qi(0);
23725     skip_byte(mp->nl)=stop_flag+1; /* this specifies an unconditional stop */
23726   }
23727   if ( mp->nl==max_tfm_int) mp_fatal_error(mp, "ligtable too large");
23728   incr(mp->nl);
23729   if ( mp->cur_cmd==comma ) goto CONTINUE;
23730   if ( skip_byte(mp->nl-1)<stop_flag ) skip_byte(mp->nl-1)=stop_flag;
23731 }
23732 DONE:
23733
23734 @ @<Put each...@>=
23735 mp_primitive(mp, "=:",lig_kern_token,0);
23736 @:=:_}{\.{=:} primitive@>
23737 mp_primitive(mp, "=:|",lig_kern_token,1);
23738 @:=:/_}{\.{=:\char'174} primitive@>
23739 mp_primitive(mp, "=:|>",lig_kern_token,5);
23740 @:=:/>_}{\.{=:\char'174>} primitive@>
23741 mp_primitive(mp, "|=:",lig_kern_token,2);
23742 @:=:/_}{\.{\char'174=:} primitive@>
23743 mp_primitive(mp, "|=:>",lig_kern_token,6);
23744 @:=:/>_}{\.{\char'174=:>} primitive@>
23745 mp_primitive(mp, "|=:|",lig_kern_token,3);
23746 @:=:/_}{\.{\char'174=:\char'174} primitive@>
23747 mp_primitive(mp, "|=:|>",lig_kern_token,7);
23748 @:=:/>_}{\.{\char'174=:\char'174>} primitive@>
23749 mp_primitive(mp, "|=:|>>",lig_kern_token,11);
23750 @:=:/>_}{\.{\char'174=:\char'174>>} primitive@>
23751 mp_primitive(mp, "kern",lig_kern_token,128);
23752 @:kern_}{\&{kern} primitive@>
23753
23754 @ @<Cases of |print_cmd...@>=
23755 case lig_kern_token: 
23756   switch (m) {
23757   case 0:mp_print(mp, "=:"); break;
23758   case 1:mp_print(mp, "=:|"); break;
23759   case 2:mp_print(mp, "|=:"); break;
23760   case 3:mp_print(mp, "|=:|"); break;
23761   case 5:mp_print(mp, "=:|>"); break;
23762   case 6:mp_print(mp, "|=:>"); break;
23763   case 7:mp_print(mp, "|=:|>"); break;
23764   case 11:mp_print(mp, "|=:|>>"); break;
23765   default: mp_print(mp, "kern"); break;
23766   }
23767   break;
23768
23769 @ Local labels are implemented by maintaining the |skip_table| array,
23770 where |skip_table[c]| is either |undefined_label| or the address of the
23771 most recent lig/kern instruction that skips to local label~|c|. In the
23772 latter case, the |skip_byte| in that instruction will (temporarily)
23773 be zero if there were no prior skips to this label, or it will be the
23774 distance to the prior skip.
23775
23776 We may need to cancel skips that span more than 127 lig/kern steps.
23777
23778 @d cancel_skips(A) mp->ll=(A);
23779   do {  
23780     mp->lll=qo(skip_byte(mp->ll)); 
23781     skip_byte(mp->ll)=stop_flag; mp->ll=mp->ll-mp->lll;
23782   } while (mp->lll!=0)
23783 @d skip_error(A) { print_err("Too far to skip");
23784 @.Too far to skip@>
23785   help1("At most 127 lig/kern steps can separate skipto1 from 1::.");
23786   mp_error(mp); cancel_skips((A));
23787   }
23788
23789 @<Process a |skip_to| command and |goto done|@>=
23790
23791   c=mp_get_code(mp);
23792   if ( mp->nl-mp->skip_table[c]>128 ) { /* |skip_table[c]<<nl<=undefined_label| */
23793     skip_error(mp->skip_table[c]); mp->skip_table[c]=undefined_label;
23794   }
23795   if ( mp->skip_table[c]==undefined_label ) skip_byte(mp->nl-1)=qi(0);
23796   else skip_byte(mp->nl-1)=qi(mp->nl-mp->skip_table[c]-1);
23797   mp->skip_table[c]=mp->nl-1; goto DONE;
23798 }
23799
23800 @ @<Record a label in a lig/kern subprogram and |goto continue|@>=
23801
23802   if ( mp->cur_cmd==colon ) {
23803     if ( c==256 ) mp->bch_label=mp->nl;
23804     else mp_set_tag(mp, c,lig_tag,mp->nl);
23805   } else if ( mp->skip_table[c]<undefined_label ) {
23806     mp->ll=mp->skip_table[c]; mp->skip_table[c]=undefined_label;
23807     do {  
23808       mp->lll=qo(skip_byte(mp->ll));
23809       if ( mp->nl-mp->ll>128 ) {
23810         skip_error(mp->ll); goto CONTINUE;
23811       }
23812       skip_byte(mp->ll)=qi(mp->nl-mp->ll-1); mp->ll=mp->ll-mp->lll;
23813     } while (mp->lll!=0);
23814   }
23815   goto CONTINUE;
23816 }
23817
23818 @ @<Compile a ligature/kern...@>=
23819
23820   next_char(mp->nl)=qi(c); skip_byte(mp->nl)=qi(0);
23821   if ( mp->cur_mod<128 ) { /* ligature op */
23822     op_byte(mp->nl)=qi(mp->cur_mod); rem_byte(mp->nl)=qi(mp_get_code(mp));
23823   } else { 
23824     mp_get_x_next(mp); mp_scan_expression(mp);
23825     if ( mp->cur_type!=mp_known ) {
23826       exp_err("Improper kern");
23827 @.Improper kern@>
23828       help2("The amount of kern should be a known numeric value.")
23829         ("I'm zeroing this one. Proceed, with fingers crossed.");
23830       mp_put_get_flush_error(mp, 0);
23831     }
23832     mp->kern[mp->nk]=mp->cur_exp;
23833     k=0; 
23834     while ( mp->kern[k]!=mp->cur_exp ) incr(k);
23835     if ( k==mp->nk ) {
23836       if ( mp->nk==max_tfm_int ) mp_fatal_error(mp, "too many TFM kerns");
23837       incr(mp->nk);
23838     }
23839     op_byte(mp->nl)=kern_flag+(k / 256);
23840     rem_byte(mp->nl)=qi((k % 256));
23841   }
23842   mp->lk_started=true;
23843 }
23844
23845 @ @d missing_extensible_punctuation(A) 
23846   { mp_missing_err(mp, (A));
23847 @.Missing `\char`\#'@>
23848   help1("I'm processing `extensible c: t,m,b,r'."); mp_back_error(mp);
23849   }
23850
23851 @<Define an extensible recipe@>=
23852
23853   if ( mp->ne==256 ) mp_fatal_error(mp, "too many extensible recipies");
23854   c=mp_get_code(mp); mp_set_tag(mp, c,ext_tag,mp->ne);
23855   if ( mp->cur_cmd!=colon ) missing_extensible_punctuation(":");
23856   ext_top(mp->ne)=qi(mp_get_code(mp));
23857   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23858   ext_mid(mp->ne)=qi(mp_get_code(mp));
23859   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23860   ext_bot(mp->ne)=qi(mp_get_code(mp));
23861   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23862   ext_rep(mp->ne)=qi(mp_get_code(mp));
23863   incr(mp->ne);
23864 }
23865
23866 @ The header could contain ASCII zeroes, so can't use |strdup|.
23867
23868 @<Store a list of header bytes@>=
23869 do {  
23870   if ( j>=mp->header_size ) {
23871     int l = mp->header_size + (mp->header_size >> 2);
23872     char *t = xmalloc(l,sizeof(char));
23873     memset(t,0,l); 
23874     memcpy(t,mp->header_byte,mp->header_size);
23875     xfree (mp->header_byte);
23876     mp->header_byte = t;
23877     mp->header_size = l;
23878   }
23879   mp->header_byte[j]=mp_get_code(mp); 
23880   incr(j); incr(mp->header_last);
23881 } while (mp->cur_cmd==comma)
23882
23883 @ @<Store a list of font dimensions@>=
23884 do {  
23885   if ( j>max_tfm_int ) mp_fatal_error(mp, "too many fontdimens");
23886   while ( j>mp->np ) { incr(mp->np); mp->param[mp->np]=0; };
23887   mp_get_x_next(mp); mp_scan_expression(mp);
23888   if ( mp->cur_type!=mp_known ){ 
23889     exp_err("Improper font parameter");
23890 @.Improper font parameter@>
23891     help1("I'm zeroing this one. Proceed, with fingers crossed.");
23892     mp_put_get_flush_error(mp, 0);
23893   }
23894   mp->param[j]=mp->cur_exp; incr(j);
23895 } while (mp->cur_cmd==comma)
23896
23897 @ OK: We've stored all the data that is needed for the \.{TFM} file.
23898 All that remains is to output it in the correct format.
23899
23900 An interesting problem needs to be solved in this connection, because
23901 the \.{TFM} format allows at most 256~widths, 16~heights, 16~depths,
23902 and 64~italic corrections. If the data has more distinct values than
23903 this, we want to meet the necessary restrictions by perturbing the
23904 given values as little as possible.
23905
23906 \MP\ solves this problem in two steps. First the values of a given
23907 kind (widths, heights, depths, or italic corrections) are sorted;
23908 then the list of sorted values is perturbed, if necessary.
23909
23910 The sorting operation is facilitated by having a special node of
23911 essentially infinite |value| at the end of the current list.
23912
23913 @<Initialize table entries...@>=
23914 value(inf_val)=fraction_four;
23915
23916 @ Straight linear insertion is good enough for sorting, since the lists
23917 are usually not terribly long. As we work on the data, the current list
23918 will start at |link(temp_head)| and end at |inf_val|; the nodes in this
23919 list will be in increasing order of their |value| fields.
23920
23921 Given such a list, the |sort_in| function takes a value and returns a pointer
23922 to where that value can be found in the list. The value is inserted in
23923 the proper place, if necessary.
23924
23925 At the time we need to do these operations, most of \MP's work has been
23926 completed, so we will have plenty of memory to play with. The value nodes
23927 that are allocated for sorting will never be returned to free storage.
23928
23929 @d clear_the_list link(temp_head)=inf_val
23930
23931 @c pointer mp_sort_in (MP mp,scaled v) {
23932   pointer p,q,r; /* list manipulation registers */
23933   p=temp_head;
23934   while (1) { 
23935     q=link(p);
23936     if ( v<=value(q) ) break;
23937     p=q;
23938   }
23939   if ( v<value(q) ) {
23940     r=mp_get_node(mp, value_node_size); value(r)=v; link(r)=q; link(p)=r;
23941   }
23942   return link(p);
23943 }
23944
23945 @ Now we come to the interesting part, where we reduce the list if necessary
23946 until it has the required size. The |min_cover| routine is basic to this
23947 process; it computes the minimum number~|m| such that the values of the
23948 current sorted list can be covered by |m|~intervals of width~|d|. It
23949 also sets the global value |perturbation| to the smallest value $d'>d$
23950 such that the covering found by this algorithm would be different.
23951
23952 In particular, |min_cover(0)| returns the number of distinct values in the
23953 current list and sets |perturbation| to the minimum distance between
23954 adjacent values.
23955
23956 @c integer mp_min_cover (MP mp,scaled d) {
23957   pointer p; /* runs through the current list */
23958   scaled l; /* the least element covered by the current interval */
23959   integer m; /* lower bound on the size of the minimum cover */
23960   m=0; p=link(temp_head); mp->perturbation=el_gordo;
23961   while ( p!=inf_val ){ 
23962     incr(m); l=value(p);
23963     do {  p=link(p); } while (value(p)<=l+d);
23964     if ( value(p)-l<mp->perturbation ) 
23965       mp->perturbation=value(p)-l;
23966   }
23967   return m;
23968 }
23969
23970 @ @<Glob...@>=
23971 scaled perturbation; /* quantity related to \.{TFM} rounding */
23972 integer excess; /* the list is this much too long */
23973
23974 @ The smallest |d| such that a given list can be covered with |m| intervals
23975 is determined by the |threshold| routine, which is sort of an inverse
23976 to |min_cover|. The idea is to increase the interval size rapidly until
23977 finding the range, then to go sequentially until the exact borderline has
23978 been discovered.
23979
23980 @c scaled mp_threshold (MP mp,integer m) {
23981   scaled d; /* lower bound on the smallest interval size */
23982   mp->excess=mp_min_cover(mp, 0)-m;
23983   if ( mp->excess<=0 ) {
23984     return 0;
23985   } else  { 
23986     do {  
23987       d=mp->perturbation;
23988     } while (mp_min_cover(mp, d+d)>m);
23989     while ( mp_min_cover(mp, d)>m ) 
23990       d=mp->perturbation;
23991     return d;
23992   }
23993 }
23994
23995 @ The |skimp| procedure reduces the current list to at most |m| entries,
23996 by changing values if necessary. It also sets |info(p):=k| if |value(p)|
23997 is the |k|th distinct value on the resulting list, and it sets
23998 |perturbation| to the maximum amount by which a |value| field has
23999 been changed. The size of the resulting list is returned as the
24000 value of |skimp|.
24001
24002 @c integer mp_skimp (MP mp,integer m) {
24003   scaled d; /* the size of intervals being coalesced */
24004   pointer p,q,r; /* list manipulation registers */
24005   scaled l; /* the least value in the current interval */
24006   scaled v; /* a compromise value */
24007   d=mp_threshold(mp, m); mp->perturbation=0;
24008   q=temp_head; m=0; p=link(temp_head);
24009   while ( p!=inf_val ) {
24010     incr(m); l=value(p); info(p)=m;
24011     if ( value(link(p))<=l+d ) {
24012       @<Replace an interval of values by its midpoint@>;
24013     }
24014     q=p; p=link(p);
24015   }
24016   return m;
24017 }
24018
24019 @ @<Replace an interval...@>=
24020
24021   do {  
24022     p=link(p); info(p)=m;
24023     decr(mp->excess); if ( mp->excess==0 ) d=0;
24024   } while (value(link(p))<=l+d);
24025   v=l+halfp(value(p)-l);
24026   if ( value(p)-v>mp->perturbation ) 
24027     mp->perturbation=value(p)-v;
24028   r=q;
24029   do {  
24030     r=link(r); value(r)=v;
24031   } while (r!=p);
24032   link(q)=p; /* remove duplicate values from the current list */
24033 }
24034
24035 @ A warning message is issued whenever something is perturbed by
24036 more than 1/16\thinspace pt.
24037
24038 @c void mp_tfm_warning (MP mp,small_number m) { 
24039   mp_print_nl(mp, "(some "); 
24040   mp_print(mp, mp->int_name[m]);
24041 @.some charwds...@>
24042 @.some chardps...@>
24043 @.some charhts...@>
24044 @.some charics...@>
24045   mp_print(mp, " values had to be adjusted by as much as ");
24046   mp_print_scaled(mp, mp->perturbation); mp_print(mp, "pt)");
24047 }
24048
24049 @ Here's an example of how we use these routines.
24050 The width data needs to be perturbed only if there are 256 distinct
24051 widths, but \MP\ must check for this case even though it is
24052 highly unusual.
24053
24054 An integer variable |k| will be defined when we use this code.
24055 The |dimen_head| array will contain pointers to the sorted
24056 lists of dimensions.
24057
24058 @<Massage the \.{TFM} widths@>=
24059 clear_the_list;
24060 for (k=mp->bc;k<=mp->ec;k++)  {
24061   if ( mp->char_exists[k] )
24062     mp->tfm_width[k]=mp_sort_in(mp, mp->tfm_width[k]);
24063 }
24064 mp->nw=mp_skimp(mp, 255)+1; mp->dimen_head[1]=link(temp_head);
24065 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_wd)
24066
24067 @ @<Glob...@>=
24068 pointer dimen_head[5]; /* lists of \.{TFM} dimensions */
24069
24070 @ Heights, depths, and italic corrections are different from widths
24071 not only because their list length is more severely restricted, but
24072 also because zero values do not need to be put into the lists.
24073
24074 @<Massage the \.{TFM} heights, depths, and italic corrections@>=
24075 clear_the_list;
24076 for (k=mp->bc;k<=mp->ec;k++) {
24077   if ( mp->char_exists[k] ) {
24078     if ( mp->tfm_height[k]==0 ) mp->tfm_height[k]=zero_val;
24079     else mp->tfm_height[k]=mp_sort_in(mp, mp->tfm_height[k]);
24080   }
24081 }
24082 mp->nh=mp_skimp(mp, 15)+1; mp->dimen_head[2]=link(temp_head);
24083 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ht);
24084 clear_the_list;
24085 for (k=mp->bc;k<=mp->ec;k++) {
24086   if ( mp->char_exists[k] ) {
24087     if ( mp->tfm_depth[k]==0 ) mp->tfm_depth[k]=zero_val;
24088     else mp->tfm_depth[k]=mp_sort_in(mp, mp->tfm_depth[k]);
24089   }
24090 }
24091 mp->nd=mp_skimp(mp, 15)+1; mp->dimen_head[3]=link(temp_head);
24092 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_dp);
24093 clear_the_list;
24094 for (k=mp->bc;k<=mp->ec;k++) {
24095   if ( mp->char_exists[k] ) {
24096     if ( mp->tfm_ital_corr[k]==0 ) mp->tfm_ital_corr[k]=zero_val;
24097     else mp->tfm_ital_corr[k]=mp_sort_in(mp, mp->tfm_ital_corr[k]);
24098   }
24099 }
24100 mp->ni=mp_skimp(mp, 63)+1; mp->dimen_head[4]=link(temp_head);
24101 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ic)
24102
24103 @ @<Initialize table entries...@>=
24104 value(zero_val)=0; info(zero_val)=0;
24105
24106 @ Bytes 5--8 of the header are set to the design size, unless the user has
24107 some crazy reason for specifying them differently.
24108
24109 Error messages are not allowed at the time this procedure is called,
24110 so a warning is printed instead.
24111
24112 The value of |max_tfm_dimen| is calculated so that
24113 $$\hbox{|make_scaled(16*max_tfm_dimen,internal[mp_design_size])|}
24114  < \\{three\_bytes}.$$
24115
24116 @d three_bytes 0100000000 /* $2^{24}$ */
24117
24118 @c 
24119 void mp_fix_design_size (MP mp) {
24120   scaled d; /* the design size */
24121   d=mp->internal[mp_design_size];
24122   if ( (d<unity)||(d>=fraction_half) ) {
24123     if ( d!=0 )
24124       mp_print_nl(mp, "(illegal design size has been changed to 128pt)");
24125 @.illegal design size...@>
24126     d=040000000; mp->internal[mp_design_size]=d;
24127   }
24128   if ( mp->header_byte[4]<0 ) if ( mp->header_byte[5]<0 )
24129     if ( mp->header_byte[6]<0 ) if ( mp->header_byte[7]<0 ) {
24130      mp->header_byte[4]=d / 04000000;
24131      mp->header_byte[5]=(d / 4096) % 256;
24132      mp->header_byte[6]=(d / 16) % 256;
24133      mp->header_byte[7]=(d % 16)*16;
24134   };
24135   mp->max_tfm_dimen=16*mp->internal[mp_design_size]-mp->internal[mp_design_size] / 010000000;
24136   if ( mp->max_tfm_dimen>=fraction_half ) mp->max_tfm_dimen=fraction_half-1;
24137 }
24138
24139 @ The |dimen_out| procedure computes a |fix_word| relative to the
24140 design size. If the data was out of range, it is corrected and the
24141 global variable |tfm_changed| is increased by~one.
24142
24143 @c integer mp_dimen_out (MP mp,scaled x) { 
24144   if ( abs(x)>mp->max_tfm_dimen ) {
24145     incr(mp->tfm_changed);
24146     if ( x>0 ) x=three_bytes-1; else x=1-three_bytes;
24147   } else {
24148     x=mp_make_scaled(mp, x*16,mp->internal[mp_design_size]);
24149   }
24150   return x;
24151 }
24152
24153 @ @<Glob...@>=
24154 scaled max_tfm_dimen; /* bound on widths, heights, kerns, etc. */
24155 integer tfm_changed; /* the number of data entries that were out of bounds */
24156
24157 @ If the user has not specified any of the first four header bytes,
24158 the |fix_check_sum| procedure replaces them by a ``check sum'' computed
24159 from the |tfm_width| data relative to the design size.
24160 @^check sum@>
24161
24162 @c void mp_fix_check_sum (MP mp) {
24163   eight_bits k; /* runs through character codes */
24164   eight_bits B1,B2,B3,B4; /* bytes of the check sum */
24165   integer x;  /* hash value used in check sum computation */
24166   if ( mp->header_byte[0]==0 && mp->header_byte[1]==0 &&
24167        mp->header_byte[2]==0 && mp->header_byte[3]==0 ) {
24168     @<Compute a check sum in |(b1,b2,b3,b4)|@>;
24169     mp->header_byte[0]=B1; mp->header_byte[1]=B2;
24170     mp->header_byte[2]=B3; mp->header_byte[3]=B4; 
24171     return;
24172   }
24173 }
24174
24175 @ @<Compute a check sum in |(b1,b2,b3,b4)|@>=
24176 B1=mp->bc; B2=mp->ec; B3=mp->bc; B4=mp->ec; mp->tfm_changed=0;
24177 for (k=mp->bc;k<=mp->ec;k++) { 
24178   if ( mp->char_exists[k] ) {
24179     x=mp_dimen_out(mp, value(mp->tfm_width[k]))+(k+4)*020000000; /* this is positive */
24180     B1=(B1+B1+x) % 255;
24181     B2=(B2+B2+x) % 253;
24182     B3=(B3+B3+x) % 251;
24183     B4=(B4+B4+x) % 247;
24184   }
24185 }
24186
24187 @ Finally we're ready to actually write the \.{TFM} information.
24188 Here are some utility routines for this purpose.
24189
24190 @d tfm_out(A) fputc((A),mp->tfm_file) /* output one byte to |tfm_file| */
24191
24192 @c void mp_tfm_two (MP mp,integer x) { /* output two bytes to |tfm_file| */
24193   tfm_out(x / 256); tfm_out(x % 256);
24194 }
24195 void mp_tfm_four (MP mp,integer x) { /* output four bytes to |tfm_file| */
24196   if ( x>=0 ) tfm_out(x / three_bytes);
24197   else { 
24198     x=x+010000000000; /* use two's complement for negative values */
24199     x=x+010000000000;
24200     tfm_out((x / three_bytes) + 128);
24201   };
24202   x=x % three_bytes; tfm_out(x / unity);
24203   x=x % unity; tfm_out(x / 0400);
24204   tfm_out(x % 0400);
24205 }
24206 void mp_tfm_qqqq (MP mp,four_quarters x) { /* output four quarterwords to |tfm_file| */
24207   tfm_out(qo(x.b0)); tfm_out(qo(x.b1)); 
24208   tfm_out(qo(x.b2)); tfm_out(qo(x.b3));
24209 }
24210
24211 @ @<Finish the \.{TFM} file@>=
24212 if ( mp->job_name==NULL ) mp_open_log_file(mp);
24213 mp_pack_job_name(mp, ".tfm");
24214 while ( ! mp_b_open_out(mp, &mp->tfm_file, mp_filetype_metrics) )
24215   mp_prompt_file_name(mp, "file name for font metrics",".tfm");
24216 mp->metric_file_name=xstrdup(mp->name_of_file);
24217 @<Output the subfile sizes and header bytes@>;
24218 @<Output the character information bytes, then
24219   output the dimensions themselves@>;
24220 @<Output the ligature/kern program@>;
24221 @<Output the extensible character recipes and the font metric parameters@>;
24222   if ( mp->internal[mp_tracing_stats]>0 )
24223   @<Log the subfile sizes of the \.{TFM} file@>;
24224 mp_print_nl(mp, "Font metrics written on "); 
24225 mp_print(mp, mp->metric_file_name); mp_print_char(mp, '.');
24226 @.Font metrics written...@>
24227 fclose(mp->tfm_file)
24228
24229 @ Integer variables |lh|, |k|, and |lk_offset| will be defined when we use
24230 this code.
24231
24232 @<Output the subfile sizes and header bytes@>=
24233 k=mp->header_last;
24234 LH=(k+3) / 4; /* this is the number of header words */
24235 if ( mp->bc>mp->ec ) mp->bc=1; /* if there are no characters, |ec=0| and |bc=1| */
24236 @<Compute the ligature/kern program offset and implant the
24237   left boundary label@>;
24238 mp_tfm_two(mp,6+LH+(mp->ec-mp->bc+1)+mp->nw+mp->nh+mp->nd+mp->ni+mp->nl
24239      +lk_offset+mp->nk+mp->ne+mp->np);
24240   /* this is the total number of file words that will be output */
24241 mp_tfm_two(mp, LH); mp_tfm_two(mp, mp->bc); mp_tfm_two(mp, mp->ec); 
24242 mp_tfm_two(mp, mp->nw); mp_tfm_two(mp, mp->nh);
24243 mp_tfm_two(mp, mp->nd); mp_tfm_two(mp, mp->ni); mp_tfm_two(mp, mp->nl+lk_offset); 
24244 mp_tfm_two(mp, mp->nk); mp_tfm_two(mp, mp->ne);
24245 mp_tfm_two(mp, mp->np);
24246 for (k=0;k< 4*LH;k++)   { 
24247   tfm_out(mp->header_byte[k]);
24248 }
24249
24250 @ @<Output the character information bytes...@>=
24251 for (k=mp->bc;k<=mp->ec;k++) {
24252   if ( ! mp->char_exists[k] ) {
24253     mp_tfm_four(mp, 0);
24254   } else { 
24255     tfm_out(info(mp->tfm_width[k])); /* the width index */
24256     tfm_out((info(mp->tfm_height[k]))*16+info(mp->tfm_depth[k]));
24257     tfm_out((info(mp->tfm_ital_corr[k]))*4+mp->char_tag[k]);
24258     tfm_out(mp->char_remainder[k]);
24259   };
24260 }
24261 mp->tfm_changed=0;
24262 for (k=1;k<=4;k++) { 
24263   mp_tfm_four(mp, 0); p=mp->dimen_head[k];
24264   while ( p!=inf_val ) {
24265     mp_tfm_four(mp, mp_dimen_out(mp, value(p))); p=link(p);
24266   }
24267 }
24268
24269
24270 @ We need to output special instructions at the beginning of the
24271 |lig_kern| array in order to specify the right boundary character
24272 and/or to handle starting addresses that exceed 255. The |label_loc|
24273 and |label_char| arrays have been set up to record all the
24274 starting addresses; we have $-1=|label_loc|[0]<|label_loc|[1]\le\cdots
24275 \le|label_loc|[|label_ptr]|$.
24276
24277 @<Compute the ligature/kern program offset...@>=
24278 mp->bchar=mp_round_unscaled(mp, mp->internal[mp_boundary_char]);
24279 if ((mp->bchar<0)||(mp->bchar>255))
24280   { mp->bchar=-1; mp->lk_started=false; lk_offset=0; }
24281 else { mp->lk_started=true; lk_offset=1; };
24282 @<Find the minimum |lk_offset| and adjust all remainders@>;
24283 if ( mp->bch_label<undefined_label )
24284   { skip_byte(mp->nl)=qi(255); next_char(mp->nl)=qi(0);
24285   op_byte(mp->nl)=qi(((mp->bch_label+lk_offset)/ 256));
24286   rem_byte(mp->nl)=qi(((mp->bch_label+lk_offset)% 256));
24287   incr(mp->nl); /* possibly |nl=lig_table_size+1| */
24288   }
24289
24290 @ @<Find the minimum |lk_offset|...@>=
24291 k=mp->label_ptr; /* pointer to the largest unallocated label */
24292 if ( mp->label_loc[k]+lk_offset>255 ) {
24293   lk_offset=0; mp->lk_started=false; /* location 0 can do double duty */
24294   do {  
24295     mp->char_remainder[mp->label_char[k]]=lk_offset;
24296     while ( mp->label_loc[k-1]==mp->label_loc[k] ) {
24297        decr(k); mp->char_remainder[mp->label_char[k]]=lk_offset;
24298     }
24299     incr(lk_offset); decr(k);
24300   } while (! (lk_offset+mp->label_loc[k]<256));
24301     /* N.B.: |lk_offset=256| satisfies this when |k=0| */
24302 };
24303 if ( lk_offset>0 ) {
24304   while ( k>0 ) {
24305     mp->char_remainder[mp->label_char[k]]
24306      =mp->char_remainder[mp->label_char[k]]+lk_offset;
24307     decr(k);
24308   }
24309 }
24310
24311 @ @<Output the ligature/kern program@>=
24312 for (k=0;k<= 255;k++ ) {
24313   if ( mp->skip_table[k]<undefined_label ) {
24314      mp_print_nl(mp, "(local label "); mp_print_int(mp, k); mp_print(mp, ":: was missing)");
24315 @.local label l:: was missing@>
24316     cancel_skips(mp->skip_table[k]);
24317   }
24318 }
24319 if ( mp->lk_started ) { /* |lk_offset=1| for the special |bchar| */
24320   tfm_out(255); tfm_out(mp->bchar); mp_tfm_two(mp, 0);
24321 } else {
24322   for (k=1;k<=lk_offset;k++) {/* output the redirection specs */
24323     mp->ll=mp->label_loc[mp->label_ptr];
24324     if ( mp->bchar<0 ) { tfm_out(254); tfm_out(0);   }
24325     else { tfm_out(255); tfm_out(mp->bchar);   };
24326     mp_tfm_two(mp, mp->ll+lk_offset);
24327     do {  
24328       decr(mp->label_ptr);
24329     } while (! (mp->label_loc[mp->label_ptr]<mp->ll));
24330   }
24331 }
24332 for (k=0;k<=mp->nl-1;k++) mp_tfm_qqqq(mp, mp->lig_kern[k]);
24333 for (k=0;k<=mp->nk-1;k++) mp_tfm_four(mp, mp_dimen_out(mp, mp->kern[k]))
24334
24335 @ @<Output the extensible character recipes...@>=
24336 for (k=0;k<=mp->ne-1;k++) 
24337   mp_tfm_qqqq(mp, mp->exten[k]);
24338 for (k=1;k<=mp->np;k++) {
24339   if ( k==1 ) {
24340     if ( abs(mp->param[1])<fraction_half ) {
24341       mp_tfm_four(mp, mp->param[1]*16);
24342     } else  { 
24343       incr(mp->tfm_changed);
24344       if ( mp->param[1]>0 ) mp_tfm_four(mp, el_gordo);
24345       else mp_tfm_four(mp, -el_gordo);
24346     }
24347   } else {
24348     mp_tfm_four(mp, mp_dimen_out(mp, mp->param[k]));
24349   }
24350 }
24351 if ( mp->tfm_changed>0 )  { 
24352   if ( mp->tfm_changed==1 ) mp_print_nl(mp, "(a font metric dimension");
24353 @.a font metric dimension...@>
24354   else  { 
24355     mp_print_nl(mp, "("); mp_print_int(mp, mp->tfm_changed);
24356 @.font metric dimensions...@>
24357     mp_print(mp, " font metric dimensions");
24358   }
24359   mp_print(mp, " had to be decreased)");
24360 }
24361
24362 @ @<Log the subfile sizes of the \.{TFM} file@>=
24363
24364   char s[200];
24365   wlog_ln(" ");
24366   if ( mp->bch_label<undefined_label ) decr(mp->nl);
24367   snprintf(s,128,"(You used %iw,%ih,%id,%ii,%il,%ik,%ie,%ip metric file positions)",
24368                  mp->nw, mp->nh, mp->nd, mp->ni, mp->nl, mp->nk, mp->ne,mp->np);
24369   wlog_ln(s);
24370 }
24371
24372 @* \[43] Reading font metric data.
24373
24374 \MP\ isn't a typesetting program but it does need to find the bounding box
24375 of a sequence of typeset characters.  Thus it needs to read \.{TFM} files as
24376 well as write them.
24377
24378 @<Glob...@>=
24379 FILE * tfm_infile;
24380
24381 @ All the width, height, and depth information is stored in an array called
24382 |font_info|.  This array is allocated sequentially and each font is stored
24383 as a series of |char_info| words followed by the width, height, and depth
24384 tables.  Since |font_name| entries are permanent, their |str_ref| values are
24385 set to |max_str_ref|.
24386
24387 @<Types...@>=
24388 typedef unsigned int font_number; /* |0..font_max| */
24389
24390 @ The |font_info| array is indexed via a group directory arrays.
24391 For example, the |char_info| data for character~|c| in font~|f| will be
24392 in |font_info[char_base[f]+c].qqqq|.
24393
24394 @<Glob...@>=
24395 font_number font_max; /* maximum font number for included text fonts */
24396 size_t      font_mem_size; /* number of words for \.{TFM} information for text fonts */
24397 memory_word *font_info; /* height, width, and depth data */
24398 char        **font_enc_name; /* encoding names, if any */
24399 boolean     *font_ps_name_fixed; /* are the postscript names fixed already?  */
24400 int         next_fmem; /* next unused entry in |font_info| */
24401 font_number last_fnum; /* last font number used so far */
24402 scaled      *font_dsize;  /* 16 times the ``design'' size in \ps\ points */
24403 char        **font_name;  /* name as specified in the \&{infont} command */
24404 char        **font_ps_name;  /* PostScript name for use when |internal[mp_prologues]>0| */
24405 font_number last_ps_fnum; /* last valid |font_ps_name| index */
24406 eight_bits  *font_bc;
24407 eight_bits  *font_ec;  /* first and last character code */
24408 int         *char_base;  /* base address for |char_info| */
24409 int         *width_base; /* index for zeroth character width */
24410 int         *height_base; /* index for zeroth character height */
24411 int         *depth_base; /* index for zeroth character depth */
24412 pointer     *font_sizes;
24413
24414 @ @<Allocate or initialize ...@>=
24415 mp->font_mem_size = 10000; 
24416 mp->font_info = xmalloc ((mp->font_mem_size+1),sizeof(memory_word));
24417 memset (mp->font_info,0,sizeof(memory_word)*(mp->font_mem_size+1));
24418 mp->font_enc_name = NULL;
24419 mp->font_ps_name_fixed = NULL;
24420 mp->font_dsize = NULL;
24421 mp->font_name = NULL;
24422 mp->font_ps_name = NULL;
24423 mp->font_bc = NULL;
24424 mp->font_ec = NULL;
24425 mp->last_fnum = null_font;
24426 mp->char_base = NULL;
24427 mp->width_base = NULL;
24428 mp->height_base = NULL;
24429 mp->depth_base = NULL;
24430 mp->font_sizes = null;
24431
24432 @ @<Dealloc variables@>=
24433 xfree(mp->font_info);
24434 xfree(mp->font_enc_name);
24435 xfree(mp->font_ps_name_fixed);
24436 xfree(mp->font_dsize);
24437 xfree(mp->font_name);
24438 xfree(mp->font_ps_name);
24439 xfree(mp->font_bc);
24440 xfree(mp->font_ec);
24441 xfree(mp->char_base);
24442 xfree(mp->width_base);
24443 xfree(mp->height_base);
24444 xfree(mp->depth_base);
24445 xfree(mp->font_sizes);
24446
24447
24448 @c 
24449 void mp_reallocate_fonts (MP mp, font_number l) {
24450   font_number f;
24451   XREALLOC(mp->font_enc_name,      l, char *);
24452   XREALLOC(mp->font_ps_name_fixed, l, boolean);
24453   XREALLOC(mp->font_dsize,         l, scaled);
24454   XREALLOC(mp->font_name,          l, char *);
24455   XREALLOC(mp->font_ps_name,       l, char *);
24456   XREALLOC(mp->font_bc,            l, eight_bits);
24457   XREALLOC(mp->font_ec,            l, eight_bits);
24458   XREALLOC(mp->char_base,          l, int);
24459   XREALLOC(mp->width_base,         l, int);
24460   XREALLOC(mp->height_base,        l, int);
24461   XREALLOC(mp->depth_base,         l, int);
24462   XREALLOC(mp->font_sizes,         l, pointer);
24463   for (f=(mp->last_fnum+1);f<=l;f++) {
24464     mp->font_enc_name[f]=NULL;
24465     mp->font_ps_name_fixed[f] = false;
24466     mp->font_name[f]=NULL;
24467     mp->font_ps_name[f]=NULL;
24468     mp->font_sizes[f]=null;
24469   }
24470   mp->font_max = l;
24471 }
24472
24473 @ @<Declare |mp_reallocate| functions@>=
24474 void mp_reallocate_fonts (MP mp, font_number l);
24475
24476
24477 @ A |null_font| containing no characters is useful for error recovery.  Its
24478 |font_name| entry starts out empty but is reset each time an erroneous font is
24479 found.  This helps to cut down on the number of duplicate error messages without
24480 wasting a lot of space.
24481
24482 @d null_font 0 /* the |font_number| for an empty font */
24483
24484 @<Set initial...@>=
24485 mp->font_dsize[null_font]=0;
24486 mp->font_bc[null_font]=1;
24487 mp->font_ec[null_font]=0;
24488 mp->char_base[null_font]=0;
24489 mp->width_base[null_font]=0;
24490 mp->height_base[null_font]=0;
24491 mp->depth_base[null_font]=0;
24492 mp->next_fmem=0;
24493 mp->last_fnum=null_font;
24494 mp->last_ps_fnum=null_font;
24495 mp->font_name[null_font]="nullfont";
24496 mp->font_ps_name[null_font]="";
24497
24498 @ Each |char_info| word is of type |four_quarters|.  The |b0| field contains
24499 the |width index|; the |b1| field contains the height
24500 index; the |b2| fields contains the depth index, and the |b3| field used only
24501 for temporary storage. (It is used to keep track of which characters occur in
24502 an edge structure that is being shipped out.)
24503 The corresponding words in the width, height, and depth tables are stored as
24504 |scaled| values in units of \ps\ points.
24505
24506 With the macros below, the |char_info| word for character~|c| in font~|f| is
24507 |char_info(f)(c)| and the width is
24508 $$\hbox{|char_width(f)(char_info(f)(c)).sc|.}$$
24509
24510 @d char_info_end(A) (A)].qqqq
24511 @d char_info(A) mp->font_info[mp->char_base[(A)]+char_info_end
24512 @d char_width_end(A) (A).b0].sc
24513 @d char_width(A) mp->font_info[mp->width_base[(A)]+char_width_end
24514 @d char_height_end(A) (A).b1].sc
24515 @d char_height(A) mp->font_info[mp->height_base[(A)]+char_height_end
24516 @d char_depth_end(A) (A).b2].sc
24517 @d char_depth(A) mp->font_info[mp->depth_base[(A)]+char_depth_end
24518 @d ichar_exists(A) ((A).b0>0)
24519
24520 @ The |font_ps_name| for a built-in font should be what PostScript expects.
24521 A preliminary name is obtained here from the \.{TFM} name as given in the
24522 |fname| argument.  This gets updated later from an external table if necessary.
24523
24524 @<Declare text measuring subroutines@>=
24525 @<Declare subroutines for parsing file names@>;
24526 font_number mp_read_font_info (MP mp, char*fname) {
24527   boolean file_opened; /* has |tfm_infile| been opened? */
24528   font_number n; /* the number to return */
24529   halfword lf,tfm_lh,bc,ec,nw,nh,nd; /* subfile size parameters */
24530   size_t whd_size; /* words needed for heights, widths, and depths */
24531   int i,ii; /* |font_info| indices */
24532   int jj; /* counts bytes to be ignored */
24533   scaled z; /* used to compute the design size */
24534   fraction d;
24535   /* height, width, or depth as a fraction of design size times $2^{-8}$ */
24536   eight_bits h_and_d; /* height and depth indices being unpacked */
24537   int tfbyte; /* a byte read from the file */
24538   n=null_font;
24539   @<Open |tfm_infile| for input@>;
24540   @<Read data from |tfm_infile|; if there is no room, say so and |goto done|;
24541     otherwise |goto bad_tfm| or |goto done| as appropriate@>;
24542 BAD_TFM:
24543   @<Complain that the \.{TFM} file is bad@>;
24544 DONE:
24545   if ( file_opened ) fclose(mp->tfm_infile);
24546   if ( n!=null_font ) { 
24547     mp->font_ps_name[n]=fname;
24548     mp->font_name[n]=fname;
24549   }
24550   return n;
24551 }
24552
24553 @ \MP\ doesn't bother to check the entire \.{TFM} file for errors or explain
24554 precisely what is wrong if it does find a problem.  Programs called \.{TFtoPL}
24555 @.TFtoPL@> @.PLtoTF@>
24556 and \.{PLtoTF} can be used to debug \.{TFM} files.
24557
24558 @<Complain that the \.{TFM} file is bad@>=
24559 print_err("Font ");
24560 mp_print(mp, fname);
24561 if ( file_opened ) mp_print(mp, " not usable: TFM file is bad");
24562 else mp_print(mp, " not usable: TFM file not found");
24563 help3("I wasn't able to read the size data for this font so this")
24564   ("`infont' operation won't produce anything. If the font name")
24565   ("is right, you might ask an expert to make a TFM file");
24566 if ( file_opened )
24567   mp->help_line[0]="is right, try asking an expert to fix the TFM file";
24568 mp_error(mp)
24569
24570 @ @<Read data from |tfm_infile|; if there is no room, say so...@>=
24571 @<Read the \.{TFM} size fields@>;
24572 @<Use the size fields to allocate space in |font_info|@>;
24573 @<Read the \.{TFM} header@>;
24574 @<Read the character data and the width, height, and depth tables and
24575   |goto done|@>
24576
24577 @ A bad \.{TFM} file can be shorter than it claims to be.  The code given here
24578 might try to read past the end of the file if this happens.  Changes will be
24579 needed if it causes a system error to refer to |tfm_infile^| or call
24580 |get_tfm_infile| when |eof(tfm_infile)| is true.  For example, the definition
24581 @^system dependencies@>
24582 of |tfget| could be changed to
24583 ``|begin get(tfm_infile); if eof(tfm_infile) then goto bad_tfm; end|.''
24584
24585 @d tfget {tfbyte = fgetc(mp->tfm_infile); }
24586 @d read_two(A) { (A)=tfbyte;
24587   if ( (A)>127 ) goto BAD_TFM;
24588   tfget; (A)=(A)*0400+tfbyte;
24589   }
24590 @d tf_ignore(A) { for (jj=(A);jj>=1;jj--) tfget; }
24591
24592 @<Read the \.{TFM} size fields@>=
24593 tfget; read_two(lf);
24594 tfget; read_two(tfm_lh);
24595 tfget; read_two(bc);
24596 tfget; read_two(ec);
24597 if ( (bc>1+ec)||(ec>255) ) goto BAD_TFM;
24598 tfget; read_two(nw);
24599 tfget; read_two(nh);
24600 tfget; read_two(nd);
24601 whd_size=(ec+1-bc)+nw+nh+nd;
24602 if ( lf<(int)(6+tfm_lh+whd_size) ) goto BAD_TFM;
24603 tf_ignore(10)
24604
24605 @ Offsets are added to |char_base[n]| and |width_base[n]| so that is not
24606 necessary to apply the |so|  and |qo| macros when looking up the width of a
24607 character in the string pool.  In order to ensure nonnegative |char_base|
24608 values when |bc>0|, it may be necessary to reserve a few unused |font_info|
24609 elements.
24610
24611 @<Use the size fields to allocate space in |font_info|@>=
24612 if ( mp->next_fmem<bc) mp->next_fmem=bc;  /* ensure nonnegative |char_base| */
24613 if (mp->last_fnum==mp->font_max)
24614   mp_reallocate_fonts(mp,(mp->font_max+(mp->font_max>>2)));
24615 while (mp->next_fmem+whd_size>=mp->font_mem_size) {
24616   size_t l = mp->font_mem_size+(mp->font_mem_size>>2);
24617   memory_word *font_info;
24618   font_info = xmalloc ((l+1),sizeof(memory_word));
24619   memset (font_info,0,sizeof(memory_word)*(l+1));
24620   memcpy (font_info,mp->font_info,sizeof(memory_word)*(mp->font_mem_size+1));
24621   xfree(mp->font_info);
24622   mp->font_info = font_info;
24623   mp->font_mem_size = l;
24624 }
24625 incr(mp->last_fnum);
24626 n=mp->last_fnum;
24627 mp->font_bc[n]=bc;
24628 mp->font_ec[n]=ec;
24629 mp->char_base[n]=mp->next_fmem-bc;
24630 mp->width_base[n]=mp->next_fmem+ec-bc+1;
24631 mp->height_base[n]=mp->width_base[n]+nw;
24632 mp->depth_base[n]=mp->height_base[n]+nh;
24633 mp->next_fmem=mp->next_fmem+whd_size;
24634
24635
24636 @ @<Read the \.{TFM} header@>=
24637 if ( tfm_lh<2 ) goto BAD_TFM;
24638 tf_ignore(4);
24639 tfget; read_two(z);
24640 tfget; z=z*0400+tfbyte;
24641 tfget; z=z*0400+tfbyte; /* now |z| is 16 times the design size */
24642 mp->font_dsize[n]=mp_take_fraction(mp, z,267432584);
24643   /* times ${72\over72.27}2^{28}$ to convert from \TeX\ points */
24644 tf_ignore(4*(tfm_lh-2))
24645
24646 @ @<Read the character data and the width, height, and depth tables...@>=
24647 ii=mp->width_base[n];
24648 i=mp->char_base[n]+bc;
24649 while ( i<ii ) { 
24650   tfget; mp->font_info[i].qqqq.b0=qi(tfbyte);
24651   tfget; h_and_d=tfbyte;
24652   mp->font_info[i].qqqq.b1=h_and_d / 16;
24653   mp->font_info[i].qqqq.b2=h_and_d % 16;
24654   tfget; tfget;
24655   incr(i);
24656 }
24657 while ( i<mp->next_fmem ) {
24658   @<Read a four byte dimension, scale it by the design size, store it in
24659     |font_info[i]|, and increment |i|@>;
24660 }
24661 if (feof(mp->tfm_infile) ) goto BAD_TFM;
24662 goto DONE
24663
24664 @ The raw dimension read into |d| should have magnitude at most $2^{24}$ when
24665 interpreted as an integer, and this includes a scale factor of $2^{20}$.  Thus
24666 we can multiply it by sixteen and think of it as a |fraction| that has been
24667 divided by sixteen.  This cancels the extra scale factor contained in
24668 |font_dsize[n|.
24669
24670 @<Read a four byte dimension, scale it by the design size, store it in...@>=
24671
24672 tfget; d=tfbyte;
24673 if ( d>=0200 ) d=d-0400;
24674 tfget; d=d*0400+tfbyte;
24675 tfget; d=d*0400+tfbyte;
24676 tfget; d=d*0400+tfbyte;
24677 mp->font_info[i].sc=mp_take_fraction(mp, d*16,mp->font_dsize[n]);
24678 incr(i);
24679 }
24680
24681 @ This function does no longer use the file name parser, because |fname| is
24682 a C string already.
24683 @<Open |tfm_infile| for input@>=
24684 file_opened=false;
24685 mp_ptr_scan_file(mp, fname);
24686 if ( strlen(mp->cur_area)==0 ) { xfree(mp->cur_area); mp->cur_area=xstrdup(MP_font_area);}
24687 if ( strlen(mp->cur_ext)==0 )  { xfree(mp->cur_ext); mp->cur_ext=xstrdup(".tfm"); }
24688 pack_cur_name;
24689 mp->tfm_infile = mp_open_file(mp, mp->name_of_file, "rb",mp_filetype_metrics);
24690 if ( !mp->tfm_infile  ) goto BAD_TFM;
24691 file_opened=true
24692
24693 @ When we have a font name and we don't know whether it has been loaded yet,
24694 we scan the |font_name| array before calling |read_font_info|.
24695
24696 @<Declare text measuring subroutines@>=
24697 font_number mp_find_font (MP mp, char *f) {
24698   font_number n;
24699   for (n=0;n<=mp->last_fnum;n++) {
24700     if (mp_xstrcmp(f,mp->font_name[n])==0 )
24701       return n;
24702   }
24703   return mp_read_font_info(mp, f);
24704 }
24705
24706 @ One simple application of |find_font| is the implementation of the |font_size|
24707 operator that gets the design size for a given font name.
24708
24709 @<Find the design size of the font whose name is |cur_exp|@>=
24710 mp_flush_cur_exp(mp, (mp->font_dsize[mp_find_font(mp, str(mp->cur_exp))]+8) / 16)
24711
24712 @ If we discover that the font doesn't have a requested character, we omit it
24713 from the bounding box computation and expect the \ps\ interpreter to drop it.
24714 This routine issues a warning message if the user has asked for it.
24715
24716 @<Declare text measuring subroutines@>=
24717 void mp_lost_warning (MP mp,font_number f, pool_pointer k) { 
24718   if ( mp->internal[mp_tracing_lost_chars]>0 ) { 
24719     mp_begin_diagnostic(mp);
24720     if ( mp->selector==log_only ) incr(mp->selector);
24721     mp_print_nl(mp, "Missing character: There is no ");
24722 @.Missing character@>
24723     mp_print_str(mp, mp->str_pool[k]); 
24724     mp_print(mp, " in font ");
24725     mp_print(mp, mp->font_name[f]); mp_print_char(mp, '!'); 
24726     mp_end_diagnostic(mp, false);
24727   }
24728 }
24729
24730 @ The whole purpose of saving the height, width, and depth information is to be
24731 able to find the bounding box of an item of text in an edge structure.  The
24732 |set_text_box| procedure takes a text node and adds this information.
24733
24734 @<Declare text measuring subroutines@>=
24735 void mp_set_text_box (MP mp,pointer p) {
24736   font_number f; /* |font_n(p)| */
24737   ASCII_code bc,ec; /* range of valid characters for font |f| */
24738   pool_pointer k,kk; /* current character and character to stop at */
24739   four_quarters cc; /* the |char_info| for the current character */
24740   scaled h,d; /* dimensions of the current character */
24741   width_val(p)=0;
24742   height_val(p)=-el_gordo;
24743   depth_val(p)=-el_gordo;
24744   f=font_n(p);
24745   bc=mp->font_bc[f];
24746   ec=mp->font_ec[f];
24747   kk=str_stop(text_p(p));
24748   k=mp->str_start[text_p(p)];
24749   while ( k<kk ) {
24750     @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>;
24751   }
24752   @<Set the height and depth to zero if the bounding box is empty@>;
24753 }
24754
24755 @ @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>=
24756
24757   if ( (mp->str_pool[k]<bc)||(mp->str_pool[k]>ec) ) {
24758     mp_lost_warning(mp, f,k);
24759   } else { 
24760     cc=char_info(f)(mp->str_pool[k]);
24761     if ( ! ichar_exists(cc) ) {
24762       mp_lost_warning(mp, f,k);
24763     } else { 
24764       width_val(p)=width_val(p)+char_width(f)(cc);
24765       h=char_height(f)(cc);
24766       d=char_depth(f)(cc);
24767       if ( h>height_val(p) ) height_val(p)=h;
24768       if ( d>depth_val(p) ) depth_val(p)=d;
24769     }
24770   }
24771   incr(k);
24772 }
24773
24774 @ Let's hope modern compilers do comparisons correctly when the difference would
24775 overflow.
24776
24777 @<Set the height and depth to zero if the bounding box is empty@>=
24778 if ( height_val(p)<-depth_val(p) ) { 
24779   height_val(p)=0;
24780   depth_val(p)=0;
24781 }
24782
24783 @ The new primitives fontmapfile and fontmapline.
24784
24785 @<Declare action procedures for use by |do_statement|@>=
24786 void mp_do_mapfile (MP mp) ;
24787 void mp_do_mapline (MP mp) ;
24788
24789 @ @c void mp_do_mapfile (MP mp) { 
24790   mp_get_x_next(mp); mp_scan_expression(mp);
24791   if ( mp->cur_type!=mp_string_type ) {
24792     @<Complain about improper map operation@>;
24793   } else {
24794     mp_map_file(mp,mp->cur_exp);
24795   }
24796 }
24797 void mp_do_mapline (MP mp) { 
24798   mp_get_x_next(mp); mp_scan_expression(mp);
24799   if ( mp->cur_type!=mp_string_type ) {
24800      @<Complain about improper map operation@>;
24801   } else { 
24802      mp_map_line(mp,mp->cur_exp);
24803   }
24804 }
24805
24806 @ @<Complain about improper map operation@>=
24807
24808   exp_err("Unsuitable expression");
24809   help1("Only known strings can be map files or map lines.");
24810   mp_put_get_error(mp);
24811 }
24812
24813 @ This is temporary.
24814
24815 @d ps_room(A) mp_ps_room(mp,A)
24816
24817 @ To print |scaled| value to PDF output we need some subroutines to ensure
24818 accurary.
24819
24820 @d max_integer   0x7FFFFFFF /* $2^{31}-1$ */
24821
24822 @<Glob...@>=
24823 scaled one_bp; /* scaled value corresponds to 1bp */
24824 scaled one_hundred_bp; /* scaled value corresponds to 100bp */
24825 scaled one_hundred_inch; /* scaled value corresponds to 100in */
24826 integer ten_pow[10]; /* $10^0..10^9$ */
24827 integer scaled_out; /* amount of |scaled| that was taken out in |divide_scaled| */
24828
24829 @ @<Set init...@>=
24830 mp->one_bp = 65782; /* 65781.76 */
24831 mp->one_hundred_bp = 6578176;
24832 mp->one_hundred_inch = 473628672;
24833 mp->ten_pow[0] = 1;
24834 for (i = 1;i<= 9; i++ ) {
24835   mp->ten_pow[i] = 10*mp->ten_pow[i - 1];
24836 }
24837
24838 @ The following function divides |s| by |m|. |dd| is number of decimal digits.
24839
24840 @c scaled mp_divide_scaled (MP mp,scaled s, scaled m, integer  dd) {
24841   scaled q,r;
24842   integer sign,i;
24843   sign = 1;
24844   if ( s < 0 ) { sign = -sign; s = -s; }
24845   if ( m < 0 ) { sign = -sign; m = -m; }
24846   if ( m == 0 )
24847     mp_confusion(mp, "arithmetic: divided by zero");
24848   else if ( m >= (max_integer / 10) )
24849     mp_confusion(mp, "arithmetic: number too big");
24850   q = s / m;
24851   r = s % m;
24852   for (i = 1;i<=dd;i++) {
24853     q = 10*q + (10*r) / m;
24854     r = (10*r) % m;
24855   }
24856   if ( 2*r >= m ) { incr(q); r = r - m; }
24857   mp->scaled_out = sign*(s - (r / mp->ten_pow[dd]));
24858   return (sign*q);
24859 }
24860
24861 @* \[44] Shipping pictures out.
24862 The |ship_out| procedure, to be described below, is given a pointer to
24863 an edge structure. Its mission is to output a file containing the \ps\
24864 description of an edge structure.
24865
24866 @ Each time an edge structure is shipped out we write a new \ps\ output
24867 file named according to the current \&{charcode}.
24868 @:char_code_}{\&{charcode} primitive@>
24869
24870 @<Declare the \ps\ output procedures@>=
24871 void mp_open_output_file (MP mp) ;
24872
24873 @ @c void mp_open_output_file (MP mp) {
24874   integer c; /* \&{charcode} rounded to the nearest integer */
24875   int old_setting; /* previous |selector| setting */
24876   pool_pointer i; /*  indexes into |filename_template|  */
24877   integer cc; /* a temporary integer for template building  */
24878   integer f,g=0; /* field widths */
24879   if ( mp->job_name==NULL ) mp_open_log_file(mp);
24880   c=mp_round_unscaled(mp, mp->internal[mp_char_code]);
24881   if ( mp->filename_template==0 ) {
24882     char *s; /* a file extension derived from |c| */
24883     if ( c<0 ) 
24884       s=xstrdup(".ps");
24885     else 
24886       @<Use |c| to compute the file extension |s|@>;
24887     mp_pack_job_name(mp, s);
24888     xfree(s);
24889     while ( ! mp_a_open_out(mp, &mp->ps_file, mp_filetype_postscript) )
24890       mp_prompt_file_name(mp, "file name for output",s);
24891   } else { /* initializations */
24892     str_number s, n; /* a file extension derived from |c| */
24893     old_setting=mp->selector; 
24894     mp->selector=new_string;
24895     f = 0;
24896     i = mp->str_start[mp->filename_template];
24897     n = rts(""); /* initialize */
24898     while ( i<str_stop(mp->filename_template) ) {
24899        if ( mp->str_pool[i]=='%' ) {
24900       CONTINUE:
24901         incr(i);
24902         if ( i<str_stop(mp->filename_template) ) {
24903           if ( mp->str_pool[i]=='j' ) {
24904             mp_print(mp, mp->job_name);
24905           } else if ( mp->str_pool[i]=='d' ) {
24906              cc= mp_round_unscaled(mp, mp->internal[mp_day]);
24907              print_with_leading_zeroes(cc);
24908           } else if ( mp->str_pool[i]=='m' ) {
24909              cc= mp_round_unscaled(mp, mp->internal[mp_month]);
24910              print_with_leading_zeroes(cc);
24911           } else if ( mp->str_pool[i]=='y' ) {
24912              cc= mp_round_unscaled(mp, mp->internal[mp_year]);
24913              print_with_leading_zeroes(cc);
24914           } else if ( mp->str_pool[i]=='H' ) {
24915              cc= mp_round_unscaled(mp, mp->internal[mp_time]) / 60;
24916              print_with_leading_zeroes(cc);
24917           }  else if ( mp->str_pool[i]=='M' ) {
24918              cc= mp_round_unscaled(mp, mp->internal[mp_time]) % 60;
24919              print_with_leading_zeroes(cc);
24920           } else if ( mp->str_pool[i]=='c' ) {
24921             if ( c<0 ) mp_print(mp, "ps");
24922             else print_with_leading_zeroes(c);
24923           } else if ( (mp->str_pool[i]>='0') && 
24924                       (mp->str_pool[i]<='9') ) {
24925             if ( (f<10)  )
24926               f = (f*10) + mp->str_pool[i]-'0';
24927             goto CONTINUE;
24928           } else {
24929             mp_print_str(mp, mp->str_pool[i]);
24930           }
24931         }
24932       } else {
24933         if ( mp->str_pool[i]=='.' )
24934           if (length(n)==0)
24935             n = mp_make_string(mp);
24936         mp_print_str(mp, mp->str_pool[i]);
24937       };
24938       incr(i);
24939     };
24940     s = mp_make_string(mp);
24941     mp->selector= old_setting;
24942     if (length(n)==0) {
24943        n=s;
24944        s=rts("");
24945     };
24946     mp_pack_file_name(mp, str(n),"",str(s));
24947     while ( ! mp_a_open_out(mp, &mp->ps_file, mp_filetype_postscript) )
24948       mp_prompt_file_name(mp, "file name for output",str(s));
24949     delete_str_ref(n);
24950     delete_str_ref(s);
24951   }
24952   @<Store the true output file name if appropriate@>;
24953   @<Begin the progress report for the output of picture~|c|@>;
24954 }
24955
24956 @ The file extension created here could be up to five characters long in
24957 extreme cases so it may have to be shortened on some systems.
24958 @^system dependencies@>
24959
24960 @<Use |c| to compute the file extension |s|@>=
24961
24962   s = xmalloc(7,1);
24963   snprintf(s,7,".%i",(int)c);
24964 }
24965
24966 @ The user won't want to see all the output file names so we only save the
24967 first and last ones and a count of how many there were.  For this purpose
24968 files are ordered primarily by \&{charcode} and secondarily by order of
24969 creation.
24970 @:char_code_}{\&{charcode} primitive@>
24971
24972 @<Store the true output file name if appropriate@>=
24973 if ((c<mp->first_output_code)&&(mp->first_output_code>=0)) {
24974   mp->first_output_code=c;
24975   xfree(mp->first_file_name);
24976   mp->first_file_name=xstrdup(mp->name_of_file);
24977 }
24978 if ( c>=mp->last_output_code ) {
24979   mp->last_output_code=c;
24980   xfree(mp->last_file_name);
24981   mp->last_file_name=xstrdup(mp->name_of_file);
24982 }
24983
24984 @ @<Glob...@>=
24985 char * first_file_name;
24986 char * last_file_name; /* full file names */
24987 integer first_output_code;integer last_output_code; /* rounded \&{charcode} values */
24988 @:char_code_}{\&{charcode} primitive@>
24989 integer total_shipped; /* total number of |ship_out| operations completed */
24990
24991 @ @<Set init...@>=
24992 mp->first_file_name=xstrdup("");
24993 mp->last_file_name=xstrdup("");
24994 mp->first_output_code=32768;
24995 mp->last_output_code=-32768;
24996 mp->total_shipped=0;
24997
24998 @ @<Dealloc variables@>=
24999 xfree(mp->first_file_name);
25000 xfree(mp->last_file_name);
25001
25002 @ @<Begin the progress report for the output of picture~|c|@>=
25003 if ( (int)mp->term_offset>mp->max_print_line-6 ) mp_print_ln(mp);
25004 else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
25005 mp_print_char(mp, '[');
25006 if ( c>=0 ) mp_print_int(mp, c)
25007
25008 @ @<End progress report@>=
25009 mp_print_char(mp, ']');
25010 update_terminal;
25011 incr(mp->total_shipped)
25012
25013 @ @<Explain what output files were written@>=
25014 if ( mp->total_shipped>0 ) { 
25015   mp_print_nl(mp, "");
25016   mp_print_int(mp, mp->total_shipped);
25017   mp_print(mp, " output file");
25018   if ( mp->total_shipped>1 ) mp_print_char(mp, 's');
25019   mp_print(mp, " written: ");
25020   mp_print(mp, mp->first_file_name);
25021   if ( mp->total_shipped>1 ) {
25022     if ( 31+strlen(mp->first_file_name)+
25023          strlen(mp->last_file_name)> (unsigned)mp->max_print_line) 
25024       mp_print_ln(mp);
25025     mp_print(mp, " .. ");
25026     mp_print(mp, mp->last_file_name);
25027   }
25028 }
25029
25030 @ A text node may specify an arbitrary transformation but the usual case
25031 involves only shifting, scaling, and occasionally rotation.  The purpose
25032 of |choose_scale| is to select a scale factor so that the remaining
25033 transformation is as ``nice'' as possible.  The definition of ``nice''
25034 is somewhat arbitrary but shifting and $90^\circ$ rotation are especially
25035 nice because they work out well for bitmap fonts.  The code here selects
25036 a scale factor equal to $1/\sqrt2$ times the Frobenius norm of the
25037 non-shifting part of the transformation matrix.  It is careful to avoid
25038 additions that might cause undetected overflow.
25039
25040 @<Declare the \ps\ output procedures@>=
25041 scaled mp_choose_scale (MP mp,pointer p) ;
25042
25043 @ @c scaled mp_choose_scale (MP mp,pointer p) {
25044   /* |p| should point to a text node */
25045   scaled a,b,c,d,ad,bc; /* temporary values */
25046   a=txx_val(p);
25047   b=txy_val(p);
25048   c=tyx_val(p);
25049   d=tyy_val(p);
25050   if ( (a<0) ) negate(a);
25051   if ( (b<0) ) negate(b);
25052   if ( (c<0) ) negate(c);
25053   if ( (d<0) ) negate(d);
25054   ad=half(a-d);
25055   bc=half(b-c);
25056   return mp_pyth_add(mp, mp_pyth_add(mp, d+ad,ad), mp_pyth_add(mp, c+bc,bc));
25057 }
25058
25059 @ There may be many sizes of one font and we need to keep track of the
25060 characters used for each size.  This is done by keeping a linked list of
25061 sizes for each font with a counter in each text node giving the appropriate
25062 position in the size list for its font.
25063
25064 @d sc_factor(A) mp->mem[(A)+1].sc /* the scale factor stored in a font size node */
25065 @d font_size_size 2 /* size of a font size node */
25066
25067 @ @<Internal library declarations@>=
25068 boolean mp_has_font_size(MP mp, font_number f );
25069
25070 @ @c 
25071 boolean mp_has_font_size(MP mp, font_number f ) {
25072   return (mp->font_sizes[f]!=null);
25073 }
25074
25075
25076 @ The potential overflow here is caused by the fact the returned value
25077 has to fit in a |name_type|, which is a quarterword. 
25078
25079 @d fscale_tolerance 65 /* that's $.001\times2^{16}$ */
25080
25081 @<Declare the \ps\ output procedures@>=
25082 quarterword mp_size_index (MP mp, font_number f, scaled s) {
25083   pointer p,q; /* the previous and current font size nodes */
25084   quarterword i; /* the size index for |q| */
25085   q=mp->font_sizes[f];
25086   i=0;
25087   while ( q!=null ) {
25088     if ( abs(s-sc_factor(q))<=fscale_tolerance ) 
25089       return i;
25090     else 
25091       { p=q; q=link(q); incr(i); };
25092     if ( i==max_quarterword )
25093       mp_overflow(mp, "sizes per font",max_quarterword);
25094 @:MetaPost capacity exceeded sizes per font}{\quad sizes per font@>
25095   }
25096   q=mp_get_node(mp, font_size_size);
25097   sc_factor(q)=s;
25098   if ( i==0 ) mp->font_sizes[f]=q;  else link(p)=q;
25099   return i;
25100 }
25101
25102 @ @<Internal library ...@>=
25103 scaled mp_indexed_size (MP mp,font_number f, quarterword j);
25104
25105 @ @c
25106 scaled mp_indexed_size (MP mp,font_number f, quarterword j) {
25107   pointer p; /* a font size node */
25108   quarterword i; /* the size index for |p| */
25109   p=mp->font_sizes[f];
25110   i=0;
25111   if ( p==null ) mp_confusion(mp, "size");
25112   while ( (i!=j) ) { 
25113     incr(i); p=link(p);
25114     if ( p==null ) mp_confusion(mp, "size");
25115   }
25116   return sc_factor(p);
25117 }
25118
25119 @ @<Declare the \ps\ output procedures@>=
25120 void mp_clear_sizes (MP mp) ;
25121
25122 @ @c void mp_clear_sizes (MP mp) {
25123   font_number f;  /* the font whose size list is being cleared */
25124   pointer p;  /* current font size nodes */
25125   for (f=null_font+1;f<=mp->last_fnum;f++) {
25126     while ( mp->font_sizes[f]!=null ) {
25127       p=mp->font_sizes[f];
25128       mp->font_sizes[f]=link(p);
25129       mp_free_node(mp, p,font_size_size);
25130     }
25131   }
25132 }
25133
25134 @ The \&{special} command saves up lines of text to be printed during the next
25135 |ship_out| operation.  The saved items are stored as a list of capsule tokens.
25136
25137 @<Glob...@>=
25138 pointer last_pending; /* the last token in a list of pending specials */
25139
25140 @ @<Set init...@>=
25141 mp->last_pending=spec_head;
25142
25143 @ @<Cases of |do_statement|...@>=
25144 case special_command: 
25145   if ( mp->cur_mod==0 ) mp_do_special(mp); else 
25146   if ( mp->cur_mod==1 ) mp_do_mapfile(mp); else 
25147   mp_do_mapline(mp);
25148   break;
25149
25150 @ @<Declare action procedures for use by |do_statement|@>=
25151 void mp_do_special (MP mp) ;
25152
25153 @ @c void mp_do_special (MP mp) { 
25154   mp_get_x_next(mp); mp_scan_expression(mp);
25155   if ( mp->cur_type!=mp_string_type ) {
25156     @<Complain about improper special operation@>;
25157   } else { 
25158     link(mp->last_pending)=mp_stash_cur_exp(mp);
25159     mp->last_pending=link(mp->last_pending);
25160     link(mp->last_pending)=null;
25161   }
25162 }
25163
25164 @ @<Complain about improper special operation@>=
25165
25166   exp_err("Unsuitable expression");
25167   help1("Only known strings are allowed for output as specials.");
25168   mp_put_get_error(mp);
25169 }
25170
25171 @ On the export side, we need an extra object type for special strings.
25172
25173 @<Graphical object codes@>=
25174 mp_special_code=8, 
25175
25176 @ @<Export pending specials@>=
25177 p=link(spec_head);
25178 while ( p!=null ) {
25179   hq = mp_new_graphic_object(mp,mp_special_code);
25180   gr_pre_script(hq)  = str(value(p));
25181   if (hh->body==NULL) hh->body=hq; else gr_link(hp) = hq;
25182   hp = hq;
25183   p=link(p);
25184 }
25185 mp_flush_token_list(mp, link(spec_head));
25186 link(spec_head)=null;
25187 mp->last_pending=spec_head
25188
25189 @ We are now ready for the main output procedure.  Note that the |selector|
25190 setting is saved in a global variable so that |begin_diagnostic| can access it.
25191
25192 @<Declare the \ps\ output procedures@>=
25193 void mp_ship_out (MP mp, pointer h) ;
25194
25195
25196 @d gr_type(A)         (A)->_type_field
25197 @d gr_link(A)         (A)->_link_field
25198 @d gr_name_type(A)    (A)->name_type_field
25199 @d gr_path_p(A)       (A)->path_p_field 
25200 @d gr_htap_p(A)       (A)->htap_p_field 
25201 @d gr_pen_p(A)        (A)->pen_p_field 
25202 @d gr_ljoin_val(A)    (A)->ljoin_field
25203 @d gr_lcap_val(A)     (A)->lcap_field
25204 @d gr_dash_scale(A)   (A)->dash_scale_field
25205 @d gr_miterlim_val(A) (A)->miterlim_field
25206 @d gr_pre_script(A)   (A)->pre_script_field
25207 @d gr_post_script(A)  (A)->post_script_field
25208 @d gr_dash_p(A)       (A)->dash_p_field
25209 @d gr_text_p(A)       (A)->text_p_field 
25210 @d gr_font_n(A)       (A)->font_n_field 
25211 @d gr_width_val(A)    (A)->width_field
25212 @d gr_height_val(A)   (A)->height_field
25213 @d gr_depth_val(A)    (A)->depth_field
25214 @d gr_tx_val(A)       (A)->tx_field
25215 @d gr_ty_val(A)       (A)->ty_field
25216 @d gr_txx_val(A)      (A)->txx_field
25217 @d gr_txy_val(A)      (A)->txy_field
25218 @d gr_tyx_val(A)      (A)->tyx_field
25219 @d gr_tyy_val(A)      (A)->tyy_field
25220
25221 @c
25222 void mp_ship_out (MP mp, pointer h) { /* output edge structure |h| */
25223   pointer p; /* the current graphical object */
25224   integer t; /* a temporary value */
25225   font_number f; /* fonts used in a text node or as loop counters */
25226   struct mp_edge_object *hh; /* the first graphical object */
25227   struct mp_graphic_object *hp; /* the current graphical object */
25228   struct mp_graphic_object *hq; /* something |hp| points to  */
25229   int prologues = mp->internal[mp_prologues];
25230   mp_open_output_file(mp);
25231   mp->non_ps_setting=mp->selector;
25232   mp->selector=ps_file_only;
25233   mp_set_bbox(mp, h, true);
25234   mp_print_initial_comment(mp, minx_val(h),miny_val(h),maxx_val(h),maxy_val(h));
25235   @<Unmark all marked characters@>;
25236   mp_reload_encodings(mp);
25237   @<Scan all the text nodes and mark the used characters@>;
25238   if ( prologues==two || prologues==three ) {
25239     mp_print_improved_prologue(mp, h);
25240   } else {
25241     mp_print_prologue(mp, h);
25242   }
25243   hh = mp_xmalloc(mp,1,sizeof(struct mp_edge_object));
25244   hh->body = NULL;
25245   @<Export pending specials@>;
25246   p=link(dummy_loc(h));
25247   while ( p!=null ) { 
25248     hq = mp_new_graphic_object(mp,type(p));
25249     switch (type(p)) {
25250     case mp_fill_code:
25251       gr_pen_p(hq)        = mp_export_knot_list(mp,pen_p(p));
25252       if ((pen_p(p)==null) || pen_is_elliptical(pen_p(p)))  {
25253           gr_path_p(hq)       = mp_export_knot_list(mp,path_p(p));
25254       } else {
25255         pointer pc, pp;
25256         pc = mp_copy_path(mp, path_p(p));
25257         pp = mp_make_envelope(mp, pc, pen_p(p),ljoin_val(p),0,miterlim_val(p));
25258         gr_path_p(hq)       = mp_export_knot_list(mp,pp);
25259         mp_toss_knot_list(mp, pp);
25260         pc = mp_htap_ypoc(mp, path_p(p));
25261         pp = mp_make_envelope(mp, pc, pen_p(p),ljoin_val(p),0,miterlim_val(p));
25262         gr_htap_p(hq)       = mp_export_knot_list(mp,pp);
25263         mp_toss_knot_list(mp, pp);
25264       }
25265       @<Export object color@>;
25266       @<Export object scripts@>;
25267       gr_ljoin_val(hq)    = ljoin_val(p);
25268       gr_miterlim_val(hq) = miterlim_val(p);
25269       break;
25270     case mp_stroked_code:
25271       gr_pen_p(hq)        = mp_export_knot_list(mp,pen_p(p));
25272       if (pen_is_elliptical(pen_p(p)))  {
25273               gr_path_p(hq)       = mp_export_knot_list(mp,path_p(p));
25274       } else {
25275         pointer pc;
25276         pc=mp_copy_path(mp, path_p(p));
25277         t=lcap_val(p);
25278         if ( left_type(pc)!=mp_endpoint ) { 
25279           left_type(mp_insert_knot(mp, pc,x_coord(pc),y_coord(pc)))=mp_endpoint;
25280           right_type(pc)=mp_endpoint;
25281           pc=link(pc);
25282           t=1;
25283         }
25284         pc=mp_make_envelope(mp,pc,pen_p(p),ljoin_val(p),t,miterlim_val(p));
25285         gr_path_p(hq)       = mp_export_knot_list(mp,pc);
25286         mp_toss_knot_list(mp, pc);
25287       }
25288       @<Export object color@>;
25289       @<Export object scripts@>;
25290       gr_ljoin_val(hq)    = ljoin_val(p);
25291       gr_miterlim_val(hq) = miterlim_val(p);
25292       gr_lcap_val(hq)     = lcap_val(p);
25293       gr_dash_scale(hq)   = dash_scale(p);
25294       gr_dash_p(hq)       = mp_export_dashes(mp,dash_p(p));
25295       break;
25296     case mp_text_code:
25297       gr_text_p(hq)       = str(text_p(p));
25298       gr_font_n(hq)       = font_n(p);
25299       @<Export object color@>;
25300       @<Export object scripts@>;
25301       gr_width_val(hq)    = width_val(p);
25302       gr_height_val(hq)   = height_val(p);
25303       gr_depth_val(hq)    = depth_val(p);
25304       gr_tx_val(hq)       = tx_val(p);
25305       gr_ty_val(hq)       = ty_val(p);
25306       gr_txx_val(hq)      = txx_val(p);
25307       gr_txy_val(hq)      = txy_val(p);
25308       gr_tyx_val(hq)      = tyx_val(p);
25309       gr_tyy_val(hq)      = tyy_val(p);
25310       break;
25311     case mp_start_clip_code: 
25312     case mp_start_bounds_code:
25313       gr_path_p(hq) = mp_export_knot_list(mp,path_p(p));
25314       break;
25315     case mp_stop_clip_code: 
25316     case mp_stop_bounds_code:
25317       /* nothing to do here */
25318       break;
25319     } 
25320     if (hh->body==NULL) hh->body=hq; else  gr_link(hp) = hq;
25321     hp = hq;
25322     p=link(p);
25323   }
25324   mp_gr_ship_out (mp, hh->body);
25325   mp_xfree(hh);
25326   fclose(mp->ps_file);
25327   mp->selector=mp->non_ps_setting;
25328   if ( mp->internal[mp_prologues]<=0 ) mp_clear_sizes(mp);
25329   @<End progress report@>;
25330   if ( mp->internal[mp_tracing_output]>0 ) 
25331    mp_print_edges(mp, h," (just shipped out)",true);
25332 }
25333
25334
25335 @d gr_color_model(A)  (A)->color_model_field
25336 @d gr_red_val(A)      (A)->color_field.rgb._red_val
25337 @d gr_green_val(A)    (A)->color_field.rgb._green_val
25338 @d gr_blue_val(A)     (A)->color_field.rgb._blue_val
25339 @d gr_cyan_val(A)     (A)->color_field.cmyk._cyan_val
25340 @d gr_magenta_val(A)  (A)->color_field.cmyk._magenta_val
25341 @d gr_yellow_val(A)   (A)->color_field.cmyk._yellow_val
25342 @d gr_black_val(A)    (A)->color_field.cmyk._black_val
25343 @d gr_grey_val(A)     (A)->color_field.grey._grey_val
25344
25345 @<Export object color@>=
25346 gr_color_model(hq)  = color_model(p);
25347 gr_cyan_val(hq)     = cyan_val(p);
25348 gr_magenta_val(hq)  = magenta_val(p);
25349 gr_yellow_val(hq)   = yellow_val(p);
25350 gr_black_val(hq)    = black_val(p);
25351 gr_red_val(hq)      = red_val(p);
25352 gr_green_val(hq)    = green_val(p);
25353 gr_blue_val(hq)     = blue_val(p);
25354 gr_grey_val(hq)     = grey_val(p)
25355
25356
25357 @ @<Export object scripts@>=
25358 if (pre_script(p)!=null)
25359   gr_pre_script(hq)   = str(pre_script(p));
25360 if (post_script(p)!=null)
25361   gr_post_script(hq)  = str(post_script(p));
25362
25363 @ @<Internal library declarations@>=
25364 void mp_apply_mark_string_chars(MP mp, pointer h, int next_size);
25365
25366 @ @c
25367 void mp_apply_mark_string_chars(MP mp, pointer h, int next_size) {
25368   pointer p;
25369   p=link(dummy_loc(h));
25370   while ( p!=null ) {
25371     if ( type(p)==mp_text_code ) {
25372       if ( font_n(p)!=null_font ) { 
25373         if ( name_type(p)==next_size )
25374           mp_mark_string_chars(mp, font_n(p),text_p(p));
25375       }
25376     }
25377     p=link(p);
25378   }
25379 }
25380
25381 @ @<Unmark all marked characters@>=
25382 for (f=null_font+1;f<=mp->last_fnum;f++) {
25383   if ( mp->font_sizes[f]!=null ) {
25384     mp_unmark_font(mp, f);
25385     mp->font_sizes[f]=null;
25386   }
25387 }
25388
25389 @ @<Scan all the text nodes and mark the used ...@>=
25390 p=link(dummy_loc(h));
25391 while ( p!=null ) {
25392   if ( type(p)==mp_text_code ) {
25393     f = font_n(p);
25394     if (f!=null_font ) {
25395       switch (prologues) {
25396       case two:
25397       case three:
25398         mp->font_sizes[f] = mp_void;
25399         mp_mark_string_chars(mp, f,text_p(p));
25400             if (mp_has_fm_entry(mp,f,NULL) ) {
25401           if (mp->font_enc_name[f]==NULL )
25402             mp->font_enc_name[f] = mp_fm_encoding_name(mp,f);
25403           mp->font_ps_name[f] = mp_fm_font_name(mp,f);
25404         }
25405         break;
25406       case unity:
25407         mp->font_sizes[f]=mp_void;
25408         break;
25409       default: 
25410         name_type(p)=mp_size_index(mp, f,mp_choose_scale(mp, p));
25411         if ( name_type(p)==0 )
25412           mp_mark_string_chars(mp, f,text_p(p));
25413       }
25414     }
25415   }
25416   p=link(p);
25417 }
25418
25419 @ Now that we've finished |ship_out|, let's look at the other commands
25420 by which a user can send things to the \.{GF} file.
25421
25422 @ @<Determine if a character has been shipped out@>=
25423
25424   mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256;
25425   if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
25426   boolean_reset(mp->char_exists[mp->cur_exp]);
25427   mp->cur_type=mp_boolean_type;
25428 }
25429
25430 @ @<Glob...@>=
25431 psout_data ps;
25432
25433 @ @<Allocate or initialize ...@>=
25434 mp_backend_initialize(mp);
25435
25436 @ @<Dealloc...@>=
25437 mp_backend_free(mp);
25438
25439
25440 @* \[45] Dumping and undumping the tables.
25441 After \.{INIMP} has seen a collection of macros, it
25442 can write all the necessary information on an auxiliary file so
25443 that production versions of \MP\ are able to initialize their
25444 memory at high speed. The present section of the program takes
25445 care of such output and input. We shall consider simultaneously
25446 the processes of storing and restoring,
25447 so that the inverse relation between them is clear.
25448 @.INIMP@>
25449
25450 The global variable |mem_ident| is a string that is printed right
25451 after the |banner| line when \MP\ is ready to start. For \.{INIMP} this
25452 string says simply `\.{(INIMP)}'; for other versions of \MP\ it says,
25453 for example, `\.{(mem=plain 90.4.14)}', showing the year,
25454 month, and day that the mem file was created. We have |mem_ident=0|
25455 before \MP's tables are loaded.
25456
25457 @<Glob...@>=
25458 char * mem_ident;
25459
25460 @ @<Set init...@>=
25461 mp->mem_ident=NULL;
25462
25463 @ @<Initialize table entries...@>=
25464 mp->mem_ident=xstrdup(" (INIMP)");
25465
25466 @ @<Declare act...@>=
25467 void mp_store_mem_file (MP mp) ;
25468
25469 @ @c void mp_store_mem_file (MP mp) {
25470   integer k;  /* all-purpose index */
25471   pointer p,q; /* all-purpose pointers */
25472   integer x; /* something to dump */
25473   four_quarters w; /* four ASCII codes */
25474   memory_word WW;
25475   @<Create the |mem_ident|, open the mem file,
25476     and inform the user that dumping has begun@>;
25477   @<Dump constants for consistency check@>;
25478   @<Dump the string pool@>;
25479   @<Dump the dynamic memory@>;
25480   @<Dump the table of equivalents and the hash table@>;
25481   @<Dump a few more things and the closing check word@>;
25482   @<Close the mem file@>;
25483 }
25484
25485 @ Corresponding to the procedure that dumps a mem file, we also have a function
25486 that reads~one~in. The function returns |false| if the dumped mem is
25487 incompatible with the present \MP\ table sizes, etc.
25488
25489 @d off_base 6666 /* go here if the mem file is unacceptable */
25490 @d too_small(A) { wake_up_terminal;
25491   wterm_ln("---! Must increase the "); wterm((A));
25492 @.Must increase the x@>
25493   goto OFF_BASE;
25494   }
25495
25496 @c 
25497 boolean mp_load_mem_file (MP mp) {
25498   integer k; /* all-purpose index */
25499   pointer p,q; /* all-purpose pointers */
25500   integer x; /* something undumped */
25501   str_number s; /* some temporary string */
25502   four_quarters w; /* four ASCII codes */
25503   memory_word WW;
25504   @<Undump constants for consistency check@>;
25505   @<Undump the string pool@>;
25506   @<Undump the dynamic memory@>;
25507   @<Undump the table of equivalents and the hash table@>;
25508   @<Undump a few more things and the closing check word@>;
25509   return true; /* it worked! */
25510 OFF_BASE: 
25511   wake_up_terminal;
25512   wterm_ln("(Fatal mem file error; I'm stymied)\n");
25513 @.Fatal mem file error@>
25514    return false;
25515 }
25516
25517 @ @<Declarations@>=
25518 boolean mp_load_mem_file (MP mp) ;
25519
25520 @ Mem files consist of |memory_word| items, and we use the following
25521 macros to dump words of different types:
25522
25523 @d dump_wd(A)   { WW=(A);       fwrite(&WW,sizeof(WW),1,mp->mem_file); }
25524 @d dump_int(A)  { int cint=(A); fwrite(&cint,sizeof(cint),1,mp->mem_file); }
25525 @d dump_hh(A)   { WW.hh=(A);    fwrite(&WW,sizeof(WW),1,mp->mem_file); }
25526 @d dump_qqqq(A) { WW.qqqq=(A);  fwrite(&WW,sizeof(WW),1,mp->mem_file); }
25527 @d dump_string(A) { dump_int(strlen(A)+1);
25528                     fwrite(A,strlen(A)+1,1,mp->mem_file); }
25529
25530 @<Glob...@>=
25531 FILE * mem_file; /* for input or output of mem information */
25532
25533 @ The inverse macros are slightly more complicated, since we need to check
25534 the range of the values we are reading in. We say `|undump(a)(b)(x)|' to
25535 read an integer value |x| that is supposed to be in the range |a<=x<=b|.
25536
25537 @d undump_wd(A)   { fread(&WW,sizeof(WW),1,mp->mem_file); A=WW; }
25538 @d undump_int(A)  { int cint; fread(&cint,sizeof(cint),1,mp->mem_file); A=cint; }
25539 @d undump_hh(A)   { fread(&WW,sizeof(WW),1,mp->mem_file); A=WW.hh; }
25540 @d undump_qqqq(A) { fread(&WW,sizeof(WW),1,mp->mem_file); A=WW.qqqq; }
25541 @d undump_strings(A,B,C) { 
25542    undump_int(x); if ( (x<(A)) || (x>(B)) ) goto OFF_BASE; else C=str(x); }
25543 @d undump(A,B,C) { undump_int(x); if ( (x<(A)) || (x>(int)(B)) ) goto OFF_BASE; else C=x; }
25544 @d undump_size(A,B,C,D) { undump_int(x);
25545                           if (x<(A)) goto OFF_BASE; 
25546                           if (x>(B)) { too_small((C)); } else { D=x;} }
25547 @d undump_string(A) { integer XX=0; undump_int(XX);
25548                       A = xmalloc(XX,sizeof(char));
25549                       fread(A,XX,1,mp->mem_file); }
25550
25551 @ The next few sections of the program should make it clear how we use the
25552 dump/undump macros.
25553
25554 @<Dump constants for consistency check@>=
25555 dump_int(mp->mem_top);
25556 dump_int(mp->hash_size);
25557 dump_int(mp->hash_prime)
25558 dump_int(mp->param_size);
25559 dump_int(mp->max_in_open);
25560
25561 @ Sections of a \.{WEB} program that are ``commented out'' still contribute
25562 strings to the string pool; therefore \.{INIMP} and \MP\ will have
25563 the same strings. (And it is, of course, a good thing that they do.)
25564 @.WEB@>
25565 @^string pool@>
25566
25567 @<Undump constants for consistency check@>=
25568 undump_int(x); mp->mem_top = x;
25569 undump_int(x); if (mp->hash_size != x) goto OFF_BASE;
25570 undump_int(x); if (mp->hash_prime != x) goto OFF_BASE;
25571 undump_int(x); if (mp->param_size != x) goto OFF_BASE;
25572 undump_int(x); if (mp->max_in_open != x) goto OFF_BASE
25573
25574 @ We do string pool compaction to avoid dumping unused strings.
25575
25576 @d dump_four_ASCII 
25577   w.b0=qi(mp->str_pool[k]); w.b1=qi(mp->str_pool[k+1]);
25578   w.b2=qi(mp->str_pool[k+2]); w.b3=qi(mp->str_pool[k+3]);
25579   dump_qqqq(w)
25580
25581 @<Dump the string pool@>=
25582 mp_do_compaction(mp, mp->pool_size);
25583 dump_int(mp->pool_ptr);
25584 dump_int(mp->max_str_ptr);
25585 dump_int(mp->str_ptr);
25586 k=0;
25587 while ( (mp->next_str[k]==k+1) && (k<=mp->max_str_ptr) ) 
25588   incr(k);
25589 dump_int(k);
25590 while ( k<=mp->max_str_ptr ) { 
25591   dump_int(mp->next_str[k]); incr(k);
25592 }
25593 k=0;
25594 while (1)  { 
25595   dump_int(mp->str_start[k]); /* TODO: valgrind warning here */
25596   if ( k==mp->str_ptr ) {
25597     break;
25598   } else { 
25599     k=mp->next_str[k]; 
25600   }
25601 };
25602 k=0;
25603 while (k+4<mp->pool_ptr ) { 
25604   dump_four_ASCII; k=k+4; 
25605 }
25606 k=mp->pool_ptr-4; dump_four_ASCII;
25607 mp_print_ln(mp); mp_print(mp, "at most "); mp_print_int(mp, mp->max_str_ptr);
25608 mp_print(mp, " strings of total length ");
25609 mp_print_int(mp, mp->pool_ptr)
25610
25611 @ @d undump_four_ASCII 
25612   undump_qqqq(w);
25613   mp->str_pool[k]=qo(w.b0); mp->str_pool[k+1]=qo(w.b1);
25614   mp->str_pool[k+2]=qo(w.b2); mp->str_pool[k+3]=qo(w.b3)
25615
25616 @<Undump the string pool@>=
25617 undump_int(mp->pool_ptr);
25618 mp_reallocate_pool(mp, mp->pool_ptr) ;
25619 undump_int(mp->max_str_ptr);
25620 mp_reallocate_strings (mp,mp->max_str_ptr) ;
25621 undump(0,mp->max_str_ptr,mp->str_ptr);
25622 undump(0,mp->max_str_ptr+1,s);
25623 for (k=0;k<=s-1;k++) 
25624   mp->next_str[k]=k+1;
25625 for (k=s;k<=mp->max_str_ptr;k++) 
25626   undump(s+1,mp->max_str_ptr+1,mp->next_str[k]);
25627 mp->fixed_str_use=0;
25628 k=0;
25629 while (1) { 
25630   undump(0,mp->pool_ptr,mp->str_start[k]);
25631   if ( k==mp->str_ptr ) break;
25632   mp->str_ref[k]=max_str_ref;
25633   incr(mp->fixed_str_use);
25634   mp->last_fixed_str=k; k=mp->next_str[k];
25635 }
25636 k=0;
25637 while ( k+4<mp->pool_ptr ) { 
25638   undump_four_ASCII; k=k+4;
25639 }
25640 k=mp->pool_ptr-4; undump_four_ASCII;
25641 mp->init_str_use=mp->fixed_str_use; mp->init_pool_ptr=mp->pool_ptr;
25642 mp->max_pool_ptr=mp->pool_ptr;
25643 mp->strs_used_up=mp->fixed_str_use;
25644 mp->pool_in_use=mp->str_start[mp->str_ptr]; mp->strs_in_use=mp->fixed_str_use;
25645 mp->max_pl_used=mp->pool_in_use; mp->max_strs_used=mp->strs_in_use;
25646 mp->pact_count=0; mp->pact_chars=0; mp->pact_strs=0;
25647
25648 @ By sorting the list of available spaces in the variable-size portion of
25649 |mem|, we are usually able to get by without having to dump very much
25650 of the dynamic memory.
25651
25652 We recompute |var_used| and |dyn_used|, so that \.{INIMP} dumps valid
25653 information even when it has not been gathering statistics.
25654
25655 @<Dump the dynamic memory@>=
25656 mp_sort_avail(mp); mp->var_used=0;
25657 dump_int(mp->lo_mem_max); dump_int(mp->rover);
25658 p=0; q=mp->rover; x=0;
25659 do {  
25660   for (k=p;k<= q+1;k++) 
25661     dump_wd(mp->mem[k]);
25662   x=x+q+2-p; mp->var_used=mp->var_used+q-p;
25663   p=q+node_size(q); q=rlink(q);
25664 } while (q!=mp->rover);
25665 mp->var_used=mp->var_used+mp->lo_mem_max-p; 
25666 mp->dyn_used=mp->mem_end+1-mp->hi_mem_min;
25667 for (k=p;k<= mp->lo_mem_max;k++ ) 
25668   dump_wd(mp->mem[k]);
25669 x=x+mp->lo_mem_max+1-p;
25670 dump_int(mp->hi_mem_min); dump_int(mp->avail);
25671 for (k=mp->hi_mem_min;k<=mp->mem_end;k++ ) 
25672   dump_wd(mp->mem[k]);
25673 x=x+mp->mem_end+1-mp->hi_mem_min;
25674 p=mp->avail;
25675 while ( p!=null ) { 
25676   decr(mp->dyn_used); p=link(p);
25677 }
25678 dump_int(mp->var_used); dump_int(mp->dyn_used);
25679 mp_print_ln(mp); mp_print_int(mp, x);
25680 mp_print(mp, " memory locations dumped; current usage is ");
25681 mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used)
25682
25683 @ @<Undump the dynamic memory@>=
25684 undump(lo_mem_stat_max+1000,hi_mem_stat_min-1,mp->lo_mem_max);
25685 undump(lo_mem_stat_max+1,mp->lo_mem_max,mp->rover);
25686 p=0; q=mp->rover;
25687 do {  
25688   for (k=p;k<= q+1; k++) 
25689     undump_wd(mp->mem[k]);
25690   p=q+node_size(q);
25691   if ( (p>mp->lo_mem_max)||((q>=rlink(q))&&(rlink(q)!=mp->rover)) ) 
25692     goto OFF_BASE;
25693   q=rlink(q);
25694 } while (q!=mp->rover);
25695 for (k=p;k<=mp->lo_mem_max;k++ ) 
25696   undump_wd(mp->mem[k]);
25697 undump(mp->lo_mem_max+1,hi_mem_stat_min,mp->hi_mem_min);
25698 undump(null,mp->mem_top,mp->avail); mp->mem_end=mp->mem_top;
25699 for (k=mp->hi_mem_min;k<= mp->mem_end;k++) 
25700   undump_wd(mp->mem[k]);
25701 undump_int(mp->var_used); undump_int(mp->dyn_used)
25702
25703 @ A different scheme is used to compress the hash table, since its lower region
25704 is usually sparse. When |text(p)<>0| for |p<=hash_used|, we output three
25705 words: |p|, |hash[p]|, and |eqtb[p]|. The hash table is, of course, densely
25706 packed for |p>=hash_used|, so the remaining entries are output in~a~block.
25707
25708 @<Dump the table of equivalents and the hash table@>=
25709 dump_int(mp->hash_used); 
25710 mp->st_count=frozen_inaccessible-1-mp->hash_used;
25711 for (p=1;p<=mp->hash_used;p++) {
25712   if ( text(p)!=0 ) {
25713      dump_int(p); dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]); incr(mp->st_count);
25714   }
25715 }
25716 for (p=mp->hash_used+1;p<=(int)hash_end;p++) {
25717   dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]);
25718 }
25719 dump_int(mp->st_count);
25720 mp_print_ln(mp); mp_print_int(mp, mp->st_count); mp_print(mp, " symbolic tokens")
25721
25722 @ @<Undump the table of equivalents and the hash table@>=
25723 undump(1,frozen_inaccessible,mp->hash_used); 
25724 p=0;
25725 do {  
25726   undump(p+1,mp->hash_used,p); 
25727   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
25728 } while (p!=mp->hash_used);
25729 for (p=mp->hash_used+1;p<=(int)hash_end;p++ )  { 
25730   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
25731 }
25732 undump_int(mp->st_count)
25733
25734 @ We have already printed a lot of statistics, so we set |mp_tracing_stats:=0|
25735 to prevent them appearing again.
25736
25737 @<Dump a few more things and the closing check word@>=
25738 dump_int(mp->max_internal);
25739 dump_int(mp->int_ptr);
25740 for (k=1;k<= mp->int_ptr;k++ ) { 
25741   dump_int(mp->internal[k]); 
25742   dump_string(mp->int_name[k]);
25743 }
25744 dump_int(mp->start_sym); 
25745 dump_int(mp->interaction); 
25746 dump_string(mp->mem_ident);
25747 dump_int(mp->bg_loc); dump_int(mp->eg_loc); dump_int(mp->serial_no); dump_int(69073);
25748 mp->internal[mp_tracing_stats]=0
25749
25750 @ @<Undump a few more things and the closing check word@>=
25751 undump_int(x);
25752 if (x>mp->max_internal) mp_grow_internals(mp,x);
25753 undump_int(mp->int_ptr);
25754 for (k=1;k<= mp->int_ptr;k++) { 
25755   undump_int(mp->internal[k]);
25756   undump_string(mp->int_name[k]);
25757 }
25758 undump(0,frozen_inaccessible,mp->start_sym);
25759 if (mp->interaction==mp_unspecified_mode) {
25760   undump(mp_unspecified_mode,mp_error_stop_mode,mp->interaction);
25761 } else {
25762   undump(mp_unspecified_mode,mp_error_stop_mode,x);
25763 }
25764 undump_string(mp->mem_ident);
25765 undump(1,hash_end,mp->bg_loc);
25766 undump(1,hash_end,mp->eg_loc);
25767 undump_int(mp->serial_no);
25768 undump_int(x); 
25769 if ( (x!=69073)|| feof(mp->mem_file) ) goto OFF_BASE
25770
25771 @ @<Create the |mem_ident|...@>=
25772
25773   xfree(mp->mem_ident);
25774   mp->mem_ident = xmalloc(256,1);
25775   snprintf(mp->mem_ident,256," (mem=%s %i.%i.%i)", 
25776            mp->job_name,
25777            (int)(mp_round_unscaled(mp, mp->internal[mp_year]) % 100),
25778            (int)mp_round_unscaled(mp, mp->internal[mp_month]),
25779            (int)mp_round_unscaled(mp, mp->internal[mp_day]));
25780   mp_pack_job_name(mp, mem_extension);
25781   while (! mp_w_open_out(mp, &mp->mem_file) )
25782     mp_prompt_file_name(mp, "mem file name", mem_extension);
25783   mp_print_nl(mp, "Beginning to dump on file ");
25784 @.Beginning to dump...@>
25785   mp_print(mp, mp->name_of_file); 
25786   mp_print_nl(mp, mp->mem_ident);
25787 }
25788
25789 @ @<Dealloc variables@>=
25790 xfree(mp->mem_ident);
25791
25792 @ @<Close the mem file@>=
25793 fclose(mp->mem_file)
25794
25795 @* \[46] The main program.
25796 This is it: the part of \MP\ that executes all those procedures we have
25797 written.
25798
25799 Well---almost. We haven't put the parsing subroutines into the
25800 program yet; and we'd better leave space for a few more routines that may
25801 have been forgotten.
25802
25803 @c @<Declare the basic parsing subroutines@>;
25804 @<Declare miscellaneous procedures that were declared |forward|@>;
25805 @<Last-minute procedures@>
25806
25807 @ We've noted that there are two versions of \MP. One, called \.{INIMP},
25808 @.INIMP@>
25809 has to be run first; it initializes everything from scratch, without
25810 reading a mem file, and it has the capability of dumping a mem file.
25811 The other one is called `\.{VIRMP}'; it is a ``virgin'' program that needs
25812 @.VIRMP@>
25813 to input a mem file in order to get started. \.{VIRMP} typically has
25814 a bit more memory capacity than \.{INIMP}, because it does not need the
25815 space consumed by the dumping/undumping routines and the numerous calls on
25816 |primitive|, etc.
25817
25818 The \.{VIRMP} program cannot read a mem file instantaneously, of course;
25819 the best implementations therefore allow for production versions of \MP\ that
25820 not only avoid the loading routine for \PASCAL\ object code, they also have
25821 a mem file pre-loaded. 
25822
25823 @<Glob...@>=
25824 boolean ini_version; /* are we iniMP? */
25825
25826 @ @<Option variables@>=
25827 int ini_version; /* are we iniMP? */
25828
25829 @ @<Set |ini_version|@>=
25830 mp->ini_version = (opt->ini_version ? true : false);
25831
25832 @ Here we do whatever is needed to complete \MP's job gracefully on the
25833 local operating system. The code here might come into play after a fatal
25834 error; it must therefore consist entirely of ``safe'' operations that
25835 cannot produce error messages. For example, it would be a mistake to call
25836 |str_room| or |make_string| at this time, because a call on |overflow|
25837 might lead to an infinite loop.
25838 @^system dependencies@>
25839
25840 This program doesn't bother to close the input files that may still be open.
25841
25842 @<Last-minute...@>=
25843 void mp_close_files_and_terminate (MP mp) {
25844   integer k; /* all-purpose index */
25845   integer LH; /* the length of the \.{TFM} header, in words */
25846   int lk_offset; /* extra words inserted at beginning of |lig_kern| array */
25847   pointer p; /* runs through a list of \.{TFM} dimensions */
25848   @<Close all open files in the |rd_file| and |wr_file| arrays@>;
25849   if ( mp->internal[mp_tracing_stats]>0 )
25850     @<Output statistics about this job@>;
25851   wake_up_terminal; 
25852   @<Do all the finishing work on the \.{TFM} file@>;
25853   @<Explain what output files were written@>;
25854   if ( mp->log_opened ){ 
25855     wlog_cr;
25856     fclose(mp->log_file); mp->selector=mp->selector-2;
25857     if ( mp->selector==term_only ) {
25858       mp_print_nl(mp, "Transcript written on ");
25859 @.Transcript written...@>
25860       mp_print(mp, mp->log_name); mp_print_char(mp, '.');
25861     }
25862   }
25863   mp_print_ln(mp);
25864 }
25865
25866 @ @<Declarations@>=
25867 void mp_close_files_and_terminate (MP mp) ;
25868
25869 @ @<Close all open files in the |rd_file| and |wr_file| arrays@>=
25870 if (mp->rd_fname!=NULL) {
25871   for (k=0;k<=(int)mp->read_files-1;k++ ) {
25872     if ( mp->rd_fname[k]!=NULL ) {
25873       fclose(mp->rd_file[k]);
25874    }
25875  }
25876 }
25877 if (mp->wr_fname!=NULL) {
25878   for (k=0;k<=(int)mp->write_files-1;k++) {
25879     if ( mp->wr_fname[k]!=NULL ) {
25880      fclose(mp->wr_file[k]);
25881     }
25882   }
25883 }
25884
25885 @ @<Dealloc ...@>=
25886 for (k=0;k<(int)mp->max_read_files;k++ ) {
25887   if ( mp->rd_fname[k]!=NULL ) {
25888     fclose(mp->rd_file[k]);
25889     mp_xfree(mp->rd_fname[k]); 
25890   }
25891 }
25892 mp_xfree(mp->rd_file);
25893 mp_xfree(mp->rd_fname);
25894 for (k=0;k<(int)mp->max_write_files;k++) {
25895   if ( mp->wr_fname[k]!=NULL ) {
25896     fclose(mp->wr_file[k]);
25897     mp_xfree(mp->wr_fname[k]); 
25898   }
25899 }
25900 mp_xfree(mp->wr_file);
25901 mp_xfree(mp->wr_fname);
25902
25903
25904 @ We want to produce a \.{TFM} file if and only if |mp_fontmaking| is positive.
25905
25906 We reclaim all of the variable-size memory at this point, so that
25907 there is no chance of another memory overflow after the memory capacity
25908 has already been exceeded.
25909
25910 @<Do all the finishing work on the \.{TFM} file@>=
25911 if ( mp->internal[mp_fontmaking]>0 ) {
25912   @<Make the dynamic memory into one big available node@>;
25913   @<Massage the \.{TFM} widths@>;
25914   mp_fix_design_size(mp); mp_fix_check_sum(mp);
25915   @<Massage the \.{TFM} heights, depths, and italic corrections@>;
25916   mp->internal[mp_fontmaking]=0; /* avoid loop in case of fatal error */
25917   @<Finish the \.{TFM} file@>;
25918 }
25919
25920 @ @<Make the dynamic memory into one big available node@>=
25921 mp->rover=lo_mem_stat_max+1; link(mp->rover)=empty_flag; mp->lo_mem_max=mp->hi_mem_min-1;
25922 if ( mp->lo_mem_max-mp->rover>max_halfword ) mp->lo_mem_max=max_halfword+mp->rover;
25923 node_size(mp->rover)=mp->lo_mem_max-mp->rover; 
25924 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
25925 link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null
25926
25927 @ The present section goes directly to the log file instead of using
25928 |print| commands, because there's no need for these strings to take
25929 up |str_pool| memory when a non-{\bf stat} version of \MP\ is being used.
25930
25931 @<Output statistics...@>=
25932 if ( mp->log_opened ) { 
25933   char s[128];
25934   wlog_ln(" ");
25935   wlog_ln("Here is how much of MetaPost's memory you used:");
25936 @.Here is how much...@>
25937   snprintf(s,128," %i string%s out of %i",(int)mp->max_strs_used-mp->init_str_use,
25938           (mp->max_strs_used!=mp->init_str_use+1 ? "s" : ""),
25939           (int)(mp->max_strings-1-mp->init_str_use));
25940   wlog_ln(s);
25941   snprintf(s,128," %i string characters out of %i",
25942            (int)mp->max_pl_used-mp->init_pool_ptr,
25943            (int)mp->pool_size-mp->init_pool_ptr);
25944   wlog_ln(s);
25945   snprintf(s,128," %i words of memory out of %i",
25946            (int)mp->lo_mem_max+mp->mem_end-mp->hi_mem_min+2,
25947            (int)mp->mem_end+1);
25948   wlog_ln(s);
25949   snprintf(s,128," %i symbolic tokens out of %i", (int)mp->st_count, (int)mp->hash_size);
25950   wlog_ln(s);
25951   snprintf(s,128," %ii, %in, %ip, %ib stack positions out of %ii, %in, %ip, %ib",
25952            (int)mp->max_in_stack,(int)mp->int_ptr,
25953            (int)mp->max_param_stack,(int)mp->max_buf_stack+1,
25954            (int)mp->stack_size,(int)mp->max_internal,(int)mp->param_size,(int)mp->buf_size);
25955   wlog_ln(s);
25956   snprintf(s,128," %i string compactions (moved %i characters, %i strings)",
25957           (int)mp->pact_count,(int)mp->pact_chars,(int)mp->pact_strs);
25958   wlog_ln(s);
25959 }
25960
25961 @ We get to the |final_cleanup| routine when \&{end} or \&{dump} has
25962 been scanned.
25963
25964 @<Last-minute...@>=
25965 void mp_final_cleanup (MP mp) {
25966   small_number c; /* 0 for \&{end}, 1 for \&{dump} */
25967   c=mp->cur_mod;
25968   if ( mp->job_name==NULL ) mp_open_log_file(mp);
25969   while ( mp->input_ptr>0 ) {
25970     if ( token_state ) mp_end_token_list(mp);
25971     else  mp_end_file_reading(mp);
25972   }
25973   while ( mp->loop_ptr!=null ) mp_stop_iteration(mp);
25974   while ( mp->open_parens>0 ) { 
25975     mp_print(mp, " )"); decr(mp->open_parens);
25976   };
25977   while ( mp->cond_ptr!=null ) {
25978     mp_print_nl(mp, "(end occurred when ");
25979 @.end occurred...@>
25980     mp_print_cmd_mod(mp, fi_or_else,mp->cur_if);
25981     /* `\.{if}' or `\.{elseif}' or `\.{else}' */
25982     if ( mp->if_line!=0 ) {
25983       mp_print(mp, " on line "); mp_print_int(mp, mp->if_line);
25984     }
25985     mp_print(mp, " was incomplete)");
25986     mp->if_line=if_line_field(mp->cond_ptr);
25987     mp->cur_if=name_type(mp->cond_ptr); mp->cond_ptr=link(mp->cond_ptr);
25988   }
25989   if ( mp->history!=mp_spotless )
25990     if ( ((mp->history==mp_warning_issued)||(mp->interaction<mp_error_stop_mode)) )
25991       if ( mp->selector==term_and_log ) {
25992     mp->selector=term_only;
25993     mp_print_nl(mp, "(see the transcript file for additional information)");
25994 @.see the transcript file...@>
25995     mp->selector=term_and_log;
25996   }
25997   if ( c==1 ) {
25998     if (mp->ini_version) {
25999       mp_store_mem_file(mp); return;
26000     }
26001     mp_print_nl(mp, "(dump is performed only by INIMP)"); return;
26002 @.dump...only by INIMP@>
26003   }
26004 }
26005
26006 @ @<Declarations@>=
26007 void mp_final_cleanup (MP mp) ;
26008 void mp_init_prim (MP mp) ;
26009 void mp_init_tab (MP mp) ;
26010
26011 @ @<Last-minute...@>=
26012 void mp_init_prim (MP mp) { /* initialize all the primitives */
26013   @<Put each...@>;
26014 }
26015 @#
26016 void mp_init_tab (MP mp) { /* initialize other tables */
26017   integer k; /* all-purpose index */
26018   @<Initialize table entries (done by \.{INIMP} only)@>;
26019 }
26020
26021
26022 @ When we begin the following code, \MP's tables may still contain garbage;
26023 the strings might not even be present. Thus we must proceed cautiously to get
26024 bootstrapped in.
26025
26026 But when we finish this part of the program, \MP\ is ready to call on the
26027 |main_control| routine to do its work.
26028
26029 @<Get the first line...@>=
26030
26031   @<Initialize the input routines@>;
26032   if ( (mp->mem_ident==NULL)||(mp->buffer[loc]=='&') ) {
26033     if ( mp->mem_ident!=NULL ) {
26034       mp_do_initialize(mp); /* erase preloaded mem */
26035     }
26036     if ( ! mp_open_mem_file(mp) ) return mp_fatal_error_stop;
26037     if ( ! mp_load_mem_file(mp) ) {
26038       fclose( mp->mem_file); return mp_fatal_error_stop;
26039     }
26040     fclose( mp->mem_file);
26041     while ( (loc<limit)&&(mp->buffer[loc]==' ') ) incr(loc);
26042   }
26043   mp->buffer[limit]='%';
26044   mp_fix_date_and_time(mp);
26045   mp->sys_random_seed = (scaled)(mp->get_random_seed)(mp);
26046   mp_init_randoms(mp, mp->sys_random_seed);
26047   @<Initialize the print |selector|...@>;
26048   if ( loc<limit ) if ( mp->buffer[loc]!='\\' ) 
26049     mp_start_input(mp); /* \&{input} assumed */
26050 }
26051
26052 @ @<Run inimpost commands@>=
26053 {
26054   mp_get_strings_started(mp);
26055   mp_init_tab(mp); /* initialize the tables */
26056   mp_init_prim(mp); /* call |primitive| for each primitive */
26057   mp->init_str_use=mp->str_ptr; mp->init_pool_ptr=mp->pool_ptr;
26058   mp->max_str_ptr=mp->str_ptr; mp->max_pool_ptr=mp->pool_ptr;
26059   mp_fix_date_and_time(mp);
26060 }
26061
26062
26063 @* \[47] Debugging.
26064 Once \MP\ is working, you should be able to diagnose most errors with
26065 the \.{show} commands and other diagnostic features. But for the initial
26066 stages of debugging, and for the revelation of really deep mysteries, you
26067 can compile \MP\ with a few more aids, including the \PASCAL\ runtime
26068 checks and its debugger. An additional routine called |debug_help|
26069 will also come into play when you type `\.D' after an error message;
26070 |debug_help| also occurs just before a fatal error causes \MP\ to succumb.
26071 @^debugging@>
26072 @^system dependencies@>
26073
26074 The interface to |debug_help| is primitive, but it is good enough when used
26075 with a \PASCAL\ debugger that allows you to set breakpoints and to read
26076 variables and change their values. After getting the prompt `\.{debug \#}', you
26077 type either a negative number (this exits |debug_help|), or zero (this
26078 goes to a location where you can set a breakpoint, thereby entering into
26079 dialog with the \PASCAL\ debugger), or a positive number |m| followed by
26080 an argument |n|. The meaning of |m| and |n| will be clear from the
26081 program below. (If |m=13|, there is an additional argument, |l|.)
26082 @.debug \#@>
26083
26084 @<Last-minute...@>=
26085 void mp_debug_help (MP mp) { /* routine to display various things */
26086   integer k;
26087   int l,m,n;
26088   while (1) { 
26089     wake_up_terminal;
26090     mp_print_nl(mp, "debug # (-1 to exit):"); update_terminal;
26091 @.debug \#@>
26092     m = 0;
26093     fscanf(mp->term_in,"%i",&m);
26094     if ( m<=0 )
26095       return;
26096     n = 0 ;
26097     fscanf(mp->term_in,"%i",&n);
26098     switch (m) {
26099     @<Numbered cases for |debug_help|@>;
26100     default: mp_print(mp, "?"); break;
26101     }
26102   }
26103 }
26104
26105 @ @<Numbered cases...@>=
26106 case 1: mp_print_word(mp, mp->mem[n]); /* display |mem[n]| in all forms */
26107   break;
26108 case 2: mp_print_int(mp, info(n));
26109   break;
26110 case 3: mp_print_int(mp, link(n));
26111   break;
26112 case 4: mp_print_int(mp, eq_type(n)); mp_print_char(mp, ':'); mp_print_int(mp, equiv(n));
26113   break;
26114 case 5: mp_print_variable_name(mp, n);
26115   break;
26116 case 6: mp_print_int(mp, mp->internal[n]);
26117   break;
26118 case 7: mp_do_show_dependencies(mp);
26119   break;
26120 case 9: mp_show_token_list(mp, n,null,100000,0);
26121   break;
26122 case 10: mp_print_str(mp, n);
26123   break;
26124 case 11: mp_check_mem(mp, n>0); /* check wellformedness; print new busy locations if |n>0| */
26125   break;
26126 case 12: mp_search_mem(mp, n); /* look for pointers to |n| */
26127   break;
26128 case 13: l = 0;  fscanf(mp->term_in,"%i",&l); mp_print_cmd_mod(mp, n,l); 
26129   break;
26130 case 14: for (k=0;k<=n;k++) mp_print_str(mp, mp->buffer[k]);
26131   break;
26132 case 15: mp->panicking=! mp->panicking;
26133   break;
26134
26135
26136 @ Saving the filename template
26137
26138 @<Save the filename template@>=
26139
26140   if ( mp->filename_template!=0 ) delete_str_ref(mp->filename_template);
26141   if ( length(mp->cur_exp)==0 ) mp->filename_template=0;
26142   else { 
26143     mp->filename_template=mp->cur_exp; add_str_ref(mp->filename_template);
26144   }
26145 }
26146
26147 @* \[48] System-dependent changes.
26148 This section should be replaced, if necessary, by any special
26149 modification of the program
26150 that are necessary to make \MP\ work at a particular installation.
26151 It is usually best to design your change file so that all changes to
26152 previous sections preserve the section numbering; then everybody's version
26153 will be consistent with the published program. More extensive changes,
26154 which introduce new sections, can be inserted here; then only the index
26155 itself will get a new section number.
26156 @^system dependencies@>
26157
26158 @* \[49] Index.
26159 Here is where you can find all uses of each identifier in the program,
26160 with underlined entries pointing to where the identifier was defined.
26161 If the identifier is only one letter long, however, you get to see only
26162 the underlined entries. {\sl All references are to section numbers instead of
26163 page numbers.}
26164
26165 This index also lists error messages and other aspects of the program
26166 that you might want to look up some day. For example, the entry
26167 for ``system dependencies'' lists all sections that should receive
26168 special attention from people who are installing \MP\ in a new
26169 operating environment. A list of various things that can't happen appears
26170 under ``this can't happen''.
26171 Approximately 25 sections are listed under ``inner loop''; these account
26172 for more than 60\pct! of \MP's running time, exclusive of input and output.