remove explicit pascal references from documentation, fix a few texts, and remove...
[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\ps{PostScript}
16 \def\psqrt#1{\sqrt{\mathstrut#1}}
17 \def\k{_{k+1}}
18 \def\pct!{{\char`\%}} % percent sign in ordinary text
19 \font\tenlogo=logo10 % font used for the METAFONT logo
20 \font\logos=logosl10
21 \def\MF{{\tenlogo META}\-{\tenlogo FONT}}
22 \def\MP{{\tenlogo META}\-{\tenlogo POST}}
23 \def\[#1]{\ignorespaces} % left over from pascal web
24 \def\<#1>{$\langle#1\rangle$}
25 \def\section{\mathhexbox278}
26 \let\swap=\leftrightarrow
27 \def\round{\mathop{\rm round}\nolimits}
28 \mathchardef\vb="026A % synonym for `\|'
29
30 \def\(#1){} % this is used to make section names sort themselves better
31 \def\9#1{} % this is used for sort keys in the index via @@:sort key}{entry@@>
32 \def\title{MetaPost}
33 \pdfoutput=1
34 \pageno=3
35
36 @* \[1] Introduction.
37
38 This is \MP, a graphics-language processor based on D. E. Knuth's \MF.
39
40 The main purpose of the following program is to explain the algorithms of \MP\
41 as clearly as possible. However, the program has been written so that it
42 can be tuned to run efficiently in a wide variety of operating environments
43 by making comparatively few changes. Such flexibility is possible because
44 the documentation that follows is written in the \.{WEB} language, which is
45 at a higher level than C.
46
47 A large piece of software like \MP\ has inherent complexity that cannot
48 be reduced below a certain level of difficulty, although each individual
49 part is fairly simple by itself. The \.{WEB} language is intended to make
50 the algorithms as readable as possible, by reflecting the way the
51 individual program pieces fit together and by providing the
52 cross-references that connect different parts. Detailed comments about
53 what is going on, and about why things were done in certain ways, have
54 been liberally sprinkled throughout the program.  These comments explain
55 features of the implementation, but they rarely attempt to explain the
56 \MP\ language itself, since the reader is supposed to be familiar with
57 {\sl The {\logos METAFONT\/}book} as well as the manual
58 @.WEB@>
59 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
60 {\sl A User's Manual for MetaPost}, Computing Science Technical Report 162,
61 AT\AM T Bell Laboratories.
62
63 @ The present implementation is a preliminary version, but the possibilities
64 for new features are limited by the desire to remain as nearly compatible
65 with \MF\ as possible.
66
67 On the other hand, the \.{WEB} description can be extended without changing
68 the core of the program, and it has been designed so that such
69 extensions are not extremely difficult to make.
70 The |banner| string defined here should be changed whenever \MP\
71 undergoes any modifications, so that it will be clear which version of
72 \MP\ might be the guilty party when a problem arises.
73 @^extensions to \MP@>
74 @^system dependencies@>
75
76 @d banner "This is MetaPost, Version 1.002" /* printed when \MP\ starts */
77 @d metapost_version "1.002"
78 @d mplib_version "0.20"
79 @d version_string " (Cweb version 0.20)"
80
81 @d true 1
82 @d false 0
83
84 @ The external library header for \MP\ is |mplib.h|. It contains a
85 few typedefs and the header defintions for the externally used
86 fuctions.
87
88 The most important of the typedefs is the definition of the structure 
89 |MP_options|, that acts as a small, configurable front-end to the fairly 
90 large |MP_instance| structure.
91  
92 @(mplib.h@>=
93 typedef struct MP_instance * MP;
94 @<Exported types@>
95 typedef struct MP_options {
96   @<Option variables@>
97 } MP_options;
98 @<Exported function headers@>
99
100 @ The internal header file is much longer: it not only lists the complete
101 |MP_instance|, but also a lot of functions that have to be available to
102 the \ps\ backend, that is defined in a separate \.{WEB} file. 
103
104 The variables from |MP_options| are included inside the |MP_instance| 
105 wholesale.
106
107 @(mpmp.h@>=
108 #include <setjmp.h>
109 typedef struct psout_data_struct * psout_data;
110 typedef int boolean;
111 typedef signed int integer;
112 @<Declare helpers@>;
113 @<Types in the outer block@>;
114 @<Constants in the outer block@>
115 #  ifndef LIBAVL_ALLOCATOR
116 #    define LIBAVL_ALLOCATOR
117     struct libavl_allocator {
118         void *(*libavl_malloc) (struct libavl_allocator *, size_t libavl_size);
119         void (*libavl_free) (struct libavl_allocator *, void *libavl_block);
120     };
121 #  endif
122 typedef struct MP_instance {
123   @<Option variables@>
124   @<Global variables@>
125 } MP_instance;
126 @<Internal library declarations@>
127
128 @ @c 
129 #include <stdio.h>
130 #include <stdlib.h>
131 #include <string.h>
132 #include <stdarg.h>
133 #include <assert.h>
134 #include <unistd.h> /* for access() */
135 #include <time.h> /* for struct tm \& co */
136 #include "mplib.h"
137 #include "mpmp.h" /* internal header */
138 #include "mppsout.h" /* internal header */
139 @h
140 @<Declarations@>
141 @<Basic printing procedures@>
142 @<Error handling procedures@>
143
144 @ Here are the functions that set up the \MP\ instance.
145
146 @<Declarations@> =
147 @<Declare |mp_reallocate| functions@>;
148 struct MP_options *mp_options (void);
149 MP mp_new (struct MP_options *opt);
150
151 @ @c
152 struct MP_options *mp_options (void) {
153   struct MP_options *opt;
154   opt = malloc(sizeof(MP_options));
155   if (opt!=NULL) {
156     memset (opt,0,sizeof(MP_options));
157   }
158   return opt;
159
160
161 @ @c
162 MP mp_new (struct MP_options *opt) {
163   MP mp;
164   mp = xmalloc(1,sizeof(MP_instance));
165   @<Set |ini_version|@>;
166   @<Setup the non-local jump buffer in |mp_new|@>;
167   @<Allocate or initialize variables@>
168   if (opt->main_memory>mp->mem_max)
169     mp_reallocate_memory(mp,opt->main_memory);
170   mp_reallocate_paths(mp,1000);
171   mp_reallocate_fonts(mp,8);
172   return mp;
173 }
174
175 @ @c
176 void mp_free (MP mp) {
177   int k; /* loop variable */
178   @<Dealloc variables@>
179   xfree(mp);
180 }
181
182 @ @c
183 void mp_do_initialize ( MP mp) {
184   @<Local variables for initialization@>
185   @<Set initial values of key variables@>
186 }
187 int mp_initialize (MP mp) { /* this procedure gets things started properly */
188   mp->history=mp_fatal_error_stop; /* in case we quit during initialization */
189   @<Install and test the non-local jump buffer@>;
190   t_open_out; /* open the terminal for output */
191   @<Check the ``constant'' values...@>;
192   if ( mp->bad>0 ) {
193         char ss[256];
194     snprintf(ss,256,"Ouch---my internal constants have been clobbered!\n"
195                    "---case %i",(int)mp->bad);
196     do_fprintf(mp->err_out,(char *)ss);
197 @.Ouch...clobbered@>
198     return mp->history;
199   }
200   mp_do_initialize(mp); /* erase preloaded mem */
201   if (mp->ini_version) {
202     @<Run inimpost commands@>;
203   }
204   @<Initialize the output routines@>;
205   @<Get the first line of input and prepare to start@>;
206   mp_set_job_id(mp);
207   mp_init_map_file(mp, mp->troff_mode);
208   mp->history=mp_spotless; /* ready to go! */
209   if (mp->troff_mode) {
210     mp->internal[mp_gtroffmode]=unity; 
211     mp->internal[mp_prologues]=unity; 
212   }
213   if ( mp->start_sym>0 ) { /* insert the `\&{everyjob}' symbol */
214     mp->cur_sym=mp->start_sym; mp_back_input(mp);
215   }
216   return mp->history;
217 }
218
219
220 @<Exported function headers@>=
221 extern struct MP_options *mp_options (void);
222 extern MP mp_new (struct MP_options *opt) ;
223 extern void mp_free (MP mp);
224 extern int mp_initialize (MP mp);
225
226 @ The overall \MP\ program begins with the heading just shown, after which
227 comes a bunch of procedure declarations and function declarations.
228 Finally we will get to the main program, which begins with the
229 comment `|start_here|'. If you want to skip down to the
230 main program now, you can look up `|start_here|' in the index.
231 But the author suggests that the best way to understand this program
232 is to follow pretty much the order of \MP's components as they appear in the
233 \.{WEB} description you are now reading, since the present ordering is
234 intended to combine the advantages of the ``bottom up'' and ``top down''
235 approaches to the problem of understanding a somewhat complicated system.
236
237 @ Some of the code below is intended to be used only when diagnosing the
238 strange behavior that sometimes occurs when \MP\ is being installed or
239 when system wizards are fooling around with \MP\ without quite knowing
240 what they are doing. Such code will not normally be compiled; it is
241 delimited by the preprocessor test `|#ifdef DEBUG .. #endif|'.
242
243 @ This program has two important variations: (1) There is a long and slow
244 version called \.{INIMP}, which does the extra calculations needed to
245 @.INIMP@>
246 initialize \MP's internal tables; and (2)~there is a shorter and faster
247 production version, which cuts the initialization to a bare minimum.
248
249 Which is which is decided at runtime.
250
251 @ The following parameters can be changed at compile time to extend or
252 reduce \MP's capacity. They may have different values in \.{INIMP} and
253 in production versions of \MP.
254 @.INIMP@>
255 @^system dependencies@>
256
257 @<Constants...@>=
258 #define file_name_size 255 /* file names shouldn't be longer than this */
259 #define bistack_size 1500 /* size of stack for bisection algorithms;
260   should probably be left at this value */
261
262 @ Like the preceding parameters, the following quantities can be changed
263 at compile time to extend or reduce \MP's capacity. But if they are changed,
264 it is necessary to rerun the initialization program \.{INIMP}
265 @.INIMP@>
266 to generate new tables for the production \MP\ program.
267 One can't simply make helter-skelter changes to the following constants,
268 since certain rather complex initialization
269 numbers are computed from them. 
270
271 @ @<Glob...@>=
272 int max_strings; /* maximum number of strings; must not exceed |max_halfword| */
273 int pool_size; /* maximum number of characters in strings, including all
274   error messages and help texts, and the names of all identifiers */
275 int mem_max; /* greatest index in \MP's internal |mem| array;
276   must be strictly less than |max_halfword|;
277   must be equal to |mem_top| in \.{INIMP}, otherwise |>=mem_top| */
278 int mem_top; /* largest index in the |mem| array dumped by \.{INIMP};
279   must not be greater than |mem_max| */
280
281 @ @<Option variables@>=
282 int error_line; /* width of context lines on terminal error messages */
283 int half_error_line; /* width of first lines of contexts in terminal
284   error messages; should be between 30 and |error_line-15| */
285 int max_print_line; /* width of longest text lines output; should be at least 60 */
286 int hash_size; /* maximum number of symbolic tokens,
287   must be less than |max_halfword-3*param_size| */
288 int hash_prime; /* a prime number equal to about 85\pct! of |hash_size| */
289 int param_size; /* maximum number of simultaneous macro parameters */
290 int max_in_open; /* maximum number of input files and error insertions that
291   can be going on simultaneously */
292 int main_memory; /* only for options, to set up |mem_max| and |mem_top| */
293
294
295 @d set_value(a,b,c) do { a=c; if (b>c) a=b; } while (0)
296
297 @<Allocate or ...@>=
298 mp->max_strings=500;
299 mp->pool_size=10000;
300 set_value(mp->error_line,opt->error_line,79);
301 set_value(mp->half_error_line,opt->half_error_line,50);
302 set_value(mp->max_print_line,opt->max_print_line,100);
303 mp->main_memory=5000;
304 mp->mem_max=5000;
305 mp->mem_top=5000;
306 set_value(mp->hash_size,opt->hash_size,9500);
307 set_value(mp->hash_prime,opt->hash_prime,7919);
308 set_value(mp->param_size,opt->param_size,150);
309 set_value(mp->max_in_open,opt->max_in_open,10);
310
311
312 @ In case somebody has inadvertently made bad settings of the ``constants,''
313 \MP\ checks them using a global variable called |bad|.
314
315 This is the first of many sections of \MP\ where global variables are
316 defined.
317
318 @<Glob...@>=
319 integer bad; /* is some ``constant'' wrong? */
320
321 @ Later on we will say `\ignorespaces|if (mem_max>=max_halfword) bad=10;|',
322 or something similar. (We can't do that until |max_halfword| has been defined.)
323
324 @<Check the ``constant'' values for consistency@>=
325 mp->bad=0;
326 if ( (mp->half_error_line<30)||(mp->half_error_line>mp->error_line-15) ) mp->bad=1;
327 if ( mp->max_print_line<60 ) mp->bad=2;
328 if ( mp->mem_top<=1100 ) mp->bad=4;
329 if (mp->hash_prime>mp->hash_size ) mp->bad=5;
330
331 @ Some |goto| labels are used by the following definitions. The label
332 `|restart|' is occasionally used at the very beginning of a procedure; and
333 the label `|reswitch|' is occasionally used just prior to a |case|
334 statement in which some cases change the conditions and we wish to branch
335 to the newly applicable case.  Loops that are set up with the |loop|
336 construction defined below are commonly exited by going to `|done|' or to
337 `|found|' or to `|not_found|', and they are sometimes repeated by going to
338 `|continue|'.  If two or more parts of a subroutine start differently but
339 end up the same, the shared code may be gathered together at
340 `|common_ending|'.
341
342 @ Here are some macros for common programming idioms.
343
344 @d incr(A)   (A)=(A)+1 /* increase a variable by unity */
345 @d decr(A)   (A)=(A)-1 /* decrease a variable by unity */
346 @d negate(A) (A)=-(A) /* change the sign of a variable */
347 @d double(A) (A)=(A)+(A)
348 @d odd(A)   ((A)%2==1)
349 @d chr(A)   (A)
350 @d do_nothing   /* empty statement */
351 @d Return   goto exit /* terminate a procedure call */
352 @f return   nil /* \.{WEB} will henceforth say |return| instead of \\{return} */
353
354 @* \[2] The character set.
355 In order to make \MP\ readily portable to a wide variety of
356 computers, all of its input text is converted to an internal eight-bit
357 code that includes standard ASCII, the ``American Standard Code for
358 Information Interchange.''  This conversion is done immediately when each
359 character is read in. Conversely, characters are converted from ASCII to
360 the user's external representation just before they are output to a
361 text file.
362 @^ASCII code@>
363
364 Such an internal code is relevant to users of \MP\ only with respect to
365 the \&{char} and \&{ASCII} operations, and the comparison of strings.
366
367 @ Characters of text that have been converted to \MP's internal form
368 are said to be of type |ASCII_code|, which is a subrange of the integers.
369
370 @<Types...@>=
371 typedef unsigned char ASCII_code; /* eight-bit numbers */
372
373 @ The present specification of \MP\ has been written under the assumption
374 that the character set contains at least the letters and symbols associated
375 with ASCII codes 040 through 0176; all of these characters are now
376 available on most computer terminals.
377
378 We shall use the name |text_char| to stand for the data type of the characters 
379 that are converted to and from |ASCII_code| when they are input and output. 
380 We shall also assume that |text_char| consists of the elements 
381 |chr(first_text_char)| through |chr(last_text_char)|, inclusive. 
382 The following definitions should be adjusted if necessary.
383 @^system dependencies@>
384
385 @d first_text_char 0 /* ordinal number of the smallest element of |text_char| */
386 @d last_text_char 255 /* ordinal number of the largest element of |text_char| */
387
388 @<Types...@>=
389 typedef unsigned char text_char; /* the data type of characters in text files */
390
391 @ @<Local variables for init...@>=
392 integer i;
393
394 @ The \MP\ processor converts between ASCII code and
395 the user's external character set by means of arrays |xord| and |xchr|
396 that are analogous to Pascal's |ord| and |chr| functions.
397
398 @d xchr(A) mp->xchr[(A)]
399 @d xord(A) mp->xord[(A)]
400
401 @<Glob...@>=
402 ASCII_code xord[256];  /* specifies conversion of input characters */
403 text_char xchr[256];  /* specifies conversion of output characters */
404
405 @ The core system assumes all 8-bit is acceptable.  If it is not,
406 a change file has to alter the below section.
407 @^system dependencies@>
408
409 Additionally, people with extended character sets can
410 assign codes arbitrarily, giving an |xchr| equivalent to whatever
411 characters the users of \MP\ are allowed to have in their input files.
412 Appropriate changes to \MP's |char_class| table should then be made.
413 (Unlike \TeX, each installation of \MP\ has a fixed assignment of category
414 codes, called the |char_class|.) Such changes make portability of programs
415 more difficult, so they should be introduced cautiously if at all.
416 @^character set dependencies@>
417 @^system dependencies@>
418
419 @<Set initial ...@>=
420 for (i=0;i<=0377;i++) { xchr(i)=i; }
421
422 @ The following system-independent code makes the |xord| array contain a
423 suitable inverse to the information in |xchr|. Note that if |xchr[i]=xchr[j]|
424 where |i<j<0177|, the value of |xord[xchr[i]]| will turn out to be
425 |j| or more; hence, standard ASCII code numbers will be used instead of
426 codes below 040 in case there is a coincidence.
427
428 @<Set initial ...@>=
429 for (i=first_text_char;i<=last_text_char;i++) { 
430    xord(chr(i))=0177;
431 }
432 for (i=0200;i<=0377;i++) { xord(xchr(i))=i;}
433 for (i=0;i<=0176;i++) { xord(xchr(i))=i;}
434
435 @* \[3] Input and output.
436 The bane of portability is the fact that different operating systems treat
437 input and output quite differently, perhaps because computer scientists
438 have not given sufficient attention to this problem. People have felt somehow
439 that input and output are not part of ``real'' programming. Well, it is true
440 that some kinds of programming are more fun than others. With existing
441 input/output conventions being so diverse and so messy, the only sources of
442 joy in such parts of the code are the rare occasions when one can find a
443 way to make the program a little less bad than it might have been. We have
444 two choices, either to attack I/O now and get it over with, or to postpone
445 I/O until near the end. Neither prospect is very attractive, so let's
446 get it over with.
447
448 The basic operations we need to do are (1)~inputting and outputting of
449 text, to or from a file or the user's terminal; (2)~inputting and
450 outputting of eight-bit bytes, to or from a file; (3)~instructing the
451 operating system to initiate (``open'') or to terminate (``close'') input or
452 output from a specified file; (4)~testing whether the end of an input
453 file has been reached; (5)~display of bits on the user's screen.
454 The bit-display operation will be discussed in a later section; we shall
455 deal here only with more traditional kinds of I/O.
456
457 @ Finding files happens in a slightly roundabout fashion: the \MP\
458 instance object contains a field that holds a function pointer that finds a
459 file, and returns its name, or NULL. For this, it receives three
460 parameters: the non-qualified name |fname|, the intended |fopen|
461 operation type |fmode|, and the type of the file |ftype|.
462
463 The file types that are passed on in |ftype| can be  used to 
464 differentiate file searches if a library like kpathsea is used,
465 the fopen mode is passed along for the same reason.
466
467 @<Types...@>=
468 typedef unsigned char eight_bits ; /* unsigned one-byte quantity */
469
470 @ @<Exported types@>=
471 enum mp_filetype {
472   mp_filetype_terminal = 0, /* the terminal */
473   mp_filetype_error, /* the terminal */
474   mp_filetype_program , /* \MP\ language input */
475   mp_filetype_log,  /* the log file */
476   mp_filetype_postscript, /* the postscript output */
477   mp_filetype_memfile, /* memory dumps */
478   mp_filetype_metrics, /* TeX font metric files */
479   mp_filetype_fontmap, /* PostScript font mapping files */
480   mp_filetype_font, /*  PostScript type1 font programs */
481   mp_filetype_encoding, /*  PostScript font encoding files */
482   mp_filetype_text,  /* first text file for readfrom and writeto primitives */
483 };
484 typedef char *(*mp_file_finder)(char *, char *, int);
485 typedef void *(*mp_file_opener)(char *, char *, int);
486 typedef char *(*mp_file_reader)(void *, size_t *);
487 typedef void (*mp_binfile_reader)(void *, void **, size_t *);
488 typedef void (*mp_file_closer)(void *);
489 typedef int (*mp_file_eoftest)(void *);
490 typedef void (*mp_file_flush)(void *);
491 typedef void (*mp_file_writer)(void *, char *);
492 typedef void (*mp_binfile_writer)(void *, void *, size_t);
493 #define NOTTESTING 1
494
495 @ @<Option variables@>=
496 mp_file_finder find_file;
497 mp_file_opener open_file;
498 mp_file_reader read_ascii_file;
499 mp_binfile_reader read_binary_file;
500 mp_file_closer close_file;
501 mp_file_eoftest eof_file;
502 mp_file_flush flush_file;
503 mp_file_writer write_ascii_file;
504 mp_binfile_writer write_binary_file;
505
506 @ The default function for finding files is |mp_find_file|. It is 
507 pretty stupid: it will only find files in the current directory.
508
509 This function may disappear altogether, it is currently only
510 used for the default font map file.
511
512 @c
513 char *mp_find_file (char *fname, char *fmode, int ftype)  {
514   if (fmode[0] != 'r' || (! access (fname,R_OK)) || ftype) {  
515      return strdup(fname);
516   }
517   return NULL;
518 }
519
520 @ This has to be done very early on, so it is best to put it in with
521 the |mp_new| allocations
522
523 @d set_callback_option(A) do { mp->A = mp_##A;
524   if (opt->A!=NULL) mp->A = opt->A;
525 } while (0)
526
527 @<Allocate or initialize ...@>=
528 set_callback_option(find_file);
529 set_callback_option(open_file);
530 set_callback_option(read_ascii_file);
531 set_callback_option(read_binary_file);
532 set_callback_option(close_file);
533 set_callback_option(eof_file);
534 set_callback_option(flush_file);
535 set_callback_option(write_ascii_file);
536 set_callback_option(write_binary_file);
537
538 @ Because |mp_find_file| is used so early, it has to be in the helpers
539 section.
540
541 @<Internal ...@>=
542 char *mp_find_file (char *fname, char *fmode, int ftype) ;
543 void *mp_open_file (char *fname, char *fmode, int ftype) ;
544 char *mp_read_ascii_file (void *f, size_t *size) ;
545 void mp_read_binary_file (void *f, void **d, size_t *size) ;
546 void mp_close_file (void *f) ;
547 int mp_eof_file (void *f) ;
548 void mp_flush_file (void *f) ;
549 void mp_write_ascii_file (void *f, char *s) ;
550 void mp_write_binary_file (void *f, void *s, size_t t) ;
551
552 @ The function to open files can now be very short.
553
554 @c
555 void *mp_open_file(char *fname, char *fmode, int ftype)  {
556 #if NOTTESTING
557   if (ftype==mp_filetype_terminal) {
558     return (fmode[0] == 'r' ? stdin : stdout);
559   } else if (ftype==mp_filetype_error) {
560     return stderr;
561   } else if (fname != NULL && (fmode[0] != 'r' || (! access (fname,R_OK)))) {
562     return (void *)fopen(fname, fmode);
563   }
564 #endif
565   return NULL;
566 }
567
568 @ This is a legacy interface: (almost) all file names pass through |name_of_file|.
569
570 @<Glob...@>=
571 char name_of_file[file_name_size+1]; /* the name of a system file */
572 int name_length;/* this many characters are actually
573   relevant in |name_of_file| (the rest are blank) */
574
575 @ @<Option variables@>=
576 int print_found_names; /* configuration parameter */
577
578 @ If this parameter is true, the terminal and log will report the found
579 file names for input files instead of the requested ones. 
580 It is off by default because it creates an extra filename lookup.
581
582 @<Allocate or initialize ...@>=
583 mp->print_found_names = (opt->print_found_names>0 ? true : false);
584
585 @ \MP's file-opening procedures return |false| if no file identified by
586 |name_of_file| could be opened.
587
588 The |OPEN_FILE| macro takes care of the |print_found_names| parameter.
589 It is not used for opening a mem file for read, because that file name 
590 is never printed.
591
592 @d OPEN_FILE(A) do {
593   if (mp->print_found_names) {
594     char *s = (mp->find_file)(mp->name_of_file,A,ftype);
595     if (s!=NULL) {
596       *f = (mp->open_file)(mp->name_of_file,A, ftype); 
597       strncpy(mp->name_of_file,s,file_name_size);
598       xfree(s);
599     } else {
600       *f = NULL;
601     }
602   } else {
603     *f = (mp->open_file)(mp->name_of_file,A, ftype); 
604   }
605 } while (0);
606 return (*f ? true : false)
607
608 @c 
609 boolean mp_a_open_in (MP mp, void **f, int ftype) {
610   /* open a text file for input */
611   OPEN_FILE("r");
612 }
613 @#
614 boolean mp_w_open_in (MP mp, void **f) {
615   /* open a word file for input */
616   *f = (mp->open_file)(mp->name_of_file,"rb",mp_filetype_memfile); 
617   return (*f ? true : false);
618 }
619 @#
620 boolean mp_a_open_out (MP mp, void **f, int ftype) {
621   /* open a text file for output */
622   OPEN_FILE("w");
623 }
624 @#
625 boolean mp_b_open_out (MP mp, void **f, int ftype) {
626   /* open a binary file for output */
627   OPEN_FILE("wb");
628 }
629 @#
630 boolean mp_w_open_out (MP mp, void **f) {
631   /* open a word file for output */
632   int ftype = mp_filetype_memfile;
633   OPEN_FILE("wb");
634 }
635
636 @ @c
637 char *mp_read_ascii_file (void *f, size_t *size) {
638   int c;
639   size_t len = 0, lim = 128;
640   char *s = NULL;
641   *size = 0;
642 #if NOTTESTING
643   c = fgetc(f);
644   if (c==EOF)
645     return NULL;
646   s = malloc(lim); 
647   if (s==NULL) return NULL;
648   while (c!=EOF && c!='\n' && c!='\r') { 
649     if (len==lim) {
650       s =realloc(s, (lim+(lim>>2)));
651       if (s==NULL) return NULL;
652       lim+=(lim>>2);
653     }
654         s[len++] = c;
655     c =fgetc(f);
656   }
657   if (c=='\r') {
658     c = fgetc(f);
659     if (c!=EOF && c!='\n')
660        ungetc(c,f);
661   }
662   s[len] = 0;
663   *size = len;
664 #endif
665   return s;
666 }
667
668 @ @c
669 void mp_write_ascii_file (void *f, char *s) {
670 #if NOTTESTING
671   if (f!=NULL) {
672     fputs(s,f);
673   }
674 #endif
675 }
676
677 @ @c
678 void mp_read_binary_file (void *f, void **data, size_t *size) {
679   size_t len = 0;
680 #if NOTTESTING
681   len = fread(*data,1,*size,f);
682 #endif
683   *size = len;
684 }
685
686 @ @c
687 void mp_write_binary_file (void *f, void *s, size_t size) {
688 #if NOTTESTING
689   if (f!=NULL)
690     fwrite(s,size,1,f);
691 #endif
692 }
693
694
695 @ @c
696 void mp_close_file (void *f) {
697 #if NOTTESTING
698   fclose(f);
699 #endif
700 }
701
702 @ @c
703 int mp_eof_file (void *f) {
704 #if NOTTESTING
705   return feof(f);
706 #else
707   return 0;
708 #endif
709 }
710
711 @ @c
712 void mp_flush_file (void *f) {
713 #if NOTTESTING
714   fflush(f);
715 #endif
716 }
717
718 @ Input from text files is read one line at a time, using a routine called
719 |input_ln|. This function is defined in terms of global variables called
720 |buffer|, |first|, and |last| that will be described in detail later; for
721 now, it suffices for us to know that |buffer| is an array of |ASCII_code|
722 values, and that |first| and |last| are indices into this array
723 representing the beginning and ending of a line of text.
724
725 @<Glob...@>=
726 size_t buf_size; /* maximum number of characters simultaneously present in
727                     current lines of open files */
728 ASCII_code *buffer; /* lines of characters being read */
729 size_t first; /* the first unused position in |buffer| */
730 size_t last; /* end of the line just input to |buffer| */
731 size_t max_buf_stack; /* largest index used in |buffer| */
732
733 @ @<Allocate or initialize ...@>=
734 mp->buf_size = 200;
735 mp->buffer = xmalloc((mp->buf_size+1),sizeof(ASCII_code));
736
737 @ @<Dealloc variables@>=
738 xfree(mp->buffer);
739
740 @ @c
741 void mp_reallocate_buffer(MP mp, size_t l) {
742   ASCII_code *buffer;
743   if (l>max_halfword) {
744     mp_confusion(mp,"buffer size"); /* can't happen (I hope) */
745   }
746   buffer = xmalloc((l+1),sizeof(ASCII_code));
747   memcpy(buffer,mp->buffer,(mp->buf_size+1));
748   xfree(mp->buffer);
749   mp->buffer = buffer ;
750   mp->buf_size = l;
751 }
752
753 @ The |input_ln| function brings the next line of input from the specified
754 field into available positions of the buffer array and returns the value
755 |true|, unless the file has already been entirely read, in which case it
756 returns |false| and sets |last:=first|.  In general, the |ASCII_code|
757 numbers that represent the next line of the file are input into
758 |buffer[first]|, |buffer[first+1]|, \dots, |buffer[last-1]|; and the
759 global variable |last| is set equal to |first| plus the length of the
760 line. Trailing blanks are removed from the line; thus, either |last=first|
761 (in which case the line was entirely blank) or |buffer[last-1]<>" "|.
762 @^inner loop@>
763
764 The variable |max_buf_stack|, which is used to keep track of how large
765 the |buf_size| parameter must be to accommodate the present job, is
766 also kept up to date by |input_ln|.
767
768 @c 
769 boolean mp_input_ln (MP mp, void *f ) {
770   /* inputs the next line or returns |false| */
771   char *s;
772   size_t size = 0; 
773   mp->last=mp->first; /* cf.\ Matthew 19\thinspace:\thinspace30 */
774   s = (mp->read_ascii_file)(f, &size);
775   if (s==NULL)
776         return false;
777   if (size>0) {
778     mp->last = mp->first+size;
779     if ( mp->last>=mp->max_buf_stack ) { 
780       mp->max_buf_stack=mp->last+1;
781       while ( mp->max_buf_stack>=mp->buf_size ) {
782         mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
783       }
784     }
785     memcpy((mp->buffer+mp->first),s,size);
786     /* while ( mp->buffer[mp->last]==' ' ) mp->last--; */
787   } 
788   free(s);
789   return true;
790 }
791
792 @ The user's terminal acts essentially like other files of text, except
793 that it is used both for input and for output. When the terminal is
794 considered an input file, the file variable is called |term_in|, and when it
795 is considered an output file the file variable is |term_out|.
796 @^system dependencies@>
797
798 @<Glob...@>=
799 void * term_in; /* the terminal as an input file */
800 void * term_out; /* the terminal as an output file */
801 void * err_out; /* the terminal as an output file */
802
803 @ Here is how to open the terminal files. In the default configuration,
804 nothing happens except that the command line (if there is one) is copied
805 to the input buffer.  The variable |command_line| will be filled by the 
806 |main| procedure. The copying can not be done earlier in the program 
807 logic because in the |INI| version, the |buffer| is also used for primitive 
808 initialization.
809
810 @^system dependencies@>
811
812 @d t_open_out  do {/* open the terminal for text output */
813     mp->term_out = (mp->open_file)("terminal", "w", mp_filetype_terminal);
814     mp->err_out = (mp->open_file)("error", "w", mp_filetype_error);
815 } while (0)
816 @d t_open_in  do { /* open the terminal for text input */
817     mp->term_in = (mp->open_file)("terminal", "r", mp_filetype_terminal);
818     if (mp->command_line!=NULL) {
819       mp->last = strlen(mp->command_line);
820       strncpy((char *)mp->buffer,mp->command_line,mp->last);
821       xfree(mp->command_line);
822     }
823 } while (0)
824
825 @d t_close_out do { /* close the terminal */
826   (mp->close_file)(mp->term_out);
827   (mp->close_file)(mp->err_out);
828 } while (0)
829
830 @d t_close_in do { /* close the terminal */
831   (mp->close_file)(mp->term_in);
832 } while (0)
833
834 @<Option variables@>=
835 char *command_line;
836
837 @ @<Allocate or initialize ...@>=
838 mp->command_line = xstrdup(opt->command_line);
839
840 @ Sometimes it is necessary to synchronize the input/output mixture that
841 happens on the user's terminal, and three system-dependent
842 procedures are used for this
843 purpose. The first of these, |update_terminal|, is called when we want
844 to make sure that everything we have output to the terminal so far has
845 actually left the computer's internal buffers and been sent.
846 The second, |clear_terminal|, is called when we wish to cancel any
847 input that the user may have typed ahead (since we are about to
848 issue an unexpected error message). The third, |wake_up_terminal|,
849 is supposed to revive the terminal if the user has disabled it by
850 some instruction to the operating system.  The following macros show how
851 these operations can be specified:
852 @^system dependencies@>
853
854 @d update_terminal   (mp->flush_file)(mp->term_out) /* empty the terminal output buffer */
855 @d clear_terminal   do_nothing /* clear the terminal input buffer */
856 @d wake_up_terminal  (mp->flush_file)(mp->term_out) /* cancel the user's cancellation of output */
857
858 @ We need a special routine to read the first line of \MP\ input from
859 the user's terminal. This line is different because it is read before we
860 have opened the transcript file; there is sort of a ``chicken and
861 egg'' problem here. If the user types `\.{input cmr10}' on the first
862 line, or if some macro invoked by that line does such an \.{input},
863 the transcript file will be named `\.{cmr10.log}'; but if no \.{input}
864 commands are performed during the first line of terminal input, the transcript
865 file will acquire its default name `\.{mpout.log}'. (The transcript file
866 will not contain error messages generated by the first line before the
867 first \.{input} command.)
868
869 The first line is even more special. It's nice to let the user start
870 running a \MP\ job by typing a command line like `\.{MP cmr10}'; in
871 such a case, \MP\ will operate as if the first line of input were
872 `\.{cmr10}', i.e., the first line will consist of the remainder of the
873 command line, after the part that invoked \MP.
874
875 @ Different systems have different ways to get started. But regardless of
876 what conventions are adopted, the routine that initializes the terminal
877 should satisfy the following specifications:
878
879 \yskip\textindent{1)}It should open file |term_in| for input from the
880   terminal. (The file |term_out| will already be open for output to the
881   terminal.)
882
883 \textindent{2)}If the user has given a command line, this line should be
884   considered the first line of terminal input. Otherwise the
885   user should be prompted with `\.{**}', and the first line of input
886   should be whatever is typed in response.
887
888 \textindent{3)}The first line of input, which might or might not be a
889   command line, should appear in locations |first| to |last-1| of the
890   |buffer| array.
891
892 \textindent{4)}The global variable |loc| should be set so that the
893   character to be read next by \MP\ is in |buffer[loc]|. This
894   character should not be blank, and we should have |loc<last|.
895
896 \yskip\noindent(It may be necessary to prompt the user several times
897 before a non-blank line comes in. The prompt is `\.{**}' instead of the
898 later `\.*' because the meaning is slightly different: `\.{input}' need
899 not be typed immediately after~`\.{**}'.)
900
901 @d loc mp->cur_input.loc_field /* location of first unread character in |buffer| */
902
903 @ The following program does the required initialization
904 without retrieving a possible command line.
905 It should be clear how to modify this routine to deal with command lines,
906 if the system permits them.
907 @^system dependencies@>
908
909 @c 
910 boolean mp_init_terminal (MP mp) { /* gets the terminal input started */
911   t_open_in; 
912   if (mp->last!=0) {
913     loc = mp->first = 0;
914         return true;
915   }
916   while (1) { 
917     wake_up_terminal; do_fprintf(mp->term_out,"**"); update_terminal;
918 @.**@>
919     if ( ! mp_input_ln(mp, mp->term_in ) ) { /* this shouldn't happen */
920       do_fprintf(mp->term_out,"\n! End of file on the terminal... why?");
921 @.End of file on the terminal@>
922       return false;
923     }
924     loc=mp->first;
925     while ( (loc<(int)mp->last)&&(mp->buffer[loc]==' ') ) 
926       incr(loc);
927     if ( loc<(int)mp->last ) { 
928       return true; /* return unless the line was all blank */
929     };
930     do_fprintf(mp->term_out,"Please type the name of your input file.\n");
931   }
932 }
933
934 @ @<Declarations@>=
935 boolean mp_init_terminal (MP mp) ;
936
937
938 @* \[4] String handling.
939 Symbolic token names and diagnostic messages are variable-length strings
940 of eight-bit characters. Many strings \MP\ uses are simply literals
941 in the compiled source, like the error messages and the names of the
942 internal parameters. Other strings are used or defined from the \MP\ input 
943 language, and these have to be interned.
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 functions, 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 |pseudo|, puts output into a cyclic buffer that is used
1529   by the |show_context| routine; when we get to that routine we shall discuss
1530   the reasoning behind this curious mode.
1531
1532 \hang |new_string|, appends the output to the current string in the
1533   string pool.
1534
1535 \hang |>=write_file| prints on one of the files used for the \&{write}
1536 @:write_}{\&{write} primitive@>
1537   command.
1538
1539 \yskip
1540 \noindent The symbolic names `|term_and_log|', etc., have been assigned
1541 numeric codes that satisfy the convenient relations |no_print+1=term_only|,
1542 |no_print+2=log_only|, |term_only+2=log_only+1=term_and_log|.  These
1543 relations are not used when |selector| could be |pseudo|, or |new_string|.
1544 We need not check for unprintable characters when |selector<pseudo|.
1545
1546 Three additional global variables, |tally|, |term_offset| and |file_offset|
1547 record the number of characters that have been printed
1548 since they were most recently cleared to zero. We use |tally| to record
1549 the length of (possibly very long) stretches of printing; |term_offset|,
1550 and |file_offset|, on the other hand, keep track of how many
1551 characters have appeared so far on the current line that has been output
1552 to the terminal, the transcript file, or the \ps\ output file, respectively.
1553
1554 @d new_string 0 /* printing is deflected to the string pool */
1555 @d pseudo 2 /* special |selector| setting for |show_context| */
1556 @d no_print 3 /* |selector| setting that makes data disappear */
1557 @d term_only 4 /* printing is destined for the terminal only */
1558 @d log_only 5 /* printing is destined for the transcript file only */
1559 @d term_and_log 6 /* normal |selector| setting */
1560 @d write_file 7 /* first write file selector */
1561
1562 @<Glob...@>=
1563 void * log_file; /* transcript of \MP\ session */
1564 void * ps_file; /* the generic font output goes here */
1565 unsigned int selector; /* where to print a message */
1566 unsigned char dig[23]; /* digits in a number being output */
1567 integer tally; /* the number of characters recently printed */
1568 unsigned int term_offset;
1569   /* the number of characters on the current terminal line */
1570 unsigned int file_offset;
1571   /* the number of characters on the current file line */
1572 ASCII_code *trick_buf; /* circular buffer for pseudoprinting */
1573 integer trick_count; /* threshold for pseudoprinting, explained later */
1574 integer first_count; /* another variable for pseudoprinting */
1575
1576 @ @<Allocate or initialize ...@>=
1577 memset(mp->dig,0,23);
1578 mp->trick_buf = xmalloc((mp->error_line+1),sizeof(ASCII_code));
1579
1580 @ @<Dealloc variables@>=
1581 xfree(mp->trick_buf);
1582
1583 @ @<Initialize the output routines@>=
1584 mp->selector=term_only; mp->tally=0; mp->term_offset=0; mp->file_offset=0; 
1585
1586 @ Macro abbreviations for output to the terminal and to the log file are
1587 defined here for convenience. Some systems need special conventions
1588 for terminal output, and it is possible to adhere to those conventions
1589 by changing |wterm|, |wterm_ln|, and |wterm_cr| here.
1590 @^system dependencies@>
1591
1592 @d do_fprintf(f,b) (mp->write_ascii_file)(f,b)
1593 @d wterm(A)     do_fprintf(mp->term_out,(A))
1594 @d wterm_chr(A) { unsigned char ss[2]; ss[0]=(A); ss[1]=0; do_fprintf(mp->term_out,(char *)ss); }
1595 @d wterm_cr     do_fprintf(mp->term_out,"\n")
1596 @d wterm_ln(A)  { wterm_cr; do_fprintf(mp->term_out,(A)); }
1597 @d wlog(A)      do_fprintf(mp->log_file,(A))
1598 @d wlog_chr(A)  { unsigned char ss[2]; ss[0]=(A); ss[1]=0; do_fprintf(mp->log_file,(char *)ss); }
1599 @d wlog_cr      do_fprintf(mp->log_file, "\n")
1600 @d wlog_ln(A)   {wlog_cr; do_fprintf(mp->log_file,(A)); }
1601
1602
1603 @ To end a line of text output, we call |print_ln|.  Cases |0..max_write_files|
1604 use an array |wr_file| that will be declared later.
1605
1606 @d mp_print_text(A) mp_print_str(mp,text((A)))
1607
1608 @<Internal ...@>=
1609 void mp_print_ln (MP mp);
1610 void mp_print_visible_char (MP mp, ASCII_code s); 
1611 void mp_print_char (MP mp, ASCII_code k);
1612 void mp_print (MP mp, char *s);
1613 void mp_print_str (MP mp, str_number s);
1614 void mp_print_nl (MP mp, char *s);
1615 void mp_print_two (MP mp,scaled x, scaled y) ;
1616 void mp_print_scaled (MP mp,scaled s);
1617
1618 @ @<Basic print...@>=
1619 void mp_print_ln (MP mp) { /* prints an end-of-line */
1620  switch (mp->selector) {
1621   case term_and_log: 
1622     wterm_cr; wlog_cr;
1623     mp->term_offset=0;  mp->file_offset=0;
1624     break;
1625   case log_only: 
1626     wlog_cr; mp->file_offset=0;
1627     break;
1628   case term_only: 
1629     wterm_cr; mp->term_offset=0;
1630     break;
1631   case no_print:
1632   case pseudo: 
1633   case new_string: 
1634     break;
1635   default: 
1636     do_fprintf(mp->wr_file[(mp->selector-write_file)],"\n");
1637   }
1638 } /* note that |tally| is not affected */
1639
1640 @ The |print_visible_char| procedure sends one character to the desired
1641 destination, using the |xchr| array to map it into an external character
1642 compatible with |input_ln|.  (It assumes that it is always called with
1643 a visible ASCII character.)  All printing comes through |print_ln| or
1644 |print_char|, which ultimately calls |print_visible_char|, hence these
1645 routines are the ones that limit lines to at most |max_print_line| characters.
1646 But we must make an exception for the \ps\ output file since it is not safe
1647 to cut up lines arbitrarily in \ps.
1648
1649 Procedure |unit_str_room| needs to be declared |forward| here because it calls
1650 |do_compaction| and |do_compaction| can call the error routines.  Actually,
1651 |unit_str_room| avoids |overflow| errors but it can call |confusion|.
1652
1653 @<Basic printing...@>=
1654 void mp_print_visible_char (MP mp, ASCII_code s) { /* prints a single character */
1655   switch (mp->selector) {
1656   case term_and_log: 
1657     wterm_chr(xchr(s)); wlog_chr(xchr(s));
1658     incr(mp->term_offset); incr(mp->file_offset);
1659     if ( mp->term_offset==(unsigned)mp->max_print_line ) { 
1660        wterm_cr; mp->term_offset=0;
1661     };
1662     if ( mp->file_offset==(unsigned)mp->max_print_line ) { 
1663        wlog_cr; mp->file_offset=0;
1664     };
1665     break;
1666   case log_only: 
1667     wlog_chr(xchr(s)); incr(mp->file_offset);
1668     if ( mp->file_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1669     break;
1670   case term_only: 
1671     wterm_chr(xchr(s)); incr(mp->term_offset);
1672     if ( mp->term_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1673     break;
1674   case no_print: 
1675     break;
1676   case pseudo: 
1677     if ( mp->tally<mp->trick_count ) 
1678       mp->trick_buf[mp->tally % mp->error_line]=s;
1679     break;
1680   case new_string: 
1681     if ( mp->pool_ptr>=mp->max_pool_ptr ) { 
1682       mp_unit_str_room(mp);
1683       if ( mp->pool_ptr>=mp->pool_size ) 
1684         goto DONE; /* drop characters if string space is full */
1685     };
1686     append_char(s);
1687     break;
1688   default:
1689     { char ss[2]; ss[0] = xchr(s); ss[1]=0;
1690       do_fprintf(mp->wr_file[(mp->selector-write_file)],(char *)ss);
1691     }
1692   }
1693 DONE:
1694   incr(mp->tally);
1695 }
1696
1697 @ The |print_char| procedure sends one character to the desired destination.
1698 File names and string expressions might contain |ASCII_code| values that
1699 can't be printed using |print_visible_char|.  These characters will be
1700 printed in three- or four-symbol form like `\.{\^\^A}' or `\.{\^\^e4}'.
1701 (This procedure assumes that it is safe to bypass all checks for unprintable
1702 characters when |selector| is in the range |0..max_write_files-1|.
1703 The user might want to write unprintable characters.
1704
1705 @d print_lc_hex(A) do { l=(A);
1706     mp_print_visible_char(mp, (l<10 ? l+'0' : l-10+'a'));
1707   } while (0)
1708
1709 @<Basic printing...@>=
1710 void mp_print_char (MP mp, ASCII_code k) { /* prints a single character */
1711   int l; /* small index or counter */
1712   if ( mp->selector<pseudo || mp->selector>=write_file) {
1713     mp_print_visible_char(mp, k);
1714   } else if ( @<Character |k| cannot be printed@> ) { 
1715     mp_print(mp, "^^"); 
1716     if ( k<0100 ) { 
1717       mp_print_visible_char(mp, k+0100); 
1718     } else if ( k<0200 ) { 
1719       mp_print_visible_char(mp, k-0100); 
1720     } else { 
1721       print_lc_hex(k / 16);  
1722       print_lc_hex(k % 16); 
1723     }
1724   } else {
1725     mp_print_visible_char(mp, k);
1726   }
1727 };
1728
1729 @ An entire string is output by calling |print|. Note that if we are outputting
1730 the single standard ASCII character \.c, we could call |print("c")|, since
1731 |"c"=99| is the number of a single-character string, as explained above. But
1732 |print_char("c")| is quicker, so \MP\ goes directly to the |print_char|
1733 routine when it knows that this is safe. (The present implementation
1734 assumes that it is always safe to print a visible ASCII character.)
1735 @^system dependencies@>
1736
1737 @<Basic print...@>=
1738 void mp_do_print (MP mp, char *ss, unsigned int len) { /* prints string |s| */
1739   unsigned int j = 0;
1740   while ( j<len ){ 
1741     mp_print_char(mp, ss[j]); incr(j);
1742   }
1743 }
1744
1745
1746 @<Basic print...@>=
1747 void mp_print (MP mp, char *ss) {
1748   mp_do_print(mp, ss, strlen(ss));
1749 }
1750 void mp_print_str (MP mp, str_number s) {
1751   pool_pointer j; /* current character code position */
1752   if ( (s<0)||(s>mp->max_str_ptr) ) {
1753      mp_do_print(mp,"???",3); /* this can't happen */
1754 @.???@>
1755   }
1756   j=mp->str_start[s];
1757   mp_do_print(mp, (char *)(mp->str_pool+j), (str_stop(s)-j));
1758 }
1759
1760
1761 @ Here is the very first thing that \MP\ prints: a headline that identifies
1762 the version number and base name. The |term_offset| variable is temporarily
1763 incorrect, but the discrepancy is not serious since we assume that the banner
1764 and mem identifier together will occupy at most |max_print_line|
1765 character positions.
1766
1767 @<Initialize the output...@>=
1768 wterm (banner);
1769 wterm (version_string);
1770 if (mp->mem_ident!=NULL) 
1771   mp_print(mp,mp->mem_ident); 
1772 mp_print_ln(mp);
1773 update_terminal;
1774
1775 @ The procedure |print_nl| is like |print|, but it makes sure that the
1776 string appears at the beginning of a new line.
1777
1778 @<Basic print...@>=
1779 void mp_print_nl (MP mp, char *s) { /* prints string |s| at beginning of line */
1780   switch(mp->selector) {
1781   case term_and_log: 
1782     if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_ln(mp);
1783     break;
1784   case log_only: 
1785     if ( mp->file_offset>0 ) mp_print_ln(mp);
1786     break;
1787   case term_only: 
1788     if ( mp->term_offset>0 ) mp_print_ln(mp);
1789     break;
1790   case no_print:
1791   case pseudo:
1792   case new_string: 
1793         break;
1794   } /* there are no other cases */
1795   mp_print(mp, s);
1796 }
1797
1798 @ An array of digits in the range |0..9| is printed by |print_the_digs|.
1799
1800 @<Basic print...@>=
1801 void mp_print_the_digs (MP mp, eight_bits k) {
1802   /* prints |dig[k-1]|$\,\ldots\,$|dig[0]| */
1803   while ( k>0 ){ 
1804     decr(k); mp_print_char(mp, '0'+mp->dig[k]);
1805   }
1806 };
1807
1808 @ The following procedure, which prints out the decimal representation of a
1809 given integer |n|, has been written carefully so that it works properly
1810 if |n=0| or if |(-n)| would cause overflow. It does not apply |%| or |/|
1811 to negative arguments, since such operations are not implemented consistently
1812 on all platforms.
1813
1814 @<Basic print...@>=
1815 void mp_print_int (MP mp,integer n) { /* prints an integer in decimal form */
1816   integer m; /* used to negate |n| in possibly dangerous cases */
1817   int k = 0; /* index to current digit; we assume that $|n|<10^{23}$ */
1818   if ( n<0 ) { 
1819     mp_print_char(mp, '-');
1820     if ( n>-100000000 ) {
1821           negate(n);
1822     } else  { 
1823           m=-1-n; n=m / 10; m=(m % 10)+1; k=1;
1824       if ( m<10 ) {
1825         mp->dig[0]=m;
1826       } else { 
1827         mp->dig[0]=0; incr(n);
1828       }
1829     }
1830   }
1831   do {  
1832     mp->dig[k]=n % 10; n=n / 10; incr(k);
1833   } while (n!=0);
1834   mp_print_the_digs(mp, k);
1835 };
1836
1837 @ @<Internal ...@>=
1838 void mp_print_int (MP mp,integer n);
1839
1840 @ \MP\ also makes use of a trivial procedure to print two digits. The
1841 following subroutine is usually called with a parameter in the range |0<=n<=99|.
1842
1843 @c 
1844 void mp_print_dd (MP mp,integer n) { /* prints two least significant digits */
1845   n=abs(n) % 100; 
1846   mp_print_char(mp, '0'+(n / 10));
1847   mp_print_char(mp, '0'+(n % 10));
1848 }
1849
1850
1851 @ @<Internal ...@>=
1852 void mp_print_dd (MP mp,integer n);
1853
1854 @ Here is a procedure that asks the user to type a line of input,
1855 assuming that the |selector| setting is either |term_only| or |term_and_log|.
1856 The input is placed into locations |first| through |last-1| of the
1857 |buffer| array, and echoed on the transcript file if appropriate.
1858
1859 This procedure is never called when |interaction<mp_scroll_mode|.
1860
1861 @d prompt_input(A) do { 
1862     wake_up_terminal; mp_print(mp, (A)); mp_term_input(mp);
1863   } while (0) /* prints a string and gets a line of input */
1864
1865 @c 
1866 void mp_term_input (MP mp) { /* gets a line from the terminal */
1867   size_t k; /* index into |buffer| */
1868   update_terminal; /* Now the user sees the prompt for sure */
1869   if (!mp_input_ln(mp, mp->term_in )) 
1870     mp_fatal_error(mp, "End of file on the terminal!");
1871 @.End of file on the terminal@>
1872   mp->term_offset=0; /* the user's line ended with \<\rm return> */
1873   decr(mp->selector); /* prepare to echo the input */
1874   if ( mp->last!=mp->first ) {
1875     for (k=mp->first;k<=mp->last-1;k++) {
1876       mp_print_char(mp, mp->buffer[k]);
1877     }
1878   }
1879   mp_print_ln(mp); 
1880   mp->buffer[mp->last]='%'; 
1881   incr(mp->selector); /* restore previous status */
1882 };
1883
1884 @* \[6] Reporting errors.
1885 When something anomalous is detected, \MP\ typically does something like this:
1886 $$\vbox{\halign{#\hfil\cr
1887 |print_err("Something anomalous has been detected");|\cr
1888 |help3("This is the first line of my offer to help.")|\cr
1889 |("This is the second line. I'm trying to")|\cr
1890 |("explain the best way for you to proceed.");|\cr
1891 |error;|\cr}}$$
1892 A two-line help message would be given using |help2|, etc.; these informal
1893 helps should use simple vocabulary that complements the words used in the
1894 official error message that was printed. (Outside the U.S.A., the help
1895 messages should preferably be translated into the local vernacular. Each
1896 line of help is at most 60 characters long, in the present implementation,
1897 so that |max_print_line| will not be exceeded.)
1898
1899 The |print_err| procedure supplies a `\.!' before the official message,
1900 and makes sure that the terminal is awake if a stop is going to occur.
1901 The |error| procedure supplies a `\..' after the official message, then it
1902 shows the location of the error; and if |interaction=error_stop_mode|,
1903 it also enters into a dialog with the user, during which time the help
1904 message may be printed.
1905 @^system dependencies@>
1906
1907 @ The global variable |interaction| has four settings, representing increasing
1908 amounts of user interaction:
1909
1910 @<Exported types@>=
1911 enum mp_interaction_mode { 
1912  mp_unspecified_mode=0, /* extra value for command-line switch */
1913  mp_batch_mode, /* omits all stops and omits terminal output */
1914  mp_nonstop_mode, /* omits all stops */
1915  mp_scroll_mode, /* omits error stops */
1916  mp_error_stop_mode, /* stops at every opportunity to interact */
1917 };
1918
1919 @ @<Option variables@>=
1920 int interaction; /* current level of interaction */
1921
1922 @ Set it here so it can be overwritten by the commandline
1923
1924 @<Allocate or initialize ...@>=
1925 mp->interaction=opt->interaction;
1926 if (mp->interaction==mp_unspecified_mode || mp->interaction>mp_error_stop_mode) 
1927   mp->interaction=mp_error_stop_mode;
1928 if (mp->interaction<mp_unspecified_mode) 
1929   mp->interaction=mp_batch_mode;
1930
1931
1932
1933 @d print_err(A) mp_print_err(mp,(A))
1934
1935 @<Internal ...@>=
1936 void mp_print_err(MP mp, char * A);
1937
1938 @ @c
1939 void mp_print_err(MP mp, char * A) { 
1940   if ( mp->interaction==mp_error_stop_mode ) 
1941     wake_up_terminal;
1942   mp_print_nl(mp, "! "); 
1943   mp_print(mp, A);
1944 @.!\relax@>
1945 }
1946
1947
1948 @ \MP\ is careful not to call |error| when the print |selector| setting
1949 might be unusual. The only possible values of |selector| at the time of
1950 error messages are
1951
1952 \yskip\hang|no_print| (when |interaction=mp_batch_mode|
1953   and |log_file| not yet open);
1954
1955 \hang|term_only| (when |interaction>mp_batch_mode| and |log_file| not yet open);
1956
1957 \hang|log_only| (when |interaction=mp_batch_mode| and |log_file| is open);
1958
1959 \hang|term_and_log| (when |interaction>mp_batch_mode| and |log_file| is open).
1960
1961 @<Initialize the print |selector| based on |interaction|@>=
1962 if ( mp->interaction==mp_batch_mode ) mp->selector=no_print; else mp->selector=term_only
1963
1964 @ A global variable |deletions_allowed| is set |false| if the |get_next|
1965 routine is active when |error| is called; this ensures that |get_next|
1966 will never be called recursively.
1967 @^recursion@>
1968
1969 The global variable |history| records the worst level of error that
1970 has been detected. It has four possible values: |spotless|, |warning_issued|,
1971 |error_message_issued|, and |fatal_error_stop|.
1972
1973 Another global variable, |error_count|, is increased by one when an
1974 |error| occurs without an interactive dialog, and it is reset to zero at
1975 the end of every statement.  If |error_count| reaches 100, \MP\ decides
1976 that there is no point in continuing further.
1977
1978 @<Types...@>=
1979 enum mp_history_states {
1980   mp_spotless=0, /* |history| value when nothing has been amiss yet */
1981   mp_warning_issued, /* |history| value when |begin_diagnostic| has been called */
1982   mp_error_message_issued, /* |history| value when |error| has been called */
1983   mp_fatal_error_stop, /* |history| value when termination was premature */
1984 };
1985
1986 @ @<Glob...@>=
1987 boolean deletions_allowed; /* is it safe for |error| to call |get_next|? */
1988 int history; /* has the source input been clean so far? */
1989 int error_count; /* the number of scrolled errors since the last statement ended */
1990
1991 @ The value of |history| is initially |fatal_error_stop|, but it will
1992 be changed to |spotless| if \MP\ survives the initialization process.
1993
1994 @<Allocate or ...@>=
1995 mp->deletions_allowed=true; mp->error_count=0; /* |history| is initialized elsewhere */
1996
1997 @ Since errors can be detected almost anywhere in \MP, we want to declare the
1998 error procedures near the beginning of the program. But the error procedures
1999 in turn use some other procedures, which need to be declared |forward|
2000 before we get to |error| itself.
2001
2002 It is possible for |error| to be called recursively if some error arises
2003 when |get_next| is being used to delete a token, and/or if some fatal error
2004 occurs while \MP\ is trying to fix a non-fatal one. But such recursion
2005 @^recursion@>
2006 is never more than two levels deep.
2007
2008 @<Declarations@>=
2009 void mp_get_next (MP mp);
2010 void mp_term_input (MP mp);
2011 void mp_show_context (MP mp);
2012 void mp_begin_file_reading (MP mp);
2013 void mp_open_log_file (MP mp);
2014 void mp_clear_for_error_prompt (MP mp);
2015 void mp_debug_help (MP mp);
2016 @<Declare the procedure called |flush_string|@>
2017
2018 @ @<Internal ...@>=
2019 void mp_normalize_selector (MP mp);
2020
2021 @ Individual lines of help are recorded in the array |help_line|, which
2022 contains entries in positions |0..(help_ptr-1)|. They should be printed
2023 in reverse order, i.e., with |help_line[0]| appearing last.
2024
2025 @d hlp1(A) mp->help_line[0]=(A); }
2026 @d hlp2(A) mp->help_line[1]=(A); hlp1
2027 @d hlp3(A) mp->help_line[2]=(A); hlp2
2028 @d hlp4(A) mp->help_line[3]=(A); hlp3
2029 @d hlp5(A) mp->help_line[4]=(A); hlp4
2030 @d hlp6(A) mp->help_line[5]=(A); hlp5
2031 @d help0 mp->help_ptr=0 /* sometimes there might be no help */
2032 @d help1  { mp->help_ptr=1; hlp1 /* use this with one help line */
2033 @d help2  { mp->help_ptr=2; hlp2 /* use this with two help lines */
2034 @d help3  { mp->help_ptr=3; hlp3 /* use this with three help lines */
2035 @d help4  { mp->help_ptr=4; hlp4 /* use this with four help lines */
2036 @d help5  { mp->help_ptr=5; hlp5 /* use this with five help lines */
2037 @d help6  { mp->help_ptr=6; hlp6 /* use this with six help lines */
2038
2039 @<Glob...@>=
2040 char * help_line[6]; /* helps for the next |error| */
2041 unsigned int help_ptr; /* the number of help lines present */
2042 boolean use_err_help; /* should the |err_help| string be shown? */
2043 str_number err_help; /* a string set up by \&{errhelp} */
2044 str_number filename_template; /* a string set up by \&{filenametemplate} */
2045
2046 @ @<Allocate or ...@>=
2047 mp->help_ptr=0; mp->use_err_help=false; mp->err_help=0; mp->filename_template=0;
2048
2049 @ The |jump_out| procedure just cuts across all active procedure levels and
2050 goes to |end_of_MP|. This is the only nonlocal |goto| statement in the
2051 whole program. It is used when there is no recovery from a particular error.
2052
2053 The program uses a |jump_buf| to handle this, this is initialized at three
2054 spots: the start of |mp_new|, the start of |mp_initialize|, and the start 
2055 of |mp_run|. Those are the only library enty points.
2056
2057 @^system dependencies@>
2058
2059 @<Glob...@>=
2060 jmp_buf jump_buf;
2061
2062 @ @<Install and test the non-local jump buffer@>=
2063 if (setjmp(mp->jump_buf) != 0) return mp->history;
2064
2065 @ @<Setup the non-local jump buffer in |mp_new|@>=
2066 if (setjmp(mp->jump_buf) != 0) return NULL;
2067
2068 @ If the array of internals is still |NULL| when |jump_out| is called, a
2069 crash occured during initialization, and it is not safe to run the normal
2070 cleanup routine.
2071
2072 @<Error hand...@>=
2073 void mp_jump_out (MP mp) { 
2074   if(mp->internal!=NULL)
2075     mp_close_files_and_terminate(mp);
2076   longjmp(mp->jump_buf,1);
2077 }
2078
2079 @ Here now is the general |error| routine.
2080
2081 @<Error hand...@>=
2082 void mp_error (MP mp) { /* completes the job of error reporting */
2083   ASCII_code c; /* what the user types */
2084   integer s1,s2,s3; /* used to save global variables when deleting tokens */
2085   pool_pointer j; /* character position being printed */
2086   if ( mp->history<mp_error_message_issued ) mp->history=mp_error_message_issued;
2087   mp_print_char(mp, '.'); mp_show_context(mp);
2088   if ( mp->interaction==mp_error_stop_mode ) {
2089     @<Get user's advice and |return|@>;
2090   }
2091   incr(mp->error_count);
2092   if ( mp->error_count==100 ) { 
2093     mp_print_nl(mp,"(That makes 100 errors; please try again.)");
2094 @.That makes 100 errors...@>
2095     mp->history=mp_fatal_error_stop; mp_jump_out(mp);
2096   }
2097   @<Put help message on the transcript file@>;
2098 }
2099 void mp_warn (MP mp, char *msg) {
2100   int saved_selector = mp->selector;
2101   mp_normalize_selector(mp);
2102   mp_print_nl(mp,"Warning: ");
2103   mp_print(mp,msg);
2104   mp->selector = saved_selector;
2105 }
2106
2107 @ @<Exported function ...@>=
2108 void mp_error (MP mp);
2109 void mp_warn (MP mp, char *msg);
2110
2111
2112 @ @<Get user's advice...@>=
2113 while (1) { 
2114 CONTINUE:
2115   mp_clear_for_error_prompt(mp); prompt_input("? ");
2116 @.?\relax@>
2117   if ( mp->last==mp->first ) return;
2118   c=mp->buffer[mp->first];
2119   if ( c>='a' ) c=c+'A'-'a'; /* convert to uppercase */
2120   @<Interpret code |c| and |return| if done@>;
2121 }
2122
2123 @ It is desirable to provide an `\.E' option here that gives the user
2124 an easy way to return from \MP\ to the system editor, with the offending
2125 line ready to be edited. But such an extension requires some system
2126 wizardry, so the present implementation simply types out the name of the
2127 file that should be
2128 edited and the relevant line number.
2129 @^system dependencies@>
2130
2131 @<Exported types@>=
2132 typedef void (*mp_run_editor_command)(MP, char *, int);
2133
2134 @ @<Option variables@>=
2135 mp_run_editor_command run_editor;
2136
2137 @ @<Allocate or initialize ...@>=
2138 set_callback_option(run_editor);
2139
2140 @ @<Declarations@>=
2141 void mp_run_editor (MP mp, char *fname, int fline);
2142
2143 @ @c void mp_run_editor (MP mp, char *fname, int fline) {
2144     mp_print_nl(mp, "You want to edit file ");
2145 @.You want to edit file x@>
2146     mp_print(mp, fname);
2147     mp_print(mp, " at line "); 
2148     mp_print_int(mp, fline);
2149     mp->interaction=mp_scroll_mode; 
2150     mp_jump_out(mp);
2151 }
2152
2153
2154 There is a secret `\.D' option available when the debugging routines haven't
2155 been commented~out.
2156 @^debugging@>
2157
2158 @<Interpret code |c| and |return| if done@>=
2159 switch (c) {
2160 case '0': case '1': case '2': case '3': case '4':
2161 case '5': case '6': case '7': case '8': case '9': 
2162   if ( mp->deletions_allowed ) {
2163     @<Delete |c-"0"| tokens and |continue|@>;
2164   }
2165   break;
2166 #ifdef DEBUG
2167 case 'D': 
2168   mp_debug_help(mp); continue; 
2169   break;
2170 #endif
2171 case 'E': 
2172   if ( mp->file_ptr>0 ){ 
2173     (mp->run_editor)(mp, 
2174                      str(mp->input_stack[mp->file_ptr].name_field), 
2175                      mp_true_line(mp));
2176   }
2177   break;
2178 case 'H': 
2179   @<Print the help information and |continue|@>;
2180   break;
2181 case 'I':
2182   @<Introduce new material from the terminal and |return|@>;
2183   break;
2184 case 'Q': case 'R': case 'S':
2185   @<Change the interaction level and |return|@>;
2186   break;
2187 case 'X':
2188   mp->interaction=mp_scroll_mode; mp_jump_out(mp);
2189   break;
2190 default:
2191   break;
2192 }
2193 @<Print the menu of available options@>
2194
2195 @ @<Print the menu...@>=
2196
2197   mp_print(mp, "Type <return> to proceed, S to scroll future error messages,");
2198 @.Type <return> to proceed...@>
2199   mp_print_nl(mp, "R to run without stopping, Q to run quietly,");
2200   mp_print_nl(mp, "I to insert something, ");
2201   if ( mp->file_ptr>0 ) 
2202     mp_print(mp, "E to edit your file,");
2203   if ( mp->deletions_allowed )
2204     mp_print_nl(mp, "1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
2205   mp_print_nl(mp, "H for help, X to quit.");
2206 }
2207
2208 @ Here the author of \MP\ apologizes for making use of the numerical
2209 relation between |"Q"|, |"R"|, |"S"|, and the desired interaction settings
2210 |mp_batch_mode|, |mp_nonstop_mode|, |mp_scroll_mode|.
2211 @^Knuth, Donald Ervin@>
2212
2213 @<Change the interaction...@>=
2214
2215   mp->error_count=0; mp->interaction=mp_batch_mode+c-'Q';
2216   mp_print(mp, "OK, entering ");
2217   switch (c) {
2218   case 'Q': mp_print(mp, "batchmode"); decr(mp->selector); break;
2219   case 'R': mp_print(mp, "nonstopmode"); break;
2220   case 'S': mp_print(mp, "scrollmode"); break;
2221   } /* there are no other cases */
2222   mp_print(mp, "..."); mp_print_ln(mp); update_terminal; return;
2223 }
2224
2225 @ When the following code is executed, |buffer[(first+1)..(last-1)]| may
2226 contain the material inserted by the user; otherwise another prompt will
2227 be given. In order to understand this part of the program fully, you need
2228 to be familiar with \MP's input stacks.
2229
2230 @<Introduce new material...@>=
2231
2232   mp_begin_file_reading(mp); /* enter a new syntactic level for terminal input */
2233   if ( mp->last>mp->first+1 ) { 
2234     loc=mp->first+1; mp->buffer[mp->first]=' ';
2235   } else { 
2236    prompt_input("insert>"); loc=mp->first;
2237 @.insert>@>
2238   };
2239   mp->first=mp->last+1; mp->cur_input.limit_field=mp->last; return;
2240 }
2241
2242 @ We allow deletion of up to 99 tokens at a time.
2243
2244 @<Delete |c-"0"| tokens...@>=
2245
2246   s1=mp->cur_cmd; s2=mp->cur_mod; s3=mp->cur_sym; mp->OK_to_interrupt=false;
2247   if ( (mp->last>mp->first+1) && (mp->buffer[mp->first+1]>='0')&&(mp->buffer[mp->first+1]<='9') )
2248     c=c*10+mp->buffer[mp->first+1]-'0'*11;
2249   else 
2250     c=c-'0';
2251   while ( c>0 ) { 
2252     mp_get_next(mp); /* one-level recursive call of |error| is possible */
2253     @<Decrease the string reference count, if the current token is a string@>;
2254     decr(c);
2255   };
2256   mp->cur_cmd=s1; mp->cur_mod=s2; mp->cur_sym=s3; mp->OK_to_interrupt=true;
2257   help2("I have just deleted some text, as you asked.")
2258        ("You can now delete more, or insert, or whatever.");
2259   mp_show_context(mp); 
2260   goto CONTINUE;
2261 }
2262
2263 @ @<Print the help info...@>=
2264
2265   if ( mp->use_err_help ) { 
2266     @<Print the string |err_help|, possibly on several lines@>;
2267     mp->use_err_help=false;
2268   } else { 
2269     if ( mp->help_ptr==0 ) {
2270       help2("Sorry, I don't know how to help in this situation.")
2271            ("Maybe you should try asking a human?");
2272      }
2273     do { 
2274       decr(mp->help_ptr); mp_print(mp, mp->help_line[mp->help_ptr]); mp_print_ln(mp);
2275     } while (mp->help_ptr!=0);
2276   };
2277   help4("Sorry, I already gave what help I could...")
2278        ("Maybe you should try asking a human?")
2279        ("An error might have occurred before I noticed any problems.")
2280        ("``If all else fails, read the instructions.''");
2281   goto CONTINUE;
2282 }
2283
2284 @ @<Print the string |err_help|, possibly on several lines@>=
2285 j=mp->str_start[mp->err_help];
2286 while ( j<str_stop(mp->err_help) ) { 
2287   if ( mp->str_pool[j]!='%' ) mp_print_str(mp, mp->str_pool[j]);
2288   else if ( j+1==str_stop(mp->err_help) ) mp_print_ln(mp);
2289   else if ( mp->str_pool[j+1]!='%' ) mp_print_ln(mp);
2290   else  { incr(j); mp_print_char(mp, '%'); };
2291   incr(j);
2292 }
2293
2294 @ @<Put help message on the transcript file@>=
2295 if ( mp->interaction>mp_batch_mode ) decr(mp->selector); /* avoid terminal output */
2296 if ( mp->use_err_help ) { 
2297   mp_print_nl(mp, "");
2298   @<Print the string |err_help|, possibly on several lines@>;
2299 } else { 
2300   while ( mp->help_ptr>0 ){ 
2301     decr(mp->help_ptr); mp_print_nl(mp, mp->help_line[mp->help_ptr]);
2302   };
2303 }
2304 mp_print_ln(mp);
2305 if ( mp->interaction>mp_batch_mode ) incr(mp->selector); /* re-enable terminal output */
2306 mp_print_ln(mp)
2307
2308 @ In anomalous cases, the print selector might be in an unknown state;
2309 the following subroutine is called to fix things just enough to keep
2310 running a bit longer.
2311
2312 @c 
2313 void mp_normalize_selector (MP mp) { 
2314   if ( mp->log_opened ) mp->selector=term_and_log;
2315   else mp->selector=term_only;
2316   if ( mp->job_name==NULL ) mp_open_log_file(mp);
2317   if ( mp->interaction==mp_batch_mode ) decr(mp->selector);
2318 }
2319
2320 @ The following procedure prints \MP's last words before dying.
2321
2322 @d succumb { if ( mp->interaction==mp_error_stop_mode )
2323     mp->interaction=mp_scroll_mode; /* no more interaction */
2324   if ( mp->log_opened ) mp_error(mp);
2325   /*| if ( mp->interaction>mp_batch_mode ) mp_debug_help(mp); |*/
2326   mp->history=mp_fatal_error_stop; mp_jump_out(mp); /* irrecoverable error */
2327   }
2328
2329 @<Error hand...@>=
2330 void mp_fatal_error (MP mp, char *s) { /* prints |s|, and that's it */
2331   mp_normalize_selector(mp);
2332   print_err("Emergency stop"); help1(s); succumb;
2333 @.Emergency stop@>
2334 }
2335
2336 @ @<Exported function ...@>=
2337 void mp_fatal_error (MP mp, char *s);
2338
2339
2340 @ Here is the most dreaded error message.
2341
2342 @<Error hand...@>=
2343 void mp_overflow (MP mp, char *s, integer n) { /* stop due to finiteness */
2344   mp_normalize_selector(mp);
2345   print_err("MetaPost capacity exceeded, sorry [");
2346 @.MetaPost capacity exceeded ...@>
2347   mp_print(mp, s); mp_print_char(mp, '='); mp_print_int(mp, n); mp_print_char(mp, ']');
2348   help2("If you really absolutely need more capacity,")
2349        ("you can ask a wizard to enlarge me.");
2350   succumb;
2351 }
2352
2353 @ @<Internal library declarations@>=
2354 void mp_overflow (MP mp, char *s, integer n);
2355
2356 @ The program might sometime run completely amok, at which point there is
2357 no choice but to stop. If no previous error has been detected, that's bad
2358 news; a message is printed that is really intended for the \MP\
2359 maintenance person instead of the user (unless the user has been
2360 particularly diabolical).  The index entries for `this can't happen' may
2361 help to pinpoint the problem.
2362 @^dry rot@>
2363
2364 @<Internal library ...@>=
2365 void mp_confusion (MP mp,char *s);
2366
2367 @ @<Error hand...@>=
2368 void mp_confusion (MP mp,char *s) {
2369   /* consistency check violated; |s| tells where */
2370   mp_normalize_selector(mp);
2371   if ( mp->history<mp_error_message_issued ) { 
2372     print_err("This can't happen ("); mp_print(mp, s); mp_print_char(mp, ')');
2373 @.This can't happen@>
2374     help1("I'm broken. Please show this to someone who can fix can fix");
2375   } else { 
2376     print_err("I can\'t go on meeting you like this");
2377 @.I can't go on...@>
2378     help2("One of your faux pas seems to have wounded me deeply...")
2379          ("in fact, I'm barely conscious. Please fix it and try again.");
2380   }
2381   succumb;
2382 }
2383
2384 @ Users occasionally want to interrupt \MP\ while it's running.
2385 If the runtime system allows this, one can implement
2386 a routine that sets the global variable |interrupt| to some nonzero value
2387 when such an interrupt is signaled. Otherwise there is probably at least
2388 a way to make |interrupt| nonzero using the C debugger.
2389 @^system dependencies@>
2390 @^debugging@>
2391
2392 @d check_interrupt { if ( mp->interrupt!=0 )
2393    mp_pause_for_instructions(mp); }
2394
2395 @<Global...@>=
2396 integer interrupt; /* should \MP\ pause for instructions? */
2397 boolean OK_to_interrupt; /* should interrupts be observed? */
2398
2399 @ @<Allocate or ...@>=
2400 mp->interrupt=0; mp->OK_to_interrupt=true;
2401
2402 @ When an interrupt has been detected, the program goes into its
2403 highest interaction level and lets the user have the full flexibility of
2404 the |error| routine.  \MP\ checks for interrupts only at times when it is
2405 safe to do this.
2406
2407 @c 
2408 void mp_pause_for_instructions (MP mp) { 
2409   if ( mp->OK_to_interrupt ) { 
2410     mp->interaction=mp_error_stop_mode;
2411     if ( (mp->selector==log_only)||(mp->selector==no_print) )
2412       incr(mp->selector);
2413     print_err("Interruption");
2414 @.Interruption@>
2415     help3("You rang?")
2416          ("Try to insert some instructions for me (e.g.,`I show x'),")
2417          ("unless you just want to quit by typing `X'.");
2418     mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
2419     mp->interrupt=0;
2420   }
2421 }
2422
2423 @ Many of \MP's error messages state that a missing token has been
2424 inserted behind the scenes. We can save string space and program space
2425 by putting this common code into a subroutine.
2426
2427 @c 
2428 void mp_missing_err (MP mp, char *s) { 
2429   print_err("Missing `"); mp_print(mp, s); mp_print(mp, "' has been inserted");
2430 @.Missing...inserted@>
2431 }
2432
2433 @* \[7] Arithmetic with scaled numbers.
2434 The principal computations performed by \MP\ are done entirely in terms of
2435 integers less than $2^{31}$ in magnitude; thus, the arithmetic specified in this
2436 program can be carried out in exactly the same way on a wide variety of
2437 computers, including some small ones.
2438 @^small computers@>
2439
2440 But C does not rigidly define the |/| operation in the case of negative
2441 dividends; for example, the result of |(-2*n-1) / 2| is |-(n+1)| on some
2442 computers and |-n| on others (is this true ?).  There are two principal
2443 types of arithmetic: ``translation-preserving,'' in which the identity
2444 |(a+q*b)/b=(a/b)+q| is valid; and ``negation-preserving,'' in which
2445 |(-a)/b=-(a/b)|. This leads to two \MP s, which can produce
2446 different results, although the differences should be negligible when the
2447 language is being used properly.  The \TeX\ processor has been defined
2448 carefully so that both varieties of arithmetic will produce identical
2449 output, but it would be too inefficient to constrain \MP\ in a similar way.
2450
2451 @d el_gordo   017777777777 /* $2^{31}-1$, the largest value that \MP\ likes */
2452
2453 @ One of \MP's most common operations is the calculation of
2454 $\lfloor{a+b\over2}\rfloor$,
2455 the midpoint of two given integers |a| and~|b|. The most decent way to do
2456 this is to write `|(a+b)/2|'; but on many machines it is more efficient 
2457 to calculate `|(a+b)>>1|'.
2458
2459 Therefore the midpoint operation will always be denoted by `|half(a+b)|'
2460 in this program. If \MP\ is being implemented with languages that permit
2461 binary shifting, the |half| macro should be changed to make this operation
2462 as efficient as possible.  Since some systems have shift operators that can
2463 only be trusted to work on positive numbers, there is also a macro |halfp|
2464 that is used only when the quantity being halved is known to be positive
2465 or zero.
2466
2467 @d half(A) ((A) / 2)
2468 @d halfp(A) ((A) >> 1)
2469
2470 @ A single computation might use several subroutine calls, and it is
2471 desirable to avoid producing multiple error messages in case of arithmetic
2472 overflow. So the routines below set the global variable |arith_error| to |true|
2473 instead of reporting errors directly to the user.
2474
2475 @<Glob...@>=
2476 boolean arith_error; /* has arithmetic overflow occurred recently? */
2477
2478 @ @<Allocate or ...@>=
2479 mp->arith_error=false;
2480
2481 @ At crucial points the program will say |check_arith|, to test if
2482 an arithmetic error has been detected.
2483
2484 @d check_arith { if ( mp->arith_error ) mp_clear_arith(mp); }
2485
2486 @c 
2487 void mp_clear_arith (MP mp) { 
2488   print_err("Arithmetic overflow");
2489 @.Arithmetic overflow@>
2490   help4("Uh, oh. A little while ago one of the quantities that I was")
2491        ("computing got too large, so I'm afraid your answers will be")
2492        ("somewhat askew. You'll probably have to adopt different")
2493        ("tactics next time. But I shall try to carry on anyway.");
2494   mp_error(mp); 
2495   mp->arith_error=false;
2496 }
2497
2498 @ Addition is not always checked to make sure that it doesn't overflow,
2499 but in places where overflow isn't too unlikely the |slow_add| routine
2500 is used.
2501
2502 @c integer mp_slow_add (MP mp,integer x, integer y) { 
2503   if ( x>=0 )  {
2504     if ( y<=el_gordo-x ) { 
2505       return x+y;
2506     } else  { 
2507       mp->arith_error=true; 
2508           return el_gordo;
2509     }
2510   } else  if ( -y<=el_gordo+x ) {
2511     return x+y;
2512   } else { 
2513     mp->arith_error=true; 
2514         return -el_gordo;
2515   }
2516 }
2517
2518 @ Fixed-point arithmetic is done on {\sl scaled integers\/} that are multiples
2519 of $2^{-16}$. In other words, a binary point is assumed to be sixteen bit
2520 positions from the right end of a binary computer word.
2521
2522 @d quarter_unit   040000 /* $2^{14}$, represents 0.250000 */
2523 @d half_unit   0100000 /* $2^{15}$, represents 0.50000 */
2524 @d three_quarter_unit   0140000 /* $3\cdot2^{14}$, represents 0.75000 */
2525 @d unity   0200000 /* $2^{16}$, represents 1.00000 */
2526 @d two   0400000 /* $2^{17}$, represents 2.00000 */
2527 @d three   0600000 /* $2^{17}+2^{16}$, represents 3.00000 */
2528
2529 @<Types...@>=
2530 typedef integer scaled; /* this type is used for scaled integers */
2531 typedef unsigned char small_number; /* this type is self-explanatory */
2532
2533 @ The following function is used to create a scaled integer from a given decimal
2534 fraction $(.d_0d_1\ldots d_{k-1})$, where |0<=k<=17|. The digit $d_i$ is
2535 given in |dig[i]|, and the calculation produces a correctly rounded result.
2536
2537 @c 
2538 scaled mp_round_decimals (MP mp,small_number k) {
2539   /* converts a decimal fraction */
2540  integer a = 0; /* the accumulator */
2541  while ( k-->0 ) { 
2542     a=(a+mp->dig[k]*two) / 10;
2543   }
2544   return halfp(a+1);
2545 }
2546
2547 @ Conversely, here is a procedure analogous to |print_int|. If the output
2548 of this procedure is subsequently read by \MP\ and converted by the
2549 |round_decimals| routine above, it turns out that the original value will
2550 be reproduced exactly. A decimal point is printed only if the value is
2551 not an integer. If there is more than one way to print the result with
2552 the optimum number of digits following the decimal point, the closest
2553 possible value is given.
2554
2555 The invariant relation in the \&{repeat} loop is that a sequence of
2556 decimal digits yet to be printed will yield the original number if and only if
2557 they form a fraction~$f$ in the range $s-\delta\L10\cdot2^{16}f<s$.
2558 We can stop if and only if $f=0$ satisfies this condition; the loop will
2559 terminate before $s$ can possibly become zero.
2560
2561 @<Basic printing...@>=
2562 void mp_print_scaled (MP mp,scaled s) { /* prints scaled real, rounded to five  digits */
2563   scaled delta; /* amount of allowable inaccuracy */
2564   if ( s<0 ) { 
2565         mp_print_char(mp, '-'); 
2566     negate(s); /* print the sign, if negative */
2567   }
2568   mp_print_int(mp, s / unity); /* print the integer part */
2569   s=10*(s % unity)+5;
2570   if ( s!=5 ) { 
2571     delta=10; 
2572     mp_print_char(mp, '.');
2573     do {  
2574       if ( delta>unity )
2575         s=s+0100000-(delta / 2); /* round the final digit */
2576       mp_print_char(mp, '0'+(s / unity)); 
2577       s=10*(s % unity); 
2578       delta=delta*10;
2579     } while (s>delta);
2580   }
2581 }
2582
2583 @ We often want to print two scaled quantities in parentheses,
2584 separated by a comma.
2585
2586 @<Basic printing...@>=
2587 void mp_print_two (MP mp,scaled x, scaled y) { /* prints `|(x,y)|' */
2588   mp_print_char(mp, '('); 
2589   mp_print_scaled(mp, x); 
2590   mp_print_char(mp, ','); 
2591   mp_print_scaled(mp, y);
2592   mp_print_char(mp, ')');
2593 }
2594
2595 @ The |scaled| quantities in \MP\ programs are generally supposed to be
2596 less than $2^{12}$ in absolute value, so \MP\ does much of its internal
2597 arithmetic with 28~significant bits of precision. A |fraction| denotes
2598 a scaled integer whose binary point is assumed to be 28 bit positions
2599 from the right.
2600
2601 @d fraction_half 01000000000 /* $2^{27}$, represents 0.50000000 */
2602 @d fraction_one 02000000000 /* $2^{28}$, represents 1.00000000 */
2603 @d fraction_two 04000000000 /* $2^{29}$, represents 2.00000000 */
2604 @d fraction_three 06000000000 /* $3\cdot2^{28}$, represents 3.00000000 */
2605 @d fraction_four 010000000000 /* $2^{30}$, represents 4.00000000 */
2606
2607 @<Types...@>=
2608 typedef integer fraction; /* this type is used for scaled fractions */
2609
2610 @ In fact, the two sorts of scaling discussed above aren't quite
2611 sufficient; \MP\ has yet another, used internally to keep track of angles
2612 in units of $2^{-20}$ degrees.
2613
2614 @d forty_five_deg 0264000000 /* $45\cdot2^{20}$, represents $45^\circ$ */
2615 @d ninety_deg 0550000000 /* $90\cdot2^{20}$, represents $90^\circ$ */
2616 @d one_eighty_deg 01320000000 /* $180\cdot2^{20}$, represents $180^\circ$ */
2617 @d three_sixty_deg 02640000000 /* $360\cdot2^{20}$, represents $360^\circ$ */
2618
2619 @<Types...@>=
2620 typedef integer angle; /* this type is used for scaled angles */
2621
2622 @ The |make_fraction| routine produces the |fraction| equivalent of
2623 |p/q|, given integers |p| and~|q|; it computes the integer
2624 $f=\lfloor2^{28}p/q+{1\over2}\rfloor$, when $p$ and $q$ are
2625 positive. If |p| and |q| are both of the same scaled type |t|,
2626 the ``type relation'' |make_fraction(t,t)=fraction| is valid;
2627 and it's also possible to use the subroutine ``backwards,'' using
2628 the relation |make_fraction(t,fraction)=t| between scaled types.
2629
2630 If the result would have magnitude $2^{31}$ or more, |make_fraction|
2631 sets |arith_error:=true|. Most of \MP's internal computations have
2632 been designed to avoid this sort of error.
2633
2634 If this subroutine were programmed in assembly language on a typical
2635 machine, we could simply compute |(@t$2^{28}$@>*p)div q|, since a
2636 double-precision product can often be input to a fixed-point division
2637 instruction. But when we are restricted to int-eger arithmetic it
2638 is necessary either to resort to multiple-precision maneuvering
2639 or to use a simple but slow iteration. The multiple-precision technique
2640 would be about three times faster than the code adopted here, but it
2641 would be comparatively long and tricky, involving about sixteen
2642 additional multiplications and divisions.
2643
2644 This operation is part of \MP's ``inner loop''; indeed, it will
2645 consume nearly 10\pct! of the running time (exclusive of input and output)
2646 if the code below is left unchanged. A machine-dependent recoding
2647 will therefore make \MP\ run faster. The present implementation
2648 is highly portable, but slow; it avoids multiplication and division
2649 except in the initial stage. System wizards should be careful to
2650 replace it with a routine that is guaranteed to produce identical
2651 results in all cases.
2652 @^system dependencies@>
2653
2654 As noted below, a few more routines should also be replaced by machine-dependent
2655 code, for efficiency. But when a procedure is not part of the ``inner loop,''
2656 such changes aren't advisable; simplicity and robustness are
2657 preferable to trickery, unless the cost is too high.
2658 @^inner loop@>
2659
2660 @<Internal ...@>=
2661 fraction mp_make_fraction (MP mp,integer p, integer q);
2662 integer mp_take_scaled (MP mp,integer q, scaled f) ;
2663
2664 @ If FIXPT is not defined, we need these preprocessor values
2665
2666 @d ELGORDO  0x7fffffff
2667 @d TWEXP31  2147483648.0
2668 @d TWEXP28  268435456.0
2669 @d TWEXP16 65536.0
2670 @d TWEXP_16 (1.0/65536.0)
2671 @d TWEXP_28 (1.0/268435456.0)
2672
2673
2674 @c 
2675 fraction mp_make_fraction (MP mp,integer p, integer q) {
2676 #ifdef FIXPT
2677   integer f; /* the fraction bits, with a leading 1 bit */
2678   integer n; /* the integer part of $\vert p/q\vert$ */
2679   integer be_careful; /* disables certain compiler optimizations */
2680   boolean negative = false; /* should the result be negated? */
2681   if ( p<0 ) {
2682     negate(p); negative=true;
2683   }
2684   if ( q<=0 ) { 
2685 #ifdef DEBUG
2686     if ( q==0 ) mp_confusion(mp, '/');
2687 #endif
2688 @:this can't happen /}{\quad \./@>
2689     negate(q); negative = ! negative;
2690   };
2691   n=p / q; p=p % q;
2692   if ( n>=8 ){ 
2693     mp->arith_error=true;
2694     return ( negative ? -el_gordo : el_gordo);
2695   } else { 
2696     n=(n-1)*fraction_one;
2697     @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>;
2698     return (negative ? (-(f+n)) : (f+n));
2699   }
2700 #else /* FIXPT */
2701     register double d;
2702         register integer i;
2703 #ifdef DEBUG
2704         if (q==0) mp_confusion(mp,'/'); 
2705 #endif /* DEBUG */
2706         d = TWEXP28 * (double)p /(double)q;
2707         if ((p^q) >= 0) {
2708                 d += 0.5;
2709                 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
2710                 i = (integer) d;
2711                 if (d==i && ( ((q>0 ? -q : q)&077777)
2712                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2713         } else {
2714                 d -= 0.5;
2715                 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
2716                 i = (integer) d;
2717                 if (d==i && ( ((q>0 ? q : -q)&077777)
2718                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
2719         }
2720         return i;
2721 #endif /* FIXPT */
2722 }
2723
2724 @ The |repeat| loop here preserves the following invariant relations
2725 between |f|, |p|, and~|q|:
2726 (i)~|0<=p<q|; (ii)~$fq+p=2^k(q+p_0)$, where $k$ is an integer and
2727 $p_0$ is the original value of~$p$.
2728
2729 Notice that the computation specifies
2730 |(p-q)+p| instead of |(p+p)-q|, because the latter could overflow.
2731 Let us hope that optimizing compilers do not miss this point; a
2732 special variable |be_careful| is used to emphasize the necessary
2733 order of computation. Optimizing compilers should keep |be_careful|
2734 in a register, not store it in memory.
2735 @^inner loop@>
2736
2737 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>=
2738 {
2739   f=1;
2740   do {  
2741     be_careful=p-q; p=be_careful+p;
2742     if ( p>=0 ) { 
2743       f=f+f+1;
2744     } else  { 
2745       f+=f; p=p+q;
2746     }
2747   } while (f<fraction_one);
2748   be_careful=p-q;
2749   if ( be_careful+p>=0 ) incr(f);
2750 }
2751
2752 @ The dual of |make_fraction| is |take_fraction|, which multiplies a
2753 given integer~|q| by a fraction~|f|. When the operands are positive, it
2754 computes $p=\lfloor qf/2^{28}+{1\over2}\rfloor$, a symmetric function
2755 of |q| and~|f|.
2756
2757 This routine is even more ``inner loopy'' than |make_fraction|;
2758 the present implementation consumes almost 20\pct! of \MP's computation
2759 time during typical jobs, so a machine-language substitute is advisable.
2760 @^inner loop@> @^system dependencies@>
2761
2762 @<Declarations@>=
2763 integer mp_take_fraction (MP mp,integer q, fraction f) ;
2764
2765 @ @c 
2766 #ifdef FIXPT
2767 integer mp_take_fraction (MP mp,integer q, fraction f) {
2768   integer p; /* the fraction so far */
2769   boolean negative; /* should the result be negated? */
2770   integer n; /* additional multiple of $q$ */
2771   integer be_careful; /* disables certain compiler optimizations */
2772   @<Reduce to the case that |f>=0| and |q>0|@>;
2773   if ( f<fraction_one ) { 
2774     n=0;
2775   } else { 
2776     n=f / fraction_one; f=f % fraction_one;
2777     if ( q<=el_gordo / n ) { 
2778       n=n*q ; 
2779     } else { 
2780       mp->arith_error=true; n=el_gordo;
2781     }
2782   }
2783   f=f+fraction_one;
2784   @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>;
2785   be_careful=n-el_gordo;
2786   if ( be_careful+p>0 ){ 
2787     mp->arith_error=true; n=el_gordo-p;
2788   }
2789   if ( negative ) 
2790         return (-(n+p));
2791   else 
2792     return (n+p);
2793 #else /* FIXPT */
2794 integer mp_take_fraction (MP mp,integer p, fraction q) {
2795     register double d;
2796         register integer i;
2797         d = (double)p * (double)q * TWEXP_28;
2798         if ((p^q) >= 0) {
2799                 d += 0.5;
2800                 if (d>=TWEXP31) {
2801                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2802                                 mp->arith_error = true;
2803                         return ELGORDO;
2804                 }
2805                 i = (integer) d;
2806                 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2807         } else {
2808                 d -= 0.5;
2809                 if (d<= -TWEXP31) {
2810                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2811                                 mp->arith_error = true;
2812                         return -ELGORDO;
2813                 }
2814                 i = (integer) d;
2815                 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2816         }
2817         return i;
2818 #endif /* FIXPT */
2819 }
2820
2821 @ @<Reduce to the case that |f>=0| and |q>0|@>=
2822 if ( f>=0 ) {
2823   negative=false;
2824 } else { 
2825   negate( f); negative=true;
2826 }
2827 if ( q<0 ) { 
2828   negate(q); negative=! negative;
2829 }
2830
2831 @ The invariant relations in this case are (i)~$\lfloor(qf+p)/2^k\rfloor
2832 =\lfloor qf_0/2^{28}+{1\over2}\rfloor$, where $k$ is an integer and
2833 $f_0$ is the original value of~$f$; (ii)~$2^k\L f<2^{k+1}$.
2834 @^inner loop@>
2835
2836 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>=
2837 p=fraction_half; /* that's $2^{27}$; the invariants hold now with $k=28$ */
2838 if ( q<fraction_four ) {
2839   do {  
2840     if ( odd(f) ) p=halfp(p+q); else p=halfp(p);
2841     f=halfp(f);
2842   } while (f!=1);
2843 } else  {
2844   do {  
2845     if ( odd(f) ) p=p+halfp(q-p); else p=halfp(p);
2846     f=halfp(f);
2847   } while (f!=1);
2848 }
2849
2850
2851 @ When we want to multiply something by a |scaled| quantity, we use a scheme
2852 analogous to |take_fraction| but with a different scaling.
2853 Given positive operands, |take_scaled|
2854 computes the quantity $p=\lfloor qf/2^{16}+{1\over2}\rfloor$.
2855
2856 Once again it is a good idea to use a machine-language replacement if
2857 possible; otherwise |take_scaled| will use more than 2\pct! of the running time
2858 when the Computer Modern fonts are being generated.
2859 @^inner loop@>
2860
2861 @c 
2862 #ifdef FIXPT
2863 integer mp_take_scaled (MP mp,integer q, scaled f) {
2864   integer p; /* the fraction so far */
2865   boolean negative; /* should the result be negated? */
2866   integer n; /* additional multiple of $q$ */
2867   integer be_careful; /* disables certain compiler optimizations */
2868   @<Reduce to the case that |f>=0| and |q>0|@>;
2869   if ( f<unity ) { 
2870     n=0;
2871   } else  { 
2872     n=f / unity; f=f % unity;
2873     if ( q<=el_gordo / n ) {
2874       n=n*q;
2875     } else  { 
2876       mp->arith_error=true; n=el_gordo;
2877     }
2878   }
2879   f=f+unity;
2880   @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>;
2881   be_careful=n-el_gordo;
2882   if ( be_careful+p>0 ) { 
2883     mp->arith_error=true; n=el_gordo-p;
2884   }
2885   return ( negative ?(-(n+p)) :(n+p));
2886 #else /* FIXPT */
2887 integer mp_take_scaled (MP mp,integer p, scaled q) {
2888     register double d;
2889         register integer i;
2890         d = (double)p * (double)q * TWEXP_16;
2891         if ((p^q) >= 0) {
2892                 d += 0.5;
2893                 if (d>=TWEXP31) {
2894                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2895                                 mp->arith_error = true;
2896                         return ELGORDO;
2897                 }
2898                 i = (integer) d;
2899                 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2900         } else {
2901                 d -= 0.5;
2902                 if (d<= -TWEXP31) {
2903                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2904                                 mp->arith_error = true;
2905                         return -ELGORDO;
2906                 }
2907                 i = (integer) d;
2908                 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2909         }
2910         return i;
2911 #endif /* FIXPT */
2912 }
2913
2914 @ @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>=
2915 p=half_unit; /* that's $2^{15}$; the invariants hold now with $k=16$ */
2916 @^inner loop@>
2917 if ( q<fraction_four ) {
2918   do {  
2919     p = (odd(f) ? halfp(p+q) : halfp(p));
2920     f=halfp(f);
2921   } while (f!=1);
2922 } else {
2923   do {  
2924     p = (odd(f) ? p+halfp(q-p) : halfp(p));
2925     f=halfp(f);
2926   } while (f!=1);
2927 }
2928
2929 @ For completeness, there's also |make_scaled|, which computes a
2930 quotient as a |scaled| number instead of as a |fraction|.
2931 In other words, the result is $\lfloor2^{16}p/q+{1\over2}\rfloor$, if the
2932 operands are positive. \ (This procedure is not used especially often,
2933 so it is not part of \MP's inner loop.)
2934
2935 @<Internal library ...@>=
2936 scaled mp_make_scaled (MP mp,integer p, integer q) ;
2937
2938 @ @c 
2939 scaled mp_make_scaled (MP mp,integer p, integer q) {
2940 #ifdef FIXPT 
2941   integer f; /* the fraction bits, with a leading 1 bit */
2942   integer n; /* the integer part of $\vert p/q\vert$ */
2943   boolean negative; /* should the result be negated? */
2944   integer be_careful; /* disables certain compiler optimizations */
2945   if ( p>=0 ) negative=false;
2946   else  { negate(p); negative=true; };
2947   if ( q<=0 ) { 
2948 #ifdef DEBUG 
2949     if ( q==0 ) mp_confusion(mp, "/");
2950 @:this can't happen /}{\quad \./@>
2951 #endif
2952     negate(q); negative=! negative;
2953   }
2954   n=p / q; p=p % q;
2955   if ( n>=0100000 ) { 
2956     mp->arith_error=true;
2957     return (negative ? (-el_gordo) : el_gordo);
2958   } else  { 
2959     n=(n-1)*unity;
2960     @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>;
2961     return ( negative ? (-(f+n)) :(f+n));
2962   }
2963 #else /* FIXPT */
2964     register double d;
2965         register integer i;
2966 #ifdef DEBUG
2967         if (q==0) mp_confusion(mp,"/"); 
2968 #endif /* DEBUG */
2969         d = TWEXP16 * (double)p /(double)q;
2970         if ((p^q) >= 0) {
2971                 d += 0.5;
2972                 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
2973                 i = (integer) d;
2974                 if (d==i && ( ((q>0 ? -q : q)&077777)
2975                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2976         } else {
2977                 d -= 0.5;
2978                 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
2979                 i = (integer) d;
2980                 if (d==i && ( ((q>0 ? q : -q)&077777)
2981                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
2982         }
2983         return i;
2984 #endif /* FIXPT */
2985 }
2986
2987 @ @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>=
2988 f=1;
2989 do {  
2990   be_careful=p-q; p=be_careful+p;
2991   if ( p>=0 ) f=f+f+1;
2992   else  { f+=f; p=p+q; };
2993 } while (f<unity);
2994 be_careful=p-q;
2995 if ( be_careful+p>=0 ) incr(f)
2996
2997 @ Here is a typical example of how the routines above can be used.
2998 It computes the function
2999 $${1\over3\tau}f(\theta,\phi)=
3000 {\tau^{-1}\bigl(2+\sqrt2\,(\sin\theta-{1\over16}\sin\phi)
3001  (\sin\phi-{1\over16}\sin\theta)(\cos\theta-\cos\phi)\bigr)\over
3002 3\,\bigl(1+{1\over2}(\sqrt5-1)\cos\theta+{1\over2}(3-\sqrt5\,)\cos\phi\bigr)},$$
3003 where $\tau$ is a |scaled| ``tension'' parameter. This is \MP's magic
3004 fudge factor for placing the first control point of a curve that starts
3005 at an angle $\theta$ and ends at an angle $\phi$ from the straight path.
3006 (Actually, if the stated quantity exceeds 4, \MP\ reduces it to~4.)
3007
3008 The trigonometric quantity to be multiplied by $\sqrt2$ is less than $\sqrt2$.
3009 (It's a sum of eight terms whose absolute values can be bounded using
3010 relations such as $\sin\theta\cos\theta\L{1\over2}$.) Thus the numerator
3011 is positive; and since the tension $\tau$ is constrained to be at least
3012 $3\over4$, the numerator is less than $16\over3$. The denominator is
3013 nonnegative and at most~6.  Hence the fixed-point calculations below
3014 are guaranteed to stay within the bounds of a 32-bit computer word.
3015
3016 The angles $\theta$ and $\phi$ are given implicitly in terms of |fraction|
3017 arguments |st|, |ct|, |sf|, and |cf|, representing $\sin\theta$, $\cos\theta$,
3018 $\sin\phi$, and $\cos\phi$, respectively.
3019
3020 @c 
3021 fraction mp_velocity (MP mp,fraction st, fraction ct, fraction sf,
3022                       fraction cf, scaled t) {
3023   integer acc,num,denom; /* registers for intermediate calculations */
3024   acc=mp_take_fraction(mp, st-(sf / 16), sf-(st / 16));
3025   acc=mp_take_fraction(mp, acc,ct-cf);
3026   num=fraction_two+mp_take_fraction(mp, acc,379625062);
3027                    /* $2^{28}\sqrt2\approx379625062.497$ */
3028   denom=fraction_three+mp_take_fraction(mp, ct,497706707)+mp_take_fraction(mp, cf,307599661);
3029                       /* $3\cdot2^{27}\cdot(\sqrt5-1)\approx497706706.78$ and
3030                          $3\cdot2^{27}\cdot(3-\sqrt5\,)\approx307599661.22$ */
3031   if ( t!=unity ) num=mp_make_scaled(mp, num,t);
3032   /* |make_scaled(fraction,scaled)=fraction| */
3033   if ( num / 4>=denom ) 
3034     return fraction_four;
3035   else 
3036     return mp_make_fraction(mp, num, denom);
3037 }
3038
3039 @ The following somewhat different subroutine tests rigorously if $ab$ is
3040 greater than, equal to, or less than~$cd$,
3041 given integers $(a,b,c,d)$. In most cases a quick decision is reached.
3042 The result is $+1$, 0, or~$-1$ in the three respective cases.
3043
3044 @d mp_ab_vs_cd(M,A,B,C,D) mp_do_ab_vs_cd(A,B,C,D)
3045
3046 @c 
3047 integer mp_do_ab_vs_cd (integer a,integer b, integer c, integer d) {
3048   integer q,r; /* temporary registers */
3049   @<Reduce to the case that |a,c>=0|, |b,d>0|@>;
3050   while (1) { 
3051     q = a / d; r = c / b;
3052     if ( q!=r )
3053       return ( q>r ? 1 : -1);
3054     q = a % d; r = c % b;
3055     if ( r==0 )
3056       return (q ? 1 : 0);
3057     if ( q==0 ) return -1;
3058     a=b; b=q; c=d; d=r;
3059   } /* now |a>d>0| and |c>b>0| */
3060 }
3061
3062 @ @<Reduce to the case that |a...@>=
3063 if ( a<0 ) { negate(a); negate(b);  };
3064 if ( c<0 ) { negate(c); negate(d);  };
3065 if ( d<=0 ) { 
3066   if ( b>=0 ) {
3067     if ( (a==0||b==0)&&(c==0||d==0) ) return 0;
3068     else return 1;
3069   }
3070   if ( d==0 )
3071     return ( a==0 ? 0 : -1);
3072   q=a; a=c; c=q; q=-b; b=-d; d=q;
3073 } else if ( b<=0 ) { 
3074   if ( b<0 ) if ( a>0 ) return -1;
3075   return (c==0 ? 0 : -1);
3076 }
3077
3078 @ We conclude this set of elementary routines with some simple rounding
3079 and truncation operations.
3080
3081 @<Internal library declarations@>=
3082 #define mp_floor_scaled(M,i) ((i)&(-65536))
3083 #define mp_round_unscaled(M,i) (((i>>15)+1)>>1)
3084 #define mp_round_fraction(M,i) (((i>>11)+1)>>1)
3085
3086
3087 @* \[8] Algebraic and transcendental functions.
3088 \MP\ computes all of the necessary special functions from scratch, without
3089 relying on |real| arithmetic or system subroutines for sines, cosines, etc.
3090
3091 @ To get the square root of a |scaled| number |x|, we want to calculate
3092 $s=\lfloor 2^8\!\sqrt x +{1\over2}\rfloor$. If $x>0$, this is the unique
3093 integer such that $2^{16}x-s\L s^2<2^{16}x+s$. The following subroutine
3094 determines $s$ by an iterative method that maintains the invariant
3095 relations $x=2^{46-2k}x_0\bmod 2^{30}$, $0<y=\lfloor 2^{16-2k}x_0\rfloor
3096 -s^2+s\L q=2s$, where $x_0$ is the initial value of $x$. The value of~$y$
3097 might, however, be zero at the start of the first iteration.
3098
3099 @<Declarations@>=
3100 scaled mp_square_rt (MP mp,scaled x) ;
3101
3102 @ @c 
3103 scaled mp_square_rt (MP mp,scaled x) {
3104   small_number k; /* iteration control counter */
3105   integer y,q; /* registers for intermediate calculations */
3106   if ( x<=0 ) { 
3107     @<Handle square root of zero or negative argument@>;
3108   } else { 
3109     k=23; q=2;
3110     while ( x<fraction_two ) { /* i.e., |while x<@t$2^{29}$@>|\unskip */
3111       decr(k); x=x+x+x+x;
3112     }
3113     if ( x<fraction_four ) y=0;
3114     else  { x=x-fraction_four; y=1; };
3115     do {  
3116       @<Decrease |k| by 1, maintaining the invariant
3117       relations between |x|, |y|, and~|q|@>;
3118     } while (k!=0);
3119     return (halfp(q));
3120   }
3121 }
3122
3123 @ @<Handle square root of zero...@>=
3124
3125   if ( x<0 ) { 
3126     print_err("Square root of ");
3127 @.Square root...replaced by 0@>
3128     mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3129     help2("Since I don't take square roots of negative numbers,")
3130          ("I'm zeroing this one. Proceed, with fingers crossed.");
3131     mp_error(mp);
3132   };
3133   return 0;
3134 }
3135
3136 @ @<Decrease |k| by 1, maintaining...@>=
3137 x+=x; y+=y;
3138 if ( x>=fraction_four ) { /* note that |fraction_four=@t$2^{30}$@>| */
3139   x=x-fraction_four; incr(y);
3140 };
3141 x+=x; y=y+y-q; q+=q;
3142 if ( x>=fraction_four ) { x=x-fraction_four; incr(y); };
3143 if ( y>q ){ y=y-q; q=q+2; }
3144 else if ( y<=0 )  { q=q-2; y=y+q;  };
3145 decr(k)
3146
3147 @ Pythagorean addition $\psqrt{a^2+b^2}$ is implemented by an elegant
3148 iterative scheme due to Cleve Moler and Donald Morrison [{\sl IBM Journal
3149 @^Moler, Cleve Barry@>
3150 @^Morrison, Donald Ross@>
3151 of Research and Development\/ \bf27} (1983), 577--581]. It modifies |a| and~|b|
3152 in such a way that their Pythagorean sum remains invariant, while the
3153 smaller argument decreases.
3154
3155 @<Internal library ...@>=
3156 integer mp_pyth_add (MP mp,integer a, integer b);
3157
3158
3159 @ @c 
3160 integer mp_pyth_add (MP mp,integer a, integer b) {
3161   fraction r; /* register used to transform |a| and |b| */
3162   boolean big; /* is the result dangerously near $2^{31}$? */
3163   a=abs(a); b=abs(b);
3164   if ( a<b ) { r=b; b=a; a=r; }; /* now |0<=b<=a| */
3165   if ( b>0 ) {
3166     if ( a<fraction_two ) {
3167       big=false;
3168     } else { 
3169       a=a / 4; b=b / 4; big=true;
3170     }; /* we reduced the precision to avoid arithmetic overflow */
3171     @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>;
3172     if ( big ) {
3173       if ( a<fraction_two ) {
3174         a=a+a+a+a;
3175       } else  { 
3176         mp->arith_error=true; a=el_gordo;
3177       };
3178     }
3179   }
3180   return a;
3181 }
3182
3183 @ The key idea here is to reflect the vector $(a,b)$ about the
3184 line through $(a,b/2)$.
3185
3186 @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>=
3187 while (1) {  
3188   r=mp_make_fraction(mp, b,a);
3189   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3190   if ( r==0 ) break;
3191   r=mp_make_fraction(mp, r,fraction_four+r);
3192   a=a+mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3193 }
3194
3195
3196 @ Here is a similar algorithm for $\psqrt{a^2-b^2}$.
3197 It converges slowly when $b$ is near $a$, but otherwise it works fine.
3198
3199 @c 
3200 integer mp_pyth_sub (MP mp,integer a, integer b) {
3201   fraction r; /* register used to transform |a| and |b| */
3202   boolean big; /* is the input dangerously near $2^{31}$? */
3203   a=abs(a); b=abs(b);
3204   if ( a<=b ) {
3205     @<Handle erroneous |pyth_sub| and set |a:=0|@>;
3206   } else { 
3207     if ( a<fraction_four ) {
3208       big=false;
3209     } else  { 
3210       a=halfp(a); b=halfp(b); big=true;
3211     }
3212     @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>;
3213     if ( big ) double(a);
3214   }
3215   return a;
3216 }
3217
3218 @ @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>=
3219 while (1) { 
3220   r=mp_make_fraction(mp, b,a);
3221   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3222   if ( r==0 ) break;
3223   r=mp_make_fraction(mp, r,fraction_four-r);
3224   a=a-mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3225 }
3226
3227 @ @<Handle erroneous |pyth_sub| and set |a:=0|@>=
3228
3229   if ( a<b ){ 
3230     print_err("Pythagorean subtraction "); mp_print_scaled(mp, a);
3231     mp_print(mp, "+-+"); mp_print_scaled(mp, b); 
3232     mp_print(mp, " has been replaced by 0");
3233 @.Pythagorean...@>
3234     help2("Since I don't take square roots of negative numbers,")
3235          ("I'm zeroing this one. Proceed, with fingers crossed.");
3236     mp_error(mp);
3237   }
3238   a=0;
3239 }
3240
3241 @ The subroutines for logarithm and exponential involve two tables.
3242 The first is simple: |two_to_the[k]| equals $2^k$. The second involves
3243 a bit more calculation, which the author claims to have done correctly:
3244 |spec_log[k]| is $2^{27}$ times $\ln\bigl(1/(1-2^{-k})\bigr)=
3245 2^{-k}+{1\over2}2^{-2k}+{1\over3}2^{-3k}+\cdots\,$, rounded to the
3246 nearest integer.
3247
3248 @d two_to_the(A) (1<<(A))
3249
3250 @<Constants ...@>=
3251 static const integer spec_log[29] = { 0, /* special logarithms */
3252 93032640, 38612034, 17922280, 8662214, 4261238, 2113709,
3253 1052693, 525315, 262400, 131136, 65552, 32772, 16385,
3254 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 1 };
3255
3256 @ @<Local variables for initialization@>=
3257 integer k; /* all-purpose loop index */
3258
3259
3260 @ Here is the routine that calculates $2^8$ times the natural logarithm
3261 of a |scaled| quantity; it is an integer approximation to $2^{24}\ln(x/2^{16})$,
3262 when |x| is a given positive integer.
3263
3264 The method is based on exercise 1.2.2--25 in {\sl The Art of Computer
3265 Programming\/}: During the main iteration we have $1\L 2^{-30}x<1/(1-2^{1-k})$,
3266 and the logarithm of $2^{30}x$ remains to be added to an accumulator
3267 register called~$y$. Three auxiliary bits of accuracy are retained in~$y$
3268 during the calculation, and sixteen auxiliary bits to extend |y| are
3269 kept in~|z| during the initial argument reduction. (We add
3270 $100\cdot2^{16}=6553600$ to~|z| and subtract 100 from~|y| so that |z| will
3271 not become negative; also, the actual amount subtracted from~|y| is~96,
3272 not~100, because we want to add~4 for rounding before the final division by~8.)
3273
3274 @c 
3275 scaled mp_m_log (MP mp,scaled x) {
3276   integer y,z; /* auxiliary registers */
3277   integer k; /* iteration counter */
3278   if ( x<=0 ) {
3279      @<Handle non-positive logarithm@>;
3280   } else  { 
3281     y=1302456956+4-100; /* $14\times2^{27}\ln2\approx1302456956.421063$ */
3282     z=27595+6553600; /* and $2^{16}\times .421063\approx 27595$ */
3283     while ( x<fraction_four ) {
3284        double(x); y-=93032639; z-=48782;
3285     } /* $2^{27}\ln2\approx 93032639.74436163$ and $2^{16}\times.74436163\approx 48782$ */
3286     y=y+(z / unity); k=2;
3287     while ( x>fraction_four+4 ) {
3288       @<Increase |k| until |x| can be multiplied by a
3289         factor of $2^{-k}$, and adjust $y$ accordingly@>;
3290     }
3291     return (y / 8);
3292   }
3293 }
3294
3295 @ @<Increase |k| until |x| can...@>=
3296
3297   z=((x-1) / two_to_the(k))+1; /* $z=\lceil x/2^k\rceil$ */
3298   while ( x<fraction_four+z ) { z=halfp(z+1); incr(k); };
3299   y+=spec_log[k]; x-=z;
3300 }
3301
3302 @ @<Handle non-positive logarithm@>=
3303
3304   print_err("Logarithm of ");
3305 @.Logarithm...replaced by 0@>
3306   mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3307   help2("Since I don't take logs of non-positive numbers,")
3308        ("I'm zeroing this one. Proceed, with fingers crossed.");
3309   mp_error(mp); 
3310   return 0;
3311 }
3312
3313 @ Conversely, the exponential routine calculates $\exp(x/2^8)$,
3314 when |x| is |scaled|. The result is an integer approximation to
3315 $2^{16}\exp(x/2^{24})$, when |x| is regarded as an integer.
3316
3317 @c 
3318 scaled mp_m_exp (MP mp,scaled x) {
3319   small_number k; /* loop control index */
3320   integer y,z; /* auxiliary registers */
3321   if ( x>174436200 ) {
3322     /* $2^{24}\ln((2^{31}-1)/2^{16})\approx 174436199.51$ */
3323     mp->arith_error=true; 
3324     return el_gordo;
3325   } else if ( x<-197694359 ) {
3326         /* $2^{24}\ln(2^{-1}/2^{16})\approx-197694359.45$ */
3327     return 0;
3328   } else { 
3329     if ( x<=0 ) { 
3330        z=-8*x; y=04000000; /* $y=2^{20}$ */
3331     } else { 
3332       if ( x<=127919879 ) { 
3333         z=1023359037-8*x;
3334         /* $2^{27}\ln((2^{31}-1)/2^{20})\approx 1023359037.125$ */
3335       } else {
3336        z=8*(174436200-x); /* |z| is always nonnegative */
3337       }
3338       y=el_gordo;
3339     };
3340     @<Multiply |y| by $\exp(-z/2^{27})$@>;
3341     if ( x<=127919879 ) 
3342        return ((y+8) / 16);
3343      else 
3344        return y;
3345   }
3346 }
3347
3348 @ The idea here is that subtracting |spec_log[k]| from |z| corresponds
3349 to multiplying |y| by $1-2^{-k}$.
3350
3351 A subtle point (which had to be checked) was that if $x=127919879$, the
3352 value of~|y| will decrease so that |y+8| doesn't overflow. In fact,
3353 $z$ will be 5 in this case, and |y| will decrease by~64 when |k=25|
3354 and by~16 when |k=27|.
3355
3356 @<Multiply |y| by...@>=
3357 k=1;
3358 while ( z>0 ) { 
3359   while ( z>=spec_log[k] ) { 
3360     z-=spec_log[k];
3361     y=y-1-((y-two_to_the(k-1)) / two_to_the(k));
3362   }
3363   incr(k);
3364 }
3365
3366 @ The trigonometric subroutines use an auxiliary table such that
3367 |spec_atan[k]| contains an approximation to the |angle| whose tangent
3368 is~$1/2^k$. $\arctan2^{-k}$ times $2^{20}\cdot180/\pi$ 
3369
3370 @<Constants ...@>=
3371 static const angle spec_atan[27] = { 0, 27855475, 14718068, 7471121, 3750058, 
3372 1876857, 938658, 469357, 234682, 117342, 58671, 29335, 14668, 7334, 3667, 
3373 1833, 917, 458, 229, 115, 57, 29, 14, 7, 4, 2, 1 };
3374
3375 @ Given integers |x| and |y|, not both zero, the |n_arg| function
3376 returns the |angle| whose tangent points in the direction $(x,y)$.
3377 This subroutine first determines the correct octant, then solves the
3378 problem for |0<=y<=x|, then converts the result appropriately to
3379 return an answer in the range |-one_eighty_deg<=@t$\theta$@><=one_eighty_deg|.
3380 (The answer is |+one_eighty_deg| if |y=0| and |x<0|, but an answer of
3381 |-one_eighty_deg| is possible if, for example, |y=-1| and $x=-2^{30}$.)
3382
3383 The octants are represented in a ``Gray code,'' since that turns out
3384 to be computationally simplest.
3385
3386 @d negate_x 1
3387 @d negate_y 2
3388 @d switch_x_and_y 4
3389 @d first_octant 1
3390 @d second_octant (first_octant+switch_x_and_y)
3391 @d third_octant (first_octant+switch_x_and_y+negate_x)
3392 @d fourth_octant (first_octant+negate_x)
3393 @d fifth_octant (first_octant+negate_x+negate_y)
3394 @d sixth_octant (first_octant+switch_x_and_y+negate_x+negate_y)
3395 @d seventh_octant (first_octant+switch_x_and_y+negate_y)
3396 @d eighth_octant (first_octant+negate_y)
3397
3398 @c 
3399 angle mp_n_arg (MP mp,integer x, integer y) {
3400   angle z; /* auxiliary register */
3401   integer t; /* temporary storage */
3402   small_number k; /* loop counter */
3403   int octant; /* octant code */
3404   if ( x>=0 ) {
3405     octant=first_octant;
3406   } else { 
3407     negate(x); octant=first_octant+negate_x;
3408   }
3409   if ( y<0 ) { 
3410     negate(y); octant=octant+negate_y;
3411   }
3412   if ( x<y ) { 
3413     t=y; y=x; x=t; octant=octant+switch_x_and_y;
3414   }
3415   if ( x==0 ) { 
3416     @<Handle undefined arg@>; 
3417   } else { 
3418     @<Set variable |z| to the arg of $(x,y)$@>;
3419     @<Return an appropriate answer based on |z| and |octant|@>;
3420   }
3421 }
3422
3423 @ @<Handle undefined arg@>=
3424
3425   print_err("angle(0,0) is taken as zero");
3426 @.angle(0,0)...zero@>
3427   help2("The `angle' between two identical points is undefined.")
3428        ("I'm zeroing this one. Proceed, with fingers crossed.");
3429   mp_error(mp); 
3430   return 0;
3431 }
3432
3433 @ @<Return an appropriate answer...@>=
3434 switch (octant) {
3435 case first_octant: return z;
3436 case second_octant: return (ninety_deg-z);
3437 case third_octant: return (ninety_deg+z);
3438 case fourth_octant: return (one_eighty_deg-z);
3439 case fifth_octant: return (z-one_eighty_deg);
3440 case sixth_octant: return (-z-ninety_deg);
3441 case seventh_octant: return (z-ninety_deg);
3442 case eighth_octant: return (-z);
3443 }; /* there are no other cases */
3444 return 0
3445
3446 @ At this point we have |x>=y>=0|, and |x>0|. The numbers are scaled up
3447 or down until $2^{28}\L x<2^{29}$, so that accurate fixed-point calculations
3448 will be made.
3449
3450 @<Set variable |z| to the arg...@>=
3451 while ( x>=fraction_two ) { 
3452   x=halfp(x); y=halfp(y);
3453 }
3454 z=0;
3455 if ( y>0 ) { 
3456  while ( x<fraction_one ) { 
3457     x+=x; y+=y; 
3458  };
3459  @<Increase |z| to the arg of $(x,y)$@>;
3460 }
3461
3462 @ During the calculations of this section, variables |x| and~|y|
3463 represent actual coordinates $(x,2^{-k}y)$. We will maintain the
3464 condition |x>=y|, so that the tangent will be at most $2^{-k}$.
3465 If $x<2y$, the tangent is greater than $2^{-k-1}$. The transformation
3466 $(a,b)\mapsto(a+b\tan\phi,b-a\tan\phi)$ replaces $(a,b)$ by
3467 coordinates whose angle has decreased by~$\phi$; in the special case
3468 $a=x$, $b=2^{-k}y$, and $\tan\phi=2^{-k-1}$, this operation reduces
3469 to the particularly simple iteration shown here. [Cf.~John E. Meggitt,
3470 @^Meggitt, John E.@>
3471 {\sl IBM Journal of Research and Development\/ \bf6} (1962), 210--226.]
3472
3473 The initial value of |x| will be multiplied by at most
3474 $(1+{1\over2})(1+{1\over8})(1+{1\over32})\cdots\approx 1.7584$; hence
3475 there is no chance of integer overflow.
3476
3477 @<Increase |z|...@>=
3478 k=0;
3479 do {  
3480   y+=y; incr(k);
3481   if ( y>x ){ 
3482     z=z+spec_atan[k]; t=x; x=x+(y / two_to_the(k+k)); y=y-t;
3483   };
3484 } while (k!=15);
3485 do {  
3486   y+=y; incr(k);
3487   if ( y>x ) { z=z+spec_atan[k]; y=y-x; };
3488 } while (k!=26)
3489
3490 @ Conversely, the |n_sin_cos| routine takes an |angle| and produces the sine
3491 and cosine of that angle. The results of this routine are
3492 stored in global integer variables |n_sin| and |n_cos|.
3493
3494 @<Glob...@>=
3495 fraction n_sin;fraction n_cos; /* results computed by |n_sin_cos| */
3496
3497 @ Given an integer |z| that is $2^{20}$ times an angle $\theta$ in degrees,
3498 the purpose of |n_sin_cos(z)| is to set
3499 |x=@t$r\cos\theta$@>| and |y=@t$r\sin\theta$@>| (approximately),
3500 for some rather large number~|r|. The maximum of |x| and |y|
3501 will be between $2^{28}$ and $2^{30}$, so that there will be hardly
3502 any loss of accuracy. Then |x| and~|y| are divided by~|r|.
3503
3504 @c 
3505 void mp_n_sin_cos (MP mp,angle z) { /* computes a multiple of the sine
3506                                        and cosine */ 
3507   small_number k; /* loop control variable */
3508   int q; /* specifies the quadrant */
3509   fraction r; /* magnitude of |(x,y)| */
3510   integer x,y,t; /* temporary registers */
3511   while ( z<0 ) z=z+three_sixty_deg;
3512   z=z % three_sixty_deg; /* now |0<=z<three_sixty_deg| */
3513   q=z / forty_five_deg; z=z % forty_five_deg;
3514   x=fraction_one; y=x;
3515   if ( ! odd(q) ) z=forty_five_deg-z;
3516   @<Subtract angle |z| from |(x,y)|@>;
3517   @<Convert |(x,y)| to the octant determined by~|q|@>;
3518   r=mp_pyth_add(mp, x,y); 
3519   mp->n_cos=mp_make_fraction(mp, x,r); 
3520   mp->n_sin=mp_make_fraction(mp, y,r);
3521 }
3522
3523 @ In this case the octants are numbered sequentially.
3524
3525 @<Convert |(x,...@>=
3526 switch (q) {
3527 case 0: break;
3528 case 1: t=x; x=y; y=t; break;
3529 case 2: t=x; x=-y; y=t; break;
3530 case 3: negate(x); break;
3531 case 4: negate(x); negate(y); break;
3532 case 5: t=x; x=-y; y=-t; break;
3533 case 6: t=x; x=y; y=-t; break;
3534 case 7: negate(y); break;
3535 } /* there are no other cases */
3536
3537 @ The main iteration of |n_sin_cos| is similar to that of |n_arg| but
3538 applied in reverse. The values of |spec_atan[k]| decrease slowly enough
3539 that this loop is guaranteed to terminate before the (nonexistent) value
3540 |spec_atan[27]| would be required.
3541
3542 @<Subtract angle |z|...@>=
3543 k=1;
3544 while ( z>0 ){ 
3545   if ( z>=spec_atan[k] ) { 
3546     z=z-spec_atan[k]; t=x;
3547     x=t+y / two_to_the(k);
3548     y=y-t / two_to_the(k);
3549   }
3550   incr(k);
3551 }
3552 if ( y<0 ) y=0 /* this precaution may never be needed */
3553
3554 @ And now let's complete our collection of numeric utility routines
3555 by considering random number generation.
3556 \MP\ generates pseudo-random numbers with the additive scheme recommended
3557 in Section 3.6 of {\sl The Art of Computer Programming}; however, the
3558 results are random fractions between 0 and |fraction_one-1|, inclusive.
3559
3560 There's an auxiliary array |randoms| that contains 55 pseudo-random
3561 fractions. Using the recurrence $x_n=(x_{n-55}-x_{n-31})\bmod 2^{28}$,
3562 we generate batches of 55 new $x_n$'s at a time by calling |new_randoms|.
3563 The global variable |j_random| tells which element has most recently
3564 been consumed.
3565 The global variable |random_seed| was introduced in version 0.9,
3566 for the sole reason of stressing the fact that the initial value of the
3567 random seed is system-dependant. The initialization code below will initialize
3568 this variable to |(internal[mp_time] div unity)+internal[mp_day]|, but this 
3569 is not good enough on modern fast machines that are capable of running
3570 multiple MetaPost processes within the same second.
3571 @^system dependencies@>
3572
3573 @<Glob...@>=
3574 fraction randoms[55]; /* the last 55 random values generated */
3575 int j_random; /* the number of unused |randoms| */
3576
3577 @ @<Option variables@>=
3578 int random_seed; /* the default random seed */
3579
3580 @ @<Allocate or initialize ...@>=
3581 mp->random_seed = (scaled)opt->random_seed;
3582
3583 @ To consume a random fraction, the program below will say `|next_random|'
3584 and then it will fetch |randoms[j_random]|.
3585
3586 @d next_random { if ( mp->j_random==0 ) mp_new_randoms(mp);
3587   else decr(mp->j_random); }
3588
3589 @c 
3590 void mp_new_randoms (MP mp) {
3591   int k; /* index into |randoms| */
3592   fraction x; /* accumulator */
3593   for (k=0;k<=23;k++) { 
3594    x=mp->randoms[k]-mp->randoms[k+31];
3595     if ( x<0 ) x=x+fraction_one;
3596     mp->randoms[k]=x;
3597   }
3598   for (k=24;k<= 54;k++){ 
3599     x=mp->randoms[k]-mp->randoms[k-24];
3600     if ( x<0 ) x=x+fraction_one;
3601     mp->randoms[k]=x;
3602   }
3603   mp->j_random=54;
3604 }
3605
3606 @ @<Declarations@>=
3607 void mp_init_randoms (MP mp,scaled seed);
3608
3609 @ To initialize the |randoms| table, we call the following routine.
3610
3611 @c 
3612 void mp_init_randoms (MP mp,scaled seed) {
3613   fraction j,jj,k; /* more or less random integers */
3614   int i; /* index into |randoms| */
3615   j=abs(seed);
3616   while ( j>=fraction_one ) j=halfp(j);
3617   k=1;
3618   for (i=0;i<=54;i++ ){ 
3619     jj=k; k=j-k; j=jj;
3620     if ( k<0 ) k=k+fraction_one;
3621     mp->randoms[(i*21)% 55]=j;
3622   }
3623   mp_new_randoms(mp); 
3624   mp_new_randoms(mp); 
3625   mp_new_randoms(mp); /* ``warm up'' the array */
3626 }
3627
3628 @ To produce a uniform random number in the range |0<=u<x| or |0>=u>x|
3629 or |0=u=x|, given a |scaled| value~|x|, we proceed as shown here.
3630
3631 Note that the call of |take_fraction| will produce the values 0 and~|x|
3632 with about half the probability that it will produce any other particular
3633 values between 0 and~|x|, because it rounds its answers.
3634
3635 @c 
3636 scaled mp_unif_rand (MP mp,scaled x) {
3637   scaled y; /* trial value */
3638   next_random; y=mp_take_fraction(mp, abs(x),mp->randoms[mp->j_random]);
3639   if ( y==abs(x) ) return 0;
3640   else if ( x>0 ) return y;
3641   else return (-y);
3642 }
3643
3644 @ Finally, a normal deviate with mean zero and unit standard deviation
3645 can readily be obtained with the ratio method (Algorithm 3.4.1R in
3646 {\sl The Art of Computer Programming\/}).
3647
3648 @c 
3649 scaled mp_norm_rand (MP mp) {
3650   integer x,u,l; /* what the book would call $2^{16}X$, $2^{28}U$, and $-2^{24}\ln U$ */
3651   do { 
3652     do {  
3653       next_random;
3654       x=mp_take_fraction(mp, 112429,mp->randoms[mp->j_random]-fraction_half);
3655       /* $2^{16}\sqrt{8/e}\approx 112428.82793$ */
3656       next_random; u=mp->randoms[mp->j_random];
3657     } while (abs(x)>=u);
3658     x=mp_make_fraction(mp, x,u);
3659     l=139548960-mp_m_log(mp, u); /* $2^{24}\cdot12\ln2\approx139548959.6165$ */
3660   } while (mp_ab_vs_cd(mp, 1024,l,x,x)<0);
3661   return x;
3662 }
3663
3664 @* \[9] Packed data.
3665 In order to make efficient use of storage space, \MP\ bases its major data
3666 structures on a |memory_word|, which contains either a (signed) integer,
3667 possibly scaled, or a small number of fields that are one half or one
3668 quarter of the size used for storing integers.
3669
3670 If |x| is a variable of type |memory_word|, it contains up to four
3671 fields that can be referred to as follows:
3672 $$\vbox{\halign{\hfil#&#\hfil&#\hfil\cr
3673 |x|&.|int|&(an |integer|)\cr
3674 |x|&.|sc|\qquad&(a |scaled| integer)\cr
3675 |x.hh.lh|, |x.hh|&.|rh|&(two halfword fields)\cr
3676 |x.hh.b0|, |x.hh.b1|, |x.hh|&.|rh|&(two quarterword fields, one halfword
3677   field)\cr
3678 |x.qqqq.b0|, |x.qqqq.b1|, |x.qqqq|&.|b2|, |x.qqqq.b3|\hskip-100pt
3679   &\qquad\qquad\qquad(four quarterword fields)\cr}}$$
3680 This is somewhat cumbersome to write, and not very readable either, but
3681 macros will be used to make the notation shorter and more transparent.
3682 The code below gives a formal definition of |memory_word| and
3683 its subsidiary types, using packed variant records. \MP\ makes no
3684 assumptions about the relative positions of the fields within a word.
3685
3686 @d max_quarterword 0x3FFF /* largest allowable value in a |quarterword| */
3687 @d max_halfword 0xFFFFFFF /* largest allowable value in a |halfword| */
3688
3689 @ Here are the inequalities that the quarterword and halfword values
3690 must satisfy (or rather, the inequalities that they mustn't satisfy):
3691
3692 @<Check the ``constant''...@>=
3693 if (mp->ini_version) {
3694   if ( mp->mem_max!=mp->mem_top ) mp->bad=8;
3695 } else {
3696   if ( mp->mem_max<mp->mem_top ) mp->bad=8;
3697 }
3698 if ( max_quarterword<255 ) mp->bad=9;
3699 if ( max_halfword<65535 ) mp->bad=10;
3700 if ( max_quarterword>max_halfword ) mp->bad=11;
3701 if ( mp->mem_max>=max_halfword ) mp->bad=12;
3702 if ( mp->max_strings>max_halfword ) mp->bad=13;
3703
3704 @ The macros |qi| and |qo| are used for input to and output 
3705 from quarterwords. These are legacy macros.
3706 @^system dependencies@>
3707
3708 @d qo(A) (A) /* to read eight bits from a quarterword */
3709 @d qi(A) (A) /* to store eight bits in a quarterword */
3710
3711 @ The reader should study the following definitions closely:
3712 @^system dependencies@>
3713
3714 @d sc cint /* |scaled| data is equivalent to |integer| */
3715
3716 @<Types...@>=
3717 typedef short quarterword; /* 1/4 of a word */
3718 typedef int halfword; /* 1/2 of a word */
3719 typedef union {
3720   struct {
3721     halfword RH, LH;
3722   } v;
3723   struct { /* Make B0,B1 overlap the most significant bytes of LH.  */
3724     halfword junk;
3725     quarterword B0, B1;
3726   } u;
3727 } two_halves;
3728 typedef struct {
3729   struct {
3730     quarterword B2, B3, B0, B1;
3731   } u;
3732 } four_quarters;
3733 typedef union {
3734   two_halves hh;
3735   integer cint;
3736   four_quarters qqqq;
3737 } memory_word;
3738 #define b0 u.B0
3739 #define b1 u.B1
3740 #define b2 u.B2
3741 #define b3 u.B3
3742 #define rh v.RH
3743 #define lh v.LH
3744
3745 @ When debugging, we may want to print a |memory_word| without knowing
3746 what type it is; so we print it in all modes.
3747 @^debugging@>
3748
3749 @c 
3750 void mp_print_word (MP mp,memory_word w) {
3751   /* prints |w| in all ways */
3752   mp_print_int(mp, w.cint); mp_print_char(mp, ' ');
3753   mp_print_scaled(mp, w.sc); mp_print_char(mp, ' '); 
3754   mp_print_scaled(mp, w.sc / 010000); mp_print_ln(mp);
3755   mp_print_int(mp, w.hh.lh); mp_print_char(mp, '='); 
3756   mp_print_int(mp, w.hh.b0); mp_print_char(mp, ':');
3757   mp_print_int(mp, w.hh.b1); mp_print_char(mp, ';'); 
3758   mp_print_int(mp, w.hh.rh); mp_print_char(mp, ' ');
3759   mp_print_int(mp, w.qqqq.b0); mp_print_char(mp, ':'); 
3760   mp_print_int(mp, w.qqqq.b1); mp_print_char(mp, ':');
3761   mp_print_int(mp, w.qqqq.b2); mp_print_char(mp, ':'); 
3762   mp_print_int(mp, w.qqqq.b3);
3763 }
3764
3765
3766 @* \[10] Dynamic memory allocation.
3767
3768 The \MP\ system does nearly all of its own memory allocation, so that it
3769 can readily be transported into environments that do not have automatic
3770 facilities for strings, garbage collection, etc., and so that it can be in
3771 control of what error messages the user receives. The dynamic storage
3772 requirements of \MP\ are handled by providing a large array |mem| in
3773 which consecutive blocks of words are used as nodes by the \MP\ routines.
3774
3775 Pointer variables are indices into this array, or into another array
3776 called |eqtb| that will be explained later. A pointer variable might
3777 also be a special flag that lies outside the bounds of |mem|, so we
3778 allow pointers to assume any |halfword| value. The minimum memory
3779 index represents a null pointer.
3780
3781 @d null 0 /* the null pointer */
3782 @d mp_void (null+1) /* a null pointer different from |null| */
3783
3784
3785 @<Types...@>=
3786 typedef halfword pointer; /* a flag or a location in |mem| or |eqtb| */
3787
3788 @ The |mem| array is divided into two regions that are allocated separately,
3789 but the dividing line between these two regions is not fixed; they grow
3790 together until finding their ``natural'' size in a particular job.
3791 Locations less than or equal to |lo_mem_max| are used for storing
3792 variable-length records consisting of two or more words each. This region
3793 is maintained using an algorithm similar to the one described in exercise
3794 2.5--19 of {\sl The Art of Computer Programming}. However, no size field
3795 appears in the allocated nodes; the program is responsible for knowing the
3796 relevant size when a node is freed. Locations greater than or equal to
3797 |hi_mem_min| are used for storing one-word records; a conventional
3798 \.{AVAIL} stack is used for allocation in this region.
3799
3800 Locations of |mem| between |0| and |mem_top| may be dumped as part
3801 of preloaded format files, by the \.{INIMP} preprocessor.
3802 @.INIMP@>
3803 Production versions of \MP\ may extend the memory at the top end in order to
3804 provide more space; these locations, between |mem_top| and |mem_max|,
3805 are always used for single-word nodes.
3806
3807 The key pointers that govern |mem| allocation have a prescribed order:
3808 $$\hbox{|null=0<lo_mem_max<hi_mem_min<mem_top<=mem_end<=mem_max|.}$$
3809
3810 @<Glob...@>=
3811 memory_word *mem; /* the big dynamic storage area */
3812 pointer lo_mem_max; /* the largest location of variable-size memory in use */
3813 pointer hi_mem_min; /* the smallest location of one-word memory in use */
3814
3815
3816
3817 @d xfree(A) do { mp_xfree(A); A=NULL; } while (0)
3818 @d xrealloc(P,A,B) mp_xrealloc(mp,P,A,B)
3819 @d xmalloc(A,B)  mp_xmalloc(mp,A,B)
3820 @d xstrdup(A)  mp_xstrdup(mp,A)
3821 @d XREALLOC(a,b,c) a = xrealloc(a,(b+1),sizeof(c));
3822
3823 @<Declare helpers@>=
3824 void mp_xfree (void *x);
3825 void *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) ;
3826 void *mp_xmalloc (MP mp, size_t nmem, size_t size) ;
3827 char *mp_xstrdup(MP mp, const char *s);
3828
3829 @ The |max_size_test| guards against overflow, on the assumption that
3830 |size_t| is at least 31bits wide.
3831
3832 @d max_size_test 0x7FFFFFFF
3833
3834 @c
3835 void mp_xfree (void *x) {
3836   if (x!=NULL) free(x);
3837 }
3838 void  *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) {
3839   void *w ; 
3840   if ((max_size_test/size)<nmem) {
3841     do_fprintf(mp->err_out,"Memory size overflow!\n");
3842     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3843   }
3844   w = realloc (p,(nmem*size));
3845   if (w==NULL) {
3846     do_fprintf(mp->err_out,"Out of memory!\n");
3847     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3848   }
3849   return w;
3850 }
3851 void  *mp_xmalloc (MP mp, size_t nmem, size_t size) {
3852   void *w;
3853   if ((max_size_test/size)<nmem) {
3854     do_fprintf(mp->err_out,"Memory size overflow!\n");
3855     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3856   }
3857   w = malloc (nmem*size);
3858   if (w==NULL) {
3859     do_fprintf(mp->err_out,"Out of memory!\n");
3860     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3861   }
3862   return w;
3863 }
3864 char *mp_xstrdup(MP mp, const char *s) {
3865   char *w; 
3866   if (s==NULL)
3867     return NULL;
3868   w = strdup(s);
3869   if (w==NULL) {
3870     do_fprintf(mp->err_out,"Out of memory!\n");
3871     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3872   }
3873   return w;
3874 }
3875
3876
3877
3878 @<Allocate or initialize ...@>=
3879 mp->mem = xmalloc ((mp->mem_max+1),sizeof (memory_word));
3880 memset(mp->mem,0,(mp->mem_max+1)*sizeof (memory_word));
3881
3882 @ @<Dealloc variables@>=
3883 xfree(mp->mem);
3884
3885 @ Users who wish to study the memory requirements of particular applications can
3886 can use optional special features that keep track of current and
3887 maximum memory usage. When code between the delimiters |stat| $\ldots$
3888 |tats| is not ``commented out,'' \MP\ will run a bit slower but it will
3889 report these statistics when |mp_tracing_stats| is positive.
3890
3891 @<Glob...@>=
3892 integer var_used; integer dyn_used; /* how much memory is in use */
3893
3894 @ Let's consider the one-word memory region first, since it's the
3895 simplest. The pointer variable |mem_end| holds the highest-numbered location
3896 of |mem| that has ever been used. The free locations of |mem| that
3897 occur between |hi_mem_min| and |mem_end|, inclusive, are of type
3898 |two_halves|, and we write |info(p)| and |link(p)| for the |lh|
3899 and |rh| fields of |mem[p]| when it is of this type. The single-word
3900 free locations form a linked list
3901 $$|avail|,\;\hbox{|link(avail)|},\;\hbox{|link(link(avail))|},\;\ldots$$
3902 terminated by |null|.
3903
3904 @d link(A)   mp->mem[(A)].hh.rh /* the |link| field of a memory word */
3905 @d info(A)   mp->mem[(A)].hh.lh /* the |info| field of a memory word */
3906
3907 @<Glob...@>=
3908 pointer avail; /* head of the list of available one-word nodes */
3909 pointer mem_end; /* the last one-word node used in |mem| */
3910
3911 @ If one-word memory is exhausted, it might mean that the user has forgotten
3912 a token like `\&{enddef}' or `\&{endfor}'. We will define some procedures
3913 later that try to help pinpoint the trouble.
3914
3915 @c 
3916 @<Declare the procedure called |show_token_list|@>;
3917 @<Declare the procedure called |runaway|@>
3918
3919 @ The function |get_avail| returns a pointer to a new one-word node whose
3920 |link| field is null. However, \MP\ will halt if there is no more room left.
3921 @^inner loop@>
3922
3923 @c 
3924 pointer mp_get_avail (MP mp) { /* single-word node allocation */
3925   pointer p; /* the new node being got */
3926   p=mp->avail; /* get top location in the |avail| stack */
3927   if ( p!=null ) {
3928     mp->avail=link(mp->avail); /* and pop it off */
3929   } else if ( mp->mem_end<mp->mem_max ) { /* or go into virgin territory */
3930     incr(mp->mem_end); p=mp->mem_end;
3931   } else { 
3932     decr(mp->hi_mem_min); p=mp->hi_mem_min;
3933     if ( mp->hi_mem_min<=mp->lo_mem_max ) { 
3934       mp_runaway(mp); /* if memory is exhausted, display possible runaway text */
3935       mp_overflow(mp, "main memory size",mp->mem_max);
3936       /* quit; all one-word nodes are busy */
3937 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
3938     }
3939   }
3940   link(p)=null; /* provide an oft-desired initialization of the new node */
3941   incr(mp->dyn_used);/* maintain statistics */
3942   return p;
3943 };
3944
3945 @ Conversely, a one-word node is recycled by calling |free_avail|.
3946
3947 @d free_avail(A)  /* single-word node liberation */
3948   { link((A))=mp->avail; mp->avail=(A); decr(mp->dyn_used);  }
3949
3950 @ There's also a |fast_get_avail| routine, which saves the procedure-call
3951 overhead at the expense of extra programming. This macro is used in
3952 the places that would otherwise account for the most calls of |get_avail|.
3953 @^inner loop@>
3954
3955 @d fast_get_avail(A) { 
3956   (A)=mp->avail; /* avoid |get_avail| if possible, to save time */
3957   if ( (A)==null ) { (A)=mp_get_avail(mp); } 
3958   else { mp->avail=link((A)); link((A))=null;  incr(mp->dyn_used); }
3959   }
3960
3961 @ The available-space list that keeps track of the variable-size portion
3962 of |mem| is a nonempty, doubly-linked circular list of empty nodes,
3963 pointed to by the roving pointer |rover|.
3964
3965 Each empty node has size 2 or more; the first word contains the special
3966 value |max_halfword| in its |link| field and the size in its |info| field;
3967 the second word contains the two pointers for double linking.
3968
3969 Each nonempty node also has size 2 or more. Its first word is of type
3970 |two_halves|\kern-1pt, and its |link| field is never equal to |max_halfword|.
3971 Otherwise there is complete flexibility with respect to the contents
3972 of its other fields and its other words.
3973
3974 (We require |mem_max<max_halfword| because terrible things can happen
3975 when |max_halfword| appears in the |link| field of a nonempty node.)
3976
3977 @d empty_flag   max_halfword /* the |link| of an empty variable-size node */
3978 @d is_empty(A)   (link((A))==empty_flag) /* tests for empty node */
3979 @d node_size   info /* the size field in empty variable-size nodes */
3980 @d llink(A)   info((A)+1) /* left link in doubly-linked list of empty nodes */
3981 @d rlink(A)   link((A)+1) /* right link in doubly-linked list of empty nodes */
3982
3983 @<Glob...@>=
3984 pointer rover; /* points to some node in the list of empties */
3985
3986 @ A call to |get_node| with argument |s| returns a pointer to a new node
3987 of size~|s|, which must be 2~or more. The |link| field of the first word
3988 of this new node is set to null. An overflow stop occurs if no suitable
3989 space exists.
3990
3991 If |get_node| is called with $s=2^{30}$, it simply merges adjacent free
3992 areas and returns the value |max_halfword|.
3993
3994 @<Internal library declarations@>=
3995 pointer mp_get_node (MP mp,integer s) ;
3996
3997 @ @c 
3998 pointer mp_get_node (MP mp,integer s) { /* variable-size node allocation */
3999   pointer p; /* the node currently under inspection */
4000   pointer q;  /* the node physically after node |p| */
4001   integer r; /* the newly allocated node, or a candidate for this honor */
4002   integer t,tt; /* temporary registers */
4003 @^inner loop@>
4004  RESTART: 
4005   p=mp->rover; /* start at some free node in the ring */
4006   do {  
4007     @<Try to allocate within node |p| and its physical successors,
4008      and |goto found| if allocation was possible@>;
4009     if (rlink(p)==null || rlink(p)==p) {
4010       print_err("Free list garbled");
4011       help3("I found an entry in the list of free nodes that links")
4012        ("badly. I will try to ignore the broken link, but something")
4013        ("is seriously amiss. It is wise to warn the maintainers.")
4014           mp_error(mp);
4015       rlink(p)=mp->rover;
4016     }
4017         p=rlink(p); /* move to the next node in the ring */
4018   } while (p!=mp->rover); /* repeat until the whole list has been traversed */
4019   if ( s==010000000000 ) { 
4020     return max_halfword;
4021   };
4022   if ( mp->lo_mem_max+2<mp->hi_mem_min ) {
4023     if ( mp->lo_mem_max+2<=max_halfword ) {
4024       @<Grow more variable-size memory and |goto restart|@>;
4025     }
4026   }
4027   mp_overflow(mp, "main memory size",mp->mem_max);
4028   /* sorry, nothing satisfactory is left */
4029 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
4030 FOUND: 
4031   link(r)=null; /* this node is now nonempty */
4032   mp->var_used+=s; /* maintain usage statistics */
4033   return r;
4034 }
4035
4036 @ The lower part of |mem| grows by 1000 words at a time, unless
4037 we are very close to going under. When it grows, we simply link
4038 a new node into the available-space list. This method of controlled
4039 growth helps to keep the |mem| usage consecutive when \MP\ is
4040 implemented on ``virtual memory'' systems.
4041 @^virtual memory@>
4042
4043 @<Grow more variable-size memory and |goto restart|@>=
4044
4045   if ( mp->hi_mem_min-mp->lo_mem_max>=1998 ) {
4046     t=mp->lo_mem_max+1000;
4047   } else {
4048     t=mp->lo_mem_max+1+(mp->hi_mem_min-mp->lo_mem_max) / 2; 
4049     /* |lo_mem_max+2<=t<hi_mem_min| */
4050   }
4051   if ( t>max_halfword ) t=max_halfword;
4052   p=llink(mp->rover); q=mp->lo_mem_max; rlink(p)=q; llink(mp->rover)=q;
4053   rlink(q)=mp->rover; llink(q)=p; link(q)=empty_flag; 
4054   node_size(q)=t-mp->lo_mem_max;
4055   mp->lo_mem_max=t; link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4056   mp->rover=q; 
4057   goto RESTART;
4058 }
4059
4060 @ @<Try to allocate...@>=
4061 q=p+node_size(p); /* find the physical successor */
4062 while ( is_empty(q) ) { /* merge node |p| with node |q| */
4063   t=rlink(q); tt=llink(q);
4064 @^inner loop@>
4065   if ( q==mp->rover ) mp->rover=t;
4066   llink(t)=tt; rlink(tt)=t;
4067   q=q+node_size(q);
4068 }
4069 r=q-s;
4070 if ( r>p+1 ) {
4071   @<Allocate from the top of node |p| and |goto found|@>;
4072 }
4073 if ( r==p ) { 
4074   if ( rlink(p)!=p ) {
4075     @<Allocate entire node |p| and |goto found|@>;
4076   }
4077 }
4078 node_size(p)=q-p /* reset the size in case it grew */
4079
4080 @ @<Allocate from the top...@>=
4081
4082   node_size(p)=r-p; /* store the remaining size */
4083   mp->rover=p; /* start searching here next time */
4084   goto FOUND;
4085 }
4086
4087 @ Here we delete node |p| from the ring, and let |rover| rove around.
4088
4089 @<Allocate entire...@>=
4090
4091   mp->rover=rlink(p); t=llink(p);
4092   llink(mp->rover)=t; rlink(t)=mp->rover;
4093   goto FOUND;
4094 }
4095
4096 @ Conversely, when some variable-size node |p| of size |s| is no longer needed,
4097 the operation |free_node(p,s)| will make its words available, by inserting
4098 |p| as a new empty node just before where |rover| now points.
4099
4100 @<Internal library declarations@>=
4101 void mp_free_node (MP mp, pointer p, halfword s) ;
4102
4103 @ @c 
4104 void mp_free_node (MP mp, pointer p, halfword s) { /* variable-size node
4105   liberation */
4106   pointer q; /* |llink(rover)| */
4107   node_size(p)=s; link(p)=empty_flag;
4108 @^inner loop@>
4109   q=llink(mp->rover); llink(p)=q; rlink(p)=mp->rover; /* set both links */
4110   llink(mp->rover)=p; rlink(q)=p; /* insert |p| into the ring */
4111   mp->var_used-=s; /* maintain statistics */
4112 }
4113
4114 @ Just before \.{INIMP} writes out the memory, it sorts the doubly linked
4115 available space list. The list is probably very short at such times, so a
4116 simple insertion sort is used. The smallest available location will be
4117 pointed to by |rover|, the next-smallest by |rlink(rover)|, etc.
4118
4119 @c 
4120 void mp_sort_avail (MP mp) { /* sorts the available variable-size nodes
4121   by location */
4122   pointer p,q,r; /* indices into |mem| */
4123   pointer old_rover; /* initial |rover| setting */
4124   p=mp_get_node(mp, 010000000000); /* merge adjacent free areas */
4125   p=rlink(mp->rover); rlink(mp->rover)=max_halfword; old_rover=mp->rover;
4126   while ( p!=old_rover ) {
4127     @<Sort |p| into the list starting at |rover|
4128      and advance |p| to |rlink(p)|@>;
4129   }
4130   p=mp->rover;
4131   while ( rlink(p)!=max_halfword ) { 
4132     llink(rlink(p))=p; p=rlink(p);
4133   };
4134   rlink(p)=mp->rover; llink(mp->rover)=p;
4135 }
4136
4137 @ The following |while| loop is guaranteed to
4138 terminate, since the list that starts at
4139 |rover| ends with |max_halfword| during the sorting procedure.
4140
4141 @<Sort |p|...@>=
4142 if ( p<mp->rover ) { 
4143   q=p; p=rlink(q); rlink(q)=mp->rover; mp->rover=q;
4144 } else  { 
4145   q=mp->rover;
4146   while ( rlink(q)<p ) q=rlink(q);
4147   r=rlink(p); rlink(p)=rlink(q); rlink(q)=p; p=r;
4148 }
4149
4150 @* \[11] Memory layout.
4151 Some areas of |mem| are dedicated to fixed usage, since static allocation is
4152 more efficient than dynamic allocation when we can get away with it. For
4153 example, locations |0| to |1| are always used to store a
4154 two-word dummy token whose second word is zero.
4155 The following macro definitions accomplish the static allocation by giving
4156 symbolic names to the fixed positions. Static variable-size nodes appear
4157 in locations |0| through |lo_mem_stat_max|, and static single-word nodes
4158 appear in locations |hi_mem_stat_min| through |mem_top|, inclusive.
4159
4160 @d null_dash (2) /* the first two words are reserved for a null value */
4161 @d dep_head (null_dash+3) /* we will define |dash_node_size=3| */
4162 @d zero_val (dep_head+2) /* two words for a permanently zero value */
4163 @d temp_val (zero_val+2) /* two words for a temporary value node */
4164 @d end_attr temp_val /* we use |end_attr+2| only */
4165 @d inf_val (end_attr+2) /* and |inf_val+1| only */
4166 @d test_pen (inf_val+2)
4167   /* nine words for a pen used when testing the turning number */
4168 @d bad_vardef (test_pen+9) /* two words for \&{vardef} error recovery */
4169 @d lo_mem_stat_max (bad_vardef+1)  /* largest statically
4170   allocated word in the variable-size |mem| */
4171 @#
4172 @d sentinel mp->mem_top /* end of sorted lists */
4173 @d temp_head (mp->mem_top-1) /* head of a temporary list of some kind */
4174 @d hold_head (mp->mem_top-2) /* head of a temporary list of another kind */
4175 @d spec_head (mp->mem_top-3) /* head of a list of unprocessed \&{special} items */
4176 @d hi_mem_stat_min (mp->mem_top-3) /* smallest statically allocated word in
4177   the one-word |mem| */
4178
4179 @ The following code gets the dynamic part of |mem| off to a good start,
4180 when \MP\ is initializing itself the slow way.
4181
4182 @<Initialize table entries (done by \.{INIMP} only)@>=
4183 @^data structure assumptions@>
4184 mp->rover=lo_mem_stat_max+1; /* initialize the dynamic memory */
4185 link(mp->rover)=empty_flag;
4186 node_size(mp->rover)=1000; /* which is a 1000-word available node */
4187 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
4188 mp->lo_mem_max=mp->rover+1000; 
4189 link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4190 for (k=hi_mem_stat_min;k<=(int)mp->mem_top;k++) {
4191   mp->mem[k]=mp->mem[mp->lo_mem_max]; /* clear list heads */
4192 }
4193 mp->avail=null; mp->mem_end=mp->mem_top;
4194 mp->hi_mem_min=hi_mem_stat_min; /* initialize the one-word memory */
4195 mp->var_used=lo_mem_stat_max+1; 
4196 mp->dyn_used=mp->mem_top+1-(hi_mem_stat_min);  /* initialize statistics */
4197 @<Initialize a pen at |test_pen| so that it fits in nine words@>;
4198
4199 @ The procedure |flush_list(p)| frees an entire linked list of one-word
4200 nodes that starts at a given position, until coming to |sentinel| or a
4201 pointer that is not in the one-word region. Another procedure,
4202 |flush_node_list|, frees an entire linked list of one-word and two-word
4203 nodes, until coming to a |null| pointer.
4204 @^inner loop@>
4205
4206 @c 
4207 void mp_flush_list (MP mp,pointer p) { /* makes list of single-word nodes  available */
4208   pointer q,r; /* list traversers */
4209   if ( p>=mp->hi_mem_min ) if ( p!=sentinel ) { 
4210     r=p;
4211     do {  
4212       q=r; r=link(r); 
4213       decr(mp->dyn_used);
4214       if ( r<mp->hi_mem_min ) break;
4215     } while (r!=sentinel);
4216   /* now |q| is the last node on the list */
4217     link(q)=mp->avail; mp->avail=p;
4218   }
4219 }
4220 @#
4221 void mp_flush_node_list (MP mp,pointer p) {
4222   pointer q; /* the node being recycled */
4223   while ( p!=null ){ 
4224     q=p; p=link(p);
4225     if ( q<mp->hi_mem_min ) 
4226       mp_free_node(mp, q,2);
4227     else 
4228       free_avail(q);
4229   }
4230 }
4231
4232 @ If \MP\ is extended improperly, the |mem| array might get screwed up.
4233 For example, some pointers might be wrong, or some ``dead'' nodes might not
4234 have been freed when the last reference to them disappeared. Procedures
4235 |check_mem| and |search_mem| are available to help diagnose such
4236 problems. These procedures make use of two arrays called |free| and
4237 |was_free| that are present only if \MP's debugging routines have
4238 been included. (You may want to decrease the size of |mem| while you
4239 @^debugging@>
4240 are debugging.)
4241
4242 Because |boolean|s are typedef-d as ints, it is better to use
4243 unsigned chars here.
4244
4245 @<Glob...@>=
4246 unsigned char *free; /* free cells */
4247 unsigned char *was_free; /* previously free cells */
4248 pointer was_mem_end; pointer was_lo_max; pointer was_hi_min;
4249   /* previous |mem_end|, |lo_mem_max|,and |hi_mem_min| */
4250 boolean panicking; /* do we want to check memory constantly? */
4251
4252 @ @<Allocate or initialize ...@>=
4253 mp->free = xmalloc ((mp->mem_max+1),sizeof (unsigned char));
4254 mp->was_free = xmalloc ((mp->mem_max+1), sizeof (unsigned char));
4255
4256 @ @<Dealloc variables@>=
4257 xfree(mp->free);
4258 xfree(mp->was_free);
4259
4260 @ @<Allocate or ...@>=
4261 mp->was_mem_end=0; /* indicate that everything was previously free */
4262 mp->was_lo_max=0; mp->was_hi_min=mp->mem_max;
4263 mp->panicking=false;
4264
4265 @ @<Declare |mp_reallocate| functions@>=
4266 void mp_reallocate_memory(MP mp, int l) ;
4267
4268 @ @c
4269 void mp_reallocate_memory(MP mp, int l) {
4270    XREALLOC(mp->free,     l, unsigned char);
4271    XREALLOC(mp->was_free, l, unsigned char);
4272    if (mp->mem) {
4273          int newarea = l-mp->mem_max;
4274      XREALLOC(mp->mem,      l, memory_word);
4275      memset (mp->mem+(mp->mem_max+1),0,sizeof(memory_word)*(newarea));
4276    } else {
4277      XREALLOC(mp->mem,      l, memory_word);
4278      memset(mp->mem,0,sizeof(memory_word)*(l+1));
4279    }
4280    mp->mem_max = l;
4281    if (mp->ini_version) 
4282      mp->mem_top = l;
4283 }
4284
4285
4286
4287 @ Procedure |check_mem| makes sure that the available space lists of
4288 |mem| are well formed, and it optionally prints out all locations
4289 that are reserved now but were free the last time this procedure was called.
4290
4291 @c 
4292 void mp_check_mem (MP mp,boolean print_locs ) {
4293   pointer p,q,r; /* current locations of interest in |mem| */
4294   boolean clobbered; /* is something amiss? */
4295   for (p=0;p<=mp->lo_mem_max;p++) {
4296     mp->free[p]=false; /* you can probably do this faster */
4297   }
4298   for (p=mp->hi_mem_min;p<= mp->mem_end;p++) {
4299     mp->free[p]=false; /* ditto */
4300   }
4301   @<Check single-word |avail| list@>;
4302   @<Check variable-size |avail| list@>;
4303   @<Check flags of unavailable nodes@>;
4304   @<Check the list of linear dependencies@>;
4305   if ( print_locs ) {
4306     @<Print newly busy locations@>;
4307   }
4308   memcpy(mp->was_free,mp->free, sizeof(char)*(mp->mem_end+1));
4309   mp->was_mem_end=mp->mem_end; 
4310   mp->was_lo_max=mp->lo_mem_max; 
4311   mp->was_hi_min=mp->hi_mem_min;
4312 }
4313
4314 @ @<Check single-word...@>=
4315 p=mp->avail; q=null; clobbered=false;
4316 while ( p!=null ) { 
4317   if ( (p>mp->mem_end)||(p<mp->hi_mem_min) ) clobbered=true;
4318   else if ( mp->free[p] ) clobbered=true;
4319   if ( clobbered ) { 
4320     mp_print_nl(mp, "AVAIL list clobbered at ");
4321 @.AVAIL list clobbered...@>
4322     mp_print_int(mp, q); break;
4323   }
4324   mp->free[p]=true; q=p; p=link(q);
4325 }
4326
4327 @ @<Check variable-size...@>=
4328 p=mp->rover; q=null; clobbered=false;
4329 do {  
4330   if ( (p>=mp->lo_mem_max)||(p<0) ) clobbered=true;
4331   else if ( (rlink(p)>=mp->lo_mem_max)||(rlink(p)<0) ) clobbered=true;
4332   else if (  !(is_empty(p))||(node_size(p)<2)||
4333    (p+node_size(p)>mp->lo_mem_max)|| (llink(rlink(p))!=p) ) clobbered=true;
4334   if ( clobbered ) { 
4335     mp_print_nl(mp, "Double-AVAIL list clobbered at ");
4336 @.Double-AVAIL list clobbered...@>
4337     mp_print_int(mp, q); break;
4338   }
4339   for (q=p;q<=p+node_size(p)-1;q++) { /* mark all locations free */
4340     if ( mp->free[q] ) { 
4341       mp_print_nl(mp, "Doubly free location at ");
4342 @.Doubly free location...@>
4343       mp_print_int(mp, q); break;
4344     }
4345     mp->free[q]=true;
4346   }
4347   q=p; p=rlink(p);
4348 } while (p!=mp->rover)
4349
4350
4351 @ @<Check flags...@>=
4352 p=0;
4353 while ( p<=mp->lo_mem_max ) { /* node |p| should not be empty */
4354   if ( is_empty(p) ) {
4355     mp_print_nl(mp, "Bad flag at "); mp_print_int(mp, p);
4356 @.Bad flag...@>
4357   }
4358   while ( (p<=mp->lo_mem_max) && ! mp->free[p] ) incr(p);
4359   while ( (p<=mp->lo_mem_max) && mp->free[p] ) incr(p);
4360 }
4361
4362 @ @<Print newly busy...@>=
4363
4364   @<Do intialization required before printing new busy locations@>;
4365   mp_print_nl(mp, "New busy locs:");
4366 @.New busy locs@>
4367   for (p=0;p<= mp->lo_mem_max;p++ ) {
4368     if ( ! mp->free[p] && ((p>mp->was_lo_max) || mp->was_free[p]) ) {
4369       @<Indicate that |p| is a new busy location@>;
4370     }
4371   }
4372   for (p=mp->hi_mem_min;p<=mp->mem_end;p++ ) {
4373     if ( ! mp->free[p] &&
4374         ((p<mp->was_hi_min) || (p>mp->was_mem_end) || mp->was_free[p]) ) {
4375       @<Indicate that |p| is a new busy location@>;
4376     }
4377   }
4378   @<Finish printing new busy locations@>;
4379 }
4380
4381 @ There might be many new busy locations so we are careful to print contiguous
4382 blocks compactly.  During this operation |q| is the last new busy location and
4383 |r| is the start of the block containing |q|.
4384
4385 @<Indicate that |p| is a new busy location@>=
4386
4387   if ( p>q+1 ) { 
4388     if ( q>r ) { 
4389       mp_print(mp, ".."); mp_print_int(mp, q);
4390     }
4391     mp_print_char(mp, ' '); mp_print_int(mp, p);
4392     r=p;
4393   }
4394   q=p;
4395 }
4396
4397 @ @<Do intialization required before printing new busy locations@>=
4398 q=mp->mem_max; r=mp->mem_max
4399
4400 @ @<Finish printing new busy locations@>=
4401 if ( q>r ) { 
4402   mp_print(mp, ".."); mp_print_int(mp, q);
4403 }
4404
4405 @ The |search_mem| procedure attempts to answer the question ``Who points
4406 to node~|p|?'' In doing so, it fetches |link| and |info| fields of |mem|
4407 that might not be of type |two_halves|. Strictly speaking, this is
4408 undefined, and it can lead to ``false drops'' (words that seem to
4409 point to |p| purely by coincidence). But for debugging purposes, we want
4410 to rule out the places that do {\sl not\/} point to |p|, so a few false
4411 drops are tolerable.
4412
4413 @c
4414 void mp_search_mem (MP mp, pointer p) { /* look for pointers to |p| */
4415   integer q; /* current position being searched */
4416   for (q=0;q<=mp->lo_mem_max;q++) { 
4417     if ( link(q)==p ){ 
4418       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4419     }
4420     if ( info(q)==p ) { 
4421       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4422     }
4423   }
4424   for (q=mp->hi_mem_min;q<=mp->mem_end;q++) {
4425     if ( link(q)==p ) {
4426       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4427     }
4428     if ( info(q)==p ) {
4429       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4430     }
4431   }
4432   @<Search |eqtb| for equivalents equal to |p|@>;
4433 }
4434
4435 @* \[12] The command codes.
4436 Before we can go much further, we need to define symbolic names for the internal
4437 code numbers that represent the various commands obeyed by \MP. These codes
4438 are somewhat arbitrary, but not completely so. For example,
4439 some codes have been made adjacent so that |case| statements in the
4440 program need not consider cases that are widely spaced, or so that |case|
4441 statements can be replaced by |if| statements. A command can begin an
4442 expression if and only if its code lies between |min_primary_command| and
4443 |max_primary_command|, inclusive. The first token of a statement that doesn't
4444 begin with an expression has a command code between |min_command| and
4445 |max_statement_command|, inclusive. Anything less than |min_command| is
4446 eliminated during macro expansions, and anything no more than |max_pre_command|
4447 is eliminated when expanding \TeX\ material.  Ranges such as
4448 |min_secondary_command..max_secondary_command| are used when parsing
4449 expressions, but the relative ordering within such a range is generally not
4450 critical.
4451
4452 The ordering of the highest-numbered commands
4453 (|comma<semicolon<end_group<stop|) is crucial for the parsing and
4454 error-recovery methods of this program as is the ordering |if_test<fi_or_else|
4455 for the smallest two commands.  The ordering is also important in the ranges
4456 |numeric_token..plus_or_minus| and |left_brace..ampersand|.
4457
4458 At any rate, here is the list, for future reference.
4459
4460 @d start_tex 1 /* begin \TeX\ material (\&{btex}, \&{verbatimtex}) */
4461 @d etex_marker 2 /* end \TeX\ material (\&{etex}) */
4462 @d mpx_break 3 /* stop reading an \.{MPX} file (\&{mpxbreak}) */
4463 @d max_pre_command mpx_break
4464 @d if_test 4 /* conditional text (\&{if}) */
4465 @d fi_or_else 5 /* delimiters for conditionals (\&{elseif}, \&{else}, \&{fi} */
4466 @d input 6 /* input a source file (\&{input}, \&{endinput}) */
4467 @d iteration 7 /* iterate (\&{for}, \&{forsuffixes}, \&{forever}, \&{endfor}) */
4468 @d repeat_loop 8 /* special command substituted for \&{endfor} */
4469 @d exit_test 9 /* premature exit from a loop (\&{exitif}) */
4470 @d relax 10 /* do nothing (\.{\char`\\}) */
4471 @d scan_tokens 11 /* put a string into the input buffer */
4472 @d expand_after 12 /* look ahead one token */
4473 @d defined_macro 13 /* a macro defined by the user */
4474 @d min_command (defined_macro+1)
4475 @d save_command 14 /* save a list of tokens (\&{save}) */
4476 @d interim_command 15 /* save an internal quantity (\&{interim}) */
4477 @d let_command 16 /* redefine a symbolic token (\&{let}) */
4478 @d new_internal 17 /* define a new internal quantity (\&{newinternal}) */
4479 @d macro_def 18 /* define a macro (\&{def}, \&{vardef}, etc.) */
4480 @d ship_out_command 19 /* output a character (\&{shipout}) */
4481 @d add_to_command 20 /* add to edges (\&{addto}) */
4482 @d bounds_command 21  /* add bounding path to edges (\&{setbounds}, \&{clip}) */
4483 @d tfm_command 22 /* command for font metric info (\&{ligtable}, etc.) */
4484 @d protection_command 23 /* set protection flag (\&{outer}, \&{inner}) */
4485 @d show_command 24 /* diagnostic output (\&{show}, \&{showvariable}, etc.) */
4486 @d mode_command 25 /* set interaction level (\&{batchmode}, etc.) */
4487 @d mp_random_seed 26 /* initialize random number generator (\&{randomseed}) */
4488 @d message_command 27 /* communicate to user (\&{message}, \&{errmessage}) */
4489 @d every_job_command 28 /* designate a starting token (\&{everyjob}) */
4490 @d delimiters 29 /* define a pair of delimiters (\&{delimiters}) */
4491 @d special_command 30 /* output special info (\&{special})
4492                        or font map info (\&{fontmapfile}, \&{fontmapline}) */
4493 @d write_command 31 /* write text to a file (\&{write}) */
4494 @d type_name 32 /* declare a type (\&{numeric}, \&{pair}, etc. */
4495 @d max_statement_command type_name
4496 @d min_primary_command type_name
4497 @d left_delimiter 33 /* the left delimiter of a matching pair */
4498 @d begin_group 34 /* beginning of a group (\&{begingroup}) */
4499 @d nullary 35 /* an operator without arguments (e.g., \&{normaldeviate}) */
4500 @d unary 36 /* an operator with one argument (e.g., \&{sqrt}) */
4501 @d str_op 37 /* convert a suffix to a string (\&{str}) */
4502 @d cycle 38 /* close a cyclic path (\&{cycle}) */
4503 @d primary_binary 39 /* binary operation taking `\&{of}' (e.g., \&{point}) */
4504 @d capsule_token 40 /* a value that has been put into a token list */
4505 @d string_token 41 /* a string constant (e.g., |"hello"|) */
4506 @d internal_quantity 42 /* internal numeric parameter (e.g., \&{pausing}) */
4507 @d min_suffix_token internal_quantity
4508 @d tag_token 43 /* a symbolic token without a primitive meaning */
4509 @d numeric_token 44 /* a numeric constant (e.g., \.{3.14159}) */
4510 @d max_suffix_token numeric_token
4511 @d plus_or_minus 45 /* either `\.+' or `\.-' */
4512 @d max_primary_command plus_or_minus /* should also be |numeric_token+1| */
4513 @d min_tertiary_command plus_or_minus
4514 @d tertiary_secondary_macro 46 /* a macro defined by \&{secondarydef} */
4515 @d tertiary_binary 47 /* an operator at the tertiary level (e.g., `\.{++}') */
4516 @d max_tertiary_command tertiary_binary
4517 @d left_brace 48 /* the operator `\.{\char`\{}' */
4518 @d min_expression_command left_brace
4519 @d path_join 49 /* the operator `\.{..}' */
4520 @d ampersand 50 /* the operator `\.\&' */
4521 @d expression_tertiary_macro 51 /* a macro defined by \&{tertiarydef} */
4522 @d expression_binary 52 /* an operator at the expression level (e.g., `\.<') */
4523 @d equals 53 /* the operator `\.=' */
4524 @d max_expression_command equals
4525 @d and_command 54 /* the operator `\&{and}' */
4526 @d min_secondary_command and_command
4527 @d secondary_primary_macro 55 /* a macro defined by \&{primarydef} */
4528 @d slash 56 /* the operator `\./' */
4529 @d secondary_binary 57 /* an operator at the binary level (e.g., \&{shifted}) */
4530 @d max_secondary_command secondary_binary
4531 @d param_type 58 /* type of parameter (\&{primary}, \&{expr}, \&{suffix}, etc.) */
4532 @d controls 59 /* specify control points explicitly (\&{controls}) */
4533 @d tension 60 /* specify tension between knots (\&{tension}) */
4534 @d at_least 61 /* bounded tension value (\&{atleast}) */
4535 @d curl_command 62 /* specify curl at an end knot (\&{curl}) */
4536 @d macro_special 63 /* special macro operators (\&{quote}, \.{\#\AT!}, etc.) */
4537 @d right_delimiter 64 /* the right delimiter of a matching pair */
4538 @d left_bracket 65 /* the operator `\.[' */
4539 @d right_bracket 66 /* the operator `\.]' */
4540 @d right_brace 67 /* the operator `\.{\char`\}}' */
4541 @d with_option 68 /* option for filling (\&{withpen}, \&{withweight}, etc.) */
4542 @d thing_to_add 69
4543   /* variant of \&{addto} (\&{contour}, \&{doublepath}, \&{also}) */
4544 @d of_token 70 /* the operator `\&{of}' */
4545 @d to_token 71 /* the operator `\&{to}' */
4546 @d step_token 72 /* the operator `\&{step}' */
4547 @d until_token 73 /* the operator `\&{until}' */
4548 @d within_token 74 /* the operator `\&{within}' */
4549 @d lig_kern_token 75
4550   /* the operators `\&{kern}' and `\.{=:}' and `\.{=:\char'174}, etc. */
4551 @d assignment 76 /* the operator `\.{:=}' */
4552 @d skip_to 77 /* the operation `\&{skipto}' */
4553 @d bchar_label 78 /* the operator `\.{\char'174\char'174:}' */
4554 @d double_colon 79 /* the operator `\.{::}' */
4555 @d colon 80 /* the operator `\.:' */
4556 @#
4557 @d comma 81 /* the operator `\.,', must be |colon+1| */
4558 @d end_of_statement (mp->cur_cmd>comma)
4559 @d semicolon 82 /* the operator `\.;', must be |comma+1| */
4560 @d end_group 83 /* end a group (\&{endgroup}), must be |semicolon+1| */
4561 @d stop 84 /* end a job (\&{end}, \&{dump}), must be |end_group+1| */
4562 @d max_command_code stop
4563 @d outer_tag (max_command_code+1) /* protection code added to command code */
4564
4565 @<Types...@>=
4566 typedef int command_code;
4567
4568 @ Variables and capsules in \MP\ have a variety of ``types,''
4569 distinguished by the code numbers defined here. These numbers are also
4570 not completely arbitrary.  Things that get expanded must have types
4571 |>mp_independent|; a type remaining after expansion is numeric if and only if
4572 its code number is at least |numeric_type|; objects containing numeric
4573 parts must have types between |transform_type| and |pair_type|;
4574 all other types must be smaller than |transform_type|; and among the types
4575 that are not unknown or vacuous, the smallest two must be |boolean_type|
4576 and |string_type| in that order.
4577  
4578 @d undefined 0 /* no type has been declared */
4579 @d unknown_tag 1 /* this constant is added to certain type codes below */
4580 @d unknown_types mp_unknown_boolean: case mp_unknown_string:
4581   case mp_unknown_pen: case mp_unknown_picture: case mp_unknown_path
4582
4583 @<Types...@>=
4584 enum mp_variable_type {
4585 mp_vacuous=1, /* no expression was present */
4586 mp_boolean_type, /* \&{boolean} with a known value */
4587 mp_unknown_boolean,
4588 mp_string_type, /* \&{string} with a known value */
4589 mp_unknown_string,
4590 mp_pen_type, /* \&{pen} with a known value */
4591 mp_unknown_pen,
4592 mp_path_type, /* \&{path} with a known value */
4593 mp_unknown_path,
4594 mp_picture_type, /* \&{picture} with a known value */
4595 mp_unknown_picture,
4596 mp_transform_type, /* \&{transform} variable or capsule */
4597 mp_color_type, /* \&{color} variable or capsule */
4598 mp_cmykcolor_type, /* \&{cmykcolor} variable or capsule */
4599 mp_pair_type, /* \&{pair} variable or capsule */
4600 mp_numeric_type, /* variable that has been declared \&{numeric} but not used */
4601 mp_known, /* \&{numeric} with a known value */
4602 mp_dependent, /* a linear combination with |fraction| coefficients */
4603 mp_proto_dependent, /* a linear combination with |scaled| coefficients */
4604 mp_independent, /* \&{numeric} with unknown value */
4605 mp_token_list, /* variable name or suffix argument or text argument */
4606 mp_structured, /* variable with subscripts and attributes */
4607 mp_unsuffixed_macro, /* variable defined with \&{vardef} but no \.{\AT!\#} */
4608 mp_suffixed_macro /* variable defined with \&{vardef} and \.{\AT!\#} */
4609 } ;
4610
4611 @ @<Declarations@>=
4612 void mp_print_type (MP mp,small_number t) ;
4613
4614 @ @<Basic printing procedures@>=
4615 void mp_print_type (MP mp,small_number t) { 
4616   switch (t) {
4617   case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
4618   case mp_boolean_type:mp_print(mp, "boolean"); break;
4619   case mp_unknown_boolean:mp_print(mp, "unknown boolean"); break;
4620   case mp_string_type:mp_print(mp, "string"); break;
4621   case mp_unknown_string:mp_print(mp, "unknown string"); break;
4622   case mp_pen_type:mp_print(mp, "pen"); break;
4623   case mp_unknown_pen:mp_print(mp, "unknown pen"); break;
4624   case mp_path_type:mp_print(mp, "path"); break;
4625   case mp_unknown_path:mp_print(mp, "unknown path"); break;
4626   case mp_picture_type:mp_print(mp, "picture"); break;
4627   case mp_unknown_picture:mp_print(mp, "unknown picture"); break;
4628   case mp_transform_type:mp_print(mp, "transform"); break;
4629   case mp_color_type:mp_print(mp, "color"); break;
4630   case mp_cmykcolor_type:mp_print(mp, "cmykcolor"); break;
4631   case mp_pair_type:mp_print(mp, "pair"); break;
4632   case mp_known:mp_print(mp, "known numeric"); break;
4633   case mp_dependent:mp_print(mp, "dependent"); break;
4634   case mp_proto_dependent:mp_print(mp, "proto-dependent"); break;
4635   case mp_numeric_type:mp_print(mp, "numeric"); break;
4636   case mp_independent:mp_print(mp, "independent"); break;
4637   case mp_token_list:mp_print(mp, "token list"); break;
4638   case mp_structured:mp_print(mp, "mp_structured"); break;
4639   case mp_unsuffixed_macro:mp_print(mp, "unsuffixed macro"); break;
4640   case mp_suffixed_macro:mp_print(mp, "suffixed macro"); break;
4641   default: mp_print(mp, "undefined"); break;
4642   }
4643 }
4644
4645 @ Values inside \MP\ are stored in two-word nodes that have a |name_type|
4646 as well as a |type|. The possibilities for |name_type| are defined
4647 here; they will be explained in more detail later.
4648
4649 @<Types...@>=
4650 enum mp_name_type {
4651  mp_root=0, /* |name_type| at the top level of a variable */
4652  mp_saved_root, /* same, when the variable has been saved */
4653  mp_structured_root, /* |name_type| where a |mp_structured| branch occurs */
4654  mp_subscr, /* |name_type| in a subscript node */
4655  mp_attr, /* |name_type| in an attribute node */
4656  mp_x_part_sector, /* |name_type| in the \&{xpart} of a node */
4657  mp_y_part_sector, /* |name_type| in the \&{ypart} of a node */
4658  mp_xx_part_sector, /* |name_type| in the \&{xxpart} of a node */
4659  mp_xy_part_sector, /* |name_type| in the \&{xypart} of a node */
4660  mp_yx_part_sector, /* |name_type| in the \&{yxpart} of a node */
4661  mp_yy_part_sector, /* |name_type| in the \&{yypart} of a node */
4662  mp_red_part_sector, /* |name_type| in the \&{redpart} of a node */
4663  mp_green_part_sector, /* |name_type| in the \&{greenpart} of a node */
4664  mp_blue_part_sector, /* |name_type| in the \&{bluepart} of a node */
4665  mp_cyan_part_sector, /* |name_type| in the \&{redpart} of a node */
4666  mp_magenta_part_sector, /* |name_type| in the \&{greenpart} of a node */
4667  mp_yellow_part_sector, /* |name_type| in the \&{bluepart} of a node */
4668  mp_black_part_sector, /* |name_type| in the \&{greenpart} of a node */
4669  mp_grey_part_sector, /* |name_type| in the \&{bluepart} of a node */
4670  mp_capsule, /* |name_type| in stashed-away subexpressions */
4671  mp_token  /* |name_type| in a numeric token or string token */
4672 };
4673
4674 @ Primitive operations that produce values have a secondary identification
4675 code in addition to their command code; it's something like genera and species.
4676 For example, `\.*' has the command code |primary_binary|, and its
4677 secondary identification is |times|. The secondary codes start at 30 so that
4678 they don't overlap with the type codes; some type codes (e.g., |mp_string_type|)
4679 are used as operators as well as type identifications.  The relative values
4680 are not critical, except for |true_code..false_code|, |or_op..and_op|,
4681 and |filled_op..bounded_op|.  The restrictions are that
4682 |and_op-false_code=or_op-true_code|, that the ordering of
4683 |x_part...blue_part| must match that of |x_part_sector..mp_blue_part_sector|,
4684 and the ordering of |filled_op..bounded_op| must match that of the code
4685 values they test for.
4686
4687 @d true_code 30 /* operation code for \.{true} */
4688 @d false_code 31 /* operation code for \.{false} */
4689 @d null_picture_code 32 /* operation code for \.{nullpicture} */
4690 @d null_pen_code 33 /* operation code for \.{nullpen} */
4691 @d job_name_op 34 /* operation code for \.{jobname} */
4692 @d read_string_op 35 /* operation code for \.{readstring} */
4693 @d pen_circle 36 /* operation code for \.{pencircle} */
4694 @d normal_deviate 37 /* operation code for \.{normaldeviate} */
4695 @d read_from_op 38 /* operation code for \.{readfrom} */
4696 @d close_from_op 39 /* operation code for \.{closefrom} */
4697 @d odd_op 40 /* operation code for \.{odd} */
4698 @d known_op 41 /* operation code for \.{known} */
4699 @d unknown_op 42 /* operation code for \.{unknown} */
4700 @d not_op 43 /* operation code for \.{not} */
4701 @d decimal 44 /* operation code for \.{decimal} */
4702 @d reverse 45 /* operation code for \.{reverse} */
4703 @d make_path_op 46 /* operation code for \.{makepath} */
4704 @d make_pen_op 47 /* operation code for \.{makepen} */
4705 @d oct_op 48 /* operation code for \.{oct} */
4706 @d hex_op 49 /* operation code for \.{hex} */
4707 @d ASCII_op 50 /* operation code for \.{ASCII} */
4708 @d char_op 51 /* operation code for \.{char} */
4709 @d length_op 52 /* operation code for \.{length} */
4710 @d turning_op 53 /* operation code for \.{turningnumber} */
4711 @d color_model_part 54 /* operation code for \.{colormodel} */
4712 @d x_part 55 /* operation code for \.{xpart} */
4713 @d y_part 56 /* operation code for \.{ypart} */
4714 @d xx_part 57 /* operation code for \.{xxpart} */
4715 @d xy_part 58 /* operation code for \.{xypart} */
4716 @d yx_part 59 /* operation code for \.{yxpart} */
4717 @d yy_part 60 /* operation code for \.{yypart} */
4718 @d red_part 61 /* operation code for \.{redpart} */
4719 @d green_part 62 /* operation code for \.{greenpart} */
4720 @d blue_part 63 /* operation code for \.{bluepart} */
4721 @d cyan_part 64 /* operation code for \.{cyanpart} */
4722 @d magenta_part 65 /* operation code for \.{magentapart} */
4723 @d yellow_part 66 /* operation code for \.{yellowpart} */
4724 @d black_part 67 /* operation code for \.{blackpart} */
4725 @d grey_part 68 /* operation code for \.{greypart} */
4726 @d font_part 69 /* operation code for \.{fontpart} */
4727 @d text_part 70 /* operation code for \.{textpart} */
4728 @d path_part 71 /* operation code for \.{pathpart} */
4729 @d pen_part 72 /* operation code for \.{penpart} */
4730 @d dash_part 73 /* operation code for \.{dashpart} */
4731 @d sqrt_op 74 /* operation code for \.{sqrt} */
4732 @d m_exp_op 75 /* operation code for \.{mexp} */
4733 @d m_log_op 76 /* operation code for \.{mlog} */
4734 @d sin_d_op 77 /* operation code for \.{sind} */
4735 @d cos_d_op 78 /* operation code for \.{cosd} */
4736 @d floor_op 79 /* operation code for \.{floor} */
4737 @d uniform_deviate 80 /* operation code for \.{uniformdeviate} */
4738 @d char_exists_op 81 /* operation code for \.{charexists} */
4739 @d font_size 82 /* operation code for \.{fontsize} */
4740 @d ll_corner_op 83 /* operation code for \.{llcorner} */
4741 @d lr_corner_op 84 /* operation code for \.{lrcorner} */
4742 @d ul_corner_op 85 /* operation code for \.{ulcorner} */
4743 @d ur_corner_op 86 /* operation code for \.{urcorner} */
4744 @d arc_length 87 /* operation code for \.{arclength} */
4745 @d angle_op 88 /* operation code for \.{angle} */
4746 @d cycle_op 89 /* operation code for \.{cycle} */
4747 @d filled_op 90 /* operation code for \.{filled} */
4748 @d stroked_op 91 /* operation code for \.{stroked} */
4749 @d textual_op 92 /* operation code for \.{textual} */
4750 @d clipped_op 93 /* operation code for \.{clipped} */
4751 @d bounded_op 94 /* operation code for \.{bounded} */
4752 @d plus 95 /* operation code for \.+ */
4753 @d minus 96 /* operation code for \.- */
4754 @d times 97 /* operation code for \.* */
4755 @d over 98 /* operation code for \./ */
4756 @d pythag_add 99 /* operation code for \.{++} */
4757 @d pythag_sub 100 /* operation code for \.{+-+} */
4758 @d or_op 101 /* operation code for \.{or} */
4759 @d and_op 102 /* operation code for \.{and} */
4760 @d less_than 103 /* operation code for \.< */
4761 @d less_or_equal 104 /* operation code for \.{<=} */
4762 @d greater_than 105 /* operation code for \.> */
4763 @d greater_or_equal 106 /* operation code for \.{>=} */
4764 @d equal_to 107 /* operation code for \.= */
4765 @d unequal_to 108 /* operation code for \.{<>} */
4766 @d concatenate 109 /* operation code for \.\& */
4767 @d rotated_by 110 /* operation code for \.{rotated} */
4768 @d slanted_by 111 /* operation code for \.{slanted} */
4769 @d scaled_by 112 /* operation code for \.{scaled} */
4770 @d shifted_by 113 /* operation code for \.{shifted} */
4771 @d transformed_by 114 /* operation code for \.{transformed} */
4772 @d x_scaled 115 /* operation code for \.{xscaled} */
4773 @d y_scaled 116 /* operation code for \.{yscaled} */
4774 @d z_scaled 117 /* operation code for \.{zscaled} */
4775 @d in_font 118 /* operation code for \.{infont} */
4776 @d intersect 119 /* operation code for \.{intersectiontimes} */
4777 @d double_dot 120 /* operation code for improper \.{..} */
4778 @d substring_of 121 /* operation code for \.{substring} */
4779 @d min_of substring_of
4780 @d subpath_of 122 /* operation code for \.{subpath} */
4781 @d direction_time_of 123 /* operation code for \.{directiontime} */
4782 @d point_of 124 /* operation code for \.{point} */
4783 @d precontrol_of 125 /* operation code for \.{precontrol} */
4784 @d postcontrol_of 126 /* operation code for \.{postcontrol} */
4785 @d pen_offset_of 127 /* operation code for \.{penoffset} */
4786 @d arc_time_of 128 /* operation code for \.{arctime} */
4787 @d mp_version 129 /* operation code for \.{mpversion} */
4788 @d envelope_of 130 /* operation code for \.{envelope} */
4789
4790 @c void mp_print_op (MP mp,quarterword c) { 
4791   if (c<=mp_numeric_type ) {
4792     mp_print_type(mp, c);
4793   } else {
4794     switch (c) {
4795     case true_code:mp_print(mp, "true"); break;
4796     case false_code:mp_print(mp, "false"); break;
4797     case null_picture_code:mp_print(mp, "nullpicture"); break;
4798     case null_pen_code:mp_print(mp, "nullpen"); break;
4799     case job_name_op:mp_print(mp, "jobname"); break;
4800     case read_string_op:mp_print(mp, "readstring"); break;
4801     case pen_circle:mp_print(mp, "pencircle"); break;
4802     case normal_deviate:mp_print(mp, "normaldeviate"); break;
4803     case read_from_op:mp_print(mp, "readfrom"); break;
4804     case close_from_op:mp_print(mp, "closefrom"); break;
4805     case odd_op:mp_print(mp, "odd"); break;
4806     case known_op:mp_print(mp, "known"); break;
4807     case unknown_op:mp_print(mp, "unknown"); break;
4808     case not_op:mp_print(mp, "not"); break;
4809     case decimal:mp_print(mp, "decimal"); break;
4810     case reverse:mp_print(mp, "reverse"); break;
4811     case make_path_op:mp_print(mp, "makepath"); break;
4812     case make_pen_op:mp_print(mp, "makepen"); break;
4813     case oct_op:mp_print(mp, "oct"); break;
4814     case hex_op:mp_print(mp, "hex"); break;
4815     case ASCII_op:mp_print(mp, "ASCII"); break;
4816     case char_op:mp_print(mp, "char"); break;
4817     case length_op:mp_print(mp, "length"); break;
4818     case turning_op:mp_print(mp, "turningnumber"); break;
4819     case x_part:mp_print(mp, "xpart"); break;
4820     case y_part:mp_print(mp, "ypart"); break;
4821     case xx_part:mp_print(mp, "xxpart"); break;
4822     case xy_part:mp_print(mp, "xypart"); break;
4823     case yx_part:mp_print(mp, "yxpart"); break;
4824     case yy_part:mp_print(mp, "yypart"); break;
4825     case red_part:mp_print(mp, "redpart"); break;
4826     case green_part:mp_print(mp, "greenpart"); break;
4827     case blue_part:mp_print(mp, "bluepart"); break;
4828     case cyan_part:mp_print(mp, "cyanpart"); break;
4829     case magenta_part:mp_print(mp, "magentapart"); break;
4830     case yellow_part:mp_print(mp, "yellowpart"); break;
4831     case black_part:mp_print(mp, "blackpart"); break;
4832     case grey_part:mp_print(mp, "greypart"); break;
4833     case color_model_part:mp_print(mp, "colormodel"); break;
4834     case font_part:mp_print(mp, "fontpart"); break;
4835     case text_part:mp_print(mp, "textpart"); break;
4836     case path_part:mp_print(mp, "pathpart"); break;
4837     case pen_part:mp_print(mp, "penpart"); break;
4838     case dash_part:mp_print(mp, "dashpart"); break;
4839     case sqrt_op:mp_print(mp, "sqrt"); break;
4840     case m_exp_op:mp_print(mp, "mexp"); break;
4841     case m_log_op:mp_print(mp, "mlog"); break;
4842     case sin_d_op:mp_print(mp, "sind"); break;
4843     case cos_d_op:mp_print(mp, "cosd"); break;
4844     case floor_op:mp_print(mp, "floor"); break;
4845     case uniform_deviate:mp_print(mp, "uniformdeviate"); break;
4846     case char_exists_op:mp_print(mp, "charexists"); break;
4847     case font_size:mp_print(mp, "fontsize"); break;
4848     case ll_corner_op:mp_print(mp, "llcorner"); break;
4849     case lr_corner_op:mp_print(mp, "lrcorner"); break;
4850     case ul_corner_op:mp_print(mp, "ulcorner"); break;
4851     case ur_corner_op:mp_print(mp, "urcorner"); break;
4852     case arc_length:mp_print(mp, "arclength"); break;
4853     case angle_op:mp_print(mp, "angle"); break;
4854     case cycle_op:mp_print(mp, "cycle"); break;
4855     case filled_op:mp_print(mp, "filled"); break;
4856     case stroked_op:mp_print(mp, "stroked"); break;
4857     case textual_op:mp_print(mp, "textual"); break;
4858     case clipped_op:mp_print(mp, "clipped"); break;
4859     case bounded_op:mp_print(mp, "bounded"); break;
4860     case plus:mp_print_char(mp, '+'); break;
4861     case minus:mp_print_char(mp, '-'); break;
4862     case times:mp_print_char(mp, '*'); break;
4863     case over:mp_print_char(mp, '/'); break;
4864     case pythag_add:mp_print(mp, "++"); break;
4865     case pythag_sub:mp_print(mp, "+-+"); break;
4866     case or_op:mp_print(mp, "or"); break;
4867     case and_op:mp_print(mp, "and"); break;
4868     case less_than:mp_print_char(mp, '<'); break;
4869     case less_or_equal:mp_print(mp, "<="); break;
4870     case greater_than:mp_print_char(mp, '>'); break;
4871     case greater_or_equal:mp_print(mp, ">="); break;
4872     case equal_to:mp_print_char(mp, '='); break;
4873     case unequal_to:mp_print(mp, "<>"); break;
4874     case concatenate:mp_print(mp, "&"); break;
4875     case rotated_by:mp_print(mp, "rotated"); break;
4876     case slanted_by:mp_print(mp, "slanted"); break;
4877     case scaled_by:mp_print(mp, "scaled"); break;
4878     case shifted_by:mp_print(mp, "shifted"); break;
4879     case transformed_by:mp_print(mp, "transformed"); break;
4880     case x_scaled:mp_print(mp, "xscaled"); break;
4881     case y_scaled:mp_print(mp, "yscaled"); break;
4882     case z_scaled:mp_print(mp, "zscaled"); break;
4883     case in_font:mp_print(mp, "infont"); break;
4884     case intersect:mp_print(mp, "intersectiontimes"); break;
4885     case substring_of:mp_print(mp, "substring"); break;
4886     case subpath_of:mp_print(mp, "subpath"); break;
4887     case direction_time_of:mp_print(mp, "directiontime"); break;
4888     case point_of:mp_print(mp, "point"); break;
4889     case precontrol_of:mp_print(mp, "precontrol"); break;
4890     case postcontrol_of:mp_print(mp, "postcontrol"); break;
4891     case pen_offset_of:mp_print(mp, "penoffset"); break;
4892     case arc_time_of:mp_print(mp, "arctime"); break;
4893     case mp_version:mp_print(mp, "mpversion"); break;
4894     case envelope_of:mp_print(mp, "envelope"); break;
4895     default: mp_print(mp, ".."); break;
4896     }
4897   }
4898 }
4899
4900 @ \MP\ also has a bunch of internal parameters that a user might want to
4901 fuss with. Every such parameter has an identifying code number, defined here.
4902
4903 @<Types...@>=
4904 enum mp_given_internal {
4905   mp_tracing_titles=1, /* show titles online when they appear */
4906   mp_tracing_equations, /* show each variable when it becomes known */
4907   mp_tracing_capsules, /* show capsules too */
4908   mp_tracing_choices, /* show the control points chosen for paths */
4909   mp_tracing_specs, /* show path subdivision prior to filling with polygonal a pen */
4910   mp_tracing_commands, /* show commands and operations before they are performed */
4911   mp_tracing_restores, /* show when a variable or internal is restored */
4912   mp_tracing_macros, /* show macros before they are expanded */
4913   mp_tracing_output, /* show digitized edges as they are output */
4914   mp_tracing_stats, /* show memory usage at end of job */
4915   mp_tracing_lost_chars, /* show characters that aren't \&{infont} */
4916   mp_tracing_online, /* show long diagnostics on terminal and in the log file */
4917   mp_year, /* the current year (e.g., 1984) */
4918   mp_month, /* the current month (e.g, 3 $\equiv$ March) */
4919   mp_day, /* the current day of the month */
4920   mp_time, /* the number of minutes past midnight when this job started */
4921   mp_char_code, /* the number of the next character to be output */
4922   mp_char_ext, /* the extension code of the next character to be output */
4923   mp_char_wd, /* the width of the next character to be output */
4924   mp_char_ht, /* the height of the next character to be output */
4925   mp_char_dp, /* the depth of the next character to be output */
4926   mp_char_ic, /* the italic correction of the next character to be output */
4927   mp_design_size, /* the unit of measure used for |mp_char_wd..mp_char_ic|, in points */
4928   mp_pausing, /* positive to display lines on the terminal before they are read */
4929   mp_showstopping, /* positive to stop after each \&{show} command */
4930   mp_fontmaking, /* positive if font metric output is to be produced */
4931   mp_linejoin, /* as in \ps: 0 for mitered, 1 for round, 2 for beveled */
4932   mp_linecap, /* as in \ps: 0 for butt, 1 for round, 2 for square */
4933   mp_miterlimit, /* controls miter length as in \ps */
4934   mp_warning_check, /* controls error message when variable value is large */
4935   mp_boundary_char, /* the right boundary character for ligatures */
4936   mp_prologues, /* positive to output conforming PostScript using built-in fonts */
4937   mp_true_corners, /* positive to make \&{llcorner} etc. ignore \&{setbounds} */
4938   mp_default_color_model, /* the default color model for unspecified items */
4939   mp_restore_clip_color,
4940   mp_procset, /* wether or not create PostScript command shortcuts */
4941   mp_gtroffmode,  /* whether the user specified |-troff| on the command line */
4942 };
4943
4944 @
4945
4946 @d max_given_internal mp_gtroffmode
4947
4948 @<Glob...@>=
4949 scaled *internal;  /* the values of internal quantities */
4950 char **int_name;  /* their names */
4951 int int_ptr;  /* the maximum internal quantity defined so far */
4952 int max_internal; /* current maximum number of internal quantities */
4953
4954 @ @<Option variables@>=
4955 int troff_mode; 
4956
4957 @ @<Allocate or initialize ...@>=
4958 mp->max_internal=2*max_given_internal;
4959 mp->internal = xmalloc ((mp->max_internal+1), sizeof(scaled));
4960 mp->int_name = xmalloc ((mp->max_internal+1), sizeof(char *));
4961 mp->troff_mode=(opt->troff_mode>0 ? true : false);
4962
4963 @ @<Exported function ...@>=
4964 int mp_troff_mode(MP mp);
4965
4966 @ @c
4967 int mp_troff_mode(MP mp) { return mp->troff_mode; }
4968
4969 @ @<Set initial ...@>=
4970 for (k=0;k<= mp->max_internal; k++ ) { 
4971    mp->internal[k]=0; 
4972    mp->int_name[k]=NULL; 
4973 }
4974 mp->int_ptr=max_given_internal;
4975
4976 @ The symbolic names for internal quantities are put into \MP's hash table
4977 by using a routine called |primitive|, which will be defined later. Let us
4978 enter them now, so that we don't have to list all those names again
4979 anywhere else.
4980
4981 @<Put each of \MP's primitives into the hash table@>=
4982 mp_primitive(mp, "tracingtitles",internal_quantity,mp_tracing_titles);
4983 @:tracingtitles_}{\&{tracingtitles} primitive@>
4984 mp_primitive(mp, "tracingequations",internal_quantity,mp_tracing_equations);
4985 @:mp_tracing_equations_}{\&{tracingequations} primitive@>
4986 mp_primitive(mp, "tracingcapsules",internal_quantity,mp_tracing_capsules);
4987 @:mp_tracing_capsules_}{\&{tracingcapsules} primitive@>
4988 mp_primitive(mp, "tracingchoices",internal_quantity,mp_tracing_choices);
4989 @:mp_tracing_choices_}{\&{tracingchoices} primitive@>
4990 mp_primitive(mp, "tracingspecs",internal_quantity,mp_tracing_specs);
4991 @:mp_tracing_specs_}{\&{tracingspecs} primitive@>
4992 mp_primitive(mp, "tracingcommands",internal_quantity,mp_tracing_commands);
4993 @:mp_tracing_commands_}{\&{tracingcommands} primitive@>
4994 mp_primitive(mp, "tracingrestores",internal_quantity,mp_tracing_restores);
4995 @:mp_tracing_restores_}{\&{tracingrestores} primitive@>
4996 mp_primitive(mp, "tracingmacros",internal_quantity,mp_tracing_macros);
4997 @:mp_tracing_macros_}{\&{tracingmacros} primitive@>
4998 mp_primitive(mp, "tracingoutput",internal_quantity,mp_tracing_output);
4999 @:mp_tracing_output_}{\&{tracingoutput} primitive@>
5000 mp_primitive(mp, "tracingstats",internal_quantity,mp_tracing_stats);
5001 @:mp_tracing_stats_}{\&{tracingstats} primitive@>
5002 mp_primitive(mp, "tracinglostchars",internal_quantity,mp_tracing_lost_chars);
5003 @:mp_tracing_lost_chars_}{\&{tracinglostchars} primitive@>
5004 mp_primitive(mp, "tracingonline",internal_quantity,mp_tracing_online);
5005 @:mp_tracing_online_}{\&{tracingonline} primitive@>
5006 mp_primitive(mp, "year",internal_quantity,mp_year);
5007 @:mp_year_}{\&{year} primitive@>
5008 mp_primitive(mp, "month",internal_quantity,mp_month);
5009 @:mp_month_}{\&{month} primitive@>
5010 mp_primitive(mp, "day",internal_quantity,mp_day);
5011 @:mp_day_}{\&{day} primitive@>
5012 mp_primitive(mp, "time",internal_quantity,mp_time);
5013 @:time_}{\&{time} primitive@>
5014 mp_primitive(mp, "charcode",internal_quantity,mp_char_code);
5015 @:mp_char_code_}{\&{charcode} primitive@>
5016 mp_primitive(mp, "charext",internal_quantity,mp_char_ext);
5017 @:mp_char_ext_}{\&{charext} primitive@>
5018 mp_primitive(mp, "charwd",internal_quantity,mp_char_wd);
5019 @:mp_char_wd_}{\&{charwd} primitive@>
5020 mp_primitive(mp, "charht",internal_quantity,mp_char_ht);
5021 @:mp_char_ht_}{\&{charht} primitive@>
5022 mp_primitive(mp, "chardp",internal_quantity,mp_char_dp);
5023 @:mp_char_dp_}{\&{chardp} primitive@>
5024 mp_primitive(mp, "charic",internal_quantity,mp_char_ic);
5025 @:mp_char_ic_}{\&{charic} primitive@>
5026 mp_primitive(mp, "designsize",internal_quantity,mp_design_size);
5027 @:mp_design_size_}{\&{designsize} primitive@>
5028 mp_primitive(mp, "pausing",internal_quantity,mp_pausing);
5029 @:mp_pausing_}{\&{pausing} primitive@>
5030 mp_primitive(mp, "showstopping",internal_quantity,mp_showstopping);
5031 @:mp_showstopping_}{\&{showstopping} primitive@>
5032 mp_primitive(mp, "fontmaking",internal_quantity,mp_fontmaking);
5033 @:mp_fontmaking_}{\&{fontmaking} primitive@>
5034 mp_primitive(mp, "linejoin",internal_quantity,mp_linejoin);
5035 @:mp_linejoin_}{\&{linejoin} primitive@>
5036 mp_primitive(mp, "linecap",internal_quantity,mp_linecap);
5037 @:mp_linecap_}{\&{linecap} primitive@>
5038 mp_primitive(mp, "miterlimit",internal_quantity,mp_miterlimit);
5039 @:mp_miterlimit_}{\&{miterlimit} primitive@>
5040 mp_primitive(mp, "warningcheck",internal_quantity,mp_warning_check);
5041 @:mp_warning_check_}{\&{warningcheck} primitive@>
5042 mp_primitive(mp, "boundarychar",internal_quantity,mp_boundary_char);
5043 @:mp_boundary_char_}{\&{boundarychar} primitive@>
5044 mp_primitive(mp, "prologues",internal_quantity,mp_prologues);
5045 @:mp_prologues_}{\&{prologues} primitive@>
5046 mp_primitive(mp, "truecorners",internal_quantity,mp_true_corners);
5047 @:mp_true_corners_}{\&{truecorners} primitive@>
5048 mp_primitive(mp, "mpprocset",internal_quantity,mp_procset);
5049 @:mp_procset_}{\&{mpprocset} primitive@>
5050 mp_primitive(mp, "troffmode",internal_quantity,mp_gtroffmode);
5051 @:troffmode_}{\&{troffmode} primitive@>
5052 mp_primitive(mp, "defaultcolormodel",internal_quantity,mp_default_color_model);
5053 @:mp_default_color_model_}{\&{defaultcolormodel} primitive@>
5054 mp_primitive(mp, "restoreclipcolor",internal_quantity,mp_restore_clip_color);
5055 @:mp_restore_clip_color_}{\&{restoreclipcolor} primitive@>
5056
5057 @ Colors can be specified in four color models. In the special
5058 case of |no_model|, MetaPost does not output any color operator to
5059 the postscript output.
5060
5061 Note: these values are passed directly on to |with_option|. This only
5062 works because the other possible values passed to |with_option| are
5063 8 and 10 respectively (from |with_pen| and |with_picture|).
5064
5065 There is a first state, that is only used for |gs_colormodel|. It flags
5066 the fact that there has not been any kind of color specification by
5067 the user so far in the game.
5068
5069 @<Types...@>=
5070 enum mp_color_model {
5071   mp_no_model=1,
5072   mp_grey_model=3,
5073   mp_rgb_model=5,
5074   mp_cmyk_model=7,
5075   mp_uninitialized_model=9,
5076 };
5077
5078
5079 @ @<Initialize table entries (done by \.{INIMP} only)@>=
5080 mp->internal[mp_default_color_model]=(mp_rgb_model*unity);
5081 mp->internal[mp_restore_clip_color]=unity;
5082
5083 @ Well, we do have to list the names one more time, for use in symbolic
5084 printouts.
5085
5086 @<Initialize table...@>=
5087 mp->int_name[mp_tracing_titles]=xstrdup("tracingtitles");
5088 mp->int_name[mp_tracing_equations]=xstrdup("tracingequations");
5089 mp->int_name[mp_tracing_capsules]=xstrdup("tracingcapsules");
5090 mp->int_name[mp_tracing_choices]=xstrdup("tracingchoices");
5091 mp->int_name[mp_tracing_specs]=xstrdup("tracingspecs");
5092 mp->int_name[mp_tracing_commands]=xstrdup("tracingcommands");
5093 mp->int_name[mp_tracing_restores]=xstrdup("tracingrestores");
5094 mp->int_name[mp_tracing_macros]=xstrdup("tracingmacros");
5095 mp->int_name[mp_tracing_output]=xstrdup("tracingoutput");
5096 mp->int_name[mp_tracing_stats]=xstrdup("tracingstats");
5097 mp->int_name[mp_tracing_lost_chars]=xstrdup("tracinglostchars");
5098 mp->int_name[mp_tracing_online]=xstrdup("tracingonline");
5099 mp->int_name[mp_year]=xstrdup("year");
5100 mp->int_name[mp_month]=xstrdup("month");
5101 mp->int_name[mp_day]=xstrdup("day");
5102 mp->int_name[mp_time]=xstrdup("time");
5103 mp->int_name[mp_char_code]=xstrdup("charcode");
5104 mp->int_name[mp_char_ext]=xstrdup("charext");
5105 mp->int_name[mp_char_wd]=xstrdup("charwd");
5106 mp->int_name[mp_char_ht]=xstrdup("charht");
5107 mp->int_name[mp_char_dp]=xstrdup("chardp");
5108 mp->int_name[mp_char_ic]=xstrdup("charic");
5109 mp->int_name[mp_design_size]=xstrdup("designsize");
5110 mp->int_name[mp_pausing]=xstrdup("pausing");
5111 mp->int_name[mp_showstopping]=xstrdup("showstopping");
5112 mp->int_name[mp_fontmaking]=xstrdup("fontmaking");
5113 mp->int_name[mp_linejoin]=xstrdup("linejoin");
5114 mp->int_name[mp_linecap]=xstrdup("linecap");
5115 mp->int_name[mp_miterlimit]=xstrdup("miterlimit");
5116 mp->int_name[mp_warning_check]=xstrdup("warningcheck");
5117 mp->int_name[mp_boundary_char]=xstrdup("boundarychar");
5118 mp->int_name[mp_prologues]=xstrdup("prologues");
5119 mp->int_name[mp_true_corners]=xstrdup("truecorners");
5120 mp->int_name[mp_default_color_model]=xstrdup("defaultcolormodel");
5121 mp->int_name[mp_procset]=xstrdup("mpprocset");
5122 mp->int_name[mp_gtroffmode]=xstrdup("troffmode");
5123 mp->int_name[mp_restore_clip_color]=xstrdup("restoreclipcolor");
5124
5125 @ The following procedure, which is called just before \MP\ initializes its
5126 input and output, establishes the initial values of the date and time.
5127 @^system dependencies@>
5128
5129 Note that the values are |scaled| integers. Hence \MP\ can no longer
5130 be used after the year 32767.
5131
5132 @c 
5133 void mp_fix_date_and_time (MP mp) { 
5134   time_t clock = time ((time_t *) 0);
5135   struct tm *tmptr = localtime (&clock);
5136   mp->internal[mp_time]=
5137       (tmptr->tm_hour*60+tmptr->tm_min)*unity; /* minutes since midnight */
5138   mp->internal[mp_day]=(tmptr->tm_mday)*unity; /* fourth day of the month */
5139   mp->internal[mp_month]=(tmptr->tm_mon+1)*unity; /* seventh month of the year */
5140   mp->internal[mp_year]=(tmptr->tm_year+1900)*unity; /* Anno Domini */
5141 }
5142
5143 @ @<Declarations@>=
5144 void mp_fix_date_and_time (MP mp) ;
5145
5146 @ \MP\ is occasionally supposed to print diagnostic information that
5147 goes only into the transcript file, unless |mp_tracing_online| is positive.
5148 Now that we have defined |mp_tracing_online| we can define
5149 two routines that adjust the destination of print commands:
5150
5151 @<Declarations@>=
5152 void mp_begin_diagnostic (MP mp) ;
5153 void mp_end_diagnostic (MP mp,boolean blank_line);
5154 void mp_print_diagnostic (MP mp, char *s, char *t, boolean nuline) ;
5155
5156 @ @<Basic printing...@>=
5157 @<Declare a function called |true_line|@>;
5158 void mp_begin_diagnostic (MP mp) { /* prepare to do some tracing */
5159   mp->old_setting=mp->selector;
5160   if ((mp->internal[mp_tracing_online]<=0)&&(mp->selector==term_and_log)){ 
5161     decr(mp->selector);
5162     if ( mp->history==mp_spotless ) mp->history=mp_warning_issued;
5163   }
5164 }
5165 @#
5166 void mp_end_diagnostic (MP mp,boolean blank_line) {
5167   /* restore proper conditions after tracing */
5168   mp_print_nl(mp, "");
5169   if ( blank_line ) mp_print_ln(mp);
5170   mp->selector=mp->old_setting;
5171 }
5172
5173
5174
5175 @<Glob...@>=
5176 unsigned int old_setting;
5177
5178 @ We will occasionally use |begin_diagnostic| in connection with line-number
5179 printing, as follows. (The parameter |s| is typically |"Path"| or
5180 |"Cycle spec"|, etc.)
5181
5182 @<Basic printing...@>=
5183 void mp_print_diagnostic (MP mp, char *s, char *t, boolean nuline) { 
5184   mp_begin_diagnostic(mp);
5185   if ( nuline ) mp_print_nl(mp, s); else mp_print(mp, s);
5186   mp_print(mp, " at line "); 
5187   mp_print_int(mp, mp_true_line(mp));
5188   mp_print(mp, t); mp_print_char(mp, ':');
5189 }
5190
5191 @ The 256 |ASCII_code| characters are grouped into classes by means of
5192 the |char_class| table. Individual class numbers have no semantic
5193 or syntactic significance, except in a few instances defined here.
5194 There's also |max_class|, which can be used as a basis for additional
5195 class numbers in nonstandard extensions of \MP.
5196
5197 @d digit_class 0 /* the class number of \.{0123456789} */
5198 @d period_class 1 /* the class number of `\..' */
5199 @d space_class 2 /* the class number of spaces and nonstandard characters */
5200 @d percent_class 3 /* the class number of `\.\%' */
5201 @d string_class 4 /* the class number of `\."' */
5202 @d right_paren_class 8 /* the class number of `\.)' */
5203 @d isolated_classes 5: case 6: case 7: case 8 /* characters that make length-one tokens only */
5204 @d letter_class 9 /* letters and the underline character */
5205 @d left_bracket_class 17 /* `\.[' */
5206 @d right_bracket_class 18 /* `\.]' */
5207 @d invalid_class 20 /* bad character in the input */
5208 @d max_class 20 /* the largest class number */
5209
5210 @<Glob...@>=
5211 int char_class[256]; /* the class numbers */
5212
5213 @ If changes are made to accommodate non-ASCII character sets, they should
5214 follow the guidelines in Appendix~C of {\sl The {\logos METAFONT\/}book}.
5215 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
5216 @^system dependencies@>
5217
5218 @<Set initial ...@>=
5219 for (k='0';k<='9';k++) 
5220   mp->char_class[k]=digit_class;
5221 mp->char_class['.']=period_class;
5222 mp->char_class[' ']=space_class;
5223 mp->char_class['%']=percent_class;
5224 mp->char_class['"']=string_class;
5225 mp->char_class[',']=5;
5226 mp->char_class[';']=6;
5227 mp->char_class['(']=7;
5228 mp->char_class[')']=right_paren_class;
5229 for (k='A';k<= 'Z';k++ )
5230   mp->char_class[k]=letter_class;
5231 for (k='a';k<='z';k++) 
5232   mp->char_class[k]=letter_class;
5233 mp->char_class['_']=letter_class;
5234 mp->char_class['<']=10;
5235 mp->char_class['=']=10;
5236 mp->char_class['>']=10;
5237 mp->char_class[':']=10;
5238 mp->char_class['|']=10;
5239 mp->char_class['`']=11;
5240 mp->char_class['\'']=11;
5241 mp->char_class['+']=12;
5242 mp->char_class['-']=12;
5243 mp->char_class['/']=13;
5244 mp->char_class['*']=13;
5245 mp->char_class['\\']=13;
5246 mp->char_class['!']=14;
5247 mp->char_class['?']=14;
5248 mp->char_class['#']=15;
5249 mp->char_class['&']=15;
5250 mp->char_class['@@']=15;
5251 mp->char_class['$']=15;
5252 mp->char_class['^']=16;
5253 mp->char_class['~']=16;
5254 mp->char_class['[']=left_bracket_class;
5255 mp->char_class[']']=right_bracket_class;
5256 mp->char_class['{']=19;
5257 mp->char_class['}']=19;
5258 for (k=0;k<' ';k++)
5259   mp->char_class[k]=invalid_class;
5260 mp->char_class['\t']=space_class;
5261 mp->char_class['\f']=space_class;
5262 for (k=127;k<=255;k++)
5263   mp->char_class[k]=invalid_class;
5264
5265 @* \[13] The hash table.
5266 Symbolic tokens are stored and retrieved by means of a fairly standard hash
5267 table algorithm called the method of ``coalescing lists'' (cf.\ Algorithm 6.4C
5268 in {\sl The Art of Computer Programming\/}). Once a symbolic token enters the
5269 table, it is never removed.
5270
5271 The actual sequence of characters forming a symbolic token is
5272 stored in the |str_pool| array together with all the other strings. An
5273 auxiliary array |hash| consists of items with two halfword fields per
5274 word. The first of these, called |next(p)|, points to the next identifier
5275 belonging to the same coalesced list as the identifier corresponding to~|p|;
5276 and the other, called |text(p)|, points to the |str_start| entry for
5277 |p|'s identifier. If position~|p| of the hash table is empty, we have
5278 |text(p)=0|; if position |p| is either empty or the end of a coalesced
5279 hash list, we have |next(p)=0|.
5280
5281 An auxiliary pointer variable called |hash_used| is maintained in such a
5282 way that all locations |p>=hash_used| are nonempty. The global variable
5283 |st_count| tells how many symbolic tokens have been defined, if statistics
5284 are being kept.
5285
5286 The first 256 locations of |hash| are reserved for symbols of length one.
5287
5288 There's a parallel array called |eqtb| that contains the current equivalent
5289 values of each symbolic token. The entries of this array consist of
5290 two halfwords called |eq_type| (a command code) and |equiv| (a secondary
5291 piece of information that qualifies the |eq_type|).
5292
5293 @d next(A)   mp->hash[(A)].lh /* link for coalesced lists */
5294 @d text(A)   mp->hash[(A)].rh /* string number for symbolic token name */
5295 @d eq_type(A)   mp->eqtb[(A)].lh /* the current ``meaning'' of a symbolic token */
5296 @d equiv(A)   mp->eqtb[(A)].rh /* parametric part of a token's meaning */
5297 @d hash_base 257 /* hashing actually starts here */
5298 @d hash_is_full   (mp->hash_used==hash_base) /* are all positions occupied? */
5299
5300 @<Glob...@>=
5301 pointer hash_used; /* allocation pointer for |hash| */
5302 integer st_count; /* total number of known identifiers */
5303
5304 @ Certain entries in the hash table are ``frozen'' and not redefinable,
5305 since they are used in error recovery.
5306
5307 @d hash_top (hash_base+mp->hash_size) /* the first location of the frozen area */
5308 @d frozen_inaccessible hash_top /* |hash| location to protect the frozen area */
5309 @d frozen_repeat_loop (hash_top+1) /* |hash| location of a loop-repeat token */
5310 @d frozen_right_delimiter (hash_top+2) /* |hash| location of a permanent `\.)' */
5311 @d frozen_left_bracket (hash_top+3) /* |hash| location of a permanent `\.[' */
5312 @d frozen_slash (hash_top+4) /* |hash| location of a permanent `\./' */
5313 @d frozen_colon (hash_top+5) /* |hash| location of a permanent `\.:' */
5314 @d frozen_semicolon (hash_top+6) /* |hash| location of a permanent `\.;' */
5315 @d frozen_end_for (hash_top+7) /* |hash| location of a permanent \&{endfor} */
5316 @d frozen_end_def (hash_top+8) /* |hash| location of a permanent \&{enddef} */
5317 @d frozen_fi (hash_top+9) /* |hash| location of a permanent \&{fi} */
5318 @d frozen_end_group (hash_top+10) /* |hash| location of a permanent `\.{endgroup}' */
5319 @d frozen_etex (hash_top+11) /* |hash| location of a permanent \&{etex} */
5320 @d frozen_mpx_break (hash_top+12) /* |hash| location of a permanent \&{mpxbreak} */
5321 @d frozen_bad_vardef (hash_top+13) /* |hash| location of `\.{a bad variable}' */
5322 @d frozen_undefined (hash_top+14) /* |hash| location that never gets defined */
5323 @d hash_end (hash_top+14) /* the actual size of the |hash| and |eqtb| arrays */
5324
5325 @<Glob...@>=
5326 two_halves *hash; /* the hash table */
5327 two_halves *eqtb; /* the equivalents */
5328
5329 @ @<Allocate or initialize ...@>=
5330 mp->hash = xmalloc((hash_end+1),sizeof(two_halves));
5331 mp->eqtb = xmalloc((hash_end+1),sizeof(two_halves));
5332
5333 @ @<Dealloc variables@>=
5334 xfree(mp->hash);
5335 xfree(mp->eqtb);
5336
5337 @ @<Set init...@>=
5338 next(1)=0; text(1)=0; eq_type(1)=tag_token; equiv(1)=null;
5339 for (k=2;k<=hash_end;k++)  { 
5340   mp->hash[k]=mp->hash[1]; mp->eqtb[k]=mp->eqtb[1];
5341 }
5342
5343 @ @<Initialize table entries...@>=
5344 mp->hash_used=frozen_inaccessible; /* nothing is used */
5345 mp->st_count=0;
5346 text(frozen_bad_vardef)=intern("a bad variable");
5347 text(frozen_etex)=intern("etex");
5348 text(frozen_mpx_break)=intern("mpxbreak");
5349 text(frozen_fi)=intern("fi");
5350 text(frozen_end_group)=intern("endgroup");
5351 text(frozen_end_def)=intern("enddef");
5352 text(frozen_end_for)=intern("endfor");
5353 text(frozen_semicolon)=intern(";");
5354 text(frozen_colon)=intern(":");
5355 text(frozen_slash)=intern("/");
5356 text(frozen_left_bracket)=intern("[");
5357 text(frozen_right_delimiter)=intern(")");
5358 text(frozen_inaccessible)=intern(" INACCESSIBLE");
5359 eq_type(frozen_right_delimiter)=right_delimiter;
5360
5361 @ @<Check the ``constant'' values...@>=
5362 if ( hash_end+mp->max_internal>max_halfword ) mp->bad=17;
5363
5364 @ Here is the subroutine that searches the hash table for an identifier
5365 that matches a given string of length~|l| appearing in |buffer[j..
5366 (j+l-1)]|. If the identifier is not found, it is inserted; hence it
5367 will always be found, and the corresponding hash table address
5368 will be returned.
5369
5370 @c 
5371 pointer mp_id_lookup (MP mp,integer j, integer l) { /* search the hash table */
5372   integer h; /* hash code */
5373   pointer p; /* index in |hash| array */
5374   pointer k; /* index in |buffer| array */
5375   if (l==1) {
5376     @<Treat special case of length 1 and |break|@>;
5377   }
5378   @<Compute the hash code |h|@>;
5379   p=h+hash_base; /* we start searching here; note that |0<=h<hash_prime| */
5380   while (true)  { 
5381         if (text(p)>0 && length(text(p))==l && mp_str_eq_buf(mp, text(p),j)) 
5382       break;
5383     if ( next(p)==0 ) {
5384       @<Insert a new symbolic token after |p|, then
5385         make |p| point to it and |break|@>;
5386     }
5387     p=next(p);
5388   }
5389   return p;
5390 };
5391
5392 @ @<Treat special case of length 1...@>=
5393  p=mp->buffer[j]+1; text(p)=p-1; return p;
5394
5395
5396 @ @<Insert a new symbolic...@>=
5397 {
5398 if ( text(p)>0 ) { 
5399   do {  
5400     if ( hash_is_full )
5401       mp_overflow(mp, "hash size",mp->hash_size);
5402 @:MetaPost capacity exceeded hash size}{\quad hash size@>
5403     decr(mp->hash_used);
5404   } while (text(mp->hash_used)!=0); /* search for an empty location in |hash| */
5405   next(p)=mp->hash_used; 
5406   p=mp->hash_used;
5407 }
5408 str_room(l);
5409 for (k=j;k<=j+l-1;k++) {
5410   append_char(mp->buffer[k]);
5411 }
5412 text(p)=mp_make_string(mp); 
5413 mp->str_ref[text(p)]=max_str_ref;
5414 incr(mp->st_count);
5415 break;
5416 }
5417
5418
5419 @ The value of |hash_prime| should be roughly 85\pct! of |hash_size|, and it
5420 should be a prime number.  The theory of hashing tells us to expect fewer
5421 than two table probes, on the average, when the search is successful.
5422 [See J.~S. Vitter, {\sl Journal of the ACM\/ \bf30} (1983), 231--258.]
5423 @^Vitter, Jeffrey Scott@>
5424
5425 @<Compute the hash code |h|@>=
5426 h=mp->buffer[j];
5427 for (k=j+1;k<=j+l-1;k++){ 
5428   h=h+h+mp->buffer[k];
5429   while ( h>=mp->hash_prime ) h=h-mp->hash_prime;
5430 }
5431
5432 @ @<Search |eqtb| for equivalents equal to |p|@>=
5433 for (q=1;q<=hash_end;q++) { 
5434   if ( equiv(q)==p ) { 
5435     mp_print_nl(mp, "EQUIV("); 
5436     mp_print_int(mp, q); 
5437     mp_print_char(mp, ')');
5438   }
5439 }
5440
5441 @ We need to put \MP's ``primitive'' symbolic tokens into the hash
5442 table, together with their command code (which will be the |eq_type|)
5443 and an operand (which will be the |equiv|). The |primitive| procedure
5444 does this, in a way that no \MP\ user can. The global value |cur_sym|
5445 contains the new |eqtb| pointer after |primitive| has acted.
5446
5447 @c 
5448 void mp_primitive (MP mp, char *ss, halfword c, halfword o) {
5449   pool_pointer k; /* index into |str_pool| */
5450   small_number j; /* index into |buffer| */
5451   small_number l; /* length of the string */
5452   str_number s;
5453   s = intern(ss);
5454   k=mp->str_start[s]; l=str_stop(s)-k;
5455   /* we will move |s| into the (empty) |buffer| */
5456   for (j=0;j<=l-1;j++) {
5457     mp->buffer[j]=mp->str_pool[k+j];
5458   }
5459   mp->cur_sym=mp_id_lookup(mp, 0,l);
5460   if ( s>=256 ) { /* we don't want to have the string twice */
5461     mp_flush_string(mp, text(mp->cur_sym)); text(mp->cur_sym)=s;
5462   };
5463   eq_type(mp->cur_sym)=c; 
5464   equiv(mp->cur_sym)=o;
5465 }
5466
5467
5468 @ Many of \MP's primitives need no |equiv|, since they are identifiable
5469 by their |eq_type| alone. These primitives are loaded into the hash table
5470 as follows:
5471
5472 @<Put each of \MP's primitives into the hash table@>=
5473 mp_primitive(mp, "..",path_join,0);
5474 @:.._}{\.{..} primitive@>
5475 mp_primitive(mp, "[",left_bracket,0); mp->eqtb[frozen_left_bracket]=mp->eqtb[mp->cur_sym];
5476 @:[ }{\.{[} primitive@>
5477 mp_primitive(mp, "]",right_bracket,0);
5478 @:] }{\.{]} primitive@>
5479 mp_primitive(mp, "}",right_brace,0);
5480 @:]]}{\.{\char`\}} primitive@>
5481 mp_primitive(mp, "{",left_brace,0);
5482 @:][}{\.{\char`\{} primitive@>
5483 mp_primitive(mp, ":",colon,0); mp->eqtb[frozen_colon]=mp->eqtb[mp->cur_sym];
5484 @:: }{\.{:} primitive@>
5485 mp_primitive(mp, "::",double_colon,0);
5486 @::: }{\.{::} primitive@>
5487 mp_primitive(mp, "||:",bchar_label,0);
5488 @:::: }{\.{\char'174\char'174:} primitive@>
5489 mp_primitive(mp, ":=",assignment,0);
5490 @::=_}{\.{:=} primitive@>
5491 mp_primitive(mp, ",",comma,0);
5492 @:, }{\., primitive@>
5493 mp_primitive(mp, ";",semicolon,0); mp->eqtb[frozen_semicolon]=mp->eqtb[mp->cur_sym];
5494 @:; }{\.; primitive@>
5495 mp_primitive(mp, "\\",relax,0);
5496 @:]]\\}{\.{\char`\\} primitive@>
5497 @#
5498 mp_primitive(mp, "addto",add_to_command,0);
5499 @:add_to_}{\&{addto} primitive@>
5500 mp_primitive(mp, "atleast",at_least,0);
5501 @:at_least_}{\&{atleast} primitive@>
5502 mp_primitive(mp, "begingroup",begin_group,0); mp->bg_loc=mp->cur_sym;
5503 @:begin_group_}{\&{begingroup} primitive@>
5504 mp_primitive(mp, "controls",controls,0);
5505 @:controls_}{\&{controls} primitive@>
5506 mp_primitive(mp, "curl",curl_command,0);
5507 @:curl_}{\&{curl} primitive@>
5508 mp_primitive(mp, "delimiters",delimiters,0);
5509 @:delimiters_}{\&{delimiters} primitive@>
5510 mp_primitive(mp, "endgroup",end_group,0);
5511  mp->eqtb[frozen_end_group]=mp->eqtb[mp->cur_sym]; mp->eg_loc=mp->cur_sym;
5512 @:endgroup_}{\&{endgroup} primitive@>
5513 mp_primitive(mp, "everyjob",every_job_command,0);
5514 @:every_job_}{\&{everyjob} primitive@>
5515 mp_primitive(mp, "exitif",exit_test,0);
5516 @:exit_if_}{\&{exitif} primitive@>
5517 mp_primitive(mp, "expandafter",expand_after,0);
5518 @:expand_after_}{\&{expandafter} primitive@>
5519 mp_primitive(mp, "interim",interim_command,0);
5520 @:interim_}{\&{interim} primitive@>
5521 mp_primitive(mp, "let",let_command,0);
5522 @:let_}{\&{let} primitive@>
5523 mp_primitive(mp, "newinternal",new_internal,0);
5524 @:new_internal_}{\&{newinternal} primitive@>
5525 mp_primitive(mp, "of",of_token,0);
5526 @:of_}{\&{of} primitive@>
5527 mp_primitive(mp, "randomseed",mp_random_seed,0);
5528 @:mp_random_seed_}{\&{randomseed} primitive@>
5529 mp_primitive(mp, "save",save_command,0);
5530 @:save_}{\&{save} primitive@>
5531 mp_primitive(mp, "scantokens",scan_tokens,0);
5532 @:scan_tokens_}{\&{scantokens} primitive@>
5533 mp_primitive(mp, "shipout",ship_out_command,0);
5534 @:ship_out_}{\&{shipout} primitive@>
5535 mp_primitive(mp, "skipto",skip_to,0);
5536 @:skip_to_}{\&{skipto} primitive@>
5537 mp_primitive(mp, "special",special_command,0);
5538 @:special}{\&{special} primitive@>
5539 mp_primitive(mp, "fontmapfile",special_command,1);
5540 @:fontmapfile}{\&{fontmapfile} primitive@>
5541 mp_primitive(mp, "fontmapline",special_command,2);
5542 @:fontmapline}{\&{fontmapline} primitive@>
5543 mp_primitive(mp, "step",step_token,0);
5544 @:step_}{\&{step} primitive@>
5545 mp_primitive(mp, "str",str_op,0);
5546 @:str_}{\&{str} primitive@>
5547 mp_primitive(mp, "tension",tension,0);
5548 @:tension_}{\&{tension} primitive@>
5549 mp_primitive(mp, "to",to_token,0);
5550 @:to_}{\&{to} primitive@>
5551 mp_primitive(mp, "until",until_token,0);
5552 @:until_}{\&{until} primitive@>
5553 mp_primitive(mp, "within",within_token,0);
5554 @:within_}{\&{within} primitive@>
5555 mp_primitive(mp, "write",write_command,0);
5556 @:write_}{\&{write} primitive@>
5557
5558 @ Each primitive has a corresponding inverse, so that it is possible to
5559 display the cryptic numeric contents of |eqtb| in symbolic form.
5560 Every call of |primitive| in this program is therefore accompanied by some
5561 straightforward code that forms part of the |print_cmd_mod| routine
5562 explained below.
5563
5564 @<Cases of |print_cmd_mod| for symbolic printing of primitives@>=
5565 case add_to_command:mp_print(mp, "addto"); break;
5566 case assignment:mp_print(mp, ":="); break;
5567 case at_least:mp_print(mp, "atleast"); break;
5568 case bchar_label:mp_print(mp, "||:"); break;
5569 case begin_group:mp_print(mp, "begingroup"); break;
5570 case colon:mp_print(mp, ":"); break;
5571 case comma:mp_print(mp, ","); break;
5572 case controls:mp_print(mp, "controls"); break;
5573 case curl_command:mp_print(mp, "curl"); break;
5574 case delimiters:mp_print(mp, "delimiters"); break;
5575 case double_colon:mp_print(mp, "::"); break;
5576 case end_group:mp_print(mp, "endgroup"); break;
5577 case every_job_command:mp_print(mp, "everyjob"); break;
5578 case exit_test:mp_print(mp, "exitif"); break;
5579 case expand_after:mp_print(mp, "expandafter"); break;
5580 case interim_command:mp_print(mp, "interim"); break;
5581 case left_brace:mp_print(mp, "{"); break;
5582 case left_bracket:mp_print(mp, "["); break;
5583 case let_command:mp_print(mp, "let"); break;
5584 case new_internal:mp_print(mp, "newinternal"); break;
5585 case of_token:mp_print(mp, "of"); break;
5586 case path_join:mp_print(mp, ".."); break;
5587 case mp_random_seed:mp_print(mp, "randomseed"); break;
5588 case relax:mp_print_char(mp, '\\'); break;
5589 case right_brace:mp_print(mp, "}"); break;
5590 case right_bracket:mp_print(mp, "]"); break;
5591 case save_command:mp_print(mp, "save"); break;
5592 case scan_tokens:mp_print(mp, "scantokens"); break;
5593 case semicolon:mp_print(mp, ";"); break;
5594 case ship_out_command:mp_print(mp, "shipout"); break;
5595 case skip_to:mp_print(mp, "skipto"); break;
5596 case special_command: if ( m==2 ) mp_print(mp, "fontmapline"); else
5597                  if ( m==1 ) mp_print(mp, "fontmapfile"); else
5598                  mp_print(mp, "special"); break;
5599 case step_token:mp_print(mp, "step"); break;
5600 case str_op:mp_print(mp, "str"); break;
5601 case tension:mp_print(mp, "tension"); break;
5602 case to_token:mp_print(mp, "to"); break;
5603 case until_token:mp_print(mp, "until"); break;
5604 case within_token:mp_print(mp, "within"); break;
5605 case write_command:mp_print(mp, "write"); break;
5606
5607 @ We will deal with the other primitives later, at some point in the program
5608 where their |eq_type| and |equiv| values are more meaningful.  For example,
5609 the primitives for macro definitions will be loaded when we consider the
5610 routines that define macros.
5611 It is easy to find where each particular
5612 primitive was treated by looking in the index at the end; for example, the
5613 section where |"def"| entered |eqtb| is listed under `\&{def} primitive'.
5614
5615 @* \[14] Token lists.
5616 A \MP\ token is either symbolic or numeric or a string, or it denotes
5617 a macro parameter or capsule; so there are five corresponding ways to encode it
5618 @^token@>
5619 internally: (1)~A symbolic token whose hash code is~|p|
5620 is represented by the number |p|, in the |info| field of a single-word
5621 node in~|mem|. (2)~A numeric token whose |scaled| value is~|v| is
5622 represented in a two-word node of~|mem|; the |type| field is |known|,
5623 the |name_type| field is |token|, and the |value| field holds~|v|.
5624 The fact that this token appears in a two-word node rather than a
5625 one-word node is, of course, clear from the node address.
5626 (3)~A string token is also represented in a two-word node; the |type|
5627 field is |mp_string_type|, the |name_type| field is |token|, and the
5628 |value| field holds the corresponding |str_number|.  (4)~Capsules have
5629 |name_type=capsule|, and their |type| and |value| fields represent
5630 arbitrary values (in ways to be explained later).  (5)~Macro parameters
5631 are like symbolic tokens in that they appear in |info| fields of
5632 one-word nodes. The $k$th parameter is represented by |expr_base+k| if it
5633 is of type \&{expr}, or by |suffix_base+k| if it is of type \&{suffix}, or
5634 by |text_base+k| if it is of type \&{text}.  (Here |0<=k<param_size|.)
5635 Actual values of these parameters are kept in a separate stack, as we will
5636 see later.  The constants |expr_base|, |suffix_base|, and |text_base| are,
5637 of course, chosen so that there will be no confusion between symbolic
5638 tokens and parameters of various types.
5639
5640 Note that
5641 the `\\{type}' field of a node has nothing to do with ``type'' in a
5642 printer's sense. It's curious that the same word is used in such different ways.
5643
5644 @d type(A)   mp->mem[(A)].hh.b0 /* identifies what kind of value this is */
5645 @d name_type(A)   mp->mem[(A)].hh.b1 /* a clue to the name of this value */
5646 @d token_node_size 2 /* the number of words in a large token node */
5647 @d value_loc(A) ((A)+1) /* the word that contains the |value| field */
5648 @d value(A) mp->mem[value_loc((A))].cint /* the value stored in a large token node */
5649 @d expr_base (hash_end+1) /* code for the zeroth \&{expr} parameter */
5650 @d suffix_base (expr_base+mp->param_size) /* code for the zeroth \&{suffix} parameter */
5651 @d text_base (suffix_base+mp->param_size) /* code for the zeroth \&{text} parameter */
5652
5653 @<Check the ``constant''...@>=
5654 if ( text_base+mp->param_size>max_halfword ) mp->bad=18;
5655
5656 @ We have set aside a two word node beginning at |null| so that we can have
5657 |value(null)=0|.  We will make use of this coincidence later.
5658
5659 @<Initialize table entries...@>=
5660 link(null)=null; value(null)=0;
5661
5662 @ A numeric token is created by the following trivial routine.
5663
5664 @c 
5665 pointer mp_new_num_tok (MP mp,scaled v) {
5666   pointer p; /* the new node */
5667   p=mp_get_node(mp, token_node_size); value(p)=v;
5668   type(p)=mp_known; name_type(p)=mp_token; 
5669   return p;
5670 }
5671
5672 @ A token list is a singly linked list of nodes in |mem|, where
5673 each node contains a token and a link.  Here's a subroutine that gets rid
5674 of a token list when it is no longer needed.
5675
5676 @c void mp_flush_token_list (MP mp,pointer p) {
5677   pointer q; /* the node being recycled */
5678   while ( p!=null ) { 
5679     q=p; p=link(p);
5680     if ( q>=mp->hi_mem_min ) {
5681      free_avail(q);
5682     } else { 
5683       switch (type(q)) {
5684       case mp_vacuous: case mp_boolean_type: case mp_known:
5685         break;
5686       case mp_string_type:
5687         delete_str_ref(value(q));
5688         break;
5689       case unknown_types: case mp_pen_type: case mp_path_type: 
5690       case mp_picture_type: case mp_pair_type: case mp_color_type:
5691       case mp_cmykcolor_type: case mp_transform_type: case mp_dependent:
5692       case mp_proto_dependent: case mp_independent:
5693         mp_recycle_value(mp,q);
5694         break;
5695       default: mp_confusion(mp, "token");
5696 @:this can't happen token}{\quad token@>
5697       }
5698       mp_free_node(mp, q,token_node_size);
5699     }
5700   }
5701 }
5702
5703 @ The procedure |show_token_list|, which prints a symbolic form of
5704 the token list that starts at a given node |p|, illustrates these
5705 conventions. The token list being displayed should not begin with a reference
5706 count. However, the procedure is intended to be fairly robust, so that if the
5707 memory links are awry or if |p| is not really a pointer to a token list,
5708 almost nothing catastrophic can happen.
5709
5710 An additional parameter |q| is also given; this parameter is either null
5711 or it points to a node in the token list where a certain magic computation
5712 takes place that will be explained later. (Basically, |q| is non-null when
5713 we are printing the two-line context information at the time of an error
5714 message; |q| marks the place corresponding to where the second line
5715 should begin.)
5716
5717 The generation will stop, and `\.{\char`\ ETC.}' will be printed, if the length
5718 of printing exceeds a given limit~|l|; the length of printing upon entry is
5719 assumed to be a given amount called |null_tally|. (Note that
5720 |show_token_list| sometimes uses itself recursively to print
5721 variable names within a capsule.)
5722 @^recursion@>
5723
5724 Unusual entries are printed in the form of all-caps tokens
5725 preceded by a space, e.g., `\.{\char`\ BAD}'.
5726
5727 @<Declare the procedure called |show_token_list|@>=
5728 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5729                          integer null_tally) ;
5730
5731 @ @c
5732 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5733                          integer null_tally) {
5734   small_number class,c; /* the |char_class| of previous and new tokens */
5735   integer r,v; /* temporary registers */
5736   class=percent_class;
5737   mp->tally=null_tally;
5738   while ( (p!=null) && (mp->tally<l) ) { 
5739     if ( p==q ) 
5740       @<Do magic computation@>;
5741     @<Display token |p| and set |c| to its class;
5742       but |return| if there are problems@>;
5743     class=c; p=link(p);
5744   }
5745   if ( p!=null ) 
5746      mp_print(mp, " ETC.");
5747 @.ETC@>
5748   return;
5749 };
5750
5751 @ @<Display token |p| and set |c| to its class...@>=
5752 c=letter_class; /* the default */
5753 if ( (p<0)||(p>mp->mem_end) ) { 
5754   mp_print(mp, " CLOBBERED"); return;
5755 @.CLOBBERED@>
5756 }
5757 if ( p<mp->hi_mem_min ) { 
5758   @<Display two-word token@>;
5759 } else { 
5760   r=info(p);
5761   if ( r>=expr_base ) {
5762      @<Display a parameter token@>;
5763   } else {
5764     if ( r<1 ) {
5765       if ( r==0 ) { 
5766         @<Display a collective subscript@>
5767       } else {
5768         mp_print(mp, " IMPOSSIBLE");
5769 @.IMPOSSIBLE@>
5770       }
5771     } else { 
5772       r=text(r);
5773       if ( (r<0)||(r>mp->max_str_ptr) ) {
5774         mp_print(mp, " NONEXISTENT");
5775 @.NONEXISTENT@>
5776       } else {
5777        @<Print string |r| as a symbolic token
5778         and set |c| to its class@>;
5779       }
5780     }
5781   }
5782 }
5783
5784 @ @<Display two-word token@>=
5785 if ( name_type(p)==mp_token ) {
5786   if ( type(p)==mp_known ) {
5787     @<Display a numeric token@>;
5788   } else if ( type(p)!=mp_string_type ) {
5789     mp_print(mp, " BAD");
5790 @.BAD@>
5791   } else { 
5792     mp_print_char(mp, '"'); mp_print_str(mp, value(p)); mp_print_char(mp, '"');
5793     c=string_class;
5794   }
5795 } else if ((name_type(p)!=mp_capsule)||(type(p)<mp_vacuous)||(type(p)>mp_independent) ) {
5796   mp_print(mp, " BAD");
5797 } else { 
5798   mp_print_capsule(mp,p); c=right_paren_class;
5799 }
5800
5801 @ @<Display a numeric token@>=
5802 if ( class==digit_class ) 
5803   mp_print_char(mp, ' ');
5804 v=value(p);
5805 if ( v<0 ){ 
5806   if ( class==left_bracket_class ) 
5807     mp_print_char(mp, ' ');
5808   mp_print_char(mp, '['); mp_print_scaled(mp, v); mp_print_char(mp, ']');
5809   c=right_bracket_class;
5810 } else { 
5811   mp_print_scaled(mp, v); c=digit_class;
5812 }
5813
5814
5815 @ Strictly speaking, a genuine token will never have |info(p)=0|.
5816 But we will see later (in the |print_variable_name| routine) that
5817 it is convenient to let |info(p)=0| stand for `\.{[]}'.
5818
5819 @<Display a collective subscript@>=
5820 {
5821 if ( class==left_bracket_class ) 
5822   mp_print_char(mp, ' ');
5823 mp_print(mp, "[]"); c=right_bracket_class;
5824 }
5825
5826 @ @<Display a parameter token@>=
5827 {
5828 if ( r<suffix_base ) { 
5829   mp_print(mp, "(EXPR"); r=r-(expr_base);
5830 @.EXPR@>
5831 } else if ( r<text_base ) { 
5832   mp_print(mp, "(SUFFIX"); r=r-(suffix_base);
5833 @.SUFFIX@>
5834 } else { 
5835   mp_print(mp, "(TEXT"); r=r-(text_base);
5836 @.TEXT@>
5837 }
5838 mp_print_int(mp, r); mp_print_char(mp, ')'); c=right_paren_class;
5839 }
5840
5841
5842 @ @<Print string |r| as a symbolic token...@>=
5843
5844 c=mp->char_class[mp->str_pool[mp->str_start[r]]];
5845 if ( c==class ) {
5846   switch (c) {
5847   case letter_class:mp_print_char(mp, '.'); break;
5848   case isolated_classes: break;
5849   default: mp_print_char(mp, ' '); break;
5850   }
5851 }
5852 mp_print_str(mp, r);
5853 }
5854
5855 @ @<Declarations@>=
5856 void mp_print_capsule (MP mp, pointer p);
5857
5858 @ @<Declare miscellaneous procedures that were declared |forward|@>=
5859 void mp_print_capsule (MP mp, pointer p) { 
5860   mp_print_char(mp, '('); mp_print_exp(mp,p,0); mp_print_char(mp, ')');
5861 }
5862
5863 @ Macro definitions are kept in \MP's memory in the form of token lists
5864 that have a few extra one-word nodes at the beginning.
5865
5866 The first node contains a reference count that is used to tell when the
5867 list is no longer needed. To emphasize the fact that a reference count is
5868 present, we shall refer to the |info| field of this special node as the
5869 |ref_count| field.
5870 @^reference counts@>
5871
5872 The next node or nodes after the reference count serve to describe the
5873 formal parameters. They either contain a code word that specifies all
5874 of the parameters, or they contain zero or more parameter tokens followed
5875 by the code `|general_macro|'.
5876
5877 @d ref_count info
5878   /* reference count preceding a macro definition or picture header */
5879 @d add_mac_ref(A) incr(ref_count((A))) /* make a new reference to a macro list */
5880 @d general_macro 0 /* preface to a macro defined with a parameter list */
5881 @d primary_macro 1 /* preface to a macro with a \&{primary} parameter */
5882 @d secondary_macro 2 /* preface to a macro with a \&{secondary} parameter */
5883 @d tertiary_macro 3 /* preface to a macro with a \&{tertiary} parameter */
5884 @d expr_macro 4 /* preface to a macro with an undelimited \&{expr} parameter */
5885 @d of_macro 5 /* preface to a macro with
5886   undelimited `\&{expr} |x| \&{of}~|y|' parameters */
5887 @d suffix_macro 6 /* preface to a macro with an undelimited \&{suffix} parameter */
5888 @d text_macro 7 /* preface to a macro with an undelimited \&{text} parameter */
5889
5890 @c 
5891 void mp_delete_mac_ref (MP mp,pointer p) {
5892   /* |p| points to the reference count of a macro list that is
5893     losing one reference */
5894   if ( ref_count(p)==null ) mp_flush_token_list(mp, p);
5895   else decr(ref_count(p));
5896 }
5897
5898 @ The following subroutine displays a macro, given a pointer to its
5899 reference count.
5900
5901 @c 
5902 @<Declare the procedure called |print_cmd_mod|@>;
5903 void mp_show_macro (MP mp, pointer p, integer q, integer l) {
5904   pointer r; /* temporary storage */
5905   p=link(p); /* bypass the reference count */
5906   while ( info(p)>text_macro ){ 
5907     r=link(p); link(p)=null;
5908     mp_show_token_list(mp, p,null,l,0); link(p)=r; p=r;
5909     if ( l>0 ) l=l-mp->tally; else return;
5910   } /* control printing of `\.{ETC.}' */
5911 @.ETC@>
5912   mp->tally=0;
5913   switch(info(p)) {
5914   case general_macro:mp_print(mp, "->"); break;
5915 @.->@>
5916   case primary_macro: case secondary_macro: case tertiary_macro:
5917     mp_print_char(mp, '<');
5918     mp_print_cmd_mod(mp, param_type,info(p)); 
5919     mp_print(mp, ">->");
5920     break;
5921   case expr_macro:mp_print(mp, "<expr>->"); break;
5922   case of_macro:mp_print(mp, "<expr>of<primary>->"); break;
5923   case suffix_macro:mp_print(mp, "<suffix>->"); break;
5924   case text_macro:mp_print(mp, "<text>->"); break;
5925   } /* there are no other cases */
5926   mp_show_token_list(mp, link(p),q,l-mp->tally,0);
5927 }
5928
5929 @* \[15] Data structures for variables.
5930 The variables of \MP\ programs can be simple, like `\.x', or they can
5931 combine the structural properties of arrays and records, like `\.{x20a.b}'.
5932 A \MP\ user assigns a type to a variable like \.{x20a.b} by saying, for
5933 example, `\.{boolean} \.{x20a.b}'. It's time for us to study how such
5934 things are represented inside of the computer.
5935
5936 Each variable value occupies two consecutive words, either in a two-word
5937 node called a value node, or as a two-word subfield of a larger node.  One
5938 of those two words is called the |value| field; it is an integer,
5939 containing either a |scaled| numeric value or the representation of some
5940 other type of quantity. (It might also be subdivided into halfwords, in
5941 which case it is referred to by other names instead of |value|.) The other
5942 word is broken into subfields called |type|, |name_type|, and |link|.  The
5943 |type| field is a quarterword that specifies the variable's type, and
5944 |name_type| is a quarterword from which \MP\ can reconstruct the
5945 variable's name (sometimes by using the |link| field as well).  Thus, only
5946 1.25 words are actually devoted to the value itself; the other
5947 three-quarters of a word are overhead, but they aren't wasted because they
5948 allow \MP\ to deal with sparse arrays and to provide meaningful diagnostics.
5949
5950 In this section we shall be concerned only with the structural aspects of
5951 variables, not their values. Later parts of the program will change the
5952 |type| and |value| fields, but we shall treat those fields as black boxes
5953 whose contents should not be touched.
5954
5955 However, if the |type| field is |mp_structured|, there is no |value| field,
5956 and the second word is broken into two pointer fields called |attr_head|
5957 and |subscr_head|. Those fields point to additional nodes that
5958 contain structural information, as we shall see.
5959
5960 @d subscr_head_loc(A)   (A)+1 /* where |value|, |subscr_head| and |attr_head| are */
5961 @d attr_head(A)   info(subscr_head_loc((A))) /* pointer to attribute info */
5962 @d subscr_head(A)   link(subscr_head_loc((A))) /* pointer to subscript info */
5963 @d value_node_size 2 /* the number of words in a value node */
5964
5965 @ An attribute node is three words long. Two of these words contain |type|
5966 and |value| fields as described above, and the third word contains
5967 additional information:  There is an |attr_loc| field, which contains the
5968 hash address of the token that names this attribute; and there's also a
5969 |parent| field, which points to the value node of |mp_structured| type at the
5970 next higher level (i.e., at the level to which this attribute is
5971 subsidiary).  The |name_type| in an attribute node is `|attr|'.  The
5972 |link| field points to the next attribute with the same parent; these are
5973 arranged in increasing order, so that |attr_loc(link(p))>attr_loc(p)|. The
5974 final attribute node links to the constant |end_attr|, whose |attr_loc|
5975 field is greater than any legal hash address. The |attr_head| in the
5976 parent points to a node whose |name_type| is |mp_structured_root|; this
5977 node represents the null attribute, i.e., the variable that is relevant
5978 when no attributes are attached to the parent. The |attr_head| node is either
5979 a value node, a subscript node, or an attribute node, depending on what
5980 the parent would be if it were not structured; but the subscript and
5981 attribute fields are ignored, so it effectively contains only the data of
5982 a value node. The |link| field in this special node points to an attribute
5983 node whose |attr_loc| field is zero; the latter node represents a collective
5984 subscript `\.{[]}' attached to the parent, and its |link| field points to
5985 the first non-special attribute node (or to |end_attr| if there are none).
5986
5987 A subscript node likewise occupies three words, with |type| and |value| fields
5988 plus extra information; its |name_type| is |subscr|. In this case the
5989 third word is called the |subscript| field, which is a |scaled| integer.
5990 The |link| field points to the subscript node with the next larger
5991 subscript, if any; otherwise the |link| points to the attribute node
5992 for collective subscripts at this level. We have seen that the latter node
5993 contains an upward pointer, so that the parent can be deduced.
5994
5995 The |name_type| in a parent-less value node is |root|, and the |link|
5996 is the hash address of the token that names this value.
5997
5998 In other words, variables have a hierarchical structure that includes
5999 enough threads running around so that the program is able to move easily
6000 between siblings, parents, and children. An example should be helpful:
6001 (The reader is advised to draw a picture while reading the following
6002 description, since that will help to firm up the ideas.)
6003 Suppose that `\.x' and `\.{x.a}' and `\.{x[]b}' and `\.{x5}'
6004 and `\.{x20b}' have been mentioned in a user's program, where
6005 \.{x[]b} has been declared to be of \&{boolean} type. Let |h(x)|, |h(a)|,
6006 and |h(b)| be the hash addresses of \.x, \.a, and~\.b. Then
6007 |eq_type(h(x))=name| and |equiv(h(x))=p|, where |p|~is a two-word value
6008 node with |name_type(p)=root| and |link(p)=h(x)|. We have |type(p)=mp_structured|,
6009 |attr_head(p)=q|, and |subscr_head(p)=r|, where |q| points to a value
6010 node and |r| to a subscript node. (Are you still following this? Use
6011 a pencil to draw a diagram.) The lone variable `\.x' is represented by
6012 |type(q)| and |value(q)|; furthermore
6013 |name_type(q)=mp_structured_root| and |link(q)=q1|, where |q1| points
6014 to an attribute node representing `\.{x[]}'. Thus |name_type(q1)=attr|,
6015 |attr_loc(q1)=collective_subscript=0|, |parent(q1)=p|,
6016 |type(q1)=mp_structured|, |attr_head(q1)=qq|, and |subscr_head(q1)=qq1|;
6017 |qq| is a value node with |type(qq)=mp_numeric_type| (assuming that \.{x5} is
6018 numeric, because |qq| represents `\.{x[]}' with no further attributes),
6019 |name_type(qq)=mp_structured_root|, and
6020 |link(qq)=qq1|. (Now pay attention to the next part.) Node |qq1| is
6021 an attribute node representing `\.{x[][]}', which has never yet
6022 occurred; its |type| field is |undefined|, and its |value| field is
6023 undefined. We have |name_type(qq1)=attr|, |attr_loc(qq1)=collective_subscript|,
6024 |parent(qq1)=q1|, and |link(qq1)=qq2|. Since |qq2| represents
6025 `\.{x[]b}', |type(qq2)=mp_unknown_boolean|; also |attr_loc(qq2)=h(b)|,
6026 |parent(qq2)=q1|, |name_type(qq2)=attr|, |link(qq2)=end_attr|.
6027 (Maybe colored lines will help untangle your picture.)
6028  Node |r| is a subscript node with |type| and |value|
6029 representing `\.{x5}'; |name_type(r)=subscr|, |subscript(r)=5.0|,
6030 and |link(r)=r1| is another subscript node. To complete the picture,
6031 see if you can guess what |link(r1)| is; give up? It's~|q1|.
6032 Furthermore |subscript(r1)=20.0|, |name_type(r1)=subscr|,
6033 |type(r1)=mp_structured|, |attr_head(r1)=qqq|, |subscr_head(r1)=qqq1|,
6034 and we finish things off with three more nodes
6035 |qqq|, |qqq1|, and |qqq2| hung onto~|r1|. (Perhaps you should start again
6036 with a larger sheet of paper.) The value of variable \.{x20b}
6037 appears in node~|qqq2|, as you can well imagine.
6038
6039 If the example in the previous paragraph doesn't make things crystal
6040 clear, a glance at some of the simpler subroutines below will reveal how
6041 things work out in practice.
6042
6043 The only really unusual thing about these conventions is the use of
6044 collective subscript attributes. The idea is to avoid repeating a lot of
6045 type information when many elements of an array are identical macros
6046 (for which distinct values need not be stored) or when they don't have
6047 all of the possible attributes. Branches of the structure below collective
6048 subscript attributes do not carry actual values except for macro identifiers;
6049 branches of the structure below subscript nodes do not carry significant
6050 information in their collective subscript attributes.
6051
6052 @d attr_loc_loc(A) ((A)+2) /* where the |attr_loc| and |parent| fields are */
6053 @d attr_loc(A) info(attr_loc_loc((A))) /* hash address of this attribute */
6054 @d parent(A) link(attr_loc_loc((A))) /* pointer to |mp_structured| variable */
6055 @d subscript_loc(A) ((A)+2) /* where the |subscript| field lives */
6056 @d subscript(A) mp->mem[subscript_loc((A))].sc /* subscript of this variable */
6057 @d attr_node_size 3 /* the number of words in an attribute node */
6058 @d subscr_node_size 3 /* the number of words in a subscript node */
6059 @d collective_subscript 0 /* code for the attribute `\.{[]}' */
6060
6061 @<Initialize table...@>=
6062 attr_loc(end_attr)=hash_end+1; parent(end_attr)=null;
6063
6064 @ Variables of type \&{pair} will have values that point to four-word
6065 nodes containing two numeric values. The first of these values has
6066 |name_type=mp_x_part_sector| and the second has |name_type=mp_y_part_sector|;
6067 the |link| in the first points back to the node whose |value| points
6068 to this four-word node.
6069
6070 Variables of type \&{transform} are similar, but in this case their
6071 |value| points to a 12-word node containing six values, identified by
6072 |x_part_sector|, |y_part_sector|, |mp_xx_part_sector|, |mp_xy_part_sector|,
6073 |mp_yx_part_sector|, and |mp_yy_part_sector|.
6074 Finally, variables of type \&{color} have 3~values in 6~words
6075 identified by |mp_red_part_sector|, |mp_green_part_sector|, and |mp_blue_part_sector|.
6076
6077 When an entire structured variable is saved, the |root| indication
6078 is temporarily replaced by |saved_root|.
6079
6080 Some variables have no name; they just are used for temporary storage
6081 while expressions are being evaluated. We call them {\sl capsules}.
6082
6083 @d x_part_loc(A) (A) /* where the \&{xpart} is found in a pair or transform node */
6084 @d y_part_loc(A) ((A)+2) /* where the \&{ypart} is found in a pair or transform node */
6085 @d xx_part_loc(A) ((A)+4) /* where the \&{xxpart} is found in a transform node */
6086 @d xy_part_loc(A) ((A)+6) /* where the \&{xypart} is found in a transform node */
6087 @d yx_part_loc(A) ((A)+8) /* where the \&{yxpart} is found in a transform node */
6088 @d yy_part_loc(A) ((A)+10) /* where the \&{yypart} is found in a transform node */
6089 @d red_part_loc(A) (A) /* where the \&{redpart} is found in a color node */
6090 @d green_part_loc(A) ((A)+2) /* where the \&{greenpart} is found in a color node */
6091 @d blue_part_loc(A) ((A)+4) /* where the \&{bluepart} is found in a color node */
6092 @d cyan_part_loc(A) (A) /* where the \&{cyanpart} is found in a color node */
6093 @d magenta_part_loc(A) ((A)+2) /* where the \&{magentapart} is found in a color node */
6094 @d yellow_part_loc(A) ((A)+4) /* where the \&{yellowpart} is found in a color node */
6095 @d black_part_loc(A) ((A)+6) /* where the \&{blackpart} is found in a color node */
6096 @d grey_part_loc(A) (A) /* where the \&{greypart} is found in a color node */
6097 @#
6098 @d pair_node_size 4 /* the number of words in a pair node */
6099 @d transform_node_size 12 /* the number of words in a transform node */
6100 @d color_node_size 6 /* the number of words in a color node */
6101 @d cmykcolor_node_size 8 /* the number of words in a color node */
6102
6103 @<Glob...@>=
6104 small_number big_node_size[mp_pair_type+1];
6105 small_number sector0[mp_pair_type+1];
6106 small_number sector_offset[mp_black_part_sector+1];
6107
6108 @ The |sector0| array gives for each big node type, |name_type| values
6109 for its first subfield; the |sector_offset| array gives for each
6110 |name_type| value, the offset from the first subfield in words;
6111 and the |big_node_size| array gives the size in words for each type of
6112 big node.
6113
6114 @<Set init...@>=
6115 mp->big_node_size[mp_transform_type]=transform_node_size;
6116 mp->big_node_size[mp_pair_type]=pair_node_size;
6117 mp->big_node_size[mp_color_type]=color_node_size;
6118 mp->big_node_size[mp_cmykcolor_type]=cmykcolor_node_size;
6119 mp->sector0[mp_transform_type]=mp_x_part_sector;
6120 mp->sector0[mp_pair_type]=mp_x_part_sector;
6121 mp->sector0[mp_color_type]=mp_red_part_sector;
6122 mp->sector0[mp_cmykcolor_type]=mp_cyan_part_sector;
6123 for (k=mp_x_part_sector;k<= mp_yy_part_sector;k++ ) {
6124   mp->sector_offset[k]=2*(k-mp_x_part_sector);
6125 }
6126 for (k=mp_red_part_sector;k<= mp_blue_part_sector ; k++) {
6127   mp->sector_offset[k]=2*(k-mp_red_part_sector);
6128 }
6129 for (k=mp_cyan_part_sector;k<= mp_black_part_sector;k++ ) {
6130   mp->sector_offset[k]=2*(k-mp_cyan_part_sector);
6131 }
6132
6133 @ If |type(p)=mp_pair_type| or |mp_transform_type| and if |value(p)=null|, the
6134 procedure call |init_big_node(p)| will allocate a pair or transform node
6135 for~|p|.  The individual parts of such nodes are initially of type
6136 |mp_independent|.
6137
6138 @c 
6139 void mp_init_big_node (MP mp,pointer p) {
6140   pointer q; /* the new node */
6141   small_number s; /* its size */
6142   s=mp->big_node_size[type(p)]; q=mp_get_node(mp, s);
6143   do {  
6144     s=s-2; 
6145     @<Make variable |q+s| newly independent@>;
6146     name_type(q+s)=halfp(s)+mp->sector0[type(p)]; 
6147     link(q+s)=null;
6148   } while (s!=0);
6149   link(q)=p; value(p)=q;
6150 }
6151
6152 @ The |id_transform| function creates a capsule for the
6153 identity transformation.
6154
6155 @c 
6156 pointer mp_id_transform (MP mp) {
6157   pointer p,q,r; /* list manipulation registers */
6158   p=mp_get_node(mp, value_node_size); type(p)=mp_transform_type;
6159   name_type(p)=mp_capsule; value(p)=null; mp_init_big_node(mp, p); q=value(p);
6160   r=q+transform_node_size;
6161   do {  
6162     r=r-2;
6163     type(r)=mp_known; value(r)=0;
6164   } while (r!=q);
6165   value(xx_part_loc(q))=unity; 
6166   value(yy_part_loc(q))=unity;
6167   return p;
6168 }
6169
6170 @ Tokens are of type |tag_token| when they first appear, but they point
6171 to |null| until they are first used as the root of a variable.
6172 The following subroutine establishes the root node on such grand occasions.
6173
6174 @c 
6175 void mp_new_root (MP mp,pointer x) {
6176   pointer p; /* the new node */
6177   p=mp_get_node(mp, value_node_size); type(p)=undefined; name_type(p)=mp_root;
6178   link(p)=x; equiv(x)=p;
6179 }
6180
6181 @ These conventions for variable representation are illustrated by the
6182 |print_variable_name| routine, which displays the full name of a
6183 variable given only a pointer to its two-word value packet.
6184
6185 @<Declarations@>=
6186 void mp_print_variable_name (MP mp, pointer p);
6187
6188 @ @c 
6189 void mp_print_variable_name (MP mp, pointer p) {
6190   pointer q; /* a token list that will name the variable's suffix */
6191   pointer r; /* temporary for token list creation */
6192   while ( name_type(p)>=mp_x_part_sector ) {
6193     @<Preface the output with a part specifier; |return| in the
6194       case of a capsule@>;
6195   }
6196   q=null;
6197   while ( name_type(p)>mp_saved_root ) {
6198     @<Ascend one level, pushing a token onto list |q|
6199      and replacing |p| by its parent@>;
6200   }
6201   r=mp_get_avail(mp); info(r)=link(p); link(r)=q;
6202   if ( name_type(p)==mp_saved_root ) mp_print(mp, "(SAVED)");
6203 @.SAVED@>
6204   mp_show_token_list(mp, r,null,el_gordo,mp->tally); 
6205   mp_flush_token_list(mp, r);
6206 }
6207
6208 @ @<Ascend one level, pushing a token onto list |q|...@>=
6209
6210   if ( name_type(p)==mp_subscr ) { 
6211     r=mp_new_num_tok(mp, subscript(p));
6212     do {  
6213       p=link(p);
6214     } while (name_type(p)!=mp_attr);
6215   } else if ( name_type(p)==mp_structured_root ) {
6216     p=link(p); goto FOUND;
6217   } else { 
6218     if ( name_type(p)!=mp_attr ) mp_confusion(mp, "var");
6219 @:this can't happen var}{\quad var@>
6220     r=mp_get_avail(mp); info(r)=attr_loc(p);
6221   }
6222   link(r)=q; q=r;
6223 FOUND:  
6224   p=parent(p);
6225 }
6226
6227 @ @<Preface the output with a part specifier...@>=
6228 { switch (name_type(p)) {
6229   case mp_x_part_sector: mp_print_char(mp, 'x'); break;
6230   case mp_y_part_sector: mp_print_char(mp, 'y'); break;
6231   case mp_xx_part_sector: mp_print(mp, "xx"); break;
6232   case mp_xy_part_sector: mp_print(mp, "xy"); break;
6233   case mp_yx_part_sector: mp_print(mp, "yx"); break;
6234   case mp_yy_part_sector: mp_print(mp, "yy"); break;
6235   case mp_red_part_sector: mp_print(mp, "red"); break;
6236   case mp_green_part_sector: mp_print(mp, "green"); break;
6237   case mp_blue_part_sector: mp_print(mp, "blue"); break;
6238   case mp_cyan_part_sector: mp_print(mp, "cyan"); break;
6239   case mp_magenta_part_sector: mp_print(mp, "magenta"); break;
6240   case mp_yellow_part_sector: mp_print(mp, "yellow"); break;
6241   case mp_black_part_sector: mp_print(mp, "black"); break;
6242   case mp_grey_part_sector: mp_print(mp, "grey"); break;
6243   case mp_capsule: 
6244     mp_print(mp, "%CAPSULE"); mp_print_int(mp, p-null); return;
6245     break;
6246 @.CAPSULE@>
6247   } /* there are no other cases */
6248   mp_print(mp, "part "); 
6249   p=link(p-mp->sector_offset[name_type(p)]);
6250 }
6251
6252 @ The |interesting| function returns |true| if a given variable is not
6253 in a capsule, or if the user wants to trace capsules.
6254
6255 @c 
6256 boolean mp_interesting (MP mp,pointer p) {
6257   small_number t; /* a |name_type| */
6258   if ( mp->internal[mp_tracing_capsules]>0 ) {
6259     return true;
6260   } else { 
6261     t=name_type(p);
6262     if ( t>=mp_x_part_sector ) if ( t!=mp_capsule )
6263       t=name_type(link(p-mp->sector_offset[t]));
6264     return (t!=mp_capsule);
6265   }
6266 }
6267
6268 @ Now here is a subroutine that converts an unstructured type into an
6269 equivalent structured type, by inserting a |mp_structured| node that is
6270 capable of growing. This operation is done only when |name_type(p)=root|,
6271 |subscr|, or |attr|.
6272
6273 The procedure returns a pointer to the new node that has taken node~|p|'s
6274 place in the structure. Node~|p| itself does not move, nor are its
6275 |value| or |type| fields changed in any way.
6276
6277 @c 
6278 pointer mp_new_structure (MP mp,pointer p) {
6279   pointer q,r=0; /* list manipulation registers */
6280   switch (name_type(p)) {
6281   case mp_root: 
6282     q=link(p); r=mp_get_node(mp, value_node_size); equiv(q)=r;
6283     break;
6284   case mp_subscr: 
6285     @<Link a new subscript node |r| in place of node |p|@>;
6286     break;
6287   case mp_attr: 
6288     @<Link a new attribute node |r| in place of node |p|@>;
6289     break;
6290   default: 
6291     mp_confusion(mp, "struct");
6292 @:this can't happen struct}{\quad struct@>
6293     break;
6294   }
6295   link(r)=link(p); type(r)=mp_structured; name_type(r)=name_type(p);
6296   attr_head(r)=p; name_type(p)=mp_structured_root;
6297   q=mp_get_node(mp, attr_node_size); link(p)=q; subscr_head(r)=q;
6298   parent(q)=r; type(q)=undefined; name_type(q)=mp_attr; link(q)=end_attr;
6299   attr_loc(q)=collective_subscript; 
6300   return r;
6301 };
6302
6303 @ @<Link a new subscript node |r| in place of node |p|@>=
6304
6305   q=p;
6306   do {  
6307     q=link(q);
6308   } while (name_type(q)!=mp_attr);
6309   q=parent(q); r=subscr_head_loc(q); /* |link(r)=subscr_head(q)| */
6310   do {  
6311     q=r; r=link(r);
6312   } while (r!=p);
6313   r=mp_get_node(mp, subscr_node_size);
6314   link(q)=r; subscript(r)=subscript(p);
6315 }
6316
6317 @ If the attribute is |collective_subscript|, there are two pointers to
6318 node~|p|, so we must change both of them.
6319
6320 @<Link a new attribute node |r| in place of node |p|@>=
6321
6322   q=parent(p); r=attr_head(q);
6323   do {  
6324     q=r; r=link(r);
6325   } while (r!=p);
6326   r=mp_get_node(mp, attr_node_size); link(q)=r;
6327   mp->mem[attr_loc_loc(r)]=mp->mem[attr_loc_loc(p)]; /* copy |attr_loc| and |parent| */
6328   if ( attr_loc(p)==collective_subscript ) { 
6329     q=subscr_head_loc(parent(p));
6330     while ( link(q)!=p ) q=link(q);
6331     link(q)=r;
6332   }
6333 }
6334
6335 @ The |find_variable| routine is given a pointer~|t| to a nonempty token
6336 list of suffixes; it returns a pointer to the corresponding two-word
6337 value. For example, if |t| points to token \.x followed by a numeric
6338 token containing the value~7, |find_variable| finds where the value of
6339 \.{x7} is stored in memory. This may seem a simple task, and it
6340 usually is, except when \.{x7} has never been referenced before.
6341 Indeed, \.x may never have even been subscripted before; complexities
6342 arise with respect to updating the collective subscript information.
6343
6344 If a macro type is detected anywhere along path~|t|, or if the first
6345 item on |t| isn't a |tag_token|, the value |null| is returned.
6346 Otherwise |p| will be a non-null pointer to a node such that
6347 |undefined<type(p)<mp_structured|.
6348
6349 @d abort_find { return null; }
6350
6351 @c 
6352 pointer mp_find_variable (MP mp,pointer t) {
6353   pointer p,q,r,s; /* nodes in the ``value'' line */
6354   pointer pp,qq,rr,ss; /* nodes in the ``collective'' line */
6355   integer n; /* subscript or attribute */
6356   memory_word save_word; /* temporary storage for a word of |mem| */
6357 @^inner loop@>
6358   p=info(t); t=link(t);
6359   if ( (eq_type(p) % outer_tag) != tag_token ) abort_find;
6360   if ( equiv(p)==null ) mp_new_root(mp, p);
6361   p=equiv(p); pp=p;
6362   while ( t!=null ) { 
6363     @<Make sure that both nodes |p| and |pp| are of |mp_structured| type@>;
6364     if ( t<mp->hi_mem_min ) {
6365       @<Descend one level for the subscript |value(t)|@>
6366     } else {
6367       @<Descend one level for the attribute |info(t)|@>;
6368     }
6369     t=link(t);
6370   }
6371   if ( type(pp)>=mp_structured ) {
6372     if ( type(pp)==mp_structured ) pp=attr_head(pp); else abort_find;
6373   }
6374   if ( type(p)==mp_structured ) p=attr_head(p);
6375   if ( type(p)==undefined ) { 
6376     if ( type(pp)==undefined ) { type(pp)=mp_numeric_type; value(pp)=null; };
6377     type(p)=type(pp); value(p)=null;
6378   };
6379   return p;
6380 }
6381
6382 @ Although |pp| and |p| begin together, they diverge when a subscript occurs;
6383 |pp|~stays in the collective line while |p|~goes through actual subscript
6384 values.
6385
6386 @<Make sure that both nodes |p| and |pp|...@>=
6387 if ( type(pp)!=mp_structured ) { 
6388   if ( type(pp)>mp_structured ) abort_find;
6389   ss=mp_new_structure(mp, pp);
6390   if ( p==pp ) p=ss;
6391   pp=ss;
6392 }; /* now |type(pp)=mp_structured| */
6393 if ( type(p)!=mp_structured ) /* it cannot be |>mp_structured| */
6394   p=mp_new_structure(mp, p) /* now |type(p)=mp_structured| */
6395
6396 @ We want this part of the program to be reasonably fast, in case there are
6397 @^inner loop@>
6398 lots of subscripts at the same level of the data structure. Therefore
6399 we store an ``infinite'' value in the word that appears at the end of the
6400 subscript list, even though that word isn't part of a subscript node.
6401
6402 @<Descend one level for the subscript |value(t)|@>=
6403
6404   n=value(t);
6405   pp=link(attr_head(pp)); /* now |attr_loc(pp)=collective_subscript| */
6406   q=link(attr_head(p)); save_word=mp->mem[subscript_loc(q)];
6407   subscript(q)=el_gordo; s=subscr_head_loc(p); /* |link(s)=subscr_head(p)| */
6408   do {  
6409     r=s; s=link(s);
6410   } while (n>subscript(s));
6411   if ( n==subscript(s) ) {
6412     p=s;
6413   } else { 
6414     p=mp_get_node(mp, subscr_node_size); link(r)=p; link(p)=s;
6415     subscript(p)=n; name_type(p)=mp_subscr; type(p)=undefined;
6416   }
6417   mp->mem[subscript_loc(q)]=save_word;
6418 }
6419
6420 @ @<Descend one level for the attribute |info(t)|@>=
6421
6422   n=info(t);
6423   ss=attr_head(pp);
6424   do {  
6425     rr=ss; ss=link(ss);
6426   } while (n>attr_loc(ss));
6427   if ( n<attr_loc(ss) ) { 
6428     qq=mp_get_node(mp, attr_node_size); link(rr)=qq; link(qq)=ss;
6429     attr_loc(qq)=n; name_type(qq)=mp_attr; type(qq)=undefined;
6430     parent(qq)=pp; ss=qq;
6431   }
6432   if ( p==pp ) { 
6433     p=ss; pp=ss;
6434   } else { 
6435     pp=ss; s=attr_head(p);
6436     do {  
6437       r=s; s=link(s);
6438     } while (n>attr_loc(s));
6439     if ( n==attr_loc(s) ) {
6440       p=s;
6441     } else { 
6442       q=mp_get_node(mp, attr_node_size); link(r)=q; link(q)=s;
6443       attr_loc(q)=n; name_type(q)=mp_attr; type(q)=undefined;
6444       parent(q)=p; p=q;
6445     }
6446   }
6447 }
6448
6449 @ Variables lose their former values when they appear in a type declaration,
6450 or when they are defined to be macros or \&{let} equal to something else.
6451 A subroutine will be defined later that recycles the storage associated
6452 with any particular |type| or |value|; our goal now is to study a higher
6453 level process called |flush_variable|, which selectively frees parts of a
6454 variable structure.
6455
6456 This routine has some complexity because of examples such as
6457 `\hbox{\tt numeric x[]a[]b}'
6458 which recycles all variables of the form \.{x[i]a[j]b} (and no others), while
6459 `\hbox{\tt vardef x[]a[]=...}'
6460 discards all variables of the form \.{x[i]a[j]} followed by an arbitrary
6461 suffix, except for the collective node \.{x[]a[]} itself. The obvious way
6462 to handle such examples is to use recursion; so that's what we~do.
6463 @^recursion@>
6464
6465 Parameter |p| points to the root information of the variable;
6466 parameter |t| points to a list of one-word nodes that represent
6467 suffixes, with |info=collective_subscript| for subscripts.
6468
6469 @<Declarations@>=
6470 @<Declare subroutines for printing expressions@>
6471 @<Declare basic dependency-list subroutines@>
6472 @<Declare the recycling subroutines@>
6473 void mp_flush_cur_exp (MP mp,scaled v) ;
6474 @<Declare the procedure called |flush_below_variable|@>
6475
6476 @ @c 
6477 void mp_flush_variable (MP mp,pointer p, pointer t, boolean discard_suffixes) {
6478   pointer q,r; /* list manipulation */
6479   halfword n; /* attribute to match */
6480   while ( t!=null ) { 
6481     if ( type(p)!=mp_structured ) return;
6482     n=info(t); t=link(t);
6483     if ( n==collective_subscript ) { 
6484       r=subscr_head_loc(p); q=link(r); /* |q=subscr_head(p)| */
6485       while ( name_type(q)==mp_subscr ){ 
6486         mp_flush_variable(mp, q,t,discard_suffixes);
6487         if ( t==null ) {
6488           if ( type(q)==mp_structured ) r=q;
6489           else  { link(r)=link(q); mp_free_node(mp, q,subscr_node_size);   }
6490         } else {
6491           r=q;
6492         }
6493         q=link(r);
6494       }
6495     }
6496     p=attr_head(p);
6497     do {  
6498       r=p; p=link(p);
6499     } while (attr_loc(p)<n);
6500     if ( attr_loc(p)!=n ) return;
6501   }
6502   if ( discard_suffixes ) {
6503     mp_flush_below_variable(mp, p);
6504   } else { 
6505     if ( type(p)==mp_structured ) p=attr_head(p);
6506     mp_recycle_value(mp, p);
6507   }
6508 }
6509
6510 @ The next procedure is simpler; it wipes out everything but |p| itself,
6511 which becomes undefined.
6512
6513 @<Declare the procedure called |flush_below_variable|@>=
6514 void mp_flush_below_variable (MP mp, pointer p);
6515
6516 @ @c
6517 void mp_flush_below_variable (MP mp,pointer p) {
6518    pointer q,r; /* list manipulation registers */
6519   if ( type(p)!=mp_structured ) {
6520     mp_recycle_value(mp, p); /* this sets |type(p)=undefined| */
6521   } else { 
6522     q=subscr_head(p);
6523     while ( name_type(q)==mp_subscr ) { 
6524       mp_flush_below_variable(mp, q); r=q; q=link(q);
6525       mp_free_node(mp, r,subscr_node_size);
6526     }
6527     r=attr_head(p); q=link(r); mp_recycle_value(mp, r);
6528     if ( name_type(p)<=mp_saved_root ) mp_free_node(mp, r,value_node_size);
6529     else mp_free_node(mp, r,subscr_node_size);
6530     /* we assume that |subscr_node_size=attr_node_size| */
6531     do {  
6532       mp_flush_below_variable(mp, q); r=q; q=link(q); mp_free_node(mp, r,attr_node_size);
6533     } while (q!=end_attr);
6534     type(p)=undefined;
6535   }
6536 }
6537
6538 @ Just before assigning a new value to a variable, we will recycle the
6539 old value and make the old value undefined. The |und_type| routine
6540 determines what type of undefined value should be given, based on
6541 the current type before recycling.
6542
6543 @c 
6544 small_number mp_und_type (MP mp,pointer p) { 
6545   switch (type(p)) {
6546   case undefined: case mp_vacuous:
6547     return undefined;
6548   case mp_boolean_type: case mp_unknown_boolean:
6549     return mp_unknown_boolean;
6550   case mp_string_type: case mp_unknown_string:
6551     return mp_unknown_string;
6552   case mp_pen_type: case mp_unknown_pen:
6553     return mp_unknown_pen;
6554   case mp_path_type: case mp_unknown_path:
6555     return mp_unknown_path;
6556   case mp_picture_type: case mp_unknown_picture:
6557     return mp_unknown_picture;
6558   case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
6559   case mp_pair_type: case mp_numeric_type: 
6560     return type(p);
6561   case mp_known: case mp_dependent: case mp_proto_dependent: case mp_independent:
6562     return mp_numeric_type;
6563   } /* there are no other cases */
6564   return 0;
6565 }
6566
6567 @ The |clear_symbol| routine is used when we want to redefine the equivalent
6568 of a symbolic token. It must remove any variable structure or macro
6569 definition that is currently attached to that symbol. If the |saving|
6570 parameter is true, a subsidiary structure is saved instead of destroyed.
6571
6572 @c 
6573 void mp_clear_symbol (MP mp,pointer p, boolean saving) {
6574   pointer q; /* |equiv(p)| */
6575   q=equiv(p);
6576   switch (eq_type(p) % outer_tag)  {
6577   case defined_macro:
6578   case secondary_primary_macro:
6579   case tertiary_secondary_macro:
6580   case expression_tertiary_macro: 
6581     if ( ! saving ) mp_delete_mac_ref(mp, q);
6582     break;
6583   case tag_token:
6584     if ( q!=null ) {
6585       if ( saving ) {
6586         name_type(q)=mp_saved_root;
6587       } else { 
6588         mp_flush_below_variable(mp, q); mp_free_node(mp,q,value_node_size); 
6589       }
6590     }
6591     break;
6592   default:
6593     break;
6594   }
6595   mp->eqtb[p]=mp->eqtb[frozen_undefined];
6596 };
6597
6598 @* \[16] Saving and restoring equivalents.
6599 The nested structure given by \&{begingroup} and \&{endgroup}
6600 allows |eqtb| entries to be saved and restored, so that temporary changes
6601 can be made without difficulty.  When the user requests a current value to
6602 be saved, \MP\ puts that value into its ``save stack.'' An appearance of
6603 \&{endgroup} ultimately causes the old values to be removed from the save
6604 stack and put back in their former places.
6605
6606 The save stack is a linked list containing three kinds of entries,
6607 distinguished by their |info| fields. If |p| points to a saved item,
6608 then
6609
6610 \smallskip\hang
6611 |info(p)=0| stands for a group boundary; each \&{begingroup} contributes
6612 such an item to the save stack and each \&{endgroup} cuts back the stack
6613 until the most recent such entry has been removed.
6614
6615 \smallskip\hang
6616 |info(p)=q|, where |1<=q<=hash_end|, means that |mem[p+1]| holds the former
6617 contents of |eqtb[q]|. Such save stack entries are generated by \&{save}
6618 commands or suitable \&{interim} commands.
6619
6620 \smallskip\hang
6621 |info(p)=hash_end+q|, where |q>0|, means that |value(p)| is a |scaled|
6622 integer to be restored to internal parameter number~|q|. Such entries
6623 are generated by \&{interim} commands.
6624
6625 \smallskip\noindent
6626 The global variable |save_ptr| points to the top item on the save stack.
6627
6628 @d save_node_size 2 /* number of words per non-boundary save-stack node */
6629 @d saved_equiv(A) mp->mem[(A)+1].hh /* where an |eqtb| entry gets saved */
6630 @d save_boundary_item(A) { (A)=mp_get_avail(mp); info((A))=0;
6631   link((A))=mp->save_ptr; mp->save_ptr=(A);
6632   }
6633
6634 @<Glob...@>=
6635 pointer save_ptr; /* the most recently saved item */
6636
6637 @ @<Set init...@>=mp->save_ptr=null;
6638
6639 @ The |save_variable| routine is given a hash address |q|; it salts this
6640 address in the save stack, together with its current equivalent,
6641 then makes token~|q| behave as though it were brand new.
6642
6643 Nothing is stacked when |save_ptr=null|, however; there's no way to remove
6644 things from the stack when the program is not inside a group, so there's
6645 no point in wasting the space.
6646
6647 @c void mp_save_variable (MP mp,pointer q) {
6648   pointer p; /* temporary register */
6649   if ( mp->save_ptr!=null ){ 
6650     p=mp_get_node(mp, save_node_size); info(p)=q; link(p)=mp->save_ptr;
6651     saved_equiv(p)=mp->eqtb[q]; mp->save_ptr=p;
6652   }
6653   mp_clear_symbol(mp, q,(mp->save_ptr!=null));
6654 }
6655
6656 @ Similarly, |save_internal| is given the location |q| of an internal
6657 quantity like |mp_tracing_pens|. It creates a save stack entry of the
6658 third kind.
6659
6660 @c void mp_save_internal (MP mp,halfword q) {
6661   pointer p; /* new item for the save stack */
6662   if ( mp->save_ptr!=null ){ 
6663      p=mp_get_node(mp, save_node_size); info(p)=hash_end+q;
6664     link(p)=mp->save_ptr; value(p)=mp->internal[q]; mp->save_ptr=p;
6665   }
6666 }
6667
6668 @ At the end of a group, the |unsave| routine restores all of the saved
6669 equivalents in reverse order. This routine will be called only when there
6670 is at least one boundary item on the save stack.
6671
6672 @c 
6673 void mp_unsave (MP mp) {
6674   pointer q; /* index to saved item */
6675   pointer p; /* temporary register */
6676   while ( info(mp->save_ptr)!=0 ) {
6677     q=info(mp->save_ptr);
6678     if ( q>hash_end ) {
6679       if ( mp->internal[mp_tracing_restores]>0 ) {
6680         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6681         mp_print(mp, mp->int_name[q-(hash_end)]); mp_print_char(mp, '=');
6682         mp_print_scaled(mp, value(mp->save_ptr)); mp_print_char(mp, '}');
6683         mp_end_diagnostic(mp, false);
6684       }
6685       mp->internal[q-(hash_end)]=value(mp->save_ptr);
6686     } else { 
6687       if ( mp->internal[mp_tracing_restores]>0 ) {
6688         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6689         mp_print_text(q); mp_print_char(mp, '}');
6690         mp_end_diagnostic(mp, false);
6691       }
6692       mp_clear_symbol(mp, q,false);
6693       mp->eqtb[q]=saved_equiv(mp->save_ptr);
6694       if ( eq_type(q) % outer_tag==tag_token ) {
6695         p=equiv(q);
6696         if ( p!=null ) name_type(p)=mp_root;
6697       }
6698     }
6699     p=link(mp->save_ptr); 
6700     mp_free_node(mp, mp->save_ptr,save_node_size); mp->save_ptr=p;
6701   }
6702   p=link(mp->save_ptr); free_avail(mp->save_ptr); mp->save_ptr=p;
6703 }
6704
6705 @* \[17] Data structures for paths.
6706 When a \MP\ user specifies a path, \MP\ will create a list of knots
6707 and control points for the associated cubic spline curves. If the
6708 knots are $z_0$, $z_1$, \dots, $z_n$, there are control points
6709 $z_k^+$ and $z_{k+1}^-$ such that the cubic splines between knots
6710 $z_k$ and $z_{k+1}$ are defined by B\'ezier's formula
6711 @:Bezier}{B\'ezier, Pierre Etienne@>
6712 $$\eqalign{z(t)&=B(z_k,z_k^+,z_{k+1}^-,z_{k+1};t)\cr
6713 &=(1-t)^3z_k+3(1-t)^2tz_k^++3(1-t)t^2z_{k+1}^-+t^3z_{k+1}\cr}$$
6714 for |0<=t<=1|.
6715
6716 There is a 8-word node for each knot $z_k$, containing one word of
6717 control information and six words for the |x| and |y| coordinates of
6718 $z_k^-$ and $z_k$ and~$z_k^+$. The control information appears in the
6719 |left_type| and |right_type| fields, which each occupy a quarter of
6720 the first word in the node; they specify properties of the curve as it
6721 enters and leaves the knot. There's also a halfword |link| field,
6722 which points to the following knot, and a final supplementary word (of
6723 which only a quarter is used).
6724
6725 If the path is a closed contour, knots 0 and |n| are identical;
6726 i.e., the |link| in knot |n-1| points to knot~0. But if the path
6727 is not closed, the |left_type| of knot~0 and the |right_type| of knot~|n|
6728 are equal to |endpoint|. In the latter case the |link| in knot~|n| points
6729 to knot~0, and the control points $z_0^-$ and $z_n^+$ are not used.
6730
6731 @d left_type(A)   mp->mem[(A)].hh.b0 /* characterizes the path entering this knot */
6732 @d right_type(A)   mp->mem[(A)].hh.b1 /* characterizes the path leaving this knot */
6733 @d x_coord(A)   mp->mem[(A)+1].sc /* the |x| coordinate of this knot */
6734 @d y_coord(A)   mp->mem[(A)+2].sc /* the |y| coordinate of this knot */
6735 @d left_x(A)   mp->mem[(A)+3].sc /* the |x| coordinate of previous control point */
6736 @d left_y(A)   mp->mem[(A)+4].sc /* the |y| coordinate of previous control point */
6737 @d right_x(A)   mp->mem[(A)+5].sc /* the |x| coordinate of next control point */
6738 @d right_y(A)   mp->mem[(A)+6].sc /* the |y| coordinate of next control point */
6739 @d x_loc(A)   ((A)+1) /* where the |x| coordinate is stored in a knot */
6740 @d y_loc(A)   ((A)+2) /* where the |y| coordinate is stored in a knot */
6741 @d knot_coord(A)   mp->mem[(A)].sc /* |x| or |y| coordinate given |x_loc| or |y_loc| */
6742 @d left_coord(A)   mp->mem[(A)+2].sc
6743   /* coordinate of previous control point given |x_loc| or |y_loc| */
6744 @d right_coord(A)   mp->mem[(A)+4].sc
6745   /* coordinate of next control point given |x_loc| or |y_loc| */
6746 @d knot_node_size 8 /* number of words in a knot node */
6747
6748 @<Types...@>=
6749 enum mp_knot_type {
6750  mp_endpoint=0, /* |left_type| at path beginning and |right_type| at path end */
6751  mp_explicit, /* |left_type| or |right_type| when control points are known */
6752  mp_given, /* |left_type| or |right_type| when a direction is given */
6753  mp_curl, /* |left_type| or |right_type| when a curl is desired */
6754  mp_open, /* |left_type| or |right_type| when \MP\ should choose the direction */
6755  mp_end_cycle
6756 } ;
6757
6758 @ Before the B\'ezier control points have been calculated, the memory
6759 space they will ultimately occupy is taken up by information that can be
6760 used to compute them. There are four cases:
6761
6762 \yskip
6763 \textindent{$\bullet$} If |right_type=mp_open|, the curve should leave
6764 the knot in the same direction it entered; \MP\ will figure out a
6765 suitable direction.
6766
6767 \yskip
6768 \textindent{$\bullet$} If |right_type=mp_curl|, the curve should leave the
6769 knot in a direction depending on the angle at which it enters the next
6770 knot and on the curl parameter stored in |right_curl|.
6771
6772 \yskip
6773 \textindent{$\bullet$} If |right_type=mp_given|, the curve should leave the
6774 knot in a nonzero direction stored as an |angle| in |right_given|.
6775
6776 \yskip
6777 \textindent{$\bullet$} If |right_type=mp_explicit|, the B\'ezier control
6778 point for leaving this knot has already been computed; it is in the
6779 |right_x| and |right_y| fields.
6780
6781 \yskip\noindent
6782 The rules for |left_type| are similar, but they refer to the curve entering
6783 the knot, and to \\{left} fields instead of \\{right} fields.
6784
6785 Non-|explicit| control points will be chosen based on ``tension'' parameters
6786 in the |left_tension| and |right_tension| fields. The
6787 `\&{atleast}' option is represented by negative tension values.
6788 @:at_least_}{\&{atleast} primitive@>
6789
6790 For example, the \MP\ path specification
6791 $$\.{z0..z1..tension atleast 1..\{curl 2\}z2..z3\{-1,-2\}..tension
6792   3 and 4..p},$$
6793 where \.p is the path `\.{z4..controls z45 and z54..z5}', will be represented
6794 by the six knots
6795 \def\lodash{\hbox to 1.1em{\thinspace\hrulefill\thinspace}}
6796 $$\vbox{\halign{#\hfil&&\qquad#\hfil\cr
6797 |left_type|&\\{left} info&|x_coord,y_coord|&|right_type|&\\{right} info\cr
6798 \noalign{\yskip}
6799 |endpoint|&\lodash$,\,$\lodash&$x_0,y_0$&|curl|&$1.0,1.0$\cr
6800 |open|&\lodash$,1.0$&$x_1,y_1$&|open|&\lodash$,-1.0$\cr
6801 |curl|&$2.0,-1.0$&$x_2,y_2$&|curl|&$2.0,1.0$\cr
6802 |given|&$d,1.0$&$x_3,y_3$&|given|&$d,3.0$\cr
6803 |open|&\lodash$,4.0$&$x_4,y_4$&|explicit|&$x_{45},y_{45}$\cr
6804 |explicit|&$x_{54},y_{54}$&$x_5,y_5$&|endpoint|&\lodash$,\,$\lodash\cr}}$$
6805 Here |d| is the |angle| obtained by calling |n_arg(-unity,-two)|.
6806 Of course, this example is more complicated than anything a normal user
6807 would ever write.
6808
6809 These types must satisfy certain restrictions because of the form of \MP's
6810 path syntax:
6811 (i)~|open| type never appears in the same node together with |endpoint|,
6812 |given|, or |curl|.
6813 (ii)~The |right_type| of a node is |explicit| if and only if the
6814 |left_type| of the following node is |explicit|.
6815 (iii)~|endpoint| types occur only at the ends, as mentioned above.
6816
6817 @d left_curl left_x /* curl information when entering this knot */
6818 @d left_given left_x /* given direction when entering this knot */
6819 @d left_tension left_y /* tension information when entering this knot */
6820 @d right_curl right_x /* curl information when leaving this knot */
6821 @d right_given right_x /* given direction when leaving this knot */
6822 @d right_tension right_y /* tension information when leaving this knot */
6823
6824 @ Knots can be user-supplied, or they can be created by program code,
6825 like the |split_cubic| function, or |copy_path|. The distinction is
6826 needed for the cleanup routine that runs after |split_cubic|, because
6827 it should only delete knots it has previously inserted, and never
6828 anything that was user-supplied. In order to be able to differentiate
6829 one knot from another, we will set |originator(p):=mp_metapost_user| when
6830 it appeared in the actual metapost program, and
6831 |originator(p):=mp_program_code| in all other cases.
6832
6833 @d originator(A)   mp->mem[(A)+7].hh.b0 /* the creator of this knot */
6834
6835 @<Types...@>=
6836 enum {
6837   mp_program_code=0, /* not created by a user */
6838   mp_metapost_user, /* created by a user */
6839 };
6840
6841 @ Here is a routine that prints a given knot list
6842 in symbolic form. It illustrates the conventions discussed above,
6843 and checks for anomalies that might arise while \MP\ is being debugged.
6844
6845 @<Declare subroutines for printing expressions@>=
6846 void mp_pr_path (MP mp,pointer h);
6847
6848 @ @c
6849 void mp_pr_path (MP mp,pointer h) {
6850   pointer p,q; /* for list traversal */
6851   p=h;
6852   do {  
6853     q=link(p);
6854     if ( (p==null)||(q==null) ) { 
6855       mp_print_nl(mp, "???"); return; /* this won't happen */
6856 @.???@>
6857     }
6858     @<Print information for adjacent knots |p| and |q|@>;
6859   DONE1:
6860     p=q;
6861     if ( (p!=h)||(left_type(h)!=mp_endpoint) ) {
6862       @<Print two dots, followed by |given| or |curl| if present@>;
6863     }
6864   } while (p!=h);
6865   if ( left_type(h)!=mp_endpoint ) 
6866     mp_print(mp, "cycle");
6867 }
6868
6869 @ @<Print information for adjacent knots...@>=
6870 mp_print_two(mp, x_coord(p),y_coord(p));
6871 switch (right_type(p)) {
6872 case mp_endpoint: 
6873   if ( left_type(p)==mp_open ) mp_print(mp, "{open?}"); /* can't happen */
6874 @.open?@>
6875   if ( (left_type(q)!=mp_endpoint)||(q!=h) ) q=null; /* force an error */
6876   goto DONE1;
6877   break;
6878 case mp_explicit: 
6879   @<Print control points between |p| and |q|, then |goto done1|@>;
6880   break;
6881 case mp_open: 
6882   @<Print information for a curve that begins |open|@>;
6883   break;
6884 case mp_curl:
6885 case mp_given: 
6886   @<Print information for a curve that begins |curl| or |given|@>;
6887   break;
6888 default:
6889   mp_print(mp, "???"); /* can't happen */
6890 @.???@>
6891   break;
6892 }
6893 if ( left_type(q)<=mp_explicit ) {
6894   mp_print(mp, "..control?"); /* can't happen */
6895 @.control?@>
6896 } else if ( (right_tension(p)!=unity)||(left_tension(q)!=unity) ) {
6897   @<Print tension between |p| and |q|@>;
6898 }
6899
6900 @ Since |n_sin_cos| produces |fraction| results, which we will print as if they
6901 were |scaled|, the magnitude of a |given| direction vector will be~4096.
6902
6903 @<Print two dots...@>=
6904
6905   mp_print_nl(mp, " ..");
6906   if ( left_type(p)==mp_given ) { 
6907     mp_n_sin_cos(mp, left_given(p)); mp_print_char(mp, '{');
6908     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ',');
6909     mp_print_scaled(mp, mp->n_sin); mp_print_char(mp, '}');
6910   } else if ( left_type(p)==mp_curl ){ 
6911     mp_print(mp, "{curl "); 
6912     mp_print_scaled(mp, left_curl(p)); mp_print_char(mp, '}');
6913   }
6914 }
6915
6916 @ @<Print tension between |p| and |q|@>=
6917
6918   mp_print(mp, "..tension ");
6919   if ( right_tension(p)<0 ) mp_print(mp, "atleast");
6920   mp_print_scaled(mp, abs(right_tension(p)));
6921   if ( right_tension(p)!=left_tension(q) ){ 
6922     mp_print(mp, " and ");
6923     if ( left_tension(q)<0 ) mp_print(mp, "atleast");
6924     mp_print_scaled(mp, abs(left_tension(q)));
6925   }
6926 }
6927
6928 @ @<Print control points between |p| and |q|, then |goto done1|@>=
6929
6930   mp_print(mp, "..controls "); 
6931   mp_print_two(mp, right_x(p),right_y(p)); 
6932   mp_print(mp, " and ");
6933   if ( left_type(q)!=mp_explicit ) { 
6934     mp_print(mp, "??"); /* can't happen */
6935 @.??@>
6936   } else {
6937     mp_print_two(mp, left_x(q),left_y(q));
6938   }
6939   goto DONE1;
6940 }
6941
6942 @ @<Print information for a curve that begins |open|@>=
6943 if ( (left_type(p)!=mp_explicit)&&(left_type(p)!=mp_open) ) {
6944   mp_print(mp, "{open?}"); /* can't happen */
6945 @.open?@>
6946 }
6947
6948 @ A curl of 1 is shown explicitly, so that the user sees clearly that
6949 \MP's default curl is present.
6950
6951 The code here uses the fact that |left_curl==left_given| and
6952 |right_curl==right_given|.
6953
6954 @<Print information for a curve that begins |curl|...@>=
6955
6956   if ( left_type(p)==mp_open )  
6957     mp_print(mp, "??"); /* can't happen */
6958 @.??@>
6959   if ( right_type(p)==mp_curl ) { 
6960     mp_print(mp, "{curl "); mp_print_scaled(mp, right_curl(p));
6961   } else { 
6962     mp_n_sin_cos(mp, right_given(p)); mp_print_char(mp, '{');
6963     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ','); 
6964     mp_print_scaled(mp, mp->n_sin);
6965   }
6966   mp_print_char(mp, '}');
6967 }
6968
6969 @ It is convenient to have another version of |pr_path| that prints the path
6970 as a diagnostic message.
6971
6972 @<Declare subroutines for printing expressions@>=
6973 void mp_print_path (MP mp,pointer h, char *s, boolean nuline) { 
6974   mp_print_diagnostic(mp, "Path", s, nuline); mp_print_ln(mp);
6975 @.Path at line...@>
6976   mp_pr_path(mp, h);
6977   mp_end_diagnostic(mp, true);
6978 }
6979
6980 @ If we want to duplicate a knot node, we can say |copy_knot|:
6981
6982 @c 
6983 pointer mp_copy_knot (MP mp,pointer p) {
6984   pointer q; /* the copy */
6985   int k; /* runs through the words of a knot node */
6986   q=mp_get_node(mp, knot_node_size);
6987   for (k=0;k<knot_node_size;k++) {
6988     mp->mem[q+k]=mp->mem[p+k];
6989   }
6990   originator(q)=originator(p);
6991   return q;
6992 }
6993
6994 @ The |copy_path| routine makes a clone of a given path.
6995
6996 @c 
6997 pointer mp_copy_path (MP mp, pointer p) {
6998   pointer q,pp,qq; /* for list manipulation */
6999   q=mp_copy_knot(mp, p);
7000   qq=q; pp=link(p);
7001   while ( pp!=p ) { 
7002     link(qq)=mp_copy_knot(mp, pp);
7003     qq=link(qq);
7004     pp=link(pp);
7005   }
7006   link(qq)=q;
7007   return q;
7008 }
7009
7010
7011 @ Just before |ship_out|, knot lists are exported for printing.
7012
7013 The |gr_XXXX| macros are defined in |mppsout.h|.
7014
7015 @c 
7016 struct mp_knot *mp_export_knot (MP mp,pointer p) {
7017   struct mp_knot *q; /* the copy */
7018   if (p==null)
7019      return NULL;
7020   q = mp_xmalloc(mp, 1, sizeof (struct mp_knot));
7021   memset(q,0,sizeof (struct mp_knot));
7022   gr_left_type(q)  = left_type(p);
7023   gr_right_type(q) = right_type(p);
7024   gr_x_coord(q)    = x_coord(p);
7025   gr_y_coord(q)    = y_coord(p);
7026   gr_left_x(q)     = left_x(p);
7027   gr_left_y(q)     = left_y(p);
7028   gr_right_x(q)    = right_x(p);
7029   gr_right_y(q)    = right_y(p);
7030   gr_originator(q) = originator(p);
7031   return q;
7032 }
7033
7034 @ The |export_knot_list| routine therefore also makes a clone 
7035 of a given path.
7036
7037 @c 
7038 struct mp_knot *mp_export_knot_list (MP mp, pointer p) {
7039   struct mp_knot *q, *qq; /* for list manipulation */
7040   pointer pp; /* for list manipulation */
7041   if (p==null)
7042      return NULL;
7043   q=mp_export_knot(mp, p);
7044   qq=q; pp=link(p);
7045   while ( pp!=p ) { 
7046     gr_next_knot(qq)=mp_export_knot(mp, pp);
7047     qq=gr_next_knot(qq);
7048     pp=link(pp);
7049   }
7050   gr_next_knot(qq)=q;
7051   return q;
7052 }
7053
7054
7055 @ Similarly, there's a way to copy the {\sl reverse\/} of a path. This procedure
7056 returns a pointer to the first node of the copy, if the path is a cycle,
7057 but to the final node of a non-cyclic copy. The global
7058 variable |path_tail| will point to the final node of the original path;
7059 this trick makes it easier to implement `\&{doublepath}'.
7060
7061 All node types are assumed to be |endpoint| or |explicit| only.
7062
7063 @c 
7064 pointer mp_htap_ypoc (MP mp,pointer p) {
7065   pointer q,pp,qq,rr; /* for list manipulation */
7066   q=mp_get_node(mp, knot_node_size); /* this will correspond to |p| */
7067   qq=q; pp=p;
7068   while (1) { 
7069     right_type(qq)=left_type(pp); left_type(qq)=right_type(pp);
7070     x_coord(qq)=x_coord(pp); y_coord(qq)=y_coord(pp);
7071     right_x(qq)=left_x(pp); right_y(qq)=left_y(pp);
7072     left_x(qq)=right_x(pp); left_y(qq)=right_y(pp);
7073     originator(qq)=originator(pp);
7074     if ( link(pp)==p ) { 
7075       link(q)=qq; mp->path_tail=pp; return q;
7076     }
7077     rr=mp_get_node(mp, knot_node_size); link(rr)=qq; qq=rr; pp=link(pp);
7078   }
7079 }
7080
7081 @ @<Glob...@>=
7082 pointer path_tail; /* the node that links to the beginning of a path */
7083
7084 @ When a cyclic list of knot nodes is no longer needed, it can be recycled by
7085 calling the following subroutine.
7086
7087 @<Declare the recycling subroutines@>=
7088 void mp_toss_knot_list (MP mp,pointer p) ;
7089
7090 @ @c
7091 void mp_toss_knot_list (MP mp,pointer p) {
7092   pointer q; /* the node being freed */
7093   pointer r; /* the next node */
7094   q=p;
7095   do {  
7096     r=link(q); 
7097     mp_free_node(mp, q,knot_node_size); q=r;
7098   } while (q!=p);
7099 }
7100
7101 @* \[18] Choosing control points.
7102 Now we must actually delve into one of \MP's more difficult routines,
7103 the |make_choices| procedure that chooses angles and control points for
7104 the splines of a curve when the user has not specified them explicitly.
7105 The parameter to |make_choices| points to a list of knots and
7106 path information, as described above.
7107
7108 A path decomposes into independent segments at ``breakpoint'' knots,
7109 which are knots whose left and right angles are both prespecified in
7110 some way (i.e., their |left_type| and |right_type| aren't both open).
7111
7112 @c 
7113 @<Declare the procedure called |solve_choices|@>;
7114 void mp_make_choices (MP mp,pointer knots) {
7115   pointer h; /* the first breakpoint */
7116   pointer p,q; /* consecutive breakpoints being processed */
7117   @<Other local variables for |make_choices|@>;
7118   check_arith; /* make sure that |arith_error=false| */
7119   if ( mp->internal[mp_tracing_choices]>0 )
7120     mp_print_path(mp, knots,", before choices",true);
7121   @<If consecutive knots are equal, join them explicitly@>;
7122   @<Find the first breakpoint, |h|, on the path;
7123     insert an artificial breakpoint if the path is an unbroken cycle@>;
7124   p=h;
7125   do {  
7126     @<Fill in the control points between |p| and the next breakpoint,
7127       then advance |p| to that breakpoint@>;
7128   } while (p!=h);
7129   if ( mp->internal[mp_tracing_choices]>0 )
7130     mp_print_path(mp, knots,", after choices",true);
7131   if ( mp->arith_error ) {
7132     @<Report an unexpected problem during the choice-making@>;
7133   }
7134 }
7135
7136 @ @<Report an unexpected problem during the choice...@>=
7137
7138   print_err("Some number got too big");
7139 @.Some number got too big@>
7140   help2("The path that I just computed is out of range.")
7141        ("So it will probably look funny. Proceed, for a laugh.");
7142   mp_put_get_error(mp); mp->arith_error=false;
7143 }
7144
7145 @ Two knots in a row with the same coordinates will always be joined
7146 by an explicit ``curve'' whose control points are identical with the
7147 knots.
7148
7149 @<If consecutive knots are equal, join them explicitly@>=
7150 p=knots;
7151 do {  
7152   q=link(p);
7153   if ( x_coord(p)==x_coord(q) && y_coord(p)==y_coord(q) && right_type(p)>mp_explicit ) { 
7154     right_type(p)=mp_explicit;
7155     if ( left_type(p)==mp_open ) { 
7156       left_type(p)=mp_curl; left_curl(p)=unity;
7157     }
7158     left_type(q)=mp_explicit;
7159     if ( right_type(q)==mp_open ) { 
7160       right_type(q)=mp_curl; right_curl(q)=unity;
7161     }
7162     right_x(p)=x_coord(p); left_x(q)=x_coord(p);
7163     right_y(p)=y_coord(p); left_y(q)=y_coord(p);
7164   }
7165   p=q;
7166 } while (p!=knots)
7167
7168 @ If there are no breakpoints, it is necessary to compute the direction
7169 angles around an entire cycle. In this case the |left_type| of the first
7170 node is temporarily changed to |end_cycle|.
7171
7172 @<Find the first breakpoint, |h|, on the path...@>=
7173 h=knots;
7174 while (1) { 
7175   if ( left_type(h)!=mp_open ) break;
7176   if ( right_type(h)!=mp_open ) break;
7177   h=link(h);
7178   if ( h==knots ) { 
7179     left_type(h)=mp_end_cycle; break;
7180   }
7181 }
7182
7183 @ If |right_type(p)<given| and |q=link(p)|, we must have
7184 |right_type(p)=left_type(q)=mp_explicit| or |endpoint|.
7185
7186 @<Fill in the control points between |p| and the next breakpoint...@>=
7187 q=link(p);
7188 if ( right_type(p)>=mp_given ) { 
7189   while ( (left_type(q)==mp_open)&&(right_type(q)==mp_open) ) q=link(q);
7190   @<Fill in the control information between
7191     consecutive breakpoints |p| and |q|@>;
7192 } else if ( right_type(p)==mp_endpoint ) {
7193   @<Give reasonable values for the unused control points between |p| and~|q|@>;
7194 }
7195 p=q
7196
7197 @ This step makes it possible to transform an explicitly computed path without
7198 checking the |left_type| and |right_type| fields.
7199
7200 @<Give reasonable values for the unused control points between |p| and~|q|@>=
7201
7202   right_x(p)=x_coord(p); right_y(p)=y_coord(p);
7203   left_x(q)=x_coord(q); left_y(q)=y_coord(q);
7204 }
7205
7206 @ Before we can go further into the way choices are made, we need to
7207 consider the underlying theory. The basic ideas implemented in |make_choices|
7208 are due to John Hobby, who introduced the notion of ``mock curvature''
7209 @^Hobby, John Douglas@>
7210 at a knot. Angles are chosen so that they preserve mock curvature when
7211 a knot is passed, and this has been found to produce excellent results.
7212
7213 It is convenient to introduce some notations that simplify the necessary
7214 formulas. Let $d_{k,k+1}=\vert z\k-z_k\vert$ be the (nonzero) distance
7215 between knots |k| and |k+1|; and let
7216 $${z\k-z_k\over z_k-z_{k-1}}={d_{k,k+1}\over d_{k-1,k}}e^{i\psi_k}$$
7217 so that a polygonal line from $z_{k-1}$ to $z_k$ to $z\k$ turns left
7218 through an angle of~$\psi_k$. We assume that $\vert\psi_k\vert\L180^\circ$.
7219 The control points for the spline from $z_k$ to $z\k$ will be denoted by
7220 $$\eqalign{z_k^+&=z_k+
7221   \textstyle{1\over3}\rho_k e^{i\theta_k}(z\k-z_k),\cr
7222  z\k^-&=z\k-
7223   \textstyle{1\over3}\sigma\k e^{-i\phi\k}(z\k-z_k),\cr}$$
7224 where $\rho_k$ and $\sigma\k$ are nonnegative ``velocity ratios'' at the
7225 beginning and end of the curve, while $\theta_k$ and $\phi\k$ are the
7226 corresponding ``offset angles.'' These angles satisfy the condition
7227 $$\theta_k+\phi_k+\psi_k=0,\eqno(*)$$
7228 whenever the curve leaves an intermediate knot~|k| in the direction that
7229 it enters.
7230
7231 @ Let $\alpha_k$ and $\beta\k$ be the reciprocals of the ``tension'' of
7232 the curve at its beginning and ending points. This means that
7233 $\rho_k=\alpha_k f(\theta_k,\phi\k)$ and $\sigma\k=\beta\k f(\phi\k,\theta_k)$,
7234 where $f(\theta,\phi)$ is \MP's standard velocity function defined in
7235 the |velocity| subroutine. The cubic spline $B(z_k^{\phantom+},z_k^+,
7236 z\k^-,z\k^{\phantom+};t)$
7237 has curvature
7238 @^curvature@>
7239 $${2\sigma\k\sin(\theta_k+\phi\k)-6\sin\theta_k\over\rho_k^2d_{k,k+1}}
7240 \qquad{\rm and}\qquad
7241 {2\rho_k\sin(\theta_k+\phi\k)-6\sin\phi\k\over\sigma\k^2d_{k,k+1}}$$
7242 at |t=0| and |t=1|, respectively. The mock curvature is the linear
7243 @^mock curvature@>
7244 approximation to this true curvature that arises in the limit for
7245 small $\theta_k$ and~$\phi\k$, if second-order terms are discarded.
7246 The standard velocity function satisfies
7247 $$f(\theta,\phi)=1+O(\theta^2+\theta\phi+\phi^2);$$
7248 hence the mock curvatures are respectively
7249 $${2\beta\k(\theta_k+\phi\k)-6\theta_k\over\alpha_k^2d_{k,k+1}}
7250 \qquad{\rm and}\qquad
7251 {2\alpha_k(\theta_k+\phi\k)-6\phi\k\over\beta\k^2d_{k,k+1}}.\eqno(**)$$
7252
7253 @ The turning angles $\psi_k$ are given, and equation $(*)$ above
7254 determines $\phi_k$ when $\theta_k$ is known, so the task of
7255 angle selection is essentially to choose appropriate values for each
7256 $\theta_k$. When equation~$(*)$ is used to eliminate $\phi$~variables
7257 from $(**)$, we obtain a system of linear equations of the form
7258 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7259 where
7260 $$A_k={\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7261 \qquad B_k={3-\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7262 \qquad C_k={3-\beta\k\over\alpha_k^2d_{k,k+1}},
7263 \qquad D_k={\beta\k\over\alpha_k^2d_{k,k+1}}.$$
7264 The tensions are always $3\over4$ or more, hence each $\alpha$ and~$\beta$
7265 will be at most $4\over3$. It follows that $B_k\G{5\over4}A_k$ and
7266 $C_k\G{5\over4}D_k$; hence the equations are diagonally dominant;
7267 hence they have a unique solution. Moreover, in most cases the tensions
7268 are equal to~1, so that $B_k=2A_k$ and $C_k=2D_k$. This makes the
7269 solution numerically stable, and there is an exponential damping
7270 effect: The data at knot $k\pm j$ affects the angle at knot~$k$ by
7271 a factor of~$O(2^{-j})$.
7272
7273 @ However, we still must consider the angles at the starting and ending
7274 knots of a non-cyclic path. These angles might be given explicitly, or
7275 they might be specified implicitly in terms of an amount of ``curl.''
7276
7277 Let's assume that angles need to be determined for a non-cyclic path
7278 starting at $z_0$ and ending at~$z_n$. Then equations of the form
7279 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta_{k+1}=R_k$$
7280 have been given for $0<k<n$, and it will be convenient to introduce
7281 equations of the same form for $k=0$ and $k=n$, where
7282 $$A_0=B_0=C_n=D_n=0.$$
7283 If $\theta_0$ is supposed to have a given value $E_0$, we simply
7284 define $C_0=0$, $D_0=0$, and $R_0=E_0$. Otherwise a curl
7285 parameter, $\gamma_0$, has been specified at~$z_0$; this means
7286 that the mock curvature at $z_0$ should be $\gamma_0$ times the
7287 mock curvature at $z_1$; i.e.,
7288 $${2\beta_1(\theta_0+\phi_1)-6\theta_0\over\alpha_0^2d_{01}}
7289 =\gamma_0{2\alpha_0(\theta_0+\phi_1)-6\phi_1\over\beta_1^2d_{01}}.$$
7290 This equation simplifies to
7291 $$(\alpha_0\chi_0+3-\beta_1)\theta_0+
7292  \bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\theta_1=
7293  -\bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\psi_1,$$
7294 where $\chi_0=\alpha_0^2\gamma_0/\beta_1^2$; so we can set $C_0=
7295 \chi_0\alpha_0+3-\beta_1$, $D_0=(3-\alpha_0)\chi_0+\beta_1$, $R_0=-D_0\psi_1$.
7296 It can be shown that $C_0>0$ and $C_0B_1-A_1D_0>0$ when $\gamma_0\G0$,
7297 hence the linear equations remain nonsingular.
7298
7299 Similar considerations apply at the right end, when the final angle $\phi_n$
7300 may or may not need to be determined. It is convenient to let $\psi_n=0$,
7301 hence $\theta_n=-\phi_n$. We either have an explicit equation $\theta_n=E_n$,
7302 or we have
7303 $$\bigl((3-\beta_n)\chi_n+\alpha_{n-1}\bigr)\theta_{n-1}+
7304 (\beta_n\chi_n+3-\alpha_{n-1})\theta_n=0,\qquad
7305   \chi_n={\beta_n^2\gamma_n\over\alpha_{n-1}^2}.$$
7306
7307 When |make_choices| chooses angles, it must compute the coefficients of
7308 these linear equations, then solve the equations. To compute the coefficients,
7309 it is necessary to compute arctangents of the given turning angles~$\psi_k$.
7310 When the equations are solved, the chosen directions $\theta_k$ are put
7311 back into the form of control points by essentially computing sines and
7312 cosines.
7313
7314 @ OK, we are ready to make the hard choices of |make_choices|.
7315 Most of the work is relegated to an auxiliary procedure
7316 called |solve_choices|, which has been introduced to keep
7317 |make_choices| from being extremely long.
7318
7319 @<Fill in the control information between...@>=
7320 @<Calculate the turning angles $\psi_k$ and the distances $d_{k,k+1}$;
7321   set $n$ to the length of the path@>;
7322 @<Remove |open| types at the breakpoints@>;
7323 mp_solve_choices(mp, p,q,n)
7324
7325 @ It's convenient to precompute quantities that will be needed several
7326 times later. The values of |delta_x[k]| and |delta_y[k]| will be the
7327 coordinates of $z\k-z_k$, and the magnitude of this vector will be
7328 |delta[k]=@t$d_{k,k+1}$@>|. The path angle $\psi_k$ between $z_k-z_{k-1}$
7329 and $z\k-z_k$ will be stored in |psi[k]|.
7330
7331 @<Glob...@>=
7332 int path_size; /* maximum number of knots between breakpoints of a path */
7333 scaled *delta_x;
7334 scaled *delta_y;
7335 scaled *delta; /* knot differences */
7336 angle  *psi; /* turning angles */
7337
7338 @ @<Allocate or initialize ...@>=
7339 mp->delta_x = NULL;
7340 mp->delta_y = NULL;
7341 mp->delta = NULL;
7342 mp->psi = NULL;
7343
7344 @ @<Dealloc variables@>=
7345 xfree(mp->delta_x);
7346 xfree(mp->delta_y);
7347 xfree(mp->delta);
7348 xfree(mp->psi);
7349
7350 @ @<Other local variables for |make_choices|@>=
7351   int k,n; /* current and final knot numbers */
7352   pointer s,t; /* registers for list traversal */
7353   scaled delx,dely; /* directions where |open| meets |explicit| */
7354   fraction sine,cosine; /* trig functions of various angles */
7355
7356 @ @<Calculate the turning angles...@>=
7357 {
7358 RESTART:
7359   k=0; s=p; n=mp->path_size;
7360   do {  
7361     t=link(s);
7362     mp->delta_x[k]=x_coord(t)-x_coord(s);
7363     mp->delta_y[k]=y_coord(t)-y_coord(s);
7364     mp->delta[k]=mp_pyth_add(mp, mp->delta_x[k],mp->delta_y[k]);
7365     if ( k>0 ) { 
7366       sine=mp_make_fraction(mp, mp->delta_y[k-1],mp->delta[k-1]);
7367       cosine=mp_make_fraction(mp, mp->delta_x[k-1],mp->delta[k-1]);
7368       mp->psi[k]=mp_n_arg(mp, mp_take_fraction(mp, mp->delta_x[k],cosine)+
7369         mp_take_fraction(mp, mp->delta_y[k],sine),
7370         mp_take_fraction(mp, mp->delta_y[k],cosine)-
7371           mp_take_fraction(mp, mp->delta_x[k],sine));
7372     }
7373     incr(k); s=t;
7374     if ( k==mp->path_size ) {
7375       mp_reallocate_paths(mp, mp->path_size+(mp->path_size>>2));
7376       goto RESTART; /* retry, loop size has changed */
7377     }
7378     if ( s==q ) n=k;
7379   } while (!((k>=n)&&(left_type(s)!=mp_end_cycle)));
7380   if ( k==n ) mp->psi[n]=0; else mp->psi[k]=mp->psi[1];
7381 }
7382
7383 @ When we get to this point of the code, |right_type(p)| is either
7384 |given| or |curl| or |open|. If it is |open|, we must have
7385 |left_type(p)=mp_end_cycle| or |left_type(p)=mp_explicit|. In the latter
7386 case, the |open| type is converted to |given|; however, if the
7387 velocity coming into this knot is zero, the |open| type is
7388 converted to a |curl|, since we don't know the incoming direction.
7389
7390 Similarly, |left_type(q)| is either |given| or |curl| or |open| or
7391 |mp_end_cycle|. The |open| possibility is reduced either to |given| or to |curl|.
7392
7393 @<Remove |open| types at the breakpoints@>=
7394 if ( left_type(q)==mp_open ) { 
7395   delx=right_x(q)-x_coord(q); dely=right_y(q)-y_coord(q);
7396   if ( (delx==0)&&(dely==0) ) { 
7397     left_type(q)=mp_curl; left_curl(q)=unity;
7398   } else { 
7399     left_type(q)=mp_given; left_given(q)=mp_n_arg(mp, delx,dely);
7400   }
7401 }
7402 if ( (right_type(p)==mp_open)&&(left_type(p)==mp_explicit) ) { 
7403   delx=x_coord(p)-left_x(p); dely=y_coord(p)-left_y(p);
7404   if ( (delx==0)&&(dely==0) ) { 
7405     right_type(p)=mp_curl; right_curl(p)=unity;
7406   } else { 
7407     right_type(p)=mp_given; right_given(p)=mp_n_arg(mp, delx,dely);
7408   }
7409 }
7410
7411 @ Linear equations need to be solved whenever |n>1|; and also when |n=1|
7412 and exactly one of the breakpoints involves a curl. The simplest case occurs
7413 when |n=1| and there is a curl at both breakpoints; then we simply draw
7414 a straight line.
7415
7416 But before coding up the simple cases, we might as well face the general case,
7417 since we must deal with it sooner or later, and since the general case
7418 is likely to give some insight into the way simple cases can be handled best.
7419
7420 When there is no cycle, the linear equations to be solved form a tridiagonal
7421 system, and we can apply the standard technique of Gaussian elimination
7422 to convert that system to a sequence of equations of the form
7423 $$\theta_0+u_0\theta_1=v_0,\quad
7424 \theta_1+u_1\theta_2=v_1,\quad\ldots,\quad
7425 \theta_{n-1}+u_{n-1}\theta_n=v_{n-1},\quad
7426 \theta_n=v_n.$$
7427 It is possible to do this diagonalization while generating the equations.
7428 Once $\theta_n$ is known, it is easy to determine $\theta_{n-1}$, \dots,
7429 $\theta_1$, $\theta_0$; thus, the equations will be solved.
7430
7431 The procedure is slightly more complex when there is a cycle, but the
7432 basic idea will be nearly the same. In the cyclic case the right-hand
7433 sides will be $v_k+w_k\theta_0$ instead of simply $v_k$, and we will start
7434 the process off with $u_0=v_0=0$, $w_0=1$. The final equation will be not
7435 $\theta_n=v_n$ but $\theta_n+u_n\theta_1=v_n+w_n\theta_0$; an appropriate
7436 ending routine will take account of the fact that $\theta_n=\theta_0$ and
7437 eliminate the $w$'s from the system, after which the solution can be
7438 obtained as before.
7439
7440 When $u_k$, $v_k$, and $w_k$ are being computed, the three pointer
7441 variables |r|, |s|,~|t| will point respectively to knots |k-1|, |k|,
7442 and~|k+1|. The $u$'s and $w$'s are scaled by $2^{28}$, i.e., they are
7443 of type |fraction|; the $\theta$'s and $v$'s are of type |angle|.
7444
7445 @<Glob...@>=
7446 angle *theta; /* values of $\theta_k$ */
7447 fraction *uu; /* values of $u_k$ */
7448 angle *vv; /* values of $v_k$ */
7449 fraction *ww; /* values of $w_k$ */
7450
7451 @ @<Allocate or initialize ...@>=
7452 mp->theta = NULL;
7453 mp->uu = NULL;
7454 mp->vv = NULL;
7455 mp->ww = NULL;
7456
7457 @ @<Dealloc variables@>=
7458 xfree(mp->theta);
7459 xfree(mp->uu);
7460 xfree(mp->vv);
7461 xfree(mp->ww);
7462
7463 @ @<Declare |mp_reallocate| functions@>=
7464 void mp_reallocate_paths (MP mp, int l);
7465
7466 @ @c
7467 void mp_reallocate_paths (MP mp, int l) {
7468   XREALLOC (mp->delta_x, l, scaled);
7469   XREALLOC (mp->delta_y, l, scaled);
7470   XREALLOC (mp->delta,   l, scaled);
7471   XREALLOC (mp->psi,     l, angle);
7472   XREALLOC (mp->theta,   l, angle);
7473   XREALLOC (mp->uu,      l, fraction);
7474   XREALLOC (mp->vv,      l, angle);
7475   XREALLOC (mp->ww,      l, fraction);
7476   mp->path_size = l;
7477 }
7478
7479 @ Our immediate problem is to get the ball rolling by setting up the
7480 first equation or by realizing that no equations are needed, and to fit
7481 this initialization into a framework suitable for the overall computation.
7482
7483 @<Declare the procedure called |solve_choices|@>=
7484 @<Declare subroutines needed by |solve_choices|@>;
7485 void mp_solve_choices (MP mp,pointer p, pointer q, halfword n) {
7486   int k; /* current knot number */
7487   pointer r,s,t; /* registers for list traversal */
7488   @<Other local variables for |solve_choices|@>;
7489   k=0; s=p; r=0;
7490   while (1) { 
7491     t=link(s);
7492     if ( k==0 ) {
7493       @<Get the linear equations started; or |return|
7494         with the control points in place, if linear equations
7495         needn't be solved@>
7496     } else  { 
7497       switch (left_type(s)) {
7498       case mp_end_cycle: case mp_open:
7499         @<Set up equation to match mock curvatures
7500           at $z_k$; then |goto found| with $\theta_n$
7501           adjusted to equal $\theta_0$, if a cycle has ended@>;
7502         break;
7503       case mp_curl:
7504         @<Set up equation for a curl at $\theta_n$
7505           and |goto found|@>;
7506         break;
7507       case mp_given:
7508         @<Calculate the given value of $\theta_n$
7509           and |goto found|@>;
7510         break;
7511       } /* there are no other cases */
7512     }
7513     r=s; s=t; incr(k);
7514   }
7515 FOUND:
7516   @<Finish choosing angles and assigning control points@>;
7517 }
7518
7519 @ On the first time through the loop, we have |k=0| and |r| is not yet
7520 defined. The first linear equation, if any, will have $A_0=B_0=0$.
7521
7522 @<Get the linear equations started...@>=
7523 switch (right_type(s)) {
7524 case mp_given: 
7525   if ( left_type(t)==mp_given ) {
7526     @<Reduce to simple case of two givens  and |return|@>
7527   } else {
7528     @<Set up the equation for a given value of $\theta_0$@>;
7529   }
7530   break;
7531 case mp_curl: 
7532   if ( left_type(t)==mp_curl ) {
7533     @<Reduce to simple case of straight line and |return|@>
7534   } else {
7535     @<Set up the equation for a curl at $\theta_0$@>;
7536   }
7537   break;
7538 case mp_open: 
7539   mp->uu[0]=0; mp->vv[0]=0; mp->ww[0]=fraction_one;
7540   /* this begins a cycle */
7541   break;
7542 } /* there are no other cases */
7543
7544 @ The general equation that specifies equality of mock curvature at $z_k$ is
7545 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7546 as derived above. We want to combine this with the already-derived equation
7547 $\theta_{k-1}+u_{k-1}\theta_k=v_{k-1}+w_{k-1}\theta_0$ in order to obtain
7548 a new equation
7549 $\theta_k+u_k\theta\k=v_k+w_k\theta_0$. This can be done by dividing the
7550 equation
7551 $$(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}
7552     -A_kw_{k-1}\theta_0$$
7553 by $B_k-u_{k-1}A_k+C_k$. The trick is to do this carefully with
7554 fixed-point arithmetic, avoiding the chance of overflow while retaining
7555 suitable precision.
7556
7557 The calculations will be performed in several registers that
7558 provide temporary storage for intermediate quantities.
7559
7560 @<Other local variables for |solve_choices|@>=
7561 fraction aa,bb,cc,ff,acc; /* temporary registers */
7562 scaled dd,ee; /* likewise, but |scaled| */
7563 scaled lt,rt; /* tension values */
7564
7565 @ @<Set up equation to match mock curvatures...@>=
7566 { @<Calculate the values $\\{aa}=A_k/B_k$, $\\{bb}=D_k/C_k$,
7567     $\\{dd}=(3-\alpha_{k-1})d_{k,k+1}$, $\\{ee}=(3-\beta\k)d_{k-1,k}$,
7568     and $\\{cc}=(B_k-u_{k-1}A_k)/B_k$@>;
7569   @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>;
7570   mp->uu[k]=mp_take_fraction(mp, ff,bb);
7571   @<Calculate the values of $v_k$ and $w_k$@>;
7572   if ( left_type(s)==mp_end_cycle ) {
7573     @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>;
7574   }
7575 }
7576
7577 @ Since tension values are never less than 3/4, the values |aa| and
7578 |bb| computed here are never more than 4/5.
7579
7580 @<Calculate the values $\\{aa}=...@>=
7581 if ( abs(right_tension(r))==unity) { 
7582   aa=fraction_half; dd=2*mp->delta[k];
7583 } else { 
7584   aa=mp_make_fraction(mp, unity,3*abs(right_tension(r))-unity);
7585   dd=mp_take_fraction(mp, mp->delta[k],
7586     fraction_three-mp_make_fraction(mp, unity,abs(right_tension(r))));
7587 }
7588 if ( abs(left_tension(t))==unity ){ 
7589   bb=fraction_half; ee=2*mp->delta[k-1];
7590 } else { 
7591   bb=mp_make_fraction(mp, unity,3*abs(left_tension(t))-unity);
7592   ee=mp_take_fraction(mp, mp->delta[k-1],
7593     fraction_three-mp_make_fraction(mp, unity,abs(left_tension(t))));
7594 }
7595 cc=fraction_one-mp_take_fraction(mp, mp->uu[k-1],aa)
7596
7597 @ The ratio to be calculated in this step can be written in the form
7598 $$\beta_k^2\cdot\\{ee}\over\beta_k^2\cdot\\{ee}+\alpha_k^2\cdot
7599   \\{cc}\cdot\\{dd},$$
7600 because of the quantities just calculated. The values of |dd| and |ee|
7601 will not be needed after this step has been performed.
7602
7603 @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>=
7604 dd=mp_take_fraction(mp, dd,cc); lt=abs(left_tension(s)); rt=abs(right_tension(s));
7605 if ( lt!=rt ) { /* $\beta_k^{-1}\ne\alpha_k^{-1}$ */
7606   if ( lt<rt ) { 
7607     ff=mp_make_fraction(mp, lt,rt);
7608     ff=mp_take_fraction(mp, ff,ff); /* $\alpha_k^2/\beta_k^2$ */
7609     dd=mp_take_fraction(mp, dd,ff);
7610   } else { 
7611     ff=mp_make_fraction(mp, rt,lt);
7612     ff=mp_take_fraction(mp, ff,ff); /* $\beta_k^2/\alpha_k^2$ */
7613     ee=mp_take_fraction(mp, ee,ff);
7614   }
7615 }
7616 ff=mp_make_fraction(mp, ee,ee+dd)
7617
7618 @ The value of $u_{k-1}$ will be |<=1| except when $k=1$ and the previous
7619 equation was specified by a curl. In that case we must use a special
7620 method of computation to prevent overflow.
7621
7622 Fortunately, the calculations turn out to be even simpler in this ``hard''
7623 case. The curl equation makes $w_0=0$ and $v_0=-u_0\psi_1$, hence
7624 $-B_1\psi_1-A_1v_0=-(B_1-u_0A_1)\psi_1=-\\{cc}\cdot B_1\psi_1$.
7625
7626 @<Calculate the values of $v_k$ and $w_k$@>=
7627 acc=-mp_take_fraction(mp, mp->psi[k+1],mp->uu[k]);
7628 if ( right_type(r)==mp_curl ) { 
7629   mp->ww[k]=0;
7630   mp->vv[k]=acc-mp_take_fraction(mp, mp->psi[1],fraction_one-ff);
7631 } else { 
7632   ff=mp_make_fraction(mp, fraction_one-ff,cc); /* this is
7633     $B_k/(C_k+B_k-u_{k-1}A_k)<5$ */
7634   acc=acc-mp_take_fraction(mp, mp->psi[k],ff);
7635   ff=mp_take_fraction(mp, ff,aa); /* this is $A_k/(C_k+B_k-u_{k-1}A_k)$ */
7636   mp->vv[k]=acc-mp_take_fraction(mp, mp->vv[k-1],ff);
7637   if ( mp->ww[k-1]==0 ) mp->ww[k]=0;
7638   else mp->ww[k]=-mp_take_fraction(mp, mp->ww[k-1],ff);
7639 }
7640
7641 @ When a complete cycle has been traversed, we have $\theta_k+u_k\theta\k=
7642 v_k+w_k\theta_0$, for |1<=k<=n|. We would like to determine the value of
7643 $\theta_n$ and reduce the system to the form $\theta_k+u_k\theta\k=v_k$
7644 for |0<=k<n|, so that the cyclic case can be finished up just as if there
7645 were no cycle.
7646
7647 The idea in the following code is to observe that
7648 $$\eqalign{\theta_n&=v_n+w_n\theta_0-u_n\theta_1=\cdots\cr
7649 &=v_n+w_n\theta_0-u_n\bigl(v_1+w_1\theta_0-u_1(v_2+\cdots
7650   -u_{n-2}(v_{n-1}+w_{n-1}\theta_0-u_{n-1}\theta_0))\bigr),\cr}$$
7651 so we can solve for $\theta_n=\theta_0$.
7652
7653 @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>=
7654
7655 aa=0; bb=fraction_one; /* we have |k=n| */
7656 do {  decr(k);
7657 if ( k==0 ) k=n;
7658   aa=mp->vv[k]-mp_take_fraction(mp, aa,mp->uu[k]);
7659   bb=mp->ww[k]-mp_take_fraction(mp, bb,mp->uu[k]);
7660 } while (k!=n); /* now $\theta_n=\\{aa}+\\{bb}\cdot\theta_n$ */
7661 aa=mp_make_fraction(mp, aa,fraction_one-bb);
7662 mp->theta[n]=aa; mp->vv[0]=aa;
7663 for (k=1;k<=n-1;k++) {
7664   mp->vv[k]=mp->vv[k]+mp_take_fraction(mp, aa,mp->ww[k]);
7665 }
7666 goto FOUND;
7667 }
7668
7669 @ @d reduce_angle(A) if ( abs((A))>one_eighty_deg ) {
7670   if ( (A)>0 ) (A)=(A)-three_sixty_deg; else (A)=(A)+three_sixty_deg; }
7671
7672 @<Calculate the given value of $\theta_n$...@>=
7673
7674   mp->theta[n]=left_given(s)-mp_n_arg(mp, mp->delta_x[n-1],mp->delta_y[n-1]);
7675   reduce_angle(mp->theta[n]);
7676   goto FOUND;
7677 }
7678
7679 @ @<Set up the equation for a given value of $\theta_0$@>=
7680
7681   mp->vv[0]=right_given(s)-mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7682   reduce_angle(mp->vv[0]);
7683   mp->uu[0]=0; mp->ww[0]=0;
7684 }
7685
7686 @ @<Set up the equation for a curl at $\theta_0$@>=
7687 { cc=right_curl(s); lt=abs(left_tension(t)); rt=abs(right_tension(s));
7688   if ( (rt==unity)&&(lt==unity) )
7689     mp->uu[0]=mp_make_fraction(mp, cc+cc+unity,cc+two);
7690   else 
7691     mp->uu[0]=mp_curl_ratio(mp, cc,rt,lt);
7692   mp->vv[0]=-mp_take_fraction(mp, mp->psi[1],mp->uu[0]); mp->ww[0]=0;
7693 }
7694
7695 @ @<Set up equation for a curl at $\theta_n$...@>=
7696 { cc=left_curl(s); lt=abs(left_tension(s)); rt=abs(right_tension(r));
7697   if ( (rt==unity)&&(lt==unity) )
7698     ff=mp_make_fraction(mp, cc+cc+unity,cc+two);
7699   else 
7700     ff=mp_curl_ratio(mp, cc,lt,rt);
7701   mp->theta[n]=-mp_make_fraction(mp, mp_take_fraction(mp, mp->vv[n-1],ff),
7702     fraction_one-mp_take_fraction(mp, ff,mp->uu[n-1]));
7703   goto FOUND;
7704 }
7705
7706 @ The |curl_ratio| subroutine has three arguments, which our previous notation
7707 encourages us to call $\gamma$, $\alpha^{-1}$, and $\beta^{-1}$. It is
7708 a somewhat tedious program to calculate
7709 $${(3-\alpha)\alpha^2\gamma+\beta^3\over
7710   \alpha^3\gamma+(3-\beta)\beta^2},$$
7711 with the result reduced to 4 if it exceeds 4. (This reduction of curl
7712 is necessary only if the curl and tension are both large.)
7713 The values of $\alpha$ and $\beta$ will be at most~4/3.
7714
7715 @<Declare subroutines needed by |solve_choices|@>=
7716 fraction mp_curl_ratio (MP mp,scaled gamma, scaled a_tension, 
7717                         scaled b_tension) {
7718   fraction alpha,beta,num,denom,ff; /* registers */
7719   alpha=mp_make_fraction(mp, unity,a_tension);
7720   beta=mp_make_fraction(mp, unity,b_tension);
7721   if ( alpha<=beta ) {
7722     ff=mp_make_fraction(mp, alpha,beta); ff=mp_take_fraction(mp, ff,ff);
7723     gamma=mp_take_fraction(mp, gamma,ff);
7724     beta=beta / 010000; /* convert |fraction| to |scaled| */
7725     denom=mp_take_fraction(mp, gamma,alpha)+three-beta;
7726     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7727   } else { 
7728     ff=mp_make_fraction(mp, beta,alpha); ff=mp_take_fraction(mp, ff,ff);
7729     beta=mp_take_fraction(mp, beta,ff) / 010000; /* convert |fraction| to |scaled| */
7730     denom=mp_take_fraction(mp, gamma,alpha)+(ff / 1365)-beta;
7731       /* $1365\approx 2^{12}/3$ */
7732     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7733   }
7734   if ( num>=denom+denom+denom+denom ) return fraction_four;
7735   else return mp_make_fraction(mp, num,denom);
7736 }
7737
7738 @ We're in the home stretch now.
7739
7740 @<Finish choosing angles and assigning control points@>=
7741 for (k=n-1;k>=0;k--) {
7742   mp->theta[k]=mp->vv[k]-mp_take_fraction(mp,mp->theta[k+1],mp->uu[k]);
7743 }
7744 s=p; k=0;
7745 do {  
7746   t=link(s);
7747   mp_n_sin_cos(mp, mp->theta[k]); mp->st=mp->n_sin; mp->ct=mp->n_cos;
7748   mp_n_sin_cos(mp, -mp->psi[k+1]-mp->theta[k+1]); mp->sf=mp->n_sin; mp->cf=mp->n_cos;
7749   mp_set_controls(mp, s,t,k);
7750   incr(k); s=t;
7751 } while (k!=n)
7752
7753 @ The |set_controls| routine actually puts the control points into
7754 a pair of consecutive nodes |p| and~|q|. Global variables are used to
7755 record the values of $\sin\theta$, $\cos\theta$, $\sin\phi$, and
7756 $\cos\phi$ needed in this calculation.
7757
7758 @<Glob...@>=
7759 fraction st;
7760 fraction ct;
7761 fraction sf;
7762 fraction cf; /* sines and cosines */
7763
7764 @ @<Declare subroutines needed by |solve_choices|@>=
7765 void mp_set_controls (MP mp,pointer p, pointer q, integer k) {
7766   fraction rr,ss; /* velocities, divided by thrice the tension */
7767   scaled lt,rt; /* tensions */
7768   fraction sine; /* $\sin(\theta+\phi)$ */
7769   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7770   rr=mp_velocity(mp, mp->st,mp->ct,mp->sf,mp->cf,rt);
7771   ss=mp_velocity(mp, mp->sf,mp->cf,mp->st,mp->ct,lt);
7772   if ( (right_tension(p)<0)||(left_tension(q)<0) ) {
7773     @<Decrease the velocities,
7774       if necessary, to stay inside the bounding triangle@>;
7775   }
7776   right_x(p)=x_coord(p)+mp_take_fraction(mp, 
7777                           mp_take_fraction(mp, mp->delta_x[k],mp->ct)-
7778                           mp_take_fraction(mp, mp->delta_y[k],mp->st),rr);
7779   right_y(p)=y_coord(p)+mp_take_fraction(mp, 
7780                           mp_take_fraction(mp, mp->delta_y[k],mp->ct)+
7781                           mp_take_fraction(mp, mp->delta_x[k],mp->st),rr);
7782   left_x(q)=x_coord(q)-mp_take_fraction(mp, 
7783                          mp_take_fraction(mp, mp->delta_x[k],mp->cf)+
7784                          mp_take_fraction(mp, mp->delta_y[k],mp->sf),ss);
7785   left_y(q)=y_coord(q)-mp_take_fraction(mp, 
7786                          mp_take_fraction(mp, mp->delta_y[k],mp->cf)-
7787                          mp_take_fraction(mp, mp->delta_x[k],mp->sf),ss);
7788   right_type(p)=mp_explicit; left_type(q)=mp_explicit;
7789 }
7790
7791 @ The boundedness conditions $\\{rr}\L\sin\phi\,/\sin(\theta+\phi)$ and
7792 $\\{ss}\L\sin\theta\,/\sin(\theta+\phi)$ are to be enforced if $\sin\theta$,
7793 $\sin\phi$, and $\sin(\theta+\phi)$ all have the same sign. Otherwise
7794 there is no ``bounding triangle.''
7795 @:at_least_}{\&{atleast} primitive@>
7796
7797 @<Decrease the velocities, if necessary...@>=
7798 if (((mp->st>=0)&&(mp->sf>=0))||((mp->st<=0)&&(mp->sf<=0)) ) {
7799   sine=mp_take_fraction(mp, abs(mp->st),mp->cf)+
7800                             mp_take_fraction(mp, abs(mp->sf),mp->ct);
7801   if ( sine>0 ) {
7802     sine=mp_take_fraction(mp, sine,fraction_one+unity); /* safety factor */
7803     if ( right_tension(p)<0 )
7804      if ( mp_ab_vs_cd(mp, abs(mp->sf),fraction_one,rr,sine)<0 )
7805       rr=mp_make_fraction(mp, abs(mp->sf),sine);
7806     if ( left_tension(q)<0 )
7807      if ( mp_ab_vs_cd(mp, abs(mp->st),fraction_one,ss,sine)<0 )
7808       ss=mp_make_fraction(mp, abs(mp->st),sine);
7809   }
7810 }
7811
7812 @ Only the simple cases remain to be handled.
7813
7814 @<Reduce to simple case of two givens and |return|@>=
7815
7816   aa=mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7817   mp_n_sin_cos(mp, right_given(p)-aa); mp->ct=mp->n_cos; mp->st=mp->n_sin;
7818   mp_n_sin_cos(mp, left_given(q)-aa); mp->cf=mp->n_cos; mp->sf=-mp->n_sin;
7819   mp_set_controls(mp, p,q,0); return;
7820 }
7821
7822 @ @<Reduce to simple case of straight line and |return|@>=
7823
7824   right_type(p)=mp_explicit; left_type(q)=mp_explicit;
7825   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7826   if ( rt==unity ) {
7827     if ( mp->delta_x[0]>=0 ) right_x(p)=x_coord(p)+((mp->delta_x[0]+1) / 3);
7828     else right_x(p)=x_coord(p)+((mp->delta_x[0]-1) / 3);
7829     if ( mp->delta_y[0]>=0 ) right_y(p)=y_coord(p)+((mp->delta_y[0]+1) / 3);
7830     else right_y(p)=y_coord(p)+((mp->delta_y[0]-1) / 3);
7831   } else { 
7832     ff=mp_make_fraction(mp, unity,3*rt); /* $\alpha/3$ */
7833     right_x(p)=x_coord(p)+mp_take_fraction(mp, mp->delta_x[0],ff);
7834     right_y(p)=y_coord(p)+mp_take_fraction(mp, mp->delta_y[0],ff);
7835   }
7836   if ( lt==unity ) {
7837     if ( mp->delta_x[0]>=0 ) left_x(q)=x_coord(q)-((mp->delta_x[0]+1) / 3);
7838     else left_x(q)=x_coord(q)-((mp->delta_x[0]-1) / 3);
7839     if ( mp->delta_y[0]>=0 ) left_y(q)=y_coord(q)-((mp->delta_y[0]+1) / 3);
7840     else left_y(q)=y_coord(q)-((mp->delta_y[0]-1) / 3);
7841   } else  { 
7842     ff=mp_make_fraction(mp, unity,3*lt); /* $\beta/3$ */
7843     left_x(q)=x_coord(q)-mp_take_fraction(mp, mp->delta_x[0],ff);
7844     left_y(q)=y_coord(q)-mp_take_fraction(mp, mp->delta_y[0],ff);
7845   }
7846   return;
7847 }
7848
7849 @* \[19] Measuring paths.
7850 \MP's \&{llcorner}, \&{lrcorner}, \&{ulcorner}, and \&{urcorner} operators
7851 allow the user to measure the bounding box of anything that can go into a
7852 picture.  It's easy to get rough bounds on the $x$ and $y$ extent of a path
7853 by just finding the bounding box of the knots and the control points. We
7854 need a more accurate version of the bounding box, but we can still use the
7855 easy estimate to save time by focusing on the interesting parts of the path.
7856
7857 @ Computing an accurate bounding box involves a theme that will come up again
7858 and again. Given a Bernshte{\u\i}n polynomial
7859 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
7860 $$B(z_0,z_1,\ldots,z_n;t)=\sum_k{n\choose k}t^k(1-t)^{n-k}z_k,$$
7861 we can conveniently bisect its range as follows:
7862
7863 \smallskip
7864 \textindent{1)} Let $z_k^{(0)}=z_k$, for |0<=k<=n|.
7865
7866 \smallskip
7867 \textindent{2)} Let $z_k^{(j+1)}={1\over2}(z_k^{(j)}+z\k^{(j)})$, for
7868 |0<=k<n-j|, for |0<=j<n|.
7869
7870 \smallskip\noindent
7871 Then
7872 $$B(z_0,z_1,\ldots,z_n;t)=B(z_0^{(0)},z_0^{(1)},\ldots,z_0^{(n)};2t)
7873  =B(z_0^{(n)},z_1^{(n-1)},\ldots,z_n^{(0)};2t-1).$$
7874 This formula gives us the coefficients of polynomials to use over the ranges
7875 $0\L t\L{1\over2}$ and ${1\over2}\L t\L1$.
7876
7877 @ Now here's a subroutine that's handy for all sorts of path computations:
7878 Given a quadratic polynomial $B(a,b,c;t)$, the |crossing_point| function
7879 returns the unique |fraction| value |t| between 0 and~1 at which
7880 $B(a,b,c;t)$ changes from positive to negative, or returns
7881 |t=fraction_one+1| if no such value exists. If |a<0| (so that $B(a,b,c;t)$
7882 is already negative at |t=0|), |crossing_point| returns the value zero.
7883
7884 @d no_crossing {  return (fraction_one+1); }
7885 @d one_crossing { return fraction_one; }
7886 @d zero_crossing { return 0; }
7887 @d mp_crossing_point(M,A,B,C) mp_do_crossing_point(A,B,C)
7888
7889 @c fraction mp_do_crossing_point (integer a, integer b, integer c) {
7890   integer d; /* recursive counter */
7891   integer x,xx,x0,x1,x2; /* temporary registers for bisection */
7892   if ( a<0 ) zero_crossing;
7893   if ( c>=0 ) { 
7894     if ( b>=0 ) {
7895       if ( c>0 ) { no_crossing; }
7896       else if ( (a==0)&&(b==0) ) { no_crossing;} 
7897       else { one_crossing; } 
7898     }
7899     if ( a==0 ) zero_crossing;
7900   } else if ( a==0 ) {
7901     if ( b<=0 ) zero_crossing;
7902   }
7903   @<Use bisection to find the crossing point, if one exists@>;
7904 }
7905
7906 @ The general bisection method is quite simple when $n=2$, hence
7907 |crossing_point| does not take much time. At each stage in the
7908 recursion we have a subinterval defined by |l| and~|j| such that
7909 $B(a,b,c;2^{-l}(j+t))=B(x_0,x_1,x_2;t)$, and we want to ``zero in'' on
7910 the subinterval where $x_0\G0$ and $\min(x_1,x_2)<0$.
7911
7912 It is convenient for purposes of calculation to combine the values
7913 of |l| and~|j| in a single variable $d=2^l+j$, because the operation
7914 of bisection then corresponds simply to doubling $d$ and possibly
7915 adding~1. Furthermore it proves to be convenient to modify
7916 our previous conventions for bisection slightly, maintaining the
7917 variables $X_0=2^lx_0$, $X_1=2^l(x_0-x_1)$, and $X_2=2^l(x_1-x_2)$.
7918 With these variables the conditions $x_0\ge0$ and $\min(x_1,x_2)<0$ are
7919 equivalent to $\max(X_1,X_1+X_2)>X_0\ge0$.
7920
7921 The following code maintains the invariant relations
7922 $0\L|x0|<\max(|x1|,|x1|+|x2|)$,
7923 $\vert|x1|\vert<2^{30}$, $\vert|x2|\vert<2^{30}$;
7924 it has been constructed in such a way that no arithmetic overflow
7925 will occur if the inputs satisfy
7926 $a<2^{30}$, $\vert a-b\vert<2^{30}$, and $\vert b-c\vert<2^{30}$.
7927
7928 @<Use bisection to find the crossing point...@>=
7929 d=1; x0=a; x1=a-b; x2=b-c;
7930 do {  
7931   x=half(x1+x2);
7932   if ( x1-x0>x0 ) { 
7933     x2=x; x0+=x0; d+=d;  
7934   } else { 
7935     xx=x1+x-x0;
7936     if ( xx>x0 ) { 
7937       x2=x; x0+=x0; d+=d;
7938     }  else { 
7939       x0=x0-xx;
7940       if ( x<=x0 ) { if ( x+x2<=x0 ) no_crossing; }
7941       x1=x; d=d+d+1;
7942     }
7943   }
7944 } while (d<fraction_one);
7945 return (d-fraction_one)
7946
7947 @ Here is a routine that computes the $x$ or $y$ coordinate of the point on
7948 a cubic corresponding to the |fraction| value~|t|.
7949
7950 It is convenient to define a \.{WEB} macro |t_of_the_way| such that
7951 |t_of_the_way(a,b)| expands to |a-(a-b)*t|, i.e., to |t[a,b]|.
7952
7953 @d t_of_the_way(A,B) ((A)-mp_take_fraction(mp,((A)-(B)),t))
7954
7955 @c scaled mp_eval_cubic (MP mp,pointer p, pointer q, fraction t) {
7956   scaled x1,x2,x3; /* intermediate values */
7957   x1=t_of_the_way(knot_coord(p),right_coord(p));
7958   x2=t_of_the_way(right_coord(p),left_coord(q));
7959   x3=t_of_the_way(left_coord(q),knot_coord(q));
7960   x1=t_of_the_way(x1,x2);
7961   x2=t_of_the_way(x2,x3);
7962   return t_of_the_way(x1,x2);
7963 }
7964
7965 @ The actual bounding box information is stored in global variables.
7966 Since it is convenient to address the $x$ and $y$ information
7967 separately, we define arrays indexed by |x_code..y_code| and use
7968 macros to give them more convenient names.
7969
7970 @<Types...@>=
7971 enum mp_bb_code  {
7972   mp_x_code=0, /* index for |minx| and |maxx| */
7973   mp_y_code /* index for |miny| and |maxy| */
7974 } ;
7975
7976
7977 @d minx mp->bbmin[mp_x_code]
7978 @d maxx mp->bbmax[mp_x_code]
7979 @d miny mp->bbmin[mp_y_code]
7980 @d maxy mp->bbmax[mp_y_code]
7981
7982 @<Glob...@>=
7983 scaled bbmin[mp_y_code+1];
7984 scaled bbmax[mp_y_code+1]; 
7985 /* the result of procedures that compute bounding box information */
7986
7987 @ Now we're ready for the key part of the bounding box computation.
7988 The |bound_cubic| procedure updates |bbmin[c]| and |bbmax[c]| based on
7989 $$B(\hbox{|knot_coord(p)|}, \hbox{|right_coord(p)|},
7990     \hbox{|left_coord(q)|}, \hbox{|knot_coord(q)|};t)
7991 $$
7992 for $0<t\le1$.  In other words, the procedure adjusts the bounds to
7993 accommodate |knot_coord(q)| and any extremes over the range $0<t<1$.
7994 The |c| parameter is |x_code| or |y_code|.
7995
7996 @c void mp_bound_cubic (MP mp,pointer p, pointer q, small_number c) {
7997   boolean wavy; /* whether we need to look for extremes */
7998   scaled del1,del2,del3,del,dmax; /* proportional to the control
7999      points of a quadratic derived from a cubic */
8000   fraction t,tt; /* where a quadratic crosses zero */
8001   scaled x; /* a value that |bbmin[c]| and |bbmax[c]| must accommodate */
8002   x=knot_coord(q);
8003   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8004   @<Check the control points against the bounding box and set |wavy:=true|
8005     if any of them lie outside@>;
8006   if ( wavy ) {
8007     del1=right_coord(p)-knot_coord(p);
8008     del2=left_coord(q)-right_coord(p);
8009     del3=knot_coord(q)-left_coord(q);
8010     @<Scale up |del1|, |del2|, and |del3| for greater accuracy;
8011       also set |del| to the first nonzero element of |(del1,del2,del3)|@>;
8012     if ( del<0 ) {
8013       negate(del1); negate(del2); negate(del3);
8014     };
8015     t=mp_crossing_point(mp, del1,del2,del3);
8016     if ( t<fraction_one ) {
8017       @<Test the extremes of the cubic against the bounding box@>;
8018     }
8019   }
8020 }
8021
8022 @ @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>=
8023 if ( x<mp->bbmin[c] ) mp->bbmin[c]=x;
8024 if ( x>mp->bbmax[c] ) mp->bbmax[c]=x
8025
8026 @ @<Check the control points against the bounding box and set...@>=
8027 wavy=true;
8028 if ( mp->bbmin[c]<=right_coord(p) )
8029   if ( right_coord(p)<=mp->bbmax[c] )
8030     if ( mp->bbmin[c]<=left_coord(q) )
8031       if ( left_coord(q)<=mp->bbmax[c] )
8032         wavy=false
8033
8034 @ If |del1=del2=del3=0|, it's impossible to obey the title of this
8035 section. We just set |del=0| in that case.
8036
8037 @<Scale up |del1|, |del2|, and |del3| for greater accuracy...@>=
8038 if ( del1!=0 ) del=del1;
8039 else if ( del2!=0 ) del=del2;
8040 else del=del3;
8041 if ( del!=0 ) {
8042   dmax=abs(del1);
8043   if ( abs(del2)>dmax ) dmax=abs(del2);
8044   if ( abs(del3)>dmax ) dmax=abs(del3);
8045   while ( dmax<fraction_half ) {
8046     dmax+=dmax; del1+=del1; del2+=del2; del3+=del3;
8047   }
8048 }
8049
8050 @ Since |crossing_point| has tried to choose |t| so that
8051 $B(|del1|,|del2|,|del3|;\tau)$ crosses zero at $\tau=|t|$ with negative
8052 slope, the value of |del2| computed below should not be positive.
8053 But rounding error could make it slightly positive in which case we
8054 must cut it to zero to avoid confusion.
8055
8056 @<Test the extremes of the cubic against the bounding box@>=
8057
8058   x=mp_eval_cubic(mp, p,q,t);
8059   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8060   del2=t_of_the_way(del2,del3);
8061     /* now |0,del2,del3| represent the derivative on the remaining interval */
8062   if ( del2>0 ) del2=0;
8063   tt=mp_crossing_point(mp, 0,-del2,-del3);
8064   if ( tt<fraction_one ) {
8065     @<Test the second extreme against the bounding box@>;
8066   }
8067 }
8068
8069 @ @<Test the second extreme against the bounding box@>=
8070 {
8071    x=mp_eval_cubic(mp, p,q,t_of_the_way(tt,fraction_one));
8072   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8073 }
8074
8075 @ Finding the bounding box of a path is basically a matter of applying
8076 |bound_cubic| twice for each pair of adjacent knots.
8077
8078 @c void mp_path_bbox (MP mp,pointer h) {
8079   pointer p,q; /* a pair of adjacent knots */
8080    minx=x_coord(h); miny=y_coord(h);
8081   maxx=minx; maxy=miny;
8082   p=h;
8083   do {  
8084     if ( right_type(p)==mp_endpoint ) return;
8085     q=link(p);
8086     mp_bound_cubic(mp, x_loc(p),x_loc(q),mp_x_code);
8087     mp_bound_cubic(mp, y_loc(p),y_loc(q),mp_y_code);
8088     p=q;
8089   } while (p!=h);
8090 }
8091
8092 @ Another important way to measure a path is to find its arc length.  This
8093 is best done by using the general bisection algorithm to subdivide the path
8094 until obtaining ``well behaved'' subpaths whose arc lengths can be approximated
8095 by simple means.
8096
8097 Since the arc length is the integral with respect to time of the magnitude of
8098 the velocity, it is natural to use Simpson's rule for the approximation.
8099 @^Simpson's rule@>
8100 If $\dot B(t)$ is the spline velocity, Simpson's rule gives
8101 $$ \vb\dot B(0)\vb + 4\vb\dot B({1\over2})\vb + \vb\dot B(1)\vb \over 6 $$
8102 for the arc length of a path of length~1.  For a cubic spline
8103 $B(z_0,z_1,z_2,z_3;t)$, the time derivative $\dot B(t)$ is
8104 $3B(dz_0,dz_1,dz_2;t)$, where $dz_i=z_{i+1}-z_i$.  Hence the arc length
8105 approximation is
8106 $$ {\vb dz_0\vb \over 2} + 2\vb dz_{02}\vb + {\vb dz_2\vb \over 2}, $$
8107 where
8108 $$ dz_{02}={1\over2}\left({dz_0+dz_1\over 2}+{dz_1+dz_2\over 2}\right)$$
8109 is the result of the bisection algorithm.
8110
8111 @ The remaining problem is how to decide when a subpath is ``well behaved.''
8112 This could be done via the theoretical error bound for Simpson's rule,
8113 @^Simpson's rule@>
8114 but this is impractical because it requires an estimate of the fourth
8115 derivative of the quantity being integrated.  It is much easier to just perform
8116 a bisection step and see how much the arc length estimate changes.  Since the
8117 error for Simpson's rule is proportional to the fourth power of the sample
8118 spacing, the remaining error is typically about $1\over16$ of the amount of
8119 the change.  We say ``typically'' because the error has a pseudo-random behavior
8120 that could cause the two estimates to agree when each contain large errors.
8121
8122 To protect against disasters such as undetected cusps, the bisection process
8123 should always continue until all the $dz_i$ vectors belong to a single
8124 $90^\circ$ sector.  This ensures that no point on the spline can have velocity
8125 less than 70\% of the minimum of $\vb dz_0\vb$, $\vb dz_1\vb$ and $\vb dz_2\vb$.
8126 If such a spline happens to produce an erroneous arc length estimate that
8127 is little changed by bisection, the amount of the error is likely to be fairly
8128 small.  We will try to arrange things so that freak accidents of this type do
8129 not destroy the inverse relationship between the \&{arclength} and
8130 \&{arctime} operations.
8131 @:arclength_}{\&{arclength} primitive@>
8132 @:arctime_}{\&{arctime} primitive@>
8133
8134 @ The \&{arclength} and \&{arctime} operations are both based on a recursive
8135 @^recursion@>
8136 function that finds the arc length of a cubic spline given $dz_0$, $dz_1$,
8137 $dz_2$. This |arc_test| routine also takes an arc length goal |a_goal| and
8138 returns the time when the arc length reaches |a_goal| if there is such a time.
8139 Thus the return value is either an arc length less than |a_goal| or, if the
8140 arc length would be at least |a_goal|, it returns a time value decreased by
8141 |two|.  This allows the caller to use the sign of the result to distinguish
8142 between arc lengths and time values.  On certain types of overflow, it is
8143 possible for |a_goal| and the result of |arc_test| both to be |el_gordo|.
8144 Otherwise, the result is always less than |a_goal|.
8145
8146 Rather than halving the control point coordinates on each recursive call to
8147 |arc_test|, it is better to keep them proportional to velocity on the original
8148 curve and halve the results instead.  This means that recursive calls can
8149 potentially use larger error tolerances in their arc length estimates.  How
8150 much larger depends on to what extent the errors behave as though they are
8151 independent of each other.  To save computing time, we use optimistic assumptions
8152 and increase the tolerance by a factor of about $\sqrt2$ for each recursive
8153 call.
8154
8155 In addition to the tolerance parameter, |arc_test| should also have parameters
8156 for ${1\over3}\vb\dot B(0)\vb$, ${2\over3}\vb\dot B({1\over2})\vb$, and
8157 ${1\over3}\vb\dot B(1)\vb$.  These quantities are relatively expensive to compute
8158 and they are needed in different instances of |arc_test|.
8159
8160 @c @t\4@>@<Declare subroutines needed by |arc_test|@>;
8161 scaled mp_arc_test (MP mp, scaled dx0, scaled dy0, scaled dx1, scaled dy1, 
8162                     scaled dx2, scaled dy2, scaled  v0, scaled v02, 
8163                     scaled v2, scaled a_goal, scaled tol) {
8164   boolean simple; /* are the control points confined to a $90^\circ$ sector? */
8165   scaled dx01, dy01, dx12, dy12, dx02, dy02;  /* bisection results */
8166   scaled v002, v022;
8167     /* twice the velocity magnitudes at $t={1\over4}$ and $t={3\over4}$ */
8168   scaled arc; /* best arc length estimate before recursion */
8169   @<Other local variables in |arc_test|@>;
8170   @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,
8171     |dx2|, |dy2|@>;
8172   @<Initialize |v002|, |v022|, and the arc length estimate |arc|; if it overflows
8173     set |arc_test| and |return|@>;
8174   @<Test if the control points are confined to one quadrant or rotating them
8175     $45^\circ$ would put them in one quadrant.  Then set |simple| appropriately@>;
8176   if ( simple && (abs(arc-v02-halfp(v0+v2)) <= tol) ) {
8177     if ( arc < a_goal ) {
8178       return arc;
8179     } else {
8180        @<Estimate when the arc length reaches |a_goal| and set |arc_test| to
8181          that time minus |two|@>;
8182     }
8183   } else {
8184     @<Use one or two recursive calls to compute the |arc_test| function@>;
8185   }
8186 }
8187
8188 @ The |tol| value should by multiplied by $\sqrt 2$ before making recursive
8189 calls, but $1.5$ is an adequate approximation.  It is best to avoid using
8190 |make_fraction| in this inner loop.
8191 @^inner loop@>
8192
8193 @<Use one or two recursive calls to compute the |arc_test| function@>=
8194
8195   @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is as
8196     large as possible@>;
8197   tol = tol + halfp(tol);
8198   a = mp_arc_test(mp, dx0,dy0, dx01,dy01, dx02,dy02, v0, v002, 
8199                   halfp(v02), a_new, tol);
8200   if ( a<0 )  {
8201      return (-halfp(two-a));
8202   } else { 
8203     @<Update |a_new| to reduce |a_new+a_aux| by |a|@>;
8204     b = mp_arc_test(mp, dx02,dy02, dx12,dy12, dx2,dy2,
8205                     halfp(v02), v022, v2, a_new, tol);
8206     if ( b<0 )  
8207       return (-halfp(-b) - half_unit);
8208     else  
8209       return (a + half(b-a));
8210   }
8211 }
8212
8213 @ @<Other local variables in |arc_test|@>=
8214 scaled a,b; /* results of recursive calls */
8215 scaled a_new,a_aux; /* the sum of these gives the |a_goal| */
8216
8217 @ @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is...@>=
8218 a_aux = el_gordo - a_goal;
8219 if ( a_goal > a_aux ) {
8220   a_aux = a_goal - a_aux;
8221   a_new = el_gordo;
8222 } else { 
8223   a_new = a_goal + a_goal;
8224   a_aux = 0;
8225 }
8226
8227 @ There is no need to maintain |a_aux| at this point so we use it as a temporary
8228 to force the additions and subtractions to be done in an order that avoids
8229 overflow.
8230
8231 @<Update |a_new| to reduce |a_new+a_aux| by |a|@>=
8232 if ( a > a_aux ) {
8233   a_aux = a_aux - a;
8234   a_new = a_new + a_aux;
8235 }
8236
8237 @ This code assumes all {\it dx} and {\it dy} variables have magnitude less than
8238 |fraction_four|.  To simplify the rest of the |arc_test| routine, we strengthen
8239 this assumption by requiring the norm of each $({\it dx},{\it dy})$ pair to obey
8240 this bound.  Note that recursive calls will maintain this invariant.
8241
8242 @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,...@>=
8243 dx01 = half(dx0 + dx1);
8244 dx12 = half(dx1 + dx2);
8245 dx02 = half(dx01 + dx12);
8246 dy01 = half(dy0 + dy1);
8247 dy12 = half(dy1 + dy2);
8248 dy02 = half(dy01 + dy12)
8249
8250 @ We should be careful to keep |arc<el_gordo| so that calling |arc_test| with
8251 |a_goal=el_gordo| is guaranteed to yield the arc length.
8252
8253 @<Initialize |v002|, |v022|, and the arc length estimate |arc|;...@>=
8254 v002 = mp_pyth_add(mp, dx01+half(dx0+dx02), dy01+half(dy0+dy02));
8255 v022 = mp_pyth_add(mp, dx12+half(dx02+dx2), dy12+half(dy02+dy2));
8256 tmp = halfp(v02+2);
8257 arc1 = v002 + half(halfp(v0+tmp) - v002);
8258 arc = v022 + half(halfp(v2+tmp) - v022);
8259 if ( (arc < el_gordo-arc1) )  {
8260   arc = arc+arc1;
8261 } else { 
8262   mp->arith_error = true;
8263   if ( a_goal==el_gordo )  return (el_gordo);
8264   else return (-two);
8265 }
8266
8267 @ @<Other local variables in |arc_test|@>=
8268 scaled tmp, tmp2; /* all purpose temporary registers */
8269 scaled arc1; /* arc length estimate for the first half */
8270
8271 @ @<Test if the control points are confined to one quadrant or rotating...@>=
8272 simple = ((dx0>=0) && (dx1>=0) && (dx2>=0)) ||
8273          ((dx0<=0) && (dx1<=0) && (dx2<=0));
8274 if ( simple )
8275   simple = ((dy0>=0) && (dy1>=0) && (dy2>=0)) ||
8276            ((dy0<=0) && (dy1<=0) && (dy2<=0));
8277 if ( ! simple ) {
8278   simple = ((dx0>=dy0) && (dx1>=dy1) && (dx2>=dy2)) ||
8279            ((dx0<=dy0) && (dx1<=dy1) && (dx2<=dy2));
8280   if ( simple ) 
8281     simple = ((-dx0>=dy0) && (-dx1>=dy1) && (-dx2>=dy2)) ||
8282              ((-dx0<=dy0) && (-dx1<=dy1) && (-dx2<=dy2));
8283 }
8284
8285 @ Since Simpson's rule is based on approximating the integrand by a parabola,
8286 @^Simpson's rule@>
8287 it is appropriate to use the same approximation to decide when the integral
8288 reaches the intermediate value |a_goal|.  At this point
8289 $$\eqalign{
8290     {\vb\dot B(0)\vb\over 3} &= \hbox{|v0|}, \qquad
8291     {\vb\dot B({1\over4})\vb\over 3} = {\hbox{|v002|}\over 2}, \qquad
8292     {\vb\dot B({1\over2})\vb\over 3} = {\hbox{|v02|}\over 2}, \cr
8293     {\vb\dot B({3\over4})\vb\over 3} &= {\hbox{|v022|}\over 2}, \qquad
8294     {\vb\dot B(1)\vb\over 3} = \hbox{|v2|} \cr
8295 }
8296 $$
8297 and
8298 $$ {\vb\dot B(t)\vb\over 3} \approx
8299   \cases{B\left(\hbox{|v0|},
8300       \hbox{|v002|}-{1\over 2}\hbox{|v0|}-{1\over 4}\hbox{|v02|},
8301       {1\over 2}\hbox{|v02|}; 2t \right)&
8302     if $t\le{1\over 2}$\cr
8303   B\left({1\over 2}\hbox{|v02|},
8304       \hbox{|v022|}-{1\over 4}\hbox{|v02|}-{1\over 2}\hbox{|v2|},
8305       \hbox{|v2|}; 2t-1 \right)&
8306     if $t\ge{1\over 2}$.\cr}
8307  \eqno (*)
8308 $$
8309 We can integrate $\vb\dot B(t)\vb$ by using
8310 $$\int 3B(a,b,c;\tau)\,dt =
8311   {B(0,a,a+b,a+b+c;\tau) + {\rm constant} \over {d\tau\over dt}}.
8312 $$
8313
8314 This construction allows us to find the time when the arc length reaches
8315 |a_goal| by solving a cubic equation of the form
8316 $$ B(0,a,a+b,a+b+c;\tau) = x, $$
8317 where $\tau$ is $2t$ or $2t+1$, $x$ is |a_goal| or |a_goal-arc1|, and $a$, $b$,
8318 and $c$ are the Bernshte{\u\i}n coefficients from $(*)$ divided by
8319 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
8320 $d\tau\over dt$.  We shall define a function |solve_rising_cubic| that finds
8321 $\tau$ given $a$, $b$, $c$, and $x$.
8322
8323 @<Estimate when the arc length reaches |a_goal| and set |arc_test| to...@>=
8324
8325   tmp = (v02 + 2) / 4;
8326   if ( a_goal<=arc1 ) {
8327     tmp2 = halfp(v0);
8328     return 
8329       (halfp(mp_solve_rising_cubic(mp, tmp2, arc1-tmp2-tmp, tmp, a_goal))- two);
8330   } else { 
8331     tmp2 = halfp(v2);
8332     return ((half_unit - two) +
8333       halfp(mp_solve_rising_cubic(mp, tmp, arc-arc1-tmp-tmp2, tmp2, a_goal-arc1)));
8334   }
8335 }
8336
8337 @ Here is the |solve_rising_cubic| routine that finds the time~$t$ when
8338 $$ B(0, a, a+b, a+b+c; t) = x. $$
8339 This routine is based on |crossing_point| but is simplified by the
8340 assumptions that $B(a,b,c;t)\ge0$ for $0\le t\le1$ and that |0<=x<=a+b+c|.
8341 If rounding error causes this condition to be violated slightly, we just ignore
8342 it and proceed with binary search.  This finds a time when the function value
8343 reaches |x| and the slope is positive.
8344
8345 @<Declare subroutines needed by |arc_test|@>=
8346 scaled mp_solve_rising_cubic (MP mp,scaled a, scaled b,  scaled c, scaled x) {
8347   scaled ab, bc, ac; /* bisection results */
8348   integer t; /* $2^k+q$ where unscaled answer is in $[q2^{-k},(q+1)2^{-k})$ */
8349   integer xx; /* temporary for updating |x| */
8350   if ( (a<0) || (c<0) ) mp_confusion(mp, "rising?");
8351 @:this can't happen rising?}{\quad rising?@>
8352   if ( x<=0 ) {
8353         return 0;
8354   } else if ( x >= a+b+c ) {
8355     return unity;
8356   } else { 
8357     t = 1;
8358     @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than
8359       |el_gordo div 3|@>;
8360     do {  
8361       t+=t;
8362       @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>;
8363       xx = x - a - ab - ac;
8364       if ( xx < -x ) { x+=x; b=ab; c=ac;  }
8365       else { x = x + xx;  a=ac; b=mp->bc; t = t+1; };
8366     } while (t < unity);
8367     return (t - unity);
8368   }
8369 }
8370
8371 @ @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>=
8372 ab = half(a+b);
8373 bc = half(b+c);
8374 ac = half(ab+bc)
8375
8376 @ @d one_third_el_gordo 05252525252 /* upper bound on |a|, |b|, and |c| */
8377
8378 @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than...@>=
8379 while ((a>one_third_el_gordo)||(b>one_third_el_gordo)||(c>one_third_el_gordo)) { 
8380   a = halfp(a);
8381   b = half(b);
8382   c = halfp(c);
8383   x = halfp(x);
8384 }
8385
8386 @ It is convenient to have a simpler interface to |arc_test| that requires no
8387 unnecessary arguments and ensures that each $({\it dx},{\it dy})$ pair has
8388 length less than |fraction_four|.
8389
8390 @d arc_tol   16  /* quit when change in arc length estimate reaches this */
8391
8392 @c scaled mp_do_arc_test (MP mp,scaled dx0, scaled dy0, scaled dx1, 
8393                           scaled dy1, scaled dx2, scaled dy2, scaled a_goal) {
8394   scaled v0,v1,v2; /* length of each $({\it dx},{\it dy})$ pair */
8395   scaled v02; /* twice the norm of the quadratic at $t={1\over2}$ */
8396   v0 = mp_pyth_add(mp, dx0,dy0);
8397   v1 = mp_pyth_add(mp, dx1,dy1);
8398   v2 = mp_pyth_add(mp, dx2,dy2);
8399   if ( (v0>=fraction_four) || (v1>=fraction_four) || (v2>=fraction_four) ) { 
8400     mp->arith_error = true;
8401     if ( a_goal==el_gordo )  return el_gordo;
8402     else return (-two);
8403   } else { 
8404     v02 = mp_pyth_add(mp, dx1+half(dx0+dx2), dy1+half(dy0+dy2));
8405     return (mp_arc_test(mp, dx0,dy0, dx1,dy1, dx2,dy2,
8406                                  v0, v02, v2, a_goal, arc_tol));
8407   }
8408 }
8409
8410 @ Now it is easy to find the arc length of an entire path.
8411
8412 @c scaled mp_get_arc_length (MP mp,pointer h) {
8413   pointer p,q; /* for traversing the path */
8414   scaled a,a_tot; /* current and total arc lengths */
8415   a_tot = 0;
8416   p = h;
8417   while ( right_type(p)!=mp_endpoint ){ 
8418     q = link(p);
8419     a = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8420       left_x(q)-right_x(p), left_y(q)-right_y(p),
8421       x_coord(q)-left_x(q), y_coord(q)-left_y(q), el_gordo);
8422     a_tot = mp_slow_add(mp, a, a_tot);
8423     if ( q==h ) break;  else p=q;
8424   }
8425   check_arith;
8426   return a_tot;
8427 }
8428
8429 @ The inverse operation of finding the time on a path~|h| when the arc length
8430 reaches some value |arc0| can also be accomplished via |do_arc_test|.  Some care
8431 is required to handle very large times or negative times on cyclic paths.  For
8432 non-cyclic paths, |arc0| values that are negative or too large cause
8433 |get_arc_time| to return 0 or the length of path~|h|.
8434
8435 If |arc0| is greater than the arc length of a cyclic path~|h|, the result is a
8436 time value greater than the length of the path.  Since it could be much greater,
8437 we must be prepared to compute the arc length of path~|h| and divide this into
8438 |arc0| to find how many multiples of the length of path~|h| to add.
8439
8440 @c scaled mp_get_arc_time (MP mp,pointer h, scaled  arc0) {
8441   pointer p,q; /* for traversing the path */
8442   scaled t_tot; /* accumulator for the result */
8443   scaled t; /* the result of |do_arc_test| */
8444   scaled arc; /* portion of |arc0| not used up so far */
8445   integer n; /* number of extra times to go around the cycle */
8446   if ( arc0<0 ) {
8447     @<Deal with a negative |arc0| value and |return|@>;
8448   }
8449   if ( arc0==el_gordo ) decr(arc0);
8450   t_tot = 0;
8451   arc = arc0;
8452   p = h;
8453   while ( (right_type(p)!=mp_endpoint) && (arc>0) ) {
8454     q = link(p);
8455     t = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8456       left_x(q)-right_x(p), left_y(q)-right_y(p),
8457       x_coord(q)-left_x(q), y_coord(q)-left_y(q), arc);
8458     @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>;
8459     if ( q==h ) {
8460       @<Update |t_tot| and |arc| to avoid going around the cyclic
8461         path too many times but set |arith_error:=true| and |goto done| on
8462         overflow@>;
8463     }
8464     p = q;
8465   }
8466   check_arith;
8467   return t_tot;
8468 }
8469
8470 @ @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>=
8471 if ( t<0 ) { t_tot = t_tot + t + two;  arc = 0;  }
8472 else { t_tot = t_tot + unity;  arc = arc - t;  }
8473
8474 @ @<Deal with a negative |arc0| value and |return|@>=
8475
8476   if ( left_type(h)==mp_endpoint ) {
8477     t_tot=0;
8478   } else { 
8479     p = mp_htap_ypoc(mp, h);
8480     t_tot = -mp_get_arc_time(mp, p, -arc0);
8481     mp_toss_knot_list(mp, p);
8482   }
8483   check_arith;
8484   return t_tot;
8485 }
8486
8487 @ @<Update |t_tot| and |arc| to avoid going around the cyclic...@>=
8488 if ( arc>0 ) { 
8489   n = arc / (arc0 - arc);
8490   arc = arc - n*(arc0 - arc);
8491   if ( t_tot > el_gordo / (n+1) ) { 
8492     mp->arith_error = true;
8493     t_tot = el_gordo;
8494     break;
8495   }
8496   t_tot = (n + 1)*t_tot;
8497 }
8498
8499 @* \[20] Data structures for pens.
8500 A Pen in \MP\ can be either elliptical or polygonal.  Elliptical pens result
8501 in \ps\ \&{stroke} commands, while anything drawn with a polygonal pen is
8502 @:stroke}{\&{stroke} command@>
8503 converted into an area fill as described in the next part of this program.
8504 The mathematics behind this process is based on simple aspects of the theory
8505 of tracings developed by Leo Guibas, Lyle Ramshaw, and Jorge Stolfi
8506 [``A kinematic framework for computational geometry,'' Proc.\ IEEE Symp.\
8507 Foundations of Computer Science {\bf 24} (1983), 100--111].
8508
8509 Polygonal pens are created from paths via \MP's \&{makepen} primitive.
8510 @:makepen_}{\&{makepen} primitive@>
8511 This path representation is almost sufficient for our purposes except that
8512 a pen path should always be a convex polygon with the vertices in
8513 counter-clockwise order.
8514 Since we will need to scan pen polygons both forward and backward, a pen
8515 should be represented as a doubly linked ring of knot nodes.  There is
8516 room for the extra back pointer because we do not need the
8517 |left_type| or |right_type| fields.  In fact, we don't need the |left_x|,
8518 |left_y|, |right_x|, or |right_y| fields either but we leave these alone
8519 so that certain procedures can operate on both pens and paths.  In particular,
8520 pens can be copied using |copy_path| and recycled using |toss_knot_list|.
8521
8522 @d knil info
8523   /* this replaces the |left_type| and |right_type| fields in a pen knot */
8524
8525 @ The |make_pen| procedure turns a path into a pen by initializing
8526 the |knil| pointers and making sure the knots form a convex polygon.
8527 Thus each cubic in the given path becomes a straight line and the control
8528 points are ignored.  If the path is not cyclic, the ends are connected by a
8529 straight line.
8530
8531 @d copy_pen(A) mp_make_pen(mp, mp_copy_path(mp, (A)),false)
8532
8533 @c @<Declare a function called |convex_hull|@>;
8534 pointer mp_make_pen (MP mp,pointer h, boolean need_hull) {
8535   pointer p,q; /* two consecutive knots */
8536   q=h;
8537   do {  
8538     p=q; q=link(q);
8539     knil(q)=p;
8540   } while (q!=h);
8541   if ( need_hull ){ 
8542     h=mp_convex_hull(mp, h);
8543     @<Make sure |h| isn't confused with an elliptical pen@>;
8544   }
8545   return h;
8546 }
8547
8548 @ The only information required about an elliptical pen is the overall
8549 transformation that has been applied to the original \&{pencircle}.
8550 @:pencircle_}{\&{pencircle} primitive@>
8551 Since it suffices to keep track of how the three points $(0,0)$, $(1,0)$,
8552 and $(0,1)$ are transformed, an elliptical pen can be stored in a single
8553 knot node and transformed as if it were a path.
8554
8555 @d pen_is_elliptical(A) ((A)==link((A)))
8556
8557 @c pointer mp_get_pen_circle (MP mp,scaled diam) {
8558   pointer h; /* the knot node to return */
8559   h=mp_get_node(mp, knot_node_size);
8560   link(h)=h; knil(h)=h;
8561   originator(h)=mp_program_code;
8562   x_coord(h)=0; y_coord(h)=0;
8563   left_x(h)=diam; left_y(h)=0;
8564   right_x(h)=0; right_y(h)=diam;
8565   return h;
8566 }
8567
8568 @ If the polygon being returned by |make_pen| has only one vertex, it will
8569 be interpreted as an elliptical pen.  This is no problem since a degenerate
8570 polygon can equally well be thought of as a degenerate ellipse.  We need only
8571 initialize the |left_x|, |left_y|, |right_x|, and |right_y| fields.
8572
8573 @<Make sure |h| isn't confused with an elliptical pen@>=
8574 if ( pen_is_elliptical( h) ){ 
8575   left_x(h)=x_coord(h); left_y(h)=y_coord(h);
8576   right_x(h)=x_coord(h); right_y(h)=y_coord(h);
8577 }
8578
8579 @ We have to cheat a little here but most operations on pens only use
8580 the first three words in each knot node.
8581 @^data structure assumptions@>
8582
8583 @<Initialize a pen at |test_pen| so that it fits in nine words@>=
8584 x_coord(test_pen)=-half_unit;
8585 y_coord(test_pen)=0;
8586 x_coord(test_pen+3)=half_unit;
8587 y_coord(test_pen+3)=0;
8588 x_coord(test_pen+6)=0;
8589 y_coord(test_pen+6)=unity;
8590 link(test_pen)=test_pen+3;
8591 link(test_pen+3)=test_pen+6;
8592 link(test_pen+6)=test_pen;
8593 knil(test_pen)=test_pen+6;
8594 knil(test_pen+3)=test_pen;
8595 knil(test_pen+6)=test_pen+3
8596
8597 @ Printing a polygonal pen is very much like printing a path
8598
8599 @<Declare subroutines for printing expressions@>=
8600 void mp_pr_pen (MP mp,pointer h) {
8601   pointer p,q; /* for list traversal */
8602   if ( pen_is_elliptical(h) ) {
8603     @<Print the elliptical pen |h|@>;
8604   } else { 
8605     p=h;
8606     do {  
8607       mp_print_two(mp, x_coord(p),y_coord(p));
8608       mp_print_nl(mp, " .. ");
8609       @<Advance |p| making sure the links are OK and |return| if there is
8610         a problem@>;
8611      } while (p!=h);
8612      mp_print(mp, "cycle");
8613   }
8614 }
8615
8616 @ @<Advance |p| making sure the links are OK and |return| if there is...@>=
8617 q=link(p);
8618 if ( (q==null) || (knil(q)!=p) ) { 
8619   mp_print_nl(mp, "???"); return; /* this won't happen */
8620 @.???@>
8621 }
8622 p=q
8623
8624 @ @<Print the elliptical pen |h|@>=
8625
8626 mp_print(mp, "pencircle transformed (");
8627 mp_print_scaled(mp, x_coord(h));
8628 mp_print_char(mp, ',');
8629 mp_print_scaled(mp, y_coord(h));
8630 mp_print_char(mp, ',');
8631 mp_print_scaled(mp, left_x(h)-x_coord(h));
8632 mp_print_char(mp, ',');
8633 mp_print_scaled(mp, right_x(h)-x_coord(h));
8634 mp_print_char(mp, ',');
8635 mp_print_scaled(mp, left_y(h)-y_coord(h));
8636 mp_print_char(mp, ',');
8637 mp_print_scaled(mp, right_y(h)-y_coord(h));
8638 mp_print_char(mp, ')');
8639 }
8640
8641 @ Here us another version of |pr_pen| that prints the pen as a diagnostic
8642 message.
8643
8644 @<Declare subroutines for printing expressions@>=
8645 void mp_print_pen (MP mp,pointer h, char *s, boolean nuline) { 
8646   mp_print_diagnostic(mp, "Pen",s,nuline); mp_print_ln(mp);
8647 @.Pen at line...@>
8648   mp_pr_pen(mp, h);
8649   mp_end_diagnostic(mp, true);
8650 }
8651
8652 @ Making a polygonal pen into a path involves restoring the |left_type| and
8653 |right_type| fields and setting the control points so as to make a polygonal
8654 path.
8655
8656 @c 
8657 void mp_make_path (MP mp,pointer h) {
8658   pointer p; /* for traversing the knot list */
8659   small_number k; /* a loop counter */
8660   @<Other local variables in |make_path|@>;
8661   if ( pen_is_elliptical(h) ) {
8662     @<Make the elliptical pen |h| into a path@>;
8663   } else { 
8664     p=h;
8665     do {  
8666       left_type(p)=mp_explicit;
8667       right_type(p)=mp_explicit;
8668       @<copy the coordinates of knot |p| into its control points@>;
8669        p=link(p);
8670     } while (p!=h);
8671   }
8672 }
8673
8674 @ @<copy the coordinates of knot |p| into its control points@>=
8675 left_x(p)=x_coord(p);
8676 left_y(p)=y_coord(p);
8677 right_x(p)=x_coord(p);
8678 right_y(p)=y_coord(p)
8679
8680 @ We need an eight knot path to get a good approximation to an ellipse.
8681
8682 @<Make the elliptical pen |h| into a path@>=
8683
8684   @<Extract the transformation parameters from the elliptical pen~|h|@>;
8685   p=h;
8686   for (k=0;k<=7;k++ ) { 
8687     @<Initialize |p| as the |k|th knot of a circle of unit diameter,
8688       transforming it appropriately@>;
8689     if ( k==7 ) link(p)=h;  else link(p)=mp_get_node(mp, knot_node_size);
8690     p=link(p);
8691   }
8692 }
8693
8694 @ @<Extract the transformation parameters from the elliptical pen~|h|@>=
8695 center_x=x_coord(h);
8696 center_y=y_coord(h);
8697 width_x=left_x(h)-center_x;
8698 width_y=left_y(h)-center_y;
8699 height_x=right_x(h)-center_x;
8700 height_y=right_y(h)-center_y
8701
8702 @ @<Other local variables in |make_path|@>=
8703 scaled center_x,center_y; /* translation parameters for an elliptical pen */
8704 scaled width_x,width_y; /* the effect of a unit change in $x$ */
8705 scaled height_x,height_y; /* the effect of a unit change in $y$ */
8706 scaled dx,dy; /* the vector from knot |p| to its right control point */
8707 integer kk;
8708   /* |k| advanced $270^\circ$ around the ring (cf. $\sin\theta=\cos(\theta+270)$) */
8709
8710 @ The only tricky thing here are the tables |half_cos| and |d_cos| used to
8711 find the point $k/8$ of the way around the circle and the direction vector
8712 to use there.
8713
8714 @<Initialize |p| as the |k|th knot of a circle of unit diameter,...@>=
8715 kk=(k+6)% 8;
8716 x_coord(p)=center_x+mp_take_fraction(mp, mp->half_cos[k],width_x)
8717            +mp_take_fraction(mp, mp->half_cos[kk],height_x);
8718 y_coord(p)=center_y+mp_take_fraction(mp, mp->half_cos[k],width_y)
8719            +mp_take_fraction(mp, mp->half_cos[kk],height_y);
8720 dx=-mp_take_fraction(mp, mp->d_cos[kk],width_x)
8721    +mp_take_fraction(mp, mp->d_cos[k],height_x);
8722 dy=-mp_take_fraction(mp, mp->d_cos[kk],width_y)
8723    +mp_take_fraction(mp, mp->d_cos[k],height_y);
8724 right_x(p)=x_coord(p)+dx;
8725 right_y(p)=y_coord(p)+dy;
8726 left_x(p)=x_coord(p)-dx;
8727 left_y(p)=y_coord(p)-dy;
8728 left_type(p)=mp_explicit;
8729 right_type(p)=mp_explicit;
8730 originator(p)=mp_program_code
8731
8732 @ @<Glob...@>=
8733 fraction half_cos[8]; /* ${1\over2}\cos(45k)$ */
8734 fraction d_cos[8]; /* a magic constant times $\cos(45k)$ */
8735
8736 @ The magic constant for |d_cos| is the distance between $({1\over2},0)$ and
8737 $({1\over4}\sqrt2,{1\over4}\sqrt2)$ times the result of the |velocity|
8738 function for $\theta=\phi=22.5^\circ$.  This comes out to be
8739 $$ d = {\sqrt{2-\sqrt2}\over 3+3\cos22.5^\circ}
8740   \approx 0.132608244919772.
8741 $$
8742
8743 @<Set init...@>=
8744 mp->half_cos[0]=fraction_half;
8745 mp->half_cos[1]=94906266; /* $2^{26}\sqrt2\approx94906265.62$ */
8746 mp->half_cos[2]=0;
8747 mp->d_cos[0]=35596755; /* $2^{28}d\approx35596754.69$ */
8748 mp->d_cos[1]=25170707; /* $2^{27}\sqrt2\,d\approx25170706.63$ */
8749 mp->d_cos[2]=0;
8750 for (k=3;k<= 4;k++ ) { 
8751   mp->half_cos[k]=-mp->half_cos[4-k];
8752   mp->d_cos[k]=-mp->d_cos[4-k];
8753 }
8754 for (k=5;k<= 7;k++ ) { 
8755   mp->half_cos[k]=mp->half_cos[8-k];
8756   mp->d_cos[k]=mp->d_cos[8-k];
8757 }
8758
8759 @ The |convex_hull| function forces a pen polygon to be convex when it is
8760 returned by |make_pen| and after any subsequent transformation where rounding
8761 error might allow the convexity to be lost.
8762 The convex hull algorithm used here is described by F.~P. Preparata and
8763 M.~I. Shamos [{\sl Computational Geometry}, Springer-Verlag, 1985].
8764
8765 @<Declare a function called |convex_hull|@>=
8766 @<Declare a procedure called |move_knot|@>;
8767 pointer mp_convex_hull (MP mp,pointer h) { /* Make a polygonal pen convex */
8768   pointer l,r; /* the leftmost and rightmost knots */
8769   pointer p,q; /* knots being scanned */
8770   pointer s; /* the starting point for an upcoming scan */
8771   scaled dx,dy; /* a temporary pointer */
8772   if ( pen_is_elliptical(h) ) {
8773      return h;
8774   } else { 
8775     @<Set |l| to the leftmost knot in polygon~|h|@>;
8776     @<Set |r| to the rightmost knot in polygon~|h|@>;
8777     if ( l!=r ) { 
8778       s=link(r);
8779       @<Find any knots on the path from |l| to |r| above the |l|-|r| line and
8780         move them past~|r|@>;
8781       @<Find any knots on the path from |s| to |l| below the |l|-|r| line and
8782         move them past~|l|@>;
8783       @<Sort the path from |l| to |r| by increasing $x$@>;
8784       @<Sort the path from |r| to |l| by decreasing $x$@>;
8785     }
8786     if ( l!=link(l) ) {
8787       @<Do a Gramm scan and remove vertices where there is no left turn@>;
8788     }
8789     return l;
8790   }
8791 }
8792
8793 @ All comparisons are done primarily on $x$ and secondarily on $y$.
8794
8795 @<Set |l| to the leftmost knot in polygon~|h|@>=
8796 l=h;
8797 p=link(h);
8798 while ( p!=h ) { 
8799   if ( x_coord(p)<=x_coord(l) )
8800     if ( (x_coord(p)<x_coord(l)) || (y_coord(p)<y_coord(l)) )
8801       l=p;
8802   p=link(p);
8803 }
8804
8805 @ @<Set |r| to the rightmost knot in polygon~|h|@>=
8806 r=h;
8807 p=link(h);
8808 while ( p!=h ) { 
8809   if ( x_coord(p)>=x_coord(r) )
8810     if ( (x_coord(p)>x_coord(r)) || (y_coord(p)>y_coord(r)) )
8811       r=p;
8812   p=link(p);
8813 }
8814
8815 @ @<Find any knots on the path from |l| to |r| above the |l|-|r| line...@>=
8816 dx=x_coord(r)-x_coord(l);
8817 dy=y_coord(r)-y_coord(l);
8818 p=link(l);
8819 while ( p!=r ) { 
8820   q=link(p);
8821   if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))>0 )
8822     mp_move_knot(mp, p, r);
8823   p=q;
8824 }
8825
8826 @ The |move_knot| procedure removes |p| from a doubly linked list and inserts
8827 it after |q|.
8828
8829 @ @<Declare a procedure called |move_knot|@>=
8830 void mp_move_knot (MP mp,pointer p, pointer q) { 
8831   link(knil(p))=link(p);
8832   knil(link(p))=knil(p);
8833   knil(p)=q;
8834   link(p)=link(q);
8835   link(q)=p;
8836   knil(link(p))=p;
8837 }
8838
8839 @ @<Find any knots on the path from |s| to |l| below the |l|-|r| line...@>=
8840 p=s;
8841 while ( p!=l ) { 
8842   q=link(p);
8843   if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))<0 )
8844     mp_move_knot(mp, p,l);
8845   p=q;
8846 }
8847
8848 @ The list is likely to be in order already so we just do linear insertions.
8849 Secondary comparisons on $y$ ensure that the sort is consistent with the
8850 choice of |l| and |r|.
8851
8852 @<Sort the path from |l| to |r| by increasing $x$@>=
8853 p=link(l);
8854 while ( p!=r ) { 
8855   q=knil(p);
8856   while ( x_coord(q)>x_coord(p) ) q=knil(q);
8857   while ( x_coord(q)==x_coord(p) ) {
8858     if ( y_coord(q)>y_coord(p) ) q=knil(q); else break;
8859   }
8860   if ( q==knil(p) ) p=link(p);
8861   else { p=link(p); mp_move_knot(mp, knil(p),q); };
8862 }
8863
8864 @ @<Sort the path from |r| to |l| by decreasing $x$@>=
8865 p=link(r);
8866 while ( p!=l ){ 
8867   q=knil(p);
8868   while ( x_coord(q)<x_coord(p) ) q=knil(q);
8869   while ( x_coord(q)==x_coord(p) ) {
8870     if ( y_coord(q)<y_coord(p) ) q=knil(q); else break;
8871   }
8872   if ( q==knil(p) ) p=link(p);
8873   else { p=link(p); mp_move_knot(mp, knil(p),q); };
8874 }
8875
8876 @ The condition involving |ab_vs_cd| tests if there is not a left turn
8877 at knot |q|.  There usually will be a left turn so we streamline the case
8878 where the |then| clause is not executed.
8879
8880 @<Do a Gramm scan and remove vertices where there...@>=
8881
8882 p=l; q=link(l);
8883 while (1) { 
8884   dx=x_coord(q)-x_coord(p);
8885   dy=y_coord(q)-y_coord(p);
8886   p=q; q=link(q);
8887   if ( p==l ) break;
8888   if ( p!=r )
8889     if ( mp_ab_vs_cd(mp, dx,y_coord(q)-y_coord(p),dy,x_coord(q)-x_coord(p))<=0 ) {
8890       @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>;
8891     }
8892   }
8893 }
8894
8895 @ @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>=
8896
8897 s=knil(p);
8898 mp_free_node(mp, p,knot_node_size);
8899 link(s)=q; knil(q)=s;
8900 if ( s==l ) p=s;
8901 else { p=knil(s); q=s; };
8902 }
8903
8904 @ The |find_offset| procedure sets global variables |(cur_x,cur_y)| to the
8905 offset associated with the given direction |(x,y)|.  If two different offsets
8906 apply, it chooses one of them.
8907
8908 @c 
8909 void mp_find_offset (MP mp,scaled x, scaled y, pointer h) {
8910   pointer p,q; /* consecutive knots */
8911   scaled wx,wy,hx,hy;
8912   /* the transformation matrix for an elliptical pen */
8913   fraction xx,yy; /* untransformed offset for an elliptical pen */
8914   fraction d; /* a temporary register */
8915   if ( pen_is_elliptical(h) ) {
8916     @<Find the offset for |(x,y)| on the elliptical pen~|h|@>
8917   } else { 
8918     q=h;
8919     do {  
8920       p=q; q=link(q);
8921     } while (!(mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)>=0));
8922     do {  
8923       p=q; q=link(q);
8924     } while (!(mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)<=0));
8925     mp->cur_x=x_coord(p);
8926     mp->cur_y=y_coord(p);
8927   }
8928 }
8929
8930 @ @<Glob...@>=
8931 scaled cur_x;
8932 scaled cur_y; /* all-purpose return value registers */
8933
8934 @ @<Find the offset for |(x,y)| on the elliptical pen~|h|@>=
8935 if ( (x==0) && (y==0) ) {
8936   mp->cur_x=x_coord(h); mp->cur_y=y_coord(h);  
8937 } else { 
8938   @<Find the non-constant part of the transformation for |h|@>;
8939   while ( (abs(x)<fraction_half) && (abs(y)<fraction_half) ){ 
8940     x+=x; y+=y;  
8941   };
8942   @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the
8943     untransformed version of |(x,y)|@>;
8944   mp->cur_x=x_coord(h)+mp_take_fraction(mp, xx,wx)+mp_take_fraction(mp, yy,hx);
8945   mp->cur_y=y_coord(h)+mp_take_fraction(mp, xx,wy)+mp_take_fraction(mp, yy,hy);
8946 }
8947
8948 @ @<Find the non-constant part of the transformation for |h|@>=
8949 wx=left_x(h)-x_coord(h);
8950 wy=left_y(h)-y_coord(h);
8951 hx=right_x(h)-x_coord(h);
8952 hy=right_y(h)-y_coord(h)
8953
8954 @ @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the...@>=
8955 yy=-(mp_take_fraction(mp, x,hy)+mp_take_fraction(mp, y,-hx));
8956 xx=mp_take_fraction(mp, x,-wy)+mp_take_fraction(mp, y,wx);
8957 d=mp_pyth_add(mp, xx,yy);
8958 if ( d>0 ) { 
8959   xx=half(mp_make_fraction(mp, xx,d));
8960   yy=half(mp_make_fraction(mp, yy,d));
8961 }
8962
8963 @ Finding the bounding box of a pen is easy except if the pen is elliptical.
8964 But we can handle that case by just calling |find_offset| twice.  The answer
8965 is stored in the global variables |minx|, |maxx|, |miny|, and |maxy|.
8966
8967 @c 
8968 void mp_pen_bbox (MP mp,pointer h) {
8969   pointer p; /* for scanning the knot list */
8970   if ( pen_is_elliptical(h) ) {
8971     @<Find the bounding box of an elliptical pen@>;
8972   } else { 
8973     minx=x_coord(h); maxx=minx;
8974     miny=y_coord(h); maxy=miny;
8975     p=link(h);
8976     while ( p!=h ) {
8977       if ( x_coord(p)<minx ) minx=x_coord(p);
8978       if ( y_coord(p)<miny ) miny=y_coord(p);
8979       if ( x_coord(p)>maxx ) maxx=x_coord(p);
8980       if ( y_coord(p)>maxy ) maxy=y_coord(p);
8981       p=link(p);
8982     }
8983   }
8984 }
8985
8986 @ @<Find the bounding box of an elliptical pen@>=
8987
8988 mp_find_offset(mp, 0,fraction_one,h);
8989 maxx=mp->cur_x;
8990 minx=2*x_coord(h)-mp->cur_x;
8991 mp_find_offset(mp, -fraction_one,0,h);
8992 maxy=mp->cur_y;
8993 miny=2*y_coord(h)-mp->cur_y;
8994 }
8995
8996 @* \[21] Edge structures.
8997 Now we come to \MP's internal scheme for representing pictures.
8998 The representation is very different from \MF's edge structures
8999 because \MP\ pictures contain \ps\ graphics objects instead of pixel
9000 images.  However, the basic idea is somewhat similar in that shapes
9001 are represented via their boundaries.
9002
9003 The main purpose of edge structures is to keep track of graphical objects
9004 until it is time to translate them into \ps.  Since \MP\ does not need to
9005 know anything about an edge structure other than how to translate it into
9006 \ps\ and how to find its bounding box, edge structures can be just linked
9007 lists of graphical objects.  \MP\ has no easy way to determine whether
9008 two such objects overlap, but it suffices to draw the first one first and
9009 let the second one overwrite it if necessary.
9010
9011 @<Types...@>=
9012 enum mp_graphical_object_code {
9013   @<Graphical object codes@>
9014 };
9015
9016 @ Let's consider the types of graphical objects one at a time.
9017 First of all, a filled contour is represented by a eight-word node.  The first
9018 word contains |type| and |link| fields, and the next six words contain a
9019 pointer to a cyclic path and the value to use for \ps' \&{currentrgbcolor}
9020 parameter.  If a pen is used for filling |pen_p|, |ljoin_val| and |miterlim_val|
9021 give the relevant information.
9022
9023 @d path_p(A) link((A)+1)
9024   /* a pointer to the path that needs filling */
9025 @d pen_p(A) info((A)+1)
9026   /* a pointer to the pen to fill or stroke with */
9027 @d color_model(A) type((A)+2) /*  the color model  */
9028 @d obj_red_loc(A) ((A)+3)  /* the first of three locations for the color */
9029 @d obj_cyan_loc obj_red_loc  /* the first of four locations for the color */
9030 @d obj_grey_loc obj_red_loc  /* the location for the color */
9031 @d red_val(A) mp->mem[(A)+3].sc
9032   /* the red component of the color in the range $0\ldots1$ */
9033 @d cyan_val red_val
9034 @d grey_val red_val
9035 @d green_val(A) mp->mem[(A)+4].sc
9036   /* the green component of the color in the range $0\ldots1$ */
9037 @d magenta_val green_val
9038 @d blue_val(A) mp->mem[(A)+5].sc
9039   /* the blue component of the color in the range $0\ldots1$ */
9040 @d yellow_val blue_val
9041 @d black_val(A) mp->mem[(A)+6].sc
9042   /* the blue component of the color in the range $0\ldots1$ */
9043 @d ljoin_val(A) name_type((A))  /* the value of \&{linejoin} */
9044 @:mp_linejoin_}{\&{linejoin} primitive@>
9045 @d miterlim_val(A) mp->mem[(A)+7].sc  /* the value of \&{miterlimit} */
9046 @:mp_miterlimit_}{\&{miterlimit} primitive@>
9047 @d obj_color_part(A) mp->mem[(A)+3-red_part].sc
9048   /* interpret an object pointer that has been offset by |red_part..blue_part| */
9049 @d pre_script(A) mp->mem[(A)+8].hh.lh
9050 @d post_script(A) mp->mem[(A)+8].hh.rh
9051 @d fill_node_size 9
9052
9053 @ @<Graphical object codes@>=
9054 mp_fill_code=1,
9055
9056 @ @c 
9057 pointer mp_new_fill_node (MP mp,pointer p) {
9058   /* make a fill node for cyclic path |p| and color black */
9059   pointer t; /* the new node */
9060   t=mp_get_node(mp, fill_node_size);
9061   type(t)=mp_fill_code;
9062   path_p(t)=p;
9063   pen_p(t)=null; /* |null| means don't use a pen */
9064   red_val(t)=0;
9065   green_val(t)=0;
9066   blue_val(t)=0;
9067   black_val(t)=0;
9068   color_model(t)=mp_uninitialized_model;
9069   pre_script(t)=null;
9070   post_script(t)=null;
9071   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9072   return t;
9073 }
9074
9075 @ @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>=
9076 if ( mp->internal[mp_linejoin]>unity ) ljoin_val(t)=2;
9077 else if ( mp->internal[mp_linejoin]>0 ) ljoin_val(t)=1;
9078 else ljoin_val(t)=0;
9079 if ( mp->internal[mp_miterlimit]<unity )
9080   miterlim_val(t)=unity;
9081 else
9082   miterlim_val(t)=mp->internal[mp_miterlimit]
9083
9084 @ A stroked path is represented by an eight-word node that is like a filled
9085 contour node except that it contains the current \&{linecap} value, a scale
9086 factor for the dash pattern, and a pointer that is non-null if the stroke
9087 is to be dashed.  The purpose of the scale factor is to allow a picture to
9088 be transformed without touching the picture that |dash_p| points to.
9089
9090 @d dash_p(A) link((A)+9)
9091   /* a pointer to the edge structure that gives the dash pattern */
9092 @d lcap_val(A) type((A)+9)
9093   /* the value of \&{linecap} */
9094 @:mp_linecap_}{\&{linecap} primitive@>
9095 @d dash_scale(A) mp->mem[(A)+10].sc /* dash lengths are scaled by this factor */
9096 @d stroked_node_size 11
9097
9098 @ @<Graphical object codes@>=
9099 mp_stroked_code=2,
9100
9101 @ @c 
9102 pointer mp_new_stroked_node (MP mp,pointer p) {
9103   /* make a stroked node for path |p| with |pen_p(p)| temporarily |null| */
9104   pointer t; /* the new node */
9105   t=mp_get_node(mp, stroked_node_size);
9106   type(t)=mp_stroked_code;
9107   path_p(t)=p; pen_p(t)=null;
9108   dash_p(t)=null;
9109   dash_scale(t)=unity;
9110   red_val(t)=0;
9111   green_val(t)=0;
9112   blue_val(t)=0;
9113   black_val(t)=0;
9114   color_model(t)=mp_uninitialized_model;
9115   pre_script(t)=null;
9116   post_script(t)=null;
9117   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9118   if ( mp->internal[mp_linecap]>unity ) lcap_val(t)=2;
9119   else if ( mp->internal[mp_linecap]>0 ) lcap_val(t)=1;
9120   else lcap_val(t)=0;
9121   return t;
9122 }
9123
9124 @ When a dashed line is computed in a transformed coordinate system, the dash
9125 lengths get scaled like the pen shape and we need to compensate for this.  Since
9126 there is no unique scale factor for an arbitrary transformation, we use the
9127 the square root of the determinant.  The properties of the determinant make it
9128 easier to maintain the |dash_scale|.  The computation is fairly straight-forward
9129 except for the initialization of the scale factor |s|.  The factor of 64 is
9130 needed because |square_rt| scales its result by $2^8$ while we need $2^{14}$
9131 to counteract the effect of |take_fraction|.
9132
9133 @<Declare subroutines needed by |print_edges|@>=
9134 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) {
9135   scaled maxabs; /* $max(|a|,|b|,|c|,|d|)$ */
9136   integer s; /* amount by which the result of |square_rt| needs to be scaled */
9137   @<Initialize |maxabs|@>;
9138   s=64;
9139   while ( (maxabs<fraction_one) && (s>1) ){ 
9140     a+=a; b+=b; c+=c; d+=d;
9141     maxabs+=maxabs; s=halfp(s);
9142   }
9143   return s*mp_square_rt(mp, abs(mp_take_fraction(mp, a,d)-mp_take_fraction(mp, b,c)));
9144 }
9145 @#
9146 scaled mp_get_pen_scale (MP mp,pointer p) { 
9147   return mp_sqrt_det(mp, 
9148     left_x(p)-x_coord(p), right_x(p)-x_coord(p),
9149     left_y(p)-y_coord(p), right_y(p)-y_coord(p));
9150 }
9151
9152 @ @<Internal library ...@>=
9153 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) ;
9154
9155
9156 @ @<Initialize |maxabs|@>=
9157 maxabs=abs(a);
9158 if ( abs(b)>maxabs ) maxabs=abs(b);
9159 if ( abs(c)>maxabs ) maxabs=abs(c);
9160 if ( abs(d)>maxabs ) maxabs=abs(d)
9161
9162 @ When a picture contains text, this is represented by a fourteen-word node
9163 where the color information and |type| and |link| fields are augmented by
9164 additional fields that describe the text and  how it is transformed.
9165 The |path_p| and |pen_p| pointers are replaced by a number that identifies
9166 the font and a string number that gives the text to be displayed.
9167 The |width|, |height|, and |depth| fields
9168 give the dimensions of the text at its design size, and the remaining six
9169 words give a transformation to be applied to the text.  The |new_text_node|
9170 function initializes everything to default values so that the text comes out
9171 black with its reference point at the origin.
9172
9173 @d text_p(A) link((A)+1)  /* a string pointer for the text to display */
9174 @d font_n(A) info((A)+1)  /* the font number */
9175 @d width_val(A) mp->mem[(A)+7].sc  /* unscaled width of the text */
9176 @d height_val(A) mp->mem[(A)+9].sc  /* unscaled height of the text */
9177 @d depth_val(A) mp->mem[(A)+10].sc  /* unscaled depth of the text */
9178 @d text_tx_loc(A) ((A)+11)
9179   /* the first of six locations for transformation parameters */
9180 @d tx_val(A) mp->mem[(A)+11].sc  /* $x$ shift amount */
9181 @d ty_val(A) mp->mem[(A)+12].sc  /* $y$ shift amount */
9182 @d txx_val(A) mp->mem[(A)+13].sc  /* |txx| transformation parameter */
9183 @d txy_val(A) mp->mem[(A)+14].sc  /* |txy| transformation parameter */
9184 @d tyx_val(A) mp->mem[(A)+15].sc  /* |tyx| transformation parameter */
9185 @d tyy_val(A) mp->mem[(A)+16].sc  /* |tyy| transformation parameter */
9186 @d text_trans_part(A) mp->mem[(A)+11-x_part].sc
9187     /* interpret a text node pointer that has been offset by |x_part..yy_part| */
9188 @d text_node_size 17
9189
9190 @ @<Graphical object codes@>=
9191 mp_text_code=3,
9192
9193 @ @c @<Declare text measuring subroutines@>;
9194 pointer mp_new_text_node (MP mp,char *f,str_number s) {
9195   /* make a text node for font |f| and text string |s| */
9196   pointer t; /* the new node */
9197   t=mp_get_node(mp, text_node_size);
9198   type(t)=mp_text_code;
9199   text_p(t)=s;
9200   font_n(t)=mp_find_font(mp, f); /* this identifies the font */
9201   red_val(t)=0;
9202   green_val(t)=0;
9203   blue_val(t)=0;
9204   black_val(t)=0;
9205   color_model(t)=mp_uninitialized_model;
9206   pre_script(t)=null;
9207   post_script(t)=null;
9208   tx_val(t)=0; ty_val(t)=0;
9209   txx_val(t)=unity; txy_val(t)=0;
9210   tyx_val(t)=0; tyy_val(t)=unity;
9211   mp_set_text_box(mp, t); /* this finds the bounding box */
9212   return t;
9213 }
9214
9215 @ The last two types of graphical objects that can occur in an edge structure
9216 are clipping paths and \&{setbounds} paths.  These are slightly more difficult
9217 @:set_bounds_}{\&{setbounds} primitive@>
9218 to implement because we must keep track of exactly what is being clipped or
9219 bounded when pictures get merged together.  For this reason, each clipping or
9220 \&{setbounds} operation is represented by a pair of nodes:  first comes a
9221 two-word node whose |path_p| gives the relevant path, then there is the list
9222 of objects to clip or bound followed by a two-word node whose second word is
9223 unused.
9224
9225 Using at least two words for each graphical object node allows them all to be
9226 allocated and deallocated similarly with a global array |gr_object_size| to
9227 give the size in words for each object type.
9228
9229 @d start_clip_size 2
9230 @d start_bounds_size 2
9231 @d stop_clip_size 2 /* the second word is not used here */
9232 @d stop_bounds_size 2 /* the second word is not used here */
9233 @#
9234 @d stop_type(A) ((A)+2)
9235   /* matching |type| for |start_clip_code| or |start_bounds_code| */
9236 @d has_color(A) (type((A))<mp_start_clip_code)
9237   /* does a graphical object have color fields? */
9238 @d has_pen(A) (type((A))<mp_text_code)
9239   /* does a graphical object have a |pen_p| field? */
9240 @d is_start_or_stop(A) (type((A))>=mp_start_clip_code)
9241 @d is_stop(A) (type((A))>=mp_stop_clip_code)
9242
9243 @ @<Graphical object codes@>=
9244 mp_start_clip_code=4, /* |type| of a node that starts clipping */
9245 mp_start_bounds_code=5, /* |type| of a node that gives a \&{setbounds} path */
9246 mp_stop_clip_code=6, /* |type| of a node that stops clipping */
9247 mp_stop_bounds_code=7, /* |type| of a node that stops \&{setbounds} */
9248
9249 @ @c 
9250 pointer mp_new_bounds_node (MP mp,pointer p, small_number  c) {
9251   /* make a node of type |c| where |p| is the clipping or \&{setbounds} path */
9252   pointer t; /* the new node */
9253   t=mp_get_node(mp, mp->gr_object_size[c]);
9254   type(t)=c;
9255   path_p(t)=p;
9256   return t;
9257 };
9258
9259 @ We need an array to keep track of the sizes of graphical objects.
9260
9261 @<Glob...@>=
9262 small_number gr_object_size[mp_stop_bounds_code+1];
9263
9264 @ @<Set init...@>=
9265 mp->gr_object_size[mp_fill_code]=fill_node_size;
9266 mp->gr_object_size[mp_stroked_code]=stroked_node_size;
9267 mp->gr_object_size[mp_text_code]=text_node_size;
9268 mp->gr_object_size[mp_start_clip_code]=start_clip_size;
9269 mp->gr_object_size[mp_stop_clip_code]=stop_clip_size;
9270 mp->gr_object_size[mp_start_bounds_code]=start_bounds_size;
9271 mp->gr_object_size[mp_stop_bounds_code]=stop_bounds_size;
9272
9273 @ All the essential information in an edge structure is encoded as a linked list
9274 of graphical objects as we have just seen, but it is helpful to add some
9275 redundant information.  A single edge structure might be used as a dash pattern
9276 many times, and it would be nice to avoid scanning the same structure
9277 repeatedly.  Thus, an edge structure known to be a suitable dash pattern
9278 has a header that gives a list of dashes in a sorted order designed for rapid
9279 translation into \ps.
9280
9281 Each dash is represented by a three-word node containing the initial and final
9282 $x$~coordinates as well as the usual |link| field.  The |link| fields points to
9283 the dash node with the next higher $x$-coordinates and the final link points
9284 to a special location called |null_dash|.  (There should be no overlap between
9285 dashes).  Since the $y$~coordinate of the dash pattern is needed to determine
9286 the period of repetition, this needs to be stored in the edge header along
9287 with a pointer to the list of dash nodes.
9288
9289 @d start_x(A) mp->mem[(A)+1].sc  /* the starting $x$~coordinate in a dash node */
9290 @d stop_x(A) mp->mem[(A)+2].sc  /* the ending $x$~coordinate in a dash node */
9291 @d dash_node_size 3
9292 @d dash_list link
9293   /* in an edge header this points to the first dash node */
9294 @d dash_y(A) mp->mem[(A)+1].sc  /* $y$ value for the dash list in an edge header */
9295
9296 @ It is also convenient for an edge header to contain the bounding
9297 box information needed by the \&{llcorner} and \&{urcorner} operators
9298 so that this does not have to be recomputed unnecessarily.  This is done by
9299 adding fields for the $x$~and $y$ extremes as well as a pointer that indicates
9300 how far the bounding box computation has gotten.  Thus if the user asks for
9301 the bounding box and then adds some more text to the picture before asking
9302 for more bounding box information, the second computation need only look at
9303 the additional text.
9304
9305 When the bounding box has not been computed, the |bblast| pointer points
9306 to a dummy link at the head of the graphical object list while the |minx_val|
9307 and |miny_val| fields contain |el_gordo| and the |maxx_val| and |maxy_val|
9308 fields contain |-el_gordo|.
9309
9310 Since the bounding box of pictures containing objects of type
9311 |mp_start_bounds_code| depends on the value of \&{truecorners}, the bounding box
9312 @:mp_true_corners_}{\&{truecorners} primitive@>
9313 data might not be valid for all values of this parameter.  Hence, the |bbtype|
9314 field is needed to keep track of this.
9315
9316 @d minx_val(A) mp->mem[(A)+2].sc
9317 @d miny_val(A) mp->mem[(A)+3].sc
9318 @d maxx_val(A) mp->mem[(A)+4].sc
9319 @d maxy_val(A) mp->mem[(A)+5].sc
9320 @d bblast(A) link((A)+6)  /* last item considered in bounding box computation */
9321 @d bbtype(A) info((A)+6)  /* tells how bounding box data depends on \&{truecorners} */
9322 @d dummy_loc(A) ((A)+7)  /* where the object list begins in an edge header */
9323 @d no_bounds 0
9324   /* |bbtype| value when bounding box data is valid for all \&{truecorners} values */
9325 @d bounds_set 1
9326   /* |bbtype| value when bounding box data is for \&{truecorners}${}\le 0$ */
9327 @d bounds_unset 2
9328   /* |bbtype| value when bounding box data is for \&{truecorners}${}>0$ */
9329
9330 @c 
9331 void mp_init_bbox (MP mp,pointer h) {
9332   /* Initialize the bounding box information in edge structure |h| */
9333   bblast(h)=dummy_loc(h);
9334   bbtype(h)=no_bounds;
9335   minx_val(h)=el_gordo;
9336   miny_val(h)=el_gordo;
9337   maxx_val(h)=-el_gordo;
9338   maxy_val(h)=-el_gordo;
9339 }
9340
9341 @ The only other entries in an edge header are a reference count in the first
9342 word and a pointer to the tail of the object list in the last word.
9343
9344 @d obj_tail(A) info((A)+7)  /* points to the last entry in the object list */
9345 @d edge_header_size 8
9346
9347 @c 
9348 void mp_init_edges (MP mp,pointer h) {
9349   /* initialize an edge header to null values */
9350   dash_list(h)=null_dash;
9351   obj_tail(h)=dummy_loc(h);
9352   link(dummy_loc(h))=null;
9353   ref_count(h)=null;
9354   mp_init_bbox(mp, h);
9355 }
9356
9357 @ Here is how edge structures are deleted.  The process can be recursive because
9358 of the need to dereference edge structures that are used as dash patterns.
9359 @^recursion@>
9360
9361 @d add_edge_ref(A) incr(ref_count(A))
9362 @d delete_edge_ref(A) { 
9363    if ( ref_count((A))==null ) 
9364      mp_toss_edges(mp, A);
9365    else 
9366      decr(ref_count(A)); 
9367    }
9368
9369 @<Declare the recycling subroutines@>=
9370 void mp_flush_dash_list (MP mp,pointer h);
9371 pointer mp_toss_gr_object (MP mp,pointer p) ;
9372 void mp_toss_edges (MP mp,pointer h) ;
9373
9374 @ @c void mp_toss_edges (MP mp,pointer h) {
9375   pointer p,q;  /* pointers that scan the list being recycled */
9376   pointer r; /* an edge structure that object |p| refers to */
9377   mp_flush_dash_list(mp, h);
9378   q=link(dummy_loc(h));
9379   while ( (q!=null) ) { 
9380     p=q; q=link(q);
9381     r=mp_toss_gr_object(mp, p);
9382     if ( r!=null ) delete_edge_ref(r);
9383   }
9384   mp_free_node(mp, h,edge_header_size);
9385 }
9386 void mp_flush_dash_list (MP mp,pointer h) {
9387   pointer p,q;  /* pointers that scan the list being recycled */
9388   q=dash_list(h);
9389   while ( q!=null_dash ) { 
9390     p=q; q=link(q);
9391     mp_free_node(mp, p,dash_node_size);
9392   }
9393   dash_list(h)=null_dash;
9394 }
9395 pointer mp_toss_gr_object (MP mp,pointer p) {
9396   /* returns an edge structure that needs to be dereferenced */
9397   pointer e; /* the edge structure to return */
9398   e=null;
9399   @<Prepare to recycle graphical object |p|@>;
9400   mp_free_node(mp, p,mp->gr_object_size[type(p)]);
9401   return e;
9402 }
9403
9404 @ @<Prepare to recycle graphical object |p|@>=
9405 switch (type(p)) {
9406 case mp_fill_code: 
9407   mp_toss_knot_list(mp, path_p(p));
9408   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9409   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9410   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9411   break;
9412 case mp_stroked_code: 
9413   mp_toss_knot_list(mp, path_p(p));
9414   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9415   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9416   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9417   e=dash_p(p);
9418   break;
9419 case mp_text_code: 
9420   delete_str_ref(text_p(p));
9421   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9422   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9423   break;
9424 case mp_start_clip_code:
9425 case mp_start_bounds_code: 
9426   mp_toss_knot_list(mp, path_p(p));
9427   break;
9428 case mp_stop_clip_code:
9429 case mp_stop_bounds_code: 
9430   break;
9431 } /* there are no other cases */
9432
9433 @ If we use |add_edge_ref| to ``copy'' edge structures, the real copying needs
9434 to be done before making a significant change to an edge structure.  Much of
9435 the work is done in a separate routine |copy_objects| that copies a list of
9436 graphical objects into a new edge header.
9437
9438 @c @<Declare a function called |copy_objects|@>;
9439 pointer mp_private_edges (MP mp,pointer h) {
9440   /* make a private copy of the edge structure headed by |h| */
9441   pointer hh;  /* the edge header for the new copy */
9442   pointer p,pp;  /* pointers for copying the dash list */
9443   if ( ref_count(h)==null ) {
9444     return h;
9445   } else { 
9446     decr(ref_count(h));
9447     hh=mp_copy_objects(mp, link(dummy_loc(h)),null);
9448     @<Copy the dash list from |h| to |hh|@>;
9449     @<Copy the bounding box information from |h| to |hh| and make |bblast(hh)|
9450       point into the new object list@>;
9451     return hh;
9452   }
9453 }
9454
9455 @ Here we use the fact that |dash_list(hh)=link(hh)|.
9456 @^data structure assumptions@>
9457
9458 @<Copy the dash list from |h| to |hh|@>=
9459 pp=hh; p=dash_list(h);
9460 while ( (p!=null_dash) ) { 
9461   link(pp)=mp_get_node(mp, dash_node_size);
9462   pp=link(pp);
9463   start_x(pp)=start_x(p);
9464   stop_x(pp)=stop_x(p);
9465   p=link(p);
9466 }
9467 link(pp)=null_dash;
9468 dash_y(hh)=dash_y(h)
9469
9470
9471 @ |h| is an edge structure
9472
9473 @d gr_start_x(A)    (A)->start_x_field
9474 @d gr_stop_x(A)     (A)->stop_x_field
9475 @d gr_dash_link(A)  (A)->next_field
9476
9477 @d gr_dash_list(A)  (A)->list_field
9478 @d gr_dash_y(A)     (A)->y_field
9479
9480 @c
9481 struct mp_dash_list *mp_export_dashes (MP mp, pointer h) {
9482   struct mp_dash_list *dl;
9483   struct mp_dash_item *dh, *di;
9484   pointer p;
9485   if (h==null ||  dash_list(h)==null_dash) 
9486         return NULL;
9487   p = dash_list(h);
9488   dl = mp_xmalloc(mp,1,sizeof(struct mp_dash_list));
9489   gr_dash_list(dl) = NULL;
9490   gr_dash_y(dl) = dash_y(h);
9491   dh = NULL;
9492   while (p != null_dash) { 
9493     di=mp_xmalloc(mp,1,sizeof(struct mp_dash_item));
9494     gr_dash_link(di) = NULL;
9495     gr_start_x(di) = start_x(p);
9496     gr_stop_x(di) = stop_x(p);
9497     if (dh==NULL) {
9498       gr_dash_list(dl) = di;
9499     } else {
9500       gr_dash_link(dh) = di;
9501     }
9502     dh = di;
9503     p=link(p);
9504   }
9505   return dl;
9506 }
9507
9508
9509 @ @<Copy the bounding box information from |h| to |hh|...@>=
9510 minx_val(hh)=minx_val(h);
9511 miny_val(hh)=miny_val(h);
9512 maxx_val(hh)=maxx_val(h);
9513 maxy_val(hh)=maxy_val(h);
9514 bbtype(hh)=bbtype(h);
9515 p=dummy_loc(h); pp=dummy_loc(hh);
9516 while ((p!=bblast(h)) ) { 
9517   if ( p==null ) mp_confusion(mp, "bblast");
9518 @:this can't happen bblast}{\quad bblast@>
9519   p=link(p); pp=link(pp);
9520 }
9521 bblast(hh)=pp
9522
9523 @ Here is the promised routine for copying graphical objects into a new edge
9524 structure.  It starts copying at object~|p| and stops just before object~|q|.
9525 If |q| is null, it copies the entire sublist headed at |p|.  The resulting edge
9526 structure requires further initialization by |init_bbox|.
9527
9528 @<Declare a function called |copy_objects|@>=
9529 pointer mp_copy_objects (MP mp, pointer p, pointer q) {
9530   pointer hh;  /* the new edge header */
9531   pointer pp;  /* the last newly copied object */
9532   small_number k;  /* temporary register */
9533   hh=mp_get_node(mp, edge_header_size);
9534   dash_list(hh)=null_dash;
9535   ref_count(hh)=null;
9536   pp=dummy_loc(hh);
9537   while ( (p!=q) ) {
9538     @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>;
9539   }
9540   obj_tail(hh)=pp;
9541   link(pp)=null;
9542   return hh;
9543 }
9544
9545 @ @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>=
9546 { k=mp->gr_object_size[type(p)];
9547   link(pp)=mp_get_node(mp, k);
9548   pp=link(pp);
9549   while ( (k>0) ) { decr(k); mp->mem[pp+k]=mp->mem[p+k];  };
9550   @<Fix anything in graphical object |pp| that should differ from the
9551     corresponding field in |p|@>;
9552   p=link(p);
9553 }
9554
9555 @ @<Fix anything in graphical object |pp| that should differ from the...@>=
9556 switch (type(p)) {
9557 case mp_start_clip_code:
9558 case mp_start_bounds_code: 
9559   path_p(pp)=mp_copy_path(mp, path_p(p));
9560   break;
9561 case mp_fill_code: 
9562   path_p(pp)=mp_copy_path(mp, path_p(p));
9563   if ( pen_p(p)!=null ) pen_p(pp)=copy_pen(pen_p(p));
9564   break;
9565 case mp_stroked_code: 
9566   path_p(pp)=mp_copy_path(mp, path_p(p));
9567   pen_p(pp)=copy_pen(pen_p(p));
9568   if ( dash_p(p)!=null ) add_edge_ref(dash_p(pp));
9569   break;
9570 case mp_text_code: 
9571   add_str_ref(text_p(pp));
9572   break;
9573 case mp_stop_clip_code:
9574 case mp_stop_bounds_code: 
9575   break;
9576 }  /* there are no other cases */
9577
9578 @ Here is one way to find an acceptable value for the second argument to
9579 |copy_objects|.  Given a non-null graphical object list, |skip_1component|
9580 skips past one picture component, where a ``picture component'' is a single
9581 graphical object, or a start bounds or start clip object and everything up
9582 through the matching stop bounds or stop clip object.  The macro version avoids
9583 procedure call overhead and error handling: |skip_component(p)(e)| advances |p|
9584 unless |p| points to a stop bounds or stop clip node, in which case it executes
9585 |e| instead.
9586
9587 @d skip_component(A)
9588     if ( ! is_start_or_stop((A)) ) (A)=link((A));
9589     else if ( ! is_stop((A)) ) (A)=mp_skip_1component(mp, (A));
9590     else 
9591
9592 @c 
9593 pointer mp_skip_1component (MP mp,pointer p) {
9594   integer lev; /* current nesting level */
9595   lev=0;
9596   do {  
9597    if ( is_start_or_stop(p) ) {
9598      if ( is_stop(p) ) decr(lev);  else incr(lev);
9599    }
9600    p=link(p);
9601   } while (lev!=0);
9602   return p;
9603 }
9604
9605 @ Here is a diagnostic routine for printing an edge structure in symbolic form.
9606
9607 @<Declare subroutines for printing expressions@>=
9608 @<Declare subroutines needed by |print_edges|@>;
9609 void mp_print_edges (MP mp,pointer h, char *s, boolean nuline) {
9610   pointer p;  /* a graphical object to be printed */
9611   pointer hh,pp;  /* temporary pointers */
9612   scaled scf;  /* a scale factor for the dash pattern */
9613   boolean ok_to_dash;  /* |false| for polygonal pen strokes */
9614   mp_print_diagnostic(mp, "Edge structure",s,nuline);
9615   p=dummy_loc(h);
9616   while ( link(p)!=null ) { 
9617     p=link(p);
9618     mp_print_ln(mp);
9619     switch (type(p)) {
9620       @<Cases for printing graphical object node |p|@>;
9621     default: 
9622           mp_print(mp, "[unknown object type!]");
9623           break;
9624     }
9625   }
9626   mp_print_nl(mp, "End edges");
9627   if ( p!=obj_tail(h) ) mp_print(mp, "?");
9628 @.End edges?@>
9629   mp_end_diagnostic(mp, true);
9630 }
9631
9632 @ @<Cases for printing graphical object node |p|@>=
9633 case mp_fill_code: 
9634   mp_print(mp, "Filled contour ");
9635   mp_print_obj_color(mp, p);
9636   mp_print_char(mp, ':'); mp_print_ln(mp);
9637   mp_pr_path(mp, path_p(p)); mp_print_ln(mp);
9638   if ( (pen_p(p)!=null) ) {
9639     @<Print join type for graphical object |p|@>;
9640     mp_print(mp, " with pen"); mp_print_ln(mp);
9641     mp_pr_pen(mp, pen_p(p));
9642   }
9643   break;
9644
9645 @ @<Print join type for graphical object |p|@>=
9646 switch (ljoin_val(p)) {
9647 case 0:
9648   mp_print(mp, "mitered joins limited ");
9649   mp_print_scaled(mp, miterlim_val(p));
9650   break;
9651 case 1:
9652   mp_print(mp, "round joins");
9653   break;
9654 case 2:
9655   mp_print(mp, "beveled joins");
9656   break;
9657 default: 
9658   mp_print(mp, "?? joins");
9659 @.??@>
9660   break;
9661 }
9662
9663 @ For stroked nodes, we need to print |lcap_val(p)| as well.
9664
9665 @<Print join and cap types for stroked node |p|@>=
9666 switch (lcap_val(p)) {
9667 case 0:mp_print(mp, "butt"); break;
9668 case 1:mp_print(mp, "round"); break;
9669 case 2:mp_print(mp, "square"); break;
9670 default: mp_print(mp, "??"); break;
9671 @.??@>
9672 }
9673 mp_print(mp, " ends, ");
9674 @<Print join type for graphical object |p|@>
9675
9676 @ Here is a routine that prints the color of a graphical object if it isn't
9677 black (the default color).
9678
9679 @<Declare subroutines needed by |print_edges|@>=
9680 @<Declare a procedure called |print_compact_node|@>;
9681 void mp_print_obj_color (MP mp,pointer p) { 
9682   if ( color_model(p)==mp_grey_model ) {
9683     if ( grey_val(p)>0 ) { 
9684       mp_print(mp, "greyed ");
9685       mp_print_compact_node(mp, obj_grey_loc(p),1);
9686     };
9687   } else if ( color_model(p)==mp_cmyk_model ) {
9688     if ( (cyan_val(p)>0) || (magenta_val(p)>0) || 
9689          (yellow_val(p)>0) || (black_val(p)>0) ) { 
9690       mp_print(mp, "processcolored ");
9691       mp_print_compact_node(mp, obj_cyan_loc(p),4);
9692     };
9693   } else if ( color_model(p)==mp_rgb_model ) {
9694     if ( (red_val(p)>0) || (green_val(p)>0) || (blue_val(p)>0) ) { 
9695       mp_print(mp, "colored "); 
9696       mp_print_compact_node(mp, obj_red_loc(p),3);
9697     };
9698   }
9699 }
9700
9701 @ We also need a procedure for printing consecutive scaled values as if they
9702 were a known big node.
9703
9704 @<Declare a procedure called |print_compact_node|@>=
9705 void mp_print_compact_node (MP mp,pointer p, small_number k) {
9706   pointer q;  /* last location to print */
9707   q=p+k-1;
9708   mp_print_char(mp, '(');
9709   while ( p<=q ){ 
9710     mp_print_scaled(mp, mp->mem[p].sc);
9711     if ( p<q ) mp_print_char(mp, ',');
9712     incr(p);
9713   }
9714   mp_print_char(mp, ')');
9715 }
9716
9717 @ @<Cases for printing graphical object node |p|@>=
9718 case mp_stroked_code: 
9719   mp_print(mp, "Filled pen stroke ");
9720   mp_print_obj_color(mp, p);
9721   mp_print_char(mp, ':'); mp_print_ln(mp);
9722   mp_pr_path(mp, path_p(p));
9723   if ( dash_p(p)!=null ) { 
9724     mp_print_nl(mp, "dashed (");
9725     @<Finish printing the dash pattern that |p| refers to@>;
9726   }
9727   mp_print_ln(mp);
9728   @<Print join and cap types for stroked node |p|@>;
9729   mp_print(mp, " with pen"); mp_print_ln(mp);
9730   if ( pen_p(p)==null ) mp_print(mp, "???"); /* shouldn't happen */
9731 @.???@>
9732   else mp_pr_pen(mp, pen_p(p));
9733   break;
9734
9735 @ Normally, the  |dash_list| field in an edge header is set to |null_dash|
9736 when it is not known to define a suitable dash pattern.  This is disallowed
9737 here because the |dash_p| field should never point to such an edge header.
9738 Note that memory is allocated for |start_x(null_dash)| and we are free to
9739 give it any convenient value.
9740
9741 @<Finish printing the dash pattern that |p| refers to@>=
9742 ok_to_dash=pen_is_elliptical(pen_p(p));
9743 if ( ! ok_to_dash ) scf=unity; else scf=dash_scale(p);
9744 hh=dash_p(p);
9745 pp=dash_list(hh);
9746 if ( (pp==null_dash) || (dash_y(hh)<0) ) {
9747   mp_print(mp, " ??");
9748 } else { start_x(null_dash)=start_x(pp)+dash_y(hh);
9749   while ( pp!=null_dash ) { 
9750     mp_print(mp, "on ");
9751     mp_print_scaled(mp, mp_take_scaled(mp, stop_x(pp)-start_x(pp),scf));
9752     mp_print(mp, " off ");
9753     mp_print_scaled(mp, mp_take_scaled(mp, start_x(link(pp))-stop_x(pp),scf));
9754     pp = link(pp);
9755     if ( pp!=null_dash ) mp_print_char(mp, ' ');
9756   }
9757   mp_print(mp, ") shifted ");
9758   mp_print_scaled(mp, -mp_take_scaled(mp, mp_dash_offset(mp, hh),scf));
9759   if ( ! ok_to_dash || (dash_y(hh)==0) ) mp_print(mp, " (this will be ignored)");
9760 }
9761
9762 @ @<Declare subroutines needed by |print_edges|@>=
9763 scaled mp_dash_offset (MP mp,pointer h) {
9764   scaled x;  /* the answer */
9765   if (dash_list(h)==null_dash || dash_y(h)<0) mp_confusion(mp, "dash0");
9766 @:this can't happen dash0}{\quad dash0@>
9767   if ( dash_y(h)==0 ) {
9768     x=0; 
9769   } else { 
9770     x=-(start_x(dash_list(h)) % dash_y(h));
9771     if ( x<0 ) x=x+dash_y(h);
9772   }
9773   return x;
9774 }
9775
9776 @ @<Cases for printing graphical object node |p|@>=
9777 case mp_text_code: 
9778   mp_print_char(mp, '"'); mp_print_str(mp,text_p(p));
9779   mp_print(mp, "\" infont \""); mp_print(mp, mp->font_name[font_n(p)]);
9780   mp_print_char(mp, '"'); mp_print_ln(mp);
9781   mp_print_obj_color(mp, p);
9782   mp_print(mp, "transformed ");
9783   mp_print_compact_node(mp, text_tx_loc(p),6);
9784   break;
9785
9786 @ @<Cases for printing graphical object node |p|@>=
9787 case mp_start_clip_code: 
9788   mp_print(mp, "clipping path:");
9789   mp_print_ln(mp);
9790   mp_pr_path(mp, path_p(p));
9791   break;
9792 case mp_stop_clip_code: 
9793   mp_print(mp, "stop clipping");
9794   break;
9795
9796 @ @<Cases for printing graphical object node |p|@>=
9797 case mp_start_bounds_code: 
9798   mp_print(mp, "setbounds path:");
9799   mp_print_ln(mp);
9800   mp_pr_path(mp, path_p(p));
9801   break;
9802 case mp_stop_bounds_code: 
9803   mp_print(mp, "end of setbounds");
9804   break;
9805
9806 @ To initialize the |dash_list| field in an edge header~|h|, we need a
9807 subroutine that scans an edge structure and tries to interpret it as a dash
9808 pattern.  This can only be done when there are no filled regions or clipping
9809 paths and all the pen strokes have the same color.  The first step is to let
9810 $y_0$ be the initial $y$~coordinate of the first pen stroke.  Then we implicitly
9811 project all the pen stroke paths onto the line $y=y_0$ and require that there
9812 be no retracing.  If the resulting paths cover a range of $x$~coordinates of
9813 length $\Delta x$, we set |dash_y(h)| to the length of the dash pattern by
9814 finding the maximum of $\Delta x$ and the absolute value of~$y_0$.
9815
9816 @c @<Declare a procedure called |x_retrace_error|@>;
9817 pointer mp_make_dashes (MP mp,pointer h) { /* returns |h| or |null| */
9818   pointer p;  /* this scans the stroked nodes in the object list */
9819   pointer p0;  /* if not |null| this points to the first stroked node */
9820   pointer pp,qq,rr;  /* pointers into |path_p(p)| */
9821   pointer d,dd;  /* pointers used to create the dash list */
9822   @<Other local variables in |make_dashes|@>;
9823   scaled y0=0;  /* the initial $y$ coordinate */
9824   if ( dash_list(h)!=null_dash ) 
9825         return h;
9826   p0=null;
9827   p=link(dummy_loc(h));
9828   while ( p!=null ) { 
9829     if ( type(p)!=mp_stroked_code ) {
9830       @<Compain that the edge structure contains a node of the wrong type
9831         and |goto not_found|@>;
9832     }
9833     pp=path_p(p);
9834     if ( p0==null ){ p0=p; y0=y_coord(pp);  };
9835     @<Make |d| point to a new dash node created from stroke |p| and path |pp|
9836       or |goto not_found| if there is an error@>;
9837     @<Insert |d| into the dash list and |goto not_found| if there is an error@>;
9838     p=link(p);
9839   }
9840   if ( dash_list(h)==null_dash ) 
9841     goto NOT_FOUND; /* No error message */
9842   @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>;
9843   @<Set |dash_y(h)| and merge the first and last dashes if necessary@>;
9844   return h;
9845 NOT_FOUND: 
9846   @<Flush the dash list, recycle |h| and return |null|@>;
9847 };
9848
9849 @ @<Compain that the edge structure contains a node of the wrong type...@>=
9850
9851 print_err("Picture is too complicated to use as a dash pattern");
9852 help3("When you say `dashed p', picture p should not contain any")
9853   ("text, filled regions, or clipping paths.  This time it did")
9854   ("so I'll just make it a solid line instead.");
9855 mp_put_get_error(mp);
9856 goto NOT_FOUND;
9857 }
9858
9859 @ A similar error occurs when monotonicity fails.
9860
9861 @<Declare a procedure called |x_retrace_error|@>=
9862 void mp_x_retrace_error (MP mp) { 
9863 print_err("Picture is too complicated to use as a dash pattern");
9864 help3("When you say `dashed p', every path in p should be monotone")
9865   ("in x and there must be no overlapping.  This failed")
9866   ("so I'll just make it a solid line instead.");
9867 mp_put_get_error(mp);
9868 }
9869
9870 @ We stash |p| in |info(d)| if |dash_p(p)<>0| so that subsequent processing can
9871 handle the case where the pen stroke |p| is itself dashed.
9872
9873 @<Make |d| point to a new dash node created from stroke |p| and path...@>=
9874 @<Make sure |p| and |p0| are the same color and |goto not_found| if there is
9875   an error@>;
9876 rr=pp;
9877 if ( link(pp)!=pp ) {
9878   do {  
9879     qq=rr; rr=link(rr);
9880     @<Check for retracing between knots |qq| and |rr| and |goto not_found|
9881       if there is a problem@>;
9882   } while (right_type(rr)!=mp_endpoint);
9883 }
9884 d=mp_get_node(mp, dash_node_size);
9885 if ( dash_p(p)==0 ) info(d)=0;  else info(d)=p;
9886 if ( x_coord(pp)<x_coord(rr) ) { 
9887   start_x(d)=x_coord(pp);
9888   stop_x(d)=x_coord(rr);
9889 } else { 
9890   start_x(d)=x_coord(rr);
9891   stop_x(d)=x_coord(pp);
9892 }
9893
9894 @ We also need to check for the case where the segment from |qq| to |rr| is
9895 monotone in $x$ but is reversed relative to the path from |pp| to |qq|.
9896
9897 @<Check for retracing between knots |qq| and |rr| and |goto not_found|...@>=
9898 x0=x_coord(qq);
9899 x1=right_x(qq);
9900 x2=left_x(rr);
9901 x3=x_coord(rr);
9902 if ( (x0>x1) || (x1>x2) || (x2>x3) ) {
9903   if ( (x0<x1) || (x1<x2) || (x2<x3) ) {
9904     if ( mp_ab_vs_cd(mp, x2-x1,x2-x1,x1-x0,x3-x2)>0 ) {
9905       mp_x_retrace_error(mp); goto NOT_FOUND;
9906     }
9907   }
9908 }
9909 if ( (x_coord(pp)>x0) || (x0>x3) ) {
9910   if ( (x_coord(pp)<x0) || (x0<x3) ) {
9911     mp_x_retrace_error(mp); goto NOT_FOUND;
9912   }
9913 }
9914
9915 @ @<Other local variables in |make_dashes|@>=
9916   scaled x0,x1,x2,x3;  /* $x$ coordinates of the segment from |qq| to |rr| */
9917
9918 @ @<Make sure |p| and |p0| are the same color and |goto not_found|...@>=
9919 if ( (red_val(p)!=red_val(p0)) || (black_val(p)!=black_val(p0)) ||
9920   (green_val(p)!=green_val(p0)) || (blue_val(p)!=blue_val(p0)) ) {
9921   print_err("Picture is too complicated to use as a dash pattern");
9922   help3("When you say `dashed p', everything in picture p should")
9923     ("be the same color.  I can\'t handle your color changes")
9924     ("so I'll just make it a solid line instead.");
9925   mp_put_get_error(mp);
9926   goto NOT_FOUND;
9927 }
9928
9929 @ @<Insert |d| into the dash list and |goto not_found| if there is an error@>=
9930 start_x(null_dash)=stop_x(d);
9931 dd=h; /* this makes |link(dd)=dash_list(h)| */
9932 while ( start_x(link(dd))<stop_x(d) )
9933   dd=link(dd);
9934 if ( dd!=h ) {
9935   if ( (stop_x(dd)>start_x(d)) )
9936     { mp_x_retrace_error(mp); goto NOT_FOUND;  };
9937 }
9938 link(d)=link(dd);
9939 link(dd)=d
9940
9941 @ @<Set |dash_y(h)| and merge the first and last dashes if necessary@>=
9942 d=dash_list(h);
9943 while ( (link(d)!=null_dash) )
9944   d=link(d);
9945 dd=dash_list(h);
9946 dash_y(h)=stop_x(d)-start_x(dd);
9947 if ( abs(y0)>dash_y(h) ) {
9948   dash_y(h)=abs(y0);
9949 } else if ( d!=dd ) { 
9950   dash_list(h)=link(dd);
9951   stop_x(d)=stop_x(dd)+dash_y(h);
9952   mp_free_node(mp, dd,dash_node_size);
9953 }
9954
9955 @ We get here when the argument is a null picture or when there is an error.
9956 Recovering from an error involves making |dash_list(h)| empty to indicate
9957 that |h| is not known to be a valid dash pattern.  We also dereference |h|
9958 since it is not being used for the return value.
9959
9960 @<Flush the dash list, recycle |h| and return |null|@>=
9961 mp_flush_dash_list(mp, h);
9962 delete_edge_ref(h);
9963 return null
9964
9965 @ Having carefully saved the dashed stroked nodes in the
9966 corresponding dash nodes, we must be prepared to break up these dashes into
9967 smaller dashes.
9968
9969 @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>=
9970 d=h;  /* now |link(d)=dash_list(h)| */
9971 while ( link(d)!=null_dash ) {
9972   ds=info(link(d));
9973   if ( ds==null ) { 
9974     d=link(d);
9975   } else {
9976     hh=dash_p(ds);
9977     hsf=dash_scale(ds);
9978     if ( (hh==null) ) mp_confusion(mp, "dash1");
9979 @:this can't happen dash0}{\quad dash1@>
9980     if ( dash_y(hh)==0 ) {
9981       d=link(d);
9982     } else { 
9983       if ( dash_list(hh)==null ) mp_confusion(mp, "dash1");
9984 @:this can't happen dash0}{\quad dash1@>
9985       @<Replace |link(d)| by a dashed version as determined by edge header
9986           |hh| and scale factor |ds|@>;
9987     }
9988   }
9989 }
9990
9991 @ @<Other local variables in |make_dashes|@>=
9992 pointer dln;  /* |link(d)| */
9993 pointer hh;  /* an edge header that tells how to break up |dln| */
9994 scaled hsf;  /* the dash pattern from |hh| gets scaled by this */
9995 pointer ds;  /* the stroked node from which |hh| and |hsf| are derived */
9996 scaled xoff;  /* added to $x$ values in |dash_list(hh)| to match |dln| */
9997
9998 @ @<Replace |link(d)| by a dashed version as determined by edge header...@>=
9999 dln=link(d);
10000 dd=dash_list(hh);
10001 xoff=start_x(dln)-mp_take_scaled(mp, hsf,start_x(dd))-
10002         mp_take_scaled(mp, hsf,mp_dash_offset(mp, hh));
10003 start_x(null_dash)=mp_take_scaled(mp, hsf,start_x(dd))
10004                    +mp_take_scaled(mp, hsf,dash_y(hh));
10005 stop_x(null_dash)=start_x(null_dash);
10006 @<Advance |dd| until finding the first dash that overlaps |dln| when
10007   offset by |xoff|@>;
10008 while ( start_x(dln)<=stop_x(dln) ) {
10009   @<If |dd| has `fallen off the end', back up to the beginning and fix |xoff|@>;
10010   @<Insert a dash between |d| and |dln| for the overlap with the offset version
10011     of |dd|@>;
10012   dd=link(dd);
10013   start_x(dln)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10014 }
10015 link(d)=link(dln);
10016 mp_free_node(mp, dln,dash_node_size)
10017
10018 @ The name of this module is a bit of a lie because we just find the
10019 first |dd| where |take_scaled (hsf, stop_x(dd))| is large enough to make an
10020 overlap possible.  It could be that the unoffset version of dash |dln| falls
10021 in the gap between |dd| and its predecessor.
10022
10023 @<Advance |dd| until finding the first dash that overlaps |dln| when...@>=
10024 while ( xoff+mp_take_scaled(mp, hsf,stop_x(dd))<start_x(dln) ) {
10025   dd=link(dd);
10026 }
10027
10028 @ @<If |dd| has `fallen off the end', back up to the beginning and fix...@>=
10029 if ( dd==null_dash ) { 
10030   dd=dash_list(hh);
10031   xoff=xoff+mp_take_scaled(mp, hsf,dash_y(hh));
10032 }
10033
10034 @ At this point we already know that
10035 |start_x(dln)<=xoff+take_scaled(hsf,stop_x(dd))|.
10036
10037 @<Insert a dash between |d| and |dln| for the overlap with the offset...@>=
10038 if ( (xoff+mp_take_scaled(mp, hsf,start_x(dd)))<=stop_x(dln) ) {
10039   link(d)=mp_get_node(mp, dash_node_size);
10040   d=link(d);
10041   link(d)=dln;
10042   if ( start_x(dln)>(xoff+mp_take_scaled(mp, hsf,start_x(dd))))
10043     start_x(d)=start_x(dln);
10044   else 
10045     start_x(d)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10046   if ( stop_x(dln)<(xoff+mp_take_scaled(mp, hsf,stop_x(dd)))) 
10047     stop_x(d)=stop_x(dln);
10048   else 
10049     stop_x(d)=xoff+mp_take_scaled(mp, hsf,stop_x(dd));
10050 }
10051
10052 @ The next major task is to update the bounding box information in an edge
10053 header~|h|. This is done via a procedure |adjust_bbox| that enlarges an edge
10054 header's bounding box to accommodate the box computed by |path_bbox| or
10055 |pen_bbox|. (This is stored in global variables |minx|, |miny|, |maxx|, and
10056 |maxy|.)
10057
10058 @c void mp_adjust_bbox (MP mp,pointer h) { 
10059   if ( minx<minx_val(h) ) minx_val(h)=minx;
10060   if ( miny<miny_val(h) ) miny_val(h)=miny;
10061   if ( maxx>maxx_val(h) ) maxx_val(h)=maxx;
10062   if ( maxy>maxy_val(h) ) maxy_val(h)=maxy;
10063 }
10064
10065 @ Here is a special routine for updating the bounding box information in
10066 edge header~|h| to account for the squared-off ends of a non-cyclic path~|p|
10067 that is to be stroked with the pen~|pp|.
10068
10069 @c void mp_box_ends (MP mp, pointer p, pointer pp, pointer h) {
10070   pointer q;  /* a knot node adjacent to knot |p| */
10071   fraction dx,dy;  /* a unit vector in the direction out of the path at~|p| */
10072   scaled d;  /* a factor for adjusting the length of |(dx,dy)| */
10073   scaled z;  /* a coordinate being tested against the bounding box */
10074   scaled xx,yy;  /* the extreme pen vertex in the |(dx,dy)| direction */
10075   integer i; /* a loop counter */
10076   if ( right_type(p)!=mp_endpoint ) { 
10077     q=link(p);
10078     while (1) { 
10079       @<Make |(dx,dy)| the final direction for the path segment from
10080         |q| to~|p|; set~|d|@>;
10081       d=mp_pyth_add(mp, dx,dy);
10082       if ( d>0 ) { 
10083          @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>;
10084          for (i=1;i<= 2;i++) { 
10085            @<Use |(dx,dy)| to generate a vertex of the square end cap and
10086              update the bounding box to accommodate it@>;
10087            dx=-dx; dy=-dy; 
10088         }
10089       }
10090       if ( right_type(p)==mp_endpoint ) {
10091          return;
10092       } else {
10093         @<Advance |p| to the end of the path and make |q| the previous knot@>;
10094       } 
10095     }
10096   }
10097 }
10098
10099 @ @<Make |(dx,dy)| the final direction for the path segment from...@>=
10100 if ( q==link(p) ) { 
10101   dx=x_coord(p)-right_x(p);
10102   dy=y_coord(p)-right_y(p);
10103   if ( (dx==0)&&(dy==0) ) {
10104     dx=x_coord(p)-left_x(q);
10105     dy=y_coord(p)-left_y(q);
10106   }
10107 } else { 
10108   dx=x_coord(p)-left_x(p);
10109   dy=y_coord(p)-left_y(p);
10110   if ( (dx==0)&&(dy==0) ) {
10111     dx=x_coord(p)-right_x(q);
10112     dy=y_coord(p)-right_y(q);
10113   }
10114 }
10115 dx=x_coord(p)-x_coord(q);
10116 dy=y_coord(p)-y_coord(q)
10117
10118 @ @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>=
10119 dx=mp_make_fraction(mp, dx,d);
10120 dy=mp_make_fraction(mp, dy,d);
10121 mp_find_offset(mp, -dy,dx,pp);
10122 xx=mp->cur_x; yy=mp->cur_y
10123
10124 @ @<Use |(dx,dy)| to generate a vertex of the square end cap and...@>=
10125 mp_find_offset(mp, dx,dy,pp);
10126 d=mp_take_fraction(mp, xx-mp->cur_x,dx)+mp_take_fraction(mp, yy-mp->cur_y,dy);
10127 if ( ((d<0)&&(i==1)) || ((d>0)&&(i==2))) 
10128   mp_confusion(mp, "box_ends");
10129 @:this can't happen box ends}{\quad\\{box\_ends}@>
10130 z=x_coord(p)+mp->cur_x+mp_take_fraction(mp, d,dx);
10131 if ( z<minx_val(h) ) minx_val(h)=z;
10132 if ( z>maxx_val(h) ) maxx_val(h)=z;
10133 z=y_coord(p)+mp->cur_y+mp_take_fraction(mp, d,dy);
10134 if ( z<miny_val(h) ) miny_val(h)=z;
10135 if ( z>maxy_val(h) ) maxy_val(h)=z
10136
10137 @ @<Advance |p| to the end of the path and make |q| the previous knot@>=
10138 do {  
10139   q=p;
10140   p=link(p);
10141 } while (right_type(p)!=mp_endpoint)
10142
10143 @ The major difficulty in finding the bounding box of an edge structure is the
10144 effect of clipping paths.  We treat them conservatively by only clipping to the
10145 clipping path's bounding box, but this still
10146 requires recursive calls to |set_bbox| in order to find the bounding box of
10147 @^recursion@>
10148 the objects to be clipped.  Such calls are distinguished by the fact that the
10149 boolean parameter |top_level| is false.
10150
10151 @c void mp_set_bbox (MP mp,pointer h, boolean top_level) {
10152   pointer p;  /* a graphical object being considered */
10153   scaled sminx,sminy,smaxx,smaxy;
10154   /* for saving the bounding box during recursive calls */
10155   scaled x0,x1,y0,y1;  /* temporary registers */
10156   integer lev;  /* nesting level for |mp_start_bounds_code| nodes */
10157   @<Wipe out any existing bounding box information if |bbtype(h)| is
10158   incompatible with |internal[mp_true_corners]|@>;
10159   while ( link(bblast(h))!=null ) { 
10160     p=link(bblast(h));
10161     bblast(h)=p;
10162     switch (type(p)) {
10163     case mp_stop_clip_code: 
10164       if ( top_level ) mp_confusion(mp, "bbox");  else return;
10165 @:this can't happen bbox}{\quad bbox@>
10166       break;
10167     @<Other cases for updating the bounding box based on the type of object |p|@>;
10168     } /* all cases are enumerated above */
10169   }
10170   if ( ! top_level ) mp_confusion(mp, "bbox");
10171 }
10172
10173 @ @<Internal library declarations@>=
10174 void mp_set_bbox (MP mp,pointer h, boolean top_level);
10175
10176 @ @<Wipe out any existing bounding box information if |bbtype(h)| is...@>=
10177 switch (bbtype(h)) {
10178 case no_bounds: 
10179   break;
10180 case bounds_set: 
10181   if ( mp->internal[mp_true_corners]>0 ) mp_init_bbox(mp, h);
10182   break;
10183 case bounds_unset: 
10184   if ( mp->internal[mp_true_corners]<=0 ) mp_init_bbox(mp, h);
10185   break;
10186 } /* there are no other cases */
10187
10188 @ @<Other cases for updating the bounding box...@>=
10189 case mp_fill_code: 
10190   mp_path_bbox(mp, path_p(p));
10191   if ( pen_p(p)!=null ) { 
10192     x0=minx; y0=miny;
10193     x1=maxx; y1=maxy;
10194     mp_pen_bbox(mp, pen_p(p));
10195     minx=minx+x0;
10196     miny=miny+y0;
10197     maxx=maxx+x1;
10198     maxy=maxy+y1;
10199   }
10200   mp_adjust_bbox(mp, h);
10201   break;
10202
10203 @ @<Other cases for updating the bounding box...@>=
10204 case mp_start_bounds_code: 
10205   if ( mp->internal[mp_true_corners]>0 ) {
10206     bbtype(h)=bounds_unset;
10207   } else { 
10208     bbtype(h)=bounds_set;
10209     mp_path_bbox(mp, path_p(p));
10210     mp_adjust_bbox(mp, h);
10211     @<Scan to the matching |mp_stop_bounds_code| node and update |p| and
10212       |bblast(h)|@>;
10213   }
10214   break;
10215 case mp_stop_bounds_code: 
10216   if ( mp->internal[mp_true_corners]<=0 ) mp_confusion(mp, "bbox2");
10217 @:this can't happen bbox2}{\quad bbox2@>
10218   break;
10219
10220 @ @<Scan to the matching |mp_stop_bounds_code| node and update |p| and...@>=
10221 lev=1;
10222 while ( lev!=0 ) { 
10223   if ( link(p)==null ) mp_confusion(mp, "bbox2");
10224 @:this can't happen bbox2}{\quad bbox2@>
10225   p=link(p);
10226   if ( type(p)==mp_start_bounds_code ) incr(lev);
10227   else if ( type(p)==mp_stop_bounds_code ) decr(lev);
10228 }
10229 bblast(h)=p
10230
10231 @ It saves a lot of grief here to be slightly conservative and not account for
10232 omitted parts of dashed lines.  We also don't worry about the material omitted
10233 when using butt end caps.  The basic computation is for round end caps and
10234 |box_ends| augments it for square end caps.
10235
10236 @<Other cases for updating the bounding box...@>=
10237 case mp_stroked_code: 
10238   mp_path_bbox(mp, path_p(p));
10239   x0=minx; y0=miny;
10240   x1=maxx; y1=maxy;
10241   mp_pen_bbox(mp, pen_p(p));
10242   minx=minx+x0;
10243   miny=miny+y0;
10244   maxx=maxx+x1;
10245   maxy=maxy+y1;
10246   mp_adjust_bbox(mp, h);
10247   if ( (left_type(path_p(p))==mp_endpoint)&&(lcap_val(p)==2) )
10248     mp_box_ends(mp, path_p(p), pen_p(p), h);
10249   break;
10250
10251 @ The height width and depth information stored in a text node determines a
10252 rectangle that needs to be transformed according to the transformation
10253 parameters stored in the text node.
10254
10255 @<Other cases for updating the bounding box...@>=
10256 case mp_text_code: 
10257   x1=mp_take_scaled(mp, txx_val(p),width_val(p));
10258   y0=mp_take_scaled(mp, txy_val(p),-depth_val(p));
10259   y1=mp_take_scaled(mp, txy_val(p),height_val(p));
10260   minx=tx_val(p);
10261   maxx=minx;
10262   if ( y0<y1 ) { minx=minx+y0; maxx=maxx+y1;  }
10263   else         { minx=minx+y1; maxx=maxx+y0;  }
10264   if ( x1<0 ) minx=minx+x1;  else maxx=maxx+x1;
10265   x1=mp_take_scaled(mp, tyx_val(p),width_val(p));
10266   y0=mp_take_scaled(mp, tyy_val(p),-depth_val(p));
10267   y1=mp_take_scaled(mp, tyy_val(p),height_val(p));
10268   miny=ty_val(p);
10269   maxy=miny;
10270   if ( y0<y1 ) { miny=miny+y0; maxy=maxy+y1;  }
10271   else         { miny=miny+y1; maxy=maxy+y0;  }
10272   if ( x1<0 ) miny=miny+x1;  else maxy=maxy+x1;
10273   mp_adjust_bbox(mp, h);
10274   break;
10275
10276 @ This case involves a recursive call that advances |bblast(h)| to the node of
10277 type |mp_stop_clip_code| that matches |p|.
10278
10279 @<Other cases for updating the bounding box...@>=
10280 case mp_start_clip_code: 
10281   mp_path_bbox(mp, path_p(p));
10282   x0=minx; y0=miny;
10283   x1=maxx; y1=maxy;
10284   sminx=minx_val(h); sminy=miny_val(h);
10285   smaxx=maxx_val(h); smaxy=maxy_val(h);
10286   @<Reinitialize the bounding box in header |h| and call |set_bbox| recursively
10287     starting at |link(p)|@>;
10288   @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,
10289     |y0|, |y1|@>;
10290   minx=sminx; miny=sminy;
10291   maxx=smaxx; maxy=smaxy;
10292   mp_adjust_bbox(mp, h);
10293   break;
10294
10295 @ @<Reinitialize the bounding box in header |h| and call |set_bbox|...@>=
10296 minx_val(h)=el_gordo;
10297 miny_val(h)=el_gordo;
10298 maxx_val(h)=-el_gordo;
10299 maxy_val(h)=-el_gordo;
10300 mp_set_bbox(mp, h,false)
10301
10302 @ @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,...@>=
10303 if ( minx_val(h)<x0 ) minx_val(h)=x0;
10304 if ( miny_val(h)<y0 ) miny_val(h)=y0;
10305 if ( maxx_val(h)>x1 ) maxx_val(h)=x1;
10306 if ( maxy_val(h)>y1 ) maxy_val(h)=y1
10307
10308 @* \[22] Finding an envelope.
10309 When \MP\ has a path and a polygonal pen, it needs to express the desired
10310 shape in terms of things \ps\ can understand.  The present task is to compute
10311 a new path that describes the region to be filled.  It is convenient to
10312 define this as a two step process where the first step is determining what
10313 offset to use for each segment of the path.
10314
10315 @ Given a pointer |c| to a cyclic path,
10316 and a pointer~|h| to the first knot of a pen polygon,
10317 the |offset_prep| routine changes the path into cubics that are
10318 associated with particular pen offsets. Thus if the cubic between |p|
10319 and~|q| is associated with the |k|th offset and the cubic between |q| and~|r|
10320 has offset |l| then |info(q)=zero_off+l-k|. (The constant |zero_off| is added
10321 to because |l-k| could be negative.)
10322
10323 After overwriting the type information with offset differences, we no longer
10324 have a true path so we refer to the knot list returned by |offset_prep| as an
10325 ``envelope spec.''
10326 @^envelope spec@>
10327 Since an envelope spec only determines relative changes in pen offsets,
10328 |offset_prep| sets a global variable |spec_offset| to the relative change from
10329 |h| to the first offset.
10330
10331 @d zero_off 16384 /* added to offset changes to make them positive */
10332
10333 @<Glob...@>=
10334 integer spec_offset; /* number of pen edges between |h| and the initial offset */
10335
10336 @ @c @<Declare subroutines needed by |offset_prep|@>;
10337 pointer mp_offset_prep (MP mp,pointer c, pointer h) {
10338   halfword n; /* the number of vertices in the pen polygon */
10339   pointer p,q,q0,r,w, ww; /* for list manipulation */
10340   integer k_needed; /* amount to be added to |info(p)| when it is computed */
10341   pointer w0; /* a pointer to pen offset to use just before |p| */
10342   scaled dxin,dyin; /* the direction into knot |p| */
10343   integer turn_amt; /* change in pen offsets for the current cubic */
10344   @<Other local variables for |offset_prep|@>;
10345   dx0=0; dy0=0;
10346   @<Initialize the pen size~|n|@>;
10347   @<Initialize the incoming direction and pen offset at |c|@>;
10348   p=c; k_needed=0;
10349   do {  
10350     q=link(p);
10351     @<Split the cubic between |p| and |q|, if necessary, into cubics
10352       associated with single offsets, after which |q| should
10353       point to the end of the final such cubic@>;
10354   NOT_FOUND:
10355     @<Advance |p| to node |q|, removing any ``dead'' cubics that
10356       might have been introduced by the splitting process@>;
10357   } while (q!=c);
10358   @<Fix the offset change in |info(c)| and set |c| to the return value of
10359     |offset_prep|@>;
10360   return c;
10361 }
10362
10363 @ We shall want to keep track of where certain knots on the cyclic path
10364 wind up in the envelope spec.  It doesn't suffice just to keep pointers to
10365 knot nodes because some nodes are deleted while removing dead cubics.  Thus
10366 |offset_prep| updates the following pointers
10367
10368 @<Glob...@>=
10369 pointer spec_p1;
10370 pointer spec_p2; /* pointers to distinguished knots */
10371
10372 @ @<Set init...@>=
10373 mp->spec_p1=null; mp->spec_p2=null;
10374
10375 @ @<Initialize the pen size~|n|@>=
10376 n=0; p=h;
10377 do {  
10378   incr(n);
10379   p=link(p);
10380 } while (p!=h)
10381
10382 @ Since the true incoming direction isn't known yet, we just pick a direction
10383 consistent with the pen offset~|h|.  If this is wrong, it can be corrected
10384 later.
10385
10386 @<Initialize the incoming direction and pen offset at |c|@>=
10387 dxin=x_coord(link(h))-x_coord(knil(h));
10388 dyin=y_coord(link(h))-y_coord(knil(h));
10389 if ( (dxin==0)&&(dyin==0) ) {
10390   dxin=y_coord(knil(h))-y_coord(h);
10391   dyin=x_coord(h)-x_coord(knil(h));
10392 }
10393 w0=h
10394
10395 @ We must be careful not to remove the only cubic in a cycle.
10396
10397 But we must also be careful for another reason. If the user-supplied
10398 path starts with a set of degenerate cubics, the target node |q| can
10399 be collapsed to the initial node |p| which might be the same as the
10400 initial node |c| of the curve. This would cause the |offset_prep| routine
10401 to bail out too early, causing distress later on. (See for example
10402 the testcase reported by Bogus\l{}aw Jackowski in tracker id 267, case 52c
10403 on Sarovar.)
10404
10405 @<Advance |p| to node |q|, removing any ``dead'' cubics...@>=
10406 q0=q;
10407 do { 
10408   r=link(p);
10409   if ( x_coord(p)==right_x(p) && y_coord(p)==right_y(p) &&
10410        x_coord(p)==left_x(r)  && y_coord(p)==left_y(r) &&
10411        x_coord(p)==x_coord(r) && y_coord(p)==y_coord(r) &&
10412        r!=p ) {
10413       @<Remove the cubic following |p| and update the data structures
10414         to merge |r| into |p|@>;
10415   }
10416   p=r;
10417 } while (p!=q);
10418 /* Check if we removed too much */
10419 if(q!=q0)
10420   q = link(q)
10421
10422 @ @<Remove the cubic following |p| and update the data structures...@>=
10423 { k_needed=info(p)-zero_off;
10424   if ( r==q ) { 
10425     q=p;
10426   } else { 
10427     info(p)=k_needed+info(r);
10428     k_needed=0;
10429   };
10430   if ( r==c ) { info(p)=info(c); c=p; };
10431   if ( r==mp->spec_p1 ) mp->spec_p1=p;
10432   if ( r==mp->spec_p2 ) mp->spec_p2=p;
10433   r=p; mp_remove_cubic(mp, p);
10434 }
10435
10436 @ Not setting the |info| field of the newly created knot allows the splitting
10437 routine to work for paths.
10438
10439 @<Declare subroutines needed by |offset_prep|@>=
10440 void mp_split_cubic (MP mp,pointer p, fraction t) { /* splits the cubic after |p| */
10441   scaled v; /* an intermediate value */
10442   pointer q,r; /* for list manipulation */
10443   q=link(p); r=mp_get_node(mp, knot_node_size); link(p)=r; link(r)=q;
10444   originator(r)=mp_program_code;
10445   left_type(r)=mp_explicit; right_type(r)=mp_explicit;
10446   v=t_of_the_way(right_x(p),left_x(q));
10447   right_x(p)=t_of_the_way(x_coord(p),right_x(p));
10448   left_x(q)=t_of_the_way(left_x(q),x_coord(q));
10449   left_x(r)=t_of_the_way(right_x(p),v);
10450   right_x(r)=t_of_the_way(v,left_x(q));
10451   x_coord(r)=t_of_the_way(left_x(r),right_x(r));
10452   v=t_of_the_way(right_y(p),left_y(q));
10453   right_y(p)=t_of_the_way(y_coord(p),right_y(p));
10454   left_y(q)=t_of_the_way(left_y(q),y_coord(q));
10455   left_y(r)=t_of_the_way(right_y(p),v);
10456   right_y(r)=t_of_the_way(v,left_y(q));
10457   y_coord(r)=t_of_the_way(left_y(r),right_y(r));
10458 }
10459
10460 @ This does not set |info(p)| or |right_type(p)|.
10461
10462 @<Declare subroutines needed by |offset_prep|@>=
10463 void mp_remove_cubic (MP mp,pointer p) { /* removes the dead cubic following~|p| */
10464   pointer q; /* the node that disappears */
10465   q=link(p); link(p)=link(q);
10466   right_x(p)=right_x(q); right_y(p)=right_y(q);
10467   mp_free_node(mp, q,knot_node_size);
10468 }
10469
10470 @ Let $d\prec d'$ mean that the counter-clockwise angle from $d$ to~$d'$ is
10471 strictly between zero and $180^\circ$.  Then we can define $d\preceq d'$ to
10472 mean that the angle could be zero or $180^\circ$. If $w_k=(u_k,v_k)$ is the
10473 $k$th pen offset, the $k$th pen edge direction is defined by the formula
10474 $$d_k=(u\k-u_k,\,v\k-v_k).$$
10475 When listed by increasing $k$, these directions occur in counter-clockwise
10476 order so that $d_k\preceq d\k$ for all~$k$.
10477 The goal of |offset_prep| is to find an offset index~|k| to associate with
10478 each cubic, such that the direction $d(t)$ of the cubic satisfies
10479 $$d_{k-1}\preceq d(t)\preceq d_k\qquad\hbox{for $0\le t\le 1$.}\eqno(*)$$
10480 We may have to split a cubic into many pieces before each
10481 piece corresponds to a unique offset.
10482
10483 @<Split the cubic between |p| and |q|, if necessary, into cubics...@>=
10484 info(p)=zero_off+k_needed;
10485 k_needed=0;
10486 @<Prepare for derivative computations;
10487   |goto not_found| if the current cubic is dead@>;
10488 @<Find the initial direction |(dx,dy)|@>;
10489 @<Update |info(p)| and find the offset $w_k$ such that
10490   $d_{k-1}\preceq(\\{dx},\\{dy})\prec d_k$; also advance |w0| for
10491   the direction change at |p|@>;
10492 @<Find the final direction |(dxin,dyin)|@>;
10493 @<Decide on the net change in pen offsets and set |turn_amt|@>;
10494 @<Complete the offset splitting process@>;
10495 w0=mp_pen_walk(mp, w0,turn_amt)
10496
10497 @ @<Declare subroutines needed by |offset_prep|@>=
10498 pointer mp_pen_walk (MP mp,pointer w, integer k) {
10499   /* walk |k| steps around a pen from |w| */
10500   while ( k>0 ) { w=link(w); decr(k);  };
10501   while ( k<0 ) { w=knil(w); incr(k);  };
10502   return w;
10503 }
10504
10505 @ The direction of a cubic $B(z_0,z_1,z_2,z_3;t)=\bigl(x(t),y(t)\bigr)$ can be
10506 calculated from the quadratic polynomials
10507 ${1\over3}x'(t)=B(x_1-x_0,x_2-x_1,x_3-x_2;t)$ and
10508 ${1\over3}y'(t)=B(y_1-y_0,y_2-y_1,y_3-y_2;t)$.
10509 Since we may be calculating directions from several cubics
10510 split from the current one, it is desirable to do these calculations
10511 without losing too much precision. ``Scaled up'' values of the
10512 derivatives, which will be less tainted by accumulated errors than
10513 derivatives found from the cubics themselves, are maintained in
10514 local variables |x0|, |x1|, and |x2|, representing $X_0=2^l(x_1-x_0)$,
10515 $X_1=2^l(x_2-x_1)$, and $X_2=2^l(x_3-x_2)$; similarly |y0|, |y1|, and~|y2|
10516 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)$.
10517
10518 @<Other local variables for |offset_prep|@>=
10519 integer x0,x1,x2,y0,y1,y2; /* representatives of derivatives */
10520 integer t0,t1,t2; /* coefficients of polynomial for slope testing */
10521 integer du,dv,dx,dy; /* for directions of the pen and the curve */
10522 integer dx0,dy0; /* initial direction for the first cubic in the curve */
10523 integer max_coef; /* used while scaling */
10524 integer x0a,x1a,x2a,y0a,y1a,y2a; /* intermediate values */
10525 fraction t; /* where the derivative passes through zero */
10526 fraction s; /* a temporary value */
10527
10528 @ @<Prepare for derivative computations...@>=
10529 x0=right_x(p)-x_coord(p);
10530 x2=x_coord(q)-left_x(q);
10531 x1=left_x(q)-right_x(p);
10532 y0=right_y(p)-y_coord(p); y2=y_coord(q)-left_y(q);
10533 y1=left_y(q)-right_y(p);
10534 max_coef=abs(x0);
10535 if ( abs(x1)>max_coef ) max_coef=abs(x1);
10536 if ( abs(x2)>max_coef ) max_coef=abs(x2);
10537 if ( abs(y0)>max_coef ) max_coef=abs(y0);
10538 if ( abs(y1)>max_coef ) max_coef=abs(y1);
10539 if ( abs(y2)>max_coef ) max_coef=abs(y2);
10540 if ( max_coef==0 ) goto NOT_FOUND;
10541 while ( max_coef<fraction_half ) {
10542   double(max_coef);
10543   double(x0); double(x1); double(x2);
10544   double(y0); double(y1); double(y2);
10545 }
10546
10547 @ Let us first solve a special case of the problem: Suppose we
10548 know an index~$k$ such that either (i)~$d(t)\succeq d_{k-1}$ for all~$t$
10549 and $d(0)\prec d_k$, or (ii)~$d(t)\preceq d_k$ for all~$t$ and
10550 $d(0)\succ d_{k-1}$.
10551 Then, in a sense, we're halfway done, since one of the two relations
10552 in $(*)$ is satisfied, and the other couldn't be satisfied for
10553 any other value of~|k|.
10554
10555 Actually, the conditions can be relaxed somewhat since a relation such as
10556 $d(t)\succeq d_{k-1}$ restricts $d(t)$ to a half plane when all that really
10557 matters is whether $d(t)$ crosses the ray in the $d_{k-1}$ direction from
10558 the origin.  The condition for case~(i) becomes $d_{k-1}\preceq d(0)\prec d_k$
10559 and $d(t)$ never crosses the $d_{k-1}$ ray in the clockwise direction.
10560 Case~(ii) is similar except $d(t)$ cannot cross the $d_k$ ray in the
10561 counterclockwise direction.
10562
10563 The |fin_offset_prep| subroutine solves the stated subproblem.
10564 It has a parameter called |rise| that is |1| in
10565 case~(i), |-1| in case~(ii). Parameters |x0| through |y2| represent
10566 the derivative of the cubic following |p|.
10567 The |w| parameter should point to offset~$w_k$ and |info(p)| should already
10568 be set properly.  The |turn_amt| parameter gives the absolute value of the
10569 overall net change in pen offsets.
10570
10571 @<Declare subroutines needed by |offset_prep|@>=
10572 void mp_fin_offset_prep (MP mp,pointer p, pointer w, integer 
10573   x0,integer x1, integer x2, integer y0, integer y1, integer y2, 
10574   integer rise, integer turn_amt)  {
10575   pointer ww; /* for list manipulation */
10576   scaled du,dv; /* for slope calculation */
10577   integer t0,t1,t2; /* test coefficients */
10578   fraction t; /* place where the derivative passes a critical slope */
10579   fraction s; /* slope or reciprocal slope */
10580   integer v; /* intermediate value for updating |x0..y2| */
10581   pointer q; /* original |link(p)| */
10582   q=link(p);
10583   while (1)  { 
10584     if ( rise>0 ) ww=link(w); /* a pointer to $w\k$ */
10585     else  ww=knil(w); /* a pointer to $w_{k-1}$ */
10586     @<Compute test coefficients |(t0,t1,t2)|
10587       for $d(t)$ versus $d_k$ or $d_{k-1}$@>;
10588     t=mp_crossing_point(mp, t0,t1,t2);
10589     if ( t>=fraction_one ) {
10590       if ( turn_amt>0 ) t=fraction_one;  else return;
10591     }
10592     @<Split the cubic at $t$,
10593       and split off another cubic if the derivative crosses back@>;
10594     w=ww;
10595   }
10596 }
10597
10598 @ We want $B(\\{t0},\\{t1},\\{t2};t)$ to be the dot product of $d(t)$ with a
10599 $-90^\circ$ rotation of the vector from |w| to |ww|.  This makes the resulting
10600 function cross from positive to negative when $d_{k-1}\preceq d(t)\preceq d_k$
10601 begins to fail.
10602
10603 @<Compute test coefficients |(t0,t1,t2)| for $d(t)$ versus...@>=
10604 du=x_coord(ww)-x_coord(w); dv=y_coord(ww)-y_coord(w);
10605 if ( abs(du)>=abs(dv) ) {
10606   s=mp_make_fraction(mp, dv,du);
10607   t0=mp_take_fraction(mp, x0,s)-y0;
10608   t1=mp_take_fraction(mp, x1,s)-y1;
10609   t2=mp_take_fraction(mp, x2,s)-y2;
10610   if ( du<0 ) { negate(t0); negate(t1); negate(t2);  }
10611 } else { 
10612   s=mp_make_fraction(mp, du,dv);
10613   t0=x0-mp_take_fraction(mp, y0,s);
10614   t1=x1-mp_take_fraction(mp, y1,s);
10615   t2=x2-mp_take_fraction(mp, y2,s);
10616   if ( dv<0 ) { negate(t0); negate(t1); negate(t2);  }
10617 }
10618 if ( t0<0 ) t0=0 /* should be positive without rounding error */
10619
10620 @ The curve has crossed $d_k$ or $d_{k-1}$; its initial segment satisfies
10621 $(*)$, and it might cross again, yielding another solution of $(*)$.
10622
10623 @<Split the cubic at $t$, and split off another...@>=
10624
10625 mp_split_cubic(mp, p,t); p=link(p); info(p)=zero_off+rise;
10626 decr(turn_amt);
10627 v=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10628 x0=t_of_the_way(v,x1);
10629 v=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10630 y0=t_of_the_way(v,y1);
10631 if ( turn_amt<0 ) {
10632   t1=t_of_the_way(t1,t2);
10633   if ( t1>0 ) t1=0; /* without rounding error, |t1| would be |<=0| */
10634   t=mp_crossing_point(mp, 0,-t1,-t2);
10635   if ( t>fraction_one ) t=fraction_one;
10636   incr(turn_amt);
10637   if ( (t==fraction_one)&&(link(p)!=q) ) {
10638     info(link(p))=info(link(p))-rise;
10639   } else { 
10640     mp_split_cubic(mp, p,t); info(link(p))=zero_off-rise;
10641     v=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10642     x2=t_of_the_way(x1,v);
10643     v=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10644     y2=t_of_the_way(y1,v);
10645   }
10646 }
10647 }
10648
10649 @ Now we must consider the general problem of |offset_prep|, when
10650 nothing is known about a given cubic. We start by finding its
10651 direction in the vicinity of |t=0|.
10652
10653 If $z'(t)=0$, the given cubic is numerically unstable but |offset_prep|
10654 has not yet introduced any more numerical errors.  Thus we can compute
10655 the true initial direction for the given cubic, even if it is almost
10656 degenerate.
10657
10658 @<Find the initial direction |(dx,dy)|@>=
10659 dx=x0; dy=y0;
10660 if ( dx==0 && dy==0 ) { 
10661   dx=x1; dy=y1;
10662   if ( dx==0 && dy==0 ) { 
10663     dx=x2; dy=y2;
10664   }
10665 }
10666 if ( p==c ) { dx0=dx; dy0=dy;  }
10667
10668 @ @<Find the final direction |(dxin,dyin)|@>=
10669 dxin=x2; dyin=y2;
10670 if ( dxin==0 && dyin==0 ) {
10671   dxin=x1; dyin=y1;
10672   if ( dxin==0 && dyin==0 ) {
10673     dxin=x0; dyin=y0;
10674   }
10675 }
10676
10677 @ The next step is to bracket the initial direction between consecutive
10678 edges of the pen polygon.  We must be careful to turn clockwise only if
10679 this makes the turn less than $180^\circ$. (A $180^\circ$ turn must be
10680 counter-clockwise in order to make \&{doublepath} envelopes come out
10681 @:double_path_}{\&{doublepath} primitive@>
10682 right.) This code depends on |w0| being the offset for |(dxin,dyin)|.
10683
10684 @<Update |info(p)| and find the offset $w_k$ such that...@>=
10685 turn_amt=mp_get_turn_amt(mp,w0,dx,dy,(mp_ab_vs_cd(mp, dy,dxin,dx,dyin)>=0));
10686 w=mp_pen_walk(mp, w0, turn_amt);
10687 w0=w;
10688 info(p)=info(p)+turn_amt
10689
10690 @ Decide how many pen offsets to go away from |w| in order to find the offset
10691 for |(dx,dy)|, going counterclockwise if |ccw| is |true|.  This assumes that
10692 |w| is the offset for some direction $(x',y')$ from which the angle to |(dx,dy)|
10693 in the sense determined by |ccw| is less than or equal to $180^\circ$.
10694
10695 If the pen polygon has only two edges, they could both be parallel
10696 to |(dx,dy)|.  In this case, we must be careful to stop after crossing the first
10697 such edge in order to avoid an infinite loop.
10698
10699 @<Declare subroutines needed by |offset_prep|@>=
10700 integer mp_get_turn_amt (MP mp,pointer w, scaled  dx,
10701                          scaled dy, boolean  ccw) {
10702   pointer ww; /* a neighbor of knot~|w| */
10703   integer s; /* turn amount so far */
10704   integer t; /* |ab_vs_cd| result */
10705   s=0;
10706   if ( ccw ) { 
10707     ww=link(w);
10708     do {  
10709       t=mp_ab_vs_cd(mp, dy,(x_coord(ww)-x_coord(w)),
10710                         dx,(y_coord(ww)-y_coord(w)));
10711       if ( t<0 ) break;
10712       incr(s);
10713       w=ww; ww=link(ww);
10714     } while (t>0);
10715   } else { 
10716     ww=knil(w);
10717     while ( mp_ab_vs_cd(mp, dy,(x_coord(w)-x_coord(ww)),
10718                             dx,(y_coord(w)-y_coord(ww))) < 0) { 
10719       decr(s);
10720       w=ww; ww=knil(ww);
10721     }
10722   }
10723   return s;
10724 }
10725
10726 @ When we're all done, the final offset is |w0| and the final curve direction
10727 is |(dxin,dyin)|.  With this knowledge of the incoming direction at |c|, we
10728 can correct |info(c)| which was erroneously based on an incoming offset
10729 of~|h|.
10730
10731 @d fix_by(A) info(c)=info(c)+(A)
10732
10733 @<Fix the offset change in |info(c)| and set |c| to the return value of...@>=
10734 mp->spec_offset=info(c)-zero_off;
10735 if ( link(c)==c ) {
10736   info(c)=zero_off+n;
10737 } else { 
10738   fix_by(k_needed);
10739   while ( w0!=h ) { fix_by(1); w0=link(w0);  };
10740   while ( info(c)<=zero_off-n ) fix_by(n);
10741   while ( info(c)>zero_off ) fix_by(-n);
10742   if ( (info(c)!=zero_off)&&(mp_ab_vs_cd(mp, dy0,dxin,dx0,dyin)>=0) ) fix_by(n);
10743 }
10744 return c
10745
10746 @ Finally we want to reduce the general problem to situations that
10747 |fin_offset_prep| can handle. We split the cubic into at most three parts
10748 with respect to $d_{k-1}$, and apply |fin_offset_prep| to each part.
10749
10750 @<Complete the offset splitting process@>=
10751 ww=knil(w);
10752 @<Compute test coeff...@>;
10753 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set
10754   |t:=fraction_one+1|@>;
10755 if ( t>fraction_one ) {
10756   mp_fin_offset_prep(mp, p,w,x0,x1,x2,y0,y1,y2,1,turn_amt);
10757 } else {
10758   mp_split_cubic(mp, p,t); r=link(p);
10759   x1a=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10760   x2a=t_of_the_way(x1a,x1);
10761   y1a=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10762   y2a=t_of_the_way(y1a,y1);
10763   mp_fin_offset_prep(mp, p,w,x0,x1a,x2a,y0,y1a,y2a,1,0); x0=x2a; y0=y2a;
10764   info(r)=zero_off-1;
10765   if ( turn_amt>=0 ) {
10766     t1=t_of_the_way(t1,t2);
10767     if ( t1>0 ) t1=0;
10768     t=mp_crossing_point(mp, 0,-t1,-t2);
10769     if ( t>fraction_one ) t=fraction_one;
10770     @<Split off another rising cubic for |fin_offset_prep|@>;
10771     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,0);
10772   } else {
10773     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,(-1-turn_amt));
10774   }
10775 }
10776
10777 @ @<Split off another rising cubic for |fin_offset_prep|@>=
10778 mp_split_cubic(mp, r,t); info(link(r))=zero_off+1;
10779 x1a=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10780 x0a=t_of_the_way(x1,x1a);
10781 y1a=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10782 y0a=t_of_the_way(y1,y1a);
10783 mp_fin_offset_prep(mp, link(r),w,x0a,x1a,x2,y0a,y1a,y2,1,turn_amt);
10784 x2=x0a; y2=y0a
10785
10786 @ At this point, the direction of the incoming pen edge is |(-du,-dv)|.
10787 When the component of $d(t)$ perpendicular to |(-du,-dv)| crosses zero, we
10788 need to decide whether the directions are parallel or antiparallel.  We
10789 can test this by finding the dot product of $d(t)$ and |(-du,-dv)|, but this
10790 should be avoided when the value of |turn_amt| already determines the
10791 answer.  If |t2<0|, there is one crossing and it is antiparallel only if
10792 |turn_amt>=0|.  If |turn_amt<0|, there should always be at least one
10793 crossing and the first crossing cannot be antiparallel.
10794
10795 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set...@>=
10796 t=mp_crossing_point(mp, t0,t1,t2);
10797 if ( turn_amt>=0 ) {
10798   if ( t2<0 ) {
10799     t=fraction_one+1;
10800   } else { 
10801     u0=t_of_the_way(x0,x1);
10802     u1=t_of_the_way(x1,x2);
10803     ss=mp_take_fraction(mp, -du,t_of_the_way(u0,u1));
10804     v0=t_of_the_way(y0,y1);
10805     v1=t_of_the_way(y1,y2);
10806     ss=ss+mp_take_fraction(mp, -dv,t_of_the_way(v0,v1));
10807     if ( ss<0 ) t=fraction_one+1;
10808   }
10809 } else if ( t>fraction_one ) {
10810   t=fraction_one;
10811 }
10812
10813 @ @<Other local variables for |offset_prep|@>=
10814 integer u0,u1,v0,v1; /* intermediate values for $d(t)$ calculation */
10815 integer ss = 0; /* the part of the dot product computed so far */
10816 int d_sign; /* sign of overall change in direction for this cubic */
10817
10818 @ If the cubic almost has a cusp, it is a numerically ill-conditioned
10819 problem to decide which way it loops around but that's OK as long we're
10820 consistent.  To make \&{doublepath} envelopes work properly, reversing
10821 the path should always change the sign of |turn_amt|.
10822
10823 @<Decide on the net change in pen offsets and set |turn_amt|@>=
10824 d_sign=mp_ab_vs_cd(mp, dx,dyin, dxin,dy);
10825 if ( d_sign==0 ) {
10826   @<Check rotation direction based on node position@>
10827 }
10828 if ( d_sign==0 ) {
10829   if ( dx==0 ) {
10830     if ( dy>0 ) d_sign=1;  else d_sign=-1;
10831   } else {
10832     if ( dx>0 ) d_sign=1;  else d_sign=-1; 
10833   }
10834 }
10835 @<Make |ss| negative if and only if the total change in direction is
10836   more than $180^\circ$@>;
10837 turn_amt=mp_get_turn_amt(mp, w, dxin, dyin, (d_sign>0));
10838 if ( ss<0 ) turn_amt=turn_amt-d_sign*n
10839
10840 @ We check rotation direction by looking at the vector connecting the current
10841 node with the next. If its angle with incoming and outgoing tangents has the
10842 same sign, we pick this as |d_sign|, since it means we have a flex, not a cusp.
10843 Otherwise we proceed to the cusp code.
10844
10845 @<Check rotation direction based on node position@>=
10846 u0=x_coord(q)-x_coord(p);
10847 u1=y_coord(q)-y_coord(p);
10848 d_sign = half(mp_ab_vs_cd(mp, dx, u1, u0, dy)+
10849   mp_ab_vs_cd(mp, u0, dyin, dxin, u1));
10850
10851 @ In order to be invariant under path reversal, the result of this computation
10852 should not change when |x0|, |y0|, $\ldots$ are all negated and |(x0,y0)| is
10853 then swapped with |(x2,y2)|.  We make use of the identities
10854 |take_fraction(-a,-b)=take_fraction(a,b)| and
10855 |t_of_the_way(-a,-b)=-(t_of_the_way(a,b))|.
10856
10857 @<Make |ss| negative if and only if the total change in direction is...@>=
10858 t0=half(mp_take_fraction(mp, x0,y2))-half(mp_take_fraction(mp, x2,y0));
10859 t1=half(mp_take_fraction(mp, x1,(y0+y2)))-half(mp_take_fraction(mp, y1,(x0+x2)));
10860 if ( t0==0 ) t0=d_sign; /* path reversal always negates |d_sign| */
10861 if ( t0>0 ) {
10862   t=mp_crossing_point(mp, t0,t1,-t0);
10863   u0=t_of_the_way(x0,x1);
10864   u1=t_of_the_way(x1,x2);
10865   v0=t_of_the_way(y0,y1);
10866   v1=t_of_the_way(y1,y2);
10867 } else { 
10868   t=mp_crossing_point(mp, -t0,t1,t0);
10869   u0=t_of_the_way(x2,x1);
10870   u1=t_of_the_way(x1,x0);
10871   v0=t_of_the_way(y2,y1);
10872   v1=t_of_the_way(y1,y0);
10873 }
10874 ss=mp_take_fraction(mp, (x0+x2),t_of_the_way(u0,u1))+
10875    mp_take_fraction(mp, (y0+y2),t_of_the_way(v0,v1))
10876
10877 @ Here's a routine that prints an envelope spec in symbolic form.  It assumes
10878 that the |cur_pen| has not been walked around to the first offset.
10879
10880 @c 
10881 void mp_print_spec (MP mp,pointer cur_spec, pointer cur_pen, char *s) {
10882   pointer p,q; /* list traversal */
10883   pointer w; /* the current pen offset */
10884   mp_print_diagnostic(mp, "Envelope spec",s,true);
10885   p=cur_spec; w=mp_pen_walk(mp, cur_pen,mp->spec_offset);
10886   mp_print_ln(mp);
10887   mp_print_two(mp, x_coord(cur_spec),y_coord(cur_spec));
10888   mp_print(mp, " % beginning with offset ");
10889   mp_print_two(mp, x_coord(w),y_coord(w));
10890   do { 
10891     while (1) {  
10892       q=link(p);
10893       @<Print the cubic between |p| and |q|@>;
10894       p=q;
10895           if ((p==cur_spec) || (info(p)!=zero_off)) 
10896         break;
10897     }
10898     if ( info(p)!=zero_off ) {
10899       @<Update |w| as indicated by |info(p)| and print an explanation@>;
10900     }
10901   } while (p!=cur_spec);
10902   mp_print_nl(mp, " & cycle");
10903   mp_end_diagnostic(mp, true);
10904 }
10905
10906 @ @<Update |w| as indicated by |info(p)| and print an explanation@>=
10907
10908   w=mp_pen_walk(mp, w, (info(p)-zero_off));
10909   mp_print(mp, " % ");
10910   if ( info(p)>zero_off ) mp_print(mp, "counter");
10911   mp_print(mp, "clockwise to offset ");
10912   mp_print_two(mp, x_coord(w),y_coord(w));
10913 }
10914
10915 @ @<Print the cubic between |p| and |q|@>=
10916
10917   mp_print_nl(mp, "   ..controls ");
10918   mp_print_two(mp, right_x(p),right_y(p));
10919   mp_print(mp, " and ");
10920   mp_print_two(mp, left_x(q),left_y(q));
10921   mp_print_nl(mp, " ..");
10922   mp_print_two(mp, x_coord(q),y_coord(q));
10923 }
10924
10925 @ Once we have an envelope spec, the remaining task to construct the actual
10926 envelope by offsetting each cubic as determined by the |info| fields in
10927 the knots.  First we use |offset_prep| to convert the |c| into an envelope
10928 spec. Then we add the offsets so that |c| becomes a cyclic path that represents
10929 the envelope.
10930
10931 The |ljoin| and |miterlim| parameters control the treatment of points where the
10932 pen offset changes, and |lcap| controls the endpoints of a \&{doublepath}.
10933 The endpoints are easily located because |c| is given in undoubled form
10934 and then doubled in this procedure.  We use |spec_p1| and |spec_p2| to keep
10935 track of the endpoints and treat them like very sharp corners.
10936 Butt end caps are treated like beveled joins; round end caps are treated like
10937 round joins; and square end caps are achieved by setting |join_type:=3|.
10938
10939 None of these parameters apply to inside joins where the convolution tracing
10940 has retrograde lines.  In such cases we use a simple connect-the-endpoints
10941 approach that is achieved by setting |join_type:=2|.
10942
10943 @c @<Declare a function called |insert_knot|@>;
10944 pointer mp_make_envelope (MP mp,pointer c, pointer h, small_number ljoin,
10945   small_number lcap, scaled miterlim) {
10946   pointer p,q,r,q0; /* for manipulating the path */
10947   int join_type=0; /* codes |0..3| for mitered, round, beveled, or square */
10948   pointer w,w0; /* the pen knot for the current offset */
10949   scaled qx,qy; /* unshifted coordinates of |q| */
10950   halfword k,k0; /* controls pen edge insertion */
10951   @<Other local variables for |make_envelope|@>;
10952   dxin=0; dyin=0; dxout=0; dyout=0;
10953   mp->spec_p1=null; mp->spec_p2=null;
10954   @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>;
10955   @<Use |offset_prep| to compute the envelope spec then walk |h| around to
10956     the initial offset@>;
10957   w=h;
10958   p=c;
10959   do {  
10960     q=link(p); q0=q;
10961     qx=x_coord(q); qy=y_coord(q);
10962     k=info(q);
10963     k0=k; w0=w;
10964     if ( k!=zero_off ) {
10965       @<Set |join_type| to indicate how to handle offset changes at~|q|@>;
10966     }
10967     @<Add offset |w| to the cubic from |p| to |q|@>;
10968     while ( k!=zero_off ) { 
10969       @<Step |w| and move |k| one step closer to |zero_off|@>;
10970       if ( (join_type==1)||(k==zero_off) )
10971          q=mp_insert_knot(mp, q,qx+x_coord(w),qy+y_coord(w));
10972     };
10973     if ( q!=link(p) ) {
10974       @<Set |p=link(p)| and add knots between |p| and |q| as
10975         required by |join_type|@>;
10976     }
10977     p=q;
10978   } while (q0!=c);
10979   return c;
10980 }
10981
10982 @ @<Use |offset_prep| to compute the envelope spec then walk |h| around to...@>=
10983 c=mp_offset_prep(mp, c,h);
10984 if ( mp->internal[mp_tracing_specs]>0 ) 
10985   mp_print_spec(mp, c,h,"");
10986 h=mp_pen_walk(mp, h,mp->spec_offset)
10987
10988 @ Mitered and squared-off joins depend on path directions that are difficult to
10989 compute for degenerate cubics.  The envelope spec computed by |offset_prep| can
10990 have degenerate cubics only if the entire cycle collapses to a single
10991 degenerate cubic.  Setting |join_type:=2| in this case makes the computed
10992 envelope degenerate as well.
10993
10994 @<Set |join_type| to indicate how to handle offset changes at~|q|@>=
10995 if ( k<zero_off ) {
10996   join_type=2;
10997 } else {
10998   if ( (q!=mp->spec_p1)&&(q!=mp->spec_p2) ) join_type=ljoin;
10999   else if ( lcap==2 ) join_type=3;
11000   else join_type=2-lcap;
11001   if ( (join_type==0)||(join_type==3) ) {
11002     @<Set the incoming and outgoing directions at |q|; in case of
11003       degeneracy set |join_type:=2|@>;
11004     if ( join_type==0 ) {
11005       @<If |miterlim| is less than the secant of half the angle at |q|
11006         then set |join_type:=2|@>;
11007     }
11008   }
11009 }
11010
11011 @ @<If |miterlim| is less than the secant of half the angle at |q|...@>=
11012
11013   tmp=mp_take_fraction(mp, miterlim,fraction_half+
11014       half(mp_take_fraction(mp, dxin,dxout)+mp_take_fraction(mp, dyin,dyout)));
11015   if ( tmp<unity )
11016     if ( mp_take_scaled(mp, miterlim,tmp)<unity ) join_type=2;
11017 }
11018
11019 @ @<Other local variables for |make_envelope|@>=
11020 fraction dxin,dyin,dxout,dyout; /* directions at |q| when square or mitered */
11021 scaled tmp; /* a temporary value */
11022
11023 @ The coordinates of |p| have already been shifted unless |p| is the first
11024 knot in which case they get shifted at the very end.
11025
11026 @<Add offset |w| to the cubic from |p| to |q|@>=
11027 right_x(p)=right_x(p)+x_coord(w);
11028 right_y(p)=right_y(p)+y_coord(w);
11029 left_x(q)=left_x(q)+x_coord(w);
11030 left_y(q)=left_y(q)+y_coord(w);
11031 x_coord(q)=x_coord(q)+x_coord(w);
11032 y_coord(q)=y_coord(q)+y_coord(w);
11033 left_type(q)=mp_explicit;
11034 right_type(q)=mp_explicit
11035
11036 @ @<Step |w| and move |k| one step closer to |zero_off|@>=
11037 if ( k>zero_off ){ w=link(w); decr(k);  }
11038 else { w=knil(w); incr(k);  }
11039
11040 @ The cubic from |q| to the new knot at |(x,y)| becomes a line segment and
11041 the |right_x| and |right_y| fields of |r| are set from |q|.  This is done in
11042 case the cubic containing these control points is ``yet to be examined.''
11043
11044 @<Declare a function called |insert_knot|@>=
11045 pointer mp_insert_knot (MP mp,pointer q, scaled x, scaled y) {
11046   /* returns the inserted knot */
11047   pointer r; /* the new knot */
11048   r=mp_get_node(mp, knot_node_size);
11049   link(r)=link(q); link(q)=r;
11050   right_x(r)=right_x(q);
11051   right_y(r)=right_y(q);
11052   x_coord(r)=x;
11053   y_coord(r)=y;
11054   right_x(q)=x_coord(q);
11055   right_y(q)=y_coord(q);
11056   left_x(r)=x_coord(r);
11057   left_y(r)=y_coord(r);
11058   left_type(r)=mp_explicit;
11059   right_type(r)=mp_explicit;
11060   originator(r)=mp_program_code;
11061   return r;
11062 }
11063
11064 @ After setting |p:=link(p)|, either |join_type=1| or |q=link(p)|.
11065
11066 @<Set |p=link(p)| and add knots between |p| and |q| as...@>=
11067
11068   p=link(p);
11069   if ( (join_type==0)||(join_type==3) ) {
11070     if ( join_type==0 ) {
11071       @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>
11072     } else {
11073       @<Make |r| the last of two knots inserted between |p| and |q| to form a
11074         squared join@>;
11075     }
11076     if ( r!=null ) { 
11077       right_x(r)=x_coord(r);
11078       right_y(r)=y_coord(r);
11079     }
11080   }
11081 }
11082
11083 @ For very small angles, adding a knot is unnecessary and would cause numerical
11084 problems, so we just set |r:=null| in that case.
11085
11086 @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>=
11087
11088   det=mp_take_fraction(mp, dyout,dxin)-mp_take_fraction(mp, dxout,dyin);
11089   if ( abs(det)<26844 ) { 
11090      r=null; /* sine $<10^{-4}$ */
11091   } else { 
11092     tmp=mp_take_fraction(mp, x_coord(q)-x_coord(p),dyout)-
11093         mp_take_fraction(mp, y_coord(q)-y_coord(p),dxout);
11094     tmp=mp_make_fraction(mp, tmp,det);
11095     r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11096       y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11097   }
11098 }
11099
11100 @ @<Other local variables for |make_envelope|@>=
11101 fraction det; /* a determinant used for mitered join calculations */
11102
11103 @ @<Make |r| the last of two knots inserted between |p| and |q| to form a...@>=
11104
11105   ht_x=y_coord(w)-y_coord(w0);
11106   ht_y=x_coord(w0)-x_coord(w);
11107   while ( (abs(ht_x)<fraction_half)&&(abs(ht_y)<fraction_half) ) { 
11108     ht_x+=ht_x; ht_y+=ht_y;
11109   }
11110   @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range dot
11111     product with |(ht_x,ht_y)|@>;
11112   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxin,ht_x)+
11113                                   mp_take_fraction(mp, dyin,ht_y));
11114   r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11115                          y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11116   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxout,ht_x)+
11117                                   mp_take_fraction(mp, dyout,ht_y));
11118   r=mp_insert_knot(mp, r,x_coord(q)+mp_take_fraction(mp, tmp,dxout),
11119                          y_coord(q)+mp_take_fraction(mp, tmp,dyout));
11120 }
11121
11122 @ @<Other local variables for |make_envelope|@>=
11123 fraction ht_x,ht_y; /* perpendicular to the segment from |p| to |q| */
11124 scaled max_ht; /* maximum height of the pen polygon above the |w0|-|w| line */
11125 halfword kk; /* keeps track of the pen vertices being scanned */
11126 pointer ww; /* the pen vertex being tested */
11127
11128 @ The dot product of the vector from |w0| to |ww| with |(ht_x,ht_y)| ranges
11129 from zero to |max_ht|.
11130
11131 @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range...@>=
11132 max_ht=0;
11133 kk=zero_off;
11134 ww=w;
11135 while (1)  { 
11136   @<Step |ww| and move |kk| one step closer to |k0|@>;
11137   if ( kk==k0 ) break;
11138   tmp=mp_take_fraction(mp, (x_coord(ww)-x_coord(w0)),ht_x)+
11139       mp_take_fraction(mp, (y_coord(ww)-y_coord(w0)),ht_y);
11140   if ( tmp>max_ht ) max_ht=tmp;
11141 }
11142
11143
11144 @ @<Step |ww| and move |kk| one step closer to |k0|@>=
11145 if ( kk>k0 ) { ww=link(ww); decr(kk);  }
11146 else { ww=knil(ww); incr(kk);  }
11147
11148 @ @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>=
11149 if ( left_type(c)==mp_endpoint ) { 
11150   mp->spec_p1=mp_htap_ypoc(mp, c);
11151   mp->spec_p2=mp->path_tail;
11152   originator(mp->spec_p1)=mp_program_code;
11153   link(mp->spec_p2)=link(mp->spec_p1);
11154   link(mp->spec_p1)=c;
11155   mp_remove_cubic(mp, mp->spec_p1);
11156   c=mp->spec_p1;
11157   if ( c!=link(c) ) {
11158     originator(mp->spec_p2)=mp_program_code;
11159     mp_remove_cubic(mp, mp->spec_p2);
11160   } else {
11161     @<Make |c| look like a cycle of length one@>;
11162   }
11163 }
11164
11165 @ @<Make |c| look like a cycle of length one@>=
11166
11167   left_type(c)=mp_explicit; right_type(c)=mp_explicit;
11168   left_x(c)=x_coord(c); left_y(c)=y_coord(c);
11169   right_x(c)=x_coord(c); right_y(c)=y_coord(c);
11170 }
11171
11172 @ In degenerate situations we might have to look at the knot preceding~|q|.
11173 That knot is |p| but if |p<>c|, its coordinates have already been offset by |w|.
11174
11175 @<Set the incoming and outgoing directions at |q|; in case of...@>=
11176 dxin=x_coord(q)-left_x(q);
11177 dyin=y_coord(q)-left_y(q);
11178 if ( (dxin==0)&&(dyin==0) ) {
11179   dxin=x_coord(q)-right_x(p);
11180   dyin=y_coord(q)-right_y(p);
11181   if ( (dxin==0)&&(dyin==0) ) {
11182     dxin=x_coord(q)-x_coord(p);
11183     dyin=y_coord(q)-y_coord(p);
11184     if ( p!=c ) { /* the coordinates of |p| have been offset by |w| */
11185       dxin=dxin+x_coord(w);
11186       dyin=dyin+y_coord(w);
11187     }
11188   }
11189 }
11190 tmp=mp_pyth_add(mp, dxin,dyin);
11191 if ( tmp==0 ) {
11192   join_type=2;
11193 } else { 
11194   dxin=mp_make_fraction(mp, dxin,tmp);
11195   dyin=mp_make_fraction(mp, dyin,tmp);
11196   @<Set the outgoing direction at |q|@>;
11197 }
11198
11199 @ If |q=c| then the coordinates of |r| and the control points between |q|
11200 and~|r| have already been offset by |h|.
11201
11202 @<Set the outgoing direction at |q|@>=
11203 dxout=right_x(q)-x_coord(q);
11204 dyout=right_y(q)-y_coord(q);
11205 if ( (dxout==0)&&(dyout==0) ) {
11206   r=link(q);
11207   dxout=left_x(r)-x_coord(q);
11208   dyout=left_y(r)-y_coord(q);
11209   if ( (dxout==0)&&(dyout==0) ) {
11210     dxout=x_coord(r)-x_coord(q);
11211     dyout=y_coord(r)-y_coord(q);
11212   }
11213 }
11214 if ( q==c ) {
11215   dxout=dxout-x_coord(h);
11216   dyout=dyout-y_coord(h);
11217 }
11218 tmp=mp_pyth_add(mp, dxout,dyout);
11219 if ( tmp==0 ) mp_confusion(mp, "degenerate spec");
11220 @:this can't happen degerate spec}{\quad degenerate spec@>
11221 dxout=mp_make_fraction(mp, dxout,tmp);
11222 dyout=mp_make_fraction(mp, dyout,tmp)
11223
11224 @* \[23] Direction and intersection times.
11225 A path of length $n$ is defined parametrically by functions $x(t)$ and
11226 $y(t)$, for |0<=t<=n|; we can regard $t$ as the ``time'' at which the path
11227 reaches the point $\bigl(x(t),y(t)\bigr)$.  In this section of the program
11228 we shall consider operations that determine special times associated with
11229 given paths: the first time that a path travels in a given direction, and
11230 a pair of times at which two paths cross each other.
11231
11232 @ Let's start with the easier task. The function |find_direction_time| is
11233 given a direction |(x,y)| and a path starting at~|h|. If the path never
11234 travels in direction |(x,y)|, the direction time will be~|-1|; otherwise
11235 it will be nonnegative.
11236
11237 Certain anomalous cases can arise: If |(x,y)=(0,0)|, so that the given
11238 direction is undefined, the direction time will be~0. If $\bigl(x'(t),
11239 y'(t)\bigr)=(0,0)$, so that the path direction is undefined, it will be
11240 assumed to match any given direction at time~|t|.
11241
11242 The routine solves this problem in nondegenerate cases by rotating the path
11243 and the given direction so that |(x,y)=(1,0)|; i.e., the main task will be
11244 to find when a given path first travels ``due east.''
11245
11246 @c 
11247 scaled mp_find_direction_time (MP mp,scaled x, scaled y, pointer h) {
11248   scaled max; /* $\max\bigl(\vert x\vert,\vert y\vert\bigr)$ */
11249   pointer p,q; /* for list traversal */
11250   scaled n; /* the direction time at knot |p| */
11251   scaled tt; /* the direction time within a cubic */
11252   @<Other local variables for |find_direction_time|@>;
11253   @<Normalize the given direction for better accuracy;
11254     but |return| with zero result if it's zero@>;
11255   n=0; p=h; phi=0;
11256   while (1) { 
11257     if ( right_type(p)==mp_endpoint ) break;
11258     q=link(p);
11259     @<Rotate the cubic between |p| and |q|; then
11260       |goto found| if the rotated cubic travels due east at some time |tt|;
11261       but |break| if an entire cyclic path has been traversed@>;
11262     p=q; n=n+unity;
11263   }
11264   return (-unity);
11265 FOUND: 
11266   return (n+tt);
11267 }
11268
11269 @ @<Normalize the given direction for better accuracy...@>=
11270 if ( abs(x)<abs(y) ) { 
11271   x=mp_make_fraction(mp, x,abs(y));
11272   if ( y>0 ) y=fraction_one; else y=-fraction_one;
11273 } else if ( x==0 ) { 
11274   return 0;
11275 } else  { 
11276   y=mp_make_fraction(mp, y,abs(x));
11277   if ( x>0 ) x=fraction_one; else x=-fraction_one;
11278 }
11279
11280 @ Since we're interested in the tangent directions, we work with the
11281 derivative $${\textstyle1\over3}B'(x_0,x_1,x_2,x_3;t)=
11282 B(x_1-x_0,x_2-x_1,x_3-x_2;t)$$ instead of
11283 $B(x_0,x_1,x_2,x_3;t)$ itself. The derived coefficients are also scaled up
11284 in order to achieve better accuracy.
11285
11286 The given path may turn abruptly at a knot, and it might pass the critical
11287 tangent direction at such a time. Therefore we remember the direction |phi|
11288 in which the previous rotated cubic was traveling. (The value of |phi| will be
11289 undefined on the first cubic, i.e., when |n=0|.)
11290
11291 @<Rotate the cubic between |p| and |q|; then...@>=
11292 tt=0;
11293 @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples of the control
11294   points of the rotated derivatives@>;
11295 if ( y1==0 ) if ( x1>=0 ) goto FOUND;
11296 if ( n>0 ) { 
11297   @<Exit to |found| if an eastward direction occurs at knot |p|@>;
11298   if ( p==h ) break;
11299   };
11300 if ( (x3!=0)||(y3!=0) ) phi=mp_n_arg(mp, x3,y3);
11301 @<Exit to |found| if the curve whose derivatives are specified by
11302   |x1,x2,x3,y1,y2,y3| travels eastward at some time~|tt|@>
11303
11304 @ @<Other local variables for |find_direction_time|@>=
11305 scaled x1,x2,x3,y1,y2,y3;  /* multiples of rotated derivatives */
11306 angle theta,phi; /* angles of exit and entry at a knot */
11307 fraction t; /* temp storage */
11308
11309 @ @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples...@>=
11310 x1=right_x(p)-x_coord(p); x2=left_x(q)-right_x(p);
11311 x3=x_coord(q)-left_x(q);
11312 y1=right_y(p)-y_coord(p); y2=left_y(q)-right_y(p);
11313 y3=y_coord(q)-left_y(q);
11314 max=abs(x1);
11315 if ( abs(x2)>max ) max=abs(x2);
11316 if ( abs(x3)>max ) max=abs(x3);
11317 if ( abs(y1)>max ) max=abs(y1);
11318 if ( abs(y2)>max ) max=abs(y2);
11319 if ( abs(y3)>max ) max=abs(y3);
11320 if ( max==0 ) goto FOUND;
11321 while ( max<fraction_half ){ 
11322   max+=max; x1+=x1; x2+=x2; x3+=x3;
11323   y1+=y1; y2+=y2; y3+=y3;
11324 }
11325 t=x1; x1=mp_take_fraction(mp, x1,x)+mp_take_fraction(mp, y1,y);
11326 y1=mp_take_fraction(mp, y1,x)-mp_take_fraction(mp, t,y);
11327 t=x2; x2=mp_take_fraction(mp, x2,x)+mp_take_fraction(mp, y2,y);
11328 y2=mp_take_fraction(mp, y2,x)-mp_take_fraction(mp, t,y);
11329 t=x3; x3=mp_take_fraction(mp, x3,x)+mp_take_fraction(mp, y3,y);
11330 y3=mp_take_fraction(mp, y3,x)-mp_take_fraction(mp, t,y)
11331
11332 @ @<Exit to |found| if an eastward direction occurs at knot |p|@>=
11333 theta=mp_n_arg(mp, x1,y1);
11334 if ( theta>=0 ) if ( phi<=0 ) if ( phi>=theta-one_eighty_deg ) goto FOUND;
11335 if ( theta<=0 ) if ( phi>=0 ) if ( phi<=theta+one_eighty_deg ) goto FOUND
11336
11337 @ In this step we want to use the |crossing_point| routine to find the
11338 roots of the quadratic equation $B(y_1,y_2,y_3;t)=0$.
11339 Several complications arise: If the quadratic equation has a double root,
11340 the curve never crosses zero, and |crossing_point| will find nothing;
11341 this case occurs iff $y_1y_3=y_2^2$ and $y_1y_2<0$. If the quadratic
11342 equation has simple roots, or only one root, we may have to negate it
11343 so that $B(y_1,y_2,y_3;t)$ crosses from positive to negative at its first root.
11344 And finally, we need to do special things if $B(y_1,y_2,y_3;t)$ is
11345 identically zero.
11346
11347 @ @<Exit to |found| if the curve whose derivatives are specified by...@>=
11348 if ( x1<0 ) if ( x2<0 ) if ( x3<0 ) goto DONE;
11349 if ( mp_ab_vs_cd(mp, y1,y3,y2,y2)==0 ) {
11350   @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11351     either |goto found| or |goto done|@>;
11352 }
11353 if ( y1<=0 ) {
11354   if ( y1<0 ) { y1=-y1; y2=-y2; y3=-y3; }
11355   else if ( y2>0 ){ y2=-y2; y3=-y3; };
11356 }
11357 @<Check the places where $B(y_1,y_2,y_3;t)=0$ to see if
11358   $B(x_1,x_2,x_3;t)\ge0$@>;
11359 DONE:
11360
11361 @ The quadratic polynomial $B(y_1,y_2,y_3;t)$ begins |>=0| and has at most
11362 two roots, because we know that it isn't identically zero.
11363
11364 It must be admitted that the |crossing_point| routine is not perfectly accurate;
11365 rounding errors might cause it to find a root when $y_1y_3>y_2^2$, or to
11366 miss the roots when $y_1y_3<y_2^2$. The rotation process is itself
11367 subject to rounding errors. Yet this code optimistically tries to
11368 do the right thing.
11369
11370 @d we_found_it { tt=(t+04000) / 010000; goto FOUND; }
11371
11372 @<Check the places where $B(y_1,y_2,y_3;t)=0$...@>=
11373 t=mp_crossing_point(mp, y1,y2,y3);
11374 if ( t>fraction_one ) goto DONE;
11375 y2=t_of_the_way(y2,y3);
11376 x1=t_of_the_way(x1,x2);
11377 x2=t_of_the_way(x2,x3);
11378 x1=t_of_the_way(x1,x2);
11379 if ( x1>=0 ) we_found_it;
11380 if ( y2>0 ) y2=0;
11381 tt=t; t=mp_crossing_point(mp, 0,-y2,-y3);
11382 if ( t>fraction_one ) goto DONE;
11383 x1=t_of_the_way(x1,x2);
11384 x2=t_of_the_way(x2,x3);
11385 if ( t_of_the_way(x1,x2)>=0 ) { 
11386   t=t_of_the_way(tt,fraction_one); we_found_it;
11387 }
11388
11389 @ @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11390     either |goto found| or |goto done|@>=
11391
11392   if ( mp_ab_vs_cd(mp, y1,y2,0,0)<0 ) {
11393     t=mp_make_fraction(mp, y1,y1-y2);
11394     x1=t_of_the_way(x1,x2);
11395     x2=t_of_the_way(x2,x3);
11396     if ( t_of_the_way(x1,x2)>=0 ) we_found_it;
11397   } else if ( y3==0 ) {
11398     if ( y1==0 ) {
11399       @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|@>;
11400     } else if ( x3>=0 ) {
11401       tt=unity; goto FOUND;
11402     }
11403   }
11404   goto DONE;
11405 }
11406
11407 @ At this point we know that the derivative of |y(t)| is identically zero,
11408 and that |x1<0|; but either |x2>=0| or |x3>=0|, so there's some hope of
11409 traveling east.
11410
11411 @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|...@>=
11412
11413   t=mp_crossing_point(mp, -x1,-x2,-x3);
11414   if ( t<=fraction_one ) we_found_it;
11415   if ( mp_ab_vs_cd(mp, x1,x3,x2,x2)<=0 ) { 
11416     t=mp_make_fraction(mp, x1,x1-x2); we_found_it;
11417   }
11418 }
11419
11420 @ The intersection of two cubics can be found by an interesting variant
11421 of the general bisection scheme described in the introduction to
11422 |crossing_point|.\
11423 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)$,
11424 we wish to find a pair of times $(t_1,t_2)$ such that $w(t_1)=z(t_2)$,
11425 if an intersection exists. First we find the smallest rectangle that
11426 encloses the points $\{w_0,w_1,w_2,w_3\}$ and check that it overlaps
11427 the smallest rectangle that encloses
11428 $\{z_0,z_1,z_2,z_3\}$; if not, the cubics certainly don't intersect.
11429 But if the rectangles do overlap, we bisect the intervals, getting
11430 new cubics $w'$ and~$w''$, $z'$~and~$z''$; the intersection routine first
11431 tries for an intersection between $w'$ and~$z'$, then (if unsuccessful)
11432 between $w'$ and~$z''$, then (if still unsuccessful) between $w''$ and~$z'$,
11433 finally (if thrice unsuccessful) between $w''$ and~$z''$. After $l$~successful
11434 levels of bisection we will have determined the intersection times $t_1$
11435 and~$t_2$ to $l$~bits of accuracy.
11436
11437 \def\submin{_{\rm min}} \def\submax{_{\rm max}}
11438 As before, it is better to work with the numbers $W_k=2^l(w_k-w_{k-1})$
11439 and $Z_k=2^l(z_k-z_{k-1})$ rather than the coefficients $w_k$ and $z_k$
11440 themselves. We also need one other quantity, $\Delta=2^l(w_0-z_0)$,
11441 to determine when the enclosing rectangles overlap. Here's why:
11442 The $x$~coordinates of~$w(t)$ are between $u\submin$ and $u\submax$,
11443 and the $x$~coordinates of~$z(t)$ are between $x\submin$ and $x\submax$,
11444 if we write $w_k=(u_k,v_k)$ and $z_k=(x_k,y_k)$ and $u\submin=
11445 \min(u_0,u_1,u_2,u_3)$, etc. These intervals of $x$~coordinates
11446 overlap if and only if $u\submin\L x\submax$ and
11447 $x\submin\L u\submax$. Letting
11448 $$U\submin=\min(0,U_1,U_1+U_2,U_1+U_2+U_3),\;
11449   U\submax=\max(0,U_1,U_1+U_2,U_1+U_2+U_3),$$
11450 we have $u\submin=2^lu_0+U\submin$, etc.; the condition for overlap
11451 reduces to
11452 $$X\submin-U\submax\L 2^l(u_0-x_0)\L X\submax-U\submin.$$
11453 Thus we want to maintain the quantity $2^l(u_0-x_0)$; similarly,
11454 the quantity $2^l(v_0-y_0)$ accounts for the $y$~coordinates. The
11455 coordinates of $\Delta=2^l(w_0-z_0)$ must stay bounded as $l$ increases,
11456 because of the overlap condition; i.e., we know that $X\submin$,
11457 $X\submax$, and their relatives are bounded, hence $X\submax-
11458 U\submin$ and $X\submin-U\submax$ are bounded.
11459
11460 @ Incidentally, if the given cubics intersect more than once, the process
11461 just sketched will not necessarily find the lexicographically smallest pair
11462 $(t_1,t_2)$. The solution actually obtained will be smallest in ``shuffled
11463 order''; i.e., if $t_1=(.a_1a_2\ldots a_{16})_2$ and
11464 $t_2=(.b_1b_2\ldots b_{16})_2$, then we will minimize
11465 $a_1b_1a_2b_2\ldots a_{16}b_{16}$, not
11466 $a_1a_2\ldots a_{16}b_1b_2\ldots b_{16}$.
11467 Shuffled order agrees with lexicographic order if all pairs of solutions
11468 $(t_1,t_2)$ and $(t_1',t_2')$ have the property that $t_1<t_1'$ iff
11469 $t_2<t_2'$; but in general, lexicographic order can be quite different,
11470 and the bisection algorithm would be substantially less efficient if it were
11471 constrained by lexicographic order.
11472
11473 For example, suppose that an overlap has been found for $l=3$ and
11474 $(t_1,t_2)= (.101,.011)$ in binary, but that no overlap is produced by
11475 either of the alternatives $(.1010,.0110)$, $(.1010,.0111)$ at level~4.
11476 Then there is probably an intersection in one of the subintervals
11477 $(.1011,.011x)$; but lexicographic order would require us to explore
11478 $(.1010,.1xxx)$ and $(.1011,.00xx)$ and $(.1011,.010x)$ first. We wouldn't
11479 want to store all of the subdivision data for the second path, so the
11480 subdivisions would have to be regenerated many times. Such inefficiencies
11481 would be associated with every `1' in the binary representation of~$t_1$.
11482
11483 @ The subdivision process introduces rounding errors, hence we need to
11484 make a more liberal test for overlap. It is not hard to show that the
11485 computed values of $U_i$ differ from the truth by at most~$l$, on
11486 level~$l$, hence $U\submin$ and $U\submax$ will be at most $3l$ in error.
11487 If $\beta$ is an upper bound on the absolute error in the computed
11488 components of $\Delta=(|delx|,|dely|)$ on level~$l$, we will replace
11489 the test `$X\submin-U\submax\L|delx|$' by the more liberal test
11490 `$X\submin-U\submax\L|delx|+|tol|$', where $|tol|=6l+\beta$.
11491
11492 More accuracy is obtained if we try the algorithm first with |tol=0|;
11493 the more liberal tolerance is used only if an exact approach fails.
11494 It is convenient to do this double-take by letting `3' in the preceding
11495 paragraph be a parameter, which is first 0, then 3.
11496
11497 @<Glob...@>=
11498 unsigned int tol_step; /* either 0 or 3, usually */
11499
11500 @ We shall use an explicit stack to implement the recursive bisection
11501 method described above. The |bisect_stack| array will contain numerous 5-word
11502 packets like $(U_1,U_2,U_3,U\submin,U\submax)$, as well as 20-word packets
11503 comprising the 5-word packets for $U$, $V$, $X$, and~$Y$.
11504
11505 The following macros define the allocation of stack positions to
11506 the quantities needed for bisection-intersection.
11507
11508 @d stack_1(A) mp->bisect_stack[(A)] /* $U_1$, $V_1$, $X_1$, or $Y_1$ */
11509 @d stack_2(A) mp->bisect_stack[(A)+1] /* $U_2$, $V_2$, $X_2$, or $Y_2$ */
11510 @d stack_3(A) mp->bisect_stack[(A)+2] /* $U_3$, $V_3$, $X_3$, or $Y_3$ */
11511 @d stack_min(A) mp->bisect_stack[(A)+3]
11512   /* $U\submin$, $V\submin$, $X\submin$, or $Y\submin$ */
11513 @d stack_max(A) mp->bisect_stack[(A)+4]
11514   /* $U\submax$, $V\submax$, $X\submax$, or $Y\submax$ */
11515 @d int_packets 20 /* number of words to represent $U_k$, $V_k$, $X_k$, and $Y_k$ */
11516 @#
11517 @d u_packet(A) ((A)-5)
11518 @d v_packet(A) ((A)-10)
11519 @d x_packet(A) ((A)-15)
11520 @d y_packet(A) ((A)-20)
11521 @d l_packets (mp->bisect_ptr-int_packets)
11522 @d r_packets mp->bisect_ptr
11523 @d ul_packet u_packet(l_packets) /* base of $U'_k$ variables */
11524 @d vl_packet v_packet(l_packets) /* base of $V'_k$ variables */
11525 @d xl_packet x_packet(l_packets) /* base of $X'_k$ variables */
11526 @d yl_packet y_packet(l_packets) /* base of $Y'_k$ variables */
11527 @d ur_packet u_packet(r_packets) /* base of $U''_k$ variables */
11528 @d vr_packet v_packet(r_packets) /* base of $V''_k$ variables */
11529 @d xr_packet x_packet(r_packets) /* base of $X''_k$ variables */
11530 @d yr_packet y_packet(r_packets) /* base of $Y''_k$ variables */
11531 @#
11532 @d u1l stack_1(ul_packet) /* $U'_1$ */
11533 @d u2l stack_2(ul_packet) /* $U'_2$ */
11534 @d u3l stack_3(ul_packet) /* $U'_3$ */
11535 @d v1l stack_1(vl_packet) /* $V'_1$ */
11536 @d v2l stack_2(vl_packet) /* $V'_2$ */
11537 @d v3l stack_3(vl_packet) /* $V'_3$ */
11538 @d x1l stack_1(xl_packet) /* $X'_1$ */
11539 @d x2l stack_2(xl_packet) /* $X'_2$ */
11540 @d x3l stack_3(xl_packet) /* $X'_3$ */
11541 @d y1l stack_1(yl_packet) /* $Y'_1$ */
11542 @d y2l stack_2(yl_packet) /* $Y'_2$ */
11543 @d y3l stack_3(yl_packet) /* $Y'_3$ */
11544 @d u1r stack_1(ur_packet) /* $U''_1$ */
11545 @d u2r stack_2(ur_packet) /* $U''_2$ */
11546 @d u3r stack_3(ur_packet) /* $U''_3$ */
11547 @d v1r stack_1(vr_packet) /* $V''_1$ */
11548 @d v2r stack_2(vr_packet) /* $V''_2$ */
11549 @d v3r stack_3(vr_packet) /* $V''_3$ */
11550 @d x1r stack_1(xr_packet) /* $X''_1$ */
11551 @d x2r stack_2(xr_packet) /* $X''_2$ */
11552 @d x3r stack_3(xr_packet) /* $X''_3$ */
11553 @d y1r stack_1(yr_packet) /* $Y''_1$ */
11554 @d y2r stack_2(yr_packet) /* $Y''_2$ */
11555 @d y3r stack_3(yr_packet) /* $Y''_3$ */
11556 @#
11557 @d stack_dx mp->bisect_stack[mp->bisect_ptr] /* stacked value of |delx| */
11558 @d stack_dy mp->bisect_stack[mp->bisect_ptr+1] /* stacked value of |dely| */
11559 @d stack_tol mp->bisect_stack[mp->bisect_ptr+2] /* stacked value of |tol| */
11560 @d stack_uv mp->bisect_stack[mp->bisect_ptr+3] /* stacked value of |uv| */
11561 @d stack_xy mp->bisect_stack[mp->bisect_ptr+4] /* stacked value of |xy| */
11562 @d int_increment (int_packets+int_packets+5) /* number of stack words per level */
11563
11564 @<Glob...@>=
11565 integer *bisect_stack;
11566 unsigned int bisect_ptr;
11567
11568 @ @<Allocate or initialize ...@>=
11569 mp->bisect_stack = xmalloc((bistack_size+1),sizeof(integer));
11570
11571 @ @<Dealloc variables@>=
11572 xfree(mp->bisect_stack);
11573
11574 @ @<Check the ``constant''...@>=
11575 if ( int_packets+17*int_increment>bistack_size ) mp->bad=19;
11576
11577 @ Computation of the min and max is a tedious but fairly fast sequence of
11578 instructions; exactly four comparisons are made in each branch.
11579
11580 @d set_min_max(A) 
11581   if ( stack_1((A))<0 ) {
11582     if ( stack_3((A))>=0 ) {
11583       if ( stack_2((A))<0 ) stack_min((A))=stack_1((A))+stack_2((A));
11584       else stack_min((A))=stack_1((A));
11585       stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11586       if ( stack_max((A))<0 ) stack_max((A))=0;
11587     } else { 
11588       stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11589       if ( stack_min((A))>stack_1((A)) ) stack_min((A))=stack_1((A));
11590       stack_max((A))=stack_1((A))+stack_2((A));
11591       if ( stack_max((A))<0 ) stack_max((A))=0;
11592     }
11593   } else if ( stack_3((A))<=0 ) {
11594     if ( stack_2((A))>0 ) stack_max((A))=stack_1((A))+stack_2((A));
11595     else stack_max((A))=stack_1((A));
11596     stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11597     if ( stack_min((A))>0 ) stack_min((A))=0;
11598   } else  { 
11599     stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11600     if ( stack_max((A))<stack_1((A)) ) stack_max((A))=stack_1((A));
11601     stack_min((A))=stack_1((A))+stack_2((A));
11602     if ( stack_min((A))>0 ) stack_min((A))=0;
11603   }
11604
11605 @ It's convenient to keep the current values of $l$, $t_1$, and $t_2$ in
11606 the integer form $2^l+2^lt_1$ and $2^l+2^lt_2$. The |cubic_intersection|
11607 routine uses global variables |cur_t| and |cur_tt| for this purpose;
11608 after successful completion, |cur_t| and |cur_tt| will contain |unity|
11609 plus the |scaled| values of $t_1$ and~$t_2$.
11610
11611 The values of |cur_t| and |cur_tt| will be set to zero if |cubic_intersection|
11612 finds no intersection. The routine gives up and gives an approximate answer
11613 if it has backtracked
11614 more than 5000 times (otherwise there are cases where several minutes
11615 of fruitless computation would be possible).
11616
11617 @d max_patience 5000
11618
11619 @<Glob...@>=
11620 integer cur_t;integer cur_tt; /* controls and results of |cubic_intersection| */
11621 integer time_to_go; /* this many backtracks before giving up */
11622 integer max_t; /* maximum of $2^{l+1}$ so far achieved */
11623
11624 @ The given cubics $B(w_0,w_1,w_2,w_3;t)$ and
11625 $B(z_0,z_1,z_2,z_3;t)$ are specified in adjacent knot nodes |(p,link(p))|
11626 and |(pp,link(pp))|, respectively.
11627
11628 @c void mp_cubic_intersection (MP mp,pointer p, pointer pp) {
11629   pointer q,qq; /* |link(p)|, |link(pp)| */
11630   mp->time_to_go=max_patience; mp->max_t=2;
11631   @<Initialize for intersections at level zero@>;
11632 CONTINUE:
11633   while (1) { 
11634     if ( mp->delx-mp->tol<=stack_max(x_packet(mp->xy))-stack_min(u_packet(mp->uv)))
11635     if ( mp->delx+mp->tol>=stack_min(x_packet(mp->xy))-stack_max(u_packet(mp->uv)))
11636     if ( mp->dely-mp->tol<=stack_max(y_packet(mp->xy))-stack_min(v_packet(mp->uv)))
11637     if ( mp->dely+mp->tol>=stack_min(y_packet(mp->xy))-stack_max(v_packet(mp->uv))) 
11638     { 
11639       if ( mp->cur_t>=mp->max_t ){ 
11640         if ( mp->max_t==two ) { /* we've done 17 bisections */ 
11641            mp->cur_t=halfp(mp->cur_t+1); mp->cur_tt=halfp(mp->cur_tt+1); return;
11642         }
11643         mp->max_t+=mp->max_t; mp->appr_t=mp->cur_t; mp->appr_tt=mp->cur_tt;
11644       }
11645       @<Subdivide for a new level of intersection@>;
11646       goto CONTINUE;
11647     }
11648     if ( mp->time_to_go>0 ) {
11649       decr(mp->time_to_go);
11650     } else { 
11651       while ( mp->appr_t<unity ) { 
11652         mp->appr_t+=mp->appr_t; mp->appr_tt+=mp->appr_tt;
11653       }
11654       mp->cur_t=mp->appr_t; mp->cur_tt=mp->appr_tt; return;
11655     }
11656     @<Advance to the next pair |(cur_t,cur_tt)|@>;
11657   }
11658 }
11659
11660 @ The following variables are global, although they are used only by
11661 |cubic_intersection|, because it is necessary on some machines to
11662 split |cubic_intersection| up into two procedures.
11663
11664 @<Glob...@>=
11665 integer delx;integer dely; /* the components of $\Delta=2^l(w_0-z_0)$ */
11666 integer tol; /* bound on the uncertainly in the overlap test */
11667 unsigned int uv;
11668 unsigned int xy; /* pointers to the current packets of interest */
11669 integer three_l; /* |tol_step| times the bisection level */
11670 integer appr_t;integer appr_tt; /* best approximations known to the answers */
11671
11672 @ We shall assume that the coordinates are sufficiently non-extreme that
11673 integer overflow will not occur.
11674
11675 @<Initialize for intersections at level zero@>=
11676 q=link(p); qq=link(pp); mp->bisect_ptr=int_packets;
11677 u1r=right_x(p)-x_coord(p); u2r=left_x(q)-right_x(p);
11678 u3r=x_coord(q)-left_x(q); set_min_max(ur_packet);
11679 v1r=right_y(p)-y_coord(p); v2r=left_y(q)-right_y(p);
11680 v3r=y_coord(q)-left_y(q); set_min_max(vr_packet);
11681 x1r=right_x(pp)-x_coord(pp); x2r=left_x(qq)-right_x(pp);
11682 x3r=x_coord(qq)-left_x(qq); set_min_max(xr_packet);
11683 y1r=right_y(pp)-y_coord(pp); y2r=left_y(qq)-right_y(pp);
11684 y3r=y_coord(qq)-left_y(qq); set_min_max(yr_packet);
11685 mp->delx=x_coord(p)-x_coord(pp); mp->dely=y_coord(p)-y_coord(pp);
11686 mp->tol=0; mp->uv=r_packets; mp->xy=r_packets; 
11687 mp->three_l=0; mp->cur_t=1; mp->cur_tt=1
11688
11689 @ @<Subdivide for a new level of intersection@>=
11690 stack_dx=mp->delx; stack_dy=mp->dely; stack_tol=mp->tol; 
11691 stack_uv=mp->uv; stack_xy=mp->xy;
11692 mp->bisect_ptr=mp->bisect_ptr+int_increment;
11693 mp->cur_t+=mp->cur_t; mp->cur_tt+=mp->cur_tt;
11694 u1l=stack_1(u_packet(mp->uv)); u3r=stack_3(u_packet(mp->uv));
11695 u2l=half(u1l+stack_2(u_packet(mp->uv)));
11696 u2r=half(u3r+stack_2(u_packet(mp->uv)));
11697 u3l=half(u2l+u2r); u1r=u3l;
11698 set_min_max(ul_packet); set_min_max(ur_packet);
11699 v1l=stack_1(v_packet(mp->uv)); v3r=stack_3(v_packet(mp->uv));
11700 v2l=half(v1l+stack_2(v_packet(mp->uv)));
11701 v2r=half(v3r+stack_2(v_packet(mp->uv)));
11702 v3l=half(v2l+v2r); v1r=v3l;
11703 set_min_max(vl_packet); set_min_max(vr_packet);
11704 x1l=stack_1(x_packet(mp->xy)); x3r=stack_3(x_packet(mp->xy));
11705 x2l=half(x1l+stack_2(x_packet(mp->xy)));
11706 x2r=half(x3r+stack_2(x_packet(mp->xy)));
11707 x3l=half(x2l+x2r); x1r=x3l;
11708 set_min_max(xl_packet); set_min_max(xr_packet);
11709 y1l=stack_1(y_packet(mp->xy)); y3r=stack_3(y_packet(mp->xy));
11710 y2l=half(y1l+stack_2(y_packet(mp->xy)));
11711 y2r=half(y3r+stack_2(y_packet(mp->xy)));
11712 y3l=half(y2l+y2r); y1r=y3l;
11713 set_min_max(yl_packet); set_min_max(yr_packet);
11714 mp->uv=l_packets; mp->xy=l_packets;
11715 mp->delx+=mp->delx; mp->dely+=mp->dely;
11716 mp->tol=mp->tol-mp->three_l+mp->tol_step; 
11717 mp->tol+=mp->tol; mp->three_l=mp->three_l+mp->tol_step
11718
11719 @ @<Advance to the next pair |(cur_t,cur_tt)|@>=
11720 NOT_FOUND: 
11721 if ( odd(mp->cur_tt) ) {
11722   if ( odd(mp->cur_t) ) {
11723      @<Descend to the previous level and |goto not_found|@>;
11724   } else { 
11725     incr(mp->cur_t);
11726     mp->delx=mp->delx+stack_1(u_packet(mp->uv))+stack_2(u_packet(mp->uv))
11727       +stack_3(u_packet(mp->uv));
11728     mp->dely=mp->dely+stack_1(v_packet(mp->uv))+stack_2(v_packet(mp->uv))
11729       +stack_3(v_packet(mp->uv));
11730     mp->uv=mp->uv+int_packets; /* switch from |l_packet| to |r_packet| */
11731     decr(mp->cur_tt); mp->xy=mp->xy-int_packets; 
11732          /* switch from |r_packet| to |l_packet| */
11733     mp->delx=mp->delx+stack_1(x_packet(mp->xy))+stack_2(x_packet(mp->xy))
11734       +stack_3(x_packet(mp->xy));
11735     mp->dely=mp->dely+stack_1(y_packet(mp->xy))+stack_2(y_packet(mp->xy))
11736       +stack_3(y_packet(mp->xy));
11737   }
11738 } else { 
11739   incr(mp->cur_tt); mp->tol=mp->tol+mp->three_l;
11740   mp->delx=mp->delx-stack_1(x_packet(mp->xy))-stack_2(x_packet(mp->xy))
11741     -stack_3(x_packet(mp->xy));
11742   mp->dely=mp->dely-stack_1(y_packet(mp->xy))-stack_2(y_packet(mp->xy))
11743     -stack_3(y_packet(mp->xy));
11744   mp->xy=mp->xy+int_packets; /* switch from |l_packet| to |r_packet| */
11745 }
11746
11747 @ @<Descend to the previous level...@>=
11748
11749   mp->cur_t=halfp(mp->cur_t); mp->cur_tt=halfp(mp->cur_tt);
11750   if ( mp->cur_t==0 ) return;
11751   mp->bisect_ptr=mp->bisect_ptr-int_increment; 
11752   mp->three_l=mp->three_l-mp->tol_step;
11753   mp->delx=stack_dx; mp->dely=stack_dy; mp->tol=stack_tol; 
11754   mp->uv=stack_uv; mp->xy=stack_xy;
11755   goto NOT_FOUND;
11756 }
11757
11758 @ The |path_intersection| procedure is much simpler.
11759 It invokes |cubic_intersection| in lexicographic order until finding a
11760 pair of cubics that intersect. The final intersection times are placed in
11761 |cur_t| and~|cur_tt|.
11762
11763 @c void mp_path_intersection (MP mp,pointer h, pointer hh) {
11764   pointer p,pp; /* link registers that traverse the given paths */
11765   integer n,nn; /* integer parts of intersection times, minus |unity| */
11766   @<Change one-point paths into dead cycles@>;
11767   mp->tol_step=0;
11768   do {  
11769     n=-unity; p=h;
11770     do {  
11771       if ( right_type(p)!=mp_endpoint ) { 
11772         nn=-unity; pp=hh;
11773         do {  
11774           if ( right_type(pp)!=mp_endpoint )  { 
11775             mp_cubic_intersection(mp, p,pp);
11776             if ( mp->cur_t>0 ) { 
11777               mp->cur_t=mp->cur_t+n; mp->cur_tt=mp->cur_tt+nn; 
11778               return;
11779             }
11780           }
11781           nn=nn+unity; pp=link(pp);
11782         } while (pp!=hh);
11783       }
11784       n=n+unity; p=link(p);
11785     } while (p!=h);
11786     mp->tol_step=mp->tol_step+3;
11787   } while (mp->tol_step<=3);
11788   mp->cur_t=-unity; mp->cur_tt=-unity;
11789 }
11790
11791 @ @<Change one-point paths...@>=
11792 if ( right_type(h)==mp_endpoint ) {
11793   right_x(h)=x_coord(h); left_x(h)=x_coord(h);
11794   right_y(h)=y_coord(h); left_y(h)=y_coord(h); right_type(h)=mp_explicit;
11795 }
11796 if ( right_type(hh)==mp_endpoint ) {
11797   right_x(hh)=x_coord(hh); left_x(hh)=x_coord(hh);
11798   right_y(hh)=y_coord(hh); left_y(hh)=y_coord(hh); right_type(hh)=mp_explicit;
11799 }
11800
11801 @* \[24] Dynamic linear equations.
11802 \MP\ users define variables implicitly by stating equations that should be
11803 satisfied; the computer is supposed to be smart enough to solve those equations.
11804 And indeed, the computer tries valiantly to do so, by distinguishing five
11805 different types of numeric values:
11806
11807 \smallskip\hang
11808 |type(p)=mp_known| is the nice case, when |value(p)| is the |scaled| value
11809 of the variable whose address is~|p|.
11810
11811 \smallskip\hang
11812 |type(p)=mp_dependent| means that |value(p)| is not present, but |dep_list(p)|
11813 points to a {\sl dependency list\/} that expresses the value of variable~|p|
11814 as a |scaled| number plus a sum of independent variables with |fraction|
11815 coefficients.
11816
11817 \smallskip\hang
11818 |type(p)=mp_independent| means that |value(p)=64s+m|, where |s>0| is a ``serial
11819 number'' reflecting the time this variable was first used in an equation;
11820 also |0<=m<64|, and each dependent variable
11821 that refers to this one is actually referring to the future value of
11822 this variable times~$2^m$. (Usually |m=0|, but higher degrees of
11823 scaling are sometimes needed to keep the coefficients in dependency lists
11824 from getting too large. The value of~|m| will always be even.)
11825
11826 \smallskip\hang
11827 |type(p)=mp_numeric_type| means that variable |p| hasn't appeared in an
11828 equation before, but it has been explicitly declared to be numeric.
11829
11830 \smallskip\hang
11831 |type(p)=undefined| means that variable |p| hasn't appeared before.
11832
11833 \smallskip\noindent
11834 We have actually discussed these five types in the reverse order of their
11835 history during a computation: Once |known|, a variable never again
11836 becomes |dependent|; once |dependent|, it almost never again becomes
11837 |mp_independent|; once |mp_independent|, it never again becomes |mp_numeric_type|;
11838 and once |mp_numeric_type|, it never again becomes |undefined| (except
11839 of course when the user specifically decides to scrap the old value
11840 and start again). A backward step may, however, take place: Sometimes
11841 a |dependent| variable becomes |mp_independent| again, when one of the
11842 independent variables it depends on is reverting to |undefined|.
11843
11844
11845 The next patch detects overflow of independent-variable serial
11846 numbers. Diagnosed and patched by Thorsten Dahlheimer.
11847
11848 @d s_scale 64 /* the serial numbers are multiplied by this factor */
11849 @d max_indep_vars 0177777777 /* $2^{25}-1$ */
11850 @d max_serial_no 017777777700 /* |max_indep_vars*s_scale| */
11851 @d new_indep(A)  /* create a new independent variable */
11852   { if ( mp->serial_no==max_serial_no )
11853     mp_fatal_error(mp, "variable instance identifiers exhausted");
11854   type((A))=mp_independent; mp->serial_no=mp->serial_no+s_scale;
11855   value((A))=mp->serial_no;
11856   }
11857
11858 @<Glob...@>=
11859 integer serial_no; /* the most recent serial number, times |s_scale| */
11860
11861 @ @<Make variable |q+s| newly independent@>=new_indep(q+s)
11862
11863 @ But how are dependency lists represented? It's simple: The linear combination
11864 $\alpha_1v_1+\cdots+\alpha_kv_k+\beta$ appears in |k+1| value nodes. If
11865 |q=dep_list(p)| points to this list, and if |k>0|, then |value(q)=
11866 @t$\alpha_1$@>| (which is a |fraction|); |info(q)| points to the location
11867 of $\alpha_1$; and |link(p)| points to the dependency list
11868 $\alpha_2v_2+\cdots+\alpha_kv_k+\beta$. On the other hand if |k=0|,
11869 then |value(q)=@t$\beta$@>| (which is |scaled|) and |info(q)=null|.
11870 The independent variables $v_1$, \dots,~$v_k$ have been sorted so that
11871 they appear in decreasing order of their |value| fields (i.e., of
11872 their serial numbers). \ (It is convenient to use decreasing order,
11873 since |value(null)=0|. If the independent variables were not sorted by
11874 serial number but by some other criterion, such as their location in |mem|,
11875 the equation-solving mechanism would be too system-dependent, because
11876 the ordering can affect the computed results.)
11877
11878 The |link| field in the node that contains the constant term $\beta$ is
11879 called the {\sl final link\/} of the dependency list. \MP\ maintains
11880 a doubly-linked master list of all dependency lists, in terms of a permanently
11881 allocated node
11882 in |mem| called |dep_head|. If there are no dependencies, we have
11883 |link(dep_head)=dep_head| and |prev_dep(dep_head)=dep_head|;
11884 otherwise |link(dep_head)| points to the first dependent variable, say~|p|,
11885 and |prev_dep(p)=dep_head|. We have |type(p)=mp_dependent|, and |dep_list(p)|
11886 points to its dependency list. If the final link of that dependency list
11887 occurs in location~|q|, then |link(q)| points to the next dependent
11888 variable (say~|r|); and we have |prev_dep(r)=q|, etc.
11889
11890 @d dep_list(A) link(value_loc((A)))
11891   /* half of the |value| field in a |dependent| variable */
11892 @d prev_dep(A) info(value_loc((A)))
11893   /* the other half; makes a doubly linked list */
11894 @d dep_node_size 2 /* the number of words per dependency node */
11895
11896 @<Initialize table entries...@>= mp->serial_no=0;
11897 link(dep_head)=dep_head; prev_dep(dep_head)=dep_head;
11898 info(dep_head)=null; dep_list(dep_head)=null;
11899
11900 @ Actually the description above contains a little white lie. There's
11901 another kind of variable called |mp_proto_dependent|, which is
11902 just like a |dependent| one except that the $\alpha$ coefficients
11903 in its dependency list are |scaled| instead of being fractions.
11904 Proto-dependency lists are mixed with dependency lists in the
11905 nodes reachable from |dep_head|.
11906
11907 @ Here is a procedure that prints a dependency list in symbolic form.
11908 The second parameter should be either |dependent| or |mp_proto_dependent|,
11909 to indicate the scaling of the coefficients.
11910
11911 @<Declare subroutines for printing expressions@>=
11912 void mp_print_dependency (MP mp,pointer p, small_number t) {
11913   integer v; /* a coefficient */
11914   pointer pp,q; /* for list manipulation */
11915   pp=p;
11916   while (1) { 
11917     v=abs(value(p)); q=info(p);
11918     if ( q==null ) { /* the constant term */
11919       if ( (v!=0)||(p==pp) ) {
11920          if ( value(p)>0 ) if ( p!=pp ) mp_print_char(mp, '+');
11921          mp_print_scaled(mp, value(p));
11922       }
11923       return;
11924     }
11925     @<Print the coefficient, unless it's $\pm1.0$@>;
11926     if ( type(q)!=mp_independent ) mp_confusion(mp, "dep");
11927 @:this can't happen dep}{\quad dep@>
11928     mp_print_variable_name(mp, q); v=value(q) % s_scale;
11929     while ( v>0 ) { mp_print(mp, "*4"); v=v-2; }
11930     p=link(p);
11931   }
11932 }
11933
11934 @ @<Print the coefficient, unless it's $\pm1.0$@>=
11935 if ( value(p)<0 ) mp_print_char(mp, '-');
11936 else if ( p!=pp ) mp_print_char(mp, '+');
11937 if ( t==mp_dependent ) v=mp_round_fraction(mp, v);
11938 if ( v!=unity ) mp_print_scaled(mp, v)
11939
11940 @ The maximum absolute value of a coefficient in a given dependency list
11941 is returned by the following simple function.
11942
11943 @c fraction mp_max_coef (MP mp,pointer p) {
11944   fraction x; /* the maximum so far */
11945   x=0;
11946   while ( info(p)!=null ) {
11947     if ( abs(value(p))>x ) x=abs(value(p));
11948     p=link(p);
11949   }
11950   return x;
11951 }
11952
11953 @ One of the main operations needed on dependency lists is to add a multiple
11954 of one list to the other; we call this |p_plus_fq|, where |p| and~|q| point
11955 to dependency lists and |f| is a fraction.
11956
11957 If the coefficient of any independent variable becomes |coef_bound| or
11958 more, in absolute value, this procedure changes the type of that variable
11959 to `|independent_needing_fix|', and sets the global variable |fix_needed|
11960 to~|true|. The value of $|coef_bound|=\mu$ is chosen so that
11961 $\mu^2+\mu<8$; this means that the numbers we deal with won't
11962 get too large. (Instead of the ``optimum'' $\mu=(\sqrt{33}-1)/2\approx
11963 2.3723$, the safer value 7/3 is taken as the threshold.)
11964
11965 The changes mentioned in the preceding paragraph are actually done only if
11966 the global variable |watch_coefs| is |true|. But it usually is; in fact,
11967 it is |false| only when \MP\ is making a dependency list that will soon
11968 be equated to zero.
11969
11970 Several procedures that act on dependency lists, including |p_plus_fq|,
11971 set the global variable |dep_final| to the final (constant term) node of
11972 the dependency list that they produce.
11973
11974 @d coef_bound 04525252525 /* |fraction| approximation to 7/3 */
11975 @d independent_needing_fix 0
11976
11977 @<Glob...@>=
11978 boolean fix_needed; /* does at least one |independent| variable need scaling? */
11979 boolean watch_coefs; /* should we scale coefficients that exceed |coef_bound|? */
11980 pointer dep_final; /* location of the constant term and final link */
11981
11982 @ @<Set init...@>=
11983 mp->fix_needed=false; mp->watch_coefs=true;
11984
11985 @ The |p_plus_fq| procedure has a fourth parameter, |t|, that should be
11986 set to |mp_proto_dependent| if |p| is a proto-dependency list. In this
11987 case |f| will be |scaled|, not a |fraction|. Similarly, the fifth parameter~|tt|
11988 should be |mp_proto_dependent| if |q| is a proto-dependency list.
11989
11990 List |q| is unchanged by the operation; but list |p| is totally destroyed.
11991
11992 The final link of the dependency list or proto-dependency list returned
11993 by |p_plus_fq| is the same as the original final link of~|p|. Indeed, the
11994 constant term of the result will be located in the same |mem| location
11995 as the original constant term of~|p|.
11996
11997 Coefficients of the result are assumed to be zero if they are less than
11998 a certain threshold. This compensates for inevitable rounding errors,
11999 and tends to make more variables `|known|'. The threshold is approximately
12000 $10^{-5}$ in the case of normal dependency lists, $10^{-4}$ for
12001 proto-dependencies.
12002
12003 @d fraction_threshold 2685 /* a |fraction| coefficient less than this is zeroed */
12004 @d half_fraction_threshold 1342 /* half of |fraction_threshold| */
12005 @d scaled_threshold 8 /* a |scaled| coefficient less than this is zeroed */
12006 @d half_scaled_threshold 4 /* half of |scaled_threshold| */
12007
12008 @<Declare basic dependency-list subroutines@>=
12009 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
12010                       pointer q, small_number t, small_number tt) ;
12011
12012 @ @c
12013 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
12014                       pointer q, small_number t, small_number tt) {
12015   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
12016   pointer r,s; /* for list manipulation */
12017   integer mp_threshold; /* defines a neighborhood of zero */
12018   integer v; /* temporary register */
12019   if ( t==mp_dependent ) mp_threshold=fraction_threshold;
12020   else mp_threshold=scaled_threshold;
12021   r=temp_head; pp=info(p); qq=info(q);
12022   while (1) {
12023     if ( pp==qq ) {
12024       if ( pp==null ) {
12025        break;
12026       } else {
12027         @<Contribute a term from |p|, plus |f| times the
12028           corresponding term from |q|@>
12029       }
12030     } else if ( value(pp)<value(qq) ) {
12031       @<Contribute a term from |q|, multiplied by~|f|@>
12032     } else { 
12033      link(r)=p; r=p; p=link(p); pp=info(p);
12034     }
12035   }
12036   if ( t==mp_dependent )
12037     value(p)=mp_slow_add(mp, value(p),mp_take_fraction(mp, value(q),f));
12038   else  
12039     value(p)=mp_slow_add(mp, value(p),mp_take_scaled(mp, value(q),f));
12040   link(r)=p; mp->dep_final=p; 
12041   return link(temp_head);
12042 }
12043
12044 @ @<Contribute a term from |p|, plus |f|...@>=
12045
12046   if ( tt==mp_dependent ) v=value(p)+mp_take_fraction(mp, f,value(q));
12047   else v=value(p)+mp_take_scaled(mp, f,value(q));
12048   value(p)=v; s=p; p=link(p);
12049   if ( abs(v)<mp_threshold ) {
12050     mp_free_node(mp, s,dep_node_size);
12051   } else {
12052     if ( (abs(v)>=coef_bound)  && mp->watch_coefs ) { 
12053       type(qq)=independent_needing_fix; mp->fix_needed=true;
12054     }
12055     link(r)=s; r=s;
12056   };
12057   pp=info(p); q=link(q); qq=info(q);
12058 }
12059
12060 @ @<Contribute a term from |q|, multiplied by~|f|@>=
12061
12062   if ( tt==mp_dependent ) v=mp_take_fraction(mp, f,value(q));
12063   else v=mp_take_scaled(mp, f,value(q));
12064   if ( abs(v)>halfp(mp_threshold) ) { 
12065     s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=v;
12066     if ( (abs(v)>=coef_bound) && mp->watch_coefs ) { 
12067       type(qq)=independent_needing_fix; mp->fix_needed=true;
12068     }
12069     link(r)=s; r=s;
12070   }
12071   q=link(q); qq=info(q);
12072 }
12073
12074 @ It is convenient to have another subroutine for the special case
12075 of |p_plus_fq| when |f=1.0|. In this routine lists |p| and |q| are
12076 both of the same type~|t| (either |dependent| or |mp_proto_dependent|).
12077
12078 @c pointer mp_p_plus_q (MP mp,pointer p, pointer q, small_number t) {
12079   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
12080   pointer r,s; /* for list manipulation */
12081   integer mp_threshold; /* defines a neighborhood of zero */
12082   integer v; /* temporary register */
12083   if ( t==mp_dependent ) mp_threshold=fraction_threshold;
12084   else mp_threshold=scaled_threshold;
12085   r=temp_head; pp=info(p); qq=info(q);
12086   while (1) {
12087     if ( pp==qq ) {
12088       if ( pp==null ) {
12089         break;
12090       } else {
12091         @<Contribute a term from |p|, plus the
12092           corresponding term from |q|@>
12093       }
12094     } else if ( value(pp)<value(qq) ) {
12095       s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=value(q);
12096       q=link(q); qq=info(q); link(r)=s; r=s;
12097     } else { 
12098       link(r)=p; r=p; p=link(p); pp=info(p);
12099     }
12100   }
12101   value(p)=mp_slow_add(mp, value(p),value(q));
12102   link(r)=p; mp->dep_final=p; 
12103   return link(temp_head);
12104 }
12105
12106 @ @<Contribute a term from |p|, plus the...@>=
12107
12108   v=value(p)+value(q);
12109   value(p)=v; s=p; p=link(p); pp=info(p);
12110   if ( abs(v)<mp_threshold ) {
12111     mp_free_node(mp, s,dep_node_size);
12112   } else { 
12113     if ( (abs(v)>=coef_bound ) && mp->watch_coefs ) {
12114       type(qq)=independent_needing_fix; mp->fix_needed=true;
12115     }
12116     link(r)=s; r=s;
12117   }
12118   q=link(q); qq=info(q);
12119 }
12120
12121 @ A somewhat simpler routine will multiply a dependency list
12122 by a given constant~|v|. The constant is either a |fraction| less than
12123 |fraction_one|, or it is |scaled|. In the latter case we might be forced to
12124 convert a dependency list to a proto-dependency list.
12125 Parameters |t0| and |t1| are the list types before and after;
12126 they should agree unless |t0=mp_dependent| and |t1=mp_proto_dependent|
12127 and |v_is_scaled=true|.
12128
12129 @c pointer mp_p_times_v (MP mp,pointer p, integer v, small_number t0,
12130                          small_number t1, boolean v_is_scaled) {
12131   pointer r,s; /* for list manipulation */
12132   integer w; /* tentative coefficient */
12133   integer mp_threshold;
12134   boolean scaling_down;
12135   if ( t0!=t1 ) scaling_down=true; else scaling_down=! v_is_scaled;
12136   if ( t1==mp_dependent ) mp_threshold=half_fraction_threshold;
12137   else mp_threshold=half_scaled_threshold;
12138   r=temp_head;
12139   while ( info(p)!=null ) {    
12140     if ( scaling_down ) w=mp_take_fraction(mp, v,value(p));
12141     else w=mp_take_scaled(mp, v,value(p));
12142     if ( abs(w)<=mp_threshold ) { 
12143       s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
12144     } else {
12145       if ( abs(w)>=coef_bound ) { 
12146         mp->fix_needed=true; type(info(p))=independent_needing_fix;
12147       }
12148       link(r)=p; r=p; value(p)=w; p=link(p);
12149     }
12150   }
12151   link(r)=p;
12152   if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
12153   else value(p)=mp_take_fraction(mp, value(p),v);
12154   return link(temp_head);
12155 };
12156
12157 @ Similarly, we sometimes need to divide a dependency list
12158 by a given |scaled| constant.
12159
12160 @<Declare basic dependency-list subroutines@>=
12161 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number 
12162   t0, small_number t1) ;
12163
12164 @ @c
12165 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number 
12166   t0, small_number t1) {
12167   pointer r,s; /* for list manipulation */
12168   integer w; /* tentative coefficient */
12169   integer mp_threshold;
12170   boolean scaling_down;
12171   if ( t0!=t1 ) scaling_down=true; else scaling_down=false;
12172   if ( t1==mp_dependent ) mp_threshold=half_fraction_threshold;
12173   else mp_threshold=half_scaled_threshold;
12174   r=temp_head;
12175   while ( info( p)!=null ) {
12176     if ( scaling_down ) {
12177       if ( abs(v)<02000000 ) w=mp_make_scaled(mp, value(p),v*010000);
12178       else w=mp_make_scaled(mp, mp_round_fraction(mp, value(p)),v);
12179     } else {
12180       w=mp_make_scaled(mp, value(p),v);
12181     }
12182     if ( abs(w)<=mp_threshold ) {
12183       s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
12184     } else { 
12185       if ( abs(w)>=coef_bound ) {
12186          mp->fix_needed=true; type(info(p))=independent_needing_fix;
12187       }
12188       link(r)=p; r=p; value(p)=w; p=link(p);
12189     }
12190   }
12191   link(r)=p; value(p)=mp_make_scaled(mp, value(p),v);
12192   return link(temp_head);
12193 };
12194
12195 @ Here's another utility routine for dependency lists. When an independent
12196 variable becomes dependent, we want to remove it from all existing
12197 dependencies. The |p_with_x_becoming_q| function computes the
12198 dependency list of~|p| after variable~|x| has been replaced by~|q|.
12199
12200 This procedure has basically the same calling conventions as |p_plus_fq|:
12201 List~|q| is unchanged; list~|p| is destroyed; the constant node and the
12202 final link are inherited from~|p|; and the fourth parameter tells whether
12203 or not |p| is |mp_proto_dependent|. However, the global variable |dep_final|
12204 is not altered if |x| does not occur in list~|p|.
12205
12206 @c pointer mp_p_with_x_becoming_q (MP mp,pointer p,
12207            pointer x, pointer q, small_number t) {
12208   pointer r,s; /* for list manipulation */
12209   integer v; /* coefficient of |x| */
12210   integer sx; /* serial number of |x| */
12211   s=p; r=temp_head; sx=value(x);
12212   while ( value(info(s))>sx ) { r=s; s=link(s); };
12213   if ( info(s)!=x ) { 
12214     return p;
12215   } else { 
12216     link(temp_head)=p; link(r)=link(s); v=value(s);
12217     mp_free_node(mp, s,dep_node_size);
12218     return mp_p_plus_fq(mp, link(temp_head),v,q,t,mp_dependent);
12219   }
12220 }
12221
12222 @ Here's a simple procedure that reports an error when a variable
12223 has just received a known value that's out of the required range.
12224
12225 @<Declare basic dependency-list subroutines@>=
12226 void mp_val_too_big (MP mp,scaled x) ;
12227
12228 @ @c void mp_val_too_big (MP mp,scaled x) { 
12229   if ( mp->internal[mp_warning_check]>0 ) { 
12230     print_err("Value is too large ("); mp_print_scaled(mp, x); mp_print_char(mp, ')');
12231 @.Value is too large@>
12232     help4("The equation I just processed has given some variable")
12233       ("a value of 4096 or more. Continue and I'll try to cope")
12234       ("with that big value; but it might be dangerous.")
12235       ("(Set warningcheck:=0 to suppress this message.)");
12236     mp_error(mp);
12237   }
12238 }
12239
12240 @ When a dependent variable becomes known, the following routine
12241 removes its dependency list. Here |p| points to the variable, and
12242 |q| points to the dependency list (which is one node long).
12243
12244 @<Declare basic dependency-list subroutines@>=
12245 void mp_make_known (MP mp,pointer p, pointer q) ;
12246
12247 @ @c void mp_make_known (MP mp,pointer p, pointer q) {
12248   int t; /* the previous type */
12249   prev_dep(link(q))=prev_dep(p);
12250   link(prev_dep(p))=link(q); t=type(p);
12251   type(p)=mp_known; value(p)=value(q); mp_free_node(mp, q,dep_node_size);
12252   if ( abs(value(p))>=fraction_one ) mp_val_too_big(mp, value(p));
12253   if (( mp->internal[mp_tracing_equations]>0) && mp_interesting(mp, p) ) {
12254     mp_begin_diagnostic(mp); mp_print_nl(mp, "#### ");
12255 @:]]]\#\#\#\#_}{\.{\#\#\#\#}@>
12256     mp_print_variable_name(mp, p); 
12257     mp_print_char(mp, '='); mp_print_scaled(mp, value(p));
12258     mp_end_diagnostic(mp, false);
12259   }
12260   if (( mp->cur_exp==p ) && mp->cur_type==t ) {
12261     mp->cur_type=mp_known; mp->cur_exp=value(p);
12262     mp_free_node(mp, p,value_node_size);
12263   }
12264 }
12265
12266 @ The |fix_dependencies| routine is called into action when |fix_needed|
12267 has been triggered. The program keeps a list~|s| of independent variables
12268 whose coefficients must be divided by~4.
12269
12270 In unusual cases, this fixup process might reduce one or more coefficients
12271 to zero, so that a variable will become known more or less by default.
12272
12273 @<Declare basic dependency-list subroutines@>=
12274 void mp_fix_dependencies (MP mp);
12275
12276 @ @c void mp_fix_dependencies (MP mp) {
12277   pointer p,q,r,s,t; /* list manipulation registers */
12278   pointer x; /* an independent variable */
12279   r=link(dep_head); s=null;
12280   while ( r!=dep_head ){ 
12281     t=r;
12282     @<Run through the dependency list for variable |t|, fixing
12283       all nodes, and ending with final link~|q|@>;
12284     r=link(q);
12285     if ( q==dep_list(t) ) mp_make_known(mp, t,q);
12286   }
12287   while ( s!=null ) { 
12288     p=link(s); x=info(s); free_avail(s); s=p;
12289     type(x)=mp_independent; value(x)=value(x)+2;
12290   }
12291   mp->fix_needed=false;
12292 }
12293
12294 @ @d independent_being_fixed 1 /* this variable already appears in |s| */
12295
12296 @<Run through the dependency list for variable |t|...@>=
12297 r=value_loc(t); /* |link(r)=dep_list(t)| */
12298 while (1) { 
12299   q=link(r); x=info(q);
12300   if ( x==null ) break;
12301   if ( type(x)<=independent_being_fixed ) {
12302     if ( type(x)<independent_being_fixed ) {
12303       p=mp_get_avail(mp); link(p)=s; s=p;
12304       info(s)=x; type(x)=independent_being_fixed;
12305     }
12306     value(q)=value(q) / 4;
12307     if ( value(q)==0 ) {
12308       link(r)=link(q); mp_free_node(mp, q,dep_node_size); q=r;
12309     }
12310   }
12311   r=q;
12312 }
12313
12314
12315 @ The |new_dep| routine installs a dependency list~|p| into the value node~|q|,
12316 linking it into the list of all known dependencies. We assume that
12317 |dep_final| points to the final node of list~|p|.
12318
12319 @c void mp_new_dep (MP mp,pointer q, pointer p) {
12320   pointer r; /* what used to be the first dependency */
12321   dep_list(q)=p; prev_dep(q)=dep_head;
12322   r=link(dep_head); link(mp->dep_final)=r; prev_dep(r)=mp->dep_final;
12323   link(dep_head)=q;
12324 }
12325
12326 @ Here is one of the ways a dependency list gets started.
12327 The |const_dependency| routine produces a list that has nothing but
12328 a constant term.
12329
12330 @c pointer mp_const_dependency (MP mp, scaled v) {
12331   mp->dep_final=mp_get_node(mp, dep_node_size);
12332   value(mp->dep_final)=v; info(mp->dep_final)=null;
12333   return mp->dep_final;
12334 }
12335
12336 @ And here's a more interesting way to start a dependency list from scratch:
12337 The parameter to |single_dependency| is the location of an
12338 independent variable~|x|, and the result is the simple dependency list
12339 `|x+0|'.
12340
12341 In the unlikely event that the given independent variable has been doubled so
12342 often that we can't refer to it with a nonzero coefficient,
12343 |single_dependency| returns the simple list `0'.  This case can be
12344 recognized by testing that the returned list pointer is equal to
12345 |dep_final|.
12346
12347 @c pointer mp_single_dependency (MP mp,pointer p) {
12348   pointer q; /* the new dependency list */
12349   integer m; /* the number of doublings */
12350   m=value(p) % s_scale;
12351   if ( m>28 ) {
12352     return mp_const_dependency(mp, 0);
12353   } else { 
12354     q=mp_get_node(mp, dep_node_size);
12355     value(q)=two_to_the(28-m); info(q)=p;
12356     link(q)=mp_const_dependency(mp, 0);
12357     return q;
12358   }
12359 }
12360
12361 @ We sometimes need to make an exact copy of a dependency list.
12362
12363 @c pointer mp_copy_dep_list (MP mp,pointer p) {
12364   pointer q; /* the new dependency list */
12365   q=mp_get_node(mp, dep_node_size); mp->dep_final=q;
12366   while (1) { 
12367     info(mp->dep_final)=info(p); value(mp->dep_final)=value(p);
12368     if ( info(mp->dep_final)==null ) break;
12369     link(mp->dep_final)=mp_get_node(mp, dep_node_size);
12370     mp->dep_final=link(mp->dep_final); p=link(p);
12371   }
12372   return q;
12373 }
12374
12375 @ But how do variables normally become known? Ah, now we get to the heart of the
12376 equation-solving mechanism. The |linear_eq| procedure is given a |dependent|
12377 or |mp_proto_dependent| list,~|p|, in which at least one independent variable
12378 appears. It equates this list to zero, by choosing an independent variable
12379 with the largest coefficient and making it dependent on the others. The
12380 newly dependent variable is eliminated from all current dependencies,
12381 thereby possibly making other dependent variables known.
12382
12383 The given list |p| is, of course, totally destroyed by all this processing.
12384
12385 @c void mp_linear_eq (MP mp, pointer p, small_number t) {
12386   pointer q,r,s; /* for link manipulation */
12387   pointer x; /* the variable that loses its independence */
12388   integer n; /* the number of times |x| had been halved */
12389   integer v; /* the coefficient of |x| in list |p| */
12390   pointer prev_r; /* lags one step behind |r| */
12391   pointer final_node; /* the constant term of the new dependency list */
12392   integer w; /* a tentative coefficient */
12393    @<Find a node |q| in list |p| whose coefficient |v| is largest@>;
12394   x=info(q); n=value(x) % s_scale;
12395   @<Divide list |p| by |-v|, removing node |q|@>;
12396   if ( mp->internal[mp_tracing_equations]>0 ) {
12397     @<Display the new dependency@>;
12398   }
12399   @<Simplify all existing dependencies by substituting for |x|@>;
12400   @<Change variable |x| from |independent| to |dependent| or |known|@>;
12401   if ( mp->fix_needed ) mp_fix_dependencies(mp);
12402 }
12403
12404 @ @<Find a node |q| in list |p| whose coefficient |v| is largest@>=
12405 q=p; r=link(p); v=value(q);
12406 while ( info(r)!=null ) { 
12407   if ( abs(value(r))>abs(v) ) { q=r; v=value(r); };
12408   r=link(r);
12409 }
12410
12411 @ Here we want to change the coefficients from |scaled| to |fraction|,
12412 except in the constant term. In the common case of a trivial equation
12413 like `\.{x=3.14}', we will have |v=-fraction_one|, |q=p|, and |t=mp_dependent|.
12414
12415 @<Divide list |p| by |-v|, removing node |q|@>=
12416 s=temp_head; link(s)=p; r=p;
12417 do { 
12418   if ( r==q ) {
12419     link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12420   } else  { 
12421     w=mp_make_fraction(mp, value(r),v);
12422     if ( abs(w)<=half_fraction_threshold ) {
12423       link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12424     } else { 
12425       value(r)=-w; s=r;
12426     }
12427   }
12428   r=link(s);
12429 } while (info(r)!=null);
12430 if ( t==mp_proto_dependent ) {
12431   value(r)=-mp_make_scaled(mp, value(r),v);
12432 } else if ( v!=-fraction_one ) {
12433   value(r)=-mp_make_fraction(mp, value(r),v);
12434 }
12435 final_node=r; p=link(temp_head)
12436
12437 @ @<Display the new dependency@>=
12438 if ( mp_interesting(mp, x) ) {
12439   mp_begin_diagnostic(mp); mp_print_nl(mp, "## "); 
12440   mp_print_variable_name(mp, x);
12441 @:]]]\#\#_}{\.{\#\#}@>
12442   w=n;
12443   while ( w>0 ) { mp_print(mp, "*4"); w=w-2;  };
12444   mp_print_char(mp, '='); mp_print_dependency(mp, p,mp_dependent); 
12445   mp_end_diagnostic(mp, false);
12446 }
12447
12448 @ @<Simplify all existing dependencies by substituting for |x|@>=
12449 prev_r=dep_head; r=link(dep_head);
12450 while ( r!=dep_head ) {
12451   s=dep_list(r); q=mp_p_with_x_becoming_q(mp, s,x,p,type(r));
12452   if ( info(q)==null ) {
12453     mp_make_known(mp, r,q);
12454   } else { 
12455     dep_list(r)=q;
12456     do {  q=link(q); } while (info(q)!=null);
12457     prev_r=q;
12458   }
12459   r=link(prev_r);
12460 }
12461
12462 @ @<Change variable |x| from |independent| to |dependent| or |known|@>=
12463 if ( n>0 ) @<Divide list |p| by $2^n$@>;
12464 if ( info(p)==null ) {
12465   type(x)=mp_known;
12466   value(x)=value(p);
12467   if ( abs(value(x))>=fraction_one ) mp_val_too_big(mp, value(x));
12468   mp_free_node(mp, p,dep_node_size);
12469   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) {
12470     mp->cur_exp=value(x); mp->cur_type=mp_known;
12471     mp_free_node(mp, x,value_node_size);
12472   }
12473 } else { 
12474   type(x)=mp_dependent; mp->dep_final=final_node; mp_new_dep(mp, x,p);
12475   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) mp->cur_type=mp_dependent;
12476 }
12477
12478 @ @<Divide list |p| by $2^n$@>=
12479
12480   s=temp_head; link(temp_head)=p; r=p;
12481   do {  
12482     if ( n>30 ) w=0;
12483     else w=value(r) / two_to_the(n);
12484     if ( (abs(w)<=half_fraction_threshold)&&(info(r)!=null) ) {
12485       link(s)=link(r);
12486       mp_free_node(mp, r,dep_node_size);
12487     } else { 
12488       value(r)=w; s=r;
12489     }
12490     r=link(s);
12491   } while (info(s)!=null);
12492   p=link(temp_head);
12493 }
12494
12495 @ The |check_mem| procedure, which is used only when \MP\ is being
12496 debugged, makes sure that the current dependency lists are well formed.
12497
12498 @<Check the list of linear dependencies@>=
12499 q=dep_head; p=link(q);
12500 while ( p!=dep_head ) {
12501   if ( prev_dep(p)!=q ) {
12502     mp_print_nl(mp, "Bad PREVDEP at "); mp_print_int(mp, p);
12503 @.Bad PREVDEP...@>
12504   }
12505   p=dep_list(p);
12506   while (1) {
12507     r=info(p); q=p; p=link(q);
12508     if ( r==null ) break;
12509     if ( value(info(p))>=value(r) ) {
12510       mp_print_nl(mp, "Out of order at "); mp_print_int(mp, p);
12511 @.Out of order...@>
12512     }
12513   }
12514 }
12515
12516 @* \[25] Dynamic nonlinear equations.
12517 Variables of numeric type are maintained by the general scheme of
12518 independent, dependent, and known values that we have just studied;
12519 and the components of pair and transform variables are handled in the
12520 same way. But \MP\ also has five other types of values: \&{boolean},
12521 \&{string}, \&{pen}, \&{path}, and \&{picture}; what about them?
12522
12523 Equations are allowed between nonlinear quantities, but only in a
12524 simple form. Two variables that haven't yet been assigned values are
12525 either equal to each other, or they're not.
12526
12527 Before a boolean variable has received a value, its type is |mp_unknown_boolean|;
12528 similarly, there are variables whose type is |mp_unknown_string|, |mp_unknown_pen|,
12529 |mp_unknown_path|, and |mp_unknown_picture|. In such cases the value is either
12530 |null| (which means that no other variables are equivalent to this one), or
12531 it points to another variable of the same undefined type. The pointers in the
12532 latter case form a cycle of nodes, which we shall call a ``ring.''
12533 Rings of undefined variables may include capsules, which arise as
12534 intermediate results within expressions or as \&{expr} parameters to macros.
12535
12536 When one member of a ring receives a value, the same value is given to
12537 all the other members. In the case of paths and pictures, this implies
12538 making separate copies of a potentially large data structure; users should
12539 restrain their enthusiasm for such generality, unless they have lots and
12540 lots of memory space.
12541
12542 @ The following procedure is called when a capsule node is being
12543 added to a ring (e.g., when an unknown variable is mentioned in an expression).
12544
12545 @c pointer mp_new_ring_entry (MP mp,pointer p) {
12546   pointer q; /* the new capsule node */
12547   q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
12548   type(q)=type(p);
12549   if ( value(p)==null ) value(q)=p; else value(q)=value(p);
12550   value(p)=q;
12551   return q;
12552 }
12553
12554 @ Conversely, we might delete a capsule or a variable before it becomes known.
12555 The following procedure simply detaches a quantity from its ring,
12556 without recycling the storage.
12557
12558 @<Declare the recycling subroutines@>=
12559 void mp_ring_delete (MP mp,pointer p) {
12560   pointer q; 
12561   q=value(p);
12562   if ( q!=null ) if ( q!=p ){ 
12563     while ( value(q)!=p ) q=value(q);
12564     value(q)=value(p);
12565   }
12566 }
12567
12568 @ Eventually there might be an equation that assigns values to all of the
12569 variables in a ring. The |nonlinear_eq| subroutine does the necessary
12570 propagation of values.
12571
12572 If the parameter |flush_p| is |true|, node |p| itself needn't receive a
12573 value, it will soon be recycled.
12574
12575 @c void mp_nonlinear_eq (MP mp,integer v, pointer p, boolean flush_p) {
12576   small_number t; /* the type of ring |p| */
12577   pointer q,r; /* link manipulation registers */
12578   t=type(p)-unknown_tag; q=value(p);
12579   if ( flush_p ) type(p)=mp_vacuous; else p=q;
12580   do {  
12581     r=value(q); type(q)=t;
12582     switch (t) {
12583     case mp_boolean_type: value(q)=v; break;
12584     case mp_string_type: value(q)=v; add_str_ref(v); break;
12585     case mp_pen_type: value(q)=copy_pen(v); break;
12586     case mp_path_type: value(q)=mp_copy_path(mp, v); break;
12587     case mp_picture_type: value(q)=v; add_edge_ref(v); break;
12588     } /* there ain't no more cases */
12589     q=r;
12590   } while (q!=p);
12591 }
12592
12593 @ If two members of rings are equated, and if they have the same type,
12594 the |ring_merge| procedure is called on to make them equivalent.
12595
12596 @c void mp_ring_merge (MP mp,pointer p, pointer q) {
12597   pointer r; /* traverses one list */
12598   r=value(p);
12599   while ( r!=p ) {
12600     if ( r==q ) {
12601       @<Exclaim about a redundant equation@>;
12602       return;
12603     };
12604     r=value(r);
12605   }
12606   r=value(p); value(p)=value(q); value(q)=r;
12607 }
12608
12609 @ @<Exclaim about a redundant equation@>=
12610
12611   print_err("Redundant equation");
12612 @.Redundant equation@>
12613   help2("I already knew that this equation was true.")
12614    ("But perhaps no harm has been done; let's continue.");
12615   mp_put_get_error(mp);
12616 }
12617
12618 @* \[26] Introduction to the syntactic routines.
12619 Let's pause a moment now and try to look at the Big Picture.
12620 The \MP\ program consists of three main parts: syntactic routines,
12621 semantic routines, and output routines. The chief purpose of the
12622 syntactic routines is to deliver the user's input to the semantic routines,
12623 while parsing expressions and locating operators and operands. The
12624 semantic routines act as an interpreter responding to these operators,
12625 which may be regarded as commands. And the output routines are
12626 periodically called on to produce compact font descriptions that can be
12627 used for typesetting or for making interim proof drawings. We have
12628 discussed the basic data structures and many of the details of semantic
12629 operations, so we are good and ready to plunge into the part of \MP\ that
12630 actually controls the activities.
12631
12632 Our current goal is to come to grips with the |get_next| procedure,
12633 which is the keystone of \MP's input mechanism. Each call of |get_next|
12634 sets the value of three variables |cur_cmd|, |cur_mod|, and |cur_sym|,
12635 representing the next input token.
12636 $$\vbox{\halign{#\hfil\cr
12637   \hbox{|cur_cmd| denotes a command code from the long list of codes
12638    given earlier;}\cr
12639   \hbox{|cur_mod| denotes a modifier of the command code;}\cr
12640   \hbox{|cur_sym| is the hash address of the symbolic token that was
12641    just scanned,}\cr
12642   \hbox{\qquad or zero in the case of a numeric or string
12643    or capsule token.}\cr}}$$
12644 Underlying this external behavior of |get_next| is all the machinery
12645 necessary to convert from character files to tokens. At a given time we
12646 may be only partially finished with the reading of several files (for
12647 which \&{input} was specified), and partially finished with the expansion
12648 of some user-defined macros and/or some macro parameters, and partially
12649 finished reading some text that the user has inserted online,
12650 and so on. When reading a character file, the characters must be
12651 converted to tokens; comments and blank spaces must
12652 be removed, numeric and string tokens must be evaluated.
12653
12654 To handle these situations, which might all be present simultaneously,
12655 \MP\ uses various stacks that hold information about the incomplete
12656 activities, and there is a finite state control for each level of the
12657 input mechanism. These stacks record the current state of an implicitly
12658 recursive process, but the |get_next| procedure is not recursive.
12659
12660 @<Glob...@>=
12661 eight_bits cur_cmd; /* current command set by |get_next| */
12662 integer cur_mod; /* operand of current command */
12663 halfword cur_sym; /* hash address of current symbol */
12664
12665 @ The |print_cmd_mod| routine prints a symbolic interpretation of a
12666 command code and its modifier.
12667 It consists of a rather tedious sequence of print
12668 commands, and most of it is essentially an inverse to the |primitive|
12669 routine that enters a \MP\ primitive into |hash| and |eqtb|. Therefore almost
12670 all of this procedure appears elsewhere in the program, together with the
12671 corresponding |primitive| calls.
12672
12673 @<Declare the procedure called |print_cmd_mod|@>=
12674 void mp_print_cmd_mod (MP mp,integer c, integer m) { 
12675  switch (c) {
12676   @<Cases of |print_cmd_mod| for symbolic printing of primitives@>
12677   default: mp_print(mp, "[unknown command code!]"); break;
12678   }
12679 }
12680
12681 @ Here is a procedure that displays a given command in braces, in the
12682 user's transcript file.
12683
12684 @d show_cur_cmd_mod mp_show_cmd_mod(mp, mp->cur_cmd,mp->cur_mod)
12685
12686 @c 
12687 void mp_show_cmd_mod (MP mp,integer c, integer m) { 
12688   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
12689   mp_print_cmd_mod(mp, c,m); mp_print_char(mp, '}');
12690   mp_end_diagnostic(mp, false);
12691 }
12692
12693 @* \[27] Input stacks and states.
12694 The state of \MP's input mechanism appears in the input stack, whose
12695 entries are records with five fields, called |index|, |start|, |loc|,
12696 |limit|, and |name|. The top element of this stack is maintained in a
12697 global variable for which no subscripting needs to be done; the other
12698 elements of the stack appear in an array. Hence the stack is declared thus:
12699
12700 @<Types...@>=
12701 typedef struct {
12702   quarterword index_field;
12703   halfword start_field, loc_field, limit_field, name_field;
12704 } in_state_record;
12705
12706 @ @<Glob...@>=
12707 in_state_record *input_stack;
12708 integer input_ptr; /* first unused location of |input_stack| */
12709 integer max_in_stack; /* largest value of |input_ptr| when pushing */
12710 in_state_record cur_input; /* the ``top'' input state */
12711 int stack_size; /* maximum number of simultaneous input sources */
12712
12713 @ @<Allocate or initialize ...@>=
12714 mp->stack_size = 300;
12715 mp->input_stack = xmalloc((mp->stack_size+1),sizeof(in_state_record));
12716
12717 @ @<Dealloc variables@>=
12718 xfree(mp->input_stack);
12719
12720 @ We've already defined the special variable |loc==cur_input.loc_field|
12721 in our discussion of basic input-output routines. The other components of
12722 |cur_input| are defined in the same way:
12723
12724 @d index mp->cur_input.index_field /* reference for buffer information */
12725 @d start mp->cur_input.start_field /* starting position in |buffer| */
12726 @d limit mp->cur_input.limit_field /* end of current line in |buffer| */
12727 @d name mp->cur_input.name_field /* name of the current file */
12728
12729 @ Let's look more closely now at the five control variables
12730 (|index|,~|start|,~|loc|,~|limit|,~|name|),
12731 assuming that \MP\ is reading a line of characters that have been input
12732 from some file or from the user's terminal. There is an array called
12733 |buffer| that acts as a stack of all lines of characters that are
12734 currently being read from files, including all lines on subsidiary
12735 levels of the input stack that are not yet completed. \MP\ will return to
12736 the other lines when it is finished with the present input file.
12737
12738 (Incidentally, on a machine with byte-oriented addressing, it would be
12739 appropriate to combine |buffer| with the |str_pool| array,
12740 letting the buffer entries grow downward from the top of the string pool
12741 and checking that these two tables don't bump into each other.)
12742
12743 The line we are currently working on begins in position |start| of the
12744 buffer; the next character we are about to read is |buffer[loc]|; and
12745 |limit| is the location of the last character present. We always have
12746 |loc<=limit|. For convenience, |buffer[limit]| has been set to |"%"|, so
12747 that the end of a line is easily sensed.
12748
12749 The |name| variable is a string number that designates the name of
12750 the current file, if we are reading an ordinary text file.  Special codes
12751 |is_term..max_spec_src| indicate other sources of input text.
12752
12753 @d is_term 0 /* |name| value when reading from the terminal for normal input */
12754 @d is_read 1 /* |name| value when executing a \&{readstring} or \&{readfrom} */
12755 @d is_scantok 2 /* |name| value when reading text generated by \&{scantokens} */
12756 @d max_spec_src is_scantok
12757
12758 @ Additional information about the current line is available via the
12759 |index| variable, which counts how many lines of characters are present
12760 in the buffer below the current level. We have |index=0| when reading
12761 from the terminal and prompting the user for each line; then if the user types,
12762 e.g., `\.{input figs}', we will have |index=1| while reading
12763 the file \.{figs.mp}. However, it does not follow that |index| is the
12764 same as the input stack pointer, since many of the levels on the input
12765 stack may come from token lists and some |index| values may correspond
12766 to \.{MPX} files that are not currently on the stack.
12767
12768 The global variable |in_open| is equal to the highest |index| value counting
12769 \.{MPX} files but excluding token-list input levels.  Thus, the number of
12770 partially read lines in the buffer is |in_open+1| and we have |in_open>=index|
12771 when we are not reading a token list.
12772
12773 If we are not currently reading from the terminal,
12774 we are reading from the file variable |input_file[index]|. We use
12775 the notation |terminal_input| as a convenient abbreviation for |name=is_term|,
12776 and |cur_file| as an abbreviation for |input_file[index]|.
12777
12778 When \MP\ is not reading from the terminal, the global variable |line| contains
12779 the line number in the current file, for use in error messages. More precisely,
12780 |line| is a macro for |line_stack[index]| and the |line_stack| array gives
12781 the line number for each file in the |input_file| array.
12782
12783 When an \.{MPX} file is opened the file name is stored in the |mpx_name|
12784 array so that the name doesn't get lost when the file is temporarily removed
12785 from the input stack.
12786 Thus when |input_file[k]| is an \.{MPX} file, its name is |mpx_name[k]|
12787 and it contains translated \TeX\ pictures for |input_file[k-1]|.
12788 Since this is not an \.{MPX} file, we have
12789 $$ \hbox{|mpx_name[k-1]<=absent|}. $$
12790 This |name| field is set to |finished| when |input_file[k]| is completely
12791 read.
12792
12793 If more information about the input state is needed, it can be
12794 included in small arrays like those shown here. For example,
12795 the current page or segment number in the input file might be put
12796 into a variable |page|, that is really a macro for the current entry
12797 in `\ignorespaces|page_stack:array[0..max_in_open] of integer|\unskip'
12798 by analogy with |line_stack|.
12799 @^system dependencies@>
12800
12801 @d terminal_input (name==is_term) /* are we reading from the terminal? */
12802 @d cur_file mp->input_file[index] /* the current |void *| variable */
12803 @d line mp->line_stack[index] /* current line number in the current source file */
12804 @d in_name mp->iname_stack[index] /* a string used to construct \.{MPX} file names */
12805 @d in_area mp->iarea_stack[index] /* another string for naming \.{MPX} files */
12806 @d absent 1 /* |name_field| value for unused |mpx_in_stack| entries */
12807 @d mpx_reading (mp->mpx_name[index]>absent)
12808   /* when reading a file, is it an \.{MPX} file? */
12809 @d finished 0
12810   /* |name_field| value when the corresponding \.{MPX} file is finished */
12811
12812 @<Glob...@>=
12813 integer in_open; /* the number of lines in the buffer, less one */
12814 unsigned int open_parens; /* the number of open text files */
12815 void  * *input_file ;
12816 integer *line_stack ; /* the line number for each file */
12817 char *  *iname_stack; /* used for naming \.{MPX} files */
12818 char *  *iarea_stack; /* used for naming \.{MPX} files */
12819 halfword*mpx_name  ;
12820
12821 @ @<Allocate or ...@>=
12822 mp->input_file  = xmalloc((mp->max_in_open+1),sizeof(void *));
12823 mp->line_stack  = xmalloc((mp->max_in_open+1),sizeof(integer));
12824 mp->iname_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12825 mp->iarea_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12826 mp->mpx_name    = xmalloc((mp->max_in_open+1),sizeof(halfword));
12827 {
12828   int k;
12829   for (k=0;k<=mp->max_in_open;k++) {
12830     mp->iname_stack[k] =NULL;
12831     mp->iarea_stack[k] =NULL;
12832   }
12833 }
12834
12835 @ @<Dealloc variables@>=
12836 {
12837   int l;
12838   for (l=0;l<=mp->max_in_open;l++) {
12839     xfree(mp->iname_stack[l]);
12840     xfree(mp->iarea_stack[l]);
12841   }
12842 }
12843 xfree(mp->input_file);
12844 xfree(mp->line_stack);
12845 xfree(mp->iname_stack);
12846 xfree(mp->iarea_stack);
12847 xfree(mp->mpx_name);
12848
12849
12850 @ However, all this discussion about input state really applies only to the
12851 case that we are inputting from a file. There is another important case,
12852 namely when we are currently getting input from a token list. In this case
12853 |index>max_in_open|, and the conventions about the other state variables
12854 are different:
12855
12856 \yskip\hang|loc| is a pointer to the current node in the token list, i.e.,
12857 the node that will be read next. If |loc=null|, the token list has been
12858 fully read.
12859
12860 \yskip\hang|start| points to the first node of the token list; this node
12861 may or may not contain a reference count, depending on the type of token
12862 list involved.
12863
12864 \yskip\hang|token_type|, which takes the place of |index| in the
12865 discussion above, is a code number that explains what kind of token list
12866 is being scanned.
12867
12868 \yskip\hang|name| points to the |eqtb| address of the control sequence
12869 being expanded, if the current token list is a macro not defined by
12870 \&{vardef}. Macros defined by \&{vardef} have |name=null|; their name
12871 can be deduced by looking at their first two parameters.
12872
12873 \yskip\hang|param_start|, which takes the place of |limit|, tells where
12874 the parameters of the current macro or loop text begin in the |param_stack|.
12875
12876 \yskip\noindent The |token_type| can take several values, depending on
12877 where the current token list came from:
12878
12879 \yskip
12880 \indent|forever_text|, if the token list being scanned is the body of
12881 a \&{forever} loop;
12882
12883 \indent|loop_text|, if the token list being scanned is the body of
12884 a \&{for} or \&{forsuffixes} loop;
12885
12886 \indent|parameter|, if a \&{text} or \&{suffix} parameter is being scanned;
12887
12888 \indent|backed_up|, if the token list being scanned has been inserted as
12889 `to be read again'.
12890
12891 \indent|inserted|, if the token list being scanned has been inserted as
12892 part of error recovery;
12893
12894 \indent|macro|, if the expansion of a user-defined symbolic token is being
12895 scanned.
12896
12897 \yskip\noindent
12898 The token list begins with a reference count if and only if |token_type=
12899 macro|.
12900 @^reference counts@>
12901
12902 @d token_type index /* type of current token list */
12903 @d token_state (index>(int)mp->max_in_open) /* are we scanning a token list? */
12904 @d file_state (index<=(int)mp->max_in_open) /* are we scanning a file line? */
12905 @d param_start limit /* base of macro parameters in |param_stack| */
12906 @d forever_text (mp->max_in_open+1) /* |token_type| code for loop texts */
12907 @d loop_text (mp->max_in_open+2) /* |token_type| code for loop texts */
12908 @d parameter (mp->max_in_open+3) /* |token_type| code for parameter texts */
12909 @d backed_up (mp->max_in_open+4) /* |token_type| code for texts to be reread */
12910 @d inserted (mp->max_in_open+5) /* |token_type| code for inserted texts */
12911 @d macro (mp->max_in_open+6) /* |token_type| code for macro replacement texts */
12912
12913 @ The |param_stack| is an auxiliary array used to hold pointers to the token
12914 lists for parameters at the current level and subsidiary levels of input.
12915 This stack grows at a different rate from the others.
12916
12917 @<Glob...@>=
12918 pointer *param_stack;  /* token list pointers for parameters */
12919 integer param_ptr; /* first unused entry in |param_stack| */
12920 integer max_param_stack;  /* largest value of |param_ptr| */
12921
12922 @ @<Allocate or initialize ...@>=
12923 mp->param_stack = xmalloc((mp->param_size+1),sizeof(pointer));
12924
12925 @ @<Dealloc variables@>=
12926 xfree(mp->param_stack);
12927
12928 @ Notice that the |line| isn't valid when |token_state| is true because it
12929 depends on |index|.  If we really need to know the line number for the
12930 topmost file in the index stack we use the following function.  If a page
12931 number or other information is needed, this routine should be modified to
12932 compute it as well.
12933 @^system dependencies@>
12934
12935 @<Declare a function called |true_line|@>=
12936 integer mp_true_line (MP mp) {
12937   int k; /* an index into the input stack */
12938   if ( file_state && (name>max_spec_src) ) {
12939      return line;
12940   } else { 
12941     k=mp->input_ptr;
12942     while ((k>0) &&
12943            ((mp->input_stack[(k-1)].index_field>mp->max_in_open)||
12944             (mp->input_stack[(k-1)].name_field<=max_spec_src))) {
12945       decr(k);
12946     }
12947     return mp->line_stack[(k-1)];
12948   }
12949   return 0; 
12950 }
12951
12952 @ Thus, the ``current input state'' can be very complicated indeed; there
12953 can be many levels and each level can arise in a variety of ways. The
12954 |show_context| procedure, which is used by \MP's error-reporting routine to
12955 print out the current input state on all levels down to the most recent
12956 line of characters from an input file, illustrates most of these conventions.
12957 The global variable |file_ptr| contains the lowest level that was
12958 displayed by this procedure.
12959
12960 @<Glob...@>=
12961 integer file_ptr; /* shallowest level shown by |show_context| */
12962
12963 @ The status at each level is indicated by printing two lines, where the first
12964 line indicates what was read so far and the second line shows what remains
12965 to be read. The context is cropped, if necessary, so that the first line
12966 contains at most |half_error_line| characters, and the second contains
12967 at most |error_line|. Non-current input levels whose |token_type| is
12968 `|backed_up|' are shown only if they have not been fully read.
12969
12970 @c void mp_show_context (MP mp) { /* prints where the scanner is */
12971   int old_setting; /* saved |selector| setting */
12972   @<Local variables for formatting calculations@>
12973   mp->file_ptr=mp->input_ptr; mp->input_stack[mp->file_ptr]=mp->cur_input;
12974   /* store current state */
12975   while (1) { 
12976     mp->cur_input=mp->input_stack[mp->file_ptr]; /* enter into the context */
12977     @<Display the current context@>;
12978     if ( file_state )
12979       if ( (name>max_spec_src) || (mp->file_ptr==0) ) break;
12980     decr(mp->file_ptr);
12981   }
12982   mp->cur_input=mp->input_stack[mp->input_ptr]; /* restore original state */
12983 }
12984
12985 @ @<Display the current context@>=
12986 if ( (mp->file_ptr==mp->input_ptr) || file_state ||
12987    (token_type!=backed_up) || (loc!=null) ) {
12988     /* we omit backed-up token lists that have already been read */
12989   mp->tally=0; /* get ready to count characters */
12990   old_setting=mp->selector;
12991   if ( file_state ) {
12992     @<Print location of current line@>;
12993     @<Pseudoprint the line@>;
12994   } else { 
12995     @<Print type of token list@>;
12996     @<Pseudoprint the token list@>;
12997   }
12998   mp->selector=old_setting; /* stop pseudoprinting */
12999   @<Print two lines using the tricky pseudoprinted information@>;
13000 }
13001
13002 @ This routine should be changed, if necessary, to give the best possible
13003 indication of where the current line resides in the input file.
13004 For example, on some systems it is best to print both a page and line number.
13005 @^system dependencies@>
13006
13007 @<Print location of current line@>=
13008 if ( name>max_spec_src ) {
13009   mp_print_nl(mp, "l."); mp_print_int(mp, mp_true_line(mp));
13010 } else if ( terminal_input ) {
13011   if ( mp->file_ptr==0 ) mp_print_nl(mp, "<*>");
13012   else mp_print_nl(mp, "<insert>");
13013 } else if ( name==is_scantok ) {
13014   mp_print_nl(mp, "<scantokens>");
13015 } else {
13016   mp_print_nl(mp, "<read>");
13017 }
13018 mp_print_char(mp, ' ')
13019
13020 @ Can't use case statement here because the |token_type| is not
13021 a constant expression.
13022
13023 @<Print type of token list@>=
13024 {
13025   if(token_type==forever_text) {
13026     mp_print_nl(mp, "<forever> ");
13027   } else if (token_type==loop_text) {
13028     @<Print the current loop value@>;
13029   } else if (token_type==parameter) {
13030     mp_print_nl(mp, "<argument> "); 
13031   } else if (token_type==backed_up) { 
13032     if ( loc==null ) mp_print_nl(mp, "<recently read> ");
13033     else mp_print_nl(mp, "<to be read again> ");
13034   } else if (token_type==inserted) {
13035     mp_print_nl(mp, "<inserted text> ");
13036   } else if (token_type==macro) {
13037     mp_print_ln(mp);
13038     if ( name!=null ) mp_print_text(name);
13039     else @<Print the name of a \&{vardef}'d macro@>;
13040     mp_print(mp, "->");
13041   } else {
13042     mp_print_nl(mp, "?");/* this should never happen */
13043 @.?\relax@>
13044   }
13045 }
13046
13047 @ The parameter that corresponds to a loop text is either a token list
13048 (in the case of \&{forsuffixes}) or a ``capsule'' (in the case of \&{for}).
13049 We'll discuss capsules later; for now, all we need to know is that
13050 the |link| field in a capsule parameter is |void| and that
13051 |print_exp(p,0)| displays the value of capsule~|p| in abbreviated form.
13052
13053 @<Print the current loop value@>=
13054 { mp_print_nl(mp, "<for("); p=mp->param_stack[param_start];
13055   if ( p!=null ) {
13056     if ( link(p)==mp_void ) mp_print_exp(mp, p,0); /* we're in a \&{for} loop */
13057     else mp_show_token_list(mp, p,null,20,mp->tally);
13058   }
13059   mp_print(mp, ")> ");
13060 }
13061
13062 @ The first two parameters of a macro defined by \&{vardef} will be token
13063 lists representing the macro's prefix and ``at point.'' By putting these
13064 together, we get the macro's full name.
13065
13066 @<Print the name of a \&{vardef}'d macro@>=
13067 { p=mp->param_stack[param_start];
13068   if ( p==null ) {
13069     mp_show_token_list(mp, mp->param_stack[param_start+1],null,20,mp->tally);
13070   } else { 
13071     q=p;
13072     while ( link(q)!=null ) q=link(q);
13073     link(q)=mp->param_stack[param_start+1];
13074     mp_show_token_list(mp, p,null,20,mp->tally);
13075     link(q)=null;
13076   }
13077 }
13078
13079 @ Now it is necessary to explain a little trick. We don't want to store a long
13080 string that corresponds to a token list, because that string might take up
13081 lots of memory; and we are printing during a time when an error message is
13082 being given, so we dare not do anything that might overflow one of \MP's
13083 tables. So `pseudoprinting' is the answer: We enter a mode of printing
13084 that stores characters into a buffer of length |error_line|, where character
13085 $k+1$ is placed into \hbox{|trick_buf[k mod error_line]|} if
13086 |k<trick_count|, otherwise character |k| is dropped. Initially we set
13087 |tally:=0| and |trick_count:=1000000|; then when we reach the
13088 point where transition from line 1 to line 2 should occur, we
13089 set |first_count:=tally| and |trick_count:=@tmax@>(error_line,
13090 tally+1+error_line-half_error_line)|. At the end of the
13091 pseudoprinting, the values of |first_count|, |tally|, and
13092 |trick_count| give us all the information we need to print the two lines,
13093 and all of the necessary text is in |trick_buf|.
13094
13095 Namely, let |l| be the length of the descriptive information that appears
13096 on the first line. The length of the context information gathered for that
13097 line is |k=first_count|, and the length of the context information
13098 gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k<=h|,
13099 where |h=half_error_line|, we print |trick_buf[0..k-1]| after the
13100 descriptive information on line~1, and set |n:=l+k|; here |n| is the
13101 length of line~1. If $l+k>h$, some cropping is necessary, so we set |n:=h|
13102 and print `\.{...}' followed by
13103 $$\hbox{|trick_buf[(l+k-h+3)..k-1]|,}$$
13104 where subscripts of |trick_buf| are circular modulo |error_line|. The
13105 second line consists of |n|~spaces followed by |trick_buf[k..(k+m-1)]|,
13106 unless |n+m>error_line|; in the latter case, further cropping is done.
13107 This is easier to program than to explain.
13108
13109 @<Local variables for formatting...@>=
13110 int i; /* index into |buffer| */
13111 integer l; /* length of descriptive information on line 1 */
13112 integer m; /* context information gathered for line 2 */
13113 int n; /* length of line 1 */
13114 integer p; /* starting or ending place in |trick_buf| */
13115 integer q; /* temporary index */
13116
13117 @ The following code tells the print routines to gather
13118 the desired information.
13119
13120 @d begin_pseudoprint { 
13121   l=mp->tally; mp->tally=0; mp->selector=pseudo;
13122   mp->trick_count=1000000;
13123 }
13124 @d set_trick_count {
13125   mp->first_count=mp->tally;
13126   mp->trick_count=mp->tally+1+mp->error_line-mp->half_error_line;
13127   if ( mp->trick_count<mp->error_line ) mp->trick_count=mp->error_line;
13128 }
13129
13130 @ And the following code uses the information after it has been gathered.
13131
13132 @<Print two lines using the tricky pseudoprinted information@>=
13133 if ( mp->trick_count==1000000 ) set_trick_count;
13134   /* |set_trick_count| must be performed */
13135 if ( mp->tally<mp->trick_count ) m=mp->tally-mp->first_count;
13136 else m=mp->trick_count-mp->first_count; /* context on line 2 */
13137 if ( l+mp->first_count<=mp->half_error_line ) {
13138   p=0; n=l+mp->first_count;
13139 } else  { 
13140   mp_print(mp, "..."); p=l+mp->first_count-mp->half_error_line+3;
13141   n=mp->half_error_line;
13142 }
13143 for (q=p;q<=mp->first_count-1;q++) {
13144   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13145 }
13146 mp_print_ln(mp);
13147 for (q=1;q<=n;q++) {
13148   mp_print_char(mp, ' '); /* print |n| spaces to begin line~2 */
13149 }
13150 if ( m+n<=mp->error_line ) p=mp->first_count+m; 
13151 else p=mp->first_count+(mp->error_line-n-3);
13152 for (q=mp->first_count;q<=p-1;q++) {
13153   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13154 }
13155 if ( m+n>mp->error_line ) mp_print(mp, "...")
13156
13157 @ But the trick is distracting us from our current goal, which is to
13158 understand the input state. So let's concentrate on the data structures that
13159 are being pseudoprinted as we finish up the |show_context| procedure.
13160
13161 @<Pseudoprint the line@>=
13162 begin_pseudoprint;
13163 if ( limit>0 ) {
13164   for (i=start;i<=limit-1;i++) {
13165     if ( i==loc ) set_trick_count;
13166     mp_print_str(mp, mp->buffer[i]);
13167   }
13168 }
13169
13170 @ @<Pseudoprint the token list@>=
13171 begin_pseudoprint;
13172 if ( token_type!=macro ) mp_show_token_list(mp, start,loc,100000,0);
13173 else mp_show_macro(mp, start,loc,100000)
13174
13175 @ Here is the missing piece of |show_token_list| that is activated when the
13176 token beginning line~2 is about to be shown:
13177
13178 @<Do magic computation@>=set_trick_count
13179
13180 @* \[28] Maintaining the input stacks.
13181 The following subroutines change the input status in commonly needed ways.
13182
13183 First comes |push_input|, which stores the current state and creates a
13184 new level (having, initially, the same properties as the old).
13185
13186 @d push_input  { /* enter a new input level, save the old */
13187   if ( mp->input_ptr>mp->max_in_stack ) {
13188     mp->max_in_stack=mp->input_ptr;
13189     if ( mp->input_ptr==mp->stack_size ) {
13190       int l = (mp->stack_size+(mp->stack_size>>2));
13191       XREALLOC(mp->input_stack, l, in_state_record);
13192       mp->stack_size = l;
13193     }         
13194   }
13195   mp->input_stack[mp->input_ptr]=mp->cur_input; /* stack the record */
13196   incr(mp->input_ptr);
13197 }
13198
13199 @ And of course what goes up must come down.
13200
13201 @d pop_input { /* leave an input level, re-enter the old */
13202     decr(mp->input_ptr); mp->cur_input=mp->input_stack[mp->input_ptr];
13203   }
13204
13205 @ Here is a procedure that starts a new level of token-list input, given
13206 a token list |p| and its type |t|. If |t=macro|, the calling routine should
13207 set |name|, reset~|loc|, and increase the macro's reference count.
13208
13209 @d back_list(A) mp_begin_token_list(mp, (A),backed_up) /* backs up a simple token list */
13210
13211 @c void mp_begin_token_list (MP mp,pointer p, quarterword t)  { 
13212   push_input; start=p; token_type=t;
13213   param_start=mp->param_ptr; loc=p;
13214 }
13215
13216 @ When a token list has been fully scanned, the following computations
13217 should be done as we leave that level of input.
13218 @^inner loop@>
13219
13220 @c void mp_end_token_list (MP mp) { /* leave a token-list input level */
13221   pointer p; /* temporary register */
13222   if ( token_type>=backed_up ) { /* token list to be deleted */
13223     if ( token_type<=inserted ) { 
13224       mp_flush_token_list(mp, start); goto DONE;
13225     } else {
13226       mp_delete_mac_ref(mp, start); /* update reference count */
13227     }
13228   }
13229   while ( mp->param_ptr>param_start ) { /* parameters must be flushed */
13230     decr(mp->param_ptr);
13231     p=mp->param_stack[mp->param_ptr];
13232     if ( p!=null ) {
13233       if ( link(p)==mp_void ) { /* it's an \&{expr} parameter */
13234         mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
13235       } else {
13236         mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
13237       }
13238     }
13239   }
13240 DONE: 
13241   pop_input; check_interrupt;
13242 }
13243
13244 @ The contents of |cur_cmd,cur_mod,cur_sym| are placed into an equivalent
13245 token by the |cur_tok| routine.
13246 @^inner loop@>
13247
13248 @c @<Declare the procedure called |make_exp_copy|@>;
13249 pointer mp_cur_tok (MP mp) {
13250   pointer p; /* a new token node */
13251   small_number save_type; /* |cur_type| to be restored */
13252   integer save_exp; /* |cur_exp| to be restored */
13253   if ( mp->cur_sym==0 ) {
13254     if ( mp->cur_cmd==capsule_token ) {
13255       save_type=mp->cur_type; save_exp=mp->cur_exp;
13256       mp_make_exp_copy(mp, mp->cur_mod); p=mp_stash_cur_exp(mp); link(p)=null;
13257       mp->cur_type=save_type; mp->cur_exp=save_exp;
13258     } else { 
13259       p=mp_get_node(mp, token_node_size);
13260       value(p)=mp->cur_mod; name_type(p)=mp_token;
13261       if ( mp->cur_cmd==numeric_token ) type(p)=mp_known;
13262       else type(p)=mp_string_type;
13263     }
13264   } else { 
13265     fast_get_avail(p); info(p)=mp->cur_sym;
13266   }
13267   return p;
13268 }
13269
13270 @ Sometimes \MP\ has read too far and wants to ``unscan'' what it has
13271 seen. The |back_input| procedure takes care of this by putting the token
13272 just scanned back into the input stream, ready to be read again.
13273 If |cur_sym<>0|, the values of |cur_cmd| and |cur_mod| are irrelevant.
13274
13275 @<Declarations@>= 
13276 void mp_back_input (MP mp);
13277
13278 @ @c void mp_back_input (MP mp) {/* undoes one token of input */
13279   pointer p; /* a token list of length one */
13280   p=mp_cur_tok(mp);
13281   while ( token_state &&(loc==null) ) 
13282     mp_end_token_list(mp); /* conserve stack space */
13283   back_list(p);
13284 }
13285
13286 @ The |back_error| routine is used when we want to restore or replace an
13287 offending token just before issuing an error message.  We disable interrupts
13288 during the call of |back_input| so that the help message won't be lost.
13289
13290 @<Declarations@>=
13291 void mp_error (MP mp);
13292 void mp_back_error (MP mp);
13293
13294 @ @c void mp_back_error (MP mp) { /* back up one token and call |error| */
13295   mp->OK_to_interrupt=false; 
13296   mp_back_input(mp); 
13297   mp->OK_to_interrupt=true; mp_error(mp);
13298 }
13299 void mp_ins_error (MP mp) { /* back up one inserted token and call |error| */
13300   mp->OK_to_interrupt=false; 
13301   mp_back_input(mp); token_type=inserted;
13302   mp->OK_to_interrupt=true; mp_error(mp);
13303 }
13304
13305 @ The |begin_file_reading| procedure starts a new level of input for lines
13306 of characters to be read from a file, or as an insertion from the
13307 terminal. It does not take care of opening the file, nor does it set |loc|
13308 or |limit| or |line|.
13309 @^system dependencies@>
13310
13311 @c void mp_begin_file_reading (MP mp) { 
13312   if ( mp->in_open==mp->max_in_open ) 
13313     mp_overflow(mp, "text input levels",mp->max_in_open);
13314 @:MetaPost capacity exceeded text input levels}{\quad text input levels@>
13315   if ( mp->first==mp->buf_size ) 
13316     mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13317   incr(mp->in_open); push_input; index=mp->in_open;
13318   mp->mpx_name[index]=absent;
13319   start=mp->first;
13320   name=is_term; /* |terminal_input| is now |true| */
13321 }
13322
13323 @ Conversely, the variables must be downdated when such a level of input
13324 is finished.  Any associated \.{MPX} file must also be closed and popped
13325 off the file stack.
13326
13327 @c void mp_end_file_reading (MP mp) { 
13328   if ( mp->in_open>index ) {
13329     if ( (mp->mpx_name[mp->in_open]==absent)||(name<=max_spec_src) ) {
13330       mp_confusion(mp, "endinput");
13331 @:this can't happen endinput}{\quad endinput@>
13332     } else { 
13333       (mp->close_file)(mp->input_file[mp->in_open]); /* close an \.{MPX} file */
13334       delete_str_ref(mp->mpx_name[mp->in_open]);
13335       decr(mp->in_open);
13336     }
13337   }
13338   mp->first=start;
13339   if ( index!=mp->in_open ) mp_confusion(mp, "endinput");
13340   if ( name>max_spec_src ) {
13341     (mp->close_file)(cur_file);
13342     delete_str_ref(name);
13343     xfree(in_name); 
13344     xfree(in_area);
13345   }
13346   pop_input; decr(mp->in_open);
13347 }
13348
13349 @ Here is a function that tries to resume input from an \.{MPX} file already
13350 associated with the current input file.  It returns |false| if this doesn't
13351 work.
13352
13353 @c boolean mp_begin_mpx_reading (MP mp) { 
13354   if ( mp->in_open!=index+1 ) {
13355      return false;
13356   } else { 
13357     if ( mp->mpx_name[mp->in_open]<=absent ) mp_confusion(mp, "mpx");
13358 @:this can't happen mpx}{\quad mpx@>
13359     if ( mp->first==mp->buf_size ) 
13360       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13361     push_input; index=mp->in_open;
13362     start=mp->first;
13363     name=mp->mpx_name[mp->in_open]; add_str_ref(name);
13364     @<Put an empty line in the input buffer@>;
13365     return true;
13366   }
13367 }
13368
13369 @ This procedure temporarily stops reading an \.{MPX} file.
13370
13371 @c void mp_end_mpx_reading (MP mp) { 
13372   if ( mp->in_open!=index ) mp_confusion(mp, "mpx");
13373 @:this can't happen mpx}{\quad mpx@>
13374   if ( loc<limit ) {
13375     @<Complain that we are not at the end of a line in the \.{MPX} file@>;
13376   }
13377   mp->first=start;
13378   pop_input;
13379 }
13380
13381 @ Here we enforce a restriction that simplifies the input stacks considerably.
13382 This should not inconvenience the user because \.{MPX} files are generated
13383 by an auxiliary program called \.{DVItoMP}.
13384
13385 @ @<Complain that we are not at the end of a line in the \.{MPX} file@>=
13386
13387 print_err("`mpxbreak' must be at the end of a line");
13388 help4("This file contains picture expressions for btex...etex")
13389   ("blocks.  Such files are normally generated automatically")
13390   ("but this one seems to be messed up.  I'm going to ignore")
13391   ("the rest of this line.");
13392 mp_error(mp);
13393 }
13394
13395 @ In order to keep the stack from overflowing during a long sequence of
13396 inserted `\.{show}' commands, the following routine removes completed
13397 error-inserted lines from memory.
13398
13399 @c void mp_clear_for_error_prompt (MP mp) { 
13400   while ( file_state && terminal_input &&
13401     (mp->input_ptr>0)&&(loc==limit) ) mp_end_file_reading(mp);
13402   mp_print_ln(mp); clear_terminal;
13403 }
13404
13405 @ To get \MP's whole input mechanism going, we perform the following
13406 actions.
13407
13408 @<Initialize the input routines@>=
13409 { mp->input_ptr=0; mp->max_in_stack=0;
13410   mp->in_open=0; mp->open_parens=0; mp->max_buf_stack=0;
13411   mp->param_ptr=0; mp->max_param_stack=0;
13412   mp->first=1;
13413   start=1; index=0; line=0; name=is_term;
13414   mp->mpx_name[0]=absent;
13415   mp->force_eof=false;
13416   if ( ! mp_init_terminal(mp) ) mp_jump_out(mp);
13417   limit=mp->last; mp->first=mp->last+1; 
13418   /* |init_terminal| has set |loc| and |last| */
13419 }
13420
13421 @* \[29] Getting the next token.
13422 The heart of \MP's input mechanism is the |get_next| procedure, which
13423 we shall develop in the next few sections of the program. Perhaps we
13424 shouldn't actually call it the ``heart,'' however; it really acts as \MP's
13425 eyes and mouth, reading the source files and gobbling them up. And it also
13426 helps \MP\ to regurgitate stored token lists that are to be processed again.
13427
13428 The main duty of |get_next| is to input one token and to set |cur_cmd|
13429 and |cur_mod| to that token's command code and modifier. Furthermore, if
13430 the input token is a symbolic token, that token's |hash| address
13431 is stored in |cur_sym|; otherwise |cur_sym| is set to zero.
13432
13433 Underlying this simple description is a certain amount of complexity
13434 because of all the cases that need to be handled.
13435 However, the inner loop of |get_next| is reasonably short and fast.
13436
13437 @ Before getting into |get_next|, we need to consider a mechanism by which
13438 \MP\ helps keep errors from propagating too far. Whenever the program goes
13439 into a mode where it keeps calling |get_next| repeatedly until a certain
13440 condition is met, it sets |scanner_status| to some value other than |normal|.
13441 Then if an input file ends, or if an `\&{outer}' symbol appears,
13442 an appropriate error recovery will be possible.
13443
13444 The global variable |warning_info| helps in this error recovery by providing
13445 additional information. For example, |warning_info| might indicate the
13446 name of a macro whose replacement text is being scanned.
13447
13448 @d normal 0 /* |scanner_status| at ``quiet times'' */
13449 @d skipping 1 /* |scanner_status| when false conditional text is being skipped */
13450 @d flushing 2 /* |scanner_status| when junk after a statement is being ignored */
13451 @d absorbing 3 /* |scanner_status| when a \&{text} parameter is being scanned */
13452 @d var_defining 4 /* |scanner_status| when a \&{vardef} is being scanned */
13453 @d op_defining 5 /* |scanner_status| when a macro \&{def} is being scanned */
13454 @d loop_defining 6 /* |scanner_status| when a \&{for} loop is being scanned */
13455 @d tex_flushing 7 /* |scanner_status| when skipping \TeX\ material */
13456
13457 @<Glob...@>=
13458 integer scanner_status; /* are we scanning at high speed? */
13459 integer warning_info; /* if so, what else do we need to know,
13460     in case an error occurs? */
13461
13462 @ @<Initialize the input routines@>=
13463 mp->scanner_status=normal;
13464
13465 @ The following subroutine
13466 is called when an `\&{outer}' symbolic token has been scanned or
13467 when the end of a file has been reached. These two cases are distinguished
13468 by |cur_sym|, which is zero at the end of a file.
13469
13470 @c boolean mp_check_outer_validity (MP mp) {
13471   pointer p; /* points to inserted token list */
13472   if ( mp->scanner_status==normal ) {
13473     return true;
13474   } else if ( mp->scanner_status==tex_flushing ) {
13475     @<Check if the file has ended while flushing \TeX\ material and set the
13476       result value for |check_outer_validity|@>;
13477   } else { 
13478     mp->deletions_allowed=false;
13479     @<Back up an outer symbolic token so that it can be reread@>;
13480     if ( mp->scanner_status>skipping ) {
13481       @<Tell the user what has run away and try to recover@>;
13482     } else { 
13483       print_err("Incomplete if; all text was ignored after line ");
13484 @.Incomplete if...@>
13485       mp_print_int(mp, mp->warning_info);
13486       help3("A forbidden `outer' token occurred in skipped text.")
13487         ("This kind of error happens when you say `if...' and forget")
13488         ("the matching `fi'. I've inserted a `fi'; this might work.");
13489       if ( mp->cur_sym==0 ) 
13490         mp->help_line[2]="The file ended while I was skipping conditional text.";
13491       mp->cur_sym=frozen_fi; mp_ins_error(mp);
13492     }
13493     mp->deletions_allowed=true; 
13494         return false;
13495   }
13496 }
13497
13498 @ @<Check if the file has ended while flushing \TeX\ material and set...@>=
13499 if ( mp->cur_sym!=0 ) { 
13500    return true;
13501 } else { 
13502   mp->deletions_allowed=false;
13503   print_err("TeX mode didn't end; all text was ignored after line ");
13504   mp_print_int(mp, mp->warning_info);
13505   help2("The file ended while I was looking for the `etex' to")
13506     ("finish this TeX material.  I've inserted `etex' now.");
13507   mp->cur_sym = frozen_etex;
13508   mp_ins_error(mp);
13509   mp->deletions_allowed=true;
13510   return false;
13511 }
13512
13513 @ @<Back up an outer symbolic token so that it can be reread@>=
13514 if ( mp->cur_sym!=0 ) {
13515   p=mp_get_avail(mp); info(p)=mp->cur_sym;
13516   back_list(p); /* prepare to read the symbolic token again */
13517 }
13518
13519 @ @<Tell the user what has run away...@>=
13520
13521   mp_runaway(mp); /* print the definition-so-far */
13522   if ( mp->cur_sym==0 ) {
13523     print_err("File ended");
13524 @.File ended while scanning...@>
13525   } else { 
13526     print_err("Forbidden token found");
13527 @.Forbidden token found...@>
13528   }
13529   mp_print(mp, " while scanning ");
13530   help4("I suspect you have forgotten an `enddef',")
13531     ("causing me to read past where you wanted me to stop.")
13532     ("I'll try to recover; but if the error is serious,")
13533     ("you'd better type `E' or `X' now and fix your file.");
13534   switch (mp->scanner_status) {
13535     @<Complete the error message,
13536       and set |cur_sym| to a token that might help recover from the error@>
13537   } /* there are no other cases */
13538   mp_ins_error(mp);
13539 }
13540
13541 @ As we consider various kinds of errors, it is also appropriate to
13542 change the first line of the help message just given; |help_line[3]|
13543 points to the string that might be changed.
13544
13545 @<Complete the error message,...@>=
13546 case flushing: 
13547   mp_print(mp, "to the end of the statement");
13548   mp->help_line[3]="A previous error seems to have propagated,";
13549   mp->cur_sym=frozen_semicolon;
13550   break;
13551 case absorbing: 
13552   mp_print(mp, "a text argument");
13553   mp->help_line[3]="It seems that a right delimiter was left out,";
13554   if ( mp->warning_info==0 ) {
13555     mp->cur_sym=frozen_end_group;
13556   } else { 
13557     mp->cur_sym=frozen_right_delimiter;
13558     equiv(frozen_right_delimiter)=mp->warning_info;
13559   }
13560   break;
13561 case var_defining:
13562 case op_defining: 
13563   mp_print(mp, "the definition of ");
13564   if ( mp->scanner_status==op_defining ) 
13565      mp_print_text(mp->warning_info);
13566   else 
13567      mp_print_variable_name(mp, mp->warning_info);
13568   mp->cur_sym=frozen_end_def;
13569   break;
13570 case loop_defining: 
13571   mp_print(mp, "the text of a "); 
13572   mp_print_text(mp->warning_info);
13573   mp_print(mp, " loop");
13574   mp->help_line[3]="I suspect you have forgotten an `endfor',";
13575   mp->cur_sym=frozen_end_for;
13576   break;
13577
13578 @ The |runaway| procedure displays the first part of the text that occurred
13579 when \MP\ began its special |scanner_status|, if that text has been saved.
13580
13581 @<Declare the procedure called |runaway|@>=
13582 void mp_runaway (MP mp) { 
13583   if ( mp->scanner_status>flushing ) { 
13584      mp_print_nl(mp, "Runaway ");
13585          switch (mp->scanner_status) { 
13586          case absorbing: mp_print(mp, "text?"); break;
13587          case var_defining: 
13588      case op_defining: mp_print(mp,"definition?"); break;
13589      case loop_defining: mp_print(mp, "loop?"); break;
13590      } /* there are no other cases */
13591      mp_print_ln(mp); 
13592      mp_show_token_list(mp, link(hold_head),null,mp->error_line-10,0);
13593   }
13594 }
13595
13596 @ We need to mention a procedure that may be called by |get_next|.
13597
13598 @<Declarations@>= 
13599 void mp_firm_up_the_line (MP mp);
13600
13601 @ And now we're ready to take the plunge into |get_next| itself.
13602 Note that the behavior depends on the |scanner_status| because percent signs
13603 and double quotes need to be passed over when skipping TeX material.
13604
13605 @c 
13606 void mp_get_next (MP mp) {
13607   /* sets |cur_cmd|, |cur_mod|, |cur_sym| to next token */
13608 @^inner loop@>
13609   /*restart*/ /* go here to get the next input token */
13610   /*exit*/ /* go here when the next input token has been got */
13611   /*|common_ending|*/ /* go here to finish getting a symbolic token */
13612   /*found*/ /* go here when the end of a symbolic token has been found */
13613   /*switch*/ /* go here to branch on the class of an input character */
13614   /*|start_numeric_token|,|start_decimal_token|,|fin_numeric_token|,|done|*/
13615     /* go here at crucial stages when scanning a number */
13616   int k; /* an index into |buffer| */
13617   ASCII_code c; /* the current character in the buffer */
13618   ASCII_code class; /* its class number */
13619   integer n,f; /* registers for decimal-to-binary conversion */
13620 RESTART: 
13621   mp->cur_sym=0;
13622   if ( file_state ) {
13623     @<Input from external file; |goto restart| if no input found,
13624     or |return| if a non-symbolic token is found@>;
13625   } else {
13626     @<Input from token list; |goto restart| if end of list or
13627       if a parameter needs to be expanded,
13628       or |return| if a non-symbolic token is found@>;
13629   }
13630 COMMON_ENDING: 
13631   @<Finish getting the symbolic token in |cur_sym|;
13632    |goto restart| if it is illegal@>;
13633 }
13634
13635 @ When a symbolic token is declared to be `\&{outer}', its command code
13636 is increased by |outer_tag|.
13637 @^inner loop@>
13638
13639 @<Finish getting the symbolic token in |cur_sym|...@>=
13640 mp->cur_cmd=eq_type(mp->cur_sym); mp->cur_mod=equiv(mp->cur_sym);
13641 if ( mp->cur_cmd>=outer_tag ) {
13642   if ( mp_check_outer_validity(mp) ) 
13643     mp->cur_cmd=mp->cur_cmd-outer_tag;
13644   else 
13645     goto RESTART;
13646 }
13647
13648 @ A percent sign appears in |buffer[limit]|; this makes it unnecessary
13649 to have a special test for end-of-line.
13650 @^inner loop@>
13651
13652 @<Input from external file;...@>=
13653
13654 SWITCH: 
13655   c=mp->buffer[loc]; incr(loc); class=mp->char_class[c];
13656   switch (class) {
13657   case digit_class: goto START_NUMERIC_TOKEN; break;
13658   case period_class: 
13659     class=mp->char_class[mp->buffer[loc]];
13660     if ( class>period_class ) {
13661       goto SWITCH;
13662     } else if ( class<period_class ) { /* |class=digit_class| */
13663       n=0; goto START_DECIMAL_TOKEN;
13664     }
13665 @:. }{\..\ token@>
13666     break;
13667   case space_class: goto SWITCH; break;
13668   case percent_class: 
13669     if ( mp->scanner_status==tex_flushing ) {
13670       if ( loc<limit ) goto SWITCH;
13671     }
13672     @<Move to next line of file, or |goto restart| if there is no next line@>;
13673     check_interrupt;
13674     goto SWITCH;
13675     break;
13676   case string_class: 
13677     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13678     else @<Get a string token and |return|@>;
13679     break;
13680   case isolated_classes: 
13681     k=loc-1; goto FOUND; break;
13682   case invalid_class: 
13683     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13684     else @<Decry the invalid character and |goto restart|@>;
13685     break;
13686   default: break; /* letters, etc. */
13687   }
13688   k=loc-1;
13689   while ( mp->char_class[mp->buffer[loc]]==class ) incr(loc);
13690   goto FOUND;
13691 START_NUMERIC_TOKEN:
13692   @<Get the integer part |n| of a numeric token;
13693     set |f:=0| and |goto fin_numeric_token| if there is no decimal point@>;
13694 START_DECIMAL_TOKEN:
13695   @<Get the fraction part |f| of a numeric token@>;
13696 FIN_NUMERIC_TOKEN:
13697   @<Pack the numeric and fraction parts of a numeric token
13698     and |return|@>;
13699 FOUND: 
13700   mp->cur_sym=mp_id_lookup(mp, k,loc-k);
13701 }
13702
13703 @ We go to |restart| instead of to |SWITCH|, because |state| might equal
13704 |token_list| after the error has been dealt with
13705 (cf.\ |clear_for_error_prompt|).
13706
13707 @<Decry the invalid...@>=
13708
13709   print_err("Text line contains an invalid character");
13710 @.Text line contains...@>
13711   help2("A funny symbol that I can\'t read has just been input.")
13712     ("Continue, and I'll forget that it ever happened.");
13713   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13714   goto RESTART;
13715 }
13716
13717 @ @<Get a string token and |return|@>=
13718
13719   if ( mp->buffer[loc]=='"' ) {
13720     mp->cur_mod=rts("");
13721   } else { 
13722     k=loc; mp->buffer[limit+1]='"';
13723     do {  
13724      incr(loc);
13725     } while (mp->buffer[loc]!='"');
13726     if ( loc>limit ) {
13727       @<Decry the missing string delimiter and |goto restart|@>;
13728     }
13729     if ( loc==k+1 ) {
13730       mp->cur_mod=mp->buffer[k];
13731     } else { 
13732       str_room(loc-k);
13733       do {  
13734         append_char(mp->buffer[k]); incr(k);
13735       } while (k!=loc);
13736       mp->cur_mod=mp_make_string(mp);
13737     }
13738   }
13739   incr(loc); mp->cur_cmd=string_token; 
13740   return;
13741 }
13742
13743 @ We go to |restart| after this error message, not to |SWITCH|,
13744 because the |clear_for_error_prompt| routine might have reinstated
13745 |token_state| after |error| has finished.
13746
13747 @<Decry the missing string delimiter and |goto restart|@>=
13748
13749   loc=limit; /* the next character to be read on this line will be |"%"| */
13750   print_err("Incomplete string token has been flushed");
13751 @.Incomplete string token...@>
13752   help3("Strings should finish on the same line as they began.")
13753     ("I've deleted the partial string; you might want to")
13754     ("insert another by typing, e.g., `I\"new string\"'.");
13755   mp->deletions_allowed=false; mp_error(mp);
13756   mp->deletions_allowed=true; 
13757   goto RESTART;
13758 }
13759
13760 @ @<Get the integer part |n| of a numeric token...@>=
13761 n=c-'0';
13762 while ( mp->char_class[mp->buffer[loc]]==digit_class ) {
13763   if ( n<32768 ) n=10*n+mp->buffer[loc]-'0';
13764   incr(loc);
13765 }
13766 if ( mp->buffer[loc]=='.' ) 
13767   if ( mp->char_class[mp->buffer[loc+1]]==digit_class ) 
13768     goto DONE;
13769 f=0; 
13770 goto FIN_NUMERIC_TOKEN;
13771 DONE: incr(loc)
13772
13773 @ @<Get the fraction part |f| of a numeric token@>=
13774 k=0;
13775 do { 
13776   if ( k<17 ) { /* digits for |k>=17| cannot affect the result */
13777     mp->dig[k]=mp->buffer[loc]-'0'; incr(k);
13778   }
13779   incr(loc);
13780 } while (mp->char_class[mp->buffer[loc]]==digit_class);
13781 f=mp_round_decimals(mp, k);
13782 if ( f==unity ) {
13783   incr(n); f=0;
13784 }
13785
13786 @ @<Pack the numeric and fraction parts of a numeric token and |return|@>=
13787 if ( n<32768 ) {
13788   @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>;
13789 } else if ( mp->scanner_status!=tex_flushing ) {
13790   print_err("Enormous number has been reduced");
13791 @.Enormous number...@>
13792   help2("I can\'t handle numbers bigger than 32767.99998;")
13793     ("so I've changed your constant to that maximum amount.");
13794   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13795   mp->cur_mod=el_gordo;
13796 }
13797 mp->cur_cmd=numeric_token; return
13798
13799 @ @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>=
13800
13801   mp->cur_mod=n*unity+f;
13802   if ( mp->cur_mod>=fraction_one ) {
13803     if ( (mp->internal[mp_warning_check]>0) &&
13804          (mp->scanner_status!=tex_flushing) ) {
13805       print_err("Number is too large (");
13806       mp_print_scaled(mp, mp->cur_mod);
13807       mp_print_char(mp, ')');
13808       help3("It is at least 4096. Continue and I'll try to cope")
13809       ("with that big value; but it might be dangerous.")
13810       ("(Set warningcheck:=0 to suppress this message.)");
13811       mp_error(mp);
13812     }
13813   }
13814 }
13815
13816 @ Let's consider now what happens when |get_next| is looking at a token list.
13817 @^inner loop@>
13818
13819 @<Input from token list;...@>=
13820 if ( loc>=mp->hi_mem_min ) { /* one-word token */
13821   mp->cur_sym=info(loc); loc=link(loc); /* move to next */
13822   if ( mp->cur_sym>=expr_base ) {
13823     if ( mp->cur_sym>=suffix_base ) {
13824       @<Insert a suffix or text parameter and |goto restart|@>;
13825     } else { 
13826       mp->cur_cmd=capsule_token;
13827       mp->cur_mod=mp->param_stack[param_start+mp->cur_sym-(expr_base)];
13828       mp->cur_sym=0; return;
13829     }
13830   }
13831 } else if ( loc>null ) {
13832   @<Get a stored numeric or string or capsule token and |return|@>
13833 } else { /* we are done with this token list */
13834   mp_end_token_list(mp); goto RESTART; /* resume previous level */
13835 }
13836
13837 @ @<Insert a suffix or text parameter...@>=
13838
13839   if ( mp->cur_sym>=text_base ) mp->cur_sym=mp->cur_sym-mp->param_size;
13840   /* |param_size=text_base-suffix_base| */
13841   mp_begin_token_list(mp,
13842                       mp->param_stack[param_start+mp->cur_sym-(suffix_base)],
13843                       parameter);
13844   goto RESTART;
13845 }
13846
13847 @ @<Get a stored numeric or string or capsule token...@>=
13848
13849   if ( name_type(loc)==mp_token ) {
13850     mp->cur_mod=value(loc);
13851     if ( type(loc)==mp_known ) {
13852       mp->cur_cmd=numeric_token;
13853     } else { 
13854       mp->cur_cmd=string_token; add_str_ref(mp->cur_mod);
13855     }
13856   } else { 
13857     mp->cur_mod=loc; mp->cur_cmd=capsule_token;
13858   };
13859   loc=link(loc); return;
13860 }
13861
13862 @ All of the easy branches of |get_next| have now been taken care of.
13863 There is one more branch.
13864
13865 @<Move to next line of file, or |goto restart|...@>=
13866 if ( name>max_spec_src ) {
13867   @<Read next line of file into |buffer|, or
13868     |goto restart| if the file has ended@>;
13869 } else { 
13870   if ( mp->input_ptr>0 ) {
13871      /* text was inserted during error recovery or by \&{scantokens} */
13872     mp_end_file_reading(mp); goto RESTART; /* resume previous level */
13873   }
13874   if ( mp->selector<log_only || mp->selector>=write_file) mp_open_log_file(mp);
13875   if ( mp->interaction>mp_nonstop_mode ) {
13876     if ( limit==start ) /* previous line was empty */
13877       mp_print_nl(mp, "(Please type a command or say `end')");
13878 @.Please type...@>
13879     mp_print_ln(mp); mp->first=start;
13880     prompt_input("*"); /* input on-line into |buffer| */
13881 @.*\relax@>
13882     limit=mp->last; mp->buffer[limit]='%';
13883     mp->first=limit+1; loc=start;
13884   } else {
13885     mp_fatal_error(mp, "*** (job aborted, no legal end found)");
13886 @.job aborted@>
13887     /* nonstop mode, which is intended for overnight batch processing,
13888     never waits for on-line input */
13889   }
13890 }
13891
13892 @ The global variable |force_eof| is normally |false|; it is set |true|
13893 by an \&{endinput} command.
13894
13895 @<Glob...@>=
13896 boolean force_eof; /* should the next \&{input} be aborted early? */
13897
13898 @ We must decrement |loc| in order to leave the buffer in a valid state
13899 when an error condition causes us to |goto restart| without calling
13900 |end_file_reading|.
13901
13902 @<Read next line of file into |buffer|, or
13903   |goto restart| if the file has ended@>=
13904
13905   incr(line); mp->first=start;
13906   if ( ! mp->force_eof ) {
13907     if ( mp_input_ln(mp, cur_file ) ) /* not end of file */
13908       mp_firm_up_the_line(mp); /* this sets |limit| */
13909     else 
13910       mp->force_eof=true;
13911   };
13912   if ( mp->force_eof ) {
13913     mp->force_eof=false;
13914     decr(loc);
13915     if ( mpx_reading ) {
13916       @<Complain that the \.{MPX} file ended unexpectly; then set
13917         |cur_sym:=frozen_mpx_break| and |goto comon_ending|@>;
13918     } else { 
13919       mp_print_char(mp, ')'); decr(mp->open_parens);
13920       update_terminal; /* show user that file has been read */
13921       mp_end_file_reading(mp); /* resume previous level */
13922       if ( mp_check_outer_validity(mp) ) goto  RESTART;  
13923       else goto RESTART;
13924     }
13925   }
13926   mp->buffer[limit]='%'; mp->first=limit+1; loc=start; /* ready to read */
13927 }
13928
13929 @ We should never actually come to the end of an \.{MPX} file because such
13930 files should have an \&{mpxbreak} after the translation of the last
13931 \&{btex}$\,\ldots\,$\&{etex} block.
13932
13933 @<Complain that the \.{MPX} file ended unexpectly; then set...@>=
13934
13935   mp->mpx_name[index]=finished;
13936   print_err("mpx file ended unexpectedly");
13937   help4("The file had too few picture expressions for btex...etex")
13938     ("blocks.  Such files are normally generated automatically")
13939     ("but this one got messed up.  You might want to insert a")
13940     ("picture expression now.");
13941   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13942   mp->cur_sym=frozen_mpx_break; goto COMMON_ENDING;
13943 }
13944
13945 @ Sometimes we want to make it look as though we have just read a blank line
13946 without really doing so.
13947
13948 @<Put an empty line in the input buffer@>=
13949 mp->last=mp->first; limit=mp->last; /* simulate |input_ln| and |firm_up_the_line| */
13950 mp->buffer[limit]='%'; mp->first=limit+1; loc=start
13951
13952 @ If the user has set the |mp_pausing| parameter to some positive value,
13953 and if nonstop mode has not been selected, each line of input is displayed
13954 on the terminal and the transcript file, followed by `\.{=>}'.
13955 \MP\ waits for a response. If the response is null (i.e., if nothing is
13956 typed except perhaps a few blank spaces), the original
13957 line is accepted as it stands; otherwise the line typed is
13958 used instead of the line in the file.
13959
13960 @c void mp_firm_up_the_line (MP mp) {
13961   size_t k; /* an index into |buffer| */
13962   limit=mp->last;
13963   if ( mp->internal[mp_pausing]>0) if ( mp->interaction>mp_nonstop_mode ) {
13964     wake_up_terminal; mp_print_ln(mp);
13965     if ( start<limit ) {
13966       for (k=(size_t)start;k<=(size_t)(limit-1);k++) {
13967         mp_print_str(mp, mp->buffer[k]);
13968       } 
13969     }
13970     mp->first=limit; prompt_input("=>"); /* wait for user response */
13971 @.=>@>
13972     if ( mp->last>mp->first ) {
13973       for (k=mp->first;k<=mp->last-1;k++) { /* move line down in buffer */
13974         mp->buffer[k+start-mp->first]=mp->buffer[k];
13975       }
13976       limit=start+mp->last-mp->first;
13977     }
13978   }
13979 }
13980
13981 @* \[30] Dealing with \TeX\ material.
13982 The \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}$\,\ldots\,$\&{etex}
13983 features need to be implemented at a low level in the scanning process
13984 so that \MP\ can stay in synch with the a preprocessor that treats
13985 blocks of \TeX\ material as they occur in the input file without trying
13986 to expand \MP\ macros.  Thus we need a special version of |get_next|
13987 that does not expand macros and such but does handle \&{btex},
13988 \&{verbatimtex}, etc.
13989
13990 The special version of |get_next| is called |get_t_next|.  It works by flushing
13991 \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}\allowbreak
13992 $\,\ldots\,$\&{etex} blocks, switching to the \.{MPX} file when it sees
13993 \&{btex}, and switching back when it sees \&{mpxbreak}.
13994
13995 @d btex_code 0
13996 @d verbatim_code 1
13997
13998 @ @<Put each...@>=
13999 mp_primitive(mp, "btex",start_tex,btex_code);
14000 @:btex_}{\&{btex} primitive@>
14001 mp_primitive(mp, "verbatimtex",start_tex,verbatim_code);
14002 @:verbatimtex_}{\&{verbatimtex} primitive@>
14003 mp_primitive(mp, "etex",etex_marker,0); mp->eqtb[frozen_etex]=mp->eqtb[mp->cur_sym];
14004 @:etex_}{\&{etex} primitive@>
14005 mp_primitive(mp, "mpxbreak",mpx_break,0); mp->eqtb[frozen_mpx_break]=mp->eqtb[mp->cur_sym];
14006 @:mpx_break_}{\&{mpxbreak} primitive@>
14007
14008 @ @<Cases of |print_cmd...@>=
14009 case start_tex: if ( m==btex_code ) mp_print(mp, "btex");
14010   else mp_print(mp, "verbatimtex"); break;
14011 case etex_marker: mp_print(mp, "etex"); break;
14012 case mpx_break: mp_print(mp, "mpxbreak"); break;
14013
14014 @ Actually, |get_t_next| is a macro that avoids procedure overhead except
14015 in the unusual case where \&{btex}, \&{verbatimtex}, \&{etex}, or \&{mpxbreak}
14016 is encountered.
14017
14018 @d get_t_next {mp_get_next(mp); if ( mp->cur_cmd<=max_pre_command ) mp_t_next(mp); }
14019
14020 @<Declarations@>=
14021 void mp_start_mpx_input (MP mp);
14022
14023 @ @c 
14024 void mp_t_next (MP mp) {
14025   int old_status; /* saves the |scanner_status| */
14026   integer old_info; /* saves the |warning_info| */
14027   while ( mp->cur_cmd<=max_pre_command ) {
14028     if ( mp->cur_cmd==mpx_break ) {
14029       if ( ! file_state || (mp->mpx_name[index]==absent) ) {
14030         @<Complain about a misplaced \&{mpxbreak}@>;
14031       } else { 
14032         mp_end_mpx_reading(mp); 
14033         goto TEX_FLUSH;
14034       }
14035     } else if ( mp->cur_cmd==start_tex ) {
14036       if ( token_state || (name<=max_spec_src) ) {
14037         @<Complain that we are not reading a file@>;
14038       } else if ( mpx_reading ) {
14039         @<Complain that \.{MPX} files cannot contain \TeX\ material@>;
14040       } else if ( (mp->cur_mod!=verbatim_code)&&
14041                   (mp->mpx_name[index]!=finished) ) {
14042         if ( ! mp_begin_mpx_reading(mp) ) mp_start_mpx_input(mp);
14043       } else {
14044         goto TEX_FLUSH;
14045       }
14046     } else {
14047        @<Complain about a misplaced \&{etex}@>;
14048     }
14049     goto COMMON_ENDING;
14050   TEX_FLUSH: 
14051     @<Flush the \TeX\ material@>;
14052   COMMON_ENDING: 
14053     mp_get_next(mp);
14054   }
14055 }
14056
14057 @ We could be in the middle of an operation such as skipping false conditional
14058 text when \TeX\ material is encountered, so we must be careful to save the
14059 |scanner_status|.
14060
14061 @<Flush the \TeX\ material@>=
14062 old_status=mp->scanner_status;
14063 old_info=mp->warning_info;
14064 mp->scanner_status=tex_flushing;
14065 mp->warning_info=line;
14066 do {  mp_get_next(mp); } while (mp->cur_cmd!=etex_marker);
14067 mp->scanner_status=old_status;
14068 mp->warning_info=old_info
14069
14070 @ @<Complain that \.{MPX} files cannot contain \TeX\ material@>=
14071 { print_err("An mpx file cannot contain btex or verbatimtex blocks");
14072 help4("This file contains picture expressions for btex...etex")
14073   ("blocks.  Such files are normally generated automatically")
14074   ("but this one seems to be messed up.  I'll just keep going")
14075   ("and hope for the best.");
14076 mp_error(mp);
14077 }
14078
14079 @ @<Complain that we are not reading a file@>=
14080 { print_err("You can only use `btex' or `verbatimtex' in a file");
14081 help3("I'll have to ignore this preprocessor command because it")
14082   ("only works when there is a file to preprocess.  You might")
14083   ("want to delete everything up to the next `etex`.");
14084 mp_error(mp);
14085 }
14086
14087 @ @<Complain about a misplaced \&{mpxbreak}@>=
14088 { print_err("Misplaced mpxbreak");
14089 help2("I'll ignore this preprocessor command because it")
14090   ("doesn't belong here");
14091 mp_error(mp);
14092 }
14093
14094 @ @<Complain about a misplaced \&{etex}@>=
14095 { print_err("Extra etex will be ignored");
14096 help1("There is no btex or verbatimtex for this to match");
14097 mp_error(mp);
14098 }
14099
14100 @* \[31] Scanning macro definitions.
14101 \MP\ has a variety of ways to tuck tokens away into token lists for later
14102 use: Macros can be defined with \&{def}, \&{vardef}, \&{primarydef}, etc.;
14103 repeatable code can be defined with \&{for}, \&{forever}, \&{forsuffixes}.
14104 All such operations are handled by the routines in this part of the program.
14105
14106 The modifier part of each command code is zero for the ``ending delimiters''
14107 like \&{enddef} and \&{endfor}.
14108
14109 @d start_def 1 /* command modifier for \&{def} */
14110 @d var_def 2 /* command modifier for \&{vardef} */
14111 @d end_def 0 /* command modifier for \&{enddef} */
14112 @d start_forever 1 /* command modifier for \&{forever} */
14113 @d end_for 0 /* command modifier for \&{endfor} */
14114
14115 @<Put each...@>=
14116 mp_primitive(mp, "def",macro_def,start_def);
14117 @:def_}{\&{def} primitive@>
14118 mp_primitive(mp, "vardef",macro_def,var_def);
14119 @:var_def_}{\&{vardef} primitive@>
14120 mp_primitive(mp, "primarydef",macro_def,secondary_primary_macro);
14121 @:primary_def_}{\&{primarydef} primitive@>
14122 mp_primitive(mp, "secondarydef",macro_def,tertiary_secondary_macro);
14123 @:secondary_def_}{\&{secondarydef} primitive@>
14124 mp_primitive(mp, "tertiarydef",macro_def,expression_tertiary_macro);
14125 @:tertiary_def_}{\&{tertiarydef} primitive@>
14126 mp_primitive(mp, "enddef",macro_def,end_def); mp->eqtb[frozen_end_def]=mp->eqtb[mp->cur_sym];
14127 @:end_def_}{\&{enddef} primitive@>
14128 @#
14129 mp_primitive(mp, "for",iteration,expr_base);
14130 @:for_}{\&{for} primitive@>
14131 mp_primitive(mp, "forsuffixes",iteration,suffix_base);
14132 @:for_suffixes_}{\&{forsuffixes} primitive@>
14133 mp_primitive(mp, "forever",iteration,start_forever);
14134 @:forever_}{\&{forever} primitive@>
14135 mp_primitive(mp, "endfor",iteration,end_for); mp->eqtb[frozen_end_for]=mp->eqtb[mp->cur_sym];
14136 @:end_for_}{\&{endfor} primitive@>
14137
14138 @ @<Cases of |print_cmd...@>=
14139 case macro_def:
14140   if ( m<=var_def ) {
14141     if ( m==start_def ) mp_print(mp, "def");
14142     else if ( m<start_def ) mp_print(mp, "enddef");
14143     else mp_print(mp, "vardef");
14144   } else if ( m==secondary_primary_macro ) { 
14145     mp_print(mp, "primarydef");
14146   } else if ( m==tertiary_secondary_macro ) { 
14147     mp_print(mp, "secondarydef");
14148   } else { 
14149     mp_print(mp, "tertiarydef");
14150   }
14151   break;
14152 case iteration: 
14153   if ( m<=start_forever ) {
14154     if ( m==start_forever ) mp_print(mp, "forever"); 
14155     else mp_print(mp, "endfor");
14156   } else if ( m==expr_base ) {
14157     mp_print(mp, "for"); 
14158   } else { 
14159     mp_print(mp, "forsuffixes");
14160   }
14161   break;
14162
14163 @ Different macro-absorbing operations have different syntaxes, but they
14164 also have a lot in common. There is a list of special symbols that are to
14165 be replaced by parameter tokens; there is a special command code that
14166 ends the definition; the quotation conventions are identical.  Therefore
14167 it makes sense to have most of the work done by a single subroutine. That
14168 subroutine is called |scan_toks|.
14169
14170 The first parameter to |scan_toks| is the command code that will
14171 terminate scanning (either |macro_def|, |loop_repeat|, or |iteration|).
14172
14173 The second parameter, |subst_list|, points to a (possibly empty) list
14174 of two-word nodes whose |info| and |value| fields specify symbol tokens
14175 before and after replacement. The list will be returned to free storage
14176 by |scan_toks|.
14177
14178 The third parameter is simply appended to the token list that is built.
14179 And the final parameter tells how many of the special operations
14180 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#} are to be replaced by suffix parameters.
14181 When such parameters are present, they are called \.{(SUFFIX0)},
14182 \.{(SUFFIX1)}, and \.{(SUFFIX2)}.
14183
14184 @c pointer mp_scan_toks (MP mp,command_code terminator, pointer 
14185   subst_list, pointer tail_end, small_number suffix_count) {
14186   pointer p; /* tail of the token list being built */
14187   pointer q; /* temporary for link management */
14188   integer balance; /* left delimiters minus right delimiters */
14189   p=hold_head; balance=1; link(hold_head)=null;
14190   while (1) { 
14191     get_t_next;
14192     if ( mp->cur_sym>0 ) {
14193       @<Substitute for |cur_sym|, if it's on the |subst_list|@>;
14194       if ( mp->cur_cmd==terminator ) {
14195         @<Adjust the balance; |break| if it's zero@>;
14196       } else if ( mp->cur_cmd==macro_special ) {
14197         @<Handle quoted symbols, \.{\#\AT!}, \.{\AT!}, or \.{\AT!\#}@>;
14198       }
14199     }
14200     link(p)=mp_cur_tok(mp); p=link(p);
14201   }
14202   link(p)=tail_end; mp_flush_node_list(mp, subst_list);
14203   return link(hold_head);
14204 }
14205
14206 @ @<Substitute for |cur_sym|...@>=
14207
14208   q=subst_list;
14209   while ( q!=null ) {
14210     if ( info(q)==mp->cur_sym ) {
14211       mp->cur_sym=value(q); mp->cur_cmd=relax; break;
14212     }
14213     q=link(q);
14214   }
14215 }
14216
14217 @ @<Adjust the balance; |break| if it's zero@>=
14218 if ( mp->cur_mod>0 ) {
14219   incr(balance);
14220 } else { 
14221   decr(balance);
14222   if ( balance==0 )
14223     break;
14224 }
14225
14226 @ Four commands are intended to be used only within macro texts: \&{quote},
14227 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#}. They are variants of a single command
14228 code called |macro_special|.
14229
14230 @d quote 0 /* |macro_special| modifier for \&{quote} */
14231 @d macro_prefix 1 /* |macro_special| modifier for \.{\#\AT!} */
14232 @d macro_at 2 /* |macro_special| modifier for \.{\AT!} */
14233 @d macro_suffix 3 /* |macro_special| modifier for \.{\AT!\#} */
14234
14235 @<Put each...@>=
14236 mp_primitive(mp, "quote",macro_special,quote);
14237 @:quote_}{\&{quote} primitive@>
14238 mp_primitive(mp, "#@@",macro_special,macro_prefix);
14239 @:]]]\#\AT!_}{\.{\#\AT!} primitive@>
14240 mp_primitive(mp, "@@",macro_special,macro_at);
14241 @:]]]\AT!_}{\.{\AT!} primitive@>
14242 mp_primitive(mp, "@@#",macro_special,macro_suffix);
14243 @:]]]\AT!\#_}{\.{\AT!\#} primitive@>
14244
14245 @ @<Cases of |print_cmd...@>=
14246 case macro_special: 
14247   switch (m) {
14248   case macro_prefix: mp_print(mp, "#@@"); break;
14249   case macro_at: mp_print_char(mp, '@@'); break;
14250   case macro_suffix: mp_print(mp, "@@#"); break;
14251   default: mp_print(mp, "quote"); break;
14252   }
14253   break;
14254
14255 @ @<Handle quoted...@>=
14256
14257   if ( mp->cur_mod==quote ) { get_t_next; } 
14258   else if ( mp->cur_mod<=suffix_count ) 
14259     mp->cur_sym=suffix_base-1+mp->cur_mod;
14260 }
14261
14262 @ Here is a routine that's used whenever a token will be redefined. If
14263 the user's token is unredefinable, the `|frozen_inaccessible|' token is
14264 substituted; the latter is redefinable but essentially impossible to use,
14265 hence \MP's tables won't get fouled up.
14266
14267 @c void mp_get_symbol (MP mp) { /* sets |cur_sym| to a safe symbol */
14268 RESTART: 
14269   get_t_next;
14270   if ( (mp->cur_sym==0)||(mp->cur_sym>frozen_inaccessible) ) {
14271     print_err("Missing symbolic token inserted");
14272 @.Missing symbolic token...@>
14273     help3("Sorry: You can\'t redefine a number, string, or expr.")
14274       ("I've inserted an inaccessible symbol so that your")
14275       ("definition will be completed without mixing me up too badly.");
14276     if ( mp->cur_sym>0 )
14277       mp->help_line[2]="Sorry: You can\'t redefine my error-recovery tokens.";
14278     else if ( mp->cur_cmd==string_token ) 
14279       delete_str_ref(mp->cur_mod);
14280     mp->cur_sym=frozen_inaccessible; mp_ins_error(mp); goto RESTART;
14281   }
14282 }
14283
14284 @ Before we actually redefine a symbolic token, we need to clear away its
14285 former value, if it was a variable. The following stronger version of
14286 |get_symbol| does that.
14287
14288 @c void mp_get_clear_symbol (MP mp) { 
14289   mp_get_symbol(mp); mp_clear_symbol(mp, mp->cur_sym,false);
14290 }
14291
14292 @ Here's another little subroutine; it checks that an equals sign
14293 or assignment sign comes along at the proper place in a macro definition.
14294
14295 @c void mp_check_equals (MP mp) { 
14296   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
14297      mp_missing_err(mp, "=");
14298 @.Missing `='@>
14299     help5("The next thing in this `def' should have been `=',")
14300       ("because I've already looked at the definition heading.")
14301       ("But don't worry; I'll pretend that an equals sign")
14302       ("was present. Everything from here to `enddef'")
14303       ("will be the replacement text of this macro.");
14304     mp_back_error(mp);
14305   }
14306 }
14307
14308 @ A \&{primarydef}, \&{secondarydef}, or \&{tertiarydef} is rather easily
14309 handled now that we have |scan_toks|.  In this case there are
14310 two parameters, which will be \.{EXPR0} and \.{EXPR1} (i.e.,
14311 |expr_base| and |expr_base+1|).
14312
14313 @c void mp_make_op_def (MP mp) {
14314   command_code m; /* the type of definition */
14315   pointer p,q,r; /* for list manipulation */
14316   m=mp->cur_mod;
14317   mp_get_symbol(mp); q=mp_get_node(mp, token_node_size);
14318   info(q)=mp->cur_sym; value(q)=expr_base;
14319   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym;
14320   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
14321   info(p)=mp->cur_sym; value(p)=expr_base+1; link(p)=q;
14322   get_t_next; mp_check_equals(mp);
14323   mp->scanner_status=op_defining; q=mp_get_avail(mp); ref_count(q)=null;
14324   r=mp_get_avail(mp); link(q)=r; info(r)=general_macro;
14325   link(r)=mp_scan_toks(mp, macro_def,p,null,0);
14326   mp->scanner_status=normal; eq_type(mp->warning_info)=m;
14327   equiv(mp->warning_info)=q; mp_get_x_next(mp);
14328 }
14329
14330 @ Parameters to macros are introduced by the keywords \&{expr},
14331 \&{suffix}, \&{text}, \&{primary}, \&{secondary}, and \&{tertiary}.
14332
14333 @<Put each...@>=
14334 mp_primitive(mp, "expr",param_type,expr_base);
14335 @:expr_}{\&{expr} primitive@>
14336 mp_primitive(mp, "suffix",param_type,suffix_base);
14337 @:suffix_}{\&{suffix} primitive@>
14338 mp_primitive(mp, "text",param_type,text_base);
14339 @:text_}{\&{text} primitive@>
14340 mp_primitive(mp, "primary",param_type,primary_macro);
14341 @:primary_}{\&{primary} primitive@>
14342 mp_primitive(mp, "secondary",param_type,secondary_macro);
14343 @:secondary_}{\&{secondary} primitive@>
14344 mp_primitive(mp, "tertiary",param_type,tertiary_macro);
14345 @:tertiary_}{\&{tertiary} primitive@>
14346
14347 @ @<Cases of |print_cmd...@>=
14348 case param_type:
14349   if ( m>=expr_base ) {
14350     if ( m==expr_base ) mp_print(mp, "expr");
14351     else if ( m==suffix_base ) mp_print(mp, "suffix");
14352     else mp_print(mp, "text");
14353   } else if ( m<secondary_macro ) {
14354     mp_print(mp, "primary");
14355   } else if ( m==secondary_macro ) {
14356     mp_print(mp, "secondary");
14357   } else {
14358     mp_print(mp, "tertiary");
14359   }
14360   break;
14361
14362 @ Let's turn next to the more complex processing associated with \&{def}
14363 and \&{vardef}. When the following procedure is called, |cur_mod|
14364 should be either |start_def| or |var_def|.
14365
14366 @c @<Declare the procedure called |check_delimiter|@>;
14367 @<Declare the function called |scan_declared_variable|@>;
14368 void mp_scan_def (MP mp) {
14369   int m; /* the type of definition */
14370   int n; /* the number of special suffix parameters */
14371   int k; /* the total number of parameters */
14372   int c; /* the kind of macro we're defining */
14373   pointer r; /* parameter-substitution list */
14374   pointer q; /* tail of the macro token list */
14375   pointer p; /* temporary storage */
14376   halfword base; /* |expr_base|, |suffix_base|, or |text_base| */
14377   pointer l_delim,r_delim; /* matching delimiters */
14378   m=mp->cur_mod; c=general_macro; link(hold_head)=null;
14379   q=mp_get_avail(mp); ref_count(q)=null; r=null;
14380   @<Scan the token or variable to be defined;
14381     set |n|, |scanner_status|, and |warning_info|@>;
14382   k=n;
14383   if ( mp->cur_cmd==left_delimiter ) {
14384     @<Absorb delimited parameters, putting them into lists |q| and |r|@>;
14385   }
14386   if ( mp->cur_cmd==param_type ) {
14387     @<Absorb undelimited parameters, putting them into list |r|@>;
14388   }
14389   mp_check_equals(mp);
14390   p=mp_get_avail(mp); info(p)=c; link(q)=p;
14391   @<Attach the replacement text to the tail of node |p|@>;
14392   mp->scanner_status=normal; mp_get_x_next(mp);
14393 }
14394
14395 @ We don't put `|frozen_end_group|' into the replacement text of
14396 a \&{vardef}, because the user may want to redefine `\.{endgroup}'.
14397
14398 @<Attach the replacement text to the tail of node |p|@>=
14399 if ( m==start_def ) {
14400   link(p)=mp_scan_toks(mp, macro_def,r,null,n);
14401 } else { 
14402   q=mp_get_avail(mp); info(q)=mp->bg_loc; link(p)=q;
14403   p=mp_get_avail(mp); info(p)=mp->eg_loc;
14404   link(q)=mp_scan_toks(mp, macro_def,r,p,n);
14405 }
14406 if ( mp->warning_info==bad_vardef ) 
14407   mp_flush_token_list(mp, value(bad_vardef))
14408
14409 @ @<Glob...@>=
14410 int bg_loc;
14411 int eg_loc; /* hash addresses of `\.{begingroup}' and `\.{endgroup}' */
14412
14413 @ @<Scan the token or variable to be defined;...@>=
14414 if ( m==start_def ) {
14415   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym; get_t_next;
14416   mp->scanner_status=op_defining; n=0;
14417   eq_type(mp->warning_info)=defined_macro; equiv(mp->warning_info)=q;
14418 } else { 
14419   p=mp_scan_declared_variable(mp);
14420   mp_flush_variable(mp, equiv(info(p)),link(p),true);
14421   mp->warning_info=mp_find_variable(mp, p); mp_flush_list(mp, p);
14422   if ( mp->warning_info==null ) @<Change to `\.{a bad variable}'@>;
14423   mp->scanner_status=var_defining; n=2;
14424   if ( mp->cur_cmd==macro_special ) if ( mp->cur_mod==macro_suffix ) {/* \.{\AT!\#} */
14425     n=3; get_t_next;
14426   }
14427   type(mp->warning_info)=mp_unsuffixed_macro-2+n; value(mp->warning_info)=q;
14428 } /* |mp_suffixed_macro=mp_unsuffixed_macro+1| */
14429
14430 @ @<Change to `\.{a bad variable}'@>=
14431
14432   print_err("This variable already starts with a macro");
14433 @.This variable already...@>
14434   help2("After `vardef a' you can\'t say `vardef a.b'.")
14435     ("So I'll have to discard this definition.");
14436   mp_error(mp); mp->warning_info=bad_vardef;
14437 }
14438
14439 @ @<Initialize table entries...@>=
14440 name_type(bad_vardef)=mp_root; link(bad_vardef)=frozen_bad_vardef;
14441 equiv(frozen_bad_vardef)=bad_vardef; eq_type(frozen_bad_vardef)=tag_token;
14442
14443 @ @<Absorb delimited parameters, putting them into lists |q| and |r|@>=
14444 do {  
14445   l_delim=mp->cur_sym; r_delim=mp->cur_mod; get_t_next;
14446   if ( (mp->cur_cmd==param_type)&&(mp->cur_mod>=expr_base) ) {
14447    base=mp->cur_mod;
14448   } else { 
14449     print_err("Missing parameter type; `expr' will be assumed");
14450 @.Missing parameter type@>
14451     help1("You should've had `expr' or `suffix' or `text' here.");
14452     mp_back_error(mp); base=expr_base;
14453   }
14454   @<Absorb parameter tokens for type |base|@>;
14455   mp_check_delimiter(mp, l_delim,r_delim);
14456   get_t_next;
14457 } while (mp->cur_cmd==left_delimiter)
14458
14459 @ @<Absorb parameter tokens for type |base|@>=
14460 do { 
14461   link(q)=mp_get_avail(mp); q=link(q); info(q)=base+k;
14462   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size); 
14463   value(p)=base+k; info(p)=mp->cur_sym;
14464   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14465 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
14466   incr(k); link(p)=r; r=p; get_t_next;
14467 } while (mp->cur_cmd==comma)
14468
14469 @ @<Absorb undelimited parameters, putting them into list |r|@>=
14470
14471   p=mp_get_node(mp, token_node_size);
14472   if ( mp->cur_mod<expr_base ) {
14473     c=mp->cur_mod; value(p)=expr_base+k;
14474   } else { 
14475     value(p)=mp->cur_mod+k;
14476     if ( mp->cur_mod==expr_base ) c=expr_macro;
14477     else if ( mp->cur_mod==suffix_base ) c=suffix_macro;
14478     else c=text_macro;
14479   }
14480   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14481   incr(k); mp_get_symbol(mp); info(p)=mp->cur_sym; link(p)=r; r=p; get_t_next;
14482   if ( c==expr_macro ) if ( mp->cur_cmd==of_token ) {
14483     c=of_macro; p=mp_get_node(mp, token_node_size);
14484     if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14485     value(p)=expr_base+k; mp_get_symbol(mp); info(p)=mp->cur_sym;
14486     link(p)=r; r=p; get_t_next;
14487   }
14488 }
14489
14490 @* \[32] Expanding the next token.
14491 Only a few command codes |<min_command| can possibly be returned by
14492 |get_t_next|; in increasing order, they are
14493 |if_test|, |fi_or_else|, |input|, |iteration|, |repeat_loop|,
14494 |exit_test|, |relax|, |scan_tokens|, |expand_after|, and |defined_macro|.
14495
14496 \MP\ usually gets the next token of input by saying |get_x_next|. This is
14497 like |get_t_next| except that it keeps getting more tokens until
14498 finding |cur_cmd>=min_command|. In other words, |get_x_next| expands
14499 macros and removes conditionals or iterations or input instructions that
14500 might be present.
14501
14502 It follows that |get_x_next| might invoke itself recursively. In fact,
14503 there is massive recursion, since macro expansion can involve the
14504 scanning of arbitrarily complex expressions, which in turn involve
14505 macro expansion and conditionals, etc.
14506 @^recursion@>
14507
14508 Therefore it's necessary to declare a whole bunch of |forward|
14509 procedures at this point, and to insert some other procedures
14510 that will be invoked by |get_x_next|.
14511
14512 @<Declarations@>= 
14513 void mp_scan_primary (MP mp);
14514 void mp_scan_secondary (MP mp);
14515 void mp_scan_tertiary (MP mp);
14516 void mp_scan_expression (MP mp);
14517 void mp_scan_suffix (MP mp);
14518 @<Declare the procedure called |macro_call|@>;
14519 void mp_get_boolean (MP mp);
14520 void mp_pass_text (MP mp);
14521 void mp_conditional (MP mp);
14522 void mp_start_input (MP mp);
14523 void mp_begin_iteration (MP mp);
14524 void mp_resume_iteration (MP mp);
14525 void mp_stop_iteration (MP mp);
14526
14527 @ An auxiliary subroutine called |expand| is used by |get_x_next|
14528 when it has to do exotic expansion commands.
14529
14530 @c void mp_expand (MP mp) {
14531   pointer p; /* for list manipulation */
14532   size_t k; /* something that we hope is |<=buf_size| */
14533   pool_pointer j; /* index into |str_pool| */
14534   if ( mp->internal[mp_tracing_commands]>unity ) 
14535     if ( mp->cur_cmd!=defined_macro )
14536       show_cur_cmd_mod;
14537   switch (mp->cur_cmd)  {
14538   case if_test:
14539     mp_conditional(mp); /* this procedure is discussed in Part 36 below */
14540     break;
14541   case fi_or_else:
14542     @<Terminate the current conditional and skip to \&{fi}@>;
14543     break;
14544   case input:
14545     @<Initiate or terminate input from a file@>;
14546     break;
14547   case iteration:
14548     if ( mp->cur_mod==end_for ) {
14549       @<Scold the user for having an extra \&{endfor}@>;
14550     } else {
14551       mp_begin_iteration(mp); /* this procedure is discussed in Part 37 below */
14552     }
14553     break;
14554   case repeat_loop: 
14555     @<Repeat a loop@>;
14556     break;
14557   case exit_test: 
14558     @<Exit a loop if the proper time has come@>;
14559     break;
14560   case relax: 
14561     break;
14562   case expand_after: 
14563     @<Expand the token after the next token@>;
14564     break;
14565   case scan_tokens: 
14566     @<Put a string into the input buffer@>;
14567     break;
14568   case defined_macro:
14569    mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14570    break;
14571   }; /* there are no other cases */
14572 };
14573
14574 @ @<Scold the user...@>=
14575
14576   print_err("Extra `endfor'");
14577 @.Extra `endfor'@>
14578   help2("I'm not currently working on a for loop,")
14579     ("so I had better not try to end anything.");
14580   mp_error(mp);
14581 }
14582
14583 @ The processing of \&{input} involves the |start_input| subroutine,
14584 which will be declared later; the processing of \&{endinput} is trivial.
14585
14586 @<Put each...@>=
14587 mp_primitive(mp, "input",input,0);
14588 @:input_}{\&{input} primitive@>
14589 mp_primitive(mp, "endinput",input,1);
14590 @:end_input_}{\&{endinput} primitive@>
14591
14592 @ @<Cases of |print_cmd_mod|...@>=
14593 case input: 
14594   if ( m==0 ) mp_print(mp, "input");
14595   else mp_print(mp, "endinput");
14596   break;
14597
14598 @ @<Initiate or terminate input...@>=
14599 if ( mp->cur_mod>0 ) mp->force_eof=true;
14600 else mp_start_input(mp)
14601
14602 @ We'll discuss the complicated parts of loop operations later. For now
14603 it suffices to know that there's a global variable called |loop_ptr|
14604 that will be |null| if no loop is in progress.
14605
14606 @<Repeat a loop@>=
14607 { while ( token_state &&(loc==null) ) 
14608     mp_end_token_list(mp); /* conserve stack space */
14609   if ( mp->loop_ptr==null ) {
14610     print_err("Lost loop");
14611 @.Lost loop@>
14612     help2("I'm confused; after exiting from a loop, I still seem")
14613       ("to want to repeat it. I'll try to forget the problem.");
14614     mp_error(mp);
14615   } else {
14616     mp_resume_iteration(mp); /* this procedure is in Part 37 below */
14617   }
14618 }
14619
14620 @ @<Exit a loop if the proper time has come@>=
14621 { mp_get_boolean(mp);
14622   if ( mp->internal[mp_tracing_commands]>unity ) 
14623     mp_show_cmd_mod(mp, nullary,mp->cur_exp);
14624   if ( mp->cur_exp==true_code ) {
14625     if ( mp->loop_ptr==null ) {
14626       print_err("No loop is in progress");
14627 @.No loop is in progress@>
14628       help1("Why say `exitif' when there's nothing to exit from?");
14629       if ( mp->cur_cmd==semicolon ) mp_error(mp); else mp_back_error(mp);
14630     } else {
14631      @<Exit prematurely from an iteration@>;
14632     }
14633   } else if ( mp->cur_cmd!=semicolon ) {
14634     mp_missing_err(mp, ";");
14635 @.Missing `;'@>
14636     help2("After `exitif <boolean exp>' I expect to see a semicolon.")
14637     ("I shall pretend that one was there."); mp_back_error(mp);
14638   }
14639 }
14640
14641 @ Here we use the fact that |forever_text| is the only |token_type| that
14642 is less than |loop_text|.
14643
14644 @<Exit prematurely...@>=
14645 { p=null;
14646   do {  
14647     if ( file_state ) {
14648       mp_end_file_reading(mp);
14649     } else { 
14650       if ( token_type<=loop_text ) p=start;
14651       mp_end_token_list(mp);
14652     }
14653   } while (p==null);
14654   if ( p!=info(mp->loop_ptr) ) mp_fatal_error(mp, "*** (loop confusion)");
14655 @.loop confusion@>
14656   mp_stop_iteration(mp); /* this procedure is in Part 34 below */
14657 }
14658
14659 @ @<Expand the token after the next token@>=
14660 { get_t_next;
14661   p=mp_cur_tok(mp); get_t_next;
14662   if ( mp->cur_cmd<min_command ) mp_expand(mp); 
14663   else mp_back_input(mp);
14664   back_list(p);
14665 }
14666
14667 @ @<Put a string into the input buffer@>=
14668 { mp_get_x_next(mp); mp_scan_primary(mp);
14669   if ( mp->cur_type!=mp_string_type ) {
14670     mp_disp_err(mp, null,"Not a string");
14671 @.Not a string@>
14672     help2("I'm going to flush this expression, since")
14673        ("scantokens should be followed by a known string.");
14674     mp_put_get_flush_error(mp, 0);
14675   } else { 
14676     mp_back_input(mp);
14677     if ( length(mp->cur_exp)>0 )
14678        @<Pretend we're reading a new one-line file@>;
14679   }
14680 }
14681
14682 @ @<Pretend we're reading a new one-line file@>=
14683 { mp_begin_file_reading(mp); name=is_scantok;
14684   k=mp->first+length(mp->cur_exp);
14685   if ( k>=mp->max_buf_stack ) {
14686     while ( k>=mp->buf_size ) {
14687       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
14688     }
14689     mp->max_buf_stack=k+1;
14690   }
14691   j=mp->str_start[mp->cur_exp]; limit=k;
14692   while ( mp->first<(size_t)limit ) {
14693     mp->buffer[mp->first]=mp->str_pool[j]; incr(j); incr(mp->first);
14694   }
14695   mp->buffer[limit]='%'; mp->first=limit+1; loc=start; 
14696   mp_flush_cur_exp(mp, 0);
14697 }
14698
14699 @ Here finally is |get_x_next|.
14700
14701 The expression scanning routines to be considered later
14702 communicate via the global quantities |cur_type| and |cur_exp|;
14703 we must be very careful to save and restore these quantities while
14704 macros are being expanded.
14705 @^inner loop@>
14706
14707 @<Declarations@>=
14708 void mp_get_x_next (MP mp);
14709
14710 @ @c void mp_get_x_next (MP mp) {
14711   pointer save_exp; /* a capsule to save |cur_type| and |cur_exp| */
14712   get_t_next;
14713   if ( mp->cur_cmd<min_command ) {
14714     save_exp=mp_stash_cur_exp(mp);
14715     do {  
14716       if ( mp->cur_cmd==defined_macro ) 
14717         mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14718       else 
14719         mp_expand(mp);
14720       get_t_next;
14721      } while (mp->cur_cmd<min_command);
14722      mp_unstash_cur_exp(mp, save_exp); /* that restores |cur_type| and |cur_exp| */
14723   }
14724 }
14725
14726 @ Now let's consider the |macro_call| procedure, which is used to start up
14727 all user-defined macros. Since the arguments to a macro might be expressions,
14728 |macro_call| is recursive.
14729 @^recursion@>
14730
14731 The first parameter to |macro_call| points to the reference count of the
14732 token list that defines the macro. The second parameter contains any
14733 arguments that have already been parsed (see below).  The third parameter
14734 points to the symbolic token that names the macro. If the third parameter
14735 is |null|, the macro was defined by \&{vardef}, so its name can be
14736 reconstructed from the prefix and ``at'' arguments found within the
14737 second parameter.
14738
14739 What is this second parameter? It's simply a linked list of one-word items,
14740 whose |info| fields point to the arguments. In other words, if |arg_list=null|,
14741 no arguments have been scanned yet; otherwise |info(arg_list)| points to
14742 the first scanned argument, and |link(arg_list)| points to the list of
14743 further arguments (if any).
14744
14745 Arguments of type \&{expr} are so-called capsules, which we will
14746 discuss later when we concentrate on expressions; they can be
14747 recognized easily because their |link| field is |void|. Arguments of type
14748 \&{suffix} and \&{text} are token lists without reference counts.
14749
14750 @ After argument scanning is complete, the arguments are moved to the
14751 |param_stack|. (They can't be put on that stack any sooner, because
14752 the stack is growing and shrinking in unpredictable ways as more arguments
14753 are being acquired.)  Then the macro body is fed to the scanner; i.e.,
14754 the replacement text of the macro is placed at the top of the \MP's
14755 input stack, so that |get_t_next| will proceed to read it next.
14756
14757 @<Declare the procedure called |macro_call|@>=
14758 @<Declare the procedure called |print_macro_name|@>;
14759 @<Declare the procedure called |print_arg|@>;
14760 @<Declare the procedure called |scan_text_arg|@>;
14761 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14762                     pointer macro_name) ;
14763
14764 @ @c
14765 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14766                     pointer macro_name) {
14767   /* invokes a user-defined control sequence */
14768   pointer r; /* current node in the macro's token list */
14769   pointer p,q; /* for list manipulation */
14770   integer n; /* the number of arguments */
14771   pointer tail = 0; /* tail of the argument list */
14772   pointer l_delim=0,r_delim=0; /* a delimiter pair */
14773   r=link(def_ref); add_mac_ref(def_ref);
14774   if ( arg_list==null ) {
14775     n=0;
14776   } else {
14777    @<Determine the number |n| of arguments already supplied,
14778     and set |tail| to the tail of |arg_list|@>;
14779   }
14780   if ( mp->internal[mp_tracing_macros]>0 ) {
14781     @<Show the text of the macro being expanded, and the existing arguments@>;
14782   }
14783   @<Scan the remaining arguments, if any; set |r| to the first token
14784     of the replacement text@>;
14785   @<Feed the arguments and replacement text to the scanner@>;
14786 }
14787
14788 @ @<Show the text of the macro...@>=
14789 mp_begin_diagnostic(mp); mp_print_ln(mp); 
14790 mp_print_macro_name(mp, arg_list,macro_name);
14791 if ( n==3 ) mp_print(mp, "@@#"); /* indicate a suffixed macro */
14792 mp_show_macro(mp, def_ref,null,100000);
14793 if ( arg_list!=null ) {
14794   n=0; p=arg_list;
14795   do {  
14796     q=info(p);
14797     mp_print_arg(mp, q,n,0);
14798     incr(n); p=link(p);
14799   } while (p!=null);
14800 }
14801 mp_end_diagnostic(mp, false)
14802
14803
14804 @ @<Declare the procedure called |print_macro_name|@>=
14805 void mp_print_macro_name (MP mp,pointer a, pointer n);
14806
14807 @ @c
14808 void mp_print_macro_name (MP mp,pointer a, pointer n) {
14809   pointer p,q; /* they traverse the first part of |a| */
14810   if ( n!=null ) {
14811     mp_print_text(n);
14812   } else  { 
14813     p=info(a);
14814     if ( p==null ) {
14815       mp_print_text(info(info(link(a))));
14816     } else { 
14817       q=p;
14818       while ( link(q)!=null ) q=link(q);
14819       link(q)=info(link(a));
14820       mp_show_token_list(mp, p,null,1000,0);
14821       link(q)=null;
14822     }
14823   }
14824 }
14825
14826 @ @<Declare the procedure called |print_arg|@>=
14827 void mp_print_arg (MP mp,pointer q, integer n, pointer b) ;
14828
14829 @ @c
14830 void mp_print_arg (MP mp,pointer q, integer n, pointer b) {
14831   if ( link(q)==mp_void ) mp_print_nl(mp, "(EXPR");
14832   else if ( (b<text_base)&&(b!=text_macro) ) mp_print_nl(mp, "(SUFFIX");
14833   else mp_print_nl(mp, "(TEXT");
14834   mp_print_int(mp, n); mp_print(mp, ")<-");
14835   if ( link(q)==mp_void ) mp_print_exp(mp, q,1);
14836   else mp_show_token_list(mp, q,null,1000,0);
14837 }
14838
14839 @ @<Determine the number |n| of arguments already supplied...@>=
14840 {  
14841   n=1; tail=arg_list;
14842   while ( link(tail)!=null ) { 
14843     incr(n); tail=link(tail);
14844   }
14845 }
14846
14847 @ @<Scan the remaining arguments, if any; set |r|...@>=
14848 mp->cur_cmd=comma+1; /* anything |<>comma| will do */
14849 while ( info(r)>=expr_base ) { 
14850   @<Scan the delimited argument represented by |info(r)|@>;
14851   r=link(r);
14852 };
14853 if ( mp->cur_cmd==comma ) {
14854   print_err("Too many arguments to ");
14855 @.Too many arguments...@>
14856   mp_print_macro_name(mp, arg_list,macro_name); mp_print_char(mp, ';');
14857   mp_print_nl(mp, "  Missing `"); mp_print_text(r_delim);
14858 @.Missing `)'...@>
14859   mp_print(mp, "' has been inserted");
14860   help3("I'm going to assume that the comma I just read was a")
14861    ("right delimiter, and then I'll begin expanding the macro.")
14862    ("You might want to delete some tokens before continuing.");
14863   mp_error(mp);
14864 }
14865 if ( info(r)!=general_macro ) {
14866   @<Scan undelimited argument(s)@>;
14867 }
14868 r=link(r)
14869
14870 @ At this point, the reader will find it advisable to review the explanation
14871 of token list format that was presented earlier, paying special attention to
14872 the conventions that apply only at the beginning of a macro's token list.
14873
14874 On the other hand, the reader will have to take the expression-parsing
14875 aspects of the following program on faith; we will explain |cur_type|
14876 and |cur_exp| later. (Several things in this program depend on each other,
14877 and it's necessary to jump into the circle somewhere.)
14878
14879 @<Scan the delimited argument represented by |info(r)|@>=
14880 if ( mp->cur_cmd!=comma ) {
14881   mp_get_x_next(mp);
14882   if ( mp->cur_cmd!=left_delimiter ) {
14883     print_err("Missing argument to ");
14884 @.Missing argument...@>
14885     mp_print_macro_name(mp, arg_list,macro_name);
14886     help3("That macro has more parameters than you thought.")
14887      ("I'll continue by pretending that each missing argument")
14888      ("is either zero or null.");
14889     if ( info(r)>=suffix_base ) {
14890       mp->cur_exp=null; mp->cur_type=mp_token_list;
14891     } else { 
14892       mp->cur_exp=0; mp->cur_type=mp_known;
14893     }
14894     mp_back_error(mp); mp->cur_cmd=right_delimiter; 
14895     goto FOUND;
14896   }
14897   l_delim=mp->cur_sym; r_delim=mp->cur_mod;
14898 }
14899 @<Scan the argument represented by |info(r)|@>;
14900 if ( mp->cur_cmd!=comma ) 
14901   @<Check that the proper right delimiter was present@>;
14902 FOUND:  
14903 @<Append the current expression to |arg_list|@>
14904
14905 @ @<Check that the proper right delim...@>=
14906 if ( (mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
14907   if ( info(link(r))>=expr_base ) {
14908     mp_missing_err(mp, ",");
14909 @.Missing `,'@>
14910     help3("I've finished reading a macro argument and am about to")
14911       ("read another; the arguments weren't delimited correctly.")
14912        ("You might want to delete some tokens before continuing.");
14913     mp_back_error(mp); mp->cur_cmd=comma;
14914   } else { 
14915     mp_missing_err(mp, str(text(r_delim)));
14916 @.Missing `)'@>
14917     help2("I've gotten to the end of the macro parameter list.")
14918        ("You might want to delete some tokens before continuing.");
14919     mp_back_error(mp);
14920   }
14921 }
14922
14923 @ A \&{suffix} or \&{text} parameter will be have been scanned as
14924 a token list pointed to by |cur_exp|, in which case we will have
14925 |cur_type=token_list|.
14926
14927 @<Append the current expression to |arg_list|@>=
14928
14929   p=mp_get_avail(mp);
14930   if ( mp->cur_type==mp_token_list ) info(p)=mp->cur_exp;
14931   else info(p)=mp_stash_cur_exp(mp);
14932   if ( mp->internal[mp_tracing_macros]>0 ) {
14933     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,info(r)); 
14934     mp_end_diagnostic(mp, false);
14935   }
14936   if ( arg_list==null ) arg_list=p;
14937   else link(tail)=p;
14938   tail=p; incr(n);
14939 }
14940
14941 @ @<Scan the argument represented by |info(r)|@>=
14942 if ( info(r)>=text_base ) {
14943   mp_scan_text_arg(mp, l_delim,r_delim);
14944 } else { 
14945   mp_get_x_next(mp);
14946   if ( info(r)>=suffix_base ) mp_scan_suffix(mp);
14947   else mp_scan_expression(mp);
14948 }
14949
14950 @ The parameters to |scan_text_arg| are either a pair of delimiters
14951 or zero; the latter case is for undelimited text arguments, which
14952 end with the first semicolon or \&{endgroup} or \&{end} that is not
14953 contained in a group.
14954
14955 @<Declare the procedure called |scan_text_arg|@>=
14956 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) ;
14957
14958 @ @c
14959 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) {
14960   integer balance; /* excess of |l_delim| over |r_delim| */
14961   pointer p; /* list tail */
14962   mp->warning_info=l_delim; mp->scanner_status=absorbing;
14963   p=hold_head; balance=1; link(hold_head)=null;
14964   while (1)  { 
14965     get_t_next;
14966     if ( l_delim==0 ) {
14967       @<Adjust the balance for an undelimited argument; |break| if done@>;
14968     } else {
14969           @<Adjust the balance for a delimited argument; |break| if done@>;
14970     }
14971     link(p)=mp_cur_tok(mp); p=link(p);
14972   }
14973   mp->cur_exp=link(hold_head); mp->cur_type=mp_token_list;
14974   mp->scanner_status=normal;
14975 };
14976
14977 @ @<Adjust the balance for a delimited argument...@>=
14978 if ( mp->cur_cmd==right_delimiter ) { 
14979   if ( mp->cur_mod==l_delim ) { 
14980     decr(balance);
14981     if ( balance==0 ) break;
14982   }
14983 } else if ( mp->cur_cmd==left_delimiter ) {
14984   if ( mp->cur_mod==r_delim ) incr(balance);
14985 }
14986
14987 @ @<Adjust the balance for an undelimited...@>=
14988 if ( end_of_statement ) { /* |cur_cmd=semicolon|, |end_group|, or |stop| */
14989   if ( balance==1 ) { break; }
14990   else  { if ( mp->cur_cmd==end_group ) decr(balance); }
14991 } else if ( mp->cur_cmd==begin_group ) { 
14992   incr(balance); 
14993 }
14994
14995 @ @<Scan undelimited argument(s)@>=
14996
14997   if ( info(r)<text_macro ) {
14998     mp_get_x_next(mp);
14999     if ( info(r)!=suffix_macro ) {
15000       if ( (mp->cur_cmd==equals)||(mp->cur_cmd==assignment) ) mp_get_x_next(mp);
15001     }
15002   }
15003   switch (info(r)) {
15004   case primary_macro:mp_scan_primary(mp); break;
15005   case secondary_macro:mp_scan_secondary(mp); break;
15006   case tertiary_macro:mp_scan_tertiary(mp); break;
15007   case expr_macro:mp_scan_expression(mp); break;
15008   case of_macro:
15009     @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>;
15010     break;
15011   case suffix_macro:
15012     @<Scan a suffix with optional delimiters@>;
15013     break;
15014   case text_macro:mp_scan_text_arg(mp, 0,0); break;
15015   } /* there are no other cases */
15016   mp_back_input(mp); 
15017   @<Append the current expression to |arg_list|@>;
15018 }
15019
15020 @ @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>=
15021
15022   mp_scan_expression(mp); p=mp_get_avail(mp); info(p)=mp_stash_cur_exp(mp);
15023   if ( mp->internal[mp_tracing_macros]>0 ) { 
15024     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,0); 
15025     mp_end_diagnostic(mp, false);
15026   }
15027   if ( arg_list==null ) arg_list=p; else link(tail)=p;
15028   tail=p;incr(n);
15029   if ( mp->cur_cmd!=of_token ) {
15030     mp_missing_err(mp, "of"); mp_print(mp, " for ");
15031 @.Missing `of'@>
15032     mp_print_macro_name(mp, arg_list,macro_name);
15033     help1("I've got the first argument; will look now for the other.");
15034     mp_back_error(mp);
15035   }
15036   mp_get_x_next(mp); mp_scan_primary(mp);
15037 }
15038
15039 @ @<Scan a suffix with optional delimiters@>=
15040
15041   if ( mp->cur_cmd!=left_delimiter ) {
15042     l_delim=null;
15043   } else { 
15044     l_delim=mp->cur_sym; r_delim=mp->cur_mod; mp_get_x_next(mp);
15045   };
15046   mp_scan_suffix(mp);
15047   if ( l_delim!=null ) {
15048     if ((mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
15049       mp_missing_err(mp, str(text(r_delim)));
15050 @.Missing `)'@>
15051       help2("I've gotten to the end of the macro parameter list.")
15052          ("You might want to delete some tokens before continuing.");
15053       mp_back_error(mp);
15054     }
15055     mp_get_x_next(mp);
15056   }
15057 }
15058
15059 @ Before we put a new token list on the input stack, it is wise to clean off
15060 all token lists that have recently been depleted. Then a user macro that ends
15061 with a call to itself will not require unbounded stack space.
15062
15063 @<Feed the arguments and replacement text to the scanner@>=
15064 while ( token_state &&(loc==null) ) mp_end_token_list(mp); /* conserve stack space */
15065 if ( mp->param_ptr+n>mp->max_param_stack ) {
15066   mp->max_param_stack=mp->param_ptr+n;
15067   if ( mp->max_param_stack>mp->param_size )
15068     mp_overflow(mp, "parameter stack size",mp->param_size);
15069 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15070 }
15071 mp_begin_token_list(mp, def_ref,macro); name=macro_name; loc=r;
15072 if ( n>0 ) {
15073   p=arg_list;
15074   do {  
15075    mp->param_stack[mp->param_ptr]=info(p); incr(mp->param_ptr); p=link(p);
15076   } while (p!=null);
15077   mp_flush_list(mp, arg_list);
15078 }
15079
15080 @ It's sometimes necessary to put a single argument onto |param_stack|.
15081 The |stack_argument| subroutine does this.
15082
15083 @c void mp_stack_argument (MP mp,pointer p) { 
15084   if ( mp->param_ptr==mp->max_param_stack ) {
15085     incr(mp->max_param_stack);
15086     if ( mp->max_param_stack>mp->param_size )
15087       mp_overflow(mp, "parameter stack size",mp->param_size);
15088 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15089   }
15090   mp->param_stack[mp->param_ptr]=p; incr(mp->param_ptr);
15091 }
15092
15093 @* \[33] Conditional processing.
15094 Let's consider now the way \&{if} commands are handled.
15095
15096 Conditions can be inside conditions, and this nesting has a stack
15097 that is independent of other stacks.
15098 Four global variables represent the top of the condition stack:
15099 |cond_ptr| points to pushed-down entries, if~any; |cur_if| tells whether
15100 we are processing \&{if} or \&{elseif}; |if_limit| specifies
15101 the largest code of a |fi_or_else| command that is syntactically legal;
15102 and |if_line| is the line number at which the current conditional began.
15103
15104 If no conditions are currently in progress, the condition stack has the
15105 special state |cond_ptr=null|, |if_limit=normal|, |cur_if=0|, |if_line=0|.
15106 Otherwise |cond_ptr| points to a two-word node; the |type|, |name_type|, and
15107 |link| fields of the first word contain |if_limit|, |cur_if|, and
15108 |cond_ptr| at the next level, and the second word contains the
15109 corresponding |if_line|.
15110
15111 @d if_node_size 2 /* number of words in stack entry for conditionals */
15112 @d if_line_field(A) mp->mem[(A)+1].cint
15113 @d if_code 1 /* code for \&{if} being evaluated */
15114 @d fi_code 2 /* code for \&{fi} */
15115 @d else_code 3 /* code for \&{else} */
15116 @d else_if_code 4 /* code for \&{elseif} */
15117
15118 @<Glob...@>=
15119 pointer cond_ptr; /* top of the condition stack */
15120 integer if_limit; /* upper bound on |fi_or_else| codes */
15121 small_number cur_if; /* type of conditional being worked on */
15122 integer if_line; /* line where that conditional began */
15123
15124 @ @<Set init...@>=
15125 mp->cond_ptr=null; mp->if_limit=normal; mp->cur_if=0; mp->if_line=0;
15126
15127 @ @<Put each...@>=
15128 mp_primitive(mp, "if",if_test,if_code);
15129 @:if_}{\&{if} primitive@>
15130 mp_primitive(mp, "fi",fi_or_else,fi_code); mp->eqtb[frozen_fi]=mp->eqtb[mp->cur_sym];
15131 @:fi_}{\&{fi} primitive@>
15132 mp_primitive(mp, "else",fi_or_else,else_code);
15133 @:else_}{\&{else} primitive@>
15134 mp_primitive(mp, "elseif",fi_or_else,else_if_code);
15135 @:else_if_}{\&{elseif} primitive@>
15136
15137 @ @<Cases of |print_cmd_mod|...@>=
15138 case if_test:
15139 case fi_or_else: 
15140   switch (m) {
15141   case if_code:mp_print(mp, "if"); break;
15142   case fi_code:mp_print(mp, "fi");  break;
15143   case else_code:mp_print(mp, "else"); break;
15144   default: mp_print(mp, "elseif"); break;
15145   }
15146   break;
15147
15148 @ Here is a procedure that ignores text until coming to an \&{elseif},
15149 \&{else}, or \&{fi} at level zero of $\&{if}\ldots\&{fi}$
15150 nesting. After it has acted, |cur_mod| will indicate the token that
15151 was found.
15152
15153 \MP's smallest two command codes are |if_test| and |fi_or_else|; this
15154 makes the skipping process a bit simpler.
15155
15156 @c 
15157 void mp_pass_text (MP mp) {
15158   integer l = 0;
15159   mp->scanner_status=skipping;
15160   mp->warning_info=mp_true_line(mp);
15161   while (1)  { 
15162     get_t_next;
15163     if ( mp->cur_cmd<=fi_or_else ) {
15164       if ( mp->cur_cmd<fi_or_else ) {
15165         incr(l);
15166       } else { 
15167         if ( l==0 ) break;
15168         if ( mp->cur_mod==fi_code ) decr(l);
15169       }
15170     } else {
15171       @<Decrease the string reference count,
15172        if the current token is a string@>;
15173     }
15174   }
15175   mp->scanner_status=normal;
15176 }
15177
15178 @ @<Decrease the string reference count...@>=
15179 if ( mp->cur_cmd==string_token ) { delete_str_ref(mp->cur_mod); }
15180
15181 @ When we begin to process a new \&{if}, we set |if_limit:=if_code|; then
15182 if \&{elseif} or \&{else} or \&{fi} occurs before the current \&{if}
15183 condition has been evaluated, a colon will be inserted.
15184 A construction like `\.{if fi}' would otherwise get \MP\ confused.
15185
15186 @<Push the condition stack@>=
15187 { p=mp_get_node(mp, if_node_size); link(p)=mp->cond_ptr; type(p)=mp->if_limit;
15188   name_type(p)=mp->cur_if; if_line_field(p)=mp->if_line;
15189   mp->cond_ptr=p; mp->if_limit=if_code; mp->if_line=mp_true_line(mp); 
15190   mp->cur_if=if_code;
15191 }
15192
15193 @ @<Pop the condition stack@>=
15194 { p=mp->cond_ptr; mp->if_line=if_line_field(p);
15195   mp->cur_if=name_type(p); mp->if_limit=type(p); mp->cond_ptr=link(p);
15196   mp_free_node(mp, p,if_node_size);
15197 }
15198
15199 @ Here's a procedure that changes the |if_limit| code corresponding to
15200 a given value of |cond_ptr|.
15201
15202 @c void mp_change_if_limit (MP mp,small_number l, pointer p) {
15203   pointer q;
15204   if ( p==mp->cond_ptr ) {
15205     mp->if_limit=l; /* that's the easy case */
15206   } else  { 
15207     q=mp->cond_ptr;
15208     while (1) { 
15209       if ( q==null ) mp_confusion(mp, "if");
15210 @:this can't happen if}{\quad if@>
15211       if ( link(q)==p ) { 
15212         type(q)=l; return;
15213       }
15214       q=link(q);
15215     }
15216   }
15217 }
15218
15219 @ The user is supposed to put colons into the proper parts of conditional
15220 statements. Therefore, \MP\ has to check for their presence.
15221
15222 @c 
15223 void mp_check_colon (MP mp) { 
15224   if ( mp->cur_cmd!=colon ) { 
15225     mp_missing_err(mp, ":");
15226 @.Missing `:'@>
15227     help2("There should've been a colon after the condition.")
15228          ("I shall pretend that one was there.");;
15229     mp_back_error(mp);
15230   }
15231 }
15232
15233 @ A condition is started when the |get_x_next| procedure encounters
15234 an |if_test| command; in that case |get_x_next| calls |conditional|,
15235 which is a recursive procedure.
15236 @^recursion@>
15237
15238 @c void mp_conditional (MP mp) {
15239   pointer save_cond_ptr; /* |cond_ptr| corresponding to this conditional */
15240   int new_if_limit; /* future value of |if_limit| */
15241   pointer p; /* temporary register */
15242   @<Push the condition stack@>; 
15243   save_cond_ptr=mp->cond_ptr;
15244 RESWITCH: 
15245   mp_get_boolean(mp); new_if_limit=else_if_code;
15246   if ( mp->internal[mp_tracing_commands]>unity ) {
15247     @<Display the boolean value of |cur_exp|@>;
15248   }
15249 FOUND: 
15250   mp_check_colon(mp);
15251   if ( mp->cur_exp==true_code ) {
15252     mp_change_if_limit(mp, new_if_limit,save_cond_ptr);
15253     return; /* wait for \&{elseif}, \&{else}, or \&{fi} */
15254   };
15255   @<Skip to \&{elseif} or \&{else} or \&{fi}, then |goto done|@>;
15256 DONE: 
15257   mp->cur_if=mp->cur_mod; mp->if_line=mp_true_line(mp);
15258   if ( mp->cur_mod==fi_code ) {
15259     @<Pop the condition stack@>
15260   } else if ( mp->cur_mod==else_if_code ) {
15261     goto RESWITCH;
15262   } else  { 
15263     mp->cur_exp=true_code; new_if_limit=fi_code; mp_get_x_next(mp); 
15264     goto FOUND;
15265   }
15266 }
15267
15268 @ In a construction like `\&{if} \&{if} \&{true}: $0=1$: \\{foo}
15269 \&{else}: \\{bar} \&{fi}', the first \&{else}
15270 that we come to after learning that the \&{if} is false is not the
15271 \&{else} we're looking for. Hence the following curious logic is needed.
15272
15273 @<Skip to \&{elseif}...@>=
15274 while (1) { 
15275   mp_pass_text(mp);
15276   if ( mp->cond_ptr==save_cond_ptr ) goto DONE;
15277   else if ( mp->cur_mod==fi_code ) @<Pop the condition stack@>;
15278 }
15279
15280
15281 @ @<Display the boolean value...@>=
15282 { mp_begin_diagnostic(mp);
15283   if ( mp->cur_exp==true_code ) mp_print(mp, "{true}");
15284   else mp_print(mp, "{false}");
15285   mp_end_diagnostic(mp, false);
15286 }
15287
15288 @ The processing of conditionals is complete except for the following
15289 code, which is actually part of |get_x_next|. It comes into play when
15290 \&{elseif}, \&{else}, or \&{fi} is scanned.
15291
15292 @<Terminate the current conditional and skip to \&{fi}@>=
15293 if ( mp->cur_mod>mp->if_limit ) {
15294   if ( mp->if_limit==if_code ) { /* condition not yet evaluated */
15295     mp_missing_err(mp, ":");
15296 @.Missing `:'@>
15297     mp_back_input(mp); mp->cur_sym=frozen_colon; mp_ins_error(mp);
15298   } else  { 
15299     print_err("Extra "); mp_print_cmd_mod(mp, fi_or_else,mp->cur_mod);
15300 @.Extra else@>
15301 @.Extra elseif@>
15302 @.Extra fi@>
15303     help1("I'm ignoring this; it doesn't match any if.");
15304     mp_error(mp);
15305   }
15306 } else  { 
15307   while ( mp->cur_mod!=fi_code ) mp_pass_text(mp); /* skip to \&{fi} */
15308   @<Pop the condition stack@>;
15309 }
15310
15311 @* \[34] Iterations.
15312 To bring our treatment of |get_x_next| to a close, we need to consider what
15313 \MP\ does when it sees \&{for}, \&{forsuffixes}, and \&{forever}.
15314
15315 There's a global variable |loop_ptr| that keeps track of the \&{for} loops
15316 that are currently active. If |loop_ptr=null|, no loops are in progress;
15317 otherwise |info(loop_ptr)| points to the iterative text of the current
15318 (innermost) loop, and |link(loop_ptr)| points to the data for any other
15319 loops that enclose the current one.
15320
15321 A loop-control node also has two other fields, called |loop_type| and
15322 |loop_list|, whose contents depend on the type of loop:
15323
15324 \yskip\indent|loop_type(loop_ptr)=null| means that |loop_list(loop_ptr)|
15325 points to a list of one-word nodes whose |info| fields point to the
15326 remaining argument values of a suffix list and expression list.
15327
15328 \yskip\indent|loop_type(loop_ptr)=mp_void| means that the current loop is
15329 `\&{forever}'.
15330
15331 \yskip\indent|loop_type(loop_ptr)=progression_flag| means that
15332 |p=loop_list(loop_ptr)| points to a ``progression node'' and |value(p)|,
15333 |step_size(p)|, and |final_value(p)| contain the data for an arithmetic
15334 progression.
15335
15336 \yskip\indent|loop_type(loop_ptr)=p>mp_void| means that |p| points to an edge
15337 header and |loop_list(loop_ptr)| points into the graphical object list for
15338 that edge header.
15339
15340 \yskip\noindent In the case of a progression node, the first word is not used
15341 because the link field of words in the dynamic memory area cannot be arbitrary.
15342
15343 @d loop_list_loc(A) ((A)+1) /* where the |loop_list| field resides */
15344 @d loop_type(A) info(loop_list_loc((A))) /* the type of \&{for} loop */
15345 @d loop_list(A) link(loop_list_loc((A))) /* the remaining list elements */
15346 @d loop_node_size 2 /* the number of words in a loop control node */
15347 @d progression_node_size 4 /* the number of words in a progression node */
15348 @d step_size(A) mp->mem[(A)+2].sc /* the step size in an arithmetic progression */
15349 @d final_value(A) mp->mem[(A)+3].sc /* the final value in an arithmetic progression */
15350 @d progression_flag (null+2)
15351   /* |loop_type| value when |loop_list| points to a progression node */
15352
15353 @<Glob...@>=
15354 pointer loop_ptr; /* top of the loop-control-node stack */
15355
15356 @ @<Set init...@>=
15357 mp->loop_ptr=null;
15358
15359 @ If the expressions that define an arithmetic progression in
15360 a \&{for} loop don't have known numeric values, the |bad_for|
15361 subroutine screams at the user.
15362
15363 @c void mp_bad_for (MP mp, char * s) {
15364   mp_disp_err(mp, null,"Improper "); /* show the bad expression above the message */
15365 @.Improper...replaced by 0@>
15366   mp_print(mp, s); mp_print(mp, " has been replaced by 0");
15367   help4("When you say `for x=a step b until c',")
15368     ("the initial value `a' and the step size `b'")
15369     ("and the final value `c' must have known numeric values.")
15370     ("I'm zeroing this one. Proceed, with fingers crossed.");
15371   mp_put_get_flush_error(mp, 0);
15372 };
15373
15374 @ Here's what \MP\ does when \&{for}, \&{forsuffixes}, or \&{forever}
15375 has just been scanned. (This code requires slight familiarity with
15376 expression-parsing routines that we have not yet discussed; but it seems
15377 to belong in the present part of the program, even though the original author
15378 didn't write it until later. The reader may wish to come back to it.)
15379
15380 @c void mp_begin_iteration (MP mp) {
15381   halfword m; /* |expr_base| (\&{for}) or |suffix_base| (\&{forsuffixes}) */
15382   halfword n; /* hash address of the current symbol */
15383   pointer s; /* the new loop-control node */
15384   pointer p; /* substitution list for |scan_toks| */
15385   pointer q;  /* link manipulation register */
15386   pointer pp; /* a new progression node */
15387   m=mp->cur_mod; n=mp->cur_sym; s=mp_get_node(mp, loop_node_size);
15388   if ( m==start_forever ){ 
15389     loop_type(s)=mp_void; p=null; mp_get_x_next(mp);
15390   } else { 
15391     mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
15392     info(p)=mp->cur_sym; value(p)=m;
15393     mp_get_x_next(mp);
15394     if ( mp->cur_cmd==within_token ) {
15395       @<Set up a picture iteration@>;
15396     } else { 
15397       @<Check for the |"="| or |":="| in a loop header@>;
15398       @<Scan the values to be used in the loop@>;
15399     }
15400   }
15401   @<Check for the presence of a colon@>;
15402   @<Scan the loop text and put it on the loop control stack@>;
15403   mp_resume_iteration(mp);
15404 }
15405
15406 @ @<Check for the |"="| or |":="| in a loop header@>=
15407 if ( (mp->cur_cmd!=equals)&&(mp->cur_cmd!=assignment) ) { 
15408   mp_missing_err(mp, "=");
15409 @.Missing `='@>
15410   help3("The next thing in this loop should have been `=' or `:='.")
15411     ("But don't worry; I'll pretend that an equals sign")
15412     ("was present, and I'll look for the values next.");
15413   mp_back_error(mp);
15414 }
15415
15416 @ @<Check for the presence of a colon@>=
15417 if ( mp->cur_cmd!=colon ) { 
15418   mp_missing_err(mp, ":");
15419 @.Missing `:'@>
15420   help3("The next thing in this loop should have been a `:'.")
15421     ("So I'll pretend that a colon was present;")
15422     ("everything from here to `endfor' will be iterated.");
15423   mp_back_error(mp);
15424 }
15425
15426 @ We append a special |frozen_repeat_loop| token in place of the
15427 `\&{endfor}' at the end of the loop. This will come through \MP's scanner
15428 at the proper time to cause the loop to be repeated.
15429
15430 (If the user tries some shenanigan like `\&{for} $\ldots$ \&{let} \&{endfor}',
15431 he will be foiled by the |get_symbol| routine, which keeps frozen
15432 tokens unchanged. Furthermore the |frozen_repeat_loop| is an \&{outer}
15433 token, so it won't be lost accidentally.)
15434
15435 @ @<Scan the loop text...@>=
15436 q=mp_get_avail(mp); info(q)=frozen_repeat_loop;
15437 mp->scanner_status=loop_defining; mp->warning_info=n;
15438 info(s)=mp_scan_toks(mp, iteration,p,q,0); mp->scanner_status=normal;
15439 link(s)=mp->loop_ptr; mp->loop_ptr=s
15440
15441 @ @<Initialize table...@>=
15442 eq_type(frozen_repeat_loop)=repeat_loop+outer_tag;
15443 text(frozen_repeat_loop)=intern(" ENDFOR");
15444
15445 @ The loop text is inserted into \MP's scanning apparatus by the
15446 |resume_iteration| routine.
15447
15448 @c void mp_resume_iteration (MP mp) {
15449   pointer p,q; /* link registers */
15450   p=loop_type(mp->loop_ptr);
15451   if ( p==progression_flag ) { 
15452     p=loop_list(mp->loop_ptr); /* now |p| points to a progression node */
15453     mp->cur_exp=value(p);
15454     if ( @<The arithmetic progression has ended@> ) {
15455       mp_stop_iteration(mp);
15456       return;
15457     }
15458     mp->cur_type=mp_known; q=mp_stash_cur_exp(mp); /* make |q| an \&{expr} argument */
15459     value(p)=mp->cur_exp+step_size(p); /* set |value(p)| for the next iteration */
15460   } else if ( p==null ) { 
15461     p=loop_list(mp->loop_ptr);
15462     if ( p==null ) {
15463       mp_stop_iteration(mp);
15464       return;
15465     }
15466     loop_list(mp->loop_ptr)=link(p); q=info(p); free_avail(p);
15467   } else if ( p==mp_void ) { 
15468     mp_begin_token_list(mp, info(mp->loop_ptr),forever_text); return;
15469   } else {
15470     @<Make |q| a capsule containing the next picture component from
15471       |loop_list(loop_ptr)| or |goto not_found|@>;
15472   }
15473   mp_begin_token_list(mp, info(mp->loop_ptr),loop_text);
15474   mp_stack_argument(mp, q);
15475   if ( mp->internal[mp_tracing_commands]>unity ) {
15476      @<Trace the start of a loop@>;
15477   }
15478   return;
15479 NOT_FOUND:
15480   mp_stop_iteration(mp);
15481 }
15482
15483 @ @<The arithmetic progression has ended@>=
15484 ((step_size(p)>0)&&(mp->cur_exp>final_value(p)))||
15485  ((step_size(p)<0)&&(mp->cur_exp<final_value(p)))
15486
15487 @ @<Trace the start of a loop@>=
15488
15489   mp_begin_diagnostic(mp); mp_print_nl(mp, "{loop value=");
15490 @.loop value=n@>
15491   if ( (q!=null)&&(link(q)==mp_void) ) mp_print_exp(mp, q,1);
15492   else mp_show_token_list(mp, q,null,50,0);
15493   mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
15494 }
15495
15496 @ @<Make |q| a capsule containing the next picture component from...@>=
15497 { q=loop_list(mp->loop_ptr);
15498   if ( q==null ) goto NOT_FOUND;
15499   skip_component(q) goto NOT_FOUND;
15500   mp->cur_exp=mp_copy_objects(mp, loop_list(mp->loop_ptr),q);
15501   mp_init_bbox(mp, mp->cur_exp);
15502   mp->cur_type=mp_picture_type;
15503   loop_list(mp->loop_ptr)=q;
15504   q=mp_stash_cur_exp(mp);
15505 }
15506
15507 @ A level of loop control disappears when |resume_iteration| has decided
15508 not to resume, or when an \&{exitif} construction has removed the loop text
15509 from the input stack.
15510
15511 @c void mp_stop_iteration (MP mp) {
15512   pointer p,q; /* the usual */
15513   p=loop_type(mp->loop_ptr);
15514   if ( p==progression_flag )  {
15515     mp_free_node(mp, loop_list(mp->loop_ptr),progression_node_size);
15516   } else if ( p==null ){ 
15517     q=loop_list(mp->loop_ptr);
15518     while ( q!=null ) {
15519       p=info(q);
15520       if ( p!=null ) {
15521         if ( link(p)==mp_void ) { /* it's an \&{expr} parameter */
15522           mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
15523         } else {
15524           mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
15525         }
15526       }
15527       p=q; q=link(q); free_avail(p);
15528     }
15529   } else if ( p>progression_flag ) {
15530     delete_edge_ref(p);
15531   }
15532   p=mp->loop_ptr; mp->loop_ptr=link(p); mp_flush_token_list(mp, info(p));
15533   mp_free_node(mp, p,loop_node_size);
15534 }
15535
15536 @ Now that we know all about loop control, we can finish up
15537 the missing portion of |begin_iteration| and we'll be done.
15538
15539 The following code is performed after the `\.=' has been scanned in
15540 a \&{for} construction (if |m=expr_base|) or a \&{forsuffixes} construction
15541 (if |m=suffix_base|).
15542
15543 @<Scan the values to be used in the loop@>=
15544 loop_type(s)=null; q=loop_list_loc(s); link(q)=null; /* |link(q)=loop_list(s)| */
15545 do {  
15546   mp_get_x_next(mp);
15547   if ( m!=expr_base ) {
15548     mp_scan_suffix(mp);
15549   } else { 
15550     if ( mp->cur_cmd>=colon ) if ( mp->cur_cmd<=comma ) 
15551           goto CONTINUE;
15552     mp_scan_expression(mp);
15553     if ( mp->cur_cmd==step_token ) if ( q==loop_list_loc(s) ) {
15554       @<Prepare for step-until construction and |break|@>;
15555     }
15556     mp->cur_exp=mp_stash_cur_exp(mp);
15557   }
15558   link(q)=mp_get_avail(mp); q=link(q); 
15559   info(q)=mp->cur_exp; mp->cur_type=mp_vacuous;
15560 CONTINUE:
15561   ;
15562 } while (mp->cur_cmd==comma)
15563
15564 @ @<Prepare for step-until construction and |break|@>=
15565
15566   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "initial value");
15567   pp=mp_get_node(mp, progression_node_size); value(pp)=mp->cur_exp;
15568   mp_get_x_next(mp); mp_scan_expression(mp);
15569   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "step size");
15570   step_size(pp)=mp->cur_exp;
15571   if ( mp->cur_cmd!=until_token ) { 
15572     mp_missing_err(mp, "until");
15573 @.Missing `until'@>
15574     help2("I assume you meant to say `until' after `step'.")
15575       ("So I'll look for the final value and colon next.");
15576     mp_back_error(mp);
15577   }
15578   mp_get_x_next(mp); mp_scan_expression(mp);
15579   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "final value");
15580   final_value(pp)=mp->cur_exp; loop_list(s)=pp;
15581   loop_type(s)=progression_flag; 
15582   break;
15583 }
15584
15585 @ The last case is when we have just seen ``\&{within}'', and we need to
15586 parse a picture expression and prepare to iterate over it.
15587
15588 @<Set up a picture iteration@>=
15589 { mp_get_x_next(mp);
15590   mp_scan_expression(mp);
15591   @<Make sure the current expression is a known picture@>;
15592   loop_type(s)=mp->cur_exp; mp->cur_type=mp_vacuous;
15593   q=link(dummy_loc(mp->cur_exp));
15594   if ( q!= null ) 
15595     if ( is_start_or_stop(q) )
15596       if ( mp_skip_1component(mp, q)==null ) q=link(q);
15597   loop_list(s)=q;
15598 }
15599
15600 @ @<Make sure the current expression is a known picture@>=
15601 if ( mp->cur_type!=mp_picture_type ) {
15602   mp_disp_err(mp, null,"Improper iteration spec has been replaced by nullpicture");
15603   help1("When you say `for x in p', p must be a known picture.");
15604   mp_put_get_flush_error(mp, mp_get_node(mp, edge_header_size));
15605   mp_init_edges(mp, mp->cur_exp); mp->cur_type=mp_picture_type;
15606 }
15607
15608 @* \[35] File names.
15609 It's time now to fret about file names.  Besides the fact that different
15610 operating systems treat files in different ways, we must cope with the
15611 fact that completely different naming conventions are used by different
15612 groups of people. The following programs show what is required for one
15613 particular operating system; similar routines for other systems are not
15614 difficult to devise.
15615 @^system dependencies@>
15616
15617 \MP\ assumes that a file name has three parts: the name proper; its
15618 ``extension''; and a ``file area'' where it is found in an external file
15619 system.  The extension of an input file is assumed to be
15620 `\.{.mp}' unless otherwise specified; it is `\.{.log}' on the
15621 transcript file that records each run of \MP; it is `\.{.tfm}' on the font
15622 metric files that describe characters in any fonts created by \MP; it is
15623 `\.{.ps}' or `.{\it nnn}' for some number {\it nnn} on the \ps\ output files;
15624 and it is `\.{.mem}' on the mem files written by \.{INIMP} to initialize \MP.
15625 The file area can be arbitrary on input files, but files are usually
15626 output to the user's current area.  If an input file cannot be
15627 found on the specified area, \MP\ will look for it on a special system
15628 area; this special area is intended for commonly used input files.
15629
15630 Simple uses of \MP\ refer only to file names that have no explicit
15631 extension or area. For example, a person usually says `\.{input} \.{cmr10}'
15632 instead of `\.{input} \.{cmr10.new}'. Simple file
15633 names are best, because they make the \MP\ source files portable;
15634 whenever a file name consists entirely of letters and digits, it should be
15635 treated in the same way by all implementations of \MP. However, users
15636 need the ability to refer to other files in their environment, especially
15637 when responding to error messages concerning unopenable files; therefore
15638 we want to let them use the syntax that appears in their favorite
15639 operating system.
15640
15641 @ \MP\ uses the same conventions that have proved to be satisfactory for
15642 \TeX\ and \MF. In order to isolate the system-dependent aspects of file names,
15643 @^system dependencies@>
15644 the system-independent parts of \MP\ are expressed in terms
15645 of three system-dependent
15646 procedures called |begin_name|, |more_name|, and |end_name|. In
15647 essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
15648 the system-independent driver program does the operations
15649 $$|begin_name|;\,|more_name|(c_1);\,\ldots\,;|more_name|(c_n);
15650 \,|end_name|.$$
15651 These three procedures communicate with each other via global variables.
15652 Afterwards the file name will appear in the string pool as three strings
15653 called |cur_name|\penalty10000\hskip-.05em,
15654 |cur_area|, and |cur_ext|; the latter two are null (i.e.,
15655 |""|), unless they were explicitly specified by the user.
15656
15657 Actually the situation is slightly more complicated, because \MP\ needs
15658 to know when the file name ends. The |more_name| routine is a function
15659 (with side effects) that returns |true| on the calls |more_name|$(c_1)$,
15660 \dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
15661 returns |false|; or, it returns |true| and $c_n$ is the last character
15662 on the current input line. In other words,
15663 |more_name| is supposed to return |true| unless it is sure that the
15664 file name has been completely scanned; and |end_name| is supposed to be able
15665 to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
15666 whether $|more_name|(c_n)$ returned |true| or |false|.
15667
15668 @<Glob...@>=
15669 char * cur_name; /* name of file just scanned */
15670 char * cur_area; /* file area just scanned, or \.{""} */
15671 char * cur_ext; /* file extension just scanned, or \.{""} */
15672
15673 @ It is easier to maintain reference counts if we assign initial values.
15674
15675 @<Set init...@>=
15676 mp->cur_name=xstrdup(""); 
15677 mp->cur_area=xstrdup(""); 
15678 mp->cur_ext=xstrdup("");
15679
15680 @ @<Dealloc variables@>=
15681 xfree(mp->cur_area);
15682 xfree(mp->cur_name);
15683 xfree(mp->cur_ext);
15684
15685 @ The file names we shall deal with for illustrative purposes have the
15686 following structure:  If the name contains `\.>' or `\.:', the file area
15687 consists of all characters up to and including the final such character;
15688 otherwise the file area is null.  If the remaining file name contains
15689 `\..', the file extension consists of all such characters from the first
15690 remaining `\..' to the end, otherwise the file extension is null.
15691 @^system dependencies@>
15692
15693 We can scan such file names easily by using two global variables that keep track
15694 of the occurrences of area and extension delimiters.  Note that these variables
15695 cannot be of type |pool_pointer| because a string pool compaction could occur
15696 while scanning a file name.
15697
15698 @<Glob...@>=
15699 integer area_delimiter;
15700   /* most recent `\.>' or `\.:' relative to |str_start[str_ptr]| */
15701 integer ext_delimiter; /* the relevant `\..', if any */
15702
15703 @ Input files that can't be found in the user's area may appear in standard
15704 system areas called |MP_area| and |MF_area|.  (The latter is used when the file
15705 extension is |".mf"|.)  The standard system area for font metric files
15706 to be read is |MP_font_area|.
15707 This system area name will, of course, vary from place to place.
15708 @^system dependencies@>
15709
15710 @d MP_area "MPinputs:"
15711 @.MPinputs@>
15712 @d MF_area "MFinputs:"
15713 @.MFinputs@>
15714 @d MP_font_area ""
15715 @.TeXfonts@>
15716
15717 @ Here now is the first of the system-dependent routines for file name scanning.
15718 @^system dependencies@>
15719
15720 @<Declare subroutines for parsing file names@>=
15721 void mp_begin_name (MP mp) { 
15722   xfree(mp->cur_name); 
15723   xfree(mp->cur_area); 
15724   xfree(mp->cur_ext);
15725   mp->area_delimiter=-1; 
15726   mp->ext_delimiter=-1;
15727 }
15728
15729 @ And here's the second.
15730 @^system dependencies@>
15731
15732 @<Declare subroutines for parsing file names@>=
15733 boolean mp_more_name (MP mp, ASCII_code c) { 
15734   if (c==' ') {
15735     return false;
15736   } else { 
15737     if ( (c=='>')||(c==':') ) { 
15738       mp->area_delimiter=mp->pool_ptr; 
15739       mp->ext_delimiter=-1;
15740     } else if ( (c=='.')&&(mp->ext_delimiter<0) ) {
15741       mp->ext_delimiter=mp->pool_ptr;
15742     }
15743     str_room(1); append_char(c); /* contribute |c| to the current string */
15744     return true;
15745   }
15746 }
15747
15748 @ The third.
15749 @^system dependencies@>
15750
15751 @d copy_pool_segment(A,B,C) { 
15752       A = xmalloc(C+1,sizeof(char)); 
15753       strncpy(A,(char *)(mp->str_pool+B),C);  
15754       A[C] = 0;}
15755
15756 @<Declare subroutines for parsing file names@>=
15757 void mp_end_name (MP mp) {
15758   pool_pointer s; /* length of area, name, and extension */
15759   unsigned int len;
15760   /* "my/w.mp" */
15761   s = mp->str_start[mp->str_ptr];
15762   if ( mp->area_delimiter<0 ) {    
15763     mp->cur_area=xstrdup("");
15764   } else {
15765     len = mp->area_delimiter-s; 
15766     copy_pool_segment(mp->cur_area,s,len);
15767     s += len+1;
15768   }
15769   if ( mp->ext_delimiter<0 ) {
15770     mp->cur_ext=xstrdup("");
15771     len = mp->pool_ptr-s; 
15772   } else {
15773     copy_pool_segment(mp->cur_ext,mp->ext_delimiter,(mp->pool_ptr-mp->ext_delimiter));
15774     len = mp->ext_delimiter-s;
15775   }
15776   copy_pool_segment(mp->cur_name,s,len);
15777   mp->pool_ptr=s; /* don't need this partial string */
15778 }
15779
15780 @ Conversely, here is a routine that takes three strings and prints a file
15781 name that might have produced them. (The routine is system dependent, because
15782 some operating systems put the file area last instead of first.)
15783 @^system dependencies@>
15784
15785 @<Basic printing...@>=
15786 void mp_print_file_name (MP mp, char * n, char * a, char * e) { 
15787   mp_print(mp, a); mp_print(mp, n); mp_print(mp, e);
15788 };
15789
15790 @ Another system-dependent routine is needed to convert three internal
15791 \MP\ strings
15792 to the |name_of_file| value that is used to open files. The present code
15793 allows both lowercase and uppercase letters in the file name.
15794 @^system dependencies@>
15795
15796 @d append_to_name(A) { c=(A); 
15797   if ( k<file_name_size ) {
15798     mp->name_of_file[k]=xchr(c);
15799     incr(k);
15800   }
15801 }
15802
15803 @<Declare subroutines for parsing file names@>=
15804 void mp_pack_file_name (MP mp, char *n, char *a, char *e) {
15805   integer k; /* number of positions filled in |name_of_file| */
15806   ASCII_code c; /* character being packed */
15807   char *j; /* a character  index */
15808   k=0;
15809   assert(n);
15810   if (a!=NULL) {
15811     for (j=a;*j;j++) { append_to_name(*j); }
15812   }
15813   for (j=n;*j;j++) { append_to_name(*j); }
15814   if (e!=NULL) {
15815     for (j=e;*j;j++) { append_to_name(*j); }
15816   }
15817   mp->name_of_file[k]=0;
15818   mp->name_length=k; 
15819 }
15820
15821 @ @<Internal library declarations@>=
15822 void mp_pack_file_name (MP mp, char *n, char *a, char *e) ;
15823
15824 @ A messier routine is also needed, since mem file names must be scanned
15825 before \MP's string mechanism has been initialized. We shall use the
15826 global variable |MP_mem_default| to supply the text for default system areas
15827 and extensions related to mem files.
15828 @^system dependencies@>
15829
15830 @d mem_default_length 9 /* length of the |MP_mem_default| string */
15831 @d mem_ext_length 4 /* length of its `\.{.mem}' part */
15832 @d mem_extension ".mem" /* the extension, as a \.{WEB} constant */
15833
15834 @<Glob...@>=
15835 char *MP_mem_default;
15836
15837 @ @<Option variables@>=
15838 char *mem_name; /* for commandline */
15839
15840 @ @<Allocate or initialize ...@>=
15841 mp->MP_mem_default = xstrdup("plain.mem");
15842 mp->mem_name = xstrdup(opt->mem_name);
15843 @.plain@>
15844 @^system dependencies@>
15845
15846 @ @<Dealloc variables@>=
15847 xfree(mp->MP_mem_default);
15848 xfree(mp->mem_name);
15849
15850 @ @<Check the ``constant'' values for consistency@>=
15851 if ( mem_default_length>file_name_size ) mp->bad=20;
15852
15853 @ Here is the messy routine that was just mentioned. It sets |name_of_file|
15854 from the first |n| characters of |MP_mem_default|, followed by
15855 |buffer[a..b-1]|, followed by the last |mem_ext_length| characters of
15856 |MP_mem_default|.
15857
15858 We dare not give error messages here, since \MP\ calls this routine before
15859 the |error| routine is ready to roll. Instead, we simply drop excess characters,
15860 since the error will be detected in another way when a strange file name
15861 isn't found.
15862 @^system dependencies@>
15863
15864 @c void mp_pack_buffered_name (MP mp,small_number n, integer a,
15865                                integer b) {
15866   integer k; /* number of positions filled in |name_of_file| */
15867   ASCII_code c; /* character being packed */
15868   integer j; /* index into |buffer| or |MP_mem_default| */
15869   if ( n+b-a+1+mem_ext_length>file_name_size )
15870     b=a+file_name_size-n-1-mem_ext_length;
15871   k=0;
15872   for (j=0;j<n;j++) {
15873     append_to_name(xord((int)mp->MP_mem_default[j]));
15874   }
15875   for (j=a;j<b;j++) {
15876     append_to_name(mp->buffer[j]);
15877   }
15878   for (j=mem_default_length-mem_ext_length;
15879       j<mem_default_length;j++) {
15880     append_to_name(xord((int)mp->MP_mem_default[j]));
15881   } 
15882   mp->name_of_file[k]=0;
15883   mp->name_length=k; 
15884 }
15885
15886 @ Here is the only place we use |pack_buffered_name|. This part of the program
15887 becomes active when a ``virgin'' \MP\ is trying to get going, just after
15888 the preliminary initialization, or when the user is substituting another
15889 mem file by typing `\.\&' after the initial `\.{**}' prompt.  The buffer
15890 contains the first line of input in |buffer[loc..(last-1)]|, where
15891 |loc<last| and |buffer[loc]<>" "|.
15892
15893 @<Declarations@>=
15894 boolean mp_open_mem_file (MP mp) ;
15895
15896 @ @c
15897 boolean mp_open_mem_file (MP mp) {
15898   int j; /* the first space after the file name */
15899   if (mp->mem_name!=NULL) {
15900     mp->mem_file = (mp->open_file)(mp->mem_name, "rb", mp_filetype_memfile);
15901     if ( mp->mem_file ) return true;
15902   }
15903   j=loc;
15904   if ( mp->buffer[loc]=='&' ) {
15905     incr(loc); j=loc; mp->buffer[mp->last]=' ';
15906     while ( mp->buffer[j]!=' ' ) incr(j);
15907     mp_pack_buffered_name(mp, 0,loc,j); /* try first without the system file area */
15908     if ( mp_w_open_in(mp, &mp->mem_file) ) goto FOUND;
15909     wake_up_terminal;
15910     wterm_ln("Sorry, I can\'t find that mem file; will try PLAIN.");
15911 @.Sorry, I can't find...@>
15912     update_terminal;
15913   }
15914   /* now pull out all the stops: try for the system \.{plain} file */
15915   mp_pack_buffered_name(mp, mem_default_length-mem_ext_length,0,0);
15916   if ( ! mp_w_open_in(mp, &mp->mem_file) ) {
15917     wake_up_terminal;
15918     wterm_ln("I can\'t find the PLAIN mem file!\n");
15919 @.I can't find PLAIN...@>
15920 @.plain@>
15921     return false;
15922   }
15923 FOUND:
15924   loc=j; return true;
15925 }
15926
15927 @ Operating systems often make it possible to determine the exact name (and
15928 possible version number) of a file that has been opened. The following routine,
15929 which simply makes a \MP\ string from the value of |name_of_file|, should
15930 ideally be changed to deduce the full name of file~|f|, which is the file
15931 most recently opened, if it is possible to do this.
15932 @^system dependencies@>
15933
15934 @<Declarations@>=
15935 #define mp_a_make_name_string(A,B)  mp_make_name_string(A)
15936 #define mp_b_make_name_string(A,B)  mp_make_name_string(A)
15937 #define mp_w_make_name_string(A,B)  mp_make_name_string(A)
15938
15939 @ @c 
15940 str_number mp_make_name_string (MP mp) {
15941   int k; /* index into |name_of_file| */
15942   str_room(mp->name_length);
15943   for (k=0;k<mp->name_length;k++) {
15944     append_char(xord((int)mp->name_of_file[k]));
15945   }
15946   return mp_make_string(mp);
15947 }
15948
15949 @ Now let's consider the ``driver''
15950 routines by which \MP\ deals with file names
15951 in a system-independent manner.  First comes a procedure that looks for a
15952 file name in the input by taking the information from the input buffer.
15953 (We can't use |get_next|, because the conversion to tokens would
15954 destroy necessary information.)
15955
15956 This procedure doesn't allow semicolons or percent signs to be part of
15957 file names, because of other conventions of \MP.
15958 {\sl The {\logos METAFONT\/}book} doesn't
15959 use semicolons or percents immediately after file names, but some users
15960 no doubt will find it natural to do so; therefore system-dependent
15961 changes to allow such characters in file names should probably
15962 be made with reluctance, and only when an entire file name that
15963 includes special characters is ``quoted'' somehow.
15964 @^system dependencies@>
15965
15966 @c void mp_scan_file_name (MP mp) { 
15967   mp_begin_name(mp);
15968   while ( mp->buffer[loc]==' ' ) incr(loc);
15969   while (1) { 
15970     if ( (mp->buffer[loc]==';')||(mp->buffer[loc]=='%') ) break;
15971     if ( ! mp_more_name(mp, mp->buffer[loc]) ) break;
15972     incr(loc);
15973   }
15974   mp_end_name(mp);
15975 }
15976
15977 @ Here is another version that takes its input from a string.
15978
15979 @<Declare subroutines for parsing file names@>=
15980 void mp_str_scan_file (MP mp,  str_number s) {
15981   pool_pointer p,q; /* current position and stopping point */
15982   mp_begin_name(mp);
15983   p=mp->str_start[s]; q=str_stop(s);
15984   while ( p<q ){ 
15985     if ( ! mp_more_name(mp, mp->str_pool[p]) ) break;
15986     incr(p);
15987   }
15988   mp_end_name(mp);
15989 }
15990
15991 @ And one that reads from a |char*|.
15992
15993 @<Declare subroutines for parsing file names@>=
15994 void mp_ptr_scan_file (MP mp,  char *s) {
15995   char *p, *q; /* current position and stopping point */
15996   mp_begin_name(mp);
15997   p=s; q=p+strlen(s);
15998   while ( p<q ){ 
15999     if ( ! mp_more_name(mp, *p)) break;
16000     p++;
16001   }
16002   mp_end_name(mp);
16003 }
16004
16005
16006 @ The global variable |job_name| contains the file name that was first
16007 \&{input} by the user. This name is extended by `\.{.log}' and `\.{ps}' and
16008 `\.{.mem}' and `\.{.tfm}' in order to make the names of \MP's output files.
16009
16010 @<Glob...@>=
16011 boolean log_opened; /* has the transcript file been opened? */
16012 char *log_name; /* full name of the log file */
16013
16014 @ @<Option variables@>=
16015 char *job_name; /* principal file name */
16016
16017 @ Initially |job_name=NULL|; it becomes nonzero as soon as the true name is known.
16018 We have |job_name=NULL| if and only if the `\.{log}' file has not been opened,
16019 except of course for a short time just after |job_name| has become nonzero.
16020
16021 @<Allocate or ...@>=
16022 mp->job_name=opt->job_name; 
16023 mp->log_opened=false;
16024
16025 @ @<Dealloc variables@>=
16026 xfree(mp->job_name);
16027
16028 @ Here is a routine that manufactures the output file names, assuming that
16029 |job_name<>0|. It ignores and changes the current settings of |cur_area|
16030 and |cur_ext|.
16031
16032 @d pack_cur_name mp_pack_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext)
16033
16034 @<Declarations@>=
16035 void mp_pack_job_name (MP mp, char *s) ;
16036
16037 @ @c void mp_pack_job_name (MP mp, char  *s) { /* |s = ".log"|, |".mem"|, |".ps"|, or .\\{nnn} */
16038   xfree(mp->cur_name); mp->cur_name=xstrdup(mp->job_name);
16039   xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
16040   xfree(mp->cur_ext);  mp->cur_ext=xstrdup(s);
16041   pack_cur_name;
16042 }
16043
16044 @ If some trouble arises when \MP\ tries to open a file, the following
16045 routine calls upon the user to supply another file name. Parameter~|s|
16046 is used in the error message to identify the type of file; parameter~|e|
16047 is the default extension if none is given. Upon exit from the routine,
16048 variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
16049 ready for another attempt at file opening.
16050
16051 @<Declarations@>=
16052 void mp_prompt_file_name (MP mp,char * s, char * e) ;
16053
16054 @ @c void mp_prompt_file_name (MP mp,char * s, char * e) {
16055   size_t k; /* index into |buffer| */
16056   char * saved_cur_name;
16057   if ( mp->interaction==mp_scroll_mode ) 
16058         wake_up_terminal;
16059   if (strcmp(s,"input file name")==0) {
16060         print_err("I can\'t find file `");
16061 @.I can't find file x@>
16062   } else {
16063         print_err("I can\'t write on file `");
16064   }
16065 @.I can't write on file x@>
16066   mp_print_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext); 
16067   mp_print(mp, "'.");
16068   if (strcmp(e,"")==0) 
16069         mp_show_context(mp);
16070   mp_print_nl(mp, "Please type another "); mp_print(mp, s);
16071 @.Please type...@>
16072   if ( mp->interaction<mp_scroll_mode )
16073     mp_fatal_error(mp, "*** (job aborted, file error in nonstop mode)");
16074 @.job aborted, file error...@>
16075   saved_cur_name = xstrdup(mp->cur_name);
16076   clear_terminal; prompt_input(": "); @<Scan file name in the buffer@>;
16077   if (strcmp(mp->cur_ext,"")==0) 
16078         mp->cur_ext=e;
16079   if (strlen(mp->cur_name)==0) {
16080     mp->cur_name=saved_cur_name;
16081   } else {
16082     xfree(saved_cur_name);
16083   }
16084   pack_cur_name;
16085 }
16086
16087 @ @<Scan file name in the buffer@>=
16088
16089   mp_begin_name(mp); k=mp->first;
16090   while ( (mp->buffer[k]==' ')&&(k<mp->last) ) incr(k);
16091   while (1) { 
16092     if ( k==mp->last ) break;
16093     if ( ! mp_more_name(mp, mp->buffer[k]) ) break;
16094     incr(k);
16095   }
16096   mp_end_name(mp);
16097 }
16098
16099 @ The |open_log_file| routine is used to open the transcript file and to help
16100 it catch up to what has previously been printed on the terminal.
16101
16102 @c void mp_open_log_file (MP mp) {
16103   int old_setting; /* previous |selector| setting */
16104   int k; /* index into |months| and |buffer| */
16105   int l; /* end of first input line */
16106   integer m; /* the current month */
16107   char *months="JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"; 
16108     /* abbreviations of month names */
16109   old_setting=mp->selector;
16110   if ( mp->job_name==NULL ) {
16111      mp->job_name=xstrdup("mpout");
16112   }
16113   mp_pack_job_name(mp,".log");
16114   while ( ! mp_a_open_out(mp, &mp->log_file, mp_filetype_log) ) {
16115     @<Try to get a different log file name@>;
16116   }
16117   mp->log_name=xstrdup(mp->name_of_file);
16118   mp->selector=log_only; mp->log_opened=true;
16119   @<Print the banner line, including the date and time@>;
16120   mp->input_stack[mp->input_ptr]=mp->cur_input; 
16121     /* make sure bottom level is in memory */
16122   mp_print_nl(mp, "**");
16123 @.**@>
16124   l=mp->input_stack[0].limit_field-1; /* last position of first line */
16125   for (k=0;k<=l;k++) mp_print_str(mp, mp->buffer[k]);
16126   mp_print_ln(mp); /* now the transcript file contains the first line of input */
16127   mp->selector=old_setting+2; /* |log_only| or |term_and_log| */
16128 }
16129
16130 @ @<Dealloc variables@>=
16131 xfree(mp->log_name);
16132
16133 @ Sometimes |open_log_file| is called at awkward moments when \MP\ is
16134 unable to print error messages or even to |show_context|.
16135 The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
16136 routine will not be invoked because |log_opened| will be false.
16137
16138 The normal idea of |mp_batch_mode| is that nothing at all should be written
16139 on the terminal. However, in the unusual case that
16140 no log file could be opened, we make an exception and allow
16141 an explanatory message to be seen.
16142
16143 Incidentally, the program always refers to the log file as a `\.{transcript
16144 file}', because some systems cannot use the extension `\.{.log}' for
16145 this file.
16146
16147 @<Try to get a different log file name@>=
16148 {  
16149   mp->selector=term_only;
16150   mp_prompt_file_name(mp, "transcript file name",".log");
16151 }
16152
16153 @ @<Print the banner...@>=
16154
16155   wlog(banner);
16156   mp_print(mp, mp->mem_ident); mp_print(mp, "  ");
16157   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_day])); 
16158   mp_print_char(mp, ' ');
16159   m=mp_round_unscaled(mp, mp->internal[mp_month]);
16160   for (k=3*m-3;k<3*m;k++) { wlog_chr(months[k]); }
16161   mp_print_char(mp, ' '); 
16162   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_year])); 
16163   mp_print_char(mp, ' ');
16164   m=mp_round_unscaled(mp, mp->internal[mp_time]);
16165   mp_print_dd(mp, m / 60); mp_print_char(mp, ':'); mp_print_dd(mp, m % 60);
16166 }
16167
16168 @ The |try_extension| function tries to open an input file determined by
16169 |cur_name|, |cur_area|, and the argument |ext|.  It returns |false| if it
16170 can't find the file in |cur_area| or the appropriate system area.
16171
16172 @c boolean mp_try_extension (MP mp,char *ext) { 
16173   mp_pack_file_name(mp, mp->cur_name,mp->cur_area, ext);
16174   in_name=xstrdup(mp->cur_name); 
16175   in_area=xstrdup(mp->cur_area);
16176   if ( mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16177     return true;
16178   } else { 
16179     if (strcmp(ext,".mf")==0 ) in_area=xstrdup(MF_area);
16180     else in_area=xstrdup(MP_area);
16181     mp_pack_file_name(mp, mp->cur_name,in_area,ext);
16182     return mp_a_open_in(mp, &cur_file, mp_filetype_program);
16183   }
16184   return false;
16185 }
16186
16187 @ Let's turn now to the procedure that is used to initiate file reading
16188 when an `\.{input}' command is being processed.
16189
16190 @c void mp_start_input (MP mp) { /* \MP\ will \.{input} something */
16191   char *fname = NULL;
16192   @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>;
16193   while (1) { 
16194     mp_begin_file_reading(mp); /* set up |cur_file| and new level of input */
16195     if ( strlen(mp->cur_ext)==0 ) {
16196       if ( mp_try_extension(mp, ".mp") ) break;
16197       else if ( mp_try_extension(mp, "") ) break;
16198       else if ( mp_try_extension(mp, ".mf") ) break;
16199       /* |else do_nothing; | */
16200     } else if ( mp_try_extension(mp, mp->cur_ext) ) {
16201       break;
16202     }
16203     mp_end_file_reading(mp); /* remove the level that didn't work */
16204     mp_prompt_file_name(mp, "input file name","");
16205   }
16206   name=mp_a_make_name_string(mp, cur_file);
16207   fname = xstrdup(mp->name_of_file);
16208   if ( mp->job_name==NULL ) {
16209     mp->job_name=xstrdup(mp->cur_name); 
16210     mp_open_log_file(mp);
16211   } /* |open_log_file| doesn't |show_context|, so |limit|
16212         and |loc| needn't be set to meaningful values yet */
16213   if ( ((int)mp->term_offset+(int)strlen(fname)) > (mp->max_print_line-2)) mp_print_ln(mp);
16214   else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
16215   mp_print_char(mp, '('); incr(mp->open_parens); mp_print(mp, fname); 
16216   xfree(fname);
16217   update_terminal;
16218   @<Flush |name| and replace it with |cur_name| if it won't be needed@>;
16219   @<Read the first line of the new file@>;
16220 }
16221
16222 @ This code should be omitted if |a_make_name_string| returns something other
16223 than just a copy of its argument and the full file name is needed for opening
16224 \.{MPX} files or implementing the switch-to-editor option.
16225 @^system dependencies@>
16226
16227 @<Flush |name| and replace it with |cur_name| if it won't be needed@>=
16228 mp_flush_string(mp, name); name=rts(mp->cur_name); xfree(mp->cur_name)
16229
16230 @ If the file is empty, it is considered to contain a single blank line,
16231 so there is no need to test the return value.
16232
16233 @<Read the first line...@>=
16234
16235   line=1;
16236   (void)mp_input_ln(mp, cur_file ); 
16237   mp_firm_up_the_line(mp);
16238   mp->buffer[limit]='%'; mp->first=limit+1; loc=start;
16239 }
16240
16241 @ @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>=
16242 while ( token_state &&(loc==null) ) mp_end_token_list(mp);
16243 if ( token_state ) { 
16244   print_err("File names can't appear within macros");
16245 @.File names can't...@>
16246   help3("Sorry...I've converted what follows to tokens,")
16247     ("possibly garbaging the name you gave.")
16248     ("Please delete the tokens and insert the name again.");
16249   mp_error(mp);
16250 }
16251 if ( file_state ) {
16252   mp_scan_file_name(mp);
16253 } else { 
16254    xfree(mp->cur_name); mp->cur_name=xstrdup(""); 
16255    xfree(mp->cur_ext);  mp->cur_ext =xstrdup(""); 
16256    xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
16257 }
16258
16259 @ The following simple routine starts reading the \.{MPX} file associated
16260 with the current input file.
16261
16262 @c void mp_start_mpx_input (MP mp) {
16263   char *origname = NULL; /* a copy of nameoffile */
16264   mp_pack_file_name(mp, in_name, in_area, ".mpx");
16265   @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16266     |goto not_found| if there is a problem@>;
16267   mp_begin_file_reading(mp);
16268   if ( ! mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16269     mp_end_file_reading(mp);
16270     goto NOT_FOUND;
16271   }
16272   name=mp_a_make_name_string(mp, cur_file);
16273   mp->mpx_name[index]=name; add_str_ref(name);
16274   @<Read the first line of the new file@>;
16275   return;
16276 NOT_FOUND: 
16277     @<Explain that the \.{MPX} file can't be read and |succumb|@>;
16278   xfree(origname);
16279 }
16280
16281 @ This should ideally be changed to do whatever is necessary to create the
16282 \.{MPX} file given by |name_of_file| if it does not exist or if it is out
16283 of date.  This requires invoking \.{MPtoTeX} on the |origname| and passing
16284 the results through \TeX\ and \.{DVItoMP}.  (It is possible to use a
16285 completely different typesetting program if suitable postprocessor is
16286 available to perform the function of \.{DVItoMP}.)
16287 @^system dependencies@>
16288
16289 @ @<Exported types@>=
16290 typedef int (*mp_run_make_mpx_command)(MP mp, char *origname, char *mtxname);
16291
16292 @ @<Option variables@>=
16293 mp_run_make_mpx_command run_make_mpx;
16294
16295 @ @<Allocate or initialize ...@>=
16296 set_callback_option(run_make_mpx);
16297
16298 @ @<Internal library declarations@>=
16299 int mp_run_make_mpx (MP mp, char *origname, char *mtxname);
16300
16301 @ The default does nothing.
16302 @c 
16303 int mp_run_make_mpx (MP mp, char *origname, char *mtxname) {
16304   if (mp && origname && mtxname) /* for -W */
16305     return false;
16306   return false;
16307 }
16308
16309 @ @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16310   |goto not_found| if there is a problem@>=
16311 origname = mp_xstrdup(mp,mp->name_of_file);
16312 *(origname+strlen(origname)-1)=0; /* drop the x */
16313 if (!(mp->run_make_mpx)(mp, origname, mp->name_of_file))
16314   goto NOT_FOUND 
16315
16316 @ @<Explain that the \.{MPX} file can't be read and |succumb|@>=
16317 if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16318 mp_print_nl(mp, ">> ");
16319 mp_print(mp, origname);
16320 mp_print_nl(mp, ">> ");
16321 mp_print(mp, mp->name_of_file);
16322 mp_print_nl(mp, "! Unable to make mpx file");
16323 help4("The two files given above are one of your source files")
16324   ("and an auxiliary file I need to read to find out what your")
16325   ("btex..etex blocks mean. If you don't know why I had trouble,")
16326   ("try running it manually through MPtoTeX, TeX, and DVItoMP");
16327 succumb;
16328
16329 @ The last file-opening commands are for files accessed via the \&{readfrom}
16330 @:read_from_}{\&{readfrom} primitive@>
16331 operator and the \&{write} command.  Such files are stored in separate arrays.
16332 @:write_}{\&{write} primitive@>
16333
16334 @<Types in the outer block@>=
16335 typedef unsigned int readf_index; /* |0..max_read_files| */
16336 typedef unsigned int write_index;  /* |0..max_write_files| */
16337
16338 @ @<Glob...@>=
16339 readf_index max_read_files; /* maximum number of simultaneously open \&{readfrom} files */
16340 void ** rd_file; /* \&{readfrom} files */
16341 char ** rd_fname; /* corresponding file name or 0 if file not open */
16342 readf_index read_files; /* number of valid entries in the above arrays */
16343 write_index max_write_files; /* maximum number of simultaneously open \&{write} */
16344 void ** wr_file; /* \&{write} files */
16345 char ** wr_fname; /* corresponding file name or 0 if file not open */
16346 write_index write_files; /* number of valid entries in the above arrays */
16347
16348 @ @<Allocate or initialize ...@>=
16349 mp->max_read_files=8;
16350 mp->rd_file = xmalloc((mp->max_read_files+1),sizeof(void *));
16351 mp->rd_fname = xmalloc((mp->max_read_files+1),sizeof(char *));
16352 memset(mp->rd_fname, 0, sizeof(char *)*(mp->max_read_files+1));
16353 mp->read_files=0;
16354 mp->max_write_files=8;
16355 mp->wr_file = xmalloc((mp->max_write_files+1),sizeof(void *));
16356 mp->wr_fname = xmalloc((mp->max_write_files+1),sizeof(char *));
16357 memset(mp->wr_fname, 0, sizeof(char *)*(mp->max_write_files+1));
16358 mp->write_files=0;
16359
16360
16361 @ This routine starts reading the file named by string~|s| without setting
16362 |loc|, |limit|, or |name|.  It returns |false| if the file is empty or cannot
16363 be opened.  Otherwise it updates |rd_file[n]| and |rd_fname[n]|.
16364
16365 @c boolean mp_start_read_input (MP mp,char *s, readf_index  n) {
16366   mp_ptr_scan_file(mp, s);
16367   pack_cur_name;
16368   mp_begin_file_reading(mp);
16369   if ( ! mp_a_open_in(mp, &mp->rd_file[n], (mp_filetype_text+n)) ) 
16370         goto NOT_FOUND;
16371   if ( ! mp_input_ln(mp, mp->rd_file[n] ) ) {
16372     (mp->close_file)(mp->rd_file[n]); 
16373         goto NOT_FOUND; 
16374   }
16375   mp->rd_fname[n]=xstrdup(mp->name_of_file);
16376   return true;
16377 NOT_FOUND: 
16378   mp_end_file_reading(mp);
16379   return false;
16380 }
16381
16382 @ Open |wr_file[n]| using file name~|s| and update |wr_fname[n]|.
16383
16384 @<Declarations@>=
16385 void mp_open_write_file (MP mp, char *s, readf_index  n) ;
16386
16387 @ @c void mp_open_write_file (MP mp,char *s, readf_index  n) {
16388   mp_ptr_scan_file(mp, s);
16389   pack_cur_name;
16390   while ( ! mp_a_open_out(mp, &mp->wr_file[n], (mp_filetype_text+n)) )
16391     mp_prompt_file_name(mp, "file name for write output","");
16392   mp->wr_fname[n]=xstrdup(mp->name_of_file);
16393 }
16394
16395
16396 @* \[36] Introduction to the parsing routines.
16397 We come now to the central nervous system that sparks many of \MP's activities.
16398 By evaluating expressions, from their primary constituents to ever larger
16399 subexpressions, \MP\ builds the structures that ultimately define complete
16400 pictures or fonts of type.
16401
16402 Four mutually recursive subroutines are involved in this process: We call them
16403 $$\hbox{|scan_primary|, |scan_secondary|, |scan_tertiary|,
16404 and |scan_expression|.}$$
16405 @^recursion@>
16406 Each of them is parameterless and begins with the first token to be scanned
16407 already represented in |cur_cmd|, |cur_mod|, and |cur_sym|. After execution,
16408 the value of the primary or secondary or tertiary or expression that was
16409 found will appear in the global variables |cur_type| and |cur_exp|. The
16410 token following the expression will be represented in |cur_cmd|, |cur_mod|,
16411 and |cur_sym|.
16412
16413 Technically speaking, the parsing algorithms are ``LL(1),'' more or less;
16414 backup mechanisms have been added in order to provide reasonable error
16415 recovery.
16416
16417 @<Glob...@>=
16418 small_number cur_type; /* the type of the expression just found */
16419 integer cur_exp; /* the value of the expression just found */
16420
16421 @ @<Set init...@>=
16422 mp->cur_exp=0;
16423
16424 @ Many different kinds of expressions are possible, so it is wise to have
16425 precise descriptions of what |cur_type| and |cur_exp| mean in all cases:
16426
16427 \smallskip\hang
16428 |cur_type=mp_vacuous| means that this expression didn't turn out to have a
16429 value at all, because it arose from a \&{begingroup}$\,\ldots\,$\&{endgroup}
16430 construction in which there was no expression before the \&{endgroup}.
16431 In this case |cur_exp| has some irrelevant value.
16432
16433 \smallskip\hang
16434 |cur_type=mp_boolean_type| means that |cur_exp| is either |true_code|
16435 or |false_code|.
16436
16437 \smallskip\hang
16438 |cur_type=mp_unknown_boolean| means that |cur_exp| points to a capsule
16439 node that is in the ring of variables equivalent
16440 to at least one undefined boolean variable.
16441
16442 \smallskip\hang
16443 |cur_type=mp_string_type| means that |cur_exp| is a string number (i.e., an
16444 integer in the range |0<=cur_exp<str_ptr|). That string's reference count
16445 includes this particular reference.
16446
16447 \smallskip\hang
16448 |cur_type=mp_unknown_string| means that |cur_exp| points to a capsule
16449 node that is in the ring of variables equivalent
16450 to at least one undefined string variable.
16451
16452 \smallskip\hang
16453 |cur_type=mp_pen_type| means that |cur_exp| points to a node in a pen.  Nobody
16454 else points to any of the nodes in this pen.  The pen may be polygonal or
16455 elliptical.
16456
16457 \smallskip\hang
16458 |cur_type=mp_unknown_pen| means that |cur_exp| points to a capsule
16459 node that is in the ring of variables equivalent
16460 to at least one undefined pen variable.
16461
16462 \smallskip\hang
16463 |cur_type=mp_path_type| means that |cur_exp| points to a the first node of
16464 a path; nobody else points to this particular path. The control points of
16465 the path will have been chosen.
16466
16467 \smallskip\hang
16468 |cur_type=mp_unknown_path| means that |cur_exp| points to a capsule
16469 node that is in the ring of variables equivalent
16470 to at least one undefined path variable.
16471
16472 \smallskip\hang
16473 |cur_type=mp_picture_type| means that |cur_exp| points to an edge header node.
16474 There may be other pointers to this particular set of edges.  The header node
16475 contains a reference count that includes this particular reference.
16476
16477 \smallskip\hang
16478 |cur_type=mp_unknown_picture| means that |cur_exp| points to a capsule
16479 node that is in the ring of variables equivalent
16480 to at least one undefined picture variable.
16481
16482 \smallskip\hang
16483 |cur_type=mp_transform_type| means that |cur_exp| points to a |mp_transform_type|
16484 capsule node. The |value| part of this capsule
16485 points to a transform node that contains six numeric values,
16486 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16487
16488 \smallskip\hang
16489 |cur_type=mp_color_type| means that |cur_exp| points to a |color_type|
16490 capsule node. The |value| part of this capsule
16491 points to a color node that contains three numeric values,
16492 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16493
16494 \smallskip\hang
16495 |cur_type=mp_cmykcolor_type| means that |cur_exp| points to a |mp_cmykcolor_type|
16496 capsule node. The |value| part of this capsule
16497 points to a color node that contains four numeric values,
16498 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16499
16500 \smallskip\hang
16501 |cur_type=mp_pair_type| means that |cur_exp| points to a capsule
16502 node whose type is |mp_pair_type|. The |value| part of this capsule
16503 points to a pair node that contains two numeric values,
16504 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16505
16506 \smallskip\hang
16507 |cur_type=mp_known| means that |cur_exp| is a |scaled| value.
16508
16509 \smallskip\hang
16510 |cur_type=mp_dependent| means that |cur_exp| points to a capsule node whose type
16511 is |dependent|. The |dep_list| field in this capsule points to the associated
16512 dependency list.
16513
16514 \smallskip\hang
16515 |cur_type=mp_proto_dependent| means that |cur_exp| points to a |mp_proto_dependent|
16516 capsule node. The |dep_list| field in this capsule
16517 points to the associated dependency list.
16518
16519 \smallskip\hang
16520 |cur_type=independent| means that |cur_exp| points to a capsule node
16521 whose type is |independent|. This somewhat unusual case can arise, for
16522 example, in the expression
16523 `$x+\&{begingroup}\penalty0\,\&{string}\,x; 0\,\&{endgroup}$'.
16524
16525 \smallskip\hang
16526 |cur_type=mp_token_list| means that |cur_exp| points to a linked list of
16527 tokens. This case arises only on the left-hand side of an assignment
16528 (`\.{:=}') operation, under very special circumstances.
16529
16530 \smallskip\noindent
16531 The possible settings of |cur_type| have been listed here in increasing
16532 numerical order. Notice that |cur_type| will never be |mp_numeric_type| or
16533 |suffixed_macro| or |mp_unsuffixed_macro|, although variables of those types
16534 are allowed.  Conversely, \MP\ has no variables of type |mp_vacuous| or
16535 |token_list|.
16536
16537 @ Capsules are two-word nodes that have a similar meaning
16538 to |cur_type| and |cur_exp|. Such nodes have |name_type=capsule|
16539 and |link<=mp_void|; and their |type| field is one of the possibilities for
16540 |cur_type| listed above.
16541
16542 The |value| field of a capsule is, in most cases, the value that
16543 corresponds to its |type|, as |cur_exp| corresponds to |cur_type|.
16544 However, when |cur_exp| would point to a capsule,
16545 no extra layer of indirection is present; the |value|
16546 field is what would have been called |value(cur_exp)| if it had not been
16547 encapsulated.  Furthermore, if the type is |dependent| or
16548 |mp_proto_dependent|, the |value| field of a capsule is replaced by
16549 |dep_list| and |prev_dep| fields, since dependency lists in capsules are
16550 always part of the general |dep_list| structure.
16551
16552 The |get_x_next| routine is careful not to change the values of |cur_type|
16553 and |cur_exp| when it gets an expanded token. However, |get_x_next| might
16554 call a macro, which might parse an expression, which might execute lots of
16555 commands in a group; hence it's possible that |cur_type| might change
16556 from, say, |mp_unknown_boolean| to |mp_boolean_type|, or from |dependent| to
16557 |known| or |independent|, during the time |get_x_next| is called. The
16558 programs below are careful to stash sensitive intermediate results in
16559 capsules, so that \MP's generality doesn't cause trouble.
16560
16561 Here's a procedure that illustrates these conventions. It takes
16562 the contents of $(|cur_type|\kern-.3pt,|cur_exp|\kern-.3pt)$
16563 and stashes them away in a
16564 capsule. It is not used when |cur_type=mp_token_list|.
16565 After the operation, |cur_type=mp_vacuous|; hence there is no need to
16566 copy path lists or to update reference counts, etc.
16567
16568 The special link |mp_void| is put on the capsule returned by
16569 |stash_cur_exp|, because this procedure is used to store macro parameters
16570 that must be easily distinguishable from token lists.
16571
16572 @<Declare the stashing/unstashing routines@>=
16573 pointer mp_stash_cur_exp (MP mp) {
16574   pointer p; /* the capsule that will be returned */
16575   switch (mp->cur_type) {
16576   case unknown_types:
16577   case mp_transform_type:
16578   case mp_color_type:
16579   case mp_pair_type:
16580   case mp_dependent:
16581   case mp_proto_dependent:
16582   case mp_independent: 
16583   case mp_cmykcolor_type:
16584     p=mp->cur_exp;
16585     break;
16586   default: 
16587     p=mp_get_node(mp, value_node_size); name_type(p)=mp_capsule;
16588     type(p)=mp->cur_type; value(p)=mp->cur_exp;
16589     break;
16590   }
16591   mp->cur_type=mp_vacuous; link(p)=mp_void; 
16592   return p;
16593 }
16594
16595 @ The inverse of |stash_cur_exp| is the following procedure, which
16596 deletes an unnecessary capsule and puts its contents into |cur_type|
16597 and |cur_exp|.
16598
16599 The program steps of \MP\ can be divided into two categories: those in
16600 which |cur_type| and |cur_exp| are ``alive'' and those in which they are
16601 ``dead,'' in the sense that |cur_type| and |cur_exp| contain relevant
16602 information or not. It's important not to ignore them when they're alive,
16603 and it's important not to pay attention to them when they're dead.
16604
16605 There's also an intermediate category: If |cur_type=mp_vacuous|, then
16606 |cur_exp| is irrelevant, hence we can proceed without caring if |cur_type|
16607 and |cur_exp| are alive or dead. In such cases we say that |cur_type|
16608 and |cur_exp| are {\sl dormant}. It is permissible to call |get_x_next|
16609 only when they are alive or dormant.
16610
16611 The \\{stash} procedure above assumes that |cur_type| and |cur_exp|
16612 are alive or dormant. The \\{unstash} procedure assumes that they are
16613 dead or dormant; it resuscitates them.
16614
16615 @<Declare the stashing/unstashing...@>=
16616 void mp_unstash_cur_exp (MP mp,pointer p) ;
16617
16618 @ @c
16619 void mp_unstash_cur_exp (MP mp,pointer p) { 
16620   mp->cur_type=type(p);
16621   switch (mp->cur_type) {
16622   case unknown_types:
16623   case mp_transform_type:
16624   case mp_color_type:
16625   case mp_pair_type:
16626   case mp_dependent: 
16627   case mp_proto_dependent:
16628   case mp_independent:
16629   case mp_cmykcolor_type: 
16630     mp->cur_exp=p;
16631     break;
16632   default:
16633     mp->cur_exp=value(p);
16634     mp_free_node(mp, p,value_node_size);
16635     break;
16636   }
16637 }
16638
16639 @ The following procedure prints the values of expressions in an
16640 abbreviated format. If its first parameter |p| is null, the value of
16641 |(cur_type,cur_exp)| is displayed; otherwise |p| should be a capsule
16642 containing the desired value. The second parameter controls the amount of
16643 output. If it is~0, dependency lists will be abbreviated to
16644 `\.{linearform}' unless they consist of a single term.  If it is greater
16645 than~1, complicated structures (pens, pictures, and paths) will be displayed
16646 in full.
16647
16648 @<Declare subroutines for printing expressions@>=
16649 @<Declare the procedure called |print_dp|@>;
16650 @<Declare the stashing/unstashing routines@>;
16651 void mp_print_exp (MP mp,pointer p, small_number verbosity) {
16652   boolean restore_cur_exp; /* should |cur_exp| be restored? */
16653   small_number t; /* the type of the expression */
16654   pointer q; /* a big node being displayed */
16655   integer v=0; /* the value of the expression */
16656   if ( p!=null ) {
16657     restore_cur_exp=false;
16658   } else { 
16659     p=mp_stash_cur_exp(mp); restore_cur_exp=true;
16660   }
16661   t=type(p);
16662   if ( t<mp_dependent ) v=value(p); else if ( t<mp_independent ) v=dep_list(p);
16663   @<Print an abbreviated value of |v| with format depending on |t|@>;
16664   if ( restore_cur_exp ) mp_unstash_cur_exp(mp, p);
16665 }
16666
16667 @ @<Print an abbreviated value of |v| with format depending on |t|@>=
16668 switch (t) {
16669 case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
16670 case mp_boolean_type:
16671   if ( v==true_code ) mp_print(mp, "true"); else mp_print(mp, "false");
16672   break;
16673 case unknown_types: case mp_numeric_type:
16674   @<Display a variable that's been declared but not defined@>;
16675   break;
16676 case mp_string_type:
16677   mp_print_char(mp, '"'); mp_print_str(mp, v); mp_print_char(mp, '"');
16678   break;
16679 case mp_pen_type: case mp_path_type: case mp_picture_type:
16680   @<Display a complex type@>;
16681   break;
16682 case mp_transform_type: case mp_color_type: case mp_pair_type: case mp_cmykcolor_type:
16683   if ( v==null ) mp_print_type(mp, t);
16684   else @<Display a big node@>;
16685   break;
16686 case mp_known:mp_print_scaled(mp, v); break;
16687 case mp_dependent: case mp_proto_dependent:
16688   mp_print_dp(mp, t,v,verbosity);
16689   break;
16690 case mp_independent:mp_print_variable_name(mp, p); break;
16691 default: mp_confusion(mp, "exp"); break;
16692 @:this can't happen exp}{\quad exp@>
16693 }
16694
16695 @ @<Display a big node@>=
16696
16697   mp_print_char(mp, '('); q=v+mp->big_node_size[t];
16698   do {  
16699     if ( type(v)==mp_known ) mp_print_scaled(mp, value(v));
16700     else if ( type(v)==mp_independent ) mp_print_variable_name(mp, v);
16701     else mp_print_dp(mp, type(v),dep_list(v),verbosity);
16702     v=v+2;
16703     if ( v!=q ) mp_print_char(mp, ',');
16704   } while (v!=q);
16705   mp_print_char(mp, ')');
16706 }
16707
16708 @ Values of type \&{picture}, \&{path}, and \&{pen} are displayed verbosely
16709 in the log file only, unless the user has given a positive value to
16710 \\{tracingonline}.
16711
16712 @<Display a complex type@>=
16713 if ( verbosity<=1 ) {
16714   mp_print_type(mp, t);
16715 } else { 
16716   if ( mp->selector==term_and_log )
16717    if ( mp->internal[mp_tracing_online]<=0 ) {
16718     mp->selector=term_only;
16719     mp_print_type(mp, t); mp_print(mp, " (see the transcript file)");
16720     mp->selector=term_and_log;
16721   };
16722   switch (t) {
16723   case mp_pen_type:mp_print_pen(mp, v,"",false); break;
16724   case mp_path_type:mp_print_path(mp, v,"",false); break;
16725   case mp_picture_type:mp_print_edges(mp, v,"",false); break;
16726   } /* there are no other cases */
16727 }
16728
16729 @ @<Declare the procedure called |print_dp|@>=
16730 void mp_print_dp (MP mp,small_number t, pointer p, 
16731                   small_number verbosity)  {
16732   pointer q; /* the node following |p| */
16733   q=link(p);
16734   if ( (info(q)==null) || (verbosity>0) ) mp_print_dependency(mp, p,t);
16735   else mp_print(mp, "linearform");
16736 }
16737
16738 @ The displayed name of a variable in a ring will not be a capsule unless
16739 the ring consists entirely of capsules.
16740
16741 @<Display a variable that's been declared but not defined@>=
16742 { mp_print_type(mp, t);
16743 if ( v!=null )
16744   { mp_print_char(mp, ' ');
16745   while ( (name_type(v)==mp_capsule) && (v!=p) ) v=value(v);
16746   mp_print_variable_name(mp, v);
16747   };
16748 }
16749
16750 @ When errors are detected during parsing, it is often helpful to
16751 display an expression just above the error message, using |exp_err|
16752 or |disp_err| instead of |print_err|.
16753
16754 @d exp_err(A) mp_disp_err(mp, null,(A)) /* displays the current expression */
16755
16756 @<Declare subroutines for printing expressions@>=
16757 void mp_disp_err (MP mp,pointer p, char *s) { 
16758   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16759   mp_print_nl(mp, ">> ");
16760 @.>>@>
16761   mp_print_exp(mp, p,1); /* ``medium verbose'' printing of the expression */
16762   if (strlen(s)) { 
16763     mp_print_nl(mp, "! "); mp_print(mp, s);
16764 @.!\relax@>
16765   }
16766 }
16767
16768 @ If |cur_type| and |cur_exp| contain relevant information that should
16769 be recycled, we will use the following procedure, which changes |cur_type|
16770 to |known| and stores a given value in |cur_exp|. We can think of |cur_type|
16771 and |cur_exp| as either alive or dormant after this has been done,
16772 because |cur_exp| will not contain a pointer value.
16773
16774 @ @c void mp_flush_cur_exp (MP mp,scaled v) { 
16775   switch (mp->cur_type) {
16776   case unknown_types: case mp_transform_type: case mp_color_type: case mp_pair_type:
16777   case mp_dependent: case mp_proto_dependent: case mp_independent: case mp_cmykcolor_type:
16778     mp_recycle_value(mp, mp->cur_exp); 
16779     mp_free_node(mp, mp->cur_exp,value_node_size);
16780     break;
16781   case mp_string_type:
16782     delete_str_ref(mp->cur_exp); break;
16783   case mp_pen_type: case mp_path_type: 
16784     mp_toss_knot_list(mp, mp->cur_exp); break;
16785   case mp_picture_type:
16786     delete_edge_ref(mp->cur_exp); break;
16787   default: 
16788     break;
16789   }
16790   mp->cur_type=mp_known; mp->cur_exp=v;
16791 }
16792
16793 @ There's a much more general procedure that is capable of releasing
16794 the storage associated with any two-word value packet.
16795
16796 @<Declare the recycling subroutines@>=
16797 void mp_recycle_value (MP mp,pointer p) ;
16798
16799 @ @c void mp_recycle_value (MP mp,pointer p) {
16800   small_number t; /* a type code */
16801   integer vv; /* another value */
16802   pointer q,r,s,pp; /* link manipulation registers */
16803   integer v=0; /* a value */
16804   t=type(p);
16805   if ( t<mp_dependent ) v=value(p);
16806   switch (t) {
16807   case undefined: case mp_vacuous: case mp_boolean_type: case mp_known:
16808   case mp_numeric_type:
16809     break;
16810   case unknown_types:
16811     mp_ring_delete(mp, p); break;
16812   case mp_string_type:
16813     delete_str_ref(v); break;
16814   case mp_path_type: case mp_pen_type:
16815     mp_toss_knot_list(mp, v); break;
16816   case mp_picture_type:
16817     delete_edge_ref(v); break;
16818   case mp_cmykcolor_type: case mp_pair_type: case mp_color_type:
16819   case mp_transform_type:
16820     @<Recycle a big node@>; break; 
16821   case mp_dependent: case mp_proto_dependent:
16822     @<Recycle a dependency list@>; break;
16823   case mp_independent:
16824     @<Recycle an independent variable@>; break;
16825   case mp_token_list: case mp_structured:
16826     mp_confusion(mp, "recycle"); break;
16827 @:this can't happen recycle}{\quad recycle@>
16828   case mp_unsuffixed_macro: case mp_suffixed_macro:
16829     mp_delete_mac_ref(mp, value(p)); break;
16830   } /* there are no other cases */
16831   type(p)=undefined;
16832 }
16833
16834 @ @<Recycle a big node@>=
16835 if ( v!=null ){ 
16836   q=v+mp->big_node_size[t];
16837   do {  
16838     q=q-2; mp_recycle_value(mp, q);
16839   } while (q!=v);
16840   mp_free_node(mp, v,mp->big_node_size[t]);
16841 }
16842
16843 @ @<Recycle a dependency list@>=
16844
16845   q=dep_list(p);
16846   while ( info(q)!=null ) q=link(q);
16847   link(prev_dep(p))=link(q);
16848   prev_dep(link(q))=prev_dep(p);
16849   link(q)=null; mp_flush_node_list(mp, dep_list(p));
16850 }
16851
16852 @ When an independent variable disappears, it simply fades away, unless
16853 something depends on it. In the latter case, a dependent variable whose
16854 coefficient of dependence is maximal will take its place.
16855 The relevant algorithm is due to Ignacio~A. Zabala, who implemented it
16856 as part of his Ph.D. thesis (Stanford University, December 1982).
16857 @^Zabala Salelles, Ignacio Andres@>
16858
16859 For example, suppose that variable $x$ is being recycled, and that the
16860 only variables depending on~$x$ are $y=2x+a$ and $z=x+b$. In this case
16861 we want to make $y$ independent and $z=.5y-.5a+b$; no other variables
16862 will depend on~$y$. If $\\{tracingequations}>0$ in this situation,
16863 we will print `\.{\#\#\# -2x=-y+a}'.
16864
16865 There's a slight complication, however: An independent variable $x$
16866 can occur both in dependency lists and in proto-dependency lists.
16867 This makes it necessary to be careful when deciding which coefficient
16868 is maximal.
16869
16870 Furthermore, this complication is not so slight when
16871 a proto-dependent variable is chosen to become independent. For example,
16872 suppose that $y=2x+100a$ is proto-dependent while $z=x+b$ is dependent;
16873 then we must change $z=.5y-50a+b$ to a proto-dependency, because of the
16874 large coefficient `50'.
16875
16876 In order to deal with these complications without wasting too much time,
16877 we shall link together the occurrences of~$x$ among all the linear
16878 dependencies, maintaining separate lists for the dependent and
16879 proto-dependent cases.
16880
16881 @<Recycle an independent variable@>=
16882
16883   mp->max_c[mp_dependent]=0; mp->max_c[mp_proto_dependent]=0;
16884   mp->max_link[mp_dependent]=null; mp->max_link[mp_proto_dependent]=null;
16885   q=link(dep_head);
16886   while ( q!=dep_head ) { 
16887     s=value_loc(q); /* now |link(s)=dep_list(q)| */
16888     while (1) { 
16889       r=link(s);
16890       if ( info(r)==null ) break;;
16891       if ( info(r)!=p ) { 
16892        s=r;
16893       } else  { 
16894         t=type(q); link(s)=link(r); info(r)=q;
16895         if ( abs(value(r))>mp->max_c[t] ) {
16896           @<Record a new maximum coefficient of type |t|@>;
16897         } else { 
16898           link(r)=mp->max_link[t]; mp->max_link[t]=r;
16899         }
16900       }
16901     }   
16902     q=link(r);
16903   }
16904   if ( (mp->max_c[mp_dependent]>0)||(mp->max_c[mp_proto_dependent]>0) ) {
16905     @<Choose a dependent variable to take the place of the disappearing
16906     independent variable, and change all remaining dependencies
16907     accordingly@>;
16908   }
16909 }
16910
16911 @ The code for independency removal makes use of three two-word arrays.
16912
16913 @<Glob...@>=
16914 integer max_c[mp_proto_dependent+1];  /* max coefficient magnitude */
16915 pointer max_ptr[mp_proto_dependent+1]; /* where |p| occurs with |max_c| */
16916 pointer max_link[mp_proto_dependent+1]; /* other occurrences of |p| */
16917
16918 @ @<Record a new maximum coefficient...@>=
16919
16920   if ( mp->max_c[t]>0 ) {
16921     link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
16922   }
16923   mp->max_c[t]=abs(value(r)); mp->max_ptr[t]=r;
16924 }
16925
16926 @ @<Choose a dependent...@>=
16927
16928   if ( (mp->max_c[mp_dependent] / 010000 >= mp->max_c[mp_proto_dependent]) )
16929     t=mp_dependent;
16930   else 
16931     t=mp_proto_dependent;
16932   @<Determine the dependency list |s| to substitute for the independent
16933     variable~|p|@>;
16934   t=mp_dependent+mp_proto_dependent-t; /* complement |t| */
16935   if ( mp->max_c[t]>0 ) { /* we need to pick up an unchosen dependency */ 
16936     link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
16937   }
16938   if ( t!=mp_dependent ) { @<Substitute new dependencies in place of |p|@>; }
16939   else { @<Substitute new proto-dependencies in place of |p|@>;}
16940   mp_flush_node_list(mp, s);
16941   if ( mp->fix_needed ) mp_fix_dependencies(mp);
16942   check_arith;
16943 }
16944
16945 @ Let |s=max_ptr[t]|. At this point we have $|value|(s)=\pm|max_c|[t]$,
16946 and |info(s)| points to the dependent variable~|pp| of type~|t| from
16947 whose dependency list we have removed node~|s|. We must reinsert
16948 node~|s| into the dependency list, with coefficient $-1.0$, and with
16949 |pp| as the new independent variable. Since |pp| will have a larger serial
16950 number than any other variable, we can put node |s| at the head of the
16951 list.
16952
16953 @<Determine the dep...@>=
16954 s=mp->max_ptr[t]; pp=info(s); v=value(s);
16955 if ( t==mp_dependent ) value(s)=-fraction_one; else value(s)=-unity;
16956 r=dep_list(pp); link(s)=r;
16957 while ( info(r)!=null ) r=link(r);
16958 q=link(r); link(r)=null;
16959 prev_dep(q)=prev_dep(pp); link(prev_dep(pp))=q;
16960 new_indep(pp);
16961 if ( mp->cur_exp==pp ) if ( mp->cur_type==t ) mp->cur_type=mp_independent;
16962 if ( mp->internal[mp_tracing_equations]>0 ) { 
16963   @<Show the transformed dependency@>; 
16964 }
16965
16966 @ Now $(-v)$ times the formerly independent variable~|p| is being replaced
16967 by the dependency list~|s|.
16968
16969 @<Show the transformed...@>=
16970 if ( mp_interesting(mp, p) ) {
16971   mp_begin_diagnostic(mp); mp_print_nl(mp, "### ");
16972 @:]]]\#\#\#_}{\.{\#\#\#}@>
16973   if ( v>0 ) mp_print_char(mp, '-');
16974   if ( t==mp_dependent ) vv=mp_round_fraction(mp, mp->max_c[mp_dependent]);
16975   else vv=mp->max_c[mp_proto_dependent];
16976   if ( vv!=unity ) mp_print_scaled(mp, vv);
16977   mp_print_variable_name(mp, p);
16978   while ( value(p) % s_scale>0 ) {
16979     mp_print(mp, "*4"); value(p)=value(p)-2;
16980   }
16981   if ( t==mp_dependent ) mp_print_char(mp, '='); else mp_print(mp, " = ");
16982   mp_print_dependency(mp, s,t);
16983   mp_end_diagnostic(mp, false);
16984 }
16985
16986 @ Finally, there are dependent and proto-dependent variables whose
16987 dependency lists must be brought up to date.
16988
16989 @<Substitute new dependencies...@>=
16990 for (t=mp_dependent;t<=mp_proto_dependent;t++){ 
16991   r=mp->max_link[t];
16992   while ( r!=null ) {
16993     q=info(r);
16994     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
16995      mp_make_fraction(mp, value(r),-v),s,t,mp_dependent);
16996     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
16997     q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
16998   }
16999 }
17000
17001 @ @<Substitute new proto...@>=
17002 for (t=mp_dependent;t<=mp_proto_dependent;t++) {
17003   r=mp->max_link[t];
17004   while ( r!=null ) {
17005     q=info(r);
17006     if ( t==mp_dependent ) { /* for safety's sake, we change |q| to |mp_proto_dependent| */
17007       if ( mp->cur_exp==q ) if ( mp->cur_type==mp_dependent )
17008         mp->cur_type=mp_proto_dependent;
17009       dep_list(q)=mp_p_over_v(mp, dep_list(q),unity,mp_dependent,mp_proto_dependent);
17010       type(q)=mp_proto_dependent; value(r)=mp_round_fraction(mp, value(r));
17011     }
17012     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
17013       mp_make_scaled(mp, value(r),-v),s,mp_proto_dependent,mp_proto_dependent);
17014     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
17015     q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
17016   }
17017 }
17018
17019 @ Here are some routines that provide handy combinations of actions
17020 that are often needed during error recovery. For example,
17021 `|flush_error|' flushes the current expression, replaces it by
17022 a given value, and calls |error|.
17023
17024 Errors often are detected after an extra token has already been scanned.
17025 The `\\{put\_get}' routines put that token back before calling |error|;
17026 then they get it back again. (Or perhaps they get another token, if
17027 the user has changed things.)
17028
17029 @<Declarations@>=
17030 void mp_flush_error (MP mp,scaled v);
17031 void mp_put_get_error (MP mp);
17032 void mp_put_get_flush_error (MP mp,scaled v) ;
17033
17034 @ @c
17035 void mp_flush_error (MP mp,scaled v) { 
17036   mp_error(mp); mp_flush_cur_exp(mp, v); 
17037 }
17038 void mp_put_get_error (MP mp) { 
17039   mp_back_error(mp); mp_get_x_next(mp); 
17040 }
17041 void mp_put_get_flush_error (MP mp,scaled v) { 
17042   mp_put_get_error(mp);
17043   mp_flush_cur_exp(mp, v); 
17044 }
17045
17046 @ A global variable |var_flag| is set to a special command code
17047 just before \MP\ calls |scan_expression|, if the expression should be
17048 treated as a variable when this command code immediately follows. For
17049 example, |var_flag| is set to |assignment| at the beginning of a
17050 statement, because we want to know the {\sl location\/} of a variable at
17051 the left of `\.{:=}', not the {\sl value\/} of that variable.
17052
17053 The |scan_expression| subroutine calls |scan_tertiary|,
17054 which calls |scan_secondary|, which calls |scan_primary|, which sets
17055 |var_flag:=0|. In this way each of the scanning routines ``knows''
17056 when it has been called with a special |var_flag|, but |var_flag| is
17057 usually zero.
17058
17059 A variable preceding a command that equals |var_flag| is converted to a
17060 token list rather than a value. Furthermore, an `\.{=}' sign following an
17061 expression with |var_flag=assignment| is not considered to be a relation
17062 that produces boolean expressions.
17063
17064
17065 @<Glob...@>=
17066 int var_flag; /* command that wants a variable */
17067
17068 @ @<Set init...@>=
17069 mp->var_flag=0;
17070
17071 @* \[37] Parsing primary expressions.
17072 The first parsing routine, |scan_primary|, is also the most complicated one,
17073 since it involves so many different cases. But each case---with one
17074 exception---is fairly simple by itself.
17075
17076 When |scan_primary| begins, the first token of the primary to be scanned
17077 should already appear in |cur_cmd|, |cur_mod|, and |cur_sym|. The values
17078 of |cur_type| and |cur_exp| should be either dead or dormant, as explained
17079 earlier. If |cur_cmd| is not between |min_primary_command| and
17080 |max_primary_command|, inclusive, a syntax error will be signaled.
17081
17082 @<Declare the basic parsing subroutines@>=
17083 void mp_scan_primary (MP mp) {
17084   pointer p,q,r; /* for list manipulation */
17085   quarterword c; /* a primitive operation code */
17086   int my_var_flag; /* initial value of |my_var_flag| */
17087   pointer l_delim,r_delim; /* hash addresses of a delimiter pair */
17088   @<Other local variables for |scan_primary|@>;
17089   my_var_flag=mp->var_flag; mp->var_flag=0;
17090 RESTART:
17091   check_arith;
17092   @<Supply diagnostic information, if requested@>;
17093   switch (mp->cur_cmd) {
17094   case left_delimiter:
17095     @<Scan a delimited primary@>; break;
17096   case begin_group:
17097     @<Scan a grouped primary@>; break;
17098   case string_token:
17099     @<Scan a string constant@>; break;
17100   case numeric_token:
17101     @<Scan a primary that starts with a numeric token@>; break;
17102   case nullary:
17103     @<Scan a nullary operation@>; break;
17104   case unary: case type_name: case cycle: case plus_or_minus:
17105     @<Scan a unary operation@>; break;
17106   case primary_binary:
17107     @<Scan a binary operation with `\&{of}' between its operands@>; break;
17108   case str_op:
17109     @<Convert a suffix to a string@>; break;
17110   case internal_quantity:
17111     @<Scan an internal numeric quantity@>; break;
17112   case capsule_token:
17113     mp_make_exp_copy(mp, mp->cur_mod); break;
17114   case tag_token:
17115     @<Scan a variable primary; |goto restart| if it turns out to be a macro@>; break;
17116   default: 
17117     mp_bad_exp(mp, "A primary"); goto RESTART; break;
17118 @.A primary expression...@>
17119   }
17120   mp_get_x_next(mp); /* the routines |goto done| if they don't want this */
17121 DONE: 
17122   if ( mp->cur_cmd==left_bracket ) {
17123     if ( mp->cur_type>=mp_known ) {
17124       @<Scan a mediation construction@>;
17125     }
17126   }
17127 }
17128
17129
17130
17131 @ Errors at the beginning of expressions are flagged by |bad_exp|.
17132
17133 @c void mp_bad_exp (MP mp,char * s) {
17134   int save_flag;
17135   print_err(s); mp_print(mp, " expression can't begin with `");
17136   mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); 
17137   mp_print_char(mp, '\'');
17138   help4("I'm afraid I need some sort of value in order to continue,")
17139     ("so I've tentatively inserted `0'. You may want to")
17140     ("delete this zero and insert something else;")
17141     ("see Chapter 27 of The METAFONTbook for an example.");
17142 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
17143   mp_back_input(mp); mp->cur_sym=0; mp->cur_cmd=numeric_token; 
17144   mp->cur_mod=0; mp_ins_error(mp);
17145   save_flag=mp->var_flag; mp->var_flag=0; mp_get_x_next(mp);
17146   mp->var_flag=save_flag;
17147 }
17148
17149 @ @<Supply diagnostic information, if requested@>=
17150 #ifdef DEBUG
17151 if ( mp->panicking ) mp_check_mem(mp, false);
17152 #endif
17153 if ( mp->interrupt!=0 ) if ( mp->OK_to_interrupt ) {
17154   mp_back_input(mp); check_interrupt; mp_get_x_next(mp);
17155 }
17156
17157 @ @<Scan a delimited primary@>=
17158
17159   l_delim=mp->cur_sym; r_delim=mp->cur_mod; 
17160   mp_get_x_next(mp); mp_scan_expression(mp);
17161   if ( (mp->cur_cmd==comma) && (mp->cur_type>=mp_known) ) {
17162     @<Scan the rest of a delimited set of numerics@>;
17163   } else {
17164     mp_check_delimiter(mp, l_delim,r_delim);
17165   }
17166 }
17167
17168 @ The |stash_in| subroutine puts the current (numeric) expression into a field
17169 within a ``big node.''
17170
17171 @c void mp_stash_in (MP mp,pointer p) {
17172   pointer q; /* temporary register */
17173   type(p)=mp->cur_type;
17174   if ( mp->cur_type==mp_known ) {
17175     value(p)=mp->cur_exp;
17176   } else { 
17177     if ( mp->cur_type==mp_independent ) {
17178       @<Stash an independent |cur_exp| into a big node@>;
17179     } else { 
17180       mp->mem[value_loc(p)]=mp->mem[value_loc(mp->cur_exp)];
17181       /* |dep_list(p):=dep_list(cur_exp)| and |prev_dep(p):=prev_dep(cur_exp)| */
17182       link(prev_dep(p))=p;
17183     }
17184     mp_free_node(mp, mp->cur_exp,value_node_size);
17185   }
17186   mp->cur_type=mp_vacuous;
17187 }
17188
17189 @ In rare cases the current expression can become |independent|. There
17190 may be many dependency lists pointing to such an independent capsule,
17191 so we can't simply move it into place within a big node. Instead,
17192 we copy it, then recycle it.
17193
17194 @ @<Stash an independent |cur_exp|...@>=
17195
17196   q=mp_single_dependency(mp, mp->cur_exp);
17197   if ( q==mp->dep_final ){ 
17198     type(p)=mp_known; value(p)=0; mp_free_node(mp, q,dep_node_size);
17199   } else { 
17200     type(p)=mp_dependent; mp_new_dep(mp, p,q);
17201   }
17202   mp_recycle_value(mp, mp->cur_exp);
17203 }
17204
17205 @ This code uses the fact that |red_part_loc| and |green_part_loc|
17206 are synonymous with |x_part_loc| and |y_part_loc|.
17207
17208 @<Scan the rest of a delimited set of numerics@>=
17209
17210 p=mp_stash_cur_exp(mp);
17211 mp_get_x_next(mp); mp_scan_expression(mp);
17212 @<Make sure the second part of a pair or color has a numeric type@>;
17213 q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
17214 if ( mp->cur_cmd==comma ) type(q)=mp_color_type;
17215 else type(q)=mp_pair_type;
17216 mp_init_big_node(mp, q); r=value(q);
17217 mp_stash_in(mp, y_part_loc(r));
17218 mp_unstash_cur_exp(mp, p);
17219 mp_stash_in(mp, x_part_loc(r));
17220 if ( mp->cur_cmd==comma ) {
17221   @<Scan the last of a triplet of numerics@>;
17222 }
17223 if ( mp->cur_cmd==comma ) {
17224   type(q)=mp_cmykcolor_type;
17225   mp_init_big_node(mp, q); t=value(q);
17226   mp->mem[cyan_part_loc(t)]=mp->mem[red_part_loc(r)];
17227   value(cyan_part_loc(t))=value(red_part_loc(r));
17228   mp->mem[magenta_part_loc(t)]=mp->mem[green_part_loc(r)];
17229   value(magenta_part_loc(t))=value(green_part_loc(r));
17230   mp->mem[yellow_part_loc(t)]=mp->mem[blue_part_loc(r)];
17231   value(yellow_part_loc(t))=value(blue_part_loc(r));
17232   mp_recycle_value(mp, r);
17233   r=t;
17234   @<Scan the last of a quartet of numerics@>;
17235 }
17236 mp_check_delimiter(mp, l_delim,r_delim);
17237 mp->cur_type=type(q);
17238 mp->cur_exp=q;
17239 }
17240
17241 @ @<Make sure the second part of a pair or color has a numeric type@>=
17242 if ( mp->cur_type<mp_known ) {
17243   exp_err("Nonnumeric ypart has been replaced by 0");
17244 @.Nonnumeric...replaced by 0@>
17245   help4("I've started to scan a pair `(a,b)' or a color `(a,b,c)';")
17246     ("but after finding a nice `a' I found a `b' that isn't")
17247     ("of numeric type. So I've changed that part to zero.")
17248     ("(The b that I didn't like appears above the error message.)");
17249   mp_put_get_flush_error(mp, 0);
17250 }
17251
17252 @ @<Scan the last of a triplet of numerics@>=
17253
17254   mp_get_x_next(mp); mp_scan_expression(mp);
17255   if ( mp->cur_type<mp_known ) {
17256     exp_err("Nonnumeric third part has been replaced by 0");
17257 @.Nonnumeric...replaced by 0@>
17258     help3("I've just scanned a color `(a,b,c)' or cmykcolor(a,b,c,d); but the `c'")
17259       ("isn't of numeric type. So I've changed that part to zero.")
17260       ("(The c that I didn't like appears above the error message.)");
17261     mp_put_get_flush_error(mp, 0);
17262   }
17263   mp_stash_in(mp, blue_part_loc(r));
17264 }
17265
17266 @ @<Scan the last of a quartet of numerics@>=
17267
17268   mp_get_x_next(mp); mp_scan_expression(mp);
17269   if ( mp->cur_type<mp_known ) {
17270     exp_err("Nonnumeric blackpart has been replaced by 0");
17271 @.Nonnumeric...replaced by 0@>
17272     help3("I've just scanned a cmykcolor `(c,m,y,k)'; but the `k' isn't")
17273       ("of numeric type. So I've changed that part to zero.")
17274       ("(The k that I didn't like appears above the error message.)");
17275     mp_put_get_flush_error(mp, 0);
17276   }
17277   mp_stash_in(mp, black_part_loc(r));
17278 }
17279
17280 @ The local variable |group_line| keeps track of the line
17281 where a \&{begingroup} command occurred; this will be useful
17282 in an error message if the group doesn't actually end.
17283
17284 @<Other local variables for |scan_primary|@>=
17285 integer group_line; /* where a group began */
17286
17287 @ @<Scan a grouped primary@>=
17288
17289   group_line=mp_true_line(mp);
17290   if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17291   save_boundary_item(p);
17292   do {  
17293     mp_do_statement(mp); /* ends with |cur_cmd>=semicolon| */
17294   } while (! (mp->cur_cmd!=semicolon));
17295   if ( mp->cur_cmd!=end_group ) {
17296     print_err("A group begun on line ");
17297 @.A group...never ended@>
17298     mp_print_int(mp, group_line);
17299     mp_print(mp, " never ended");
17300     help2("I saw a `begingroup' back there that hasn't been matched")
17301          ("by `endgroup'. So I've inserted `endgroup' now.");
17302     mp_back_error(mp); mp->cur_cmd=end_group;
17303   }
17304   mp_unsave(mp); 
17305     /* this might change |cur_type|, if independent variables are recycled */
17306   if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17307 }
17308
17309 @ @<Scan a string constant@>=
17310
17311   mp->cur_type=mp_string_type; mp->cur_exp=mp->cur_mod;
17312 }
17313
17314 @ Later we'll come to procedures that perform actual operations like
17315 addition, square root, and so on; our purpose now is to do the parsing.
17316 But we might as well mention those future procedures now, so that the
17317 suspense won't be too bad:
17318
17319 \smallskip
17320 |do_nullary(c)| does primitive operations that have no operands (e.g.,
17321 `\&{true}' or `\&{pencircle}');
17322
17323 \smallskip
17324 |do_unary(c)| applies a primitive operation to the current expression;
17325
17326 \smallskip
17327 |do_binary(p,c)| applies a primitive operation to the capsule~|p|
17328 and the current expression.
17329
17330 @<Scan a nullary operation@>=mp_do_nullary(mp, mp->cur_mod)
17331
17332 @ @<Scan a unary operation@>=
17333
17334   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_primary(mp); 
17335   mp_do_unary(mp, c); goto DONE;
17336 }
17337
17338 @ A numeric token might be a primary by itself, or it might be the
17339 numerator of a fraction composed solely of numeric tokens, or it might
17340 multiply the primary that follows (provided that the primary doesn't begin
17341 with a plus sign or a minus sign). The code here uses the facts that
17342 |max_primary_command=plus_or_minus| and
17343 |max_primary_command-1=numeric_token|. If a fraction is found that is less
17344 than unity, we try to retain higher precision when we use it in scalar
17345 multiplication.
17346
17347 @<Other local variables for |scan_primary|@>=
17348 scaled num,denom; /* for primaries that are fractions, like `1/2' */
17349
17350 @ @<Scan a primary that starts with a numeric token@>=
17351
17352   mp->cur_exp=mp->cur_mod; mp->cur_type=mp_known; mp_get_x_next(mp);
17353   if ( mp->cur_cmd!=slash ) { 
17354     num=0; denom=0;
17355   } else { 
17356     mp_get_x_next(mp);
17357     if ( mp->cur_cmd!=numeric_token ) { 
17358       mp_back_input(mp);
17359       mp->cur_cmd=slash; mp->cur_mod=over; mp->cur_sym=frozen_slash;
17360       goto DONE;
17361     }
17362     num=mp->cur_exp; denom=mp->cur_mod;
17363     if ( denom==0 ) { @<Protest division by zero@>; }
17364     else { mp->cur_exp=mp_make_scaled(mp, num,denom); }
17365     check_arith; mp_get_x_next(mp);
17366   }
17367   if ( mp->cur_cmd>=min_primary_command ) {
17368    if ( mp->cur_cmd<numeric_token ) { /* in particular, |cur_cmd<>plus_or_minus| */
17369      p=mp_stash_cur_exp(mp); mp_scan_primary(mp);
17370      if ( (abs(num)>=abs(denom))||(mp->cur_type<mp_color_type) ) {
17371        mp_do_binary(mp, p,times);
17372      } else {
17373        mp_frac_mult(mp, num,denom);
17374        mp_free_node(mp, p,value_node_size);
17375      }
17376     }
17377   }
17378   goto DONE;
17379 }
17380
17381 @ @<Protest division...@>=
17382
17383   print_err("Division by zero");
17384 @.Division by zero@>
17385   help1("I'll pretend that you meant to divide by 1."); mp_error(mp);
17386 }
17387
17388 @ @<Scan a binary operation with `\&{of}' between its operands@>=
17389
17390   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
17391   if ( mp->cur_cmd!=of_token ) {
17392     mp_missing_err(mp, "of"); mp_print(mp, " for "); 
17393     mp_print_cmd_mod(mp, primary_binary,c);
17394 @.Missing `of'@>
17395     help1("I've got the first argument; will look now for the other.");
17396     mp_back_error(mp);
17397   }
17398   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_primary(mp); 
17399   mp_do_binary(mp, p,c); goto DONE;
17400 }
17401
17402 @ @<Convert a suffix to a string@>=
17403
17404   mp_get_x_next(mp); mp_scan_suffix(mp); 
17405   mp->old_setting=mp->selector; mp->selector=new_string;
17406   mp_show_token_list(mp, mp->cur_exp,null,100000,0); 
17407   mp_flush_token_list(mp, mp->cur_exp);
17408   mp->cur_exp=mp_make_string(mp); mp->selector=mp->old_setting; 
17409   mp->cur_type=mp_string_type;
17410   goto DONE;
17411 }
17412
17413 @ If an internal quantity appears all by itself on the left of an
17414 assignment, we return a token list of length one, containing the address
17415 of the internal quantity plus |hash_end|. (This accords with the conventions
17416 of the save stack, as described earlier.)
17417
17418 @<Scan an internal...@>=
17419
17420   q=mp->cur_mod;
17421   if ( my_var_flag==assignment ) {
17422     mp_get_x_next(mp);
17423     if ( mp->cur_cmd==assignment ) {
17424       mp->cur_exp=mp_get_avail(mp);
17425       info(mp->cur_exp)=q+hash_end; mp->cur_type=mp_token_list; 
17426       goto DONE;
17427     }
17428     mp_back_input(mp);
17429   }
17430   mp->cur_type=mp_known; mp->cur_exp=mp->internal[q];
17431 }
17432
17433 @ The most difficult part of |scan_primary| has been saved for last, since
17434 it was necessary to build up some confidence first. We can now face the task
17435 of scanning a variable.
17436
17437 As we scan a variable, we build a token list containing the relevant
17438 names and subscript values, simultaneously following along in the
17439 ``collective'' structure to see if we are actually dealing with a macro
17440 instead of a value.
17441
17442 The local variables |pre_head| and |post_head| will point to the beginning
17443 of the prefix and suffix lists; |tail| will point to the end of the list
17444 that is currently growing.
17445
17446 Another local variable, |tt|, contains partial information about the
17447 declared type of the variable-so-far. If |tt>=mp_unsuffixed_macro|, the
17448 relation |tt=type(q)| will always hold. If |tt=undefined|, the routine
17449 doesn't bother to update its information about type. And if
17450 |undefined<tt<mp_unsuffixed_macro|, the precise value of |tt| isn't critical.
17451
17452 @ @<Other local variables for |scan_primary|@>=
17453 pointer pre_head,post_head,tail;
17454   /* prefix and suffix list variables */
17455 small_number tt; /* approximation to the type of the variable-so-far */
17456 pointer t; /* a token */
17457 pointer macro_ref = 0; /* reference count for a suffixed macro */
17458
17459 @ @<Scan a variable primary...@>=
17460
17461   fast_get_avail(pre_head); tail=pre_head; post_head=null; tt=mp_vacuous;
17462   while (1) { 
17463     t=mp_cur_tok(mp); link(tail)=t;
17464     if ( tt!=undefined ) {
17465        @<Find the approximate type |tt| and corresponding~|q|@>;
17466       if ( tt>=mp_unsuffixed_macro ) {
17467         @<Either begin an unsuffixed macro call or
17468           prepare for a suffixed one@>;
17469       }
17470     }
17471     mp_get_x_next(mp); tail=t;
17472     if ( mp->cur_cmd==left_bracket ) {
17473       @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>;
17474     }
17475     if ( mp->cur_cmd>max_suffix_token ) break;
17476     if ( mp->cur_cmd<min_suffix_token ) break;
17477   } /* now |cur_cmd| is |internal_quantity|, |tag_token|, or |numeric_token| */
17478   @<Handle unusual cases that masquerade as variables, and |goto restart|
17479     or |goto done| if appropriate;
17480     otherwise make a copy of the variable and |goto done|@>;
17481 }
17482
17483 @ @<Either begin an unsuffixed macro call or...@>=
17484
17485   link(tail)=null;
17486   if ( tt>mp_unsuffixed_macro ) { /* |tt=mp_suffixed_macro| */
17487     post_head=mp_get_avail(mp); tail=post_head; link(tail)=t;
17488     tt=undefined; macro_ref=value(q); add_mac_ref(macro_ref);
17489   } else {
17490     @<Set up unsuffixed macro call and |goto restart|@>;
17491   }
17492 }
17493
17494 @ @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>=
17495
17496   mp_get_x_next(mp); mp_scan_expression(mp);
17497   if ( mp->cur_cmd!=right_bracket ) {
17498     @<Put the left bracket and the expression back to be rescanned@>;
17499   } else { 
17500     if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17501     mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp; mp->cur_sym=0;
17502   }
17503 }
17504
17505 @ The left bracket that we thought was introducing a subscript might have
17506 actually been the left bracket in a mediation construction like `\.{x[a,b]}'.
17507 So we don't issue an error message at this point; but we do want to back up
17508 so as to avoid any embarrassment about our incorrect assumption.
17509
17510 @<Put the left bracket and the expression back to be rescanned@>=
17511
17512   mp_back_input(mp); /* that was the token following the current expression */
17513   mp_back_expr(mp); mp->cur_cmd=left_bracket; 
17514   mp->cur_mod=0; mp->cur_sym=frozen_left_bracket;
17515 }
17516
17517 @ Here's a routine that puts the current expression back to be read again.
17518
17519 @c void mp_back_expr (MP mp) {
17520   pointer p; /* capsule token */
17521   p=mp_stash_cur_exp(mp); link(p)=null; back_list(p);
17522 }
17523
17524 @ Unknown subscripts lead to the following error message.
17525
17526 @c void mp_bad_subscript (MP mp) { 
17527   exp_err("Improper subscript has been replaced by zero");
17528 @.Improper subscript...@>
17529   help3("A bracketed subscript must have a known numeric value;")
17530     ("unfortunately, what I found was the value that appears just")
17531     ("above this error message. So I'll try a zero subscript.");
17532   mp_flush_error(mp, 0);
17533 }
17534
17535 @ Every time we call |get_x_next|, there's a chance that the variable we've
17536 been looking at will disappear. Thus, we cannot safely keep |q| pointing
17537 into the variable structure; we need to start searching from the root each time.
17538
17539 @<Find the approximate type |tt| and corresponding~|q|@>=
17540 @^inner loop@>
17541
17542   p=link(pre_head); q=info(p); tt=undefined;
17543   if ( eq_type(q) % outer_tag==tag_token ) {
17544     q=equiv(q);
17545     if ( q==null ) goto DONE2;
17546     while (1) { 
17547       p=link(p);
17548       if ( p==null ) {
17549         tt=type(q); goto DONE2;
17550       };
17551       if ( type(q)!=mp_structured ) goto DONE2;
17552       q=link(attr_head(q)); /* the |collective_subscript| attribute */
17553       if ( p>=mp->hi_mem_min ) { /* it's not a subscript */
17554         do {  q=link(q); } while (! (attr_loc(q)>=info(p)));
17555         if ( attr_loc(q)>info(p) ) goto DONE2;
17556       }
17557     }
17558   }
17559 DONE2:
17560   ;
17561 }
17562
17563 @ How do things stand now? Well, we have scanned an entire variable name,
17564 including possible subscripts and/or attributes; |cur_cmd|, |cur_mod|, and
17565 |cur_sym| represent the token that follows. If |post_head=null|, a
17566 token list for this variable name starts at |link(pre_head)|, with all
17567 subscripts evaluated. But if |post_head<>null|, the variable turned out
17568 to be a suffixed macro; |pre_head| is the head of the prefix list, while
17569 |post_head| is the head of a token list containing both `\.{\AT!}' and
17570 the suffix.
17571
17572 Our immediate problem is to see if this variable still exists. (Variable
17573 structures can change drastically whenever we call |get_x_next|; users
17574 aren't supposed to do this, but the fact that it is possible means that
17575 we must be cautious.)
17576
17577 The following procedure prints an error message when a variable
17578 unexpectedly disappears. Its help message isn't quite right for
17579 our present purposes, but we'll be able to fix that up.
17580
17581 @c 
17582 void mp_obliterated (MP mp,pointer q) { 
17583   print_err("Variable "); mp_show_token_list(mp, q,null,1000,0);
17584   mp_print(mp, " has been obliterated");
17585 @.Variable...obliterated@>
17586   help5("It seems you did a nasty thing---probably by accident,")
17587     ("but nevertheless you nearly hornswoggled me...")
17588     ("While I was evaluating the right-hand side of this")
17589     ("command, something happened, and the left-hand side")
17590     ("is no longer a variable! So I won't change anything.");
17591 }
17592
17593 @ If the variable does exist, we also need to check
17594 for a few other special cases before deciding that a plain old ordinary
17595 variable has, indeed, been scanned.
17596
17597 @<Handle unusual cases that masquerade as variables...@>=
17598 if ( post_head!=null ) {
17599   @<Set up suffixed macro call and |goto restart|@>;
17600 }
17601 q=link(pre_head); free_avail(pre_head);
17602 if ( mp->cur_cmd==my_var_flag ) { 
17603   mp->cur_type=mp_token_list; mp->cur_exp=q; goto DONE;
17604 }
17605 p=mp_find_variable(mp, q);
17606 if ( p!=null ) {
17607   mp_make_exp_copy(mp, p);
17608 } else { 
17609   mp_obliterated(mp, q);
17610   mp->help_line[2]="While I was evaluating the suffix of this variable,";
17611   mp->help_line[1]="something was redefined, and it's no longer a variable!";
17612   mp->help_line[0]="In order to get back on my feet, I've inserted `0' instead.";
17613   mp_put_get_flush_error(mp, 0);
17614 }
17615 mp_flush_node_list(mp, q); 
17616 goto DONE
17617
17618 @ The only complication associated with macro calling is that the prefix
17619 and ``at'' parameters must be packaged in an appropriate list of lists.
17620
17621 @<Set up unsuffixed macro call and |goto restart|@>=
17622
17623   p=mp_get_avail(mp); info(pre_head)=link(pre_head); link(pre_head)=p;
17624   info(p)=t; mp_macro_call(mp, value(q),pre_head,null);
17625   mp_get_x_next(mp); 
17626   goto RESTART;
17627 }
17628
17629 @ If the ``variable'' that turned out to be a suffixed macro no longer exists,
17630 we don't care, because we have reserved a pointer (|macro_ref|) to its
17631 token list.
17632
17633 @<Set up suffixed macro call and |goto restart|@>=
17634
17635   mp_back_input(mp); p=mp_get_avail(mp); q=link(post_head);
17636   info(pre_head)=link(pre_head); link(pre_head)=post_head;
17637   info(post_head)=q; link(post_head)=p; info(p)=link(q); link(q)=null;
17638   mp_macro_call(mp, macro_ref,pre_head,null); decr(ref_count(macro_ref));
17639   mp_get_x_next(mp); goto RESTART;
17640 }
17641
17642 @ Our remaining job is simply to make a copy of the value that has been
17643 found. Some cases are harder than others, but complexity arises solely
17644 because of the multiplicity of possible cases.
17645
17646 @<Declare the procedure called |make_exp_copy|@>=
17647 @<Declare subroutines needed by |make_exp_copy|@>;
17648 void mp_make_exp_copy (MP mp,pointer p) {
17649   pointer q,r,t; /* registers for list manipulation */
17650 RESTART: 
17651   mp->cur_type=type(p);
17652   switch (mp->cur_type) {
17653   case mp_vacuous: case mp_boolean_type: case mp_known:
17654     mp->cur_exp=value(p); break;
17655   case unknown_types:
17656     mp->cur_exp=mp_new_ring_entry(mp, p);
17657     break;
17658   case mp_string_type: 
17659     mp->cur_exp=value(p); add_str_ref(mp->cur_exp);
17660     break;
17661   case mp_picture_type:
17662     mp->cur_exp=value(p);add_edge_ref(mp->cur_exp);
17663     break;
17664   case mp_pen_type:
17665     mp->cur_exp=copy_pen(value(p));
17666     break; 
17667   case mp_path_type:
17668     mp->cur_exp=mp_copy_path(mp, value(p));
17669     break;
17670   case mp_transform_type: case mp_color_type: 
17671   case mp_cmykcolor_type: case mp_pair_type:
17672     @<Copy the big node |p|@>;
17673     break;
17674   case mp_dependent: case mp_proto_dependent:
17675     mp_encapsulate(mp, mp_copy_dep_list(mp, dep_list(p)));
17676     break;
17677   case mp_numeric_type: 
17678     new_indep(p); goto RESTART;
17679     break;
17680   case mp_independent: 
17681     q=mp_single_dependency(mp, p);
17682     if ( q==mp->dep_final ){ 
17683       mp->cur_type=mp_known; mp->cur_exp=0; mp_free_node(mp, q,value_node_size);
17684     } else { 
17685       mp->cur_type=mp_dependent; mp_encapsulate(mp, q);
17686     }
17687     break;
17688   default: 
17689     mp_confusion(mp, "copy");
17690 @:this can't happen copy}{\quad copy@>
17691     break;
17692   }
17693 }
17694
17695 @ The |encapsulate| subroutine assumes that |dep_final| is the
17696 tail of dependency list~|p|.
17697
17698 @<Declare subroutines needed by |make_exp_copy|@>=
17699 void mp_encapsulate (MP mp,pointer p) { 
17700   mp->cur_exp=mp_get_node(mp, value_node_size); type(mp->cur_exp)=mp->cur_type;
17701   name_type(mp->cur_exp)=mp_capsule; mp_new_dep(mp, mp->cur_exp,p);
17702 }
17703
17704 @ The most tedious case arises when the user refers to a
17705 \&{pair}, \&{color}, or \&{transform} variable; we must copy several fields,
17706 each of which can be |independent|, |dependent|, |mp_proto_dependent|,
17707 or |known|.
17708
17709 @<Copy the big node |p|@>=
17710
17711   if ( value(p)==null ) 
17712     mp_init_big_node(mp, p);
17713   t=mp_get_node(mp, value_node_size); name_type(t)=mp_capsule; type(t)=mp->cur_type;
17714   mp_init_big_node(mp, t);
17715   q=value(p)+mp->big_node_size[mp->cur_type]; 
17716   r=value(t)+mp->big_node_size[mp->cur_type];
17717   do {  
17718     q=q-2; r=r-2; mp_install(mp, r,q);
17719   } while (q!=value(p));
17720   mp->cur_exp=t;
17721 }
17722
17723 @ The |install| procedure copies a numeric field~|q| into field~|r| of
17724 a big node that will be part of a capsule.
17725
17726 @<Declare subroutines needed by |make_exp_copy|@>=
17727 void mp_install (MP mp,pointer r, pointer q) {
17728   pointer p; /* temporary register */
17729   if ( type(q)==mp_known ){ 
17730     value(r)=value(q); type(r)=mp_known;
17731   } else  if ( type(q)==mp_independent ) {
17732     p=mp_single_dependency(mp, q);
17733     if ( p==mp->dep_final ) {
17734       type(r)=mp_known; value(r)=0; mp_free_node(mp, p,value_node_size);
17735     } else  { 
17736       type(r)=mp_dependent; mp_new_dep(mp, r,p);
17737     }
17738   } else {
17739     type(r)=type(q); mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(q)));
17740   }
17741 }
17742
17743 @ Expressions of the form `\.{a[b,c]}' are converted into
17744 `\.{b+a*(c-b)}', without checking the types of \.b~or~\.c,
17745 provided that \.a is numeric.
17746
17747 @<Scan a mediation...@>=
17748
17749   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17750   if ( mp->cur_cmd!=comma ) {
17751     @<Put the left bracket and the expression back...@>;
17752     mp_unstash_cur_exp(mp, p);
17753   } else { 
17754     q=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17755     if ( mp->cur_cmd!=right_bracket ) {
17756       mp_missing_err(mp, "]");
17757 @.Missing `]'@>
17758       help3("I've scanned an expression of the form `a[b,c',")
17759       ("so a right bracket should have come next.")
17760       ("I shall pretend that one was there.");
17761       mp_back_error(mp);
17762     }
17763     r=mp_stash_cur_exp(mp); mp_make_exp_copy(mp, q);
17764     mp_do_binary(mp, r,minus); mp_do_binary(mp, p,times); 
17765     mp_do_binary(mp, q,plus); mp_get_x_next(mp);
17766   }
17767 }
17768
17769 @ Here is a comparatively simple routine that is used to scan the
17770 \&{suffix} parameters of a macro.
17771
17772 @<Declare the basic parsing subroutines@>=
17773 void mp_scan_suffix (MP mp) {
17774   pointer h,t; /* head and tail of the list being built */
17775   pointer p; /* temporary register */
17776   h=mp_get_avail(mp); t=h;
17777   while (1) { 
17778     if ( mp->cur_cmd==left_bracket ) {
17779       @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>;
17780     }
17781     if ( mp->cur_cmd==numeric_token ) {
17782       p=mp_new_num_tok(mp, mp->cur_mod);
17783     } else if ((mp->cur_cmd==tag_token)||(mp->cur_cmd==internal_quantity) ) {
17784        p=mp_get_avail(mp); info(p)=mp->cur_sym;
17785     } else {
17786       break;
17787     }
17788     link(t)=p; t=p; mp_get_x_next(mp);
17789   }
17790   mp->cur_exp=link(h); free_avail(h); mp->cur_type=mp_token_list;
17791 }
17792
17793 @ @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>=
17794
17795   mp_get_x_next(mp); mp_scan_expression(mp);
17796   if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17797   if ( mp->cur_cmd!=right_bracket ) {
17798      mp_missing_err(mp, "]");
17799 @.Missing `]'@>
17800     help3("I've seen a `[' and a subscript value, in a suffix,")
17801       ("so a right bracket should have come next.")
17802       ("I shall pretend that one was there.");
17803     mp_back_error(mp);
17804   }
17805   mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp;
17806 }
17807
17808 @* \[38] Parsing secondary and higher expressions.
17809
17810 After the intricacies of |scan_primary|\kern-1pt,
17811 the |scan_secondary| routine is
17812 refreshingly simple. It's not trivial, but the operations are relatively
17813 straightforward; the main difficulty is, again, that expressions and data
17814 structures might change drastically every time we call |get_x_next|, so a
17815 cautious approach is mandatory. For example, a macro defined by
17816 \&{primarydef} might have disappeared by the time its second argument has
17817 been scanned; we solve this by increasing the reference count of its token
17818 list, so that the macro can be called even after it has been clobbered.
17819
17820 @<Declare the basic parsing subroutines@>=
17821 void mp_scan_secondary (MP mp) {
17822   pointer p; /* for list manipulation */
17823   halfword c,d; /* operation codes or modifiers */
17824   pointer mac_name; /* token defined with \&{primarydef} */
17825 RESTART:
17826   if ((mp->cur_cmd<min_primary_command)||
17827       (mp->cur_cmd>max_primary_command) )
17828     mp_bad_exp(mp, "A secondary");
17829 @.A secondary expression...@>
17830   mp_scan_primary(mp);
17831 CONTINUE: 
17832   if ( mp->cur_cmd<=max_secondary_command )
17833     if ( mp->cur_cmd>=min_secondary_command ) {
17834       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17835       if ( d==secondary_primary_macro ) { 
17836         mac_name=mp->cur_sym; add_mac_ref(c);
17837      }
17838      mp_get_x_next(mp); mp_scan_primary(mp);
17839      if ( d!=secondary_primary_macro ) {
17840        mp_do_binary(mp, p,c);
17841      } else  { 
17842        mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17843        decr(ref_count(c)); mp_get_x_next(mp); 
17844        goto RESTART;
17845     }
17846     goto CONTINUE;
17847   }
17848 }
17849
17850 @ The following procedure calls a macro that has two parameters,
17851 |p| and |cur_exp|.
17852
17853 @c void mp_binary_mac (MP mp,pointer p, pointer c, pointer n) {
17854   pointer q,r; /* nodes in the parameter list */
17855   q=mp_get_avail(mp); r=mp_get_avail(mp); link(q)=r;
17856   info(q)=p; info(r)=mp_stash_cur_exp(mp);
17857   mp_macro_call(mp, c,q,n);
17858 }
17859
17860 @ The next procedure, |scan_tertiary|, is pretty much the same deal.
17861
17862 @<Declare the basic parsing subroutines@>=
17863 void mp_scan_tertiary (MP mp) {
17864   pointer p; /* for list manipulation */
17865   halfword c,d; /* operation codes or modifiers */
17866   pointer mac_name; /* token defined with \&{secondarydef} */
17867 RESTART:
17868   if ((mp->cur_cmd<min_primary_command)||
17869       (mp->cur_cmd>max_primary_command) )
17870     mp_bad_exp(mp, "A tertiary");
17871 @.A tertiary expression...@>
17872   mp_scan_secondary(mp);
17873 CONTINUE: 
17874   if ( mp->cur_cmd<=max_tertiary_command ) {
17875     if ( mp->cur_cmd>=min_tertiary_command ) {
17876       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17877       if ( d==tertiary_secondary_macro ) { 
17878         mac_name=mp->cur_sym; add_mac_ref(c);
17879       };
17880       mp_get_x_next(mp); mp_scan_secondary(mp);
17881       if ( d!=tertiary_secondary_macro ) {
17882         mp_do_binary(mp, p,c);
17883       } else { 
17884         mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17885         decr(ref_count(c)); mp_get_x_next(mp); 
17886         goto RESTART;
17887       }
17888       goto CONTINUE;
17889     }
17890   }
17891 }
17892
17893 @ Finally we reach the deepest level in our quartet of parsing routines.
17894 This one is much like the others; but it has an extra complication from
17895 paths, which materialize here.
17896
17897 @d continue_path 25 /* a label inside of |scan_expression| */
17898 @d finish_path 26 /* another */
17899
17900 @<Declare the basic parsing subroutines@>=
17901 void mp_scan_expression (MP mp) {
17902   pointer p,q,r,pp,qq; /* for list manipulation */
17903   halfword c,d; /* operation codes or modifiers */
17904   int my_var_flag; /* initial value of |var_flag| */
17905   pointer mac_name; /* token defined with \&{tertiarydef} */
17906   boolean cycle_hit; /* did a path expression just end with `\&{cycle}'? */
17907   scaled x,y; /* explicit coordinates or tension at a path join */
17908   int t; /* knot type following a path join */
17909   t=0; y=0; x=0;
17910   my_var_flag=mp->var_flag; mac_name=null;
17911 RESTART:
17912   if ((mp->cur_cmd<min_primary_command)||
17913       (mp->cur_cmd>max_primary_command) )
17914     mp_bad_exp(mp, "An");
17915 @.An expression...@>
17916   mp_scan_tertiary(mp);
17917 CONTINUE: 
17918   if ( mp->cur_cmd<=max_expression_command )
17919     if ( mp->cur_cmd>=min_expression_command ) {
17920       if ( (mp->cur_cmd!=equals)||(my_var_flag!=assignment) ) {
17921         p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17922         if ( d==expression_tertiary_macro ) {
17923           mac_name=mp->cur_sym; add_mac_ref(c);
17924         }
17925         if ( (d<ampersand)||((d==ampersand)&&
17926              ((type(p)==mp_pair_type)||(type(p)==mp_path_type))) ) {
17927           @<Scan a path construction operation;
17928             but |return| if |p| has the wrong type@>;
17929         } else { 
17930           mp_get_x_next(mp); mp_scan_tertiary(mp);
17931           if ( d!=expression_tertiary_macro ) {
17932             mp_do_binary(mp, p,c);
17933           } else  { 
17934             mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17935             decr(ref_count(c)); mp_get_x_next(mp); 
17936             goto RESTART;
17937           }
17938         }
17939         goto CONTINUE;
17940      }
17941   }
17942 }
17943
17944 @ The reader should review the data structure conventions for paths before
17945 hoping to understand the next part of this code.
17946
17947 @<Scan a path construction operation...@>=
17948
17949   cycle_hit=false;
17950   @<Convert the left operand, |p|, into a partial path ending at~|q|;
17951     but |return| if |p| doesn't have a suitable type@>;
17952 CONTINUE_PATH: 
17953   @<Determine the path join parameters;
17954     but |goto finish_path| if there's only a direction specifier@>;
17955   if ( mp->cur_cmd==cycle ) {
17956     @<Get ready to close a cycle@>;
17957   } else { 
17958     mp_scan_tertiary(mp);
17959     @<Convert the right operand, |cur_exp|,
17960       into a partial path from |pp| to~|qq|@>;
17961   }
17962   @<Join the partial paths and reset |p| and |q| to the head and tail
17963     of the result@>;
17964   if ( mp->cur_cmd>=min_expression_command )
17965     if ( mp->cur_cmd<=ampersand ) if ( ! cycle_hit ) goto CONTINUE_PATH;
17966 FINISH_PATH:
17967   @<Choose control points for the path and put the result into |cur_exp|@>;
17968 }
17969
17970 @ @<Convert the left operand, |p|, into a partial path ending at~|q|...@>=
17971
17972   mp_unstash_cur_exp(mp, p);
17973   if ( mp->cur_type==mp_pair_type ) p=mp_new_knot(mp);
17974   else if ( mp->cur_type==mp_path_type ) p=mp->cur_exp;
17975   else return;
17976   q=p;
17977   while ( link(q)!=p ) q=link(q);
17978   if ( left_type(p)!=mp_endpoint ) { /* open up a cycle */
17979     r=mp_copy_knot(mp, p); link(q)=r; q=r;
17980   }
17981   left_type(p)=mp_open; right_type(q)=mp_open;
17982 }
17983
17984 @ A pair of numeric values is changed into a knot node for a one-point path
17985 when \MP\ discovers that the pair is part of a path.
17986
17987 @c@<Declare the procedure called |known_pair|@>;
17988 pointer mp_new_knot (MP mp) { /* convert a pair to a knot with two endpoints */
17989   pointer q; /* the new node */
17990   q=mp_get_node(mp, knot_node_size); left_type(q)=mp_endpoint;
17991   right_type(q)=mp_endpoint; originator(q)=mp_metapost_user; link(q)=q;
17992   mp_known_pair(mp); x_coord(q)=mp->cur_x; y_coord(q)=mp->cur_y;
17993   return q;
17994 }
17995
17996 @ The |known_pair| subroutine sets |cur_x| and |cur_y| to the components
17997 of the current expression, assuming that the current expression is a
17998 pair of known numerics. Unknown components are zeroed, and the
17999 current expression is flushed.
18000
18001 @<Declare the procedure called |known_pair|@>=
18002 void mp_known_pair (MP mp) {
18003   pointer p; /* the pair node */
18004   if ( mp->cur_type!=mp_pair_type ) {
18005     exp_err("Undefined coordinates have been replaced by (0,0)");
18006 @.Undefined coordinates...@>
18007     help5("I need x and y numbers for this part of the path.")
18008       ("The value I found (see above) was no good;")
18009       ("so I'll try to keep going by using zero instead.")
18010       ("(Chapter 27 of The METAFONTbook explains that")
18011 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18012       ("you might want to type `I ??" "?' now.)");
18013     mp_put_get_flush_error(mp, 0); mp->cur_x=0; mp->cur_y=0;
18014   } else { 
18015     p=value(mp->cur_exp);
18016      @<Make sure that both |x| and |y| parts of |p| are known;
18017        copy them into |cur_x| and |cur_y|@>;
18018     mp_flush_cur_exp(mp, 0);
18019   }
18020 }
18021
18022 @ @<Make sure that both |x| and |y| parts of |p| are known...@>=
18023 if ( type(x_part_loc(p))==mp_known ) {
18024   mp->cur_x=value(x_part_loc(p));
18025 } else { 
18026   mp_disp_err(mp, x_part_loc(p),
18027     "Undefined x coordinate has been replaced by 0");
18028 @.Undefined coordinates...@>
18029   help5("I need a `known' x value for this part of the path.")
18030     ("The value I found (see above) was no good;")
18031     ("so I'll try to keep going by using zero instead.")
18032     ("(Chapter 27 of The METAFONTbook explains that")
18033 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18034     ("you might want to type `I ??" "?' now.)");
18035   mp_put_get_error(mp); mp_recycle_value(mp, x_part_loc(p)); mp->cur_x=0;
18036 }
18037 if ( type(y_part_loc(p))==mp_known ) {
18038   mp->cur_y=value(y_part_loc(p));
18039 } else { 
18040   mp_disp_err(mp, y_part_loc(p),
18041     "Undefined y coordinate has been replaced by 0");
18042   help5("I need a `known' y value for this part of the path.")
18043     ("The value I found (see above) was no good;")
18044     ("so I'll try to keep going by using zero instead.")
18045     ("(Chapter 27 of The METAFONTbook explains that")
18046     ("you might want to type `I ??" "?' now.)");
18047   mp_put_get_error(mp); mp_recycle_value(mp, y_part_loc(p)); mp->cur_y=0;
18048 }
18049
18050 @ At this point |cur_cmd| is either |ampersand|, |left_brace|, or |path_join|.
18051
18052 @<Determine the path join parameters...@>=
18053 if ( mp->cur_cmd==left_brace ) {
18054   @<Put the pre-join direction information into node |q|@>;
18055 }
18056 d=mp->cur_cmd;
18057 if ( d==path_join ) {
18058   @<Determine the tension and/or control points@>;
18059 } else if ( d!=ampersand ) {
18060   goto FINISH_PATH;
18061 }
18062 mp_get_x_next(mp);
18063 if ( mp->cur_cmd==left_brace ) {
18064   @<Put the post-join direction information into |x| and |t|@>;
18065 } else if ( right_type(q)!=mp_explicit ) {
18066   t=mp_open; x=0;
18067 }
18068
18069 @ The |scan_direction| subroutine looks at the directional information
18070 that is enclosed in braces, and also scans ahead to the following character.
18071 A type code is returned, either |open| (if the direction was $(0,0)$),
18072 or |curl| (if the direction was a curl of known value |cur_exp|), or
18073 |given| (if the direction is given by the |angle| value that now
18074 appears in |cur_exp|).
18075
18076 There's nothing difficult about this subroutine, but the program is rather
18077 lengthy because a variety of potential errors need to be nipped in the bud.
18078
18079 @c small_number mp_scan_direction (MP mp) {
18080   int t; /* the type of information found */
18081   scaled x; /* an |x| coordinate */
18082   mp_get_x_next(mp);
18083   if ( mp->cur_cmd==curl_command ) {
18084      @<Scan a curl specification@>;
18085   } else {
18086     @<Scan a given direction@>;
18087   }
18088   if ( mp->cur_cmd!=right_brace ) {
18089     mp_missing_err(mp, "}");
18090 @.Missing `\char`\}'@>
18091     help3("I've scanned a direction spec for part of a path,")
18092       ("so a right brace should have come next.")
18093       ("I shall pretend that one was there.");
18094     mp_back_error(mp);
18095   }
18096   mp_get_x_next(mp); 
18097   return t;
18098 }
18099
18100 @ @<Scan a curl specification@>=
18101 { mp_get_x_next(mp); mp_scan_expression(mp);
18102 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<0) ){ 
18103   exp_err("Improper curl has been replaced by 1");
18104 @.Improper curl@>
18105   help1("A curl must be a known, nonnegative number.");
18106   mp_put_get_flush_error(mp, unity);
18107 }
18108 t=mp_curl;
18109 }
18110
18111 @ @<Scan a given direction@>=
18112 { mp_scan_expression(mp);
18113   if ( mp->cur_type>mp_pair_type ) {
18114     @<Get given directions separated by commas@>;
18115   } else {
18116     mp_known_pair(mp);
18117   }
18118   if ( (mp->cur_x==0)&&(mp->cur_y==0) )  t=mp_open;
18119   else  { t=mp_given; mp->cur_exp=mp_n_arg(mp, mp->cur_x,mp->cur_y);}
18120 }
18121
18122 @ @<Get given directions separated by commas@>=
18123
18124   if ( mp->cur_type!=mp_known ) {
18125     exp_err("Undefined x coordinate has been replaced by 0");
18126 @.Undefined coordinates...@>
18127     help5("I need a `known' x value for this part of the path.")
18128       ("The value I found (see above) was no good;")
18129       ("so I'll try to keep going by using zero instead.")
18130       ("(Chapter 27 of The METAFONTbook explains that")
18131 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18132       ("you might want to type `I ??" "?' now.)");
18133     mp_put_get_flush_error(mp, 0);
18134   }
18135   x=mp->cur_exp;
18136   if ( mp->cur_cmd!=comma ) {
18137     mp_missing_err(mp, ",");
18138 @.Missing `,'@>
18139     help2("I've got the x coordinate of a path direction;")
18140       ("will look for the y coordinate next.");
18141     mp_back_error(mp);
18142   }
18143   mp_get_x_next(mp); mp_scan_expression(mp);
18144   if ( mp->cur_type!=mp_known ) {
18145      exp_err("Undefined y coordinate has been replaced by 0");
18146     help5("I need a `known' y value for this part of the path.")
18147       ("The value I found (see above) was no good;")
18148       ("so I'll try to keep going by using zero instead.")
18149       ("(Chapter 27 of The METAFONTbook explains that")
18150       ("you might want to type `I ??" "?' now.)");
18151     mp_put_get_flush_error(mp, 0);
18152   }
18153   mp->cur_y=mp->cur_exp; mp->cur_x=x;
18154 }
18155
18156 @ At this point |right_type(q)| is usually |open|, but it may have been
18157 set to some other value by a previous splicing operation. We must maintain
18158 the value of |right_type(q)| in unusual cases such as
18159 `\.{..z1\{z2\}\&\{z3\}z1\{0,0\}..}'.
18160
18161 @<Put the pre-join...@>=
18162
18163   t=mp_scan_direction(mp);
18164   if ( t!=mp_open ) {
18165     right_type(q)=t; right_given(q)=mp->cur_exp;
18166     if ( left_type(q)==mp_open ) {
18167       left_type(q)=t; left_given(q)=mp->cur_exp;
18168     } /* note that |left_given(q)=left_curl(q)| */
18169   }
18170 }
18171
18172 @ Since |left_tension| and |left_y| share the same position in knot nodes,
18173 and since |left_given| is similarly equivalent to |left_x|, we use
18174 |x| and |y| to hold the given direction and tension information when
18175 there are no explicit control points.
18176
18177 @<Put the post-join...@>=
18178
18179   t=mp_scan_direction(mp);
18180   if ( right_type(q)!=mp_explicit ) x=mp->cur_exp;
18181   else t=mp_explicit; /* the direction information is superfluous */
18182 }
18183
18184 @ @<Determine the tension and/or...@>=
18185
18186   mp_get_x_next(mp);
18187   if ( mp->cur_cmd==tension ) {
18188     @<Set explicit tensions@>;
18189   } else if ( mp->cur_cmd==controls ) {
18190     @<Set explicit control points@>;
18191   } else  { 
18192     right_tension(q)=unity; y=unity; mp_back_input(mp); /* default tension */
18193     goto DONE;
18194   };
18195   if ( mp->cur_cmd!=path_join ) {
18196      mp_missing_err(mp, "..");
18197 @.Missing `..'@>
18198     help1("A path join command should end with two dots.");
18199     mp_back_error(mp);
18200   }
18201 DONE:
18202   ;
18203 }
18204
18205 @ @<Set explicit tensions@>=
18206
18207   mp_get_x_next(mp); y=mp->cur_cmd;
18208   if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18209   mp_scan_primary(mp);
18210   @<Make sure that the current expression is a valid tension setting@>;
18211   if ( y==at_least ) negate(mp->cur_exp);
18212   right_tension(q)=mp->cur_exp;
18213   if ( mp->cur_cmd==and_command ) {
18214     mp_get_x_next(mp); y=mp->cur_cmd;
18215     if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18216     mp_scan_primary(mp);
18217     @<Make sure that the current expression is a valid tension setting@>;
18218     if ( y==at_least ) negate(mp->cur_exp);
18219   }
18220   y=mp->cur_exp;
18221 }
18222
18223 @ @d min_tension three_quarter_unit
18224
18225 @<Make sure that the current expression is a valid tension setting@>=
18226 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<min_tension) ) {
18227   exp_err("Improper tension has been set to 1");
18228 @.Improper tension@>
18229   help1("The expression above should have been a number >=3/4.");
18230   mp_put_get_flush_error(mp, unity);
18231 }
18232
18233 @ @<Set explicit control points@>=
18234
18235   right_type(q)=mp_explicit; t=mp_explicit; mp_get_x_next(mp); mp_scan_primary(mp);
18236   mp_known_pair(mp); right_x(q)=mp->cur_x; right_y(q)=mp->cur_y;
18237   if ( mp->cur_cmd!=and_command ) {
18238     x=right_x(q); y=right_y(q);
18239   } else { 
18240     mp_get_x_next(mp); mp_scan_primary(mp);
18241     mp_known_pair(mp); x=mp->cur_x; y=mp->cur_y;
18242   }
18243 }
18244
18245 @ @<Convert the right operand, |cur_exp|, into a partial path...@>=
18246
18247   if ( mp->cur_type!=mp_path_type ) pp=mp_new_knot(mp);
18248   else pp=mp->cur_exp;
18249   qq=pp;
18250   while ( link(qq)!=pp ) qq=link(qq);
18251   if ( left_type(pp)!=mp_endpoint ) { /* open up a cycle */
18252     r=mp_copy_knot(mp, pp); link(qq)=r; qq=r;
18253   }
18254   left_type(pp)=mp_open; right_type(qq)=mp_open;
18255 }
18256
18257 @ If a person tries to define an entire path by saying `\.{(x,y)\&cycle}',
18258 we silently change the specification to `\.{(x,y)..cycle}', since a cycle
18259 shouldn't have length zero.
18260
18261 @<Get ready to close a cycle@>=
18262
18263   cycle_hit=true; mp_get_x_next(mp); pp=p; qq=p;
18264   if ( d==ampersand ) if ( p==q ) {
18265     d=path_join; right_tension(q)=unity; y=unity;
18266   }
18267 }
18268
18269 @ @<Join the partial paths and reset |p| and |q|...@>=
18270
18271 if ( d==ampersand ) {
18272   if ( (x_coord(q)!=x_coord(pp))||(y_coord(q)!=y_coord(pp)) ) {
18273     print_err("Paths don't touch; `&' will be changed to `..'");
18274 @.Paths don't touch@>
18275     help3("When you join paths `p&q', the ending point of p")
18276       ("must be exactly equal to the starting point of q.")
18277       ("So I'm going to pretend that you said `p..q' instead.");
18278     mp_put_get_error(mp); d=path_join; right_tension(q)=unity; y=unity;
18279   }
18280 }
18281 @<Plug an opening in |right_type(pp)|, if possible@>;
18282 if ( d==ampersand ) {
18283   @<Splice independent paths together@>;
18284 } else  { 
18285   @<Plug an opening in |right_type(q)|, if possible@>;
18286   link(q)=pp; left_y(pp)=y;
18287   if ( t!=mp_open ) { left_x(pp)=x; left_type(pp)=t;  };
18288 }
18289 q=qq;
18290 }
18291
18292 @ @<Plug an opening in |right_type(q)|...@>=
18293 if ( right_type(q)==mp_open ) {
18294   if ( (left_type(q)==mp_curl)||(left_type(q)==mp_given) ) {
18295     right_type(q)=left_type(q); right_given(q)=left_given(q);
18296   }
18297 }
18298
18299 @ @<Plug an opening in |right_type(pp)|...@>=
18300 if ( right_type(pp)==mp_open ) {
18301   if ( (t==mp_curl)||(t==mp_given) ) {
18302     right_type(pp)=t; right_given(pp)=x;
18303   }
18304 }
18305
18306 @ @<Splice independent paths together@>=
18307
18308   if ( left_type(q)==mp_open ) if ( right_type(q)==mp_open ) {
18309     left_type(q)=mp_curl; left_curl(q)=unity;
18310   }
18311   if ( right_type(pp)==mp_open ) if ( t==mp_open ) {
18312     right_type(pp)=mp_curl; right_curl(pp)=unity;
18313   }
18314   right_type(q)=right_type(pp); link(q)=link(pp);
18315   right_x(q)=right_x(pp); right_y(q)=right_y(pp);
18316   mp_free_node(mp, pp,knot_node_size);
18317   if ( qq==pp ) qq=q;
18318 }
18319
18320 @ @<Choose control points for the path...@>=
18321 if ( cycle_hit ) { 
18322   if ( d==ampersand ) p=q;
18323 } else  { 
18324   left_type(p)=mp_endpoint;
18325   if ( right_type(p)==mp_open ) { 
18326     right_type(p)=mp_curl; right_curl(p)=unity;
18327   }
18328   right_type(q)=mp_endpoint;
18329   if ( left_type(q)==mp_open ) { 
18330     left_type(q)=mp_curl; left_curl(q)=unity;
18331   }
18332   link(q)=p;
18333 }
18334 mp_make_choices(mp, p);
18335 mp->cur_type=mp_path_type; mp->cur_exp=p
18336
18337 @ Finally, we sometimes need to scan an expression whose value is
18338 supposed to be either |true_code| or |false_code|.
18339
18340 @<Declare the basic parsing subroutines@>=
18341 void mp_get_boolean (MP mp) { 
18342   mp_get_x_next(mp); mp_scan_expression(mp);
18343   if ( mp->cur_type!=mp_boolean_type ) {
18344     exp_err("Undefined condition will be treated as `false'");
18345 @.Undefined condition...@>
18346     help2("The expression shown above should have had a definite")
18347       ("true-or-false value. I'm changing it to `false'.");
18348     mp_put_get_flush_error(mp, false_code); mp->cur_type=mp_boolean_type;
18349   }
18350 }
18351
18352 @* \[39] Doing the operations.
18353 The purpose of parsing is primarily to permit people to avoid piles of
18354 parentheses. But the real work is done after the structure of an expression
18355 has been recognized; that's when new expressions are generated. We
18356 turn now to the guts of \MP, which handles individual operators that
18357 have come through the parsing mechanism.
18358
18359 We'll start with the easy ones that take no operands, then work our way
18360 up to operators with one and ultimately two arguments. In other words,
18361 we will write the three procedures |do_nullary|, |do_unary|, and |do_binary|
18362 that are invoked periodically by the expression scanners.
18363
18364 First let's make sure that all of the primitive operators are in the
18365 hash table. Although |scan_primary| and its relatives made use of the
18366 \\{cmd} code for these operators, the \\{do} routines base everything
18367 on the \\{mod} code. For example, |do_binary| doesn't care whether the
18368 operation it performs is a |primary_binary| or |secondary_binary|, etc.
18369
18370 @<Put each...@>=
18371 mp_primitive(mp, "true",nullary,true_code);
18372 @:true_}{\&{true} primitive@>
18373 mp_primitive(mp, "false",nullary,false_code);
18374 @:false_}{\&{false} primitive@>
18375 mp_primitive(mp, "nullpicture",nullary,null_picture_code);
18376 @:null_picture_}{\&{nullpicture} primitive@>
18377 mp_primitive(mp, "nullpen",nullary,null_pen_code);
18378 @:null_pen_}{\&{nullpen} primitive@>
18379 mp_primitive(mp, "jobname",nullary,job_name_op);
18380 @:job_name_}{\&{jobname} primitive@>
18381 mp_primitive(mp, "readstring",nullary,read_string_op);
18382 @:read_string_}{\&{readstring} primitive@>
18383 mp_primitive(mp, "pencircle",nullary,pen_circle);
18384 @:pen_circle_}{\&{pencircle} primitive@>
18385 mp_primitive(mp, "normaldeviate",nullary,normal_deviate);
18386 @:normal_deviate_}{\&{normaldeviate} primitive@>
18387 mp_primitive(mp, "readfrom",unary,read_from_op);
18388 @:read_from_}{\&{readfrom} primitive@>
18389 mp_primitive(mp, "closefrom",unary,close_from_op);
18390 @:close_from_}{\&{closefrom} primitive@>
18391 mp_primitive(mp, "odd",unary,odd_op);
18392 @:odd_}{\&{odd} primitive@>
18393 mp_primitive(mp, "known",unary,known_op);
18394 @:known_}{\&{known} primitive@>
18395 mp_primitive(mp, "unknown",unary,unknown_op);
18396 @:unknown_}{\&{unknown} primitive@>
18397 mp_primitive(mp, "not",unary,not_op);
18398 @:not_}{\&{not} primitive@>
18399 mp_primitive(mp, "decimal",unary,decimal);
18400 @:decimal_}{\&{decimal} primitive@>
18401 mp_primitive(mp, "reverse",unary,reverse);
18402 @:reverse_}{\&{reverse} primitive@>
18403 mp_primitive(mp, "makepath",unary,make_path_op);
18404 @:make_path_}{\&{makepath} primitive@>
18405 mp_primitive(mp, "makepen",unary,make_pen_op);
18406 @:make_pen_}{\&{makepen} primitive@>
18407 mp_primitive(mp, "oct",unary,oct_op);
18408 @:oct_}{\&{oct} primitive@>
18409 mp_primitive(mp, "hex",unary,hex_op);
18410 @:hex_}{\&{hex} primitive@>
18411 mp_primitive(mp, "ASCII",unary,ASCII_op);
18412 @:ASCII_}{\&{ASCII} primitive@>
18413 mp_primitive(mp, "char",unary,char_op);
18414 @:char_}{\&{char} primitive@>
18415 mp_primitive(mp, "length",unary,length_op);
18416 @:length_}{\&{length} primitive@>
18417 mp_primitive(mp, "turningnumber",unary,turning_op);
18418 @:turning_number_}{\&{turningnumber} primitive@>
18419 mp_primitive(mp, "xpart",unary,x_part);
18420 @:x_part_}{\&{xpart} primitive@>
18421 mp_primitive(mp, "ypart",unary,y_part);
18422 @:y_part_}{\&{ypart} primitive@>
18423 mp_primitive(mp, "xxpart",unary,xx_part);
18424 @:xx_part_}{\&{xxpart} primitive@>
18425 mp_primitive(mp, "xypart",unary,xy_part);
18426 @:xy_part_}{\&{xypart} primitive@>
18427 mp_primitive(mp, "yxpart",unary,yx_part);
18428 @:yx_part_}{\&{yxpart} primitive@>
18429 mp_primitive(mp, "yypart",unary,yy_part);
18430 @:yy_part_}{\&{yypart} primitive@>
18431 mp_primitive(mp, "redpart",unary,red_part);
18432 @:red_part_}{\&{redpart} primitive@>
18433 mp_primitive(mp, "greenpart",unary,green_part);
18434 @:green_part_}{\&{greenpart} primitive@>
18435 mp_primitive(mp, "bluepart",unary,blue_part);
18436 @:blue_part_}{\&{bluepart} primitive@>
18437 mp_primitive(mp, "cyanpart",unary,cyan_part);
18438 @:cyan_part_}{\&{cyanpart} primitive@>
18439 mp_primitive(mp, "magentapart",unary,magenta_part);
18440 @:magenta_part_}{\&{magentapart} primitive@>
18441 mp_primitive(mp, "yellowpart",unary,yellow_part);
18442 @:yellow_part_}{\&{yellowpart} primitive@>
18443 mp_primitive(mp, "blackpart",unary,black_part);
18444 @:black_part_}{\&{blackpart} primitive@>
18445 mp_primitive(mp, "greypart",unary,grey_part);
18446 @:grey_part_}{\&{greypart} primitive@>
18447 mp_primitive(mp, "colormodel",unary,color_model_part);
18448 @:color_model_part_}{\&{colormodel} primitive@>
18449 mp_primitive(mp, "fontpart",unary,font_part);
18450 @:font_part_}{\&{fontpart} primitive@>
18451 mp_primitive(mp, "textpart",unary,text_part);
18452 @:text_part_}{\&{textpart} primitive@>
18453 mp_primitive(mp, "pathpart",unary,path_part);
18454 @:path_part_}{\&{pathpart} primitive@>
18455 mp_primitive(mp, "penpart",unary,pen_part);
18456 @:pen_part_}{\&{penpart} primitive@>
18457 mp_primitive(mp, "dashpart",unary,dash_part);
18458 @:dash_part_}{\&{dashpart} primitive@>
18459 mp_primitive(mp, "sqrt",unary,sqrt_op);
18460 @:sqrt_}{\&{sqrt} primitive@>
18461 mp_primitive(mp, "mexp",unary,m_exp_op);
18462 @:m_exp_}{\&{mexp} primitive@>
18463 mp_primitive(mp, "mlog",unary,m_log_op);
18464 @:m_log_}{\&{mlog} primitive@>
18465 mp_primitive(mp, "sind",unary,sin_d_op);
18466 @:sin_d_}{\&{sind} primitive@>
18467 mp_primitive(mp, "cosd",unary,cos_d_op);
18468 @:cos_d_}{\&{cosd} primitive@>
18469 mp_primitive(mp, "floor",unary,floor_op);
18470 @:floor_}{\&{floor} primitive@>
18471 mp_primitive(mp, "uniformdeviate",unary,uniform_deviate);
18472 @:uniform_deviate_}{\&{uniformdeviate} primitive@>
18473 mp_primitive(mp, "charexists",unary,char_exists_op);
18474 @:char_exists_}{\&{charexists} primitive@>
18475 mp_primitive(mp, "fontsize",unary,font_size);
18476 @:font_size_}{\&{fontsize} primitive@>
18477 mp_primitive(mp, "llcorner",unary,ll_corner_op);
18478 @:ll_corner_}{\&{llcorner} primitive@>
18479 mp_primitive(mp, "lrcorner",unary,lr_corner_op);
18480 @:lr_corner_}{\&{lrcorner} primitive@>
18481 mp_primitive(mp, "ulcorner",unary,ul_corner_op);
18482 @:ul_corner_}{\&{ulcorner} primitive@>
18483 mp_primitive(mp, "urcorner",unary,ur_corner_op);
18484 @:ur_corner_}{\&{urcorner} primitive@>
18485 mp_primitive(mp, "arclength",unary,arc_length);
18486 @:arc_length_}{\&{arclength} primitive@>
18487 mp_primitive(mp, "angle",unary,angle_op);
18488 @:angle_}{\&{angle} primitive@>
18489 mp_primitive(mp, "cycle",cycle,cycle_op);
18490 @:cycle_}{\&{cycle} primitive@>
18491 mp_primitive(mp, "stroked",unary,stroked_op);
18492 @:stroked_}{\&{stroked} primitive@>
18493 mp_primitive(mp, "filled",unary,filled_op);
18494 @:filled_}{\&{filled} primitive@>
18495 mp_primitive(mp, "textual",unary,textual_op);
18496 @:textual_}{\&{textual} primitive@>
18497 mp_primitive(mp, "clipped",unary,clipped_op);
18498 @:clipped_}{\&{clipped} primitive@>
18499 mp_primitive(mp, "bounded",unary,bounded_op);
18500 @:bounded_}{\&{bounded} primitive@>
18501 mp_primitive(mp, "+",plus_or_minus,plus);
18502 @:+ }{\.{+} primitive@>
18503 mp_primitive(mp, "-",plus_or_minus,minus);
18504 @:- }{\.{-} primitive@>
18505 mp_primitive(mp, "*",secondary_binary,times);
18506 @:* }{\.{*} primitive@>
18507 mp_primitive(mp, "/",slash,over); mp->eqtb[frozen_slash]=mp->eqtb[mp->cur_sym];
18508 @:/ }{\.{/} primitive@>
18509 mp_primitive(mp, "++",tertiary_binary,pythag_add);
18510 @:++_}{\.{++} primitive@>
18511 mp_primitive(mp, "+-+",tertiary_binary,pythag_sub);
18512 @:+-+_}{\.{+-+} primitive@>
18513 mp_primitive(mp, "or",tertiary_binary,or_op);
18514 @:or_}{\&{or} primitive@>
18515 mp_primitive(mp, "and",and_command,and_op);
18516 @:and_}{\&{and} primitive@>
18517 mp_primitive(mp, "<",expression_binary,less_than);
18518 @:< }{\.{<} primitive@>
18519 mp_primitive(mp, "<=",expression_binary,less_or_equal);
18520 @:<=_}{\.{<=} primitive@>
18521 mp_primitive(mp, ">",expression_binary,greater_than);
18522 @:> }{\.{>} primitive@>
18523 mp_primitive(mp, ">=",expression_binary,greater_or_equal);
18524 @:>=_}{\.{>=} primitive@>
18525 mp_primitive(mp, "=",equals,equal_to);
18526 @:= }{\.{=} primitive@>
18527 mp_primitive(mp, "<>",expression_binary,unequal_to);
18528 @:<>_}{\.{<>} primitive@>
18529 mp_primitive(mp, "substring",primary_binary,substring_of);
18530 @:substring_}{\&{substring} primitive@>
18531 mp_primitive(mp, "subpath",primary_binary,subpath_of);
18532 @:subpath_}{\&{subpath} primitive@>
18533 mp_primitive(mp, "directiontime",primary_binary,direction_time_of);
18534 @:direction_time_}{\&{directiontime} primitive@>
18535 mp_primitive(mp, "point",primary_binary,point_of);
18536 @:point_}{\&{point} primitive@>
18537 mp_primitive(mp, "precontrol",primary_binary,precontrol_of);
18538 @:precontrol_}{\&{precontrol} primitive@>
18539 mp_primitive(mp, "postcontrol",primary_binary,postcontrol_of);
18540 @:postcontrol_}{\&{postcontrol} primitive@>
18541 mp_primitive(mp, "penoffset",primary_binary,pen_offset_of);
18542 @:pen_offset_}{\&{penoffset} primitive@>
18543 mp_primitive(mp, "arctime",primary_binary,arc_time_of);
18544 @:arc_time_of_}{\&{arctime} primitive@>
18545 mp_primitive(mp, "mpversion",nullary,mp_version);
18546 @:mp_verison_}{\&{mpversion} primitive@>
18547 mp_primitive(mp, "&",ampersand,concatenate);
18548 @:!!!}{\.{\&} primitive@>
18549 mp_primitive(mp, "rotated",secondary_binary,rotated_by);
18550 @:rotated_}{\&{rotated} primitive@>
18551 mp_primitive(mp, "slanted",secondary_binary,slanted_by);
18552 @:slanted_}{\&{slanted} primitive@>
18553 mp_primitive(mp, "scaled",secondary_binary,scaled_by);
18554 @:scaled_}{\&{scaled} primitive@>
18555 mp_primitive(mp, "shifted",secondary_binary,shifted_by);
18556 @:shifted_}{\&{shifted} primitive@>
18557 mp_primitive(mp, "transformed",secondary_binary,transformed_by);
18558 @:transformed_}{\&{transformed} primitive@>
18559 mp_primitive(mp, "xscaled",secondary_binary,x_scaled);
18560 @:x_scaled_}{\&{xscaled} primitive@>
18561 mp_primitive(mp, "yscaled",secondary_binary,y_scaled);
18562 @:y_scaled_}{\&{yscaled} primitive@>
18563 mp_primitive(mp, "zscaled",secondary_binary,z_scaled);
18564 @:z_scaled_}{\&{zscaled} primitive@>
18565 mp_primitive(mp, "infont",secondary_binary,in_font);
18566 @:in_font_}{\&{infont} primitive@>
18567 mp_primitive(mp, "intersectiontimes",tertiary_binary,intersect);
18568 @:intersection_times_}{\&{intersectiontimes} primitive@>
18569 mp_primitive(mp, "envelope",primary_binary,envelope_of);
18570 @:envelope_}{\&{envelope} primitive@>
18571
18572 @ @<Cases of |print_cmd...@>=
18573 case nullary:
18574 case unary:
18575 case primary_binary:
18576 case secondary_binary:
18577 case tertiary_binary:
18578 case expression_binary:
18579 case cycle:
18580 case plus_or_minus:
18581 case slash:
18582 case ampersand:
18583 case equals:
18584 case and_command:
18585   mp_print_op(mp, m);
18586   break;
18587
18588 @ OK, let's look at the simplest \\{do} procedure first.
18589
18590 @c @<Declare nullary action procedure@>;
18591 void mp_do_nullary (MP mp,quarterword c) { 
18592   check_arith;
18593   if ( mp->internal[mp_tracing_commands]>two )
18594     mp_show_cmd_mod(mp, nullary,c);
18595   switch (c) {
18596   case true_code: case false_code: 
18597     mp->cur_type=mp_boolean_type; mp->cur_exp=c;
18598     break;
18599   case null_picture_code: 
18600     mp->cur_type=mp_picture_type;
18601     mp->cur_exp=mp_get_node(mp, edge_header_size); 
18602     mp_init_edges(mp, mp->cur_exp);
18603     break;
18604   case null_pen_code: 
18605     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, 0);
18606     break;
18607   case normal_deviate: 
18608     mp->cur_type=mp_known; mp->cur_exp=mp_norm_rand(mp);
18609     break;
18610   case pen_circle: 
18611     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, unity);
18612     break;
18613   case job_name_op:  
18614     if ( mp->job_name==NULL ) mp_open_log_file(mp);
18615     mp->cur_type=mp_string_type; mp->cur_exp=rts(mp->job_name);
18616     break;
18617   case mp_version: 
18618     mp->cur_type=mp_string_type; 
18619     mp->cur_exp=intern(metapost_version) ;
18620     break;
18621   case read_string_op:
18622     @<Read a string from the terminal@>;
18623     break;
18624   } /* there are no other cases */
18625   check_arith;
18626 }
18627
18628 @ @<Read a string...@>=
18629
18630   if ( mp->interaction<=mp_nonstop_mode )
18631     mp_fatal_error(mp, "*** (cannot readstring in nonstop modes)");
18632   mp_begin_file_reading(mp); name=is_read;
18633   limit=start; prompt_input("");
18634   mp_finish_read(mp);
18635 }
18636
18637 @ @<Declare nullary action procedure@>=
18638 void mp_finish_read (MP mp) { /* copy |buffer| line to |cur_exp| */
18639   size_t k;
18640   str_room((int)mp->last-start);
18641   for (k=start;k<=mp->last-1;k++) {
18642    append_char(mp->buffer[k]);
18643   }
18644   mp_end_file_reading(mp); mp->cur_type=mp_string_type; 
18645   mp->cur_exp=mp_make_string(mp);
18646 }
18647
18648 @ Things get a bit more interesting when there's an operand. The
18649 operand to |do_unary| appears in |cur_type| and |cur_exp|.
18650
18651 @c @<Declare unary action procedures@>;
18652 void mp_do_unary (MP mp,quarterword c) {
18653   pointer p,q,r; /* for list manipulation */
18654   integer x; /* a temporary register */
18655   check_arith;
18656   if ( mp->internal[mp_tracing_commands]>two )
18657     @<Trace the current unary operation@>;
18658   switch (c) {
18659   case plus:
18660     if ( mp->cur_type<mp_color_type ) mp_bad_unary(mp, plus);
18661     break;
18662   case minus:
18663     @<Negate the current expression@>;
18664     break;
18665   @<Additional cases of unary operators@>;
18666   } /* there are no other cases */
18667   check_arith;
18668 };
18669
18670 @ The |nice_pair| function returns |true| if both components of a pair
18671 are known.
18672
18673 @<Declare unary action procedures@>=
18674 boolean mp_nice_pair (MP mp,integer p, quarterword t) { 
18675   if ( t==mp_pair_type ) {
18676     p=value(p);
18677     if ( type(x_part_loc(p))==mp_known )
18678       if ( type(y_part_loc(p))==mp_known )
18679         return true;
18680   }
18681   return false;
18682 }
18683
18684 @ The |nice_color_or_pair| function is analogous except that it also accepts
18685 fully known colors.
18686
18687 @<Declare unary action procedures@>=
18688 boolean mp_nice_color_or_pair (MP mp,integer p, quarterword t) {
18689   pointer q,r; /* for scanning the big node */
18690   if ( (t!=mp_pair_type)&&(t!=mp_color_type)&&(t!=mp_cmykcolor_type) ) {
18691     return false;
18692   } else { 
18693     q=value(p);
18694     r=q+mp->big_node_size[type(p)];
18695     do {  
18696       r=r-2;
18697       if ( type(r)!=mp_known )
18698         return false;
18699     } while (r!=q);
18700     return true;
18701   }
18702 }
18703
18704 @ @<Declare unary action...@>=
18705 void mp_print_known_or_unknown_type (MP mp,small_number t, integer v) { 
18706   mp_print_char(mp, '(');
18707   if ( t>mp_known ) mp_print(mp, "unknown numeric");
18708   else { if ( (t==mp_pair_type)||(t==mp_color_type)||(t==mp_cmykcolor_type) )
18709     if ( ! mp_nice_color_or_pair(mp, v,t) ) mp_print(mp, "unknown ");
18710     mp_print_type(mp, t);
18711   }
18712   mp_print_char(mp, ')');
18713 }
18714
18715 @ @<Declare unary action...@>=
18716 void mp_bad_unary (MP mp,quarterword c) { 
18717   exp_err("Not implemented: "); mp_print_op(mp, c);
18718 @.Not implemented...@>
18719   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
18720   help3("I'm afraid I don't know how to apply that operation to that")
18721     ("particular type. Continue, and I'll simply return the")
18722     ("argument (shown above) as the result of the operation.");
18723   mp_put_get_error(mp);
18724 }
18725
18726 @ @<Trace the current unary operation@>=
18727
18728   mp_begin_diagnostic(mp); mp_print_nl(mp, "{"); 
18729   mp_print_op(mp, c); mp_print_char(mp, '(');
18730   mp_print_exp(mp, null,0); /* show the operand, but not verbosely */
18731   mp_print(mp, ")}"); mp_end_diagnostic(mp, false);
18732 }
18733
18734 @ Negation is easy except when the current expression
18735 is of type |independent|, or when it is a pair with one or more
18736 |independent| components.
18737
18738 It is tempting to argue that the negative of an independent variable
18739 is an independent variable, hence we don't have to do anything when
18740 negating it. The fallacy is that other dependent variables pointing
18741 to the current expression must change the sign of their
18742 coefficients if we make no change to the current expression.
18743
18744 Instead, we work around the problem by copying the current expression
18745 and recycling it afterwards (cf.~the |stash_in| routine).
18746
18747 @<Negate the current expression@>=
18748 switch (mp->cur_type) {
18749 case mp_color_type:
18750 case mp_cmykcolor_type:
18751 case mp_pair_type:
18752 case mp_independent: 
18753   q=mp->cur_exp; mp_make_exp_copy(mp, q);
18754   if ( mp->cur_type==mp_dependent ) {
18755     mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18756   } else if ( mp->cur_type<=mp_pair_type ) { /* |mp_color_type| or |mp_pair_type| */
18757     p=value(mp->cur_exp);
18758     r=p+mp->big_node_size[mp->cur_type];
18759     do {  
18760       r=r-2;
18761       if ( type(r)==mp_known ) negate(value(r));
18762       else mp_negate_dep_list(mp, dep_list(r));
18763     } while (r!=p);
18764   } /* if |cur_type=mp_known| then |cur_exp=0| */
18765   mp_recycle_value(mp, q); mp_free_node(mp, q,value_node_size);
18766   break;
18767 case mp_dependent:
18768 case mp_proto_dependent:
18769   mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18770   break;
18771 case mp_known:
18772   negate(mp->cur_exp);
18773   break;
18774 default:
18775   mp_bad_unary(mp, minus);
18776   break;
18777 }
18778
18779 @ @<Declare unary action...@>=
18780 void mp_negate_dep_list (MP mp,pointer p) { 
18781   while (1) { 
18782     negate(value(p));
18783     if ( info(p)==null ) return;
18784     p=link(p);
18785   }
18786 }
18787
18788 @ @<Additional cases of unary operators@>=
18789 case not_op: 
18790   if ( mp->cur_type!=mp_boolean_type ) mp_bad_unary(mp, not_op);
18791   else mp->cur_exp=true_code+false_code-mp->cur_exp;
18792   break;
18793
18794 @ @d three_sixty_units 23592960 /* that's |360*unity| */
18795 @d boolean_reset(A) if ( (A) ) mp->cur_exp=true_code; else mp->cur_exp=false_code
18796
18797 @<Additional cases of unary operators@>=
18798 case sqrt_op:
18799 case m_exp_op:
18800 case m_log_op:
18801 case sin_d_op:
18802 case cos_d_op:
18803 case floor_op:
18804 case  uniform_deviate:
18805 case odd_op:
18806 case char_exists_op:
18807   if ( mp->cur_type!=mp_known ) {
18808     mp_bad_unary(mp, c);
18809   } else {
18810     switch (c) {
18811     case sqrt_op:mp->cur_exp=mp_square_rt(mp, mp->cur_exp);break;
18812     case m_exp_op:mp->cur_exp=mp_m_exp(mp, mp->cur_exp);break;
18813     case m_log_op:mp->cur_exp=mp_m_log(mp, mp->cur_exp);break;
18814     case sin_d_op:
18815     case cos_d_op:
18816       mp_n_sin_cos(mp, (mp->cur_exp % three_sixty_units)*16);
18817       if ( c==sin_d_op ) mp->cur_exp=mp_round_fraction(mp, mp->n_sin);
18818       else mp->cur_exp=mp_round_fraction(mp, mp->n_cos);
18819       break;
18820     case floor_op:mp->cur_exp=mp_floor_scaled(mp, mp->cur_exp);break;
18821     case uniform_deviate:mp->cur_exp=mp_unif_rand(mp, mp->cur_exp);break;
18822     case odd_op: 
18823       boolean_reset(odd(mp_round_unscaled(mp, mp->cur_exp)));
18824       mp->cur_type=mp_boolean_type;
18825       break;
18826     case char_exists_op:
18827       @<Determine if a character has been shipped out@>;
18828       break;
18829     } /* there are no other cases */
18830   }
18831   break;
18832
18833 @ @<Additional cases of unary operators@>=
18834 case angle_op:
18835   if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) ) {
18836     p=value(mp->cur_exp);
18837     x=mp_n_arg(mp, value(x_part_loc(p)),value(y_part_loc(p)));
18838     if ( x>=0 ) mp_flush_cur_exp(mp, (x+8)/ 16);
18839     else mp_flush_cur_exp(mp, -((-x+8)/ 16));
18840   } else {
18841     mp_bad_unary(mp, angle_op);
18842   }
18843   break;
18844
18845 @ If the current expression is a pair, but the context wants it to
18846 be a path, we call |pair_to_path|.
18847
18848 @<Declare unary action...@>=
18849 void mp_pair_to_path (MP mp) { 
18850   mp->cur_exp=mp_new_knot(mp); 
18851   mp->cur_type=mp_path_type;
18852 };
18853
18854 @ @<Additional cases of unary operators@>=
18855 case x_part:
18856 case y_part:
18857   if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_transform_type) )
18858     mp_take_part(mp, c);
18859   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18860   else mp_bad_unary(mp, c);
18861   break;
18862 case xx_part:
18863 case xy_part:
18864 case yx_part:
18865 case yy_part: 
18866   if ( mp->cur_type==mp_transform_type ) mp_take_part(mp, c);
18867   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18868   else mp_bad_unary(mp, c);
18869   break;
18870 case red_part:
18871 case green_part:
18872 case blue_part: 
18873   if ( mp->cur_type==mp_color_type ) mp_take_part(mp, c);
18874   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18875   else mp_bad_unary(mp, c);
18876   break;
18877 case cyan_part:
18878 case magenta_part:
18879 case yellow_part:
18880 case black_part: 
18881   if ( mp->cur_type==mp_cmykcolor_type) mp_take_part(mp, c); 
18882   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18883   else mp_bad_unary(mp, c);
18884   break;
18885 case grey_part: 
18886   if ( mp->cur_type==mp_known ) mp->cur_exp=value(c);
18887   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18888   else mp_bad_unary(mp, c);
18889   break;
18890 case color_model_part: 
18891   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18892   else mp_bad_unary(mp, c);
18893   break;
18894
18895 @ In the following procedure, |cur_exp| points to a capsule, which points to
18896 a big node. We want to delete all but one part of the big node.
18897
18898 @<Declare unary action...@>=
18899 void mp_take_part (MP mp,quarterword c) {
18900   pointer p; /* the big node */
18901   p=value(mp->cur_exp); value(temp_val)=p; type(temp_val)=mp->cur_type;
18902   link(p)=temp_val; mp_free_node(mp, mp->cur_exp,value_node_size);
18903   mp_make_exp_copy(mp, p+mp->sector_offset[c+mp_x_part_sector-x_part]);
18904   mp_recycle_value(mp, temp_val);
18905 }
18906
18907 @ @<Initialize table entries...@>=
18908 name_type(temp_val)=mp_capsule;
18909
18910 @ @<Additional cases of unary operators@>=
18911 case font_part:
18912 case text_part:
18913 case path_part:
18914 case pen_part:
18915 case dash_part:
18916   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18917   else mp_bad_unary(mp, c);
18918   break;
18919
18920 @ @<Declarations@>=
18921 void mp_scale_edges (MP mp);
18922
18923 @ @<Declare unary action...@>=
18924 void mp_take_pict_part (MP mp,quarterword c) {
18925   pointer p; /* first graphical object in |cur_exp| */
18926   p=link(dummy_loc(mp->cur_exp));
18927   if ( p!=null ) {
18928     switch (c) {
18929     case x_part: case y_part: case xx_part:
18930     case xy_part: case yx_part: case yy_part:
18931       if ( type(p)==mp_text_code ) mp_flush_cur_exp(mp, text_trans_part(p+c));
18932       else goto NOT_FOUND;
18933       break;
18934     case red_part: case green_part: case blue_part:
18935       if ( has_color(p) ) mp_flush_cur_exp(mp, obj_color_part(p+c));
18936       else goto NOT_FOUND;
18937       break;
18938     case cyan_part: case magenta_part: case yellow_part:
18939     case black_part:
18940       if ( has_color(p) ) {
18941         if ( color_model(p)==mp_uninitialized_model )
18942           mp_flush_cur_exp(mp, unity);
18943         else
18944           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-cyan_part)));
18945       } else goto NOT_FOUND;
18946       break;
18947     case grey_part:
18948       if ( has_color(p) )
18949           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-grey_part)));
18950       else goto NOT_FOUND;
18951       break;
18952     case color_model_part:
18953       if ( has_color(p) ) {
18954         if ( color_model(p)==mp_uninitialized_model )
18955           mp_flush_cur_exp(mp, mp->internal[mp_default_color_model]);
18956         else
18957           mp_flush_cur_exp(mp, color_model(p)*unity);
18958       } else goto NOT_FOUND;
18959       break;
18960     @<Handle other cases in |take_pict_part| or |goto not_found|@>;
18961     } /* all cases have been enumerated */
18962     return;
18963   };
18964 NOT_FOUND:
18965   @<Convert the current expression to a null value appropriate
18966     for |c|@>;
18967 }
18968
18969 @ @<Handle other cases in |take_pict_part| or |goto not_found|@>=
18970 case text_part: 
18971   if ( type(p)!=mp_text_code ) goto NOT_FOUND;
18972   else { 
18973     mp_flush_cur_exp(mp, text_p(p));
18974     add_str_ref(mp->cur_exp);
18975     mp->cur_type=mp_string_type;
18976     };
18977   break;
18978 case font_part: 
18979   if ( type(p)!=mp_text_code ) goto NOT_FOUND;
18980   else { 
18981     mp_flush_cur_exp(mp, rts(mp->font_name[font_n(p)])); 
18982     add_str_ref(mp->cur_exp);
18983     mp->cur_type=mp_string_type;
18984   };
18985   break;
18986 case path_part:
18987   if ( type(p)==mp_text_code ) goto NOT_FOUND;
18988   else if ( is_stop(p) ) mp_confusion(mp, "pict");
18989 @:this can't happen pict}{\quad pict@>
18990   else { 
18991     mp_flush_cur_exp(mp, mp_copy_path(mp, path_p(p)));
18992     mp->cur_type=mp_path_type;
18993   }
18994   break;
18995 case pen_part: 
18996   if ( ! has_pen(p) ) goto NOT_FOUND;
18997   else {
18998     if ( pen_p(p)==null ) goto NOT_FOUND;
18999     else { mp_flush_cur_exp(mp, copy_pen(pen_p(p)));
19000       mp->cur_type=mp_pen_type;
19001     };
19002   }
19003   break;
19004 case dash_part: 
19005   if ( type(p)!=mp_stroked_code ) goto NOT_FOUND;
19006   else { if ( dash_p(p)==null ) goto NOT_FOUND;
19007     else { add_edge_ref(dash_p(p));
19008     mp->se_sf=dash_scale(p);
19009     mp->se_pic=dash_p(p);
19010     mp_scale_edges(mp);
19011     mp_flush_cur_exp(mp, mp->se_pic);
19012     mp->cur_type=mp_picture_type;
19013     };
19014   }
19015   break;
19016
19017 @ Since |scale_edges| had to be declared |forward|, it had to be declared as a
19018 parameterless procedure even though it really takes two arguments and updates
19019 one of them.  Hence the following globals are needed.
19020
19021 @<Global...@>=
19022 pointer se_pic;  /* edge header used and updated by |scale_edges| */
19023 scaled se_sf;  /* the scale factor argument to |scale_edges| */
19024
19025 @ @<Convert the current expression to a null value appropriate...@>=
19026 switch (c) {
19027 case text_part: case font_part: 
19028   mp_flush_cur_exp(mp, rts(""));
19029   mp->cur_type=mp_string_type;
19030   break;
19031 case path_part: 
19032   mp_flush_cur_exp(mp, mp_get_node(mp, knot_node_size));
19033   left_type(mp->cur_exp)=mp_endpoint;
19034   right_type(mp->cur_exp)=mp_endpoint;
19035   link(mp->cur_exp)=mp->cur_exp;
19036   x_coord(mp->cur_exp)=0;
19037   y_coord(mp->cur_exp)=0;
19038   originator(mp->cur_exp)=mp_metapost_user;
19039   mp->cur_type=mp_path_type;
19040   break;
19041 case pen_part: 
19042   mp_flush_cur_exp(mp, mp_get_pen_circle(mp, 0));
19043   mp->cur_type=mp_pen_type;
19044   break;
19045 case dash_part: 
19046   mp_flush_cur_exp(mp, mp_get_node(mp, edge_header_size));
19047   mp_init_edges(mp, mp->cur_exp);
19048   mp->cur_type=mp_picture_type;
19049   break;
19050 default: 
19051    mp_flush_cur_exp(mp, 0);
19052   break;
19053 }
19054
19055 @ @<Additional cases of unary...@>=
19056 case char_op: 
19057   if ( mp->cur_type!=mp_known ) { 
19058     mp_bad_unary(mp, char_op);
19059   } else { 
19060     mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256; 
19061     mp->cur_type=mp_string_type;
19062     if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
19063   }
19064   break;
19065 case decimal: 
19066   if ( mp->cur_type!=mp_known ) {
19067      mp_bad_unary(mp, decimal);
19068   } else { 
19069     mp->old_setting=mp->selector; mp->selector=new_string;
19070     mp_print_scaled(mp, mp->cur_exp); mp->cur_exp=mp_make_string(mp);
19071     mp->selector=mp->old_setting; mp->cur_type=mp_string_type;
19072   }
19073   break;
19074 case oct_op:
19075 case hex_op:
19076 case ASCII_op: 
19077   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19078   else mp_str_to_num(mp, c);
19079   break;
19080 case font_size: 
19081   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, font_size);
19082   else @<Find the design size of the font whose name is |cur_exp|@>;
19083   break;
19084
19085 @ @<Declare unary action...@>=
19086 void mp_str_to_num (MP mp,quarterword c) { /* converts a string to a number */
19087   integer n; /* accumulator */
19088   ASCII_code m; /* current character */
19089   pool_pointer k; /* index into |str_pool| */
19090   int b; /* radix of conversion */
19091   boolean bad_char; /* did the string contain an invalid digit? */
19092   if ( c==ASCII_op ) {
19093     if ( length(mp->cur_exp)==0 ) n=-1;
19094     else n=mp->str_pool[mp->str_start[mp->cur_exp]];
19095   } else { 
19096     if ( c==oct_op ) b=8; else b=16;
19097     n=0; bad_char=false;
19098     for (k=mp->str_start[mp->cur_exp];k<=str_stop(mp->cur_exp)-1;k++) {
19099       m=mp->str_pool[k];
19100       if ( (m>='0')&&(m<='9') ) m=m-'0';
19101       else if ( (m>='A')&&(m<='F') ) m=m-'A'+10;
19102       else if ( (m>='a')&&(m<='f') ) m=m-'a'+10;
19103       else  { bad_char=true; m=0; };
19104       if ( m>=b ) { bad_char=true; m=0; };
19105       if ( n<32768 / b ) n=n*b+m; else n=32767;
19106     }
19107     @<Give error messages if |bad_char| or |n>=4096|@>;
19108   }
19109   mp_flush_cur_exp(mp, n*unity);
19110 }
19111
19112 @ @<Give error messages if |bad_char|...@>=
19113 if ( bad_char ) { 
19114   exp_err("String contains illegal digits");
19115 @.String contains illegal digits@>
19116   if ( c==oct_op ) {
19117     help1("I zeroed out characters that weren't in the range 0..7.");
19118   } else  {
19119     help1("I zeroed out characters that weren't hex digits.");
19120   }
19121   mp_put_get_error(mp);
19122 }
19123 if ( (n>4095) ) {
19124   if ( mp->internal[mp_warning_check]>0 ) {
19125     print_err("Number too large ("); 
19126     mp_print_int(mp, n); mp_print_char(mp, ')');
19127 @.Number too large@>
19128     help2("I have trouble with numbers greater than 4095; watch out.")
19129       ("(Set warningcheck:=0 to suppress this message.)");
19130     mp_put_get_error(mp);
19131   }
19132 }
19133
19134 @ The length operation is somewhat unusual in that it applies to a variety
19135 of different types of operands.
19136
19137 @<Additional cases of unary...@>=
19138 case length_op: 
19139   switch (mp->cur_type) {
19140   case mp_string_type: mp_flush_cur_exp(mp, length(mp->cur_exp)*unity); break;
19141   case mp_path_type: mp_flush_cur_exp(mp, mp_path_length(mp)); break;
19142   case mp_known: mp->cur_exp=abs(mp->cur_exp); break;
19143   case mp_picture_type: mp_flush_cur_exp(mp, mp_pict_length(mp)); break;
19144   default: 
19145     if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) )
19146       mp_flush_cur_exp(mp, mp_pyth_add(mp, 
19147         value(x_part_loc(value(mp->cur_exp))),
19148         value(y_part_loc(value(mp->cur_exp)))));
19149     else mp_bad_unary(mp, c);
19150     break;
19151   }
19152   break;
19153
19154 @ @<Declare unary action...@>=
19155 scaled mp_path_length (MP mp) { /* computes the length of the current path */
19156   scaled n; /* the path length so far */
19157   pointer p; /* traverser */
19158   p=mp->cur_exp;
19159   if ( left_type(p)==mp_endpoint ) n=-unity; else n=0;
19160   do {  p=link(p); n=n+unity; } while (p!=mp->cur_exp);
19161   return n;
19162 }
19163
19164 @ @<Declare unary action...@>=
19165 scaled mp_pict_length (MP mp) { 
19166   /* counts interior components in picture |cur_exp| */
19167   scaled n; /* the count so far */
19168   pointer p; /* traverser */
19169   n=0;
19170   p=link(dummy_loc(mp->cur_exp));
19171   if ( p!=null ) {
19172     if ( is_start_or_stop(p) )
19173       if ( mp_skip_1component(mp, p)==null ) p=link(p);
19174     while ( p!=null )  { 
19175       skip_component(p) return n; 
19176       n=n+unity;   
19177     }
19178   }
19179   return n;
19180 }
19181
19182 @ Implement |turningnumber|
19183
19184 @<Additional cases of unary...@>=
19185 case turning_op:
19186   if ( mp->cur_type==mp_pair_type ) mp_flush_cur_exp(mp, 0);
19187   else if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, turning_op);
19188   else if ( left_type(mp->cur_exp)==mp_endpoint )
19189      mp_flush_cur_exp(mp, 0); /* not a cyclic path */
19190   else
19191     mp_flush_cur_exp(mp, mp_turn_cycles_wrapper(mp, mp->cur_exp));
19192   break;
19193
19194 @ The function |an_angle| returns the value of the |angle| primitive, or $0$ if the
19195 argument is |origin|.
19196
19197 @<Declare unary action...@>=
19198 angle mp_an_angle (MP mp,scaled xpar, scaled ypar) {
19199   if ( (! ((xpar==0) && (ypar==0))) )
19200     return mp_n_arg(mp, xpar,ypar);
19201   return 0;
19202 }
19203
19204
19205 @ The actual turning number is (for the moment) computed in a C function
19206 that receives eight integers corresponding to the four controlling points,
19207 and returns a single angle.  Besides those, we have to account for discrete
19208 moves at the actual points.
19209
19210 @d floor(a) (a>=0 ? a : -(int)(-a))
19211 @d bezier_error (720<<20)+1
19212 @d sign(v) ((v)>0 ? 1 : ((v)<0 ? -1 : 0 ))
19213 @d print_roots(a) 
19214 @d out ((double)(xo>>20))
19215 @d mid ((double)(xm>>20))
19216 @d in  ((double)(xi>>20))
19217 @d divisor (256*256)
19218 @d double2angle(a) (int)floor(a*256.0*256.0*16.0)
19219
19220 @<Declare unary action...@>=
19221 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19222             integer CX,integer CY,integer DX,integer DY);
19223
19224 @ @c 
19225 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19226             integer CX,integer CY,integer DX,integer DY) {
19227   double a, b, c;
19228   integer deltax,deltay;
19229   double ax,ay,bx,by,cx,cy,dx,dy;
19230   angle xi = 0, xo = 0, xm = 0;
19231   double res = 0;
19232   ax=AX/divisor;  ay=AY/divisor;
19233   bx=BX/divisor;  by=BY/divisor;
19234   cx=CX/divisor;  cy=CY/divisor;
19235   dx=DX/divisor;  dy=DY/divisor;
19236
19237   deltax = (BX-AX); deltay = (BY-AY);
19238   if (deltax==0 && deltay == 0) { deltax=(CX-AX); deltay=(CY-AY); }
19239   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19240   xi = mp_an_angle(mp,deltax,deltay);
19241
19242   deltax = (CX-BX); deltay = (CY-BY);
19243   xm = mp_an_angle(mp,deltax,deltay);
19244
19245   deltax = (DX-CX); deltay = (DY-CY);
19246   if (deltax==0 && deltay == 0) { deltax=(DX-BX); deltay=(DY-BY); }
19247   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19248   xo = mp_an_angle(mp,deltax,deltay);
19249
19250   a = (bx-ax)*(cy-by) - (cx-bx)*(by-ay); /* a = (bp-ap)x(cp-bp); */
19251   b = (bx-ax)*(dy-cy) - (by-ay)*(dx-cx);; /* b = (bp-ap)x(dp-cp);*/
19252   c = (cx-bx)*(dy-cy) - (dx-cx)*(cy-by); /* c = (cp-bp)x(dp-cp);*/
19253
19254   if ((a==0)&&(c==0)) {
19255     res = (b==0 ?  0 :  (out-in)); 
19256     print_roots("no roots (a)");
19257   } else if ((a==0)||(c==0)) {
19258     if ((sign(b) == sign(a)) || (sign(b) == sign(c))) {
19259       res = out-in; /* ? */
19260       if (res<-180.0) 
19261         res += 360.0;
19262       else if (res>180.0)
19263         res -= 360.0;
19264       print_roots("no roots (b)");
19265     } else {
19266       res = out-in; /* ? */
19267       print_roots("one root (a)");
19268     }
19269   } else if ((sign(a)*sign(c))<0) {
19270     res = out-in; /* ? */
19271       if (res<-180.0) 
19272         res += 360.0;
19273       else if (res>180.0)
19274         res -= 360.0;
19275     print_roots("one root (b)");
19276   } else {
19277     if (sign(a) == sign(b)) {
19278       res = out-in; /* ? */
19279       if (res<-180.0) 
19280         res += 360.0;
19281       else if (res>180.0)
19282         res -= 360.0;
19283       print_roots("no roots (d)");
19284     } else {
19285       if ((b*b) == (4*a*c)) {
19286         res = bezier_error;
19287         print_roots("double root"); /* cusp */
19288       } else if ((b*b) < (4*a*c)) {
19289         res = out-in; /* ? */
19290         if (res<=0.0 &&res>-180.0) 
19291           res += 360.0;
19292         else if (res>=0.0 && res<180.0)
19293           res -= 360.0;
19294         print_roots("no roots (e)");
19295       } else {
19296         res = out-in;
19297         if (res<-180.0) 
19298           res += 360.0;
19299         else if (res>180.0)
19300           res -= 360.0;
19301         print_roots("two roots"); /* two inflections */
19302       }
19303     }
19304   }
19305   return double2angle(res);
19306 }
19307
19308 @
19309 @d p_nextnext link(link(p))
19310 @d p_next link(p)
19311 @d seven_twenty_deg 05500000000 /* $720\cdot2^{20}$, represents $720^\circ$ */
19312
19313 @<Declare unary action...@>=
19314 scaled mp_new_turn_cycles (MP mp,pointer c) {
19315   angle res,ang; /*  the angles of intermediate results  */
19316   scaled turns;  /*  the turn counter  */
19317   pointer p;     /*  for running around the path  */
19318   integer xp,yp;   /*  coordinates of next point  */
19319   integer x,y;   /*  helper coordinates  */
19320   angle in_angle,out_angle;     /*  helper angles */
19321   int old_setting; /* saved |selector| setting */
19322   res=0;
19323   turns= 0;
19324   p=c;
19325   old_setting = mp->selector; mp->selector=term_only;
19326   if ( mp->internal[mp_tracing_commands]>unity ) {
19327     mp_begin_diagnostic(mp);
19328     mp_print_nl(mp, "");
19329     mp_end_diagnostic(mp, false);
19330   }
19331   do { 
19332     xp = x_coord(p_next); yp = y_coord(p_next);
19333     ang  = mp_bezier_slope(mp,x_coord(p), y_coord(p), right_x(p), right_y(p),
19334              left_x(p_next), left_y(p_next), xp, yp);
19335     if ( ang>seven_twenty_deg ) {
19336       print_err("Strange path");
19337       mp_error(mp);
19338       mp->selector=old_setting;
19339       return 0;
19340     }
19341     res  = res + ang;
19342     if ( res > one_eighty_deg ) {
19343       res = res - three_sixty_deg;
19344       turns = turns + unity;
19345     }
19346     if ( res <= -one_eighty_deg ) {
19347       res = res + three_sixty_deg;
19348       turns = turns - unity;
19349     }
19350     /*  incoming angle at next point  */
19351     x = left_x(p_next);  y = left_y(p_next);
19352     if ( (xp==x)&&(yp==y) ) { x = right_x(p);  y = right_y(p);  };
19353     if ( (xp==x)&&(yp==y) ) { x = x_coord(p);  y = y_coord(p);  };
19354     in_angle = mp_an_angle(mp, xp - x, yp - y);
19355     /*  outgoing angle at next point  */
19356     x = right_x(p_next);  y = right_y(p_next);
19357     if ( (xp==x)&&(yp==y) ) { x = left_x(p_nextnext);  y = left_y(p_nextnext);  };
19358     if ( (xp==x)&&(yp==y) ) { x = x_coord(p_nextnext); y = y_coord(p_nextnext); };
19359     out_angle = mp_an_angle(mp, x - xp, y- yp);
19360     ang  = (out_angle - in_angle);
19361     reduce_angle(ang);
19362     if ( ang!=0 ) {
19363       res  = res + ang;
19364       if ( res >= one_eighty_deg ) {
19365         res = res - three_sixty_deg;
19366         turns = turns + unity;
19367       };
19368       if ( res <= -one_eighty_deg ) {
19369         res = res + three_sixty_deg;
19370         turns = turns - unity;
19371       };
19372     };
19373     p = link(p);
19374   } while (p!=c);
19375   mp->selector=old_setting;
19376   return turns;
19377 }
19378
19379
19380 @ This code is based on Bogus\l{}av Jackowski's
19381 |emergency_turningnumber| macro, with some minor changes by Taco
19382 Hoekwater. The macro code looked more like this:
19383 {\obeylines
19384 vardef turning\_number primary p =
19385 ~~save res, ang, turns;
19386 ~~res := 0;
19387 ~~if length p <= 2:
19388 ~~~~if Angle ((point 0 of p) - (postcontrol 0 of p)) >= 0:  1  else: -1 fi
19389 ~~else:
19390 ~~~~for t = 0 upto length p-1 :
19391 ~~~~~~angc := Angle ((point t+1 of p)  - (point t of p))
19392 ~~~~~~~~- Angle ((point t of p) - (point t-1 of p));
19393 ~~~~~~if angc > 180: angc := angc - 360; fi;
19394 ~~~~~~if angc < -180: angc := angc + 360; fi;
19395 ~~~~~~res  := res + angc;
19396 ~~~~endfor;
19397 ~~res/360
19398 ~~fi
19399 enddef;}
19400 The general idea is to calculate only the sum of the angles of
19401 straight lines between the points, of a path, not worrying about cusps
19402 or self-intersections in the segments at all. If the segment is not
19403 well-behaved, the result is not necesarily correct. But the old code
19404 was not always correct either, and worse, it sometimes failed for
19405 well-behaved paths as well. All known bugs that were triggered by the
19406 original code no longer occur with this code, and it runs roughly 3
19407 times as fast because the algorithm is much simpler.
19408
19409 @ It is possible to overflow the return value of the |turn_cycles|
19410 function when the path is sufficiently long and winding, but I am not
19411 going to bother testing for that. In any case, it would only return
19412 the looped result value, which is not a big problem.
19413
19414 The macro code for the repeat loop was a bit nicer to look
19415 at than the pascal code, because it could use |point -1 of p|. In
19416 pascal, the fastest way to loop around the path is not to look
19417 backward once, but forward twice. These defines help hide the trick.
19418
19419 @d p_to link(link(p))
19420 @d p_here link(p)
19421 @d p_from p
19422
19423 @<Declare unary action...@>=
19424 scaled mp_turn_cycles (MP mp,pointer c) {
19425   angle res,ang; /*  the angles of intermediate results  */
19426   scaled turns;  /*  the turn counter  */
19427   pointer p;     /*  for running around the path  */
19428   res=0;  turns= 0; p=c;
19429   do { 
19430     ang  = mp_an_angle (mp, x_coord(p_to) - x_coord(p_here), 
19431                             y_coord(p_to) - y_coord(p_here))
19432         - mp_an_angle (mp, x_coord(p_here) - x_coord(p_from), 
19433                            y_coord(p_here) - y_coord(p_from));
19434     reduce_angle(ang);
19435     res  = res + ang;
19436     if ( res >= three_sixty_deg )  {
19437       res = res - three_sixty_deg;
19438       turns = turns + unity;
19439     };
19440     if ( res <= -three_sixty_deg ) {
19441       res = res + three_sixty_deg;
19442       turns = turns - unity;
19443     };
19444     p = link(p);
19445   } while (p!=c);
19446   return turns;
19447 }
19448
19449 @ @<Declare unary action...@>=
19450 scaled mp_turn_cycles_wrapper (MP mp,pointer c) {
19451   scaled nval,oval;
19452   scaled saved_t_o; /* tracing\_online saved  */
19453   if ( (link(c)==c)||(link(link(c))==c) ) {
19454     if ( mp_an_angle (mp, x_coord(c) - right_x(c),  y_coord(c) - right_y(c)) > 0 )
19455       return unity;
19456     else
19457       return -unity;
19458   } else {
19459     nval = mp_new_turn_cycles(mp, c);
19460     oval = mp_turn_cycles(mp, c);
19461     if ( nval!=oval ) {
19462       saved_t_o=mp->internal[mp_tracing_online];
19463       mp->internal[mp_tracing_online]=unity;
19464       mp_begin_diagnostic(mp);
19465       mp_print_nl (mp, "Warning: the turningnumber algorithms do not agree."
19466                        " The current computed value is ");
19467       mp_print_scaled(mp, nval);
19468       mp_print(mp, ", but the 'connect-the-dots' algorithm returned ");
19469       mp_print_scaled(mp, oval);
19470       mp_end_diagnostic(mp, false);
19471       mp->internal[mp_tracing_online]=saved_t_o;
19472     }
19473     return nval;
19474   }
19475 }
19476
19477 @ @<Declare unary action...@>=
19478 scaled mp_count_turns (MP mp,pointer c) {
19479   pointer p; /* a knot in envelope spec |c| */
19480   integer t; /* total pen offset changes counted */
19481   t=0; p=c;
19482   do {  
19483     t=t+info(p)-zero_off;
19484     p=link(p);
19485   } while (p!=c);
19486   return ((t / 3)*unity);
19487 }
19488
19489 @ @d type_range(A,B) { 
19490   if ( (mp->cur_type>=(A)) && (mp->cur_type<=(B)) ) 
19491     mp_flush_cur_exp(mp, true_code);
19492   else mp_flush_cur_exp(mp, false_code);
19493   mp->cur_type=mp_boolean_type;
19494   }
19495 @d type_test(A) { 
19496   if ( mp->cur_type==(A) ) mp_flush_cur_exp(mp, true_code);
19497   else mp_flush_cur_exp(mp, false_code);
19498   mp->cur_type=mp_boolean_type;
19499   }
19500
19501 @<Additional cases of unary operators@>=
19502 case mp_boolean_type: 
19503   type_range(mp_boolean_type,mp_unknown_boolean); break;
19504 case mp_string_type: 
19505   type_range(mp_string_type,mp_unknown_string); break;
19506 case mp_pen_type: 
19507   type_range(mp_pen_type,mp_unknown_pen); break;
19508 case mp_path_type: 
19509   type_range(mp_path_type,mp_unknown_path); break;
19510 case mp_picture_type: 
19511   type_range(mp_picture_type,mp_unknown_picture); break;
19512 case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
19513 case mp_pair_type: 
19514   type_test(c); break;
19515 case mp_numeric_type: 
19516   type_range(mp_known,mp_independent); break;
19517 case known_op: case unknown_op: 
19518   mp_test_known(mp, c); break;
19519
19520 @ @<Declare unary action procedures@>=
19521 void mp_test_known (MP mp,quarterword c) {
19522   int b; /* is the current expression known? */
19523   pointer p,q; /* locations in a big node */
19524   b=false_code;
19525   switch (mp->cur_type) {
19526   case mp_vacuous: case mp_boolean_type: case mp_string_type:
19527   case mp_pen_type: case mp_path_type: case mp_picture_type:
19528   case mp_known: 
19529     b=true_code;
19530     break;
19531   case mp_transform_type:
19532   case mp_color_type: case mp_cmykcolor_type: case mp_pair_type: 
19533     p=value(mp->cur_exp);
19534     q=p+mp->big_node_size[mp->cur_type];
19535     do {  
19536       q=q-2;
19537       if ( type(q)!=mp_known ) 
19538        goto DONE;
19539     } while (q!=p);
19540     b=true_code;
19541   DONE:  
19542     break;
19543   default: 
19544     break;
19545   }
19546   if ( c==known_op ) mp_flush_cur_exp(mp, b);
19547   else mp_flush_cur_exp(mp, true_code+false_code-b);
19548   mp->cur_type=mp_boolean_type;
19549 }
19550
19551 @ @<Additional cases of unary operators@>=
19552 case cycle_op: 
19553   if ( mp->cur_type!=mp_path_type ) mp_flush_cur_exp(mp, false_code);
19554   else if ( left_type(mp->cur_exp)!=mp_endpoint ) mp_flush_cur_exp(mp, true_code);
19555   else mp_flush_cur_exp(mp, false_code);
19556   mp->cur_type=mp_boolean_type;
19557   break;
19558
19559 @ @<Additional cases of unary operators@>=
19560 case arc_length: 
19561   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19562   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, arc_length);
19563   else mp_flush_cur_exp(mp, mp_get_arc_length(mp, mp->cur_exp));
19564   break;
19565
19566 @ Here we use the fact that |c-filled_op+fill_code| is the desired graphical
19567 object |type|.
19568 @^data structure assumptions@>
19569
19570 @<Additional cases of unary operators@>=
19571 case filled_op:
19572 case stroked_op:
19573 case textual_op:
19574 case clipped_op:
19575 case bounded_op:
19576   if ( mp->cur_type!=mp_picture_type ) mp_flush_cur_exp(mp, false_code);
19577   else if ( link(dummy_loc(mp->cur_exp))==null ) mp_flush_cur_exp(mp, false_code);
19578   else if ( type(link(dummy_loc(mp->cur_exp)))==c+mp_fill_code-filled_op )
19579     mp_flush_cur_exp(mp, true_code);
19580   else mp_flush_cur_exp(mp, false_code);
19581   mp->cur_type=mp_boolean_type;
19582   break;
19583
19584 @ @<Additional cases of unary operators@>=
19585 case make_pen_op: 
19586   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19587   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, make_pen_op);
19588   else { 
19589     mp->cur_type=mp_pen_type;
19590     mp->cur_exp=mp_make_pen(mp, mp->cur_exp,true);
19591   };
19592   break;
19593 case make_path_op: 
19594   if ( mp->cur_type!=mp_pen_type ) mp_bad_unary(mp, make_path_op);
19595   else  { 
19596     mp->cur_type=mp_path_type;
19597     mp_make_path(mp, mp->cur_exp);
19598   };
19599   break;
19600 case reverse: 
19601   if ( mp->cur_type==mp_path_type ) {
19602     p=mp_htap_ypoc(mp, mp->cur_exp);
19603     if ( right_type(p)==mp_endpoint ) p=link(p);
19604     mp_toss_knot_list(mp, mp->cur_exp); mp->cur_exp=p;
19605   } else if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19606   else mp_bad_unary(mp, reverse);
19607   break;
19608
19609 @ The |pair_value| routine changes the current expression to a
19610 given ordered pair of values.
19611
19612 @<Declare unary action procedures@>=
19613 void mp_pair_value (MP mp,scaled x, scaled y) {
19614   pointer p; /* a pair node */
19615   p=mp_get_node(mp, value_node_size); 
19616   mp_flush_cur_exp(mp, p); mp->cur_type=mp_pair_type;
19617   type(p)=mp_pair_type; name_type(p)=mp_capsule; mp_init_big_node(mp, p);
19618   p=value(p);
19619   type(x_part_loc(p))=mp_known; value(x_part_loc(p))=x;
19620   type(y_part_loc(p))=mp_known; value(y_part_loc(p))=y;
19621 }
19622
19623 @ @<Additional cases of unary operators@>=
19624 case ll_corner_op: 
19625   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ll_corner_op);
19626   else mp_pair_value(mp, minx,miny);
19627   break;
19628 case lr_corner_op: 
19629   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, lr_corner_op);
19630   else mp_pair_value(mp, maxx,miny);
19631   break;
19632 case ul_corner_op: 
19633   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ul_corner_op);
19634   else mp_pair_value(mp, minx,maxy);
19635   break;
19636 case ur_corner_op: 
19637   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ur_corner_op);
19638   else mp_pair_value(mp, maxx,maxy);
19639   break;
19640
19641 @ Here is a function that sets |minx|, |maxx|, |miny|, |maxy| to the bounding
19642 box of the current expression.  The boolean result is |false| if the expression
19643 has the wrong type.
19644
19645 @<Declare unary action procedures@>=
19646 boolean mp_get_cur_bbox (MP mp) { 
19647   switch (mp->cur_type) {
19648   case mp_picture_type: 
19649     mp_set_bbox(mp, mp->cur_exp,true);
19650     if ( minx_val(mp->cur_exp)>maxx_val(mp->cur_exp) ) {
19651       minx=0; maxx=0; miny=0; maxy=0;
19652     } else { 
19653       minx=minx_val(mp->cur_exp);
19654       maxx=maxx_val(mp->cur_exp);
19655       miny=miny_val(mp->cur_exp);
19656       maxy=maxy_val(mp->cur_exp);
19657     }
19658     break;
19659   case mp_path_type: 
19660     mp_path_bbox(mp, mp->cur_exp);
19661     break;
19662   case mp_pen_type: 
19663     mp_pen_bbox(mp, mp->cur_exp);
19664     break;
19665   default: 
19666     return false;
19667   }
19668   return true;
19669 }
19670
19671 @ @<Additional cases of unary operators@>=
19672 case read_from_op:
19673 case close_from_op: 
19674   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19675   else mp_do_read_or_close(mp,c);
19676   break;
19677
19678 @ Here is a routine that interprets |cur_exp| as a file name and tries to read
19679 a line from the file or to close the file.
19680
19681 @<Declare unary action procedures@>=
19682 void mp_do_read_or_close (MP mp,quarterword c) {
19683   readf_index n,n0; /* indices for searching |rd_fname| */
19684   @<Find the |n| where |rd_fname[n]=cur_exp|; if |cur_exp| must be inserted,
19685     call |start_read_input| and |goto found| or |not_found|@>;
19686   mp_begin_file_reading(mp);
19687   name=is_read;
19688   if ( mp_input_ln(mp, mp->rd_file[n] ) ) 
19689     goto FOUND;
19690   mp_end_file_reading(mp);
19691 NOT_FOUND:
19692   @<Record the end of file and set |cur_exp| to a dummy value@>;
19693   return;
19694 CLOSE_FILE:
19695   mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous; 
19696   return;
19697 FOUND:
19698   mp_flush_cur_exp(mp, 0);
19699   mp_finish_read(mp);
19700 }
19701
19702 @ Free slots in the |rd_file| and |rd_fname| arrays are marked with NULL's in
19703 |rd_fname|.
19704
19705 @<Find the |n| where |rd_fname[n]=cur_exp|...@>=
19706 {   
19707   char *fn;
19708   n=mp->read_files;
19709   n0=mp->read_files;
19710   fn = str(mp->cur_exp);
19711   while (mp_xstrcmp(fn,mp->rd_fname[n])!=0) { 
19712     if ( n>0 ) {
19713       decr(n);
19714     } else if ( c==close_from_op ) {
19715       goto CLOSE_FILE;
19716     } else {
19717       if ( n0==mp->read_files ) {
19718         if ( mp->read_files<mp->max_read_files ) {
19719           incr(mp->read_files);
19720         } else {
19721           void **rd_file;
19722           char **rd_fname;
19723               readf_index l,k;
19724           l = mp->max_read_files + (mp->max_read_files>>2);
19725           rd_file = xmalloc((l+1), sizeof(void *));
19726           rd_fname = xmalloc((l+1), sizeof(char *));
19727               for (k=0;k<=l;k++) {
19728             if (k<=mp->max_read_files) {
19729                   rd_file[k]=mp->rd_file[k]; 
19730               rd_fname[k]=mp->rd_fname[k];
19731             } else {
19732               rd_file[k]=0; 
19733               rd_fname[k]=NULL;
19734             }
19735           }
19736               xfree(mp->rd_file); xfree(mp->rd_fname);
19737           mp->max_read_files = l;
19738           mp->rd_file = rd_file;
19739           mp->rd_fname = rd_fname;
19740         }
19741       }
19742       n=n0;
19743       if ( mp_start_read_input(mp,fn,n) ) 
19744         goto FOUND;
19745       else 
19746         goto NOT_FOUND;
19747     }
19748     if ( mp->rd_fname[n]==NULL ) { n0=n; }
19749   } 
19750   if ( c==close_from_op ) { 
19751     (mp->close_file)(mp->rd_file[n]); 
19752     goto NOT_FOUND; 
19753   }
19754 }
19755
19756 @ @<Record the end of file and set |cur_exp| to a dummy value@>=
19757 xfree(mp->rd_fname[n]);
19758 mp->rd_fname[n]=NULL;
19759 if ( n==mp->read_files-1 ) mp->read_files=n;
19760 if ( c==close_from_op ) 
19761   goto CLOSE_FILE;
19762 mp_flush_cur_exp(mp, mp->eof_line);
19763 mp->cur_type=mp_string_type
19764
19765 @ The string denoting end-of-file is a one-byte string at position zero, by definition
19766
19767 @<Glob...@>=
19768 str_number eof_line;
19769
19770 @ @<Set init...@>=
19771 mp->eof_line=0;
19772
19773 @ Finally, we have the operations that combine a capsule~|p|
19774 with the current expression.
19775
19776 @c @<Declare binary action procedures@>;
19777 void mp_do_binary (MP mp,pointer p, quarterword c) {
19778   pointer q,r,rr; /* for list manipulation */
19779   pointer old_p,old_exp; /* capsules to recycle */
19780   integer v; /* for numeric manipulation */
19781   check_arith;
19782   if ( mp->internal[mp_tracing_commands]>two ) {
19783     @<Trace the current binary operation@>;
19784   }
19785   @<Sidestep |independent| cases in capsule |p|@>;
19786   @<Sidestep |independent| cases in the current expression@>;
19787   switch (c) {
19788   case plus: case minus:
19789     @<Add or subtract the current expression from |p|@>;
19790     break;
19791   @<Additional cases of binary operators@>;
19792   }; /* there are no other cases */
19793   mp_recycle_value(mp, p); 
19794   mp_free_node(mp, p,value_node_size); /* |return| to avoid this */
19795   check_arith; 
19796   @<Recycle any sidestepped |independent| capsules@>;
19797 }
19798
19799 @ @<Declare binary action...@>=
19800 void mp_bad_binary (MP mp,pointer p, quarterword c) { 
19801   mp_disp_err(mp, p,"");
19802   exp_err("Not implemented: ");
19803 @.Not implemented...@>
19804   if ( c>=min_of ) mp_print_op(mp, c);
19805   mp_print_known_or_unknown_type(mp, type(p),p);
19806   if ( c>=min_of ) mp_print(mp, "of"); else mp_print_op(mp, c);
19807   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
19808   help3("I'm afraid I don't know how to apply that operation to that")
19809        ("combination of types. Continue, and I'll return the second")
19810       ("argument (see above) as the result of the operation.");
19811   mp_put_get_error(mp);
19812 }
19813 void mp_bad_envelope_pen (MP mp) {
19814   mp_disp_err(mp, null,"");
19815   exp_err("Not implemented: envelope(elliptical pen)of(path)");
19816 @.Not implemented...@>
19817   help3("I'm afraid I don't know how to apply that operation to that")
19818        ("combination of types. Continue, and I'll return the second")
19819       ("argument (see above) as the result of the operation.");
19820   mp_put_get_error(mp);
19821 }
19822
19823 @ @<Trace the current binary operation@>=
19824
19825   mp_begin_diagnostic(mp); mp_print_nl(mp, "{(");
19826   mp_print_exp(mp,p,0); /* show the operand, but not verbosely */
19827   mp_print_char(mp,')'); mp_print_op(mp,c); mp_print_char(mp,'(');
19828   mp_print_exp(mp,null,0); mp_print(mp,")}"); 
19829   mp_end_diagnostic(mp, false);
19830 }
19831
19832 @ Several of the binary operations are potentially complicated by the
19833 fact that |independent| values can sneak into capsules. For example,
19834 we've seen an instance of this difficulty in the unary operation
19835 of negation. In order to reduce the number of cases that need to be
19836 handled, we first change the two operands (if necessary)
19837 to rid them of |independent| components. The original operands are
19838 put into capsules called |old_p| and |old_exp|, which will be
19839 recycled after the binary operation has been safely carried out.
19840
19841 @<Recycle any sidestepped |independent| capsules@>=
19842 if ( old_p!=null ) { 
19843   mp_recycle_value(mp, old_p); mp_free_node(mp, old_p,value_node_size);
19844 }
19845 if ( old_exp!=null ) {
19846   mp_recycle_value(mp, old_exp); mp_free_node(mp, old_exp,value_node_size);
19847 }
19848
19849 @ A big node is considered to be ``tarnished'' if it contains at least one
19850 independent component. We will define a simple function called `|tarnished|'
19851 that returns |null| if and only if its argument is not tarnished.
19852
19853 @<Sidestep |independent| cases in capsule |p|@>=
19854 switch (type(p)) {
19855 case mp_transform_type:
19856 case mp_color_type:
19857 case mp_cmykcolor_type:
19858 case mp_pair_type: 
19859   old_p=mp_tarnished(mp, p);
19860   break;
19861 case mp_independent: old_p=mp_void; break;
19862 default: old_p=null; break;
19863 };
19864 if ( old_p!=null ) {
19865   q=mp_stash_cur_exp(mp); old_p=p; mp_make_exp_copy(mp, old_p);
19866   p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
19867 }
19868
19869 @ @<Sidestep |independent| cases in the current expression@>=
19870 switch (mp->cur_type) {
19871 case mp_transform_type:
19872 case mp_color_type:
19873 case mp_cmykcolor_type:
19874 case mp_pair_type: 
19875   old_exp=mp_tarnished(mp, mp->cur_exp);
19876   break;
19877 case mp_independent:old_exp=mp_void; break;
19878 default: old_exp=null; break;
19879 };
19880 if ( old_exp!=null ) {
19881   old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
19882 }
19883
19884 @ @<Declare binary action...@>=
19885 pointer mp_tarnished (MP mp,pointer p) {
19886   pointer q; /* beginning of the big node */
19887   pointer r; /* current position in the big node */
19888   q=value(p); r=q+mp->big_node_size[type(p)];
19889   do {  
19890    r=r-2;
19891    if ( type(r)==mp_independent ) return mp_void; 
19892   } while (r!=q);
19893   return null;
19894 }
19895
19896 @ @<Add or subtract the current expression from |p|@>=
19897 if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
19898   mp_bad_binary(mp, p,c);
19899 } else  {
19900   if ((mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
19901     mp_add_or_subtract(mp, p,null,c);
19902   } else {
19903     if ( mp->cur_type!=type(p) )  {
19904       mp_bad_binary(mp, p,c);
19905     } else { 
19906       q=value(p); r=value(mp->cur_exp);
19907       rr=r+mp->big_node_size[mp->cur_type];
19908       while ( r<rr ) { 
19909         mp_add_or_subtract(mp, q,r,c);
19910         q=q+2; r=r+2;
19911       }
19912     }
19913   }
19914 }
19915
19916 @ The first argument to |add_or_subtract| is the location of a value node
19917 in a capsule or pair node that will soon be recycled. The second argument
19918 is either a location within a pair or transform node of |cur_exp|,
19919 or it is null (which means that |cur_exp| itself should be the second
19920 argument).  The third argument is either |plus| or |minus|.
19921
19922 The sum or difference of the numeric quantities will replace the second
19923 operand.  Arithmetic overflow may go undetected; users aren't supposed to
19924 be monkeying around with really big values.
19925
19926 @<Declare binary action...@>=
19927 @<Declare the procedure called |dep_finish|@>;
19928 void mp_add_or_subtract (MP mp,pointer p, pointer q, quarterword c) {
19929   small_number s,t; /* operand types */
19930   pointer r; /* list traverser */
19931   integer v; /* second operand value */
19932   if ( q==null ) { 
19933     t=mp->cur_type;
19934     if ( t<mp_dependent ) v=mp->cur_exp; else v=dep_list(mp->cur_exp);
19935   } else { 
19936     t=type(q);
19937     if ( t<mp_dependent ) v=value(q); else v=dep_list(q);
19938   }
19939   if ( t==mp_known ) {
19940     if ( c==minus ) negate(v);
19941     if ( type(p)==mp_known ) {
19942       v=mp_slow_add(mp, value(p),v);
19943       if ( q==null ) mp->cur_exp=v; else value(q)=v;
19944       return;
19945     }
19946     @<Add a known value to the constant term of |dep_list(p)|@>;
19947   } else  { 
19948     if ( c==minus ) mp_negate_dep_list(mp, v);
19949     @<Add operand |p| to the dependency list |v|@>;
19950   }
19951 }
19952
19953 @ @<Add a known value to the constant term of |dep_list(p)|@>=
19954 r=dep_list(p);
19955 while ( info(r)!=null ) r=link(r);
19956 value(r)=mp_slow_add(mp, value(r),v);
19957 if ( q==null ) {
19958   q=mp_get_node(mp, value_node_size); mp->cur_exp=q; mp->cur_type=type(p);
19959   name_type(q)=mp_capsule;
19960 }
19961 dep_list(q)=dep_list(p); type(q)=type(p);
19962 prev_dep(q)=prev_dep(p); link(prev_dep(p))=q;
19963 type(p)=mp_known; /* this will keep the recycler from collecting non-garbage */
19964
19965 @ We prefer |dependent| lists to |mp_proto_dependent| ones, because it is
19966 nice to retain the extra accuracy of |fraction| coefficients.
19967 But we have to handle both kinds, and mixtures too.
19968
19969 @<Add operand |p| to the dependency list |v|@>=
19970 if ( type(p)==mp_known ) {
19971   @<Add the known |value(p)| to the constant term of |v|@>;
19972 } else { 
19973   s=type(p); r=dep_list(p);
19974   if ( t==mp_dependent ) {
19975     if ( s==mp_dependent ) {
19976       if ( mp_max_coef(mp, r)+mp_max_coef(mp, v)<coef_bound )
19977         v=mp_p_plus_q(mp, v,r,mp_dependent); goto DONE;
19978       } /* |fix_needed| will necessarily be false */
19979       t=mp_proto_dependent; 
19980       v=mp_p_over_v(mp, v,unity,mp_dependent,mp_proto_dependent);
19981     }
19982     if ( s==mp_proto_dependent ) v=mp_p_plus_q(mp, v,r,mp_proto_dependent);
19983     else v=mp_p_plus_fq(mp, v,unity,r,mp_proto_dependent,mp_dependent);
19984  DONE:  
19985     @<Output the answer, |v| (which might have become |known|)@>;
19986   }
19987
19988 @ @<Add the known |value(p)| to the constant term of |v|@>=
19989
19990   while ( info(v)!=null ) v=link(v);
19991   value(v)=mp_slow_add(mp, value(p),value(v));
19992 }
19993
19994 @ @<Output the answer, |v| (which might have become |known|)@>=
19995 if ( q!=null ) mp_dep_finish(mp, v,q,t);
19996 else  { mp->cur_type=t; mp_dep_finish(mp, v,null,t); }
19997
19998 @ Here's the current situation: The dependency list |v| of type |t|
19999 should either be put into the current expression (if |q=null|) or
20000 into location |q| within a pair node (otherwise). The destination (|cur_exp|
20001 or |q|) formerly held a dependency list with the same
20002 final pointer as the list |v|.
20003
20004 @<Declare the procedure called |dep_finish|@>=
20005 void mp_dep_finish (MP mp, pointer v, pointer q, small_number t) {
20006   pointer p; /* the destination */
20007   scaled vv; /* the value, if it is |known| */
20008   if ( q==null ) p=mp->cur_exp; else p=q;
20009   dep_list(p)=v; type(p)=t;
20010   if ( info(v)==null ) { 
20011     vv=value(v);
20012     if ( q==null ) { 
20013       mp_flush_cur_exp(mp, vv);
20014     } else  { 
20015       mp_recycle_value(mp, p); type(q)=mp_known; value(q)=vv; 
20016     }
20017   } else if ( q==null ) {
20018     mp->cur_type=t;
20019   }
20020   if ( mp->fix_needed ) mp_fix_dependencies(mp);
20021 }
20022
20023 @ Let's turn now to the six basic relations of comparison.
20024
20025 @<Additional cases of binary operators@>=
20026 case less_than: case less_or_equal: case greater_than:
20027 case greater_or_equal: case equal_to: case unequal_to:
20028   check_arith; /* at this point |arith_error| should be |false|? */
20029   if ( (mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
20030     mp_add_or_subtract(mp, p,null,minus); /* |cur_exp:=(p)-cur_exp| */
20031   } else if ( mp->cur_type!=type(p) ) {
20032     mp_bad_binary(mp, p,c); goto DONE; 
20033   } else if ( mp->cur_type==mp_string_type ) {
20034     mp_flush_cur_exp(mp, mp_str_vs_str(mp, value(p),mp->cur_exp));
20035   } else if ((mp->cur_type==mp_unknown_string)||
20036            (mp->cur_type==mp_unknown_boolean) ) {
20037     @<Check if unknowns have been equated@>;
20038   } else if ( (mp->cur_type<=mp_pair_type)&&(mp->cur_type>=mp_transform_type)) {
20039     @<Reduce comparison of big nodes to comparison of scalars@>;
20040   } else if ( mp->cur_type==mp_boolean_type ) {
20041     mp_flush_cur_exp(mp, mp->cur_exp-value(p));
20042   } else { 
20043     mp_bad_binary(mp, p,c); goto DONE;
20044   }
20045   @<Compare the current expression with zero@>;
20046 DONE:  
20047   mp->arith_error=false; /* ignore overflow in comparisons */
20048   break;
20049
20050 @ @<Compare the current expression with zero@>=
20051 if ( mp->cur_type!=mp_known ) {
20052   if ( mp->cur_type<mp_known ) {
20053     mp_disp_err(mp, p,"");
20054     help1("The quantities shown above have not been equated.")
20055   } else  {
20056     help2("Oh dear. I can\'t decide if the expression above is positive,")
20057      ("negative, or zero. So this comparison test won't be `true'.");
20058   }
20059   exp_err("Unknown relation will be considered false");
20060 @.Unknown relation...@>
20061   mp_put_get_flush_error(mp, false_code);
20062 } else {
20063   switch (c) {
20064   case less_than: boolean_reset(mp->cur_exp<0); break;
20065   case less_or_equal: boolean_reset(mp->cur_exp<=0); break;
20066   case greater_than: boolean_reset(mp->cur_exp>0); break;
20067   case greater_or_equal: boolean_reset(mp->cur_exp>=0); break;
20068   case equal_to: boolean_reset(mp->cur_exp==0); break;
20069   case unequal_to: boolean_reset(mp->cur_exp!=0); break;
20070   }; /* there are no other cases */
20071 }
20072 mp->cur_type=mp_boolean_type
20073
20074 @ When two unknown strings are in the same ring, we know that they are
20075 equal. Otherwise, we don't know whether they are equal or not, so we
20076 make no change.
20077
20078 @<Check if unknowns have been equated@>=
20079
20080   q=value(mp->cur_exp);
20081   while ( (q!=mp->cur_exp)&&(q!=p) ) q=value(q);
20082   if ( q==p ) mp_flush_cur_exp(mp, 0);
20083 }
20084
20085 @ @<Reduce comparison of big nodes to comparison of scalars@>=
20086
20087   q=value(p); r=value(mp->cur_exp);
20088   rr=r+mp->big_node_size[mp->cur_type]-2;
20089   while (1) { mp_add_or_subtract(mp, q,r,minus);
20090     if ( type(r)!=mp_known ) break;
20091     if ( value(r)!=0 ) break;
20092     if ( r==rr ) break;
20093     q=q+2; r=r+2;
20094   }
20095   mp_take_part(mp, name_type(r)+x_part-mp_x_part_sector);
20096 }
20097
20098 @ Here we use the sneaky fact that |and_op-false_code=or_op-true_code|.
20099
20100 @<Additional cases of binary operators@>=
20101 case and_op:
20102 case or_op: 
20103   if ( (type(p)!=mp_boolean_type)||(mp->cur_type!=mp_boolean_type) )
20104     mp_bad_binary(mp, p,c);
20105   else if ( value(p)==c+false_code-and_op ) mp->cur_exp=value(p);
20106   break;
20107
20108 @ @<Additional cases of binary operators@>=
20109 case times: 
20110   if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
20111    mp_bad_binary(mp, p,times);
20112   } else if ( (mp->cur_type==mp_known)||(type(p)==mp_known) ) {
20113     @<Multiply when at least one operand is known@>;
20114   } else if ( (mp_nice_color_or_pair(mp, p,type(p))&&(mp->cur_type>mp_pair_type))
20115       ||(mp_nice_color_or_pair(mp, mp->cur_exp,mp->cur_type)&&
20116           (type(p)>mp_pair_type)) ) {
20117     mp_hard_times(mp, p); return;
20118   } else {
20119     mp_bad_binary(mp, p,times);
20120   }
20121   break;
20122
20123 @ @<Multiply when at least one operand is known@>=
20124
20125   if ( type(p)==mp_known ) {
20126     v=value(p); mp_free_node(mp, p,value_node_size); 
20127   } else {
20128     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20129   }
20130   if ( mp->cur_type==mp_known ) {
20131     mp->cur_exp=mp_take_scaled(mp, mp->cur_exp,v);
20132   } else if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_color_type)||
20133               (mp->cur_type==mp_cmykcolor_type) ) {
20134     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20135     do {  
20136        p=p-2; mp_dep_mult(mp, p,v,true);
20137     } while (p!=value(mp->cur_exp));
20138   } else {
20139     mp_dep_mult(mp, null,v,true);
20140   }
20141   return;
20142 }
20143
20144 @ @<Declare binary action...@>=
20145 void mp_dep_mult (MP mp,pointer p, integer v, boolean v_is_scaled) {
20146   pointer q; /* the dependency list being multiplied by |v| */
20147   small_number s,t; /* its type, before and after */
20148   if ( p==null ) {
20149     q=mp->cur_exp;
20150   } else if ( type(p)!=mp_known ) {
20151     q=p;
20152   } else { 
20153     if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
20154     else value(p)=mp_take_fraction(mp, value(p),v);
20155     return;
20156   };
20157   t=type(q); q=dep_list(q); s=t;
20158   if ( t==mp_dependent ) if ( v_is_scaled )
20159     if (mp_ab_vs_cd(mp, mp_max_coef(mp,q),abs(v),coef_bound-1,unity)>=0 ) 
20160       t=mp_proto_dependent;
20161   q=mp_p_times_v(mp, q,v,s,t,v_is_scaled); 
20162   mp_dep_finish(mp, q,p,t);
20163 }
20164
20165 @ Here is a routine that is similar to |times|; but it is invoked only
20166 internally, when |v| is a |fraction| whose magnitude is at most~1,
20167 and when |cur_type>=mp_color_type|.
20168
20169 @c void mp_frac_mult (MP mp,scaled n, scaled d) {
20170   /* multiplies |cur_exp| by |n/d| */
20171   pointer p; /* a pair node */
20172   pointer old_exp; /* a capsule to recycle */
20173   fraction v; /* |n/d| */
20174   if ( mp->internal[mp_tracing_commands]>two ) {
20175     @<Trace the fraction multiplication@>;
20176   }
20177   switch (mp->cur_type) {
20178   case mp_transform_type:
20179   case mp_color_type:
20180   case mp_cmykcolor_type:
20181   case mp_pair_type:
20182    old_exp=mp_tarnished(mp, mp->cur_exp);
20183    break;
20184   case mp_independent: old_exp=mp_void; break;
20185   default: old_exp=null; break;
20186   }
20187   if ( old_exp!=null ) { 
20188      old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
20189   }
20190   v=mp_make_fraction(mp, n,d);
20191   if ( mp->cur_type==mp_known ) {
20192     mp->cur_exp=mp_take_fraction(mp, mp->cur_exp,v);
20193   } else if ( mp->cur_type<=mp_pair_type ) { 
20194     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20195     do {  
20196       p=p-2;
20197       mp_dep_mult(mp, p,v,false);
20198     } while (p!=value(mp->cur_exp));
20199   } else {
20200     mp_dep_mult(mp, null,v,false);
20201   }
20202   if ( old_exp!=null ) {
20203     mp_recycle_value(mp, old_exp); 
20204     mp_free_node(mp, old_exp,value_node_size);
20205   }
20206 }
20207
20208 @ @<Trace the fraction multiplication@>=
20209
20210   mp_begin_diagnostic(mp); 
20211   mp_print_nl(mp, "{("); mp_print_scaled(mp,n); mp_print_char(mp,'/');
20212   mp_print_scaled(mp,d); mp_print(mp,")*("); mp_print_exp(mp,null,0); 
20213   mp_print(mp,")}");
20214   mp_end_diagnostic(mp, false);
20215 }
20216
20217 @ The |hard_times| routine multiplies a nice color or pair by a dependency list.
20218
20219 @<Declare binary action procedures@>=
20220 void mp_hard_times (MP mp,pointer p) {
20221   pointer q; /* a copy of the dependent variable |p| */
20222   pointer r; /* a component of the big node for the nice color or pair */
20223   scaled v; /* the known value for |r| */
20224   if ( type(p)<=mp_pair_type ) { 
20225      q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p); p=q;
20226   }; /* now |cur_type=mp_pair_type| or |cur_type=mp_color_type| */
20227   r=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20228   while (1) { 
20229     r=r-2;
20230     v=value(r);
20231     type(r)=type(p);
20232     if ( r==value(mp->cur_exp) ) 
20233       break;
20234     mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(p)));
20235     mp_dep_mult(mp, r,v,true);
20236   }
20237   mp->mem[value_loc(r)]=mp->mem[value_loc(p)];
20238   link(prev_dep(p))=r;
20239   mp_free_node(mp, p,value_node_size);
20240   mp_dep_mult(mp, r,v,true);
20241 }
20242
20243 @ @<Additional cases of binary operators@>=
20244 case over: 
20245   if ( (mp->cur_type!=mp_known)||(type(p)<mp_color_type) ) {
20246     mp_bad_binary(mp, p,over);
20247   } else { 
20248     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20249     if ( v==0 ) {
20250       @<Squeal about division by zero@>;
20251     } else { 
20252       if ( mp->cur_type==mp_known ) {
20253         mp->cur_exp=mp_make_scaled(mp, mp->cur_exp,v);
20254       } else if ( mp->cur_type<=mp_pair_type ) { 
20255         p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20256         do {  
20257           p=p-2;  mp_dep_div(mp, p,v);
20258         } while (p!=value(mp->cur_exp));
20259       } else {
20260         mp_dep_div(mp, null,v);
20261       }
20262     }
20263     return;
20264   }
20265   break;
20266
20267 @ @<Declare binary action...@>=
20268 void mp_dep_div (MP mp,pointer p, scaled v) {
20269   pointer q; /* the dependency list being divided by |v| */
20270   small_number s,t; /* its type, before and after */
20271   if ( p==null ) q=mp->cur_exp;
20272   else if ( type(p)!=mp_known ) q=p;
20273   else { value(p)=mp_make_scaled(mp, value(p),v); return; };
20274   t=type(q); q=dep_list(q); s=t;
20275   if ( t==mp_dependent )
20276     if ( mp_ab_vs_cd(mp, mp_max_coef(mp,q),unity,coef_bound-1,abs(v))>=0 ) 
20277       t=mp_proto_dependent;
20278   q=mp_p_over_v(mp, q,v,s,t); 
20279   mp_dep_finish(mp, q,p,t);
20280 }
20281
20282 @ @<Squeal about division by zero@>=
20283
20284   exp_err("Division by zero");
20285 @.Division by zero@>
20286   help2("You're trying to divide the quantity shown above the error")
20287     ("message by zero. I'm going to divide it by one instead.");
20288   mp_put_get_error(mp);
20289 }
20290
20291 @ @<Additional cases of binary operators@>=
20292 case pythag_add:
20293 case pythag_sub: 
20294    if ( (mp->cur_type==mp_known)&&(type(p)==mp_known) ) {
20295      if ( c==pythag_add ) mp->cur_exp=mp_pyth_add(mp, value(p),mp->cur_exp);
20296      else mp->cur_exp=mp_pyth_sub(mp, value(p),mp->cur_exp);
20297    } else mp_bad_binary(mp, p,c);
20298    break;
20299
20300 @ The next few sections of the program deal with affine transformations
20301 of coordinate data.
20302
20303 @<Additional cases of binary operators@>=
20304 case rotated_by: case slanted_by:
20305 case scaled_by: case shifted_by: case transformed_by:
20306 case x_scaled: case y_scaled: case z_scaled:
20307   if ( type(p)==mp_path_type ) { 
20308     path_trans(c,p); return;
20309   } else if ( type(p)==mp_pen_type ) { 
20310     pen_trans(c,p);
20311     mp->cur_exp=mp_convex_hull(mp, mp->cur_exp); 
20312       /* rounding error could destroy convexity */
20313     return;
20314   } else if ( (type(p)==mp_pair_type)||(type(p)==mp_transform_type) ) {
20315     mp_big_trans(mp, p,c);
20316   } else if ( type(p)==mp_picture_type ) {
20317     mp_do_edges_trans(mp, p,c); return;
20318   } else {
20319     mp_bad_binary(mp, p,c);
20320   }
20321   break;
20322
20323 @ Let |c| be one of the eight transform operators. The procedure call
20324 |set_up_trans(c)| first changes |cur_exp| to a transform that corresponds to
20325 |c| and the original value of |cur_exp|. (In particular, |cur_exp| doesn't
20326 change at all if |c=transformed_by|.)
20327
20328 Then, if all components of the resulting transform are |known|, they are
20329 moved to the global variables |txx|, |txy|, |tyx|, |tyy|, |tx|, |ty|;
20330 and |cur_exp| is changed to the known value zero.
20331
20332 @<Declare binary action...@>=
20333 void mp_set_up_trans (MP mp,quarterword c) {
20334   pointer p,q,r; /* list manipulation registers */
20335   if ( (c!=transformed_by)||(mp->cur_type!=mp_transform_type) ) {
20336     @<Put the current transform into |cur_exp|@>;
20337   }
20338   @<If the current transform is entirely known, stash it in global variables;
20339     otherwise |return|@>;
20340 }
20341
20342 @ @<Glob...@>=
20343 scaled txx;
20344 scaled txy;
20345 scaled tyx;
20346 scaled tyy;
20347 scaled tx;
20348 scaled ty; /* current transform coefficients */
20349
20350 @ @<Put the current transform...@>=
20351
20352   p=mp_stash_cur_exp(mp); 
20353   mp->cur_exp=mp_id_transform(mp); 
20354   mp->cur_type=mp_transform_type;
20355   q=value(mp->cur_exp);
20356   switch (c) {
20357   @<For each of the eight cases, change the relevant fields of |cur_exp|
20358     and |goto done|;
20359     but do nothing if capsule |p| doesn't have the appropriate type@>;
20360   }; /* there are no other cases */
20361   mp_disp_err(mp, p,"Improper transformation argument");
20362 @.Improper transformation argument@>
20363   help3("The expression shown above has the wrong type,")
20364        ("so I can\'t transform anything using it.")
20365        ("Proceed, and I'll omit the transformation.");
20366   mp_put_get_error(mp);
20367 DONE: 
20368   mp_recycle_value(mp, p); 
20369   mp_free_node(mp, p,value_node_size);
20370 }
20371
20372 @ @<If the current transform is entirely known, ...@>=
20373 q=value(mp->cur_exp); r=q+transform_node_size;
20374 do {  
20375   r=r-2;
20376   if ( type(r)!=mp_known ) return;
20377 } while (r!=q);
20378 mp->txx=value(xx_part_loc(q));
20379 mp->txy=value(xy_part_loc(q));
20380 mp->tyx=value(yx_part_loc(q));
20381 mp->tyy=value(yy_part_loc(q));
20382 mp->tx=value(x_part_loc(q));
20383 mp->ty=value(y_part_loc(q));
20384 mp_flush_cur_exp(mp, 0)
20385
20386 @ @<For each of the eight cases...@>=
20387 case rotated_by:
20388   if ( type(p)==mp_known )
20389     @<Install sines and cosines, then |goto done|@>;
20390   break;
20391 case slanted_by:
20392   if ( type(p)>mp_pair_type ) { 
20393    mp_install(mp, xy_part_loc(q),p); goto DONE;
20394   };
20395   break;
20396 case scaled_by:
20397   if ( type(p)>mp_pair_type ) { 
20398     mp_install(mp, xx_part_loc(q),p); mp_install(mp, yy_part_loc(q),p); 
20399     goto DONE;
20400   };
20401   break;
20402 case shifted_by:
20403   if ( type(p)==mp_pair_type ) {
20404     r=value(p); mp_install(mp, x_part_loc(q),x_part_loc(r));
20405     mp_install(mp, y_part_loc(q),y_part_loc(r)); goto DONE;
20406   };
20407   break;
20408 case x_scaled:
20409   if ( type(p)>mp_pair_type ) {
20410     mp_install(mp, xx_part_loc(q),p); goto DONE;
20411   };
20412   break;
20413 case y_scaled:
20414   if ( type(p)>mp_pair_type ) {
20415     mp_install(mp, yy_part_loc(q),p); goto DONE;
20416   };
20417   break;
20418 case z_scaled:
20419   if ( type(p)==mp_pair_type )
20420     @<Install a complex multiplier, then |goto done|@>;
20421   break;
20422 case transformed_by:
20423   break;
20424   
20425
20426 @ @<Install sines and cosines, then |goto done|@>=
20427 { mp_n_sin_cos(mp, (value(p) % three_sixty_units)*16);
20428   value(xx_part_loc(q))=mp_round_fraction(mp, mp->n_cos);
20429   value(yx_part_loc(q))=mp_round_fraction(mp, mp->n_sin);
20430   value(xy_part_loc(q))=-value(yx_part_loc(q));
20431   value(yy_part_loc(q))=value(xx_part_loc(q));
20432   goto DONE;
20433 }
20434
20435 @ @<Install a complex multiplier, then |goto done|@>=
20436
20437   r=value(p);
20438   mp_install(mp, xx_part_loc(q),x_part_loc(r));
20439   mp_install(mp, yy_part_loc(q),x_part_loc(r));
20440   mp_install(mp, yx_part_loc(q),y_part_loc(r));
20441   if ( type(y_part_loc(r))==mp_known ) negate(value(y_part_loc(r)));
20442   else mp_negate_dep_list(mp, dep_list(y_part_loc(r)));
20443   mp_install(mp, xy_part_loc(q),y_part_loc(r));
20444   goto DONE;
20445 }
20446
20447 @ Procedure |set_up_known_trans| is like |set_up_trans|, but it
20448 insists that the transformation be entirely known.
20449
20450 @<Declare binary action...@>=
20451 void mp_set_up_known_trans (MP mp,quarterword c) { 
20452   mp_set_up_trans(mp, c);
20453   if ( mp->cur_type!=mp_known ) {
20454     exp_err("Transform components aren't all known");
20455 @.Transform components...@>
20456     help3("I'm unable to apply a partially specified transformation")
20457       ("except to a fully known pair or transform.")
20458       ("Proceed, and I'll omit the transformation.");
20459     mp_put_get_flush_error(mp, 0);
20460     mp->txx=unity; mp->txy=0; mp->tyx=0; mp->tyy=unity; 
20461     mp->tx=0; mp->ty=0;
20462   }
20463 }
20464
20465 @ Here's a procedure that applies the transform |txx..ty| to a pair of
20466 coordinates in locations |p| and~|q|.
20467
20468 @<Declare binary action...@>= 
20469 void mp_trans (MP mp,pointer p, pointer q) {
20470   scaled v; /* the new |x| value */
20471   v=mp_take_scaled(mp, mp->mem[p].sc,mp->txx)+
20472   mp_take_scaled(mp, mp->mem[q].sc,mp->txy)+mp->tx;
20473   mp->mem[q].sc=mp_take_scaled(mp, mp->mem[p].sc,mp->tyx)+
20474   mp_take_scaled(mp, mp->mem[q].sc,mp->tyy)+mp->ty;
20475   mp->mem[p].sc=v;
20476 }
20477
20478 @ The simplest transformation procedure applies a transform to all
20479 coordinates of a path.  The |path_trans(c)(p)| macro applies
20480 a transformation defined by |cur_exp| and the transform operator |c|
20481 to the path~|p|.
20482
20483 @d path_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20484                      mp_unstash_cur_exp(mp, (B)); 
20485                      mp_do_path_trans(mp, mp->cur_exp); }
20486
20487 @<Declare binary action...@>=
20488 void mp_do_path_trans (MP mp,pointer p) {
20489   pointer q; /* list traverser */
20490   q=p;
20491   do { 
20492     if ( left_type(q)!=mp_endpoint ) 
20493       mp_trans(mp, q+3,q+4); /* that's |left_x| and |left_y| */
20494     mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20495     if ( right_type(q)!=mp_endpoint ) 
20496       mp_trans(mp, q+5,q+6); /* that's |right_x| and |right_y| */
20497 @^data structure assumptions@>
20498     q=link(q);
20499   } while (q!=p);
20500 }
20501
20502 @ Transforming a pen is very similar, except that there are no |left_type|
20503 and |right_type| fields.
20504
20505 @d pen_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20506                     mp_unstash_cur_exp(mp, (B)); 
20507                     mp_do_pen_trans(mp, mp->cur_exp); }
20508
20509 @<Declare binary action...@>=
20510 void mp_do_pen_trans (MP mp,pointer p) {
20511   pointer q; /* list traverser */
20512   if ( pen_is_elliptical(p) ) {
20513     mp_trans(mp, p+3,p+4); /* that's |left_x| and |left_y| */
20514     mp_trans(mp, p+5,p+6); /* that's |right_x| and |right_y| */
20515   };
20516   q=p;
20517   do { 
20518     mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20519 @^data structure assumptions@>
20520     q=link(q);
20521   } while (q!=p);
20522 }
20523
20524 @ The next transformation procedure applies to edge structures. It will do
20525 any transformation, but the results may be substandard if the picture contains
20526 text that uses downloaded bitmap fonts.  The binary action procedure is
20527 |do_edges_trans|, but we also need a function that just scales a picture.
20528 That routine is |scale_edges|.  Both it and the underlying routine |edges_trans|
20529 should be thought of as procedures that update an edge structure |h|, except
20530 that they have to return a (possibly new) structure because of the need to call
20531 |private_edges|.
20532
20533 @<Declare binary action...@>=
20534 pointer mp_edges_trans (MP mp, pointer h) {
20535   pointer q; /* the object being transformed */
20536   pointer r,s; /* for list manipulation */
20537   scaled sx,sy; /* saved transformation parameters */
20538   scaled sqdet; /* square root of determinant for |dash_scale| */
20539   integer sgndet; /* sign of the determinant */
20540   scaled v; /* a temporary value */
20541   h=mp_private_edges(mp, h);
20542   sqdet=mp_sqrt_det(mp, mp->txx,mp->txy,mp->tyx,mp->tyy);
20543   sgndet=mp_ab_vs_cd(mp, mp->txx,mp->tyy,mp->txy,mp->tyx);
20544   if ( dash_list(h)!=null_dash ) {
20545     @<Try to transform the dash list of |h|@>;
20546   }
20547   @<Make the bounding box of |h| unknown if it can't be updated properly
20548     without scanning the whole structure@>;  
20549   q=link(dummy_loc(h));
20550   while ( q!=null ) { 
20551     @<Transform graphical object |q|@>;
20552     q=link(q);
20553   }
20554   return h;
20555 }
20556 void mp_do_edges_trans (MP mp,pointer p, quarterword c) { 
20557   mp_set_up_known_trans(mp, c);
20558   value(p)=mp_edges_trans(mp, value(p));
20559   mp_unstash_cur_exp(mp, p);
20560 }
20561 void mp_scale_edges (MP mp) { 
20562   mp->txx=mp->se_sf; mp->tyy=mp->se_sf;
20563   mp->txy=0; mp->tyx=0; mp->tx=0; mp->ty=0;
20564   mp->se_pic=mp_edges_trans(mp, mp->se_pic);
20565 }
20566
20567 @ @<Try to transform the dash list of |h|@>=
20568 if ( (mp->txy!=0)||(mp->tyx!=0)||
20569      (mp->ty!=0)||(abs(mp->txx)!=abs(mp->tyy))) {
20570   mp_flush_dash_list(mp, h);
20571 } else { 
20572   if ( mp->txx<0 ) { @<Reverse the dash list of |h|@>; } 
20573   @<Scale the dash list by |txx| and shift it by |tx|@>;
20574   dash_y(h)=mp_take_scaled(mp, dash_y(h),abs(mp->tyy));
20575 }
20576
20577 @ @<Reverse the dash list of |h|@>=
20578
20579   r=dash_list(h);
20580   dash_list(h)=null_dash;
20581   while ( r!=null_dash ) {
20582     s=r; r=link(r);
20583     v=start_x(s); start_x(s)=stop_x(s); stop_x(s)=v;
20584     link(s)=dash_list(h);
20585     dash_list(h)=s;
20586   }
20587 }
20588
20589 @ @<Scale the dash list by |txx| and shift it by |tx|@>=
20590 r=dash_list(h);
20591 while ( r!=null_dash ) {
20592   start_x(r)=mp_take_scaled(mp, start_x(r),mp->txx)+mp->tx;
20593   stop_x(r)=mp_take_scaled(mp, stop_x(r),mp->txx)+mp->tx;
20594   r=link(r);
20595 }
20596
20597 @ @<Make the bounding box of |h| unknown if it can't be updated properly...@>=
20598 if ( (mp->txx==0)&&(mp->tyy==0) ) {
20599   @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>;
20600 } else if ( (mp->txy!=0)||(mp->tyx!=0) ) {
20601   mp_init_bbox(mp, h);
20602   goto DONE1;
20603 }
20604 if ( minx_val(h)<=maxx_val(h) ) {
20605   @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift by
20606    |(tx,ty)|@>;
20607 }
20608 DONE1:
20609
20610
20611
20612 @ @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>=
20613
20614   v=minx_val(h); minx_val(h)=miny_val(h); miny_val(h)=v;
20615   v=maxx_val(h); maxx_val(h)=maxy_val(h); maxy_val(h)=v;
20616 }
20617
20618 @ The sum ``|txx+txy|'' is whichever of |txx| or |txy| is nonzero.  The other
20619 sum is similar.
20620
20621 @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift...@>=
20622
20623   minx_val(h)=mp_take_scaled(mp, minx_val(h),mp->txx+mp->txy)+mp->tx;
20624   maxx_val(h)=mp_take_scaled(mp, maxx_val(h),mp->txx+mp->txy)+mp->tx;
20625   miny_val(h)=mp_take_scaled(mp, miny_val(h),mp->tyx+mp->tyy)+mp->ty;
20626   maxy_val(h)=mp_take_scaled(mp, maxy_val(h),mp->tyx+mp->tyy)+mp->ty;
20627   if ( mp->txx+mp->txy<0 ) {
20628     v=minx_val(h); minx_val(h)=maxx_val(h); maxx_val(h)=v;
20629   }
20630   if ( mp->tyx+mp->tyy<0 ) {
20631     v=miny_val(h); miny_val(h)=maxy_val(h); maxy_val(h)=v;
20632   }
20633 }
20634
20635 @ Now we ready for the main task of transforming the graphical objects in edge
20636 structure~|h|.
20637
20638 @<Transform graphical object |q|@>=
20639 switch (type(q)) {
20640 case mp_fill_code: case mp_stroked_code: 
20641   mp_do_path_trans(mp, path_p(q));
20642   @<Transform |pen_p(q)|, making sure polygonal pens stay counter-clockwise@>;
20643   break;
20644 case mp_start_clip_code: case mp_start_bounds_code: 
20645   mp_do_path_trans(mp, path_p(q));
20646   break;
20647 case mp_text_code: 
20648   r=text_tx_loc(q);
20649   @<Transform the compact transformation starting at |r|@>;
20650   break;
20651 case mp_stop_clip_code: case mp_stop_bounds_code: 
20652   break;
20653 } /* there are no other cases */
20654
20655 @ Note that the shift parameters |(tx,ty)| apply only to the path being stroked.
20656 The |dash_scale| has to be adjusted  to scale the dash lengths in |dash_p(q)|
20657 since the \ps\ output procedures will try to compensate for the transformation
20658 we are applying to |pen_p(q)|.  Since this compensation is based on the square
20659 root of the determinant, |sqdet| is the appropriate factor.
20660
20661 @<Transform |pen_p(q)|, making sure...@>=
20662 if ( pen_p(q)!=null ) {
20663   sx=mp->tx; sy=mp->ty;
20664   mp->tx=0; mp->ty=0;
20665   mp_do_pen_trans(mp, pen_p(q));
20666   if ( ((type(q)==mp_stroked_code)&&(dash_p(q)!=null)) )
20667     dash_scale(q)=mp_take_scaled(mp, dash_scale(q),sqdet);
20668   if ( ! pen_is_elliptical(pen_p(q)) )
20669     if ( sgndet<0 )
20670       pen_p(q)=mp_make_pen(mp, mp_copy_path(mp, pen_p(q)),true); 
20671          /* this unreverses the pen */
20672   mp->tx=sx; mp->ty=sy;
20673 }
20674
20675 @ This uses the fact that transformations are stored in the order
20676 |(tx,ty,txx,txy,tyx,tyy)|.
20677 @^data structure assumptions@>
20678
20679 @<Transform the compact transformation starting at |r|@>=
20680 mp_trans(mp, r,r+1);
20681 sx=mp->tx; sy=mp->ty;
20682 mp->tx=0; mp->ty=0;
20683 mp_trans(mp, r+2,r+4);
20684 mp_trans(mp, r+3,r+5);
20685 mp->tx=sx; mp->ty=sy
20686
20687 @ The hard cases of transformation occur when big nodes are involved,
20688 and when some of their components are unknown.
20689
20690 @<Declare binary action...@>=
20691 @<Declare subroutines needed by |big_trans|@>;
20692 void mp_big_trans (MP mp,pointer p, quarterword c) {
20693   pointer q,r,pp,qq; /* list manipulation registers */
20694   small_number s; /* size of a big node */
20695   s=mp->big_node_size[type(p)]; q=value(p); r=q+s;
20696   do {  
20697     r=r-2;
20698     if ( type(r)!=mp_known ) {
20699       @<Transform an unknown big node and |return|@>;
20700     }
20701   } while (r!=q);
20702   @<Transform a known big node@>;
20703 }; /* node |p| will now be recycled by |do_binary| */
20704
20705 @ @<Transform an unknown big node and |return|@>=
20706
20707   mp_set_up_known_trans(mp, c); mp_make_exp_copy(mp, p); 
20708   r=value(mp->cur_exp);
20709   if ( mp->cur_type==mp_transform_type ) {
20710     mp_bilin1(mp, yy_part_loc(r),mp->tyy,xy_part_loc(q),mp->tyx,0);
20711     mp_bilin1(mp, yx_part_loc(r),mp->tyy,xx_part_loc(q),mp->tyx,0);
20712     mp_bilin1(mp, xy_part_loc(r),mp->txx,yy_part_loc(q),mp->txy,0);
20713     mp_bilin1(mp, xx_part_loc(r),mp->txx,yx_part_loc(q),mp->txy,0);
20714   }
20715   mp_bilin1(mp, y_part_loc(r),mp->tyy,x_part_loc(q),mp->tyx,mp->ty);
20716   mp_bilin1(mp, x_part_loc(r),mp->txx,y_part_loc(q),mp->txy,mp->tx);
20717   return;
20718 }
20719
20720 @ Let |p| point to a two-word value field inside a big node of |cur_exp|,
20721 and let |q| point to a another value field. The |bilin1| procedure
20722 replaces |p| by $p\cdot t+q\cdot u+\delta$.
20723
20724 @<Declare subroutines needed by |big_trans|@>=
20725 void mp_bilin1 (MP mp, pointer p, scaled t, pointer q, 
20726                 scaled u, scaled delta) {
20727   pointer r; /* list traverser */
20728   if ( t!=unity ) mp_dep_mult(mp, p,t,true);
20729   if ( u!=0 ) {
20730     if ( type(q)==mp_known ) {
20731       delta+=mp_take_scaled(mp, value(q),u);
20732     } else { 
20733       @<Ensure that |type(p)=mp_proto_dependent|@>;
20734       dep_list(p)=mp_p_plus_fq(mp, dep_list(p),u,dep_list(q),
20735                                mp_proto_dependent,type(q));
20736     }
20737   }
20738   if ( type(p)==mp_known ) {
20739     value(p)+=delta;
20740   } else {
20741     r=dep_list(p);
20742     while ( info(r)!=null ) r=link(r);
20743     delta+=value(r);
20744     if ( r!=dep_list(p) ) value(r)=delta;
20745     else { mp_recycle_value(mp, p); type(p)=mp_known; value(p)=delta; };
20746   }
20747   if ( mp->fix_needed ) mp_fix_dependencies(mp);
20748 }
20749
20750 @ @<Ensure that |type(p)=mp_proto_dependent|@>=
20751 if ( type(p)!=mp_proto_dependent ) {
20752   if ( type(p)==mp_known ) 
20753     mp_new_dep(mp, p,mp_const_dependency(mp, value(p)));
20754   else 
20755     dep_list(p)=mp_p_times_v(mp, dep_list(p),unity,mp_dependent,
20756                              mp_proto_dependent,true);
20757   type(p)=mp_proto_dependent;
20758 }
20759
20760 @ @<Transform a known big node@>=
20761 mp_set_up_trans(mp, c);
20762 if ( mp->cur_type==mp_known ) {
20763   @<Transform known by known@>;
20764 } else { 
20765   pp=mp_stash_cur_exp(mp); qq=value(pp);
20766   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20767   if ( mp->cur_type==mp_transform_type ) {
20768     mp_bilin2(mp, yy_part_loc(r),yy_part_loc(qq),
20769       value(xy_part_loc(q)),yx_part_loc(qq),null);
20770     mp_bilin2(mp, yx_part_loc(r),yy_part_loc(qq),
20771       value(xx_part_loc(q)),yx_part_loc(qq),null);
20772     mp_bilin2(mp, xy_part_loc(r),xx_part_loc(qq),
20773       value(yy_part_loc(q)),xy_part_loc(qq),null);
20774     mp_bilin2(mp, xx_part_loc(r),xx_part_loc(qq),
20775       value(yx_part_loc(q)),xy_part_loc(qq),null);
20776   };
20777   mp_bilin2(mp, y_part_loc(r),yy_part_loc(qq),
20778     value(x_part_loc(q)),yx_part_loc(qq),y_part_loc(qq));
20779   mp_bilin2(mp, x_part_loc(r),xx_part_loc(qq),
20780     value(y_part_loc(q)),xy_part_loc(qq),x_part_loc(qq));
20781   mp_recycle_value(mp, pp); mp_free_node(mp, pp,value_node_size);
20782 }
20783
20784 @ Let |p| be a |mp_proto_dependent| value whose dependency list ends
20785 at |dep_final|. The following procedure adds |v| times another
20786 numeric quantity to~|p|.
20787
20788 @<Declare subroutines needed by |big_trans|@>=
20789 void mp_add_mult_dep (MP mp,pointer p, scaled v, pointer r) { 
20790   if ( type(r)==mp_known ) {
20791     value(mp->dep_final)+=mp_take_scaled(mp, value(r),v);
20792   } else  { 
20793     dep_list(p)=mp_p_plus_fq(mp, dep_list(p),v,dep_list(r),
20794                                                          mp_proto_dependent,type(r));
20795     if ( mp->fix_needed ) mp_fix_dependencies(mp);
20796   }
20797 }
20798
20799 @ The |bilin2| procedure is something like |bilin1|, but with known
20800 and unknown quantities reversed. Parameter |p| points to a value field
20801 within the big node for |cur_exp|; and |type(p)=mp_known|. Parameters
20802 |t| and~|u| point to value fields elsewhere; so does parameter~|q|,
20803 unless it is |null| (which stands for zero). Location~|p| will be
20804 replaced by $p\cdot t+v\cdot u+q$.
20805
20806 @<Declare subroutines needed by |big_trans|@>=
20807 void mp_bilin2 (MP mp,pointer p, pointer t, scaled v, 
20808                 pointer u, pointer q) {
20809   scaled vv; /* temporary storage for |value(p)| */
20810   vv=value(p); type(p)=mp_proto_dependent;
20811   mp_new_dep(mp, p,mp_const_dependency(mp, 0)); /* this sets |dep_final| */
20812   if ( vv!=0 ) 
20813     mp_add_mult_dep(mp, p,vv,t); /* |dep_final| doesn't change */
20814   if ( v!=0 ) mp_add_mult_dep(mp, p,v,u);
20815   if ( q!=null ) mp_add_mult_dep(mp, p,unity,q);
20816   if ( dep_list(p)==mp->dep_final ) {
20817     vv=value(mp->dep_final); mp_recycle_value(mp, p);
20818     type(p)=mp_known; value(p)=vv;
20819   }
20820 }
20821
20822 @ @<Transform known by known@>=
20823
20824   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20825   if ( mp->cur_type==mp_transform_type ) {
20826     mp_bilin3(mp, yy_part_loc(r),mp->tyy,value(xy_part_loc(q)),mp->tyx,0);
20827     mp_bilin3(mp, yx_part_loc(r),mp->tyy,value(xx_part_loc(q)),mp->tyx,0);
20828     mp_bilin3(mp, xy_part_loc(r),mp->txx,value(yy_part_loc(q)),mp->txy,0);
20829     mp_bilin3(mp, xx_part_loc(r),mp->txx,value(yx_part_loc(q)),mp->txy,0);
20830   }
20831   mp_bilin3(mp, y_part_loc(r),mp->tyy,value(x_part_loc(q)),mp->tyx,mp->ty);
20832   mp_bilin3(mp, x_part_loc(r),mp->txx,value(y_part_loc(q)),mp->txy,mp->tx);
20833 }
20834
20835 @ Finally, in |bilin3| everything is |known|.
20836
20837 @<Declare subroutines needed by |big_trans|@>=
20838 void mp_bilin3 (MP mp,pointer p, scaled t, 
20839                scaled v, scaled u, scaled delta) { 
20840   if ( t!=unity )
20841     delta+=mp_take_scaled(mp, value(p),t);
20842   else 
20843     delta+=value(p);
20844   if ( u!=0 ) value(p)=delta+mp_take_scaled(mp, v,u);
20845   else value(p)=delta;
20846 }
20847
20848 @ @<Additional cases of binary operators@>=
20849 case concatenate: 
20850   if ( (mp->cur_type==mp_string_type)&&(type(p)==mp_string_type) ) mp_cat(mp, p);
20851   else mp_bad_binary(mp, p,concatenate);
20852   break;
20853 case substring_of: 
20854   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_string_type) )
20855     mp_chop_string(mp, value(p));
20856   else mp_bad_binary(mp, p,substring_of);
20857   break;
20858 case subpath_of: 
20859   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
20860   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_path_type) )
20861     mp_chop_path(mp, value(p));
20862   else mp_bad_binary(mp, p,subpath_of);
20863   break;
20864
20865 @ @<Declare binary action...@>=
20866 void mp_cat (MP mp,pointer p) {
20867   str_number a,b; /* the strings being concatenated */
20868   pool_pointer k; /* index into |str_pool| */
20869   a=value(p); b=mp->cur_exp; str_room(length(a)+length(b));
20870   for (k=mp->str_start[a];k<=str_stop(a)-1;k++) {
20871     append_char(mp->str_pool[k]);
20872   }
20873   for (k=mp->str_start[b];k<=str_stop(b)-1;k++) {
20874     append_char(mp->str_pool[k]);
20875   }
20876   mp->cur_exp=mp_make_string(mp); delete_str_ref(b);
20877 }
20878
20879 @ @<Declare binary action...@>=
20880 void mp_chop_string (MP mp,pointer p) {
20881   integer a, b; /* start and stop points */
20882   integer l; /* length of the original string */
20883   integer k; /* runs from |a| to |b| */
20884   str_number s; /* the original string */
20885   boolean reversed; /* was |a>b|? */
20886   a=mp_round_unscaled(mp, value(x_part_loc(p)));
20887   b=mp_round_unscaled(mp, value(y_part_loc(p)));
20888   if ( a<=b ) reversed=false;
20889   else  { reversed=true; k=a; a=b; b=k; };
20890   s=mp->cur_exp; l=length(s);
20891   if ( a<0 ) { 
20892     a=0;
20893     if ( b<0 ) b=0;
20894   }
20895   if ( b>l ) { 
20896     b=l;
20897     if ( a>l ) a=l;
20898   }
20899   str_room(b-a);
20900   if ( reversed ) {
20901     for (k=mp->str_start[s]+b-1;k>=mp->str_start[s]+a;k--)  {
20902       append_char(mp->str_pool[k]);
20903     }
20904   } else  {
20905     for (k=mp->str_start[s]+a;k<=mp->str_start[s]+b-1;k++)  {
20906       append_char(mp->str_pool[k]);
20907     }
20908   }
20909   mp->cur_exp=mp_make_string(mp); delete_str_ref(s);
20910 }
20911
20912 @ @<Declare binary action...@>=
20913 void mp_chop_path (MP mp,pointer p) {
20914   pointer q; /* a knot in the original path */
20915   pointer pp,qq,rr,ss; /* link variables for copies of path nodes */
20916   scaled a,b,k,l; /* indices for chopping */
20917   boolean reversed; /* was |a>b|? */
20918   l=mp_path_length(mp); a=value(x_part_loc(p)); b=value(y_part_loc(p));
20919   if ( a<=b ) reversed=false;
20920   else  { reversed=true; k=a; a=b; b=k; };
20921   @<Dispense with the cases |a<0| and/or |b>l|@>;
20922   q=mp->cur_exp;
20923   while ( a>=unity ) {
20924     q=link(q); a=a-unity; b=b-unity;
20925   }
20926   if ( b==a ) {
20927     @<Construct a path from |pp| to |qq| of length zero@>; 
20928   } else { 
20929     @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>; 
20930   }
20931   left_type(pp)=mp_endpoint; right_type(qq)=mp_endpoint; link(qq)=pp;
20932   mp_toss_knot_list(mp, mp->cur_exp);
20933   if ( reversed ) {
20934     mp->cur_exp=link(mp_htap_ypoc(mp, pp)); mp_toss_knot_list(mp, pp);
20935   } else {
20936     mp->cur_exp=pp;
20937   }
20938 }
20939
20940 @ @<Dispense with the cases |a<0| and/or |b>l|@>=
20941 if ( a<0 ) {
20942   if ( left_type(mp->cur_exp)==mp_endpoint ) {
20943     a=0; if ( b<0 ) b=0;
20944   } else  {
20945     do {  a=a+l; b=b+l; } while (a<0); /* a cycle always has length |l>0| */
20946   }
20947 }
20948 if ( b>l ) {
20949   if ( left_type(mp->cur_exp)==mp_endpoint ) {
20950     b=l; if ( a>l ) a=l;
20951   } else {
20952     while ( a>=l ) { 
20953       a=a-l; b=b-l;
20954     }
20955   }
20956 }
20957
20958 @ @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>=
20959
20960   pp=mp_copy_knot(mp, q); qq=pp;
20961   do {  
20962     q=link(q); rr=qq; qq=mp_copy_knot(mp, q); link(rr)=qq; b=b-unity;
20963   } while (b>0);
20964   if ( a>0 ) {
20965     ss=pp; pp=link(pp);
20966     mp_split_cubic(mp, ss,a*010000); pp=link(ss);
20967     mp_free_node(mp, ss,knot_node_size);
20968     if ( rr==ss ) {
20969       b=mp_make_scaled(mp, b,unity-a); rr=pp;
20970     }
20971   }
20972   if ( b<0 ) {
20973     mp_split_cubic(mp, rr,(b+unity)*010000);
20974     mp_free_node(mp, qq,knot_node_size);
20975     qq=link(rr);
20976   }
20977 }
20978
20979 @ @<Construct a path from |pp| to |qq| of length zero@>=
20980
20981   if ( a>0 ) { mp_split_cubic(mp, q,a*010000); q=link(q); };
20982   pp=mp_copy_knot(mp, q); qq=pp;
20983 }
20984
20985 @ @<Additional cases of binary operators@>=
20986 case point_of: case precontrol_of: case postcontrol_of: 
20987   if ( mp->cur_type==mp_pair_type )
20988      mp_pair_to_path(mp);
20989   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
20990     mp_find_point(mp, value(p),c);
20991   else 
20992     mp_bad_binary(mp, p,c);
20993   break;
20994 case pen_offset_of: 
20995   if ( (mp->cur_type==mp_pen_type)&& mp_nice_pair(mp, p,type(p)) )
20996     mp_set_up_offset(mp, value(p));
20997   else 
20998     mp_bad_binary(mp, p,pen_offset_of);
20999   break;
21000 case direction_time_of: 
21001   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21002   if ( (mp->cur_type==mp_path_type)&& mp_nice_pair(mp, p,type(p)) )
21003     mp_set_up_direction_time(mp, value(p));
21004   else 
21005     mp_bad_binary(mp, p,direction_time_of);
21006   break;
21007 case envelope_of:
21008   if ( (type(p) != mp_pen_type) || (mp->cur_type != mp_path_type) )
21009     mp_bad_binary(mp, p,envelope_of);
21010   else
21011     mp_set_up_envelope(mp, p);
21012   break;
21013
21014 @ @<Declare binary action...@>=
21015 void mp_set_up_offset (MP mp,pointer p) { 
21016   mp_find_offset(mp, value(x_part_loc(p)),value(y_part_loc(p)),mp->cur_exp);
21017   mp_pair_value(mp, mp->cur_x,mp->cur_y);
21018 }
21019 void mp_set_up_direction_time (MP mp,pointer p) { 
21020   mp_flush_cur_exp(mp, mp_find_direction_time(mp, value(x_part_loc(p)),
21021   value(y_part_loc(p)),mp->cur_exp));
21022 }
21023 void mp_set_up_envelope (MP mp,pointer p) {
21024   pointer q = mp_copy_path(mp, mp->cur_exp); /* the original path */
21025   /* TODO: accept elliptical pens for straight paths */
21026   if (pen_is_elliptical(value(p))) {
21027     mp_bad_envelope_pen(mp);
21028     mp->cur_exp = q;
21029     mp->cur_type = mp_path_type;
21030     return;
21031   }
21032   small_number ljoin, lcap;
21033   scaled miterlim;
21034   if ( mp->internal[mp_linejoin]>unity ) ljoin=2;
21035   else if ( mp->internal[mp_linejoin]>0 ) ljoin=1;
21036   else ljoin=0;
21037   if ( mp->internal[mp_linecap]>unity ) lcap=2;
21038   else if ( mp->internal[mp_linecap]>0 ) lcap=1;
21039   else lcap=0;
21040   if ( mp->internal[mp_miterlimit]<unity )
21041     miterlim=unity;
21042   else
21043     miterlim=mp->internal[mp_miterlimit];
21044   mp->cur_exp = mp_make_envelope(mp, q, value(p), ljoin,lcap,miterlim);
21045   mp->cur_type = mp_path_type;
21046 }
21047
21048 @ @<Declare binary action...@>=
21049 void mp_find_point (MP mp,scaled v, quarterword c) {
21050   pointer p; /* the path */
21051   scaled n; /* its length */
21052   p=mp->cur_exp;
21053   if ( left_type(p)==mp_endpoint ) n=-unity; else n=0;
21054   do {  p=link(p); n=n+unity; } while (p!=mp->cur_exp);
21055   if ( n==0 ) { 
21056     v=0; 
21057   } else if ( v<0 ) {
21058     if ( left_type(p)==mp_endpoint ) v=0;
21059     else v=n-1-((-v-1) % n);
21060   } else if ( v>n ) {
21061     if ( left_type(p)==mp_endpoint ) v=n;
21062     else v=v % n;
21063   }
21064   p=mp->cur_exp;
21065   while ( v>=unity ) { p=link(p); v=v-unity;  };
21066   if ( v!=0 ) {
21067      @<Insert a fractional node by splitting the cubic@>;
21068   }
21069   @<Set the current expression to the desired path coordinates@>;
21070 }
21071
21072 @ @<Insert a fractional node...@>=
21073 { mp_split_cubic(mp, p,v*010000); p=link(p); }
21074
21075 @ @<Set the current expression to the desired path coordinates...@>=
21076 switch (c) {
21077 case point_of: 
21078   mp_pair_value(mp, x_coord(p),y_coord(p));
21079   break;
21080 case precontrol_of: 
21081   if ( left_type(p)==mp_endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
21082   else mp_pair_value(mp, left_x(p),left_y(p));
21083   break;
21084 case postcontrol_of: 
21085   if ( right_type(p)==mp_endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
21086   else mp_pair_value(mp, right_x(p),right_y(p));
21087   break;
21088 } /* there are no other cases */
21089
21090 @ @<Additional cases of binary operators@>=
21091 case arc_time_of: 
21092   if ( mp->cur_type==mp_pair_type )
21093      mp_pair_to_path(mp);
21094   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
21095     mp_flush_cur_exp(mp, mp_get_arc_time(mp, mp->cur_exp,value(p)));
21096   else 
21097     mp_bad_binary(mp, p,c);
21098   break;
21099
21100 @ @<Additional cases of bin...@>=
21101 case intersect: 
21102   if ( type(p)==mp_pair_type ) {
21103     q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p);
21104     mp_pair_to_path(mp); p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
21105   };
21106   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21107   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_path_type) ) {
21108     mp_path_intersection(mp, value(p),mp->cur_exp);
21109     mp_pair_value(mp, mp->cur_t,mp->cur_tt);
21110   } else {
21111     mp_bad_binary(mp, p,intersect);
21112   }
21113   break;
21114
21115 @ @<Additional cases of bin...@>=
21116 case in_font:
21117   if ( (mp->cur_type!=mp_string_type)||(type(p)!=mp_string_type)) 
21118     mp_bad_binary(mp, p,in_font);
21119   else { mp_do_infont(mp, p); return; }
21120   break;
21121
21122 @ Function |new_text_node| owns the reference count for its second argument
21123 (the text string) but not its first (the font name).
21124
21125 @<Declare binary action...@>=
21126 void mp_do_infont (MP mp,pointer p) {
21127   pointer q;
21128   q=mp_get_node(mp, edge_header_size);
21129   mp_init_edges(mp, q);
21130   link(obj_tail(q))=mp_new_text_node(mp,str(mp->cur_exp),value(p));
21131   obj_tail(q)=link(obj_tail(q));
21132   mp_free_node(mp, p,value_node_size);
21133   mp_flush_cur_exp(mp, q);
21134   mp->cur_type=mp_picture_type;
21135 }
21136
21137 @* \[40] Statements and commands.
21138 The chief executive of \MP\ is the |do_statement| routine, which
21139 contains the master switch that causes all the various pieces of \MP\
21140 to do their things, in the right order.
21141
21142 In a sense, this is the grand climax of the program: It applies all the
21143 tools that we have worked so hard to construct. In another sense, this is
21144 the messiest part of the program: It necessarily refers to other pieces
21145 of code all over the place, so that a person can't fully understand what is
21146 going on without paging back and forth to be reminded of conventions that
21147 are defined elsewhere. We are now at the hub of the web.
21148
21149 The structure of |do_statement| itself is quite simple.  The first token
21150 of the statement is fetched using |get_x_next|.  If it can be the first
21151 token of an expression, we look for an equation, an assignment, or a
21152 title. Otherwise we use a \&{case} construction to branch at high speed to
21153 the appropriate routine for various and sundry other types of commands,
21154 each of which has an ``action procedure'' that does the necessary work.
21155
21156 The program uses the fact that
21157 $$\hbox{|min_primary_command=max_statement_command=type_name|}$$
21158 to interpret a statement that starts with, e.g., `\&{string}',
21159 as a type declaration rather than a boolean expression.
21160
21161 @c void mp_do_statement (MP mp) { /* governs \MP's activities */
21162   mp->cur_type=mp_vacuous; mp_get_x_next(mp);
21163   if ( mp->cur_cmd>max_primary_command ) {
21164     @<Worry about bad statement@>;
21165   } else if ( mp->cur_cmd>max_statement_command ) {
21166     @<Do an equation, assignment, title, or
21167      `$\langle\,$expression$\,\rangle\,$\&{endgroup}'@>;
21168   } else {
21169     @<Do a statement that doesn't begin with an expression@>;
21170   }
21171   if ( mp->cur_cmd<semicolon )
21172     @<Flush unparsable junk that was found after the statement@>;
21173   mp->error_count=0;
21174 }
21175
21176 @ @<Declarations@>=
21177 @<Declare action procedures for use by |do_statement|@>;
21178
21179 @ The only command codes |>max_primary_command| that can be present
21180 at the beginning of a statement are |semicolon| and higher; these
21181 occur when the statement is null.
21182
21183 @<Worry about bad statement@>=
21184
21185   if ( mp->cur_cmd<semicolon ) {
21186     print_err("A statement can't begin with `");
21187 @.A statement can't begin with x@>
21188     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); mp_print_char(mp, '\'');
21189     help5("I was looking for the beginning of a new statement.")
21190       ("If you just proceed without changing anything, I'll ignore")
21191       ("everything up to the next `;'. Please insert a semicolon")
21192       ("now in front of anything that you don't want me to delete.")
21193       ("(See Chapter 27 of The METAFONTbook for an example.)");
21194 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21195     mp_back_error(mp); mp_get_x_next(mp);
21196   }
21197 }
21198
21199 @ The help message printed here says that everything is flushed up to
21200 a semicolon, but actually the commands |end_group| and |stop| will
21201 also terminate a statement.
21202
21203 @<Flush unparsable junk that was found after the statement@>=
21204
21205   print_err("Extra tokens will be flushed");
21206 @.Extra tokens will be flushed@>
21207   help6("I've just read as much of that statement as I could fathom,")
21208        ("so a semicolon should have been next. It's very puzzling...")
21209        ("but I'll try to get myself back together, by ignoring")
21210        ("everything up to the next `;'. Please insert a semicolon")
21211        ("now in front of anything that you don't want me to delete.")
21212        ("(See Chapter 27 of The METAFONTbook for an example.)");
21213 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21214   mp_back_error(mp); mp->scanner_status=flushing;
21215   do {  
21216     get_t_next;
21217     @<Decrease the string reference count...@>;
21218   } while (! end_of_statement); /* |cur_cmd=semicolon|, |end_group|, or |stop| */
21219   mp->scanner_status=normal;
21220 }
21221
21222 @ If |do_statement| ends with |cur_cmd=end_group|, we should have
21223 |cur_type=mp_vacuous| unless the statement was simply an expression;
21224 in the latter case, |cur_type| and |cur_exp| should represent that
21225 expression.
21226
21227 @<Do a statement that doesn't...@>=
21228
21229   if ( mp->internal[mp_tracing_commands]>0 ) 
21230     show_cur_cmd_mod;
21231   switch (mp->cur_cmd ) {
21232   case type_name:mp_do_type_declaration(mp); break;
21233   case macro_def:
21234     if ( mp->cur_mod>var_def ) mp_make_op_def(mp);
21235     else if ( mp->cur_mod>end_def ) mp_scan_def(mp);
21236      break;
21237   @<Cases of |do_statement| that invoke particular commands@>;
21238   } /* there are no other cases */
21239   mp->cur_type=mp_vacuous;
21240 }
21241
21242 @ The most important statements begin with expressions.
21243
21244 @<Do an equation, assignment, title, or...@>=
21245
21246   mp->var_flag=assignment; mp_scan_expression(mp);
21247   if ( mp->cur_cmd<end_group ) {
21248     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21249     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21250     else if ( mp->cur_type==mp_string_type ) {@<Do a title@> ; }
21251     else if ( mp->cur_type!=mp_vacuous ){ 
21252       exp_err("Isolated expression");
21253 @.Isolated expression@>
21254       help3("I couldn't find an `=' or `:=' after the")
21255         ("expression that is shown above this error message,")
21256         ("so I guess I'll just ignore it and carry on.");
21257       mp_put_get_error(mp);
21258     }
21259     mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous;
21260   }
21261 }
21262
21263 @ @<Do a title@>=
21264
21265   if ( mp->internal[mp_tracing_titles]>0 ) {
21266     mp_print_nl(mp, "");  mp_print_str(mp, mp->cur_exp); update_terminal;
21267   }
21268 }
21269
21270 @ Equations and assignments are performed by the pair of mutually recursive
21271 @^recursion@>
21272 routines |do_equation| and |do_assignment|. These routines are called when
21273 |cur_cmd=equals| and when |cur_cmd=assignment|, respectively; the left-hand
21274 side is in |cur_type| and |cur_exp|, while the right-hand side is yet
21275 to be scanned. After the routines are finished, |cur_type| and |cur_exp|
21276 will be equal to the right-hand side (which will normally be equal
21277 to the left-hand side).
21278
21279 @<Declare action procedures for use by |do_statement|@>=
21280 @<Declare the procedure called |try_eq|@>;
21281 @<Declare the procedure called |make_eq|@>;
21282 void mp_do_equation (MP mp) ;
21283
21284 @ @c
21285 void mp_do_equation (MP mp) {
21286   pointer lhs; /* capsule for the left-hand side */
21287   pointer p; /* temporary register */
21288   lhs=mp_stash_cur_exp(mp); mp_get_x_next(mp); 
21289   mp->var_flag=assignment; mp_scan_expression(mp);
21290   if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21291   else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21292   if ( mp->internal[mp_tracing_commands]>two ) 
21293     @<Trace the current equation@>;
21294   if ( mp->cur_type==mp_unknown_path ) if ( type(lhs)==mp_pair_type ) {
21295     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, lhs); lhs=p;
21296   }; /* in this case |make_eq| will change the pair to a path */
21297   mp_make_eq(mp, lhs); /* equate |lhs| to |(cur_type,cur_exp)| */
21298 }
21299
21300 @ And |do_assignment| is similar to |do_expression|:
21301
21302 @<Declarations@>=
21303 void mp_do_assignment (MP mp);
21304
21305 @ @<Declare action procedures for use by |do_statement|@>=
21306 void mp_do_assignment (MP mp) ;
21307
21308 @ @c
21309 void mp_do_assignment (MP mp) {
21310   pointer lhs; /* token list for the left-hand side */
21311   pointer p; /* where the left-hand value is stored */
21312   pointer q; /* temporary capsule for the right-hand value */
21313   if ( mp->cur_type!=mp_token_list ) { 
21314     exp_err("Improper `:=' will be changed to `='");
21315 @.Improper `:='@>
21316     help2("I didn't find a variable name at the left of the `:=',")
21317       ("so I'm going to pretend that you said `=' instead.");
21318     mp_error(mp); mp_do_equation(mp);
21319   } else { 
21320     lhs=mp->cur_exp; mp->cur_type=mp_vacuous;
21321     mp_get_x_next(mp); mp->var_flag=assignment; mp_scan_expression(mp);
21322     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21323     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21324     if ( mp->internal[mp_tracing_commands]>two ) 
21325       @<Trace the current assignment@>;
21326     if ( info(lhs)>hash_end ) {
21327       @<Assign the current expression to an internal variable@>;
21328     } else  {
21329       @<Assign the current expression to the variable |lhs|@>;
21330     }
21331     mp_flush_node_list(mp, lhs);
21332   }
21333 }
21334
21335 @ @<Trace the current equation@>=
21336
21337   mp_begin_diagnostic(mp); mp_print_nl(mp, "{("); mp_print_exp(mp,lhs,0);
21338   mp_print(mp,")=("); mp_print_exp(mp,null,0); 
21339   mp_print(mp,")}"); mp_end_diagnostic(mp, false);
21340 }
21341
21342 @ @<Trace the current assignment@>=
21343
21344   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
21345   if ( info(lhs)>hash_end ) 
21346      mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21347   else 
21348      mp_show_token_list(mp, lhs,null,1000,0);
21349   mp_print(mp, ":="); mp_print_exp(mp, null,0); 
21350   mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
21351 }
21352
21353 @ @<Assign the current expression to an internal variable@>=
21354 if ( mp->cur_type==mp_known )  {
21355   mp->internal[info(lhs)-(hash_end)]=mp->cur_exp;
21356 } else { 
21357   exp_err("Internal quantity `");
21358 @.Internal quantity...@>
21359   mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21360   mp_print(mp, "' must receive a known value");
21361   help2("I can\'t set an internal quantity to anything but a known")
21362     ("numeric value, so I'll have to ignore this assignment.");
21363   mp_put_get_error(mp);
21364 }
21365
21366 @ @<Assign the current expression to the variable |lhs|@>=
21367
21368   p=mp_find_variable(mp, lhs);
21369   if ( p!=null ) {
21370     q=mp_stash_cur_exp(mp); mp->cur_type=mp_und_type(mp, p); 
21371     mp_recycle_value(mp, p);
21372     type(p)=mp->cur_type; value(p)=null; mp_make_exp_copy(mp, p);
21373     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q); mp_make_eq(mp, p);
21374   } else  { 
21375     mp_obliterated(mp, lhs); mp_put_get_error(mp);
21376   }
21377 }
21378
21379
21380 @ And now we get to the nitty-gritty. The |make_eq| procedure is given
21381 a pointer to a capsule that is to be equated to the current expression.
21382
21383 @<Declare the procedure called |make_eq|@>=
21384 void mp_make_eq (MP mp,pointer lhs) ;
21385
21386
21387
21388 @c void mp_make_eq (MP mp,pointer lhs) {
21389   small_number t; /* type of the left-hand side */
21390   pointer p,q; /* pointers inside of big nodes */
21391   integer v=0; /* value of the left-hand side */
21392 RESTART: 
21393   t=type(lhs);
21394   if ( t<=mp_pair_type ) v=value(lhs);
21395   switch (t) {
21396   @<For each type |t|, make an equation and |goto done| unless |cur_type|
21397     is incompatible with~|t|@>;
21398   } /* all cases have been listed */
21399   @<Announce that the equation cannot be performed@>;
21400 DONE:
21401   check_arith; mp_recycle_value(mp, lhs); 
21402   mp_free_node(mp, lhs,value_node_size);
21403 }
21404
21405 @ @<Announce that the equation cannot be performed@>=
21406 mp_disp_err(mp, lhs,""); 
21407 exp_err("Equation cannot be performed (");
21408 @.Equation cannot be performed@>
21409 if ( type(lhs)<=mp_pair_type ) mp_print_type(mp, type(lhs));
21410 else mp_print(mp, "numeric");
21411 mp_print_char(mp, '=');
21412 if ( mp->cur_type<=mp_pair_type ) mp_print_type(mp, mp->cur_type);
21413 else mp_print(mp, "numeric");
21414 mp_print_char(mp, ')');
21415 help2("I'm sorry, but I don't know how to make such things equal.")
21416      ("(See the two expressions just above the error message.)");
21417 mp_put_get_error(mp)
21418
21419 @ @<For each type |t|, make an equation and |goto done| unless...@>=
21420 case mp_boolean_type: case mp_string_type: case mp_pen_type:
21421 case mp_path_type: case mp_picture_type:
21422   if ( mp->cur_type==t+unknown_tag ) { 
21423     mp_nonlinear_eq(mp, v,mp->cur_exp,false); goto DONE;
21424   } else if ( mp->cur_type==t ) {
21425     @<Report redundant or inconsistent equation and |goto done|@>;
21426   }
21427   break;
21428 case unknown_types:
21429   if ( mp->cur_type==t-unknown_tag ) { 
21430     mp_nonlinear_eq(mp, mp->cur_exp,lhs,true); goto DONE;
21431   } else if ( mp->cur_type==t ) { 
21432     mp_ring_merge(mp, lhs,mp->cur_exp); goto DONE;
21433   } else if ( mp->cur_type==mp_pair_type ) {
21434     if ( t==mp_unknown_path ) { 
21435      mp_pair_to_path(mp); goto RESTART;
21436     };
21437   }
21438   break;
21439 case mp_transform_type: case mp_color_type:
21440 case mp_cmykcolor_type: case mp_pair_type:
21441   if ( mp->cur_type==t ) {
21442     @<Do multiple equations and |goto done|@>;
21443   }
21444   break;
21445 case mp_known: case mp_dependent:
21446 case mp_proto_dependent: case mp_independent:
21447   if ( mp->cur_type>=mp_known ) { 
21448     mp_try_eq(mp, lhs,null); goto DONE;
21449   };
21450   break;
21451 case mp_vacuous:
21452   break;
21453
21454 @ @<Report redundant or inconsistent equation and |goto done|@>=
21455
21456   if ( mp->cur_type<=mp_string_type ) {
21457     if ( mp->cur_type==mp_string_type ) {
21458       if ( mp_str_vs_str(mp, v,mp->cur_exp)!=0 ) {
21459         goto NOT_FOUND;
21460       }
21461     } else if ( v!=mp->cur_exp ) {
21462       goto NOT_FOUND;
21463     }
21464     @<Exclaim about a redundant equation@>; goto DONE;
21465   }
21466   print_err("Redundant or inconsistent equation");
21467 @.Redundant or inconsistent equation@>
21468   help2("An equation between already-known quantities can't help.")
21469        ("But don't worry; continue and I'll just ignore it.");
21470   mp_put_get_error(mp); goto DONE;
21471 NOT_FOUND: 
21472   print_err("Inconsistent equation");
21473 @.Inconsistent equation@>
21474   help2("The equation I just read contradicts what was said before.")
21475        ("But don't worry; continue and I'll just ignore it.");
21476   mp_put_get_error(mp); goto DONE;
21477 }
21478
21479 @ @<Do multiple equations and |goto done|@>=
21480
21481   p=v+mp->big_node_size[t]; 
21482   q=value(mp->cur_exp)+mp->big_node_size[t];
21483   do {  
21484     p=p-2; q=q-2; mp_try_eq(mp, p,q);
21485   } while (p!=v);
21486   goto DONE;
21487 }
21488
21489 @ The first argument to |try_eq| is the location of a value node
21490 in a capsule that will soon be recycled. The second argument is
21491 either a location within a pair or transform node pointed to by
21492 |cur_exp|, or it is |null| (which means that |cur_exp| itself
21493 serves as the second argument). The idea is to leave |cur_exp| unchanged,
21494 but to equate the two operands.
21495
21496 @<Declare the procedure called |try_eq|@>=
21497 void mp_try_eq (MP mp,pointer l, pointer r) ;
21498
21499
21500 @c void mp_try_eq (MP mp,pointer l, pointer r) {
21501   pointer p; /* dependency list for right operand minus left operand */
21502   int t; /* the type of list |p| */
21503   pointer q; /* the constant term of |p| is here */
21504   pointer pp; /* dependency list for right operand */
21505   int tt; /* the type of list |pp| */
21506   boolean copied; /* have we copied a list that ought to be recycled? */
21507   @<Remove the left operand from its container, negate it, and
21508     put it into dependency list~|p| with constant term~|q|@>;
21509   @<Add the right operand to list |p|@>;
21510   if ( info(p)==null ) {
21511     @<Deal with redundant or inconsistent equation@>;
21512   } else { 
21513     mp_linear_eq(mp, p,t);
21514     if ( r==null ) if ( mp->cur_type!=mp_known ) {
21515       if ( type(mp->cur_exp)==mp_known ) {
21516         pp=mp->cur_exp; mp->cur_exp=value(mp->cur_exp); mp->cur_type=mp_known;
21517         mp_free_node(mp, pp,value_node_size);
21518       }
21519     }
21520   }
21521 }
21522
21523 @ @<Remove the left operand from its container, negate it, and...@>=
21524 t=type(l);
21525 if ( t==mp_known ) { 
21526   t=mp_dependent; p=mp_const_dependency(mp, -value(l)); q=p;
21527 } else if ( t==mp_independent ) {
21528   t=mp_dependent; p=mp_single_dependency(mp, l); negate(value(p));
21529   q=mp->dep_final;
21530 } else { 
21531   p=dep_list(l); q=p;
21532   while (1) { 
21533     negate(value(q));
21534     if ( info(q)==null ) break;
21535     q=link(q);
21536   }
21537   link(prev_dep(l))=link(q); prev_dep(link(q))=prev_dep(l);
21538   type(l)=mp_known;
21539 }
21540
21541 @ @<Deal with redundant or inconsistent equation@>=
21542
21543   if ( abs(value(p))>64 ) { /* off by .001 or more */
21544     print_err("Inconsistent equation");
21545 @.Inconsistent equation@>
21546     mp_print(mp, " (off by "); mp_print_scaled(mp, value(p)); 
21547     mp_print_char(mp, ')');
21548     help2("The equation I just read contradicts what was said before.")
21549       ("But don't worry; continue and I'll just ignore it.");
21550     mp_put_get_error(mp);
21551   } else if ( r==null ) {
21552     @<Exclaim about a redundant equation@>;
21553   }
21554   mp_free_node(mp, p,dep_node_size);
21555 }
21556
21557 @ @<Add the right operand to list |p|@>=
21558 if ( r==null ) {
21559   if ( mp->cur_type==mp_known ) {
21560     value(q)=value(q)+mp->cur_exp; goto DONE1;
21561   } else { 
21562     tt=mp->cur_type;
21563     if ( tt==mp_independent ) pp=mp_single_dependency(mp, mp->cur_exp);
21564     else pp=dep_list(mp->cur_exp);
21565   } 
21566 } else {
21567   if ( type(r)==mp_known ) {
21568     value(q)=value(q)+value(r); goto DONE1;
21569   } else { 
21570     tt=type(r);
21571     if ( tt==mp_independent ) pp=mp_single_dependency(mp, r);
21572     else pp=dep_list(r);
21573   }
21574 }
21575 if ( tt!=mp_independent ) copied=false;
21576 else  { copied=true; tt=mp_dependent; };
21577 @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>;
21578 if ( copied ) mp_flush_node_list(mp, pp);
21579 DONE1:
21580
21581 @ @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>=
21582 mp->watch_coefs=false;
21583 if ( t==tt ) {
21584   p=mp_p_plus_q(mp, p,pp,t);
21585 } else if ( t==mp_proto_dependent ) {
21586   p=mp_p_plus_fq(mp, p,unity,pp,mp_proto_dependent,mp_dependent);
21587 } else { 
21588   q=p;
21589   while ( info(q)!=null ) {
21590     value(q)=mp_round_fraction(mp, value(q)); q=link(q);
21591   }
21592   t=mp_proto_dependent; p=mp_p_plus_q(mp, p,pp,t);
21593 }
21594 mp->watch_coefs=true;
21595
21596 @ Our next goal is to process type declarations. For this purpose it's
21597 convenient to have a procedure that scans a $\langle\,$declared
21598 variable$\,\rangle$ and returns the corresponding token list. After the
21599 following procedure has acted, the token after the declared variable
21600 will have been scanned, so it will appear in |cur_cmd|, |cur_mod|,
21601 and~|cur_sym|.
21602
21603 @<Declare the function called |scan_declared_variable|@>=
21604 pointer mp_scan_declared_variable (MP mp) {
21605   pointer x; /* hash address of the variable's root */
21606   pointer h,t; /* head and tail of the token list to be returned */
21607   pointer l; /* hash address of left bracket */
21608   mp_get_symbol(mp); x=mp->cur_sym;
21609   if ( mp->cur_cmd!=tag_token ) mp_clear_symbol(mp, x,false);
21610   h=mp_get_avail(mp); info(h)=x; t=h;
21611   while (1) { 
21612     mp_get_x_next(mp);
21613     if ( mp->cur_sym==0 ) break;
21614     if ( mp->cur_cmd!=tag_token ) if ( mp->cur_cmd!=internal_quantity)  {
21615       if ( mp->cur_cmd==left_bracket ) {
21616         @<Descend past a collective subscript@>;
21617       } else {
21618         break;
21619       }
21620     }
21621     link(t)=mp_get_avail(mp); t=link(t); info(t)=mp->cur_sym;
21622   }
21623   if ( eq_type(x)!=tag_token ) mp_clear_symbol(mp, x,false);
21624   if ( equiv(x)==null ) mp_new_root(mp, x);
21625   return h;
21626 }
21627
21628 @ If the subscript isn't collective, we don't accept it as part of the
21629 declared variable.
21630
21631 @<Descend past a collective subscript@>=
21632
21633   l=mp->cur_sym; mp_get_x_next(mp);
21634   if ( mp->cur_cmd!=right_bracket ) {
21635     mp_back_input(mp); mp->cur_sym=l; mp->cur_cmd=left_bracket; break;
21636   } else {
21637     mp->cur_sym=collective_subscript;
21638   }
21639 }
21640
21641 @ Type declarations are introduced by the following primitive operations.
21642
21643 @<Put each...@>=
21644 mp_primitive(mp, "numeric",type_name,mp_numeric_type);
21645 @:numeric_}{\&{numeric} primitive@>
21646 mp_primitive(mp, "string",type_name,mp_string_type);
21647 @:string_}{\&{string} primitive@>
21648 mp_primitive(mp, "boolean",type_name,mp_boolean_type);
21649 @:boolean_}{\&{boolean} primitive@>
21650 mp_primitive(mp, "path",type_name,mp_path_type);
21651 @:path_}{\&{path} primitive@>
21652 mp_primitive(mp, "pen",type_name,mp_pen_type);
21653 @:pen_}{\&{pen} primitive@>
21654 mp_primitive(mp, "picture",type_name,mp_picture_type);
21655 @:picture_}{\&{picture} primitive@>
21656 mp_primitive(mp, "transform",type_name,mp_transform_type);
21657 @:transform_}{\&{transform} primitive@>
21658 mp_primitive(mp, "color",type_name,mp_color_type);
21659 @:color_}{\&{color} primitive@>
21660 mp_primitive(mp, "rgbcolor",type_name,mp_color_type);
21661 @:color_}{\&{rgbcolor} primitive@>
21662 mp_primitive(mp, "cmykcolor",type_name,mp_cmykcolor_type);
21663 @:color_}{\&{cmykcolor} primitive@>
21664 mp_primitive(mp, "pair",type_name,mp_pair_type);
21665 @:pair_}{\&{pair} primitive@>
21666
21667 @ @<Cases of |print_cmd...@>=
21668 case type_name: mp_print_type(mp, m); break;
21669
21670 @ Now we are ready to handle type declarations, assuming that a
21671 |type_name| has just been scanned.
21672
21673 @<Declare action procedures for use by |do_statement|@>=
21674 void mp_do_type_declaration (MP mp) ;
21675
21676 @ @c
21677 void mp_do_type_declaration (MP mp) {
21678   small_number t; /* the type being declared */
21679   pointer p; /* token list for a declared variable */
21680   pointer q; /* value node for the variable */
21681   if ( mp->cur_mod>=mp_transform_type ) 
21682     t=mp->cur_mod;
21683   else 
21684     t=mp->cur_mod+unknown_tag;
21685   do {  
21686     p=mp_scan_declared_variable(mp);
21687     mp_flush_variable(mp, equiv(info(p)),link(p),false);
21688     q=mp_find_variable(mp, p);
21689     if ( q!=null ) { 
21690       type(q)=t; value(q)=null; 
21691     } else  { 
21692       print_err("Declared variable conflicts with previous vardef");
21693 @.Declared variable conflicts...@>
21694       help2("You can't use, e.g., `numeric foo[]' after `vardef foo'.")
21695            ("Proceed, and I'll ignore the illegal redeclaration.");
21696       mp_put_get_error(mp);
21697     }
21698     mp_flush_list(mp, p);
21699     if ( mp->cur_cmd<comma ) {
21700       @<Flush spurious symbols after the declared variable@>;
21701     }
21702   } while (! end_of_statement);
21703 }
21704
21705 @ @<Flush spurious symbols after the declared variable@>=
21706
21707   print_err("Illegal suffix of declared variable will be flushed");
21708 @.Illegal suffix...flushed@>
21709   help5("Variables in declarations must consist entirely of")
21710     ("names and collective subscripts, e.g., `x[]a'.")
21711     ("Are you trying to use a reserved word in a variable name?")
21712     ("I'm going to discard the junk I found here,")
21713     ("up to the next comma or the end of the declaration.");
21714   if ( mp->cur_cmd==numeric_token )
21715     mp->help_line[2]="Explicit subscripts like `x15a' aren't permitted.";
21716   mp_put_get_error(mp); mp->scanner_status=flushing;
21717   do {  
21718     get_t_next;
21719     @<Decrease the string reference count...@>;
21720   } while (mp->cur_cmd<comma); /* either |end_of_statement| or |cur_cmd=comma| */
21721   mp->scanner_status=normal;
21722 }
21723
21724 @ \MP's |main_control| procedure just calls |do_statement| repeatedly
21725 until coming to the end of the user's program.
21726 Each execution of |do_statement| concludes with
21727 |cur_cmd=semicolon|, |end_group|, or |stop|.
21728
21729 @c void mp_main_control (MP mp) { 
21730   do {  
21731     mp_do_statement(mp);
21732     if ( mp->cur_cmd==end_group ) {
21733       print_err("Extra `endgroup'");
21734 @.Extra `endgroup'@>
21735       help2("I'm not currently working on a `begingroup',")
21736         ("so I had better not try to end anything.");
21737       mp_flush_error(mp, 0);
21738     }
21739   } while (mp->cur_cmd!=stop);
21740 }
21741 int mp_run (MP mp) {
21742   @<Install and test the non-local jump buffer@>;
21743   mp_main_control(mp); /* come to life */
21744   mp_final_cleanup(mp); /* prepare for death */
21745   mp_close_files_and_terminate(mp);
21746   return mp->history;
21747 }
21748 char * mp_mplib_version (MP mp) {
21749   assert(mp);
21750   return mplib_version;
21751 }
21752 char * mp_metapost_version (MP mp) {
21753   assert(mp);
21754   return metapost_version;
21755 }
21756
21757 @ @<Exported function headers@>=
21758 int mp_run (MP mp);
21759 char * mp_mplib_version (MP mp);
21760 char * mp_metapost_version (MP mp);
21761
21762 @ @<Put each...@>=
21763 mp_primitive(mp, "end",stop,0);
21764 @:end_}{\&{end} primitive@>
21765 mp_primitive(mp, "dump",stop,1);
21766 @:dump_}{\&{dump} primitive@>
21767
21768 @ @<Cases of |print_cmd...@>=
21769 case stop:
21770   if ( m==0 ) mp_print(mp, "end");
21771   else mp_print(mp, "dump");
21772   break;
21773
21774 @* \[41] Commands.
21775 Let's turn now to statements that are classified as ``commands'' because
21776 of their imperative nature. We'll begin with simple ones, so that it
21777 will be clear how to hook command processing into the |do_statement| routine;
21778 then we'll tackle the tougher commands.
21779
21780 Here's one of the simplest:
21781
21782 @<Cases of |do_statement|...@>=
21783 case mp_random_seed: mp_do_random_seed(mp);  break;
21784
21785 @ @<Declare action procedures for use by |do_statement|@>=
21786 void mp_do_random_seed (MP mp) ;
21787
21788 @ @c void mp_do_random_seed (MP mp) { 
21789   mp_get_x_next(mp);
21790   if ( mp->cur_cmd!=assignment ) {
21791     mp_missing_err(mp, ":=");
21792 @.Missing `:='@>
21793     help1("Always say `randomseed:=<numeric expression>'.");
21794     mp_back_error(mp);
21795   };
21796   mp_get_x_next(mp); mp_scan_expression(mp);
21797   if ( mp->cur_type!=mp_known ) {
21798     exp_err("Unknown value will be ignored");
21799 @.Unknown value...ignored@>
21800     help2("Your expression was too random for me to handle,")
21801       ("so I won't change the random seed just now.");
21802     mp_put_get_flush_error(mp, 0);
21803   } else {
21804    @<Initialize the random seed to |cur_exp|@>;
21805   }
21806 }
21807
21808 @ @<Initialize the random seed to |cur_exp|@>=
21809
21810   mp_init_randoms(mp, mp->cur_exp);
21811   if ( mp->selector>=log_only && mp->selector<write_file) {
21812     mp->old_setting=mp->selector; mp->selector=log_only;
21813     mp_print_nl(mp, "{randomseed:="); 
21814     mp_print_scaled(mp, mp->cur_exp); 
21815     mp_print_char(mp, '}');
21816     mp_print_nl(mp, ""); mp->selector=mp->old_setting;
21817   }
21818 }
21819
21820 @ And here's another simple one (somewhat different in flavor):
21821
21822 @<Cases of |do_statement|...@>=
21823 case mode_command: 
21824   mp_print_ln(mp); mp->interaction=mp->cur_mod;
21825   @<Initialize the print |selector| based on |interaction|@>;
21826   if ( mp->log_opened ) mp->selector=mp->selector+2;
21827   mp_get_x_next(mp);
21828   break;
21829
21830 @ @<Put each...@>=
21831 mp_primitive(mp, "batchmode",mode_command,mp_batch_mode);
21832 @:mp_batch_mode_}{\&{batchmode} primitive@>
21833 mp_primitive(mp, "nonstopmode",mode_command,mp_nonstop_mode);
21834 @:mp_nonstop_mode_}{\&{nonstopmode} primitive@>
21835 mp_primitive(mp, "scrollmode",mode_command,mp_scroll_mode);
21836 @:mp_scroll_mode_}{\&{scrollmode} primitive@>
21837 mp_primitive(mp, "errorstopmode",mode_command,mp_error_stop_mode);
21838 @:mp_error_stop_mode_}{\&{errorstopmode} primitive@>
21839
21840 @ @<Cases of |print_cmd_mod|...@>=
21841 case mode_command: 
21842   switch (m) {
21843   case mp_batch_mode: mp_print(mp, "batchmode"); break;
21844   case mp_nonstop_mode: mp_print(mp, "nonstopmode"); break;
21845   case mp_scroll_mode: mp_print(mp, "scrollmode"); break;
21846   default: mp_print(mp, "errorstopmode"); break;
21847   }
21848   break;
21849
21850 @ The `\&{inner}' and `\&{outer}' commands are only slightly harder.
21851
21852 @<Cases of |do_statement|...@>=
21853 case protection_command: mp_do_protection(mp); break;
21854
21855 @ @<Put each...@>=
21856 mp_primitive(mp, "inner",protection_command,0);
21857 @:inner_}{\&{inner} primitive@>
21858 mp_primitive(mp, "outer",protection_command,1);
21859 @:outer_}{\&{outer} primitive@>
21860
21861 @ @<Cases of |print_cmd...@>=
21862 case protection_command: 
21863   if ( m==0 ) mp_print(mp, "inner");
21864   else mp_print(mp, "outer");
21865   break;
21866
21867 @ @<Declare action procedures for use by |do_statement|@>=
21868 void mp_do_protection (MP mp) ;
21869
21870 @ @c void mp_do_protection (MP mp) {
21871   int m; /* 0 to unprotect, 1 to protect */
21872   halfword t; /* the |eq_type| before we change it */
21873   m=mp->cur_mod;
21874   do {  
21875     mp_get_symbol(mp); t=eq_type(mp->cur_sym);
21876     if ( m==0 ) { 
21877       if ( t>=outer_tag ) 
21878         eq_type(mp->cur_sym)=t-outer_tag;
21879     } else if ( t<outer_tag ) {
21880       eq_type(mp->cur_sym)=t+outer_tag;
21881     }
21882     mp_get_x_next(mp);
21883   } while (mp->cur_cmd==comma);
21884 }
21885
21886 @ \MP\ never defines the tokens `\.(' and `\.)' to be primitives, but
21887 plain \MP\ begins with the declaration `\&{delimiters} \.{()}'. Such a
21888 declaration assigns the command code |left_delimiter| to `\.{(}' and
21889 |right_delimiter| to `\.{)}'; the |equiv| of each delimiter is the
21890 hash address of its mate.
21891
21892 @<Cases of |do_statement|...@>=
21893 case delimiters: mp_def_delims(mp); break;
21894
21895 @ @<Declare action procedures for use by |do_statement|@>=
21896 void mp_def_delims (MP mp) ;
21897
21898 @ @c void mp_def_delims (MP mp) {
21899   pointer l_delim,r_delim; /* the new delimiter pair */
21900   mp_get_clear_symbol(mp); l_delim=mp->cur_sym;
21901   mp_get_clear_symbol(mp); r_delim=mp->cur_sym;
21902   eq_type(l_delim)=left_delimiter; equiv(l_delim)=r_delim;
21903   eq_type(r_delim)=right_delimiter; equiv(r_delim)=l_delim;
21904   mp_get_x_next(mp);
21905 }
21906
21907 @ Here is a procedure that is called when \MP\ has reached a point
21908 where some right delimiter is mandatory.
21909
21910 @<Declare the procedure called |check_delimiter|@>=
21911 void mp_check_delimiter (MP mp,pointer l_delim, pointer r_delim) {
21912   if ( mp->cur_cmd==right_delimiter ) 
21913     if ( mp->cur_mod==l_delim ) 
21914       return;
21915   if ( mp->cur_sym!=r_delim ) {
21916      mp_missing_err(mp, str(text(r_delim)));
21917 @.Missing `)'@>
21918     help2("I found no right delimiter to match a left one. So I've")
21919       ("put one in, behind the scenes; this may fix the problem.");
21920     mp_back_error(mp);
21921   } else { 
21922     print_err("The token `"); mp_print_text(r_delim);
21923 @.The token...delimiter@>
21924     mp_print(mp, "' is no longer a right delimiter");
21925     help3("Strange: This token has lost its former meaning!")
21926       ("I'll read it as a right delimiter this time;")
21927       ("but watch out, I'll probably miss it later.");
21928     mp_error(mp);
21929   }
21930 }
21931
21932 @ The next four commands save or change the values associated with tokens.
21933
21934 @<Cases of |do_statement|...@>=
21935 case save_command: 
21936   do {  
21937     mp_get_symbol(mp); mp_save_variable(mp, mp->cur_sym); mp_get_x_next(mp);
21938   } while (mp->cur_cmd==comma);
21939   break;
21940 case interim_command: mp_do_interim(mp); break;
21941 case let_command: mp_do_let(mp); break;
21942 case new_internal: mp_do_new_internal(mp); break;
21943
21944 @ @<Declare action procedures for use by |do_statement|@>=
21945 void mp_do_statement (MP mp);
21946 void mp_do_interim (MP mp);
21947
21948 @ @c void mp_do_interim (MP mp) { 
21949   mp_get_x_next(mp);
21950   if ( mp->cur_cmd!=internal_quantity ) {
21951      print_err("The token `");
21952 @.The token...quantity@>
21953     if ( mp->cur_sym==0 ) mp_print(mp, "(%CAPSULE)");
21954     else mp_print_text(mp->cur_sym);
21955     mp_print(mp, "' isn't an internal quantity");
21956     help1("Something like `tracingonline' should follow `interim'.");
21957     mp_back_error(mp);
21958   } else { 
21959     mp_save_internal(mp, mp->cur_mod); mp_back_input(mp);
21960   }
21961   mp_do_statement(mp);
21962 }
21963
21964 @ The following procedure is careful not to undefine the left-hand symbol
21965 too soon, lest commands like `{\tt let x=x}' have a surprising effect.
21966
21967 @<Declare action procedures for use by |do_statement|@>=
21968 void mp_do_let (MP mp) ;
21969
21970 @ @c void mp_do_let (MP mp) {
21971   pointer l; /* hash location of the left-hand symbol */
21972   mp_get_symbol(mp); l=mp->cur_sym; mp_get_x_next(mp);
21973   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
21974      mp_missing_err(mp, "=");
21975 @.Missing `='@>
21976     help3("You should have said `let symbol = something'.")
21977       ("But don't worry; I'll pretend that an equals sign")
21978       ("was present. The next token I read will be `something'.");
21979     mp_back_error(mp);
21980   }
21981   mp_get_symbol(mp);
21982   switch (mp->cur_cmd) {
21983   case defined_macro: case secondary_primary_macro:
21984   case tertiary_secondary_macro: case expression_tertiary_macro: 
21985     add_mac_ref(mp->cur_mod);
21986     break;
21987   default: 
21988     break;
21989   }
21990   mp_clear_symbol(mp, l,false); eq_type(l)=mp->cur_cmd;
21991   if ( mp->cur_cmd==tag_token ) equiv(l)=null;
21992   else equiv(l)=mp->cur_mod;
21993   mp_get_x_next(mp);
21994 }
21995
21996 @ @<Declarations@>=
21997 void mp_grow_internals (MP mp, int l);
21998 void mp_do_new_internal (MP mp) ;
21999
22000 @ @c
22001 void mp_grow_internals (MP mp, int l) {
22002   scaled *internal;
22003   char * *int_name; 
22004   int k;
22005   if ( hash_end+l>max_halfword ) {
22006     mp_confusion(mp, "out of memory space"); /* can't be reached */
22007   }
22008   int_name = xmalloc ((l+1),sizeof(char *));
22009   internal = xmalloc ((l+1),sizeof(scaled));
22010   for (k=0;k<=l; k++ ) { 
22011     if (k<=mp->max_internal) {
22012       internal[k]=mp->internal[k]; 
22013       int_name[k]=mp->int_name[k]; 
22014     } else {
22015       internal[k]=0; 
22016       int_name[k]=NULL; 
22017     }
22018   }
22019   xfree(mp->internal); xfree(mp->int_name);
22020   mp->int_name = int_name;
22021   mp->internal = internal;
22022   mp->max_internal = l;
22023 }
22024
22025
22026 void mp_do_new_internal (MP mp) { 
22027   do {  
22028     if ( mp->int_ptr==mp->max_internal ) {
22029       mp_grow_internals(mp, (mp->max_internal + (mp->max_internal>>2)));
22030     }
22031     mp_get_clear_symbol(mp); incr(mp->int_ptr);
22032     eq_type(mp->cur_sym)=internal_quantity; 
22033     equiv(mp->cur_sym)=mp->int_ptr;
22034     if(mp->int_name[mp->int_ptr]!=NULL)
22035       xfree(mp->int_name[mp->int_ptr]);
22036     mp->int_name[mp->int_ptr]=str(text(mp->cur_sym)); 
22037     mp->internal[mp->int_ptr]=0;
22038     mp_get_x_next(mp);
22039   } while (mp->cur_cmd==comma);
22040 }
22041
22042 @ @<Dealloc variables@>=
22043 for (k=0;k<=mp->max_internal;k++) {
22044    xfree(mp->int_name[k]);
22045 }
22046 xfree(mp->internal); 
22047 xfree(mp->int_name); 
22048
22049
22050 @ The various `\&{show}' commands are distinguished by modifier fields
22051 in the usual way.
22052
22053 @d show_token_code 0 /* show the meaning of a single token */
22054 @d show_stats_code 1 /* show current memory and string usage */
22055 @d show_code 2 /* show a list of expressions */
22056 @d show_var_code 3 /* show a variable and its descendents */
22057 @d show_dependencies_code 4 /* show dependent variables in terms of independents */
22058
22059 @<Put each...@>=
22060 mp_primitive(mp, "showtoken",show_command,show_token_code);
22061 @:show_token_}{\&{showtoken} primitive@>
22062 mp_primitive(mp, "showstats",show_command,show_stats_code);
22063 @:show_stats_}{\&{showstats} primitive@>
22064 mp_primitive(mp, "show",show_command,show_code);
22065 @:show_}{\&{show} primitive@>
22066 mp_primitive(mp, "showvariable",show_command,show_var_code);
22067 @:show_var_}{\&{showvariable} primitive@>
22068 mp_primitive(mp, "showdependencies",show_command,show_dependencies_code);
22069 @:show_dependencies_}{\&{showdependencies} primitive@>
22070
22071 @ @<Cases of |print_cmd...@>=
22072 case show_command: 
22073   switch (m) {
22074   case show_token_code:mp_print(mp, "showtoken"); break;
22075   case show_stats_code:mp_print(mp, "showstats"); break;
22076   case show_code:mp_print(mp, "show"); break;
22077   case show_var_code:mp_print(mp, "showvariable"); break;
22078   default: mp_print(mp, "showdependencies"); break;
22079   }
22080   break;
22081
22082 @ @<Cases of |do_statement|...@>=
22083 case show_command:mp_do_show_whatever(mp); break;
22084
22085 @ The value of |cur_mod| controls the |verbosity| in the |print_exp| routine:
22086 if it's |show_code|, complicated structures are abbreviated, otherwise
22087 they aren't.
22088
22089 @<Declare action procedures for use by |do_statement|@>=
22090 void mp_do_show (MP mp) ;
22091
22092 @ @c void mp_do_show (MP mp) { 
22093   do {  
22094     mp_get_x_next(mp); mp_scan_expression(mp);
22095     mp_print_nl(mp, ">> ");
22096 @.>>@>
22097     mp_print_exp(mp, null,2); mp_flush_cur_exp(mp, 0);
22098   } while (mp->cur_cmd==comma);
22099 }
22100
22101 @ @<Declare action procedures for use by |do_statement|@>=
22102 void mp_disp_token (MP mp) ;
22103
22104 @ @c void mp_disp_token (MP mp) { 
22105   mp_print_nl(mp, "> ");
22106 @.>\relax@>
22107   if ( mp->cur_sym==0 ) {
22108     @<Show a numeric or string or capsule token@>;
22109   } else { 
22110     mp_print_text(mp->cur_sym); mp_print_char(mp, '=');
22111     if ( eq_type(mp->cur_sym)>=outer_tag ) mp_print(mp, "(outer) ");
22112     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod);
22113     if ( mp->cur_cmd==defined_macro ) {
22114       mp_print_ln(mp); mp_show_macro(mp, mp->cur_mod,null,100000);
22115     } /* this avoids recursion between |show_macro| and |print_cmd_mod| */
22116 @^recursion@>
22117   }
22118 }
22119
22120 @ @<Show a numeric or string or capsule token@>=
22121
22122   if ( mp->cur_cmd==numeric_token ) {
22123     mp_print_scaled(mp, mp->cur_mod);
22124   } else if ( mp->cur_cmd==capsule_token ) {
22125     mp_print_capsule(mp,mp->cur_mod);
22126   } else  { 
22127     mp_print_char(mp, '"'); 
22128     mp_print_str(mp, mp->cur_mod); mp_print_char(mp, '"');
22129     delete_str_ref(mp->cur_mod);
22130   }
22131 }
22132
22133 @ The following cases of |print_cmd_mod| might arise in connection
22134 with |disp_token|, although they don't correspond to any
22135 primitive tokens.
22136
22137 @<Cases of |print_cmd_...@>=
22138 case left_delimiter:
22139 case right_delimiter: 
22140   if ( c==left_delimiter ) mp_print(mp, "left");
22141   else mp_print(mp, "right");
22142   mp_print(mp, " delimiter that matches "); 
22143   mp_print_text(m);
22144   break;
22145 case tag_token:
22146   if ( m==null ) mp_print(mp, "tag");
22147    else mp_print(mp, "variable");
22148    break;
22149 case defined_macro: 
22150    mp_print(mp, "macro:");
22151    break;
22152 case secondary_primary_macro:
22153 case tertiary_secondary_macro:
22154 case expression_tertiary_macro:
22155   mp_print_cmd_mod(mp, macro_def,c); 
22156   mp_print(mp, "'d macro:");
22157   mp_print_ln(mp); mp_show_token_list(mp, link(link(m)),null,1000,0);
22158   break;
22159 case repeat_loop:
22160   mp_print(mp, "[repeat the loop]");
22161   break;
22162 case internal_quantity:
22163   mp_print(mp, mp->int_name[m]);
22164   break;
22165
22166 @ @<Declare action procedures for use by |do_statement|@>=
22167 void mp_do_show_token (MP mp) ;
22168
22169 @ @c void mp_do_show_token (MP mp) { 
22170   do {  
22171     get_t_next; mp_disp_token(mp);
22172     mp_get_x_next(mp);
22173   } while (mp->cur_cmd==comma);
22174 }
22175
22176 @ @<Declare action procedures for use by |do_statement|@>=
22177 void mp_do_show_stats (MP mp) ;
22178
22179 @ @c void mp_do_show_stats (MP mp) { 
22180   mp_print_nl(mp, "Memory usage ");
22181 @.Memory usage...@>
22182   mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used);
22183   if ( false )
22184     mp_print(mp, "unknown");
22185   mp_print(mp, " ("); mp_print_int(mp, mp->hi_mem_min-mp->lo_mem_max-1);
22186   mp_print(mp, " still untouched)"); mp_print_ln(mp);
22187   mp_print_nl(mp, "String usage ");
22188   mp_print_int(mp, mp->strs_in_use-mp->init_str_use);
22189   mp_print_char(mp, '&'); mp_print_int(mp, mp->pool_in_use-mp->init_pool_ptr);
22190   if ( false )
22191     mp_print(mp, "unknown");
22192   mp_print(mp, " (");
22193   mp_print_int(mp, mp->max_strings-1-mp->strs_used_up); mp_print_char(mp, '&');
22194   mp_print_int(mp, mp->pool_size-mp->pool_ptr); 
22195   mp_print(mp, " now untouched)"); mp_print_ln(mp);
22196   mp_get_x_next(mp);
22197 }
22198
22199 @ Here's a recursive procedure that gives an abbreviated account
22200 of a variable, for use by |do_show_var|.
22201
22202 @<Declare action procedures for use by |do_statement|@>=
22203 void mp_disp_var (MP mp,pointer p) ;
22204
22205 @ @c void mp_disp_var (MP mp,pointer p) {
22206   pointer q; /* traverses attributes and subscripts */
22207   int n; /* amount of macro text to show */
22208   if ( type(p)==mp_structured )  {
22209     @<Descend the structure@>;
22210   } else if ( type(p)>=mp_unsuffixed_macro ) {
22211     @<Display a variable macro@>;
22212   } else if ( type(p)!=undefined ){ 
22213     mp_print_nl(mp, ""); mp_print_variable_name(mp, p); 
22214     mp_print_char(mp, '=');
22215     mp_print_exp(mp, p,0);
22216   }
22217 }
22218
22219 @ @<Descend the structure@>=
22220
22221   q=attr_head(p);
22222   do {  mp_disp_var(mp, q); q=link(q); } while (q!=end_attr);
22223   q=subscr_head(p);
22224   while ( name_type(q)==mp_subscr ) { 
22225     mp_disp_var(mp, q); q=link(q);
22226   }
22227 }
22228
22229 @ @<Display a variable macro@>=
22230
22231   mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22232   if ( type(p)>mp_unsuffixed_macro ) 
22233     mp_print(mp, "@@#"); /* |suffixed_macro| */
22234   mp_print(mp, "=macro:");
22235   if ( (int)mp->file_offset>=mp->max_print_line-20 ) n=5;
22236   else n=mp->max_print_line-mp->file_offset-15;
22237   mp_show_macro(mp, value(p),null,n);
22238 }
22239
22240 @ @<Declare action procedures for use by |do_statement|@>=
22241 void mp_do_show_var (MP mp) ;
22242
22243 @ @c void mp_do_show_var (MP mp) { 
22244   do {  
22245     get_t_next;
22246     if ( mp->cur_sym>0 ) if ( mp->cur_sym<=hash_end )
22247       if ( mp->cur_cmd==tag_token ) if ( mp->cur_mod!=null ) {
22248       mp_disp_var(mp, mp->cur_mod); goto DONE;
22249     }
22250    mp_disp_token(mp);
22251   DONE:
22252    mp_get_x_next(mp);
22253   } while (mp->cur_cmd==comma);
22254 }
22255
22256 @ @<Declare action procedures for use by |do_statement|@>=
22257 void mp_do_show_dependencies (MP mp) ;
22258
22259 @ @c void mp_do_show_dependencies (MP mp) {
22260   pointer p; /* link that runs through all dependencies */
22261   p=link(dep_head);
22262   while ( p!=dep_head ) {
22263     if ( mp_interesting(mp, p) ) {
22264       mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22265       if ( type(p)==mp_dependent ) mp_print_char(mp, '=');
22266       else mp_print(mp, " = "); /* extra spaces imply proto-dependency */
22267       mp_print_dependency(mp, dep_list(p),type(p));
22268     }
22269     p=dep_list(p);
22270     while ( info(p)!=null ) p=link(p);
22271     p=link(p);
22272   }
22273   mp_get_x_next(mp);
22274 }
22275
22276 @ Finally we are ready for the procedure that governs all of the
22277 show commands.
22278
22279 @<Declare action procedures for use by |do_statement|@>=
22280 void mp_do_show_whatever (MP mp) ;
22281
22282 @ @c void mp_do_show_whatever (MP mp) { 
22283   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
22284   switch (mp->cur_mod) {
22285   case show_token_code:mp_do_show_token(mp); break;
22286   case show_stats_code:mp_do_show_stats(mp); break;
22287   case show_code:mp_do_show(mp); break;
22288   case show_var_code:mp_do_show_var(mp); break;
22289   case show_dependencies_code:mp_do_show_dependencies(mp); break;
22290   } /* there are no other cases */
22291   if ( mp->internal[mp_showstopping]>0 ){ 
22292     print_err("OK");
22293 @.OK@>
22294     if ( mp->interaction<mp_error_stop_mode ) { 
22295       help0; decr(mp->error_count);
22296     } else {
22297       help1("This isn't an error message; I'm just showing something.");
22298     }
22299     if ( mp->cur_cmd==semicolon ) mp_error(mp);
22300      else mp_put_get_error(mp);
22301   }
22302 }
22303
22304 @ The `\&{addto}' command needs the following additional primitives:
22305
22306 @d double_path_code 0 /* command modifier for `\&{doublepath}' */
22307 @d contour_code 1 /* command modifier for `\&{contour}' */
22308 @d also_code 2 /* command modifier for `\&{also}' */
22309
22310 @ Pre and postscripts need two new identifiers:
22311
22312 @d with_pre_script 11
22313 @d with_post_script 13
22314
22315 @<Put each...@>=
22316 mp_primitive(mp, "doublepath",thing_to_add,double_path_code);
22317 @:double_path_}{\&{doublepath} primitive@>
22318 mp_primitive(mp, "contour",thing_to_add,contour_code);
22319 @:contour_}{\&{contour} primitive@>
22320 mp_primitive(mp, "also",thing_to_add,also_code);
22321 @:also_}{\&{also} primitive@>
22322 mp_primitive(mp, "withpen",with_option,mp_pen_type);
22323 @:with_pen_}{\&{withpen} primitive@>
22324 mp_primitive(mp, "dashed",with_option,mp_picture_type);
22325 @:dashed_}{\&{dashed} primitive@>
22326 mp_primitive(mp, "withprescript",with_option,with_pre_script);
22327 @:with_pre_script_}{\&{withprescript} primitive@>
22328 mp_primitive(mp, "withpostscript",with_option,with_post_script);
22329 @:with_post_script_}{\&{withpostscript} primitive@>
22330 mp_primitive(mp, "withoutcolor",with_option,mp_no_model);
22331 @:with_color_}{\&{withoutcolor} primitive@>
22332 mp_primitive(mp, "withgreyscale",with_option,mp_grey_model);
22333 @:with_color_}{\&{withgreyscale} primitive@>
22334 mp_primitive(mp, "withcolor",with_option,mp_uninitialized_model);
22335 @:with_color_}{\&{withcolor} primitive@>
22336 /*  \&{withrgbcolor} is an alias for \&{withcolor} */
22337 mp_primitive(mp, "withrgbcolor",with_option,mp_rgb_model);
22338 @:with_color_}{\&{withrgbcolor} primitive@>
22339 mp_primitive(mp, "withcmykcolor",with_option,mp_cmyk_model);
22340 @:with_color_}{\&{withcmykcolor} primitive@>
22341
22342 @ @<Cases of |print_cmd...@>=
22343 case thing_to_add:
22344   if ( m==contour_code ) mp_print(mp, "contour");
22345   else if ( m==double_path_code ) mp_print(mp, "doublepath");
22346   else mp_print(mp, "also");
22347   break;
22348 case with_option:
22349   if ( m==mp_pen_type ) mp_print(mp, "withpen");
22350   else if ( m==with_pre_script ) mp_print(mp, "withprescript");
22351   else if ( m==with_post_script ) mp_print(mp, "withpostscript");
22352   else if ( m==mp_no_model ) mp_print(mp, "withoutcolor");
22353   else if ( m==mp_rgb_model ) mp_print(mp, "withrgbcolor");
22354   else if ( m==mp_uninitialized_model ) mp_print(mp, "withcolor");
22355   else if ( m==mp_cmyk_model ) mp_print(mp, "withcmykcolor");
22356   else if ( m==mp_grey_model ) mp_print(mp, "withgreyscale");
22357   else mp_print(mp, "dashed");
22358   break;
22359
22360 @ The |scan_with_list| procedure parses a $\langle$with list$\rangle$ and
22361 updates the list of graphical objects starting at |p|.  Each $\langle$with
22362 clause$\rangle$ updates all graphical objects whose |type| is compatible.
22363 Other objects are ignored.
22364
22365 @<Declare action procedures for use by |do_statement|@>=
22366 void mp_scan_with_list (MP mp,pointer p) ;
22367
22368 @ @c void mp_scan_with_list (MP mp,pointer p) {
22369   small_number t; /* |cur_mod| of the |with_option| (should match |cur_type|) */
22370   pointer q; /* for list manipulation */
22371   int old_setting; /* saved |selector| setting */
22372   pointer k; /* for finding the near-last item in a list  */
22373   str_number s; /* for string cleanup after combining  */
22374   pointer cp,pp,dp,ap,bp;
22375     /* objects being updated; |void| initially; |null| to suppress update */
22376   cp=mp_void; pp=mp_void; dp=mp_void; ap=mp_void; bp=mp_void;
22377   k=0;
22378   while ( mp->cur_cmd==with_option ){ 
22379     t=mp->cur_mod;
22380     mp_get_x_next(mp);
22381     if ( t!=mp_no_model ) mp_scan_expression(mp);
22382     if (((t==with_pre_script)&&(mp->cur_type!=mp_string_type))||
22383      ((t==with_post_script)&&(mp->cur_type!=mp_string_type))||
22384      ((t==mp_uninitialized_model)&&
22385         ((mp->cur_type!=mp_cmykcolor_type)&&(mp->cur_type!=mp_color_type)
22386           &&(mp->cur_type!=mp_known)&&(mp->cur_type!=mp_boolean_type)))||
22387      ((t==mp_cmyk_model)&&(mp->cur_type!=mp_cmykcolor_type))||
22388      ((t==mp_rgb_model)&&(mp->cur_type!=mp_color_type))||
22389      ((t==mp_grey_model)&&(mp->cur_type!=mp_known))||
22390      ((t==mp_pen_type)&&(mp->cur_type!=t))||
22391      ((t==mp_picture_type)&&(mp->cur_type!=t)) ) {
22392       @<Complain about improper type@>;
22393     } else if ( t==mp_uninitialized_model ) {
22394       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22395       if ( cp!=null )
22396         @<Transfer a color from the current expression to object~|cp|@>;
22397       mp_flush_cur_exp(mp, 0);
22398     } else if ( t==mp_rgb_model ) {
22399       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22400       if ( cp!=null )
22401         @<Transfer a rgbcolor from the current expression to object~|cp|@>;
22402       mp_flush_cur_exp(mp, 0);
22403     } else if ( t==mp_cmyk_model ) {
22404       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22405       if ( cp!=null )
22406         @<Transfer a cmykcolor from the current expression to object~|cp|@>;
22407       mp_flush_cur_exp(mp, 0);
22408     } else if ( t==mp_grey_model ) {
22409       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22410       if ( cp!=null )
22411         @<Transfer a greyscale from the current expression to object~|cp|@>;
22412       mp_flush_cur_exp(mp, 0);
22413     } else if ( t==mp_no_model ) {
22414       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22415       if ( cp!=null )
22416         @<Transfer a noncolor from the current expression to object~|cp|@>;
22417     } else if ( t==mp_pen_type ) {
22418       if ( pp==mp_void ) @<Make |pp| an object in list~|p| that needs a pen@>;
22419       if ( pp!=null ) {
22420         if ( pen_p(pp)!=null ) mp_toss_knot_list(mp, pen_p(pp));
22421         pen_p(pp)=mp->cur_exp; mp->cur_type=mp_vacuous;
22422       }
22423     } else if ( t==with_pre_script ) {
22424       if ( ap==mp_void )
22425         ap=p;
22426       while ( (ap!=null)&&(! has_color(ap)) )
22427          ap=link(ap);
22428       if ( ap!=null ) {
22429         if ( pre_script(ap)!=null ) { /*  build a new,combined string  */
22430           s=pre_script(ap);
22431           old_setting=mp->selector;
22432               mp->selector=new_string;
22433           str_room(length(pre_script(ap))+length(mp->cur_exp)+2);
22434               mp_print_str(mp, mp->cur_exp);
22435           append_char(13);  /* a forced \ps\ newline  */
22436           mp_print_str(mp, pre_script(ap));
22437           pre_script(ap)=mp_make_string(mp);
22438           delete_str_ref(s);
22439           mp->selector=old_setting;
22440         } else {
22441           pre_script(ap)=mp->cur_exp;
22442         }
22443         mp->cur_type=mp_vacuous;
22444       }
22445     } else if ( t==with_post_script ) {
22446       if ( bp==mp_void )
22447         k=p; 
22448       bp=k;
22449       while ( link(k)!=null ) {
22450         k=link(k);
22451         if ( has_color(k) ) bp=k;
22452       }
22453       if ( bp!=null ) {
22454          if ( post_script(bp)!=null ) {
22455            s=post_script(bp);
22456            old_setting=mp->selector;
22457                mp->selector=new_string;
22458            str_room(length(post_script(bp))+length(mp->cur_exp)+2);
22459            mp_print_str(mp, post_script(bp));
22460            append_char(13); /* a forced \ps\ newline  */
22461            mp_print_str(mp, mp->cur_exp);
22462            post_script(bp)=mp_make_string(mp);
22463            delete_str_ref(s);
22464            mp->selector=old_setting;
22465          } else {
22466            post_script(bp)=mp->cur_exp;
22467          }
22468          mp->cur_type=mp_vacuous;
22469        }
22470     } else { 
22471       if ( dp==mp_void ) {
22472         @<Make |dp| a stroked node in list~|p|@>;
22473       }
22474       if ( dp!=null ) {
22475         if ( dash_p(dp)!=null ) delete_edge_ref(dash_p(dp));
22476         dash_p(dp)=mp_make_dashes(mp, mp->cur_exp);
22477         dash_scale(dp)=unity;
22478         mp->cur_type=mp_vacuous;
22479       }
22480     }
22481   }
22482   @<Copy the information from objects |cp|, |pp|, and |dp| into the rest
22483     of the list@>;
22484 };
22485
22486 @ @<Complain about improper type@>=
22487 { exp_err("Improper type");
22488 @.Improper type@>
22489 help2("Next time say `withpen <known pen expression>';")
22490   ("I'll ignore the bad `with' clause and look for another.");
22491 if ( t==with_pre_script )
22492   mp->help_line[1]="Next time say `withprescript <known string expression>';";
22493 else if ( t==with_post_script )
22494   mp->help_line[1]="Next time say `withpostscript <known string expression>';";
22495 else if ( t==mp_picture_type )
22496   mp->help_line[1]="Next time say `dashed <known picture expression>';";
22497 else if ( t==mp_uninitialized_model )
22498   mp->help_line[1]="Next time say `withcolor <known color expression>';";
22499 else if ( t==mp_rgb_model )
22500   mp->help_line[1]="Next time say `withrgbcolor <known color expression>';";
22501 else if ( t==mp_cmyk_model )
22502   mp->help_line[1]="Next time say `withcmykcolor <known cmykcolor expression>';";
22503 else if ( t==mp_grey_model )
22504   mp->help_line[1]="Next time say `withgreyscale <known numeric expression>';";;
22505 mp_put_get_flush_error(mp, 0);
22506 }
22507
22508 @ Forcing the color to be between |0| and |unity| here guarantees that no
22509 picture will ever contain a color outside the legal range for \ps\ graphics.
22510
22511 @<Transfer a color from the current expression to object~|cp|@>=
22512 { if ( mp->cur_type==mp_color_type )
22513    @<Transfer a rgbcolor from the current expression to object~|cp|@>
22514 else if ( mp->cur_type==mp_cmykcolor_type )
22515    @<Transfer a cmykcolor from the current expression to object~|cp|@>
22516 else if ( mp->cur_type==mp_known )
22517    @<Transfer a greyscale from the current expression to object~|cp|@>
22518 else if ( mp->cur_exp==false_code )
22519    @<Transfer a noncolor from the current expression to object~|cp|@>;
22520 }
22521
22522 @ @<Transfer a rgbcolor from the current expression to object~|cp|@>=
22523 { q=value(mp->cur_exp);
22524 cyan_val(cp)=0;
22525 magenta_val(cp)=0;
22526 yellow_val(cp)=0;
22527 black_val(cp)=0;
22528 red_val(cp)=value(red_part_loc(q));
22529 green_val(cp)=value(green_part_loc(q));
22530 blue_val(cp)=value(blue_part_loc(q));
22531 color_model(cp)=mp_rgb_model;
22532 if ( red_val(cp)<0 ) red_val(cp)=0;
22533 if ( green_val(cp)<0 ) green_val(cp)=0;
22534 if ( blue_val(cp)<0 ) blue_val(cp)=0;
22535 if ( red_val(cp)>unity ) red_val(cp)=unity;
22536 if ( green_val(cp)>unity ) green_val(cp)=unity;
22537 if ( blue_val(cp)>unity ) blue_val(cp)=unity;
22538 }
22539
22540 @ @<Transfer a cmykcolor from the current expression to object~|cp|@>=
22541 { q=value(mp->cur_exp);
22542 cyan_val(cp)=value(cyan_part_loc(q));
22543 magenta_val(cp)=value(magenta_part_loc(q));
22544 yellow_val(cp)=value(yellow_part_loc(q));
22545 black_val(cp)=value(black_part_loc(q));
22546 color_model(cp)=mp_cmyk_model;
22547 if ( cyan_val(cp)<0 ) cyan_val(cp)=0;
22548 if ( magenta_val(cp)<0 ) magenta_val(cp)=0;
22549 if ( yellow_val(cp)<0 ) yellow_val(cp)=0;
22550 if ( black_val(cp)<0 ) black_val(cp)=0;
22551 if ( cyan_val(cp)>unity ) cyan_val(cp)=unity;
22552 if ( magenta_val(cp)>unity ) magenta_val(cp)=unity;
22553 if ( yellow_val(cp)>unity ) yellow_val(cp)=unity;
22554 if ( black_val(cp)>unity ) black_val(cp)=unity;
22555 }
22556
22557 @ @<Transfer a greyscale from the current expression to object~|cp|@>=
22558 { q=mp->cur_exp;
22559 cyan_val(cp)=0;
22560 magenta_val(cp)=0;
22561 yellow_val(cp)=0;
22562 black_val(cp)=0;
22563 grey_val(cp)=q;
22564 color_model(cp)=mp_grey_model;
22565 if ( grey_val(cp)<0 ) grey_val(cp)=0;
22566 if ( grey_val(cp)>unity ) grey_val(cp)=unity;
22567 }
22568
22569 @ @<Transfer a noncolor from the current expression to object~|cp|@>=
22570 {
22571 cyan_val(cp)=0;
22572 magenta_val(cp)=0;
22573 yellow_val(cp)=0;
22574 black_val(cp)=0;
22575 grey_val(cp)=0;
22576 color_model(cp)=mp_no_model;
22577 }
22578
22579 @ @<Make |cp| a colored object in object list~|p|@>=
22580 { cp=p;
22581   while ( cp!=null ){ 
22582     if ( has_color(cp) ) break;
22583     cp=link(cp);
22584   }
22585 }
22586
22587 @ @<Make |pp| an object in list~|p| that needs a pen@>=
22588 { pp=p;
22589   while ( pp!=null ) {
22590     if ( has_pen(pp) ) break;
22591     pp=link(pp);
22592   }
22593 }
22594
22595 @ @<Make |dp| a stroked node in list~|p|@>=
22596 { dp=p;
22597   while ( dp!=null ) {
22598     if ( type(dp)==mp_stroked_code ) break;
22599     dp=link(dp);
22600   }
22601 }
22602
22603 @ @<Copy the information from objects |cp|, |pp|, and |dp| into...@>=
22604 @<Copy |cp|'s color into the colored objects linked to~|cp|@>;
22605 if ( pp>mp_void ) {
22606   @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>;
22607 }
22608 if ( dp>mp_void ) {
22609   @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>;
22610 }
22611
22612
22613 @ @<Copy |cp|'s color into the colored objects linked to~|cp|@>=
22614 { q=link(cp);
22615   while ( q!=null ) { 
22616     if ( has_color(q) ) {
22617       red_val(q)=red_val(cp);
22618       green_val(q)=green_val(cp);
22619       blue_val(q)=blue_val(cp);
22620       black_val(q)=black_val(cp);
22621       color_model(q)=color_model(cp);
22622     }
22623     q=link(q);
22624   }
22625 }
22626
22627 @ @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>=
22628 { q=link(pp);
22629   while ( q!=null ) {
22630     if ( has_pen(q) ) {
22631       if ( pen_p(q)!=null ) mp_toss_knot_list(mp, pen_p(q));
22632       pen_p(q)=copy_pen(pen_p(pp));
22633     }
22634     q=link(q);
22635   }
22636 }
22637
22638 @ @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>=
22639 { q=link(dp);
22640   while ( q!=null ) {
22641     if ( type(q)==mp_stroked_code ) {
22642       if ( dash_p(q)!=null ) delete_edge_ref(dash_p(q));
22643       dash_p(q)=dash_p(dp);
22644       dash_scale(q)=unity;
22645       if ( dash_p(q)!=null ) add_edge_ref(dash_p(q));
22646     }
22647     q=link(q);
22648   }
22649 }
22650
22651 @ One of the things we need to do when we've parsed an \&{addto} or
22652 similar command is find the header of a supposed \&{picture} variable, given
22653 a token list for that variable.  Since the edge structure is about to be
22654 updated, we use |private_edges| to make sure that this is possible.
22655
22656 @<Declare action procedures for use by |do_statement|@>=
22657 pointer mp_find_edges_var (MP mp, pointer t) ;
22658
22659 @ @c pointer mp_find_edges_var (MP mp, pointer t) {
22660   pointer p;
22661   pointer cur_edges; /* the return value */
22662   p=mp_find_variable(mp, t); cur_edges=null;
22663   if ( p==null ) { 
22664     mp_obliterated(mp, t); mp_put_get_error(mp);
22665   } else if ( type(p)!=mp_picture_type )  { 
22666     print_err("Variable "); mp_show_token_list(mp, t,null,1000,0);
22667 @.Variable x is the wrong type@>
22668     mp_print(mp, " is the wrong type ("); 
22669     mp_print_type(mp, type(p)); mp_print_char(mp, ')');
22670     help2("I was looking for a \"known\" picture variable.")
22671          ("So I'll not change anything just now."); 
22672     mp_put_get_error(mp);
22673   } else { 
22674     value(p)=mp_private_edges(mp, value(p));
22675     cur_edges=value(p);
22676   }
22677   mp_flush_node_list(mp, t);
22678   return cur_edges;
22679 };
22680
22681 @ @<Cases of |do_statement|...@>=
22682 case add_to_command: mp_do_add_to(mp); break;
22683 case bounds_command:mp_do_bounds(mp); break;
22684
22685 @ @<Put each...@>=
22686 mp_primitive(mp, "clip",bounds_command,mp_start_clip_code);
22687 @:clip_}{\&{clip} primitive@>
22688 mp_primitive(mp, "setbounds",bounds_command,mp_start_bounds_code);
22689 @:set_bounds_}{\&{setbounds} primitive@>
22690
22691 @ @<Cases of |print_cmd...@>=
22692 case bounds_command: 
22693   if ( m==mp_start_clip_code ) mp_print(mp, "clip");
22694   else mp_print(mp, "setbounds");
22695   break;
22696
22697 @ The following function parses the beginning of an \&{addto} or \&{clip}
22698 command: it expects a variable name followed by a token with |cur_cmd=sep|
22699 and then an expression.  The function returns the token list for the variable
22700 and stores the command modifier for the separator token in the global variable
22701 |last_add_type|.  We must be careful because this variable might get overwritten
22702 any time we call |get_x_next|.
22703
22704 @<Glob...@>=
22705 quarterword last_add_type;
22706   /* command modifier that identifies the last \&{addto} command */
22707
22708 @ @<Declare action procedures for use by |do_statement|@>=
22709 pointer mp_start_draw_cmd (MP mp,quarterword sep) ;
22710
22711 @ @c pointer mp_start_draw_cmd (MP mp,quarterword sep) {
22712   pointer lhv; /* variable to add to left */
22713   quarterword add_type=0; /* value to be returned in |last_add_type| */
22714   lhv=null;
22715   mp_get_x_next(mp); mp->var_flag=sep; mp_scan_primary(mp);
22716   if ( mp->cur_type!=mp_token_list ) {
22717     @<Abandon edges command because there's no variable@>;
22718   } else  { 
22719     lhv=mp->cur_exp; add_type=mp->cur_mod;
22720     mp->cur_type=mp_vacuous; mp_get_x_next(mp); mp_scan_expression(mp);
22721   }
22722   mp->last_add_type=add_type;
22723   return lhv;
22724 }
22725
22726 @ @<Abandon edges command because there's no variable@>=
22727 { exp_err("Not a suitable variable");
22728 @.Not a suitable variable@>
22729   help4("At this point I needed to see the name of a picture variable.")
22730     ("(Or perhaps you have indeed presented me with one; I might")
22731     ("have missed it, if it wasn't followed by the proper token.)")
22732     ("So I'll not change anything just now.");
22733   mp_put_get_flush_error(mp, 0);
22734 }
22735
22736 @ Here is an example of how to use |start_draw_cmd|.
22737
22738 @<Declare action procedures for use by |do_statement|@>=
22739 void mp_do_bounds (MP mp) ;
22740
22741 @ @c void mp_do_bounds (MP mp) {
22742   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22743   pointer p; /* for list manipulation */
22744   integer m; /* initial value of |cur_mod| */
22745   m=mp->cur_mod;
22746   lhv=mp_start_draw_cmd(mp, to_token);
22747   if ( lhv!=null ) {
22748     lhe=mp_find_edges_var(mp, lhv);
22749     if ( lhe==null ) {
22750       mp_flush_cur_exp(mp, 0);
22751     } else if ( mp->cur_type!=mp_path_type ) {
22752       exp_err("Improper `clip'");
22753 @.Improper `addto'@>
22754       help2("This expression should have specified a known path.")
22755         ("So I'll not change anything just now."); 
22756       mp_put_get_flush_error(mp, 0);
22757     } else if ( left_type(mp->cur_exp)==mp_endpoint ) {
22758       @<Complain about a non-cycle@>;
22759     } else {
22760       @<Make |cur_exp| into a \&{setbounds} or clipping path and add it to |lhe|@>;
22761     }
22762   }
22763 }
22764
22765 @ @<Complain about a non-cycle@>=
22766 { print_err("Not a cycle");
22767 @.Not a cycle@>
22768   help2("That contour should have ended with `..cycle' or `&cycle'.")
22769     ("So I'll not change anything just now."); mp_put_get_error(mp);
22770 }
22771
22772 @ @<Make |cur_exp| into a \&{setbounds} or clipping path and add...@>=
22773 { p=mp_new_bounds_node(mp, mp->cur_exp,m);
22774   link(p)=link(dummy_loc(lhe));
22775   link(dummy_loc(lhe))=p;
22776   if ( obj_tail(lhe)==dummy_loc(lhe) ) obj_tail(lhe)=p;
22777   p=mp_get_node(mp, mp->gr_object_size[stop_type(m)]);
22778   type(p)=stop_type(m);
22779   link(obj_tail(lhe))=p;
22780   obj_tail(lhe)=p;
22781   mp_init_bbox(mp, lhe);
22782 }
22783
22784 @ The |do_add_to| procedure is a little like |do_clip| but there are a lot more
22785 cases to deal with.
22786
22787 @<Declare action procedures for use by |do_statement|@>=
22788 void mp_do_add_to (MP mp) ;
22789
22790 @ @c void mp_do_add_to (MP mp) {
22791   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22792   pointer p; /* the graphical object or list for |scan_with_list| to update */
22793   pointer e; /* an edge structure to be merged */
22794   quarterword add_type; /* |also_code|, |contour_code|, or |double_path_code| */
22795   lhv=mp_start_draw_cmd(mp, thing_to_add); add_type=mp->last_add_type;
22796   if ( lhv!=null ) {
22797     if ( add_type==also_code ) {
22798       @<Make sure the current expression is a suitable picture and set |e| and |p|
22799        appropriately@>;
22800     } else {
22801       @<Create a graphical object |p| based on |add_type| and the current
22802         expression@>;
22803     }
22804     mp_scan_with_list(mp, p);
22805     @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>;
22806   }
22807 }
22808
22809 @ Setting |p:=null| causes the $\langle$with list$\rangle$ to be ignored;
22810 setting |e:=null| prevents anything from being added to |lhe|.
22811
22812 @ @<Make sure the current expression is a suitable picture and set |e|...@>=
22813
22814   p=null; e=null;
22815   if ( mp->cur_type!=mp_picture_type ) {
22816     exp_err("Improper `addto'");
22817 @.Improper `addto'@>
22818     help2("This expression should have specified a known picture.")
22819       ("So I'll not change anything just now."); mp_put_get_flush_error(mp, 0);
22820   } else { 
22821     e=mp_private_edges(mp, mp->cur_exp); mp->cur_type=mp_vacuous;
22822     p=link(dummy_loc(e));
22823   }
22824 }
22825
22826 @ In this case |add_type<>also_code| so setting |p:=null| suppresses future
22827 attempts to add to the edge structure.
22828
22829 @<Create a graphical object |p| based on |add_type| and the current...@>=
22830 { e=null; p=null;
22831   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
22832   if ( mp->cur_type!=mp_path_type ) {
22833     exp_err("Improper `addto'");
22834 @.Improper `addto'@>
22835     help2("This expression should have specified a known path.")
22836       ("So I'll not change anything just now."); 
22837     mp_put_get_flush_error(mp, 0);
22838   } else if ( add_type==contour_code ) {
22839     if ( left_type(mp->cur_exp)==mp_endpoint ) {
22840       @<Complain about a non-cycle@>;
22841     } else { 
22842       p=mp_new_fill_node(mp, mp->cur_exp);
22843       mp->cur_type=mp_vacuous;
22844     }
22845   } else { 
22846     p=mp_new_stroked_node(mp, mp->cur_exp);
22847     mp->cur_type=mp_vacuous;
22848   }
22849 }
22850
22851 @ @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>=
22852 lhe=mp_find_edges_var(mp, lhv);
22853 if ( lhe==null ) {
22854   if ( (e==null)&&(p!=null) ) e=mp_toss_gr_object(mp, p);
22855   if ( e!=null ) delete_edge_ref(e);
22856 } else if ( add_type==also_code ) {
22857   if ( e!=null ) {
22858     @<Merge |e| into |lhe| and delete |e|@>;
22859   } else { 
22860     do_nothing;
22861   }
22862 } else if ( p!=null ) {
22863   link(obj_tail(lhe))=p;
22864   obj_tail(lhe)=p;
22865   if ( add_type==double_path_code )
22866     if ( pen_p(p)==null ) 
22867       pen_p(p)=mp_get_pen_circle(mp, 0);
22868 }
22869
22870 @ @<Merge |e| into |lhe| and delete |e|@>=
22871 { if ( link(dummy_loc(e))!=null ) {
22872     link(obj_tail(lhe))=link(dummy_loc(e));
22873     obj_tail(lhe)=obj_tail(e);
22874     obj_tail(e)=dummy_loc(e);
22875     link(dummy_loc(e))=null;
22876     mp_flush_dash_list(mp, lhe);
22877   }
22878   mp_toss_edges(mp, e);
22879 }
22880
22881 @ @<Cases of |do_statement|...@>=
22882 case ship_out_command: mp_do_ship_out(mp); break;
22883
22884 @ @<Declare action procedures for use by |do_statement|@>=
22885 @<Declare the function called |tfm_check|@>;
22886 @<Declare the \ps\ output procedures@>;
22887 void mp_do_ship_out (MP mp) ;
22888
22889 @ @c void mp_do_ship_out (MP mp) {
22890   integer c; /* the character code */
22891   mp_get_x_next(mp); mp_scan_expression(mp);
22892   if ( mp->cur_type!=mp_picture_type ) {
22893     @<Complain that it's not a known picture@>;
22894   } else { 
22895     c=mp_round_unscaled(mp, mp->internal[mp_char_code]) % 256;
22896     if ( c<0 ) c=c+256;
22897     @<Store the width information for character code~|c|@>;
22898     mp_ship_out(mp, mp->cur_exp);
22899     mp_flush_cur_exp(mp, 0);
22900   }
22901 }
22902
22903 @ @<Complain that it's not a known picture@>=
22904
22905   exp_err("Not a known picture");
22906   help1("I can only output known pictures.");
22907   mp_put_get_flush_error(mp, 0);
22908 }
22909
22910 @ The \&{everyjob} command simply assigns a nonzero value to the global variable
22911 |start_sym|.
22912
22913 @<Cases of |do_statement|...@>=
22914 case every_job_command: 
22915   mp_get_symbol(mp); mp->start_sym=mp->cur_sym; mp_get_x_next(mp);
22916   break;
22917
22918 @ @<Glob...@>=
22919 halfword start_sym; /* a symbolic token to insert at beginning of job */
22920
22921 @ @<Set init...@>=
22922 mp->start_sym=0;
22923
22924 @ Finally, we have only the ``message'' commands remaining.
22925
22926 @d message_code 0
22927 @d err_message_code 1
22928 @d err_help_code 2
22929 @d filename_template_code 3
22930 @d print_with_leading_zeroes(A)  g = mp->pool_ptr;
22931               mp_print_int(mp, (A)); g = mp->pool_ptr-g;
22932               if ( f>g ) {
22933                 mp->pool_ptr = mp->pool_ptr - g;
22934                 while ( f>g ) {
22935                   mp_print_char(mp, '0');
22936                   decr(f);
22937                   };
22938                 mp_print_int(mp, (A));
22939               };
22940               f = 0
22941
22942 @<Put each...@>=
22943 mp_primitive(mp, "message",message_command,message_code);
22944 @:message_}{\&{message} primitive@>
22945 mp_primitive(mp, "errmessage",message_command,err_message_code);
22946 @:err_message_}{\&{errmessage} primitive@>
22947 mp_primitive(mp, "errhelp",message_command,err_help_code);
22948 @:err_help_}{\&{errhelp} primitive@>
22949 mp_primitive(mp, "filenametemplate",message_command,filename_template_code);
22950 @:filename_template_}{\&{filenametemplate} primitive@>
22951
22952 @ @<Cases of |print_cmd...@>=
22953 case message_command: 
22954   if ( m<err_message_code ) mp_print(mp, "message");
22955   else if ( m==err_message_code ) mp_print(mp, "errmessage");
22956   else if ( m==filename_template_code ) mp_print(mp, "filenametemplate");
22957   else mp_print(mp, "errhelp");
22958   break;
22959
22960 @ @<Cases of |do_statement|...@>=
22961 case message_command: mp_do_message(mp); break;
22962
22963 @ @<Declare action procedures for use by |do_statement|@>=
22964 @<Declare a procedure called |no_string_err|@>;
22965 void mp_do_message (MP mp) ;
22966
22967
22968 @c void mp_do_message (MP mp) {
22969   int m; /* the type of message */
22970   m=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
22971   if ( mp->cur_type!=mp_string_type )
22972     mp_no_string_err(mp, "A message should be a known string expression.");
22973   else {
22974     switch (m) {
22975     case message_code: 
22976       mp_print_nl(mp, ""); mp_print_str(mp, mp->cur_exp);
22977       break;
22978     case err_message_code:
22979       @<Print string |cur_exp| as an error message@>;
22980       break;
22981     case err_help_code:
22982       @<Save string |cur_exp| as the |err_help|@>;
22983       break;
22984     case filename_template_code:
22985       @<Save the filename template@>;
22986       break;
22987     } /* there are no other cases */
22988   }
22989   mp_flush_cur_exp(mp, 0);
22990 }
22991
22992 @ @<Declare a procedure called |no_string_err|@>=
22993 void mp_no_string_err (MP mp,char *s) { 
22994    exp_err("Not a string");
22995 @.Not a string@>
22996   help1(s);
22997   mp_put_get_error(mp);
22998 }
22999
23000 @ The global variable |err_help| is zero when the user has most recently
23001 given an empty help string, or if none has ever been given.
23002
23003 @<Save string |cur_exp| as the |err_help|@>=
23004
23005   if ( mp->err_help!=0 ) delete_str_ref(mp->err_help);
23006   if ( length(mp->cur_exp)==0 ) mp->err_help=0;
23007   else  { mp->err_help=mp->cur_exp; add_str_ref(mp->err_help); }
23008 }
23009
23010 @ If \&{errmessage} occurs often in |mp_scroll_mode|, without user-defined
23011 \&{errhelp}, we don't want to give a long help message each time. So we
23012 give a verbose explanation only once.
23013
23014 @<Glob...@>=
23015 boolean long_help_seen; /* has the long \.{\\errmessage} help been used? */
23016
23017 @ @<Set init...@>=mp->long_help_seen=false;
23018
23019 @ @<Print string |cur_exp| as an error message@>=
23020
23021   print_err(""); mp_print_str(mp, mp->cur_exp);
23022   if ( mp->err_help!=0 ) {
23023     mp->use_err_help=true;
23024   } else if ( mp->long_help_seen ) { 
23025     help1("(That was another `errmessage'.)") ; 
23026   } else  { 
23027    if ( mp->interaction<mp_error_stop_mode ) mp->long_help_seen=true;
23028     help4("This error message was generated by an `errmessage'")
23029      ("command, so I can\'t give any explicit help.")
23030      ("Pretend that you're Miss Marple: Examine all clues,")
23031 @^Marple, Jane@>
23032      ("and deduce the truth by inspired guesses.");
23033   }
23034   mp_put_get_error(mp); mp->use_err_help=false;
23035 }
23036
23037 @ @<Cases of |do_statement|...@>=
23038 case write_command: mp_do_write(mp); break;
23039
23040 @ @<Declare action procedures for use by |do_statement|@>=
23041 void mp_do_write (MP mp) ;
23042
23043 @ @c void mp_do_write (MP mp) {
23044   str_number t; /* the line of text to be written */
23045   write_index n,n0; /* for searching |wr_fname| and |wr_file| arrays */
23046   int old_setting; /* for saving |selector| during output */
23047   mp_get_x_next(mp);
23048   mp_scan_expression(mp);
23049   if ( mp->cur_type!=mp_string_type ) {
23050     mp_no_string_err(mp, "The text to be written should be a known string expression");
23051   } else if ( mp->cur_cmd!=to_token ) { 
23052     print_err("Missing `to' clause");
23053     help1("A write command should end with `to <filename>'");
23054     mp_put_get_error(mp);
23055   } else { 
23056     t=mp->cur_exp; mp->cur_type=mp_vacuous;
23057     mp_get_x_next(mp);
23058     mp_scan_expression(mp);
23059     if ( mp->cur_type!=mp_string_type )
23060       mp_no_string_err(mp, "I can\'t write to that file name.  It isn't a known string");
23061     else {
23062       @<Write |t| to the file named by |cur_exp|@>;
23063     }
23064     delete_str_ref(t);
23065   }
23066   mp_flush_cur_exp(mp, 0);
23067 }
23068
23069 @ @<Write |t| to the file named by |cur_exp|@>=
23070
23071   @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if
23072     |cur_exp| must be inserted@>;
23073   if ( mp_str_vs_str(mp, t,mp->eof_line)==0 ) {
23074     @<Record the end of file on |wr_file[n]|@>;
23075   } else { 
23076     old_setting=mp->selector;
23077     mp->selector=n+write_file;
23078     mp_print_str(mp, t); mp_print_ln(mp);
23079     mp->selector = old_setting;
23080   }
23081 }
23082
23083 @ @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if...@>=
23084 {
23085   char *fn = str(mp->cur_exp);
23086   n=mp->write_files;
23087   n0=mp->write_files;
23088   while (mp_xstrcmp(fn,mp->wr_fname[n])!=0) { 
23089     if ( n==0 ) { /* bottom reached */
23090           if ( n0==mp->write_files ) {
23091         if ( mp->write_files<mp->max_write_files ) {
23092           incr(mp->write_files);
23093         } else {
23094           void **wr_file;
23095           char **wr_fname;
23096               write_index l,k;
23097           l = mp->max_write_files + (mp->max_write_files>>2);
23098           wr_file = xmalloc((l+1),sizeof(void *));
23099           wr_fname = xmalloc((l+1),sizeof(char *));
23100               for (k=0;k<=l;k++) {
23101             if (k<=mp->max_write_files) {
23102                   wr_file[k]=mp->wr_file[k]; 
23103               wr_fname[k]=mp->wr_fname[k];
23104             } else {
23105                   wr_file[k]=0; 
23106               wr_fname[k]=NULL;
23107             }
23108           }
23109               xfree(mp->wr_file); xfree(mp->wr_fname);
23110           mp->max_write_files = l;
23111           mp->wr_file = wr_file;
23112           mp->wr_fname = wr_fname;
23113         }
23114       }
23115       n=n0;
23116       mp_open_write_file(mp, fn ,n);
23117     } else { 
23118       decr(n);
23119           if ( mp->wr_fname[n]==NULL )  n0=n; 
23120     }
23121   }
23122 }
23123
23124 @ @<Record the end of file on |wr_file[n]|@>=
23125 { (mp->close_file)(mp->wr_file[n]);
23126   xfree(mp->wr_fname[n]);
23127   mp->wr_fname[n]=NULL;
23128   if ( n==mp->write_files-1 ) mp->write_files=n;
23129 }
23130
23131
23132 @* \[42] Writing font metric data.
23133 \TeX\ gets its knowledge about fonts from font metric files, also called
23134 \.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
23135 but other programs know about them too. One of \MP's duties is to
23136 write \.{TFM} files so that the user's fonts can readily be
23137 applied to typesetting.
23138 @:TFM files}{\.{TFM} files@>
23139 @^font metric files@>
23140
23141 The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
23142 Since the number of bytes is always a multiple of~4, we could
23143 also regard the file as a sequence of 32-bit words, but \MP\ uses the
23144 byte interpretation. The format of \.{TFM} files was designed by
23145 Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
23146 @^Ramshaw, Lyle Harold@>
23147 of information in a compact but useful form.
23148
23149 @<Glob...@>=
23150 void * tfm_file; /* the font metric output goes here */
23151 char * metric_file_name; /* full name of the font metric file */
23152
23153 @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
23154 integers that give the lengths of the various subsequent portions
23155 of the file. These twelve integers are, in order:
23156 $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
23157 |lf|&length of the entire file, in words;\cr
23158 |lh|&length of the header data, in words;\cr
23159 |bc|&smallest character code in the font;\cr
23160 |ec|&largest character code in the font;\cr
23161 |nw|&number of words in the width table;\cr
23162 |nh|&number of words in the height table;\cr
23163 |nd|&number of words in the depth table;\cr
23164 |ni|&number of words in the italic correction table;\cr
23165 |nl|&number of words in the lig/kern table;\cr
23166 |nk|&number of words in the kern table;\cr
23167 |ne|&number of words in the extensible character table;\cr
23168 |np|&number of font parameter words.\cr}}$$
23169 They are all nonnegative and less than $2^{15}$. We must have |bc-1<=ec<=255|,
23170 |ne<=256|, and
23171 $$\hbox{|lf=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
23172 Note that a font may contain as many as 256 characters (if |bc=0| and |ec=255|),
23173 and as few as 0 characters (if |bc=ec+1|).
23174
23175 Incidentally, when two or more 8-bit bytes are combined to form an integer of
23176 16 or more bits, the most significant bytes appear first in the file.
23177 This is called BigEndian order.
23178 @^BigEndian order@>
23179
23180 @ The rest of the \.{TFM} file may be regarded as a sequence of ten data
23181 arrays.
23182
23183 The most important data type used here is a |fix_word|, which is
23184 a 32-bit representation of a binary fraction. A |fix_word| is a signed
23185 quantity, with the two's complement of the entire word used to represent
23186 negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
23187 binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
23188 the smallest is $-2048$. We will see below, however, that all but two of
23189 the |fix_word| values must lie between $-16$ and $+16$.
23190
23191 @ The first data array is a block of header information, which contains
23192 general facts about the font. The header must contain at least two words,
23193 |header[0]| and |header[1]|, whose meaning is explained below.  Additional
23194 header information of use to other software routines might also be
23195 included, and \MP\ will generate it if the \.{headerbyte} command occurs.
23196 For example, 16 more words of header information are in use at the Xerox
23197 Palo Alto Research Center; the first ten specify the character coding
23198 scheme used (e.g., `\.{XEROX TEXT}' or `\.{TEX MATHSY}'), the next five
23199 give the font family name (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
23200 last gives the ``face byte.''
23201
23202 \yskip\hang|header[0]| is a 32-bit check sum that \MP\ will copy into
23203 the \.{GF} output file. This helps ensure consistency between files,
23204 since \TeX\ records the check sums from the \.{TFM}'s it reads, and these
23205 should match the check sums on actual fonts that are used.  The actual
23206 relation between this check sum and the rest of the \.{TFM} file is not
23207 important; the check sum is simply an identification number with the
23208 property that incompatible fonts almost always have distinct check sums.
23209 @^check sum@>
23210
23211 \yskip\hang|header[1]| is a |fix_word| containing the design size of the
23212 font, in units of \TeX\ points. This number must be at least 1.0; it is
23213 fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
23214 font, i.e., a font that was designed to look best at a 10-point size,
23215 whatever that really means. When a \TeX\ user asks for a font `\.{at}
23216 $\delta$ \.{pt}', the effect is to override the design size and replace it
23217 by $\delta$, and to multiply the $x$ and~$y$ coordinates of the points in
23218 the font image by a factor of $\delta$ divided by the design size.  {\sl
23219 All other dimensions in the\/ \.{TFM} file are |fix_word|\kern-1pt\
23220 numbers in design-size units.} Thus, for example, the value of |param[6]|,
23221 which defines the \.{em} unit, is often the |fix_word| value $2^{20}=1.0$,
23222 since many fonts have a design size equal to one em.  The other dimensions
23223 must be less than 16 design-size units in absolute value; thus,
23224 |header[1]| and |param[1]| are the only |fix_word| entries in the whole
23225 \.{TFM} file whose first byte might be something besides 0 or 255.
23226
23227 @ Next comes the |char_info| array, which contains one |char_info_word|
23228 per character. Each word in this part of the file contains six fields
23229 packed into four bytes as follows.
23230
23231 \yskip\hang first byte: |width_index| (8 bits)\par
23232 \hang second byte: |height_index| (4 bits) times 16, plus |depth_index|
23233   (4~bits)\par
23234 \hang third byte: |italic_index| (6 bits) times 4, plus |tag|
23235   (2~bits)\par
23236 \hang fourth byte: |remainder| (8 bits)\par
23237 \yskip\noindent
23238 The actual width of a character is \\{width}|[width_index]|, in design-size
23239 units; this is a device for compressing information, since many characters
23240 have the same width. Since it is quite common for many characters
23241 to have the same height, depth, or italic correction, the \.{TFM} format
23242 imposes a limit of 16 different heights, 16 different depths, and
23243 64 different italic corrections.
23244
23245 Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
23246 \\{italic}[0]=0$ should always hold, so that an index of zero implies a
23247 value of zero.  The |width_index| should never be zero unless the
23248 character does not exist in the font, since a character is valid if and
23249 only if it lies between |bc| and |ec| and has a nonzero |width_index|.
23250
23251 @ The |tag| field in a |char_info_word| has four values that explain how to
23252 interpret the |remainder| field.
23253
23254 \yskip\hang|tag=0| (|no_tag|) means that |remainder| is unused.\par
23255 \hang|tag=1| (|lig_tag|) means that this character has a ligature/kerning
23256 program starting at location |remainder| in the |lig_kern| array.\par
23257 \hang|tag=2| (|list_tag|) means that this character is part of a chain of
23258 characters of ascending sizes, and not the largest in the chain.  The
23259 |remainder| field gives the character code of the next larger character.\par
23260 \hang|tag=3| (|ext_tag|) means that this character code represents an
23261 extensible character, i.e., a character that is built up of smaller pieces
23262 so that it can be made arbitrarily large. The pieces are specified in
23263 |exten[remainder]|.\par
23264 \yskip\noindent
23265 Characters with |tag=2| and |tag=3| are treated as characters with |tag=0|
23266 unless they are used in special circumstances in math formulas. For example,
23267 \TeX's \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
23268 operation looks for both |list_tag| and |ext_tag|.
23269
23270 @d no_tag 0 /* vanilla character */
23271 @d lig_tag 1 /* character has a ligature/kerning program */
23272 @d list_tag 2 /* character has a successor in a charlist */
23273 @d ext_tag 3 /* character is extensible */
23274
23275 @ The |lig_kern| array contains instructions in a simple programming language
23276 that explains what to do for special letter pairs. Each word in this array is a
23277 |lig_kern_command| of four bytes.
23278
23279 \yskip\hang first byte: |skip_byte|, indicates that this is the final program
23280   step if the byte is 128 or more, otherwise the next step is obtained by
23281   skipping this number of intervening steps.\par
23282 \hang second byte: |next_char|, ``if |next_char| follows the current character,
23283   then perform the operation and stop, otherwise continue.''\par
23284 \hang third byte: |op_byte|, indicates a ligature step if less than~128,
23285   a kern step otherwise.\par
23286 \hang fourth byte: |remainder|.\par
23287 \yskip\noindent
23288 In a kern step, an
23289 additional space equal to |kern[256*(op_byte-128)+remainder]| is inserted
23290 between the current character and |next_char|. This amount is
23291 often negative, so that the characters are brought closer together
23292 by kerning; but it might be positive.
23293
23294 There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
23295 $0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
23296 |remainder| is inserted between the current character and |next_char|;
23297 then the current character is deleted if $b=0$, and |next_char| is
23298 deleted if $c=0$; then we pass over $a$~characters to reach the next
23299 current character (which may have a ligature/kerning program of its own).
23300
23301 If the very first instruction of the |lig_kern| array has |skip_byte=255|,
23302 the |next_char| byte is the so-called right boundary character of this font;
23303 the value of |next_char| need not lie between |bc| and~|ec|.
23304 If the very last instruction of the |lig_kern| array has |skip_byte=255|,
23305 there is a special ligature/kerning program for a left boundary character,
23306 beginning at location |256*op_byte+remainder|.
23307 The interpretation is that \TeX\ puts implicit boundary characters
23308 before and after each consecutive string of characters from the same font.
23309 These implicit characters do not appear in the output, but they can affect
23310 ligatures and kerning.
23311
23312 If the very first instruction of a character's |lig_kern| program has
23313 |skip_byte>128|, the program actually begins in location
23314 |256*op_byte+remainder|. This feature allows access to large |lig_kern|
23315 arrays, because the first instruction must otherwise
23316 appear in a location |<=255|.
23317
23318 Any instruction with |skip_byte>128| in the |lig_kern| array must satisfy
23319 the condition
23320 $$\hbox{|256*op_byte+remainder<nl|.}$$
23321 If such an instruction is encountered during
23322 normal program execution, it denotes an unconditional halt; no ligature
23323 command is performed.
23324
23325 @d stop_flag (128)
23326   /* value indicating `\.{STOP}' in a lig/kern program */
23327 @d kern_flag (128) /* op code for a kern step */
23328 @d skip_byte(A) mp->lig_kern[(A)].b0
23329 @d next_char(A) mp->lig_kern[(A)].b1
23330 @d op_byte(A) mp->lig_kern[(A)].b2
23331 @d rem_byte(A) mp->lig_kern[(A)].b3
23332
23333 @ Extensible characters are specified by an |extensible_recipe|, which
23334 consists of four bytes called |top|, |mid|, |bot|, and |rep| (in this
23335 order). These bytes are the character codes of individual pieces used to
23336 build up a large symbol.  If |top|, |mid|, or |bot| are zero, they are not
23337 present in the built-up result. For example, an extensible vertical line is
23338 like an extensible bracket, except that the top and bottom pieces are missing.
23339
23340 Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
23341 if the piece isn't present. Then the extensible characters have the form
23342 $TR^kMR^kB$ from top to bottom, for some |k>=0|, unless $M$ is absent;
23343 in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
23344 The width of the extensible character is the width of $R$; and the
23345 height-plus-depth is the sum of the individual height-plus-depths of the
23346 components used, since the pieces are butted together in a vertical list.
23347
23348 @d ext_top(A) mp->exten[(A)].b0 /* |top| piece in a recipe */
23349 @d ext_mid(A) mp->exten[(A)].b1 /* |mid| piece in a recipe */
23350 @d ext_bot(A) mp->exten[(A)].b2 /* |bot| piece in a recipe */
23351 @d ext_rep(A) mp->exten[(A)].b3 /* |rep| piece in a recipe */
23352
23353 @ The final portion of a \.{TFM} file is the |param| array, which is another
23354 sequence of |fix_word| values.
23355
23356 \yskip\hang|param[1]=slant| is the amount of italic slant, which is used
23357 to help position accents. For example, |slant=.25| means that when you go
23358 up one unit, you also go .25 units to the right. The |slant| is a pure
23359 number; it is the only |fix_word| other than the design size itself that is
23360 not scaled by the design size.
23361
23362 \hang|param[2]=space| is the normal spacing between words in text.
23363 Note that character 040 in the font need not have anything to do with
23364 blank spaces.
23365
23366 \hang|param[3]=space_stretch| is the amount of glue stretching between words.
23367
23368 \hang|param[4]=space_shrink| is the amount of glue shrinking between words.
23369
23370 \hang|param[5]=x_height| is the size of one ex in the font; it is also
23371 the height of letters for which accents don't have to be raised or lowered.
23372
23373 \hang|param[6]=quad| is the size of one em in the font.
23374
23375 \hang|param[7]=extra_space| is the amount added to |param[2]| at the
23376 ends of sentences.
23377
23378 \yskip\noindent
23379 If fewer than seven parameters are present, \TeX\ sets the missing parameters
23380 to zero.
23381
23382 @d slant_code 1
23383 @d space_code 2
23384 @d space_stretch_code 3
23385 @d space_shrink_code 4
23386 @d x_height_code 5
23387 @d quad_code 6
23388 @d extra_space_code 7
23389
23390 @ So that is what \.{TFM} files hold. One of \MP's duties is to output such
23391 information, and it does this all at once at the end of a job.
23392 In order to prepare for such frenetic activity, it squirrels away the
23393 necessary facts in various arrays as information becomes available.
23394
23395 Character dimensions (\&{charwd}, \&{charht}, \&{chardp}, and \&{charic})
23396 are stored respectively in |tfm_width|, |tfm_height|, |tfm_depth|, and
23397 |tfm_ital_corr|. Other information about a character (e.g., about
23398 its ligatures or successors) is accessible via the |char_tag| and
23399 |char_remainder| arrays. Other information about the font as a whole
23400 is kept in additional arrays called |header_byte|, |lig_kern|,
23401 |kern|, |exten|, and |param|.
23402
23403 @d max_tfm_int 32510
23404 @d undefined_label max_tfm_int /* an undefined local label */
23405
23406 @<Glob...@>=
23407 #define TFM_ITEMS 257
23408 eight_bits bc;
23409 eight_bits ec; /* smallest and largest character codes shipped out */
23410 scaled tfm_width[TFM_ITEMS]; /* \&{charwd} values */
23411 scaled tfm_height[TFM_ITEMS]; /* \&{charht} values */
23412 scaled tfm_depth[TFM_ITEMS]; /* \&{chardp} values */
23413 scaled tfm_ital_corr[TFM_ITEMS]; /* \&{charic} values */
23414 boolean char_exists[TFM_ITEMS]; /* has this code been shipped out? */
23415 int char_tag[TFM_ITEMS]; /* |remainder| category */
23416 int char_remainder[TFM_ITEMS]; /* the |remainder| byte */
23417 char *header_byte; /* bytes of the \.{TFM} header */
23418 int header_last; /* last initialized \.{TFM} header byte */
23419 int header_size; /* size of the \.{TFM} header */
23420 four_quarters *lig_kern; /* the ligature/kern table */
23421 short nl; /* the number of ligature/kern steps so far */
23422 scaled *kern; /* distinct kerning amounts */
23423 short nk; /* the number of distinct kerns so far */
23424 four_quarters exten[TFM_ITEMS]; /* extensible character recipes */
23425 short ne; /* the number of extensible characters so far */
23426 scaled *param; /* \&{fontinfo} parameters */
23427 short np; /* the largest \&{fontinfo} parameter specified so far */
23428 short nw;short nh;short nd;short ni; /* sizes of \.{TFM} subtables */
23429 short skip_table[TFM_ITEMS]; /* local label status */
23430 boolean lk_started; /* has there been a lig/kern step in this command yet? */
23431 integer bchar; /* right boundary character */
23432 short bch_label; /* left boundary starting location */
23433 short ll;short lll; /* registers used for lig/kern processing */
23434 short label_loc[257]; /* lig/kern starting addresses */
23435 eight_bits label_char[257]; /* characters for |label_loc| */
23436 short label_ptr; /* highest position occupied in |label_loc| */
23437
23438 @ @<Allocate or initialize ...@>=
23439 mp->header_last = 0; mp->header_size = 128; /* just for init */
23440 mp->header_byte = xmalloc(mp->header_size, sizeof(char));
23441 mp->lig_kern = NULL; /* allocated when needed */
23442 mp->kern = NULL; /* allocated when needed */ 
23443 mp->param = NULL; /* allocated when needed */
23444
23445 @ @<Dealloc variables@>=
23446 xfree(mp->header_byte);
23447 xfree(mp->lig_kern);
23448 xfree(mp->kern);
23449 xfree(mp->param);
23450
23451 @ @<Set init...@>=
23452 for (k=0;k<= 255;k++ ) {
23453   mp->tfm_width[k]=0; mp->tfm_height[k]=0; mp->tfm_depth[k]=0; mp->tfm_ital_corr[k]=0;
23454   mp->char_exists[k]=false; mp->char_tag[k]=no_tag; mp->char_remainder[k]=0;
23455   mp->skip_table[k]=undefined_label;
23456 };
23457 memset(mp->header_byte,0,mp->header_size);
23458 mp->bc=255; mp->ec=0; mp->nl=0; mp->nk=0; mp->ne=0; mp->np=0;
23459 mp->internal[mp_boundary_char]=-unity;
23460 mp->bch_label=undefined_label;
23461 mp->label_loc[0]=-1; mp->label_ptr=0;
23462
23463 @ @<Declarations@>=
23464 scaled mp_tfm_check (MP mp,small_number m) ;
23465
23466 @ @<Declare the function called |tfm_check|@>=
23467 scaled mp_tfm_check (MP mp,small_number m) {
23468   if ( abs(mp->internal[m])>=fraction_half ) {
23469     print_err("Enormous "); mp_print(mp, mp->int_name[m]);
23470 @.Enormous charwd...@>
23471 @.Enormous chardp...@>
23472 @.Enormous charht...@>
23473 @.Enormous charic...@>
23474 @.Enormous designsize...@>
23475     mp_print(mp, " has been reduced");
23476     help1("Font metric dimensions must be less than 2048pt.");
23477     mp_put_get_error(mp);
23478     if ( mp->internal[m]>0 ) return (fraction_half-1);
23479     else return (1-fraction_half);
23480   } else {
23481     return mp->internal[m];
23482   }
23483 }
23484
23485 @ @<Store the width information for character code~|c|@>=
23486 if ( c<mp->bc ) mp->bc=c;
23487 if ( c>mp->ec ) mp->ec=c;
23488 mp->char_exists[c]=true;
23489 mp->tfm_width[c]=mp_tfm_check(mp, mp_char_wd);
23490 mp->tfm_height[c]=mp_tfm_check(mp, mp_char_ht);
23491 mp->tfm_depth[c]=mp_tfm_check(mp, mp_char_dp);
23492 mp->tfm_ital_corr[c]=mp_tfm_check(mp, mp_char_ic)
23493
23494 @ Now let's consider \MP's special \.{TFM}-oriented commands.
23495
23496 @<Cases of |do_statement|...@>=
23497 case tfm_command: mp_do_tfm_command(mp); break;
23498
23499 @ @d char_list_code 0
23500 @d lig_table_code 1
23501 @d extensible_code 2
23502 @d header_byte_code 3
23503 @d font_dimen_code 4
23504
23505 @<Put each...@>=
23506 mp_primitive(mp, "charlist",tfm_command,char_list_code);
23507 @:char_list_}{\&{charlist} primitive@>
23508 mp_primitive(mp, "ligtable",tfm_command,lig_table_code);
23509 @:lig_table_}{\&{ligtable} primitive@>
23510 mp_primitive(mp, "extensible",tfm_command,extensible_code);
23511 @:extensible_}{\&{extensible} primitive@>
23512 mp_primitive(mp, "headerbyte",tfm_command,header_byte_code);
23513 @:header_byte_}{\&{headerbyte} primitive@>
23514 mp_primitive(mp, "fontdimen",tfm_command,font_dimen_code);
23515 @:font_dimen_}{\&{fontdimen} primitive@>
23516
23517 @ @<Cases of |print_cmd...@>=
23518 case tfm_command: 
23519   switch (m) {
23520   case char_list_code:mp_print(mp, "charlist"); break;
23521   case lig_table_code:mp_print(mp, "ligtable"); break;
23522   case extensible_code:mp_print(mp, "extensible"); break;
23523   case header_byte_code:mp_print(mp, "headerbyte"); break;
23524   default: mp_print(mp, "fontdimen"); break;
23525   }
23526   break;
23527
23528 @ @<Declare action procedures for use by |do_statement|@>=
23529 eight_bits mp_get_code (MP mp) ;
23530
23531 @ @c eight_bits mp_get_code (MP mp) { /* scans a character code value */
23532   integer c; /* the code value found */
23533   mp_get_x_next(mp); mp_scan_expression(mp);
23534   if ( mp->cur_type==mp_known ) { 
23535     c=mp_round_unscaled(mp, mp->cur_exp);
23536     if ( c>=0 ) if ( c<256 ) return c;
23537   } else if ( mp->cur_type==mp_string_type ) {
23538     if ( length(mp->cur_exp)==1 )  { 
23539       c=mp->str_pool[mp->str_start[mp->cur_exp]];
23540       return c;
23541     }
23542   }
23543   exp_err("Invalid code has been replaced by 0");
23544 @.Invalid code...@>
23545   help2("I was looking for a number between 0 and 255, or for a")
23546        ("string of length 1. Didn't find it; will use 0 instead.");
23547   mp_put_get_flush_error(mp, 0); c=0;
23548   return c;
23549 };
23550
23551 @ @<Declare action procedures for use by |do_statement|@>=
23552 void mp_set_tag (MP mp,halfword c, small_number t, halfword r) ;
23553
23554 @ @c void mp_set_tag (MP mp,halfword c, small_number t, halfword r) { 
23555   if ( mp->char_tag[c]==no_tag ) {
23556     mp->char_tag[c]=t; mp->char_remainder[c]=r;
23557     if ( t==lig_tag ){ 
23558       incr(mp->label_ptr); mp->label_loc[mp->label_ptr]=r; 
23559       mp->label_char[mp->label_ptr]=c;
23560     }
23561   } else {
23562     @<Complain about a character tag conflict@>;
23563   }
23564 }
23565
23566 @ @<Complain about a character tag conflict@>=
23567
23568   print_err("Character ");
23569   if ( (c>' ')&&(c<127) ) mp_print_char(mp,c);
23570   else if ( c==256 ) mp_print(mp, "||");
23571   else  { mp_print(mp, "code "); mp_print_int(mp, c); };
23572   mp_print(mp, " is already ");
23573 @.Character c is already...@>
23574   switch (mp->char_tag[c]) {
23575   case lig_tag: mp_print(mp, "in a ligtable"); break;
23576   case list_tag: mp_print(mp, "in a charlist"); break;
23577   case ext_tag: mp_print(mp, "extensible"); break;
23578   } /* there are no other cases */
23579   help2("It's not legal to label a character more than once.")
23580     ("So I'll not change anything just now.");
23581   mp_put_get_error(mp); 
23582 }
23583
23584 @ @<Declare action procedures for use by |do_statement|@>=
23585 void mp_do_tfm_command (MP mp) ;
23586
23587 @ @c void mp_do_tfm_command (MP mp) {
23588   int c,cc; /* character codes */
23589   int k; /* index into the |kern| array */
23590   int j; /* index into |header_byte| or |param| */
23591   switch (mp->cur_mod) {
23592   case char_list_code: 
23593     c=mp_get_code(mp);
23594      /* we will store a list of character successors */
23595     while ( mp->cur_cmd==colon )   { 
23596       cc=mp_get_code(mp); mp_set_tag(mp, c,list_tag,cc); c=cc;
23597     };
23598     break;
23599   case lig_table_code: 
23600     if (mp->lig_kern==NULL) 
23601        mp->lig_kern = xmalloc((max_tfm_int+1),sizeof(four_quarters));
23602     if (mp->kern==NULL) 
23603        mp->kern = xmalloc((max_tfm_int+1),sizeof(scaled));
23604     @<Store a list of ligature/kern steps@>;
23605     break;
23606   case extensible_code: 
23607     @<Define an extensible recipe@>;
23608     break;
23609   case header_byte_code: 
23610   case font_dimen_code: 
23611     c=mp->cur_mod; mp_get_x_next(mp);
23612     mp_scan_expression(mp);
23613     if ( (mp->cur_type!=mp_known)||(mp->cur_exp<half_unit) ) {
23614       exp_err("Improper location");
23615 @.Improper location@>
23616       help2("I was looking for a known, positive number.")
23617        ("For safety's sake I'll ignore the present command.");
23618       mp_put_get_error(mp);
23619     } else  { 
23620       j=mp_round_unscaled(mp, mp->cur_exp);
23621       if ( mp->cur_cmd!=colon ) {
23622         mp_missing_err(mp, ":");
23623 @.Missing `:'@>
23624         help1("A colon should follow a headerbyte or fontinfo location.");
23625         mp_back_error(mp);
23626       }
23627       if ( c==header_byte_code ) { 
23628         @<Store a list of header bytes@>;
23629       } else {     
23630         if (mp->param==NULL) 
23631           mp->param = xmalloc((max_tfm_int+1),sizeof(scaled));
23632         @<Store a list of font dimensions@>;
23633       }
23634     }
23635     break;
23636   } /* there are no other cases */
23637 };
23638
23639 @ @<Store a list of ligature/kern steps@>=
23640
23641   mp->lk_started=false;
23642 CONTINUE: 
23643   mp_get_x_next(mp);
23644   if ((mp->cur_cmd==skip_to)&& mp->lk_started )
23645     @<Process a |skip_to| command and |goto done|@>;
23646   if ( mp->cur_cmd==bchar_label ) { c=256; mp->cur_cmd=colon; }
23647   else { mp_back_input(mp); c=mp_get_code(mp); };
23648   if ((mp->cur_cmd==colon)||(mp->cur_cmd==double_colon)) {
23649     @<Record a label in a lig/kern subprogram and |goto continue|@>;
23650   }
23651   if ( mp->cur_cmd==lig_kern_token ) { 
23652     @<Compile a ligature/kern command@>; 
23653   } else  { 
23654     print_err("Illegal ligtable step");
23655 @.Illegal ligtable step@>
23656     help1("I was looking for `=:' or `kern' here.");
23657     mp_back_error(mp); next_char(mp->nl)=qi(0); 
23658     op_byte(mp->nl)=qi(0); rem_byte(mp->nl)=qi(0);
23659     skip_byte(mp->nl)=stop_flag+1; /* this specifies an unconditional stop */
23660   }
23661   if ( mp->nl==max_tfm_int) mp_fatal_error(mp, "ligtable too large");
23662   incr(mp->nl);
23663   if ( mp->cur_cmd==comma ) goto CONTINUE;
23664   if ( skip_byte(mp->nl-1)<stop_flag ) skip_byte(mp->nl-1)=stop_flag;
23665 }
23666 DONE:
23667
23668 @ @<Put each...@>=
23669 mp_primitive(mp, "=:",lig_kern_token,0);
23670 @:=:_}{\.{=:} primitive@>
23671 mp_primitive(mp, "=:|",lig_kern_token,1);
23672 @:=:/_}{\.{=:\char'174} primitive@>
23673 mp_primitive(mp, "=:|>",lig_kern_token,5);
23674 @:=:/>_}{\.{=:\char'174>} primitive@>
23675 mp_primitive(mp, "|=:",lig_kern_token,2);
23676 @:=:/_}{\.{\char'174=:} primitive@>
23677 mp_primitive(mp, "|=:>",lig_kern_token,6);
23678 @:=:/>_}{\.{\char'174=:>} primitive@>
23679 mp_primitive(mp, "|=:|",lig_kern_token,3);
23680 @:=:/_}{\.{\char'174=:\char'174} primitive@>
23681 mp_primitive(mp, "|=:|>",lig_kern_token,7);
23682 @:=:/>_}{\.{\char'174=:\char'174>} primitive@>
23683 mp_primitive(mp, "|=:|>>",lig_kern_token,11);
23684 @:=:/>_}{\.{\char'174=:\char'174>>} primitive@>
23685 mp_primitive(mp, "kern",lig_kern_token,128);
23686 @:kern_}{\&{kern} primitive@>
23687
23688 @ @<Cases of |print_cmd...@>=
23689 case lig_kern_token: 
23690   switch (m) {
23691   case 0:mp_print(mp, "=:"); break;
23692   case 1:mp_print(mp, "=:|"); break;
23693   case 2:mp_print(mp, "|=:"); break;
23694   case 3:mp_print(mp, "|=:|"); break;
23695   case 5:mp_print(mp, "=:|>"); break;
23696   case 6:mp_print(mp, "|=:>"); break;
23697   case 7:mp_print(mp, "|=:|>"); break;
23698   case 11:mp_print(mp, "|=:|>>"); break;
23699   default: mp_print(mp, "kern"); break;
23700   }
23701   break;
23702
23703 @ Local labels are implemented by maintaining the |skip_table| array,
23704 where |skip_table[c]| is either |undefined_label| or the address of the
23705 most recent lig/kern instruction that skips to local label~|c|. In the
23706 latter case, the |skip_byte| in that instruction will (temporarily)
23707 be zero if there were no prior skips to this label, or it will be the
23708 distance to the prior skip.
23709
23710 We may need to cancel skips that span more than 127 lig/kern steps.
23711
23712 @d cancel_skips(A) mp->ll=(A);
23713   do {  
23714     mp->lll=qo(skip_byte(mp->ll)); 
23715     skip_byte(mp->ll)=stop_flag; mp->ll=mp->ll-mp->lll;
23716   } while (mp->lll!=0)
23717 @d skip_error(A) { print_err("Too far to skip");
23718 @.Too far to skip@>
23719   help1("At most 127 lig/kern steps can separate skipto1 from 1::.");
23720   mp_error(mp); cancel_skips((A));
23721   }
23722
23723 @<Process a |skip_to| command and |goto done|@>=
23724
23725   c=mp_get_code(mp);
23726   if ( mp->nl-mp->skip_table[c]>128 ) { /* |skip_table[c]<<nl<=undefined_label| */
23727     skip_error(mp->skip_table[c]); mp->skip_table[c]=undefined_label;
23728   }
23729   if ( mp->skip_table[c]==undefined_label ) skip_byte(mp->nl-1)=qi(0);
23730   else skip_byte(mp->nl-1)=qi(mp->nl-mp->skip_table[c]-1);
23731   mp->skip_table[c]=mp->nl-1; goto DONE;
23732 }
23733
23734 @ @<Record a label in a lig/kern subprogram and |goto continue|@>=
23735
23736   if ( mp->cur_cmd==colon ) {
23737     if ( c==256 ) mp->bch_label=mp->nl;
23738     else mp_set_tag(mp, c,lig_tag,mp->nl);
23739   } else if ( mp->skip_table[c]<undefined_label ) {
23740     mp->ll=mp->skip_table[c]; mp->skip_table[c]=undefined_label;
23741     do {  
23742       mp->lll=qo(skip_byte(mp->ll));
23743       if ( mp->nl-mp->ll>128 ) {
23744         skip_error(mp->ll); goto CONTINUE;
23745       }
23746       skip_byte(mp->ll)=qi(mp->nl-mp->ll-1); mp->ll=mp->ll-mp->lll;
23747     } while (mp->lll!=0);
23748   }
23749   goto CONTINUE;
23750 }
23751
23752 @ @<Compile a ligature/kern...@>=
23753
23754   next_char(mp->nl)=qi(c); skip_byte(mp->nl)=qi(0);
23755   if ( mp->cur_mod<128 ) { /* ligature op */
23756     op_byte(mp->nl)=qi(mp->cur_mod); rem_byte(mp->nl)=qi(mp_get_code(mp));
23757   } else { 
23758     mp_get_x_next(mp); mp_scan_expression(mp);
23759     if ( mp->cur_type!=mp_known ) {
23760       exp_err("Improper kern");
23761 @.Improper kern@>
23762       help2("The amount of kern should be a known numeric value.")
23763         ("I'm zeroing this one. Proceed, with fingers crossed.");
23764       mp_put_get_flush_error(mp, 0);
23765     }
23766     mp->kern[mp->nk]=mp->cur_exp;
23767     k=0; 
23768     while ( mp->kern[k]!=mp->cur_exp ) incr(k);
23769     if ( k==mp->nk ) {
23770       if ( mp->nk==max_tfm_int ) mp_fatal_error(mp, "too many TFM kerns");
23771       incr(mp->nk);
23772     }
23773     op_byte(mp->nl)=kern_flag+(k / 256);
23774     rem_byte(mp->nl)=qi((k % 256));
23775   }
23776   mp->lk_started=true;
23777 }
23778
23779 @ @d missing_extensible_punctuation(A) 
23780   { mp_missing_err(mp, (A));
23781 @.Missing `\char`\#'@>
23782   help1("I'm processing `extensible c: t,m,b,r'."); mp_back_error(mp);
23783   }
23784
23785 @<Define an extensible recipe@>=
23786
23787   if ( mp->ne==256 ) mp_fatal_error(mp, "too many extensible recipies");
23788   c=mp_get_code(mp); mp_set_tag(mp, c,ext_tag,mp->ne);
23789   if ( mp->cur_cmd!=colon ) missing_extensible_punctuation(":");
23790   ext_top(mp->ne)=qi(mp_get_code(mp));
23791   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23792   ext_mid(mp->ne)=qi(mp_get_code(mp));
23793   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23794   ext_bot(mp->ne)=qi(mp_get_code(mp));
23795   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23796   ext_rep(mp->ne)=qi(mp_get_code(mp));
23797   incr(mp->ne);
23798 }
23799
23800 @ The header could contain ASCII zeroes, so can't use |strdup|.
23801
23802 @<Store a list of header bytes@>=
23803 do {  
23804   if ( j>=mp->header_size ) {
23805     int l = mp->header_size + (mp->header_size >> 2);
23806     char *t = xmalloc(l,sizeof(char));
23807     memset(t,0,l); 
23808     memcpy(t,mp->header_byte,mp->header_size);
23809     xfree (mp->header_byte);
23810     mp->header_byte = t;
23811     mp->header_size = l;
23812   }
23813   mp->header_byte[j]=mp_get_code(mp); 
23814   incr(j); incr(mp->header_last);
23815 } while (mp->cur_cmd==comma)
23816
23817 @ @<Store a list of font dimensions@>=
23818 do {  
23819   if ( j>max_tfm_int ) mp_fatal_error(mp, "too many fontdimens");
23820   while ( j>mp->np ) { incr(mp->np); mp->param[mp->np]=0; };
23821   mp_get_x_next(mp); mp_scan_expression(mp);
23822   if ( mp->cur_type!=mp_known ){ 
23823     exp_err("Improper font parameter");
23824 @.Improper font parameter@>
23825     help1("I'm zeroing this one. Proceed, with fingers crossed.");
23826     mp_put_get_flush_error(mp, 0);
23827   }
23828   mp->param[j]=mp->cur_exp; incr(j);
23829 } while (mp->cur_cmd==comma)
23830
23831 @ OK: We've stored all the data that is needed for the \.{TFM} file.
23832 All that remains is to output it in the correct format.
23833
23834 An interesting problem needs to be solved in this connection, because
23835 the \.{TFM} format allows at most 256~widths, 16~heights, 16~depths,
23836 and 64~italic corrections. If the data has more distinct values than
23837 this, we want to meet the necessary restrictions by perturbing the
23838 given values as little as possible.
23839
23840 \MP\ solves this problem in two steps. First the values of a given
23841 kind (widths, heights, depths, or italic corrections) are sorted;
23842 then the list of sorted values is perturbed, if necessary.
23843
23844 The sorting operation is facilitated by having a special node of
23845 essentially infinite |value| at the end of the current list.
23846
23847 @<Initialize table entries...@>=
23848 value(inf_val)=fraction_four;
23849
23850 @ Straight linear insertion is good enough for sorting, since the lists
23851 are usually not terribly long. As we work on the data, the current list
23852 will start at |link(temp_head)| and end at |inf_val|; the nodes in this
23853 list will be in increasing order of their |value| fields.
23854
23855 Given such a list, the |sort_in| function takes a value and returns a pointer
23856 to where that value can be found in the list. The value is inserted in
23857 the proper place, if necessary.
23858
23859 At the time we need to do these operations, most of \MP's work has been
23860 completed, so we will have plenty of memory to play with. The value nodes
23861 that are allocated for sorting will never be returned to free storage.
23862
23863 @d clear_the_list link(temp_head)=inf_val
23864
23865 @c pointer mp_sort_in (MP mp,scaled v) {
23866   pointer p,q,r; /* list manipulation registers */
23867   p=temp_head;
23868   while (1) { 
23869     q=link(p);
23870     if ( v<=value(q) ) break;
23871     p=q;
23872   }
23873   if ( v<value(q) ) {
23874     r=mp_get_node(mp, value_node_size); value(r)=v; link(r)=q; link(p)=r;
23875   }
23876   return link(p);
23877 }
23878
23879 @ Now we come to the interesting part, where we reduce the list if necessary
23880 until it has the required size. The |min_cover| routine is basic to this
23881 process; it computes the minimum number~|m| such that the values of the
23882 current sorted list can be covered by |m|~intervals of width~|d|. It
23883 also sets the global value |perturbation| to the smallest value $d'>d$
23884 such that the covering found by this algorithm would be different.
23885
23886 In particular, |min_cover(0)| returns the number of distinct values in the
23887 current list and sets |perturbation| to the minimum distance between
23888 adjacent values.
23889
23890 @c integer mp_min_cover (MP mp,scaled d) {
23891   pointer p; /* runs through the current list */
23892   scaled l; /* the least element covered by the current interval */
23893   integer m; /* lower bound on the size of the minimum cover */
23894   m=0; p=link(temp_head); mp->perturbation=el_gordo;
23895   while ( p!=inf_val ){ 
23896     incr(m); l=value(p);
23897     do {  p=link(p); } while (value(p)<=l+d);
23898     if ( value(p)-l<mp->perturbation ) 
23899       mp->perturbation=value(p)-l;
23900   }
23901   return m;
23902 }
23903
23904 @ @<Glob...@>=
23905 scaled perturbation; /* quantity related to \.{TFM} rounding */
23906 integer excess; /* the list is this much too long */
23907
23908 @ The smallest |d| such that a given list can be covered with |m| intervals
23909 is determined by the |threshold| routine, which is sort of an inverse
23910 to |min_cover|. The idea is to increase the interval size rapidly until
23911 finding the range, then to go sequentially until the exact borderline has
23912 been discovered.
23913
23914 @c scaled mp_threshold (MP mp,integer m) {
23915   scaled d; /* lower bound on the smallest interval size */
23916   mp->excess=mp_min_cover(mp, 0)-m;
23917   if ( mp->excess<=0 ) {
23918     return 0;
23919   } else  { 
23920     do {  
23921       d=mp->perturbation;
23922     } while (mp_min_cover(mp, d+d)>m);
23923     while ( mp_min_cover(mp, d)>m ) 
23924       d=mp->perturbation;
23925     return d;
23926   }
23927 }
23928
23929 @ The |skimp| procedure reduces the current list to at most |m| entries,
23930 by changing values if necessary. It also sets |info(p):=k| if |value(p)|
23931 is the |k|th distinct value on the resulting list, and it sets
23932 |perturbation| to the maximum amount by which a |value| field has
23933 been changed. The size of the resulting list is returned as the
23934 value of |skimp|.
23935
23936 @c integer mp_skimp (MP mp,integer m) {
23937   scaled d; /* the size of intervals being coalesced */
23938   pointer p,q,r; /* list manipulation registers */
23939   scaled l; /* the least value in the current interval */
23940   scaled v; /* a compromise value */
23941   d=mp_threshold(mp, m); mp->perturbation=0;
23942   q=temp_head; m=0; p=link(temp_head);
23943   while ( p!=inf_val ) {
23944     incr(m); l=value(p); info(p)=m;
23945     if ( value(link(p))<=l+d ) {
23946       @<Replace an interval of values by its midpoint@>;
23947     }
23948     q=p; p=link(p);
23949   }
23950   return m;
23951 }
23952
23953 @ @<Replace an interval...@>=
23954
23955   do {  
23956     p=link(p); info(p)=m;
23957     decr(mp->excess); if ( mp->excess==0 ) d=0;
23958   } while (value(link(p))<=l+d);
23959   v=l+halfp(value(p)-l);
23960   if ( value(p)-v>mp->perturbation ) 
23961     mp->perturbation=value(p)-v;
23962   r=q;
23963   do {  
23964     r=link(r); value(r)=v;
23965   } while (r!=p);
23966   link(q)=p; /* remove duplicate values from the current list */
23967 }
23968
23969 @ A warning message is issued whenever something is perturbed by
23970 more than 1/16\thinspace pt.
23971
23972 @c void mp_tfm_warning (MP mp,small_number m) { 
23973   mp_print_nl(mp, "(some "); 
23974   mp_print(mp, mp->int_name[m]);
23975 @.some charwds...@>
23976 @.some chardps...@>
23977 @.some charhts...@>
23978 @.some charics...@>
23979   mp_print(mp, " values had to be adjusted by as much as ");
23980   mp_print_scaled(mp, mp->perturbation); mp_print(mp, "pt)");
23981 }
23982
23983 @ Here's an example of how we use these routines.
23984 The width data needs to be perturbed only if there are 256 distinct
23985 widths, but \MP\ must check for this case even though it is
23986 highly unusual.
23987
23988 An integer variable |k| will be defined when we use this code.
23989 The |dimen_head| array will contain pointers to the sorted
23990 lists of dimensions.
23991
23992 @<Massage the \.{TFM} widths@>=
23993 clear_the_list;
23994 for (k=mp->bc;k<=mp->ec;k++)  {
23995   if ( mp->char_exists[k] )
23996     mp->tfm_width[k]=mp_sort_in(mp, mp->tfm_width[k]);
23997 }
23998 mp->nw=mp_skimp(mp, 255)+1; mp->dimen_head[1]=link(temp_head);
23999 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_wd)
24000
24001 @ @<Glob...@>=
24002 pointer dimen_head[5]; /* lists of \.{TFM} dimensions */
24003
24004 @ Heights, depths, and italic corrections are different from widths
24005 not only because their list length is more severely restricted, but
24006 also because zero values do not need to be put into the lists.
24007
24008 @<Massage the \.{TFM} heights, depths, and italic corrections@>=
24009 clear_the_list;
24010 for (k=mp->bc;k<=mp->ec;k++) {
24011   if ( mp->char_exists[k] ) {
24012     if ( mp->tfm_height[k]==0 ) mp->tfm_height[k]=zero_val;
24013     else mp->tfm_height[k]=mp_sort_in(mp, mp->tfm_height[k]);
24014   }
24015 }
24016 mp->nh=mp_skimp(mp, 15)+1; mp->dimen_head[2]=link(temp_head);
24017 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ht);
24018 clear_the_list;
24019 for (k=mp->bc;k<=mp->ec;k++) {
24020   if ( mp->char_exists[k] ) {
24021     if ( mp->tfm_depth[k]==0 ) mp->tfm_depth[k]=zero_val;
24022     else mp->tfm_depth[k]=mp_sort_in(mp, mp->tfm_depth[k]);
24023   }
24024 }
24025 mp->nd=mp_skimp(mp, 15)+1; mp->dimen_head[3]=link(temp_head);
24026 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_dp);
24027 clear_the_list;
24028 for (k=mp->bc;k<=mp->ec;k++) {
24029   if ( mp->char_exists[k] ) {
24030     if ( mp->tfm_ital_corr[k]==0 ) mp->tfm_ital_corr[k]=zero_val;
24031     else mp->tfm_ital_corr[k]=mp_sort_in(mp, mp->tfm_ital_corr[k]);
24032   }
24033 }
24034 mp->ni=mp_skimp(mp, 63)+1; mp->dimen_head[4]=link(temp_head);
24035 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ic)
24036
24037 @ @<Initialize table entries...@>=
24038 value(zero_val)=0; info(zero_val)=0;
24039
24040 @ Bytes 5--8 of the header are set to the design size, unless the user has
24041 some crazy reason for specifying them differently.
24042
24043 Error messages are not allowed at the time this procedure is called,
24044 so a warning is printed instead.
24045
24046 The value of |max_tfm_dimen| is calculated so that
24047 $$\hbox{|make_scaled(16*max_tfm_dimen,internal[mp_design_size])|}
24048  < \\{three\_bytes}.$$
24049
24050 @d three_bytes 0100000000 /* $2^{24}$ */
24051
24052 @c 
24053 void mp_fix_design_size (MP mp) {
24054   scaled d; /* the design size */
24055   d=mp->internal[mp_design_size];
24056   if ( (d<unity)||(d>=fraction_half) ) {
24057     if ( d!=0 )
24058       mp_print_nl(mp, "(illegal design size has been changed to 128pt)");
24059 @.illegal design size...@>
24060     d=040000000; mp->internal[mp_design_size]=d;
24061   }
24062   if ( mp->header_byte[4]<0 ) if ( mp->header_byte[5]<0 )
24063     if ( mp->header_byte[6]<0 ) if ( mp->header_byte[7]<0 ) {
24064      mp->header_byte[4]=d / 04000000;
24065      mp->header_byte[5]=(d / 4096) % 256;
24066      mp->header_byte[6]=(d / 16) % 256;
24067      mp->header_byte[7]=(d % 16)*16;
24068   };
24069   mp->max_tfm_dimen=16*mp->internal[mp_design_size]-mp->internal[mp_design_size] / 010000000;
24070   if ( mp->max_tfm_dimen>=fraction_half ) mp->max_tfm_dimen=fraction_half-1;
24071 }
24072
24073 @ The |dimen_out| procedure computes a |fix_word| relative to the
24074 design size. If the data was out of range, it is corrected and the
24075 global variable |tfm_changed| is increased by~one.
24076
24077 @c integer mp_dimen_out (MP mp,scaled x) { 
24078   if ( abs(x)>mp->max_tfm_dimen ) {
24079     incr(mp->tfm_changed);
24080     if ( x>0 ) x=three_bytes-1; else x=1-three_bytes;
24081   } else {
24082     x=mp_make_scaled(mp, x*16,mp->internal[mp_design_size]);
24083   }
24084   return x;
24085 }
24086
24087 @ @<Glob...@>=
24088 scaled max_tfm_dimen; /* bound on widths, heights, kerns, etc. */
24089 integer tfm_changed; /* the number of data entries that were out of bounds */
24090
24091 @ If the user has not specified any of the first four header bytes,
24092 the |fix_check_sum| procedure replaces them by a ``check sum'' computed
24093 from the |tfm_width| data relative to the design size.
24094 @^check sum@>
24095
24096 @c void mp_fix_check_sum (MP mp) {
24097   eight_bits k; /* runs through character codes */
24098   eight_bits B1,B2,B3,B4; /* bytes of the check sum */
24099   integer x;  /* hash value used in check sum computation */
24100   if ( mp->header_byte[0]==0 && mp->header_byte[1]==0 &&
24101        mp->header_byte[2]==0 && mp->header_byte[3]==0 ) {
24102     @<Compute a check sum in |(b1,b2,b3,b4)|@>;
24103     mp->header_byte[0]=B1; mp->header_byte[1]=B2;
24104     mp->header_byte[2]=B3; mp->header_byte[3]=B4; 
24105     return;
24106   }
24107 }
24108
24109 @ @<Compute a check sum in |(b1,b2,b3,b4)|@>=
24110 B1=mp->bc; B2=mp->ec; B3=mp->bc; B4=mp->ec; mp->tfm_changed=0;
24111 for (k=mp->bc;k<=mp->ec;k++) { 
24112   if ( mp->char_exists[k] ) {
24113     x=mp_dimen_out(mp, value(mp->tfm_width[k]))+(k+4)*020000000; /* this is positive */
24114     B1=(B1+B1+x) % 255;
24115     B2=(B2+B2+x) % 253;
24116     B3=(B3+B3+x) % 251;
24117     B4=(B4+B4+x) % 247;
24118   }
24119 }
24120
24121 @ Finally we're ready to actually write the \.{TFM} information.
24122 Here are some utility routines for this purpose.
24123
24124 @d tfm_out(A) do { /* output one byte to |tfm_file| */
24125   unsigned char s=(A); 
24126   (mp->write_binary_file)(mp->tfm_file,(void *)&s,1); 
24127   } while (0)
24128
24129 @c void mp_tfm_two (MP mp,integer x) { /* output two bytes to |tfm_file| */
24130   tfm_out(x / 256); tfm_out(x % 256);
24131 }
24132 void mp_tfm_four (MP mp,integer x) { /* output four bytes to |tfm_file| */
24133   if ( x>=0 ) tfm_out(x / three_bytes);
24134   else { 
24135     x=x+010000000000; /* use two's complement for negative values */
24136     x=x+010000000000;
24137     tfm_out((x / three_bytes) + 128);
24138   };
24139   x=x % three_bytes; tfm_out(x / unity);
24140   x=x % unity; tfm_out(x / 0400);
24141   tfm_out(x % 0400);
24142 }
24143 void mp_tfm_qqqq (MP mp,four_quarters x) { /* output four quarterwords to |tfm_file| */
24144   tfm_out(qo(x.b0)); tfm_out(qo(x.b1)); 
24145   tfm_out(qo(x.b2)); tfm_out(qo(x.b3));
24146 }
24147
24148 @ @<Finish the \.{TFM} file@>=
24149 if ( mp->job_name==NULL ) mp_open_log_file(mp);
24150 mp_pack_job_name(mp, ".tfm");
24151 while ( ! mp_b_open_out(mp, &mp->tfm_file, mp_filetype_metrics) )
24152   mp_prompt_file_name(mp, "file name for font metrics",".tfm");
24153 mp->metric_file_name=xstrdup(mp->name_of_file);
24154 @<Output the subfile sizes and header bytes@>;
24155 @<Output the character information bytes, then
24156   output the dimensions themselves@>;
24157 @<Output the ligature/kern program@>;
24158 @<Output the extensible character recipes and the font metric parameters@>;
24159   if ( mp->internal[mp_tracing_stats]>0 )
24160   @<Log the subfile sizes of the \.{TFM} file@>;
24161 mp_print_nl(mp, "Font metrics written on "); 
24162 mp_print(mp, mp->metric_file_name); mp_print_char(mp, '.');
24163 @.Font metrics written...@>
24164 (mp->close_file)(mp->tfm_file)
24165
24166 @ Integer variables |lh|, |k|, and |lk_offset| will be defined when we use
24167 this code.
24168
24169 @<Output the subfile sizes and header bytes@>=
24170 k=mp->header_last;
24171 LH=(k+3) / 4; /* this is the number of header words */
24172 if ( mp->bc>mp->ec ) mp->bc=1; /* if there are no characters, |ec=0| and |bc=1| */
24173 @<Compute the ligature/kern program offset and implant the
24174   left boundary label@>;
24175 mp_tfm_two(mp,6+LH+(mp->ec-mp->bc+1)+mp->nw+mp->nh+mp->nd+mp->ni+mp->nl
24176      +lk_offset+mp->nk+mp->ne+mp->np);
24177   /* this is the total number of file words that will be output */
24178 mp_tfm_two(mp, LH); mp_tfm_two(mp, mp->bc); mp_tfm_two(mp, mp->ec); 
24179 mp_tfm_two(mp, mp->nw); mp_tfm_two(mp, mp->nh);
24180 mp_tfm_two(mp, mp->nd); mp_tfm_two(mp, mp->ni); mp_tfm_two(mp, mp->nl+lk_offset); 
24181 mp_tfm_two(mp, mp->nk); mp_tfm_two(mp, mp->ne);
24182 mp_tfm_two(mp, mp->np);
24183 for (k=0;k< 4*LH;k++)   { 
24184   tfm_out(mp->header_byte[k]);
24185 }
24186
24187 @ @<Output the character information bytes...@>=
24188 for (k=mp->bc;k<=mp->ec;k++) {
24189   if ( ! mp->char_exists[k] ) {
24190     mp_tfm_four(mp, 0);
24191   } else { 
24192     tfm_out(info(mp->tfm_width[k])); /* the width index */
24193     tfm_out((info(mp->tfm_height[k]))*16+info(mp->tfm_depth[k]));
24194     tfm_out((info(mp->tfm_ital_corr[k]))*4+mp->char_tag[k]);
24195     tfm_out(mp->char_remainder[k]);
24196   };
24197 }
24198 mp->tfm_changed=0;
24199 for (k=1;k<=4;k++) { 
24200   mp_tfm_four(mp, 0); p=mp->dimen_head[k];
24201   while ( p!=inf_val ) {
24202     mp_tfm_four(mp, mp_dimen_out(mp, value(p))); p=link(p);
24203   }
24204 }
24205
24206
24207 @ We need to output special instructions at the beginning of the
24208 |lig_kern| array in order to specify the right boundary character
24209 and/or to handle starting addresses that exceed 255. The |label_loc|
24210 and |label_char| arrays have been set up to record all the
24211 starting addresses; we have $-1=|label_loc|[0]<|label_loc|[1]\le\cdots
24212 \le|label_loc|[|label_ptr]|$.
24213
24214 @<Compute the ligature/kern program offset...@>=
24215 mp->bchar=mp_round_unscaled(mp, mp->internal[mp_boundary_char]);
24216 if ((mp->bchar<0)||(mp->bchar>255))
24217   { mp->bchar=-1; mp->lk_started=false; lk_offset=0; }
24218 else { mp->lk_started=true; lk_offset=1; };
24219 @<Find the minimum |lk_offset| and adjust all remainders@>;
24220 if ( mp->bch_label<undefined_label )
24221   { skip_byte(mp->nl)=qi(255); next_char(mp->nl)=qi(0);
24222   op_byte(mp->nl)=qi(((mp->bch_label+lk_offset)/ 256));
24223   rem_byte(mp->nl)=qi(((mp->bch_label+lk_offset)% 256));
24224   incr(mp->nl); /* possibly |nl=lig_table_size+1| */
24225   }
24226
24227 @ @<Find the minimum |lk_offset|...@>=
24228 k=mp->label_ptr; /* pointer to the largest unallocated label */
24229 if ( mp->label_loc[k]+lk_offset>255 ) {
24230   lk_offset=0; mp->lk_started=false; /* location 0 can do double duty */
24231   do {  
24232     mp->char_remainder[mp->label_char[k]]=lk_offset;
24233     while ( mp->label_loc[k-1]==mp->label_loc[k] ) {
24234        decr(k); mp->char_remainder[mp->label_char[k]]=lk_offset;
24235     }
24236     incr(lk_offset); decr(k);
24237   } while (! (lk_offset+mp->label_loc[k]<256));
24238     /* N.B.: |lk_offset=256| satisfies this when |k=0| */
24239 };
24240 if ( lk_offset>0 ) {
24241   while ( k>0 ) {
24242     mp->char_remainder[mp->label_char[k]]
24243      =mp->char_remainder[mp->label_char[k]]+lk_offset;
24244     decr(k);
24245   }
24246 }
24247
24248 @ @<Output the ligature/kern program@>=
24249 for (k=0;k<= 255;k++ ) {
24250   if ( mp->skip_table[k]<undefined_label ) {
24251      mp_print_nl(mp, "(local label "); mp_print_int(mp, k); mp_print(mp, ":: was missing)");
24252 @.local label l:: was missing@>
24253     cancel_skips(mp->skip_table[k]);
24254   }
24255 }
24256 if ( mp->lk_started ) { /* |lk_offset=1| for the special |bchar| */
24257   tfm_out(255); tfm_out(mp->bchar); mp_tfm_two(mp, 0);
24258 } else {
24259   for (k=1;k<=lk_offset;k++) {/* output the redirection specs */
24260     mp->ll=mp->label_loc[mp->label_ptr];
24261     if ( mp->bchar<0 ) { tfm_out(254); tfm_out(0);   }
24262     else { tfm_out(255); tfm_out(mp->bchar);   };
24263     mp_tfm_two(mp, mp->ll+lk_offset);
24264     do {  
24265       decr(mp->label_ptr);
24266     } while (! (mp->label_loc[mp->label_ptr]<mp->ll));
24267   }
24268 }
24269 for (k=0;k<=mp->nl-1;k++) mp_tfm_qqqq(mp, mp->lig_kern[k]);
24270 for (k=0;k<=mp->nk-1;k++) mp_tfm_four(mp, mp_dimen_out(mp, mp->kern[k]))
24271
24272 @ @<Output the extensible character recipes...@>=
24273 for (k=0;k<=mp->ne-1;k++) 
24274   mp_tfm_qqqq(mp, mp->exten[k]);
24275 for (k=1;k<=mp->np;k++) {
24276   if ( k==1 ) {
24277     if ( abs(mp->param[1])<fraction_half ) {
24278       mp_tfm_four(mp, mp->param[1]*16);
24279     } else  { 
24280       incr(mp->tfm_changed);
24281       if ( mp->param[1]>0 ) mp_tfm_four(mp, el_gordo);
24282       else mp_tfm_four(mp, -el_gordo);
24283     }
24284   } else {
24285     mp_tfm_four(mp, mp_dimen_out(mp, mp->param[k]));
24286   }
24287 }
24288 if ( mp->tfm_changed>0 )  { 
24289   if ( mp->tfm_changed==1 ) mp_print_nl(mp, "(a font metric dimension");
24290 @.a font metric dimension...@>
24291   else  { 
24292     mp_print_nl(mp, "("); mp_print_int(mp, mp->tfm_changed);
24293 @.font metric dimensions...@>
24294     mp_print(mp, " font metric dimensions");
24295   }
24296   mp_print(mp, " had to be decreased)");
24297 }
24298
24299 @ @<Log the subfile sizes of the \.{TFM} file@>=
24300
24301   char s[200];
24302   wlog_ln(" ");
24303   if ( mp->bch_label<undefined_label ) decr(mp->nl);
24304   snprintf(s,128,"(You used %iw,%ih,%id,%ii,%il,%ik,%ie,%ip metric file positions)",
24305                  mp->nw, mp->nh, mp->nd, mp->ni, mp->nl, mp->nk, mp->ne,mp->np);
24306   wlog_ln(s);
24307 }
24308
24309 @* \[43] Reading font metric data.
24310
24311 \MP\ isn't a typesetting program but it does need to find the bounding box
24312 of a sequence of typeset characters.  Thus it needs to read \.{TFM} files as
24313 well as write them.
24314
24315 @<Glob...@>=
24316 void * tfm_infile;
24317
24318 @ All the width, height, and depth information is stored in an array called
24319 |font_info|.  This array is allocated sequentially and each font is stored
24320 as a series of |char_info| words followed by the width, height, and depth
24321 tables.  Since |font_name| entries are permanent, their |str_ref| values are
24322 set to |max_str_ref|.
24323
24324 @<Types...@>=
24325 typedef unsigned int font_number; /* |0..font_max| */
24326
24327 @ The |font_info| array is indexed via a group directory arrays.
24328 For example, the |char_info| data for character~|c| in font~|f| will be
24329 in |font_info[char_base[f]+c].qqqq|.
24330
24331 @<Glob...@>=
24332 font_number font_max; /* maximum font number for included text fonts */
24333 size_t      font_mem_size; /* number of words for \.{TFM} information for text fonts */
24334 memory_word *font_info; /* height, width, and depth data */
24335 char        **font_enc_name; /* encoding names, if any */
24336 boolean     *font_ps_name_fixed; /* are the postscript names fixed already?  */
24337 int         next_fmem; /* next unused entry in |font_info| */
24338 font_number last_fnum; /* last font number used so far */
24339 scaled      *font_dsize;  /* 16 times the ``design'' size in \ps\ points */
24340 char        **font_name;  /* name as specified in the \&{infont} command */
24341 char        **font_ps_name;  /* PostScript name for use when |internal[mp_prologues]>0| */
24342 font_number last_ps_fnum; /* last valid |font_ps_name| index */
24343 eight_bits  *font_bc;
24344 eight_bits  *font_ec;  /* first and last character code */
24345 int         *char_base;  /* base address for |char_info| */
24346 int         *width_base; /* index for zeroth character width */
24347 int         *height_base; /* index for zeroth character height */
24348 int         *depth_base; /* index for zeroth character depth */
24349 pointer     *font_sizes;
24350
24351 @ @<Allocate or initialize ...@>=
24352 mp->font_mem_size = 10000; 
24353 mp->font_info = xmalloc ((mp->font_mem_size+1),sizeof(memory_word));
24354 memset (mp->font_info,0,sizeof(memory_word)*(mp->font_mem_size+1));
24355 mp->font_enc_name = NULL;
24356 mp->font_ps_name_fixed = NULL;
24357 mp->font_dsize = NULL;
24358 mp->font_name = NULL;
24359 mp->font_ps_name = NULL;
24360 mp->font_bc = NULL;
24361 mp->font_ec = NULL;
24362 mp->last_fnum = null_font;
24363 mp->char_base = NULL;
24364 mp->width_base = NULL;
24365 mp->height_base = NULL;
24366 mp->depth_base = NULL;
24367 mp->font_sizes = null;
24368
24369 @ @<Dealloc variables@>=
24370 for (k=1;k<=(int)mp->last_fnum;k++) {
24371   xfree(mp->font_enc_name[k]);
24372   xfree(mp->font_name[k]);
24373   xfree(mp->font_ps_name[k]);
24374 }
24375 xfree(mp->font_info);
24376 xfree(mp->font_enc_name);
24377 xfree(mp->font_ps_name_fixed);
24378 xfree(mp->font_dsize);
24379 xfree(mp->font_name);
24380 xfree(mp->font_ps_name);
24381 xfree(mp->font_bc);
24382 xfree(mp->font_ec);
24383 xfree(mp->char_base);
24384 xfree(mp->width_base);
24385 xfree(mp->height_base);
24386 xfree(mp->depth_base);
24387 xfree(mp->font_sizes);
24388
24389
24390 @c 
24391 void mp_reallocate_fonts (MP mp, font_number l) {
24392   font_number f;
24393   XREALLOC(mp->font_enc_name,      l, char *);
24394   XREALLOC(mp->font_ps_name_fixed, l, boolean);
24395   XREALLOC(mp->font_dsize,         l, scaled);
24396   XREALLOC(mp->font_name,          l, char *);
24397   XREALLOC(mp->font_ps_name,       l, char *);
24398   XREALLOC(mp->font_bc,            l, eight_bits);
24399   XREALLOC(mp->font_ec,            l, eight_bits);
24400   XREALLOC(mp->char_base,          l, int);
24401   XREALLOC(mp->width_base,         l, int);
24402   XREALLOC(mp->height_base,        l, int);
24403   XREALLOC(mp->depth_base,         l, int);
24404   XREALLOC(mp->font_sizes,         l, pointer);
24405   for (f=(mp->last_fnum+1);f<=l;f++) {
24406     mp->font_enc_name[f]=NULL;
24407     mp->font_ps_name_fixed[f] = false;
24408     mp->font_name[f]=NULL;
24409     mp->font_ps_name[f]=NULL;
24410     mp->font_sizes[f]=null;
24411   }
24412   mp->font_max = l;
24413 }
24414
24415 @ @<Declare |mp_reallocate| functions@>=
24416 void mp_reallocate_fonts (MP mp, font_number l);
24417
24418
24419 @ A |null_font| containing no characters is useful for error recovery.  Its
24420 |font_name| entry starts out empty but is reset each time an erroneous font is
24421 found.  This helps to cut down on the number of duplicate error messages without
24422 wasting a lot of space.
24423
24424 @d null_font 0 /* the |font_number| for an empty font */
24425
24426 @<Set initial...@>=
24427 mp->font_dsize[null_font]=0;
24428 mp->font_bc[null_font]=1;
24429 mp->font_ec[null_font]=0;
24430 mp->char_base[null_font]=0;
24431 mp->width_base[null_font]=0;
24432 mp->height_base[null_font]=0;
24433 mp->depth_base[null_font]=0;
24434 mp->next_fmem=0;
24435 mp->last_fnum=null_font;
24436 mp->last_ps_fnum=null_font;
24437 mp->font_name[null_font]="nullfont";
24438 mp->font_ps_name[null_font]="";
24439 mp->font_ps_name_fixed[null_font] = false;
24440 mp->font_enc_name[null_font]=NULL;
24441 mp->font_sizes[null_font]=null;
24442
24443 @ Each |char_info| word is of type |four_quarters|.  The |b0| field contains
24444 the |width index|; the |b1| field contains the height
24445 index; the |b2| fields contains the depth index, and the |b3| field used only
24446 for temporary storage. (It is used to keep track of which characters occur in
24447 an edge structure that is being shipped out.)
24448 The corresponding words in the width, height, and depth tables are stored as
24449 |scaled| values in units of \ps\ points.
24450
24451 With the macros below, the |char_info| word for character~|c| in font~|f| is
24452 |char_info(f)(c)| and the width is
24453 $$\hbox{|char_width(f)(char_info(f)(c)).sc|.}$$
24454
24455 @d char_info_end(A) (A)].qqqq
24456 @d char_info(A) mp->font_info[mp->char_base[(A)]+char_info_end
24457 @d char_width_end(A) (A).b0].sc
24458 @d char_width(A) mp->font_info[mp->width_base[(A)]+char_width_end
24459 @d char_height_end(A) (A).b1].sc
24460 @d char_height(A) mp->font_info[mp->height_base[(A)]+char_height_end
24461 @d char_depth_end(A) (A).b2].sc
24462 @d char_depth(A) mp->font_info[mp->depth_base[(A)]+char_depth_end
24463 @d ichar_exists(A) ((A).b0>0)
24464
24465 @ The |font_ps_name| for a built-in font should be what PostScript expects.
24466 A preliminary name is obtained here from the \.{TFM} name as given in the
24467 |fname| argument.  This gets updated later from an external table if necessary.
24468
24469 @<Declare text measuring subroutines@>=
24470 @<Declare subroutines for parsing file names@>;
24471 font_number mp_read_font_info (MP mp, char *fname) {
24472   boolean file_opened; /* has |tfm_infile| been opened? */
24473   font_number n; /* the number to return */
24474   halfword lf,tfm_lh,bc,ec,nw,nh,nd; /* subfile size parameters */
24475   size_t whd_size; /* words needed for heights, widths, and depths */
24476   int i,ii; /* |font_info| indices */
24477   int jj; /* counts bytes to be ignored */
24478   scaled z; /* used to compute the design size */
24479   fraction d;
24480   /* height, width, or depth as a fraction of design size times $2^{-8}$ */
24481   eight_bits h_and_d; /* height and depth indices being unpacked */
24482   unsigned char tfbyte; /* a byte read from the file */
24483   n=null_font;
24484   @<Open |tfm_infile| for input@>;
24485   @<Read data from |tfm_infile|; if there is no room, say so and |goto done|;
24486     otherwise |goto bad_tfm| or |goto done| as appropriate@>;
24487 BAD_TFM:
24488   @<Complain that the \.{TFM} file is bad@>;
24489 DONE:
24490   if ( file_opened ) (mp->close_file)(mp->tfm_infile);
24491   if ( n!=null_font ) { 
24492     mp->font_ps_name[n]=mp_xstrdup(mp,fname);
24493     mp->font_name[n]=mp_xstrdup(mp,fname);
24494   }
24495   return n;
24496 }
24497
24498 @ \MP\ doesn't bother to check the entire \.{TFM} file for errors or explain
24499 precisely what is wrong if it does find a problem.  Programs called \.{TFtoPL}
24500 @.TFtoPL@> @.PLtoTF@>
24501 and \.{PLtoTF} can be used to debug \.{TFM} files.
24502
24503 @<Complain that the \.{TFM} file is bad@>=
24504 print_err("Font ");
24505 mp_print(mp, fname);
24506 if ( file_opened ) mp_print(mp, " not usable: TFM file is bad");
24507 else mp_print(mp, " not usable: TFM file not found");
24508 help3("I wasn't able to read the size data for this font so this")
24509   ("`infont' operation won't produce anything. If the font name")
24510   ("is right, you might ask an expert to make a TFM file");
24511 if ( file_opened )
24512   mp->help_line[0]="is right, try asking an expert to fix the TFM file";
24513 mp_error(mp)
24514
24515 @ @<Read data from |tfm_infile|; if there is no room, say so...@>=
24516 @<Read the \.{TFM} size fields@>;
24517 @<Use the size fields to allocate space in |font_info|@>;
24518 @<Read the \.{TFM} header@>;
24519 @<Read the character data and the width, height, and depth tables and
24520   |goto done|@>
24521
24522 @ A bad \.{TFM} file can be shorter than it claims to be.  The code given here
24523 might try to read past the end of the file if this happens.  Changes will be
24524 needed if it causes a system error to refer to |tfm_infile^| or call
24525 |get_tfm_infile| when |eof(tfm_infile)| is true.  For example, the definition
24526 @^system dependencies@>
24527 of |tfget| could be changed to
24528 ``|begin get(tfm_infile); if eof(tfm_infile) then goto bad_tfm; end|.''
24529
24530 @d tfget do { 
24531   size_t wanted=1; 
24532   void *tfbyte_ptr = &tfbyte;
24533   (mp->read_binary_file)(mp->tfm_infile,&tfbyte_ptr,&wanted); 
24534   if (wanted==0) goto BAD_TFM; 
24535 } while (0)
24536 @d read_two(A) { (A)=tfbyte;
24537   if ( (A)>127 ) goto BAD_TFM;
24538   tfget; (A)=(A)*0400+tfbyte;
24539 }
24540 @d tf_ignore(A) { for (jj=(A);jj>=1;jj--) tfget; }
24541
24542 @<Read the \.{TFM} size fields@>=
24543 tfget; read_two(lf);
24544 tfget; read_two(tfm_lh);
24545 tfget; read_two(bc);
24546 tfget; read_two(ec);
24547 if ( (bc>1+ec)||(ec>255) ) goto BAD_TFM;
24548 tfget; read_two(nw);
24549 tfget; read_two(nh);
24550 tfget; read_two(nd);
24551 whd_size=(ec+1-bc)+nw+nh+nd;
24552 if ( lf<(int)(6+tfm_lh+whd_size) ) goto BAD_TFM;
24553 tf_ignore(10)
24554
24555 @ Offsets are added to |char_base[n]| and |width_base[n]| so that is not
24556 necessary to apply the |so|  and |qo| macros when looking up the width of a
24557 character in the string pool.  In order to ensure nonnegative |char_base|
24558 values when |bc>0|, it may be necessary to reserve a few unused |font_info|
24559 elements.
24560
24561 @<Use the size fields to allocate space in |font_info|@>=
24562 if ( mp->next_fmem<bc) mp->next_fmem=bc;  /* ensure nonnegative |char_base| */
24563 if (mp->last_fnum==mp->font_max)
24564   mp_reallocate_fonts(mp,(mp->font_max+(mp->font_max>>2)));
24565 while (mp->next_fmem+whd_size>=mp->font_mem_size) {
24566   size_t l = mp->font_mem_size+(mp->font_mem_size>>2);
24567   memory_word *font_info;
24568   font_info = xmalloc ((l+1),sizeof(memory_word));
24569   memset (font_info,0,sizeof(memory_word)*(l+1));
24570   memcpy (font_info,mp->font_info,sizeof(memory_word)*(mp->font_mem_size+1));
24571   xfree(mp->font_info);
24572   mp->font_info = font_info;
24573   mp->font_mem_size = l;
24574 }
24575 incr(mp->last_fnum);
24576 n=mp->last_fnum;
24577 mp->font_bc[n]=bc;
24578 mp->font_ec[n]=ec;
24579 mp->char_base[n]=mp->next_fmem-bc;
24580 mp->width_base[n]=mp->next_fmem+ec-bc+1;
24581 mp->height_base[n]=mp->width_base[n]+nw;
24582 mp->depth_base[n]=mp->height_base[n]+nh;
24583 mp->next_fmem=mp->next_fmem+whd_size;
24584
24585
24586 @ @<Read the \.{TFM} header@>=
24587 if ( tfm_lh<2 ) goto BAD_TFM;
24588 tf_ignore(4);
24589 tfget; read_two(z);
24590 tfget; z=z*0400+tfbyte;
24591 tfget; z=z*0400+tfbyte; /* now |z| is 16 times the design size */
24592 mp->font_dsize[n]=mp_take_fraction(mp, z,267432584);
24593   /* times ${72\over72.27}2^{28}$ to convert from \TeX\ points */
24594 tf_ignore(4*(tfm_lh-2))
24595
24596 @ @<Read the character data and the width, height, and depth tables...@>=
24597 ii=mp->width_base[n];
24598 i=mp->char_base[n]+bc;
24599 while ( i<ii ) { 
24600   tfget; mp->font_info[i].qqqq.b0=qi(tfbyte);
24601   tfget; h_and_d=tfbyte;
24602   mp->font_info[i].qqqq.b1=h_and_d / 16;
24603   mp->font_info[i].qqqq.b2=h_and_d % 16;
24604   tfget; tfget;
24605   incr(i);
24606 }
24607 while ( i<mp->next_fmem ) {
24608   @<Read a four byte dimension, scale it by the design size, store it in
24609     |font_info[i]|, and increment |i|@>;
24610 }
24611 goto DONE
24612
24613 @ The raw dimension read into |d| should have magnitude at most $2^{24}$ when
24614 interpreted as an integer, and this includes a scale factor of $2^{20}$.  Thus
24615 we can multiply it by sixteen and think of it as a |fraction| that has been
24616 divided by sixteen.  This cancels the extra scale factor contained in
24617 |font_dsize[n|.
24618
24619 @<Read a four byte dimension, scale it by the design size, store it in...@>=
24620
24621 tfget; d=tfbyte;
24622 if ( d>=0200 ) d=d-0400;
24623 tfget; d=d*0400+tfbyte;
24624 tfget; d=d*0400+tfbyte;
24625 tfget; d=d*0400+tfbyte;
24626 mp->font_info[i].sc=mp_take_fraction(mp, d*16,mp->font_dsize[n]);
24627 incr(i);
24628 }
24629
24630 @ This function does no longer use the file name parser, because |fname| is
24631 a C string already.
24632 @<Open |tfm_infile| for input@>=
24633 file_opened=false;
24634 mp_ptr_scan_file(mp, fname);
24635 if ( strlen(mp->cur_area)==0 ) { xfree(mp->cur_area); mp->cur_area=xstrdup(MP_font_area);}
24636 if ( strlen(mp->cur_ext)==0 )  { xfree(mp->cur_ext); mp->cur_ext=xstrdup(".tfm"); }
24637 pack_cur_name;
24638 mp->tfm_infile = (mp->open_file)( mp->name_of_file, "rb",mp_filetype_metrics);
24639 if ( !mp->tfm_infile  ) goto BAD_TFM;
24640 file_opened=true
24641
24642 @ When we have a font name and we don't know whether it has been loaded yet,
24643 we scan the |font_name| array before calling |read_font_info|.
24644
24645 @<Declare text measuring subroutines@>=
24646 font_number mp_find_font (MP mp, char *f) {
24647   font_number n;
24648   for (n=0;n<=mp->last_fnum;n++) {
24649     if (mp_xstrcmp(f,mp->font_name[n])==0 ) {
24650       mp_xfree(f);
24651       return n;
24652     }
24653   }
24654   n = mp_read_font_info(mp, f);
24655   mp_xfree(f);
24656   return n;
24657 }
24658
24659 @ One simple application of |find_font| is the implementation of the |font_size|
24660 operator that gets the design size for a given font name.
24661
24662 @<Find the design size of the font whose name is |cur_exp|@>=
24663 mp_flush_cur_exp(mp, (mp->font_dsize[mp_find_font(mp, str(mp->cur_exp))]+8) / 16)
24664
24665 @ If we discover that the font doesn't have a requested character, we omit it
24666 from the bounding box computation and expect the \ps\ interpreter to drop it.
24667 This routine issues a warning message if the user has asked for it.
24668
24669 @<Declare text measuring subroutines@>=
24670 void mp_lost_warning (MP mp,font_number f, pool_pointer k) { 
24671   if ( mp->internal[mp_tracing_lost_chars]>0 ) { 
24672     mp_begin_diagnostic(mp);
24673     if ( mp->selector==log_only ) incr(mp->selector);
24674     mp_print_nl(mp, "Missing character: There is no ");
24675 @.Missing character@>
24676     mp_print_str(mp, mp->str_pool[k]); 
24677     mp_print(mp, " in font ");
24678     mp_print(mp, mp->font_name[f]); mp_print_char(mp, '!'); 
24679     mp_end_diagnostic(mp, false);
24680   }
24681 }
24682
24683 @ The whole purpose of saving the height, width, and depth information is to be
24684 able to find the bounding box of an item of text in an edge structure.  The
24685 |set_text_box| procedure takes a text node and adds this information.
24686
24687 @<Declare text measuring subroutines@>=
24688 void mp_set_text_box (MP mp,pointer p) {
24689   font_number f; /* |font_n(p)| */
24690   ASCII_code bc,ec; /* range of valid characters for font |f| */
24691   pool_pointer k,kk; /* current character and character to stop at */
24692   four_quarters cc; /* the |char_info| for the current character */
24693   scaled h,d; /* dimensions of the current character */
24694   width_val(p)=0;
24695   height_val(p)=-el_gordo;
24696   depth_val(p)=-el_gordo;
24697   f=font_n(p);
24698   bc=mp->font_bc[f];
24699   ec=mp->font_ec[f];
24700   kk=str_stop(text_p(p));
24701   k=mp->str_start[text_p(p)];
24702   while ( k<kk ) {
24703     @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>;
24704   }
24705   @<Set the height and depth to zero if the bounding box is empty@>;
24706 }
24707
24708 @ @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>=
24709
24710   if ( (mp->str_pool[k]<bc)||(mp->str_pool[k]>ec) ) {
24711     mp_lost_warning(mp, f,k);
24712   } else { 
24713     cc=char_info(f)(mp->str_pool[k]);
24714     if ( ! ichar_exists(cc) ) {
24715       mp_lost_warning(mp, f,k);
24716     } else { 
24717       width_val(p)=width_val(p)+char_width(f)(cc);
24718       h=char_height(f)(cc);
24719       d=char_depth(f)(cc);
24720       if ( h>height_val(p) ) height_val(p)=h;
24721       if ( d>depth_val(p) ) depth_val(p)=d;
24722     }
24723   }
24724   incr(k);
24725 }
24726
24727 @ Let's hope modern compilers do comparisons correctly when the difference would
24728 overflow.
24729
24730 @<Set the height and depth to zero if the bounding box is empty@>=
24731 if ( height_val(p)<-depth_val(p) ) { 
24732   height_val(p)=0;
24733   depth_val(p)=0;
24734 }
24735
24736 @ The new primitives fontmapfile and fontmapline.
24737
24738 @<Declare action procedures for use by |do_statement|@>=
24739 void mp_do_mapfile (MP mp) ;
24740 void mp_do_mapline (MP mp) ;
24741
24742 @ @c void mp_do_mapfile (MP mp) { 
24743   mp_get_x_next(mp); mp_scan_expression(mp);
24744   if ( mp->cur_type!=mp_string_type ) {
24745     @<Complain about improper map operation@>;
24746   } else {
24747     mp_map_file(mp,mp->cur_exp);
24748   }
24749 }
24750 void mp_do_mapline (MP mp) { 
24751   mp_get_x_next(mp); mp_scan_expression(mp);
24752   if ( mp->cur_type!=mp_string_type ) {
24753      @<Complain about improper map operation@>;
24754   } else { 
24755      mp_map_line(mp,mp->cur_exp);
24756   }
24757 }
24758
24759 @ @<Complain about improper map operation@>=
24760
24761   exp_err("Unsuitable expression");
24762   help1("Only known strings can be map files or map lines.");
24763   mp_put_get_error(mp);
24764 }
24765
24766 @ To print |scaled| value to PDF output we need some subroutines to ensure
24767 accurary.
24768
24769 @d max_integer   0x7FFFFFFF /* $2^{31}-1$ */
24770
24771 @<Glob...@>=
24772 scaled one_bp; /* scaled value corresponds to 1bp */
24773 scaled one_hundred_bp; /* scaled value corresponds to 100bp */
24774 scaled one_hundred_inch; /* scaled value corresponds to 100in */
24775 integer ten_pow[10]; /* $10^0..10^9$ */
24776 integer scaled_out; /* amount of |scaled| that was taken out in |divide_scaled| */
24777
24778 @ @<Set init...@>=
24779 mp->one_bp = 65782; /* 65781.76 */
24780 mp->one_hundred_bp = 6578176;
24781 mp->one_hundred_inch = 473628672;
24782 mp->ten_pow[0] = 1;
24783 for (i = 1;i<= 9; i++ ) {
24784   mp->ten_pow[i] = 10*mp->ten_pow[i - 1];
24785 }
24786
24787 @ The following function divides |s| by |m|. |dd| is number of decimal digits.
24788
24789 @c scaled mp_divide_scaled (MP mp,scaled s, scaled m, integer  dd) {
24790   scaled q,r;
24791   integer sign,i;
24792   sign = 1;
24793   if ( s < 0 ) { sign = -sign; s = -s; }
24794   if ( m < 0 ) { sign = -sign; m = -m; }
24795   if ( m == 0 )
24796     mp_confusion(mp, "arithmetic: divided by zero");
24797   else if ( m >= (max_integer / 10) )
24798     mp_confusion(mp, "arithmetic: number too big");
24799   q = s / m;
24800   r = s % m;
24801   for (i = 1;i<=dd;i++) {
24802     q = 10*q + (10*r) / m;
24803     r = (10*r) % m;
24804   }
24805   if ( 2*r >= m ) { incr(q); r = r - m; }
24806   mp->scaled_out = sign*(s - (r / mp->ten_pow[dd]));
24807   return (sign*q);
24808 }
24809
24810 @* \[44] Shipping pictures out.
24811 The |ship_out| procedure, to be described below, is given a pointer to
24812 an edge structure. Its mission is to output a file containing the \ps\
24813 description of an edge structure.
24814
24815 @ Each time an edge structure is shipped out we write a new \ps\ output
24816 file named according to the current \&{charcode}.
24817 @:char_code_}{\&{charcode} primitive@>
24818
24819 This is the only backend function that remains in the main |mpost.w| file. 
24820 There are just too many variable accesses needed for status reporting 
24821 etcetera to make it worthwile to move the code to |psout.w|.
24822
24823 @<Internal library declarations@>=
24824 void mp_open_output_file (MP mp) ;
24825
24826 @ @c void mp_open_output_file (MP mp) {
24827   integer c; /* \&{charcode} rounded to the nearest integer */
24828   int old_setting; /* previous |selector| setting */
24829   pool_pointer i; /*  indexes into |filename_template|  */
24830   integer cc; /* a temporary integer for template building  */
24831   integer f,g=0; /* field widths */
24832   if ( mp->job_name==NULL ) mp_open_log_file(mp);
24833   c=mp_round_unscaled(mp, mp->internal[mp_char_code]);
24834   if ( mp->filename_template==0 ) {
24835     char *s; /* a file extension derived from |c| */
24836     if ( c<0 ) 
24837       s=xstrdup(".ps");
24838     else 
24839       @<Use |c| to compute the file extension |s|@>;
24840     mp_pack_job_name(mp, s);
24841     xfree(s);
24842     while ( ! mp_a_open_out(mp, (void *)&mp->ps_file, mp_filetype_postscript) )
24843       mp_prompt_file_name(mp, "file name for output",s);
24844   } else { /* initializations */
24845     str_number s, n; /* a file extension derived from |c| */
24846     old_setting=mp->selector; 
24847     mp->selector=new_string;
24848     f = 0;
24849     i = mp->str_start[mp->filename_template];
24850     n = rts(""); /* initialize */
24851     while ( i<str_stop(mp->filename_template) ) {
24852        if ( mp->str_pool[i]=='%' ) {
24853       CONTINUE:
24854         incr(i);
24855         if ( i<str_stop(mp->filename_template) ) {
24856           if ( mp->str_pool[i]=='j' ) {
24857             mp_print(mp, mp->job_name);
24858           } else if ( mp->str_pool[i]=='d' ) {
24859              cc= mp_round_unscaled(mp, mp->internal[mp_day]);
24860              print_with_leading_zeroes(cc);
24861           } else if ( mp->str_pool[i]=='m' ) {
24862              cc= mp_round_unscaled(mp, mp->internal[mp_month]);
24863              print_with_leading_zeroes(cc);
24864           } else if ( mp->str_pool[i]=='y' ) {
24865              cc= mp_round_unscaled(mp, mp->internal[mp_year]);
24866              print_with_leading_zeroes(cc);
24867           } else if ( mp->str_pool[i]=='H' ) {
24868              cc= mp_round_unscaled(mp, mp->internal[mp_time]) / 60;
24869              print_with_leading_zeroes(cc);
24870           }  else if ( mp->str_pool[i]=='M' ) {
24871              cc= mp_round_unscaled(mp, mp->internal[mp_time]) % 60;
24872              print_with_leading_zeroes(cc);
24873           } else if ( mp->str_pool[i]=='c' ) {
24874             if ( c<0 ) mp_print(mp, "ps");
24875             else print_with_leading_zeroes(c);
24876           } else if ( (mp->str_pool[i]>='0') && 
24877                       (mp->str_pool[i]<='9') ) {
24878             if ( (f<10)  )
24879               f = (f*10) + mp->str_pool[i]-'0';
24880             goto CONTINUE;
24881           } else {
24882             mp_print_str(mp, mp->str_pool[i]);
24883           }
24884         }
24885       } else {
24886         if ( mp->str_pool[i]=='.' )
24887           if (length(n)==0)
24888             n = mp_make_string(mp);
24889         mp_print_str(mp, mp->str_pool[i]);
24890       };
24891       incr(i);
24892     };
24893     s = mp_make_string(mp);
24894     mp->selector= old_setting;
24895     if (length(n)==0) {
24896        n=s;
24897        s=rts("");
24898     };
24899     mp_pack_file_name(mp, str(n),"",str(s));
24900     while ( ! mp_a_open_out(mp, (void *)&mp->ps_file, mp_filetype_postscript) )
24901       mp_prompt_file_name(mp, "file name for output",str(s));
24902     delete_str_ref(n);
24903     delete_str_ref(s);
24904   }
24905   @<Store the true output file name if appropriate@>;
24906   @<Begin the progress report for the output of picture~|c|@>;
24907 }
24908
24909 @ The file extension created here could be up to five characters long in
24910 extreme cases so it may have to be shortened on some systems.
24911 @^system dependencies@>
24912
24913 @<Use |c| to compute the file extension |s|@>=
24914
24915   s = xmalloc(7,1);
24916   snprintf(s,7,".%i",(int)c);
24917 }
24918
24919 @ The user won't want to see all the output file names so we only save the
24920 first and last ones and a count of how many there were.  For this purpose
24921 files are ordered primarily by \&{charcode} and secondarily by order of
24922 creation.
24923 @:char_code_}{\&{charcode} primitive@>
24924
24925 @<Store the true output file name if appropriate@>=
24926 if ((c<mp->first_output_code)&&(mp->first_output_code>=0)) {
24927   mp->first_output_code=c;
24928   xfree(mp->first_file_name);
24929   mp->first_file_name=xstrdup(mp->name_of_file);
24930 }
24931 if ( c>=mp->last_output_code ) {
24932   mp->last_output_code=c;
24933   xfree(mp->last_file_name);
24934   mp->last_file_name=xstrdup(mp->name_of_file);
24935 }
24936
24937 @ @<Glob...@>=
24938 char * first_file_name;
24939 char * last_file_name; /* full file names */
24940 integer first_output_code;integer last_output_code; /* rounded \&{charcode} values */
24941 @:char_code_}{\&{charcode} primitive@>
24942 integer total_shipped; /* total number of |ship_out| operations completed */
24943
24944 @ @<Set init...@>=
24945 mp->first_file_name=xstrdup("");
24946 mp->last_file_name=xstrdup("");
24947 mp->first_output_code=32768;
24948 mp->last_output_code=-32768;
24949 mp->total_shipped=0;
24950
24951 @ @<Dealloc variables@>=
24952 xfree(mp->first_file_name);
24953 xfree(mp->last_file_name);
24954
24955 @ @<Begin the progress report for the output of picture~|c|@>=
24956 if ( (int)mp->term_offset>mp->max_print_line-6 ) mp_print_ln(mp);
24957 else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
24958 mp_print_char(mp, '[');
24959 if ( c>=0 ) mp_print_int(mp, c)
24960
24961 @ @<End progress report@>=
24962 mp_print_char(mp, ']');
24963 update_terminal;
24964 incr(mp->total_shipped)
24965
24966 @ @<Explain what output files were written@>=
24967 if ( mp->total_shipped>0 ) { 
24968   mp_print_nl(mp, "");
24969   mp_print_int(mp, mp->total_shipped);
24970   mp_print(mp, " output file");
24971   if ( mp->total_shipped>1 ) mp_print_char(mp, 's');
24972   mp_print(mp, " written: ");
24973   mp_print(mp, mp->first_file_name);
24974   if ( mp->total_shipped>1 ) {
24975     if ( 31+strlen(mp->first_file_name)+
24976          strlen(mp->last_file_name)> (unsigned)mp->max_print_line) 
24977       mp_print_ln(mp);
24978     mp_print(mp, " .. ");
24979     mp_print(mp, mp->last_file_name);
24980   }
24981 }
24982
24983 @ @<Internal library declarations@>=
24984 boolean mp_has_font_size(MP mp, font_number f );
24985
24986 @ @c 
24987 boolean mp_has_font_size(MP mp, font_number f ) {
24988   return (mp->font_sizes[f]!=null);
24989 }
24990
24991 @ The \&{special} command saves up lines of text to be printed during the next
24992 |ship_out| operation.  The saved items are stored as a list of capsule tokens.
24993
24994 @<Glob...@>=
24995 pointer last_pending; /* the last token in a list of pending specials */
24996
24997 @ @<Set init...@>=
24998 mp->last_pending=spec_head;
24999
25000 @ @<Cases of |do_statement|...@>=
25001 case special_command: 
25002   if ( mp->cur_mod==0 ) mp_do_special(mp); else 
25003   if ( mp->cur_mod==1 ) mp_do_mapfile(mp); else 
25004   mp_do_mapline(mp);
25005   break;
25006
25007 @ @<Declare action procedures for use by |do_statement|@>=
25008 void mp_do_special (MP mp) ;
25009
25010 @ @c void mp_do_special (MP mp) { 
25011   mp_get_x_next(mp); mp_scan_expression(mp);
25012   if ( mp->cur_type!=mp_string_type ) {
25013     @<Complain about improper special operation@>;
25014   } else { 
25015     link(mp->last_pending)=mp_stash_cur_exp(mp);
25016     mp->last_pending=link(mp->last_pending);
25017     link(mp->last_pending)=null;
25018   }
25019 }
25020
25021 @ @<Complain about improper special operation@>=
25022
25023   exp_err("Unsuitable expression");
25024   help1("Only known strings are allowed for output as specials.");
25025   mp_put_get_error(mp);
25026 }
25027
25028 @ On the export side, we need an extra object type for special strings.
25029
25030 @<Graphical object codes@>=
25031 mp_special_code=8, 
25032
25033 @ @<Export pending specials@>=
25034 p=link(spec_head);
25035 while ( p!=null ) {
25036   hq = mp_new_graphic_object(mp,mp_special_code);
25037   gr_pre_script(hq)  = str(value(p));
25038   if (hh->body==NULL) hh->body=hq; else gr_link(hp) = hq;
25039   hp = hq;
25040   p=link(p);
25041 }
25042 mp_flush_token_list(mp, link(spec_head));
25043 link(spec_head)=null;
25044 mp->last_pending=spec_head
25045
25046 @ We are now ready for the main output procedure.  Note that the |selector|
25047 setting is saved in a global variable so that |begin_diagnostic| can access it.
25048
25049 @<Declare the \ps\ output procedures@>=
25050 void mp_ship_out (MP mp, pointer h) ;
25051
25052 @ Once again, the |gr_XXXX| macros are defined in |mppsout.h|
25053
25054 @c
25055 struct mp_edge_object *mp_gr_export(MP mp, pointer h) {
25056   pointer p; /* the current graphical object */
25057   integer t; /* a temporary value */
25058   struct mp_edge_object *hh; /* the first graphical object */
25059   struct mp_graphic_object *hp; /* the current graphical object */
25060   struct mp_graphic_object *hq; /* something |hp| points to  */
25061   mp_set_bbox(mp, h, true);
25062   hh = mp_xmalloc(mp,1,sizeof(struct mp_edge_object));
25063   hh->body = NULL;
25064   hh->_minx = minx_val(h);
25065   hh->_miny = miny_val(h);
25066   hh->_maxx = maxx_val(h);
25067   hh->_maxy = maxy_val(h);
25068   @<Export pending specials@>;
25069   p=link(dummy_loc(h));
25070   while ( p!=null ) { 
25071     hq = mp_new_graphic_object(mp,type(p));
25072     switch (type(p)) {
25073     case mp_fill_code:
25074       gr_pen_p(hq)        = mp_export_knot_list(mp,pen_p(p));
25075       if ((pen_p(p)==null) || pen_is_elliptical(pen_p(p)))  {
25076           gr_path_p(hq)       = mp_export_knot_list(mp,path_p(p));
25077       } else {
25078         pointer pc, pp;
25079         pc = mp_copy_path(mp, path_p(p));
25080         pp = mp_make_envelope(mp, pc, pen_p(p),ljoin_val(p),0,miterlim_val(p));
25081         gr_path_p(hq)       = mp_export_knot_list(mp,pp);
25082         mp_toss_knot_list(mp, pp);
25083         pc = mp_htap_ypoc(mp, path_p(p));
25084         pp = mp_make_envelope(mp, pc, pen_p(p),ljoin_val(p),0,miterlim_val(p));
25085         gr_htap_p(hq)       = mp_export_knot_list(mp,pp);
25086         mp_toss_knot_list(mp, pp);
25087       }
25088       @<Export object color@>;
25089       @<Export object scripts@>;
25090       gr_ljoin_val(hq)    = ljoin_val(p);
25091       gr_miterlim_val(hq) = miterlim_val(p);
25092       break;
25093     case mp_stroked_code:
25094       gr_pen_p(hq)        = mp_export_knot_list(mp,pen_p(p));
25095       if (pen_is_elliptical(pen_p(p)))  {
25096               gr_path_p(hq)       = mp_export_knot_list(mp,path_p(p));
25097       } else {
25098         pointer pc;
25099         pc=mp_copy_path(mp, path_p(p));
25100         t=lcap_val(p);
25101         if ( left_type(pc)!=mp_endpoint ) { 
25102           left_type(mp_insert_knot(mp, pc,x_coord(pc),y_coord(pc)))=mp_endpoint;
25103           right_type(pc)=mp_endpoint;
25104           pc=link(pc);
25105           t=1;
25106         }
25107         pc=mp_make_envelope(mp,pc,pen_p(p),ljoin_val(p),t,miterlim_val(p));
25108         gr_path_p(hq)       = mp_export_knot_list(mp,pc);
25109         mp_toss_knot_list(mp, pc);
25110       }
25111       @<Export object color@>;
25112       @<Export object scripts@>;
25113       gr_ljoin_val(hq)    = ljoin_val(p);
25114       gr_miterlim_val(hq) = miterlim_val(p);
25115       gr_lcap_val(hq)     = lcap_val(p);
25116       gr_dash_scale(hq)   = dash_scale(p);
25117       gr_dash_p(hq)       = mp_export_dashes(mp,dash_p(p));
25118       break;
25119     case mp_text_code:
25120       gr_text_p(hq)       = str(text_p(p));
25121       gr_font_n(hq)       = font_n(p);
25122       @<Export object color@>;
25123       @<Export object scripts@>;
25124       gr_width_val(hq)    = width_val(p);
25125       gr_height_val(hq)   = height_val(p);
25126       gr_depth_val(hq)    = depth_val(p);
25127       gr_tx_val(hq)       = tx_val(p);
25128       gr_ty_val(hq)       = ty_val(p);
25129       gr_txx_val(hq)      = txx_val(p);
25130       gr_txy_val(hq)      = txy_val(p);
25131       gr_tyx_val(hq)      = tyx_val(p);
25132       gr_tyy_val(hq)      = tyy_val(p);
25133       break;
25134     case mp_start_clip_code: 
25135     case mp_start_bounds_code:
25136       gr_path_p(hq) = mp_export_knot_list(mp,path_p(p));
25137       break;
25138     case mp_stop_clip_code: 
25139     case mp_stop_bounds_code:
25140       /* nothing to do here */
25141       break;
25142     } 
25143     if (hh->body==NULL) hh->body=hq; else  gr_link(hp) = hq;
25144     hp = hq;
25145     p=link(p);
25146   }
25147   return hh;
25148 }
25149
25150 @ @<Exported function ...@>=
25151 struct mp_edge_object *mp_gr_export(MP mp, int h);
25152 extern void mp_gr_ship_out (MP mp, struct mp_edge_object *hh) ;
25153
25154 @ This function is now nearly trivial.
25155
25156 @c
25157 void mp_ship_out (MP mp, pointer h) { /* output edge structure |h| */
25158   (mp->shipout_backend) (mp, h);
25159   @<End progress report@>;
25160   if ( mp->internal[mp_tracing_output]>0 ) 
25161    mp_print_edges(mp, h," (just shipped out)",true);
25162 }
25163
25164 @ @<Declarations@>=
25165 void mp_shipout_backend (MP mp, pointer h);
25166
25167 @ @c
25168 void mp_shipout_backend (MP mp, pointer h) {
25169   struct mp_edge_object *hh; /* the first graphical object */
25170   hh = mp_gr_export(mp,h);
25171   mp_gr_ship_out (mp, hh);
25172   mp_xfree(hh);
25173 }
25174
25175 @ @<Exported types@>=
25176 typedef void (*mp_backend_writer)(MP, int);
25177
25178 @ @<Option variables@>=
25179 mp_backend_writer shipout_backend;
25180
25181 @ @<Allocate or initialize ...@>=
25182 set_callback_option(shipout_backend);
25183
25184
25185
25186 @ Once again, the |gr_XXXX| macros are defined in |mppsout.h|
25187
25188 @<Export object color@>=
25189 gr_color_model(hq)  = color_model(p);
25190 gr_cyan_val(hq)     = cyan_val(p);
25191 gr_magenta_val(hq)  = magenta_val(p);
25192 gr_yellow_val(hq)   = yellow_val(p);
25193 gr_black_val(hq)    = black_val(p);
25194 gr_red_val(hq)      = red_val(p);
25195 gr_green_val(hq)    = green_val(p);
25196 gr_blue_val(hq)     = blue_val(p);
25197 gr_grey_val(hq)     = grey_val(p)
25198
25199
25200 @ @<Export object scripts@>=
25201 if (pre_script(p)!=null)
25202   gr_pre_script(hq)   = str(pre_script(p));
25203 if (post_script(p)!=null)
25204   gr_post_script(hq)  = str(post_script(p));
25205
25206 @ Now that we've finished |ship_out|, let's look at the other commands
25207 by which a user can send things to the \.{GF} file.
25208
25209 @ @<Determine if a character has been shipped out@>=
25210
25211   mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256;
25212   if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
25213   boolean_reset(mp->char_exists[mp->cur_exp]);
25214   mp->cur_type=mp_boolean_type;
25215 }
25216
25217 @ @<Glob...@>=
25218 psout_data ps;
25219
25220 @ @<Allocate or initialize ...@>=
25221 mp_backend_initialize(mp);
25222
25223 @ @<Dealloc...@>=
25224 mp_backend_free(mp);
25225
25226
25227 @* \[45] Dumping and undumping the tables.
25228 After \.{INIMP} has seen a collection of macros, it
25229 can write all the necessary information on an auxiliary file so
25230 that production versions of \MP\ are able to initialize their
25231 memory at high speed. The present section of the program takes
25232 care of such output and input. We shall consider simultaneously
25233 the processes of storing and restoring,
25234 so that the inverse relation between them is clear.
25235 @.INIMP@>
25236
25237 The global variable |mem_ident| is a string that is printed right
25238 after the |banner| line when \MP\ is ready to start. For \.{INIMP} this
25239 string says simply `\.{(INIMP)}'; for other versions of \MP\ it says,
25240 for example, `\.{(mem=plain 90.4.14)}', showing the year,
25241 month, and day that the mem file was created. We have |mem_ident=0|
25242 before \MP's tables are loaded.
25243
25244 @<Glob...@>=
25245 char * mem_ident;
25246
25247 @ @<Set init...@>=
25248 mp->mem_ident=NULL;
25249
25250 @ @<Initialize table entries...@>=
25251 mp->mem_ident=xstrdup(" (INIMP)");
25252
25253 @ @<Declare act...@>=
25254 void mp_store_mem_file (MP mp) ;
25255
25256 @ @c void mp_store_mem_file (MP mp) {
25257   integer k;  /* all-purpose index */
25258   pointer p,q; /* all-purpose pointers */
25259   integer x; /* something to dump */
25260   four_quarters w; /* four ASCII codes */
25261   memory_word WW;
25262   @<Create the |mem_ident|, open the mem file,
25263     and inform the user that dumping has begun@>;
25264   @<Dump constants for consistency check@>;
25265   @<Dump the string pool@>;
25266   @<Dump the dynamic memory@>;
25267   @<Dump the table of equivalents and the hash table@>;
25268   @<Dump a few more things and the closing check word@>;
25269   @<Close the mem file@>;
25270 }
25271
25272 @ Corresponding to the procedure that dumps a mem file, we also have a function
25273 that reads~one~in. The function returns |false| if the dumped mem is
25274 incompatible with the present \MP\ table sizes, etc.
25275
25276 @d off_base 6666 /* go here if the mem file is unacceptable */
25277 @d too_small(A) { wake_up_terminal;
25278   wterm_ln("---! Must increase the "); wterm((A));
25279 @.Must increase the x@>
25280   goto OFF_BASE;
25281   }
25282
25283 @c 
25284 boolean mp_load_mem_file (MP mp) {
25285   integer k; /* all-purpose index */
25286   pointer p,q; /* all-purpose pointers */
25287   integer x; /* something undumped */
25288   str_number s; /* some temporary string */
25289   four_quarters w; /* four ASCII codes */
25290   memory_word WW;
25291   @<Undump constants for consistency check@>;
25292   @<Undump the string pool@>;
25293   @<Undump the dynamic memory@>;
25294   @<Undump the table of equivalents and the hash table@>;
25295   @<Undump a few more things and the closing check word@>;
25296   return true; /* it worked! */
25297 OFF_BASE: 
25298   wake_up_terminal;
25299   wterm_ln("(Fatal mem file error; I'm stymied)\n");
25300 @.Fatal mem file error@>
25301    return false;
25302 }
25303
25304 @ @<Declarations@>=
25305 boolean mp_load_mem_file (MP mp) ;
25306
25307 @ Mem files consist of |memory_word| items, and we use the following
25308 macros to dump words of different types:
25309
25310 @d dump_wd(A)   { WW=(A);       (mp->write_binary_file)(mp->mem_file,&WW,sizeof(WW)); }
25311 @d dump_int(A)  { int cint=(A); (mp->write_binary_file)(mp->mem_file,&cint,sizeof(cint)); }
25312 @d dump_hh(A)   { WW.hh=(A);    (mp->write_binary_file)(mp->mem_file,&WW,sizeof(WW)); }
25313 @d dump_qqqq(A) { WW.qqqq=(A);  (mp->write_binary_file)(mp->mem_file,&WW,sizeof(WW)); }
25314 @d dump_string(A) { dump_int(strlen(A)+1);
25315                     (mp->write_binary_file)(mp->mem_file,A,strlen(A)+1); }
25316
25317 @<Glob...@>=
25318 void * mem_file; /* for input or output of mem information */
25319
25320 @ The inverse macros are slightly more complicated, since we need to check
25321 the range of the values we are reading in. We say `|undump(a)(b)(x)|' to
25322 read an integer value |x| that is supposed to be in the range |a<=x<=b|.
25323
25324 @d mgeti(A) do {
25325   size_t wanted = sizeof(A);
25326   void *A_ptr = &A;
25327   (mp->read_binary_file)(mp->mem_file,&A_ptr,&wanted);
25328   if (wanted!=sizeof(A)) goto OFF_BASE;
25329 } while (0)
25330
25331 @d mgetw(A) do {
25332   size_t wanted = sizeof(A);
25333   void *A_ptr = &A;
25334   (mp->read_binary_file)(mp->mem_file,&A_ptr,&wanted);
25335   if (wanted!=sizeof(A)) goto OFF_BASE;
25336 } while (0)
25337
25338 @d undump_wd(A)   { mgetw(WW); A=WW; }
25339 @d undump_int(A)  { int cint; mgeti(cint); A=cint; }
25340 @d undump_hh(A)   { mgetw(WW); A=WW.hh; }
25341 @d undump_qqqq(A) { mgetw(WW); A=WW.qqqq; }
25342 @d undump_strings(A,B,C) { 
25343    undump_int(x); if ( (x<(A)) || (x>(B)) ) goto OFF_BASE; else C=str(x); }
25344 @d undump(A,B,C) { undump_int(x); if ( (x<(A)) || (x>(int)(B)) ) goto OFF_BASE; else C=x; }
25345 @d undump_size(A,B,C,D) { undump_int(x);
25346                           if (x<(A)) goto OFF_BASE; 
25347                           if (x>(B)) { too_small((C)); } else { D=x;} }
25348 @d undump_string(A) do { 
25349   size_t wanted; 
25350   integer XX=0; 
25351   undump_int(XX);
25352   wanted = XX;
25353   A = xmalloc(XX,sizeof(char));
25354   (mp->read_binary_file)(mp->mem_file,(void **)&A,&wanted);
25355   if (wanted!=(size_t)XX) goto OFF_BASE;
25356 } while (0)
25357
25358 @ The next few sections of the program should make it clear how we use the
25359 dump/undump macros.
25360
25361 @<Dump constants for consistency check@>=
25362 dump_int(mp->mem_top);
25363 dump_int(mp->hash_size);
25364 dump_int(mp->hash_prime)
25365 dump_int(mp->param_size);
25366 dump_int(mp->max_in_open);
25367
25368 @ Sections of a \.{WEB} program that are ``commented out'' still contribute
25369 strings to the string pool; therefore \.{INIMP} and \MP\ will have
25370 the same strings. (And it is, of course, a good thing that they do.)
25371 @.WEB@>
25372 @^string pool@>
25373
25374 @<Undump constants for consistency check@>=
25375 undump_int(x); mp->mem_top = x;
25376 undump_int(x); if (mp->hash_size != x) goto OFF_BASE;
25377 undump_int(x); if (mp->hash_prime != x) goto OFF_BASE;
25378 undump_int(x); if (mp->param_size != x) goto OFF_BASE;
25379 undump_int(x); if (mp->max_in_open != x) goto OFF_BASE
25380
25381 @ We do string pool compaction to avoid dumping unused strings.
25382
25383 @d dump_four_ASCII 
25384   w.b0=qi(mp->str_pool[k]); w.b1=qi(mp->str_pool[k+1]);
25385   w.b2=qi(mp->str_pool[k+2]); w.b3=qi(mp->str_pool[k+3]);
25386   dump_qqqq(w)
25387
25388 @<Dump the string pool@>=
25389 mp_do_compaction(mp, mp->pool_size);
25390 dump_int(mp->pool_ptr);
25391 dump_int(mp->max_str_ptr);
25392 dump_int(mp->str_ptr);
25393 k=0;
25394 while ( (mp->next_str[k]==k+1) && (k<=mp->max_str_ptr) ) 
25395   incr(k);
25396 dump_int(k);
25397 while ( k<=mp->max_str_ptr ) { 
25398   dump_int(mp->next_str[k]); incr(k);
25399 }
25400 k=0;
25401 while (1)  { 
25402   dump_int(mp->str_start[k]); /* TODO: valgrind warning here */
25403   if ( k==mp->str_ptr ) {
25404     break;
25405   } else { 
25406     k=mp->next_str[k]; 
25407   }
25408 };
25409 k=0;
25410 while (k+4<mp->pool_ptr ) { 
25411   dump_four_ASCII; k=k+4; 
25412 }
25413 k=mp->pool_ptr-4; dump_four_ASCII;
25414 mp_print_ln(mp); mp_print(mp, "at most "); mp_print_int(mp, mp->max_str_ptr);
25415 mp_print(mp, " strings of total length ");
25416 mp_print_int(mp, mp->pool_ptr)
25417
25418 @ @d undump_four_ASCII 
25419   undump_qqqq(w);
25420   mp->str_pool[k]=qo(w.b0); mp->str_pool[k+1]=qo(w.b1);
25421   mp->str_pool[k+2]=qo(w.b2); mp->str_pool[k+3]=qo(w.b3)
25422
25423 @<Undump the string pool@>=
25424 undump_int(mp->pool_ptr);
25425 mp_reallocate_pool(mp, mp->pool_ptr) ;
25426 undump_int(mp->max_str_ptr);
25427 mp_reallocate_strings (mp,mp->max_str_ptr) ;
25428 undump(0,mp->max_str_ptr,mp->str_ptr);
25429 undump(0,mp->max_str_ptr+1,s);
25430 for (k=0;k<=s-1;k++) 
25431   mp->next_str[k]=k+1;
25432 for (k=s;k<=mp->max_str_ptr;k++) 
25433   undump(s+1,mp->max_str_ptr+1,mp->next_str[k]);
25434 mp->fixed_str_use=0;
25435 k=0;
25436 while (1) { 
25437   undump(0,mp->pool_ptr,mp->str_start[k]);
25438   if ( k==mp->str_ptr ) break;
25439   mp->str_ref[k]=max_str_ref;
25440   incr(mp->fixed_str_use);
25441   mp->last_fixed_str=k; k=mp->next_str[k];
25442 }
25443 k=0;
25444 while ( k+4<mp->pool_ptr ) { 
25445   undump_four_ASCII; k=k+4;
25446 }
25447 k=mp->pool_ptr-4; undump_four_ASCII;
25448 mp->init_str_use=mp->fixed_str_use; mp->init_pool_ptr=mp->pool_ptr;
25449 mp->max_pool_ptr=mp->pool_ptr;
25450 mp->strs_used_up=mp->fixed_str_use;
25451 mp->pool_in_use=mp->str_start[mp->str_ptr]; mp->strs_in_use=mp->fixed_str_use;
25452 mp->max_pl_used=mp->pool_in_use; mp->max_strs_used=mp->strs_in_use;
25453 mp->pact_count=0; mp->pact_chars=0; mp->pact_strs=0;
25454
25455 @ By sorting the list of available spaces in the variable-size portion of
25456 |mem|, we are usually able to get by without having to dump very much
25457 of the dynamic memory.
25458
25459 We recompute |var_used| and |dyn_used|, so that \.{INIMP} dumps valid
25460 information even when it has not been gathering statistics.
25461
25462 @<Dump the dynamic memory@>=
25463 mp_sort_avail(mp); mp->var_used=0;
25464 dump_int(mp->lo_mem_max); dump_int(mp->rover);
25465 p=0; q=mp->rover; x=0;
25466 do {  
25467   for (k=p;k<= q+1;k++) 
25468     dump_wd(mp->mem[k]);
25469   x=x+q+2-p; mp->var_used=mp->var_used+q-p;
25470   p=q+node_size(q); q=rlink(q);
25471 } while (q!=mp->rover);
25472 mp->var_used=mp->var_used+mp->lo_mem_max-p; 
25473 mp->dyn_used=mp->mem_end+1-mp->hi_mem_min;
25474 for (k=p;k<= mp->lo_mem_max;k++ ) 
25475   dump_wd(mp->mem[k]);
25476 x=x+mp->lo_mem_max+1-p;
25477 dump_int(mp->hi_mem_min); dump_int(mp->avail);
25478 for (k=mp->hi_mem_min;k<=mp->mem_end;k++ ) 
25479   dump_wd(mp->mem[k]);
25480 x=x+mp->mem_end+1-mp->hi_mem_min;
25481 p=mp->avail;
25482 while ( p!=null ) { 
25483   decr(mp->dyn_used); p=link(p);
25484 }
25485 dump_int(mp->var_used); dump_int(mp->dyn_used);
25486 mp_print_ln(mp); mp_print_int(mp, x);
25487 mp_print(mp, " memory locations dumped; current usage is ");
25488 mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used)
25489
25490 @ @<Undump the dynamic memory@>=
25491 undump(lo_mem_stat_max+1000,hi_mem_stat_min-1,mp->lo_mem_max);
25492 undump(lo_mem_stat_max+1,mp->lo_mem_max,mp->rover);
25493 p=0; q=mp->rover;
25494 do {  
25495   for (k=p;k<= q+1; k++) 
25496     undump_wd(mp->mem[k]);
25497   p=q+node_size(q);
25498   if ( (p>mp->lo_mem_max)||((q>=rlink(q))&&(rlink(q)!=mp->rover)) ) 
25499     goto OFF_BASE;
25500   q=rlink(q);
25501 } while (q!=mp->rover);
25502 for (k=p;k<=mp->lo_mem_max;k++ ) 
25503   undump_wd(mp->mem[k]);
25504 undump(mp->lo_mem_max+1,hi_mem_stat_min,mp->hi_mem_min);
25505 undump(null,mp->mem_top,mp->avail); mp->mem_end=mp->mem_top;
25506 for (k=mp->hi_mem_min;k<= mp->mem_end;k++) 
25507   undump_wd(mp->mem[k]);
25508 undump_int(mp->var_used); undump_int(mp->dyn_used)
25509
25510 @ A different scheme is used to compress the hash table, since its lower region
25511 is usually sparse. When |text(p)<>0| for |p<=hash_used|, we output three
25512 words: |p|, |hash[p]|, and |eqtb[p]|. The hash table is, of course, densely
25513 packed for |p>=hash_used|, so the remaining entries are output in~a~block.
25514
25515 @<Dump the table of equivalents and the hash table@>=
25516 dump_int(mp->hash_used); 
25517 mp->st_count=frozen_inaccessible-1-mp->hash_used;
25518 for (p=1;p<=mp->hash_used;p++) {
25519   if ( text(p)!=0 ) {
25520      dump_int(p); dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]); incr(mp->st_count);
25521   }
25522 }
25523 for (p=mp->hash_used+1;p<=(int)hash_end;p++) {
25524   dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]);
25525 }
25526 dump_int(mp->st_count);
25527 mp_print_ln(mp); mp_print_int(mp, mp->st_count); mp_print(mp, " symbolic tokens")
25528
25529 @ @<Undump the table of equivalents and the hash table@>=
25530 undump(1,frozen_inaccessible,mp->hash_used); 
25531 p=0;
25532 do {  
25533   undump(p+1,mp->hash_used,p); 
25534   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
25535 } while (p!=mp->hash_used);
25536 for (p=mp->hash_used+1;p<=(int)hash_end;p++ )  { 
25537   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
25538 }
25539 undump_int(mp->st_count)
25540
25541 @ We have already printed a lot of statistics, so we set |mp_tracing_stats:=0|
25542 to prevent them appearing again.
25543
25544 @<Dump a few more things and the closing check word@>=
25545 dump_int(mp->max_internal);
25546 dump_int(mp->int_ptr);
25547 for (k=1;k<= mp->int_ptr;k++ ) { 
25548   dump_int(mp->internal[k]); 
25549   dump_string(mp->int_name[k]);
25550 }
25551 dump_int(mp->start_sym); 
25552 dump_int(mp->interaction); 
25553 dump_string(mp->mem_ident);
25554 dump_int(mp->bg_loc); dump_int(mp->eg_loc); dump_int(mp->serial_no); dump_int(69073);
25555 mp->internal[mp_tracing_stats]=0
25556
25557 @ @<Undump a few more things and the closing check word@>=
25558 undump_int(x);
25559 if (x>mp->max_internal) mp_grow_internals(mp,x);
25560 undump_int(mp->int_ptr);
25561 for (k=1;k<= mp->int_ptr;k++) { 
25562   undump_int(mp->internal[k]);
25563   undump_string(mp->int_name[k]);
25564 }
25565 undump(0,frozen_inaccessible,mp->start_sym);
25566 if (mp->interaction==mp_unspecified_mode) {
25567   undump(mp_unspecified_mode,mp_error_stop_mode,mp->interaction);
25568 } else {
25569   undump(mp_unspecified_mode,mp_error_stop_mode,x);
25570 }
25571 undump_string(mp->mem_ident);
25572 undump(1,hash_end,mp->bg_loc);
25573 undump(1,hash_end,mp->eg_loc);
25574 undump_int(mp->serial_no);
25575 undump_int(x); 
25576 if (x!=69073) goto OFF_BASE
25577
25578 @ @<Create the |mem_ident|...@>=
25579
25580   xfree(mp->mem_ident);
25581   mp->mem_ident = xmalloc(256,1);
25582   snprintf(mp->mem_ident,256," (mem=%s %i.%i.%i)", 
25583            mp->job_name,
25584            (int)(mp_round_unscaled(mp, mp->internal[mp_year]) % 100),
25585            (int)mp_round_unscaled(mp, mp->internal[mp_month]),
25586            (int)mp_round_unscaled(mp, mp->internal[mp_day]));
25587   mp_pack_job_name(mp, mem_extension);
25588   while (! mp_w_open_out(mp, &mp->mem_file) )
25589     mp_prompt_file_name(mp, "mem file name", mem_extension);
25590   mp_print_nl(mp, "Beginning to dump on file ");
25591 @.Beginning to dump...@>
25592   mp_print(mp, mp->name_of_file); 
25593   mp_print_nl(mp, mp->mem_ident);
25594 }
25595
25596 @ @<Dealloc variables@>=
25597 xfree(mp->mem_ident);
25598
25599 @ @<Close the mem file@>=
25600 (mp->close_file)(mp->mem_file)
25601
25602 @* \[46] The main program.
25603 This is it: the part of \MP\ that executes all those procedures we have
25604 written.
25605
25606 Well---almost. We haven't put the parsing subroutines into the
25607 program yet; and we'd better leave space for a few more routines that may
25608 have been forgotten.
25609
25610 @c @<Declare the basic parsing subroutines@>;
25611 @<Declare miscellaneous procedures that were declared |forward|@>;
25612 @<Last-minute procedures@>
25613
25614 @ We've noted that there are two versions of \MP. One, called \.{INIMP},
25615 @.INIMP@>
25616 has to be run first; it initializes everything from scratch, without
25617 reading a mem file, and it has the capability of dumping a mem file.
25618 The other one is called `\.{VIRMP}'; it is a ``virgin'' program that needs
25619 @.VIRMP@>
25620 to input a mem file in order to get started. \.{VIRMP} typically has
25621 a bit more memory capacity than \.{INIMP}, because it does not need the
25622 space consumed by the dumping/undumping routines and the numerous calls on
25623 |primitive|, etc.
25624
25625 The \.{VIRMP} program cannot read a mem file instantaneously, of course;
25626 the best implementations therefore allow for production versions of \MP\ that
25627 not only avoid the loading routine for object code, they also have
25628 a mem file pre-loaded. 
25629
25630 @ @<Option variables@>=
25631 int ini_version; /* are we iniMP? */
25632
25633 @ @<Set |ini_version|@>=
25634 mp->ini_version = (opt->ini_version ? true : false);
25635
25636 @ Here we do whatever is needed to complete \MP's job gracefully on the
25637 local operating system. The code here might come into play after a fatal
25638 error; it must therefore consist entirely of ``safe'' operations that
25639 cannot produce error messages. For example, it would be a mistake to call
25640 |str_room| or |make_string| at this time, because a call on |overflow|
25641 might lead to an infinite loop.
25642 @^system dependencies@>
25643
25644 This program doesn't bother to close the input files that may still be open.
25645
25646 @<Last-minute...@>=
25647 void mp_close_files_and_terminate (MP mp) {
25648   integer k; /* all-purpose index */
25649   integer LH; /* the length of the \.{TFM} header, in words */
25650   int lk_offset; /* extra words inserted at beginning of |lig_kern| array */
25651   pointer p; /* runs through a list of \.{TFM} dimensions */
25652   @<Close all open files in the |rd_file| and |wr_file| arrays@>;
25653   if ( mp->internal[mp_tracing_stats]>0 )
25654     @<Output statistics about this job@>;
25655   wake_up_terminal; 
25656   @<Do all the finishing work on the \.{TFM} file@>;
25657   @<Explain what output files were written@>;
25658   if ( mp->log_opened ){ 
25659     wlog_cr;
25660     (mp->close_file)(mp->log_file); 
25661     mp->selector=mp->selector-2;
25662     if ( mp->selector==term_only ) {
25663       mp_print_nl(mp, "Transcript written on ");
25664 @.Transcript written...@>
25665       mp_print(mp, mp->log_name); mp_print_char(mp, '.');
25666     }
25667   }
25668   mp_print_ln(mp);
25669   t_close_out;
25670   t_close_in;
25671 }
25672
25673 @ @<Declarations@>=
25674 void mp_close_files_and_terminate (MP mp) ;
25675
25676 @ @<Close all open files in the |rd_file| and |wr_file| arrays@>=
25677 if (mp->rd_fname!=NULL) {
25678   for (k=0;k<=(int)mp->read_files-1;k++ ) {
25679     if ( mp->rd_fname[k]!=NULL ) {
25680       (mp->close_file)(mp->rd_file[k]);
25681    }
25682  }
25683 }
25684 if (mp->wr_fname!=NULL) {
25685   for (k=0;k<=(int)mp->write_files-1;k++) {
25686     if ( mp->wr_fname[k]!=NULL ) {
25687      (mp->close_file)(mp->wr_file[k]);
25688     }
25689   }
25690 }
25691
25692 @ @<Dealloc ...@>=
25693 for (k=0;k<(int)mp->max_read_files;k++ ) {
25694   if ( mp->rd_fname[k]!=NULL ) {
25695     (mp->close_file)(mp->rd_file[k]);
25696     mp_xfree(mp->rd_fname[k]); 
25697   }
25698 }
25699 mp_xfree(mp->rd_file);
25700 mp_xfree(mp->rd_fname);
25701 for (k=0;k<(int)mp->max_write_files;k++) {
25702   if ( mp->wr_fname[k]!=NULL ) {
25703     (mp->close_file)(mp->wr_file[k]);
25704     mp_xfree(mp->wr_fname[k]); 
25705   }
25706 }
25707 mp_xfree(mp->wr_file);
25708 mp_xfree(mp->wr_fname);
25709
25710
25711 @ We want to produce a \.{TFM} file if and only if |mp_fontmaking| is positive.
25712
25713 We reclaim all of the variable-size memory at this point, so that
25714 there is no chance of another memory overflow after the memory capacity
25715 has already been exceeded.
25716
25717 @<Do all the finishing work on the \.{TFM} file@>=
25718 if ( mp->internal[mp_fontmaking]>0 ) {
25719   @<Make the dynamic memory into one big available node@>;
25720   @<Massage the \.{TFM} widths@>;
25721   mp_fix_design_size(mp); mp_fix_check_sum(mp);
25722   @<Massage the \.{TFM} heights, depths, and italic corrections@>;
25723   mp->internal[mp_fontmaking]=0; /* avoid loop in case of fatal error */
25724   @<Finish the \.{TFM} file@>;
25725 }
25726
25727 @ @<Make the dynamic memory into one big available node@>=
25728 mp->rover=lo_mem_stat_max+1; link(mp->rover)=empty_flag; mp->lo_mem_max=mp->hi_mem_min-1;
25729 if ( mp->lo_mem_max-mp->rover>max_halfword ) mp->lo_mem_max=max_halfword+mp->rover;
25730 node_size(mp->rover)=mp->lo_mem_max-mp->rover; 
25731 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
25732 link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null
25733
25734 @ The present section goes directly to the log file instead of using
25735 |print| commands, because there's no need for these strings to take
25736 up |str_pool| memory when a non-{\bf stat} version of \MP\ is being used.
25737
25738 @<Output statistics...@>=
25739 if ( mp->log_opened ) { 
25740   char s[128];
25741   wlog_ln(" ");
25742   wlog_ln("Here is how much of MetaPost's memory you used:");
25743 @.Here is how much...@>
25744   snprintf(s,128," %i string%s out of %i",(int)mp->max_strs_used-mp->init_str_use,
25745           (mp->max_strs_used!=mp->init_str_use+1 ? "s" : ""),
25746           (int)(mp->max_strings-1-mp->init_str_use));
25747   wlog_ln(s);
25748   snprintf(s,128," %i string characters out of %i",
25749            (int)mp->max_pl_used-mp->init_pool_ptr,
25750            (int)mp->pool_size-mp->init_pool_ptr);
25751   wlog_ln(s);
25752   snprintf(s,128," %i words of memory out of %i",
25753            (int)mp->lo_mem_max+mp->mem_end-mp->hi_mem_min+2,
25754            (int)mp->mem_end+1);
25755   wlog_ln(s);
25756   snprintf(s,128," %i symbolic tokens out of %i", (int)mp->st_count, (int)mp->hash_size);
25757   wlog_ln(s);
25758   snprintf(s,128," %ii, %in, %ip, %ib stack positions out of %ii, %in, %ip, %ib",
25759            (int)mp->max_in_stack,(int)mp->int_ptr,
25760            (int)mp->max_param_stack,(int)mp->max_buf_stack+1,
25761            (int)mp->stack_size,(int)mp->max_internal,(int)mp->param_size,(int)mp->buf_size);
25762   wlog_ln(s);
25763   snprintf(s,128," %i string compactions (moved %i characters, %i strings)",
25764           (int)mp->pact_count,(int)mp->pact_chars,(int)mp->pact_strs);
25765   wlog_ln(s);
25766 }
25767
25768 @ We get to the |final_cleanup| routine when \&{end} or \&{dump} has
25769 been scanned.
25770
25771 @<Last-minute...@>=
25772 void mp_final_cleanup (MP mp) {
25773   small_number c; /* 0 for \&{end}, 1 for \&{dump} */
25774   c=mp->cur_mod;
25775   if ( mp->job_name==NULL ) mp_open_log_file(mp);
25776   while ( mp->input_ptr>0 ) {
25777     if ( token_state ) mp_end_token_list(mp);
25778     else  mp_end_file_reading(mp);
25779   }
25780   while ( mp->loop_ptr!=null ) mp_stop_iteration(mp);
25781   while ( mp->open_parens>0 ) { 
25782     mp_print(mp, " )"); decr(mp->open_parens);
25783   };
25784   while ( mp->cond_ptr!=null ) {
25785     mp_print_nl(mp, "(end occurred when ");
25786 @.end occurred...@>
25787     mp_print_cmd_mod(mp, fi_or_else,mp->cur_if);
25788     /* `\.{if}' or `\.{elseif}' or `\.{else}' */
25789     if ( mp->if_line!=0 ) {
25790       mp_print(mp, " on line "); mp_print_int(mp, mp->if_line);
25791     }
25792     mp_print(mp, " was incomplete)");
25793     mp->if_line=if_line_field(mp->cond_ptr);
25794     mp->cur_if=name_type(mp->cond_ptr); mp->cond_ptr=link(mp->cond_ptr);
25795   }
25796   if ( mp->history!=mp_spotless )
25797     if ( ((mp->history==mp_warning_issued)||(mp->interaction<mp_error_stop_mode)) )
25798       if ( mp->selector==term_and_log ) {
25799     mp->selector=term_only;
25800     mp_print_nl(mp, "(see the transcript file for additional information)");
25801 @.see the transcript file...@>
25802     mp->selector=term_and_log;
25803   }
25804   if ( c==1 ) {
25805     if (mp->ini_version) {
25806       mp_store_mem_file(mp); return;
25807     }
25808     mp_print_nl(mp, "(dump is performed only by INIMP)"); return;
25809 @.dump...only by INIMP@>
25810   }
25811 }
25812
25813 @ @<Declarations@>=
25814 void mp_final_cleanup (MP mp) ;
25815 void mp_init_prim (MP mp) ;
25816 void mp_init_tab (MP mp) ;
25817
25818 @ @<Last-minute...@>=
25819 void mp_init_prim (MP mp) { /* initialize all the primitives */
25820   @<Put each...@>;
25821 }
25822 @#
25823 void mp_init_tab (MP mp) { /* initialize other tables */
25824   integer k; /* all-purpose index */
25825   @<Initialize table entries (done by \.{INIMP} only)@>;
25826 }
25827
25828
25829 @ When we begin the following code, \MP's tables may still contain garbage;
25830 the strings might not even be present. Thus we must proceed cautiously to get
25831 bootstrapped in.
25832
25833 But when we finish this part of the program, \MP\ is ready to call on the
25834 |main_control| routine to do its work.
25835
25836 @<Get the first line...@>=
25837
25838   @<Initialize the input routines@>;
25839   if ( (mp->mem_ident==NULL)||(mp->buffer[loc]=='&') ) {
25840     if ( mp->mem_ident!=NULL ) {
25841       mp_do_initialize(mp); /* erase preloaded mem */
25842     }
25843     if ( ! mp_open_mem_file(mp) ) return mp_fatal_error_stop;
25844     if ( ! mp_load_mem_file(mp) ) {
25845       (mp->close_file)(mp->mem_file); 
25846       return mp_fatal_error_stop;
25847     }
25848     (mp->close_file)( mp->mem_file);
25849     while ( (loc<limit)&&(mp->buffer[loc]==' ') ) incr(loc);
25850   }
25851   mp->buffer[limit]='%';
25852   mp_fix_date_and_time(mp);
25853   if (mp->random_seed==0)
25854     mp->random_seed = (mp->internal[mp_time] / unity)+mp->internal[mp_day];
25855   mp_init_randoms(mp, mp->random_seed);
25856   @<Initialize the print |selector|...@>;
25857   if ( loc<limit ) if ( mp->buffer[loc]!='\\' ) 
25858     mp_start_input(mp); /* \&{input} assumed */
25859 }
25860
25861 @ @<Run inimpost commands@>=
25862 {
25863   mp_get_strings_started(mp);
25864   mp_init_tab(mp); /* initialize the tables */
25865   mp_init_prim(mp); /* call |primitive| for each primitive */
25866   mp->init_str_use=mp->str_ptr; mp->init_pool_ptr=mp->pool_ptr;
25867   mp->max_str_ptr=mp->str_ptr; mp->max_pool_ptr=mp->pool_ptr;
25868   mp_fix_date_and_time(mp);
25869 }
25870
25871
25872 @* \[47] Debugging.
25873 Once \MP\ is working, you should be able to diagnose most errors with
25874 the \.{show} commands and other diagnostic features. But for the initial
25875 stages of debugging, and for the revelation of really deep mysteries, you
25876 can compile \MP\ with a few more aids. An additional routine called |debug_help|
25877 will also come into play when you type `\.D' after an error message;
25878 |debug_help| also occurs just before a fatal error causes \MP\ to succumb.
25879 @^debugging@>
25880 @^system dependencies@>
25881
25882 The interface to |debug_help| is primitive, but it is good enough when used
25883 with a debugger that allows you to set breakpoints and to read
25884 variables and change their values. After getting the prompt `\.{debug \#}', you
25885 type either a negative number (this exits |debug_help|), or zero (this
25886 goes to a location where you can set a breakpoint, thereby entering into
25887 dialog with the debugger), or a positive number |m| followed by
25888 an argument |n|. The meaning of |m| and |n| will be clear from the
25889 program below. (If |m=13|, there is an additional argument, |l|.)
25890 @.debug \#@>
25891
25892 @<Last-minute...@>=
25893 void mp_debug_help (MP mp) { /* routine to display various things */
25894   integer k;
25895   int l,m,n;
25896   char *aline;
25897   size_t len;
25898   while (1) { 
25899     wake_up_terminal;
25900     mp_print_nl(mp, "debug # (-1 to exit):"); update_terminal;
25901 @.debug \#@>
25902     m = 0;
25903     aline = (mp->read_ascii_file)(mp->term_in, &len);
25904     if (len) { sscanf(aline,"%i",&m); xfree(aline); }
25905     if ( m<=0 )
25906       return;
25907     n = 0 ;
25908     aline = (mp->read_ascii_file)(mp->term_in, &len);
25909     if (len) { sscanf(aline,"%i",&n); xfree(aline); }
25910     switch (m) {
25911     @<Numbered cases for |debug_help|@>;
25912     default: mp_print(mp, "?"); break;
25913     }
25914   }
25915 }
25916
25917 @ @<Numbered cases...@>=
25918 case 1: mp_print_word(mp, mp->mem[n]); /* display |mem[n]| in all forms */
25919   break;
25920 case 2: mp_print_int(mp, info(n));
25921   break;
25922 case 3: mp_print_int(mp, link(n));
25923   break;
25924 case 4: mp_print_int(mp, eq_type(n)); mp_print_char(mp, ':'); mp_print_int(mp, equiv(n));
25925   break;
25926 case 5: mp_print_variable_name(mp, n);
25927   break;
25928 case 6: mp_print_int(mp, mp->internal[n]);
25929   break;
25930 case 7: mp_do_show_dependencies(mp);
25931   break;
25932 case 9: mp_show_token_list(mp, n,null,100000,0);
25933   break;
25934 case 10: mp_print_str(mp, n);
25935   break;
25936 case 11: mp_check_mem(mp, n>0); /* check wellformedness; print new busy locations if |n>0| */
25937   break;
25938 case 12: mp_search_mem(mp, n); /* look for pointers to |n| */
25939   break;
25940 case 13: 
25941   l = 0;  
25942   aline = (mp->read_ascii_file)(mp->term_in, &len);
25943   if (len) { sscanf(aline,"%i",&l); xfree(aline); }
25944   mp_print_cmd_mod(mp, n,l); 
25945   break;
25946 case 14: for (k=0;k<=n;k++) mp_print_str(mp, mp->buffer[k]);
25947   break;
25948 case 15: mp->panicking=! mp->panicking;
25949   break;
25950
25951
25952 @ Saving the filename template
25953
25954 @<Save the filename template@>=
25955
25956   if ( mp->filename_template!=0 ) delete_str_ref(mp->filename_template);
25957   if ( length(mp->cur_exp)==0 ) mp->filename_template=0;
25958   else { 
25959     mp->filename_template=mp->cur_exp; add_str_ref(mp->filename_template);
25960   }
25961 }
25962
25963 @* \[48] System-dependent changes.
25964 This section should be replaced, if necessary, by any special
25965 modification of the program
25966 that are necessary to make \MP\ work at a particular installation.
25967 It is usually best to design your change file so that all changes to
25968 previous sections preserve the section numbering; then everybody's version
25969 will be consistent with the published program. More extensive changes,
25970 which introduce new sections, can be inserted here; then only the index
25971 itself will get a new section number.
25972 @^system dependencies@>
25973
25974 @* \[49] Index.
25975 Here is where you can find all uses of each identifier in the program,
25976 with underlined entries pointing to where the identifier was defined.
25977 If the identifier is only one letter long, however, you get to see only
25978 the underlined entries. {\sl All references are to section numbers instead of
25979 page numbers.}
25980
25981 This index also lists error messages and other aspects of the program
25982 that you might want to look up some day. For example, the entry
25983 for ``system dependencies'' lists all sections that should receive
25984 special attention from people who are installing \MP\ in a new
25985 operating environment. A list of various things that can't happen appears
25986 under ``this can't happen''.
25987 Approximately 25 sections are listed under ``inner loop''; these account
25988 for more than 60\pct! of \MP's running time, exclusive of input and output.