updated test file
[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 @ The |__attribute__| pragma is gcc-only.
162
163 @<Internal library ... @>=
164 #if !defined(__GNUC__) || (__GNUC__ < 2)
165 # define __attribute__(x)
166 #endif /* !defined(__GNUC__) || (__GNUC__ < 2) */
167
168 @ @c
169 MP __attribute__ ((noinline))
170 mp_new (struct MP_options *opt) {
171   MP mp;
172   mp = xmalloc(1,sizeof(MP_instance));
173   @<Set |ini_version|@>;
174   @<Setup the non-local jump buffer in |mp_new|@>;
175   @<Allocate or initialize variables@>
176   if (opt->main_memory>mp->mem_max)
177     mp_reallocate_memory(mp,opt->main_memory);
178   mp_reallocate_paths(mp,1000);
179   mp_reallocate_fonts(mp,8);
180   return mp;
181 }
182
183 @ @c
184 void mp_free (MP mp) {
185   int k; /* loop variable */
186   @<Dealloc variables@>
187   xfree(mp);
188 }
189
190 @ @c
191 void  __attribute__((noinline))
192 mp_do_initialize ( MP mp) {
193   @<Local variables for initialization@>
194   @<Set initial values of key variables@>
195 }
196 int mp_initialize (MP mp) { /* this procedure gets things started properly */
197   mp->history=mp_fatal_error_stop; /* in case we quit during initialization */
198   @<Install and test the non-local jump buffer@>;
199   t_open_out; /* open the terminal for output */
200   @<Check the ``constant'' values...@>;
201   if ( mp->bad>0 ) {
202         char ss[256];
203     snprintf(ss,256,"Ouch---my internal constants have been clobbered!\n"
204                    "---case %i",(int)mp->bad);
205     do_fprintf(mp->err_out,(char *)ss);
206 @.Ouch...clobbered@>
207     return mp->history;
208   }
209   mp_do_initialize(mp); /* erase preloaded mem */
210   if (mp->ini_version) {
211     @<Run inimpost commands@>;
212   }
213   @<Initialize the output routines@>;
214   @<Get the first line of input and prepare to start@>;
215   mp_set_job_id(mp);
216   mp_init_map_file(mp, mp->troff_mode);
217   mp->history=mp_spotless; /* ready to go! */
218   if (mp->troff_mode) {
219     mp->internal[mp_gtroffmode]=unity; 
220     mp->internal[mp_prologues]=unity; 
221   }
222   if ( mp->start_sym>0 ) { /* insert the `\&{everyjob}' symbol */
223     mp->cur_sym=mp->start_sym; mp_back_input(mp);
224   }
225   return mp->history;
226 }
227
228
229 @<Exported function headers@>=
230 extern struct MP_options *mp_options (void);
231 extern MP mp_new (struct MP_options *opt) ;
232 extern void mp_free (MP mp);
233 extern int mp_initialize (MP mp);
234
235 @ The overall \MP\ program begins with the heading just shown, after which
236 comes a bunch of procedure declarations and function declarations.
237 Finally we will get to the main program, which begins with the
238 comment `|start_here|'. If you want to skip down to the
239 main program now, you can look up `|start_here|' in the index.
240 But the author suggests that the best way to understand this program
241 is to follow pretty much the order of \MP's components as they appear in the
242 \.{WEB} description you are now reading, since the present ordering is
243 intended to combine the advantages of the ``bottom up'' and ``top down''
244 approaches to the problem of understanding a somewhat complicated system.
245
246 @ Some of the code below is intended to be used only when diagnosing the
247 strange behavior that sometimes occurs when \MP\ is being installed or
248 when system wizards are fooling around with \MP\ without quite knowing
249 what they are doing. Such code will not normally be compiled; it is
250 delimited by the preprocessor test `|#ifdef DEBUG .. #endif|'.
251
252 @ This program has two important variations: (1) There is a long and slow
253 version called \.{INIMP}, which does the extra calculations needed to
254 @.INIMP@>
255 initialize \MP's internal tables; and (2)~there is a shorter and faster
256 production version, which cuts the initialization to a bare minimum.
257
258 Which is which is decided at runtime.
259
260 @ The following parameters can be changed at compile time to extend or
261 reduce \MP's capacity. They may have different values in \.{INIMP} and
262 in production versions of \MP.
263 @.INIMP@>
264 @^system dependencies@>
265
266 @<Constants...@>=
267 #define file_name_size 255 /* file names shouldn't be longer than this */
268 #define bistack_size 1500 /* size of stack for bisection algorithms;
269   should probably be left at this value */
270
271 @ Like the preceding parameters, the following quantities can be changed
272 at compile time to extend or reduce \MP's capacity. But if they are changed,
273 it is necessary to rerun the initialization program \.{INIMP}
274 @.INIMP@>
275 to generate new tables for the production \MP\ program.
276 One can't simply make helter-skelter changes to the following constants,
277 since certain rather complex initialization
278 numbers are computed from them. 
279
280 @ @<Glob...@>=
281 int max_strings; /* maximum number of strings; must not exceed |max_halfword| */
282 int pool_size; /* maximum number of characters in strings, including all
283   error messages and help texts, and the names of all identifiers */
284 int mem_max; /* greatest index in \MP's internal |mem| array;
285   must be strictly less than |max_halfword|;
286   must be equal to |mem_top| in \.{INIMP}, otherwise |>=mem_top| */
287 int mem_top; /* largest index in the |mem| array dumped by \.{INIMP};
288   must not be greater than |mem_max| */
289
290 @ @<Option variables@>=
291 int error_line; /* width of context lines on terminal error messages */
292 int half_error_line; /* width of first lines of contexts in terminal
293   error messages; should be between 30 and |error_line-15| */
294 int max_print_line; /* width of longest text lines output; should be at least 60 */
295 int hash_size; /* maximum number of symbolic tokens,
296   must be less than |max_halfword-3*param_size| */
297 int hash_prime; /* a prime number equal to about 85\pct! of |hash_size| */
298 int param_size; /* maximum number of simultaneous macro parameters */
299 int max_in_open; /* maximum number of input files and error insertions that
300   can be going on simultaneously */
301 int main_memory; /* only for options, to set up |mem_max| and |mem_top| */
302
303
304 @d set_value(a,b,c) do { a=c; if (b>c) a=b; } while (0)
305
306 @<Allocate or ...@>=
307 mp->max_strings=500;
308 mp->pool_size=10000;
309 set_value(mp->error_line,opt->error_line,79);
310 set_value(mp->half_error_line,opt->half_error_line,50);
311 set_value(mp->max_print_line,opt->max_print_line,100);
312 mp->main_memory=5000;
313 mp->mem_max=5000;
314 mp->mem_top=5000;
315 set_value(mp->hash_size,opt->hash_size,9500);
316 set_value(mp->hash_prime,opt->hash_prime,7919);
317 set_value(mp->param_size,opt->param_size,150);
318 set_value(mp->max_in_open,opt->max_in_open,10);
319
320
321 @ In case somebody has inadvertently made bad settings of the ``constants,''
322 \MP\ checks them using a global variable called |bad|.
323
324 This is the first of many sections of \MP\ where global variables are
325 defined.
326
327 @<Glob...@>=
328 integer bad; /* is some ``constant'' wrong? */
329
330 @ Later on we will say `\ignorespaces|if (mem_max>=max_halfword) bad=10;|',
331 or something similar. (We can't do that until |max_halfword| has been defined.)
332
333 @<Check the ``constant'' values for consistency@>=
334 mp->bad=0;
335 if ( (mp->half_error_line<30)||(mp->half_error_line>mp->error_line-15) ) mp->bad=1;
336 if ( mp->max_print_line<60 ) mp->bad=2;
337 if ( mp->mem_top<=1100 ) mp->bad=4;
338 if (mp->hash_prime>mp->hash_size ) mp->bad=5;
339
340 @ Some |goto| labels are used by the following definitions. The label
341 `|restart|' is occasionally used at the very beginning of a procedure; and
342 the label `|reswitch|' is occasionally used just prior to a |case|
343 statement in which some cases change the conditions and we wish to branch
344 to the newly applicable case.  Loops that are set up with the |loop|
345 construction defined below are commonly exited by going to `|done|' or to
346 `|found|' or to `|not_found|', and they are sometimes repeated by going to
347 `|continue|'.  If two or more parts of a subroutine start differently but
348 end up the same, the shared code may be gathered together at
349 `|common_ending|'.
350
351 @ Here are some macros for common programming idioms.
352
353 @d incr(A)   (A)=(A)+1 /* increase a variable by unity */
354 @d decr(A)   (A)=(A)-1 /* decrease a variable by unity */
355 @d negate(A) (A)=-(A) /* change the sign of a variable */
356 @d double(A) (A)=(A)+(A)
357 @d odd(A)   ((A)%2==1)
358 @d chr(A)   (A)
359 @d do_nothing   /* empty statement */
360 @d Return   goto exit /* terminate a procedure call */
361 @f return   nil /* \.{WEB} will henceforth say |return| instead of \\{return} */
362
363 @* \[2] The character set.
364 In order to make \MP\ readily portable to a wide variety of
365 computers, all of its input text is converted to an internal eight-bit
366 code that includes standard ASCII, the ``American Standard Code for
367 Information Interchange.''  This conversion is done immediately when each
368 character is read in. Conversely, characters are converted from ASCII to
369 the user's external representation just before they are output to a
370 text file.
371 @^ASCII code@>
372
373 Such an internal code is relevant to users of \MP\ only with respect to
374 the \&{char} and \&{ASCII} operations, and the comparison of strings.
375
376 @ Characters of text that have been converted to \MP's internal form
377 are said to be of type |ASCII_code|, which is a subrange of the integers.
378
379 @<Types...@>=
380 typedef unsigned char ASCII_code; /* eight-bit numbers */
381
382 @ The present specification of \MP\ has been written under the assumption
383 that the character set contains at least the letters and symbols associated
384 with ASCII codes 040 through 0176; all of these characters are now
385 available on most computer terminals.
386
387 We shall use the name |text_char| to stand for the data type of the characters 
388 that are converted to and from |ASCII_code| when they are input and output. 
389 We shall also assume that |text_char| consists of the elements 
390 |chr(first_text_char)| through |chr(last_text_char)|, inclusive. 
391 The following definitions should be adjusted if necessary.
392 @^system dependencies@>
393
394 @d first_text_char 0 /* ordinal number of the smallest element of |text_char| */
395 @d last_text_char 255 /* ordinal number of the largest element of |text_char| */
396
397 @<Types...@>=
398 typedef unsigned char text_char; /* the data type of characters in text files */
399
400 @ @<Local variables for init...@>=
401 integer i;
402
403 @ The \MP\ processor converts between ASCII code and
404 the user's external character set by means of arrays |xord| and |xchr|
405 that are analogous to Pascal's |ord| and |chr| functions.
406
407 @d xchr(A) mp->xchr[(A)]
408 @d xord(A) mp->xord[(A)]
409
410 @<Glob...@>=
411 ASCII_code xord[256];  /* specifies conversion of input characters */
412 text_char xchr[256];  /* specifies conversion of output characters */
413
414 @ The core system assumes all 8-bit is acceptable.  If it is not,
415 a change file has to alter the below section.
416 @^system dependencies@>
417
418 Additionally, people with extended character sets can
419 assign codes arbitrarily, giving an |xchr| equivalent to whatever
420 characters the users of \MP\ are allowed to have in their input files.
421 Appropriate changes to \MP's |char_class| table should then be made.
422 (Unlike \TeX, each installation of \MP\ has a fixed assignment of category
423 codes, called the |char_class|.) Such changes make portability of programs
424 more difficult, so they should be introduced cautiously if at all.
425 @^character set dependencies@>
426 @^system dependencies@>
427
428 @<Set initial ...@>=
429 for (i=0;i<=0377;i++) { xchr(i)=i; }
430
431 @ The following system-independent code makes the |xord| array contain a
432 suitable inverse to the information in |xchr|. Note that if |xchr[i]=xchr[j]|
433 where |i<j<0177|, the value of |xord[xchr[i]]| will turn out to be
434 |j| or more; hence, standard ASCII code numbers will be used instead of
435 codes below 040 in case there is a coincidence.
436
437 @<Set initial ...@>=
438 for (i=first_text_char;i<=last_text_char;i++) { 
439    xord(chr(i))=0177;
440 }
441 for (i=0200;i<=0377;i++) { xord(xchr(i))=i;}
442 for (i=0;i<=0176;i++) { xord(xchr(i))=i;}
443
444 @* \[3] Input and output.
445 The bane of portability is the fact that different operating systems treat
446 input and output quite differently, perhaps because computer scientists
447 have not given sufficient attention to this problem. People have felt somehow
448 that input and output are not part of ``real'' programming. Well, it is true
449 that some kinds of programming are more fun than others. With existing
450 input/output conventions being so diverse and so messy, the only sources of
451 joy in such parts of the code are the rare occasions when one can find a
452 way to make the program a little less bad than it might have been. We have
453 two choices, either to attack I/O now and get it over with, or to postpone
454 I/O until near the end. Neither prospect is very attractive, so let's
455 get it over with.
456
457 The basic operations we need to do are (1)~inputting and outputting of
458 text, to or from a file or the user's terminal; (2)~inputting and
459 outputting of eight-bit bytes, to or from a file; (3)~instructing the
460 operating system to initiate (``open'') or to terminate (``close'') input or
461 output from a specified file; (4)~testing whether the end of an input
462 file has been reached; (5)~display of bits on the user's screen.
463 The bit-display operation will be discussed in a later section; we shall
464 deal here only with more traditional kinds of I/O.
465
466 @ Finding files happens in a slightly roundabout fashion: the \MP\
467 instance object contains a field that holds a function pointer that finds a
468 file, and returns its name, or NULL. For this, it receives three
469 parameters: the non-qualified name |fname|, the intended |fopen|
470 operation type |fmode|, and the type of the file |ftype|.
471
472 The file types that are passed on in |ftype| can be  used to 
473 differentiate file searches if a library like kpathsea is used,
474 the fopen mode is passed along for the same reason.
475
476 @<Types...@>=
477 typedef unsigned char eight_bits ; /* unsigned one-byte quantity */
478
479 @ @<Exported types@>=
480 enum mp_filetype {
481   mp_filetype_terminal = 0, /* the terminal */
482   mp_filetype_error, /* the terminal */
483   mp_filetype_program , /* \MP\ language input */
484   mp_filetype_log,  /* the log file */
485   mp_filetype_postscript, /* the postscript output */
486   mp_filetype_memfile, /* memory dumps */
487   mp_filetype_metrics, /* TeX font metric files */
488   mp_filetype_fontmap, /* PostScript font mapping files */
489   mp_filetype_font, /*  PostScript type1 font programs */
490   mp_filetype_encoding, /*  PostScript font encoding files */
491   mp_filetype_text,  /* first text file for readfrom and writeto primitives */
492 };
493 typedef char *(*mp_file_finder)(char *, char *, int);
494 typedef void *(*mp_file_opener)(char *, char *, int);
495 typedef char *(*mp_file_reader)(void *, size_t *);
496 typedef void (*mp_binfile_reader)(void *, void **, size_t *);
497 typedef void (*mp_file_closer)(void *);
498 typedef int (*mp_file_eoftest)(void *);
499 typedef void (*mp_file_flush)(void *);
500 typedef void (*mp_file_writer)(void *, char *);
501 typedef void (*mp_binfile_writer)(void *, void *, size_t);
502 #define NOTTESTING 1
503
504 @ @<Option variables@>=
505 mp_file_finder find_file;
506 mp_file_opener open_file;
507 mp_file_reader read_ascii_file;
508 mp_binfile_reader read_binary_file;
509 mp_file_closer close_file;
510 mp_file_eoftest eof_file;
511 mp_file_flush flush_file;
512 mp_file_writer write_ascii_file;
513 mp_binfile_writer write_binary_file;
514
515 @ The default function for finding files is |mp_find_file|. It is 
516 pretty stupid: it will only find files in the current directory.
517
518 This function may disappear altogether, it is currently only
519 used for the default font map file.
520
521 @c
522 char *mp_find_file (char *fname, char *fmode, int ftype)  {
523   if (fmode[0] != 'r' || (! access (fname,R_OK)) || ftype) {  
524      return strdup(fname);
525   }
526   return NULL;
527 }
528
529 @ This has to be done very early on, so it is best to put it in with
530 the |mp_new| allocations
531
532 @d set_callback_option(A) do { mp->A = mp_##A;
533   if (opt->A!=NULL) mp->A = opt->A;
534 } while (0)
535
536 @<Allocate or initialize ...@>=
537 set_callback_option(find_file);
538 set_callback_option(open_file);
539 set_callback_option(read_ascii_file);
540 set_callback_option(read_binary_file);
541 set_callback_option(close_file);
542 set_callback_option(eof_file);
543 set_callback_option(flush_file);
544 set_callback_option(write_ascii_file);
545 set_callback_option(write_binary_file);
546
547 @ Because |mp_find_file| is used so early, it has to be in the helpers
548 section.
549
550 @<Internal ...@>=
551 char *mp_find_file (char *fname, char *fmode, int ftype) ;
552 void *mp_open_file (char *fname, char *fmode, int ftype) ;
553 char *mp_read_ascii_file (void *f, size_t *size) ;
554 void mp_read_binary_file (void *f, void **d, size_t *size) ;
555 void mp_close_file (void *f) ;
556 int mp_eof_file (void *f) ;
557 void mp_flush_file (void *f) ;
558 void mp_write_ascii_file (void *f, char *s) ;
559 void mp_write_binary_file (void *f, void *s, size_t t) ;
560
561 @ The function to open files can now be very short.
562
563 @c
564 void *mp_open_file(char *fname, char *fmode, int ftype)  {
565 #if NOTTESTING
566   if (ftype==mp_filetype_terminal) {
567     return (fmode[0] == 'r' ? stdin : stdout);
568   } else if (ftype==mp_filetype_error) {
569     return stderr;
570   } else if (fname != NULL && (fmode[0] != 'r' || (! access (fname,R_OK)))) {
571     return (void *)fopen(fname, fmode);
572   }
573 #endif
574   return NULL;
575 }
576
577 @ This is a legacy interface: (almost) all file names pass through |name_of_file|.
578
579 @<Glob...@>=
580 char name_of_file[file_name_size+1]; /* the name of a system file */
581 int name_length;/* this many characters are actually
582   relevant in |name_of_file| (the rest are blank) */
583
584 @ @<Option variables@>=
585 int print_found_names; /* configuration parameter */
586
587 @ If this parameter is true, the terminal and log will report the found
588 file names for input files instead of the requested ones. 
589 It is off by default because it creates an extra filename lookup.
590
591 @<Allocate or initialize ...@>=
592 mp->print_found_names = (opt->print_found_names>0 ? true : false);
593
594 @ \MP's file-opening procedures return |false| if no file identified by
595 |name_of_file| could be opened.
596
597 The |OPEN_FILE| macro takes care of the |print_found_names| parameter.
598 It is not used for opening a mem file for read, because that file name 
599 is never printed.
600
601 @d OPEN_FILE(A) do {
602   if (mp->print_found_names) {
603     char *s = (mp->find_file)(mp->name_of_file,A,ftype);
604     if (s!=NULL) {
605       *f = (mp->open_file)(mp->name_of_file,A, ftype); 
606       strncpy(mp->name_of_file,s,file_name_size);
607       xfree(s);
608     } else {
609       *f = NULL;
610     }
611   } else {
612     *f = (mp->open_file)(mp->name_of_file,A, ftype); 
613   }
614 } while (0);
615 return (*f ? true : false)
616
617 @c 
618 boolean mp_a_open_in (MP mp, void **f, int ftype) {
619   /* open a text file for input */
620   OPEN_FILE("r");
621 }
622 @#
623 boolean mp_w_open_in (MP mp, void **f) {
624   /* open a word file for input */
625   *f = (mp->open_file)(mp->name_of_file,"rb",mp_filetype_memfile); 
626   return (*f ? true : false);
627 }
628 @#
629 boolean mp_a_open_out (MP mp, void **f, int ftype) {
630   /* open a text file for output */
631   OPEN_FILE("w");
632 }
633 @#
634 boolean mp_b_open_out (MP mp, void **f, int ftype) {
635   /* open a binary file for output */
636   OPEN_FILE("wb");
637 }
638 @#
639 boolean mp_w_open_out (MP mp, void **f) {
640   /* open a word file for output */
641   int ftype = mp_filetype_memfile;
642   OPEN_FILE("wb");
643 }
644
645 @ @c
646 char *mp_read_ascii_file (void *ff, size_t *size) {
647   int c;
648   size_t len = 0, lim = 128;
649   char *s = NULL;
650   FILE *f = (FILE *)ff;
651   *size = 0;
652 #if NOTTESTING
653   c = fgetc(f);
654   if (c==EOF)
655     return NULL;
656   s = malloc(lim); 
657   if (s==NULL) return NULL;
658   while (c!=EOF && c!='\n' && c!='\r') { 
659     if (len==lim) {
660       s =realloc(s, (lim+(lim>>2)));
661       if (s==NULL) return NULL;
662       lim+=(lim>>2);
663     }
664         s[len++] = c;
665     c =fgetc(f);
666   }
667   if (c=='\r') {
668     c = fgetc(f);
669     if (c!=EOF && c!='\n')
670        ungetc(c,f);
671   }
672   s[len] = 0;
673   *size = len;
674 #endif
675   return s;
676 }
677
678 @ @c
679 void mp_write_ascii_file (void *f, char *s) {
680 #if NOTTESTING
681   if (f!=NULL) {
682     fputs(s,(FILE *)f);
683   }
684 #endif
685 }
686
687 @ @c
688 void mp_read_binary_file (void *f, void **data, size_t *size) {
689   size_t len = 0;
690 #if NOTTESTING
691   len = fread(*data,1,*size,(FILE *)f);
692 #endif
693   *size = len;
694 }
695
696 @ @c
697 void mp_write_binary_file (void *f, void *s, size_t size) {
698 #if NOTTESTING
699   if (f!=NULL)
700     fwrite(s,size,1,(FILE *)f);
701 #endif
702 }
703
704
705 @ @c
706 void mp_close_file (void *f) {
707 #if NOTTESTING
708   fclose((FILE *)f);
709 #endif
710 }
711
712 @ @c
713 int mp_eof_file (void *f) {
714 #if NOTTESTING
715   return feof((FILE *)f);
716 #else
717   return 0;
718 #endif
719 }
720
721 @ @c
722 void mp_flush_file (void *f) {
723 #if NOTTESTING
724   fflush((FILE *)f);
725 #endif
726 }
727
728 @ Input from text files is read one line at a time, using a routine called
729 |input_ln|. This function is defined in terms of global variables called
730 |buffer|, |first|, and |last| that will be described in detail later; for
731 now, it suffices for us to know that |buffer| is an array of |ASCII_code|
732 values, and that |first| and |last| are indices into this array
733 representing the beginning and ending of a line of text.
734
735 @<Glob...@>=
736 size_t buf_size; /* maximum number of characters simultaneously present in
737                     current lines of open files */
738 ASCII_code *buffer; /* lines of characters being read */
739 size_t first; /* the first unused position in |buffer| */
740 size_t last; /* end of the line just input to |buffer| */
741 size_t max_buf_stack; /* largest index used in |buffer| */
742
743 @ @<Allocate or initialize ...@>=
744 mp->buf_size = 200;
745 mp->buffer = xmalloc((mp->buf_size+1),sizeof(ASCII_code));
746
747 @ @<Dealloc variables@>=
748 xfree(mp->buffer);
749
750 @ @c
751 void mp_reallocate_buffer(MP mp, size_t l) {
752   ASCII_code *buffer;
753   if (l>max_halfword) {
754     mp_confusion(mp,"buffer size"); /* can't happen (I hope) */
755   }
756   buffer = xmalloc((l+1),sizeof(ASCII_code));
757   memcpy(buffer,mp->buffer,(mp->buf_size+1));
758   xfree(mp->buffer);
759   mp->buffer = buffer ;
760   mp->buf_size = l;
761 }
762
763 @ The |input_ln| function brings the next line of input from the specified
764 field into available positions of the buffer array and returns the value
765 |true|, unless the file has already been entirely read, in which case it
766 returns |false| and sets |last:=first|.  In general, the |ASCII_code|
767 numbers that represent the next line of the file are input into
768 |buffer[first]|, |buffer[first+1]|, \dots, |buffer[last-1]|; and the
769 global variable |last| is set equal to |first| plus the length of the
770 line. Trailing blanks are removed from the line; thus, either |last=first|
771 (in which case the line was entirely blank) or |buffer[last-1]<>" "|.
772 @^inner loop@>
773
774 The variable |max_buf_stack|, which is used to keep track of how large
775 the |buf_size| parameter must be to accommodate the present job, is
776 also kept up to date by |input_ln|.
777
778 @c 
779 boolean mp_input_ln (MP mp, void *f ) {
780   /* inputs the next line or returns |false| */
781   char *s;
782   size_t size = 0; 
783   mp->last=mp->first; /* cf.\ Matthew 19\thinspace:\thinspace30 */
784   s = (mp->read_ascii_file)(f, &size);
785   if (s==NULL)
786         return false;
787   if (size>0) {
788     mp->last = mp->first+size;
789     if ( mp->last>=mp->max_buf_stack ) { 
790       mp->max_buf_stack=mp->last+1;
791       while ( mp->max_buf_stack>=mp->buf_size ) {
792         mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
793       }
794     }
795     memcpy((mp->buffer+mp->first),s,size);
796     /* while ( mp->buffer[mp->last]==' ' ) mp->last--; */
797   } 
798   free(s);
799   return true;
800 }
801
802 @ The user's terminal acts essentially like other files of text, except
803 that it is used both for input and for output. When the terminal is
804 considered an input file, the file variable is called |term_in|, and when it
805 is considered an output file the file variable is |term_out|.
806 @^system dependencies@>
807
808 @<Glob...@>=
809 void * term_in; /* the terminal as an input file */
810 void * term_out; /* the terminal as an output file */
811 void * err_out; /* the terminal as an output file */
812
813 @ Here is how to open the terminal files. In the default configuration,
814 nothing happens except that the command line (if there is one) is copied
815 to the input buffer.  The variable |command_line| will be filled by the 
816 |main| procedure. The copying can not be done earlier in the program 
817 logic because in the |INI| version, the |buffer| is also used for primitive 
818 initialization.
819
820 @^system dependencies@>
821
822 @d t_open_out  do {/* open the terminal for text output */
823     mp->term_out = (mp->open_file)("terminal", "w", mp_filetype_terminal);
824     mp->err_out = (mp->open_file)("error", "w", mp_filetype_error);
825 } while (0)
826 @d t_open_in  do { /* open the terminal for text input */
827     mp->term_in = (mp->open_file)("terminal", "r", mp_filetype_terminal);
828     if (mp->command_line!=NULL) {
829       mp->last = strlen(mp->command_line);
830       strncpy((char *)mp->buffer,mp->command_line,mp->last);
831       xfree(mp->command_line);
832     } else {
833           mp->last = 0;
834     }
835 } while (0)
836
837 @d t_close_out do { /* close the terminal */
838   (mp->close_file)(mp->term_out);
839   (mp->close_file)(mp->err_out);
840 } while (0)
841
842 @d t_close_in do { /* close the terminal */
843   (mp->close_file)(mp->term_in);
844 } while (0)
845
846 @<Option variables@>=
847 char *command_line;
848
849 @ @<Allocate or initialize ...@>=
850 mp->command_line = xstrdup(opt->command_line);
851
852 @ Sometimes it is necessary to synchronize the input/output mixture that
853 happens on the user's terminal, and three system-dependent
854 procedures are used for this
855 purpose. The first of these, |update_terminal|, is called when we want
856 to make sure that everything we have output to the terminal so far has
857 actually left the computer's internal buffers and been sent.
858 The second, |clear_terminal|, is called when we wish to cancel any
859 input that the user may have typed ahead (since we are about to
860 issue an unexpected error message). The third, |wake_up_terminal|,
861 is supposed to revive the terminal if the user has disabled it by
862 some instruction to the operating system.  The following macros show how
863 these operations can be specified:
864 @^system dependencies@>
865
866 @d update_terminal   (mp->flush_file)(mp->term_out) /* empty the terminal output buffer */
867 @d clear_terminal   do_nothing /* clear the terminal input buffer */
868 @d wake_up_terminal  (mp->flush_file)(mp->term_out) /* cancel the user's cancellation of output */
869
870 @ We need a special routine to read the first line of \MP\ input from
871 the user's terminal. This line is different because it is read before we
872 have opened the transcript file; there is sort of a ``chicken and
873 egg'' problem here. If the user types `\.{input cmr10}' on the first
874 line, or if some macro invoked by that line does such an \.{input},
875 the transcript file will be named `\.{cmr10.log}'; but if no \.{input}
876 commands are performed during the first line of terminal input, the transcript
877 file will acquire its default name `\.{mpout.log}'. (The transcript file
878 will not contain error messages generated by the first line before the
879 first \.{input} command.)
880
881 The first line is even more special. It's nice to let the user start
882 running a \MP\ job by typing a command line like `\.{MP cmr10}'; in
883 such a case, \MP\ will operate as if the first line of input were
884 `\.{cmr10}', i.e., the first line will consist of the remainder of the
885 command line, after the part that invoked \MP.
886
887 @ Different systems have different ways to get started. But regardless of
888 what conventions are adopted, the routine that initializes the terminal
889 should satisfy the following specifications:
890
891 \yskip\textindent{1)}It should open file |term_in| for input from the
892   terminal. (The file |term_out| will already be open for output to the
893   terminal.)
894
895 \textindent{2)}If the user has given a command line, this line should be
896   considered the first line of terminal input. Otherwise the
897   user should be prompted with `\.{**}', and the first line of input
898   should be whatever is typed in response.
899
900 \textindent{3)}The first line of input, which might or might not be a
901   command line, should appear in locations |first| to |last-1| of the
902   |buffer| array.
903
904 \textindent{4)}The global variable |loc| should be set so that the
905   character to be read next by \MP\ is in |buffer[loc]|. This
906   character should not be blank, and we should have |loc<last|.
907
908 \yskip\noindent(It may be necessary to prompt the user several times
909 before a non-blank line comes in. The prompt is `\.{**}' instead of the
910 later `\.*' because the meaning is slightly different: `\.{input}' need
911 not be typed immediately after~`\.{**}'.)
912
913 @d loc mp->cur_input.loc_field /* location of first unread character in |buffer| */
914
915 @ The following program does the required initialization
916 without retrieving a possible command line.
917 It should be clear how to modify this routine to deal with command lines,
918 if the system permits them.
919 @^system dependencies@>
920
921 @c 
922 boolean mp_init_terminal (MP mp) { /* gets the terminal input started */
923   t_open_in; 
924   if (mp->last!=0) {
925     loc = mp->first = 0;
926         return true;
927   }
928   while (1) { 
929     if (!mp->noninteractive) {
930           wake_up_terminal; do_fprintf(mp->term_out,"**"); update_terminal;
931 @.**@>
932     }
933     if ( ! mp_input_ln(mp, mp->term_in ) ) { /* this shouldn't happen */
934       do_fprintf(mp->term_out,"\n! End of file on the terminal... why?");
935 @.End of file on the terminal@>
936       return false;
937     }
938     loc=mp->first;
939     while ( (loc<(int)mp->last)&&(mp->buffer[loc]==' ') ) 
940       incr(loc);
941     if ( loc<(int)mp->last ) { 
942       return true; /* return unless the line was all blank */
943     }
944     if (!mp->noninteractive) {
945           do_fprintf(mp->term_out,"Please type the name of your input file.\n");
946     }
947   }
948 }
949
950 @ @<Declarations@>=
951 boolean mp_init_terminal (MP mp) ;
952
953
954 @* \[4] String handling.
955 Symbolic token names and diagnostic messages are variable-length strings
956 of eight-bit characters. Many strings \MP\ uses are simply literals
957 in the compiled source, like the error messages and the names of the
958 internal parameters. Other strings are used or defined from the \MP\ input 
959 language, and these have to be interned.
960
961 \MP\ uses strings more extensively than \MF\ does, but the necessary
962 operations can still be handled with a fairly simple data structure.
963 The array |str_pool| contains all of the (eight-bit) ASCII codes in all
964 of the strings, and the array |str_start| contains indices of the starting
965 points of each string. Strings are referred to by integer numbers, so that
966 string number |s| comprises the characters |str_pool[j]| for
967 |str_start[s]<=j<str_start[ss]| where |ss=next_str[s]|.  The string pool
968 is allocated sequentially and |str_pool[pool_ptr]| is the next unused
969 location.  The first string number not currently in use is |str_ptr|
970 and |next_str[str_ptr]| begins a list of free string numbers.  String
971 pool entries |str_start[str_ptr]| up to |pool_ptr| are reserved for a
972 string currently being constructed.
973
974 String numbers 0 to 255 are reserved for strings that correspond to single
975 ASCII characters. This is in accordance with the conventions of \.{WEB},
976 @.WEB@>
977 which converts single-character strings into the ASCII code number of the
978 single character involved, while it converts other strings into integers
979 and builds a string pool file. Thus, when the string constant \.{"."} appears
980 in the program below, \.{WEB} converts it into the integer 46, which is the
981 ASCII code for a period, while \.{WEB} will convert a string like \.{"hello"}
982 into some integer greater than~255. String number 46 will presumably be the
983 single character `\..'\thinspace; but some ASCII codes have no standard visible
984 representation, and \MP\ may need to be able to print an arbitrary
985 ASCII character, so the first 256 strings are used to specify exactly what
986 should be printed for each of the 256 possibilities.
987
988 @<Types...@>=
989 typedef int pool_pointer; /* for variables that point into |str_pool| */
990 typedef int str_number; /* for variables that point into |str_start| */
991
992 @ @<Glob...@>=
993 ASCII_code *str_pool; /* the characters */
994 pool_pointer *str_start; /* the starting pointers */
995 str_number *next_str; /* for linking strings in order */
996 pool_pointer pool_ptr; /* first unused position in |str_pool| */
997 str_number str_ptr; /* number of the current string being created */
998 pool_pointer init_pool_ptr; /* the starting value of |pool_ptr| */
999 str_number init_str_use; /* the initial number of strings in use */
1000 pool_pointer max_pool_ptr; /* the maximum so far of |pool_ptr| */
1001 str_number max_str_ptr; /* the maximum so far of |str_ptr| */
1002
1003 @ @<Allocate or initialize ...@>=
1004 mp->str_pool  = xmalloc ((mp->pool_size +1),sizeof(ASCII_code));
1005 mp->str_start = xmalloc ((mp->max_strings+1),sizeof(pool_pointer));
1006 mp->next_str  = xmalloc ((mp->max_strings+1),sizeof(str_number));
1007
1008 @ @<Dealloc variables@>=
1009 xfree(mp->str_pool);
1010 xfree(mp->str_start);
1011 xfree(mp->next_str);
1012
1013 @ Most printing is done from |char *|s, but sometimes not. Here are
1014 functions that convert an internal string into a |char *| for use
1015 by the printing routines, and vice versa.
1016
1017 @d str(A) mp_str(mp,A)
1018 @d rts(A) mp_rts(mp,A)
1019
1020 @<Internal ...@>=
1021 int mp_xstrcmp (const char *a, const char *b);
1022 char * mp_str (MP mp, str_number s);
1023
1024 @ @<Declarations@>=
1025 str_number mp_rts (MP mp, char *s);
1026 str_number mp_make_string (MP mp);
1027
1028 @ The attempt to catch interrupted strings that is in |mp_rts|, is not 
1029 very good: it does not handle nesting over more than one level.
1030
1031 @c 
1032 int mp_xstrcmp (const char *a, const char *b) {
1033         if (a==NULL && b==NULL) 
1034           return 0;
1035     if (a==NULL)
1036       return -1;
1037     if (b==NULL)
1038       return 1;
1039     return strcmp(a,b);
1040 }
1041
1042 @ @c
1043 char * mp_str (MP mp, str_number ss) {
1044   char *s;
1045   int len;
1046   if (ss==mp->str_ptr) {
1047     return NULL;
1048   } else {
1049     len = length(ss);
1050     s = xmalloc(len+1,sizeof(char));
1051     strncpy(s,(char *)(mp->str_pool+(mp->str_start[ss])),len);
1052     s[len] = 0;
1053     return (char *)s;
1054   }
1055 }
1056 str_number mp_rts (MP mp, char *s) {
1057   int r; /* the new string */ 
1058   int old; /* a possible string in progress */
1059   int i=0;
1060   if (strlen(s)==0) {
1061     return 256;
1062   } else if (strlen(s)==1) {
1063     return s[0];
1064   } else {
1065    old=0;
1066    str_room((integer)strlen(s));
1067    if (mp->str_start[mp->str_ptr]<mp->pool_ptr)
1068      old = mp_make_string(mp);
1069    while (*s) {
1070      append_char(*s);
1071      s++;
1072    }
1073    r = mp_make_string(mp);
1074    if (old!=0) {
1075       str_room(length(old));
1076       while (i<length(old)) {
1077         append_char((mp->str_start[old]+i));
1078       } 
1079       mp_flush_string(mp,old);
1080     }
1081     return r;
1082   }
1083 }
1084
1085 @ Except for |strs_used_up|, the following string statistics are only
1086 maintained when code between |stat| $\ldots$ |tats| delimiters is not
1087 commented out:
1088
1089 @<Glob...@>=
1090 integer strs_used_up; /* strings in use or unused but not reclaimed */
1091 integer pool_in_use; /* total number of cells of |str_pool| actually in use */
1092 integer strs_in_use; /* total number of strings actually in use */
1093 integer max_pl_used; /* maximum |pool_in_use| so far */
1094 integer max_strs_used; /* maximum |strs_in_use| so far */
1095
1096 @ Several of the elementary string operations are performed using \.{WEB}
1097 macros instead of functions, because many of the
1098 operations are done quite frequently and we want to avoid the
1099 overhead of procedure calls. For example, here is
1100 a simple macro that computes the length of a string.
1101 @.WEB@>
1102
1103 @d str_stop(A) mp->str_start[mp->next_str[(A)]] /* one cell past the end of string
1104   number \# */
1105 @d length(A) (str_stop((A))-mp->str_start[(A)]) /* the number of characters in string \# */
1106
1107 @ The length of the current string is called |cur_length|.  If we decide that
1108 the current string is not needed, |flush_cur_string| resets |pool_ptr| so that
1109 |cur_length| becomes zero.
1110
1111 @d cur_length   (mp->pool_ptr - mp->str_start[mp->str_ptr])
1112 @d flush_cur_string   mp->pool_ptr=mp->str_start[mp->str_ptr]
1113
1114 @ Strings are created by appending character codes to |str_pool|.
1115 The |append_char| macro, defined here, does not check to see if the
1116 value of |pool_ptr| has gotten too high; this test is supposed to be
1117 made before |append_char| is used.
1118
1119 To test if there is room to append |l| more characters to |str_pool|,
1120 we shall write |str_room(l)|, which tries to make sure there is enough room
1121 by compacting the string pool if necessary.  If this does not work,
1122 |do_compaction| aborts \MP\ and gives an apologetic error message.
1123
1124 @d append_char(A)   /* put |ASCII_code| \# at the end of |str_pool| */
1125 { mp->str_pool[mp->pool_ptr]=(A); incr(mp->pool_ptr);
1126 }
1127 @d str_room(A)   /* make sure that the pool hasn't overflowed */
1128   { if ( mp->pool_ptr+(A) > mp->max_pool_ptr ) {
1129     if ( mp->pool_ptr+(A) > mp->pool_size ) mp_do_compaction(mp, (A));
1130     else mp->max_pool_ptr=mp->pool_ptr+(A); }
1131   }
1132
1133 @ The following routine is similar to |str_room(1)| but it uses the
1134 argument |mp->pool_size| to prevent |do_compaction| from aborting when
1135 string space is exhausted.
1136
1137 @<Declare the procedure called |unit_str_room|@>=
1138 void mp_unit_str_room (MP mp);
1139
1140 @ @c
1141 void mp_unit_str_room (MP mp) { 
1142   if ( mp->pool_ptr>=mp->pool_size ) mp_do_compaction(mp, mp->pool_size);
1143   if ( mp->pool_ptr>=mp->max_pool_ptr ) mp->max_pool_ptr=mp->pool_ptr+1;
1144 }
1145
1146 @ \MP's string expressions are implemented in a brute-force way: Every
1147 new string or substring that is needed is simply copied into the string pool.
1148 Space is eventually reclaimed by a procedure called |do_compaction| with
1149 the aid of a simple system system of reference counts.
1150 @^reference counts@>
1151
1152 The number of references to string number |s| will be |str_ref[s]|. The
1153 special value |str_ref[s]=max_str_ref=127| is used to denote an unknown
1154 positive number of references; such strings will never be recycled. If
1155 a string is ever referred to more than 126 times, simultaneously, we
1156 put it in this category. Hence a single byte suffices to store each |str_ref|.
1157
1158 @d max_str_ref 127 /* ``infinite'' number of references */
1159 @d add_str_ref(A) { if ( mp->str_ref[(A)]<max_str_ref ) incr(mp->str_ref[(A)]);
1160   }
1161
1162 @<Glob...@>=
1163 int *str_ref;
1164
1165 @ @<Allocate or initialize ...@>=
1166 mp->str_ref = xmalloc ((mp->max_strings+1),sizeof(int));
1167
1168 @ @<Dealloc variables@>=
1169 xfree(mp->str_ref);
1170
1171 @ Here's what we do when a string reference disappears:
1172
1173 @d delete_str_ref(A)  { 
1174     if ( mp->str_ref[(A)]<max_str_ref ) {
1175        if ( mp->str_ref[(A)]>1 ) decr(mp->str_ref[(A)]); 
1176        else mp_flush_string(mp, (A));
1177     }
1178   }
1179
1180 @<Declare the procedure called |flush_string|@>=
1181 void mp_flush_string (MP mp,str_number s) ;
1182
1183
1184 @ We can't flush the first set of static strings at all, so there 
1185 is no point in trying
1186
1187 @c
1188 void mp_flush_string (MP mp,str_number s) { 
1189   if (length(s)>1) {
1190     mp->pool_in_use=mp->pool_in_use-length(s);
1191     decr(mp->strs_in_use);
1192     if ( mp->next_str[s]!=mp->str_ptr ) {
1193       mp->str_ref[s]=0;
1194     } else { 
1195       mp->str_ptr=s;
1196       decr(mp->strs_used_up);
1197     }
1198     mp->pool_ptr=mp->str_start[mp->str_ptr];
1199   }
1200 }
1201
1202 @ C literals cannot be simply added, they need to be set so they can't
1203 be flushed.
1204
1205 @d intern(A) mp_intern(mp,(A))
1206
1207 @c
1208 str_number mp_intern (MP mp, char *s) {
1209   str_number r ;
1210   r = rts(s);
1211   mp->str_ref[r] = max_str_ref;
1212   return r;
1213 }
1214
1215 @ @<Declarations@>=
1216 str_number mp_intern (MP mp, char *s);
1217
1218
1219 @ Once a sequence of characters has been appended to |str_pool|, it
1220 officially becomes a string when the function |make_string| is called.
1221 This function returns the identification number of the new string as its
1222 value.
1223
1224 When getting the next unused string number from the linked list, we pretend
1225 that
1226 $$ \hbox{|max_str_ptr+1|, |max_str_ptr+2|, $\ldots$, |mp->max_strings|} $$
1227 are linked sequentially even though the |next_str| entries have not been
1228 initialized yet.  We never allow |str_ptr| to reach |mp->max_strings|;
1229 |do_compaction| is responsible for making sure of this.
1230
1231 @<Declarations@>=
1232 @<Declare the procedure called |do_compaction|@>;
1233 @<Declare the procedure called |unit_str_room|@>;
1234 str_number mp_make_string (MP mp);
1235
1236 @ @c 
1237 str_number mp_make_string (MP mp) { /* current string enters the pool */
1238   str_number s; /* the new string */
1239 RESTART: 
1240   s=mp->str_ptr;
1241   mp->str_ptr=mp->next_str[s];
1242   if ( mp->str_ptr>mp->max_str_ptr ) {
1243     if ( mp->str_ptr==mp->max_strings ) { 
1244       mp->str_ptr=s;
1245       mp_do_compaction(mp, 0);
1246       goto RESTART;
1247     } else {
1248 #ifdef DEBUG 
1249       if ( mp->strs_used_up!=mp->max_str_ptr ) mp_confusion(mp, "s");
1250 @:this can't happen s}{\quad \.s@>
1251 #endif
1252       mp->max_str_ptr=mp->str_ptr;
1253       mp->next_str[mp->str_ptr]=mp->max_str_ptr+1;
1254     }
1255   }
1256   mp->str_ref[s]=1;
1257   mp->str_start[mp->str_ptr]=mp->pool_ptr;
1258   incr(mp->strs_used_up);
1259   incr(mp->strs_in_use);
1260   mp->pool_in_use=mp->pool_in_use+length(s);
1261   if ( mp->pool_in_use>mp->max_pl_used ) 
1262     mp->max_pl_used=mp->pool_in_use;
1263   if ( mp->strs_in_use>mp->max_strs_used ) 
1264     mp->max_strs_used=mp->strs_in_use;
1265   return s;
1266 }
1267
1268 @ The most interesting string operation is string pool compaction.  The idea
1269 is to recover unused space in the |str_pool| array by recopying the strings
1270 to close the gaps created when some strings become unused.  All string
1271 numbers~$k$ where |str_ref[k]=0| are to be linked into the list of free string
1272 numbers after |str_ptr|.  If this fails to free enough pool space we issue an
1273 |overflow| error unless |needed=mp->pool_size|.  Calling |do_compaction|
1274 with |needed=mp->pool_size| supresses all overflow tests.
1275
1276 The compaction process starts with |last_fixed_str| because all lower numbered
1277 strings are permanently allocated with |max_str_ref| in their |str_ref| entries.
1278
1279 @<Glob...@>=
1280 str_number last_fixed_str; /* last permanently allocated string */
1281 str_number fixed_str_use; /* number of permanently allocated strings */
1282
1283 @ @<Declare the procedure called |do_compaction|@>=
1284 void mp_do_compaction (MP mp, pool_pointer needed) ;
1285
1286 @ @c
1287 void mp_do_compaction (MP mp, pool_pointer needed) {
1288   str_number str_use; /* a count of strings in use */
1289   str_number r,s,t; /* strings being manipulated */
1290   pool_pointer p,q; /* destination and source for copying string characters */
1291   @<Advance |last_fixed_str| as far as possible and set |str_use|@>;
1292   r=mp->last_fixed_str;
1293   s=mp->next_str[r];
1294   p=mp->str_start[s];
1295   while ( s!=mp->str_ptr ) { 
1296     while ( mp->str_ref[s]==0 ) {
1297       @<Advance |s| and add the old |s| to the list of free string numbers;
1298         then |break| if |s=str_ptr|@>;
1299     }
1300     r=s; s=mp->next_str[s];
1301     incr(str_use);
1302     @<Move string |r| back so that |str_start[r]=p|; make |p| the location
1303      after the end of the string@>;
1304   }
1305   @<Move the current string back so that it starts at |p|@>;
1306   if ( needed<mp->pool_size ) {
1307     @<Make sure that there is room for another string with |needed| characters@>;
1308   }
1309   @<Account for the compaction and make sure the statistics agree with the
1310      global versions@>;
1311   mp->strs_used_up=str_use;
1312 }
1313
1314 @ @<Advance |last_fixed_str| as far as possible and set |str_use|@>=
1315 t=mp->next_str[mp->last_fixed_str];
1316 while (t!=mp->str_ptr && mp->str_ref[t]==max_str_ref) {
1317   incr(mp->fixed_str_use);
1318   mp->last_fixed_str=t;
1319   t=mp->next_str[t];
1320 }
1321 str_use=mp->fixed_str_use
1322
1323 @ Because of the way |flush_string| has been written, it should never be
1324 necessary to |break| here.  The extra line of code seems worthwhile to
1325 preserve the generality of |do_compaction|.
1326
1327 @<Advance |s| and add the old |s| to the list of free string numbers;...@>=
1328 {
1329 t=s;
1330 s=mp->next_str[s];
1331 mp->next_str[r]=s;
1332 mp->next_str[t]=mp->next_str[mp->str_ptr];
1333 mp->next_str[mp->str_ptr]=t;
1334 if ( s==mp->str_ptr ) break;
1335 }
1336
1337 @ The string currently starts at |str_start[r]| and ends just before
1338 |str_start[s]|.  We don't change |str_start[s]| because it might be needed
1339 to locate the next string.
1340
1341 @<Move string |r| back so that |str_start[r]=p|; make |p| the location...@>=
1342 q=mp->str_start[r];
1343 mp->str_start[r]=p;
1344 while ( q<mp->str_start[s] ) { 
1345   mp->str_pool[p]=mp->str_pool[q];
1346   incr(p); incr(q);
1347 }
1348
1349 @ Pointers |str_start[str_ptr]| and |pool_ptr| have not been updated.  When
1350 we do this, anything between them should be moved.
1351
1352 @ @<Move the current string back so that it starts at |p|@>=
1353 q=mp->str_start[mp->str_ptr];
1354 mp->str_start[mp->str_ptr]=p;
1355 while ( q<mp->pool_ptr ) { 
1356   mp->str_pool[p]=mp->str_pool[q];
1357   incr(p); incr(q);
1358 }
1359 mp->pool_ptr=p
1360
1361 @ We must remember that |str_ptr| is not allowed to reach |mp->max_strings|.
1362
1363 @<Make sure that there is room for another string with |needed| char...@>=
1364 if ( str_use>=mp->max_strings-1 )
1365   mp_reallocate_strings (mp,str_use);
1366 if ( mp->pool_ptr+needed>mp->max_pool_ptr ) {
1367   mp_reallocate_pool(mp, mp->pool_ptr+needed);
1368   mp->max_pool_ptr=mp->pool_ptr+needed;
1369 }
1370
1371 @ @<Declarations@>=
1372 void mp_reallocate_strings (MP mp, str_number str_use) ;
1373 void mp_reallocate_pool(MP mp, pool_pointer needed) ;
1374
1375 @ @c 
1376 void mp_reallocate_strings (MP mp, str_number str_use) { 
1377   while ( str_use>=mp->max_strings-1 ) {
1378     int l = mp->max_strings + (mp->max_strings>>2);
1379     XREALLOC (mp->str_ref,   l, int);
1380     XREALLOC (mp->str_start, l, pool_pointer);
1381     XREALLOC (mp->next_str,  l, str_number);
1382     mp->max_strings = l;
1383   }
1384 }
1385 void mp_reallocate_pool(MP mp, pool_pointer needed) {
1386   while ( needed>mp->pool_size ) {
1387     int l = mp->pool_size + (mp->pool_size>>2);
1388         XREALLOC (mp->str_pool, l, ASCII_code);
1389     mp->pool_size = l;
1390   }
1391 }
1392
1393 @ @<Account for the compaction and make sure the statistics agree with...@>=
1394 if ( (mp->str_start[mp->str_ptr]!=mp->pool_in_use)||(str_use!=mp->strs_in_use) )
1395   mp_confusion(mp, "string");
1396 @:this can't happen string}{\quad string@>
1397 incr(mp->pact_count);
1398 mp->pact_chars=mp->pact_chars+mp->pool_ptr-str_stop(mp->last_fixed_str);
1399 mp->pact_strs=mp->pact_strs+str_use-mp->fixed_str_use;
1400 #ifdef DEBUG
1401 s=mp->str_ptr; t=str_use;
1402 while ( s<=mp->max_str_ptr ){
1403   if ( t>mp->max_str_ptr ) mp_confusion(mp, "\"");
1404   incr(t); s=mp->next_str[s];
1405 };
1406 if ( t<=mp->max_str_ptr ) mp_confusion(mp, "\"");
1407 #endif
1408
1409 @ A few more global variables are needed to keep track of statistics when
1410 |stat| $\ldots$ |tats| blocks are not commented out.
1411
1412 @<Glob...@>=
1413 integer pact_count; /* number of string pool compactions so far */
1414 integer pact_chars; /* total number of characters moved during compactions */
1415 integer pact_strs; /* total number of strings moved during compactions */
1416
1417 @ @<Initialize compaction statistics@>=
1418 mp->pact_count=0;
1419 mp->pact_chars=0;
1420 mp->pact_strs=0;
1421
1422 @ The following subroutine compares string |s| with another string of the
1423 same length that appears in |buffer| starting at position |k|;
1424 the result is |true| if and only if the strings are equal.
1425
1426 @c 
1427 boolean mp_str_eq_buf (MP mp,str_number s, integer k) {
1428   /* test equality of strings */
1429   pool_pointer j; /* running index */
1430   j=mp->str_start[s];
1431   while ( j<str_stop(s) ) { 
1432     if ( mp->str_pool[j++]!=mp->buffer[k++] ) 
1433       return false;
1434   }
1435   return true;
1436 }
1437
1438 @ Here is a similar routine, but it compares two strings in the string pool,
1439 and it does not assume that they have the same length. If the first string
1440 is lexicographically greater than, less than, or equal to the second,
1441 the result is respectively positive, negative, or zero.
1442
1443 @c 
1444 integer mp_str_vs_str (MP mp, str_number s, str_number t) {
1445   /* test equality of strings */
1446   pool_pointer j,k; /* running indices */
1447   integer ls,lt; /* lengths */
1448   integer l; /* length remaining to test */
1449   ls=length(s); lt=length(t);
1450   if ( ls<=lt ) l=ls; else l=lt;
1451   j=mp->str_start[s]; k=mp->str_start[t];
1452   while ( l-->0 ) { 
1453     if ( mp->str_pool[j]!=mp->str_pool[k] ) {
1454        return (mp->str_pool[j]-mp->str_pool[k]); 
1455     }
1456     incr(j); incr(k);
1457   }
1458   return (ls-lt);
1459 }
1460
1461 @ The initial values of |str_pool|, |str_start|, |pool_ptr|,
1462 and |str_ptr| are computed by the \.{INIMP} program, based in part
1463 on the information that \.{WEB} has output while processing \MP.
1464 @.INIMP@>
1465 @^string pool@>
1466
1467 @c 
1468 void mp_get_strings_started (MP mp) { 
1469   /* initializes the string pool,
1470     but returns |false| if something goes wrong */
1471   int k; /* small indices or counters */
1472   str_number g; /* a new string */
1473   mp->pool_ptr=0; mp->str_ptr=0; mp->max_pool_ptr=0; mp->max_str_ptr=0;
1474   mp->str_start[0]=0;
1475   mp->next_str[0]=1;
1476   mp->pool_in_use=0; mp->strs_in_use=0;
1477   mp->max_pl_used=0; mp->max_strs_used=0;
1478   @<Initialize compaction statistics@>;
1479   mp->strs_used_up=0;
1480   @<Make the first 256 strings@>;
1481   g=mp_make_string(mp); /* string 256 == "" */
1482   mp->str_ref[g]=max_str_ref;
1483   mp->last_fixed_str=mp->str_ptr-1;
1484   mp->fixed_str_use=mp->str_ptr;
1485   return;
1486 }
1487
1488 @ @<Declarations@>=
1489 void mp_get_strings_started (MP mp);
1490
1491 @ The first 256 strings will consist of a single character only.
1492
1493 @<Make the first 256...@>=
1494 for (k=0;k<=255;k++) { 
1495   append_char(k);
1496   g=mp_make_string(mp); 
1497   mp->str_ref[g]=max_str_ref;
1498 }
1499
1500 @ The first 128 strings will contain 95 standard ASCII characters, and the
1501 other 33 characters will be printed in three-symbol form like `\.{\^\^A}'
1502 unless a system-dependent change is made here. Installations that have
1503 an extended character set, where for example |xchr[032]=@t\.{'^^Z'}@>|,
1504 would like string 032 to be printed as the single character 032 instead
1505 of the three characters 0136, 0136, 0132 (\.{\^\^Z}). On the other hand,
1506 even people with an extended character set will want to represent string
1507 015 by \.{\^\^M}, since 015 is ASCII's ``carriage return'' code; the idea is
1508 to produce visible strings instead of tabs or line-feeds or carriage-returns
1509 or bell-rings or characters that are treated anomalously in text files.
1510
1511 Unprintable characters of codes 128--255 are, similarly, rendered
1512 \.{\^\^80}--\.{\^\^ff}.
1513
1514 The boolean expression defined here should be |true| unless \MP\ internal
1515 code number~|k| corresponds to a non-troublesome visible symbol in the
1516 local character set.
1517 If character |k| cannot be printed, and |k<0200|, then character |k+0100| or
1518 |k-0100| must be printable; moreover, ASCII codes |[060..071, 0141..0146]|
1519 must be printable.
1520 @^character set dependencies@>
1521 @^system dependencies@>
1522
1523 @<Character |k| cannot be printed@>=
1524   (k<' ')||(k>'~')
1525
1526 @* \[5] On-line and off-line printing.
1527 Messages that are sent to a user's terminal and to the transcript-log file
1528 are produced by several `|print|' procedures. These procedures will
1529 direct their output to a variety of places, based on the setting of
1530 the global variable |selector|, which has the following possible
1531 values:
1532
1533 \yskip
1534 \hang |term_and_log|, the normal setting, prints on the terminal and on the
1535   transcript file.
1536
1537 \hang |log_only|, prints only on the transcript file.
1538
1539 \hang |term_only|, prints only on the terminal.
1540
1541 \hang |no_print|, doesn't print at all. This is used only in rare cases
1542   before the transcript file is open.
1543
1544 \hang |pseudo|, puts output into a cyclic buffer that is used
1545   by the |show_context| routine; when we get to that routine we shall discuss
1546   the reasoning behind this curious mode.
1547
1548 \hang |new_string|, appends the output to the current string in the
1549   string pool.
1550
1551 \hang |>=write_file| prints on one of the files used for the \&{write}
1552 @:write_}{\&{write} primitive@>
1553   command.
1554
1555 \yskip
1556 \noindent The symbolic names `|term_and_log|', etc., have been assigned
1557 numeric codes that satisfy the convenient relations |no_print+1=term_only|,
1558 |no_print+2=log_only|, |term_only+2=log_only+1=term_and_log|.  These
1559 relations are not used when |selector| could be |pseudo|, or |new_string|.
1560 We need not check for unprintable characters when |selector<pseudo|.
1561
1562 Three additional global variables, |tally|, |term_offset| and |file_offset|
1563 record the number of characters that have been printed
1564 since they were most recently cleared to zero. We use |tally| to record
1565 the length of (possibly very long) stretches of printing; |term_offset|,
1566 and |file_offset|, on the other hand, keep track of how many
1567 characters have appeared so far on the current line that has been output
1568 to the terminal, the transcript file, or the \ps\ output file, respectively.
1569
1570 @d new_string 0 /* printing is deflected to the string pool */
1571 @d pseudo 2 /* special |selector| setting for |show_context| */
1572 @d no_print 3 /* |selector| setting that makes data disappear */
1573 @d term_only 4 /* printing is destined for the terminal only */
1574 @d log_only 5 /* printing is destined for the transcript file only */
1575 @d term_and_log 6 /* normal |selector| setting */
1576 @d write_file 7 /* first write file selector */
1577
1578 @<Glob...@>=
1579 void * log_file; /* transcript of \MP\ session */
1580 void * ps_file; /* the generic font output goes here */
1581 unsigned int selector; /* where to print a message */
1582 unsigned char dig[23]; /* digits in a number being output */
1583 integer tally; /* the number of characters recently printed */
1584 unsigned int term_offset;
1585   /* the number of characters on the current terminal line */
1586 unsigned int file_offset;
1587   /* the number of characters on the current file line */
1588 ASCII_code *trick_buf; /* circular buffer for pseudoprinting */
1589 integer trick_count; /* threshold for pseudoprinting, explained later */
1590 integer first_count; /* another variable for pseudoprinting */
1591
1592 @ @<Allocate or initialize ...@>=
1593 memset(mp->dig,0,23);
1594 mp->trick_buf = xmalloc((mp->error_line+1),sizeof(ASCII_code));
1595
1596 @ @<Dealloc variables@>=
1597 xfree(mp->trick_buf);
1598
1599 @ @<Initialize the output routines@>=
1600 mp->selector=term_only; mp->tally=0; mp->term_offset=0; mp->file_offset=0; 
1601
1602 @ Macro abbreviations for output to the terminal and to the log file are
1603 defined here for convenience. Some systems need special conventions
1604 for terminal output, and it is possible to adhere to those conventions
1605 by changing |wterm|, |wterm_ln|, and |wterm_cr| here.
1606 @^system dependencies@>
1607
1608 @d do_fprintf(f,b) (mp->write_ascii_file)(f,b)
1609 @d wterm(A)     do_fprintf(mp->term_out,(A))
1610 @d wterm_chr(A) { unsigned char ss[2]; ss[0]=(A); ss[1]=0; do_fprintf(mp->term_out,(char *)ss); }
1611 @d wterm_cr     do_fprintf(mp->term_out,"\n")
1612 @d wterm_ln(A)  { wterm_cr; do_fprintf(mp->term_out,(A)); }
1613 @d wlog(A)      do_fprintf(mp->log_file,(A))
1614 @d wlog_chr(A)  { unsigned char ss[2]; ss[0]=(A); ss[1]=0; do_fprintf(mp->log_file,(char *)ss); }
1615 @d wlog_cr      do_fprintf(mp->log_file, "\n")
1616 @d wlog_ln(A)   {wlog_cr; do_fprintf(mp->log_file,(A)); }
1617
1618
1619 @ To end a line of text output, we call |print_ln|.  Cases |0..max_write_files|
1620 use an array |wr_file| that will be declared later.
1621
1622 @d mp_print_text(A) mp_print_str(mp,text((A)))
1623
1624 @<Internal ...@>=
1625 void mp_print_ln (MP mp);
1626 void mp_print_visible_char (MP mp, ASCII_code s); 
1627 void mp_print_char (MP mp, ASCII_code k);
1628 void mp_print (MP mp, char *s);
1629 void mp_print_str (MP mp, str_number s);
1630 void mp_print_nl (MP mp, char *s);
1631 void mp_print_two (MP mp,scaled x, scaled y) ;
1632 void mp_print_scaled (MP mp,scaled s);
1633
1634 @ @<Basic print...@>=
1635 void mp_print_ln (MP mp) { /* prints an end-of-line */
1636  switch (mp->selector) {
1637   case term_and_log: 
1638     wterm_cr; wlog_cr;
1639     mp->term_offset=0;  mp->file_offset=0;
1640     break;
1641   case log_only: 
1642     wlog_cr; mp->file_offset=0;
1643     break;
1644   case term_only: 
1645     wterm_cr; mp->term_offset=0;
1646     break;
1647   case no_print:
1648   case pseudo: 
1649   case new_string: 
1650     break;
1651   default: 
1652     do_fprintf(mp->wr_file[(mp->selector-write_file)],"\n");
1653   }
1654 } /* note that |tally| is not affected */
1655
1656 @ The |print_visible_char| procedure sends one character to the desired
1657 destination, using the |xchr| array to map it into an external character
1658 compatible with |input_ln|.  (It assumes that it is always called with
1659 a visible ASCII character.)  All printing comes through |print_ln| or
1660 |print_char|, which ultimately calls |print_visible_char|, hence these
1661 routines are the ones that limit lines to at most |max_print_line| characters.
1662 But we must make an exception for the \ps\ output file since it is not safe
1663 to cut up lines arbitrarily in \ps.
1664
1665 Procedure |unit_str_room| needs to be declared |forward| here because it calls
1666 |do_compaction| and |do_compaction| can call the error routines.  Actually,
1667 |unit_str_room| avoids |overflow| errors but it can call |confusion|.
1668
1669 @<Basic printing...@>=
1670 void mp_print_visible_char (MP mp, ASCII_code s) { /* prints a single character */
1671   switch (mp->selector) {
1672   case term_and_log: 
1673     wterm_chr(xchr(s)); wlog_chr(xchr(s));
1674     incr(mp->term_offset); incr(mp->file_offset);
1675     if ( mp->term_offset==(unsigned)mp->max_print_line ) { 
1676        wterm_cr; mp->term_offset=0;
1677     };
1678     if ( mp->file_offset==(unsigned)mp->max_print_line ) { 
1679        wlog_cr; mp->file_offset=0;
1680     };
1681     break;
1682   case log_only: 
1683     wlog_chr(xchr(s)); incr(mp->file_offset);
1684     if ( mp->file_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1685     break;
1686   case term_only: 
1687     wterm_chr(xchr(s)); incr(mp->term_offset);
1688     if ( mp->term_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1689     break;
1690   case no_print: 
1691     break;
1692   case pseudo: 
1693     if ( mp->tally<mp->trick_count ) 
1694       mp->trick_buf[mp->tally % mp->error_line]=s;
1695     break;
1696   case new_string: 
1697     if ( mp->pool_ptr>=mp->max_pool_ptr ) { 
1698       mp_unit_str_room(mp);
1699       if ( mp->pool_ptr>=mp->pool_size ) 
1700         goto DONE; /* drop characters if string space is full */
1701     };
1702     append_char(s);
1703     break;
1704   default:
1705     { char ss[2]; ss[0] = xchr(s); ss[1]=0;
1706       do_fprintf(mp->wr_file[(mp->selector-write_file)],(char *)ss);
1707     }
1708   }
1709 DONE:
1710   incr(mp->tally);
1711 }
1712
1713 @ The |print_char| procedure sends one character to the desired destination.
1714 File names and string expressions might contain |ASCII_code| values that
1715 can't be printed using |print_visible_char|.  These characters will be
1716 printed in three- or four-symbol form like `\.{\^\^A}' or `\.{\^\^e4}'.
1717 (This procedure assumes that it is safe to bypass all checks for unprintable
1718 characters when |selector| is in the range |0..max_write_files-1|.
1719 The user might want to write unprintable characters.
1720
1721 @d print_lc_hex(A) do { l=(A);
1722     mp_print_visible_char(mp, (l<10 ? l+'0' : l-10+'a'));
1723   } while (0)
1724
1725 @<Basic printing...@>=
1726 void mp_print_char (MP mp, ASCII_code k) { /* prints a single character */
1727   int l; /* small index or counter */
1728   if ( mp->selector<pseudo || mp->selector>=write_file) {
1729     mp_print_visible_char(mp, k);
1730   } else if ( @<Character |k| cannot be printed@> ) { 
1731     mp_print(mp, "^^"); 
1732     if ( k<0100 ) { 
1733       mp_print_visible_char(mp, k+0100); 
1734     } else if ( k<0200 ) { 
1735       mp_print_visible_char(mp, k-0100); 
1736     } else { 
1737       print_lc_hex(k / 16);  
1738       print_lc_hex(k % 16); 
1739     }
1740   } else {
1741     mp_print_visible_char(mp, k);
1742   }
1743 };
1744
1745 @ An entire string is output by calling |print|. Note that if we are outputting
1746 the single standard ASCII character \.c, we could call |print("c")|, since
1747 |"c"=99| is the number of a single-character string, as explained above. But
1748 |print_char("c")| is quicker, so \MP\ goes directly to the |print_char|
1749 routine when it knows that this is safe. (The present implementation
1750 assumes that it is always safe to print a visible ASCII character.)
1751 @^system dependencies@>
1752
1753 @<Basic print...@>=
1754 void mp_do_print (MP mp, char *ss, unsigned int len) { /* prints string |s| */
1755   unsigned int j = 0;
1756   while ( j<len ){ 
1757     mp_print_char(mp, ss[j]); incr(j);
1758   }
1759 }
1760
1761
1762 @<Basic print...@>=
1763 void mp_print (MP mp, char *ss) {
1764   mp_do_print(mp, ss, strlen(ss));
1765 }
1766 void mp_print_str (MP mp, str_number s) {
1767   pool_pointer j; /* current character code position */
1768   if ( (s<0)||(s>mp->max_str_ptr) ) {
1769      mp_do_print(mp,"???",3); /* this can't happen */
1770 @.???@>
1771   }
1772   j=mp->str_start[s];
1773   mp_do_print(mp, (char *)(mp->str_pool+j), (str_stop(s)-j));
1774 }
1775
1776
1777 @ Here is the very first thing that \MP\ prints: a headline that identifies
1778 the version number and base name. The |term_offset| variable is temporarily
1779 incorrect, but the discrepancy is not serious since we assume that the banner
1780 and mem identifier together will occupy at most |max_print_line|
1781 character positions.
1782
1783 @<Initialize the output...@>=
1784 wterm (banner);
1785 wterm (version_string);
1786 if (mp->mem_ident!=NULL) 
1787   mp_print(mp,mp->mem_ident); 
1788 mp_print_ln(mp);
1789 update_terminal;
1790
1791 @ The procedure |print_nl| is like |print|, but it makes sure that the
1792 string appears at the beginning of a new line.
1793
1794 @<Basic print...@>=
1795 void mp_print_nl (MP mp, char *s) { /* prints string |s| at beginning of line */
1796   switch(mp->selector) {
1797   case term_and_log: 
1798     if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_ln(mp);
1799     break;
1800   case log_only: 
1801     if ( mp->file_offset>0 ) mp_print_ln(mp);
1802     break;
1803   case term_only: 
1804     if ( mp->term_offset>0 ) mp_print_ln(mp);
1805     break;
1806   case no_print:
1807   case pseudo:
1808   case new_string: 
1809         break;
1810   } /* there are no other cases */
1811   mp_print(mp, s);
1812 }
1813
1814 @ An array of digits in the range |0..9| is printed by |print_the_digs|.
1815
1816 @<Basic print...@>=
1817 void mp_print_the_digs (MP mp, eight_bits k) {
1818   /* prints |dig[k-1]|$\,\ldots\,$|dig[0]| */
1819   while ( k>0 ){ 
1820     decr(k); mp_print_char(mp, '0'+mp->dig[k]);
1821   }
1822 };
1823
1824 @ The following procedure, which prints out the decimal representation of a
1825 given integer |n|, has been written carefully so that it works properly
1826 if |n=0| or if |(-n)| would cause overflow. It does not apply |%| or |/|
1827 to negative arguments, since such operations are not implemented consistently
1828 on all platforms.
1829
1830 @<Basic print...@>=
1831 void mp_print_int (MP mp,integer n) { /* prints an integer in decimal form */
1832   integer m; /* used to negate |n| in possibly dangerous cases */
1833   int k = 0; /* index to current digit; we assume that $|n|<10^{23}$ */
1834   if ( n<0 ) { 
1835     mp_print_char(mp, '-');
1836     if ( n>-100000000 ) {
1837           negate(n);
1838     } else  { 
1839           m=-1-n; n=m / 10; m=(m % 10)+1; k=1;
1840       if ( m<10 ) {
1841         mp->dig[0]=m;
1842       } else { 
1843         mp->dig[0]=0; incr(n);
1844       }
1845     }
1846   }
1847   do {  
1848     mp->dig[k]=n % 10; n=n / 10; incr(k);
1849   } while (n!=0);
1850   mp_print_the_digs(mp, k);
1851 };
1852
1853 @ @<Internal ...@>=
1854 void mp_print_int (MP mp,integer n);
1855
1856 @ \MP\ also makes use of a trivial procedure to print two digits. The
1857 following subroutine is usually called with a parameter in the range |0<=n<=99|.
1858
1859 @c 
1860 void mp_print_dd (MP mp,integer n) { /* prints two least significant digits */
1861   n=abs(n) % 100; 
1862   mp_print_char(mp, '0'+(n / 10));
1863   mp_print_char(mp, '0'+(n % 10));
1864 }
1865
1866
1867 @ @<Internal ...@>=
1868 void mp_print_dd (MP mp,integer n);
1869
1870 @ Here is a procedure that asks the user to type a line of input,
1871 assuming that the |selector| setting is either |term_only| or |term_and_log|.
1872 The input is placed into locations |first| through |last-1| of the
1873 |buffer| array, and echoed on the transcript file if appropriate.
1874
1875 This procedure is never called when |interaction<mp_scroll_mode|.
1876
1877 @d prompt_input(A) do { 
1878     if (!mp->noninteractive) {
1879       wake_up_terminal; mp_print(mp, (A)); 
1880     }
1881     mp_term_input(mp);
1882   } while (0) /* prints a string and gets a line of input */
1883
1884 @c 
1885 void mp_term_input (MP mp) { /* gets a line from the terminal */
1886   size_t k; /* index into |buffer| */
1887   update_terminal; /* Now the user sees the prompt for sure */
1888   if (!mp_input_ln(mp, mp->term_in )) {
1889     if (!mp->noninteractive) {
1890           mp_fatal_error(mp, "End of file on the terminal!");
1891 @.End of file on the terminal@>
1892     } else { /* we are done with this input chunk */
1893           longjmp(mp->jump_buf,1);      
1894     }
1895   }
1896   if (!mp->noninteractive) {
1897     mp->term_offset=0; /* the user's line ended with \<\rm return> */
1898     decr(mp->selector); /* prepare to echo the input */
1899     if ( mp->last!=mp->first ) {
1900       for (k=mp->first;k<=mp->last-1;k++) {
1901         mp_print_char(mp, mp->buffer[k]);
1902       }
1903     }
1904     mp_print_ln(mp); 
1905     mp->buffer[mp->last]='%'; 
1906     incr(mp->selector); /* restore previous status */
1907   }
1908 }
1909
1910 @* \[6] Reporting errors.
1911 When something anomalous is detected, \MP\ typically does something like this:
1912 $$\vbox{\halign{#\hfil\cr
1913 |print_err("Something anomalous has been detected");|\cr
1914 |help3("This is the first line of my offer to help.")|\cr
1915 |("This is the second line. I'm trying to")|\cr
1916 |("explain the best way for you to proceed.");|\cr
1917 |error;|\cr}}$$
1918 A two-line help message would be given using |help2|, etc.; these informal
1919 helps should use simple vocabulary that complements the words used in the
1920 official error message that was printed. (Outside the U.S.A., the help
1921 messages should preferably be translated into the local vernacular. Each
1922 line of help is at most 60 characters long, in the present implementation,
1923 so that |max_print_line| will not be exceeded.)
1924
1925 The |print_err| procedure supplies a `\.!' before the official message,
1926 and makes sure that the terminal is awake if a stop is going to occur.
1927 The |error| procedure supplies a `\..' after the official message, then it
1928 shows the location of the error; and if |interaction=error_stop_mode|,
1929 it also enters into a dialog with the user, during which time the help
1930 message may be printed.
1931 @^system dependencies@>
1932
1933 @ The global variable |interaction| has four settings, representing increasing
1934 amounts of user interaction:
1935
1936 @<Exported types@>=
1937 enum mp_interaction_mode { 
1938  mp_unspecified_mode=0, /* extra value for command-line switch */
1939  mp_batch_mode, /* omits all stops and omits terminal output */
1940  mp_nonstop_mode, /* omits all stops */
1941  mp_scroll_mode, /* omits error stops */
1942  mp_error_stop_mode, /* stops at every opportunity to interact */
1943 };
1944
1945 @ @<Option variables@>=
1946 int interaction; /* current level of interaction */
1947 int noninteractive; /* do we have a terminal? */
1948
1949 @ Set it here so it can be overwritten by the commandline
1950
1951 @<Allocate or initialize ...@>=
1952 mp->interaction=opt->interaction;
1953 if (mp->interaction==mp_unspecified_mode || mp->interaction>mp_error_stop_mode) 
1954   mp->interaction=mp_error_stop_mode;
1955 if (mp->interaction<mp_unspecified_mode) 
1956   mp->interaction=mp_batch_mode;
1957 mp->noninteractive=opt->noninteractive;
1958
1959
1960
1961 @d print_err(A) mp_print_err(mp,(A))
1962
1963 @<Internal ...@>=
1964 void mp_print_err(MP mp, char * A);
1965
1966 @ @c
1967 void mp_print_err(MP mp, char * A) { 
1968   if ( mp->interaction==mp_error_stop_mode ) 
1969     wake_up_terminal;
1970   mp_print_nl(mp, "! "); 
1971   mp_print(mp, A);
1972 @.!\relax@>
1973 }
1974
1975
1976 @ \MP\ is careful not to call |error| when the print |selector| setting
1977 might be unusual. The only possible values of |selector| at the time of
1978 error messages are
1979
1980 \yskip\hang|no_print| (when |interaction=mp_batch_mode|
1981   and |log_file| not yet open);
1982
1983 \hang|term_only| (when |interaction>mp_batch_mode| and |log_file| not yet open);
1984
1985 \hang|log_only| (when |interaction=mp_batch_mode| and |log_file| is open);
1986
1987 \hang|term_and_log| (when |interaction>mp_batch_mode| and |log_file| is open).
1988
1989 @<Initialize the print |selector| based on |interaction|@>=
1990 if ( mp->interaction==mp_batch_mode ) mp->selector=no_print; else mp->selector=term_only
1991
1992 @ A global variable |deletions_allowed| is set |false| if the |get_next|
1993 routine is active when |error| is called; this ensures that |get_next|
1994 will never be called recursively.
1995 @^recursion@>
1996
1997 The global variable |history| records the worst level of error that
1998 has been detected. It has four possible values: |spotless|, |warning_issued|,
1999 |error_message_issued|, and |fatal_error_stop|.
2000
2001 Another global variable, |error_count|, is increased by one when an
2002 |error| occurs without an interactive dialog, and it is reset to zero at
2003 the end of every statement.  If |error_count| reaches 100, \MP\ decides
2004 that there is no point in continuing further.
2005
2006 @<Types...@>=
2007 enum mp_history_states {
2008   mp_spotless=0, /* |history| value when nothing has been amiss yet */
2009   mp_warning_issued, /* |history| value when |begin_diagnostic| has been called */
2010   mp_error_message_issued, /* |history| value when |error| has been called */
2011   mp_fatal_error_stop, /* |history| value when termination was premature */
2012 };
2013
2014 @ @<Glob...@>=
2015 boolean deletions_allowed; /* is it safe for |error| to call |get_next|? */
2016 int history; /* has the source input been clean so far? */
2017 int error_count; /* the number of scrolled errors since the last statement ended */
2018
2019 @ The value of |history| is initially |fatal_error_stop|, but it will
2020 be changed to |spotless| if \MP\ survives the initialization process.
2021
2022 @<Allocate or ...@>=
2023 mp->deletions_allowed=true; mp->error_count=0; /* |history| is initialized elsewhere */
2024
2025 @ Since errors can be detected almost anywhere in \MP, we want to declare the
2026 error procedures near the beginning of the program. But the error procedures
2027 in turn use some other procedures, which need to be declared |forward|
2028 before we get to |error| itself.
2029
2030 It is possible for |error| to be called recursively if some error arises
2031 when |get_next| is being used to delete a token, and/or if some fatal error
2032 occurs while \MP\ is trying to fix a non-fatal one. But such recursion
2033 @^recursion@>
2034 is never more than two levels deep.
2035
2036 @<Declarations@>=
2037 void mp_get_next (MP mp);
2038 void mp_term_input (MP mp);
2039 void mp_show_context (MP mp);
2040 void mp_begin_file_reading (MP mp);
2041 void mp_open_log_file (MP mp);
2042 void mp_clear_for_error_prompt (MP mp);
2043 void mp_debug_help (MP mp);
2044 @<Declare the procedure called |flush_string|@>
2045
2046 @ @<Internal ...@>=
2047 void mp_normalize_selector (MP mp);
2048
2049 @ Individual lines of help are recorded in the array |help_line|, which
2050 contains entries in positions |0..(help_ptr-1)|. They should be printed
2051 in reverse order, i.e., with |help_line[0]| appearing last.
2052
2053 @d hlp1(A) mp->help_line[0]=(A); }
2054 @d hlp2(A) mp->help_line[1]=(A); hlp1
2055 @d hlp3(A) mp->help_line[2]=(A); hlp2
2056 @d hlp4(A) mp->help_line[3]=(A); hlp3
2057 @d hlp5(A) mp->help_line[4]=(A); hlp4
2058 @d hlp6(A) mp->help_line[5]=(A); hlp5
2059 @d help0 mp->help_ptr=0 /* sometimes there might be no help */
2060 @d help1  { mp->help_ptr=1; hlp1 /* use this with one help line */
2061 @d help2  { mp->help_ptr=2; hlp2 /* use this with two help lines */
2062 @d help3  { mp->help_ptr=3; hlp3 /* use this with three help lines */
2063 @d help4  { mp->help_ptr=4; hlp4 /* use this with four help lines */
2064 @d help5  { mp->help_ptr=5; hlp5 /* use this with five help lines */
2065 @d help6  { mp->help_ptr=6; hlp6 /* use this with six help lines */
2066
2067 @<Glob...@>=
2068 char * help_line[6]; /* helps for the next |error| */
2069 unsigned int help_ptr; /* the number of help lines present */
2070 boolean use_err_help; /* should the |err_help| string be shown? */
2071 str_number err_help; /* a string set up by \&{errhelp} */
2072 str_number filename_template; /* a string set up by \&{filenametemplate} */
2073
2074 @ @<Allocate or ...@>=
2075 mp->help_ptr=0; mp->use_err_help=false; mp->err_help=0; mp->filename_template=0;
2076
2077 @ The |jump_out| procedure just cuts across all active procedure levels and
2078 goes to |end_of_MP|. This is the only nonlocal |goto| statement in the
2079 whole program. It is used when there is no recovery from a particular error.
2080
2081 The program uses a |jump_buf| to handle this, this is initialized at three
2082 spots: the start of |mp_new|, the start of |mp_initialize|, and the start 
2083 of |mp_run|. Those are the only library enty points.
2084
2085 @^system dependencies@>
2086
2087 @<Glob...@>=
2088 jmp_buf jump_buf;
2089
2090 @ @<Install and test the non-local jump buffer@>=
2091 if (setjmp(mp->jump_buf) != 0) { return mp->history; }
2092
2093
2094 @ @<Setup the non-local jump buffer in |mp_new|@>=
2095 if (setjmp(mp->jump_buf) != 0) return NULL;
2096
2097 @ If the array of internals is still |NULL| when |jump_out| is called, a
2098 crash occured during initialization, and it is not safe to run the normal
2099 cleanup routine.
2100
2101 @<Error hand...@>=
2102 void mp_jump_out (MP mp) { 
2103   if(mp->internal!=NULL)
2104     mp_close_files_and_terminate(mp);
2105   longjmp(mp->jump_buf,1);
2106 }
2107
2108 @ Here now is the general |error| routine.
2109
2110 @<Error hand...@>=
2111 void mp_error (MP mp) { /* completes the job of error reporting */
2112   ASCII_code c; /* what the user types */
2113   integer s1,s2,s3; /* used to save global variables when deleting tokens */
2114   pool_pointer j; /* character position being printed */
2115   if ( mp->history<mp_error_message_issued ) 
2116         mp->history=mp_error_message_issued;
2117   mp_print_char(mp, '.'); mp_show_context(mp);
2118   if ((!mp->noninteractive) && (mp->interaction==mp_error_stop_mode )) {
2119     @<Get user's advice and |return|@>;
2120   }
2121   incr(mp->error_count);
2122   if ( mp->error_count==100 ) { 
2123     mp_print_nl(mp,"(That makes 100 errors; please try again.)");
2124 @.That makes 100 errors...@>
2125     mp->history=mp_fatal_error_stop; mp_jump_out(mp);
2126   }
2127   @<Put help message on the transcript file@>;
2128 }
2129 void mp_warn (MP mp, char *msg) {
2130   int saved_selector = mp->selector;
2131   mp_normalize_selector(mp);
2132   mp_print_nl(mp,"Warning: ");
2133   mp_print(mp,msg);
2134   mp->selector = saved_selector;
2135 }
2136
2137 @ @<Exported function ...@>=
2138 void mp_error (MP mp);
2139 void mp_warn (MP mp, char *msg);
2140
2141
2142 @ @<Get user's advice...@>=
2143 while (1) { 
2144 CONTINUE:
2145   mp_clear_for_error_prompt(mp); prompt_input("? ");
2146 @.?\relax@>
2147   if ( mp->last==mp->first ) return;
2148   c=mp->buffer[mp->first];
2149   if ( c>='a' ) c=c+'A'-'a'; /* convert to uppercase */
2150   @<Interpret code |c| and |return| if done@>;
2151 }
2152
2153 @ It is desirable to provide an `\.E' option here that gives the user
2154 an easy way to return from \MP\ to the system editor, with the offending
2155 line ready to be edited. But such an extension requires some system
2156 wizardry, so the present implementation simply types out the name of the
2157 file that should be
2158 edited and the relevant line number.
2159 @^system dependencies@>
2160
2161 @<Exported types@>=
2162 typedef void (*mp_run_editor_command)(MP, char *, int);
2163
2164 @ @<Option variables@>=
2165 mp_run_editor_command run_editor;
2166
2167 @ @<Allocate or initialize ...@>=
2168 set_callback_option(run_editor);
2169
2170 @ @<Declarations@>=
2171 void mp_run_editor (MP mp, char *fname, int fline);
2172
2173 @ @c void mp_run_editor (MP mp, char *fname, int fline) {
2174     mp_print_nl(mp, "You want to edit file ");
2175 @.You want to edit file x@>
2176     mp_print(mp, fname);
2177     mp_print(mp, " at line "); 
2178     mp_print_int(mp, fline);
2179     mp->interaction=mp_scroll_mode; 
2180     mp_jump_out(mp);
2181 }
2182
2183
2184 There is a secret `\.D' option available when the debugging routines haven't
2185 been commented~out.
2186 @^debugging@>
2187
2188 @<Interpret code |c| and |return| if done@>=
2189 switch (c) {
2190 case '0': case '1': case '2': case '3': case '4':
2191 case '5': case '6': case '7': case '8': case '9': 
2192   if ( mp->deletions_allowed ) {
2193     @<Delete |c-"0"| tokens and |continue|@>;
2194   }
2195   break;
2196 #ifdef DEBUG
2197 case 'D': 
2198   mp_debug_help(mp); continue; 
2199   break;
2200 #endif
2201 case 'E': 
2202   if ( mp->file_ptr>0 ){ 
2203     (mp->run_editor)(mp, 
2204                      str(mp->input_stack[mp->file_ptr].name_field), 
2205                      mp_true_line(mp));
2206   }
2207   break;
2208 case 'H': 
2209   @<Print the help information and |continue|@>;
2210   break;
2211 case 'I':
2212   @<Introduce new material from the terminal and |return|@>;
2213   break;
2214 case 'Q': case 'R': case 'S':
2215   @<Change the interaction level and |return|@>;
2216   break;
2217 case 'X':
2218   mp->interaction=mp_scroll_mode; mp_jump_out(mp);
2219   break;
2220 default:
2221   break;
2222 }
2223 @<Print the menu of available options@>
2224
2225 @ @<Print the menu...@>=
2226
2227   mp_print(mp, "Type <return> to proceed, S to scroll future error messages,");
2228 @.Type <return> to proceed...@>
2229   mp_print_nl(mp, "R to run without stopping, Q to run quietly,");
2230   mp_print_nl(mp, "I to insert something, ");
2231   if ( mp->file_ptr>0 ) 
2232     mp_print(mp, "E to edit your file,");
2233   if ( mp->deletions_allowed )
2234     mp_print_nl(mp, "1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
2235   mp_print_nl(mp, "H for help, X to quit.");
2236 }
2237
2238 @ Here the author of \MP\ apologizes for making use of the numerical
2239 relation between |"Q"|, |"R"|, |"S"|, and the desired interaction settings
2240 |mp_batch_mode|, |mp_nonstop_mode|, |mp_scroll_mode|.
2241 @^Knuth, Donald Ervin@>
2242
2243 @<Change the interaction...@>=
2244
2245   mp->error_count=0; mp->interaction=mp_batch_mode+c-'Q';
2246   mp_print(mp, "OK, entering ");
2247   switch (c) {
2248   case 'Q': mp_print(mp, "batchmode"); decr(mp->selector); break;
2249   case 'R': mp_print(mp, "nonstopmode"); break;
2250   case 'S': mp_print(mp, "scrollmode"); break;
2251   } /* there are no other cases */
2252   mp_print(mp, "..."); mp_print_ln(mp); update_terminal; return;
2253 }
2254
2255 @ When the following code is executed, |buffer[(first+1)..(last-1)]| may
2256 contain the material inserted by the user; otherwise another prompt will
2257 be given. In order to understand this part of the program fully, you need
2258 to be familiar with \MP's input stacks.
2259
2260 @<Introduce new material...@>=
2261
2262   mp_begin_file_reading(mp); /* enter a new syntactic level for terminal input */
2263   if ( mp->last>mp->first+1 ) { 
2264     loc=mp->first+1; mp->buffer[mp->first]=' ';
2265   } else { 
2266    prompt_input("insert>"); loc=mp->first;
2267 @.insert>@>
2268   };
2269   mp->first=mp->last+1; mp->cur_input.limit_field=mp->last; return;
2270 }
2271
2272 @ We allow deletion of up to 99 tokens at a time.
2273
2274 @<Delete |c-"0"| tokens...@>=
2275
2276   s1=mp->cur_cmd; s2=mp->cur_mod; s3=mp->cur_sym; mp->OK_to_interrupt=false;
2277   if ( (mp->last>mp->first+1) && (mp->buffer[mp->first+1]>='0')&&(mp->buffer[mp->first+1]<='9') )
2278     c=c*10+mp->buffer[mp->first+1]-'0'*11;
2279   else 
2280     c=c-'0';
2281   while ( c>0 ) { 
2282     mp_get_next(mp); /* one-level recursive call of |error| is possible */
2283     @<Decrease the string reference count, if the current token is a string@>;
2284     decr(c);
2285   };
2286   mp->cur_cmd=s1; mp->cur_mod=s2; mp->cur_sym=s3; mp->OK_to_interrupt=true;
2287   help2("I have just deleted some text, as you asked.")
2288        ("You can now delete more, or insert, or whatever.");
2289   mp_show_context(mp); 
2290   goto CONTINUE;
2291 }
2292
2293 @ @<Print the help info...@>=
2294
2295   if ( mp->use_err_help ) { 
2296     @<Print the string |err_help|, possibly on several lines@>;
2297     mp->use_err_help=false;
2298   } else { 
2299     if ( mp->help_ptr==0 ) {
2300       help2("Sorry, I don't know how to help in this situation.")
2301            ("Maybe you should try asking a human?");
2302      }
2303     do { 
2304       decr(mp->help_ptr); mp_print(mp, mp->help_line[mp->help_ptr]); mp_print_ln(mp);
2305     } while (mp->help_ptr!=0);
2306   };
2307   help4("Sorry, I already gave what help I could...")
2308        ("Maybe you should try asking a human?")
2309        ("An error might have occurred before I noticed any problems.")
2310        ("``If all else fails, read the instructions.''");
2311   goto CONTINUE;
2312 }
2313
2314 @ @<Print the string |err_help|, possibly on several lines@>=
2315 j=mp->str_start[mp->err_help];
2316 while ( j<str_stop(mp->err_help) ) { 
2317   if ( mp->str_pool[j]!='%' ) mp_print_str(mp, mp->str_pool[j]);
2318   else if ( j+1==str_stop(mp->err_help) ) mp_print_ln(mp);
2319   else if ( mp->str_pool[j+1]!='%' ) mp_print_ln(mp);
2320   else  { incr(j); mp_print_char(mp, '%'); };
2321   incr(j);
2322 }
2323
2324 @ @<Put help message on the transcript file@>=
2325 if ( mp->interaction>mp_batch_mode ) decr(mp->selector); /* avoid terminal output */
2326 if ( mp->use_err_help ) { 
2327   mp_print_nl(mp, "");
2328   @<Print the string |err_help|, possibly on several lines@>;
2329 } else { 
2330   while ( mp->help_ptr>0 ){ 
2331     decr(mp->help_ptr); mp_print_nl(mp, mp->help_line[mp->help_ptr]);
2332   };
2333 }
2334 mp_print_ln(mp);
2335 if ( mp->interaction>mp_batch_mode ) incr(mp->selector); /* re-enable terminal output */
2336 mp_print_ln(mp)
2337
2338 @ In anomalous cases, the print selector might be in an unknown state;
2339 the following subroutine is called to fix things just enough to keep
2340 running a bit longer.
2341
2342 @c 
2343 void mp_normalize_selector (MP mp) { 
2344   if ( mp->log_opened ) mp->selector=term_and_log;
2345   else mp->selector=term_only;
2346   if ( mp->job_name==NULL ) mp_open_log_file(mp);
2347   if ( mp->interaction==mp_batch_mode ) decr(mp->selector);
2348 }
2349
2350 @ The following procedure prints \MP's last words before dying.
2351
2352 @d succumb { if ( mp->interaction==mp_error_stop_mode )
2353     mp->interaction=mp_scroll_mode; /* no more interaction */
2354   if ( mp->log_opened ) mp_error(mp);
2355   /*| if ( mp->interaction>mp_batch_mode ) mp_debug_help(mp); |*/
2356   mp->history=mp_fatal_error_stop; mp_jump_out(mp); /* irrecoverable error */
2357   }
2358
2359 @<Error hand...@>=
2360 void mp_fatal_error (MP mp, char *s) { /* prints |s|, and that's it */
2361   mp_normalize_selector(mp);
2362   print_err("Emergency stop"); help1(s); succumb;
2363 @.Emergency stop@>
2364 }
2365
2366 @ @<Exported function ...@>=
2367 void mp_fatal_error (MP mp, char *s);
2368
2369
2370 @ Here is the most dreaded error message.
2371
2372 @<Error hand...@>=
2373 void mp_overflow (MP mp, char *s, integer n) { /* stop due to finiteness */
2374   mp_normalize_selector(mp);
2375   print_err("MetaPost capacity exceeded, sorry [");
2376 @.MetaPost capacity exceeded ...@>
2377   mp_print(mp, s); mp_print_char(mp, '='); mp_print_int(mp, n); mp_print_char(mp, ']');
2378   help2("If you really absolutely need more capacity,")
2379        ("you can ask a wizard to enlarge me.");
2380   succumb;
2381 }
2382
2383 @ @<Internal library declarations@>=
2384 void mp_overflow (MP mp, char *s, integer n);
2385
2386 @ The program might sometime run completely amok, at which point there is
2387 no choice but to stop. If no previous error has been detected, that's bad
2388 news; a message is printed that is really intended for the \MP\
2389 maintenance person instead of the user (unless the user has been
2390 particularly diabolical).  The index entries for `this can't happen' may
2391 help to pinpoint the problem.
2392 @^dry rot@>
2393
2394 @<Internal library ...@>=
2395 void mp_confusion (MP mp,char *s);
2396
2397 @ @<Error hand...@>=
2398 void mp_confusion (MP mp,char *s) {
2399   /* consistency check violated; |s| tells where */
2400   mp_normalize_selector(mp);
2401   if ( mp->history<mp_error_message_issued ) { 
2402     print_err("This can't happen ("); mp_print(mp, s); mp_print_char(mp, ')');
2403 @.This can't happen@>
2404     help1("I'm broken. Please show this to someone who can fix can fix");
2405   } else { 
2406     print_err("I can\'t go on meeting you like this");
2407 @.I can't go on...@>
2408     help2("One of your faux pas seems to have wounded me deeply...")
2409          ("in fact, I'm barely conscious. Please fix it and try again.");
2410   }
2411   succumb;
2412 }
2413
2414 @ Users occasionally want to interrupt \MP\ while it's running.
2415 If the runtime system allows this, one can implement
2416 a routine that sets the global variable |interrupt| to some nonzero value
2417 when such an interrupt is signaled. Otherwise there is probably at least
2418 a way to make |interrupt| nonzero using the C debugger.
2419 @^system dependencies@>
2420 @^debugging@>
2421
2422 @d check_interrupt { if ( mp->interrupt!=0 )
2423    mp_pause_for_instructions(mp); }
2424
2425 @<Global...@>=
2426 integer interrupt; /* should \MP\ pause for instructions? */
2427 boolean OK_to_interrupt; /* should interrupts be observed? */
2428 integer run_state; /* are we processing input ?*/
2429
2430 @ @<Allocate or ...@>=
2431 mp->interrupt=0; mp->OK_to_interrupt=true; mp->run_state=0; 
2432
2433 @ When an interrupt has been detected, the program goes into its
2434 highest interaction level and lets the user have the full flexibility of
2435 the |error| routine.  \MP\ checks for interrupts only at times when it is
2436 safe to do this.
2437
2438 @c 
2439 void mp_pause_for_instructions (MP mp) { 
2440   if ( mp->OK_to_interrupt ) { 
2441     mp->interaction=mp_error_stop_mode;
2442     if ( (mp->selector==log_only)||(mp->selector==no_print) )
2443       incr(mp->selector);
2444     print_err("Interruption");
2445 @.Interruption@>
2446     help3("You rang?")
2447          ("Try to insert some instructions for me (e.g.,`I show x'),")
2448          ("unless you just want to quit by typing `X'.");
2449     mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
2450     mp->interrupt=0;
2451   }
2452 }
2453
2454 @ Many of \MP's error messages state that a missing token has been
2455 inserted behind the scenes. We can save string space and program space
2456 by putting this common code into a subroutine.
2457
2458 @c 
2459 void mp_missing_err (MP mp, char *s) { 
2460   print_err("Missing `"); mp_print(mp, s); mp_print(mp, "' has been inserted");
2461 @.Missing...inserted@>
2462 }
2463
2464 @* \[7] Arithmetic with scaled numbers.
2465 The principal computations performed by \MP\ are done entirely in terms of
2466 integers less than $2^{31}$ in magnitude; thus, the arithmetic specified in this
2467 program can be carried out in exactly the same way on a wide variety of
2468 computers, including some small ones.
2469 @^small computers@>
2470
2471 But C does not rigidly define the |/| operation in the case of negative
2472 dividends; for example, the result of |(-2*n-1) / 2| is |-(n+1)| on some
2473 computers and |-n| on others (is this true ?).  There are two principal
2474 types of arithmetic: ``translation-preserving,'' in which the identity
2475 |(a+q*b)/b=(a/b)+q| is valid; and ``negation-preserving,'' in which
2476 |(-a)/b=-(a/b)|. This leads to two \MP s, which can produce
2477 different results, although the differences should be negligible when the
2478 language is being used properly.  The \TeX\ processor has been defined
2479 carefully so that both varieties of arithmetic will produce identical
2480 output, but it would be too inefficient to constrain \MP\ in a similar way.
2481
2482 @d el_gordo   017777777777 /* $2^{31}-1$, the largest value that \MP\ likes */
2483
2484 @ One of \MP's most common operations is the calculation of
2485 $\lfloor{a+b\over2}\rfloor$,
2486 the midpoint of two given integers |a| and~|b|. The most decent way to do
2487 this is to write `|(a+b)/2|'; but on many machines it is more efficient 
2488 to calculate `|(a+b)>>1|'.
2489
2490 Therefore the midpoint operation will always be denoted by `|half(a+b)|'
2491 in this program. If \MP\ is being implemented with languages that permit
2492 binary shifting, the |half| macro should be changed to make this operation
2493 as efficient as possible.  Since some systems have shift operators that can
2494 only be trusted to work on positive numbers, there is also a macro |halfp|
2495 that is used only when the quantity being halved is known to be positive
2496 or zero.
2497
2498 @d half(A) ((A) / 2)
2499 @d halfp(A) ((A) >> 1)
2500
2501 @ A single computation might use several subroutine calls, and it is
2502 desirable to avoid producing multiple error messages in case of arithmetic
2503 overflow. So the routines below set the global variable |arith_error| to |true|
2504 instead of reporting errors directly to the user.
2505
2506 @<Glob...@>=
2507 boolean arith_error; /* has arithmetic overflow occurred recently? */
2508
2509 @ @<Allocate or ...@>=
2510 mp->arith_error=false;
2511
2512 @ At crucial points the program will say |check_arith|, to test if
2513 an arithmetic error has been detected.
2514
2515 @d check_arith { if ( mp->arith_error ) mp_clear_arith(mp); }
2516
2517 @c 
2518 void mp_clear_arith (MP mp) { 
2519   print_err("Arithmetic overflow");
2520 @.Arithmetic overflow@>
2521   help4("Uh, oh. A little while ago one of the quantities that I was")
2522        ("computing got too large, so I'm afraid your answers will be")
2523        ("somewhat askew. You'll probably have to adopt different")
2524        ("tactics next time. But I shall try to carry on anyway.");
2525   mp_error(mp); 
2526   mp->arith_error=false;
2527 }
2528
2529 @ Addition is not always checked to make sure that it doesn't overflow,
2530 but in places where overflow isn't too unlikely the |slow_add| routine
2531 is used.
2532
2533 @c integer mp_slow_add (MP mp,integer x, integer y) { 
2534   if ( x>=0 )  {
2535     if ( y<=el_gordo-x ) { 
2536       return x+y;
2537     } else  { 
2538       mp->arith_error=true; 
2539           return el_gordo;
2540     }
2541   } else  if ( -y<=el_gordo+x ) {
2542     return x+y;
2543   } else { 
2544     mp->arith_error=true; 
2545         return -el_gordo;
2546   }
2547 }
2548
2549 @ Fixed-point arithmetic is done on {\sl scaled integers\/} that are multiples
2550 of $2^{-16}$. In other words, a binary point is assumed to be sixteen bit
2551 positions from the right end of a binary computer word.
2552
2553 @d quarter_unit   040000 /* $2^{14}$, represents 0.250000 */
2554 @d half_unit   0100000 /* $2^{15}$, represents 0.50000 */
2555 @d three_quarter_unit   0140000 /* $3\cdot2^{14}$, represents 0.75000 */
2556 @d unity   0200000 /* $2^{16}$, represents 1.00000 */
2557 @d two   0400000 /* $2^{17}$, represents 2.00000 */
2558 @d three   0600000 /* $2^{17}+2^{16}$, represents 3.00000 */
2559
2560 @<Types...@>=
2561 typedef integer scaled; /* this type is used for scaled integers */
2562 typedef unsigned char small_number; /* this type is self-explanatory */
2563
2564 @ The following function is used to create a scaled integer from a given decimal
2565 fraction $(.d_0d_1\ldots d_{k-1})$, where |0<=k<=17|. The digit $d_i$ is
2566 given in |dig[i]|, and the calculation produces a correctly rounded result.
2567
2568 @c 
2569 scaled mp_round_decimals (MP mp,small_number k) {
2570   /* converts a decimal fraction */
2571  integer a = 0; /* the accumulator */
2572  while ( k-->0 ) { 
2573     a=(a+mp->dig[k]*two) / 10;
2574   }
2575   return halfp(a+1);
2576 }
2577
2578 @ Conversely, here is a procedure analogous to |print_int|. If the output
2579 of this procedure is subsequently read by \MP\ and converted by the
2580 |round_decimals| routine above, it turns out that the original value will
2581 be reproduced exactly. A decimal point is printed only if the value is
2582 not an integer. If there is more than one way to print the result with
2583 the optimum number of digits following the decimal point, the closest
2584 possible value is given.
2585
2586 The invariant relation in the \&{repeat} loop is that a sequence of
2587 decimal digits yet to be printed will yield the original number if and only if
2588 they form a fraction~$f$ in the range $s-\delta\L10\cdot2^{16}f<s$.
2589 We can stop if and only if $f=0$ satisfies this condition; the loop will
2590 terminate before $s$ can possibly become zero.
2591
2592 @<Basic printing...@>=
2593 void mp_print_scaled (MP mp,scaled s) { /* prints scaled real, rounded to five  digits */
2594   scaled delta; /* amount of allowable inaccuracy */
2595   if ( s<0 ) { 
2596         mp_print_char(mp, '-'); 
2597     negate(s); /* print the sign, if negative */
2598   }
2599   mp_print_int(mp, s / unity); /* print the integer part */
2600   s=10*(s % unity)+5;
2601   if ( s!=5 ) { 
2602     delta=10; 
2603     mp_print_char(mp, '.');
2604     do {  
2605       if ( delta>unity )
2606         s=s+0100000-(delta / 2); /* round the final digit */
2607       mp_print_char(mp, '0'+(s / unity)); 
2608       s=10*(s % unity); 
2609       delta=delta*10;
2610     } while (s>delta);
2611   }
2612 }
2613
2614 @ We often want to print two scaled quantities in parentheses,
2615 separated by a comma.
2616
2617 @<Basic printing...@>=
2618 void mp_print_two (MP mp,scaled x, scaled y) { /* prints `|(x,y)|' */
2619   mp_print_char(mp, '('); 
2620   mp_print_scaled(mp, x); 
2621   mp_print_char(mp, ','); 
2622   mp_print_scaled(mp, y);
2623   mp_print_char(mp, ')');
2624 }
2625
2626 @ The |scaled| quantities in \MP\ programs are generally supposed to be
2627 less than $2^{12}$ in absolute value, so \MP\ does much of its internal
2628 arithmetic with 28~significant bits of precision. A |fraction| denotes
2629 a scaled integer whose binary point is assumed to be 28 bit positions
2630 from the right.
2631
2632 @d fraction_half 01000000000 /* $2^{27}$, represents 0.50000000 */
2633 @d fraction_one 02000000000 /* $2^{28}$, represents 1.00000000 */
2634 @d fraction_two 04000000000 /* $2^{29}$, represents 2.00000000 */
2635 @d fraction_three 06000000000 /* $3\cdot2^{28}$, represents 3.00000000 */
2636 @d fraction_four 010000000000 /* $2^{30}$, represents 4.00000000 */
2637
2638 @<Types...@>=
2639 typedef integer fraction; /* this type is used for scaled fractions */
2640
2641 @ In fact, the two sorts of scaling discussed above aren't quite
2642 sufficient; \MP\ has yet another, used internally to keep track of angles
2643 in units of $2^{-20}$ degrees.
2644
2645 @d forty_five_deg 0264000000 /* $45\cdot2^{20}$, represents $45^\circ$ */
2646 @d ninety_deg 0550000000 /* $90\cdot2^{20}$, represents $90^\circ$ */
2647 @d one_eighty_deg 01320000000 /* $180\cdot2^{20}$, represents $180^\circ$ */
2648 @d three_sixty_deg 02640000000 /* $360\cdot2^{20}$, represents $360^\circ$ */
2649
2650 @<Types...@>=
2651 typedef integer angle; /* this type is used for scaled angles */
2652
2653 @ The |make_fraction| routine produces the |fraction| equivalent of
2654 |p/q|, given integers |p| and~|q|; it computes the integer
2655 $f=\lfloor2^{28}p/q+{1\over2}\rfloor$, when $p$ and $q$ are
2656 positive. If |p| and |q| are both of the same scaled type |t|,
2657 the ``type relation'' |make_fraction(t,t)=fraction| is valid;
2658 and it's also possible to use the subroutine ``backwards,'' using
2659 the relation |make_fraction(t,fraction)=t| between scaled types.
2660
2661 If the result would have magnitude $2^{31}$ or more, |make_fraction|
2662 sets |arith_error:=true|. Most of \MP's internal computations have
2663 been designed to avoid this sort of error.
2664
2665 If this subroutine were programmed in assembly language on a typical
2666 machine, we could simply compute |(@t$2^{28}$@>*p)div q|, since a
2667 double-precision product can often be input to a fixed-point division
2668 instruction. But when we are restricted to int-eger arithmetic it
2669 is necessary either to resort to multiple-precision maneuvering
2670 or to use a simple but slow iteration. The multiple-precision technique
2671 would be about three times faster than the code adopted here, but it
2672 would be comparatively long and tricky, involving about sixteen
2673 additional multiplications and divisions.
2674
2675 This operation is part of \MP's ``inner loop''; indeed, it will
2676 consume nearly 10\pct! of the running time (exclusive of input and output)
2677 if the code below is left unchanged. A machine-dependent recoding
2678 will therefore make \MP\ run faster. The present implementation
2679 is highly portable, but slow; it avoids multiplication and division
2680 except in the initial stage. System wizards should be careful to
2681 replace it with a routine that is guaranteed to produce identical
2682 results in all cases.
2683 @^system dependencies@>
2684
2685 As noted below, a few more routines should also be replaced by machine-dependent
2686 code, for efficiency. But when a procedure is not part of the ``inner loop,''
2687 such changes aren't advisable; simplicity and robustness are
2688 preferable to trickery, unless the cost is too high.
2689 @^inner loop@>
2690
2691 @<Internal ...@>=
2692 fraction mp_make_fraction (MP mp,integer p, integer q);
2693 integer mp_take_scaled (MP mp,integer q, scaled f) ;
2694
2695 @ If FIXPT is not defined, we need these preprocessor values
2696
2697 @d ELGORDO  0x7fffffff
2698 @d TWEXP31  2147483648.0
2699 @d TWEXP28  268435456.0
2700 @d TWEXP16 65536.0
2701 @d TWEXP_16 (1.0/65536.0)
2702 @d TWEXP_28 (1.0/268435456.0)
2703
2704
2705 @c 
2706 fraction mp_make_fraction (MP mp,integer p, integer q) {
2707 #ifdef FIXPT
2708   integer f; /* the fraction bits, with a leading 1 bit */
2709   integer n; /* the integer part of $\vert p/q\vert$ */
2710   integer be_careful; /* disables certain compiler optimizations */
2711   boolean negative = false; /* should the result be negated? */
2712   if ( p<0 ) {
2713     negate(p); negative=true;
2714   }
2715   if ( q<=0 ) { 
2716 #ifdef DEBUG
2717     if ( q==0 ) mp_confusion(mp, '/');
2718 #endif
2719 @:this can't happen /}{\quad \./@>
2720     negate(q); negative = ! negative;
2721   };
2722   n=p / q; p=p % q;
2723   if ( n>=8 ){ 
2724     mp->arith_error=true;
2725     return ( negative ? -el_gordo : el_gordo);
2726   } else { 
2727     n=(n-1)*fraction_one;
2728     @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>;
2729     return (negative ? (-(f+n)) : (f+n));
2730   }
2731 #else /* FIXPT */
2732     register double d;
2733         register integer i;
2734 #ifdef DEBUG
2735         if (q==0) mp_confusion(mp,'/'); 
2736 #endif /* DEBUG */
2737         d = TWEXP28 * (double)p /(double)q;
2738         if ((p^q) >= 0) {
2739                 d += 0.5;
2740                 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
2741                 i = (integer) d;
2742                 if (d==i && ( ((q>0 ? -q : q)&077777)
2743                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2744         } else {
2745                 d -= 0.5;
2746                 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
2747                 i = (integer) d;
2748                 if (d==i && ( ((q>0 ? q : -q)&077777)
2749                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
2750         }
2751         return i;
2752 #endif /* FIXPT */
2753 }
2754
2755 @ The |repeat| loop here preserves the following invariant relations
2756 between |f|, |p|, and~|q|:
2757 (i)~|0<=p<q|; (ii)~$fq+p=2^k(q+p_0)$, where $k$ is an integer and
2758 $p_0$ is the original value of~$p$.
2759
2760 Notice that the computation specifies
2761 |(p-q)+p| instead of |(p+p)-q|, because the latter could overflow.
2762 Let us hope that optimizing compilers do not miss this point; a
2763 special variable |be_careful| is used to emphasize the necessary
2764 order of computation. Optimizing compilers should keep |be_careful|
2765 in a register, not store it in memory.
2766 @^inner loop@>
2767
2768 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>=
2769 {
2770   f=1;
2771   do {  
2772     be_careful=p-q; p=be_careful+p;
2773     if ( p>=0 ) { 
2774       f=f+f+1;
2775     } else  { 
2776       f+=f; p=p+q;
2777     }
2778   } while (f<fraction_one);
2779   be_careful=p-q;
2780   if ( be_careful+p>=0 ) incr(f);
2781 }
2782
2783 @ The dual of |make_fraction| is |take_fraction|, which multiplies a
2784 given integer~|q| by a fraction~|f|. When the operands are positive, it
2785 computes $p=\lfloor qf/2^{28}+{1\over2}\rfloor$, a symmetric function
2786 of |q| and~|f|.
2787
2788 This routine is even more ``inner loopy'' than |make_fraction|;
2789 the present implementation consumes almost 20\pct! of \MP's computation
2790 time during typical jobs, so a machine-language substitute is advisable.
2791 @^inner loop@> @^system dependencies@>
2792
2793 @<Declarations@>=
2794 integer mp_take_fraction (MP mp,integer q, fraction f) ;
2795
2796 @ @c 
2797 #ifdef FIXPT
2798 integer mp_take_fraction (MP mp,integer q, fraction f) {
2799   integer p; /* the fraction so far */
2800   boolean negative; /* should the result be negated? */
2801   integer n; /* additional multiple of $q$ */
2802   integer be_careful; /* disables certain compiler optimizations */
2803   @<Reduce to the case that |f>=0| and |q>0|@>;
2804   if ( f<fraction_one ) { 
2805     n=0;
2806   } else { 
2807     n=f / fraction_one; f=f % fraction_one;
2808     if ( q<=el_gordo / n ) { 
2809       n=n*q ; 
2810     } else { 
2811       mp->arith_error=true; n=el_gordo;
2812     }
2813   }
2814   f=f+fraction_one;
2815   @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>;
2816   be_careful=n-el_gordo;
2817   if ( be_careful+p>0 ){ 
2818     mp->arith_error=true; n=el_gordo-p;
2819   }
2820   if ( negative ) 
2821         return (-(n+p));
2822   else 
2823     return (n+p);
2824 #else /* FIXPT */
2825 integer mp_take_fraction (MP mp,integer p, fraction q) {
2826     register double d;
2827         register integer i;
2828         d = (double)p * (double)q * TWEXP_28;
2829         if ((p^q) >= 0) {
2830                 d += 0.5;
2831                 if (d>=TWEXP31) {
2832                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2833                                 mp->arith_error = true;
2834                         return ELGORDO;
2835                 }
2836                 i = (integer) d;
2837                 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2838         } else {
2839                 d -= 0.5;
2840                 if (d<= -TWEXP31) {
2841                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2842                                 mp->arith_error = true;
2843                         return -ELGORDO;
2844                 }
2845                 i = (integer) d;
2846                 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2847         }
2848         return i;
2849 #endif /* FIXPT */
2850 }
2851
2852 @ @<Reduce to the case that |f>=0| and |q>0|@>=
2853 if ( f>=0 ) {
2854   negative=false;
2855 } else { 
2856   negate( f); negative=true;
2857 }
2858 if ( q<0 ) { 
2859   negate(q); negative=! negative;
2860 }
2861
2862 @ The invariant relations in this case are (i)~$\lfloor(qf+p)/2^k\rfloor
2863 =\lfloor qf_0/2^{28}+{1\over2}\rfloor$, where $k$ is an integer and
2864 $f_0$ is the original value of~$f$; (ii)~$2^k\L f<2^{k+1}$.
2865 @^inner loop@>
2866
2867 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>=
2868 p=fraction_half; /* that's $2^{27}$; the invariants hold now with $k=28$ */
2869 if ( q<fraction_four ) {
2870   do {  
2871     if ( odd(f) ) p=halfp(p+q); else p=halfp(p);
2872     f=halfp(f);
2873   } while (f!=1);
2874 } else  {
2875   do {  
2876     if ( odd(f) ) p=p+halfp(q-p); else p=halfp(p);
2877     f=halfp(f);
2878   } while (f!=1);
2879 }
2880
2881
2882 @ When we want to multiply something by a |scaled| quantity, we use a scheme
2883 analogous to |take_fraction| but with a different scaling.
2884 Given positive operands, |take_scaled|
2885 computes the quantity $p=\lfloor qf/2^{16}+{1\over2}\rfloor$.
2886
2887 Once again it is a good idea to use a machine-language replacement if
2888 possible; otherwise |take_scaled| will use more than 2\pct! of the running time
2889 when the Computer Modern fonts are being generated.
2890 @^inner loop@>
2891
2892 @c 
2893 #ifdef FIXPT
2894 integer mp_take_scaled (MP mp,integer q, scaled f) {
2895   integer p; /* the fraction so far */
2896   boolean negative; /* should the result be negated? */
2897   integer n; /* additional multiple of $q$ */
2898   integer be_careful; /* disables certain compiler optimizations */
2899   @<Reduce to the case that |f>=0| and |q>0|@>;
2900   if ( f<unity ) { 
2901     n=0;
2902   } else  { 
2903     n=f / unity; f=f % unity;
2904     if ( q<=el_gordo / n ) {
2905       n=n*q;
2906     } else  { 
2907       mp->arith_error=true; n=el_gordo;
2908     }
2909   }
2910   f=f+unity;
2911   @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>;
2912   be_careful=n-el_gordo;
2913   if ( be_careful+p>0 ) { 
2914     mp->arith_error=true; n=el_gordo-p;
2915   }
2916   return ( negative ?(-(n+p)) :(n+p));
2917 #else /* FIXPT */
2918 integer mp_take_scaled (MP mp,integer p, scaled q) {
2919     register double d;
2920         register integer i;
2921         d = (double)p * (double)q * TWEXP_16;
2922         if ((p^q) >= 0) {
2923                 d += 0.5;
2924                 if (d>=TWEXP31) {
2925                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2926                                 mp->arith_error = true;
2927                         return ELGORDO;
2928                 }
2929                 i = (integer) d;
2930                 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2931         } else {
2932                 d -= 0.5;
2933                 if (d<= -TWEXP31) {
2934                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2935                                 mp->arith_error = true;
2936                         return -ELGORDO;
2937                 }
2938                 i = (integer) d;
2939                 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2940         }
2941         return i;
2942 #endif /* FIXPT */
2943 }
2944
2945 @ @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>=
2946 p=half_unit; /* that's $2^{15}$; the invariants hold now with $k=16$ */
2947 @^inner loop@>
2948 if ( q<fraction_four ) {
2949   do {  
2950     p = (odd(f) ? halfp(p+q) : halfp(p));
2951     f=halfp(f);
2952   } while (f!=1);
2953 } else {
2954   do {  
2955     p = (odd(f) ? p+halfp(q-p) : halfp(p));
2956     f=halfp(f);
2957   } while (f!=1);
2958 }
2959
2960 @ For completeness, there's also |make_scaled|, which computes a
2961 quotient as a |scaled| number instead of as a |fraction|.
2962 In other words, the result is $\lfloor2^{16}p/q+{1\over2}\rfloor$, if the
2963 operands are positive. \ (This procedure is not used especially often,
2964 so it is not part of \MP's inner loop.)
2965
2966 @<Internal library ...@>=
2967 scaled mp_make_scaled (MP mp,integer p, integer q) ;
2968
2969 @ @c 
2970 scaled mp_make_scaled (MP mp,integer p, integer q) {
2971 #ifdef FIXPT 
2972   integer f; /* the fraction bits, with a leading 1 bit */
2973   integer n; /* the integer part of $\vert p/q\vert$ */
2974   boolean negative; /* should the result be negated? */
2975   integer be_careful; /* disables certain compiler optimizations */
2976   if ( p>=0 ) negative=false;
2977   else  { negate(p); negative=true; };
2978   if ( q<=0 ) { 
2979 #ifdef DEBUG 
2980     if ( q==0 ) mp_confusion(mp, "/");
2981 @:this can't happen /}{\quad \./@>
2982 #endif
2983     negate(q); negative=! negative;
2984   }
2985   n=p / q; p=p % q;
2986   if ( n>=0100000 ) { 
2987     mp->arith_error=true;
2988     return (negative ? (-el_gordo) : el_gordo);
2989   } else  { 
2990     n=(n-1)*unity;
2991     @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>;
2992     return ( negative ? (-(f+n)) :(f+n));
2993   }
2994 #else /* FIXPT */
2995     register double d;
2996         register integer i;
2997 #ifdef DEBUG
2998         if (q==0) mp_confusion(mp,"/"); 
2999 #endif /* DEBUG */
3000         d = TWEXP16 * (double)p /(double)q;
3001         if ((p^q) >= 0) {
3002                 d += 0.5;
3003                 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
3004                 i = (integer) d;
3005                 if (d==i && ( ((q>0 ? -q : q)&077777)
3006                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
3007         } else {
3008                 d -= 0.5;
3009                 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
3010                 i = (integer) d;
3011                 if (d==i && ( ((q>0 ? q : -q)&077777)
3012                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
3013         }
3014         return i;
3015 #endif /* FIXPT */
3016 }
3017
3018 @ @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>=
3019 f=1;
3020 do {  
3021   be_careful=p-q; p=be_careful+p;
3022   if ( p>=0 ) f=f+f+1;
3023   else  { f+=f; p=p+q; };
3024 } while (f<unity);
3025 be_careful=p-q;
3026 if ( be_careful+p>=0 ) incr(f)
3027
3028 @ Here is a typical example of how the routines above can be used.
3029 It computes the function
3030 $${1\over3\tau}f(\theta,\phi)=
3031 {\tau^{-1}\bigl(2+\sqrt2\,(\sin\theta-{1\over16}\sin\phi)
3032  (\sin\phi-{1\over16}\sin\theta)(\cos\theta-\cos\phi)\bigr)\over
3033 3\,\bigl(1+{1\over2}(\sqrt5-1)\cos\theta+{1\over2}(3-\sqrt5\,)\cos\phi\bigr)},$$
3034 where $\tau$ is a |scaled| ``tension'' parameter. This is \MP's magic
3035 fudge factor for placing the first control point of a curve that starts
3036 at an angle $\theta$ and ends at an angle $\phi$ from the straight path.
3037 (Actually, if the stated quantity exceeds 4, \MP\ reduces it to~4.)
3038
3039 The trigonometric quantity to be multiplied by $\sqrt2$ is less than $\sqrt2$.
3040 (It's a sum of eight terms whose absolute values can be bounded using
3041 relations such as $\sin\theta\cos\theta\L{1\over2}$.) Thus the numerator
3042 is positive; and since the tension $\tau$ is constrained to be at least
3043 $3\over4$, the numerator is less than $16\over3$. The denominator is
3044 nonnegative and at most~6.  Hence the fixed-point calculations below
3045 are guaranteed to stay within the bounds of a 32-bit computer word.
3046
3047 The angles $\theta$ and $\phi$ are given implicitly in terms of |fraction|
3048 arguments |st|, |ct|, |sf|, and |cf|, representing $\sin\theta$, $\cos\theta$,
3049 $\sin\phi$, and $\cos\phi$, respectively.
3050
3051 @c 
3052 fraction mp_velocity (MP mp,fraction st, fraction ct, fraction sf,
3053                       fraction cf, scaled t) {
3054   integer acc,num,denom; /* registers for intermediate calculations */
3055   acc=mp_take_fraction(mp, st-(sf / 16), sf-(st / 16));
3056   acc=mp_take_fraction(mp, acc,ct-cf);
3057   num=fraction_two+mp_take_fraction(mp, acc,379625062);
3058                    /* $2^{28}\sqrt2\approx379625062.497$ */
3059   denom=fraction_three+mp_take_fraction(mp, ct,497706707)+mp_take_fraction(mp, cf,307599661);
3060                       /* $3\cdot2^{27}\cdot(\sqrt5-1)\approx497706706.78$ and
3061                          $3\cdot2^{27}\cdot(3-\sqrt5\,)\approx307599661.22$ */
3062   if ( t!=unity ) num=mp_make_scaled(mp, num,t);
3063   /* |make_scaled(fraction,scaled)=fraction| */
3064   if ( num / 4>=denom ) 
3065     return fraction_four;
3066   else 
3067     return mp_make_fraction(mp, num, denom);
3068 }
3069
3070 @ The following somewhat different subroutine tests rigorously if $ab$ is
3071 greater than, equal to, or less than~$cd$,
3072 given integers $(a,b,c,d)$. In most cases a quick decision is reached.
3073 The result is $+1$, 0, or~$-1$ in the three respective cases.
3074
3075 @d mp_ab_vs_cd(M,A,B,C,D) mp_do_ab_vs_cd(A,B,C,D)
3076
3077 @c 
3078 integer mp_do_ab_vs_cd (integer a,integer b, integer c, integer d) {
3079   integer q,r; /* temporary registers */
3080   @<Reduce to the case that |a,c>=0|, |b,d>0|@>;
3081   while (1) { 
3082     q = a / d; r = c / b;
3083     if ( q!=r )
3084       return ( q>r ? 1 : -1);
3085     q = a % d; r = c % b;
3086     if ( r==0 )
3087       return (q ? 1 : 0);
3088     if ( q==0 ) return -1;
3089     a=b; b=q; c=d; d=r;
3090   } /* now |a>d>0| and |c>b>0| */
3091 }
3092
3093 @ @<Reduce to the case that |a...@>=
3094 if ( a<0 ) { negate(a); negate(b);  };
3095 if ( c<0 ) { negate(c); negate(d);  };
3096 if ( d<=0 ) { 
3097   if ( b>=0 ) {
3098     if ( (a==0||b==0)&&(c==0||d==0) ) return 0;
3099     else return 1;
3100   }
3101   if ( d==0 )
3102     return ( a==0 ? 0 : -1);
3103   q=a; a=c; c=q; q=-b; b=-d; d=q;
3104 } else if ( b<=0 ) { 
3105   if ( b<0 ) if ( a>0 ) return -1;
3106   return (c==0 ? 0 : -1);
3107 }
3108
3109 @ We conclude this set of elementary routines with some simple rounding
3110 and truncation operations.
3111
3112 @<Internal library declarations@>=
3113 #define mp_floor_scaled(M,i) ((i)&(-65536))
3114 #define mp_round_unscaled(M,i) (((i>>15)+1)>>1)
3115 #define mp_round_fraction(M,i) (((i>>11)+1)>>1)
3116
3117
3118 @* \[8] Algebraic and transcendental functions.
3119 \MP\ computes all of the necessary special functions from scratch, without
3120 relying on |real| arithmetic or system subroutines for sines, cosines, etc.
3121
3122 @ To get the square root of a |scaled| number |x|, we want to calculate
3123 $s=\lfloor 2^8\!\sqrt x +{1\over2}\rfloor$. If $x>0$, this is the unique
3124 integer such that $2^{16}x-s\L s^2<2^{16}x+s$. The following subroutine
3125 determines $s$ by an iterative method that maintains the invariant
3126 relations $x=2^{46-2k}x_0\bmod 2^{30}$, $0<y=\lfloor 2^{16-2k}x_0\rfloor
3127 -s^2+s\L q=2s$, where $x_0$ is the initial value of $x$. The value of~$y$
3128 might, however, be zero at the start of the first iteration.
3129
3130 @<Declarations@>=
3131 scaled mp_square_rt (MP mp,scaled x) ;
3132
3133 @ @c 
3134 scaled mp_square_rt (MP mp,scaled x) {
3135   small_number k; /* iteration control counter */
3136   integer y,q; /* registers for intermediate calculations */
3137   if ( x<=0 ) { 
3138     @<Handle square root of zero or negative argument@>;
3139   } else { 
3140     k=23; q=2;
3141     while ( x<fraction_two ) { /* i.e., |while x<@t$2^{29}$@>|\unskip */
3142       decr(k); x=x+x+x+x;
3143     }
3144     if ( x<fraction_four ) y=0;
3145     else  { x=x-fraction_four; y=1; };
3146     do {  
3147       @<Decrease |k| by 1, maintaining the invariant
3148       relations between |x|, |y|, and~|q|@>;
3149     } while (k!=0);
3150     return (halfp(q));
3151   }
3152 }
3153
3154 @ @<Handle square root of zero...@>=
3155
3156   if ( x<0 ) { 
3157     print_err("Square root of ");
3158 @.Square root...replaced by 0@>
3159     mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3160     help2("Since I don't take square roots of negative numbers,")
3161          ("I'm zeroing this one. Proceed, with fingers crossed.");
3162     mp_error(mp);
3163   };
3164   return 0;
3165 }
3166
3167 @ @<Decrease |k| by 1, maintaining...@>=
3168 x+=x; y+=y;
3169 if ( x>=fraction_four ) { /* note that |fraction_four=@t$2^{30}$@>| */
3170   x=x-fraction_four; incr(y);
3171 };
3172 x+=x; y=y+y-q; q+=q;
3173 if ( x>=fraction_four ) { x=x-fraction_four; incr(y); };
3174 if ( y>q ){ y=y-q; q=q+2; }
3175 else if ( y<=0 )  { q=q-2; y=y+q;  };
3176 decr(k)
3177
3178 @ Pythagorean addition $\psqrt{a^2+b^2}$ is implemented by an elegant
3179 iterative scheme due to Cleve Moler and Donald Morrison [{\sl IBM Journal
3180 @^Moler, Cleve Barry@>
3181 @^Morrison, Donald Ross@>
3182 of Research and Development\/ \bf27} (1983), 577--581]. It modifies |a| and~|b|
3183 in such a way that their Pythagorean sum remains invariant, while the
3184 smaller argument decreases.
3185
3186 @<Internal library ...@>=
3187 integer mp_pyth_add (MP mp,integer a, integer b);
3188
3189
3190 @ @c 
3191 integer mp_pyth_add (MP mp,integer a, integer b) {
3192   fraction r; /* register used to transform |a| and |b| */
3193   boolean big; /* is the result dangerously near $2^{31}$? */
3194   a=abs(a); b=abs(b);
3195   if ( a<b ) { r=b; b=a; a=r; }; /* now |0<=b<=a| */
3196   if ( b>0 ) {
3197     if ( a<fraction_two ) {
3198       big=false;
3199     } else { 
3200       a=a / 4; b=b / 4; big=true;
3201     }; /* we reduced the precision to avoid arithmetic overflow */
3202     @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>;
3203     if ( big ) {
3204       if ( a<fraction_two ) {
3205         a=a+a+a+a;
3206       } else  { 
3207         mp->arith_error=true; a=el_gordo;
3208       };
3209     }
3210   }
3211   return a;
3212 }
3213
3214 @ The key idea here is to reflect the vector $(a,b)$ about the
3215 line through $(a,b/2)$.
3216
3217 @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>=
3218 while (1) {  
3219   r=mp_make_fraction(mp, b,a);
3220   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3221   if ( r==0 ) break;
3222   r=mp_make_fraction(mp, r,fraction_four+r);
3223   a=a+mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3224 }
3225
3226
3227 @ Here is a similar algorithm for $\psqrt{a^2-b^2}$.
3228 It converges slowly when $b$ is near $a$, but otherwise it works fine.
3229
3230 @c 
3231 integer mp_pyth_sub (MP mp,integer a, integer b) {
3232   fraction r; /* register used to transform |a| and |b| */
3233   boolean big; /* is the input dangerously near $2^{31}$? */
3234   a=abs(a); b=abs(b);
3235   if ( a<=b ) {
3236     @<Handle erroneous |pyth_sub| and set |a:=0|@>;
3237   } else { 
3238     if ( a<fraction_four ) {
3239       big=false;
3240     } else  { 
3241       a=halfp(a); b=halfp(b); big=true;
3242     }
3243     @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>;
3244     if ( big ) double(a);
3245   }
3246   return a;
3247 }
3248
3249 @ @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>=
3250 while (1) { 
3251   r=mp_make_fraction(mp, b,a);
3252   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3253   if ( r==0 ) break;
3254   r=mp_make_fraction(mp, r,fraction_four-r);
3255   a=a-mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3256 }
3257
3258 @ @<Handle erroneous |pyth_sub| and set |a:=0|@>=
3259
3260   if ( a<b ){ 
3261     print_err("Pythagorean subtraction "); mp_print_scaled(mp, a);
3262     mp_print(mp, "+-+"); mp_print_scaled(mp, b); 
3263     mp_print(mp, " has been replaced by 0");
3264 @.Pythagorean...@>
3265     help2("Since I don't take square roots of negative numbers,")
3266          ("I'm zeroing this one. Proceed, with fingers crossed.");
3267     mp_error(mp);
3268   }
3269   a=0;
3270 }
3271
3272 @ The subroutines for logarithm and exponential involve two tables.
3273 The first is simple: |two_to_the[k]| equals $2^k$. The second involves
3274 a bit more calculation, which the author claims to have done correctly:
3275 |spec_log[k]| is $2^{27}$ times $\ln\bigl(1/(1-2^{-k})\bigr)=
3276 2^{-k}+{1\over2}2^{-2k}+{1\over3}2^{-3k}+\cdots\,$, rounded to the
3277 nearest integer.
3278
3279 @d two_to_the(A) (1<<(A))
3280
3281 @<Constants ...@>=
3282 static const integer spec_log[29] = { 0, /* special logarithms */
3283 93032640, 38612034, 17922280, 8662214, 4261238, 2113709,
3284 1052693, 525315, 262400, 131136, 65552, 32772, 16385,
3285 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 1 };
3286
3287 @ @<Local variables for initialization@>=
3288 integer k; /* all-purpose loop index */
3289
3290
3291 @ Here is the routine that calculates $2^8$ times the natural logarithm
3292 of a |scaled| quantity; it is an integer approximation to $2^{24}\ln(x/2^{16})$,
3293 when |x| is a given positive integer.
3294
3295 The method is based on exercise 1.2.2--25 in {\sl The Art of Computer
3296 Programming\/}: During the main iteration we have $1\L 2^{-30}x<1/(1-2^{1-k})$,
3297 and the logarithm of $2^{30}x$ remains to be added to an accumulator
3298 register called~$y$. Three auxiliary bits of accuracy are retained in~$y$
3299 during the calculation, and sixteen auxiliary bits to extend |y| are
3300 kept in~|z| during the initial argument reduction. (We add
3301 $100\cdot2^{16}=6553600$ to~|z| and subtract 100 from~|y| so that |z| will
3302 not become negative; also, the actual amount subtracted from~|y| is~96,
3303 not~100, because we want to add~4 for rounding before the final division by~8.)
3304
3305 @c 
3306 scaled mp_m_log (MP mp,scaled x) {
3307   integer y,z; /* auxiliary registers */
3308   integer k; /* iteration counter */
3309   if ( x<=0 ) {
3310      @<Handle non-positive logarithm@>;
3311   } else  { 
3312     y=1302456956+4-100; /* $14\times2^{27}\ln2\approx1302456956.421063$ */
3313     z=27595+6553600; /* and $2^{16}\times .421063\approx 27595$ */
3314     while ( x<fraction_four ) {
3315        double(x); y-=93032639; z-=48782;
3316     } /* $2^{27}\ln2\approx 93032639.74436163$ and $2^{16}\times.74436163\approx 48782$ */
3317     y=y+(z / unity); k=2;
3318     while ( x>fraction_four+4 ) {
3319       @<Increase |k| until |x| can be multiplied by a
3320         factor of $2^{-k}$, and adjust $y$ accordingly@>;
3321     }
3322     return (y / 8);
3323   }
3324 }
3325
3326 @ @<Increase |k| until |x| can...@>=
3327
3328   z=((x-1) / two_to_the(k))+1; /* $z=\lceil x/2^k\rceil$ */
3329   while ( x<fraction_four+z ) { z=halfp(z+1); incr(k); };
3330   y+=spec_log[k]; x-=z;
3331 }
3332
3333 @ @<Handle non-positive logarithm@>=
3334
3335   print_err("Logarithm of ");
3336 @.Logarithm...replaced by 0@>
3337   mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3338   help2("Since I don't take logs of non-positive numbers,")
3339        ("I'm zeroing this one. Proceed, with fingers crossed.");
3340   mp_error(mp); 
3341   return 0;
3342 }
3343
3344 @ Conversely, the exponential routine calculates $\exp(x/2^8)$,
3345 when |x| is |scaled|. The result is an integer approximation to
3346 $2^{16}\exp(x/2^{24})$, when |x| is regarded as an integer.
3347
3348 @c 
3349 scaled mp_m_exp (MP mp,scaled x) {
3350   small_number k; /* loop control index */
3351   integer y,z; /* auxiliary registers */
3352   if ( x>174436200 ) {
3353     /* $2^{24}\ln((2^{31}-1)/2^{16})\approx 174436199.51$ */
3354     mp->arith_error=true; 
3355     return el_gordo;
3356   } else if ( x<-197694359 ) {
3357         /* $2^{24}\ln(2^{-1}/2^{16})\approx-197694359.45$ */
3358     return 0;
3359   } else { 
3360     if ( x<=0 ) { 
3361        z=-8*x; y=04000000; /* $y=2^{20}$ */
3362     } else { 
3363       if ( x<=127919879 ) { 
3364         z=1023359037-8*x;
3365         /* $2^{27}\ln((2^{31}-1)/2^{20})\approx 1023359037.125$ */
3366       } else {
3367        z=8*(174436200-x); /* |z| is always nonnegative */
3368       }
3369       y=el_gordo;
3370     };
3371     @<Multiply |y| by $\exp(-z/2^{27})$@>;
3372     if ( x<=127919879 ) 
3373        return ((y+8) / 16);
3374      else 
3375        return y;
3376   }
3377 }
3378
3379 @ The idea here is that subtracting |spec_log[k]| from |z| corresponds
3380 to multiplying |y| by $1-2^{-k}$.
3381
3382 A subtle point (which had to be checked) was that if $x=127919879$, the
3383 value of~|y| will decrease so that |y+8| doesn't overflow. In fact,
3384 $z$ will be 5 in this case, and |y| will decrease by~64 when |k=25|
3385 and by~16 when |k=27|.
3386
3387 @<Multiply |y| by...@>=
3388 k=1;
3389 while ( z>0 ) { 
3390   while ( z>=spec_log[k] ) { 
3391     z-=spec_log[k];
3392     y=y-1-((y-two_to_the(k-1)) / two_to_the(k));
3393   }
3394   incr(k);
3395 }
3396
3397 @ The trigonometric subroutines use an auxiliary table such that
3398 |spec_atan[k]| contains an approximation to the |angle| whose tangent
3399 is~$1/2^k$. $\arctan2^{-k}$ times $2^{20}\cdot180/\pi$ 
3400
3401 @<Constants ...@>=
3402 static const angle spec_atan[27] = { 0, 27855475, 14718068, 7471121, 3750058, 
3403 1876857, 938658, 469357, 234682, 117342, 58671, 29335, 14668, 7334, 3667, 
3404 1833, 917, 458, 229, 115, 57, 29, 14, 7, 4, 2, 1 };
3405
3406 @ Given integers |x| and |y|, not both zero, the |n_arg| function
3407 returns the |angle| whose tangent points in the direction $(x,y)$.
3408 This subroutine first determines the correct octant, then solves the
3409 problem for |0<=y<=x|, then converts the result appropriately to
3410 return an answer in the range |-one_eighty_deg<=@t$\theta$@><=one_eighty_deg|.
3411 (The answer is |+one_eighty_deg| if |y=0| and |x<0|, but an answer of
3412 |-one_eighty_deg| is possible if, for example, |y=-1| and $x=-2^{30}$.)
3413
3414 The octants are represented in a ``Gray code,'' since that turns out
3415 to be computationally simplest.
3416
3417 @d negate_x 1
3418 @d negate_y 2
3419 @d switch_x_and_y 4
3420 @d first_octant 1
3421 @d second_octant (first_octant+switch_x_and_y)
3422 @d third_octant (first_octant+switch_x_and_y+negate_x)
3423 @d fourth_octant (first_octant+negate_x)
3424 @d fifth_octant (first_octant+negate_x+negate_y)
3425 @d sixth_octant (first_octant+switch_x_and_y+negate_x+negate_y)
3426 @d seventh_octant (first_octant+switch_x_and_y+negate_y)
3427 @d eighth_octant (first_octant+negate_y)
3428
3429 @c 
3430 angle mp_n_arg (MP mp,integer x, integer y) {
3431   angle z; /* auxiliary register */
3432   integer t; /* temporary storage */
3433   small_number k; /* loop counter */
3434   int octant; /* octant code */
3435   if ( x>=0 ) {
3436     octant=first_octant;
3437   } else { 
3438     negate(x); octant=first_octant+negate_x;
3439   }
3440   if ( y<0 ) { 
3441     negate(y); octant=octant+negate_y;
3442   }
3443   if ( x<y ) { 
3444     t=y; y=x; x=t; octant=octant+switch_x_and_y;
3445   }
3446   if ( x==0 ) { 
3447     @<Handle undefined arg@>; 
3448   } else { 
3449     @<Set variable |z| to the arg of $(x,y)$@>;
3450     @<Return an appropriate answer based on |z| and |octant|@>;
3451   }
3452 }
3453
3454 @ @<Handle undefined arg@>=
3455
3456   print_err("angle(0,0) is taken as zero");
3457 @.angle(0,0)...zero@>
3458   help2("The `angle' between two identical points is undefined.")
3459        ("I'm zeroing this one. Proceed, with fingers crossed.");
3460   mp_error(mp); 
3461   return 0;
3462 }
3463
3464 @ @<Return an appropriate answer...@>=
3465 switch (octant) {
3466 case first_octant: return z;
3467 case second_octant: return (ninety_deg-z);
3468 case third_octant: return (ninety_deg+z);
3469 case fourth_octant: return (one_eighty_deg-z);
3470 case fifth_octant: return (z-one_eighty_deg);
3471 case sixth_octant: return (-z-ninety_deg);
3472 case seventh_octant: return (z-ninety_deg);
3473 case eighth_octant: return (-z);
3474 }; /* there are no other cases */
3475 return 0
3476
3477 @ At this point we have |x>=y>=0|, and |x>0|. The numbers are scaled up
3478 or down until $2^{28}\L x<2^{29}$, so that accurate fixed-point calculations
3479 will be made.
3480
3481 @<Set variable |z| to the arg...@>=
3482 while ( x>=fraction_two ) { 
3483   x=halfp(x); y=halfp(y);
3484 }
3485 z=0;
3486 if ( y>0 ) { 
3487  while ( x<fraction_one ) { 
3488     x+=x; y+=y; 
3489  };
3490  @<Increase |z| to the arg of $(x,y)$@>;
3491 }
3492
3493 @ During the calculations of this section, variables |x| and~|y|
3494 represent actual coordinates $(x,2^{-k}y)$. We will maintain the
3495 condition |x>=y|, so that the tangent will be at most $2^{-k}$.
3496 If $x<2y$, the tangent is greater than $2^{-k-1}$. The transformation
3497 $(a,b)\mapsto(a+b\tan\phi,b-a\tan\phi)$ replaces $(a,b)$ by
3498 coordinates whose angle has decreased by~$\phi$; in the special case
3499 $a=x$, $b=2^{-k}y$, and $\tan\phi=2^{-k-1}$, this operation reduces
3500 to the particularly simple iteration shown here. [Cf.~John E. Meggitt,
3501 @^Meggitt, John E.@>
3502 {\sl IBM Journal of Research and Development\/ \bf6} (1962), 210--226.]
3503
3504 The initial value of |x| will be multiplied by at most
3505 $(1+{1\over2})(1+{1\over8})(1+{1\over32})\cdots\approx 1.7584$; hence
3506 there is no chance of integer overflow.
3507
3508 @<Increase |z|...@>=
3509 k=0;
3510 do {  
3511   y+=y; incr(k);
3512   if ( y>x ){ 
3513     z=z+spec_atan[k]; t=x; x=x+(y / two_to_the(k+k)); y=y-t;
3514   };
3515 } while (k!=15);
3516 do {  
3517   y+=y; incr(k);
3518   if ( y>x ) { z=z+spec_atan[k]; y=y-x; };
3519 } while (k!=26)
3520
3521 @ Conversely, the |n_sin_cos| routine takes an |angle| and produces the sine
3522 and cosine of that angle. The results of this routine are
3523 stored in global integer variables |n_sin| and |n_cos|.
3524
3525 @<Glob...@>=
3526 fraction n_sin;fraction n_cos; /* results computed by |n_sin_cos| */
3527
3528 @ Given an integer |z| that is $2^{20}$ times an angle $\theta$ in degrees,
3529 the purpose of |n_sin_cos(z)| is to set
3530 |x=@t$r\cos\theta$@>| and |y=@t$r\sin\theta$@>| (approximately),
3531 for some rather large number~|r|. The maximum of |x| and |y|
3532 will be between $2^{28}$ and $2^{30}$, so that there will be hardly
3533 any loss of accuracy. Then |x| and~|y| are divided by~|r|.
3534
3535 @c 
3536 void mp_n_sin_cos (MP mp,angle z) { /* computes a multiple of the sine
3537                                        and cosine */ 
3538   small_number k; /* loop control variable */
3539   int q; /* specifies the quadrant */
3540   fraction r; /* magnitude of |(x,y)| */
3541   integer x,y,t; /* temporary registers */
3542   while ( z<0 ) z=z+three_sixty_deg;
3543   z=z % three_sixty_deg; /* now |0<=z<three_sixty_deg| */
3544   q=z / forty_five_deg; z=z % forty_five_deg;
3545   x=fraction_one; y=x;
3546   if ( ! odd(q) ) z=forty_five_deg-z;
3547   @<Subtract angle |z| from |(x,y)|@>;
3548   @<Convert |(x,y)| to the octant determined by~|q|@>;
3549   r=mp_pyth_add(mp, x,y); 
3550   mp->n_cos=mp_make_fraction(mp, x,r); 
3551   mp->n_sin=mp_make_fraction(mp, y,r);
3552 }
3553
3554 @ In this case the octants are numbered sequentially.
3555
3556 @<Convert |(x,...@>=
3557 switch (q) {
3558 case 0: break;
3559 case 1: t=x; x=y; y=t; break;
3560 case 2: t=x; x=-y; y=t; break;
3561 case 3: negate(x); break;
3562 case 4: negate(x); negate(y); break;
3563 case 5: t=x; x=-y; y=-t; break;
3564 case 6: t=x; x=y; y=-t; break;
3565 case 7: negate(y); break;
3566 } /* there are no other cases */
3567
3568 @ The main iteration of |n_sin_cos| is similar to that of |n_arg| but
3569 applied in reverse. The values of |spec_atan[k]| decrease slowly enough
3570 that this loop is guaranteed to terminate before the (nonexistent) value
3571 |spec_atan[27]| would be required.
3572
3573 @<Subtract angle |z|...@>=
3574 k=1;
3575 while ( z>0 ){ 
3576   if ( z>=spec_atan[k] ) { 
3577     z=z-spec_atan[k]; t=x;
3578     x=t+y / two_to_the(k);
3579     y=y-t / two_to_the(k);
3580   }
3581   incr(k);
3582 }
3583 if ( y<0 ) y=0 /* this precaution may never be needed */
3584
3585 @ And now let's complete our collection of numeric utility routines
3586 by considering random number generation.
3587 \MP\ generates pseudo-random numbers with the additive scheme recommended
3588 in Section 3.6 of {\sl The Art of Computer Programming}; however, the
3589 results are random fractions between 0 and |fraction_one-1|, inclusive.
3590
3591 There's an auxiliary array |randoms| that contains 55 pseudo-random
3592 fractions. Using the recurrence $x_n=(x_{n-55}-x_{n-31})\bmod 2^{28}$,
3593 we generate batches of 55 new $x_n$'s at a time by calling |new_randoms|.
3594 The global variable |j_random| tells which element has most recently
3595 been consumed.
3596 The global variable |random_seed| was introduced in version 0.9,
3597 for the sole reason of stressing the fact that the initial value of the
3598 random seed is system-dependant. The initialization code below will initialize
3599 this variable to |(internal[mp_time] div unity)+internal[mp_day]|, but this 
3600 is not good enough on modern fast machines that are capable of running
3601 multiple MetaPost processes within the same second.
3602 @^system dependencies@>
3603
3604 @<Glob...@>=
3605 fraction randoms[55]; /* the last 55 random values generated */
3606 int j_random; /* the number of unused |randoms| */
3607
3608 @ @<Option variables@>=
3609 int random_seed; /* the default random seed */
3610
3611 @ @<Allocate or initialize ...@>=
3612 mp->random_seed = (scaled)opt->random_seed;
3613
3614 @ To consume a random fraction, the program below will say `|next_random|'
3615 and then it will fetch |randoms[j_random]|.
3616
3617 @d next_random { if ( mp->j_random==0 ) mp_new_randoms(mp);
3618   else decr(mp->j_random); }
3619
3620 @c 
3621 void mp_new_randoms (MP mp) {
3622   int k; /* index into |randoms| */
3623   fraction x; /* accumulator */
3624   for (k=0;k<=23;k++) { 
3625    x=mp->randoms[k]-mp->randoms[k+31];
3626     if ( x<0 ) x=x+fraction_one;
3627     mp->randoms[k]=x;
3628   }
3629   for (k=24;k<= 54;k++){ 
3630     x=mp->randoms[k]-mp->randoms[k-24];
3631     if ( x<0 ) x=x+fraction_one;
3632     mp->randoms[k]=x;
3633   }
3634   mp->j_random=54;
3635 }
3636
3637 @ @<Declarations@>=
3638 void mp_init_randoms (MP mp,scaled seed);
3639
3640 @ To initialize the |randoms| table, we call the following routine.
3641
3642 @c 
3643 void mp_init_randoms (MP mp,scaled seed) {
3644   fraction j,jj,k; /* more or less random integers */
3645   int i; /* index into |randoms| */
3646   j=abs(seed);
3647   while ( j>=fraction_one ) j=halfp(j);
3648   k=1;
3649   for (i=0;i<=54;i++ ){ 
3650     jj=k; k=j-k; j=jj;
3651     if ( k<0 ) k=k+fraction_one;
3652     mp->randoms[(i*21)% 55]=j;
3653   }
3654   mp_new_randoms(mp); 
3655   mp_new_randoms(mp); 
3656   mp_new_randoms(mp); /* ``warm up'' the array */
3657 }
3658
3659 @ To produce a uniform random number in the range |0<=u<x| or |0>=u>x|
3660 or |0=u=x|, given a |scaled| value~|x|, we proceed as shown here.
3661
3662 Note that the call of |take_fraction| will produce the values 0 and~|x|
3663 with about half the probability that it will produce any other particular
3664 values between 0 and~|x|, because it rounds its answers.
3665
3666 @c 
3667 scaled mp_unif_rand (MP mp,scaled x) {
3668   scaled y; /* trial value */
3669   next_random; y=mp_take_fraction(mp, abs(x),mp->randoms[mp->j_random]);
3670   if ( y==abs(x) ) return 0;
3671   else if ( x>0 ) return y;
3672   else return (-y);
3673 }
3674
3675 @ Finally, a normal deviate with mean zero and unit standard deviation
3676 can readily be obtained with the ratio method (Algorithm 3.4.1R in
3677 {\sl The Art of Computer Programming\/}).
3678
3679 @c 
3680 scaled mp_norm_rand (MP mp) {
3681   integer x,u,l; /* what the book would call $2^{16}X$, $2^{28}U$, and $-2^{24}\ln U$ */
3682   do { 
3683     do {  
3684       next_random;
3685       x=mp_take_fraction(mp, 112429,mp->randoms[mp->j_random]-fraction_half);
3686       /* $2^{16}\sqrt{8/e}\approx 112428.82793$ */
3687       next_random; u=mp->randoms[mp->j_random];
3688     } while (abs(x)>=u);
3689     x=mp_make_fraction(mp, x,u);
3690     l=139548960-mp_m_log(mp, u); /* $2^{24}\cdot12\ln2\approx139548959.6165$ */
3691   } while (mp_ab_vs_cd(mp, 1024,l,x,x)<0);
3692   return x;
3693 }
3694
3695 @* \[9] Packed data.
3696 In order to make efficient use of storage space, \MP\ bases its major data
3697 structures on a |memory_word|, which contains either a (signed) integer,
3698 possibly scaled, or a small number of fields that are one half or one
3699 quarter of the size used for storing integers.
3700
3701 If |x| is a variable of type |memory_word|, it contains up to four
3702 fields that can be referred to as follows:
3703 $$\vbox{\halign{\hfil#&#\hfil&#\hfil\cr
3704 |x|&.|int|&(an |integer|)\cr
3705 |x|&.|sc|\qquad&(a |scaled| integer)\cr
3706 |x.hh.lh|, |x.hh|&.|rh|&(two halfword fields)\cr
3707 |x.hh.b0|, |x.hh.b1|, |x.hh|&.|rh|&(two quarterword fields, one halfword
3708   field)\cr
3709 |x.qqqq.b0|, |x.qqqq.b1|, |x.qqqq|&.|b2|, |x.qqqq.b3|\hskip-100pt
3710   &\qquad\qquad\qquad(four quarterword fields)\cr}}$$
3711 This is somewhat cumbersome to write, and not very readable either, but
3712 macros will be used to make the notation shorter and more transparent.
3713 The code below gives a formal definition of |memory_word| and
3714 its subsidiary types, using packed variant records. \MP\ makes no
3715 assumptions about the relative positions of the fields within a word.
3716
3717 @d max_quarterword 0x3FFF /* largest allowable value in a |quarterword| */
3718 @d max_halfword 0xFFFFFFF /* largest allowable value in a |halfword| */
3719
3720 @ Here are the inequalities that the quarterword and halfword values
3721 must satisfy (or rather, the inequalities that they mustn't satisfy):
3722
3723 @<Check the ``constant''...@>=
3724 if (mp->ini_version) {
3725   if ( mp->mem_max!=mp->mem_top ) mp->bad=8;
3726 } else {
3727   if ( mp->mem_max<mp->mem_top ) mp->bad=8;
3728 }
3729 if ( max_quarterword<255 ) mp->bad=9;
3730 if ( max_halfword<65535 ) mp->bad=10;
3731 if ( max_quarterword>max_halfword ) mp->bad=11;
3732 if ( mp->mem_max>=max_halfword ) mp->bad=12;
3733 if ( mp->max_strings>max_halfword ) mp->bad=13;
3734
3735 @ The macros |qi| and |qo| are used for input to and output 
3736 from quarterwords. These are legacy macros.
3737 @^system dependencies@>
3738
3739 @d qo(A) (A) /* to read eight bits from a quarterword */
3740 @d qi(A) (A) /* to store eight bits in a quarterword */
3741
3742 @ The reader should study the following definitions closely:
3743 @^system dependencies@>
3744
3745 @d sc cint /* |scaled| data is equivalent to |integer| */
3746
3747 @<Types...@>=
3748 typedef short quarterword; /* 1/4 of a word */
3749 typedef int halfword; /* 1/2 of a word */
3750 typedef union {
3751   struct {
3752     halfword RH, LH;
3753   } v;
3754   struct { /* Make B0,B1 overlap the most significant bytes of LH.  */
3755     halfword junk;
3756     quarterword B0, B1;
3757   } u;
3758 } two_halves;
3759 typedef struct {
3760   struct {
3761     quarterword B2, B3, B0, B1;
3762   } u;
3763 } four_quarters;
3764 typedef union {
3765   two_halves hh;
3766   integer cint;
3767   four_quarters qqqq;
3768 } memory_word;
3769 #define b0 u.B0
3770 #define b1 u.B1
3771 #define b2 u.B2
3772 #define b3 u.B3
3773 #define rh v.RH
3774 #define lh v.LH
3775
3776 @ When debugging, we may want to print a |memory_word| without knowing
3777 what type it is; so we print it in all modes.
3778 @^debugging@>
3779
3780 @c 
3781 void mp_print_word (MP mp,memory_word w) {
3782   /* prints |w| in all ways */
3783   mp_print_int(mp, w.cint); mp_print_char(mp, ' ');
3784   mp_print_scaled(mp, w.sc); mp_print_char(mp, ' '); 
3785   mp_print_scaled(mp, w.sc / 010000); mp_print_ln(mp);
3786   mp_print_int(mp, w.hh.lh); mp_print_char(mp, '='); 
3787   mp_print_int(mp, w.hh.b0); mp_print_char(mp, ':');
3788   mp_print_int(mp, w.hh.b1); mp_print_char(mp, ';'); 
3789   mp_print_int(mp, w.hh.rh); mp_print_char(mp, ' ');
3790   mp_print_int(mp, w.qqqq.b0); mp_print_char(mp, ':'); 
3791   mp_print_int(mp, w.qqqq.b1); mp_print_char(mp, ':');
3792   mp_print_int(mp, w.qqqq.b2); mp_print_char(mp, ':'); 
3793   mp_print_int(mp, w.qqqq.b3);
3794 }
3795
3796
3797 @* \[10] Dynamic memory allocation.
3798
3799 The \MP\ system does nearly all of its own memory allocation, so that it
3800 can readily be transported into environments that do not have automatic
3801 facilities for strings, garbage collection, etc., and so that it can be in
3802 control of what error messages the user receives. The dynamic storage
3803 requirements of \MP\ are handled by providing a large array |mem| in
3804 which consecutive blocks of words are used as nodes by the \MP\ routines.
3805
3806 Pointer variables are indices into this array, or into another array
3807 called |eqtb| that will be explained later. A pointer variable might
3808 also be a special flag that lies outside the bounds of |mem|, so we
3809 allow pointers to assume any |halfword| value. The minimum memory
3810 index represents a null pointer.
3811
3812 @d null 0 /* the null pointer */
3813 @d mp_void (null+1) /* a null pointer different from |null| */
3814
3815
3816 @<Types...@>=
3817 typedef halfword pointer; /* a flag or a location in |mem| or |eqtb| */
3818
3819 @ The |mem| array is divided into two regions that are allocated separately,
3820 but the dividing line between these two regions is not fixed; they grow
3821 together until finding their ``natural'' size in a particular job.
3822 Locations less than or equal to |lo_mem_max| are used for storing
3823 variable-length records consisting of two or more words each. This region
3824 is maintained using an algorithm similar to the one described in exercise
3825 2.5--19 of {\sl The Art of Computer Programming}. However, no size field
3826 appears in the allocated nodes; the program is responsible for knowing the
3827 relevant size when a node is freed. Locations greater than or equal to
3828 |hi_mem_min| are used for storing one-word records; a conventional
3829 \.{AVAIL} stack is used for allocation in this region.
3830
3831 Locations of |mem| between |0| and |mem_top| may be dumped as part
3832 of preloaded format files, by the \.{INIMP} preprocessor.
3833 @.INIMP@>
3834 Production versions of \MP\ may extend the memory at the top end in order to
3835 provide more space; these locations, between |mem_top| and |mem_max|,
3836 are always used for single-word nodes.
3837
3838 The key pointers that govern |mem| allocation have a prescribed order:
3839 $$\hbox{|null=0<lo_mem_max<hi_mem_min<mem_top<=mem_end<=mem_max|.}$$
3840
3841 @<Glob...@>=
3842 memory_word *mem; /* the big dynamic storage area */
3843 pointer lo_mem_max; /* the largest location of variable-size memory in use */
3844 pointer hi_mem_min; /* the smallest location of one-word memory in use */
3845
3846
3847
3848 @d xfree(A) do { mp_xfree(A); A=NULL; } while (0)
3849 @d xrealloc(P,A,B) mp_xrealloc(mp,P,A,B)
3850 @d xmalloc(A,B)  mp_xmalloc(mp,A,B)
3851 @d xstrdup(A)  mp_xstrdup(mp,A)
3852 @d XREALLOC(a,b,c) a = xrealloc(a,(b+1),sizeof(c));
3853
3854 @<Declare helpers@>=
3855 void mp_xfree (void *x);
3856 void *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) ;
3857 void *mp_xmalloc (MP mp, size_t nmem, size_t size) ;
3858 char *mp_xstrdup(MP mp, const char *s);
3859
3860 @ The |max_size_test| guards against overflow, on the assumption that
3861 |size_t| is at least 31bits wide.
3862
3863 @d max_size_test 0x7FFFFFFF
3864
3865 @c
3866 void mp_xfree (void *x) {
3867   if (x!=NULL) free(x);
3868 }
3869 void  *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) {
3870   void *w ; 
3871   if ((max_size_test/size)<nmem) {
3872     do_fprintf(mp->err_out,"Memory size overflow!\n");
3873     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3874   }
3875   w = realloc (p,(nmem*size));
3876   if (w==NULL) {
3877     do_fprintf(mp->err_out,"Out of memory!\n");
3878     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3879   }
3880   return w;
3881 }
3882 void  *mp_xmalloc (MP mp, size_t nmem, size_t size) {
3883   void *w;
3884   if ((max_size_test/size)<nmem) {
3885     do_fprintf(mp->err_out,"Memory size overflow!\n");
3886     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3887   }
3888   w = malloc (nmem*size);
3889   if (w==NULL) {
3890     do_fprintf(mp->err_out,"Out of memory!\n");
3891     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3892   }
3893   return w;
3894 }
3895 char *mp_xstrdup(MP mp, const char *s) {
3896   char *w; 
3897   if (s==NULL)
3898     return NULL;
3899   w = strdup(s);
3900   if (w==NULL) {
3901     do_fprintf(mp->err_out,"Out of memory!\n");
3902     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3903   }
3904   return w;
3905 }
3906
3907
3908
3909 @<Allocate or initialize ...@>=
3910 mp->mem = xmalloc ((mp->mem_max+1),sizeof (memory_word));
3911 memset(mp->mem,0,(mp->mem_max+1)*sizeof (memory_word));
3912
3913 @ @<Dealloc variables@>=
3914 xfree(mp->mem);
3915
3916 @ Users who wish to study the memory requirements of particular applications can
3917 can use optional special features that keep track of current and
3918 maximum memory usage. When code between the delimiters |stat| $\ldots$
3919 |tats| is not ``commented out,'' \MP\ will run a bit slower but it will
3920 report these statistics when |mp_tracing_stats| is positive.
3921
3922 @<Glob...@>=
3923 integer var_used; integer dyn_used; /* how much memory is in use */
3924
3925 @ Let's consider the one-word memory region first, since it's the
3926 simplest. The pointer variable |mem_end| holds the highest-numbered location
3927 of |mem| that has ever been used. The free locations of |mem| that
3928 occur between |hi_mem_min| and |mem_end|, inclusive, are of type
3929 |two_halves|, and we write |info(p)| and |link(p)| for the |lh|
3930 and |rh| fields of |mem[p]| when it is of this type. The single-word
3931 free locations form a linked list
3932 $$|avail|,\;\hbox{|link(avail)|},\;\hbox{|link(link(avail))|},\;\ldots$$
3933 terminated by |null|.
3934
3935 @d link(A)   mp->mem[(A)].hh.rh /* the |link| field of a memory word */
3936 @d info(A)   mp->mem[(A)].hh.lh /* the |info| field of a memory word */
3937
3938 @<Glob...@>=
3939 pointer avail; /* head of the list of available one-word nodes */
3940 pointer mem_end; /* the last one-word node used in |mem| */
3941
3942 @ If one-word memory is exhausted, it might mean that the user has forgotten
3943 a token like `\&{enddef}' or `\&{endfor}'. We will define some procedures
3944 later that try to help pinpoint the trouble.
3945
3946 @c 
3947 @<Declare the procedure called |show_token_list|@>;
3948 @<Declare the procedure called |runaway|@>
3949
3950 @ The function |get_avail| returns a pointer to a new one-word node whose
3951 |link| field is null. However, \MP\ will halt if there is no more room left.
3952 @^inner loop@>
3953
3954 @c 
3955 pointer mp_get_avail (MP mp) { /* single-word node allocation */
3956   pointer p; /* the new node being got */
3957   p=mp->avail; /* get top location in the |avail| stack */
3958   if ( p!=null ) {
3959     mp->avail=link(mp->avail); /* and pop it off */
3960   } else if ( mp->mem_end<mp->mem_max ) { /* or go into virgin territory */
3961     incr(mp->mem_end); p=mp->mem_end;
3962   } else { 
3963     decr(mp->hi_mem_min); p=mp->hi_mem_min;
3964     if ( mp->hi_mem_min<=mp->lo_mem_max ) { 
3965       mp_runaway(mp); /* if memory is exhausted, display possible runaway text */
3966       mp_overflow(mp, "main memory size",mp->mem_max);
3967       /* quit; all one-word nodes are busy */
3968 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
3969     }
3970   }
3971   link(p)=null; /* provide an oft-desired initialization of the new node */
3972   incr(mp->dyn_used);/* maintain statistics */
3973   return p;
3974 };
3975
3976 @ Conversely, a one-word node is recycled by calling |free_avail|.
3977
3978 @d free_avail(A)  /* single-word node liberation */
3979   { link((A))=mp->avail; mp->avail=(A); decr(mp->dyn_used);  }
3980
3981 @ There's also a |fast_get_avail| routine, which saves the procedure-call
3982 overhead at the expense of extra programming. This macro is used in
3983 the places that would otherwise account for the most calls of |get_avail|.
3984 @^inner loop@>
3985
3986 @d fast_get_avail(A) { 
3987   (A)=mp->avail; /* avoid |get_avail| if possible, to save time */
3988   if ( (A)==null ) { (A)=mp_get_avail(mp); } 
3989   else { mp->avail=link((A)); link((A))=null;  incr(mp->dyn_used); }
3990   }
3991
3992 @ The available-space list that keeps track of the variable-size portion
3993 of |mem| is a nonempty, doubly-linked circular list of empty nodes,
3994 pointed to by the roving pointer |rover|.
3995
3996 Each empty node has size 2 or more; the first word contains the special
3997 value |max_halfword| in its |link| field and the size in its |info| field;
3998 the second word contains the two pointers for double linking.
3999
4000 Each nonempty node also has size 2 or more. Its first word is of type
4001 |two_halves|\kern-1pt, and its |link| field is never equal to |max_halfword|.
4002 Otherwise there is complete flexibility with respect to the contents
4003 of its other fields and its other words.
4004
4005 (We require |mem_max<max_halfword| because terrible things can happen
4006 when |max_halfword| appears in the |link| field of a nonempty node.)
4007
4008 @d empty_flag   max_halfword /* the |link| of an empty variable-size node */
4009 @d is_empty(A)   (link((A))==empty_flag) /* tests for empty node */
4010 @d node_size   info /* the size field in empty variable-size nodes */
4011 @d llink(A)   info((A)+1) /* left link in doubly-linked list of empty nodes */
4012 @d rlink(A)   link((A)+1) /* right link in doubly-linked list of empty nodes */
4013
4014 @<Glob...@>=
4015 pointer rover; /* points to some node in the list of empties */
4016
4017 @ A call to |get_node| with argument |s| returns a pointer to a new node
4018 of size~|s|, which must be 2~or more. The |link| field of the first word
4019 of this new node is set to null. An overflow stop occurs if no suitable
4020 space exists.
4021
4022 If |get_node| is called with $s=2^{30}$, it simply merges adjacent free
4023 areas and returns the value |max_halfword|.
4024
4025 @<Internal library declarations@>=
4026 pointer mp_get_node (MP mp,integer s) ;
4027
4028 @ @c 
4029 pointer mp_get_node (MP mp,integer s) { /* variable-size node allocation */
4030   pointer p; /* the node currently under inspection */
4031   pointer q;  /* the node physically after node |p| */
4032   integer r; /* the newly allocated node, or a candidate for this honor */
4033   integer t,tt; /* temporary registers */
4034 @^inner loop@>
4035  RESTART: 
4036   p=mp->rover; /* start at some free node in the ring */
4037   do {  
4038     @<Try to allocate within node |p| and its physical successors,
4039      and |goto found| if allocation was possible@>;
4040     if (rlink(p)==null || rlink(p)==p) {
4041       print_err("Free list garbled");
4042       help3("I found an entry in the list of free nodes that links")
4043        ("badly. I will try to ignore the broken link, but something")
4044        ("is seriously amiss. It is wise to warn the maintainers.")
4045           mp_error(mp);
4046       rlink(p)=mp->rover;
4047     }
4048         p=rlink(p); /* move to the next node in the ring */
4049   } while (p!=mp->rover); /* repeat until the whole list has been traversed */
4050   if ( s==010000000000 ) { 
4051     return max_halfword;
4052   };
4053   if ( mp->lo_mem_max+2<mp->hi_mem_min ) {
4054     if ( mp->lo_mem_max+2<=max_halfword ) {
4055       @<Grow more variable-size memory and |goto restart|@>;
4056     }
4057   }
4058   mp_overflow(mp, "main memory size",mp->mem_max);
4059   /* sorry, nothing satisfactory is left */
4060 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
4061 FOUND: 
4062   link(r)=null; /* this node is now nonempty */
4063   mp->var_used+=s; /* maintain usage statistics */
4064   return r;
4065 }
4066
4067 @ The lower part of |mem| grows by 1000 words at a time, unless
4068 we are very close to going under. When it grows, we simply link
4069 a new node into the available-space list. This method of controlled
4070 growth helps to keep the |mem| usage consecutive when \MP\ is
4071 implemented on ``virtual memory'' systems.
4072 @^virtual memory@>
4073
4074 @<Grow more variable-size memory and |goto restart|@>=
4075
4076   if ( mp->hi_mem_min-mp->lo_mem_max>=1998 ) {
4077     t=mp->lo_mem_max+1000;
4078   } else {
4079     t=mp->lo_mem_max+1+(mp->hi_mem_min-mp->lo_mem_max) / 2; 
4080     /* |lo_mem_max+2<=t<hi_mem_min| */
4081   }
4082   if ( t>max_halfword ) t=max_halfword;
4083   p=llink(mp->rover); q=mp->lo_mem_max; rlink(p)=q; llink(mp->rover)=q;
4084   rlink(q)=mp->rover; llink(q)=p; link(q)=empty_flag; 
4085   node_size(q)=t-mp->lo_mem_max;
4086   mp->lo_mem_max=t; link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4087   mp->rover=q; 
4088   goto RESTART;
4089 }
4090
4091 @ @<Try to allocate...@>=
4092 q=p+node_size(p); /* find the physical successor */
4093 while ( is_empty(q) ) { /* merge node |p| with node |q| */
4094   t=rlink(q); tt=llink(q);
4095 @^inner loop@>
4096   if ( q==mp->rover ) mp->rover=t;
4097   llink(t)=tt; rlink(tt)=t;
4098   q=q+node_size(q);
4099 }
4100 r=q-s;
4101 if ( r>p+1 ) {
4102   @<Allocate from the top of node |p| and |goto found|@>;
4103 }
4104 if ( r==p ) { 
4105   if ( rlink(p)!=p ) {
4106     @<Allocate entire node |p| and |goto found|@>;
4107   }
4108 }
4109 node_size(p)=q-p /* reset the size in case it grew */
4110
4111 @ @<Allocate from the top...@>=
4112
4113   node_size(p)=r-p; /* store the remaining size */
4114   mp->rover=p; /* start searching here next time */
4115   goto FOUND;
4116 }
4117
4118 @ Here we delete node |p| from the ring, and let |rover| rove around.
4119
4120 @<Allocate entire...@>=
4121
4122   mp->rover=rlink(p); t=llink(p);
4123   llink(mp->rover)=t; rlink(t)=mp->rover;
4124   goto FOUND;
4125 }
4126
4127 @ Conversely, when some variable-size node |p| of size |s| is no longer needed,
4128 the operation |free_node(p,s)| will make its words available, by inserting
4129 |p| as a new empty node just before where |rover| now points.
4130
4131 @<Internal library declarations@>=
4132 void mp_free_node (MP mp, pointer p, halfword s) ;
4133
4134 @ @c 
4135 void mp_free_node (MP mp, pointer p, halfword s) { /* variable-size node
4136   liberation */
4137   pointer q; /* |llink(rover)| */
4138   node_size(p)=s; link(p)=empty_flag;
4139 @^inner loop@>
4140   q=llink(mp->rover); llink(p)=q; rlink(p)=mp->rover; /* set both links */
4141   llink(mp->rover)=p; rlink(q)=p; /* insert |p| into the ring */
4142   mp->var_used-=s; /* maintain statistics */
4143 }
4144
4145 @ Just before \.{INIMP} writes out the memory, it sorts the doubly linked
4146 available space list. The list is probably very short at such times, so a
4147 simple insertion sort is used. The smallest available location will be
4148 pointed to by |rover|, the next-smallest by |rlink(rover)|, etc.
4149
4150 @c 
4151 void mp_sort_avail (MP mp) { /* sorts the available variable-size nodes
4152   by location */
4153   pointer p,q,r; /* indices into |mem| */
4154   pointer old_rover; /* initial |rover| setting */
4155   p=mp_get_node(mp, 010000000000); /* merge adjacent free areas */
4156   p=rlink(mp->rover); rlink(mp->rover)=max_halfword; old_rover=mp->rover;
4157   while ( p!=old_rover ) {
4158     @<Sort |p| into the list starting at |rover|
4159      and advance |p| to |rlink(p)|@>;
4160   }
4161   p=mp->rover;
4162   while ( rlink(p)!=max_halfword ) { 
4163     llink(rlink(p))=p; p=rlink(p);
4164   };
4165   rlink(p)=mp->rover; llink(mp->rover)=p;
4166 }
4167
4168 @ The following |while| loop is guaranteed to
4169 terminate, since the list that starts at
4170 |rover| ends with |max_halfword| during the sorting procedure.
4171
4172 @<Sort |p|...@>=
4173 if ( p<mp->rover ) { 
4174   q=p; p=rlink(q); rlink(q)=mp->rover; mp->rover=q;
4175 } else  { 
4176   q=mp->rover;
4177   while ( rlink(q)<p ) q=rlink(q);
4178   r=rlink(p); rlink(p)=rlink(q); rlink(q)=p; p=r;
4179 }
4180
4181 @* \[11] Memory layout.
4182 Some areas of |mem| are dedicated to fixed usage, since static allocation is
4183 more efficient than dynamic allocation when we can get away with it. For
4184 example, locations |0| to |1| are always used to store a
4185 two-word dummy token whose second word is zero.
4186 The following macro definitions accomplish the static allocation by giving
4187 symbolic names to the fixed positions. Static variable-size nodes appear
4188 in locations |0| through |lo_mem_stat_max|, and static single-word nodes
4189 appear in locations |hi_mem_stat_min| through |mem_top|, inclusive.
4190
4191 @d null_dash (2) /* the first two words are reserved for a null value */
4192 @d dep_head (null_dash+3) /* we will define |dash_node_size=3| */
4193 @d zero_val (dep_head+2) /* two words for a permanently zero value */
4194 @d temp_val (zero_val+2) /* two words for a temporary value node */
4195 @d end_attr temp_val /* we use |end_attr+2| only */
4196 @d inf_val (end_attr+2) /* and |inf_val+1| only */
4197 @d test_pen (inf_val+2)
4198   /* nine words for a pen used when testing the turning number */
4199 @d bad_vardef (test_pen+9) /* two words for \&{vardef} error recovery */
4200 @d lo_mem_stat_max (bad_vardef+1)  /* largest statically
4201   allocated word in the variable-size |mem| */
4202 @#
4203 @d sentinel mp->mem_top /* end of sorted lists */
4204 @d temp_head (mp->mem_top-1) /* head of a temporary list of some kind */
4205 @d hold_head (mp->mem_top-2) /* head of a temporary list of another kind */
4206 @d spec_head (mp->mem_top-3) /* head of a list of unprocessed \&{special} items */
4207 @d hi_mem_stat_min (mp->mem_top-3) /* smallest statically allocated word in
4208   the one-word |mem| */
4209
4210 @ The following code gets the dynamic part of |mem| off to a good start,
4211 when \MP\ is initializing itself the slow way.
4212
4213 @<Initialize table entries (done by \.{INIMP} only)@>=
4214 @^data structure assumptions@>
4215 mp->rover=lo_mem_stat_max+1; /* initialize the dynamic memory */
4216 link(mp->rover)=empty_flag;
4217 node_size(mp->rover)=1000; /* which is a 1000-word available node */
4218 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
4219 mp->lo_mem_max=mp->rover+1000; 
4220 link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4221 for (k=hi_mem_stat_min;k<=(int)mp->mem_top;k++) {
4222   mp->mem[k]=mp->mem[mp->lo_mem_max]; /* clear list heads */
4223 }
4224 mp->avail=null; mp->mem_end=mp->mem_top;
4225 mp->hi_mem_min=hi_mem_stat_min; /* initialize the one-word memory */
4226 mp->var_used=lo_mem_stat_max+1; 
4227 mp->dyn_used=mp->mem_top+1-(hi_mem_stat_min);  /* initialize statistics */
4228 @<Initialize a pen at |test_pen| so that it fits in nine words@>;
4229
4230 @ The procedure |flush_list(p)| frees an entire linked list of one-word
4231 nodes that starts at a given position, until coming to |sentinel| or a
4232 pointer that is not in the one-word region. Another procedure,
4233 |flush_node_list|, frees an entire linked list of one-word and two-word
4234 nodes, until coming to a |null| pointer.
4235 @^inner loop@>
4236
4237 @c 
4238 void mp_flush_list (MP mp,pointer p) { /* makes list of single-word nodes  available */
4239   pointer q,r; /* list traversers */
4240   if ( p>=mp->hi_mem_min ) if ( p!=sentinel ) { 
4241     r=p;
4242     do {  
4243       q=r; r=link(r); 
4244       decr(mp->dyn_used);
4245       if ( r<mp->hi_mem_min ) break;
4246     } while (r!=sentinel);
4247   /* now |q| is the last node on the list */
4248     link(q)=mp->avail; mp->avail=p;
4249   }
4250 }
4251 @#
4252 void mp_flush_node_list (MP mp,pointer p) {
4253   pointer q; /* the node being recycled */
4254   while ( p!=null ){ 
4255     q=p; p=link(p);
4256     if ( q<mp->hi_mem_min ) 
4257       mp_free_node(mp, q,2);
4258     else 
4259       free_avail(q);
4260   }
4261 }
4262
4263 @ If \MP\ is extended improperly, the |mem| array might get screwed up.
4264 For example, some pointers might be wrong, or some ``dead'' nodes might not
4265 have been freed when the last reference to them disappeared. Procedures
4266 |check_mem| and |search_mem| are available to help diagnose such
4267 problems. These procedures make use of two arrays called |free| and
4268 |was_free| that are present only if \MP's debugging routines have
4269 been included. (You may want to decrease the size of |mem| while you
4270 @^debugging@>
4271 are debugging.)
4272
4273 Because |boolean|s are typedef-d as ints, it is better to use
4274 unsigned chars here.
4275
4276 @<Glob...@>=
4277 unsigned char *free; /* free cells */
4278 unsigned char *was_free; /* previously free cells */
4279 pointer was_mem_end; pointer was_lo_max; pointer was_hi_min;
4280   /* previous |mem_end|, |lo_mem_max|,and |hi_mem_min| */
4281 boolean panicking; /* do we want to check memory constantly? */
4282
4283 @ @<Allocate or initialize ...@>=
4284 mp->free = xmalloc ((mp->mem_max+1),sizeof (unsigned char));
4285 mp->was_free = xmalloc ((mp->mem_max+1), sizeof (unsigned char));
4286
4287 @ @<Dealloc variables@>=
4288 xfree(mp->free);
4289 xfree(mp->was_free);
4290
4291 @ @<Allocate or ...@>=
4292 mp->was_mem_end=0; /* indicate that everything was previously free */
4293 mp->was_lo_max=0; mp->was_hi_min=mp->mem_max;
4294 mp->panicking=false;
4295
4296 @ @<Declare |mp_reallocate| functions@>=
4297 void mp_reallocate_memory(MP mp, int l) ;
4298
4299 @ @c
4300 void mp_reallocate_memory(MP mp, int l) {
4301    XREALLOC(mp->free,     l, unsigned char);
4302    XREALLOC(mp->was_free, l, unsigned char);
4303    if (mp->mem) {
4304          int newarea = l-mp->mem_max;
4305      XREALLOC(mp->mem,      l, memory_word);
4306      memset (mp->mem+(mp->mem_max+1),0,sizeof(memory_word)*(newarea));
4307    } else {
4308      XREALLOC(mp->mem,      l, memory_word);
4309      memset(mp->mem,0,sizeof(memory_word)*(l+1));
4310    }
4311    mp->mem_max = l;
4312    if (mp->ini_version) 
4313      mp->mem_top = l;
4314 }
4315
4316
4317
4318 @ Procedure |check_mem| makes sure that the available space lists of
4319 |mem| are well formed, and it optionally prints out all locations
4320 that are reserved now but were free the last time this procedure was called.
4321
4322 @c 
4323 void mp_check_mem (MP mp,boolean print_locs ) {
4324   pointer p,q,r; /* current locations of interest in |mem| */
4325   boolean clobbered; /* is something amiss? */
4326   for (p=0;p<=mp->lo_mem_max;p++) {
4327     mp->free[p]=false; /* you can probably do this faster */
4328   }
4329   for (p=mp->hi_mem_min;p<= mp->mem_end;p++) {
4330     mp->free[p]=false; /* ditto */
4331   }
4332   @<Check single-word |avail| list@>;
4333   @<Check variable-size |avail| list@>;
4334   @<Check flags of unavailable nodes@>;
4335   @<Check the list of linear dependencies@>;
4336   if ( print_locs ) {
4337     @<Print newly busy locations@>;
4338   }
4339   memcpy(mp->was_free,mp->free, sizeof(char)*(mp->mem_end+1));
4340   mp->was_mem_end=mp->mem_end; 
4341   mp->was_lo_max=mp->lo_mem_max; 
4342   mp->was_hi_min=mp->hi_mem_min;
4343 }
4344
4345 @ @<Check single-word...@>=
4346 p=mp->avail; q=null; clobbered=false;
4347 while ( p!=null ) { 
4348   if ( (p>mp->mem_end)||(p<mp->hi_mem_min) ) clobbered=true;
4349   else if ( mp->free[p] ) clobbered=true;
4350   if ( clobbered ) { 
4351     mp_print_nl(mp, "AVAIL list clobbered at ");
4352 @.AVAIL list clobbered...@>
4353     mp_print_int(mp, q); break;
4354   }
4355   mp->free[p]=true; q=p; p=link(q);
4356 }
4357
4358 @ @<Check variable-size...@>=
4359 p=mp->rover; q=null; clobbered=false;
4360 do {  
4361   if ( (p>=mp->lo_mem_max)||(p<0) ) clobbered=true;
4362   else if ( (rlink(p)>=mp->lo_mem_max)||(rlink(p)<0) ) clobbered=true;
4363   else if (  !(is_empty(p))||(node_size(p)<2)||
4364    (p+node_size(p)>mp->lo_mem_max)|| (llink(rlink(p))!=p) ) clobbered=true;
4365   if ( clobbered ) { 
4366     mp_print_nl(mp, "Double-AVAIL list clobbered at ");
4367 @.Double-AVAIL list clobbered...@>
4368     mp_print_int(mp, q); break;
4369   }
4370   for (q=p;q<=p+node_size(p)-1;q++) { /* mark all locations free */
4371     if ( mp->free[q] ) { 
4372       mp_print_nl(mp, "Doubly free location at ");
4373 @.Doubly free location...@>
4374       mp_print_int(mp, q); break;
4375     }
4376     mp->free[q]=true;
4377   }
4378   q=p; p=rlink(p);
4379 } while (p!=mp->rover)
4380
4381
4382 @ @<Check flags...@>=
4383 p=0;
4384 while ( p<=mp->lo_mem_max ) { /* node |p| should not be empty */
4385   if ( is_empty(p) ) {
4386     mp_print_nl(mp, "Bad flag at "); mp_print_int(mp, p);
4387 @.Bad flag...@>
4388   }
4389   while ( (p<=mp->lo_mem_max) && ! mp->free[p] ) incr(p);
4390   while ( (p<=mp->lo_mem_max) && mp->free[p] ) incr(p);
4391 }
4392
4393 @ @<Print newly busy...@>=
4394
4395   @<Do intialization required before printing new busy locations@>;
4396   mp_print_nl(mp, "New busy locs:");
4397 @.New busy locs@>
4398   for (p=0;p<= mp->lo_mem_max;p++ ) {
4399     if ( ! mp->free[p] && ((p>mp->was_lo_max) || mp->was_free[p]) ) {
4400       @<Indicate that |p| is a new busy location@>;
4401     }
4402   }
4403   for (p=mp->hi_mem_min;p<=mp->mem_end;p++ ) {
4404     if ( ! mp->free[p] &&
4405         ((p<mp->was_hi_min) || (p>mp->was_mem_end) || mp->was_free[p]) ) {
4406       @<Indicate that |p| is a new busy location@>;
4407     }
4408   }
4409   @<Finish printing new busy locations@>;
4410 }
4411
4412 @ There might be many new busy locations so we are careful to print contiguous
4413 blocks compactly.  During this operation |q| is the last new busy location and
4414 |r| is the start of the block containing |q|.
4415
4416 @<Indicate that |p| is a new busy location@>=
4417
4418   if ( p>q+1 ) { 
4419     if ( q>r ) { 
4420       mp_print(mp, ".."); mp_print_int(mp, q);
4421     }
4422     mp_print_char(mp, ' '); mp_print_int(mp, p);
4423     r=p;
4424   }
4425   q=p;
4426 }
4427
4428 @ @<Do intialization required before printing new busy locations@>=
4429 q=mp->mem_max; r=mp->mem_max
4430
4431 @ @<Finish printing new busy locations@>=
4432 if ( q>r ) { 
4433   mp_print(mp, ".."); mp_print_int(mp, q);
4434 }
4435
4436 @ The |search_mem| procedure attempts to answer the question ``Who points
4437 to node~|p|?'' In doing so, it fetches |link| and |info| fields of |mem|
4438 that might not be of type |two_halves|. Strictly speaking, this is
4439 undefined, and it can lead to ``false drops'' (words that seem to
4440 point to |p| purely by coincidence). But for debugging purposes, we want
4441 to rule out the places that do {\sl not\/} point to |p|, so a few false
4442 drops are tolerable.
4443
4444 @c
4445 void mp_search_mem (MP mp, pointer p) { /* look for pointers to |p| */
4446   integer q; /* current position being searched */
4447   for (q=0;q<=mp->lo_mem_max;q++) { 
4448     if ( link(q)==p ){ 
4449       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4450     }
4451     if ( info(q)==p ) { 
4452       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4453     }
4454   }
4455   for (q=mp->hi_mem_min;q<=mp->mem_end;q++) {
4456     if ( link(q)==p ) {
4457       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4458     }
4459     if ( info(q)==p ) {
4460       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4461     }
4462   }
4463   @<Search |eqtb| for equivalents equal to |p|@>;
4464 }
4465
4466 @* \[12] The command codes.
4467 Before we can go much further, we need to define symbolic names for the internal
4468 code numbers that represent the various commands obeyed by \MP. These codes
4469 are somewhat arbitrary, but not completely so. For example,
4470 some codes have been made adjacent so that |case| statements in the
4471 program need not consider cases that are widely spaced, or so that |case|
4472 statements can be replaced by |if| statements. A command can begin an
4473 expression if and only if its code lies between |min_primary_command| and
4474 |max_primary_command|, inclusive. The first token of a statement that doesn't
4475 begin with an expression has a command code between |min_command| and
4476 |max_statement_command|, inclusive. Anything less than |min_command| is
4477 eliminated during macro expansions, and anything no more than |max_pre_command|
4478 is eliminated when expanding \TeX\ material.  Ranges such as
4479 |min_secondary_command..max_secondary_command| are used when parsing
4480 expressions, but the relative ordering within such a range is generally not
4481 critical.
4482
4483 The ordering of the highest-numbered commands
4484 (|comma<semicolon<end_group<stop|) is crucial for the parsing and
4485 error-recovery methods of this program as is the ordering |if_test<fi_or_else|
4486 for the smallest two commands.  The ordering is also important in the ranges
4487 |numeric_token..plus_or_minus| and |left_brace..ampersand|.
4488
4489 At any rate, here is the list, for future reference.
4490
4491 @d start_tex 1 /* begin \TeX\ material (\&{btex}, \&{verbatimtex}) */
4492 @d etex_marker 2 /* end \TeX\ material (\&{etex}) */
4493 @d mpx_break 3 /* stop reading an \.{MPX} file (\&{mpxbreak}) */
4494 @d max_pre_command mpx_break
4495 @d if_test 4 /* conditional text (\&{if}) */
4496 @d fi_or_else 5 /* delimiters for conditionals (\&{elseif}, \&{else}, \&{fi} */
4497 @d input 6 /* input a source file (\&{input}, \&{endinput}) */
4498 @d iteration 7 /* iterate (\&{for}, \&{forsuffixes}, \&{forever}, \&{endfor}) */
4499 @d repeat_loop 8 /* special command substituted for \&{endfor} */
4500 @d exit_test 9 /* premature exit from a loop (\&{exitif}) */
4501 @d relax 10 /* do nothing (\.{\char`\\}) */
4502 @d scan_tokens 11 /* put a string into the input buffer */
4503 @d expand_after 12 /* look ahead one token */
4504 @d defined_macro 13 /* a macro defined by the user */
4505 @d min_command (defined_macro+1)
4506 @d save_command 14 /* save a list of tokens (\&{save}) */
4507 @d interim_command 15 /* save an internal quantity (\&{interim}) */
4508 @d let_command 16 /* redefine a symbolic token (\&{let}) */
4509 @d new_internal 17 /* define a new internal quantity (\&{newinternal}) */
4510 @d macro_def 18 /* define a macro (\&{def}, \&{vardef}, etc.) */
4511 @d ship_out_command 19 /* output a character (\&{shipout}) */
4512 @d add_to_command 20 /* add to edges (\&{addto}) */
4513 @d bounds_command 21  /* add bounding path to edges (\&{setbounds}, \&{clip}) */
4514 @d tfm_command 22 /* command for font metric info (\&{ligtable}, etc.) */
4515 @d protection_command 23 /* set protection flag (\&{outer}, \&{inner}) */
4516 @d show_command 24 /* diagnostic output (\&{show}, \&{showvariable}, etc.) */
4517 @d mode_command 25 /* set interaction level (\&{batchmode}, etc.) */
4518 @d mp_random_seed 26 /* initialize random number generator (\&{randomseed}) */
4519 @d message_command 27 /* communicate to user (\&{message}, \&{errmessage}) */
4520 @d every_job_command 28 /* designate a starting token (\&{everyjob}) */
4521 @d delimiters 29 /* define a pair of delimiters (\&{delimiters}) */
4522 @d special_command 30 /* output special info (\&{special})
4523                        or font map info (\&{fontmapfile}, \&{fontmapline}) */
4524 @d write_command 31 /* write text to a file (\&{write}) */
4525 @d type_name 32 /* declare a type (\&{numeric}, \&{pair}, etc. */
4526 @d max_statement_command type_name
4527 @d min_primary_command type_name
4528 @d left_delimiter 33 /* the left delimiter of a matching pair */
4529 @d begin_group 34 /* beginning of a group (\&{begingroup}) */
4530 @d nullary 35 /* an operator without arguments (e.g., \&{normaldeviate}) */
4531 @d unary 36 /* an operator with one argument (e.g., \&{sqrt}) */
4532 @d str_op 37 /* convert a suffix to a string (\&{str}) */
4533 @d cycle 38 /* close a cyclic path (\&{cycle}) */
4534 @d primary_binary 39 /* binary operation taking `\&{of}' (e.g., \&{point}) */
4535 @d capsule_token 40 /* a value that has been put into a token list */
4536 @d string_token 41 /* a string constant (e.g., |"hello"|) */
4537 @d internal_quantity 42 /* internal numeric parameter (e.g., \&{pausing}) */
4538 @d min_suffix_token internal_quantity
4539 @d tag_token 43 /* a symbolic token without a primitive meaning */
4540 @d numeric_token 44 /* a numeric constant (e.g., \.{3.14159}) */
4541 @d max_suffix_token numeric_token
4542 @d plus_or_minus 45 /* either `\.+' or `\.-' */
4543 @d max_primary_command plus_or_minus /* should also be |numeric_token+1| */
4544 @d min_tertiary_command plus_or_minus
4545 @d tertiary_secondary_macro 46 /* a macro defined by \&{secondarydef} */
4546 @d tertiary_binary 47 /* an operator at the tertiary level (e.g., `\.{++}') */
4547 @d max_tertiary_command tertiary_binary
4548 @d left_brace 48 /* the operator `\.{\char`\{}' */
4549 @d min_expression_command left_brace
4550 @d path_join 49 /* the operator `\.{..}' */
4551 @d ampersand 50 /* the operator `\.\&' */
4552 @d expression_tertiary_macro 51 /* a macro defined by \&{tertiarydef} */
4553 @d expression_binary 52 /* an operator at the expression level (e.g., `\.<') */
4554 @d equals 53 /* the operator `\.=' */
4555 @d max_expression_command equals
4556 @d and_command 54 /* the operator `\&{and}' */
4557 @d min_secondary_command and_command
4558 @d secondary_primary_macro 55 /* a macro defined by \&{primarydef} */
4559 @d slash 56 /* the operator `\./' */
4560 @d secondary_binary 57 /* an operator at the binary level (e.g., \&{shifted}) */
4561 @d max_secondary_command secondary_binary
4562 @d param_type 58 /* type of parameter (\&{primary}, \&{expr}, \&{suffix}, etc.) */
4563 @d controls 59 /* specify control points explicitly (\&{controls}) */
4564 @d tension 60 /* specify tension between knots (\&{tension}) */
4565 @d at_least 61 /* bounded tension value (\&{atleast}) */
4566 @d curl_command 62 /* specify curl at an end knot (\&{curl}) */
4567 @d macro_special 63 /* special macro operators (\&{quote}, \.{\#\AT!}, etc.) */
4568 @d right_delimiter 64 /* the right delimiter of a matching pair */
4569 @d left_bracket 65 /* the operator `\.[' */
4570 @d right_bracket 66 /* the operator `\.]' */
4571 @d right_brace 67 /* the operator `\.{\char`\}}' */
4572 @d with_option 68 /* option for filling (\&{withpen}, \&{withweight}, etc.) */
4573 @d thing_to_add 69
4574   /* variant of \&{addto} (\&{contour}, \&{doublepath}, \&{also}) */
4575 @d of_token 70 /* the operator `\&{of}' */
4576 @d to_token 71 /* the operator `\&{to}' */
4577 @d step_token 72 /* the operator `\&{step}' */
4578 @d until_token 73 /* the operator `\&{until}' */
4579 @d within_token 74 /* the operator `\&{within}' */
4580 @d lig_kern_token 75
4581   /* the operators `\&{kern}' and `\.{=:}' and `\.{=:\char'174}, etc. */
4582 @d assignment 76 /* the operator `\.{:=}' */
4583 @d skip_to 77 /* the operation `\&{skipto}' */
4584 @d bchar_label 78 /* the operator `\.{\char'174\char'174:}' */
4585 @d double_colon 79 /* the operator `\.{::}' */
4586 @d colon 80 /* the operator `\.:' */
4587 @#
4588 @d comma 81 /* the operator `\.,', must be |colon+1| */
4589 @d end_of_statement (mp->cur_cmd>comma)
4590 @d semicolon 82 /* the operator `\.;', must be |comma+1| */
4591 @d end_group 83 /* end a group (\&{endgroup}), must be |semicolon+1| */
4592 @d stop 84 /* end a job (\&{end}, \&{dump}), must be |end_group+1| */
4593 @d max_command_code stop
4594 @d outer_tag (max_command_code+1) /* protection code added to command code */
4595
4596 @<Types...@>=
4597 typedef int command_code;
4598
4599 @ Variables and capsules in \MP\ have a variety of ``types,''
4600 distinguished by the code numbers defined here. These numbers are also
4601 not completely arbitrary.  Things that get expanded must have types
4602 |>mp_independent|; a type remaining after expansion is numeric if and only if
4603 its code number is at least |numeric_type|; objects containing numeric
4604 parts must have types between |transform_type| and |pair_type|;
4605 all other types must be smaller than |transform_type|; and among the types
4606 that are not unknown or vacuous, the smallest two must be |boolean_type|
4607 and |string_type| in that order.
4608  
4609 @d undefined 0 /* no type has been declared */
4610 @d unknown_tag 1 /* this constant is added to certain type codes below */
4611 @d unknown_types mp_unknown_boolean: case mp_unknown_string:
4612   case mp_unknown_pen: case mp_unknown_picture: case mp_unknown_path
4613
4614 @<Types...@>=
4615 enum mp_variable_type {
4616 mp_vacuous=1, /* no expression was present */
4617 mp_boolean_type, /* \&{boolean} with a known value */
4618 mp_unknown_boolean,
4619 mp_string_type, /* \&{string} with a known value */
4620 mp_unknown_string,
4621 mp_pen_type, /* \&{pen} with a known value */
4622 mp_unknown_pen,
4623 mp_path_type, /* \&{path} with a known value */
4624 mp_unknown_path,
4625 mp_picture_type, /* \&{picture} with a known value */
4626 mp_unknown_picture,
4627 mp_transform_type, /* \&{transform} variable or capsule */
4628 mp_color_type, /* \&{color} variable or capsule */
4629 mp_cmykcolor_type, /* \&{cmykcolor} variable or capsule */
4630 mp_pair_type, /* \&{pair} variable or capsule */
4631 mp_numeric_type, /* variable that has been declared \&{numeric} but not used */
4632 mp_known, /* \&{numeric} with a known value */
4633 mp_dependent, /* a linear combination with |fraction| coefficients */
4634 mp_proto_dependent, /* a linear combination with |scaled| coefficients */
4635 mp_independent, /* \&{numeric} with unknown value */
4636 mp_token_list, /* variable name or suffix argument or text argument */
4637 mp_structured, /* variable with subscripts and attributes */
4638 mp_unsuffixed_macro, /* variable defined with \&{vardef} but no \.{\AT!\#} */
4639 mp_suffixed_macro /* variable defined with \&{vardef} and \.{\AT!\#} */
4640 } ;
4641
4642 @ @<Declarations@>=
4643 void mp_print_type (MP mp,small_number t) ;
4644
4645 @ @<Basic printing procedures@>=
4646 void mp_print_type (MP mp,small_number t) { 
4647   switch (t) {
4648   case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
4649   case mp_boolean_type:mp_print(mp, "boolean"); break;
4650   case mp_unknown_boolean:mp_print(mp, "unknown boolean"); break;
4651   case mp_string_type:mp_print(mp, "string"); break;
4652   case mp_unknown_string:mp_print(mp, "unknown string"); break;
4653   case mp_pen_type:mp_print(mp, "pen"); break;
4654   case mp_unknown_pen:mp_print(mp, "unknown pen"); break;
4655   case mp_path_type:mp_print(mp, "path"); break;
4656   case mp_unknown_path:mp_print(mp, "unknown path"); break;
4657   case mp_picture_type:mp_print(mp, "picture"); break;
4658   case mp_unknown_picture:mp_print(mp, "unknown picture"); break;
4659   case mp_transform_type:mp_print(mp, "transform"); break;
4660   case mp_color_type:mp_print(mp, "color"); break;
4661   case mp_cmykcolor_type:mp_print(mp, "cmykcolor"); break;
4662   case mp_pair_type:mp_print(mp, "pair"); break;
4663   case mp_known:mp_print(mp, "known numeric"); break;
4664   case mp_dependent:mp_print(mp, "dependent"); break;
4665   case mp_proto_dependent:mp_print(mp, "proto-dependent"); break;
4666   case mp_numeric_type:mp_print(mp, "numeric"); break;
4667   case mp_independent:mp_print(mp, "independent"); break;
4668   case mp_token_list:mp_print(mp, "token list"); break;
4669   case mp_structured:mp_print(mp, "mp_structured"); break;
4670   case mp_unsuffixed_macro:mp_print(mp, "unsuffixed macro"); break;
4671   case mp_suffixed_macro:mp_print(mp, "suffixed macro"); break;
4672   default: mp_print(mp, "undefined"); break;
4673   }
4674 }
4675
4676 @ Values inside \MP\ are stored in two-word nodes that have a |name_type|
4677 as well as a |type|. The possibilities for |name_type| are defined
4678 here; they will be explained in more detail later.
4679
4680 @<Types...@>=
4681 enum mp_name_type {
4682  mp_root=0, /* |name_type| at the top level of a variable */
4683  mp_saved_root, /* same, when the variable has been saved */
4684  mp_structured_root, /* |name_type| where a |mp_structured| branch occurs */
4685  mp_subscr, /* |name_type| in a subscript node */
4686  mp_attr, /* |name_type| in an attribute node */
4687  mp_x_part_sector, /* |name_type| in the \&{xpart} of a node */
4688  mp_y_part_sector, /* |name_type| in the \&{ypart} of a node */
4689  mp_xx_part_sector, /* |name_type| in the \&{xxpart} of a node */
4690  mp_xy_part_sector, /* |name_type| in the \&{xypart} of a node */
4691  mp_yx_part_sector, /* |name_type| in the \&{yxpart} of a node */
4692  mp_yy_part_sector, /* |name_type| in the \&{yypart} of a node */
4693  mp_red_part_sector, /* |name_type| in the \&{redpart} of a node */
4694  mp_green_part_sector, /* |name_type| in the \&{greenpart} of a node */
4695  mp_blue_part_sector, /* |name_type| in the \&{bluepart} of a node */
4696  mp_cyan_part_sector, /* |name_type| in the \&{redpart} of a node */
4697  mp_magenta_part_sector, /* |name_type| in the \&{greenpart} of a node */
4698  mp_yellow_part_sector, /* |name_type| in the \&{bluepart} of a node */
4699  mp_black_part_sector, /* |name_type| in the \&{greenpart} of a node */
4700  mp_grey_part_sector, /* |name_type| in the \&{bluepart} of a node */
4701  mp_capsule, /* |name_type| in stashed-away subexpressions */
4702  mp_token  /* |name_type| in a numeric token or string token */
4703 };
4704
4705 @ Primitive operations that produce values have a secondary identification
4706 code in addition to their command code; it's something like genera and species.
4707 For example, `\.*' has the command code |primary_binary|, and its
4708 secondary identification is |times|. The secondary codes start at 30 so that
4709 they don't overlap with the type codes; some type codes (e.g., |mp_string_type|)
4710 are used as operators as well as type identifications.  The relative values
4711 are not critical, except for |true_code..false_code|, |or_op..and_op|,
4712 and |filled_op..bounded_op|.  The restrictions are that
4713 |and_op-false_code=or_op-true_code|, that the ordering of
4714 |x_part...blue_part| must match that of |x_part_sector..mp_blue_part_sector|,
4715 and the ordering of |filled_op..bounded_op| must match that of the code
4716 values they test for.
4717
4718 @d true_code 30 /* operation code for \.{true} */
4719 @d false_code 31 /* operation code for \.{false} */
4720 @d null_picture_code 32 /* operation code for \.{nullpicture} */
4721 @d null_pen_code 33 /* operation code for \.{nullpen} */
4722 @d job_name_op 34 /* operation code for \.{jobname} */
4723 @d read_string_op 35 /* operation code for \.{readstring} */
4724 @d pen_circle 36 /* operation code for \.{pencircle} */
4725 @d normal_deviate 37 /* operation code for \.{normaldeviate} */
4726 @d read_from_op 38 /* operation code for \.{readfrom} */
4727 @d close_from_op 39 /* operation code for \.{closefrom} */
4728 @d odd_op 40 /* operation code for \.{odd} */
4729 @d known_op 41 /* operation code for \.{known} */
4730 @d unknown_op 42 /* operation code for \.{unknown} */
4731 @d not_op 43 /* operation code for \.{not} */
4732 @d decimal 44 /* operation code for \.{decimal} */
4733 @d reverse 45 /* operation code for \.{reverse} */
4734 @d make_path_op 46 /* operation code for \.{makepath} */
4735 @d make_pen_op 47 /* operation code for \.{makepen} */
4736 @d oct_op 48 /* operation code for \.{oct} */
4737 @d hex_op 49 /* operation code for \.{hex} */
4738 @d ASCII_op 50 /* operation code for \.{ASCII} */
4739 @d char_op 51 /* operation code for \.{char} */
4740 @d length_op 52 /* operation code for \.{length} */
4741 @d turning_op 53 /* operation code for \.{turningnumber} */
4742 @d color_model_part 54 /* operation code for \.{colormodel} */
4743 @d x_part 55 /* operation code for \.{xpart} */
4744 @d y_part 56 /* operation code for \.{ypart} */
4745 @d xx_part 57 /* operation code for \.{xxpart} */
4746 @d xy_part 58 /* operation code for \.{xypart} */
4747 @d yx_part 59 /* operation code for \.{yxpart} */
4748 @d yy_part 60 /* operation code for \.{yypart} */
4749 @d red_part 61 /* operation code for \.{redpart} */
4750 @d green_part 62 /* operation code for \.{greenpart} */
4751 @d blue_part 63 /* operation code for \.{bluepart} */
4752 @d cyan_part 64 /* operation code for \.{cyanpart} */
4753 @d magenta_part 65 /* operation code for \.{magentapart} */
4754 @d yellow_part 66 /* operation code for \.{yellowpart} */
4755 @d black_part 67 /* operation code for \.{blackpart} */
4756 @d grey_part 68 /* operation code for \.{greypart} */
4757 @d font_part 69 /* operation code for \.{fontpart} */
4758 @d text_part 70 /* operation code for \.{textpart} */
4759 @d path_part 71 /* operation code for \.{pathpart} */
4760 @d pen_part 72 /* operation code for \.{penpart} */
4761 @d dash_part 73 /* operation code for \.{dashpart} */
4762 @d sqrt_op 74 /* operation code for \.{sqrt} */
4763 @d m_exp_op 75 /* operation code for \.{mexp} */
4764 @d m_log_op 76 /* operation code for \.{mlog} */
4765 @d sin_d_op 77 /* operation code for \.{sind} */
4766 @d cos_d_op 78 /* operation code for \.{cosd} */
4767 @d floor_op 79 /* operation code for \.{floor} */
4768 @d uniform_deviate 80 /* operation code for \.{uniformdeviate} */
4769 @d char_exists_op 81 /* operation code for \.{charexists} */
4770 @d font_size 82 /* operation code for \.{fontsize} */
4771 @d ll_corner_op 83 /* operation code for \.{llcorner} */
4772 @d lr_corner_op 84 /* operation code for \.{lrcorner} */
4773 @d ul_corner_op 85 /* operation code for \.{ulcorner} */
4774 @d ur_corner_op 86 /* operation code for \.{urcorner} */
4775 @d arc_length 87 /* operation code for \.{arclength} */
4776 @d angle_op 88 /* operation code for \.{angle} */
4777 @d cycle_op 89 /* operation code for \.{cycle} */
4778 @d filled_op 90 /* operation code for \.{filled} */
4779 @d stroked_op 91 /* operation code for \.{stroked} */
4780 @d textual_op 92 /* operation code for \.{textual} */
4781 @d clipped_op 93 /* operation code for \.{clipped} */
4782 @d bounded_op 94 /* operation code for \.{bounded} */
4783 @d plus 95 /* operation code for \.+ */
4784 @d minus 96 /* operation code for \.- */
4785 @d times 97 /* operation code for \.* */
4786 @d over 98 /* operation code for \./ */
4787 @d pythag_add 99 /* operation code for \.{++} */
4788 @d pythag_sub 100 /* operation code for \.{+-+} */
4789 @d or_op 101 /* operation code for \.{or} */
4790 @d and_op 102 /* operation code for \.{and} */
4791 @d less_than 103 /* operation code for \.< */
4792 @d less_or_equal 104 /* operation code for \.{<=} */
4793 @d greater_than 105 /* operation code for \.> */
4794 @d greater_or_equal 106 /* operation code for \.{>=} */
4795 @d equal_to 107 /* operation code for \.= */
4796 @d unequal_to 108 /* operation code for \.{<>} */
4797 @d concatenate 109 /* operation code for \.\& */
4798 @d rotated_by 110 /* operation code for \.{rotated} */
4799 @d slanted_by 111 /* operation code for \.{slanted} */
4800 @d scaled_by 112 /* operation code for \.{scaled} */
4801 @d shifted_by 113 /* operation code for \.{shifted} */
4802 @d transformed_by 114 /* operation code for \.{transformed} */
4803 @d x_scaled 115 /* operation code for \.{xscaled} */
4804 @d y_scaled 116 /* operation code for \.{yscaled} */
4805 @d z_scaled 117 /* operation code for \.{zscaled} */
4806 @d in_font 118 /* operation code for \.{infont} */
4807 @d intersect 119 /* operation code for \.{intersectiontimes} */
4808 @d double_dot 120 /* operation code for improper \.{..} */
4809 @d substring_of 121 /* operation code for \.{substring} */
4810 @d min_of substring_of
4811 @d subpath_of 122 /* operation code for \.{subpath} */
4812 @d direction_time_of 123 /* operation code for \.{directiontime} */
4813 @d point_of 124 /* operation code for \.{point} */
4814 @d precontrol_of 125 /* operation code for \.{precontrol} */
4815 @d postcontrol_of 126 /* operation code for \.{postcontrol} */
4816 @d pen_offset_of 127 /* operation code for \.{penoffset} */
4817 @d arc_time_of 128 /* operation code for \.{arctime} */
4818 @d mp_version 129 /* operation code for \.{mpversion} */
4819 @d envelope_of 130 /* operation code for \.{envelope} */
4820
4821 @c void mp_print_op (MP mp,quarterword c) { 
4822   if (c<=mp_numeric_type ) {
4823     mp_print_type(mp, c);
4824   } else {
4825     switch (c) {
4826     case true_code:mp_print(mp, "true"); break;
4827     case false_code:mp_print(mp, "false"); break;
4828     case null_picture_code:mp_print(mp, "nullpicture"); break;
4829     case null_pen_code:mp_print(mp, "nullpen"); break;
4830     case job_name_op:mp_print(mp, "jobname"); break;
4831     case read_string_op:mp_print(mp, "readstring"); break;
4832     case pen_circle:mp_print(mp, "pencircle"); break;
4833     case normal_deviate:mp_print(mp, "normaldeviate"); break;
4834     case read_from_op:mp_print(mp, "readfrom"); break;
4835     case close_from_op:mp_print(mp, "closefrom"); break;
4836     case odd_op:mp_print(mp, "odd"); break;
4837     case known_op:mp_print(mp, "known"); break;
4838     case unknown_op:mp_print(mp, "unknown"); break;
4839     case not_op:mp_print(mp, "not"); break;
4840     case decimal:mp_print(mp, "decimal"); break;
4841     case reverse:mp_print(mp, "reverse"); break;
4842     case make_path_op:mp_print(mp, "makepath"); break;
4843     case make_pen_op:mp_print(mp, "makepen"); break;
4844     case oct_op:mp_print(mp, "oct"); break;
4845     case hex_op:mp_print(mp, "hex"); break;
4846     case ASCII_op:mp_print(mp, "ASCII"); break;
4847     case char_op:mp_print(mp, "char"); break;
4848     case length_op:mp_print(mp, "length"); break;
4849     case turning_op:mp_print(mp, "turningnumber"); break;
4850     case x_part:mp_print(mp, "xpart"); break;
4851     case y_part:mp_print(mp, "ypart"); break;
4852     case xx_part:mp_print(mp, "xxpart"); break;
4853     case xy_part:mp_print(mp, "xypart"); break;
4854     case yx_part:mp_print(mp, "yxpart"); break;
4855     case yy_part:mp_print(mp, "yypart"); break;
4856     case red_part:mp_print(mp, "redpart"); break;
4857     case green_part:mp_print(mp, "greenpart"); break;
4858     case blue_part:mp_print(mp, "bluepart"); break;
4859     case cyan_part:mp_print(mp, "cyanpart"); break;
4860     case magenta_part:mp_print(mp, "magentapart"); break;
4861     case yellow_part:mp_print(mp, "yellowpart"); break;
4862     case black_part:mp_print(mp, "blackpart"); break;
4863     case grey_part:mp_print(mp, "greypart"); break;
4864     case color_model_part:mp_print(mp, "colormodel"); break;
4865     case font_part:mp_print(mp, "fontpart"); break;
4866     case text_part:mp_print(mp, "textpart"); break;
4867     case path_part:mp_print(mp, "pathpart"); break;
4868     case pen_part:mp_print(mp, "penpart"); break;
4869     case dash_part:mp_print(mp, "dashpart"); break;
4870     case sqrt_op:mp_print(mp, "sqrt"); break;
4871     case m_exp_op:mp_print(mp, "mexp"); break;
4872     case m_log_op:mp_print(mp, "mlog"); break;
4873     case sin_d_op:mp_print(mp, "sind"); break;
4874     case cos_d_op:mp_print(mp, "cosd"); break;
4875     case floor_op:mp_print(mp, "floor"); break;
4876     case uniform_deviate:mp_print(mp, "uniformdeviate"); break;
4877     case char_exists_op:mp_print(mp, "charexists"); break;
4878     case font_size:mp_print(mp, "fontsize"); break;
4879     case ll_corner_op:mp_print(mp, "llcorner"); break;
4880     case lr_corner_op:mp_print(mp, "lrcorner"); break;
4881     case ul_corner_op:mp_print(mp, "ulcorner"); break;
4882     case ur_corner_op:mp_print(mp, "urcorner"); break;
4883     case arc_length:mp_print(mp, "arclength"); break;
4884     case angle_op:mp_print(mp, "angle"); break;
4885     case cycle_op:mp_print(mp, "cycle"); break;
4886     case filled_op:mp_print(mp, "filled"); break;
4887     case stroked_op:mp_print(mp, "stroked"); break;
4888     case textual_op:mp_print(mp, "textual"); break;
4889     case clipped_op:mp_print(mp, "clipped"); break;
4890     case bounded_op:mp_print(mp, "bounded"); break;
4891     case plus:mp_print_char(mp, '+'); break;
4892     case minus:mp_print_char(mp, '-'); break;
4893     case times:mp_print_char(mp, '*'); break;
4894     case over:mp_print_char(mp, '/'); break;
4895     case pythag_add:mp_print(mp, "++"); break;
4896     case pythag_sub:mp_print(mp, "+-+"); break;
4897     case or_op:mp_print(mp, "or"); break;
4898     case and_op:mp_print(mp, "and"); break;
4899     case less_than:mp_print_char(mp, '<'); break;
4900     case less_or_equal:mp_print(mp, "<="); break;
4901     case greater_than:mp_print_char(mp, '>'); break;
4902     case greater_or_equal:mp_print(mp, ">="); break;
4903     case equal_to:mp_print_char(mp, '='); break;
4904     case unequal_to:mp_print(mp, "<>"); break;
4905     case concatenate:mp_print(mp, "&"); break;
4906     case rotated_by:mp_print(mp, "rotated"); break;
4907     case slanted_by:mp_print(mp, "slanted"); break;
4908     case scaled_by:mp_print(mp, "scaled"); break;
4909     case shifted_by:mp_print(mp, "shifted"); break;
4910     case transformed_by:mp_print(mp, "transformed"); break;
4911     case x_scaled:mp_print(mp, "xscaled"); break;
4912     case y_scaled:mp_print(mp, "yscaled"); break;
4913     case z_scaled:mp_print(mp, "zscaled"); break;
4914     case in_font:mp_print(mp, "infont"); break;
4915     case intersect:mp_print(mp, "intersectiontimes"); break;
4916     case substring_of:mp_print(mp, "substring"); break;
4917     case subpath_of:mp_print(mp, "subpath"); break;
4918     case direction_time_of:mp_print(mp, "directiontime"); break;
4919     case point_of:mp_print(mp, "point"); break;
4920     case precontrol_of:mp_print(mp, "precontrol"); break;
4921     case postcontrol_of:mp_print(mp, "postcontrol"); break;
4922     case pen_offset_of:mp_print(mp, "penoffset"); break;
4923     case arc_time_of:mp_print(mp, "arctime"); break;
4924     case mp_version:mp_print(mp, "mpversion"); break;
4925     case envelope_of:mp_print(mp, "envelope"); break;
4926     default: mp_print(mp, ".."); break;
4927     }
4928   }
4929 }
4930
4931 @ \MP\ also has a bunch of internal parameters that a user might want to
4932 fuss with. Every such parameter has an identifying code number, defined here.
4933
4934 @<Types...@>=
4935 enum mp_given_internal {
4936   mp_tracing_titles=1, /* show titles online when they appear */
4937   mp_tracing_equations, /* show each variable when it becomes known */
4938   mp_tracing_capsules, /* show capsules too */
4939   mp_tracing_choices, /* show the control points chosen for paths */
4940   mp_tracing_specs, /* show path subdivision prior to filling with polygonal a pen */
4941   mp_tracing_commands, /* show commands and operations before they are performed */
4942   mp_tracing_restores, /* show when a variable or internal is restored */
4943   mp_tracing_macros, /* show macros before they are expanded */
4944   mp_tracing_output, /* show digitized edges as they are output */
4945   mp_tracing_stats, /* show memory usage at end of job */
4946   mp_tracing_lost_chars, /* show characters that aren't \&{infont} */
4947   mp_tracing_online, /* show long diagnostics on terminal and in the log file */
4948   mp_year, /* the current year (e.g., 1984) */
4949   mp_month, /* the current month (e.g, 3 $\equiv$ March) */
4950   mp_day, /* the current day of the month */
4951   mp_time, /* the number of minutes past midnight when this job started */
4952   mp_char_code, /* the number of the next character to be output */
4953   mp_char_ext, /* the extension code of the next character to be output */
4954   mp_char_wd, /* the width of the next character to be output */
4955   mp_char_ht, /* the height of the next character to be output */
4956   mp_char_dp, /* the depth of the next character to be output */
4957   mp_char_ic, /* the italic correction of the next character to be output */
4958   mp_design_size, /* the unit of measure used for |mp_char_wd..mp_char_ic|, in points */
4959   mp_pausing, /* positive to display lines on the terminal before they are read */
4960   mp_showstopping, /* positive to stop after each \&{show} command */
4961   mp_fontmaking, /* positive if font metric output is to be produced */
4962   mp_linejoin, /* as in \ps: 0 for mitered, 1 for round, 2 for beveled */
4963   mp_linecap, /* as in \ps: 0 for butt, 1 for round, 2 for square */
4964   mp_miterlimit, /* controls miter length as in \ps */
4965   mp_warning_check, /* controls error message when variable value is large */
4966   mp_boundary_char, /* the right boundary character for ligatures */
4967   mp_prologues, /* positive to output conforming PostScript using built-in fonts */
4968   mp_true_corners, /* positive to make \&{llcorner} etc. ignore \&{setbounds} */
4969   mp_default_color_model, /* the default color model for unspecified items */
4970   mp_restore_clip_color,
4971   mp_procset, /* wether or not create PostScript command shortcuts */
4972   mp_gtroffmode,  /* whether the user specified |-troff| on the command line */
4973 };
4974
4975 @
4976
4977 @d max_given_internal mp_gtroffmode
4978
4979 @<Glob...@>=
4980 scaled *internal;  /* the values of internal quantities */
4981 char **int_name;  /* their names */
4982 int int_ptr;  /* the maximum internal quantity defined so far */
4983 int max_internal; /* current maximum number of internal quantities */
4984
4985 @ @<Option variables@>=
4986 int troff_mode; 
4987
4988 @ @<Allocate or initialize ...@>=
4989 mp->max_internal=2*max_given_internal;
4990 mp->internal = xmalloc ((mp->max_internal+1), sizeof(scaled));
4991 mp->int_name = xmalloc ((mp->max_internal+1), sizeof(char *));
4992 mp->troff_mode=(opt->troff_mode>0 ? true : false);
4993
4994 @ @<Exported function ...@>=
4995 int mp_troff_mode(MP mp);
4996
4997 @ @c
4998 int mp_troff_mode(MP mp) { return mp->troff_mode; }
4999
5000 @ @<Set initial ...@>=
5001 for (k=0;k<= mp->max_internal; k++ ) { 
5002    mp->internal[k]=0; 
5003    mp->int_name[k]=NULL; 
5004 }
5005 mp->int_ptr=max_given_internal;
5006
5007 @ The symbolic names for internal quantities are put into \MP's hash table
5008 by using a routine called |primitive|, which will be defined later. Let us
5009 enter them now, so that we don't have to list all those names again
5010 anywhere else.
5011
5012 @<Put each of \MP's primitives into the hash table@>=
5013 mp_primitive(mp, "tracingtitles",internal_quantity,mp_tracing_titles);
5014 @:tracingtitles_}{\&{tracingtitles} primitive@>
5015 mp_primitive(mp, "tracingequations",internal_quantity,mp_tracing_equations);
5016 @:mp_tracing_equations_}{\&{tracingequations} primitive@>
5017 mp_primitive(mp, "tracingcapsules",internal_quantity,mp_tracing_capsules);
5018 @:mp_tracing_capsules_}{\&{tracingcapsules} primitive@>
5019 mp_primitive(mp, "tracingchoices",internal_quantity,mp_tracing_choices);
5020 @:mp_tracing_choices_}{\&{tracingchoices} primitive@>
5021 mp_primitive(mp, "tracingspecs",internal_quantity,mp_tracing_specs);
5022 @:mp_tracing_specs_}{\&{tracingspecs} primitive@>
5023 mp_primitive(mp, "tracingcommands",internal_quantity,mp_tracing_commands);
5024 @:mp_tracing_commands_}{\&{tracingcommands} primitive@>
5025 mp_primitive(mp, "tracingrestores",internal_quantity,mp_tracing_restores);
5026 @:mp_tracing_restores_}{\&{tracingrestores} primitive@>
5027 mp_primitive(mp, "tracingmacros",internal_quantity,mp_tracing_macros);
5028 @:mp_tracing_macros_}{\&{tracingmacros} primitive@>
5029 mp_primitive(mp, "tracingoutput",internal_quantity,mp_tracing_output);
5030 @:mp_tracing_output_}{\&{tracingoutput} primitive@>
5031 mp_primitive(mp, "tracingstats",internal_quantity,mp_tracing_stats);
5032 @:mp_tracing_stats_}{\&{tracingstats} primitive@>
5033 mp_primitive(mp, "tracinglostchars",internal_quantity,mp_tracing_lost_chars);
5034 @:mp_tracing_lost_chars_}{\&{tracinglostchars} primitive@>
5035 mp_primitive(mp, "tracingonline",internal_quantity,mp_tracing_online);
5036 @:mp_tracing_online_}{\&{tracingonline} primitive@>
5037 mp_primitive(mp, "year",internal_quantity,mp_year);
5038 @:mp_year_}{\&{year} primitive@>
5039 mp_primitive(mp, "month",internal_quantity,mp_month);
5040 @:mp_month_}{\&{month} primitive@>
5041 mp_primitive(mp, "day",internal_quantity,mp_day);
5042 @:mp_day_}{\&{day} primitive@>
5043 mp_primitive(mp, "time",internal_quantity,mp_time);
5044 @:time_}{\&{time} primitive@>
5045 mp_primitive(mp, "charcode",internal_quantity,mp_char_code);
5046 @:mp_char_code_}{\&{charcode} primitive@>
5047 mp_primitive(mp, "charext",internal_quantity,mp_char_ext);
5048 @:mp_char_ext_}{\&{charext} primitive@>
5049 mp_primitive(mp, "charwd",internal_quantity,mp_char_wd);
5050 @:mp_char_wd_}{\&{charwd} primitive@>
5051 mp_primitive(mp, "charht",internal_quantity,mp_char_ht);
5052 @:mp_char_ht_}{\&{charht} primitive@>
5053 mp_primitive(mp, "chardp",internal_quantity,mp_char_dp);
5054 @:mp_char_dp_}{\&{chardp} primitive@>
5055 mp_primitive(mp, "charic",internal_quantity,mp_char_ic);
5056 @:mp_char_ic_}{\&{charic} primitive@>
5057 mp_primitive(mp, "designsize",internal_quantity,mp_design_size);
5058 @:mp_design_size_}{\&{designsize} primitive@>
5059 mp_primitive(mp, "pausing",internal_quantity,mp_pausing);
5060 @:mp_pausing_}{\&{pausing} primitive@>
5061 mp_primitive(mp, "showstopping",internal_quantity,mp_showstopping);
5062 @:mp_showstopping_}{\&{showstopping} primitive@>
5063 mp_primitive(mp, "fontmaking",internal_quantity,mp_fontmaking);
5064 @:mp_fontmaking_}{\&{fontmaking} primitive@>
5065 mp_primitive(mp, "linejoin",internal_quantity,mp_linejoin);
5066 @:mp_linejoin_}{\&{linejoin} primitive@>
5067 mp_primitive(mp, "linecap",internal_quantity,mp_linecap);
5068 @:mp_linecap_}{\&{linecap} primitive@>
5069 mp_primitive(mp, "miterlimit",internal_quantity,mp_miterlimit);
5070 @:mp_miterlimit_}{\&{miterlimit} primitive@>
5071 mp_primitive(mp, "warningcheck",internal_quantity,mp_warning_check);
5072 @:mp_warning_check_}{\&{warningcheck} primitive@>
5073 mp_primitive(mp, "boundarychar",internal_quantity,mp_boundary_char);
5074 @:mp_boundary_char_}{\&{boundarychar} primitive@>
5075 mp_primitive(mp, "prologues",internal_quantity,mp_prologues);
5076 @:mp_prologues_}{\&{prologues} primitive@>
5077 mp_primitive(mp, "truecorners",internal_quantity,mp_true_corners);
5078 @:mp_true_corners_}{\&{truecorners} primitive@>
5079 mp_primitive(mp, "mpprocset",internal_quantity,mp_procset);
5080 @:mp_procset_}{\&{mpprocset} primitive@>
5081 mp_primitive(mp, "troffmode",internal_quantity,mp_gtroffmode);
5082 @:troffmode_}{\&{troffmode} primitive@>
5083 mp_primitive(mp, "defaultcolormodel",internal_quantity,mp_default_color_model);
5084 @:mp_default_color_model_}{\&{defaultcolormodel} primitive@>
5085 mp_primitive(mp, "restoreclipcolor",internal_quantity,mp_restore_clip_color);
5086 @:mp_restore_clip_color_}{\&{restoreclipcolor} primitive@>
5087
5088 @ Colors can be specified in four color models. In the special
5089 case of |no_model|, MetaPost does not output any color operator to
5090 the postscript output.
5091
5092 Note: these values are passed directly on to |with_option|. This only
5093 works because the other possible values passed to |with_option| are
5094 8 and 10 respectively (from |with_pen| and |with_picture|).
5095
5096 There is a first state, that is only used for |gs_colormodel|. It flags
5097 the fact that there has not been any kind of color specification by
5098 the user so far in the game.
5099
5100 @<Types...@>=
5101 enum mp_color_model {
5102   mp_no_model=1,
5103   mp_grey_model=3,
5104   mp_rgb_model=5,
5105   mp_cmyk_model=7,
5106   mp_uninitialized_model=9,
5107 };
5108
5109
5110 @ @<Initialize table entries (done by \.{INIMP} only)@>=
5111 mp->internal[mp_default_color_model]=(mp_rgb_model*unity);
5112 mp->internal[mp_restore_clip_color]=unity;
5113
5114 @ Well, we do have to list the names one more time, for use in symbolic
5115 printouts.
5116
5117 @<Initialize table...@>=
5118 mp->int_name[mp_tracing_titles]=xstrdup("tracingtitles");
5119 mp->int_name[mp_tracing_equations]=xstrdup("tracingequations");
5120 mp->int_name[mp_tracing_capsules]=xstrdup("tracingcapsules");
5121 mp->int_name[mp_tracing_choices]=xstrdup("tracingchoices");
5122 mp->int_name[mp_tracing_specs]=xstrdup("tracingspecs");
5123 mp->int_name[mp_tracing_commands]=xstrdup("tracingcommands");
5124 mp->int_name[mp_tracing_restores]=xstrdup("tracingrestores");
5125 mp->int_name[mp_tracing_macros]=xstrdup("tracingmacros");
5126 mp->int_name[mp_tracing_output]=xstrdup("tracingoutput");
5127 mp->int_name[mp_tracing_stats]=xstrdup("tracingstats");
5128 mp->int_name[mp_tracing_lost_chars]=xstrdup("tracinglostchars");
5129 mp->int_name[mp_tracing_online]=xstrdup("tracingonline");
5130 mp->int_name[mp_year]=xstrdup("year");
5131 mp->int_name[mp_month]=xstrdup("month");
5132 mp->int_name[mp_day]=xstrdup("day");
5133 mp->int_name[mp_time]=xstrdup("time");
5134 mp->int_name[mp_char_code]=xstrdup("charcode");
5135 mp->int_name[mp_char_ext]=xstrdup("charext");
5136 mp->int_name[mp_char_wd]=xstrdup("charwd");
5137 mp->int_name[mp_char_ht]=xstrdup("charht");
5138 mp->int_name[mp_char_dp]=xstrdup("chardp");
5139 mp->int_name[mp_char_ic]=xstrdup("charic");
5140 mp->int_name[mp_design_size]=xstrdup("designsize");
5141 mp->int_name[mp_pausing]=xstrdup("pausing");
5142 mp->int_name[mp_showstopping]=xstrdup("showstopping");
5143 mp->int_name[mp_fontmaking]=xstrdup("fontmaking");
5144 mp->int_name[mp_linejoin]=xstrdup("linejoin");
5145 mp->int_name[mp_linecap]=xstrdup("linecap");
5146 mp->int_name[mp_miterlimit]=xstrdup("miterlimit");
5147 mp->int_name[mp_warning_check]=xstrdup("warningcheck");
5148 mp->int_name[mp_boundary_char]=xstrdup("boundarychar");
5149 mp->int_name[mp_prologues]=xstrdup("prologues");
5150 mp->int_name[mp_true_corners]=xstrdup("truecorners");
5151 mp->int_name[mp_default_color_model]=xstrdup("defaultcolormodel");
5152 mp->int_name[mp_procset]=xstrdup("mpprocset");
5153 mp->int_name[mp_gtroffmode]=xstrdup("troffmode");
5154 mp->int_name[mp_restore_clip_color]=xstrdup("restoreclipcolor");
5155
5156 @ The following procedure, which is called just before \MP\ initializes its
5157 input and output, establishes the initial values of the date and time.
5158 @^system dependencies@>
5159
5160 Note that the values are |scaled| integers. Hence \MP\ can no longer
5161 be used after the year 32767.
5162
5163 @c 
5164 void mp_fix_date_and_time (MP mp) { 
5165   time_t clock = time ((time_t *) 0);
5166   struct tm *tmptr = localtime (&clock);
5167   mp->internal[mp_time]=
5168       (tmptr->tm_hour*60+tmptr->tm_min)*unity; /* minutes since midnight */
5169   mp->internal[mp_day]=(tmptr->tm_mday)*unity; /* fourth day of the month */
5170   mp->internal[mp_month]=(tmptr->tm_mon+1)*unity; /* seventh month of the year */
5171   mp->internal[mp_year]=(tmptr->tm_year+1900)*unity; /* Anno Domini */
5172 }
5173
5174 @ @<Declarations@>=
5175 void mp_fix_date_and_time (MP mp) ;
5176
5177 @ \MP\ is occasionally supposed to print diagnostic information that
5178 goes only into the transcript file, unless |mp_tracing_online| is positive.
5179 Now that we have defined |mp_tracing_online| we can define
5180 two routines that adjust the destination of print commands:
5181
5182 @<Declarations@>=
5183 void mp_begin_diagnostic (MP mp) ;
5184 void mp_end_diagnostic (MP mp,boolean blank_line);
5185 void mp_print_diagnostic (MP mp, char *s, char *t, boolean nuline) ;
5186
5187 @ @<Basic printing...@>=
5188 @<Declare a function called |true_line|@>;
5189 void mp_begin_diagnostic (MP mp) { /* prepare to do some tracing */
5190   mp->old_setting=mp->selector;
5191   if ((mp->internal[mp_tracing_online]<=0)&&(mp->selector==term_and_log)){ 
5192     decr(mp->selector);
5193     if ( mp->history==mp_spotless ) mp->history=mp_warning_issued;
5194   }
5195 }
5196 @#
5197 void mp_end_diagnostic (MP mp,boolean blank_line) {
5198   /* restore proper conditions after tracing */
5199   mp_print_nl(mp, "");
5200   if ( blank_line ) mp_print_ln(mp);
5201   mp->selector=mp->old_setting;
5202 }
5203
5204
5205
5206 @<Glob...@>=
5207 unsigned int old_setting;
5208
5209 @ We will occasionally use |begin_diagnostic| in connection with line-number
5210 printing, as follows. (The parameter |s| is typically |"Path"| or
5211 |"Cycle spec"|, etc.)
5212
5213 @<Basic printing...@>=
5214 void mp_print_diagnostic (MP mp, char *s, char *t, boolean nuline) { 
5215   mp_begin_diagnostic(mp);
5216   if ( nuline ) mp_print_nl(mp, s); else mp_print(mp, s);
5217   mp_print(mp, " at line "); 
5218   mp_print_int(mp, mp_true_line(mp));
5219   mp_print(mp, t); mp_print_char(mp, ':');
5220 }
5221
5222 @ The 256 |ASCII_code| characters are grouped into classes by means of
5223 the |char_class| table. Individual class numbers have no semantic
5224 or syntactic significance, except in a few instances defined here.
5225 There's also |max_class|, which can be used as a basis for additional
5226 class numbers in nonstandard extensions of \MP.
5227
5228 @d digit_class 0 /* the class number of \.{0123456789} */
5229 @d period_class 1 /* the class number of `\..' */
5230 @d space_class 2 /* the class number of spaces and nonstandard characters */
5231 @d percent_class 3 /* the class number of `\.\%' */
5232 @d string_class 4 /* the class number of `\."' */
5233 @d right_paren_class 8 /* the class number of `\.)' */
5234 @d isolated_classes 5: case 6: case 7: case 8 /* characters that make length-one tokens only */
5235 @d letter_class 9 /* letters and the underline character */
5236 @d left_bracket_class 17 /* `\.[' */
5237 @d right_bracket_class 18 /* `\.]' */
5238 @d invalid_class 20 /* bad character in the input */
5239 @d max_class 20 /* the largest class number */
5240
5241 @<Glob...@>=
5242 int char_class[256]; /* the class numbers */
5243
5244 @ If changes are made to accommodate non-ASCII character sets, they should
5245 follow the guidelines in Appendix~C of {\sl The {\logos METAFONT\/}book}.
5246 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
5247 @^system dependencies@>
5248
5249 @<Set initial ...@>=
5250 for (k='0';k<='9';k++) 
5251   mp->char_class[k]=digit_class;
5252 mp->char_class['.']=period_class;
5253 mp->char_class[' ']=space_class;
5254 mp->char_class['%']=percent_class;
5255 mp->char_class['"']=string_class;
5256 mp->char_class[',']=5;
5257 mp->char_class[';']=6;
5258 mp->char_class['(']=7;
5259 mp->char_class[')']=right_paren_class;
5260 for (k='A';k<= 'Z';k++ )
5261   mp->char_class[k]=letter_class;
5262 for (k='a';k<='z';k++) 
5263   mp->char_class[k]=letter_class;
5264 mp->char_class['_']=letter_class;
5265 mp->char_class['<']=10;
5266 mp->char_class['=']=10;
5267 mp->char_class['>']=10;
5268 mp->char_class[':']=10;
5269 mp->char_class['|']=10;
5270 mp->char_class['`']=11;
5271 mp->char_class['\'']=11;
5272 mp->char_class['+']=12;
5273 mp->char_class['-']=12;
5274 mp->char_class['/']=13;
5275 mp->char_class['*']=13;
5276 mp->char_class['\\']=13;
5277 mp->char_class['!']=14;
5278 mp->char_class['?']=14;
5279 mp->char_class['#']=15;
5280 mp->char_class['&']=15;
5281 mp->char_class['@@']=15;
5282 mp->char_class['$']=15;
5283 mp->char_class['^']=16;
5284 mp->char_class['~']=16;
5285 mp->char_class['[']=left_bracket_class;
5286 mp->char_class[']']=right_bracket_class;
5287 mp->char_class['{']=19;
5288 mp->char_class['}']=19;
5289 for (k=0;k<' ';k++)
5290   mp->char_class[k]=invalid_class;
5291 mp->char_class['\t']=space_class;
5292 mp->char_class['\f']=space_class;
5293 for (k=127;k<=255;k++)
5294   mp->char_class[k]=invalid_class;
5295
5296 @* \[13] The hash table.
5297 Symbolic tokens are stored and retrieved by means of a fairly standard hash
5298 table algorithm called the method of ``coalescing lists'' (cf.\ Algorithm 6.4C
5299 in {\sl The Art of Computer Programming\/}). Once a symbolic token enters the
5300 table, it is never removed.
5301
5302 The actual sequence of characters forming a symbolic token is
5303 stored in the |str_pool| array together with all the other strings. An
5304 auxiliary array |hash| consists of items with two halfword fields per
5305 word. The first of these, called |next(p)|, points to the next identifier
5306 belonging to the same coalesced list as the identifier corresponding to~|p|;
5307 and the other, called |text(p)|, points to the |str_start| entry for
5308 |p|'s identifier. If position~|p| of the hash table is empty, we have
5309 |text(p)=0|; if position |p| is either empty or the end of a coalesced
5310 hash list, we have |next(p)=0|.
5311
5312 An auxiliary pointer variable called |hash_used| is maintained in such a
5313 way that all locations |p>=hash_used| are nonempty. The global variable
5314 |st_count| tells how many symbolic tokens have been defined, if statistics
5315 are being kept.
5316
5317 The first 256 locations of |hash| are reserved for symbols of length one.
5318
5319 There's a parallel array called |eqtb| that contains the current equivalent
5320 values of each symbolic token. The entries of this array consist of
5321 two halfwords called |eq_type| (a command code) and |equiv| (a secondary
5322 piece of information that qualifies the |eq_type|).
5323
5324 @d next(A)   mp->hash[(A)].lh /* link for coalesced lists */
5325 @d text(A)   mp->hash[(A)].rh /* string number for symbolic token name */
5326 @d eq_type(A)   mp->eqtb[(A)].lh /* the current ``meaning'' of a symbolic token */
5327 @d equiv(A)   mp->eqtb[(A)].rh /* parametric part of a token's meaning */
5328 @d hash_base 257 /* hashing actually starts here */
5329 @d hash_is_full   (mp->hash_used==hash_base) /* are all positions occupied? */
5330
5331 @<Glob...@>=
5332 pointer hash_used; /* allocation pointer for |hash| */
5333 integer st_count; /* total number of known identifiers */
5334
5335 @ Certain entries in the hash table are ``frozen'' and not redefinable,
5336 since they are used in error recovery.
5337
5338 @d hash_top (hash_base+mp->hash_size) /* the first location of the frozen area */
5339 @d frozen_inaccessible hash_top /* |hash| location to protect the frozen area */
5340 @d frozen_repeat_loop (hash_top+1) /* |hash| location of a loop-repeat token */
5341 @d frozen_right_delimiter (hash_top+2) /* |hash| location of a permanent `\.)' */
5342 @d frozen_left_bracket (hash_top+3) /* |hash| location of a permanent `\.[' */
5343 @d frozen_slash (hash_top+4) /* |hash| location of a permanent `\./' */
5344 @d frozen_colon (hash_top+5) /* |hash| location of a permanent `\.:' */
5345 @d frozen_semicolon (hash_top+6) /* |hash| location of a permanent `\.;' */
5346 @d frozen_end_for (hash_top+7) /* |hash| location of a permanent \&{endfor} */
5347 @d frozen_end_def (hash_top+8) /* |hash| location of a permanent \&{enddef} */
5348 @d frozen_fi (hash_top+9) /* |hash| location of a permanent \&{fi} */
5349 @d frozen_end_group (hash_top+10) /* |hash| location of a permanent `\.{endgroup}' */
5350 @d frozen_etex (hash_top+11) /* |hash| location of a permanent \&{etex} */
5351 @d frozen_mpx_break (hash_top+12) /* |hash| location of a permanent \&{mpxbreak} */
5352 @d frozen_bad_vardef (hash_top+13) /* |hash| location of `\.{a bad variable}' */
5353 @d frozen_undefined (hash_top+14) /* |hash| location that never gets defined */
5354 @d hash_end (hash_top+14) /* the actual size of the |hash| and |eqtb| arrays */
5355
5356 @<Glob...@>=
5357 two_halves *hash; /* the hash table */
5358 two_halves *eqtb; /* the equivalents */
5359
5360 @ @<Allocate or initialize ...@>=
5361 mp->hash = xmalloc((hash_end+1),sizeof(two_halves));
5362 mp->eqtb = xmalloc((hash_end+1),sizeof(two_halves));
5363
5364 @ @<Dealloc variables@>=
5365 xfree(mp->hash);
5366 xfree(mp->eqtb);
5367
5368 @ @<Set init...@>=
5369 next(1)=0; text(1)=0; eq_type(1)=tag_token; equiv(1)=null;
5370 for (k=2;k<=hash_end;k++)  { 
5371   mp->hash[k]=mp->hash[1]; mp->eqtb[k]=mp->eqtb[1];
5372 }
5373
5374 @ @<Initialize table entries...@>=
5375 mp->hash_used=frozen_inaccessible; /* nothing is used */
5376 mp->st_count=0;
5377 text(frozen_bad_vardef)=intern("a bad variable");
5378 text(frozen_etex)=intern("etex");
5379 text(frozen_mpx_break)=intern("mpxbreak");
5380 text(frozen_fi)=intern("fi");
5381 text(frozen_end_group)=intern("endgroup");
5382 text(frozen_end_def)=intern("enddef");
5383 text(frozen_end_for)=intern("endfor");
5384 text(frozen_semicolon)=intern(";");
5385 text(frozen_colon)=intern(":");
5386 text(frozen_slash)=intern("/");
5387 text(frozen_left_bracket)=intern("[");
5388 text(frozen_right_delimiter)=intern(")");
5389 text(frozen_inaccessible)=intern(" INACCESSIBLE");
5390 eq_type(frozen_right_delimiter)=right_delimiter;
5391
5392 @ @<Check the ``constant'' values...@>=
5393 if ( hash_end+mp->max_internal>max_halfword ) mp->bad=17;
5394
5395 @ Here is the subroutine that searches the hash table for an identifier
5396 that matches a given string of length~|l| appearing in |buffer[j..
5397 (j+l-1)]|. If the identifier is not found, it is inserted; hence it
5398 will always be found, and the corresponding hash table address
5399 will be returned.
5400
5401 @c 
5402 pointer mp_id_lookup (MP mp,integer j, integer l) { /* search the hash table */
5403   integer h; /* hash code */
5404   pointer p; /* index in |hash| array */
5405   pointer k; /* index in |buffer| array */
5406   if (l==1) {
5407     @<Treat special case of length 1 and |break|@>;
5408   }
5409   @<Compute the hash code |h|@>;
5410   p=h+hash_base; /* we start searching here; note that |0<=h<hash_prime| */
5411   while (true)  { 
5412         if (text(p)>0 && length(text(p))==l && mp_str_eq_buf(mp, text(p),j)) 
5413       break;
5414     if ( next(p)==0 ) {
5415       @<Insert a new symbolic token after |p|, then
5416         make |p| point to it and |break|@>;
5417     }
5418     p=next(p);
5419   }
5420   return p;
5421 };
5422
5423 @ @<Treat special case of length 1...@>=
5424  p=mp->buffer[j]+1; text(p)=p-1; return p;
5425
5426
5427 @ @<Insert a new symbolic...@>=
5428 {
5429 if ( text(p)>0 ) { 
5430   do {  
5431     if ( hash_is_full )
5432       mp_overflow(mp, "hash size",mp->hash_size);
5433 @:MetaPost capacity exceeded hash size}{\quad hash size@>
5434     decr(mp->hash_used);
5435   } while (text(mp->hash_used)!=0); /* search for an empty location in |hash| */
5436   next(p)=mp->hash_used; 
5437   p=mp->hash_used;
5438 }
5439 str_room(l);
5440 for (k=j;k<=j+l-1;k++) {
5441   append_char(mp->buffer[k]);
5442 }
5443 text(p)=mp_make_string(mp); 
5444 mp->str_ref[text(p)]=max_str_ref;
5445 incr(mp->st_count);
5446 break;
5447 }
5448
5449
5450 @ The value of |hash_prime| should be roughly 85\pct! of |hash_size|, and it
5451 should be a prime number.  The theory of hashing tells us to expect fewer
5452 than two table probes, on the average, when the search is successful.
5453 [See J.~S. Vitter, {\sl Journal of the ACM\/ \bf30} (1983), 231--258.]
5454 @^Vitter, Jeffrey Scott@>
5455
5456 @<Compute the hash code |h|@>=
5457 h=mp->buffer[j];
5458 for (k=j+1;k<=j+l-1;k++){ 
5459   h=h+h+mp->buffer[k];
5460   while ( h>=mp->hash_prime ) h=h-mp->hash_prime;
5461 }
5462
5463 @ @<Search |eqtb| for equivalents equal to |p|@>=
5464 for (q=1;q<=hash_end;q++) { 
5465   if ( equiv(q)==p ) { 
5466     mp_print_nl(mp, "EQUIV("); 
5467     mp_print_int(mp, q); 
5468     mp_print_char(mp, ')');
5469   }
5470 }
5471
5472 @ We need to put \MP's ``primitive'' symbolic tokens into the hash
5473 table, together with their command code (which will be the |eq_type|)
5474 and an operand (which will be the |equiv|). The |primitive| procedure
5475 does this, in a way that no \MP\ user can. The global value |cur_sym|
5476 contains the new |eqtb| pointer after |primitive| has acted.
5477
5478 @c 
5479 void mp_primitive (MP mp, char *ss, halfword c, halfword o) {
5480   pool_pointer k; /* index into |str_pool| */
5481   small_number j; /* index into |buffer| */
5482   small_number l; /* length of the string */
5483   str_number s;
5484   s = intern(ss);
5485   k=mp->str_start[s]; l=str_stop(s)-k;
5486   /* we will move |s| into the (empty) |buffer| */
5487   for (j=0;j<=l-1;j++) {
5488     mp->buffer[j]=mp->str_pool[k+j];
5489   }
5490   mp->cur_sym=mp_id_lookup(mp, 0,l);
5491   if ( s>=256 ) { /* we don't want to have the string twice */
5492     mp_flush_string(mp, text(mp->cur_sym)); text(mp->cur_sym)=s;
5493   };
5494   eq_type(mp->cur_sym)=c; 
5495   equiv(mp->cur_sym)=o;
5496 }
5497
5498
5499 @ Many of \MP's primitives need no |equiv|, since they are identifiable
5500 by their |eq_type| alone. These primitives are loaded into the hash table
5501 as follows:
5502
5503 @<Put each of \MP's primitives into the hash table@>=
5504 mp_primitive(mp, "..",path_join,0);
5505 @:.._}{\.{..} primitive@>
5506 mp_primitive(mp, "[",left_bracket,0); mp->eqtb[frozen_left_bracket]=mp->eqtb[mp->cur_sym];
5507 @:[ }{\.{[} primitive@>
5508 mp_primitive(mp, "]",right_bracket,0);
5509 @:] }{\.{]} primitive@>
5510 mp_primitive(mp, "}",right_brace,0);
5511 @:]]}{\.{\char`\}} primitive@>
5512 mp_primitive(mp, "{",left_brace,0);
5513 @:][}{\.{\char`\{} primitive@>
5514 mp_primitive(mp, ":",colon,0); mp->eqtb[frozen_colon]=mp->eqtb[mp->cur_sym];
5515 @:: }{\.{:} primitive@>
5516 mp_primitive(mp, "::",double_colon,0);
5517 @::: }{\.{::} primitive@>
5518 mp_primitive(mp, "||:",bchar_label,0);
5519 @:::: }{\.{\char'174\char'174:} primitive@>
5520 mp_primitive(mp, ":=",assignment,0);
5521 @::=_}{\.{:=} primitive@>
5522 mp_primitive(mp, ",",comma,0);
5523 @:, }{\., primitive@>
5524 mp_primitive(mp, ";",semicolon,0); mp->eqtb[frozen_semicolon]=mp->eqtb[mp->cur_sym];
5525 @:; }{\.; primitive@>
5526 mp_primitive(mp, "\\",relax,0);
5527 @:]]\\}{\.{\char`\\} primitive@>
5528 @#
5529 mp_primitive(mp, "addto",add_to_command,0);
5530 @:add_to_}{\&{addto} primitive@>
5531 mp_primitive(mp, "atleast",at_least,0);
5532 @:at_least_}{\&{atleast} primitive@>
5533 mp_primitive(mp, "begingroup",begin_group,0); mp->bg_loc=mp->cur_sym;
5534 @:begin_group_}{\&{begingroup} primitive@>
5535 mp_primitive(mp, "controls",controls,0);
5536 @:controls_}{\&{controls} primitive@>
5537 mp_primitive(mp, "curl",curl_command,0);
5538 @:curl_}{\&{curl} primitive@>
5539 mp_primitive(mp, "delimiters",delimiters,0);
5540 @:delimiters_}{\&{delimiters} primitive@>
5541 mp_primitive(mp, "endgroup",end_group,0);
5542  mp->eqtb[frozen_end_group]=mp->eqtb[mp->cur_sym]; mp->eg_loc=mp->cur_sym;
5543 @:endgroup_}{\&{endgroup} primitive@>
5544 mp_primitive(mp, "everyjob",every_job_command,0);
5545 @:every_job_}{\&{everyjob} primitive@>
5546 mp_primitive(mp, "exitif",exit_test,0);
5547 @:exit_if_}{\&{exitif} primitive@>
5548 mp_primitive(mp, "expandafter",expand_after,0);
5549 @:expand_after_}{\&{expandafter} primitive@>
5550 mp_primitive(mp, "interim",interim_command,0);
5551 @:interim_}{\&{interim} primitive@>
5552 mp_primitive(mp, "let",let_command,0);
5553 @:let_}{\&{let} primitive@>
5554 mp_primitive(mp, "newinternal",new_internal,0);
5555 @:new_internal_}{\&{newinternal} primitive@>
5556 mp_primitive(mp, "of",of_token,0);
5557 @:of_}{\&{of} primitive@>
5558 mp_primitive(mp, "randomseed",mp_random_seed,0);
5559 @:mp_random_seed_}{\&{randomseed} primitive@>
5560 mp_primitive(mp, "save",save_command,0);
5561 @:save_}{\&{save} primitive@>
5562 mp_primitive(mp, "scantokens",scan_tokens,0);
5563 @:scan_tokens_}{\&{scantokens} primitive@>
5564 mp_primitive(mp, "shipout",ship_out_command,0);
5565 @:ship_out_}{\&{shipout} primitive@>
5566 mp_primitive(mp, "skipto",skip_to,0);
5567 @:skip_to_}{\&{skipto} primitive@>
5568 mp_primitive(mp, "special",special_command,0);
5569 @:special}{\&{special} primitive@>
5570 mp_primitive(mp, "fontmapfile",special_command,1);
5571 @:fontmapfile}{\&{fontmapfile} primitive@>
5572 mp_primitive(mp, "fontmapline",special_command,2);
5573 @:fontmapline}{\&{fontmapline} primitive@>
5574 mp_primitive(mp, "step",step_token,0);
5575 @:step_}{\&{step} primitive@>
5576 mp_primitive(mp, "str",str_op,0);
5577 @:str_}{\&{str} primitive@>
5578 mp_primitive(mp, "tension",tension,0);
5579 @:tension_}{\&{tension} primitive@>
5580 mp_primitive(mp, "to",to_token,0);
5581 @:to_}{\&{to} primitive@>
5582 mp_primitive(mp, "until",until_token,0);
5583 @:until_}{\&{until} primitive@>
5584 mp_primitive(mp, "within",within_token,0);
5585 @:within_}{\&{within} primitive@>
5586 mp_primitive(mp, "write",write_command,0);
5587 @:write_}{\&{write} primitive@>
5588
5589 @ Each primitive has a corresponding inverse, so that it is possible to
5590 display the cryptic numeric contents of |eqtb| in symbolic form.
5591 Every call of |primitive| in this program is therefore accompanied by some
5592 straightforward code that forms part of the |print_cmd_mod| routine
5593 explained below.
5594
5595 @<Cases of |print_cmd_mod| for symbolic printing of primitives@>=
5596 case add_to_command:mp_print(mp, "addto"); break;
5597 case assignment:mp_print(mp, ":="); break;
5598 case at_least:mp_print(mp, "atleast"); break;
5599 case bchar_label:mp_print(mp, "||:"); break;
5600 case begin_group:mp_print(mp, "begingroup"); break;
5601 case colon:mp_print(mp, ":"); break;
5602 case comma:mp_print(mp, ","); break;
5603 case controls:mp_print(mp, "controls"); break;
5604 case curl_command:mp_print(mp, "curl"); break;
5605 case delimiters:mp_print(mp, "delimiters"); break;
5606 case double_colon:mp_print(mp, "::"); break;
5607 case end_group:mp_print(mp, "endgroup"); break;
5608 case every_job_command:mp_print(mp, "everyjob"); break;
5609 case exit_test:mp_print(mp, "exitif"); break;
5610 case expand_after:mp_print(mp, "expandafter"); break;
5611 case interim_command:mp_print(mp, "interim"); break;
5612 case left_brace:mp_print(mp, "{"); break;
5613 case left_bracket:mp_print(mp, "["); break;
5614 case let_command:mp_print(mp, "let"); break;
5615 case new_internal:mp_print(mp, "newinternal"); break;
5616 case of_token:mp_print(mp, "of"); break;
5617 case path_join:mp_print(mp, ".."); break;
5618 case mp_random_seed:mp_print(mp, "randomseed"); break;
5619 case relax:mp_print_char(mp, '\\'); break;
5620 case right_brace:mp_print(mp, "}"); break;
5621 case right_bracket:mp_print(mp, "]"); break;
5622 case save_command:mp_print(mp, "save"); break;
5623 case scan_tokens:mp_print(mp, "scantokens"); break;
5624 case semicolon:mp_print(mp, ";"); break;
5625 case ship_out_command:mp_print(mp, "shipout"); break;
5626 case skip_to:mp_print(mp, "skipto"); break;
5627 case special_command: if ( m==2 ) mp_print(mp, "fontmapline"); else
5628                  if ( m==1 ) mp_print(mp, "fontmapfile"); else
5629                  mp_print(mp, "special"); break;
5630 case step_token:mp_print(mp, "step"); break;
5631 case str_op:mp_print(mp, "str"); break;
5632 case tension:mp_print(mp, "tension"); break;
5633 case to_token:mp_print(mp, "to"); break;
5634 case until_token:mp_print(mp, "until"); break;
5635 case within_token:mp_print(mp, "within"); break;
5636 case write_command:mp_print(mp, "write"); break;
5637
5638 @ We will deal with the other primitives later, at some point in the program
5639 where their |eq_type| and |equiv| values are more meaningful.  For example,
5640 the primitives for macro definitions will be loaded when we consider the
5641 routines that define macros.
5642 It is easy to find where each particular
5643 primitive was treated by looking in the index at the end; for example, the
5644 section where |"def"| entered |eqtb| is listed under `\&{def} primitive'.
5645
5646 @* \[14] Token lists.
5647 A \MP\ token is either symbolic or numeric or a string, or it denotes
5648 a macro parameter or capsule; so there are five corresponding ways to encode it
5649 @^token@>
5650 internally: (1)~A symbolic token whose hash code is~|p|
5651 is represented by the number |p|, in the |info| field of a single-word
5652 node in~|mem|. (2)~A numeric token whose |scaled| value is~|v| is
5653 represented in a two-word node of~|mem|; the |type| field is |known|,
5654 the |name_type| field is |token|, and the |value| field holds~|v|.
5655 The fact that this token appears in a two-word node rather than a
5656 one-word node is, of course, clear from the node address.
5657 (3)~A string token is also represented in a two-word node; the |type|
5658 field is |mp_string_type|, the |name_type| field is |token|, and the
5659 |value| field holds the corresponding |str_number|.  (4)~Capsules have
5660 |name_type=capsule|, and their |type| and |value| fields represent
5661 arbitrary values (in ways to be explained later).  (5)~Macro parameters
5662 are like symbolic tokens in that they appear in |info| fields of
5663 one-word nodes. The $k$th parameter is represented by |expr_base+k| if it
5664 is of type \&{expr}, or by |suffix_base+k| if it is of type \&{suffix}, or
5665 by |text_base+k| if it is of type \&{text}.  (Here |0<=k<param_size|.)
5666 Actual values of these parameters are kept in a separate stack, as we will
5667 see later.  The constants |expr_base|, |suffix_base|, and |text_base| are,
5668 of course, chosen so that there will be no confusion between symbolic
5669 tokens and parameters of various types.
5670
5671 Note that
5672 the `\\{type}' field of a node has nothing to do with ``type'' in a
5673 printer's sense. It's curious that the same word is used in such different ways.
5674
5675 @d type(A)   mp->mem[(A)].hh.b0 /* identifies what kind of value this is */
5676 @d name_type(A)   mp->mem[(A)].hh.b1 /* a clue to the name of this value */
5677 @d token_node_size 2 /* the number of words in a large token node */
5678 @d value_loc(A) ((A)+1) /* the word that contains the |value| field */
5679 @d value(A) mp->mem[value_loc((A))].cint /* the value stored in a large token node */
5680 @d expr_base (hash_end+1) /* code for the zeroth \&{expr} parameter */
5681 @d suffix_base (expr_base+mp->param_size) /* code for the zeroth \&{suffix} parameter */
5682 @d text_base (suffix_base+mp->param_size) /* code for the zeroth \&{text} parameter */
5683
5684 @<Check the ``constant''...@>=
5685 if ( text_base+mp->param_size>max_halfword ) mp->bad=18;
5686
5687 @ We have set aside a two word node beginning at |null| so that we can have
5688 |value(null)=0|.  We will make use of this coincidence later.
5689
5690 @<Initialize table entries...@>=
5691 link(null)=null; value(null)=0;
5692
5693 @ A numeric token is created by the following trivial routine.
5694
5695 @c 
5696 pointer mp_new_num_tok (MP mp,scaled v) {
5697   pointer p; /* the new node */
5698   p=mp_get_node(mp, token_node_size); value(p)=v;
5699   type(p)=mp_known; name_type(p)=mp_token; 
5700   return p;
5701 }
5702
5703 @ A token list is a singly linked list of nodes in |mem|, where
5704 each node contains a token and a link.  Here's a subroutine that gets rid
5705 of a token list when it is no longer needed.
5706
5707 @c void mp_flush_token_list (MP mp,pointer p) {
5708   pointer q; /* the node being recycled */
5709   while ( p!=null ) { 
5710     q=p; p=link(p);
5711     if ( q>=mp->hi_mem_min ) {
5712      free_avail(q);
5713     } else { 
5714       switch (type(q)) {
5715       case mp_vacuous: case mp_boolean_type: case mp_known:
5716         break;
5717       case mp_string_type:
5718         delete_str_ref(value(q));
5719         break;
5720       case unknown_types: case mp_pen_type: case mp_path_type: 
5721       case mp_picture_type: case mp_pair_type: case mp_color_type:
5722       case mp_cmykcolor_type: case mp_transform_type: case mp_dependent:
5723       case mp_proto_dependent: case mp_independent:
5724         mp_recycle_value(mp,q);
5725         break;
5726       default: mp_confusion(mp, "token");
5727 @:this can't happen token}{\quad token@>
5728       }
5729       mp_free_node(mp, q,token_node_size);
5730     }
5731   }
5732 }
5733
5734 @ The procedure |show_token_list|, which prints a symbolic form of
5735 the token list that starts at a given node |p|, illustrates these
5736 conventions. The token list being displayed should not begin with a reference
5737 count. However, the procedure is intended to be fairly robust, so that if the
5738 memory links are awry or if |p| is not really a pointer to a token list,
5739 almost nothing catastrophic can happen.
5740
5741 An additional parameter |q| is also given; this parameter is either null
5742 or it points to a node in the token list where a certain magic computation
5743 takes place that will be explained later. (Basically, |q| is non-null when
5744 we are printing the two-line context information at the time of an error
5745 message; |q| marks the place corresponding to where the second line
5746 should begin.)
5747
5748 The generation will stop, and `\.{\char`\ ETC.}' will be printed, if the length
5749 of printing exceeds a given limit~|l|; the length of printing upon entry is
5750 assumed to be a given amount called |null_tally|. (Note that
5751 |show_token_list| sometimes uses itself recursively to print
5752 variable names within a capsule.)
5753 @^recursion@>
5754
5755 Unusual entries are printed in the form of all-caps tokens
5756 preceded by a space, e.g., `\.{\char`\ BAD}'.
5757
5758 @<Declare the procedure called |show_token_list|@>=
5759 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5760                          integer null_tally) ;
5761
5762 @ @c
5763 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5764                          integer null_tally) {
5765   small_number class,c; /* the |char_class| of previous and new tokens */
5766   integer r,v; /* temporary registers */
5767   class=percent_class;
5768   mp->tally=null_tally;
5769   while ( (p!=null) && (mp->tally<l) ) { 
5770     if ( p==q ) 
5771       @<Do magic computation@>;
5772     @<Display token |p| and set |c| to its class;
5773       but |return| if there are problems@>;
5774     class=c; p=link(p);
5775   }
5776   if ( p!=null ) 
5777      mp_print(mp, " ETC.");
5778 @.ETC@>
5779   return;
5780 };
5781
5782 @ @<Display token |p| and set |c| to its class...@>=
5783 c=letter_class; /* the default */
5784 if ( (p<0)||(p>mp->mem_end) ) { 
5785   mp_print(mp, " CLOBBERED"); return;
5786 @.CLOBBERED@>
5787 }
5788 if ( p<mp->hi_mem_min ) { 
5789   @<Display two-word token@>;
5790 } else { 
5791   r=info(p);
5792   if ( r>=expr_base ) {
5793      @<Display a parameter token@>;
5794   } else {
5795     if ( r<1 ) {
5796       if ( r==0 ) { 
5797         @<Display a collective subscript@>
5798       } else {
5799         mp_print(mp, " IMPOSSIBLE");
5800 @.IMPOSSIBLE@>
5801       }
5802     } else { 
5803       r=text(r);
5804       if ( (r<0)||(r>mp->max_str_ptr) ) {
5805         mp_print(mp, " NONEXISTENT");
5806 @.NONEXISTENT@>
5807       } else {
5808        @<Print string |r| as a symbolic token
5809         and set |c| to its class@>;
5810       }
5811     }
5812   }
5813 }
5814
5815 @ @<Display two-word token@>=
5816 if ( name_type(p)==mp_token ) {
5817   if ( type(p)==mp_known ) {
5818     @<Display a numeric token@>;
5819   } else if ( type(p)!=mp_string_type ) {
5820     mp_print(mp, " BAD");
5821 @.BAD@>
5822   } else { 
5823     mp_print_char(mp, '"'); mp_print_str(mp, value(p)); mp_print_char(mp, '"');
5824     c=string_class;
5825   }
5826 } else if ((name_type(p)!=mp_capsule)||(type(p)<mp_vacuous)||(type(p)>mp_independent) ) {
5827   mp_print(mp, " BAD");
5828 } else { 
5829   mp_print_capsule(mp,p); c=right_paren_class;
5830 }
5831
5832 @ @<Display a numeric token@>=
5833 if ( class==digit_class ) 
5834   mp_print_char(mp, ' ');
5835 v=value(p);
5836 if ( v<0 ){ 
5837   if ( class==left_bracket_class ) 
5838     mp_print_char(mp, ' ');
5839   mp_print_char(mp, '['); mp_print_scaled(mp, v); mp_print_char(mp, ']');
5840   c=right_bracket_class;
5841 } else { 
5842   mp_print_scaled(mp, v); c=digit_class;
5843 }
5844
5845
5846 @ Strictly speaking, a genuine token will never have |info(p)=0|.
5847 But we will see later (in the |print_variable_name| routine) that
5848 it is convenient to let |info(p)=0| stand for `\.{[]}'.
5849
5850 @<Display a collective subscript@>=
5851 {
5852 if ( class==left_bracket_class ) 
5853   mp_print_char(mp, ' ');
5854 mp_print(mp, "[]"); c=right_bracket_class;
5855 }
5856
5857 @ @<Display a parameter token@>=
5858 {
5859 if ( r<suffix_base ) { 
5860   mp_print(mp, "(EXPR"); r=r-(expr_base);
5861 @.EXPR@>
5862 } else if ( r<text_base ) { 
5863   mp_print(mp, "(SUFFIX"); r=r-(suffix_base);
5864 @.SUFFIX@>
5865 } else { 
5866   mp_print(mp, "(TEXT"); r=r-(text_base);
5867 @.TEXT@>
5868 }
5869 mp_print_int(mp, r); mp_print_char(mp, ')'); c=right_paren_class;
5870 }
5871
5872
5873 @ @<Print string |r| as a symbolic token...@>=
5874
5875 c=mp->char_class[mp->str_pool[mp->str_start[r]]];
5876 if ( c==class ) {
5877   switch (c) {
5878   case letter_class:mp_print_char(mp, '.'); break;
5879   case isolated_classes: break;
5880   default: mp_print_char(mp, ' '); break;
5881   }
5882 }
5883 mp_print_str(mp, r);
5884 }
5885
5886 @ @<Declarations@>=
5887 void mp_print_capsule (MP mp, pointer p);
5888
5889 @ @<Declare miscellaneous procedures that were declared |forward|@>=
5890 void mp_print_capsule (MP mp, pointer p) { 
5891   mp_print_char(mp, '('); mp_print_exp(mp,p,0); mp_print_char(mp, ')');
5892 }
5893
5894 @ Macro definitions are kept in \MP's memory in the form of token lists
5895 that have a few extra one-word nodes at the beginning.
5896
5897 The first node contains a reference count that is used to tell when the
5898 list is no longer needed. To emphasize the fact that a reference count is
5899 present, we shall refer to the |info| field of this special node as the
5900 |ref_count| field.
5901 @^reference counts@>
5902
5903 The next node or nodes after the reference count serve to describe the
5904 formal parameters. They either contain a code word that specifies all
5905 of the parameters, or they contain zero or more parameter tokens followed
5906 by the code `|general_macro|'.
5907
5908 @d ref_count info
5909   /* reference count preceding a macro definition or picture header */
5910 @d add_mac_ref(A) incr(ref_count((A))) /* make a new reference to a macro list */
5911 @d general_macro 0 /* preface to a macro defined with a parameter list */
5912 @d primary_macro 1 /* preface to a macro with a \&{primary} parameter */
5913 @d secondary_macro 2 /* preface to a macro with a \&{secondary} parameter */
5914 @d tertiary_macro 3 /* preface to a macro with a \&{tertiary} parameter */
5915 @d expr_macro 4 /* preface to a macro with an undelimited \&{expr} parameter */
5916 @d of_macro 5 /* preface to a macro with
5917   undelimited `\&{expr} |x| \&{of}~|y|' parameters */
5918 @d suffix_macro 6 /* preface to a macro with an undelimited \&{suffix} parameter */
5919 @d text_macro 7 /* preface to a macro with an undelimited \&{text} parameter */
5920
5921 @c 
5922 void mp_delete_mac_ref (MP mp,pointer p) {
5923   /* |p| points to the reference count of a macro list that is
5924     losing one reference */
5925   if ( ref_count(p)==null ) mp_flush_token_list(mp, p);
5926   else decr(ref_count(p));
5927 }
5928
5929 @ The following subroutine displays a macro, given a pointer to its
5930 reference count.
5931
5932 @c 
5933 @<Declare the procedure called |print_cmd_mod|@>;
5934 void mp_show_macro (MP mp, pointer p, integer q, integer l) {
5935   pointer r; /* temporary storage */
5936   p=link(p); /* bypass the reference count */
5937   while ( info(p)>text_macro ){ 
5938     r=link(p); link(p)=null;
5939     mp_show_token_list(mp, p,null,l,0); link(p)=r; p=r;
5940     if ( l>0 ) l=l-mp->tally; else return;
5941   } /* control printing of `\.{ETC.}' */
5942 @.ETC@>
5943   mp->tally=0;
5944   switch(info(p)) {
5945   case general_macro:mp_print(mp, "->"); break;
5946 @.->@>
5947   case primary_macro: case secondary_macro: case tertiary_macro:
5948     mp_print_char(mp, '<');
5949     mp_print_cmd_mod(mp, param_type,info(p)); 
5950     mp_print(mp, ">->");
5951     break;
5952   case expr_macro:mp_print(mp, "<expr>->"); break;
5953   case of_macro:mp_print(mp, "<expr>of<primary>->"); break;
5954   case suffix_macro:mp_print(mp, "<suffix>->"); break;
5955   case text_macro:mp_print(mp, "<text>->"); break;
5956   } /* there are no other cases */
5957   mp_show_token_list(mp, link(p),q,l-mp->tally,0);
5958 }
5959
5960 @* \[15] Data structures for variables.
5961 The variables of \MP\ programs can be simple, like `\.x', or they can
5962 combine the structural properties of arrays and records, like `\.{x20a.b}'.
5963 A \MP\ user assigns a type to a variable like \.{x20a.b} by saying, for
5964 example, `\.{boolean} \.{x20a.b}'. It's time for us to study how such
5965 things are represented inside of the computer.
5966
5967 Each variable value occupies two consecutive words, either in a two-word
5968 node called a value node, or as a two-word subfield of a larger node.  One
5969 of those two words is called the |value| field; it is an integer,
5970 containing either a |scaled| numeric value or the representation of some
5971 other type of quantity. (It might also be subdivided into halfwords, in
5972 which case it is referred to by other names instead of |value|.) The other
5973 word is broken into subfields called |type|, |name_type|, and |link|.  The
5974 |type| field is a quarterword that specifies the variable's type, and
5975 |name_type| is a quarterword from which \MP\ can reconstruct the
5976 variable's name (sometimes by using the |link| field as well).  Thus, only
5977 1.25 words are actually devoted to the value itself; the other
5978 three-quarters of a word are overhead, but they aren't wasted because they
5979 allow \MP\ to deal with sparse arrays and to provide meaningful diagnostics.
5980
5981 In this section we shall be concerned only with the structural aspects of
5982 variables, not their values. Later parts of the program will change the
5983 |type| and |value| fields, but we shall treat those fields as black boxes
5984 whose contents should not be touched.
5985
5986 However, if the |type| field is |mp_structured|, there is no |value| field,
5987 and the second word is broken into two pointer fields called |attr_head|
5988 and |subscr_head|. Those fields point to additional nodes that
5989 contain structural information, as we shall see.
5990
5991 @d subscr_head_loc(A)   (A)+1 /* where |value|, |subscr_head| and |attr_head| are */
5992 @d attr_head(A)   info(subscr_head_loc((A))) /* pointer to attribute info */
5993 @d subscr_head(A)   link(subscr_head_loc((A))) /* pointer to subscript info */
5994 @d value_node_size 2 /* the number of words in a value node */
5995
5996 @ An attribute node is three words long. Two of these words contain |type|
5997 and |value| fields as described above, and the third word contains
5998 additional information:  There is an |attr_loc| field, which contains the
5999 hash address of the token that names this attribute; and there's also a
6000 |parent| field, which points to the value node of |mp_structured| type at the
6001 next higher level (i.e., at the level to which this attribute is
6002 subsidiary).  The |name_type| in an attribute node is `|attr|'.  The
6003 |link| field points to the next attribute with the same parent; these are
6004 arranged in increasing order, so that |attr_loc(link(p))>attr_loc(p)|. The
6005 final attribute node links to the constant |end_attr|, whose |attr_loc|
6006 field is greater than any legal hash address. The |attr_head| in the
6007 parent points to a node whose |name_type| is |mp_structured_root|; this
6008 node represents the null attribute, i.e., the variable that is relevant
6009 when no attributes are attached to the parent. The |attr_head| node is either
6010 a value node, a subscript node, or an attribute node, depending on what
6011 the parent would be if it were not structured; but the subscript and
6012 attribute fields are ignored, so it effectively contains only the data of
6013 a value node. The |link| field in this special node points to an attribute
6014 node whose |attr_loc| field is zero; the latter node represents a collective
6015 subscript `\.{[]}' attached to the parent, and its |link| field points to
6016 the first non-special attribute node (or to |end_attr| if there are none).
6017
6018 A subscript node likewise occupies three words, with |type| and |value| fields
6019 plus extra information; its |name_type| is |subscr|. In this case the
6020 third word is called the |subscript| field, which is a |scaled| integer.
6021 The |link| field points to the subscript node with the next larger
6022 subscript, if any; otherwise the |link| points to the attribute node
6023 for collective subscripts at this level. We have seen that the latter node
6024 contains an upward pointer, so that the parent can be deduced.
6025
6026 The |name_type| in a parent-less value node is |root|, and the |link|
6027 is the hash address of the token that names this value.
6028
6029 In other words, variables have a hierarchical structure that includes
6030 enough threads running around so that the program is able to move easily
6031 between siblings, parents, and children. An example should be helpful:
6032 (The reader is advised to draw a picture while reading the following
6033 description, since that will help to firm up the ideas.)
6034 Suppose that `\.x' and `\.{x.a}' and `\.{x[]b}' and `\.{x5}'
6035 and `\.{x20b}' have been mentioned in a user's program, where
6036 \.{x[]b} has been declared to be of \&{boolean} type. Let |h(x)|, |h(a)|,
6037 and |h(b)| be the hash addresses of \.x, \.a, and~\.b. Then
6038 |eq_type(h(x))=name| and |equiv(h(x))=p|, where |p|~is a two-word value
6039 node with |name_type(p)=root| and |link(p)=h(x)|. We have |type(p)=mp_structured|,
6040 |attr_head(p)=q|, and |subscr_head(p)=r|, where |q| points to a value
6041 node and |r| to a subscript node. (Are you still following this? Use
6042 a pencil to draw a diagram.) The lone variable `\.x' is represented by
6043 |type(q)| and |value(q)|; furthermore
6044 |name_type(q)=mp_structured_root| and |link(q)=q1|, where |q1| points
6045 to an attribute node representing `\.{x[]}'. Thus |name_type(q1)=attr|,
6046 |attr_loc(q1)=collective_subscript=0|, |parent(q1)=p|,
6047 |type(q1)=mp_structured|, |attr_head(q1)=qq|, and |subscr_head(q1)=qq1|;
6048 |qq| is a value node with |type(qq)=mp_numeric_type| (assuming that \.{x5} is
6049 numeric, because |qq| represents `\.{x[]}' with no further attributes),
6050 |name_type(qq)=mp_structured_root|, and
6051 |link(qq)=qq1|. (Now pay attention to the next part.) Node |qq1| is
6052 an attribute node representing `\.{x[][]}', which has never yet
6053 occurred; its |type| field is |undefined|, and its |value| field is
6054 undefined. We have |name_type(qq1)=attr|, |attr_loc(qq1)=collective_subscript|,
6055 |parent(qq1)=q1|, and |link(qq1)=qq2|. Since |qq2| represents
6056 `\.{x[]b}', |type(qq2)=mp_unknown_boolean|; also |attr_loc(qq2)=h(b)|,
6057 |parent(qq2)=q1|, |name_type(qq2)=attr|, |link(qq2)=end_attr|.
6058 (Maybe colored lines will help untangle your picture.)
6059  Node |r| is a subscript node with |type| and |value|
6060 representing `\.{x5}'; |name_type(r)=subscr|, |subscript(r)=5.0|,
6061 and |link(r)=r1| is another subscript node. To complete the picture,
6062 see if you can guess what |link(r1)| is; give up? It's~|q1|.
6063 Furthermore |subscript(r1)=20.0|, |name_type(r1)=subscr|,
6064 |type(r1)=mp_structured|, |attr_head(r1)=qqq|, |subscr_head(r1)=qqq1|,
6065 and we finish things off with three more nodes
6066 |qqq|, |qqq1|, and |qqq2| hung onto~|r1|. (Perhaps you should start again
6067 with a larger sheet of paper.) The value of variable \.{x20b}
6068 appears in node~|qqq2|, as you can well imagine.
6069
6070 If the example in the previous paragraph doesn't make things crystal
6071 clear, a glance at some of the simpler subroutines below will reveal how
6072 things work out in practice.
6073
6074 The only really unusual thing about these conventions is the use of
6075 collective subscript attributes. The idea is to avoid repeating a lot of
6076 type information when many elements of an array are identical macros
6077 (for which distinct values need not be stored) or when they don't have
6078 all of the possible attributes. Branches of the structure below collective
6079 subscript attributes do not carry actual values except for macro identifiers;
6080 branches of the structure below subscript nodes do not carry significant
6081 information in their collective subscript attributes.
6082
6083 @d attr_loc_loc(A) ((A)+2) /* where the |attr_loc| and |parent| fields are */
6084 @d attr_loc(A) info(attr_loc_loc((A))) /* hash address of this attribute */
6085 @d parent(A) link(attr_loc_loc((A))) /* pointer to |mp_structured| variable */
6086 @d subscript_loc(A) ((A)+2) /* where the |subscript| field lives */
6087 @d subscript(A) mp->mem[subscript_loc((A))].sc /* subscript of this variable */
6088 @d attr_node_size 3 /* the number of words in an attribute node */
6089 @d subscr_node_size 3 /* the number of words in a subscript node */
6090 @d collective_subscript 0 /* code for the attribute `\.{[]}' */
6091
6092 @<Initialize table...@>=
6093 attr_loc(end_attr)=hash_end+1; parent(end_attr)=null;
6094
6095 @ Variables of type \&{pair} will have values that point to four-word
6096 nodes containing two numeric values. The first of these values has
6097 |name_type=mp_x_part_sector| and the second has |name_type=mp_y_part_sector|;
6098 the |link| in the first points back to the node whose |value| points
6099 to this four-word node.
6100
6101 Variables of type \&{transform} are similar, but in this case their
6102 |value| points to a 12-word node containing six values, identified by
6103 |x_part_sector|, |y_part_sector|, |mp_xx_part_sector|, |mp_xy_part_sector|,
6104 |mp_yx_part_sector|, and |mp_yy_part_sector|.
6105 Finally, variables of type \&{color} have 3~values in 6~words
6106 identified by |mp_red_part_sector|, |mp_green_part_sector|, and |mp_blue_part_sector|.
6107
6108 When an entire structured variable is saved, the |root| indication
6109 is temporarily replaced by |saved_root|.
6110
6111 Some variables have no name; they just are used for temporary storage
6112 while expressions are being evaluated. We call them {\sl capsules}.
6113
6114 @d x_part_loc(A) (A) /* where the \&{xpart} is found in a pair or transform node */
6115 @d y_part_loc(A) ((A)+2) /* where the \&{ypart} is found in a pair or transform node */
6116 @d xx_part_loc(A) ((A)+4) /* where the \&{xxpart} is found in a transform node */
6117 @d xy_part_loc(A) ((A)+6) /* where the \&{xypart} is found in a transform node */
6118 @d yx_part_loc(A) ((A)+8) /* where the \&{yxpart} is found in a transform node */
6119 @d yy_part_loc(A) ((A)+10) /* where the \&{yypart} is found in a transform node */
6120 @d red_part_loc(A) (A) /* where the \&{redpart} is found in a color node */
6121 @d green_part_loc(A) ((A)+2) /* where the \&{greenpart} is found in a color node */
6122 @d blue_part_loc(A) ((A)+4) /* where the \&{bluepart} is found in a color node */
6123 @d cyan_part_loc(A) (A) /* where the \&{cyanpart} is found in a color node */
6124 @d magenta_part_loc(A) ((A)+2) /* where the \&{magentapart} is found in a color node */
6125 @d yellow_part_loc(A) ((A)+4) /* where the \&{yellowpart} is found in a color node */
6126 @d black_part_loc(A) ((A)+6) /* where the \&{blackpart} is found in a color node */
6127 @d grey_part_loc(A) (A) /* where the \&{greypart} is found in a color node */
6128 @#
6129 @d pair_node_size 4 /* the number of words in a pair node */
6130 @d transform_node_size 12 /* the number of words in a transform node */
6131 @d color_node_size 6 /* the number of words in a color node */
6132 @d cmykcolor_node_size 8 /* the number of words in a color node */
6133
6134 @<Glob...@>=
6135 small_number big_node_size[mp_pair_type+1];
6136 small_number sector0[mp_pair_type+1];
6137 small_number sector_offset[mp_black_part_sector+1];
6138
6139 @ The |sector0| array gives for each big node type, |name_type| values
6140 for its first subfield; the |sector_offset| array gives for each
6141 |name_type| value, the offset from the first subfield in words;
6142 and the |big_node_size| array gives the size in words for each type of
6143 big node.
6144
6145 @<Set init...@>=
6146 mp->big_node_size[mp_transform_type]=transform_node_size;
6147 mp->big_node_size[mp_pair_type]=pair_node_size;
6148 mp->big_node_size[mp_color_type]=color_node_size;
6149 mp->big_node_size[mp_cmykcolor_type]=cmykcolor_node_size;
6150 mp->sector0[mp_transform_type]=mp_x_part_sector;
6151 mp->sector0[mp_pair_type]=mp_x_part_sector;
6152 mp->sector0[mp_color_type]=mp_red_part_sector;
6153 mp->sector0[mp_cmykcolor_type]=mp_cyan_part_sector;
6154 for (k=mp_x_part_sector;k<= mp_yy_part_sector;k++ ) {
6155   mp->sector_offset[k]=2*(k-mp_x_part_sector);
6156 }
6157 for (k=mp_red_part_sector;k<= mp_blue_part_sector ; k++) {
6158   mp->sector_offset[k]=2*(k-mp_red_part_sector);
6159 }
6160 for (k=mp_cyan_part_sector;k<= mp_black_part_sector;k++ ) {
6161   mp->sector_offset[k]=2*(k-mp_cyan_part_sector);
6162 }
6163
6164 @ If |type(p)=mp_pair_type| or |mp_transform_type| and if |value(p)=null|, the
6165 procedure call |init_big_node(p)| will allocate a pair or transform node
6166 for~|p|.  The individual parts of such nodes are initially of type
6167 |mp_independent|.
6168
6169 @c 
6170 void mp_init_big_node (MP mp,pointer p) {
6171   pointer q; /* the new node */
6172   small_number s; /* its size */
6173   s=mp->big_node_size[type(p)]; q=mp_get_node(mp, s);
6174   do {  
6175     s=s-2; 
6176     @<Make variable |q+s| newly independent@>;
6177     name_type(q+s)=halfp(s)+mp->sector0[type(p)]; 
6178     link(q+s)=null;
6179   } while (s!=0);
6180   link(q)=p; value(p)=q;
6181 }
6182
6183 @ The |id_transform| function creates a capsule for the
6184 identity transformation.
6185
6186 @c 
6187 pointer mp_id_transform (MP mp) {
6188   pointer p,q,r; /* list manipulation registers */
6189   p=mp_get_node(mp, value_node_size); type(p)=mp_transform_type;
6190   name_type(p)=mp_capsule; value(p)=null; mp_init_big_node(mp, p); q=value(p);
6191   r=q+transform_node_size;
6192   do {  
6193     r=r-2;
6194     type(r)=mp_known; value(r)=0;
6195   } while (r!=q);
6196   value(xx_part_loc(q))=unity; 
6197   value(yy_part_loc(q))=unity;
6198   return p;
6199 }
6200
6201 @ Tokens are of type |tag_token| when they first appear, but they point
6202 to |null| until they are first used as the root of a variable.
6203 The following subroutine establishes the root node on such grand occasions.
6204
6205 @c 
6206 void mp_new_root (MP mp,pointer x) {
6207   pointer p; /* the new node */
6208   p=mp_get_node(mp, value_node_size); type(p)=undefined; name_type(p)=mp_root;
6209   link(p)=x; equiv(x)=p;
6210 }
6211
6212 @ These conventions for variable representation are illustrated by the
6213 |print_variable_name| routine, which displays the full name of a
6214 variable given only a pointer to its two-word value packet.
6215
6216 @<Declarations@>=
6217 void mp_print_variable_name (MP mp, pointer p);
6218
6219 @ @c 
6220 void mp_print_variable_name (MP mp, pointer p) {
6221   pointer q; /* a token list that will name the variable's suffix */
6222   pointer r; /* temporary for token list creation */
6223   while ( name_type(p)>=mp_x_part_sector ) {
6224     @<Preface the output with a part specifier; |return| in the
6225       case of a capsule@>;
6226   }
6227   q=null;
6228   while ( name_type(p)>mp_saved_root ) {
6229     @<Ascend one level, pushing a token onto list |q|
6230      and replacing |p| by its parent@>;
6231   }
6232   r=mp_get_avail(mp); info(r)=link(p); link(r)=q;
6233   if ( name_type(p)==mp_saved_root ) mp_print(mp, "(SAVED)");
6234 @.SAVED@>
6235   mp_show_token_list(mp, r,null,el_gordo,mp->tally); 
6236   mp_flush_token_list(mp, r);
6237 }
6238
6239 @ @<Ascend one level, pushing a token onto list |q|...@>=
6240
6241   if ( name_type(p)==mp_subscr ) { 
6242     r=mp_new_num_tok(mp, subscript(p));
6243     do {  
6244       p=link(p);
6245     } while (name_type(p)!=mp_attr);
6246   } else if ( name_type(p)==mp_structured_root ) {
6247     p=link(p); goto FOUND;
6248   } else { 
6249     if ( name_type(p)!=mp_attr ) mp_confusion(mp, "var");
6250 @:this can't happen var}{\quad var@>
6251     r=mp_get_avail(mp); info(r)=attr_loc(p);
6252   }
6253   link(r)=q; q=r;
6254 FOUND:  
6255   p=parent(p);
6256 }
6257
6258 @ @<Preface the output with a part specifier...@>=
6259 { switch (name_type(p)) {
6260   case mp_x_part_sector: mp_print_char(mp, 'x'); break;
6261   case mp_y_part_sector: mp_print_char(mp, 'y'); break;
6262   case mp_xx_part_sector: mp_print(mp, "xx"); break;
6263   case mp_xy_part_sector: mp_print(mp, "xy"); break;
6264   case mp_yx_part_sector: mp_print(mp, "yx"); break;
6265   case mp_yy_part_sector: mp_print(mp, "yy"); break;
6266   case mp_red_part_sector: mp_print(mp, "red"); break;
6267   case mp_green_part_sector: mp_print(mp, "green"); break;
6268   case mp_blue_part_sector: mp_print(mp, "blue"); break;
6269   case mp_cyan_part_sector: mp_print(mp, "cyan"); break;
6270   case mp_magenta_part_sector: mp_print(mp, "magenta"); break;
6271   case mp_yellow_part_sector: mp_print(mp, "yellow"); break;
6272   case mp_black_part_sector: mp_print(mp, "black"); break;
6273   case mp_grey_part_sector: mp_print(mp, "grey"); break;
6274   case mp_capsule: 
6275     mp_print(mp, "%CAPSULE"); mp_print_int(mp, p-null); return;
6276     break;
6277 @.CAPSULE@>
6278   } /* there are no other cases */
6279   mp_print(mp, "part "); 
6280   p=link(p-mp->sector_offset[name_type(p)]);
6281 }
6282
6283 @ The |interesting| function returns |true| if a given variable is not
6284 in a capsule, or if the user wants to trace capsules.
6285
6286 @c 
6287 boolean mp_interesting (MP mp,pointer p) {
6288   small_number t; /* a |name_type| */
6289   if ( mp->internal[mp_tracing_capsules]>0 ) {
6290     return true;
6291   } else { 
6292     t=name_type(p);
6293     if ( t>=mp_x_part_sector ) if ( t!=mp_capsule )
6294       t=name_type(link(p-mp->sector_offset[t]));
6295     return (t!=mp_capsule);
6296   }
6297 }
6298
6299 @ Now here is a subroutine that converts an unstructured type into an
6300 equivalent structured type, by inserting a |mp_structured| node that is
6301 capable of growing. This operation is done only when |name_type(p)=root|,
6302 |subscr|, or |attr|.
6303
6304 The procedure returns a pointer to the new node that has taken node~|p|'s
6305 place in the structure. Node~|p| itself does not move, nor are its
6306 |value| or |type| fields changed in any way.
6307
6308 @c 
6309 pointer mp_new_structure (MP mp,pointer p) {
6310   pointer q,r=0; /* list manipulation registers */
6311   switch (name_type(p)) {
6312   case mp_root: 
6313     q=link(p); r=mp_get_node(mp, value_node_size); equiv(q)=r;
6314     break;
6315   case mp_subscr: 
6316     @<Link a new subscript node |r| in place of node |p|@>;
6317     break;
6318   case mp_attr: 
6319     @<Link a new attribute node |r| in place of node |p|@>;
6320     break;
6321   default: 
6322     mp_confusion(mp, "struct");
6323 @:this can't happen struct}{\quad struct@>
6324     break;
6325   }
6326   link(r)=link(p); type(r)=mp_structured; name_type(r)=name_type(p);
6327   attr_head(r)=p; name_type(p)=mp_structured_root;
6328   q=mp_get_node(mp, attr_node_size); link(p)=q; subscr_head(r)=q;
6329   parent(q)=r; type(q)=undefined; name_type(q)=mp_attr; link(q)=end_attr;
6330   attr_loc(q)=collective_subscript; 
6331   return r;
6332 };
6333
6334 @ @<Link a new subscript node |r| in place of node |p|@>=
6335
6336   q=p;
6337   do {  
6338     q=link(q);
6339   } while (name_type(q)!=mp_attr);
6340   q=parent(q); r=subscr_head_loc(q); /* |link(r)=subscr_head(q)| */
6341   do {  
6342     q=r; r=link(r);
6343   } while (r!=p);
6344   r=mp_get_node(mp, subscr_node_size);
6345   link(q)=r; subscript(r)=subscript(p);
6346 }
6347
6348 @ If the attribute is |collective_subscript|, there are two pointers to
6349 node~|p|, so we must change both of them.
6350
6351 @<Link a new attribute node |r| in place of node |p|@>=
6352
6353   q=parent(p); r=attr_head(q);
6354   do {  
6355     q=r; r=link(r);
6356   } while (r!=p);
6357   r=mp_get_node(mp, attr_node_size); link(q)=r;
6358   mp->mem[attr_loc_loc(r)]=mp->mem[attr_loc_loc(p)]; /* copy |attr_loc| and |parent| */
6359   if ( attr_loc(p)==collective_subscript ) { 
6360     q=subscr_head_loc(parent(p));
6361     while ( link(q)!=p ) q=link(q);
6362     link(q)=r;
6363   }
6364 }
6365
6366 @ The |find_variable| routine is given a pointer~|t| to a nonempty token
6367 list of suffixes; it returns a pointer to the corresponding two-word
6368 value. For example, if |t| points to token \.x followed by a numeric
6369 token containing the value~7, |find_variable| finds where the value of
6370 \.{x7} is stored in memory. This may seem a simple task, and it
6371 usually is, except when \.{x7} has never been referenced before.
6372 Indeed, \.x may never have even been subscripted before; complexities
6373 arise with respect to updating the collective subscript information.
6374
6375 If a macro type is detected anywhere along path~|t|, or if the first
6376 item on |t| isn't a |tag_token|, the value |null| is returned.
6377 Otherwise |p| will be a non-null pointer to a node such that
6378 |undefined<type(p)<mp_structured|.
6379
6380 @d abort_find { return null; }
6381
6382 @c 
6383 pointer mp_find_variable (MP mp,pointer t) {
6384   pointer p,q,r,s; /* nodes in the ``value'' line */
6385   pointer pp,qq,rr,ss; /* nodes in the ``collective'' line */
6386   integer n; /* subscript or attribute */
6387   memory_word save_word; /* temporary storage for a word of |mem| */
6388 @^inner loop@>
6389   p=info(t); t=link(t);
6390   if ( (eq_type(p) % outer_tag) != tag_token ) abort_find;
6391   if ( equiv(p)==null ) mp_new_root(mp, p);
6392   p=equiv(p); pp=p;
6393   while ( t!=null ) { 
6394     @<Make sure that both nodes |p| and |pp| are of |mp_structured| type@>;
6395     if ( t<mp->hi_mem_min ) {
6396       @<Descend one level for the subscript |value(t)|@>
6397     } else {
6398       @<Descend one level for the attribute |info(t)|@>;
6399     }
6400     t=link(t);
6401   }
6402   if ( type(pp)>=mp_structured ) {
6403     if ( type(pp)==mp_structured ) pp=attr_head(pp); else abort_find;
6404   }
6405   if ( type(p)==mp_structured ) p=attr_head(p);
6406   if ( type(p)==undefined ) { 
6407     if ( type(pp)==undefined ) { type(pp)=mp_numeric_type; value(pp)=null; };
6408     type(p)=type(pp); value(p)=null;
6409   };
6410   return p;
6411 }
6412
6413 @ Although |pp| and |p| begin together, they diverge when a subscript occurs;
6414 |pp|~stays in the collective line while |p|~goes through actual subscript
6415 values.
6416
6417 @<Make sure that both nodes |p| and |pp|...@>=
6418 if ( type(pp)!=mp_structured ) { 
6419   if ( type(pp)>mp_structured ) abort_find;
6420   ss=mp_new_structure(mp, pp);
6421   if ( p==pp ) p=ss;
6422   pp=ss;
6423 }; /* now |type(pp)=mp_structured| */
6424 if ( type(p)!=mp_structured ) /* it cannot be |>mp_structured| */
6425   p=mp_new_structure(mp, p) /* now |type(p)=mp_structured| */
6426
6427 @ We want this part of the program to be reasonably fast, in case there are
6428 @^inner loop@>
6429 lots of subscripts at the same level of the data structure. Therefore
6430 we store an ``infinite'' value in the word that appears at the end of the
6431 subscript list, even though that word isn't part of a subscript node.
6432
6433 @<Descend one level for the subscript |value(t)|@>=
6434
6435   n=value(t);
6436   pp=link(attr_head(pp)); /* now |attr_loc(pp)=collective_subscript| */
6437   q=link(attr_head(p)); save_word=mp->mem[subscript_loc(q)];
6438   subscript(q)=el_gordo; s=subscr_head_loc(p); /* |link(s)=subscr_head(p)| */
6439   do {  
6440     r=s; s=link(s);
6441   } while (n>subscript(s));
6442   if ( n==subscript(s) ) {
6443     p=s;
6444   } else { 
6445     p=mp_get_node(mp, subscr_node_size); link(r)=p; link(p)=s;
6446     subscript(p)=n; name_type(p)=mp_subscr; type(p)=undefined;
6447   }
6448   mp->mem[subscript_loc(q)]=save_word;
6449 }
6450
6451 @ @<Descend one level for the attribute |info(t)|@>=
6452
6453   n=info(t);
6454   ss=attr_head(pp);
6455   do {  
6456     rr=ss; ss=link(ss);
6457   } while (n>attr_loc(ss));
6458   if ( n<attr_loc(ss) ) { 
6459     qq=mp_get_node(mp, attr_node_size); link(rr)=qq; link(qq)=ss;
6460     attr_loc(qq)=n; name_type(qq)=mp_attr; type(qq)=undefined;
6461     parent(qq)=pp; ss=qq;
6462   }
6463   if ( p==pp ) { 
6464     p=ss; pp=ss;
6465   } else { 
6466     pp=ss; s=attr_head(p);
6467     do {  
6468       r=s; s=link(s);
6469     } while (n>attr_loc(s));
6470     if ( n==attr_loc(s) ) {
6471       p=s;
6472     } else { 
6473       q=mp_get_node(mp, attr_node_size); link(r)=q; link(q)=s;
6474       attr_loc(q)=n; name_type(q)=mp_attr; type(q)=undefined;
6475       parent(q)=p; p=q;
6476     }
6477   }
6478 }
6479
6480 @ Variables lose their former values when they appear in a type declaration,
6481 or when they are defined to be macros or \&{let} equal to something else.
6482 A subroutine will be defined later that recycles the storage associated
6483 with any particular |type| or |value|; our goal now is to study a higher
6484 level process called |flush_variable|, which selectively frees parts of a
6485 variable structure.
6486
6487 This routine has some complexity because of examples such as
6488 `\hbox{\tt numeric x[]a[]b}'
6489 which recycles all variables of the form \.{x[i]a[j]b} (and no others), while
6490 `\hbox{\tt vardef x[]a[]=...}'
6491 discards all variables of the form \.{x[i]a[j]} followed by an arbitrary
6492 suffix, except for the collective node \.{x[]a[]} itself. The obvious way
6493 to handle such examples is to use recursion; so that's what we~do.
6494 @^recursion@>
6495
6496 Parameter |p| points to the root information of the variable;
6497 parameter |t| points to a list of one-word nodes that represent
6498 suffixes, with |info=collective_subscript| for subscripts.
6499
6500 @<Declarations@>=
6501 @<Declare subroutines for printing expressions@>
6502 @<Declare basic dependency-list subroutines@>
6503 @<Declare the recycling subroutines@>
6504 void mp_flush_cur_exp (MP mp,scaled v) ;
6505 @<Declare the procedure called |flush_below_variable|@>
6506
6507 @ @c 
6508 void mp_flush_variable (MP mp,pointer p, pointer t, boolean discard_suffixes) {
6509   pointer q,r; /* list manipulation */
6510   halfword n; /* attribute to match */
6511   while ( t!=null ) { 
6512     if ( type(p)!=mp_structured ) return;
6513     n=info(t); t=link(t);
6514     if ( n==collective_subscript ) { 
6515       r=subscr_head_loc(p); q=link(r); /* |q=subscr_head(p)| */
6516       while ( name_type(q)==mp_subscr ){ 
6517         mp_flush_variable(mp, q,t,discard_suffixes);
6518         if ( t==null ) {
6519           if ( type(q)==mp_structured ) r=q;
6520           else  { link(r)=link(q); mp_free_node(mp, q,subscr_node_size);   }
6521         } else {
6522           r=q;
6523         }
6524         q=link(r);
6525       }
6526     }
6527     p=attr_head(p);
6528     do {  
6529       r=p; p=link(p);
6530     } while (attr_loc(p)<n);
6531     if ( attr_loc(p)!=n ) return;
6532   }
6533   if ( discard_suffixes ) {
6534     mp_flush_below_variable(mp, p);
6535   } else { 
6536     if ( type(p)==mp_structured ) p=attr_head(p);
6537     mp_recycle_value(mp, p);
6538   }
6539 }
6540
6541 @ The next procedure is simpler; it wipes out everything but |p| itself,
6542 which becomes undefined.
6543
6544 @<Declare the procedure called |flush_below_variable|@>=
6545 void mp_flush_below_variable (MP mp, pointer p);
6546
6547 @ @c
6548 void mp_flush_below_variable (MP mp,pointer p) {
6549    pointer q,r; /* list manipulation registers */
6550   if ( type(p)!=mp_structured ) {
6551     mp_recycle_value(mp, p); /* this sets |type(p)=undefined| */
6552   } else { 
6553     q=subscr_head(p);
6554     while ( name_type(q)==mp_subscr ) { 
6555       mp_flush_below_variable(mp, q); r=q; q=link(q);
6556       mp_free_node(mp, r,subscr_node_size);
6557     }
6558     r=attr_head(p); q=link(r); mp_recycle_value(mp, r);
6559     if ( name_type(p)<=mp_saved_root ) mp_free_node(mp, r,value_node_size);
6560     else mp_free_node(mp, r,subscr_node_size);
6561     /* we assume that |subscr_node_size=attr_node_size| */
6562     do {  
6563       mp_flush_below_variable(mp, q); r=q; q=link(q); mp_free_node(mp, r,attr_node_size);
6564     } while (q!=end_attr);
6565     type(p)=undefined;
6566   }
6567 }
6568
6569 @ Just before assigning a new value to a variable, we will recycle the
6570 old value and make the old value undefined. The |und_type| routine
6571 determines what type of undefined value should be given, based on
6572 the current type before recycling.
6573
6574 @c 
6575 small_number mp_und_type (MP mp,pointer p) { 
6576   switch (type(p)) {
6577   case undefined: case mp_vacuous:
6578     return undefined;
6579   case mp_boolean_type: case mp_unknown_boolean:
6580     return mp_unknown_boolean;
6581   case mp_string_type: case mp_unknown_string:
6582     return mp_unknown_string;
6583   case mp_pen_type: case mp_unknown_pen:
6584     return mp_unknown_pen;
6585   case mp_path_type: case mp_unknown_path:
6586     return mp_unknown_path;
6587   case mp_picture_type: case mp_unknown_picture:
6588     return mp_unknown_picture;
6589   case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
6590   case mp_pair_type: case mp_numeric_type: 
6591     return type(p);
6592   case mp_known: case mp_dependent: case mp_proto_dependent: case mp_independent:
6593     return mp_numeric_type;
6594   } /* there are no other cases */
6595   return 0;
6596 }
6597
6598 @ The |clear_symbol| routine is used when we want to redefine the equivalent
6599 of a symbolic token. It must remove any variable structure or macro
6600 definition that is currently attached to that symbol. If the |saving|
6601 parameter is true, a subsidiary structure is saved instead of destroyed.
6602
6603 @c 
6604 void mp_clear_symbol (MP mp,pointer p, boolean saving) {
6605   pointer q; /* |equiv(p)| */
6606   q=equiv(p);
6607   switch (eq_type(p) % outer_tag)  {
6608   case defined_macro:
6609   case secondary_primary_macro:
6610   case tertiary_secondary_macro:
6611   case expression_tertiary_macro: 
6612     if ( ! saving ) mp_delete_mac_ref(mp, q);
6613     break;
6614   case tag_token:
6615     if ( q!=null ) {
6616       if ( saving ) {
6617         name_type(q)=mp_saved_root;
6618       } else { 
6619         mp_flush_below_variable(mp, q); mp_free_node(mp,q,value_node_size); 
6620       }
6621     }
6622     break;
6623   default:
6624     break;
6625   }
6626   mp->eqtb[p]=mp->eqtb[frozen_undefined];
6627 };
6628
6629 @* \[16] Saving and restoring equivalents.
6630 The nested structure given by \&{begingroup} and \&{endgroup}
6631 allows |eqtb| entries to be saved and restored, so that temporary changes
6632 can be made without difficulty.  When the user requests a current value to
6633 be saved, \MP\ puts that value into its ``save stack.'' An appearance of
6634 \&{endgroup} ultimately causes the old values to be removed from the save
6635 stack and put back in their former places.
6636
6637 The save stack is a linked list containing three kinds of entries,
6638 distinguished by their |info| fields. If |p| points to a saved item,
6639 then
6640
6641 \smallskip\hang
6642 |info(p)=0| stands for a group boundary; each \&{begingroup} contributes
6643 such an item to the save stack and each \&{endgroup} cuts back the stack
6644 until the most recent such entry has been removed.
6645
6646 \smallskip\hang
6647 |info(p)=q|, where |1<=q<=hash_end|, means that |mem[p+1]| holds the former
6648 contents of |eqtb[q]|. Such save stack entries are generated by \&{save}
6649 commands or suitable \&{interim} commands.
6650
6651 \smallskip\hang
6652 |info(p)=hash_end+q|, where |q>0|, means that |value(p)| is a |scaled|
6653 integer to be restored to internal parameter number~|q|. Such entries
6654 are generated by \&{interim} commands.
6655
6656 \smallskip\noindent
6657 The global variable |save_ptr| points to the top item on the save stack.
6658
6659 @d save_node_size 2 /* number of words per non-boundary save-stack node */
6660 @d saved_equiv(A) mp->mem[(A)+1].hh /* where an |eqtb| entry gets saved */
6661 @d save_boundary_item(A) { (A)=mp_get_avail(mp); info((A))=0;
6662   link((A))=mp->save_ptr; mp->save_ptr=(A);
6663   }
6664
6665 @<Glob...@>=
6666 pointer save_ptr; /* the most recently saved item */
6667
6668 @ @<Set init...@>=mp->save_ptr=null;
6669
6670 @ The |save_variable| routine is given a hash address |q|; it salts this
6671 address in the save stack, together with its current equivalent,
6672 then makes token~|q| behave as though it were brand new.
6673
6674 Nothing is stacked when |save_ptr=null|, however; there's no way to remove
6675 things from the stack when the program is not inside a group, so there's
6676 no point in wasting the space.
6677
6678 @c void mp_save_variable (MP mp,pointer q) {
6679   pointer p; /* temporary register */
6680   if ( mp->save_ptr!=null ){ 
6681     p=mp_get_node(mp, save_node_size); info(p)=q; link(p)=mp->save_ptr;
6682     saved_equiv(p)=mp->eqtb[q]; mp->save_ptr=p;
6683   }
6684   mp_clear_symbol(mp, q,(mp->save_ptr!=null));
6685 }
6686
6687 @ Similarly, |save_internal| is given the location |q| of an internal
6688 quantity like |mp_tracing_pens|. It creates a save stack entry of the
6689 third kind.
6690
6691 @c void mp_save_internal (MP mp,halfword q) {
6692   pointer p; /* new item for the save stack */
6693   if ( mp->save_ptr!=null ){ 
6694      p=mp_get_node(mp, save_node_size); info(p)=hash_end+q;
6695     link(p)=mp->save_ptr; value(p)=mp->internal[q]; mp->save_ptr=p;
6696   }
6697 }
6698
6699 @ At the end of a group, the |unsave| routine restores all of the saved
6700 equivalents in reverse order. This routine will be called only when there
6701 is at least one boundary item on the save stack.
6702
6703 @c 
6704 void mp_unsave (MP mp) {
6705   pointer q; /* index to saved item */
6706   pointer p; /* temporary register */
6707   while ( info(mp->save_ptr)!=0 ) {
6708     q=info(mp->save_ptr);
6709     if ( q>hash_end ) {
6710       if ( mp->internal[mp_tracing_restores]>0 ) {
6711         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6712         mp_print(mp, mp->int_name[q-(hash_end)]); mp_print_char(mp, '=');
6713         mp_print_scaled(mp, value(mp->save_ptr)); mp_print_char(mp, '}');
6714         mp_end_diagnostic(mp, false);
6715       }
6716       mp->internal[q-(hash_end)]=value(mp->save_ptr);
6717     } else { 
6718       if ( mp->internal[mp_tracing_restores]>0 ) {
6719         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6720         mp_print_text(q); mp_print_char(mp, '}');
6721         mp_end_diagnostic(mp, false);
6722       }
6723       mp_clear_symbol(mp, q,false);
6724       mp->eqtb[q]=saved_equiv(mp->save_ptr);
6725       if ( eq_type(q) % outer_tag==tag_token ) {
6726         p=equiv(q);
6727         if ( p!=null ) name_type(p)=mp_root;
6728       }
6729     }
6730     p=link(mp->save_ptr); 
6731     mp_free_node(mp, mp->save_ptr,save_node_size); mp->save_ptr=p;
6732   }
6733   p=link(mp->save_ptr); free_avail(mp->save_ptr); mp->save_ptr=p;
6734 }
6735
6736 @* \[17] Data structures for paths.
6737 When a \MP\ user specifies a path, \MP\ will create a list of knots
6738 and control points for the associated cubic spline curves. If the
6739 knots are $z_0$, $z_1$, \dots, $z_n$, there are control points
6740 $z_k^+$ and $z_{k+1}^-$ such that the cubic splines between knots
6741 $z_k$ and $z_{k+1}$ are defined by B\'ezier's formula
6742 @:Bezier}{B\'ezier, Pierre Etienne@>
6743 $$\eqalign{z(t)&=B(z_k,z_k^+,z_{k+1}^-,z_{k+1};t)\cr
6744 &=(1-t)^3z_k+3(1-t)^2tz_k^++3(1-t)t^2z_{k+1}^-+t^3z_{k+1}\cr}$$
6745 for |0<=t<=1|.
6746
6747 There is a 8-word node for each knot $z_k$, containing one word of
6748 control information and six words for the |x| and |y| coordinates of
6749 $z_k^-$ and $z_k$ and~$z_k^+$. The control information appears in the
6750 |left_type| and |right_type| fields, which each occupy a quarter of
6751 the first word in the node; they specify properties of the curve as it
6752 enters and leaves the knot. There's also a halfword |link| field,
6753 which points to the following knot, and a final supplementary word (of
6754 which only a quarter is used).
6755
6756 If the path is a closed contour, knots 0 and |n| are identical;
6757 i.e., the |link| in knot |n-1| points to knot~0. But if the path
6758 is not closed, the |left_type| of knot~0 and the |right_type| of knot~|n|
6759 are equal to |endpoint|. In the latter case the |link| in knot~|n| points
6760 to knot~0, and the control points $z_0^-$ and $z_n^+$ are not used.
6761
6762 @d left_type(A)   mp->mem[(A)].hh.b0 /* characterizes the path entering this knot */
6763 @d right_type(A)   mp->mem[(A)].hh.b1 /* characterizes the path leaving this knot */
6764 @d x_coord(A)   mp->mem[(A)+1].sc /* the |x| coordinate of this knot */
6765 @d y_coord(A)   mp->mem[(A)+2].sc /* the |y| coordinate of this knot */
6766 @d left_x(A)   mp->mem[(A)+3].sc /* the |x| coordinate of previous control point */
6767 @d left_y(A)   mp->mem[(A)+4].sc /* the |y| coordinate of previous control point */
6768 @d right_x(A)   mp->mem[(A)+5].sc /* the |x| coordinate of next control point */
6769 @d right_y(A)   mp->mem[(A)+6].sc /* the |y| coordinate of next control point */
6770 @d x_loc(A)   ((A)+1) /* where the |x| coordinate is stored in a knot */
6771 @d y_loc(A)   ((A)+2) /* where the |y| coordinate is stored in a knot */
6772 @d knot_coord(A)   mp->mem[(A)].sc /* |x| or |y| coordinate given |x_loc| or |y_loc| */
6773 @d left_coord(A)   mp->mem[(A)+2].sc
6774   /* coordinate of previous control point given |x_loc| or |y_loc| */
6775 @d right_coord(A)   mp->mem[(A)+4].sc
6776   /* coordinate of next control point given |x_loc| or |y_loc| */
6777 @d knot_node_size 8 /* number of words in a knot node */
6778
6779 @<Types...@>=
6780 enum mp_knot_type {
6781  mp_endpoint=0, /* |left_type| at path beginning and |right_type| at path end */
6782  mp_explicit, /* |left_type| or |right_type| when control points are known */
6783  mp_given, /* |left_type| or |right_type| when a direction is given */
6784  mp_curl, /* |left_type| or |right_type| when a curl is desired */
6785  mp_open, /* |left_type| or |right_type| when \MP\ should choose the direction */
6786  mp_end_cycle
6787 } ;
6788
6789 @ Before the B\'ezier control points have been calculated, the memory
6790 space they will ultimately occupy is taken up by information that can be
6791 used to compute them. There are four cases:
6792
6793 \yskip
6794 \textindent{$\bullet$} If |right_type=mp_open|, the curve should leave
6795 the knot in the same direction it entered; \MP\ will figure out a
6796 suitable direction.
6797
6798 \yskip
6799 \textindent{$\bullet$} If |right_type=mp_curl|, the curve should leave the
6800 knot in a direction depending on the angle at which it enters the next
6801 knot and on the curl parameter stored in |right_curl|.
6802
6803 \yskip
6804 \textindent{$\bullet$} If |right_type=mp_given|, the curve should leave the
6805 knot in a nonzero direction stored as an |angle| in |right_given|.
6806
6807 \yskip
6808 \textindent{$\bullet$} If |right_type=mp_explicit|, the B\'ezier control
6809 point for leaving this knot has already been computed; it is in the
6810 |right_x| and |right_y| fields.
6811
6812 \yskip\noindent
6813 The rules for |left_type| are similar, but they refer to the curve entering
6814 the knot, and to \\{left} fields instead of \\{right} fields.
6815
6816 Non-|explicit| control points will be chosen based on ``tension'' parameters
6817 in the |left_tension| and |right_tension| fields. The
6818 `\&{atleast}' option is represented by negative tension values.
6819 @:at_least_}{\&{atleast} primitive@>
6820
6821 For example, the \MP\ path specification
6822 $$\.{z0..z1..tension atleast 1..\{curl 2\}z2..z3\{-1,-2\}..tension
6823   3 and 4..p},$$
6824 where \.p is the path `\.{z4..controls z45 and z54..z5}', will be represented
6825 by the six knots
6826 \def\lodash{\hbox to 1.1em{\thinspace\hrulefill\thinspace}}
6827 $$\vbox{\halign{#\hfil&&\qquad#\hfil\cr
6828 |left_type|&\\{left} info&|x_coord,y_coord|&|right_type|&\\{right} info\cr
6829 \noalign{\yskip}
6830 |endpoint|&\lodash$,\,$\lodash&$x_0,y_0$&|curl|&$1.0,1.0$\cr
6831 |open|&\lodash$,1.0$&$x_1,y_1$&|open|&\lodash$,-1.0$\cr
6832 |curl|&$2.0,-1.0$&$x_2,y_2$&|curl|&$2.0,1.0$\cr
6833 |given|&$d,1.0$&$x_3,y_3$&|given|&$d,3.0$\cr
6834 |open|&\lodash$,4.0$&$x_4,y_4$&|explicit|&$x_{45},y_{45}$\cr
6835 |explicit|&$x_{54},y_{54}$&$x_5,y_5$&|endpoint|&\lodash$,\,$\lodash\cr}}$$
6836 Here |d| is the |angle| obtained by calling |n_arg(-unity,-two)|.
6837 Of course, this example is more complicated than anything a normal user
6838 would ever write.
6839
6840 These types must satisfy certain restrictions because of the form of \MP's
6841 path syntax:
6842 (i)~|open| type never appears in the same node together with |endpoint|,
6843 |given|, or |curl|.
6844 (ii)~The |right_type| of a node is |explicit| if and only if the
6845 |left_type| of the following node is |explicit|.
6846 (iii)~|endpoint| types occur only at the ends, as mentioned above.
6847
6848 @d left_curl left_x /* curl information when entering this knot */
6849 @d left_given left_x /* given direction when entering this knot */
6850 @d left_tension left_y /* tension information when entering this knot */
6851 @d right_curl right_x /* curl information when leaving this knot */
6852 @d right_given right_x /* given direction when leaving this knot */
6853 @d right_tension right_y /* tension information when leaving this knot */
6854
6855 @ Knots can be user-supplied, or they can be created by program code,
6856 like the |split_cubic| function, or |copy_path|. The distinction is
6857 needed for the cleanup routine that runs after |split_cubic|, because
6858 it should only delete knots it has previously inserted, and never
6859 anything that was user-supplied. In order to be able to differentiate
6860 one knot from another, we will set |originator(p):=mp_metapost_user| when
6861 it appeared in the actual metapost program, and
6862 |originator(p):=mp_program_code| in all other cases.
6863
6864 @d originator(A)   mp->mem[(A)+7].hh.b0 /* the creator of this knot */
6865
6866 @<Types...@>=
6867 enum {
6868   mp_program_code=0, /* not created by a user */
6869   mp_metapost_user, /* created by a user */
6870 };
6871
6872 @ Here is a routine that prints a given knot list
6873 in symbolic form. It illustrates the conventions discussed above,
6874 and checks for anomalies that might arise while \MP\ is being debugged.
6875
6876 @<Declare subroutines for printing expressions@>=
6877 void mp_pr_path (MP mp,pointer h);
6878
6879 @ @c
6880 void mp_pr_path (MP mp,pointer h) {
6881   pointer p,q; /* for list traversal */
6882   p=h;
6883   do {  
6884     q=link(p);
6885     if ( (p==null)||(q==null) ) { 
6886       mp_print_nl(mp, "???"); return; /* this won't happen */
6887 @.???@>
6888     }
6889     @<Print information for adjacent knots |p| and |q|@>;
6890   DONE1:
6891     p=q;
6892     if ( (p!=h)||(left_type(h)!=mp_endpoint) ) {
6893       @<Print two dots, followed by |given| or |curl| if present@>;
6894     }
6895   } while (p!=h);
6896   if ( left_type(h)!=mp_endpoint ) 
6897     mp_print(mp, "cycle");
6898 }
6899
6900 @ @<Print information for adjacent knots...@>=
6901 mp_print_two(mp, x_coord(p),y_coord(p));
6902 switch (right_type(p)) {
6903 case mp_endpoint: 
6904   if ( left_type(p)==mp_open ) mp_print(mp, "{open?}"); /* can't happen */
6905 @.open?@>
6906   if ( (left_type(q)!=mp_endpoint)||(q!=h) ) q=null; /* force an error */
6907   goto DONE1;
6908   break;
6909 case mp_explicit: 
6910   @<Print control points between |p| and |q|, then |goto done1|@>;
6911   break;
6912 case mp_open: 
6913   @<Print information for a curve that begins |open|@>;
6914   break;
6915 case mp_curl:
6916 case mp_given: 
6917   @<Print information for a curve that begins |curl| or |given|@>;
6918   break;
6919 default:
6920   mp_print(mp, "???"); /* can't happen */
6921 @.???@>
6922   break;
6923 }
6924 if ( left_type(q)<=mp_explicit ) {
6925   mp_print(mp, "..control?"); /* can't happen */
6926 @.control?@>
6927 } else if ( (right_tension(p)!=unity)||(left_tension(q)!=unity) ) {
6928   @<Print tension between |p| and |q|@>;
6929 }
6930
6931 @ Since |n_sin_cos| produces |fraction| results, which we will print as if they
6932 were |scaled|, the magnitude of a |given| direction vector will be~4096.
6933
6934 @<Print two dots...@>=
6935
6936   mp_print_nl(mp, " ..");
6937   if ( left_type(p)==mp_given ) { 
6938     mp_n_sin_cos(mp, left_given(p)); mp_print_char(mp, '{');
6939     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ',');
6940     mp_print_scaled(mp, mp->n_sin); mp_print_char(mp, '}');
6941   } else if ( left_type(p)==mp_curl ){ 
6942     mp_print(mp, "{curl "); 
6943     mp_print_scaled(mp, left_curl(p)); mp_print_char(mp, '}');
6944   }
6945 }
6946
6947 @ @<Print tension between |p| and |q|@>=
6948
6949   mp_print(mp, "..tension ");
6950   if ( right_tension(p)<0 ) mp_print(mp, "atleast");
6951   mp_print_scaled(mp, abs(right_tension(p)));
6952   if ( right_tension(p)!=left_tension(q) ){ 
6953     mp_print(mp, " and ");
6954     if ( left_tension(q)<0 ) mp_print(mp, "atleast");
6955     mp_print_scaled(mp, abs(left_tension(q)));
6956   }
6957 }
6958
6959 @ @<Print control points between |p| and |q|, then |goto done1|@>=
6960
6961   mp_print(mp, "..controls "); 
6962   mp_print_two(mp, right_x(p),right_y(p)); 
6963   mp_print(mp, " and ");
6964   if ( left_type(q)!=mp_explicit ) { 
6965     mp_print(mp, "??"); /* can't happen */
6966 @.??@>
6967   } else {
6968     mp_print_two(mp, left_x(q),left_y(q));
6969   }
6970   goto DONE1;
6971 }
6972
6973 @ @<Print information for a curve that begins |open|@>=
6974 if ( (left_type(p)!=mp_explicit)&&(left_type(p)!=mp_open) ) {
6975   mp_print(mp, "{open?}"); /* can't happen */
6976 @.open?@>
6977 }
6978
6979 @ A curl of 1 is shown explicitly, so that the user sees clearly that
6980 \MP's default curl is present.
6981
6982 The code here uses the fact that |left_curl==left_given| and
6983 |right_curl==right_given|.
6984
6985 @<Print information for a curve that begins |curl|...@>=
6986
6987   if ( left_type(p)==mp_open )  
6988     mp_print(mp, "??"); /* can't happen */
6989 @.??@>
6990   if ( right_type(p)==mp_curl ) { 
6991     mp_print(mp, "{curl "); mp_print_scaled(mp, right_curl(p));
6992   } else { 
6993     mp_n_sin_cos(mp, right_given(p)); mp_print_char(mp, '{');
6994     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ','); 
6995     mp_print_scaled(mp, mp->n_sin);
6996   }
6997   mp_print_char(mp, '}');
6998 }
6999
7000 @ It is convenient to have another version of |pr_path| that prints the path
7001 as a diagnostic message.
7002
7003 @<Declare subroutines for printing expressions@>=
7004 void mp_print_path (MP mp,pointer h, char *s, boolean nuline) { 
7005   mp_print_diagnostic(mp, "Path", s, nuline); mp_print_ln(mp);
7006 @.Path at line...@>
7007   mp_pr_path(mp, h);
7008   mp_end_diagnostic(mp, true);
7009 }
7010
7011 @ If we want to duplicate a knot node, we can say |copy_knot|:
7012
7013 @c 
7014 pointer mp_copy_knot (MP mp,pointer p) {
7015   pointer q; /* the copy */
7016   int k; /* runs through the words of a knot node */
7017   q=mp_get_node(mp, knot_node_size);
7018   for (k=0;k<knot_node_size;k++) {
7019     mp->mem[q+k]=mp->mem[p+k];
7020   }
7021   originator(q)=originator(p);
7022   return q;
7023 }
7024
7025 @ The |copy_path| routine makes a clone of a given path.
7026
7027 @c 
7028 pointer mp_copy_path (MP mp, pointer p) {
7029   pointer q,pp,qq; /* for list manipulation */
7030   q=mp_copy_knot(mp, p);
7031   qq=q; pp=link(p);
7032   while ( pp!=p ) { 
7033     link(qq)=mp_copy_knot(mp, pp);
7034     qq=link(qq);
7035     pp=link(pp);
7036   }
7037   link(qq)=q;
7038   return q;
7039 }
7040
7041
7042 @ Just before |ship_out|, knot lists are exported for printing.
7043
7044 The |gr_XXXX| macros are defined in |mppsout.h|.
7045
7046 @c 
7047 struct mp_knot *mp_export_knot (MP mp,pointer p) {
7048   struct mp_knot *q; /* the copy */
7049   if (p==null)
7050      return NULL;
7051   q = mp_xmalloc(mp, 1, sizeof (struct mp_knot));
7052   memset(q,0,sizeof (struct mp_knot));
7053   gr_left_type(q)  = left_type(p);
7054   gr_right_type(q) = right_type(p);
7055   gr_x_coord(q)    = x_coord(p);
7056   gr_y_coord(q)    = y_coord(p);
7057   gr_left_x(q)     = left_x(p);
7058   gr_left_y(q)     = left_y(p);
7059   gr_right_x(q)    = right_x(p);
7060   gr_right_y(q)    = right_y(p);
7061   gr_originator(q) = originator(p);
7062   return q;
7063 }
7064
7065 @ The |export_knot_list| routine therefore also makes a clone 
7066 of a given path.
7067
7068 @c 
7069 struct mp_knot *mp_export_knot_list (MP mp, pointer p) {
7070   struct mp_knot *q, *qq; /* for list manipulation */
7071   pointer pp; /* for list manipulation */
7072   if (p==null)
7073      return NULL;
7074   q=mp_export_knot(mp, p);
7075   qq=q; pp=link(p);
7076   while ( pp!=p ) { 
7077     gr_next_knot(qq)=mp_export_knot(mp, pp);
7078     qq=gr_next_knot(qq);
7079     pp=link(pp);
7080   }
7081   gr_next_knot(qq)=q;
7082   return q;
7083 }
7084
7085
7086 @ Similarly, there's a way to copy the {\sl reverse\/} of a path. This procedure
7087 returns a pointer to the first node of the copy, if the path is a cycle,
7088 but to the final node of a non-cyclic copy. The global
7089 variable |path_tail| will point to the final node of the original path;
7090 this trick makes it easier to implement `\&{doublepath}'.
7091
7092 All node types are assumed to be |endpoint| or |explicit| only.
7093
7094 @c 
7095 pointer mp_htap_ypoc (MP mp,pointer p) {
7096   pointer q,pp,qq,rr; /* for list manipulation */
7097   q=mp_get_node(mp, knot_node_size); /* this will correspond to |p| */
7098   qq=q; pp=p;
7099   while (1) { 
7100     right_type(qq)=left_type(pp); left_type(qq)=right_type(pp);
7101     x_coord(qq)=x_coord(pp); y_coord(qq)=y_coord(pp);
7102     right_x(qq)=left_x(pp); right_y(qq)=left_y(pp);
7103     left_x(qq)=right_x(pp); left_y(qq)=right_y(pp);
7104     originator(qq)=originator(pp);
7105     if ( link(pp)==p ) { 
7106       link(q)=qq; mp->path_tail=pp; return q;
7107     }
7108     rr=mp_get_node(mp, knot_node_size); link(rr)=qq; qq=rr; pp=link(pp);
7109   }
7110 }
7111
7112 @ @<Glob...@>=
7113 pointer path_tail; /* the node that links to the beginning of a path */
7114
7115 @ When a cyclic list of knot nodes is no longer needed, it can be recycled by
7116 calling the following subroutine.
7117
7118 @<Declare the recycling subroutines@>=
7119 void mp_toss_knot_list (MP mp,pointer p) ;
7120
7121 @ @c
7122 void mp_toss_knot_list (MP mp,pointer p) {
7123   pointer q; /* the node being freed */
7124   pointer r; /* the next node */
7125   q=p;
7126   do {  
7127     r=link(q); 
7128     mp_free_node(mp, q,knot_node_size); q=r;
7129   } while (q!=p);
7130 }
7131
7132 @* \[18] Choosing control points.
7133 Now we must actually delve into one of \MP's more difficult routines,
7134 the |make_choices| procedure that chooses angles and control points for
7135 the splines of a curve when the user has not specified them explicitly.
7136 The parameter to |make_choices| points to a list of knots and
7137 path information, as described above.
7138
7139 A path decomposes into independent segments at ``breakpoint'' knots,
7140 which are knots whose left and right angles are both prespecified in
7141 some way (i.e., their |left_type| and |right_type| aren't both open).
7142
7143 @c 
7144 @<Declare the procedure called |solve_choices|@>;
7145 void mp_make_choices (MP mp,pointer knots) {
7146   pointer h; /* the first breakpoint */
7147   pointer p,q; /* consecutive breakpoints being processed */
7148   @<Other local variables for |make_choices|@>;
7149   check_arith; /* make sure that |arith_error=false| */
7150   if ( mp->internal[mp_tracing_choices]>0 )
7151     mp_print_path(mp, knots,", before choices",true);
7152   @<If consecutive knots are equal, join them explicitly@>;
7153   @<Find the first breakpoint, |h|, on the path;
7154     insert an artificial breakpoint if the path is an unbroken cycle@>;
7155   p=h;
7156   do {  
7157     @<Fill in the control points between |p| and the next breakpoint,
7158       then advance |p| to that breakpoint@>;
7159   } while (p!=h);
7160   if ( mp->internal[mp_tracing_choices]>0 )
7161     mp_print_path(mp, knots,", after choices",true);
7162   if ( mp->arith_error ) {
7163     @<Report an unexpected problem during the choice-making@>;
7164   }
7165 }
7166
7167 @ @<Report an unexpected problem during the choice...@>=
7168
7169   print_err("Some number got too big");
7170 @.Some number got too big@>
7171   help2("The path that I just computed is out of range.")
7172        ("So it will probably look funny. Proceed, for a laugh.");
7173   mp_put_get_error(mp); mp->arith_error=false;
7174 }
7175
7176 @ Two knots in a row with the same coordinates will always be joined
7177 by an explicit ``curve'' whose control points are identical with the
7178 knots.
7179
7180 @<If consecutive knots are equal, join them explicitly@>=
7181 p=knots;
7182 do {  
7183   q=link(p);
7184   if ( x_coord(p)==x_coord(q) && y_coord(p)==y_coord(q) && right_type(p)>mp_explicit ) { 
7185     right_type(p)=mp_explicit;
7186     if ( left_type(p)==mp_open ) { 
7187       left_type(p)=mp_curl; left_curl(p)=unity;
7188     }
7189     left_type(q)=mp_explicit;
7190     if ( right_type(q)==mp_open ) { 
7191       right_type(q)=mp_curl; right_curl(q)=unity;
7192     }
7193     right_x(p)=x_coord(p); left_x(q)=x_coord(p);
7194     right_y(p)=y_coord(p); left_y(q)=y_coord(p);
7195   }
7196   p=q;
7197 } while (p!=knots)
7198
7199 @ If there are no breakpoints, it is necessary to compute the direction
7200 angles around an entire cycle. In this case the |left_type| of the first
7201 node is temporarily changed to |end_cycle|.
7202
7203 @<Find the first breakpoint, |h|, on the path...@>=
7204 h=knots;
7205 while (1) { 
7206   if ( left_type(h)!=mp_open ) break;
7207   if ( right_type(h)!=mp_open ) break;
7208   h=link(h);
7209   if ( h==knots ) { 
7210     left_type(h)=mp_end_cycle; break;
7211   }
7212 }
7213
7214 @ If |right_type(p)<given| and |q=link(p)|, we must have
7215 |right_type(p)=left_type(q)=mp_explicit| or |endpoint|.
7216
7217 @<Fill in the control points between |p| and the next breakpoint...@>=
7218 q=link(p);
7219 if ( right_type(p)>=mp_given ) { 
7220   while ( (left_type(q)==mp_open)&&(right_type(q)==mp_open) ) q=link(q);
7221   @<Fill in the control information between
7222     consecutive breakpoints |p| and |q|@>;
7223 } else if ( right_type(p)==mp_endpoint ) {
7224   @<Give reasonable values for the unused control points between |p| and~|q|@>;
7225 }
7226 p=q
7227
7228 @ This step makes it possible to transform an explicitly computed path without
7229 checking the |left_type| and |right_type| fields.
7230
7231 @<Give reasonable values for the unused control points between |p| and~|q|@>=
7232
7233   right_x(p)=x_coord(p); right_y(p)=y_coord(p);
7234   left_x(q)=x_coord(q); left_y(q)=y_coord(q);
7235 }
7236
7237 @ Before we can go further into the way choices are made, we need to
7238 consider the underlying theory. The basic ideas implemented in |make_choices|
7239 are due to John Hobby, who introduced the notion of ``mock curvature''
7240 @^Hobby, John Douglas@>
7241 at a knot. Angles are chosen so that they preserve mock curvature when
7242 a knot is passed, and this has been found to produce excellent results.
7243
7244 It is convenient to introduce some notations that simplify the necessary
7245 formulas. Let $d_{k,k+1}=\vert z\k-z_k\vert$ be the (nonzero) distance
7246 between knots |k| and |k+1|; and let
7247 $${z\k-z_k\over z_k-z_{k-1}}={d_{k,k+1}\over d_{k-1,k}}e^{i\psi_k}$$
7248 so that a polygonal line from $z_{k-1}$ to $z_k$ to $z\k$ turns left
7249 through an angle of~$\psi_k$. We assume that $\vert\psi_k\vert\L180^\circ$.
7250 The control points for the spline from $z_k$ to $z\k$ will be denoted by
7251 $$\eqalign{z_k^+&=z_k+
7252   \textstyle{1\over3}\rho_k e^{i\theta_k}(z\k-z_k),\cr
7253  z\k^-&=z\k-
7254   \textstyle{1\over3}\sigma\k e^{-i\phi\k}(z\k-z_k),\cr}$$
7255 where $\rho_k$ and $\sigma\k$ are nonnegative ``velocity ratios'' at the
7256 beginning and end of the curve, while $\theta_k$ and $\phi\k$ are the
7257 corresponding ``offset angles.'' These angles satisfy the condition
7258 $$\theta_k+\phi_k+\psi_k=0,\eqno(*)$$
7259 whenever the curve leaves an intermediate knot~|k| in the direction that
7260 it enters.
7261
7262 @ Let $\alpha_k$ and $\beta\k$ be the reciprocals of the ``tension'' of
7263 the curve at its beginning and ending points. This means that
7264 $\rho_k=\alpha_k f(\theta_k,\phi\k)$ and $\sigma\k=\beta\k f(\phi\k,\theta_k)$,
7265 where $f(\theta,\phi)$ is \MP's standard velocity function defined in
7266 the |velocity| subroutine. The cubic spline $B(z_k^{\phantom+},z_k^+,
7267 z\k^-,z\k^{\phantom+};t)$
7268 has curvature
7269 @^curvature@>
7270 $${2\sigma\k\sin(\theta_k+\phi\k)-6\sin\theta_k\over\rho_k^2d_{k,k+1}}
7271 \qquad{\rm and}\qquad
7272 {2\rho_k\sin(\theta_k+\phi\k)-6\sin\phi\k\over\sigma\k^2d_{k,k+1}}$$
7273 at |t=0| and |t=1|, respectively. The mock curvature is the linear
7274 @^mock curvature@>
7275 approximation to this true curvature that arises in the limit for
7276 small $\theta_k$ and~$\phi\k$, if second-order terms are discarded.
7277 The standard velocity function satisfies
7278 $$f(\theta,\phi)=1+O(\theta^2+\theta\phi+\phi^2);$$
7279 hence the mock curvatures are respectively
7280 $${2\beta\k(\theta_k+\phi\k)-6\theta_k\over\alpha_k^2d_{k,k+1}}
7281 \qquad{\rm and}\qquad
7282 {2\alpha_k(\theta_k+\phi\k)-6\phi\k\over\beta\k^2d_{k,k+1}}.\eqno(**)$$
7283
7284 @ The turning angles $\psi_k$ are given, and equation $(*)$ above
7285 determines $\phi_k$ when $\theta_k$ is known, so the task of
7286 angle selection is essentially to choose appropriate values for each
7287 $\theta_k$. When equation~$(*)$ is used to eliminate $\phi$~variables
7288 from $(**)$, we obtain a system of linear equations of the form
7289 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7290 where
7291 $$A_k={\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7292 \qquad B_k={3-\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7293 \qquad C_k={3-\beta\k\over\alpha_k^2d_{k,k+1}},
7294 \qquad D_k={\beta\k\over\alpha_k^2d_{k,k+1}}.$$
7295 The tensions are always $3\over4$ or more, hence each $\alpha$ and~$\beta$
7296 will be at most $4\over3$. It follows that $B_k\G{5\over4}A_k$ and
7297 $C_k\G{5\over4}D_k$; hence the equations are diagonally dominant;
7298 hence they have a unique solution. Moreover, in most cases the tensions
7299 are equal to~1, so that $B_k=2A_k$ and $C_k=2D_k$. This makes the
7300 solution numerically stable, and there is an exponential damping
7301 effect: The data at knot $k\pm j$ affects the angle at knot~$k$ by
7302 a factor of~$O(2^{-j})$.
7303
7304 @ However, we still must consider the angles at the starting and ending
7305 knots of a non-cyclic path. These angles might be given explicitly, or
7306 they might be specified implicitly in terms of an amount of ``curl.''
7307
7308 Let's assume that angles need to be determined for a non-cyclic path
7309 starting at $z_0$ and ending at~$z_n$. Then equations of the form
7310 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta_{k+1}=R_k$$
7311 have been given for $0<k<n$, and it will be convenient to introduce
7312 equations of the same form for $k=0$ and $k=n$, where
7313 $$A_0=B_0=C_n=D_n=0.$$
7314 If $\theta_0$ is supposed to have a given value $E_0$, we simply
7315 define $C_0=0$, $D_0=0$, and $R_0=E_0$. Otherwise a curl
7316 parameter, $\gamma_0$, has been specified at~$z_0$; this means
7317 that the mock curvature at $z_0$ should be $\gamma_0$ times the
7318 mock curvature at $z_1$; i.e.,
7319 $${2\beta_1(\theta_0+\phi_1)-6\theta_0\over\alpha_0^2d_{01}}
7320 =\gamma_0{2\alpha_0(\theta_0+\phi_1)-6\phi_1\over\beta_1^2d_{01}}.$$
7321 This equation simplifies to
7322 $$(\alpha_0\chi_0+3-\beta_1)\theta_0+
7323  \bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\theta_1=
7324  -\bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\psi_1,$$
7325 where $\chi_0=\alpha_0^2\gamma_0/\beta_1^2$; so we can set $C_0=
7326 \chi_0\alpha_0+3-\beta_1$, $D_0=(3-\alpha_0)\chi_0+\beta_1$, $R_0=-D_0\psi_1$.
7327 It can be shown that $C_0>0$ and $C_0B_1-A_1D_0>0$ when $\gamma_0\G0$,
7328 hence the linear equations remain nonsingular.
7329
7330 Similar considerations apply at the right end, when the final angle $\phi_n$
7331 may or may not need to be determined. It is convenient to let $\psi_n=0$,
7332 hence $\theta_n=-\phi_n$. We either have an explicit equation $\theta_n=E_n$,
7333 or we have
7334 $$\bigl((3-\beta_n)\chi_n+\alpha_{n-1}\bigr)\theta_{n-1}+
7335 (\beta_n\chi_n+3-\alpha_{n-1})\theta_n=0,\qquad
7336   \chi_n={\beta_n^2\gamma_n\over\alpha_{n-1}^2}.$$
7337
7338 When |make_choices| chooses angles, it must compute the coefficients of
7339 these linear equations, then solve the equations. To compute the coefficients,
7340 it is necessary to compute arctangents of the given turning angles~$\psi_k$.
7341 When the equations are solved, the chosen directions $\theta_k$ are put
7342 back into the form of control points by essentially computing sines and
7343 cosines.
7344
7345 @ OK, we are ready to make the hard choices of |make_choices|.
7346 Most of the work is relegated to an auxiliary procedure
7347 called |solve_choices|, which has been introduced to keep
7348 |make_choices| from being extremely long.
7349
7350 @<Fill in the control information between...@>=
7351 @<Calculate the turning angles $\psi_k$ and the distances $d_{k,k+1}$;
7352   set $n$ to the length of the path@>;
7353 @<Remove |open| types at the breakpoints@>;
7354 mp_solve_choices(mp, p,q,n)
7355
7356 @ It's convenient to precompute quantities that will be needed several
7357 times later. The values of |delta_x[k]| and |delta_y[k]| will be the
7358 coordinates of $z\k-z_k$, and the magnitude of this vector will be
7359 |delta[k]=@t$d_{k,k+1}$@>|. The path angle $\psi_k$ between $z_k-z_{k-1}$
7360 and $z\k-z_k$ will be stored in |psi[k]|.
7361
7362 @<Glob...@>=
7363 int path_size; /* maximum number of knots between breakpoints of a path */
7364 scaled *delta_x;
7365 scaled *delta_y;
7366 scaled *delta; /* knot differences */
7367 angle  *psi; /* turning angles */
7368
7369 @ @<Allocate or initialize ...@>=
7370 mp->delta_x = NULL;
7371 mp->delta_y = NULL;
7372 mp->delta = NULL;
7373 mp->psi = NULL;
7374
7375 @ @<Dealloc variables@>=
7376 xfree(mp->delta_x);
7377 xfree(mp->delta_y);
7378 xfree(mp->delta);
7379 xfree(mp->psi);
7380
7381 @ @<Other local variables for |make_choices|@>=
7382   int k,n; /* current and final knot numbers */
7383   pointer s,t; /* registers for list traversal */
7384   scaled delx,dely; /* directions where |open| meets |explicit| */
7385   fraction sine,cosine; /* trig functions of various angles */
7386
7387 @ @<Calculate the turning angles...@>=
7388 {
7389 RESTART:
7390   k=0; s=p; n=mp->path_size;
7391   do {  
7392     t=link(s);
7393     mp->delta_x[k]=x_coord(t)-x_coord(s);
7394     mp->delta_y[k]=y_coord(t)-y_coord(s);
7395     mp->delta[k]=mp_pyth_add(mp, mp->delta_x[k],mp->delta_y[k]);
7396     if ( k>0 ) { 
7397       sine=mp_make_fraction(mp, mp->delta_y[k-1],mp->delta[k-1]);
7398       cosine=mp_make_fraction(mp, mp->delta_x[k-1],mp->delta[k-1]);
7399       mp->psi[k]=mp_n_arg(mp, mp_take_fraction(mp, mp->delta_x[k],cosine)+
7400         mp_take_fraction(mp, mp->delta_y[k],sine),
7401         mp_take_fraction(mp, mp->delta_y[k],cosine)-
7402           mp_take_fraction(mp, mp->delta_x[k],sine));
7403     }
7404     incr(k); s=t;
7405     if ( k==mp->path_size ) {
7406       mp_reallocate_paths(mp, mp->path_size+(mp->path_size>>2));
7407       goto RESTART; /* retry, loop size has changed */
7408     }
7409     if ( s==q ) n=k;
7410   } while (!((k>=n)&&(left_type(s)!=mp_end_cycle)));
7411   if ( k==n ) mp->psi[n]=0; else mp->psi[k]=mp->psi[1];
7412 }
7413
7414 @ When we get to this point of the code, |right_type(p)| is either
7415 |given| or |curl| or |open|. If it is |open|, we must have
7416 |left_type(p)=mp_end_cycle| or |left_type(p)=mp_explicit|. In the latter
7417 case, the |open| type is converted to |given|; however, if the
7418 velocity coming into this knot is zero, the |open| type is
7419 converted to a |curl|, since we don't know the incoming direction.
7420
7421 Similarly, |left_type(q)| is either |given| or |curl| or |open| or
7422 |mp_end_cycle|. The |open| possibility is reduced either to |given| or to |curl|.
7423
7424 @<Remove |open| types at the breakpoints@>=
7425 if ( left_type(q)==mp_open ) { 
7426   delx=right_x(q)-x_coord(q); dely=right_y(q)-y_coord(q);
7427   if ( (delx==0)&&(dely==0) ) { 
7428     left_type(q)=mp_curl; left_curl(q)=unity;
7429   } else { 
7430     left_type(q)=mp_given; left_given(q)=mp_n_arg(mp, delx,dely);
7431   }
7432 }
7433 if ( (right_type(p)==mp_open)&&(left_type(p)==mp_explicit) ) { 
7434   delx=x_coord(p)-left_x(p); dely=y_coord(p)-left_y(p);
7435   if ( (delx==0)&&(dely==0) ) { 
7436     right_type(p)=mp_curl; right_curl(p)=unity;
7437   } else { 
7438     right_type(p)=mp_given; right_given(p)=mp_n_arg(mp, delx,dely);
7439   }
7440 }
7441
7442 @ Linear equations need to be solved whenever |n>1|; and also when |n=1|
7443 and exactly one of the breakpoints involves a curl. The simplest case occurs
7444 when |n=1| and there is a curl at both breakpoints; then we simply draw
7445 a straight line.
7446
7447 But before coding up the simple cases, we might as well face the general case,
7448 since we must deal with it sooner or later, and since the general case
7449 is likely to give some insight into the way simple cases can be handled best.
7450
7451 When there is no cycle, the linear equations to be solved form a tridiagonal
7452 system, and we can apply the standard technique of Gaussian elimination
7453 to convert that system to a sequence of equations of the form
7454 $$\theta_0+u_0\theta_1=v_0,\quad
7455 \theta_1+u_1\theta_2=v_1,\quad\ldots,\quad
7456 \theta_{n-1}+u_{n-1}\theta_n=v_{n-1},\quad
7457 \theta_n=v_n.$$
7458 It is possible to do this diagonalization while generating the equations.
7459 Once $\theta_n$ is known, it is easy to determine $\theta_{n-1}$, \dots,
7460 $\theta_1$, $\theta_0$; thus, the equations will be solved.
7461
7462 The procedure is slightly more complex when there is a cycle, but the
7463 basic idea will be nearly the same. In the cyclic case the right-hand
7464 sides will be $v_k+w_k\theta_0$ instead of simply $v_k$, and we will start
7465 the process off with $u_0=v_0=0$, $w_0=1$. The final equation will be not
7466 $\theta_n=v_n$ but $\theta_n+u_n\theta_1=v_n+w_n\theta_0$; an appropriate
7467 ending routine will take account of the fact that $\theta_n=\theta_0$ and
7468 eliminate the $w$'s from the system, after which the solution can be
7469 obtained as before.
7470
7471 When $u_k$, $v_k$, and $w_k$ are being computed, the three pointer
7472 variables |r|, |s|,~|t| will point respectively to knots |k-1|, |k|,
7473 and~|k+1|. The $u$'s and $w$'s are scaled by $2^{28}$, i.e., they are
7474 of type |fraction|; the $\theta$'s and $v$'s are of type |angle|.
7475
7476 @<Glob...@>=
7477 angle *theta; /* values of $\theta_k$ */
7478 fraction *uu; /* values of $u_k$ */
7479 angle *vv; /* values of $v_k$ */
7480 fraction *ww; /* values of $w_k$ */
7481
7482 @ @<Allocate or initialize ...@>=
7483 mp->theta = NULL;
7484 mp->uu = NULL;
7485 mp->vv = NULL;
7486 mp->ww = NULL;
7487
7488 @ @<Dealloc variables@>=
7489 xfree(mp->theta);
7490 xfree(mp->uu);
7491 xfree(mp->vv);
7492 xfree(mp->ww);
7493
7494 @ @<Declare |mp_reallocate| functions@>=
7495 void mp_reallocate_paths (MP mp, int l);
7496
7497 @ @c
7498 void mp_reallocate_paths (MP mp, int l) {
7499   XREALLOC (mp->delta_x, l, scaled);
7500   XREALLOC (mp->delta_y, l, scaled);
7501   XREALLOC (mp->delta,   l, scaled);
7502   XREALLOC (mp->psi,     l, angle);
7503   XREALLOC (mp->theta,   l, angle);
7504   XREALLOC (mp->uu,      l, fraction);
7505   XREALLOC (mp->vv,      l, angle);
7506   XREALLOC (mp->ww,      l, fraction);
7507   mp->path_size = l;
7508 }
7509
7510 @ Our immediate problem is to get the ball rolling by setting up the
7511 first equation or by realizing that no equations are needed, and to fit
7512 this initialization into a framework suitable for the overall computation.
7513
7514 @<Declare the procedure called |solve_choices|@>=
7515 @<Declare subroutines needed by |solve_choices|@>;
7516 void mp_solve_choices (MP mp,pointer p, pointer q, halfword n) {
7517   int k; /* current knot number */
7518   pointer r,s,t; /* registers for list traversal */
7519   @<Other local variables for |solve_choices|@>;
7520   k=0; s=p; r=0;
7521   while (1) { 
7522     t=link(s);
7523     if ( k==0 ) {
7524       @<Get the linear equations started; or |return|
7525         with the control points in place, if linear equations
7526         needn't be solved@>
7527     } else  { 
7528       switch (left_type(s)) {
7529       case mp_end_cycle: case mp_open:
7530         @<Set up equation to match mock curvatures
7531           at $z_k$; then |goto found| with $\theta_n$
7532           adjusted to equal $\theta_0$, if a cycle has ended@>;
7533         break;
7534       case mp_curl:
7535         @<Set up equation for a curl at $\theta_n$
7536           and |goto found|@>;
7537         break;
7538       case mp_given:
7539         @<Calculate the given value of $\theta_n$
7540           and |goto found|@>;
7541         break;
7542       } /* there are no other cases */
7543     }
7544     r=s; s=t; incr(k);
7545   }
7546 FOUND:
7547   @<Finish choosing angles and assigning control points@>;
7548 }
7549
7550 @ On the first time through the loop, we have |k=0| and |r| is not yet
7551 defined. The first linear equation, if any, will have $A_0=B_0=0$.
7552
7553 @<Get the linear equations started...@>=
7554 switch (right_type(s)) {
7555 case mp_given: 
7556   if ( left_type(t)==mp_given ) {
7557     @<Reduce to simple case of two givens  and |return|@>
7558   } else {
7559     @<Set up the equation for a given value of $\theta_0$@>;
7560   }
7561   break;
7562 case mp_curl: 
7563   if ( left_type(t)==mp_curl ) {
7564     @<Reduce to simple case of straight line and |return|@>
7565   } else {
7566     @<Set up the equation for a curl at $\theta_0$@>;
7567   }
7568   break;
7569 case mp_open: 
7570   mp->uu[0]=0; mp->vv[0]=0; mp->ww[0]=fraction_one;
7571   /* this begins a cycle */
7572   break;
7573 } /* there are no other cases */
7574
7575 @ The general equation that specifies equality of mock curvature at $z_k$ is
7576 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7577 as derived above. We want to combine this with the already-derived equation
7578 $\theta_{k-1}+u_{k-1}\theta_k=v_{k-1}+w_{k-1}\theta_0$ in order to obtain
7579 a new equation
7580 $\theta_k+u_k\theta\k=v_k+w_k\theta_0$. This can be done by dividing the
7581 equation
7582 $$(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}
7583     -A_kw_{k-1}\theta_0$$
7584 by $B_k-u_{k-1}A_k+C_k$. The trick is to do this carefully with
7585 fixed-point arithmetic, avoiding the chance of overflow while retaining
7586 suitable precision.
7587
7588 The calculations will be performed in several registers that
7589 provide temporary storage for intermediate quantities.
7590
7591 @<Other local variables for |solve_choices|@>=
7592 fraction aa,bb,cc,ff,acc; /* temporary registers */
7593 scaled dd,ee; /* likewise, but |scaled| */
7594 scaled lt,rt; /* tension values */
7595
7596 @ @<Set up equation to match mock curvatures...@>=
7597 { @<Calculate the values $\\{aa}=A_k/B_k$, $\\{bb}=D_k/C_k$,
7598     $\\{dd}=(3-\alpha_{k-1})d_{k,k+1}$, $\\{ee}=(3-\beta\k)d_{k-1,k}$,
7599     and $\\{cc}=(B_k-u_{k-1}A_k)/B_k$@>;
7600   @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>;
7601   mp->uu[k]=mp_take_fraction(mp, ff,bb);
7602   @<Calculate the values of $v_k$ and $w_k$@>;
7603   if ( left_type(s)==mp_end_cycle ) {
7604     @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>;
7605   }
7606 }
7607
7608 @ Since tension values are never less than 3/4, the values |aa| and
7609 |bb| computed here are never more than 4/5.
7610
7611 @<Calculate the values $\\{aa}=...@>=
7612 if ( abs(right_tension(r))==unity) { 
7613   aa=fraction_half; dd=2*mp->delta[k];
7614 } else { 
7615   aa=mp_make_fraction(mp, unity,3*abs(right_tension(r))-unity);
7616   dd=mp_take_fraction(mp, mp->delta[k],
7617     fraction_three-mp_make_fraction(mp, unity,abs(right_tension(r))));
7618 }
7619 if ( abs(left_tension(t))==unity ){ 
7620   bb=fraction_half; ee=2*mp->delta[k-1];
7621 } else { 
7622   bb=mp_make_fraction(mp, unity,3*abs(left_tension(t))-unity);
7623   ee=mp_take_fraction(mp, mp->delta[k-1],
7624     fraction_three-mp_make_fraction(mp, unity,abs(left_tension(t))));
7625 }
7626 cc=fraction_one-mp_take_fraction(mp, mp->uu[k-1],aa)
7627
7628 @ The ratio to be calculated in this step can be written in the form
7629 $$\beta_k^2\cdot\\{ee}\over\beta_k^2\cdot\\{ee}+\alpha_k^2\cdot
7630   \\{cc}\cdot\\{dd},$$
7631 because of the quantities just calculated. The values of |dd| and |ee|
7632 will not be needed after this step has been performed.
7633
7634 @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>=
7635 dd=mp_take_fraction(mp, dd,cc); lt=abs(left_tension(s)); rt=abs(right_tension(s));
7636 if ( lt!=rt ) { /* $\beta_k^{-1}\ne\alpha_k^{-1}$ */
7637   if ( lt<rt ) { 
7638     ff=mp_make_fraction(mp, lt,rt);
7639     ff=mp_take_fraction(mp, ff,ff); /* $\alpha_k^2/\beta_k^2$ */
7640     dd=mp_take_fraction(mp, dd,ff);
7641   } else { 
7642     ff=mp_make_fraction(mp, rt,lt);
7643     ff=mp_take_fraction(mp, ff,ff); /* $\beta_k^2/\alpha_k^2$ */
7644     ee=mp_take_fraction(mp, ee,ff);
7645   }
7646 }
7647 ff=mp_make_fraction(mp, ee,ee+dd)
7648
7649 @ The value of $u_{k-1}$ will be |<=1| except when $k=1$ and the previous
7650 equation was specified by a curl. In that case we must use a special
7651 method of computation to prevent overflow.
7652
7653 Fortunately, the calculations turn out to be even simpler in this ``hard''
7654 case. The curl equation makes $w_0=0$ and $v_0=-u_0\psi_1$, hence
7655 $-B_1\psi_1-A_1v_0=-(B_1-u_0A_1)\psi_1=-\\{cc}\cdot B_1\psi_1$.
7656
7657 @<Calculate the values of $v_k$ and $w_k$@>=
7658 acc=-mp_take_fraction(mp, mp->psi[k+1],mp->uu[k]);
7659 if ( right_type(r)==mp_curl ) { 
7660   mp->ww[k]=0;
7661   mp->vv[k]=acc-mp_take_fraction(mp, mp->psi[1],fraction_one-ff);
7662 } else { 
7663   ff=mp_make_fraction(mp, fraction_one-ff,cc); /* this is
7664     $B_k/(C_k+B_k-u_{k-1}A_k)<5$ */
7665   acc=acc-mp_take_fraction(mp, mp->psi[k],ff);
7666   ff=mp_take_fraction(mp, ff,aa); /* this is $A_k/(C_k+B_k-u_{k-1}A_k)$ */
7667   mp->vv[k]=acc-mp_take_fraction(mp, mp->vv[k-1],ff);
7668   if ( mp->ww[k-1]==0 ) mp->ww[k]=0;
7669   else mp->ww[k]=-mp_take_fraction(mp, mp->ww[k-1],ff);
7670 }
7671
7672 @ When a complete cycle has been traversed, we have $\theta_k+u_k\theta\k=
7673 v_k+w_k\theta_0$, for |1<=k<=n|. We would like to determine the value of
7674 $\theta_n$ and reduce the system to the form $\theta_k+u_k\theta\k=v_k$
7675 for |0<=k<n|, so that the cyclic case can be finished up just as if there
7676 were no cycle.
7677
7678 The idea in the following code is to observe that
7679 $$\eqalign{\theta_n&=v_n+w_n\theta_0-u_n\theta_1=\cdots\cr
7680 &=v_n+w_n\theta_0-u_n\bigl(v_1+w_1\theta_0-u_1(v_2+\cdots
7681   -u_{n-2}(v_{n-1}+w_{n-1}\theta_0-u_{n-1}\theta_0))\bigr),\cr}$$
7682 so we can solve for $\theta_n=\theta_0$.
7683
7684 @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>=
7685
7686 aa=0; bb=fraction_one; /* we have |k=n| */
7687 do {  decr(k);
7688 if ( k==0 ) k=n;
7689   aa=mp->vv[k]-mp_take_fraction(mp, aa,mp->uu[k]);
7690   bb=mp->ww[k]-mp_take_fraction(mp, bb,mp->uu[k]);
7691 } while (k!=n); /* now $\theta_n=\\{aa}+\\{bb}\cdot\theta_n$ */
7692 aa=mp_make_fraction(mp, aa,fraction_one-bb);
7693 mp->theta[n]=aa; mp->vv[0]=aa;
7694 for (k=1;k<=n-1;k++) {
7695   mp->vv[k]=mp->vv[k]+mp_take_fraction(mp, aa,mp->ww[k]);
7696 }
7697 goto FOUND;
7698 }
7699
7700 @ @d reduce_angle(A) if ( abs((A))>one_eighty_deg ) {
7701   if ( (A)>0 ) (A)=(A)-three_sixty_deg; else (A)=(A)+three_sixty_deg; }
7702
7703 @<Calculate the given value of $\theta_n$...@>=
7704
7705   mp->theta[n]=left_given(s)-mp_n_arg(mp, mp->delta_x[n-1],mp->delta_y[n-1]);
7706   reduce_angle(mp->theta[n]);
7707   goto FOUND;
7708 }
7709
7710 @ @<Set up the equation for a given value of $\theta_0$@>=
7711
7712   mp->vv[0]=right_given(s)-mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7713   reduce_angle(mp->vv[0]);
7714   mp->uu[0]=0; mp->ww[0]=0;
7715 }
7716
7717 @ @<Set up the equation for a curl at $\theta_0$@>=
7718 { cc=right_curl(s); lt=abs(left_tension(t)); rt=abs(right_tension(s));
7719   if ( (rt==unity)&&(lt==unity) )
7720     mp->uu[0]=mp_make_fraction(mp, cc+cc+unity,cc+two);
7721   else 
7722     mp->uu[0]=mp_curl_ratio(mp, cc,rt,lt);
7723   mp->vv[0]=-mp_take_fraction(mp, mp->psi[1],mp->uu[0]); mp->ww[0]=0;
7724 }
7725
7726 @ @<Set up equation for a curl at $\theta_n$...@>=
7727 { cc=left_curl(s); lt=abs(left_tension(s)); rt=abs(right_tension(r));
7728   if ( (rt==unity)&&(lt==unity) )
7729     ff=mp_make_fraction(mp, cc+cc+unity,cc+two);
7730   else 
7731     ff=mp_curl_ratio(mp, cc,lt,rt);
7732   mp->theta[n]=-mp_make_fraction(mp, mp_take_fraction(mp, mp->vv[n-1],ff),
7733     fraction_one-mp_take_fraction(mp, ff,mp->uu[n-1]));
7734   goto FOUND;
7735 }
7736
7737 @ The |curl_ratio| subroutine has three arguments, which our previous notation
7738 encourages us to call $\gamma$, $\alpha^{-1}$, and $\beta^{-1}$. It is
7739 a somewhat tedious program to calculate
7740 $${(3-\alpha)\alpha^2\gamma+\beta^3\over
7741   \alpha^3\gamma+(3-\beta)\beta^2},$$
7742 with the result reduced to 4 if it exceeds 4. (This reduction of curl
7743 is necessary only if the curl and tension are both large.)
7744 The values of $\alpha$ and $\beta$ will be at most~4/3.
7745
7746 @<Declare subroutines needed by |solve_choices|@>=
7747 fraction mp_curl_ratio (MP mp,scaled gamma, scaled a_tension, 
7748                         scaled b_tension) {
7749   fraction alpha,beta,num,denom,ff; /* registers */
7750   alpha=mp_make_fraction(mp, unity,a_tension);
7751   beta=mp_make_fraction(mp, unity,b_tension);
7752   if ( alpha<=beta ) {
7753     ff=mp_make_fraction(mp, alpha,beta); ff=mp_take_fraction(mp, ff,ff);
7754     gamma=mp_take_fraction(mp, gamma,ff);
7755     beta=beta / 010000; /* convert |fraction| to |scaled| */
7756     denom=mp_take_fraction(mp, gamma,alpha)+three-beta;
7757     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7758   } else { 
7759     ff=mp_make_fraction(mp, beta,alpha); ff=mp_take_fraction(mp, ff,ff);
7760     beta=mp_take_fraction(mp, beta,ff) / 010000; /* convert |fraction| to |scaled| */
7761     denom=mp_take_fraction(mp, gamma,alpha)+(ff / 1365)-beta;
7762       /* $1365\approx 2^{12}/3$ */
7763     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7764   }
7765   if ( num>=denom+denom+denom+denom ) return fraction_four;
7766   else return mp_make_fraction(mp, num,denom);
7767 }
7768
7769 @ We're in the home stretch now.
7770
7771 @<Finish choosing angles and assigning control points@>=
7772 for (k=n-1;k>=0;k--) {
7773   mp->theta[k]=mp->vv[k]-mp_take_fraction(mp,mp->theta[k+1],mp->uu[k]);
7774 }
7775 s=p; k=0;
7776 do {  
7777   t=link(s);
7778   mp_n_sin_cos(mp, mp->theta[k]); mp->st=mp->n_sin; mp->ct=mp->n_cos;
7779   mp_n_sin_cos(mp, -mp->psi[k+1]-mp->theta[k+1]); mp->sf=mp->n_sin; mp->cf=mp->n_cos;
7780   mp_set_controls(mp, s,t,k);
7781   incr(k); s=t;
7782 } while (k!=n)
7783
7784 @ The |set_controls| routine actually puts the control points into
7785 a pair of consecutive nodes |p| and~|q|. Global variables are used to
7786 record the values of $\sin\theta$, $\cos\theta$, $\sin\phi$, and
7787 $\cos\phi$ needed in this calculation.
7788
7789 @<Glob...@>=
7790 fraction st;
7791 fraction ct;
7792 fraction sf;
7793 fraction cf; /* sines and cosines */
7794
7795 @ @<Declare subroutines needed by |solve_choices|@>=
7796 void mp_set_controls (MP mp,pointer p, pointer q, integer k) {
7797   fraction rr,ss; /* velocities, divided by thrice the tension */
7798   scaled lt,rt; /* tensions */
7799   fraction sine; /* $\sin(\theta+\phi)$ */
7800   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7801   rr=mp_velocity(mp, mp->st,mp->ct,mp->sf,mp->cf,rt);
7802   ss=mp_velocity(mp, mp->sf,mp->cf,mp->st,mp->ct,lt);
7803   if ( (right_tension(p)<0)||(left_tension(q)<0) ) {
7804     @<Decrease the velocities,
7805       if necessary, to stay inside the bounding triangle@>;
7806   }
7807   right_x(p)=x_coord(p)+mp_take_fraction(mp, 
7808                           mp_take_fraction(mp, mp->delta_x[k],mp->ct)-
7809                           mp_take_fraction(mp, mp->delta_y[k],mp->st),rr);
7810   right_y(p)=y_coord(p)+mp_take_fraction(mp, 
7811                           mp_take_fraction(mp, mp->delta_y[k],mp->ct)+
7812                           mp_take_fraction(mp, mp->delta_x[k],mp->st),rr);
7813   left_x(q)=x_coord(q)-mp_take_fraction(mp, 
7814                          mp_take_fraction(mp, mp->delta_x[k],mp->cf)+
7815                          mp_take_fraction(mp, mp->delta_y[k],mp->sf),ss);
7816   left_y(q)=y_coord(q)-mp_take_fraction(mp, 
7817                          mp_take_fraction(mp, mp->delta_y[k],mp->cf)-
7818                          mp_take_fraction(mp, mp->delta_x[k],mp->sf),ss);
7819   right_type(p)=mp_explicit; left_type(q)=mp_explicit;
7820 }
7821
7822 @ The boundedness conditions $\\{rr}\L\sin\phi\,/\sin(\theta+\phi)$ and
7823 $\\{ss}\L\sin\theta\,/\sin(\theta+\phi)$ are to be enforced if $\sin\theta$,
7824 $\sin\phi$, and $\sin(\theta+\phi)$ all have the same sign. Otherwise
7825 there is no ``bounding triangle.''
7826 @:at_least_}{\&{atleast} primitive@>
7827
7828 @<Decrease the velocities, if necessary...@>=
7829 if (((mp->st>=0)&&(mp->sf>=0))||((mp->st<=0)&&(mp->sf<=0)) ) {
7830   sine=mp_take_fraction(mp, abs(mp->st),mp->cf)+
7831                             mp_take_fraction(mp, abs(mp->sf),mp->ct);
7832   if ( sine>0 ) {
7833     sine=mp_take_fraction(mp, sine,fraction_one+unity); /* safety factor */
7834     if ( right_tension(p)<0 )
7835      if ( mp_ab_vs_cd(mp, abs(mp->sf),fraction_one,rr,sine)<0 )
7836       rr=mp_make_fraction(mp, abs(mp->sf),sine);
7837     if ( left_tension(q)<0 )
7838      if ( mp_ab_vs_cd(mp, abs(mp->st),fraction_one,ss,sine)<0 )
7839       ss=mp_make_fraction(mp, abs(mp->st),sine);
7840   }
7841 }
7842
7843 @ Only the simple cases remain to be handled.
7844
7845 @<Reduce to simple case of two givens and |return|@>=
7846
7847   aa=mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7848   mp_n_sin_cos(mp, right_given(p)-aa); mp->ct=mp->n_cos; mp->st=mp->n_sin;
7849   mp_n_sin_cos(mp, left_given(q)-aa); mp->cf=mp->n_cos; mp->sf=-mp->n_sin;
7850   mp_set_controls(mp, p,q,0); return;
7851 }
7852
7853 @ @<Reduce to simple case of straight line and |return|@>=
7854
7855   right_type(p)=mp_explicit; left_type(q)=mp_explicit;
7856   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7857   if ( rt==unity ) {
7858     if ( mp->delta_x[0]>=0 ) right_x(p)=x_coord(p)+((mp->delta_x[0]+1) / 3);
7859     else right_x(p)=x_coord(p)+((mp->delta_x[0]-1) / 3);
7860     if ( mp->delta_y[0]>=0 ) right_y(p)=y_coord(p)+((mp->delta_y[0]+1) / 3);
7861     else right_y(p)=y_coord(p)+((mp->delta_y[0]-1) / 3);
7862   } else { 
7863     ff=mp_make_fraction(mp, unity,3*rt); /* $\alpha/3$ */
7864     right_x(p)=x_coord(p)+mp_take_fraction(mp, mp->delta_x[0],ff);
7865     right_y(p)=y_coord(p)+mp_take_fraction(mp, mp->delta_y[0],ff);
7866   }
7867   if ( lt==unity ) {
7868     if ( mp->delta_x[0]>=0 ) left_x(q)=x_coord(q)-((mp->delta_x[0]+1) / 3);
7869     else left_x(q)=x_coord(q)-((mp->delta_x[0]-1) / 3);
7870     if ( mp->delta_y[0]>=0 ) left_y(q)=y_coord(q)-((mp->delta_y[0]+1) / 3);
7871     else left_y(q)=y_coord(q)-((mp->delta_y[0]-1) / 3);
7872   } else  { 
7873     ff=mp_make_fraction(mp, unity,3*lt); /* $\beta/3$ */
7874     left_x(q)=x_coord(q)-mp_take_fraction(mp, mp->delta_x[0],ff);
7875     left_y(q)=y_coord(q)-mp_take_fraction(mp, mp->delta_y[0],ff);
7876   }
7877   return;
7878 }
7879
7880 @* \[19] Measuring paths.
7881 \MP's \&{llcorner}, \&{lrcorner}, \&{ulcorner}, and \&{urcorner} operators
7882 allow the user to measure the bounding box of anything that can go into a
7883 picture.  It's easy to get rough bounds on the $x$ and $y$ extent of a path
7884 by just finding the bounding box of the knots and the control points. We
7885 need a more accurate version of the bounding box, but we can still use the
7886 easy estimate to save time by focusing on the interesting parts of the path.
7887
7888 @ Computing an accurate bounding box involves a theme that will come up again
7889 and again. Given a Bernshte{\u\i}n polynomial
7890 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
7891 $$B(z_0,z_1,\ldots,z_n;t)=\sum_k{n\choose k}t^k(1-t)^{n-k}z_k,$$
7892 we can conveniently bisect its range as follows:
7893
7894 \smallskip
7895 \textindent{1)} Let $z_k^{(0)}=z_k$, for |0<=k<=n|.
7896
7897 \smallskip
7898 \textindent{2)} Let $z_k^{(j+1)}={1\over2}(z_k^{(j)}+z\k^{(j)})$, for
7899 |0<=k<n-j|, for |0<=j<n|.
7900
7901 \smallskip\noindent
7902 Then
7903 $$B(z_0,z_1,\ldots,z_n;t)=B(z_0^{(0)},z_0^{(1)},\ldots,z_0^{(n)};2t)
7904  =B(z_0^{(n)},z_1^{(n-1)},\ldots,z_n^{(0)};2t-1).$$
7905 This formula gives us the coefficients of polynomials to use over the ranges
7906 $0\L t\L{1\over2}$ and ${1\over2}\L t\L1$.
7907
7908 @ Now here's a subroutine that's handy for all sorts of path computations:
7909 Given a quadratic polynomial $B(a,b,c;t)$, the |crossing_point| function
7910 returns the unique |fraction| value |t| between 0 and~1 at which
7911 $B(a,b,c;t)$ changes from positive to negative, or returns
7912 |t=fraction_one+1| if no such value exists. If |a<0| (so that $B(a,b,c;t)$
7913 is already negative at |t=0|), |crossing_point| returns the value zero.
7914
7915 @d no_crossing {  return (fraction_one+1); }
7916 @d one_crossing { return fraction_one; }
7917 @d zero_crossing { return 0; }
7918 @d mp_crossing_point(M,A,B,C) mp_do_crossing_point(A,B,C)
7919
7920 @c fraction mp_do_crossing_point (integer a, integer b, integer c) {
7921   integer d; /* recursive counter */
7922   integer x,xx,x0,x1,x2; /* temporary registers for bisection */
7923   if ( a<0 ) zero_crossing;
7924   if ( c>=0 ) { 
7925     if ( b>=0 ) {
7926       if ( c>0 ) { no_crossing; }
7927       else if ( (a==0)&&(b==0) ) { no_crossing;} 
7928       else { one_crossing; } 
7929     }
7930     if ( a==0 ) zero_crossing;
7931   } else if ( a==0 ) {
7932     if ( b<=0 ) zero_crossing;
7933   }
7934   @<Use bisection to find the crossing point, if one exists@>;
7935 }
7936
7937 @ The general bisection method is quite simple when $n=2$, hence
7938 |crossing_point| does not take much time. At each stage in the
7939 recursion we have a subinterval defined by |l| and~|j| such that
7940 $B(a,b,c;2^{-l}(j+t))=B(x_0,x_1,x_2;t)$, and we want to ``zero in'' on
7941 the subinterval where $x_0\G0$ and $\min(x_1,x_2)<0$.
7942
7943 It is convenient for purposes of calculation to combine the values
7944 of |l| and~|j| in a single variable $d=2^l+j$, because the operation
7945 of bisection then corresponds simply to doubling $d$ and possibly
7946 adding~1. Furthermore it proves to be convenient to modify
7947 our previous conventions for bisection slightly, maintaining the
7948 variables $X_0=2^lx_0$, $X_1=2^l(x_0-x_1)$, and $X_2=2^l(x_1-x_2)$.
7949 With these variables the conditions $x_0\ge0$ and $\min(x_1,x_2)<0$ are
7950 equivalent to $\max(X_1,X_1+X_2)>X_0\ge0$.
7951
7952 The following code maintains the invariant relations
7953 $0\L|x0|<\max(|x1|,|x1|+|x2|)$,
7954 $\vert|x1|\vert<2^{30}$, $\vert|x2|\vert<2^{30}$;
7955 it has been constructed in such a way that no arithmetic overflow
7956 will occur if the inputs satisfy
7957 $a<2^{30}$, $\vert a-b\vert<2^{30}$, and $\vert b-c\vert<2^{30}$.
7958
7959 @<Use bisection to find the crossing point...@>=
7960 d=1; x0=a; x1=a-b; x2=b-c;
7961 do {  
7962   x=half(x1+x2);
7963   if ( x1-x0>x0 ) { 
7964     x2=x; x0+=x0; d+=d;  
7965   } else { 
7966     xx=x1+x-x0;
7967     if ( xx>x0 ) { 
7968       x2=x; x0+=x0; d+=d;
7969     }  else { 
7970       x0=x0-xx;
7971       if ( x<=x0 ) { if ( x+x2<=x0 ) no_crossing; }
7972       x1=x; d=d+d+1;
7973     }
7974   }
7975 } while (d<fraction_one);
7976 return (d-fraction_one)
7977
7978 @ Here is a routine that computes the $x$ or $y$ coordinate of the point on
7979 a cubic corresponding to the |fraction| value~|t|.
7980
7981 It is convenient to define a \.{WEB} macro |t_of_the_way| such that
7982 |t_of_the_way(a,b)| expands to |a-(a-b)*t|, i.e., to |t[a,b]|.
7983
7984 @d t_of_the_way(A,B) ((A)-mp_take_fraction(mp,((A)-(B)),t))
7985
7986 @c scaled mp_eval_cubic (MP mp,pointer p, pointer q, fraction t) {
7987   scaled x1,x2,x3; /* intermediate values */
7988   x1=t_of_the_way(knot_coord(p),right_coord(p));
7989   x2=t_of_the_way(right_coord(p),left_coord(q));
7990   x3=t_of_the_way(left_coord(q),knot_coord(q));
7991   x1=t_of_the_way(x1,x2);
7992   x2=t_of_the_way(x2,x3);
7993   return t_of_the_way(x1,x2);
7994 }
7995
7996 @ The actual bounding box information is stored in global variables.
7997 Since it is convenient to address the $x$ and $y$ information
7998 separately, we define arrays indexed by |x_code..y_code| and use
7999 macros to give them more convenient names.
8000
8001 @<Types...@>=
8002 enum mp_bb_code  {
8003   mp_x_code=0, /* index for |minx| and |maxx| */
8004   mp_y_code /* index for |miny| and |maxy| */
8005 } ;
8006
8007
8008 @d minx mp->bbmin[mp_x_code]
8009 @d maxx mp->bbmax[mp_x_code]
8010 @d miny mp->bbmin[mp_y_code]
8011 @d maxy mp->bbmax[mp_y_code]
8012
8013 @<Glob...@>=
8014 scaled bbmin[mp_y_code+1];
8015 scaled bbmax[mp_y_code+1]; 
8016 /* the result of procedures that compute bounding box information */
8017
8018 @ Now we're ready for the key part of the bounding box computation.
8019 The |bound_cubic| procedure updates |bbmin[c]| and |bbmax[c]| based on
8020 $$B(\hbox{|knot_coord(p)|}, \hbox{|right_coord(p)|},
8021     \hbox{|left_coord(q)|}, \hbox{|knot_coord(q)|};t)
8022 $$
8023 for $0<t\le1$.  In other words, the procedure adjusts the bounds to
8024 accommodate |knot_coord(q)| and any extremes over the range $0<t<1$.
8025 The |c| parameter is |x_code| or |y_code|.
8026
8027 @c void mp_bound_cubic (MP mp,pointer p, pointer q, small_number c) {
8028   boolean wavy; /* whether we need to look for extremes */
8029   scaled del1,del2,del3,del,dmax; /* proportional to the control
8030      points of a quadratic derived from a cubic */
8031   fraction t,tt; /* where a quadratic crosses zero */
8032   scaled x; /* a value that |bbmin[c]| and |bbmax[c]| must accommodate */
8033   x=knot_coord(q);
8034   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8035   @<Check the control points against the bounding box and set |wavy:=true|
8036     if any of them lie outside@>;
8037   if ( wavy ) {
8038     del1=right_coord(p)-knot_coord(p);
8039     del2=left_coord(q)-right_coord(p);
8040     del3=knot_coord(q)-left_coord(q);
8041     @<Scale up |del1|, |del2|, and |del3| for greater accuracy;
8042       also set |del| to the first nonzero element of |(del1,del2,del3)|@>;
8043     if ( del<0 ) {
8044       negate(del1); negate(del2); negate(del3);
8045     };
8046     t=mp_crossing_point(mp, del1,del2,del3);
8047     if ( t<fraction_one ) {
8048       @<Test the extremes of the cubic against the bounding box@>;
8049     }
8050   }
8051 }
8052
8053 @ @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>=
8054 if ( x<mp->bbmin[c] ) mp->bbmin[c]=x;
8055 if ( x>mp->bbmax[c] ) mp->bbmax[c]=x
8056
8057 @ @<Check the control points against the bounding box and set...@>=
8058 wavy=true;
8059 if ( mp->bbmin[c]<=right_coord(p) )
8060   if ( right_coord(p)<=mp->bbmax[c] )
8061     if ( mp->bbmin[c]<=left_coord(q) )
8062       if ( left_coord(q)<=mp->bbmax[c] )
8063         wavy=false
8064
8065 @ If |del1=del2=del3=0|, it's impossible to obey the title of this
8066 section. We just set |del=0| in that case.
8067
8068 @<Scale up |del1|, |del2|, and |del3| for greater accuracy...@>=
8069 if ( del1!=0 ) del=del1;
8070 else if ( del2!=0 ) del=del2;
8071 else del=del3;
8072 if ( del!=0 ) {
8073   dmax=abs(del1);
8074   if ( abs(del2)>dmax ) dmax=abs(del2);
8075   if ( abs(del3)>dmax ) dmax=abs(del3);
8076   while ( dmax<fraction_half ) {
8077     dmax+=dmax; del1+=del1; del2+=del2; del3+=del3;
8078   }
8079 }
8080
8081 @ Since |crossing_point| has tried to choose |t| so that
8082 $B(|del1|,|del2|,|del3|;\tau)$ crosses zero at $\tau=|t|$ with negative
8083 slope, the value of |del2| computed below should not be positive.
8084 But rounding error could make it slightly positive in which case we
8085 must cut it to zero to avoid confusion.
8086
8087 @<Test the extremes of the cubic against the bounding box@>=
8088
8089   x=mp_eval_cubic(mp, p,q,t);
8090   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8091   del2=t_of_the_way(del2,del3);
8092     /* now |0,del2,del3| represent the derivative on the remaining interval */
8093   if ( del2>0 ) del2=0;
8094   tt=mp_crossing_point(mp, 0,-del2,-del3);
8095   if ( tt<fraction_one ) {
8096     @<Test the second extreme against the bounding box@>;
8097   }
8098 }
8099
8100 @ @<Test the second extreme against the bounding box@>=
8101 {
8102    x=mp_eval_cubic(mp, p,q,t_of_the_way(tt,fraction_one));
8103   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8104 }
8105
8106 @ Finding the bounding box of a path is basically a matter of applying
8107 |bound_cubic| twice for each pair of adjacent knots.
8108
8109 @c void mp_path_bbox (MP mp,pointer h) {
8110   pointer p,q; /* a pair of adjacent knots */
8111    minx=x_coord(h); miny=y_coord(h);
8112   maxx=minx; maxy=miny;
8113   p=h;
8114   do {  
8115     if ( right_type(p)==mp_endpoint ) return;
8116     q=link(p);
8117     mp_bound_cubic(mp, x_loc(p),x_loc(q),mp_x_code);
8118     mp_bound_cubic(mp, y_loc(p),y_loc(q),mp_y_code);
8119     p=q;
8120   } while (p!=h);
8121 }
8122
8123 @ Another important way to measure a path is to find its arc length.  This
8124 is best done by using the general bisection algorithm to subdivide the path
8125 until obtaining ``well behaved'' subpaths whose arc lengths can be approximated
8126 by simple means.
8127
8128 Since the arc length is the integral with respect to time of the magnitude of
8129 the velocity, it is natural to use Simpson's rule for the approximation.
8130 @^Simpson's rule@>
8131 If $\dot B(t)$ is the spline velocity, Simpson's rule gives
8132 $$ \vb\dot B(0)\vb + 4\vb\dot B({1\over2})\vb + \vb\dot B(1)\vb \over 6 $$
8133 for the arc length of a path of length~1.  For a cubic spline
8134 $B(z_0,z_1,z_2,z_3;t)$, the time derivative $\dot B(t)$ is
8135 $3B(dz_0,dz_1,dz_2;t)$, where $dz_i=z_{i+1}-z_i$.  Hence the arc length
8136 approximation is
8137 $$ {\vb dz_0\vb \over 2} + 2\vb dz_{02}\vb + {\vb dz_2\vb \over 2}, $$
8138 where
8139 $$ dz_{02}={1\over2}\left({dz_0+dz_1\over 2}+{dz_1+dz_2\over 2}\right)$$
8140 is the result of the bisection algorithm.
8141
8142 @ The remaining problem is how to decide when a subpath is ``well behaved.''
8143 This could be done via the theoretical error bound for Simpson's rule,
8144 @^Simpson's rule@>
8145 but this is impractical because it requires an estimate of the fourth
8146 derivative of the quantity being integrated.  It is much easier to just perform
8147 a bisection step and see how much the arc length estimate changes.  Since the
8148 error for Simpson's rule is proportional to the fourth power of the sample
8149 spacing, the remaining error is typically about $1\over16$ of the amount of
8150 the change.  We say ``typically'' because the error has a pseudo-random behavior
8151 that could cause the two estimates to agree when each contain large errors.
8152
8153 To protect against disasters such as undetected cusps, the bisection process
8154 should always continue until all the $dz_i$ vectors belong to a single
8155 $90^\circ$ sector.  This ensures that no point on the spline can have velocity
8156 less than 70\% of the minimum of $\vb dz_0\vb$, $\vb dz_1\vb$ and $\vb dz_2\vb$.
8157 If such a spline happens to produce an erroneous arc length estimate that
8158 is little changed by bisection, the amount of the error is likely to be fairly
8159 small.  We will try to arrange things so that freak accidents of this type do
8160 not destroy the inverse relationship between the \&{arclength} and
8161 \&{arctime} operations.
8162 @:arclength_}{\&{arclength} primitive@>
8163 @:arctime_}{\&{arctime} primitive@>
8164
8165 @ The \&{arclength} and \&{arctime} operations are both based on a recursive
8166 @^recursion@>
8167 function that finds the arc length of a cubic spline given $dz_0$, $dz_1$,
8168 $dz_2$. This |arc_test| routine also takes an arc length goal |a_goal| and
8169 returns the time when the arc length reaches |a_goal| if there is such a time.
8170 Thus the return value is either an arc length less than |a_goal| or, if the
8171 arc length would be at least |a_goal|, it returns a time value decreased by
8172 |two|.  This allows the caller to use the sign of the result to distinguish
8173 between arc lengths and time values.  On certain types of overflow, it is
8174 possible for |a_goal| and the result of |arc_test| both to be |el_gordo|.
8175 Otherwise, the result is always less than |a_goal|.
8176
8177 Rather than halving the control point coordinates on each recursive call to
8178 |arc_test|, it is better to keep them proportional to velocity on the original
8179 curve and halve the results instead.  This means that recursive calls can
8180 potentially use larger error tolerances in their arc length estimates.  How
8181 much larger depends on to what extent the errors behave as though they are
8182 independent of each other.  To save computing time, we use optimistic assumptions
8183 and increase the tolerance by a factor of about $\sqrt2$ for each recursive
8184 call.
8185
8186 In addition to the tolerance parameter, |arc_test| should also have parameters
8187 for ${1\over3}\vb\dot B(0)\vb$, ${2\over3}\vb\dot B({1\over2})\vb$, and
8188 ${1\over3}\vb\dot B(1)\vb$.  These quantities are relatively expensive to compute
8189 and they are needed in different instances of |arc_test|.
8190
8191 @c @t\4@>@<Declare subroutines needed by |arc_test|@>;
8192 scaled mp_arc_test (MP mp, scaled dx0, scaled dy0, scaled dx1, scaled dy1, 
8193                     scaled dx2, scaled dy2, scaled  v0, scaled v02, 
8194                     scaled v2, scaled a_goal, scaled tol) {
8195   boolean simple; /* are the control points confined to a $90^\circ$ sector? */
8196   scaled dx01, dy01, dx12, dy12, dx02, dy02;  /* bisection results */
8197   scaled v002, v022;
8198     /* twice the velocity magnitudes at $t={1\over4}$ and $t={3\over4}$ */
8199   scaled arc; /* best arc length estimate before recursion */
8200   @<Other local variables in |arc_test|@>;
8201   @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,
8202     |dx2|, |dy2|@>;
8203   @<Initialize |v002|, |v022|, and the arc length estimate |arc|; if it overflows
8204     set |arc_test| and |return|@>;
8205   @<Test if the control points are confined to one quadrant or rotating them
8206     $45^\circ$ would put them in one quadrant.  Then set |simple| appropriately@>;
8207   if ( simple && (abs(arc-v02-halfp(v0+v2)) <= tol) ) {
8208     if ( arc < a_goal ) {
8209       return arc;
8210     } else {
8211        @<Estimate when the arc length reaches |a_goal| and set |arc_test| to
8212          that time minus |two|@>;
8213     }
8214   } else {
8215     @<Use one or two recursive calls to compute the |arc_test| function@>;
8216   }
8217 }
8218
8219 @ The |tol| value should by multiplied by $\sqrt 2$ before making recursive
8220 calls, but $1.5$ is an adequate approximation.  It is best to avoid using
8221 |make_fraction| in this inner loop.
8222 @^inner loop@>
8223
8224 @<Use one or two recursive calls to compute the |arc_test| function@>=
8225
8226   @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is as
8227     large as possible@>;
8228   tol = tol + halfp(tol);
8229   a = mp_arc_test(mp, dx0,dy0, dx01,dy01, dx02,dy02, v0, v002, 
8230                   halfp(v02), a_new, tol);
8231   if ( a<0 )  {
8232      return (-halfp(two-a));
8233   } else { 
8234     @<Update |a_new| to reduce |a_new+a_aux| by |a|@>;
8235     b = mp_arc_test(mp, dx02,dy02, dx12,dy12, dx2,dy2,
8236                     halfp(v02), v022, v2, a_new, tol);
8237     if ( b<0 )  
8238       return (-halfp(-b) - half_unit);
8239     else  
8240       return (a + half(b-a));
8241   }
8242 }
8243
8244 @ @<Other local variables in |arc_test|@>=
8245 scaled a,b; /* results of recursive calls */
8246 scaled a_new,a_aux; /* the sum of these gives the |a_goal| */
8247
8248 @ @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is...@>=
8249 a_aux = el_gordo - a_goal;
8250 if ( a_goal > a_aux ) {
8251   a_aux = a_goal - a_aux;
8252   a_new = el_gordo;
8253 } else { 
8254   a_new = a_goal + a_goal;
8255   a_aux = 0;
8256 }
8257
8258 @ There is no need to maintain |a_aux| at this point so we use it as a temporary
8259 to force the additions and subtractions to be done in an order that avoids
8260 overflow.
8261
8262 @<Update |a_new| to reduce |a_new+a_aux| by |a|@>=
8263 if ( a > a_aux ) {
8264   a_aux = a_aux - a;
8265   a_new = a_new + a_aux;
8266 }
8267
8268 @ This code assumes all {\it dx} and {\it dy} variables have magnitude less than
8269 |fraction_four|.  To simplify the rest of the |arc_test| routine, we strengthen
8270 this assumption by requiring the norm of each $({\it dx},{\it dy})$ pair to obey
8271 this bound.  Note that recursive calls will maintain this invariant.
8272
8273 @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,...@>=
8274 dx01 = half(dx0 + dx1);
8275 dx12 = half(dx1 + dx2);
8276 dx02 = half(dx01 + dx12);
8277 dy01 = half(dy0 + dy1);
8278 dy12 = half(dy1 + dy2);
8279 dy02 = half(dy01 + dy12)
8280
8281 @ We should be careful to keep |arc<el_gordo| so that calling |arc_test| with
8282 |a_goal=el_gordo| is guaranteed to yield the arc length.
8283
8284 @<Initialize |v002|, |v022|, and the arc length estimate |arc|;...@>=
8285 v002 = mp_pyth_add(mp, dx01+half(dx0+dx02), dy01+half(dy0+dy02));
8286 v022 = mp_pyth_add(mp, dx12+half(dx02+dx2), dy12+half(dy02+dy2));
8287 tmp = halfp(v02+2);
8288 arc1 = v002 + half(halfp(v0+tmp) - v002);
8289 arc = v022 + half(halfp(v2+tmp) - v022);
8290 if ( (arc < el_gordo-arc1) )  {
8291   arc = arc+arc1;
8292 } else { 
8293   mp->arith_error = true;
8294   if ( a_goal==el_gordo )  return (el_gordo);
8295   else return (-two);
8296 }
8297
8298 @ @<Other local variables in |arc_test|@>=
8299 scaled tmp, tmp2; /* all purpose temporary registers */
8300 scaled arc1; /* arc length estimate for the first half */
8301
8302 @ @<Test if the control points are confined to one quadrant or rotating...@>=
8303 simple = ((dx0>=0) && (dx1>=0) && (dx2>=0)) ||
8304          ((dx0<=0) && (dx1<=0) && (dx2<=0));
8305 if ( simple )
8306   simple = ((dy0>=0) && (dy1>=0) && (dy2>=0)) ||
8307            ((dy0<=0) && (dy1<=0) && (dy2<=0));
8308 if ( ! simple ) {
8309   simple = ((dx0>=dy0) && (dx1>=dy1) && (dx2>=dy2)) ||
8310            ((dx0<=dy0) && (dx1<=dy1) && (dx2<=dy2));
8311   if ( simple ) 
8312     simple = ((-dx0>=dy0) && (-dx1>=dy1) && (-dx2>=dy2)) ||
8313              ((-dx0<=dy0) && (-dx1<=dy1) && (-dx2<=dy2));
8314 }
8315
8316 @ Since Simpson's rule is based on approximating the integrand by a parabola,
8317 @^Simpson's rule@>
8318 it is appropriate to use the same approximation to decide when the integral
8319 reaches the intermediate value |a_goal|.  At this point
8320 $$\eqalign{
8321     {\vb\dot B(0)\vb\over 3} &= \hbox{|v0|}, \qquad
8322     {\vb\dot B({1\over4})\vb\over 3} = {\hbox{|v002|}\over 2}, \qquad
8323     {\vb\dot B({1\over2})\vb\over 3} = {\hbox{|v02|}\over 2}, \cr
8324     {\vb\dot B({3\over4})\vb\over 3} &= {\hbox{|v022|}\over 2}, \qquad
8325     {\vb\dot B(1)\vb\over 3} = \hbox{|v2|} \cr
8326 }
8327 $$
8328 and
8329 $$ {\vb\dot B(t)\vb\over 3} \approx
8330   \cases{B\left(\hbox{|v0|},
8331       \hbox{|v002|}-{1\over 2}\hbox{|v0|}-{1\over 4}\hbox{|v02|},
8332       {1\over 2}\hbox{|v02|}; 2t \right)&
8333     if $t\le{1\over 2}$\cr
8334   B\left({1\over 2}\hbox{|v02|},
8335       \hbox{|v022|}-{1\over 4}\hbox{|v02|}-{1\over 2}\hbox{|v2|},
8336       \hbox{|v2|}; 2t-1 \right)&
8337     if $t\ge{1\over 2}$.\cr}
8338  \eqno (*)
8339 $$
8340 We can integrate $\vb\dot B(t)\vb$ by using
8341 $$\int 3B(a,b,c;\tau)\,dt =
8342   {B(0,a,a+b,a+b+c;\tau) + {\rm constant} \over {d\tau\over dt}}.
8343 $$
8344
8345 This construction allows us to find the time when the arc length reaches
8346 |a_goal| by solving a cubic equation of the form
8347 $$ B(0,a,a+b,a+b+c;\tau) = x, $$
8348 where $\tau$ is $2t$ or $2t+1$, $x$ is |a_goal| or |a_goal-arc1|, and $a$, $b$,
8349 and $c$ are the Bernshte{\u\i}n coefficients from $(*)$ divided by
8350 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
8351 $d\tau\over dt$.  We shall define a function |solve_rising_cubic| that finds
8352 $\tau$ given $a$, $b$, $c$, and $x$.
8353
8354 @<Estimate when the arc length reaches |a_goal| and set |arc_test| to...@>=
8355
8356   tmp = (v02 + 2) / 4;
8357   if ( a_goal<=arc1 ) {
8358     tmp2 = halfp(v0);
8359     return 
8360       (halfp(mp_solve_rising_cubic(mp, tmp2, arc1-tmp2-tmp, tmp, a_goal))- two);
8361   } else { 
8362     tmp2 = halfp(v2);
8363     return ((half_unit - two) +
8364       halfp(mp_solve_rising_cubic(mp, tmp, arc-arc1-tmp-tmp2, tmp2, a_goal-arc1)));
8365   }
8366 }
8367
8368 @ Here is the |solve_rising_cubic| routine that finds the time~$t$ when
8369 $$ B(0, a, a+b, a+b+c; t) = x. $$
8370 This routine is based on |crossing_point| but is simplified by the
8371 assumptions that $B(a,b,c;t)\ge0$ for $0\le t\le1$ and that |0<=x<=a+b+c|.
8372 If rounding error causes this condition to be violated slightly, we just ignore
8373 it and proceed with binary search.  This finds a time when the function value
8374 reaches |x| and the slope is positive.
8375
8376 @<Declare subroutines needed by |arc_test|@>=
8377 scaled mp_solve_rising_cubic (MP mp,scaled a, scaled b,  scaled c, scaled x) {
8378   scaled ab, bc, ac; /* bisection results */
8379   integer t; /* $2^k+q$ where unscaled answer is in $[q2^{-k},(q+1)2^{-k})$ */
8380   integer xx; /* temporary for updating |x| */
8381   if ( (a<0) || (c<0) ) mp_confusion(mp, "rising?");
8382 @:this can't happen rising?}{\quad rising?@>
8383   if ( x<=0 ) {
8384         return 0;
8385   } else if ( x >= a+b+c ) {
8386     return unity;
8387   } else { 
8388     t = 1;
8389     @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than
8390       |el_gordo div 3|@>;
8391     do {  
8392       t+=t;
8393       @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>;
8394       xx = x - a - ab - ac;
8395       if ( xx < -x ) { x+=x; b=ab; c=ac;  }
8396       else { x = x + xx;  a=ac; b=mp->bc; t = t+1; };
8397     } while (t < unity);
8398     return (t - unity);
8399   }
8400 }
8401
8402 @ @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>=
8403 ab = half(a+b);
8404 bc = half(b+c);
8405 ac = half(ab+bc)
8406
8407 @ @d one_third_el_gordo 05252525252 /* upper bound on |a|, |b|, and |c| */
8408
8409 @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than...@>=
8410 while ((a>one_third_el_gordo)||(b>one_third_el_gordo)||(c>one_third_el_gordo)) { 
8411   a = halfp(a);
8412   b = half(b);
8413   c = halfp(c);
8414   x = halfp(x);
8415 }
8416
8417 @ It is convenient to have a simpler interface to |arc_test| that requires no
8418 unnecessary arguments and ensures that each $({\it dx},{\it dy})$ pair has
8419 length less than |fraction_four|.
8420
8421 @d arc_tol   16  /* quit when change in arc length estimate reaches this */
8422
8423 @c scaled mp_do_arc_test (MP mp,scaled dx0, scaled dy0, scaled dx1, 
8424                           scaled dy1, scaled dx2, scaled dy2, scaled a_goal) {
8425   scaled v0,v1,v2; /* length of each $({\it dx},{\it dy})$ pair */
8426   scaled v02; /* twice the norm of the quadratic at $t={1\over2}$ */
8427   v0 = mp_pyth_add(mp, dx0,dy0);
8428   v1 = mp_pyth_add(mp, dx1,dy1);
8429   v2 = mp_pyth_add(mp, dx2,dy2);
8430   if ( (v0>=fraction_four) || (v1>=fraction_four) || (v2>=fraction_four) ) { 
8431     mp->arith_error = true;
8432     if ( a_goal==el_gordo )  return el_gordo;
8433     else return (-two);
8434   } else { 
8435     v02 = mp_pyth_add(mp, dx1+half(dx0+dx2), dy1+half(dy0+dy2));
8436     return (mp_arc_test(mp, dx0,dy0, dx1,dy1, dx2,dy2,
8437                                  v0, v02, v2, a_goal, arc_tol));
8438   }
8439 }
8440
8441 @ Now it is easy to find the arc length of an entire path.
8442
8443 @c scaled mp_get_arc_length (MP mp,pointer h) {
8444   pointer p,q; /* for traversing the path */
8445   scaled a,a_tot; /* current and total arc lengths */
8446   a_tot = 0;
8447   p = h;
8448   while ( right_type(p)!=mp_endpoint ){ 
8449     q = link(p);
8450     a = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8451       left_x(q)-right_x(p), left_y(q)-right_y(p),
8452       x_coord(q)-left_x(q), y_coord(q)-left_y(q), el_gordo);
8453     a_tot = mp_slow_add(mp, a, a_tot);
8454     if ( q==h ) break;  else p=q;
8455   }
8456   check_arith;
8457   return a_tot;
8458 }
8459
8460 @ The inverse operation of finding the time on a path~|h| when the arc length
8461 reaches some value |arc0| can also be accomplished via |do_arc_test|.  Some care
8462 is required to handle very large times or negative times on cyclic paths.  For
8463 non-cyclic paths, |arc0| values that are negative or too large cause
8464 |get_arc_time| to return 0 or the length of path~|h|.
8465
8466 If |arc0| is greater than the arc length of a cyclic path~|h|, the result is a
8467 time value greater than the length of the path.  Since it could be much greater,
8468 we must be prepared to compute the arc length of path~|h| and divide this into
8469 |arc0| to find how many multiples of the length of path~|h| to add.
8470
8471 @c scaled mp_get_arc_time (MP mp,pointer h, scaled  arc0) {
8472   pointer p,q; /* for traversing the path */
8473   scaled t_tot; /* accumulator for the result */
8474   scaled t; /* the result of |do_arc_test| */
8475   scaled arc; /* portion of |arc0| not used up so far */
8476   integer n; /* number of extra times to go around the cycle */
8477   if ( arc0<0 ) {
8478     @<Deal with a negative |arc0| value and |return|@>;
8479   }
8480   if ( arc0==el_gordo ) decr(arc0);
8481   t_tot = 0;
8482   arc = arc0;
8483   p = h;
8484   while ( (right_type(p)!=mp_endpoint) && (arc>0) ) {
8485     q = link(p);
8486     t = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8487       left_x(q)-right_x(p), left_y(q)-right_y(p),
8488       x_coord(q)-left_x(q), y_coord(q)-left_y(q), arc);
8489     @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>;
8490     if ( q==h ) {
8491       @<Update |t_tot| and |arc| to avoid going around the cyclic
8492         path too many times but set |arith_error:=true| and |goto done| on
8493         overflow@>;
8494     }
8495     p = q;
8496   }
8497   check_arith;
8498   return t_tot;
8499 }
8500
8501 @ @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>=
8502 if ( t<0 ) { t_tot = t_tot + t + two;  arc = 0;  }
8503 else { t_tot = t_tot + unity;  arc = arc - t;  }
8504
8505 @ @<Deal with a negative |arc0| value and |return|@>=
8506
8507   if ( left_type(h)==mp_endpoint ) {
8508     t_tot=0;
8509   } else { 
8510     p = mp_htap_ypoc(mp, h);
8511     t_tot = -mp_get_arc_time(mp, p, -arc0);
8512     mp_toss_knot_list(mp, p);
8513   }
8514   check_arith;
8515   return t_tot;
8516 }
8517
8518 @ @<Update |t_tot| and |arc| to avoid going around the cyclic...@>=
8519 if ( arc>0 ) { 
8520   n = arc / (arc0 - arc);
8521   arc = arc - n*(arc0 - arc);
8522   if ( t_tot > el_gordo / (n+1) ) { 
8523     mp->arith_error = true;
8524     t_tot = el_gordo;
8525     break;
8526   }
8527   t_tot = (n + 1)*t_tot;
8528 }
8529
8530 @* \[20] Data structures for pens.
8531 A Pen in \MP\ can be either elliptical or polygonal.  Elliptical pens result
8532 in \ps\ \&{stroke} commands, while anything drawn with a polygonal pen is
8533 @:stroke}{\&{stroke} command@>
8534 converted into an area fill as described in the next part of this program.
8535 The mathematics behind this process is based on simple aspects of the theory
8536 of tracings developed by Leo Guibas, Lyle Ramshaw, and Jorge Stolfi
8537 [``A kinematic framework for computational geometry,'' Proc.\ IEEE Symp.\
8538 Foundations of Computer Science {\bf 24} (1983), 100--111].
8539
8540 Polygonal pens are created from paths via \MP's \&{makepen} primitive.
8541 @:makepen_}{\&{makepen} primitive@>
8542 This path representation is almost sufficient for our purposes except that
8543 a pen path should always be a convex polygon with the vertices in
8544 counter-clockwise order.
8545 Since we will need to scan pen polygons both forward and backward, a pen
8546 should be represented as a doubly linked ring of knot nodes.  There is
8547 room for the extra back pointer because we do not need the
8548 |left_type| or |right_type| fields.  In fact, we don't need the |left_x|,
8549 |left_y|, |right_x|, or |right_y| fields either but we leave these alone
8550 so that certain procedures can operate on both pens and paths.  In particular,
8551 pens can be copied using |copy_path| and recycled using |toss_knot_list|.
8552
8553 @d knil info
8554   /* this replaces the |left_type| and |right_type| fields in a pen knot */
8555
8556 @ The |make_pen| procedure turns a path into a pen by initializing
8557 the |knil| pointers and making sure the knots form a convex polygon.
8558 Thus each cubic in the given path becomes a straight line and the control
8559 points are ignored.  If the path is not cyclic, the ends are connected by a
8560 straight line.
8561
8562 @d copy_pen(A) mp_make_pen(mp, mp_copy_path(mp, (A)),false)
8563
8564 @c @<Declare a function called |convex_hull|@>;
8565 pointer mp_make_pen (MP mp,pointer h, boolean need_hull) {
8566   pointer p,q; /* two consecutive knots */
8567   q=h;
8568   do {  
8569     p=q; q=link(q);
8570     knil(q)=p;
8571   } while (q!=h);
8572   if ( need_hull ){ 
8573     h=mp_convex_hull(mp, h);
8574     @<Make sure |h| isn't confused with an elliptical pen@>;
8575   }
8576   return h;
8577 }
8578
8579 @ The only information required about an elliptical pen is the overall
8580 transformation that has been applied to the original \&{pencircle}.
8581 @:pencircle_}{\&{pencircle} primitive@>
8582 Since it suffices to keep track of how the three points $(0,0)$, $(1,0)$,
8583 and $(0,1)$ are transformed, an elliptical pen can be stored in a single
8584 knot node and transformed as if it were a path.
8585
8586 @d pen_is_elliptical(A) ((A)==link((A)))
8587
8588 @c pointer mp_get_pen_circle (MP mp,scaled diam) {
8589   pointer h; /* the knot node to return */
8590   h=mp_get_node(mp, knot_node_size);
8591   link(h)=h; knil(h)=h;
8592   originator(h)=mp_program_code;
8593   x_coord(h)=0; y_coord(h)=0;
8594   left_x(h)=diam; left_y(h)=0;
8595   right_x(h)=0; right_y(h)=diam;
8596   return h;
8597 }
8598
8599 @ If the polygon being returned by |make_pen| has only one vertex, it will
8600 be interpreted as an elliptical pen.  This is no problem since a degenerate
8601 polygon can equally well be thought of as a degenerate ellipse.  We need only
8602 initialize the |left_x|, |left_y|, |right_x|, and |right_y| fields.
8603
8604 @<Make sure |h| isn't confused with an elliptical pen@>=
8605 if ( pen_is_elliptical( h) ){ 
8606   left_x(h)=x_coord(h); left_y(h)=y_coord(h);
8607   right_x(h)=x_coord(h); right_y(h)=y_coord(h);
8608 }
8609
8610 @ We have to cheat a little here but most operations on pens only use
8611 the first three words in each knot node.
8612 @^data structure assumptions@>
8613
8614 @<Initialize a pen at |test_pen| so that it fits in nine words@>=
8615 x_coord(test_pen)=-half_unit;
8616 y_coord(test_pen)=0;
8617 x_coord(test_pen+3)=half_unit;
8618 y_coord(test_pen+3)=0;
8619 x_coord(test_pen+6)=0;
8620 y_coord(test_pen+6)=unity;
8621 link(test_pen)=test_pen+3;
8622 link(test_pen+3)=test_pen+6;
8623 link(test_pen+6)=test_pen;
8624 knil(test_pen)=test_pen+6;
8625 knil(test_pen+3)=test_pen;
8626 knil(test_pen+6)=test_pen+3
8627
8628 @ Printing a polygonal pen is very much like printing a path
8629
8630 @<Declare subroutines for printing expressions@>=
8631 void mp_pr_pen (MP mp,pointer h) {
8632   pointer p,q; /* for list traversal */
8633   if ( pen_is_elliptical(h) ) {
8634     @<Print the elliptical pen |h|@>;
8635   } else { 
8636     p=h;
8637     do {  
8638       mp_print_two(mp, x_coord(p),y_coord(p));
8639       mp_print_nl(mp, " .. ");
8640       @<Advance |p| making sure the links are OK and |return| if there is
8641         a problem@>;
8642      } while (p!=h);
8643      mp_print(mp, "cycle");
8644   }
8645 }
8646
8647 @ @<Advance |p| making sure the links are OK and |return| if there is...@>=
8648 q=link(p);
8649 if ( (q==null) || (knil(q)!=p) ) { 
8650   mp_print_nl(mp, "???"); return; /* this won't happen */
8651 @.???@>
8652 }
8653 p=q
8654
8655 @ @<Print the elliptical pen |h|@>=
8656
8657 mp_print(mp, "pencircle transformed (");
8658 mp_print_scaled(mp, x_coord(h));
8659 mp_print_char(mp, ',');
8660 mp_print_scaled(mp, y_coord(h));
8661 mp_print_char(mp, ',');
8662 mp_print_scaled(mp, left_x(h)-x_coord(h));
8663 mp_print_char(mp, ',');
8664 mp_print_scaled(mp, right_x(h)-x_coord(h));
8665 mp_print_char(mp, ',');
8666 mp_print_scaled(mp, left_y(h)-y_coord(h));
8667 mp_print_char(mp, ',');
8668 mp_print_scaled(mp, right_y(h)-y_coord(h));
8669 mp_print_char(mp, ')');
8670 }
8671
8672 @ Here us another version of |pr_pen| that prints the pen as a diagnostic
8673 message.
8674
8675 @<Declare subroutines for printing expressions@>=
8676 void mp_print_pen (MP mp,pointer h, char *s, boolean nuline) { 
8677   mp_print_diagnostic(mp, "Pen",s,nuline); mp_print_ln(mp);
8678 @.Pen at line...@>
8679   mp_pr_pen(mp, h);
8680   mp_end_diagnostic(mp, true);
8681 }
8682
8683 @ Making a polygonal pen into a path involves restoring the |left_type| and
8684 |right_type| fields and setting the control points so as to make a polygonal
8685 path.
8686
8687 @c 
8688 void mp_make_path (MP mp,pointer h) {
8689   pointer p; /* for traversing the knot list */
8690   small_number k; /* a loop counter */
8691   @<Other local variables in |make_path|@>;
8692   if ( pen_is_elliptical(h) ) {
8693     @<Make the elliptical pen |h| into a path@>;
8694   } else { 
8695     p=h;
8696     do {  
8697       left_type(p)=mp_explicit;
8698       right_type(p)=mp_explicit;
8699       @<copy the coordinates of knot |p| into its control points@>;
8700        p=link(p);
8701     } while (p!=h);
8702   }
8703 }
8704
8705 @ @<copy the coordinates of knot |p| into its control points@>=
8706 left_x(p)=x_coord(p);
8707 left_y(p)=y_coord(p);
8708 right_x(p)=x_coord(p);
8709 right_y(p)=y_coord(p)
8710
8711 @ We need an eight knot path to get a good approximation to an ellipse.
8712
8713 @<Make the elliptical pen |h| into a path@>=
8714
8715   @<Extract the transformation parameters from the elliptical pen~|h|@>;
8716   p=h;
8717   for (k=0;k<=7;k++ ) { 
8718     @<Initialize |p| as the |k|th knot of a circle of unit diameter,
8719       transforming it appropriately@>;
8720     if ( k==7 ) link(p)=h;  else link(p)=mp_get_node(mp, knot_node_size);
8721     p=link(p);
8722   }
8723 }
8724
8725 @ @<Extract the transformation parameters from the elliptical pen~|h|@>=
8726 center_x=x_coord(h);
8727 center_y=y_coord(h);
8728 width_x=left_x(h)-center_x;
8729 width_y=left_y(h)-center_y;
8730 height_x=right_x(h)-center_x;
8731 height_y=right_y(h)-center_y
8732
8733 @ @<Other local variables in |make_path|@>=
8734 scaled center_x,center_y; /* translation parameters for an elliptical pen */
8735 scaled width_x,width_y; /* the effect of a unit change in $x$ */
8736 scaled height_x,height_y; /* the effect of a unit change in $y$ */
8737 scaled dx,dy; /* the vector from knot |p| to its right control point */
8738 integer kk;
8739   /* |k| advanced $270^\circ$ around the ring (cf. $\sin\theta=\cos(\theta+270)$) */
8740
8741 @ The only tricky thing here are the tables |half_cos| and |d_cos| used to
8742 find the point $k/8$ of the way around the circle and the direction vector
8743 to use there.
8744
8745 @<Initialize |p| as the |k|th knot of a circle of unit diameter,...@>=
8746 kk=(k+6)% 8;
8747 x_coord(p)=center_x+mp_take_fraction(mp, mp->half_cos[k],width_x)
8748            +mp_take_fraction(mp, mp->half_cos[kk],height_x);
8749 y_coord(p)=center_y+mp_take_fraction(mp, mp->half_cos[k],width_y)
8750            +mp_take_fraction(mp, mp->half_cos[kk],height_y);
8751 dx=-mp_take_fraction(mp, mp->d_cos[kk],width_x)
8752    +mp_take_fraction(mp, mp->d_cos[k],height_x);
8753 dy=-mp_take_fraction(mp, mp->d_cos[kk],width_y)
8754    +mp_take_fraction(mp, mp->d_cos[k],height_y);
8755 right_x(p)=x_coord(p)+dx;
8756 right_y(p)=y_coord(p)+dy;
8757 left_x(p)=x_coord(p)-dx;
8758 left_y(p)=y_coord(p)-dy;
8759 left_type(p)=mp_explicit;
8760 right_type(p)=mp_explicit;
8761 originator(p)=mp_program_code
8762
8763 @ @<Glob...@>=
8764 fraction half_cos[8]; /* ${1\over2}\cos(45k)$ */
8765 fraction d_cos[8]; /* a magic constant times $\cos(45k)$ */
8766
8767 @ The magic constant for |d_cos| is the distance between $({1\over2},0)$ and
8768 $({1\over4}\sqrt2,{1\over4}\sqrt2)$ times the result of the |velocity|
8769 function for $\theta=\phi=22.5^\circ$.  This comes out to be
8770 $$ d = {\sqrt{2-\sqrt2}\over 3+3\cos22.5^\circ}
8771   \approx 0.132608244919772.
8772 $$
8773
8774 @<Set init...@>=
8775 mp->half_cos[0]=fraction_half;
8776 mp->half_cos[1]=94906266; /* $2^{26}\sqrt2\approx94906265.62$ */
8777 mp->half_cos[2]=0;
8778 mp->d_cos[0]=35596755; /* $2^{28}d\approx35596754.69$ */
8779 mp->d_cos[1]=25170707; /* $2^{27}\sqrt2\,d\approx25170706.63$ */
8780 mp->d_cos[2]=0;
8781 for (k=3;k<= 4;k++ ) { 
8782   mp->half_cos[k]=-mp->half_cos[4-k];
8783   mp->d_cos[k]=-mp->d_cos[4-k];
8784 }
8785 for (k=5;k<= 7;k++ ) { 
8786   mp->half_cos[k]=mp->half_cos[8-k];
8787   mp->d_cos[k]=mp->d_cos[8-k];
8788 }
8789
8790 @ The |convex_hull| function forces a pen polygon to be convex when it is
8791 returned by |make_pen| and after any subsequent transformation where rounding
8792 error might allow the convexity to be lost.
8793 The convex hull algorithm used here is described by F.~P. Preparata and
8794 M.~I. Shamos [{\sl Computational Geometry}, Springer-Verlag, 1985].
8795
8796 @<Declare a function called |convex_hull|@>=
8797 @<Declare a procedure called |move_knot|@>;
8798 pointer mp_convex_hull (MP mp,pointer h) { /* Make a polygonal pen convex */
8799   pointer l,r; /* the leftmost and rightmost knots */
8800   pointer p,q; /* knots being scanned */
8801   pointer s; /* the starting point for an upcoming scan */
8802   scaled dx,dy; /* a temporary pointer */
8803   if ( pen_is_elliptical(h) ) {
8804      return h;
8805   } else { 
8806     @<Set |l| to the leftmost knot in polygon~|h|@>;
8807     @<Set |r| to the rightmost knot in polygon~|h|@>;
8808     if ( l!=r ) { 
8809       s=link(r);
8810       @<Find any knots on the path from |l| to |r| above the |l|-|r| line and
8811         move them past~|r|@>;
8812       @<Find any knots on the path from |s| to |l| below the |l|-|r| line and
8813         move them past~|l|@>;
8814       @<Sort the path from |l| to |r| by increasing $x$@>;
8815       @<Sort the path from |r| to |l| by decreasing $x$@>;
8816     }
8817     if ( l!=link(l) ) {
8818       @<Do a Gramm scan and remove vertices where there is no left turn@>;
8819     }
8820     return l;
8821   }
8822 }
8823
8824 @ All comparisons are done primarily on $x$ and secondarily on $y$.
8825
8826 @<Set |l| to the leftmost knot in polygon~|h|@>=
8827 l=h;
8828 p=link(h);
8829 while ( p!=h ) { 
8830   if ( x_coord(p)<=x_coord(l) )
8831     if ( (x_coord(p)<x_coord(l)) || (y_coord(p)<y_coord(l)) )
8832       l=p;
8833   p=link(p);
8834 }
8835
8836 @ @<Set |r| to the rightmost knot in polygon~|h|@>=
8837 r=h;
8838 p=link(h);
8839 while ( p!=h ) { 
8840   if ( x_coord(p)>=x_coord(r) )
8841     if ( (x_coord(p)>x_coord(r)) || (y_coord(p)>y_coord(r)) )
8842       r=p;
8843   p=link(p);
8844 }
8845
8846 @ @<Find any knots on the path from |l| to |r| above the |l|-|r| line...@>=
8847 dx=x_coord(r)-x_coord(l);
8848 dy=y_coord(r)-y_coord(l);
8849 p=link(l);
8850 while ( p!=r ) { 
8851   q=link(p);
8852   if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))>0 )
8853     mp_move_knot(mp, p, r);
8854   p=q;
8855 }
8856
8857 @ The |move_knot| procedure removes |p| from a doubly linked list and inserts
8858 it after |q|.
8859
8860 @ @<Declare a procedure called |move_knot|@>=
8861 void mp_move_knot (MP mp,pointer p, pointer q) { 
8862   link(knil(p))=link(p);
8863   knil(link(p))=knil(p);
8864   knil(p)=q;
8865   link(p)=link(q);
8866   link(q)=p;
8867   knil(link(p))=p;
8868 }
8869
8870 @ @<Find any knots on the path from |s| to |l| below the |l|-|r| line...@>=
8871 p=s;
8872 while ( p!=l ) { 
8873   q=link(p);
8874   if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))<0 )
8875     mp_move_knot(mp, p,l);
8876   p=q;
8877 }
8878
8879 @ The list is likely to be in order already so we just do linear insertions.
8880 Secondary comparisons on $y$ ensure that the sort is consistent with the
8881 choice of |l| and |r|.
8882
8883 @<Sort the path from |l| to |r| by increasing $x$@>=
8884 p=link(l);
8885 while ( p!=r ) { 
8886   q=knil(p);
8887   while ( x_coord(q)>x_coord(p) ) q=knil(q);
8888   while ( x_coord(q)==x_coord(p) ) {
8889     if ( y_coord(q)>y_coord(p) ) q=knil(q); else break;
8890   }
8891   if ( q==knil(p) ) p=link(p);
8892   else { p=link(p); mp_move_knot(mp, knil(p),q); };
8893 }
8894
8895 @ @<Sort the path from |r| to |l| by decreasing $x$@>=
8896 p=link(r);
8897 while ( p!=l ){ 
8898   q=knil(p);
8899   while ( x_coord(q)<x_coord(p) ) q=knil(q);
8900   while ( x_coord(q)==x_coord(p) ) {
8901     if ( y_coord(q)<y_coord(p) ) q=knil(q); else break;
8902   }
8903   if ( q==knil(p) ) p=link(p);
8904   else { p=link(p); mp_move_knot(mp, knil(p),q); };
8905 }
8906
8907 @ The condition involving |ab_vs_cd| tests if there is not a left turn
8908 at knot |q|.  There usually will be a left turn so we streamline the case
8909 where the |then| clause is not executed.
8910
8911 @<Do a Gramm scan and remove vertices where there...@>=
8912
8913 p=l; q=link(l);
8914 while (1) { 
8915   dx=x_coord(q)-x_coord(p);
8916   dy=y_coord(q)-y_coord(p);
8917   p=q; q=link(q);
8918   if ( p==l ) break;
8919   if ( p!=r )
8920     if ( mp_ab_vs_cd(mp, dx,y_coord(q)-y_coord(p),dy,x_coord(q)-x_coord(p))<=0 ) {
8921       @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>;
8922     }
8923   }
8924 }
8925
8926 @ @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>=
8927
8928 s=knil(p);
8929 mp_free_node(mp, p,knot_node_size);
8930 link(s)=q; knil(q)=s;
8931 if ( s==l ) p=s;
8932 else { p=knil(s); q=s; };
8933 }
8934
8935 @ The |find_offset| procedure sets global variables |(cur_x,cur_y)| to the
8936 offset associated with the given direction |(x,y)|.  If two different offsets
8937 apply, it chooses one of them.
8938
8939 @c 
8940 void mp_find_offset (MP mp,scaled x, scaled y, pointer h) {
8941   pointer p,q; /* consecutive knots */
8942   scaled wx,wy,hx,hy;
8943   /* the transformation matrix for an elliptical pen */
8944   fraction xx,yy; /* untransformed offset for an elliptical pen */
8945   fraction d; /* a temporary register */
8946   if ( pen_is_elliptical(h) ) {
8947     @<Find the offset for |(x,y)| on the elliptical pen~|h|@>
8948   } else { 
8949     q=h;
8950     do {  
8951       p=q; q=link(q);
8952     } while (!(mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)>=0));
8953     do {  
8954       p=q; q=link(q);
8955     } while (!(mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)<=0));
8956     mp->cur_x=x_coord(p);
8957     mp->cur_y=y_coord(p);
8958   }
8959 }
8960
8961 @ @<Glob...@>=
8962 scaled cur_x;
8963 scaled cur_y; /* all-purpose return value registers */
8964
8965 @ @<Find the offset for |(x,y)| on the elliptical pen~|h|@>=
8966 if ( (x==0) && (y==0) ) {
8967   mp->cur_x=x_coord(h); mp->cur_y=y_coord(h);  
8968 } else { 
8969   @<Find the non-constant part of the transformation for |h|@>;
8970   while ( (abs(x)<fraction_half) && (abs(y)<fraction_half) ){ 
8971     x+=x; y+=y;  
8972   };
8973   @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the
8974     untransformed version of |(x,y)|@>;
8975   mp->cur_x=x_coord(h)+mp_take_fraction(mp, xx,wx)+mp_take_fraction(mp, yy,hx);
8976   mp->cur_y=y_coord(h)+mp_take_fraction(mp, xx,wy)+mp_take_fraction(mp, yy,hy);
8977 }
8978
8979 @ @<Find the non-constant part of the transformation for |h|@>=
8980 wx=left_x(h)-x_coord(h);
8981 wy=left_y(h)-y_coord(h);
8982 hx=right_x(h)-x_coord(h);
8983 hy=right_y(h)-y_coord(h)
8984
8985 @ @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the...@>=
8986 yy=-(mp_take_fraction(mp, x,hy)+mp_take_fraction(mp, y,-hx));
8987 xx=mp_take_fraction(mp, x,-wy)+mp_take_fraction(mp, y,wx);
8988 d=mp_pyth_add(mp, xx,yy);
8989 if ( d>0 ) { 
8990   xx=half(mp_make_fraction(mp, xx,d));
8991   yy=half(mp_make_fraction(mp, yy,d));
8992 }
8993
8994 @ Finding the bounding box of a pen is easy except if the pen is elliptical.
8995 But we can handle that case by just calling |find_offset| twice.  The answer
8996 is stored in the global variables |minx|, |maxx|, |miny|, and |maxy|.
8997
8998 @c 
8999 void mp_pen_bbox (MP mp,pointer h) {
9000   pointer p; /* for scanning the knot list */
9001   if ( pen_is_elliptical(h) ) {
9002     @<Find the bounding box of an elliptical pen@>;
9003   } else { 
9004     minx=x_coord(h); maxx=minx;
9005     miny=y_coord(h); maxy=miny;
9006     p=link(h);
9007     while ( p!=h ) {
9008       if ( x_coord(p)<minx ) minx=x_coord(p);
9009       if ( y_coord(p)<miny ) miny=y_coord(p);
9010       if ( x_coord(p)>maxx ) maxx=x_coord(p);
9011       if ( y_coord(p)>maxy ) maxy=y_coord(p);
9012       p=link(p);
9013     }
9014   }
9015 }
9016
9017 @ @<Find the bounding box of an elliptical pen@>=
9018
9019 mp_find_offset(mp, 0,fraction_one,h);
9020 maxx=mp->cur_x;
9021 minx=2*x_coord(h)-mp->cur_x;
9022 mp_find_offset(mp, -fraction_one,0,h);
9023 maxy=mp->cur_y;
9024 miny=2*y_coord(h)-mp->cur_y;
9025 }
9026
9027 @* \[21] Edge structures.
9028 Now we come to \MP's internal scheme for representing pictures.
9029 The representation is very different from \MF's edge structures
9030 because \MP\ pictures contain \ps\ graphics objects instead of pixel
9031 images.  However, the basic idea is somewhat similar in that shapes
9032 are represented via their boundaries.
9033
9034 The main purpose of edge structures is to keep track of graphical objects
9035 until it is time to translate them into \ps.  Since \MP\ does not need to
9036 know anything about an edge structure other than how to translate it into
9037 \ps\ and how to find its bounding box, edge structures can be just linked
9038 lists of graphical objects.  \MP\ has no easy way to determine whether
9039 two such objects overlap, but it suffices to draw the first one first and
9040 let the second one overwrite it if necessary.
9041
9042 @<Types...@>=
9043 enum mp_graphical_object_code {
9044   @<Graphical object codes@>
9045 };
9046
9047 @ Let's consider the types of graphical objects one at a time.
9048 First of all, a filled contour is represented by a eight-word node.  The first
9049 word contains |type| and |link| fields, and the next six words contain a
9050 pointer to a cyclic path and the value to use for \ps' \&{currentrgbcolor}
9051 parameter.  If a pen is used for filling |pen_p|, |ljoin_val| and |miterlim_val|
9052 give the relevant information.
9053
9054 @d path_p(A) link((A)+1)
9055   /* a pointer to the path that needs filling */
9056 @d pen_p(A) info((A)+1)
9057   /* a pointer to the pen to fill or stroke with */
9058 @d color_model(A) type((A)+2) /*  the color model  */
9059 @d obj_red_loc(A) ((A)+3)  /* the first of three locations for the color */
9060 @d obj_cyan_loc obj_red_loc  /* the first of four locations for the color */
9061 @d obj_grey_loc obj_red_loc  /* the location for the color */
9062 @d red_val(A) mp->mem[(A)+3].sc
9063   /* the red component of the color in the range $0\ldots1$ */
9064 @d cyan_val red_val
9065 @d grey_val red_val
9066 @d green_val(A) mp->mem[(A)+4].sc
9067   /* the green component of the color in the range $0\ldots1$ */
9068 @d magenta_val green_val
9069 @d blue_val(A) mp->mem[(A)+5].sc
9070   /* the blue component of the color in the range $0\ldots1$ */
9071 @d yellow_val blue_val
9072 @d black_val(A) mp->mem[(A)+6].sc
9073   /* the blue component of the color in the range $0\ldots1$ */
9074 @d ljoin_val(A) name_type((A))  /* the value of \&{linejoin} */
9075 @:mp_linejoin_}{\&{linejoin} primitive@>
9076 @d miterlim_val(A) mp->mem[(A)+7].sc  /* the value of \&{miterlimit} */
9077 @:mp_miterlimit_}{\&{miterlimit} primitive@>
9078 @d obj_color_part(A) mp->mem[(A)+3-red_part].sc
9079   /* interpret an object pointer that has been offset by |red_part..blue_part| */
9080 @d pre_script(A) mp->mem[(A)+8].hh.lh
9081 @d post_script(A) mp->mem[(A)+8].hh.rh
9082 @d fill_node_size 9
9083
9084 @ @<Graphical object codes@>=
9085 mp_fill_code=1,
9086
9087 @ @c 
9088 pointer mp_new_fill_node (MP mp,pointer p) {
9089   /* make a fill node for cyclic path |p| and color black */
9090   pointer t; /* the new node */
9091   t=mp_get_node(mp, fill_node_size);
9092   type(t)=mp_fill_code;
9093   path_p(t)=p;
9094   pen_p(t)=null; /* |null| means don't use a pen */
9095   red_val(t)=0;
9096   green_val(t)=0;
9097   blue_val(t)=0;
9098   black_val(t)=0;
9099   color_model(t)=mp_uninitialized_model;
9100   pre_script(t)=null;
9101   post_script(t)=null;
9102   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9103   return t;
9104 }
9105
9106 @ @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>=
9107 if ( mp->internal[mp_linejoin]>unity ) ljoin_val(t)=2;
9108 else if ( mp->internal[mp_linejoin]>0 ) ljoin_val(t)=1;
9109 else ljoin_val(t)=0;
9110 if ( mp->internal[mp_miterlimit]<unity )
9111   miterlim_val(t)=unity;
9112 else
9113   miterlim_val(t)=mp->internal[mp_miterlimit]
9114
9115 @ A stroked path is represented by an eight-word node that is like a filled
9116 contour node except that it contains the current \&{linecap} value, a scale
9117 factor for the dash pattern, and a pointer that is non-null if the stroke
9118 is to be dashed.  The purpose of the scale factor is to allow a picture to
9119 be transformed without touching the picture that |dash_p| points to.
9120
9121 @d dash_p(A) link((A)+9)
9122   /* a pointer to the edge structure that gives the dash pattern */
9123 @d lcap_val(A) type((A)+9)
9124   /* the value of \&{linecap} */
9125 @:mp_linecap_}{\&{linecap} primitive@>
9126 @d dash_scale(A) mp->mem[(A)+10].sc /* dash lengths are scaled by this factor */
9127 @d stroked_node_size 11
9128
9129 @ @<Graphical object codes@>=
9130 mp_stroked_code=2,
9131
9132 @ @c 
9133 pointer mp_new_stroked_node (MP mp,pointer p) {
9134   /* make a stroked node for path |p| with |pen_p(p)| temporarily |null| */
9135   pointer t; /* the new node */
9136   t=mp_get_node(mp, stroked_node_size);
9137   type(t)=mp_stroked_code;
9138   path_p(t)=p; pen_p(t)=null;
9139   dash_p(t)=null;
9140   dash_scale(t)=unity;
9141   red_val(t)=0;
9142   green_val(t)=0;
9143   blue_val(t)=0;
9144   black_val(t)=0;
9145   color_model(t)=mp_uninitialized_model;
9146   pre_script(t)=null;
9147   post_script(t)=null;
9148   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9149   if ( mp->internal[mp_linecap]>unity ) lcap_val(t)=2;
9150   else if ( mp->internal[mp_linecap]>0 ) lcap_val(t)=1;
9151   else lcap_val(t)=0;
9152   return t;
9153 }
9154
9155 @ When a dashed line is computed in a transformed coordinate system, the dash
9156 lengths get scaled like the pen shape and we need to compensate for this.  Since
9157 there is no unique scale factor for an arbitrary transformation, we use the
9158 the square root of the determinant.  The properties of the determinant make it
9159 easier to maintain the |dash_scale|.  The computation is fairly straight-forward
9160 except for the initialization of the scale factor |s|.  The factor of 64 is
9161 needed because |square_rt| scales its result by $2^8$ while we need $2^{14}$
9162 to counteract the effect of |take_fraction|.
9163
9164 @<Declare subroutines needed by |print_edges|@>=
9165 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) {
9166   scaled maxabs; /* $max(|a|,|b|,|c|,|d|)$ */
9167   integer s; /* amount by which the result of |square_rt| needs to be scaled */
9168   @<Initialize |maxabs|@>;
9169   s=64;
9170   while ( (maxabs<fraction_one) && (s>1) ){ 
9171     a+=a; b+=b; c+=c; d+=d;
9172     maxabs+=maxabs; s=halfp(s);
9173   }
9174   return s*mp_square_rt(mp, abs(mp_take_fraction(mp, a,d)-mp_take_fraction(mp, b,c)));
9175 }
9176 @#
9177 scaled mp_get_pen_scale (MP mp,pointer p) { 
9178   return mp_sqrt_det(mp, 
9179     left_x(p)-x_coord(p), right_x(p)-x_coord(p),
9180     left_y(p)-y_coord(p), right_y(p)-y_coord(p));
9181 }
9182
9183 @ @<Internal library ...@>=
9184 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) ;
9185
9186
9187 @ @<Initialize |maxabs|@>=
9188 maxabs=abs(a);
9189 if ( abs(b)>maxabs ) maxabs=abs(b);
9190 if ( abs(c)>maxabs ) maxabs=abs(c);
9191 if ( abs(d)>maxabs ) maxabs=abs(d)
9192
9193 @ When a picture contains text, this is represented by a fourteen-word node
9194 where the color information and |type| and |link| fields are augmented by
9195 additional fields that describe the text and  how it is transformed.
9196 The |path_p| and |pen_p| pointers are replaced by a number that identifies
9197 the font and a string number that gives the text to be displayed.
9198 The |width|, |height|, and |depth| fields
9199 give the dimensions of the text at its design size, and the remaining six
9200 words give a transformation to be applied to the text.  The |new_text_node|
9201 function initializes everything to default values so that the text comes out
9202 black with its reference point at the origin.
9203
9204 @d text_p(A) link((A)+1)  /* a string pointer for the text to display */
9205 @d font_n(A) info((A)+1)  /* the font number */
9206 @d width_val(A) mp->mem[(A)+7].sc  /* unscaled width of the text */
9207 @d height_val(A) mp->mem[(A)+9].sc  /* unscaled height of the text */
9208 @d depth_val(A) mp->mem[(A)+10].sc  /* unscaled depth of the text */
9209 @d text_tx_loc(A) ((A)+11)
9210   /* the first of six locations for transformation parameters */
9211 @d tx_val(A) mp->mem[(A)+11].sc  /* $x$ shift amount */
9212 @d ty_val(A) mp->mem[(A)+12].sc  /* $y$ shift amount */
9213 @d txx_val(A) mp->mem[(A)+13].sc  /* |txx| transformation parameter */
9214 @d txy_val(A) mp->mem[(A)+14].sc  /* |txy| transformation parameter */
9215 @d tyx_val(A) mp->mem[(A)+15].sc  /* |tyx| transformation parameter */
9216 @d tyy_val(A) mp->mem[(A)+16].sc  /* |tyy| transformation parameter */
9217 @d text_trans_part(A) mp->mem[(A)+11-x_part].sc
9218     /* interpret a text node pointer that has been offset by |x_part..yy_part| */
9219 @d text_node_size 17
9220
9221 @ @<Graphical object codes@>=
9222 mp_text_code=3,
9223
9224 @ @c @<Declare text measuring subroutines@>;
9225 pointer mp_new_text_node (MP mp,char *f,str_number s) {
9226   /* make a text node for font |f| and text string |s| */
9227   pointer t; /* the new node */
9228   t=mp_get_node(mp, text_node_size);
9229   type(t)=mp_text_code;
9230   text_p(t)=s;
9231   font_n(t)=mp_find_font(mp, f); /* this identifies the font */
9232   red_val(t)=0;
9233   green_val(t)=0;
9234   blue_val(t)=0;
9235   black_val(t)=0;
9236   color_model(t)=mp_uninitialized_model;
9237   pre_script(t)=null;
9238   post_script(t)=null;
9239   tx_val(t)=0; ty_val(t)=0;
9240   txx_val(t)=unity; txy_val(t)=0;
9241   tyx_val(t)=0; tyy_val(t)=unity;
9242   mp_set_text_box(mp, t); /* this finds the bounding box */
9243   return t;
9244 }
9245
9246 @ The last two types of graphical objects that can occur in an edge structure
9247 are clipping paths and \&{setbounds} paths.  These are slightly more difficult
9248 @:set_bounds_}{\&{setbounds} primitive@>
9249 to implement because we must keep track of exactly what is being clipped or
9250 bounded when pictures get merged together.  For this reason, each clipping or
9251 \&{setbounds} operation is represented by a pair of nodes:  first comes a
9252 two-word node whose |path_p| gives the relevant path, then there is the list
9253 of objects to clip or bound followed by a two-word node whose second word is
9254 unused.
9255
9256 Using at least two words for each graphical object node allows them all to be
9257 allocated and deallocated similarly with a global array |gr_object_size| to
9258 give the size in words for each object type.
9259
9260 @d start_clip_size 2
9261 @d start_bounds_size 2
9262 @d stop_clip_size 2 /* the second word is not used here */
9263 @d stop_bounds_size 2 /* the second word is not used here */
9264 @#
9265 @d stop_type(A) ((A)+2)
9266   /* matching |type| for |start_clip_code| or |start_bounds_code| */
9267 @d has_color(A) (type((A))<mp_start_clip_code)
9268   /* does a graphical object have color fields? */
9269 @d has_pen(A) (type((A))<mp_text_code)
9270   /* does a graphical object have a |pen_p| field? */
9271 @d is_start_or_stop(A) (type((A))>=mp_start_clip_code)
9272 @d is_stop(A) (type((A))>=mp_stop_clip_code)
9273
9274 @ @<Graphical object codes@>=
9275 mp_start_clip_code=4, /* |type| of a node that starts clipping */
9276 mp_start_bounds_code=5, /* |type| of a node that gives a \&{setbounds} path */
9277 mp_stop_clip_code=6, /* |type| of a node that stops clipping */
9278 mp_stop_bounds_code=7, /* |type| of a node that stops \&{setbounds} */
9279
9280 @ @c 
9281 pointer mp_new_bounds_node (MP mp,pointer p, small_number  c) {
9282   /* make a node of type |c| where |p| is the clipping or \&{setbounds} path */
9283   pointer t; /* the new node */
9284   t=mp_get_node(mp, mp->gr_object_size[c]);
9285   type(t)=c;
9286   path_p(t)=p;
9287   return t;
9288 };
9289
9290 @ We need an array to keep track of the sizes of graphical objects.
9291
9292 @<Glob...@>=
9293 small_number gr_object_size[mp_stop_bounds_code+1];
9294
9295 @ @<Set init...@>=
9296 mp->gr_object_size[mp_fill_code]=fill_node_size;
9297 mp->gr_object_size[mp_stroked_code]=stroked_node_size;
9298 mp->gr_object_size[mp_text_code]=text_node_size;
9299 mp->gr_object_size[mp_start_clip_code]=start_clip_size;
9300 mp->gr_object_size[mp_stop_clip_code]=stop_clip_size;
9301 mp->gr_object_size[mp_start_bounds_code]=start_bounds_size;
9302 mp->gr_object_size[mp_stop_bounds_code]=stop_bounds_size;
9303
9304 @ All the essential information in an edge structure is encoded as a linked list
9305 of graphical objects as we have just seen, but it is helpful to add some
9306 redundant information.  A single edge structure might be used as a dash pattern
9307 many times, and it would be nice to avoid scanning the same structure
9308 repeatedly.  Thus, an edge structure known to be a suitable dash pattern
9309 has a header that gives a list of dashes in a sorted order designed for rapid
9310 translation into \ps.
9311
9312 Each dash is represented by a three-word node containing the initial and final
9313 $x$~coordinates as well as the usual |link| field.  The |link| fields points to
9314 the dash node with the next higher $x$-coordinates and the final link points
9315 to a special location called |null_dash|.  (There should be no overlap between
9316 dashes).  Since the $y$~coordinate of the dash pattern is needed to determine
9317 the period of repetition, this needs to be stored in the edge header along
9318 with a pointer to the list of dash nodes.
9319
9320 @d start_x(A) mp->mem[(A)+1].sc  /* the starting $x$~coordinate in a dash node */
9321 @d stop_x(A) mp->mem[(A)+2].sc  /* the ending $x$~coordinate in a dash node */
9322 @d dash_node_size 3
9323 @d dash_list link
9324   /* in an edge header this points to the first dash node */
9325 @d dash_y(A) mp->mem[(A)+1].sc  /* $y$ value for the dash list in an edge header */
9326
9327 @ It is also convenient for an edge header to contain the bounding
9328 box information needed by the \&{llcorner} and \&{urcorner} operators
9329 so that this does not have to be recomputed unnecessarily.  This is done by
9330 adding fields for the $x$~and $y$ extremes as well as a pointer that indicates
9331 how far the bounding box computation has gotten.  Thus if the user asks for
9332 the bounding box and then adds some more text to the picture before asking
9333 for more bounding box information, the second computation need only look at
9334 the additional text.
9335
9336 When the bounding box has not been computed, the |bblast| pointer points
9337 to a dummy link at the head of the graphical object list while the |minx_val|
9338 and |miny_val| fields contain |el_gordo| and the |maxx_val| and |maxy_val|
9339 fields contain |-el_gordo|.
9340
9341 Since the bounding box of pictures containing objects of type
9342 |mp_start_bounds_code| depends on the value of \&{truecorners}, the bounding box
9343 @:mp_true_corners_}{\&{truecorners} primitive@>
9344 data might not be valid for all values of this parameter.  Hence, the |bbtype|
9345 field is needed to keep track of this.
9346
9347 @d minx_val(A) mp->mem[(A)+2].sc
9348 @d miny_val(A) mp->mem[(A)+3].sc
9349 @d maxx_val(A) mp->mem[(A)+4].sc
9350 @d maxy_val(A) mp->mem[(A)+5].sc
9351 @d bblast(A) link((A)+6)  /* last item considered in bounding box computation */
9352 @d bbtype(A) info((A)+6)  /* tells how bounding box data depends on \&{truecorners} */
9353 @d dummy_loc(A) ((A)+7)  /* where the object list begins in an edge header */
9354 @d no_bounds 0
9355   /* |bbtype| value when bounding box data is valid for all \&{truecorners} values */
9356 @d bounds_set 1
9357   /* |bbtype| value when bounding box data is for \&{truecorners}${}\le 0$ */
9358 @d bounds_unset 2
9359   /* |bbtype| value when bounding box data is for \&{truecorners}${}>0$ */
9360
9361 @c 
9362 void mp_init_bbox (MP mp,pointer h) {
9363   /* Initialize the bounding box information in edge structure |h| */
9364   bblast(h)=dummy_loc(h);
9365   bbtype(h)=no_bounds;
9366   minx_val(h)=el_gordo;
9367   miny_val(h)=el_gordo;
9368   maxx_val(h)=-el_gordo;
9369   maxy_val(h)=-el_gordo;
9370 }
9371
9372 @ The only other entries in an edge header are a reference count in the first
9373 word and a pointer to the tail of the object list in the last word.
9374
9375 @d obj_tail(A) info((A)+7)  /* points to the last entry in the object list */
9376 @d edge_header_size 8
9377
9378 @c 
9379 void mp_init_edges (MP mp,pointer h) {
9380   /* initialize an edge header to null values */
9381   dash_list(h)=null_dash;
9382   obj_tail(h)=dummy_loc(h);
9383   link(dummy_loc(h))=null;
9384   ref_count(h)=null;
9385   mp_init_bbox(mp, h);
9386 }
9387
9388 @ Here is how edge structures are deleted.  The process can be recursive because
9389 of the need to dereference edge structures that are used as dash patterns.
9390 @^recursion@>
9391
9392 @d add_edge_ref(A) incr(ref_count(A))
9393 @d delete_edge_ref(A) { 
9394    if ( ref_count((A))==null ) 
9395      mp_toss_edges(mp, A);
9396    else 
9397      decr(ref_count(A)); 
9398    }
9399
9400 @<Declare the recycling subroutines@>=
9401 void mp_flush_dash_list (MP mp,pointer h);
9402 pointer mp_toss_gr_object (MP mp,pointer p) ;
9403 void mp_toss_edges (MP mp,pointer h) ;
9404
9405 @ @c void mp_toss_edges (MP mp,pointer h) {
9406   pointer p,q;  /* pointers that scan the list being recycled */
9407   pointer r; /* an edge structure that object |p| refers to */
9408   mp_flush_dash_list(mp, h);
9409   q=link(dummy_loc(h));
9410   while ( (q!=null) ) { 
9411     p=q; q=link(q);
9412     r=mp_toss_gr_object(mp, p);
9413     if ( r!=null ) delete_edge_ref(r);
9414   }
9415   mp_free_node(mp, h,edge_header_size);
9416 }
9417 void mp_flush_dash_list (MP mp,pointer h) {
9418   pointer p,q;  /* pointers that scan the list being recycled */
9419   q=dash_list(h);
9420   while ( q!=null_dash ) { 
9421     p=q; q=link(q);
9422     mp_free_node(mp, p,dash_node_size);
9423   }
9424   dash_list(h)=null_dash;
9425 }
9426 pointer mp_toss_gr_object (MP mp,pointer p) {
9427   /* returns an edge structure that needs to be dereferenced */
9428   pointer e; /* the edge structure to return */
9429   e=null;
9430   @<Prepare to recycle graphical object |p|@>;
9431   mp_free_node(mp, p,mp->gr_object_size[type(p)]);
9432   return e;
9433 }
9434
9435 @ @<Prepare to recycle graphical object |p|@>=
9436 switch (type(p)) {
9437 case mp_fill_code: 
9438   mp_toss_knot_list(mp, path_p(p));
9439   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9440   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9441   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9442   break;
9443 case mp_stroked_code: 
9444   mp_toss_knot_list(mp, path_p(p));
9445   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9446   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9447   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9448   e=dash_p(p);
9449   break;
9450 case mp_text_code: 
9451   delete_str_ref(text_p(p));
9452   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9453   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9454   break;
9455 case mp_start_clip_code:
9456 case mp_start_bounds_code: 
9457   mp_toss_knot_list(mp, path_p(p));
9458   break;
9459 case mp_stop_clip_code:
9460 case mp_stop_bounds_code: 
9461   break;
9462 } /* there are no other cases */
9463
9464 @ If we use |add_edge_ref| to ``copy'' edge structures, the real copying needs
9465 to be done before making a significant change to an edge structure.  Much of
9466 the work is done in a separate routine |copy_objects| that copies a list of
9467 graphical objects into a new edge header.
9468
9469 @c @<Declare a function called |copy_objects|@>;
9470 pointer mp_private_edges (MP mp,pointer h) {
9471   /* make a private copy of the edge structure headed by |h| */
9472   pointer hh;  /* the edge header for the new copy */
9473   pointer p,pp;  /* pointers for copying the dash list */
9474   if ( ref_count(h)==null ) {
9475     return h;
9476   } else { 
9477     decr(ref_count(h));
9478     hh=mp_copy_objects(mp, link(dummy_loc(h)),null);
9479     @<Copy the dash list from |h| to |hh|@>;
9480     @<Copy the bounding box information from |h| to |hh| and make |bblast(hh)|
9481       point into the new object list@>;
9482     return hh;
9483   }
9484 }
9485
9486 @ Here we use the fact that |dash_list(hh)=link(hh)|.
9487 @^data structure assumptions@>
9488
9489 @<Copy the dash list from |h| to |hh|@>=
9490 pp=hh; p=dash_list(h);
9491 while ( (p!=null_dash) ) { 
9492   link(pp)=mp_get_node(mp, dash_node_size);
9493   pp=link(pp);
9494   start_x(pp)=start_x(p);
9495   stop_x(pp)=stop_x(p);
9496   p=link(p);
9497 }
9498 link(pp)=null_dash;
9499 dash_y(hh)=dash_y(h)
9500
9501
9502 @ |h| is an edge structure
9503
9504 @d gr_start_x(A)    (A)->start_x_field
9505 @d gr_stop_x(A)     (A)->stop_x_field
9506 @d gr_dash_link(A)  (A)->next_field
9507
9508 @d gr_dash_list(A)  (A)->list_field
9509 @d gr_dash_y(A)     (A)->y_field
9510
9511 @c
9512 struct mp_dash_list *mp_export_dashes (MP mp, pointer h) {
9513   struct mp_dash_list *dl;
9514   struct mp_dash_item *dh, *di;
9515   pointer p;
9516   if (h==null ||  dash_list(h)==null_dash) 
9517         return NULL;
9518   p = dash_list(h);
9519   dl = mp_xmalloc(mp,1,sizeof(struct mp_dash_list));
9520   gr_dash_list(dl) = NULL;
9521   gr_dash_y(dl) = dash_y(h);
9522   dh = NULL;
9523   while (p != null_dash) { 
9524     di=mp_xmalloc(mp,1,sizeof(struct mp_dash_item));
9525     gr_dash_link(di) = NULL;
9526     gr_start_x(di) = start_x(p);
9527     gr_stop_x(di) = stop_x(p);
9528     if (dh==NULL) {
9529       gr_dash_list(dl) = di;
9530     } else {
9531       gr_dash_link(dh) = di;
9532     }
9533     dh = di;
9534     p=link(p);
9535   }
9536   return dl;
9537 }
9538
9539
9540 @ @<Copy the bounding box information from |h| to |hh|...@>=
9541 minx_val(hh)=minx_val(h);
9542 miny_val(hh)=miny_val(h);
9543 maxx_val(hh)=maxx_val(h);
9544 maxy_val(hh)=maxy_val(h);
9545 bbtype(hh)=bbtype(h);
9546 p=dummy_loc(h); pp=dummy_loc(hh);
9547 while ((p!=bblast(h)) ) { 
9548   if ( p==null ) mp_confusion(mp, "bblast");
9549 @:this can't happen bblast}{\quad bblast@>
9550   p=link(p); pp=link(pp);
9551 }
9552 bblast(hh)=pp
9553
9554 @ Here is the promised routine for copying graphical objects into a new edge
9555 structure.  It starts copying at object~|p| and stops just before object~|q|.
9556 If |q| is null, it copies the entire sublist headed at |p|.  The resulting edge
9557 structure requires further initialization by |init_bbox|.
9558
9559 @<Declare a function called |copy_objects|@>=
9560 pointer mp_copy_objects (MP mp, pointer p, pointer q) {
9561   pointer hh;  /* the new edge header */
9562   pointer pp;  /* the last newly copied object */
9563   small_number k;  /* temporary register */
9564   hh=mp_get_node(mp, edge_header_size);
9565   dash_list(hh)=null_dash;
9566   ref_count(hh)=null;
9567   pp=dummy_loc(hh);
9568   while ( (p!=q) ) {
9569     @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>;
9570   }
9571   obj_tail(hh)=pp;
9572   link(pp)=null;
9573   return hh;
9574 }
9575
9576 @ @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>=
9577 { k=mp->gr_object_size[type(p)];
9578   link(pp)=mp_get_node(mp, k);
9579   pp=link(pp);
9580   while ( (k>0) ) { decr(k); mp->mem[pp+k]=mp->mem[p+k];  };
9581   @<Fix anything in graphical object |pp| that should differ from the
9582     corresponding field in |p|@>;
9583   p=link(p);
9584 }
9585
9586 @ @<Fix anything in graphical object |pp| that should differ from the...@>=
9587 switch (type(p)) {
9588 case mp_start_clip_code:
9589 case mp_start_bounds_code: 
9590   path_p(pp)=mp_copy_path(mp, path_p(p));
9591   break;
9592 case mp_fill_code: 
9593   path_p(pp)=mp_copy_path(mp, path_p(p));
9594   if ( pen_p(p)!=null ) pen_p(pp)=copy_pen(pen_p(p));
9595   break;
9596 case mp_stroked_code: 
9597   path_p(pp)=mp_copy_path(mp, path_p(p));
9598   pen_p(pp)=copy_pen(pen_p(p));
9599   if ( dash_p(p)!=null ) add_edge_ref(dash_p(pp));
9600   break;
9601 case mp_text_code: 
9602   add_str_ref(text_p(pp));
9603   break;
9604 case mp_stop_clip_code:
9605 case mp_stop_bounds_code: 
9606   break;
9607 }  /* there are no other cases */
9608
9609 @ Here is one way to find an acceptable value for the second argument to
9610 |copy_objects|.  Given a non-null graphical object list, |skip_1component|
9611 skips past one picture component, where a ``picture component'' is a single
9612 graphical object, or a start bounds or start clip object and everything up
9613 through the matching stop bounds or stop clip object.  The macro version avoids
9614 procedure call overhead and error handling: |skip_component(p)(e)| advances |p|
9615 unless |p| points to a stop bounds or stop clip node, in which case it executes
9616 |e| instead.
9617
9618 @d skip_component(A)
9619     if ( ! is_start_or_stop((A)) ) (A)=link((A));
9620     else if ( ! is_stop((A)) ) (A)=mp_skip_1component(mp, (A));
9621     else 
9622
9623 @c 
9624 pointer mp_skip_1component (MP mp,pointer p) {
9625   integer lev; /* current nesting level */
9626   lev=0;
9627   do {  
9628    if ( is_start_or_stop(p) ) {
9629      if ( is_stop(p) ) decr(lev);  else incr(lev);
9630    }
9631    p=link(p);
9632   } while (lev!=0);
9633   return p;
9634 }
9635
9636 @ Here is a diagnostic routine for printing an edge structure in symbolic form.
9637
9638 @<Declare subroutines for printing expressions@>=
9639 @<Declare subroutines needed by |print_edges|@>;
9640 void mp_print_edges (MP mp,pointer h, char *s, boolean nuline) {
9641   pointer p;  /* a graphical object to be printed */
9642   pointer hh,pp;  /* temporary pointers */
9643   scaled scf;  /* a scale factor for the dash pattern */
9644   boolean ok_to_dash;  /* |false| for polygonal pen strokes */
9645   mp_print_diagnostic(mp, "Edge structure",s,nuline);
9646   p=dummy_loc(h);
9647   while ( link(p)!=null ) { 
9648     p=link(p);
9649     mp_print_ln(mp);
9650     switch (type(p)) {
9651       @<Cases for printing graphical object node |p|@>;
9652     default: 
9653           mp_print(mp, "[unknown object type!]");
9654           break;
9655     }
9656   }
9657   mp_print_nl(mp, "End edges");
9658   if ( p!=obj_tail(h) ) mp_print(mp, "?");
9659 @.End edges?@>
9660   mp_end_diagnostic(mp, true);
9661 }
9662
9663 @ @<Cases for printing graphical object node |p|@>=
9664 case mp_fill_code: 
9665   mp_print(mp, "Filled contour ");
9666   mp_print_obj_color(mp, p);
9667   mp_print_char(mp, ':'); mp_print_ln(mp);
9668   mp_pr_path(mp, path_p(p)); mp_print_ln(mp);
9669   if ( (pen_p(p)!=null) ) {
9670     @<Print join type for graphical object |p|@>;
9671     mp_print(mp, " with pen"); mp_print_ln(mp);
9672     mp_pr_pen(mp, pen_p(p));
9673   }
9674   break;
9675
9676 @ @<Print join type for graphical object |p|@>=
9677 switch (ljoin_val(p)) {
9678 case 0:
9679   mp_print(mp, "mitered joins limited ");
9680   mp_print_scaled(mp, miterlim_val(p));
9681   break;
9682 case 1:
9683   mp_print(mp, "round joins");
9684   break;
9685 case 2:
9686   mp_print(mp, "beveled joins");
9687   break;
9688 default: 
9689   mp_print(mp, "?? joins");
9690 @.??@>
9691   break;
9692 }
9693
9694 @ For stroked nodes, we need to print |lcap_val(p)| as well.
9695
9696 @<Print join and cap types for stroked node |p|@>=
9697 switch (lcap_val(p)) {
9698 case 0:mp_print(mp, "butt"); break;
9699 case 1:mp_print(mp, "round"); break;
9700 case 2:mp_print(mp, "square"); break;
9701 default: mp_print(mp, "??"); break;
9702 @.??@>
9703 }
9704 mp_print(mp, " ends, ");
9705 @<Print join type for graphical object |p|@>
9706
9707 @ Here is a routine that prints the color of a graphical object if it isn't
9708 black (the default color).
9709
9710 @<Declare subroutines needed by |print_edges|@>=
9711 @<Declare a procedure called |print_compact_node|@>;
9712 void mp_print_obj_color (MP mp,pointer p) { 
9713   if ( color_model(p)==mp_grey_model ) {
9714     if ( grey_val(p)>0 ) { 
9715       mp_print(mp, "greyed ");
9716       mp_print_compact_node(mp, obj_grey_loc(p),1);
9717     };
9718   } else if ( color_model(p)==mp_cmyk_model ) {
9719     if ( (cyan_val(p)>0) || (magenta_val(p)>0) || 
9720          (yellow_val(p)>0) || (black_val(p)>0) ) { 
9721       mp_print(mp, "processcolored ");
9722       mp_print_compact_node(mp, obj_cyan_loc(p),4);
9723     };
9724   } else if ( color_model(p)==mp_rgb_model ) {
9725     if ( (red_val(p)>0) || (green_val(p)>0) || (blue_val(p)>0) ) { 
9726       mp_print(mp, "colored "); 
9727       mp_print_compact_node(mp, obj_red_loc(p),3);
9728     };
9729   }
9730 }
9731
9732 @ We also need a procedure for printing consecutive scaled values as if they
9733 were a known big node.
9734
9735 @<Declare a procedure called |print_compact_node|@>=
9736 void mp_print_compact_node (MP mp,pointer p, small_number k) {
9737   pointer q;  /* last location to print */
9738   q=p+k-1;
9739   mp_print_char(mp, '(');
9740   while ( p<=q ){ 
9741     mp_print_scaled(mp, mp->mem[p].sc);
9742     if ( p<q ) mp_print_char(mp, ',');
9743     incr(p);
9744   }
9745   mp_print_char(mp, ')');
9746 }
9747
9748 @ @<Cases for printing graphical object node |p|@>=
9749 case mp_stroked_code: 
9750   mp_print(mp, "Filled pen stroke ");
9751   mp_print_obj_color(mp, p);
9752   mp_print_char(mp, ':'); mp_print_ln(mp);
9753   mp_pr_path(mp, path_p(p));
9754   if ( dash_p(p)!=null ) { 
9755     mp_print_nl(mp, "dashed (");
9756     @<Finish printing the dash pattern that |p| refers to@>;
9757   }
9758   mp_print_ln(mp);
9759   @<Print join and cap types for stroked node |p|@>;
9760   mp_print(mp, " with pen"); mp_print_ln(mp);
9761   if ( pen_p(p)==null ) mp_print(mp, "???"); /* shouldn't happen */
9762 @.???@>
9763   else mp_pr_pen(mp, pen_p(p));
9764   break;
9765
9766 @ Normally, the  |dash_list| field in an edge header is set to |null_dash|
9767 when it is not known to define a suitable dash pattern.  This is disallowed
9768 here because the |dash_p| field should never point to such an edge header.
9769 Note that memory is allocated for |start_x(null_dash)| and we are free to
9770 give it any convenient value.
9771
9772 @<Finish printing the dash pattern that |p| refers to@>=
9773 ok_to_dash=pen_is_elliptical(pen_p(p));
9774 if ( ! ok_to_dash ) scf=unity; else scf=dash_scale(p);
9775 hh=dash_p(p);
9776 pp=dash_list(hh);
9777 if ( (pp==null_dash) || (dash_y(hh)<0) ) {
9778   mp_print(mp, " ??");
9779 } else { start_x(null_dash)=start_x(pp)+dash_y(hh);
9780   while ( pp!=null_dash ) { 
9781     mp_print(mp, "on ");
9782     mp_print_scaled(mp, mp_take_scaled(mp, stop_x(pp)-start_x(pp),scf));
9783     mp_print(mp, " off ");
9784     mp_print_scaled(mp, mp_take_scaled(mp, start_x(link(pp))-stop_x(pp),scf));
9785     pp = link(pp);
9786     if ( pp!=null_dash ) mp_print_char(mp, ' ');
9787   }
9788   mp_print(mp, ") shifted ");
9789   mp_print_scaled(mp, -mp_take_scaled(mp, mp_dash_offset(mp, hh),scf));
9790   if ( ! ok_to_dash || (dash_y(hh)==0) ) mp_print(mp, " (this will be ignored)");
9791 }
9792
9793 @ @<Declare subroutines needed by |print_edges|@>=
9794 scaled mp_dash_offset (MP mp,pointer h) {
9795   scaled x;  /* the answer */
9796   if (dash_list(h)==null_dash || dash_y(h)<0) mp_confusion(mp, "dash0");
9797 @:this can't happen dash0}{\quad dash0@>
9798   if ( dash_y(h)==0 ) {
9799     x=0; 
9800   } else { 
9801     x=-(start_x(dash_list(h)) % dash_y(h));
9802     if ( x<0 ) x=x+dash_y(h);
9803   }
9804   return x;
9805 }
9806
9807 @ @<Cases for printing graphical object node |p|@>=
9808 case mp_text_code: 
9809   mp_print_char(mp, '"'); mp_print_str(mp,text_p(p));
9810   mp_print(mp, "\" infont \""); mp_print(mp, mp->font_name[font_n(p)]);
9811   mp_print_char(mp, '"'); mp_print_ln(mp);
9812   mp_print_obj_color(mp, p);
9813   mp_print(mp, "transformed ");
9814   mp_print_compact_node(mp, text_tx_loc(p),6);
9815   break;
9816
9817 @ @<Cases for printing graphical object node |p|@>=
9818 case mp_start_clip_code: 
9819   mp_print(mp, "clipping path:");
9820   mp_print_ln(mp);
9821   mp_pr_path(mp, path_p(p));
9822   break;
9823 case mp_stop_clip_code: 
9824   mp_print(mp, "stop clipping");
9825   break;
9826
9827 @ @<Cases for printing graphical object node |p|@>=
9828 case mp_start_bounds_code: 
9829   mp_print(mp, "setbounds path:");
9830   mp_print_ln(mp);
9831   mp_pr_path(mp, path_p(p));
9832   break;
9833 case mp_stop_bounds_code: 
9834   mp_print(mp, "end of setbounds");
9835   break;
9836
9837 @ To initialize the |dash_list| field in an edge header~|h|, we need a
9838 subroutine that scans an edge structure and tries to interpret it as a dash
9839 pattern.  This can only be done when there are no filled regions or clipping
9840 paths and all the pen strokes have the same color.  The first step is to let
9841 $y_0$ be the initial $y$~coordinate of the first pen stroke.  Then we implicitly
9842 project all the pen stroke paths onto the line $y=y_0$ and require that there
9843 be no retracing.  If the resulting paths cover a range of $x$~coordinates of
9844 length $\Delta x$, we set |dash_y(h)| to the length of the dash pattern by
9845 finding the maximum of $\Delta x$ and the absolute value of~$y_0$.
9846
9847 @c @<Declare a procedure called |x_retrace_error|@>;
9848 pointer mp_make_dashes (MP mp,pointer h) { /* returns |h| or |null| */
9849   pointer p;  /* this scans the stroked nodes in the object list */
9850   pointer p0;  /* if not |null| this points to the first stroked node */
9851   pointer pp,qq,rr;  /* pointers into |path_p(p)| */
9852   pointer d,dd;  /* pointers used to create the dash list */
9853   @<Other local variables in |make_dashes|@>;
9854   scaled y0=0;  /* the initial $y$ coordinate */
9855   if ( dash_list(h)!=null_dash ) 
9856         return h;
9857   p0=null;
9858   p=link(dummy_loc(h));
9859   while ( p!=null ) { 
9860     if ( type(p)!=mp_stroked_code ) {
9861       @<Compain that the edge structure contains a node of the wrong type
9862         and |goto not_found|@>;
9863     }
9864     pp=path_p(p);
9865     if ( p0==null ){ p0=p; y0=y_coord(pp);  };
9866     @<Make |d| point to a new dash node created from stroke |p| and path |pp|
9867       or |goto not_found| if there is an error@>;
9868     @<Insert |d| into the dash list and |goto not_found| if there is an error@>;
9869     p=link(p);
9870   }
9871   if ( dash_list(h)==null_dash ) 
9872     goto NOT_FOUND; /* No error message */
9873   @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>;
9874   @<Set |dash_y(h)| and merge the first and last dashes if necessary@>;
9875   return h;
9876 NOT_FOUND: 
9877   @<Flush the dash list, recycle |h| and return |null|@>;
9878 };
9879
9880 @ @<Compain that the edge structure contains a node of the wrong type...@>=
9881
9882 print_err("Picture is too complicated to use as a dash pattern");
9883 help3("When you say `dashed p', picture p should not contain any")
9884   ("text, filled regions, or clipping paths.  This time it did")
9885   ("so I'll just make it a solid line instead.");
9886 mp_put_get_error(mp);
9887 goto NOT_FOUND;
9888 }
9889
9890 @ A similar error occurs when monotonicity fails.
9891
9892 @<Declare a procedure called |x_retrace_error|@>=
9893 void mp_x_retrace_error (MP mp) { 
9894 print_err("Picture is too complicated to use as a dash pattern");
9895 help3("When you say `dashed p', every path in p should be monotone")
9896   ("in x and there must be no overlapping.  This failed")
9897   ("so I'll just make it a solid line instead.");
9898 mp_put_get_error(mp);
9899 }
9900
9901 @ We stash |p| in |info(d)| if |dash_p(p)<>0| so that subsequent processing can
9902 handle the case where the pen stroke |p| is itself dashed.
9903
9904 @<Make |d| point to a new dash node created from stroke |p| and path...@>=
9905 @<Make sure |p| and |p0| are the same color and |goto not_found| if there is
9906   an error@>;
9907 rr=pp;
9908 if ( link(pp)!=pp ) {
9909   do {  
9910     qq=rr; rr=link(rr);
9911     @<Check for retracing between knots |qq| and |rr| and |goto not_found|
9912       if there is a problem@>;
9913   } while (right_type(rr)!=mp_endpoint);
9914 }
9915 d=mp_get_node(mp, dash_node_size);
9916 if ( dash_p(p)==0 ) info(d)=0;  else info(d)=p;
9917 if ( x_coord(pp)<x_coord(rr) ) { 
9918   start_x(d)=x_coord(pp);
9919   stop_x(d)=x_coord(rr);
9920 } else { 
9921   start_x(d)=x_coord(rr);
9922   stop_x(d)=x_coord(pp);
9923 }
9924
9925 @ We also need to check for the case where the segment from |qq| to |rr| is
9926 monotone in $x$ but is reversed relative to the path from |pp| to |qq|.
9927
9928 @<Check for retracing between knots |qq| and |rr| and |goto not_found|...@>=
9929 x0=x_coord(qq);
9930 x1=right_x(qq);
9931 x2=left_x(rr);
9932 x3=x_coord(rr);
9933 if ( (x0>x1) || (x1>x2) || (x2>x3) ) {
9934   if ( (x0<x1) || (x1<x2) || (x2<x3) ) {
9935     if ( mp_ab_vs_cd(mp, x2-x1,x2-x1,x1-x0,x3-x2)>0 ) {
9936       mp_x_retrace_error(mp); goto NOT_FOUND;
9937     }
9938   }
9939 }
9940 if ( (x_coord(pp)>x0) || (x0>x3) ) {
9941   if ( (x_coord(pp)<x0) || (x0<x3) ) {
9942     mp_x_retrace_error(mp); goto NOT_FOUND;
9943   }
9944 }
9945
9946 @ @<Other local variables in |make_dashes|@>=
9947   scaled x0,x1,x2,x3;  /* $x$ coordinates of the segment from |qq| to |rr| */
9948
9949 @ @<Make sure |p| and |p0| are the same color and |goto not_found|...@>=
9950 if ( (red_val(p)!=red_val(p0)) || (black_val(p)!=black_val(p0)) ||
9951   (green_val(p)!=green_val(p0)) || (blue_val(p)!=blue_val(p0)) ) {
9952   print_err("Picture is too complicated to use as a dash pattern");
9953   help3("When you say `dashed p', everything in picture p should")
9954     ("be the same color.  I can\'t handle your color changes")
9955     ("so I'll just make it a solid line instead.");
9956   mp_put_get_error(mp);
9957   goto NOT_FOUND;
9958 }
9959
9960 @ @<Insert |d| into the dash list and |goto not_found| if there is an error@>=
9961 start_x(null_dash)=stop_x(d);
9962 dd=h; /* this makes |link(dd)=dash_list(h)| */
9963 while ( start_x(link(dd))<stop_x(d) )
9964   dd=link(dd);
9965 if ( dd!=h ) {
9966   if ( (stop_x(dd)>start_x(d)) )
9967     { mp_x_retrace_error(mp); goto NOT_FOUND;  };
9968 }
9969 link(d)=link(dd);
9970 link(dd)=d
9971
9972 @ @<Set |dash_y(h)| and merge the first and last dashes if necessary@>=
9973 d=dash_list(h);
9974 while ( (link(d)!=null_dash) )
9975   d=link(d);
9976 dd=dash_list(h);
9977 dash_y(h)=stop_x(d)-start_x(dd);
9978 if ( abs(y0)>dash_y(h) ) {
9979   dash_y(h)=abs(y0);
9980 } else if ( d!=dd ) { 
9981   dash_list(h)=link(dd);
9982   stop_x(d)=stop_x(dd)+dash_y(h);
9983   mp_free_node(mp, dd,dash_node_size);
9984 }
9985
9986 @ We get here when the argument is a null picture or when there is an error.
9987 Recovering from an error involves making |dash_list(h)| empty to indicate
9988 that |h| is not known to be a valid dash pattern.  We also dereference |h|
9989 since it is not being used for the return value.
9990
9991 @<Flush the dash list, recycle |h| and return |null|@>=
9992 mp_flush_dash_list(mp, h);
9993 delete_edge_ref(h);
9994 return null
9995
9996 @ Having carefully saved the dashed stroked nodes in the
9997 corresponding dash nodes, we must be prepared to break up these dashes into
9998 smaller dashes.
9999
10000 @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>=
10001 d=h;  /* now |link(d)=dash_list(h)| */
10002 while ( link(d)!=null_dash ) {
10003   ds=info(link(d));
10004   if ( ds==null ) { 
10005     d=link(d);
10006   } else {
10007     hh=dash_p(ds);
10008     hsf=dash_scale(ds);
10009     if ( (hh==null) ) mp_confusion(mp, "dash1");
10010 @:this can't happen dash0}{\quad dash1@>
10011     if ( dash_y(hh)==0 ) {
10012       d=link(d);
10013     } else { 
10014       if ( dash_list(hh)==null ) mp_confusion(mp, "dash1");
10015 @:this can't happen dash0}{\quad dash1@>
10016       @<Replace |link(d)| by a dashed version as determined by edge header
10017           |hh| and scale factor |ds|@>;
10018     }
10019   }
10020 }
10021
10022 @ @<Other local variables in |make_dashes|@>=
10023 pointer dln;  /* |link(d)| */
10024 pointer hh;  /* an edge header that tells how to break up |dln| */
10025 scaled hsf;  /* the dash pattern from |hh| gets scaled by this */
10026 pointer ds;  /* the stroked node from which |hh| and |hsf| are derived */
10027 scaled xoff;  /* added to $x$ values in |dash_list(hh)| to match |dln| */
10028
10029 @ @<Replace |link(d)| by a dashed version as determined by edge header...@>=
10030 dln=link(d);
10031 dd=dash_list(hh);
10032 xoff=start_x(dln)-mp_take_scaled(mp, hsf,start_x(dd))-
10033         mp_take_scaled(mp, hsf,mp_dash_offset(mp, hh));
10034 start_x(null_dash)=mp_take_scaled(mp, hsf,start_x(dd))
10035                    +mp_take_scaled(mp, hsf,dash_y(hh));
10036 stop_x(null_dash)=start_x(null_dash);
10037 @<Advance |dd| until finding the first dash that overlaps |dln| when
10038   offset by |xoff|@>;
10039 while ( start_x(dln)<=stop_x(dln) ) {
10040   @<If |dd| has `fallen off the end', back up to the beginning and fix |xoff|@>;
10041   @<Insert a dash between |d| and |dln| for the overlap with the offset version
10042     of |dd|@>;
10043   dd=link(dd);
10044   start_x(dln)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10045 }
10046 link(d)=link(dln);
10047 mp_free_node(mp, dln,dash_node_size)
10048
10049 @ The name of this module is a bit of a lie because we just find the
10050 first |dd| where |take_scaled (hsf, stop_x(dd))| is large enough to make an
10051 overlap possible.  It could be that the unoffset version of dash |dln| falls
10052 in the gap between |dd| and its predecessor.
10053
10054 @<Advance |dd| until finding the first dash that overlaps |dln| when...@>=
10055 while ( xoff+mp_take_scaled(mp, hsf,stop_x(dd))<start_x(dln) ) {
10056   dd=link(dd);
10057 }
10058
10059 @ @<If |dd| has `fallen off the end', back up to the beginning and fix...@>=
10060 if ( dd==null_dash ) { 
10061   dd=dash_list(hh);
10062   xoff=xoff+mp_take_scaled(mp, hsf,dash_y(hh));
10063 }
10064
10065 @ At this point we already know that
10066 |start_x(dln)<=xoff+take_scaled(hsf,stop_x(dd))|.
10067
10068 @<Insert a dash between |d| and |dln| for the overlap with the offset...@>=
10069 if ( (xoff+mp_take_scaled(mp, hsf,start_x(dd)))<=stop_x(dln) ) {
10070   link(d)=mp_get_node(mp, dash_node_size);
10071   d=link(d);
10072   link(d)=dln;
10073   if ( start_x(dln)>(xoff+mp_take_scaled(mp, hsf,start_x(dd))))
10074     start_x(d)=start_x(dln);
10075   else 
10076     start_x(d)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10077   if ( stop_x(dln)<(xoff+mp_take_scaled(mp, hsf,stop_x(dd)))) 
10078     stop_x(d)=stop_x(dln);
10079   else 
10080     stop_x(d)=xoff+mp_take_scaled(mp, hsf,stop_x(dd));
10081 }
10082
10083 @ The next major task is to update the bounding box information in an edge
10084 header~|h|. This is done via a procedure |adjust_bbox| that enlarges an edge
10085 header's bounding box to accommodate the box computed by |path_bbox| or
10086 |pen_bbox|. (This is stored in global variables |minx|, |miny|, |maxx|, and
10087 |maxy|.)
10088
10089 @c void mp_adjust_bbox (MP mp,pointer h) { 
10090   if ( minx<minx_val(h) ) minx_val(h)=minx;
10091   if ( miny<miny_val(h) ) miny_val(h)=miny;
10092   if ( maxx>maxx_val(h) ) maxx_val(h)=maxx;
10093   if ( maxy>maxy_val(h) ) maxy_val(h)=maxy;
10094 }
10095
10096 @ Here is a special routine for updating the bounding box information in
10097 edge header~|h| to account for the squared-off ends of a non-cyclic path~|p|
10098 that is to be stroked with the pen~|pp|.
10099
10100 @c void mp_box_ends (MP mp, pointer p, pointer pp, pointer h) {
10101   pointer q;  /* a knot node adjacent to knot |p| */
10102   fraction dx,dy;  /* a unit vector in the direction out of the path at~|p| */
10103   scaled d;  /* a factor for adjusting the length of |(dx,dy)| */
10104   scaled z;  /* a coordinate being tested against the bounding box */
10105   scaled xx,yy;  /* the extreme pen vertex in the |(dx,dy)| direction */
10106   integer i; /* a loop counter */
10107   if ( right_type(p)!=mp_endpoint ) { 
10108     q=link(p);
10109     while (1) { 
10110       @<Make |(dx,dy)| the final direction for the path segment from
10111         |q| to~|p|; set~|d|@>;
10112       d=mp_pyth_add(mp, dx,dy);
10113       if ( d>0 ) { 
10114          @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>;
10115          for (i=1;i<= 2;i++) { 
10116            @<Use |(dx,dy)| to generate a vertex of the square end cap and
10117              update the bounding box to accommodate it@>;
10118            dx=-dx; dy=-dy; 
10119         }
10120       }
10121       if ( right_type(p)==mp_endpoint ) {
10122          return;
10123       } else {
10124         @<Advance |p| to the end of the path and make |q| the previous knot@>;
10125       } 
10126     }
10127   }
10128 }
10129
10130 @ @<Make |(dx,dy)| the final direction for the path segment from...@>=
10131 if ( q==link(p) ) { 
10132   dx=x_coord(p)-right_x(p);
10133   dy=y_coord(p)-right_y(p);
10134   if ( (dx==0)&&(dy==0) ) {
10135     dx=x_coord(p)-left_x(q);
10136     dy=y_coord(p)-left_y(q);
10137   }
10138 } else { 
10139   dx=x_coord(p)-left_x(p);
10140   dy=y_coord(p)-left_y(p);
10141   if ( (dx==0)&&(dy==0) ) {
10142     dx=x_coord(p)-right_x(q);
10143     dy=y_coord(p)-right_y(q);
10144   }
10145 }
10146 dx=x_coord(p)-x_coord(q);
10147 dy=y_coord(p)-y_coord(q)
10148
10149 @ @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>=
10150 dx=mp_make_fraction(mp, dx,d);
10151 dy=mp_make_fraction(mp, dy,d);
10152 mp_find_offset(mp, -dy,dx,pp);
10153 xx=mp->cur_x; yy=mp->cur_y
10154
10155 @ @<Use |(dx,dy)| to generate a vertex of the square end cap and...@>=
10156 mp_find_offset(mp, dx,dy,pp);
10157 d=mp_take_fraction(mp, xx-mp->cur_x,dx)+mp_take_fraction(mp, yy-mp->cur_y,dy);
10158 if ( ((d<0)&&(i==1)) || ((d>0)&&(i==2))) 
10159   mp_confusion(mp, "box_ends");
10160 @:this can't happen box ends}{\quad\\{box\_ends}@>
10161 z=x_coord(p)+mp->cur_x+mp_take_fraction(mp, d,dx);
10162 if ( z<minx_val(h) ) minx_val(h)=z;
10163 if ( z>maxx_val(h) ) maxx_val(h)=z;
10164 z=y_coord(p)+mp->cur_y+mp_take_fraction(mp, d,dy);
10165 if ( z<miny_val(h) ) miny_val(h)=z;
10166 if ( z>maxy_val(h) ) maxy_val(h)=z
10167
10168 @ @<Advance |p| to the end of the path and make |q| the previous knot@>=
10169 do {  
10170   q=p;
10171   p=link(p);
10172 } while (right_type(p)!=mp_endpoint)
10173
10174 @ The major difficulty in finding the bounding box of an edge structure is the
10175 effect of clipping paths.  We treat them conservatively by only clipping to the
10176 clipping path's bounding box, but this still
10177 requires recursive calls to |set_bbox| in order to find the bounding box of
10178 @^recursion@>
10179 the objects to be clipped.  Such calls are distinguished by the fact that the
10180 boolean parameter |top_level| is false.
10181
10182 @c void mp_set_bbox (MP mp,pointer h, boolean top_level) {
10183   pointer p;  /* a graphical object being considered */
10184   scaled sminx,sminy,smaxx,smaxy;
10185   /* for saving the bounding box during recursive calls */
10186   scaled x0,x1,y0,y1;  /* temporary registers */
10187   integer lev;  /* nesting level for |mp_start_bounds_code| nodes */
10188   @<Wipe out any existing bounding box information if |bbtype(h)| is
10189   incompatible with |internal[mp_true_corners]|@>;
10190   while ( link(bblast(h))!=null ) { 
10191     p=link(bblast(h));
10192     bblast(h)=p;
10193     switch (type(p)) {
10194     case mp_stop_clip_code: 
10195       if ( top_level ) mp_confusion(mp, "bbox");  else return;
10196 @:this can't happen bbox}{\quad bbox@>
10197       break;
10198     @<Other cases for updating the bounding box based on the type of object |p|@>;
10199     } /* all cases are enumerated above */
10200   }
10201   if ( ! top_level ) mp_confusion(mp, "bbox");
10202 }
10203
10204 @ @<Internal library declarations@>=
10205 void mp_set_bbox (MP mp,pointer h, boolean top_level);
10206
10207 @ @<Wipe out any existing bounding box information if |bbtype(h)| is...@>=
10208 switch (bbtype(h)) {
10209 case no_bounds: 
10210   break;
10211 case bounds_set: 
10212   if ( mp->internal[mp_true_corners]>0 ) mp_init_bbox(mp, h);
10213   break;
10214 case bounds_unset: 
10215   if ( mp->internal[mp_true_corners]<=0 ) mp_init_bbox(mp, h);
10216   break;
10217 } /* there are no other cases */
10218
10219 @ @<Other cases for updating the bounding box...@>=
10220 case mp_fill_code: 
10221   mp_path_bbox(mp, path_p(p));
10222   if ( pen_p(p)!=null ) { 
10223     x0=minx; y0=miny;
10224     x1=maxx; y1=maxy;
10225     mp_pen_bbox(mp, pen_p(p));
10226     minx=minx+x0;
10227     miny=miny+y0;
10228     maxx=maxx+x1;
10229     maxy=maxy+y1;
10230   }
10231   mp_adjust_bbox(mp, h);
10232   break;
10233
10234 @ @<Other cases for updating the bounding box...@>=
10235 case mp_start_bounds_code: 
10236   if ( mp->internal[mp_true_corners]>0 ) {
10237     bbtype(h)=bounds_unset;
10238   } else { 
10239     bbtype(h)=bounds_set;
10240     mp_path_bbox(mp, path_p(p));
10241     mp_adjust_bbox(mp, h);
10242     @<Scan to the matching |mp_stop_bounds_code| node and update |p| and
10243       |bblast(h)|@>;
10244   }
10245   break;
10246 case mp_stop_bounds_code: 
10247   if ( mp->internal[mp_true_corners]<=0 ) mp_confusion(mp, "bbox2");
10248 @:this can't happen bbox2}{\quad bbox2@>
10249   break;
10250
10251 @ @<Scan to the matching |mp_stop_bounds_code| node and update |p| and...@>=
10252 lev=1;
10253 while ( lev!=0 ) { 
10254   if ( link(p)==null ) mp_confusion(mp, "bbox2");
10255 @:this can't happen bbox2}{\quad bbox2@>
10256   p=link(p);
10257   if ( type(p)==mp_start_bounds_code ) incr(lev);
10258   else if ( type(p)==mp_stop_bounds_code ) decr(lev);
10259 }
10260 bblast(h)=p
10261
10262 @ It saves a lot of grief here to be slightly conservative and not account for
10263 omitted parts of dashed lines.  We also don't worry about the material omitted
10264 when using butt end caps.  The basic computation is for round end caps and
10265 |box_ends| augments it for square end caps.
10266
10267 @<Other cases for updating the bounding box...@>=
10268 case mp_stroked_code: 
10269   mp_path_bbox(mp, path_p(p));
10270   x0=minx; y0=miny;
10271   x1=maxx; y1=maxy;
10272   mp_pen_bbox(mp, pen_p(p));
10273   minx=minx+x0;
10274   miny=miny+y0;
10275   maxx=maxx+x1;
10276   maxy=maxy+y1;
10277   mp_adjust_bbox(mp, h);
10278   if ( (left_type(path_p(p))==mp_endpoint)&&(lcap_val(p)==2) )
10279     mp_box_ends(mp, path_p(p), pen_p(p), h);
10280   break;
10281
10282 @ The height width and depth information stored in a text node determines a
10283 rectangle that needs to be transformed according to the transformation
10284 parameters stored in the text node.
10285
10286 @<Other cases for updating the bounding box...@>=
10287 case mp_text_code: 
10288   x1=mp_take_scaled(mp, txx_val(p),width_val(p));
10289   y0=mp_take_scaled(mp, txy_val(p),-depth_val(p));
10290   y1=mp_take_scaled(mp, txy_val(p),height_val(p));
10291   minx=tx_val(p);
10292   maxx=minx;
10293   if ( y0<y1 ) { minx=minx+y0; maxx=maxx+y1;  }
10294   else         { minx=minx+y1; maxx=maxx+y0;  }
10295   if ( x1<0 ) minx=minx+x1;  else maxx=maxx+x1;
10296   x1=mp_take_scaled(mp, tyx_val(p),width_val(p));
10297   y0=mp_take_scaled(mp, tyy_val(p),-depth_val(p));
10298   y1=mp_take_scaled(mp, tyy_val(p),height_val(p));
10299   miny=ty_val(p);
10300   maxy=miny;
10301   if ( y0<y1 ) { miny=miny+y0; maxy=maxy+y1;  }
10302   else         { miny=miny+y1; maxy=maxy+y0;  }
10303   if ( x1<0 ) miny=miny+x1;  else maxy=maxy+x1;
10304   mp_adjust_bbox(mp, h);
10305   break;
10306
10307 @ This case involves a recursive call that advances |bblast(h)| to the node of
10308 type |mp_stop_clip_code| that matches |p|.
10309
10310 @<Other cases for updating the bounding box...@>=
10311 case mp_start_clip_code: 
10312   mp_path_bbox(mp, path_p(p));
10313   x0=minx; y0=miny;
10314   x1=maxx; y1=maxy;
10315   sminx=minx_val(h); sminy=miny_val(h);
10316   smaxx=maxx_val(h); smaxy=maxy_val(h);
10317   @<Reinitialize the bounding box in header |h| and call |set_bbox| recursively
10318     starting at |link(p)|@>;
10319   @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,
10320     |y0|, |y1|@>;
10321   minx=sminx; miny=sminy;
10322   maxx=smaxx; maxy=smaxy;
10323   mp_adjust_bbox(mp, h);
10324   break;
10325
10326 @ @<Reinitialize the bounding box in header |h| and call |set_bbox|...@>=
10327 minx_val(h)=el_gordo;
10328 miny_val(h)=el_gordo;
10329 maxx_val(h)=-el_gordo;
10330 maxy_val(h)=-el_gordo;
10331 mp_set_bbox(mp, h,false)
10332
10333 @ @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,...@>=
10334 if ( minx_val(h)<x0 ) minx_val(h)=x0;
10335 if ( miny_val(h)<y0 ) miny_val(h)=y0;
10336 if ( maxx_val(h)>x1 ) maxx_val(h)=x1;
10337 if ( maxy_val(h)>y1 ) maxy_val(h)=y1
10338
10339 @* \[22] Finding an envelope.
10340 When \MP\ has a path and a polygonal pen, it needs to express the desired
10341 shape in terms of things \ps\ can understand.  The present task is to compute
10342 a new path that describes the region to be filled.  It is convenient to
10343 define this as a two step process where the first step is determining what
10344 offset to use for each segment of the path.
10345
10346 @ Given a pointer |c| to a cyclic path,
10347 and a pointer~|h| to the first knot of a pen polygon,
10348 the |offset_prep| routine changes the path into cubics that are
10349 associated with particular pen offsets. Thus if the cubic between |p|
10350 and~|q| is associated with the |k|th offset and the cubic between |q| and~|r|
10351 has offset |l| then |info(q)=zero_off+l-k|. (The constant |zero_off| is added
10352 to because |l-k| could be negative.)
10353
10354 After overwriting the type information with offset differences, we no longer
10355 have a true path so we refer to the knot list returned by |offset_prep| as an
10356 ``envelope spec.''
10357 @^envelope spec@>
10358 Since an envelope spec only determines relative changes in pen offsets,
10359 |offset_prep| sets a global variable |spec_offset| to the relative change from
10360 |h| to the first offset.
10361
10362 @d zero_off 16384 /* added to offset changes to make them positive */
10363
10364 @<Glob...@>=
10365 integer spec_offset; /* number of pen edges between |h| and the initial offset */
10366
10367 @ @c @<Declare subroutines needed by |offset_prep|@>;
10368 pointer mp_offset_prep (MP mp,pointer c, pointer h) {
10369   halfword n; /* the number of vertices in the pen polygon */
10370   pointer p,q,q0,r,w, ww; /* for list manipulation */
10371   integer k_needed; /* amount to be added to |info(p)| when it is computed */
10372   pointer w0; /* a pointer to pen offset to use just before |p| */
10373   scaled dxin,dyin; /* the direction into knot |p| */
10374   integer turn_amt; /* change in pen offsets for the current cubic */
10375   @<Other local variables for |offset_prep|@>;
10376   dx0=0; dy0=0;
10377   @<Initialize the pen size~|n|@>;
10378   @<Initialize the incoming direction and pen offset at |c|@>;
10379   p=c; k_needed=0;
10380   do {  
10381     q=link(p);
10382     @<Split the cubic between |p| and |q|, if necessary, into cubics
10383       associated with single offsets, after which |q| should
10384       point to the end of the final such cubic@>;
10385   NOT_FOUND:
10386     @<Advance |p| to node |q|, removing any ``dead'' cubics that
10387       might have been introduced by the splitting process@>;
10388   } while (q!=c);
10389   @<Fix the offset change in |info(c)| and set |c| to the return value of
10390     |offset_prep|@>;
10391   return c;
10392 }
10393
10394 @ We shall want to keep track of where certain knots on the cyclic path
10395 wind up in the envelope spec.  It doesn't suffice just to keep pointers to
10396 knot nodes because some nodes are deleted while removing dead cubics.  Thus
10397 |offset_prep| updates the following pointers
10398
10399 @<Glob...@>=
10400 pointer spec_p1;
10401 pointer spec_p2; /* pointers to distinguished knots */
10402
10403 @ @<Set init...@>=
10404 mp->spec_p1=null; mp->spec_p2=null;
10405
10406 @ @<Initialize the pen size~|n|@>=
10407 n=0; p=h;
10408 do {  
10409   incr(n);
10410   p=link(p);
10411 } while (p!=h)
10412
10413 @ Since the true incoming direction isn't known yet, we just pick a direction
10414 consistent with the pen offset~|h|.  If this is wrong, it can be corrected
10415 later.
10416
10417 @<Initialize the incoming direction and pen offset at |c|@>=
10418 dxin=x_coord(link(h))-x_coord(knil(h));
10419 dyin=y_coord(link(h))-y_coord(knil(h));
10420 if ( (dxin==0)&&(dyin==0) ) {
10421   dxin=y_coord(knil(h))-y_coord(h);
10422   dyin=x_coord(h)-x_coord(knil(h));
10423 }
10424 w0=h
10425
10426 @ We must be careful not to remove the only cubic in a cycle.
10427
10428 But we must also be careful for another reason. If the user-supplied
10429 path starts with a set of degenerate cubics, the target node |q| can
10430 be collapsed to the initial node |p| which might be the same as the
10431 initial node |c| of the curve. This would cause the |offset_prep| routine
10432 to bail out too early, causing distress later on. (See for example
10433 the testcase reported by Bogus\l{}aw Jackowski in tracker id 267, case 52c
10434 on Sarovar.)
10435
10436 @<Advance |p| to node |q|, removing any ``dead'' cubics...@>=
10437 q0=q;
10438 do { 
10439   r=link(p);
10440   if ( x_coord(p)==right_x(p) && y_coord(p)==right_y(p) &&
10441        x_coord(p)==left_x(r)  && y_coord(p)==left_y(r) &&
10442        x_coord(p)==x_coord(r) && y_coord(p)==y_coord(r) &&
10443        r!=p ) {
10444       @<Remove the cubic following |p| and update the data structures
10445         to merge |r| into |p|@>;
10446   }
10447   p=r;
10448 } while (p!=q);
10449 /* Check if we removed too much */
10450 if(q!=q0)
10451   q = link(q)
10452
10453 @ @<Remove the cubic following |p| and update the data structures...@>=
10454 { k_needed=info(p)-zero_off;
10455   if ( r==q ) { 
10456     q=p;
10457   } else { 
10458     info(p)=k_needed+info(r);
10459     k_needed=0;
10460   };
10461   if ( r==c ) { info(p)=info(c); c=p; };
10462   if ( r==mp->spec_p1 ) mp->spec_p1=p;
10463   if ( r==mp->spec_p2 ) mp->spec_p2=p;
10464   r=p; mp_remove_cubic(mp, p);
10465 }
10466
10467 @ Not setting the |info| field of the newly created knot allows the splitting
10468 routine to work for paths.
10469
10470 @<Declare subroutines needed by |offset_prep|@>=
10471 void mp_split_cubic (MP mp,pointer p, fraction t) { /* splits the cubic after |p| */
10472   scaled v; /* an intermediate value */
10473   pointer q,r; /* for list manipulation */
10474   q=link(p); r=mp_get_node(mp, knot_node_size); link(p)=r; link(r)=q;
10475   originator(r)=mp_program_code;
10476   left_type(r)=mp_explicit; right_type(r)=mp_explicit;
10477   v=t_of_the_way(right_x(p),left_x(q));
10478   right_x(p)=t_of_the_way(x_coord(p),right_x(p));
10479   left_x(q)=t_of_the_way(left_x(q),x_coord(q));
10480   left_x(r)=t_of_the_way(right_x(p),v);
10481   right_x(r)=t_of_the_way(v,left_x(q));
10482   x_coord(r)=t_of_the_way(left_x(r),right_x(r));
10483   v=t_of_the_way(right_y(p),left_y(q));
10484   right_y(p)=t_of_the_way(y_coord(p),right_y(p));
10485   left_y(q)=t_of_the_way(left_y(q),y_coord(q));
10486   left_y(r)=t_of_the_way(right_y(p),v);
10487   right_y(r)=t_of_the_way(v,left_y(q));
10488   y_coord(r)=t_of_the_way(left_y(r),right_y(r));
10489 }
10490
10491 @ This does not set |info(p)| or |right_type(p)|.
10492
10493 @<Declare subroutines needed by |offset_prep|@>=
10494 void mp_remove_cubic (MP mp,pointer p) { /* removes the dead cubic following~|p| */
10495   pointer q; /* the node that disappears */
10496   q=link(p); link(p)=link(q);
10497   right_x(p)=right_x(q); right_y(p)=right_y(q);
10498   mp_free_node(mp, q,knot_node_size);
10499 }
10500
10501 @ Let $d\prec d'$ mean that the counter-clockwise angle from $d$ to~$d'$ is
10502 strictly between zero and $180^\circ$.  Then we can define $d\preceq d'$ to
10503 mean that the angle could be zero or $180^\circ$. If $w_k=(u_k,v_k)$ is the
10504 $k$th pen offset, the $k$th pen edge direction is defined by the formula
10505 $$d_k=(u\k-u_k,\,v\k-v_k).$$
10506 When listed by increasing $k$, these directions occur in counter-clockwise
10507 order so that $d_k\preceq d\k$ for all~$k$.
10508 The goal of |offset_prep| is to find an offset index~|k| to associate with
10509 each cubic, such that the direction $d(t)$ of the cubic satisfies
10510 $$d_{k-1}\preceq d(t)\preceq d_k\qquad\hbox{for $0\le t\le 1$.}\eqno(*)$$
10511 We may have to split a cubic into many pieces before each
10512 piece corresponds to a unique offset.
10513
10514 @<Split the cubic between |p| and |q|, if necessary, into cubics...@>=
10515 info(p)=zero_off+k_needed;
10516 k_needed=0;
10517 @<Prepare for derivative computations;
10518   |goto not_found| if the current cubic is dead@>;
10519 @<Find the initial direction |(dx,dy)|@>;
10520 @<Update |info(p)| and find the offset $w_k$ such that
10521   $d_{k-1}\preceq(\\{dx},\\{dy})\prec d_k$; also advance |w0| for
10522   the direction change at |p|@>;
10523 @<Find the final direction |(dxin,dyin)|@>;
10524 @<Decide on the net change in pen offsets and set |turn_amt|@>;
10525 @<Complete the offset splitting process@>;
10526 w0=mp_pen_walk(mp, w0,turn_amt)
10527
10528 @ @<Declare subroutines needed by |offset_prep|@>=
10529 pointer mp_pen_walk (MP mp,pointer w, integer k) {
10530   /* walk |k| steps around a pen from |w| */
10531   while ( k>0 ) { w=link(w); decr(k);  };
10532   while ( k<0 ) { w=knil(w); incr(k);  };
10533   return w;
10534 }
10535
10536 @ The direction of a cubic $B(z_0,z_1,z_2,z_3;t)=\bigl(x(t),y(t)\bigr)$ can be
10537 calculated from the quadratic polynomials
10538 ${1\over3}x'(t)=B(x_1-x_0,x_2-x_1,x_3-x_2;t)$ and
10539 ${1\over3}y'(t)=B(y_1-y_0,y_2-y_1,y_3-y_2;t)$.
10540 Since we may be calculating directions from several cubics
10541 split from the current one, it is desirable to do these calculations
10542 without losing too much precision. ``Scaled up'' values of the
10543 derivatives, which will be less tainted by accumulated errors than
10544 derivatives found from the cubics themselves, are maintained in
10545 local variables |x0|, |x1|, and |x2|, representing $X_0=2^l(x_1-x_0)$,
10546 $X_1=2^l(x_2-x_1)$, and $X_2=2^l(x_3-x_2)$; similarly |y0|, |y1|, and~|y2|
10547 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)$.
10548
10549 @<Other local variables for |offset_prep|@>=
10550 integer x0,x1,x2,y0,y1,y2; /* representatives of derivatives */
10551 integer t0,t1,t2; /* coefficients of polynomial for slope testing */
10552 integer du,dv,dx,dy; /* for directions of the pen and the curve */
10553 integer dx0,dy0; /* initial direction for the first cubic in the curve */
10554 integer max_coef; /* used while scaling */
10555 integer x0a,x1a,x2a,y0a,y1a,y2a; /* intermediate values */
10556 fraction t; /* where the derivative passes through zero */
10557 fraction s; /* a temporary value */
10558
10559 @ @<Prepare for derivative computations...@>=
10560 x0=right_x(p)-x_coord(p);
10561 x2=x_coord(q)-left_x(q);
10562 x1=left_x(q)-right_x(p);
10563 y0=right_y(p)-y_coord(p); y2=y_coord(q)-left_y(q);
10564 y1=left_y(q)-right_y(p);
10565 max_coef=abs(x0);
10566 if ( abs(x1)>max_coef ) max_coef=abs(x1);
10567 if ( abs(x2)>max_coef ) max_coef=abs(x2);
10568 if ( abs(y0)>max_coef ) max_coef=abs(y0);
10569 if ( abs(y1)>max_coef ) max_coef=abs(y1);
10570 if ( abs(y2)>max_coef ) max_coef=abs(y2);
10571 if ( max_coef==0 ) goto NOT_FOUND;
10572 while ( max_coef<fraction_half ) {
10573   double(max_coef);
10574   double(x0); double(x1); double(x2);
10575   double(y0); double(y1); double(y2);
10576 }
10577
10578 @ Let us first solve a special case of the problem: Suppose we
10579 know an index~$k$ such that either (i)~$d(t)\succeq d_{k-1}$ for all~$t$
10580 and $d(0)\prec d_k$, or (ii)~$d(t)\preceq d_k$ for all~$t$ and
10581 $d(0)\succ d_{k-1}$.
10582 Then, in a sense, we're halfway done, since one of the two relations
10583 in $(*)$ is satisfied, and the other couldn't be satisfied for
10584 any other value of~|k|.
10585
10586 Actually, the conditions can be relaxed somewhat since a relation such as
10587 $d(t)\succeq d_{k-1}$ restricts $d(t)$ to a half plane when all that really
10588 matters is whether $d(t)$ crosses the ray in the $d_{k-1}$ direction from
10589 the origin.  The condition for case~(i) becomes $d_{k-1}\preceq d(0)\prec d_k$
10590 and $d(t)$ never crosses the $d_{k-1}$ ray in the clockwise direction.
10591 Case~(ii) is similar except $d(t)$ cannot cross the $d_k$ ray in the
10592 counterclockwise direction.
10593
10594 The |fin_offset_prep| subroutine solves the stated subproblem.
10595 It has a parameter called |rise| that is |1| in
10596 case~(i), |-1| in case~(ii). Parameters |x0| through |y2| represent
10597 the derivative of the cubic following |p|.
10598 The |w| parameter should point to offset~$w_k$ and |info(p)| should already
10599 be set properly.  The |turn_amt| parameter gives the absolute value of the
10600 overall net change in pen offsets.
10601
10602 @<Declare subroutines needed by |offset_prep|@>=
10603 void mp_fin_offset_prep (MP mp,pointer p, pointer w, integer 
10604   x0,integer x1, integer x2, integer y0, integer y1, integer y2, 
10605   integer rise, integer turn_amt)  {
10606   pointer ww; /* for list manipulation */
10607   scaled du,dv; /* for slope calculation */
10608   integer t0,t1,t2; /* test coefficients */
10609   fraction t; /* place where the derivative passes a critical slope */
10610   fraction s; /* slope or reciprocal slope */
10611   integer v; /* intermediate value for updating |x0..y2| */
10612   pointer q; /* original |link(p)| */
10613   q=link(p);
10614   while (1)  { 
10615     if ( rise>0 ) ww=link(w); /* a pointer to $w\k$ */
10616     else  ww=knil(w); /* a pointer to $w_{k-1}$ */
10617     @<Compute test coefficients |(t0,t1,t2)|
10618       for $d(t)$ versus $d_k$ or $d_{k-1}$@>;
10619     t=mp_crossing_point(mp, t0,t1,t2);
10620     if ( t>=fraction_one ) {
10621       if ( turn_amt>0 ) t=fraction_one;  else return;
10622     }
10623     @<Split the cubic at $t$,
10624       and split off another cubic if the derivative crosses back@>;
10625     w=ww;
10626   }
10627 }
10628
10629 @ We want $B(\\{t0},\\{t1},\\{t2};t)$ to be the dot product of $d(t)$ with a
10630 $-90^\circ$ rotation of the vector from |w| to |ww|.  This makes the resulting
10631 function cross from positive to negative when $d_{k-1}\preceq d(t)\preceq d_k$
10632 begins to fail.
10633
10634 @<Compute test coefficients |(t0,t1,t2)| for $d(t)$ versus...@>=
10635 du=x_coord(ww)-x_coord(w); dv=y_coord(ww)-y_coord(w);
10636 if ( abs(du)>=abs(dv) ) {
10637   s=mp_make_fraction(mp, dv,du);
10638   t0=mp_take_fraction(mp, x0,s)-y0;
10639   t1=mp_take_fraction(mp, x1,s)-y1;
10640   t2=mp_take_fraction(mp, x2,s)-y2;
10641   if ( du<0 ) { negate(t0); negate(t1); negate(t2);  }
10642 } else { 
10643   s=mp_make_fraction(mp, du,dv);
10644   t0=x0-mp_take_fraction(mp, y0,s);
10645   t1=x1-mp_take_fraction(mp, y1,s);
10646   t2=x2-mp_take_fraction(mp, y2,s);
10647   if ( dv<0 ) { negate(t0); negate(t1); negate(t2);  }
10648 }
10649 if ( t0<0 ) t0=0 /* should be positive without rounding error */
10650
10651 @ The curve has crossed $d_k$ or $d_{k-1}$; its initial segment satisfies
10652 $(*)$, and it might cross again, yielding another solution of $(*)$.
10653
10654 @<Split the cubic at $t$, and split off another...@>=
10655
10656 mp_split_cubic(mp, p,t); p=link(p); info(p)=zero_off+rise;
10657 decr(turn_amt);
10658 v=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10659 x0=t_of_the_way(v,x1);
10660 v=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10661 y0=t_of_the_way(v,y1);
10662 if ( turn_amt<0 ) {
10663   t1=t_of_the_way(t1,t2);
10664   if ( t1>0 ) t1=0; /* without rounding error, |t1| would be |<=0| */
10665   t=mp_crossing_point(mp, 0,-t1,-t2);
10666   if ( t>fraction_one ) t=fraction_one;
10667   incr(turn_amt);
10668   if ( (t==fraction_one)&&(link(p)!=q) ) {
10669     info(link(p))=info(link(p))-rise;
10670   } else { 
10671     mp_split_cubic(mp, p,t); info(link(p))=zero_off-rise;
10672     v=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10673     x2=t_of_the_way(x1,v);
10674     v=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10675     y2=t_of_the_way(y1,v);
10676   }
10677 }
10678 }
10679
10680 @ Now we must consider the general problem of |offset_prep|, when
10681 nothing is known about a given cubic. We start by finding its
10682 direction in the vicinity of |t=0|.
10683
10684 If $z'(t)=0$, the given cubic is numerically unstable but |offset_prep|
10685 has not yet introduced any more numerical errors.  Thus we can compute
10686 the true initial direction for the given cubic, even if it is almost
10687 degenerate.
10688
10689 @<Find the initial direction |(dx,dy)|@>=
10690 dx=x0; dy=y0;
10691 if ( dx==0 && dy==0 ) { 
10692   dx=x1; dy=y1;
10693   if ( dx==0 && dy==0 ) { 
10694     dx=x2; dy=y2;
10695   }
10696 }
10697 if ( p==c ) { dx0=dx; dy0=dy;  }
10698
10699 @ @<Find the final direction |(dxin,dyin)|@>=
10700 dxin=x2; dyin=y2;
10701 if ( dxin==0 && dyin==0 ) {
10702   dxin=x1; dyin=y1;
10703   if ( dxin==0 && dyin==0 ) {
10704     dxin=x0; dyin=y0;
10705   }
10706 }
10707
10708 @ The next step is to bracket the initial direction between consecutive
10709 edges of the pen polygon.  We must be careful to turn clockwise only if
10710 this makes the turn less than $180^\circ$. (A $180^\circ$ turn must be
10711 counter-clockwise in order to make \&{doublepath} envelopes come out
10712 @:double_path_}{\&{doublepath} primitive@>
10713 right.) This code depends on |w0| being the offset for |(dxin,dyin)|.
10714
10715 @<Update |info(p)| and find the offset $w_k$ such that...@>=
10716 turn_amt=mp_get_turn_amt(mp,w0,dx,dy,(mp_ab_vs_cd(mp, dy,dxin,dx,dyin)>=0));
10717 w=mp_pen_walk(mp, w0, turn_amt);
10718 w0=w;
10719 info(p)=info(p)+turn_amt
10720
10721 @ Decide how many pen offsets to go away from |w| in order to find the offset
10722 for |(dx,dy)|, going counterclockwise if |ccw| is |true|.  This assumes that
10723 |w| is the offset for some direction $(x',y')$ from which the angle to |(dx,dy)|
10724 in the sense determined by |ccw| is less than or equal to $180^\circ$.
10725
10726 If the pen polygon has only two edges, they could both be parallel
10727 to |(dx,dy)|.  In this case, we must be careful to stop after crossing the first
10728 such edge in order to avoid an infinite loop.
10729
10730 @<Declare subroutines needed by |offset_prep|@>=
10731 integer mp_get_turn_amt (MP mp,pointer w, scaled  dx,
10732                          scaled dy, boolean  ccw) {
10733   pointer ww; /* a neighbor of knot~|w| */
10734   integer s; /* turn amount so far */
10735   integer t; /* |ab_vs_cd| result */
10736   s=0;
10737   if ( ccw ) { 
10738     ww=link(w);
10739     do {  
10740       t=mp_ab_vs_cd(mp, dy,(x_coord(ww)-x_coord(w)),
10741                         dx,(y_coord(ww)-y_coord(w)));
10742       if ( t<0 ) break;
10743       incr(s);
10744       w=ww; ww=link(ww);
10745     } while (t>0);
10746   } else { 
10747     ww=knil(w);
10748     while ( mp_ab_vs_cd(mp, dy,(x_coord(w)-x_coord(ww)),
10749                             dx,(y_coord(w)-y_coord(ww))) < 0) { 
10750       decr(s);
10751       w=ww; ww=knil(ww);
10752     }
10753   }
10754   return s;
10755 }
10756
10757 @ When we're all done, the final offset is |w0| and the final curve direction
10758 is |(dxin,dyin)|.  With this knowledge of the incoming direction at |c|, we
10759 can correct |info(c)| which was erroneously based on an incoming offset
10760 of~|h|.
10761
10762 @d fix_by(A) info(c)=info(c)+(A)
10763
10764 @<Fix the offset change in |info(c)| and set |c| to the return value of...@>=
10765 mp->spec_offset=info(c)-zero_off;
10766 if ( link(c)==c ) {
10767   info(c)=zero_off+n;
10768 } else { 
10769   fix_by(k_needed);
10770   while ( w0!=h ) { fix_by(1); w0=link(w0);  };
10771   while ( info(c)<=zero_off-n ) fix_by(n);
10772   while ( info(c)>zero_off ) fix_by(-n);
10773   if ( (info(c)!=zero_off)&&(mp_ab_vs_cd(mp, dy0,dxin,dx0,dyin)>=0) ) fix_by(n);
10774 }
10775 return c
10776
10777 @ Finally we want to reduce the general problem to situations that
10778 |fin_offset_prep| can handle. We split the cubic into at most three parts
10779 with respect to $d_{k-1}$, and apply |fin_offset_prep| to each part.
10780
10781 @<Complete the offset splitting process@>=
10782 ww=knil(w);
10783 @<Compute test coeff...@>;
10784 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set
10785   |t:=fraction_one+1|@>;
10786 if ( t>fraction_one ) {
10787   mp_fin_offset_prep(mp, p,w,x0,x1,x2,y0,y1,y2,1,turn_amt);
10788 } else {
10789   mp_split_cubic(mp, p,t); r=link(p);
10790   x1a=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10791   x2a=t_of_the_way(x1a,x1);
10792   y1a=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10793   y2a=t_of_the_way(y1a,y1);
10794   mp_fin_offset_prep(mp, p,w,x0,x1a,x2a,y0,y1a,y2a,1,0); x0=x2a; y0=y2a;
10795   info(r)=zero_off-1;
10796   if ( turn_amt>=0 ) {
10797     t1=t_of_the_way(t1,t2);
10798     if ( t1>0 ) t1=0;
10799     t=mp_crossing_point(mp, 0,-t1,-t2);
10800     if ( t>fraction_one ) t=fraction_one;
10801     @<Split off another rising cubic for |fin_offset_prep|@>;
10802     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,0);
10803   } else {
10804     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,(-1-turn_amt));
10805   }
10806 }
10807
10808 @ @<Split off another rising cubic for |fin_offset_prep|@>=
10809 mp_split_cubic(mp, r,t); info(link(r))=zero_off+1;
10810 x1a=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10811 x0a=t_of_the_way(x1,x1a);
10812 y1a=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10813 y0a=t_of_the_way(y1,y1a);
10814 mp_fin_offset_prep(mp, link(r),w,x0a,x1a,x2,y0a,y1a,y2,1,turn_amt);
10815 x2=x0a; y2=y0a
10816
10817 @ At this point, the direction of the incoming pen edge is |(-du,-dv)|.
10818 When the component of $d(t)$ perpendicular to |(-du,-dv)| crosses zero, we
10819 need to decide whether the directions are parallel or antiparallel.  We
10820 can test this by finding the dot product of $d(t)$ and |(-du,-dv)|, but this
10821 should be avoided when the value of |turn_amt| already determines the
10822 answer.  If |t2<0|, there is one crossing and it is antiparallel only if
10823 |turn_amt>=0|.  If |turn_amt<0|, there should always be at least one
10824 crossing and the first crossing cannot be antiparallel.
10825
10826 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set...@>=
10827 t=mp_crossing_point(mp, t0,t1,t2);
10828 if ( turn_amt>=0 ) {
10829   if ( t2<0 ) {
10830     t=fraction_one+1;
10831   } else { 
10832     u0=t_of_the_way(x0,x1);
10833     u1=t_of_the_way(x1,x2);
10834     ss=mp_take_fraction(mp, -du,t_of_the_way(u0,u1));
10835     v0=t_of_the_way(y0,y1);
10836     v1=t_of_the_way(y1,y2);
10837     ss=ss+mp_take_fraction(mp, -dv,t_of_the_way(v0,v1));
10838     if ( ss<0 ) t=fraction_one+1;
10839   }
10840 } else if ( t>fraction_one ) {
10841   t=fraction_one;
10842 }
10843
10844 @ @<Other local variables for |offset_prep|@>=
10845 integer u0,u1,v0,v1; /* intermediate values for $d(t)$ calculation */
10846 integer ss = 0; /* the part of the dot product computed so far */
10847 int d_sign; /* sign of overall change in direction for this cubic */
10848
10849 @ If the cubic almost has a cusp, it is a numerically ill-conditioned
10850 problem to decide which way it loops around but that's OK as long we're
10851 consistent.  To make \&{doublepath} envelopes work properly, reversing
10852 the path should always change the sign of |turn_amt|.
10853
10854 @<Decide on the net change in pen offsets and set |turn_amt|@>=
10855 d_sign=mp_ab_vs_cd(mp, dx,dyin, dxin,dy);
10856 if ( d_sign==0 ) {
10857   @<Check rotation direction based on node position@>
10858 }
10859 if ( d_sign==0 ) {
10860   if ( dx==0 ) {
10861     if ( dy>0 ) d_sign=1;  else d_sign=-1;
10862   } else {
10863     if ( dx>0 ) d_sign=1;  else d_sign=-1; 
10864   }
10865 }
10866 @<Make |ss| negative if and only if the total change in direction is
10867   more than $180^\circ$@>;
10868 turn_amt=mp_get_turn_amt(mp, w, dxin, dyin, (d_sign>0));
10869 if ( ss<0 ) turn_amt=turn_amt-d_sign*n
10870
10871 @ We check rotation direction by looking at the vector connecting the current
10872 node with the next. If its angle with incoming and outgoing tangents has the
10873 same sign, we pick this as |d_sign|, since it means we have a flex, not a cusp.
10874 Otherwise we proceed to the cusp code.
10875
10876 @<Check rotation direction based on node position@>=
10877 u0=x_coord(q)-x_coord(p);
10878 u1=y_coord(q)-y_coord(p);
10879 d_sign = half(mp_ab_vs_cd(mp, dx, u1, u0, dy)+
10880   mp_ab_vs_cd(mp, u0, dyin, dxin, u1));
10881
10882 @ In order to be invariant under path reversal, the result of this computation
10883 should not change when |x0|, |y0|, $\ldots$ are all negated and |(x0,y0)| is
10884 then swapped with |(x2,y2)|.  We make use of the identities
10885 |take_fraction(-a,-b)=take_fraction(a,b)| and
10886 |t_of_the_way(-a,-b)=-(t_of_the_way(a,b))|.
10887
10888 @<Make |ss| negative if and only if the total change in direction is...@>=
10889 t0=half(mp_take_fraction(mp, x0,y2))-half(mp_take_fraction(mp, x2,y0));
10890 t1=half(mp_take_fraction(mp, x1,(y0+y2)))-half(mp_take_fraction(mp, y1,(x0+x2)));
10891 if ( t0==0 ) t0=d_sign; /* path reversal always negates |d_sign| */
10892 if ( t0>0 ) {
10893   t=mp_crossing_point(mp, t0,t1,-t0);
10894   u0=t_of_the_way(x0,x1);
10895   u1=t_of_the_way(x1,x2);
10896   v0=t_of_the_way(y0,y1);
10897   v1=t_of_the_way(y1,y2);
10898 } else { 
10899   t=mp_crossing_point(mp, -t0,t1,t0);
10900   u0=t_of_the_way(x2,x1);
10901   u1=t_of_the_way(x1,x0);
10902   v0=t_of_the_way(y2,y1);
10903   v1=t_of_the_way(y1,y0);
10904 }
10905 ss=mp_take_fraction(mp, (x0+x2),t_of_the_way(u0,u1))+
10906    mp_take_fraction(mp, (y0+y2),t_of_the_way(v0,v1))
10907
10908 @ Here's a routine that prints an envelope spec in symbolic form.  It assumes
10909 that the |cur_pen| has not been walked around to the first offset.
10910
10911 @c 
10912 void mp_print_spec (MP mp,pointer cur_spec, pointer cur_pen, char *s) {
10913   pointer p,q; /* list traversal */
10914   pointer w; /* the current pen offset */
10915   mp_print_diagnostic(mp, "Envelope spec",s,true);
10916   p=cur_spec; w=mp_pen_walk(mp, cur_pen,mp->spec_offset);
10917   mp_print_ln(mp);
10918   mp_print_two(mp, x_coord(cur_spec),y_coord(cur_spec));
10919   mp_print(mp, " % beginning with offset ");
10920   mp_print_two(mp, x_coord(w),y_coord(w));
10921   do { 
10922     while (1) {  
10923       q=link(p);
10924       @<Print the cubic between |p| and |q|@>;
10925       p=q;
10926           if ((p==cur_spec) || (info(p)!=zero_off)) 
10927         break;
10928     }
10929     if ( info(p)!=zero_off ) {
10930       @<Update |w| as indicated by |info(p)| and print an explanation@>;
10931     }
10932   } while (p!=cur_spec);
10933   mp_print_nl(mp, " & cycle");
10934   mp_end_diagnostic(mp, true);
10935 }
10936
10937 @ @<Update |w| as indicated by |info(p)| and print an explanation@>=
10938
10939   w=mp_pen_walk(mp, w, (info(p)-zero_off));
10940   mp_print(mp, " % ");
10941   if ( info(p)>zero_off ) mp_print(mp, "counter");
10942   mp_print(mp, "clockwise to offset ");
10943   mp_print_two(mp, x_coord(w),y_coord(w));
10944 }
10945
10946 @ @<Print the cubic between |p| and |q|@>=
10947
10948   mp_print_nl(mp, "   ..controls ");
10949   mp_print_two(mp, right_x(p),right_y(p));
10950   mp_print(mp, " and ");
10951   mp_print_two(mp, left_x(q),left_y(q));
10952   mp_print_nl(mp, " ..");
10953   mp_print_two(mp, x_coord(q),y_coord(q));
10954 }
10955
10956 @ Once we have an envelope spec, the remaining task to construct the actual
10957 envelope by offsetting each cubic as determined by the |info| fields in
10958 the knots.  First we use |offset_prep| to convert the |c| into an envelope
10959 spec. Then we add the offsets so that |c| becomes a cyclic path that represents
10960 the envelope.
10961
10962 The |ljoin| and |miterlim| parameters control the treatment of points where the
10963 pen offset changes, and |lcap| controls the endpoints of a \&{doublepath}.
10964 The endpoints are easily located because |c| is given in undoubled form
10965 and then doubled in this procedure.  We use |spec_p1| and |spec_p2| to keep
10966 track of the endpoints and treat them like very sharp corners.
10967 Butt end caps are treated like beveled joins; round end caps are treated like
10968 round joins; and square end caps are achieved by setting |join_type:=3|.
10969
10970 None of these parameters apply to inside joins where the convolution tracing
10971 has retrograde lines.  In such cases we use a simple connect-the-endpoints
10972 approach that is achieved by setting |join_type:=2|.
10973
10974 @c @<Declare a function called |insert_knot|@>;
10975 pointer mp_make_envelope (MP mp,pointer c, pointer h, small_number ljoin,
10976   small_number lcap, scaled miterlim) {
10977   pointer p,q,r,q0; /* for manipulating the path */
10978   int join_type=0; /* codes |0..3| for mitered, round, beveled, or square */
10979   pointer w,w0; /* the pen knot for the current offset */
10980   scaled qx,qy; /* unshifted coordinates of |q| */
10981   halfword k,k0; /* controls pen edge insertion */
10982   @<Other local variables for |make_envelope|@>;
10983   dxin=0; dyin=0; dxout=0; dyout=0;
10984   mp->spec_p1=null; mp->spec_p2=null;
10985   @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>;
10986   @<Use |offset_prep| to compute the envelope spec then walk |h| around to
10987     the initial offset@>;
10988   w=h;
10989   p=c;
10990   do {  
10991     q=link(p); q0=q;
10992     qx=x_coord(q); qy=y_coord(q);
10993     k=info(q);
10994     k0=k; w0=w;
10995     if ( k!=zero_off ) {
10996       @<Set |join_type| to indicate how to handle offset changes at~|q|@>;
10997     }
10998     @<Add offset |w| to the cubic from |p| to |q|@>;
10999     while ( k!=zero_off ) { 
11000       @<Step |w| and move |k| one step closer to |zero_off|@>;
11001       if ( (join_type==1)||(k==zero_off) )
11002          q=mp_insert_knot(mp, q,qx+x_coord(w),qy+y_coord(w));
11003     };
11004     if ( q!=link(p) ) {
11005       @<Set |p=link(p)| and add knots between |p| and |q| as
11006         required by |join_type|@>;
11007     }
11008     p=q;
11009   } while (q0!=c);
11010   return c;
11011 }
11012
11013 @ @<Use |offset_prep| to compute the envelope spec then walk |h| around to...@>=
11014 c=mp_offset_prep(mp, c,h);
11015 if ( mp->internal[mp_tracing_specs]>0 ) 
11016   mp_print_spec(mp, c,h,"");
11017 h=mp_pen_walk(mp, h,mp->spec_offset)
11018
11019 @ Mitered and squared-off joins depend on path directions that are difficult to
11020 compute for degenerate cubics.  The envelope spec computed by |offset_prep| can
11021 have degenerate cubics only if the entire cycle collapses to a single
11022 degenerate cubic.  Setting |join_type:=2| in this case makes the computed
11023 envelope degenerate as well.
11024
11025 @<Set |join_type| to indicate how to handle offset changes at~|q|@>=
11026 if ( k<zero_off ) {
11027   join_type=2;
11028 } else {
11029   if ( (q!=mp->spec_p1)&&(q!=mp->spec_p2) ) join_type=ljoin;
11030   else if ( lcap==2 ) join_type=3;
11031   else join_type=2-lcap;
11032   if ( (join_type==0)||(join_type==3) ) {
11033     @<Set the incoming and outgoing directions at |q|; in case of
11034       degeneracy set |join_type:=2|@>;
11035     if ( join_type==0 ) {
11036       @<If |miterlim| is less than the secant of half the angle at |q|
11037         then set |join_type:=2|@>;
11038     }
11039   }
11040 }
11041
11042 @ @<If |miterlim| is less than the secant of half the angle at |q|...@>=
11043
11044   tmp=mp_take_fraction(mp, miterlim,fraction_half+
11045       half(mp_take_fraction(mp, dxin,dxout)+mp_take_fraction(mp, dyin,dyout)));
11046   if ( tmp<unity )
11047     if ( mp_take_scaled(mp, miterlim,tmp)<unity ) join_type=2;
11048 }
11049
11050 @ @<Other local variables for |make_envelope|@>=
11051 fraction dxin,dyin,dxout,dyout; /* directions at |q| when square or mitered */
11052 scaled tmp; /* a temporary value */
11053
11054 @ The coordinates of |p| have already been shifted unless |p| is the first
11055 knot in which case they get shifted at the very end.
11056
11057 @<Add offset |w| to the cubic from |p| to |q|@>=
11058 right_x(p)=right_x(p)+x_coord(w);
11059 right_y(p)=right_y(p)+y_coord(w);
11060 left_x(q)=left_x(q)+x_coord(w);
11061 left_y(q)=left_y(q)+y_coord(w);
11062 x_coord(q)=x_coord(q)+x_coord(w);
11063 y_coord(q)=y_coord(q)+y_coord(w);
11064 left_type(q)=mp_explicit;
11065 right_type(q)=mp_explicit
11066
11067 @ @<Step |w| and move |k| one step closer to |zero_off|@>=
11068 if ( k>zero_off ){ w=link(w); decr(k);  }
11069 else { w=knil(w); incr(k);  }
11070
11071 @ The cubic from |q| to the new knot at |(x,y)| becomes a line segment and
11072 the |right_x| and |right_y| fields of |r| are set from |q|.  This is done in
11073 case the cubic containing these control points is ``yet to be examined.''
11074
11075 @<Declare a function called |insert_knot|@>=
11076 pointer mp_insert_knot (MP mp,pointer q, scaled x, scaled y) {
11077   /* returns the inserted knot */
11078   pointer r; /* the new knot */
11079   r=mp_get_node(mp, knot_node_size);
11080   link(r)=link(q); link(q)=r;
11081   right_x(r)=right_x(q);
11082   right_y(r)=right_y(q);
11083   x_coord(r)=x;
11084   y_coord(r)=y;
11085   right_x(q)=x_coord(q);
11086   right_y(q)=y_coord(q);
11087   left_x(r)=x_coord(r);
11088   left_y(r)=y_coord(r);
11089   left_type(r)=mp_explicit;
11090   right_type(r)=mp_explicit;
11091   originator(r)=mp_program_code;
11092   return r;
11093 }
11094
11095 @ After setting |p:=link(p)|, either |join_type=1| or |q=link(p)|.
11096
11097 @<Set |p=link(p)| and add knots between |p| and |q| as...@>=
11098
11099   p=link(p);
11100   if ( (join_type==0)||(join_type==3) ) {
11101     if ( join_type==0 ) {
11102       @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>
11103     } else {
11104       @<Make |r| the last of two knots inserted between |p| and |q| to form a
11105         squared join@>;
11106     }
11107     if ( r!=null ) { 
11108       right_x(r)=x_coord(r);
11109       right_y(r)=y_coord(r);
11110     }
11111   }
11112 }
11113
11114 @ For very small angles, adding a knot is unnecessary and would cause numerical
11115 problems, so we just set |r:=null| in that case.
11116
11117 @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>=
11118
11119   det=mp_take_fraction(mp, dyout,dxin)-mp_take_fraction(mp, dxout,dyin);
11120   if ( abs(det)<26844 ) { 
11121      r=null; /* sine $<10^{-4}$ */
11122   } else { 
11123     tmp=mp_take_fraction(mp, x_coord(q)-x_coord(p),dyout)-
11124         mp_take_fraction(mp, y_coord(q)-y_coord(p),dxout);
11125     tmp=mp_make_fraction(mp, tmp,det);
11126     r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11127       y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11128   }
11129 }
11130
11131 @ @<Other local variables for |make_envelope|@>=
11132 fraction det; /* a determinant used for mitered join calculations */
11133
11134 @ @<Make |r| the last of two knots inserted between |p| and |q| to form a...@>=
11135
11136   ht_x=y_coord(w)-y_coord(w0);
11137   ht_y=x_coord(w0)-x_coord(w);
11138   while ( (abs(ht_x)<fraction_half)&&(abs(ht_y)<fraction_half) ) { 
11139     ht_x+=ht_x; ht_y+=ht_y;
11140   }
11141   @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range dot
11142     product with |(ht_x,ht_y)|@>;
11143   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxin,ht_x)+
11144                                   mp_take_fraction(mp, dyin,ht_y));
11145   r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11146                          y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11147   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxout,ht_x)+
11148                                   mp_take_fraction(mp, dyout,ht_y));
11149   r=mp_insert_knot(mp, r,x_coord(q)+mp_take_fraction(mp, tmp,dxout),
11150                          y_coord(q)+mp_take_fraction(mp, tmp,dyout));
11151 }
11152
11153 @ @<Other local variables for |make_envelope|@>=
11154 fraction ht_x,ht_y; /* perpendicular to the segment from |p| to |q| */
11155 scaled max_ht; /* maximum height of the pen polygon above the |w0|-|w| line */
11156 halfword kk; /* keeps track of the pen vertices being scanned */
11157 pointer ww; /* the pen vertex being tested */
11158
11159 @ The dot product of the vector from |w0| to |ww| with |(ht_x,ht_y)| ranges
11160 from zero to |max_ht|.
11161
11162 @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range...@>=
11163 max_ht=0;
11164 kk=zero_off;
11165 ww=w;
11166 while (1)  { 
11167   @<Step |ww| and move |kk| one step closer to |k0|@>;
11168   if ( kk==k0 ) break;
11169   tmp=mp_take_fraction(mp, (x_coord(ww)-x_coord(w0)),ht_x)+
11170       mp_take_fraction(mp, (y_coord(ww)-y_coord(w0)),ht_y);
11171   if ( tmp>max_ht ) max_ht=tmp;
11172 }
11173
11174
11175 @ @<Step |ww| and move |kk| one step closer to |k0|@>=
11176 if ( kk>k0 ) { ww=link(ww); decr(kk);  }
11177 else { ww=knil(ww); incr(kk);  }
11178
11179 @ @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>=
11180 if ( left_type(c)==mp_endpoint ) { 
11181   mp->spec_p1=mp_htap_ypoc(mp, c);
11182   mp->spec_p2=mp->path_tail;
11183   originator(mp->spec_p1)=mp_program_code;
11184   link(mp->spec_p2)=link(mp->spec_p1);
11185   link(mp->spec_p1)=c;
11186   mp_remove_cubic(mp, mp->spec_p1);
11187   c=mp->spec_p1;
11188   if ( c!=link(c) ) {
11189     originator(mp->spec_p2)=mp_program_code;
11190     mp_remove_cubic(mp, mp->spec_p2);
11191   } else {
11192     @<Make |c| look like a cycle of length one@>;
11193   }
11194 }
11195
11196 @ @<Make |c| look like a cycle of length one@>=
11197
11198   left_type(c)=mp_explicit; right_type(c)=mp_explicit;
11199   left_x(c)=x_coord(c); left_y(c)=y_coord(c);
11200   right_x(c)=x_coord(c); right_y(c)=y_coord(c);
11201 }
11202
11203 @ In degenerate situations we might have to look at the knot preceding~|q|.
11204 That knot is |p| but if |p<>c|, its coordinates have already been offset by |w|.
11205
11206 @<Set the incoming and outgoing directions at |q|; in case of...@>=
11207 dxin=x_coord(q)-left_x(q);
11208 dyin=y_coord(q)-left_y(q);
11209 if ( (dxin==0)&&(dyin==0) ) {
11210   dxin=x_coord(q)-right_x(p);
11211   dyin=y_coord(q)-right_y(p);
11212   if ( (dxin==0)&&(dyin==0) ) {
11213     dxin=x_coord(q)-x_coord(p);
11214     dyin=y_coord(q)-y_coord(p);
11215     if ( p!=c ) { /* the coordinates of |p| have been offset by |w| */
11216       dxin=dxin+x_coord(w);
11217       dyin=dyin+y_coord(w);
11218     }
11219   }
11220 }
11221 tmp=mp_pyth_add(mp, dxin,dyin);
11222 if ( tmp==0 ) {
11223   join_type=2;
11224 } else { 
11225   dxin=mp_make_fraction(mp, dxin,tmp);
11226   dyin=mp_make_fraction(mp, dyin,tmp);
11227   @<Set the outgoing direction at |q|@>;
11228 }
11229
11230 @ If |q=c| then the coordinates of |r| and the control points between |q|
11231 and~|r| have already been offset by |h|.
11232
11233 @<Set the outgoing direction at |q|@>=
11234 dxout=right_x(q)-x_coord(q);
11235 dyout=right_y(q)-y_coord(q);
11236 if ( (dxout==0)&&(dyout==0) ) {
11237   r=link(q);
11238   dxout=left_x(r)-x_coord(q);
11239   dyout=left_y(r)-y_coord(q);
11240   if ( (dxout==0)&&(dyout==0) ) {
11241     dxout=x_coord(r)-x_coord(q);
11242     dyout=y_coord(r)-y_coord(q);
11243   }
11244 }
11245 if ( q==c ) {
11246   dxout=dxout-x_coord(h);
11247   dyout=dyout-y_coord(h);
11248 }
11249 tmp=mp_pyth_add(mp, dxout,dyout);
11250 if ( tmp==0 ) mp_confusion(mp, "degenerate spec");
11251 @:this can't happen degerate spec}{\quad degenerate spec@>
11252 dxout=mp_make_fraction(mp, dxout,tmp);
11253 dyout=mp_make_fraction(mp, dyout,tmp)
11254
11255 @* \[23] Direction and intersection times.
11256 A path of length $n$ is defined parametrically by functions $x(t)$ and
11257 $y(t)$, for |0<=t<=n|; we can regard $t$ as the ``time'' at which the path
11258 reaches the point $\bigl(x(t),y(t)\bigr)$.  In this section of the program
11259 we shall consider operations that determine special times associated with
11260 given paths: the first time that a path travels in a given direction, and
11261 a pair of times at which two paths cross each other.
11262
11263 @ Let's start with the easier task. The function |find_direction_time| is
11264 given a direction |(x,y)| and a path starting at~|h|. If the path never
11265 travels in direction |(x,y)|, the direction time will be~|-1|; otherwise
11266 it will be nonnegative.
11267
11268 Certain anomalous cases can arise: If |(x,y)=(0,0)|, so that the given
11269 direction is undefined, the direction time will be~0. If $\bigl(x'(t),
11270 y'(t)\bigr)=(0,0)$, so that the path direction is undefined, it will be
11271 assumed to match any given direction at time~|t|.
11272
11273 The routine solves this problem in nondegenerate cases by rotating the path
11274 and the given direction so that |(x,y)=(1,0)|; i.e., the main task will be
11275 to find when a given path first travels ``due east.''
11276
11277 @c 
11278 scaled mp_find_direction_time (MP mp,scaled x, scaled y, pointer h) {
11279   scaled max; /* $\max\bigl(\vert x\vert,\vert y\vert\bigr)$ */
11280   pointer p,q; /* for list traversal */
11281   scaled n; /* the direction time at knot |p| */
11282   scaled tt; /* the direction time within a cubic */
11283   @<Other local variables for |find_direction_time|@>;
11284   @<Normalize the given direction for better accuracy;
11285     but |return| with zero result if it's zero@>;
11286   n=0; p=h; phi=0;
11287   while (1) { 
11288     if ( right_type(p)==mp_endpoint ) break;
11289     q=link(p);
11290     @<Rotate the cubic between |p| and |q|; then
11291       |goto found| if the rotated cubic travels due east at some time |tt|;
11292       but |break| if an entire cyclic path has been traversed@>;
11293     p=q; n=n+unity;
11294   }
11295   return (-unity);
11296 FOUND: 
11297   return (n+tt);
11298 }
11299
11300 @ @<Normalize the given direction for better accuracy...@>=
11301 if ( abs(x)<abs(y) ) { 
11302   x=mp_make_fraction(mp, x,abs(y));
11303   if ( y>0 ) y=fraction_one; else y=-fraction_one;
11304 } else if ( x==0 ) { 
11305   return 0;
11306 } else  { 
11307   y=mp_make_fraction(mp, y,abs(x));
11308   if ( x>0 ) x=fraction_one; else x=-fraction_one;
11309 }
11310
11311 @ Since we're interested in the tangent directions, we work with the
11312 derivative $${\textstyle1\over3}B'(x_0,x_1,x_2,x_3;t)=
11313 B(x_1-x_0,x_2-x_1,x_3-x_2;t)$$ instead of
11314 $B(x_0,x_1,x_2,x_3;t)$ itself. The derived coefficients are also scaled up
11315 in order to achieve better accuracy.
11316
11317 The given path may turn abruptly at a knot, and it might pass the critical
11318 tangent direction at such a time. Therefore we remember the direction |phi|
11319 in which the previous rotated cubic was traveling. (The value of |phi| will be
11320 undefined on the first cubic, i.e., when |n=0|.)
11321
11322 @<Rotate the cubic between |p| and |q|; then...@>=
11323 tt=0;
11324 @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples of the control
11325   points of the rotated derivatives@>;
11326 if ( y1==0 ) if ( x1>=0 ) goto FOUND;
11327 if ( n>0 ) { 
11328   @<Exit to |found| if an eastward direction occurs at knot |p|@>;
11329   if ( p==h ) break;
11330   };
11331 if ( (x3!=0)||(y3!=0) ) phi=mp_n_arg(mp, x3,y3);
11332 @<Exit to |found| if the curve whose derivatives are specified by
11333   |x1,x2,x3,y1,y2,y3| travels eastward at some time~|tt|@>
11334
11335 @ @<Other local variables for |find_direction_time|@>=
11336 scaled x1,x2,x3,y1,y2,y3;  /* multiples of rotated derivatives */
11337 angle theta,phi; /* angles of exit and entry at a knot */
11338 fraction t; /* temp storage */
11339
11340 @ @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples...@>=
11341 x1=right_x(p)-x_coord(p); x2=left_x(q)-right_x(p);
11342 x3=x_coord(q)-left_x(q);
11343 y1=right_y(p)-y_coord(p); y2=left_y(q)-right_y(p);
11344 y3=y_coord(q)-left_y(q);
11345 max=abs(x1);
11346 if ( abs(x2)>max ) max=abs(x2);
11347 if ( abs(x3)>max ) max=abs(x3);
11348 if ( abs(y1)>max ) max=abs(y1);
11349 if ( abs(y2)>max ) max=abs(y2);
11350 if ( abs(y3)>max ) max=abs(y3);
11351 if ( max==0 ) goto FOUND;
11352 while ( max<fraction_half ){ 
11353   max+=max; x1+=x1; x2+=x2; x3+=x3;
11354   y1+=y1; y2+=y2; y3+=y3;
11355 }
11356 t=x1; x1=mp_take_fraction(mp, x1,x)+mp_take_fraction(mp, y1,y);
11357 y1=mp_take_fraction(mp, y1,x)-mp_take_fraction(mp, t,y);
11358 t=x2; x2=mp_take_fraction(mp, x2,x)+mp_take_fraction(mp, y2,y);
11359 y2=mp_take_fraction(mp, y2,x)-mp_take_fraction(mp, t,y);
11360 t=x3; x3=mp_take_fraction(mp, x3,x)+mp_take_fraction(mp, y3,y);
11361 y3=mp_take_fraction(mp, y3,x)-mp_take_fraction(mp, t,y)
11362
11363 @ @<Exit to |found| if an eastward direction occurs at knot |p|@>=
11364 theta=mp_n_arg(mp, x1,y1);
11365 if ( theta>=0 ) if ( phi<=0 ) if ( phi>=theta-one_eighty_deg ) goto FOUND;
11366 if ( theta<=0 ) if ( phi>=0 ) if ( phi<=theta+one_eighty_deg ) goto FOUND
11367
11368 @ In this step we want to use the |crossing_point| routine to find the
11369 roots of the quadratic equation $B(y_1,y_2,y_3;t)=0$.
11370 Several complications arise: If the quadratic equation has a double root,
11371 the curve never crosses zero, and |crossing_point| will find nothing;
11372 this case occurs iff $y_1y_3=y_2^2$ and $y_1y_2<0$. If the quadratic
11373 equation has simple roots, or only one root, we may have to negate it
11374 so that $B(y_1,y_2,y_3;t)$ crosses from positive to negative at its first root.
11375 And finally, we need to do special things if $B(y_1,y_2,y_3;t)$ is
11376 identically zero.
11377
11378 @ @<Exit to |found| if the curve whose derivatives are specified by...@>=
11379 if ( x1<0 ) if ( x2<0 ) if ( x3<0 ) goto DONE;
11380 if ( mp_ab_vs_cd(mp, y1,y3,y2,y2)==0 ) {
11381   @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11382     either |goto found| or |goto done|@>;
11383 }
11384 if ( y1<=0 ) {
11385   if ( y1<0 ) { y1=-y1; y2=-y2; y3=-y3; }
11386   else if ( y2>0 ){ y2=-y2; y3=-y3; };
11387 }
11388 @<Check the places where $B(y_1,y_2,y_3;t)=0$ to see if
11389   $B(x_1,x_2,x_3;t)\ge0$@>;
11390 DONE:
11391
11392 @ The quadratic polynomial $B(y_1,y_2,y_3;t)$ begins |>=0| and has at most
11393 two roots, because we know that it isn't identically zero.
11394
11395 It must be admitted that the |crossing_point| routine is not perfectly accurate;
11396 rounding errors might cause it to find a root when $y_1y_3>y_2^2$, or to
11397 miss the roots when $y_1y_3<y_2^2$. The rotation process is itself
11398 subject to rounding errors. Yet this code optimistically tries to
11399 do the right thing.
11400
11401 @d we_found_it { tt=(t+04000) / 010000; goto FOUND; }
11402
11403 @<Check the places where $B(y_1,y_2,y_3;t)=0$...@>=
11404 t=mp_crossing_point(mp, y1,y2,y3);
11405 if ( t>fraction_one ) goto DONE;
11406 y2=t_of_the_way(y2,y3);
11407 x1=t_of_the_way(x1,x2);
11408 x2=t_of_the_way(x2,x3);
11409 x1=t_of_the_way(x1,x2);
11410 if ( x1>=0 ) we_found_it;
11411 if ( y2>0 ) y2=0;
11412 tt=t; t=mp_crossing_point(mp, 0,-y2,-y3);
11413 if ( t>fraction_one ) goto DONE;
11414 x1=t_of_the_way(x1,x2);
11415 x2=t_of_the_way(x2,x3);
11416 if ( t_of_the_way(x1,x2)>=0 ) { 
11417   t=t_of_the_way(tt,fraction_one); we_found_it;
11418 }
11419
11420 @ @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11421     either |goto found| or |goto done|@>=
11422
11423   if ( mp_ab_vs_cd(mp, y1,y2,0,0)<0 ) {
11424     t=mp_make_fraction(mp, y1,y1-y2);
11425     x1=t_of_the_way(x1,x2);
11426     x2=t_of_the_way(x2,x3);
11427     if ( t_of_the_way(x1,x2)>=0 ) we_found_it;
11428   } else if ( y3==0 ) {
11429     if ( y1==0 ) {
11430       @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|@>;
11431     } else if ( x3>=0 ) {
11432       tt=unity; goto FOUND;
11433     }
11434   }
11435   goto DONE;
11436 }
11437
11438 @ At this point we know that the derivative of |y(t)| is identically zero,
11439 and that |x1<0|; but either |x2>=0| or |x3>=0|, so there's some hope of
11440 traveling east.
11441
11442 @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|...@>=
11443
11444   t=mp_crossing_point(mp, -x1,-x2,-x3);
11445   if ( t<=fraction_one ) we_found_it;
11446   if ( mp_ab_vs_cd(mp, x1,x3,x2,x2)<=0 ) { 
11447     t=mp_make_fraction(mp, x1,x1-x2); we_found_it;
11448   }
11449 }
11450
11451 @ The intersection of two cubics can be found by an interesting variant
11452 of the general bisection scheme described in the introduction to
11453 |crossing_point|.\
11454 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)$,
11455 we wish to find a pair of times $(t_1,t_2)$ such that $w(t_1)=z(t_2)$,
11456 if an intersection exists. First we find the smallest rectangle that
11457 encloses the points $\{w_0,w_1,w_2,w_3\}$ and check that it overlaps
11458 the smallest rectangle that encloses
11459 $\{z_0,z_1,z_2,z_3\}$; if not, the cubics certainly don't intersect.
11460 But if the rectangles do overlap, we bisect the intervals, getting
11461 new cubics $w'$ and~$w''$, $z'$~and~$z''$; the intersection routine first
11462 tries for an intersection between $w'$ and~$z'$, then (if unsuccessful)
11463 between $w'$ and~$z''$, then (if still unsuccessful) between $w''$ and~$z'$,
11464 finally (if thrice unsuccessful) between $w''$ and~$z''$. After $l$~successful
11465 levels of bisection we will have determined the intersection times $t_1$
11466 and~$t_2$ to $l$~bits of accuracy.
11467
11468 \def\submin{_{\rm min}} \def\submax{_{\rm max}}
11469 As before, it is better to work with the numbers $W_k=2^l(w_k-w_{k-1})$
11470 and $Z_k=2^l(z_k-z_{k-1})$ rather than the coefficients $w_k$ and $z_k$
11471 themselves. We also need one other quantity, $\Delta=2^l(w_0-z_0)$,
11472 to determine when the enclosing rectangles overlap. Here's why:
11473 The $x$~coordinates of~$w(t)$ are between $u\submin$ and $u\submax$,
11474 and the $x$~coordinates of~$z(t)$ are between $x\submin$ and $x\submax$,
11475 if we write $w_k=(u_k,v_k)$ and $z_k=(x_k,y_k)$ and $u\submin=
11476 \min(u_0,u_1,u_2,u_3)$, etc. These intervals of $x$~coordinates
11477 overlap if and only if $u\submin\L x\submax$ and
11478 $x\submin\L u\submax$. Letting
11479 $$U\submin=\min(0,U_1,U_1+U_2,U_1+U_2+U_3),\;
11480   U\submax=\max(0,U_1,U_1+U_2,U_1+U_2+U_3),$$
11481 we have $u\submin=2^lu_0+U\submin$, etc.; the condition for overlap
11482 reduces to
11483 $$X\submin-U\submax\L 2^l(u_0-x_0)\L X\submax-U\submin.$$
11484 Thus we want to maintain the quantity $2^l(u_0-x_0)$; similarly,
11485 the quantity $2^l(v_0-y_0)$ accounts for the $y$~coordinates. The
11486 coordinates of $\Delta=2^l(w_0-z_0)$ must stay bounded as $l$ increases,
11487 because of the overlap condition; i.e., we know that $X\submin$,
11488 $X\submax$, and their relatives are bounded, hence $X\submax-
11489 U\submin$ and $X\submin-U\submax$ are bounded.
11490
11491 @ Incidentally, if the given cubics intersect more than once, the process
11492 just sketched will not necessarily find the lexicographically smallest pair
11493 $(t_1,t_2)$. The solution actually obtained will be smallest in ``shuffled
11494 order''; i.e., if $t_1=(.a_1a_2\ldots a_{16})_2$ and
11495 $t_2=(.b_1b_2\ldots b_{16})_2$, then we will minimize
11496 $a_1b_1a_2b_2\ldots a_{16}b_{16}$, not
11497 $a_1a_2\ldots a_{16}b_1b_2\ldots b_{16}$.
11498 Shuffled order agrees with lexicographic order if all pairs of solutions
11499 $(t_1,t_2)$ and $(t_1',t_2')$ have the property that $t_1<t_1'$ iff
11500 $t_2<t_2'$; but in general, lexicographic order can be quite different,
11501 and the bisection algorithm would be substantially less efficient if it were
11502 constrained by lexicographic order.
11503
11504 For example, suppose that an overlap has been found for $l=3$ and
11505 $(t_1,t_2)= (.101,.011)$ in binary, but that no overlap is produced by
11506 either of the alternatives $(.1010,.0110)$, $(.1010,.0111)$ at level~4.
11507 Then there is probably an intersection in one of the subintervals
11508 $(.1011,.011x)$; but lexicographic order would require us to explore
11509 $(.1010,.1xxx)$ and $(.1011,.00xx)$ and $(.1011,.010x)$ first. We wouldn't
11510 want to store all of the subdivision data for the second path, so the
11511 subdivisions would have to be regenerated many times. Such inefficiencies
11512 would be associated with every `1' in the binary representation of~$t_1$.
11513
11514 @ The subdivision process introduces rounding errors, hence we need to
11515 make a more liberal test for overlap. It is not hard to show that the
11516 computed values of $U_i$ differ from the truth by at most~$l$, on
11517 level~$l$, hence $U\submin$ and $U\submax$ will be at most $3l$ in error.
11518 If $\beta$ is an upper bound on the absolute error in the computed
11519 components of $\Delta=(|delx|,|dely|)$ on level~$l$, we will replace
11520 the test `$X\submin-U\submax\L|delx|$' by the more liberal test
11521 `$X\submin-U\submax\L|delx|+|tol|$', where $|tol|=6l+\beta$.
11522
11523 More accuracy is obtained if we try the algorithm first with |tol=0|;
11524 the more liberal tolerance is used only if an exact approach fails.
11525 It is convenient to do this double-take by letting `3' in the preceding
11526 paragraph be a parameter, which is first 0, then 3.
11527
11528 @<Glob...@>=
11529 unsigned int tol_step; /* either 0 or 3, usually */
11530
11531 @ We shall use an explicit stack to implement the recursive bisection
11532 method described above. The |bisect_stack| array will contain numerous 5-word
11533 packets like $(U_1,U_2,U_3,U\submin,U\submax)$, as well as 20-word packets
11534 comprising the 5-word packets for $U$, $V$, $X$, and~$Y$.
11535
11536 The following macros define the allocation of stack positions to
11537 the quantities needed for bisection-intersection.
11538
11539 @d stack_1(A) mp->bisect_stack[(A)] /* $U_1$, $V_1$, $X_1$, or $Y_1$ */
11540 @d stack_2(A) mp->bisect_stack[(A)+1] /* $U_2$, $V_2$, $X_2$, or $Y_2$ */
11541 @d stack_3(A) mp->bisect_stack[(A)+2] /* $U_3$, $V_3$, $X_3$, or $Y_3$ */
11542 @d stack_min(A) mp->bisect_stack[(A)+3]
11543   /* $U\submin$, $V\submin$, $X\submin$, or $Y\submin$ */
11544 @d stack_max(A) mp->bisect_stack[(A)+4]
11545   /* $U\submax$, $V\submax$, $X\submax$, or $Y\submax$ */
11546 @d int_packets 20 /* number of words to represent $U_k$, $V_k$, $X_k$, and $Y_k$ */
11547 @#
11548 @d u_packet(A) ((A)-5)
11549 @d v_packet(A) ((A)-10)
11550 @d x_packet(A) ((A)-15)
11551 @d y_packet(A) ((A)-20)
11552 @d l_packets (mp->bisect_ptr-int_packets)
11553 @d r_packets mp->bisect_ptr
11554 @d ul_packet u_packet(l_packets) /* base of $U'_k$ variables */
11555 @d vl_packet v_packet(l_packets) /* base of $V'_k$ variables */
11556 @d xl_packet x_packet(l_packets) /* base of $X'_k$ variables */
11557 @d yl_packet y_packet(l_packets) /* base of $Y'_k$ variables */
11558 @d ur_packet u_packet(r_packets) /* base of $U''_k$ variables */
11559 @d vr_packet v_packet(r_packets) /* base of $V''_k$ variables */
11560 @d xr_packet x_packet(r_packets) /* base of $X''_k$ variables */
11561 @d yr_packet y_packet(r_packets) /* base of $Y''_k$ variables */
11562 @#
11563 @d u1l stack_1(ul_packet) /* $U'_1$ */
11564 @d u2l stack_2(ul_packet) /* $U'_2$ */
11565 @d u3l stack_3(ul_packet) /* $U'_3$ */
11566 @d v1l stack_1(vl_packet) /* $V'_1$ */
11567 @d v2l stack_2(vl_packet) /* $V'_2$ */
11568 @d v3l stack_3(vl_packet) /* $V'_3$ */
11569 @d x1l stack_1(xl_packet) /* $X'_1$ */
11570 @d x2l stack_2(xl_packet) /* $X'_2$ */
11571 @d x3l stack_3(xl_packet) /* $X'_3$ */
11572 @d y1l stack_1(yl_packet) /* $Y'_1$ */
11573 @d y2l stack_2(yl_packet) /* $Y'_2$ */
11574 @d y3l stack_3(yl_packet) /* $Y'_3$ */
11575 @d u1r stack_1(ur_packet) /* $U''_1$ */
11576 @d u2r stack_2(ur_packet) /* $U''_2$ */
11577 @d u3r stack_3(ur_packet) /* $U''_3$ */
11578 @d v1r stack_1(vr_packet) /* $V''_1$ */
11579 @d v2r stack_2(vr_packet) /* $V''_2$ */
11580 @d v3r stack_3(vr_packet) /* $V''_3$ */
11581 @d x1r stack_1(xr_packet) /* $X''_1$ */
11582 @d x2r stack_2(xr_packet) /* $X''_2$ */
11583 @d x3r stack_3(xr_packet) /* $X''_3$ */
11584 @d y1r stack_1(yr_packet) /* $Y''_1$ */
11585 @d y2r stack_2(yr_packet) /* $Y''_2$ */
11586 @d y3r stack_3(yr_packet) /* $Y''_3$ */
11587 @#
11588 @d stack_dx mp->bisect_stack[mp->bisect_ptr] /* stacked value of |delx| */
11589 @d stack_dy mp->bisect_stack[mp->bisect_ptr+1] /* stacked value of |dely| */
11590 @d stack_tol mp->bisect_stack[mp->bisect_ptr+2] /* stacked value of |tol| */
11591 @d stack_uv mp->bisect_stack[mp->bisect_ptr+3] /* stacked value of |uv| */
11592 @d stack_xy mp->bisect_stack[mp->bisect_ptr+4] /* stacked value of |xy| */
11593 @d int_increment (int_packets+int_packets+5) /* number of stack words per level */
11594
11595 @<Glob...@>=
11596 integer *bisect_stack;
11597 unsigned int bisect_ptr;
11598
11599 @ @<Allocate or initialize ...@>=
11600 mp->bisect_stack = xmalloc((bistack_size+1),sizeof(integer));
11601
11602 @ @<Dealloc variables@>=
11603 xfree(mp->bisect_stack);
11604
11605 @ @<Check the ``constant''...@>=
11606 if ( int_packets+17*int_increment>bistack_size ) mp->bad=19;
11607
11608 @ Computation of the min and max is a tedious but fairly fast sequence of
11609 instructions; exactly four comparisons are made in each branch.
11610
11611 @d set_min_max(A) 
11612   if ( stack_1((A))<0 ) {
11613     if ( stack_3((A))>=0 ) {
11614       if ( stack_2((A))<0 ) stack_min((A))=stack_1((A))+stack_2((A));
11615       else stack_min((A))=stack_1((A));
11616       stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11617       if ( stack_max((A))<0 ) stack_max((A))=0;
11618     } else { 
11619       stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11620       if ( stack_min((A))>stack_1((A)) ) stack_min((A))=stack_1((A));
11621       stack_max((A))=stack_1((A))+stack_2((A));
11622       if ( stack_max((A))<0 ) stack_max((A))=0;
11623     }
11624   } else if ( stack_3((A))<=0 ) {
11625     if ( stack_2((A))>0 ) stack_max((A))=stack_1((A))+stack_2((A));
11626     else stack_max((A))=stack_1((A));
11627     stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11628     if ( stack_min((A))>0 ) stack_min((A))=0;
11629   } else  { 
11630     stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11631     if ( stack_max((A))<stack_1((A)) ) stack_max((A))=stack_1((A));
11632     stack_min((A))=stack_1((A))+stack_2((A));
11633     if ( stack_min((A))>0 ) stack_min((A))=0;
11634   }
11635
11636 @ It's convenient to keep the current values of $l$, $t_1$, and $t_2$ in
11637 the integer form $2^l+2^lt_1$ and $2^l+2^lt_2$. The |cubic_intersection|
11638 routine uses global variables |cur_t| and |cur_tt| for this purpose;
11639 after successful completion, |cur_t| and |cur_tt| will contain |unity|
11640 plus the |scaled| values of $t_1$ and~$t_2$.
11641
11642 The values of |cur_t| and |cur_tt| will be set to zero if |cubic_intersection|
11643 finds no intersection. The routine gives up and gives an approximate answer
11644 if it has backtracked
11645 more than 5000 times (otherwise there are cases where several minutes
11646 of fruitless computation would be possible).
11647
11648 @d max_patience 5000
11649
11650 @<Glob...@>=
11651 integer cur_t;integer cur_tt; /* controls and results of |cubic_intersection| */
11652 integer time_to_go; /* this many backtracks before giving up */
11653 integer max_t; /* maximum of $2^{l+1}$ so far achieved */
11654
11655 @ The given cubics $B(w_0,w_1,w_2,w_3;t)$ and
11656 $B(z_0,z_1,z_2,z_3;t)$ are specified in adjacent knot nodes |(p,link(p))|
11657 and |(pp,link(pp))|, respectively.
11658
11659 @c void mp_cubic_intersection (MP mp,pointer p, pointer pp) {
11660   pointer q,qq; /* |link(p)|, |link(pp)| */
11661   mp->time_to_go=max_patience; mp->max_t=2;
11662   @<Initialize for intersections at level zero@>;
11663 CONTINUE:
11664   while (1) { 
11665     if ( mp->delx-mp->tol<=stack_max(x_packet(mp->xy))-stack_min(u_packet(mp->uv)))
11666     if ( mp->delx+mp->tol>=stack_min(x_packet(mp->xy))-stack_max(u_packet(mp->uv)))
11667     if ( mp->dely-mp->tol<=stack_max(y_packet(mp->xy))-stack_min(v_packet(mp->uv)))
11668     if ( mp->dely+mp->tol>=stack_min(y_packet(mp->xy))-stack_max(v_packet(mp->uv))) 
11669     { 
11670       if ( mp->cur_t>=mp->max_t ){ 
11671         if ( mp->max_t==two ) { /* we've done 17 bisections */ 
11672            mp->cur_t=halfp(mp->cur_t+1); mp->cur_tt=halfp(mp->cur_tt+1); return;
11673         }
11674         mp->max_t+=mp->max_t; mp->appr_t=mp->cur_t; mp->appr_tt=mp->cur_tt;
11675       }
11676       @<Subdivide for a new level of intersection@>;
11677       goto CONTINUE;
11678     }
11679     if ( mp->time_to_go>0 ) {
11680       decr(mp->time_to_go);
11681     } else { 
11682       while ( mp->appr_t<unity ) { 
11683         mp->appr_t+=mp->appr_t; mp->appr_tt+=mp->appr_tt;
11684       }
11685       mp->cur_t=mp->appr_t; mp->cur_tt=mp->appr_tt; return;
11686     }
11687     @<Advance to the next pair |(cur_t,cur_tt)|@>;
11688   }
11689 }
11690
11691 @ The following variables are global, although they are used only by
11692 |cubic_intersection|, because it is necessary on some machines to
11693 split |cubic_intersection| up into two procedures.
11694
11695 @<Glob...@>=
11696 integer delx;integer dely; /* the components of $\Delta=2^l(w_0-z_0)$ */
11697 integer tol; /* bound on the uncertainly in the overlap test */
11698 unsigned int uv;
11699 unsigned int xy; /* pointers to the current packets of interest */
11700 integer three_l; /* |tol_step| times the bisection level */
11701 integer appr_t;integer appr_tt; /* best approximations known to the answers */
11702
11703 @ We shall assume that the coordinates are sufficiently non-extreme that
11704 integer overflow will not occur.
11705
11706 @<Initialize for intersections at level zero@>=
11707 q=link(p); qq=link(pp); mp->bisect_ptr=int_packets;
11708 u1r=right_x(p)-x_coord(p); u2r=left_x(q)-right_x(p);
11709 u3r=x_coord(q)-left_x(q); set_min_max(ur_packet);
11710 v1r=right_y(p)-y_coord(p); v2r=left_y(q)-right_y(p);
11711 v3r=y_coord(q)-left_y(q); set_min_max(vr_packet);
11712 x1r=right_x(pp)-x_coord(pp); x2r=left_x(qq)-right_x(pp);
11713 x3r=x_coord(qq)-left_x(qq); set_min_max(xr_packet);
11714 y1r=right_y(pp)-y_coord(pp); y2r=left_y(qq)-right_y(pp);
11715 y3r=y_coord(qq)-left_y(qq); set_min_max(yr_packet);
11716 mp->delx=x_coord(p)-x_coord(pp); mp->dely=y_coord(p)-y_coord(pp);
11717 mp->tol=0; mp->uv=r_packets; mp->xy=r_packets; 
11718 mp->three_l=0; mp->cur_t=1; mp->cur_tt=1
11719
11720 @ @<Subdivide for a new level of intersection@>=
11721 stack_dx=mp->delx; stack_dy=mp->dely; stack_tol=mp->tol; 
11722 stack_uv=mp->uv; stack_xy=mp->xy;
11723 mp->bisect_ptr=mp->bisect_ptr+int_increment;
11724 mp->cur_t+=mp->cur_t; mp->cur_tt+=mp->cur_tt;
11725 u1l=stack_1(u_packet(mp->uv)); u3r=stack_3(u_packet(mp->uv));
11726 u2l=half(u1l+stack_2(u_packet(mp->uv)));
11727 u2r=half(u3r+stack_2(u_packet(mp->uv)));
11728 u3l=half(u2l+u2r); u1r=u3l;
11729 set_min_max(ul_packet); set_min_max(ur_packet);
11730 v1l=stack_1(v_packet(mp->uv)); v3r=stack_3(v_packet(mp->uv));
11731 v2l=half(v1l+stack_2(v_packet(mp->uv)));
11732 v2r=half(v3r+stack_2(v_packet(mp->uv)));
11733 v3l=half(v2l+v2r); v1r=v3l;
11734 set_min_max(vl_packet); set_min_max(vr_packet);
11735 x1l=stack_1(x_packet(mp->xy)); x3r=stack_3(x_packet(mp->xy));
11736 x2l=half(x1l+stack_2(x_packet(mp->xy)));
11737 x2r=half(x3r+stack_2(x_packet(mp->xy)));
11738 x3l=half(x2l+x2r); x1r=x3l;
11739 set_min_max(xl_packet); set_min_max(xr_packet);
11740 y1l=stack_1(y_packet(mp->xy)); y3r=stack_3(y_packet(mp->xy));
11741 y2l=half(y1l+stack_2(y_packet(mp->xy)));
11742 y2r=half(y3r+stack_2(y_packet(mp->xy)));
11743 y3l=half(y2l+y2r); y1r=y3l;
11744 set_min_max(yl_packet); set_min_max(yr_packet);
11745 mp->uv=l_packets; mp->xy=l_packets;
11746 mp->delx+=mp->delx; mp->dely+=mp->dely;
11747 mp->tol=mp->tol-mp->three_l+mp->tol_step; 
11748 mp->tol+=mp->tol; mp->three_l=mp->three_l+mp->tol_step
11749
11750 @ @<Advance to the next pair |(cur_t,cur_tt)|@>=
11751 NOT_FOUND: 
11752 if ( odd(mp->cur_tt) ) {
11753   if ( odd(mp->cur_t) ) {
11754      @<Descend to the previous level and |goto not_found|@>;
11755   } else { 
11756     incr(mp->cur_t);
11757     mp->delx=mp->delx+stack_1(u_packet(mp->uv))+stack_2(u_packet(mp->uv))
11758       +stack_3(u_packet(mp->uv));
11759     mp->dely=mp->dely+stack_1(v_packet(mp->uv))+stack_2(v_packet(mp->uv))
11760       +stack_3(v_packet(mp->uv));
11761     mp->uv=mp->uv+int_packets; /* switch from |l_packet| to |r_packet| */
11762     decr(mp->cur_tt); mp->xy=mp->xy-int_packets; 
11763          /* switch from |r_packet| to |l_packet| */
11764     mp->delx=mp->delx+stack_1(x_packet(mp->xy))+stack_2(x_packet(mp->xy))
11765       +stack_3(x_packet(mp->xy));
11766     mp->dely=mp->dely+stack_1(y_packet(mp->xy))+stack_2(y_packet(mp->xy))
11767       +stack_3(y_packet(mp->xy));
11768   }
11769 } else { 
11770   incr(mp->cur_tt); mp->tol=mp->tol+mp->three_l;
11771   mp->delx=mp->delx-stack_1(x_packet(mp->xy))-stack_2(x_packet(mp->xy))
11772     -stack_3(x_packet(mp->xy));
11773   mp->dely=mp->dely-stack_1(y_packet(mp->xy))-stack_2(y_packet(mp->xy))
11774     -stack_3(y_packet(mp->xy));
11775   mp->xy=mp->xy+int_packets; /* switch from |l_packet| to |r_packet| */
11776 }
11777
11778 @ @<Descend to the previous level...@>=
11779
11780   mp->cur_t=halfp(mp->cur_t); mp->cur_tt=halfp(mp->cur_tt);
11781   if ( mp->cur_t==0 ) return;
11782   mp->bisect_ptr=mp->bisect_ptr-int_increment; 
11783   mp->three_l=mp->three_l-mp->tol_step;
11784   mp->delx=stack_dx; mp->dely=stack_dy; mp->tol=stack_tol; 
11785   mp->uv=stack_uv; mp->xy=stack_xy;
11786   goto NOT_FOUND;
11787 }
11788
11789 @ The |path_intersection| procedure is much simpler.
11790 It invokes |cubic_intersection| in lexicographic order until finding a
11791 pair of cubics that intersect. The final intersection times are placed in
11792 |cur_t| and~|cur_tt|.
11793
11794 @c void mp_path_intersection (MP mp,pointer h, pointer hh) {
11795   pointer p,pp; /* link registers that traverse the given paths */
11796   integer n,nn; /* integer parts of intersection times, minus |unity| */
11797   @<Change one-point paths into dead cycles@>;
11798   mp->tol_step=0;
11799   do {  
11800     n=-unity; p=h;
11801     do {  
11802       if ( right_type(p)!=mp_endpoint ) { 
11803         nn=-unity; pp=hh;
11804         do {  
11805           if ( right_type(pp)!=mp_endpoint )  { 
11806             mp_cubic_intersection(mp, p,pp);
11807             if ( mp->cur_t>0 ) { 
11808               mp->cur_t=mp->cur_t+n; mp->cur_tt=mp->cur_tt+nn; 
11809               return;
11810             }
11811           }
11812           nn=nn+unity; pp=link(pp);
11813         } while (pp!=hh);
11814       }
11815       n=n+unity; p=link(p);
11816     } while (p!=h);
11817     mp->tol_step=mp->tol_step+3;
11818   } while (mp->tol_step<=3);
11819   mp->cur_t=-unity; mp->cur_tt=-unity;
11820 }
11821
11822 @ @<Change one-point paths...@>=
11823 if ( right_type(h)==mp_endpoint ) {
11824   right_x(h)=x_coord(h); left_x(h)=x_coord(h);
11825   right_y(h)=y_coord(h); left_y(h)=y_coord(h); right_type(h)=mp_explicit;
11826 }
11827 if ( right_type(hh)==mp_endpoint ) {
11828   right_x(hh)=x_coord(hh); left_x(hh)=x_coord(hh);
11829   right_y(hh)=y_coord(hh); left_y(hh)=y_coord(hh); right_type(hh)=mp_explicit;
11830 }
11831
11832 @* \[24] Dynamic linear equations.
11833 \MP\ users define variables implicitly by stating equations that should be
11834 satisfied; the computer is supposed to be smart enough to solve those equations.
11835 And indeed, the computer tries valiantly to do so, by distinguishing five
11836 different types of numeric values:
11837
11838 \smallskip\hang
11839 |type(p)=mp_known| is the nice case, when |value(p)| is the |scaled| value
11840 of the variable whose address is~|p|.
11841
11842 \smallskip\hang
11843 |type(p)=mp_dependent| means that |value(p)| is not present, but |dep_list(p)|
11844 points to a {\sl dependency list\/} that expresses the value of variable~|p|
11845 as a |scaled| number plus a sum of independent variables with |fraction|
11846 coefficients.
11847
11848 \smallskip\hang
11849 |type(p)=mp_independent| means that |value(p)=64s+m|, where |s>0| is a ``serial
11850 number'' reflecting the time this variable was first used in an equation;
11851 also |0<=m<64|, and each dependent variable
11852 that refers to this one is actually referring to the future value of
11853 this variable times~$2^m$. (Usually |m=0|, but higher degrees of
11854 scaling are sometimes needed to keep the coefficients in dependency lists
11855 from getting too large. The value of~|m| will always be even.)
11856
11857 \smallskip\hang
11858 |type(p)=mp_numeric_type| means that variable |p| hasn't appeared in an
11859 equation before, but it has been explicitly declared to be numeric.
11860
11861 \smallskip\hang
11862 |type(p)=undefined| means that variable |p| hasn't appeared before.
11863
11864 \smallskip\noindent
11865 We have actually discussed these five types in the reverse order of their
11866 history during a computation: Once |known|, a variable never again
11867 becomes |dependent|; once |dependent|, it almost never again becomes
11868 |mp_independent|; once |mp_independent|, it never again becomes |mp_numeric_type|;
11869 and once |mp_numeric_type|, it never again becomes |undefined| (except
11870 of course when the user specifically decides to scrap the old value
11871 and start again). A backward step may, however, take place: Sometimes
11872 a |dependent| variable becomes |mp_independent| again, when one of the
11873 independent variables it depends on is reverting to |undefined|.
11874
11875
11876 The next patch detects overflow of independent-variable serial
11877 numbers. Diagnosed and patched by Thorsten Dahlheimer.
11878
11879 @d s_scale 64 /* the serial numbers are multiplied by this factor */
11880 @d max_indep_vars 0177777777 /* $2^{25}-1$ */
11881 @d max_serial_no 017777777700 /* |max_indep_vars*s_scale| */
11882 @d new_indep(A)  /* create a new independent variable */
11883   { if ( mp->serial_no==max_serial_no )
11884     mp_fatal_error(mp, "variable instance identifiers exhausted");
11885   type((A))=mp_independent; mp->serial_no=mp->serial_no+s_scale;
11886   value((A))=mp->serial_no;
11887   }
11888
11889 @<Glob...@>=
11890 integer serial_no; /* the most recent serial number, times |s_scale| */
11891
11892 @ @<Make variable |q+s| newly independent@>=new_indep(q+s)
11893
11894 @ But how are dependency lists represented? It's simple: The linear combination
11895 $\alpha_1v_1+\cdots+\alpha_kv_k+\beta$ appears in |k+1| value nodes. If
11896 |q=dep_list(p)| points to this list, and if |k>0|, then |value(q)=
11897 @t$\alpha_1$@>| (which is a |fraction|); |info(q)| points to the location
11898 of $\alpha_1$; and |link(p)| points to the dependency list
11899 $\alpha_2v_2+\cdots+\alpha_kv_k+\beta$. On the other hand if |k=0|,
11900 then |value(q)=@t$\beta$@>| (which is |scaled|) and |info(q)=null|.
11901 The independent variables $v_1$, \dots,~$v_k$ have been sorted so that
11902 they appear in decreasing order of their |value| fields (i.e., of
11903 their serial numbers). \ (It is convenient to use decreasing order,
11904 since |value(null)=0|. If the independent variables were not sorted by
11905 serial number but by some other criterion, such as their location in |mem|,
11906 the equation-solving mechanism would be too system-dependent, because
11907 the ordering can affect the computed results.)
11908
11909 The |link| field in the node that contains the constant term $\beta$ is
11910 called the {\sl final link\/} of the dependency list. \MP\ maintains
11911 a doubly-linked master list of all dependency lists, in terms of a permanently
11912 allocated node
11913 in |mem| called |dep_head|. If there are no dependencies, we have
11914 |link(dep_head)=dep_head| and |prev_dep(dep_head)=dep_head|;
11915 otherwise |link(dep_head)| points to the first dependent variable, say~|p|,
11916 and |prev_dep(p)=dep_head|. We have |type(p)=mp_dependent|, and |dep_list(p)|
11917 points to its dependency list. If the final link of that dependency list
11918 occurs in location~|q|, then |link(q)| points to the next dependent
11919 variable (say~|r|); and we have |prev_dep(r)=q|, etc.
11920
11921 @d dep_list(A) link(value_loc((A)))
11922   /* half of the |value| field in a |dependent| variable */
11923 @d prev_dep(A) info(value_loc((A)))
11924   /* the other half; makes a doubly linked list */
11925 @d dep_node_size 2 /* the number of words per dependency node */
11926
11927 @<Initialize table entries...@>= mp->serial_no=0;
11928 link(dep_head)=dep_head; prev_dep(dep_head)=dep_head;
11929 info(dep_head)=null; dep_list(dep_head)=null;
11930
11931 @ Actually the description above contains a little white lie. There's
11932 another kind of variable called |mp_proto_dependent|, which is
11933 just like a |dependent| one except that the $\alpha$ coefficients
11934 in its dependency list are |scaled| instead of being fractions.
11935 Proto-dependency lists are mixed with dependency lists in the
11936 nodes reachable from |dep_head|.
11937
11938 @ Here is a procedure that prints a dependency list in symbolic form.
11939 The second parameter should be either |dependent| or |mp_proto_dependent|,
11940 to indicate the scaling of the coefficients.
11941
11942 @<Declare subroutines for printing expressions@>=
11943 void mp_print_dependency (MP mp,pointer p, small_number t) {
11944   integer v; /* a coefficient */
11945   pointer pp,q; /* for list manipulation */
11946   pp=p;
11947   while (1) { 
11948     v=abs(value(p)); q=info(p);
11949     if ( q==null ) { /* the constant term */
11950       if ( (v!=0)||(p==pp) ) {
11951          if ( value(p)>0 ) if ( p!=pp ) mp_print_char(mp, '+');
11952          mp_print_scaled(mp, value(p));
11953       }
11954       return;
11955     }
11956     @<Print the coefficient, unless it's $\pm1.0$@>;
11957     if ( type(q)!=mp_independent ) mp_confusion(mp, "dep");
11958 @:this can't happen dep}{\quad dep@>
11959     mp_print_variable_name(mp, q); v=value(q) % s_scale;
11960     while ( v>0 ) { mp_print(mp, "*4"); v=v-2; }
11961     p=link(p);
11962   }
11963 }
11964
11965 @ @<Print the coefficient, unless it's $\pm1.0$@>=
11966 if ( value(p)<0 ) mp_print_char(mp, '-');
11967 else if ( p!=pp ) mp_print_char(mp, '+');
11968 if ( t==mp_dependent ) v=mp_round_fraction(mp, v);
11969 if ( v!=unity ) mp_print_scaled(mp, v)
11970
11971 @ The maximum absolute value of a coefficient in a given dependency list
11972 is returned by the following simple function.
11973
11974 @c fraction mp_max_coef (MP mp,pointer p) {
11975   fraction x; /* the maximum so far */
11976   x=0;
11977   while ( info(p)!=null ) {
11978     if ( abs(value(p))>x ) x=abs(value(p));
11979     p=link(p);
11980   }
11981   return x;
11982 }
11983
11984 @ One of the main operations needed on dependency lists is to add a multiple
11985 of one list to the other; we call this |p_plus_fq|, where |p| and~|q| point
11986 to dependency lists and |f| is a fraction.
11987
11988 If the coefficient of any independent variable becomes |coef_bound| or
11989 more, in absolute value, this procedure changes the type of that variable
11990 to `|independent_needing_fix|', and sets the global variable |fix_needed|
11991 to~|true|. The value of $|coef_bound|=\mu$ is chosen so that
11992 $\mu^2+\mu<8$; this means that the numbers we deal with won't
11993 get too large. (Instead of the ``optimum'' $\mu=(\sqrt{33}-1)/2\approx
11994 2.3723$, the safer value 7/3 is taken as the threshold.)
11995
11996 The changes mentioned in the preceding paragraph are actually done only if
11997 the global variable |watch_coefs| is |true|. But it usually is; in fact,
11998 it is |false| only when \MP\ is making a dependency list that will soon
11999 be equated to zero.
12000
12001 Several procedures that act on dependency lists, including |p_plus_fq|,
12002 set the global variable |dep_final| to the final (constant term) node of
12003 the dependency list that they produce.
12004
12005 @d coef_bound 04525252525 /* |fraction| approximation to 7/3 */
12006 @d independent_needing_fix 0
12007
12008 @<Glob...@>=
12009 boolean fix_needed; /* does at least one |independent| variable need scaling? */
12010 boolean watch_coefs; /* should we scale coefficients that exceed |coef_bound|? */
12011 pointer dep_final; /* location of the constant term and final link */
12012
12013 @ @<Set init...@>=
12014 mp->fix_needed=false; mp->watch_coefs=true;
12015
12016 @ The |p_plus_fq| procedure has a fourth parameter, |t|, that should be
12017 set to |mp_proto_dependent| if |p| is a proto-dependency list. In this
12018 case |f| will be |scaled|, not a |fraction|. Similarly, the fifth parameter~|tt|
12019 should be |mp_proto_dependent| if |q| is a proto-dependency list.
12020
12021 List |q| is unchanged by the operation; but list |p| is totally destroyed.
12022
12023 The final link of the dependency list or proto-dependency list returned
12024 by |p_plus_fq| is the same as the original final link of~|p|. Indeed, the
12025 constant term of the result will be located in the same |mem| location
12026 as the original constant term of~|p|.
12027
12028 Coefficients of the result are assumed to be zero if they are less than
12029 a certain threshold. This compensates for inevitable rounding errors,
12030 and tends to make more variables `|known|'. The threshold is approximately
12031 $10^{-5}$ in the case of normal dependency lists, $10^{-4}$ for
12032 proto-dependencies.
12033
12034 @d fraction_threshold 2685 /* a |fraction| coefficient less than this is zeroed */
12035 @d half_fraction_threshold 1342 /* half of |fraction_threshold| */
12036 @d scaled_threshold 8 /* a |scaled| coefficient less than this is zeroed */
12037 @d half_scaled_threshold 4 /* half of |scaled_threshold| */
12038
12039 @<Declare basic dependency-list subroutines@>=
12040 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
12041                       pointer q, small_number t, small_number tt) ;
12042
12043 @ @c
12044 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
12045                       pointer q, small_number t, small_number tt) {
12046   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
12047   pointer r,s; /* for list manipulation */
12048   integer mp_threshold; /* defines a neighborhood of zero */
12049   integer v; /* temporary register */
12050   if ( t==mp_dependent ) mp_threshold=fraction_threshold;
12051   else mp_threshold=scaled_threshold;
12052   r=temp_head; pp=info(p); qq=info(q);
12053   while (1) {
12054     if ( pp==qq ) {
12055       if ( pp==null ) {
12056        break;
12057       } else {
12058         @<Contribute a term from |p|, plus |f| times the
12059           corresponding term from |q|@>
12060       }
12061     } else if ( value(pp)<value(qq) ) {
12062       @<Contribute a term from |q|, multiplied by~|f|@>
12063     } else { 
12064      link(r)=p; r=p; p=link(p); pp=info(p);
12065     }
12066   }
12067   if ( t==mp_dependent )
12068     value(p)=mp_slow_add(mp, value(p),mp_take_fraction(mp, value(q),f));
12069   else  
12070     value(p)=mp_slow_add(mp, value(p),mp_take_scaled(mp, value(q),f));
12071   link(r)=p; mp->dep_final=p; 
12072   return link(temp_head);
12073 }
12074
12075 @ @<Contribute a term from |p|, plus |f|...@>=
12076
12077   if ( tt==mp_dependent ) v=value(p)+mp_take_fraction(mp, f,value(q));
12078   else v=value(p)+mp_take_scaled(mp, f,value(q));
12079   value(p)=v; s=p; p=link(p);
12080   if ( abs(v)<mp_threshold ) {
12081     mp_free_node(mp, s,dep_node_size);
12082   } else {
12083     if ( (abs(v)>=coef_bound)  && mp->watch_coefs ) { 
12084       type(qq)=independent_needing_fix; mp->fix_needed=true;
12085     }
12086     link(r)=s; r=s;
12087   };
12088   pp=info(p); q=link(q); qq=info(q);
12089 }
12090
12091 @ @<Contribute a term from |q|, multiplied by~|f|@>=
12092
12093   if ( tt==mp_dependent ) v=mp_take_fraction(mp, f,value(q));
12094   else v=mp_take_scaled(mp, f,value(q));
12095   if ( abs(v)>halfp(mp_threshold) ) { 
12096     s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=v;
12097     if ( (abs(v)>=coef_bound) && mp->watch_coefs ) { 
12098       type(qq)=independent_needing_fix; mp->fix_needed=true;
12099     }
12100     link(r)=s; r=s;
12101   }
12102   q=link(q); qq=info(q);
12103 }
12104
12105 @ It is convenient to have another subroutine for the special case
12106 of |p_plus_fq| when |f=1.0|. In this routine lists |p| and |q| are
12107 both of the same type~|t| (either |dependent| or |mp_proto_dependent|).
12108
12109 @c pointer mp_p_plus_q (MP mp,pointer p, pointer q, small_number t) {
12110   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
12111   pointer r,s; /* for list manipulation */
12112   integer mp_threshold; /* defines a neighborhood of zero */
12113   integer v; /* temporary register */
12114   if ( t==mp_dependent ) mp_threshold=fraction_threshold;
12115   else mp_threshold=scaled_threshold;
12116   r=temp_head; pp=info(p); qq=info(q);
12117   while (1) {
12118     if ( pp==qq ) {
12119       if ( pp==null ) {
12120         break;
12121       } else {
12122         @<Contribute a term from |p|, plus the
12123           corresponding term from |q|@>
12124       }
12125     } else if ( value(pp)<value(qq) ) {
12126       s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=value(q);
12127       q=link(q); qq=info(q); link(r)=s; r=s;
12128     } else { 
12129       link(r)=p; r=p; p=link(p); pp=info(p);
12130     }
12131   }
12132   value(p)=mp_slow_add(mp, value(p),value(q));
12133   link(r)=p; mp->dep_final=p; 
12134   return link(temp_head);
12135 }
12136
12137 @ @<Contribute a term from |p|, plus the...@>=
12138
12139   v=value(p)+value(q);
12140   value(p)=v; s=p; p=link(p); pp=info(p);
12141   if ( abs(v)<mp_threshold ) {
12142     mp_free_node(mp, s,dep_node_size);
12143   } else { 
12144     if ( (abs(v)>=coef_bound ) && mp->watch_coefs ) {
12145       type(qq)=independent_needing_fix; mp->fix_needed=true;
12146     }
12147     link(r)=s; r=s;
12148   }
12149   q=link(q); qq=info(q);
12150 }
12151
12152 @ A somewhat simpler routine will multiply a dependency list
12153 by a given constant~|v|. The constant is either a |fraction| less than
12154 |fraction_one|, or it is |scaled|. In the latter case we might be forced to
12155 convert a dependency list to a proto-dependency list.
12156 Parameters |t0| and |t1| are the list types before and after;
12157 they should agree unless |t0=mp_dependent| and |t1=mp_proto_dependent|
12158 and |v_is_scaled=true|.
12159
12160 @c pointer mp_p_times_v (MP mp,pointer p, integer v, small_number t0,
12161                          small_number t1, boolean v_is_scaled) {
12162   pointer r,s; /* for list manipulation */
12163   integer w; /* tentative coefficient */
12164   integer mp_threshold;
12165   boolean scaling_down;
12166   if ( t0!=t1 ) scaling_down=true; else scaling_down=! v_is_scaled;
12167   if ( t1==mp_dependent ) mp_threshold=half_fraction_threshold;
12168   else mp_threshold=half_scaled_threshold;
12169   r=temp_head;
12170   while ( info(p)!=null ) {    
12171     if ( scaling_down ) w=mp_take_fraction(mp, v,value(p));
12172     else w=mp_take_scaled(mp, v,value(p));
12173     if ( abs(w)<=mp_threshold ) { 
12174       s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
12175     } else {
12176       if ( abs(w)>=coef_bound ) { 
12177         mp->fix_needed=true; type(info(p))=independent_needing_fix;
12178       }
12179       link(r)=p; r=p; value(p)=w; p=link(p);
12180     }
12181   }
12182   link(r)=p;
12183   if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
12184   else value(p)=mp_take_fraction(mp, value(p),v);
12185   return link(temp_head);
12186 };
12187
12188 @ Similarly, we sometimes need to divide a dependency list
12189 by a given |scaled| constant.
12190
12191 @<Declare basic dependency-list subroutines@>=
12192 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number 
12193   t0, small_number t1) ;
12194
12195 @ @c
12196 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number 
12197   t0, small_number t1) {
12198   pointer r,s; /* for list manipulation */
12199   integer w; /* tentative coefficient */
12200   integer mp_threshold;
12201   boolean scaling_down;
12202   if ( t0!=t1 ) scaling_down=true; else scaling_down=false;
12203   if ( t1==mp_dependent ) mp_threshold=half_fraction_threshold;
12204   else mp_threshold=half_scaled_threshold;
12205   r=temp_head;
12206   while ( info( p)!=null ) {
12207     if ( scaling_down ) {
12208       if ( abs(v)<02000000 ) w=mp_make_scaled(mp, value(p),v*010000);
12209       else w=mp_make_scaled(mp, mp_round_fraction(mp, value(p)),v);
12210     } else {
12211       w=mp_make_scaled(mp, value(p),v);
12212     }
12213     if ( abs(w)<=mp_threshold ) {
12214       s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
12215     } else { 
12216       if ( abs(w)>=coef_bound ) {
12217          mp->fix_needed=true; type(info(p))=independent_needing_fix;
12218       }
12219       link(r)=p; r=p; value(p)=w; p=link(p);
12220     }
12221   }
12222   link(r)=p; value(p)=mp_make_scaled(mp, value(p),v);
12223   return link(temp_head);
12224 };
12225
12226 @ Here's another utility routine for dependency lists. When an independent
12227 variable becomes dependent, we want to remove it from all existing
12228 dependencies. The |p_with_x_becoming_q| function computes the
12229 dependency list of~|p| after variable~|x| has been replaced by~|q|.
12230
12231 This procedure has basically the same calling conventions as |p_plus_fq|:
12232 List~|q| is unchanged; list~|p| is destroyed; the constant node and the
12233 final link are inherited from~|p|; and the fourth parameter tells whether
12234 or not |p| is |mp_proto_dependent|. However, the global variable |dep_final|
12235 is not altered if |x| does not occur in list~|p|.
12236
12237 @c pointer mp_p_with_x_becoming_q (MP mp,pointer p,
12238            pointer x, pointer q, small_number t) {
12239   pointer r,s; /* for list manipulation */
12240   integer v; /* coefficient of |x| */
12241   integer sx; /* serial number of |x| */
12242   s=p; r=temp_head; sx=value(x);
12243   while ( value(info(s))>sx ) { r=s; s=link(s); };
12244   if ( info(s)!=x ) { 
12245     return p;
12246   } else { 
12247     link(temp_head)=p; link(r)=link(s); v=value(s);
12248     mp_free_node(mp, s,dep_node_size);
12249     return mp_p_plus_fq(mp, link(temp_head),v,q,t,mp_dependent);
12250   }
12251 }
12252
12253 @ Here's a simple procedure that reports an error when a variable
12254 has just received a known value that's out of the required range.
12255
12256 @<Declare basic dependency-list subroutines@>=
12257 void mp_val_too_big (MP mp,scaled x) ;
12258
12259 @ @c void mp_val_too_big (MP mp,scaled x) { 
12260   if ( mp->internal[mp_warning_check]>0 ) { 
12261     print_err("Value is too large ("); mp_print_scaled(mp, x); mp_print_char(mp, ')');
12262 @.Value is too large@>
12263     help4("The equation I just processed has given some variable")
12264       ("a value of 4096 or more. Continue and I'll try to cope")
12265       ("with that big value; but it might be dangerous.")
12266       ("(Set warningcheck:=0 to suppress this message.)");
12267     mp_error(mp);
12268   }
12269 }
12270
12271 @ When a dependent variable becomes known, the following routine
12272 removes its dependency list. Here |p| points to the variable, and
12273 |q| points to the dependency list (which is one node long).
12274
12275 @<Declare basic dependency-list subroutines@>=
12276 void mp_make_known (MP mp,pointer p, pointer q) ;
12277
12278 @ @c void mp_make_known (MP mp,pointer p, pointer q) {
12279   int t; /* the previous type */
12280   prev_dep(link(q))=prev_dep(p);
12281   link(prev_dep(p))=link(q); t=type(p);
12282   type(p)=mp_known; value(p)=value(q); mp_free_node(mp, q,dep_node_size);
12283   if ( abs(value(p))>=fraction_one ) mp_val_too_big(mp, value(p));
12284   if (( mp->internal[mp_tracing_equations]>0) && mp_interesting(mp, p) ) {
12285     mp_begin_diagnostic(mp); mp_print_nl(mp, "#### ");
12286 @:]]]\#\#\#\#_}{\.{\#\#\#\#}@>
12287     mp_print_variable_name(mp, p); 
12288     mp_print_char(mp, '='); mp_print_scaled(mp, value(p));
12289     mp_end_diagnostic(mp, false);
12290   }
12291   if (( mp->cur_exp==p ) && mp->cur_type==t ) {
12292     mp->cur_type=mp_known; mp->cur_exp=value(p);
12293     mp_free_node(mp, p,value_node_size);
12294   }
12295 }
12296
12297 @ The |fix_dependencies| routine is called into action when |fix_needed|
12298 has been triggered. The program keeps a list~|s| of independent variables
12299 whose coefficients must be divided by~4.
12300
12301 In unusual cases, this fixup process might reduce one or more coefficients
12302 to zero, so that a variable will become known more or less by default.
12303
12304 @<Declare basic dependency-list subroutines@>=
12305 void mp_fix_dependencies (MP mp);
12306
12307 @ @c void mp_fix_dependencies (MP mp) {
12308   pointer p,q,r,s,t; /* list manipulation registers */
12309   pointer x; /* an independent variable */
12310   r=link(dep_head); s=null;
12311   while ( r!=dep_head ){ 
12312     t=r;
12313     @<Run through the dependency list for variable |t|, fixing
12314       all nodes, and ending with final link~|q|@>;
12315     r=link(q);
12316     if ( q==dep_list(t) ) mp_make_known(mp, t,q);
12317   }
12318   while ( s!=null ) { 
12319     p=link(s); x=info(s); free_avail(s); s=p;
12320     type(x)=mp_independent; value(x)=value(x)+2;
12321   }
12322   mp->fix_needed=false;
12323 }
12324
12325 @ @d independent_being_fixed 1 /* this variable already appears in |s| */
12326
12327 @<Run through the dependency list for variable |t|...@>=
12328 r=value_loc(t); /* |link(r)=dep_list(t)| */
12329 while (1) { 
12330   q=link(r); x=info(q);
12331   if ( x==null ) break;
12332   if ( type(x)<=independent_being_fixed ) {
12333     if ( type(x)<independent_being_fixed ) {
12334       p=mp_get_avail(mp); link(p)=s; s=p;
12335       info(s)=x; type(x)=independent_being_fixed;
12336     }
12337     value(q)=value(q) / 4;
12338     if ( value(q)==0 ) {
12339       link(r)=link(q); mp_free_node(mp, q,dep_node_size); q=r;
12340     }
12341   }
12342   r=q;
12343 }
12344
12345
12346 @ The |new_dep| routine installs a dependency list~|p| into the value node~|q|,
12347 linking it into the list of all known dependencies. We assume that
12348 |dep_final| points to the final node of list~|p|.
12349
12350 @c void mp_new_dep (MP mp,pointer q, pointer p) {
12351   pointer r; /* what used to be the first dependency */
12352   dep_list(q)=p; prev_dep(q)=dep_head;
12353   r=link(dep_head); link(mp->dep_final)=r; prev_dep(r)=mp->dep_final;
12354   link(dep_head)=q;
12355 }
12356
12357 @ Here is one of the ways a dependency list gets started.
12358 The |const_dependency| routine produces a list that has nothing but
12359 a constant term.
12360
12361 @c pointer mp_const_dependency (MP mp, scaled v) {
12362   mp->dep_final=mp_get_node(mp, dep_node_size);
12363   value(mp->dep_final)=v; info(mp->dep_final)=null;
12364   return mp->dep_final;
12365 }
12366
12367 @ And here's a more interesting way to start a dependency list from scratch:
12368 The parameter to |single_dependency| is the location of an
12369 independent variable~|x|, and the result is the simple dependency list
12370 `|x+0|'.
12371
12372 In the unlikely event that the given independent variable has been doubled so
12373 often that we can't refer to it with a nonzero coefficient,
12374 |single_dependency| returns the simple list `0'.  This case can be
12375 recognized by testing that the returned list pointer is equal to
12376 |dep_final|.
12377
12378 @c pointer mp_single_dependency (MP mp,pointer p) {
12379   pointer q; /* the new dependency list */
12380   integer m; /* the number of doublings */
12381   m=value(p) % s_scale;
12382   if ( m>28 ) {
12383     return mp_const_dependency(mp, 0);
12384   } else { 
12385     q=mp_get_node(mp, dep_node_size);
12386     value(q)=two_to_the(28-m); info(q)=p;
12387     link(q)=mp_const_dependency(mp, 0);
12388     return q;
12389   }
12390 }
12391
12392 @ We sometimes need to make an exact copy of a dependency list.
12393
12394 @c pointer mp_copy_dep_list (MP mp,pointer p) {
12395   pointer q; /* the new dependency list */
12396   q=mp_get_node(mp, dep_node_size); mp->dep_final=q;
12397   while (1) { 
12398     info(mp->dep_final)=info(p); value(mp->dep_final)=value(p);
12399     if ( info(mp->dep_final)==null ) break;
12400     link(mp->dep_final)=mp_get_node(mp, dep_node_size);
12401     mp->dep_final=link(mp->dep_final); p=link(p);
12402   }
12403   return q;
12404 }
12405
12406 @ But how do variables normally become known? Ah, now we get to the heart of the
12407 equation-solving mechanism. The |linear_eq| procedure is given a |dependent|
12408 or |mp_proto_dependent| list,~|p|, in which at least one independent variable
12409 appears. It equates this list to zero, by choosing an independent variable
12410 with the largest coefficient and making it dependent on the others. The
12411 newly dependent variable is eliminated from all current dependencies,
12412 thereby possibly making other dependent variables known.
12413
12414 The given list |p| is, of course, totally destroyed by all this processing.
12415
12416 @c void mp_linear_eq (MP mp, pointer p, small_number t) {
12417   pointer q,r,s; /* for link manipulation */
12418   pointer x; /* the variable that loses its independence */
12419   integer n; /* the number of times |x| had been halved */
12420   integer v; /* the coefficient of |x| in list |p| */
12421   pointer prev_r; /* lags one step behind |r| */
12422   pointer final_node; /* the constant term of the new dependency list */
12423   integer w; /* a tentative coefficient */
12424    @<Find a node |q| in list |p| whose coefficient |v| is largest@>;
12425   x=info(q); n=value(x) % s_scale;
12426   @<Divide list |p| by |-v|, removing node |q|@>;
12427   if ( mp->internal[mp_tracing_equations]>0 ) {
12428     @<Display the new dependency@>;
12429   }
12430   @<Simplify all existing dependencies by substituting for |x|@>;
12431   @<Change variable |x| from |independent| to |dependent| or |known|@>;
12432   if ( mp->fix_needed ) mp_fix_dependencies(mp);
12433 }
12434
12435 @ @<Find a node |q| in list |p| whose coefficient |v| is largest@>=
12436 q=p; r=link(p); v=value(q);
12437 while ( info(r)!=null ) { 
12438   if ( abs(value(r))>abs(v) ) { q=r; v=value(r); };
12439   r=link(r);
12440 }
12441
12442 @ Here we want to change the coefficients from |scaled| to |fraction|,
12443 except in the constant term. In the common case of a trivial equation
12444 like `\.{x=3.14}', we will have |v=-fraction_one|, |q=p|, and |t=mp_dependent|.
12445
12446 @<Divide list |p| by |-v|, removing node |q|@>=
12447 s=temp_head; link(s)=p; r=p;
12448 do { 
12449   if ( r==q ) {
12450     link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12451   } else  { 
12452     w=mp_make_fraction(mp, value(r),v);
12453     if ( abs(w)<=half_fraction_threshold ) {
12454       link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12455     } else { 
12456       value(r)=-w; s=r;
12457     }
12458   }
12459   r=link(s);
12460 } while (info(r)!=null);
12461 if ( t==mp_proto_dependent ) {
12462   value(r)=-mp_make_scaled(mp, value(r),v);
12463 } else if ( v!=-fraction_one ) {
12464   value(r)=-mp_make_fraction(mp, value(r),v);
12465 }
12466 final_node=r; p=link(temp_head)
12467
12468 @ @<Display the new dependency@>=
12469 if ( mp_interesting(mp, x) ) {
12470   mp_begin_diagnostic(mp); mp_print_nl(mp, "## "); 
12471   mp_print_variable_name(mp, x);
12472 @:]]]\#\#_}{\.{\#\#}@>
12473   w=n;
12474   while ( w>0 ) { mp_print(mp, "*4"); w=w-2;  };
12475   mp_print_char(mp, '='); mp_print_dependency(mp, p,mp_dependent); 
12476   mp_end_diagnostic(mp, false);
12477 }
12478
12479 @ @<Simplify all existing dependencies by substituting for |x|@>=
12480 prev_r=dep_head; r=link(dep_head);
12481 while ( r!=dep_head ) {
12482   s=dep_list(r); q=mp_p_with_x_becoming_q(mp, s,x,p,type(r));
12483   if ( info(q)==null ) {
12484     mp_make_known(mp, r,q);
12485   } else { 
12486     dep_list(r)=q;
12487     do {  q=link(q); } while (info(q)!=null);
12488     prev_r=q;
12489   }
12490   r=link(prev_r);
12491 }
12492
12493 @ @<Change variable |x| from |independent| to |dependent| or |known|@>=
12494 if ( n>0 ) @<Divide list |p| by $2^n$@>;
12495 if ( info(p)==null ) {
12496   type(x)=mp_known;
12497   value(x)=value(p);
12498   if ( abs(value(x))>=fraction_one ) mp_val_too_big(mp, value(x));
12499   mp_free_node(mp, p,dep_node_size);
12500   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) {
12501     mp->cur_exp=value(x); mp->cur_type=mp_known;
12502     mp_free_node(mp, x,value_node_size);
12503   }
12504 } else { 
12505   type(x)=mp_dependent; mp->dep_final=final_node; mp_new_dep(mp, x,p);
12506   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) mp->cur_type=mp_dependent;
12507 }
12508
12509 @ @<Divide list |p| by $2^n$@>=
12510
12511   s=temp_head; link(temp_head)=p; r=p;
12512   do {  
12513     if ( n>30 ) w=0;
12514     else w=value(r) / two_to_the(n);
12515     if ( (abs(w)<=half_fraction_threshold)&&(info(r)!=null) ) {
12516       link(s)=link(r);
12517       mp_free_node(mp, r,dep_node_size);
12518     } else { 
12519       value(r)=w; s=r;
12520     }
12521     r=link(s);
12522   } while (info(s)!=null);
12523   p=link(temp_head);
12524 }
12525
12526 @ The |check_mem| procedure, which is used only when \MP\ is being
12527 debugged, makes sure that the current dependency lists are well formed.
12528
12529 @<Check the list of linear dependencies@>=
12530 q=dep_head; p=link(q);
12531 while ( p!=dep_head ) {
12532   if ( prev_dep(p)!=q ) {
12533     mp_print_nl(mp, "Bad PREVDEP at "); mp_print_int(mp, p);
12534 @.Bad PREVDEP...@>
12535   }
12536   p=dep_list(p);
12537   while (1) {
12538     r=info(p); q=p; p=link(q);
12539     if ( r==null ) break;
12540     if ( value(info(p))>=value(r) ) {
12541       mp_print_nl(mp, "Out of order at "); mp_print_int(mp, p);
12542 @.Out of order...@>
12543     }
12544   }
12545 }
12546
12547 @* \[25] Dynamic nonlinear equations.
12548 Variables of numeric type are maintained by the general scheme of
12549 independent, dependent, and known values that we have just studied;
12550 and the components of pair and transform variables are handled in the
12551 same way. But \MP\ also has five other types of values: \&{boolean},
12552 \&{string}, \&{pen}, \&{path}, and \&{picture}; what about them?
12553
12554 Equations are allowed between nonlinear quantities, but only in a
12555 simple form. Two variables that haven't yet been assigned values are
12556 either equal to each other, or they're not.
12557
12558 Before a boolean variable has received a value, its type is |mp_unknown_boolean|;
12559 similarly, there are variables whose type is |mp_unknown_string|, |mp_unknown_pen|,
12560 |mp_unknown_path|, and |mp_unknown_picture|. In such cases the value is either
12561 |null| (which means that no other variables are equivalent to this one), or
12562 it points to another variable of the same undefined type. The pointers in the
12563 latter case form a cycle of nodes, which we shall call a ``ring.''
12564 Rings of undefined variables may include capsules, which arise as
12565 intermediate results within expressions or as \&{expr} parameters to macros.
12566
12567 When one member of a ring receives a value, the same value is given to
12568 all the other members. In the case of paths and pictures, this implies
12569 making separate copies of a potentially large data structure; users should
12570 restrain their enthusiasm for such generality, unless they have lots and
12571 lots of memory space.
12572
12573 @ The following procedure is called when a capsule node is being
12574 added to a ring (e.g., when an unknown variable is mentioned in an expression).
12575
12576 @c pointer mp_new_ring_entry (MP mp,pointer p) {
12577   pointer q; /* the new capsule node */
12578   q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
12579   type(q)=type(p);
12580   if ( value(p)==null ) value(q)=p; else value(q)=value(p);
12581   value(p)=q;
12582   return q;
12583 }
12584
12585 @ Conversely, we might delete a capsule or a variable before it becomes known.
12586 The following procedure simply detaches a quantity from its ring,
12587 without recycling the storage.
12588
12589 @<Declare the recycling subroutines@>=
12590 void mp_ring_delete (MP mp,pointer p) {
12591   pointer q; 
12592   q=value(p);
12593   if ( q!=null ) if ( q!=p ){ 
12594     while ( value(q)!=p ) q=value(q);
12595     value(q)=value(p);
12596   }
12597 }
12598
12599 @ Eventually there might be an equation that assigns values to all of the
12600 variables in a ring. The |nonlinear_eq| subroutine does the necessary
12601 propagation of values.
12602
12603 If the parameter |flush_p| is |true|, node |p| itself needn't receive a
12604 value, it will soon be recycled.
12605
12606 @c void mp_nonlinear_eq (MP mp,integer v, pointer p, boolean flush_p) {
12607   small_number t; /* the type of ring |p| */
12608   pointer q,r; /* link manipulation registers */
12609   t=type(p)-unknown_tag; q=value(p);
12610   if ( flush_p ) type(p)=mp_vacuous; else p=q;
12611   do {  
12612     r=value(q); type(q)=t;
12613     switch (t) {
12614     case mp_boolean_type: value(q)=v; break;
12615     case mp_string_type: value(q)=v; add_str_ref(v); break;
12616     case mp_pen_type: value(q)=copy_pen(v); break;
12617     case mp_path_type: value(q)=mp_copy_path(mp, v); break;
12618     case mp_picture_type: value(q)=v; add_edge_ref(v); break;
12619     } /* there ain't no more cases */
12620     q=r;
12621   } while (q!=p);
12622 }
12623
12624 @ If two members of rings are equated, and if they have the same type,
12625 the |ring_merge| procedure is called on to make them equivalent.
12626
12627 @c void mp_ring_merge (MP mp,pointer p, pointer q) {
12628   pointer r; /* traverses one list */
12629   r=value(p);
12630   while ( r!=p ) {
12631     if ( r==q ) {
12632       @<Exclaim about a redundant equation@>;
12633       return;
12634     };
12635     r=value(r);
12636   }
12637   r=value(p); value(p)=value(q); value(q)=r;
12638 }
12639
12640 @ @<Exclaim about a redundant equation@>=
12641
12642   print_err("Redundant equation");
12643 @.Redundant equation@>
12644   help2("I already knew that this equation was true.")
12645    ("But perhaps no harm has been done; let's continue.");
12646   mp_put_get_error(mp);
12647 }
12648
12649 @* \[26] Introduction to the syntactic routines.
12650 Let's pause a moment now and try to look at the Big Picture.
12651 The \MP\ program consists of three main parts: syntactic routines,
12652 semantic routines, and output routines. The chief purpose of the
12653 syntactic routines is to deliver the user's input to the semantic routines,
12654 while parsing expressions and locating operators and operands. The
12655 semantic routines act as an interpreter responding to these operators,
12656 which may be regarded as commands. And the output routines are
12657 periodically called on to produce compact font descriptions that can be
12658 used for typesetting or for making interim proof drawings. We have
12659 discussed the basic data structures and many of the details of semantic
12660 operations, so we are good and ready to plunge into the part of \MP\ that
12661 actually controls the activities.
12662
12663 Our current goal is to come to grips with the |get_next| procedure,
12664 which is the keystone of \MP's input mechanism. Each call of |get_next|
12665 sets the value of three variables |cur_cmd|, |cur_mod|, and |cur_sym|,
12666 representing the next input token.
12667 $$\vbox{\halign{#\hfil\cr
12668   \hbox{|cur_cmd| denotes a command code from the long list of codes
12669    given earlier;}\cr
12670   \hbox{|cur_mod| denotes a modifier of the command code;}\cr
12671   \hbox{|cur_sym| is the hash address of the symbolic token that was
12672    just scanned,}\cr
12673   \hbox{\qquad or zero in the case of a numeric or string
12674    or capsule token.}\cr}}$$
12675 Underlying this external behavior of |get_next| is all the machinery
12676 necessary to convert from character files to tokens. At a given time we
12677 may be only partially finished with the reading of several files (for
12678 which \&{input} was specified), and partially finished with the expansion
12679 of some user-defined macros and/or some macro parameters, and partially
12680 finished reading some text that the user has inserted online,
12681 and so on. When reading a character file, the characters must be
12682 converted to tokens; comments and blank spaces must
12683 be removed, numeric and string tokens must be evaluated.
12684
12685 To handle these situations, which might all be present simultaneously,
12686 \MP\ uses various stacks that hold information about the incomplete
12687 activities, and there is a finite state control for each level of the
12688 input mechanism. These stacks record the current state of an implicitly
12689 recursive process, but the |get_next| procedure is not recursive.
12690
12691 @<Glob...@>=
12692 eight_bits cur_cmd; /* current command set by |get_next| */
12693 integer cur_mod; /* operand of current command */
12694 halfword cur_sym; /* hash address of current symbol */
12695
12696 @ The |print_cmd_mod| routine prints a symbolic interpretation of a
12697 command code and its modifier.
12698 It consists of a rather tedious sequence of print
12699 commands, and most of it is essentially an inverse to the |primitive|
12700 routine that enters a \MP\ primitive into |hash| and |eqtb|. Therefore almost
12701 all of this procedure appears elsewhere in the program, together with the
12702 corresponding |primitive| calls.
12703
12704 @<Declare the procedure called |print_cmd_mod|@>=
12705 void mp_print_cmd_mod (MP mp,integer c, integer m) { 
12706  switch (c) {
12707   @<Cases of |print_cmd_mod| for symbolic printing of primitives@>
12708   default: mp_print(mp, "[unknown command code!]"); break;
12709   }
12710 }
12711
12712 @ Here is a procedure that displays a given command in braces, in the
12713 user's transcript file.
12714
12715 @d show_cur_cmd_mod mp_show_cmd_mod(mp, mp->cur_cmd,mp->cur_mod)
12716
12717 @c 
12718 void mp_show_cmd_mod (MP mp,integer c, integer m) { 
12719   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
12720   mp_print_cmd_mod(mp, c,m); mp_print_char(mp, '}');
12721   mp_end_diagnostic(mp, false);
12722 }
12723
12724 @* \[27] Input stacks and states.
12725 The state of \MP's input mechanism appears in the input stack, whose
12726 entries are records with five fields, called |index|, |start|, |loc|,
12727 |limit|, and |name|. The top element of this stack is maintained in a
12728 global variable for which no subscripting needs to be done; the other
12729 elements of the stack appear in an array. Hence the stack is declared thus:
12730
12731 @<Types...@>=
12732 typedef struct {
12733   quarterword index_field;
12734   halfword start_field, loc_field, limit_field, name_field;
12735 } in_state_record;
12736
12737 @ @<Glob...@>=
12738 in_state_record *input_stack;
12739 integer input_ptr; /* first unused location of |input_stack| */
12740 integer max_in_stack; /* largest value of |input_ptr| when pushing */
12741 in_state_record cur_input; /* the ``top'' input state */
12742 int stack_size; /* maximum number of simultaneous input sources */
12743
12744 @ @<Allocate or initialize ...@>=
12745 mp->stack_size = 300;
12746 mp->input_stack = xmalloc((mp->stack_size+1),sizeof(in_state_record));
12747
12748 @ @<Dealloc variables@>=
12749 xfree(mp->input_stack);
12750
12751 @ We've already defined the special variable |loc==cur_input.loc_field|
12752 in our discussion of basic input-output routines. The other components of
12753 |cur_input| are defined in the same way:
12754
12755 @d index mp->cur_input.index_field /* reference for buffer information */
12756 @d start mp->cur_input.start_field /* starting position in |buffer| */
12757 @d limit mp->cur_input.limit_field /* end of current line in |buffer| */
12758 @d name mp->cur_input.name_field /* name of the current file */
12759
12760 @ Let's look more closely now at the five control variables
12761 (|index|,~|start|,~|loc|,~|limit|,~|name|),
12762 assuming that \MP\ is reading a line of characters that have been input
12763 from some file or from the user's terminal. There is an array called
12764 |buffer| that acts as a stack of all lines of characters that are
12765 currently being read from files, including all lines on subsidiary
12766 levels of the input stack that are not yet completed. \MP\ will return to
12767 the other lines when it is finished with the present input file.
12768
12769 (Incidentally, on a machine with byte-oriented addressing, it would be
12770 appropriate to combine |buffer| with the |str_pool| array,
12771 letting the buffer entries grow downward from the top of the string pool
12772 and checking that these two tables don't bump into each other.)
12773
12774 The line we are currently working on begins in position |start| of the
12775 buffer; the next character we are about to read is |buffer[loc]|; and
12776 |limit| is the location of the last character present. We always have
12777 |loc<=limit|. For convenience, |buffer[limit]| has been set to |"%"|, so
12778 that the end of a line is easily sensed.
12779
12780 The |name| variable is a string number that designates the name of
12781 the current file, if we are reading an ordinary text file.  Special codes
12782 |is_term..max_spec_src| indicate other sources of input text.
12783
12784 @d is_term 0 /* |name| value when reading from the terminal for normal input */
12785 @d is_read 1 /* |name| value when executing a \&{readstring} or \&{readfrom} */
12786 @d is_scantok 2 /* |name| value when reading text generated by \&{scantokens} */
12787 @d max_spec_src is_scantok
12788
12789 @ Additional information about the current line is available via the
12790 |index| variable, which counts how many lines of characters are present
12791 in the buffer below the current level. We have |index=0| when reading
12792 from the terminal and prompting the user for each line; then if the user types,
12793 e.g., `\.{input figs}', we will have |index=1| while reading
12794 the file \.{figs.mp}. However, it does not follow that |index| is the
12795 same as the input stack pointer, since many of the levels on the input
12796 stack may come from token lists and some |index| values may correspond
12797 to \.{MPX} files that are not currently on the stack.
12798
12799 The global variable |in_open| is equal to the highest |index| value counting
12800 \.{MPX} files but excluding token-list input levels.  Thus, the number of
12801 partially read lines in the buffer is |in_open+1| and we have |in_open>=index|
12802 when we are not reading a token list.
12803
12804 If we are not currently reading from the terminal,
12805 we are reading from the file variable |input_file[index]|. We use
12806 the notation |terminal_input| as a convenient abbreviation for |name=is_term|,
12807 and |cur_file| as an abbreviation for |input_file[index]|.
12808
12809 When \MP\ is not reading from the terminal, the global variable |line| contains
12810 the line number in the current file, for use in error messages. More precisely,
12811 |line| is a macro for |line_stack[index]| and the |line_stack| array gives
12812 the line number for each file in the |input_file| array.
12813
12814 When an \.{MPX} file is opened the file name is stored in the |mpx_name|
12815 array so that the name doesn't get lost when the file is temporarily removed
12816 from the input stack.
12817 Thus when |input_file[k]| is an \.{MPX} file, its name is |mpx_name[k]|
12818 and it contains translated \TeX\ pictures for |input_file[k-1]|.
12819 Since this is not an \.{MPX} file, we have
12820 $$ \hbox{|mpx_name[k-1]<=absent|}. $$
12821 This |name| field is set to |finished| when |input_file[k]| is completely
12822 read.
12823
12824 If more information about the input state is needed, it can be
12825 included in small arrays like those shown here. For example,
12826 the current page or segment number in the input file might be put
12827 into a variable |page|, that is really a macro for the current entry
12828 in `\ignorespaces|page_stack:array[0..max_in_open] of integer|\unskip'
12829 by analogy with |line_stack|.
12830 @^system dependencies@>
12831
12832 @d terminal_input (name==is_term) /* are we reading from the terminal? */
12833 @d cur_file mp->input_file[index] /* the current |void *| variable */
12834 @d line mp->line_stack[index] /* current line number in the current source file */
12835 @d in_name mp->iname_stack[index] /* a string used to construct \.{MPX} file names */
12836 @d in_area mp->iarea_stack[index] /* another string for naming \.{MPX} files */
12837 @d absent 1 /* |name_field| value for unused |mpx_in_stack| entries */
12838 @d mpx_reading (mp->mpx_name[index]>absent)
12839   /* when reading a file, is it an \.{MPX} file? */
12840 @d finished 0
12841   /* |name_field| value when the corresponding \.{MPX} file is finished */
12842
12843 @<Glob...@>=
12844 integer in_open; /* the number of lines in the buffer, less one */
12845 unsigned int open_parens; /* the number of open text files */
12846 void  * *input_file ;
12847 integer *line_stack ; /* the line number for each file */
12848 char *  *iname_stack; /* used for naming \.{MPX} files */
12849 char *  *iarea_stack; /* used for naming \.{MPX} files */
12850 halfword*mpx_name  ;
12851
12852 @ @<Allocate or ...@>=
12853 mp->input_file  = xmalloc((mp->max_in_open+1),sizeof(void *));
12854 mp->line_stack  = xmalloc((mp->max_in_open+1),sizeof(integer));
12855 mp->iname_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12856 mp->iarea_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12857 mp->mpx_name    = xmalloc((mp->max_in_open+1),sizeof(halfword));
12858 {
12859   int k;
12860   for (k=0;k<=mp->max_in_open;k++) {
12861     mp->iname_stack[k] =NULL;
12862     mp->iarea_stack[k] =NULL;
12863   }
12864 }
12865
12866 @ @<Dealloc variables@>=
12867 {
12868   int l;
12869   for (l=0;l<=mp->max_in_open;l++) {
12870     xfree(mp->iname_stack[l]);
12871     xfree(mp->iarea_stack[l]);
12872   }
12873 }
12874 xfree(mp->input_file);
12875 xfree(mp->line_stack);
12876 xfree(mp->iname_stack);
12877 xfree(mp->iarea_stack);
12878 xfree(mp->mpx_name);
12879
12880
12881 @ However, all this discussion about input state really applies only to the
12882 case that we are inputting from a file. There is another important case,
12883 namely when we are currently getting input from a token list. In this case
12884 |index>max_in_open|, and the conventions about the other state variables
12885 are different:
12886
12887 \yskip\hang|loc| is a pointer to the current node in the token list, i.e.,
12888 the node that will be read next. If |loc=null|, the token list has been
12889 fully read.
12890
12891 \yskip\hang|start| points to the first node of the token list; this node
12892 may or may not contain a reference count, depending on the type of token
12893 list involved.
12894
12895 \yskip\hang|token_type|, which takes the place of |index| in the
12896 discussion above, is a code number that explains what kind of token list
12897 is being scanned.
12898
12899 \yskip\hang|name| points to the |eqtb| address of the control sequence
12900 being expanded, if the current token list is a macro not defined by
12901 \&{vardef}. Macros defined by \&{vardef} have |name=null|; their name
12902 can be deduced by looking at their first two parameters.
12903
12904 \yskip\hang|param_start|, which takes the place of |limit|, tells where
12905 the parameters of the current macro or loop text begin in the |param_stack|.
12906
12907 \yskip\noindent The |token_type| can take several values, depending on
12908 where the current token list came from:
12909
12910 \yskip
12911 \indent|forever_text|, if the token list being scanned is the body of
12912 a \&{forever} loop;
12913
12914 \indent|loop_text|, if the token list being scanned is the body of
12915 a \&{for} or \&{forsuffixes} loop;
12916
12917 \indent|parameter|, if a \&{text} or \&{suffix} parameter is being scanned;
12918
12919 \indent|backed_up|, if the token list being scanned has been inserted as
12920 `to be read again'.
12921
12922 \indent|inserted|, if the token list being scanned has been inserted as
12923 part of error recovery;
12924
12925 \indent|macro|, if the expansion of a user-defined symbolic token is being
12926 scanned.
12927
12928 \yskip\noindent
12929 The token list begins with a reference count if and only if |token_type=
12930 macro|.
12931 @^reference counts@>
12932
12933 @d token_type index /* type of current token list */
12934 @d token_state (index>(int)mp->max_in_open) /* are we scanning a token list? */
12935 @d file_state (index<=(int)mp->max_in_open) /* are we scanning a file line? */
12936 @d param_start limit /* base of macro parameters in |param_stack| */
12937 @d forever_text (mp->max_in_open+1) /* |token_type| code for loop texts */
12938 @d loop_text (mp->max_in_open+2) /* |token_type| code for loop texts */
12939 @d parameter (mp->max_in_open+3) /* |token_type| code for parameter texts */
12940 @d backed_up (mp->max_in_open+4) /* |token_type| code for texts to be reread */
12941 @d inserted (mp->max_in_open+5) /* |token_type| code for inserted texts */
12942 @d macro (mp->max_in_open+6) /* |token_type| code for macro replacement texts */
12943
12944 @ The |param_stack| is an auxiliary array used to hold pointers to the token
12945 lists for parameters at the current level and subsidiary levels of input.
12946 This stack grows at a different rate from the others.
12947
12948 @<Glob...@>=
12949 pointer *param_stack;  /* token list pointers for parameters */
12950 integer param_ptr; /* first unused entry in |param_stack| */
12951 integer max_param_stack;  /* largest value of |param_ptr| */
12952
12953 @ @<Allocate or initialize ...@>=
12954 mp->param_stack = xmalloc((mp->param_size+1),sizeof(pointer));
12955
12956 @ @<Dealloc variables@>=
12957 xfree(mp->param_stack);
12958
12959 @ Notice that the |line| isn't valid when |token_state| is true because it
12960 depends on |index|.  If we really need to know the line number for the
12961 topmost file in the index stack we use the following function.  If a page
12962 number or other information is needed, this routine should be modified to
12963 compute it as well.
12964 @^system dependencies@>
12965
12966 @<Declare a function called |true_line|@>=
12967 integer mp_true_line (MP mp) {
12968   int k; /* an index into the input stack */
12969   if ( file_state && (name>max_spec_src) ) {
12970      return line;
12971   } else { 
12972     k=mp->input_ptr;
12973     while ((k>0) &&
12974            ((mp->input_stack[(k-1)].index_field>mp->max_in_open)||
12975             (mp->input_stack[(k-1)].name_field<=max_spec_src))) {
12976       decr(k);
12977     }
12978     return (k>0 ? mp->line_stack[(k-1)] : 0 );
12979   }
12980   return 0; 
12981 }
12982
12983 @ Thus, the ``current input state'' can be very complicated indeed; there
12984 can be many levels and each level can arise in a variety of ways. The
12985 |show_context| procedure, which is used by \MP's error-reporting routine to
12986 print out the current input state on all levels down to the most recent
12987 line of characters from an input file, illustrates most of these conventions.
12988 The global variable |file_ptr| contains the lowest level that was
12989 displayed by this procedure.
12990
12991 @<Glob...@>=
12992 integer file_ptr; /* shallowest level shown by |show_context| */
12993
12994 @ The status at each level is indicated by printing two lines, where the first
12995 line indicates what was read so far and the second line shows what remains
12996 to be read. The context is cropped, if necessary, so that the first line
12997 contains at most |half_error_line| characters, and the second contains
12998 at most |error_line|. Non-current input levels whose |token_type| is
12999 `|backed_up|' are shown only if they have not been fully read.
13000
13001 @c void mp_show_context (MP mp) { /* prints where the scanner is */
13002   int old_setting; /* saved |selector| setting */
13003   @<Local variables for formatting calculations@>
13004   mp->file_ptr=mp->input_ptr; mp->input_stack[mp->file_ptr]=mp->cur_input;
13005   /* store current state */
13006   while (1) { 
13007     mp->cur_input=mp->input_stack[mp->file_ptr]; /* enter into the context */
13008     @<Display the current context@>;
13009     if ( file_state )
13010       if ( (name>max_spec_src) || (mp->file_ptr==0) ) break;
13011     decr(mp->file_ptr);
13012   }
13013   mp->cur_input=mp->input_stack[mp->input_ptr]; /* restore original state */
13014 }
13015
13016 @ @<Display the current context@>=
13017 if ( (mp->file_ptr==mp->input_ptr) || file_state ||
13018    (token_type!=backed_up) || (loc!=null) ) {
13019     /* we omit backed-up token lists that have already been read */
13020   mp->tally=0; /* get ready to count characters */
13021   old_setting=mp->selector;
13022   if ( file_state ) {
13023     @<Print location of current line@>;
13024     @<Pseudoprint the line@>;
13025   } else { 
13026     @<Print type of token list@>;
13027     @<Pseudoprint the token list@>;
13028   }
13029   mp->selector=old_setting; /* stop pseudoprinting */
13030   @<Print two lines using the tricky pseudoprinted information@>;
13031 }
13032
13033 @ This routine should be changed, if necessary, to give the best possible
13034 indication of where the current line resides in the input file.
13035 For example, on some systems it is best to print both a page and line number.
13036 @^system dependencies@>
13037
13038 @<Print location of current line@>=
13039 if ( name>max_spec_src ) {
13040   mp_print_nl(mp, "l."); mp_print_int(mp, mp_true_line(mp));
13041 } else if ( terminal_input ) {
13042   if ( mp->file_ptr==0 ) mp_print_nl(mp, "<*>");
13043   else mp_print_nl(mp, "<insert>");
13044 } else if ( name==is_scantok ) {
13045   mp_print_nl(mp, "<scantokens>");
13046 } else {
13047   mp_print_nl(mp, "<read>");
13048 }
13049 mp_print_char(mp, ' ')
13050
13051 @ Can't use case statement here because the |token_type| is not
13052 a constant expression.
13053
13054 @<Print type of token list@>=
13055 {
13056   if(token_type==forever_text) {
13057     mp_print_nl(mp, "<forever> ");
13058   } else if (token_type==loop_text) {
13059     @<Print the current loop value@>;
13060   } else if (token_type==parameter) {
13061     mp_print_nl(mp, "<argument> "); 
13062   } else if (token_type==backed_up) { 
13063     if ( loc==null ) mp_print_nl(mp, "<recently read> ");
13064     else mp_print_nl(mp, "<to be read again> ");
13065   } else if (token_type==inserted) {
13066     mp_print_nl(mp, "<inserted text> ");
13067   } else if (token_type==macro) {
13068     mp_print_ln(mp);
13069     if ( name!=null ) mp_print_text(name);
13070     else @<Print the name of a \&{vardef}'d macro@>;
13071     mp_print(mp, "->");
13072   } else {
13073     mp_print_nl(mp, "?");/* this should never happen */
13074 @.?\relax@>
13075   }
13076 }
13077
13078 @ The parameter that corresponds to a loop text is either a token list
13079 (in the case of \&{forsuffixes}) or a ``capsule'' (in the case of \&{for}).
13080 We'll discuss capsules later; for now, all we need to know is that
13081 the |link| field in a capsule parameter is |void| and that
13082 |print_exp(p,0)| displays the value of capsule~|p| in abbreviated form.
13083
13084 @<Print the current loop value@>=
13085 { mp_print_nl(mp, "<for("); p=mp->param_stack[param_start];
13086   if ( p!=null ) {
13087     if ( link(p)==mp_void ) mp_print_exp(mp, p,0); /* we're in a \&{for} loop */
13088     else mp_show_token_list(mp, p,null,20,mp->tally);
13089   }
13090   mp_print(mp, ")> ");
13091 }
13092
13093 @ The first two parameters of a macro defined by \&{vardef} will be token
13094 lists representing the macro's prefix and ``at point.'' By putting these
13095 together, we get the macro's full name.
13096
13097 @<Print the name of a \&{vardef}'d macro@>=
13098 { p=mp->param_stack[param_start];
13099   if ( p==null ) {
13100     mp_show_token_list(mp, mp->param_stack[param_start+1],null,20,mp->tally);
13101   } else { 
13102     q=p;
13103     while ( link(q)!=null ) q=link(q);
13104     link(q)=mp->param_stack[param_start+1];
13105     mp_show_token_list(mp, p,null,20,mp->tally);
13106     link(q)=null;
13107   }
13108 }
13109
13110 @ Now it is necessary to explain a little trick. We don't want to store a long
13111 string that corresponds to a token list, because that string might take up
13112 lots of memory; and we are printing during a time when an error message is
13113 being given, so we dare not do anything that might overflow one of \MP's
13114 tables. So `pseudoprinting' is the answer: We enter a mode of printing
13115 that stores characters into a buffer of length |error_line|, where character
13116 $k+1$ is placed into \hbox{|trick_buf[k mod error_line]|} if
13117 |k<trick_count|, otherwise character |k| is dropped. Initially we set
13118 |tally:=0| and |trick_count:=1000000|; then when we reach the
13119 point where transition from line 1 to line 2 should occur, we
13120 set |first_count:=tally| and |trick_count:=@tmax@>(error_line,
13121 tally+1+error_line-half_error_line)|. At the end of the
13122 pseudoprinting, the values of |first_count|, |tally|, and
13123 |trick_count| give us all the information we need to print the two lines,
13124 and all of the necessary text is in |trick_buf|.
13125
13126 Namely, let |l| be the length of the descriptive information that appears
13127 on the first line. The length of the context information gathered for that
13128 line is |k=first_count|, and the length of the context information
13129 gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k<=h|,
13130 where |h=half_error_line|, we print |trick_buf[0..k-1]| after the
13131 descriptive information on line~1, and set |n:=l+k|; here |n| is the
13132 length of line~1. If $l+k>h$, some cropping is necessary, so we set |n:=h|
13133 and print `\.{...}' followed by
13134 $$\hbox{|trick_buf[(l+k-h+3)..k-1]|,}$$
13135 where subscripts of |trick_buf| are circular modulo |error_line|. The
13136 second line consists of |n|~spaces followed by |trick_buf[k..(k+m-1)]|,
13137 unless |n+m>error_line|; in the latter case, further cropping is done.
13138 This is easier to program than to explain.
13139
13140 @<Local variables for formatting...@>=
13141 int i; /* index into |buffer| */
13142 integer l; /* length of descriptive information on line 1 */
13143 integer m; /* context information gathered for line 2 */
13144 int n; /* length of line 1 */
13145 integer p; /* starting or ending place in |trick_buf| */
13146 integer q; /* temporary index */
13147
13148 @ The following code tells the print routines to gather
13149 the desired information.
13150
13151 @d begin_pseudoprint { 
13152   l=mp->tally; mp->tally=0; mp->selector=pseudo;
13153   mp->trick_count=1000000;
13154 }
13155 @d set_trick_count {
13156   mp->first_count=mp->tally;
13157   mp->trick_count=mp->tally+1+mp->error_line-mp->half_error_line;
13158   if ( mp->trick_count<mp->error_line ) mp->trick_count=mp->error_line;
13159 }
13160
13161 @ And the following code uses the information after it has been gathered.
13162
13163 @<Print two lines using the tricky pseudoprinted information@>=
13164 if ( mp->trick_count==1000000 ) set_trick_count;
13165   /* |set_trick_count| must be performed */
13166 if ( mp->tally<mp->trick_count ) m=mp->tally-mp->first_count;
13167 else m=mp->trick_count-mp->first_count; /* context on line 2 */
13168 if ( l+mp->first_count<=mp->half_error_line ) {
13169   p=0; n=l+mp->first_count;
13170 } else  { 
13171   mp_print(mp, "..."); p=l+mp->first_count-mp->half_error_line+3;
13172   n=mp->half_error_line;
13173 }
13174 for (q=p;q<=mp->first_count-1;q++) {
13175   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13176 }
13177 mp_print_ln(mp);
13178 for (q=1;q<=n;q++) {
13179   mp_print_char(mp, ' '); /* print |n| spaces to begin line~2 */
13180 }
13181 if ( m+n<=mp->error_line ) p=mp->first_count+m; 
13182 else p=mp->first_count+(mp->error_line-n-3);
13183 for (q=mp->first_count;q<=p-1;q++) {
13184   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13185 }
13186 if ( m+n>mp->error_line ) mp_print(mp, "...")
13187
13188 @ But the trick is distracting us from our current goal, which is to
13189 understand the input state. So let's concentrate on the data structures that
13190 are being pseudoprinted as we finish up the |show_context| procedure.
13191
13192 @<Pseudoprint the line@>=
13193 begin_pseudoprint;
13194 if ( limit>0 ) {
13195   for (i=start;i<=limit-1;i++) {
13196     if ( i==loc ) set_trick_count;
13197     mp_print_str(mp, mp->buffer[i]);
13198   }
13199 }
13200
13201 @ @<Pseudoprint the token list@>=
13202 begin_pseudoprint;
13203 if ( token_type!=macro ) mp_show_token_list(mp, start,loc,100000,0);
13204 else mp_show_macro(mp, start,loc,100000)
13205
13206 @ Here is the missing piece of |show_token_list| that is activated when the
13207 token beginning line~2 is about to be shown:
13208
13209 @<Do magic computation@>=set_trick_count
13210
13211 @* \[28] Maintaining the input stacks.
13212 The following subroutines change the input status in commonly needed ways.
13213
13214 First comes |push_input|, which stores the current state and creates a
13215 new level (having, initially, the same properties as the old).
13216
13217 @d push_input  { /* enter a new input level, save the old */
13218   if ( mp->input_ptr>mp->max_in_stack ) {
13219     mp->max_in_stack=mp->input_ptr;
13220     if ( mp->input_ptr==mp->stack_size ) {
13221       int l = (mp->stack_size+(mp->stack_size>>2));
13222       XREALLOC(mp->input_stack, l, in_state_record);
13223       mp->stack_size = l;
13224     }         
13225   }
13226   mp->input_stack[mp->input_ptr]=mp->cur_input; /* stack the record */
13227   incr(mp->input_ptr);
13228 }
13229
13230 @ And of course what goes up must come down.
13231
13232 @d pop_input { /* leave an input level, re-enter the old */
13233     decr(mp->input_ptr); mp->cur_input=mp->input_stack[mp->input_ptr];
13234   }
13235
13236 @ Here is a procedure that starts a new level of token-list input, given
13237 a token list |p| and its type |t|. If |t=macro|, the calling routine should
13238 set |name|, reset~|loc|, and increase the macro's reference count.
13239
13240 @d back_list(A) mp_begin_token_list(mp, (A),backed_up) /* backs up a simple token list */
13241
13242 @c void mp_begin_token_list (MP mp,pointer p, quarterword t)  { 
13243   push_input; start=p; token_type=t;
13244   param_start=mp->param_ptr; loc=p;
13245 }
13246
13247 @ When a token list has been fully scanned, the following computations
13248 should be done as we leave that level of input.
13249 @^inner loop@>
13250
13251 @c void mp_end_token_list (MP mp) { /* leave a token-list input level */
13252   pointer p; /* temporary register */
13253   if ( token_type>=backed_up ) { /* token list to be deleted */
13254     if ( token_type<=inserted ) { 
13255       mp_flush_token_list(mp, start); goto DONE;
13256     } else {
13257       mp_delete_mac_ref(mp, start); /* update reference count */
13258     }
13259   }
13260   while ( mp->param_ptr>param_start ) { /* parameters must be flushed */
13261     decr(mp->param_ptr);
13262     p=mp->param_stack[mp->param_ptr];
13263     if ( p!=null ) {
13264       if ( link(p)==mp_void ) { /* it's an \&{expr} parameter */
13265         mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
13266       } else {
13267         mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
13268       }
13269     }
13270   }
13271 DONE: 
13272   pop_input; check_interrupt;
13273 }
13274
13275 @ The contents of |cur_cmd,cur_mod,cur_sym| are placed into an equivalent
13276 token by the |cur_tok| routine.
13277 @^inner loop@>
13278
13279 @c @<Declare the procedure called |make_exp_copy|@>;
13280 pointer mp_cur_tok (MP mp) {
13281   pointer p; /* a new token node */
13282   small_number save_type; /* |cur_type| to be restored */
13283   integer save_exp; /* |cur_exp| to be restored */
13284   if ( mp->cur_sym==0 ) {
13285     if ( mp->cur_cmd==capsule_token ) {
13286       save_type=mp->cur_type; save_exp=mp->cur_exp;
13287       mp_make_exp_copy(mp, mp->cur_mod); p=mp_stash_cur_exp(mp); link(p)=null;
13288       mp->cur_type=save_type; mp->cur_exp=save_exp;
13289     } else { 
13290       p=mp_get_node(mp, token_node_size);
13291       value(p)=mp->cur_mod; name_type(p)=mp_token;
13292       if ( mp->cur_cmd==numeric_token ) type(p)=mp_known;
13293       else type(p)=mp_string_type;
13294     }
13295   } else { 
13296     fast_get_avail(p); info(p)=mp->cur_sym;
13297   }
13298   return p;
13299 }
13300
13301 @ Sometimes \MP\ has read too far and wants to ``unscan'' what it has
13302 seen. The |back_input| procedure takes care of this by putting the token
13303 just scanned back into the input stream, ready to be read again.
13304 If |cur_sym<>0|, the values of |cur_cmd| and |cur_mod| are irrelevant.
13305
13306 @<Declarations@>= 
13307 void mp_back_input (MP mp);
13308
13309 @ @c void mp_back_input (MP mp) {/* undoes one token of input */
13310   pointer p; /* a token list of length one */
13311   p=mp_cur_tok(mp);
13312   while ( token_state &&(loc==null) ) 
13313     mp_end_token_list(mp); /* conserve stack space */
13314   back_list(p);
13315 }
13316
13317 @ The |back_error| routine is used when we want to restore or replace an
13318 offending token just before issuing an error message.  We disable interrupts
13319 during the call of |back_input| so that the help message won't be lost.
13320
13321 @<Declarations@>=
13322 void mp_error (MP mp);
13323 void mp_back_error (MP mp);
13324
13325 @ @c void mp_back_error (MP mp) { /* back up one token and call |error| */
13326   mp->OK_to_interrupt=false; 
13327   mp_back_input(mp); 
13328   mp->OK_to_interrupt=true; mp_error(mp);
13329 }
13330 void mp_ins_error (MP mp) { /* back up one inserted token and call |error| */
13331   mp->OK_to_interrupt=false; 
13332   mp_back_input(mp); token_type=inserted;
13333   mp->OK_to_interrupt=true; mp_error(mp);
13334 }
13335
13336 @ The |begin_file_reading| procedure starts a new level of input for lines
13337 of characters to be read from a file, or as an insertion from the
13338 terminal. It does not take care of opening the file, nor does it set |loc|
13339 or |limit| or |line|.
13340 @^system dependencies@>
13341
13342 @c void mp_begin_file_reading (MP mp) { 
13343   if ( mp->in_open==mp->max_in_open ) 
13344     mp_overflow(mp, "text input levels",mp->max_in_open);
13345 @:MetaPost capacity exceeded text input levels}{\quad text input levels@>
13346   if ( mp->first==mp->buf_size ) 
13347     mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13348   incr(mp->in_open); push_input; index=mp->in_open;
13349   mp->mpx_name[index]=absent;
13350   start=mp->first;
13351   name=is_term; /* |terminal_input| is now |true| */
13352 }
13353
13354 @ Conversely, the variables must be downdated when such a level of input
13355 is finished.  Any associated \.{MPX} file must also be closed and popped
13356 off the file stack.
13357
13358 @c void mp_end_file_reading (MP mp) { 
13359   if ( mp->in_open>index ) {
13360     if ( (mp->mpx_name[mp->in_open]==absent)||(name<=max_spec_src) ) {
13361       mp_confusion(mp, "endinput");
13362 @:this can't happen endinput}{\quad endinput@>
13363     } else { 
13364       (mp->close_file)(mp->input_file[mp->in_open]); /* close an \.{MPX} file */
13365       delete_str_ref(mp->mpx_name[mp->in_open]);
13366       decr(mp->in_open);
13367     }
13368   }
13369   mp->first=start;
13370   if ( index!=mp->in_open ) mp_confusion(mp, "endinput");
13371   if ( name>max_spec_src ) {
13372     (mp->close_file)(cur_file);
13373     delete_str_ref(name);
13374     xfree(in_name); 
13375     xfree(in_area);
13376   }
13377   pop_input; decr(mp->in_open);
13378 }
13379
13380 @ Here is a function that tries to resume input from an \.{MPX} file already
13381 associated with the current input file.  It returns |false| if this doesn't
13382 work.
13383
13384 @c boolean mp_begin_mpx_reading (MP mp) { 
13385   if ( mp->in_open!=index+1 ) {
13386      return false;
13387   } else { 
13388     if ( mp->mpx_name[mp->in_open]<=absent ) mp_confusion(mp, "mpx");
13389 @:this can't happen mpx}{\quad mpx@>
13390     if ( mp->first==mp->buf_size ) 
13391       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13392     push_input; index=mp->in_open;
13393     start=mp->first;
13394     name=mp->mpx_name[mp->in_open]; add_str_ref(name);
13395     @<Put an empty line in the input buffer@>;
13396     return true;
13397   }
13398 }
13399
13400 @ This procedure temporarily stops reading an \.{MPX} file.
13401
13402 @c void mp_end_mpx_reading (MP mp) { 
13403   if ( mp->in_open!=index ) mp_confusion(mp, "mpx");
13404 @:this can't happen mpx}{\quad mpx@>
13405   if ( loc<limit ) {
13406     @<Complain that we are not at the end of a line in the \.{MPX} file@>;
13407   }
13408   mp->first=start;
13409   pop_input;
13410 }
13411
13412 @ Here we enforce a restriction that simplifies the input stacks considerably.
13413 This should not inconvenience the user because \.{MPX} files are generated
13414 by an auxiliary program called \.{DVItoMP}.
13415
13416 @ @<Complain that we are not at the end of a line in the \.{MPX} file@>=
13417
13418 print_err("`mpxbreak' must be at the end of a line");
13419 help4("This file contains picture expressions for btex...etex")
13420   ("blocks.  Such files are normally generated automatically")
13421   ("but this one seems to be messed up.  I'm going to ignore")
13422   ("the rest of this line.");
13423 mp_error(mp);
13424 }
13425
13426 @ In order to keep the stack from overflowing during a long sequence of
13427 inserted `\.{show}' commands, the following routine removes completed
13428 error-inserted lines from memory.
13429
13430 @c void mp_clear_for_error_prompt (MP mp) { 
13431   while ( file_state && terminal_input &&
13432     (mp->input_ptr>0)&&(loc==limit) ) mp_end_file_reading(mp);
13433   mp_print_ln(mp); clear_terminal;
13434 }
13435
13436 @ To get \MP's whole input mechanism going, we perform the following
13437 actions.
13438
13439 @<Initialize the input routines@>=
13440 { mp->input_ptr=0; mp->max_in_stack=0;
13441   mp->in_open=0; mp->open_parens=0; mp->max_buf_stack=0;
13442   mp->param_ptr=0; mp->max_param_stack=0;
13443   mp->first=1;
13444   start=1; index=0; line=0; name=is_term;
13445   mp->mpx_name[0]=absent;
13446   mp->force_eof=false;
13447   if ( ! mp_init_terminal(mp) ) mp_jump_out(mp);
13448   limit=mp->last; mp->first=mp->last+1; 
13449   /* |init_terminal| has set |loc| and |last| */
13450 }
13451
13452 @* \[29] Getting the next token.
13453 The heart of \MP's input mechanism is the |get_next| procedure, which
13454 we shall develop in the next few sections of the program. Perhaps we
13455 shouldn't actually call it the ``heart,'' however; it really acts as \MP's
13456 eyes and mouth, reading the source files and gobbling them up. And it also
13457 helps \MP\ to regurgitate stored token lists that are to be processed again.
13458
13459 The main duty of |get_next| is to input one token and to set |cur_cmd|
13460 and |cur_mod| to that token's command code and modifier. Furthermore, if
13461 the input token is a symbolic token, that token's |hash| address
13462 is stored in |cur_sym|; otherwise |cur_sym| is set to zero.
13463
13464 Underlying this simple description is a certain amount of complexity
13465 because of all the cases that need to be handled.
13466 However, the inner loop of |get_next| is reasonably short and fast.
13467
13468 @ Before getting into |get_next|, we need to consider a mechanism by which
13469 \MP\ helps keep errors from propagating too far. Whenever the program goes
13470 into a mode where it keeps calling |get_next| repeatedly until a certain
13471 condition is met, it sets |scanner_status| to some value other than |normal|.
13472 Then if an input file ends, or if an `\&{outer}' symbol appears,
13473 an appropriate error recovery will be possible.
13474
13475 The global variable |warning_info| helps in this error recovery by providing
13476 additional information. For example, |warning_info| might indicate the
13477 name of a macro whose replacement text is being scanned.
13478
13479 @d normal 0 /* |scanner_status| at ``quiet times'' */
13480 @d skipping 1 /* |scanner_status| when false conditional text is being skipped */
13481 @d flushing 2 /* |scanner_status| when junk after a statement is being ignored */
13482 @d absorbing 3 /* |scanner_status| when a \&{text} parameter is being scanned */
13483 @d var_defining 4 /* |scanner_status| when a \&{vardef} is being scanned */
13484 @d op_defining 5 /* |scanner_status| when a macro \&{def} is being scanned */
13485 @d loop_defining 6 /* |scanner_status| when a \&{for} loop is being scanned */
13486 @d tex_flushing 7 /* |scanner_status| when skipping \TeX\ material */
13487
13488 @<Glob...@>=
13489 integer scanner_status; /* are we scanning at high speed? */
13490 integer warning_info; /* if so, what else do we need to know,
13491     in case an error occurs? */
13492
13493 @ @<Initialize the input routines@>=
13494 mp->scanner_status=normal;
13495
13496 @ The following subroutine
13497 is called when an `\&{outer}' symbolic token has been scanned or
13498 when the end of a file has been reached. These two cases are distinguished
13499 by |cur_sym|, which is zero at the end of a file.
13500
13501 @c boolean mp_check_outer_validity (MP mp) {
13502   pointer p; /* points to inserted token list */
13503   if ( mp->scanner_status==normal ) {
13504     return true;
13505   } else if ( mp->scanner_status==tex_flushing ) {
13506     @<Check if the file has ended while flushing \TeX\ material and set the
13507       result value for |check_outer_validity|@>;
13508   } else { 
13509     mp->deletions_allowed=false;
13510     @<Back up an outer symbolic token so that it can be reread@>;
13511     if ( mp->scanner_status>skipping ) {
13512       @<Tell the user what has run away and try to recover@>;
13513     } else { 
13514       print_err("Incomplete if; all text was ignored after line ");
13515 @.Incomplete if...@>
13516       mp_print_int(mp, mp->warning_info);
13517       help3("A forbidden `outer' token occurred in skipped text.")
13518         ("This kind of error happens when you say `if...' and forget")
13519         ("the matching `fi'. I've inserted a `fi'; this might work.");
13520       if ( mp->cur_sym==0 ) 
13521         mp->help_line[2]="The file ended while I was skipping conditional text.";
13522       mp->cur_sym=frozen_fi; mp_ins_error(mp);
13523     }
13524     mp->deletions_allowed=true; 
13525         return false;
13526   }
13527 }
13528
13529 @ @<Check if the file has ended while flushing \TeX\ material and set...@>=
13530 if ( mp->cur_sym!=0 ) { 
13531    return true;
13532 } else { 
13533   mp->deletions_allowed=false;
13534   print_err("TeX mode didn't end; all text was ignored after line ");
13535   mp_print_int(mp, mp->warning_info);
13536   help2("The file ended while I was looking for the `etex' to")
13537     ("finish this TeX material.  I've inserted `etex' now.");
13538   mp->cur_sym = frozen_etex;
13539   mp_ins_error(mp);
13540   mp->deletions_allowed=true;
13541   return false;
13542 }
13543
13544 @ @<Back up an outer symbolic token so that it can be reread@>=
13545 if ( mp->cur_sym!=0 ) {
13546   p=mp_get_avail(mp); info(p)=mp->cur_sym;
13547   back_list(p); /* prepare to read the symbolic token again */
13548 }
13549
13550 @ @<Tell the user what has run away...@>=
13551
13552   mp_runaway(mp); /* print the definition-so-far */
13553   if ( mp->cur_sym==0 ) {
13554     print_err("File ended");
13555 @.File ended while scanning...@>
13556   } else { 
13557     print_err("Forbidden token found");
13558 @.Forbidden token found...@>
13559   }
13560   mp_print(mp, " while scanning ");
13561   help4("I suspect you have forgotten an `enddef',")
13562     ("causing me to read past where you wanted me to stop.")
13563     ("I'll try to recover; but if the error is serious,")
13564     ("you'd better type `E' or `X' now and fix your file.");
13565   switch (mp->scanner_status) {
13566     @<Complete the error message,
13567       and set |cur_sym| to a token that might help recover from the error@>
13568   } /* there are no other cases */
13569   mp_ins_error(mp);
13570 }
13571
13572 @ As we consider various kinds of errors, it is also appropriate to
13573 change the first line of the help message just given; |help_line[3]|
13574 points to the string that might be changed.
13575
13576 @<Complete the error message,...@>=
13577 case flushing: 
13578   mp_print(mp, "to the end of the statement");
13579   mp->help_line[3]="A previous error seems to have propagated,";
13580   mp->cur_sym=frozen_semicolon;
13581   break;
13582 case absorbing: 
13583   mp_print(mp, "a text argument");
13584   mp->help_line[3]="It seems that a right delimiter was left out,";
13585   if ( mp->warning_info==0 ) {
13586     mp->cur_sym=frozen_end_group;
13587   } else { 
13588     mp->cur_sym=frozen_right_delimiter;
13589     equiv(frozen_right_delimiter)=mp->warning_info;
13590   }
13591   break;
13592 case var_defining:
13593 case op_defining: 
13594   mp_print(mp, "the definition of ");
13595   if ( mp->scanner_status==op_defining ) 
13596      mp_print_text(mp->warning_info);
13597   else 
13598      mp_print_variable_name(mp, mp->warning_info);
13599   mp->cur_sym=frozen_end_def;
13600   break;
13601 case loop_defining: 
13602   mp_print(mp, "the text of a "); 
13603   mp_print_text(mp->warning_info);
13604   mp_print(mp, " loop");
13605   mp->help_line[3]="I suspect you have forgotten an `endfor',";
13606   mp->cur_sym=frozen_end_for;
13607   break;
13608
13609 @ The |runaway| procedure displays the first part of the text that occurred
13610 when \MP\ began its special |scanner_status|, if that text has been saved.
13611
13612 @<Declare the procedure called |runaway|@>=
13613 void mp_runaway (MP mp) { 
13614   if ( mp->scanner_status>flushing ) { 
13615      mp_print_nl(mp, "Runaway ");
13616          switch (mp->scanner_status) { 
13617          case absorbing: mp_print(mp, "text?"); break;
13618          case var_defining: 
13619      case op_defining: mp_print(mp,"definition?"); break;
13620      case loop_defining: mp_print(mp, "loop?"); break;
13621      } /* there are no other cases */
13622      mp_print_ln(mp); 
13623      mp_show_token_list(mp, link(hold_head),null,mp->error_line-10,0);
13624   }
13625 }
13626
13627 @ We need to mention a procedure that may be called by |get_next|.
13628
13629 @<Declarations@>= 
13630 void mp_firm_up_the_line (MP mp);
13631
13632 @ And now we're ready to take the plunge into |get_next| itself.
13633 Note that the behavior depends on the |scanner_status| because percent signs
13634 and double quotes need to be passed over when skipping TeX material.
13635
13636 @c 
13637 void mp_get_next (MP mp) {
13638   /* sets |cur_cmd|, |cur_mod|, |cur_sym| to next token */
13639 @^inner loop@>
13640   /*restart*/ /* go here to get the next input token */
13641   /*exit*/ /* go here when the next input token has been got */
13642   /*|common_ending|*/ /* go here to finish getting a symbolic token */
13643   /*found*/ /* go here when the end of a symbolic token has been found */
13644   /*switch*/ /* go here to branch on the class of an input character */
13645   /*|start_numeric_token|,|start_decimal_token|,|fin_numeric_token|,|done|*/
13646     /* go here at crucial stages when scanning a number */
13647   int k; /* an index into |buffer| */
13648   ASCII_code c; /* the current character in the buffer */
13649   ASCII_code class; /* its class number */
13650   integer n,f; /* registers for decimal-to-binary conversion */
13651 RESTART: 
13652   mp->cur_sym=0;
13653   if ( file_state ) {
13654     @<Input from external file; |goto restart| if no input found,
13655     or |return| if a non-symbolic token is found@>;
13656   } else {
13657     @<Input from token list; |goto restart| if end of list or
13658       if a parameter needs to be expanded,
13659       or |return| if a non-symbolic token is found@>;
13660   }
13661 COMMON_ENDING: 
13662   @<Finish getting the symbolic token in |cur_sym|;
13663    |goto restart| if it is illegal@>;
13664 }
13665
13666 @ When a symbolic token is declared to be `\&{outer}', its command code
13667 is increased by |outer_tag|.
13668 @^inner loop@>
13669
13670 @<Finish getting the symbolic token in |cur_sym|...@>=
13671 mp->cur_cmd=eq_type(mp->cur_sym); mp->cur_mod=equiv(mp->cur_sym);
13672 if ( mp->cur_cmd>=outer_tag ) {
13673   if ( mp_check_outer_validity(mp) ) 
13674     mp->cur_cmd=mp->cur_cmd-outer_tag;
13675   else 
13676     goto RESTART;
13677 }
13678
13679 @ A percent sign appears in |buffer[limit]|; this makes it unnecessary
13680 to have a special test for end-of-line.
13681 @^inner loop@>
13682
13683 @<Input from external file;...@>=
13684
13685 SWITCH: 
13686   c=mp->buffer[loc]; incr(loc); class=mp->char_class[c];
13687   switch (class) {
13688   case digit_class: goto START_NUMERIC_TOKEN; break;
13689   case period_class: 
13690     class=mp->char_class[mp->buffer[loc]];
13691     if ( class>period_class ) {
13692       goto SWITCH;
13693     } else if ( class<period_class ) { /* |class=digit_class| */
13694       n=0; goto START_DECIMAL_TOKEN;
13695     }
13696 @:. }{\..\ token@>
13697     break;
13698   case space_class: goto SWITCH; break;
13699   case percent_class: 
13700     if ( mp->scanner_status==tex_flushing ) {
13701       if ( loc<limit ) goto SWITCH;
13702     }
13703     @<Move to next line of file, or |goto restart| if there is no next line@>;
13704     check_interrupt;
13705     goto SWITCH;
13706     break;
13707   case string_class: 
13708     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13709     else @<Get a string token and |return|@>;
13710     break;
13711   case isolated_classes: 
13712     k=loc-1; goto FOUND; break;
13713   case invalid_class: 
13714     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13715     else @<Decry the invalid character and |goto restart|@>;
13716     break;
13717   default: break; /* letters, etc. */
13718   }
13719   k=loc-1;
13720   while ( mp->char_class[mp->buffer[loc]]==class ) incr(loc);
13721   goto FOUND;
13722 START_NUMERIC_TOKEN:
13723   @<Get the integer part |n| of a numeric token;
13724     set |f:=0| and |goto fin_numeric_token| if there is no decimal point@>;
13725 START_DECIMAL_TOKEN:
13726   @<Get the fraction part |f| of a numeric token@>;
13727 FIN_NUMERIC_TOKEN:
13728   @<Pack the numeric and fraction parts of a numeric token
13729     and |return|@>;
13730 FOUND: 
13731   mp->cur_sym=mp_id_lookup(mp, k,loc-k);
13732 }
13733
13734 @ We go to |restart| instead of to |SWITCH|, because |state| might equal
13735 |token_list| after the error has been dealt with
13736 (cf.\ |clear_for_error_prompt|).
13737
13738 @<Decry the invalid...@>=
13739
13740   print_err("Text line contains an invalid character");
13741 @.Text line contains...@>
13742   help2("A funny symbol that I can\'t read has just been input.")
13743     ("Continue, and I'll forget that it ever happened.");
13744   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13745   goto RESTART;
13746 }
13747
13748 @ @<Get a string token and |return|@>=
13749
13750   if ( mp->buffer[loc]=='"' ) {
13751     mp->cur_mod=rts("");
13752   } else { 
13753     k=loc; mp->buffer[limit+1]='"';
13754     do {  
13755      incr(loc);
13756     } while (mp->buffer[loc]!='"');
13757     if ( loc>limit ) {
13758       @<Decry the missing string delimiter and |goto restart|@>;
13759     }
13760     if ( loc==k+1 ) {
13761       mp->cur_mod=mp->buffer[k];
13762     } else { 
13763       str_room(loc-k);
13764       do {  
13765         append_char(mp->buffer[k]); incr(k);
13766       } while (k!=loc);
13767       mp->cur_mod=mp_make_string(mp);
13768     }
13769   }
13770   incr(loc); mp->cur_cmd=string_token; 
13771   return;
13772 }
13773
13774 @ We go to |restart| after this error message, not to |SWITCH|,
13775 because the |clear_for_error_prompt| routine might have reinstated
13776 |token_state| after |error| has finished.
13777
13778 @<Decry the missing string delimiter and |goto restart|@>=
13779
13780   loc=limit; /* the next character to be read on this line will be |"%"| */
13781   print_err("Incomplete string token has been flushed");
13782 @.Incomplete string token...@>
13783   help3("Strings should finish on the same line as they began.")
13784     ("I've deleted the partial string; you might want to")
13785     ("insert another by typing, e.g., `I\"new string\"'.");
13786   mp->deletions_allowed=false; mp_error(mp);
13787   mp->deletions_allowed=true; 
13788   goto RESTART;
13789 }
13790
13791 @ @<Get the integer part |n| of a numeric token...@>=
13792 n=c-'0';
13793 while ( mp->char_class[mp->buffer[loc]]==digit_class ) {
13794   if ( n<32768 ) n=10*n+mp->buffer[loc]-'0';
13795   incr(loc);
13796 }
13797 if ( mp->buffer[loc]=='.' ) 
13798   if ( mp->char_class[mp->buffer[loc+1]]==digit_class ) 
13799     goto DONE;
13800 f=0; 
13801 goto FIN_NUMERIC_TOKEN;
13802 DONE: incr(loc)
13803
13804 @ @<Get the fraction part |f| of a numeric token@>=
13805 k=0;
13806 do { 
13807   if ( k<17 ) { /* digits for |k>=17| cannot affect the result */
13808     mp->dig[k]=mp->buffer[loc]-'0'; incr(k);
13809   }
13810   incr(loc);
13811 } while (mp->char_class[mp->buffer[loc]]==digit_class);
13812 f=mp_round_decimals(mp, k);
13813 if ( f==unity ) {
13814   incr(n); f=0;
13815 }
13816
13817 @ @<Pack the numeric and fraction parts of a numeric token and |return|@>=
13818 if ( n<32768 ) {
13819   @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>;
13820 } else if ( mp->scanner_status!=tex_flushing ) {
13821   print_err("Enormous number has been reduced");
13822 @.Enormous number...@>
13823   help2("I can\'t handle numbers bigger than 32767.99998;")
13824     ("so I've changed your constant to that maximum amount.");
13825   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13826   mp->cur_mod=el_gordo;
13827 }
13828 mp->cur_cmd=numeric_token; return
13829
13830 @ @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>=
13831
13832   mp->cur_mod=n*unity+f;
13833   if ( mp->cur_mod>=fraction_one ) {
13834     if ( (mp->internal[mp_warning_check]>0) &&
13835          (mp->scanner_status!=tex_flushing) ) {
13836       print_err("Number is too large (");
13837       mp_print_scaled(mp, mp->cur_mod);
13838       mp_print_char(mp, ')');
13839       help3("It is at least 4096. Continue and I'll try to cope")
13840       ("with that big value; but it might be dangerous.")
13841       ("(Set warningcheck:=0 to suppress this message.)");
13842       mp_error(mp);
13843     }
13844   }
13845 }
13846
13847 @ Let's consider now what happens when |get_next| is looking at a token list.
13848 @^inner loop@>
13849
13850 @<Input from token list;...@>=
13851 if ( loc>=mp->hi_mem_min ) { /* one-word token */
13852   mp->cur_sym=info(loc); loc=link(loc); /* move to next */
13853   if ( mp->cur_sym>=expr_base ) {
13854     if ( mp->cur_sym>=suffix_base ) {
13855       @<Insert a suffix or text parameter and |goto restart|@>;
13856     } else { 
13857       mp->cur_cmd=capsule_token;
13858       mp->cur_mod=mp->param_stack[param_start+mp->cur_sym-(expr_base)];
13859       mp->cur_sym=0; return;
13860     }
13861   }
13862 } else if ( loc>null ) {
13863   @<Get a stored numeric or string or capsule token and |return|@>
13864 } else { /* we are done with this token list */
13865   mp_end_token_list(mp); goto RESTART; /* resume previous level */
13866 }
13867
13868 @ @<Insert a suffix or text parameter...@>=
13869
13870   if ( mp->cur_sym>=text_base ) mp->cur_sym=mp->cur_sym-mp->param_size;
13871   /* |param_size=text_base-suffix_base| */
13872   mp_begin_token_list(mp,
13873                       mp->param_stack[param_start+mp->cur_sym-(suffix_base)],
13874                       parameter);
13875   goto RESTART;
13876 }
13877
13878 @ @<Get a stored numeric or string or capsule token...@>=
13879
13880   if ( name_type(loc)==mp_token ) {
13881     mp->cur_mod=value(loc);
13882     if ( type(loc)==mp_known ) {
13883       mp->cur_cmd=numeric_token;
13884     } else { 
13885       mp->cur_cmd=string_token; add_str_ref(mp->cur_mod);
13886     }
13887   } else { 
13888     mp->cur_mod=loc; mp->cur_cmd=capsule_token;
13889   };
13890   loc=link(loc); return;
13891 }
13892
13893 @ All of the easy branches of |get_next| have now been taken care of.
13894 There is one more branch.
13895
13896 @<Move to next line of file, or |goto restart|...@>=
13897 if ( name>max_spec_src ) {
13898   @<Read next line of file into |buffer|, or
13899     |goto restart| if the file has ended@>;
13900 } else { 
13901   if ( mp->input_ptr>0 ) {
13902      /* text was inserted during error recovery or by \&{scantokens} */
13903     mp_end_file_reading(mp); goto RESTART; /* resume previous level */
13904   }
13905   if ( mp->selector<log_only || mp->selector>=write_file) mp_open_log_file(mp);
13906   if ( mp->interaction>mp_nonstop_mode ) {
13907     if ( limit==start ) /* previous line was empty */
13908       mp_print_nl(mp, "(Please type a command or say `end')");
13909 @.Please type...@>
13910     mp_print_ln(mp); mp->first=start;
13911     prompt_input("*"); /* input on-line into |buffer| */
13912 @.*\relax@>
13913     limit=mp->last; mp->buffer[limit]='%';
13914     mp->first=limit+1; loc=start;
13915   } else {
13916     mp_fatal_error(mp, "*** (job aborted, no legal end found)");
13917 @.job aborted@>
13918     /* nonstop mode, which is intended for overnight batch processing,
13919     never waits for on-line input */
13920   }
13921 }
13922
13923 @ The global variable |force_eof| is normally |false|; it is set |true|
13924 by an \&{endinput} command.
13925
13926 @<Glob...@>=
13927 boolean force_eof; /* should the next \&{input} be aborted early? */
13928
13929 @ We must decrement |loc| in order to leave the buffer in a valid state
13930 when an error condition causes us to |goto restart| without calling
13931 |end_file_reading|.
13932
13933 @<Read next line of file into |buffer|, or
13934   |goto restart| if the file has ended@>=
13935
13936   incr(line); mp->first=start;
13937   if ( ! mp->force_eof ) {
13938     if ( mp_input_ln(mp, cur_file ) ) /* not end of file */
13939       mp_firm_up_the_line(mp); /* this sets |limit| */
13940     else 
13941       mp->force_eof=true;
13942   };
13943   if ( mp->force_eof ) {
13944     mp->force_eof=false;
13945     decr(loc);
13946     if ( mpx_reading ) {
13947       @<Complain that the \.{MPX} file ended unexpectly; then set
13948         |cur_sym:=frozen_mpx_break| and |goto comon_ending|@>;
13949     } else { 
13950       mp_print_char(mp, ')'); decr(mp->open_parens);
13951       update_terminal; /* show user that file has been read */
13952       mp_end_file_reading(mp); /* resume previous level */
13953       if ( mp_check_outer_validity(mp) ) goto  RESTART;  
13954       else goto RESTART;
13955     }
13956   }
13957   mp->buffer[limit]='%'; mp->first=limit+1; loc=start; /* ready to read */
13958 }
13959
13960 @ We should never actually come to the end of an \.{MPX} file because such
13961 files should have an \&{mpxbreak} after the translation of the last
13962 \&{btex}$\,\ldots\,$\&{etex} block.
13963
13964 @<Complain that the \.{MPX} file ended unexpectly; then set...@>=
13965
13966   mp->mpx_name[index]=finished;
13967   print_err("mpx file ended unexpectedly");
13968   help4("The file had too few picture expressions for btex...etex")
13969     ("blocks.  Such files are normally generated automatically")
13970     ("but this one got messed up.  You might want to insert a")
13971     ("picture expression now.");
13972   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13973   mp->cur_sym=frozen_mpx_break; goto COMMON_ENDING;
13974 }
13975
13976 @ Sometimes we want to make it look as though we have just read a blank line
13977 without really doing so.
13978
13979 @<Put an empty line in the input buffer@>=
13980 mp->last=mp->first; limit=mp->last; /* simulate |input_ln| and |firm_up_the_line| */
13981 mp->buffer[limit]='%'; mp->first=limit+1; loc=start
13982
13983 @ If the user has set the |mp_pausing| parameter to some positive value,
13984 and if nonstop mode has not been selected, each line of input is displayed
13985 on the terminal and the transcript file, followed by `\.{=>}'.
13986 \MP\ waits for a response. If the response is null (i.e., if nothing is
13987 typed except perhaps a few blank spaces), the original
13988 line is accepted as it stands; otherwise the line typed is
13989 used instead of the line in the file.
13990
13991 @c void mp_firm_up_the_line (MP mp) {
13992   size_t k; /* an index into |buffer| */
13993   limit=mp->last;
13994   if ( mp->internal[mp_pausing]>0) if ( mp->interaction>mp_nonstop_mode ) {
13995     wake_up_terminal; mp_print_ln(mp);
13996     if ( start<limit ) {
13997       for (k=(size_t)start;k<=(size_t)(limit-1);k++) {
13998         mp_print_str(mp, mp->buffer[k]);
13999       } 
14000     }
14001     mp->first=limit; prompt_input("=>"); /* wait for user response */
14002 @.=>@>
14003     if ( mp->last>mp->first ) {
14004       for (k=mp->first;k<=mp->last-1;k++) { /* move line down in buffer */
14005         mp->buffer[k+start-mp->first]=mp->buffer[k];
14006       }
14007       limit=start+mp->last-mp->first;
14008     }
14009   }
14010 }
14011
14012 @* \[30] Dealing with \TeX\ material.
14013 The \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}$\,\ldots\,$\&{etex}
14014 features need to be implemented at a low level in the scanning process
14015 so that \MP\ can stay in synch with the a preprocessor that treats
14016 blocks of \TeX\ material as they occur in the input file without trying
14017 to expand \MP\ macros.  Thus we need a special version of |get_next|
14018 that does not expand macros and such but does handle \&{btex},
14019 \&{verbatimtex}, etc.
14020
14021 The special version of |get_next| is called |get_t_next|.  It works by flushing
14022 \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}\allowbreak
14023 $\,\ldots\,$\&{etex} blocks, switching to the \.{MPX} file when it sees
14024 \&{btex}, and switching back when it sees \&{mpxbreak}.
14025
14026 @d btex_code 0
14027 @d verbatim_code 1
14028
14029 @ @<Put each...@>=
14030 mp_primitive(mp, "btex",start_tex,btex_code);
14031 @:btex_}{\&{btex} primitive@>
14032 mp_primitive(mp, "verbatimtex",start_tex,verbatim_code);
14033 @:verbatimtex_}{\&{verbatimtex} primitive@>
14034 mp_primitive(mp, "etex",etex_marker,0); mp->eqtb[frozen_etex]=mp->eqtb[mp->cur_sym];
14035 @:etex_}{\&{etex} primitive@>
14036 mp_primitive(mp, "mpxbreak",mpx_break,0); mp->eqtb[frozen_mpx_break]=mp->eqtb[mp->cur_sym];
14037 @:mpx_break_}{\&{mpxbreak} primitive@>
14038
14039 @ @<Cases of |print_cmd...@>=
14040 case start_tex: if ( m==btex_code ) mp_print(mp, "btex");
14041   else mp_print(mp, "verbatimtex"); break;
14042 case etex_marker: mp_print(mp, "etex"); break;
14043 case mpx_break: mp_print(mp, "mpxbreak"); break;
14044
14045 @ Actually, |get_t_next| is a macro that avoids procedure overhead except
14046 in the unusual case where \&{btex}, \&{verbatimtex}, \&{etex}, or \&{mpxbreak}
14047 is encountered.
14048
14049 @d get_t_next {mp_get_next(mp); if ( mp->cur_cmd<=max_pre_command ) mp_t_next(mp); }
14050
14051 @<Declarations@>=
14052 void mp_start_mpx_input (MP mp);
14053
14054 @ @c 
14055 void mp_t_next (MP mp) {
14056   int old_status; /* saves the |scanner_status| */
14057   integer old_info; /* saves the |warning_info| */
14058   while ( mp->cur_cmd<=max_pre_command ) {
14059     if ( mp->cur_cmd==mpx_break ) {
14060       if ( ! file_state || (mp->mpx_name[index]==absent) ) {
14061         @<Complain about a misplaced \&{mpxbreak}@>;
14062       } else { 
14063         mp_end_mpx_reading(mp); 
14064         goto TEX_FLUSH;
14065       }
14066     } else if ( mp->cur_cmd==start_tex ) {
14067       if ( token_state || (name<=max_spec_src) ) {
14068         @<Complain that we are not reading a file@>;
14069       } else if ( mpx_reading ) {
14070         @<Complain that \.{MPX} files cannot contain \TeX\ material@>;
14071       } else if ( (mp->cur_mod!=verbatim_code)&&
14072                   (mp->mpx_name[index]!=finished) ) {
14073         if ( ! mp_begin_mpx_reading(mp) ) mp_start_mpx_input(mp);
14074       } else {
14075         goto TEX_FLUSH;
14076       }
14077     } else {
14078        @<Complain about a misplaced \&{etex}@>;
14079     }
14080     goto COMMON_ENDING;
14081   TEX_FLUSH: 
14082     @<Flush the \TeX\ material@>;
14083   COMMON_ENDING: 
14084     mp_get_next(mp);
14085   }
14086 }
14087
14088 @ We could be in the middle of an operation such as skipping false conditional
14089 text when \TeX\ material is encountered, so we must be careful to save the
14090 |scanner_status|.
14091
14092 @<Flush the \TeX\ material@>=
14093 old_status=mp->scanner_status;
14094 old_info=mp->warning_info;
14095 mp->scanner_status=tex_flushing;
14096 mp->warning_info=line;
14097 do {  mp_get_next(mp); } while (mp->cur_cmd!=etex_marker);
14098 mp->scanner_status=old_status;
14099 mp->warning_info=old_info
14100
14101 @ @<Complain that \.{MPX} files cannot contain \TeX\ material@>=
14102 { print_err("An mpx file cannot contain btex or verbatimtex blocks");
14103 help4("This file contains picture expressions for btex...etex")
14104   ("blocks.  Such files are normally generated automatically")
14105   ("but this one seems to be messed up.  I'll just keep going")
14106   ("and hope for the best.");
14107 mp_error(mp);
14108 }
14109
14110 @ @<Complain that we are not reading a file@>=
14111 { print_err("You can only use `btex' or `verbatimtex' in a file");
14112 help3("I'll have to ignore this preprocessor command because it")
14113   ("only works when there is a file to preprocess.  You might")
14114   ("want to delete everything up to the next `etex`.");
14115 mp_error(mp);
14116 }
14117
14118 @ @<Complain about a misplaced \&{mpxbreak}@>=
14119 { print_err("Misplaced mpxbreak");
14120 help2("I'll ignore this preprocessor command because it")
14121   ("doesn't belong here");
14122 mp_error(mp);
14123 }
14124
14125 @ @<Complain about a misplaced \&{etex}@>=
14126 { print_err("Extra etex will be ignored");
14127 help1("There is no btex or verbatimtex for this to match");
14128 mp_error(mp);
14129 }
14130
14131 @* \[31] Scanning macro definitions.
14132 \MP\ has a variety of ways to tuck tokens away into token lists for later
14133 use: Macros can be defined with \&{def}, \&{vardef}, \&{primarydef}, etc.;
14134 repeatable code can be defined with \&{for}, \&{forever}, \&{forsuffixes}.
14135 All such operations are handled by the routines in this part of the program.
14136
14137 The modifier part of each command code is zero for the ``ending delimiters''
14138 like \&{enddef} and \&{endfor}.
14139
14140 @d start_def 1 /* command modifier for \&{def} */
14141 @d var_def 2 /* command modifier for \&{vardef} */
14142 @d end_def 0 /* command modifier for \&{enddef} */
14143 @d start_forever 1 /* command modifier for \&{forever} */
14144 @d end_for 0 /* command modifier for \&{endfor} */
14145
14146 @<Put each...@>=
14147 mp_primitive(mp, "def",macro_def,start_def);
14148 @:def_}{\&{def} primitive@>
14149 mp_primitive(mp, "vardef",macro_def,var_def);
14150 @:var_def_}{\&{vardef} primitive@>
14151 mp_primitive(mp, "primarydef",macro_def,secondary_primary_macro);
14152 @:primary_def_}{\&{primarydef} primitive@>
14153 mp_primitive(mp, "secondarydef",macro_def,tertiary_secondary_macro);
14154 @:secondary_def_}{\&{secondarydef} primitive@>
14155 mp_primitive(mp, "tertiarydef",macro_def,expression_tertiary_macro);
14156 @:tertiary_def_}{\&{tertiarydef} primitive@>
14157 mp_primitive(mp, "enddef",macro_def,end_def); mp->eqtb[frozen_end_def]=mp->eqtb[mp->cur_sym];
14158 @:end_def_}{\&{enddef} primitive@>
14159 @#
14160 mp_primitive(mp, "for",iteration,expr_base);
14161 @:for_}{\&{for} primitive@>
14162 mp_primitive(mp, "forsuffixes",iteration,suffix_base);
14163 @:for_suffixes_}{\&{forsuffixes} primitive@>
14164 mp_primitive(mp, "forever",iteration,start_forever);
14165 @:forever_}{\&{forever} primitive@>
14166 mp_primitive(mp, "endfor",iteration,end_for); mp->eqtb[frozen_end_for]=mp->eqtb[mp->cur_sym];
14167 @:end_for_}{\&{endfor} primitive@>
14168
14169 @ @<Cases of |print_cmd...@>=
14170 case macro_def:
14171   if ( m<=var_def ) {
14172     if ( m==start_def ) mp_print(mp, "def");
14173     else if ( m<start_def ) mp_print(mp, "enddef");
14174     else mp_print(mp, "vardef");
14175   } else if ( m==secondary_primary_macro ) { 
14176     mp_print(mp, "primarydef");
14177   } else if ( m==tertiary_secondary_macro ) { 
14178     mp_print(mp, "secondarydef");
14179   } else { 
14180     mp_print(mp, "tertiarydef");
14181   }
14182   break;
14183 case iteration: 
14184   if ( m<=start_forever ) {
14185     if ( m==start_forever ) mp_print(mp, "forever"); 
14186     else mp_print(mp, "endfor");
14187   } else if ( m==expr_base ) {
14188     mp_print(mp, "for"); 
14189   } else { 
14190     mp_print(mp, "forsuffixes");
14191   }
14192   break;
14193
14194 @ Different macro-absorbing operations have different syntaxes, but they
14195 also have a lot in common. There is a list of special symbols that are to
14196 be replaced by parameter tokens; there is a special command code that
14197 ends the definition; the quotation conventions are identical.  Therefore
14198 it makes sense to have most of the work done by a single subroutine. That
14199 subroutine is called |scan_toks|.
14200
14201 The first parameter to |scan_toks| is the command code that will
14202 terminate scanning (either |macro_def|, |loop_repeat|, or |iteration|).
14203
14204 The second parameter, |subst_list|, points to a (possibly empty) list
14205 of two-word nodes whose |info| and |value| fields specify symbol tokens
14206 before and after replacement. The list will be returned to free storage
14207 by |scan_toks|.
14208
14209 The third parameter is simply appended to the token list that is built.
14210 And the final parameter tells how many of the special operations
14211 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#} are to be replaced by suffix parameters.
14212 When such parameters are present, they are called \.{(SUFFIX0)},
14213 \.{(SUFFIX1)}, and \.{(SUFFIX2)}.
14214
14215 @c pointer mp_scan_toks (MP mp,command_code terminator, pointer 
14216   subst_list, pointer tail_end, small_number suffix_count) {
14217   pointer p; /* tail of the token list being built */
14218   pointer q; /* temporary for link management */
14219   integer balance; /* left delimiters minus right delimiters */
14220   p=hold_head; balance=1; link(hold_head)=null;
14221   while (1) { 
14222     get_t_next;
14223     if ( mp->cur_sym>0 ) {
14224       @<Substitute for |cur_sym|, if it's on the |subst_list|@>;
14225       if ( mp->cur_cmd==terminator ) {
14226         @<Adjust the balance; |break| if it's zero@>;
14227       } else if ( mp->cur_cmd==macro_special ) {
14228         @<Handle quoted symbols, \.{\#\AT!}, \.{\AT!}, or \.{\AT!\#}@>;
14229       }
14230     }
14231     link(p)=mp_cur_tok(mp); p=link(p);
14232   }
14233   link(p)=tail_end; mp_flush_node_list(mp, subst_list);
14234   return link(hold_head);
14235 }
14236
14237 @ @<Substitute for |cur_sym|...@>=
14238
14239   q=subst_list;
14240   while ( q!=null ) {
14241     if ( info(q)==mp->cur_sym ) {
14242       mp->cur_sym=value(q); mp->cur_cmd=relax; break;
14243     }
14244     q=link(q);
14245   }
14246 }
14247
14248 @ @<Adjust the balance; |break| if it's zero@>=
14249 if ( mp->cur_mod>0 ) {
14250   incr(balance);
14251 } else { 
14252   decr(balance);
14253   if ( balance==0 )
14254     break;
14255 }
14256
14257 @ Four commands are intended to be used only within macro texts: \&{quote},
14258 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#}. They are variants of a single command
14259 code called |macro_special|.
14260
14261 @d quote 0 /* |macro_special| modifier for \&{quote} */
14262 @d macro_prefix 1 /* |macro_special| modifier for \.{\#\AT!} */
14263 @d macro_at 2 /* |macro_special| modifier for \.{\AT!} */
14264 @d macro_suffix 3 /* |macro_special| modifier for \.{\AT!\#} */
14265
14266 @<Put each...@>=
14267 mp_primitive(mp, "quote",macro_special,quote);
14268 @:quote_}{\&{quote} primitive@>
14269 mp_primitive(mp, "#@@",macro_special,macro_prefix);
14270 @:]]]\#\AT!_}{\.{\#\AT!} primitive@>
14271 mp_primitive(mp, "@@",macro_special,macro_at);
14272 @:]]]\AT!_}{\.{\AT!} primitive@>
14273 mp_primitive(mp, "@@#",macro_special,macro_suffix);
14274 @:]]]\AT!\#_}{\.{\AT!\#} primitive@>
14275
14276 @ @<Cases of |print_cmd...@>=
14277 case macro_special: 
14278   switch (m) {
14279   case macro_prefix: mp_print(mp, "#@@"); break;
14280   case macro_at: mp_print_char(mp, '@@'); break;
14281   case macro_suffix: mp_print(mp, "@@#"); break;
14282   default: mp_print(mp, "quote"); break;
14283   }
14284   break;
14285
14286 @ @<Handle quoted...@>=
14287
14288   if ( mp->cur_mod==quote ) { get_t_next; } 
14289   else if ( mp->cur_mod<=suffix_count ) 
14290     mp->cur_sym=suffix_base-1+mp->cur_mod;
14291 }
14292
14293 @ Here is a routine that's used whenever a token will be redefined. If
14294 the user's token is unredefinable, the `|frozen_inaccessible|' token is
14295 substituted; the latter is redefinable but essentially impossible to use,
14296 hence \MP's tables won't get fouled up.
14297
14298 @c void mp_get_symbol (MP mp) { /* sets |cur_sym| to a safe symbol */
14299 RESTART: 
14300   get_t_next;
14301   if ( (mp->cur_sym==0)||(mp->cur_sym>frozen_inaccessible) ) {
14302     print_err("Missing symbolic token inserted");
14303 @.Missing symbolic token...@>
14304     help3("Sorry: You can\'t redefine a number, string, or expr.")
14305       ("I've inserted an inaccessible symbol so that your")
14306       ("definition will be completed without mixing me up too badly.");
14307     if ( mp->cur_sym>0 )
14308       mp->help_line[2]="Sorry: You can\'t redefine my error-recovery tokens.";
14309     else if ( mp->cur_cmd==string_token ) 
14310       delete_str_ref(mp->cur_mod);
14311     mp->cur_sym=frozen_inaccessible; mp_ins_error(mp); goto RESTART;
14312   }
14313 }
14314
14315 @ Before we actually redefine a symbolic token, we need to clear away its
14316 former value, if it was a variable. The following stronger version of
14317 |get_symbol| does that.
14318
14319 @c void mp_get_clear_symbol (MP mp) { 
14320   mp_get_symbol(mp); mp_clear_symbol(mp, mp->cur_sym,false);
14321 }
14322
14323 @ Here's another little subroutine; it checks that an equals sign
14324 or assignment sign comes along at the proper place in a macro definition.
14325
14326 @c void mp_check_equals (MP mp) { 
14327   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
14328      mp_missing_err(mp, "=");
14329 @.Missing `='@>
14330     help5("The next thing in this `def' should have been `=',")
14331       ("because I've already looked at the definition heading.")
14332       ("But don't worry; I'll pretend that an equals sign")
14333       ("was present. Everything from here to `enddef'")
14334       ("will be the replacement text of this macro.");
14335     mp_back_error(mp);
14336   }
14337 }
14338
14339 @ A \&{primarydef}, \&{secondarydef}, or \&{tertiarydef} is rather easily
14340 handled now that we have |scan_toks|.  In this case there are
14341 two parameters, which will be \.{EXPR0} and \.{EXPR1} (i.e.,
14342 |expr_base| and |expr_base+1|).
14343
14344 @c void mp_make_op_def (MP mp) {
14345   command_code m; /* the type of definition */
14346   pointer p,q,r; /* for list manipulation */
14347   m=mp->cur_mod;
14348   mp_get_symbol(mp); q=mp_get_node(mp, token_node_size);
14349   info(q)=mp->cur_sym; value(q)=expr_base;
14350   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym;
14351   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
14352   info(p)=mp->cur_sym; value(p)=expr_base+1; link(p)=q;
14353   get_t_next; mp_check_equals(mp);
14354   mp->scanner_status=op_defining; q=mp_get_avail(mp); ref_count(q)=null;
14355   r=mp_get_avail(mp); link(q)=r; info(r)=general_macro;
14356   link(r)=mp_scan_toks(mp, macro_def,p,null,0);
14357   mp->scanner_status=normal; eq_type(mp->warning_info)=m;
14358   equiv(mp->warning_info)=q; mp_get_x_next(mp);
14359 }
14360
14361 @ Parameters to macros are introduced by the keywords \&{expr},
14362 \&{suffix}, \&{text}, \&{primary}, \&{secondary}, and \&{tertiary}.
14363
14364 @<Put each...@>=
14365 mp_primitive(mp, "expr",param_type,expr_base);
14366 @:expr_}{\&{expr} primitive@>
14367 mp_primitive(mp, "suffix",param_type,suffix_base);
14368 @:suffix_}{\&{suffix} primitive@>
14369 mp_primitive(mp, "text",param_type,text_base);
14370 @:text_}{\&{text} primitive@>
14371 mp_primitive(mp, "primary",param_type,primary_macro);
14372 @:primary_}{\&{primary} primitive@>
14373 mp_primitive(mp, "secondary",param_type,secondary_macro);
14374 @:secondary_}{\&{secondary} primitive@>
14375 mp_primitive(mp, "tertiary",param_type,tertiary_macro);
14376 @:tertiary_}{\&{tertiary} primitive@>
14377
14378 @ @<Cases of |print_cmd...@>=
14379 case param_type:
14380   if ( m>=expr_base ) {
14381     if ( m==expr_base ) mp_print(mp, "expr");
14382     else if ( m==suffix_base ) mp_print(mp, "suffix");
14383     else mp_print(mp, "text");
14384   } else if ( m<secondary_macro ) {
14385     mp_print(mp, "primary");
14386   } else if ( m==secondary_macro ) {
14387     mp_print(mp, "secondary");
14388   } else {
14389     mp_print(mp, "tertiary");
14390   }
14391   break;
14392
14393 @ Let's turn next to the more complex processing associated with \&{def}
14394 and \&{vardef}. When the following procedure is called, |cur_mod|
14395 should be either |start_def| or |var_def|.
14396
14397 @c @<Declare the procedure called |check_delimiter|@>;
14398 @<Declare the function called |scan_declared_variable|@>;
14399 void mp_scan_def (MP mp) {
14400   int m; /* the type of definition */
14401   int n; /* the number of special suffix parameters */
14402   int k; /* the total number of parameters */
14403   int c; /* the kind of macro we're defining */
14404   pointer r; /* parameter-substitution list */
14405   pointer q; /* tail of the macro token list */
14406   pointer p; /* temporary storage */
14407   halfword base; /* |expr_base|, |suffix_base|, or |text_base| */
14408   pointer l_delim,r_delim; /* matching delimiters */
14409   m=mp->cur_mod; c=general_macro; link(hold_head)=null;
14410   q=mp_get_avail(mp); ref_count(q)=null; r=null;
14411   @<Scan the token or variable to be defined;
14412     set |n|, |scanner_status|, and |warning_info|@>;
14413   k=n;
14414   if ( mp->cur_cmd==left_delimiter ) {
14415     @<Absorb delimited parameters, putting them into lists |q| and |r|@>;
14416   }
14417   if ( mp->cur_cmd==param_type ) {
14418     @<Absorb undelimited parameters, putting them into list |r|@>;
14419   }
14420   mp_check_equals(mp);
14421   p=mp_get_avail(mp); info(p)=c; link(q)=p;
14422   @<Attach the replacement text to the tail of node |p|@>;
14423   mp->scanner_status=normal; mp_get_x_next(mp);
14424 }
14425
14426 @ We don't put `|frozen_end_group|' into the replacement text of
14427 a \&{vardef}, because the user may want to redefine `\.{endgroup}'.
14428
14429 @<Attach the replacement text to the tail of node |p|@>=
14430 if ( m==start_def ) {
14431   link(p)=mp_scan_toks(mp, macro_def,r,null,n);
14432 } else { 
14433   q=mp_get_avail(mp); info(q)=mp->bg_loc; link(p)=q;
14434   p=mp_get_avail(mp); info(p)=mp->eg_loc;
14435   link(q)=mp_scan_toks(mp, macro_def,r,p,n);
14436 }
14437 if ( mp->warning_info==bad_vardef ) 
14438   mp_flush_token_list(mp, value(bad_vardef))
14439
14440 @ @<Glob...@>=
14441 int bg_loc;
14442 int eg_loc; /* hash addresses of `\.{begingroup}' and `\.{endgroup}' */
14443
14444 @ @<Scan the token or variable to be defined;...@>=
14445 if ( m==start_def ) {
14446   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym; get_t_next;
14447   mp->scanner_status=op_defining; n=0;
14448   eq_type(mp->warning_info)=defined_macro; equiv(mp->warning_info)=q;
14449 } else { 
14450   p=mp_scan_declared_variable(mp);
14451   mp_flush_variable(mp, equiv(info(p)),link(p),true);
14452   mp->warning_info=mp_find_variable(mp, p); mp_flush_list(mp, p);
14453   if ( mp->warning_info==null ) @<Change to `\.{a bad variable}'@>;
14454   mp->scanner_status=var_defining; n=2;
14455   if ( mp->cur_cmd==macro_special ) if ( mp->cur_mod==macro_suffix ) {/* \.{\AT!\#} */
14456     n=3; get_t_next;
14457   }
14458   type(mp->warning_info)=mp_unsuffixed_macro-2+n; value(mp->warning_info)=q;
14459 } /* |mp_suffixed_macro=mp_unsuffixed_macro+1| */
14460
14461 @ @<Change to `\.{a bad variable}'@>=
14462
14463   print_err("This variable already starts with a macro");
14464 @.This variable already...@>
14465   help2("After `vardef a' you can\'t say `vardef a.b'.")
14466     ("So I'll have to discard this definition.");
14467   mp_error(mp); mp->warning_info=bad_vardef;
14468 }
14469
14470 @ @<Initialize table entries...@>=
14471 name_type(bad_vardef)=mp_root; link(bad_vardef)=frozen_bad_vardef;
14472 equiv(frozen_bad_vardef)=bad_vardef; eq_type(frozen_bad_vardef)=tag_token;
14473
14474 @ @<Absorb delimited parameters, putting them into lists |q| and |r|@>=
14475 do {  
14476   l_delim=mp->cur_sym; r_delim=mp->cur_mod; get_t_next;
14477   if ( (mp->cur_cmd==param_type)&&(mp->cur_mod>=expr_base) ) {
14478    base=mp->cur_mod;
14479   } else { 
14480     print_err("Missing parameter type; `expr' will be assumed");
14481 @.Missing parameter type@>
14482     help1("You should've had `expr' or `suffix' or `text' here.");
14483     mp_back_error(mp); base=expr_base;
14484   }
14485   @<Absorb parameter tokens for type |base|@>;
14486   mp_check_delimiter(mp, l_delim,r_delim);
14487   get_t_next;
14488 } while (mp->cur_cmd==left_delimiter)
14489
14490 @ @<Absorb parameter tokens for type |base|@>=
14491 do { 
14492   link(q)=mp_get_avail(mp); q=link(q); info(q)=base+k;
14493   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size); 
14494   value(p)=base+k; info(p)=mp->cur_sym;
14495   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14496 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
14497   incr(k); link(p)=r; r=p; get_t_next;
14498 } while (mp->cur_cmd==comma)
14499
14500 @ @<Absorb undelimited parameters, putting them into list |r|@>=
14501
14502   p=mp_get_node(mp, token_node_size);
14503   if ( mp->cur_mod<expr_base ) {
14504     c=mp->cur_mod; value(p)=expr_base+k;
14505   } else { 
14506     value(p)=mp->cur_mod+k;
14507     if ( mp->cur_mod==expr_base ) c=expr_macro;
14508     else if ( mp->cur_mod==suffix_base ) c=suffix_macro;
14509     else c=text_macro;
14510   }
14511   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14512   incr(k); mp_get_symbol(mp); info(p)=mp->cur_sym; link(p)=r; r=p; get_t_next;
14513   if ( c==expr_macro ) if ( mp->cur_cmd==of_token ) {
14514     c=of_macro; p=mp_get_node(mp, token_node_size);
14515     if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14516     value(p)=expr_base+k; mp_get_symbol(mp); info(p)=mp->cur_sym;
14517     link(p)=r; r=p; get_t_next;
14518   }
14519 }
14520
14521 @* \[32] Expanding the next token.
14522 Only a few command codes |<min_command| can possibly be returned by
14523 |get_t_next|; in increasing order, they are
14524 |if_test|, |fi_or_else|, |input|, |iteration|, |repeat_loop|,
14525 |exit_test|, |relax|, |scan_tokens|, |expand_after|, and |defined_macro|.
14526
14527 \MP\ usually gets the next token of input by saying |get_x_next|. This is
14528 like |get_t_next| except that it keeps getting more tokens until
14529 finding |cur_cmd>=min_command|. In other words, |get_x_next| expands
14530 macros and removes conditionals or iterations or input instructions that
14531 might be present.
14532
14533 It follows that |get_x_next| might invoke itself recursively. In fact,
14534 there is massive recursion, since macro expansion can involve the
14535 scanning of arbitrarily complex expressions, which in turn involve
14536 macro expansion and conditionals, etc.
14537 @^recursion@>
14538
14539 Therefore it's necessary to declare a whole bunch of |forward|
14540 procedures at this point, and to insert some other procedures
14541 that will be invoked by |get_x_next|.
14542
14543 @<Declarations@>= 
14544 void mp_scan_primary (MP mp);
14545 void mp_scan_secondary (MP mp);
14546 void mp_scan_tertiary (MP mp);
14547 void mp_scan_expression (MP mp);
14548 void mp_scan_suffix (MP mp);
14549 @<Declare the procedure called |macro_call|@>;
14550 void mp_get_boolean (MP mp);
14551 void mp_pass_text (MP mp);
14552 void mp_conditional (MP mp);
14553 void mp_start_input (MP mp);
14554 void mp_begin_iteration (MP mp);
14555 void mp_resume_iteration (MP mp);
14556 void mp_stop_iteration (MP mp);
14557
14558 @ An auxiliary subroutine called |expand| is used by |get_x_next|
14559 when it has to do exotic expansion commands.
14560
14561 @c void mp_expand (MP mp) {
14562   pointer p; /* for list manipulation */
14563   size_t k; /* something that we hope is |<=buf_size| */
14564   pool_pointer j; /* index into |str_pool| */
14565   if ( mp->internal[mp_tracing_commands]>unity ) 
14566     if ( mp->cur_cmd!=defined_macro )
14567       show_cur_cmd_mod;
14568   switch (mp->cur_cmd)  {
14569   case if_test:
14570     mp_conditional(mp); /* this procedure is discussed in Part 36 below */
14571     break;
14572   case fi_or_else:
14573     @<Terminate the current conditional and skip to \&{fi}@>;
14574     break;
14575   case input:
14576     @<Initiate or terminate input from a file@>;
14577     break;
14578   case iteration:
14579     if ( mp->cur_mod==end_for ) {
14580       @<Scold the user for having an extra \&{endfor}@>;
14581     } else {
14582       mp_begin_iteration(mp); /* this procedure is discussed in Part 37 below */
14583     }
14584     break;
14585   case repeat_loop: 
14586     @<Repeat a loop@>;
14587     break;
14588   case exit_test: 
14589     @<Exit a loop if the proper time has come@>;
14590     break;
14591   case relax: 
14592     break;
14593   case expand_after: 
14594     @<Expand the token after the next token@>;
14595     break;
14596   case scan_tokens: 
14597     @<Put a string into the input buffer@>;
14598     break;
14599   case defined_macro:
14600    mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14601    break;
14602   }; /* there are no other cases */
14603 };
14604
14605 @ @<Scold the user...@>=
14606
14607   print_err("Extra `endfor'");
14608 @.Extra `endfor'@>
14609   help2("I'm not currently working on a for loop,")
14610     ("so I had better not try to end anything.");
14611   mp_error(mp);
14612 }
14613
14614 @ The processing of \&{input} involves the |start_input| subroutine,
14615 which will be declared later; the processing of \&{endinput} is trivial.
14616
14617 @<Put each...@>=
14618 mp_primitive(mp, "input",input,0);
14619 @:input_}{\&{input} primitive@>
14620 mp_primitive(mp, "endinput",input,1);
14621 @:end_input_}{\&{endinput} primitive@>
14622
14623 @ @<Cases of |print_cmd_mod|...@>=
14624 case input: 
14625   if ( m==0 ) mp_print(mp, "input");
14626   else mp_print(mp, "endinput");
14627   break;
14628
14629 @ @<Initiate or terminate input...@>=
14630 if ( mp->cur_mod>0 ) mp->force_eof=true;
14631 else mp_start_input(mp)
14632
14633 @ We'll discuss the complicated parts of loop operations later. For now
14634 it suffices to know that there's a global variable called |loop_ptr|
14635 that will be |null| if no loop is in progress.
14636
14637 @<Repeat a loop@>=
14638 { while ( token_state &&(loc==null) ) 
14639     mp_end_token_list(mp); /* conserve stack space */
14640   if ( mp->loop_ptr==null ) {
14641     print_err("Lost loop");
14642 @.Lost loop@>
14643     help2("I'm confused; after exiting from a loop, I still seem")
14644       ("to want to repeat it. I'll try to forget the problem.");
14645     mp_error(mp);
14646   } else {
14647     mp_resume_iteration(mp); /* this procedure is in Part 37 below */
14648   }
14649 }
14650
14651 @ @<Exit a loop if the proper time has come@>=
14652 { mp_get_boolean(mp);
14653   if ( mp->internal[mp_tracing_commands]>unity ) 
14654     mp_show_cmd_mod(mp, nullary,mp->cur_exp);
14655   if ( mp->cur_exp==true_code ) {
14656     if ( mp->loop_ptr==null ) {
14657       print_err("No loop is in progress");
14658 @.No loop is in progress@>
14659       help1("Why say `exitif' when there's nothing to exit from?");
14660       if ( mp->cur_cmd==semicolon ) mp_error(mp); else mp_back_error(mp);
14661     } else {
14662      @<Exit prematurely from an iteration@>;
14663     }
14664   } else if ( mp->cur_cmd!=semicolon ) {
14665     mp_missing_err(mp, ";");
14666 @.Missing `;'@>
14667     help2("After `exitif <boolean exp>' I expect to see a semicolon.")
14668     ("I shall pretend that one was there."); mp_back_error(mp);
14669   }
14670 }
14671
14672 @ Here we use the fact that |forever_text| is the only |token_type| that
14673 is less than |loop_text|.
14674
14675 @<Exit prematurely...@>=
14676 { p=null;
14677   do {  
14678     if ( file_state ) {
14679       mp_end_file_reading(mp);
14680     } else { 
14681       if ( token_type<=loop_text ) p=start;
14682       mp_end_token_list(mp);
14683     }
14684   } while (p==null);
14685   if ( p!=info(mp->loop_ptr) ) mp_fatal_error(mp, "*** (loop confusion)");
14686 @.loop confusion@>
14687   mp_stop_iteration(mp); /* this procedure is in Part 34 below */
14688 }
14689
14690 @ @<Expand the token after the next token@>=
14691 { get_t_next;
14692   p=mp_cur_tok(mp); get_t_next;
14693   if ( mp->cur_cmd<min_command ) mp_expand(mp); 
14694   else mp_back_input(mp);
14695   back_list(p);
14696 }
14697
14698 @ @<Put a string into the input buffer@>=
14699 { mp_get_x_next(mp); mp_scan_primary(mp);
14700   if ( mp->cur_type!=mp_string_type ) {
14701     mp_disp_err(mp, null,"Not a string");
14702 @.Not a string@>
14703     help2("I'm going to flush this expression, since")
14704        ("scantokens should be followed by a known string.");
14705     mp_put_get_flush_error(mp, 0);
14706   } else { 
14707     mp_back_input(mp);
14708     if ( length(mp->cur_exp)>0 )
14709        @<Pretend we're reading a new one-line file@>;
14710   }
14711 }
14712
14713 @ @<Pretend we're reading a new one-line file@>=
14714 { mp_begin_file_reading(mp); name=is_scantok;
14715   k=mp->first+length(mp->cur_exp);
14716   if ( k>=mp->max_buf_stack ) {
14717     while ( k>=mp->buf_size ) {
14718       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
14719     }
14720     mp->max_buf_stack=k+1;
14721   }
14722   j=mp->str_start[mp->cur_exp]; limit=k;
14723   while ( mp->first<(size_t)limit ) {
14724     mp->buffer[mp->first]=mp->str_pool[j]; incr(j); incr(mp->first);
14725   }
14726   mp->buffer[limit]='%'; mp->first=limit+1; loc=start; 
14727   mp_flush_cur_exp(mp, 0);
14728 }
14729
14730 @ Here finally is |get_x_next|.
14731
14732 The expression scanning routines to be considered later
14733 communicate via the global quantities |cur_type| and |cur_exp|;
14734 we must be very careful to save and restore these quantities while
14735 macros are being expanded.
14736 @^inner loop@>
14737
14738 @<Declarations@>=
14739 void mp_get_x_next (MP mp);
14740
14741 @ @c void mp_get_x_next (MP mp) {
14742   pointer save_exp; /* a capsule to save |cur_type| and |cur_exp| */
14743   get_t_next;
14744   if ( mp->cur_cmd<min_command ) {
14745     save_exp=mp_stash_cur_exp(mp);
14746     do {  
14747       if ( mp->cur_cmd==defined_macro ) 
14748         mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14749       else 
14750         mp_expand(mp);
14751       get_t_next;
14752      } while (mp->cur_cmd<min_command);
14753      mp_unstash_cur_exp(mp, save_exp); /* that restores |cur_type| and |cur_exp| */
14754   }
14755 }
14756
14757 @ Now let's consider the |macro_call| procedure, which is used to start up
14758 all user-defined macros. Since the arguments to a macro might be expressions,
14759 |macro_call| is recursive.
14760 @^recursion@>
14761
14762 The first parameter to |macro_call| points to the reference count of the
14763 token list that defines the macro. The second parameter contains any
14764 arguments that have already been parsed (see below).  The third parameter
14765 points to the symbolic token that names the macro. If the third parameter
14766 is |null|, the macro was defined by \&{vardef}, so its name can be
14767 reconstructed from the prefix and ``at'' arguments found within the
14768 second parameter.
14769
14770 What is this second parameter? It's simply a linked list of one-word items,
14771 whose |info| fields point to the arguments. In other words, if |arg_list=null|,
14772 no arguments have been scanned yet; otherwise |info(arg_list)| points to
14773 the first scanned argument, and |link(arg_list)| points to the list of
14774 further arguments (if any).
14775
14776 Arguments of type \&{expr} are so-called capsules, which we will
14777 discuss later when we concentrate on expressions; they can be
14778 recognized easily because their |link| field is |void|. Arguments of type
14779 \&{suffix} and \&{text} are token lists without reference counts.
14780
14781 @ After argument scanning is complete, the arguments are moved to the
14782 |param_stack|. (They can't be put on that stack any sooner, because
14783 the stack is growing and shrinking in unpredictable ways as more arguments
14784 are being acquired.)  Then the macro body is fed to the scanner; i.e.,
14785 the replacement text of the macro is placed at the top of the \MP's
14786 input stack, so that |get_t_next| will proceed to read it next.
14787
14788 @<Declare the procedure called |macro_call|@>=
14789 @<Declare the procedure called |print_macro_name|@>;
14790 @<Declare the procedure called |print_arg|@>;
14791 @<Declare the procedure called |scan_text_arg|@>;
14792 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14793                     pointer macro_name) ;
14794
14795 @ @c
14796 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14797                     pointer macro_name) {
14798   /* invokes a user-defined control sequence */
14799   pointer r; /* current node in the macro's token list */
14800   pointer p,q; /* for list manipulation */
14801   integer n; /* the number of arguments */
14802   pointer tail = 0; /* tail of the argument list */
14803   pointer l_delim=0,r_delim=0; /* a delimiter pair */
14804   r=link(def_ref); add_mac_ref(def_ref);
14805   if ( arg_list==null ) {
14806     n=0;
14807   } else {
14808    @<Determine the number |n| of arguments already supplied,
14809     and set |tail| to the tail of |arg_list|@>;
14810   }
14811   if ( mp->internal[mp_tracing_macros]>0 ) {
14812     @<Show the text of the macro being expanded, and the existing arguments@>;
14813   }
14814   @<Scan the remaining arguments, if any; set |r| to the first token
14815     of the replacement text@>;
14816   @<Feed the arguments and replacement text to the scanner@>;
14817 }
14818
14819 @ @<Show the text of the macro...@>=
14820 mp_begin_diagnostic(mp); mp_print_ln(mp); 
14821 mp_print_macro_name(mp, arg_list,macro_name);
14822 if ( n==3 ) mp_print(mp, "@@#"); /* indicate a suffixed macro */
14823 mp_show_macro(mp, def_ref,null,100000);
14824 if ( arg_list!=null ) {
14825   n=0; p=arg_list;
14826   do {  
14827     q=info(p);
14828     mp_print_arg(mp, q,n,0);
14829     incr(n); p=link(p);
14830   } while (p!=null);
14831 }
14832 mp_end_diagnostic(mp, false)
14833
14834
14835 @ @<Declare the procedure called |print_macro_name|@>=
14836 void mp_print_macro_name (MP mp,pointer a, pointer n);
14837
14838 @ @c
14839 void mp_print_macro_name (MP mp,pointer a, pointer n) {
14840   pointer p,q; /* they traverse the first part of |a| */
14841   if ( n!=null ) {
14842     mp_print_text(n);
14843   } else  { 
14844     p=info(a);
14845     if ( p==null ) {
14846       mp_print_text(info(info(link(a))));
14847     } else { 
14848       q=p;
14849       while ( link(q)!=null ) q=link(q);
14850       link(q)=info(link(a));
14851       mp_show_token_list(mp, p,null,1000,0);
14852       link(q)=null;
14853     }
14854   }
14855 }
14856
14857 @ @<Declare the procedure called |print_arg|@>=
14858 void mp_print_arg (MP mp,pointer q, integer n, pointer b) ;
14859
14860 @ @c
14861 void mp_print_arg (MP mp,pointer q, integer n, pointer b) {
14862   if ( link(q)==mp_void ) mp_print_nl(mp, "(EXPR");
14863   else if ( (b<text_base)&&(b!=text_macro) ) mp_print_nl(mp, "(SUFFIX");
14864   else mp_print_nl(mp, "(TEXT");
14865   mp_print_int(mp, n); mp_print(mp, ")<-");
14866   if ( link(q)==mp_void ) mp_print_exp(mp, q,1);
14867   else mp_show_token_list(mp, q,null,1000,0);
14868 }
14869
14870 @ @<Determine the number |n| of arguments already supplied...@>=
14871 {  
14872   n=1; tail=arg_list;
14873   while ( link(tail)!=null ) { 
14874     incr(n); tail=link(tail);
14875   }
14876 }
14877
14878 @ @<Scan the remaining arguments, if any; set |r|...@>=
14879 mp->cur_cmd=comma+1; /* anything |<>comma| will do */
14880 while ( info(r)>=expr_base ) { 
14881   @<Scan the delimited argument represented by |info(r)|@>;
14882   r=link(r);
14883 };
14884 if ( mp->cur_cmd==comma ) {
14885   print_err("Too many arguments to ");
14886 @.Too many arguments...@>
14887   mp_print_macro_name(mp, arg_list,macro_name); mp_print_char(mp, ';');
14888   mp_print_nl(mp, "  Missing `"); mp_print_text(r_delim);
14889 @.Missing `)'...@>
14890   mp_print(mp, "' has been inserted");
14891   help3("I'm going to assume that the comma I just read was a")
14892    ("right delimiter, and then I'll begin expanding the macro.")
14893    ("You might want to delete some tokens before continuing.");
14894   mp_error(mp);
14895 }
14896 if ( info(r)!=general_macro ) {
14897   @<Scan undelimited argument(s)@>;
14898 }
14899 r=link(r)
14900
14901 @ At this point, the reader will find it advisable to review the explanation
14902 of token list format that was presented earlier, paying special attention to
14903 the conventions that apply only at the beginning of a macro's token list.
14904
14905 On the other hand, the reader will have to take the expression-parsing
14906 aspects of the following program on faith; we will explain |cur_type|
14907 and |cur_exp| later. (Several things in this program depend on each other,
14908 and it's necessary to jump into the circle somewhere.)
14909
14910 @<Scan the delimited argument represented by |info(r)|@>=
14911 if ( mp->cur_cmd!=comma ) {
14912   mp_get_x_next(mp);
14913   if ( mp->cur_cmd!=left_delimiter ) {
14914     print_err("Missing argument to ");
14915 @.Missing argument...@>
14916     mp_print_macro_name(mp, arg_list,macro_name);
14917     help3("That macro has more parameters than you thought.")
14918      ("I'll continue by pretending that each missing argument")
14919      ("is either zero or null.");
14920     if ( info(r)>=suffix_base ) {
14921       mp->cur_exp=null; mp->cur_type=mp_token_list;
14922     } else { 
14923       mp->cur_exp=0; mp->cur_type=mp_known;
14924     }
14925     mp_back_error(mp); mp->cur_cmd=right_delimiter; 
14926     goto FOUND;
14927   }
14928   l_delim=mp->cur_sym; r_delim=mp->cur_mod;
14929 }
14930 @<Scan the argument represented by |info(r)|@>;
14931 if ( mp->cur_cmd!=comma ) 
14932   @<Check that the proper right delimiter was present@>;
14933 FOUND:  
14934 @<Append the current expression to |arg_list|@>
14935
14936 @ @<Check that the proper right delim...@>=
14937 if ( (mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
14938   if ( info(link(r))>=expr_base ) {
14939     mp_missing_err(mp, ",");
14940 @.Missing `,'@>
14941     help3("I've finished reading a macro argument and am about to")
14942       ("read another; the arguments weren't delimited correctly.")
14943        ("You might want to delete some tokens before continuing.");
14944     mp_back_error(mp); mp->cur_cmd=comma;
14945   } else { 
14946     mp_missing_err(mp, str(text(r_delim)));
14947 @.Missing `)'@>
14948     help2("I've gotten to the end of the macro parameter list.")
14949        ("You might want to delete some tokens before continuing.");
14950     mp_back_error(mp);
14951   }
14952 }
14953
14954 @ A \&{suffix} or \&{text} parameter will be have been scanned as
14955 a token list pointed to by |cur_exp|, in which case we will have
14956 |cur_type=token_list|.
14957
14958 @<Append the current expression to |arg_list|@>=
14959
14960   p=mp_get_avail(mp);
14961   if ( mp->cur_type==mp_token_list ) info(p)=mp->cur_exp;
14962   else info(p)=mp_stash_cur_exp(mp);
14963   if ( mp->internal[mp_tracing_macros]>0 ) {
14964     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,info(r)); 
14965     mp_end_diagnostic(mp, false);
14966   }
14967   if ( arg_list==null ) arg_list=p;
14968   else link(tail)=p;
14969   tail=p; incr(n);
14970 }
14971
14972 @ @<Scan the argument represented by |info(r)|@>=
14973 if ( info(r)>=text_base ) {
14974   mp_scan_text_arg(mp, l_delim,r_delim);
14975 } else { 
14976   mp_get_x_next(mp);
14977   if ( info(r)>=suffix_base ) mp_scan_suffix(mp);
14978   else mp_scan_expression(mp);
14979 }
14980
14981 @ The parameters to |scan_text_arg| are either a pair of delimiters
14982 or zero; the latter case is for undelimited text arguments, which
14983 end with the first semicolon or \&{endgroup} or \&{end} that is not
14984 contained in a group.
14985
14986 @<Declare the procedure called |scan_text_arg|@>=
14987 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) ;
14988
14989 @ @c
14990 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) {
14991   integer balance; /* excess of |l_delim| over |r_delim| */
14992   pointer p; /* list tail */
14993   mp->warning_info=l_delim; mp->scanner_status=absorbing;
14994   p=hold_head; balance=1; link(hold_head)=null;
14995   while (1)  { 
14996     get_t_next;
14997     if ( l_delim==0 ) {
14998       @<Adjust the balance for an undelimited argument; |break| if done@>;
14999     } else {
15000           @<Adjust the balance for a delimited argument; |break| if done@>;
15001     }
15002     link(p)=mp_cur_tok(mp); p=link(p);
15003   }
15004   mp->cur_exp=link(hold_head); mp->cur_type=mp_token_list;
15005   mp->scanner_status=normal;
15006 };
15007
15008 @ @<Adjust the balance for a delimited argument...@>=
15009 if ( mp->cur_cmd==right_delimiter ) { 
15010   if ( mp->cur_mod==l_delim ) { 
15011     decr(balance);
15012     if ( balance==0 ) break;
15013   }
15014 } else if ( mp->cur_cmd==left_delimiter ) {
15015   if ( mp->cur_mod==r_delim ) incr(balance);
15016 }
15017
15018 @ @<Adjust the balance for an undelimited...@>=
15019 if ( end_of_statement ) { /* |cur_cmd=semicolon|, |end_group|, or |stop| */
15020   if ( balance==1 ) { break; }
15021   else  { if ( mp->cur_cmd==end_group ) decr(balance); }
15022 } else if ( mp->cur_cmd==begin_group ) { 
15023   incr(balance); 
15024 }
15025
15026 @ @<Scan undelimited argument(s)@>=
15027
15028   if ( info(r)<text_macro ) {
15029     mp_get_x_next(mp);
15030     if ( info(r)!=suffix_macro ) {
15031       if ( (mp->cur_cmd==equals)||(mp->cur_cmd==assignment) ) mp_get_x_next(mp);
15032     }
15033   }
15034   switch (info(r)) {
15035   case primary_macro:mp_scan_primary(mp); break;
15036   case secondary_macro:mp_scan_secondary(mp); break;
15037   case tertiary_macro:mp_scan_tertiary(mp); break;
15038   case expr_macro:mp_scan_expression(mp); break;
15039   case of_macro:
15040     @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>;
15041     break;
15042   case suffix_macro:
15043     @<Scan a suffix with optional delimiters@>;
15044     break;
15045   case text_macro:mp_scan_text_arg(mp, 0,0); break;
15046   } /* there are no other cases */
15047   mp_back_input(mp); 
15048   @<Append the current expression to |arg_list|@>;
15049 }
15050
15051 @ @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>=
15052
15053   mp_scan_expression(mp); p=mp_get_avail(mp); info(p)=mp_stash_cur_exp(mp);
15054   if ( mp->internal[mp_tracing_macros]>0 ) { 
15055     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,0); 
15056     mp_end_diagnostic(mp, false);
15057   }
15058   if ( arg_list==null ) arg_list=p; else link(tail)=p;
15059   tail=p;incr(n);
15060   if ( mp->cur_cmd!=of_token ) {
15061     mp_missing_err(mp, "of"); mp_print(mp, " for ");
15062 @.Missing `of'@>
15063     mp_print_macro_name(mp, arg_list,macro_name);
15064     help1("I've got the first argument; will look now for the other.");
15065     mp_back_error(mp);
15066   }
15067   mp_get_x_next(mp); mp_scan_primary(mp);
15068 }
15069
15070 @ @<Scan a suffix with optional delimiters@>=
15071
15072   if ( mp->cur_cmd!=left_delimiter ) {
15073     l_delim=null;
15074   } else { 
15075     l_delim=mp->cur_sym; r_delim=mp->cur_mod; mp_get_x_next(mp);
15076   };
15077   mp_scan_suffix(mp);
15078   if ( l_delim!=null ) {
15079     if ((mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
15080       mp_missing_err(mp, str(text(r_delim)));
15081 @.Missing `)'@>
15082       help2("I've gotten to the end of the macro parameter list.")
15083          ("You might want to delete some tokens before continuing.");
15084       mp_back_error(mp);
15085     }
15086     mp_get_x_next(mp);
15087   }
15088 }
15089
15090 @ Before we put a new token list on the input stack, it is wise to clean off
15091 all token lists that have recently been depleted. Then a user macro that ends
15092 with a call to itself will not require unbounded stack space.
15093
15094 @<Feed the arguments and replacement text to the scanner@>=
15095 while ( token_state &&(loc==null) ) mp_end_token_list(mp); /* conserve stack space */
15096 if ( mp->param_ptr+n>mp->max_param_stack ) {
15097   mp->max_param_stack=mp->param_ptr+n;
15098   if ( mp->max_param_stack>mp->param_size )
15099     mp_overflow(mp, "parameter stack size",mp->param_size);
15100 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15101 }
15102 mp_begin_token_list(mp, def_ref,macro); name=macro_name; loc=r;
15103 if ( n>0 ) {
15104   p=arg_list;
15105   do {  
15106    mp->param_stack[mp->param_ptr]=info(p); incr(mp->param_ptr); p=link(p);
15107   } while (p!=null);
15108   mp_flush_list(mp, arg_list);
15109 }
15110
15111 @ It's sometimes necessary to put a single argument onto |param_stack|.
15112 The |stack_argument| subroutine does this.
15113
15114 @c void mp_stack_argument (MP mp,pointer p) { 
15115   if ( mp->param_ptr==mp->max_param_stack ) {
15116     incr(mp->max_param_stack);
15117     if ( mp->max_param_stack>mp->param_size )
15118       mp_overflow(mp, "parameter stack size",mp->param_size);
15119 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15120   }
15121   mp->param_stack[mp->param_ptr]=p; incr(mp->param_ptr);
15122 }
15123
15124 @* \[33] Conditional processing.
15125 Let's consider now the way \&{if} commands are handled.
15126
15127 Conditions can be inside conditions, and this nesting has a stack
15128 that is independent of other stacks.
15129 Four global variables represent the top of the condition stack:
15130 |cond_ptr| points to pushed-down entries, if~any; |cur_if| tells whether
15131 we are processing \&{if} or \&{elseif}; |if_limit| specifies
15132 the largest code of a |fi_or_else| command that is syntactically legal;
15133 and |if_line| is the line number at which the current conditional began.
15134
15135 If no conditions are currently in progress, the condition stack has the
15136 special state |cond_ptr=null|, |if_limit=normal|, |cur_if=0|, |if_line=0|.
15137 Otherwise |cond_ptr| points to a two-word node; the |type|, |name_type|, and
15138 |link| fields of the first word contain |if_limit|, |cur_if|, and
15139 |cond_ptr| at the next level, and the second word contains the
15140 corresponding |if_line|.
15141
15142 @d if_node_size 2 /* number of words in stack entry for conditionals */
15143 @d if_line_field(A) mp->mem[(A)+1].cint
15144 @d if_code 1 /* code for \&{if} being evaluated */
15145 @d fi_code 2 /* code for \&{fi} */
15146 @d else_code 3 /* code for \&{else} */
15147 @d else_if_code 4 /* code for \&{elseif} */
15148
15149 @<Glob...@>=
15150 pointer cond_ptr; /* top of the condition stack */
15151 integer if_limit; /* upper bound on |fi_or_else| codes */
15152 small_number cur_if; /* type of conditional being worked on */
15153 integer if_line; /* line where that conditional began */
15154
15155 @ @<Set init...@>=
15156 mp->cond_ptr=null; mp->if_limit=normal; mp->cur_if=0; mp->if_line=0;
15157
15158 @ @<Put each...@>=
15159 mp_primitive(mp, "if",if_test,if_code);
15160 @:if_}{\&{if} primitive@>
15161 mp_primitive(mp, "fi",fi_or_else,fi_code); mp->eqtb[frozen_fi]=mp->eqtb[mp->cur_sym];
15162 @:fi_}{\&{fi} primitive@>
15163 mp_primitive(mp, "else",fi_or_else,else_code);
15164 @:else_}{\&{else} primitive@>
15165 mp_primitive(mp, "elseif",fi_or_else,else_if_code);
15166 @:else_if_}{\&{elseif} primitive@>
15167
15168 @ @<Cases of |print_cmd_mod|...@>=
15169 case if_test:
15170 case fi_or_else: 
15171   switch (m) {
15172   case if_code:mp_print(mp, "if"); break;
15173   case fi_code:mp_print(mp, "fi");  break;
15174   case else_code:mp_print(mp, "else"); break;
15175   default: mp_print(mp, "elseif"); break;
15176   }
15177   break;
15178
15179 @ Here is a procedure that ignores text until coming to an \&{elseif},
15180 \&{else}, or \&{fi} at level zero of $\&{if}\ldots\&{fi}$
15181 nesting. After it has acted, |cur_mod| will indicate the token that
15182 was found.
15183
15184 \MP's smallest two command codes are |if_test| and |fi_or_else|; this
15185 makes the skipping process a bit simpler.
15186
15187 @c 
15188 void mp_pass_text (MP mp) {
15189   integer l = 0;
15190   mp->scanner_status=skipping;
15191   mp->warning_info=mp_true_line(mp);
15192   while (1)  { 
15193     get_t_next;
15194     if ( mp->cur_cmd<=fi_or_else ) {
15195       if ( mp->cur_cmd<fi_or_else ) {
15196         incr(l);
15197       } else { 
15198         if ( l==0 ) break;
15199         if ( mp->cur_mod==fi_code ) decr(l);
15200       }
15201     } else {
15202       @<Decrease the string reference count,
15203        if the current token is a string@>;
15204     }
15205   }
15206   mp->scanner_status=normal;
15207 }
15208
15209 @ @<Decrease the string reference count...@>=
15210 if ( mp->cur_cmd==string_token ) { delete_str_ref(mp->cur_mod); }
15211
15212 @ When we begin to process a new \&{if}, we set |if_limit:=if_code|; then
15213 if \&{elseif} or \&{else} or \&{fi} occurs before the current \&{if}
15214 condition has been evaluated, a colon will be inserted.
15215 A construction like `\.{if fi}' would otherwise get \MP\ confused.
15216
15217 @<Push the condition stack@>=
15218 { p=mp_get_node(mp, if_node_size); link(p)=mp->cond_ptr; type(p)=mp->if_limit;
15219   name_type(p)=mp->cur_if; if_line_field(p)=mp->if_line;
15220   mp->cond_ptr=p; mp->if_limit=if_code; mp->if_line=mp_true_line(mp); 
15221   mp->cur_if=if_code;
15222 }
15223
15224 @ @<Pop the condition stack@>=
15225 { p=mp->cond_ptr; mp->if_line=if_line_field(p);
15226   mp->cur_if=name_type(p); mp->if_limit=type(p); mp->cond_ptr=link(p);
15227   mp_free_node(mp, p,if_node_size);
15228 }
15229
15230 @ Here's a procedure that changes the |if_limit| code corresponding to
15231 a given value of |cond_ptr|.
15232
15233 @c void mp_change_if_limit (MP mp,small_number l, pointer p) {
15234   pointer q;
15235   if ( p==mp->cond_ptr ) {
15236     mp->if_limit=l; /* that's the easy case */
15237   } else  { 
15238     q=mp->cond_ptr;
15239     while (1) { 
15240       if ( q==null ) mp_confusion(mp, "if");
15241 @:this can't happen if}{\quad if@>
15242       if ( link(q)==p ) { 
15243         type(q)=l; return;
15244       }
15245       q=link(q);
15246     }
15247   }
15248 }
15249
15250 @ The user is supposed to put colons into the proper parts of conditional
15251 statements. Therefore, \MP\ has to check for their presence.
15252
15253 @c 
15254 void mp_check_colon (MP mp) { 
15255   if ( mp->cur_cmd!=colon ) { 
15256     mp_missing_err(mp, ":");
15257 @.Missing `:'@>
15258     help2("There should've been a colon after the condition.")
15259          ("I shall pretend that one was there.");;
15260     mp_back_error(mp);
15261   }
15262 }
15263
15264 @ A condition is started when the |get_x_next| procedure encounters
15265 an |if_test| command; in that case |get_x_next| calls |conditional|,
15266 which is a recursive procedure.
15267 @^recursion@>
15268
15269 @c void mp_conditional (MP mp) {
15270   pointer save_cond_ptr; /* |cond_ptr| corresponding to this conditional */
15271   int new_if_limit; /* future value of |if_limit| */
15272   pointer p; /* temporary register */
15273   @<Push the condition stack@>; 
15274   save_cond_ptr=mp->cond_ptr;
15275 RESWITCH: 
15276   mp_get_boolean(mp); new_if_limit=else_if_code;
15277   if ( mp->internal[mp_tracing_commands]>unity ) {
15278     @<Display the boolean value of |cur_exp|@>;
15279   }
15280 FOUND: 
15281   mp_check_colon(mp);
15282   if ( mp->cur_exp==true_code ) {
15283     mp_change_if_limit(mp, new_if_limit,save_cond_ptr);
15284     return; /* wait for \&{elseif}, \&{else}, or \&{fi} */
15285   };
15286   @<Skip to \&{elseif} or \&{else} or \&{fi}, then |goto done|@>;
15287 DONE: 
15288   mp->cur_if=mp->cur_mod; mp->if_line=mp_true_line(mp);
15289   if ( mp->cur_mod==fi_code ) {
15290     @<Pop the condition stack@>
15291   } else if ( mp->cur_mod==else_if_code ) {
15292     goto RESWITCH;
15293   } else  { 
15294     mp->cur_exp=true_code; new_if_limit=fi_code; mp_get_x_next(mp); 
15295     goto FOUND;
15296   }
15297 }
15298
15299 @ In a construction like `\&{if} \&{if} \&{true}: $0=1$: \\{foo}
15300 \&{else}: \\{bar} \&{fi}', the first \&{else}
15301 that we come to after learning that the \&{if} is false is not the
15302 \&{else} we're looking for. Hence the following curious logic is needed.
15303
15304 @<Skip to \&{elseif}...@>=
15305 while (1) { 
15306   mp_pass_text(mp);
15307   if ( mp->cond_ptr==save_cond_ptr ) goto DONE;
15308   else if ( mp->cur_mod==fi_code ) @<Pop the condition stack@>;
15309 }
15310
15311
15312 @ @<Display the boolean value...@>=
15313 { mp_begin_diagnostic(mp);
15314   if ( mp->cur_exp==true_code ) mp_print(mp, "{true}");
15315   else mp_print(mp, "{false}");
15316   mp_end_diagnostic(mp, false);
15317 }
15318
15319 @ The processing of conditionals is complete except for the following
15320 code, which is actually part of |get_x_next|. It comes into play when
15321 \&{elseif}, \&{else}, or \&{fi} is scanned.
15322
15323 @<Terminate the current conditional and skip to \&{fi}@>=
15324 if ( mp->cur_mod>mp->if_limit ) {
15325   if ( mp->if_limit==if_code ) { /* condition not yet evaluated */
15326     mp_missing_err(mp, ":");
15327 @.Missing `:'@>
15328     mp_back_input(mp); mp->cur_sym=frozen_colon; mp_ins_error(mp);
15329   } else  { 
15330     print_err("Extra "); mp_print_cmd_mod(mp, fi_or_else,mp->cur_mod);
15331 @.Extra else@>
15332 @.Extra elseif@>
15333 @.Extra fi@>
15334     help1("I'm ignoring this; it doesn't match any if.");
15335     mp_error(mp);
15336   }
15337 } else  { 
15338   while ( mp->cur_mod!=fi_code ) mp_pass_text(mp); /* skip to \&{fi} */
15339   @<Pop the condition stack@>;
15340 }
15341
15342 @* \[34] Iterations.
15343 To bring our treatment of |get_x_next| to a close, we need to consider what
15344 \MP\ does when it sees \&{for}, \&{forsuffixes}, and \&{forever}.
15345
15346 There's a global variable |loop_ptr| that keeps track of the \&{for} loops
15347 that are currently active. If |loop_ptr=null|, no loops are in progress;
15348 otherwise |info(loop_ptr)| points to the iterative text of the current
15349 (innermost) loop, and |link(loop_ptr)| points to the data for any other
15350 loops that enclose the current one.
15351
15352 A loop-control node also has two other fields, called |loop_type| and
15353 |loop_list|, whose contents depend on the type of loop:
15354
15355 \yskip\indent|loop_type(loop_ptr)=null| means that |loop_list(loop_ptr)|
15356 points to a list of one-word nodes whose |info| fields point to the
15357 remaining argument values of a suffix list and expression list.
15358
15359 \yskip\indent|loop_type(loop_ptr)=mp_void| means that the current loop is
15360 `\&{forever}'.
15361
15362 \yskip\indent|loop_type(loop_ptr)=progression_flag| means that
15363 |p=loop_list(loop_ptr)| points to a ``progression node'' and |value(p)|,
15364 |step_size(p)|, and |final_value(p)| contain the data for an arithmetic
15365 progression.
15366
15367 \yskip\indent|loop_type(loop_ptr)=p>mp_void| means that |p| points to an edge
15368 header and |loop_list(loop_ptr)| points into the graphical object list for
15369 that edge header.
15370
15371 \yskip\noindent In the case of a progression node, the first word is not used
15372 because the link field of words in the dynamic memory area cannot be arbitrary.
15373
15374 @d loop_list_loc(A) ((A)+1) /* where the |loop_list| field resides */
15375 @d loop_type(A) info(loop_list_loc((A))) /* the type of \&{for} loop */
15376 @d loop_list(A) link(loop_list_loc((A))) /* the remaining list elements */
15377 @d loop_node_size 2 /* the number of words in a loop control node */
15378 @d progression_node_size 4 /* the number of words in a progression node */
15379 @d step_size(A) mp->mem[(A)+2].sc /* the step size in an arithmetic progression */
15380 @d final_value(A) mp->mem[(A)+3].sc /* the final value in an arithmetic progression */
15381 @d progression_flag (null+2)
15382   /* |loop_type| value when |loop_list| points to a progression node */
15383
15384 @<Glob...@>=
15385 pointer loop_ptr; /* top of the loop-control-node stack */
15386
15387 @ @<Set init...@>=
15388 mp->loop_ptr=null;
15389
15390 @ If the expressions that define an arithmetic progression in
15391 a \&{for} loop don't have known numeric values, the |bad_for|
15392 subroutine screams at the user.
15393
15394 @c void mp_bad_for (MP mp, char * s) {
15395   mp_disp_err(mp, null,"Improper "); /* show the bad expression above the message */
15396 @.Improper...replaced by 0@>
15397   mp_print(mp, s); mp_print(mp, " has been replaced by 0");
15398   help4("When you say `for x=a step b until c',")
15399     ("the initial value `a' and the step size `b'")
15400     ("and the final value `c' must have known numeric values.")
15401     ("I'm zeroing this one. Proceed, with fingers crossed.");
15402   mp_put_get_flush_error(mp, 0);
15403 };
15404
15405 @ Here's what \MP\ does when \&{for}, \&{forsuffixes}, or \&{forever}
15406 has just been scanned. (This code requires slight familiarity with
15407 expression-parsing routines that we have not yet discussed; but it seems
15408 to belong in the present part of the program, even though the original author
15409 didn't write it until later. The reader may wish to come back to it.)
15410
15411 @c void mp_begin_iteration (MP mp) {
15412   halfword m; /* |expr_base| (\&{for}) or |suffix_base| (\&{forsuffixes}) */
15413   halfword n; /* hash address of the current symbol */
15414   pointer s; /* the new loop-control node */
15415   pointer p; /* substitution list for |scan_toks| */
15416   pointer q;  /* link manipulation register */
15417   pointer pp; /* a new progression node */
15418   m=mp->cur_mod; n=mp->cur_sym; s=mp_get_node(mp, loop_node_size);
15419   if ( m==start_forever ){ 
15420     loop_type(s)=mp_void; p=null; mp_get_x_next(mp);
15421   } else { 
15422     mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
15423     info(p)=mp->cur_sym; value(p)=m;
15424     mp_get_x_next(mp);
15425     if ( mp->cur_cmd==within_token ) {
15426       @<Set up a picture iteration@>;
15427     } else { 
15428       @<Check for the |"="| or |":="| in a loop header@>;
15429       @<Scan the values to be used in the loop@>;
15430     }
15431   }
15432   @<Check for the presence of a colon@>;
15433   @<Scan the loop text and put it on the loop control stack@>;
15434   mp_resume_iteration(mp);
15435 }
15436
15437 @ @<Check for the |"="| or |":="| in a loop header@>=
15438 if ( (mp->cur_cmd!=equals)&&(mp->cur_cmd!=assignment) ) { 
15439   mp_missing_err(mp, "=");
15440 @.Missing `='@>
15441   help3("The next thing in this loop should have been `=' or `:='.")
15442     ("But don't worry; I'll pretend that an equals sign")
15443     ("was present, and I'll look for the values next.");
15444   mp_back_error(mp);
15445 }
15446
15447 @ @<Check for the presence of a colon@>=
15448 if ( mp->cur_cmd!=colon ) { 
15449   mp_missing_err(mp, ":");
15450 @.Missing `:'@>
15451   help3("The next thing in this loop should have been a `:'.")
15452     ("So I'll pretend that a colon was present;")
15453     ("everything from here to `endfor' will be iterated.");
15454   mp_back_error(mp);
15455 }
15456
15457 @ We append a special |frozen_repeat_loop| token in place of the
15458 `\&{endfor}' at the end of the loop. This will come through \MP's scanner
15459 at the proper time to cause the loop to be repeated.
15460
15461 (If the user tries some shenanigan like `\&{for} $\ldots$ \&{let} \&{endfor}',
15462 he will be foiled by the |get_symbol| routine, which keeps frozen
15463 tokens unchanged. Furthermore the |frozen_repeat_loop| is an \&{outer}
15464 token, so it won't be lost accidentally.)
15465
15466 @ @<Scan the loop text...@>=
15467 q=mp_get_avail(mp); info(q)=frozen_repeat_loop;
15468 mp->scanner_status=loop_defining; mp->warning_info=n;
15469 info(s)=mp_scan_toks(mp, iteration,p,q,0); mp->scanner_status=normal;
15470 link(s)=mp->loop_ptr; mp->loop_ptr=s
15471
15472 @ @<Initialize table...@>=
15473 eq_type(frozen_repeat_loop)=repeat_loop+outer_tag;
15474 text(frozen_repeat_loop)=intern(" ENDFOR");
15475
15476 @ The loop text is inserted into \MP's scanning apparatus by the
15477 |resume_iteration| routine.
15478
15479 @c void mp_resume_iteration (MP mp) {
15480   pointer p,q; /* link registers */
15481   p=loop_type(mp->loop_ptr);
15482   if ( p==progression_flag ) { 
15483     p=loop_list(mp->loop_ptr); /* now |p| points to a progression node */
15484     mp->cur_exp=value(p);
15485     if ( @<The arithmetic progression has ended@> ) {
15486       mp_stop_iteration(mp);
15487       return;
15488     }
15489     mp->cur_type=mp_known; q=mp_stash_cur_exp(mp); /* make |q| an \&{expr} argument */
15490     value(p)=mp->cur_exp+step_size(p); /* set |value(p)| for the next iteration */
15491   } else if ( p==null ) { 
15492     p=loop_list(mp->loop_ptr);
15493     if ( p==null ) {
15494       mp_stop_iteration(mp);
15495       return;
15496     }
15497     loop_list(mp->loop_ptr)=link(p); q=info(p); free_avail(p);
15498   } else if ( p==mp_void ) { 
15499     mp_begin_token_list(mp, info(mp->loop_ptr),forever_text); return;
15500   } else {
15501     @<Make |q| a capsule containing the next picture component from
15502       |loop_list(loop_ptr)| or |goto not_found|@>;
15503   }
15504   mp_begin_token_list(mp, info(mp->loop_ptr),loop_text);
15505   mp_stack_argument(mp, q);
15506   if ( mp->internal[mp_tracing_commands]>unity ) {
15507      @<Trace the start of a loop@>;
15508   }
15509   return;
15510 NOT_FOUND:
15511   mp_stop_iteration(mp);
15512 }
15513
15514 @ @<The arithmetic progression has ended@>=
15515 ((step_size(p)>0)&&(mp->cur_exp>final_value(p)))||
15516  ((step_size(p)<0)&&(mp->cur_exp<final_value(p)))
15517
15518 @ @<Trace the start of a loop@>=
15519
15520   mp_begin_diagnostic(mp); mp_print_nl(mp, "{loop value=");
15521 @.loop value=n@>
15522   if ( (q!=null)&&(link(q)==mp_void) ) mp_print_exp(mp, q,1);
15523   else mp_show_token_list(mp, q,null,50,0);
15524   mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
15525 }
15526
15527 @ @<Make |q| a capsule containing the next picture component from...@>=
15528 { q=loop_list(mp->loop_ptr);
15529   if ( q==null ) goto NOT_FOUND;
15530   skip_component(q) goto NOT_FOUND;
15531   mp->cur_exp=mp_copy_objects(mp, loop_list(mp->loop_ptr),q);
15532   mp_init_bbox(mp, mp->cur_exp);
15533   mp->cur_type=mp_picture_type;
15534   loop_list(mp->loop_ptr)=q;
15535   q=mp_stash_cur_exp(mp);
15536 }
15537
15538 @ A level of loop control disappears when |resume_iteration| has decided
15539 not to resume, or when an \&{exitif} construction has removed the loop text
15540 from the input stack.
15541
15542 @c void mp_stop_iteration (MP mp) {
15543   pointer p,q; /* the usual */
15544   p=loop_type(mp->loop_ptr);
15545   if ( p==progression_flag )  {
15546     mp_free_node(mp, loop_list(mp->loop_ptr),progression_node_size);
15547   } else if ( p==null ){ 
15548     q=loop_list(mp->loop_ptr);
15549     while ( q!=null ) {
15550       p=info(q);
15551       if ( p!=null ) {
15552         if ( link(p)==mp_void ) { /* it's an \&{expr} parameter */
15553           mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
15554         } else {
15555           mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
15556         }
15557       }
15558       p=q; q=link(q); free_avail(p);
15559     }
15560   } else if ( p>progression_flag ) {
15561     delete_edge_ref(p);
15562   }
15563   p=mp->loop_ptr; mp->loop_ptr=link(p); mp_flush_token_list(mp, info(p));
15564   mp_free_node(mp, p,loop_node_size);
15565 }
15566
15567 @ Now that we know all about loop control, we can finish up
15568 the missing portion of |begin_iteration| and we'll be done.
15569
15570 The following code is performed after the `\.=' has been scanned in
15571 a \&{for} construction (if |m=expr_base|) or a \&{forsuffixes} construction
15572 (if |m=suffix_base|).
15573
15574 @<Scan the values to be used in the loop@>=
15575 loop_type(s)=null; q=loop_list_loc(s); link(q)=null; /* |link(q)=loop_list(s)| */
15576 do {  
15577   mp_get_x_next(mp);
15578   if ( m!=expr_base ) {
15579     mp_scan_suffix(mp);
15580   } else { 
15581     if ( mp->cur_cmd>=colon ) if ( mp->cur_cmd<=comma ) 
15582           goto CONTINUE;
15583     mp_scan_expression(mp);
15584     if ( mp->cur_cmd==step_token ) if ( q==loop_list_loc(s) ) {
15585       @<Prepare for step-until construction and |break|@>;
15586     }
15587     mp->cur_exp=mp_stash_cur_exp(mp);
15588   }
15589   link(q)=mp_get_avail(mp); q=link(q); 
15590   info(q)=mp->cur_exp; mp->cur_type=mp_vacuous;
15591 CONTINUE:
15592   ;
15593 } while (mp->cur_cmd==comma)
15594
15595 @ @<Prepare for step-until construction and |break|@>=
15596
15597   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "initial value");
15598   pp=mp_get_node(mp, progression_node_size); value(pp)=mp->cur_exp;
15599   mp_get_x_next(mp); mp_scan_expression(mp);
15600   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "step size");
15601   step_size(pp)=mp->cur_exp;
15602   if ( mp->cur_cmd!=until_token ) { 
15603     mp_missing_err(mp, "until");
15604 @.Missing `until'@>
15605     help2("I assume you meant to say `until' after `step'.")
15606       ("So I'll look for the final value and colon next.");
15607     mp_back_error(mp);
15608   }
15609   mp_get_x_next(mp); mp_scan_expression(mp);
15610   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "final value");
15611   final_value(pp)=mp->cur_exp; loop_list(s)=pp;
15612   loop_type(s)=progression_flag; 
15613   break;
15614 }
15615
15616 @ The last case is when we have just seen ``\&{within}'', and we need to
15617 parse a picture expression and prepare to iterate over it.
15618
15619 @<Set up a picture iteration@>=
15620 { mp_get_x_next(mp);
15621   mp_scan_expression(mp);
15622   @<Make sure the current expression is a known picture@>;
15623   loop_type(s)=mp->cur_exp; mp->cur_type=mp_vacuous;
15624   q=link(dummy_loc(mp->cur_exp));
15625   if ( q!= null ) 
15626     if ( is_start_or_stop(q) )
15627       if ( mp_skip_1component(mp, q)==null ) q=link(q);
15628   loop_list(s)=q;
15629 }
15630
15631 @ @<Make sure the current expression is a known picture@>=
15632 if ( mp->cur_type!=mp_picture_type ) {
15633   mp_disp_err(mp, null,"Improper iteration spec has been replaced by nullpicture");
15634   help1("When you say `for x in p', p must be a known picture.");
15635   mp_put_get_flush_error(mp, mp_get_node(mp, edge_header_size));
15636   mp_init_edges(mp, mp->cur_exp); mp->cur_type=mp_picture_type;
15637 }
15638
15639 @* \[35] File names.
15640 It's time now to fret about file names.  Besides the fact that different
15641 operating systems treat files in different ways, we must cope with the
15642 fact that completely different naming conventions are used by different
15643 groups of people. The following programs show what is required for one
15644 particular operating system; similar routines for other systems are not
15645 difficult to devise.
15646 @^system dependencies@>
15647
15648 \MP\ assumes that a file name has three parts: the name proper; its
15649 ``extension''; and a ``file area'' where it is found in an external file
15650 system.  The extension of an input file is assumed to be
15651 `\.{.mp}' unless otherwise specified; it is `\.{.log}' on the
15652 transcript file that records each run of \MP; it is `\.{.tfm}' on the font
15653 metric files that describe characters in any fonts created by \MP; it is
15654 `\.{.ps}' or `.{\it nnn}' for some number {\it nnn} on the \ps\ output files;
15655 and it is `\.{.mem}' on the mem files written by \.{INIMP} to initialize \MP.
15656 The file area can be arbitrary on input files, but files are usually
15657 output to the user's current area.  If an input file cannot be
15658 found on the specified area, \MP\ will look for it on a special system
15659 area; this special area is intended for commonly used input files.
15660
15661 Simple uses of \MP\ refer only to file names that have no explicit
15662 extension or area. For example, a person usually says `\.{input} \.{cmr10}'
15663 instead of `\.{input} \.{cmr10.new}'. Simple file
15664 names are best, because they make the \MP\ source files portable;
15665 whenever a file name consists entirely of letters and digits, it should be
15666 treated in the same way by all implementations of \MP. However, users
15667 need the ability to refer to other files in their environment, especially
15668 when responding to error messages concerning unopenable files; therefore
15669 we want to let them use the syntax that appears in their favorite
15670 operating system.
15671
15672 @ \MP\ uses the same conventions that have proved to be satisfactory for
15673 \TeX\ and \MF. In order to isolate the system-dependent aspects of file names,
15674 @^system dependencies@>
15675 the system-independent parts of \MP\ are expressed in terms
15676 of three system-dependent
15677 procedures called |begin_name|, |more_name|, and |end_name|. In
15678 essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
15679 the system-independent driver program does the operations
15680 $$|begin_name|;\,|more_name|(c_1);\,\ldots\,;|more_name|(c_n);
15681 \,|end_name|.$$
15682 These three procedures communicate with each other via global variables.
15683 Afterwards the file name will appear in the string pool as three strings
15684 called |cur_name|\penalty10000\hskip-.05em,
15685 |cur_area|, and |cur_ext|; the latter two are null (i.e.,
15686 |""|), unless they were explicitly specified by the user.
15687
15688 Actually the situation is slightly more complicated, because \MP\ needs
15689 to know when the file name ends. The |more_name| routine is a function
15690 (with side effects) that returns |true| on the calls |more_name|$(c_1)$,
15691 \dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
15692 returns |false|; or, it returns |true| and $c_n$ is the last character
15693 on the current input line. In other words,
15694 |more_name| is supposed to return |true| unless it is sure that the
15695 file name has been completely scanned; and |end_name| is supposed to be able
15696 to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
15697 whether $|more_name|(c_n)$ returned |true| or |false|.
15698
15699 @<Glob...@>=
15700 char * cur_name; /* name of file just scanned */
15701 char * cur_area; /* file area just scanned, or \.{""} */
15702 char * cur_ext; /* file extension just scanned, or \.{""} */
15703
15704 @ It is easier to maintain reference counts if we assign initial values.
15705
15706 @<Set init...@>=
15707 mp->cur_name=xstrdup(""); 
15708 mp->cur_area=xstrdup(""); 
15709 mp->cur_ext=xstrdup("");
15710
15711 @ @<Dealloc variables@>=
15712 xfree(mp->cur_area);
15713 xfree(mp->cur_name);
15714 xfree(mp->cur_ext);
15715
15716 @ The file names we shall deal with for illustrative purposes have the
15717 following structure:  If the name contains `\.>' or `\.:', the file area
15718 consists of all characters up to and including the final such character;
15719 otherwise the file area is null.  If the remaining file name contains
15720 `\..', the file extension consists of all such characters from the first
15721 remaining `\..' to the end, otherwise the file extension is null.
15722 @^system dependencies@>
15723
15724 We can scan such file names easily by using two global variables that keep track
15725 of the occurrences of area and extension delimiters.  Note that these variables
15726 cannot be of type |pool_pointer| because a string pool compaction could occur
15727 while scanning a file name.
15728
15729 @<Glob...@>=
15730 integer area_delimiter;
15731   /* most recent `\.>' or `\.:' relative to |str_start[str_ptr]| */
15732 integer ext_delimiter; /* the relevant `\..', if any */
15733
15734 @ Here now is the first of the system-dependent routines for file name scanning.
15735 @^system dependencies@>
15736
15737 @<Declare subroutines for parsing file names@>=
15738 void mp_begin_name (MP mp) { 
15739   xfree(mp->cur_name); 
15740   xfree(mp->cur_area); 
15741   xfree(mp->cur_ext);
15742   mp->area_delimiter=-1; 
15743   mp->ext_delimiter=-1;
15744 }
15745
15746 @ And here's the second.
15747 @^system dependencies@>
15748
15749 @<Declare subroutines for parsing file names@>=
15750 boolean mp_more_name (MP mp, ASCII_code c) { 
15751   if (c==' ') {
15752     return false;
15753   } else { 
15754     if ( (c=='>')||(c==':') ) { 
15755       mp->area_delimiter=mp->pool_ptr; 
15756       mp->ext_delimiter=-1;
15757     } else if ( (c=='.')&&(mp->ext_delimiter<0) ) {
15758       mp->ext_delimiter=mp->pool_ptr;
15759     }
15760     str_room(1); append_char(c); /* contribute |c| to the current string */
15761     return true;
15762   }
15763 }
15764
15765 @ The third.
15766 @^system dependencies@>
15767
15768 @d copy_pool_segment(A,B,C) { 
15769       A = xmalloc(C+1,sizeof(char)); 
15770       strncpy(A,(char *)(mp->str_pool+B),C);  
15771       A[C] = 0;}
15772
15773 @<Declare subroutines for parsing file names@>=
15774 void mp_end_name (MP mp) {
15775   pool_pointer s; /* length of area, name, and extension */
15776   unsigned int len;
15777   /* "my/w.mp" */
15778   s = mp->str_start[mp->str_ptr];
15779   if ( mp->area_delimiter<0 ) {    
15780     mp->cur_area=xstrdup("");
15781   } else {
15782     len = mp->area_delimiter-s; 
15783     copy_pool_segment(mp->cur_area,s,len);
15784     s += len+1;
15785   }
15786   if ( mp->ext_delimiter<0 ) {
15787     mp->cur_ext=xstrdup("");
15788     len = mp->pool_ptr-s; 
15789   } else {
15790     copy_pool_segment(mp->cur_ext,mp->ext_delimiter,(mp->pool_ptr-mp->ext_delimiter));
15791     len = mp->ext_delimiter-s;
15792   }
15793   copy_pool_segment(mp->cur_name,s,len);
15794   mp->pool_ptr=s; /* don't need this partial string */
15795 }
15796
15797 @ Conversely, here is a routine that takes three strings and prints a file
15798 name that might have produced them. (The routine is system dependent, because
15799 some operating systems put the file area last instead of first.)
15800 @^system dependencies@>
15801
15802 @<Basic printing...@>=
15803 void mp_print_file_name (MP mp, char * n, char * a, char * e) { 
15804   mp_print(mp, a); mp_print(mp, n); mp_print(mp, e);
15805 };
15806
15807 @ Another system-dependent routine is needed to convert three internal
15808 \MP\ strings
15809 to the |name_of_file| value that is used to open files. The present code
15810 allows both lowercase and uppercase letters in the file name.
15811 @^system dependencies@>
15812
15813 @d append_to_name(A) { c=(A); 
15814   if ( k<file_name_size ) {
15815     mp->name_of_file[k]=xchr(c);
15816     incr(k);
15817   }
15818 }
15819
15820 @<Declare subroutines for parsing file names@>=
15821 void mp_pack_file_name (MP mp, char *n, char *a, char *e) {
15822   integer k; /* number of positions filled in |name_of_file| */
15823   ASCII_code c; /* character being packed */
15824   char *j; /* a character  index */
15825   k=0;
15826   assert(n);
15827   if (a!=NULL) {
15828     for (j=a;*j;j++) { append_to_name(*j); }
15829   }
15830   for (j=n;*j;j++) { append_to_name(*j); }
15831   if (e!=NULL) {
15832     for (j=e;*j;j++) { append_to_name(*j); }
15833   }
15834   mp->name_of_file[k]=0;
15835   mp->name_length=k; 
15836 }
15837
15838 @ @<Internal library declarations@>=
15839 void mp_pack_file_name (MP mp, char *n, char *a, char *e) ;
15840
15841 @ A messier routine is also needed, since mem file names must be scanned
15842 before \MP's string mechanism has been initialized. We shall use the
15843 global variable |MP_mem_default| to supply the text for default system areas
15844 and extensions related to mem files.
15845 @^system dependencies@>
15846
15847 @d mem_default_length 9 /* length of the |MP_mem_default| string */
15848 @d mem_ext_length 4 /* length of its `\.{.mem}' part */
15849 @d mem_extension ".mem" /* the extension, as a \.{WEB} constant */
15850
15851 @<Glob...@>=
15852 char *MP_mem_default;
15853
15854 @ @<Option variables@>=
15855 char *mem_name; /* for commandline */
15856
15857 @ @<Allocate or initialize ...@>=
15858 mp->MP_mem_default = xstrdup("plain.mem");
15859 mp->mem_name = xstrdup(opt->mem_name);
15860 @.plain@>
15861 @^system dependencies@>
15862
15863 @ @<Dealloc variables@>=
15864 xfree(mp->MP_mem_default);
15865 xfree(mp->mem_name);
15866
15867 @ @<Check the ``constant'' values for consistency@>=
15868 if ( mem_default_length>file_name_size ) mp->bad=20;
15869
15870 @ Here is the messy routine that was just mentioned. It sets |name_of_file|
15871 from the first |n| characters of |MP_mem_default|, followed by
15872 |buffer[a..b-1]|, followed by the last |mem_ext_length| characters of
15873 |MP_mem_default|.
15874
15875 We dare not give error messages here, since \MP\ calls this routine before
15876 the |error| routine is ready to roll. Instead, we simply drop excess characters,
15877 since the error will be detected in another way when a strange file name
15878 isn't found.
15879 @^system dependencies@>
15880
15881 @c void mp_pack_buffered_name (MP mp,small_number n, integer a,
15882                                integer b) {
15883   integer k; /* number of positions filled in |name_of_file| */
15884   ASCII_code c; /* character being packed */
15885   integer j; /* index into |buffer| or |MP_mem_default| */
15886   if ( n+b-a+1+mem_ext_length>file_name_size )
15887     b=a+file_name_size-n-1-mem_ext_length;
15888   k=0;
15889   for (j=0;j<n;j++) {
15890     append_to_name(xord((int)mp->MP_mem_default[j]));
15891   }
15892   for (j=a;j<b;j++) {
15893     append_to_name(mp->buffer[j]);
15894   }
15895   for (j=mem_default_length-mem_ext_length;
15896       j<mem_default_length;j++) {
15897     append_to_name(xord((int)mp->MP_mem_default[j]));
15898   } 
15899   mp->name_of_file[k]=0;
15900   mp->name_length=k; 
15901 }
15902
15903 @ Here is the only place we use |pack_buffered_name|. This part of the program
15904 becomes active when a ``virgin'' \MP\ is trying to get going, just after
15905 the preliminary initialization, or when the user is substituting another
15906 mem file by typing `\.\&' after the initial `\.{**}' prompt.  The buffer
15907 contains the first line of input in |buffer[loc..(last-1)]|, where
15908 |loc<last| and |buffer[loc]<>" "|.
15909
15910 @<Declarations@>=
15911 boolean mp_open_mem_file (MP mp) ;
15912
15913 @ @c
15914 boolean mp_open_mem_file (MP mp) {
15915   int j; /* the first space after the file name */
15916   if (mp->mem_name!=NULL) {
15917     mp->mem_file = (mp->open_file)(mp->mem_name, "rb", mp_filetype_memfile);
15918     if ( mp->mem_file ) return true;
15919   }
15920   j=loc;
15921   if ( mp->buffer[loc]=='&' ) {
15922     incr(loc); j=loc; mp->buffer[mp->last]=' ';
15923     while ( mp->buffer[j]!=' ' ) incr(j);
15924     mp_pack_buffered_name(mp, 0,loc,j); /* try first without the system file area */
15925     if ( mp_w_open_in(mp, &mp->mem_file) ) goto FOUND;
15926     wake_up_terminal;
15927     wterm_ln("Sorry, I can\'t find that mem file; will try PLAIN.");
15928 @.Sorry, I can't find...@>
15929     update_terminal;
15930   }
15931   /* now pull out all the stops: try for the system \.{plain} file */
15932   mp_pack_buffered_name(mp, mem_default_length-mem_ext_length,0,0);
15933   if ( ! mp_w_open_in(mp, &mp->mem_file) ) {
15934     wake_up_terminal;
15935     wterm_ln("I can\'t find the PLAIN mem file!\n");
15936 @.I can't find PLAIN...@>
15937 @.plain@>
15938     return false;
15939   }
15940 FOUND:
15941   loc=j; return true;
15942 }
15943
15944 @ Operating systems often make it possible to determine the exact name (and
15945 possible version number) of a file that has been opened. The following routine,
15946 which simply makes a \MP\ string from the value of |name_of_file|, should
15947 ideally be changed to deduce the full name of file~|f|, which is the file
15948 most recently opened, if it is possible to do this.
15949 @^system dependencies@>
15950
15951 @<Declarations@>=
15952 #define mp_a_make_name_string(A,B)  mp_make_name_string(A)
15953 #define mp_b_make_name_string(A,B)  mp_make_name_string(A)
15954 #define mp_w_make_name_string(A,B)  mp_make_name_string(A)
15955
15956 @ @c 
15957 str_number mp_make_name_string (MP mp) {
15958   int k; /* index into |name_of_file| */
15959   str_room(mp->name_length);
15960   for (k=0;k<mp->name_length;k++) {
15961     append_char(xord((int)mp->name_of_file[k]));
15962   }
15963   return mp_make_string(mp);
15964 }
15965
15966 @ Now let's consider the ``driver''
15967 routines by which \MP\ deals with file names
15968 in a system-independent manner.  First comes a procedure that looks for a
15969 file name in the input by taking the information from the input buffer.
15970 (We can't use |get_next|, because the conversion to tokens would
15971 destroy necessary information.)
15972
15973 This procedure doesn't allow semicolons or percent signs to be part of
15974 file names, because of other conventions of \MP.
15975 {\sl The {\logos METAFONT\/}book} doesn't
15976 use semicolons or percents immediately after file names, but some users
15977 no doubt will find it natural to do so; therefore system-dependent
15978 changes to allow such characters in file names should probably
15979 be made with reluctance, and only when an entire file name that
15980 includes special characters is ``quoted'' somehow.
15981 @^system dependencies@>
15982
15983 @c void mp_scan_file_name (MP mp) { 
15984   mp_begin_name(mp);
15985   while ( mp->buffer[loc]==' ' ) incr(loc);
15986   while (1) { 
15987     if ( (mp->buffer[loc]==';')||(mp->buffer[loc]=='%') ) break;
15988     if ( ! mp_more_name(mp, mp->buffer[loc]) ) break;
15989     incr(loc);
15990   }
15991   mp_end_name(mp);
15992 }
15993
15994 @ Here is another version that takes its input from a string.
15995
15996 @<Declare subroutines for parsing file names@>=
15997 void mp_str_scan_file (MP mp,  str_number s) {
15998   pool_pointer p,q; /* current position and stopping point */
15999   mp_begin_name(mp);
16000   p=mp->str_start[s]; q=str_stop(s);
16001   while ( p<q ){ 
16002     if ( ! mp_more_name(mp, mp->str_pool[p]) ) break;
16003     incr(p);
16004   }
16005   mp_end_name(mp);
16006 }
16007
16008 @ And one that reads from a |char*|.
16009
16010 @<Declare subroutines for parsing file names@>=
16011 void mp_ptr_scan_file (MP mp,  char *s) {
16012   char *p, *q; /* current position and stopping point */
16013   mp_begin_name(mp);
16014   p=s; q=p+strlen(s);
16015   while ( p<q ){ 
16016     if ( ! mp_more_name(mp, *p)) break;
16017     p++;
16018   }
16019   mp_end_name(mp);
16020 }
16021
16022
16023 @ The global variable |job_name| contains the file name that was first
16024 \&{input} by the user. This name is extended by `\.{.log}' and `\.{ps}' and
16025 `\.{.mem}' and `\.{.tfm}' in order to make the names of \MP's output files.
16026
16027 @<Glob...@>=
16028 boolean log_opened; /* has the transcript file been opened? */
16029 char *log_name; /* full name of the log file */
16030
16031 @ @<Option variables@>=
16032 char *job_name; /* principal file name */
16033
16034 @ Initially |job_name=NULL|; it becomes nonzero as soon as the true name is known.
16035 We have |job_name=NULL| if and only if the `\.{log}' file has not been opened,
16036 except of course for a short time just after |job_name| has become nonzero.
16037
16038 @<Allocate or ...@>=
16039 mp->job_name=opt->job_name; 
16040 mp->log_opened=false;
16041
16042 @ @<Dealloc variables@>=
16043 xfree(mp->job_name);
16044
16045 @ Here is a routine that manufactures the output file names, assuming that
16046 |job_name<>0|. It ignores and changes the current settings of |cur_area|
16047 and |cur_ext|.
16048
16049 @d pack_cur_name mp_pack_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext)
16050
16051 @<Declarations@>=
16052 void mp_pack_job_name (MP mp, char *s) ;
16053
16054 @ @c void mp_pack_job_name (MP mp, char  *s) { /* |s = ".log"|, |".mem"|, |".ps"|, or .\\{nnn} */
16055   xfree(mp->cur_name); mp->cur_name=xstrdup(mp->job_name);
16056   xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
16057   xfree(mp->cur_ext);  mp->cur_ext=xstrdup(s);
16058   pack_cur_name;
16059 }
16060
16061 @ If some trouble arises when \MP\ tries to open a file, the following
16062 routine calls upon the user to supply another file name. Parameter~|s|
16063 is used in the error message to identify the type of file; parameter~|e|
16064 is the default extension if none is given. Upon exit from the routine,
16065 variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
16066 ready for another attempt at file opening.
16067
16068 @<Declarations@>=
16069 void mp_prompt_file_name (MP mp,char * s, char * e) ;
16070
16071 @ @c void mp_prompt_file_name (MP mp,char * s, char * e) {
16072   size_t k; /* index into |buffer| */
16073   char * saved_cur_name;
16074   if ( mp->interaction==mp_scroll_mode ) 
16075         wake_up_terminal;
16076   if (strcmp(s,"input file name")==0) {
16077         print_err("I can\'t find file `");
16078 @.I can't find file x@>
16079   } else {
16080         print_err("I can\'t write on file `");
16081   }
16082 @.I can't write on file x@>
16083   mp_print_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext); 
16084   mp_print(mp, "'.");
16085   if (strcmp(e,"")==0) 
16086         mp_show_context(mp);
16087   mp_print_nl(mp, "Please type another "); mp_print(mp, s);
16088 @.Please type...@>
16089   if ( mp->interaction<mp_scroll_mode )
16090     mp_fatal_error(mp, "*** (job aborted, file error in nonstop mode)");
16091 @.job aborted, file error...@>
16092   saved_cur_name = xstrdup(mp->cur_name);
16093   clear_terminal; prompt_input(": "); @<Scan file name in the buffer@>;
16094   if (strcmp(mp->cur_ext,"")==0) 
16095         mp->cur_ext=e;
16096   if (strlen(mp->cur_name)==0) {
16097     mp->cur_name=saved_cur_name;
16098   } else {
16099     xfree(saved_cur_name);
16100   }
16101   pack_cur_name;
16102 }
16103
16104 @ @<Scan file name in the buffer@>=
16105
16106   mp_begin_name(mp); k=mp->first;
16107   while ( (mp->buffer[k]==' ')&&(k<mp->last) ) incr(k);
16108   while (1) { 
16109     if ( k==mp->last ) break;
16110     if ( ! mp_more_name(mp, mp->buffer[k]) ) break;
16111     incr(k);
16112   }
16113   mp_end_name(mp);
16114 }
16115
16116 @ The |open_log_file| routine is used to open the transcript file and to help
16117 it catch up to what has previously been printed on the terminal.
16118
16119 @c void mp_open_log_file (MP mp) {
16120   int old_setting; /* previous |selector| setting */
16121   int k; /* index into |months| and |buffer| */
16122   int l; /* end of first input line */
16123   integer m; /* the current month */
16124   char *months="JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"; 
16125     /* abbreviations of month names */
16126   old_setting=mp->selector;
16127   if ( mp->job_name==NULL ) {
16128      mp->job_name=xstrdup("mpout");
16129   }
16130   mp_pack_job_name(mp,".log");
16131   while ( ! mp_a_open_out(mp, &mp->log_file, mp_filetype_log) ) {
16132     @<Try to get a different log file name@>;
16133   }
16134   mp->log_name=xstrdup(mp->name_of_file);
16135   mp->selector=log_only; mp->log_opened=true;
16136   @<Print the banner line, including the date and time@>;
16137   mp->input_stack[mp->input_ptr]=mp->cur_input; 
16138     /* make sure bottom level is in memory */
16139 @.**@>
16140   if (!mp->noninteractive) {
16141     mp_print_nl(mp, "**");
16142     l=mp->input_stack[0].limit_field-1; /* last position of first line */
16143     for (k=0;k<=l;k++) mp_print_str(mp, mp->buffer[k]);
16144     mp_print_ln(mp); /* now the transcript file contains the first line of input */
16145   }
16146   mp->selector=old_setting+2; /* |log_only| or |term_and_log| */
16147 }
16148
16149 @ @<Dealloc variables@>=
16150 xfree(mp->log_name);
16151
16152 @ Sometimes |open_log_file| is called at awkward moments when \MP\ is
16153 unable to print error messages or even to |show_context|.
16154 The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
16155 routine will not be invoked because |log_opened| will be false.
16156
16157 The normal idea of |mp_batch_mode| is that nothing at all should be written
16158 on the terminal. However, in the unusual case that
16159 no log file could be opened, we make an exception and allow
16160 an explanatory message to be seen.
16161
16162 Incidentally, the program always refers to the log file as a `\.{transcript
16163 file}', because some systems cannot use the extension `\.{.log}' for
16164 this file.
16165
16166 @<Try to get a different log file name@>=
16167 {  
16168   mp->selector=term_only;
16169   mp_prompt_file_name(mp, "transcript file name",".log");
16170 }
16171
16172 @ @<Print the banner...@>=
16173
16174   wlog(banner);
16175   mp_print(mp, mp->mem_ident); mp_print(mp, "  ");
16176   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_day])); 
16177   mp_print_char(mp, ' ');
16178   m=mp_round_unscaled(mp, mp->internal[mp_month]);
16179   for (k=3*m-3;k<3*m;k++) { wlog_chr(months[k]); }
16180   mp_print_char(mp, ' '); 
16181   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_year])); 
16182   mp_print_char(mp, ' ');
16183   m=mp_round_unscaled(mp, mp->internal[mp_time]);
16184   mp_print_dd(mp, m / 60); mp_print_char(mp, ':'); mp_print_dd(mp, m % 60);
16185 }
16186
16187 @ The |try_extension| function tries to open an input file determined by
16188 |cur_name|, |cur_area|, and the argument |ext|.  It returns |false| if it
16189 can't find the file in |cur_area| or the appropriate system area.
16190
16191 @c boolean mp_try_extension (MP mp,char *ext) { 
16192   mp_pack_file_name(mp, mp->cur_name,mp->cur_area, ext);
16193   in_name=xstrdup(mp->cur_name); 
16194   in_area=xstrdup(mp->cur_area);
16195   if ( mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16196     return true;
16197   } else { 
16198     mp_pack_file_name(mp, mp->cur_name,NULL,ext);
16199     return mp_a_open_in(mp, &cur_file, mp_filetype_program);
16200   }
16201   return false;
16202 }
16203
16204 @ Let's turn now to the procedure that is used to initiate file reading
16205 when an `\.{input}' command is being processed.
16206
16207 @c void mp_start_input (MP mp) { /* \MP\ will \.{input} something */
16208   char *fname = NULL;
16209   @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>;
16210   while (1) { 
16211     mp_begin_file_reading(mp); /* set up |cur_file| and new level of input */
16212     if ( strlen(mp->cur_ext)==0 ) {
16213       if ( mp_try_extension(mp, ".mp") ) break;
16214       else if ( mp_try_extension(mp, "") ) break;
16215       else if ( mp_try_extension(mp, ".mf") ) break;
16216       /* |else do_nothing; | */
16217     } else if ( mp_try_extension(mp, mp->cur_ext) ) {
16218       break;
16219     }
16220     mp_end_file_reading(mp); /* remove the level that didn't work */
16221     mp_prompt_file_name(mp, "input file name","");
16222   }
16223   name=mp_a_make_name_string(mp, cur_file);
16224   fname = xstrdup(mp->name_of_file);
16225   if ( mp->job_name==NULL ) {
16226     mp->job_name=xstrdup(mp->cur_name); 
16227     mp_open_log_file(mp);
16228   } /* |open_log_file| doesn't |show_context|, so |limit|
16229         and |loc| needn't be set to meaningful values yet */
16230   if ( ((int)mp->term_offset+(int)strlen(fname)) > (mp->max_print_line-2)) mp_print_ln(mp);
16231   else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
16232   mp_print_char(mp, '('); incr(mp->open_parens); mp_print(mp, fname); 
16233   xfree(fname);
16234   update_terminal;
16235   @<Flush |name| and replace it with |cur_name| if it won't be needed@>;
16236   @<Read the first line of the new file@>;
16237 }
16238
16239 @ This code should be omitted if |a_make_name_string| returns something other
16240 than just a copy of its argument and the full file name is needed for opening
16241 \.{MPX} files or implementing the switch-to-editor option.
16242 @^system dependencies@>
16243
16244 @<Flush |name| and replace it with |cur_name| if it won't be needed@>=
16245 mp_flush_string(mp, name); name=rts(mp->cur_name); xfree(mp->cur_name)
16246
16247 @ If the file is empty, it is considered to contain a single blank line,
16248 so there is no need to test the return value.
16249
16250 @<Read the first line...@>=
16251
16252   line=1;
16253   (void)mp_input_ln(mp, cur_file ); 
16254   mp_firm_up_the_line(mp);
16255   mp->buffer[limit]='%'; mp->first=limit+1; loc=start;
16256 }
16257
16258 @ @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>=
16259 while ( token_state &&(loc==null) ) mp_end_token_list(mp);
16260 if ( token_state ) { 
16261   print_err("File names can't appear within macros");
16262 @.File names can't...@>
16263   help3("Sorry...I've converted what follows to tokens,")
16264     ("possibly garbaging the name you gave.")
16265     ("Please delete the tokens and insert the name again.");
16266   mp_error(mp);
16267 }
16268 if ( file_state ) {
16269   mp_scan_file_name(mp);
16270 } else { 
16271    xfree(mp->cur_name); mp->cur_name=xstrdup(""); 
16272    xfree(mp->cur_ext);  mp->cur_ext =xstrdup(""); 
16273    xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
16274 }
16275
16276 @ The following simple routine starts reading the \.{MPX} file associated
16277 with the current input file.
16278
16279 @c void mp_start_mpx_input (MP mp) {
16280   char *origname = NULL; /* a copy of nameoffile */
16281   mp_pack_file_name(mp, in_name, in_area, ".mpx");
16282   @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16283     |goto not_found| if there is a problem@>;
16284   mp_begin_file_reading(mp);
16285   if ( ! mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16286     mp_end_file_reading(mp);
16287     goto NOT_FOUND;
16288   }
16289   name=mp_a_make_name_string(mp, cur_file);
16290   mp->mpx_name[index]=name; add_str_ref(name);
16291   @<Read the first line of the new file@>;
16292   return;
16293 NOT_FOUND: 
16294     @<Explain that the \.{MPX} file can't be read and |succumb|@>;
16295   xfree(origname);
16296 }
16297
16298 @ This should ideally be changed to do whatever is necessary to create the
16299 \.{MPX} file given by |name_of_file| if it does not exist or if it is out
16300 of date.  This requires invoking \.{MPtoTeX} on the |origname| and passing
16301 the results through \TeX\ and \.{DVItoMP}.  (It is possible to use a
16302 completely different typesetting program if suitable postprocessor is
16303 available to perform the function of \.{DVItoMP}.)
16304 @^system dependencies@>
16305
16306 @ @<Exported types@>=
16307 typedef int (*mp_run_make_mpx_command)(MP mp, char *origname, char *mtxname);
16308
16309 @ @<Option variables@>=
16310 mp_run_make_mpx_command run_make_mpx;
16311
16312 @ @<Allocate or initialize ...@>=
16313 set_callback_option(run_make_mpx);
16314
16315 @ @<Internal library declarations@>=
16316 int mp_run_make_mpx (MP mp, char *origname, char *mtxname);
16317
16318 @ The default does nothing.
16319 @c 
16320 int mp_run_make_mpx (MP mp, char *origname, char *mtxname) {
16321   if (mp && origname && mtxname) /* for -W */
16322     return false;
16323   return false;
16324 }
16325
16326 @ @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16327   |goto not_found| if there is a problem@>=
16328 origname = mp_xstrdup(mp,mp->name_of_file);
16329 *(origname+strlen(origname)-1)=0; /* drop the x */
16330 if (!(mp->run_make_mpx)(mp, origname, mp->name_of_file))
16331   goto NOT_FOUND 
16332
16333 @ @<Explain that the \.{MPX} file can't be read and |succumb|@>=
16334 if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16335 mp_print_nl(mp, ">> ");
16336 mp_print(mp, origname);
16337 mp_print_nl(mp, ">> ");
16338 mp_print(mp, mp->name_of_file);
16339 mp_print_nl(mp, "! Unable to make mpx file");
16340 help4("The two files given above are one of your source files")
16341   ("and an auxiliary file I need to read to find out what your")
16342   ("btex..etex blocks mean. If you don't know why I had trouble,")
16343   ("try running it manually through MPtoTeX, TeX, and DVItoMP");
16344 succumb;
16345
16346 @ The last file-opening commands are for files accessed via the \&{readfrom}
16347 @:read_from_}{\&{readfrom} primitive@>
16348 operator and the \&{write} command.  Such files are stored in separate arrays.
16349 @:write_}{\&{write} primitive@>
16350
16351 @<Types in the outer block@>=
16352 typedef unsigned int readf_index; /* |0..max_read_files| */
16353 typedef unsigned int write_index;  /* |0..max_write_files| */
16354
16355 @ @<Glob...@>=
16356 readf_index max_read_files; /* maximum number of simultaneously open \&{readfrom} files */
16357 void ** rd_file; /* \&{readfrom} files */
16358 char ** rd_fname; /* corresponding file name or 0 if file not open */
16359 readf_index read_files; /* number of valid entries in the above arrays */
16360 write_index max_write_files; /* maximum number of simultaneously open \&{write} */
16361 void ** wr_file; /* \&{write} files */
16362 char ** wr_fname; /* corresponding file name or 0 if file not open */
16363 write_index write_files; /* number of valid entries in the above arrays */
16364
16365 @ @<Allocate or initialize ...@>=
16366 mp->max_read_files=8;
16367 mp->rd_file = xmalloc((mp->max_read_files+1),sizeof(void *));
16368 mp->rd_fname = xmalloc((mp->max_read_files+1),sizeof(char *));
16369 memset(mp->rd_fname, 0, sizeof(char *)*(mp->max_read_files+1));
16370 mp->read_files=0;
16371 mp->max_write_files=8;
16372 mp->wr_file = xmalloc((mp->max_write_files+1),sizeof(void *));
16373 mp->wr_fname = xmalloc((mp->max_write_files+1),sizeof(char *));
16374 memset(mp->wr_fname, 0, sizeof(char *)*(mp->max_write_files+1));
16375 mp->write_files=0;
16376
16377
16378 @ This routine starts reading the file named by string~|s| without setting
16379 |loc|, |limit|, or |name|.  It returns |false| if the file is empty or cannot
16380 be opened.  Otherwise it updates |rd_file[n]| and |rd_fname[n]|.
16381
16382 @c boolean mp_start_read_input (MP mp,char *s, readf_index  n) {
16383   mp_ptr_scan_file(mp, s);
16384   pack_cur_name;
16385   mp_begin_file_reading(mp);
16386   if ( ! mp_a_open_in(mp, &mp->rd_file[n], (mp_filetype_text+n)) ) 
16387         goto NOT_FOUND;
16388   if ( ! mp_input_ln(mp, mp->rd_file[n] ) ) {
16389     (mp->close_file)(mp->rd_file[n]); 
16390         goto NOT_FOUND; 
16391   }
16392   mp->rd_fname[n]=xstrdup(mp->name_of_file);
16393   return true;
16394 NOT_FOUND: 
16395   mp_end_file_reading(mp);
16396   return false;
16397 }
16398
16399 @ Open |wr_file[n]| using file name~|s| and update |wr_fname[n]|.
16400
16401 @<Declarations@>=
16402 void mp_open_write_file (MP mp, char *s, readf_index  n) ;
16403
16404 @ @c void mp_open_write_file (MP mp,char *s, readf_index  n) {
16405   mp_ptr_scan_file(mp, s);
16406   pack_cur_name;
16407   while ( ! mp_a_open_out(mp, &mp->wr_file[n], (mp_filetype_text+n)) )
16408     mp_prompt_file_name(mp, "file name for write output","");
16409   mp->wr_fname[n]=xstrdup(mp->name_of_file);
16410 }
16411
16412
16413 @* \[36] Introduction to the parsing routines.
16414 We come now to the central nervous system that sparks many of \MP's activities.
16415 By evaluating expressions, from their primary constituents to ever larger
16416 subexpressions, \MP\ builds the structures that ultimately define complete
16417 pictures or fonts of type.
16418
16419 Four mutually recursive subroutines are involved in this process: We call them
16420 $$\hbox{|scan_primary|, |scan_secondary|, |scan_tertiary|,
16421 and |scan_expression|.}$$
16422 @^recursion@>
16423 Each of them is parameterless and begins with the first token to be scanned
16424 already represented in |cur_cmd|, |cur_mod|, and |cur_sym|. After execution,
16425 the value of the primary or secondary or tertiary or expression that was
16426 found will appear in the global variables |cur_type| and |cur_exp|. The
16427 token following the expression will be represented in |cur_cmd|, |cur_mod|,
16428 and |cur_sym|.
16429
16430 Technically speaking, the parsing algorithms are ``LL(1),'' more or less;
16431 backup mechanisms have been added in order to provide reasonable error
16432 recovery.
16433
16434 @<Glob...@>=
16435 small_number cur_type; /* the type of the expression just found */
16436 integer cur_exp; /* the value of the expression just found */
16437
16438 @ @<Set init...@>=
16439 mp->cur_exp=0;
16440
16441 @ Many different kinds of expressions are possible, so it is wise to have
16442 precise descriptions of what |cur_type| and |cur_exp| mean in all cases:
16443
16444 \smallskip\hang
16445 |cur_type=mp_vacuous| means that this expression didn't turn out to have a
16446 value at all, because it arose from a \&{begingroup}$\,\ldots\,$\&{endgroup}
16447 construction in which there was no expression before the \&{endgroup}.
16448 In this case |cur_exp| has some irrelevant value.
16449
16450 \smallskip\hang
16451 |cur_type=mp_boolean_type| means that |cur_exp| is either |true_code|
16452 or |false_code|.
16453
16454 \smallskip\hang
16455 |cur_type=mp_unknown_boolean| means that |cur_exp| points to a capsule
16456 node that is in the ring of variables equivalent
16457 to at least one undefined boolean variable.
16458
16459 \smallskip\hang
16460 |cur_type=mp_string_type| means that |cur_exp| is a string number (i.e., an
16461 integer in the range |0<=cur_exp<str_ptr|). That string's reference count
16462 includes this particular reference.
16463
16464 \smallskip\hang
16465 |cur_type=mp_unknown_string| means that |cur_exp| points to a capsule
16466 node that is in the ring of variables equivalent
16467 to at least one undefined string variable.
16468
16469 \smallskip\hang
16470 |cur_type=mp_pen_type| means that |cur_exp| points to a node in a pen.  Nobody
16471 else points to any of the nodes in this pen.  The pen may be polygonal or
16472 elliptical.
16473
16474 \smallskip\hang
16475 |cur_type=mp_unknown_pen| means that |cur_exp| points to a capsule
16476 node that is in the ring of variables equivalent
16477 to at least one undefined pen variable.
16478
16479 \smallskip\hang
16480 |cur_type=mp_path_type| means that |cur_exp| points to a the first node of
16481 a path; nobody else points to this particular path. The control points of
16482 the path will have been chosen.
16483
16484 \smallskip\hang
16485 |cur_type=mp_unknown_path| means that |cur_exp| points to a capsule
16486 node that is in the ring of variables equivalent
16487 to at least one undefined path variable.
16488
16489 \smallskip\hang
16490 |cur_type=mp_picture_type| means that |cur_exp| points to an edge header node.
16491 There may be other pointers to this particular set of edges.  The header node
16492 contains a reference count that includes this particular reference.
16493
16494 \smallskip\hang
16495 |cur_type=mp_unknown_picture| means that |cur_exp| points to a capsule
16496 node that is in the ring of variables equivalent
16497 to at least one undefined picture variable.
16498
16499 \smallskip\hang
16500 |cur_type=mp_transform_type| means that |cur_exp| points to a |mp_transform_type|
16501 capsule node. The |value| part of this capsule
16502 points to a transform node that contains six numeric values,
16503 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16504
16505 \smallskip\hang
16506 |cur_type=mp_color_type| means that |cur_exp| points to a |color_type|
16507 capsule node. The |value| part of this capsule
16508 points to a color node that contains three numeric values,
16509 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16510
16511 \smallskip\hang
16512 |cur_type=mp_cmykcolor_type| means that |cur_exp| points to a |mp_cmykcolor_type|
16513 capsule node. The |value| part of this capsule
16514 points to a color node that contains four numeric values,
16515 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16516
16517 \smallskip\hang
16518 |cur_type=mp_pair_type| means that |cur_exp| points to a capsule
16519 node whose type is |mp_pair_type|. The |value| part of this capsule
16520 points to a pair node that contains two numeric values,
16521 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16522
16523 \smallskip\hang
16524 |cur_type=mp_known| means that |cur_exp| is a |scaled| value.
16525
16526 \smallskip\hang
16527 |cur_type=mp_dependent| means that |cur_exp| points to a capsule node whose type
16528 is |dependent|. The |dep_list| field in this capsule points to the associated
16529 dependency list.
16530
16531 \smallskip\hang
16532 |cur_type=mp_proto_dependent| means that |cur_exp| points to a |mp_proto_dependent|
16533 capsule node. The |dep_list| field in this capsule
16534 points to the associated dependency list.
16535
16536 \smallskip\hang
16537 |cur_type=independent| means that |cur_exp| points to a capsule node
16538 whose type is |independent|. This somewhat unusual case can arise, for
16539 example, in the expression
16540 `$x+\&{begingroup}\penalty0\,\&{string}\,x; 0\,\&{endgroup}$'.
16541
16542 \smallskip\hang
16543 |cur_type=mp_token_list| means that |cur_exp| points to a linked list of
16544 tokens. This case arises only on the left-hand side of an assignment
16545 (`\.{:=}') operation, under very special circumstances.
16546
16547 \smallskip\noindent
16548 The possible settings of |cur_type| have been listed here in increasing
16549 numerical order. Notice that |cur_type| will never be |mp_numeric_type| or
16550 |suffixed_macro| or |mp_unsuffixed_macro|, although variables of those types
16551 are allowed.  Conversely, \MP\ has no variables of type |mp_vacuous| or
16552 |token_list|.
16553
16554 @ Capsules are two-word nodes that have a similar meaning
16555 to |cur_type| and |cur_exp|. Such nodes have |name_type=capsule|
16556 and |link<=mp_void|; and their |type| field is one of the possibilities for
16557 |cur_type| listed above.
16558
16559 The |value| field of a capsule is, in most cases, the value that
16560 corresponds to its |type|, as |cur_exp| corresponds to |cur_type|.
16561 However, when |cur_exp| would point to a capsule,
16562 no extra layer of indirection is present; the |value|
16563 field is what would have been called |value(cur_exp)| if it had not been
16564 encapsulated.  Furthermore, if the type is |dependent| or
16565 |mp_proto_dependent|, the |value| field of a capsule is replaced by
16566 |dep_list| and |prev_dep| fields, since dependency lists in capsules are
16567 always part of the general |dep_list| structure.
16568
16569 The |get_x_next| routine is careful not to change the values of |cur_type|
16570 and |cur_exp| when it gets an expanded token. However, |get_x_next| might
16571 call a macro, which might parse an expression, which might execute lots of
16572 commands in a group; hence it's possible that |cur_type| might change
16573 from, say, |mp_unknown_boolean| to |mp_boolean_type|, or from |dependent| to
16574 |known| or |independent|, during the time |get_x_next| is called. The
16575 programs below are careful to stash sensitive intermediate results in
16576 capsules, so that \MP's generality doesn't cause trouble.
16577
16578 Here's a procedure that illustrates these conventions. It takes
16579 the contents of $(|cur_type|\kern-.3pt,|cur_exp|\kern-.3pt)$
16580 and stashes them away in a
16581 capsule. It is not used when |cur_type=mp_token_list|.
16582 After the operation, |cur_type=mp_vacuous|; hence there is no need to
16583 copy path lists or to update reference counts, etc.
16584
16585 The special link |mp_void| is put on the capsule returned by
16586 |stash_cur_exp|, because this procedure is used to store macro parameters
16587 that must be easily distinguishable from token lists.
16588
16589 @<Declare the stashing/unstashing routines@>=
16590 pointer mp_stash_cur_exp (MP mp) {
16591   pointer p; /* the capsule that will be returned */
16592   switch (mp->cur_type) {
16593   case unknown_types:
16594   case mp_transform_type:
16595   case mp_color_type:
16596   case mp_pair_type:
16597   case mp_dependent:
16598   case mp_proto_dependent:
16599   case mp_independent: 
16600   case mp_cmykcolor_type:
16601     p=mp->cur_exp;
16602     break;
16603   default: 
16604     p=mp_get_node(mp, value_node_size); name_type(p)=mp_capsule;
16605     type(p)=mp->cur_type; value(p)=mp->cur_exp;
16606     break;
16607   }
16608   mp->cur_type=mp_vacuous; link(p)=mp_void; 
16609   return p;
16610 }
16611
16612 @ The inverse of |stash_cur_exp| is the following procedure, which
16613 deletes an unnecessary capsule and puts its contents into |cur_type|
16614 and |cur_exp|.
16615
16616 The program steps of \MP\ can be divided into two categories: those in
16617 which |cur_type| and |cur_exp| are ``alive'' and those in which they are
16618 ``dead,'' in the sense that |cur_type| and |cur_exp| contain relevant
16619 information or not. It's important not to ignore them when they're alive,
16620 and it's important not to pay attention to them when they're dead.
16621
16622 There's also an intermediate category: If |cur_type=mp_vacuous|, then
16623 |cur_exp| is irrelevant, hence we can proceed without caring if |cur_type|
16624 and |cur_exp| are alive or dead. In such cases we say that |cur_type|
16625 and |cur_exp| are {\sl dormant}. It is permissible to call |get_x_next|
16626 only when they are alive or dormant.
16627
16628 The \\{stash} procedure above assumes that |cur_type| and |cur_exp|
16629 are alive or dormant. The \\{unstash} procedure assumes that they are
16630 dead or dormant; it resuscitates them.
16631
16632 @<Declare the stashing/unstashing...@>=
16633 void mp_unstash_cur_exp (MP mp,pointer p) ;
16634
16635 @ @c
16636 void mp_unstash_cur_exp (MP mp,pointer p) { 
16637   mp->cur_type=type(p);
16638   switch (mp->cur_type) {
16639   case unknown_types:
16640   case mp_transform_type:
16641   case mp_color_type:
16642   case mp_pair_type:
16643   case mp_dependent: 
16644   case mp_proto_dependent:
16645   case mp_independent:
16646   case mp_cmykcolor_type: 
16647     mp->cur_exp=p;
16648     break;
16649   default:
16650     mp->cur_exp=value(p);
16651     mp_free_node(mp, p,value_node_size);
16652     break;
16653   }
16654 }
16655
16656 @ The following procedure prints the values of expressions in an
16657 abbreviated format. If its first parameter |p| is null, the value of
16658 |(cur_type,cur_exp)| is displayed; otherwise |p| should be a capsule
16659 containing the desired value. The second parameter controls the amount of
16660 output. If it is~0, dependency lists will be abbreviated to
16661 `\.{linearform}' unless they consist of a single term.  If it is greater
16662 than~1, complicated structures (pens, pictures, and paths) will be displayed
16663 in full.
16664
16665 @<Declare subroutines for printing expressions@>=
16666 @<Declare the procedure called |print_dp|@>;
16667 @<Declare the stashing/unstashing routines@>;
16668 void mp_print_exp (MP mp,pointer p, small_number verbosity) {
16669   boolean restore_cur_exp; /* should |cur_exp| be restored? */
16670   small_number t; /* the type of the expression */
16671   pointer q; /* a big node being displayed */
16672   integer v=0; /* the value of the expression */
16673   if ( p!=null ) {
16674     restore_cur_exp=false;
16675   } else { 
16676     p=mp_stash_cur_exp(mp); restore_cur_exp=true;
16677   }
16678   t=type(p);
16679   if ( t<mp_dependent ) v=value(p); else if ( t<mp_independent ) v=dep_list(p);
16680   @<Print an abbreviated value of |v| with format depending on |t|@>;
16681   if ( restore_cur_exp ) mp_unstash_cur_exp(mp, p);
16682 }
16683
16684 @ @<Print an abbreviated value of |v| with format depending on |t|@>=
16685 switch (t) {
16686 case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
16687 case mp_boolean_type:
16688   if ( v==true_code ) mp_print(mp, "true"); else mp_print(mp, "false");
16689   break;
16690 case unknown_types: case mp_numeric_type:
16691   @<Display a variable that's been declared but not defined@>;
16692   break;
16693 case mp_string_type:
16694   mp_print_char(mp, '"'); mp_print_str(mp, v); mp_print_char(mp, '"');
16695   break;
16696 case mp_pen_type: case mp_path_type: case mp_picture_type:
16697   @<Display a complex type@>;
16698   break;
16699 case mp_transform_type: case mp_color_type: case mp_pair_type: case mp_cmykcolor_type:
16700   if ( v==null ) mp_print_type(mp, t);
16701   else @<Display a big node@>;
16702   break;
16703 case mp_known:mp_print_scaled(mp, v); break;
16704 case mp_dependent: case mp_proto_dependent:
16705   mp_print_dp(mp, t,v,verbosity);
16706   break;
16707 case mp_independent:mp_print_variable_name(mp, p); break;
16708 default: mp_confusion(mp, "exp"); break;
16709 @:this can't happen exp}{\quad exp@>
16710 }
16711
16712 @ @<Display a big node@>=
16713
16714   mp_print_char(mp, '('); q=v+mp->big_node_size[t];
16715   do {  
16716     if ( type(v)==mp_known ) mp_print_scaled(mp, value(v));
16717     else if ( type(v)==mp_independent ) mp_print_variable_name(mp, v);
16718     else mp_print_dp(mp, type(v),dep_list(v),verbosity);
16719     v=v+2;
16720     if ( v!=q ) mp_print_char(mp, ',');
16721   } while (v!=q);
16722   mp_print_char(mp, ')');
16723 }
16724
16725 @ Values of type \&{picture}, \&{path}, and \&{pen} are displayed verbosely
16726 in the log file only, unless the user has given a positive value to
16727 \\{tracingonline}.
16728
16729 @<Display a complex type@>=
16730 if ( verbosity<=1 ) {
16731   mp_print_type(mp, t);
16732 } else { 
16733   if ( mp->selector==term_and_log )
16734    if ( mp->internal[mp_tracing_online]<=0 ) {
16735     mp->selector=term_only;
16736     mp_print_type(mp, t); mp_print(mp, " (see the transcript file)");
16737     mp->selector=term_and_log;
16738   };
16739   switch (t) {
16740   case mp_pen_type:mp_print_pen(mp, v,"",false); break;
16741   case mp_path_type:mp_print_path(mp, v,"",false); break;
16742   case mp_picture_type:mp_print_edges(mp, v,"",false); break;
16743   } /* there are no other cases */
16744 }
16745
16746 @ @<Declare the procedure called |print_dp|@>=
16747 void mp_print_dp (MP mp,small_number t, pointer p, 
16748                   small_number verbosity)  {
16749   pointer q; /* the node following |p| */
16750   q=link(p);
16751   if ( (info(q)==null) || (verbosity>0) ) mp_print_dependency(mp, p,t);
16752   else mp_print(mp, "linearform");
16753 }
16754
16755 @ The displayed name of a variable in a ring will not be a capsule unless
16756 the ring consists entirely of capsules.
16757
16758 @<Display a variable that's been declared but not defined@>=
16759 { mp_print_type(mp, t);
16760 if ( v!=null )
16761   { mp_print_char(mp, ' ');
16762   while ( (name_type(v)==mp_capsule) && (v!=p) ) v=value(v);
16763   mp_print_variable_name(mp, v);
16764   };
16765 }
16766
16767 @ When errors are detected during parsing, it is often helpful to
16768 display an expression just above the error message, using |exp_err|
16769 or |disp_err| instead of |print_err|.
16770
16771 @d exp_err(A) mp_disp_err(mp, null,(A)) /* displays the current expression */
16772
16773 @<Declare subroutines for printing expressions@>=
16774 void mp_disp_err (MP mp,pointer p, char *s) { 
16775   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16776   mp_print_nl(mp, ">> ");
16777 @.>>@>
16778   mp_print_exp(mp, p,1); /* ``medium verbose'' printing of the expression */
16779   if (strlen(s)) { 
16780     mp_print_nl(mp, "! "); mp_print(mp, s);
16781 @.!\relax@>
16782   }
16783 }
16784
16785 @ If |cur_type| and |cur_exp| contain relevant information that should
16786 be recycled, we will use the following procedure, which changes |cur_type|
16787 to |known| and stores a given value in |cur_exp|. We can think of |cur_type|
16788 and |cur_exp| as either alive or dormant after this has been done,
16789 because |cur_exp| will not contain a pointer value.
16790
16791 @ @c void mp_flush_cur_exp (MP mp,scaled v) { 
16792   switch (mp->cur_type) {
16793   case unknown_types: case mp_transform_type: case mp_color_type: case mp_pair_type:
16794   case mp_dependent: case mp_proto_dependent: case mp_independent: case mp_cmykcolor_type:
16795     mp_recycle_value(mp, mp->cur_exp); 
16796     mp_free_node(mp, mp->cur_exp,value_node_size);
16797     break;
16798   case mp_string_type:
16799     delete_str_ref(mp->cur_exp); break;
16800   case mp_pen_type: case mp_path_type: 
16801     mp_toss_knot_list(mp, mp->cur_exp); break;
16802   case mp_picture_type:
16803     delete_edge_ref(mp->cur_exp); break;
16804   default: 
16805     break;
16806   }
16807   mp->cur_type=mp_known; mp->cur_exp=v;
16808 }
16809
16810 @ There's a much more general procedure that is capable of releasing
16811 the storage associated with any two-word value packet.
16812
16813 @<Declare the recycling subroutines@>=
16814 void mp_recycle_value (MP mp,pointer p) ;
16815
16816 @ @c void mp_recycle_value (MP mp,pointer p) {
16817   small_number t; /* a type code */
16818   integer vv; /* another value */
16819   pointer q,r,s,pp; /* link manipulation registers */
16820   integer v=0; /* a value */
16821   t=type(p);
16822   if ( t<mp_dependent ) v=value(p);
16823   switch (t) {
16824   case undefined: case mp_vacuous: case mp_boolean_type: case mp_known:
16825   case mp_numeric_type:
16826     break;
16827   case unknown_types:
16828     mp_ring_delete(mp, p); break;
16829   case mp_string_type:
16830     delete_str_ref(v); break;
16831   case mp_path_type: case mp_pen_type:
16832     mp_toss_knot_list(mp, v); break;
16833   case mp_picture_type:
16834     delete_edge_ref(v); break;
16835   case mp_cmykcolor_type: case mp_pair_type: case mp_color_type:
16836   case mp_transform_type:
16837     @<Recycle a big node@>; break; 
16838   case mp_dependent: case mp_proto_dependent:
16839     @<Recycle a dependency list@>; break;
16840   case mp_independent:
16841     @<Recycle an independent variable@>; break;
16842   case mp_token_list: case mp_structured:
16843     mp_confusion(mp, "recycle"); break;
16844 @:this can't happen recycle}{\quad recycle@>
16845   case mp_unsuffixed_macro: case mp_suffixed_macro:
16846     mp_delete_mac_ref(mp, value(p)); break;
16847   } /* there are no other cases */
16848   type(p)=undefined;
16849 }
16850
16851 @ @<Recycle a big node@>=
16852 if ( v!=null ){ 
16853   q=v+mp->big_node_size[t];
16854   do {  
16855     q=q-2; mp_recycle_value(mp, q);
16856   } while (q!=v);
16857   mp_free_node(mp, v,mp->big_node_size[t]);
16858 }
16859
16860 @ @<Recycle a dependency list@>=
16861
16862   q=dep_list(p);
16863   while ( info(q)!=null ) q=link(q);
16864   link(prev_dep(p))=link(q);
16865   prev_dep(link(q))=prev_dep(p);
16866   link(q)=null; mp_flush_node_list(mp, dep_list(p));
16867 }
16868
16869 @ When an independent variable disappears, it simply fades away, unless
16870 something depends on it. In the latter case, a dependent variable whose
16871 coefficient of dependence is maximal will take its place.
16872 The relevant algorithm is due to Ignacio~A. Zabala, who implemented it
16873 as part of his Ph.D. thesis (Stanford University, December 1982).
16874 @^Zabala Salelles, Ignacio Andres@>
16875
16876 For example, suppose that variable $x$ is being recycled, and that the
16877 only variables depending on~$x$ are $y=2x+a$ and $z=x+b$. In this case
16878 we want to make $y$ independent and $z=.5y-.5a+b$; no other variables
16879 will depend on~$y$. If $\\{tracingequations}>0$ in this situation,
16880 we will print `\.{\#\#\# -2x=-y+a}'.
16881
16882 There's a slight complication, however: An independent variable $x$
16883 can occur both in dependency lists and in proto-dependency lists.
16884 This makes it necessary to be careful when deciding which coefficient
16885 is maximal.
16886
16887 Furthermore, this complication is not so slight when
16888 a proto-dependent variable is chosen to become independent. For example,
16889 suppose that $y=2x+100a$ is proto-dependent while $z=x+b$ is dependent;
16890 then we must change $z=.5y-50a+b$ to a proto-dependency, because of the
16891 large coefficient `50'.
16892
16893 In order to deal with these complications without wasting too much time,
16894 we shall link together the occurrences of~$x$ among all the linear
16895 dependencies, maintaining separate lists for the dependent and
16896 proto-dependent cases.
16897
16898 @<Recycle an independent variable@>=
16899
16900   mp->max_c[mp_dependent]=0; mp->max_c[mp_proto_dependent]=0;
16901   mp->max_link[mp_dependent]=null; mp->max_link[mp_proto_dependent]=null;
16902   q=link(dep_head);
16903   while ( q!=dep_head ) { 
16904     s=value_loc(q); /* now |link(s)=dep_list(q)| */
16905     while (1) { 
16906       r=link(s);
16907       if ( info(r)==null ) break;;
16908       if ( info(r)!=p ) { 
16909        s=r;
16910       } else  { 
16911         t=type(q); link(s)=link(r); info(r)=q;
16912         if ( abs(value(r))>mp->max_c[t] ) {
16913           @<Record a new maximum coefficient of type |t|@>;
16914         } else { 
16915           link(r)=mp->max_link[t]; mp->max_link[t]=r;
16916         }
16917       }
16918     }   
16919     q=link(r);
16920   }
16921   if ( (mp->max_c[mp_dependent]>0)||(mp->max_c[mp_proto_dependent]>0) ) {
16922     @<Choose a dependent variable to take the place of the disappearing
16923     independent variable, and change all remaining dependencies
16924     accordingly@>;
16925   }
16926 }
16927
16928 @ The code for independency removal makes use of three two-word arrays.
16929
16930 @<Glob...@>=
16931 integer max_c[mp_proto_dependent+1];  /* max coefficient magnitude */
16932 pointer max_ptr[mp_proto_dependent+1]; /* where |p| occurs with |max_c| */
16933 pointer max_link[mp_proto_dependent+1]; /* other occurrences of |p| */
16934
16935 @ @<Record a new maximum coefficient...@>=
16936
16937   if ( mp->max_c[t]>0 ) {
16938     link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
16939   }
16940   mp->max_c[t]=abs(value(r)); mp->max_ptr[t]=r;
16941 }
16942
16943 @ @<Choose a dependent...@>=
16944
16945   if ( (mp->max_c[mp_dependent] / 010000 >= mp->max_c[mp_proto_dependent]) )
16946     t=mp_dependent;
16947   else 
16948     t=mp_proto_dependent;
16949   @<Determine the dependency list |s| to substitute for the independent
16950     variable~|p|@>;
16951   t=mp_dependent+mp_proto_dependent-t; /* complement |t| */
16952   if ( mp->max_c[t]>0 ) { /* we need to pick up an unchosen dependency */ 
16953     link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
16954   }
16955   if ( t!=mp_dependent ) { @<Substitute new dependencies in place of |p|@>; }
16956   else { @<Substitute new proto-dependencies in place of |p|@>;}
16957   mp_flush_node_list(mp, s);
16958   if ( mp->fix_needed ) mp_fix_dependencies(mp);
16959   check_arith;
16960 }
16961
16962 @ Let |s=max_ptr[t]|. At this point we have $|value|(s)=\pm|max_c|[t]$,
16963 and |info(s)| points to the dependent variable~|pp| of type~|t| from
16964 whose dependency list we have removed node~|s|. We must reinsert
16965 node~|s| into the dependency list, with coefficient $-1.0$, and with
16966 |pp| as the new independent variable. Since |pp| will have a larger serial
16967 number than any other variable, we can put node |s| at the head of the
16968 list.
16969
16970 @<Determine the dep...@>=
16971 s=mp->max_ptr[t]; pp=info(s); v=value(s);
16972 if ( t==mp_dependent ) value(s)=-fraction_one; else value(s)=-unity;
16973 r=dep_list(pp); link(s)=r;
16974 while ( info(r)!=null ) r=link(r);
16975 q=link(r); link(r)=null;
16976 prev_dep(q)=prev_dep(pp); link(prev_dep(pp))=q;
16977 new_indep(pp);
16978 if ( mp->cur_exp==pp ) if ( mp->cur_type==t ) mp->cur_type=mp_independent;
16979 if ( mp->internal[mp_tracing_equations]>0 ) { 
16980   @<Show the transformed dependency@>; 
16981 }
16982
16983 @ Now $(-v)$ times the formerly independent variable~|p| is being replaced
16984 by the dependency list~|s|.
16985
16986 @<Show the transformed...@>=
16987 if ( mp_interesting(mp, p) ) {
16988   mp_begin_diagnostic(mp); mp_print_nl(mp, "### ");
16989 @:]]]\#\#\#_}{\.{\#\#\#}@>
16990   if ( v>0 ) mp_print_char(mp, '-');
16991   if ( t==mp_dependent ) vv=mp_round_fraction(mp, mp->max_c[mp_dependent]);
16992   else vv=mp->max_c[mp_proto_dependent];
16993   if ( vv!=unity ) mp_print_scaled(mp, vv);
16994   mp_print_variable_name(mp, p);
16995   while ( value(p) % s_scale>0 ) {
16996     mp_print(mp, "*4"); value(p)=value(p)-2;
16997   }
16998   if ( t==mp_dependent ) mp_print_char(mp, '='); else mp_print(mp, " = ");
16999   mp_print_dependency(mp, s,t);
17000   mp_end_diagnostic(mp, false);
17001 }
17002
17003 @ Finally, there are dependent and proto-dependent variables whose
17004 dependency lists must be brought up to date.
17005
17006 @<Substitute new dependencies...@>=
17007 for (t=mp_dependent;t<=mp_proto_dependent;t++){ 
17008   r=mp->max_link[t];
17009   while ( r!=null ) {
17010     q=info(r);
17011     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
17012      mp_make_fraction(mp, value(r),-v),s,t,mp_dependent);
17013     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
17014     q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
17015   }
17016 }
17017
17018 @ @<Substitute new proto...@>=
17019 for (t=mp_dependent;t<=mp_proto_dependent;t++) {
17020   r=mp->max_link[t];
17021   while ( r!=null ) {
17022     q=info(r);
17023     if ( t==mp_dependent ) { /* for safety's sake, we change |q| to |mp_proto_dependent| */
17024       if ( mp->cur_exp==q ) if ( mp->cur_type==mp_dependent )
17025         mp->cur_type=mp_proto_dependent;
17026       dep_list(q)=mp_p_over_v(mp, dep_list(q),unity,mp_dependent,mp_proto_dependent);
17027       type(q)=mp_proto_dependent; value(r)=mp_round_fraction(mp, value(r));
17028     }
17029     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
17030       mp_make_scaled(mp, value(r),-v),s,mp_proto_dependent,mp_proto_dependent);
17031     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
17032     q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
17033   }
17034 }
17035
17036 @ Here are some routines that provide handy combinations of actions
17037 that are often needed during error recovery. For example,
17038 `|flush_error|' flushes the current expression, replaces it by
17039 a given value, and calls |error|.
17040
17041 Errors often are detected after an extra token has already been scanned.
17042 The `\\{put\_get}' routines put that token back before calling |error|;
17043 then they get it back again. (Or perhaps they get another token, if
17044 the user has changed things.)
17045
17046 @<Declarations@>=
17047 void mp_flush_error (MP mp,scaled v);
17048 void mp_put_get_error (MP mp);
17049 void mp_put_get_flush_error (MP mp,scaled v) ;
17050
17051 @ @c
17052 void mp_flush_error (MP mp,scaled v) { 
17053   mp_error(mp); mp_flush_cur_exp(mp, v); 
17054 }
17055 void mp_put_get_error (MP mp) { 
17056   mp_back_error(mp); mp_get_x_next(mp); 
17057 }
17058 void mp_put_get_flush_error (MP mp,scaled v) { 
17059   mp_put_get_error(mp);
17060   mp_flush_cur_exp(mp, v); 
17061 }
17062
17063 @ A global variable |var_flag| is set to a special command code
17064 just before \MP\ calls |scan_expression|, if the expression should be
17065 treated as a variable when this command code immediately follows. For
17066 example, |var_flag| is set to |assignment| at the beginning of a
17067 statement, because we want to know the {\sl location\/} of a variable at
17068 the left of `\.{:=}', not the {\sl value\/} of that variable.
17069
17070 The |scan_expression| subroutine calls |scan_tertiary|,
17071 which calls |scan_secondary|, which calls |scan_primary|, which sets
17072 |var_flag:=0|. In this way each of the scanning routines ``knows''
17073 when it has been called with a special |var_flag|, but |var_flag| is
17074 usually zero.
17075
17076 A variable preceding a command that equals |var_flag| is converted to a
17077 token list rather than a value. Furthermore, an `\.{=}' sign following an
17078 expression with |var_flag=assignment| is not considered to be a relation
17079 that produces boolean expressions.
17080
17081
17082 @<Glob...@>=
17083 int var_flag; /* command that wants a variable */
17084
17085 @ @<Set init...@>=
17086 mp->var_flag=0;
17087
17088 @* \[37] Parsing primary expressions.
17089 The first parsing routine, |scan_primary|, is also the most complicated one,
17090 since it involves so many different cases. But each case---with one
17091 exception---is fairly simple by itself.
17092
17093 When |scan_primary| begins, the first token of the primary to be scanned
17094 should already appear in |cur_cmd|, |cur_mod|, and |cur_sym|. The values
17095 of |cur_type| and |cur_exp| should be either dead or dormant, as explained
17096 earlier. If |cur_cmd| is not between |min_primary_command| and
17097 |max_primary_command|, inclusive, a syntax error will be signaled.
17098
17099 @<Declare the basic parsing subroutines@>=
17100 void mp_scan_primary (MP mp) {
17101   pointer p,q,r; /* for list manipulation */
17102   quarterword c; /* a primitive operation code */
17103   int my_var_flag; /* initial value of |my_var_flag| */
17104   pointer l_delim,r_delim; /* hash addresses of a delimiter pair */
17105   @<Other local variables for |scan_primary|@>;
17106   my_var_flag=mp->var_flag; mp->var_flag=0;
17107 RESTART:
17108   check_arith;
17109   @<Supply diagnostic information, if requested@>;
17110   switch (mp->cur_cmd) {
17111   case left_delimiter:
17112     @<Scan a delimited primary@>; break;
17113   case begin_group:
17114     @<Scan a grouped primary@>; break;
17115   case string_token:
17116     @<Scan a string constant@>; break;
17117   case numeric_token:
17118     @<Scan a primary that starts with a numeric token@>; break;
17119   case nullary:
17120     @<Scan a nullary operation@>; break;
17121   case unary: case type_name: case cycle: case plus_or_minus:
17122     @<Scan a unary operation@>; break;
17123   case primary_binary:
17124     @<Scan a binary operation with `\&{of}' between its operands@>; break;
17125   case str_op:
17126     @<Convert a suffix to a string@>; break;
17127   case internal_quantity:
17128     @<Scan an internal numeric quantity@>; break;
17129   case capsule_token:
17130     mp_make_exp_copy(mp, mp->cur_mod); break;
17131   case tag_token:
17132     @<Scan a variable primary; |goto restart| if it turns out to be a macro@>; break;
17133   default: 
17134     mp_bad_exp(mp, "A primary"); goto RESTART; break;
17135 @.A primary expression...@>
17136   }
17137   mp_get_x_next(mp); /* the routines |goto done| if they don't want this */
17138 DONE: 
17139   if ( mp->cur_cmd==left_bracket ) {
17140     if ( mp->cur_type>=mp_known ) {
17141       @<Scan a mediation construction@>;
17142     }
17143   }
17144 }
17145
17146
17147
17148 @ Errors at the beginning of expressions are flagged by |bad_exp|.
17149
17150 @c void mp_bad_exp (MP mp,char * s) {
17151   int save_flag;
17152   print_err(s); mp_print(mp, " expression can't begin with `");
17153   mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); 
17154   mp_print_char(mp, '\'');
17155   help4("I'm afraid I need some sort of value in order to continue,")
17156     ("so I've tentatively inserted `0'. You may want to")
17157     ("delete this zero and insert something else;")
17158     ("see Chapter 27 of The METAFONTbook for an example.");
17159 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
17160   mp_back_input(mp); mp->cur_sym=0; mp->cur_cmd=numeric_token; 
17161   mp->cur_mod=0; mp_ins_error(mp);
17162   save_flag=mp->var_flag; mp->var_flag=0; mp_get_x_next(mp);
17163   mp->var_flag=save_flag;
17164 }
17165
17166 @ @<Supply diagnostic information, if requested@>=
17167 #ifdef DEBUG
17168 if ( mp->panicking ) mp_check_mem(mp, false);
17169 #endif
17170 if ( mp->interrupt!=0 ) if ( mp->OK_to_interrupt ) {
17171   mp_back_input(mp); check_interrupt; mp_get_x_next(mp);
17172 }
17173
17174 @ @<Scan a delimited primary@>=
17175
17176   l_delim=mp->cur_sym; r_delim=mp->cur_mod; 
17177   mp_get_x_next(mp); mp_scan_expression(mp);
17178   if ( (mp->cur_cmd==comma) && (mp->cur_type>=mp_known) ) {
17179     @<Scan the rest of a delimited set of numerics@>;
17180   } else {
17181     mp_check_delimiter(mp, l_delim,r_delim);
17182   }
17183 }
17184
17185 @ The |stash_in| subroutine puts the current (numeric) expression into a field
17186 within a ``big node.''
17187
17188 @c void mp_stash_in (MP mp,pointer p) {
17189   pointer q; /* temporary register */
17190   type(p)=mp->cur_type;
17191   if ( mp->cur_type==mp_known ) {
17192     value(p)=mp->cur_exp;
17193   } else { 
17194     if ( mp->cur_type==mp_independent ) {
17195       @<Stash an independent |cur_exp| into a big node@>;
17196     } else { 
17197       mp->mem[value_loc(p)]=mp->mem[value_loc(mp->cur_exp)];
17198       /* |dep_list(p):=dep_list(cur_exp)| and |prev_dep(p):=prev_dep(cur_exp)| */
17199       link(prev_dep(p))=p;
17200     }
17201     mp_free_node(mp, mp->cur_exp,value_node_size);
17202   }
17203   mp->cur_type=mp_vacuous;
17204 }
17205
17206 @ In rare cases the current expression can become |independent|. There
17207 may be many dependency lists pointing to such an independent capsule,
17208 so we can't simply move it into place within a big node. Instead,
17209 we copy it, then recycle it.
17210
17211 @ @<Stash an independent |cur_exp|...@>=
17212
17213   q=mp_single_dependency(mp, mp->cur_exp);
17214   if ( q==mp->dep_final ){ 
17215     type(p)=mp_known; value(p)=0; mp_free_node(mp, q,dep_node_size);
17216   } else { 
17217     type(p)=mp_dependent; mp_new_dep(mp, p,q);
17218   }
17219   mp_recycle_value(mp, mp->cur_exp);
17220 }
17221
17222 @ This code uses the fact that |red_part_loc| and |green_part_loc|
17223 are synonymous with |x_part_loc| and |y_part_loc|.
17224
17225 @<Scan the rest of a delimited set of numerics@>=
17226
17227 p=mp_stash_cur_exp(mp);
17228 mp_get_x_next(mp); mp_scan_expression(mp);
17229 @<Make sure the second part of a pair or color has a numeric type@>;
17230 q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
17231 if ( mp->cur_cmd==comma ) type(q)=mp_color_type;
17232 else type(q)=mp_pair_type;
17233 mp_init_big_node(mp, q); r=value(q);
17234 mp_stash_in(mp, y_part_loc(r));
17235 mp_unstash_cur_exp(mp, p);
17236 mp_stash_in(mp, x_part_loc(r));
17237 if ( mp->cur_cmd==comma ) {
17238   @<Scan the last of a triplet of numerics@>;
17239 }
17240 if ( mp->cur_cmd==comma ) {
17241   type(q)=mp_cmykcolor_type;
17242   mp_init_big_node(mp, q); t=value(q);
17243   mp->mem[cyan_part_loc(t)]=mp->mem[red_part_loc(r)];
17244   value(cyan_part_loc(t))=value(red_part_loc(r));
17245   mp->mem[magenta_part_loc(t)]=mp->mem[green_part_loc(r)];
17246   value(magenta_part_loc(t))=value(green_part_loc(r));
17247   mp->mem[yellow_part_loc(t)]=mp->mem[blue_part_loc(r)];
17248   value(yellow_part_loc(t))=value(blue_part_loc(r));
17249   mp_recycle_value(mp, r);
17250   r=t;
17251   @<Scan the last of a quartet of numerics@>;
17252 }
17253 mp_check_delimiter(mp, l_delim,r_delim);
17254 mp->cur_type=type(q);
17255 mp->cur_exp=q;
17256 }
17257
17258 @ @<Make sure the second part of a pair or color has a numeric type@>=
17259 if ( mp->cur_type<mp_known ) {
17260   exp_err("Nonnumeric ypart has been replaced by 0");
17261 @.Nonnumeric...replaced by 0@>
17262   help4("I've started to scan a pair `(a,b)' or a color `(a,b,c)';")
17263     ("but after finding a nice `a' I found a `b' that isn't")
17264     ("of numeric type. So I've changed that part to zero.")
17265     ("(The b that I didn't like appears above the error message.)");
17266   mp_put_get_flush_error(mp, 0);
17267 }
17268
17269 @ @<Scan the last of a triplet of numerics@>=
17270
17271   mp_get_x_next(mp); mp_scan_expression(mp);
17272   if ( mp->cur_type<mp_known ) {
17273     exp_err("Nonnumeric third part has been replaced by 0");
17274 @.Nonnumeric...replaced by 0@>
17275     help3("I've just scanned a color `(a,b,c)' or cmykcolor(a,b,c,d); but the `c'")
17276       ("isn't of numeric type. So I've changed that part to zero.")
17277       ("(The c that I didn't like appears above the error message.)");
17278     mp_put_get_flush_error(mp, 0);
17279   }
17280   mp_stash_in(mp, blue_part_loc(r));
17281 }
17282
17283 @ @<Scan the last of a quartet of numerics@>=
17284
17285   mp_get_x_next(mp); mp_scan_expression(mp);
17286   if ( mp->cur_type<mp_known ) {
17287     exp_err("Nonnumeric blackpart has been replaced by 0");
17288 @.Nonnumeric...replaced by 0@>
17289     help3("I've just scanned a cmykcolor `(c,m,y,k)'; but the `k' isn't")
17290       ("of numeric type. So I've changed that part to zero.")
17291       ("(The k that I didn't like appears above the error message.)");
17292     mp_put_get_flush_error(mp, 0);
17293   }
17294   mp_stash_in(mp, black_part_loc(r));
17295 }
17296
17297 @ The local variable |group_line| keeps track of the line
17298 where a \&{begingroup} command occurred; this will be useful
17299 in an error message if the group doesn't actually end.
17300
17301 @<Other local variables for |scan_primary|@>=
17302 integer group_line; /* where a group began */
17303
17304 @ @<Scan a grouped primary@>=
17305
17306   group_line=mp_true_line(mp);
17307   if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17308   save_boundary_item(p);
17309   do {  
17310     mp_do_statement(mp); /* ends with |cur_cmd>=semicolon| */
17311   } while (! (mp->cur_cmd!=semicolon));
17312   if ( mp->cur_cmd!=end_group ) {
17313     print_err("A group begun on line ");
17314 @.A group...never ended@>
17315     mp_print_int(mp, group_line);
17316     mp_print(mp, " never ended");
17317     help2("I saw a `begingroup' back there that hasn't been matched")
17318          ("by `endgroup'. So I've inserted `endgroup' now.");
17319     mp_back_error(mp); mp->cur_cmd=end_group;
17320   }
17321   mp_unsave(mp); 
17322     /* this might change |cur_type|, if independent variables are recycled */
17323   if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17324 }
17325
17326 @ @<Scan a string constant@>=
17327
17328   mp->cur_type=mp_string_type; mp->cur_exp=mp->cur_mod;
17329 }
17330
17331 @ Later we'll come to procedures that perform actual operations like
17332 addition, square root, and so on; our purpose now is to do the parsing.
17333 But we might as well mention those future procedures now, so that the
17334 suspense won't be too bad:
17335
17336 \smallskip
17337 |do_nullary(c)| does primitive operations that have no operands (e.g.,
17338 `\&{true}' or `\&{pencircle}');
17339
17340 \smallskip
17341 |do_unary(c)| applies a primitive operation to the current expression;
17342
17343 \smallskip
17344 |do_binary(p,c)| applies a primitive operation to the capsule~|p|
17345 and the current expression.
17346
17347 @<Scan a nullary operation@>=mp_do_nullary(mp, mp->cur_mod)
17348
17349 @ @<Scan a unary operation@>=
17350
17351   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_primary(mp); 
17352   mp_do_unary(mp, c); goto DONE;
17353 }
17354
17355 @ A numeric token might be a primary by itself, or it might be the
17356 numerator of a fraction composed solely of numeric tokens, or it might
17357 multiply the primary that follows (provided that the primary doesn't begin
17358 with a plus sign or a minus sign). The code here uses the facts that
17359 |max_primary_command=plus_or_minus| and
17360 |max_primary_command-1=numeric_token|. If a fraction is found that is less
17361 than unity, we try to retain higher precision when we use it in scalar
17362 multiplication.
17363
17364 @<Other local variables for |scan_primary|@>=
17365 scaled num,denom; /* for primaries that are fractions, like `1/2' */
17366
17367 @ @<Scan a primary that starts with a numeric token@>=
17368
17369   mp->cur_exp=mp->cur_mod; mp->cur_type=mp_known; mp_get_x_next(mp);
17370   if ( mp->cur_cmd!=slash ) { 
17371     num=0; denom=0;
17372   } else { 
17373     mp_get_x_next(mp);
17374     if ( mp->cur_cmd!=numeric_token ) { 
17375       mp_back_input(mp);
17376       mp->cur_cmd=slash; mp->cur_mod=over; mp->cur_sym=frozen_slash;
17377       goto DONE;
17378     }
17379     num=mp->cur_exp; denom=mp->cur_mod;
17380     if ( denom==0 ) { @<Protest division by zero@>; }
17381     else { mp->cur_exp=mp_make_scaled(mp, num,denom); }
17382     check_arith; mp_get_x_next(mp);
17383   }
17384   if ( mp->cur_cmd>=min_primary_command ) {
17385    if ( mp->cur_cmd<numeric_token ) { /* in particular, |cur_cmd<>plus_or_minus| */
17386      p=mp_stash_cur_exp(mp); mp_scan_primary(mp);
17387      if ( (abs(num)>=abs(denom))||(mp->cur_type<mp_color_type) ) {
17388        mp_do_binary(mp, p,times);
17389      } else {
17390        mp_frac_mult(mp, num,denom);
17391        mp_free_node(mp, p,value_node_size);
17392      }
17393     }
17394   }
17395   goto DONE;
17396 }
17397
17398 @ @<Protest division...@>=
17399
17400   print_err("Division by zero");
17401 @.Division by zero@>
17402   help1("I'll pretend that you meant to divide by 1."); mp_error(mp);
17403 }
17404
17405 @ @<Scan a binary operation with `\&{of}' between its operands@>=
17406
17407   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
17408   if ( mp->cur_cmd!=of_token ) {
17409     mp_missing_err(mp, "of"); mp_print(mp, " for "); 
17410     mp_print_cmd_mod(mp, primary_binary,c);
17411 @.Missing `of'@>
17412     help1("I've got the first argument; will look now for the other.");
17413     mp_back_error(mp);
17414   }
17415   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_primary(mp); 
17416   mp_do_binary(mp, p,c); goto DONE;
17417 }
17418
17419 @ @<Convert a suffix to a string@>=
17420
17421   mp_get_x_next(mp); mp_scan_suffix(mp); 
17422   mp->old_setting=mp->selector; mp->selector=new_string;
17423   mp_show_token_list(mp, mp->cur_exp,null,100000,0); 
17424   mp_flush_token_list(mp, mp->cur_exp);
17425   mp->cur_exp=mp_make_string(mp); mp->selector=mp->old_setting; 
17426   mp->cur_type=mp_string_type;
17427   goto DONE;
17428 }
17429
17430 @ If an internal quantity appears all by itself on the left of an
17431 assignment, we return a token list of length one, containing the address
17432 of the internal quantity plus |hash_end|. (This accords with the conventions
17433 of the save stack, as described earlier.)
17434
17435 @<Scan an internal...@>=
17436
17437   q=mp->cur_mod;
17438   if ( my_var_flag==assignment ) {
17439     mp_get_x_next(mp);
17440     if ( mp->cur_cmd==assignment ) {
17441       mp->cur_exp=mp_get_avail(mp);
17442       info(mp->cur_exp)=q+hash_end; mp->cur_type=mp_token_list; 
17443       goto DONE;
17444     }
17445     mp_back_input(mp);
17446   }
17447   mp->cur_type=mp_known; mp->cur_exp=mp->internal[q];
17448 }
17449
17450 @ The most difficult part of |scan_primary| has been saved for last, since
17451 it was necessary to build up some confidence first. We can now face the task
17452 of scanning a variable.
17453
17454 As we scan a variable, we build a token list containing the relevant
17455 names and subscript values, simultaneously following along in the
17456 ``collective'' structure to see if we are actually dealing with a macro
17457 instead of a value.
17458
17459 The local variables |pre_head| and |post_head| will point to the beginning
17460 of the prefix and suffix lists; |tail| will point to the end of the list
17461 that is currently growing.
17462
17463 Another local variable, |tt|, contains partial information about the
17464 declared type of the variable-so-far. If |tt>=mp_unsuffixed_macro|, the
17465 relation |tt=type(q)| will always hold. If |tt=undefined|, the routine
17466 doesn't bother to update its information about type. And if
17467 |undefined<tt<mp_unsuffixed_macro|, the precise value of |tt| isn't critical.
17468
17469 @ @<Other local variables for |scan_primary|@>=
17470 pointer pre_head,post_head,tail;
17471   /* prefix and suffix list variables */
17472 small_number tt; /* approximation to the type of the variable-so-far */
17473 pointer t; /* a token */
17474 pointer macro_ref = 0; /* reference count for a suffixed macro */
17475
17476 @ @<Scan a variable primary...@>=
17477
17478   fast_get_avail(pre_head); tail=pre_head; post_head=null; tt=mp_vacuous;
17479   while (1) { 
17480     t=mp_cur_tok(mp); link(tail)=t;
17481     if ( tt!=undefined ) {
17482        @<Find the approximate type |tt| and corresponding~|q|@>;
17483       if ( tt>=mp_unsuffixed_macro ) {
17484         @<Either begin an unsuffixed macro call or
17485           prepare for a suffixed one@>;
17486       }
17487     }
17488     mp_get_x_next(mp); tail=t;
17489     if ( mp->cur_cmd==left_bracket ) {
17490       @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>;
17491     }
17492     if ( mp->cur_cmd>max_suffix_token ) break;
17493     if ( mp->cur_cmd<min_suffix_token ) break;
17494   } /* now |cur_cmd| is |internal_quantity|, |tag_token|, or |numeric_token| */
17495   @<Handle unusual cases that masquerade as variables, and |goto restart|
17496     or |goto done| if appropriate;
17497     otherwise make a copy of the variable and |goto done|@>;
17498 }
17499
17500 @ @<Either begin an unsuffixed macro call or...@>=
17501
17502   link(tail)=null;
17503   if ( tt>mp_unsuffixed_macro ) { /* |tt=mp_suffixed_macro| */
17504     post_head=mp_get_avail(mp); tail=post_head; link(tail)=t;
17505     tt=undefined; macro_ref=value(q); add_mac_ref(macro_ref);
17506   } else {
17507     @<Set up unsuffixed macro call and |goto restart|@>;
17508   }
17509 }
17510
17511 @ @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>=
17512
17513   mp_get_x_next(mp); mp_scan_expression(mp);
17514   if ( mp->cur_cmd!=right_bracket ) {
17515     @<Put the left bracket and the expression back to be rescanned@>;
17516   } else { 
17517     if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17518     mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp; mp->cur_sym=0;
17519   }
17520 }
17521
17522 @ The left bracket that we thought was introducing a subscript might have
17523 actually been the left bracket in a mediation construction like `\.{x[a,b]}'.
17524 So we don't issue an error message at this point; but we do want to back up
17525 so as to avoid any embarrassment about our incorrect assumption.
17526
17527 @<Put the left bracket and the expression back to be rescanned@>=
17528
17529   mp_back_input(mp); /* that was the token following the current expression */
17530   mp_back_expr(mp); mp->cur_cmd=left_bracket; 
17531   mp->cur_mod=0; mp->cur_sym=frozen_left_bracket;
17532 }
17533
17534 @ Here's a routine that puts the current expression back to be read again.
17535
17536 @c void mp_back_expr (MP mp) {
17537   pointer p; /* capsule token */
17538   p=mp_stash_cur_exp(mp); link(p)=null; back_list(p);
17539 }
17540
17541 @ Unknown subscripts lead to the following error message.
17542
17543 @c void mp_bad_subscript (MP mp) { 
17544   exp_err("Improper subscript has been replaced by zero");
17545 @.Improper subscript...@>
17546   help3("A bracketed subscript must have a known numeric value;")
17547     ("unfortunately, what I found was the value that appears just")
17548     ("above this error message. So I'll try a zero subscript.");
17549   mp_flush_error(mp, 0);
17550 }
17551
17552 @ Every time we call |get_x_next|, there's a chance that the variable we've
17553 been looking at will disappear. Thus, we cannot safely keep |q| pointing
17554 into the variable structure; we need to start searching from the root each time.
17555
17556 @<Find the approximate type |tt| and corresponding~|q|@>=
17557 @^inner loop@>
17558
17559   p=link(pre_head); q=info(p); tt=undefined;
17560   if ( eq_type(q) % outer_tag==tag_token ) {
17561     q=equiv(q);
17562     if ( q==null ) goto DONE2;
17563     while (1) { 
17564       p=link(p);
17565       if ( p==null ) {
17566         tt=type(q); goto DONE2;
17567       };
17568       if ( type(q)!=mp_structured ) goto DONE2;
17569       q=link(attr_head(q)); /* the |collective_subscript| attribute */
17570       if ( p>=mp->hi_mem_min ) { /* it's not a subscript */
17571         do {  q=link(q); } while (! (attr_loc(q)>=info(p)));
17572         if ( attr_loc(q)>info(p) ) goto DONE2;
17573       }
17574     }
17575   }
17576 DONE2:
17577   ;
17578 }
17579
17580 @ How do things stand now? Well, we have scanned an entire variable name,
17581 including possible subscripts and/or attributes; |cur_cmd|, |cur_mod|, and
17582 |cur_sym| represent the token that follows. If |post_head=null|, a
17583 token list for this variable name starts at |link(pre_head)|, with all
17584 subscripts evaluated. But if |post_head<>null|, the variable turned out
17585 to be a suffixed macro; |pre_head| is the head of the prefix list, while
17586 |post_head| is the head of a token list containing both `\.{\AT!}' and
17587 the suffix.
17588
17589 Our immediate problem is to see if this variable still exists. (Variable
17590 structures can change drastically whenever we call |get_x_next|; users
17591 aren't supposed to do this, but the fact that it is possible means that
17592 we must be cautious.)
17593
17594 The following procedure prints an error message when a variable
17595 unexpectedly disappears. Its help message isn't quite right for
17596 our present purposes, but we'll be able to fix that up.
17597
17598 @c 
17599 void mp_obliterated (MP mp,pointer q) { 
17600   print_err("Variable "); mp_show_token_list(mp, q,null,1000,0);
17601   mp_print(mp, " has been obliterated");
17602 @.Variable...obliterated@>
17603   help5("It seems you did a nasty thing---probably by accident,")
17604     ("but nevertheless you nearly hornswoggled me...")
17605     ("While I was evaluating the right-hand side of this")
17606     ("command, something happened, and the left-hand side")
17607     ("is no longer a variable! So I won't change anything.");
17608 }
17609
17610 @ If the variable does exist, we also need to check
17611 for a few other special cases before deciding that a plain old ordinary
17612 variable has, indeed, been scanned.
17613
17614 @<Handle unusual cases that masquerade as variables...@>=
17615 if ( post_head!=null ) {
17616   @<Set up suffixed macro call and |goto restart|@>;
17617 }
17618 q=link(pre_head); free_avail(pre_head);
17619 if ( mp->cur_cmd==my_var_flag ) { 
17620   mp->cur_type=mp_token_list; mp->cur_exp=q; goto DONE;
17621 }
17622 p=mp_find_variable(mp, q);
17623 if ( p!=null ) {
17624   mp_make_exp_copy(mp, p);
17625 } else { 
17626   mp_obliterated(mp, q);
17627   mp->help_line[2]="While I was evaluating the suffix of this variable,";
17628   mp->help_line[1]="something was redefined, and it's no longer a variable!";
17629   mp->help_line[0]="In order to get back on my feet, I've inserted `0' instead.";
17630   mp_put_get_flush_error(mp, 0);
17631 }
17632 mp_flush_node_list(mp, q); 
17633 goto DONE
17634
17635 @ The only complication associated with macro calling is that the prefix
17636 and ``at'' parameters must be packaged in an appropriate list of lists.
17637
17638 @<Set up unsuffixed macro call and |goto restart|@>=
17639
17640   p=mp_get_avail(mp); info(pre_head)=link(pre_head); link(pre_head)=p;
17641   info(p)=t; mp_macro_call(mp, value(q),pre_head,null);
17642   mp_get_x_next(mp); 
17643   goto RESTART;
17644 }
17645
17646 @ If the ``variable'' that turned out to be a suffixed macro no longer exists,
17647 we don't care, because we have reserved a pointer (|macro_ref|) to its
17648 token list.
17649
17650 @<Set up suffixed macro call and |goto restart|@>=
17651
17652   mp_back_input(mp); p=mp_get_avail(mp); q=link(post_head);
17653   info(pre_head)=link(pre_head); link(pre_head)=post_head;
17654   info(post_head)=q; link(post_head)=p; info(p)=link(q); link(q)=null;
17655   mp_macro_call(mp, macro_ref,pre_head,null); decr(ref_count(macro_ref));
17656   mp_get_x_next(mp); goto RESTART;
17657 }
17658
17659 @ Our remaining job is simply to make a copy of the value that has been
17660 found. Some cases are harder than others, but complexity arises solely
17661 because of the multiplicity of possible cases.
17662
17663 @<Declare the procedure called |make_exp_copy|@>=
17664 @<Declare subroutines needed by |make_exp_copy|@>;
17665 void mp_make_exp_copy (MP mp,pointer p) {
17666   pointer q,r,t; /* registers for list manipulation */
17667 RESTART: 
17668   mp->cur_type=type(p);
17669   switch (mp->cur_type) {
17670   case mp_vacuous: case mp_boolean_type: case mp_known:
17671     mp->cur_exp=value(p); break;
17672   case unknown_types:
17673     mp->cur_exp=mp_new_ring_entry(mp, p);
17674     break;
17675   case mp_string_type: 
17676     mp->cur_exp=value(p); add_str_ref(mp->cur_exp);
17677     break;
17678   case mp_picture_type:
17679     mp->cur_exp=value(p);add_edge_ref(mp->cur_exp);
17680     break;
17681   case mp_pen_type:
17682     mp->cur_exp=copy_pen(value(p));
17683     break; 
17684   case mp_path_type:
17685     mp->cur_exp=mp_copy_path(mp, value(p));
17686     break;
17687   case mp_transform_type: case mp_color_type: 
17688   case mp_cmykcolor_type: case mp_pair_type:
17689     @<Copy the big node |p|@>;
17690     break;
17691   case mp_dependent: case mp_proto_dependent:
17692     mp_encapsulate(mp, mp_copy_dep_list(mp, dep_list(p)));
17693     break;
17694   case mp_numeric_type: 
17695     new_indep(p); goto RESTART;
17696     break;
17697   case mp_independent: 
17698     q=mp_single_dependency(mp, p);
17699     if ( q==mp->dep_final ){ 
17700       mp->cur_type=mp_known; mp->cur_exp=0; mp_free_node(mp, q,value_node_size);
17701     } else { 
17702       mp->cur_type=mp_dependent; mp_encapsulate(mp, q);
17703     }
17704     break;
17705   default: 
17706     mp_confusion(mp, "copy");
17707 @:this can't happen copy}{\quad copy@>
17708     break;
17709   }
17710 }
17711
17712 @ The |encapsulate| subroutine assumes that |dep_final| is the
17713 tail of dependency list~|p|.
17714
17715 @<Declare subroutines needed by |make_exp_copy|@>=
17716 void mp_encapsulate (MP mp,pointer p) { 
17717   mp->cur_exp=mp_get_node(mp, value_node_size); type(mp->cur_exp)=mp->cur_type;
17718   name_type(mp->cur_exp)=mp_capsule; mp_new_dep(mp, mp->cur_exp,p);
17719 }
17720
17721 @ The most tedious case arises when the user refers to a
17722 \&{pair}, \&{color}, or \&{transform} variable; we must copy several fields,
17723 each of which can be |independent|, |dependent|, |mp_proto_dependent|,
17724 or |known|.
17725
17726 @<Copy the big node |p|@>=
17727
17728   if ( value(p)==null ) 
17729     mp_init_big_node(mp, p);
17730   t=mp_get_node(mp, value_node_size); name_type(t)=mp_capsule; type(t)=mp->cur_type;
17731   mp_init_big_node(mp, t);
17732   q=value(p)+mp->big_node_size[mp->cur_type]; 
17733   r=value(t)+mp->big_node_size[mp->cur_type];
17734   do {  
17735     q=q-2; r=r-2; mp_install(mp, r,q);
17736   } while (q!=value(p));
17737   mp->cur_exp=t;
17738 }
17739
17740 @ The |install| procedure copies a numeric field~|q| into field~|r| of
17741 a big node that will be part of a capsule.
17742
17743 @<Declare subroutines needed by |make_exp_copy|@>=
17744 void mp_install (MP mp,pointer r, pointer q) {
17745   pointer p; /* temporary register */
17746   if ( type(q)==mp_known ){ 
17747     value(r)=value(q); type(r)=mp_known;
17748   } else  if ( type(q)==mp_independent ) {
17749     p=mp_single_dependency(mp, q);
17750     if ( p==mp->dep_final ) {
17751       type(r)=mp_known; value(r)=0; mp_free_node(mp, p,value_node_size);
17752     } else  { 
17753       type(r)=mp_dependent; mp_new_dep(mp, r,p);
17754     }
17755   } else {
17756     type(r)=type(q); mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(q)));
17757   }
17758 }
17759
17760 @ Expressions of the form `\.{a[b,c]}' are converted into
17761 `\.{b+a*(c-b)}', without checking the types of \.b~or~\.c,
17762 provided that \.a is numeric.
17763
17764 @<Scan a mediation...@>=
17765
17766   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17767   if ( mp->cur_cmd!=comma ) {
17768     @<Put the left bracket and the expression back...@>;
17769     mp_unstash_cur_exp(mp, p);
17770   } else { 
17771     q=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17772     if ( mp->cur_cmd!=right_bracket ) {
17773       mp_missing_err(mp, "]");
17774 @.Missing `]'@>
17775       help3("I've scanned an expression of the form `a[b,c',")
17776       ("so a right bracket should have come next.")
17777       ("I shall pretend that one was there.");
17778       mp_back_error(mp);
17779     }
17780     r=mp_stash_cur_exp(mp); mp_make_exp_copy(mp, q);
17781     mp_do_binary(mp, r,minus); mp_do_binary(mp, p,times); 
17782     mp_do_binary(mp, q,plus); mp_get_x_next(mp);
17783   }
17784 }
17785
17786 @ Here is a comparatively simple routine that is used to scan the
17787 \&{suffix} parameters of a macro.
17788
17789 @<Declare the basic parsing subroutines@>=
17790 void mp_scan_suffix (MP mp) {
17791   pointer h,t; /* head and tail of the list being built */
17792   pointer p; /* temporary register */
17793   h=mp_get_avail(mp); t=h;
17794   while (1) { 
17795     if ( mp->cur_cmd==left_bracket ) {
17796       @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>;
17797     }
17798     if ( mp->cur_cmd==numeric_token ) {
17799       p=mp_new_num_tok(mp, mp->cur_mod);
17800     } else if ((mp->cur_cmd==tag_token)||(mp->cur_cmd==internal_quantity) ) {
17801        p=mp_get_avail(mp); info(p)=mp->cur_sym;
17802     } else {
17803       break;
17804     }
17805     link(t)=p; t=p; mp_get_x_next(mp);
17806   }
17807   mp->cur_exp=link(h); free_avail(h); mp->cur_type=mp_token_list;
17808 }
17809
17810 @ @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>=
17811
17812   mp_get_x_next(mp); mp_scan_expression(mp);
17813   if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17814   if ( mp->cur_cmd!=right_bracket ) {
17815      mp_missing_err(mp, "]");
17816 @.Missing `]'@>
17817     help3("I've seen a `[' and a subscript value, in a suffix,")
17818       ("so a right bracket should have come next.")
17819       ("I shall pretend that one was there.");
17820     mp_back_error(mp);
17821   }
17822   mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp;
17823 }
17824
17825 @* \[38] Parsing secondary and higher expressions.
17826
17827 After the intricacies of |scan_primary|\kern-1pt,
17828 the |scan_secondary| routine is
17829 refreshingly simple. It's not trivial, but the operations are relatively
17830 straightforward; the main difficulty is, again, that expressions and data
17831 structures might change drastically every time we call |get_x_next|, so a
17832 cautious approach is mandatory. For example, a macro defined by
17833 \&{primarydef} might have disappeared by the time its second argument has
17834 been scanned; we solve this by increasing the reference count of its token
17835 list, so that the macro can be called even after it has been clobbered.
17836
17837 @<Declare the basic parsing subroutines@>=
17838 void mp_scan_secondary (MP mp) {
17839   pointer p; /* for list manipulation */
17840   halfword c,d; /* operation codes or modifiers */
17841   pointer mac_name; /* token defined with \&{primarydef} */
17842 RESTART:
17843   if ((mp->cur_cmd<min_primary_command)||
17844       (mp->cur_cmd>max_primary_command) )
17845     mp_bad_exp(mp, "A secondary");
17846 @.A secondary expression...@>
17847   mp_scan_primary(mp);
17848 CONTINUE: 
17849   if ( mp->cur_cmd<=max_secondary_command )
17850     if ( mp->cur_cmd>=min_secondary_command ) {
17851       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17852       if ( d==secondary_primary_macro ) { 
17853         mac_name=mp->cur_sym; add_mac_ref(c);
17854      }
17855      mp_get_x_next(mp); mp_scan_primary(mp);
17856      if ( d!=secondary_primary_macro ) {
17857        mp_do_binary(mp, p,c);
17858      } else  { 
17859        mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17860        decr(ref_count(c)); mp_get_x_next(mp); 
17861        goto RESTART;
17862     }
17863     goto CONTINUE;
17864   }
17865 }
17866
17867 @ The following procedure calls a macro that has two parameters,
17868 |p| and |cur_exp|.
17869
17870 @c void mp_binary_mac (MP mp,pointer p, pointer c, pointer n) {
17871   pointer q,r; /* nodes in the parameter list */
17872   q=mp_get_avail(mp); r=mp_get_avail(mp); link(q)=r;
17873   info(q)=p; info(r)=mp_stash_cur_exp(mp);
17874   mp_macro_call(mp, c,q,n);
17875 }
17876
17877 @ The next procedure, |scan_tertiary|, is pretty much the same deal.
17878
17879 @<Declare the basic parsing subroutines@>=
17880 void mp_scan_tertiary (MP mp) {
17881   pointer p; /* for list manipulation */
17882   halfword c,d; /* operation codes or modifiers */
17883   pointer mac_name; /* token defined with \&{secondarydef} */
17884 RESTART:
17885   if ((mp->cur_cmd<min_primary_command)||
17886       (mp->cur_cmd>max_primary_command) )
17887     mp_bad_exp(mp, "A tertiary");
17888 @.A tertiary expression...@>
17889   mp_scan_secondary(mp);
17890 CONTINUE: 
17891   if ( mp->cur_cmd<=max_tertiary_command ) {
17892     if ( mp->cur_cmd>=min_tertiary_command ) {
17893       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17894       if ( d==tertiary_secondary_macro ) { 
17895         mac_name=mp->cur_sym; add_mac_ref(c);
17896       };
17897       mp_get_x_next(mp); mp_scan_secondary(mp);
17898       if ( d!=tertiary_secondary_macro ) {
17899         mp_do_binary(mp, p,c);
17900       } else { 
17901         mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17902         decr(ref_count(c)); mp_get_x_next(mp); 
17903         goto RESTART;
17904       }
17905       goto CONTINUE;
17906     }
17907   }
17908 }
17909
17910 @ Finally we reach the deepest level in our quartet of parsing routines.
17911 This one is much like the others; but it has an extra complication from
17912 paths, which materialize here.
17913
17914 @d continue_path 25 /* a label inside of |scan_expression| */
17915 @d finish_path 26 /* another */
17916
17917 @<Declare the basic parsing subroutines@>=
17918 void mp_scan_expression (MP mp) {
17919   pointer p,q,r,pp,qq; /* for list manipulation */
17920   halfword c,d; /* operation codes or modifiers */
17921   int my_var_flag; /* initial value of |var_flag| */
17922   pointer mac_name; /* token defined with \&{tertiarydef} */
17923   boolean cycle_hit; /* did a path expression just end with `\&{cycle}'? */
17924   scaled x,y; /* explicit coordinates or tension at a path join */
17925   int t; /* knot type following a path join */
17926   t=0; y=0; x=0;
17927   my_var_flag=mp->var_flag; mac_name=null;
17928 RESTART:
17929   if ((mp->cur_cmd<min_primary_command)||
17930       (mp->cur_cmd>max_primary_command) )
17931     mp_bad_exp(mp, "An");
17932 @.An expression...@>
17933   mp_scan_tertiary(mp);
17934 CONTINUE: 
17935   if ( mp->cur_cmd<=max_expression_command )
17936     if ( mp->cur_cmd>=min_expression_command ) {
17937       if ( (mp->cur_cmd!=equals)||(my_var_flag!=assignment) ) {
17938         p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17939         if ( d==expression_tertiary_macro ) {
17940           mac_name=mp->cur_sym; add_mac_ref(c);
17941         }
17942         if ( (d<ampersand)||((d==ampersand)&&
17943              ((type(p)==mp_pair_type)||(type(p)==mp_path_type))) ) {
17944           @<Scan a path construction operation;
17945             but |return| if |p| has the wrong type@>;
17946         } else { 
17947           mp_get_x_next(mp); mp_scan_tertiary(mp);
17948           if ( d!=expression_tertiary_macro ) {
17949             mp_do_binary(mp, p,c);
17950           } else  { 
17951             mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17952             decr(ref_count(c)); mp_get_x_next(mp); 
17953             goto RESTART;
17954           }
17955         }
17956         goto CONTINUE;
17957      }
17958   }
17959 }
17960
17961 @ The reader should review the data structure conventions for paths before
17962 hoping to understand the next part of this code.
17963
17964 @<Scan a path construction operation...@>=
17965
17966   cycle_hit=false;
17967   @<Convert the left operand, |p|, into a partial path ending at~|q|;
17968     but |return| if |p| doesn't have a suitable type@>;
17969 CONTINUE_PATH: 
17970   @<Determine the path join parameters;
17971     but |goto finish_path| if there's only a direction specifier@>;
17972   if ( mp->cur_cmd==cycle ) {
17973     @<Get ready to close a cycle@>;
17974   } else { 
17975     mp_scan_tertiary(mp);
17976     @<Convert the right operand, |cur_exp|,
17977       into a partial path from |pp| to~|qq|@>;
17978   }
17979   @<Join the partial paths and reset |p| and |q| to the head and tail
17980     of the result@>;
17981   if ( mp->cur_cmd>=min_expression_command )
17982     if ( mp->cur_cmd<=ampersand ) if ( ! cycle_hit ) goto CONTINUE_PATH;
17983 FINISH_PATH:
17984   @<Choose control points for the path and put the result into |cur_exp|@>;
17985 }
17986
17987 @ @<Convert the left operand, |p|, into a partial path ending at~|q|...@>=
17988
17989   mp_unstash_cur_exp(mp, p);
17990   if ( mp->cur_type==mp_pair_type ) p=mp_new_knot(mp);
17991   else if ( mp->cur_type==mp_path_type ) p=mp->cur_exp;
17992   else return;
17993   q=p;
17994   while ( link(q)!=p ) q=link(q);
17995   if ( left_type(p)!=mp_endpoint ) { /* open up a cycle */
17996     r=mp_copy_knot(mp, p); link(q)=r; q=r;
17997   }
17998   left_type(p)=mp_open; right_type(q)=mp_open;
17999 }
18000
18001 @ A pair of numeric values is changed into a knot node for a one-point path
18002 when \MP\ discovers that the pair is part of a path.
18003
18004 @c@<Declare the procedure called |known_pair|@>;
18005 pointer mp_new_knot (MP mp) { /* convert a pair to a knot with two endpoints */
18006   pointer q; /* the new node */
18007   q=mp_get_node(mp, knot_node_size); left_type(q)=mp_endpoint;
18008   right_type(q)=mp_endpoint; originator(q)=mp_metapost_user; link(q)=q;
18009   mp_known_pair(mp); x_coord(q)=mp->cur_x; y_coord(q)=mp->cur_y;
18010   return q;
18011 }
18012
18013 @ The |known_pair| subroutine sets |cur_x| and |cur_y| to the components
18014 of the current expression, assuming that the current expression is a
18015 pair of known numerics. Unknown components are zeroed, and the
18016 current expression is flushed.
18017
18018 @<Declare the procedure called |known_pair|@>=
18019 void mp_known_pair (MP mp) {
18020   pointer p; /* the pair node */
18021   if ( mp->cur_type!=mp_pair_type ) {
18022     exp_err("Undefined coordinates have been replaced by (0,0)");
18023 @.Undefined coordinates...@>
18024     help5("I need x and y numbers for this part of the path.")
18025       ("The value I found (see above) was no good;")
18026       ("so I'll try to keep going by using zero instead.")
18027       ("(Chapter 27 of The METAFONTbook explains that")
18028 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18029       ("you might want to type `I ??" "?' now.)");
18030     mp_put_get_flush_error(mp, 0); mp->cur_x=0; mp->cur_y=0;
18031   } else { 
18032     p=value(mp->cur_exp);
18033      @<Make sure that both |x| and |y| parts of |p| are known;
18034        copy them into |cur_x| and |cur_y|@>;
18035     mp_flush_cur_exp(mp, 0);
18036   }
18037 }
18038
18039 @ @<Make sure that both |x| and |y| parts of |p| are known...@>=
18040 if ( type(x_part_loc(p))==mp_known ) {
18041   mp->cur_x=value(x_part_loc(p));
18042 } else { 
18043   mp_disp_err(mp, x_part_loc(p),
18044     "Undefined x coordinate has been replaced by 0");
18045 @.Undefined coordinates...@>
18046   help5("I need a `known' x value for this part of the path.")
18047     ("The value I found (see above) was no good;")
18048     ("so I'll try to keep going by using zero instead.")
18049     ("(Chapter 27 of The METAFONTbook explains that")
18050 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18051     ("you might want to type `I ??" "?' now.)");
18052   mp_put_get_error(mp); mp_recycle_value(mp, x_part_loc(p)); mp->cur_x=0;
18053 }
18054 if ( type(y_part_loc(p))==mp_known ) {
18055   mp->cur_y=value(y_part_loc(p));
18056 } else { 
18057   mp_disp_err(mp, y_part_loc(p),
18058     "Undefined y coordinate has been replaced by 0");
18059   help5("I need a `known' y value for this part of the path.")
18060     ("The value I found (see above) was no good;")
18061     ("so I'll try to keep going by using zero instead.")
18062     ("(Chapter 27 of The METAFONTbook explains that")
18063     ("you might want to type `I ??" "?' now.)");
18064   mp_put_get_error(mp); mp_recycle_value(mp, y_part_loc(p)); mp->cur_y=0;
18065 }
18066
18067 @ At this point |cur_cmd| is either |ampersand|, |left_brace|, or |path_join|.
18068
18069 @<Determine the path join parameters...@>=
18070 if ( mp->cur_cmd==left_brace ) {
18071   @<Put the pre-join direction information into node |q|@>;
18072 }
18073 d=mp->cur_cmd;
18074 if ( d==path_join ) {
18075   @<Determine the tension and/or control points@>;
18076 } else if ( d!=ampersand ) {
18077   goto FINISH_PATH;
18078 }
18079 mp_get_x_next(mp);
18080 if ( mp->cur_cmd==left_brace ) {
18081   @<Put the post-join direction information into |x| and |t|@>;
18082 } else if ( right_type(q)!=mp_explicit ) {
18083   t=mp_open; x=0;
18084 }
18085
18086 @ The |scan_direction| subroutine looks at the directional information
18087 that is enclosed in braces, and also scans ahead to the following character.
18088 A type code is returned, either |open| (if the direction was $(0,0)$),
18089 or |curl| (if the direction was a curl of known value |cur_exp|), or
18090 |given| (if the direction is given by the |angle| value that now
18091 appears in |cur_exp|).
18092
18093 There's nothing difficult about this subroutine, but the program is rather
18094 lengthy because a variety of potential errors need to be nipped in the bud.
18095
18096 @c small_number mp_scan_direction (MP mp) {
18097   int t; /* the type of information found */
18098   scaled x; /* an |x| coordinate */
18099   mp_get_x_next(mp);
18100   if ( mp->cur_cmd==curl_command ) {
18101      @<Scan a curl specification@>;
18102   } else {
18103     @<Scan a given direction@>;
18104   }
18105   if ( mp->cur_cmd!=right_brace ) {
18106     mp_missing_err(mp, "}");
18107 @.Missing `\char`\}'@>
18108     help3("I've scanned a direction spec for part of a path,")
18109       ("so a right brace should have come next.")
18110       ("I shall pretend that one was there.");
18111     mp_back_error(mp);
18112   }
18113   mp_get_x_next(mp); 
18114   return t;
18115 }
18116
18117 @ @<Scan a curl specification@>=
18118 { mp_get_x_next(mp); mp_scan_expression(mp);
18119 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<0) ){ 
18120   exp_err("Improper curl has been replaced by 1");
18121 @.Improper curl@>
18122   help1("A curl must be a known, nonnegative number.");
18123   mp_put_get_flush_error(mp, unity);
18124 }
18125 t=mp_curl;
18126 }
18127
18128 @ @<Scan a given direction@>=
18129 { mp_scan_expression(mp);
18130   if ( mp->cur_type>mp_pair_type ) {
18131     @<Get given directions separated by commas@>;
18132   } else {
18133     mp_known_pair(mp);
18134   }
18135   if ( (mp->cur_x==0)&&(mp->cur_y==0) )  t=mp_open;
18136   else  { t=mp_given; mp->cur_exp=mp_n_arg(mp, mp->cur_x,mp->cur_y);}
18137 }
18138
18139 @ @<Get given directions separated by commas@>=
18140
18141   if ( mp->cur_type!=mp_known ) {
18142     exp_err("Undefined x coordinate has been replaced by 0");
18143 @.Undefined coordinates...@>
18144     help5("I need a `known' x value for this part of the path.")
18145       ("The value I found (see above) was no good;")
18146       ("so I'll try to keep going by using zero instead.")
18147       ("(Chapter 27 of The METAFONTbook explains that")
18148 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18149       ("you might want to type `I ??" "?' now.)");
18150     mp_put_get_flush_error(mp, 0);
18151   }
18152   x=mp->cur_exp;
18153   if ( mp->cur_cmd!=comma ) {
18154     mp_missing_err(mp, ",");
18155 @.Missing `,'@>
18156     help2("I've got the x coordinate of a path direction;")
18157       ("will look for the y coordinate next.");
18158     mp_back_error(mp);
18159   }
18160   mp_get_x_next(mp); mp_scan_expression(mp);
18161   if ( mp->cur_type!=mp_known ) {
18162      exp_err("Undefined y coordinate has been replaced by 0");
18163     help5("I need a `known' y value for this part of the path.")
18164       ("The value I found (see above) was no good;")
18165       ("so I'll try to keep going by using zero instead.")
18166       ("(Chapter 27 of The METAFONTbook explains that")
18167       ("you might want to type `I ??" "?' now.)");
18168     mp_put_get_flush_error(mp, 0);
18169   }
18170   mp->cur_y=mp->cur_exp; mp->cur_x=x;
18171 }
18172
18173 @ At this point |right_type(q)| is usually |open|, but it may have been
18174 set to some other value by a previous splicing operation. We must maintain
18175 the value of |right_type(q)| in unusual cases such as
18176 `\.{..z1\{z2\}\&\{z3\}z1\{0,0\}..}'.
18177
18178 @<Put the pre-join...@>=
18179
18180   t=mp_scan_direction(mp);
18181   if ( t!=mp_open ) {
18182     right_type(q)=t; right_given(q)=mp->cur_exp;
18183     if ( left_type(q)==mp_open ) {
18184       left_type(q)=t; left_given(q)=mp->cur_exp;
18185     } /* note that |left_given(q)=left_curl(q)| */
18186   }
18187 }
18188
18189 @ Since |left_tension| and |left_y| share the same position in knot nodes,
18190 and since |left_given| is similarly equivalent to |left_x|, we use
18191 |x| and |y| to hold the given direction and tension information when
18192 there are no explicit control points.
18193
18194 @<Put the post-join...@>=
18195
18196   t=mp_scan_direction(mp);
18197   if ( right_type(q)!=mp_explicit ) x=mp->cur_exp;
18198   else t=mp_explicit; /* the direction information is superfluous */
18199 }
18200
18201 @ @<Determine the tension and/or...@>=
18202
18203   mp_get_x_next(mp);
18204   if ( mp->cur_cmd==tension ) {
18205     @<Set explicit tensions@>;
18206   } else if ( mp->cur_cmd==controls ) {
18207     @<Set explicit control points@>;
18208   } else  { 
18209     right_tension(q)=unity; y=unity; mp_back_input(mp); /* default tension */
18210     goto DONE;
18211   };
18212   if ( mp->cur_cmd!=path_join ) {
18213      mp_missing_err(mp, "..");
18214 @.Missing `..'@>
18215     help1("A path join command should end with two dots.");
18216     mp_back_error(mp);
18217   }
18218 DONE:
18219   ;
18220 }
18221
18222 @ @<Set explicit tensions@>=
18223
18224   mp_get_x_next(mp); y=mp->cur_cmd;
18225   if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18226   mp_scan_primary(mp);
18227   @<Make sure that the current expression is a valid tension setting@>;
18228   if ( y==at_least ) negate(mp->cur_exp);
18229   right_tension(q)=mp->cur_exp;
18230   if ( mp->cur_cmd==and_command ) {
18231     mp_get_x_next(mp); y=mp->cur_cmd;
18232     if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18233     mp_scan_primary(mp);
18234     @<Make sure that the current expression is a valid tension setting@>;
18235     if ( y==at_least ) negate(mp->cur_exp);
18236   }
18237   y=mp->cur_exp;
18238 }
18239
18240 @ @d min_tension three_quarter_unit
18241
18242 @<Make sure that the current expression is a valid tension setting@>=
18243 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<min_tension) ) {
18244   exp_err("Improper tension has been set to 1");
18245 @.Improper tension@>
18246   help1("The expression above should have been a number >=3/4.");
18247   mp_put_get_flush_error(mp, unity);
18248 }
18249
18250 @ @<Set explicit control points@>=
18251
18252   right_type(q)=mp_explicit; t=mp_explicit; mp_get_x_next(mp); mp_scan_primary(mp);
18253   mp_known_pair(mp); right_x(q)=mp->cur_x; right_y(q)=mp->cur_y;
18254   if ( mp->cur_cmd!=and_command ) {
18255     x=right_x(q); y=right_y(q);
18256   } else { 
18257     mp_get_x_next(mp); mp_scan_primary(mp);
18258     mp_known_pair(mp); x=mp->cur_x; y=mp->cur_y;
18259   }
18260 }
18261
18262 @ @<Convert the right operand, |cur_exp|, into a partial path...@>=
18263
18264   if ( mp->cur_type!=mp_path_type ) pp=mp_new_knot(mp);
18265   else pp=mp->cur_exp;
18266   qq=pp;
18267   while ( link(qq)!=pp ) qq=link(qq);
18268   if ( left_type(pp)!=mp_endpoint ) { /* open up a cycle */
18269     r=mp_copy_knot(mp, pp); link(qq)=r; qq=r;
18270   }
18271   left_type(pp)=mp_open; right_type(qq)=mp_open;
18272 }
18273
18274 @ If a person tries to define an entire path by saying `\.{(x,y)\&cycle}',
18275 we silently change the specification to `\.{(x,y)..cycle}', since a cycle
18276 shouldn't have length zero.
18277
18278 @<Get ready to close a cycle@>=
18279
18280   cycle_hit=true; mp_get_x_next(mp); pp=p; qq=p;
18281   if ( d==ampersand ) if ( p==q ) {
18282     d=path_join; right_tension(q)=unity; y=unity;
18283   }
18284 }
18285
18286 @ @<Join the partial paths and reset |p| and |q|...@>=
18287
18288 if ( d==ampersand ) {
18289   if ( (x_coord(q)!=x_coord(pp))||(y_coord(q)!=y_coord(pp)) ) {
18290     print_err("Paths don't touch; `&' will be changed to `..'");
18291 @.Paths don't touch@>
18292     help3("When you join paths `p&q', the ending point of p")
18293       ("must be exactly equal to the starting point of q.")
18294       ("So I'm going to pretend that you said `p..q' instead.");
18295     mp_put_get_error(mp); d=path_join; right_tension(q)=unity; y=unity;
18296   }
18297 }
18298 @<Plug an opening in |right_type(pp)|, if possible@>;
18299 if ( d==ampersand ) {
18300   @<Splice independent paths together@>;
18301 } else  { 
18302   @<Plug an opening in |right_type(q)|, if possible@>;
18303   link(q)=pp; left_y(pp)=y;
18304   if ( t!=mp_open ) { left_x(pp)=x; left_type(pp)=t;  };
18305 }
18306 q=qq;
18307 }
18308
18309 @ @<Plug an opening in |right_type(q)|...@>=
18310 if ( right_type(q)==mp_open ) {
18311   if ( (left_type(q)==mp_curl)||(left_type(q)==mp_given) ) {
18312     right_type(q)=left_type(q); right_given(q)=left_given(q);
18313   }
18314 }
18315
18316 @ @<Plug an opening in |right_type(pp)|...@>=
18317 if ( right_type(pp)==mp_open ) {
18318   if ( (t==mp_curl)||(t==mp_given) ) {
18319     right_type(pp)=t; right_given(pp)=x;
18320   }
18321 }
18322
18323 @ @<Splice independent paths together@>=
18324
18325   if ( left_type(q)==mp_open ) if ( right_type(q)==mp_open ) {
18326     left_type(q)=mp_curl; left_curl(q)=unity;
18327   }
18328   if ( right_type(pp)==mp_open ) if ( t==mp_open ) {
18329     right_type(pp)=mp_curl; right_curl(pp)=unity;
18330   }
18331   right_type(q)=right_type(pp); link(q)=link(pp);
18332   right_x(q)=right_x(pp); right_y(q)=right_y(pp);
18333   mp_free_node(mp, pp,knot_node_size);
18334   if ( qq==pp ) qq=q;
18335 }
18336
18337 @ @<Choose control points for the path...@>=
18338 if ( cycle_hit ) { 
18339   if ( d==ampersand ) p=q;
18340 } else  { 
18341   left_type(p)=mp_endpoint;
18342   if ( right_type(p)==mp_open ) { 
18343     right_type(p)=mp_curl; right_curl(p)=unity;
18344   }
18345   right_type(q)=mp_endpoint;
18346   if ( left_type(q)==mp_open ) { 
18347     left_type(q)=mp_curl; left_curl(q)=unity;
18348   }
18349   link(q)=p;
18350 }
18351 mp_make_choices(mp, p);
18352 mp->cur_type=mp_path_type; mp->cur_exp=p
18353
18354 @ Finally, we sometimes need to scan an expression whose value is
18355 supposed to be either |true_code| or |false_code|.
18356
18357 @<Declare the basic parsing subroutines@>=
18358 void mp_get_boolean (MP mp) { 
18359   mp_get_x_next(mp); mp_scan_expression(mp);
18360   if ( mp->cur_type!=mp_boolean_type ) {
18361     exp_err("Undefined condition will be treated as `false'");
18362 @.Undefined condition...@>
18363     help2("The expression shown above should have had a definite")
18364       ("true-or-false value. I'm changing it to `false'.");
18365     mp_put_get_flush_error(mp, false_code); mp->cur_type=mp_boolean_type;
18366   }
18367 }
18368
18369 @* \[39] Doing the operations.
18370 The purpose of parsing is primarily to permit people to avoid piles of
18371 parentheses. But the real work is done after the structure of an expression
18372 has been recognized; that's when new expressions are generated. We
18373 turn now to the guts of \MP, which handles individual operators that
18374 have come through the parsing mechanism.
18375
18376 We'll start with the easy ones that take no operands, then work our way
18377 up to operators with one and ultimately two arguments. In other words,
18378 we will write the three procedures |do_nullary|, |do_unary|, and |do_binary|
18379 that are invoked periodically by the expression scanners.
18380
18381 First let's make sure that all of the primitive operators are in the
18382 hash table. Although |scan_primary| and its relatives made use of the
18383 \\{cmd} code for these operators, the \\{do} routines base everything
18384 on the \\{mod} code. For example, |do_binary| doesn't care whether the
18385 operation it performs is a |primary_binary| or |secondary_binary|, etc.
18386
18387 @<Put each...@>=
18388 mp_primitive(mp, "true",nullary,true_code);
18389 @:true_}{\&{true} primitive@>
18390 mp_primitive(mp, "false",nullary,false_code);
18391 @:false_}{\&{false} primitive@>
18392 mp_primitive(mp, "nullpicture",nullary,null_picture_code);
18393 @:null_picture_}{\&{nullpicture} primitive@>
18394 mp_primitive(mp, "nullpen",nullary,null_pen_code);
18395 @:null_pen_}{\&{nullpen} primitive@>
18396 mp_primitive(mp, "jobname",nullary,job_name_op);
18397 @:job_name_}{\&{jobname} primitive@>
18398 mp_primitive(mp, "readstring",nullary,read_string_op);
18399 @:read_string_}{\&{readstring} primitive@>
18400 mp_primitive(mp, "pencircle",nullary,pen_circle);
18401 @:pen_circle_}{\&{pencircle} primitive@>
18402 mp_primitive(mp, "normaldeviate",nullary,normal_deviate);
18403 @:normal_deviate_}{\&{normaldeviate} primitive@>
18404 mp_primitive(mp, "readfrom",unary,read_from_op);
18405 @:read_from_}{\&{readfrom} primitive@>
18406 mp_primitive(mp, "closefrom",unary,close_from_op);
18407 @:close_from_}{\&{closefrom} primitive@>
18408 mp_primitive(mp, "odd",unary,odd_op);
18409 @:odd_}{\&{odd} primitive@>
18410 mp_primitive(mp, "known",unary,known_op);
18411 @:known_}{\&{known} primitive@>
18412 mp_primitive(mp, "unknown",unary,unknown_op);
18413 @:unknown_}{\&{unknown} primitive@>
18414 mp_primitive(mp, "not",unary,not_op);
18415 @:not_}{\&{not} primitive@>
18416 mp_primitive(mp, "decimal",unary,decimal);
18417 @:decimal_}{\&{decimal} primitive@>
18418 mp_primitive(mp, "reverse",unary,reverse);
18419 @:reverse_}{\&{reverse} primitive@>
18420 mp_primitive(mp, "makepath",unary,make_path_op);
18421 @:make_path_}{\&{makepath} primitive@>
18422 mp_primitive(mp, "makepen",unary,make_pen_op);
18423 @:make_pen_}{\&{makepen} primitive@>
18424 mp_primitive(mp, "oct",unary,oct_op);
18425 @:oct_}{\&{oct} primitive@>
18426 mp_primitive(mp, "hex",unary,hex_op);
18427 @:hex_}{\&{hex} primitive@>
18428 mp_primitive(mp, "ASCII",unary,ASCII_op);
18429 @:ASCII_}{\&{ASCII} primitive@>
18430 mp_primitive(mp, "char",unary,char_op);
18431 @:char_}{\&{char} primitive@>
18432 mp_primitive(mp, "length",unary,length_op);
18433 @:length_}{\&{length} primitive@>
18434 mp_primitive(mp, "turningnumber",unary,turning_op);
18435 @:turning_number_}{\&{turningnumber} primitive@>
18436 mp_primitive(mp, "xpart",unary,x_part);
18437 @:x_part_}{\&{xpart} primitive@>
18438 mp_primitive(mp, "ypart",unary,y_part);
18439 @:y_part_}{\&{ypart} primitive@>
18440 mp_primitive(mp, "xxpart",unary,xx_part);
18441 @:xx_part_}{\&{xxpart} primitive@>
18442 mp_primitive(mp, "xypart",unary,xy_part);
18443 @:xy_part_}{\&{xypart} primitive@>
18444 mp_primitive(mp, "yxpart",unary,yx_part);
18445 @:yx_part_}{\&{yxpart} primitive@>
18446 mp_primitive(mp, "yypart",unary,yy_part);
18447 @:yy_part_}{\&{yypart} primitive@>
18448 mp_primitive(mp, "redpart",unary,red_part);
18449 @:red_part_}{\&{redpart} primitive@>
18450 mp_primitive(mp, "greenpart",unary,green_part);
18451 @:green_part_}{\&{greenpart} primitive@>
18452 mp_primitive(mp, "bluepart",unary,blue_part);
18453 @:blue_part_}{\&{bluepart} primitive@>
18454 mp_primitive(mp, "cyanpart",unary,cyan_part);
18455 @:cyan_part_}{\&{cyanpart} primitive@>
18456 mp_primitive(mp, "magentapart",unary,magenta_part);
18457 @:magenta_part_}{\&{magentapart} primitive@>
18458 mp_primitive(mp, "yellowpart",unary,yellow_part);
18459 @:yellow_part_}{\&{yellowpart} primitive@>
18460 mp_primitive(mp, "blackpart",unary,black_part);
18461 @:black_part_}{\&{blackpart} primitive@>
18462 mp_primitive(mp, "greypart",unary,grey_part);
18463 @:grey_part_}{\&{greypart} primitive@>
18464 mp_primitive(mp, "colormodel",unary,color_model_part);
18465 @:color_model_part_}{\&{colormodel} primitive@>
18466 mp_primitive(mp, "fontpart",unary,font_part);
18467 @:font_part_}{\&{fontpart} primitive@>
18468 mp_primitive(mp, "textpart",unary,text_part);
18469 @:text_part_}{\&{textpart} primitive@>
18470 mp_primitive(mp, "pathpart",unary,path_part);
18471 @:path_part_}{\&{pathpart} primitive@>
18472 mp_primitive(mp, "penpart",unary,pen_part);
18473 @:pen_part_}{\&{penpart} primitive@>
18474 mp_primitive(mp, "dashpart",unary,dash_part);
18475 @:dash_part_}{\&{dashpart} primitive@>
18476 mp_primitive(mp, "sqrt",unary,sqrt_op);
18477 @:sqrt_}{\&{sqrt} primitive@>
18478 mp_primitive(mp, "mexp",unary,m_exp_op);
18479 @:m_exp_}{\&{mexp} primitive@>
18480 mp_primitive(mp, "mlog",unary,m_log_op);
18481 @:m_log_}{\&{mlog} primitive@>
18482 mp_primitive(mp, "sind",unary,sin_d_op);
18483 @:sin_d_}{\&{sind} primitive@>
18484 mp_primitive(mp, "cosd",unary,cos_d_op);
18485 @:cos_d_}{\&{cosd} primitive@>
18486 mp_primitive(mp, "floor",unary,floor_op);
18487 @:floor_}{\&{floor} primitive@>
18488 mp_primitive(mp, "uniformdeviate",unary,uniform_deviate);
18489 @:uniform_deviate_}{\&{uniformdeviate} primitive@>
18490 mp_primitive(mp, "charexists",unary,char_exists_op);
18491 @:char_exists_}{\&{charexists} primitive@>
18492 mp_primitive(mp, "fontsize",unary,font_size);
18493 @:font_size_}{\&{fontsize} primitive@>
18494 mp_primitive(mp, "llcorner",unary,ll_corner_op);
18495 @:ll_corner_}{\&{llcorner} primitive@>
18496 mp_primitive(mp, "lrcorner",unary,lr_corner_op);
18497 @:lr_corner_}{\&{lrcorner} primitive@>
18498 mp_primitive(mp, "ulcorner",unary,ul_corner_op);
18499 @:ul_corner_}{\&{ulcorner} primitive@>
18500 mp_primitive(mp, "urcorner",unary,ur_corner_op);
18501 @:ur_corner_}{\&{urcorner} primitive@>
18502 mp_primitive(mp, "arclength",unary,arc_length);
18503 @:arc_length_}{\&{arclength} primitive@>
18504 mp_primitive(mp, "angle",unary,angle_op);
18505 @:angle_}{\&{angle} primitive@>
18506 mp_primitive(mp, "cycle",cycle,cycle_op);
18507 @:cycle_}{\&{cycle} primitive@>
18508 mp_primitive(mp, "stroked",unary,stroked_op);
18509 @:stroked_}{\&{stroked} primitive@>
18510 mp_primitive(mp, "filled",unary,filled_op);
18511 @:filled_}{\&{filled} primitive@>
18512 mp_primitive(mp, "textual",unary,textual_op);
18513 @:textual_}{\&{textual} primitive@>
18514 mp_primitive(mp, "clipped",unary,clipped_op);
18515 @:clipped_}{\&{clipped} primitive@>
18516 mp_primitive(mp, "bounded",unary,bounded_op);
18517 @:bounded_}{\&{bounded} primitive@>
18518 mp_primitive(mp, "+",plus_or_minus,plus);
18519 @:+ }{\.{+} primitive@>
18520 mp_primitive(mp, "-",plus_or_minus,minus);
18521 @:- }{\.{-} primitive@>
18522 mp_primitive(mp, "*",secondary_binary,times);
18523 @:* }{\.{*} primitive@>
18524 mp_primitive(mp, "/",slash,over); mp->eqtb[frozen_slash]=mp->eqtb[mp->cur_sym];
18525 @:/ }{\.{/} primitive@>
18526 mp_primitive(mp, "++",tertiary_binary,pythag_add);
18527 @:++_}{\.{++} primitive@>
18528 mp_primitive(mp, "+-+",tertiary_binary,pythag_sub);
18529 @:+-+_}{\.{+-+} primitive@>
18530 mp_primitive(mp, "or",tertiary_binary,or_op);
18531 @:or_}{\&{or} primitive@>
18532 mp_primitive(mp, "and",and_command,and_op);
18533 @:and_}{\&{and} primitive@>
18534 mp_primitive(mp, "<",expression_binary,less_than);
18535 @:< }{\.{<} primitive@>
18536 mp_primitive(mp, "<=",expression_binary,less_or_equal);
18537 @:<=_}{\.{<=} primitive@>
18538 mp_primitive(mp, ">",expression_binary,greater_than);
18539 @:> }{\.{>} primitive@>
18540 mp_primitive(mp, ">=",expression_binary,greater_or_equal);
18541 @:>=_}{\.{>=} primitive@>
18542 mp_primitive(mp, "=",equals,equal_to);
18543 @:= }{\.{=} primitive@>
18544 mp_primitive(mp, "<>",expression_binary,unequal_to);
18545 @:<>_}{\.{<>} primitive@>
18546 mp_primitive(mp, "substring",primary_binary,substring_of);
18547 @:substring_}{\&{substring} primitive@>
18548 mp_primitive(mp, "subpath",primary_binary,subpath_of);
18549 @:subpath_}{\&{subpath} primitive@>
18550 mp_primitive(mp, "directiontime",primary_binary,direction_time_of);
18551 @:direction_time_}{\&{directiontime} primitive@>
18552 mp_primitive(mp, "point",primary_binary,point_of);
18553 @:point_}{\&{point} primitive@>
18554 mp_primitive(mp, "precontrol",primary_binary,precontrol_of);
18555 @:precontrol_}{\&{precontrol} primitive@>
18556 mp_primitive(mp, "postcontrol",primary_binary,postcontrol_of);
18557 @:postcontrol_}{\&{postcontrol} primitive@>
18558 mp_primitive(mp, "penoffset",primary_binary,pen_offset_of);
18559 @:pen_offset_}{\&{penoffset} primitive@>
18560 mp_primitive(mp, "arctime",primary_binary,arc_time_of);
18561 @:arc_time_of_}{\&{arctime} primitive@>
18562 mp_primitive(mp, "mpversion",nullary,mp_version);
18563 @:mp_verison_}{\&{mpversion} primitive@>
18564 mp_primitive(mp, "&",ampersand,concatenate);
18565 @:!!!}{\.{\&} primitive@>
18566 mp_primitive(mp, "rotated",secondary_binary,rotated_by);
18567 @:rotated_}{\&{rotated} primitive@>
18568 mp_primitive(mp, "slanted",secondary_binary,slanted_by);
18569 @:slanted_}{\&{slanted} primitive@>
18570 mp_primitive(mp, "scaled",secondary_binary,scaled_by);
18571 @:scaled_}{\&{scaled} primitive@>
18572 mp_primitive(mp, "shifted",secondary_binary,shifted_by);
18573 @:shifted_}{\&{shifted} primitive@>
18574 mp_primitive(mp, "transformed",secondary_binary,transformed_by);
18575 @:transformed_}{\&{transformed} primitive@>
18576 mp_primitive(mp, "xscaled",secondary_binary,x_scaled);
18577 @:x_scaled_}{\&{xscaled} primitive@>
18578 mp_primitive(mp, "yscaled",secondary_binary,y_scaled);
18579 @:y_scaled_}{\&{yscaled} primitive@>
18580 mp_primitive(mp, "zscaled",secondary_binary,z_scaled);
18581 @:z_scaled_}{\&{zscaled} primitive@>
18582 mp_primitive(mp, "infont",secondary_binary,in_font);
18583 @:in_font_}{\&{infont} primitive@>
18584 mp_primitive(mp, "intersectiontimes",tertiary_binary,intersect);
18585 @:intersection_times_}{\&{intersectiontimes} primitive@>
18586 mp_primitive(mp, "envelope",primary_binary,envelope_of);
18587 @:envelope_}{\&{envelope} primitive@>
18588
18589 @ @<Cases of |print_cmd...@>=
18590 case nullary:
18591 case unary:
18592 case primary_binary:
18593 case secondary_binary:
18594 case tertiary_binary:
18595 case expression_binary:
18596 case cycle:
18597 case plus_or_minus:
18598 case slash:
18599 case ampersand:
18600 case equals:
18601 case and_command:
18602   mp_print_op(mp, m);
18603   break;
18604
18605 @ OK, let's look at the simplest \\{do} procedure first.
18606
18607 @c @<Declare nullary action procedure@>;
18608 void mp_do_nullary (MP mp,quarterword c) { 
18609   check_arith;
18610   if ( mp->internal[mp_tracing_commands]>two )
18611     mp_show_cmd_mod(mp, nullary,c);
18612   switch (c) {
18613   case true_code: case false_code: 
18614     mp->cur_type=mp_boolean_type; mp->cur_exp=c;
18615     break;
18616   case null_picture_code: 
18617     mp->cur_type=mp_picture_type;
18618     mp->cur_exp=mp_get_node(mp, edge_header_size); 
18619     mp_init_edges(mp, mp->cur_exp);
18620     break;
18621   case null_pen_code: 
18622     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, 0);
18623     break;
18624   case normal_deviate: 
18625     mp->cur_type=mp_known; mp->cur_exp=mp_norm_rand(mp);
18626     break;
18627   case pen_circle: 
18628     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, unity);
18629     break;
18630   case job_name_op:  
18631     if ( mp->job_name==NULL ) mp_open_log_file(mp);
18632     mp->cur_type=mp_string_type; mp->cur_exp=rts(mp->job_name);
18633     break;
18634   case mp_version: 
18635     mp->cur_type=mp_string_type; 
18636     mp->cur_exp=intern(metapost_version) ;
18637     break;
18638   case read_string_op:
18639     @<Read a string from the terminal@>;
18640     break;
18641   } /* there are no other cases */
18642   check_arith;
18643 }
18644
18645 @ @<Read a string...@>=
18646
18647   if ( mp->interaction<=mp_nonstop_mode )
18648     mp_fatal_error(mp, "*** (cannot readstring in nonstop modes)");
18649   mp_begin_file_reading(mp); name=is_read;
18650   limit=start; prompt_input("");
18651   mp_finish_read(mp);
18652 }
18653
18654 @ @<Declare nullary action procedure@>=
18655 void mp_finish_read (MP mp) { /* copy |buffer| line to |cur_exp| */
18656   size_t k;
18657   str_room((int)mp->last-start);
18658   for (k=start;k<=mp->last-1;k++) {
18659    append_char(mp->buffer[k]);
18660   }
18661   mp_end_file_reading(mp); mp->cur_type=mp_string_type; 
18662   mp->cur_exp=mp_make_string(mp);
18663 }
18664
18665 @ Things get a bit more interesting when there's an operand. The
18666 operand to |do_unary| appears in |cur_type| and |cur_exp|.
18667
18668 @c @<Declare unary action procedures@>;
18669 void mp_do_unary (MP mp,quarterword c) {
18670   pointer p,q,r; /* for list manipulation */
18671   integer x; /* a temporary register */
18672   check_arith;
18673   if ( mp->internal[mp_tracing_commands]>two )
18674     @<Trace the current unary operation@>;
18675   switch (c) {
18676   case plus:
18677     if ( mp->cur_type<mp_color_type ) mp_bad_unary(mp, plus);
18678     break;
18679   case minus:
18680     @<Negate the current expression@>;
18681     break;
18682   @<Additional cases of unary operators@>;
18683   } /* there are no other cases */
18684   check_arith;
18685 };
18686
18687 @ The |nice_pair| function returns |true| if both components of a pair
18688 are known.
18689
18690 @<Declare unary action procedures@>=
18691 boolean mp_nice_pair (MP mp,integer p, quarterword t) { 
18692   if ( t==mp_pair_type ) {
18693     p=value(p);
18694     if ( type(x_part_loc(p))==mp_known )
18695       if ( type(y_part_loc(p))==mp_known )
18696         return true;
18697   }
18698   return false;
18699 }
18700
18701 @ The |nice_color_or_pair| function is analogous except that it also accepts
18702 fully known colors.
18703
18704 @<Declare unary action procedures@>=
18705 boolean mp_nice_color_or_pair (MP mp,integer p, quarterword t) {
18706   pointer q,r; /* for scanning the big node */
18707   if ( (t!=mp_pair_type)&&(t!=mp_color_type)&&(t!=mp_cmykcolor_type) ) {
18708     return false;
18709   } else { 
18710     q=value(p);
18711     r=q+mp->big_node_size[type(p)];
18712     do {  
18713       r=r-2;
18714       if ( type(r)!=mp_known )
18715         return false;
18716     } while (r!=q);
18717     return true;
18718   }
18719 }
18720
18721 @ @<Declare unary action...@>=
18722 void mp_print_known_or_unknown_type (MP mp,small_number t, integer v) { 
18723   mp_print_char(mp, '(');
18724   if ( t>mp_known ) mp_print(mp, "unknown numeric");
18725   else { if ( (t==mp_pair_type)||(t==mp_color_type)||(t==mp_cmykcolor_type) )
18726     if ( ! mp_nice_color_or_pair(mp, v,t) ) mp_print(mp, "unknown ");
18727     mp_print_type(mp, t);
18728   }
18729   mp_print_char(mp, ')');
18730 }
18731
18732 @ @<Declare unary action...@>=
18733 void mp_bad_unary (MP mp,quarterword c) { 
18734   exp_err("Not implemented: "); mp_print_op(mp, c);
18735 @.Not implemented...@>
18736   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
18737   help3("I'm afraid I don't know how to apply that operation to that")
18738     ("particular type. Continue, and I'll simply return the")
18739     ("argument (shown above) as the result of the operation.");
18740   mp_put_get_error(mp);
18741 }
18742
18743 @ @<Trace the current unary operation@>=
18744
18745   mp_begin_diagnostic(mp); mp_print_nl(mp, "{"); 
18746   mp_print_op(mp, c); mp_print_char(mp, '(');
18747   mp_print_exp(mp, null,0); /* show the operand, but not verbosely */
18748   mp_print(mp, ")}"); mp_end_diagnostic(mp, false);
18749 }
18750
18751 @ Negation is easy except when the current expression
18752 is of type |independent|, or when it is a pair with one or more
18753 |independent| components.
18754
18755 It is tempting to argue that the negative of an independent variable
18756 is an independent variable, hence we don't have to do anything when
18757 negating it. The fallacy is that other dependent variables pointing
18758 to the current expression must change the sign of their
18759 coefficients if we make no change to the current expression.
18760
18761 Instead, we work around the problem by copying the current expression
18762 and recycling it afterwards (cf.~the |stash_in| routine).
18763
18764 @<Negate the current expression@>=
18765 switch (mp->cur_type) {
18766 case mp_color_type:
18767 case mp_cmykcolor_type:
18768 case mp_pair_type:
18769 case mp_independent: 
18770   q=mp->cur_exp; mp_make_exp_copy(mp, q);
18771   if ( mp->cur_type==mp_dependent ) {
18772     mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18773   } else if ( mp->cur_type<=mp_pair_type ) { /* |mp_color_type| or |mp_pair_type| */
18774     p=value(mp->cur_exp);
18775     r=p+mp->big_node_size[mp->cur_type];
18776     do {  
18777       r=r-2;
18778       if ( type(r)==mp_known ) negate(value(r));
18779       else mp_negate_dep_list(mp, dep_list(r));
18780     } while (r!=p);
18781   } /* if |cur_type=mp_known| then |cur_exp=0| */
18782   mp_recycle_value(mp, q); mp_free_node(mp, q,value_node_size);
18783   break;
18784 case mp_dependent:
18785 case mp_proto_dependent:
18786   mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18787   break;
18788 case mp_known:
18789   negate(mp->cur_exp);
18790   break;
18791 default:
18792   mp_bad_unary(mp, minus);
18793   break;
18794 }
18795
18796 @ @<Declare unary action...@>=
18797 void mp_negate_dep_list (MP mp,pointer p) { 
18798   while (1) { 
18799     negate(value(p));
18800     if ( info(p)==null ) return;
18801     p=link(p);
18802   }
18803 }
18804
18805 @ @<Additional cases of unary operators@>=
18806 case not_op: 
18807   if ( mp->cur_type!=mp_boolean_type ) mp_bad_unary(mp, not_op);
18808   else mp->cur_exp=true_code+false_code-mp->cur_exp;
18809   break;
18810
18811 @ @d three_sixty_units 23592960 /* that's |360*unity| */
18812 @d boolean_reset(A) if ( (A) ) mp->cur_exp=true_code; else mp->cur_exp=false_code
18813
18814 @<Additional cases of unary operators@>=
18815 case sqrt_op:
18816 case m_exp_op:
18817 case m_log_op:
18818 case sin_d_op:
18819 case cos_d_op:
18820 case floor_op:
18821 case  uniform_deviate:
18822 case odd_op:
18823 case char_exists_op:
18824   if ( mp->cur_type!=mp_known ) {
18825     mp_bad_unary(mp, c);
18826   } else {
18827     switch (c) {
18828     case sqrt_op:mp->cur_exp=mp_square_rt(mp, mp->cur_exp);break;
18829     case m_exp_op:mp->cur_exp=mp_m_exp(mp, mp->cur_exp);break;
18830     case m_log_op:mp->cur_exp=mp_m_log(mp, mp->cur_exp);break;
18831     case sin_d_op:
18832     case cos_d_op:
18833       mp_n_sin_cos(mp, (mp->cur_exp % three_sixty_units)*16);
18834       if ( c==sin_d_op ) mp->cur_exp=mp_round_fraction(mp, mp->n_sin);
18835       else mp->cur_exp=mp_round_fraction(mp, mp->n_cos);
18836       break;
18837     case floor_op:mp->cur_exp=mp_floor_scaled(mp, mp->cur_exp);break;
18838     case uniform_deviate:mp->cur_exp=mp_unif_rand(mp, mp->cur_exp);break;
18839     case odd_op: 
18840       boolean_reset(odd(mp_round_unscaled(mp, mp->cur_exp)));
18841       mp->cur_type=mp_boolean_type;
18842       break;
18843     case char_exists_op:
18844       @<Determine if a character has been shipped out@>;
18845       break;
18846     } /* there are no other cases */
18847   }
18848   break;
18849
18850 @ @<Additional cases of unary operators@>=
18851 case angle_op:
18852   if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) ) {
18853     p=value(mp->cur_exp);
18854     x=mp_n_arg(mp, value(x_part_loc(p)),value(y_part_loc(p)));
18855     if ( x>=0 ) mp_flush_cur_exp(mp, (x+8)/ 16);
18856     else mp_flush_cur_exp(mp, -((-x+8)/ 16));
18857   } else {
18858     mp_bad_unary(mp, angle_op);
18859   }
18860   break;
18861
18862 @ If the current expression is a pair, but the context wants it to
18863 be a path, we call |pair_to_path|.
18864
18865 @<Declare unary action...@>=
18866 void mp_pair_to_path (MP mp) { 
18867   mp->cur_exp=mp_new_knot(mp); 
18868   mp->cur_type=mp_path_type;
18869 };
18870
18871 @ @<Additional cases of unary operators@>=
18872 case x_part:
18873 case y_part:
18874   if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_transform_type) )
18875     mp_take_part(mp, c);
18876   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18877   else mp_bad_unary(mp, c);
18878   break;
18879 case xx_part:
18880 case xy_part:
18881 case yx_part:
18882 case yy_part: 
18883   if ( mp->cur_type==mp_transform_type ) mp_take_part(mp, c);
18884   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18885   else mp_bad_unary(mp, c);
18886   break;
18887 case red_part:
18888 case green_part:
18889 case blue_part: 
18890   if ( mp->cur_type==mp_color_type ) mp_take_part(mp, c);
18891   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18892   else mp_bad_unary(mp, c);
18893   break;
18894 case cyan_part:
18895 case magenta_part:
18896 case yellow_part:
18897 case black_part: 
18898   if ( mp->cur_type==mp_cmykcolor_type) mp_take_part(mp, c); 
18899   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18900   else mp_bad_unary(mp, c);
18901   break;
18902 case grey_part: 
18903   if ( mp->cur_type==mp_known ) mp->cur_exp=value(c);
18904   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18905   else mp_bad_unary(mp, c);
18906   break;
18907 case color_model_part: 
18908   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18909   else mp_bad_unary(mp, c);
18910   break;
18911
18912 @ In the following procedure, |cur_exp| points to a capsule, which points to
18913 a big node. We want to delete all but one part of the big node.
18914
18915 @<Declare unary action...@>=
18916 void mp_take_part (MP mp,quarterword c) {
18917   pointer p; /* the big node */
18918   p=value(mp->cur_exp); value(temp_val)=p; type(temp_val)=mp->cur_type;
18919   link(p)=temp_val; mp_free_node(mp, mp->cur_exp,value_node_size);
18920   mp_make_exp_copy(mp, p+mp->sector_offset[c+mp_x_part_sector-x_part]);
18921   mp_recycle_value(mp, temp_val);
18922 }
18923
18924 @ @<Initialize table entries...@>=
18925 name_type(temp_val)=mp_capsule;
18926
18927 @ @<Additional cases of unary operators@>=
18928 case font_part:
18929 case text_part:
18930 case path_part:
18931 case pen_part:
18932 case dash_part:
18933   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18934   else mp_bad_unary(mp, c);
18935   break;
18936
18937 @ @<Declarations@>=
18938 void mp_scale_edges (MP mp);
18939
18940 @ @<Declare unary action...@>=
18941 void mp_take_pict_part (MP mp,quarterword c) {
18942   pointer p; /* first graphical object in |cur_exp| */
18943   p=link(dummy_loc(mp->cur_exp));
18944   if ( p!=null ) {
18945     switch (c) {
18946     case x_part: case y_part: case xx_part:
18947     case xy_part: case yx_part: case yy_part:
18948       if ( type(p)==mp_text_code ) mp_flush_cur_exp(mp, text_trans_part(p+c));
18949       else goto NOT_FOUND;
18950       break;
18951     case red_part: case green_part: case blue_part:
18952       if ( has_color(p) ) mp_flush_cur_exp(mp, obj_color_part(p+c));
18953       else goto NOT_FOUND;
18954       break;
18955     case cyan_part: case magenta_part: case yellow_part:
18956     case black_part:
18957       if ( has_color(p) ) {
18958         if ( color_model(p)==mp_uninitialized_model )
18959           mp_flush_cur_exp(mp, unity);
18960         else
18961           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-cyan_part)));
18962       } else goto NOT_FOUND;
18963       break;
18964     case grey_part:
18965       if ( has_color(p) )
18966           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-grey_part)));
18967       else goto NOT_FOUND;
18968       break;
18969     case color_model_part:
18970       if ( has_color(p) ) {
18971         if ( color_model(p)==mp_uninitialized_model )
18972           mp_flush_cur_exp(mp, mp->internal[mp_default_color_model]);
18973         else
18974           mp_flush_cur_exp(mp, color_model(p)*unity);
18975       } else goto NOT_FOUND;
18976       break;
18977     @<Handle other cases in |take_pict_part| or |goto not_found|@>;
18978     } /* all cases have been enumerated */
18979     return;
18980   };
18981 NOT_FOUND:
18982   @<Convert the current expression to a null value appropriate
18983     for |c|@>;
18984 }
18985
18986 @ @<Handle other cases in |take_pict_part| or |goto not_found|@>=
18987 case text_part: 
18988   if ( type(p)!=mp_text_code ) goto NOT_FOUND;
18989   else { 
18990     mp_flush_cur_exp(mp, text_p(p));
18991     add_str_ref(mp->cur_exp);
18992     mp->cur_type=mp_string_type;
18993     };
18994   break;
18995 case font_part: 
18996   if ( type(p)!=mp_text_code ) goto NOT_FOUND;
18997   else { 
18998     mp_flush_cur_exp(mp, rts(mp->font_name[font_n(p)])); 
18999     add_str_ref(mp->cur_exp);
19000     mp->cur_type=mp_string_type;
19001   };
19002   break;
19003 case path_part:
19004   if ( type(p)==mp_text_code ) goto NOT_FOUND;
19005   else if ( is_stop(p) ) mp_confusion(mp, "pict");
19006 @:this can't happen pict}{\quad pict@>
19007   else { 
19008     mp_flush_cur_exp(mp, mp_copy_path(mp, path_p(p)));
19009     mp->cur_type=mp_path_type;
19010   }
19011   break;
19012 case pen_part: 
19013   if ( ! has_pen(p) ) goto NOT_FOUND;
19014   else {
19015     if ( pen_p(p)==null ) goto NOT_FOUND;
19016     else { mp_flush_cur_exp(mp, copy_pen(pen_p(p)));
19017       mp->cur_type=mp_pen_type;
19018     };
19019   }
19020   break;
19021 case dash_part: 
19022   if ( type(p)!=mp_stroked_code ) goto NOT_FOUND;
19023   else { if ( dash_p(p)==null ) goto NOT_FOUND;
19024     else { add_edge_ref(dash_p(p));
19025     mp->se_sf=dash_scale(p);
19026     mp->se_pic=dash_p(p);
19027     mp_scale_edges(mp);
19028     mp_flush_cur_exp(mp, mp->se_pic);
19029     mp->cur_type=mp_picture_type;
19030     };
19031   }
19032   break;
19033
19034 @ Since |scale_edges| had to be declared |forward|, it had to be declared as a
19035 parameterless procedure even though it really takes two arguments and updates
19036 one of them.  Hence the following globals are needed.
19037
19038 @<Global...@>=
19039 pointer se_pic;  /* edge header used and updated by |scale_edges| */
19040 scaled se_sf;  /* the scale factor argument to |scale_edges| */
19041
19042 @ @<Convert the current expression to a null value appropriate...@>=
19043 switch (c) {
19044 case text_part: case font_part: 
19045   mp_flush_cur_exp(mp, rts(""));
19046   mp->cur_type=mp_string_type;
19047   break;
19048 case path_part: 
19049   mp_flush_cur_exp(mp, mp_get_node(mp, knot_node_size));
19050   left_type(mp->cur_exp)=mp_endpoint;
19051   right_type(mp->cur_exp)=mp_endpoint;
19052   link(mp->cur_exp)=mp->cur_exp;
19053   x_coord(mp->cur_exp)=0;
19054   y_coord(mp->cur_exp)=0;
19055   originator(mp->cur_exp)=mp_metapost_user;
19056   mp->cur_type=mp_path_type;
19057   break;
19058 case pen_part: 
19059   mp_flush_cur_exp(mp, mp_get_pen_circle(mp, 0));
19060   mp->cur_type=mp_pen_type;
19061   break;
19062 case dash_part: 
19063   mp_flush_cur_exp(mp, mp_get_node(mp, edge_header_size));
19064   mp_init_edges(mp, mp->cur_exp);
19065   mp->cur_type=mp_picture_type;
19066   break;
19067 default: 
19068    mp_flush_cur_exp(mp, 0);
19069   break;
19070 }
19071
19072 @ @<Additional cases of unary...@>=
19073 case char_op: 
19074   if ( mp->cur_type!=mp_known ) { 
19075     mp_bad_unary(mp, char_op);
19076   } else { 
19077     mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256; 
19078     mp->cur_type=mp_string_type;
19079     if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
19080   }
19081   break;
19082 case decimal: 
19083   if ( mp->cur_type!=mp_known ) {
19084      mp_bad_unary(mp, decimal);
19085   } else { 
19086     mp->old_setting=mp->selector; mp->selector=new_string;
19087     mp_print_scaled(mp, mp->cur_exp); mp->cur_exp=mp_make_string(mp);
19088     mp->selector=mp->old_setting; mp->cur_type=mp_string_type;
19089   }
19090   break;
19091 case oct_op:
19092 case hex_op:
19093 case ASCII_op: 
19094   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19095   else mp_str_to_num(mp, c);
19096   break;
19097 case font_size: 
19098   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, font_size);
19099   else @<Find the design size of the font whose name is |cur_exp|@>;
19100   break;
19101
19102 @ @<Declare unary action...@>=
19103 void mp_str_to_num (MP mp,quarterword c) { /* converts a string to a number */
19104   integer n; /* accumulator */
19105   ASCII_code m; /* current character */
19106   pool_pointer k; /* index into |str_pool| */
19107   int b; /* radix of conversion */
19108   boolean bad_char; /* did the string contain an invalid digit? */
19109   if ( c==ASCII_op ) {
19110     if ( length(mp->cur_exp)==0 ) n=-1;
19111     else n=mp->str_pool[mp->str_start[mp->cur_exp]];
19112   } else { 
19113     if ( c==oct_op ) b=8; else b=16;
19114     n=0; bad_char=false;
19115     for (k=mp->str_start[mp->cur_exp];k<=str_stop(mp->cur_exp)-1;k++) {
19116       m=mp->str_pool[k];
19117       if ( (m>='0')&&(m<='9') ) m=m-'0';
19118       else if ( (m>='A')&&(m<='F') ) m=m-'A'+10;
19119       else if ( (m>='a')&&(m<='f') ) m=m-'a'+10;
19120       else  { bad_char=true; m=0; };
19121       if ( m>=b ) { bad_char=true; m=0; };
19122       if ( n<32768 / b ) n=n*b+m; else n=32767;
19123     }
19124     @<Give error messages if |bad_char| or |n>=4096|@>;
19125   }
19126   mp_flush_cur_exp(mp, n*unity);
19127 }
19128
19129 @ @<Give error messages if |bad_char|...@>=
19130 if ( bad_char ) { 
19131   exp_err("String contains illegal digits");
19132 @.String contains illegal digits@>
19133   if ( c==oct_op ) {
19134     help1("I zeroed out characters that weren't in the range 0..7.");
19135   } else  {
19136     help1("I zeroed out characters that weren't hex digits.");
19137   }
19138   mp_put_get_error(mp);
19139 }
19140 if ( (n>4095) ) {
19141   if ( mp->internal[mp_warning_check]>0 ) {
19142     print_err("Number too large ("); 
19143     mp_print_int(mp, n); mp_print_char(mp, ')');
19144 @.Number too large@>
19145     help2("I have trouble with numbers greater than 4095; watch out.")
19146       ("(Set warningcheck:=0 to suppress this message.)");
19147     mp_put_get_error(mp);
19148   }
19149 }
19150
19151 @ The length operation is somewhat unusual in that it applies to a variety
19152 of different types of operands.
19153
19154 @<Additional cases of unary...@>=
19155 case length_op: 
19156   switch (mp->cur_type) {
19157   case mp_string_type: mp_flush_cur_exp(mp, length(mp->cur_exp)*unity); break;
19158   case mp_path_type: mp_flush_cur_exp(mp, mp_path_length(mp)); break;
19159   case mp_known: mp->cur_exp=abs(mp->cur_exp); break;
19160   case mp_picture_type: mp_flush_cur_exp(mp, mp_pict_length(mp)); break;
19161   default: 
19162     if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) )
19163       mp_flush_cur_exp(mp, mp_pyth_add(mp, 
19164         value(x_part_loc(value(mp->cur_exp))),
19165         value(y_part_loc(value(mp->cur_exp)))));
19166     else mp_bad_unary(mp, c);
19167     break;
19168   }
19169   break;
19170
19171 @ @<Declare unary action...@>=
19172 scaled mp_path_length (MP mp) { /* computes the length of the current path */
19173   scaled n; /* the path length so far */
19174   pointer p; /* traverser */
19175   p=mp->cur_exp;
19176   if ( left_type(p)==mp_endpoint ) n=-unity; else n=0;
19177   do {  p=link(p); n=n+unity; } while (p!=mp->cur_exp);
19178   return n;
19179 }
19180
19181 @ @<Declare unary action...@>=
19182 scaled mp_pict_length (MP mp) { 
19183   /* counts interior components in picture |cur_exp| */
19184   scaled n; /* the count so far */
19185   pointer p; /* traverser */
19186   n=0;
19187   p=link(dummy_loc(mp->cur_exp));
19188   if ( p!=null ) {
19189     if ( is_start_or_stop(p) )
19190       if ( mp_skip_1component(mp, p)==null ) p=link(p);
19191     while ( p!=null )  { 
19192       skip_component(p) return n; 
19193       n=n+unity;   
19194     }
19195   }
19196   return n;
19197 }
19198
19199 @ Implement |turningnumber|
19200
19201 @<Additional cases of unary...@>=
19202 case turning_op:
19203   if ( mp->cur_type==mp_pair_type ) mp_flush_cur_exp(mp, 0);
19204   else if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, turning_op);
19205   else if ( left_type(mp->cur_exp)==mp_endpoint )
19206      mp_flush_cur_exp(mp, 0); /* not a cyclic path */
19207   else
19208     mp_flush_cur_exp(mp, mp_turn_cycles_wrapper(mp, mp->cur_exp));
19209   break;
19210
19211 @ The function |an_angle| returns the value of the |angle| primitive, or $0$ if the
19212 argument is |origin|.
19213
19214 @<Declare unary action...@>=
19215 angle mp_an_angle (MP mp,scaled xpar, scaled ypar) {
19216   if ( (! ((xpar==0) && (ypar==0))) )
19217     return mp_n_arg(mp, xpar,ypar);
19218   return 0;
19219 }
19220
19221
19222 @ The actual turning number is (for the moment) computed in a C function
19223 that receives eight integers corresponding to the four controlling points,
19224 and returns a single angle.  Besides those, we have to account for discrete
19225 moves at the actual points.
19226
19227 @d floor(a) (a>=0 ? a : -(int)(-a))
19228 @d bezier_error (720<<20)+1
19229 @d sign(v) ((v)>0 ? 1 : ((v)<0 ? -1 : 0 ))
19230 @d print_roots(a) 
19231 @d out ((double)(xo>>20))
19232 @d mid ((double)(xm>>20))
19233 @d in  ((double)(xi>>20))
19234 @d divisor (256*256)
19235 @d double2angle(a) (int)floor(a*256.0*256.0*16.0)
19236
19237 @<Declare unary action...@>=
19238 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19239             integer CX,integer CY,integer DX,integer DY);
19240
19241 @ @c 
19242 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19243             integer CX,integer CY,integer DX,integer DY) {
19244   double a, b, c;
19245   integer deltax,deltay;
19246   double ax,ay,bx,by,cx,cy,dx,dy;
19247   angle xi = 0, xo = 0, xm = 0;
19248   double res = 0;
19249   ax=AX/divisor;  ay=AY/divisor;
19250   bx=BX/divisor;  by=BY/divisor;
19251   cx=CX/divisor;  cy=CY/divisor;
19252   dx=DX/divisor;  dy=DY/divisor;
19253
19254   deltax = (BX-AX); deltay = (BY-AY);
19255   if (deltax==0 && deltay == 0) { deltax=(CX-AX); deltay=(CY-AY); }
19256   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19257   xi = mp_an_angle(mp,deltax,deltay);
19258
19259   deltax = (CX-BX); deltay = (CY-BY);
19260   xm = mp_an_angle(mp,deltax,deltay);
19261
19262   deltax = (DX-CX); deltay = (DY-CY);
19263   if (deltax==0 && deltay == 0) { deltax=(DX-BX); deltay=(DY-BY); }
19264   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19265   xo = mp_an_angle(mp,deltax,deltay);
19266
19267   a = (bx-ax)*(cy-by) - (cx-bx)*(by-ay); /* a = (bp-ap)x(cp-bp); */
19268   b = (bx-ax)*(dy-cy) - (by-ay)*(dx-cx);; /* b = (bp-ap)x(dp-cp);*/
19269   c = (cx-bx)*(dy-cy) - (dx-cx)*(cy-by); /* c = (cp-bp)x(dp-cp);*/
19270
19271   if ((a==0)&&(c==0)) {
19272     res = (b==0 ?  0 :  (out-in)); 
19273     print_roots("no roots (a)");
19274   } else if ((a==0)||(c==0)) {
19275     if ((sign(b) == sign(a)) || (sign(b) == sign(c))) {
19276       res = out-in; /* ? */
19277       if (res<-180.0) 
19278         res += 360.0;
19279       else if (res>180.0)
19280         res -= 360.0;
19281       print_roots("no roots (b)");
19282     } else {
19283       res = out-in; /* ? */
19284       print_roots("one root (a)");
19285     }
19286   } else if ((sign(a)*sign(c))<0) {
19287     res = out-in; /* ? */
19288       if (res<-180.0) 
19289         res += 360.0;
19290       else if (res>180.0)
19291         res -= 360.0;
19292     print_roots("one root (b)");
19293   } else {
19294     if (sign(a) == sign(b)) {
19295       res = out-in; /* ? */
19296       if (res<-180.0) 
19297         res += 360.0;
19298       else if (res>180.0)
19299         res -= 360.0;
19300       print_roots("no roots (d)");
19301     } else {
19302       if ((b*b) == (4*a*c)) {
19303         res = bezier_error;
19304         print_roots("double root"); /* cusp */
19305       } else if ((b*b) < (4*a*c)) {
19306         res = out-in; /* ? */
19307         if (res<=0.0 &&res>-180.0) 
19308           res += 360.0;
19309         else if (res>=0.0 && res<180.0)
19310           res -= 360.0;
19311         print_roots("no roots (e)");
19312       } else {
19313         res = out-in;
19314         if (res<-180.0) 
19315           res += 360.0;
19316         else if (res>180.0)
19317           res -= 360.0;
19318         print_roots("two roots"); /* two inflections */
19319       }
19320     }
19321   }
19322   return double2angle(res);
19323 }
19324
19325 @
19326 @d p_nextnext link(link(p))
19327 @d p_next link(p)
19328 @d seven_twenty_deg 05500000000 /* $720\cdot2^{20}$, represents $720^\circ$ */
19329
19330 @<Declare unary action...@>=
19331 scaled mp_new_turn_cycles (MP mp,pointer c) {
19332   angle res,ang; /*  the angles of intermediate results  */
19333   scaled turns;  /*  the turn counter  */
19334   pointer p;     /*  for running around the path  */
19335   integer xp,yp;   /*  coordinates of next point  */
19336   integer x,y;   /*  helper coordinates  */
19337   angle in_angle,out_angle;     /*  helper angles */
19338   int old_setting; /* saved |selector| setting */
19339   res=0;
19340   turns= 0;
19341   p=c;
19342   old_setting = mp->selector; mp->selector=term_only;
19343   if ( mp->internal[mp_tracing_commands]>unity ) {
19344     mp_begin_diagnostic(mp);
19345     mp_print_nl(mp, "");
19346     mp_end_diagnostic(mp, false);
19347   }
19348   do { 
19349     xp = x_coord(p_next); yp = y_coord(p_next);
19350     ang  = mp_bezier_slope(mp,x_coord(p), y_coord(p), right_x(p), right_y(p),
19351              left_x(p_next), left_y(p_next), xp, yp);
19352     if ( ang>seven_twenty_deg ) {
19353       print_err("Strange path");
19354       mp_error(mp);
19355       mp->selector=old_setting;
19356       return 0;
19357     }
19358     res  = res + ang;
19359     if ( res > one_eighty_deg ) {
19360       res = res - three_sixty_deg;
19361       turns = turns + unity;
19362     }
19363     if ( res <= -one_eighty_deg ) {
19364       res = res + three_sixty_deg;
19365       turns = turns - unity;
19366     }
19367     /*  incoming angle at next point  */
19368     x = left_x(p_next);  y = left_y(p_next);
19369     if ( (xp==x)&&(yp==y) ) { x = right_x(p);  y = right_y(p);  };
19370     if ( (xp==x)&&(yp==y) ) { x = x_coord(p);  y = y_coord(p);  };
19371     in_angle = mp_an_angle(mp, xp - x, yp - y);
19372     /*  outgoing angle at next point  */
19373     x = right_x(p_next);  y = right_y(p_next);
19374     if ( (xp==x)&&(yp==y) ) { x = left_x(p_nextnext);  y = left_y(p_nextnext);  };
19375     if ( (xp==x)&&(yp==y) ) { x = x_coord(p_nextnext); y = y_coord(p_nextnext); };
19376     out_angle = mp_an_angle(mp, x - xp, y- yp);
19377     ang  = (out_angle - in_angle);
19378     reduce_angle(ang);
19379     if ( ang!=0 ) {
19380       res  = res + ang;
19381       if ( res >= one_eighty_deg ) {
19382         res = res - three_sixty_deg;
19383         turns = turns + unity;
19384       };
19385       if ( res <= -one_eighty_deg ) {
19386         res = res + three_sixty_deg;
19387         turns = turns - unity;
19388       };
19389     };
19390     p = link(p);
19391   } while (p!=c);
19392   mp->selector=old_setting;
19393   return turns;
19394 }
19395
19396
19397 @ This code is based on Bogus\l{}av Jackowski's
19398 |emergency_turningnumber| macro, with some minor changes by Taco
19399 Hoekwater. The macro code looked more like this:
19400 {\obeylines
19401 vardef turning\_number primary p =
19402 ~~save res, ang, turns;
19403 ~~res := 0;
19404 ~~if length p <= 2:
19405 ~~~~if Angle ((point 0 of p) - (postcontrol 0 of p)) >= 0:  1  else: -1 fi
19406 ~~else:
19407 ~~~~for t = 0 upto length p-1 :
19408 ~~~~~~angc := Angle ((point t+1 of p)  - (point t of p))
19409 ~~~~~~~~- Angle ((point t of p) - (point t-1 of p));
19410 ~~~~~~if angc > 180: angc := angc - 360; fi;
19411 ~~~~~~if angc < -180: angc := angc + 360; fi;
19412 ~~~~~~res  := res + angc;
19413 ~~~~endfor;
19414 ~~res/360
19415 ~~fi
19416 enddef;}
19417 The general idea is to calculate only the sum of the angles of
19418 straight lines between the points, of a path, not worrying about cusps
19419 or self-intersections in the segments at all. If the segment is not
19420 well-behaved, the result is not necesarily correct. But the old code
19421 was not always correct either, and worse, it sometimes failed for
19422 well-behaved paths as well. All known bugs that were triggered by the
19423 original code no longer occur with this code, and it runs roughly 3
19424 times as fast because the algorithm is much simpler.
19425
19426 @ It is possible to overflow the return value of the |turn_cycles|
19427 function when the path is sufficiently long and winding, but I am not
19428 going to bother testing for that. In any case, it would only return
19429 the looped result value, which is not a big problem.
19430
19431 The macro code for the repeat loop was a bit nicer to look
19432 at than the pascal code, because it could use |point -1 of p|. In
19433 pascal, the fastest way to loop around the path is not to look
19434 backward once, but forward twice. These defines help hide the trick.
19435
19436 @d p_to link(link(p))
19437 @d p_here link(p)
19438 @d p_from p
19439
19440 @<Declare unary action...@>=
19441 scaled mp_turn_cycles (MP mp,pointer c) {
19442   angle res,ang; /*  the angles of intermediate results  */
19443   scaled turns;  /*  the turn counter  */
19444   pointer p;     /*  for running around the path  */
19445   res=0;  turns= 0; p=c;
19446   do { 
19447     ang  = mp_an_angle (mp, x_coord(p_to) - x_coord(p_here), 
19448                             y_coord(p_to) - y_coord(p_here))
19449         - mp_an_angle (mp, x_coord(p_here) - x_coord(p_from), 
19450                            y_coord(p_here) - y_coord(p_from));
19451     reduce_angle(ang);
19452     res  = res + ang;
19453     if ( res >= three_sixty_deg )  {
19454       res = res - three_sixty_deg;
19455       turns = turns + unity;
19456     };
19457     if ( res <= -three_sixty_deg ) {
19458       res = res + three_sixty_deg;
19459       turns = turns - unity;
19460     };
19461     p = link(p);
19462   } while (p!=c);
19463   return turns;
19464 }
19465
19466 @ @<Declare unary action...@>=
19467 scaled mp_turn_cycles_wrapper (MP mp,pointer c) {
19468   scaled nval,oval;
19469   scaled saved_t_o; /* tracing\_online saved  */
19470   if ( (link(c)==c)||(link(link(c))==c) ) {
19471     if ( mp_an_angle (mp, x_coord(c) - right_x(c),  y_coord(c) - right_y(c)) > 0 )
19472       return unity;
19473     else
19474       return -unity;
19475   } else {
19476     nval = mp_new_turn_cycles(mp, c);
19477     oval = mp_turn_cycles(mp, c);
19478     if ( nval!=oval ) {
19479       saved_t_o=mp->internal[mp_tracing_online];
19480       mp->internal[mp_tracing_online]=unity;
19481       mp_begin_diagnostic(mp);
19482       mp_print_nl (mp, "Warning: the turningnumber algorithms do not agree."
19483                        " The current computed value is ");
19484       mp_print_scaled(mp, nval);
19485       mp_print(mp, ", but the 'connect-the-dots' algorithm returned ");
19486       mp_print_scaled(mp, oval);
19487       mp_end_diagnostic(mp, false);
19488       mp->internal[mp_tracing_online]=saved_t_o;
19489     }
19490     return nval;
19491   }
19492 }
19493
19494 @ @<Declare unary action...@>=
19495 scaled mp_count_turns (MP mp,pointer c) {
19496   pointer p; /* a knot in envelope spec |c| */
19497   integer t; /* total pen offset changes counted */
19498   t=0; p=c;
19499   do {  
19500     t=t+info(p)-zero_off;
19501     p=link(p);
19502   } while (p!=c);
19503   return ((t / 3)*unity);
19504 }
19505
19506 @ @d type_range(A,B) { 
19507   if ( (mp->cur_type>=(A)) && (mp->cur_type<=(B)) ) 
19508     mp_flush_cur_exp(mp, true_code);
19509   else mp_flush_cur_exp(mp, false_code);
19510   mp->cur_type=mp_boolean_type;
19511   }
19512 @d type_test(A) { 
19513   if ( mp->cur_type==(A) ) mp_flush_cur_exp(mp, true_code);
19514   else mp_flush_cur_exp(mp, false_code);
19515   mp->cur_type=mp_boolean_type;
19516   }
19517
19518 @<Additional cases of unary operators@>=
19519 case mp_boolean_type: 
19520   type_range(mp_boolean_type,mp_unknown_boolean); break;
19521 case mp_string_type: 
19522   type_range(mp_string_type,mp_unknown_string); break;
19523 case mp_pen_type: 
19524   type_range(mp_pen_type,mp_unknown_pen); break;
19525 case mp_path_type: 
19526   type_range(mp_path_type,mp_unknown_path); break;
19527 case mp_picture_type: 
19528   type_range(mp_picture_type,mp_unknown_picture); break;
19529 case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
19530 case mp_pair_type: 
19531   type_test(c); break;
19532 case mp_numeric_type: 
19533   type_range(mp_known,mp_independent); break;
19534 case known_op: case unknown_op: 
19535   mp_test_known(mp, c); break;
19536
19537 @ @<Declare unary action procedures@>=
19538 void mp_test_known (MP mp,quarterword c) {
19539   int b; /* is the current expression known? */
19540   pointer p,q; /* locations in a big node */
19541   b=false_code;
19542   switch (mp->cur_type) {
19543   case mp_vacuous: case mp_boolean_type: case mp_string_type:
19544   case mp_pen_type: case mp_path_type: case mp_picture_type:
19545   case mp_known: 
19546     b=true_code;
19547     break;
19548   case mp_transform_type:
19549   case mp_color_type: case mp_cmykcolor_type: case mp_pair_type: 
19550     p=value(mp->cur_exp);
19551     q=p+mp->big_node_size[mp->cur_type];
19552     do {  
19553       q=q-2;
19554       if ( type(q)!=mp_known ) 
19555        goto DONE;
19556     } while (q!=p);
19557     b=true_code;
19558   DONE:  
19559     break;
19560   default: 
19561     break;
19562   }
19563   if ( c==known_op ) mp_flush_cur_exp(mp, b);
19564   else mp_flush_cur_exp(mp, true_code+false_code-b);
19565   mp->cur_type=mp_boolean_type;
19566 }
19567
19568 @ @<Additional cases of unary operators@>=
19569 case cycle_op: 
19570   if ( mp->cur_type!=mp_path_type ) mp_flush_cur_exp(mp, false_code);
19571   else if ( left_type(mp->cur_exp)!=mp_endpoint ) mp_flush_cur_exp(mp, true_code);
19572   else mp_flush_cur_exp(mp, false_code);
19573   mp->cur_type=mp_boolean_type;
19574   break;
19575
19576 @ @<Additional cases of unary operators@>=
19577 case arc_length: 
19578   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19579   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, arc_length);
19580   else mp_flush_cur_exp(mp, mp_get_arc_length(mp, mp->cur_exp));
19581   break;
19582
19583 @ Here we use the fact that |c-filled_op+fill_code| is the desired graphical
19584 object |type|.
19585 @^data structure assumptions@>
19586
19587 @<Additional cases of unary operators@>=
19588 case filled_op:
19589 case stroked_op:
19590 case textual_op:
19591 case clipped_op:
19592 case bounded_op:
19593   if ( mp->cur_type!=mp_picture_type ) mp_flush_cur_exp(mp, false_code);
19594   else if ( link(dummy_loc(mp->cur_exp))==null ) mp_flush_cur_exp(mp, false_code);
19595   else if ( type(link(dummy_loc(mp->cur_exp)))==c+mp_fill_code-filled_op )
19596     mp_flush_cur_exp(mp, true_code);
19597   else mp_flush_cur_exp(mp, false_code);
19598   mp->cur_type=mp_boolean_type;
19599   break;
19600
19601 @ @<Additional cases of unary operators@>=
19602 case make_pen_op: 
19603   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19604   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, make_pen_op);
19605   else { 
19606     mp->cur_type=mp_pen_type;
19607     mp->cur_exp=mp_make_pen(mp, mp->cur_exp,true);
19608   };
19609   break;
19610 case make_path_op: 
19611   if ( mp->cur_type!=mp_pen_type ) mp_bad_unary(mp, make_path_op);
19612   else  { 
19613     mp->cur_type=mp_path_type;
19614     mp_make_path(mp, mp->cur_exp);
19615   };
19616   break;
19617 case reverse: 
19618   if ( mp->cur_type==mp_path_type ) {
19619     p=mp_htap_ypoc(mp, mp->cur_exp);
19620     if ( right_type(p)==mp_endpoint ) p=link(p);
19621     mp_toss_knot_list(mp, mp->cur_exp); mp->cur_exp=p;
19622   } else if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19623   else mp_bad_unary(mp, reverse);
19624   break;
19625
19626 @ The |pair_value| routine changes the current expression to a
19627 given ordered pair of values.
19628
19629 @<Declare unary action procedures@>=
19630 void mp_pair_value (MP mp,scaled x, scaled y) {
19631   pointer p; /* a pair node */
19632   p=mp_get_node(mp, value_node_size); 
19633   mp_flush_cur_exp(mp, p); mp->cur_type=mp_pair_type;
19634   type(p)=mp_pair_type; name_type(p)=mp_capsule; mp_init_big_node(mp, p);
19635   p=value(p);
19636   type(x_part_loc(p))=mp_known; value(x_part_loc(p))=x;
19637   type(y_part_loc(p))=mp_known; value(y_part_loc(p))=y;
19638 }
19639
19640 @ @<Additional cases of unary operators@>=
19641 case ll_corner_op: 
19642   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ll_corner_op);
19643   else mp_pair_value(mp, minx,miny);
19644   break;
19645 case lr_corner_op: 
19646   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, lr_corner_op);
19647   else mp_pair_value(mp, maxx,miny);
19648   break;
19649 case ul_corner_op: 
19650   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ul_corner_op);
19651   else mp_pair_value(mp, minx,maxy);
19652   break;
19653 case ur_corner_op: 
19654   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ur_corner_op);
19655   else mp_pair_value(mp, maxx,maxy);
19656   break;
19657
19658 @ Here is a function that sets |minx|, |maxx|, |miny|, |maxy| to the bounding
19659 box of the current expression.  The boolean result is |false| if the expression
19660 has the wrong type.
19661
19662 @<Declare unary action procedures@>=
19663 boolean mp_get_cur_bbox (MP mp) { 
19664   switch (mp->cur_type) {
19665   case mp_picture_type: 
19666     mp_set_bbox(mp, mp->cur_exp,true);
19667     if ( minx_val(mp->cur_exp)>maxx_val(mp->cur_exp) ) {
19668       minx=0; maxx=0; miny=0; maxy=0;
19669     } else { 
19670       minx=minx_val(mp->cur_exp);
19671       maxx=maxx_val(mp->cur_exp);
19672       miny=miny_val(mp->cur_exp);
19673       maxy=maxy_val(mp->cur_exp);
19674     }
19675     break;
19676   case mp_path_type: 
19677     mp_path_bbox(mp, mp->cur_exp);
19678     break;
19679   case mp_pen_type: 
19680     mp_pen_bbox(mp, mp->cur_exp);
19681     break;
19682   default: 
19683     return false;
19684   }
19685   return true;
19686 }
19687
19688 @ @<Additional cases of unary operators@>=
19689 case read_from_op:
19690 case close_from_op: 
19691   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19692   else mp_do_read_or_close(mp,c);
19693   break;
19694
19695 @ Here is a routine that interprets |cur_exp| as a file name and tries to read
19696 a line from the file or to close the file.
19697
19698 @<Declare unary action procedures@>=
19699 void mp_do_read_or_close (MP mp,quarterword c) {
19700   readf_index n,n0; /* indices for searching |rd_fname| */
19701   @<Find the |n| where |rd_fname[n]=cur_exp|; if |cur_exp| must be inserted,
19702     call |start_read_input| and |goto found| or |not_found|@>;
19703   mp_begin_file_reading(mp);
19704   name=is_read;
19705   if ( mp_input_ln(mp, mp->rd_file[n] ) ) 
19706     goto FOUND;
19707   mp_end_file_reading(mp);
19708 NOT_FOUND:
19709   @<Record the end of file and set |cur_exp| to a dummy value@>;
19710   return;
19711 CLOSE_FILE:
19712   mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous; 
19713   return;
19714 FOUND:
19715   mp_flush_cur_exp(mp, 0);
19716   mp_finish_read(mp);
19717 }
19718
19719 @ Free slots in the |rd_file| and |rd_fname| arrays are marked with NULL's in
19720 |rd_fname|.
19721
19722 @<Find the |n| where |rd_fname[n]=cur_exp|...@>=
19723 {   
19724   char *fn;
19725   n=mp->read_files;
19726   n0=mp->read_files;
19727   fn = str(mp->cur_exp);
19728   while (mp_xstrcmp(fn,mp->rd_fname[n])!=0) { 
19729     if ( n>0 ) {
19730       decr(n);
19731     } else if ( c==close_from_op ) {
19732       goto CLOSE_FILE;
19733     } else {
19734       if ( n0==mp->read_files ) {
19735         if ( mp->read_files<mp->max_read_files ) {
19736           incr(mp->read_files);
19737         } else {
19738           void **rd_file;
19739           char **rd_fname;
19740               readf_index l,k;
19741           l = mp->max_read_files + (mp->max_read_files>>2);
19742           rd_file = xmalloc((l+1), sizeof(void *));
19743           rd_fname = xmalloc((l+1), sizeof(char *));
19744               for (k=0;k<=l;k++) {
19745             if (k<=mp->max_read_files) {
19746                   rd_file[k]=mp->rd_file[k]; 
19747               rd_fname[k]=mp->rd_fname[k];
19748             } else {
19749               rd_file[k]=0; 
19750               rd_fname[k]=NULL;
19751             }
19752           }
19753               xfree(mp->rd_file); xfree(mp->rd_fname);
19754           mp->max_read_files = l;
19755           mp->rd_file = rd_file;
19756           mp->rd_fname = rd_fname;
19757         }
19758       }
19759       n=n0;
19760       if ( mp_start_read_input(mp,fn,n) ) 
19761         goto FOUND;
19762       else 
19763         goto NOT_FOUND;
19764     }
19765     if ( mp->rd_fname[n]==NULL ) { n0=n; }
19766   } 
19767   if ( c==close_from_op ) { 
19768     (mp->close_file)(mp->rd_file[n]); 
19769     goto NOT_FOUND; 
19770   }
19771 }
19772
19773 @ @<Record the end of file and set |cur_exp| to a dummy value@>=
19774 xfree(mp->rd_fname[n]);
19775 mp->rd_fname[n]=NULL;
19776 if ( n==mp->read_files-1 ) mp->read_files=n;
19777 if ( c==close_from_op ) 
19778   goto CLOSE_FILE;
19779 mp_flush_cur_exp(mp, mp->eof_line);
19780 mp->cur_type=mp_string_type
19781
19782 @ The string denoting end-of-file is a one-byte string at position zero, by definition
19783
19784 @<Glob...@>=
19785 str_number eof_line;
19786
19787 @ @<Set init...@>=
19788 mp->eof_line=0;
19789
19790 @ Finally, we have the operations that combine a capsule~|p|
19791 with the current expression.
19792
19793 @c @<Declare binary action procedures@>;
19794 void mp_do_binary (MP mp,pointer p, quarterword c) {
19795   pointer q,r,rr; /* for list manipulation */
19796   pointer old_p,old_exp; /* capsules to recycle */
19797   integer v; /* for numeric manipulation */
19798   check_arith;
19799   if ( mp->internal[mp_tracing_commands]>two ) {
19800     @<Trace the current binary operation@>;
19801   }
19802   @<Sidestep |independent| cases in capsule |p|@>;
19803   @<Sidestep |independent| cases in the current expression@>;
19804   switch (c) {
19805   case plus: case minus:
19806     @<Add or subtract the current expression from |p|@>;
19807     break;
19808   @<Additional cases of binary operators@>;
19809   }; /* there are no other cases */
19810   mp_recycle_value(mp, p); 
19811   mp_free_node(mp, p,value_node_size); /* |return| to avoid this */
19812   check_arith; 
19813   @<Recycle any sidestepped |independent| capsules@>;
19814 }
19815
19816 @ @<Declare binary action...@>=
19817 void mp_bad_binary (MP mp,pointer p, quarterword c) { 
19818   mp_disp_err(mp, p,"");
19819   exp_err("Not implemented: ");
19820 @.Not implemented...@>
19821   if ( c>=min_of ) mp_print_op(mp, c);
19822   mp_print_known_or_unknown_type(mp, type(p),p);
19823   if ( c>=min_of ) mp_print(mp, "of"); else mp_print_op(mp, c);
19824   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
19825   help3("I'm afraid I don't know how to apply that operation to that")
19826        ("combination of types. Continue, and I'll return the second")
19827       ("argument (see above) as the result of the operation.");
19828   mp_put_get_error(mp);
19829 }
19830 void mp_bad_envelope_pen (MP mp) {
19831   mp_disp_err(mp, null,"");
19832   exp_err("Not implemented: envelope(elliptical pen)of(path)");
19833 @.Not implemented...@>
19834   help3("I'm afraid I don't know how to apply that operation to that")
19835        ("combination of types. Continue, and I'll return the second")
19836       ("argument (see above) as the result of the operation.");
19837   mp_put_get_error(mp);
19838 }
19839
19840 @ @<Trace the current binary operation@>=
19841
19842   mp_begin_diagnostic(mp); mp_print_nl(mp, "{(");
19843   mp_print_exp(mp,p,0); /* show the operand, but not verbosely */
19844   mp_print_char(mp,')'); mp_print_op(mp,c); mp_print_char(mp,'(');
19845   mp_print_exp(mp,null,0); mp_print(mp,")}"); 
19846   mp_end_diagnostic(mp, false);
19847 }
19848
19849 @ Several of the binary operations are potentially complicated by the
19850 fact that |independent| values can sneak into capsules. For example,
19851 we've seen an instance of this difficulty in the unary operation
19852 of negation. In order to reduce the number of cases that need to be
19853 handled, we first change the two operands (if necessary)
19854 to rid them of |independent| components. The original operands are
19855 put into capsules called |old_p| and |old_exp|, which will be
19856 recycled after the binary operation has been safely carried out.
19857
19858 @<Recycle any sidestepped |independent| capsules@>=
19859 if ( old_p!=null ) { 
19860   mp_recycle_value(mp, old_p); mp_free_node(mp, old_p,value_node_size);
19861 }
19862 if ( old_exp!=null ) {
19863   mp_recycle_value(mp, old_exp); mp_free_node(mp, old_exp,value_node_size);
19864 }
19865
19866 @ A big node is considered to be ``tarnished'' if it contains at least one
19867 independent component. We will define a simple function called `|tarnished|'
19868 that returns |null| if and only if its argument is not tarnished.
19869
19870 @<Sidestep |independent| cases in capsule |p|@>=
19871 switch (type(p)) {
19872 case mp_transform_type:
19873 case mp_color_type:
19874 case mp_cmykcolor_type:
19875 case mp_pair_type: 
19876   old_p=mp_tarnished(mp, p);
19877   break;
19878 case mp_independent: old_p=mp_void; break;
19879 default: old_p=null; break;
19880 };
19881 if ( old_p!=null ) {
19882   q=mp_stash_cur_exp(mp); old_p=p; mp_make_exp_copy(mp, old_p);
19883   p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
19884 }
19885
19886 @ @<Sidestep |independent| cases in the current expression@>=
19887 switch (mp->cur_type) {
19888 case mp_transform_type:
19889 case mp_color_type:
19890 case mp_cmykcolor_type:
19891 case mp_pair_type: 
19892   old_exp=mp_tarnished(mp, mp->cur_exp);
19893   break;
19894 case mp_independent:old_exp=mp_void; break;
19895 default: old_exp=null; break;
19896 };
19897 if ( old_exp!=null ) {
19898   old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
19899 }
19900
19901 @ @<Declare binary action...@>=
19902 pointer mp_tarnished (MP mp,pointer p) {
19903   pointer q; /* beginning of the big node */
19904   pointer r; /* current position in the big node */
19905   q=value(p); r=q+mp->big_node_size[type(p)];
19906   do {  
19907    r=r-2;
19908    if ( type(r)==mp_independent ) return mp_void; 
19909   } while (r!=q);
19910   return null;
19911 }
19912
19913 @ @<Add or subtract the current expression from |p|@>=
19914 if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
19915   mp_bad_binary(mp, p,c);
19916 } else  {
19917   if ((mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
19918     mp_add_or_subtract(mp, p,null,c);
19919   } else {
19920     if ( mp->cur_type!=type(p) )  {
19921       mp_bad_binary(mp, p,c);
19922     } else { 
19923       q=value(p); r=value(mp->cur_exp);
19924       rr=r+mp->big_node_size[mp->cur_type];
19925       while ( r<rr ) { 
19926         mp_add_or_subtract(mp, q,r,c);
19927         q=q+2; r=r+2;
19928       }
19929     }
19930   }
19931 }
19932
19933 @ The first argument to |add_or_subtract| is the location of a value node
19934 in a capsule or pair node that will soon be recycled. The second argument
19935 is either a location within a pair or transform node of |cur_exp|,
19936 or it is null (which means that |cur_exp| itself should be the second
19937 argument).  The third argument is either |plus| or |minus|.
19938
19939 The sum or difference of the numeric quantities will replace the second
19940 operand.  Arithmetic overflow may go undetected; users aren't supposed to
19941 be monkeying around with really big values.
19942
19943 @<Declare binary action...@>=
19944 @<Declare the procedure called |dep_finish|@>;
19945 void mp_add_or_subtract (MP mp,pointer p, pointer q, quarterword c) {
19946   small_number s,t; /* operand types */
19947   pointer r; /* list traverser */
19948   integer v; /* second operand value */
19949   if ( q==null ) { 
19950     t=mp->cur_type;
19951     if ( t<mp_dependent ) v=mp->cur_exp; else v=dep_list(mp->cur_exp);
19952   } else { 
19953     t=type(q);
19954     if ( t<mp_dependent ) v=value(q); else v=dep_list(q);
19955   }
19956   if ( t==mp_known ) {
19957     if ( c==minus ) negate(v);
19958     if ( type(p)==mp_known ) {
19959       v=mp_slow_add(mp, value(p),v);
19960       if ( q==null ) mp->cur_exp=v; else value(q)=v;
19961       return;
19962     }
19963     @<Add a known value to the constant term of |dep_list(p)|@>;
19964   } else  { 
19965     if ( c==minus ) mp_negate_dep_list(mp, v);
19966     @<Add operand |p| to the dependency list |v|@>;
19967   }
19968 }
19969
19970 @ @<Add a known value to the constant term of |dep_list(p)|@>=
19971 r=dep_list(p);
19972 while ( info(r)!=null ) r=link(r);
19973 value(r)=mp_slow_add(mp, value(r),v);
19974 if ( q==null ) {
19975   q=mp_get_node(mp, value_node_size); mp->cur_exp=q; mp->cur_type=type(p);
19976   name_type(q)=mp_capsule;
19977 }
19978 dep_list(q)=dep_list(p); type(q)=type(p);
19979 prev_dep(q)=prev_dep(p); link(prev_dep(p))=q;
19980 type(p)=mp_known; /* this will keep the recycler from collecting non-garbage */
19981
19982 @ We prefer |dependent| lists to |mp_proto_dependent| ones, because it is
19983 nice to retain the extra accuracy of |fraction| coefficients.
19984 But we have to handle both kinds, and mixtures too.
19985
19986 @<Add operand |p| to the dependency list |v|@>=
19987 if ( type(p)==mp_known ) {
19988   @<Add the known |value(p)| to the constant term of |v|@>;
19989 } else { 
19990   s=type(p); r=dep_list(p);
19991   if ( t==mp_dependent ) {
19992     if ( s==mp_dependent ) {
19993       if ( mp_max_coef(mp, r)+mp_max_coef(mp, v)<coef_bound )
19994         v=mp_p_plus_q(mp, v,r,mp_dependent); goto DONE;
19995       } /* |fix_needed| will necessarily be false */
19996       t=mp_proto_dependent; 
19997       v=mp_p_over_v(mp, v,unity,mp_dependent,mp_proto_dependent);
19998     }
19999     if ( s==mp_proto_dependent ) v=mp_p_plus_q(mp, v,r,mp_proto_dependent);
20000     else v=mp_p_plus_fq(mp, v,unity,r,mp_proto_dependent,mp_dependent);
20001  DONE:  
20002     @<Output the answer, |v| (which might have become |known|)@>;
20003   }
20004
20005 @ @<Add the known |value(p)| to the constant term of |v|@>=
20006
20007   while ( info(v)!=null ) v=link(v);
20008   value(v)=mp_slow_add(mp, value(p),value(v));
20009 }
20010
20011 @ @<Output the answer, |v| (which might have become |known|)@>=
20012 if ( q!=null ) mp_dep_finish(mp, v,q,t);
20013 else  { mp->cur_type=t; mp_dep_finish(mp, v,null,t); }
20014
20015 @ Here's the current situation: The dependency list |v| of type |t|
20016 should either be put into the current expression (if |q=null|) or
20017 into location |q| within a pair node (otherwise). The destination (|cur_exp|
20018 or |q|) formerly held a dependency list with the same
20019 final pointer as the list |v|.
20020
20021 @<Declare the procedure called |dep_finish|@>=
20022 void mp_dep_finish (MP mp, pointer v, pointer q, small_number t) {
20023   pointer p; /* the destination */
20024   scaled vv; /* the value, if it is |known| */
20025   if ( q==null ) p=mp->cur_exp; else p=q;
20026   dep_list(p)=v; type(p)=t;
20027   if ( info(v)==null ) { 
20028     vv=value(v);
20029     if ( q==null ) { 
20030       mp_flush_cur_exp(mp, vv);
20031     } else  { 
20032       mp_recycle_value(mp, p); type(q)=mp_known; value(q)=vv; 
20033     }
20034   } else if ( q==null ) {
20035     mp->cur_type=t;
20036   }
20037   if ( mp->fix_needed ) mp_fix_dependencies(mp);
20038 }
20039
20040 @ Let's turn now to the six basic relations of comparison.
20041
20042 @<Additional cases of binary operators@>=
20043 case less_than: case less_or_equal: case greater_than:
20044 case greater_or_equal: case equal_to: case unequal_to:
20045   check_arith; /* at this point |arith_error| should be |false|? */
20046   if ( (mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
20047     mp_add_or_subtract(mp, p,null,minus); /* |cur_exp:=(p)-cur_exp| */
20048   } else if ( mp->cur_type!=type(p) ) {
20049     mp_bad_binary(mp, p,c); goto DONE; 
20050   } else if ( mp->cur_type==mp_string_type ) {
20051     mp_flush_cur_exp(mp, mp_str_vs_str(mp, value(p),mp->cur_exp));
20052   } else if ((mp->cur_type==mp_unknown_string)||
20053            (mp->cur_type==mp_unknown_boolean) ) {
20054     @<Check if unknowns have been equated@>;
20055   } else if ( (mp->cur_type<=mp_pair_type)&&(mp->cur_type>=mp_transform_type)) {
20056     @<Reduce comparison of big nodes to comparison of scalars@>;
20057   } else if ( mp->cur_type==mp_boolean_type ) {
20058     mp_flush_cur_exp(mp, mp->cur_exp-value(p));
20059   } else { 
20060     mp_bad_binary(mp, p,c); goto DONE;
20061   }
20062   @<Compare the current expression with zero@>;
20063 DONE:  
20064   mp->arith_error=false; /* ignore overflow in comparisons */
20065   break;
20066
20067 @ @<Compare the current expression with zero@>=
20068 if ( mp->cur_type!=mp_known ) {
20069   if ( mp->cur_type<mp_known ) {
20070     mp_disp_err(mp, p,"");
20071     help1("The quantities shown above have not been equated.")
20072   } else  {
20073     help2("Oh dear. I can\'t decide if the expression above is positive,")
20074      ("negative, or zero. So this comparison test won't be `true'.");
20075   }
20076   exp_err("Unknown relation will be considered false");
20077 @.Unknown relation...@>
20078   mp_put_get_flush_error(mp, false_code);
20079 } else {
20080   switch (c) {
20081   case less_than: boolean_reset(mp->cur_exp<0); break;
20082   case less_or_equal: boolean_reset(mp->cur_exp<=0); break;
20083   case greater_than: boolean_reset(mp->cur_exp>0); break;
20084   case greater_or_equal: boolean_reset(mp->cur_exp>=0); break;
20085   case equal_to: boolean_reset(mp->cur_exp==0); break;
20086   case unequal_to: boolean_reset(mp->cur_exp!=0); break;
20087   }; /* there are no other cases */
20088 }
20089 mp->cur_type=mp_boolean_type
20090
20091 @ When two unknown strings are in the same ring, we know that they are
20092 equal. Otherwise, we don't know whether they are equal or not, so we
20093 make no change.
20094
20095 @<Check if unknowns have been equated@>=
20096
20097   q=value(mp->cur_exp);
20098   while ( (q!=mp->cur_exp)&&(q!=p) ) q=value(q);
20099   if ( q==p ) mp_flush_cur_exp(mp, 0);
20100 }
20101
20102 @ @<Reduce comparison of big nodes to comparison of scalars@>=
20103
20104   q=value(p); r=value(mp->cur_exp);
20105   rr=r+mp->big_node_size[mp->cur_type]-2;
20106   while (1) { mp_add_or_subtract(mp, q,r,minus);
20107     if ( type(r)!=mp_known ) break;
20108     if ( value(r)!=0 ) break;
20109     if ( r==rr ) break;
20110     q=q+2; r=r+2;
20111   }
20112   mp_take_part(mp, name_type(r)+x_part-mp_x_part_sector);
20113 }
20114
20115 @ Here we use the sneaky fact that |and_op-false_code=or_op-true_code|.
20116
20117 @<Additional cases of binary operators@>=
20118 case and_op:
20119 case or_op: 
20120   if ( (type(p)!=mp_boolean_type)||(mp->cur_type!=mp_boolean_type) )
20121     mp_bad_binary(mp, p,c);
20122   else if ( value(p)==c+false_code-and_op ) mp->cur_exp=value(p);
20123   break;
20124
20125 @ @<Additional cases of binary operators@>=
20126 case times: 
20127   if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
20128    mp_bad_binary(mp, p,times);
20129   } else if ( (mp->cur_type==mp_known)||(type(p)==mp_known) ) {
20130     @<Multiply when at least one operand is known@>;
20131   } else if ( (mp_nice_color_or_pair(mp, p,type(p))&&(mp->cur_type>mp_pair_type))
20132       ||(mp_nice_color_or_pair(mp, mp->cur_exp,mp->cur_type)&&
20133           (type(p)>mp_pair_type)) ) {
20134     mp_hard_times(mp, p); return;
20135   } else {
20136     mp_bad_binary(mp, p,times);
20137   }
20138   break;
20139
20140 @ @<Multiply when at least one operand is known@>=
20141
20142   if ( type(p)==mp_known ) {
20143     v=value(p); mp_free_node(mp, p,value_node_size); 
20144   } else {
20145     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20146   }
20147   if ( mp->cur_type==mp_known ) {
20148     mp->cur_exp=mp_take_scaled(mp, mp->cur_exp,v);
20149   } else if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_color_type)||
20150               (mp->cur_type==mp_cmykcolor_type) ) {
20151     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20152     do {  
20153        p=p-2; mp_dep_mult(mp, p,v,true);
20154     } while (p!=value(mp->cur_exp));
20155   } else {
20156     mp_dep_mult(mp, null,v,true);
20157   }
20158   return;
20159 }
20160
20161 @ @<Declare binary action...@>=
20162 void mp_dep_mult (MP mp,pointer p, integer v, boolean v_is_scaled) {
20163   pointer q; /* the dependency list being multiplied by |v| */
20164   small_number s,t; /* its type, before and after */
20165   if ( p==null ) {
20166     q=mp->cur_exp;
20167   } else if ( type(p)!=mp_known ) {
20168     q=p;
20169   } else { 
20170     if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
20171     else value(p)=mp_take_fraction(mp, value(p),v);
20172     return;
20173   };
20174   t=type(q); q=dep_list(q); s=t;
20175   if ( t==mp_dependent ) if ( v_is_scaled )
20176     if (mp_ab_vs_cd(mp, mp_max_coef(mp,q),abs(v),coef_bound-1,unity)>=0 ) 
20177       t=mp_proto_dependent;
20178   q=mp_p_times_v(mp, q,v,s,t,v_is_scaled); 
20179   mp_dep_finish(mp, q,p,t);
20180 }
20181
20182 @ Here is a routine that is similar to |times|; but it is invoked only
20183 internally, when |v| is a |fraction| whose magnitude is at most~1,
20184 and when |cur_type>=mp_color_type|.
20185
20186 @c void mp_frac_mult (MP mp,scaled n, scaled d) {
20187   /* multiplies |cur_exp| by |n/d| */
20188   pointer p; /* a pair node */
20189   pointer old_exp; /* a capsule to recycle */
20190   fraction v; /* |n/d| */
20191   if ( mp->internal[mp_tracing_commands]>two ) {
20192     @<Trace the fraction multiplication@>;
20193   }
20194   switch (mp->cur_type) {
20195   case mp_transform_type:
20196   case mp_color_type:
20197   case mp_cmykcolor_type:
20198   case mp_pair_type:
20199    old_exp=mp_tarnished(mp, mp->cur_exp);
20200    break;
20201   case mp_independent: old_exp=mp_void; break;
20202   default: old_exp=null; break;
20203   }
20204   if ( old_exp!=null ) { 
20205      old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
20206   }
20207   v=mp_make_fraction(mp, n,d);
20208   if ( mp->cur_type==mp_known ) {
20209     mp->cur_exp=mp_take_fraction(mp, mp->cur_exp,v);
20210   } else if ( mp->cur_type<=mp_pair_type ) { 
20211     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20212     do {  
20213       p=p-2;
20214       mp_dep_mult(mp, p,v,false);
20215     } while (p!=value(mp->cur_exp));
20216   } else {
20217     mp_dep_mult(mp, null,v,false);
20218   }
20219   if ( old_exp!=null ) {
20220     mp_recycle_value(mp, old_exp); 
20221     mp_free_node(mp, old_exp,value_node_size);
20222   }
20223 }
20224
20225 @ @<Trace the fraction multiplication@>=
20226
20227   mp_begin_diagnostic(mp); 
20228   mp_print_nl(mp, "{("); mp_print_scaled(mp,n); mp_print_char(mp,'/');
20229   mp_print_scaled(mp,d); mp_print(mp,")*("); mp_print_exp(mp,null,0); 
20230   mp_print(mp,")}");
20231   mp_end_diagnostic(mp, false);
20232 }
20233
20234 @ The |hard_times| routine multiplies a nice color or pair by a dependency list.
20235
20236 @<Declare binary action procedures@>=
20237 void mp_hard_times (MP mp,pointer p) {
20238   pointer q; /* a copy of the dependent variable |p| */
20239   pointer r; /* a component of the big node for the nice color or pair */
20240   scaled v; /* the known value for |r| */
20241   if ( type(p)<=mp_pair_type ) { 
20242      q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p); p=q;
20243   }; /* now |cur_type=mp_pair_type| or |cur_type=mp_color_type| */
20244   r=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20245   while (1) { 
20246     r=r-2;
20247     v=value(r);
20248     type(r)=type(p);
20249     if ( r==value(mp->cur_exp) ) 
20250       break;
20251     mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(p)));
20252     mp_dep_mult(mp, r,v,true);
20253   }
20254   mp->mem[value_loc(r)]=mp->mem[value_loc(p)];
20255   link(prev_dep(p))=r;
20256   mp_free_node(mp, p,value_node_size);
20257   mp_dep_mult(mp, r,v,true);
20258 }
20259
20260 @ @<Additional cases of binary operators@>=
20261 case over: 
20262   if ( (mp->cur_type!=mp_known)||(type(p)<mp_color_type) ) {
20263     mp_bad_binary(mp, p,over);
20264   } else { 
20265     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20266     if ( v==0 ) {
20267       @<Squeal about division by zero@>;
20268     } else { 
20269       if ( mp->cur_type==mp_known ) {
20270         mp->cur_exp=mp_make_scaled(mp, mp->cur_exp,v);
20271       } else if ( mp->cur_type<=mp_pair_type ) { 
20272         p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20273         do {  
20274           p=p-2;  mp_dep_div(mp, p,v);
20275         } while (p!=value(mp->cur_exp));
20276       } else {
20277         mp_dep_div(mp, null,v);
20278       }
20279     }
20280     return;
20281   }
20282   break;
20283
20284 @ @<Declare binary action...@>=
20285 void mp_dep_div (MP mp,pointer p, scaled v) {
20286   pointer q; /* the dependency list being divided by |v| */
20287   small_number s,t; /* its type, before and after */
20288   if ( p==null ) q=mp->cur_exp;
20289   else if ( type(p)!=mp_known ) q=p;
20290   else { value(p)=mp_make_scaled(mp, value(p),v); return; };
20291   t=type(q); q=dep_list(q); s=t;
20292   if ( t==mp_dependent )
20293     if ( mp_ab_vs_cd(mp, mp_max_coef(mp,q),unity,coef_bound-1,abs(v))>=0 ) 
20294       t=mp_proto_dependent;
20295   q=mp_p_over_v(mp, q,v,s,t); 
20296   mp_dep_finish(mp, q,p,t);
20297 }
20298
20299 @ @<Squeal about division by zero@>=
20300
20301   exp_err("Division by zero");
20302 @.Division by zero@>
20303   help2("You're trying to divide the quantity shown above the error")
20304     ("message by zero. I'm going to divide it by one instead.");
20305   mp_put_get_error(mp);
20306 }
20307
20308 @ @<Additional cases of binary operators@>=
20309 case pythag_add:
20310 case pythag_sub: 
20311    if ( (mp->cur_type==mp_known)&&(type(p)==mp_known) ) {
20312      if ( c==pythag_add ) mp->cur_exp=mp_pyth_add(mp, value(p),mp->cur_exp);
20313      else mp->cur_exp=mp_pyth_sub(mp, value(p),mp->cur_exp);
20314    } else mp_bad_binary(mp, p,c);
20315    break;
20316
20317 @ The next few sections of the program deal with affine transformations
20318 of coordinate data.
20319
20320 @<Additional cases of binary operators@>=
20321 case rotated_by: case slanted_by:
20322 case scaled_by: case shifted_by: case transformed_by:
20323 case x_scaled: case y_scaled: case z_scaled:
20324   if ( type(p)==mp_path_type ) { 
20325     path_trans(c,p); return;
20326   } else if ( type(p)==mp_pen_type ) { 
20327     pen_trans(c,p);
20328     mp->cur_exp=mp_convex_hull(mp, mp->cur_exp); 
20329       /* rounding error could destroy convexity */
20330     return;
20331   } else if ( (type(p)==mp_pair_type)||(type(p)==mp_transform_type) ) {
20332     mp_big_trans(mp, p,c);
20333   } else if ( type(p)==mp_picture_type ) {
20334     mp_do_edges_trans(mp, p,c); return;
20335   } else {
20336     mp_bad_binary(mp, p,c);
20337   }
20338   break;
20339
20340 @ Let |c| be one of the eight transform operators. The procedure call
20341 |set_up_trans(c)| first changes |cur_exp| to a transform that corresponds to
20342 |c| and the original value of |cur_exp|. (In particular, |cur_exp| doesn't
20343 change at all if |c=transformed_by|.)
20344
20345 Then, if all components of the resulting transform are |known|, they are
20346 moved to the global variables |txx|, |txy|, |tyx|, |tyy|, |tx|, |ty|;
20347 and |cur_exp| is changed to the known value zero.
20348
20349 @<Declare binary action...@>=
20350 void mp_set_up_trans (MP mp,quarterword c) {
20351   pointer p,q,r; /* list manipulation registers */
20352   if ( (c!=transformed_by)||(mp->cur_type!=mp_transform_type) ) {
20353     @<Put the current transform into |cur_exp|@>;
20354   }
20355   @<If the current transform is entirely known, stash it in global variables;
20356     otherwise |return|@>;
20357 }
20358
20359 @ @<Glob...@>=
20360 scaled txx;
20361 scaled txy;
20362 scaled tyx;
20363 scaled tyy;
20364 scaled tx;
20365 scaled ty; /* current transform coefficients */
20366
20367 @ @<Put the current transform...@>=
20368
20369   p=mp_stash_cur_exp(mp); 
20370   mp->cur_exp=mp_id_transform(mp); 
20371   mp->cur_type=mp_transform_type;
20372   q=value(mp->cur_exp);
20373   switch (c) {
20374   @<For each of the eight cases, change the relevant fields of |cur_exp|
20375     and |goto done|;
20376     but do nothing if capsule |p| doesn't have the appropriate type@>;
20377   }; /* there are no other cases */
20378   mp_disp_err(mp, p,"Improper transformation argument");
20379 @.Improper transformation argument@>
20380   help3("The expression shown above has the wrong type,")
20381        ("so I can\'t transform anything using it.")
20382        ("Proceed, and I'll omit the transformation.");
20383   mp_put_get_error(mp);
20384 DONE: 
20385   mp_recycle_value(mp, p); 
20386   mp_free_node(mp, p,value_node_size);
20387 }
20388
20389 @ @<If the current transform is entirely known, ...@>=
20390 q=value(mp->cur_exp); r=q+transform_node_size;
20391 do {  
20392   r=r-2;
20393   if ( type(r)!=mp_known ) return;
20394 } while (r!=q);
20395 mp->txx=value(xx_part_loc(q));
20396 mp->txy=value(xy_part_loc(q));
20397 mp->tyx=value(yx_part_loc(q));
20398 mp->tyy=value(yy_part_loc(q));
20399 mp->tx=value(x_part_loc(q));
20400 mp->ty=value(y_part_loc(q));
20401 mp_flush_cur_exp(mp, 0)
20402
20403 @ @<For each of the eight cases...@>=
20404 case rotated_by:
20405   if ( type(p)==mp_known )
20406     @<Install sines and cosines, then |goto done|@>;
20407   break;
20408 case slanted_by:
20409   if ( type(p)>mp_pair_type ) { 
20410    mp_install(mp, xy_part_loc(q),p); goto DONE;
20411   };
20412   break;
20413 case scaled_by:
20414   if ( type(p)>mp_pair_type ) { 
20415     mp_install(mp, xx_part_loc(q),p); mp_install(mp, yy_part_loc(q),p); 
20416     goto DONE;
20417   };
20418   break;
20419 case shifted_by:
20420   if ( type(p)==mp_pair_type ) {
20421     r=value(p); mp_install(mp, x_part_loc(q),x_part_loc(r));
20422     mp_install(mp, y_part_loc(q),y_part_loc(r)); goto DONE;
20423   };
20424   break;
20425 case x_scaled:
20426   if ( type(p)>mp_pair_type ) {
20427     mp_install(mp, xx_part_loc(q),p); goto DONE;
20428   };
20429   break;
20430 case y_scaled:
20431   if ( type(p)>mp_pair_type ) {
20432     mp_install(mp, yy_part_loc(q),p); goto DONE;
20433   };
20434   break;
20435 case z_scaled:
20436   if ( type(p)==mp_pair_type )
20437     @<Install a complex multiplier, then |goto done|@>;
20438   break;
20439 case transformed_by:
20440   break;
20441   
20442
20443 @ @<Install sines and cosines, then |goto done|@>=
20444 { mp_n_sin_cos(mp, (value(p) % three_sixty_units)*16);
20445   value(xx_part_loc(q))=mp_round_fraction(mp, mp->n_cos);
20446   value(yx_part_loc(q))=mp_round_fraction(mp, mp->n_sin);
20447   value(xy_part_loc(q))=-value(yx_part_loc(q));
20448   value(yy_part_loc(q))=value(xx_part_loc(q));
20449   goto DONE;
20450 }
20451
20452 @ @<Install a complex multiplier, then |goto done|@>=
20453
20454   r=value(p);
20455   mp_install(mp, xx_part_loc(q),x_part_loc(r));
20456   mp_install(mp, yy_part_loc(q),x_part_loc(r));
20457   mp_install(mp, yx_part_loc(q),y_part_loc(r));
20458   if ( type(y_part_loc(r))==mp_known ) negate(value(y_part_loc(r)));
20459   else mp_negate_dep_list(mp, dep_list(y_part_loc(r)));
20460   mp_install(mp, xy_part_loc(q),y_part_loc(r));
20461   goto DONE;
20462 }
20463
20464 @ Procedure |set_up_known_trans| is like |set_up_trans|, but it
20465 insists that the transformation be entirely known.
20466
20467 @<Declare binary action...@>=
20468 void mp_set_up_known_trans (MP mp,quarterword c) { 
20469   mp_set_up_trans(mp, c);
20470   if ( mp->cur_type!=mp_known ) {
20471     exp_err("Transform components aren't all known");
20472 @.Transform components...@>
20473     help3("I'm unable to apply a partially specified transformation")
20474       ("except to a fully known pair or transform.")
20475       ("Proceed, and I'll omit the transformation.");
20476     mp_put_get_flush_error(mp, 0);
20477     mp->txx=unity; mp->txy=0; mp->tyx=0; mp->tyy=unity; 
20478     mp->tx=0; mp->ty=0;
20479   }
20480 }
20481
20482 @ Here's a procedure that applies the transform |txx..ty| to a pair of
20483 coordinates in locations |p| and~|q|.
20484
20485 @<Declare binary action...@>= 
20486 void mp_trans (MP mp,pointer p, pointer q) {
20487   scaled v; /* the new |x| value */
20488   v=mp_take_scaled(mp, mp->mem[p].sc,mp->txx)+
20489   mp_take_scaled(mp, mp->mem[q].sc,mp->txy)+mp->tx;
20490   mp->mem[q].sc=mp_take_scaled(mp, mp->mem[p].sc,mp->tyx)+
20491   mp_take_scaled(mp, mp->mem[q].sc,mp->tyy)+mp->ty;
20492   mp->mem[p].sc=v;
20493 }
20494
20495 @ The simplest transformation procedure applies a transform to all
20496 coordinates of a path.  The |path_trans(c)(p)| macro applies
20497 a transformation defined by |cur_exp| and the transform operator |c|
20498 to the path~|p|.
20499
20500 @d path_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20501                      mp_unstash_cur_exp(mp, (B)); 
20502                      mp_do_path_trans(mp, mp->cur_exp); }
20503
20504 @<Declare binary action...@>=
20505 void mp_do_path_trans (MP mp,pointer p) {
20506   pointer q; /* list traverser */
20507   q=p;
20508   do { 
20509     if ( left_type(q)!=mp_endpoint ) 
20510       mp_trans(mp, q+3,q+4); /* that's |left_x| and |left_y| */
20511     mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20512     if ( right_type(q)!=mp_endpoint ) 
20513       mp_trans(mp, q+5,q+6); /* that's |right_x| and |right_y| */
20514 @^data structure assumptions@>
20515     q=link(q);
20516   } while (q!=p);
20517 }
20518
20519 @ Transforming a pen is very similar, except that there are no |left_type|
20520 and |right_type| fields.
20521
20522 @d pen_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20523                     mp_unstash_cur_exp(mp, (B)); 
20524                     mp_do_pen_trans(mp, mp->cur_exp); }
20525
20526 @<Declare binary action...@>=
20527 void mp_do_pen_trans (MP mp,pointer p) {
20528   pointer q; /* list traverser */
20529   if ( pen_is_elliptical(p) ) {
20530     mp_trans(mp, p+3,p+4); /* that's |left_x| and |left_y| */
20531     mp_trans(mp, p+5,p+6); /* that's |right_x| and |right_y| */
20532   };
20533   q=p;
20534   do { 
20535     mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20536 @^data structure assumptions@>
20537     q=link(q);
20538   } while (q!=p);
20539 }
20540
20541 @ The next transformation procedure applies to edge structures. It will do
20542 any transformation, but the results may be substandard if the picture contains
20543 text that uses downloaded bitmap fonts.  The binary action procedure is
20544 |do_edges_trans|, but we also need a function that just scales a picture.
20545 That routine is |scale_edges|.  Both it and the underlying routine |edges_trans|
20546 should be thought of as procedures that update an edge structure |h|, except
20547 that they have to return a (possibly new) structure because of the need to call
20548 |private_edges|.
20549
20550 @<Declare binary action...@>=
20551 pointer mp_edges_trans (MP mp, pointer h) {
20552   pointer q; /* the object being transformed */
20553   pointer r,s; /* for list manipulation */
20554   scaled sx,sy; /* saved transformation parameters */
20555   scaled sqdet; /* square root of determinant for |dash_scale| */
20556   integer sgndet; /* sign of the determinant */
20557   scaled v; /* a temporary value */
20558   h=mp_private_edges(mp, h);
20559   sqdet=mp_sqrt_det(mp, mp->txx,mp->txy,mp->tyx,mp->tyy);
20560   sgndet=mp_ab_vs_cd(mp, mp->txx,mp->tyy,mp->txy,mp->tyx);
20561   if ( dash_list(h)!=null_dash ) {
20562     @<Try to transform the dash list of |h|@>;
20563   }
20564   @<Make the bounding box of |h| unknown if it can't be updated properly
20565     without scanning the whole structure@>;  
20566   q=link(dummy_loc(h));
20567   while ( q!=null ) { 
20568     @<Transform graphical object |q|@>;
20569     q=link(q);
20570   }
20571   return h;
20572 }
20573 void mp_do_edges_trans (MP mp,pointer p, quarterword c) { 
20574   mp_set_up_known_trans(mp, c);
20575   value(p)=mp_edges_trans(mp, value(p));
20576   mp_unstash_cur_exp(mp, p);
20577 }
20578 void mp_scale_edges (MP mp) { 
20579   mp->txx=mp->se_sf; mp->tyy=mp->se_sf;
20580   mp->txy=0; mp->tyx=0; mp->tx=0; mp->ty=0;
20581   mp->se_pic=mp_edges_trans(mp, mp->se_pic);
20582 }
20583
20584 @ @<Try to transform the dash list of |h|@>=
20585 if ( (mp->txy!=0)||(mp->tyx!=0)||
20586      (mp->ty!=0)||(abs(mp->txx)!=abs(mp->tyy))) {
20587   mp_flush_dash_list(mp, h);
20588 } else { 
20589   if ( mp->txx<0 ) { @<Reverse the dash list of |h|@>; } 
20590   @<Scale the dash list by |txx| and shift it by |tx|@>;
20591   dash_y(h)=mp_take_scaled(mp, dash_y(h),abs(mp->tyy));
20592 }
20593
20594 @ @<Reverse the dash list of |h|@>=
20595
20596   r=dash_list(h);
20597   dash_list(h)=null_dash;
20598   while ( r!=null_dash ) {
20599     s=r; r=link(r);
20600     v=start_x(s); start_x(s)=stop_x(s); stop_x(s)=v;
20601     link(s)=dash_list(h);
20602     dash_list(h)=s;
20603   }
20604 }
20605
20606 @ @<Scale the dash list by |txx| and shift it by |tx|@>=
20607 r=dash_list(h);
20608 while ( r!=null_dash ) {
20609   start_x(r)=mp_take_scaled(mp, start_x(r),mp->txx)+mp->tx;
20610   stop_x(r)=mp_take_scaled(mp, stop_x(r),mp->txx)+mp->tx;
20611   r=link(r);
20612 }
20613
20614 @ @<Make the bounding box of |h| unknown if it can't be updated properly...@>=
20615 if ( (mp->txx==0)&&(mp->tyy==0) ) {
20616   @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>;
20617 } else if ( (mp->txy!=0)||(mp->tyx!=0) ) {
20618   mp_init_bbox(mp, h);
20619   goto DONE1;
20620 }
20621 if ( minx_val(h)<=maxx_val(h) ) {
20622   @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift by
20623    |(tx,ty)|@>;
20624 }
20625 DONE1:
20626
20627
20628
20629 @ @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>=
20630
20631   v=minx_val(h); minx_val(h)=miny_val(h); miny_val(h)=v;
20632   v=maxx_val(h); maxx_val(h)=maxy_val(h); maxy_val(h)=v;
20633 }
20634
20635 @ The sum ``|txx+txy|'' is whichever of |txx| or |txy| is nonzero.  The other
20636 sum is similar.
20637
20638 @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift...@>=
20639
20640   minx_val(h)=mp_take_scaled(mp, minx_val(h),mp->txx+mp->txy)+mp->tx;
20641   maxx_val(h)=mp_take_scaled(mp, maxx_val(h),mp->txx+mp->txy)+mp->tx;
20642   miny_val(h)=mp_take_scaled(mp, miny_val(h),mp->tyx+mp->tyy)+mp->ty;
20643   maxy_val(h)=mp_take_scaled(mp, maxy_val(h),mp->tyx+mp->tyy)+mp->ty;
20644   if ( mp->txx+mp->txy<0 ) {
20645     v=minx_val(h); minx_val(h)=maxx_val(h); maxx_val(h)=v;
20646   }
20647   if ( mp->tyx+mp->tyy<0 ) {
20648     v=miny_val(h); miny_val(h)=maxy_val(h); maxy_val(h)=v;
20649   }
20650 }
20651
20652 @ Now we ready for the main task of transforming the graphical objects in edge
20653 structure~|h|.
20654
20655 @<Transform graphical object |q|@>=
20656 switch (type(q)) {
20657 case mp_fill_code: case mp_stroked_code: 
20658   mp_do_path_trans(mp, path_p(q));
20659   @<Transform |pen_p(q)|, making sure polygonal pens stay counter-clockwise@>;
20660   break;
20661 case mp_start_clip_code: case mp_start_bounds_code: 
20662   mp_do_path_trans(mp, path_p(q));
20663   break;
20664 case mp_text_code: 
20665   r=text_tx_loc(q);
20666   @<Transform the compact transformation starting at |r|@>;
20667   break;
20668 case mp_stop_clip_code: case mp_stop_bounds_code: 
20669   break;
20670 } /* there are no other cases */
20671
20672 @ Note that the shift parameters |(tx,ty)| apply only to the path being stroked.
20673 The |dash_scale| has to be adjusted  to scale the dash lengths in |dash_p(q)|
20674 since the \ps\ output procedures will try to compensate for the transformation
20675 we are applying to |pen_p(q)|.  Since this compensation is based on the square
20676 root of the determinant, |sqdet| is the appropriate factor.
20677
20678 @<Transform |pen_p(q)|, making sure...@>=
20679 if ( pen_p(q)!=null ) {
20680   sx=mp->tx; sy=mp->ty;
20681   mp->tx=0; mp->ty=0;
20682   mp_do_pen_trans(mp, pen_p(q));
20683   if ( ((type(q)==mp_stroked_code)&&(dash_p(q)!=null)) )
20684     dash_scale(q)=mp_take_scaled(mp, dash_scale(q),sqdet);
20685   if ( ! pen_is_elliptical(pen_p(q)) )
20686     if ( sgndet<0 )
20687       pen_p(q)=mp_make_pen(mp, mp_copy_path(mp, pen_p(q)),true); 
20688          /* this unreverses the pen */
20689   mp->tx=sx; mp->ty=sy;
20690 }
20691
20692 @ This uses the fact that transformations are stored in the order
20693 |(tx,ty,txx,txy,tyx,tyy)|.
20694 @^data structure assumptions@>
20695
20696 @<Transform the compact transformation starting at |r|@>=
20697 mp_trans(mp, r,r+1);
20698 sx=mp->tx; sy=mp->ty;
20699 mp->tx=0; mp->ty=0;
20700 mp_trans(mp, r+2,r+4);
20701 mp_trans(mp, r+3,r+5);
20702 mp->tx=sx; mp->ty=sy
20703
20704 @ The hard cases of transformation occur when big nodes are involved,
20705 and when some of their components are unknown.
20706
20707 @<Declare binary action...@>=
20708 @<Declare subroutines needed by |big_trans|@>;
20709 void mp_big_trans (MP mp,pointer p, quarterword c) {
20710   pointer q,r,pp,qq; /* list manipulation registers */
20711   small_number s; /* size of a big node */
20712   s=mp->big_node_size[type(p)]; q=value(p); r=q+s;
20713   do {  
20714     r=r-2;
20715     if ( type(r)!=mp_known ) {
20716       @<Transform an unknown big node and |return|@>;
20717     }
20718   } while (r!=q);
20719   @<Transform a known big node@>;
20720 }; /* node |p| will now be recycled by |do_binary| */
20721
20722 @ @<Transform an unknown big node and |return|@>=
20723
20724   mp_set_up_known_trans(mp, c); mp_make_exp_copy(mp, p); 
20725   r=value(mp->cur_exp);
20726   if ( mp->cur_type==mp_transform_type ) {
20727     mp_bilin1(mp, yy_part_loc(r),mp->tyy,xy_part_loc(q),mp->tyx,0);
20728     mp_bilin1(mp, yx_part_loc(r),mp->tyy,xx_part_loc(q),mp->tyx,0);
20729     mp_bilin1(mp, xy_part_loc(r),mp->txx,yy_part_loc(q),mp->txy,0);
20730     mp_bilin1(mp, xx_part_loc(r),mp->txx,yx_part_loc(q),mp->txy,0);
20731   }
20732   mp_bilin1(mp, y_part_loc(r),mp->tyy,x_part_loc(q),mp->tyx,mp->ty);
20733   mp_bilin1(mp, x_part_loc(r),mp->txx,y_part_loc(q),mp->txy,mp->tx);
20734   return;
20735 }
20736
20737 @ Let |p| point to a two-word value field inside a big node of |cur_exp|,
20738 and let |q| point to a another value field. The |bilin1| procedure
20739 replaces |p| by $p\cdot t+q\cdot u+\delta$.
20740
20741 @<Declare subroutines needed by |big_trans|@>=
20742 void mp_bilin1 (MP mp, pointer p, scaled t, pointer q, 
20743                 scaled u, scaled delta) {
20744   pointer r; /* list traverser */
20745   if ( t!=unity ) mp_dep_mult(mp, p,t,true);
20746   if ( u!=0 ) {
20747     if ( type(q)==mp_known ) {
20748       delta+=mp_take_scaled(mp, value(q),u);
20749     } else { 
20750       @<Ensure that |type(p)=mp_proto_dependent|@>;
20751       dep_list(p)=mp_p_plus_fq(mp, dep_list(p),u,dep_list(q),
20752                                mp_proto_dependent,type(q));
20753     }
20754   }
20755   if ( type(p)==mp_known ) {
20756     value(p)+=delta;
20757   } else {
20758     r=dep_list(p);
20759     while ( info(r)!=null ) r=link(r);
20760     delta+=value(r);
20761     if ( r!=dep_list(p) ) value(r)=delta;
20762     else { mp_recycle_value(mp, p); type(p)=mp_known; value(p)=delta; };
20763   }
20764   if ( mp->fix_needed ) mp_fix_dependencies(mp);
20765 }
20766
20767 @ @<Ensure that |type(p)=mp_proto_dependent|@>=
20768 if ( type(p)!=mp_proto_dependent ) {
20769   if ( type(p)==mp_known ) 
20770     mp_new_dep(mp, p,mp_const_dependency(mp, value(p)));
20771   else 
20772     dep_list(p)=mp_p_times_v(mp, dep_list(p),unity,mp_dependent,
20773                              mp_proto_dependent,true);
20774   type(p)=mp_proto_dependent;
20775 }
20776
20777 @ @<Transform a known big node@>=
20778 mp_set_up_trans(mp, c);
20779 if ( mp->cur_type==mp_known ) {
20780   @<Transform known by known@>;
20781 } else { 
20782   pp=mp_stash_cur_exp(mp); qq=value(pp);
20783   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20784   if ( mp->cur_type==mp_transform_type ) {
20785     mp_bilin2(mp, yy_part_loc(r),yy_part_loc(qq),
20786       value(xy_part_loc(q)),yx_part_loc(qq),null);
20787     mp_bilin2(mp, yx_part_loc(r),yy_part_loc(qq),
20788       value(xx_part_loc(q)),yx_part_loc(qq),null);
20789     mp_bilin2(mp, xy_part_loc(r),xx_part_loc(qq),
20790       value(yy_part_loc(q)),xy_part_loc(qq),null);
20791     mp_bilin2(mp, xx_part_loc(r),xx_part_loc(qq),
20792       value(yx_part_loc(q)),xy_part_loc(qq),null);
20793   };
20794   mp_bilin2(mp, y_part_loc(r),yy_part_loc(qq),
20795     value(x_part_loc(q)),yx_part_loc(qq),y_part_loc(qq));
20796   mp_bilin2(mp, x_part_loc(r),xx_part_loc(qq),
20797     value(y_part_loc(q)),xy_part_loc(qq),x_part_loc(qq));
20798   mp_recycle_value(mp, pp); mp_free_node(mp, pp,value_node_size);
20799 }
20800
20801 @ Let |p| be a |mp_proto_dependent| value whose dependency list ends
20802 at |dep_final|. The following procedure adds |v| times another
20803 numeric quantity to~|p|.
20804
20805 @<Declare subroutines needed by |big_trans|@>=
20806 void mp_add_mult_dep (MP mp,pointer p, scaled v, pointer r) { 
20807   if ( type(r)==mp_known ) {
20808     value(mp->dep_final)+=mp_take_scaled(mp, value(r),v);
20809   } else  { 
20810     dep_list(p)=mp_p_plus_fq(mp, dep_list(p),v,dep_list(r),
20811                                                          mp_proto_dependent,type(r));
20812     if ( mp->fix_needed ) mp_fix_dependencies(mp);
20813   }
20814 }
20815
20816 @ The |bilin2| procedure is something like |bilin1|, but with known
20817 and unknown quantities reversed. Parameter |p| points to a value field
20818 within the big node for |cur_exp|; and |type(p)=mp_known|. Parameters
20819 |t| and~|u| point to value fields elsewhere; so does parameter~|q|,
20820 unless it is |null| (which stands for zero). Location~|p| will be
20821 replaced by $p\cdot t+v\cdot u+q$.
20822
20823 @<Declare subroutines needed by |big_trans|@>=
20824 void mp_bilin2 (MP mp,pointer p, pointer t, scaled v, 
20825                 pointer u, pointer q) {
20826   scaled vv; /* temporary storage for |value(p)| */
20827   vv=value(p); type(p)=mp_proto_dependent;
20828   mp_new_dep(mp, p,mp_const_dependency(mp, 0)); /* this sets |dep_final| */
20829   if ( vv!=0 ) 
20830     mp_add_mult_dep(mp, p,vv,t); /* |dep_final| doesn't change */
20831   if ( v!=0 ) mp_add_mult_dep(mp, p,v,u);
20832   if ( q!=null ) mp_add_mult_dep(mp, p,unity,q);
20833   if ( dep_list(p)==mp->dep_final ) {
20834     vv=value(mp->dep_final); mp_recycle_value(mp, p);
20835     type(p)=mp_known; value(p)=vv;
20836   }
20837 }
20838
20839 @ @<Transform known by known@>=
20840
20841   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20842   if ( mp->cur_type==mp_transform_type ) {
20843     mp_bilin3(mp, yy_part_loc(r),mp->tyy,value(xy_part_loc(q)),mp->tyx,0);
20844     mp_bilin3(mp, yx_part_loc(r),mp->tyy,value(xx_part_loc(q)),mp->tyx,0);
20845     mp_bilin3(mp, xy_part_loc(r),mp->txx,value(yy_part_loc(q)),mp->txy,0);
20846     mp_bilin3(mp, xx_part_loc(r),mp->txx,value(yx_part_loc(q)),mp->txy,0);
20847   }
20848   mp_bilin3(mp, y_part_loc(r),mp->tyy,value(x_part_loc(q)),mp->tyx,mp->ty);
20849   mp_bilin3(mp, x_part_loc(r),mp->txx,value(y_part_loc(q)),mp->txy,mp->tx);
20850 }
20851
20852 @ Finally, in |bilin3| everything is |known|.
20853
20854 @<Declare subroutines needed by |big_trans|@>=
20855 void mp_bilin3 (MP mp,pointer p, scaled t, 
20856                scaled v, scaled u, scaled delta) { 
20857   if ( t!=unity )
20858     delta+=mp_take_scaled(mp, value(p),t);
20859   else 
20860     delta+=value(p);
20861   if ( u!=0 ) value(p)=delta+mp_take_scaled(mp, v,u);
20862   else value(p)=delta;
20863 }
20864
20865 @ @<Additional cases of binary operators@>=
20866 case concatenate: 
20867   if ( (mp->cur_type==mp_string_type)&&(type(p)==mp_string_type) ) mp_cat(mp, p);
20868   else mp_bad_binary(mp, p,concatenate);
20869   break;
20870 case substring_of: 
20871   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_string_type) )
20872     mp_chop_string(mp, value(p));
20873   else mp_bad_binary(mp, p,substring_of);
20874   break;
20875 case subpath_of: 
20876   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
20877   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_path_type) )
20878     mp_chop_path(mp, value(p));
20879   else mp_bad_binary(mp, p,subpath_of);
20880   break;
20881
20882 @ @<Declare binary action...@>=
20883 void mp_cat (MP mp,pointer p) {
20884   str_number a,b; /* the strings being concatenated */
20885   pool_pointer k; /* index into |str_pool| */
20886   a=value(p); b=mp->cur_exp; str_room(length(a)+length(b));
20887   for (k=mp->str_start[a];k<=str_stop(a)-1;k++) {
20888     append_char(mp->str_pool[k]);
20889   }
20890   for (k=mp->str_start[b];k<=str_stop(b)-1;k++) {
20891     append_char(mp->str_pool[k]);
20892   }
20893   mp->cur_exp=mp_make_string(mp); delete_str_ref(b);
20894 }
20895
20896 @ @<Declare binary action...@>=
20897 void mp_chop_string (MP mp,pointer p) {
20898   integer a, b; /* start and stop points */
20899   integer l; /* length of the original string */
20900   integer k; /* runs from |a| to |b| */
20901   str_number s; /* the original string */
20902   boolean reversed; /* was |a>b|? */
20903   a=mp_round_unscaled(mp, value(x_part_loc(p)));
20904   b=mp_round_unscaled(mp, value(y_part_loc(p)));
20905   if ( a<=b ) reversed=false;
20906   else  { reversed=true; k=a; a=b; b=k; };
20907   s=mp->cur_exp; l=length(s);
20908   if ( a<0 ) { 
20909     a=0;
20910     if ( b<0 ) b=0;
20911   }
20912   if ( b>l ) { 
20913     b=l;
20914     if ( a>l ) a=l;
20915   }
20916   str_room(b-a);
20917   if ( reversed ) {
20918     for (k=mp->str_start[s]+b-1;k>=mp->str_start[s]+a;k--)  {
20919       append_char(mp->str_pool[k]);
20920     }
20921   } else  {
20922     for (k=mp->str_start[s]+a;k<=mp->str_start[s]+b-1;k++)  {
20923       append_char(mp->str_pool[k]);
20924     }
20925   }
20926   mp->cur_exp=mp_make_string(mp); delete_str_ref(s);
20927 }
20928
20929 @ @<Declare binary action...@>=
20930 void mp_chop_path (MP mp,pointer p) {
20931   pointer q; /* a knot in the original path */
20932   pointer pp,qq,rr,ss; /* link variables for copies of path nodes */
20933   scaled a,b,k,l; /* indices for chopping */
20934   boolean reversed; /* was |a>b|? */
20935   l=mp_path_length(mp); a=value(x_part_loc(p)); b=value(y_part_loc(p));
20936   if ( a<=b ) reversed=false;
20937   else  { reversed=true; k=a; a=b; b=k; };
20938   @<Dispense with the cases |a<0| and/or |b>l|@>;
20939   q=mp->cur_exp;
20940   while ( a>=unity ) {
20941     q=link(q); a=a-unity; b=b-unity;
20942   }
20943   if ( b==a ) {
20944     @<Construct a path from |pp| to |qq| of length zero@>; 
20945   } else { 
20946     @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>; 
20947   }
20948   left_type(pp)=mp_endpoint; right_type(qq)=mp_endpoint; link(qq)=pp;
20949   mp_toss_knot_list(mp, mp->cur_exp);
20950   if ( reversed ) {
20951     mp->cur_exp=link(mp_htap_ypoc(mp, pp)); mp_toss_knot_list(mp, pp);
20952   } else {
20953     mp->cur_exp=pp;
20954   }
20955 }
20956
20957 @ @<Dispense with the cases |a<0| and/or |b>l|@>=
20958 if ( a<0 ) {
20959   if ( left_type(mp->cur_exp)==mp_endpoint ) {
20960     a=0; if ( b<0 ) b=0;
20961   } else  {
20962     do {  a=a+l; b=b+l; } while (a<0); /* a cycle always has length |l>0| */
20963   }
20964 }
20965 if ( b>l ) {
20966   if ( left_type(mp->cur_exp)==mp_endpoint ) {
20967     b=l; if ( a>l ) a=l;
20968   } else {
20969     while ( a>=l ) { 
20970       a=a-l; b=b-l;
20971     }
20972   }
20973 }
20974
20975 @ @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>=
20976
20977   pp=mp_copy_knot(mp, q); qq=pp;
20978   do {  
20979     q=link(q); rr=qq; qq=mp_copy_knot(mp, q); link(rr)=qq; b=b-unity;
20980   } while (b>0);
20981   if ( a>0 ) {
20982     ss=pp; pp=link(pp);
20983     mp_split_cubic(mp, ss,a*010000); pp=link(ss);
20984     mp_free_node(mp, ss,knot_node_size);
20985     if ( rr==ss ) {
20986       b=mp_make_scaled(mp, b,unity-a); rr=pp;
20987     }
20988   }
20989   if ( b<0 ) {
20990     mp_split_cubic(mp, rr,(b+unity)*010000);
20991     mp_free_node(mp, qq,knot_node_size);
20992     qq=link(rr);
20993   }
20994 }
20995
20996 @ @<Construct a path from |pp| to |qq| of length zero@>=
20997
20998   if ( a>0 ) { mp_split_cubic(mp, q,a*010000); q=link(q); };
20999   pp=mp_copy_knot(mp, q); qq=pp;
21000 }
21001
21002 @ @<Additional cases of binary operators@>=
21003 case point_of: case precontrol_of: case postcontrol_of: 
21004   if ( mp->cur_type==mp_pair_type )
21005      mp_pair_to_path(mp);
21006   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
21007     mp_find_point(mp, value(p),c);
21008   else 
21009     mp_bad_binary(mp, p,c);
21010   break;
21011 case pen_offset_of: 
21012   if ( (mp->cur_type==mp_pen_type)&& mp_nice_pair(mp, p,type(p)) )
21013     mp_set_up_offset(mp, value(p));
21014   else 
21015     mp_bad_binary(mp, p,pen_offset_of);
21016   break;
21017 case direction_time_of: 
21018   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21019   if ( (mp->cur_type==mp_path_type)&& mp_nice_pair(mp, p,type(p)) )
21020     mp_set_up_direction_time(mp, value(p));
21021   else 
21022     mp_bad_binary(mp, p,direction_time_of);
21023   break;
21024 case envelope_of:
21025   if ( (type(p) != mp_pen_type) || (mp->cur_type != mp_path_type) )
21026     mp_bad_binary(mp, p,envelope_of);
21027   else
21028     mp_set_up_envelope(mp, p);
21029   break;
21030
21031 @ @<Declare binary action...@>=
21032 void mp_set_up_offset (MP mp,pointer p) { 
21033   mp_find_offset(mp, value(x_part_loc(p)),value(y_part_loc(p)),mp->cur_exp);
21034   mp_pair_value(mp, mp->cur_x,mp->cur_y);
21035 }
21036 void mp_set_up_direction_time (MP mp,pointer p) { 
21037   mp_flush_cur_exp(mp, mp_find_direction_time(mp, value(x_part_loc(p)),
21038   value(y_part_loc(p)),mp->cur_exp));
21039 }
21040 void mp_set_up_envelope (MP mp,pointer p) {
21041   pointer q = mp_copy_path(mp, mp->cur_exp); /* the original path */
21042   /* TODO: accept elliptical pens for straight paths */
21043   if (pen_is_elliptical(value(p))) {
21044     mp_bad_envelope_pen(mp);
21045     mp->cur_exp = q;
21046     mp->cur_type = mp_path_type;
21047     return;
21048   }
21049   small_number ljoin, lcap;
21050   scaled miterlim;
21051   if ( mp->internal[mp_linejoin]>unity ) ljoin=2;
21052   else if ( mp->internal[mp_linejoin]>0 ) ljoin=1;
21053   else ljoin=0;
21054   if ( mp->internal[mp_linecap]>unity ) lcap=2;
21055   else if ( mp->internal[mp_linecap]>0 ) lcap=1;
21056   else lcap=0;
21057   if ( mp->internal[mp_miterlimit]<unity )
21058     miterlim=unity;
21059   else
21060     miterlim=mp->internal[mp_miterlimit];
21061   mp->cur_exp = mp_make_envelope(mp, q, value(p), ljoin,lcap,miterlim);
21062   mp->cur_type = mp_path_type;
21063 }
21064
21065 @ @<Declare binary action...@>=
21066 void mp_find_point (MP mp,scaled v, quarterword c) {
21067   pointer p; /* the path */
21068   scaled n; /* its length */
21069   p=mp->cur_exp;
21070   if ( left_type(p)==mp_endpoint ) n=-unity; else n=0;
21071   do {  p=link(p); n=n+unity; } while (p!=mp->cur_exp);
21072   if ( n==0 ) { 
21073     v=0; 
21074   } else if ( v<0 ) {
21075     if ( left_type(p)==mp_endpoint ) v=0;
21076     else v=n-1-((-v-1) % n);
21077   } else if ( v>n ) {
21078     if ( left_type(p)==mp_endpoint ) v=n;
21079     else v=v % n;
21080   }
21081   p=mp->cur_exp;
21082   while ( v>=unity ) { p=link(p); v=v-unity;  };
21083   if ( v!=0 ) {
21084      @<Insert a fractional node by splitting the cubic@>;
21085   }
21086   @<Set the current expression to the desired path coordinates@>;
21087 }
21088
21089 @ @<Insert a fractional node...@>=
21090 { mp_split_cubic(mp, p,v*010000); p=link(p); }
21091
21092 @ @<Set the current expression to the desired path coordinates...@>=
21093 switch (c) {
21094 case point_of: 
21095   mp_pair_value(mp, x_coord(p),y_coord(p));
21096   break;
21097 case precontrol_of: 
21098   if ( left_type(p)==mp_endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
21099   else mp_pair_value(mp, left_x(p),left_y(p));
21100   break;
21101 case postcontrol_of: 
21102   if ( right_type(p)==mp_endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
21103   else mp_pair_value(mp, right_x(p),right_y(p));
21104   break;
21105 } /* there are no other cases */
21106
21107 @ @<Additional cases of binary operators@>=
21108 case arc_time_of: 
21109   if ( mp->cur_type==mp_pair_type )
21110      mp_pair_to_path(mp);
21111   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
21112     mp_flush_cur_exp(mp, mp_get_arc_time(mp, mp->cur_exp,value(p)));
21113   else 
21114     mp_bad_binary(mp, p,c);
21115   break;
21116
21117 @ @<Additional cases of bin...@>=
21118 case intersect: 
21119   if ( type(p)==mp_pair_type ) {
21120     q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p);
21121     mp_pair_to_path(mp); p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
21122   };
21123   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21124   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_path_type) ) {
21125     mp_path_intersection(mp, value(p),mp->cur_exp);
21126     mp_pair_value(mp, mp->cur_t,mp->cur_tt);
21127   } else {
21128     mp_bad_binary(mp, p,intersect);
21129   }
21130   break;
21131
21132 @ @<Additional cases of bin...@>=
21133 case in_font:
21134   if ( (mp->cur_type!=mp_string_type)||(type(p)!=mp_string_type)) 
21135     mp_bad_binary(mp, p,in_font);
21136   else { mp_do_infont(mp, p); return; }
21137   break;
21138
21139 @ Function |new_text_node| owns the reference count for its second argument
21140 (the text string) but not its first (the font name).
21141
21142 @<Declare binary action...@>=
21143 void mp_do_infont (MP mp,pointer p) {
21144   pointer q;
21145   q=mp_get_node(mp, edge_header_size);
21146   mp_init_edges(mp, q);
21147   link(obj_tail(q))=mp_new_text_node(mp,str(mp->cur_exp),value(p));
21148   obj_tail(q)=link(obj_tail(q));
21149   mp_free_node(mp, p,value_node_size);
21150   mp_flush_cur_exp(mp, q);
21151   mp->cur_type=mp_picture_type;
21152 }
21153
21154 @* \[40] Statements and commands.
21155 The chief executive of \MP\ is the |do_statement| routine, which
21156 contains the master switch that causes all the various pieces of \MP\
21157 to do their things, in the right order.
21158
21159 In a sense, this is the grand climax of the program: It applies all the
21160 tools that we have worked so hard to construct. In another sense, this is
21161 the messiest part of the program: It necessarily refers to other pieces
21162 of code all over the place, so that a person can't fully understand what is
21163 going on without paging back and forth to be reminded of conventions that
21164 are defined elsewhere. We are now at the hub of the web.
21165
21166 The structure of |do_statement| itself is quite simple.  The first token
21167 of the statement is fetched using |get_x_next|.  If it can be the first
21168 token of an expression, we look for an equation, an assignment, or a
21169 title. Otherwise we use a \&{case} construction to branch at high speed to
21170 the appropriate routine for various and sundry other types of commands,
21171 each of which has an ``action procedure'' that does the necessary work.
21172
21173 The program uses the fact that
21174 $$\hbox{|min_primary_command=max_statement_command=type_name|}$$
21175 to interpret a statement that starts with, e.g., `\&{string}',
21176 as a type declaration rather than a boolean expression.
21177
21178 @c void mp_do_statement (MP mp) { /* governs \MP's activities */
21179   mp->cur_type=mp_vacuous; mp_get_x_next(mp);
21180   if ( mp->cur_cmd>max_primary_command ) {
21181     @<Worry about bad statement@>;
21182   } else if ( mp->cur_cmd>max_statement_command ) {
21183     @<Do an equation, assignment, title, or
21184      `$\langle\,$expression$\,\rangle\,$\&{endgroup}'@>;
21185   } else {
21186     @<Do a statement that doesn't begin with an expression@>;
21187   }
21188   if ( mp->cur_cmd<semicolon )
21189     @<Flush unparsable junk that was found after the statement@>;
21190   mp->error_count=0;
21191 }
21192
21193 @ @<Declarations@>=
21194 @<Declare action procedures for use by |do_statement|@>;
21195
21196 @ The only command codes |>max_primary_command| that can be present
21197 at the beginning of a statement are |semicolon| and higher; these
21198 occur when the statement is null.
21199
21200 @<Worry about bad statement@>=
21201
21202   if ( mp->cur_cmd<semicolon ) {
21203     print_err("A statement can't begin with `");
21204 @.A statement can't begin with x@>
21205     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); mp_print_char(mp, '\'');
21206     help5("I was looking for the beginning of a new statement.")
21207       ("If you just proceed without changing anything, I'll ignore")
21208       ("everything up to the next `;'. Please insert a semicolon")
21209       ("now in front of anything that you don't want me to delete.")
21210       ("(See Chapter 27 of The METAFONTbook for an example.)");
21211 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21212     mp_back_error(mp); mp_get_x_next(mp);
21213   }
21214 }
21215
21216 @ The help message printed here says that everything is flushed up to
21217 a semicolon, but actually the commands |end_group| and |stop| will
21218 also terminate a statement.
21219
21220 @<Flush unparsable junk that was found after the statement@>=
21221
21222   print_err("Extra tokens will be flushed");
21223 @.Extra tokens will be flushed@>
21224   help6("I've just read as much of that statement as I could fathom,")
21225        ("so a semicolon should have been next. It's very puzzling...")
21226        ("but I'll try to get myself back together, by ignoring")
21227        ("everything up to the next `;'. Please insert a semicolon")
21228        ("now in front of anything that you don't want me to delete.")
21229        ("(See Chapter 27 of The METAFONTbook for an example.)");
21230 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21231   mp_back_error(mp); mp->scanner_status=flushing;
21232   do {  
21233     get_t_next;
21234     @<Decrease the string reference count...@>;
21235   } while (! end_of_statement); /* |cur_cmd=semicolon|, |end_group|, or |stop| */
21236   mp->scanner_status=normal;
21237 }
21238
21239 @ If |do_statement| ends with |cur_cmd=end_group|, we should have
21240 |cur_type=mp_vacuous| unless the statement was simply an expression;
21241 in the latter case, |cur_type| and |cur_exp| should represent that
21242 expression.
21243
21244 @<Do a statement that doesn't...@>=
21245
21246   if ( mp->internal[mp_tracing_commands]>0 ) 
21247     show_cur_cmd_mod;
21248   switch (mp->cur_cmd ) {
21249   case type_name:mp_do_type_declaration(mp); break;
21250   case macro_def:
21251     if ( mp->cur_mod>var_def ) mp_make_op_def(mp);
21252     else if ( mp->cur_mod>end_def ) mp_scan_def(mp);
21253      break;
21254   @<Cases of |do_statement| that invoke particular commands@>;
21255   } /* there are no other cases */
21256   mp->cur_type=mp_vacuous;
21257 }
21258
21259 @ The most important statements begin with expressions.
21260
21261 @<Do an equation, assignment, title, or...@>=
21262
21263   mp->var_flag=assignment; mp_scan_expression(mp);
21264   if ( mp->cur_cmd<end_group ) {
21265     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21266     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21267     else if ( mp->cur_type==mp_string_type ) {@<Do a title@> ; }
21268     else if ( mp->cur_type!=mp_vacuous ){ 
21269       exp_err("Isolated expression");
21270 @.Isolated expression@>
21271       help3("I couldn't find an `=' or `:=' after the")
21272         ("expression that is shown above this error message,")
21273         ("so I guess I'll just ignore it and carry on.");
21274       mp_put_get_error(mp);
21275     }
21276     mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous;
21277   }
21278 }
21279
21280 @ @<Do a title@>=
21281
21282   if ( mp->internal[mp_tracing_titles]>0 ) {
21283     mp_print_nl(mp, "");  mp_print_str(mp, mp->cur_exp); update_terminal;
21284   }
21285 }
21286
21287 @ Equations and assignments are performed by the pair of mutually recursive
21288 @^recursion@>
21289 routines |do_equation| and |do_assignment|. These routines are called when
21290 |cur_cmd=equals| and when |cur_cmd=assignment|, respectively; the left-hand
21291 side is in |cur_type| and |cur_exp|, while the right-hand side is yet
21292 to be scanned. After the routines are finished, |cur_type| and |cur_exp|
21293 will be equal to the right-hand side (which will normally be equal
21294 to the left-hand side).
21295
21296 @<Declare action procedures for use by |do_statement|@>=
21297 @<Declare the procedure called |try_eq|@>;
21298 @<Declare the procedure called |make_eq|@>;
21299 void mp_do_equation (MP mp) ;
21300
21301 @ @c
21302 void mp_do_equation (MP mp) {
21303   pointer lhs; /* capsule for the left-hand side */
21304   pointer p; /* temporary register */
21305   lhs=mp_stash_cur_exp(mp); mp_get_x_next(mp); 
21306   mp->var_flag=assignment; mp_scan_expression(mp);
21307   if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21308   else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21309   if ( mp->internal[mp_tracing_commands]>two ) 
21310     @<Trace the current equation@>;
21311   if ( mp->cur_type==mp_unknown_path ) if ( type(lhs)==mp_pair_type ) {
21312     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, lhs); lhs=p;
21313   }; /* in this case |make_eq| will change the pair to a path */
21314   mp_make_eq(mp, lhs); /* equate |lhs| to |(cur_type,cur_exp)| */
21315 }
21316
21317 @ And |do_assignment| is similar to |do_expression|:
21318
21319 @<Declarations@>=
21320 void mp_do_assignment (MP mp);
21321
21322 @ @<Declare action procedures for use by |do_statement|@>=
21323 void mp_do_assignment (MP mp) ;
21324
21325 @ @c
21326 void mp_do_assignment (MP mp) {
21327   pointer lhs; /* token list for the left-hand side */
21328   pointer p; /* where the left-hand value is stored */
21329   pointer q; /* temporary capsule for the right-hand value */
21330   if ( mp->cur_type!=mp_token_list ) { 
21331     exp_err("Improper `:=' will be changed to `='");
21332 @.Improper `:='@>
21333     help2("I didn't find a variable name at the left of the `:=',")
21334       ("so I'm going to pretend that you said `=' instead.");
21335     mp_error(mp); mp_do_equation(mp);
21336   } else { 
21337     lhs=mp->cur_exp; mp->cur_type=mp_vacuous;
21338     mp_get_x_next(mp); mp->var_flag=assignment; mp_scan_expression(mp);
21339     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21340     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21341     if ( mp->internal[mp_tracing_commands]>two ) 
21342       @<Trace the current assignment@>;
21343     if ( info(lhs)>hash_end ) {
21344       @<Assign the current expression to an internal variable@>;
21345     } else  {
21346       @<Assign the current expression to the variable |lhs|@>;
21347     }
21348     mp_flush_node_list(mp, lhs);
21349   }
21350 }
21351
21352 @ @<Trace the current equation@>=
21353
21354   mp_begin_diagnostic(mp); mp_print_nl(mp, "{("); mp_print_exp(mp,lhs,0);
21355   mp_print(mp,")=("); mp_print_exp(mp,null,0); 
21356   mp_print(mp,")}"); mp_end_diagnostic(mp, false);
21357 }
21358
21359 @ @<Trace the current assignment@>=
21360
21361   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
21362   if ( info(lhs)>hash_end ) 
21363      mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21364   else 
21365      mp_show_token_list(mp, lhs,null,1000,0);
21366   mp_print(mp, ":="); mp_print_exp(mp, null,0); 
21367   mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
21368 }
21369
21370 @ @<Assign the current expression to an internal variable@>=
21371 if ( mp->cur_type==mp_known )  {
21372   mp->internal[info(lhs)-(hash_end)]=mp->cur_exp;
21373 } else { 
21374   exp_err("Internal quantity `");
21375 @.Internal quantity...@>
21376   mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21377   mp_print(mp, "' must receive a known value");
21378   help2("I can\'t set an internal quantity to anything but a known")
21379     ("numeric value, so I'll have to ignore this assignment.");
21380   mp_put_get_error(mp);
21381 }
21382
21383 @ @<Assign the current expression to the variable |lhs|@>=
21384
21385   p=mp_find_variable(mp, lhs);
21386   if ( p!=null ) {
21387     q=mp_stash_cur_exp(mp); mp->cur_type=mp_und_type(mp, p); 
21388     mp_recycle_value(mp, p);
21389     type(p)=mp->cur_type; value(p)=null; mp_make_exp_copy(mp, p);
21390     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q); mp_make_eq(mp, p);
21391   } else  { 
21392     mp_obliterated(mp, lhs); mp_put_get_error(mp);
21393   }
21394 }
21395
21396
21397 @ And now we get to the nitty-gritty. The |make_eq| procedure is given
21398 a pointer to a capsule that is to be equated to the current expression.
21399
21400 @<Declare the procedure called |make_eq|@>=
21401 void mp_make_eq (MP mp,pointer lhs) ;
21402
21403
21404
21405 @c void mp_make_eq (MP mp,pointer lhs) {
21406   small_number t; /* type of the left-hand side */
21407   pointer p,q; /* pointers inside of big nodes */
21408   integer v=0; /* value of the left-hand side */
21409 RESTART: 
21410   t=type(lhs);
21411   if ( t<=mp_pair_type ) v=value(lhs);
21412   switch (t) {
21413   @<For each type |t|, make an equation and |goto done| unless |cur_type|
21414     is incompatible with~|t|@>;
21415   } /* all cases have been listed */
21416   @<Announce that the equation cannot be performed@>;
21417 DONE:
21418   check_arith; mp_recycle_value(mp, lhs); 
21419   mp_free_node(mp, lhs,value_node_size);
21420 }
21421
21422 @ @<Announce that the equation cannot be performed@>=
21423 mp_disp_err(mp, lhs,""); 
21424 exp_err("Equation cannot be performed (");
21425 @.Equation cannot be performed@>
21426 if ( type(lhs)<=mp_pair_type ) mp_print_type(mp, type(lhs));
21427 else mp_print(mp, "numeric");
21428 mp_print_char(mp, '=');
21429 if ( mp->cur_type<=mp_pair_type ) mp_print_type(mp, mp->cur_type);
21430 else mp_print(mp, "numeric");
21431 mp_print_char(mp, ')');
21432 help2("I'm sorry, but I don't know how to make such things equal.")
21433      ("(See the two expressions just above the error message.)");
21434 mp_put_get_error(mp)
21435
21436 @ @<For each type |t|, make an equation and |goto done| unless...@>=
21437 case mp_boolean_type: case mp_string_type: case mp_pen_type:
21438 case mp_path_type: case mp_picture_type:
21439   if ( mp->cur_type==t+unknown_tag ) { 
21440     mp_nonlinear_eq(mp, v,mp->cur_exp,false); goto DONE;
21441   } else if ( mp->cur_type==t ) {
21442     @<Report redundant or inconsistent equation and |goto done|@>;
21443   }
21444   break;
21445 case unknown_types:
21446   if ( mp->cur_type==t-unknown_tag ) { 
21447     mp_nonlinear_eq(mp, mp->cur_exp,lhs,true); goto DONE;
21448   } else if ( mp->cur_type==t ) { 
21449     mp_ring_merge(mp, lhs,mp->cur_exp); goto DONE;
21450   } else if ( mp->cur_type==mp_pair_type ) {
21451     if ( t==mp_unknown_path ) { 
21452      mp_pair_to_path(mp); goto RESTART;
21453     };
21454   }
21455   break;
21456 case mp_transform_type: case mp_color_type:
21457 case mp_cmykcolor_type: case mp_pair_type:
21458   if ( mp->cur_type==t ) {
21459     @<Do multiple equations and |goto done|@>;
21460   }
21461   break;
21462 case mp_known: case mp_dependent:
21463 case mp_proto_dependent: case mp_independent:
21464   if ( mp->cur_type>=mp_known ) { 
21465     mp_try_eq(mp, lhs,null); goto DONE;
21466   };
21467   break;
21468 case mp_vacuous:
21469   break;
21470
21471 @ @<Report redundant or inconsistent equation and |goto done|@>=
21472
21473   if ( mp->cur_type<=mp_string_type ) {
21474     if ( mp->cur_type==mp_string_type ) {
21475       if ( mp_str_vs_str(mp, v,mp->cur_exp)!=0 ) {
21476         goto NOT_FOUND;
21477       }
21478     } else if ( v!=mp->cur_exp ) {
21479       goto NOT_FOUND;
21480     }
21481     @<Exclaim about a redundant equation@>; goto DONE;
21482   }
21483   print_err("Redundant or inconsistent equation");
21484 @.Redundant or inconsistent equation@>
21485   help2("An equation between already-known quantities can't help.")
21486        ("But don't worry; continue and I'll just ignore it.");
21487   mp_put_get_error(mp); goto DONE;
21488 NOT_FOUND: 
21489   print_err("Inconsistent equation");
21490 @.Inconsistent equation@>
21491   help2("The equation I just read contradicts what was said before.")
21492        ("But don't worry; continue and I'll just ignore it.");
21493   mp_put_get_error(mp); goto DONE;
21494 }
21495
21496 @ @<Do multiple equations and |goto done|@>=
21497
21498   p=v+mp->big_node_size[t]; 
21499   q=value(mp->cur_exp)+mp->big_node_size[t];
21500   do {  
21501     p=p-2; q=q-2; mp_try_eq(mp, p,q);
21502   } while (p!=v);
21503   goto DONE;
21504 }
21505
21506 @ The first argument to |try_eq| is the location of a value node
21507 in a capsule that will soon be recycled. The second argument is
21508 either a location within a pair or transform node pointed to by
21509 |cur_exp|, or it is |null| (which means that |cur_exp| itself
21510 serves as the second argument). The idea is to leave |cur_exp| unchanged,
21511 but to equate the two operands.
21512
21513 @<Declare the procedure called |try_eq|@>=
21514 void mp_try_eq (MP mp,pointer l, pointer r) ;
21515
21516
21517 @c void mp_try_eq (MP mp,pointer l, pointer r) {
21518   pointer p; /* dependency list for right operand minus left operand */
21519   int t; /* the type of list |p| */
21520   pointer q; /* the constant term of |p| is here */
21521   pointer pp; /* dependency list for right operand */
21522   int tt; /* the type of list |pp| */
21523   boolean copied; /* have we copied a list that ought to be recycled? */
21524   @<Remove the left operand from its container, negate it, and
21525     put it into dependency list~|p| with constant term~|q|@>;
21526   @<Add the right operand to list |p|@>;
21527   if ( info(p)==null ) {
21528     @<Deal with redundant or inconsistent equation@>;
21529   } else { 
21530     mp_linear_eq(mp, p,t);
21531     if ( r==null ) if ( mp->cur_type!=mp_known ) {
21532       if ( type(mp->cur_exp)==mp_known ) {
21533         pp=mp->cur_exp; mp->cur_exp=value(mp->cur_exp); mp->cur_type=mp_known;
21534         mp_free_node(mp, pp,value_node_size);
21535       }
21536     }
21537   }
21538 }
21539
21540 @ @<Remove the left operand from its container, negate it, and...@>=
21541 t=type(l);
21542 if ( t==mp_known ) { 
21543   t=mp_dependent; p=mp_const_dependency(mp, -value(l)); q=p;
21544 } else if ( t==mp_independent ) {
21545   t=mp_dependent; p=mp_single_dependency(mp, l); negate(value(p));
21546   q=mp->dep_final;
21547 } else { 
21548   p=dep_list(l); q=p;
21549   while (1) { 
21550     negate(value(q));
21551     if ( info(q)==null ) break;
21552     q=link(q);
21553   }
21554   link(prev_dep(l))=link(q); prev_dep(link(q))=prev_dep(l);
21555   type(l)=mp_known;
21556 }
21557
21558 @ @<Deal with redundant or inconsistent equation@>=
21559
21560   if ( abs(value(p))>64 ) { /* off by .001 or more */
21561     print_err("Inconsistent equation");
21562 @.Inconsistent equation@>
21563     mp_print(mp, " (off by "); mp_print_scaled(mp, value(p)); 
21564     mp_print_char(mp, ')');
21565     help2("The equation I just read contradicts what was said before.")
21566       ("But don't worry; continue and I'll just ignore it.");
21567     mp_put_get_error(mp);
21568   } else if ( r==null ) {
21569     @<Exclaim about a redundant equation@>;
21570   }
21571   mp_free_node(mp, p,dep_node_size);
21572 }
21573
21574 @ @<Add the right operand to list |p|@>=
21575 if ( r==null ) {
21576   if ( mp->cur_type==mp_known ) {
21577     value(q)=value(q)+mp->cur_exp; goto DONE1;
21578   } else { 
21579     tt=mp->cur_type;
21580     if ( tt==mp_independent ) pp=mp_single_dependency(mp, mp->cur_exp);
21581     else pp=dep_list(mp->cur_exp);
21582   } 
21583 } else {
21584   if ( type(r)==mp_known ) {
21585     value(q)=value(q)+value(r); goto DONE1;
21586   } else { 
21587     tt=type(r);
21588     if ( tt==mp_independent ) pp=mp_single_dependency(mp, r);
21589     else pp=dep_list(r);
21590   }
21591 }
21592 if ( tt!=mp_independent ) copied=false;
21593 else  { copied=true; tt=mp_dependent; };
21594 @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>;
21595 if ( copied ) mp_flush_node_list(mp, pp);
21596 DONE1:
21597
21598 @ @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>=
21599 mp->watch_coefs=false;
21600 if ( t==tt ) {
21601   p=mp_p_plus_q(mp, p,pp,t);
21602 } else if ( t==mp_proto_dependent ) {
21603   p=mp_p_plus_fq(mp, p,unity,pp,mp_proto_dependent,mp_dependent);
21604 } else { 
21605   q=p;
21606   while ( info(q)!=null ) {
21607     value(q)=mp_round_fraction(mp, value(q)); q=link(q);
21608   }
21609   t=mp_proto_dependent; p=mp_p_plus_q(mp, p,pp,t);
21610 }
21611 mp->watch_coefs=true;
21612
21613 @ Our next goal is to process type declarations. For this purpose it's
21614 convenient to have a procedure that scans a $\langle\,$declared
21615 variable$\,\rangle$ and returns the corresponding token list. After the
21616 following procedure has acted, the token after the declared variable
21617 will have been scanned, so it will appear in |cur_cmd|, |cur_mod|,
21618 and~|cur_sym|.
21619
21620 @<Declare the function called |scan_declared_variable|@>=
21621 pointer mp_scan_declared_variable (MP mp) {
21622   pointer x; /* hash address of the variable's root */
21623   pointer h,t; /* head and tail of the token list to be returned */
21624   pointer l; /* hash address of left bracket */
21625   mp_get_symbol(mp); x=mp->cur_sym;
21626   if ( mp->cur_cmd!=tag_token ) mp_clear_symbol(mp, x,false);
21627   h=mp_get_avail(mp); info(h)=x; t=h;
21628   while (1) { 
21629     mp_get_x_next(mp);
21630     if ( mp->cur_sym==0 ) break;
21631     if ( mp->cur_cmd!=tag_token ) if ( mp->cur_cmd!=internal_quantity)  {
21632       if ( mp->cur_cmd==left_bracket ) {
21633         @<Descend past a collective subscript@>;
21634       } else {
21635         break;
21636       }
21637     }
21638     link(t)=mp_get_avail(mp); t=link(t); info(t)=mp->cur_sym;
21639   }
21640   if ( eq_type(x)!=tag_token ) mp_clear_symbol(mp, x,false);
21641   if ( equiv(x)==null ) mp_new_root(mp, x);
21642   return h;
21643 }
21644
21645 @ If the subscript isn't collective, we don't accept it as part of the
21646 declared variable.
21647
21648 @<Descend past a collective subscript@>=
21649
21650   l=mp->cur_sym; mp_get_x_next(mp);
21651   if ( mp->cur_cmd!=right_bracket ) {
21652     mp_back_input(mp); mp->cur_sym=l; mp->cur_cmd=left_bracket; break;
21653   } else {
21654     mp->cur_sym=collective_subscript;
21655   }
21656 }
21657
21658 @ Type declarations are introduced by the following primitive operations.
21659
21660 @<Put each...@>=
21661 mp_primitive(mp, "numeric",type_name,mp_numeric_type);
21662 @:numeric_}{\&{numeric} primitive@>
21663 mp_primitive(mp, "string",type_name,mp_string_type);
21664 @:string_}{\&{string} primitive@>
21665 mp_primitive(mp, "boolean",type_name,mp_boolean_type);
21666 @:boolean_}{\&{boolean} primitive@>
21667 mp_primitive(mp, "path",type_name,mp_path_type);
21668 @:path_}{\&{path} primitive@>
21669 mp_primitive(mp, "pen",type_name,mp_pen_type);
21670 @:pen_}{\&{pen} primitive@>
21671 mp_primitive(mp, "picture",type_name,mp_picture_type);
21672 @:picture_}{\&{picture} primitive@>
21673 mp_primitive(mp, "transform",type_name,mp_transform_type);
21674 @:transform_}{\&{transform} primitive@>
21675 mp_primitive(mp, "color",type_name,mp_color_type);
21676 @:color_}{\&{color} primitive@>
21677 mp_primitive(mp, "rgbcolor",type_name,mp_color_type);
21678 @:color_}{\&{rgbcolor} primitive@>
21679 mp_primitive(mp, "cmykcolor",type_name,mp_cmykcolor_type);
21680 @:color_}{\&{cmykcolor} primitive@>
21681 mp_primitive(mp, "pair",type_name,mp_pair_type);
21682 @:pair_}{\&{pair} primitive@>
21683
21684 @ @<Cases of |print_cmd...@>=
21685 case type_name: mp_print_type(mp, m); break;
21686
21687 @ Now we are ready to handle type declarations, assuming that a
21688 |type_name| has just been scanned.
21689
21690 @<Declare action procedures for use by |do_statement|@>=
21691 void mp_do_type_declaration (MP mp) ;
21692
21693 @ @c
21694 void mp_do_type_declaration (MP mp) {
21695   small_number t; /* the type being declared */
21696   pointer p; /* token list for a declared variable */
21697   pointer q; /* value node for the variable */
21698   if ( mp->cur_mod>=mp_transform_type ) 
21699     t=mp->cur_mod;
21700   else 
21701     t=mp->cur_mod+unknown_tag;
21702   do {  
21703     p=mp_scan_declared_variable(mp);
21704     mp_flush_variable(mp, equiv(info(p)),link(p),false);
21705     q=mp_find_variable(mp, p);
21706     if ( q!=null ) { 
21707       type(q)=t; value(q)=null; 
21708     } else  { 
21709       print_err("Declared variable conflicts with previous vardef");
21710 @.Declared variable conflicts...@>
21711       help2("You can't use, e.g., `numeric foo[]' after `vardef foo'.")
21712            ("Proceed, and I'll ignore the illegal redeclaration.");
21713       mp_put_get_error(mp);
21714     }
21715     mp_flush_list(mp, p);
21716     if ( mp->cur_cmd<comma ) {
21717       @<Flush spurious symbols after the declared variable@>;
21718     }
21719   } while (! end_of_statement);
21720 }
21721
21722 @ @<Flush spurious symbols after the declared variable@>=
21723
21724   print_err("Illegal suffix of declared variable will be flushed");
21725 @.Illegal suffix...flushed@>
21726   help5("Variables in declarations must consist entirely of")
21727     ("names and collective subscripts, e.g., `x[]a'.")
21728     ("Are you trying to use a reserved word in a variable name?")
21729     ("I'm going to discard the junk I found here,")
21730     ("up to the next comma or the end of the declaration.");
21731   if ( mp->cur_cmd==numeric_token )
21732     mp->help_line[2]="Explicit subscripts like `x15a' aren't permitted.";
21733   mp_put_get_error(mp); mp->scanner_status=flushing;
21734   do {  
21735     get_t_next;
21736     @<Decrease the string reference count...@>;
21737   } while (mp->cur_cmd<comma); /* either |end_of_statement| or |cur_cmd=comma| */
21738   mp->scanner_status=normal;
21739 }
21740
21741 @ \MP's |main_control| procedure just calls |do_statement| repeatedly
21742 until coming to the end of the user's program.
21743 Each execution of |do_statement| concludes with
21744 |cur_cmd=semicolon|, |end_group|, or |stop|.
21745
21746 @c void mp_main_control (MP mp) { 
21747   do {  
21748     mp_do_statement(mp);
21749     if ( mp->cur_cmd==end_group ) {
21750       print_err("Extra `endgroup'");
21751 @.Extra `endgroup'@>
21752       help2("I'm not currently working on a `begingroup',")
21753         ("so I had better not try to end anything.");
21754       mp_flush_error(mp, 0);
21755     }
21756   } while (mp->cur_cmd!=stop);
21757 }
21758 int __attribute__((noinline)) 
21759 mp_run (MP mp) {
21760   if (mp->history < mp_fatal_error_stop ) {
21761     @<Install and test the non-local jump buffer@>;
21762     mp_main_control(mp); /* come to life */
21763     mp_final_cleanup(mp); /* prepare for death */
21764     mp_close_files_and_terminate(mp);
21765   }
21766   return mp->history;
21767 }
21768 int __attribute__((noinline)) 
21769 mp_execute (MP mp) {
21770   if (mp->history < mp_fatal_error_stop ) {
21771     mp->history = mp_spotless;
21772     mp->file_offset = 0;
21773     mp->term_offset = 0;
21774     mp->tally = 0; 
21775     @<Install and test the non-local jump buffer@>;
21776         if (mp->run_state==0) {
21777       mp->run_state = 1;
21778     } else {
21779       mp_input_ln(mp,mp->term_in);
21780       mp_firm_up_the_line(mp);  
21781       mp->buffer[limit]='%';
21782       mp->first=limit+1; 
21783       loc=start;
21784     }
21785     mp_main_control(mp); /* come to life */ 
21786   }
21787   return mp->history;
21788 }
21789 int __attribute__((noinline)) 
21790 mp_finish (MP mp) {
21791   if (mp->history < mp_fatal_error_stop ) {
21792     @<Install and test the non-local jump buffer@>;
21793     mp_final_cleanup(mp); /* prepare for death */
21794     mp_close_files_and_terminate(mp);
21795   }
21796   return mp->history;
21797 }
21798 char * mp_mplib_version (MP mp) {
21799   assert(mp);
21800   return mplib_version;
21801 }
21802 char * mp_metapost_version (MP mp) {
21803   assert(mp);
21804   return metapost_version;
21805 }
21806
21807 @ @<Exported function headers@>=
21808 int mp_run (MP mp);
21809 int mp_execute (MP mp);
21810 int mp_finish (MP mp);
21811 char * mp_mplib_version (MP mp);
21812 char * mp_metapost_version (MP mp);
21813
21814 @ @<Put each...@>=
21815 mp_primitive(mp, "end",stop,0);
21816 @:end_}{\&{end} primitive@>
21817 mp_primitive(mp, "dump",stop,1);
21818 @:dump_}{\&{dump} primitive@>
21819
21820 @ @<Cases of |print_cmd...@>=
21821 case stop:
21822   if ( m==0 ) mp_print(mp, "end");
21823   else mp_print(mp, "dump");
21824   break;
21825
21826 @* \[41] Commands.
21827 Let's turn now to statements that are classified as ``commands'' because
21828 of their imperative nature. We'll begin with simple ones, so that it
21829 will be clear how to hook command processing into the |do_statement| routine;
21830 then we'll tackle the tougher commands.
21831
21832 Here's one of the simplest:
21833
21834 @<Cases of |do_statement|...@>=
21835 case mp_random_seed: mp_do_random_seed(mp);  break;
21836
21837 @ @<Declare action procedures for use by |do_statement|@>=
21838 void mp_do_random_seed (MP mp) ;
21839
21840 @ @c void mp_do_random_seed (MP mp) { 
21841   mp_get_x_next(mp);
21842   if ( mp->cur_cmd!=assignment ) {
21843     mp_missing_err(mp, ":=");
21844 @.Missing `:='@>
21845     help1("Always say `randomseed:=<numeric expression>'.");
21846     mp_back_error(mp);
21847   };
21848   mp_get_x_next(mp); mp_scan_expression(mp);
21849   if ( mp->cur_type!=mp_known ) {
21850     exp_err("Unknown value will be ignored");
21851 @.Unknown value...ignored@>
21852     help2("Your expression was too random for me to handle,")
21853       ("so I won't change the random seed just now.");
21854     mp_put_get_flush_error(mp, 0);
21855   } else {
21856    @<Initialize the random seed to |cur_exp|@>;
21857   }
21858 }
21859
21860 @ @<Initialize the random seed to |cur_exp|@>=
21861
21862   mp_init_randoms(mp, mp->cur_exp);
21863   if ( mp->selector>=log_only && mp->selector<write_file) {
21864     mp->old_setting=mp->selector; mp->selector=log_only;
21865     mp_print_nl(mp, "{randomseed:="); 
21866     mp_print_scaled(mp, mp->cur_exp); 
21867     mp_print_char(mp, '}');
21868     mp_print_nl(mp, ""); mp->selector=mp->old_setting;
21869   }
21870 }
21871
21872 @ And here's another simple one (somewhat different in flavor):
21873
21874 @<Cases of |do_statement|...@>=
21875 case mode_command: 
21876   mp_print_ln(mp); mp->interaction=mp->cur_mod;
21877   @<Initialize the print |selector| based on |interaction|@>;
21878   if ( mp->log_opened ) mp->selector=mp->selector+2;
21879   mp_get_x_next(mp);
21880   break;
21881
21882 @ @<Put each...@>=
21883 mp_primitive(mp, "batchmode",mode_command,mp_batch_mode);
21884 @:mp_batch_mode_}{\&{batchmode} primitive@>
21885 mp_primitive(mp, "nonstopmode",mode_command,mp_nonstop_mode);
21886 @:mp_nonstop_mode_}{\&{nonstopmode} primitive@>
21887 mp_primitive(mp, "scrollmode",mode_command,mp_scroll_mode);
21888 @:mp_scroll_mode_}{\&{scrollmode} primitive@>
21889 mp_primitive(mp, "errorstopmode",mode_command,mp_error_stop_mode);
21890 @:mp_error_stop_mode_}{\&{errorstopmode} primitive@>
21891
21892 @ @<Cases of |print_cmd_mod|...@>=
21893 case mode_command: 
21894   switch (m) {
21895   case mp_batch_mode: mp_print(mp, "batchmode"); break;
21896   case mp_nonstop_mode: mp_print(mp, "nonstopmode"); break;
21897   case mp_scroll_mode: mp_print(mp, "scrollmode"); break;
21898   default: mp_print(mp, "errorstopmode"); break;
21899   }
21900   break;
21901
21902 @ The `\&{inner}' and `\&{outer}' commands are only slightly harder.
21903
21904 @<Cases of |do_statement|...@>=
21905 case protection_command: mp_do_protection(mp); break;
21906
21907 @ @<Put each...@>=
21908 mp_primitive(mp, "inner",protection_command,0);
21909 @:inner_}{\&{inner} primitive@>
21910 mp_primitive(mp, "outer",protection_command,1);
21911 @:outer_}{\&{outer} primitive@>
21912
21913 @ @<Cases of |print_cmd...@>=
21914 case protection_command: 
21915   if ( m==0 ) mp_print(mp, "inner");
21916   else mp_print(mp, "outer");
21917   break;
21918
21919 @ @<Declare action procedures for use by |do_statement|@>=
21920 void mp_do_protection (MP mp) ;
21921
21922 @ @c void mp_do_protection (MP mp) {
21923   int m; /* 0 to unprotect, 1 to protect */
21924   halfword t; /* the |eq_type| before we change it */
21925   m=mp->cur_mod;
21926   do {  
21927     mp_get_symbol(mp); t=eq_type(mp->cur_sym);
21928     if ( m==0 ) { 
21929       if ( t>=outer_tag ) 
21930         eq_type(mp->cur_sym)=t-outer_tag;
21931     } else if ( t<outer_tag ) {
21932       eq_type(mp->cur_sym)=t+outer_tag;
21933     }
21934     mp_get_x_next(mp);
21935   } while (mp->cur_cmd==comma);
21936 }
21937
21938 @ \MP\ never defines the tokens `\.(' and `\.)' to be primitives, but
21939 plain \MP\ begins with the declaration `\&{delimiters} \.{()}'. Such a
21940 declaration assigns the command code |left_delimiter| to `\.{(}' and
21941 |right_delimiter| to `\.{)}'; the |equiv| of each delimiter is the
21942 hash address of its mate.
21943
21944 @<Cases of |do_statement|...@>=
21945 case delimiters: mp_def_delims(mp); break;
21946
21947 @ @<Declare action procedures for use by |do_statement|@>=
21948 void mp_def_delims (MP mp) ;
21949
21950 @ @c void mp_def_delims (MP mp) {
21951   pointer l_delim,r_delim; /* the new delimiter pair */
21952   mp_get_clear_symbol(mp); l_delim=mp->cur_sym;
21953   mp_get_clear_symbol(mp); r_delim=mp->cur_sym;
21954   eq_type(l_delim)=left_delimiter; equiv(l_delim)=r_delim;
21955   eq_type(r_delim)=right_delimiter; equiv(r_delim)=l_delim;
21956   mp_get_x_next(mp);
21957 }
21958
21959 @ Here is a procedure that is called when \MP\ has reached a point
21960 where some right delimiter is mandatory.
21961
21962 @<Declare the procedure called |check_delimiter|@>=
21963 void mp_check_delimiter (MP mp,pointer l_delim, pointer r_delim) {
21964   if ( mp->cur_cmd==right_delimiter ) 
21965     if ( mp->cur_mod==l_delim ) 
21966       return;
21967   if ( mp->cur_sym!=r_delim ) {
21968      mp_missing_err(mp, str(text(r_delim)));
21969 @.Missing `)'@>
21970     help2("I found no right delimiter to match a left one. So I've")
21971       ("put one in, behind the scenes; this may fix the problem.");
21972     mp_back_error(mp);
21973   } else { 
21974     print_err("The token `"); mp_print_text(r_delim);
21975 @.The token...delimiter@>
21976     mp_print(mp, "' is no longer a right delimiter");
21977     help3("Strange: This token has lost its former meaning!")
21978       ("I'll read it as a right delimiter this time;")
21979       ("but watch out, I'll probably miss it later.");
21980     mp_error(mp);
21981   }
21982 }
21983
21984 @ The next four commands save or change the values associated with tokens.
21985
21986 @<Cases of |do_statement|...@>=
21987 case save_command: 
21988   do {  
21989     mp_get_symbol(mp); mp_save_variable(mp, mp->cur_sym); mp_get_x_next(mp);
21990   } while (mp->cur_cmd==comma);
21991   break;
21992 case interim_command: mp_do_interim(mp); break;
21993 case let_command: mp_do_let(mp); break;
21994 case new_internal: mp_do_new_internal(mp); break;
21995
21996 @ @<Declare action procedures for use by |do_statement|@>=
21997 void mp_do_statement (MP mp);
21998 void mp_do_interim (MP mp);
21999
22000 @ @c void mp_do_interim (MP mp) { 
22001   mp_get_x_next(mp);
22002   if ( mp->cur_cmd!=internal_quantity ) {
22003      print_err("The token `");
22004 @.The token...quantity@>
22005     if ( mp->cur_sym==0 ) mp_print(mp, "(%CAPSULE)");
22006     else mp_print_text(mp->cur_sym);
22007     mp_print(mp, "' isn't an internal quantity");
22008     help1("Something like `tracingonline' should follow `interim'.");
22009     mp_back_error(mp);
22010   } else { 
22011     mp_save_internal(mp, mp->cur_mod); mp_back_input(mp);
22012   }
22013   mp_do_statement(mp);
22014 }
22015
22016 @ The following procedure is careful not to undefine the left-hand symbol
22017 too soon, lest commands like `{\tt let x=x}' have a surprising effect.
22018
22019 @<Declare action procedures for use by |do_statement|@>=
22020 void mp_do_let (MP mp) ;
22021
22022 @ @c void mp_do_let (MP mp) {
22023   pointer l; /* hash location of the left-hand symbol */
22024   mp_get_symbol(mp); l=mp->cur_sym; mp_get_x_next(mp);
22025   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
22026      mp_missing_err(mp, "=");
22027 @.Missing `='@>
22028     help3("You should have said `let symbol = something'.")
22029       ("But don't worry; I'll pretend that an equals sign")
22030       ("was present. The next token I read will be `something'.");
22031     mp_back_error(mp);
22032   }
22033   mp_get_symbol(mp);
22034   switch (mp->cur_cmd) {
22035   case defined_macro: case secondary_primary_macro:
22036   case tertiary_secondary_macro: case expression_tertiary_macro: 
22037     add_mac_ref(mp->cur_mod);
22038     break;
22039   default: 
22040     break;
22041   }
22042   mp_clear_symbol(mp, l,false); eq_type(l)=mp->cur_cmd;
22043   if ( mp->cur_cmd==tag_token ) equiv(l)=null;
22044   else equiv(l)=mp->cur_mod;
22045   mp_get_x_next(mp);
22046 }
22047
22048 @ @<Declarations@>=
22049 void mp_grow_internals (MP mp, int l);
22050 void mp_do_new_internal (MP mp) ;
22051
22052 @ @c
22053 void mp_grow_internals (MP mp, int l) {
22054   scaled *internal;
22055   char * *int_name; 
22056   int k;
22057   if ( hash_end+l>max_halfword ) {
22058     mp_confusion(mp, "out of memory space"); /* can't be reached */
22059   }
22060   int_name = xmalloc ((l+1),sizeof(char *));
22061   internal = xmalloc ((l+1),sizeof(scaled));
22062   for (k=0;k<=l; k++ ) { 
22063     if (k<=mp->max_internal) {
22064       internal[k]=mp->internal[k]; 
22065       int_name[k]=mp->int_name[k]; 
22066     } else {
22067       internal[k]=0; 
22068       int_name[k]=NULL; 
22069     }
22070   }
22071   xfree(mp->internal); xfree(mp->int_name);
22072   mp->int_name = int_name;
22073   mp->internal = internal;
22074   mp->max_internal = l;
22075 }
22076
22077
22078 void mp_do_new_internal (MP mp) { 
22079   do {  
22080     if ( mp->int_ptr==mp->max_internal ) {
22081       mp_grow_internals(mp, (mp->max_internal + (mp->max_internal>>2)));
22082     }
22083     mp_get_clear_symbol(mp); incr(mp->int_ptr);
22084     eq_type(mp->cur_sym)=internal_quantity; 
22085     equiv(mp->cur_sym)=mp->int_ptr;
22086     if(mp->int_name[mp->int_ptr]!=NULL)
22087       xfree(mp->int_name[mp->int_ptr]);
22088     mp->int_name[mp->int_ptr]=str(text(mp->cur_sym)); 
22089     mp->internal[mp->int_ptr]=0;
22090     mp_get_x_next(mp);
22091   } while (mp->cur_cmd==comma);
22092 }
22093
22094 @ @<Dealloc variables@>=
22095 for (k=0;k<=mp->max_internal;k++) {
22096    xfree(mp->int_name[k]);
22097 }
22098 xfree(mp->internal); 
22099 xfree(mp->int_name); 
22100
22101
22102 @ The various `\&{show}' commands are distinguished by modifier fields
22103 in the usual way.
22104
22105 @d show_token_code 0 /* show the meaning of a single token */
22106 @d show_stats_code 1 /* show current memory and string usage */
22107 @d show_code 2 /* show a list of expressions */
22108 @d show_var_code 3 /* show a variable and its descendents */
22109 @d show_dependencies_code 4 /* show dependent variables in terms of independents */
22110
22111 @<Put each...@>=
22112 mp_primitive(mp, "showtoken",show_command,show_token_code);
22113 @:show_token_}{\&{showtoken} primitive@>
22114 mp_primitive(mp, "showstats",show_command,show_stats_code);
22115 @:show_stats_}{\&{showstats} primitive@>
22116 mp_primitive(mp, "show",show_command,show_code);
22117 @:show_}{\&{show} primitive@>
22118 mp_primitive(mp, "showvariable",show_command,show_var_code);
22119 @:show_var_}{\&{showvariable} primitive@>
22120 mp_primitive(mp, "showdependencies",show_command,show_dependencies_code);
22121 @:show_dependencies_}{\&{showdependencies} primitive@>
22122
22123 @ @<Cases of |print_cmd...@>=
22124 case show_command: 
22125   switch (m) {
22126   case show_token_code:mp_print(mp, "showtoken"); break;
22127   case show_stats_code:mp_print(mp, "showstats"); break;
22128   case show_code:mp_print(mp, "show"); break;
22129   case show_var_code:mp_print(mp, "showvariable"); break;
22130   default: mp_print(mp, "showdependencies"); break;
22131   }
22132   break;
22133
22134 @ @<Cases of |do_statement|...@>=
22135 case show_command:mp_do_show_whatever(mp); break;
22136
22137 @ The value of |cur_mod| controls the |verbosity| in the |print_exp| routine:
22138 if it's |show_code|, complicated structures are abbreviated, otherwise
22139 they aren't.
22140
22141 @<Declare action procedures for use by |do_statement|@>=
22142 void mp_do_show (MP mp) ;
22143
22144 @ @c void mp_do_show (MP mp) { 
22145   do {  
22146     mp_get_x_next(mp); mp_scan_expression(mp);
22147     mp_print_nl(mp, ">> ");
22148 @.>>@>
22149     mp_print_exp(mp, null,2); mp_flush_cur_exp(mp, 0);
22150   } while (mp->cur_cmd==comma);
22151 }
22152
22153 @ @<Declare action procedures for use by |do_statement|@>=
22154 void mp_disp_token (MP mp) ;
22155
22156 @ @c void mp_disp_token (MP mp) { 
22157   mp_print_nl(mp, "> ");
22158 @.>\relax@>
22159   if ( mp->cur_sym==0 ) {
22160     @<Show a numeric or string or capsule token@>;
22161   } else { 
22162     mp_print_text(mp->cur_sym); mp_print_char(mp, '=');
22163     if ( eq_type(mp->cur_sym)>=outer_tag ) mp_print(mp, "(outer) ");
22164     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod);
22165     if ( mp->cur_cmd==defined_macro ) {
22166       mp_print_ln(mp); mp_show_macro(mp, mp->cur_mod,null,100000);
22167     } /* this avoids recursion between |show_macro| and |print_cmd_mod| */
22168 @^recursion@>
22169   }
22170 }
22171
22172 @ @<Show a numeric or string or capsule token@>=
22173
22174   if ( mp->cur_cmd==numeric_token ) {
22175     mp_print_scaled(mp, mp->cur_mod);
22176   } else if ( mp->cur_cmd==capsule_token ) {
22177     mp_print_capsule(mp,mp->cur_mod);
22178   } else  { 
22179     mp_print_char(mp, '"'); 
22180     mp_print_str(mp, mp->cur_mod); mp_print_char(mp, '"');
22181     delete_str_ref(mp->cur_mod);
22182   }
22183 }
22184
22185 @ The following cases of |print_cmd_mod| might arise in connection
22186 with |disp_token|, although they don't correspond to any
22187 primitive tokens.
22188
22189 @<Cases of |print_cmd_...@>=
22190 case left_delimiter:
22191 case right_delimiter: 
22192   if ( c==left_delimiter ) mp_print(mp, "left");
22193   else mp_print(mp, "right");
22194   mp_print(mp, " delimiter that matches "); 
22195   mp_print_text(m);
22196   break;
22197 case tag_token:
22198   if ( m==null ) mp_print(mp, "tag");
22199    else mp_print(mp, "variable");
22200    break;
22201 case defined_macro: 
22202    mp_print(mp, "macro:");
22203    break;
22204 case secondary_primary_macro:
22205 case tertiary_secondary_macro:
22206 case expression_tertiary_macro:
22207   mp_print_cmd_mod(mp, macro_def,c); 
22208   mp_print(mp, "'d macro:");
22209   mp_print_ln(mp); mp_show_token_list(mp, link(link(m)),null,1000,0);
22210   break;
22211 case repeat_loop:
22212   mp_print(mp, "[repeat the loop]");
22213   break;
22214 case internal_quantity:
22215   mp_print(mp, mp->int_name[m]);
22216   break;
22217
22218 @ @<Declare action procedures for use by |do_statement|@>=
22219 void mp_do_show_token (MP mp) ;
22220
22221 @ @c void mp_do_show_token (MP mp) { 
22222   do {  
22223     get_t_next; mp_disp_token(mp);
22224     mp_get_x_next(mp);
22225   } while (mp->cur_cmd==comma);
22226 }
22227
22228 @ @<Declare action procedures for use by |do_statement|@>=
22229 void mp_do_show_stats (MP mp) ;
22230
22231 @ @c void mp_do_show_stats (MP mp) { 
22232   mp_print_nl(mp, "Memory usage ");
22233 @.Memory usage...@>
22234   mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used);
22235   if ( false )
22236     mp_print(mp, "unknown");
22237   mp_print(mp, " ("); mp_print_int(mp, mp->hi_mem_min-mp->lo_mem_max-1);
22238   mp_print(mp, " still untouched)"); mp_print_ln(mp);
22239   mp_print_nl(mp, "String usage ");
22240   mp_print_int(mp, mp->strs_in_use-mp->init_str_use);
22241   mp_print_char(mp, '&'); mp_print_int(mp, mp->pool_in_use-mp->init_pool_ptr);
22242   if ( false )
22243     mp_print(mp, "unknown");
22244   mp_print(mp, " (");
22245   mp_print_int(mp, mp->max_strings-1-mp->strs_used_up); mp_print_char(mp, '&');
22246   mp_print_int(mp, mp->pool_size-mp->pool_ptr); 
22247   mp_print(mp, " now untouched)"); mp_print_ln(mp);
22248   mp_get_x_next(mp);
22249 }
22250
22251 @ Here's a recursive procedure that gives an abbreviated account
22252 of a variable, for use by |do_show_var|.
22253
22254 @<Declare action procedures for use by |do_statement|@>=
22255 void mp_disp_var (MP mp,pointer p) ;
22256
22257 @ @c void mp_disp_var (MP mp,pointer p) {
22258   pointer q; /* traverses attributes and subscripts */
22259   int n; /* amount of macro text to show */
22260   if ( type(p)==mp_structured )  {
22261     @<Descend the structure@>;
22262   } else if ( type(p)>=mp_unsuffixed_macro ) {
22263     @<Display a variable macro@>;
22264   } else if ( type(p)!=undefined ){ 
22265     mp_print_nl(mp, ""); mp_print_variable_name(mp, p); 
22266     mp_print_char(mp, '=');
22267     mp_print_exp(mp, p,0);
22268   }
22269 }
22270
22271 @ @<Descend the structure@>=
22272
22273   q=attr_head(p);
22274   do {  mp_disp_var(mp, q); q=link(q); } while (q!=end_attr);
22275   q=subscr_head(p);
22276   while ( name_type(q)==mp_subscr ) { 
22277     mp_disp_var(mp, q); q=link(q);
22278   }
22279 }
22280
22281 @ @<Display a variable macro@>=
22282
22283   mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22284   if ( type(p)>mp_unsuffixed_macro ) 
22285     mp_print(mp, "@@#"); /* |suffixed_macro| */
22286   mp_print(mp, "=macro:");
22287   if ( (int)mp->file_offset>=mp->max_print_line-20 ) n=5;
22288   else n=mp->max_print_line-mp->file_offset-15;
22289   mp_show_macro(mp, value(p),null,n);
22290 }
22291
22292 @ @<Declare action procedures for use by |do_statement|@>=
22293 void mp_do_show_var (MP mp) ;
22294
22295 @ @c void mp_do_show_var (MP mp) { 
22296   do {  
22297     get_t_next;
22298     if ( mp->cur_sym>0 ) if ( mp->cur_sym<=hash_end )
22299       if ( mp->cur_cmd==tag_token ) if ( mp->cur_mod!=null ) {
22300       mp_disp_var(mp, mp->cur_mod); goto DONE;
22301     }
22302    mp_disp_token(mp);
22303   DONE:
22304    mp_get_x_next(mp);
22305   } while (mp->cur_cmd==comma);
22306 }
22307
22308 @ @<Declare action procedures for use by |do_statement|@>=
22309 void mp_do_show_dependencies (MP mp) ;
22310
22311 @ @c void mp_do_show_dependencies (MP mp) {
22312   pointer p; /* link that runs through all dependencies */
22313   p=link(dep_head);
22314   while ( p!=dep_head ) {
22315     if ( mp_interesting(mp, p) ) {
22316       mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22317       if ( type(p)==mp_dependent ) mp_print_char(mp, '=');
22318       else mp_print(mp, " = "); /* extra spaces imply proto-dependency */
22319       mp_print_dependency(mp, dep_list(p),type(p));
22320     }
22321     p=dep_list(p);
22322     while ( info(p)!=null ) p=link(p);
22323     p=link(p);
22324   }
22325   mp_get_x_next(mp);
22326 }
22327
22328 @ Finally we are ready for the procedure that governs all of the
22329 show commands.
22330
22331 @<Declare action procedures for use by |do_statement|@>=
22332 void mp_do_show_whatever (MP mp) ;
22333
22334 @ @c void mp_do_show_whatever (MP mp) { 
22335   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
22336   switch (mp->cur_mod) {
22337   case show_token_code:mp_do_show_token(mp); break;
22338   case show_stats_code:mp_do_show_stats(mp); break;
22339   case show_code:mp_do_show(mp); break;
22340   case show_var_code:mp_do_show_var(mp); break;
22341   case show_dependencies_code:mp_do_show_dependencies(mp); break;
22342   } /* there are no other cases */
22343   if ( mp->internal[mp_showstopping]>0 ){ 
22344     print_err("OK");
22345 @.OK@>
22346     if ( mp->interaction<mp_error_stop_mode ) { 
22347       help0; decr(mp->error_count);
22348     } else {
22349       help1("This isn't an error message; I'm just showing something.");
22350     }
22351     if ( mp->cur_cmd==semicolon ) mp_error(mp);
22352      else mp_put_get_error(mp);
22353   }
22354 }
22355
22356 @ The `\&{addto}' command needs the following additional primitives:
22357
22358 @d double_path_code 0 /* command modifier for `\&{doublepath}' */
22359 @d contour_code 1 /* command modifier for `\&{contour}' */
22360 @d also_code 2 /* command modifier for `\&{also}' */
22361
22362 @ Pre and postscripts need two new identifiers:
22363
22364 @d with_pre_script 11
22365 @d with_post_script 13
22366
22367 @<Put each...@>=
22368 mp_primitive(mp, "doublepath",thing_to_add,double_path_code);
22369 @:double_path_}{\&{doublepath} primitive@>
22370 mp_primitive(mp, "contour",thing_to_add,contour_code);
22371 @:contour_}{\&{contour} primitive@>
22372 mp_primitive(mp, "also",thing_to_add,also_code);
22373 @:also_}{\&{also} primitive@>
22374 mp_primitive(mp, "withpen",with_option,mp_pen_type);
22375 @:with_pen_}{\&{withpen} primitive@>
22376 mp_primitive(mp, "dashed",with_option,mp_picture_type);
22377 @:dashed_}{\&{dashed} primitive@>
22378 mp_primitive(mp, "withprescript",with_option,with_pre_script);
22379 @:with_pre_script_}{\&{withprescript} primitive@>
22380 mp_primitive(mp, "withpostscript",with_option,with_post_script);
22381 @:with_post_script_}{\&{withpostscript} primitive@>
22382 mp_primitive(mp, "withoutcolor",with_option,mp_no_model);
22383 @:with_color_}{\&{withoutcolor} primitive@>
22384 mp_primitive(mp, "withgreyscale",with_option,mp_grey_model);
22385 @:with_color_}{\&{withgreyscale} primitive@>
22386 mp_primitive(mp, "withcolor",with_option,mp_uninitialized_model);
22387 @:with_color_}{\&{withcolor} primitive@>
22388 /*  \&{withrgbcolor} is an alias for \&{withcolor} */
22389 mp_primitive(mp, "withrgbcolor",with_option,mp_rgb_model);
22390 @:with_color_}{\&{withrgbcolor} primitive@>
22391 mp_primitive(mp, "withcmykcolor",with_option,mp_cmyk_model);
22392 @:with_color_}{\&{withcmykcolor} primitive@>
22393
22394 @ @<Cases of |print_cmd...@>=
22395 case thing_to_add:
22396   if ( m==contour_code ) mp_print(mp, "contour");
22397   else if ( m==double_path_code ) mp_print(mp, "doublepath");
22398   else mp_print(mp, "also");
22399   break;
22400 case with_option:
22401   if ( m==mp_pen_type ) mp_print(mp, "withpen");
22402   else if ( m==with_pre_script ) mp_print(mp, "withprescript");
22403   else if ( m==with_post_script ) mp_print(mp, "withpostscript");
22404   else if ( m==mp_no_model ) mp_print(mp, "withoutcolor");
22405   else if ( m==mp_rgb_model ) mp_print(mp, "withrgbcolor");
22406   else if ( m==mp_uninitialized_model ) mp_print(mp, "withcolor");
22407   else if ( m==mp_cmyk_model ) mp_print(mp, "withcmykcolor");
22408   else if ( m==mp_grey_model ) mp_print(mp, "withgreyscale");
22409   else mp_print(mp, "dashed");
22410   break;
22411
22412 @ The |scan_with_list| procedure parses a $\langle$with list$\rangle$ and
22413 updates the list of graphical objects starting at |p|.  Each $\langle$with
22414 clause$\rangle$ updates all graphical objects whose |type| is compatible.
22415 Other objects are ignored.
22416
22417 @<Declare action procedures for use by |do_statement|@>=
22418 void mp_scan_with_list (MP mp,pointer p) ;
22419
22420 @ @c void mp_scan_with_list (MP mp,pointer p) {
22421   small_number t; /* |cur_mod| of the |with_option| (should match |cur_type|) */
22422   pointer q; /* for list manipulation */
22423   int old_setting; /* saved |selector| setting */
22424   pointer k; /* for finding the near-last item in a list  */
22425   str_number s; /* for string cleanup after combining  */
22426   pointer cp,pp,dp,ap,bp;
22427     /* objects being updated; |void| initially; |null| to suppress update */
22428   cp=mp_void; pp=mp_void; dp=mp_void; ap=mp_void; bp=mp_void;
22429   k=0;
22430   while ( mp->cur_cmd==with_option ){ 
22431     t=mp->cur_mod;
22432     mp_get_x_next(mp);
22433     if ( t!=mp_no_model ) mp_scan_expression(mp);
22434     if (((t==with_pre_script)&&(mp->cur_type!=mp_string_type))||
22435      ((t==with_post_script)&&(mp->cur_type!=mp_string_type))||
22436      ((t==mp_uninitialized_model)&&
22437         ((mp->cur_type!=mp_cmykcolor_type)&&(mp->cur_type!=mp_color_type)
22438           &&(mp->cur_type!=mp_known)&&(mp->cur_type!=mp_boolean_type)))||
22439      ((t==mp_cmyk_model)&&(mp->cur_type!=mp_cmykcolor_type))||
22440      ((t==mp_rgb_model)&&(mp->cur_type!=mp_color_type))||
22441      ((t==mp_grey_model)&&(mp->cur_type!=mp_known))||
22442      ((t==mp_pen_type)&&(mp->cur_type!=t))||
22443      ((t==mp_picture_type)&&(mp->cur_type!=t)) ) {
22444       @<Complain about improper type@>;
22445     } else if ( t==mp_uninitialized_model ) {
22446       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22447       if ( cp!=null )
22448         @<Transfer a color from the current expression to object~|cp|@>;
22449       mp_flush_cur_exp(mp, 0);
22450     } else if ( t==mp_rgb_model ) {
22451       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22452       if ( cp!=null )
22453         @<Transfer a rgbcolor from the current expression to object~|cp|@>;
22454       mp_flush_cur_exp(mp, 0);
22455     } else if ( t==mp_cmyk_model ) {
22456       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22457       if ( cp!=null )
22458         @<Transfer a cmykcolor from the current expression to object~|cp|@>;
22459       mp_flush_cur_exp(mp, 0);
22460     } else if ( t==mp_grey_model ) {
22461       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22462       if ( cp!=null )
22463         @<Transfer a greyscale from the current expression to object~|cp|@>;
22464       mp_flush_cur_exp(mp, 0);
22465     } else if ( t==mp_no_model ) {
22466       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22467       if ( cp!=null )
22468         @<Transfer a noncolor from the current expression to object~|cp|@>;
22469     } else if ( t==mp_pen_type ) {
22470       if ( pp==mp_void ) @<Make |pp| an object in list~|p| that needs a pen@>;
22471       if ( pp!=null ) {
22472         if ( pen_p(pp)!=null ) mp_toss_knot_list(mp, pen_p(pp));
22473         pen_p(pp)=mp->cur_exp; mp->cur_type=mp_vacuous;
22474       }
22475     } else if ( t==with_pre_script ) {
22476       if ( ap==mp_void )
22477         ap=p;
22478       while ( (ap!=null)&&(! has_color(ap)) )
22479          ap=link(ap);
22480       if ( ap!=null ) {
22481         if ( pre_script(ap)!=null ) { /*  build a new,combined string  */
22482           s=pre_script(ap);
22483           old_setting=mp->selector;
22484               mp->selector=new_string;
22485           str_room(length(pre_script(ap))+length(mp->cur_exp)+2);
22486               mp_print_str(mp, mp->cur_exp);
22487           append_char(13);  /* a forced \ps\ newline  */
22488           mp_print_str(mp, pre_script(ap));
22489           pre_script(ap)=mp_make_string(mp);
22490           delete_str_ref(s);
22491           mp->selector=old_setting;
22492         } else {
22493           pre_script(ap)=mp->cur_exp;
22494         }
22495         mp->cur_type=mp_vacuous;
22496       }
22497     } else if ( t==with_post_script ) {
22498       if ( bp==mp_void )
22499         k=p; 
22500       bp=k;
22501       while ( link(k)!=null ) {
22502         k=link(k);
22503         if ( has_color(k) ) bp=k;
22504       }
22505       if ( bp!=null ) {
22506          if ( post_script(bp)!=null ) {
22507            s=post_script(bp);
22508            old_setting=mp->selector;
22509                mp->selector=new_string;
22510            str_room(length(post_script(bp))+length(mp->cur_exp)+2);
22511            mp_print_str(mp, post_script(bp));
22512            append_char(13); /* a forced \ps\ newline  */
22513            mp_print_str(mp, mp->cur_exp);
22514            post_script(bp)=mp_make_string(mp);
22515            delete_str_ref(s);
22516            mp->selector=old_setting;
22517          } else {
22518            post_script(bp)=mp->cur_exp;
22519          }
22520          mp->cur_type=mp_vacuous;
22521        }
22522     } else { 
22523       if ( dp==mp_void ) {
22524         @<Make |dp| a stroked node in list~|p|@>;
22525       }
22526       if ( dp!=null ) {
22527         if ( dash_p(dp)!=null ) delete_edge_ref(dash_p(dp));
22528         dash_p(dp)=mp_make_dashes(mp, mp->cur_exp);
22529         dash_scale(dp)=unity;
22530         mp->cur_type=mp_vacuous;
22531       }
22532     }
22533   }
22534   @<Copy the information from objects |cp|, |pp|, and |dp| into the rest
22535     of the list@>;
22536 };
22537
22538 @ @<Complain about improper type@>=
22539 { exp_err("Improper type");
22540 @.Improper type@>
22541 help2("Next time say `withpen <known pen expression>';")
22542   ("I'll ignore the bad `with' clause and look for another.");
22543 if ( t==with_pre_script )
22544   mp->help_line[1]="Next time say `withprescript <known string expression>';";
22545 else if ( t==with_post_script )
22546   mp->help_line[1]="Next time say `withpostscript <known string expression>';";
22547 else if ( t==mp_picture_type )
22548   mp->help_line[1]="Next time say `dashed <known picture expression>';";
22549 else if ( t==mp_uninitialized_model )
22550   mp->help_line[1]="Next time say `withcolor <known color expression>';";
22551 else if ( t==mp_rgb_model )
22552   mp->help_line[1]="Next time say `withrgbcolor <known color expression>';";
22553 else if ( t==mp_cmyk_model )
22554   mp->help_line[1]="Next time say `withcmykcolor <known cmykcolor expression>';";
22555 else if ( t==mp_grey_model )
22556   mp->help_line[1]="Next time say `withgreyscale <known numeric expression>';";;
22557 mp_put_get_flush_error(mp, 0);
22558 }
22559
22560 @ Forcing the color to be between |0| and |unity| here guarantees that no
22561 picture will ever contain a color outside the legal range for \ps\ graphics.
22562
22563 @<Transfer a color from the current expression to object~|cp|@>=
22564 { if ( mp->cur_type==mp_color_type )
22565    @<Transfer a rgbcolor from the current expression to object~|cp|@>
22566 else if ( mp->cur_type==mp_cmykcolor_type )
22567    @<Transfer a cmykcolor from the current expression to object~|cp|@>
22568 else if ( mp->cur_type==mp_known )
22569    @<Transfer a greyscale from the current expression to object~|cp|@>
22570 else if ( mp->cur_exp==false_code )
22571    @<Transfer a noncolor from the current expression to object~|cp|@>;
22572 }
22573
22574 @ @<Transfer a rgbcolor from the current expression to object~|cp|@>=
22575 { q=value(mp->cur_exp);
22576 cyan_val(cp)=0;
22577 magenta_val(cp)=0;
22578 yellow_val(cp)=0;
22579 black_val(cp)=0;
22580 red_val(cp)=value(red_part_loc(q));
22581 green_val(cp)=value(green_part_loc(q));
22582 blue_val(cp)=value(blue_part_loc(q));
22583 color_model(cp)=mp_rgb_model;
22584 if ( red_val(cp)<0 ) red_val(cp)=0;
22585 if ( green_val(cp)<0 ) green_val(cp)=0;
22586 if ( blue_val(cp)<0 ) blue_val(cp)=0;
22587 if ( red_val(cp)>unity ) red_val(cp)=unity;
22588 if ( green_val(cp)>unity ) green_val(cp)=unity;
22589 if ( blue_val(cp)>unity ) blue_val(cp)=unity;
22590 }
22591
22592 @ @<Transfer a cmykcolor from the current expression to object~|cp|@>=
22593 { q=value(mp->cur_exp);
22594 cyan_val(cp)=value(cyan_part_loc(q));
22595 magenta_val(cp)=value(magenta_part_loc(q));
22596 yellow_val(cp)=value(yellow_part_loc(q));
22597 black_val(cp)=value(black_part_loc(q));
22598 color_model(cp)=mp_cmyk_model;
22599 if ( cyan_val(cp)<0 ) cyan_val(cp)=0;
22600 if ( magenta_val(cp)<0 ) magenta_val(cp)=0;
22601 if ( yellow_val(cp)<0 ) yellow_val(cp)=0;
22602 if ( black_val(cp)<0 ) black_val(cp)=0;
22603 if ( cyan_val(cp)>unity ) cyan_val(cp)=unity;
22604 if ( magenta_val(cp)>unity ) magenta_val(cp)=unity;
22605 if ( yellow_val(cp)>unity ) yellow_val(cp)=unity;
22606 if ( black_val(cp)>unity ) black_val(cp)=unity;
22607 }
22608
22609 @ @<Transfer a greyscale from the current expression to object~|cp|@>=
22610 { q=mp->cur_exp;
22611 cyan_val(cp)=0;
22612 magenta_val(cp)=0;
22613 yellow_val(cp)=0;
22614 black_val(cp)=0;
22615 grey_val(cp)=q;
22616 color_model(cp)=mp_grey_model;
22617 if ( grey_val(cp)<0 ) grey_val(cp)=0;
22618 if ( grey_val(cp)>unity ) grey_val(cp)=unity;
22619 }
22620
22621 @ @<Transfer a noncolor from the current expression to object~|cp|@>=
22622 {
22623 cyan_val(cp)=0;
22624 magenta_val(cp)=0;
22625 yellow_val(cp)=0;
22626 black_val(cp)=0;
22627 grey_val(cp)=0;
22628 color_model(cp)=mp_no_model;
22629 }
22630
22631 @ @<Make |cp| a colored object in object list~|p|@>=
22632 { cp=p;
22633   while ( cp!=null ){ 
22634     if ( has_color(cp) ) break;
22635     cp=link(cp);
22636   }
22637 }
22638
22639 @ @<Make |pp| an object in list~|p| that needs a pen@>=
22640 { pp=p;
22641   while ( pp!=null ) {
22642     if ( has_pen(pp) ) break;
22643     pp=link(pp);
22644   }
22645 }
22646
22647 @ @<Make |dp| a stroked node in list~|p|@>=
22648 { dp=p;
22649   while ( dp!=null ) {
22650     if ( type(dp)==mp_stroked_code ) break;
22651     dp=link(dp);
22652   }
22653 }
22654
22655 @ @<Copy the information from objects |cp|, |pp|, and |dp| into...@>=
22656 @<Copy |cp|'s color into the colored objects linked to~|cp|@>;
22657 if ( pp>mp_void ) {
22658   @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>;
22659 }
22660 if ( dp>mp_void ) {
22661   @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>;
22662 }
22663
22664
22665 @ @<Copy |cp|'s color into the colored objects linked to~|cp|@>=
22666 { q=link(cp);
22667   while ( q!=null ) { 
22668     if ( has_color(q) ) {
22669       red_val(q)=red_val(cp);
22670       green_val(q)=green_val(cp);
22671       blue_val(q)=blue_val(cp);
22672       black_val(q)=black_val(cp);
22673       color_model(q)=color_model(cp);
22674     }
22675     q=link(q);
22676   }
22677 }
22678
22679 @ @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>=
22680 { q=link(pp);
22681   while ( q!=null ) {
22682     if ( has_pen(q) ) {
22683       if ( pen_p(q)!=null ) mp_toss_knot_list(mp, pen_p(q));
22684       pen_p(q)=copy_pen(pen_p(pp));
22685     }
22686     q=link(q);
22687   }
22688 }
22689
22690 @ @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>=
22691 { q=link(dp);
22692   while ( q!=null ) {
22693     if ( type(q)==mp_stroked_code ) {
22694       if ( dash_p(q)!=null ) delete_edge_ref(dash_p(q));
22695       dash_p(q)=dash_p(dp);
22696       dash_scale(q)=unity;
22697       if ( dash_p(q)!=null ) add_edge_ref(dash_p(q));
22698     }
22699     q=link(q);
22700   }
22701 }
22702
22703 @ One of the things we need to do when we've parsed an \&{addto} or
22704 similar command is find the header of a supposed \&{picture} variable, given
22705 a token list for that variable.  Since the edge structure is about to be
22706 updated, we use |private_edges| to make sure that this is possible.
22707
22708 @<Declare action procedures for use by |do_statement|@>=
22709 pointer mp_find_edges_var (MP mp, pointer t) ;
22710
22711 @ @c pointer mp_find_edges_var (MP mp, pointer t) {
22712   pointer p;
22713   pointer cur_edges; /* the return value */
22714   p=mp_find_variable(mp, t); cur_edges=null;
22715   if ( p==null ) { 
22716     mp_obliterated(mp, t); mp_put_get_error(mp);
22717   } else if ( type(p)!=mp_picture_type )  { 
22718     print_err("Variable "); mp_show_token_list(mp, t,null,1000,0);
22719 @.Variable x is the wrong type@>
22720     mp_print(mp, " is the wrong type ("); 
22721     mp_print_type(mp, type(p)); mp_print_char(mp, ')');
22722     help2("I was looking for a \"known\" picture variable.")
22723          ("So I'll not change anything just now."); 
22724     mp_put_get_error(mp);
22725   } else { 
22726     value(p)=mp_private_edges(mp, value(p));
22727     cur_edges=value(p);
22728   }
22729   mp_flush_node_list(mp, t);
22730   return cur_edges;
22731 };
22732
22733 @ @<Cases of |do_statement|...@>=
22734 case add_to_command: mp_do_add_to(mp); break;
22735 case bounds_command:mp_do_bounds(mp); break;
22736
22737 @ @<Put each...@>=
22738 mp_primitive(mp, "clip",bounds_command,mp_start_clip_code);
22739 @:clip_}{\&{clip} primitive@>
22740 mp_primitive(mp, "setbounds",bounds_command,mp_start_bounds_code);
22741 @:set_bounds_}{\&{setbounds} primitive@>
22742
22743 @ @<Cases of |print_cmd...@>=
22744 case bounds_command: 
22745   if ( m==mp_start_clip_code ) mp_print(mp, "clip");
22746   else mp_print(mp, "setbounds");
22747   break;
22748
22749 @ The following function parses the beginning of an \&{addto} or \&{clip}
22750 command: it expects a variable name followed by a token with |cur_cmd=sep|
22751 and then an expression.  The function returns the token list for the variable
22752 and stores the command modifier for the separator token in the global variable
22753 |last_add_type|.  We must be careful because this variable might get overwritten
22754 any time we call |get_x_next|.
22755
22756 @<Glob...@>=
22757 quarterword last_add_type;
22758   /* command modifier that identifies the last \&{addto} command */
22759
22760 @ @<Declare action procedures for use by |do_statement|@>=
22761 pointer mp_start_draw_cmd (MP mp,quarterword sep) ;
22762
22763 @ @c pointer mp_start_draw_cmd (MP mp,quarterword sep) {
22764   pointer lhv; /* variable to add to left */
22765   quarterword add_type=0; /* value to be returned in |last_add_type| */
22766   lhv=null;
22767   mp_get_x_next(mp); mp->var_flag=sep; mp_scan_primary(mp);
22768   if ( mp->cur_type!=mp_token_list ) {
22769     @<Abandon edges command because there's no variable@>;
22770   } else  { 
22771     lhv=mp->cur_exp; add_type=mp->cur_mod;
22772     mp->cur_type=mp_vacuous; mp_get_x_next(mp); mp_scan_expression(mp);
22773   }
22774   mp->last_add_type=add_type;
22775   return lhv;
22776 }
22777
22778 @ @<Abandon edges command because there's no variable@>=
22779 { exp_err("Not a suitable variable");
22780 @.Not a suitable variable@>
22781   help4("At this point I needed to see the name of a picture variable.")
22782     ("(Or perhaps you have indeed presented me with one; I might")
22783     ("have missed it, if it wasn't followed by the proper token.)")
22784     ("So I'll not change anything just now.");
22785   mp_put_get_flush_error(mp, 0);
22786 }
22787
22788 @ Here is an example of how to use |start_draw_cmd|.
22789
22790 @<Declare action procedures for use by |do_statement|@>=
22791 void mp_do_bounds (MP mp) ;
22792
22793 @ @c void mp_do_bounds (MP mp) {
22794   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22795   pointer p; /* for list manipulation */
22796   integer m; /* initial value of |cur_mod| */
22797   m=mp->cur_mod;
22798   lhv=mp_start_draw_cmd(mp, to_token);
22799   if ( lhv!=null ) {
22800     lhe=mp_find_edges_var(mp, lhv);
22801     if ( lhe==null ) {
22802       mp_flush_cur_exp(mp, 0);
22803     } else if ( mp->cur_type!=mp_path_type ) {
22804       exp_err("Improper `clip'");
22805 @.Improper `addto'@>
22806       help2("This expression should have specified a known path.")
22807         ("So I'll not change anything just now."); 
22808       mp_put_get_flush_error(mp, 0);
22809     } else if ( left_type(mp->cur_exp)==mp_endpoint ) {
22810       @<Complain about a non-cycle@>;
22811     } else {
22812       @<Make |cur_exp| into a \&{setbounds} or clipping path and add it to |lhe|@>;
22813     }
22814   }
22815 }
22816
22817 @ @<Complain about a non-cycle@>=
22818 { print_err("Not a cycle");
22819 @.Not a cycle@>
22820   help2("That contour should have ended with `..cycle' or `&cycle'.")
22821     ("So I'll not change anything just now."); mp_put_get_error(mp);
22822 }
22823
22824 @ @<Make |cur_exp| into a \&{setbounds} or clipping path and add...@>=
22825 { p=mp_new_bounds_node(mp, mp->cur_exp,m);
22826   link(p)=link(dummy_loc(lhe));
22827   link(dummy_loc(lhe))=p;
22828   if ( obj_tail(lhe)==dummy_loc(lhe) ) obj_tail(lhe)=p;
22829   p=mp_get_node(mp, mp->gr_object_size[stop_type(m)]);
22830   type(p)=stop_type(m);
22831   link(obj_tail(lhe))=p;
22832   obj_tail(lhe)=p;
22833   mp_init_bbox(mp, lhe);
22834 }
22835
22836 @ The |do_add_to| procedure is a little like |do_clip| but there are a lot more
22837 cases to deal with.
22838
22839 @<Declare action procedures for use by |do_statement|@>=
22840 void mp_do_add_to (MP mp) ;
22841
22842 @ @c void mp_do_add_to (MP mp) {
22843   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22844   pointer p; /* the graphical object or list for |scan_with_list| to update */
22845   pointer e; /* an edge structure to be merged */
22846   quarterword add_type; /* |also_code|, |contour_code|, or |double_path_code| */
22847   lhv=mp_start_draw_cmd(mp, thing_to_add); add_type=mp->last_add_type;
22848   if ( lhv!=null ) {
22849     if ( add_type==also_code ) {
22850       @<Make sure the current expression is a suitable picture and set |e| and |p|
22851        appropriately@>;
22852     } else {
22853       @<Create a graphical object |p| based on |add_type| and the current
22854         expression@>;
22855     }
22856     mp_scan_with_list(mp, p);
22857     @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>;
22858   }
22859 }
22860
22861 @ Setting |p:=null| causes the $\langle$with list$\rangle$ to be ignored;
22862 setting |e:=null| prevents anything from being added to |lhe|.
22863
22864 @ @<Make sure the current expression is a suitable picture and set |e|...@>=
22865
22866   p=null; e=null;
22867   if ( mp->cur_type!=mp_picture_type ) {
22868     exp_err("Improper `addto'");
22869 @.Improper `addto'@>
22870     help2("This expression should have specified a known picture.")
22871       ("So I'll not change anything just now."); mp_put_get_flush_error(mp, 0);
22872   } else { 
22873     e=mp_private_edges(mp, mp->cur_exp); mp->cur_type=mp_vacuous;
22874     p=link(dummy_loc(e));
22875   }
22876 }
22877
22878 @ In this case |add_type<>also_code| so setting |p:=null| suppresses future
22879 attempts to add to the edge structure.
22880
22881 @<Create a graphical object |p| based on |add_type| and the current...@>=
22882 { e=null; p=null;
22883   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
22884   if ( mp->cur_type!=mp_path_type ) {
22885     exp_err("Improper `addto'");
22886 @.Improper `addto'@>
22887     help2("This expression should have specified a known path.")
22888       ("So I'll not change anything just now."); 
22889     mp_put_get_flush_error(mp, 0);
22890   } else if ( add_type==contour_code ) {
22891     if ( left_type(mp->cur_exp)==mp_endpoint ) {
22892       @<Complain about a non-cycle@>;
22893     } else { 
22894       p=mp_new_fill_node(mp, mp->cur_exp);
22895       mp->cur_type=mp_vacuous;
22896     }
22897   } else { 
22898     p=mp_new_stroked_node(mp, mp->cur_exp);
22899     mp->cur_type=mp_vacuous;
22900   }
22901 }
22902
22903 @ @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>=
22904 lhe=mp_find_edges_var(mp, lhv);
22905 if ( lhe==null ) {
22906   if ( (e==null)&&(p!=null) ) e=mp_toss_gr_object(mp, p);
22907   if ( e!=null ) delete_edge_ref(e);
22908 } else if ( add_type==also_code ) {
22909   if ( e!=null ) {
22910     @<Merge |e| into |lhe| and delete |e|@>;
22911   } else { 
22912     do_nothing;
22913   }
22914 } else if ( p!=null ) {
22915   link(obj_tail(lhe))=p;
22916   obj_tail(lhe)=p;
22917   if ( add_type==double_path_code )
22918     if ( pen_p(p)==null ) 
22919       pen_p(p)=mp_get_pen_circle(mp, 0);
22920 }
22921
22922 @ @<Merge |e| into |lhe| and delete |e|@>=
22923 { if ( link(dummy_loc(e))!=null ) {
22924     link(obj_tail(lhe))=link(dummy_loc(e));
22925     obj_tail(lhe)=obj_tail(e);
22926     obj_tail(e)=dummy_loc(e);
22927     link(dummy_loc(e))=null;
22928     mp_flush_dash_list(mp, lhe);
22929   }
22930   mp_toss_edges(mp, e);
22931 }
22932
22933 @ @<Cases of |do_statement|...@>=
22934 case ship_out_command: mp_do_ship_out(mp); break;
22935
22936 @ @<Declare action procedures for use by |do_statement|@>=
22937 @<Declare the function called |tfm_check|@>;
22938 @<Declare the \ps\ output procedures@>;
22939 void mp_do_ship_out (MP mp) ;
22940
22941 @ @c void mp_do_ship_out (MP mp) {
22942   integer c; /* the character code */
22943   mp_get_x_next(mp); mp_scan_expression(mp);
22944   if ( mp->cur_type!=mp_picture_type ) {
22945     @<Complain that it's not a known picture@>;
22946   } else { 
22947     c=mp_round_unscaled(mp, mp->internal[mp_char_code]) % 256;
22948     if ( c<0 ) c=c+256;
22949     @<Store the width information for character code~|c|@>;
22950     mp_ship_out(mp, mp->cur_exp);
22951     mp_flush_cur_exp(mp, 0);
22952   }
22953 }
22954
22955 @ @<Complain that it's not a known picture@>=
22956
22957   exp_err("Not a known picture");
22958   help1("I can only output known pictures.");
22959   mp_put_get_flush_error(mp, 0);
22960 }
22961
22962 @ The \&{everyjob} command simply assigns a nonzero value to the global variable
22963 |start_sym|.
22964
22965 @<Cases of |do_statement|...@>=
22966 case every_job_command: 
22967   mp_get_symbol(mp); mp->start_sym=mp->cur_sym; mp_get_x_next(mp);
22968   break;
22969
22970 @ @<Glob...@>=
22971 halfword start_sym; /* a symbolic token to insert at beginning of job */
22972
22973 @ @<Set init...@>=
22974 mp->start_sym=0;
22975
22976 @ Finally, we have only the ``message'' commands remaining.
22977
22978 @d message_code 0
22979 @d err_message_code 1
22980 @d err_help_code 2
22981 @d filename_template_code 3
22982 @d print_with_leading_zeroes(A)  g = mp->pool_ptr;
22983               mp_print_int(mp, (A)); g = mp->pool_ptr-g;
22984               if ( f>g ) {
22985                 mp->pool_ptr = mp->pool_ptr - g;
22986                 while ( f>g ) {
22987                   mp_print_char(mp, '0');
22988                   decr(f);
22989                   };
22990                 mp_print_int(mp, (A));
22991               };
22992               f = 0
22993
22994 @<Put each...@>=
22995 mp_primitive(mp, "message",message_command,message_code);
22996 @:message_}{\&{message} primitive@>
22997 mp_primitive(mp, "errmessage",message_command,err_message_code);
22998 @:err_message_}{\&{errmessage} primitive@>
22999 mp_primitive(mp, "errhelp",message_command,err_help_code);
23000 @:err_help_}{\&{errhelp} primitive@>
23001 mp_primitive(mp, "filenametemplate",message_command,filename_template_code);
23002 @:filename_template_}{\&{filenametemplate} primitive@>
23003
23004 @ @<Cases of |print_cmd...@>=
23005 case message_command: 
23006   if ( m<err_message_code ) mp_print(mp, "message");
23007   else if ( m==err_message_code ) mp_print(mp, "errmessage");
23008   else if ( m==filename_template_code ) mp_print(mp, "filenametemplate");
23009   else mp_print(mp, "errhelp");
23010   break;
23011
23012 @ @<Cases of |do_statement|...@>=
23013 case message_command: mp_do_message(mp); break;
23014
23015 @ @<Declare action procedures for use by |do_statement|@>=
23016 @<Declare a procedure called |no_string_err|@>;
23017 void mp_do_message (MP mp) ;
23018
23019
23020 @c void mp_do_message (MP mp) {
23021   int m; /* the type of message */
23022   m=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
23023   if ( mp->cur_type!=mp_string_type )
23024     mp_no_string_err(mp, "A message should be a known string expression.");
23025   else {
23026     switch (m) {
23027     case message_code: 
23028       mp_print_nl(mp, ""); mp_print_str(mp, mp->cur_exp);
23029       break;
23030     case err_message_code:
23031       @<Print string |cur_exp| as an error message@>;
23032       break;
23033     case err_help_code:
23034       @<Save string |cur_exp| as the |err_help|@>;
23035       break;
23036     case filename_template_code:
23037       @<Save the filename template@>;
23038       break;
23039     } /* there are no other cases */
23040   }
23041   mp_flush_cur_exp(mp, 0);
23042 }
23043
23044 @ @<Declare a procedure called |no_string_err|@>=
23045 void mp_no_string_err (MP mp,char *s) { 
23046    exp_err("Not a string");
23047 @.Not a string@>
23048   help1(s);
23049   mp_put_get_error(mp);
23050 }
23051
23052 @ The global variable |err_help| is zero when the user has most recently
23053 given an empty help string, or if none has ever been given.
23054
23055 @<Save string |cur_exp| as the |err_help|@>=
23056
23057   if ( mp->err_help!=0 ) delete_str_ref(mp->err_help);
23058   if ( length(mp->cur_exp)==0 ) mp->err_help=0;
23059   else  { mp->err_help=mp->cur_exp; add_str_ref(mp->err_help); }
23060 }
23061
23062 @ If \&{errmessage} occurs often in |mp_scroll_mode|, without user-defined
23063 \&{errhelp}, we don't want to give a long help message each time. So we
23064 give a verbose explanation only once.
23065
23066 @<Glob...@>=
23067 boolean long_help_seen; /* has the long \.{\\errmessage} help been used? */
23068
23069 @ @<Set init...@>=mp->long_help_seen=false;
23070
23071 @ @<Print string |cur_exp| as an error message@>=
23072
23073   print_err(""); mp_print_str(mp, mp->cur_exp);
23074   if ( mp->err_help!=0 ) {
23075     mp->use_err_help=true;
23076   } else if ( mp->long_help_seen ) { 
23077     help1("(That was another `errmessage'.)") ; 
23078   } else  { 
23079    if ( mp->interaction<mp_error_stop_mode ) mp->long_help_seen=true;
23080     help4("This error message was generated by an `errmessage'")
23081      ("command, so I can\'t give any explicit help.")
23082      ("Pretend that you're Miss Marple: Examine all clues,")
23083 @^Marple, Jane@>
23084      ("and deduce the truth by inspired guesses.");
23085   }
23086   mp_put_get_error(mp); mp->use_err_help=false;
23087 }
23088
23089 @ @<Cases of |do_statement|...@>=
23090 case write_command: mp_do_write(mp); break;
23091
23092 @ @<Declare action procedures for use by |do_statement|@>=
23093 void mp_do_write (MP mp) ;
23094
23095 @ @c void mp_do_write (MP mp) {
23096   str_number t; /* the line of text to be written */
23097   write_index n,n0; /* for searching |wr_fname| and |wr_file| arrays */
23098   int old_setting; /* for saving |selector| during output */
23099   mp_get_x_next(mp);
23100   mp_scan_expression(mp);
23101   if ( mp->cur_type!=mp_string_type ) {
23102     mp_no_string_err(mp, "The text to be written should be a known string expression");
23103   } else if ( mp->cur_cmd!=to_token ) { 
23104     print_err("Missing `to' clause");
23105     help1("A write command should end with `to <filename>'");
23106     mp_put_get_error(mp);
23107   } else { 
23108     t=mp->cur_exp; mp->cur_type=mp_vacuous;
23109     mp_get_x_next(mp);
23110     mp_scan_expression(mp);
23111     if ( mp->cur_type!=mp_string_type )
23112       mp_no_string_err(mp, "I can\'t write to that file name.  It isn't a known string");
23113     else {
23114       @<Write |t| to the file named by |cur_exp|@>;
23115     }
23116     delete_str_ref(t);
23117   }
23118   mp_flush_cur_exp(mp, 0);
23119 }
23120
23121 @ @<Write |t| to the file named by |cur_exp|@>=
23122
23123   @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if
23124     |cur_exp| must be inserted@>;
23125   if ( mp_str_vs_str(mp, t,mp->eof_line)==0 ) {
23126     @<Record the end of file on |wr_file[n]|@>;
23127   } else { 
23128     old_setting=mp->selector;
23129     mp->selector=n+write_file;
23130     mp_print_str(mp, t); mp_print_ln(mp);
23131     mp->selector = old_setting;
23132   }
23133 }
23134
23135 @ @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if...@>=
23136 {
23137   char *fn = str(mp->cur_exp);
23138   n=mp->write_files;
23139   n0=mp->write_files;
23140   while (mp_xstrcmp(fn,mp->wr_fname[n])!=0) { 
23141     if ( n==0 ) { /* bottom reached */
23142           if ( n0==mp->write_files ) {
23143         if ( mp->write_files<mp->max_write_files ) {
23144           incr(mp->write_files);
23145         } else {
23146           void **wr_file;
23147           char **wr_fname;
23148               write_index l,k;
23149           l = mp->max_write_files + (mp->max_write_files>>2);
23150           wr_file = xmalloc((l+1),sizeof(void *));
23151           wr_fname = xmalloc((l+1),sizeof(char *));
23152               for (k=0;k<=l;k++) {
23153             if (k<=mp->max_write_files) {
23154                   wr_file[k]=mp->wr_file[k]; 
23155               wr_fname[k]=mp->wr_fname[k];
23156             } else {
23157                   wr_file[k]=0; 
23158               wr_fname[k]=NULL;
23159             }
23160           }
23161               xfree(mp->wr_file); xfree(mp->wr_fname);
23162           mp->max_write_files = l;
23163           mp->wr_file = wr_file;
23164           mp->wr_fname = wr_fname;
23165         }
23166       }
23167       n=n0;
23168       mp_open_write_file(mp, fn ,n);
23169     } else { 
23170       decr(n);
23171           if ( mp->wr_fname[n]==NULL )  n0=n; 
23172     }
23173   }
23174 }
23175
23176 @ @<Record the end of file on |wr_file[n]|@>=
23177 { (mp->close_file)(mp->wr_file[n]);
23178   xfree(mp->wr_fname[n]);
23179   mp->wr_fname[n]=NULL;
23180   if ( n==mp->write_files-1 ) mp->write_files=n;
23181 }
23182
23183
23184 @* \[42] Writing font metric data.
23185 \TeX\ gets its knowledge about fonts from font metric files, also called
23186 \.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
23187 but other programs know about them too. One of \MP's duties is to
23188 write \.{TFM} files so that the user's fonts can readily be
23189 applied to typesetting.
23190 @:TFM files}{\.{TFM} files@>
23191 @^font metric files@>
23192
23193 The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
23194 Since the number of bytes is always a multiple of~4, we could
23195 also regard the file as a sequence of 32-bit words, but \MP\ uses the
23196 byte interpretation. The format of \.{TFM} files was designed by
23197 Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
23198 @^Ramshaw, Lyle Harold@>
23199 of information in a compact but useful form.
23200
23201 @<Glob...@>=
23202 void * tfm_file; /* the font metric output goes here */
23203 char * metric_file_name; /* full name of the font metric file */
23204
23205 @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
23206 integers that give the lengths of the various subsequent portions
23207 of the file. These twelve integers are, in order:
23208 $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
23209 |lf|&length of the entire file, in words;\cr
23210 |lh|&length of the header data, in words;\cr
23211 |bc|&smallest character code in the font;\cr
23212 |ec|&largest character code in the font;\cr
23213 |nw|&number of words in the width table;\cr
23214 |nh|&number of words in the height table;\cr
23215 |nd|&number of words in the depth table;\cr
23216 |ni|&number of words in the italic correction table;\cr
23217 |nl|&number of words in the lig/kern table;\cr
23218 |nk|&number of words in the kern table;\cr
23219 |ne|&number of words in the extensible character table;\cr
23220 |np|&number of font parameter words.\cr}}$$
23221 They are all nonnegative and less than $2^{15}$. We must have |bc-1<=ec<=255|,
23222 |ne<=256|, and
23223 $$\hbox{|lf=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
23224 Note that a font may contain as many as 256 characters (if |bc=0| and |ec=255|),
23225 and as few as 0 characters (if |bc=ec+1|).
23226
23227 Incidentally, when two or more 8-bit bytes are combined to form an integer of
23228 16 or more bits, the most significant bytes appear first in the file.
23229 This is called BigEndian order.
23230 @^BigEndian order@>
23231
23232 @ The rest of the \.{TFM} file may be regarded as a sequence of ten data
23233 arrays.
23234
23235 The most important data type used here is a |fix_word|, which is
23236 a 32-bit representation of a binary fraction. A |fix_word| is a signed
23237 quantity, with the two's complement of the entire word used to represent
23238 negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
23239 binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
23240 the smallest is $-2048$. We will see below, however, that all but two of
23241 the |fix_word| values must lie between $-16$ and $+16$.
23242
23243 @ The first data array is a block of header information, which contains
23244 general facts about the font. The header must contain at least two words,
23245 |header[0]| and |header[1]|, whose meaning is explained below.  Additional
23246 header information of use to other software routines might also be
23247 included, and \MP\ will generate it if the \.{headerbyte} command occurs.
23248 For example, 16 more words of header information are in use at the Xerox
23249 Palo Alto Research Center; the first ten specify the character coding
23250 scheme used (e.g., `\.{XEROX TEXT}' or `\.{TEX MATHSY}'), the next five
23251 give the font family name (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
23252 last gives the ``face byte.''
23253
23254 \yskip\hang|header[0]| is a 32-bit check sum that \MP\ will copy into
23255 the \.{GF} output file. This helps ensure consistency between files,
23256 since \TeX\ records the check sums from the \.{TFM}'s it reads, and these
23257 should match the check sums on actual fonts that are used.  The actual
23258 relation between this check sum and the rest of the \.{TFM} file is not
23259 important; the check sum is simply an identification number with the
23260 property that incompatible fonts almost always have distinct check sums.
23261 @^check sum@>
23262
23263 \yskip\hang|header[1]| is a |fix_word| containing the design size of the
23264 font, in units of \TeX\ points. This number must be at least 1.0; it is
23265 fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
23266 font, i.e., a font that was designed to look best at a 10-point size,
23267 whatever that really means. When a \TeX\ user asks for a font `\.{at}
23268 $\delta$ \.{pt}', the effect is to override the design size and replace it
23269 by $\delta$, and to multiply the $x$ and~$y$ coordinates of the points in
23270 the font image by a factor of $\delta$ divided by the design size.  {\sl
23271 All other dimensions in the\/ \.{TFM} file are |fix_word|\kern-1pt\
23272 numbers in design-size units.} Thus, for example, the value of |param[6]|,
23273 which defines the \.{em} unit, is often the |fix_word| value $2^{20}=1.0$,
23274 since many fonts have a design size equal to one em.  The other dimensions
23275 must be less than 16 design-size units in absolute value; thus,
23276 |header[1]| and |param[1]| are the only |fix_word| entries in the whole
23277 \.{TFM} file whose first byte might be something besides 0 or 255.
23278
23279 @ Next comes the |char_info| array, which contains one |char_info_word|
23280 per character. Each word in this part of the file contains six fields
23281 packed into four bytes as follows.
23282
23283 \yskip\hang first byte: |width_index| (8 bits)\par
23284 \hang second byte: |height_index| (4 bits) times 16, plus |depth_index|
23285   (4~bits)\par
23286 \hang third byte: |italic_index| (6 bits) times 4, plus |tag|
23287   (2~bits)\par
23288 \hang fourth byte: |remainder| (8 bits)\par
23289 \yskip\noindent
23290 The actual width of a character is \\{width}|[width_index]|, in design-size
23291 units; this is a device for compressing information, since many characters
23292 have the same width. Since it is quite common for many characters
23293 to have the same height, depth, or italic correction, the \.{TFM} format
23294 imposes a limit of 16 different heights, 16 different depths, and
23295 64 different italic corrections.
23296
23297 Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
23298 \\{italic}[0]=0$ should always hold, so that an index of zero implies a
23299 value of zero.  The |width_index| should never be zero unless the
23300 character does not exist in the font, since a character is valid if and
23301 only if it lies between |bc| and |ec| and has a nonzero |width_index|.
23302
23303 @ The |tag| field in a |char_info_word| has four values that explain how to
23304 interpret the |remainder| field.
23305
23306 \yskip\hang|tag=0| (|no_tag|) means that |remainder| is unused.\par
23307 \hang|tag=1| (|lig_tag|) means that this character has a ligature/kerning
23308 program starting at location |remainder| in the |lig_kern| array.\par
23309 \hang|tag=2| (|list_tag|) means that this character is part of a chain of
23310 characters of ascending sizes, and not the largest in the chain.  The
23311 |remainder| field gives the character code of the next larger character.\par
23312 \hang|tag=3| (|ext_tag|) means that this character code represents an
23313 extensible character, i.e., a character that is built up of smaller pieces
23314 so that it can be made arbitrarily large. The pieces are specified in
23315 |exten[remainder]|.\par
23316 \yskip\noindent
23317 Characters with |tag=2| and |tag=3| are treated as characters with |tag=0|
23318 unless they are used in special circumstances in math formulas. For example,
23319 \TeX's \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
23320 operation looks for both |list_tag| and |ext_tag|.
23321
23322 @d no_tag 0 /* vanilla character */
23323 @d lig_tag 1 /* character has a ligature/kerning program */
23324 @d list_tag 2 /* character has a successor in a charlist */
23325 @d ext_tag 3 /* character is extensible */
23326
23327 @ The |lig_kern| array contains instructions in a simple programming language
23328 that explains what to do for special letter pairs. Each word in this array is a
23329 |lig_kern_command| of four bytes.
23330
23331 \yskip\hang first byte: |skip_byte|, indicates that this is the final program
23332   step if the byte is 128 or more, otherwise the next step is obtained by
23333   skipping this number of intervening steps.\par
23334 \hang second byte: |next_char|, ``if |next_char| follows the current character,
23335   then perform the operation and stop, otherwise continue.''\par
23336 \hang third byte: |op_byte|, indicates a ligature step if less than~128,
23337   a kern step otherwise.\par
23338 \hang fourth byte: |remainder|.\par
23339 \yskip\noindent
23340 In a kern step, an
23341 additional space equal to |kern[256*(op_byte-128)+remainder]| is inserted
23342 between the current character and |next_char|. This amount is
23343 often negative, so that the characters are brought closer together
23344 by kerning; but it might be positive.
23345
23346 There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
23347 $0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
23348 |remainder| is inserted between the current character and |next_char|;
23349 then the current character is deleted if $b=0$, and |next_char| is
23350 deleted if $c=0$; then we pass over $a$~characters to reach the next
23351 current character (which may have a ligature/kerning program of its own).
23352
23353 If the very first instruction of the |lig_kern| array has |skip_byte=255|,
23354 the |next_char| byte is the so-called right boundary character of this font;
23355 the value of |next_char| need not lie between |bc| and~|ec|.
23356 If the very last instruction of the |lig_kern| array has |skip_byte=255|,
23357 there is a special ligature/kerning program for a left boundary character,
23358 beginning at location |256*op_byte+remainder|.
23359 The interpretation is that \TeX\ puts implicit boundary characters
23360 before and after each consecutive string of characters from the same font.
23361 These implicit characters do not appear in the output, but they can affect
23362 ligatures and kerning.
23363
23364 If the very first instruction of a character's |lig_kern| program has
23365 |skip_byte>128|, the program actually begins in location
23366 |256*op_byte+remainder|. This feature allows access to large |lig_kern|
23367 arrays, because the first instruction must otherwise
23368 appear in a location |<=255|.
23369
23370 Any instruction with |skip_byte>128| in the |lig_kern| array must satisfy
23371 the condition
23372 $$\hbox{|256*op_byte+remainder<nl|.}$$
23373 If such an instruction is encountered during
23374 normal program execution, it denotes an unconditional halt; no ligature
23375 command is performed.
23376
23377 @d stop_flag (128)
23378   /* value indicating `\.{STOP}' in a lig/kern program */
23379 @d kern_flag (128) /* op code for a kern step */
23380 @d skip_byte(A) mp->lig_kern[(A)].b0
23381 @d next_char(A) mp->lig_kern[(A)].b1
23382 @d op_byte(A) mp->lig_kern[(A)].b2
23383 @d rem_byte(A) mp->lig_kern[(A)].b3
23384
23385 @ Extensible characters are specified by an |extensible_recipe|, which
23386 consists of four bytes called |top|, |mid|, |bot|, and |rep| (in this
23387 order). These bytes are the character codes of individual pieces used to
23388 build up a large symbol.  If |top|, |mid|, or |bot| are zero, they are not
23389 present in the built-up result. For example, an extensible vertical line is
23390 like an extensible bracket, except that the top and bottom pieces are missing.
23391
23392 Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
23393 if the piece isn't present. Then the extensible characters have the form
23394 $TR^kMR^kB$ from top to bottom, for some |k>=0|, unless $M$ is absent;
23395 in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
23396 The width of the extensible character is the width of $R$; and the
23397 height-plus-depth is the sum of the individual height-plus-depths of the
23398 components used, since the pieces are butted together in a vertical list.
23399
23400 @d ext_top(A) mp->exten[(A)].b0 /* |top| piece in a recipe */
23401 @d ext_mid(A) mp->exten[(A)].b1 /* |mid| piece in a recipe */
23402 @d ext_bot(A) mp->exten[(A)].b2 /* |bot| piece in a recipe */
23403 @d ext_rep(A) mp->exten[(A)].b3 /* |rep| piece in a recipe */
23404
23405 @ The final portion of a \.{TFM} file is the |param| array, which is another
23406 sequence of |fix_word| values.
23407
23408 \yskip\hang|param[1]=slant| is the amount of italic slant, which is used
23409 to help position accents. For example, |slant=.25| means that when you go
23410 up one unit, you also go .25 units to the right. The |slant| is a pure
23411 number; it is the only |fix_word| other than the design size itself that is
23412 not scaled by the design size.
23413
23414 \hang|param[2]=space| is the normal spacing between words in text.
23415 Note that character 040 in the font need not have anything to do with
23416 blank spaces.
23417
23418 \hang|param[3]=space_stretch| is the amount of glue stretching between words.
23419
23420 \hang|param[4]=space_shrink| is the amount of glue shrinking between words.
23421
23422 \hang|param[5]=x_height| is the size of one ex in the font; it is also
23423 the height of letters for which accents don't have to be raised or lowered.
23424
23425 \hang|param[6]=quad| is the size of one em in the font.
23426
23427 \hang|param[7]=extra_space| is the amount added to |param[2]| at the
23428 ends of sentences.
23429
23430 \yskip\noindent
23431 If fewer than seven parameters are present, \TeX\ sets the missing parameters
23432 to zero.
23433
23434 @d slant_code 1
23435 @d space_code 2
23436 @d space_stretch_code 3
23437 @d space_shrink_code 4
23438 @d x_height_code 5
23439 @d quad_code 6
23440 @d extra_space_code 7
23441
23442 @ So that is what \.{TFM} files hold. One of \MP's duties is to output such
23443 information, and it does this all at once at the end of a job.
23444 In order to prepare for such frenetic activity, it squirrels away the
23445 necessary facts in various arrays as information becomes available.
23446
23447 Character dimensions (\&{charwd}, \&{charht}, \&{chardp}, and \&{charic})
23448 are stored respectively in |tfm_width|, |tfm_height|, |tfm_depth|, and
23449 |tfm_ital_corr|. Other information about a character (e.g., about
23450 its ligatures or successors) is accessible via the |char_tag| and
23451 |char_remainder| arrays. Other information about the font as a whole
23452 is kept in additional arrays called |header_byte|, |lig_kern|,
23453 |kern|, |exten|, and |param|.
23454
23455 @d max_tfm_int 32510
23456 @d undefined_label max_tfm_int /* an undefined local label */
23457
23458 @<Glob...@>=
23459 #define TFM_ITEMS 257
23460 eight_bits bc;
23461 eight_bits ec; /* smallest and largest character codes shipped out */
23462 scaled tfm_width[TFM_ITEMS]; /* \&{charwd} values */
23463 scaled tfm_height[TFM_ITEMS]; /* \&{charht} values */
23464 scaled tfm_depth[TFM_ITEMS]; /* \&{chardp} values */
23465 scaled tfm_ital_corr[TFM_ITEMS]; /* \&{charic} values */
23466 boolean char_exists[TFM_ITEMS]; /* has this code been shipped out? */
23467 int char_tag[TFM_ITEMS]; /* |remainder| category */
23468 int char_remainder[TFM_ITEMS]; /* the |remainder| byte */
23469 char *header_byte; /* bytes of the \.{TFM} header */
23470 int header_last; /* last initialized \.{TFM} header byte */
23471 int header_size; /* size of the \.{TFM} header */
23472 four_quarters *lig_kern; /* the ligature/kern table */
23473 short nl; /* the number of ligature/kern steps so far */
23474 scaled *kern; /* distinct kerning amounts */
23475 short nk; /* the number of distinct kerns so far */
23476 four_quarters exten[TFM_ITEMS]; /* extensible character recipes */
23477 short ne; /* the number of extensible characters so far */
23478 scaled *param; /* \&{fontinfo} parameters */
23479 short np; /* the largest \&{fontinfo} parameter specified so far */
23480 short nw;short nh;short nd;short ni; /* sizes of \.{TFM} subtables */
23481 short skip_table[TFM_ITEMS]; /* local label status */
23482 boolean lk_started; /* has there been a lig/kern step in this command yet? */
23483 integer bchar; /* right boundary character */
23484 short bch_label; /* left boundary starting location */
23485 short ll;short lll; /* registers used for lig/kern processing */
23486 short label_loc[257]; /* lig/kern starting addresses */
23487 eight_bits label_char[257]; /* characters for |label_loc| */
23488 short label_ptr; /* highest position occupied in |label_loc| */
23489
23490 @ @<Allocate or initialize ...@>=
23491 mp->header_last = 0; mp->header_size = 128; /* just for init */
23492 mp->header_byte = xmalloc(mp->header_size, sizeof(char));
23493 mp->lig_kern = NULL; /* allocated when needed */
23494 mp->kern = NULL; /* allocated when needed */ 
23495 mp->param = NULL; /* allocated when needed */
23496
23497 @ @<Dealloc variables@>=
23498 xfree(mp->header_byte);
23499 xfree(mp->lig_kern);
23500 xfree(mp->kern);
23501 xfree(mp->param);
23502
23503 @ @<Set init...@>=
23504 for (k=0;k<= 255;k++ ) {
23505   mp->tfm_width[k]=0; mp->tfm_height[k]=0; mp->tfm_depth[k]=0; mp->tfm_ital_corr[k]=0;
23506   mp->char_exists[k]=false; mp->char_tag[k]=no_tag; mp->char_remainder[k]=0;
23507   mp->skip_table[k]=undefined_label;
23508 };
23509 memset(mp->header_byte,0,mp->header_size);
23510 mp->bc=255; mp->ec=0; mp->nl=0; mp->nk=0; mp->ne=0; mp->np=0;
23511 mp->internal[mp_boundary_char]=-unity;
23512 mp->bch_label=undefined_label;
23513 mp->label_loc[0]=-1; mp->label_ptr=0;
23514
23515 @ @<Declarations@>=
23516 scaled mp_tfm_check (MP mp,small_number m) ;
23517
23518 @ @<Declare the function called |tfm_check|@>=
23519 scaled mp_tfm_check (MP mp,small_number m) {
23520   if ( abs(mp->internal[m])>=fraction_half ) {
23521     print_err("Enormous "); mp_print(mp, mp->int_name[m]);
23522 @.Enormous charwd...@>
23523 @.Enormous chardp...@>
23524 @.Enormous charht...@>
23525 @.Enormous charic...@>
23526 @.Enormous designsize...@>
23527     mp_print(mp, " has been reduced");
23528     help1("Font metric dimensions must be less than 2048pt.");
23529     mp_put_get_error(mp);
23530     if ( mp->internal[m]>0 ) return (fraction_half-1);
23531     else return (1-fraction_half);
23532   } else {
23533     return mp->internal[m];
23534   }
23535 }
23536
23537 @ @<Store the width information for character code~|c|@>=
23538 if ( c<mp->bc ) mp->bc=c;
23539 if ( c>mp->ec ) mp->ec=c;
23540 mp->char_exists[c]=true;
23541 mp->tfm_width[c]=mp_tfm_check(mp, mp_char_wd);
23542 mp->tfm_height[c]=mp_tfm_check(mp, mp_char_ht);
23543 mp->tfm_depth[c]=mp_tfm_check(mp, mp_char_dp);
23544 mp->tfm_ital_corr[c]=mp_tfm_check(mp, mp_char_ic)
23545
23546 @ Now let's consider \MP's special \.{TFM}-oriented commands.
23547
23548 @<Cases of |do_statement|...@>=
23549 case tfm_command: mp_do_tfm_command(mp); break;
23550
23551 @ @d char_list_code 0
23552 @d lig_table_code 1
23553 @d extensible_code 2
23554 @d header_byte_code 3
23555 @d font_dimen_code 4
23556
23557 @<Put each...@>=
23558 mp_primitive(mp, "charlist",tfm_command,char_list_code);
23559 @:char_list_}{\&{charlist} primitive@>
23560 mp_primitive(mp, "ligtable",tfm_command,lig_table_code);
23561 @:lig_table_}{\&{ligtable} primitive@>
23562 mp_primitive(mp, "extensible",tfm_command,extensible_code);
23563 @:extensible_}{\&{extensible} primitive@>
23564 mp_primitive(mp, "headerbyte",tfm_command,header_byte_code);
23565 @:header_byte_}{\&{headerbyte} primitive@>
23566 mp_primitive(mp, "fontdimen",tfm_command,font_dimen_code);
23567 @:font_dimen_}{\&{fontdimen} primitive@>
23568
23569 @ @<Cases of |print_cmd...@>=
23570 case tfm_command: 
23571   switch (m) {
23572   case char_list_code:mp_print(mp, "charlist"); break;
23573   case lig_table_code:mp_print(mp, "ligtable"); break;
23574   case extensible_code:mp_print(mp, "extensible"); break;
23575   case header_byte_code:mp_print(mp, "headerbyte"); break;
23576   default: mp_print(mp, "fontdimen"); break;
23577   }
23578   break;
23579
23580 @ @<Declare action procedures for use by |do_statement|@>=
23581 eight_bits mp_get_code (MP mp) ;
23582
23583 @ @c eight_bits mp_get_code (MP mp) { /* scans a character code value */
23584   integer c; /* the code value found */
23585   mp_get_x_next(mp); mp_scan_expression(mp);
23586   if ( mp->cur_type==mp_known ) { 
23587     c=mp_round_unscaled(mp, mp->cur_exp);
23588     if ( c>=0 ) if ( c<256 ) return c;
23589   } else if ( mp->cur_type==mp_string_type ) {
23590     if ( length(mp->cur_exp)==1 )  { 
23591       c=mp->str_pool[mp->str_start[mp->cur_exp]];
23592       return c;
23593     }
23594   }
23595   exp_err("Invalid code has been replaced by 0");
23596 @.Invalid code...@>
23597   help2("I was looking for a number between 0 and 255, or for a")
23598        ("string of length 1. Didn't find it; will use 0 instead.");
23599   mp_put_get_flush_error(mp, 0); c=0;
23600   return c;
23601 };
23602
23603 @ @<Declare action procedures for use by |do_statement|@>=
23604 void mp_set_tag (MP mp,halfword c, small_number t, halfword r) ;
23605
23606 @ @c void mp_set_tag (MP mp,halfword c, small_number t, halfword r) { 
23607   if ( mp->char_tag[c]==no_tag ) {
23608     mp->char_tag[c]=t; mp->char_remainder[c]=r;
23609     if ( t==lig_tag ){ 
23610       incr(mp->label_ptr); mp->label_loc[mp->label_ptr]=r; 
23611       mp->label_char[mp->label_ptr]=c;
23612     }
23613   } else {
23614     @<Complain about a character tag conflict@>;
23615   }
23616 }
23617
23618 @ @<Complain about a character tag conflict@>=
23619
23620   print_err("Character ");
23621   if ( (c>' ')&&(c<127) ) mp_print_char(mp,c);
23622   else if ( c==256 ) mp_print(mp, "||");
23623   else  { mp_print(mp, "code "); mp_print_int(mp, c); };
23624   mp_print(mp, " is already ");
23625 @.Character c is already...@>
23626   switch (mp->char_tag[c]) {
23627   case lig_tag: mp_print(mp, "in a ligtable"); break;
23628   case list_tag: mp_print(mp, "in a charlist"); break;
23629   case ext_tag: mp_print(mp, "extensible"); break;
23630   } /* there are no other cases */
23631   help2("It's not legal to label a character more than once.")
23632     ("So I'll not change anything just now.");
23633   mp_put_get_error(mp); 
23634 }
23635
23636 @ @<Declare action procedures for use by |do_statement|@>=
23637 void mp_do_tfm_command (MP mp) ;
23638
23639 @ @c void mp_do_tfm_command (MP mp) {
23640   int c,cc; /* character codes */
23641   int k; /* index into the |kern| array */
23642   int j; /* index into |header_byte| or |param| */
23643   switch (mp->cur_mod) {
23644   case char_list_code: 
23645     c=mp_get_code(mp);
23646      /* we will store a list of character successors */
23647     while ( mp->cur_cmd==colon )   { 
23648       cc=mp_get_code(mp); mp_set_tag(mp, c,list_tag,cc); c=cc;
23649     };
23650     break;
23651   case lig_table_code: 
23652     if (mp->lig_kern==NULL) 
23653        mp->lig_kern = xmalloc((max_tfm_int+1),sizeof(four_quarters));
23654     if (mp->kern==NULL) 
23655        mp->kern = xmalloc((max_tfm_int+1),sizeof(scaled));
23656     @<Store a list of ligature/kern steps@>;
23657     break;
23658   case extensible_code: 
23659     @<Define an extensible recipe@>;
23660     break;
23661   case header_byte_code: 
23662   case font_dimen_code: 
23663     c=mp->cur_mod; mp_get_x_next(mp);
23664     mp_scan_expression(mp);
23665     if ( (mp->cur_type!=mp_known)||(mp->cur_exp<half_unit) ) {
23666       exp_err("Improper location");
23667 @.Improper location@>
23668       help2("I was looking for a known, positive number.")
23669        ("For safety's sake I'll ignore the present command.");
23670       mp_put_get_error(mp);
23671     } else  { 
23672       j=mp_round_unscaled(mp, mp->cur_exp);
23673       if ( mp->cur_cmd!=colon ) {
23674         mp_missing_err(mp, ":");
23675 @.Missing `:'@>
23676         help1("A colon should follow a headerbyte or fontinfo location.");
23677         mp_back_error(mp);
23678       }
23679       if ( c==header_byte_code ) { 
23680         @<Store a list of header bytes@>;
23681       } else {     
23682         if (mp->param==NULL) 
23683           mp->param = xmalloc((max_tfm_int+1),sizeof(scaled));
23684         @<Store a list of font dimensions@>;
23685       }
23686     }
23687     break;
23688   } /* there are no other cases */
23689 };
23690
23691 @ @<Store a list of ligature/kern steps@>=
23692
23693   mp->lk_started=false;
23694 CONTINUE: 
23695   mp_get_x_next(mp);
23696   if ((mp->cur_cmd==skip_to)&& mp->lk_started )
23697     @<Process a |skip_to| command and |goto done|@>;
23698   if ( mp->cur_cmd==bchar_label ) { c=256; mp->cur_cmd=colon; }
23699   else { mp_back_input(mp); c=mp_get_code(mp); };
23700   if ((mp->cur_cmd==colon)||(mp->cur_cmd==double_colon)) {
23701     @<Record a label in a lig/kern subprogram and |goto continue|@>;
23702   }
23703   if ( mp->cur_cmd==lig_kern_token ) { 
23704     @<Compile a ligature/kern command@>; 
23705   } else  { 
23706     print_err("Illegal ligtable step");
23707 @.Illegal ligtable step@>
23708     help1("I was looking for `=:' or `kern' here.");
23709     mp_back_error(mp); next_char(mp->nl)=qi(0); 
23710     op_byte(mp->nl)=qi(0); rem_byte(mp->nl)=qi(0);
23711     skip_byte(mp->nl)=stop_flag+1; /* this specifies an unconditional stop */
23712   }
23713   if ( mp->nl==max_tfm_int) mp_fatal_error(mp, "ligtable too large");
23714   incr(mp->nl);
23715   if ( mp->cur_cmd==comma ) goto CONTINUE;
23716   if ( skip_byte(mp->nl-1)<stop_flag ) skip_byte(mp->nl-1)=stop_flag;
23717 }
23718 DONE:
23719
23720 @ @<Put each...@>=
23721 mp_primitive(mp, "=:",lig_kern_token,0);
23722 @:=:_}{\.{=:} primitive@>
23723 mp_primitive(mp, "=:|",lig_kern_token,1);
23724 @:=:/_}{\.{=:\char'174} primitive@>
23725 mp_primitive(mp, "=:|>",lig_kern_token,5);
23726 @:=:/>_}{\.{=:\char'174>} primitive@>
23727 mp_primitive(mp, "|=:",lig_kern_token,2);
23728 @:=:/_}{\.{\char'174=:} primitive@>
23729 mp_primitive(mp, "|=:>",lig_kern_token,6);
23730 @:=:/>_}{\.{\char'174=:>} primitive@>
23731 mp_primitive(mp, "|=:|",lig_kern_token,3);
23732 @:=:/_}{\.{\char'174=:\char'174} primitive@>
23733 mp_primitive(mp, "|=:|>",lig_kern_token,7);
23734 @:=:/>_}{\.{\char'174=:\char'174>} primitive@>
23735 mp_primitive(mp, "|=:|>>",lig_kern_token,11);
23736 @:=:/>_}{\.{\char'174=:\char'174>>} primitive@>
23737 mp_primitive(mp, "kern",lig_kern_token,128);
23738 @:kern_}{\&{kern} primitive@>
23739
23740 @ @<Cases of |print_cmd...@>=
23741 case lig_kern_token: 
23742   switch (m) {
23743   case 0:mp_print(mp, "=:"); break;
23744   case 1:mp_print(mp, "=:|"); break;
23745   case 2:mp_print(mp, "|=:"); break;
23746   case 3:mp_print(mp, "|=:|"); break;
23747   case 5:mp_print(mp, "=:|>"); break;
23748   case 6:mp_print(mp, "|=:>"); break;
23749   case 7:mp_print(mp, "|=:|>"); break;
23750   case 11:mp_print(mp, "|=:|>>"); break;
23751   default: mp_print(mp, "kern"); break;
23752   }
23753   break;
23754
23755 @ Local labels are implemented by maintaining the |skip_table| array,
23756 where |skip_table[c]| is either |undefined_label| or the address of the
23757 most recent lig/kern instruction that skips to local label~|c|. In the
23758 latter case, the |skip_byte| in that instruction will (temporarily)
23759 be zero if there were no prior skips to this label, or it will be the
23760 distance to the prior skip.
23761
23762 We may need to cancel skips that span more than 127 lig/kern steps.
23763
23764 @d cancel_skips(A) mp->ll=(A);
23765   do {  
23766     mp->lll=qo(skip_byte(mp->ll)); 
23767     skip_byte(mp->ll)=stop_flag; mp->ll=mp->ll-mp->lll;
23768   } while (mp->lll!=0)
23769 @d skip_error(A) { print_err("Too far to skip");
23770 @.Too far to skip@>
23771   help1("At most 127 lig/kern steps can separate skipto1 from 1::.");
23772   mp_error(mp); cancel_skips((A));
23773   }
23774
23775 @<Process a |skip_to| command and |goto done|@>=
23776
23777   c=mp_get_code(mp);
23778   if ( mp->nl-mp->skip_table[c]>128 ) { /* |skip_table[c]<<nl<=undefined_label| */
23779     skip_error(mp->skip_table[c]); mp->skip_table[c]=undefined_label;
23780   }
23781   if ( mp->skip_table[c]==undefined_label ) skip_byte(mp->nl-1)=qi(0);
23782   else skip_byte(mp->nl-1)=qi(mp->nl-mp->skip_table[c]-1);
23783   mp->skip_table[c]=mp->nl-1; goto DONE;
23784 }
23785
23786 @ @<Record a label in a lig/kern subprogram and |goto continue|@>=
23787
23788   if ( mp->cur_cmd==colon ) {
23789     if ( c==256 ) mp->bch_label=mp->nl;
23790     else mp_set_tag(mp, c,lig_tag,mp->nl);
23791   } else if ( mp->skip_table[c]<undefined_label ) {
23792     mp->ll=mp->skip_table[c]; mp->skip_table[c]=undefined_label;
23793     do {  
23794       mp->lll=qo(skip_byte(mp->ll));
23795       if ( mp->nl-mp->ll>128 ) {
23796         skip_error(mp->ll); goto CONTINUE;
23797       }
23798       skip_byte(mp->ll)=qi(mp->nl-mp->ll-1); mp->ll=mp->ll-mp->lll;
23799     } while (mp->lll!=0);
23800   }
23801   goto CONTINUE;
23802 }
23803
23804 @ @<Compile a ligature/kern...@>=
23805
23806   next_char(mp->nl)=qi(c); skip_byte(mp->nl)=qi(0);
23807   if ( mp->cur_mod<128 ) { /* ligature op */
23808     op_byte(mp->nl)=qi(mp->cur_mod); rem_byte(mp->nl)=qi(mp_get_code(mp));
23809   } else { 
23810     mp_get_x_next(mp); mp_scan_expression(mp);
23811     if ( mp->cur_type!=mp_known ) {
23812       exp_err("Improper kern");
23813 @.Improper kern@>
23814       help2("The amount of kern should be a known numeric value.")
23815         ("I'm zeroing this one. Proceed, with fingers crossed.");
23816       mp_put_get_flush_error(mp, 0);
23817     }
23818     mp->kern[mp->nk]=mp->cur_exp;
23819     k=0; 
23820     while ( mp->kern[k]!=mp->cur_exp ) incr(k);
23821     if ( k==mp->nk ) {
23822       if ( mp->nk==max_tfm_int ) mp_fatal_error(mp, "too many TFM kerns");
23823       incr(mp->nk);
23824     }
23825     op_byte(mp->nl)=kern_flag+(k / 256);
23826     rem_byte(mp->nl)=qi((k % 256));
23827   }
23828   mp->lk_started=true;
23829 }
23830
23831 @ @d missing_extensible_punctuation(A) 
23832   { mp_missing_err(mp, (A));
23833 @.Missing `\char`\#'@>
23834   help1("I'm processing `extensible c: t,m,b,r'."); mp_back_error(mp);
23835   }
23836
23837 @<Define an extensible recipe@>=
23838
23839   if ( mp->ne==256 ) mp_fatal_error(mp, "too many extensible recipies");
23840   c=mp_get_code(mp); mp_set_tag(mp, c,ext_tag,mp->ne);
23841   if ( mp->cur_cmd!=colon ) missing_extensible_punctuation(":");
23842   ext_top(mp->ne)=qi(mp_get_code(mp));
23843   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23844   ext_mid(mp->ne)=qi(mp_get_code(mp));
23845   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23846   ext_bot(mp->ne)=qi(mp_get_code(mp));
23847   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23848   ext_rep(mp->ne)=qi(mp_get_code(mp));
23849   incr(mp->ne);
23850 }
23851
23852 @ The header could contain ASCII zeroes, so can't use |strdup|.
23853
23854 @<Store a list of header bytes@>=
23855 do {  
23856   if ( j>=mp->header_size ) {
23857     int l = mp->header_size + (mp->header_size >> 2);
23858     char *t = xmalloc(l,sizeof(char));
23859     memset(t,0,l); 
23860     memcpy(t,mp->header_byte,mp->header_size);
23861     xfree (mp->header_byte);
23862     mp->header_byte = t;
23863     mp->header_size = l;
23864   }
23865   mp->header_byte[j]=mp_get_code(mp); 
23866   incr(j); incr(mp->header_last);
23867 } while (mp->cur_cmd==comma)
23868
23869 @ @<Store a list of font dimensions@>=
23870 do {  
23871   if ( j>max_tfm_int ) mp_fatal_error(mp, "too many fontdimens");
23872   while ( j>mp->np ) { incr(mp->np); mp->param[mp->np]=0; };
23873   mp_get_x_next(mp); mp_scan_expression(mp);
23874   if ( mp->cur_type!=mp_known ){ 
23875     exp_err("Improper font parameter");
23876 @.Improper font parameter@>
23877     help1("I'm zeroing this one. Proceed, with fingers crossed.");
23878     mp_put_get_flush_error(mp, 0);
23879   }
23880   mp->param[j]=mp->cur_exp; incr(j);
23881 } while (mp->cur_cmd==comma)
23882
23883 @ OK: We've stored all the data that is needed for the \.{TFM} file.
23884 All that remains is to output it in the correct format.
23885
23886 An interesting problem needs to be solved in this connection, because
23887 the \.{TFM} format allows at most 256~widths, 16~heights, 16~depths,
23888 and 64~italic corrections. If the data has more distinct values than
23889 this, we want to meet the necessary restrictions by perturbing the
23890 given values as little as possible.
23891
23892 \MP\ solves this problem in two steps. First the values of a given
23893 kind (widths, heights, depths, or italic corrections) are sorted;
23894 then the list of sorted values is perturbed, if necessary.
23895
23896 The sorting operation is facilitated by having a special node of
23897 essentially infinite |value| at the end of the current list.
23898
23899 @<Initialize table entries...@>=
23900 value(inf_val)=fraction_four;
23901
23902 @ Straight linear insertion is good enough for sorting, since the lists
23903 are usually not terribly long. As we work on the data, the current list
23904 will start at |link(temp_head)| and end at |inf_val|; the nodes in this
23905 list will be in increasing order of their |value| fields.
23906
23907 Given such a list, the |sort_in| function takes a value and returns a pointer
23908 to where that value can be found in the list. The value is inserted in
23909 the proper place, if necessary.
23910
23911 At the time we need to do these operations, most of \MP's work has been
23912 completed, so we will have plenty of memory to play with. The value nodes
23913 that are allocated for sorting will never be returned to free storage.
23914
23915 @d clear_the_list link(temp_head)=inf_val
23916
23917 @c pointer mp_sort_in (MP mp,scaled v) {
23918   pointer p,q,r; /* list manipulation registers */
23919   p=temp_head;
23920   while (1) { 
23921     q=link(p);
23922     if ( v<=value(q) ) break;
23923     p=q;
23924   }
23925   if ( v<value(q) ) {
23926     r=mp_get_node(mp, value_node_size); value(r)=v; link(r)=q; link(p)=r;
23927   }
23928   return link(p);
23929 }
23930
23931 @ Now we come to the interesting part, where we reduce the list if necessary
23932 until it has the required size. The |min_cover| routine is basic to this
23933 process; it computes the minimum number~|m| such that the values of the
23934 current sorted list can be covered by |m|~intervals of width~|d|. It
23935 also sets the global value |perturbation| to the smallest value $d'>d$
23936 such that the covering found by this algorithm would be different.
23937
23938 In particular, |min_cover(0)| returns the number of distinct values in the
23939 current list and sets |perturbation| to the minimum distance between
23940 adjacent values.
23941
23942 @c integer mp_min_cover (MP mp,scaled d) {
23943   pointer p; /* runs through the current list */
23944   scaled l; /* the least element covered by the current interval */
23945   integer m; /* lower bound on the size of the minimum cover */
23946   m=0; p=link(temp_head); mp->perturbation=el_gordo;
23947   while ( p!=inf_val ){ 
23948     incr(m); l=value(p);
23949     do {  p=link(p); } while (value(p)<=l+d);
23950     if ( value(p)-l<mp->perturbation ) 
23951       mp->perturbation=value(p)-l;
23952   }
23953   return m;
23954 }
23955
23956 @ @<Glob...@>=
23957 scaled perturbation; /* quantity related to \.{TFM} rounding */
23958 integer excess; /* the list is this much too long */
23959
23960 @ The smallest |d| such that a given list can be covered with |m| intervals
23961 is determined by the |threshold| routine, which is sort of an inverse
23962 to |min_cover|. The idea is to increase the interval size rapidly until
23963 finding the range, then to go sequentially until the exact borderline has
23964 been discovered.
23965
23966 @c scaled mp_threshold (MP mp,integer m) {
23967   scaled d; /* lower bound on the smallest interval size */
23968   mp->excess=mp_min_cover(mp, 0)-m;
23969   if ( mp->excess<=0 ) {
23970     return 0;
23971   } else  { 
23972     do {  
23973       d=mp->perturbation;
23974     } while (mp_min_cover(mp, d+d)>m);
23975     while ( mp_min_cover(mp, d)>m ) 
23976       d=mp->perturbation;
23977     return d;
23978   }
23979 }
23980
23981 @ The |skimp| procedure reduces the current list to at most |m| entries,
23982 by changing values if necessary. It also sets |info(p):=k| if |value(p)|
23983 is the |k|th distinct value on the resulting list, and it sets
23984 |perturbation| to the maximum amount by which a |value| field has
23985 been changed. The size of the resulting list is returned as the
23986 value of |skimp|.
23987
23988 @c integer mp_skimp (MP mp,integer m) {
23989   scaled d; /* the size of intervals being coalesced */
23990   pointer p,q,r; /* list manipulation registers */
23991   scaled l; /* the least value in the current interval */
23992   scaled v; /* a compromise value */
23993   d=mp_threshold(mp, m); mp->perturbation=0;
23994   q=temp_head; m=0; p=link(temp_head);
23995   while ( p!=inf_val ) {
23996     incr(m); l=value(p); info(p)=m;
23997     if ( value(link(p))<=l+d ) {
23998       @<Replace an interval of values by its midpoint@>;
23999     }
24000     q=p; p=link(p);
24001   }
24002   return m;
24003 }
24004
24005 @ @<Replace an interval...@>=
24006
24007   do {  
24008     p=link(p); info(p)=m;
24009     decr(mp->excess); if ( mp->excess==0 ) d=0;
24010   } while (value(link(p))<=l+d);
24011   v=l+halfp(value(p)-l);
24012   if ( value(p)-v>mp->perturbation ) 
24013     mp->perturbation=value(p)-v;
24014   r=q;
24015   do {  
24016     r=link(r); value(r)=v;
24017   } while (r!=p);
24018   link(q)=p; /* remove duplicate values from the current list */
24019 }
24020
24021 @ A warning message is issued whenever something is perturbed by
24022 more than 1/16\thinspace pt.
24023
24024 @c void mp_tfm_warning (MP mp,small_number m) { 
24025   mp_print_nl(mp, "(some "); 
24026   mp_print(mp, mp->int_name[m]);
24027 @.some charwds...@>
24028 @.some chardps...@>
24029 @.some charhts...@>
24030 @.some charics...@>
24031   mp_print(mp, " values had to be adjusted by as much as ");
24032   mp_print_scaled(mp, mp->perturbation); mp_print(mp, "pt)");
24033 }
24034
24035 @ Here's an example of how we use these routines.
24036 The width data needs to be perturbed only if there are 256 distinct
24037 widths, but \MP\ must check for this case even though it is
24038 highly unusual.
24039
24040 An integer variable |k| will be defined when we use this code.
24041 The |dimen_head| array will contain pointers to the sorted
24042 lists of dimensions.
24043
24044 @<Massage the \.{TFM} widths@>=
24045 clear_the_list;
24046 for (k=mp->bc;k<=mp->ec;k++)  {
24047   if ( mp->char_exists[k] )
24048     mp->tfm_width[k]=mp_sort_in(mp, mp->tfm_width[k]);
24049 }
24050 mp->nw=mp_skimp(mp, 255)+1; mp->dimen_head[1]=link(temp_head);
24051 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_wd)
24052
24053 @ @<Glob...@>=
24054 pointer dimen_head[5]; /* lists of \.{TFM} dimensions */
24055
24056 @ Heights, depths, and italic corrections are different from widths
24057 not only because their list length is more severely restricted, but
24058 also because zero values do not need to be put into the lists.
24059
24060 @<Massage the \.{TFM} heights, depths, and italic corrections@>=
24061 clear_the_list;
24062 for (k=mp->bc;k<=mp->ec;k++) {
24063   if ( mp->char_exists[k] ) {
24064     if ( mp->tfm_height[k]==0 ) mp->tfm_height[k]=zero_val;
24065     else mp->tfm_height[k]=mp_sort_in(mp, mp->tfm_height[k]);
24066   }
24067 }
24068 mp->nh=mp_skimp(mp, 15)+1; mp->dimen_head[2]=link(temp_head);
24069 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ht);
24070 clear_the_list;
24071 for (k=mp->bc;k<=mp->ec;k++) {
24072   if ( mp->char_exists[k] ) {
24073     if ( mp->tfm_depth[k]==0 ) mp->tfm_depth[k]=zero_val;
24074     else mp->tfm_depth[k]=mp_sort_in(mp, mp->tfm_depth[k]);
24075   }
24076 }
24077 mp->nd=mp_skimp(mp, 15)+1; mp->dimen_head[3]=link(temp_head);
24078 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_dp);
24079 clear_the_list;
24080 for (k=mp->bc;k<=mp->ec;k++) {
24081   if ( mp->char_exists[k] ) {
24082     if ( mp->tfm_ital_corr[k]==0 ) mp->tfm_ital_corr[k]=zero_val;
24083     else mp->tfm_ital_corr[k]=mp_sort_in(mp, mp->tfm_ital_corr[k]);
24084   }
24085 }
24086 mp->ni=mp_skimp(mp, 63)+1; mp->dimen_head[4]=link(temp_head);
24087 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ic)
24088
24089 @ @<Initialize table entries...@>=
24090 value(zero_val)=0; info(zero_val)=0;
24091
24092 @ Bytes 5--8 of the header are set to the design size, unless the user has
24093 some crazy reason for specifying them differently.
24094
24095 Error messages are not allowed at the time this procedure is called,
24096 so a warning is printed instead.
24097
24098 The value of |max_tfm_dimen| is calculated so that
24099 $$\hbox{|make_scaled(16*max_tfm_dimen,internal[mp_design_size])|}
24100  < \\{three\_bytes}.$$
24101
24102 @d three_bytes 0100000000 /* $2^{24}$ */
24103
24104 @c 
24105 void mp_fix_design_size (MP mp) {
24106   scaled d; /* the design size */
24107   d=mp->internal[mp_design_size];
24108   if ( (d<unity)||(d>=fraction_half) ) {
24109     if ( d!=0 )
24110       mp_print_nl(mp, "(illegal design size has been changed to 128pt)");
24111 @.illegal design size...@>
24112     d=040000000; mp->internal[mp_design_size]=d;
24113   }
24114   if ( mp->header_byte[4]<0 ) if ( mp->header_byte[5]<0 )
24115     if ( mp->header_byte[6]<0 ) if ( mp->header_byte[7]<0 ) {
24116      mp->header_byte[4]=d / 04000000;
24117      mp->header_byte[5]=(d / 4096) % 256;
24118      mp->header_byte[6]=(d / 16) % 256;
24119      mp->header_byte[7]=(d % 16)*16;
24120   };
24121   mp->max_tfm_dimen=16*mp->internal[mp_design_size]-mp->internal[mp_design_size] / 010000000;
24122   if ( mp->max_tfm_dimen>=fraction_half ) mp->max_tfm_dimen=fraction_half-1;
24123 }
24124
24125 @ The |dimen_out| procedure computes a |fix_word| relative to the
24126 design size. If the data was out of range, it is corrected and the
24127 global variable |tfm_changed| is increased by~one.
24128
24129 @c integer mp_dimen_out (MP mp,scaled x) { 
24130   if ( abs(x)>mp->max_tfm_dimen ) {
24131     incr(mp->tfm_changed);
24132     if ( x>0 ) x=three_bytes-1; else x=1-three_bytes;
24133   } else {
24134     x=mp_make_scaled(mp, x*16,mp->internal[mp_design_size]);
24135   }
24136   return x;
24137 }
24138
24139 @ @<Glob...@>=
24140 scaled max_tfm_dimen; /* bound on widths, heights, kerns, etc. */
24141 integer tfm_changed; /* the number of data entries that were out of bounds */
24142
24143 @ If the user has not specified any of the first four header bytes,
24144 the |fix_check_sum| procedure replaces them by a ``check sum'' computed
24145 from the |tfm_width| data relative to the design size.
24146 @^check sum@>
24147
24148 @c void mp_fix_check_sum (MP mp) {
24149   eight_bits k; /* runs through character codes */
24150   eight_bits B1,B2,B3,B4; /* bytes of the check sum */
24151   integer x;  /* hash value used in check sum computation */
24152   if ( mp->header_byte[0]==0 && mp->header_byte[1]==0 &&
24153        mp->header_byte[2]==0 && mp->header_byte[3]==0 ) {
24154     @<Compute a check sum in |(b1,b2,b3,b4)|@>;
24155     mp->header_byte[0]=B1; mp->header_byte[1]=B2;
24156     mp->header_byte[2]=B3; mp->header_byte[3]=B4; 
24157     return;
24158   }
24159 }
24160
24161 @ @<Compute a check sum in |(b1,b2,b3,b4)|@>=
24162 B1=mp->bc; B2=mp->ec; B3=mp->bc; B4=mp->ec; mp->tfm_changed=0;
24163 for (k=mp->bc;k<=mp->ec;k++) { 
24164   if ( mp->char_exists[k] ) {
24165     x=mp_dimen_out(mp, value(mp->tfm_width[k]))+(k+4)*020000000; /* this is positive */
24166     B1=(B1+B1+x) % 255;
24167     B2=(B2+B2+x) % 253;
24168     B3=(B3+B3+x) % 251;
24169     B4=(B4+B4+x) % 247;
24170   }
24171 }
24172
24173 @ Finally we're ready to actually write the \.{TFM} information.
24174 Here are some utility routines for this purpose.
24175
24176 @d tfm_out(A) do { /* output one byte to |tfm_file| */
24177   unsigned char s=(A); 
24178   (mp->write_binary_file)(mp->tfm_file,(void *)&s,1); 
24179   } while (0)
24180
24181 @c void mp_tfm_two (MP mp,integer x) { /* output two bytes to |tfm_file| */
24182   tfm_out(x / 256); tfm_out(x % 256);
24183 }
24184 void mp_tfm_four (MP mp,integer x) { /* output four bytes to |tfm_file| */
24185   if ( x>=0 ) tfm_out(x / three_bytes);
24186   else { 
24187     x=x+010000000000; /* use two's complement for negative values */
24188     x=x+010000000000;
24189     tfm_out((x / three_bytes) + 128);
24190   };
24191   x=x % three_bytes; tfm_out(x / unity);
24192   x=x % unity; tfm_out(x / 0400);
24193   tfm_out(x % 0400);
24194 }
24195 void mp_tfm_qqqq (MP mp,four_quarters x) { /* output four quarterwords to |tfm_file| */
24196   tfm_out(qo(x.b0)); tfm_out(qo(x.b1)); 
24197   tfm_out(qo(x.b2)); tfm_out(qo(x.b3));
24198 }
24199
24200 @ @<Finish the \.{TFM} file@>=
24201 if ( mp->job_name==NULL ) mp_open_log_file(mp);
24202 mp_pack_job_name(mp, ".tfm");
24203 while ( ! mp_b_open_out(mp, &mp->tfm_file, mp_filetype_metrics) )
24204   mp_prompt_file_name(mp, "file name for font metrics",".tfm");
24205 mp->metric_file_name=xstrdup(mp->name_of_file);
24206 @<Output the subfile sizes and header bytes@>;
24207 @<Output the character information bytes, then
24208   output the dimensions themselves@>;
24209 @<Output the ligature/kern program@>;
24210 @<Output the extensible character recipes and the font metric parameters@>;
24211   if ( mp->internal[mp_tracing_stats]>0 )
24212   @<Log the subfile sizes of the \.{TFM} file@>;
24213 mp_print_nl(mp, "Font metrics written on "); 
24214 mp_print(mp, mp->metric_file_name); mp_print_char(mp, '.');
24215 @.Font metrics written...@>
24216 (mp->close_file)(mp->tfm_file)
24217
24218 @ Integer variables |lh|, |k|, and |lk_offset| will be defined when we use
24219 this code.
24220
24221 @<Output the subfile sizes and header bytes@>=
24222 k=mp->header_last;
24223 LH=(k+3) / 4; /* this is the number of header words */
24224 if ( mp->bc>mp->ec ) mp->bc=1; /* if there are no characters, |ec=0| and |bc=1| */
24225 @<Compute the ligature/kern program offset and implant the
24226   left boundary label@>;
24227 mp_tfm_two(mp,6+LH+(mp->ec-mp->bc+1)+mp->nw+mp->nh+mp->nd+mp->ni+mp->nl
24228      +lk_offset+mp->nk+mp->ne+mp->np);
24229   /* this is the total number of file words that will be output */
24230 mp_tfm_two(mp, LH); mp_tfm_two(mp, mp->bc); mp_tfm_two(mp, mp->ec); 
24231 mp_tfm_two(mp, mp->nw); mp_tfm_two(mp, mp->nh);
24232 mp_tfm_two(mp, mp->nd); mp_tfm_two(mp, mp->ni); mp_tfm_two(mp, mp->nl+lk_offset); 
24233 mp_tfm_two(mp, mp->nk); mp_tfm_two(mp, mp->ne);
24234 mp_tfm_two(mp, mp->np);
24235 for (k=0;k< 4*LH;k++)   { 
24236   tfm_out(mp->header_byte[k]);
24237 }
24238
24239 @ @<Output the character information bytes...@>=
24240 for (k=mp->bc;k<=mp->ec;k++) {
24241   if ( ! mp->char_exists[k] ) {
24242     mp_tfm_four(mp, 0);
24243   } else { 
24244     tfm_out(info(mp->tfm_width[k])); /* the width index */
24245     tfm_out((info(mp->tfm_height[k]))*16+info(mp->tfm_depth[k]));
24246     tfm_out((info(mp->tfm_ital_corr[k]))*4+mp->char_tag[k]);
24247     tfm_out(mp->char_remainder[k]);
24248   };
24249 }
24250 mp->tfm_changed=0;
24251 for (k=1;k<=4;k++) { 
24252   mp_tfm_four(mp, 0); p=mp->dimen_head[k];
24253   while ( p!=inf_val ) {
24254     mp_tfm_four(mp, mp_dimen_out(mp, value(p))); p=link(p);
24255   }
24256 }
24257
24258
24259 @ We need to output special instructions at the beginning of the
24260 |lig_kern| array in order to specify the right boundary character
24261 and/or to handle starting addresses that exceed 255. The |label_loc|
24262 and |label_char| arrays have been set up to record all the
24263 starting addresses; we have $-1=|label_loc|[0]<|label_loc|[1]\le\cdots
24264 \le|label_loc|[|label_ptr]|$.
24265
24266 @<Compute the ligature/kern program offset...@>=
24267 mp->bchar=mp_round_unscaled(mp, mp->internal[mp_boundary_char]);
24268 if ((mp->bchar<0)||(mp->bchar>255))
24269   { mp->bchar=-1; mp->lk_started=false; lk_offset=0; }
24270 else { mp->lk_started=true; lk_offset=1; };
24271 @<Find the minimum |lk_offset| and adjust all remainders@>;
24272 if ( mp->bch_label<undefined_label )
24273   { skip_byte(mp->nl)=qi(255); next_char(mp->nl)=qi(0);
24274   op_byte(mp->nl)=qi(((mp->bch_label+lk_offset)/ 256));
24275   rem_byte(mp->nl)=qi(((mp->bch_label+lk_offset)% 256));
24276   incr(mp->nl); /* possibly |nl=lig_table_size+1| */
24277   }
24278
24279 @ @<Find the minimum |lk_offset|...@>=
24280 k=mp->label_ptr; /* pointer to the largest unallocated label */
24281 if ( mp->label_loc[k]+lk_offset>255 ) {
24282   lk_offset=0; mp->lk_started=false; /* location 0 can do double duty */
24283   do {  
24284     mp->char_remainder[mp->label_char[k]]=lk_offset;
24285     while ( mp->label_loc[k-1]==mp->label_loc[k] ) {
24286        decr(k); mp->char_remainder[mp->label_char[k]]=lk_offset;
24287     }
24288     incr(lk_offset); decr(k);
24289   } while (! (lk_offset+mp->label_loc[k]<256));
24290     /* N.B.: |lk_offset=256| satisfies this when |k=0| */
24291 };
24292 if ( lk_offset>0 ) {
24293   while ( k>0 ) {
24294     mp->char_remainder[mp->label_char[k]]
24295      =mp->char_remainder[mp->label_char[k]]+lk_offset;
24296     decr(k);
24297   }
24298 }
24299
24300 @ @<Output the ligature/kern program@>=
24301 for (k=0;k<= 255;k++ ) {
24302   if ( mp->skip_table[k]<undefined_label ) {
24303      mp_print_nl(mp, "(local label "); mp_print_int(mp, k); mp_print(mp, ":: was missing)");
24304 @.local label l:: was missing@>
24305     cancel_skips(mp->skip_table[k]);
24306   }
24307 }
24308 if ( mp->lk_started ) { /* |lk_offset=1| for the special |bchar| */
24309   tfm_out(255); tfm_out(mp->bchar); mp_tfm_two(mp, 0);
24310 } else {
24311   for (k=1;k<=lk_offset;k++) {/* output the redirection specs */
24312     mp->ll=mp->label_loc[mp->label_ptr];
24313     if ( mp->bchar<0 ) { tfm_out(254); tfm_out(0);   }
24314     else { tfm_out(255); tfm_out(mp->bchar);   };
24315     mp_tfm_two(mp, mp->ll+lk_offset);
24316     do {  
24317       decr(mp->label_ptr);
24318     } while (! (mp->label_loc[mp->label_ptr]<mp->ll));
24319   }
24320 }
24321 for (k=0;k<=mp->nl-1;k++) mp_tfm_qqqq(mp, mp->lig_kern[k]);
24322 for (k=0;k<=mp->nk-1;k++) mp_tfm_four(mp, mp_dimen_out(mp, mp->kern[k]))
24323
24324 @ @<Output the extensible character recipes...@>=
24325 for (k=0;k<=mp->ne-1;k++) 
24326   mp_tfm_qqqq(mp, mp->exten[k]);
24327 for (k=1;k<=mp->np;k++) {
24328   if ( k==1 ) {
24329     if ( abs(mp->param[1])<fraction_half ) {
24330       mp_tfm_four(mp, mp->param[1]*16);
24331     } else  { 
24332       incr(mp->tfm_changed);
24333       if ( mp->param[1]>0 ) mp_tfm_four(mp, el_gordo);
24334       else mp_tfm_four(mp, -el_gordo);
24335     }
24336   } else {
24337     mp_tfm_four(mp, mp_dimen_out(mp, mp->param[k]));
24338   }
24339 }
24340 if ( mp->tfm_changed>0 )  { 
24341   if ( mp->tfm_changed==1 ) mp_print_nl(mp, "(a font metric dimension");
24342 @.a font metric dimension...@>
24343   else  { 
24344     mp_print_nl(mp, "("); mp_print_int(mp, mp->tfm_changed);
24345 @.font metric dimensions...@>
24346     mp_print(mp, " font metric dimensions");
24347   }
24348   mp_print(mp, " had to be decreased)");
24349 }
24350
24351 @ @<Log the subfile sizes of the \.{TFM} file@>=
24352
24353   char s[200];
24354   wlog_ln(" ");
24355   if ( mp->bch_label<undefined_label ) decr(mp->nl);
24356   snprintf(s,128,"(You used %iw,%ih,%id,%ii,%il,%ik,%ie,%ip metric file positions)",
24357                  mp->nw, mp->nh, mp->nd, mp->ni, mp->nl, mp->nk, mp->ne,mp->np);
24358   wlog_ln(s);
24359 }
24360
24361 @* \[43] Reading font metric data.
24362
24363 \MP\ isn't a typesetting program but it does need to find the bounding box
24364 of a sequence of typeset characters.  Thus it needs to read \.{TFM} files as
24365 well as write them.
24366
24367 @<Glob...@>=
24368 void * tfm_infile;
24369
24370 @ All the width, height, and depth information is stored in an array called
24371 |font_info|.  This array is allocated sequentially and each font is stored
24372 as a series of |char_info| words followed by the width, height, and depth
24373 tables.  Since |font_name| entries are permanent, their |str_ref| values are
24374 set to |max_str_ref|.
24375
24376 @<Types...@>=
24377 typedef unsigned int font_number; /* |0..font_max| */
24378
24379 @ The |font_info| array is indexed via a group directory arrays.
24380 For example, the |char_info| data for character~|c| in font~|f| will be
24381 in |font_info[char_base[f]+c].qqqq|.
24382
24383 @<Glob...@>=
24384 font_number font_max; /* maximum font number for included text fonts */
24385 size_t      font_mem_size; /* number of words for \.{TFM} information for text fonts */
24386 memory_word *font_info; /* height, width, and depth data */
24387 char        **font_enc_name; /* encoding names, if any */
24388 boolean     *font_ps_name_fixed; /* are the postscript names fixed already?  */
24389 int         next_fmem; /* next unused entry in |font_info| */
24390 font_number last_fnum; /* last font number used so far */
24391 scaled      *font_dsize;  /* 16 times the ``design'' size in \ps\ points */
24392 char        **font_name;  /* name as specified in the \&{infont} command */
24393 char        **font_ps_name;  /* PostScript name for use when |internal[mp_prologues]>0| */
24394 font_number last_ps_fnum; /* last valid |font_ps_name| index */
24395 eight_bits  *font_bc;
24396 eight_bits  *font_ec;  /* first and last character code */
24397 int         *char_base;  /* base address for |char_info| */
24398 int         *width_base; /* index for zeroth character width */
24399 int         *height_base; /* index for zeroth character height */
24400 int         *depth_base; /* index for zeroth character depth */
24401 pointer     *font_sizes;
24402
24403 @ @<Allocate or initialize ...@>=
24404 mp->font_mem_size = 10000; 
24405 mp->font_info = xmalloc ((mp->font_mem_size+1),sizeof(memory_word));
24406 memset (mp->font_info,0,sizeof(memory_word)*(mp->font_mem_size+1));
24407 mp->font_enc_name = NULL;
24408 mp->font_ps_name_fixed = NULL;
24409 mp->font_dsize = NULL;
24410 mp->font_name = NULL;
24411 mp->font_ps_name = NULL;
24412 mp->font_bc = NULL;
24413 mp->font_ec = NULL;
24414 mp->last_fnum = null_font;
24415 mp->char_base = NULL;
24416 mp->width_base = NULL;
24417 mp->height_base = NULL;
24418 mp->depth_base = NULL;
24419 mp->font_sizes = null;
24420
24421 @ @<Dealloc variables@>=
24422 for (k=1;k<=(int)mp->last_fnum;k++) {
24423   xfree(mp->font_enc_name[k]);
24424   xfree(mp->font_name[k]);
24425   xfree(mp->font_ps_name[k]);
24426 }
24427 xfree(mp->font_info);
24428 xfree(mp->font_enc_name);
24429 xfree(mp->font_ps_name_fixed);
24430 xfree(mp->font_dsize);
24431 xfree(mp->font_name);
24432 xfree(mp->font_ps_name);
24433 xfree(mp->font_bc);
24434 xfree(mp->font_ec);
24435 xfree(mp->char_base);
24436 xfree(mp->width_base);
24437 xfree(mp->height_base);
24438 xfree(mp->depth_base);
24439 xfree(mp->font_sizes);
24440
24441
24442 @c 
24443 void mp_reallocate_fonts (MP mp, font_number l) {
24444   font_number f;
24445   XREALLOC(mp->font_enc_name,      l, char *);
24446   XREALLOC(mp->font_ps_name_fixed, l, boolean);
24447   XREALLOC(mp->font_dsize,         l, scaled);
24448   XREALLOC(mp->font_name,          l, char *);
24449   XREALLOC(mp->font_ps_name,       l, char *);
24450   XREALLOC(mp->font_bc,            l, eight_bits);
24451   XREALLOC(mp->font_ec,            l, eight_bits);
24452   XREALLOC(mp->char_base,          l, int);
24453   XREALLOC(mp->width_base,         l, int);
24454   XREALLOC(mp->height_base,        l, int);
24455   XREALLOC(mp->depth_base,         l, int);
24456   XREALLOC(mp->font_sizes,         l, pointer);
24457   for (f=(mp->last_fnum+1);f<=l;f++) {
24458     mp->font_enc_name[f]=NULL;
24459     mp->font_ps_name_fixed[f] = false;
24460     mp->font_name[f]=NULL;
24461     mp->font_ps_name[f]=NULL;
24462     mp->font_sizes[f]=null;
24463   }
24464   mp->font_max = l;
24465 }
24466
24467 @ @<Declare |mp_reallocate| functions@>=
24468 void mp_reallocate_fonts (MP mp, font_number l);
24469
24470
24471 @ A |null_font| containing no characters is useful for error recovery.  Its
24472 |font_name| entry starts out empty but is reset each time an erroneous font is
24473 found.  This helps to cut down on the number of duplicate error messages without
24474 wasting a lot of space.
24475
24476 @d null_font 0 /* the |font_number| for an empty font */
24477
24478 @<Set initial...@>=
24479 mp->font_dsize[null_font]=0;
24480 mp->font_bc[null_font]=1;
24481 mp->font_ec[null_font]=0;
24482 mp->char_base[null_font]=0;
24483 mp->width_base[null_font]=0;
24484 mp->height_base[null_font]=0;
24485 mp->depth_base[null_font]=0;
24486 mp->next_fmem=0;
24487 mp->last_fnum=null_font;
24488 mp->last_ps_fnum=null_font;
24489 mp->font_name[null_font]="nullfont";
24490 mp->font_ps_name[null_font]="";
24491 mp->font_ps_name_fixed[null_font] = false;
24492 mp->font_enc_name[null_font]=NULL;
24493 mp->font_sizes[null_font]=null;
24494
24495 @ Each |char_info| word is of type |four_quarters|.  The |b0| field contains
24496 the |width index|; the |b1| field contains the height
24497 index; the |b2| fields contains the depth index, and the |b3| field used only
24498 for temporary storage. (It is used to keep track of which characters occur in
24499 an edge structure that is being shipped out.)
24500 The corresponding words in the width, height, and depth tables are stored as
24501 |scaled| values in units of \ps\ points.
24502
24503 With the macros below, the |char_info| word for character~|c| in font~|f| is
24504 |char_info(f)(c)| and the width is
24505 $$\hbox{|char_width(f)(char_info(f)(c)).sc|.}$$
24506
24507 @d char_info_end(A) (A)].qqqq
24508 @d char_info(A) mp->font_info[mp->char_base[(A)]+char_info_end
24509 @d char_width_end(A) (A).b0].sc
24510 @d char_width(A) mp->font_info[mp->width_base[(A)]+char_width_end
24511 @d char_height_end(A) (A).b1].sc
24512 @d char_height(A) mp->font_info[mp->height_base[(A)]+char_height_end
24513 @d char_depth_end(A) (A).b2].sc
24514 @d char_depth(A) mp->font_info[mp->depth_base[(A)]+char_depth_end
24515 @d ichar_exists(A) ((A).b0>0)
24516
24517 @ The |font_ps_name| for a built-in font should be what PostScript expects.
24518 A preliminary name is obtained here from the \.{TFM} name as given in the
24519 |fname| argument.  This gets updated later from an external table if necessary.
24520
24521 @<Declare text measuring subroutines@>=
24522 @<Declare subroutines for parsing file names@>;
24523 font_number mp_read_font_info (MP mp, char *fname) {
24524   boolean file_opened; /* has |tfm_infile| been opened? */
24525   font_number n; /* the number to return */
24526   halfword lf,tfm_lh,bc,ec,nw,nh,nd; /* subfile size parameters */
24527   size_t whd_size; /* words needed for heights, widths, and depths */
24528   int i,ii; /* |font_info| indices */
24529   int jj; /* counts bytes to be ignored */
24530   scaled z; /* used to compute the design size */
24531   fraction d;
24532   /* height, width, or depth as a fraction of design size times $2^{-8}$ */
24533   eight_bits h_and_d; /* height and depth indices being unpacked */
24534   unsigned char tfbyte; /* a byte read from the file */
24535   n=null_font;
24536   @<Open |tfm_infile| for input@>;
24537   @<Read data from |tfm_infile|; if there is no room, say so and |goto done|;
24538     otherwise |goto bad_tfm| or |goto done| as appropriate@>;
24539 BAD_TFM:
24540   @<Complain that the \.{TFM} file is bad@>;
24541 DONE:
24542   if ( file_opened ) (mp->close_file)(mp->tfm_infile);
24543   if ( n!=null_font ) { 
24544     mp->font_ps_name[n]=mp_xstrdup(mp,fname);
24545     mp->font_name[n]=mp_xstrdup(mp,fname);
24546   }
24547   return n;
24548 }
24549
24550 @ \MP\ doesn't bother to check the entire \.{TFM} file for errors or explain
24551 precisely what is wrong if it does find a problem.  Programs called \.{TFtoPL}
24552 @.TFtoPL@> @.PLtoTF@>
24553 and \.{PLtoTF} can be used to debug \.{TFM} files.
24554
24555 @<Complain that the \.{TFM} file is bad@>=
24556 print_err("Font ");
24557 mp_print(mp, fname);
24558 if ( file_opened ) mp_print(mp, " not usable: TFM file is bad");
24559 else mp_print(mp, " not usable: TFM file not found");
24560 help3("I wasn't able to read the size data for this font so this")
24561   ("`infont' operation won't produce anything. If the font name")
24562   ("is right, you might ask an expert to make a TFM file");
24563 if ( file_opened )
24564   mp->help_line[0]="is right, try asking an expert to fix the TFM file";
24565 mp_error(mp)
24566
24567 @ @<Read data from |tfm_infile|; if there is no room, say so...@>=
24568 @<Read the \.{TFM} size fields@>;
24569 @<Use the size fields to allocate space in |font_info|@>;
24570 @<Read the \.{TFM} header@>;
24571 @<Read the character data and the width, height, and depth tables and
24572   |goto done|@>
24573
24574 @ A bad \.{TFM} file can be shorter than it claims to be.  The code given here
24575 might try to read past the end of the file if this happens.  Changes will be
24576 needed if it causes a system error to refer to |tfm_infile^| or call
24577 |get_tfm_infile| when |eof(tfm_infile)| is true.  For example, the definition
24578 @^system dependencies@>
24579 of |tfget| could be changed to
24580 ``|begin get(tfm_infile); if eof(tfm_infile) then goto bad_tfm; end|.''
24581
24582 @d tfget do { 
24583   size_t wanted=1; 
24584   void *tfbyte_ptr = &tfbyte;
24585   (mp->read_binary_file)(mp->tfm_infile,&tfbyte_ptr,&wanted); 
24586   if (wanted==0) goto BAD_TFM; 
24587 } while (0)
24588 @d read_two(A) { (A)=tfbyte;
24589   if ( (A)>127 ) goto BAD_TFM;
24590   tfget; (A)=(A)*0400+tfbyte;
24591 }
24592 @d tf_ignore(A) { for (jj=(A);jj>=1;jj--) tfget; }
24593
24594 @<Read the \.{TFM} size fields@>=
24595 tfget; read_two(lf);
24596 tfget; read_two(tfm_lh);
24597 tfget; read_two(bc);
24598 tfget; read_two(ec);
24599 if ( (bc>1+ec)||(ec>255) ) goto BAD_TFM;
24600 tfget; read_two(nw);
24601 tfget; read_two(nh);
24602 tfget; read_two(nd);
24603 whd_size=(ec+1-bc)+nw+nh+nd;
24604 if ( lf<(int)(6+tfm_lh+whd_size) ) goto BAD_TFM;
24605 tf_ignore(10)
24606
24607 @ Offsets are added to |char_base[n]| and |width_base[n]| so that is not
24608 necessary to apply the |so|  and |qo| macros when looking up the width of a
24609 character in the string pool.  In order to ensure nonnegative |char_base|
24610 values when |bc>0|, it may be necessary to reserve a few unused |font_info|
24611 elements.
24612
24613 @<Use the size fields to allocate space in |font_info|@>=
24614 if ( mp->next_fmem<bc) mp->next_fmem=bc;  /* ensure nonnegative |char_base| */
24615 if (mp->last_fnum==mp->font_max)
24616   mp_reallocate_fonts(mp,(mp->font_max+(mp->font_max>>2)));
24617 while (mp->next_fmem+whd_size>=mp->font_mem_size) {
24618   size_t l = mp->font_mem_size+(mp->font_mem_size>>2);
24619   memory_word *font_info;
24620   font_info = xmalloc ((l+1),sizeof(memory_word));
24621   memset (font_info,0,sizeof(memory_word)*(l+1));
24622   memcpy (font_info,mp->font_info,sizeof(memory_word)*(mp->font_mem_size+1));
24623   xfree(mp->font_info);
24624   mp->font_info = font_info;
24625   mp->font_mem_size = l;
24626 }
24627 incr(mp->last_fnum);
24628 n=mp->last_fnum;
24629 mp->font_bc[n]=bc;
24630 mp->font_ec[n]=ec;
24631 mp->char_base[n]=mp->next_fmem-bc;
24632 mp->width_base[n]=mp->next_fmem+ec-bc+1;
24633 mp->height_base[n]=mp->width_base[n]+nw;
24634 mp->depth_base[n]=mp->height_base[n]+nh;
24635 mp->next_fmem=mp->next_fmem+whd_size;
24636
24637
24638 @ @<Read the \.{TFM} header@>=
24639 if ( tfm_lh<2 ) goto BAD_TFM;
24640 tf_ignore(4);
24641 tfget; read_two(z);
24642 tfget; z=z*0400+tfbyte;
24643 tfget; z=z*0400+tfbyte; /* now |z| is 16 times the design size */
24644 mp->font_dsize[n]=mp_take_fraction(mp, z,267432584);
24645   /* times ${72\over72.27}2^{28}$ to convert from \TeX\ points */
24646 tf_ignore(4*(tfm_lh-2))
24647
24648 @ @<Read the character data and the width, height, and depth tables...@>=
24649 ii=mp->width_base[n];
24650 i=mp->char_base[n]+bc;
24651 while ( i<ii ) { 
24652   tfget; mp->font_info[i].qqqq.b0=qi(tfbyte);
24653   tfget; h_and_d=tfbyte;
24654   mp->font_info[i].qqqq.b1=h_and_d / 16;
24655   mp->font_info[i].qqqq.b2=h_and_d % 16;
24656   tfget; tfget;
24657   incr(i);
24658 }
24659 while ( i<mp->next_fmem ) {
24660   @<Read a four byte dimension, scale it by the design size, store it in
24661     |font_info[i]|, and increment |i|@>;
24662 }
24663 goto DONE
24664
24665 @ The raw dimension read into |d| should have magnitude at most $2^{24}$ when
24666 interpreted as an integer, and this includes a scale factor of $2^{20}$.  Thus
24667 we can multiply it by sixteen and think of it as a |fraction| that has been
24668 divided by sixteen.  This cancels the extra scale factor contained in
24669 |font_dsize[n|.
24670
24671 @<Read a four byte dimension, scale it by the design size, store it in...@>=
24672
24673 tfget; d=tfbyte;
24674 if ( d>=0200 ) d=d-0400;
24675 tfget; d=d*0400+tfbyte;
24676 tfget; d=d*0400+tfbyte;
24677 tfget; d=d*0400+tfbyte;
24678 mp->font_info[i].sc=mp_take_fraction(mp, d*16,mp->font_dsize[n]);
24679 incr(i);
24680 }
24681
24682 @ This function does no longer use the file name parser, because |fname| is
24683 a C string already.
24684 @<Open |tfm_infile| for input@>=
24685 file_opened=false;
24686 mp_ptr_scan_file(mp, fname);
24687 if ( strlen(mp->cur_area)==0 ) { xfree(mp->cur_area); }
24688 if ( strlen(mp->cur_ext)==0 )  { xfree(mp->cur_ext); mp->cur_ext=xstrdup(".tfm"); }
24689 pack_cur_name;
24690 mp->tfm_infile = (mp->open_file)( mp->name_of_file, "rb",mp_filetype_metrics);
24691 if ( !mp->tfm_infile  ) goto BAD_TFM;
24692 file_opened=true
24693
24694 @ When we have a font name and we don't know whether it has been loaded yet,
24695 we scan the |font_name| array before calling |read_font_info|.
24696
24697 @<Declare text measuring subroutines@>=
24698 font_number mp_find_font (MP mp, char *f) {
24699   font_number n;
24700   for (n=0;n<=mp->last_fnum;n++) {
24701     if (mp_xstrcmp(f,mp->font_name[n])==0 ) {
24702       mp_xfree(f);
24703       return n;
24704     }
24705   }
24706   n = mp_read_font_info(mp, f);
24707   mp_xfree(f);
24708   return n;
24709 }
24710
24711 @ One simple application of |find_font| is the implementation of the |font_size|
24712 operator that gets the design size for a given font name.
24713
24714 @<Find the design size of the font whose name is |cur_exp|@>=
24715 mp_flush_cur_exp(mp, (mp->font_dsize[mp_find_font(mp, str(mp->cur_exp))]+8) / 16)
24716
24717 @ If we discover that the font doesn't have a requested character, we omit it
24718 from the bounding box computation and expect the \ps\ interpreter to drop it.
24719 This routine issues a warning message if the user has asked for it.
24720
24721 @<Declare text measuring subroutines@>=
24722 void mp_lost_warning (MP mp,font_number f, pool_pointer k) { 
24723   if ( mp->internal[mp_tracing_lost_chars]>0 ) { 
24724     mp_begin_diagnostic(mp);
24725     if ( mp->selector==log_only ) incr(mp->selector);
24726     mp_print_nl(mp, "Missing character: There is no ");
24727 @.Missing character@>
24728     mp_print_str(mp, mp->str_pool[k]); 
24729     mp_print(mp, " in font ");
24730     mp_print(mp, mp->font_name[f]); mp_print_char(mp, '!'); 
24731     mp_end_diagnostic(mp, false);
24732   }
24733 }
24734
24735 @ The whole purpose of saving the height, width, and depth information is to be
24736 able to find the bounding box of an item of text in an edge structure.  The
24737 |set_text_box| procedure takes a text node and adds this information.
24738
24739 @<Declare text measuring subroutines@>=
24740 void mp_set_text_box (MP mp,pointer p) {
24741   font_number f; /* |font_n(p)| */
24742   ASCII_code bc,ec; /* range of valid characters for font |f| */
24743   pool_pointer k,kk; /* current character and character to stop at */
24744   four_quarters cc; /* the |char_info| for the current character */
24745   scaled h,d; /* dimensions of the current character */
24746   width_val(p)=0;
24747   height_val(p)=-el_gordo;
24748   depth_val(p)=-el_gordo;
24749   f=font_n(p);
24750   bc=mp->font_bc[f];
24751   ec=mp->font_ec[f];
24752   kk=str_stop(text_p(p));
24753   k=mp->str_start[text_p(p)];
24754   while ( k<kk ) {
24755     @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>;
24756   }
24757   @<Set the height and depth to zero if the bounding box is empty@>;
24758 }
24759
24760 @ @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>=
24761
24762   if ( (mp->str_pool[k]<bc)||(mp->str_pool[k]>ec) ) {
24763     mp_lost_warning(mp, f,k);
24764   } else { 
24765     cc=char_info(f)(mp->str_pool[k]);
24766     if ( ! ichar_exists(cc) ) {
24767       mp_lost_warning(mp, f,k);
24768     } else { 
24769       width_val(p)=width_val(p)+char_width(f)(cc);
24770       h=char_height(f)(cc);
24771       d=char_depth(f)(cc);
24772       if ( h>height_val(p) ) height_val(p)=h;
24773       if ( d>depth_val(p) ) depth_val(p)=d;
24774     }
24775   }
24776   incr(k);
24777 }
24778
24779 @ Let's hope modern compilers do comparisons correctly when the difference would
24780 overflow.
24781
24782 @<Set the height and depth to zero if the bounding box is empty@>=
24783 if ( height_val(p)<-depth_val(p) ) { 
24784   height_val(p)=0;
24785   depth_val(p)=0;
24786 }
24787
24788 @ The new primitives fontmapfile and fontmapline.
24789
24790 @<Declare action procedures for use by |do_statement|@>=
24791 void mp_do_mapfile (MP mp) ;
24792 void mp_do_mapline (MP mp) ;
24793
24794 @ @c void mp_do_mapfile (MP mp) { 
24795   mp_get_x_next(mp); mp_scan_expression(mp);
24796   if ( mp->cur_type!=mp_string_type ) {
24797     @<Complain about improper map operation@>;
24798   } else {
24799     mp_map_file(mp,mp->cur_exp);
24800   }
24801 }
24802 void mp_do_mapline (MP mp) { 
24803   mp_get_x_next(mp); mp_scan_expression(mp);
24804   if ( mp->cur_type!=mp_string_type ) {
24805      @<Complain about improper map operation@>;
24806   } else { 
24807      mp_map_line(mp,mp->cur_exp);
24808   }
24809 }
24810
24811 @ @<Complain about improper map operation@>=
24812
24813   exp_err("Unsuitable expression");
24814   help1("Only known strings can be map files or map lines.");
24815   mp_put_get_error(mp);
24816 }
24817
24818 @ To print |scaled| value to PDF output we need some subroutines to ensure
24819 accurary.
24820
24821 @d max_integer   0x7FFFFFFF /* $2^{31}-1$ */
24822
24823 @<Glob...@>=
24824 scaled one_bp; /* scaled value corresponds to 1bp */
24825 scaled one_hundred_bp; /* scaled value corresponds to 100bp */
24826 scaled one_hundred_inch; /* scaled value corresponds to 100in */
24827 integer ten_pow[10]; /* $10^0..10^9$ */
24828 integer scaled_out; /* amount of |scaled| that was taken out in |divide_scaled| */
24829
24830 @ @<Set init...@>=
24831 mp->one_bp = 65782; /* 65781.76 */
24832 mp->one_hundred_bp = 6578176;
24833 mp->one_hundred_inch = 473628672;
24834 mp->ten_pow[0] = 1;
24835 for (i = 1;i<= 9; i++ ) {
24836   mp->ten_pow[i] = 10*mp->ten_pow[i - 1];
24837 }
24838
24839 @ The following function divides |s| by |m|. |dd| is number of decimal digits.
24840
24841 @c scaled mp_divide_scaled (MP mp,scaled s, scaled m, integer  dd) {
24842   scaled q,r;
24843   integer sign,i;
24844   sign = 1;
24845   if ( s < 0 ) { sign = -sign; s = -s; }
24846   if ( m < 0 ) { sign = -sign; m = -m; }
24847   if ( m == 0 )
24848     mp_confusion(mp, "arithmetic: divided by zero");
24849   else if ( m >= (max_integer / 10) )
24850     mp_confusion(mp, "arithmetic: number too big");
24851   q = s / m;
24852   r = s % m;
24853   for (i = 1;i<=dd;i++) {
24854     q = 10*q + (10*r) / m;
24855     r = (10*r) % m;
24856   }
24857   if ( 2*r >= m ) { incr(q); r = r - m; }
24858   mp->scaled_out = sign*(s - (r / mp->ten_pow[dd]));
24859   return (sign*q);
24860 }
24861
24862 @* \[44] Shipping pictures out.
24863 The |ship_out| procedure, to be described below, is given a pointer to
24864 an edge structure. Its mission is to output a file containing the \ps\
24865 description of an edge structure.
24866
24867 @ Each time an edge structure is shipped out we write a new \ps\ output
24868 file named according to the current \&{charcode}.
24869 @:char_code_}{\&{charcode} primitive@>
24870
24871 This is the only backend function that remains in the main |mpost.w| file. 
24872 There are just too many variable accesses needed for status reporting 
24873 etcetera to make it worthwile to move the code to |psout.w|.
24874
24875 @<Internal library declarations@>=
24876 void mp_open_output_file (MP mp) ;
24877
24878 @ @c 
24879 char *mp_set_output_file_name (MP mp, integer c) {
24880   char *ss = NULL; /* filename extension proposal */  
24881   int old_setting; /* previous |selector| setting */
24882   pool_pointer i; /*  indexes into |filename_template|  */
24883   integer cc; /* a temporary integer for template building  */
24884   integer f,g=0; /* field widths */
24885   if ( mp->job_name==NULL ) mp_open_log_file(mp);
24886   if ( mp->filename_template==0 ) {
24887     char *s; /* a file extension derived from |c| */
24888     if ( c<0 ) 
24889       s=xstrdup(".ps");
24890     else 
24891       @<Use |c| to compute the file extension |s|@>;
24892     mp_pack_job_name(mp, s);
24893     ss = s ;
24894   } else { /* initializations */
24895     str_number s, n; /* a file extension derived from |c| */
24896     old_setting=mp->selector; 
24897     mp->selector=new_string;
24898     f = 0;
24899     i = mp->str_start[mp->filename_template];
24900     n = rts(""); /* initialize */
24901     while ( i<str_stop(mp->filename_template) ) {
24902        if ( mp->str_pool[i]=='%' ) {
24903       CONTINUE:
24904         incr(i);
24905         if ( i<str_stop(mp->filename_template) ) {
24906           if ( mp->str_pool[i]=='j' ) {
24907             mp_print(mp, mp->job_name);
24908           } else if ( mp->str_pool[i]=='d' ) {
24909              cc= mp_round_unscaled(mp, mp->internal[mp_day]);
24910              print_with_leading_zeroes(cc);
24911           } else if ( mp->str_pool[i]=='m' ) {
24912              cc= mp_round_unscaled(mp, mp->internal[mp_month]);
24913              print_with_leading_zeroes(cc);
24914           } else if ( mp->str_pool[i]=='y' ) {
24915              cc= mp_round_unscaled(mp, mp->internal[mp_year]);
24916              print_with_leading_zeroes(cc);
24917           } else if ( mp->str_pool[i]=='H' ) {
24918              cc= mp_round_unscaled(mp, mp->internal[mp_time]) / 60;
24919              print_with_leading_zeroes(cc);
24920           }  else if ( mp->str_pool[i]=='M' ) {
24921              cc= mp_round_unscaled(mp, mp->internal[mp_time]) % 60;
24922              print_with_leading_zeroes(cc);
24923           } else if ( mp->str_pool[i]=='c' ) {
24924             if ( c<0 ) mp_print(mp, "ps");
24925             else print_with_leading_zeroes(c);
24926           } else if ( (mp->str_pool[i]>='0') && 
24927                       (mp->str_pool[i]<='9') ) {
24928             if ( (f<10)  )
24929               f = (f*10) + mp->str_pool[i]-'0';
24930             goto CONTINUE;
24931           } else {
24932             mp_print_str(mp, mp->str_pool[i]);
24933           }
24934         }
24935       } else {
24936         if ( mp->str_pool[i]=='.' )
24937           if (length(n)==0)
24938             n = mp_make_string(mp);
24939         mp_print_str(mp, mp->str_pool[i]);
24940       };
24941       incr(i);
24942     };
24943     s = mp_make_string(mp);
24944     mp->selector= old_setting;
24945     if (length(n)==0) {
24946        n=s;
24947        s=rts("");
24948     };
24949     mp_pack_file_name(mp, str(n),"",str(s));
24950     delete_str_ref(n);
24951         ss = str(s);
24952     delete_str_ref(s);
24953   }
24954   return ss;
24955 }
24956
24957 char * mp_get_output_file_name (MP mp) {
24958   char *fname; /* return value */
24959   char *saved_name;  /* saved |name_of_file| */
24960   saved_name = mp_xstrdup(mp, mp->name_of_file);
24961   (void)mp_set_output_file_name(mp, mp_round_unscaled(mp, mp->internal[mp_char_code]));
24962   fname = mp_xstrdup(mp, mp->name_of_file);
24963   mp_pack_file_name(mp, saved_name,NULL,NULL);
24964   return fname;
24965 }
24966
24967 void mp_open_output_file (MP mp) {
24968   char *ss; /* filename extension proposal */
24969   integer c; /* \&{charcode} rounded to the nearest integer */
24970   c=mp_round_unscaled(mp, mp->internal[mp_char_code]);
24971   ss = mp_set_output_file_name(mp, c);
24972   while ( ! mp_a_open_out(mp, (void *)&mp->ps_file, mp_filetype_postscript) )
24973     mp_prompt_file_name(mp, "file name for output",ss);
24974   xfree(ss);
24975   @<Store the true output file name if appropriate@>;
24976 }
24977
24978 @ The file extension created here could be up to five characters long in
24979 extreme cases so it may have to be shortened on some systems.
24980 @^system dependencies@>
24981
24982 @<Use |c| to compute the file extension |s|@>=
24983
24984   s = xmalloc(7,1);
24985   snprintf(s,7,".%i",(int)c);
24986 }
24987
24988 @ The user won't want to see all the output file names so we only save the
24989 first and last ones and a count of how many there were.  For this purpose
24990 files are ordered primarily by \&{charcode} and secondarily by order of
24991 creation.
24992 @:char_code_}{\&{charcode} primitive@>
24993
24994 @<Store the true output file name if appropriate@>=
24995 if ((c<mp->first_output_code)&&(mp->first_output_code>=0)) {
24996   mp->first_output_code=c;
24997   xfree(mp->first_file_name);
24998   mp->first_file_name=xstrdup(mp->name_of_file);
24999 }
25000 if ( c>=mp->last_output_code ) {
25001   mp->last_output_code=c;
25002   xfree(mp->last_file_name);
25003   mp->last_file_name=xstrdup(mp->name_of_file);
25004 }
25005
25006 @ @<Glob...@>=
25007 char * first_file_name;
25008 char * last_file_name; /* full file names */
25009 integer first_output_code;integer last_output_code; /* rounded \&{charcode} values */
25010 @:char_code_}{\&{charcode} primitive@>
25011 integer total_shipped; /* total number of |ship_out| operations completed */
25012
25013 @ @<Set init...@>=
25014 mp->first_file_name=xstrdup("");
25015 mp->last_file_name=xstrdup("");
25016 mp->first_output_code=32768;
25017 mp->last_output_code=-32768;
25018 mp->total_shipped=0;
25019
25020 @ @<Dealloc variables@>=
25021 xfree(mp->first_file_name);
25022 xfree(mp->last_file_name);
25023
25024 @ @<Begin the progress report for the output of picture~|c|@>=
25025 if ( (int)mp->term_offset>mp->max_print_line-6 ) mp_print_ln(mp);
25026 else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
25027 mp_print_char(mp, '[');
25028 if ( c>=0 ) mp_print_int(mp, c)
25029
25030 @ @<End progress report@>=
25031 mp_print_char(mp, ']');
25032 update_terminal;
25033 incr(mp->total_shipped)
25034
25035 @ @<Explain what output files were written@>=
25036 if ( mp->total_shipped>0 ) { 
25037   mp_print_nl(mp, "");
25038   mp_print_int(mp, mp->total_shipped);
25039   mp_print(mp, " output file");
25040   if ( mp->total_shipped>1 ) mp_print_char(mp, 's');
25041   mp_print(mp, " written: ");
25042   mp_print(mp, mp->first_file_name);
25043   if ( mp->total_shipped>1 ) {
25044     if ( 31+strlen(mp->first_file_name)+
25045          strlen(mp->last_file_name)> (unsigned)mp->max_print_line) 
25046       mp_print_ln(mp);
25047     mp_print(mp, " .. ");
25048     mp_print(mp, mp->last_file_name);
25049   }
25050 }
25051
25052 @ @<Internal library declarations@>=
25053 boolean mp_has_font_size(MP mp, font_number f );
25054
25055 @ @c 
25056 boolean mp_has_font_size(MP mp, font_number f ) {
25057   return (mp->font_sizes[f]!=null);
25058 }
25059
25060 @ The \&{special} command saves up lines of text to be printed during the next
25061 |ship_out| operation.  The saved items are stored as a list of capsule tokens.
25062
25063 @<Glob...@>=
25064 pointer last_pending; /* the last token in a list of pending specials */
25065
25066 @ @<Set init...@>=
25067 mp->last_pending=spec_head;
25068
25069 @ @<Cases of |do_statement|...@>=
25070 case special_command: 
25071   if ( mp->cur_mod==0 ) mp_do_special(mp); else 
25072   if ( mp->cur_mod==1 ) mp_do_mapfile(mp); else 
25073   mp_do_mapline(mp);
25074   break;
25075
25076 @ @<Declare action procedures for use by |do_statement|@>=
25077 void mp_do_special (MP mp) ;
25078
25079 @ @c void mp_do_special (MP mp) { 
25080   mp_get_x_next(mp); mp_scan_expression(mp);
25081   if ( mp->cur_type!=mp_string_type ) {
25082     @<Complain about improper special operation@>;
25083   } else { 
25084     link(mp->last_pending)=mp_stash_cur_exp(mp);
25085     mp->last_pending=link(mp->last_pending);
25086     link(mp->last_pending)=null;
25087   }
25088 }
25089
25090 @ @<Complain about improper special operation@>=
25091
25092   exp_err("Unsuitable expression");
25093   help1("Only known strings are allowed for output as specials.");
25094   mp_put_get_error(mp);
25095 }
25096
25097 @ On the export side, we need an extra object type for special strings.
25098
25099 @<Graphical object codes@>=
25100 mp_special_code=8, 
25101
25102 @ @<Export pending specials@>=
25103 p=link(spec_head);
25104 while ( p!=null ) {
25105   hq = mp_new_graphic_object(mp,mp_special_code);
25106   gr_pre_script(hq)  = str(value(p));
25107   if (hh->body==NULL) hh->body=hq; else gr_link(hp) = hq;
25108   hp = hq;
25109   p=link(p);
25110 }
25111 mp_flush_token_list(mp, link(spec_head));
25112 link(spec_head)=null;
25113 mp->last_pending=spec_head
25114
25115 @ We are now ready for the main output procedure.  Note that the |selector|
25116 setting is saved in a global variable so that |begin_diagnostic| can access it.
25117
25118 @<Declare the \ps\ output procedures@>=
25119 void mp_ship_out (MP mp, pointer h) ;
25120
25121 @ Once again, the |gr_XXXX| macros are defined in |mppsout.h|
25122
25123 @c
25124 struct mp_edge_object *mp_gr_export(MP mp, pointer h) {
25125   pointer p; /* the current graphical object */
25126   integer t; /* a temporary value */
25127   struct mp_edge_object *hh; /* the first graphical object */
25128   struct mp_graphic_object *hp; /* the current graphical object */
25129   struct mp_graphic_object *hq; /* something |hp| points to  */
25130   mp_set_bbox(mp, h, true);
25131   hh = mp_xmalloc(mp,1,sizeof(struct mp_edge_object));
25132   hh->body = NULL;
25133   hh->_next = NULL;
25134   hh->_parent = mp;
25135   hh->_minx = minx_val(h);
25136   hh->_miny = miny_val(h);
25137   hh->_maxx = maxx_val(h);
25138   hh->_maxy = maxy_val(h);
25139   hh->_filename = mp_get_output_file_name(mp);
25140   @<Export pending specials@>;
25141   p=link(dummy_loc(h));
25142   while ( p!=null ) { 
25143     hq = mp_new_graphic_object(mp,type(p));
25144     switch (type(p)) {
25145     case mp_fill_code:
25146       gr_pen_p(hq)        = mp_export_knot_list(mp,pen_p(p));
25147       if ((pen_p(p)==null) || pen_is_elliptical(pen_p(p)))  {
25148           gr_path_p(hq)       = mp_export_knot_list(mp,path_p(p));
25149       } else {
25150         pointer pc, pp;
25151         pc = mp_copy_path(mp, path_p(p));
25152         pp = mp_make_envelope(mp, pc, pen_p(p),ljoin_val(p),0,miterlim_val(p));
25153         gr_path_p(hq)       = mp_export_knot_list(mp,pp);
25154         mp_toss_knot_list(mp, pp);
25155         pc = mp_htap_ypoc(mp, path_p(p));
25156         pp = mp_make_envelope(mp, pc, pen_p(p),ljoin_val(p),0,miterlim_val(p));
25157         gr_htap_p(hq)       = mp_export_knot_list(mp,pp);
25158         mp_toss_knot_list(mp, pp);
25159       }
25160       @<Export object color@>;
25161       @<Export object scripts@>;
25162       gr_ljoin_val(hq)    = ljoin_val(p);
25163       gr_miterlim_val(hq) = miterlim_val(p);
25164       break;
25165     case mp_stroked_code:
25166       gr_pen_p(hq)        = mp_export_knot_list(mp,pen_p(p));
25167       if (pen_is_elliptical(pen_p(p)))  {
25168               gr_path_p(hq)       = mp_export_knot_list(mp,path_p(p));
25169       } else {
25170         pointer pc;
25171         pc=mp_copy_path(mp, path_p(p));
25172         t=lcap_val(p);
25173         if ( left_type(pc)!=mp_endpoint ) { 
25174           left_type(mp_insert_knot(mp, pc,x_coord(pc),y_coord(pc)))=mp_endpoint;
25175           right_type(pc)=mp_endpoint;
25176           pc=link(pc);
25177           t=1;
25178         }
25179         pc=mp_make_envelope(mp,pc,pen_p(p),ljoin_val(p),t,miterlim_val(p));
25180         gr_path_p(hq)       = mp_export_knot_list(mp,pc);
25181         mp_toss_knot_list(mp, pc);
25182       }
25183       @<Export object color@>;
25184       @<Export object scripts@>;
25185       gr_ljoin_val(hq)    = ljoin_val(p);
25186       gr_miterlim_val(hq) = miterlim_val(p);
25187       gr_lcap_val(hq)     = lcap_val(p);
25188       gr_dash_scale(hq)   = dash_scale(p);
25189       gr_dash_p(hq)       = mp_export_dashes(mp,dash_p(p));
25190       break;
25191     case mp_text_code:
25192       gr_text_p(hq)       = str(text_p(p));
25193       gr_font_n(hq)       = font_n(p);
25194       gr_font_name(hq)    = mp_xstrdup(mp,mp->font_name[font_n(p)]);
25195       gr_font_dsize(hq)   = mp->font_dsize[font_n(p)];
25196       @<Export object color@>;
25197       @<Export object scripts@>;
25198       gr_width_val(hq)    = width_val(p);
25199       gr_height_val(hq)   = height_val(p);
25200       gr_depth_val(hq)    = depth_val(p);
25201       gr_tx_val(hq)       = tx_val(p);
25202       gr_ty_val(hq)       = ty_val(p);
25203       gr_txx_val(hq)      = txx_val(p);
25204       gr_txy_val(hq)      = txy_val(p);
25205       gr_tyx_val(hq)      = tyx_val(p);
25206       gr_tyy_val(hq)      = tyy_val(p);
25207       break;
25208     case mp_start_clip_code: 
25209     case mp_start_bounds_code:
25210       gr_path_p(hq) = mp_export_knot_list(mp,path_p(p));
25211       break;
25212     case mp_stop_clip_code: 
25213     case mp_stop_bounds_code:
25214       /* nothing to do here */
25215       break;
25216     } 
25217     if (hh->body==NULL) hh->body=hq; else  gr_link(hp) = hq;
25218     hp = hq;
25219     p=link(p);
25220   }
25221   return hh;
25222 }
25223
25224 @ @<Exported function ...@>=
25225 struct mp_edge_object *mp_gr_export(MP mp, int h);
25226
25227 @ This function is now nearly trivial.
25228
25229 @c
25230 void mp_ship_out (MP mp, pointer h) { /* output edge structure |h| */
25231   integer c; /* \&{charcode} rounded to the nearest integer */
25232   c=mp_round_unscaled(mp, mp->internal[mp_char_code]);
25233   @<Begin the progress report for the output of picture~|c|@>;
25234   (mp->shipout_backend) (mp, h);
25235   @<End progress report@>;
25236   if ( mp->internal[mp_tracing_output]>0 ) 
25237    mp_print_edges(mp, h," (just shipped out)",true);
25238 }
25239
25240 @ @<Declarations@>=
25241 void mp_shipout_backend (MP mp, pointer h);
25242
25243 @ @c
25244 void mp_shipout_backend (MP mp, pointer h) {
25245   struct mp_edge_object *hh; /* the first graphical object */
25246   hh = mp_gr_export(mp,h);
25247   mp_gr_ship_out (hh,
25248                  (mp->internal[mp_prologues]>>16),
25249                  (mp->internal[mp_procset]>>16));
25250   mp_gr_toss_objects(hh);
25251 }
25252
25253 @ @<Exported types@>=
25254 typedef void (*mp_backend_writer)(MP, int);
25255
25256 @ @<Option variables@>=
25257 mp_backend_writer shipout_backend;
25258
25259 @ @<Allocate or initialize ...@>=
25260 set_callback_option(shipout_backend);
25261
25262
25263
25264 @ Once again, the |gr_XXXX| macros are defined in |mppsout.h|
25265
25266 @<Export object color@>=
25267 gr_color_model(hq)  = color_model(p);
25268 gr_cyan_val(hq)     = cyan_val(p);
25269 gr_magenta_val(hq)  = magenta_val(p);
25270 gr_yellow_val(hq)   = yellow_val(p);
25271 gr_black_val(hq)    = black_val(p);
25272 gr_red_val(hq)      = red_val(p);
25273 gr_green_val(hq)    = green_val(p);
25274 gr_blue_val(hq)     = blue_val(p);
25275 gr_grey_val(hq)     = grey_val(p)
25276
25277
25278 @ @<Export object scripts@>=
25279 if (pre_script(p)!=null)
25280   gr_pre_script(hq)   = str(pre_script(p));
25281 if (post_script(p)!=null)
25282   gr_post_script(hq)  = str(post_script(p));
25283
25284 @ Now that we've finished |ship_out|, let's look at the other commands
25285 by which a user can send things to the \.{GF} file.
25286
25287 @ @<Determine if a character has been shipped out@>=
25288
25289   mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256;
25290   if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
25291   boolean_reset(mp->char_exists[mp->cur_exp]);
25292   mp->cur_type=mp_boolean_type;
25293 }
25294
25295 @ @<Glob...@>=
25296 psout_data ps;
25297
25298 @ @<Allocate or initialize ...@>=
25299 mp_backend_initialize(mp);
25300
25301 @ @<Dealloc...@>=
25302 mp_backend_free(mp);
25303
25304
25305 @* \[45] Dumping and undumping the tables.
25306 After \.{INIMP} has seen a collection of macros, it
25307 can write all the necessary information on an auxiliary file so
25308 that production versions of \MP\ are able to initialize their
25309 memory at high speed. The present section of the program takes
25310 care of such output and input. We shall consider simultaneously
25311 the processes of storing and restoring,
25312 so that the inverse relation between them is clear.
25313 @.INIMP@>
25314
25315 The global variable |mem_ident| is a string that is printed right
25316 after the |banner| line when \MP\ is ready to start. For \.{INIMP} this
25317 string says simply `\.{(INIMP)}'; for other versions of \MP\ it says,
25318 for example, `\.{(mem=plain 90.4.14)}', showing the year,
25319 month, and day that the mem file was created. We have |mem_ident=0|
25320 before \MP's tables are loaded.
25321
25322 @<Glob...@>=
25323 char * mem_ident;
25324
25325 @ @<Set init...@>=
25326 mp->mem_ident=NULL;
25327
25328 @ @<Initialize table entries...@>=
25329 mp->mem_ident=xstrdup(" (INIMP)");
25330
25331 @ @<Declare act...@>=
25332 void mp_store_mem_file (MP mp) ;
25333
25334 @ @c void mp_store_mem_file (MP mp) {
25335   integer k;  /* all-purpose index */
25336   pointer p,q; /* all-purpose pointers */
25337   integer x; /* something to dump */
25338   four_quarters w; /* four ASCII codes */
25339   memory_word WW;
25340   @<Create the |mem_ident|, open the mem file,
25341     and inform the user that dumping has begun@>;
25342   @<Dump constants for consistency check@>;
25343   @<Dump the string pool@>;
25344   @<Dump the dynamic memory@>;
25345   @<Dump the table of equivalents and the hash table@>;
25346   @<Dump a few more things and the closing check word@>;
25347   @<Close the mem file@>;
25348 }
25349
25350 @ Corresponding to the procedure that dumps a mem file, we also have a function
25351 that reads~one~in. The function returns |false| if the dumped mem is
25352 incompatible with the present \MP\ table sizes, etc.
25353
25354 @d off_base 6666 /* go here if the mem file is unacceptable */
25355 @d too_small(A) { wake_up_terminal;
25356   wterm_ln("---! Must increase the "); wterm((A));
25357 @.Must increase the x@>
25358   goto OFF_BASE;
25359   }
25360
25361 @c 
25362 boolean mp_load_mem_file (MP mp) {
25363   integer k; /* all-purpose index */
25364   pointer p,q; /* all-purpose pointers */
25365   integer x; /* something undumped */
25366   str_number s; /* some temporary string */
25367   four_quarters w; /* four ASCII codes */
25368   memory_word WW;
25369   @<Undump constants for consistency check@>;
25370   @<Undump the string pool@>;
25371   @<Undump the dynamic memory@>;
25372   @<Undump the table of equivalents and the hash table@>;
25373   @<Undump a few more things and the closing check word@>;
25374   return true; /* it worked! */
25375 OFF_BASE: 
25376   wake_up_terminal;
25377   wterm_ln("(Fatal mem file error; I'm stymied)\n");
25378 @.Fatal mem file error@>
25379    return false;
25380 }
25381
25382 @ @<Declarations@>=
25383 boolean mp_load_mem_file (MP mp) ;
25384
25385 @ Mem files consist of |memory_word| items, and we use the following
25386 macros to dump words of different types:
25387
25388 @d dump_wd(A)   { WW=(A);       (mp->write_binary_file)(mp->mem_file,&WW,sizeof(WW)); }
25389 @d dump_int(A)  { int cint=(A); (mp->write_binary_file)(mp->mem_file,&cint,sizeof(cint)); }
25390 @d dump_hh(A)   { WW.hh=(A);    (mp->write_binary_file)(mp->mem_file,&WW,sizeof(WW)); }
25391 @d dump_qqqq(A) { WW.qqqq=(A);  (mp->write_binary_file)(mp->mem_file,&WW,sizeof(WW)); }
25392 @d dump_string(A) { dump_int(strlen(A)+1);
25393                     (mp->write_binary_file)(mp->mem_file,A,strlen(A)+1); }
25394
25395 @<Glob...@>=
25396 void * mem_file; /* for input or output of mem information */
25397
25398 @ The inverse macros are slightly more complicated, since we need to check
25399 the range of the values we are reading in. We say `|undump(a)(b)(x)|' to
25400 read an integer value |x| that is supposed to be in the range |a<=x<=b|.
25401
25402 @d mgeti(A) do {
25403   size_t wanted = sizeof(A);
25404   void *A_ptr = &A;
25405   (mp->read_binary_file)(mp->mem_file,&A_ptr,&wanted);
25406   if (wanted!=sizeof(A)) goto OFF_BASE;
25407 } while (0)
25408
25409 @d mgetw(A) do {
25410   size_t wanted = sizeof(A);
25411   void *A_ptr = &A;
25412   (mp->read_binary_file)(mp->mem_file,&A_ptr,&wanted);
25413   if (wanted!=sizeof(A)) goto OFF_BASE;
25414 } while (0)
25415
25416 @d undump_wd(A)   { mgetw(WW); A=WW; }
25417 @d undump_int(A)  { int cint; mgeti(cint); A=cint; }
25418 @d undump_hh(A)   { mgetw(WW); A=WW.hh; }
25419 @d undump_qqqq(A) { mgetw(WW); A=WW.qqqq; }
25420 @d undump_strings(A,B,C) { 
25421    undump_int(x); if ( (x<(A)) || (x>(B)) ) goto OFF_BASE; else C=str(x); }
25422 @d undump(A,B,C) { undump_int(x); if ( (x<(A)) || (x>(int)(B)) ) goto OFF_BASE; else C=x; }
25423 @d undump_size(A,B,C,D) { undump_int(x);
25424                           if (x<(A)) goto OFF_BASE; 
25425                           if (x>(B)) { too_small((C)); } else { D=x;} }
25426 @d undump_string(A) do { 
25427   size_t wanted; 
25428   integer XX=0; 
25429   undump_int(XX);
25430   wanted = XX;
25431   A = xmalloc(XX,sizeof(char));
25432   (mp->read_binary_file)(mp->mem_file,(void **)&A,&wanted);
25433   if (wanted!=(size_t)XX) goto OFF_BASE;
25434 } while (0)
25435
25436 @ The next few sections of the program should make it clear how we use the
25437 dump/undump macros.
25438
25439 @<Dump constants for consistency check@>=
25440 dump_int(mp->mem_top);
25441 dump_int(mp->hash_size);
25442 dump_int(mp->hash_prime)
25443 dump_int(mp->param_size);
25444 dump_int(mp->max_in_open);
25445
25446 @ Sections of a \.{WEB} program that are ``commented out'' still contribute
25447 strings to the string pool; therefore \.{INIMP} and \MP\ will have
25448 the same strings. (And it is, of course, a good thing that they do.)
25449 @.WEB@>
25450 @^string pool@>
25451
25452 @<Undump constants for consistency check@>=
25453 undump_int(x); mp->mem_top = x;
25454 undump_int(x); if (mp->hash_size != x) goto OFF_BASE;
25455 undump_int(x); if (mp->hash_prime != x) goto OFF_BASE;
25456 undump_int(x); if (mp->param_size != x) goto OFF_BASE;
25457 undump_int(x); if (mp->max_in_open != x) goto OFF_BASE
25458
25459 @ We do string pool compaction to avoid dumping unused strings.
25460
25461 @d dump_four_ASCII 
25462   w.b0=qi(mp->str_pool[k]); w.b1=qi(mp->str_pool[k+1]);
25463   w.b2=qi(mp->str_pool[k+2]); w.b3=qi(mp->str_pool[k+3]);
25464   dump_qqqq(w)
25465
25466 @<Dump the string pool@>=
25467 mp_do_compaction(mp, mp->pool_size);
25468 dump_int(mp->pool_ptr);
25469 dump_int(mp->max_str_ptr);
25470 dump_int(mp->str_ptr);
25471 k=0;
25472 while ( (mp->next_str[k]==k+1) && (k<=mp->max_str_ptr) ) 
25473   incr(k);
25474 dump_int(k);
25475 while ( k<=mp->max_str_ptr ) { 
25476   dump_int(mp->next_str[k]); incr(k);
25477 }
25478 k=0;
25479 while (1)  { 
25480   dump_int(mp->str_start[k]); /* TODO: valgrind warning here */
25481   if ( k==mp->str_ptr ) {
25482     break;
25483   } else { 
25484     k=mp->next_str[k]; 
25485   }
25486 };
25487 k=0;
25488 while (k+4<mp->pool_ptr ) { 
25489   dump_four_ASCII; k=k+4; 
25490 }
25491 k=mp->pool_ptr-4; dump_four_ASCII;
25492 mp_print_ln(mp); mp_print(mp, "at most "); mp_print_int(mp, mp->max_str_ptr);
25493 mp_print(mp, " strings of total length ");
25494 mp_print_int(mp, mp->pool_ptr)
25495
25496 @ @d undump_four_ASCII 
25497   undump_qqqq(w);
25498   mp->str_pool[k]=qo(w.b0); mp->str_pool[k+1]=qo(w.b1);
25499   mp->str_pool[k+2]=qo(w.b2); mp->str_pool[k+3]=qo(w.b3)
25500
25501 @<Undump the string pool@>=
25502 undump_int(mp->pool_ptr);
25503 mp_reallocate_pool(mp, mp->pool_ptr) ;
25504 undump_int(mp->max_str_ptr);
25505 mp_reallocate_strings (mp,mp->max_str_ptr) ;
25506 undump(0,mp->max_str_ptr,mp->str_ptr);
25507 undump(0,mp->max_str_ptr+1,s);
25508 for (k=0;k<=s-1;k++) 
25509   mp->next_str[k]=k+1;
25510 for (k=s;k<=mp->max_str_ptr;k++) 
25511   undump(s+1,mp->max_str_ptr+1,mp->next_str[k]);
25512 mp->fixed_str_use=0;
25513 k=0;
25514 while (1) { 
25515   undump(0,mp->pool_ptr,mp->str_start[k]);
25516   if ( k==mp->str_ptr ) break;
25517   mp->str_ref[k]=max_str_ref;
25518   incr(mp->fixed_str_use);
25519   mp->last_fixed_str=k; k=mp->next_str[k];
25520 }
25521 k=0;
25522 while ( k+4<mp->pool_ptr ) { 
25523   undump_four_ASCII; k=k+4;
25524 }
25525 k=mp->pool_ptr-4; undump_four_ASCII;
25526 mp->init_str_use=mp->fixed_str_use; mp->init_pool_ptr=mp->pool_ptr;
25527 mp->max_pool_ptr=mp->pool_ptr;
25528 mp->strs_used_up=mp->fixed_str_use;
25529 mp->pool_in_use=mp->str_start[mp->str_ptr]; mp->strs_in_use=mp->fixed_str_use;
25530 mp->max_pl_used=mp->pool_in_use; mp->max_strs_used=mp->strs_in_use;
25531 mp->pact_count=0; mp->pact_chars=0; mp->pact_strs=0;
25532
25533 @ By sorting the list of available spaces in the variable-size portion of
25534 |mem|, we are usually able to get by without having to dump very much
25535 of the dynamic memory.
25536
25537 We recompute |var_used| and |dyn_used|, so that \.{INIMP} dumps valid
25538 information even when it has not been gathering statistics.
25539
25540 @<Dump the dynamic memory@>=
25541 mp_sort_avail(mp); mp->var_used=0;
25542 dump_int(mp->lo_mem_max); dump_int(mp->rover);
25543 p=0; q=mp->rover; x=0;
25544 do {  
25545   for (k=p;k<= q+1;k++) 
25546     dump_wd(mp->mem[k]);
25547   x=x+q+2-p; mp->var_used=mp->var_used+q-p;
25548   p=q+node_size(q); q=rlink(q);
25549 } while (q!=mp->rover);
25550 mp->var_used=mp->var_used+mp->lo_mem_max-p; 
25551 mp->dyn_used=mp->mem_end+1-mp->hi_mem_min;
25552 for (k=p;k<= mp->lo_mem_max;k++ ) 
25553   dump_wd(mp->mem[k]);
25554 x=x+mp->lo_mem_max+1-p;
25555 dump_int(mp->hi_mem_min); dump_int(mp->avail);
25556 for (k=mp->hi_mem_min;k<=mp->mem_end;k++ ) 
25557   dump_wd(mp->mem[k]);
25558 x=x+mp->mem_end+1-mp->hi_mem_min;
25559 p=mp->avail;
25560 while ( p!=null ) { 
25561   decr(mp->dyn_used); p=link(p);
25562 }
25563 dump_int(mp->var_used); dump_int(mp->dyn_used);
25564 mp_print_ln(mp); mp_print_int(mp, x);
25565 mp_print(mp, " memory locations dumped; current usage is ");
25566 mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used)
25567
25568 @ @<Undump the dynamic memory@>=
25569 undump(lo_mem_stat_max+1000,hi_mem_stat_min-1,mp->lo_mem_max);
25570 undump(lo_mem_stat_max+1,mp->lo_mem_max,mp->rover);
25571 p=0; q=mp->rover;
25572 do {  
25573   for (k=p;k<= q+1; k++) 
25574     undump_wd(mp->mem[k]);
25575   p=q+node_size(q);
25576   if ( (p>mp->lo_mem_max)||((q>=rlink(q))&&(rlink(q)!=mp->rover)) ) 
25577     goto OFF_BASE;
25578   q=rlink(q);
25579 } while (q!=mp->rover);
25580 for (k=p;k<=mp->lo_mem_max;k++ ) 
25581   undump_wd(mp->mem[k]);
25582 undump(mp->lo_mem_max+1,hi_mem_stat_min,mp->hi_mem_min);
25583 undump(null,mp->mem_top,mp->avail); mp->mem_end=mp->mem_top;
25584 for (k=mp->hi_mem_min;k<= mp->mem_end;k++) 
25585   undump_wd(mp->mem[k]);
25586 undump_int(mp->var_used); undump_int(mp->dyn_used)
25587
25588 @ A different scheme is used to compress the hash table, since its lower region
25589 is usually sparse. When |text(p)<>0| for |p<=hash_used|, we output three
25590 words: |p|, |hash[p]|, and |eqtb[p]|. The hash table is, of course, densely
25591 packed for |p>=hash_used|, so the remaining entries are output in~a~block.
25592
25593 @<Dump the table of equivalents and the hash table@>=
25594 dump_int(mp->hash_used); 
25595 mp->st_count=frozen_inaccessible-1-mp->hash_used;
25596 for (p=1;p<=mp->hash_used;p++) {
25597   if ( text(p)!=0 ) {
25598      dump_int(p); dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]); incr(mp->st_count);
25599   }
25600 }
25601 for (p=mp->hash_used+1;p<=(int)hash_end;p++) {
25602   dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]);
25603 }
25604 dump_int(mp->st_count);
25605 mp_print_ln(mp); mp_print_int(mp, mp->st_count); mp_print(mp, " symbolic tokens")
25606
25607 @ @<Undump the table of equivalents and the hash table@>=
25608 undump(1,frozen_inaccessible,mp->hash_used); 
25609 p=0;
25610 do {  
25611   undump(p+1,mp->hash_used,p); 
25612   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
25613 } while (p!=mp->hash_used);
25614 for (p=mp->hash_used+1;p<=(int)hash_end;p++ )  { 
25615   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
25616 }
25617 undump_int(mp->st_count)
25618
25619 @ We have already printed a lot of statistics, so we set |mp_tracing_stats:=0|
25620 to prevent them appearing again.
25621
25622 @<Dump a few more things and the closing check word@>=
25623 dump_int(mp->max_internal);
25624 dump_int(mp->int_ptr);
25625 for (k=1;k<= mp->int_ptr;k++ ) { 
25626   dump_int(mp->internal[k]); 
25627   dump_string(mp->int_name[k]);
25628 }
25629 dump_int(mp->start_sym); 
25630 dump_int(mp->interaction); 
25631 dump_string(mp->mem_ident);
25632 dump_int(mp->bg_loc); dump_int(mp->eg_loc); dump_int(mp->serial_no); dump_int(69073);
25633 mp->internal[mp_tracing_stats]=0
25634
25635 @ @<Undump a few more things and the closing check word@>=
25636 undump_int(x);
25637 if (x>mp->max_internal) mp_grow_internals(mp,x);
25638 undump_int(mp->int_ptr);
25639 for (k=1;k<= mp->int_ptr;k++) { 
25640   undump_int(mp->internal[k]);
25641   undump_string(mp->int_name[k]);
25642 }
25643 undump(0,frozen_inaccessible,mp->start_sym);
25644 if (mp->interaction==mp_unspecified_mode) {
25645   undump(mp_unspecified_mode,mp_error_stop_mode,mp->interaction);
25646 } else {
25647   undump(mp_unspecified_mode,mp_error_stop_mode,x);
25648 }
25649 undump_string(mp->mem_ident);
25650 undump(1,hash_end,mp->bg_loc);
25651 undump(1,hash_end,mp->eg_loc);
25652 undump_int(mp->serial_no);
25653 undump_int(x); 
25654 if (x!=69073) goto OFF_BASE
25655
25656 @ @<Create the |mem_ident|...@>=
25657
25658   xfree(mp->mem_ident);
25659   mp->mem_ident = xmalloc(256,1);
25660   snprintf(mp->mem_ident,256," (mem=%s %i.%i.%i)", 
25661            mp->job_name,
25662            (int)(mp_round_unscaled(mp, mp->internal[mp_year]) % 100),
25663            (int)mp_round_unscaled(mp, mp->internal[mp_month]),
25664            (int)mp_round_unscaled(mp, mp->internal[mp_day]));
25665   mp_pack_job_name(mp, mem_extension);
25666   while (! mp_w_open_out(mp, &mp->mem_file) )
25667     mp_prompt_file_name(mp, "mem file name", mem_extension);
25668   mp_print_nl(mp, "Beginning to dump on file ");
25669 @.Beginning to dump...@>
25670   mp_print(mp, mp->name_of_file); 
25671   mp_print_nl(mp, mp->mem_ident);
25672 }
25673
25674 @ @<Dealloc variables@>=
25675 xfree(mp->mem_ident);
25676
25677 @ @<Close the mem file@>=
25678 (mp->close_file)(mp->mem_file)
25679
25680 @* \[46] The main program.
25681 This is it: the part of \MP\ that executes all those procedures we have
25682 written.
25683
25684 Well---almost. We haven't put the parsing subroutines into the
25685 program yet; and we'd better leave space for a few more routines that may
25686 have been forgotten.
25687
25688 @c @<Declare the basic parsing subroutines@>;
25689 @<Declare miscellaneous procedures that were declared |forward|@>;
25690 @<Last-minute procedures@>
25691
25692 @ We've noted that there are two versions of \MP. One, called \.{INIMP},
25693 @.INIMP@>
25694 has to be run first; it initializes everything from scratch, without
25695 reading a mem file, and it has the capability of dumping a mem file.
25696 The other one is called `\.{VIRMP}'; it is a ``virgin'' program that needs
25697 @.VIRMP@>
25698 to input a mem file in order to get started. \.{VIRMP} typically has
25699 a bit more memory capacity than \.{INIMP}, because it does not need the
25700 space consumed by the dumping/undumping routines and the numerous calls on
25701 |primitive|, etc.
25702
25703 The \.{VIRMP} program cannot read a mem file instantaneously, of course;
25704 the best implementations therefore allow for production versions of \MP\ that
25705 not only avoid the loading routine for object code, they also have
25706 a mem file pre-loaded. 
25707
25708 @ @<Option variables@>=
25709 int ini_version; /* are we iniMP? */
25710
25711 @ @<Set |ini_version|@>=
25712 mp->ini_version = (opt->ini_version ? true : false);
25713
25714 @ Here we do whatever is needed to complete \MP's job gracefully on the
25715 local operating system. The code here might come into play after a fatal
25716 error; it must therefore consist entirely of ``safe'' operations that
25717 cannot produce error messages. For example, it would be a mistake to call
25718 |str_room| or |make_string| at this time, because a call on |overflow|
25719 might lead to an infinite loop.
25720 @^system dependencies@>
25721
25722 This program doesn't bother to close the input files that may still be open.
25723
25724 @<Last-minute...@>=
25725 void mp_close_files_and_terminate (MP mp) {
25726   integer k; /* all-purpose index */
25727   integer LH; /* the length of the \.{TFM} header, in words */
25728   int lk_offset; /* extra words inserted at beginning of |lig_kern| array */
25729   pointer p; /* runs through a list of \.{TFM} dimensions */
25730   @<Close all open files in the |rd_file| and |wr_file| arrays@>;
25731   if ( mp->internal[mp_tracing_stats]>0 )
25732     @<Output statistics about this job@>;
25733   wake_up_terminal; 
25734   @<Do all the finishing work on the \.{TFM} file@>;
25735   @<Explain what output files were written@>;
25736   if ( mp->log_opened ){ 
25737     wlog_cr;
25738     (mp->close_file)(mp->log_file); 
25739     mp->selector=mp->selector-2;
25740     if ( mp->selector==term_only ) {
25741       mp_print_nl(mp, "Transcript written on ");
25742 @.Transcript written...@>
25743       mp_print(mp, mp->log_name); mp_print_char(mp, '.');
25744     }
25745   }
25746   mp_print_ln(mp);
25747   t_close_out;
25748   t_close_in;
25749 }
25750
25751 @ @<Declarations@>=
25752 void mp_close_files_and_terminate (MP mp) ;
25753
25754 @ @<Close all open files in the |rd_file| and |wr_file| arrays@>=
25755 if (mp->rd_fname!=NULL) {
25756   for (k=0;k<=(int)mp->read_files-1;k++ ) {
25757     if ( mp->rd_fname[k]!=NULL ) {
25758       (mp->close_file)(mp->rd_file[k]);
25759    }
25760  }
25761 }
25762 if (mp->wr_fname!=NULL) {
25763   for (k=0;k<=(int)mp->write_files-1;k++) {
25764     if ( mp->wr_fname[k]!=NULL ) {
25765      (mp->close_file)(mp->wr_file[k]);
25766     }
25767   }
25768 }
25769
25770 @ @<Dealloc ...@>=
25771 for (k=0;k<(int)mp->max_read_files;k++ ) {
25772   if ( mp->rd_fname[k]!=NULL ) {
25773     (mp->close_file)(mp->rd_file[k]);
25774     mp_xfree(mp->rd_fname[k]); 
25775   }
25776 }
25777 mp_xfree(mp->rd_file);
25778 mp_xfree(mp->rd_fname);
25779 for (k=0;k<(int)mp->max_write_files;k++) {
25780   if ( mp->wr_fname[k]!=NULL ) {
25781     (mp->close_file)(mp->wr_file[k]);
25782     mp_xfree(mp->wr_fname[k]); 
25783   }
25784 }
25785 mp_xfree(mp->wr_file);
25786 mp_xfree(mp->wr_fname);
25787
25788
25789 @ We want to produce a \.{TFM} file if and only if |mp_fontmaking| is positive.
25790
25791 We reclaim all of the variable-size memory at this point, so that
25792 there is no chance of another memory overflow after the memory capacity
25793 has already been exceeded.
25794
25795 @<Do all the finishing work on the \.{TFM} file@>=
25796 if ( mp->internal[mp_fontmaking]>0 ) {
25797   @<Make the dynamic memory into one big available node@>;
25798   @<Massage the \.{TFM} widths@>;
25799   mp_fix_design_size(mp); mp_fix_check_sum(mp);
25800   @<Massage the \.{TFM} heights, depths, and italic corrections@>;
25801   mp->internal[mp_fontmaking]=0; /* avoid loop in case of fatal error */
25802   @<Finish the \.{TFM} file@>;
25803 }
25804
25805 @ @<Make the dynamic memory into one big available node@>=
25806 mp->rover=lo_mem_stat_max+1; link(mp->rover)=empty_flag; mp->lo_mem_max=mp->hi_mem_min-1;
25807 if ( mp->lo_mem_max-mp->rover>max_halfword ) mp->lo_mem_max=max_halfword+mp->rover;
25808 node_size(mp->rover)=mp->lo_mem_max-mp->rover; 
25809 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
25810 link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null
25811
25812 @ The present section goes directly to the log file instead of using
25813 |print| commands, because there's no need for these strings to take
25814 up |str_pool| memory when a non-{\bf stat} version of \MP\ is being used.
25815
25816 @<Output statistics...@>=
25817 if ( mp->log_opened ) { 
25818   char s[128];
25819   wlog_ln(" ");
25820   wlog_ln("Here is how much of MetaPost's memory you used:");
25821 @.Here is how much...@>
25822   snprintf(s,128," %i string%s out of %i",(int)mp->max_strs_used-mp->init_str_use,
25823           (mp->max_strs_used!=mp->init_str_use+1 ? "s" : ""),
25824           (int)(mp->max_strings-1-mp->init_str_use));
25825   wlog_ln(s);
25826   snprintf(s,128," %i string characters out of %i",
25827            (int)mp->max_pl_used-mp->init_pool_ptr,
25828            (int)mp->pool_size-mp->init_pool_ptr);
25829   wlog_ln(s);
25830   snprintf(s,128," %i words of memory out of %i",
25831            (int)mp->lo_mem_max+mp->mem_end-mp->hi_mem_min+2,
25832            (int)mp->mem_end+1);
25833   wlog_ln(s);
25834   snprintf(s,128," %i symbolic tokens out of %i", (int)mp->st_count, (int)mp->hash_size);
25835   wlog_ln(s);
25836   snprintf(s,128," %ii, %in, %ip, %ib stack positions out of %ii, %in, %ip, %ib",
25837            (int)mp->max_in_stack,(int)mp->int_ptr,
25838            (int)mp->max_param_stack,(int)mp->max_buf_stack+1,
25839            (int)mp->stack_size,(int)mp->max_internal,(int)mp->param_size,(int)mp->buf_size);
25840   wlog_ln(s);
25841   snprintf(s,128," %i string compactions (moved %i characters, %i strings)",
25842           (int)mp->pact_count,(int)mp->pact_chars,(int)mp->pact_strs);
25843   wlog_ln(s);
25844 }
25845
25846 @ We get to the |final_cleanup| routine when \&{end} or \&{dump} has
25847 been scanned.
25848
25849 @<Last-minute...@>=
25850 void mp_final_cleanup (MP mp) {
25851   small_number c; /* 0 for \&{end}, 1 for \&{dump} */
25852   c=mp->cur_mod;
25853   if ( mp->job_name==NULL ) mp_open_log_file(mp);
25854   while ( mp->input_ptr>0 ) {
25855     if ( token_state ) mp_end_token_list(mp);
25856     else  mp_end_file_reading(mp);
25857   }
25858   while ( mp->loop_ptr!=null ) mp_stop_iteration(mp);
25859   while ( mp->open_parens>0 ) { 
25860     mp_print(mp, " )"); decr(mp->open_parens);
25861   };
25862   while ( mp->cond_ptr!=null ) {
25863     mp_print_nl(mp, "(end occurred when ");
25864 @.end occurred...@>
25865     mp_print_cmd_mod(mp, fi_or_else,mp->cur_if);
25866     /* `\.{if}' or `\.{elseif}' or `\.{else}' */
25867     if ( mp->if_line!=0 ) {
25868       mp_print(mp, " on line "); mp_print_int(mp, mp->if_line);
25869     }
25870     mp_print(mp, " was incomplete)");
25871     mp->if_line=if_line_field(mp->cond_ptr);
25872     mp->cur_if=name_type(mp->cond_ptr); mp->cond_ptr=link(mp->cond_ptr);
25873   }
25874   if ( mp->history!=mp_spotless )
25875     if ( ((mp->history==mp_warning_issued)||(mp->interaction<mp_error_stop_mode)) )
25876       if ( mp->selector==term_and_log ) {
25877     mp->selector=term_only;
25878     mp_print_nl(mp, "(see the transcript file for additional information)");
25879 @.see the transcript file...@>
25880     mp->selector=term_and_log;
25881   }
25882   if ( c==1 ) {
25883     if (mp->ini_version) {
25884       mp_store_mem_file(mp); return;
25885     }
25886     mp_print_nl(mp, "(dump is performed only by INIMP)"); return;
25887 @.dump...only by INIMP@>
25888   }
25889 }
25890
25891 @ @<Declarations@>=
25892 void mp_final_cleanup (MP mp) ;
25893 void mp_init_prim (MP mp) ;
25894 void mp_init_tab (MP mp) ;
25895
25896 @ @<Last-minute...@>=
25897 void mp_init_prim (MP mp) { /* initialize all the primitives */
25898   @<Put each...@>;
25899 }
25900 @#
25901 void mp_init_tab (MP mp) { /* initialize other tables */
25902   integer k; /* all-purpose index */
25903   @<Initialize table entries (done by \.{INIMP} only)@>;
25904 }
25905
25906
25907 @ When we begin the following code, \MP's tables may still contain garbage;
25908 the strings might not even be present. Thus we must proceed cautiously to get
25909 bootstrapped in.
25910
25911 But when we finish this part of the program, \MP\ is ready to call on the
25912 |main_control| routine to do its work.
25913
25914 @<Get the first line...@>=
25915
25916   @<Initialize the input routines@>;
25917   if ( (mp->mem_ident==NULL)||(mp->buffer[loc]=='&') ) {
25918     if ( mp->mem_ident!=NULL ) {
25919       mp_do_initialize(mp); /* erase preloaded mem */
25920     }
25921     if ( ! mp_open_mem_file(mp) ) return mp_fatal_error_stop;
25922     if ( ! mp_load_mem_file(mp) ) {
25923       (mp->close_file)(mp->mem_file); 
25924       return mp_fatal_error_stop;
25925     }
25926     (mp->close_file)( mp->mem_file);
25927     while ( (loc<limit)&&(mp->buffer[loc]==' ') ) incr(loc);
25928   }
25929   mp->buffer[limit]='%';
25930   mp_fix_date_and_time(mp);
25931   if (mp->random_seed==0)
25932     mp->random_seed = (mp->internal[mp_time] / unity)+mp->internal[mp_day];
25933   mp_init_randoms(mp, mp->random_seed);
25934   @<Initialize the print |selector|...@>;
25935   if ( loc<limit ) if ( mp->buffer[loc]!='\\' ) 
25936     mp_start_input(mp); /* \&{input} assumed */
25937 }
25938
25939 @ @<Run inimpost commands@>=
25940 {
25941   mp_get_strings_started(mp);
25942   mp_init_tab(mp); /* initialize the tables */
25943   mp_init_prim(mp); /* call |primitive| for each primitive */
25944   mp->init_str_use=mp->str_ptr; mp->init_pool_ptr=mp->pool_ptr;
25945   mp->max_str_ptr=mp->str_ptr; mp->max_pool_ptr=mp->pool_ptr;
25946   mp_fix_date_and_time(mp);
25947 }
25948
25949
25950 @* \[47] Debugging.
25951 Once \MP\ is working, you should be able to diagnose most errors with
25952 the \.{show} commands and other diagnostic features. But for the initial
25953 stages of debugging, and for the revelation of really deep mysteries, you
25954 can compile \MP\ with a few more aids. An additional routine called |debug_help|
25955 will also come into play when you type `\.D' after an error message;
25956 |debug_help| also occurs just before a fatal error causes \MP\ to succumb.
25957 @^debugging@>
25958 @^system dependencies@>
25959
25960 The interface to |debug_help| is primitive, but it is good enough when used
25961 with a debugger that allows you to set breakpoints and to read
25962 variables and change their values. After getting the prompt `\.{debug \#}', you
25963 type either a negative number (this exits |debug_help|), or zero (this
25964 goes to a location where you can set a breakpoint, thereby entering into
25965 dialog with the debugger), or a positive number |m| followed by
25966 an argument |n|. The meaning of |m| and |n| will be clear from the
25967 program below. (If |m=13|, there is an additional argument, |l|.)
25968 @.debug \#@>
25969
25970 @<Last-minute...@>=
25971 void mp_debug_help (MP mp) { /* routine to display various things */
25972   integer k;
25973   int l,m,n;
25974   char *aline;
25975   size_t len;
25976   while (1) { 
25977     wake_up_terminal;
25978     mp_print_nl(mp, "debug # (-1 to exit):"); update_terminal;
25979 @.debug \#@>
25980     m = 0;
25981     aline = (mp->read_ascii_file)(mp->term_in, &len);
25982     if (len) { sscanf(aline,"%i",&m); xfree(aline); }
25983     if ( m<=0 )
25984       return;
25985     n = 0 ;
25986     aline = (mp->read_ascii_file)(mp->term_in, &len);
25987     if (len) { sscanf(aline,"%i",&n); xfree(aline); }
25988     switch (m) {
25989     @<Numbered cases for |debug_help|@>;
25990     default: mp_print(mp, "?"); break;
25991     }
25992   }
25993 }
25994
25995 @ @<Numbered cases...@>=
25996 case 1: mp_print_word(mp, mp->mem[n]); /* display |mem[n]| in all forms */
25997   break;
25998 case 2: mp_print_int(mp, info(n));
25999   break;
26000 case 3: mp_print_int(mp, link(n));
26001   break;
26002 case 4: mp_print_int(mp, eq_type(n)); mp_print_char(mp, ':'); mp_print_int(mp, equiv(n));
26003   break;
26004 case 5: mp_print_variable_name(mp, n);
26005   break;
26006 case 6: mp_print_int(mp, mp->internal[n]);
26007   break;
26008 case 7: mp_do_show_dependencies(mp);
26009   break;
26010 case 9: mp_show_token_list(mp, n,null,100000,0);
26011   break;
26012 case 10: mp_print_str(mp, n);
26013   break;
26014 case 11: mp_check_mem(mp, n>0); /* check wellformedness; print new busy locations if |n>0| */
26015   break;
26016 case 12: mp_search_mem(mp, n); /* look for pointers to |n| */
26017   break;
26018 case 13: 
26019   l = 0;  
26020   aline = (mp->read_ascii_file)(mp->term_in, &len);
26021   if (len) { sscanf(aline,"%i",&l); xfree(aline); }
26022   mp_print_cmd_mod(mp, n,l); 
26023   break;
26024 case 14: for (k=0;k<=n;k++) mp_print_str(mp, mp->buffer[k]);
26025   break;
26026 case 15: mp->panicking=! mp->panicking;
26027   break;
26028
26029
26030 @ Saving the filename template
26031
26032 @<Save the filename template@>=
26033
26034   if ( mp->filename_template!=0 ) delete_str_ref(mp->filename_template);
26035   if ( length(mp->cur_exp)==0 ) mp->filename_template=0;
26036   else { 
26037     mp->filename_template=mp->cur_exp; add_str_ref(mp->filename_template);
26038   }
26039 }
26040
26041 @* \[48] System-dependent changes.
26042 This section should be replaced, if necessary, by any special
26043 modification of the program
26044 that are necessary to make \MP\ work at a particular installation.
26045 It is usually best to design your change file so that all changes to
26046 previous sections preserve the section numbering; then everybody's version
26047 will be consistent with the published program. More extensive changes,
26048 which introduce new sections, can be inserted here; then only the index
26049 itself will get a new section number.
26050 @^system dependencies@>
26051
26052 @* \[49] Index.
26053 Here is where you can find all uses of each identifier in the program,
26054 with underlined entries pointing to where the identifier was defined.
26055 If the identifier is only one letter long, however, you get to see only
26056 the underlined entries. {\sl All references are to section numbers instead of
26057 page numbers.}
26058
26059 This index also lists error messages and other aspects of the program
26060 that you might want to look up some day. For example, the entry
26061 for ``system dependencies'' lists all sections that should receive
26062 special attention from people who are installing \MP\ in a new
26063 operating environment. A list of various things that can't happen appears
26064 under ``this can't happen''.
26065 Approximately 25 sections are listed under ``inner loop''; these account
26066 for more than 60\pct! of \MP's running time, exclusive of input and output.